repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
nielsrowinbik/seaman
|
src/components/Select/Menu.tsx
|
522
|
import React from 'react';
import styled from '../../util/styled-components';
const UnstyledMenu = ({ children, className, innerProps }) => <div {...{ children, className, ...innerProps }} />;
export const Menu = styled(UnstyledMenu)`
background-color: #ffffff;
border-radius: 3px;
box-shadow: 0 4px 8px -2px rgba(9, 30, 66, 0.25), 0 0 1px rgba(9, 30, 66, 0.31);
left: 0;
margin: 6px 0 0 0;
min-width: 100%;
overflow: auto;
padding: 4px 0;
position: absolute;
top: 100%;
z-index: 10;
`;
export default Menu;
|
gpl-3.0
|
arkatebi/CAFA-Toolset
|
misc/Get_taxons.py
|
3524
|
#!/usr/bin/env python
'''
How to run this program:
python Get_taxons.py cafa3targetlist.csv uniprot_sprot.dat.2016_06 > t.txt
The program takes takes two input files:
cafa3targetlist.csv: a file with protein names - one protein per line.
uniprot_sprot.dat.2016_06: a UniProtKB/SwissProt file
The program retreives the taxon id for each protein in the first
input file from the second file. Then groups the proteins
according to the taxon ids.
It outputs these proteins by taxon ids as groups.
It also has a method (print_protein_dict) which can be invoked to print each protein and
its taxon id as retrieved.
'''
import os
import sys
import subprocess
from collections import defaultdict
from Bio import SwissProt as sp
#import Config
config_filename = '.cafarc'
class Get_taxons:
def __init__(self, tList_fname, sprot_fname):
# Collect config file entries:
# self.ConfigParam = Config.read_config(config_filename)
# self.work_dir = (self.ConfigParam['workdir']).rstrip('/')
self.work_dir = './workspace'
self.tList_fname = self.work_dir + '/' + tList_fname
self.sprot_fname = self.work_dir + '/' + sprot_fname
def obtain_taxons(self, protein_dict, fh_sprot):
found = False
for rec in sp.parse(fh_sprot):
for ac in range(len(rec.accessions)):
if rec.accessions[ac] in protein_dict.keys():
# assign rec.taxonomy_id list to the protein
protein_dict[rec.accessions[ac]] = rec.taxonomy_id
found = True
break
#if found:
# break
return protein_dict
def group_proteins_by_taxons(self, protein_dict):
taxons = set()
for v in list(protein_dict.values()):
taxons = taxons.union(set(v))
#print(taxons)
taxon_dict = defaultdict(list)
for t in list(taxons):
for p in protein_dict.keys():
if t in protein_dict[p]:
taxon_dict[t].append(p)
return taxon_dict
def print_protein_dict(self, protein_dict):
for p,t in protein_dict.items():
print(p + '\t' + ','.join(t))
return None
def print_taxon_dict(self, taxon_dict):
for t,p in taxon_dict.items():
print(t+'\t',', '.join(p))
return None
def process_data(self):
"""
This method invokes other methods to process data
and obtain desired results.
"""
#print('Checking target proteins in the UniProt-GOA list ...')
fh_tlist = open(self.tList_fname, 'r')
# Create a dictionary with the target proteins:
protein_dict = defaultdict(list)
for line in fh_tlist:
protName = line.strip()
protein_dict[protName] = []
fh_tlist.close()
self.obtain_taxons(protein_dict, open(self.sprot_fname, 'r'))
taxon_dict = self.group_proteins_by_taxons(protein_dict)
#self.print_protein_dict(protein_dict)
self.print_taxon_dict(taxon_dict)
return None
if __name__ == '__main__':
if len(sys.argv) == 1:
print (sys.argv[0] + ':')
print(__doc__)
else:
# sys.argv[1]: file containing proteins, one protein in each row
# sys.argv[2]: SwissProt file to retrieve the taxon ids from
gt = Get_taxons(sys.argv[1], sys.argv[2])
gt.process_data()
sys.exit(0)
|
gpl-3.0
|
khaslu/design-pattern
|
design-pattern-decorator/src/main/java/br/com/khaslu/dp/tarefa3/ContasComSaldoMaiorQueQuinhentosMilReais.java
|
636
|
package br.com.khaslu.dp.tarefa3;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ContasComSaldoMaiorQueQuinhentosMilReais extends Analise {
public ContasComSaldoMaiorQueQuinhentosMilReais() {
}
public ContasComSaldoMaiorQueQuinhentosMilReais(final Analise proximaAnalise) {
super(proximaAnalise);
}
@Override
public Set<Conta> processar(final List<Conta> contas) {
final Set<Conta> contasSuspeitas = contas.stream().filter(conta -> conta.getSaldo() > 500000)
.collect(Collectors.toSet());
contasSuspeitas.addAll(this.nextStep(contas));
return contasSuspeitas;
}
}
|
gpl-3.0
|
Stormister/Rediscovered-Mod-1.6.4
|
source/main/RediscoveredMod/TileEntityLectern.java
|
1280
|
// Copyright 2012-2014 Matthew Karcz
//
// This file is part of The Rediscovered Mod.
//
// The Rediscovered Mod 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.
//
// The Rediscovered Mod 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 The Rediscovered Mod. If not, see <http://www.gnu.org/licenses/>.
package RediscoveredMod;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
public class TileEntityLectern extends TileEntity
{
}
|
gpl-3.0
|
danij/IRCService.NET
|
IRCService.NET.Protocols.P10/P10/Parsers/G_Parser.cs
|
2048
|
//IRCService.NET. Generic IRC service library for .NET
//Copyright (C) 2010-2012 Dani J
//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/>.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRCServiceNET.Protocols.P10.Parsers
{
/// <summary>
/// Parses and replies to a ping request
/// </summary>
public class G_Parser : CommandParser
{
public override string CommandHeader
{
get { return "G"; }
}
public override void Parse(string[] spaceSplit, string[] colonSplit,
string fullRow)
{
if (spaceSplit.Count() < 3)
{
return;
}
if ((spaceSplit[2][0] == '!') && (spaceSplit.Count() > 4))
{
var command = Service.CommandFactory.CreatePingReplyCommand();
command.From = Service.MainServer;
command.To = spaceSplit[0];
command.Message = spaceSplit[4];
Service.SendCommand(command);
}
else
{
if (colonSplit.Count() > 1)
{
var command = Service.CommandFactory.CreatePingReplyCommand();
command.From = Service.MainServer;
command.Message = colonSplit[1];
Service.SendCommand(command);
}
}
}
}
}
|
gpl-3.0
|
JensGuckenbiehl/HAOM8-Software
|
src/modules/buttonmodule.cpp
|
3591
|
#include "buttonmodule.h"
#include "modulefactory.h"
REGISTER_MODULE("button", ButtonModule)
#include "config/all.h"
ButtonModule::ButtonModule() : _gpio(-1),
_clickCommand(""), _clickTopic(""), _clickPayload(""),
_doubleClickCommand(""), _doubleClickTopic(""), _doubleClickPayload(""),
_longClickCommand(""), _longClickTopic(""), _longClickPayload("") {
}
ButtonModule::~ButtonModule() {
}
void ButtonModule::start() {
if(_gpio != -1) {
pinMode(_gpio, INPUT_PULLUP);
}
}
void ButtonModule::stop() {
_gpio = -1;
}
String ButtonModule::serialize() {
DynamicJsonBuffer jsonBuffer;
JsonObject& configJson = jsonBuffer.createObject();
configJson["gpio"] = _gpio;
configJson["clickCommand"] = _clickCommand;
configJson["clickTopic"] = _clickTopic;
configJson["clickPayload"] = _clickPayload;
configJson["doubleClickCommand"] = _doubleClickCommand;
configJson["doubleClickTopic"] = _doubleClickTopic;
configJson["doubleClickPayload"] = _doubleClickPayload;
configJson["longClickCommand"] = _longClickCommand;
configJson["longClickTopic"] = _longClickTopic;
configJson["longClickPayload"] = _longClickPayload;
String output;
configJson.printTo(output);
return output;
}
void ButtonModule::deserialize(const String& json) {
DynamicJsonBuffer jsonBuffer;
JsonObject& configJson = jsonBuffer.parseObject(json);
if(configJson.containsKey("gpio")) {
_gpio = configJson["gpio"];
}
if(configJson.containsKey("clickCommand")) {
_clickCommand = configJson["clickCommand"].as<String>();
}
if(configJson.containsKey("clickTopic")) {
_clickTopic = configJson["clickTopic"].as<String>();
}
if(configJson.containsKey("clickPayload")) {
_clickPayload = configJson["clickPayload"].as<String>();
}
if(configJson.containsKey("doubleClickCommand")) {
_doubleClickCommand = configJson["doubleClickCommand"].as<String>();
}
if(configJson.containsKey("doubleClickTopic")) {
_doubleClickTopic = configJson["doubleClickTopic"].as<String>();
}
if(configJson.containsKey("doubleClickPayload")) {
_doubleClickPayload = configJson["doubleClickPayload"].as<String>();
}
if(configJson.containsKey("longClickCommand")) {
_longClickCommand = configJson["longClickCommand"].as<String>();
}
if(configJson.containsKey("longClickTopic")) {
_longClickTopic = configJson["longClickTopic"].as<String>();
}
if(configJson.containsKey("longClickPayload")) {
_longClickPayload = configJson["longClickPayload"].as<String>();
}
}
void ButtonModule::loop() {
if(_gpio == -1) {
return;
}
_multiButton.update(digitalRead(_gpio) == 0);
String command;
String topic;
String payload;
if(_multiButton.isSingleClick()) {
command = _clickCommand;
topic = _clickTopic;
payload = _clickPayload;
} else if(_multiButton.isDoubleClick()) {
command = _doubleClickCommand;
topic = _doubleClickTopic;
payload = _doubleClickPayload;
} else if(_multiButton.isLongClick()) {
command = _longClickCommand;
topic = _longClickTopic;
payload = _longClickPayload;
}
if(command == "mqtt") {
if(topic.length() > 0) {
mqttSendRaw(topic.c_str(), payload.c_str(), false);
}
} else if(command.length() > 0) {
command = command + "\n";
settingsInject(const_cast< char* >(command.c_str()), command.length());
}
}
|
gpl-3.0
|
AhmedMater/AM-Tutoiral
|
Development/AM_Files/app/api/repository/UserRepository.js
|
12110
|
/**
* Created by Ahmed Mater on 10/6/2016.
*/
var DB = rootRequire('AM-Database');
var async = require('async');
var SystemParam = rootRequire('SystemParameters');
var ErrMsg = rootRequire('ErrorMessages');
var Logger = rootRequire('Logger');
var Generic = rootRequire('GenericRepository');
var Models = rootRequire('Models');
var USER = "User";
var USERS = "Users";
var DB_ERROR = SystemParam.DATABASE_ERROR;
var REPOSITORY = USER + SystemParam.REPOSITORY;
var exports = module.exports = {};
/**
* It's a Repository function responsible for inserting new User record in the Database
* @param userData User Data extracted from the Sign Up form
* @param RepositoryCallback
* @return int UserID of the record in Database
* @throws Error - if there is error in the Query
* @throws Error
*/
exports.insertUser = function(userData, RepositoryCallback) {
var fnName = "insertUser";
var query = 'INSERT INTO users SET ?';
var recordData = {
user_name: userData.userName,
password: userData.password,
email: userData.email,
user_role_id: userData.userRoleID,
first_name: userData.firstName,
last_name: userData.lastName,
gender: userData.gender,
mail_subscribe: userData.mailSubscribe,
university: userData.university,
college: userData.college,
job: userData.job,
country: userData.country,
date_of_birth: Generic.createSQLDate(userData.dateOfBirth)
};
async.waterfall([
function(GenericCallback){ Generic.insertRecord(query, recordData, REPOSITORY, fnName, USER, GenericCallback); }],
function(err, userID) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, userID);
}
);
};
/**
* It's a Repository function responsible for retrieving all the Data of the User from Database by its User ID
* @param userName
* @param password
* @param RepositoryCallback
* @return User Object - has the full data of the user from the Database
*/
exports.selectUserByLoginData = function(userName, password, RepositoryCallback) {
var fnName = "selectUserByLoginData";
var query =
"SELECT " +
"user.id userID, user_name, first_name, last_name, email, profile_pic, date_of_registration, gender, " +
"mail_subscribe, university, college, job, country, date_of_birth, mobile_number, " +
"role.id AS roleID, role.name AS roleName, role.value AS roleValue " +
"FROM " +
"users user LEFT JOIN lookup_user_role role ON user.user_role_id = role.id " +
"WHERE " +
"user_name = " + DB.escape(userName) + " AND " +
"password = " + DB.escape(password) + ";";
async.waterfall([
function(GenericCallback){ Generic.selectRecord(query, REPOSITORY, fnName, USER, GenericCallback); },
function(data, ModelCallback){ Models.setUser(data, ModelCallback); }
], function(err, User) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, User);
}
);
};
/**
* It's a Repository function responsible for retrieving all the Data of the User from the Database by its User ID
* @param userID
* @param RepositoryCallback
* @return User Object has the full data of the user from the Database
*/
exports.selectUserByID = function(userID, RepositoryCallback) {
var fnName = "selectUserByID";
var query =
"SELECT " +
"user.id userID, user_name, first_name, last_name, email, profile_pic, date_of_registration, gender, " +
"mail_subscribe, university, college, job, country, date_of_birth, mobile_number, " +
"role.id AS roleID, role.name AS roleName, role.value AS roleValue " +
"FROM " +
"users user LEFT JOIN lookup_user_role role ON user.user_role_id = role.id " +
"WHERE " +
"user.id = " + DB.escape(userID) + ";";
async.waterfall([
function(GenericCallback){ Generic.selectRecord(query, REPOSITORY, fnName, USER, GenericCallback); },
function(data, ModelCallback){ Models.setUser(data, ModelCallback); }
], function(err, User) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, User);
}
);
};
/**
* It's a Repository function responsible for retrieving all the User Data according to filtering criteria from the Database
* @param RepositoryCallback
* @return User[] Array of User Objects
*/
exports.selectAllUsers = function(name, dateOfRegFrom, dateOfRegTo, roleID, gender, datOfBirthFrom, datOfBirthTo, isActive, RepositoryCallback){
var fnName = "selectAllUsers";
var query =
"SELECT " +
"user.id userID, CONCAT(first_name, ' ', last_name) as fullName, date_of_registration, gender, " +
"university, college, job, country, date_of_birth, role.name AS roleName " +
"FROM " +
"users user LEFT JOIN lookup_user_role role ON user.user_role_id = role.id ";
var conditions = [];
conditions.push(Generic.setCondition("CONCAT(first_name, ' ', last_name)", name, "LIKE"));
conditions.push(Generic.setCondition("user.user_role_id", roleID));
conditions.push(Generic.setCondition("user.gender", gender));
conditions.push(Generic.setCondition("user.active", isActive));
conditions.push(Generic.setCondition("date_of_registration", null, null, "date", dateOfRegFrom, dateOfRegTo));
conditions.push(Generic.setCondition("date_of_birth", null, null, "date", datOfBirthFrom, datOfBirthTo));
async.waterfall([
function(DBUtilityCallback){ Generic.constructWhereStatement(conditions, DBUtilityCallback);},
function(whereStatement, GenericCallback){ Generic.selectAllRecords(query + ((whereStatement) ? whereStatement : ""), REPOSITORY, fnName, USER, GenericCallback); },
function(data, ModelCallback){ Models.setAllUsers(data, ModelCallback); }
], function(err, Users) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, Users);
}
);
};
/**
* It's a Repository function responsible for deleting User record from the Database
* @param userID
* @param RepositoryCallback
* @return Boolean - true if Deleting Successfully Done <br/>
* false if Deleting failed
*/
exports.deleteUserByID = function(userID, RepositoryCallback){
var fnName = "deleteUserByID";
var query = "DELETE FROM users WHERE id = " + DB.escape(userID);
async.waterfall([
function(GenericCallback){ Generic.deleteRecords(query, false, REPOSITORY, fnName, USER, GenericCallback); }],
function(err, done) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, done);
}
);
};
/**
* It's a Repository function responsible for updating the User Data in the Database
* @param userID
* @param newUserDate
* @param RepositoryCallback
* return Boolean true if Update succeeded <br/>
* false if Update failed
*/
exports.updateUserByID = function(userID, newUserData, RepositoryCallback){
var fnName = "updateUserByID";
var attributes = {};
if(newUserData.email) attributes['email'] = newUserData.email;
if(newUserData.userRoleID) attributes['user_role_id'] = newUserData.userRoleID;
if(newUserData.firstName) attributes['first_name'] = newUserData.firstName;
if(newUserData.lastName) attributes['last_name'] = newUserData.lastName;
if(newUserData.gender) attributes['gender'] = newUserData.gender;
if(newUserData.mailSubscribe) attributes['mail_subscribe'] = newUserData.mailSubscribe;
if(newUserData.university) attributes['university'] = newUserData.university;
if(newUserData.college) attributes['college'] = newUserData.college;
if(newUserData.job) attributes['job'] = newUserData.job;
if(newUserData.country) attributes['country'] = newUserData.country;
if(newUserData.dateOfBirth) attributes['date_of_birth'] = newUserData.dateOfBirth.year + '-' + newUserData.dateOfBirth.month + '-' + newUserData.dateOfBirth.day;
if(newUserData.profilePic) attributes['profile_pic'] = newUserData.profilePic;
if(newUserData.mobileNumber) attributes['mobile_number'] = newUserData.mobileNumber;
attributes['last_updated'] = new Date();
var query = "UPDATE users SET ? WHERE id = " + DB.escape(userID);
async.waterfall([ function(GenericCallback){Generic.updateRecord(query, attributes, REPOSITORY, fnName, USER, GenericCallback); }],
function(err, done) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, done);
}
);
};
/**
* It's a Repository function responsible for testing if this User already found before in the Database
* @param userName
* @param email
* @param RepositoryCallback
* @return Boolean true - if found <br/>
* false - if not found
*/
exports.isUserFound = function(userName, email, RepositoryCallback){
var fnName = "isUserFound";
var query =
"SELECT 1 FROM users " +
"WHERE " +
"user_name = " + DB.escape(userName) + " OR " +
"email = " + DB.escape(email) + ";";
async.waterfall([function(GenericCallback){Generic.isRecordFound(query, REPOSITORY, fnName, USER, GenericCallback);}],
function(err, isFound) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, isFound);
}
);
};
/**
* It's a Repository function responsible for testing if this User is active before in the Database
* @param userID
* @param RepositoryCallback
* @return Boolean true - if active <br/>
* false - if not active
*/
exports.isUserActive = function(userID, RepositoryCallback){
var fnName = "isUserActive";
var query = "SELECT active FROM users WHERE id = " + DB.escape(userID);
async.waterfall([function(GenericCallback){Generic.selectValue(query, "active", REPOSITORY, fnName, USER, GenericCallback);}],
function(err, isActive) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, (isActive == 1));
}
);
};
/**
* It's a Repository function responsible for changing the User Password in the Database
* @param userID
* @param userName
* @param oldPassword
* @param newPassword
* @param RepositoryCallback
* @return Boolean - true if Update succeeded <br/>
* false if Update failed
*/
exports.changePassword = function(userID, userName, oldPassword, newPassword, RepositoryCallback) {
var fnName = "changePassword";
var newData = { password: newPassword };
var query =
"UPDATE users SET ? WHERE " +
"id = " + DB.escape(userID) + " AND " +
"user_name = " + DB.escape(userName) + " AND " +
"password = " + DB.escape(oldPassword);
async.waterfall([function(GenericCallback){Generic.updateRecord(query, newData, REPOSITORY, fnName, USER, GenericCallback);}],
function(err, done) {
if(err != null)
return RepositoryCallback(ErrMsg.createError(DB_ERROR, err.message), null);
else
return RepositoryCallback(null, done);
}
);
};
|
gpl-3.0
|
09zwcbupt/undergrad_thesis
|
ext/poxdesk/qx/framework/source/class/qx/test/mobile/form/NumberField.js
|
2725
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2012 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Christopher Zuendorf (czuendorf)
************************************************************************ */
qx.Class.define("qx.test.mobile.form.NumberField",
{
extend : qx.test.mobile.MobileTestCase,
members :
{
testValue : function()
{
var numberField = new qx.ui.mobile.form.NumberField();
this.getRoot().add(numberField);
this.assertEquals('',numberField.getValue());
this.assertEquals(null, qx.bom.element.Attribute.get(numberField.getContainerElement(),'value'));
this.assertEventFired(numberField, "changeValue", function() {
numberField.setValue(15);
});
this.assertEquals(15,numberField.getValue());
this.assertEquals(15,qx.bom.element.Attribute.get(numberField.getContainerElement(),'value'));
numberField.destroy();
},
testMinimum : function()
{
var numberField = new qx.ui.mobile.form.NumberField();
this.getRoot().add(numberField);
this.assertEquals('',numberField.getMinimum());
numberField.setMinimum(42);
this.assertEquals(42,numberField.getMinimum());
numberField.destroy();
},
testMaximum : function()
{
var numberField = new qx.ui.mobile.form.NumberField();
this.getRoot().add(numberField);
this.assertEquals('',numberField.getMaximum());
numberField.setMaximum(42);
this.assertEquals(42,numberField.getMaximum());
numberField.destroy();
},
testStep : function()
{
var numberField = new qx.ui.mobile.form.NumberField();
this.getRoot().add(numberField);
this.assertEquals('',numberField.getStep());
numberField.setStep(42);
this.assertEquals(42,numberField.getStep());
numberField.destroy();
},
testEnabled : function()
{
var numberField = new qx.ui.mobile.form.NumberField();
this.getRoot().add(numberField);
this.assertEquals(true,numberField.getEnabled());
this.assertFalse(qx.bom.element.Class.has(numberField.getContainerElement(),'disabled'));
numberField.setEnabled(false);
this.assertEquals(false,numberField.getEnabled());
this.assertEquals(true,qx.bom.element.Class.has(numberField.getContainerElement(),'disabled'));
numberField.destroy();
}
}
});
|
gpl-3.0
|
FzPying/wordthink
|
assets/js/weather.js
|
12114
|
(function($) {
$.fn.leoweather = function(opts) {
var defaults = {
city: '',
format: '\u5c0a\u656c\u7684\u4f1a\u5458\uff0c\u007b\u65f6\u6bb5\u007d\u597d\uff01\u0020\u73b0\u5728\u662f\uff1a\u007b\u5e74\u007d\u002f\u007b\u6708\u007d\u002f\u007b\u65e5\u007d\u0020\u007b\u65f6\u007d\u003a\u007b\u5206\u007d\u003a\u007b\u79d2\u007d\u0020\u661f\u671f\u007b\u5468\u007d\u0020\u60a8\u6240\u5728\u7684\u57ce\u5e02\uff1a\u007b\u57ce\u5e02\u007d\u0020\u4eca\u5929\u007b\u663c\u591c\u007d\u7684\u5929\u6c14\u662f\uff1a\u007b\u5929\u6c14\u007d\u0020\u6c14\u6e29\uff1a\u007b\u6c14\u6e29\u007d\u0020\u98ce\u5411\uff1a\u007b\u98ce\u5411\u007d\u0020\u98ce\u7ea7\uff1a\u007b\u98ce\u7ea7\u007d\u0020\u56fe\u6807\uff1a\u007b\u56fe\u6807\u007d'
};
var options = $.extend(defaults, opts);
return this.each(function() {
var obj = $(this),
weather = new Array(),
format = UC8F6C6362(options.format),
url = '\u0068\u0074\u0074\u0070\u003a\u002f\u002f\u0070\u0068\u0070\u002e\u0077\u0065\u0061\u0074\u0068\u0065\u0072\u002e\u0073\u0069\u006e\u0061\u002e\u0063\u006f\u006d\u002e\u0063\u006e\u002f\u0069\u0066\u0072\u0061\u006d\u0065\u002f\u0069\u006e\u0064\u0065\u0078\u002f\u0077\u005f\u0063\u006c\u002e\u0070\u0068\u0070\u003f\u0063\u006f\u0064\u0065\u003d\u006a\u0073\u0026\u0064\u0061\u0079\u003d\u0030\u0026\u0063\u0069\u0074\u0079\u003d';
var model = format.match(/\{.*?\}/g),
action = new Array();
for (var i = 0; model.length > i; i++) {
action[i] = 'UC' + escape(model[i]).replace(/%u/g, '').replace(/%7B/g, '').replace(/%7D/g, '')
};
var valid = action.toString();
if (valid.indexOf('UC57CE5E02') > 0 || valid.indexOf('UC59296C14') > 0 || valid.indexOf('UC6C146E29') > 0 || valid.indexOf('UC98CE5411') > 0 || valid.indexOf('UC98CE7EA7') > 0 || valid.indexOf('UC57CE5E02') > 0 || valid.indexOf('UC56FE6807') > 0) {
$.ajax({
url: UC7F515740(url, options.city),
dataType: "script",
success: function() {
for (s in SWther.w) {
var data = SWther.w[s][0];
weather['name'] = s;
weather['d1'] = data['d1'];
weather['p1'] = data['p1'];
weather['s1'] = data['s1'];
weather['t1'] = data['t1'];
weather['f1'] = data['f1'];
weather['d2'] = data['d2'];
weather['p2'] = data['p2'];
weather['s2'] = data['s2'];
weather['t2'] = data['t2'];
weather['f2'] = data['f2']
};
getcontent(obj, weather)
}
})
} else {
getcontent(obj, '')
};
function getcontent(o, w) {
var d = new Date(),
timer = 0;
for (var i = 0; action.length > i; i++) {
str = format.replace(/\{(.*?)\}/g,
function(a, b) {
var fun = 'UC' + escape(b).replace(/%u/g, '').replace(/%7B/g, '').replace(/%7D/g, '');
return eval(fun + '(d,w)')
})
};
if (action.toString().indexOf('UC65F6') > 0) {
timer = 1000 * 60 * 60
};
if (action.toString().indexOf('UC5206') > 0) {
timer = 1000 * 60
};
if (action.toString().indexOf('UC79D2') > 0) {
timer = 1000
};
o.html(str);
if (timer > 0) {
var ClockTimer = setInterval(UC66F465B0SJ, timer)
}
}
function UC66F465B0SJ() {
var today = new Date();
YY = today.getYear();
if (YY < 1900) YY = YY + 1900;
var MM = today.getMonth() + 1;
if (MM < 10) MM = '0' + MM;
var DD = today.getDate();
if (DD < 10) DD = '0' + DD;
var hh = today.getHours();
if (hh < 10) hh = '0' + hh;
var mm = today.getMinutes();
if (mm < 10) mm = '0' + mm;
var ss = today.getSeconds();
if (ss < 10) ss = '0' + ss;
var ww = today.getDay();
if (ww == 0) ww = UC8F6C6362('\u65e5');
if (ww == 1) ww = UC8F6C6362('\u4e00');
if (ww == 2) ww = UC8F6C6362('\u4e8c');
if (ww == 3) ww = UC8F6C6362('\u4e09');
if (ww == 4) ww = UC8F6C6362('\u56db');
if (ww == 5) ww = UC8F6C6362('\u4e94');
if (ww == 6) ww = UC8F6C6362('\u516d');
if (hh < 06) {
xx = UC8F6C6362('\u51cc\u6668')
} else if (hh < 09) {
xx = UC8F6C6362('\u65e9\u4e0a')
} else if (hh < 12) {
xx = UC8F6C6362('\u4e0a\u5348')
} else if (hh < 14) {
xx = UC8F6C6362('\u4e2d\u5348')
} else if (hh < 17) {
xx = UC8F6C6362('\u4e0b\u5348')
} else if (hh < 19) {
xx = UC8F6C6362('\u508d\u665a')
} else {
xx = UC8F6C6362('\u665a\u4e0a')
};
$('#weather_YY').html(YY);
$('#weather_MM').html(MM);
$('#weather_DD').html(DD);
$('#weather_hh').html(hh);
$('#weather_mm').html(mm);
$('#weather_ss').html(ss);
$('#weather_ww').html(ww);
$('#weather_xx').html(xx)
}
function UC5E74(today, weather) {
YY = today.getYear();
if (YY < 1900) YY = YY + 1900;
return '<span id="weather_YY">' + YY + '</span>'
}
function UC6708(today, weather) {
var MM = today.getMonth() + 1;
if (MM < 10) MM = '0' + MM;
return '<span id="weather_MM">' + MM + '</span>'
}
function UC65E5(today, weather) {
var DD = today.getDate();
if (DD < 10) DD = '0' + DD;
return '<span id="weather_DD">' + DD + '</span>'
}
function UC65F6(today, weather) {
var hh = today.getHours();
if (hh < 10) hh = '0' + hh;
return '<span id="weather_hh">' + hh + '</span>'
}
function UC5206(today, weather) {
var mm = today.getMinutes();
if (mm < 10) mm = '0' + mm;
return '<span id="weather_mm">' + mm + '</span>'
}
function UC79D2(today, weather) {
var ss = today.getSeconds();
if (ss < 10) ss = '0' + ss;
return '<span id="weather_ss">' + ss + '</span>'
}
function UC5468(today, weather) {
var ww = today.getDay();
if (ww == 0) ww = UC8F6C6362('\u65e5');
if (ww == 1) ww = UC8F6C6362('\u4e00');
if (ww == 2) ww = UC8F6C6362('\u4e8c');
if (ww == 3) ww = UC8F6C6362('\u4e09');
if (ww == 4) ww = UC8F6C6362('\u56db');
if (ww == 5) ww = UC8F6C6362('\u4e94');
if (ww == 6) ww = UC8F6C6362('\u516d');
return '<span id="weather_ww">' + ww + '</span>'
}
function UC65F66BB5(today, weather) {
var hh = today.getHours();
if (hh < 06) {
xx = UC8F6C6362('\u51cc\u6668')
} else if (hh < 09) {
xx = UC8F6C6362('\u65e9\u4e0a')
} else if (hh < 12) {
xx = UC8F6C6362('\u4e0a\u5348')
} else if (hh < 14) {
xx = UC8F6C6362('\u4e2d\u5348')
} else if (hh < 17) {
xx = UC8F6C6362('\u4e0b\u5348')
} else if (hh < 19) {
xx = UC8F6C6362('\u508d\u665a')
} else {
xx = UC8F6C6362('\u665a\u4e0a')
};
return '<span id="weather_xx">' + xx + '</span>'
}
function UC57CE5E02(today, weather) {
return weather['name']
}
function UC59296C14(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC591C95F459296C14(today, weather)
} else {
return UC767D592959296C14(today, weather)
}
}
function UC767D592959296C14(today, weather) {
return weather['s1']
}
function UC591C95F459296C14(today, weather) {
return weather['s2']
}
function UC6C146E29(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC591C95F46C146E29(today, weather)
} else {
return UC767D59296C146E29(today, weather)
}
}
function UC767D59296C146E29(today, weather) {
return weather['t1']
}
function UC591C95F46C146E29(today, weather) {
return weather['t2']
}
function UC98CE5411(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC591C95F498CE5411(today, weather)
} else {
return UC767D592998CE5411(today, weather)
}
}
function UC767D592998CE5411(today, weather) {
return weather['d1']
}
function UC591C95F498CE5411(today, weather) {
return weather['d2']
}
function UC98CE7EA7(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC591C95F498CE7EA7(today, weather)
} else {
return UC767D592998CE7EA7(today, weather)
}
}
function UC767D592998CE7EA7(today, weather) {
return weather['p1']
}
function UC591C95F498CE7EA7(today, weather) {
return weather['p2']
}
function UC56FE6807(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC591C95F456FE6807(today, weather)
} else {
return UC767D592956FE6807(today, weather)
}
}
function UC767D592956FE6807(today, weather) {
return weather['f1']
}
function UC591C95F456FE6807(today, weather) {
return weather['f2']
}
function UC663C591C(today, weather) {
if (today.getHours() > 18 && today.getHours() < 8) {
return UC8F6C6362('\u591c\u95f4')
} else {
return UC8F6C6362('\u767d\u5929')
}
}
function UC8F6C6362(string) {
return unescape(string.replace(/\u/g, "%u"))
}
function UC7F515740(url, city) {
return UC8F6C6362(url) + city + UC8F6C6362('\u0026\u0064\u0066\u0063\u003d\u0031\u0026\u0063\u0068\u0061\u0072\u0073\u0065\u0074\u003d\u0075\u0074\u0066\u002d\u0038').replace(/\%/g, '')
}
})
}
})(jQuery);
|
gpl-3.0
|
dzonekl/oss2nms
|
plugins/com.netxforge.oss2.config.model/src/com/netxforge/oss2/config/reporting/jasperReports/descriptors/ReportDescriptor.java
|
9496
|
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package com.netxforge.oss2.config.reporting.jasperReports.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import com.netxforge.oss2.config.reporting.jasperReports.Report;
/**
* Class ReportDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class ReportDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ReportDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/jasper-reports";
_xmlName = "report";
_elementDefinition = true;
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _id
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_id", "id", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Report target = (Report) object;
return target.getId();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Report target = (Report) object;
target.setId( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _id
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _template
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_template", "template", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Report target = (Report) object;
return target.getTemplate();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Report target = (Report) object;
target.setTemplate( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _template
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _engine
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_engine", "engine", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Report target = (Report) object;
return target.getEngine();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Report target = (Report) object;
target.setEngine( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _engine
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.addPattern("(jdbc|opennms|null)");
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return com.netxforge.oss2.config.reporting.jasperReports.Report.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
|
gpl-3.0
|
Laterus/Darkstar-Linux-Fork
|
src/map/fishingutils.cpp
|
19081
|
/*
===========================================================================
Copyright (c) 2010-2012 Darkstar Dev Teams
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/
This file is part of DarkStar-server source code.
===========================================================================
*/
#include "../common/showmsg.h"
#include <string.h>
#include "packets/caught_fish.h"
#include "packets/char_update.h"
#include "packets/char_sync.h"
#include "packets/fishing.h"
#include "packets/inventory_finish.h"
#include "packets/message_text.h"
#include "packets/release.h"
#include "packets/message_system.h"
#include "charutils.h"
#include "fishingutils.h"
#include "itemutils.h"
#include "map.h"
#include "vana_time.h"
#include "zoneutils.h"
namespace fishingutils
{
/************************************************************************
* *
* Массив смещений для сообщений рыбалки *
* *
************************************************************************/
uint16 MessageOffset[] =
{
0, // Residential_Area
7163, // Phanauet_Channel
7215, // Carpenters_Landing
7164, // Manaclipper
7209, // Bibiki_Bay
0, // Uleguerand_Range
0, // Bearclaw_Pinnacle
0, // Attohwa_Chasm
0, // Boneyard_Gully
0, // PsoXja
0, // The_Shrouded_Maw
7512, // Oldton_Movalpolos
0, // Newton_Movalpolos
0, // MineShaft_#2716
0, // Hall_of_Transference
0, // none
0, // Promyvion_Holla
0, // Spire_of_Holla
0, // Promyvion_Dem
0, // Spire_of_Dem
0, // Promyvion_Mea
0, // Spire_of_Mea
0, // Promyvion_Vahzl
0, // Spire_of_Vahzl
7495, // Lufaise_Meadows
7016, // Misareaux_Coast
10202, // Tavnazian_Safehold
7177, // Phomiuna_Aqueducts
0, // Sacrarium
0, // Riverne_Site_#B01
0, // Riverne_Site_#A01
0, // Monarch_Linn
0, // Sealions_Den
0, // AlTaieu
0, // Grand_Palace_of_HuXzoi
0, // The_Garden_of_RuHmet
0, // Empyreal_Paradox
0, // Temenos
0, // Apollyon
0, // Dynamis_Valkurm
0, // Dynamis_Buburimu
0, // Dynamis_Qufim
0, // Dynamis_Tavnazia
0, // Diorama_Abdhaljs_Ghelsba
0, // Abdhaljs_Isle_Purgonorgo
0, // Abyssea-Tahrongi
6994, // Open_sea_route_to_Al_Zahbi
6994, // Open_sea_route_to_Mhaura
6994, // Al_Zahbi
0, // none
831, // Aht_Urhgan_Whitegate
6994, // Wajaom_Woodlands
6994, // Bhaflau_Thickets
6994, // Nashmau
6994, // Arrapago_Reef
0, // Ilrusi_Atoll
0, // Periqia
6994, // Talacca_Cove
6994, // Silver_Sea_route_to_Nashmau
6994, // Silver_Sea_route_to_Al_Zahbi
0, // The_Ashu_Talif
6994, // Mount_Zhayolm
0, // Halvung
0, // Lebros_Cavern
0, // Navukgo_Execution_Chamber
6994, // Mamook
0, // Mamool_Ja_Training_Grounds
0, // Jade_Sepulcher
6994, // Aydeewa_Subterrane
0, // Leujaoam_Sanctum
0, // Chocobo_Circuit
0, // The_Colosseum
0, // Alzadaal_Undersea_Ruins
0, // Zhayolm_Remnants
0, // Arrapago_Remnants
0, // Bhaflau_Remnants
0, // Silver_Sea_Remnants
0, // Nyzul_Isle
0, // Hazhalm_Testing_Grounds
6994, // Caedarva_Mire
0, // Southern_San_d'Oria_[S]
7674, // East_Ronfaure_[S]
7306, // Jugner_Forest_[S]
6994, // Vunkerl_Inlet_[S]
7013, // Batallia_Downs_[S]
0, // La_Vaule_[S]
0, // Everbloom_Hollow
6994, // Bastok_Markets_[S]
7299, // North_Gustaberg_[S]
6994, // Grauberg_[S]
7090, // Pashhow_Marshlands_[S]
7013, // Rolanberry_Fields_[S]
0, // Beadeaux_[S]
0, // Ruhotz_Silvermines
6994, // Windurst_Waters_[S]
7020, // West_Sarutabaruta_[S]
0, // Fort_Karugo-Narugo_[S]
0, // Meriphataud_Mountains_[S]
0, // Sauromugue_Champaign_[S]
6994, // Castle_Oztroja_[S]
7156, // West_Ronfaure
7156, // East_Ronfaure
7156, // La_Theine_Plateau
7156, // Valkurm_Dunes
7628, // Jugner_Forest
7156, // Batallia_Downs
7156, // North_Gustaberg
7156, // South_Gustaberg
0, // Konschtat_Highlands
7156, // Pashhow_Marshlands
7156, // Rolanberry_Fields
7156, // Beaucedine_Glacier
0, // Xarcabard
7494, // Cape_Teriggan
7494, // Eastern_Altepa_Desert
6994, // West_Sarutabaruta
7153, // East_Sarutabaruta
7156, // Tahrongi_Canyon
7162, // Buburimu_Peninsula
7156, // Meriphataud_Mountains
7164, // Sauromugue_Champaign
7494, // The_Sanctuary_of_ZiTah
7153, // RoMaeve
7494, // Yuhtunga_Jungle
7494, // Yhoator_Jungle
7153, // Western_Altepa_Desert
7153, // Qufim_Island
0, // Behemoths_Dominion
0, // Valley_of_Sorrows
0, // Ghoyu's_Reverie
0, // RuAun_Gardens
0, // Mordion_Gaol
6994, // Abyssea-La_Theine
0, // unknown
0, // Dynamis_Beaucedine
0, // Dynamis_Xarcabard
0, // Beaucedine_Glacier_[S]
0, // Xarcabard_[S]
0, // Castle_Zvahl_Baileys_[S]
0, // Horlais_Peak
7512, // Ghelsba_Outpost
0, // Fort_Ghelsba
7153, // Yughott_Grotto
7153, // Palborough_Mines
0, // Waughroon_Shrine
7153, // Giddeus
0, // Balgas_Dais
0, // Beadeaux
0, // Qulun_Dome
7153, // Davoi
0, // Monastic_Cavern
7198, // Castle_Oztroja
0, // Altar_Room
6994, // The_Boyahda_Tree
6994, // Dragons_Aery
0, // Castle_Zvahl_Keep_[S]
0, // Throne_Room_[S]
0, // Middle_Delkfutts_Tower
0, // Upper_Delkfutts_Tower
7153, // Temple_of_Uggalepih
7181, // Den_of_Rancor
0, // Castle_Zvahl_Baileys
0, // Castle_Zvahl_Keep
0, // Sacrificial_Chamber
0, // Garlaige_Citadel_[S]
0, // Throne_Room
7153, // Ranguemont_Pass
7153, // Bostaunieux_Oubliette
0, // Chamber_of_Oracles
7199, // Toraimarai_Canal
0, // Full_Moon_Fountain
0, // Crawlers'_Nest_[S]
7153, // Zeruhn_Mines
6994, // Korroloka_Tunnel
7153, // Kuftal_Tunnel
0, // The_Eldieme_Necropolis_[S]
7153, // Sea_Serpent_Grotto
0, // VeLugannon_Palace
0, // The_Shrine_of_RuAvitau
0, // Stellar_Fulcrum
0, // LaLoff_Amphitheater
0, // The_Celestial_Nexus
0, // Walk_of_Echos
0, // The_Last_Stand
0, // Lower_Delkfutts_Tower
0, // Dynamis_San_dOria
0, // Dynamis_Bastok
0, // Dynamis_Windurst
0, // Dynamis_Jeuno
0, // unknown
0, // King_Ranperres_Tomb
7153, // Dangruf_Wadi
0, // Inner_Horutoto_Ruins
7153, // Ordelles_Caves
0, // Outer_Horutoto_Ruins
0, // The_Eldieme_Necropolis
7153, // Gusgen_Mines
0, // Crawlers_Nest
0, // Maze_of_Shakhrami
0, // unknown
0, // Garlaige_Citadel
0, // Cloister_of_Gales
0, // Cloister_of_Storms
0, // Cloister_of_Frost
7173, // FeiYin
0, // Ifrits_Cauldron
0, // QuBia_Arena
0, // Cloister_of_Flames
7153, // Quicksand_Caves
0, // Cloister_of_Tremors
0, // unknown
0, // Cloister_of_Tides
0, // Gustav_Tunnel
7153, // Labyrinth_of_Onzozo
0, // Al_Zahbi_Residential_Area
0, // Abyssea-Attohwa
6994, // Abyssea-Misareaux
6994, // Abyssea-Vunkerl
0, // Abyssea-Altepa
0, // unknown
7156, // Ship_bound_for_Selbina
7156, // Ship_bound_for_Mhaura
0, // test_zone
0, // San_dOria_Jeuno_Airship
0, // Bastok_Jeuno_Airship
0, // Windurst_Jeuno_Airship
0, // Kazham_Jeuno_Airship
7156, // Ship_bound_for_Selbina_Pirate
7156, // Ship_bound_for_Mhaura_Pirate
0, // unknown
0, // Southern_San_dOria
7199, // Northern_San_dOria
6744, // Port_San_dOria
0, // Chateau_dOraguille
10525, // Bastok_Mines
6923, // Bastok_Markets
6831, // Port_Bastok
0, // Bastok_Metalworks
6813, // Windurst_Waters
6824, // Windurst_Walls
11299, // Port_Windurst
6838, // Windurst_Woods
7292, // Heavens_Tower
0, // RuLude_Gardens
0, // Upper_Jeuno
6757, // Lower_Jeuno
6756, // Port_Jeuno
6584, // Rabao
6452, // Selbina
6613, // Mhaura
6584, // Kazham
0, // Hall_of_the_Gods
6584, // Norg
0, // Abyssea-Uleguerand
0, // Abyssea-Grauberg
0 // Abyssea-Empyreal_Paradox
};
/************************************************************************
* *
* Получение смещения для сообщений рыбалки *
* *
************************************************************************/
uint16 GetMessageOffset(uint8 ZoneID)
{
return MessageOffset[ZoneID];
}
/************************************************************************
* *
* Проверяем наличие удочки, наживки и возможности ловли *
* *
************************************************************************/
void StartFishing(CCharEntity* PChar)
{
if (PChar->animation != ANIMATION_NONE)
{
PChar->pushPacket(new CMessageSystemPacket(0,0,142));
PChar->pushPacket(new CReleasePacket(PChar,RELEASE_FISHING));
return;
}
uint16 MessageOffset = GetMessageOffset(PChar->getZone());
if (MessageOffset == 0)
{
ShowWarning(CL_YELLOW"Player wants to fish in %s\n"CL_RESET, PChar->loc.zone->GetName());
PChar->pushPacket(new CReleasePacket(PChar,RELEASE_FISHING));
return;
}
CItemWeapon* WeaponItem = NULL;
WeaponItem = (CItemWeapon*)PChar->getStorage(LOC_INVENTORY)->GetItem(PChar->equip[SLOT_RANGED]);
if ((WeaponItem == NULL) ||
!(WeaponItem->getType() & ITEM_WEAPON) ||
(WeaponItem->getSkillType() != SKILL_FSH))
{
// сообщение: "You can't fish without a rod in your hands"
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x01));
PChar->pushPacket(new CReleasePacket(PChar,RELEASE_FISHING));
return;
}
WeaponItem = (CItemWeapon*)PChar->getStorage(LOC_INVENTORY)->GetItem(PChar->equip[SLOT_AMMO]);
if ((WeaponItem == NULL) ||
!(WeaponItem->getType() & ITEM_WEAPON) ||
(WeaponItem->getSkillType() != SKILL_FSH))
{
// сообщение: "You can't fish without bait on the hook"
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x02));
PChar->pushPacket(new CReleasePacket(PChar,RELEASE_FISHING));
return;
}
PChar->status = STATUS_UPDATE;
PChar->animation = ANIMATION_FISHING_START;
PChar->pushPacket(new CCharUpdatePacket(PChar));
PChar->pushPacket(new CCharSyncPacket(PChar));
}
/************************************************************************
* *
* Персонаж ломает удочку *
* *
************************************************************************/
bool CheckFisherLuck(CCharEntity* PChar)
{
if (PChar->UContainer->GetType() != UCONTAINER_EMPTY)
{
ShowDebug(CL_CYAN"Player cannot fish! UContainer is not empty\n"CL_RESET);
return false;
}
CItem* PFish = NULL;
CItemWeapon* WeaponItem = NULL;
WeaponItem = (CItemWeapon*)PChar->getStorage(LOC_INVENTORY)->GetItem(PChar->equip[SLOT_RANGED]);
//DSP_DEBUG_BREAK_IF(WeaponItem == NULL);
//DSP_DEBUG_BREAK_IF(!(WeaponItem->getType() & ITEM_WEAPON));
//DSP_DEBUG_BREAK_IF(WeaponItem->getSkillType() != SKILL_FSH);
uint16 RodID = WeaponItem->getID();
WeaponItem = (CItemWeapon*)PChar->getStorage(LOC_INVENTORY)->GetItem(PChar->equip[SLOT_AMMO]);
//DSP_DEBUG_BREAK_IF(WeaponItem == NULL);
//DSP_DEBUG_BREAK_IF(!(WeaponItem->getType() & ITEM_WEAPON));
//DSP_DEBUG_BREAK_IF(WeaponItem->getSkillType() != SKILL_FSH);
uint16 LureID = WeaponItem->getID();
int32 FishingChance = rand()%100;
if (FishingChance <= 20)
{
const int8* fmtQuery = "SELECT fish.fishid, fish.max, fish.watertype, fish.size, fish.stamina, lure.luck, rod.flag \
FROM fishing_zone AS zone \
INNER JOIN fishing_rod AS rod USING (fishid) \
INNER JOIN fishing_lure AS lure USING (fishid) \
INNER JOIN fishing_fish AS fish USING (fishid) \
WHERE zone.zoneid = %u AND rod.rodid = %u AND lure.lureid = %u AND lure.luck = 0";
int32 ret = Sql_Query(SqlHandle, fmtQuery, PChar->getZone(), RodID, LureID);
if( ret != SQL_ERROR && Sql_NumRows(SqlHandle) != 0)
{
// результат ловли предмета
}
}
else
{
const int8* fmtQuery = "SELECT fish.fishid, lure.luck, rod.flag \
FROM fishing_zone AS zone \
INNER JOIN fishing_rod AS rod USING (fishid) \
INNER JOIN fishing_lure AS lure USING (fishid) \
INNER JOIN fishing_fish AS fish USING (fishid) \
WHERE zone.zoneid = %u AND rod.rodid = %u AND lure.lureid = %u AND lure.luck != 0 \
ORDER BY luck";
int32 ret = Sql_Query(SqlHandle, fmtQuery, PChar->getZone(), RodID, LureID);
if( ret != SQL_ERROR && Sql_NumRows(SqlHandle) != 0)
{
int32 FisherLuck = 0;
int32 FishingChance = rand()%1000;
while(Sql_NextRow(SqlHandle) == SQL_SUCCESS)
{
FisherLuck += Sql_GetIntData(SqlHandle,1);
if (FishingChance <= FisherLuck)
{
PFish = itemutils::GetItemPointer(Sql_GetIntData(SqlHandle,0));
PChar->UContainer->SetType(UCONTAINER_FISHING);
PChar->UContainer->SetItem(0, PFish);
break;
}
}
}
}
return (PFish != NULL);
}
/************************************************************************
* *
* Персонаж теряет наживку (теряет блесну лишь при условии RemoveFly) *
* *
************************************************************************/
bool LureLoss(CCharEntity* PChar, bool RemoveFly)
{
CItemWeapon* PLure = (CItemWeapon*)PChar->getStorage(LOC_INVENTORY)->GetItem(PChar->equip[SLOT_AMMO]);
//DSP_DEBUG_BREAK_IF(PLure == NULL);
//DSP_DEBUG_BREAK_IF(!(PLure->getType() & ITEM_WEAPON));
//DSP_DEBUG_BREAK_IF(PLure->getSkillType() != SKILL_FSH);
if (!RemoveFly &&
( PLure->getStackSize() == 1))
{
return false;
}
if (PLure->getQuantity() == 1)
{
charutils::UnequipItem(PChar, PChar->equip[SLOT_AMMO]);
}
charutils::UpdateItem(PChar, PLure->getLocationID(), PLure->getSlotID(), -1);
PChar->pushPacket(new CInventoryFinishPacket());
return true;
}
/************************************************************************
* *
* Персонаж ломает удочку *
* *
************************************************************************/
void RodBreaks(CCharEntity* PChar)
{
uint8 SlotID = PChar->equip[SLOT_RANGED];
CItem* PRod = PChar->getStorage(LOC_INVENTORY)->GetItem(SlotID);
//DSP_DEBUG_BREAK_IF(PRod == NULL);
uint16 BrokenRodID = 0;
switch (PRod->getID())
{
case 0x4276: BrokenRodID = 0x0728; break;
case 0x4277: BrokenRodID = 0x0729; break;
case 0x43E4: BrokenRodID = 0x01E3; break;
case 0x43E5: BrokenRodID = 0x01D9; break;
case 0x43E6: BrokenRodID = 0x01D8; break;
case 0x43E7: BrokenRodID = 0x01E2; break;
case 0x43E8: BrokenRodID = 0x01EA; break;
case 0x43E9: BrokenRodID = 0x01EB; break;
case 0x43EA: BrokenRodID = 0x01E9; break;
case 0x43EB: BrokenRodID = 0x01E4; break;
case 0x43EC: BrokenRodID = 0x01E8; break;
case 0x43ED: BrokenRodID = 0x01E7; break;
case 0x43EE: BrokenRodID = 0x01E6; break;
case 0x43EF: BrokenRodID = 0x01E5; break;
}
//DSP_DEBUG_BREAK_IF(BrokenRodID == 0);
charutils::EquipItem(PChar, 0, SLOT_RANGED);
charutils::UpdateItem(PChar, LOC_INVENTORY, SlotID, -1);
charutils::AddItem(PChar, LOC_INVENTORY, BrokenRodID, 1);
}
/************************************************************************
* *
* *
* *
************************************************************************/
void FishingAction(CCharEntity* PChar, FISHACTION action, uint16 stamina)
{
uint16 MessageOffset = GetMessageOffset(PChar->getZone());
switch (action)
{
case FISHACTION_CHECK:
{
if (CheckFisherLuck(PChar))
{
// сообщение: "Something caught the hook!"
PChar->animation = ANIMATION_FISHING_FISH;
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x08));
PChar->pushPacket(new CFishingPacket());
}
else
{
// сообщение: "You didn't catch anything."
PChar->animation = ANIMATION_FISHING_STOP;
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x04));
}
}
break;
case FISHACTION_FINISH:
{
if (stamina == 0)
{
// сообщение: "You caught fish!"
//DSP_DEBUG_BREAK_IF(PChar->UContainer->GetType() != UCONTAINER_FISHING);
//DSP_DEBUG_BREAK_IF(PChar->UContainer->GetItem(0) == NULL);
PChar->animation = ANIMATION_FISHING_CAUGHT;
CItem* PFish = PChar->UContainer->GetItem(0);
charutils::AddItem(PChar, LOC_INVENTORY, PFish->getID(), 1);
PChar->loc.zone->PushPacket(PChar, CHAR_INRANGE_SELF, new CCaughtFishPacket(PChar, PFish->getID(), MessageOffset + 0x27));
if (PFish->getType() & ITEM_USABLE)
{
LureLoss(PChar, false);
}
}
else if (stamina <= 0x64)
{
// сообщение: "Your line breaks!"
PChar->animation = ANIMATION_FISHING_LINE_BREAK;
LureLoss(PChar, true);
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x06));
}
else if (stamina <= 0x100)
{
// сообщение: "You give up!"
PChar->animation = ANIMATION_FISHING_STOP;
if (PChar->UContainer->GetType() == UCONTAINER_FISHING &&
LureLoss(PChar, false))
{
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x24));
} else {
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x25));
}
}
else
{
// сообщение: "You lost your catch!"
PChar->animation = ANIMATION_FISHING_STOP;
LureLoss(PChar, false);
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x09));
}
PChar->UContainer->Clean();
}
break;
case FISHACTION_WARNING:
{
// сообщение: "You don't know how much longer you can keep this one on the line..."
PChar->pushPacket(new CMessageTextPacket(PChar, MessageOffset + 0x28));
return;
}
break;
case FISHACTION_END:
{
// skillup
PChar->animation = ANIMATION_NONE;
}
break;
}
PChar->status = STATUS_UPDATE;
PChar->pushPacket(new CCharUpdatePacket(PChar));
PChar->pushPacket(new CCharSyncPacket(PChar));
}
} // namespace fishingutils
|
gpl-3.0
|
pumanzor/mediatek
|
linkitsmart7688/stepper/test_motor.py
|
357
|
import mraa
#pin = mraa.Pwm(18)
pin19 = mraa.Pwm(19)
pin1 = mraa.Gpio(1)
pin1.dir(mraa.DIR_OUT)
pin0 = mraa.Gpio(0)
pin0.dir(mraa.DIR_OUT)
number = 0
while True:
pin0.write(0)
pin1 = mraa.Gpio(1)
pin1.dir(mraa.DIR_OUT)
pin1.write(1)
pin19.period_us(400)
pin19.enable(True)
pin19.write(0.5)
number += 1
if number == 1000:
break
|
gpl-3.0
|
pstavirs/ostinato
|
common/mld.cpp
|
18120
|
/*
Copyright (C) 2010 Srivats P.
This file is part of "Ostinato"
This 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/>
*/
#include "mld.h"
#include "iputils.h"
#include <QHostAddress>
#include <QStringList>
MldProtocol::MldProtocol(StreamBase *stream, AbstractProtocol *parent)
: GmpProtocol(stream, parent)
{
_hasPayload = false;
data.set_type(kMldV1Query);
}
MldProtocol::~MldProtocol()
{
}
AbstractProtocol* MldProtocol::createInstance(StreamBase *stream,
AbstractProtocol *parent)
{
return new MldProtocol(stream, parent);
}
quint32 MldProtocol::protocolNumber() const
{
return OstProto::Protocol::kMldFieldNumber;
}
void MldProtocol::protoDataCopyInto(OstProto::Protocol &protocol) const
{
protocol.MutableExtension(OstProto::mld)->CopyFrom(data);
protocol.mutable_protocol_id()->set_id(protocolNumber());
}
void MldProtocol::protoDataCopyFrom(const OstProto::Protocol &protocol)
{
if (protocol.protocol_id().id() == protocolNumber() &&
protocol.HasExtension(OstProto::mld))
data.MergeFrom(protocol.GetExtension(OstProto::mld));
}
QString MldProtocol::name() const
{
return QString("Multicast Listener Discovery");
}
QString MldProtocol::shortName() const
{
return QString("MLD");
}
quint32 MldProtocol::protocolId(ProtocolIdType type) const
{
switch(type)
{
case ProtocolIdIp: return 0x3a;
default:break;
}
return AbstractProtocol::protocolId(type);
}
AbstractProtocol::FieldFlags MldProtocol::fieldFlags(int index) const
{
AbstractProtocol::FieldFlags flags;
flags = GmpProtocol::fieldFlags(index);
switch(index)
{
case kMldMrt:
case kMldRsvd:
if (msgType() != kMldV2Report)
flags |= FrameField;
break;
default:
break;
}
return flags;
}
QVariant MldProtocol::fieldData(int index, FieldAttrib attrib,
int streamIndex) const
{
switch (index)
{
case kRsvdMrtCode:
{
switch(attrib)
{
case FieldName: return QString("Code");
default: break;
}
break;
}
case kMldMrt:
{
quint16 mrt = 0, mrcode = 0;
if (msgType() == kMldV2Query)
{
mrt = data.max_response_time();
mrcode = mrc(mrt);
}
else if (msgType() == kMldV1Query)
mrcode = mrt = data.max_response_time() & 0xFFFF;
switch(attrib)
{
case FieldName:
if (isQuery())
return QString("Max Response Time");
return QString("Reserved");
case FieldValue:
return mrt;
case FieldTextValue:
return QString("%1 ms").arg(mrt);
case FieldFrameValue:
{
QByteArray fv;
fv.resize(2);
qToBigEndian(mrcode, (uchar*) fv.data());
return fv;
}
default:
break;
}
break;
}
case kMldRsvd:
{
quint16 rsvd = 0;
switch(attrib)
{
case FieldName:
return QString("Reserved");
case FieldValue:
return rsvd;
case FieldTextValue:
return QString("%1").arg(rsvd);
case FieldFrameValue:
{
QByteArray fv;
fv.resize(2);
qToBigEndian(rsvd, (uchar*) fv.data());
return fv;
}
default:
break;
}
break;
}
case kGroupAddress:
{
quint64 grpHi = 0, grpLo = 0;
ipUtils::ipAddress(
data.group_address().v6_hi(),
data.group_address().v6_lo(),
data.group_prefix(),
ipUtils::AddrMode(data.group_mode()),
data.group_count(),
streamIndex,
grpHi,
grpLo);
switch(attrib)
{
case FieldName:
return QString("Group Address");
case FieldValue:
return QVariant::fromValue(UInt128(grpHi, grpLo));
case FieldTextValue:
case FieldFrameValue:
{
QByteArray fv;
fv.resize(16);
qToBigEndian(grpHi, (uchar*) fv.data());
qToBigEndian(grpLo, (uchar*) (fv.data() + 8));
if (attrib == FieldFrameValue)
return fv;
else
return QHostAddress((quint8*)fv.constData()).toString();
}
default:
break;
}
break;
}
case kSources:
{
switch(attrib)
{
case FieldName:
return QString("Source List");
case FieldValue:
{
QStringList list;
QByteArray fv;
fv.resize(16);
for (int i = 0; i < data.sources_size(); i++)
{
qToBigEndian(quint64(data.sources(i).v6_hi()),
(uchar*)fv.data());
qToBigEndian(quint64(data.sources(i).v6_lo()),
(uchar*)fv.data()+8);
list << QHostAddress((quint8*)fv.constData()).toString();
}
return list;
}
case FieldFrameValue:
{
QByteArray fv;
fv.resize(16 * data.sources_size());
for (int i = 0; i < data.sources_size(); i++)
{
qToBigEndian(quint64(data.sources(i).v6_hi()),
(uchar*)(fv.data() + i*16));
qToBigEndian(quint64(data.sources(i).v6_lo()),
(uchar*)(fv.data() + i*16 + 8));
}
return fv;
}
case FieldTextValue:
{
QStringList list;
QByteArray fv;
fv.resize(16);
for (int i = 0; i < data.sources_size(); i++)
{
qToBigEndian(quint64(data.sources(i).v6_hi()),
(uchar*)fv.data());
qToBigEndian(quint64(data.sources(i).v6_lo()),
(uchar*)fv.data()+8);
list << QHostAddress((quint8*)fv.constData()).toString();
}
return list.join(", ");
}
default:
break;
}
break;
}
case kGroupRecords:
{
switch(attrib)
{
case FieldValue:
{
QVariantList grpRecords = GmpProtocol::fieldData(
index, attrib, streamIndex).toList();
QByteArray ip;
ip.resize(16);
for (int i = 0; i < data.group_records_size(); i++)
{
QVariantMap grpRec = grpRecords.at(i).toMap();
OstProto::Gmp::GroupRecord rec = data.group_records(i);
qToBigEndian(quint64(rec.group_address().v6_hi()),
(uchar*)(ip.data()));
qToBigEndian(quint64(rec.group_address().v6_lo()),
(uchar*)(ip.data() + 8));
grpRec["groupRecordAddress"] = QHostAddress(
(quint8*)ip.constData()).toString();
QStringList sl;
for (int j = 0; j < rec.sources_size(); j++)
{
qToBigEndian(quint64(rec.sources(j).v6_hi()),
(uchar*)(ip.data()));
qToBigEndian(quint64(rec.sources(j).v6_lo()),
(uchar*)(ip.data() + 8));
sl.append(QHostAddress(
(quint8*)ip.constData()).toString());
}
grpRec["groupRecordSourceList"] = sl;
grpRecords.replace(i, grpRec);
}
return grpRecords;
}
case FieldFrameValue:
{
QVariantList list = GmpProtocol::fieldData(
index, attrib, streamIndex).toList();
QByteArray fv;
QByteArray ip;
ip.resize(16);
for (int i = 0; i < data.group_records_size(); i++)
{
OstProto::Gmp::GroupRecord rec = data.group_records(i);
QByteArray rv = list.at(i).toByteArray();
rv.insert(4, QByteArray(16+16*rec.sources_size(), char(0)));
qToBigEndian(quint64(rec.group_address().v6_hi()),
(uchar*)(rv.data()+4));
qToBigEndian(quint64(rec.group_address().v6_lo()),
(uchar*)(rv.data()+4+8));
for (int j = 0; j < rec.sources_size(); j++)
{
qToBigEndian(quint64(rec.sources(j).v6_hi()),
(uchar*)(rv.data()+20+16*j));
qToBigEndian(quint64(rec.sources(j).v6_lo()),
(uchar*)(rv.data()+20+16*j+8));
}
fv.append(rv);
}
return fv;
}
case FieldTextValue:
{
QStringList list = GmpProtocol::fieldData(
index, attrib, streamIndex).toStringList();
QByteArray ip;
ip.resize(16);
for (int i = 0; i < data.group_records_size(); i++)
{
OstProto::Gmp::GroupRecord rec = data.group_records(i);
QString recStr = list.at(i);
QString str;
qToBigEndian(quint64(rec.group_address().v6_hi()),
(uchar*)(ip.data()));
qToBigEndian(quint64(rec.group_address().v6_lo()),
(uchar*)(ip.data() + 8));
str.append(QString("Group: %1").arg(
QHostAddress((quint8*)ip.constData()).toString()));
str.append("; Sources: ");
QStringList sl;
for (int j = 0; j < rec.sources_size(); j++)
{
qToBigEndian(quint64(rec.sources(j).v6_hi()),
(uchar*)(ip.data()));
qToBigEndian(quint64(rec.sources(j).v6_lo()),
(uchar*)(ip.data() + 8));
sl.append(QHostAddress(
(quint8*)ip.constData()).toString());
}
str.append(sl.join(", "));
recStr.replace("XXX", str);
list.replace(i, recStr);
}
return list.join("\n").insert(0, "\n");
}
default:
break;
}
break;
}
default:
break;
}
return GmpProtocol::fieldData(index, attrib, streamIndex);
}
bool MldProtocol::setFieldData(int index, const QVariant &value,
FieldAttrib attrib)
{
bool isOk = false;
if (attrib != FieldValue)
goto _exit;
switch (index)
{
case kGroupAddress:
{
if (value.typeName() == QString("UInt128")) {
UInt128 addr = value.value<UInt128>();
data.mutable_group_address()->set_v6_hi(addr.hi64());
data.mutable_group_address()->set_v6_lo(addr.lo64());
isOk = true;
break;
}
Q_IPV6ADDR addr = QHostAddress(value.toString()).toIPv6Address();
quint64 x;
x = (quint64(addr[0]) << 56)
| (quint64(addr[1]) << 48)
| (quint64(addr[2]) << 40)
| (quint64(addr[3]) << 32)
| (quint64(addr[4]) << 24)
| (quint64(addr[5]) << 16)
| (quint64(addr[6]) << 8)
| (quint64(addr[7]) << 0);
data.mutable_group_address()->set_v6_hi(x);
x = (quint64(addr[ 8]) << 56)
| (quint64(addr[ 9]) << 48)
| (quint64(addr[10]) << 40)
| (quint64(addr[11]) << 32)
| (quint64(addr[12]) << 24)
| (quint64(addr[13]) << 16)
| (quint64(addr[14]) << 8)
| (quint64(addr[15]) << 0);
data.mutable_group_address()->set_v6_lo(x);
isOk = true;
break;
}
case kSources:
{
QStringList list = value.toStringList();
data.clear_sources();
foreach(QString str, list)
{
OstProto::Gmp::IpAddress *src = data.add_sources();
Q_IPV6ADDR addr = QHostAddress(str).toIPv6Address();
quint64 x;
x = (quint64(addr[0]) << 56)
| (quint64(addr[1]) << 48)
| (quint64(addr[2]) << 40)
| (quint64(addr[3]) << 32)
| (quint64(addr[4]) << 24)
| (quint64(addr[5]) << 16)
| (quint64(addr[6]) << 8)
| (quint64(addr[7]) << 0);
src->set_v6_hi(x);
x = (quint64(addr[ 8]) << 56)
| (quint64(addr[ 9]) << 48)
| (quint64(addr[10]) << 40)
| (quint64(addr[11]) << 32)
| (quint64(addr[12]) << 24)
| (quint64(addr[13]) << 16)
| (quint64(addr[14]) << 8)
| (quint64(addr[15]) << 0);
src->set_v6_lo(x);
}
isOk = true;
break;
}
case kGroupRecords:
{
GmpProtocol::setFieldData(index, value, attrib);
QVariantList list = value.toList();
for (int i = 0; i < list.count(); i++)
{
QVariantMap grpRec = list.at(i).toMap();
OstProto::Gmp::GroupRecord *rec = data.mutable_group_records(i);
Q_IPV6ADDR addr = QHostAddress(
grpRec["groupRecordAddress"].toString())
.toIPv6Address();
quint64 x;
x = (quint64(addr[0]) << 56)
| (quint64(addr[1]) << 48)
| (quint64(addr[2]) << 40)
| (quint64(addr[3]) << 32)
| (quint64(addr[4]) << 24)
| (quint64(addr[5]) << 16)
| (quint64(addr[6]) << 8)
| (quint64(addr[7]) << 0);
rec->mutable_group_address()->set_v6_hi(x);
x = (quint64(addr[ 8]) << 56)
| (quint64(addr[ 9]) << 48)
| (quint64(addr[10]) << 40)
| (quint64(addr[11]) << 32)
| (quint64(addr[12]) << 24)
| (quint64(addr[13]) << 16)
| (quint64(addr[14]) << 8)
| (quint64(addr[15]) << 0);
rec->mutable_group_address()->set_v6_lo(x);
QStringList srcList = grpRec["groupRecordSourceList"]
.toStringList();
rec->clear_sources();
foreach (QString str, srcList)
{
OstProto::Gmp::IpAddress *src = rec->add_sources();
Q_IPV6ADDR addr = QHostAddress(str).toIPv6Address();
quint64 x;
x = (quint64(addr[0]) << 56)
| (quint64(addr[1]) << 48)
| (quint64(addr[2]) << 40)
| (quint64(addr[3]) << 32)
| (quint64(addr[4]) << 24)
| (quint64(addr[5]) << 16)
| (quint64(addr[6]) << 8)
| (quint64(addr[7]) << 0);
src->set_v6_hi(x);
x = (quint64(addr[ 8]) << 56)
| (quint64(addr[ 9]) << 48)
| (quint64(addr[10]) << 40)
| (quint64(addr[11]) << 32)
| (quint64(addr[12]) << 24)
| (quint64(addr[13]) << 16)
| (quint64(addr[14]) << 8)
| (quint64(addr[15]) << 0);
src->set_v6_lo(x);
}
}
isOk = true;
break;
}
default:
isOk = GmpProtocol::setFieldData(index, value, attrib);
break;
}
_exit:
return isOk;
}
quint16 MldProtocol::checksum(int streamIndex) const
{
return AbstractProtocol::protocolFrameCksum(streamIndex, CksumTcpUdp);
}
|
gpl-3.0
|
minagerges/MODX-GoogleAuthenticatorX
|
_build/GoogleAuthenticatorX/setup.options.php
|
1869
|
<?php
/*
* GoogleAuthenticatorX
*
* Copyright 2014 by Mina Gerges <mina@minagerges.com>
*
* GoogleAuthenticatorX 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.
*
* GoogleAuthenticatorX 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
* WipeCache; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
switch ($options[xPDOTransport::PACKAGE_ACTION]) {
case xPDOTransport::ACTION_INSTALL:
case xPDOTransport::ACTION_UPGRADE:
$output = <<<HTML
<p style="font-style: italic;"><strong>NB:</strong> Sending emails might extend the installation process time depending on the amount of users with manager access.</p>
<br/>
<div style="padding-left: 20px;">
<input type="checkbox" name="sendnotifymail" checked />
<label for="sendnotifymail" style="display: inline;">Email users with manager access <i>(New install only)</i></label>
<br/><br/>
<input type="checkbox" name="enablegax"/>
<label for="enablegax" style="display: inline;">Enable 2-factor verification</label>
<br />
<p style="color:red;">If you enable 2-step verification, be ready with your mobile device for setting up Google Authenticator, otherwise you will lose your login session.</p>
</div>
HTML;
break;
default:
case xPDOTransport::ACTION_UNINSTALL:
$output = '';
break;
}
return $output;
|
gpl-3.0
|
ourcities/rebu-client
|
packages/bonde-admin/src/mobrender/widgets/adjustments/component.js
|
4615
|
/**
* AdjustmentsForm
*
* Um componente para para submeter formulários de ajustes de widgets.
*/
import React from 'react'
import { intlShape, FormattedMessage } from 'react-intl'
import PropTypes from 'prop-types'
import {
FormGroup,
ControlLabel,
FormControl,
ColorPicker,
HelpBlock
} from '@/components/forms'
import { SettingsForm } from '@/ux/components'
const fieldsComponent = {
'call_to_action': ({ intl, ...field }) => (
<FormGroup controlId='call-to-action-id' {...field}>
<ControlLabel>
<FormattedMessage
id='adjustments.form.call-to-action.label'
defaultMessage='Título do formulário'
/>
</ControlLabel>
<FormControl
type='text'
placeholder={intl.formatMessage({
id: 'adjustments.form.call-to-action.placeholder',
defaultMessage: 'Ex: Preencha o formulário abaixo para assinar a petição.'
})}
/>
</FormGroup>
),
'button_text': ({ intl, ...field }) => (
<FormGroup controlId='button-text-id' {...field}>
<ControlLabel>
<FormattedMessage
id='adjustments.form.button-text.label'
defaultMessage='Botão'
/>
</ControlLabel>
<FormControl
type='text'
placeholder={intl.formatMessage({
id: 'adjustments.form.button-text.placeholder',
defaultMessage: 'Defina o texto do botão de confirmação do formulário.'
})}
/>
</FormGroup>
),
'count_text': ({ intl, ...field }) => (
<FormGroup controlId='count-text-id' {...field}>
<ControlLabel>
<FormattedMessage
id='adjustments.form.count-text.label'
defaultMessage='Contador'
/>
</ControlLabel>
<FormControl
type='text'
placeholder={intl.formatMessage({
id: 'adjustments.form.count-text.placeholder',
defaultMessage: 'Defina o texto que ficará ao lado do número de pessoas que agiram.'
})}
/>
<HelpBlock>
<FormattedMessage
id='adjustments.form.count-text.helpBlock'
defaultMessage='O contador será mostrado se existir um texto definido.'
/>
</HelpBlock>
</FormGroup>
),
'main_color': ({ intl, dispatch, colorScheme, ...field }) => (
<FormGroup controlId='main-color-id' {...field}>
<ControlLabel>
<FormattedMessage
id='adjustments.form.main-color.label'
defaultMessage='Cor padrão'
/>
</ControlLabel>
<HelpBlock>
<FormattedMessage
id='adjustments.form.main-color.helpBlock'
defaultMessage='Selecione a cor no box abaixo ou insira o valor em hex, por exemplo: #DC3DCE.'
/>
</HelpBlock>
<ColorPicker
dispatch={dispatch}
theme={colorScheme.replace('-scheme', '')}
/>
</FormGroup>
)
}
export const createAdjustmentsForm = (fieldList) => (props) => {
const {
children,
widget,
asyncWidgetUpdate,
// TODO: Remover essa dependencia da mobilização
dispatch,
colorScheme,
intl,
...formProps
} = props
return (
<SettingsForm
{...formProps}
onSubmit={values => {
const settings = widget.settings || {}
return asyncWidgetUpdate({
...widget,
settings: { ...settings, ...values }
})
}}
successMessage={intl.formatMessage({
id: 'adjustments.form.successMessage',
defaultMessage: 'Formulário configurado com sucesso!'
})}
>
{fieldList.filter(name => props.fields[name]).map(fieldName => {
const FieldComponent = fieldsComponent[fieldName]
const fieldProps = props.fields[fieldName]
return (
<FieldComponent
intl={intl}
dispatch={dispatch}
colorScheme={colorScheme}
{...fieldProps}
/>
)
})}
{children}
</SettingsForm>
)
}
export const AdjustmentsSettingsForm = createAdjustmentsForm([
'call_to_action', 'button_text', 'count_text', 'main_color'
])
AdjustmentsSettingsForm.propTypes = {
// Injected by redux-form
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
submitting: PropTypes.bool.isRequired,
error: PropTypes.string,
// Injected by widgets/models/ModelForm
colorScheme: PropTypes.string,
// Injected by container
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
asyncWidgetUpdate: PropTypes.func.isRequired,
// Injected by react-intl
intl: intlShape.isRequired
}
|
gpl-3.0
|
cheshirekow/codebase
|
src/tabwm/util.cc
|
8594
|
#include "util.h"
#include <algorithm>
#include <map>
#include <sstream>
#include <vector>
// Joins a container of elements into a single string, assuming each element
// in the container has a stream operator defined.
template <typename Container>
std::string Join(const Container& container, const std::string& delimiter) {
std::ostringstream out;
for (auto i = container.cbegin(); i != container.cend(); ++i) {
if (i != container.cbegin()) {
out << delimiter;
}
out << *i;
}
return out.str();
}
static std::vector<std::string> kEventTypeNames = {
"",
"",
"KeyPress",
"KeyRelease",
"ButtonPress",
"ButtonRelease",
"MotionNotify",
"EnterNotify",
"LeaveNotify",
"FocusIn",
"FocusOut",
"KeymapNotify",
"Expose",
"GraphicsExpose",
"NoExpose",
"VisibilityNotify",
"CreateNotify",
"DestroyNotify",
"UnmapNotify",
"MapNotify",
"MapRequest",
"ReparentNotify",
"ConfigureNotify",
"ConfigureRequest",
"GravityNotify",
"ResizeRequest",
"CirculateNotify",
"CirculateRequest",
"PropertyNotify",
"SelectionClear",
"SelectionRequest",
"SelectionNotify",
"ColormapNotify",
"ClientMessage",
"MappingNotify",
};
std::string XEventToString(const XEvent& e) {
std::stringstream properties_strm;
if (0 < e.type && e.type < kEventTypeNames.size()) {
properties_strm << kEventTypeNames[e.type] << "\n";
} else {
properties_strm << FormatStr("Unknown event type [%d]\n", e.type);
}
switch (e.type) {
case CreateNotify: {
const XCreateWindowEvent& ee = e.xcreatewindow;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("parent: %ul\n", ee.parent)
<< FormatStr("size: (%d,%d)\n", ee.width, ee.height)
<< FormatStr("position: (%d,%d)\n", ee.x, ee.y)
<< FormatStr("border_width: %d\n", ee.border_width)
<< FormatStr("override_redirect: %d\n", ee.override_redirect);
break;
}
case DestroyNotify: {
const XDestroyWindowEvent& ee = e.xdestroywindow;
properties_strm << FormatStr("window: %ul\n", ee.window);
break;
}
case MapNotify: {
const XMapEvent& ee = e.xmap;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("event: %ul", ee.event)
<< FormatStr("override_redirect: %ul\n", ee.override_redirect);
break;
}
case UnmapNotify: {
const XUnmapEvent& ee = e.xunmap;
properties_strm << FormatStr("window: %ul\n", ee.window)
<< FormatStr("event: %ul", ee.event)
<< FormatStr("from_configure: %ul\n", ee.from_configure);
break;
}
case ConfigureNotify: {
const XConfigureEvent& ee = e.xconfigure;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("size: (%d,%d)\n", ee.width, ee.height)
<< FormatStr("position: (%d,%d)\n", ee.x, ee.y)
<< FormatStr("border_width: %d\n", ee.border_width)
<< FormatStr("override_redirect: %d\n", ee.override_redirect);
break;
}
case ReparentNotify: {
const XReparentEvent& ee = e.xreparent;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("parent: %ul\n", ee.parent)
<< FormatStr("position: (%d,%d)\n", ee.x, ee.y)
<< FormatStr("override_redirect: %d", ee.override_redirect);
break;
}
case MapRequest: {
const XMapRequestEvent& ee = e.xmaprequest;
properties_strm << FormatStr("window: %ul\n", ee.window);
break;
}
case ConfigureRequest: {
const XConfigureRequestEvent& ee = e.xconfigurerequest;
std::vector<std::string> masks;
if (ee.value_mask & CWX) {
masks.emplace_back("X");
}
if (ee.value_mask & CWY) {
masks.emplace_back("Y");
}
if (ee.value_mask & CWWidth) {
masks.emplace_back("Width");
}
if (ee.value_mask & CWHeight) {
masks.emplace_back("Height");
}
if (ee.value_mask & CWBorderWidth) {
masks.emplace_back("BorderWidth");
}
if (ee.value_mask & CWSibling) {
masks.emplace_back("Sibling");
}
if (ee.value_mask & CWStackMode) {
masks.emplace_back("StackMode");
}
properties_strm << FormatStr("window: %ul\n", ee.window)
<< FormatStr("parent; %ul\n", ee.parent)
<< FormatStr("value_mask: %s\n", Join(masks, "|"))
<< FormatStr("position: (%d,%d)\n", ee.x, ee.y)
<< FormatStr("size: (%d,%d)\n", ee.width, ee.height)
<< FormatStr("border_width: %d\n", ee.border_width);
break;
}
case ButtonPress:
case ButtonRelease: {
const XButtonEvent& ee = e.xbutton;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("button: %ul\n", ee.button)
<< FormatStr("position_root: (%d,%d)\n", ee.x_root, ee.y_root);
break;
}
case MotionNotify: {
const XMotionEvent& ee = e.xmotion;
properties_strm
<< FormatStr("window: %ul\n", ee.window)
<< FormatStr("position_root: (%d,%d)\n", ee.x_root, ee.y_root)
<< FormatStr("state: %ul\n", ee.state)
<< FormatStr("time: %ul\n", ee.time);
break;
}
case KeyPress:
case KeyRelease: {
const XKeyEvent& ee = e.xkey;
properties_strm << FormatStr("window: %ul\n", ee.window)
<< FormatStr("state: %ul\n", ee.state)
<< FormatStr("keycode: %ul\n", ee.keycode);
break;
}
case Expose: {
const XExposeEvent& ee = e.xexpose;
properties_strm << FormatStr("window: %ul\n", ee.window)
<< FormatStr("offset: (%d,%d)\n", ee.x, ee.y)
<< FormatStr("size: (%d,%d)\n", ee.width, ee.height);
break;
}
default:
break;
}
return properties_strm.str();
}
static std::vector<std::string> kRequestCodeNames = {
"",
"CreateWindow",
"ChangeWindowAttributes",
"GetWindowAttributes",
"DestroyWindow",
"DestroySubwindows",
"ChangeSaveSet",
"ReparentWindow",
"MapWindow",
"MapSubwindows",
"UnmapWindow",
"UnmapSubwindows",
"ConfigureWindow",
"CirculateWindow",
"GetGeometry",
"QueryTree",
"InternAtom",
"GetAtomName",
"ChangeProperty",
"DeleteProperty",
"GetProperty",
"ListProperties",
"SetSelectionOwner",
"GetSelectionOwner",
"ConvertSelection",
"SendEvent",
"GrabPointer",
"UngrabPointer",
"GrabButton",
"UngrabButton",
"ChangeActivePointerGrab",
"GrabKeyboard",
"UngrabKeyboard",
"GrabKey",
"UngrabKey",
"AllowEvents",
"GrabServer",
"UngrabServer",
"QueryPointer",
"GetMotionEvents",
"TranslateCoords",
"WarpPointer",
"SetInputFocus",
"GetInputFocus",
"QueryKeymap",
"OpenFont",
"CloseFont",
"QueryFont",
"QueryTextExtents",
"ListFonts",
"ListFontsWithInfo",
"SetFontPath",
"GetFontPath",
"CreatePixmap",
"FreePixmap",
"CreateGC",
"ChangeGC",
"CopyGC",
"SetDashes",
"SetClipRectangles",
"FreeGC",
"ClearArea",
"CopyArea",
"CopyPlane",
"PolyPoint",
"PolyLine",
"PolySegment",
"PolyRectangle",
"PolyArc",
"FillPoly",
"PolyFillRectangle",
"PolyFillArc",
"PutImage",
"GetImage",
"PolyText8",
"PolyText16",
"ImageText8",
"ImageText16",
"CreateColormap",
"FreeColormap",
"CopyColormapAndFree",
"InstallColormap",
"UninstallColormap",
"ListInstalledColormaps",
"AllocColor",
"AllocNamedColor",
"AllocColorCells",
"AllocColorPlanes",
"FreeColors",
"StoreColors",
"StoreNamedColor",
"QueryColors",
"LookupColor",
"CreateCursor",
"CreateGlyphCursor",
"FreeCursor",
"RecolorCursor",
"QueryBestSize",
"QueryExtension",
"ListExtensions",
"ChangeKeyboardMapping",
"GetKeyboardMapping",
"ChangeKeyboardControl",
"GetKeyboardControl",
"Bell",
"ChangePointerControl",
"GetPointerControl",
"SetScreenSaver",
"GetScreenSaver",
"ChangeHosts",
"ListHosts",
"SetAccessControl",
"SetCloseDownMode",
"KillClient",
"RotateProperties",
"ForceScreenSaver",
"SetPointerMapping",
"GetPointerMapping",
"SetModifierMapping",
"GetModifierMapping",
"NoOperation",
};
std::string XRequestCodeToString(unsigned char request_code) {
if (0 < request_code && request_code < kRequestCodeNames.size()) {
return kRequestCodeNames[request_code];
} else {
return "Unknown request code";
}
}
|
gpl-3.0
|
VVLJyotsna/PipelineEmbolization
|
dataprocessing.py
|
2649
|
import csv, json
import numpy as np
from collections import Counter
from sklearn import svm
def readdata (): #calls the csv file into python
csvfile = open('DrColby_data.csv',"rU")
dmd = csv.reader(csvfile, delimiter = ",")
dmd.next()
header = list(dmd)
csvfile.close()
dmd_data = []
for row in header:
dmd_data.append(row)
return dmd_data
mydata = readdata() #the data from the csv file
def readanycolumn(mydata, n): #to read a column
datacolumn = []
for row in mydata:
datacolumn.append(row[n])
return datacolumn
def countelements(n):
x = readanycolumn(mydata,n)
d = Counter(x)
count=json.dumps(d)
return count
with open('DrColby_data.csv') as fin, open('out.csv', 'wb') as fout:
r = csv.reader(fin)
w = csv.writer(fout)
for row in r:
replacements = {'Y':'1', 'N':'0', 'F':'3', 'M':'4', 'W':'1', 'B': '2', 'A':'3', 'H':'4', 'C':'1', 'PE':'2', 'S':'4','M':'1', 'V':'2','SL':'1', 'SG':'2', 'L':'3', 'S':'4', 'G':'5','DS':'1', 'SF':'2', 'F':'3', 'D':'4', 'T':'1', 'B':'2', 'R':'3', 'P' : '1', 'MO':'0', 'MI':'0', '':'0', ' ': '0'}
for row in r:
w.writerow([replacements.get(cell,cell)for cell in row])
def new_data (): #calls the csv file into python
csv_file = open('out.csv',"rU")
dmd = csv.reader(csv_file, delimiter = ",")
#header = list(dmd)
# strip=map(lambda s: s.strip (), strip)
dmd_data = []
for row in csv_file:
dmd_data.append(row)
csv_file.close()
return dmd_data
newdata=new_data()
newdata[:]=[line.rstrip("\n") for line in newdata]
the_data= np.array(newdata)
#print dataset
thedata = the_data.T
dataset = thedata.tolist()
#the_data = [float(x) for x in the_data]
def split_class_and_data(dataset): #splits the class values into one list and the remaining data into 2nd list
y =[]
d=[]
for row in dataset:
row1 = row.split(",");
y.append(row1[15])
d.append(row1[1:14]+row1[16:])
return (y,d) #tuple that returns the 1st elent, the second element)
y,X= split_class_and_data(dataset)
clf=svm.SVC(kernel='linear', C=1) #setting up svm to be trained. use linear as default
clf.fit(X,y) #first arg is data, second arg is the class
print "clf=", clf
print"Now predicting"
t1=X[0] #the first entry in the data, and without the class info and predict what class it belongs to.
r=clf.predict(t1) #pass in the item or entry that you want to make a prediction about
print "Prediction result=",r
print "\n\n"
print "svmdata.py loaded"
#training is analogous to treatment outcome, location etc etc is learned by the svm and it is trained
|
gpl-3.0
|
LeoTremblay/activityinfo
|
server/src/main/java/org/activityinfo/legacy/shared/adapter/projection/PartnerProjectionUpdater.java
|
1810
|
package org.activityinfo.legacy.shared.adapter.projection;
/*
* #%L
* ActivityInfo Server
* %%
* Copyright (C) 2009 - 2013 UNICEF
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import org.activityinfo.core.shared.Projection;
import org.activityinfo.model.formTree.FieldPath;
import org.activityinfo.legacy.shared.adapter.CuidAdapter;
import org.activityinfo.legacy.shared.model.PartnerDTO;
/**
* @author yuriyz on 4/15/14.
*/
public class PartnerProjectionUpdater implements ProjectionUpdater<PartnerDTO> {
private FieldPath path;
private int databaseId;
private int fieldIndex;
public PartnerProjectionUpdater(FieldPath path, int databaseId, int fieldIndex) {
this.path = path;
this.databaseId = databaseId;
this.fieldIndex = fieldIndex;
}
@Override
public void update(Projection projection, PartnerDTO dto) {
switch (fieldIndex) {
case CuidAdapter.NAME_FIELD:
projection.setValue(path, dto.getName());
break;
case CuidAdapter.FULL_NAME_FIELD:
projection.setValue(path, dto.getFullName());
break;
}
}
}
|
gpl-3.0
|
diego-nz/socialNetWorkv5
|
core/model/Company.php
|
3993
|
<?php
include ("Connection.php");
class Company extends Connection{
public function companySignUp($nameCompany,$giro,$rfc){
//VIFG2335636V4
$objRFC = new Company();
if($objRFC->validaRFC($rfc)){
$query2 = "SELECT * FROM empresa WHERE nombre = '".$nameCompany."'";
$rs2 = mysqli_query($this->getConnection(),$query2) or die("ERROR ".mysqli_error($this->getConnection()));
if(mysqli_num_rows($rs2)!=0){
echo 1;
}else {
$query3 = "SELECT * FROM empresa WHERE rfc='".$rfc."'";
$rs3 = mysqli_query($this->getConnection(),$query3);
if(mysqli_num_rows($rs3)!=0){
echo 2;
}else {
$query = "SELECT MAX(idUsuario) as idUsu FROM usuario";
$rs = mysqli_query($this->getConnection(),$query) or die("ERROR ".mysqli_error($this->getConnection()));
$row = mysqli_fetch_array($rs);
$idUsu = $row['idUsu'];
$queryInsert = "INSERT INTO empresa VALUES(null,'".$nameCompany."',".$idUsu.",'".$giro."','".$rfc."')";
mysqli_query($this->getConnection(),$queryInsert) or die ("ERROR ".mysqli_error($this->getConnection()));
echo 3;
}
}
}else{
echo 4;
}
/*$query2 = "SELECT * FROM empresa WHERE nombre = '".$nameCompany."'";
$rs2 = mysqli_query($this->getConnection(),$query2) or die("ERROR ".mysqli_error($this->getConnection()));
if(mysqli_num_rows($rs2)!=0){
echo 1;
}else {
$query3 = "SELECT * FROM empres WHERE rfc='".$rfc."'";
$rs3 = mysqli_query($this->getConnection(),$query3);
if(mysqli_num_rows($rs3)!=0){
echo 2;
}else {
$query = "SELECT MAX(idUsuario) as idUsu FROM usuario";
$rs = mysqli_query($this->getConnection(),$query) or die("ERROR ".mysqli_error($this->getConnection()));
$row = mysqli_fetch_array($rs);
$idUsu = $row['idUsu'];
$queryInsert = "INSERT INTO empresa VALUES(null,'".$nameCompany."',".$idUsu.",'".$giro."','".$rfc."')";
mysqli_query($this->getConnection(),$queryInsert) or die ("ERROR ".mysqli_error($this->getConnection()));
echo 3;
}
}
*/
}
public function typePersonRFC($typePerson){
/*Persona fisica*/
if($typePerson == 1){
echo '<input type="text" maxlength="13" class="form-control" placeholder="RFC" id="txtRFC" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase();">';
/*Persona Moral*/
}else if($typePerson == 2){
echo '<input type="text" maxlength="12" class="form-control" placeholder="RFC" id="txtRFC" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase();">';
}
}
public function validaRFC($valor) {
$valor = str_replace("-", "", $valor);
$cuartoValor = substr($valor, 3, 1);
//RFC Persona Moral.
if (ctype_digit($cuartoValor) && strlen($valor) == 12) {
$letras = substr($valor, 0, 3);
$numeros = substr($valor, 3, 6);
$homoclave = substr($valor, 9, 3);
if (ctype_alpha($letras) && ctype_digit($numeros) && ctype_alnum($homoclave)) {
return true;
}
//RFC Persona Física.
} else if (ctype_alpha($cuartoValor) && strlen($valor) == 13) {
$letras = substr($valor, 0, 4);
$numeros = substr($valor, 4, 6);
$homoclave = substr($valor, 10, 3);
if (ctype_alpha($letras) && ctype_digit($numeros) && ctype_alnum($homoclave)) {
return true;
}
}else {
return false;
}
}
}
?>
|
gpl-3.0
|
lotaris/rox-center
|
spec/factories/user.rb
|
1316
|
# Copyright (c) 2012-2014 Lotaris SA
#
# This file is part of ROX Center.
#
# ROX Center 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.
#
# ROX Center 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 ROX Center. If not, see <http://www.gnu.org/licenses/>.
FactoryGirl.define do
factory :user, aliases: [ :author, :runner ] do
name 'jdoe'
email 'john.doe@lotaris.com'
password 'testtest'
factory :other_user do
name 'jsmith'
email 'john.smith@lotaris.com'
end
factory :another_user do
name 'jsparrow'
email 'jack.sparrow@lotaris.com'
end
factory :technical_user do
name 'bot'
email nil
roles_mask User.mask_for(:technical)
end
factory :admin_user, aliases: [ :admin ] do
name 'admin'
email 'admin@lotaris.com'
roles_mask User.mask_for(:admin)
end
end
end
|
gpl-3.0
|
lukegjpotter/BikeRacingIreland-AndroidApp
|
app/src/main/java/com/lukegjpotter/bikeracingireland/repository/retrofit/BikeRaceRetrofitClient.java
|
617
|
package com.lukegjpotter.bikeracingireland.repository.retrofit;
import com.lukegjpotter.bikeracingireland.model.entity.BikeRaceWithStageDetails;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
/**
* The Client for Retrofit.
* <p>
* This will define the calls that we can make.
* It will map the EndPoints too.
* <p>
* Created by lukegjpotter on 19/12/2017.
*/
public interface BikeRaceRetrofitClient {
@GET("/roadraces/month/{monthNumber}")
Call<List<BikeRaceWithStageDetails>> bikeRacesForMonthNumber(@Path("monthNumber") int monthNumber);
}
|
gpl-3.0
|
asoplata/dynasim-benchmark-brette-2007
|
Brian2/brian2_benchmark_CUBA_nosyn_0001.py
|
1997
|
"""
# Notes:
- This simulation seeks to emulate the CUBA benchmark simulations of (Brette
et al. 2007) using the Brian2 simulator for speed benchmark comparison to
DynaSim. However, this simulation does NOT include synapses, for better
comparison to Figure 5 of (Goodman and Brette, 2008).
- The time taken to simulate will be indicated in the stdout log file
'~/batchdirs/brian_benchmark_CUBA_nosyn_1/pbsout/brian_benchmark_CUBA_nosyn_1.out'
- Note that this code has been slightly modified from the original (Brette et
al. 2007) benchmarking code, available here on ModelDB:
https://senselab.med.yale.edu/modeldb/showModel.cshtml?model=83319
in order to work with version 2 of the Brian simulator (aka Brian2), and also
modified to change the model being benchmarked, etc.
# References:
- Brette R, Rudolph M, Carnevale T, Hines M, Beeman D, Bower JM, et al.
Simulation of networks of spiking neurons: A review of tools and strategies.
Journal of Computational Neuroscience 2007;23:349–98.
doi:10.1007/s10827-007-0038-6.
- Goodman D, Brette R. Brian: a simulator for spiking neural networks in Python.
Frontiers in Neuroinformatics 2008;2. doi:10.3389/neuro.11.005.2008.
"""
from brian2 import *
# Parameters
cells = 1
defaultclock.dt = 0.01*ms
taum=20*ms
Vt = -50*mV
Vr = -60*mV
El = -49*mV
# The model
eqs = Equations('''
dv/dt = ((v-El))/taum : volt
''')
P = NeuronGroup(cells, model=eqs,threshold="v>Vt",reset="v=Vr",refractory=5*ms,
method='euler')
proportion=int(0.8*cells)
Pe = P[:proportion]
Pi = P[proportion:]
# Initialization
P.v = Vr
# Record a few traces
trace = StateMonitor(P, 'v', record=[1, 10, 100])
totaldata = StateMonitor(P, 'v', record=True)
run(0.5 * second, report='text')
# plot(trace.t/ms, trace[1].v/mV)
# plot(trace.t/ms, trace[10].v/mV)
# plot(trace.t/ms, trace[100].v/mV)
# xlabel('t (ms)')
# ylabel('v (mV)')
# show()
# print("Saving TC cell voltages!")
# numpy.savetxt("foo_totaldata.csv", totaldata.v/mV, delimiter=",")
|
gpl-3.0
|
fetux/multimediamanager
|
app/src/main/java/com/fetu/multimedia/FileAdapter.java
|
2726
|
package com.fetu.multimedia;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.fetu.manager.Album;
import com.fetu.manager.File;
import com.fetu.manager.ImageFile;
import com.fetu.manager.Nodo;
import com.fetu.manager.VideoFile;
import java.util.Iterator;
import java.util.TreeSet;
/**
* Created by fetu on 09/05/15.
*/
public class FileAdapter extends BaseAdapter{
private final Activity actividad;
private final TreeSet<Nodo> lista;
public FileAdapter(Activity actividad, TreeSet<Nodo> lista) {
super();
this.actividad = actividad;
this.lista = lista;
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Object getItem(int position) {
int i=0;
Iterator<Nodo> iterator = lista.iterator();
while (iterator.hasNext() && i < position){
i++;
iterator.next();
}
if (i == position) {
return iterator.next();
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = actividad.getLayoutInflater();
View view = inflater.inflate(R.layout.file,null,true);
int i=0;
Iterator<Nodo> iterator = lista.iterator();
while (iterator.hasNext() && i < position){
iterator.next();
i++;
}
if (i == position) {
Nodo f = iterator.next();
TextView textView = (TextView) view.findViewById(R.id.name);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
if (f instanceof File){
textView.setText(((File)f).getName());
if (f instanceof ImageFile){
imageView.setImageResource(R.drawable.image);
} else
if (f instanceof VideoFile){
imageView.setImageResource(R.drawable.video);
} else {
imageView.setImageResource(R.drawable.audio);
}
}
else if (f instanceof Album){
textView.setText(((Album)f).getName());
imageView.setImageResource(R.drawable.folder);
}
return view;
}
return null;
}
}
|
gpl-3.0
|
yuqirong/BlogBackup
|
uploads/20160826/CrashHandler.java
|
4411
|
package com.example.crash;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.util.Log;
public class CrashHandler implements UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final boolean DEBUG = true;
private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/CrashTest/log/";
private static final String FILE_NAME = "crash";
private static final String FILE_NAME_SUFFIX = ".trace";
private static CrashHandler sInstance = new CrashHandler();
private UncaughtExceptionHandler mDefaultCrashHandler;
private Context mContext;
private CrashHandler() {
}
public static CrashHandler getInstance() {
return sInstance;
}
public void init(Context context) {
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
/**
* Õâ¸öÊÇ×î¹Ø¼üµÄº¯Êý£¬µ±³ÌÐòÖÐÓÐδ±»²¶»ñµÄÒì³££¬ÏµÍ³½«»á×Ô¶¯µ÷ÓÃ#uncaughtException·½·¨
* threadΪ³öÏÖδ²¶»ñÒì³£µÄỊ̈߳¬exΪδ²¶»ñµÄÒì³££¬ÓÐÁËÕâ¸öex£¬ÎÒÃǾͿÉÒԵõ½Òì³£ÐÅÏ¢¡£
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
//µ¼³öÒì³£ÐÅÏ¢µ½SD¿¨ÖÐ
dumpExceptionToSDCard(ex);
uploadExceptionToServer();
//ÕâÀï¿ÉÒÔͨ¹ýÍøÂçÉÏ´«Òì³£ÐÅÏ¢µ½·þÎñÆ÷£¬±ãÓÚ¿ª·¢ÈËÔ±·ÖÎöÈÕÖ¾´Ó¶ø½â¾öbug
} catch (IOException e) {
e.printStackTrace();
}
ex.printStackTrace();
//Èç¹ûϵͳÌṩÁËĬÈϵÄÒì³£´¦ÀíÆ÷£¬Ôò½»¸øÏµÍ³È¥½áÊøÎÒÃǵijÌÐò£¬·ñÔò¾ÍÓÉÎÒÃÇ×Ô¼º½áÊø×Ô¼º
if (mDefaultCrashHandler != null) {
mDefaultCrashHandler.uncaughtException(thread, ex);
} else {
Process.killProcess(Process.myPid());
}
}
private void dumpExceptionToSDCard(Throwable ex) throws IOException {
//Èç¹ûSD¿¨²»´æÔÚ»òÎÞ·¨Ê¹Óã¬ÔòÎÞ·¨°ÑÒì³£ÐÅϢдÈëSD¿¨
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (DEBUG) {
Log.w(TAG, "sdcard unmounted,skip dump exception");
return;
}
}
File dir = new File(PATH);
if (!dir.exists()) {
dir.mkdirs();
}
long current = System.currentTimeMillis();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
try {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(time);
dumpPhoneInfo(pw);
pw.println();
ex.printStackTrace(pw);
pw.close();
} catch (Exception e) {
Log.e(TAG, "dump crash info failed");
}
}
private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
pw.print("App Version: ");
pw.print(pi.versionName);
pw.print('_');
pw.println(pi.versionCode);
//android°æ±¾ºÅ
pw.print("OS Version: ");
pw.print(Build.VERSION.RELEASE);
pw.print("_");
pw.println(Build.VERSION.SDK_INT);
//ÊÖ»úÖÆÔìÉÌ
pw.print("Vendor: ");
pw.println(Build.MANUFACTURER);
//ÊÖ»úÐͺÅ
pw.print("Model: ");
pw.println(Build.MODEL);
//cpu¼Ü¹¹
pw.print("CPU ABI: ");
pw.println(Build.CPU_ABI);
}
private void uploadExceptionToServer() {
//TODO Upload Exception Message To Your Web Server
}
}
|
gpl-3.0
|
ymirsky/pcStream
|
pcStream/Android/accelerometerPcStream/gen/com/example/accelerometerPcStream/R.java
|
189
|
/*___Generated_by_IDEA___*/
package com.example.accelerometerPcStream;
/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */
public final class R {
}
|
gpl-3.0
|
f-arruza/PaymentService
|
paymentservice/urls.py
|
222
|
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^', include('payment.urls')),
# url(r'^payment/', include('payment.urls')),
url(r'^admin/', admin.site.urls),
]
|
gpl-3.0
|
nickapos/myCrop
|
src/gr/oncrete/nick/myCrop/BusinessLogic/InsertFertRecipy.java
|
3962
|
/*
myCrop, crop managment program
Copyright (C) 2010 Nick Apostolakis
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/>.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gr.oncrete.nick.myCrop.BusinessLogic;
import gr.oncrete.nick.myCrop.RDBMS.InsertIntoTable;
import gr.oncrete.nick.myCrop.UserInterface.PopupMessageFrame;
import gr.oncrete.nick.myCrop.BusinessLogic.SelectInfo.SelectCropTypeDetails;
import gr.oncrete.nick.myCrop.BusinessLogic.SelectInfo.SelectNutrientTypeDetails;
/**
*
* @author nickapos
*
* This class is used to insert new type entries into the database
*/
public class InsertFertRecipy {
/**
* Constructor insert company without an id
*
* @param cName
* @param afm
*/
public InsertFertRecipy()
{
}
/**
* method that will insert a fertilizer recipy when provided with the croptype id
* and nutrient type id
*
* @param cid
* @param nutid
* @param quantity
* @param obs
*/
public void insertFrecipyWithIDs(String cid, String nutid,String quantity ,String obs)
{
if(cid.length()>0 && nutid.length()>0 &&quantity.length()>0 )
{
if (!(obs.length()>0))
obs = "";
String sql = "insert into frecipy (cid,nutid,quantity,observations) values ("+cid+","+nutid+","+quantity+",'"+obs+"')";
InsertIntoTable in = new InsertIntoTable(sql);
System.out.println(sql);
}
else
{
this.emptyValuesPopup();
}
}
public void insertFrecipyWithIDs(String frid,String cid, String nutid,String quantity ,String obs)
{
if(cid.length()>0 && nutid.length()>0 &&quantity.length()>0 )
{
if (!(obs.length()>0))
obs = "";
String sql = "insert into frecipy (frid,cid,nutid,quantity,observations) values ("+frid+","+cid+","+nutid+","+quantity+",'"+obs+"')";
InsertIntoTable in = new InsertIntoTable(sql);
System.out.println(sql);
}
else
{
this.emptyValuesPopup();
}
}
/**
* this method will take as arguments the recipy types with crop and nutrient names
* convert the names to ids and feed it to insertFrecipyWithIDs
* @param ctypeName
* @param nutTypeID
* @param quantity
* @param obs
*/
public void insertFrecipyWithNames(String ctypeName, String nutTypeName,String quantity ,String obs)
{
if(ctypeName.length()>0 && nutTypeName.length()>0 &&quantity.length()>0 )
{
SelectCropTypeDetails ct = new SelectCropTypeDetails();
ct.SelectCropTypeDetailsWithName(ctypeName);
SelectNutrientTypeDetails nt = new SelectNutrientTypeDetails();
nt.SelectNutrientTypeDetailsWithName(nutTypeName);
this.insertFrecipyWithIDs(ct.getID(), nt.getID(), quantity, obs);
}
else
{
this.emptyValuesPopup();
}
}
private void emptyValuesPopup() {
PopupMessageFrame mes = new PopupMessageFrame();
mes.setWarning(java.util.ResourceBundle.getBundle("gr/oncrete/nick/myCrop/UserInterface/Bundle").getString("EMPTY-VALUES"));
}
}
|
gpl-3.0
|
haskelladdict/sconcho
|
sconcho/gui/export_bitmap_dialog.py
|
15506
|
# -*- coding: utf-8 -*-
########################################################################
#
# (c) 2009-2013 Markus Dittrich
#
# This program 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.
#
# 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 Version 3 for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
#######################################################################
import math
import logging
from functools import partial
from PyQt4.QtCore import (QDir,
QFile,
QFileInfo,
Qt,
SIGNAL)
from PyQt4.QtGui import (QDialog,
QDialogButtonBox,
QFileDialog,
QImageWriter,
QMessageBox)
from sconcho.gui.ui_export_bitmap_dialog import Ui_ExportBitmapDialog
from sconcho.util.canvas import visible_bounding_rect
import sconcho.util.messages as msg
# module lever logger:
logger = logging.getLogger(__name__)
# global conversion
inToCm = 1/0.393700787
# dictionary with description of most common image file formats
imageFileFormats = { "png" : "Portable Networks Graphic",
"bmp" : "Bitmap Image File",
"ico" : "Ico File Format",
"jpeg" : "Joint Photographic Experts Group Format",
"jpg" : "Joint Photographic Experts Group Format",
"ppm" : "Netpbm Color Image Format",
"tif" : "Tagged Image File Format",
"tiff" : "Tagged Image File Format",
"xbm" : "X Bitmap Format",
"xpm" : "X PixMap Format",
"svg" : "Scalable Vector Graphics" }
##########################################################################
#
# This widget allows users to adjust to control exporting of the
# canvas to a bitmap
#
##########################################################################
class ExportBitmapDialog(QDialog, Ui_ExportBitmapDialog):
def __init__(self, canvas, fileName = "Unknown", parent = None):
""" Initialize the dialog. """
super(ExportBitmapDialog, self).__init__(parent)
self.setupUi(self)
self._determine_image_formats()
self._add_image_formats_to_gui()
if fileName:
self.fullPath = QDir.homePath() + "/" + \
QFileInfo(fileName).baseName()
else:
self.fullPath = QDir.homePath() + "/"
extension = self.selected_file_extension()
self.fileNameEdit.setText(self.fullPath + "." + extension)
# NOTE: This has to come first since we rely on them
# to syncronize the widgets
self._set_up_connections()
self.canvas = canvas
self.currentUnit = 0
self.unitSelector.setCurrentIndex(self.currentUnit)
self.defaultDPI = 300
self.update_dimensions()
self.dpiSpinner.setValue(self.defaultDPI)
def _set_up_connections(self):
""" Set up all the widget connections. """
# synchronize spin boxes
self.connect(self.imageWidthSpinner, SIGNAL("valueChanged(double)"),
self.imageWidth_update)
self.connect(self.imageHeightSpinner,
SIGNAL("valueChanged(double)"),
self.imageHeight_update)
self.connect(self.widthSpinner, SIGNAL("valueChanged(int)"),
self.width_update)
self.connect(self.heightSpinner, SIGNAL("valueChanged(int)"),
self.height_update)
self.connect(self.dpiSpinner, SIGNAL("valueChanged(int)"),
self.dpi_update)
self.connect(self.unitSelector, SIGNAL("currentIndexChanged(int)"),
self.unit_update)
self.connect(self.browseButton, SIGNAL("pressed()"),
self.open_file_selector)
self.connect(self.cancelButton, SIGNAL("pressed()"),
self.close)
self.connect(self.exportButton, SIGNAL("pressed()"),
self.accept)
self.connect(self.availableFormatsChooser,
SIGNAL("currentIndexChanged(int)"),
self.update_path_extension)
def showEvent(self, event):
""" We derive showEvent so we can update
the current canvas dimensions.
"""
self.update_dimensions()
return QDialog.showEvent(self, event)
def update_dimensions(self):
""" Update values with the current canvas dimensions """
size = visible_bounding_rect(self.canvas.items())
imageWidth = math.floor(size.width())
imageHeight = math.floor(size.height())
self.imageWidth = imageWidth
self.imageHeight = imageHeight
self._aspectRatio = imageWidth/imageHeight
self.imageWidthSpinner.setValue(
int(self._convert_pixels_to_length(self.imageWidth)))
self.imageHeightSpinner.setValue(
int(self._convert_pixels_to_length(self.imageHeight)))
def _determine_image_formats(self):
""" Determine and store all image formats we can
support.
"""
self.formats = [str(formating, "utf-8") for \
formating in QImageWriter.supportedImageFormats()]
# we support svg format as well
self.formats.append("svg")
def _add_image_formats_to_gui(self):
""" This function lists all available formats on the gui
NOTE: We set png as the default for now.
"""
defaultIndex = 0
for (index, aFormat) in enumerate(self.formats):
if aFormat in imageFileFormats:
description = imageFileFormats[aFormat]
else:
description = "Image Format"
if aFormat == "png":
defaultIndex = index
formatStr = ("%s (*.%s)" % (description, aFormat))
self.availableFormatsChooser.insertItem(index, formatStr, aFormat)
# set the default
self.availableFormatsChooser.setCurrentIndex(defaultIndex)
def imageWidth_update(self, newWidth):
""" Update after image width change. """
self.imageWidth = self._convert_length_to_pixels(newWidth)
self.imageHeight = self.imageWidth/self._aspectRatio
height = self._convert_pixels_to_length(self.imageHeight)
dpi = self.dpiSpinner.value()
self._set_blocking_value(self.imageHeightSpinner, height)
self._set_blocking_value(self.widthSpinner,
self.imageWidth * dpi/self.defaultDPI)
self._set_blocking_value(self.heightSpinner,
self.imageHeight * dpi/self.defaultDPI)
def imageHeight_update(self, newHeight):
""" Update after image width change. """
self.imageHeight = self._convert_length_to_pixels(newHeight)
self.imageWidth = self.imageHeight * self._aspectRatio
width = self._convert_pixels_to_length(self.imageWidth)
dpi = self.dpiSpinner.value()
self._set_blocking_value(self.imageWidthSpinner, width)
self._set_blocking_value(self.widthSpinner,
self.imageWidth * dpi/self.defaultDPI)
self._set_blocking_value(self.heightSpinner,
self.imageHeight * dpi/self.defaultDPI)
def _convert_length_to_pixels(self, length):
""" Converts a length value in currentUnit to pixels """
# pixels
if self.currentUnit == 1:
length *= self.defaultDPI
elif self.currentUnit == 2:
length = length/inToCm * self.defaultDPI
return length
def _convert_pixels_to_length(self, length):
""" Converts a pixel value to length in currentUnit """
# pixels
if self.currentUnit == 1:
length /= self.defaultDPI
elif self.currentUnit == 2:
length = length/self.defaultDPI * inToCm
return length
def width_update(self, newWidth):
""" Update after width change. """
height = newWidth/self._aspectRatio
dpi = newWidth/self.imageWidth * self.defaultDPI
self._set_blocking_value(self.heightSpinner, height)
self._set_blocking_value(self.dpiSpinner, dpi)
def height_update(self, newHeight):
""" Update after height change. """
width = newHeight * self._aspectRatio
dpi = width/self.imageWidth * self.defaultDPI
self._set_blocking_value(self.widthSpinner, width)
self._set_blocking_value(self.dpiSpinner, dpi)
def dpi_update(self, newDPI):
""" Update after dpi change. """
width = newDPI/self.defaultDPI * self.imageWidth
height = width/self._aspectRatio
self._set_blocking_value(self.heightSpinner, height)
self._set_blocking_value(self.widthSpinner, width)
def unit_update(self, newUnit):
""" Update after unit change. """
self.currentUnit = newUnit
# pixels
if newUnit == 0:
self._set_blocking_value(self.imageWidthSpinner,
self.imageWidth)
self._set_blocking_value(self.imageHeightSpinner,
self.imageHeight)
# inches
elif newUnit == 1:
self._set_blocking_value(self.imageWidthSpinner,
self.imageWidth/self.defaultDPI)
self._set_blocking_value(self.imageHeightSpinner,
self.imageHeight/self.defaultDPI)
# cm
elif newUnit == 2:
self._set_blocking_value(self.imageWidthSpinner,
self.imageWidth/self.defaultDPI*inToCm)
self._set_blocking_value(self.imageHeightSpinner,
self.imageHeight/self.defaultDPI*inToCm)
def _set_blocking_value(self, theObject, value):
""" Helper function for setting selector values.
Blocks signals to avoid infinite loop.
"""
theObject.blockSignals(True)
theObject.setValue(value)
theObject.blockSignals(False)
def update_path_extension(self, selectionID):
""" This function updates the filename extension
if the user changes the image file format.
"""
selectedExtension = \
self.availableFormatsChooser.itemData(selectionID)
self.fileNameEdit.setText(self.fullPath + "." + selectedExtension)
def update_export_path(self, filePath):
""" This function is called if the export file
name has changed.
If the filePath has a valid image file format extension
we keep it otherwise we use the currently selected one.
"""
basename = QFileInfo(filePath).completeBaseName()
path = QFileInfo(filePath).absolutePath()
self.fullPath = \
QFileInfo(path + "/" + basename).absoluteFilePath()
extension = QFileInfo(filePath).suffix()
if extension in self.formats:
for index in range(self.availableFormatsChooser.count()):
item = self.availableFormatsChooser.itemData(index)
if item == extension:
self.availableFormatsChooser.setCurrentIndex(index)
break
else:
extension = self.selected_file_extension()
self.fileNameEdit.setText(self.fullPath + "." + extension)
def open_file_selector(self):
""" Open a file selector and ask for the name """
formatStr = "All Files (*.*)"
for aFormat in self.formats:
if aFormat in imageFileFormats:
description = imageFileFormats[aFormat]
else:
description = "Image Format"
formatStr = ("%s;; %s ( *.%s)" % (formatStr, description,
aFormat))
defaultPath = self.fileNameEdit.text()
if not defaultPath:
defaultPath = QDir.homePath()
exportFilePath = QFileDialog.getSaveFileName(self,
msg.exportPatternTitle,
defaultPath,
formatStr,
QFileDialog.DontConfirmOverwrite)
if exportFilePath:
self.update_export_path(exportFilePath)
def accept(self):
""" Checks that we have a path and reminds the user to
enter one if not.
"""
exportFilePath = self.fileNameEdit.text()
if not exportFilePath:
logger.warn(msg.noFilePathText)
QMessageBox.warning(self, msg.noFilePathTitle,
msg.noFilePathText,
QMessageBox.Close)
return
# check if a filename was provided - if not we open the
# file dialog
if not QFileInfo(exportFilePath).baseName():
self.open_file_selector()
return
# check the extension; if none is present we use the one
# selected in the format combo box
extension = QFileInfo(exportFilePath).suffix()
if extension not in self.formats:
exportFilePath += ("." + self.selected_file_extension())
# if file exists issue a warning as well
if QFile(exportFilePath).exists():
saveFileName = QFileInfo(exportFilePath).fileName()
messageBox = QMessageBox.question(self,
msg.imageFileExistsTitle,
msg.imageFileExistsText % saveFileName,
QMessageBox.Ok | QMessageBox.Cancel)
if (messageBox == QMessageBox.Cancel):
return
# provide the io subroutines with the relevant info
width = self.widthSpinner.value()
height = self.heightSpinner.value()
dpi = self.dpiSpinner.value()
self.emit(SIGNAL("export_pattern"), width, height, dpi,
exportFilePath)
QDialog.accept(self)
def selected_file_extension(self):
""" Returns a string with the currently selected image file
extension.
"""
extensionID = \
self.availableFormatsChooser.currentIndex()
selectedExtension = \
str(self.availableFormatsChooser.itemData(extensionID))
return selectedExtension
def keyPressEvent(self, event):
""" We catch the return key so we don't open
up the browse menu.
"""
if event.key() == Qt.Key_Return:
return
QDialog.keyPressEvent(self, event)
|
gpl-3.0
|
tawazz/crm
|
app/views/parts/css.php
|
514
|
<!-- Bootstrap Core CSS -->
<link href="{{ assets('css/bootstrap.min.css')}}" rel="stylesheet">
<link href="{{ assets('css/bootstrap-material-design.min.css')}}" rel="stylesheet">
<link href="{{ assets('css/ripples.min.css')}}" rel="stylesheet">
<link href="{{ assets('font-awesome/css/font-awesome.min.css')}}" rel="stylesheet">
<link href="{{ assets('css/nprogress.css')}}" rel="stylesheet">
<link href="{{ assets('css/build.css')}}" rel="stylesheet">
<link href="{{ assets('css/theme.css')}}" rel="stylesheet">
|
gpl-3.0
|
PnEcrins/GeoNature-atlas
|
atlas/modeles/entities/vmObservations.py
|
1430
|
# coding: utf-8
from geoalchemy2.types import Geometry
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
String,
Table,
Text,
)
from sqlalchemy.ext.declarative import declarative_base
from atlas.utils import engine
metadata = MetaData()
Base = declarative_base()
class VmObservations(Base):
__table__ = Table(
"vm_observations",
metadata,
Column("id_observation", Integer, primary_key=True, unique=True),
Column("insee", String(5), index=True),
Column("dateobs", Date, index=True),
Column("observateurs", String(255)),
Column("altitude_retenue", Integer, index=True),
Column("cd_ref", Integer, index=True),
Column("the_geom_point", Geometry(geometry_type="POINT", srid=4326)),
Column("geojson_point", Text),
Column("diffusion_level"),
schema="atlas",
autoload=True,
autoload_with=engine,
)
class VmObservationsMailles(Base):
"""
Table des observations par maille
"""
__table__ = Table(
"vm_observations_mailles",
metadata,
Column("id_observation", Integer, primary_key=True, unique=True),
Column("id_maille", Integer),
Column("the_geom", Geometry),
Column("geojson_maille", Text),
Column("annee", String(1000)),
schema="atlas",
autoload=True,
autoload_with=engine,
)
|
gpl-3.0
|
spncrlkt/gillard
|
gillard/invalid_usage.py
|
437
|
from flask import jsonify
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
|
gpl-3.0
|
osadchyi-s/pdf-forms
|
App/Facades/MetaBoxesFacade.php
|
2893
|
<?php
namespace PdfFormsLoader\Facades;
use PdfFormsLoader\Core\Views;
class MetaBoxesFacade
{
protected $slug;
protected $fields;
protected $fieldsName = [];
protected $title;
protected $postType;
protected $context;
protected $priority;
protected $args;
public function __construct($params)
{
$this->slug = $params['slug'];
$this->title = $params['title'];
$this->postType = $params['postType'];
$this->context = $params['context'];
$this->priority = $params['priority'];
$this->fields = $params['fields'];
$this->setFieldsNames();
$this->args = $params;
return $this;
}
public static function make($params) {
$box = new MetaBoxesFacade($params);
add_action('add_meta_boxes', [&$box, 'addMetaBox']);
add_action( 'save_post', [&$box, 'metaSave'] );
}
public function addMetaBox() {
add_meta_box(
$this->slug,
$this->title,
[&$this, 'render'],
$this->postType,
$this->context
//, $this->priority
);
}
function metaSave($postId) {
if (empty($_POST['post_type'])) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( $this->postType == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $postId ) )
return;
} else {
if ( !current_user_can( 'edit_post', $postId ) )
return;
}
foreach($this->getFieldsNames() as $name) {
if (isset($_POST[$name])) {
$value = $_POST[$name];
update_post_meta( $postId, $name, $value );
}
}
}
protected function getCurrentValue($slug) {
if (isset($_GET['post'])) {
return get_post_meta($_GET['post'], $slug, true);
}
return '';
}
protected function setFieldsNames() {
foreach($this->fields as $field) {
$this->fieldsName[] = $this->getFieldName($field['name']);
}
}
protected function getFieldName($name) {
return $this->slug . '_' . $name;
}
protected function getFieldsNames() {
return $this->fieldsName;
}
public function render() {
$fields = [];
foreach($this->fields as $field) {
$uiType = 'PdfFormsLoader\\Core\Ui\\' . ucfirst($field['type']);
$field['name'] = $this->getFieldName($field['name']);
$field['value'] = $this->getCurrentValue($field['name']);
$ui = new $uiType($field);
$fields[] = $ui->output();
}
echo Views::render(
'meta-boxes/box.php',
[
'fields' => $fields,
]
);;
}
}
|
gpl-3.0
|
lyrachord/FX3DAndroid
|
src/main/java/org/fxyz/shapes/primitives/CuboidMesh.java
|
14855
|
/*
* Copyright (C) 2013-2015 F(X)yz,
* Sean Phillips, Jason Pollastrini and Jose Pereda
* 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/>.
*/
package org.fxyz.shapes.primitives;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java8.util.stream.*;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.scene.DepthTest;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.transform.Affine;
import javafx.scene.transform.NonInvertibleTransformException;
import javafx.scene.transform.Transform;
import javafx.scene.transform.Translate;
import org.fxyz.geometry.Face3;
import org.fxyz.geometry.Point3D;
import org.fxyz.utils.FloatCollector;
import static java8.util.stream.StreamSupport.*;
import java8.lang.Iterables;
import java8.util.stream.*;
/**
*
* @author José Pereda Llamas
* Created on 22-dic-2014 - 21:51:51
*/
public class CuboidMesh extends TexturedMesh {
private final static double DEFAULT_WIDTH = 10;
private final static double DEFAULT_HEIGHT = 10;
private final static double DEFAULT_DEPTH = 10;
private final static int DEFAULT_LEVEL = 1;
private final static Point3D DEFAULT_CENTER = new Point3D(0f,0f,0f);
public CuboidMesh(){
this(DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_DEPTH, DEFAULT_LEVEL,null);
}
public CuboidMesh(double width, double height, double depth){
this(width, height, depth, DEFAULT_LEVEL, null);
}
public CuboidMesh(double width, double height, double depth, int level, Point3D center){
setWidth(width);
setHeight(height);
setDepth(depth);
setLevel(level);
setCenter(center);
updateMesh();
setCullFace(CullFace.BACK);
setDrawMode(DrawMode.FILL);
setDepthTest(DepthTest.ENABLE);
}
private final DoubleProperty width = new SimpleDoubleProperty(DEFAULT_WIDTH){
@Override
protected void invalidated() {
if(mesh!=null){
updateMesh();
}
}
};
public double getWidth() {
return width.get();
}
public final void setWidth(double value) {
width.set(value);
}
public DoubleProperty widthProperty() {
return width;
}
private final DoubleProperty height = new SimpleDoubleProperty(DEFAULT_HEIGHT){
@Override
protected void invalidated() {
if(mesh!=null){
updateMesh();
}
}
};
public double getHeight() {
return height.get();
}
public final void setHeight(double value) {
height.set(value);
}
public DoubleProperty heightProperty() {
return height;
}
private final DoubleProperty depth = new SimpleDoubleProperty(DEFAULT_DEPTH){
@Override
protected void invalidated() {
if(mesh!=null){
updateMesh();
}
}
};
public double getDepth() {
return depth.get();
}
public final void setDepth(double value) {
depth.set(value);
}
public DoubleProperty depthProperty() {
return depth;
}
private final IntegerProperty level = new SimpleIntegerProperty(DEFAULT_LEVEL){
@Override
protected void invalidated() {
if(mesh!=null){
updateMesh();
}
}
};
public final int getLevel() {
return level.get();
}
public final void setLevel(int value) {
level.set(value);
}
public final IntegerProperty levelProperty() {
return level;
}
private final ObjectProperty<Point3D> center = new SimpleObjectProperty<Point3D>(DEFAULT_CENTER){
@Override
protected void invalidated() {
if(mesh!=null){
updateMesh();
}
}
};
public Point3D getCenter() {
return center.get();
}
public final void setCenter(Point3D value) {
center.set(value);
}
public ObjectProperty<Point3D> centerProperty() {
return center;
}
@Override
protected final void updateMesh() {
setMesh(null);
mesh=createCube((float)getWidth(), (float)getHeight(), (float)getDepth(), getLevel());
setMesh(mesh);
}
private int numVertices, numTexCoords, numFaces;
private float[] points0, texCoord0;
private int[] faces0;
private List<Point2D> texCoord1;
private Transform a = new Affine();
private TriangleMesh createCube(float width, float height, float depth,
int level){
TriangleMesh m0=null;
if(level>0){
m0= createCube(width, height, depth, level-1);
}
if(level==0){
a = new Affine();
float L=2f*width+2f*depth;
float H=height+2f*depth;
float hw=width/2f, hh=height/2f, hd=depth/2f;
if(center.get()!=null){
a=a.createConcatenation(new Translate(center.get().x,center.get().y,center.get().z));
// hw+=center.get().x;
// hh+=center.get().y;
// hd+=center.get().z;
}
final float[] baseVertices = new float[]{
hw, hh, hd, hw, hh, -hd,
hw, -hh, hd, hw, -hh, -hd,
-hw, hh, hd, -hw, hh, -hd,
-hw, -hh, hd, -hw, -hh, -hd
};
final float[] baseTexCoords = new float[]{
depth/L, 0f, (depth+width)/L, 0f,
0f, depth/H, depth/L, depth/H,
(depth+width)/L, depth/H, (2f*depth+width)/L,
depth/H, 1f, depth/H, 0f, (depth+height)/H,
depth/L, (depth+height)/H, (depth+width)/L, (depth+height)/H,
(2f*depth+width)/L, (depth+height)/H, 1f, (depth+height)/H,
depth/L, 1f, ( depth+width)/L, 1f
};
final int[] baseTexture = new int[]{
8,3,7, 3,2,7,
9,10,4, 4,10,5,
8,12,9, 9,12,13,
3,4,0, 0,4,1,
8,9,3, 3,9,4,
11,6,10, 10,6,5
};
final List<Integer> baseFaces = Arrays.asList(
0,2,1, 2,3,1,
4,5,6, 6,5,7,
0,1,4, 4,1,5,
2,6,3, 3,6,7,
0,4,2, 2,4,6,
1,3,5, 5,3,7
);
for(int i=0; i<baseVertices.length/3; i++){
Point3D ta = transform(baseVertices[3*i],baseVertices[3*i+1],baseVertices[3*i+2]);
baseVertices[3*i]=ta.x;
baseVertices[3*i+1]=ta.y;
baseVertices[3*i+2]=ta.z;
}
points0 = baseVertices;
numVertices=baseVertices.length/3;
texCoord0 = baseTexCoords;
numTexCoords=baseTexCoords.length/2;
faces0 = IntStreams.range(0, baseFaces.size()/3)
.mapToObj(i->IntStreams.of(baseFaces.get(3*i), baseTexture[3*i],
baseFaces.get(3*i+1), baseTexture[3*i+1],
baseFaces.get(3*i+2), baseTexture[3*i+2]))
.flatMapToInt(i->i).toArray();
numFaces=baseFaces.size()/3;
} else if(m0!=null) {
points0=new float[numVertices*m0.getPointElementSize()];
m0.getPoints().toArray(points0);
}
List<Point3D> points1 = IntStreams.range(0, numVertices)
.mapToObj(i -> new Point3D(points0[3*i], points0[3*i+1], points0[3*i+2]))
.collect(Collectors.toList());
if(level>0 && m0!=null){
texCoord0=new float[numTexCoords*m0.getTexCoordElementSize()];
m0.getTexCoords().toArray(texCoord0);
}
texCoord1 = IntStreams.range(0, numTexCoords)
.mapToObj(i -> new Point2D(texCoord0[2*i], texCoord0[2*i+1]))
.collect(Collectors.toList());
if(level>0 && m0!=null){
faces0=new int[numFaces*m0.getFaceElementSize()];
m0.getFaces().toArray(faces0);
}
List<Face3> faces1 = IntStreams.range(0, numFaces)
.mapToObj(i -> new Face3(faces0[6*i], faces0[6*i+2], faces0[6*i+4]))
.collect(Collectors.toList());
index.set(points1.size());
map.clear();
listVertices.clear();
listFaces.clear();
listVertices.addAll(points1);
Iterables.forEach(faces1, face->{
int v1=face.p0;
int v2=face.p1;
int v3=face.p2;
if(level>0){
int a = getMiddle(v1,points1.get(v1),v2,points1.get(v2));
int b = getMiddle(v2,points1.get(v2),v3,points1.get(v3));
int c = getMiddle(v3,points1.get(v3),v1,points1.get(v1));
listFaces.add(new Face3(v1,a,c));
listFaces.add(new Face3(v2,b,a));
listFaces.add(new Face3(v3,c,b));
listFaces.add(new Face3(a,b,c));
} else {
listFaces.add(new Face3(v1,v2,v3));
}
});
map.clear();
numVertices=listVertices.size();
numFaces=listFaces.size();
List<Face3> textures1;
if(level==0){
textures1= IntStreams.range(0, faces0.length/6)
.mapToObj(i -> new Face3(faces0[6*i+1], faces0[6*i+3], faces0[6*i+5]))
.collect(Collectors.toList());
} else {
textures1 = stream(listTextures).map(t->t).collect(Collectors.toList());
}
index.set(texCoord1.size());
listTextures.clear();
Iterables.forEach(textures1, face->{
int v1=face.p0;
int v2=face.p1;
int v3=face.p2;
if(level>0){
int a = getMiddle(v1,texCoord1.get(v1),v2,texCoord1.get(v2));
int b = getMiddle(v2,texCoord1.get(v2),v3,texCoord1.get(v3));
int c = getMiddle(v3,texCoord1.get(v3),v1,texCoord1.get(v1));
listTextures.add(new Face3(v1,a,c));
listTextures.add(new Face3(v2,b,a));
listTextures.add(new Face3(v3,c,b));
listTextures.add(new Face3(a,b,c));
} else {
listTextures.add(new Face3(v1,v2,v3));
}
});
map.clear();
texCoord0=stream(texCoord1).flatMapToDouble(p->DoubleStreams.of(p.getX(),p.getY()))
.collect(()->new FloatCollector(texCoord1.size()*2), FloatCollector::add, FloatCollector::join).toArray();
numTexCoords=texCoord0.length/2;
textureCoords=texCoord0;
if(level==getLevel()){
areaMesh.setWidth(2f*width+2f*depth);
areaMesh.setHeight(height+2f*depth);
// 1<<j -> bitset, 00100. Otherwise: 000111 will mean they are shared
smoothingGroups=IntStreams.range(0,listFaces.size()).map(i->1<<(i/(listFaces.size()/6))).toArray();
// smoothing groups based on 3DViewer -> same result
// float[] normals=new float[]{1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1};
// int[] newFaces = IntStream.range(0, listFaces.size())
// .mapToObj(i->IntStream.of((int)listFaces.get(i).x, (int)listFaces.get(i).x,
// (int)listFaces.get(i).y, (int)listFaces.get(i).y,
// (int)listFaces.get(i).z, (int)listFaces.get(i).z))
// .flatMapToInt(i->i).toArray();
// int[] newFaceNormals = IntStream.range(0,listFaces.size()).mapToObj(i->{
// int j=(i/(listFaces.size()/6));
// return IntStream.of(j,j,j);
// }).flatMapToInt(i->i).toArray();
// smoothingGroups=SmoothingGroups.calcSmoothGroups(new TriangleMesh(), newFaces, newFaceNormals, normals);
}
return createMesh();
}
private Point3D transform(Point3D p){
javafx.geometry.Point3D ta = a.transform(p.x,p.y,p.z);
return new Point3D((float)ta.getX(), (float)ta.getY(), (float)ta.getZ());
}
private Point3D transform(double x, double y, double z){
javafx.geometry.Point3D ta = a.transform(x,y,z);
return new Point3D((float)ta.getX(), (float)ta.getY(), (float)ta.getZ());
}
public Point3D unTransform(Point3D p){
try {
javafx.geometry.Point3D ta = a.inverseTransform(p.x,p.y,p.z);
return new Point3D((float)ta.getX(), (float)ta.getY(), (float)ta.getZ());
} catch (NonInvertibleTransformException ex) {
System.out.println("p not invertible "+p);
}
return p;
}
private final AtomicInteger index = new AtomicInteger();
private final HashMap<String, Integer> map = new HashMap<>();
private int getMiddle(int v1, Point3D p1, int v2, Point3D p2){
String key = ""+Math.min(v1,v2)+"_"+Math.max(v1,v2);
if(map.get(key)!=null){
return map.get(key);
}
listVertices.add(p1.add(p2).multiply(0.5f));
map.put(key,index.get());
return index.getAndIncrement();
}
private int getMiddle(int v1, Point2D p1, int v2, Point2D p2){
String key = ""+Math.min(v1,v2)+"_"+Math.max(v1,v2);
if(map.get(key)!=null){
return map.get(key);
}
texCoord1.add(p1.add(p2).multiply(0.5f));
map.put(key,index.get());
return index.getAndIncrement();
}
}
|
gpl-3.0
|
CWHISME/CryStoryEditor
|
CryStoryEditor/Assets/CryStoryEditor/System/Runtime/Attributes/ValueFuncAttribute.cs
|
400
|
/**********************************************************
*Author: wangjiaying
*Date: 2016.7.20
*Func:
**********************************************************/
namespace CryStory.Runtime
{
public class ValueFuncAttribute : System.Attribute
{
public VarType _varType;
public ValueFuncAttribute(VarType type)
{
_varType = type;
}
}
}
|
gpl-3.0
|
chunter1/precipitationSensorESP32
|
StateManager.cpp
|
3661
|
#include "StateManager.h"
#include "WiFi.h"
StateManager::StateManager() {
m_roolOverIsPossible = false;
m_uptimeDays = 0;
}
void StateManager::Begin(String version, String identity) {
m_version = version;
m_identity = identity;
}
void StateManager::SetLoopStart() {
m_loopStartTime = micros();
}
void StateManager::SetLoopEnd() {
m_loopCount++;
uint32_t currentLoopTime = micros() - m_loopStartTime;
m_loopTotalTime += currentLoopTime;
if (currentLoopTime < m_loopMinTime) {
m_loopMinTime = currentLoopTime;
}
if (currentLoopTime > m_loopMaxTime) {
m_loopMaxTime = currentLoopTime;
}
if (millis() < m_loopMeasureStart) {
m_loopMeasureStart = 0;
}
if (millis() > m_loopMeasureStart + 5000) {
word loopAverage = m_loopTotalTime / m_loopCount;
m_loopDurationMin = m_loopMinTime;
m_loopDurationAvg = loopAverage;
m_loopDurationMax = m_loopMaxTime;
m_loopTotalTime = 0;
m_loopCount = 0;
m_loopMinTime = 64000;
m_loopMaxTime = 0;
m_loopMeasureStart = millis();
}
}
void StateManager::SetHostname(String hostname){
m_hostname = hostname;
}
String StateManager::GetHostname(){
return m_hostname;
}
void StateManager::Handle(){
unsigned long currentMillis = millis();
// Handle 50 Days rollover for UpTime
if(currentMillis >= 3000000000) {
m_roolOverIsPossible = true;
}
if(currentMillis <= 100000 && m_roolOverIsPossible) {
m_uptimeDays += 50;
m_roolOverIsPossible = false;
}
}
String StateManager::GetVersion() {
return m_version;
}
String StateManager::GetUpTime() {
Update();
return m_values.Get("UpTimeText","");
}
void StateManager::Update() {
m_values.Clear();
unsigned long upTimeSeconds = millis() / 1000;
String upTimeText(m_uptimeDays + upTimeSeconds / 86400);
upTimeText += "Tg. ";
upTimeText += String(upTimeSeconds / 3600 % 24);
upTimeText += "Std. ";
upTimeText += String((upTimeSeconds / 60) % 60);
upTimeText += "Min. ";
upTimeText += String(upTimeSeconds % 60);
upTimeText += "Sek. ";
m_values.Put("UpTimeSeconds", String(upTimeSeconds));
m_values.Put("UpTimeText", upTimeText);
m_values.Put("WIFI", WiFi.SSID());
m_values.Put("MacAddress", WiFi.macAddress());
m_values.Put("RSSI", WiFi.getMode() == WiFiMode_t::WIFI_OFF ? "Off" : String(WiFi.RSSI()));
m_values.Put("FreeHeap", String(ESP.getFreeHeap()));
m_values.Put("Version", GetVersion());
m_values.Put("LD.Min (ms)", String((float)m_loopDurationMin / 1000.0));
m_values.Put("LD.Avg (ms)", String((float)m_loopDurationAvg / 1000.0));
m_values.Put("LD.Max (ms)", String((float)m_loopDurationMax / 1000.0));
}
String StateManager::GetHTML() {
Update();
String result = "<style>table{border:1px solid black;border-collapse:collapse;}tr,td{padding:4px;border:1px solid; Margin:5px}</style>";
result += "<table>";
for (uint i = 0; i < m_values.Size(); i++) {
result += "<tr><td>";
result += m_values.GetKeyAt(i);
result += ": </td><td>";
result += m_values.GetValueAt(i);
result += "</td></tr>";
}
return result;
}
String StateManager::GetXML() {
Update();
String result = "";
result += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
result += "<LGW>";
for (uint i = 0; i < m_values.Size(); i++) {
result += "<Info Key = \"";
result += m_values.GetKeyAt(i);
result += "\" Value=\"";
result += m_values.GetValueAt(i);
result += "\"/>";
}
result += "</LGW>";
return result;
}
void StateManager::SetWiFiConnectTime(float connectTime) {
m_wifiConnnectTime = connectTime;
}
float StateManager::GetWiFiConnectTime() {
return m_wifiConnnectTime;
}
|
gpl-3.0
|
dineshkummarc/KChange
|
Docs/html/search/functions_6d.js
|
1977
|
var searchData=
[
['main',['Main',['../class_k_change_logger_1_1_program.html#abf4d299b9a86819ede3d42a52fbb8b80',1,'KChangeLogger::Program']]],
['mainform',['MainForm',['../class_k_change_logger_1_1_main_form.html#ae03a0c6d5e6d196049bbe80a4683851f',1,'KChangeLogger::MainForm']]],
['mainformprojects',['MainFormProjects',['../class_k_change_logger_1_1_main_form_projects.html#a60393e7a098488fc5afc21b3bf18fe95',1,'KChangeLogger::MainFormProjects']]],
['mainformprojectsinfo',['MainFormProjectsInfo',['../class_k_change_logger_1_1_main_form_projects_info.html#afe03368c50d7367c577f1a570dd90458',1,'KChangeLogger::MainFormProjectsInfo']]],
['mainformprojectsnew',['MainFormProjectsNew',['../class_k_change_logger_1_1_main_form_projects_new.html#ab63a9401c86765eba5146fdea96c6d44',1,'KChangeLogger::MainFormProjectsNew']]],
['maintenancebutton_5fclick',['MaintenanceButton_Click',['../class_k_change_logger_1_1_main_form.html#a842fa58f0f8477873c60626f5031f4f1',1,'KChangeLogger::MainForm']]],
['maintenanceform',['MaintenanceForm',['../class_k_change_logger_1_1_maintenance_form.html#ad80b31312ae708b37004cf51d0a13832',1,'KChangeLogger::MaintenanceForm']]],
['maintenanceformchanges',['MaintenanceFormChanges',['../class_k_change_logger_1_1_maintenance_form_changes.html#adab7830626c31ee9be5b487465dc5e83',1,'KChangeLogger::MaintenanceFormChanges']]],
['maintenanceformchangesdetail',['MaintenanceFormChangesDetail',['../class_k_change_logger_1_1_maintenance_form_changes_detail.html#a5dbfdd536c9d75f317a455861abc5836',1,'KChangeLogger::MaintenanceFormChangesDetail']]],
['maintenanceformfiles',['MaintenanceFormFiles',['../class_k_change_logger_1_1_maintenance_form_files.html#a30eefd8152421a4fb6169f6dec4b1072',1,'KChangeLogger::MaintenanceFormFiles']]],
['maintenanceformfilesadd',['MaintenanceFormFilesAdd',['../class_k_change_logger_1_1_maintenance_form_files_add.html#aa2f9c50a4728d39e5e0ff7eb74676752',1,'KChangeLogger::MaintenanceFormFilesAdd']]]
];
|
gpl-3.0
|
ZeroOne71/ql
|
02_ECCentral/03_Service/BizEntity/PO/Vendor/VendorModifyRequestInfo.cs
|
4674
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace ECCentral.BizEntity.PO
{
/// <summary>
/// 供应商修改请求信息
/// </summary>
[Serializable]
[DataContract]
public class VendorModifyRequestInfo
{
/// <summary>
/// 系统编号
/// </summary>
[DataMember]
public int? SysNo { get; set; }
/// <summary>
/// 修改请求系统编号
/// </summary>
[DataMember]
public int? RequestSysNo { get; set; }
/// <summary>
/// 供应商等级
/// </summary>
[DataMember]
public VendorRank? Rank { get; set; }
/// <summary>
/// 供应商系统编号
/// </summary>
[DataMember]
public int VendorSysNo { get; set; }
/// <summary>
/// 供应商名称
/// </summary>
[DataMember]
public string VendorName { get; set; }
/// <summary>
/// 供应商账期信息
/// </summary>
[DataMember]
public VendorPayTermsItemInfo PayPeriodType { get; set; }
/// <summary>
/// 生效日期
/// </summary>
[DataMember]
public DateTime? ValidDate { get; set; }
/// <summary>
/// 过期日期
/// </summary>
[DataMember]
public DateTime? ExpiredDate { get; set; }
/// <summary>
/// 合同金额
/// </summary>
[DataMember]
public decimal? ContractAmt { get; set; }
/// <summary>
/// 修改请求状态
/// </summary>
[DataMember]
public VendorModifyRequestStatus? Status { get; set; }
/// <summary>
/// 创建人系统编号
/// </summary>
[DataMember]
public int? CreateUserSysNo { get; set; }
/// <summary>
/// 公司编号
/// </summary>
[DataMember]
public string CompanyCode { get; set; }
/// <summary>
/// 语言编码
/// </summary>
[DataMember]
public string LanguageCode { get; set; }
/// <summary>
/// 货币系统编号
/// </summary>
[DataMember]
public int? CurrencySysNo { get; set; }
/// <summary>
/// 供应商修改请求类型
/// </summary>
[DataMember]
public VendorModifyRequestType? RequestType { get; set; }
/// <summary>
/// 代理级别
/// </summary>
[DataMember]
public string AgentLevel { get; set; }
/// <summary>
/// 生产商系统编号
/// </summary>
[DataMember]
public int? ManufacturerSysNo { get; set; }
/// <summary>
/// 2级分类系统编号
/// </summary>
[DataMember]
public int? C2SysNo { get; set; }
/// <summary>
/// 3级分类系统编号
/// </summary>
[DataMember]
public int? C3SysNo { get; set; }
/// <summary>
/// 供应商结算类型
/// </summary>
[DataMember]
public SettleType? SettleType { get; set; }
/// <summary>
/// 供应商财务结算方式
/// </summary>
[DataMember]
public VendorSettlePeriodType? SettlePeriodType { get; set; }
/// <summary>
/// 佣金百分比
/// </summary>
[DataMember]
public decimal? SettlePercentage { get; set; }
/// <summary>
/// 送货周期
/// </summary>
[DataMember]
public string SendPeriod { get; set; }
/// <summary>
/// 品牌系统编号
/// </summary>
[DataMember]
public int? BrandSysNo { get; set; }
/// <summary>
/// 请求操作类型
/// </summary>
[DataMember]
public VendorModifyActionType? ActionType { get; set; }
/// <summary>
/// 供应商代理系统编号
/// </summary>
[DataMember]
public int? VendorManufacturerSysNo { get; set; }
/// <summary>
/// 操作内容
/// </summary>
[DataMember]
public string Content { get; set; }
/// <summary>
/// 备注(财务信息审核不通过理由)
/// </summary>
[DataMember]
public string Memo { get; set; }
/// <summary>
/// 下单日期
/// </summary>
[DataMember]
public string BuyWeekDay { get; set; }
/// <summary>
/// 自动审核
/// </summary>
[DataMember]
public bool? AutoAudit { get; set; }
}
}
|
gpl-3.0
|
Foo-Manroot/CAL
|
src/networking/NetUtils.java
|
2460
|
/*
* CAL.
* A P2P chat program that lets you communicate without any infrastructure.
*
* Copyright (C) 2015 Foo-Manroot
*
* 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 networking;
import common.Common;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
/**
* This class has some methods to ease some tasks as getting the network
* interfaces address.
*/
public class NetUtils {
/**
* Gets the addresses of all the active interfaces.
*
* @return
* A list with all the addresses of the active interfaces.
*/
public static ArrayList<InetAddress> getInterfaces() {
ArrayList<InetAddress> addresses = new ArrayList<>();
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
/* Adds the wildcard addresses -> 0.0.0.0 and 0:0:0:0:0:0:0:0 */
addresses.add(new InetSocketAddress(0).getAddress());
addresses.add(InetAddress.getByName("::"));
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
/* The inactive interfaces are omitted */
if (!iface.isUp()) {
continue;
}
for (InterfaceAddress addr : iface.getInterfaceAddresses()) {
addresses.add(addr.getAddress());
}
}
} catch (SocketException | UnknownHostException ex) {
Common.logger.logError("Exception at Common.getInterfaces(): " + ex.getMessage());
}
return addresses;
}
}
|
gpl-3.0
|
pichalite/NodeBB
|
public/src/modules/notifications.js
|
5131
|
'use strict';
define('notifications', ['sounds', 'translator', 'components', 'navigator', 'benchpress'], function (sounds, translator, components, navigator, Benchpress) {
var Notifications = {};
var unreadNotifs = {};
Notifications.prepareDOM = function () {
var notifContainer = components.get('notifications');
var notifTrigger = notifContainer.children('a');
var notifList = components.get('notifications/list');
notifTrigger.on('click', function (e) {
e.preventDefault();
if (notifContainer.hasClass('open')) {
return;
}
Notifications.loadNotifications(notifList);
});
notifList.on('click', '[data-nid]', function (ev) {
var notifEl = $(this);
if (scrollToPostIndexIfOnPage(notifEl)) {
ev.stopPropagation();
ev.preventDefault();
notifTrigger.dropdown('toggle');
}
var unread = notifEl.hasClass('unread');
if (!unread) {
return;
}
var nid = notifEl.attr('data-nid');
socket.emit('notifications.markRead', nid, function (err) {
if (err) {
return app.alertError(err.message);
}
if (unreadNotifs[nid]) {
delete unreadNotifs[nid];
}
});
});
notifContainer.on('click', '.mark-all-read', Notifications.markAllRead);
notifList.on('click', '.mark-read', function () {
var liEl = $(this).parent();
var unread = liEl.hasClass('unread');
var nid = liEl.attr('data-nid');
socket.emit('notifications.mark' + (unread ? 'Read' : 'Unread'), nid, function (err) {
if (err) {
return app.alertError(err.message);
}
liEl.toggleClass('unread');
if (unread && unreadNotifs[nid]) {
delete unreadNotifs[nid];
}
});
return false;
});
socket.on('event:new_notification', function (notifData) {
// If a path is defined, show notif data, otherwise show generic data
var payload = {
alert_id: 'new_notif',
title: '[[notifications:new_notification]]',
timeout: 2000,
};
if (notifData.path) {
payload.message = notifData.bodyShort;
payload.type = 'info';
payload.clickfn = function () {
if (notifData.path.startsWith('http') && notifData.path.startsWith('https')) {
window.location.href = notifData.path;
} else {
window.location.href = window.location.protocol + '//' + window.location.host + config.relative_path + notifData.path;
}
};
} else {
payload.message = '[[notifications:you_have_unread_notifications]]';
payload.type = 'warning';
}
app.alert(payload);
app.refreshTitle();
if (ajaxify.currentPage === 'notifications') {
ajaxify.refresh();
}
socket.emit('notifications.getCount', function (err, count) {
if (err) {
return app.alertError(err.message);
}
Notifications.updateNotifCount(count);
});
if (!unreadNotifs[notifData.nid]) {
sounds.play('notification', notifData.nid);
unreadNotifs[notifData.nid] = true;
}
});
socket.on('event:notifications.updateCount', function (count) {
Notifications.updateNotifCount(count);
});
};
function scrollToPostIndexIfOnPage(notifEl) {
// Scroll to index if already in topic (gh#5873)
var pid = notifEl.attr('data-pid');
var tid = notifEl.attr('data-tid');
var path = notifEl.attr('data-path');
var postEl = components.get('post', 'pid', pid);
if (path.startsWith(config.relative_path + '/post/') && pid && postEl.length && ajaxify.data.template.topic && parseInt(ajaxify.data.tid, 10) === parseInt(tid, 10)) {
navigator.scrollToIndex(postEl.attr('data-index'), true);
return true;
}
return false;
}
Notifications.loadNotifications = function (notifList) {
socket.emit('notifications.get', null, function (err, data) {
if (err) {
return app.alertError(err.message);
}
var notifs = data.unread.concat(data.read).sort(function (a, b) {
return parseInt(a.datetime, 10) > parseInt(b.datetime, 10) ? -1 : 1;
});
translator.toggleTimeagoShorthand(function () {
for (var i = 0; i < notifs.length; i += 1) {
notifs[i].timeago = $.timeago(new Date(parseInt(notifs[i].datetime, 10)));
}
translator.toggleTimeagoShorthand();
Benchpress.parse('partials/notifications_list', { notifications: notifs }, function (html) {
notifList.translateHtml(html);
});
});
});
};
Notifications.updateNotifCount = function (count) {
var notifIcon = components.get('notifications/icon');
count = Math.max(0, count);
if (count > 0) {
notifIcon.removeClass('fa-bell-o').addClass('fa-bell');
} else {
notifIcon.removeClass('fa-bell').addClass('fa-bell-o');
}
notifIcon.toggleClass('unread-count', count > 0);
notifIcon.attr('data-content', count > 99 ? '99+' : count);
var payload = {
count: count,
updateFavicon: true,
};
$(window).trigger('action:notification.updateCount', payload);
if (payload.updateFavicon) {
Tinycon.setBubble(count > 99 ? '99+' : count);
}
};
Notifications.markAllRead = function () {
socket.emit('notifications.markAllRead', function (err) {
if (err) {
app.alertError(err.message);
}
unreadNotifs = {};
});
};
return Notifications;
});
|
gpl-3.0
|
RadioCanut/site-radiocanut
|
ecrire/lang/public_ja.php
|
4180
|
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/public?lang_cible=ja
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// A
'accueil_site' => 'ホーム', # MODIF
'articles' => '記事',
'articles_auteur' => 'この記事の著者',
'articles_populaires' => '最も読まれている記事',
'articles_rubrique' => 'このセクションの記事',
'aucun_article' => 'このアドレスに記事はありません',
'aucun_auteur' => 'このアドレスに著者はいません',
'aucun_site' => 'このアドレスにサイトはありません',
'aucune_breve' => 'このアドレスにニュースはありません',
'aucune_rubrique' => 'このアドレスにセクションはありません',
'autres_breves' => '他のニュース',
'autres_groupes_mots_clefs' => 'キーワードの他のグループ',
'autres_sites' => '他のサイト',
// B
'bonjour' => 'おはようございます',
// C
'commenter_site' => 'このサイトについてコメントして下さい',
// D
'date' => '日付',
'dernier_ajout' => '最新の追加',
'dernieres_breves' => '最新のニュース',
'derniers_articles' => '最新の記事',
'derniers_commentaires' => '最新のコメント',
'derniers_messages_forum' => 'フォーラムで投稿された最新のメッセージ',
// E
'edition_mode_texte' => 'テキストモードonly',
'en_reponse' => 'Replying to:',
'en_resume' => 'まとめ',
'envoyer_message' => 'メッセージを送る',
'espace_prive' => 'プライベートエリア',
// H
'hierarchie_site' => 'サイトの階層',
// J
'jours' => '日付け',
// M
'meme_auteur' => '同じ著者によって',
'meme_rubrique' => '同じセクションの中で',
'memes_auteurs' => '同じ著者によって',
'message' => 'メッセージ',
'messages_forum' => 'フォーラムメッセージ', # MODIF
'messages_recents' => '最も新しいフォーラムのメッセージ',
'mots_clefs' => 'キーワード',
'mots_clefs_meme_groupe' => '同じグループのキーワード',
// N
'navigation' => 'ナビゲーション',
'nom' => '名前',
'nouveautes' => '新しいもの',
'nouveautes_web' => 'Webの中で新しいもの',
'nouveaux_articles' => '新しい記事',
'nouvelles_breves' => '新しいニュース',
// P
'page_precedente' => '前のページ',
'page_suivante' => '次のページ',
'par_auteur' => 'によって ',
'participer_site' => 'あなたはこのウェブサイトで活動することによって、登録後、あなたの記事を書くことが出来ます。それからあなたはすぐに、サイトのプライベートエリアへのアクセスコードを、emailによって得られるでしょう。',
'plan_site' => 'サイトマップ',
'popularite' => 'ポピュラー',
'poster_message' => 'メッセージを投稿',
'proposer_site' => 'あなたはこのセクションに追加するサイトを提案することが出来ます:',
// R
'repondre_article' => 'この記事に返信',
'repondre_breve' => 'このニュースに返信',
'resultats_recherche' => '検索結果',
'retour_debut_forums' => 'フォーラムの最初のページに戻る',
'rubrique' => 'セクション',
'rubriques' => 'セクション',
// S
'signatures_petition' => '署名',
'site_realise_avec_spip' => 'SPIPによってサイトは作られました',
'sites_web' => 'ウェブサイト',
'sous_rubriques' => 'サブセクション',
'suite' => '次の',
'sur_web' => 'ウェブ上',
'syndiquer_rubrique' => 'このセクションを供給する',
'syndiquer_site' => 'サイト全体を供給する',
// T
'texte_lettre_information' => 'サイトのニュースレターはここ',
'texte_lettre_information_2' => 'この手紙は、以来公表された記事とニュースをまとめてあります。', # MODIF
// V
'ver_imprimer' => 'バージョン表記',
'voir_en_ligne' => 'オンラインを見る',
'voir_squelette' => '???????????????' # MODIF
);
|
gpl-3.0
|
NeuroStat/Python-scripts
|
python_scripts_day1/unique_labels.py
|
19
|
np.unique(labels)
|
gpl-3.0
|
felixsch/trollolo
|
lib/version.rb
|
42
|
module Trollolo
VERSION = "0.0.7"
end
|
gpl-3.0
|
Bundeswahlrechner/Bundeswahlrechner
|
mandatsverteilung/src/test/java/edu/kit/iti/formal/mandatsverteilung/wahlberechnung/Bundeswahlgesetz2013ZuteilungsverfahrenTest.java
|
2389
|
package edu.kit.iti.formal.mandatsverteilung.wahlberechnung;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl;
import edu.kit.iti.formal.mandatsverteilung.importer.TestDatenBereitsteller;
@RunWith(value = Parameterized.class)
public class Bundeswahlgesetz2013ZuteilungsverfahrenTest {
@Parameters(name = "Verfahren: {0}")
public static Iterable<Object[]> verfahren() {
Object[][] verfahren = new Object[][] {
{ new SainteLagueHoechstzahl() },
{ new SainteLagueRangmasszahl() },
{ new SainteLagueIterativ() }, { new DHondt() },
{ new HareNiemeyer() } };
return Arrays.asList(verfahren);
}
/** Die {@link Bundestagswahl} auf der die Berechnung ausgeführt wird. */
private Bundestagswahl bt;
@Rule
public ExpectedException thrown = ExpectedException.none();
/** Das getestete {@link Wahlverfahren}. */
private Bundeswahlgesetz2013 verfahren;
/** Das für den Test verwendete {@link Zuteilungsverfahren}. */
private Zuteilungsverfahren zt;
public Bundeswahlgesetz2013ZuteilungsverfahrenTest(Zuteilungsverfahren zt) {
this.zt = zt;
}
@Before
public void setUp() throws Exception {
bt = TestDatenBereitsteller.getStandardBTW();
verfahren = new Bundeswahlgesetz2013(bt, zt);
BundeswahlgesetzSperrklauselpruefer spk = new BundeswahlgesetzSperrklauselpruefer();
spk.setGesamteZweitstimmenzahl(bt.berechneZweitstimmen());
verfahren.setzeSperrklauselpruefer(spk);
}
@After
public void tearDown() throws Exception {
bt = null;
verfahren = null;
zt = null;
}
/**
* Prüft die Berechnungsperformance mit verschiedenen Zuteilungsverfahren.
*/
@Test(timeout = 500)
public void testeBerechnungsperformance() {
if (zt instanceof HareNiemeyer) {
thrown.expect(IllegalArgumentException.class);
// Test mit HareNiemeyer - das Alamaba-Paradoxon verhindert hier
// eine Wahlberechnung.
verfahren.berechneWahlergebnis();
} else {
// Zuteilungsverfahren, mit dem sich die Daten berechnen lassen.
verfahren.berechneWahlergebnis();
assertTrue(true);
}
}
}
|
gpl-3.0
|
ff36/jnoc
|
src/main/java/co/ff36/jnoc/service/ticket/EditTicket.java
|
4801
|
/**
* Copyright (C) 2015 555 inc ltd.
*
* 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 co.ff36.jnoc.service.ticket;
import co.ff36.jnoc.app.misc.JsfUtil;
import co.ff36.jnoc.per.dap.CrudService;
import co.ff36.jnoc.per.entity.Comment;
import co.ff36.jnoc.per.entity.Ticket;
import co.ff36.jnoc.service.navigation.Navigator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
/**
* Edit Ticket CDI bean. Permits Users to edit support tickets.
*
*
* @version 2.0.0
* @since Build 2.0-SNAPSHOT (Aug 21, 2013)
* @author Tarka L'Herpiniere
*/
@Named
@ViewScoped
public class EditTicket implements Serializable {
//<editor-fold defaultstate="collapsed" desc="Properties">
private static final Logger LOG = Logger.getLogger(EditTicket.class.getName());
private static final long serialVersionUID = 1L;
private Ticket ticket;
private final String viewParamTicketID;
private boolean renderEditor;
private boolean render;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Constructors">
public EditTicket() {
this.renderEditor = true;
this.ticket = new Ticket();
this.viewParamTicketID = JsfUtil.getRequestParameter("ticket");
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="EJB">
@EJB
private CrudService dap;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="CDI">
@Inject
private Navigator navigator;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Getters">
/**
* Get the value of ticket.
*
* @return the value of ticket
*/
public Ticket getTicket() {
return ticket;
}
/**
* Get the value of render.
*
* @return the value of render
*/
public boolean isRender() {
return render;
}
/**
* Get the value of renderEditor.
*
* @return the value of renderEditor
*/
public boolean isRenderEditor() {
return renderEditor;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Setters">
/**
* Set the value of ticket.
*
* @param ticket new value of ticket
*/
public void setTicket(Ticket ticket) {
this.ticket = ticket;
}
/**
* Set the value of renderEditor.
*
* @param renderEditor new value of renderEditor
*/
public void setRenderEditor(boolean renderEditor) {
this.renderEditor = renderEditor;
}
//</editor-fold>
/**
* Initialize the page by loading the specified ticket from the persistence
* layer.
*/
public void init() {
try {
// Get the ticket from the persistence layer
ticket = (Ticket) dap.find(Ticket.class, Long.valueOf(viewParamTicketID));
ticket.setComment(new Comment());
// Redirect if the user is not allowed access to the ticket
if (!ticket.initEditor()) {
navigator.navigate("LIST_TICKETS");
}
ticket.setCcEmailRecipients(new ArrayList<String>());
ticket.setComment(new Comment());
} catch (NullPointerException | NumberFormatException e) {
// The ticket was not found in the persistence
navigator.navigate("LIST_TICKETS");
}
render = true;
}
/**
* Inverts the state of renderEditor
*/
public void changeEditor() {
if (renderEditor) {
//renderEditor = false;
} else {
this.ticket.setComment(new Comment());
renderEditor = true;
}
}
/**
* When a push notification comes in we want to update the ticket but without
* loosing what the administrator was working on.
*/
public void updateComments() {
Ticket newTicket = (Ticket) dap.find(Ticket.class, Long.valueOf(viewParamTicketID));
newTicket.setComment(ticket.getComment());
ticket = newTicket;
}
}
|
gpl-3.0
|
mathhobbit/EditCalculateAndChart
|
src/org/ioblako/edit/Redo_Action.java
|
2482
|
/*
* Copyright (C) 2019 Sergey Nikitin
*
* 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.ioblako.edit;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.undo.UndoManager;
import javax.swing.undo.CannotRedoException;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
public class Redo_Action extends AbstractAction {
public static final long serialVersionUID=1L;
private TextEdit TEdit;
private UndoManager undo;
public Redo_Action(TextEdit ed, String text, ImageIcon icon,
String desc) {
super(text, icon);
TEdit = ed;
undo=ed.getUndoManager();
setEnabled(false);
putValue(SHORT_DESCRIPTION, desc);
// putValue(MNEMONIC_KEY, KeyEvent.VK_CUT);
}
public Redo_Action(TextEdit ed) {
super("Redo");
TEdit = ed;
undo=ed.getUndoManager();
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undo.redo();
} catch (CannotRedoException ex) {
TEdit.showDialog("Unable to redo: " + ex.getMessage());
//ex.printStackTrace();
}
updateState();
}
protected void updateState() {
if (undo.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undo.getRedoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
if (undo.canUndo()) {
TEdit.setEnabled("Undo",true);
TEdit.putValue("Undo",undo.getUndoPresentationName());
} else {
TEdit.setEnabled("Undo",false);
TEdit.putValue("Undo","Undo");
}
}
}
|
gpl-3.0
|
Co0sh/BetonQuest
|
src/main/java/org/betonquest/betonquest/variables/PlayerNameVariable.java
|
865
|
package org.betonquest.betonquest.variables;
import org.betonquest.betonquest.Instruction;
import org.betonquest.betonquest.api.Variable;
import org.betonquest.betonquest.utils.PlayerConverter;
import org.bukkit.entity.Player;
/**
* This variable resolves into the player's name. It can has optional "display"
* argument, which will resolve it to the display name.
*/
@SuppressWarnings("PMD.CommentRequired")
public class PlayerNameVariable extends Variable {
private final boolean display;
public PlayerNameVariable(final Instruction instruction) {
super(instruction);
display = instruction.hasArgument("display");
}
@Override
public String getValue(final String playerID) {
final Player player = PlayerConverter.getPlayer(playerID);
return display ? player.getDisplayName() : player.getName();
}
}
|
gpl-3.0
|
cachapa/AerialDream
|
app/src/main/java/com/codingbuffalo/aerialdream/VideoProgressBar.java
|
1254
|
package com.codingbuffalo.aerialdream;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.MediaController;
public class VideoProgressBar extends View {
private static final int COLOR = 0x66FFFFFF;
private MediaController.MediaPlayerControl controller;
private Paint paint;
public VideoProgressBar(Context context) {
this(context, null);
}
public VideoProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(COLOR);
}
public void setController(MediaController.MediaPlayerControl controller) {
this.controller = controller;
postInvalidate();
}
@Override
protected synchronized void onDraw(Canvas canvas) {
if (controller == null || isInEditMode()) {
return;
}
float progress = controller.getCurrentPosition() / (float) controller.getDuration();
float x = progress * getWidth();
canvas.drawRect(0, 0, x, getHeight(), paint);
postInvalidate();
}
}
|
gpl-3.0
|
cea-sec/ivre
|
ivre/tools/flowcli.py
|
16049
|
#! /usr/bin/env python
# This file is part of IVRE.
# Copyright 2011 - 2021 Pierre LALET <pierre@droids-corp.org>
#
# IVRE 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.
#
# IVRE 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 IVRE. If not, see <http://www.gnu.org/licenses/>.
"""
Access and query the flows database.
See doc/FLOW.md for more information.
"""
from argparse import ArgumentParser
import datetime
import os
import sys
from typing import Dict, Tuple
try:
import matplotlib # type: ignore
import matplotlib.pyplot as plt # type: ignore
except ImportError:
plt = None
from ivre.db import db
from ivre import utils, config
import ivre.flow
addr_fields = {
"src": {"type": "edges", "field": "src.addr"},
"dst": {"type": "edges", "field": "dst.addr"},
"host": {"type": "nodes", "field": "addr"},
}
def get_addr_argument(field: str, value: str) -> Tuple[str, str]:
addr_field = addr_fields[field]
# Detect CIDR
op = "="
if "/" in value:
op = "=~"
return (addr_field["type"], "%s %s %s" % (addr_field["field"], op, value))
def print_fields() -> None:
equals = "=" * 7
title = "General"
sys.stdout.write("{0} {1:^10} {0}\n".format(equals, title))
sys.stdout.writelines(
("%-12s: %s\n" % (field, ivre.flow.FIELDS[field]) for field in ivre.flow.FIELDS)
)
for meta in ivre.flow.META_DESC:
sys.stdout.write("{0} {1:^10} {0}\n".format(equals, meta))
sys.stdout.writelines(
(
"meta.%s.%s (list)\n" % (meta, name)
for name in ivre.flow.META_DESC[meta]["keys"]
)
)
sys.stdout.writelines(
(
"meta.%s.%s\n" % (meta, name)
for name in ivre.flow.META_DESC[meta].get("counters", [])
)
)
def main() -> None:
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"--init",
"--purgedb",
action="store_true",
help="Purge or create and initialize the database.",
)
parser.add_argument(
"--ensure-indexes",
action="store_true",
help="Create missing indexes (will lock the " "database).",
)
parser.add_argument(
"--node-filters",
"-n",
nargs="+",
metavar="FILTER",
help="Filter the results with a list of ivre specific "
"node textual filters (see WebUI doc in FLOW.md).",
)
parser.add_argument(
"--flow-filters",
"-f",
nargs="+",
metavar="FILTER",
help="Filter the results with a list of ivre specific "
"flow textual filters (see WebUI doc in FLOW.md).",
)
parser.add_argument(
"--json",
"-j",
action="store_true",
help="Outputs the full json records of results.",
)
parser.add_argument(
"--count",
"-c",
action="store_true",
help="Only return the count of the results.",
)
parser.add_argument(
"--limit", "-l", type=int, default=None, help="Output at most LIMIT results."
)
parser.add_argument("--skip", type=int, default=0, help="Skip first SKIP results.")
parser.add_argument(
"--orderby", "-o", help='Order of results ("src", "dst" or "flow")'
)
parser.add_argument("--separator", "-s", help="Separator string.")
parser.add_argument(
"--top",
"-t",
nargs="+",
help="Top flows for a given set of fields, e.g. " '"--top src.addr dport".',
)
parser.add_argument(
"--collect",
"-C",
nargs="+",
help="When using --top, also collect these " "properties.",
default=[],
)
parser.add_argument(
"--sum",
"-S",
nargs="+",
help="When using --top, sum on these properties to " "order the result.",
default=[],
)
parser.add_argument(
"--least",
"-L",
action="store_true",
help="When using --top, sort records by least",
)
parser.add_argument(
"--mode", "-m", help="Query special mode (flow_map, talk_map...)"
)
parser.add_argument(
"--timeline",
"-T",
action="store_true",
help="Retrieves the timeline of each flow",
)
parser.add_argument(
"--flow-daily",
action="store_true",
help="Flow count per times of the day. If --precision "
"is absent, it will be based on FLOW_TIME_PRECISION "
"(%d)" % config.FLOW_TIME_PRECISION,
)
parser.add_argument(
"--plot",
action="store_true",
help="Plot data when possible (requires matplotlib).",
)
parser.add_argument(
"--fields",
nargs="*",
help="Without values, gives the list of available "
"fields. Otherwise, display these fields for each "
"entry.",
)
parser.add_argument(
"--reduce-precision",
type=int,
metavar="NEW_PRECISION",
help="Only with MongoDB backend. "
"Reduce precision to NEW_PRECISION for flows "
"timeslots. Uses precision, before, after and "
"filters.",
)
parser.add_argument(
"--after",
"-a",
type=str,
help="Only with MongoDB "
"backend. Get only flows seen after this date. "
"Date format: YEAR-MONTH-DAY HOUR:MINUTE. "
"Based on timeslots precision. If the given date is "
"in the middle of a timeslot, flows start at the next "
"timeslot.",
)
parser.add_argument(
"--before",
"-b",
type=str,
help="Only with MongoDB "
"backend. Get only flows seen before this date. "
"Date format: YEAR-MONTH-DAY HOUR:MINUTE. "
"Based on timeslots precision. If the given date is "
"in the middle of a timeslot, the whole period is "
"kept even if theoretically some flows may have been "
"seen after the given date.",
)
parser.add_argument(
"--precision",
nargs="?",
default=None,
const=0,
help="Only With MongoDB backend. If PRECISION is "
"specified, get only flows with one timeslot of "
"the given precision. Otherwise, list "
"precisions.",
type=int,
)
parser.add_argument(
"--host",
type=str,
metavar="HOST",
help="Filter on " "source OR destination IP. Accepts IP address or " "CIDR.",
)
parser.add_argument(
"--src",
type=str,
metavar="SRC",
help="Filter on " "source IP. Accepts IP address or CIDR.",
)
parser.add_argument(
"--dst",
type=str,
metavar="DST",
help="Filter on " "destination IP. Accepts IP address or CIDR.",
)
parser.add_argument(
"--proto", type=str, metavar="PROTO", help="Filter on " "transport protocol."
)
parser.add_argument("--tcp", action="store_true", help="Alias to " "--proto tcp")
parser.add_argument("--udp", action="store_true", help="Alias to " "--proto udp")
parser.add_argument("--port", type=int, metavar="PORT", help="Alias to " "--dport")
parser.add_argument(
"--dport", type=int, metavar="DPORT", help="Filter on " "destination port."
)
parser.add_argument(
"--sport", type=int, metavar="SPORT", help="Filter on " "source port."
)
args = parser.parse_args()
out = sys.stdout
if args.plot and plt is None:
utils.LOGGER.critical("Matplotlib is required for --plot")
sys.exit(-1)
if args.init:
if os.isatty(sys.stdin.fileno()):
out.write(
"This will remove any flow result in your database. " "Process ? [y/N] "
)
ans = input()
if ans.lower() != "y":
sys.exit(-1)
db.flow.init()
sys.exit(0)
if args.ensure_indexes:
if os.isatty(sys.stdin.fileno()):
out.write("This will lock your database. " "Process ? [y/N] ")
ans = input()
if ans.lower() != "y":
sys.exit(-1)
db.flow.ensure_indexes()
sys.exit(0)
if args.fields is not None and not args.fields:
# Print fields list
print_fields()
sys.exit(0)
elif args.fields is not None:
# Validate given fields
for field in args.fields:
ivre.flow.validate_field(field)
if args.precision == 0:
# Get precisions list
out.writelines("%d\n" % precision for precision in db.flow.list_precisions())
sys.exit(0)
filters = {"nodes": args.node_filters or [], "edges": args.flow_filters or []}
args_dict = vars(args)
for key in addr_fields:
if args_dict[key] is not None:
flt_t, flt_v = get_addr_argument(key, args_dict[key])
filters[flt_t].append(flt_v)
if args.proto is not None:
filters["edges"].append("proto = %s" % args.proto)
for key in ["tcp", "udp"]:
if args_dict[key]:
filters["edges"].append("proto = %s" % key)
for key in ["port", "dport"]:
if args_dict[key] is not None:
filters["edges"].append("dport = %d" % args_dict[key])
if args.sport is not None:
filters["edges"].append("ANY sports = %d" % args.sport)
time_args = ["before", "after"]
time_values = {}
for arg in time_args:
time_values[arg] = (
datetime.datetime.strptime(args_dict[arg], "%Y-%m-%d %H:%M")
if args_dict[arg] is not None
else None
)
query = db.flow.from_filters(
filters,
limit=args.limit,
skip=args.skip,
orderby=args.orderby,
mode=args.mode,
timeline=args.timeline,
after=time_values["after"],
before=time_values["before"],
precision=args.precision,
)
if args.reduce_precision:
if os.isatty(sys.stdin.fileno()):
out.write(
"This will permanently reduce the precision of your "
"database. Process ? [y/N] "
)
ans = input()
if ans.lower() != "y":
sys.exit(-1)
new_precision = args.reduce_precision
db.flow.reduce_precision(
new_precision,
flt=query,
before=time_values["before"],
after=time_values["after"],
current_precision=args.precision,
)
sys.exit(0)
sep = args.separator or " | "
coma = " ;" if args.separator else " ; "
coma2 = "," if args.separator else ", "
if args.count:
count = db.flow.count(query)
out.write(
"%(clients)d clients\n%(servers)d servers\n" "%(flows)d flows\n" % count
)
elif args.top:
top = db.flow.topvalues(
query,
args.top,
collect_fields=args.collect,
sum_fields=args.sum,
topnbr=args.limit,
skip=args.skip,
least=args.least,
)
for rec in top:
sys.stdout.write(
"%s%s%s%s%s\n"
% (
"(" + coma2.join(str(val) for val in rec["fields"]) + ")",
sep,
rec["count"],
sep,
coma.join(
str("(" + coma2.join(str(val) for val in collected) + ")")
for collected in rec["collected"]
)
if rec["collected"]
else "",
)
)
elif args.flow_daily:
precision = (
args.precision if args.precision is not None else config.FLOW_TIME_PRECISION
)
plot_data: Dict[str, Dict[datetime.datetime, int]] = {}
for rec in db.flow.flow_daily(
precision, query, after=time_values["after"], before=time_values["before"]
):
out.write(
sep.join(
[
rec["time_in_day"].strftime("%T.%f"),
" ; ".join(
["(" + x[0] + ", " + str(x[1]) + ")" for x in rec["flows"]]
),
]
)
)
out.write("\n")
if args.plot:
for flw in rec["flows"]:
t = rec["time_in_day"]
# pyplot needs datetime objects
dt = datetime.datetime(
1970, 1, 1, hour=t.hour, minute=t.minute, second=t.second
)
plot_data.setdefault(flw[0], {})
plot_data[flw[0]][dt] = flw[1]
if args.plot and plot_data:
t = datetime.datetime(1970, 1, 1, 0, 0, 0)
t += datetime.timedelta(seconds=config.FLOW_TIME_BASE % precision)
times = []
while t < datetime.datetime(1970, 1, 2):
times.append(t)
t = t + datetime.timedelta(seconds=precision)
ax = plt.subplots()[1]
fmt = matplotlib.dates.DateFormatter("%H:%M:%S")
for flow, data in plot_data.items():
values = [(data[ti] if ti in data else 0) for ti in times]
plt.step(times, values, ".-", where="post", label=flow)
plt.legend(loc="best")
ax.xaxis.set_major_formatter(fmt)
plt.gcf().autofmt_xdate()
plt.show()
else:
fmt = "%%s%s%%s%s%%s" % (sep, sep)
node_width = len("XXXX:XXXX:XXXX:XXXX:XXXX:XXXX")
flow_width = len("tcp/XXXXX")
for res in db.flow.to_iter(
query,
limit=args.limit,
skip=args.skip,
orderby=args.orderby,
mode=args.mode,
timeline=args.timeline,
):
if args.json:
out.write("%s\n" % res)
else:
elts = {}
for elt in ["src", "flow", "dst"]:
elts[elt] = res[elt]["label"]
if args.fields:
elts[elt] = "%s%s%s" % (
elts[elt],
coma,
coma.join(
str(res[elt]["data"].get(field, ""))
for field in args.fields
),
)
src, flow, dst = elts["src"], elts["flow"], elts["dst"]
node_width = max(node_width, len(src), len(dst))
flow_width = max(flow_width, len(flow))
if not args.separator:
fmt = "%%-%ds%s%%-%ds%s%%-%ds" % (
node_width,
sep,
flow_width,
sep,
node_width,
)
out.write(fmt % (src, flow, dst))
if args.timeline:
out.write(sep)
# Print '?' instead of failing if meta.times does not exist
try:
out.write(
coma.join(
str(elt)
for elt in sorted(res["flow"]["data"]["meta"]["times"])
)
)
except KeyError:
out.write("?")
out.write("\n")
|
gpl-3.0
|
printempw/blessing-skin-server
|
resources/views/setup/updates/master.blade.php
|
651
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex,nofollow" />
<title>{{ trans('setup.updates.master.title') }}</title>
<link rel="shortcut icon" href="../resources/assets/dist/images/favicon.ico">
<link rel="stylesheet" type="text/css" href="../resources/assets/dist/css/install.css">
</head>
<body class="container">
<p id="logo"><a href="https://github.com/printempw/blessing-skin-server" tabindex="-1">Blessing Skin Server</a></p>
@yield('content')
</body>
</html>
|
gpl-3.0
|
MIT-Niceti/core-war-web
|
cpp/virtualMachine/Corewar-VM.cpp
|
753
|
// Corewar-VM.cpp�: d�finit le point d'entr�e pour l'application console.
//
#include "stdafx.h"
#include "Arena.h"
std::string startMachine(std::vector<std::string> &champions)
{
Arena *arena = new Arena();
std::vector<std::string> championss;
/* std::cout << "BEGIN LOAD" << std::endl;
championss.push_back("C:\\Users\\norman_e\\Pictures\\reference_champion.out");
championss.push_back("C:\\Users\\norman_e\\Pictures\\forker.out");*/
for (std::vector<std::string>::iterator it = champions.begin(); it != champions.end(); it++)
std::cout << "Path champion: " << *it << std::endl;
std::cout << "DONE LOAD" << std::endl;
if (arena->setupArena(champions))
return (arena->start());
std::cout << "DONE GAME" << std::endl;
return "";
}
|
gpl-3.0
|
bnetcc/darkstar
|
scripts/globals/spells/diaga_iv.lua
|
2163
|
-----------------------------------------
-- Spell: Diaga IV
-- Lowers an enemy's defense and gradually deals light elemental damage.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- calculate raw damage
local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 3;
local dmg = calculateMagicDamage(basedmg,5,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false);
dmg = utils.clamp(dmg, 1, 120);
-- get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0);
-- get the resisted damage
dmg = dmg*resist;
-- add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
-- add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
-- add in final adjustments including the actual damage dealt
local final = finalMagicAdjustments(caster,target,spell,dmg);
-- Calculate duration and bonus
local duration = 150;
local dotBonus = caster:getMod(MOD_DIA_DOT); -- Dia Wand
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
caster:delStatusEffect(EFFECT_SABOTEUR);
end
-- Check for Bio.
bio = target:getStatusEffect(EFFECT_BIO);
-- Do it!
if (bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 4) or (DIA_OVERWRITE == 1 and bio:getPower() < 4)) then
target:addStatusEffect(EFFECT_DIA,4+dotBonus,3,duration,FLAG_ERASABLE,20);
spell:setMsg(msgBasic.MAGIC_DMG);
else
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
end
-- Try to kill same tier Bio
if (BIO_OVERWRITE == 1 and bio ~= nil) then
if (bio:getPower() <= 4) then
target:delStatusEffect(EFFECT_BIO);
end
end
return final;
end;
|
gpl-3.0
|
license-wp/license-wp
|
src/File.php
|
599
|
<?php
namespace Never5\LicenseWP;
class File {
/** @var String */
private $file;
public function __construct( $file ) {
$this->file = $file;
}
/**
* Return plugin file
*
* @return String
*/
public function plugin_file() {
return $this->file;
}
/**
* Return plugin path
*
* @return string
*/
public function plugin_path() {
return untrailingslashit( plugin_dir_path( $this->file ) );
}
/**
* Return plugin url
*
* @param string $path
*
* @return string
*/
public function plugin_url( $path = '' ) {
return plugins_url( $path, $this->file );
}
}
|
gpl-3.0
|
TeamDeltaQuadrant/fine-uploader
|
lib/grunt/tasks/tests.js
|
1215
|
/* jshint node: true */
var spawn = require("child_process").spawn;
module.exports = function(grunt) {
"use strict";
grunt.registerMultiTask("tests", "** Use ` grunt-test` instead **", function() {
return startKarma.call(this, this.data, this.async());
});
function startKarma(config, done) {
var args, autoWatch, browsers, p, port, reporters, singleRun;
browsers = grunt.option("browsers");
reporters = grunt.option("reporters");
port = grunt.option("port");
autoWatch = grunt.option("autoWatch");
singleRun = grunt.option("singleRun");
args = ["node_modules/karma/bin/karma", "start", config, singleRun ? "--single-run" : "", autoWatch ? "--auto-watch" : "", reporters ? "--reporters=" + reporters : "", browsers ? "--browsers=" + browsers : "", port ? "--port=" + port : ""];
console.log(args);
p = spawn("node", args);
p.stdout.pipe(process.stdout);
p.stderr.pipe(process.stderr);
return p.on("exit", function(code) {
if (code !== 0) {
grunt.fail.warn("Karma test(s) failed. Exit code: " + code);
}
return done();
});
}
};
|
gpl-3.0
|
Foorgol/QTournament
|
Court.cpp
|
3577
|
/*
* This is QTournament, a badminton tournament management program.
* Copyright (C) 2014 - 2019 Volker Knollmann
*
* 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
* 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/>.
*/
#include <stdexcept>
#include "Court.h"
#include "TournamentDataDefs.h"
#include "TournamentDB.h"
#include "TournamentErrorCodes.h"
#include "HelperFunc.h"
#include "CourtMngr.h"
#include "MatchMngr.h"
namespace QTournament
{
Court::Court(const TournamentDB& _db, int& rowId)
:TournamentDatabaseObject(_db, TabCourt, rowId)
{
}
//----------------------------------------------------------------------------
Court::Court(const TournamentDB& _db, const SqliteOverlay::TabRow& _row)
:TournamentDatabaseObject(_db, _row)
{
}
//----------------------------------------------------------------------------
QString Court::getName(int maxLen) const
{
auto _result = row.getString2(GenericNameFieldName);
if (!_result) return QString(); // empty name field
QString result = stdString2QString(*_result);
if ((maxLen > 0) && (result.length() > maxLen))
{
result = result.left(maxLen);
}
return result;
}
//----------------------------------------------------------------------------
Error Court::rename(const QString &newName)
{
CourtMngr cm{db};
return cm.renameCourt(*this, newName);
}
//----------------------------------------------------------------------------
int Court::getNumber() const
{
return row.getInt(CO_Number);
}
//----------------------------------------------------------------------------
bool Court::isManualAssignmentOnly() const
{
return (row.getInt(CO_IsManualAssignment) == 1);
}
//----------------------------------------------------------------------------
void Court::setManualAssignment(bool isManual)
{
row.update(CO_IsManualAssignment, isManual ? 1 : 0);
}
//----------------------------------------------------------------------------
std::optional<Match> Court::getMatch() const
{
MatchMngr mm{db};
return mm.getMatchForCourt(*this);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
}
|
gpl-3.0
|
Staartvin/Statz
|
src/me/staartvin/statz/listeners/BlocksBrokenListener.java
|
1493
|
package me.staartvin.statz.listeners;
import me.staartvin.statz.Statz;
import me.staartvin.statz.datamanager.player.PlayerStat;
import me.staartvin.statz.datamanager.player.specification.BlocksBrokenSpecification;
import me.staartvin.statz.datamanager.player.specification.PlayerStatSpecification;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class BlocksBrokenListener implements Listener {
private final Statz plugin;
public BlocksBrokenListener(final Statz plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBreak(final BlockBreakEvent event) {
final PlayerStat stat = PlayerStat.BLOCKS_BROKEN;
// Get player
final Player player = event.getPlayer();
// Do general check
if (!plugin.doGeneralCheck(player, stat))
return;
Block blockBroken = event.getBlock();
final String worldName = blockBroken.getWorld().getName();
PlayerStatSpecification specification = new BlocksBrokenSpecification(player.getUniqueId(), 1,
worldName, blockBroken.getType());
// Update value to new stat.
plugin.getDataManager().setPlayerInfo(player.getUniqueId(), stat, specification.constructQuery());
}
}
|
gpl-3.0
|
Ed-von-Schleck/dml
|
src/main.py
|
2134
|
# -*- coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import sys
import os, os.path
from collections import namedtuple
from tempfile import NamedTemporaryFile
import io
from src.dmlexceptions import DMLError
from src.broadcast import broadcast
from src.lex import DmlLex
from sinks import * # so that they register themselves
import src.registry
class NullDevice():
"Dummy output device if option '-q' is selected"
def write(self, dummy_out):
pass
MySink = namedtuple("MySink", "meta send tmpfile")
Metadata = namedtuple("Metadata", "filepath name filename working_dir")
def main(dml_file, options):
filepath, filename = os.path.split(dml_file)
name, ext = os.path.splitext(os.path.basename(dml_file))
del ext
metadata = Metadata(filepath, name, filename, os.getcwd())
if not options.verbose:
sys.stdout = NullDevice()
# This won't win a beauty contest, but seems robust.
mysinks = []
for sinkname, sink in src.registry.sinks.items():
if options.__dict__[sinkname]:
tmpfile = NamedTemporaryFile(mode="w", delete=False)
cor = sink.coroutine(metadata, tmpfile)
cor.next()
mysinks.append(MySink(sink, cor.send, tmpfile))
broadcaster = broadcast(metadata, mysinks)
broadcaster.next()
try:
dml = io.open(dml_file, "rU", encoding="utf-8")
print(b"opening", dml_file, b"...")
lexer = DmlLex(dml, filename=dml_file)
lexer.run(broadcaster, metadata)
except IOError:
pass
except DMLError as dml_error:
import linecache
print (b"*" * 80)
print(b"A", dml_error.error_name, b"was encountered:")
print(dml_error)
print(b"\tfile: ", lexer.filename)
print(b"\tline: ", lexer.lineno)
print(b"\tcolumn:", lexer.pos)
print(linecache.getline(lexer.filename, lexer.lineno), end="")
print(b" " * (lexer.pos - 1) + b"^")
print (b"*" * 80)
sys.exit(1)
finally:
dml.close()
print(b"closed", dml_file)
|
gpl-3.0
|
pizza2004/OpenRCT2
|
src/openrct2-ui/windows/ShortcutKeys.cpp
|
16781
|
/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#include "Window.h"
#include <openrct2-ui/input/KeyboardShortcuts.h>
#include <openrct2-ui/interface/Widget.h>
#include <openrct2/config/Config.h>
#include <openrct2/drawing/Drawing.h>
#include <openrct2/localisation/Localisation.h>
static constexpr const rct_string_id WINDOW_TITLE = STR_SHORTCUTS_TITLE;
static constexpr const int32_t WW = 420;
static constexpr const int32_t WH = 280;
static constexpr const int32_t WW_SC_MAX = 1200;
static constexpr const int32_t WH_SC_MAX = 800;
// clang-format off
enum WINDOW_SHORTCUT_WIDGET_IDX {
WIDX_BACKGROUND,
WIDX_TITLE,
WIDX_CLOSE,
WIDX_SCROLL,
WIDX_RESET
};
// 0x9DE48C
static rct_widget window_shortcut_widgets[] = {
WINDOW_SHIM(WINDOW_TITLE, WW, WH),
MakeWidget({4, 18}, {412, 245}, WWT_SCROLL, 0, SCROLL_VERTICAL, STR_SHORTCUT_LIST_TIP ),
MakeWidget({4, WH-15}, {150, 12}, WWT_BUTTON, 0, STR_SHORTCUT_ACTION_RESET, STR_SHORTCUT_ACTION_RESET_TIP),
{ WIDGETS_END }
};
static void window_shortcut_mouseup(rct_window *w, rct_widgetindex widgetIndex);
static void window_shortcut_resize(rct_window *w);
static void window_shortcut_invalidate(rct_window *w);
static void window_shortcut_paint(rct_window *w, rct_drawpixelinfo *dpi);
static void window_shortcut_scrollgetsize(rct_window *w, int32_t scrollIndex, int32_t *width, int32_t *height);
static void window_shortcut_scrollmousedown(rct_window *w, int32_t scrollIndex, const ScreenCoordsXY& screenCoords);
static void window_shortcut_scrollmouseover(rct_window *w, int32_t scrollIndex, const ScreenCoordsXY& screenCoords);
static void window_shortcut_scrollpaint(rct_window *w, rct_drawpixelinfo *dpi, int32_t scrollIndex);
static rct_window_event_list window_shortcut_events = {
nullptr,
window_shortcut_mouseup,
window_shortcut_resize,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
window_shortcut_scrollgetsize,
window_shortcut_scrollmousedown,
nullptr,
window_shortcut_scrollmouseover,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
window_shortcut_invalidate,
window_shortcut_paint,
window_shortcut_scrollpaint
};
struct ShortcutStringPair
{
KeyboardShortcut ShortcutId;
rct_string_id StringId;
};
static const ShortcutStringPair ShortcutList[] =
{
{ SHORTCUT_CLOSE_TOP_MOST_WINDOW, STR_SHORTCUT_CLOSE_TOP_MOST_WINDOW },
{ SHORTCUT_CLOSE_ALL_FLOATING_WINDOWS, STR_SHORTCUT_CLOSE_ALL_FLOATING_WINDOWS },
{ SHORTCUT_CANCEL_CONSTRUCTION_MODE, STR_SHORTCUT_CANCEL_CONSTRUCTION_MODE },
{ SHORTCUT_REMOVE_TOP_BOTTOM_TOOLBAR_TOGGLE, STR_SHORTCUT_TOGGLE_VISIBILITY_OF_TOOLBARS },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_PAUSE_GAME, STR_SHORTCUT_PAUSE_GAME },
{ SHORTCUT_REDUCE_GAME_SPEED, STR_SHORTCUT_REDUCE_GAME_SPEED },
{ SHORTCUT_INCREASE_GAME_SPEED, STR_SHORTCUT_INCREASE_GAME_SPEED },
{ SHORTCUT_LOAD_GAME, STR_LOAD_GAME },
{ SHORTCUT_QUICK_SAVE_GAME, STR_SHORTCUT_QUICK_SAVE_GAME },
{ SHORTCUT_SHOW_OPTIONS, STR_SHORTCUT_SHOW_OPTIONS },
{ SHORTCUT_SCREENSHOT, STR_SHORTCUT_SCREENSHOT },
{ SHORTCUT_MUTE_SOUND, STR_SHORTCUT_MUTE_SOUND },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_OPEN_CHEAT_WINDOW, STR_SHORTCUT_OPEN_CHEATS_WINDOW },
{ SHORTCUT_TOGGLE_CLEARANCE_CHECKS, STR_SHORTCUT_TOGGLE_CLEARANCE_CHECKS },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_ZOOM_VIEW_OUT, STR_SHORTCUT_ZOOM_VIEW_OUT },
{ SHORTCUT_ZOOM_VIEW_IN, STR_SHORTCUT_ZOOM_VIEW_IN },
{ SHORTCUT_ROTATE_VIEW_CLOCKWISE, STR_SHORTCUT_ROTATE_VIEW_CLOCKWISE },
{ SHORTCUT_ROTATE_VIEW_ANTICLOCKWISE, STR_SHORTCUT_ROTATE_VIEW_ANTICLOCKWISE },
{ SHORTCUT_SHOW_MAP, STR_SHORTCUT_SHOW_MAP },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_CLEAR_SCENERY, STR_SHORTCUT_CLEAR_SCENERY },
{ SHORTCUT_ADJUST_LAND, STR_SHORTCUT_ADJUST_LAND },
{ SHORTCUT_ADJUST_WATER, STR_SHORTCUT_ADJUST_WATER },
{ SHORTCUT_BUILD_SCENERY, STR_SHORTCUT_BUILD_SCENERY },
{ SHORTCUT_BUILD_PATHS, STR_SHORTCUT_BUILD_PATHS },
{ SHORTCUT_BUILD_NEW_RIDE, STR_SHORTCUT_BUILD_NEW_RIDE },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_SHOW_FINANCIAL_INFORMATION, STR_SHORTCUT_SHOW_FINANCIAL_INFORMATION },
{ SHORTCUT_SHOW_RESEARCH_INFORMATION, STR_SHORTCUT_SHOW_RESEARCH_INFORMATION },
{ SHORTCUT_SHOW_RIDES_LIST, STR_SHORTCUT_SHOW_RIDES_LIST },
{ SHORTCUT_SHOW_PARK_INFORMATION, STR_SHORTCUT_SHOW_PARK_INFORMATION },
{ SHORTCUT_SHOW_GUEST_LIST, STR_SHORTCUT_SHOW_GUEST_LIST },
{ SHORTCUT_SHOW_STAFF_LIST, STR_SHORTCUT_SHOW_STAFF_LIST },
{ SHORTCUT_SHOW_RECENT_MESSAGES, STR_SHORTCUT_SHOW_RECENT_MESSAGES },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_SHOW_MULTIPLAYER, STR_SHORTCUT_SHOW_MULTIPLAYER },
{ SHORTCUT_OPEN_CHAT_WINDOW, STR_SEND_MESSAGE },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_UNDERGROUND_VIEW_TOGGLE, STR_SHORTCUT_UNDERGROUND_VIEW_TOGGLE },
{ SHORTCUT_REMOVE_BASE_LAND_TOGGLE, STR_SHORTCUT_REMOVE_BASE_LAND_TOGGLE },
{ SHORTCUT_REMOVE_VERTICAL_LAND_TOGGLE, STR_SHORTCUT_REMOVE_VERTICAL_LAND_TOGGLE },
{ SHORTCUT_SEE_THROUGH_RIDES_TOGGLE, STR_SHORTCUT_SEE_THROUGH_RIDES_TOGGLE },
{ SHORTCUT_SEE_THROUGH_SCENERY_TOGGLE, STR_SHORTCUT_SEE_THROUGH_SCENERY_TOGGLE },
{ SHORTCUT_SEE_THROUGH_PATHS_TOGGLE, STR_SHORTCUT_SEE_THROUGH_PATHS_TOGGLE },
{ SHORTCUT_INVISIBLE_SUPPORTS_TOGGLE, STR_SHORTCUT_INVISIBLE_SUPPORTS_TOGGLE },
{ SHORTCUT_INVISIBLE_PEOPLE_TOGGLE, STR_SHORTCUT_INVISIBLE_PEOPLE_TOGGLE },
{ SHORTCUT_HEIGHT_MARKS_ON_LAND_TOGGLE, STR_SHORTCUT_HEIGHT_MARKS_ON_LAND_TOGGLE },
{ SHORTCUT_HEIGHT_MARKS_ON_RIDE_TRACKS_TOGGLE, STR_SHORTCUT_HEIGHT_MARKS_ON_RIDE_TRACKS_TOGGLE },
{ SHORTCUT_HEIGHT_MARKS_ON_PATHS_TOGGLE, STR_SHORTCUT_HEIGHT_MARKS_ON_PATHS_TOGGLE },
{ SHORTCUT_VIEW_CLIPPING, STR_SHORTCUT_VIEW_CLIPPING },
{ SHORTCUT_HIGHLIGHT_PATH_ISSUES_TOGGLE, STR_SHORTCUT_HIGHLIGHT_PATH_ISSUES_TOGGLE },
{ SHORTCUT_GRIDLINES_DISPLAY_TOGGLE, STR_SHORTCUT_GRIDLINES_DISPLAY_TOGGLE },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_SCENERY_PICKER, STR_SHORTCUT_OPEN_SCENERY_PICKER },
{ SHORTCUT_ROTATE_CONSTRUCTION_OBJECT, STR_SHORTCUT_ROTATE_CONSTRUCTION_OBJECT },
{ SHORTCUT_RIDE_CONSTRUCTION_TURN_LEFT, STR_SHORTCUT_RIDE_CONSTRUCTION_TURN_LEFT },
{ SHORTCUT_RIDE_CONSTRUCTION_TURN_RIGHT, STR_SHORTCUT_RIDE_CONSTRUCTION_TURN_RIGHT },
{ SHORTCUT_RIDE_CONSTRUCTION_USE_TRACK_DEFAULT, STR_SHORTCUT_RIDE_CONSTRUCTION_USE_TRACK_DEFAULT },
{ SHORTCUT_RIDE_CONSTRUCTION_SLOPE_DOWN, STR_SHORTCUT_RIDE_CONSTRUCTION_SLOPE_DOWN },
{ SHORTCUT_RIDE_CONSTRUCTION_SLOPE_UP, STR_SHORTCUT_RIDE_CONSTRUCTION_SLOPE_UP },
{ SHORTCUT_RIDE_CONSTRUCTION_CHAIN_LIFT_TOGGLE, STR_SHORTCUT_RIDE_CONSTRUCTION_CHAIN_LIFT_TOGGLE },
{ SHORTCUT_RIDE_CONSTRUCTION_BANK_LEFT, STR_SHORTCUT_RIDE_CONSTRUCTION_BANK_LEFT },
{ SHORTCUT_RIDE_CONSTRUCTION_BANK_RIGHT, STR_SHORTCUT_RIDE_CONSTRUCTION_BANK_RIGHT },
{ SHORTCUT_RIDE_CONSTRUCTION_PREVIOUS_TRACK, STR_SHORTCUT_RIDE_CONSTRUCTION_PREVIOUS_TRACK },
{ SHORTCUT_RIDE_CONSTRUCTION_NEXT_TRACK, STR_SHORTCUT_RIDE_CONSTRUCTION_NEXT_TRACK },
{ SHORTCUT_RIDE_CONSTRUCTION_BUILD_CURRENT, STR_SHORTCUT_RIDE_CONSTRUCTION_BUILD_CURRENT },
{ SHORTCUT_RIDE_CONSTRUCTION_DEMOLISH_CURRENT, STR_SHORTCUT_RIDE_CONSTRUCTION_DEMOLISH_CURRENT },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_SCROLL_MAP_UP, STR_SHORTCUT_SCROLL_MAP_UP },
{ SHORTCUT_SCROLL_MAP_LEFT, STR_SHORTCUT_SCROLL_MAP_LEFT },
{ SHORTCUT_SCROLL_MAP_DOWN, STR_SHORTCUT_SCROLL_MAP_DOWN },
{ SHORTCUT_SCROLL_MAP_RIGHT, STR_SHORTCUT_SCROLL_MAP_RIGHT },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_WINDOWED_MODE_TOGGLE, STR_SHORTCUT_WINDOWED_MODE_TOGGLE },
{ SHORTCUT_SCALE_UP, STR_SHORTCUT_SCALE_UP },
{ SHORTCUT_SCALE_DOWN, STR_SHORTCUT_SCALE_DOWN },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_TILE_INSPECTOR, STR_SHORTCUT_OPEN_TILE_INSPECTOR },
{ SHORTCUT_INSERT_CORRUPT_ELEMENT, STR_SHORTCUT_INSERT_CORRPUT_ELEMENT },
{ SHORTCUT_COPY_ELEMENT, STR_SHORTCUT_COPY_ELEMENT },
{ SHORTCUT_PASTE_ELEMENT, STR_SHORTCUT_PASTE_ELEMENT },
{ SHORTCUT_REMOVE_ELEMENT, STR_SHORTCUT_REMOVE_ELEMENT },
{ SHORTCUT_MOVE_ELEMENT_UP, STR_SHORTCUT_MOVE_ELEMENT_UP },
{ SHORTCUT_MOVE_ELEMENT_DOWN, STR_SHORTCUT_MOVE_ELEMENT_DOWN },
{ SHORTCUT_INCREASE_X_COORD, STR_SHORTCUT_INCREASE_X_COORD },
{ SHORTCUT_DECREASE_X_COORD, STR_SHORTCUT_DECREASE_X_COORD },
{ SHORTCUT_INCREASE_Y_COORD, STR_SHORTCUT_INCREASE_Y_COORD },
{ SHORTCUT_DECREASE_Y_COORD, STR_SHORTCUT_DECREASE_Y_COORD },
{ SHORTCUT_INCREASE_ELEM_HEIGHT, STR_SHORTCUT_INCREASE_ELEM_HEIGHT },
{ SHORTCUT_DECREASE_ELEM_HEIGHT, STR_SHORTCUT_DECREASE_ELEM_HEIGHT },
{ SHORTCUT_UNDEFINED, STR_NONE },
{ SHORTCUT_ADVANCE_TO_NEXT_TICK, STR_ADVANCE_TO_NEXT_TICK },
{ SHORTCUT_PAINT_ORIGINAL_TOGGLE, STR_SHORTCUT_PAINT_ORIGINAL },
{ SHORTCUT_DEBUG_PAINT_TOGGLE, STR_SHORTCUT_DEBUG_PAINT_TOGGLE },
};
// clang-format on
/**
*
* rct2: 0x006E3884
*/
rct_window* window_shortcut_keys_open()
{
rct_window* w = window_bring_to_front_by_class(WC_KEYBOARD_SHORTCUT_LIST);
if (w == nullptr)
{
w = window_create_auto_pos(WW, WH, &window_shortcut_events, WC_KEYBOARD_SHORTCUT_LIST, WF_RESIZABLE);
w->widgets = window_shortcut_widgets;
w->enabled_widgets = (1 << WIDX_CLOSE) | (1 << WIDX_RESET);
window_init_scroll_widgets(w);
w->no_list_items = static_cast<uint16_t>(std::size(ShortcutList));
w->selected_list_item = -1;
w->min_width = WW;
w->min_height = WH;
w->max_width = WW_SC_MAX;
w->max_height = WH_SC_MAX;
}
return w;
}
/**
*
* rct2: 0x006E39E4
*/
static void window_shortcut_mouseup(rct_window* w, rct_widgetindex widgetIndex)
{
switch (widgetIndex)
{
case WIDX_CLOSE:
window_close(w);
break;
case WIDX_RESET:
keyboard_shortcuts_reset();
keyboard_shortcuts_save();
w->Invalidate();
break;
}
}
static void window_shortcut_resize(rct_window* w)
{
window_set_resize(w, w->min_width, w->min_height, w->max_width, w->max_height);
}
static void window_shortcut_invalidate(rct_window* w)
{
window_shortcut_widgets[WIDX_BACKGROUND].right = w->width - 1;
window_shortcut_widgets[WIDX_BACKGROUND].bottom = w->height - 1;
window_shortcut_widgets[WIDX_TITLE].right = w->width - 2;
window_shortcut_widgets[WIDX_CLOSE].right = w->width - 3;
window_shortcut_widgets[WIDX_CLOSE].left = w->width - 13;
window_shortcut_widgets[WIDX_SCROLL].right = w->width - 5;
window_shortcut_widgets[WIDX_SCROLL].bottom = w->height - 18;
window_shortcut_widgets[WIDX_RESET].top = w->height - 15;
window_shortcut_widgets[WIDX_RESET].bottom = w->height - 4;
}
/**
*
* rct2: 0x006E38E0
*/
static void window_shortcut_paint(rct_window* w, rct_drawpixelinfo* dpi)
{
window_draw_widgets(w, dpi);
}
/**
*
* rct2: 0x006E3A07
*/
static void window_shortcut_scrollgetsize(rct_window* w, int32_t scrollIndex, int32_t* width, int32_t* height)
{
*height = w->no_list_items * SCROLLABLE_ROW_HEIGHT;
}
/**
*
* rct2: 0x006E3A3E
*/
static void window_shortcut_scrollmousedown(rct_window* w, int32_t scrollIndex, const ScreenCoordsXY& screenCoords)
{
int32_t selected_item = (screenCoords.y - 1) / SCROLLABLE_ROW_HEIGHT;
if (selected_item >= w->no_list_items)
return;
// Is this a separator?
if (ShortcutList[selected_item].ShortcutId == SHORTCUT_UNDEFINED)
return;
auto& shortcut = ShortcutList[selected_item];
window_shortcut_change_open(shortcut.ShortcutId, shortcut.StringId);
}
/**
*
* rct2: 0x006E3A16
*/
static void window_shortcut_scrollmouseover(rct_window* w, int32_t scrollIndex, const ScreenCoordsXY& screenCoords)
{
int32_t selected_item = (screenCoords.y - 1) / SCROLLABLE_ROW_HEIGHT;
if (selected_item >= w->no_list_items)
return;
w->selected_list_item = selected_item;
w->Invalidate();
}
/**
*
* rct2: 0x006E38E6
*/
static void window_shortcut_scrollpaint(rct_window* w, rct_drawpixelinfo* dpi, int32_t scrollIndex)
{
auto dpiCoords = ScreenCoordsXY{ dpi->x, dpi->y };
gfx_fill_rect(
dpi, { dpiCoords, dpiCoords + ScreenCoordsXY{ dpi->width - 1, dpi->height - 1 } }, ColourMapA[w->colours[1]].mid_light);
// TODO: the line below is a workaround for what is presumably a bug with dpi->width
// see https://github.com/OpenRCT2/OpenRCT2/issues/11238 for details
const auto scrollWidth = w->width - SCROLLBAR_WIDTH - 10;
for (int32_t i = 0; i < w->no_list_items; ++i)
{
int32_t y = 1 + i * SCROLLABLE_ROW_HEIGHT;
if (y > dpi->y + dpi->height)
{
break;
}
if (y + SCROLLABLE_ROW_HEIGHT < dpi->y)
{
continue;
}
// Is this a separator?
if (ShortcutList[i].ShortcutId == SHORTCUT_UNDEFINED)
{
const int32_t top = y + (SCROLLABLE_ROW_HEIGHT / 2) - 1;
gfx_fill_rect(dpi, { { 0, top }, { scrollWidth, top } }, ColourMapA[w->colours[0]].mid_dark);
gfx_fill_rect(dpi, { { 0, top + 1 }, { scrollWidth, top + 1 } }, ColourMapA[w->colours[0]].lightest);
continue;
}
int32_t format = STR_BLACK_STRING;
if (i == w->selected_list_item)
{
format = STR_WINDOW_COLOUR_2_STRINGID;
gfx_filter_rect(dpi, 0, y - 1, scrollWidth, y + (SCROLLABLE_ROW_HEIGHT - 2), PALETTE_DARKEN_1);
}
const int32_t bindingOffset = scrollWidth - 150;
auto ft = Formatter::Common();
ft.Add<rct_string_id>(STR_SHORTCUT_ENTRY_FORMAT);
ft.Add<rct_string_id>(ShortcutList[i].StringId);
gfx_draw_string_left_clipped(dpi, format, gCommonFormatArgs, COLOUR_BLACK, { 0, y - 1 }, bindingOffset);
char keybinding[128];
keyboard_shortcuts_format_string(keybinding, 128, ShortcutList[i].ShortcutId);
if (strlen(keybinding) > 0)
{
const int32_t maxWidth = 150;
ft = Formatter::Common();
ft.Add<rct_string_id>(STR_STRING);
ft.Add<char*>(keybinding);
gfx_draw_string_left_clipped(dpi, format, gCommonFormatArgs, COLOUR_BLACK, { bindingOffset, y - 1 }, maxWidth);
}
}
}
|
gpl-3.0
|
alibell/PAS
|
admin/evaluations/index.php
|
2546
|
<?php
/**
Copyright (C) 2015 Ali BELLAMINE
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.
**/
/*
21/05/15 - index.php - Ali Bellamine
Page d'accueil de la gestion des évaluations - Routeur de la gestion des évaluations
*/
require '../../core/main.php';
require '../../core/header.php';
/**
Page divisée en 2 parties :
- Bandeau latéral contenant le menu
- Corps contenant la page à afficher, dépendant de la variable $_GET['page']
**/
/*
Récupération de la variable $_GET['page']
*/
$listePage = array('liste' => LANG_ADMIN_EVALUATIONS_MENU_ITEM_LISTE, 'module' => LANG_ADMIN_EBALUATION_MENU_ITEM_MODULE); // Liste des pages liés à la gestion des évaluations
if (isset($_GET['page']) && isset($listePage[$_GET['page']]))
{
$currentPage = $_GET['page'];
}
else
{
$currentPage = 'liste';
}
/*
Chargement des pages
*/
$url = ROOT.CURRENT_FILE.'?';
?>
<div id = "adminPage">
<div id = "barreLaterale">
<div id = "barreLateraleTitre">
<?php echo LANG_ADMIN_MENU_TITLE; ?>
</div>
<ul id = "barreLateraleMenu">
<?php
foreach ($listePage AS $pageFile => $pageName)
{
if ($pageName != '')
{
?>
<a class = "<?php if ($currentPage == $pageFile) { echo 'barreLateraleSelected'; } ?>" href = "<?php echo $url.'page='.$pageFile; ?>"><li><?php echo $pageName; ?></li></a>
<?php
}
}
?>
</ul>
<div class = "mobileAdminMenuButtonClose"><i class="fa fa-caret-up"></i></div>
</div>
<!-- Bouton permettant d'afficher le menu sur les portables -->
<div class = "mobileAdminMenuButton"><i class="fa fa-caret-down"></i></div>
<div id = "corps">
<?php
if (is_file($currentPage.'.php'))
{
require($currentPage.'.php');
}
?>
</div>
</div>
<?php
require '../../core/footer.php';
?>
|
gpl-3.0
|
ggonzales/ksl
|
src/com/liferay/portlet/polls/action/ActionUtil.java
|
2751
|
/**
* Copyright (c) 2000-2005 Liferay, LLC. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.liferay.portlet.polls.action;
import java.util.List;
import javax.portlet.ActionRequest;
import javax.portlet.RenderRequest;
import javax.servlet.http.HttpServletRequest;
import com.liferay.portal.util.WebKeys;
import com.liferay.portlet.ActionRequestImpl;
import com.liferay.portlet.RenderRequestImpl;
import com.liferay.portlet.polls.ejb.PollsChoiceManagerUtil;
import com.liferay.portlet.polls.ejb.PollsQuestionManagerUtil;
import com.liferay.portlet.polls.model.PollsQuestion;
import com.liferay.util.Validator;
/**
* <a href="ActionUtil.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
* @version $Revision: 1.3 $
*
*/
public class ActionUtil {
public static void getQuestion(ActionRequest req) throws Exception {
HttpServletRequest httpReq =
((ActionRequestImpl)req).getHttpServletRequest();
getQuestion(httpReq);
}
public static void getQuestion(RenderRequest req) throws Exception {
HttpServletRequest httpReq =
((RenderRequestImpl)req).getHttpServletRequest();
getQuestion(httpReq);
}
public static void getQuestion(HttpServletRequest req) throws Exception {
String questionId = req.getParameter("question_id");
// Find question
PollsQuestion question = null;
if (Validator.isNotNull(questionId)) {
question = PollsQuestionManagerUtil.getQuestion(questionId);
}
// Find choices
List choices = null;
if (question != null) {
choices = PollsChoiceManagerUtil.getChoices(questionId);
}
req.setAttribute(WebKeys.POLLS_QUESTION, question);
req.setAttribute(WebKeys.POLLS_CHOICES, choices);
}
}
|
gpl-3.0
|
HuygensING/elaborate4-backend
|
elab4-backend/src/main/java/elaborate/editor/export/tei/AnnotationBodyConverter.java
|
4359
|
package elaborate.editor.export.tei;
/*
* #%L
* elab4-backend
* =======
* Copyright (C) 2011 - 2019 Huygens ING
* =======
* 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/gpl-3.0.html>.
* #L%
*/
import static nl.knaw.huygens.tei.Traversal.NEXT;
import java.util.TreeSet;
import elaborate.util.XmlUtil;
import nl.knaw.huygens.Log;
import nl.knaw.huygens.tei.DelegatingVisitor;
import nl.knaw.huygens.tei.Document;
import nl.knaw.huygens.tei.Element;
import nl.knaw.huygens.tei.ElementHandler;
import nl.knaw.huygens.tei.Traversal;
import nl.knaw.huygens.tei.XmlContext;
import nl.knaw.huygens.tei.handlers.XmlTextHandler;
public class AnnotationBodyConverter {
static final TreeSet<String> unhandledTags = new TreeSet<String>();
@SuppressWarnings("synthetic-access")
public static String convert(String xml) {
String fixedXml = XmlUtil.fixXhtml(XmlUtil.wrapInXml(xml));
try {
Document document = Document.createFromXml(fixedXml, false);
DelegatingVisitor<XmlContext> visitor = new DelegatingVisitor<XmlContext>(new XmlContext());
visitor.setTextHandler(new XmlTextHandler<XmlContext>());
visitor.setDefaultElementHandler(new DefaultElementHandler());
visitor.addElementHandler(new IgnoreElementHandler(), "xml", "span");
visitor.addElementHandler(new HiHandler(), TeiMaker.HI_TAGS.keySet().toArray(new String[] {}));
visitor.addElementHandler(new DelHandler(), "strike");
visitor.addElementHandler(new BrHandler(), "br");
document.accept(visitor);
if (!unhandledTags.isEmpty()) {
Log.warn("unhandled tags: {} for annotation body {}", unhandledTags, fixedXml);
unhandledTags.clear();
}
return visitor.getContext().getResult();
} catch (Exception e) {
e.printStackTrace();
return " :: error in parsing annotation body ::" + e.getMessage();
}
}
private static class DefaultElementHandler implements ElementHandler<XmlContext> {
@Override
public Traversal enterElement(Element e, XmlContext c) {
unhandledTags.add(e.getName());
c.addOpenTag(e);
return NEXT;
}
@Override
public Traversal leaveElement(Element e, XmlContext c) {
c.addCloseTag(e);
return NEXT;
}
}
private static class BrHandler implements ElementHandler<XmlContext> {
@Override
public Traversal enterElement(Element e, XmlContext c) {
return NEXT;
}
@Override
public Traversal leaveElement(Element e, XmlContext c) {
c.addEmptyElementTag("lb");
return NEXT;
}
}
private static class DelHandler implements ElementHandler<XmlContext> {
private static final String DEL = "del";
@Override
public Traversal enterElement(Element e, XmlContext c) {
c.addOpenTag(DEL);
return NEXT;
}
@Override
public Traversal leaveElement(Element e, XmlContext c) {
c.addCloseTag(DEL);
return NEXT;
}
}
private static class HiHandler implements ElementHandler<XmlContext> {
@Override
public Traversal enterElement(Element e, XmlContext c) {
Element hi = hiElement(e);
c.addOpenTag(hi);
return NEXT;
}
@Override
public Traversal leaveElement(Element e, XmlContext c) {
Element hi = hiElement(e);
c.addCloseTag(hi);
return NEXT;
}
private Element hiElement(Element e) {
return new Element("hi", "rend", TeiMaker.HI_TAGS.get(e.getName()));
}
}
private static class IgnoreElementHandler implements ElementHandler<XmlContext> {
@Override
public Traversal enterElement(Element e, XmlContext c) {
return NEXT;
}
@Override
public Traversal leaveElement(Element e, XmlContext c) {
return NEXT;
}
}
}
|
gpl-3.0
|
jabber-at/hp
|
hp/core/static/lib/tinymce/src/plugins/autosave/test/ts/browser/AutoSavePluginTest.ts
|
4028
|
import { Pipeline } from '@ephox/agar';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/autosave/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.autosave.AutoSavePluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
Plugin();
Theme();
suite.test('isEmpty true', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.isEmpty(''), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty(' '), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('\t\t\t'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p id="x"></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p> </p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>\t</p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br><br></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /><br /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /><br data-mce-bogus="true" /></p>'), true);
});
suite.test('isEmpty false', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.isEmpty('X'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty(' X'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('\t\t\tX'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p> X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>\tX</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br><br>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /><br />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /><br data-mce-bogus="true" />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<h1></h1>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<img src="x" />'), false);
});
suite.test('hasDraft/storeDraft/restoreDraft', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
editor.setContent('X');
editor.undoManager.add();
editor.plugins.autosave.storeDraft();
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), true);
editor.setContent('Y');
editor.undoManager.add();
editor.plugins.autosave.restoreDraft();
LegacyUnit.equal(editor.getContent(), '<p>X</p>');
editor.plugins.autosave.removeDraft();
});
suite.test('recognises location hash change', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
editor.setContent('X');
editor.undoManager.add();
editor.plugins.autosave.storeDraft();
window.location.hash = 'test';
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
history.replaceState('', document.title, window.location.pathname + window.location.search);
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'autosave',
indent: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});
|
gpl-3.0
|
cathyyul/sumo-0.18
|
docs/doxygen/d8/db4/class_n_i_vissim_edge_1_1connection__position__sorter.js
|
470
|
var class_n_i_vissim_edge_1_1connection__position__sorter =
[
[ "connection_position_sorter", "d8/db4/class_n_i_vissim_edge_1_1connection__position__sorter.html#a89b6a8bb39213e5a7165034ec2c43a33", null ],
[ "operator()", "d8/db4/class_n_i_vissim_edge_1_1connection__position__sorter.html#a7d2b41c412b6cba4057f7f05775c2194", null ],
[ "myEdgeID", "d8/db4/class_n_i_vissim_edge_1_1connection__position__sorter.html#ae79e5ac21b29d17be932cf70d4880bda", null ]
];
|
gpl-3.0
|
karv/Art-of-Meow
|
Test/MapReadingTest.cs
|
402
|
using System;
using NUnit.Framework;
namespace Test
{
[TestFixtureAttribute]
public class MapReadingTest
{
[Test]
public void ReadMaps ()
{
var files = System.IO.Directory.EnumerateFiles (AoM.FileNames.MapFolder, "*.json");
foreach (var file in files) {
Console.WriteLine ("Testing " + file);
var map = Maps.Map.ReadFromFile (file);
map.GenerateGrid (0);
}
}
}
}
|
gpl-3.0
|
Gentleman1983/haVoxTimes
|
haVox_times_model_impl/src/test/java/net/havox/times/model/impl/booking/AccountApiTest.java
|
1742
|
/*
* Copyright (C) 2018 [haVox] Design
*
* 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 net.havox.times.model.impl.booking;
import org.junit.BeforeClass;
import net.havox.times.model.api.booking.AbstractAccountTest;
import net.havox.times.model.api.booking.Account;
import net.havox.times.model.api.booking.Booking;
import net.havox.times.model.api.booking.Project;
import net.havox.times.model.factory.BookingModelFactory;
/**
* API specific tests for {@link Account}.
*
* @author Christian Otto
*/
public class AccountApiTest extends AbstractAccountTest
{
private static BookingModelFactory bookingFactory;
@BeforeClass
public static void setupClass()
{
bookingFactory = BookingModelFactory.getInstance();
}
@Override
public Account newInstance() throws Exception
{
return bookingFactory.getNewAccount();
}
@Override
public Project newProject() throws Exception
{
return bookingFactory.getNewProject();
}
@Override
public Booking newBooking() throws Exception
{
return bookingFactory.getNewBooking();
}
}
|
gpl-3.0
|
ZabuzaW/NashFinder
|
src/de/tischner/nashfinder/nash/NashStrategy.java
|
3218
|
package de.tischner.nashfinder.nash;
import java.util.LinkedHashMap;
import java.util.Map;
import de.tischner.nashfinder.locale.ErrorMessages;
/**
* A nash strategy specifies, for a player, which actions he should play with
* what probability, so that it results in a nash equilibrium.
*
* @author Daniel Tischner {@literal <zabuza.dev@gmail.com>}
*
* @param <ACTION>
* Class of the actions
*/
public final class NashStrategy<ACTION> {
/**
* Inclusive lower bound for probabilities.
*/
private static final int PROBABILITY_LOWER_BOUND = 0;
/**
* Inclusive upper bound for probabilities.
*/
private static final int PROBABILITY_UPPER_BOUND = 1;
/**
* Data structure that allows a fast access to the probability for a given
* action.
*/
private final Map<ACTION, Number> mActionToProbability;
/**
* Creates a new empty nash strategy.
*/
public NashStrategy() {
this.mActionToProbability = new LinkedHashMap<>();
}
/**
* Adds an action with a given probability to the strategy.
*
* @param action
* Action to add
* @param probability
* The probability of the given action between <tt>0</tt> and
* <tt>1</tt> (both inclusive)
* @throws IllegalArgumentException
* If the given probability is not between <tt>0</tt> and
* <tt>1</tt> (both inclusive)
*/
public void addAction(final ACTION action, final Number probability) {
if (probability.doubleValue() < PROBABILITY_LOWER_BOUND
|| probability.doubleValue() > PROBABILITY_UPPER_BOUND) {
throw new IllegalArgumentException(ErrorMessages.PROBABILITY_EXCEEDS_LIMITS + " Got: " + probability);
}
this.mActionToProbability.put(action, probability);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof NashStrategy)) {
return false;
}
final NashStrategy<?> other = (NashStrategy<?>) obj;
if (this.mActionToProbability == null) {
if (other.mActionToProbability != null) {
return false;
}
} else if (!this.mActionToProbability.equals(other.mActionToProbability)) {
return false;
}
return true;
}
/**
* Gets the probability of the given action.
*
* @param action
* Action to get the probability for
* @return The probability of the given action between <tt>0</tt> and
* <tt>1</tt> (both inclusive)
*/
public Number getActionProbability(final ACTION action) {
return this.mActionToProbability.get(action);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.mActionToProbability == null) ? 0 : this.mActionToProbability.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.mActionToProbability.toString();
}
}
|
gpl-3.0
|
raymondbh/TFCraft
|
src/Common/com/bioxx/tfc/CommonProxy.java
|
27750
|
package com.bioxx.tfc;
import java.io.File;
import com.bioxx.tfc.Tools.ChiselMode_Detailed;
import com.bioxx.tfc.Tools.ChiselMode_Slab;
import com.bioxx.tfc.Tools.ChiselMode_Smooth;
import com.bioxx.tfc.Tools.ChiselMode_Stair;
import com.bioxx.tfc.api.Tools.ChiselManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import com.bioxx.tfc.Core.FluidBaseTFC;
import com.bioxx.tfc.Entities.EntityBarrel;
import com.bioxx.tfc.Entities.EntityCustomMinecart;
import com.bioxx.tfc.Entities.EntityFallingBlockTFC;
import com.bioxx.tfc.Entities.EntityJavelin;
import com.bioxx.tfc.Entities.EntityProjectileTFC;
import com.bioxx.tfc.Entities.EntityStand;
import com.bioxx.tfc.Entities.Mobs.EntityBear;
import com.bioxx.tfc.Entities.Mobs.EntityBlazeTFC;
import com.bioxx.tfc.Entities.Mobs.EntityCaveSpiderTFC;
import com.bioxx.tfc.Entities.Mobs.EntityChickenTFC;
import com.bioxx.tfc.Entities.Mobs.EntityCowTFC;
import com.bioxx.tfc.Entities.Mobs.EntityCreeperTFC;
import com.bioxx.tfc.Entities.Mobs.EntityDeer;
import com.bioxx.tfc.Entities.Mobs.EntityEndermanTFC;
import com.bioxx.tfc.Entities.Mobs.EntityFishTFC;
import com.bioxx.tfc.Entities.Mobs.EntityGhastTFC;
import com.bioxx.tfc.Entities.Mobs.EntityHorseTFC;
import com.bioxx.tfc.Entities.Mobs.EntityIronGolemTFC;
import com.bioxx.tfc.Entities.Mobs.EntityPheasantTFC;
import com.bioxx.tfc.Entities.Mobs.EntityPigTFC;
import com.bioxx.tfc.Entities.Mobs.EntityPigZombieTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySheepTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySilverfishTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySkeletonTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySlimeTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySpiderTFC;
import com.bioxx.tfc.Entities.Mobs.EntitySquidTFC;
import com.bioxx.tfc.Entities.Mobs.EntityWolfTFC;
import com.bioxx.tfc.Entities.Mobs.EntityZombieTFC;
import com.bioxx.tfc.Handlers.GuiHandler;
import com.bioxx.tfc.Handlers.ServerTickHandler;
import com.bioxx.tfc.TileEntities.TEAnvil;
import com.bioxx.tfc.TileEntities.TEBarrel;
import com.bioxx.tfc.TileEntities.TEBellows;
import com.bioxx.tfc.TileEntities.TEBerryBush;
import com.bioxx.tfc.TileEntities.TEBlastFurnace;
import com.bioxx.tfc.TileEntities.TEBloom;
import com.bioxx.tfc.TileEntities.TEBloomery;
import com.bioxx.tfc.TileEntities.TEChest;
import com.bioxx.tfc.TileEntities.TECrop;
import com.bioxx.tfc.TileEntities.TECrucible;
import com.bioxx.tfc.TileEntities.TEDetailed;
import com.bioxx.tfc.TileEntities.TEFarmland;
import com.bioxx.tfc.TileEntities.TEFenceGate;
import com.bioxx.tfc.TileEntities.TEFirepit;
import com.bioxx.tfc.TileEntities.TEFoodPrep;
import com.bioxx.tfc.TileEntities.TEForge;
import com.bioxx.tfc.TileEntities.TEFruitLeaves;
import com.bioxx.tfc.TileEntities.TEFruitTreeWood;
import com.bioxx.tfc.TileEntities.TEGrill;
import com.bioxx.tfc.TileEntities.TEHopper;
import com.bioxx.tfc.TileEntities.TEIngotPile;
import com.bioxx.tfc.TileEntities.TELeatherRack;
import com.bioxx.tfc.TileEntities.TELightEmitter;
import com.bioxx.tfc.TileEntities.TELogPile;
import com.bioxx.tfc.TileEntities.TELoom;
import com.bioxx.tfc.TileEntities.TEMetalSheet;
import com.bioxx.tfc.TileEntities.TEMetalTrapDoor;
import com.bioxx.tfc.TileEntities.TENestBox;
import com.bioxx.tfc.TileEntities.TEOilLamp;
import com.bioxx.tfc.TileEntities.TEOre;
import com.bioxx.tfc.TileEntities.TEPartial;
import com.bioxx.tfc.TileEntities.TEPottery;
import com.bioxx.tfc.TileEntities.TEQuern;
import com.bioxx.tfc.TileEntities.TESapling;
import com.bioxx.tfc.TileEntities.TESluice;
import com.bioxx.tfc.TileEntities.TESmokeRack;
import com.bioxx.tfc.TileEntities.TESpawnMeter;
import com.bioxx.tfc.TileEntities.TEStand;
import com.bioxx.tfc.TileEntities.TEToolRack;
import com.bioxx.tfc.TileEntities.TEVessel;
import com.bioxx.tfc.TileEntities.TEWaterPlant;
import com.bioxx.tfc.TileEntities.TEWoodConstruct;
import com.bioxx.tfc.TileEntities.TEWorkbench;
import com.bioxx.tfc.TileEntities.TEWorldItem;
import com.bioxx.tfc.WorldGen.TFCProvider;
import com.bioxx.tfc.api.TFCFluids;
import com.bioxx.tfc.api.TFCItems;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
public class CommonProxy
{
public void registerFluidIcons()
{
}
public void registerRenderInformation()
{
// NOOP on server
}
public void registerBiomeEventHandler()
{
// NOOP on server
}
public void registerPlayerRenderEventHandler()
{
// NOOP on server
}
public void setupGuiIngameForge()
{
// NOOP on server
}
public String getCurrentLanguage()
{
return null;
}
public void registerTileEntities(boolean b)
{
GameRegistry.registerTileEntity(TELogPile.class, "TerraLogPile");
GameRegistry.registerTileEntity(TEWorkbench.class, "TerraWorkbench");
GameRegistry.registerTileEntity(TEForge.class, "TerraForge");
GameRegistry.registerTileEntity(TEBlastFurnace.class, "TerraBloomery");
GameRegistry.registerTileEntity(TEBloomery.class, "TerraEarlyBloomery");
GameRegistry.registerTileEntity(TESluice.class, "TerraSluice");
GameRegistry.registerTileEntity(TEFarmland.class, "TileEntityFarmland");
GameRegistry.registerTileEntity(TECrop.class, "TileEntityCrop");
GameRegistry.registerTileEntity(TEFruitTreeWood.class, "FruitTreeWood");
GameRegistry.registerTileEntity(TEPartial.class, "Partial");
GameRegistry.registerTileEntity(TEDetailed.class, "Detailed");
GameRegistry.registerTileEntity(TESpawnMeter.class, "SpawnMeter");
GameRegistry.registerTileEntity(TESapling.class, "Sapling");
GameRegistry.registerTileEntity(TEWoodConstruct.class, "WoodConstruct");
GameRegistry.registerTileEntity(TEBarrel.class, "Barrel");
GameRegistry.registerTileEntity(TEFenceGate.class, "FenceGate");
GameRegistry.registerTileEntity(TEBloom.class, "IronBloom");
GameRegistry.registerTileEntity(TECrucible.class, "Crucible");
GameRegistry.registerTileEntity(TENestBox.class, "Nest Box");
GameRegistry.registerTileEntity(TEStand.class, "Armour Stand");
GameRegistry.registerTileEntity(TEBerryBush.class, "Berry Bush");
GameRegistry.registerTileEntity(TEFruitLeaves.class, "Fruit Leaves");
GameRegistry.registerTileEntity(TEMetalSheet.class, "Metal Sheet");
GameRegistry.registerTileEntity(TEOre.class, "ore");
GameRegistry.registerTileEntity(TELeatherRack.class, "leatherRack");
GameRegistry.registerTileEntity(TEMetalTrapDoor.class, "MetalTrapDoor");
GameRegistry.registerTileEntity(TEWaterPlant.class, "Sea Weed");
GameRegistry.registerTileEntity(TEVessel.class, "Vessel");
GameRegistry.registerTileEntity(TELightEmitter.class, "LightEmitter");
GameRegistry.registerTileEntity(TESmokeRack.class, "Smoke Rack");
GameRegistry.registerTileEntity(TEOilLamp.class, "Oil Lamp");
if(b)
{
GameRegistry.registerTileEntity(TEFirepit.class, "TerraFirepit");
GameRegistry.registerTileEntity(TEIngotPile.class, "ingotPile");
GameRegistry.registerTileEntity(TEPottery.class, "Pottery");
GameRegistry.registerTileEntity(TEChest.class, "chest");
GameRegistry.registerTileEntity(TEFoodPrep.class, "FoodPrep");
GameRegistry.registerTileEntity(TEBellows.class, "Bellows");
GameRegistry.registerTileEntity(TEToolRack.class, "ToolRack");
GameRegistry.registerTileEntity(TEAnvil.class, "TerraAnvil");
GameRegistry.registerTileEntity(TEWorldItem.class, "worldItem");
GameRegistry.registerTileEntity(TEQuern.class, "Quern");
GameRegistry.registerTileEntity(TELoom.class, "Loom");
GameRegistry.registerTileEntity(TEGrill.class, "grill");
GameRegistry.registerTileEntity(TEHopper.class, "HopperTFC");
}
EntityRegistry.registerGlobalEntityID(EntitySquidTFC.class, "squidTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x3c5466, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityFishTFC.class, "fishTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x535231, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityCowTFC.class, "cowTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x3d2f23, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityWolfTFC.class, "wolfTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x938f8c, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityBear.class, "bearTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x5c4b3b, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityChickenTFC.class, "chickenTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xf3f45e, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityPigTFC.class, "pigTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xe78786, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityDeer.class, "deerTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x7c624c, 0x260026);
EntityRegistry.registerGlobalEntityID(EntitySkeletonTFC.class, "skeletonTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x979797, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityZombieTFC.class, "zombieTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x426a33, 0x260026);
EntityRegistry.registerGlobalEntityID(EntitySpiderTFC.class, "spiderTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x322b24, 0x260026);
EntityRegistry.registerGlobalEntityID(EntitySlimeTFC.class, "slimeTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x6eb35c, 0x260026);
EntityRegistry.registerGlobalEntityID(EntitySilverfishTFC.class, "silverfishTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x858887, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityGhastTFC.class, "ghastTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xebebeb, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityCaveSpiderTFC.class, "caveSpiderTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x123236, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityBlazeTFC.class, "blazeTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xad6d0b, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityEndermanTFC.class, "endermanTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x0d0d0d, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityPigZombieTFC.class, "pigZombieTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xb6735f, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityIronGolemTFC.class, "irongolemTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xbfb99a, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityCreeperTFC.class, "creeperTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x66c55c, 0x260026);
EntityRegistry.registerGlobalEntityID(EntitySheepTFC.class, "sheepTFC", EntityRegistry.findGlobalUniqueEntityId(), 0xcdbfb4, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityPheasantTFC.class, "pheasantTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x822c1c, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityHorseTFC.class, "horseTFC", EntityRegistry.findGlobalUniqueEntityId(), 0x966936, 0x260026);
EntityRegistry.registerGlobalEntityID(EntityCustomMinecart.class, "minecartTFC", EntityRegistry.findGlobalUniqueEntityId());
EntityRegistry.registerGlobalEntityID(EntityProjectileTFC.class, "arrowTFC", EntityRegistry.findGlobalUniqueEntityId());
EntityRegistry.registerGlobalEntityID(EntityStand.class, "standTFC", EntityRegistry.findGlobalUniqueEntityId());
EntityRegistry.registerGlobalEntityID(EntityFallingBlockTFC.class, "fallingBlock", EntityRegistry.findGlobalUniqueEntityId());
EntityRegistry.registerGlobalEntityID(EntityBarrel.class, "barrel", EntityRegistry.findGlobalUniqueEntityId());
EntityRegistry.registerModEntity(EntityJavelin.class, "javelin", 1, TerraFirmaCraft.instance, 64, 5, true);
EntityRegistry.registerModEntity(EntitySquidTFC.class, "squidTFC", 2, TerraFirmaCraft.instance, 64, 5, true);
EntityRegistry.registerModEntity(EntityCowTFC.class, "cowTFC", 6, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityWolfTFC.class, "wolfTFC", 7, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityBear.class, "bearTFC", 8, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityChickenTFC.class, "chickenTFC", 9, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityPigTFC.class, "pigTFC", 10, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityDeer.class, "deerTFC", 11, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityCustomMinecart.class, "minecartTFC", 12, TerraFirmaCraft.instance, 80, 5, true);
EntityRegistry.registerModEntity(EntitySkeletonTFC.class, "skeletonTFC", 13, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityZombieTFC.class, "zombieTFC", 14, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntitySpiderTFC.class, "spiderTFC", 15, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntitySlimeTFC.class, "slimeTFC", 16, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntitySilverfishTFC.class, "silverFishTFC", 17, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityGhastTFC.class, "ghastTFC", 18, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityCaveSpiderTFC.class, "caveSpiderTFC", 19, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityBlazeTFC.class, "blazeTFC", 20, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityEndermanTFC.class, "endermanTFC", 21, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityPigZombieTFC.class, "pigZombieTFC", 22, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityIronGolemTFC.class, "irongolemTFC", 23, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityCreeperTFC.class, "creeperTFC", 24, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityStand.class, "standTFC", 25, TerraFirmaCraft.instance, 64, 20, false);
EntityRegistry.registerModEntity(EntityPheasantTFC.class, "PheasantTFC", 26, TerraFirmaCraft.instance, 160, 5, true);
EntityRegistry.registerModEntity(EntityFishTFC.class, "fishTFC", 27, TerraFirmaCraft.instance, 64, 5, true);
EntityRegistry.registerModEntity(EntityFallingBlockTFC.class, "fallingBlock", 28, TerraFirmaCraft.instance, 160, 20, true);
EntityRegistry.registerModEntity(EntityBarrel.class, "barrel", 29, TerraFirmaCraft.instance, 64, 20, true);
/*Function<EntitySpawnMessage, Entity> spawnFunction = new Function<EntitySpawnMessage, Entity>()
{
@Override
public Entity apply(EntitySpawnMessage input) {
return null;
}};
EntityRegistry.instance().lookupModSpawn(EntityFallingBlockTFC.class, false).setCustomSpawning(spawnFunction, false);
*/
//EntityRegistry.registerModEntity(EntityArrowTFC.class, "arrowTFC", 27, TerraFirmaCraft.instance, 160, 5, true);
}
public void registerFluids()
{
TFCFluids.SALTWATER = new FluidBaseTFC("saltwater").setBaseColor(0x354d35);
TFCFluids.FRESHWATER = new FluidBaseTFC("freshwater").setBaseColor(0x354d35);
TFCFluids.HOTWATER = new FluidBaseTFC("hotwater").setBaseColor(0x1f5099).setTemperature(372/*Kelvin*/);
TFCFluids.LAVA = new FluidBaseTFC("lavatfc").setLuminosity(15).setDensity(3000).setViscosity(6000).setTemperature(1300).setUnlocalizedName(Blocks.lava.getUnlocalizedName());
TFCFluids.RUM = new FluidBaseTFC("rum").setBaseColor(0x6e0123);
TFCFluids.BEER = new FluidBaseTFC("beer").setBaseColor(0xc39e37);
TFCFluids.RYEWHISKEY = new FluidBaseTFC("ryewhiskey").setBaseColor(0xc77d51);
TFCFluids.WHISKEY = new FluidBaseTFC("whiskey").setBaseColor(0x583719);
TFCFluids.CORNWHISKEY = new FluidBaseTFC("cornwhiskey").setBaseColor(0xd9c7b7);
TFCFluids.SAKE = new FluidBaseTFC("sake").setBaseColor(0xb7d9bc);
TFCFluids.VODKA = new FluidBaseTFC("vodka").setBaseColor(0xdcdcdc);
TFCFluids.CIDER = new FluidBaseTFC("cider").setBaseColor(0xb0ae32);
TFCFluids.TANNIN = new FluidBaseTFC("tannin").setBaseColor(0x63594e);
TFCFluids.VINEGAR = new FluidBaseTFC("vinegar").setBaseColor(0xc7c2aa);
TFCFluids.BRINE = new FluidBaseTFC("brine").setBaseColor(0xdcd3c9);
TFCFluids.LIMEWATER = new FluidBaseTFC("limewater").setBaseColor(0xb4b4b4);
TFCFluids.MILK = new FluidBaseTFC("milk").setBaseColor(0xffffff);
TFCFluids.MILKCURDLED = new FluidBaseTFC("milkcurdled").setBaseColor(0xfffbe8);
TFCFluids.MILKVINEGAR = new FluidBaseTFC("milkvinegar").setBaseColor(0xfffbe8);
TFCFluids.OLIVEOIL = new FluidBaseTFC("oliveoil").setBaseColor(0x6a7537);
FluidRegistry.registerFluid(TFCFluids.LAVA);
FluidRegistry.registerFluid(TFCFluids.SALTWATER);
FluidRegistry.registerFluid(TFCFluids.FRESHWATER);
FluidRegistry.registerFluid(TFCFluids.HOTWATER);
FluidRegistry.registerFluid(TFCFluids.RUM);
FluidRegistry.registerFluid(TFCFluids.BEER);
FluidRegistry.registerFluid(TFCFluids.RYEWHISKEY);
FluidRegistry.registerFluid(TFCFluids.CORNWHISKEY);
FluidRegistry.registerFluid(TFCFluids.WHISKEY);
FluidRegistry.registerFluid(TFCFluids.SAKE);
FluidRegistry.registerFluid(TFCFluids.VODKA);
FluidRegistry.registerFluid(TFCFluids.CIDER);
FluidRegistry.registerFluid(TFCFluids.TANNIN);
FluidRegistry.registerFluid(TFCFluids.VINEGAR);
FluidRegistry.registerFluid(TFCFluids.BRINE);
FluidRegistry.registerFluid(TFCFluids.LIMEWATER);
FluidRegistry.registerFluid(TFCFluids.MILK);
FluidRegistry.registerFluid(TFCFluids.MILKCURDLED);
FluidRegistry.registerFluid(TFCFluids.MILKVINEGAR);
FluidRegistry.registerFluid(TFCFluids.OLIVEOIL);
}
public void setupFluids()
{
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluid(TFCFluids.LAVA.getName()), new ItemStack(TFCItems.BlueSteelBucketLava), new ItemStack(TFCItems.BlueSteelBucketEmpty));
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluid(TFCFluids.FRESHWATER.getName()), new ItemStack(TFCItems.RedSteelBucketWater), new ItemStack(TFCItems.RedSteelBucketEmpty));
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluid(TFCFluids.SALTWATER.getName()), new ItemStack(TFCItems.RedSteelBucketSaltWater), new ItemStack(TFCItems.RedSteelBucketEmpty));
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluid(TFCFluids.FRESHWATER.getName()), new ItemStack(TFCItems.WoodenBucketWater), new ItemStack(TFCItems.WoodenBucketEmpty));
FluidContainerRegistry.registerFluidContainer(FluidRegistry.getFluid(TFCFluids.SALTWATER.getName()), new ItemStack(TFCItems.WoodenBucketSaltWater), new ItemStack(TFCItems.WoodenBucketEmpty));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.FRESHWATER, 1000), new ItemStack(TFCItems.PotteryJug, 1, 2), new ItemStack(TFCItems.PotteryJug,1, 1));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.RUM, 250), new ItemStack(TFCItems.Rum), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.BEER, 250), new ItemStack(TFCItems.Beer), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.RYEWHISKEY, 250), new ItemStack(TFCItems.RyeWhiskey), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.WHISKEY, 250), new ItemStack(TFCItems.Whiskey), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.CORNWHISKEY, 250), new ItemStack(TFCItems.CornWhiskey), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.SAKE, 250), new ItemStack(TFCItems.Sake), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.CIDER, 250), new ItemStack(TFCItems.Cider), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.VODKA, 250), new ItemStack(TFCItems.Vodka), new ItemStack(TFCItems.GlassBottle));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.MILK, 1000), new ItemStack(TFCItems.WoodenBucketMilk), new ItemStack(TFCItems.WoodenBucketEmpty));
FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.VINEGAR, 1000), new ItemStack(TFCItems.Vinegar), new ItemStack(TFCItems.WoodenBucketEmpty));
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(0), new ItemStack(TFCBlocks.OilLamp, 1, 0));//Gold
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(1), new ItemStack(TFCBlocks.OilLamp, 1, 1));//Platinum
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(2), new ItemStack(TFCBlocks.OilLamp, 1, 2));//RoseGold
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(3), new ItemStack(TFCBlocks.OilLamp, 1, 3));//Silver
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(4), new ItemStack(TFCBlocks.OilLamp, 1, 4));//Sterling Silver
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.OLIVEOIL, 250), ItemOilLamp.GetFullLamp(5), new ItemStack(TFCBlocks.OilLamp, 1, 5));//BlueSteel
//FluidContainerRegistry.registerFluidContainer(new FluidStack(TFCFluids.LAVA, 250), ItemOilLamp.GetFullLamp(5), new ItemStack(TFCBlocks.OilLamp, 1, 5));//BlueSteel
}
public void registerToolClasses()
{
//pickaxes
TFCItems.BismuthBronzePick.setHarvestLevel("pickaxe", 2);
TFCItems.BismuthBronzePick.setHarvestLevel("pickaxe", 2);
TFCItems.BlackBronzePick.setHarvestLevel("pickaxe", 2);
TFCItems.BlackSteelPick.setHarvestLevel("pickaxe", 5);
TFCItems.BlueSteelPick.setHarvestLevel("pickaxe", 6);
TFCItems.BronzePick.setHarvestLevel("pickaxe", 2);
TFCItems.CopperPick.setHarvestLevel("pickaxe", 1);
TFCItems.WroughtIronPick.setHarvestLevel("pickaxe", 3);
TFCItems.RedSteelPick.setHarvestLevel("pickaxe", 6);
TFCItems.SteelPick.setHarvestLevel("pickaxe", 4);
//shovels
TFCItems.IgInShovel.setHarvestLevel("shovel", 1);
TFCItems.IgExShovel.setHarvestLevel("shovel", 1);
TFCItems.SedShovel.setHarvestLevel("shovel", 1);
TFCItems.MMShovel.setHarvestLevel("shovel", 1);
TFCItems.BismuthBronzeShovel.setHarvestLevel("shovel", 2);
TFCItems.BlackBronzeShovel.setHarvestLevel("shovel", 2);
TFCItems.BlackSteelShovel.setHarvestLevel("shovel", 5);
TFCItems.BlueSteelShovel.setHarvestLevel("shovel", 6);
TFCItems.BronzeShovel.setHarvestLevel("shovel", 2);
TFCItems.CopperShovel.setHarvestLevel("shovel", 1);
TFCItems.WroughtIronShovel.setHarvestLevel("shovel", 3);
TFCItems.RedSteelShovel.setHarvestLevel("shovel", 6);
TFCItems.SteelShovel.setHarvestLevel("shovel", 4);
//Axes
TFCItems.IgInAxe.setHarvestLevel("axe", 1);
TFCItems.IgExAxe.setHarvestLevel("axe", 1);
TFCItems.SedAxe.setHarvestLevel("axe", 1);
TFCItems.MMAxe.setHarvestLevel("axe", 1);
TFCItems.BismuthBronzeAxe.setHarvestLevel("axe", 2);
TFCItems.BlackBronzeAxe.setHarvestLevel("axe", 2);
TFCItems.BlackSteelAxe.setHarvestLevel("axe", 5);
TFCItems.BlueSteelAxe.setHarvestLevel("axe", 6);
TFCItems.BronzeAxe.setHarvestLevel("axe", 2);
TFCItems.CopperAxe.setHarvestLevel("axe", 1);
TFCItems.WroughtIronAxe.setHarvestLevel("axe", 3);
TFCItems.RedSteelAxe.setHarvestLevel("axe", 6);
TFCItems.SteelAxe.setHarvestLevel("axe", 4);
TFCItems.BismuthBronzeSaw.setHarvestLevel("axe", 2);
TFCItems.BlackBronzeSaw.setHarvestLevel("axe", 2);
TFCItems.BlackSteelSaw.setHarvestLevel("axe", 5);
TFCItems.BlueSteelSaw.setHarvestLevel("axe", 6);
TFCItems.BronzeSaw.setHarvestLevel("axe", 2);
TFCItems.CopperSaw.setHarvestLevel("axe", 1);
TFCItems.WroughtIronSaw.setHarvestLevel("axe", 3);
TFCItems.RedSteelSaw.setHarvestLevel("axe", 6);
TFCItems.SteelSaw.setHarvestLevel("axe", 4);
TFCItems.StoneHammer.setHarvestLevel("hammer", 1);
TFCItems.BismuthBronzeHammer.setHarvestLevel("hammer", 2);
TFCItems.BlackBronzeHammer.setHarvestLevel("hammer", 2);
TFCItems.BlackSteelHammer.setHarvestLevel("hammer", 5);
TFCItems.BlueSteelHammer.setHarvestLevel("hammer", 6);
TFCItems.BronzeHammer.setHarvestLevel("hammer", 2);
TFCItems.CopperHammer.setHarvestLevel("hammer", 1);
TFCItems.WroughtIronHammer.setHarvestLevel("hammer", 3);
TFCItems.RedSteelHammer.setHarvestLevel("hammer", 6);
TFCItems.SteelHammer.setHarvestLevel("hammer", 4);
}
public void onClientLogin()
{
}
public File getMinecraftDir()
{
return FMLCommonHandler.instance().getMinecraftServerInstance().getFile("");/*new File(".");*/
}
public void registerSkyProvider(TFCProvider P)
{
}
public boolean isRemote()
{
return false;
}
public World getCurrentWorld()
{
return MinecraftServer.getServer().getEntityWorld();
}
public int waterColorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return 0;
}
public int grassColorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return 0;
}
public int foliageColorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
return 0;
}
public void takenFromCrafting(EntityPlayer entityplayer, ItemStack itemstack, IInventory iinventory)
{
FMLCommonHandler.instance().firePlayerCraftingEvent(entityplayer, itemstack, iinventory);
}
public int getArmorRenderID(String name)
{
return 0;
}
public boolean getGraphicsLevel()
{
return false;
}
public void registerKeys()
{
}
public void registerKeyBindingHandler()
{
}
public void uploadKeyBindingsToGame()
{
}
public void registerHandlers()
{
}
public void registerSoundHandler()
{
}
public void registerTickHandler()
{
FMLCommonHandler.instance().bus().register(new ServerTickHandler());
}
public void registerGuiHandler()
{
NetworkRegistry.INSTANCE.registerGuiHandler(TerraFirmaCraft.instance, new GuiHandler());
}
public void registerWailaClasses()
{
FMLInterModComms.sendMessage("Waila", "register", "com.bioxx.tfc.WAILA.WAILAData.callbackRegister");
FMLInterModComms.sendMessage("Waila", "register", "com.bioxx.tfc.WAILA.WCrucible.callbackRegister"); // Crucible has it's own file due to extra calculations.
}
public void registerChiselModes()
{
ChiselManager.getInstance().addChiselMode(new ChiselMode_Smooth("Smooth"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Stair("Stairs"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Slab("Slabs"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Detailed("Detailed"));
}
public void hideNEIItems() {}
}
|
gpl-3.0
|
SufferMyJoy/dobsondev-theme
|
dobsondev-theme/search.php
|
902
|
<?php
/**
* The template for displaying search results.
*
* @package DobsonDev Theme
* @author Alex Dobson - http://dobsondev.com/
*/
get_header();
do_action('dobsondev_before_content');
?>
<div class="entry-content">
<h1> <?php _e( 'Search Results for "' . get_search_query() . '"' ); ?> </h1>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="search-results">
<a class="search-results-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<div class="search-results-date"> <?php the_date(); ?> </div>
<div class="search-results-excerpt"><?php the_excerpt(); ?> </div>
<div class="clear"></div>
</div><!-- END POST -->
<?php endwhile; // end of the loop. ?>
</div><!-- ENTRY CONTENT -->
<?php
do_action('dobsondev_menu');
do_action('dobsondev_after_content');
get_footer();
?>
|
gpl-3.0
|
snlpatel001213/algorithmia
|
bayesian/HiddenMarkovModel/baumWelch.py
|
18315
|
#!/usr/bin/env python
"""
CS 65 Lab #3 -- 5 Oct 2008
Dougal Sutherland
Implements a hidden Markov model, based on Jurafsky + Martin's presentation,
which is in turn based off work by Jason Eisner. We test our program with
data from Eisner's spreadsheets.
"""
identity = lambda x: x
class HiddenMarkovModel(object):
"""A hidden Markov model."""
def __init__(self, states, transitions, emissions, vocab):
"""
states - a list/tuple of states, e.g. ('start', 'hot', 'cold', 'end')
start state needs to be first, end state last
states are numbered by their order here
transitions - the probabilities to go from one state to another
transitions[from_state][to_state] = prob
emissions - the probabilities of an observation for a given state
emissions[state][observation] = prob
vocab: a list/tuple of the names of observable values, in order
"""
self.states = states
self.real_states = states[1:-1]
self.start_state = 0
self.end_state = len(states) - 1
self.transitions = transitions
self.emissions = emissions
self.vocab = vocab
# functions to get stuff one-indexed
state_num = lambda self, n: self.states[n]
state_nums = lambda self: xrange(1, len(self.real_states) + 1)
vocab_num = lambda self, n: self.vocab[n - 1]
vocab_nums = lambda self: xrange(1, len(self.vocab) + 1)
num_for_vocab = lambda self, s: self.vocab.index(s) + 1
def transition(self, from_state, to_state):
return self.transitions[from_state][to_state]
def emission(self, state, observed):
return self.emissions[state][observed - 1]
# helper stuff
def _normalize_observations(self, observations):
return [None] + [self.num_for_vocab(o) if o.__class__ == str else o
for o in observations]
def _init_trellis(self, observed, forward=True, init_func=identity):
trellis = [ [None for j in range(len(observed))]
for i in range(len(self.real_states) + 1) ]
if forward:
v = lambda s: self.transition(0, s) * self.emission(s, observed[1])
else:
v = lambda s: self.transition(s, self.end_state)
init_pos = 1 if forward else -1
for state in self.state_nums():
trellis[state][init_pos] = init_func( v(state) )
return trellis
def _follow_backpointers(self, trellis, start):
# don't bother branching
pointer = start[0]
seq = [pointer, self.end_state]
for t in reversed(xrange(1, len(trellis[1]))):
val, backs = trellis[pointer][t]
pointer = backs[0]
seq.insert(0, pointer)
return seq
# actual algorithms
def forward_prob(self, observations, return_trellis=False):
"""
Returns the probability of seeing the given `observations` sequence,
using the Forward algorithm.
"""
observed = self._normalize_observations(observations)
trellis = self._init_trellis(observed)
for t in range(2, len(observed)):
for state in self.state_nums():
trellis[state][t] = sum(
self.transition(old_state, state)
* self.emission(state, observed[t])
* trellis[old_state][t-1]
for old_state in self.state_nums()
)
final = sum(trellis[state][-1] * self.transition(state, -1)
for state in self.state_nums())
return (final, trellis) if return_trellis else final
def backward_prob(self, observations, return_trellis=False):
"""
Returns the probability of seeing the given `observations` sequence,
using the Backward algorithm.
"""
observed = self._normalize_observations(observations)
trellis = self._init_trellis(observed, forward=False)
for t in reversed(range(1, len(observed) - 1)):
for state in self.state_nums():
trellis[state][t] = sum(
self.transition(state, next_state)
* self.emission(next_state, observed[t+1])
* trellis[next_state][t+1]
for next_state in self.state_nums()
)
final = sum(self.transition(0, state)
* self.emission(state, observed[1])
* trellis[state][1]
for state in self.state_nums())
return (final, trellis) if return_trellis else final
def viterbi_sequence(self, observations, return_trellis=False):
"""
Returns the most likely sequence of hidden states, for a given
sequence of observations. Uses the Viterbi algorithm.
"""
observed = self._normalize_observations(observations)
trellis = self._init_trellis(observed, init_func=lambda val: (val, [0]))
for t in range(2, len(observed)):
for state in self.state_nums():
emission_prob = self.emission(state, observed[t])
last = [(old_state, trellis[old_state][t-1][0] * \
self.transition(old_state, state) * \
emission_prob)
for old_state in self.state_nums()]
highest = max(last, key=lambda p: p[1])[1]
backs = [s for s, val in last if val == highest]
trellis[state][t] = (highest, backs)
last = [(old_state, trellis[old_state][-1][0] * \
self.transition(old_state, self.end_state))
for old_state in self.state_nums()]
highest = max(last, key = lambda p: p[1])[1]
backs = [s for s, val in last if val == highest]
seq = self._follow_backpointers(trellis, backs)
return (seq, trellis) if return_trellis else seq
def train_on_obs(self, observations, return_probs=False):
"""
Trains the model once, using the forward-backward algorithm. This
function returns a new HMM instance rather than modifying this one.
"""
observed = self._normalize_observations(observations)
forward_prob, forwards = self.forward_prob( observations, True)
backward_prob, backwards = self.backward_prob(observations, True)
# gamma values
prob_of_state_at_time = posat = [None] + [
[0] + [forwards[state][t] * backwards[state][t] / forward_prob
for t in range(1, len(observations)+1)]
for state in self.state_nums()]
# xi values
prob_of_transition = pot = [None] + [
[None] + [
[0] + [forwards[state1][t]
* self.transition(state1, state2)
* self.emission(state2, observed[t+1])
* backwards[state2][t+1]
/ forward_prob
for t in range(1, len(observations))]
for state2 in self.state_nums()]
for state1 in self.state_nums()]
# new transition probabilities
trans = [[0 for j in range(len(self.states))]
for i in range(len(self.states))]
trans[self.end_state][self.end_state] = 1
for state in self.state_nums():
state_prob = sum(posat[state])
trans[0][state] = posat[state][1]
trans[state][-1] = posat[state][-1] / state_prob
for oth in self.state_nums():
trans[state][oth] = sum(pot[state][oth]) / state_prob
# new emission probabilities
emit = [[0 for j in range(len(self.vocab))]
for i in range(len(self.states))]
for state in self.state_nums():
for output in range(1, len(self.vocab) + 1):
n = sum(posat[state][t] for t in range(1, len(observations)+1)
if observed[t] == output)
emit[state][output-1] = n / sum(posat[state])
trained = HiddenMarkovModel(self.states, trans, emit, self.vocab)
return (trained, posat, pot) if return_probs else trained
# ======================
# = reading from files =
# ======================
def normalize(string):
if '#' in string:
string = string[:string.index('#')]
return string.strip()
def make_hmm_from_file(f):
def nextline():
line = f.readline()
if line == '': # EOF
return None
else:
return normalize(line) or nextline()
n = int(nextline())
states = [nextline() for i in range(n)] # <3 list comprehension abuse
num_vocab = int(nextline())
vocab = [nextline() for i in range(num_vocab)]
transitions = [[float(x) for x in nextline().split()] for i in range(n)]
emissions = [[float(x) for x in nextline().split()] for i in range(n)]
assert nextline() is None
return HiddenMarkovModel(states, transitions, emissions, vocab)
def read_observations_from_file(f):
return filter(lambda x: x, [normalize(line) for line in f.readlines()])
# =========
# = tests =
# =========
import unittest
class TestHMM(unittest.TestCase):
def setUp(self):
# it's complicated to pass args to a testcase, so just use globals
self.hmm = make_hmm_from_file(file(HMM_FILENAME))
self.obs = read_observations_from_file(file(OBS_FILENAME))
def test_forward(self):
prob, trellis = self.hmm.forward_prob(self.obs, True)
self.assertAlmostEqual(prob, 9.1276e-19, 21)
self.assertAlmostEqual(trellis[1][1], 0.1, 4)
self.assertAlmostEqual(trellis[1][3], 0.00135, 5)
self.assertAlmostEqual(trellis[1][6], 8.71549e-5, 9)
self.assertAlmostEqual(trellis[1][13], 5.70827e-9, 9)
self.assertAlmostEqual(trellis[1][20], 1.3157e-10, 14)
self.assertAlmostEqual(trellis[1][27], 3.1912e-14, 13)
self.assertAlmostEqual(trellis[1][33], 2.0498e-18, 22)
self.assertAlmostEqual(trellis[2][1], 0.1, 4)
self.assertAlmostEqual(trellis[2][3], 0.03591, 5)
self.assertAlmostEqual(trellis[2][6], 5.30337e-4, 8)
self.assertAlmostEqual(trellis[2][13], 1.37864e-7, 11)
self.assertAlmostEqual(trellis[2][20], 2.7819e-12, 15)
self.assertAlmostEqual(trellis[2][27], 4.6599e-15, 18)
self.assertAlmostEqual(trellis[2][33], 7.0777e-18, 22)
def test_backward(self):
prob, trellis = self.hmm.backward_prob(self.obs, True)
self.assertAlmostEqual(prob, 9.1276e-19, 21)
self.assertAlmostEqual(trellis[1][1], 1.1780e-18, 22)
self.assertAlmostEqual(trellis[1][3], 7.2496e-18, 22)
self.assertAlmostEqual(trellis[1][6], 3.3422e-16, 20)
self.assertAlmostEqual(trellis[1][13], 3.5380e-11, 15)
self.assertAlmostEqual(trellis[1][20], 6.77837e-9, 14)
self.assertAlmostEqual(trellis[1][27], 1.44877e-5, 10)
self.assertAlmostEqual(trellis[1][33], 0.1, 4)
self.assertAlmostEqual(trellis[2][1], 7.9496e-18, 22)
self.assertAlmostEqual(trellis[2][3], 2.5145e-17, 21)
self.assertAlmostEqual(trellis[2][6], 1.6662e-15, 19)
self.assertAlmostEqual(trellis[2][13], 5.1558e-12, 16)
self.assertAlmostEqual(trellis[2][20], 7.52345e-9, 14)
self.assertAlmostEqual(trellis[2][27], 9.66609e-5, 9)
self.assertAlmostEqual(trellis[2][33], 0.1, 4)
def test_viterbi(self):
path, trellis = self.hmm.viterbi_sequence(self.obs, True)
self.assertEqual(path, [0] + [2]*13 + [1]*14 + [2]*6 + [3])
self.assertAlmostEqual(trellis[1][1] [0], 0.1, 4)
self.assertAlmostEqual(trellis[1][6] [0], 5.62e-05, 7)
self.assertAlmostEqual(trellis[1][7] [0], 4.50e-06, 8)
self.assertAlmostEqual(trellis[1][16][0], 1.99e-09, 11)
self.assertAlmostEqual(trellis[1][17][0], 3.18e-10, 12)
self.assertAlmostEqual(trellis[1][23][0], 4.00e-13, 15)
self.assertAlmostEqual(trellis[1][25][0], 1.26e-13, 15)
self.assertAlmostEqual(trellis[1][29][0], 7.20e-17, 19)
self.assertAlmostEqual(trellis[1][30][0], 1.15e-17, 19)
self.assertAlmostEqual(trellis[1][32][0], 7.90e-19, 21)
self.assertAlmostEqual(trellis[1][33][0], 1.26e-19, 21)
self.assertAlmostEqual(trellis[2][ 1][0], 0.1, 4)
self.assertAlmostEqual(trellis[2][ 4][0], 0.00502, 5)
self.assertAlmostEqual(trellis[2][ 6][0], 0.00045, 5)
self.assertAlmostEqual(trellis[2][12][0], 1.62e-07, 9)
self.assertAlmostEqual(trellis[2][18][0], 3.18e-12, 14)
self.assertAlmostEqual(trellis[2][19][0], 1.78e-12, 14)
self.assertAlmostEqual(trellis[2][23][0], 5.00e-14, 16)
self.assertAlmostEqual(trellis[2][28][0], 7.87e-16, 18)
self.assertAlmostEqual(trellis[2][29][0], 4.41e-16, 18)
self.assertAlmostEqual(trellis[2][30][0], 7.06e-17, 19)
self.assertAlmostEqual(trellis[2][33][0], 1.01e-18, 20)
def test_learning_probs(self):
trained, gamma, xi = self.hmm.train_on_obs(self.obs, True)
self.assertAlmostEqual(gamma[1][1], 0.129, 3)
self.assertAlmostEqual(gamma[1][3], 0.011, 3)
self.assertAlmostEqual(gamma[1][7], 0.022, 3)
self.assertAlmostEqual(gamma[1][14], 0.887, 3)
self.assertAlmostEqual(gamma[1][18], 0.994, 3)
self.assertAlmostEqual(gamma[1][23], 0.961, 3)
self.assertAlmostEqual(gamma[1][27], 0.507, 3)
self.assertAlmostEqual(gamma[1][33], 0.225, 3)
self.assertAlmostEqual(gamma[2][1], 0.871, 3)
self.assertAlmostEqual(gamma[2][3], 0.989, 3)
self.assertAlmostEqual(gamma[2][7], 0.978, 3)
self.assertAlmostEqual(gamma[2][14], 0.113, 3)
self.assertAlmostEqual(gamma[2][18], 0.006, 3)
self.assertAlmostEqual(gamma[2][23], 0.039, 3)
self.assertAlmostEqual(gamma[2][27], 0.493, 3)
self.assertAlmostEqual(gamma[2][33], 0.775, 3)
self.assertAlmostEqual(xi[1][1][1], 0.021, 3)
self.assertAlmostEqual(xi[1][1][12], 0.128, 3)
self.assertAlmostEqual(xi[1][1][32], 0.13, 3)
self.assertAlmostEqual(xi[2][1][1], 0.003, 3)
self.assertAlmostEqual(xi[2][1][22], 0.017, 3)
self.assertAlmostEqual(xi[2][1][32], 0.095, 3)
self.assertAlmostEqual(xi[1][2][4], 0.02, 3)
self.assertAlmostEqual(xi[1][2][16], 0.018, 3)
self.assertAlmostEqual(xi[1][2][29], 0.010, 3)
self.assertAlmostEqual(xi[2][2][2], 0.972, 3)
self.assertAlmostEqual(xi[2][2][12], 0.762, 3)
self.assertAlmostEqual(xi[2][2][28], 0.907, 3)
def test_learning_results(self):
trained = self.hmm.train_on_obs(self.obs)
tr = trained.transition
self.assertAlmostEqual(tr(0, 0), 0, 5)
self.assertAlmostEqual(tr(0, 1), 0.1291, 4)
self.assertAlmostEqual(tr(0, 2), 0.8709, 4)
self.assertAlmostEqual(tr(0, 3), 0, 4)
self.assertAlmostEqual(tr(1, 0), 0, 5)
self.assertAlmostEqual(tr(1, 1), 0.8757, 4)
self.assertAlmostEqual(tr(1, 2), 0.1090, 4)
self.assertAlmostEqual(tr(1, 3), 0.0153, 4)
self.assertAlmostEqual(tr(2, 0), 0, 5)
self.assertAlmostEqual(tr(2, 1), 0.0925, 4)
self.assertAlmostEqual(tr(2, 2), 0.8652, 4)
self.assertAlmostEqual(tr(2, 3), 0.0423, 4)
self.assertAlmostEqual(tr(3, 0), 0, 5)
self.assertAlmostEqual(tr(3, 1), 0, 4)
self.assertAlmostEqual(tr(3, 2), 0, 4)
self.assertAlmostEqual(tr(3, 3), 1, 4)
em = trained.emission
self.assertAlmostEqual(em(0, 1), 0, 4)
self.assertAlmostEqual(em(0, 2), 0, 4)
self.assertAlmostEqual(em(0, 3), 0, 4)
self.assertAlmostEqual(em(1, 1), 0.6765, 4)
self.assertAlmostEqual(em(1, 2), 0.2188, 4)
self.assertAlmostEqual(em(1, 3), 0.1047, 4)
self.assertAlmostEqual(em(2, 1), 0.0584, 4)
self.assertAlmostEqual(em(2, 2), 0.4251, 4)
self.assertAlmostEqual(em(2, 3), 0.5165, 4)
self.assertAlmostEqual(em(3, 1), 0, 4)
self.assertAlmostEqual(em(3, 2), 0, 4)
self.assertAlmostEqual(em(3, 3), 0, 4)
# train 9 more times
for i in range(9):
trained = trained.train_on_obs(self.obs)
tr = trained.transition
self.assertAlmostEqual(tr(0, 0), 0, 4)
self.assertAlmostEqual(tr(0, 1), 0, 4)
self.assertAlmostEqual(tr(0, 2), 1, 4)
self.assertAlmostEqual(tr(0, 3), 0, 4)
self.assertAlmostEqual(tr(1, 0), 0, 4)
self.assertAlmostEqual(tr(1, 1), 0.9337, 4)
self.assertAlmostEqual(tr(1, 2), 0.0663, 4)
self.assertAlmostEqual(tr(1, 3), 0, 4)
self.assertAlmostEqual(tr(2, 0), 0, 4)
self.assertAlmostEqual(tr(2, 1), 0.0718, 4)
self.assertAlmostEqual(tr(2, 2), 0.8650, 4)
self.assertAlmostEqual(tr(2, 3), 0.0632, 4)
self.assertAlmostEqual(tr(3, 0), 0, 4)
self.assertAlmostEqual(tr(3, 1), 0, 4)
self.assertAlmostEqual(tr(3, 2), 0, 4)
self.assertAlmostEqual(tr(3, 3), 1, 4)
em = trained.emission
self.assertAlmostEqual(em(0, 1), 0, 4)
self.assertAlmostEqual(em(0, 2), 0, 4)
self.assertAlmostEqual(em(0, 3), 0, 4)
self.assertAlmostEqual(em(1, 1), 0.6407, 4)
self.assertAlmostEqual(em(1, 2), 0.1481, 4)
self.assertAlmostEqual(em(1, 3), 0.2112, 4)
self.assertAlmostEqual(em(2, 1), 0.00016,5)
self.assertAlmostEqual(em(2, 2), 0.5341, 4)
self.assertAlmostEqual(em(2, 3), 0.4657, 4)
self.assertAlmostEqual(em(3, 1), 0, 4)
self.assertAlmostEqual(em(3, 2), 0, 4)
self.assertAlmostEqual(em(3, 3), 0, 4)
if __name__ == '__main__':
import sys
HMM_FILENAME = sys.argv[1] if len(sys.argv) >= 2 else 'example.hmm'
OBS_FILENAME = sys.argv[2] if len(sys.argv) >= 3 else 'observations.txt'
unittest.main()
|
gpl-3.0
|
arielmachini/Colibri
|
Biblioteca maestra/Implementación/Aplicación Web/colibri/app/rol.eliminar.procesar.php
|
2989
|
<!DOCTYPE html>
<?php
include_once '../lib/ControlAcceso.Class.php';
ControlAcceso::requierePermiso(PermisosSistema::PERMISO_ROLES);
include_once '../modelo/BDConexion.Class.php';
$DatosFormulario = $_POST;
BDConexion::getInstancia()->autocommit(false);
BDConexion::getInstancia()->begin_transaction();
$query = "DELETE FROM " . BDCatalogoTablas::BD_TABLA_ROL_PERMISO . " "
. "WHERE id_rol = {$DatosFormulario["id"]}";
$consulta = BDConexion::getInstancia()->query($query);
if (!$consulta) {
BDConexion::getInstancia()->rollback();
//arrojar una excepcion
die(BDConexion::getInstancia()->errno);
}
$query = "DELETE FROM " . BDCatalogoTablas::BD_TABLA_USUARIO_ROL . " "
. "WHERE id_rol = {$DatosFormulario["id"]}";
$consulta = BDConexion::getInstancia()->query($query);
if (!$consulta) {
BDConexion::getInstancia()->rollback();
//arrojar una excepcion
die(BDConexion::getInstancia()->errno);
}
$query = "DELETE FROM " . BDCatalogoTablas::BD_TABLA_ROL . " "
. "WHERE id = {$DatosFormulario["id"]}";
$consulta = BDConexion::getInstancia()->query($query);
if (!$consulta) {
BDConexion::getInstancia()->rollback();
//arrojar una excepcion
die(BDConexion::getInstancia()->errno);
}
BDConexion::getInstancia()->commit();
BDConexion::getInstancia()->autocommit(true);
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../lib/bootstrap-4.1.1-dist/css/bootstrap.css" />
<link rel="stylesheet" href="../lib/open-iconic-master/font/css/open-iconic-bootstrap.css" />
<script type="text/javascript" src="../lib/JQuery/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../lib/bootstrap-4.1.1-dist/js/bootstrap.min.js"></script>
<title><?php echo Constantes::NOMBRE_SISTEMA; ?> - Eliminar Rol</title>
</head>
<body>
<?php include_once '../gui/navbar.php'; ?>
<div class="container">
<p></p>
<div class="card">
<div class="card-header">
<h3>Eliminar Rol</h3>
</div>
<div class="card-body">
<?php if ($consulta) { ?>
<div class="alert alert-success" role="alert">
Operación realizada con éxito.
</div>
<?php } ?>
<?php if (!$consulta) { ?>
<div class="alert alert-danger" role="alert">
Ha ocurrido un error.
</div>
<?php } ?>
<hr />
<h5 class="card-text">Opciones</h5>
<a class="btn btn-primary" href="roles.php">
<span class="oi oi-account-logout"></span> Salir
</a>
</div>
</div>
</div>
<?php include_once '../gui/footer.php'; ?>
</body>
</html>
|
gpl-3.0
|
sx02exp21/midicsv-cmake
|
master/test/src/crc32_func.cpp
|
167
|
int GetCrc32(const string& my_string) {
boost::crc_32_type result;
result.process_bytes(my_string.data(), my_string.length());
return result.checksum();
}
|
gpl-3.0
|
peterpilgrim/javaee7-developer-handbook
|
ch02/standalone-owb/src/main/java/je7hb/standalone/alternatives/XenoniqueFoodProcessor.java
|
1182
|
/*******************************************************************************
* 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.alternatives;
import javax.annotation.Priority;
import javax.enterprise.inject.Alternative;
import javax.interceptor.Interceptor;
/**
* The type XenoniqueFoodProcessor
*
* @author Peter Pilgrim (peter)
*/
@Alternative
@Priority(Interceptor.Priority.APPLICATION+100)
public class XenoniqueFoodProcessor implements FoodProcessor {
@Override
public String sayBrand() {
return "Xenonique";
}
}
|
gpl-3.0
|
tessak22/Incredible-Code-Test
|
wp-content/themes/strappress/sidebar-contact.php
|
797
|
<?php
/**
* Main Widget Template
*
*
* @file sidebar.php
* @package StrapPress
* @author Brad Williams
* @copyright 2010 - 2015 Brag Interactive
* @license license.txt
* @version Release: 3.3.6
* @link http://codex.wordpress.org/Theme_Development#Widgets_.28sidebar.php.29
* @since available since Release 1.0
*/
?>
<div class="col-lg-3">
<aside id="widgets" class="well">
<?php responsive_widgets(); // above widgets hook ?>
<?php if (!dynamic_sidebar('contact-widget')) : ?>
<?php endif; //end of right-sidebar ?>
<?php responsive_widgets_end(); // after widgets hook ?>
</aside><!-- end of widgets -->
</div>
</div>
|
gpl-3.0
|
Emergen/zivios-panel
|
application/library/Zend/Validate/Exception.php
|
1102
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
*/
/**
* @see Zend_Exception
*/
// require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Exception extends Zend_Exception
{}
|
gpl-3.0
|
wereallfeds/webshag
|
webshag/gui/gui_widgets.py
|
4927
|
# -*- coding: utf-8 -*-
## ################################################################# ##
## (C) SCRT - Information Security, 2007 - 2008 // author: ~SaD~ ##
## ################################################################# ##
## 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. ##
## ################################################################# ##
## last mod: 2008-11-03
import wx
## ################################################################# ##
## CLASS: ImportDialog
## ################################################################# ##
class ImportDialog(wx.Dialog):
def __init__(self, parent, coordinator, cb_import):
wx.Dialog.__init__(self, parent, -1, u'Import Results...', size=(600, 400), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
importPanel = Import_Panel(self, coordinator, cb_import)
rootSizer = wx.BoxSizer()
rootSizer.Add(importPanel, 1, wx.EXPAND)
self.SetSizer(rootSizer)
class Import_Panel(wx.Panel):
def __init__(self, parent, coordinator, cb_import):
wx.Panel.__init__(self, parent)
# Variables ##############################################
self.__parent = parent
self.__coordinator = coordinator
self.__callback = cb_import
hosts = self.__coordinator.get_info_results()
ports = self.__coordinator.get_portscan_results()
roots = self.__coordinator.get_spider_results()
# Widgets ##############################################
self.__hosts_list = wx.ListBox(self, -1, choices=hosts, style=wx.LB_MULTIPLE)
self.__openPorts_list = wx.ListBox(self, -1, choices=ports, style=wx.LB_MULTIPLE)
self.__roots_list = wx.ListBox(self, -1, choices=roots, style=wx.LB_MULTIPLE)
self.__apply_button = wx.Button(self, wx.ID_APPLY, u'&Apply')
self.__close_button = wx.Button(self, wx.ID_CLOSE, u'&Close')
self.__command_text = wx.StaticText(self, -1, u'')
# Event Bindings ##############################################
self.Bind(wx.EVT_BUTTON, self.__onCloseButton, id=self.__close_button.GetId())
self.Bind(wx.EVT_BUTTON, self.__onApplyButton, id=self.__apply_button.GetId())
listsSizerGrid = wx.GridBagSizer()
listsSizerGrid.Add(wx.StaticText(self, -1, u'hosts:'), (0, 0), (1, 1), wx.ALIGN_BOTTOM | wx.ALIGN_LEFT | wx.LEFT, 5)
listsSizerGrid.Add(wx.StaticText(self, -1, u'roots:'), (0, 1), (1, 1), wx.ALIGN_BOTTOM | wx.ALIGN_LEFT | wx.LEFT, 5)
listsSizerGrid.Add(wx.StaticText(self, -1, u'ports:'), (0, 2), (1, 1), wx.ALIGN_BOTTOM | wx.ALIGN_LEFT | wx.LEFT, 5)
listsSizerGrid.Add(self.__hosts_list, (1, 0), (1, 1), wx.EXPAND | wx.LEFT, 5)
listsSizerGrid.Add(self.__roots_list, (1, 1), (1, 1), wx.EXPAND | wx.LEFT, 5)
listsSizerGrid.Add(self.__openPorts_list, (1, 2), (1, 1), wx.EXPAND | wx.LEFT, 5)
listsSizerGrid.AddGrowableCol(0)
listsSizerGrid.AddGrowableCol(1)
listsSizerGrid.AddGrowableRow(1)
buttonGridSizer = wx.GridBagSizer()
buttonGridSizer.Add(self.__command_text, (0, 0), (1, 1), wx.ALIGN_CENTER_VERTICAL)
buttonGridSizer.Add(self.__close_button, (0, 1), (1, 1), wx.EXPAND)
buttonGridSizer.Add(self.__apply_button, (0, 2), (1, 1), wx.EXPAND)
buttonGridSizer.AddGrowableCol(0)
rootSizer = wx.BoxSizer(wx.VERTICAL)
rootSizer.Add(listsSizerGrid, 1, wx.EXPAND)
rootSizer.Add(buttonGridSizer, 0, wx.EXPAND | wx.TOP, 5)
self.SetSizer(rootSizer)
def __onCloseButton(self, event):
self.__parent.Close()
def __onApplyButton(self, event):
hosts_list = [self.__hosts_list.GetString(index) for index in self.__hosts_list.GetSelections()]
ports_list = [self.__openPorts_list.GetString(index) for index in self.__openPorts_list.GetSelections()]
roots_list = [self.__roots_list.GetString(index) for index in self.__roots_list.GetSelections()]
hosts_string = u','.join(hosts_list)
ports_string = u','.join(ports_list)
roots_string = u','.join(roots_list)
self.__callback(hosts_string, ports_string, roots_string)
self.__parent.Close()
|
gpl-3.0
|
hcasse/maat
|
maat/config.py
|
7891
|
# MAAT top-level script
# Copyright (C) 2016 H. Casse <hugues.casse@laposte.net>
#
# 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/>.
"""Maat module providing configuration classes."""
import imp
import os.path
import sys
import maat
from maat import common
from maat import env
from maat import io
from maat import action
from maat import recipe
# public variables
GOAL = None
"""Goal corresponding to the configuration"""
# configuration state
config_list = [] # list of configuration modules
updated = False
loaded = False
configured = False
win_list = ['win32', 'win64', 'cygwin']
comments = { }
# convenient functions
def host():
"""Return a string identifying the host platform."""
info = os.uname()
return "%s %s %s %s" % (info[0], info[1], info[2], info[4])
def register(config):
"""Function used to register a configuration."""
if config not in config_list:
config_list.append((config))
def set(id, val):
"""Set the value to the given identifier in the configuration environment."""
env.conf.map[id] = val
def set_if(id, fun):
"""Set a configuration item if it is not set. To obtain the value, call the function fun."""
if not is_set(id):
env.conf.set(id, fun())
global updated
updated = True
def set_comment(id, com):
"""Set a comment associated with a configuration variable."""
comments[id] = com
def setup():
"""Set up the configuration from scratch."""
# look for a build path
bpath = env.root["BPATH"]
if bpath:
env.conf["BPATH"] = bpath
# builtin configuration
global win_list
set_if("IS_WINDOWS", lambda : sys.platform in win_list)
set_if("IS_UNIX", lambda : sys.platform not in win_list)
def load(do_config):
"""Called to load the configuration file.
do_config informs it is a load for configuration and
therefore do not alert user for incompatibility."""
global loaded
if loaded:
return
cpath = env.topdir / "config.py"
if not cpath.exists():
setup()
else:
# load the configuration
mod = imp.load_source('config.py', str(cpath))
env.conf.map = mod.__dict__
# check host compatibility
try:
h = env.conf.map['ELF_HOST']
if h != None and h != host():
# warn if we are not in configuration
if not do_config:
print("WARNING: config.py for a different host found!\nReconfigure it with ./make.py config")
# reset configuration else
else:
env.conf.map = { }
except KeyError as e:
pass
loaded = True
def save():
"""Save the configuration to the disk."""
env.conf.set("ELF_HOST", host())
f = open(str(env.topdir / 'config.py'), "w")
f.write("# generated by Maat\n")
f.write("# You're ALLOWED modifying this file to tune or complete your configuration\n")
for k in env.conf.map:
if not k.startswith("__"):
com = None
if comments.has_key(k):
com = comments[k]
if com != None and "\n" in com:
f.write("# %s\n" % com.replace("\n", "\n# "))
f.write("%s = %s" % (k, repr(env.conf.map[k])))
if com != None and "\n" not in com:
f.write("\t# %s" % com)
f.write("\n")
f.close()
def is_set(id):
"""Test if a configuration item is set (exists, not None, not empty string, not 0)."""
try:
return env.conf.map[id]
except KeyError as e:
return False
def begin():
"""Begin the configuration."""
if configured:
return
if not loaded:
load(False)
configured = True
def make(ctx = io.Context()):
"""Build a configuration."""
# set up basis
setup()
# launch module configuration
todo = list(config_list)
for conf in config_list:
conf.result = None
while todo:
conf = todo.pop()
if conf.result == None:
if conf.done():
conf.result = True
else:
conf.perform(ctx)
# if needed, output the configuration file
if updated:
save()
# install config goal
GOAL = recipe.goal("config", [], action.FunAction(make))
GOAL.DESCRIPTION = "build configuration"
# Config class
class Config(recipe.File):
"""Configuration node: it is responsible for performing a configuration
step and, if successful, chain with sub-configuration items."""
name = None
blocking = False
deps = None
result = None
def __init__(self, name, blocking = False, deps = []):
recipe.File.__init__(self, common.Path("config/%s" % name))
self.name = name
self.blocking = blocking
self.deps = []
self.result = None
def succeed(self, msg = None):
"""Call to record success of the configuration."""
self.result = True
self.ctx.print_action_success(msg)
global updated
updated = True
def fail(self, msg = None):
"""Called to record a failed configuration."""
self.result = False
if self.blocking:
common.error("cannot configure %s: %s" % self.name, msg)
else:
self.ctx.print_action_failure(msg)
def perform(self, ctx):
"""Call to perform the configuration of this item and of its
dependent configuration item."""
self.ctx = ctx
# look in dependencies
for dep in self.deps:
if dep.result == None:
dep.perform(ctx)
if not dep.result:
fail("missing dependency on %s" % dep.name)
# perform self configuration
self.configure(ctx)
def configure(self, ctx):
"""Perform configuration for this item. Must call one of fail()
or succeed() to record configuration result."""
self.fail()
def done(self):
"""Test if the configuration is already available."""
return False
class VarConfig(Config):
def __init__(self, name, var, blocking = False, deps = []):
Config.__init__(self, name, blocking, deps)
self.var = var
def done(self):
return env.conf.is_configured(self.var)
def needs_update(self):
return not self.done()
class FindProgram(VarConfig):
"""Find the path of a program and display associated message.
The label is displayed during the look-up, one of progs
is look in the given paths including system path if syspath is True.
If sysfirst is true, look system paths first.
If the variable var already exists and is set, do nothing.
Else store the result in configuration environment."""
def __init__(self, label, var, progs, paths = [], syspath = True, sysfirst = True):
VarConfig.__init__(self, label, var)
self.progs = maat.list_of(progs)
self.paths = paths
self.syspath = syspath
self.sysfirst = sysfirst
def configure(self, ctx):
# include system paths
if self.syspath:
spaths = os.getenv("PATH").split(os.pathsep)
if self.sysfirst:
lpaths = spaths + self.paths
else:
lpaths = self.paths + spaths
else:
lpaths = self.paths
# lookup
ctx.print_action(self.name)
fpath = None
for path in lpaths:
for prog in self.progs:
ppath = os.path.join(path, prog)
if os.access(ppath, os.X_OK):
if path in self.paths:
fpath = ppath
else:
fpath = prog
break
# process result
env.conf.set(self.var, fpath)
if fpath:
self.succeed("found: %s" % fpath)
else:
self.fail("not found")
def find_program(label, var, progs, paths = [], syspath = True, sysfirst = True):
"""Add a configuration node looking for a program with the given label,
setting the variable var, looking for program in progs and in the given
paths. If syspath is set to False, do not look in system path. If sysfirst
is set to False, do not first look in system paths."""
register(FindProgram(label, var, progs, paths, syspath, sysfirst))
|
gpl-3.0
|
DovidM/eyeStorm-nodeJS
|
server/src/test/issues/mutations/updateIssueTest.php
|
4107
|
<?php
require_once(__DIR__ . '/../../../../vendor/autoload.php');
require_once(__DIR__ . '/../helpers.php');
class UpdateIssueTest extends IssueTestHelper {
/**
* Sends graphql query
*
* @param $variableTypes - graphql variables with type. Example: ['$num: => 'ID', '$limit': 'Int']
* @param $variableValues - values to give variables listed as keys to $variableTypes
* @param $loggedIn - if user is logged in or not
* @param $userLevel - what level user should be
*/
protected function helpTestArgs(array $variableTypes, array $variableValues, bool $loggedIn = true,
int $userLevel = 3, bool $correctPassword = true) {
$user = TestHelper::searchArray($this->Database->GenerateRows->users, function (array $currentUser, int $userLevel) {
return $currentUser['level'] == $userLevel;
}, $userLevel);
$variablesStrings = TestHelper::convertVariableArrayToGraphql(array_merge($variableTypes, ['$password' => 'String!']));
if (!$correctPassword) {
$user['password'] .= '.'; // the dot is random char to invalidate password
}
return $this->request([
'query' => "mutation updateIssue({$variablesStrings['types']}) {
updateIssue({$variablesStrings['mappings']}) {
name
public
}
}",
'variables' => array_merge($variableValues, ['password' => $user['password']])
], $loggedIn ? TestHelper::getJwt($user) : '');
}
function testCannotModifyIfNotLoggedIn() {
$data = $this->helpTestArgs(['$name' => 'String'], ['name' => TestHelper::faker()->name()], false);
$actualName = Db::query("SELECT name FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchColumn();
$this->assertEquals($this->Database->GenerateRows->issues[0]['name'], $actualName);
}
function testCannotModifyIfBadPassword() {
$data = $this->helpTestArgs(['$name' => 'String'], ['name' => TestHelper::faker()->word()],
true, 3, false);
$actualName = Db::query("SELECT name FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchColumn();
$this->assertEquals($this->Database->GenerateRows->issues[0]['name'], $actualName);
}
function testCannotModifyIfLevelLessThanThree() {
$data = $this->helpTestArgs(['$name' => 'String'], ['name' => TestHelper::faker()->word()], true, rand(1, 2));
$actualName = Db::query("SELECT name FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchColumn();
$this->assertEquals($this->Database->GenerateRows->issues[0]['name'], $actualName);
}
function testCanModifyName() {
$newName = TestHelper::faker()->word();
$data = $this->helpTestArgs(['$name' => 'String'], ['name' => $newName]);
$actualName = Db::query("SELECT name FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchColumn();
$this->assertEquals($newName, $actualName);
}
function testCanMakeIssuePublic() {
$data = $this->helpTestArgs(['$public' => 'Boolean'], ['public' => true]);
$actualPublicStatus = Db::query("SELECT ispublic, madepub FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchAll(PDO::FETCH_ASSOC)[0];
$this->assertEquals(1, $actualPublicStatus['ispublic']);
$this->assertEquals(date('Y-m-d'), $actualPublicStatus['madepub']);
}
function testCannotMakeIssuePrivate() {
Db::query("UPDATE issues SET ispublic = 1");
$data = $this->helpTestArgs(['$public' => 'Boolean'], ['public' => false]);
$actualPublicStatus = Db::query("SELECT ispublic FROM issues WHERE num = ?", [$this->Database->GenerateRows->issues[0]['num']])->fetchColumn();
$this->assertEquals(1, $actualPublicStatus);
Db::query("UPDATE issues SET ispublic = 0");
}
}
?>
|
gpl-3.0
|
michaelerule/neurotools
|
jobs/__init__.py
|
300
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import division
from __future__ import nested_scopes
from __future__ import generators
from __future__ import unicode_literals
from __future__ import print_function
|
gpl-3.0
|
Logicworks/puppet-foreman
|
spec/acceptance/foreman_remote_file_spec.rb
|
406
|
require 'spec_helper_acceptance'
describe 'remote_file works' do
let(:pp) do
<<-EOS
foreman::remote_file {"/var/tmp/test":
remote_location => "https://codeload.github.com/theforeman/puppet-foreman/tar.gz/9.0.0",
}
EOS
end
it_behaves_like 'a idempotent resource'
describe file('/var/tmp/test') do
its(:md5sum) { should eq '5ef89571e3775b4bc17e4f5a55d1c146' }
end
end
|
gpl-3.0
|
Dangetsu/vnr
|
Frameworks/Sakura/py/apps/reader/managers/jsonapi.py
|
5201
|
# coding: utf8
# jsonman.py
# 8/10/2013 jichi
import json, re
from datetime import datetime
from operator import attrgetter
from sakurakit.skdebug import dprint, dwarn
import dataman
KEYS = (
'itemId',
'timestamp',
'local',
'visitCount', 'commentCount', 'playUserCount', 'subtitleCount',
'title0',
'romajiTitle0',
'brand0',
'date0',
'fileSize0',
'imageUrl0',
'series0',
'okazu0',
'otome0',
'tags0',
'artists0',
'sdartists0',
'writers0',
'musicians0',
'scapeMedian0',
'scapeCount0',
'overallScore0',
'overallScoreCount0',
'overallScoreSum0',
'ecchiScore0',
'ecchiScoreCount0',
'ecchiScoreSum0',
)
class GameInfoEncoder(json.JSONEncoder):
def default(self, obj):
"""@reimp
@param obj GameInfo
@return dict
"""
return {k.replace('0',''):getattr(obj,k) for k in KEYS}
def gameinfo(start=0, count=100, sort=None, reverse=None, filters=None):
"""
@param* start int
@param* count int
@param* sort str
@param* reverse bool
@param* filters unicode JSON
@return unicode json, int left, int total
"""
dprint("enter: start = %i, count = %i, sort = %s, reverse = %s, filters =" % (start, count, sort, reverse), filters)
dm = dataman.manager()
data = dm.getGameInfo()
if filters:
try:
params = json.loads(filters)
error = False
searchRe = searchDate = searchId = None
search = params.get('search') # unicode
searchLargeSize = None # bool or None
if search:
if (search.startswith('20') or search.startswith('19')) and search.isdigit():
searchDate = search
elif search.startswith('#') and search[1:].isdigit():
searchId = int(search[1:])
elif search in ('GB', 'gb'):
searchLargeSize = True
elif search in ('MB', 'mb'):
searchLargeSize = False
if not searchDate and not searchId and searchLargeSize is None:
try: searchRe = re.compile(search, re.IGNORECASE)
except Exception, e:
dwarn(e)
error = True
if error:
data = []
else:
l = []
year = params.get('year') # int
month = params.get('month') # int
local = params.get('local') # bool
genre = params.get('genre') # str
t = params.get('time') # str
upcoming = t == 'upcoming' # bool
recent = t == 'recent' # bool
okazu = otome = None # bool
if genre is not None:
otome = genre == 'otome'
if not otome:
okazu = genre == 'nuki' # bool
tags = params.get('tags') # unicode
if tags:
tags = map(unicode.lower, tags)
for it in data:
if searchLargeSize is not None:
if not it.fileSize0 or it.fileSize0 < 1024 * 1024: continue
if searchLargeSize:
if it.fileSize0 < 1024 * 1024 * 1024: continue
else:
if it.fileSize0 >= 1024 * 1024 * 1024: continue
if otome is not None and otome != it.otome0: continue
if okazu is not None and okazu != it.okazu0: continue
if local is not None and local != it.local: continue
if upcoming and not it.upcoming0: continue
if recent and not it.recent0: continue
dt = None
if year or month:
if not it.dateObject0: continue
dt = it.dateObject0
if month and month != dt.month: continue
if year:
if year < 2000: # aggregate 199x together
if dt.year >= 2000 or dt.year < 1990: continue
elif year != dt.year: continue
if search:
if searchRe:
matched = False
for k in 'title0', 'romajiTitle0', 'brand0', 'series0', 'tags0', 'artists0', 'sdartists0', 'writers0', 'musicians0':
v = getattr(it, k)
if v and searchRe.search(v):
matched = True
break
if not matched:
continue
elif searchDate:
if not dt:
if not it.dateObject0: continue
dt = it.dateObject0
if not dt.strftime("%Y%m%d").startswith(searchDate): continue
elif searchId:
if searchId != it.itemId: continue
if tags:
t = it.tags0
if not t: continue
t = t.lower()
contd = False
for k in tags:
if k not in t:
contd = True
break
if contd: continue
l.append(it)
data = l
except ValueError, e: dwarn(e)
total = len(data)
if data:
if not sort and reverse:
data.reverse()
elif sort:
k = sort if sort in KEYS else sort + '0'
data.sort(key=attrgetter(k), reverse=bool(reverse))
if start:
data = data[start:]
if count and count < len(data):
data = data[:count]
left = len(data)
dprint("leave: count = %i/%i" % (left, total))
return json.dumps(data, #[it for it in data if it.image], # Generator not supported
cls=GameInfoEncoder), left, total
# EOF
|
gpl-3.0
|
lecousin/net.lecousin.framework-0.1
|
net.lecousin.framework.media/src/net/lecousin/framework/media/ui/MediaPlayerWindow.java
|
1078
|
package net.lecousin.framework.media.ui;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
public class MediaPlayerWindow extends ApplicationWindow {
public MediaPlayerWindow() {
super(null);
}
private MediaPlayerControl player = null;
@Override
protected final Control createContents(Composite container) {
player = createMediaPlayer(container);
getShell().setSize(700, 500);
Rectangle r = getShell().getDisplay().getBounds();
getShell().setLocation(r.x + r.width/2 - 350, r.y + r.height/2 - 250);
return player.getControl();
}
@Override
protected final void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(getTitle());
}
public MediaPlayerControl getPlayer() { return player; }
protected MediaPlayerControl createMediaPlayer(Composite parent) {
return new MediaPlayerControl(parent);
}
protected String getTitle() { return "Media Player"; }
}
|
gpl-3.0
|
holdam/washingmachine-booking
|
WashingmachineBackend/src/test/java/UserDAOTest.java
|
3286
|
import core.RoleHelper;
import api.UserDTO;
import db.BookingDAO;
import db.UserDAO;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class UserDAOTest {
private BookingDAO bookingDAO;
private UserDAO userDAO;
private final String USERNAME_1 = "user";
private final String USERNAME_1_ALTERNATIVE = "UsEr";
private final String USERNAME_2 = "user2";
private final String USER_1_PASSWORD = "password_that_should_have_been_hashed_and_salted";
private final String USER_1_SALT = "salt";
private final String APARTMENT_1 = "apartment";
private final String NAME_1 = "name";
@Before
public void setup() {
DBI dbi = new DBI("jdbc:postgresql://localhost:5432/test", "postgres", "root");
bookingDAO = dbi.onDemand(BookingDAO.class);
userDAO = dbi.onDemand(UserDAO.class);
userDAO.createRoleTable();
userDAO.createUsersTable();
}
@After
public void tearDown() throws InterruptedException {
userDAO.truncateUsersTable();
}
@Test
public void insertUserShouldWork() {
int numberInserted = userDAO.insertUser(USERNAME_1, USER_1_PASSWORD, USER_1_SALT, NAME_1, APARTMENT_1, RoleHelper.ROLE_DEFAULT);
assertEquals(1, numberInserted);
}
@Test(expected = UnableToExecuteStatementException.class)
public void usernamesAreUnique() {
insertUser1();
insertUser1();
}
@Test
public void authenticateUserShouldWork() {
insertUser1();
boolean login = userDAO.authenticateUser(USERNAME_1, USER_1_PASSWORD);
assertTrue(login);
login = userDAO.authenticateUser(USERNAME_2, USER_1_PASSWORD);
assertFalse(login);
}
@Test
public void getUserShouldWork() {
insertUser1();
UserDTO userDTO = userDAO.getUser(USERNAME_1);
assertEquals(USERNAME_1, userDTO.getName());
assertEquals(RoleHelper.ROLE_DEFAULT, userDTO.getRole());
assertEquals(APARTMENT_1, userDTO.getApartment());
assertEquals(NAME_1, userDTO.getRealName());
userDTO = userDAO.getUser(USERNAME_2);
assertEquals(null, userDTO);
}
@Test
public void getSaltForUserShouldWork() {
insertUser1();
String salt = userDAO.getSaltForUser(USERNAME_1);
assertEquals(salt, USER_1_SALT);
salt = userDAO.getSaltForUser(USERNAME_2);
assertEquals(null, salt);
}
@Test
public void usernameCasingShouldNotMatterForAuthentication() {
insertUser1();
boolean login = userDAO.authenticateUser(USERNAME_1_ALTERNATIVE, USER_1_PASSWORD);
assertTrue(login);
}
@Test
public void usernameCasingShouldNotMatterForGettingSalt() {
insertUser1();
String salt = userDAO.getSaltForUser(USERNAME_1_ALTERNATIVE);
assertEquals(USER_1_SALT, salt);
}
private void insertUser1() {
userDAO.insertUser(USERNAME_1, USER_1_PASSWORD, USER_1_SALT, NAME_1, APARTMENT_1, RoleHelper.ROLE_DEFAULT);
}
}
|
gpl-3.0
|
binary42/FuzzyFlockingSimulator
|
src/com/fuzzy/simulator/CAnimat.java
|
8141
|
/**
* Again, heavily drawn from Lalena's sim. Contains constructor and general
* movement method for sim. The fuzzy alg. is in CFlock Move
*/
package com.fuzzy.simulator;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Vector;
import com.fuzzy.controller.CFuzzyController;
import com.fuzzy.controller.CFuzzyStruct;
// Rule class structure
class CRuleStruct{
public static String rule1 = "alignment";
public static String rule2 = "attraction";
public static String rule3 = "repulsion";
}
public class CAnimat {
public static int DetectionRange;
public static int SeparationRange;
public static boolean showRanges = false;
protected Point location = new Point( 0, 0 );
private int _currentTheta;
protected Color _color;
protected static Dimension s_map = new Dimension( CFlock.DIM, CFlock.DIM );
private double _currentSpeed;
private int _maxTurnTheta;
// Each Animat gets a fuzzy controller
private CFuzzyController _animatController;
public CAnimat( Color colorIn ) {
this((int)( Math.random() * s_map.width ), (int)( Math.random() * s_map.height ), (int)( Math.random() * 360 ), colorIn );
}
public CAnimat( int xIn, int yIn, int thetaIn, Color colorIn ){
location.x = xIn;
location.y = yIn;
_currentTheta = thetaIn;
_color = colorIn;
// Hard code # of rule sets for now...
_animatController = new CFuzzyController( 3 );
InitController();
}
private void InitController()
{
Vector<String> files = new Vector<String>( 3 );
// Hardcode order TODO - change this hack
files.add( "../rules/alignment_rules.fcl" );
files.add( "../rules/attraction_rules.fcl" );
files.add( "../rules/repulsion_rules.fcl" );
_animatController.LoadFCL( files );
}
public static void SetMapSize( Dimension sizeIn ) {
s_map = sizeIn;
}
public void SetSpeed( int speedIn ) {
_currentSpeed = speedIn;
}
public void SetMaxTurnTheta( int thetaIn ) {
_maxTurnTheta = thetaIn;
}
public Color GetColor() {
return _color;
}
public void draw( Graphics g) {
g.setColor( this._color);
g.fillArc( location.x - 12, location.y - 12, 24, 24, _currentTheta + 180 - 20, 40 );
if( showRanges) {
drawRanges( g );
}
}
// Lalena
public void drawRanges( Graphics g ) {
drawCircles(g, location.x, location.y );
boolean top = ( location.y < DetectionRange );
boolean bottom = ( location.y > s_map.height - DetectionRange );
if (location.x < DetectionRange) { // if left
drawCircles(g, s_map.width + location.x, location.y );
if (top) {
drawCircles(g, s_map.width + location.x, s_map.height + location.y );
}
else if ( bottom ) {
drawCircles(g, s_map.width + location.x, location.y - s_map.height );
}
} else if ( location.x > s_map.width - DetectionRange ) { // if right
drawCircles(g, location.x - s_map.width, location.y );
if ( top ) {
drawCircles(g, location.x - s_map.width, s_map.height + location.y );
}
else if ( bottom ) {
drawCircles(g, location.x - s_map.width, location.y - s_map.height );
}
}
if ( top ) {
drawCircles( g, location.x, s_map.height + location.y );
}
else if ( bottom ) {
drawCircles( g, location.x, location.y - s_map.height );
}
}
protected void drawCircles( Graphics g, int x, int y ) {
g.setColor( new Color((int)_color.getRed()/2, (int)_color.getGreen()/2, (int)_color.getBlue()/2 ) );
g.drawOval( x-DetectionRange, y-DetectionRange, 2*DetectionRange, 2*DetectionRange );
g.setColor( _color);
g.drawOval( x-SeparationRange, y-SeparationRange, 2*SeparationRange, 2*SeparationRange );
}
// Lalena
public void Move( int newHeadingIn ) {
// determine if it is better to turn left or right for the new heading
int left = ( newHeadingIn - _currentTheta + 360 ) % 360;
int right = ( _currentTheta - newHeadingIn + 360 ) % 360;
// after deciding which way to turn, find out if we can turn that much
int thetaChange = 0;
if (left < right) {
// if left > than the max turn, then we can't fully adopt the new heading
thetaChange = Math.min( _maxTurnTheta, left );
}
else {
// right turns are negative degrees
thetaChange = -Math.min( _maxTurnTheta, right );
}
// Make the turn
_currentTheta = ( _currentTheta + thetaChange + 360 ) % 360;
// Now move currentSpeed pixels in the direction the animat now faces.
// Note: Because values are truncated, a speed of 1 will result in no
// movement unless the animat is moving exactly vertically or horizontally.
location.x += (int)( _currentSpeed * Math.cos( _currentTheta * Math.PI/180) ) + s_map.width;
location.x %= s_map.width;
location.y -= (int)( _currentSpeed * Math.sin( _currentTheta * Math.PI/180) ) - s_map.height;
location.y %= s_map.height;
}
public Point GetLocation() {
return location;
}
public int GetCurrentHeading()
{
return _currentTheta;
}
public double GetCurrentSpeed()
{
return _currentSpeed;
}
public int GetLocationDegrees( CAnimat otherAnimatIn )
{
int dx = otherAnimatIn.GetLocation().x - location.x;
int dy = otherAnimatIn.GetLocation().y - location.y;
// atan2 returns radians
int out = (int)((Math.atan2( dy, dx ) * 180)/Math.PI);
return out;
}
// Lalena ---------------
public int GetDistance( CAnimat otherAnimatIn ) {
int dX = otherAnimatIn.GetLocation().x - location.x;
int dY = otherAnimatIn.GetLocation().y - location.y;
return (int)Math.sqrt( Math.pow( dX, 2 ) + Math.pow( dY, 2 ));
}
public int GetDistance( Point pointIn ) {
int dX = pointIn.x - location.x;
int dY = pointIn.y - location.y;
return (int)Math.sqrt( Math.pow( dX, 2 ) + Math.pow( dY, 2 ));
}
// ---------------
public int GetFuzzyVelocityAndHeading( CAnimat otherAnimatIn )
{
Point newPointOut = new Point( 0, 0 );
// Algorithm ---------------------------------------------------------
// Set variables for each fuzzy attribute
int distance = this.GetDistance( otherAnimatIn );
// Direction - Distance difference in degrees from neighbor
_animatController.SetVariable( CRuleStruct.rule1, "distance", distance );
int direction = ( ( otherAnimatIn.GetCurrentHeading() + 180 ) % 360 ) - 180;
_animatController.SetVariable( CRuleStruct.rule1, "direction", direction );
_animatController.SetVariable( CRuleStruct.rule1, "speed", otherAnimatIn.GetCurrentSpeed() );
// Position needs degree -180 to 180 of location of other animat
int position = ( ( this.GetLocationDegrees( otherAnimatIn ) + 180 ) % 360 ) - 180;
_animatController.SetVariable( CRuleStruct.rule2, "distance", distance );
_animatController.SetVariable( CRuleStruct.rule2, "position", position );
_animatController.SetVariable( CRuleStruct.rule3, "distance", distance );
_animatController.SetVariable( CRuleStruct.rule3, "position", position );
// Evaluate for each rules set - alignment/attraction/repulsion
_animatController.Evaluate();
// Set weights for controller - for output
_animatController.SetWeights(.5, .5, .5);// alignment, attraction, repulsion
// Let's do an average sum of weighted speeds
// _currentSpeed = _animatController.GetWeightedAvgSumSpeed();
// Let's do an average sum of weighted directions
int sumDirOut = _animatController.GetWeightedAvgSumDirections();
// Get New position and velocity from controller
return sumDirOut;
}
public boolean Equals( CAnimat animatIn )
{
return ( this._color == animatIn._color );
}
}
|
gpl-3.0
|
MariFormiga/sisreagent
|
Fornecedores/models.py
|
546
|
from django.db import models
from django.utils import timezone
class Fornecedores (models.Model):
Nome_Fantasia = models.CharField(max_length=200)
CNPJ = models.CharField(max_length=200)
Endereço = models.CharField(max_length=200)
Entrega = models.CharField(max_length=200)
Atraso = models.CharField(max_length=200)
Pagamento = models.CharField(max_length=200)
Email = models.CharField(max_length=200)
Observação = models.CharField(max_length=500)
class Meta:
verbose_name_plural = 'Fornecedores'
|
gpl-3.0
|
abmindiarepomanager/ABMOpenMainet
|
Mainet1.1/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/master/service/TbCfcApplicationMstService.java
|
1449
|
/*
* Created on 19 Aug 2015 ( Time 17:12:00 )
* Generated by Telosys Tools Generator ( version 2.1.1 )
*/
package com.abm.mainet.common.master.service;
import java.util.List;
import com.abm.mainet.common.master.dto.TbCfcApplicationMst;
/**
* Business Service Interface for entity TbCfcApplicationMst.
*/
public interface TbCfcApplicationMstService {
/**
* Loads an entity from the database using its Primary Key
* @param apmApplicationId
* @return entity
*/
TbCfcApplicationMst findById(Long apmApplicationId);
/**
* Loads all entities.
* @return all entities
*/
List<TbCfcApplicationMst> findAll();
/**
* Saves the given entity in the database (create or update)
* @param entity
* @return entity
*/
TbCfcApplicationMst save(TbCfcApplicationMst entity);
/**
* Updates the given entity in the database
* @param entity
* @return
*/
TbCfcApplicationMst update(TbCfcApplicationMst entity);
/**
* Creates the given entity in the database
* @param entity
* @return
*/
TbCfcApplicationMst create(TbCfcApplicationMst entity);
/**
* Deletes an entity using its Primary Key
* @param apmApplicationId
*/
void delete(Long apmApplicationId);
/**
*
* @param serviceId
* @param orgId
* @return
*/
int checkForTransactionExist(Long serviceId, Long orgId);
}
|
gpl-3.0
|
Aeronavics/MissionPlanner
|
GCSViews/FlightPlanner.Designer.cs
|
92068
|
using MissionPlanner.Controls;
namespace MissionPlanner.GCSViews
{
partial class FlightPlanner
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
if (currentMarker != null)
currentMarker.Dispose();
if (drawnpolygon != null)
drawnpolygon.Dispose();
if (kmlpolygonsoverlay != null)
kmlpolygonsoverlay.Dispose();
if (wppolygon != null)
wppolygon.Dispose();
if (top != null)
top.Dispose();
if (geofencepolygon != null)
geofencepolygon.Dispose();
if (geofenceoverlay != null)
geofenceoverlay.Dispose();
if (drawnpolygonsoverlay != null)
drawnpolygonsoverlay.Dispose();
if (center != null)
center.Dispose();
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FlightPlanner));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
this.Commands = new MissionPlanner.Controls.MyDataGridView();
this.CHK_verifyheight = new System.Windows.Forms.CheckBox();
this.TXT_WPRad = new System.Windows.Forms.TextBox();
this.TXT_DefaultAlt = new System.Windows.Forms.TextBox();
this.LBL_WPRad = new System.Windows.Forms.Label();
this.LBL_defalutalt = new System.Windows.Forms.Label();
this.TXT_loiterrad = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.panel5 = new System.Windows.Forms.Panel();
this.but_writewpfast = new MissionPlanner.Controls.MyButton();
this.BUT_write = new MissionPlanner.Controls.MyButton();
this.BUT_read = new MissionPlanner.Controls.MyButton();
this.panel1 = new System.Windows.Forms.Panel();
this.label4 = new System.Windows.Forms.LinkLabel();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.TXT_homealt = new System.Windows.Forms.TextBox();
this.TXT_homelng = new System.Windows.Forms.TextBox();
this.TXT_homelat = new System.Windows.Forms.TextBox();
this.dataGridViewImageColumn1 = new System.Windows.Forms.DataGridViewImageColumn();
this.dataGridViewImageColumn2 = new System.Windows.Forms.DataGridViewImageColumn();
this.label6 = new System.Windows.Forms.Label();
this.coords1 = new MissionPlanner.Controls.Coords();
this.lbl_status = new System.Windows.Forms.Label();
this.panelWaypoints = new BSE.Windows.Forms.Panel();
this.splitter1 = new BSE.Windows.Forms.Splitter();
this.CMB_altmode = new System.Windows.Forms.ComboBox();
this.CHK_splinedefault = new System.Windows.Forms.CheckBox();
this.label17 = new System.Windows.Forms.Label();
this.TXT_altwarn = new System.Windows.Forms.TextBox();
this.BUT_Add = new MissionPlanner.Controls.MyButton();
this.panelAction = new BSE.Windows.Forms.Panel();
this.splitter2 = new BSE.Windows.Forms.Splitter();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.chk_grid = new System.Windows.Forms.CheckBox();
this.comboBoxMapType = new System.Windows.Forms.ComboBox();
this.lnk_kml = new System.Windows.Forms.LinkLabel();
this.panel2 = new System.Windows.Forms.Panel();
this.lbl_wpfile = new System.Windows.Forms.Label();
this.BUT_loadwpfile = new MissionPlanner.Controls.MyButton();
this.BUT_saveWPFile = new MissionPlanner.Controls.MyButton();
this.panelMap = new System.Windows.Forms.Panel();
this.lbl_homedist = new System.Windows.Forms.Label();
this.lbl_prevdist = new System.Windows.Forms.Label();
this.trackBar1 = new MissionPlanner.Controls.MyTrackBar();
this.label11 = new System.Windows.Forms.Label();
this.lbl_distance = new System.Windows.Forms.Label();
this.MainMap = new MissionPlanner.Controls.myGMAP();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.deleteWPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertWpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.currentPositionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.insertSplineWPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loiterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loiterForeverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loitertimeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loitercirclesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.jumpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.jumpstartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.jumpwPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rTLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.landToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.takeoffToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setROIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearMissionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.polygonToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addPolygonPointToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearPolygonToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.savePolygonToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadPolygonToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fromSHPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.areaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rallyPointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setRallyPointToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.getRallyPointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveRallyPointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearRallyPointsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToFileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.loadFromFileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.geoFenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.GeoFenceuploadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.GeoFencedownloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setReturnLocationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadFromFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autoWPToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createWpCircleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createSplineCircleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.areaToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.textToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createCircleSurveyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.surveyGridToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mapToolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ContextMeasure = new System.Windows.Forms.ToolStripMenuItem();
this.rotateMapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomToToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prefetchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.prefetchWPPathToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.kMLOverlayToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.elevationGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reverseWPsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fileLoadSaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadWPFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadAndAppendToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveWPFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadKMLFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadSHPFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pOIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.poiaddToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.poideleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.poieditToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.trackerHomeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.modifyAltToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.enterUTMCoordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.switchDockingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setHomeHereToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panelBASE = new System.Windows.Forms.Panel();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.Command = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.Param1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Param2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Param3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Param4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Lat = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Lon = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Alt = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.coordZone = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.coordEasting = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.coordNorthing = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.MGRS = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Delete = new System.Windows.Forms.DataGridViewButtonColumn();
this.Up = new System.Windows.Forms.DataGridViewImageColumn();
this.Down = new System.Windows.Forms.DataGridViewImageColumn();
this.Grad = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Angle = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Dist = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.AZ = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.TagData = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.Commands)).BeginInit();
this.panel5.SuspendLayout();
this.panel1.SuspendLayout();
this.panelWaypoints.SuspendLayout();
this.panelAction.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.panel4.SuspendLayout();
this.panel3.SuspendLayout();
this.panel2.SuspendLayout();
this.panelMap.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
this.contextMenuStrip1.SuspendLayout();
this.panelBASE.SuspendLayout();
this.SuspendLayout();
//
// Commands
//
this.Commands.AllowUserToAddRows = false;
resources.ApplyResources(this.Commands, "Commands");
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.Commands.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.Commands.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Command,
this.Param1,
this.Param2,
this.Param3,
this.Param4,
this.Lat,
this.Lon,
this.Alt,
this.coordZone,
this.coordEasting,
this.coordNorthing,
this.MGRS,
this.Delete,
this.Up,
this.Down,
this.Grad,
this.Angle,
this.Dist,
this.AZ,
this.TagData});
this.Commands.Name = "Commands";
dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle5.Format = "N0";
dataGridViewCellStyle5.NullValue = "0";
dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
this.Commands.RowHeadersDefaultCellStyle = dataGridViewCellStyle5;
dataGridViewCellStyle6.ForeColor = System.Drawing.Color.Black;
this.Commands.RowsDefaultCellStyle = dataGridViewCellStyle6;
this.Commands.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.Commands_CellContentClick);
this.Commands.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.Commands_CellEndEdit);
this.Commands.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.Commands_DataError);
this.Commands.DefaultValuesNeeded += new System.Windows.Forms.DataGridViewRowEventHandler(this.Commands_DefaultValuesNeeded);
this.Commands.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.Commands_EditingControlShowing);
this.Commands.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.Commands_RowEnter);
this.Commands.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.Commands_RowsAdded);
this.Commands.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.Commands_RowsRemoved);
this.Commands.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.Commands_RowValidating);
//
// CHK_verifyheight
//
resources.ApplyResources(this.CHK_verifyheight, "CHK_verifyheight");
this.CHK_verifyheight.Name = "CHK_verifyheight";
this.CHK_verifyheight.UseVisualStyleBackColor = true;
//
// TXT_WPRad
//
resources.ApplyResources(this.TXT_WPRad, "TXT_WPRad");
this.TXT_WPRad.Name = "TXT_WPRad";
this.TXT_WPRad.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TXT_WPRad_KeyPress);
this.TXT_WPRad.Leave += new System.EventHandler(this.TXT_WPRad_Leave);
//
// TXT_DefaultAlt
//
resources.ApplyResources(this.TXT_DefaultAlt, "TXT_DefaultAlt");
this.TXT_DefaultAlt.Name = "TXT_DefaultAlt";
this.TXT_DefaultAlt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TXT_DefaultAlt_KeyPress);
this.TXT_DefaultAlt.Leave += new System.EventHandler(this.TXT_DefaultAlt_Leave);
//
// LBL_WPRad
//
resources.ApplyResources(this.LBL_WPRad, "LBL_WPRad");
this.LBL_WPRad.Name = "LBL_WPRad";
//
// LBL_defalutalt
//
resources.ApplyResources(this.LBL_defalutalt, "LBL_defalutalt");
this.LBL_defalutalt.Name = "LBL_defalutalt";
//
// TXT_loiterrad
//
resources.ApplyResources(this.TXT_loiterrad, "TXT_loiterrad");
this.TXT_loiterrad.Name = "TXT_loiterrad";
this.TXT_loiterrad.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TXT_loiterrad_KeyPress);
this.TXT_loiterrad.Leave += new System.EventHandler(this.TXT_loiterrad_Leave);
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// panel5
//
this.panel5.Controls.Add(this.but_writewpfast);
this.panel5.Controls.Add(this.BUT_write);
this.panel5.Controls.Add(this.BUT_read);
resources.ApplyResources(this.panel5, "panel5");
this.panel5.Name = "panel5";
//
// but_writewpfast
//
resources.ApplyResources(this.but_writewpfast, "but_writewpfast");
this.but_writewpfast.Name = "but_writewpfast";
this.but_writewpfast.UseVisualStyleBackColor = true;
this.but_writewpfast.Click += new System.EventHandler(this.but_writewpfast_Click);
//
// BUT_write
//
resources.ApplyResources(this.BUT_write, "BUT_write");
this.BUT_write.Name = "BUT_write";
this.BUT_write.UseVisualStyleBackColor = true;
this.BUT_write.Click += new System.EventHandler(this.BUT_write_Click);
//
// BUT_read
//
resources.ApplyResources(this.BUT_read, "BUT_read");
this.BUT_read.Name = "BUT_read";
this.BUT_read.UseVisualStyleBackColor = true;
this.BUT_read.Click += new System.EventHandler(this.BUT_read_Click);
//
// panel1
//
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.Label1);
this.panel1.Controls.Add(this.TXT_homealt);
this.panel1.Controls.Add(this.TXT_homelng);
this.panel1.Controls.Add(this.TXT_homelat);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
this.label4.TabStop = true;
this.label4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.label4_LinkClicked);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// Label1
//
resources.ApplyResources(this.Label1, "Label1");
this.Label1.Name = "Label1";
//
// TXT_homealt
//
resources.ApplyResources(this.TXT_homealt, "TXT_homealt");
this.TXT_homealt.Name = "TXT_homealt";
this.TXT_homealt.TextChanged += new System.EventHandler(this.TXT_homealt_TextChanged);
//
// TXT_homelng
//
resources.ApplyResources(this.TXT_homelng, "TXT_homelng");
this.TXT_homelng.Name = "TXT_homelng";
this.TXT_homelng.TextChanged += new System.EventHandler(this.TXT_homelng_TextChanged);
//
// TXT_homelat
//
resources.ApplyResources(this.TXT_homelat, "TXT_homelat");
this.TXT_homelat.Name = "TXT_homelat";
this.TXT_homelat.TextChanged += new System.EventHandler(this.TXT_homelat_TextChanged);
this.TXT_homelat.Enter += new System.EventHandler(this.TXT_homelat_Enter);
//
// dataGridViewImageColumn1
//
dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.dataGridViewImageColumn1.DefaultCellStyle = dataGridViewCellStyle7;
resources.ApplyResources(this.dataGridViewImageColumn1, "dataGridViewImageColumn1");
this.dataGridViewImageColumn1.Image = ((System.Drawing.Image)(resources.GetObject("dataGridViewImageColumn1.Image")));
this.dataGridViewImageColumn1.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Stretch;
this.dataGridViewImageColumn1.Name = "dataGridViewImageColumn1";
//
// dataGridViewImageColumn2
//
dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.dataGridViewImageColumn2.DefaultCellStyle = dataGridViewCellStyle8;
resources.ApplyResources(this.dataGridViewImageColumn2, "dataGridViewImageColumn2");
this.dataGridViewImageColumn2.Image = ((System.Drawing.Image)(resources.GetObject("dataGridViewImageColumn2.Image")));
this.dataGridViewImageColumn2.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Stretch;
this.dataGridViewImageColumn2.Name = "dataGridViewImageColumn2";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// coords1
//
this.coords1.Alt = 0D;
this.coords1.AltSource = "";
this.coords1.AltUnit = "m";
this.coords1.Lat = 0D;
this.coords1.Lng = 0D;
resources.ApplyResources(this.coords1, "coords1");
this.coords1.Name = "coords1";
this.coords1.Vertical = true;
this.coords1.SystemChanged += new System.EventHandler(this.coords1_SystemChanged);
//
// lbl_status
//
resources.ApplyResources(this.lbl_status, "lbl_status");
this.lbl_status.Name = "lbl_status";
//
// panelWaypoints
//
this.panelWaypoints.AssociatedSplitter = this.splitter1;
this.panelWaypoints.BackColor = System.Drawing.Color.Transparent;
this.panelWaypoints.CaptionFont = new System.Drawing.Font("Segoe UI", 11.75F, System.Drawing.FontStyle.Bold);
this.panelWaypoints.CaptionHeight = 21;
this.panelWaypoints.ColorScheme = BSE.Windows.Forms.ColorScheme.Custom;
this.panelWaypoints.Controls.Add(this.CMB_altmode);
this.panelWaypoints.Controls.Add(this.CHK_splinedefault);
this.panelWaypoints.Controls.Add(this.label17);
this.panelWaypoints.Controls.Add(this.TXT_altwarn);
this.panelWaypoints.Controls.Add(this.LBL_WPRad);
this.panelWaypoints.Controls.Add(this.label5);
this.panelWaypoints.Controls.Add(this.TXT_loiterrad);
this.panelWaypoints.Controls.Add(this.LBL_defalutalt);
this.panelWaypoints.Controls.Add(this.Commands);
this.panelWaypoints.Controls.Add(this.TXT_DefaultAlt);
this.panelWaypoints.Controls.Add(this.CHK_verifyheight);
this.panelWaypoints.Controls.Add(this.TXT_WPRad);
this.panelWaypoints.Controls.Add(this.BUT_Add);
this.panelWaypoints.CustomColors.BorderColor = System.Drawing.Color.Black;
this.panelWaypoints.CustomColors.CaptionCloseIcon = System.Drawing.Color.White;
this.panelWaypoints.CustomColors.CaptionExpandIcon = System.Drawing.Color.White;
this.panelWaypoints.CustomColors.CaptionGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(148)))), ((int)(((byte)(193)))), ((int)(((byte)(31)))));
this.panelWaypoints.CustomColors.CaptionGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(205)))), ((int)(((byte)(226)))), ((int)(((byte)(150)))));
this.panelWaypoints.CustomColors.CaptionGradientMiddle = System.Drawing.Color.Transparent;
this.panelWaypoints.CustomColors.CaptionSelectedGradientBegin = System.Drawing.Color.Transparent;
this.panelWaypoints.CustomColors.CaptionSelectedGradientEnd = System.Drawing.Color.Transparent;
this.panelWaypoints.CustomColors.CaptionText = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(87)))), ((int)(((byte)(4)))));
this.panelWaypoints.CustomColors.CollapsedCaptionText = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(87)))), ((int)(((byte)(4)))));
this.panelWaypoints.CustomColors.ContentGradientBegin = System.Drawing.SystemColors.ButtonFace;
this.panelWaypoints.CustomColors.ContentGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(252)))), ((int)(((byte)(252)))));
this.panelWaypoints.CustomColors.InnerBorderColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.panelWaypoints, "panelWaypoints");
this.panelWaypoints.ForeColor = System.Drawing.SystemColors.ControlText;
this.panelWaypoints.Image = null;
this.panelWaypoints.Name = "panelWaypoints";
this.panelWaypoints.ShowExpandIcon = true;
this.panelWaypoints.ToolTipTextCloseIcon = null;
this.panelWaypoints.ToolTipTextExpandIconPanelCollapsed = null;
this.panelWaypoints.ToolTipTextExpandIconPanelExpanded = null;
this.panelWaypoints.ExpandClick += new System.EventHandler<System.EventArgs>(this.panelWaypoints_ExpandClick);
//
// splitter1
//
this.splitter1.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.splitter1, "splitter1");
this.splitter1.Name = "splitter1";
this.splitter1.TabStop = false;
//
// CMB_altmode
//
this.CMB_altmode.FormattingEnabled = true;
resources.ApplyResources(this.CMB_altmode, "CMB_altmode");
this.CMB_altmode.Name = "CMB_altmode";
this.CMB_altmode.SelectedIndexChanged += new System.EventHandler(this.CMB_altmode_SelectedIndexChanged);
//
// CHK_splinedefault
//
resources.ApplyResources(this.CHK_splinedefault, "CHK_splinedefault");
this.CHK_splinedefault.Name = "CHK_splinedefault";
this.CHK_splinedefault.UseVisualStyleBackColor = true;
this.CHK_splinedefault.CheckedChanged += new System.EventHandler(this.CHK_splinedefault_CheckedChanged);
//
// label17
//
resources.ApplyResources(this.label17, "label17");
this.label17.Name = "label17";
//
// TXT_altwarn
//
resources.ApplyResources(this.TXT_altwarn, "TXT_altwarn");
this.TXT_altwarn.Name = "TXT_altwarn";
//
// BUT_Add
//
resources.ApplyResources(this.BUT_Add, "BUT_Add");
this.BUT_Add.Name = "BUT_Add";
this.toolTip1.SetToolTip(this.BUT_Add, resources.GetString("BUT_Add.ToolTip"));
this.BUT_Add.UseVisualStyleBackColor = true;
this.BUT_Add.Click += new System.EventHandler(this.BUT_Add_Click);
//
// panelAction
//
this.panelAction.AssociatedSplitter = this.splitter2;
this.panelAction.BackColor = System.Drawing.Color.Transparent;
this.panelAction.CaptionFont = new System.Drawing.Font("Segoe UI", 11.75F, System.Drawing.FontStyle.Bold);
this.panelAction.CaptionHeight = 21;
this.panelAction.ColorScheme = BSE.Windows.Forms.ColorScheme.Custom;
this.panelAction.Controls.Add(this.flowLayoutPanel1);
this.panelAction.CustomColors.BorderColor = System.Drawing.Color.Black;
this.panelAction.CustomColors.CaptionCloseIcon = System.Drawing.Color.White;
this.panelAction.CustomColors.CaptionExpandIcon = System.Drawing.Color.White;
this.panelAction.CustomColors.CaptionGradientBegin = System.Drawing.Color.FromArgb(((int)(((byte)(148)))), ((int)(((byte)(193)))), ((int)(((byte)(31)))));
this.panelAction.CustomColors.CaptionGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(205)))), ((int)(((byte)(226)))), ((int)(((byte)(150)))));
this.panelAction.CustomColors.CaptionGradientMiddle = System.Drawing.Color.Transparent;
this.panelAction.CustomColors.CaptionSelectedGradientBegin = System.Drawing.Color.Transparent;
this.panelAction.CustomColors.CaptionSelectedGradientEnd = System.Drawing.Color.Transparent;
this.panelAction.CustomColors.CaptionText = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(87)))), ((int)(((byte)(4)))));
this.panelAction.CustomColors.CollapsedCaptionText = System.Drawing.Color.White;
this.panelAction.CustomColors.ContentGradientBegin = System.Drawing.SystemColors.ButtonFace;
this.panelAction.CustomColors.ContentGradientEnd = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(252)))), ((int)(((byte)(252)))));
this.panelAction.CustomColors.InnerBorderColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.panelAction, "panelAction");
this.panelAction.ForeColor = System.Drawing.SystemColors.ControlText;
this.panelAction.Image = null;
this.panelAction.Name = "panelAction";
this.panelAction.ShowExpandIcon = true;
this.panelAction.ToolTipTextCloseIcon = null;
this.panelAction.ToolTipTextExpandIconPanelCollapsed = null;
this.panelAction.ToolTipTextExpandIconPanelExpanded = null;
//
// splitter2
//
this.splitter2.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.splitter2, "splitter2");
this.splitter2.Name = "splitter2";
this.splitter2.TabStop = false;
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Controls.Add(this.panel4);
this.flowLayoutPanel1.Controls.Add(this.panel3);
this.flowLayoutPanel1.Controls.Add(this.panel2);
this.flowLayoutPanel1.Controls.Add(this.panel5);
this.flowLayoutPanel1.Controls.Add(this.panel1);
resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1");
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
//
// panel4
//
this.panel4.Controls.Add(this.coords1);
resources.ApplyResources(this.panel4, "panel4");
this.panel4.Name = "panel4";
//
// panel3
//
this.panel3.Controls.Add(this.chk_grid);
this.panel3.Controls.Add(this.lbl_status);
this.panel3.Controls.Add(this.comboBoxMapType);
this.panel3.Controls.Add(this.lnk_kml);
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// chk_grid
//
resources.ApplyResources(this.chk_grid, "chk_grid");
this.chk_grid.Name = "chk_grid";
this.chk_grid.UseVisualStyleBackColor = true;
this.chk_grid.CheckedChanged += new System.EventHandler(this.chk_grid_CheckedChanged);
//
// comboBoxMapType
//
this.comboBoxMapType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxMapType.FormattingEnabled = true;
resources.ApplyResources(this.comboBoxMapType, "comboBoxMapType");
this.comboBoxMapType.Name = "comboBoxMapType";
this.toolTip1.SetToolTip(this.comboBoxMapType, resources.GetString("comboBoxMapType.ToolTip"));
//
// lnk_kml
//
resources.ApplyResources(this.lnk_kml, "lnk_kml");
this.lnk_kml.Name = "lnk_kml";
this.lnk_kml.TabStop = true;
this.lnk_kml.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnk_kml_LinkClicked);
//
// panel2
//
this.panel2.Controls.Add(this.lbl_wpfile);
this.panel2.Controls.Add(this.BUT_loadwpfile);
this.panel2.Controls.Add(this.BUT_saveWPFile);
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Name = "panel2";
//
// lbl_wpfile
//
resources.ApplyResources(this.lbl_wpfile, "lbl_wpfile");
this.lbl_wpfile.Name = "lbl_wpfile";
//
// BUT_loadwpfile
//
resources.ApplyResources(this.BUT_loadwpfile, "BUT_loadwpfile");
this.BUT_loadwpfile.Name = "BUT_loadwpfile";
this.BUT_loadwpfile.UseVisualStyleBackColor = true;
this.BUT_loadwpfile.Click += new System.EventHandler(this.BUT_loadwpfile_Click);
//
// BUT_saveWPFile
//
resources.ApplyResources(this.BUT_saveWPFile, "BUT_saveWPFile");
this.BUT_saveWPFile.Name = "BUT_saveWPFile";
this.BUT_saveWPFile.UseVisualStyleBackColor = true;
this.BUT_saveWPFile.Click += new System.EventHandler(this.BUT_saveWPFile_Click);
//
// panelMap
//
this.panelMap.Controls.Add(this.lbl_homedist);
this.panelMap.Controls.Add(this.lbl_prevdist);
this.panelMap.Controls.Add(this.trackBar1);
this.panelMap.Controls.Add(this.label11);
this.panelMap.Controls.Add(this.lbl_distance);
this.panelMap.Controls.Add(this.MainMap);
resources.ApplyResources(this.panelMap, "panelMap");
this.panelMap.ForeColor = System.Drawing.SystemColors.ControlText;
this.panelMap.Name = "panelMap";
this.panelMap.Resize += new System.EventHandler(this.panelMap_Resize);
//
// lbl_homedist
//
resources.ApplyResources(this.lbl_homedist, "lbl_homedist");
this.lbl_homedist.Name = "lbl_homedist";
//
// lbl_prevdist
//
resources.ApplyResources(this.lbl_prevdist, "lbl_prevdist");
this.lbl_prevdist.Name = "lbl_prevdist";
//
// trackBar1
//
resources.ApplyResources(this.trackBar1, "trackBar1");
this.trackBar1.LargeChange = 0.005F;
this.trackBar1.Maximum = 24F;
this.trackBar1.Minimum = 1F;
this.trackBar1.Name = "trackBar1";
this.trackBar1.SmallChange = 0.001F;
this.trackBar1.TickFrequency = 1F;
this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.TopLeft;
this.trackBar1.Value = 2F;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// lbl_distance
//
resources.ApplyResources(this.lbl_distance, "lbl_distance");
this.lbl_distance.Name = "lbl_distance";
//
// MainMap
//
resources.ApplyResources(this.MainMap, "MainMap");
this.MainMap.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(38)))), ((int)(((byte)(39)))), ((int)(((byte)(40)))));
this.MainMap.Bearing = 0F;
this.MainMap.CanDragMap = true;
this.MainMap.ContextMenuStrip = this.contextMenuStrip1;
this.MainMap.Cursor = System.Windows.Forms.Cursors.Default;
this.MainMap.EmptyTileColor = System.Drawing.Color.Gray;
this.MainMap.GrayScaleMode = false;
this.MainMap.HelperLineOption = GMap.NET.WindowsForms.HelperLineOptions.DontShow;
this.MainMap.HoldInvalidation = false;
this.MainMap.LevelsKeepInMemmory = 5;
this.MainMap.MarkersEnabled = true;
this.MainMap.MaxZoom = 19;
this.MainMap.MinZoom = 0;
this.MainMap.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.MousePositionWithoutCenter;
this.MainMap.Name = "MainMap";
this.MainMap.NegativeMode = false;
this.MainMap.PolygonsEnabled = true;
this.MainMap.RetryLoadTile = 0;
this.MainMap.RoutesEnabled = false;
this.MainMap.ScaleMode = GMap.NET.WindowsForms.ScaleModes.Fractional;
this.MainMap.SelectedAreaFillColor = System.Drawing.Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(65)))), ((int)(((byte)(105)))), ((int)(((byte)(225)))));
this.MainMap.ShowTileGridLines = false;
this.MainMap.Zoom = 0D;
this.MainMap.Paint += new System.Windows.Forms.PaintEventHandler(this.MainMap_Paint);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.deleteWPToolStripMenuItem,
this.insertWpToolStripMenuItem,
this.insertSplineWPToolStripMenuItem,
this.loiterToolStripMenuItem,
this.jumpToolStripMenuItem,
this.rTLToolStripMenuItem,
this.landToolStripMenuItem,
this.takeoffToolStripMenuItem,
this.setROIToolStripMenuItem,
this.clearMissionToolStripMenuItem,
this.toolStripSeparator1,
this.polygonToolStripMenuItem,
this.rallyPointsToolStripMenuItem,
this.geoFenceToolStripMenuItem,
this.autoWPToolStripMenuItem,
this.mapToolToolStripMenuItem,
this.fileLoadSaveToolStripMenuItem,
this.pOIToolStripMenuItem,
this.trackerHomeToolStripMenuItem,
this.modifyAltToolStripMenuItem,
this.enterUTMCoordToolStripMenuItem,
this.switchDockingToolStripMenuItem,
this.setHomeHereToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1");
this.contextMenuStrip1.Closed += new System.Windows.Forms.ToolStripDropDownClosedEventHandler(this.contextMenuStrip1_Closed);
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening);
//
// deleteWPToolStripMenuItem
//
this.deleteWPToolStripMenuItem.Name = "deleteWPToolStripMenuItem";
resources.ApplyResources(this.deleteWPToolStripMenuItem, "deleteWPToolStripMenuItem");
this.deleteWPToolStripMenuItem.Click += new System.EventHandler(this.deleteWPToolStripMenuItem_Click);
//
// insertWpToolStripMenuItem
//
this.insertWpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.currentPositionToolStripMenuItem});
this.insertWpToolStripMenuItem.Name = "insertWpToolStripMenuItem";
resources.ApplyResources(this.insertWpToolStripMenuItem, "insertWpToolStripMenuItem");
this.insertWpToolStripMenuItem.Click += new System.EventHandler(this.insertWpToolStripMenuItem_Click);
//
// currentPositionToolStripMenuItem
//
this.currentPositionToolStripMenuItem.Name = "currentPositionToolStripMenuItem";
resources.ApplyResources(this.currentPositionToolStripMenuItem, "currentPositionToolStripMenuItem");
this.currentPositionToolStripMenuItem.Click += new System.EventHandler(this.currentPositionToolStripMenuItem_Click);
//
// insertSplineWPToolStripMenuItem
//
this.insertSplineWPToolStripMenuItem.Name = "insertSplineWPToolStripMenuItem";
resources.ApplyResources(this.insertSplineWPToolStripMenuItem, "insertSplineWPToolStripMenuItem");
this.insertSplineWPToolStripMenuItem.Click += new System.EventHandler(this.insertSplineWPToolStripMenuItem_Click);
//
// loiterToolStripMenuItem
//
this.loiterToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loiterForeverToolStripMenuItem,
this.loitertimeToolStripMenuItem,
this.loitercirclesToolStripMenuItem});
this.loiterToolStripMenuItem.Name = "loiterToolStripMenuItem";
resources.ApplyResources(this.loiterToolStripMenuItem, "loiterToolStripMenuItem");
//
// loiterForeverToolStripMenuItem
//
this.loiterForeverToolStripMenuItem.Name = "loiterForeverToolStripMenuItem";
resources.ApplyResources(this.loiterForeverToolStripMenuItem, "loiterForeverToolStripMenuItem");
this.loiterForeverToolStripMenuItem.Click += new System.EventHandler(this.loiterForeverToolStripMenuItem_Click);
//
// loitertimeToolStripMenuItem
//
this.loitertimeToolStripMenuItem.Name = "loitertimeToolStripMenuItem";
resources.ApplyResources(this.loitertimeToolStripMenuItem, "loitertimeToolStripMenuItem");
this.loitertimeToolStripMenuItem.Click += new System.EventHandler(this.loitertimeToolStripMenuItem_Click);
//
// loitercirclesToolStripMenuItem
//
this.loitercirclesToolStripMenuItem.Name = "loitercirclesToolStripMenuItem";
resources.ApplyResources(this.loitercirclesToolStripMenuItem, "loitercirclesToolStripMenuItem");
this.loitercirclesToolStripMenuItem.Click += new System.EventHandler(this.loitercirclesToolStripMenuItem_Click);
//
// jumpToolStripMenuItem
//
this.jumpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.jumpstartToolStripMenuItem,
this.jumpwPToolStripMenuItem});
this.jumpToolStripMenuItem.Name = "jumpToolStripMenuItem";
resources.ApplyResources(this.jumpToolStripMenuItem, "jumpToolStripMenuItem");
//
// jumpstartToolStripMenuItem
//
this.jumpstartToolStripMenuItem.Name = "jumpstartToolStripMenuItem";
resources.ApplyResources(this.jumpstartToolStripMenuItem, "jumpstartToolStripMenuItem");
this.jumpstartToolStripMenuItem.Click += new System.EventHandler(this.jumpstartToolStripMenuItem_Click);
//
// jumpwPToolStripMenuItem
//
this.jumpwPToolStripMenuItem.Name = "jumpwPToolStripMenuItem";
resources.ApplyResources(this.jumpwPToolStripMenuItem, "jumpwPToolStripMenuItem");
this.jumpwPToolStripMenuItem.Click += new System.EventHandler(this.jumpwPToolStripMenuItem_Click);
//
// rTLToolStripMenuItem
//
this.rTLToolStripMenuItem.Name = "rTLToolStripMenuItem";
resources.ApplyResources(this.rTLToolStripMenuItem, "rTLToolStripMenuItem");
this.rTLToolStripMenuItem.Click += new System.EventHandler(this.rTLToolStripMenuItem_Click);
//
// landToolStripMenuItem
//
this.landToolStripMenuItem.Name = "landToolStripMenuItem";
resources.ApplyResources(this.landToolStripMenuItem, "landToolStripMenuItem");
this.landToolStripMenuItem.Click += new System.EventHandler(this.landToolStripMenuItem_Click);
//
// takeoffToolStripMenuItem
//
this.takeoffToolStripMenuItem.Name = "takeoffToolStripMenuItem";
resources.ApplyResources(this.takeoffToolStripMenuItem, "takeoffToolStripMenuItem");
this.takeoffToolStripMenuItem.Click += new System.EventHandler(this.takeoffToolStripMenuItem_Click);
//
// setROIToolStripMenuItem
//
this.setROIToolStripMenuItem.Name = "setROIToolStripMenuItem";
resources.ApplyResources(this.setROIToolStripMenuItem, "setROIToolStripMenuItem");
this.setROIToolStripMenuItem.Click += new System.EventHandler(this.setROIToolStripMenuItem_Click);
//
// clearMissionToolStripMenuItem
//
this.clearMissionToolStripMenuItem.Name = "clearMissionToolStripMenuItem";
resources.ApplyResources(this.clearMissionToolStripMenuItem, "clearMissionToolStripMenuItem");
this.clearMissionToolStripMenuItem.Click += new System.EventHandler(this.clearMissionToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// polygonToolStripMenuItem
//
this.polygonToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addPolygonPointToolStripMenuItem,
this.clearPolygonToolStripMenuItem,
this.savePolygonToolStripMenuItem,
this.loadPolygonToolStripMenuItem,
this.fromSHPToolStripMenuItem,
this.areaToolStripMenuItem});
this.polygonToolStripMenuItem.Name = "polygonToolStripMenuItem";
resources.ApplyResources(this.polygonToolStripMenuItem, "polygonToolStripMenuItem");
//
// addPolygonPointToolStripMenuItem
//
this.addPolygonPointToolStripMenuItem.Name = "addPolygonPointToolStripMenuItem";
resources.ApplyResources(this.addPolygonPointToolStripMenuItem, "addPolygonPointToolStripMenuItem");
this.addPolygonPointToolStripMenuItem.Click += new System.EventHandler(this.addPolygonPointToolStripMenuItem_Click);
//
// clearPolygonToolStripMenuItem
//
this.clearPolygonToolStripMenuItem.Name = "clearPolygonToolStripMenuItem";
resources.ApplyResources(this.clearPolygonToolStripMenuItem, "clearPolygonToolStripMenuItem");
this.clearPolygonToolStripMenuItem.Click += new System.EventHandler(this.clearPolygonToolStripMenuItem_Click);
//
// savePolygonToolStripMenuItem
//
this.savePolygonToolStripMenuItem.Name = "savePolygonToolStripMenuItem";
resources.ApplyResources(this.savePolygonToolStripMenuItem, "savePolygonToolStripMenuItem");
this.savePolygonToolStripMenuItem.Click += new System.EventHandler(this.savePolygonToolStripMenuItem_Click);
//
// loadPolygonToolStripMenuItem
//
this.loadPolygonToolStripMenuItem.Name = "loadPolygonToolStripMenuItem";
resources.ApplyResources(this.loadPolygonToolStripMenuItem, "loadPolygonToolStripMenuItem");
this.loadPolygonToolStripMenuItem.Click += new System.EventHandler(this.loadPolygonToolStripMenuItem_Click);
//
// fromSHPToolStripMenuItem
//
this.fromSHPToolStripMenuItem.Name = "fromSHPToolStripMenuItem";
resources.ApplyResources(this.fromSHPToolStripMenuItem, "fromSHPToolStripMenuItem");
this.fromSHPToolStripMenuItem.Click += new System.EventHandler(this.fromSHPToolStripMenuItem_Click);
//
// areaToolStripMenuItem
//
this.areaToolStripMenuItem.Name = "areaToolStripMenuItem";
resources.ApplyResources(this.areaToolStripMenuItem, "areaToolStripMenuItem");
this.areaToolStripMenuItem.Click += new System.EventHandler(this.areaToolStripMenuItem_Click);
//
// rallyPointsToolStripMenuItem
//
this.rallyPointsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.setRallyPointToolStripMenuItem,
this.getRallyPointsToolStripMenuItem,
this.saveRallyPointsToolStripMenuItem,
this.clearRallyPointsToolStripMenuItem,
this.saveToFileToolStripMenuItem1,
this.loadFromFileToolStripMenuItem1});
this.rallyPointsToolStripMenuItem.Name = "rallyPointsToolStripMenuItem";
resources.ApplyResources(this.rallyPointsToolStripMenuItem, "rallyPointsToolStripMenuItem");
//
// setRallyPointToolStripMenuItem
//
this.setRallyPointToolStripMenuItem.Name = "setRallyPointToolStripMenuItem";
resources.ApplyResources(this.setRallyPointToolStripMenuItem, "setRallyPointToolStripMenuItem");
this.setRallyPointToolStripMenuItem.Click += new System.EventHandler(this.setRallyPointToolStripMenuItem_Click);
//
// getRallyPointsToolStripMenuItem
//
this.getRallyPointsToolStripMenuItem.Name = "getRallyPointsToolStripMenuItem";
resources.ApplyResources(this.getRallyPointsToolStripMenuItem, "getRallyPointsToolStripMenuItem");
this.getRallyPointsToolStripMenuItem.Click += new System.EventHandler(this.getRallyPointsToolStripMenuItem_Click);
//
// saveRallyPointsToolStripMenuItem
//
this.saveRallyPointsToolStripMenuItem.Name = "saveRallyPointsToolStripMenuItem";
resources.ApplyResources(this.saveRallyPointsToolStripMenuItem, "saveRallyPointsToolStripMenuItem");
this.saveRallyPointsToolStripMenuItem.Click += new System.EventHandler(this.saveRallyPointsToolStripMenuItem_Click);
//
// clearRallyPointsToolStripMenuItem
//
this.clearRallyPointsToolStripMenuItem.Name = "clearRallyPointsToolStripMenuItem";
resources.ApplyResources(this.clearRallyPointsToolStripMenuItem, "clearRallyPointsToolStripMenuItem");
this.clearRallyPointsToolStripMenuItem.Click += new System.EventHandler(this.clearRallyPointsToolStripMenuItem_Click);
//
// saveToFileToolStripMenuItem1
//
this.saveToFileToolStripMenuItem1.Name = "saveToFileToolStripMenuItem1";
resources.ApplyResources(this.saveToFileToolStripMenuItem1, "saveToFileToolStripMenuItem1");
this.saveToFileToolStripMenuItem1.Click += new System.EventHandler(this.saveToFileToolStripMenuItem1_Click);
//
// loadFromFileToolStripMenuItem1
//
this.loadFromFileToolStripMenuItem1.Name = "loadFromFileToolStripMenuItem1";
resources.ApplyResources(this.loadFromFileToolStripMenuItem1, "loadFromFileToolStripMenuItem1");
this.loadFromFileToolStripMenuItem1.Click += new System.EventHandler(this.loadFromFileToolStripMenuItem1_Click);
//
// geoFenceToolStripMenuItem
//
this.geoFenceToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1,
this.toolStripSeparator4,
this.GeoFenceuploadToolStripMenuItem,
this.GeoFencedownloadToolStripMenuItem,
this.setReturnLocationToolStripMenuItem,
this.loadFromFileToolStripMenuItem,
this.saveToFileToolStripMenuItem,
this.clearToolStripMenuItem});
this.geoFenceToolStripMenuItem.Name = "geoFenceToolStripMenuItem";
resources.ApplyResources(this.geoFenceToolStripMenuItem, "geoFenceToolStripMenuItem");
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// GeoFenceuploadToolStripMenuItem
//
this.GeoFenceuploadToolStripMenuItem.Name = "GeoFenceuploadToolStripMenuItem";
resources.ApplyResources(this.GeoFenceuploadToolStripMenuItem, "GeoFenceuploadToolStripMenuItem");
this.GeoFenceuploadToolStripMenuItem.Click += new System.EventHandler(this.GeoFenceuploadToolStripMenuItem_Click);
//
// GeoFencedownloadToolStripMenuItem
//
this.GeoFencedownloadToolStripMenuItem.Name = "GeoFencedownloadToolStripMenuItem";
resources.ApplyResources(this.GeoFencedownloadToolStripMenuItem, "GeoFencedownloadToolStripMenuItem");
this.GeoFencedownloadToolStripMenuItem.Click += new System.EventHandler(this.GeoFencedownloadToolStripMenuItem_Click);
//
// setReturnLocationToolStripMenuItem
//
this.setReturnLocationToolStripMenuItem.Name = "setReturnLocationToolStripMenuItem";
resources.ApplyResources(this.setReturnLocationToolStripMenuItem, "setReturnLocationToolStripMenuItem");
this.setReturnLocationToolStripMenuItem.Click += new System.EventHandler(this.setReturnLocationToolStripMenuItem_Click);
//
// loadFromFileToolStripMenuItem
//
this.loadFromFileToolStripMenuItem.Name = "loadFromFileToolStripMenuItem";
resources.ApplyResources(this.loadFromFileToolStripMenuItem, "loadFromFileToolStripMenuItem");
this.loadFromFileToolStripMenuItem.Click += new System.EventHandler(this.loadFromFileToolStripMenuItem_Click);
//
// saveToFileToolStripMenuItem
//
this.saveToFileToolStripMenuItem.Name = "saveToFileToolStripMenuItem";
resources.ApplyResources(this.saveToFileToolStripMenuItem, "saveToFileToolStripMenuItem");
this.saveToFileToolStripMenuItem.Click += new System.EventHandler(this.saveToFileToolStripMenuItem_Click);
//
// clearToolStripMenuItem
//
this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
resources.ApplyResources(this.clearToolStripMenuItem, "clearToolStripMenuItem");
this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click);
//
// autoWPToolStripMenuItem
//
this.autoWPToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createWpCircleToolStripMenuItem,
this.createSplineCircleToolStripMenuItem,
this.areaToolStripMenuItem1,
this.textToolStripMenuItem,
this.createCircleSurveyToolStripMenuItem,
this.surveyGridToolStripMenuItem});
this.autoWPToolStripMenuItem.Name = "autoWPToolStripMenuItem";
resources.ApplyResources(this.autoWPToolStripMenuItem, "autoWPToolStripMenuItem");
//
// createWpCircleToolStripMenuItem
//
this.createWpCircleToolStripMenuItem.Name = "createWpCircleToolStripMenuItem";
resources.ApplyResources(this.createWpCircleToolStripMenuItem, "createWpCircleToolStripMenuItem");
this.createWpCircleToolStripMenuItem.Click += new System.EventHandler(this.createWpCircleToolStripMenuItem_Click);
//
// createSplineCircleToolStripMenuItem
//
this.createSplineCircleToolStripMenuItem.Name = "createSplineCircleToolStripMenuItem";
resources.ApplyResources(this.createSplineCircleToolStripMenuItem, "createSplineCircleToolStripMenuItem");
this.createSplineCircleToolStripMenuItem.Click += new System.EventHandler(this.createSplineCircleToolStripMenuItem_Click);
//
// areaToolStripMenuItem1
//
this.areaToolStripMenuItem1.Name = "areaToolStripMenuItem1";
resources.ApplyResources(this.areaToolStripMenuItem1, "areaToolStripMenuItem1");
this.areaToolStripMenuItem1.Click += new System.EventHandler(this.areaToolStripMenuItem_Click);
//
// textToolStripMenuItem
//
this.textToolStripMenuItem.Name = "textToolStripMenuItem";
resources.ApplyResources(this.textToolStripMenuItem, "textToolStripMenuItem");
this.textToolStripMenuItem.Click += new System.EventHandler(this.textToolStripMenuItem_Click);
//
// createCircleSurveyToolStripMenuItem
//
this.createCircleSurveyToolStripMenuItem.Name = "createCircleSurveyToolStripMenuItem";
resources.ApplyResources(this.createCircleSurveyToolStripMenuItem, "createCircleSurveyToolStripMenuItem");
this.createCircleSurveyToolStripMenuItem.Click += new System.EventHandler(this.createCircleSurveyToolStripMenuItem_Click);
//
// surveyGridToolStripMenuItem
//
this.surveyGridToolStripMenuItem.Name = "surveyGridToolStripMenuItem";
resources.ApplyResources(this.surveyGridToolStripMenuItem, "surveyGridToolStripMenuItem");
this.surveyGridToolStripMenuItem.Click += new System.EventHandler(this.surveyGridToolStripMenuItem_Click);
//
// mapToolToolStripMenuItem
//
this.mapToolToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.ContextMeasure,
this.rotateMapToolStripMenuItem,
this.zoomToToolStripMenuItem,
this.prefetchToolStripMenuItem,
this.prefetchWPPathToolStripMenuItem,
this.kMLOverlayToolStripMenuItem,
this.elevationGraphToolStripMenuItem,
this.reverseWPsToolStripMenuItem});
this.mapToolToolStripMenuItem.Name = "mapToolToolStripMenuItem";
resources.ApplyResources(this.mapToolToolStripMenuItem, "mapToolToolStripMenuItem");
//
// ContextMeasure
//
this.ContextMeasure.Name = "ContextMeasure";
resources.ApplyResources(this.ContextMeasure, "ContextMeasure");
this.ContextMeasure.Click += new System.EventHandler(this.ContextMeasure_Click);
//
// rotateMapToolStripMenuItem
//
this.rotateMapToolStripMenuItem.Name = "rotateMapToolStripMenuItem";
resources.ApplyResources(this.rotateMapToolStripMenuItem, "rotateMapToolStripMenuItem");
this.rotateMapToolStripMenuItem.Click += new System.EventHandler(this.rotateMapToolStripMenuItem_Click);
//
// zoomToToolStripMenuItem
//
this.zoomToToolStripMenuItem.Name = "zoomToToolStripMenuItem";
resources.ApplyResources(this.zoomToToolStripMenuItem, "zoomToToolStripMenuItem");
this.zoomToToolStripMenuItem.Click += new System.EventHandler(this.zoomToToolStripMenuItem_Click);
//
// prefetchToolStripMenuItem
//
this.prefetchToolStripMenuItem.Name = "prefetchToolStripMenuItem";
resources.ApplyResources(this.prefetchToolStripMenuItem, "prefetchToolStripMenuItem");
this.prefetchToolStripMenuItem.Click += new System.EventHandler(this.prefetchToolStripMenuItem_Click);
//
// prefetchWPPathToolStripMenuItem
//
this.prefetchWPPathToolStripMenuItem.Name = "prefetchWPPathToolStripMenuItem";
resources.ApplyResources(this.prefetchWPPathToolStripMenuItem, "prefetchWPPathToolStripMenuItem");
this.prefetchWPPathToolStripMenuItem.Click += new System.EventHandler(this.prefetchWPPathToolStripMenuItem_Click);
//
// kMLOverlayToolStripMenuItem
//
this.kMLOverlayToolStripMenuItem.Name = "kMLOverlayToolStripMenuItem";
resources.ApplyResources(this.kMLOverlayToolStripMenuItem, "kMLOverlayToolStripMenuItem");
this.kMLOverlayToolStripMenuItem.Click += new System.EventHandler(this.kMLOverlayToolStripMenuItem_Click);
//
// elevationGraphToolStripMenuItem
//
this.elevationGraphToolStripMenuItem.Name = "elevationGraphToolStripMenuItem";
resources.ApplyResources(this.elevationGraphToolStripMenuItem, "elevationGraphToolStripMenuItem");
this.elevationGraphToolStripMenuItem.Click += new System.EventHandler(this.elevationGraphToolStripMenuItem_Click);
//
// reverseWPsToolStripMenuItem
//
this.reverseWPsToolStripMenuItem.Name = "reverseWPsToolStripMenuItem";
resources.ApplyResources(this.reverseWPsToolStripMenuItem, "reverseWPsToolStripMenuItem");
this.reverseWPsToolStripMenuItem.Click += new System.EventHandler(this.reverseWPsToolStripMenuItem_Click);
//
// fileLoadSaveToolStripMenuItem
//
this.fileLoadSaveToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadWPFileToolStripMenuItem,
this.loadAndAppendToolStripMenuItem,
this.saveWPFileToolStripMenuItem,
this.loadKMLFileToolStripMenuItem,
this.loadSHPFileToolStripMenuItem});
this.fileLoadSaveToolStripMenuItem.Name = "fileLoadSaveToolStripMenuItem";
resources.ApplyResources(this.fileLoadSaveToolStripMenuItem, "fileLoadSaveToolStripMenuItem");
//
// loadWPFileToolStripMenuItem
//
this.loadWPFileToolStripMenuItem.Name = "loadWPFileToolStripMenuItem";
resources.ApplyResources(this.loadWPFileToolStripMenuItem, "loadWPFileToolStripMenuItem");
this.loadWPFileToolStripMenuItem.Click += new System.EventHandler(this.loadWPFileToolStripMenuItem_Click);
//
// loadAndAppendToolStripMenuItem
//
this.loadAndAppendToolStripMenuItem.Name = "loadAndAppendToolStripMenuItem";
resources.ApplyResources(this.loadAndAppendToolStripMenuItem, "loadAndAppendToolStripMenuItem");
this.loadAndAppendToolStripMenuItem.Click += new System.EventHandler(this.loadAndAppendToolStripMenuItem_Click);
//
// saveWPFileToolStripMenuItem
//
this.saveWPFileToolStripMenuItem.Name = "saveWPFileToolStripMenuItem";
resources.ApplyResources(this.saveWPFileToolStripMenuItem, "saveWPFileToolStripMenuItem");
this.saveWPFileToolStripMenuItem.Click += new System.EventHandler(this.saveWPFileToolStripMenuItem_Click);
//
// loadKMLFileToolStripMenuItem
//
this.loadKMLFileToolStripMenuItem.Name = "loadKMLFileToolStripMenuItem";
resources.ApplyResources(this.loadKMLFileToolStripMenuItem, "loadKMLFileToolStripMenuItem");
this.loadKMLFileToolStripMenuItem.Click += new System.EventHandler(this.loadKMLFileToolStripMenuItem_Click);
//
// loadSHPFileToolStripMenuItem
//
this.loadSHPFileToolStripMenuItem.Name = "loadSHPFileToolStripMenuItem";
resources.ApplyResources(this.loadSHPFileToolStripMenuItem, "loadSHPFileToolStripMenuItem");
this.loadSHPFileToolStripMenuItem.Click += new System.EventHandler(this.loadSHPFileToolStripMenuItem_Click);
//
// pOIToolStripMenuItem
//
this.pOIToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.poiaddToolStripMenuItem,
this.poideleteToolStripMenuItem,
this.poieditToolStripMenuItem});
this.pOIToolStripMenuItem.Name = "pOIToolStripMenuItem";
resources.ApplyResources(this.pOIToolStripMenuItem, "pOIToolStripMenuItem");
//
// poiaddToolStripMenuItem
//
this.poiaddToolStripMenuItem.Name = "poiaddToolStripMenuItem";
resources.ApplyResources(this.poiaddToolStripMenuItem, "poiaddToolStripMenuItem");
this.poiaddToolStripMenuItem.Click += new System.EventHandler(this.poiaddToolStripMenuItem_Click);
//
// poideleteToolStripMenuItem
//
this.poideleteToolStripMenuItem.Name = "poideleteToolStripMenuItem";
resources.ApplyResources(this.poideleteToolStripMenuItem, "poideleteToolStripMenuItem");
this.poideleteToolStripMenuItem.Click += new System.EventHandler(this.poideleteToolStripMenuItem_Click);
//
// poieditToolStripMenuItem
//
this.poieditToolStripMenuItem.Name = "poieditToolStripMenuItem";
resources.ApplyResources(this.poieditToolStripMenuItem, "poieditToolStripMenuItem");
this.poieditToolStripMenuItem.Click += new System.EventHandler(this.poieditToolStripMenuItem_Click);
//
// trackerHomeToolStripMenuItem
//
this.trackerHomeToolStripMenuItem.Name = "trackerHomeToolStripMenuItem";
resources.ApplyResources(this.trackerHomeToolStripMenuItem, "trackerHomeToolStripMenuItem");
this.trackerHomeToolStripMenuItem.Click += new System.EventHandler(this.trackerHomeToolStripMenuItem_Click);
//
// modifyAltToolStripMenuItem
//
this.modifyAltToolStripMenuItem.Name = "modifyAltToolStripMenuItem";
resources.ApplyResources(this.modifyAltToolStripMenuItem, "modifyAltToolStripMenuItem");
this.modifyAltToolStripMenuItem.Click += new System.EventHandler(this.modifyAltToolStripMenuItem_Click);
//
// enterUTMCoordToolStripMenuItem
//
this.enterUTMCoordToolStripMenuItem.Name = "enterUTMCoordToolStripMenuItem";
resources.ApplyResources(this.enterUTMCoordToolStripMenuItem, "enterUTMCoordToolStripMenuItem");
this.enterUTMCoordToolStripMenuItem.Click += new System.EventHandler(this.enterUTMCoordToolStripMenuItem_Click);
//
// switchDockingToolStripMenuItem
//
this.switchDockingToolStripMenuItem.Name = "switchDockingToolStripMenuItem";
resources.ApplyResources(this.switchDockingToolStripMenuItem, "switchDockingToolStripMenuItem");
this.switchDockingToolStripMenuItem.Click += new System.EventHandler(this.switchDockingToolStripMenuItem_Click);
//
// setHomeHereToolStripMenuItem
//
this.setHomeHereToolStripMenuItem.Name = "setHomeHereToolStripMenuItem";
resources.ApplyResources(this.setHomeHereToolStripMenuItem, "setHomeHereToolStripMenuItem");
this.setHomeHereToolStripMenuItem.Click += new System.EventHandler(this.setHomeHereToolStripMenuItem_Click);
//
// panelBASE
//
this.panelBASE.Controls.Add(this.splitter2);
this.panelBASE.Controls.Add(this.splitter1);
this.panelBASE.Controls.Add(this.panelMap);
this.panelBASE.Controls.Add(this.panelWaypoints);
this.panelBASE.Controls.Add(this.panelAction);
this.panelBASE.Controls.Add(this.label6);
resources.ApplyResources(this.panelBASE, "panelBASE");
this.panelBASE.Name = "panelBASE";
//
// timer1
//
this.timer1.Interval = 1200;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Command
//
dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(67)))), ((int)(((byte)(68)))), ((int)(((byte)(69)))));
dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White;
this.Command.DefaultCellStyle = dataGridViewCellStyle2;
this.Command.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox;
resources.ApplyResources(this.Command, "Command");
this.Command.Name = "Command";
//
// Param1
//
resources.ApplyResources(this.Param1, "Param1");
this.Param1.Name = "Param1";
this.Param1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Param2
//
resources.ApplyResources(this.Param2, "Param2");
this.Param2.Name = "Param2";
this.Param2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Param3
//
resources.ApplyResources(this.Param3, "Param3");
this.Param3.Name = "Param3";
this.Param3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Param4
//
resources.ApplyResources(this.Param4, "Param4");
this.Param4.Name = "Param4";
this.Param4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Lat
//
resources.ApplyResources(this.Lat, "Lat");
this.Lat.Name = "Lat";
this.Lat.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Lon
//
resources.ApplyResources(this.Lon, "Lon");
this.Lon.Name = "Lon";
this.Lon.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Alt
//
resources.ApplyResources(this.Alt, "Alt");
this.Alt.Name = "Alt";
this.Alt.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// coordZone
//
resources.ApplyResources(this.coordZone, "coordZone");
this.coordZone.Name = "coordZone";
//
// coordEasting
//
resources.ApplyResources(this.coordEasting, "coordEasting");
this.coordEasting.Name = "coordEasting";
//
// coordNorthing
//
resources.ApplyResources(this.coordNorthing, "coordNorthing");
this.coordNorthing.Name = "coordNorthing";
//
// MGRS
//
resources.ApplyResources(this.MGRS, "MGRS");
this.MGRS.Name = "MGRS";
//
// Delete
//
resources.ApplyResources(this.Delete, "Delete");
this.Delete.Name = "Delete";
this.Delete.Text = "X";
//
// Up
//
this.Up.DefaultCellStyle = dataGridViewCellStyle3;
resources.ApplyResources(this.Up, "Up");
this.Up.Image = ((System.Drawing.Image)(resources.GetObject("Up.Image")));
this.Up.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Stretch;
this.Up.Name = "Up";
//
// Down
//
this.Down.DefaultCellStyle = dataGridViewCellStyle4;
resources.ApplyResources(this.Down, "Down");
this.Down.Image = ((System.Drawing.Image)(resources.GetObject("Down.Image")));
this.Down.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Stretch;
this.Down.Name = "Down";
//
// Grad
//
resources.ApplyResources(this.Grad, "Grad");
this.Grad.Name = "Grad";
this.Grad.ReadOnly = true;
this.Grad.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Angle
//
resources.ApplyResources(this.Angle, "Angle");
this.Angle.Name = "Angle";
this.Angle.ReadOnly = true;
this.Angle.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// Dist
//
resources.ApplyResources(this.Dist, "Dist");
this.Dist.Name = "Dist";
this.Dist.ReadOnly = true;
this.Dist.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// AZ
//
resources.ApplyResources(this.AZ, "AZ");
this.AZ.Name = "AZ";
this.AZ.ReadOnly = true;
this.AZ.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// TagData
//
resources.ApplyResources(this.TagData, "TagData");
this.TagData.Name = "TagData";
this.TagData.ReadOnly = true;
//
// FlightPlanner
//
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.panelBASE);
resources.ApplyResources(this, "$this");
this.Name = "FlightPlanner";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FlightPlanner_FormClosing);
this.Load += new System.EventHandler(this.FlightPlanner_Load);
this.Resize += new System.EventHandler(this.Planner_Resize);
((System.ComponentModel.ISupportInitialize)(this.Commands)).EndInit();
this.panel5.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panelWaypoints.ResumeLayout(false);
this.panelWaypoints.PerformLayout();
this.panelAction.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panelMap.ResumeLayout(false);
this.panelMap.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
this.contextMenuStrip1.ResumeLayout(false);
this.panelBASE.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Controls.MyButton BUT_read;
private Controls.MyButton BUT_write;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.LinkLabel label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label Label1;
private System.Windows.Forms.TextBox TXT_homealt;
private System.Windows.Forms.TextBox TXT_homelng;
private System.Windows.Forms.TextBox TXT_homelat;
private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn1;
private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn2;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label lbl_status;
private Controls.MyDataGridView Commands;
private Controls.MyButton BUT_Add;
private System.Windows.Forms.Label LBL_WPRad;
private System.Windows.Forms.Label LBL_defalutalt;
private System.Windows.Forms.Label label5;
public BSE.Windows.Forms.Panel panelWaypoints;
public BSE.Windows.Forms.Panel panelAction;
private System.Windows.Forms.Panel panelMap;
public Controls.myGMAP MainMap;
private Controls.MyTrackBar trackBar1;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label lbl_distance;
private System.Windows.Forms.Label lbl_prevdist;
private BSE.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panelBASE;
private System.Windows.Forms.Label lbl_homedist;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.ToolStripMenuItem clearMissionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem polygonToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addPolygonPointToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearPolygonToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loiterToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loiterForeverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loitertimeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loitercirclesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem jumpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem jumpstartToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem jumpwPToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem deleteWPToolStripMenuItem;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.ToolStripMenuItem geoFenceToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem GeoFencedownloadToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem setReturnLocationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadFromFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem GeoFenceuploadToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem setROIToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autoWPToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createWpCircleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mapToolToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ContextMeasure;
private System.Windows.Forms.ToolStripMenuItem rotateMapToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem zoomToToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem prefetchToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem kMLOverlayToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem elevationGraphToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem rTLToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem landToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem takeoffToolStripMenuItem;
private System.Windows.Forms.ComboBox comboBoxMapType;
private System.Windows.Forms.ToolStripMenuItem fileLoadSaveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadWPFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveWPFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem trackerHomeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem reverseWPsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadAndAppendToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem savePolygonToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadPolygonToolStripMenuItem;
public System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.CheckBox chk_grid;
private System.Windows.Forms.ToolStripMenuItem insertWpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem rallyPointsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem getRallyPointsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveRallyPointsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem setRallyPointToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem clearRallyPointsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadKMLFileToolStripMenuItem;
private System.Windows.Forms.LinkLabel lnk_kml;
private System.Windows.Forms.ToolStripMenuItem modifyAltToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToFileToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem loadFromFileToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem prefetchWPPathToolStripMenuItem;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TextBox TXT_altwarn;
private System.Windows.Forms.ToolStripMenuItem pOIToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem poiaddToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem poideleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem poieditToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem enterUTMCoordToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadSHPFileToolStripMenuItem;
private Controls.Coords coords1;
private Controls.MyButton BUT_loadwpfile;
private Controls.MyButton BUT_saveWPFile;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.ToolStripMenuItem switchDockingToolStripMenuItem;
private BSE.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.ToolStripMenuItem insertSplineWPToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createSplineCircleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fromSHPToolStripMenuItem;
private System.Windows.Forms.Label lbl_wpfile;
private System.Windows.Forms.ToolStripMenuItem textToolStripMenuItem;
public System.Windows.Forms.CheckBox CHK_verifyheight;
public System.Windows.Forms.TextBox TXT_WPRad;
public System.Windows.Forms.TextBox TXT_DefaultAlt;
public System.Windows.Forms.TextBox TXT_loiterrad;
public System.Windows.Forms.CheckBox CHK_splinedefault;
public System.Windows.Forms.ComboBox CMB_altmode;
private System.Windows.Forms.ToolStripMenuItem areaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem setHomeHereToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem areaToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createCircleSurveyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem currentPositionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem surveyGridToolStripMenuItem;
private MyButton but_writewpfast;
private System.Windows.Forms.DataGridViewComboBoxColumn Command;
private System.Windows.Forms.DataGridViewTextBoxColumn Param1;
private System.Windows.Forms.DataGridViewTextBoxColumn Param2;
private System.Windows.Forms.DataGridViewTextBoxColumn Param3;
private System.Windows.Forms.DataGridViewTextBoxColumn Param4;
private System.Windows.Forms.DataGridViewTextBoxColumn Lat;
private System.Windows.Forms.DataGridViewTextBoxColumn Lon;
private System.Windows.Forms.DataGridViewTextBoxColumn Alt;
private System.Windows.Forms.DataGridViewTextBoxColumn coordZone;
private System.Windows.Forms.DataGridViewTextBoxColumn coordEasting;
private System.Windows.Forms.DataGridViewTextBoxColumn coordNorthing;
private System.Windows.Forms.DataGridViewTextBoxColumn MGRS;
private System.Windows.Forms.DataGridViewButtonColumn Delete;
private System.Windows.Forms.DataGridViewImageColumn Up;
private System.Windows.Forms.DataGridViewImageColumn Down;
private System.Windows.Forms.DataGridViewTextBoxColumn Grad;
private System.Windows.Forms.DataGridViewTextBoxColumn Angle;
private System.Windows.Forms.DataGridViewTextBoxColumn Dist;
private System.Windows.Forms.DataGridViewTextBoxColumn AZ;
private System.Windows.Forms.DataGridViewTextBoxColumn TagData;
}
}
|
gpl-3.0
|
tgerring/go-ethereum
|
core/block_cache_test.go
|
2003
|
// Copyright 2015 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum 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.
//
// go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package core
import (
"math/big"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
func newChain(size int) (chain []*types.Block) {
var parentHash common.Hash
for i := 0; i < size; i++ {
head := &types.Header{ParentHash: parentHash, Number: big.NewInt(int64(i))}
block := types.NewBlock(head, nil, nil, nil)
chain = append(chain, block)
parentHash = block.Hash()
}
return chain
}
func insertChainCache(cache *BlockCache, chain []*types.Block) {
for _, block := range chain {
cache.Push(block)
}
}
func TestNewBlockCache(t *testing.T) {
chain := newChain(3)
cache := NewBlockCache(2)
insertChainCache(cache, chain)
if cache.hashes[0] != chain[1].Hash() {
t.Error("oldest block incorrect")
}
}
func TestInclusion(t *testing.T) {
chain := newChain(3)
cache := NewBlockCache(3)
insertChainCache(cache, chain)
for _, block := range chain {
if b := cache.Get(block.Hash()); b == nil {
t.Errorf("getting %x failed", block.Hash())
}
}
}
func TestDeletion(t *testing.T) {
chain := newChain(3)
cache := NewBlockCache(3)
insertChainCache(cache, chain)
cache.Delete(chain[1].Hash())
if cache.Has(chain[1].Hash()) {
t.Errorf("expected %x not to be included")
}
}
|
gpl-3.0
|
sknepneklab/SAMoS
|
src/constraints/constraint_tetrahedron.cpp
|
3579
|
/* ***************************************************************************
*
* Copyright (C) 2013-2016 University of Dundee
* All rights reserved.
*
* This file is part of SAMoS (Soft Active Matter on Surfaces) program.
*
* SAMoS 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.
*
* SAMoS 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/>.
*
* ****************************************************************************/
/*!
* \file constraint_tetrahedron.cpp
* \author Rastko Sknepnek, sknepnek@gmail.com
* \date 18-Aug-2015
* \brief Implementation of the tetrahedron constraint
*/
#include "constraint_tetrahedron.hpp"
/*! Compute normal to the surface at p
*/
void ConstraintTetrahedron::compute_normal(Particle& p, double& Nx, double& Ny, double& Nz)
{
this->compute_gradient(p,Nx,Ny,Nz);
// Normalize N
double len_N = sqrt(Nx*Nx + Ny*Ny + Nz*Nz);
Nx /= len_N; Ny /= len_N; Nz /= len_N;
p.Nx = Nx; p.Ny = Ny; p.Nz = Nz;
}
/*! Compute gradient at a point
* \param p reference to a point
*/
void ConstraintTetrahedron::compute_gradient(Particle&p, double& gx, double& gy, double& gz)
{
Vector3d pos = Vector3d(p.x,p.y,p.z);
Vector3d p_a1 = pos - m_a1;
Vector3d p_a2 = pos - m_a2;
Vector3d p_a3 = pos - m_a3;
Vector3d p_a4 = pos - m_a4;
double l1 = p_a1.len();
double l2 = p_a2.len();
double l3 = p_a3.len();
double l4 = p_a4.len();
double l1_3 = l1*l1*l1, l2_3 = l2*l2*l2, l3_3 = l3*l3*l3, l4_3 = l4*l4*l4;
gx = -(p_a1.x/l1_3 + p_a2.x/l2_3 + p_a3.x/l3_3 + p_a4.x/l4_3);
gy = -(p_a1.y/l1_3 + p_a2.y/l2_3 + p_a3.y/l3_3 + p_a4.y/l4_3);
gz = -(p_a1.z/l1_3 + p_a2.z/l2_3 + p_a3.z/l3_3 + p_a4.z/l4_3);
}
/*! Compute constraint value at particle p
* The constraint is given as the equipotential surface of the potential
* \f$ V(\vec r) = \sum_{i=1}^{4}\frac{1}{|\vec r - \vec a_i|} \f$, where
* \f$ \vec a_i \f$ are position of the four unit charges generating the
* potential.
* \param p reference to the particle
*/
double ConstraintTetrahedron::constraint_value(Particle& p)
{
Vector3d pos = Vector3d(p.x,p.y,p.z);
Vector3d p_a1 = pos - m_a1;
Vector3d p_a2 = pos - m_a2;
Vector3d p_a3 = pos - m_a3;
Vector3d p_a4 = pos - m_a4;
double g = 1.0/sqrt(dot(p_a1, p_a1));
g += 1.0/sqrt(dot(p_a2, p_a2));
g += 1.0/sqrt(dot(p_a3, p_a3));
g += 1.0/sqrt(dot(p_a4, p_a4));
return g - m_value;
}
/*! Rescale tetrahedron size and make sure that all particles are still on it.
* Rescaling is done only at certain steps and only if rescale
* factor is not equal to 1.
*/
bool ConstraintTetrahedron::rescale()
{
if (m_rescale != 1.0)
{
int step = m_system->get_step();
if ((step % m_rescale_freq == 0) && (step < m_rescale_steps))
{
m_s *= m_scale;
m_a1 = m_s*tetra_a1;
m_a2 = m_s*tetra_a2;
m_a3 = m_s*tetra_a3;
m_a4 = m_s*tetra_a4;
for (int i = 0; i < m_system->size(); i++)
{
Particle& p = m_system->get_particle(i);
this->enforce(p);
}
return true;
}
}
return false;
}
|
gpl-3.0
|
Flozi95/AlarmWorkflow
|
BackendServices/AlarmWorkflow.BackendService.AddressingContracts/EntryObjects/LoopEntryObject.cs
|
1397
|
// This file is part of AlarmWorkflow.
//
// AlarmWorkflow 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.
//
// AlarmWorkflow 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 AlarmWorkflow. If not, see <http://www.gnu.org/licenses/>.
using System.Runtime.Serialization;
namespace AlarmWorkflow.BackendService.AddressingContracts.EntryObjects
{
/// <summary>
/// Represents a "Loop" entry in the address book.
/// </summary>
[DataContract()]
public class LoopEntryObject
{
#region Constants
/// <summary>
/// Defines the type identifier for this entry object.
/// </summary>
public const string TypeId = "Loop";
#endregion
#region Properties
/// <summary>
/// Gets/sets the loop code represented by this entry object.
/// </summary>
[DataMember()]
public string Loop { get; set; }
#endregion
}
}
|
gpl-3.0
|
jcntux/Dolibarr
|
htdocs/public/members/public_list.php
|
5519
|
<?php
/* Copyright (C) 2001-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
* Copyright (C) 2004-2009 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/public/members/public_list.php
* \ingroup member
* \brief File sample to list members
*/
define("NOLOGIN",1); // This means this output page does not require to be logged.
define("NOCSRFCHECK",1); // We accept to go on this page from external web site.
// For MultiCompany module
$entity=(! empty($_GET['entity']) ? (int) $_GET['entity'] : 1);
if (is_int($entity))
{
define("DOLENTITY", $entity);
}
require '../../main.inc.php';
// Security check
if (empty($conf->adherent->enabled)) accessforbidden('',1,1,1);
$langs->load("main");
$langs->load("members");
$langs->load("companies");
$langs->load("other");
/**
* Show header for member list
*
* @param string $title Title
* @param string $head More info into header
* @return void
*/
function llxHeaderVierge($title, $head = "")
{
global $user, $conf, $langs;
header("Content-type: text/html; charset=".$conf->file->character_set_client);
print "<html>\n";
print "<head>\n";
print "<title>".$title."</title>\n";
if ($head) print $head."\n";
print "</head>\n";
print "<body>\n";
}
/**
* Show footer for member list
*
* @return void
*/
function llxFooterVierge()
{
printCommonFooter('public');
print "</body>\n";
print "</html>\n";
}
$sortfield = GETPOST("sortfield",'alpha');
$sortorder = GETPOST("sortorder",'alpha');
$page = GETPOST("page",'int');
if ($page == -1) { $page = 0; }
$offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
$filter=GETPOST('filter');
$statut=GETPOST('statut');
if (! $sortorder) { $sortorder="ASC"; }
if (! $sortfield) { $sortfield="nom"; }
/*
* View
*/
llxHeaderVierge($langs->trans("ListOfValidatedPublicMembers"));
$sql = "SELECT rowid, firstname, lastname, societe, zip, town, email, birth, photo";
$sql.= " FROM ".MAIN_DB_PREFIX."adherent";
$sql.= " WHERE entity = ".$entity;
$sql.= " AND statut = 1";
$sql.= " AND public = 1";
$sql.= $db->order($sortfield,$sortorder);
$sql.= $db->plimit($conf->liste_limit+1, $offset);
//$sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, zip, town, d.email, t.libelle as type, d.morphy, d.statut, t.cotisation";
//$sql .= " FROM ".MAIN_DB_PREFIX."adherent as d, ".MAIN_DB_PREFIX."adherent_type as t";
//$sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = $statut";
//$sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit, $offset);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
$i = 0;
$param="&statut=$statut&sortorder=$sortorder&sortfield=$sortfield";
print_barre_liste($langs->trans("ListOfValidatedPublicMembers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, 0, '');
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre">';
print '<td><a href="'.$_SERVER["PHP_SELF"].'?page='.$page.'&sortorder=ASC&sortfield=firstname">'.$langs->trans("Firstname").'</a>';
print ' <a href="'.$_SERVER['PHP_SELF'].'?page='.$page.'&sortorder=ASC&sortfield=lastname">'.$langs->trans("Lastname").'</a>';
print ' / <a href="'.$_SERVER["PHP_SELF"].'?page='.$page.'&sortorder=ASC&sortfield=societe">'.$langs->trans("Company").'</a></td>'."\n";
//print_liste_field_titre($langs->trans("DateToBirth"),"public_list.php","birth",'',$param,$sortfield,$sortorder); // est-ce nécessaire ??
print_liste_field_titre($langs->trans("EMail"),"public_list.php","email",'',$param,$sortfield,$sortorder);
print_liste_field_titre($langs->trans("Zip"),"public_list.php","zip","",$param,$sortfield,$sortorder);
print_liste_field_titre($langs->trans("Town"),"public_list.php","town","",$param,$sortfield,$sortorder);
print "<td>".$langs->trans("Photo")."</td>\n";
print "</tr>\n";
$var=True;
while ($i < $num && $i < $conf->liste_limit)
{
$objp = $db->fetch_object($result);
$var=!$var;
print "<tr $bc[$var]>";
print '<td><a href="public_card.php?id='.$objp->rowid.'">'.dolGetFirstLastname($obj->firstname, $obj->lastname).($objp->societe?' / '.$objp->societe:'').'</a></td>'."\n";
//print "<td>$objp->birth</td>\n"; // est-ce nécessaire ??
print '<td>'.$objp->email.'</td>'."\n";
print '<td>'.$objp->zip.'</td>'."\n";
print '<td>'.$objp->town.'</td>'."\n";
if (isset($objp->photo) && $objp->photo != '')
{
$form = new Form($db);
print '<td>';
print $form->showphoto('memberphoto', $objp, 64);
print '</td>'."\n";
}
else
{
print "<td> </td>\n";
}
print "</tr>";
$i++;
}
print "</table>";
}
else
{
dol_print_error($db);
}
$db->close();
llxFooterVierge();
?>
|
gpl-3.0
|
Tomtombinary/RPiHackFM
|
gen/com/example/rpihackfm/BuildConfig.java
|
163
|
/** Automatically generated file. DO NOT MODIFY */
package com.example.rpihackfm;
public final class BuildConfig {
public final static boolean DEBUG = true;
}
|
gpl-3.0
|
uplusware/erisemail
|
antispam/antispam.cpp
|
3363
|
/*
Copyright (c) openheap, uplusware
uplusware@gmail.com
*/
#include <stdio.h>
#include "antispam.h"
/*
Brief:
Initiate the mfilter, invoked by MTA in a new session beginning
Parameter:
Parameter string for this filter
Return:
Return a filter's handler
*/
void* mfilter_init(const char* param)
{
///////////////////////////////////////////////////////////////
// Example codes
MailFilter * filter = new MailFilter;
if(filter)
{
filter->is_spam = -1;
filter->is_virs = -1;
filter->param = param;
}
return (void*)filter;
// End example
///////////////////////////////////////////////////////////////
}
/*
Brief:
Get the local email domain name
Parameter:
The handler of the exist filter
Return:
None
*/
void mfilter_emaildomain(void* filter, const char* domain, unsigned int len)
{
}
/*
Brief:
Get the client site's IP in a MTA session
Parameter:
The handler of the exist filter
A pointer of the buffer which storage the ip
The length of buffer
Return:
None
*/
void mfilter_clientip(void* filter, const char* ip, unsigned int len)
{
///////////////////////////////////////////////////////////////
// Example codes
MailFilter * tfilter = (MailFilter *)filter;
// End example
///////////////////////////////////////////////////////////////
}
/*
Brief:
Get the client site's domai nname in a MTA session
Parameter:
The handler of the exist filter
A pointer of the buffer which storage the domain name
The length of buffer
Return:
None
*/
void mfilter_clientdomain(void * filter, const char* domain, unsigned int len)
{
}
/*
Brief:
Get the address of "MAIL FROM"
Parameter:
The handler of the exist filter
A pointer of the buffer which storage the address of "MAIL FROM"
The length of buffer
Return:
None
*/
void mfilter_mailfrom(void * filter, const char* from, unsigned int len)
{
}
/*
Brief:
Get the address of "RCPT TO"
Parameter:
The handler of the exist filter
A pointer of the buffer which storage the address of "RCPT TO"
The length of buffer
Return:
None
*/
void mfilter_rcptto(void * filter, const char* to, unsigned int len)
{
}
/*
Brief:
Get each line of mail body
Parameter:
The handler of the exist filter
A pointer of the buffer which storage the mail body
The length of buffer
Return:
None
*/
void mfilter_data(void * filter, const char* data, unsigned int len)
{
}
/*
Brief:
check the eml file
Parameter:
The handler of the exist filter
A zero teminated string to the eml file path
The length of path string
Return:
None
*/
void mfilter_eml(void * filter, const char* emlpath, unsigned int len)
{
}
/*
Brief:
Get the result of filter
Parameter:
The handler of the exist filter
The flag whether the mail is a spam mail. -1 is a general mail, other value is spam mail
Return:
None
*/
void mfilter_result(void * filter, int* is_spam)
{
///////////////////////////////////////////////////////////////
// Example codes
*is_spam = -1;
// End example
///////////////////////////////////////////////////////////////
}
/*
Brief:
Destory the filter
Parameter:
The handler of the exist filter
Return:
None
*/
void mfilter_exit(void * filter)
{
///////////////////////////////////////////////////////////////
// Example codes
delete filter;
// End example
///////////////////////////////////////////////////////////////
}
|
gpl-3.0
|
UtrechtUniversity/yoda-ansible
|
library/yoda_addgroupuser.py
|
2328
|
#!/usr/bin/python
# Copyright (c) 2017-2018 Utrecht University
# GNU General Public License v3.0
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'supported_by': 'community',
'status': ['preview']
}
from ansible.module_utils.basic import *
IRODSCLIENT_AVAILABLE = False
try:
import textwrap
from irods.session import iRODSSession
from irods.rule import Rule
except ImportError:
pass
else:
IRODSCLIENT_AVAILABLE = True
def get_session():
env_file = os.path.expanduser('~/.irods/irods_environment.json')
with open(env_file) as data_file:
ienv = json.load(data_file)
return (iRODSSession(irods_env_file=env_file), ienv)
def main():
module = AnsibleModule(
argument_spec=dict(
groupName=dict(default=None, required=True),
user=dict(default=None, required=True),
role=dict(default=None, required=True),
state=dict(default="present")
),
supports_check_mode=True)
groupName = module.params["groupName"]
user = module.params["user"]
role = module.params["role"]
state = module.params["state"]
if IRODSCLIENT_AVAILABLE:
try:
session, ienv = get_session()
except iRODSException:
module.fail_json(
msg="Could not establish irods connection. Please check ~/.irods/irods_environment.json"
)
else:
module.fail_json(msg="python-irodsclient needs to be installed")
changed = False
# Rule to add an user to a group in Yoda.
rule_body = textwrap.dedent('''\
test {{
uuGroupUserAdd(*groupName, *user, *status, *message);
uuGroupUserChangeRole(*groupName, *user, *role, *status, *message);
}}''')
# Rule parameters.
input_params = {
'*groupName': '"{groupName}"'.format(**locals()),
'*user': '"{user}"'.format(**locals()),
'*role': '"{role}"'.format(**locals())
}
output = 'ruleExecOut'
# Execute rule.
if not module.check_mode:
myrule = Rule(session, body=rule_body,
params=input_params, output=output)
myrule.execute()
changed = True
module.exit_json(
changed=changed,
irods_environment=ienv)
if __name__ == '__main__':
main()
|
gpl-3.0
|
runpaint/eye
|
spec/eye/new_spec.rb
|
933
|
describe "Eye.new" do
it "initialises without arguments" do
lambda{eye = Eye.new}.should_not raise_error
end
it "creates an instance of Eye" do
eye = Eye.new
eye.class.should == Eye
eye.should.is_a?(Eye)
end
it "accepts a ':type => :symbol' argument" do
lambda{Eye.new(:type => :hash)}.should_not raise_error(ArgumentError)
end
it "requires the argument to :type to be a symbol if given" do
lambda{Eye.new(:type => 1)}.should raise_error(ArgumentError)
lambda{Eye.new(:type => 'hash')}.should raise_error(ArgumentError)
end
it "raises an ArgumentError on unknown keys" do
lambda{Eye.new(:type => :hash, :f => :g)}.should raise_error(ArgumentError)
lambda{Eye.new(:f => :bar, :b => :foo)}.should raise_error(ArgumentError)
end
it "raises an ArgumentError exception on invalid types" do
lambda{Eye.new(:type => :foo)}.should raise_error(ArgumentError)
end
end
|
gpl-3.0
|
puhnastik/robot-plugin
|
src/main/scala/amailp/intellij/robot/structureView/RobotTreeBasedStructureViewBuilder.scala
|
683
|
package amailp.intellij.robot.structureView
import amailp.intellij.robot.psi.RobotPsiFile
import com.intellij.ide.structureView.{StructureViewTreeElement, StructureViewModel, TreeBasedStructureViewBuilder}
import com.intellij.openapi.editor.Editor
import amailp.intellij.robot.psi
class RobotTreeBasedStructureViewBuilder(psiFile: RobotPsiFile) extends TreeBasedStructureViewBuilder {
override def createStructureViewModel(editor: Editor): StructureViewModel = {
val element: StructureViewTreeElement = psiFile.findChildByClass(classOf[psi.Tables]).structureTreeElement
new RobotStructureViewModel(psiFile, editor, element)
}
override val isRootNodeShown = false
}
|
gpl-3.0
|
Karlosjp/Clase-DAM
|
Luis Braille/1 DAM/Programacion - Entornos/2 Trimestre/practicaprogramacion/src/herencia/ejercicio02/Publicacion.java
|
608
|
package herencia.ejercicio02;
public abstract class Publicacion {
protected String strIsbn, strTitulo;
protected int intAnhoPublicacion;
public Publicacion() {
this.strIsbn = "";
this.strTitulo = "";
this.intAnhoPublicacion = 1970;
}
public Publicacion(String strIsbn, String strTitulo, int intAnhoPublicacion) {
this.strIsbn = strIsbn;
this.strTitulo = strTitulo;
this.intAnhoPublicacion = intAnhoPublicacion;
}
@Override
public String toString() {
return "ISBN: " + this.strIsbn + ", título: " + this.strTitulo + ", año de publicación: "
+ this.intAnhoPublicacion;
}
}
|
gpl-3.0
|
EuphoriaDev/Euphoria-VK-Client
|
app/src/main/java/ru/euphoriadev/vk/adapter/NoteAdapter.java
|
2682
|
package ru.euphoriadev.vk.adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import ru.euphoriadev.vk.R;
import ru.euphoriadev.vk.api.model.VKNote;
import ru.euphoriadev.vk.common.AppLoader;
import ru.euphoriadev.vk.common.TypefaceManager;
import ru.euphoriadev.vk.util.ViewUtil;
/**
* Created by Igor on 09.12.15.
*/
public class NoteAdapter extends BaseArrayAdapter<VKNote> {
AppLoader loader;
SimpleDateFormat sdf;
Date date;
XmlPullParser xmlParser;
public NoteAdapter(Context context, ArrayList<VKNote> values) {
super(context, values);
loader = AppLoader.getLoader();
sdf = new SimpleDateFormat("d MMM, yyyy");
date = new Date(System.currentTimeMillis());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
view = getInflater().inflate(R.layout.list_item_note, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final VKNote item = getItem(position);
holder.tvTitle.setTypeface(TypefaceManager.getBoldTypeface(getContext()));
ViewUtil.setTypeface(holder.tvText);
ViewUtil.setTypeface(holder.tvDate);
holder.tvTitle.setText(item.title);
holder.tvText.setText(Html.fromHtml(item.text));
holder.tvDate.setText(sdf.format(item.date * 1000));
return view;
}
public String parseForText(VKNote note) throws XmlPullParserException {
// if (xmlParser == null) {
// xmlParser = Xml.newPullParser();
// }
//
// while (xmlParser.getEventType() != XmlPullParser.END_DOCUMENT) {
// }
// String xmlText = note.text;
return null;
}
private class ViewHolder {
public CardView cardView;
public TextView tvTitle;
public TextView tvText;
public TextView tvDate;
public ViewHolder(View v) {
cardView = (CardView) v.findViewById(R.id.cardNote);
tvTitle = (TextView) v.findViewById(R.id.tvNoteTitle);
tvText = (TextView) v.findViewById(R.id.tvNoteText);
tvDate = (TextView) v.findViewById(R.id.tvNoteDate);
}
}
}
|
gpl-3.0
|
Elexorien/technoMelonfirma
|
src/main/java/technofirma/items/ItemWoodenOilBucket.java
|
2310
|
package technofirma.items;
import buildcraft.BuildCraftEnergy;
import buildcraft.energy.ItemBucketBuildcraft;
import com.bioxx.tfc.Items.ItemTerra;
import com.bioxx.tfc.api.Enums.EnumItemReach;
import com.bioxx.tfc.api.Enums.EnumSize;
import com.bioxx.tfc.api.Enums.EnumWeight;
import com.bioxx.tfc.api.Interfaces.ISize;
import com.bioxx.tfc.api.TFCItems;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBucket;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidRegistry;
import technofirma.core.Reference;
import java.util.List;
public class ItemWoodenOilBucket extends ItemBucket implements ISize
{
private final ItemStack container = new ItemStack(TFCItems.woodenBucketEmpty);
public ItemWoodenOilBucket(Block block)
{
super(block);
}
//public Item setUnlocalizedName(String name)
//{
// return super.setUnlocalizedName(name);
//}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister register)
{
this.itemIcon = register.registerIcon(Reference.MOD_ID + "WoodenOilBucket");
}
//public ItemStack getContainerItem(ItemStack stack)
//{
// return this.container.copy();
//}
//public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
//{
// return stack;
//}
@Override
public EnumSize getSize(ItemStack is)
{
return EnumSize.MEDIUM;
}
@Override
public EnumWeight getWeight(ItemStack is)
{
return EnumWeight.LIGHT;
}
@Override
public EnumItemReach getReach(ItemStack is)
{
return EnumItemReach.SHORT;
}
@Override
public boolean canStack()
{
return false;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void addInformation(ItemStack is, EntityPlayer player, List arraylist, boolean flag)
{
ItemTerra.addSizeInformation(is, arraylist);
}
}
|
gpl-3.0
|
javastraat/arduino
|
libraries/Menu/Menu.cpp
|
2525
|
/*
||
|| @file Menu.cpp
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Provide an easy way of making menus
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include "Menu.h"
Menu::Menu( void (*onMenuUse)(MenuItemInterface*) ){
menuUse = onMenuUse;
menuChange = 0;
previousIndex = currentIndex = numberOfMenuItems = 0;
item[currentIndex] = 0;
}
Menu::Menu( void (*onMenuUse)(MenuItemInterface*) , void (*onMenuChange)(MenuItemInterface*) ){
menuUse = onMenuUse;
menuChange = onMenuChange;
previousIndex = currentIndex = numberOfMenuItems = 0;
item[currentIndex] = 0;
}
void Menu::up(){
select(currentIndex+1);
}
void Menu::down(){
select(currentIndex-1);
}
void Menu::previous(){
select(previousIndex);
}
bool Menu::select(byte select){
if (select>=0 && select<numberOfMenuItems){
setCurrentIndex(select);
if (menuChange!=0){
menuChange( item[currentIndex]->use() );
}
return true;
}
return false;
}
void Menu::use(){
menuUse(item[currentIndex]->use());
}
MenuItemInterface* Menu::getCurrentItem(){
return item[currentIndex];
}
bool Menu::addMenuItem( MenuItem& menuItem ){
if (numberOfMenuItems+1<MAXIMUM_MENU_ITEMS){
item[numberOfMenuItems++] = &menuItem;
return true;
}
return false;
}
bool Menu::isCurrentSubMenu(){ return item[currentIndex]->isSubMenu(); }
//private
void Menu::setCurrentIndex( byte select ){
if (select>=0 && select<numberOfMenuItems){
previousIndex = currentIndex;
currentIndex = select;
}
}
/*
|| @changelog
|| | 1.0 2009-04-22 - Alexander Brevig : Initial Release
|| #
*/
|
gpl-3.0
|
IET-OU/nquire-web-source
|
app/src/main/java/org/greengin/nquireit/entities/users/RoleType.java
|
575
|
package org.greengin.nquireit.entities.users;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum RoleType {
NONE,
LOGGED_IN,
ADMIN,
MEMBER;
@JsonValue
public String getValue() { return this.name().toLowerCase(); }
@JsonCreator
public static RoleType create(String val) {
RoleType[] units = RoleType.values();
for (RoleType unit : units) {
if (unit.getValue().equals(val)) {
return unit;
}
}
return NONE;
}
}
|
gpl-3.0
|
Inorizushi/DDR-SN1HD
|
Scripts/01 ThemeInfo.lua
|
158
|
-- theme identification:
themeInfo = {
ProductCode = "DDR SuperNOVA 3",
Name = "DDR SN3",
Version = "beta 0",
Date = "2016????",
Author = "MidflightDigital"
}
|
gpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.