repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
yondri/newyorkando | wp-content/themes/chaoticsoul/header.php | 1345 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<title><?php wp_title(); ?> <?php bloginfo('name'); ?></title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/ie.css" type="text/css" media="screen" />
<![endif]-->
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php
if ( is_singular() ) wp_enqueue_script( 'comment-reply' );
wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page">
<div id="header">
<h1><a href="<?php echo home_url( '/' ); ?>"><?php bloginfo('title'); ?></a></h1>
<div class="description"><?php bloginfo('description'); ?></div>
</div>
<div class="hr"> </div> <!-- because IE sucks at styling HRs -->
<div id="headerimg" class="clearfix">
<div id="header-overlay"> </div>
<div id="header-image"><img alt="" src="<?php header_image() ?>" /></div>
</div>
<div class="hr"> </div>
<div id="wrapper" class="clearfix">
| gpl-2.0 |
tejdeeps/tejcs.com | frameworks/phpdevshell/plugins/ExamplePlugin/controllers/example/widget-example.php | 1597 | <?php
class WidgetExample extends PHPDS_controller
{
/**
* We always start by overriding the execute method for the controller.
* @author Jason Schoeman
*/
public function execute()
{
// a Default heading.
$this->template->heading(_('I wanna add my widget!'));
// Some info regarding this node.
$this->template->info(_('So you just finished one of your widgets and you want to add it to your page, and some users should be able to see it.'));
$this->template->note(_('Remember, an ajax node type must also have the correct permissions else it wont show.'));
/////////////////
// This is how you load a plugin, in this case we have registered 'views' plugin class and calling it.
// This plugin is using Smarty to split HTML from code.
$view = $this->factory('views');
// Continue to next example.
$this->template->requestWidget('2282118247', 'widget1', 'data=Hello World&moredata=Foobar');
// If you are lazy and dont want to locate menus permanent id, locate it from path with.
$this->template->requestWidget('1337263253', 'widget2', 'more_about=More about Linux...');
// Ajax as main page example.
$this->template->requestAjax('1821693117', 'ajax1', 'data=FooBar');
// Again you can call multiple lightbox pages...
$lightboxurl = $this->template->requestLightbox('1133107805', 'lightbox', 'data=Lightbox Foobar');
$view->set('lightboxurl', $lightboxurl);
// Output View.
// The view also has the same name as the controller, you can find the view in ExamplePlugin/views/readme-example.tpl
$view->show();
}
}
return 'WidgetExample'; | gpl-2.0 |
RaphaelFreire/java | src/model/BoxDemo4.java | 939 | package model;
/**
* @author raphaelmachadofreire
* Instruções às classes
* Utilizando método volume da Classe Box que retorna um valor
* Capítulo 6 - Página 118
*/
public class BoxDemo4 {
public static void main(String args[]){
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// atribuir valor às variáveis de instâncias de mybox1
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// atribuir valor às variáveis de instâncias de mybox2
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// obter o volume da primeira caixa
vol = mybox1.volume();
System.out.println("O volume é " + vol);
// obter o volume da segunda caixa
vol = mybox2.volume();
System.out.println("O volume é " + vol);
}
}
| gpl-2.0 |
midaboghetich/netnumero | gen/com/numhero/client/widget/com_numhero_client_widget_HRElement_HRElementUiBinderImpl_GenBundle_en_US_InlineClientBundleGenerator.java | 1509 | package com.numhero.client.widget;
import com.google.gwt.resources.client.ResourcePrototype;
import com.google.gwt.core.client.GWT;
public class com_numhero_client_widget_HRElement_HRElementUiBinderImpl_GenBundle_en_US_InlineClientBundleGenerator implements com.numhero.client.widget.HRElement_HRElementUiBinderImpl_GenBundle {
public com.numhero.client.widget.HRElement_HRElementUiBinderImpl_GenCss_style style() {
if (style == null) {
style = new com.numhero.client.widget.HRElement_HRElementUiBinderImpl_GenCss_style() {
private boolean injected;
public boolean ensureInjected() {
if (!injected) {
injected = true;
com.google.gwt.dom.client.StyleInjector.inject(getText());
return true;
}
return false;
}
public String getName() {
return "style";
}
public String getText() {
return com.google.gwt.i18n.client.LocaleInfo.getCurrentLocale().isRTL() ? (("")) : ((""));
}
}
;
}
return style;
}
private static com.numhero.client.widget.HRElement_HRElementUiBinderImpl_GenCss_style style;
public ResourcePrototype[] getResources() {
return new ResourcePrototype[] {
style(),
};
}
public native ResourcePrototype getResource(String name) /*-{
switch (name) {
case 'style': return [email protected]_HRElementUiBinderImpl_GenBundle::style()();
}
return null;
}-*/;
}
| gpl-2.0 |
moppedijk/jsd_02_application | fietsenstallingen/server/server.js | 7912 | var _localData = "http://api.fietsenstallingen.local/veiligstalling_small.xml";
var _remoteData = "http://www.veiligstallen.nl/veiligstallen.xml";
var _development = false;
/* ==========================================================================
*
* Get Cycles server route
*
========================================================================== */
Router.route( "/api/cycles", { where: "server" } ).get( function() {
// NodeJS request/response objects
var params = this.params.query;
var request = this.request;
var response = this.response;
var url = _remoteData;
if(_development) {
url = _localData;
}
try {
HTTP.get( url, {}, onFetchCyclesComplete );
} catch ( error ) {
errorResponse({
message: "Something went wrong...",
error: error
});
}
function onFetchCyclesComplete(error, response) {
if(error) {
errorResponse({
message: "Something went wrong...",
error: error
});
} else {
xml2js.parseString( response.content, {
explicitArray: false,
emptyTag: undefined
}, onXmlToJsComplete
);
};
}
function onXmlToJsComplete(error, result) {
if( error ){
errorResponse({
message: "Something went wrong...",
error: error
});
} else {
findObjectsByLocality( result );
};
};
function findObjectsByLocality( result ) {
var result = result.Fietsenstallingen.Fietsenstalling;
var resultObj = [];
for(var i = 0; i < result.length; i++) {
if(result[i].Plaats) {
// Check if locality and city are the same
if(cleanUpString(params.city) === cleanUpString(result[i].Plaats)) {
resultObj.push(result[i]);
}
}
};
if(resultObj.length > 0) {
// Response content-type is JSON
response.writeHead(200, {'Content-type': 'application/json'});
// Response write
response.write( JSON.stringify( refactorObjectKeys(resultObj) ));
// Response end
response.end();
} else {
errorResponse({
message: "Something went wrong, " + params.city + " not found!"
});
};
};
function errorResponse ( error ) {
// Response content-type is JSON
response.writeHead(400, {'Content-type': 'application/json'});
// Response write
response.write( JSON.stringify( error ));
// Response end
response.end();
}
function cleanUpString( string ) {
return string.toLowerCase().replace(/\-/g,' ');
}
});
/* ==========================================================================
*
* Get Cycles ID server route
*
========================================================================== */
Router.route( "/api/cycles/:id", { where: "server" } ).get( function() {
// Get params
var cycleId = this.params.id;
var request = this.request;
var response = this.response;
var url = _remoteData;
if(_development) {
url = _localData;
}
try {
HTTP.get( url, {}, onFetchCyclesComplete );
} catch ( error ) {
errorResponse({
message: "Something went wrong...",
error: error
});
}
function onFetchCyclesComplete(error, response) {
if(error) {
errorResponse({
message: "Something went wrong...",
error: error
});
} else {
xml2js.parseString( response.content, {
explicitArray: false,
emptyTag: undefined
}, onXmlToJsComplete
);
};
}
function onXmlToJsComplete(error, result) {
if( error ){
errorResponse({
message: "Something went wrong...",
error: error
});
} else {
findObjectById( result );
};
};
function findObjectById( result ) {
var result = result.Fietsenstallingen.Fietsenstalling;
var resultObj = [];
for(var i = 0; i < result.length; i++) {
if(result[i].ID == cycleId) {
resultObj.push(result[i]);
}
}
if(resultObj.length > 0) {
// Response content-type is JSON
response.writeHead(200, {'Content-type': 'application/json'});
// Response write
response.write( JSON.stringify( refactorObjectKeys(resultObj) ));
// Response end
response.end();
} else {
errorResponse({
message: "Something went wrong, no match with id: " + cycleId + " found"
});
};
};
function errorResponse ( error ) {
// Response content-type is JSON
response.writeHead(400, {'Content-type': 'application/json'});
// Response write
response.write( JSON.stringify( error ));
// Response end
response.end();
}
});
/* ==========================================================================
*
* Helper functions
*
========================================================================== */
// Refactor Object Keys
function refactorObjectKeys (result) {
var resultObj = [];
// Loop trought results in result
for(var i = 0; i < result.length; i++) {
var cycleObj = {};
// Beheerder
if (result[i].Beheerder) {
cycleObj.administrator = result[i].Beheerder;
} else {
cycleObj.administrator = false;
}
// BeheerderContact
if (result[i].BeheerderContact) {
cycleObj.administratorContact = result[i].BeheerderContact;
} else {
cycleObj.administratorContact = false;
}
// CapaciteitFiets
if (result[i].CapaciteitFiets) {
cycleObj.capacityBike = result[i].CapaciteitFiets;
} else {
cycleObj.capacityBike = false;
}
// CapaciteitTotaal
if (result[i].CapaciteitTotaal) {
cycleObj.capacityTotal = result[i].CapaciteitTotaal;
} else {
cycleObj.capacityTotal = false;
}
// Coordinaten
if (result[i].Coordinaten) {
var coordinates = result[i].Coordinaten;
var string = coordinates.split(/,/);
cycleObj.coordinates = string;
} else {
cycleObj.coordinates = false;
}
// Gemeente
if (result[i].Gemeente) {
cycleObj.congregation = result[i].Gemeente;
} else {
cycleObj.congregation = false;
}
// ID
if (result[i].ID) {
cycleObj.id = result[i].ID;
} else {
cycleObj.id = false;
}
// Naam
if (result[i].Naam) {
cycleObj.name = result[i].Naam;
} else {
cycleObj.name = false;
}
// Openingstijden
if (result[i].Openingstijden) {
var array = [];
var obj = result[i].Openingstijden;
for (var p in obj) {
if( obj.hasOwnProperty(p) ) {
var object = obj[p];
var open = object.Open;
var closed = object.Dicht;
if(!open)
open = "Niet beschikbaar"
if(!closed)
closed = "Niet beschikbaar"
array.push({
dayName: p,
dayOpen: open,
dayClose: closed
});
}
}
cycleObj.openinghours = array;
} else {
cycleObj.openinghours = false;
}
// Plaats
if (result[i].Plaats) {
cycleObj.city = result[i].Plaats;
} else {
cycleObj.city = false;
}
// Postcode
if (result[i].Postcode) {
cycleObj.zipcode = result[i].Postcode;
} else {
cycleObj.zipcode = false;
}
// Stationsstalling
if (result[i].Stationsstalling) {
cycleObj.stationHousing = result[i].Stationsstalling;
} else {
cycleObj.stationHousing = false;
}
// Straat
if (result[i].Straat) {
cycleObj.street = result[i].Straat;
} else {
cycleObj.street = false;
}
// Toegangscontrole
if (result[i].Toegangscontrole) {
cycleObj.accesControl = result[i].Toegangscontrole;
} else {
cycleObj.accesControl = false;
}
// Type
if (result[i].Type) {
cycleObj.type = result[i].Type;
} else {
cycleObj.type = false;
}
// Url
if (result[i].Url) {
cycleObj.homepage = result[i].Url;
} else {
cycleObj.homepage = false;
}
// Verwijssysteem
if (result[i].Verwijssysteem) {
cycleObj.referral = result[i].Verwijssysteem;
} else {
cycleObj.referral = false;
}
// Voorzieningen
if (result[i].Voorzieningen) {
cycleObj.services = result[i].Voorzieningen;
} else {
cycleObj.services = false;
}
resultObj.push(cycleObj);
}
// Check if new object is not empty
if(resultObj.length > 0) {
return resultObj;
} else {
return false;
}
} | gpl-2.0 |
nikrou/tbehat | admin/languages.php | 3264 | <?php
// +-----------------------------------------------------------------------+
// | Phyxo - Another web based photo gallery |
// | Copyright(C) 2014-2016 Nicolas Roudaire http://www.phyxo.net/ |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | 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 |
// | |
// | This program is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA. |
// +-----------------------------------------------------------------------+
if (!defined("PHPWG_ROOT_PATH")) {
die ("Hacking attempt!");
}
define('LANGUAGES_BASE_URL', get_root_url().'admin/index.php?page=languages');
use Phyxo\TabSheet\TabSheet;
// +-----------------------------------------------------------------------+
// | Check Access and exit when user status is not ok |
// +-----------------------------------------------------------------------+
$services['users']->checkStatus(ACCESS_ADMINISTRATOR);
// +-----------------------------------------------------------------------+
// | Tabs |
// +-----------------------------------------------------------------------+
if (isset($_GET['section'])) {
$page['section'] = $_GET['section'];
} else {
$page['section'] = 'installed';
}
$tabsheet = new TabSheet();
$tabsheet->setId('languages');
$tabsheet->select($page['section']);
$tabsheet->assign($template);
// +-----------------------------------------------------------------------+
// | template init |
// +-----------------------------------------------------------------------+
$template->set_filenames(array('languages' => 'languages_'.$page['section'].'.tpl'));
// +-----------------------------------------------------------------------+
// | Load the tab |
// +-----------------------------------------------------------------------+
include(PHPWG_ROOT_PATH.'admin/languages_'.$page['section'].'.php');
| gpl-2.0 |
rzymek/cxxsp | external/stripped-boost/boost/archive/detail/basic_oarchive.hpp | 3668 | #ifndef BOOST_ARCHIVE_BASIC_OARCHIVE_HPP
#define BOOST_ARCHIVE_BASIC_OARCHIVE_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// basic_oarchive.hpp:
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
// can't use this - much as I'd like to as borland doesn't support it
// #include <boost/scoped_ptr.hpp>
#include <boost/archive/basic_archive.hpp>
#include <boost/serialization/tracking_enum.hpp>
#include <boost/archive/detail/abi_prefix.hpp> // must be the last header
namespace boost {
template<class T>
class shared_ptr;
namespace serialization {
class extended_type_info;
} // namespace serialization
namespace archive {
namespace detail {
class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_oarchive_impl;
class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_oserializer;
class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_pointer_oserializer;
//////////////////////////////////////////////////////////////////////
// class basic_oarchive - write serialized objects to an output stream
class BOOST_ARCHIVE_OR_WARCHIVE_DECL(BOOST_PP_EMPTY()) basic_oarchive
{
friend class basic_oarchive_impl;
// hide implementation of this class to minimize header conclusion
// in client code. note: borland can't use scoped_ptr
//boost::scoped_ptr<basic_oarchive_impl> pimpl;
basic_oarchive_impl * pimpl;
// overload these to bracket object attributes. Used to implement
// xml archives
virtual void vsave(const version_type t) = 0;
virtual void vsave(const object_id_type t) = 0;
virtual void vsave(const object_reference_type t) = 0;
virtual void vsave(const class_id_type t) = 0;
virtual void vsave(const class_id_optional_type t) = 0;
virtual void vsave(const class_id_reference_type t) = 0;
virtual void vsave(const class_name_type & t) = 0;
virtual void vsave(const tracking_type t) = 0;
protected:
basic_oarchive(unsigned int flags);
virtual ~basic_oarchive();
public:
// note: NOT part of the public interface
void register_basic_serializer(const basic_oserializer & bos);
void
lookup_basic_helper(
const boost::serialization::extended_type_info * const eti,
shared_ptr<void> & sph
);
void
insert_basic_helper(
const boost::serialization::extended_type_info * const eti,
shared_ptr<void> & sph
);
void save_object(
const void *x,
const basic_oserializer & bos
);
void save_pointer(
const void * t,
const basic_pointer_oserializer * bpos_ptr
);
void save_null_pointer(){
vsave(NULL_POINTER_TAG);
}
// real public interface starts here
void end_preamble(); // default implementation does nothing
unsigned int get_library_version() const;
unsigned int get_flags() const;
};
} // namespace detail
} // namespace archive
} // namespace boost
// required by smart_cast for compilers not implementing
// partial template specialization
BOOST_BROKEN_COMPILER_TYPE_TRAITS_SPECIALIZATION(
boost::archive::detail::basic_oarchive
)
#include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas
#endif //BOOST_ARCHIVE_BASIC_OARCHIVE_HPP
| gpl-2.0 |
savvypanda/donorcart | components/com_donorcart/controllers/postback.php | 1602 | <?php defined('_JEXEC') or die("Restricted Access");
class DonorcartControllerPostback extends FOFController {
public function __construct($config = array()) {
parent::__construct($config);
}
public function display($cachable = false, $urlparams = false) {
return false;
//return parent::display($cachable, $urlparams);
}
public function execute($task) {
//this request would not originate from the Joomla website.
//We cannot validate it with the regular token method.
//It is up to the plugins to validate the request origin.
//default to invalid. It is only valid if one of the plugins says it is valid.
//the request validation should occur in the onBeforePostback event.
$is_valid = false;
$plugin_validated = '';
$returnval = '';
$post = JRequest::get('POST');
JPluginHelper::importPlugin('donorcart');
$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger('onBeforePostback', array(&$post, &$plugin_validated));
foreach($results as $result) {
if($result === true) {
$is_valid = true;
} elseif(is_string($result)) {
$returnval .= $result;
}
}
$results = $dispatcher->trigger('onPostback', array(&$post, &$is_valid, &$plugin_validated));
foreach($results as $result) {
if($result === false) {
$is_valid = false;
} elseif(is_string($result)) {
$returnval .= $result;
}
}
$results = $dispatcher->trigger('onAfterPostback', array(&$post, $is_valid, &$plugin_validated));
foreach($results as $result) {
if(is_string($result)) {
$returnval .= $result;
}
}
return $returnval;
}
} | gpl-3.0 |
jelon94/Capstone | Login/home.php | 1016 | <?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<div class="header">
<a href="http://www.rapidmade.com"><img src="https://image.ibb.co/ejwNtv/Rapid_Made.png" alt="RapidMade" border="0"></a>
</div>
<body>
<h1>Home</h1>
<div><h4>Welcome <?php echo $_SESSION['msg']; ?></h4></div>
<div class="button_group">
<a href="index.php"><button class="button2" style="vertical-align:middle"><span>Past Orders</span></button></a>
<a href="retrieve_accout.php"><button class="button2" style="vertical-align:middle"><span>Account</span></button></a>
<a href="quickform.php"><button class="button2" style="vertical-align:middle"><span>New Order</span></button></a>
<a href="http://www.rapidmade.com"><button class="button2" style="vertical-align:middle"><span>Nothing</span></button></a>
<a href="logout.php"><button class="button2" style="vertical-align:middle"><span>Logout</span></button></a>
</div>
</body>
</html> | gpl-3.0 |
avasquez614/commons | audit/src/test/java/org/craftercms/commons/audit/TestAuditModel.java | 1465 | /*
* Copyright (C) 2007-2019 Crafter Software Corporation. 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.craftercms.commons.audit;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* Audit Model impl for Testing.
*/
public class TestAuditModel extends AuditModel {
public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
public TestAuditModel() {
this(new SimpleDateFormat(PATTERN).format(new Date()));
}
public TestAuditModel(final String date) {
try {
this.auditDate = new SimpleDateFormat(PATTERN).parse(date);
this.id = UUID.randomUUID().toString();
this.setPayload(null);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
| gpl-3.0 |
DevilRep/imagery-laravel | app/Http/Requests/FileValidatedRequest.php | 287 | <?php
namespace App\Http\Requests;
class FileValidatedRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'max:100'
];
}
} | gpl-3.0 |
hzlf/openbroadcast | website/apps/exporter/migrations/0011_auto__del_field_export_size.py | 8081 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Export.size'
db.delete_column('exporter_export', 'size')
def backwards(self, orm):
# Adding field 'Export.size'
db.add_column('exporter_export', 'size',
self.gf('django.db.models.fields.IntegerField')(default=0, null=True, blank=True),
keep_default=False)
models = {
'actstream.action': {
'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'},
'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}),
'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'exporter.export': {
'Meta': {'ordering': "('-created',)", 'object_name': 'Export'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'downloaded': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'fileformat': ('django.db.models.fields.CharField', [], {'default': "'mp3'", 'max_length': '4'}),
'filename': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'filesize': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'token': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'default': "'web'", 'max_length': "'10'"}),
'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exports'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['auth.User']"}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36', 'blank': 'True'})
},
'exporter.exportitem': {
'Meta': {'ordering': "('-created',)", 'object_name': 'ExportItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'export_session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'export_items'", 'null': 'True', 'to': "orm['exporter.Export']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['exporter'] | gpl-3.0 |
yatan/birthofnations | politico/info_partido.php | 3151 | <?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/include/funciones.php");
if (!isset($_GET['id_partido']))
die("Error: id no valido"); //Substituir por error 404
$party = sql("SELECT * FROM partidos WHERE id_partido = " . $_GET['id_partido']);
$leader = sql("SELECT nick, avatar FROM usuarios WHERE id_usuario = " . $party['id_lider']);
$user = sql("SELECT id_partido, id_nacionalidad FROM usuarios WHERE id_usuario = " . $_SESSION['id_usuario']);
$dia_actual = sql("SELECT day FROM settings");
echo "<h1>" . '<img src="' . $party['url_bandera'] . '">';
echo $party['nombre_partido'] . "</h1>";
if ($user['id_nacionalidad'] == $party['id_pais'] && $user['id_partido'] == 0) {//Condiciones para poder afiliarse
echo '<a href="/politico/afiliar.php?af=' . $party['id_partido'] . '">'.getString('affiliate').'</a>';
} elseif ($user['id_partido'] == $_GET['id_partido']) {//Condiciones para desafiliarse
echo '<a href="/politico/desafiliar.php">'.getString('unaffiliate').'</a>';
}
echo "Jefe actual: " . $leader['nick'] . '<img src="' . $leader['avatar'] . '">';
if ($dia_actual % $party['frec_elecciones'] == $party['dia_elecciones'] && $user['id_partido'] == $party['id_partido']) { //Dia de elecciones + Estoy afiliado
//Mensaje de que hay elecciones
echo "<br>".getString('vote_day')."<br>";
//Sacar id de la votacion
$time = time();
$sql = sql("SELECT id_votacion FROM votaciones WHERE tipo_votacion = 1 AND param1 = " . $party['id_partido'] . " AND fin > " . $time);
echo '<a href="/politico/lista_candidatos.php?id=' . $sql . '">'.getSTring('vote').'</a>';
} elseif (($dia_actual % $party['frec_elecciones'] == $party['dia_elecciones'] - 1 || $dia_actual % $party['frec_elecciones'] == $party['dia_elecciones'] - 2) && $user['id_partido'] == $party['id_partido']) {
//2 dias anteriores a las elecciones + Estoy afiliado
// Fecha + Postulacion
echo getString('next_elections') . next_elecciones($dia_actual, $party['dia_elecciones'], $party['frec_elecciones']);
$time = time();
$vot = sql("SELECT id_votacion FROM votaciones WHERE param1 = " . $party['id_partido'] . " AND tipo_votacion = 1 AND fin > " . $time);
$sql = sql("SELECT * from candidatos_elecciones WHERE id_candidato = " . $_SESSION['id_usuario'] . " AND id_votacion = " . $vot);
if ($sql == false) {//Si aun no esta postulado
echo "[<a href='/politico/postular.php?v=" . $vot . "'>".getString('postulate')."</a>]";
} else {//Si ya esta postulado
echo "[<a href='/politico/despostular.php?v=" . $vot . "'>".getString('unpostulate')."</a>]";
}
} else {
//Calculamos la siguiente fecha
echo getString('next_elections') . next_elecciones($dia_actual, $party['dia_elecciones'], $party['frec_elecciones']);
}
$sql = sql("SELECT COUNT(*) FROM usuarios WHERE id_partido = " . $_GET['id_partido']);
echo "<h2> ".getString('member_list')." (" . $sql . ")</h2>";
$sql = sql2("SELECT id_usuario, nick FROM usuarios WHERE id_partido = " . $_GET['id_partido']);
foreach ($sql as $miembro) {
echo '<a href="../perfil/' . $miembro['id_usuario'] . '">' . $miembro['nick'] . '</a><br>';
}
?> | gpl-3.0 |
crisis-economics/CRISIS | CRISIS/src/eu/crisis_economics/abm/algorithms/statistics/package-info.java | 877 | /*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 John Kieran Phillips
*
* CRISIS 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.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Statistics routines for discrete data.
*/
/**
* @author phillips
*/
package eu.crisis_economics.abm.algorithms.statistics; | gpl-3.0 |
concko/PortAIO | Dual-Port/xQx/xQx LeBlanc/Slide.cs | 464 | using EloBuddy;
using LeagueSharp;
using SharpDX;
using SharpDX.Direct3D9;
namespace LeblancOLD
{
internal class Slide
{
public GameObject Object { get; set; }
public float NetworkId { get; set; }
public Vector3 Position { get; set; }
public double ExpireTime { get; set; }
public Texture ExpireTimePicture { get; set; }
public string Type { get; set; }
public Texture Picture { get; set; }
}
} | gpl-3.0 |
Recolize/recommendation-engine-magento2 | Console/Command/ProductExportCommand.php | 2926 | <?php
/**
* Recolize GmbH
*
* @section LICENSE
* This source file is subject to the GNU General Public License Version 3 (GPLv3).
*
* @category Recolize
* @package Recolize\RecommendationEngine
* @author Recolize GmbH <[email protected]>
* @copyright since 2015 Recolize GmbH (http://www.recolize.com)
* @license http://opensource.org/licenses/GPL-3.0 GNU General Public License Version 3 (GPLv3).
*/
namespace Recolize\RecommendationEngine\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
class ProductExportCommand extends Command
{
/**
* @var \Recolize\RecommendationEngine\Model\Feed
*/
private $feed;
/**
* @var \Magento\Framework\App\State
*/
private $state;
/**
* @param \Magento\Framework\App\State $state
* @param \Recolize\RecommendationEngine\Model\Feed $feed
*/
public function __construct(
\Magento\Framework\App\State $state,
\Recolize\RecommendationEngine\Model\Feed $feed
) {
$this->state = $state;
$this->feed = $feed;
parent::__construct();
}
/**
* Configures of the Recolize feed generation command.
*/
protected function configure()
{
$this->setName('recolize:feed:generate')
->setDescription('Generates the Recolize product feed.')
->setDefinition(array(
new InputArgument('store-id', InputArgument::OPTIONAL, 'Store ID to generate Recolize product feed for.')
));
}
/**
* Triggers the feed generation.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return integer|null
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$storeId = $input->getArgument('store-id');
try {
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
$generatedFilenames = $this->feed->generate($storeId);
} catch (\Exception $e) {
$output->writeln("<error>{$e->getMessage()}</error>");
// we must have an exit code higher than zero to indicate something was wrong
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
}
if (empty($generatedFilenames) === true) {
$output->writeln("<comment>Recolize product feeds were NOT generated. Please check settings in Stores > Configuration > Recolize Recommendation Engine and Magento log files.</comment>");
} else {
$output->writeln("<info>Recolize product feeds were generated successfully: " . join(', ', $generatedFilenames) . "</info>");
}
return null;
}
} | gpl-3.0 |
pyrocko/pyrocko | test/base/test_fomosto_report.py | 3733 | from __future__ import division, print_function, absolute_import
import unittest
import logging
from tempfile import mkdtemp
import shutil
from pyrocko import util, trace, gf, cake # noqa
from pyrocko.fomosto import qseis
from pyrocko.fomosto.report import GreensFunctionTest as gftest
logger = logging.getLogger('pyrocko.test.test_fomosto_report')
km = 1e3
class ReportTestCase(unittest.TestCase):
tempdirs = []
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
@classmethod
def tearDownClass(cls):
for d in cls.tempdirs:
shutil.rmtree(d)
def test_pyrocko_report_with_gf_and_qseis(self):
mod = cake.LayeredModel.from_scanlines(cake.read_nd_model_str('''
0. 5.8 3.46 2.6 1264. 600.
20. 5.8 3.46 2.6 1264. 600.
20. 6.5 3.85 2.9 1283. 600.
35. 6.5 3.85 2.9 1283. 600.
mantle
35. 8.04 4.48 3.58 1449. 600.
77.5 8.045 4.49 3.5 1445. 600.
77.5 8.045 4.49 3.5 180.6 75.
120. 8.05 4.5 3.427 180. 75.
120. 8.05 4.5 3.427 182.6 76.06
165. 8.175 4.509 3.371 188.7 76.55
210. 8.301 4.518 3.324 201. 79.4
210. 8.3 4.52 3.321 336.9 133.3
410. 9.03 4.871 3.504 376.5 146.1
410. 9.36 5.08 3.929 414.1 162.7
660. 10.2 5.611 3.918 428.5 172.9
660. 10.79 5.965 4.229 1349. 549.6'''.lstrip()))
store_dir = mkdtemp(prefix='gft_')
self.tempdirs.append(store_dir)
qsconf = qseis.QSeisConfig()
qsconf.qseis_version = '2006a'
qsconf.time_region = (
gf.meta.Timing('0'),
gf.meta.Timing('end+100'))
qsconf.cut = (
gf.meta.Timing('0'),
gf.meta.Timing('end+100'))
qsconf.wavelet_duration_samples = 0.001
qsconf.sw_flat_earth_transform = 0
config = gf.meta.ConfigTypeA(
id='gft_test',
ncomponents=10,
sample_rate=0.25,
receiver_depth=0.*km,
source_depth_min=10*km,
source_depth_max=10*km,
source_depth_delta=1*km,
distance_min=550*km,
distance_max=560*km,
distance_delta=1*km,
modelling_code_id='qseis.2006a',
earthmodel_1d=mod,
tabulated_phases=[
gf.meta.TPDef(
id='begin',
definition='p,P,p\\,P\\'),
gf.meta.TPDef(
id='end',
definition='2.5'),
])
config.validate()
gf.store.Store.create_editables(
store_dir, config=config, extra={'qseis': qsconf})
store = gf.store.Store(store_dir, 'r')
store.make_ttt()
store.close()
try:
qseis.build(store_dir, nworkers=1)
except qseis.QSeisError as e:
if str(e).find('could not start qseis') != -1:
logger.warn('qseis not installed; '
'skipping test_pyrocko_gf_vs_qseis')
return
else:
raise
gft = gftest(store_dir, sensor_count=2, pdf_dir=store_dir,
plot_velocity=True, rel_lowpass_frequency=(1. / 110),
rel_highpass_frequency=(1. / 16), output_format='html')
src = gft.createSource('DC', None, 45., 90., 180.)
sen = gft.createSensors(strike=0., codes=('', 'STA', '', 'Z'),
azimuth=0., dip=-90.)
gft.trace_configs = [[src, sen]]
gft.createDisplacementTraces()
gft.createVelocityTraces()
gft.applyFrequencyFilters()
gft.getPhaseArrivals()
gft.createOutputDoc()
if __name__ == '__main__':
util.setup_logging('test_fomosto_report', 'warning')
unittest.main()
| gpl-3.0 |
michel-slm/zeal | src/registry/docset.cpp | 24214 | /****************************************************************************
**
** Copyright (C) 2015-2016 Oleg Shparber
** Copyright (C) 2013-2014 Jerzy Kozera
** Contact: https://go.zealdocs.org/l/contact
**
** This file is part of Zeal.
**
** Zeal 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.
**
** Zeal 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 Zeal. If not, see <https://www.gnu.org/licenses/>.
**
****************************************************************************/
#include "docset.h"
#include "searchquery.h"
#include "searchresult.h"
#include "util/plist.h"
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSqlError>
#include <QSqlQuery>
#include <QUrl>
#include <QVariant>
using namespace Zeal;
namespace {
const char IndexNamePrefix[] = "__zi_name"; // zi - Zeal index
const char IndexNameVersion[] = "0001"; // Current index version
namespace InfoPlist {
const char CFBundleName[] = "CFBundleName";
const char CFBundleIdentifier[] = "CFBundleIdentifier";
const char DashDocSetFamily[] = "DashDocSetFamily";
const char DashDocSetKeyword[] = "DashDocSetKeyword";
const char DashDocSetPluginKeyword[] = "DashDocSetPluginKeyword";
const char DashIndexFilePath[] = "dashIndexFilePath";
const char DocSetPlatformFamily[] = "DocSetPlatformFamily";
const char IsDashDocset[] = "isDashDocset";
const char IsJavaScriptEnabled[] = "isJavaScriptEnabled";
}
}
Docset::Docset(const QString &path) :
m_path(path)
{
QDir dir(m_path);
if (!dir.exists())
return;
loadMetadata();
// Attempt to find the icon in any supported format
for (const QString &iconFile : dir.entryList({QStringLiteral("icon.*")}, QDir::Files)) {
m_icon = QIcon(dir.absoluteFilePath(iconFile));
if (!m_icon.availableSizes().isEmpty())
break;
}
// TODO: Report errors here and below
if (!dir.cd(QStringLiteral("Contents")))
return;
// TODO: 'info.plist' is invalid according to Apple, and must alsways be 'Info.plist'
// https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPRuntimeConfig
// /Articles/ConfigFiles.html
Util::Plist plist;
if (dir.exists(QStringLiteral("Info.plist")))
plist.read(dir.absoluteFilePath(QStringLiteral("Info.plist")));
else if (dir.exists(QStringLiteral("info.plist")))
plist.read(dir.absoluteFilePath(QStringLiteral("info.plist")));
else
return;
if (plist.hasError())
return;
if (m_name.isEmpty()) {
// Fallback if meta.json is absent
if (!plist.contains(InfoPlist::CFBundleName)) {
m_name = m_title = plist[InfoPlist::CFBundleName].toString();
// TODO: Remove when MainWindow::docsetName() will not use directory name
m_name.replace(QLatin1Char(' '), QLatin1Char('_'));
} else {
m_name = QFileInfo(m_path).fileName().remove(QStringLiteral(".docset"));
}
}
if (m_title.isEmpty()) {
m_title = m_name;
m_title.replace(QLatin1Char('_'), QLatin1Char(' '));
}
// TODO: Verify if this is needed
if (plist.contains(InfoPlist::DashDocSetFamily)
&& plist[InfoPlist::DashDocSetFamily].toString() == QLatin1String("cheatsheet")) {
m_name = m_name + QLatin1String("cheats");
}
if (!dir.cd(QStringLiteral("Resources")) || !dir.exists(QStringLiteral("docSet.dsidx")))
return;
QSqlDatabase db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), m_name);
db.setDatabaseName(dir.absoluteFilePath(QStringLiteral("docSet.dsidx")));
if (!db.open()) {
qWarning("SQL Error: %s", qPrintable(db.lastError().text()));
return;
}
m_type = db.tables().contains(QStringLiteral("searchIndex")) ? Type::Dash : Type::ZDash;
createIndex();
if (!dir.cd(QStringLiteral("Documents")))
return;
// Setup keywords
if (plist.contains(InfoPlist::DocSetPlatformFamily))
m_keywords << plist[InfoPlist::DocSetPlatformFamily].toString();
if (plist.contains(InfoPlist::DashDocSetPluginKeyword))
m_keywords << plist[InfoPlist::DashDocSetPluginKeyword].toString();
if (plist.contains(InfoPlist::DashDocSetKeyword))
m_keywords << plist[InfoPlist::DashDocSetKeyword].toString();
if (plist.contains(InfoPlist::DashDocSetFamily)) {
const QString kw = plist[InfoPlist::DashDocSetFamily].toString();
if (kw != QStringLiteral("dashtoc"))
m_keywords << kw;
}
// TODO: Use 'unknown' instead of CFBundleName? (See #383)
m_keywords << plist.value(InfoPlist::CFBundleName, m_name).toString().toLower();
m_keywords.removeDuplicates();
// Try to find index path if metadata is missing one
if (m_indexFilePath.isEmpty()) {
if (plist.contains(InfoPlist::DashIndexFilePath))
m_indexFilePath = plist[InfoPlist::DashIndexFilePath].toString();
else if (dir.exists(QStringLiteral("index.html")))
m_indexFilePath = QStringLiteral("index.html");
else
qWarning("Cannot determine index file for docset %s", qPrintable(m_name));
}
countSymbols();
}
Docset::~Docset()
{
QSqlDatabase::removeDatabase(m_name);
}
bool Docset::isValid() const
{
return m_type != Type::Invalid;
}
QString Docset::name() const
{
return m_name;
}
QString Docset::title() const
{
return m_title;
}
QStringList Docset::keywords() const
{
return m_keywords;
}
QString Docset::version() const
{
return m_version;
}
QString Docset::revision() const
{
return m_revision;
}
QString Docset::path() const
{
return m_path;
}
QString Docset::documentPath() const
{
return QDir(m_path).absoluteFilePath(QStringLiteral("Contents/Resources/Documents"));
}
QIcon Docset::icon() const
{
return m_icon;
}
QIcon Docset::symbolTypeIcon(const QString &symbolType) const
{
static const QIcon unknownIcon(QStringLiteral("typeIcon:Unknown.png"));
const QIcon icon(QStringLiteral("typeIcon:%1.png").arg(symbolType));
return icon.availableSizes().isEmpty() ? unknownIcon : icon;
}
QString Docset::indexFilePath() const
{
return QDir(documentPath()).absoluteFilePath(m_indexFilePath);
}
QMap<QString, int> Docset::symbolCounts() const
{
return m_symbolCounts;
}
int Docset::symbolCount(const QString &symbolType) const
{
return m_symbolCounts.value(symbolType);
}
const QMap<QString, QString> &Docset::symbols(const QString &symbolType) const
{
if (!m_symbols.contains(symbolType))
loadSymbols(symbolType);
return m_symbols[symbolType];
}
QList<SearchResult> Docset::search(const QString &query) const
{
QList<SearchResult> results;
const SearchQuery searchQuery = SearchQuery::fromString(query);
const QString sanitizedQuery = searchQuery.sanitizedQuery();
if (searchQuery.hasKeywords() && !searchQuery.hasKeywords(m_keywords))
return results;
QString queryStr;
bool withSubStrings = false;
// %.%1% for long Django docset values like django.utils.http
// %::%1% for long C++ docset values like std::set
// %/%1% for long Go docset values like archive/tar
QString subNames = QStringLiteral(" OR %1 LIKE '%.%2%' ESCAPE '\\'");
subNames += QLatin1String(" OR %1 LIKE '%::%2%' ESCAPE '\\'");
subNames += QLatin1String(" OR %1 LIKE '%/%2%' ESCAPE '\\'");
while (results.size() < 100) {
QString curQuery = sanitizedQuery;
QString notQuery; // don't return the same result twice
if (withSubStrings) {
// if less than 100 found starting with query, search all substrings
curQuery = QLatin1Char('%') + sanitizedQuery;
// don't return 'starting with' results twice
if (m_type == Docset::Type::Dash)
notQuery = QString(" AND NOT (name LIKE '%1%' ESCAPE '\\' %2) ").arg(sanitizedQuery, subNames.arg("name", sanitizedQuery));
else
notQuery = QString(" AND NOT (ztokenname LIKE '%1%' ESCAPE '\\' %2) ").arg(sanitizedQuery, subNames.arg("ztokenname", sanitizedQuery));
}
if (m_type == Docset::Type::Dash) {
queryStr = QString("SELECT name, type, path "
" FROM searchIndex "
"WHERE (name LIKE '%1%' ESCAPE '\\' %3) %2 "
"ORDER BY name COLLATE NOCASE LIMIT 100")
.arg(curQuery, notQuery, subNames.arg("name", curQuery));
} else {
queryStr = QString("SELECT ztokenname, ztypename, zpath, zanchor "
" FROM ztoken "
"JOIN ztokenmetainformation "
" ON ztoken.zmetainformation = ztokenmetainformation.z_pk "
"JOIN zfilepath "
" ON ztokenmetainformation.zfile = zfilepath.z_pk "
"JOIN ztokentype "
" ON ztoken.ztokentype = ztokentype.z_pk "
"WHERE (ztokenname LIKE '%1%' ESCAPE '\\' %3) %2 "
"ORDER BY ztokenname COLLATE NOCASE LIMIT 100")
.arg(curQuery, notQuery, subNames.arg("ztokenname", curQuery));
}
QSqlQuery query(queryStr, database());
while (query.next()) {
const QString itemName = query.value(0).toString();
QString path = query.value(2).toString();
if (m_type == Docset::Type::ZDash) {
const QString anchor = query.value(3).toString();
if (!anchor.isEmpty())
path += QLatin1Char('#') + anchor;
}
// TODO: Third should be type
results.append(SearchResult{itemName, QString(),
parseSymbolType(query.value(1).toString()),
const_cast<Docset *>(this), path, sanitizedQuery});
}
if (withSubStrings)
break;
withSubStrings = true; // try again searching for substrings
}
return results;
}
QList<SearchResult> Docset::relatedLinks(const QUrl &url) const
{
QList<SearchResult> results;
// Strip docset path and anchor from url
const QString dir = documentPath();
QString urlPath = url.path();
int dirPosition = urlPath.indexOf(dir);
QString path = url.path().mid(dirPosition + dir.size() + 1);
// Get the url without the #anchor.
QUrl cleanUrl(path);
cleanUrl.setFragment(QString());
// Prepare the query to look up all pages with the same url.
QString queryStr;
if (m_type == Docset::Type::Dash) {
queryStr = QStringLiteral("SELECT name, type, path FROM searchIndex "
"WHERE path LIKE \"%1%%\" AND path <> \"%1\"");
} else if (m_type == Docset::Type::ZDash) {
queryStr = QStringLiteral("SELECT ztoken.ztokenname, ztokentype.ztypename, zfilepath.zpath, ztokenmetainformation.zanchor "
"FROM ztoken "
"JOIN ztokenmetainformation ON ztoken.zmetainformation = ztokenmetainformation.z_pk "
"JOIN zfilepath ON ztokenmetainformation.zfile = zfilepath.z_pk "
"JOIN ztokentype ON ztoken.ztokentype = ztokentype.z_pk "
"WHERE zfilepath.zpath = \"%1\" AND ztokenmetainformation.zanchor IS NOT NULL");
}
QSqlQuery query(queryStr.arg(cleanUrl.toString()), database());
while (query.next()) {
const QString sectionName = query.value(0).toString();
QString sectionPath = query.value(2).toString();
if (m_type == Docset::Type::ZDash) {
sectionPath += QLatin1Char('#');
sectionPath += query.value(3).toString();
}
results.append(SearchResult{sectionName, QString(),
parseSymbolType(query.value(1).toString()),
const_cast<Docset *>(this), sectionPath, QString()});
}
if (results.size() == 1)
results.clear();
return results;
}
QSqlDatabase Docset::database() const
{
return QSqlDatabase::database(m_name, true);
}
void Docset::loadMetadata()
{
const QDir dir(m_path);
// Fallback if meta.json is absent
if (!dir.exists(QStringLiteral("meta.json")))
return;
QScopedPointer<QFile> file(new QFile(dir.filePath(QStringLiteral("meta.json"))));
if (!file->open(QIODevice::ReadOnly))
return;
QJsonParseError jsonError;
const QJsonObject jsonObject = QJsonDocument::fromJson(file->readAll(), &jsonError).object();
if (jsonError.error != QJsonParseError::NoError)
return;
m_name = jsonObject[QStringLiteral("name")].toString();
m_title = jsonObject[QStringLiteral("title")].toString();
m_version = jsonObject[QStringLiteral("version")].toString();
m_revision = jsonObject[QStringLiteral("revision")].toString();
if (jsonObject.contains(QStringLiteral("extra"))) {
const QJsonObject extra = jsonObject[QStringLiteral("extra")].toObject();
m_indexFilePath = extra[QStringLiteral("indexFilePath")].toString();
}
}
void Docset::countSymbols()
{
QString queryStr;
if (m_type == Docset::Type::Dash) {
queryStr = QStringLiteral("SELECT type, COUNT(*) FROM searchIndex GROUP BY type");
} else if (m_type == Docset::Type::ZDash) {
queryStr = QStringLiteral("SELECT ztypename, COUNT(*) FROM ztoken JOIN ztokentype"
" ON ztoken.ztokentype = ztokentype.z_pk GROUP BY ztypename");
}
QSqlQuery query(queryStr, database());
if (query.lastError().type() != QSqlError::NoError) {
qWarning("SQL Error: %s", qPrintable(query.lastError().text()));
return;
}
while (query.next()) {
const QString symbolTypeStr = query.value(0).toString();
const QString symbolType = parseSymbolType(symbolTypeStr);
m_symbolStrings.insertMulti(symbolType, symbolTypeStr);
m_symbolCounts[symbolType] += query.value(1).toInt();
}
}
// TODO: Fetch and cache only portions of symbols
void Docset::loadSymbols(const QString &symbolType) const
{
for (const QString &symbol : m_symbolStrings.values(symbolType))
loadSymbols(symbolType, symbol);
}
void Docset::loadSymbols(const QString &symbolType, const QString &symbolString) const
{
QSqlDatabase db = database();
if (!db.isOpen())
return;
QString queryStr;
if (m_type == Docset::Type::Dash) {
queryStr = QStringLiteral("SELECT name, path FROM searchIndex WHERE type='%1' ORDER BY name ASC");
} else {
queryStr = QStringLiteral("SELECT ztokenname AS name, "
"CASE WHEN (zanchor IS NULL) THEN zpath "
"ELSE (zpath || '#' || zanchor) "
"END AS path FROM ztoken "
"JOIN ztokenmetainformation ON ztoken.zmetainformation = ztokenmetainformation.z_pk "
"JOIN zfilepath ON ztokenmetainformation.zfile = zfilepath.z_pk "
"JOIN ztokentype ON ztoken.ztokentype = ztokentype.z_pk WHERE ztypename='%1' "
"ORDER BY ztokenname ASC");
}
QSqlQuery query(queryStr.arg(symbolString), database());
if (query.lastError().type() != QSqlError::NoError) {
qWarning("SQL Error: %s", qPrintable(query.lastError().text()));
return;
}
QMap<QString, QString> &symbols = m_symbols[symbolType];
while (query.next())
symbols.insertMulti(query.value(0).toString(), QDir(documentPath()).absoluteFilePath(query.value(1).toString()));
}
void Docset::createIndex()
{
static const QString indexListQuery = QStringLiteral("PRAGMA INDEX_LIST('%1')");
static const QString indexDropQuery = QStringLiteral("DROP INDEX '%1'");
static const QString indexCreateQuery = QStringLiteral("CREATE INDEX IF NOT EXISTS %1%2"
" ON %3 (%4 COLLATE NOCASE)");
QSqlQuery query(database());
const QString tableName = m_type == Type::Dash ? QStringLiteral("searchIndex")
: QStringLiteral("ztoken");
const QString columnName = m_type == Type::Dash ? QStringLiteral("name")
: QStringLiteral("ztokenname");
query.exec(indexListQuery.arg(tableName));
QStringList oldIndexes;
while (query.next()) {
const QString indexName = query.value(1).toString();
if (!indexName.startsWith(IndexNamePrefix))
continue;
if (indexName.endsWith(IndexNameVersion))
return;
oldIndexes << indexName;
}
// Drop old indexes
for (const QString oldIndexName : oldIndexes)
query.exec(indexDropQuery.arg(oldIndexName));
query.exec(indexCreateQuery.arg(IndexNamePrefix, IndexNameVersion, tableName, columnName));
}
QString Docset::parseSymbolType(const QString &str)
{
// Dash symbol aliases
const static QHash<QString, QString> aliases = {
// Attribute
{QStringLiteral("Package Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Private Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Protected Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Public Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Package Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Private Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Protected Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Public Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("XML Attributes"), QStringLiteral("Attribute")},
// Binding
{QStringLiteral("binding"), QStringLiteral("Binding")},
// Category
{QStringLiteral("cat"), QStringLiteral("Category")},
{QStringLiteral("Groups"), QStringLiteral("Category")},
{QStringLiteral("Pages"), QStringLiteral("Category")},
// Class
{QStringLiteral("cl"), QStringLiteral("Class")},
{QStringLiteral("specialization"), QStringLiteral("Class")},
{QStringLiteral("tmplt"), QStringLiteral("Class")},
// Constant
{QStringLiteral("data"), QStringLiteral("Constant")},
{QStringLiteral("econst"), QStringLiteral("Constant")},
{QStringLiteral("enumelt"), QStringLiteral("Constant")},
{QStringLiteral("clconst"), QStringLiteral("Constant")},
{QStringLiteral("structdata"), QStringLiteral("Constant")},
{QStringLiteral("Notifications"), QStringLiteral("Constant")},
// Constructor
{QStringLiteral("Public Constructors"), QStringLiteral("Constructor")},
// Enumeration
{QStringLiteral("enum"), QStringLiteral("Enumeration")},
{QStringLiteral("Enum"), QStringLiteral("Enumeration")},
{QStringLiteral("Enumerations"), QStringLiteral("Enumeration")},
// Event
{QStringLiteral("event"), QStringLiteral("Event")},
{QStringLiteral("Public Events"), QStringLiteral("Event")},
{QStringLiteral("Inherited Events"), QStringLiteral("Event")},
{QStringLiteral("Private Events"), QStringLiteral("Event")},
// Field
{QStringLiteral("Data Fields"), QStringLiteral("Field")},
// Function
{QStringLiteral("dcop"), QStringLiteral("Function")},
{QStringLiteral("func"), QStringLiteral("Function")},
{QStringLiteral("ffunc"), QStringLiteral("Function")},
{QStringLiteral("signal"), QStringLiteral("Function")},
{QStringLiteral("slot"), QStringLiteral("Function")},
{QStringLiteral("grammar"), QStringLiteral("Function")},
{QStringLiteral("Function Prototypes"), QStringLiteral("Function")},
{QStringLiteral("Functions/Subroutines"), QStringLiteral("Function")},
{QStringLiteral("Members"), QStringLiteral("Function")},
{QStringLiteral("Package Functions"), QStringLiteral("Function")},
{QStringLiteral("Private Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Private Slots"), QStringLiteral("Function")},
{QStringLiteral("Protected Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Protected Slots"), QStringLiteral("Function")},
{QStringLiteral("Public Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Public Slots"), QStringLiteral("Function")},
{QStringLiteral("Signals"), QStringLiteral("Function")},
{QStringLiteral("Static Package Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Private Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Protected Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Public Member Functions"), QStringLiteral("Function")},
// Guide
{QStringLiteral("doc"), QStringLiteral("Guide")},
// Namespace
{QStringLiteral("ns"), QStringLiteral("Namespace")},
// Macro
{QStringLiteral("macro"), QStringLiteral("Macro")},
// Method
{QStringLiteral("clm"), QStringLiteral("Method")},
{QStringLiteral("intfctr"), QStringLiteral("Method")},
{QStringLiteral("intfcm"), QStringLiteral("Method")},
{QStringLiteral("intfm"), QStringLiteral("Method")},
{QStringLiteral("instctr"), QStringLiteral("Method")},
{QStringLiteral("instm"), QStringLiteral("Method")},
{QStringLiteral("Class Methods"), QStringLiteral("Method")},
{QStringLiteral("Inherited Methods"), QStringLiteral("Method")},
{QStringLiteral("Instance Methods"), QStringLiteral("Method")},
{QStringLiteral("Private Methods"), QStringLiteral("Method")},
{QStringLiteral("Protected Methods"), QStringLiteral("Method")},
{QStringLiteral("Public Methods"), QStringLiteral("Method")},
// Property
{QStringLiteral("intfp"), QStringLiteral("Property")},
{QStringLiteral("instp"), QStringLiteral("Property")},
{QStringLiteral("Inherited Properties"), QStringLiteral("Property")},
{QStringLiteral("Private Properties"), QStringLiteral("Property")},
{QStringLiteral("Protected Properties"), QStringLiteral("Property")},
{QStringLiteral("Public Properties"), QStringLiteral("Property")},
// Protocol
{QStringLiteral("intf"), QStringLiteral("Protocol")},
// Structure
{QStringLiteral("struct"), QStringLiteral("Structure")},
{QStringLiteral("Data Structures"), QStringLiteral("Structure")},
{QStringLiteral("Struct"), QStringLiteral("Structure")},
// Type
{QStringLiteral("tag"), QStringLiteral("Type")},
{QStringLiteral("tdef"), QStringLiteral("Type")},
{QStringLiteral("Data Types"), QStringLiteral("Type")},
{QStringLiteral("Package Types"), QStringLiteral("Type")},
{QStringLiteral("Private Types"), QStringLiteral("Type")},
{QStringLiteral("Protected Types"), QStringLiteral("Type")},
{QStringLiteral("Public Types"), QStringLiteral("Type")},
{QStringLiteral("Typedefs"), QStringLiteral("Type")},
// Variable
{QStringLiteral("var"), QStringLiteral("Variable")}
};
return aliases.value(str, str);
}
| gpl-3.0 |
partyzanEX/html-helper | source/element/Td.php | 162 | <?php
namespace HtmlHelper\Source\Element;
use HtmlHelper\Source\Base\TableElement;
class Td extends TableElement {
public function output()
{
}
} | gpl-3.0 |
teampheenix/StarCraft-Casting-Tool | scctool/matchgrabber/rstl.py | 11217 | """Provide match grabber for RSTL (deprecated)."""
import logging
import scctool.settings
import scctool.settings.translation
from scctool.matchgrabber.custom import MatchGrabber as MatchGrabberParent
# create logger
module_logger = logging.getLogger(__name__)
_ = scctool.settings.translation.gettext
class MatchGrabber(MatchGrabberParent):
"""Grabs match data from Russian StarCraft 2 Teamleague."""
_provider = "RSTL"
def __init__(self, *args):
"""Init match grabber."""
super().__init__(*args)
self._urlprefix = \
"http://hdgame.net/en/tournaments/matches/match/"
self._apiprefix = \
"http://hdgame.net/index.php?ajax=1&do=tournament&act=api"\
+ "&data_type=json&lang=en&service=match&match_id="
def grabData(self, metaChange=False, logoManager=None):
"""Grab match data."""
data = self._getJson()
if(data['code'] != "200"):
msg = 'API-Error: ' + data['code']
raise ValueError(msg)
data = data['data']
self._rawData = data
overwrite = (metaChange
or self._matchData.getURL().strip()
!= self.getURL().strip())
with self._matchData.emitLock(overwrite,
self._matchData.metaChanged):
if overwrite:
self._matchData.resetSwap()
if(data['game_format'] == "3"):
self._matchData.setNoSets(5, 3, resetPlayers=overwrite)
self._matchData.setMinSets(4)
self._matchData.resetLabels()
self._matchData.setSolo(False)
self._matchData.setLeague(
self._aliasLeagueself._aliasLeague(
(data['tournament']['name'])))
for set_idx in range(7):
self._matchData.setMap(
set_idx, data['start_maps'][str(set_idx)]['name'])
for team_idx in range(2):
for set_idx in range(4):
try:
lu = 'lu' + str(team_idx + 1)
self._matchData.setPlayer(
self._matchData.getSwappedIdx(
team_idx), set_idx,
self._aliasPlayer(
data[lu][str(set_idx)]['member_name']),
data[lu][str(set_idx)]['r_name'])
except Exception:
pass
for set_idx in range(4, 7):
try:
player = data['result']['8']['member_name'
+ str(team_idx + 1)]
race = data['result']['8']['r_name'
+ str(team_idx + 1)]
except Exception:
pass
try:
idx = str(4 + set_idx)
try:
idx = str(5 + set_idx)
temp_race = \
data['result'][idx]['r_name'
+ str(team_idx + 1)]
if temp_race is not None:
race = temp_race
finally:
if race is None:
race = "Random"
try:
temp_player = data['result'][str(
5 + set_idx)][f'member_name{team_idx + 1}']
if temp_player is not None:
player = temp_player
finally:
if temp_player is None:
player = "TBD"
player = self._aliasPlayer(player)
self._matchData.setPlayer(
self._matchData.getSwappedIdx(team_idx),
set_idx, player, race)
except Exception:
pass
team = data['member' + str(team_idx + 1)]
self._matchData.setTeam(
self._matchData.getSwappedIdx(team_idx),
self._aliasTeam(team['name']), team['tag'])
for idx in range(4, 7):
self._matchData.setLabel(idx, "Ace Map {}".format(idx - 3))
self._matchData.setAce(idx, True)
for set_idx in range(4):
try:
score1 = int(
data['result'][str(set_idx * 2)]['score1'])
score2 = int(
data['result'][str(set_idx * 2)]['score2'])
except Exception:
score1 = 0
score2 = 0
if(score1 > score2):
score = -1
elif(score1 < score2):
score = 1
else:
score = 0
self._matchData.setMapScore(
set_idx, score, overwrite, True)
for set_idx in range(4, 7):
try:
score1 = int(
data['result'][str(5 + set_idx)]['score1'])
score2 = int(
data['result'][str(5 + set_idx)]['score2'])
except Exception:
score1 = 0
score2 = 0
if(score1 > score2):
score = -1
elif(score1 < score2):
score = 1
else:
score = 0
self._matchData.setMapScore(
set_idx, score, overwrite, True)
self._matchData.setAllKill(False)
elif(data['game_format'] == "2"): # All-Kill BoX
# self._matchData.resetData()
bo = int(data['game_format_bo'])
self._matchData.setNoSets(bo, bo, resetPlayers=overwrite)
self._matchData.setMinSets(0)
self._matchData.setSolo(False)
self._matchData.setLeague(data['tournament']['name'])
try:
mapname = data['start_maps']["1"]['name']
except KeyError:
mapname = data['start_map']['name']
self._matchData.setMap(0, mapname)
for team_idx in range(2):
for set_idx in range(1):
try:
lu = 'lu' + str(team_idx + 1)
self._matchData.setPlayer(
self._matchData.getSwappedIdx(
team_idx), set_idx,
data[lu][str(set_idx)]['member_name'],
data[lu][str(set_idx)]['r_name'])
except Exception:
pass
for set_idx in range(1, bo):
try:
idx = str(set_idx * 2)
if(not data['result'][idx]['r_name'
+ str(team_idx + 1)]):
try:
idx = str(set_idx * 2 + 1)
race = \
data['result'][idx][
f'r_name{team_idx + 1}']
except Exception:
race = "Random"
else:
race = data['result'][str(
set_idx * 2)][f'r_name{team_idx + 1}']
player = \
data['result'][str(
set_idx * 2)][f'member_name{team_idx + 1}']
player = self._aliasPlayer(player)
self._matchData.setPlayer(
self._matchData.getSwappedIdx(team_idx),
set_idx, player, race)
except Exception:
pass
team = data['member' + str(team_idx + 1)]
self._matchData.setTeam(
self._matchData.getSwappedIdx(team_idx),
self._aliasTeam(team['name']), team['tag'])
for set_idx in range(bo):
try:
score1 = int(
data['result'][str(set_idx * 2)]['score1'])
score2 = int(
data['result'][str(set_idx * 2)]['score2'])
except Exception:
score1 = 0
score2 = 0
if(score1 > score2):
score = -1
elif(score1 < score2):
score = 1
else:
score = 0
self._matchData.setMapScore(
set_idx, score, overwrite, True)
self._matchData.resetLabels()
self._matchData.setAllKill(True)
else:
module_logger.info("RSTL Format Unknown")
if logoManager is not None:
self.downloadLogos(logoManager)
self._matchData.autoSetMyTeam(
swap=scctool.settings.config.parser.getboolean(
"SCT", "swap_myteam"))
def downloadLogos(self, logoManager):
"""Download team logos."""
if self._rawData is None:
raise ValueError(
"Error: No raw data.")
if self._rawData is None:
raise ValueError(
"Error: No raw data.")
for idx in range(1, 3):
try:
if self._matchData.isSwapped():
logo_idx = 3 - idx
else:
logo_idx = idx
oldLogo = logoManager.getTeam(logo_idx)
logo = logoManager.newLogo()
new_logo = logo.fromURL(
"http://hdgame.net"
+ self._rawData['member' + str(idx)]['img_m'],
localFile=oldLogo.getAbsFile())
if new_logo:
logoManager.setTeamLogo(logo_idx, logo)
else:
module_logger.info("Logo download is not needed.")
except Exception:
module_logger.exception('message')
| gpl-3.0 |
BN701/Multi-Arp | maListBuilder.cpp | 11468 | //
// MultiArp - Another step in the Great Midi Adventure!
// Copyright (C) 2017, 2018 Barry Neilsen
//
// 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/>.
//
//////////////////////////////////////////////////////////////////////////////
#include "maListBuilder.h"
#include <alsa/asoundlib.h>
using namespace std;
// From curses.h
#define KEY_BACKSPACE 0407 /* backspace key */
#define LOG_ON 0
#if LOG_ON
ofstream fLog;
#endif
ListBuilder::ListBuilder(ableton::Link * linkInstance):
m_Link(linkInstance)
{
//ctor
#if LOG_ON
fLog.open("ListBuilder.log");
#endif
}
ListBuilder::~ListBuilder()
{
//dtor
#if LOG_ON
fLog.close();
#endif
}
void ListBuilder::SetMidiInputMode( int val )
{
if ( m_MidiInputMode != val )
{
m_MidiInputMode = val;
m_MidiInputModeChanged = true;
if ( m_MidiInputMode == MIDI_INPUT_OFF )
{
m_StepList.Clear();
m_Captured.Clear();
}
}
}
int ListBuilder::MidiInputMode()
{
return m_MidiInputMode;
}
bool ListBuilder::MidiInputModeChanged()
{
// Call once and clear flag.
if ( m_MidiInputModeChanged )
{
m_MidiInputModeChanged = false;
return true;
}
else
return false;
}
char ListBuilder::MidiInputModeAsChar()
{
switch ( m_MidiInputMode )
{
case MIDI_INPUT_REAL_TIME:
return 'R';
case MIDI_INPUT_STEP:
return 'S';
case MIDI_INPUT_QUICK:
return 'Q';
default:
return 'X';
}
}
std::string ListBuilder::ToString()
{
switch ( m_MidiInputMode )
{
case MIDI_INPUT_REAL_TIME:
{
char buff[100];
sprintf(buff, " Open: %lu, captured: %lu", m_OpenNotes.size(), m_RealTimeList.size());
return buff;
}
break;
case MIDI_INPUT_STEP:
if ( m_StepList.Empty() )
return m_Captured.ToString();
else if ( m_Captured.Empty() )
return m_StepList.ToString(false);
else
return m_StepList.ToString(false) + "," + m_Captured.ToString();
case MIDI_INPUT_QUICK:
return m_StepList.ToString(false);
default:
return m_Activity.ToString(false);
}
}
bool ListBuilder::HandleKeybInput(int c)
{
switch (c)
{
case 10:
switch ( m_MidiInputMode )
{
case MIDI_INPUT_REAL_TIME:
return !m_RealTimeList.empty();
case MIDI_INPUT_STEP:
return !m_StepList.Empty();
default:
return false;
}
case 32:
m_StepList.Add();
return true;
case KEY_BACKSPACE:
switch ( m_MidiInputMode )
{
case MIDI_INPUT_REAL_TIME:
if ( !m_RealTimeUndoIndex.empty() )
{
m_RealTimeList.erase(m_RealTimeUndoIndex.back());
m_RealTimeUndoIndex.pop_back();
return true;
}
else
return false;
case MIDI_INPUT_STEP:
return m_StepList.DeleteLast();
default:
return false;
}
default:
return false;
}
}
void ListBuilder::SetPhaseIsZero(double beat, double quantum)
{
m_BeatAtLastPhaseZero = beat;
m_LinkQuantum = quantum;
}
bool ListBuilder::HandleMidi(snd_seq_event_t *ev, double inBeat)
{
switch ( m_MidiInputMode )
{
case MIDI_INPUT_REAL_TIME:
{
if ( m_Link == NULL )
throw string("ListBuilder::HandleMidi() - Expecting Ableton Link Instance to be set.");
chrono::microseconds t_now = m_Link->clock().micros();
ableton::Link::Timeline timeline = m_Link->captureAppTimeline();
double beat = timeline.beatAtTime(t_now, m_LinkQuantum);
// Create notes for note-on, complete notes and calculate
// duration for note off.
#if LOG_ON
char buff[100];
sprintf(buff, "Beat %6.2f", beat);
fLog << buff;
#endif
if ( ev->type == SND_SEQ_EVENT_NOTEON )
{
Note note(ev->data.note.note, ev->data.note.velocity);
note.SetPhase(beat); // Temporarily store beat in the notes Phase member.
map<unsigned char,Note>::iterator it = m_OpenNotes.find(ev->data.note.note);
if ( it != m_OpenNotes.end() )
m_OpenNotes.at(ev->data.note.note) = note;
else
m_OpenNotes.insert(make_pair(ev->data.note.note, note));
#if LOG_ON
sprintf(buff, " opening %3i\n", ev->data.note.note);
fLog << buff;
#endif
}
else
{
map<unsigned char,Note>::iterator it = m_OpenNotes.find(ev->data.note.note);
if ( it != m_OpenNotes.end() )
{
Note note = m_OpenNotes.at(ev->data.note.note);
m_OpenNotes.erase(it);
double beatStart = note.Phase();
note.SetLength(beat - beatStart);
// Normalize beat Start
while ( beatStart < m_BeatAtLastPhaseZero )
beatStart += m_LinkQuantum;
note.SetPhase(beatStart - m_BeatAtLastPhaseZero);
// Syntax here is getting ridiculous! Here's what's going on:
//
// m_RealTimeList is a map of Note objects, keyed on their beat value.
// You have to make a std::pair to add items to the map.
// The insert() operation returns another pair, the first element of
// which is an iterator pointing to the new item in the map.
// We put the iterator on the undo stack, m_RealTimeUndoIndex.
//
// (TODO: We might need to handle clashes, as I guess it's not
// impossible for two events to have the same beat value.)
m_RealTimeUndoIndex.push_back(m_RealTimeList.insert(make_pair(note.Phase(), note)).first);
#if LOG_ON
sprintf(buff, " closing %3i, phase %6.2f length %6.2f\n",
ev->data.note.note,
note.Phase(),
note.Length());
fLog << buff;
#endif
}
}
}
return false;
case MIDI_INPUT_FILE:
{
// Similar to real time capture, except we don't get time from link
// and we don't try to normalize the beat as that's provided as input.
if ( ev->type == SND_SEQ_EVENT_NOTEON )
{
Note note(ev->data.note.note, ev->data.note.velocity);
note.SetPhase(inBeat); // Temporarily store beat in the notes Phase member.
map<unsigned char,Note>::iterator it = m_OpenNotes.find(ev->data.note.note);
if ( it != m_OpenNotes.end() )
m_OpenNotes.at(ev->data.note.note) = note;
else
m_OpenNotes.insert(make_pair(ev->data.note.note, note));
}
else
{
map<unsigned char,Note>::iterator openPair = m_OpenNotes.find(ev->data.note.note);
if ( openPair != m_OpenNotes.end() )
{
double beatStart = openPair->second.Phase();
openPair->second.SetLength(inBeat - beatStart);
m_RealTimeList.insert(make_pair(openPair->second.Phase(), openPair->second));
m_OpenNotes.erase(openPair);
// Note note = m_OpenNotes.at(ev->data.note.note);
// m_OpenNotes.erase(it);
//
// double beatStart = note.Phase();
// note.SetLength(inBeat - beatStart);
//
// m_RealTimeList.insert(make_pair(note.Phase(), note));
}
}
}
return false;
case MIDI_INPUT_STEP:
// Build the current chord and addto the note list when all keys
// are released. Keep adding chords - which can be single notes,
// of course - until something else, probably a keypress, uses and
// clears the notelist.
if ( ev->type == SND_SEQ_EVENT_NOTEON )
{
m_Captured.Add(ev->data.note.note, ev->data.note.velocity);
m_openNotes += 1;
}
else if ( m_openNotes > 0 )
{
m_openNotes -= 1;
}
if ( m_openNotes == 0 )
{
m_StepList.Add(m_Captured);
m_Captured.Clear();
}
return false;
case MIDI_INPUT_QUICK:
if ( ev->type == SND_SEQ_EVENT_NOTEON )
{
m_StepList.Add(ev->data.note.note, ev->data.note.velocity);
m_openNotes += 1;
}
else if ( m_openNotes > 0 )
{
m_openNotes -= 1;
}
return m_openNotes == 0; // Tell calling function we have a complete notelist.
default:
m_Activity.m_NoteNumber = ev->data.note.note;
return false;
}
}
Cluster * ListBuilder::Step(double phase, double stepValue)
{
m_Captured.Clear();
double windowStart = phase - 2 / stepValue;
double windowEnd = phase + 2 / stepValue;
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
it != m_RealTimeList.upper_bound(windowEnd); it++ )
m_Captured.Add(it->second);
// When phase is zero, window start will be negative, so we also need to
// look for notes at the top of the loop that would normally be quantized
// up to next beat zero.
if ( windowStart < 0 )
{
windowStart += m_LinkQuantum;
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
it != m_RealTimeList.upper_bound(m_LinkQuantum); it++ )
m_Captured.Add(it->second);
}
return & m_Captured;
}
| gpl-3.0 |
PhoenixRiver/naev | dat/missions/neutral/pirbounty_alive.lua | 6438 | --[[
Alive Pirate Bounty
Copyright 2014, 2015 Julian Marchant
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/>.
--
Bounty mission where you must capture the target alive.
Can work with any faction.
--]]
include "numstring.lua"
include "dat/missions/neutral/pirbounty_dead.lua"
-- Localization
lang = naev.lang()
if lang == "es" then
else -- Default to English
pronoun = rnd.rnd() < 0.5 and "He" or "She"
kill_instead_title = "Better Dead than Free"
kill_instead_text = {}
kill_instead_text[1] = [[As you return to your ship, you are contacted by an officer. "I see you were unable to capture %s," the officer says. "Disappointing. However, we would rather this pirate be dead than roaming free, so you will be paid %s credits if you finish him off right now."]]
kill_instead_text[2] = [[On your way back to your ship, you receive a message from an officer. It reads, "Your failure to capture %s is disappointing. We really wanted to capture this pirate alive. However, we would rather he be dead than roaming free, so if you kill him now, you will be paid the lesser sum of %s credits."]]
kill_instead_text[3] = [[When you return to your cockpit, you are contacted by an officer. "Pathetic! If I were in charge, I'd say you get no bounty! Can't fight off a couple low-life pirates?!" He sighs. "But lucky for you, I'm not in charge, and my higher-ups would rather %s be dead than free. So if you finish him off, you'll get %s credits. Just be snappy about it!" And with that, the officer ceases communication.]]
kill_instead_text[4] = [[When you get back to the ship, you see a message giving you a new mission to kill %s; the reward is %s credits. Well, that's pitiful compared to what you were planning on collecting, but it's better than nothing.]]
pay_capture_text = {}
pay_capture_text[1] = "An officer takes %s into custody and hands you your pay."
pay_capture_text[2] = "The officer seems to think your acceptance of the alive bounty for %s was insane. " .. pronoun .. " carefully takes the pirate off your hands, taking precautions you think are completely unnecessary, and then hands you your pay."
pay_capture_text[3] = "The officer you deal with seems to especially dislike %s. " .. pronoun .. " takes the pirate off your hands and hands you your pay without speaking a word."
pay_capture_text[4] = "A fearful-looking officer rushes %s into a secure hold, pays you the appropriate bounty, and then hurries off."
pay_capture_text[5] = "The officer you deal with thanks you profusely for capturing %s alive, pays you, and sends you off."
pay_capture_text[6] = "Upon learning that you managed to capture %s alive, the previously depressed-looking officer suddenly brightens up. " .. pronoun .. " takes the pirate into custody and hands you your pay."
pay_capture_text[7] = "When you ask the officer for your bounty on %s, " .. pronoun:lower() .. " sighs, takes the pirate into custody, goes through some paperwork, and hands you your pay, mumbling something about how useless capturing pirates alive is."
pay_kill_text = {}
pay_kill_text[1] = "After verifying that you killed %s, an officer hands you your pay."
pay_kill_text[2] = "After verifying that %s is indeed dead, the officer sighs and hands you your pay."
pay_kill_text[3] = "This officer is clearly annoyed that %s is dead. " .. pronoun .. " mumbles something about incompetent bounty hunters the entire time as " .. pronoun:lower() .. " takes care of the paperwork and hands you your bounty."
pay_kill_text[4] = "The officer seems disappointed, yet unsurprised that you failed to capture %s alive. " .. pronoun .. " hands you your lesser bounty without speaking a word."
pay_kill_text[5] = "When you ask the officer for your bounty on %s, " .. pronoun:lower() .. " sighs, leads you into his office, goes through some paperwork, and hands you your pay, mumbling something about how useless bounty hunters are."
pay_kill_text[6] = "The officer verifies the death of %s, goes through the necessary paperwork, and hands you your pay, looking annoyed the entire time."
fail_kill_text = "MISSION FAILURE! %s has been killed."
misn_title = "%s Alive Bounty in %s"
misn_desc = "The pirate known as %s was recently seen in the %s system. %s authorities want this pirate alive."
osd_msg[2] = "Capture %s"
osd_msg_kill = "Kill %s"
end
function pilot_death ()
if board_failed then
succeed()
target_killed = true
else
fail( fail_kill_text:format( name ) )
end
end
-- Set up the ship, credits, and reputation based on the level.
function bounty_setup ()
if level == 1 then
ship = "Pirate Hyena"
credits = 100000 + rnd.sigma() * 30000
reputation = 0
elseif level == 2 then
ship = "Pirate Shark"
credits = 300000 + rnd.sigma() * 100000
reputation = 1
elseif level == 3 then
if rnd.rnd() < 0.5 then
ship = "Pirate Vendetta"
else
ship = "Pirate Ancestor"
end
credits = 800000 + rnd.sigma() * 160000
reputation = 3
elseif level == 4 then
if rnd.rnd() < 0.5 then
ship = "Pirate Admonisher"
else
ship = "Pirate Phalanx"
end
credits = 1400000 + rnd.sigma() * 240000
reputation = 5
elseif level == 5 then
ship = "Pirate Kestrel"
credits = 2500000 + rnd.sigma() * 500000
reputation = 7
end
end
function board_fail ()
if rnd.rnd() < 0.25 then
board_failed = true
credits = credits / 5
local t = kill_instead_text[ rnd.rnd( 1, #kill_instead_text ) ]:format(
name, numstring( credits ) )
tk.msg( kill_instead_title, t )
osd_msg[2] = osd_msg_kill:format( name )
misn.osdCreate( osd_title, osd_msg )
misn.osdActive( 2 )
end
end
| gpl-3.0 |
fwellner-tgm/Bruchtest | Test/Unit_Division.py | 1575 | """
Created on 27.12.2013
@author: uhs374h
"""
import unittest
from Bruch.Bruch import *
class TestDivision(unittest.TestCase):
def setUp(self):
self.b = Bruch(3, 2)
self.b2 = Bruch(self.b)
self.b3 = Bruch(4, 2)
pass
def tearDown(self):
del self.b, self.b2, self.b3
pass
def testdiv(self):
self.b = self.b / Bruch(4)
assert(float(self.b) == 0.375)
def testdiv2(self):
self.b = self.b / self.b3
assert(float(self.b) == 0.75)
def testdiv3(self):
self.b2 = self.b / 2
assert(float(self.b2) == 0.75)
def testrdivError(self):
self.assertRaises(TypeError, self.b2.__rtruediv__, 3.0)
def testrdiv(self):
self.b2 = 2 / Bruch(2)
assert(float(self.b2) == 1)
def testdivZeroError(self):
self.assertRaises(ZeroDivisionError, self.b2.__truediv__, 0)
def testdivTypeError(self):
self.assertRaises(TypeError, self.b2.__truediv__, 3.1)
def testdivZeroError2(self):
self.assertRaises(ZeroDivisionError, self.b2.__truediv__, Bruch(0, 3))
def testrdivZeroError(self):
bneu = Bruch(0, 3)
self.assertRaises(ZeroDivisionError, bneu.__rtruediv__, 3)
def testiDiv(self):
self.b /= 2
assert(self.b == Bruch(3, 4))
def testiDiv2(self):
self.b /= Bruch(2)
assert(self.b == Bruch(3, 4))
def testiDivError(self):
self.assertRaises(TypeError, self.b.__itruediv__, "other")
if __name__ == "__main__":
unittest.main() | gpl-3.0 |
tor4kichi/Hohoema | Hohoema/Models.UseCase/Playlist/PlaylistFactory/LocalMylistPlaylistFactory.cs | 1756 | using Hohoema.Models.Domain.LocalMylist;
using Hohoema.Models.Domain.Playlist;
using Hohoema.Models.Infrastructure;
using Hohoema.Models.UseCase.Hohoema.LocalMylist;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Hohoema.Models.UseCase.Playlist.PlaylistFactory
{
public sealed class LocalMylistPlaylistFactory : IPlaylistFactory
{
private readonly LocalMylistManager _localMylistManager;
private readonly QueuePlaylist _queuePlaylist;
public LocalMylistPlaylistFactory(
LocalMylistManager localMylistManager,
QueuePlaylist queuePlaylist
)
{
_localMylistManager = localMylistManager;
_queuePlaylist = queuePlaylist;
}
public ValueTask<IPlaylist> Create(PlaylistId playlistId)
{
if (playlistId == QueuePlaylist.Id)
{
return new(_queuePlaylist);
}
else
{
var localPlaylist = _localMylistManager.GetPlaylist(playlistId.Id);
if (localPlaylist == null)
{
throw new HohoemaExpception();
}
return new(localPlaylist);
}
}
public IPlaylistSortOption DeserializeSortOptions(string serializedSortOptions)
{
if (string.IsNullOrEmpty(serializedSortOptions))
{
return new LocalPlaylistSortOption();
}
return LocalPlaylistSortOption.Deserialize(serializedSortOptions);
}
}
}
| gpl-3.0 |
zenn1989/scoria-interlude | L2Jscoria-Game/data/scripts/village_master/elven_human_fighters_2/__init__.py | 4821 | # Created by DrLecter, based on DraX' scripts
# This script is part of the L2J Datapack Project
# Visit us at http://www.l2jdp.com/
# See readme-dp.txt and gpl.txt for license and distribution details
# Let us know if you did not receive a copy of such files.
import sys
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "elven_human_fighters_2"
#Quest items
MARK_OF_CHALLENGER = 2627
MARK_OF_DUTY = 2633
MARK_OF_SEEKER = 2673
MARK_OF_TRUST = 2734
MARK_OF_DUELIST = 2762
MARK_OF_SEARCHER = 2809
MARK_OF_HEALER = 2820
MARK_OF_LIFE = 3140
MARK_OF_CHAMPION = 3276
MARK_OF_SAGITTARIUS = 3293
MARK_OF_WITCHCRAFT = 3307
#HANNAVALT,BLACKBIRD,SIRIA,SEDRICK,MARCUS,HECTOR,SCHULE
NPCS=[30109,30187,30689,30849,30900,31965,32094]
#event:[newclass,req_class,req_race,low_ni,low_i,ok_ni,ok_i,req_item]
#low_ni : level too low, and you dont have quest item
#low_i: level too low, despite you have the item
#ok_ni: level ok, but you don't have quest item
#ok_i: level ok, you got quest item, class change takes place
CLASSES = {
"TK":[20,19,1,"36","37","38","39",[MARK_OF_DUTY,MARK_OF_LIFE,MARK_OF_HEALER]],
"SS":[21,19,1,"40","41","42","43",[MARK_OF_CHALLENGER,MARK_OF_LIFE,MARK_OF_DUELIST]],
"PL":[ 5, 4,0,"44","45","46","47",[MARK_OF_DUTY,MARK_OF_TRUST,MARK_OF_HEALER]],
"DA":[ 6, 4,0,"48","49","50","51",[MARK_OF_DUTY,MARK_OF_TRUST,MARK_OF_WITCHCRAFT]],
"TH":[ 8, 7,0,"52","53","54","55",[MARK_OF_SEEKER,MARK_OF_TRUST,MARK_OF_SEARCHER]],
"HE":[ 9, 7,0,"56","57","58","59",[MARK_OF_SEEKER,MARK_OF_TRUST,MARK_OF_SAGITTARIUS]],
"PW":[23,22,1,"60","61","62","63",[MARK_OF_SEEKER,MARK_OF_LIFE,MARK_OF_SEARCHER]],
"SR":[24,22,1,"64","65","66","67",[MARK_OF_SEEKER,MARK_OF_LIFE,MARK_OF_SAGITTARIUS]],
"GL":[ 2, 1,0,"68","69","70","71",[MARK_OF_CHALLENGER,MARK_OF_TRUST,MARK_OF_DUELIST]],
"WL":[ 3, 1,0,"72","73","74","75",[MARK_OF_CHALLENGER,MARK_OF_TRUST,MARK_OF_CHAMPION]]
}
#Messages
default = "No Quest"
def change(st,player,newclass,items) :
for item in items :
st.takeItems(item,1)
st.playSound("ItemSound.quest_fanfare_2")
player.setClassId(newclass)
player.setBaseClass(newclass)
player.broadcastUserInfo()
return
class Quest (JQuest) :
def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)
def onAdvEvent (self,event,npc,player) :
npcId = npc.getNpcId()
htmltext = default
suffix = ''
st = player.getQuestState(qn)
if not st : return
race = player.getRace().ordinal()
classid = player.getClassId().getId()
level = player.getLevel()
if npcId not in NPCS : return
if not event in CLASSES.keys() :
return event
else :
newclass,req_class,req_race,low_ni,low_i,ok_ni,ok_i,req_item=CLASSES[event]
if race == req_race and classid == req_class :
item = True
for i in req_item :
if not st.getQuestItemsCount(i):
item = False
if level < 40 :
suffix = low_i
if not item :
suffix = low_ni
else :
if not item :
suffix = ok_ni
else :
suffix = ok_i
change(st,player,newclass,req_item)
st.exitQuest(1)
htmltext = "30109-"+suffix+".htm"
return htmltext
def onTalk (self,npc,player):
st = player.getQuestState(qn)
npcId = npc.getNpcId()
race = player.getRace().ordinal()
classId = player.getClassId()
id = classId.getId()
htmltext = default
if player.isSubClassActive() :
st.exitQuest(1)
return htmltext
if npcId in NPCS :
htmltext = "30109"
if race in [0,1] : # Human and Elves only
if id == 19 : # elven knight
return htmltext+"-01.htm"
elif id == 4 : # human knight
return htmltext+"-08.htm"
elif id == 7 : # rogue
return htmltext+"-15.htm"
elif id == 22 : # elven scout
return htmltext+"-22.htm"
elif id == 1 : # human warrior
return htmltext+"-29.htm"
elif classId.level() == 0 : # first occupation change not made yet
htmltext += "-76.htm"
elif classId.level() >= 2 : # second/third occupation change already made
htmltext += "-77.htm"
else :
htmltext += "-78.htm" # other conditions
else :
htmltext += "-78.htm" # other races
st.exitQuest(1)
return htmltext
QUEST = Quest(99991,qn,"village_master")
CREATED = State('Start', QUEST)
QUEST.setInitialState(CREATED)
for npc in NPCS:
QUEST.addStartNpc(npc)
QUEST.addTalkId(npc)
| gpl-3.0 |
reichlab/diffport | tests/test_watchers.py | 15267 | """
Tests for watchers
"""
from diffport.core import Diffport
from diffport.watchers import *
from pathlib import Path
from random import random, randint
import pytest
import dataset
@pytest.fixture
def pgurl(request):
"""
Return url for connecting to postgres
"""
# Fill in stuff
url = "postgresql://postgres@localhost:5432/diffport_test_db"
db = dataset.connect(url)
def clear_db():
# Remove left-out stuff
db.query("DROP SCHEMA public CASCADE;")
db.query("CREATE SCHEMA public;")
request.addfinalizer(clear_db)
return url
def get_diffp(path, config, url):
"""
Return a diffport instance
"""
diffp = Diffport(config, Path(path).joinpath("store"))
diffp.connect(url)
return diffp
class TestNumberOfRowsHash:
"""
Tests for number-of-rows-hash
"""
config_basic = [{
"name": "number-of-rows-hash",
"config": [
{
"table": "table_basic"
}
]
}]
config_grouped = [{
"name": "number-of-rows-hash",
"config": [
{
"groupby": ["g_one", "g_two"],
"table": "table_grouped"
}
]
}]
def init_db(self, db):
# Setup basic table
db.query(f"CREATE TABLE table_basic (id SERIAL PRIMARY KEY, one INTEGER, two INTEGER);")
db.query(f"CREATE TABLE table_grouped (id SERIAL PRIMARY KEY, g_one TEXT, g_two TEXT, num INTEGER);")
def seed_db(self, db):
for _ in range(20):
db.query(f"INSERT INTO table_basic(one, two) VALUES ({randint(0, 100)}, {randint(0, 100)});")
for _ in range(20):
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'b', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'c', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', {randint(0, 100)});")
# Rows for removal
# 5555x are removed, 1111x are not
db.query(f"INSERT INTO table_basic(one, two) VALUES (55555, 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', 55555);")
def add_rows(self, db):
db.query(f"INSERT INTO table_basic(one, two) VALUES (11111, 11111);")
db.query(f"INSERT INTO table_basic(one, two) VALUES (11111, 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
def remove_rows(self, db):
db.query(f"DELETE FROM table_basic WHERE one = 55555;")
db.query(f"DELETE FROM table_grouped WHERE num = 55555;")
# Remove a grouping completely
db.query(f"DELETE FROM table_grouped WHERE g_two = 'b'")
def clean_db(self, db):
db.query(f"DROP TABLE table_basic;")
db.query(f"DROP TABLE table_grouped;")
def test_diff_basic(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config_basic, pgurl)
self.init_db(diffp.db)
self.seed_db(diffp.db)
old_hash = diffp.save_snapshot()
self.add_rows(diffp.db)
self.remove_rows(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": [{ "table": "table_basic" }],
"data": [["table_basic", {"removed": 1, "added": 2}, "basic"]]
}
report = NumberOfRowsHash.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
def test_diff_grouped(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config_grouped, pgurl)
self.init_db(diffp.db)
self.seed_db(diffp.db)
old_hash = diffp.save_snapshot()
self.add_rows(diffp.db)
self.remove_rows(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": [{ "groupby": ["g_one", "g_two"], "table": "table_grouped" }],
"data": [
["table_grouped",
[(['elec', 'a'], {"removed": 1, "added": 1}),
(['mech', 'x'], {"removed": 2, "added": 0}),
(['mech', 'y'], {"removed": 0, "added": 2}),
(['elec', 'b'], {"removed": 20, "added": 0}),
(['mech', 'z'], {"removed": 0, "added": 3})],
"grouped"]
]
}
report = NumberOfRowsHash.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
class TestNumberOfRows:
"""
Tests for number-of-rows
"""
config_basic = [{
"name": "number-of-rows",
"config": [
{
"table": "table_basic"
}
]
}]
config_grouped = [{
"name": "number-of-rows",
"config": [
{
"groupby": ["g_one", "g_two"],
"table": "table_grouped"
}
]
}]
def init_db(self, db):
# Setup basic table
db.query(f"CREATE TABLE table_basic (id SERIAL PRIMARY KEY, one INTEGER, two INTEGER);")
db.query(f"CREATE TABLE table_grouped (id SERIAL PRIMARY KEY, g_one TEXT, g_two TEXT, num INTEGER);")
def seed_db(self, db):
for _ in range(20):
db.query(f"INSERT INTO table_basic(one, two) VALUES ({randint(0, 100)}, {randint(0, 100)});")
for _ in range(20):
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'b', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'c', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', {randint(0, 100)});")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', {randint(0, 100)});")
# Rows for removal
# 5555x are removed, 1111x are not
db.query(f"INSERT INTO table_basic(one, two) VALUES (55555, 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', 55555);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'x', 55555);")
def add_rows(self, db):
db.query(f"INSERT INTO table_basic(one, two) VALUES (11111, 11111);")
db.query(f"INSERT INTO table_basic(one, two) VALUES (11111, 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('elec', 'a', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'y', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
db.query(f"INSERT INTO table_grouped(g_one, g_two, num) VALUES ('mech', 'z', 11111);")
def remove_rows(self, db):
db.query(f"DELETE FROM table_basic WHERE one = 55555;")
db.query(f"DELETE FROM table_grouped WHERE num = 55555;")
# Remove a grouping completely
db.query(f"DELETE FROM table_grouped WHERE g_two = 'b'")
def clean_db(self, db):
db.query(f"DROP TABLE table_basic;")
db.query(f"DROP TABLE table_grouped;")
def test_diff_basic(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config_basic, pgurl)
self.init_db(diffp.db)
self.seed_db(diffp.db)
old_hash = diffp.save_snapshot()
self.add_rows(diffp.db)
self.remove_rows(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": [{ "table": "table_basic" }],
"data": [["table_basic", 1, "basic"]]
}
report = NumberOfRows.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
def test_diff_grouped(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config_grouped, pgurl)
self.init_db(diffp.db)
self.seed_db(diffp.db)
old_hash = diffp.save_snapshot()
self.add_rows(diffp.db)
self.remove_rows(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": [{ "groupby": ["g_one", "g_two"], "table": "table_grouped" }],
"data": [
["table_grouped",
[(['mech', 'x'], -2),
(['mech', 'y'], 2),
(['elec', 'b'], -20),
(['mech', 'z'], 3)],
"grouped"]
]
}
report = NumberOfRows.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
class TestTablesInSchema:
"""
Tests for tables-in-schema watcher
"""
config = [{
"name": "tables-in-schema",
"config": ["scm_one", "scm_two", "scm_three"]
}]
schema_tables = [
"scm_one.tab_one",
"scm_one.tab_two",
"scm_two.tab_one"
]
to_add = ["scm_one.tab_three", "scm_two.tab_two"]
to_remove = ["scm_one.tab_one"]
def init_db(self, db):
for schema in self.config[0]["config"]:
db.query(f"CREATE SCHEMA {schema};")
for table in self.schema_tables:
db.query(f"CREATE TABLE {table} (num INTEGER);")
def fill_db(self, db):
for table in self.to_add:
db.query(f"CREATE TABLE {table} (num INTEGER);")
for table in self.to_remove:
db.query(f"DROP TABLE {table};")
def clean_db(self, db):
for schema in self.config[0]["config"]:
db.query(f"DROP SCHEMA {schema} CASCADE;")
def test_diff(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config, pgurl)
self.init_db(diffp.db)
old_hash = diffp.save_snapshot()
self.fill_db(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": ["scm_one", "scm_two", "scm_three"],
"data": [
["scm_one", {
"removed": ["tab_one"],
"added": ["tab_three"]
}],
["scm_two", {
"removed": [],
"added": ["tab_two"]
}]
]
}
report = SchemaTables.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
class TestColumnsInSchema:
"""
Tests for columns-in-schema
"""
config = [{
"name": "columns-in-schema",
"config": ["scm_one", "scm_two", "scm_three"]
}]
schema_tables = [
"scm_one.tab_one",
"scm_one.tab_two",
"scm_two.tab_one",
"scm_three.tab_one"
]
to_add = ["scm_one.tab_one"]
to_remove = ["scm_one.tab_one", "scm_one.tab_two", "scm_two.tab_one"]
def init_db(self, db):
for schema in self.config[0]["config"]:
db.query(f"CREATE SCHEMA {schema};")
for table in self.schema_tables:
db.query(f"CREATE TABLE {table} (one INTEGER, pruned_col INTEGER);")
def fill_db(self, db):
for table in self.to_add:
db.query(f"ALTER TABLE {table} ADD COLUMN added_col INTEGER;")
for table in self.to_remove:
db.query(f"ALTER TABLE {table} DROP COLUMN pruned_col;")
def clean_db(self, db):
for schema in self.config[0]["config"]:
db.query(f"DROP SCHEMA {schema} CASCADE;")
def test_diff(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config, pgurl)
self.init_db(diffp.db)
old_hash = diffp.save_snapshot()
self.fill_db(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": ["scm_one", "scm_two", "scm_three"],
"data": [
["scm_one", {
"removed": ["pruned_col"],
"added": ["added_col"]
}],
["scm_two", {
"removed": ["pruned_col"],
"added": []
}]
]
}
report = SchemaColumns.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
class TestTableChange:
"""
Tests for table-change
"""
config = [{
"name": "table-change",
"config": {
"schemas": ["scm_one", "scm_two"],
"tables": ["tab_one", "tab_two"]
}
}]
schema_tables = [
"scm_one.tab_one",
"scm_one.tab_two",
"scm_two.tab_one",
"scm_two.tab_two",
"scm_two.tab_three",
"scm_two.tab_four"
]
to_change = [
"tab_one",
"scm_one.tab_two",
"scm_two.tab_three",
"scm_two.tab_four"
]
def init_db(self, db):
for schema in self.config[0]["config"]["schemas"]:
db.query(f"CREATE SCHEMA {schema};")
for table in self.schema_tables + self.config[0]["config"]["tables"]:
db.query(f"CREATE TABLE {table} (num INTEGER);")
def fill_db(self, db):
for table in self.to_change:
db.query(f"INSERT INTO {table} VALUES ({randint(0, 100)});")
def clean_db(self, db):
for table in self.schema_tables + self.config[0]["config"]["tables"]:
db.query(f"DROP TABLE {table};")
for schema in self.config[0]["config"]["schemas"]:
db.query(f"DROP SCHEMA {schema} CASCADE;")
def test_diff(self, tmpdir, pgurl):
diffp = get_diffp(tmpdir, self.config, pgurl)
self.init_db(diffp.db)
old_hash = diffp.save_snapshot()
self.fill_db(diffp.db)
new_hash = diffp.save_snapshot()
self.clean_db(diffp.db)
diff = {
"config": {
"schemas": ["scm_one", "scm_two"],
"tables": ["tab_one", "tab_two"]
},
"data": self.to_change
}
report = TableChange.report(diff)
assert diffp.report(old_hash, new_hash).endswith(report)
| gpl-3.0 |
legacy-vault/tests | go/tree/binary/binary.go | 429 | // binary.go
package main
import (
"fmt"
)
type treeNode struct {
originalIndex uint64 // Index of the Object in the DataBase.
content string // Text of an Object.
parentNode *treeNode
leftNode *treeNode
rightNode *treeNode
duplicatesCount uint64 // Number of Objects with the same Text.
}
type tree struct {
root *treeNode
nodesCount uint64
}
func main() {
fmt.Println("") //
}
| gpl-3.0 |
iCarto/siga | es.icarto.gvsig.siga.mapsheets/src/org/gvsig/mapsheets/print/series/tool/action/ActionDelete.java | 879 | package org.gvsig.mapsheets.print.series.tool.action;
import org.gvsig.mapsheets.print.series.fmap.MapSheetGrid;
import org.gvsig.mapsheets.print.series.fmap.MapSheetGridGraphic;
/**
* Undo-able delete action. You can delete several sheets at a time.
*
* @author jldominguez
*
*/
public class ActionDelete implements ActionOnGrid {
protected MapSheetGridGraphic[] grfs = null;
protected MapSheetGrid grid = null;
public ActionDelete(MapSheetGridGraphic[] gg, MapSheetGrid gr) {
grfs = gg;
grid = gr;
}
public int getType() {
return ActionOnGrid.GRID_ACTION_DELETE;
}
public boolean undo() {
if (grfs == null || grid == null) {
return false;
} else {
int len = grfs.length;
for (int i=0; i<len; i++) {
grid.getTheMemoryDriver().addGraphic(grfs[i], false);
}
grid.getTheMemoryDriver().updateExtent();
return true;
}
}
}
| gpl-3.0 |
ebrahimraeyat/civilTools | py_widget/settings.py | 6520 | import os
from pathlib import Path
from PySide2 import QtWidgets
from PySide2.QtWidgets import QTreeWidgetItemIterator
import FreeCAD
import FreeCADGui as Gui
from db import ostanha
from exporter import config
civiltools_path = Path(__file__).absolute().parent.parent
class Form(QtWidgets.QWidget):
def __init__(self, etabs_model):
super(Form, self).__init__()
self.form = Gui.PySideUic.loadUi(str(civiltools_path / 'widgets' / 'civiltools_project_settings.ui'))
self.etabs = etabs_model
self.stories = self.etabs.SapModel.Story.GetStories()[1]
self.create_widgets()
self.create_connections()
self.fill_top_bot_stories()
self.fill_height_and_no_of_stories()
self.load_config()
def create_widgets(self):
ostans = ostanha.ostans.keys()
self.form.ostanBox.addItems(ostans)
self.set_citys_of_current_ostan()
# self.setA()
iterator = QTreeWidgetItemIterator(self.form.x_treeWidget)
i = 0
while iterator.value():
item = iterator.value()
iterator += 1
if i == 2:
self.form.x_treeWidget.setCurrentItem(item, 0)
break
i += 1
iterator = QTreeWidgetItemIterator(self.form.y_treeWidget)
i = 0
while iterator.value():
item = iterator.value()
iterator += 1
if i == 2:
self.form.y_treeWidget.setCurrentItem(item, 0)
break
i += 1
def fill_top_bot_stories(self):
for combo_box in (
self.form.bot_x_combo,
self.form.top_x_combo,
# self.form.bot_y_combo,
# self.form.top_y_combo,
):
combo_box.addItems(self.stories)
n = len(self.stories)
self.form.bot_x_combo.setCurrentIndex(0)
self.form.top_x_combo.setCurrentIndex(n - 2)
# self.form.bot_y_combo.setCurrentIndex(0)
# self.form.top_y_combo.setCurrentIndex(n - 2)
def fill_height_and_no_of_stories(self):
bot_story_x = bot_story_y = self.form.bot_x_combo.currentText()
top_story_x = top_story_y = self.form.top_x_combo.currentText()
# bot_story_y = self.form.bot_y_combo.currentText()
# top_story_y = self.form.top_y_combo.currentText()
bot_level_x, top_level_x, bot_level_y, top_level_y = self.etabs.story.get_top_bot_levels(
bot_story_x, top_story_x, bot_story_y, top_story_y, False
)
hx, hy = self.etabs.story.get_heights(bot_story_x, top_story_x, bot_story_y, top_story_y, False)
nx, ny = self.etabs.story.get_no_of_stories(bot_level_x, top_level_x, bot_level_y, top_level_y)
self.form.no_story_x_spinbox.setValue(nx)
# self.form.no_story_y_spinbox.setValue(ny)
self.form.height_x_spinbox.setValue(hx)
# self.form.height_y_spinbox.setValue(hy)
def get_current_ostan(self):
return self.form.ostanBox.currentText()
def get_current_city(self):
return self.form.cityBox.currentText()
def get_citys_of_current_ostan(self, ostan):
'''return citys of ostan'''
return ostanha.ostans[ostan].keys()
def set_citys_of_current_ostan(self):
self.form.cityBox.clear()
ostan = self.get_current_ostan()
citys = self.get_citys_of_current_ostan(ostan)
# citys.sort()
self.form.cityBox.addItems(citys)
def create_connections(self):
self.form.ostanBox.currentIndexChanged.connect(self.set_citys_of_current_ostan)
self.form.cityBox.currentIndexChanged.connect(self.setA)
self.form.x_treeWidget.itemActivated.connect(self.xactivate)
self.form.bot_x_combo.currentIndexChanged.connect(self.fill_height_and_no_of_stories)
self.form.top_x_combo.currentIndexChanged.connect(self.fill_height_and_no_of_stories)
def accept(self):
self.save_config()
Gui.Control.closeDialog()
def load_config(self):
etabs_filename = self.etabs.get_filename()
json_file = etabs_filename.with_suffix('.json')
if json_file.exists():
config.load(json_file, self.form)
param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/civilTools")
show_at_startup = param.GetBool("FirstTime", True)
self.form.show_at_startup.setChecked(show_at_startup)
ostan = param.GetString("ostan", 'قم')
city = param.GetString("city", 'قم')
index = self.form.ostanBox.findText(ostan)
self.form.ostanBox.setCurrentIndex(index)
index = self.form.cityBox.findText(city)
self.form.cityBox.setCurrentIndex(index)
def save_config(self, json_file=None):
exists = False
if not json_file:
etabs_filename = self.etabs.get_filename()
json_file = etabs_filename.with_suffix('.json')
if json_file.exists():
exists = True
tx, ty = config.get_analytical_periods(json_file)
config.save(json_file, self.form)
if exists:
config.save_analytical_periods(json_file, tx, ty)
param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/civilTools")
show_at_startup = self.form.show_at_startup.isChecked()
param.SetBool("FirstTime", show_at_startup)
ostan = self.get_current_ostan()
city = self.get_current_city()
param.SetString("ostan", ostan)
param.SetString("city", city)
def xactivate(self):
if self.form.x_treeWidget.currentItem().parent():
system = self.form.x_treeWidget.currentItem().parent().text(0)
lateral = self.form.x_treeWidget.currentItem().text(0)
self.form.y_treeWidget.scrollToItem(self.form.x_treeWidget.currentItem())
return (system, lateral)
return None
def yactivate(self):
if self.form.y_treeWidget.currentItem().parent():
system = self.form.y_treeWidget.currentItem().parent().text(0)
lateral = self.form.y_treeWidget.currentItem().text(0)
return (system, lateral)
return None
def setA(self):
sotoh = ['خیلی زیاد', 'زیاد', 'متوسط', 'کم']
ostan = self.get_current_ostan()
city = self.get_current_city()
try:
A = int(ostanha.ostans[ostan][city][0])
self.form.accText.setText(sotoh[A - 1])
except KeyError:
pass
| gpl-3.0 |
cyborgize/love | src/common/Variant.cpp | 5168 | /**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "Variant.h"
#include "common/StringMap.h"
namespace love
{
extern StringMap<Type, TYPE_MAX_ENUM> types;
static love::Type extractudatatype(lua_State *L, int idx)
{
Type t = INVALID_ID;
if (!lua_isuserdata(L, idx))
return t;
if (luaL_getmetafield(L, idx, "type") == 0)
return t;
lua_pushvalue(L, idx);
int result = lua_pcall(L, 1, 1, 0);
if (result == 0)
types.find(lua_tostring(L, -1), t);
if (result == 0 || result == LUA_ERRRUN)
lua_pop(L, 1);
return t;
}
static inline void delete_table(std::vector<std::pair<Variant*, Variant*> > *table)
{
while (!table->empty())
{
std::pair<Variant*, Variant*> &kv = table->back();
kv.first->release();
kv.second->release();
table->pop_back();
}
delete table;
}
Variant::Variant()
: type(NIL)
, data()
{
}
Variant::Variant(bool boolean)
: type(BOOLEAN)
{
data.boolean = boolean;
}
Variant::Variant(double number)
: type(NUMBER)
{
data.number = number;
}
Variant::Variant(const char *string, size_t len)
: type(STRING)
{
char *buf = new char[len+1];
memset(buf, 0, len+1);
memcpy(buf, string, len);
data.string.str = buf;
data.string.len = len;
}
Variant::Variant(char c)
: type(CHARACTER)
{
data.character = c;
}
Variant::Variant(void *userdata)
: type(LUSERDATA)
{
data.userdata = userdata;
}
Variant::Variant(love::Type udatatype, void *userdata)
: type(FUSERDATA)
, udatatype(udatatype)
{
if (udatatype != INVALID_ID)
{
Proxy *p = (Proxy *) userdata;
data.userdata = p->object;
p->object->retain();
}
else
data.userdata = userdata;
}
// Variant gets ownership of the vector.
Variant::Variant(std::vector<std::pair<Variant*, Variant*> > *table)
: type(TABLE)
{
data.table = table;
}
Variant::~Variant()
{
switch (type)
{
case STRING:
delete[] data.string.str;
break;
case FUSERDATA:
((love::Object *) data.userdata)->release();
break;
case TABLE:
delete_table(data.table);
default:
break;
}
}
Variant *Variant::fromLua(lua_State *L, int n, bool allowTables)
{
Variant *v = nullptr;
size_t len;
const char *str;
if (n < 0) // Fix the stack position, we might modify it later
n += lua_gettop(L) + 1;
switch (lua_type(L, n))
{
case LUA_TBOOLEAN:
v = new Variant(luax_toboolean(L, n));
break;
case LUA_TNUMBER:
v = new Variant(lua_tonumber(L, n));
break;
case LUA_TSTRING:
str = lua_tolstring(L, n, &len);
v = new Variant(str, len);
break;
case LUA_TLIGHTUSERDATA:
v = new Variant(lua_touserdata(L, n));
break;
case LUA_TUSERDATA:
v = new Variant(extractudatatype(L, n), lua_touserdata(L, n));
break;
case LUA_TNIL:
v = new Variant();
break;
case LUA_TTABLE:
if (allowTables)
{
bool success = true;
std::vector<std::pair<Variant*, Variant*> > *table = new std::vector<std::pair<Variant*, Variant*> >();
lua_pushnil(L);
while (lua_next(L, n))
{
Variant *key = fromLua(L, -2, false);
if (!key)
{
success = false;
lua_pop(L, 2);
break;
}
Variant *value = fromLua(L, -1, false);
if (!value)
{
delete key;
success = false;
lua_pop(L, 2);
break;
}
table->push_back(std::make_pair(key, value));
lua_pop(L, 1);
}
if (success)
v = new Variant(table);
else
delete_table(table);
}
break;
}
return v;
}
void Variant::toLua(lua_State *L)
{
switch (type)
{
case BOOLEAN:
lua_pushboolean(L, data.boolean);
break;
case CHARACTER:
lua_pushlstring(L, &data.character, 1);
break;
case NUMBER:
lua_pushnumber(L, data.number);
break;
case STRING:
lua_pushlstring(L, data.string.str, data.string.len);
break;
case LUSERDATA:
lua_pushlightuserdata(L, data.userdata);
break;
case FUSERDATA:
if (udatatype != INVALID_ID)
luax_pushtype(L, udatatype, (love::Object *) data.userdata);
else
lua_pushlightuserdata(L, data.userdata);
// I know this is not the same
// sadly, however, it's the most
// I can do (at the moment).
break;
case TABLE:
lua_newtable(L);
for (size_t i = 0; i < data.table->size(); ++i)
{
std::pair<Variant*, Variant*> &kv = data.table->at(i);
kv.first->toLua(L);
kv.second->toLua(L);
lua_settable(L, -3);
}
break;
case NIL:
default:
lua_pushnil(L);
break;
}
}
} // love
| gpl-3.0 |
DennisWeyrauch/MetaLanguageParser | Common/RWDictionary.cs | 13733 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace Common
{
/// <summary>
/// Represents an ordered dictionary with read/write access and non-muteable KeyValuePairs.<para/>
/// This is realized with a <see cref="List{T}"/> (T being <see cref="RWDictElement{TKey, TValue}"/>) that implements
/// <see cref="IDictionary{TKey, TValue}"/> to provide the order of a list with the lookup of a Dictionary.
/// It provides fluent transition between <see cref="KeyValuePair{TKey, TValue}"/> and <see cref="RWDictElement{TKey, TValue}"/>.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class RWDictionary<TKey, TValue> : List<RWDictElement<TKey, TValue>>, IDictionary<TKey, TValue>
{
#region Fields and Indexers
/// <summary>Gets or sets the element with the specified key.</summary>
/// <param name="key">The key of the element to get or set.</param>
/// <returns>The element with the specified key. See <see cref="List{T}.this[int]"/></returns>
/// <exception cref="System.ArgumentNullException"><paramref name="key"/> is null</exception>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found</exception>
public TValue this[TKey key]
{
get { return base[FindIndex(key)].Value; }
set { base[FindIndex(key)].Value = value; }
}
/// <summary>Gets the Value of the element at position <paramref name="idx"/></summary>
/// <param name="idx">Index to lookup</param>
/// <returns>See <see cref="List{T}.this[int]"/></returns>
public new TValue this[int idx]
{
get { return base[idx].Value; }
set { base[idx].Value = value; }
}
/// <summary>Gets an System.Collections.Generic.ICollection`1 containing the keys of the System.Collections.Generic.IDictionary`2.</summary>
/// <returns>An System.Collections.Generic.ICollection`1 containing the keys of the object\r\n that implements System.Collections.Generic.IDictionary`2.</returns>
public ICollection<TKey> Keys
{
get
{
ICollection<TKey> keys = new List<TKey>();
foreach (var item in this) {
keys.Add(item.Key);
}
return keys;
}
}
/// <summary>Gets an System.Collections.Generic.ICollection`1 containing the values in the\r\n
/// System.Collections.Generic.IDictionary`2.</summary>
/// <returns>An System.Collections.Generic.ICollection`1 containing the values in the object\r\n
/// that implements System.Collections.Generic.IDictionary`2.</returns>
public ICollection<TValue> Values
{
get
{
ICollection<TValue> values = new List<TValue>();
foreach (var item in this) {
values.Add(item.Value);
}
return values;
}
}
//public TValue this[TKey key] {...}
public bool IsReadOnly => false;
/// <summary>Retrieves the key at position <paramref name="idx"/></summary>
/// <param name="idx"></param>
/// <returns></returns>
public TKey getKey(int idx) => base[idx].Key;
public RWDictElement<TKey, TValue> getElem(TKey k) => base[FindIndex(k)];
//List<RWDictElement<TKey, TValue>>.FindIndex(Predicate<RWDictElement<TKey, TValue>> match)
/// <summary>
/// See <see cref="List{T}.FindIndex(Predicate{T} match)"/><para/>
/// Calls "List{T}.FindIndex() and searches for the first entry whoose Key matches <paramref name="k"/>
/// </summary>
/// <param name="k"></param>
/// <returns>Zero-based index of first match found, if any; otherwise, -1</returns>
public int FindIndex(TKey k)
{
return base.FindIndex((RWDictElement<TKey, TValue> da) => {
return da.Key.Equals(k);
});
}
#endregion
#region IDictionary-Methods
/// <summary>Adds an element with the provided key and value to the System.Collections.Generic.IDictionary`2.</summary>
/// <param name="k">The object to use as the key of the element to add.</param>
/// <param name="v">The object to use as the value of the element to add.</param>
/// <param name="overwrite">Whether or not to force assignment if <paramref name="k"/> already exists</param>
/// <exception cref="System.ArgumentNullException"><paramref name="k"/> is null.</exception>
/// <exception cref="System.ArgumentException">An element with the same key already exists in the System.Collections.Generic.IDictionary`2 and <paramref name="overwrite"/> is false.</exception>
/// <exception cref="System.NotSupportedException">The System.Collections.Generic.IDictionary`2 is read-only.</exception>
public void Add(TKey k, TValue v, bool overwrite)
{
if (k == null) throw new ArgumentNullException("Key is null");
if (FindIndex(k) != -1) {
if (overwrite) {
base[FindIndex(k)].Value = v;
} else throw new System.ArgumentException($"Key '{k}' already exists");
} else base.Add(new RWDictElement<TKey, TValue>(k, v));
}
/// <summary>Adds an element with the provided key and value to the System.Collections.Generic.IDictionary`2.</summary>
/// <param name="k">The object to use as the key of the element to add.</param>
/// <param name="v">The object to use as the value of the element to add.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="k"/> is null.</exception>
/// <exception cref="System.ArgumentException">An element with the same key already exists in the System.Collections.Generic.IDictionary`2.</exception>
/// <exception cref="System.NotSupportedException">The System.Collections.Generic.IDictionary`2 is read-only.</exception>
public void Add(TKey k, TValue v) => this.Add(k, v, false);
/*
}
// This partial part is to make the type fully compatible with the IDictionary Interface (from which all descriptions are copied over)
public partial class RWDictionary<TKey, TValue> : List<RWDictElement<TKey, TValue>>, IDictionary<TKey, TValue>
{//*/
//#region Fields and Indexers
//#endregion
//#region IDictionary-Methods
/// <summary>Determines whether the System.Collections.Generic.IDictionary`2 contains an element\r\n with the specified key.</summary>
/// <param name="key">The key to locate in the System.Collections.Generic.IDictionary`2.</param>
/// <returns>true if the System.Collections.Generic.IDictionary`2 contains an element with\r\n the key; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
public bool ContainsKey(TKey key) => (FindIndex(key) != -1);
/// <summary>Removes the element with the specified key from the System.Collections.Generic.IDictionary`2.</summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>true if the element is successfully removed; otherwise, false. This method also\r\n returns false if <paramref name="key"/> was not found in the original System.Collections.Generic.IDictionary`2.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="key"/> is null.</exception>
/// <exception cref="System.NotSupportedException">The System.Collections.Generic.IDictionary`2 is read-only.</exception>
public bool Remove(TKey key)
{
if (key == null) throw new ArgumentNullException("Key is null");
try {
base.RemoveAt(FindIndex(key));
} catch (Exception e) {
Console.WriteLine(e.Message);
return false;
}
return true;
}
/// <summary>Gets the value associated with the specified key.</summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the\r\n key is found; otherwise, the default value for the type of the value parameter.\r\n This parameter is passed uninitialized.</param>
/// <returns>true if the object that implements System.Collections.Generic.IDictionary`2 contains\r\n an element with the specified key; otherwise, false.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null) throw new ArgumentNullException("Key is null");
int idx = FindIndex(key);
if (idx != -1) {
value = base[idx].Value;
return true;
} else {
value = default(TValue);
return false;
}
}
#endregion
#region ICollection-Methods
public void Add(KeyValuePair<TKey, TValue> item) => Add(item.Key, item.Value);
public bool Contains(KeyValuePair<TKey, TValue> item) => base.Contains(item);
#warning UNTESTED:: ICollection<T>.CopyTo(KeyValuePair<>, int)
// Required override of IDictionary (Explicit since List already defines it via IList<-ICollection)
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
base.CopyTo(RWDictElement<TKey, TValue>.Convert(array), arrayIndex);
}
// Public accessor of above
//public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) => CopyTo(array, arrayIndex);
public bool Remove(KeyValuePair<TKey, TValue> item) => base.Remove(item);//Remove(item.Key);
#warning UNTESTED:: IEnumerable.GetEnumerator()
ReadOnlyDictionary<TKey, TValue> rodict;
/// <summary>
/// Converts the dictionary into a <see cref="System.Collections.ObjectModel.ReadOnlyDictionary{TKey, TValue}"/> and returns its Enumerator.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
rodict = new ReadOnlyDictionary<TKey, TValue>(this);
return rodict.GetEnumerator();
}
#endregion
/// <returns>String representation of this object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var elem in this) {
sb.AppendLine(elem.ToString());
}
return sb.ToString();
}
}
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
/// <summary>
/// <see cref="KeyValuePair{TKey, TValue}"/> with additional setter. Provides fluent transition between both.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class RWDictElement<TKey, TValue>
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
{
private TKey _key;
public TKey Key => _key;
public TValue Value;
private RWDictElement() { }
public RWDictElement(TKey k, TValue v)
{
this._key = k;
this.Value = v;
}
#region RWDictElement to KeyValuePair
public static implicit operator KeyValuePair<TKey, TValue>(RWDictElement<TKey, TValue> rw)
=> new KeyValuePair<TKey, TValue>(rw.Key, rw.Value);
public static KeyValuePair<TKey, TValue>[] Convert(RWDictElement<TKey, TValue>[] rw)
=> Array.ConvertAll(rw, (item) => (KeyValuePair<TKey, TValue>)item);
#endregion
#region KeyValuePair to RWDictElement
public RWDictElement(KeyValuePair<TKey, TValue> kw)
{
this._key = kw.Key;
this.Value = kw.Value;
}
public static implicit operator RWDictElement<TKey, TValue>(KeyValuePair<TKey, TValue> kv)
=> new RWDictElement<TKey, TValue>(kv.Key, kv.Value);
public static RWDictElement<TKey, TValue>[] Convert(KeyValuePair<TKey, TValue>[] kv)
=> Array.ConvertAll(kv, (item) => (RWDictElement<TKey, TValue>)item);
#endregion
#warning UNTESTED:: RWDictElement.Equals(object)
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public override bool Equals(object obj)
{
var rw = obj as RWDictElement<TKey, TValue>;
return Key.Equals(rw.Key) && Value.Equals(rw.Value);
}
/// <summary>Returns a string that represents the current object.</summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString() => $"{Key.ToString()} : {Value.ToString()}";
}
}
| gpl-3.0 |
UCLOrengoGroup/cath-tools | source/ct_uni/cath/scan/detail/stride/co_stride.hpp | 5265 | /// \file
/// \brief The co_stride header
/// \copyright
/// CATH Tools - Protein structure comparison tools such as SSAP and SNAP
/// Copyright (C) 2011, Orengo Group, University College London
///
/// 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/>.
#ifndef _CATH_TOOLS_SOURCE_CT_UNI_CATH_SCAN_DETAIL_STRIDE_CO_STRIDE_HPP
#define _CATH_TOOLS_SOURCE_CT_UNI_CATH_SCAN_DETAIL_STRIDE_CO_STRIDE_HPP
#include <numeric>
#include <optional>
#include <type_traits>
#include <utility>
#include "cath/common/algorithm/constexpr_modulo_fns.hpp"
namespace cath::scan::detail {
namespace detail {
/// \brief TODOCUMENT
template <typename T>
inline constexpr T stride_neighbour_index_of_centre(const T &prm_co_stride ///< TODOCUMENT
) {
static_assert( std::is_unsigned_v<T>, "stride_neighbour_index_of_centre() must be performed on an unsigned integral type" );
return prm_co_stride / 2;
}
/// \brief TODOCUMENT
///
/// \returns TODOCUMENT
///
/// \todo When there is a constexpr std::optional<> available, use that as the return type instead
template <typename T>
inline constexpr std::pair<bool, T> entry_index_of_stride_neighbour_index_impl(const T &prm_stride_index, ///< TODOCUMENT
const T &prm_co_stride, ///< TODOCUMENT
const T &prm_centre_entry_index, ///< TODOCUMENT
const T &prm_num_entries ///< TODOCUMENT
) {
static_assert( std::is_unsigned_v<T>, "entry_index_of_stride_neighbour_index_impl() must be performed on an unsigned integral type" );
return ( prm_centre_entry_index + prm_stride_index < detail::stride_neighbour_index_of_centre( prm_co_stride ) ) ? std::pair<bool, T>( false, 0 ) :
( prm_centre_entry_index + prm_stride_index >= detail::stride_neighbour_index_of_centre( prm_co_stride ) + prm_num_entries ) ? std::pair<bool, T>( false, 0 ) :
std::make_pair( true, prm_centre_entry_index + prm_stride_index - detail::stride_neighbour_index_of_centre( prm_co_stride ) );
}
} // namespace detail
/// \brief TODOCUMENT
template <typename T>
inline constexpr T co_stride(const T &prm_stride_a, ///< The stride TODOCUMENT
const T &prm_stride_b ///< The stride TODOCUMENT
) {
static_assert( std::is_unsigned_v<T>, "co_stride() must be performed on an unsigned integral type" );
return ::std::lcm( prm_stride_a + 1, prm_stride_b + 1 ) - 1;
}
/// \brief TODOCUMENT
template <typename T>
inline constexpr T entry_index_of_stride_rep(const T &prm_entry_index, ///< TODOCUMENT
const T &prm_co_stride ///< TODOCUMENT
) {
return ( prm_co_stride + 1 ) * ( ( prm_entry_index + detail::stride_neighbour_index_of_centre( prm_co_stride ) ) / ( prm_co_stride + 1 ) );
}
/// \brief TODOCUMENT
template <typename T>
inline constexpr T num_in_stride_neighbour_range(const T &prm_co_stride ///< TODOCUMENT
) {
static_assert( std::is_unsigned_v<T>, "num_stride_neighbour_range() must be performed on an unsigned integral type" );
return prm_co_stride + 1;
}
/// \brief TODOCUMENT
///
/// \returns TODOCUMENT
template <typename T>
inline ::std::optional<T> entry_index_of_stride_neighbour_index(const T &prm_stride_index, ///< TODOCUMENT
const T &prm_co_stride, ///< TODOCUMENT
const T &prm_centre_entry_index, ///< TODOCUMENT
const T &prm_num_entries ///< TODOCUMENT
) {
static_assert( std::is_unsigned_v<T>, "entry_index_of_stride_neighbour_index() must be performed on an unsigned integral type" );
const auto result = detail::entry_index_of_stride_neighbour_index_impl( prm_stride_index, prm_co_stride, prm_centre_entry_index, prm_num_entries );
return result.first ? ::std::make_optional( result.second ) : ::std::nullopt;
}
} // namespace cath::scan::detail
#endif // _CATH_TOOLS_SOURCE_CT_UNI_CATH_SCAN_DETAIL_STRIDE_CO_STRIDE_HPP
| gpl-3.0 |
hitchhiker/prime | Ext/Prime.Finance/Misc/DesignPortfolioItemModel.cs | 1308 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prime.Finance
{
public class DesignPortfolioItemModel
{
public decimal Units { get; }
public decimal AvgOpen { get; }
public decimal ProfitLossPerc { get; }
public decimal Sell { get; }
public decimal Buy { get; }
public string IconPath { get; }
public string Market { get; }
public string MarketDescription { get; }
public Money Invested { get; }
public Money ProfitLoss { get; }
public Money Value { get; }
public DesignPortfolioItemModel(decimal units, decimal avgOpen, decimal profitLossPerc, decimal sell, decimal buy, string iconPath, string market, string marketDescription, Money invested, Money profitLoss, Money value)
{
this.Units = units;
this.AvgOpen = avgOpen;
this.ProfitLossPerc = profitLossPerc;
this.Sell = sell;
this.Buy = buy;
this.IconPath = iconPath;
this.Market = market;
this.MarketDescription = marketDescription;
this.Invested = invested;
this.ProfitLoss = profitLoss;
this.Value = value;
}
}
}
| gpl-3.0 |
hkwi/pio | spec/pio/open_flow/type_spec.rb | 105 | require 'pio'
describe Pio::OpenFlow do
Then { Pio::OpenFlow.constants.include?(:HELLO) == true }
end
| gpl-3.0 |
jorants/vopidy | vopidy_core/__init__.py | 115 | # -*- coding: utf-8 -*-
__author__ = 'Joran van APeldoorn'
__email__ = '[email protected]'
__version__ = '0.1.0'
| gpl-3.0 |
arguslab/ancor | spec/tasks/provision_network_spec.rb | 1128 | # Author: Ian Unruh, Alexandru G. Bardas
# Copyright (C) 2013-2014 Argus Cybersecurity Lab, Kansas State University
#
# This file is part of ANCOR.
#
# ANCOR 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.
#
# ANCOR 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 ANCOR. If not, see <http://www.gnu.org/licenses/>.
require 'spec_helper'
module Ancor
module Tasks
describe ProvisionNetwork do
include OpenStackHelper
let(:delete_task) { DeleteNetwork.new }
it 'creates and deletes a network', live: true do
network_id = setup_network_fixture
subject.perform network_id
delete_task.perform network_id
end
end
end
end
| gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/tests/tests/location/src/android/location/cts/GnssMeasurementTest.java | 5037 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.location.cts;
import android.location.GnssMeasurement;
import android.location.GnssStatus;
import android.os.Parcel;
public class GnssMeasurementTest extends GnssTestCase {
public void testDescribeContents() {
GnssMeasurement measurement = new GnssMeasurement();
measurement.describeContents();
}
public void testReset() {
GnssMeasurement measurement = new GnssMeasurement();
measurement.reset();
}
private static void setTestValues(GnssMeasurement measurement) {
measurement.setAccumulatedDeltaRangeMeters(1.0);
measurement.setAccumulatedDeltaRangeState(2);
measurement.setAccumulatedDeltaRangeUncertaintyMeters(3.0);
measurement.setCarrierCycles(4);
measurement.setCarrierFrequencyHz(5.0f);
measurement.setCarrierPhase(6.0);
measurement.setCarrierPhaseUncertainty(7.0);
measurement.setCn0DbHz(8.0);
measurement.setConstellationType(GnssStatus.CONSTELLATION_GALILEO);
measurement.setMultipathIndicator(GnssMeasurement.MULTIPATH_INDICATOR_DETECTED);
measurement.setPseudorangeRateMetersPerSecond(9.0);
measurement.setPseudorangeRateUncertaintyMetersPerSecond(10.0);
measurement.setReceivedSvTimeNanos(11);
measurement.setReceivedSvTimeUncertaintyNanos(12);
measurement.setSnrInDb(13.0);
measurement.setState(14);
measurement.setSvid(15);
measurement.setTimeOffsetNanos(16.0);
}
private static void verifyTestValues(GnssMeasurement measurement) {
assertEquals(1.0, measurement.getAccumulatedDeltaRangeMeters());
assertEquals(2, measurement.getAccumulatedDeltaRangeState());
assertEquals(3.0, measurement.getAccumulatedDeltaRangeUncertaintyMeters());
assertEquals(4, measurement.getCarrierCycles());
assertEquals(5.0f, measurement.getCarrierFrequencyHz());
assertEquals(6.0, measurement.getCarrierPhase());
assertEquals(7.0, measurement.getCarrierPhaseUncertainty());
assertEquals(8.0, measurement.getCn0DbHz());
assertEquals(GnssStatus.CONSTELLATION_GALILEO, measurement.getConstellationType());
assertEquals(GnssMeasurement.MULTIPATH_INDICATOR_DETECTED,
measurement.getMultipathIndicator());
assertEquals(9.0, measurement.getPseudorangeRateMetersPerSecond());
assertEquals(10.0, measurement.getPseudorangeRateUncertaintyMetersPerSecond());
assertEquals(11, measurement.getReceivedSvTimeNanos());
assertEquals(12, measurement.getReceivedSvTimeUncertaintyNanos());
assertEquals(13.0, measurement.getSnrInDb());
assertEquals(14, measurement.getState());
assertEquals(15, measurement.getSvid());
assertEquals(16.0, measurement.getTimeOffsetNanos());
}
public void testWriteToParcel() {
GnssMeasurement measurement = new GnssMeasurement();
setTestValues(measurement);
Parcel parcel = Parcel.obtain();
measurement.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
GnssMeasurement newMeasurement = GnssMeasurement.CREATOR.createFromParcel(parcel);
verifyTestValues(newMeasurement);
}
public void testSet() {
GnssMeasurement measurement = new GnssMeasurement();
setTestValues(measurement);
GnssMeasurement newMeasurement = new GnssMeasurement();
newMeasurement.set(measurement);
verifyTestValues(newMeasurement);
}
public void testSetReset() {
GnssMeasurement measurement = new GnssMeasurement();
setTestValues(measurement);
assertTrue(measurement.hasCarrierCycles());
measurement.resetCarrierCycles();
assertFalse(measurement.hasCarrierCycles());
assertTrue(measurement.hasCarrierFrequencyHz());
measurement.resetCarrierFrequencyHz();
assertFalse(measurement.hasCarrierFrequencyHz());
assertTrue(measurement.hasCarrierPhase());
measurement.resetCarrierPhase();
assertFalse(measurement.hasCarrierPhase());
assertTrue(measurement.hasCarrierPhaseUncertainty());
measurement.resetCarrierPhaseUncertainty();
assertFalse(measurement.hasCarrierPhaseUncertainty());
assertTrue(measurement.hasSnrInDb());
measurement.resetSnrInDb();
assertFalse(measurement.hasSnrInDb());
}
}
| gpl-3.0 |
Glorf/Formoza | connection.hpp | 2302 | /***********************************************************************************
* Copyright (C) 2013 Michał Bień.
*
* This file is part of Formoza.
*
* Formoza 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.
*
* Formoza 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 Formoza; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************************/
#ifndef CONNECTION_HPP
#define CONNECTION_HPP
#include <QObject>
#include <QtNetwork/QTcpSocket>
#include <QHostInfo>
#include <QtNetwork/QHostAddress>
#include <QCryptographicHash>
#include <QPair>
class MainWindow;
struct GroupInfo
{
QString grupaOpis;
QVector<QString> users;
QVector<QString> ogloszenia;
QHash<QString, QString> tematyOgloszen;
QHash<QString, QString> tekstyOgloszen;
};
struct Wiadomosc
{
QString sender;
QString message;
QString date;
};
struct Powiadomienie
{
QString type;
QString message;
};
class Connection : public QObject
{
Q_OBJECT
public:
Connection(MainWindow *parent = 0);
~Connection();
void zaloguj(QString hostname);
QVector<QString> getDane();
QVector<QPair<QString, QString> > getGrupy();
GroupInfo getGrupaDane(QString grupa);
QVector<QString> getAllUsers();
QVector<Wiadomosc> getChatLog(QString person);
QVector<Powiadomienie> getFirstUpdate();
void sendMessage(QString receiver, QString message);
public slots:
void connectHost(QHostInfo hostinfo);
void setConnected();
void setDisconnected();
void updateMessage();
private:
MainWindow* parent;
QTcpSocket* socket;
QCryptographicHash *cryptPass;
QString sendCommand(QString cmd, QString arg);
};
#endif // CONNECTION_HPP
| gpl-3.0 |
dmitry-vlasov/mdl | src/mm/lexer/mm_lexer_Scaner.cpp | 3691 | /*****************************************************************************/
/* Project name: mm - decompiler from metamath to mdl */
/* File name: mm_lexer_Scaner.cpp */
/* Description: metamath scaner */
/* Copyright: (c) 2006-2009 Dmitri Vlasov */
/* Author: Dmitri Yurievich Vlasov, Novosibirsk, Russia */
/* Email: vlasov at academ.org */
/* URL: http://mathdevlanguage.sourceforge.net */
/* Modified by: */
/* License: GNU General Public License Version 3 */
/*****************************************************************************/
#pragma once
#include "lexer/mm_lexer.hpp"
namespace mm {
namespace lexer {
/****************************
* Public members
****************************/
Scaner :: Scaner (Source& source) :
source_ (source),
literalScaner_ (source_),
identificatorScaner_ (source_),
pathScaner_ (source_),
whitespaceScaner_ (source_),
inExpression_ (false),
inProof_ (false),
inInclude_ (false) {
}
Scaner :: ~ Scaner() {
}
Token :: Type
Scaner :: scan()
{
whitespaceScaner_.scan();
source_.startToken();
if (source_.getChar().isEOF()) {
return finalize (Token :: EOF_);
}
if (source_.getChar().getValue() != '$') {
if (inExpression_) {
return finalize (literalScaner_.scan());
} else if (inInclude_) {
return finalize (pathScaner_.scan());
} else {
return finalize (identificatorScaner_.scan());
}
}
++ source_;
return finalize (scanSingleChar());
}
inline Scaner :: Comments_&
Scaner :: comments() {
return whitespaceScaner_.comments();
}
inline void
Scaner :: scanComments() {
whitespaceScaner_.scan();
}
using manipulator :: endLine;
// nstd :: Object implementation
void
Scaner :: commitSuicide() {
delete this;
}
Size_t
Scaner :: getVolume() const {
return whitespaceScaner_.getVolume();
}
Size_t
Scaner :: getSizeOf() const {
return sizeof (Scaner);
}
void
Scaner :: show (nstd :: String<>&) const {
}
/****************************
* Private members
****************************/
Token :: Type
Scaner :: scanSingleChar()
{
switch (source_.getChar().getValue()) {
case 'c' :
inExpression_ = true;
++ source_;
return Token :: CONSTANT;
case 'v' :
inExpression_ = true;
++ source_;
return Token :: VARIABLE;
case 'f' :
inExpression_ = true;
++ source_;
return Token :: FLOATING;
case 'd' :
inExpression_ = true;
++ source_;
return Token :: DISJOINED;
case 'e' :
inExpression_ = true;
++ source_;
return Token :: ESSENTIAL;
case 'a' :
inExpression_ = true;
++ source_;
return Token :: AXIOMATIC;
case 'p' :
inExpression_ = true;
++ source_;
return Token :: PROVABLE;
case '.' :
inProof_ = false;
inExpression_ = false;
++ source_;
return Token :: END;
case '{' :
++ source_;
return Token :: BLOCK_BEGIN;
case '}' :
++ source_;
return Token :: BLOCK_END;
case '[' :
++ source_;
inInclude_ = true;
return Token :: INCLUSION_BEGIN;
case ']' :
++ source_;
inInclude_ = false;
return Token :: INCLUSION_END;
case '=' :
inExpression_ = false;
inProof_ = true;
++ source_;
return Token :: PROOF;
default :
++ source_;
return Token :: UNKNOWN;
}
}
Token :: Type
Scaner :: finalize (const Token :: Type type) {
source_.stopToken();
return type;
}
}
}
| gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/modules/sender/install/admin/sender_list_admin.php | 61 | Bitrix 16.5 Business Demo = 13c83a7c24759503e4a0482819a5ecd9
| gpl-3.0 |
hfut-xcsoft/badu-navigation | api/models/website.js | 975 | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const WebsiteSchema = new Schema({
name: String,
url: String,
icon_url: String,
description: String,
weights: { type: Number, default: 0 },
subcategory: ObjectId,
recommend_by: String,
__v: { type: Number, select: false }
});
WebsiteSchema.methods = {
create: function() {
return this.save();
},
update: function (obj) {
Object.assign(this, obj);
return this.save();
},
delete: function () {
return Website.remove({_id: this._id})
}
};
WebsiteSchema.statics = {
getByQuery: function (query, opt, field) {
opt = opt || {};
opt.sort = Object.assign({ subcategory: 1, weights: -1 }, opt && opt.sort);
return this.find(query, field, opt).exec();
},
getById: function (id) {
return this.findById(id).exec();
}
};
const Website = mongoose.model('Website', WebsiteSchema);
module.exports = Website;
| gpl-3.0 |
ftninformatika/bisis-v5 | bisis-model/src/main/java/com/ftninformatika/bisis/circ/CorporateMember.java | 947 | package com.ftninformatika.bisis.circ;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.Date;
/**
* Created by dboberic on 28/07/2017.
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(collection="coders.corporate_member")
public class CorporateMember implements Serializable {
@Id
private String _id;
private String library;
private String userId;
private String instName;
private Date signDate;
private String address;
private String city;
private Integer zip;
private String phone;
private String email;
private String fax;
private String secAddress;
private Integer secZip;
private String secCity;
private String secPhone;
private String contFirstName;
private String contLastName;
private String contEmail;
}
| gpl-3.0 |
Glain/FFTPatcher | FFTorgASM/Properties/AssemblyInfo.cs | 1387 | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "FFTorgASM" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "" )]
[assembly: AssemblyProduct( "FFTorgASM" )]
[assembly: AssemblyCopyright( "Copyright © Joe Davidson 2009" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "d4139c4f-69dc-43d6-b8b5-b2598780b9fc" )]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.494")]
[assembly: AssemblyFileVersion("1.0.0.494")]
| gpl-3.0 |
repology/repology | repology/repomgr.py | 7182 | # Copyright (C) 2016-2021 Dmitry Marakasov <[email protected]>
#
# This file is part of repology
#
# repology 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.
#
# repology 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 repology. If not, see <http://www.gnu.org/licenses/>.
import copy
import datetime
import json
from enum import Enum
from typing import Any, Collection, Iterable, Optional, TYPE_CHECKING, overload
if TYPE_CHECKING:
from dataclasses import dataclass
else:
from pydantic.dataclasses import dataclass
from pydantic.json import pydantic_encoder
from repology.package import LinkType
from repology.yamlloader import YamlConfig
RepositoryNameList = Optional[Collection[str]] # XXX: can't use |-union yet, see https://github.com/python/mypy/issues/11280
def _subst_source_recursively(container: dict[str, Any] | list[Any], name: str) -> None:
key_iter: Iterable[Any]
if isinstance(container, list):
key_iter = range(len(container))
elif isinstance(container, dict):
key_iter = container.keys()
else:
return
for key in key_iter:
if isinstance(container[key], str):
container[key] = container[key].replace('{source}', name)
elif isinstance(container[key], list) or isinstance(container[key], dict):
_subst_source_recursively(container[key], name)
@overload
def _parse_duration(arg: str | int) -> datetime.timedelta:
pass
@overload
def _parse_duration(arg: None) -> None:
pass
def _parse_duration(arg: str | int | None) -> datetime.timedelta | None:
if arg is None:
return None
if isinstance(arg, int):
return datetime.timedelta(seconds=arg)
elif arg.endswith('m'):
return datetime.timedelta(minutes=int(arg[:-1]))
elif arg.endswith('h'):
return datetime.timedelta(hours=int(arg[:-1]))
elif arg.endswith('d'):
return datetime.timedelta(days=int(arg[:-1]))
else:
return datetime.timedelta(seconds=int(arg))
def _listify(arg: Any) -> list[Any]:
if not isinstance(arg, list):
return [arg]
else:
return arg
@dataclass
class PackageLink:
type: int # noqa
url: str
@dataclass
class Source:
name: str
subrepo: Optional[str]
fetcher: dict[str, Any]
parser: dict[str, Any]
packagelinks: list[PackageLink]
class RepositoryType(str, Enum):
REPOSITORY = 'repository'
SITE = 'site'
MODULES = 'modules'
@dataclass
class Repository:
name: str
sortname: str
singular: str
type: RepositoryType # noqa
desc: str
statsgroup: str
family: str
ruleset: list[str]
color: Optional[str]
valid_till: Optional[datetime.date]
default_maintainer: Optional[str]
update_period: datetime.timedelta
minpackages: int
shadow: bool
incomplete: bool
repolinks: list[Any]
packagelinks: list[PackageLink]
groups: list[str]
sources: list[Source]
class RepositoryManager:
_repositories: list[Repository]
_repo_by_name: dict[str, Repository]
def __init__(self, repositories_config: YamlConfig) -> None:
self._repositories = []
self._repo_by_name = {}
# process source loops
for repodata in repositories_config.get_items():
extra_groups = set()
sources = []
for sourcedata in repodata['sources']:
if sourcedata.get('disabled', False):
continue
for name in _listify(sourcedata['name']):
# if there are multiple names, clone source data for each of them
processed_sourcedata = copy.deepcopy(sourcedata)
_subst_source_recursively(processed_sourcedata, name)
sources.append(
Source(
name=name,
subrepo=processed_sourcedata.get('subrepo'),
fetcher=processed_sourcedata['fetcher'],
parser=processed_sourcedata['parser'],
packagelinks=[PackageLink(type=LinkType.from_string(linkdata['type']), url=linkdata['url']) for linkdata in processed_sourcedata.get('packagelinks', [])],
)
)
extra_groups.add(sourcedata['fetcher']['class'])
extra_groups.add(sourcedata['parser']['class'])
repo = Repository(
name=repodata['name'],
sortname=repodata.get('sortname', repodata['name']),
singular=repodata.get('singular', repodata['desc'] + ' package'),
type=repodata.get('type', 'repository'),
desc=repodata['desc'],
statsgroup=repodata.get('statsgroup', repodata['desc']),
family=repodata['family'],
ruleset=_listify(repodata.get('ruleset', repodata['family'])),
color=repodata.get('color'),
valid_till=repodata.get('valid_till'),
default_maintainer=repodata.get('default_maintainer'),
update_period=_parse_duration(repodata.get('update_period', 600)),
minpackages=repodata.get('minpackages', 0),
shadow=repodata.get('shadow', False),
incomplete=repodata.get('incomplete', False),
repolinks=repodata.get('repolinks', []),
packagelinks=[PackageLink(type=LinkType.from_string(linkdata['type']), url=linkdata['url']) for linkdata in repodata.get('packagelinks', [])],
groups=repodata.get('groups', []) + list(extra_groups),
sources=sources,
)
self._repositories.append(repo)
self._repo_by_name[repo.name] = repo
self._repositories = sorted(self._repositories, key=lambda repo: repo.sortname)
def get_repository(self, name: str) -> Repository:
return self._repo_by_name[name]
def get_repositories(self, names: RepositoryNameList = None) -> list[Repository]:
if names is None:
return []
filtered_repositories = []
for repository in self._repositories:
for name in names:
if name == repository.name or name in repository.groups:
filtered_repositories.append(repository)
break
return filtered_repositories
def get_names(self, names: RepositoryNameList = None) -> list[str]:
return [repository.name for repository in self.get_repositories(names)]
def get_repository_json(self, name: str) -> str:
return json.dumps(self.get_repository(name), default=pydantic_encoder)
| gpl-3.0 |
padelt/temper-python | temperusb/snmp.py | 3612 | # encoding: utf-8
#
# Run snmp_temper.py as a pass-persist module for NetSNMP.
# See README.md for instructions.
#
# Copyright 2012-2020 Philipp Adelt <[email protected]>
#
# This code is licensed under the GNU public license (GPL). See LICENSE.md for details.
import os
import sys
import syslog
import threading
import snmp_passpersist as snmp
from temperusb.temper import TemperHandler, TemperDevice
ERROR_TEMPERATURE = 9999
def _unbuffered_handle(fd):
return os.fdopen(fd.fileno(), 'w', 0)
class LogWriter():
def __init__(self, ident='temper-python', facility=syslog.LOG_DAEMON):
syslog.openlog(ident, 0, facility)
def write_log(self, message, prio=syslog.LOG_INFO):
syslog.syslog(prio, message)
class Updater():
def __init__(self, pp, logger, testmode=False):
self.logger = logger
self.pp = pp
self.testmode = testmode
self.usb_lock = threading.Lock() # used to stop reinitialization interfering with update-thread
self._initialize()
def _initialize(self):
with self.usb_lock:
try:
self.th = TemperHandler()
self.devs = self.th.get_devices()
self.logger.write_log('Found %i thermometer devices.' % len(self.devs))
for i, d in enumerate(self.devs):
self.logger.write_log('Initial temperature of device #%i: %0.1f degree celsius' % (i, d.get_temperature()))
except Exception as e:
self.logger.write_log('Exception while initializing: %s' % str(e))
def _reinitialize(self):
# Tries to close all known devices and starts over.
self.logger.write_log('Reinitializing devices')
with self.usb_lock:
for i,d in enumerate(self.devs):
try:
d.close()
except Exception as e:
self.logger.write_log('Exception closing device #%i: %s' % (i, str(e)))
self._initialize()
def update(self):
if self.testmode:
# APC Internal/Battery Temperature
self.pp.add_int('318.1.1.1.2.2.2.0', 99)
# Cisco devices temperature OIDs
self.pp.add_int('9.9.13.1.3.1.3.1', 97)
self.pp.add_int('9.9.13.1.3.1.3.2', 98)
self.pp.add_int('9.9.13.1.3.1.3.3', 99)
else:
try:
with self.usb_lock:
temperatures = [d.get_temperature() for d in self.devs]
self.pp.add_int('318.1.1.1.2.2.2.0', int(max(temperatures)))
for i, temperature in enumerate(temperatures[:3]): # use max. first 3 devices
self.pp.add_int('9.9.13.1.3.1.3.%i' % (i+1), int(temperature))
except Exception as e:
self.logger.write_log('Exception while updating data: %s' % str(e))
# Report an exceptionally large temperature to set off all alarms.
# snmp_passpersist does not expose an API to remove an OID.
for oid in ('318.1.1.1.2.2.2.0', '9.9.13.1.3.1.3.1', '9.9.13.1.3.1.3.2', '9.9.13.1.3.1.3.3'):
self.pp.add_int(oid, ERROR_TEMPERATURE)
self.logger.write_log('Starting reinitialize after error on update')
self._reinitialize()
def main():
sys.stdout = _unbuffered_handle(sys.stdout)
pp = snmp.PassPersist(".1.3.6.1.4.1")
logger = LogWriter()
upd = Updater(pp, logger, testmode=('--testmode' in sys.argv))
pp.start(upd.update, 5) # update every 5s
if __name__ == '__main__':
main()
| gpl-3.0 |
FireBladeNooT/Medusa_1_6 | lib/github/tests/NamedUser.py | 10311 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> #
# Copyright 2013 Vincent Jacques <[email protected]> #
# #
# This file is part of PyGithub. #
# http://pygithub.github.io/PyGithub/v1/index.html #
# #
# PyGithub 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. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import Framework
import github
import datetime
class NamedUser(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.user = self.g.get_user("jacquev6")
def testAttributesOfOtherUser(self):
self.user = self.g.get_user("nvie")
self.assertEqual(self.user.avatar_url, "https://secure.gravatar.com/avatar/c5a7f21b46df698f3db31c37ed0cf55a?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png")
self.assertEqual(self.user.bio, None)
self.assertEqual(self.user.blog, "http://nvie.com")
self.assertEqual(self.user.collaborators, None)
self.assertEqual(self.user.company, "3rd Cloud")
self.assertEqual(self.user.created_at, datetime.datetime(2009, 5, 12, 21, 19, 38))
self.assertEqual(self.user.disk_usage, None)
self.assertEqual(self.user.email, "[email protected]")
self.assertEqual(self.user.followers, 296)
self.assertEqual(self.user.following, 41)
self.assertEqual(self.user.gravatar_id, "c5a7f21b46df698f3db31c37ed0cf55a")
self.assertFalse(self.user.hireable)
self.assertEqual(self.user.html_url, "https://github.com/nvie")
self.assertEqual(self.user.id, 83844)
self.assertEqual(self.user.location, "Netherlands")
self.assertEqual(self.user.login, "nvie")
self.assertEqual(self.user.name, "Vincent Driessen")
self.assertEqual(self.user.owned_private_repos, None)
self.assertEqual(self.user.plan, None)
self.assertEqual(self.user.private_gists, None)
self.assertEqual(self.user.public_gists, 16)
self.assertEqual(self.user.public_repos, 61)
self.assertEqual(self.user.total_private_repos, None)
self.assertEqual(self.user.type, "User")
self.assertEqual(self.user.url, "https://api.github.com/users/nvie")
# test __repr__() based on this attributes
self.assertEqual(self.user.__repr__(), 'NamedUser(login="nvie")')
def testAttributesOfSelf(self):
self.assertEqual(self.user.avatar_url, "https://secure.gravatar.com/avatar/b68de5ae38616c296fa345d2b9df2225?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png")
self.assertEqual(self.user.bio, "")
self.assertEqual(self.user.blog, "http://vincent-jacques.net")
self.assertEqual(self.user.collaborators, 0)
self.assertEqual(self.user.company, "Criteo")
self.assertEqual(self.user.created_at, datetime.datetime(2010, 7, 9, 6, 10, 6))
self.assertEqual(self.user.disk_usage, 17080)
self.assertEqual(self.user.email, "[email protected]")
self.assertEqual(self.user.followers, 13)
self.assertEqual(self.user.following, 24)
self.assertEqual(self.user.gravatar_id, "b68de5ae38616c296fa345d2b9df2225")
self.assertFalse(self.user.hireable)
self.assertEqual(self.user.html_url, "https://github.com/jacquev6")
self.assertEqual(self.user.id, 327146)
self.assertEqual(self.user.location, "Paris, France")
self.assertEqual(self.user.login, "jacquev6")
self.assertEqual(self.user.name, "Vincent Jacques")
self.assertEqual(self.user.owned_private_repos, 5)
self.assertEqual(self.user.plan.name, "micro")
self.assertEqual(self.user.plan.collaborators, 1)
self.assertEqual(self.user.plan.space, 614400)
self.assertEqual(self.user.plan.private_repos, 5)
self.assertEqual(self.user.private_gists, 5)
self.assertEqual(self.user.public_gists, 2)
self.assertEqual(self.user.public_repos, 11)
self.assertEqual(self.user.total_private_repos, 5)
self.assertEqual(self.user.type, "User")
self.assertEqual(self.user.url, "https://api.github.com/users/jacquev6")
# test __repr__() based on this attributes
self.assertEqual(self.user.__repr__(), 'NamedUser(login="jacquev6")')
def testGetGists(self):
self.assertListKeyEqual(self.user.get_gists(), lambda g: g.description, ["Gist created by PyGithub", "FairThreadPoolPool.cpp", "How to error 500 Github API v3, as requested by Rick (GitHub Staff)", "Cadfael: order of episodes in French DVD edition"])
def testGetFollowers(self):
self.assertListKeyEqual(self.user.get_followers(), lambda f: f.login, ["jnorthrup", "brugidou", "regisb", "walidk", "afzalkhan", "sdanzan", "vineus", "gturri", "fjardon", "cjuniet", "jardon-u", "kamaradclimber", "L42y"])
def testGetFollowing(self):
self.assertListKeyEqual(self.user.get_following(), lambda f: f.login, ["nvie", "schacon", "jamis", "chad", "unclebob", "dabrahams", "jnorthrup", "brugidou", "regisb", "walidk", "tanzilli", "fjardon", "r3c", "sdanzan", "vineus", "cjuniet", "gturri", "ant9000", "asquini", "claudyus", "jardon-u", "s-bernard", "kamaradclimber", "Lyloa"])
def testHasInFollowing(self):
nvie = self.g.get_user("nvie")
self.assertTrue(self.user.has_in_following(nvie))
def testGetOrgs(self):
self.assertListKeyEqual(self.user.get_orgs(), lambda o: o.login, ["BeaverSoftware"])
def testGetRepo(self):
self.assertEqual(self.user.get_repo("PyGithub").description, "Python library implementing the full Github API v3")
def testGetRepos(self):
self.assertListKeyEqual(self.user.get_repos(), lambda r: r.name, ["TestPyGithub", "django", "PyGithub", "developer.github.com", "acme-public-website", "C4Planner", "DrawTurksHead", "DrawSyntax", "QuadProgMm", "Boost.HierarchicalEnum", "ViDE"])
def testGetReposWithType(self):
self.assertListKeyEqual(self.user.get_repos("owner"), lambda r: r.name, ["django", "PyGithub", "developer.github.com", "acme-public-website", "C4Planner", "DrawTurksHead", "DrawSyntax", "QuadProgMm", "Boost.HierarchicalEnum", "ViDE"])
def testGetWatched(self):
self.assertListKeyEqual(self.user.get_watched(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "PyGithub", "django", "django", "TestPyGithub"])
def testGetStarred(self):
self.assertListKeyEqual(self.user.get_starred(), lambda r: r.name, ["git", "boost.php", "capistrano", "boost.perl", "git-subtree", "git-hg", "homebrew", "celtic_knot", "twisted-intro", "markup", "hub", "gitflow", "murder", "boto", "agit", "d3", "pygit2", "git-pulls", "django_mathlatex", "scrumblr", "developer.github.com", "python-github3", "PlantUML", "bootstrap", "drawnby", "django-socketio", "django-realtime", "playground", "BozoCrack", "FatherBeaver", "amaunet", "django", "django", "moviePlanning", "folly"])
def testGetSubscriptions(self):
self.assertListKeyEqual(self.user.get_subscriptions(), lambda r: r.name, ["ViDE", "Boost.HierarchicalEnum", "QuadProgMm", "DrawSyntax", "DrawTurksHead", "PrivateStuff", "vincent-jacques.net", "Hacking", "C4Planner", "developer.github.com", "PyGithub", "PyGithub", "django", "CinePlanning", "PyGithub", "PyGithub", "PyGithub", "IpMap", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub", "PyGithub"])
def testGetEvents(self):
self.assertListKeyBegin(self.user.get_events(), lambda e: e.type, ["GistEvent", "IssueCommentEvent", "PushEvent", "IssuesEvent"])
def testGetPublicEvents(self):
self.assertListKeyBegin(self.user.get_public_events(), lambda e: e.type, ["PushEvent", "CreateEvent", "GistEvent", "IssuesEvent"])
def testGetPublicReceivedEvents(self):
self.assertListKeyBegin(self.user.get_public_received_events(), lambda e: e.type, ["IssueCommentEvent", "IssueCommentEvent", "IssueCommentEvent", "IssueCommentEvent"])
def testGetReceivedEvents(self):
self.assertListKeyBegin(self.user.get_received_events(), lambda e: e.type, ["IssueCommentEvent", "IssueCommentEvent", "IssueCommentEvent", "IssueCommentEvent"])
def testGetKeys(self):
self.assertListKeyEqual(self.user.get_keys(), lambda k: k.id, [3557894, 3791954, 3937333, 4051357, 4051492])
| gpl-3.0 |
bozanfaruk/AnaJavaticaRep | AnaJavatica/src/anajavatica/pattern/structural/flyweight/Water.java | 123 | package anajavatica.pattern.structural.flyweight;
@SuppressWarnings("javadoc")
public class Water extends Obstacle {
} | gpl-3.0 |
morpheby/ist303-miye | models/SpaRes.py | 1088 | class SpaRes:
def __init__(self, personID, date, time, treatment_type, duration):
self.person = personID
self.date = date
self.time = time
self.treatment_type = treatment_type
self.duration = duration
def checkSpaAvailability(date, time, type):
pass
def makeSpaRes(clientID, date, time, treatment_type):
SpaRes(clientID, date, time, treatment_type)
def print_avail_sched():
pass
def print_price_menu():
pass
#SPA STATIC VARS
#available time slots
timeslots_military = [(x + 5)/10 for x in range(75,200,5)]
timeslots = [] #human readable list of time slots, i.e. 3:00 PM instead of 14
for timeval in timeslots_military:
hour_min = divmod(timeval,1)
if timeval < 12:
ampm = 'AM'
hour = int(hour_min[0])
elif timeval == 12 or timeval == 12.5:
ampm = 'PM'
hour = int(hour_min[0])
else:
ampm = 'PM'
hour = int(hour_min[0]-12)
min = int(hour_min[1]*60)
min = str(min)
if min == '0':
min = '00'
timeslots.append(str(hour) + ":" + min + " " + ampm)
| gpl-3.0 |
CBegau/AtomViewer | src/crystalStructures/L12_Ni3AlStructure.java | 9351 | // Part of AtomViewer: AtomViewer is a tool to display and analyse
// atomistic simulations
//
// Copyright (C) 2013 ICAMS, Ruhr-Universität Bochum
//
// AtomViewer 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.
//
// AtomViewer 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 AtomViewer. If not, see <http://www.gnu.org/licenses/>
package crystalStructures;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import common.Tupel;
import common.Vec3;
import gui.PrimitiveProperty.BooleanProperty;
import model.Atom;
import model.AtomData;
import model.NearestNeighborBuilder;
public class L12_Ni3AlStructure extends FCCStructure{
private static final float[][] bondsAngleClasses;
static protected BooleanProperty flipNiAlelementIDConventionProperty =
new BooleanProperty("NiAlconvention", "Even element IDs denote Al, odd ones Ni.",
"<html>If not selected even element IDs denote Ni, odd ones Al.</html>",
false);
static{
float[] tol_l = new float[]{0f, 7f, 6f, 5f, 4f, 3f};
float[] tol_u = new float[]{13f, 10f, 6f, 5f, 4f, 3f};
float[] angles = new float[]{180f, 146.5f, 120f, 109.5f, 90f, 60f};
bondsAngleClasses = new float[6][2];
// Lower bonds
bondsAngleClasses[0][0] = -1.001f; //Should be exactly -1, but there might be rounding errors
bondsAngleClasses[1][0] = (float)Math.cos((angles[1]+tol_l[1])*Math.PI/180.);
bondsAngleClasses[2][0] = (float)Math.cos((angles[2]+tol_l[2])*Math.PI/180.);
bondsAngleClasses[3][0] = (float)Math.cos((angles[3]+tol_l[3])*Math.PI/180.);
bondsAngleClasses[4][0] = (float)Math.cos((angles[4]+tol_l[4])*Math.PI/180.);
bondsAngleClasses[5][0] = (float)Math.cos((angles[5]+tol_l[5])*Math.PI/180.);
//Upper bonds
bondsAngleClasses[0][1] = (float)Math.cos((angles[0]-tol_u[0])*Math.PI/180.);
bondsAngleClasses[1][1] = (float)Math.cos((angles[1]-tol_u[1])*Math.PI/180.);
bondsAngleClasses[2][1] = (float)Math.cos((angles[2]-tol_u[2])*Math.PI/180.);
bondsAngleClasses[3][1] = (float)Math.cos((angles[3]-tol_u[3])*Math.PI/180.);
bondsAngleClasses[4][1] = (float)Math.cos((angles[4]-tol_u[4])*Math.PI/180.);
bondsAngleClasses[5][1] = (float)Math.cos((angles[5]-tol_u[5])*Math.PI/180.);
}
public L12_Ni3AlStructure() {
super();
crystalProperties.add(flipNiAlelementIDConventionProperty);
}
@Override
protected CrystalStructure deriveNewInstance() {
return new L12_Ni3AlStructure();
}
@Override
protected String getIDName() {
return "Ni3Al";
}
public float getDefaultSkeletonizerRBVThreshold(){
return 0.25f;
}
@Override
public void identifyDefectAtoms(List<Atom> atoms, NearestNeighborBuilder<Atom> nnb,
int start, int end, CyclicBarrier barrier) {
for (int i=start; i<end; i++){
if (Thread.interrupted()) return;
Atom a = atoms.get(i);
a.setType(identifyAtomType(a, nnb));
}
try {
barrier.await();
} catch (Exception e) {
if (Thread.interrupted()) return;
}
float tol = (float)(Math.cos(167)*Math.PI/180.);
for (int i=start; i<end; i++){
if (Thread.interrupted()) return;
Atom a = atoms.get(i);
if (a.getType() == 0){
int countPseudoTwin = 0;
int pairs = 0;
ArrayList<Atom> nei = nnb.getNeigh(a);
for (int j=0; j<nei.size(); j++){
if (nei.get(j).getType() == 8){
countPseudoTwin++;
Vec3 u = nei.get(j).subClone(a);
boolean pairFound = false;
for (int k=0; k<nei.size(); k++){
if (nei.get(k).getType() == 8){
Vec3 v = nei.get(j).subClone(a);
if (u.getAngle(v)>tol){
pairFound = true;
break;
}
}
}
if (pairFound) pairs++;
}
}
if (pairs>=2 && countPseudoTwin >= 4) a.setType(8);
}
}
}
@Override
public int identifyAtomType(Atom atom, NearestNeighborBuilder<Atom> nnb) {
ArrayList<Tupel<Atom, Vec3>> d_cont = nnb.getNeighAndNeighVec(atom);
boolean flipNiAlConvention = flipNiAlelementIDConventionProperty.getValue();
/*
* type=0: L12
* type=1: APB
* type=2: CSF
* type=3: SISF
* type=4: 12 neighbors, defect
* type=5: 10-11 neighbors
* type=6: >=13 neighbors
* type=7: <10 neighbors (surface)
* type=8: pseudoTwin
*/
if (d_cont.size() < 10) return 7;
else if (d_cont.size() < 11) return 5;
else if (d_cont.size() > 13) return 6;
else {
//There are three type of bond within the binary system with an atom of type A in the middle of the bond
//type 0: B-A-B (both neighbor the same, but other type)
//type 1: A-A-B (one neighbor of each element)
//type 2: A-A-A (bond consists of only one type)
int bonds[][] = new int[bondsAngleClasses.length][3];
//Element of the central atom in the bond pair
int type_atom = atom.getElement()%2;
if (flipNiAlConvention)
type_atom = 1-type_atom;
for (int i = 0; i < d_cont.size(); i++) {
//Element of the first bond atom
int type_i = d_cont.get(i).o1.getElement()%2;
if (flipNiAlConvention)
type_i = 1-type_i;
Vec3 v = d_cont.get(i).o2;
float v_length = v.getLength();
for (int j = 0; j < i; j++) {
//Element of the second bond atom
int type_j = d_cont.get(j).o1.getElement()%2;
if (flipNiAlConvention)
type_j = 1-type_j;
int bondType = 0;
//Identify the type of bond
if (type_j!=type_i) bondType = 1;
else {
if (type_i == type_atom) bondType = 2;
else bondType = 0;
}
Vec3 u = d_cont.get(j).o2;
float u_length = u.getLength();
float a = v.dot(u) / (v_length*u_length);
for (int k=0; k<bondsAngleClasses.length; k++){
if (a>=bondsAngleClasses[k][0] && a<=bondsAngleClasses[k][1]) bonds[k][bondType]++;
}
}
}
//type 0: B-A-B (both neighbor the same, but other type)
//type 1: A-A-B (one neighbor of each element)
//type 2: A-A-A (bond consists of only one type)
//Nickel
if (type_atom == 0){
if (bonds[0][0] == 2 && bonds[0][2] == 4) return 0; //L12
if (bonds[0][2] == 3 && bonds[0][1] == 2 && bonds[0][0] == 1) return 1; //APB
if (bonds[0][2] == 4 && bonds[0][1] == 1 && bonds[0][0] == 1) return 1; //APB
if (bonds[0][2] == 2 && bonds[0][0] == 1 && bonds[1][2] == 3 && bonds[1][1] == 2 && bonds[1][0] == 1) return 2; //CSF
if (bonds[0][2] == 2 && bonds[0][0] == 1 && bonds[1][2] == 4 && bonds[1][1] == 2) return 2; //CSF
if (bonds[0][2] == 2 && bonds[0][0] == 1 && bonds[1][2] == 2 && bonds[1][1] == 4) return 3; //SISF
if (bonds[0][2] == 2 && bonds[0][0] == 1 && bonds[1][2]+bonds[1][1]+bonds[1][0] >= 3) return 2; //CSF
if (bonds[0][0] == 1 && bonds[0][2] == 5 && bonds[1][0] == 0) return 8; //Pseudo-twin
} else { //Aluminum
if (bonds[0][0] == 6) return 0; //L12
if (bonds[0][0] == 5 && bonds[0][1] == 1) return 1; //APB
if (bonds[0][0] == 3 && bonds[1][1] == 2 && bonds[1][0] == 4) return 2; //CSF
if (bonds[0][0] == 3 && bonds[1][0] == 6) return 3; //SISF
if (bonds[0][0] == 3 && bonds[1][2]+bonds[1][1]+bonds[1][0] >=3 ) return 2; //CSF
if (bonds[0][2] == 1 && bonds[0][0] == 5 && bonds[1][2] == 0) return 8; //Pseudo-twin
}
if (d_cont.size() < 12) return 5;
else if (d_cont.size() > 12) return 6;
else return 4;
}
}
@Override
public String getNameForType(int i) {
switch (i) {
case 0: return "L12";
case 1: return "APB";
case 2: return "CSF";
case 3: return "SISF";
case 4: return "12 neigbors, defect";
case 5: return "10-11 neighbors";
case 6: return ">=13 neighbors";
case 7: return "<10 neighbors";
case 8: return "PseudoTwin";
default: return "unknown";
}
}
@Override
public boolean hasMultipleStackingFaultTypes(){
return true;
}
@Override
public List<Atom> getStackingFaultAtoms(AtomData data){
List<Atom> sfAtoms = new ArrayList<Atom>();
for (int i=0; i<data.getAtoms().size(); i++){
Atom a = data.getAtoms().get(i);
if (a.getType() >= 1 && a.getType() <= 3 && a.getGrain() != Atom.IGNORED_GRAIN)
sfAtoms.add(a);
}
return sfAtoms;
}
@Override
public int getSurfaceType() {
return 7;
}
@Override
public int getDefaultType(){
return 0;
}
@Override
public int getNumberOfTypes() {
return 9;
}
@Override
public int getNumberOfElements(){
return 2;
}
@Override
public float[] getDefaultSphereSizeScalings(){
if (!flipNiAlelementIDConventionProperty.getValue())
return new float[]{1f, 0.79f};
else return new float[]{0.79f, 1f};
}
@Override
public String[] getNamesOfElements(){
if (!flipNiAlelementIDConventionProperty.getValue())
return new String[]{"Ni", "Al"};
else return new String[]{"Al", "Ni"};
}
@Override
public float getRBVIntegrationRadius() {
return 0.707107f*latticeConstant*1.1f;
}
@Override
public boolean isRBVToBeCalculated(Atom a) {
return (a.getType() != 0 && a.getType() != 7);
}
}
| gpl-3.0 |
marvisan/HadesFIX | Model/src/main/java/net/hades/fix/message/group/DistribInstsGroup.java | 13893 | /*
* Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved.
* Use is subject to license terms.
*/
/*
* DistribInstsGroup.java
*
* $Id: DistribInstsGroup.java,v 1.1 2011-10-27 09:16:59 vrotaru Exp $
*/
package net.hades.fix.message.group;
import net.hades.fix.message.anno.FIXVersion;
import net.hades.fix.message.struct.Tag;
import net.hades.fix.message.type.DistribPaymentMethod;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import net.hades.fix.message.anno.TagNumRef;
import net.hades.fix.message.FragmentContext;
import net.hades.fix.message.exception.BadFormatMsgException;
import net.hades.fix.message.exception.TagNotPresentException;
import net.hades.fix.message.type.Currency;
import net.hades.fix.message.type.SessionRejectReason;
import net.hades.fix.message.type.TagNum;
import net.hades.fix.message.util.TagEncoder;
/**
* Distribution instruction group.
*
* @author <a href="mailto:[email protected]">Support Team</a>
* @version $Revision: 1.1 $
* @created 05/04/2009, 11:10:10 AM
*/
@XmlAccessorType(XmlAccessType.NONE)
public abstract class DistribInstsGroup extends Group {
// <editor-fold defaultstate="collapsed" desc="Constants">
private static final long serialVersionUID = 1L;
protected static final Set<Integer> TAGS = new HashSet<Integer>(Arrays.asList(new Integer[] {
TagNum.DistribPaymentMethod.getValue(),
TagNum.DistribPercentage.getValue(),
TagNum.CashDistribCurr.getValue(),
TagNum.CashDistribAgentName.getValue(),
TagNum.CashDistribAgentCode.getValue(),
TagNum.CashDistribAgentAcctNumber.getValue(),
TagNum.CashDistribPayRef.getValue(),
TagNum.CashDistribAgentAcctName.getValue()
}));
protected static final Set<Integer> START_COMP_TAGS = null;
protected static final Set<Integer> START_DATA_TAGS = null;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Static Block">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Attributes">
// ACCESSORS
//////////////////////////////////////////
/**
* TagNum = 477. Starting with 4.3 version.
*/
protected DistribPaymentMethod distribPaymentMethod;
/**
* TagNum = 512. Starting with 4.3 version.
*/
protected Double distribPercentage;
/**
* TagNum = 478. Starting with 4.3 version.
*/
protected Currency cashDistribCurr;
/**
* TagNum = 498. Starting with 4.3 version.
*/
protected String cashDistribAgentName;
/**
* TagNum = 499. Starting with 4.3 version.
*/
protected String cashDistribAgentCode;
/**
* TagNum = 500. Starting with 4.3 version.
*/
protected String cashDistribAgentAcctNumber;
/**
* TagNum = 501. Starting with 4.3 version.
*/
protected String cashDistribPayRef;
/**
* TagNum = 502. Starting with 4.3 version.
*/
protected String cashDistribAgentAcctName;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Constructors">
public DistribInstsGroup() {
}
public DistribInstsGroup(FragmentContext context) {
super(context);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Public Methods">
@Override
public Set<Integer> getFragmentTags() {
return TAGS;
}
// ACCESSORS
//////////////////////////////////////////
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.DistribPaymentMethod)
public DistribPaymentMethod getDistribPaymentMethod() {
return distribPaymentMethod;
}
/**
* Message field setter.
* @param distribPaymentMethod field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.DistribPaymentMethod)
public void setDistribPaymentMethod(DistribPaymentMethod distribPaymentMethod) {
this.distribPaymentMethod = distribPaymentMethod;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.DistribPercentage)
public Double getDistribPercentage() {
return distribPercentage;
}
/**
* Message field setter.
* @param distribPercentage field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.DistribPercentage)
public void setDistribPercentage(Double distribPercentage) {
this.distribPercentage = distribPercentage;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribCurr)
public Currency getCashDistribCurr() {
return cashDistribCurr;
}
/**
* Message field setter.
* @param cashDistribCurr field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribCurr)
public void setCashDistribCurr(Currency cashDistribCurr) {
this.cashDistribCurr = cashDistribCurr;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentName)
public String getCashDistribAgentName() {
return cashDistribAgentName;
}
/**
* Message field setter.
* @param cashDistribAgentName field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentName)
public void setCashDistribAgentName(String cashDistribAgentName) {
this.cashDistribAgentName = cashDistribAgentName;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentCode)
public String getCashDistribAgentCode() {
return cashDistribAgentCode;
}
/**
* Message field setter.
* @param cashDistribAgentCode field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentCode)
public void setCashDistribAgentCode(String cashDistribAgentCode) {
this.cashDistribAgentCode = cashDistribAgentCode;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentAcctNumber)
public String getCashDistribAgentAcctNumber() {
return cashDistribAgentAcctNumber;
}
/**
* Message field setter.
* @param cashDistribAgentAcctNumber field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentAcctNumber)
public void setCashDistribAgentAcctNumber(String cashDistribAgentAcctNumber) {
this.cashDistribAgentAcctNumber = cashDistribAgentAcctNumber;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribPayRef)
public String getCashDistribPayRef() {
return cashDistribPayRef;
}
/**
* Message field setter.
* @param cashDistribPayRef field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribPayRef)
public void setCashDistribPayRef(String cashDistribPayRef) {
this.cashDistribPayRef = cashDistribPayRef;
}
/**
* Message field getter.
* @return field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentAcctName)
public String getCashDistribAgentAcctName() {
return cashDistribAgentAcctName;
}
/**
* Message field setter.
* @param cashDistribAgentAcctName field value
*/
@FIXVersion(introduced="4.3")
@TagNumRef(tagNum=TagNum.CashDistribAgentAcctName)
public void setCashDistribAgentAcctName(String cashDistribAgentAcctName) {
this.cashDistribAgentAcctName = cashDistribAgentAcctName;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Protected Methods">
@Override
protected int getFirstTag() {
return TagNum.DistribPaymentMethod.getValue();
}
@Override
protected void validateRequiredTags() throws TagNotPresentException {
StringBuilder errorMsg = new StringBuilder("Tag value(s) for");
boolean hasMissingTag = false;
if (distribPaymentMethod == null) {
errorMsg.append(" [DistribPaymentMethod]");
hasMissingTag = true;
}
errorMsg.append(" is missing.");
if (hasMissingTag) {
throw new TagNotPresentException(errorMsg.toString());
}
}
@Override
protected byte[] encodeFragmentAll() throws TagNotPresentException, BadFormatMsgException {
if (validateRequired) {
validateRequiredTags();
}
byte[] result = new byte[0];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
try {
if (distribPaymentMethod != null) {
TagEncoder.encode(bao, TagNum.DistribPaymentMethod, distribPaymentMethod.getValue());
}
TagEncoder.encode(bao, TagNum.DistribPercentage, distribPercentage);
if (cashDistribCurr != null) {
TagEncoder.encode(bao, TagNum.CashDistribCurr, cashDistribCurr.getValue());
}
TagEncoder.encode(bao, TagNum.CashDistribAgentName, cashDistribAgentName);
TagEncoder.encode(bao, TagNum.CashDistribAgentCode, cashDistribAgentCode);
TagEncoder.encode(bao, TagNum.CashDistribAgentAcctNumber, cashDistribAgentAcctNumber);
TagEncoder.encode(bao, TagNum.CashDistribPayRef, cashDistribPayRef);
TagEncoder.encode(bao, TagNum.CashDistribAgentAcctName, cashDistribAgentAcctName);
result = bao.toByteArray();
} catch (IOException ex) {
String error = "Error writing to the byte array.";
LOGGER.log(Level.SEVERE, "{0} Error was : {1}", new Object[] { error, ex.toString() });
throw new BadFormatMsgException(error, ex);
}
return result;
}
@Override
protected byte[] encodeFragmentSecured(boolean secured) throws TagNotPresentException, BadFormatMsgException {
if (secured) {
return new byte[0];
} else {
return encodeFragmentAll();
}
}
@Override
protected void setFragmentTagValue(Tag tag) throws BadFormatMsgException {
TagNum tagNum = TagNum.fromString(tag.tagNum);
switch (tagNum) {
case DistribPaymentMethod:
distribPaymentMethod = DistribPaymentMethod.valueFor(Integer.valueOf(new String(tag.value, sessionCharset)));
break;
case DistribPercentage:
distribPercentage = new Double(new String(tag.value, sessionCharset));
break;
case CashDistribCurr:
cashDistribCurr = Currency.valueFor(new String(tag.value, sessionCharset));
break;
case CashDistribAgentName:
cashDistribAgentName = new String(tag.value, sessionCharset);
break;
case CashDistribAgentCode:
cashDistribAgentCode = new String(tag.value, sessionCharset);
break;
case CashDistribAgentAcctNumber:
cashDistribAgentAcctNumber = new String(tag.value, sessionCharset);
break;
case CashDistribPayRef:
cashDistribPayRef = new String(tag.value, sessionCharset);
break;
case CashDistribAgentAcctName:
cashDistribAgentAcctName = new String(tag.value, sessionCharset);
break;
default:
String error = "Tag value [" + tag.tagNum + "] not present in [DistribInstsGroup] fields.";
LOGGER.severe(error);
throw new BadFormatMsgException(SessionRejectReason.InvalidTagNumber, tag.tagNum, error);
}
}
@Override
protected Set<Integer> getFragmentDataTags() {
return START_DATA_TAGS;
}
@Override
protected Set<Integer> getFragmentCompTags() {
return START_COMP_TAGS;
}
@Override
protected Set<Integer> getFragmentSecuredTags() {
return SECURED_TAGS;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Package Methods">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Private Methods">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Inner Classes">
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="toString()">
@Override
public String toString() {
StringBuilder b = new StringBuilder(System.getProperty("line.separator"));
b.append("{DistribInstsGroup=");
printTagValue(b, TagNum.DistribPaymentMethod, distribPaymentMethod);
printTagValue(b, TagNum.DistribPercentage, distribPercentage);
printTagValue(b, TagNum.CashDistribCurr, cashDistribCurr);
printTagValue(b, TagNum.CashDistribAgentName, cashDistribAgentName);
printTagValue(b, TagNum.CashDistribAgentCode, cashDistribAgentCode);
printTagValue(b, TagNum.CashDistribAgentAcctNumber, cashDistribAgentAcctNumber);
printTagValue(b, TagNum.CashDistribPayRef, cashDistribPayRef);
printTagValue(b, TagNum.CashDistribAgentAcctName, cashDistribAgentAcctName);
b.append("}");
return b.toString();
}
// </editor-fold>
}
| gpl-3.0 |
doug65536/dgos | libc/src/pthread/pthread_spin_trylock.cc | 463 | #include <pthread.h>
#include <errno.h>
#include <sys/likely.h>
int pthread_spin_trylock(pthread_spinlock_t *s)
{
if (unlikely(s->sig != __PTHREAD_SPINLOCK_SIG))
return EINVAL;
int tid = pthread_self();
int expect = s->owner;
if (unlikely(expect != -1 || !__atomic_compare_exchange_n(
&s->owner, &expect, tid, false,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)))
return EBUSY;
return 0;
}
| gpl-3.0 |
bq/bloqs | src/scripts/bloqs/functions/advanced/arguments.js | 1183 | /*global require */
'use strict';
var _ = require('lodash'),
utils = require('./../../build-utils'),
OutputBloq = require('./../../outputBloq');
/**
* Bloq name: arguments
*
* Bloq type: Output
*
* Description: It allows to declare two arguments instead of one.
*
* Return type: var
*/
var bloqArguments = _.merge(_.clone(OutputBloq, true), {
name: 'arguments',
bloqClass: 'bloq-arguments',
content: [
[{
bloqInputId: 'ARG1',
alias: 'bloqInput',
acceptType: ['all'],
suggestedBloqs: ['argument', 'arguments', 'number', 'string', 'selectVariable']
}, {
alias: 'text',
value: ','
}, {
bloqInputId: 'ARG2',
alias: 'bloqInput',
acceptType: ['all'],
suggestedBloqs: ['argument', 'arguments', 'number', 'string', 'selectVariable']
}]
],
createDynamicContent: 'softwareVars',
code: '{ARG1},{ARG2}',
returnType: {
type: 'simple',
value: 'var'
},
arduino: {
code: '{ARG1},{ARG2}'
}
});
utils.preprocessBloq(bloqArguments);
module.exports = bloqArguments; | gpl-3.0 |
Fedict/eid-pki-ra | eid-pki-ra-blm-model/src/main/java/be/fedict/eid/pkira/blm/model/certificatedomain/validation/UniqueCertificateAuthorityName.java | 1359 | /*
* eID PKI RA Project.
* Copyright (C) 2010-2014 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.eid.pkira.blm.model.certificatedomain.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.hibernate.validator.ValidatorClass;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* @author Hans Vandenbroeck
*
*/
@Documented
@ValidatorClass(UniqueCertificateAuthorityNameValidator.class)
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention( RUNTIME )
public @interface UniqueCertificateAuthorityName {
String message() default "{validation.notUnique.certificateAuthorityName}";
}
| gpl-3.0 |
mmgen/mmgen | mmgen/sha2.py | 6623 | #!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
# Copyright (C)2013-2022 The MMGen Project <[email protected]>
#
# 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/>.
"""
sha2.py: A non-optimized but very compact implementation of the SHA2 hash
algorithm for the MMGen suite. Implements SHA256, SHA512 and
SHA256Compress (unpadded SHA256, required for Zcash addresses)
"""
# IMPORTANT NOTE: Since GMP precision is platform-dependent, generated constants
# for SHA512 are not guaranteed to be correct! Therefore, the SHA512
# implementation must not be used for anything but testing and study. Test with
# the test/hashfunc.py script in the MMGen repository.
from struct import pack,unpack
class Sha2(object):
'Implementation based on the pseudocode at https://en.wikipedia.org/wiki/SHA-2'
K = None
@classmethod
def initConstants(cls):
from math import sqrt
def nextPrime(n=2):
while True:
for factor in range(2,int(sqrt(n))+1):
if n % factor == 0:
break
else:
yield n
n += 1
# Find the first nRounds primes
npgen = nextPrime()
primes = [next(npgen) for x in range(cls.nRounds)]
fb_mul = 2 ** cls.wordBits
def getFractionalBits(n):
return int((n - int(n)) * fb_mul)
if cls.use_gmp:
from gmpy2 import context,set_context,sqrt,cbrt
# context() parameters are platform-dependent!
set_context(context(precision=75,round=1)) # OK for gmp 6.1.2 / gmpy 2.1.0
else:
cbrt = lambda n: pow(n, 1 / 3)
# First wordBits bits of the fractional parts of the square roots of the first 8 primes
H = (getFractionalBits(sqrt(n)) for n in primes[:8])
# First wordBits bits of the fractional parts of the cube roots of the first nRounds primes
K = (getFractionalBits(cbrt(n)) for n in primes)
cls.H_init = tuple(H)
cls.K = tuple(K)
def __init__(self,message,preprocess=True):
'Use preprocess=False for Sha256Compress'
assert isinstance(message,(bytes,bytearray,list)),'message must be of type bytes, bytearray or list'
if self.K == None:
type(self).initConstants()
self.H = list(self.H_init)
self.M = message
self.W = [0] * self.nRounds
if preprocess:
self.padMessage()
self.bytesToWords()
self.compute()
def padMessage(self):
"""
Pre-processing (padding) (adapted from the standard, translating bits to bytes)
- Begin with the original message of length MSGLEN bytes
- Create MLPACK := MSGLEN * 8 encoded as a blkSize-bit big-endian integer
- Append 0x80 (0b10000000)
- Append PADLEN null bytes, where PADLEN is the minimum number >= 0 such that
MSGLEN + 1 + PADLEN + len(MLPACK) is a multiple of blkSize
- Append MLPACK
"""
mlpack = self.pack_msglen()
padlen = self.blkSize - (len(self.M) % self.blkSize) - len(mlpack) - 1
if padlen < 0: padlen += self.blkSize
self.M = self.M + bytes([0x80] + [0] * padlen) + mlpack
def bytesToWords(self):
ws = self.wordSize
assert len(self.M) % ws == 0
self.M = tuple([unpack(self.word_fmt,self.M[i*ws:ws+(i*ws)])[0] for i in range(len(self.M) // ws)])
def digest(self):
return b''.join((pack(self.word_fmt,w) for w in self.H))
def hexdigest(self):
return self.digest().hex()
def compute(self):
for i in range(0,len(self.M),16):
self.processBlock(i)
def processBlock(self,offset):
'Process a blkSize-byte chunk of the message'
def rrotate(a,b): return ((a << self.wordBits-b) & self.wordMask) | (a >> b)
def addm(a,b): return (a + b) & self.wordMask
# Copy chunk into first 16 words of message schedule array
for i in range(16):
self.W[i] = self.M[offset + i]
# Extend the first 16 words into the remaining nRounds words of message schedule array
for i in range(16,self.nRounds):
g0 = self.W[i-15]
gamma0 = rrotate(g0,self.g0r1) ^ rrotate(g0,self.g0r2) ^ (g0 >> self.g0r3)
g1 = self.W[i-2]
gamma1 = rrotate(g1,self.g1r1) ^ rrotate(g1,self.g1r2) ^ (g1 >> self.g1r3)
self.W[i] = addm(addm(addm(gamma0,self.W[i-7]),gamma1),self.W[i-16])
# Initialize working variables from current hash state
a,b,c,d,e,f,g,h = self.H
# Compression function main loop
for i in range(self.nRounds):
ch = (e & f) ^ (~e & g)
maj = (a & b) ^ (a & c) ^ (b & c)
sigma0 = rrotate(a,self.s0r1) ^ rrotate(a,self.s0r2) ^ rrotate(a,self.s0r3)
sigma1 = rrotate(e,self.s1r1) ^ rrotate(e,self.s1r2) ^ rrotate(e,self.s1r3)
t1 = addm(addm(addm(addm(h,sigma1),ch),self.K[i]),self.W[i])
t2 = addm(sigma0,maj)
h = g
g = f
f = e
e = addm(d,t1)
d = c
c = b
b = a
a = addm(t1,t2)
# Save hash state
for n,v in enumerate((a,b,c,d,e,f,g,h)):
self.H[n] = addm(self.H[n],v)
class Sha256(Sha2):
use_gmp = False
g0r1,g0r2,g0r3 = (7,18,3)
g1r1,g1r2,g1r3 = (17,19,10)
s0r1,s0r2,s0r3 = (2,13,22)
s1r1,s1r2,s1r3 = (6,11,25)
blkSize = 64
nRounds = 64
wordSize = 4
wordBits = 32
wordMask = 0xffffffff
word_fmt = '>I'
def pack_msglen(self):
return pack('>Q',len(self.M)*8)
class Sha512(Sha2):
"""
SHA-512 is identical in structure to SHA-256, but:
- the message is broken into 1024-bit chunks,
- the initial hash values and round constants are extended to 64 bits,
- there are 80 rounds instead of 64,
- the message schedule array W has 80 64-bit words instead of 64 32-bit words,
- to extend the message schedule array W, the loop is from 16 to 79 instead of from 16 to 63,
- the round constants are based on the first 80 primes 2..409,
- the word size used for calculations is 64 bits long,
- the appended length of the message (before pre-processing), in bits, is a 128-bit big-endian integer, and
- the shift and rotate amounts used are different.
"""
use_gmp = True
g0r1,g0r2,g0r3 = (1,8,7)
g1r1,g1r2,g1r3 = (19,61,6)
s0r1,s0r2,s0r3 = (28,34,39)
s1r1,s1r2,s1r3 = (14,18,41)
blkSize = 128
nRounds = 80
wordSize = 8
wordBits = 64
wordMask = 0xffffffffffffffff
word_fmt = '>Q'
def pack_msglen(self):
return pack('>Q', (len(self.M)*8) // (2**64)) + \
pack('>Q', (len(self.M)*8) % (2**64))
| gpl-3.0 |
eilin1208/QT_Test | MtcLane_SM/ShowPlate/DisplayPlateNumber.cpp | 9261 | #include "DisplayPlateNumber.h"
#include "MtcKey/MtcKeyDef.h"
const int CHAR_NUM_PER_PAGE=8;//每页个数
const int MAX_PLATE_LEN = 100;//最大数字个数
/***************************************
根据车型获取车牌颜色
***************************************/
int DisplayPlateNumber::GetDefaultVehPlateColorForVehClass(int nVehClass)
{
switch (nVehClass)
{
case VC_Car1:
return VP_COLOR_BLUE;
case VC_Car3:
case VC_Car4:
case VC_Truck2:
case VC_Truck3:
case VC_Truck4:
case VC_Truck5:
return VP_COLOR_YELLOW;
default:
return VP_COLOR_NONE;
}
}
/***************************************
根据按键获取车牌颜色
***************************************/
int DisplayPlateNumber::GetVehPlateColorFromKey(int nValue)
{
switch (nValue)
{
case KeyBlue:
return VP_COLOR_BLUE;
case KeyYellow:
return VP_COLOR_YELLOW;
case KeyWhite:
return VP_COLOR_WHITE;
case KeyBlack:
return VP_COLOR_BLACK;
default:
return VP_COLOR_NONE;
}
}
/******************************************
根据输入拼音查询可选车牌,放入list中
******************************************/
QStringList DisplayPlateNumber::DisplaySelect(QString nValue)
{
InitList();
resultLetter = nValue;
//DB.QueryVehPlateChar(resultLetter.toLocal8Bit().toLower(),list);
return list;
}
/***************
初始化
****************/
void DisplayPlateNumber::InitList()
{
list.clear();
resultLetter.clear();
tempResult.clear();
currentPage = 0;
countPlate = 1;
}
/*********************************************
读取配置文件
*********************************************/
QString DisplayPlateNumber::ReadCfg()
{
//实际用
// QSysParamFile * sysInfo;
// QString platePinyin;
// if(getParamFile(&sysInfo, cfSysParaDic) == true)
// {
// QSysParamInfo info = sysInfo->GetSysParamInfo();
// platePinyin = info.m_sDeftVLP ;
// }
// return platePinyin;
//测试用
QString platePinyin="123";
// QSysParamFile infoFile;
// infoFile.InitParamFile();
// bool isNew;
// SParamFileHead cfgHead;
// if(infoFile.LoadParamFile(infoFile.GetFileName(), cfgHead, isNew) == true)
// {
// QSysParamInfo info = infoFile.GetSysParamInfo();
// platePinyin = info.m_sDeftVLP ;
// }
return platePinyin;
}
void DisplayPlateNumber::LetterEventProcess(int &cursorPosition,QString &sSelect,QString &sResult)
{
if(sResult.length()== cursorPosition)
{
cursorPosition++;
}
resultLetter.append(keyPropertity.ascii);
list = DisplaySelect(resultLetter);
if(list.size()!=0)
{
tempResult.clear();
for(int i=0;i<qMin(CHAR_NUM_PER_PAGE,list.size());i++)
{
tempResult.append(QString::number(i)+"."+list[i]);
}
sSelect = resultLetter.toLower()+": "+tempResult;
}
else
{
if(resultLetter.mid(resultLetter.length()-2,1)==(QString)keyPropertity.ascii)
{
if(cursorPosition<sResult.length())
{
sResult = sResult.left(cursorPosition)+keyPropertity.ascii+sResult.mid(cursorPosition);
cursorPosition++;
}
else
{
sResult = sResult +keyPropertity.ascii;
}
sSelect.clear();
}
else
{
sSelect.clear();
}
resultLetter.clear();
}
}
void DisplayPlateNumber::NumKey(int &cursorPosition,char keyValue, int i,QString &sSelect, QString &sResult)
{
resultLetter.clear();
QString str1,str2,finallStr ;
if(sSelect!="")
{
if(i>=0 && i<qMin(CHAR_NUM_PER_PAGE,list.size()) )
{
str1 = tempResult.left(tempResult.indexOf(QString::number(i+1)));
str2 = str1.mid(str1.indexOf(QString::number(i)));
finallStr =str2.mid(2,1);
if(cursorPosition<sResult.length())
{
sResult = sResult.left(cursorPosition)+finallStr+sResult.mid(cursorPosition);
}
else
{
sResult = sResult+finallStr;
}
sSelect.clear();
resultLetter.clear();
}
}
else
{
if(countPlate < MAX_PLATE_LEN +1)
{
if(cursorPosition<sResult.length())
{
sResult = sResult.left(cursorPosition)+QString::number(i)+sResult.mid(cursorPosition);
}
else
{
countPlate++;
sResult = sResult+QString::number(i);
}
}
}
}
void DisplayPlateNumber::NumEventProcess(int &cursorPosition,int nValue, QString &sSelect, QString &sResult)
{
NumKey(cursorPosition,keyPropertity.ascii,(int)keyPropertity.ascii-Key0,sSelect,sResult);
cursorPosition++;
}
void DisplayPlateNumber::FuncEventProcess(int &cursorPosition,int nValue, QString &sSelect, QString &sResult,QString &color)
{
switch(keyPropertity.func)
{
case KeyRight: KeyRightProcess(cursorPosition,sSelect,sResult); break;
case KeyLeft: KeyLeftProcess(cursorPosition,sSelect,sResult);break;
case KeyDel: KeyDelProcess(cursorPosition,sSelect,sResult);break;
case KeyEsc:ClearResult(sSelect,sResult); break;
case KeyConfirm:KeyConfirmProcess(); break;
}
}
/*********************************************
键盘按键处理
*********************************************/
bool DisplayPlateNumber::KeyEventProcess(int &cursorPosition,int nValue,QString &sSelect,QString &sResult,QString &color)
{
container.findKey(nValue,keyPropertity);
if(keyPropertity.isLetterKey())
{
LetterEventProcess(cursorPosition,sSelect,sResult);
}
else if(keyPropertity.isVehPlateColorKey())
{
color = keyPropertity.keyName;
resultLetter.clear();
}
else if(keyPropertity.isNumKey())
{
NumEventProcess(cursorPosition,nValue,sSelect,sResult);
}
else if(keyPropertity.isFuncKey())
{
FuncEventProcess(cursorPosition,nValue,sSelect,sResult,color);
}
else
{
}
return true;
}
void DisplayPlateNumber::KeyRightProcess(int &cursorPosition,QString &sSelect, QString &sResult)
{
if(list.size()%CHAR_NUM_PER_PAGE == 0)
{
totalPage = list.size()/CHAR_NUM_PER_PAGE;
}
else
{
totalPage =list.size()/CHAR_NUM_PER_PAGE +1;
}
if(sSelect!=NULL)
{
currentPage++;
if(currentPage < totalPage)
{
sSelect.clear();
tempResult.clear();
int index = currentPage * CHAR_NUM_PER_PAGE;
for(int i = 0 ; i < qMin(list.length() - index, CHAR_NUM_PER_PAGE); i++)
{
tempResult.append(QString::number(i) + "." + list[index + i ]);
}
sSelect = resultLetter.toLower()+": "+tempResult;
}
else
{
currentPage = totalPage-1;
}
}
else
{
cursorPosition ++;
}
if(sResult==NULL&&sSelect == NULL)
{
sResult = ReadCfg();
cursorPosition = sResult.length();
}
}
void DisplayPlateNumber::KeyLeftProcess(int &cursorPosition,QString &sSelect, QString &sResult)
{
if(sSelect!=NULL)
{
sSelect.clear();
tempResult.clear();
currentPage--;
if(currentPage<0)
{
currentPage = 0;
}
int index = currentPage * CHAR_NUM_PER_PAGE;
for(int i = 0 ; i < qMin(list.length() - index, CHAR_NUM_PER_PAGE); i++)
{
tempResult.append(QString::number(i) + "." + list[index + i ]);
sSelect = resultLetter.toLower()+": "+tempResult;
}
}
else
{
cursorPosition--;
}
}
void DisplayPlateNumber::KeyDelProcess(int &cursorPosition,QString &sSelect, QString &sResult)
{
currentPage = 0;
if(sSelect!=NULL)
{
resultLetter = resultLetter.remove(resultLetter.length()-1,1);
list = DisplaySelect(resultLetter.trimmed());
if(list.size()!=0&& resultLetter!=NULL)
{
tempResult.clear();
for(int i=0;i<qMin(CHAR_NUM_PER_PAGE,list.size());i++)
{
tempResult.append(QString::number(i)+"."+list[i]);
}
sSelect = resultLetter.toLower()+": "+tempResult;
}
if(resultLetter == NULL)
{
sSelect.clear();
}
}
else
{
if(sResult!=NULL&&cursorPosition!=0)
{
sResult = sResult.remove(cursorPosition-1,1);
cursorPosition--;
}
else
{
resultLetter.clear();
countPlate =1;
}
}
}
void DisplayPlateNumber::ClearResult(QString &sSelect, QString &sResult)
{
if(sSelect!=NULL)
{
sSelect.clear();
}
else
{
sResult.clear();
countPlate =1;
}
resultLetter.clear();
}
void DisplayPlateNumber::KeyConfirmProcess()
{
}
DisplayPlateNumber::DisplayPlateNumber()
{
InitList();
}
| gpl-3.0 |
yeshucheng/CloudM | src/cloudm-invoke/src/main/java/com/github/cloudm/invoke/init/GeneratorLocalTemplateFile.java | 3116 | package com.github.cloudm.invoke.init;
/**
*
* @author andy.wan
*
*/
public class GeneratorLocalTemplateFile {
/*private static final Logger LOGGER = Logger.getLogger(GeneratorLocalTemplateFile.class);
@Autowired
private PPiaasCallbackTemplateRepository templateService;
@Value("${default.win}")
private String defaultWinRootPath ;
@Value("${default.linux}")
private String defaultLinuxRootPath ;
*//**
* 生成模版文件
*//*
public void init() {
LOGGER.info("begin generator template file...");
boolean delFullTemplates=this.deleteTemplateFile("*.vm");
if(delFullTemplates){
Collection<PPiaasCallbackTemplate> templates=templateService.findAll();
if(templates!=null){
for (PPiaasCallbackTemplate pPiaasCallbackTemplate : templates) {
String templateBody=pPiaasCallbackTemplate.getTemplate();
Integer method=pPiaasCallbackTemplate.getMethod();
//如果方法为post或�?put方法
if(this.isPostOrPut(method)){
if(StringUtils.isNotBlank(templateBody)){
String genteratorFilePath="";
//根据不同的操作系统构建对应的根目�?
if (SystemPropertyUtils.isWindowsOS()) {
genteratorFilePath=defaultWinRootPath;
} else if (SystemPropertyUtils.isLinuxOS()) {
genteratorFilePath=defaultLinuxRootPath;
}
//�?��生成模版文件到对应的目录�?
String newPath=genteratorFilePath+pPiaasCallbackTemplate.getName()+".vm";
boolean flag = FileUtils.createFile(newPath);
LOGGER.debug("[ Generator template file flag is ]:"+flag);
if (flag) {
File file=new File(newPath);
FileOutputStream output =null;
try {
output = new FileOutputStream(file);
IOUtils.write(templateBody, output);
} catch (ResourceNotFoundException e) {
throw new ResourceNotFoundException(ModuleCode.PIAAS,"init template resource exception!");
} catch (IOException e) {
throw new InputOutputException(ModuleCode.PIAAS,"init template resource exception!");
}finally{
IOUtils.closeQuietly(output);
}
}
}else{
throw new IllegalArgsException(ModuleCode.PIAAS,"template content is null");
}
}else{
continue;
}
}
LOGGER.debug("generator local template file is ok!");
}else{
throw new IllegalArgsException(ModuleCode.PIAAS,"query template is null");
}
}else{
throw new PiaasDeleteFileException("delete local template error");
}
}
*//**
* 删除模版文件
*
* @param pattern 通配�?
* @return
*//*
private boolean deleteTemplateFile(String pattern){
boolean delFlag=false;
String deletePath="";
if (SystemPropertyUtils.isWindowsOS()) {
deletePath=defaultWinRootPath;
} else if (SystemPropertyUtils.isLinuxOS()) {
deletePath=defaultLinuxRootPath;
}
delFlag=FileUtils.delete(deletePath, pattern);
return delFlag;
}
*/
/**
* 判断请求方法是否为post或�?put
* @param i
* @return
*/
private boolean isPostOrPut(int i){
return (i & 1) != 0;
}
}
| gpl-3.0 |
SoundWarp/sound-warp | tasks/run.js | 626 | 'use strict';
const PREBUILD = process.env.ELECTRON_PREBUILD || false;
const BUILD = 'D';
const ELECTRON_PATH = `${BASE_PATH}/electron/`;
let exec = require(`${TASKS_PATH}/helpers/exec`),
electron = PREBUILD ? 'electron' : `${ELECTRON_PATH}/out/${BUILD}/Electron.app/Contents/MacOS/Electron`,
_electron = null,
dist_path = `${BASE_PATH}/dist`,
child = null;
if (_electron = process.env.ELECTRON && _electron) {
electron = _electron;
}
module.exports = function(gulp) {
gulp.task('run', ['build'], function(next) {
exec(`${electron} ${dist_path}`, function(err) {
return next(err);
});
});
};
| gpl-3.0 |
grebenarov/Zen-Cart--Add-Photo-To-Profile | catalog/includes/templates/YOUR_TEMPLATE/templates/tpl_account_edit_default.php | 6225 | <?php
/**
* Page Template
*
* Loaded automatically by index.php?main_page=account_edit.<br />
* View or change Customer Account Information
*
* @package templateSystem
* @copyright Copyright 2003-2005 Zen Cart Development Team
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: tpl_account_edit_default.php 3848 2006-06-25 20:33:42Z drbyte $
* @copyright Portions Copyright 2003 osCommerce
*/
?>
<div class="centerColumn" id="accountEditDefault">
<?php echo zen_draw_form('account_edit', zen_href_link(FILENAME_ACCOUNT_EDIT, '', 'SSL'), 'post', 'id="acc_edit_form" onsubmit="return check_form(account_edit);" enctype="multipart/form-data"') . zen_draw_hidden_field('action', 'process'); ?>
<?php if ($messageStack->size('account_edit') > 0) echo $messageStack->output('account_edit'); ?>
<fieldset>
<legend><?php echo HEADING_TITLE; ?></legend>
<div class="alert forward"><?php echo FORM_REQUIRED_INFORMATION; ?></div>
<br class="clearBoth" />
<?php
if ( $account->fields["customers_photo"] ) {
$no_cache = rand();
$cust_photo_path = "profile-photos/" . $account->fields["customers_photo"] . "?no_cache=" . $no_cache;
}
else {
$cust_photo_path = "profile-photos/no-photo.gif";
}
?>
<img id="cust_img" width="152" src="<?= DIR_WS_IMAGES . $cust_photo_path ?>" alt="" />
<br /><br /><span class="form_titles"><?php echo (!$account->fields["customers_photo"]) ? "Add" : "Update"; ?> Photo</span> <span style="font-size: 11px; color: #777;">(JPG, PNG, or GIF; Up to 1.0MB)</span>:<br />
<input type="hidden" value="1048576" name="MAX_FILE_SIZE" />
<input name="file_ph" id="file_ph" type="file" onchange="process_photo()" size="35" />
<div id="photo_alert" style="display: none; padding: 4px; color: #fff; background-color: #f00; text-align: center; font-weight: bold;">Click [Update] to upload new photo!</div>
<?php
echo ($account->fields["customers_photo"]) ? "<div style='font-size: 11px; color: darkred;'>(Updating will delete the old photo from the store permanently!)</div>" : "";
?>
<br class="clearBoth" /><br /><br />
<?php
if (ACCOUNT_GENDER == 'true') {
?>
<?php echo zen_draw_radio_field('gender', 'm', $male, 'id="gender-male"') . '<label class="radioButtonLabel" for="gender-male">' . MALE . '</label>' . zen_draw_radio_field('gender', 'f', $female, 'id="gender-female"') . '<label class="radioButtonLabel" for="gender-female">' . FEMALE . '</label>' . (zen_not_null(ENTRY_GENDER_TEXT) ? '<span class="alert">' . ENTRY_GENDER_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<?php
}
?>
<label class="inputLabel" for="firstname"><?php echo ENTRY_FIRST_NAME; ?></label>
<?php echo zen_draw_input_field('firstname', $account->fields['customers_firstname'], 'id="firstname"') . (zen_not_null(ENTRY_FIRST_NAME_TEXT) ? '<span class="alert">' . ENTRY_FIRST_NAME_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<label class="inputLabel" for="lastname"><?php echo ENTRY_LAST_NAME; ?></label>
<?php echo zen_draw_input_field('lastname', $account->fields['customers_lastname'], 'id="lastname"') . (zen_not_null(ENTRY_LAST_NAME_TEXT) ? '<span class="alert">' . ENTRY_LAST_NAME_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<?php
if (ACCOUNT_DOB == 'true') {
?>
<label class="inputLabel" for="dob"><?php echo ENTRY_DATE_OF_BIRTH; ?></label>
<?php echo zen_draw_input_field('dob', zen_date_short($account->fields['customers_dob']), 'id="dob"') . (zen_not_null(ENTRY_DATE_OF_BIRTH_TEXT) ? '<span class="alert">' . ENTRY_DATE_OF_BIRTH_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<?php
}
?>
<label class="inputLabel" for="email-address"><?php echo ENTRY_EMAIL_ADDRESS; ?></label>
<?php echo zen_draw_input_field('email_address', $account->fields['customers_email_address'], 'id="email-address"') . (zen_not_null(ENTRY_EMAIL_ADDRESS_TEXT) ? '<span class="alert">' . ENTRY_EMAIL_ADDRESS_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<label class="inputLabel" for="telephone"><?php echo ENTRY_TELEPHONE_NUMBER; ?></label>
<?php echo zen_draw_input_field('telephone', $account->fields['customers_telephone'], 'id="telephone"') . (zen_not_null(ENTRY_TELEPHONE_NUMBER_TEXT) ? '<span class="alert">' . ENTRY_TELEPHONE_NUMBER_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<label class="inputLabel" for="fax"><?php echo ENTRY_FAX_NUMBER; ?></label>
<?php echo zen_draw_input_field('fax', $account->fields['customers_fax'], 'id="fax"') . (zen_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="alert">' . ENTRY_FAX_NUMBER_TEXT . '</span>': ''); ?>
<br class="clearBoth" />
<?php
if (CUSTOMERS_REFERRAL_STATUS == 2 and $customers_referral == '') {
?>
<label class="inputLabel" for="customers-referral"><?php echo ENTRY_CUSTOMERS_REFERRAL; ?></label>
<?php echo zen_draw_input_field('customers_referral', '', zen_set_field_length(TABLE_CUSTOMERS, 'customers_referral', 15), 'id="customers-referral"'); ?>
<br class="clearBoth" />
<?php } ?>
<?php
if (CUSTOMERS_REFERRAL_STATUS == 2 and $customers_referral != '') {
?>
<label for="customers-referral-readonly"><?php echo ENTRY_CUSTOMERS_REFERRAL; ?></label>
<?php echo $customers_referral; zen_draw_hidden_field('customers_referral', $customers_referral,'id="customers-referral-readonly"'); ?>
<br class="clearBoth" />
<?php } ?>
</fieldset>
<fieldset>
<legend><?php echo ENTRY_EMAIL_PREFERENCE; ?></legend>
<?php echo zen_draw_radio_field('email_format', 'HTML', $email_pref_html,'id="email-format-html"') . '<label class="radioButtonLabel" for="email-format-html">' . ENTRY_EMAIL_HTML_DISPLAY . '</label>' . zen_draw_radio_field('email_format', 'TEXT', $email_pref_text, 'id="email-format-text"') . '<label class="radioButtonLabel" for="email-format-text">' . ENTRY_EMAIL_TEXT_DISPLAY . '</label>'; ?>
<br class="clearBoth" />
</fieldset>
<div class="buttonRow back"><?php echo '<a href="' . zen_href_link(FILENAME_ACCOUNT, '', 'SSL') . '">' . zen_image_button(BUTTON_IMAGE_BACK , BUTTON_BACK_ALT) . '</a>'; ?></div>
<div class="buttonRow forward"><?php echo zen_image_submit(BUTTON_IMAGE_UPDATE , BUTTON_UPDATE_ALT); ?></div>
<br class="clearBoth" />
</form>
</div> | gpl-3.0 |
mwveliz/siglas-mppp | lib/model/doctrine/project/Comunicaciones/Comunicaciones_NotificacionHistorico.class.php | 368 | <?php
/**
* Comunicaciones_NotificacionHistorico
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package siglas
* @subpackage model
* @author Livio Lopez
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
class Comunicaciones_NotificacionHistorico extends BaseComunicaciones_NotificacionHistorico
{
}
| gpl-3.0 |
bootphon/h5features | h5features/items.py | 4179 | # Copyright 2014-2019 Thomas Schatz, Mathieu Bernard, Roland Thiolliere
#
# This file is part of h5features.
#
# h5features 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.
#
# h5features 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 h5features. If not, see <http://www.gnu.org/licenses/>.
"""Provides the Items class to the h5features package."""
import numpy as np
from h5py import string_dtype
from .entry import Entry, nb_per_chunk
def read_items(group, version='1.1', check=False):
"""Return an Items instance initialized from a h5features group."""
if version == '0.1':
# parse unicode to strings
return ''.join(
[unichr(int(c)) for c in group['files'][...]]
).replace('/-', '/').split('/\\')
elif version == '1.0':
return Items(list(group['files'][...]), check)
else:
return Items(list(group['items'][...]), check)
class Items(Entry):
"""This class manages items in h5features files.
:param data: A list of item names (e.g. files from which the
features where extracted). Each name of the list must be
unique.
:type data: list of str
:raise IOError: if data is empty or if one or more names are not
unique in the list.
"""
def __init__(self, data, check=True):
if check:
if not data:
raise IOError('data is empty')
if not len(set(data)) == len(data):
raise IOError('all items must have different names.')
data = [d.decode() if isinstance(d, bytes) else d for d in data]
super(Items, self).__init__(
'items', data, 1, string_dtype(), check)
def create_dataset(
self, group, chunk_size, compression=None, compression_opts=None):
self._create_dataset(group, chunk_size, compression, compression_opts)
def is_appendable_to(self, group):
group_data = [
d.decode() if isinstance(d, bytes) else d
for d in group[self.name][...]]
return not set(group_data).intersection(self.data)
def write_to(self, group):
"""Write stored items to the given HDF5 group.
We assume that self.create() has been called.
"""
# The HDF5 group where to write data
items_group = group[self.name]
nitems = items_group.shape[0]
items_group.resize((nitems + len(self.data),))
items_group[nitems:] = self.data
def is_valid_interval(self, lower, upper):
"""Return False if [lower:upper] is not a valid subitems interval. If
it is, then returns a tuple of (lower index, upper index)"""
try:
lower_idx = self.data.index(lower)
upper_idx = self.data.index(upper)
return (lower_idx, upper_idx) if lower_idx <= upper_idx else False
except ValueError:
return False
def _create_dataset(
self, group, chunk_size, compression, compression_opts):
"""Create an empty dataset in a group."""
if chunk_size == 'auto':
chunks = True
else:
# if dtype is a variable str, guess representative size is 20 bytes
per_chunk = (
nb_per_chunk(20, 1, chunk_size) if self.dtype == np.dtype('O')
else nb_per_chunk(
np.dtype(self.dtype).itemsize, 1, chunk_size))
chunks = (per_chunk,)
shape = (0,)
maxshape = (None,)
# raise if per_chunk >= 4 Gb, this is requested by h5py
group.create_dataset(
self.name, shape, dtype=self.dtype,
chunks=chunks, maxshape=maxshape, compression=compression,
compression_opts=compression_opts)
| gpl-3.0 |
conejoninja/pelisalacarta | python/main-classic/channels/novedades.py | 5820 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para novedades
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
from core import logger
from core import config
from core import scrapertools
from core.item import Item
from servers import servertools
__channel__ = "novedades"
__category__ = "F"
__type__ = "generic"
__title__ = "Novedades"
__language__ = "ES"
DEBUG = config.get_setting("debug")
def isGeneric():
return True
def mainlist(item,preferred_thumbnail="squares"):
logger.info("pelisalacarta.channels.novedades mainlist")
itemlist = []
itemlist.append( Item(channel=__channel__, action="peliculas" , title="Películas", thumbnail="http://media.tvalacarta.info/pelisalacarta/"+preferred_thumbnail+"/thumb_canales_peliculas.png",viewmode="movie"))
itemlist.append( Item(channel=__channel__, action="peliculas_infantiles" , title="Para niños", thumbnail="http://media.tvalacarta.info/pelisalacarta/"+preferred_thumbnail+"/thumb_canales_infantiles.png",viewmode="movie"))
itemlist.append( Item(channel=__channel__, action="series" , title="Episodios de series", thumbnail="http://media.tvalacarta.info/pelisalacarta/"+preferred_thumbnail+"/thumb_canales_series.png",viewmode="movie"))
itemlist.append( Item(channel=__channel__, action="anime" , title="Episodios de anime", thumbnail="http://media.tvalacarta.info/pelisalacarta/"+preferred_thumbnail+"/thumb_canales_anime.png",viewmode="movie"))
itemlist.append( Item(channel=__channel__, action="documentales" , title="Documentales", thumbnail="http://media.tvalacarta.info/pelisalacarta/"+preferred_thumbnail+"/thumb_canales_documentales.png",viewmode="movie"))
return itemlist
def peliculas(item):
logger.info("pelisalacarta.channels.novedades peliculas")
itemlist = []
import zpeliculas
item.url = "http://www.zpeliculas.com"
itemlist.extend( zpeliculas.peliculas(item) )
import cinetux
item.url = "http://www.cinetux.org/"
itemlist.extend( cinetux.peliculas(item) )
import divxatope
item.url = "http://www.divxatope.com/categoria/peliculas-castellano"
itemlist.extend( divxatope.lista(item) )
import yaske
item.url = "http://www.yaske.cc/"
itemlist.extend( yaske.peliculas(item) )
sorted_itemlist = []
for item in itemlist:
if item.extra!="next_page" and not item.title.startswith(">>"):
item.title = item.title + " ["+item.channel+"]"
sorted_itemlist.append(item)
sorted_itemlist = sorted(sorted_itemlist, key=lambda Item: Item.title)
return sorted_itemlist
def peliculas_infantiles(item):
logger.info("pelisalacarta.channels.novedades peliculas_infantiles")
itemlist = []
import zpeliculas
item.url = "http://www.zpeliculas.com/peliculas/p-animacion/"
itemlist.extend( zpeliculas.peliculas(item) )
import cinetux
item.url = "http://www.cinetux.org/genero/infantil"
itemlist.extend( cinetux.peliculas(item) )
import yaske
item.url = "http://www.yaske.cc/es/peliculas/custom/?gender=animation"
itemlist.extend( yaske.peliculas(item) )
import oranline
item.url = "http://www.oranline.com/Películas/infantil/"
itemlist.extend( oranline.peliculas(item) )
sorted_itemlist = []
for item in itemlist:
if item.extra!="next_page" and not item.title.startswith(">>"):
item.title = item.title + " ["+item.channel+"]"
sorted_itemlist.append(item)
sorted_itemlist = sorted(sorted_itemlist, key=lambda Item: Item.title)
return sorted_itemlist
def series(item):
logger.info("pelisalacarta.channels.novedades series")
itemlist = []
import divxatope
item.url = "http://www.divxatope.com/categoria/series"
itemlist.extend( divxatope.lista(item) )
import seriesflv
item.url = "es"
itemlist.extend( seriesflv.ultimos_episodios(item) )
sorted_itemlist = []
for item in itemlist:
if item.extra!="next_page" and not item.title.startswith(">>"):
item.title = item.title + " ["+item.channel+"]"
sorted_itemlist.append(item)
sorted_itemlist = sorted(sorted_itemlist, key=lambda Item: Item.title)
return sorted_itemlist
def anime(item):
logger.info("pelisalacarta.channels.novedades anime")
itemlist = []
import animeid
item.url = "http://animeid.tv/"
itemlist.extend( animeid.novedades_episodios(item) )
import animeflv
item.url = "http://animeflv.net/"
itemlist.extend( animeflv.novedades(item) )
sorted_itemlist = []
for item in itemlist:
if item.extra!="next_page" and not item.title.startswith(">>"):
item.title = item.title + " ["+item.channel+"]"
sorted_itemlist.append(item)
sorted_itemlist = sorted(sorted_itemlist, key=lambda Item: Item.title)
return sorted_itemlist
def documentales(item):
logger.info("pelisalacarta.channels.novedades documentales")
itemlist = []
import documaniatv
item.url = "http://www.documaniatv.com/newvideos.html"
itemlist.extend( documaniatv.novedades(item) )
import oranline
item.url = "http://oranline.com/Pel%C3%ADculas/documentales/"
itemlist.extend( oranline.peliculas(item) )
sorted_itemlist = []
for item in itemlist:
if item.extra!="next_page" and not item.title.startswith(">>"):
item.title = item.title + " ["+item.channel+"]"
sorted_itemlist.append(item)
sorted_itemlist = sorted(sorted_itemlist, key=lambda Item: Item.title)
return sorted_itemlist
| gpl-3.0 |
spillerrec/Overmix | src/aligners/AnimationSaver.cpp | 3960 | /*
This file is part of Overmix.
Overmix 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.
Overmix 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 Overmix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AnimationSaver.hpp"
#include "../planes/ImageEx.hpp"
#include "../containers/FrameContainer.hpp"
#include <QDir>
#include <cmath>
#include <fstream>
using namespace std;
using namespace Overmix;
//TODO: not needed, can be done with QString directly
static QString numberZeroFill( int number, int digits ){
QString str = QString::number( number );
while( str.count() < digits )
str = "0" + str;
return str;
}
AnimationSaver::AnimationSaver( QString folder ) : folder(folder){
//Create the folder
QDir dir( folder );
QString name = dir.dirName();
dir.cdUp();
dir.mkdir( name );
dir.cd( name );
//Create sub-folders for data
dir.mkdir( "data" );
dir.mkdir( "Thumbnails" );
//Create mimetype file
ofstream mime( (folder + "/mimetype" ).toLocal8Bit().constData() );
mime << "image/openraster";
mime.close();
}
bool AnimationSaver::removeUnneededFrames(){
for( unsigned i=1; i<frames.size(); i++ ){
auto& first = frames[i-1].second;
auto& second = frames[i].second;
if( first.image_id == second.image_id && first.x == second.x && first.y == second.y ){
first.delay += second.delay;
frames.erase( frames.begin() + i );
return true;
}
}
return false;
}
QSize AnimationSaver::normalize(){
QPoint pos;
for( auto frame : frames ){
pos.setX( min( pos.x(), frame.second.x ) );
pos.setY( min( pos.y(), frame.second.y ) );
}
for( auto& frame : frames ){
frame.second.x -= pos.x();
frame.second.y -= pos.y();
}
QSize size;
for( auto& frame : frames ){
auto image = images[frame.second.image_id];
size.setWidth( max( size.width(), frame.second.x + image.size.width() ) );
size.setHeight( max( size.height(), frame.second.y + image.size.height() ) );
}
return size;
}
int AnimationSaver::addImage( const ImageEx& img ){
//Create thumbnail for first frame
if( current_id == 1 ){
QImage raw = img.to_qimage( true );
raw.scaled( 256, 256, Qt::KeepAspectRatio )
.save( folder + "/Thumbnails/thumbnail.jpg", nullptr, 95 );
}
QString filename = "data/" + numberZeroFill( current_id++, 4 ) + ".dump"; //TODO: allow file format to be changed?
img.saveDump( (folder + "/" + filename).toLocal8Bit().constData() );
images.push_back( {filename, QSize( img.get_width(), img.get_height() )} );
return images.size() - 1;
}
void AnimationSaver::write(){
//Make sure the frames are in the correct order
sort( frames.begin(), frames.end(), [](pair<int,FrameInfo> first, pair<int,FrameInfo> second){
return first.first < second.first;
} );
//Remove unneeded frames
while( removeUnneededFrames() );
//Write the file
ofstream file( (folder + "/stack.xml").toLocal8Bit().constData() );
file << "<?xml version='1.0' encoding='UTF-8'?>\n";
//Get the actual size, and avoid negative positions
auto size = normalize();
file << "<image w=\"" << size.width() << "\" h=\"" << size.height() << "\" loops=\"-1\">\n";
//Write all the frames
for( auto frame : frames ){
auto image = frame.second;
file << "<stack delay=\"" << image.delay << "\">";
file << "<layer src=\"" << images[image.image_id].name.toUtf8().constData() << "\" ";
file << "x=\"" << image.x << "\" ";
file << "y=\"" << image.y << "\"/></stack>\n";
//TODO: add option to have average image as background
}
file << "</image>";
file.close();
}
| gpl-3.0 |
Moussa/Wiki-Fi | static/js/heading-anchors.js | 1431 | /*
* Heading Anchors v1.0.2
* Copyright (c) 2010-2012 Rafaël Blais Masson <http://twitter.com/rafBM>
*
* Freely distributable under the terms of the MIT license.
* <http://github.com/rafBM/heading-anchors>
*
*/
window.HeadingAnchors = {
init: function(customSelector) {
if (!document.querySelectorAll || ![].forEach)
return
var $ = function(selector) {
return [].slice.call(document.querySelectorAll(selector), 0)
}
var slugize = function(str) {
return str.replace(/['’]/g, '').replace(/[^a-z0-9]+/ig, '-')
}
var existingSlugsNumbers = {}
, selector = customSelector ? customSelector : 'h2, h3, h4'
$(selector).forEach(function(heading) {
var anchor = document.createElement('a')
, slug = slugize(heading.id ? heading.id : heading.textContent)
anchor.className = 'heading-anchor'
// if slug #Foo-bar already exists, create #Foo-bar-2, #Foo-bar-3 and so on
if (slug in existingSlugsNumbers) {
existingSlugsNumbers[slug] += 1
slug += '-' + existingSlugsNumbers[slug]
} else {
existingSlugsNumbers[slug] = 1
}
anchor.href = '#' + slug
heading.id = slug
anchor.innerHTML = '¶'
heading.appendChild(anchor)
})
var headingInHash = document.getElementById(location.hash.substr(1))
if (headingInHash)
window.scrollTo(0, headingInHash.offsetTop)
}
} | gpl-3.0 |
joeyliu616/ci-demo | version/version-service/src/main/java/com/aoe/service/version/Launcher.java | 618 | package com.aoe.service.version;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
/**
* Created by joey on 16-7-20.
*/
@SpringBootApplication
public class Launcher {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Launcher.class,args);
while (true){
synchronized (Launcher.class){
Launcher.class.wait();
}
}
}
}
| gpl-3.0 |
guedouari/xstr.me | src/app/components/xstr-header/index.ts | 41 | export * from './xstr-header.component';
| gpl-3.0 |
BeGnuLinux/invoices | pages/vendor/vendor.php | 6878 | <?php
require_once $_SERVER['DOCUMENT_ROOT'] . "/invoices/core/init.php";
if (!$vendorid = Input::get('vendorid') || $user->exists()) {
Session::flash('fmsg', "You should choose a vendor to view.");
Redirect::to('index.php');
}
$vendorid = Input::get('vendorid');
?>
<!doctype html>
<html lang="en">
<head>
<?php include $INC_DIR . "head.php"; ?>
<title>MLM System: Vendor Profile Page</title>
</head>
<body>
<div class="container-fluid" canvas="container">
<?php include $INC_DIR . "nav.php"; ?>
<div class="row">
<!--
page content starts
-->
<div class="col-md-12">
<?php
if (Session::exists('smsg')) {
Success(Session::flash('smsg'));
}elseif (Session::exists('fmsg')) {
Danger(Session::flash('fmsg'));
}
if ($user->isLoggedIn()) {
if (!empty($vendorid)) {
$vendorProfile = new Vendor($vendorid);
if (!$vendorProfile->exists()) {
Session::flash('fmsg', 'Vendor dosn\'t exists');
Redirect::to('index.php');
}
} else {
//$userProfile = new User();
}
?>
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="jumbotron">
<?php
if ($user->data()->id == $vendorProfile->data()->vendorUserId || $user->hasPermission('admin')) {
?>
<div class="row">
<div class="col-md-3 text-left">
<img class="img-responsive img-circle" alt="" src="<?php linkto('img/users_img/default.jpg'); ?>" />
</div>
<div class="col-md 9 text-right">
<a href="#"><button class="btn btn-default btn-xs">
<span class="fa fa-pencil"></span>
</button></a>
</div>
</div>
<?php } ?>
<div class="space"></div>
<div class="row">
<div class="col-md-12">
<table class="table-hover table-striped">
<tr>
<td><h5><span class="fa fa-user"></span> Vendor Name:</h5></td>
<td><span class="text-left"><h5 class="text-left"><?php echo $vendorProfile->data()->vendorName; ?></h5></span></td>
</tr>
<tr>
<td><h5><span class="fa fa-user"></span> Full Name:</h5></td>
<td><span class="text-left"><h5 class="text-left"><?php echo $vendorProfile->data()->vendorEmailAddress; ?></h5></span></td>
</tr>
</table>
<small class="text-muted">Vendor have invoices with total
<?php
$id = $vendorProfile->data()->id;
$totalInvoices = DB::getInstance()->query("SELECT SUM(invoiceTotal) as total FROM invoices WHERE vendorId = $id");
echo number_format($totalInvoices->first()->total,2);
?>
</small>
</div>
</div>
</div>
</div>
<div class="col-md-3"></div>
<?php
} else {
Redirect::to('index.php');
}
?>
</div>
<!--
page content ends
-->
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#invoices" aria-controls="invoices" role="tab" data-toggle="tab">Invoices</a></li>
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="invoices">
<table id="vendorinvoices" class="display table" cellspacing="0" width="100%">
<thead>
<tr>
<th>Vendor Id</th>
<th>Vendor Name</th>
<th>Vendor Email</th>
<th>Created By</th>
<th>Bank Account</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php
$id = $vendorProfile->data()->id;
$invoices = DB::getInstance()->query("SELECT
invoices.id,
invoiceTotal,
invoiceCreatedDate,
invoiceUserId,
vendorId,
vendors.id as vendorid,
vendorName,
vendorEmailAddress,
vendorBankAccount,
vendorType,
vendorUserId,
users.id as userid,
userFullName
FROM invoices
JOIN vendors on invoices.vendorId = vendors.id
JOIN users on invoices.invoiceUserId = users.id
WHERE invoices.vendorId = $id");
foreach ($invoices->results() as $tinvoice) {
?>
<tr>
<td><a href='<?php linkto("pages/invoices/invoice.php?invoiceid=$tinvoice->id"); ?>'><?php echo $tinvoice->id; ?></a></td>
<td><?php echo number_format($tinvoice->invoiceTotal, 2); ?></td>
<td><?php echo $tinvoice->invoiceCreatedDate; ?></td>
<td><a href='<?php linkto("profile.php?userid=$tinvoice->invoiceUserId"); ?>'><?php echo $tinvoice->userFullName; ?></td>
<td><a href='<?php linkto("pages/vendor/vendor.php?vendorid=$tinvoice->vendorId"); ?>'><?php echo $tinvoice->vendorBankAccount; ?></a></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="profile">...</div>
<div role="tabpanel" class="tab-pane" id="messages">...</div>
<div role="tabpanel" class="tab-pane" id="settings">...</div>
</div>
</div>
<div class="col-md-2"></div>
</div>
</div>
<?php include $INC_DIR . "slidebar.php"; ?>
<?php include $INC_DIR . "footer.php"; ?>
</body>
</html>
| gpl-3.0 |
appfog/af-php-thinkup | _lib/dao/class.HashtagMySQLDAO.php | 4654 | <?php
/**
*
* ThinkUp/webapp/_lib/model/class.HashtagMySQLDAO.php
*
* Copyright (c) 2011-2012 Amy Unruh
*
* LICENSE:
*
* This file is part of ThinkUp (http://thinkupapp.com).
*
* ThinkUp 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.
*
* ThinkUp 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 ThinkUp. If not, see
* <http://www.gnu.org/licenses/>.
*
* @license http://www.gnu.org/licenses/gpl.html
* @copyright 2011-2012
* @author Amy Unruh
*/
class HashtagMySQLDAO extends PDODAO implements HashtagDAO {
public function insertHashtags(array $hashtags, $post_id, $network) {
foreach ($hashtags as $hashtag) {
$this->insertHashtag($hashtag, $post_id, $network);
}
}
public function insertHashtag($hashtag, $post_id, $network) {
$this->logger->logDebug("processing hashtag: $hashtag", __METHOD__.','.__LINE__);
$hashtag_id = null;
// see if record for hashtag already exists. If so, increment its count.
$q = "SELECT id from #prefix#hashtags ";
$q .= "WHERE hashtag = :hashtag AND network = :network ";
$vars = array(
':hashtag' =>$hashtag,
':network' =>$network
);
$ps = $this->execute($q, $vars);
$row = $this->getDataRowAsArray($ps);
if ($row) {
$hashtag_id = $row['id'];
$q = "UPDATE #prefix#hashtags ";
$q .= "SET count_cache = count_cache + 1 where id = :id";
$vars = array(
':id' =>$hashtag_id
);
$ps = $this->execute($q, $vars);
$res = $this->getUpdateCount($ps);
if (!$res) {
throw new Exception("Error: Could not update hashtag.");
}
} else {
// do the insert
$q = "INSERT IGNORE INTO #prefix#hashtags ";
$q .= "(hashtag, network, count_cache) ";
$q .= "VALUES ( :hashtag, :network, :count) ";
$vars = array(
':hashtag' =>$hashtag,
':network' =>$network,
':count' => 1
);
$ps = $this->execute($q, $vars);
$hashtag_id = $this->getInsertId($ps);
if (!$hashtag_id) {
throw new Exception("Error: Could not insert hashtag.");
}
}
// now create the join table entry
$q = "INSERT IGNORE INTO #prefix#hashtags_posts ";
$q .= "(post_id, hashtag_id, network) ";
$q .= "VALUES ( :post_id, :hashtag_id, :network) ";
$vars = array(
':hashtag_id' => $hashtag_id,
':post_id' =>(string)$post_id,
':network' => $network
);
$ps = $this->execute($q, $vars);
$res = $this->getUpdateCount($ps);
}
public function getHashtagInfoForTag($hashtag, $network = 'twitter') {
$q = "SELECT * FROM #prefix#hashtags WHERE hashtag = :hashtag AND network = :network";
$vars = array(
':hashtag' => $hashtag,
':network' => $network
);
$ps = $this->execute($q, $vars);
$row = $this->getDataRowAsArray($ps);
if ($row) {
return $row;
} else {
return null;
}
}
public function getHashtagsForPost($pid, $network = 'twitter') {
$q = "SELECT * FROM #prefix#hashtags_posts WHERE post_id = :post_id AND network = :network ORDER BY hashtag_id";
$vars = array(
':post_id' => $pid,
':network' => $network
);
$ps = $this->execute($q, $vars);
$all_rows = $this->getDataRowsAsArrays($ps);
if ($all_rows) {
return $all_rows;
} else {
return null;
}
}
public function getHashtagsForPostHID($hid) {
$q = "SELECT * FROM #prefix#hashtags_posts WHERE hashtag_id = :hashtag_id ORDER BY post_id";
$vars = array(
':hashtag_id' => $hid
);
$ps = $this->execute($q, $vars);
$all_rows = $this->getDataRowsAsArrays($ps);
if ($all_rows) {
return $all_rows;
} else {
return null;
}
}
}
| gpl-3.0 |
matthew-macgregor/isecurepasswords | iSecurePasswords/src/com/sudolink/isp/app/DesktopManager.java | 1949 | /**
* This file is part of iSecurePasswords.
*
* iSecurePasswords 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.
*
* iSecurePasswords 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 iSecurePasswords. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Matthew MacGregor
* Created: 2012
* iSecurePasswords, copyright 2013 Sudolink, LLC
*
*/
package com.sudolink.isp.app;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
/**
*
* @author dev
*/
public class DesktopManager {
private Desktop desktop;
public boolean isDesktopSupported()
{
if (Desktop.isDesktopSupported()) {
if( desktop == null)
{
desktop = Desktop.getDesktop();
}
return true;
} else {
return false;
}
}
public boolean isBrowserLaunchSupported()
{
if ( isDesktopSupported())
{
if (desktop.isSupported(Desktop.Action.BROWSE)) {
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public void browse(URI uri) throws IOException
{
if ( isBrowserLaunchSupported() )
{
desktop.browse(uri);
}
}
}
| gpl-3.0 |
Altaxo/Altaxo | Altaxo/Base/Gui/Graph/Graph3D/Viewing/GraphToolType.cs | 1671 | #region Copyright
/////////////////////////////////////////////////////////////////////////////
// Altaxo: a data processing and data plotting program
// Copyright (C) 2002-2016 Dr. Dirk Lellinger
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
/////////////////////////////////////////////////////////////////////////////
#endregion Copyright
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Altaxo.Gui.Graph.Graph3D.Viewing
{
public enum GraphToolType
{
None,
ObjectPointer,
ArrowLineDrawing,
SingleLineDrawing,
RectangleDrawing,
CurlyBraceDrawing,
EllipseDrawing,
TextDrawing,
ReadPlotItemData,
ReadXYCoordinates,
ZoomAxes,
RegularPolygonDrawing,
OpenCardinalSplineDrawing,
ClosedCardinalSplineDrawing,
/// <summary>Edits the grid of the current layer, or if it has no childs, the grid of the parent layer.</summary>
EditGrid
}
}
| gpl-3.0 |
xingh/bsn-goldparser | bsn.GoldParser/Grammar/CgtWriter.cs | 3043 | // bsn GoldParser .NET Engine
// --------------------------
//
// Copyright 2009, 2010 by Arsène von Wyss - [email protected]
//
// Development has been supported by Sirius Technologies AG, Basel
//
// Source:
//
// https://bsn-goldparser.googlecode.com/hg/
//
// License:
//
// The library is distributed under the GNU Lesser General Public License:
// http://www.gnu.org/licenses/lgpl.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.IO;
using System.Text;
namespace bsn.GoldParser.Grammar {
internal class CgtWriter {
private readonly BinaryWriter writer;
private int entryCount;
public CgtWriter(BinaryWriter writer) {
if (writer == null) {
throw new ArgumentNullException("writer");
}
this.writer = writer;
}
public void WriteBoolEntry(bool value) {
WriteEntryType(CgtEntryType.Boolean);
entryCount--;
writer.Write(value);
}
public void WriteByteEntry(byte value) {
WriteEntryType(CgtEntryType.Byte);
entryCount--;
writer.Write(value);
}
public void WriteEmptyEntry() {
WriteEntryType(CgtEntryType.Empty);
entryCount--;
}
public void WriteHeaderString(string header) {
if (entryCount != 0) {
throw new FileLoadException("Header expected");
}
WriteString(header);
}
public void WriteIntegerEntry(int value) {
WriteEntryType(CgtEntryType.Integer);
entryCount--;
writer.Write(checked((UInt16)value));
}
public void WriteNextRecord(CgtRecordType recordType, int entries) {
if (entryCount != 0) {
throw new InvalidOperationException("There are entries missing before starting a new record");
}
entryCount = entries+1;
writer.Write((byte)'M');
writer.Write(checked((UInt16)entryCount));
WriteByteEntry((byte)recordType);
}
public void WriteStringEntry(string value) {
WriteEntryType(CgtEntryType.String);
entryCount--;
WriteString(value);
}
private void WriteEntryType(CgtEntryType entryType) {
if (entryCount <= 0) {
throw new FileLoadException("No entry pending in this record");
}
writer.Write((byte)entryType);
}
private void WriteString(string data) {
if (data == null) {
throw new ArgumentNullException("data");
}
writer.Write(Encoding.Unicode.GetBytes(data));
writer.Write((UInt16)0);
}
}
}
| gpl-3.0 |
ajbloureiro/list-to-qrcode | index.js | 1707 | #!/usr/bin/env node
var process = require('process'),
args = process.argv,
CSVReader = require('./lib/csv-reader'),
QRImage = require( './lib/qrcode-image-generator' ),
Util = require('findhit-util'),
fs = require('fs'),
mkpath = require('mkpath'),
path = require('path'),
qrCodeGenerator = module.exports = {},
DS = path.sep,
__file_ext = 'svg';
var generateCodes =
qrCodeGenerator.generateCodes =
function( csvList, savePath ){
var reader = fs.createReadStream( csvList );
CSVReader.readLine( reader , function processLine( filename, siteUrl ){
console.log(savePath + DS + filename + '.' + __file_ext);
var writer = fs.createWriteStream(
savePath + filename + '.' + __file_ext
);
QRImage.generate( writer, siteUrl , function(){
console.log( filename, siteUrl );
console.log('-> QR Code generated for ',filename);
} );
},
function processFinished(){
console.log('All lines processed');
}
);
};
var _csvList = '',
_imgPath = 'qr_images';
if(args.length == 2){
console.error('missing csv list to process');
return;
}
_csvList = args[2];
if(args.length == 4){
_imgPath = args[3];
if(_imgPath[0] != DS)
_imgPath = path.dirname(_csvList) + DS + _imgPath;
}
else
_imgPath = path.dirname(_csvList) + DS + _imgPath;
path.normalize(_imgPath);
if(_imgPath[_imgPath.length - 1] != DS)
_imgPath += DS;
if ( !fs.existsSync(_imgPath) ) {
mkpath.sync(_imgPath, 0755);
}
generateCodes( _csvList, _imgPath );
| gpl-3.0 |
Justasic/ATF | src/user.cpp | 3082 | /* Arbitrary Navn Tool -- User Routines.
*
* (C) 2011-2012 Azuru
* Contact us at [email protected]
*
* Please read COPYING and README for further details.
*
* Based on the original code of CIA.vc by Micah Dowty
* Based on the original code of Anope by The Anope Team.
*/
#include "user.h"
#include <map>
#include "SocketException.h"
#include "channel.h"
#include "log.h"
#include "network.h"
std::map<User*, std::vector<Channel*>> CUserMap;
// std::map<Channel*, std::vector<User*>> UChanMap;
uint32_t usercnt = 0, maxusercnt = 0;
User::User(Network *net, const Flux::string &snick, const Flux::string &sident, const Flux::string &shost, const Flux::string &srealname, const Flux::string &sserver) :
nickname(snick), hostname(shost), realname(srealname), ident(sident),
fullhost(snick+"!"+sident+"@"+shost), server(sserver), n(net)
{
Log(LOG_RAWIO) << "new User(" << (void*)net << ", " << snick << ", " << sident << ", " << shost << ", " << srealname << ", " << sserver << ");";
/* check to see if a empty string was passed into the constructor */
if (snick.empty() || sident.empty() || shost.empty())
throw CoreException("Bad args sent to User constructor");
if (!net)
throw CoreException("User created with no network??");
this->n->UserNickList[snick] = this;
CUserMap[this] = std::vector<Channel*>();
Log(LOG_RAWIO) << "New user! " << this->nickname << '!' << this->ident << '@' << this->hostname << (this->realname.empty()?"":" :"+this->realname);
++usercnt;
if (usercnt > maxusercnt)
{
maxusercnt = usercnt;
Log(LOG_TERMINAL) << "New maximum user count: " << maxusercnt;
}
}
User::~User()
{
Log() << "Deleting user " << this->nickname << '!' << this->ident << '@' << this->hostname << (this->realname.empty()?"":" :"+this->realname);
this->n->UserNickList.erase(this->nickname);
CUserMap.erase(this);
for (auto it : UChanMap)
{
for (std::vector<User*>::iterator it2 = it.second.begin(), it2_end = it.second.end(); it2 != it2_end; ++it2)
if ((*it2) == this)
it.second.erase(it2);
}
}
void User::SetNewNick(const Flux::string &newnick)
{
if (newnick.empty())
throw CoreException("User::SetNewNick() was called with empty arguement");
Log(LOG_TERMINAL) << "Setting new nickname: " << this->nickname << " -> " << newnick;
this->n->UserNickList.erase(this->nickname);
this->nickname = newnick;
this->n->UserNickList[this->nickname] = this;
}
void User::AddChan(Channel *c)
{
if (c)
CUserMap[this].push_back(c);
}
void User::DelChan(Channel *c)
{
if (c)
{
for (auto it : CUserMap)
{
if (it.first == this)
{
for (std::vector<Channel*>::iterator it2 = it.second.begin(), it2_end = it.second.end(); it2 != it2_end; ++it2)
if ((*it2) == c)
CUserMap[this].erase(it2);
}
}
if (CUserMap[this].empty())
delete this; // remove the user, it has no channels.
}
}
Channel *User::FindChannel(const Flux::string &name)
{
for (auto it : CUserMap)
{
if (it.first == this)
{
for (auto it2 : it.second)
if (it2->name.equals_ci(name))
return it2;
}
}
return nullptr;
}
| gpl-3.0 |
Kev/evexin | Controllers/FileDataStore.cpp | 1458 | /*
* Copyright (c) 2013 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Eve-Xin/Controllers/FileDataStore.h>
#include <boost/filesystem/fstream.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Path.h>
#include <Swiften/StringCodecs/Base64.h>
#include <SwifTools/Application/ApplicationPathProvider.h>
namespace EveXin {
FileDataStore::FileDataStore(boost::filesystem::path dataDir) : dataDir_(dataDir) {
}
FileDataStore::~FileDataStore() {
}
Swift::ByteArray FileDataStore::getContent(const Swift::URL& url) {
auto path = urlToPath(url);
if (!boost::filesystem::exists(path)) {
return Swift::createByteArray("");
}
Swift::ByteArray content;
Swift::readByteArrayFromFile(content, path);
return content;
}
void FileDataStore::setContent(const Swift::URL& url, const Swift::ByteArray& content) {
boost::filesystem::path path = urlToPath(url);
std::cerr << "Saving data to " << Swift::pathToString(path) << std::endl;
try {
boost::filesystem::ofstream file(path);
file << Swift::byteArrayToString(content);
}
catch (const boost::filesystem::filesystem_error& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
}
}
boost::filesystem::path FileDataStore::urlToPath(const Swift::URL& url) {
std::string fileName = Swift::Base64::encode(Swift::createByteArray(url.toString())) + ".xml";
return dataDir_ / fileName;
}
}
| gpl-3.0 |
AnguisCaptor/AsmNet | Asm.Net/src/Opcodes/XOR/XOR_ESI_ECX.cs | 723 | using System;
using System.Collections.Generic;
using System.Text;
using Asm.Net.src.Interfaces;
namespace Asm.Net.src.Opcodes.XOR
{
public class XOR_ESI_ECX : Instruction, IXor
{
public XOR_ESI_ECX()
: base(2, typeof(IXor))
{
}
public override byte[] ToByteArray()
{
return new byte[] { (byte)OpcodeList.XOR_REGISTER, (byte)XorRegisterOpcodes.XOR_ESI_ECX };
}
public override void Dispose()
{
}
public override string ToString()
{
return "XOR ESI, ECX";
}
public void XorValue(Registers register)
{
register.ESI ^= register.ECX;
}
}
} | gpl-3.0 |
fener06/pyload | module/plugins/hooks/Ev0InFetcher.py | 3770 | # -*- coding: utf-8 -*-
"""
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/>.
@author: mkaay
"""
from module.lib import feedparser
from time import mktime, time
from module.plugins.Hook import Hook
class Ev0InFetcher(Hook):
__name__ = "Ev0InFetcher"
__version__ = "0.2"
__description__ = """checks rss feeds for ev0.in"""
__config__ = [("activated", "bool", "Activated", "False"),
("interval", "int", "Check interval in minutes", "10"),
("queue", "bool", "Move new shows directly to Queue", False),
("shows", "str", "Shows to check for (comma seperated)", ""),
("quality", "xvid;x264;rmvb", "Video Format", "xvid"),
("hoster", "str", "Hoster to use (comma seperated)", "NetloadIn,RapidshareCom,MegauploadCom,HotfileCom")]
__author_name__ = ("mkaay")
__author_mail__ = ("[email protected]")
def setup(self):
self.interval = self.getConfig("interval") * 60
def filterLinks(self, links):
results = self.core.pluginManager.parseUrls(links)
sortedLinks = {}
for url, hoster in results:
if hoster not in sortedLinks:
sortedLinks[hoster] = []
sortedLinks[hoster].append(url)
for h in self.getConfig("hoster").split(","):
try:
return sortedLinks[h.strip()]
except:
continue
return []
def periodical(self):
def normalizefiletitle(filename):
filename = filename.replace('.', ' ')
filename = filename.replace('_', ' ')
filename = filename.lower()
return filename
shows = [s.strip() for s in self.getConfig("shows").split(",")]
feed = feedparser.parse("http://feeds.feedburner.com/ev0in/%s?format=xml" % self.getConfig("quality"))
showStorage = {}
for show in shows:
showStorage[show] = int(self.getStorage("show_%s_lastfound" % show, 0))
found = False
for item in feed['items']:
for show, lastfound in showStorage.iteritems():
if show.lower() in normalizefiletitle(item['title']) and lastfound < int(mktime(item.date_parsed)):
links = self.filterLinks(item['description'].split("<br />"))
packagename = item['title'].encode("utf-8")
self.core.log.info("Ev0InFetcher: new episode '%s' (matched '%s')" % (packagename, show))
self.core.api.addPackage(packagename, links, 1 if self.getConfig("queue") else 0)
self.setStorage("show_%s_lastfound" % show, int(mktime(item.date_parsed)))
found = True
if not found:
#self.core.log.debug("Ev0InFetcher: no new episodes found")
pass
for show, lastfound in self.getStorage().iteritems():
if int(lastfound) > 0 and int(lastfound) + (3600*24*30) < int(time()):
self.delStorage("show_%s_lastfound" % show)
self.core.log.debug("Ev0InFetcher: cleaned '%s' record" % show)
| gpl-3.0 |
mop/LTPTextDetector | scripts/gridsearch.py | 2959 | import numpy as np
import subprocess
import re
import os
TEMPLATE = """%%YAML:1.0
input_directory: ../sample_icdar_2005/
responses_directory: ../result_sample/
crf_model_file: models/model_crf_rf_svm.dat
svm_model_file: models/model_svm_cc.yml
cnn_model_file: dumpnet_bin/
random_forest_model_file: models/model_forest_cc.yml
random_forest_pw_1_1_model_file: models/model_forest_cc_pw_1_1.yml
random_forest_pw_1_0_model_file: models/model_forest_cc_pw_1_0.yml
random_forest_pw_0_0_model_file: models/model_forest_cc_pw_0_0.yml
random_seed: 4
threshold: 0.10
word_split_model: "MODEL_PROJECTION_PROFILE_SOFT"
classification_model: "CLASSIFICATION_MODEL_CRF_RF"
pre_classification_model: "PRE_CLASSIFICATION_MODEL_RF_SVM_ENSEMBLE"
word_group_threshold: %(word_group_threshold)f
pre_classification_prob_threshold: %(pre_classification_prob_threshold)f
maximum_height_ratio: %(maximum_height_ratio)f
minimum_vertical_overlap: %(minimum_vertical_overlap)f
allow_single_letters: 1
cache_directory: "cache_rf"
verbose: 1
"""
os.system("taskset -p 0xff %d >/dev/null" % os.getpid())
LOGFILE = 'gridlog.txt'
log = open(LOGFILE, 'w')
word_group_grid = [x for x in np.linspace(0.5, 1.0, 6)]
pre_class_group_grid = [x for x in np.linspace(0, 0.5, 6)]
min_vertical_overlap_grid = [x for x in np.linspace(0.2, 0.8, 7)]
max_height_ratio_grid = [x for x in np.linspace(1, 3, 9)]
params = [(w,p,mver,maxh) for w in word_group_grid for p in pre_class_group_grid for mver in min_vertical_overlap_grid for maxh in max_height_ratio_grid]
np.random.shuffle(params)
best_params = []
best_fscore = 0
for w,p,mver,maxh in params:
template = TEMPLATE % {
'word_group_threshold': w,
'pre_classification_prob_threshold': p,
'maximum_height_ratio': maxh,
'minimum_vertical_overlap': mver
}
with open('config_cv.yml', 'w') as fp:
fp.write(template)
os.system('./bin/create_boxes -c config_cv.yml')
os.system('cd .. && python2 ./scripts/to_xml4.py result_sample > eval_cv.xml')
os.system('cd .. && /home/nax/Downloads/deteval-linux/detevalcmd/evaldetection eval_cv.xml datasets/icdar-sample/locations.xml > results_cv.xml')
pipe = subprocess.Popen('cd .. && /home/nax/Downloads/deteval-linux/detevalcmd/readdeteval results_cv.xml', shell=True, stdout=subprocess.PIPE)
result_str = pipe.stdout.read()
hmean_2003, hmean_2011 = re.findall('hmean="([^"]*)"', result_str, flags=re.MULTILINE)
hmean_2003, hmean_2011 = float(hmean_2003), float(hmean_2011)
if hmean_2003 > best_fscore:
best_fscore = hmean_2003
best_params = (w,p, mver, maxh)
print '****NEW BEST****'
print best_fscore
print best_params
os.system('cp ../eval_cv.xml ../eval_cv_best.xml')
log.write("F-2003: %f, F-2011: %f, w: %f, p: %f, minv: %f, maxh: %f\n" % (hmean_2003, hmean_2011, w,p, mver, maxh))
log.flush()
print '****BEST****'
print best_fscore
print best_params
log.close()
| gpl-3.0 |
MyEmbeddedWork/ARM_CORTEX_M3-STM32 | 1. Docs/Doxygen/html/__sbrk_8c.js | 94 | var __sbrk_8c =
[
[ "_sbrk", "__sbrk_8c.html#aae54d7b9578ba1fc171ce6f30f4c68a3", null ]
]; | gpl-3.0 |
cXhristian/django-wiki | src/wiki/plugins/macros/mdx/wikilinks.py | 2208 | #!/usr/bin/env python
"""
Extend the shipped Markdown extension 'wikilinks'
"""
from __future__ import unicode_literals
import re
import markdown
from django.core.urlresolvers import reverse
from markdown.extensions import wikilinks
def build_url(label, base, end, md):
""" Build a url from the label, a base, and an end. """
clean_label = re.sub(r'([ ]+_)|(_[ ]+)|([ ]+)', '_', label)
urlpaths = md.article.urlpath_set.all()
# Nevermind about the base we are fed, just keep the original
# call pattern from the wikilinks plugin for later...
base = reverse('wiki:get', kwargs={'path': ''})
for urlpath in urlpaths:
if urlpath.children.filter(slug=clean_label).exists():
base = ''
break
return '%s%s%s' % (base, clean_label, end)
class WikiLinkExtension(wikilinks.WikiLinkExtension):
def __init__(self, configs={}):
# set extension defaults
self.config = {
'base_url': ['', 'String to append to beginning or URL.'],
'end_url': ['/', 'String to append to end of URL.'],
'html_class': ['wiki_wikilink', 'CSS hook. Leave blank for none.'],
'build_url': [build_url, 'Callable formats URL from label.'],
}
# Override defaults with user settings
for key, value in configs:
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
self.md = md
# append to end of inline patterns
WIKILINK_RE = r'\[\[([\w0-9_ -]+)\]\]'
wikilinkPattern = WikiLinks(WIKILINK_RE, self.getConfigs())
wikilinkPattern.md = md
md.inlinePatterns.add('wikilink', wikilinkPattern, "<not_strong")
class WikiLinks(wikilinks.WikiLinks):
def handleMatch(self, m):
if m.group(2).strip():
base_url, end_url, html_class = self._getMeta()
label = m.group(2).strip()
url = self.config['build_url'](label, base_url, end_url, self.md)
a = markdown.util.etree.Element('a')
a.text = label
a.set('href', url)
if html_class:
a.set('class', html_class)
else:
a = ''
return a
| gpl-3.0 |
ouyangyu/fdmoodle | backup/util/structure/tests/baseatom_test.php | 4625 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package core_backup
* @category phpunit
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// Include all the needed stuff
require_once(__DIR__.'/fixtures/structure_fixtures.php');
/**
* Unit test case the base_atom class. Note: as it's abstract we are testing
* mock_base_atom instantiable class instead
*/
class backup_base_atom_testcase extends basic_testcase {
/**
* Correct base_atom_tests
*/
function test_base_atom() {
$name_with_all_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
$value_to_test = 'Some <value> to test';
// Create instance with correct names
$instance = new mock_base_atom($name_with_all_chars);
$this->assertInstanceOf('base_atom', $instance);
$this->assertEquals($instance->get_name(), $name_with_all_chars);
$this->assertFalse($instance->is_set());
$this->assertNull($instance->get_value());
// Set value
$instance->set_value($value_to_test);
$this->assertEquals($instance->get_value(), $value_to_test);
$this->assertTrue($instance->is_set());
// Clean value
$instance->clean_value();
$this->assertFalse($instance->is_set());
$this->assertNull($instance->get_value());
// Get to_string() results (with values)
$instance = new mock_base_atom($name_with_all_chars);
$instance->set_value($value_to_test);
$tostring = $instance->to_string(true);
$this->assertTrue(strpos($tostring, $name_with_all_chars) !== false);
$this->assertTrue(strpos($tostring, ' => ') !== false);
$this->assertTrue(strpos($tostring, $value_to_test) !== false);
// Get to_string() results (without values)
$tostring = $instance->to_string(false);
$this->assertTrue(strpos($tostring, $name_with_all_chars) !== false);
$this->assertFalse(strpos($tostring, ' => '));
$this->assertFalse(strpos($tostring, $value_to_test));
}
/**
* Throwing exception base_atom tests
*/
function test_base_atom_exceptions() {
// empty names
try {
$instance = new mock_base_atom('');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// whitespace names
try {
$instance = new mock_base_atom('TESTING ATOM');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// ascii names
try {
$instance = new mock_base_atom('TESTING-ATOM');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
try {
$instance = new mock_base_atom('TESTING_ATOM_Á');
$this->fail("Expecting base_atom_struct_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_struct_exception);
}
// setting already set value
$instance = new mock_base_atom('TEST');
$instance->set_value('test');
try {
$instance->set_value('test');
$this->fail("Expecting base_atom_content_exception exception, none occurred");
} catch (Exception $e) {
$this->assertTrue($e instanceof base_atom_content_exception);
}
}
}
| gpl-3.0 |
patxoca/arv.autotest | tests/test_event_filters.py | 7603 | # -*- coding: utf-8 -*-
# $Id$
from __future__ import unicode_literals
from builtins import object
from future.utils import PY2
import os
import re
import shutil
import tempfile
import unittest
import pyinotify
from arv.autotest.config import watch_node_validator
from arv.autotest.event_filters import and_
from arv.autotest.event_filters import is_delete_dir_event
from arv.autotest.event_filters import not_
from arv.autotest.event_filters import simple_event_filter_factory
from arv.autotest.event_filters import throttler_factory
class Object(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def make_event(path, name, mask=0):
return Object(path=path, name=name, mask=mask)
def make_watch(path, recurse=False, auto_add=False, include=[], exclude=[]):
return watch_node_validator({
"path": path,
"recurse": recurse,
"auto_add": auto_add,
"include": include,
"exclude": exclude
})
def make_fake_timer(start, deltas):
def generator():
total = start
yield total
for i in deltas:
total += i
yield total
if PY2:
return generator().next
else:
return generator().__next__
class TestIsDirEvent(unittest.TestCase):
def test_exclude_directory_delete(self):
event = make_event("", "", pyinotify.IN_DELETE | pyinotify.IN_ISDIR)
self.assert_(is_delete_dir_event(event))
def test_exclude_self_delete(self):
event = make_event("", "", pyinotify.IN_DELETE | pyinotify.IN_DELETE_SELF)
self.assert_(is_delete_dir_event(event))
def test_include_directory_create(self):
event = make_event("", "", pyinotify.IN_CREATE | pyinotify.IN_ISDIR)
self.failIf(is_delete_dir_event(event))
class TestSimpleEventFilterFactory(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmpdir)
def make_subdir(self, name):
name = os.path.join(self.tmpdir, name)
os.mkdir(name)
return name
def test_exclude_excluded_file(self):
event = make_event(self.tmpdir, "exclude.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, exclude=[u".*\\.abc"])
])
self.failIf(filter(event))
def test_include_included_file(self):
event = make_event(self.tmpdir, "include.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, include=[u".*\\.abc"])
])
self.assert_(filter(event))
def test_exclude_excluced_file_in_subdirectory(self):
subdir = self.make_subdir("subdir")
event = make_event(subdir, "exclude.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, exclude=[u".*\\.abc"])
])
self.failIf(filter(event))
def test_include_included_file_in_subdirectory(self):
subdir = self.make_subdir("subdir")
event = make_event(subdir, "include.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, include=[u".*\\.abc"])
])
self.assert_(filter(event))
def test_exclude_specific_takes_over_generic(self):
subdir = self.make_subdir("subdir")
event = make_event(subdir, "exclude.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, include=[u".*\\.abc"]), # /tmp
make_watch(subdir, exclude=[u".*\\.abc"]), # /tmp/subdir
])
self.failIf(filter(event))
def test_include_specific_takes_over_generic(self):
subdir = self.make_subdir("subdir")
event = make_event(subdir, "exclude.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, exclude=[u".*\\.abc"]), # /tmp
make_watch(subdir, include=[u".*\\.abc"]), # /tmp/subdir
])
self.assert_(filter(event))
def test_global_exclude_takes_over_all(self):
event = make_event(self.tmpdir, ".exclude.abc")
filter = simple_event_filter_factory(
watches=[
make_watch(self.tmpdir, include=[u".*\\.abc"]),
],
global_ignores=[re.compile("\\..*")]
)
self.failIf(filter(event))
def test_neither_excluded_nor_included_gets_excluded_by_default(self):
event = make_event(self.tmpdir, "exclude.txt")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, exclude=[u".*\\.abc"], include=[u".*\\.py"])
])
self.failIf(filter(event))
def test_unwatched_directory_raises_ValueError(self):
parent = os.path.dirname(self.tmpdir)
event = make_event(parent, "exclude.abc")
filter = simple_event_filter_factory([
make_watch(self.tmpdir, include=[u".*\\.abc"])
])
self.assertRaises(ValueError, filter, event)
class TestFilterCombinators(unittest.TestCase):
def setUp(self):
def is_odd(value):
return bool(value % 2)
def is_big(value):
return value > 100
self.is_odd = is_odd
self.is_big = is_big
def test_preconditions(self):
self.assert_(self.is_odd(3))
self.failIf(self.is_odd(2))
self.assert_(self.is_big(1000))
self.failIf(self.is_big(2))
def test_negation(self):
f = not_(self.is_odd)
self.assert_(f(2))
self.failIf(f(3))
def test_and(self):
f = and_(self.is_odd, self.is_big)
self.assert_(f(1003))
self.failIf(f(1002))
self.failIf(f(3))
self.failIf(f(2))
class TestThrottlingFilter(unittest.TestCase):
def set_up(self, deltas, start=0, count=10):
self.cfg = Object(max_events_second=count) # 10 events/second
self.timer = make_fake_timer(start, deltas)
self.throttler = throttler_factory(self.cfg, self.timer)
self.event = make_event("/tmp", "foo")
def test_fake_timer(self):
timer = make_fake_timer(5, [0.1, 0, 0.5])
self.assertEqual(timer(), 5)
self.assertEqual(timer(), 5.1)
self.assertEqual(timer(), 5.1)
self.assertEqual(timer(), 5.6)
self.assertRaises(StopIteration, timer)
def test_first_event_is_accepted(self):
self.set_up([])
self.assert_(self.throttler(self.event))
def test_event_accepted_if_delta_elapsed(self):
self.set_up([0.1])
self.throttler(self.event)
self.assert_(self.throttler(self.event))
def test_event_accepted_if_delta_elapsed_cummulative(self):
self.set_up([0.05, 0.06])
self.throttler(self.event)
self.failIf(self.throttler(self.event))
self.assert_(self.throttler(self.event))
def test_event_rejected_if_delta_not_elapsed(self):
self.set_up([0.01])
self.throttler(self.event)
self.failIf(self.throttler(self.event))
def test_None_cfg_disables_throttling(self):
throttler = throttler_factory(None, make_fake_timer(0, [0, 0]))
event = make_event("/tmp", "foo")
self.assert_(throttler(event)) # always accepted
self.assert_(throttler(event)) # two deltas
self.assert_(throttler(event))
self.assert_(throttler(event)) # timer isn't called
def test_adjust_delta(self):
self.set_up([0.2, 0.5])
self.throttler(self.event)
self.assert_(self.throttler(self.event))
self.throttler.adjust_delta(0.7)
self.failIf(self.throttler(self.event))
| gpl-3.0 |
TuxmAL/dice-api | app/models/doah_deck.rb | 1176 | # encoding: utf-8
# doah_deck.rb
class DevOpsAgainstHumanityDeck
# github master: 'https://raw.githubusercontent.com/bridgetkromhout/devops-against-humanity/master/cards-DevOpsAgainstHumanity.csv'
def initialize(local_deck = true)
#puts "Sinatra root #{Sinatra::Application::settings.root}."
url = (local_deck)? ::File.join(Sinatra::Application::settings.root, '/resources/'): 'https://raw.githubusercontent.com/bridgetkromhout/devops-against-humanity/master/'
url += 'cards-DevOpsAgainstHumanity.csv'
#puts "Getting deck from #{url}."
csv = CSV.new(open(url, "r:UTF-8"))
@white=[]
@black=[]
csv.each do |row|
@white << row[0] unless (row[0]).nil?
@black << row[1] unless (row[1]).nil?
end
end
def draw(discard = 0)
raise RuntimeError, "You are allowed to discard zero to 10 card at least." if discard < 0
raise RuntimeError, "No more than 10 cards allowed to be discarded." if discard > 10
draw = ''
(0..discard).each do
draw = (" #{@black.sample} ".gsub(/( +)?(\b|[^_])_+(\b|[^_])( +)?/) {" #{@white.sample.downcase} "}).strip.gsub(/\s+([.,!?;:])/, '\1')
end
return draw
end
end
| gpl-3.0 |
roma/roma-java-client | java/client/src/main/java/jp/co/rakuten/rit/roma/client/util/commands/ExpiredSwapAndPushCommand.java | 958 | package jp.co.rakuten.rit.roma.client.util.commands;
import jp.co.rakuten.rit.roma.client.ClientException;
import jp.co.rakuten.rit.roma.client.commands.CommandContext;
public class ExpiredSwapAndPushCommand extends UpdateCommand {
@Override
protected void create(CommandContext context) throws ClientException {
// alist_expired_swap_and_push <key> <expire-time> <bytes>\r\n
// <value>\r\n
StringBuilder sb = (StringBuilder) context.get(CommandContext.STRING_DATA);
sb.append(ListCommandID.STR_ALIST_EXPIRED_SWAP_AND_PUSH)
.append(ListCommandID.STR_WHITE_SPACE)
.append(context.get(CommandContext.KEY))
.append(ListCommandID.STR_WHITE_SPACE)
.append(context.get(UpdateCommand.EXPIRY))
.append(ListCommandID.STR_WHITE_SPACE)
.append(((byte[]) context.get(CommandContext.VALUE)).length)
.append(ListCommandID.STR_CRLF);
context.put(CommandContext.STRING_DATA, sb);
}
} | gpl-3.0 |
ArtisticPhoenix/Evo | Evo/Core/Plexer/PlexerException.php | 1376 | <?php
namespace Evo\Core\Plexer;
use Evo\Core\Error\ErrorException;
use Evo\Debug;
/**
* validate dependancies
*/
if (!defined('EVO_PATH_CORE')) {
die('No direct access allowed!');
}
require_once EVO_PATH_CORE . 'validate_env.php';
/**
*
* (c) 2016 Hugh Durham III
*
* For license information please view the LICENSE file included with this source code.
*
* Suggested Constant Value Serizes
* default error codes 0 - 4,999
* core error codes 5,000 - 9,999
* app error codes 10,000 - 15,000
* plugin error codes 20,000 - 25,000
*
* @author HughDurham {ArtisticPhoenix}
* @package Evo
* @subpackage Plexer
*
*/
class PlexerException extends ErrorException
{
const NOT_CALLABLE = 2000;
const INVALID_INPUT = 2001;
const TOKEN_STREAM_OUT_OF_BOUNDS = 2100;
const UNPARSABLE_TOKEN = 2200;
const UNEXPECTED_END_OF_FILE = 2210;
const UNEXPECTED_TOKEN = 2220;
const UNKNOWN_TOKEN = 2240;
const UNCLOSED_TOKEN = 2260;
const UNDEFINED_TOKEN_CLASS = 2280;
const INVALID_TOKEN = 2300;
const TEMPLATE_UNPARSABLE = 3000;
const INVALID_TOKEN_MAPPER = 3001;
}
| gpl-3.0 |
jspenguin2017/uBlockProtector | src/reporter/index.js | 7352 | // ----------------------------------------------------------------------------------------------------------------- //
// Nano Defender - An anti-adblock defuser
// Copyright (C) 2016-2019 Nano Defender contributors
//
// 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/>.
// ----------------------------------------------------------------------------------------------------------------- //
// Script for quick issue reporter
// ----------------------------------------------------------------------------------------------------------------- //
"use strict";
// ----------------------------------------------------------------------------------------------------------------- //
const knownGood = [
// Wrong page
"addons.mozilla.org",
"chrome.google.com",
"hugoxu.com",
"github.com",
"jspenguin2017.github.io",
"local.ntp",
"www.microsoft.com", // Do not remove "www"
// Bad installation
"blockadblock.com",
"detectadblock.com",
// Other known good
"youtube.com",
];
const knownBad = [
// https://github.com/NanoMeow/QuickReports/issues/903
"browserleaks.com",
];
// ----------------------------------------------------------------------------------------------------------------- //
let initialUrl = "";
// ----------------------------------------------------------------------------------------------------------------- //
const lastReportStorageKey = "quick-issue-reporter-last-report";
const bugReportDomainSuffix = "-nanobugreport.hugoxu.com";
const reportsRateLimit = 900000; // 15 minutes
const detailsLengthLimit = 3072;
const updateDetailsLengthDisplay = () => {
const length = $("#details").prop("value").length;
$("#character-count").text(length.toString() + "/" + detailsLengthLimit.toString());
if (length > detailsLengthLimit)
$("#character-count").addClass("red");
else
$("#character-count").rmClass("red");
};
// ----------------------------------------------------------------------------------------------------------------- //
const appName = (() => {
const manifest = chrome.runtime.getManifest();
return manifest.name + " " + manifest.version;
})();
const showMessage = (msg) => {
$("#msg-specific-error p").html(msg);
$("#msg-specific-error").addClass("open");
};
const domCmp = (domain, matchers) => {
if (domain.endsWith(bugReportDomainSuffix))
return false;
for (const d of matchers) {
if (domain.endsWith(d) && (domain.length === d.length || domain.charAt(domain.length - d.length - 1) === "."))
return true;
}
return false;
};
const randId = () => {
const r = Math.random();
return r.toString(16).substring(2);
};
// ----------------------------------------------------------------------------------------------------------------- //
$("#category").on("change", function () {
if (this.value === "Ads") {
showMessage(
"For missed ads and popups, please report to the <a href='https://forums.lanik.us/'>EasyList Forum</a> " +
"first.",
);
}
if (this.value === "Bug")
$("#url").prop("value", "https://" + randId() + bugReportDomainSuffix + "/").attr("disabled", "");
else
$("#url").prop("value", initialUrl).rmAttr("disabled");
});
$("#details").on("input", updateDetailsLengthDisplay);
updateDetailsLengthDisplay();
$("#send").on("click", async () => {
const category = $("#category").prop("value");
const url = $("#url").prop("value").trim();
const details = $("#details").prop("value");
if (!category)
return void showMessage("Please select an issue type.");
let domain = /^https?:\/\/([^/]+)/.exec(url);
if (!domain)
return void showMessage("Please enter a valid URL.");
domain = domain[1];
if (domCmp(domain, knownGood))
return void $("#msg-known-good").addClass("open");
if (domCmp(domain, knownBad))
return void $("#msg-known-bad").addClass("open");
if (category === "Other" && details.length < 10) {
return void showMessage(
"Please add a quick explanation for the "Other issue" category that you have chosen " +
"(minimum 10 characters).",
);
}
if (category === "Bug" && details.length < 100) {
return void showMessage(
"Please incude a detailed step-by-step reproduction guide for this issue (minimum 100 characters).",
);
}
if (details.length > detailsLengthLimit) {
return void showMessage(
"Additional details can be at most " + detailsLengthLimit.toString() + " characters long.",
);
}
const payload = [
"send",
"Quick Issue Reporter",
navigator.userAgent,
appName,
"",
"[" + category + "] " + url,
"",
];
if (url !== initialUrl) {
payload.push(
"Original URL: `" + initialUrl + "`",
"",
);
}
payload.push(details);
let response;
try {
response = await post(payload.join("\n"));
} catch (err) {
return void $("#msg-generic-error").addClass("open");
}
if (response === "ok") {
localStorage.setItem(lastReportStorageKey, Date.now());
$("#msg-report-sent").addClass("open");
$("#main").addClass("hidden");
} else {
console.error(response);
$("#msg-generic-error").addClass("open");
}
});
$(".popup-container button.float-right").on("click", function () {
this.parentNode.parentNode.classList.remove("open");
});
// ----------------------------------------------------------------------------------------------------------------- //
const init = () => {
let lastReport = localStorage.getItem(lastReportStorageKey);
// Maximum accuracy of integer is about 16 digits
// Cap at 15 digits to be safe, which is still more than enough to represent the next 30 thousand years
if (/^\d{13,15}$/.test(lastReport))
lastReport = parseInt(lastReport);
const now = Date.now();
if (typeof lastReport === "number" && lastReport + reportsRateLimit > now)
$("#msg-rate-limited").addClass("open");
else
$("#main").rmClass("hidden");
};
if (/^\?\d{1,15}$/.test(location.search)) {
chrome.tabs.get(parseInt(location.search.substring(1)), (tab) => {
if (!chrome.runtime.lastError) {
initialUrl = tab.url;
if ($("#url").prop("value").trim() === "")
$("#url").prop("value", tab.url);
}
init();
});
} else {
init();
}
// ----------------------------------------------------------------------------------------------------------------- //
| gpl-3.0 |
jongrant/SpotlightToDesktop | Main/Wallpaper.cs | 1835 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace SpotlightToDesktop
{
public static class Wallpaper
{
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public enum Style : int
{
Tiled,
Centered,
Stretched
}
public static void Set(string fileName, Style style)
{
// convert it to a bitmap
var img = Image.FromFile(fileName);
string tempPath = Path.Combine(Path.GetTempPath(), "Spotlight.bmp");
img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (style == Style.Stretched)
{
key.SetValue(@"WallpaperStyle", "2");
key.SetValue(@"TileWallpaper", "0");
}
if (style == Style.Centered)
{
key.SetValue(@"WallpaperStyle", "1");
key.SetValue(@"TileWallpaper", "0");
}
if (style == Style.Tiled)
{
key.SetValue(@"WallpaperStyle", "1");
key.SetValue(@"TileWallpaper", "1");
}
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
}
}
| gpl-3.0 |
redsolution/django-server-config | config/management/commands/make_config.py | 553 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = '''Usage manage.py make_config [template]
Make specified config file.
Available templates:
init.d
lighttpd
logrotate
monit
httpd
'''
def handle(self, *args, **options):
if not args or len(args) > 1:
print self.help
else:
template = 'config/%s.conf' % args[0]
from config.utils import make_config
print make_config(template)
| gpl-3.0 |
multiplemonomials/Equivalent-Exchange-Reborn | src/main/java/net/multiplemonomials/eer/data/EERExtendedPlayer.java | 5392 | package net.multiplemonomials.eer.data;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import net.multiplemonomials.eer.exchange.EnergyRegistry;
import net.multiplemonomials.eer.exchange.EnergyValue;
import net.multiplemonomials.eer.network.PacketHandler;
import net.multiplemonomials.eer.network.message.MessageEERExtendedPlayerUpdateClient;
import net.multiplemonomials.eer.network.message.MessageEERExtendedPlayerUpdateServer;
import net.multiplemonomials.eer.proxy.CommonProxy;
import net.multiplemonomials.eer.reference.Names;
import net.multiplemonomials.eer.util.ItemHelper;
import net.multiplemonomials.eer.util.LogHelper;
//http://www.minecraftforum.net/forums/mapping-and-modding/mapping-and-modding-tutorials/1571567-1-7-2-1-6-4-eventhandler-and
//coolAlias thank you so much
public class EERExtendedPlayer implements IExtendedEntityProperties
{
private final EntityPlayer player;
public EntityPlayer getBoundPlayer()
{
return player;
}
public Set<ItemStack> learnedItems;
public EERExtendedPlayer(EntityPlayer player)
{
this.player = player;
learnedItems = new HashSet<ItemStack>();
}
public static final EERExtendedPlayer get(EntityPlayer player)
{
return (EERExtendedPlayer) player.getExtendedProperties(Names.Data.EEREXTENDEDPROPERTIES);
}
public static final void register(EntityPlayer player)
{
player.registerExtendedProperties(Names.Data.EEREXTENDEDPROPERTIES, new EERExtendedPlayer(player));
}
@Override
public void saveNBTData(NBTTagCompound compound)
{
NBTTagCompound masterTag = new NBTTagCompound();
if(!learnedItems.isEmpty())
{
// Write the known items to NBT
NBTTagList learnedItemList = new NBTTagList();
for(ItemStack wrappedStack : learnedItems)
{
NBTTagCompound tagCompound = new NBTTagCompound();
wrappedStack.writeToNBT(tagCompound);
learnedItemList.appendTag(tagCompound);
}
masterTag.setTag("learnedItems", learnedItemList);
}
compound.setTag(Names.Data.EEREXTENDEDPROPERTIES, masterTag);
}
@Override
public void loadNBTData(NBTTagCompound compound)
{
// read the known items from NBT
if(compound != null)
{
NBTTagCompound masterTag = (NBTTagCompound) compound.getTag(Names.Data.EEREXTENDEDPROPERTIES);
NBTTagList learnedItemList = masterTag.getTagList("learnedItems", 10);
for(int currentIndex = 0; currentIndex < learnedItemList.tagCount(); ++currentIndex)
{
NBTTagCompound tagCompound = learnedItemList.getCompoundTagAt(currentIndex);
ItemStack itemStackToAdd = ItemStack.loadItemStackFromNBT(tagCompound);
if(itemStackToAdd == null)
{
LogHelper.error("[EER] Could not load a learned item from NBT");
continue;
}
EnergyValue energyValue = EnergyRegistry.getInstance().getEnergyValue(itemStackToAdd);
if(energyValue == null)
{
LogHelper.error("[EER] Could not load the EMC value of a learned item");
continue;
}
learnedItems.add(itemStackToAdd);
}
}
}
/**
* Adds the ItemStack to the database of learned items.
* @param itemToLearn
*/
public void learnNewItem(ItemStack itemToLearn)
{
if(itemToLearn != null)
{
ItemStack stackToAdd = new ItemStack(itemToLearn.getItem(), 1, itemToLearn.getItemDamage());
if(!ItemHelper.containsItem(learnedItems, stackToAdd))
{
learnedItems.add(stackToAdd);
syncExtendedPlayer(player, this);
}
}
}
private static final String getSaveKey(EntityPlayer player)
{
// no longer a username field, so use the command sender name instead:
return player.getCommandSenderName() + ":" + Names.Data.EEREXTENDEDPROPERTIES;
}
public static final void loadProxyData(EntityPlayer player)
{
EERExtendedPlayer playerData = EERExtendedPlayer.get(player);
NBTTagCompound savedData = CommonProxy.getEntityData(getSaveKey(player));
if (savedData != null)
{
playerData.loadNBTData(savedData);
}
syncExtendedPlayer(player, playerData);
}
public static void saveProxyData(EntityPlayer player)
{
EERExtendedPlayer playerData = EERExtendedPlayer.get(player);
NBTTagCompound savedData = new NBTTagCompound();
playerData.saveNBTData(savedData);
CommonProxy.storeEntityData(getSaveKey(player), savedData);
}
public static void syncExtendedPlayer(EntityPlayer player, EERExtendedPlayer playerData)
{
if(!player.worldObj.isRemote)
{
PacketHandler.INSTANCE.sendTo(new MessageEERExtendedPlayerUpdateClient(playerData), (EntityPlayerMP)player);
}
else
{
PacketHandler.INSTANCE.sendToServer(new MessageEERExtendedPlayerUpdateServer(playerData));
}
}
@Override
public void init(Entity entity, World world)
{
}
}
| gpl-3.0 |
tarceri/phoronix-test-suite | pts-core/objects/pts_math.php | 2985 | <?php
/*
Phoronix Test Suite
URLs: http://www.phoronix.com, http://www.phoronix-test-suite.com/
Copyright (C) 2009 - 2011, Phoronix Media
Copyright (C) 2009 - 2011, Michael Larabel
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/>.
*/
class pts_math
{
public static function geometric_mean($values)
{
return pow(array_product($values), (1 / count($values)));
}
public static function harmonic_mean($values)
{
$b = 0;
$c = 0;
foreach($values as $value)
{
if($value != 0)
{
$b += 1 / $value;
$c++;
}
}
return $b != 0 ? $c / $b : 0;
}
public static function standard_error($values)
{
self::clean_numeric_array($values);
return empty($values) ? 0 : (self::standard_deviation($values) / sqrt(count($values)));
}
public static function standard_deviation($values)
{
self::clean_numeric_array($values);
$count = count($values);
if($count < 2)
{
return 0;
}
$total = array_sum($values);
$mean = $total / $count;
$standard_sum = 0;
foreach($values as $value)
{
$standard_sum += pow(($value - $mean), 2);
}
return sqrt($standard_sum / ($count - 1));
}
public static function percent_standard_deviation($values)
{
if(count($values) == 0)
{
// No values
return 0;
}
$standard_deviation = pts_math::standard_deviation($values);
$average_value = array_sum($values) / count($values);
return $average_value != 0 ? ($standard_deviation / $average_value * 100) : 0;
}
public static function set_precision($number, $precision = 2)
{
// This is better than using round() with precision because of the $precision is > than the current value, 0s will not be appended
return number_format($number, $precision, '.', '');
}
public static function find_percentile($values, $quartile)
{
sort($values, SORT_NUMERIC);
$qr_index = count($values) * $quartile;
$qr = $values[floor($qr_index)];
return $qr;
}
public static function first_quartile($values)
{
return self::find_percentile($values, 0.25);
}
public static function third_quartile($values)
{
return self::find_percentile($values, 0.75);
}
public static function inter_quartile_range($values)
{
return self::third_quartile($values) - self::first_quartile($values);
}
protected static function clean_numeric_array(&$values)
{
foreach($values as $i => $value)
{
if(!is_numeric($value))
{
unset($values[$i]);
}
}
}
}
?>
| gpl-3.0 |
DurandetErwan/StageDUT | Projet_Son/PlayAudio/PlayAudio/obj/Debug/android/src/playaudio/playaudio/R.java | 813 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package playaudio.playaudio;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int playButton=0x7f060000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class raw {
public static final int test=0x7f040000;
}
public static final class string {
public static final int app_name=0x7f050001;
public static final int playAudioText=0x7f050000;
}
}
| gpl-3.0 |
Drakuwa/aBusTripMK | src/org/andnav/osm/util/NetworkLocationIgnorer.java | 1422 | package org.andnav.osm.util;
import android.location.LocationManager;
/**
*
* A class to check whether we want to use a location.
* If there are multiple location providers, i.e. network and GPS,
* then you want to ignore network locations shortly after a GPS location
* because you will get another GPS location soon.
*
* @author Neil Boyd
*
*/
public class NetworkLocationIgnorer {
/**
* The time we wait after the last gps location before displaying
* a non-gps location.
*/
private static final long GPS_WAIT_TIME = 20000; // 20 seconds
/** last time we got a location from the gps provider */
private long mLastGps = 0;
/**
* Whether we should ignore this location.
* @param pProvider the provider that provided the location
* @param pTime the time of the location
* @return true if we should ignore this location, false if not
*/
public boolean shouldIgnore(final String pProvider, final long pTime) {
if (LocationManager.GPS_PROVIDER.equals(pProvider)) {
mLastGps = pTime;
} else {
if (pTime < mLastGps + GPS_WAIT_TIME) {
return true;
}
}
return false;
}
}
| gpl-3.0 |
ArmandDelessert/WarTanks | WarTanks/src/gamemanager/map/Cell.java | 1169 | /**
* Projet : WarTanks
* Auteur : Armand Delessert
* Date : 21.03.2015
*/
package gamemanager.map;
/**
*
* @author Armand
*/
public abstract class Cell {
/*** Getters ***/
public Class cellType() {
return this.getClass();
}
public Cell destroyCell() {
return null;
}
/*** Méthodes ***/
public String toString() {
return null;
}
}
/*** Cases libres ***/
// Case libre
class FreeCell extends Cell {
public String toString() {
return " ";
}
}
// Mur cassé
class BrokenWall extends Cell {
public String toString() {
return " ";
}
}
// Tache noire (après une explosion)
class BlackSpot extends Cell {
public String toString() {
return " ";
}
}
/*** Obstacles cassables ***/
// Mur cassable
class BreakableWall extends Cell {
public String toString() {
return "+";
}
public Cell destroyCell() {
return GlobalCell.brokenWall;
}
}
// Epave
class Wreck extends Cell {
public String toString() {
return "w";
}
public Cell destroyCell() {
return GlobalCell.blackSpot;
}
}
/*** Obstacles incassables ***/
// Mur incassable
class UnbreakableWall extends Cell {
public String toString() {
return "x";
}
}
| gpl-3.0 |
SYSC-3010-F5/AVA-SH | src/server/datatypes/WeatherData.java | 2260 | package server.datatypes;
//class to automatically parse the raw JSON from Open Weather Map
import org.json.JSONArray;
import org.json.JSONObject;
public class WeatherData
{
private float temperature;
private String weatherType;
private String weatherDescription;
private String city;
private String country;
private float humidity;
private static final float KELVIN_TO_CELSIUS_OFFSET = (float) 273.15;
public static final int TEMPERATURE = 0;
public static final int WEATHER_TYPE = 1;
public static final int WEATHER_DESCRIPTION = 2;
public static final int HUMIDITY = 3;
public static final int CITY = 4;
public static final int COUNTRY = 5;
//rawData should be the raw JSON returned by OpenWeatherMap
public WeatherData(JSONObject rawData)
{
JSONObject init = rawData.getJSONArray("weather").getJSONObject(0);
weatherType = init.getString("main");
weatherDescription = init.getString("description");
init = rawData.getJSONObject("main");
//OpenWeatherMap by default returns temperature in kelvin
temperature = (float) init.getDouble("temp") - KELVIN_TO_CELSIUS_OFFSET;
humidity = (float) init.getDouble("humidity");
city = rawData.getString("name");
init = rawData.getJSONObject("sys");
country = init.getString("country");
}
//rawData should be the raw JSON returned by OpenWeatherMap
public WeatherData(String rawData)
{
JSONObject data = new JSONObject(rawData);
JSONObject init = data.getJSONArray("weather").getJSONObject(0);
weatherType = init.getString("main");
weatherDescription = init.getString("description");
init = data.getJSONObject("main");
//OpenWeatherMap by default returns temperature in kelvin
temperature = (float) init.getDouble("temp") - KELVIN_TO_CELSIUS_OFFSET;
humidity = (float) init.getDouble("humidity");
city = data.getString("name");
init = data.getJSONObject("sys");
country = init.getString("country");
}
public String[] getWeatherData()
{
String str[] = new String[6];
str[0] = String.format("%.2f", temperature);
str[1] = weatherType;
str[2] = weatherDescription;
str[3] = String.format("%.2f", humidity);
str[4] = city;
str[5] = country;
return str;
}
}
| gpl-3.0 |
EterniaLogic/EterniaLibrary | src/Simulation/RPG/Entities/Creature/Creature.cpp | 2683 | #include "Creature.h"
// Default values provided here are based on an average human male
Creature::Creature(){
classname="[Creature]";
alive=true; // would be nice to have
energy.health = &health;
health.energy = &energy;
_type=CT_Unknown;
_class=CCL_NONE;
weight_kg = 81; // average human male
health.uselimbs = true;
health.regrowlimbs = false; // most creatures cannot regrow limbs
health.useblood = false;
health.immortal = false; // most creatures can be disconnected from their souls.
energy.usefood=true; // use calories
energy.usewater=true; // use calories
energy.canstarvetodeath = true;
energy.createswaste = true;
stats.canlevel = false; // Gods cannot gain material power
stats.canlevel = true;
pools.mp = pools.MPMax = 100; // soul also has MP alongside Psi.
pools.sp = pools.SPMax = 100;
mother = father = 0x0;
_initSerializers(); // only for Creature, make other names for function?
}
void Creature::_initSerializers(){
addSerial(&alive, "alive", SSE_bool);
addSerial(&weight_kg, "weight_kg", SSE_double);
addSerial(&age, "age", SSE_double);
addSerial(&_type, "type", SSE_Int);
addSerial(&_class, "class", SSE_Int);
addSerial(&spells, "spells", SSE_LinkedList);
addSerial(&skills, "skills", SSE_LinkedList);
addSerial(&actionqueue, "actionqueue", SSE_LinkedList);
addSerial(&mother->name, "mother_name", SSE_CharString);
addSerial(&father->name, "mother_name", SSE_CharString);
//addSerial(&children, "children", SSE_LinkedList);
addSerial(&soul, "soul", SSE_SSerializer);
addSerial(&health, "health", SSE_SSerializer);
addSerial(&energy, "energy", SSE_SSerializer);
addSerial(&stats, "stats", SSE_SSerializer);
addSerial(&pools, "pools", SSE_SSerializer);
}
void Creature::_tick(double seconds){
if(!alive) return;
// humans do selfheal, but REALLY slowly
if(energy.usefood) energy.starve(seconds); // use food! if possible, starve to death!
if(energy.usewater) energy.thirst(seconds);
health.selfheal(energy, seconds);
if(!health.isAlive()){
alive=false;
}
age = age*(seconds/(60*60*24*365)); // add to age
soul._tick(seconds);
pools.tick(seconds);
health.tick(seconds);
tick(seconds);
}
void Creature::_movetick(double seconds){
// move creature
// ?
movetick(seconds);
}
void Creature::tick(double seconds){
// provided by subclass
}
void Creature::movetick(double seconds){
// provided by subclass
}
| gpl-3.0 |
veskuh/Tweetian | qml/tweetian-harmattan/TweetPageJS.js | 12617 | /*
Copyright (C) 2012 Dickson Leong
This file is part of Tweetian.
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/>.
*/
var retweeters = []
var favoriters = []
var PIC_SERVICES = [
{
regexp: /http:\/\/twitpic.com\/\w+/ig,
getPicUrl: function(link) {
var twitpicId = link.substring(19)
var url = {
full: "http://twitpic.com/show/full/" + twitpicId,
thumb: "http://twitpic.com/show/thumb/" + twitpicId
}
return url
}
},
{
regexp: /http:\/\/(twitter.)?yfrog.com\/\w+/ig,
getPicUrl: function(link) {
var yfrogId = link.substring(link.indexOf("yfrog.com/") + 10)
var url = {
full: "http://yfrog.com/" + yfrogId + ":medium",
thumb: "http://yfrog.com/" + yfrogId + ":small"
}
return url
}
},
{
regexp: /http:\/\/instagram\.com\/p\/[^"]+/ig,
getPicUrl: function(link) {
link = link.replace(/\/?$/, '/') // ensure a trailing slash
var url = {
full: link + "media/?size=l",
thumb: link + "media/?size=t"
}
return url
}
},
{
regexp: /http:\/\/img.ly\/\w+/ig,
getPicUrl: function(link) {
var imglyId = link.substring(14)
var url = {
full: "http://img.ly/show/full/"+ imglyId,
thumb: "http://img.ly/show/thumb/"+ imglyId
}
return url
}
},
{
regexp: /http:\/\/moby.to\/\w+/ig,
getPicUrl: function(link) {
var url = { full: link + ":full", thumb: link + ":square" }
return url
}
},
{
regexp: /http:\/\/lockerz.com\/[^"]+/ig,
getPicUrl: function(link) {
var url = {
full: "http://api.plixi.com/api/tpapi.svc/imagefromurl?size=big&url=" + link,
thumb: "http://api.plixi.com/api/tpapi.svc/imagefromurl?size=small&url=" + link
}
return url
}
},
{
regexp: /http:\/\/molo.me\/p\/\w+/ig,
getPicUrl: function(link) {
var molomeId = link.substring(17)
var url = {
full: "http://p.molo.me/"+ molomeId,
thumb: "http://p135x135.molo.me/"+ molomeId +"_135x135"
}
return url
}
},
{
regexp: /http:\/\/(m\.)?imgur.com(?!\/a\/)\/((gallery\/)?(r\/[\w\.]+\/)?)\w+/ig,
// "http://" (optionally "m.") then "imgur.com" then not "/a/" but either:
// "gallery/" or "r/lettersordots/", then some letters.
// eg http://imgur.com/gallery/iU1SwYe or http://imgur.com/iU1SwYe
// or http://m.imgur.com/gallery/iU1SwYe or http://m.imgur.com/iU1SwYe
// or Reddit http://imgur.com/r/funny/V1Xp2rQ or http://m.imgur.com/r/reddit.com/V1Xp2rQ
// but not albums: http://imgur.com/a/Jexvo or http://m.imgur.com/a/Jexvo
getPicUrl: function(link) {
link = link.replace(/\/+$/, '') // remove trailing slashes
// Grab the ID after last slash:
var imgurId = link.substring(link.lastIndexOf("/") + 1)
var url = {
full: "http://i.imgur.com/" + imgurId + ".jpg",
thumb: "http://i.imgur.com/" + imgurId + "s.jpg"
}
return url
}
},
{
regexp: /http:\/\/twitgoo.com\/\w+/ig,
getPicUrl: function(link) {
var url = { full: link + "/img", thumb: link + "/thumb" }
return url
}
},
{
regexp: /http:\/\/sdrv.ms\/[^"]+/ig,
getPicUrl: function(link) {
var url = {
full: "https://apis.live.net/v5.0/skydrive/get_item_preview?type=normal&url=" + link,
thumb: "https://apis.live.net/v5.0/skydrive/get_item_preview?type=album&url=" + link
}
return url
}
},
{
regexp: /http:\/\/glui\.me\/\?i=\w+\/[^"/]+\//ig,
getPicUrl: function(link) {
link = link.replace(/\/+$/, '') // remove trailing slashes
link = link.replace(/_/g, "%20") // replace all _ with %20
link = link.replace("://glui.me/?i=", "://dl.dropboxusercontent.com/s/")
var url = { full: link, thumb: link }
return url
}
},
{
regexp: /http:\/\/www\.wikipaintings\.org\/..\/(?!tag)(?!search)[\w-]+\/[\w-]+/ig,
getPicUrl: function(link) {
link = link.replace(/#.*$/,'') // strip any anchor
link = link.replace('http://www.', 'http://uploads.')
link = link.replace(/\.org\/..\//, '.org/images/')
link = link + ".jpg"
var url = {
full: link,
thumb: link + "!BlogSmall.jpg"
}
return url
}
},
{
regexp: /https?:\/\/[^"]+?\.(?:jpe?g|png|gif)(?=")/gi,
getPicUrl: function (link) { return { full: link, thumb: link }; }
}
]
function createPicThumb() {
// if there is no link in the tweet, just return
if (tweet.richText.indexOf("href=\"http") < 0)
return
// Flickr pic
var flickrLinks = tweet.richText.match(Flickr.FLICKR_LINK_REGEXP)
if (flickrLinks !== null) {
flickrLinks.forEach(function(url) {
Flickr.getSizes(constant, url, function(full, thumb, link) {
thumbnailModel.append({type: "image", full: full, thumb: thumb, link: link})
})
})
}
PIC_SERVICES.forEach(function(service) {
var links = tweet.richText.match(service.regexp)
if (links === null) return
links.forEach(function(link) {
var urls = service.getPicUrl(link)
var picObj = { type: "image", full: urls.full, thumb: urls.thumb, link: link }
thumbnailModel.append(picObj)
})
})
}
function createYoutubeThumb() {
var youtubeLinks = tweet.richText.match(YouTube.YOUTUBE_LINK_REGEXP)
if (youtubeLinks == null) return
for (var i=0; i<youtubeLinks.length; i++) {
YouTube.getVideoThumbnailAndLink(constant, youtubeLinks[i], function(thumb, rstpLink) {
thumbnailModel.append({type: "video", thumb: thumb, full: "", link: rstpLink})
})
}
}
function createMapThumb() {
if (!tweet.latitude || !tweet.longitude) return
var thumbnailURL = Maps.getMaps(constant, tweet.latitude, tweet.longitude,
constant.thumbnailSize, constant.thumbnailSize)
thumbnailModel.append({type: "map", thumb: thumbnailURL, full: "", link: ""})
}
function expandTwitLonger() {
var twitLongerLink = tweet.richText.match(/http:\/\/tl.gd\/\w+/)
if (twitLongerLink == null) return
TwitLonger.getFullTweet(constant, twitLongerLink[0], getTwitLongerTextOnSuccess, commonOnFailure)
header.busy = true
}
function getConversationFromTimelineAndMentions() {
if (!tweet.inReplyToStatusId) return
var msg = {
ancestorModel: ancestorModel, descendantModel: descendantModel,
timelineModel: mainPage.timeline.model, mentionsModel: mainPage.mentions.model,
inReplyToStatusId: tweet.inReplyToStatusId
}
conversationParser.sendMessage(msg)
// header.busy = true
}
function constructReplyText(tweet) {
var replyText = "@" + tweet.retweetScreenName + " "
// if this is a retweet, include the original author screen name
if (tweet.isRetweet)
replyText += "@" + tweet.screenName + " "
// check for other mentions in the tweet
var mentionsArray = tweet.richText.match(/href="@\w+/g) || []
mentionsArray.forEach(function(mentions) {
mentions = mentions.substring(6)
if (mentions.toLowerCase() !== "@" + settings.userScreenName.toLowerCase())
replyText += mentions + " "
})
return replyText
}
function constructRetweetText(tweet) {
var retweetText = "RT @" + tweet.retweetScreenName + ": "
// if it is a retweet, include the original author screen name
if (tweet.isRetweet)
retweetText += "RT @" + tweet.screenName + ": "
retweetText += tweet.plainText
return retweetText
}
function deleteTweetOnSuccess(data) {
mainPage.timeline.removeTweet(data.id_str)
loadingRect.visible = false
infoBanner.showText(qsTr("Tweet deleted successfully"))
pageStack.pop()
}
function favouriteOnSuccess(data, isFavourite) {
mainPage.timeline.favouriteTweet(data.id_str)
mainPage.mentions.favouriteTweet(data.id_str)
favouritedTweet = isFavourite
if (favouritedTweet) infoBanner.showText(qsTr("Tweet favourited succesfully"))
else infoBanner.showText(qsTr("Tweet unfavourited successfully"))
header.busy = false
}
function getTwitLongerTextOnSuccess(fullTweetText) {
tweetTextText.text = fullTweetText;
header.busy = false
}
function translateTokenOnSuccess(token) {
cache.translationToken = token
Translation.translate(constant, cache.translationToken, tweet.plainText, settings.translateLangCode,
translateOnSuccess, commonOnFailure)
}
function translateOnSuccess(data) {
if (data.indexOf("ArgumentOutOfRangeException") === 0)
infoBanner.showText(qsTr("Unable to translate tweet"))
else if (data.indexOf("TranslateApiException") === 0)
infoBanner.showText(qsTr("Translation limit reached"))
else {
translatedTweetLoader.sourceComponent = translatedTweetComponent
translatedTweetLoader.item.translatedText = data
}
header.busy = false
}
function commonOnFailure(status, statusText) {
infoBanner.showHttpError(status, statusText)
header.busy = false
loadingRect.visible = false
}
function addToPocket(link) {
if (!settings.pocketUsername || !settings.pocketPassword) {
var message = qsTr("You are not signed in to your Pocket account. Please sign in to your Pocket account first under the \"Account\" tab in Settings.")
dialog.createMessageDialog(qsTr("Pocket - Not Signed In"), message)
return
}
Pocket.addPage(constant, settings.pocketUsername, settings.pocketPassword, link, tweet.plainText,
tweet.id, function() {
loadingRect.visible = false
infoBanner.showText(qsTr("The link has been sent to Pocket successfully"))
}, function(errorCode) {
loadingRect.visible = false
infoBanner.showText(qsTr("Error sending link to Pocket (%1)").arg(errorCode))
})
loadingRect.visible = true
}
function addToInstapaper(link) {
if (!settings.instapaperToken || !settings.instapaperTokenSecret) {
var message = qsTr("You are not sign in to your Instapaper account. Please sign in to your Instapaper account first under the \"Account\" tab in the Settings.")
dialog.createMessageDialog(qsTr("Instapaper - Not Signed In"), message)
return
}
Instapaper.addBookmark(constant, settings.instapaperToken, settings.instapaperTokenSecret, link,
tweet.plainText, function() {
loadingRect.visible = false
infoBanner.showText(qsTr("The link has been sent to Instapaper successfully"))
}, function(errorCode) {
loadingRect.visible = false
infoBanner.showText(qsTr("Error sending link to Instapaper (%1)").arg(errorCode))
})
loadingRect.visible = true
}
function createDeleteTweetDialog() {
var message = qsTr("Do you want to delete this tweet?")
dialog.createQueryDialog(qsTr("Delete Tweet"), "", message, function() {
Twitter.postDeleteStatus(tweet.id, deleteTweetOnSuccess, commonOnFailure)
loadingRect.visible = true
})
}
| gpl-3.0 |
dwengovzw/Ardublock-for-Dwenguino | ardublock-master/src/main/java/com/ardublock/translator/block/Dwenguino/Tsop.java | 1172 | package com.ardublock.translator.block.Dwenguino;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.TranslatorBlock;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
public class Tsop extends TranslatorBlock
{
public static final String REMOTE = "int __remote(int pinNumber)\n{\nint value = 0;\nint time = pulseIn(15,LOW);\n if(time>2000)\n{\nfor(int counter1=0;counter1<12;counter1++)\n{\nif(pulseIn(15,LOW)>1000)\n{\nvalue = value + (1<< counter1);\n}\n}\n}\nreturn value;\n}\n\n";
public Tsop(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label)
{
super(blockId, translator, codePrefix, codeSuffix, label);
}
@Override
public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
String ret;
TranslatorBlock translatorBlock;
translatorBlock = this.getRequiredTranslatorBlockAtSocket(0);
translator.addDefinitionCommand(REMOTE);
ret = "__remote(";
ret = ret + translatorBlock.toCode();
ret = ret + ")";
return codePrefix + ret + codeSuffix;
}
}
| gpl-3.0 |
themiwi/freefoam-debian | src/thermophysicalModels/radiation/submodels/absorptionEmissionModel/binaryAbsorptionEmission/binaryAbsorptionEmission.H | 3791 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::radiation::binaryAbsorptionEmission
Description
Radiation coefficient based on two absorption models
SourceFiles
binaryAbsorptionEmission.C
\*---------------------------------------------------------------------------*/
#ifndef radiationBinaryAbsorptionEmission_H
#define radiationBinaryAbsorptionEmission_H
#include <radiation/absorptionEmissionModel.H>
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace radiation
{
/*---------------------------------------------------------------------------*\
Class binaryAbsorptionEmission Declaration
\*---------------------------------------------------------------------------*/
class binaryAbsorptionEmission
:
public absorptionEmissionModel
{
// Private data
//- Coefficients dictionary
dictionary coeffsDict_;
//- First absorption model
autoPtr<absorptionEmissionModel> model1_;
//- Second absorption model
autoPtr<absorptionEmissionModel> model2_;
public:
//- Runtime type information
TypeName("binaryAbsorptionEmission");
// Constructors
//- Construct from components
binaryAbsorptionEmission
(
const dictionary& dict,
const fvMesh& mesh
);
// Destructor
virtual ~binaryAbsorptionEmission();
// Member Operators
// Access
// Absorption coefficient
//- Absorption coefficient for continuous phase
virtual tmp<volScalarField> aCont(const label bandI = 0) const;
//- Absorption coefficient for dispersed phase
virtual tmp<volScalarField> aDisp(const label bandI = 0) const;
// Emission coefficient
//- Emission coefficient for continuous phase
virtual tmp<volScalarField> eCont(const label bandI = 0) const;
//- Emission coefficient for dispersed phase
virtual tmp<volScalarField> eDisp(const label bandI = 0) const;
// Emission contribution
//- Emission contribution for continuous phase
virtual tmp<volScalarField> ECont(const label bandI = 0) const;
//- Emission contribution for continuous phase
virtual tmp<volScalarField> EDisp(const label bandI = 0) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace radiation
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************ vim: set sw=4 sts=4 et: ************************ //
| gpl-3.0 |
jmesmon/trifles | udp-spam/src/main.rs | 395 | use tokio::net;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
let sock = net::UdpSocket::bind("0.0.0.0:0").await?;
sock.set_broadcast(true)?;
let addr = "192.168.6.255:2000";
let buf = b"hello\r\n";
loop {
sock.send_to(&buf[..], addr).await?;
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
}
| gpl-3.0 |
ac2cz/FoxTelem | src/telemetry/FoxBPSK/FoxBPSKHeader.java | 3341 | package telemetry.FoxBPSK;
import common.Config;
import common.FoxSpacecraft;
import common.Spacecraft;
import decoder.FoxDecoder;
import telemetry.BitArrayLayout;
import telemetry.Header;
import telemetry.TelemFormat;
public class FoxBPSKHeader extends Header {
// Extended Mode Bits that are only in FoxId 6 and later
int safeMode;
int healthMode;
int scienceMode;
int cameraMode;
int minorVersion;
TelemFormat telemFormat;
public static final String ID_FIELD = "satelliteId";
public static final String TYPE_FIELD = "type";
public static final String RESET_FIELD = "resetCnt";
public static final String UPTIME_FIELD = "uptime";
public static final String PROTOCOL_VERSION_FIELD = "protocolVersion";
public static final String SAFE_MODE = "inSafeMode";
public static final String HEALTH_MODE = "inHealthMode";
public static final String SCIENCE_MODE = "inScienceMode";
public FoxBPSKHeader(BitArrayLayout layout, TelemFormat telemFormat) {
super(TYPE_EXTENDED_HEADER, layout);
this.telemFormat = telemFormat;
MAX_BYTES = telemFormat.getInt(TelemFormat.HEADER_LENGTH);
rawBits = new boolean[MAX_BYTES*8];
}
public int getType() { return type; }
/**
* Take the bits from the raw bit array and copy them into the fields
*/
public void copyBitsToFields() {
if (rawBits != null) { // only convert if we actually have a raw binary array. Otherwise this was loaded from a file and we do not want to convert
if (this.layout.fieldName != null) {
// We have a layout, so use that. GOLF-T and later
super.copyBitsToFields();
id = getRawValue(ID_FIELD);
resets = getRawValue(RESET_FIELD);
uptime = getRawValue(UPTIME_FIELD);
type = getRawValue(TYPE_FIELD);
minorVersion = getRawValue(PROTOCOL_VERSION_FIELD);
safeMode = getRawValue(SAFE_MODE);
healthMode = getRawValue(HEALTH_MODE);
scienceMode = getRawValue(SCIENCE_MODE);
setMode();
} else {
super.copyBitsToFields();
type = nextbits(4);
if (id == 0) // then take the foxId from the next 8 bits
id = nextbits(8);
if (id >= Spacecraft.FIRST_FOXID_WITH_MODE_IN_HEADER) { // Post Fox-1E BPSK has mode in header
safeMode = nextbits(1);
healthMode = nextbits(1);
scienceMode = nextbits(1);
cameraMode = nextbits(1);
minorVersion = nextbits(4);
}
setMode();
}
}
}
public void setMode() {
newMode = FoxSpacecraft.NO_MODE;
if (id >= Spacecraft.FIRST_FOXID_WITH_MODE_IN_HEADER) {
if (safeMode != 0 ) newMode = FoxSpacecraft.SAFE_MODE;
if (healthMode != 0 ) newMode = FoxSpacecraft.HEALTH_MODE;
if (scienceMode != 0 ) newMode = FoxSpacecraft.SCIENCE_MODE;
if (cameraMode != 0 ) newMode = FoxSpacecraft.CAMERA_MODE;
}
}
public boolean isValid() {
copyBitsToFields();
if (Config.satManager.validFoxId(id))
return true;
return false;
}
// TODO: This needs to be the 1E frame types
public boolean isValidType(int t) {
assert(false);
return false;
}
public String toString() {
copyBitsToFields();
String s = new String();
s = s + "ID: " + FoxDecoder.dec(id)
+ " RESET COUNT: " + FoxDecoder.dec(resets)
+ " UPTIME: " + FoxDecoder.dec(uptime)
+ " TYPE: " + FoxDecoder.dec(type);
if (id >= Spacecraft.FIRST_FOXID_WITH_MODE_IN_HEADER)
s = s + " - MODE: " + newMode;
return s;
}
}
| gpl-3.0 |
mikellow/animation-tool | app/js/animation-tool-base.js | 1740 | (function () {
"use strict";
var form = document.getElementById('transformationsForm');
console.log('form elemenets', form.elements);
var transformedElement = document.getElementById('transformed');
var transformProperties = {};
var i = 0;
var iMax = form.elements.length;
for(;i < iMax; i++){
form.elements[i].addEventListener('input', function (event) {
var cssProperty = this.dataset.property;
var unit = this.dataset.unit;
var value = this.value;
console.log('cssProperty:', cssProperty, value, unit);
handleCssProperty(transformedElement, cssProperty, value, unit);
});
}
function handleCssProperty (element, property, value, unit) {
if (transformProperties[property]) {
transformProperties[property].value = value;
} else {
transformProperties[property] = { 'name': property, 'value': value, 'unit': unit};
}
console.log(transformProperties);
updateElementStyle(element);
updateInputsValues(transformProperties[property]);
}
function updateInputsValues (property) {
var elements = form.elements[property.name];
var i = 0;
var max = elements.length;
for (; i < max; i++) {
elements[i].value = property.value;
}
}
function updateElementStyle (element) {
var styleStr ='';
var prop;
for (var property in transformProperties) {
prop = transformProperties[property];
console.log('prop', prop);
styleStr += prop.name + '(' + prop.value + prop.unit + ') ';
}
console.log('styleStr', styleStr);
element.style.WebkitTransform = styleStr;
// Code for IE9
element.style.msTransform = styleStr;
// Standard syntax
element.style.transform = styleStr;
}
})(); | gpl-3.0 |
cfrioux/MeneTools | setup.py | 2387 | # -*- coding: utf-8 -*-
# Copyright (C) 2017-2021 Clémence Frioux & Arnaud Belcour - Inria Dyliss - Pleiade
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
from setuptools import setup
import menetools
setup(
name = 'MeneTools',
version = menetools.__version__,
url = 'https://github.com/cfrioux/MeneTools',
download_url = f'https://github.com/cfrioux/MeneTools/tarball/{menetools.__version__}',
license = 'GPLv3+',
description = 'Metabolic Network Topology Analysis Tools',
long_description = 'Python Metabolic Network Topology Tools. Analyze the \
topology of metabolic networks. Explore producibility, production paths and \
needed initiation sources. \
More information on usage and troubleshooting on Github: https://github.com/cfrioux/MeneTools',
author = 'Clemence Frioux',
author_email = '[email protected]',
classifiers =[
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Unix',
],
packages = ['menetools'],
package_dir = {'menetools' : 'menetools'},
package_data = {'menetools' : ['encodings/*.lp']},
#scripts = ['menetools/menecof.py','menetools/menescope.py','menetools/menepath.py','menetools/menecheck.py'],
entry_points = {'console_scripts': ['mene = menetools.__main__:main']},
install_requires = ['clyngor_with_clingo']
)
| gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.