code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',
array( // the dialog
'id'=>'dialogTimetracker',
'options'=>array(
'title'=>'Log Time',
'autoOpen'=>false,
'modal'=>true,
'width'=>'420',
'height'=>'auto',
'minHeight'=>'350',
//'close' => 'js:function(){location.reload();}',
),
));
?>
<div class="timetrackerForm"></div>
<?php $this->endWidget();?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',
array( // the dialog
'id'=>'dialogModal',
'options'=>array(
'title'=>'Issue Transition',
'autoOpen'=>false,
'modal'=>true,
'width'=>'390',
'height'=>'auto',
'minHeight'=>'600',
//'close' => 'js:function(){location.reload();}',
),
));
?>
<div class="modalForm"></div>
<?php $this->endWidget();?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',
array( // the dialog
'id'=>'dialogRelated',
'options'=>array(
'title'=>'New Related Issue',
'autoOpen'=>false,
'modal'=>true,
'width'=>'420',
'height'=>'auto',
'minHeight'=>'300',
'close' => 'js:function(){location.reload();}',
),
));
?>
<div class="relatedForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function relatedJS()
{
<?php echo CHtml::ajax(array(
'url'=>array('issue/related/'.$model->id),
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogRelated div.relatedForm').html(data.div);
$('#dialogRelated div.relatedForm form').submit(relatedJS);
}
else
{
$('#dialogRelated div.relatedForm').html(data.div);
setTimeout(\"$('#dialogRelated').dialog('close') \",3000);
}
} ",
))
?>;
return false;
}
function logTime()
{
<?php echo CHtml::ajax(array(
'url'=>array('/timetracker/create/issue/'.$model->id),
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogTimetracker div.timetrackerForm').html(data.div);
$('#dialogTimetracker div.timetrackerForm form').submit(logTime);
}
else
{
$('#dialogTimetracker div.timetrackerForm').html(data.div);
setTimeout(\"$('#dialogTimetracker').dialog('close') \",3000);
}
} ",
))
?>;
return false;
}
function updateJS(url,title)
{
if (typeof(url)=='string'){
_dialogurl = url;
_dialogtitle = title;
}
<?php echo CHtml::ajax(array(
'url' => 'js:_dialogurl',
'data'=> "js:$(this).serialize()",
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
$('.ui-dialog-title').html(_dialogtitle);
if (data.status == 'failure')
{
$('#dialogModal div.modalForm').html(data.div);
$('#dialogModal div.modalForm form').submit(updateJS);
}
else
{
$('#dialogModal div.modalForm').html(data.div);
setTimeout(\"$('#dialogModal').dialog('close') \",3000);
}
} ",
))
?>;
return false;
}
function reloadInfo(data)
{
//$('#button-Imonit').css("display", "none");
var labelOn = 'I\'m on It!';
var labelOff = 'I\'m not on it anymore!';
var label = labelOn;
var addClass = 'btn-success';
var removeClass = 'btn-danger';
alert($('#button-Imonit').text());
if($('#button-Imonit').text() == labelOn){
label = labelOff;
addClass = 'btn-danger';
removeClass = 'btn-success';
}
$('#button-Imonit').html(label);
$('#button-Imonit').switchClass(removeClass, addClass);
$('#statusMsg').html(data).fadeIn().animate({opacity: 1.0}, 15000).fadeOut("slow");
}
function reloadList(data, grid)
{
$.fn.yiiListView.update(grid);
$('#statusMsg').html(data).fadeIn().animate({opacity: 1.0}, 15000).fadeOut("slow");
}
</script>
| Renaud-Diez/NFT | protected/views/issue/backup/_sidebar.php | PHP | gpl-3.0 | 4,692 |
/****************************************************************************
**
** For Copyright & Licensing information, see COPYRIGHT in project root
**
****************************************************************************/
#include "30_removegroup.h"
namespace MXit
{
namespace Protocol
{
namespace Handlers
{
/****************************************************************************
**
** Author: Tim Sjoberg
**
** Populates a packet with the information required to remove a group
**
****************************************************************************/
void RemoveGroup::buildPacket(MXit::Network::Packet *packet, VariableHash &variables)
{
/*
== PACKET FORMAT
***************************************************************************
**
** id=loginname[\1sesid]\0
** cm=30
** ms=deleteContacts \1 numContacts \1 contactAddress0 \1 alias0 \1 contactAddress1 \1
** alias1 \1 ... \1 contactAddressN \1 aliasN
**
***************************************************************************
== DESCRIPTION
***************************************************************************
**
** deleteContacts is a flag that indicates whether the contacts themselves should be
** deleted.
** 0 - Do not delete the contacts (default)
** 1 - Delete all the specified contacts as well
** numContacts is the number of contacts affected by this command
** contactAddress0..N is the list of contacts affected by this command
** alias0..N is the corresponding alias for each of the contacts affected
** by this command
**
***************************************************************************
*/
(*packet) << variables["deleteContacts"]
<< variables["numContacts"]
<< variables["contactList"];
}
/****************************************************************************
**
** Author: Tim Sjoberg
**
** Extracts variable information from the remove group packet
**
****************************************************************************/
VariableHash RemoveGroup::handle(const QByteArray &packet)
{
/*
== PACKET FORMAT
***************************************************************************
**
** 30\0
** errorCode[\1errorMessage]\0
**
***************************************************************************
*/
return VariableHash();
}
}
}
}
| marcbowes/mxitc | src/protocol/handlers/30_removegroup.cpp | C++ | gpl-3.0 | 2,510 |
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* 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 <https://www.gnu.org/licenses/>.
*
*/
#include "../../inc/MarlinConfig.h"
#if HAS_TOUCH_BUTTONS
#include "touch_buttons.h"
#include "../scaled_tft.h"
#include HAL_PATH(../../HAL, tft/xpt2046.h)
XPT2046 touchIO;
#if ENABLED(TOUCH_SCREEN_CALIBRATION)
#include "../tft_io/touch_calibration.h"
#endif
#include "../buttons.h" // For EN_C bit mask
#include "../marlinui.h" // For ui.refresh
#include "../tft_io/tft_io.h"
#define DOGM_AREA_LEFT TFT_PIXEL_OFFSET_X
#define DOGM_AREA_TOP TFT_PIXEL_OFFSET_Y
#define DOGM_AREA_WIDTH (GRAPHICAL_TFT_UPSCALE) * (LCD_PIXEL_WIDTH)
#define DOGM_AREA_HEIGHT (GRAPHICAL_TFT_UPSCALE) * (LCD_PIXEL_HEIGHT)
#define BUTTON_AREA_TOP BUTTON_Y_LO
#define BUTTON_AREA_BOT BUTTON_Y_HI
TouchButtons touch;
void TouchButtons::init() { touchIO.Init(); }
uint8_t TouchButtons::read_buttons() {
#ifdef HAS_WIRED_LCD
int16_t x, y;
const bool is_touched = (TERN(TOUCH_SCREEN_CALIBRATION, touch_calibration.calibration.orientation, TOUCH_ORIENTATION) == TOUCH_PORTRAIT ? touchIO.getRawPoint(&y, &x) : touchIO.getRawPoint(&x, &y));
if (!is_touched) return 0;
#if ENABLED(TOUCH_SCREEN_CALIBRATION)
const calibrationState state = touch_calibration.get_calibration_state();
if (state >= CALIBRATION_TOP_LEFT && state <= CALIBRATION_BOTTOM_RIGHT) {
if (touch_calibration.handleTouch(x, y)) ui.refresh();
return 0;
}
x = int16_t((int32_t(x) * touch_calibration.calibration.x) >> 16) + touch_calibration.calibration.offset_x;
y = int16_t((int32_t(y) * touch_calibration.calibration.y) >> 16) + touch_calibration.calibration.offset_y;
#else
x = uint16_t((uint32_t(x) * TOUCH_CALIBRATION_X) >> 16) + TOUCH_OFFSET_X;
y = uint16_t((uint32_t(y) * TOUCH_CALIBRATION_Y) >> 16) + TOUCH_OFFSET_Y;
#endif
// Touch within the button area simulates an encoder button
if (y > BUTTON_AREA_TOP && y < BUTTON_AREA_BOT)
return WITHIN(x, BUTTOND_X_LO, BUTTOND_X_HI) ? EN_D
: WITHIN(x, BUTTONA_X_LO, BUTTONA_X_HI) ? EN_A
: WITHIN(x, BUTTONB_X_LO, BUTTONB_X_HI) ? EN_B
: WITHIN(x, BUTTONC_X_LO, BUTTONC_X_HI) ? EN_C
: 0;
if ( !WITHIN(x, DOGM_AREA_LEFT, DOGM_AREA_LEFT + DOGM_AREA_WIDTH)
|| !WITHIN(y, DOGM_AREA_TOP, DOGM_AREA_TOP + DOGM_AREA_HEIGHT)
) return 0;
// Column and row above BUTTON_AREA_TOP
int8_t col = (x - (DOGM_AREA_LEFT)) * (LCD_WIDTH) / (DOGM_AREA_WIDTH),
row = (y - (DOGM_AREA_TOP)) * (LCD_HEIGHT) / (DOGM_AREA_HEIGHT);
// Send the touch to the UI (which will simulate the encoder wheel)
MarlinUI::screen_click(row, col, x, y);
#endif
return 0;
}
#endif // HAS_TOUCH_BUTTONS
| 1stsetup/Marlin | Marlin/src/lcd/touch/touch_buttons.cpp | C++ | gpl-3.0 | 3,431 |
# frozen_string_literal: true
require 'forwardable'
module Capybara
##
# A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this
# collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation:
#
# * \[\]
# * each()
# * at()
# * size()
# * count()
# * length()
# * first()
# * last()
# * empty?()
# * values_at()
# * sample()
#
# @see Capybara::Node::Element
#
class Result
include Enumerable
extend Forwardable
def initialize(elements, query)
@elements = elements
@result_cache = []
@filter_errors = []
@results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) }
@query = query
@allow_reload = false
end
def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample
alias index find_index
def each(&block)
return enum_for(:each) unless block_given?
@result_cache.each(&block)
loop do
next_result = @results_enum.next
add_to_cache(next_result)
yield next_result
end
self
end
def [](*args)
idx, length = args
max_idx = case idx
when Integer
if !idx.negative?
length.nil? ? idx : idx + length - 1
else
nil
end
when Range
# idx.max is broken with beginless ranges
# idx.end && idx.max # endless range will have end == nil
max = idx.end
max = nil if max&.negative?
max -= 1 if max && idx.exclude_end?
max
end
if max_idx.nil?
full_results[*args]
else
load_up_to(max_idx + 1)
@result_cache[*args]
end
end
alias :at :[]
def empty?
!any?
end
def compare_count
return 0 unless @query
count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between)
# Only check filters for as many elements as necessary to determine result
if count && (count = Integer(count))
return load_up_to(count + 1) <=> count
end
if min && (min = Integer(min))
return -1 if load_up_to(min) < min
end
if max && (max = Integer(max))
return 1 if load_up_to(max + 1) > max
end
if between
min, max = (between.begin && between.min) || 1, between.end
max -= 1 if max && between.exclude_end?
size = load_up_to(max ? max + 1 : min)
return size <=> min unless between.include?(size)
end
0
end
def matches_count?
compare_count.zero?
end
def failure_message
message = @query.failure_message
if count.zero?
message << ' but there were no matches'
else
message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \
<< full_results.map(&:text).map(&:inspect).join(', ')
end
unless rest.empty?
elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier
message << '. Also found ' << elements << ', which matched the selector but not all filters. '
message << @filter_errors.join('. ') if (rest.size == 1) && count.zero?
end
message
end
def negative_failure_message
failure_message.sub(/(to find)/, 'not \1')
end
def unfiltered_size
@elements.length
end
##
# @api private
#
def allow_reload!
@allow_reload = true
self
end
private
def add_to_cache(elem)
elem.allow_reload!(@result_cache.size) if @allow_reload
@result_cache << elem
end
def load_up_to(num)
loop do
break if @result_cache.size >= num
add_to_cache(@results_enum.next)
end
@result_cache.size
end
def full_results
loop { @result_cache << @results_enum.next }
@result_cache
end
def rest
@rest ||= @elements - full_results
end
if RUBY_PLATFORM == 'java'
# JRuby < 9.2.8.0 has an issue with lazy enumerators which
# causes a concurrency issue with network requests here
# https://github.com/jruby/jruby/issues/4212
# while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators
# https://github.com/teamcapybara/capybara/issues/2349
# so disable the use and JRuby users will need to pay a performance penalty
def lazy_select_elements(&block)
@elements.select(&block).to_enum # non-lazy evaluation
end
else
def lazy_select_elements(&block)
@elements.lazy.select(&block)
end
end
end
end
| BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/capybara-3.32.2/lib/capybara/result.rb | Ruby | gpl-3.0 | 4,779 |
#region license
/*
MediaFoundationLib - Provide access to MediaFoundation interfaces via .NET
Copyright (C) 2007
http://mfnet.sourceforge.net
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security;
using MediaFoundation.Misc;
using System.Drawing;
using MediaFoundation.EVR;
using MediaFoundation.Transform;
namespace MediaFoundation.ReadWrite
{
/// <summary>
/// Contains flags that indicate the status of the <see cref="ReadWrite.IMFSourceReader.ReadSample"/>
/// method.
/// </summary>
/// <remarks>
/// The above documentation is © Microsoft Corporation. It is reproduced here
/// with the sole purpose to increase usability and add IntelliSense support.
/// <para/>
/// View the original documentation topic online:
/// <a href="http://msdn.microsoft.com/en-US/library/8981A682-3C0B-458B-910A-D1462ED73E64(v=VS.85,d=hv.2).aspx">http://msdn.microsoft.com/en-US/library/8981A682-3C0B-458B-910A-D1462ED73E64(v=VS.85,d=hv.2).aspx</a>
/// </remarks>
[Flags]
[UnmanagedName("MF_SOURCE_READER_FLAG")]
public enum MF_SOURCE_READER_FLAG
{
/// <summary>
/// Default value / no flags are set.
/// </summary>
None = 0,
/// <summary>
/// An error occurred. If you receive this flag, do not make any further calls to
/// <see cref="ReadWrite.IMFSourceReader"/> methods.
/// </summary>
Error = 0x00000001,
/// <summary>
/// The source reader reached the end of the stream.
/// </summary>
EndOfStream = 0x00000002,
/// <summary>
/// One or more new streams were created. Respond to this flag by doing at least one of the following:
/// <para/>
/// <para>* Set the output types on the new streams.</para><para>* Update the stream selection by
/// selecting or deselecting streams.</para>
/// </summary>
NewStream = 0x00000004,
/// <summary>
/// The <em>native format</em> has changed for one or more streams. The native format is the format
/// delivered by the media source before any decoders are inserted.
/// </summary>
NativeMediaTypeChanged = 0x00000010,
/// <summary>
/// The current media has type changed for one or more streams. To get the current media type, call the
/// <see cref="ReadWrite.IMFSourceReader.GetCurrentMediaType"/> method.
/// </summary>
CurrentMediaTypeChanged = 0x00000020,
/// <summary>
/// All transforms inserted by the application have been removed for a particular stream. This could be
/// due to a dynamic format change from a source or decoder that prevents custom transforms from being
/// used because they cannot handle the new media type.
/// </summary>
AllEffectsRemoved = 0x00000200,
/// <summary>
/// There is a gap in the stream. This flag corresponds to an <c>MEStreamTick</c> event from the media
/// source.
/// </summary>
StreamTick = 0x00000100
}
}
| todor-dk/SuperMFLib | src/ReadWrite/Enums/MF_SOURCE_READER_FLAG.cs | C# | gpl-3.0 | 3,893 |
<?php
header('Content-Type: text/xml');
include '../xmlbuilder.php';
if(isset($_POST['HomeUrl']) &&isset($_POST['DBHost']) && isset($_POST['DBName']) && isset($_POST['DBPw']) && isset($_POST['DBLogin'])){
if(createConfigFile($_POST['HomeUrl'],$_POST['DBHost'], $_POST['DBLogin'], $_POST['DBName'], $_POST['DBPw'])) {
$db_script_path ="cake.sql";
$db_server = trim($_POST['DBHost']);
$db_name = trim($_POST['DBName']);
$db_pw = trim($_POST['DBPw']);
$db_login = trim($_POST['DBLogin']);
$return_code = build_DB($db_server, $db_login, $db_pw, $db_name, $db_script_path);
if ($return_code == 1065 || $return_code == 0) {
echo getAnswer( getRC0Xml());
} else {
echo getAnswer( getRC1Xml());
}
} else {
echo getAnswer( getRC1Xml());
}
} else {
echo getAnswer( getRC1Xml());
}
function createConfigFile($homeurl, $dbhost,$dblogin, $dbname, $dbpw){
$file = "<?php class DATABASE_CONFIG {
public \$default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => '$dbhost',
'port' => 3306,
'login' => '$dblogin',
'password' => '$dbpw',
'database' => '$dbname',
'encoding' => 'utf8'
);
} ?>";
//set up file handle
$filename = "../../../Config/database.php";
$dbfile = fopen($filename, "w+");
//put data into file
fputs($dbfile, $file);
$cake_configtbool = fclose($dbfile);
//start building up simple config file
$c_filename = "../config.php";
$c_file = fopen($c_filename, "w+");
rewind($c_file);
//write rootdir
$to_write = "HOMEURL#".$homeurl."\n";
fwrite($c_file, $to_write);
//write dbhost
$to_write = "DBHOST#".$dbhost."\n";
fwrite($c_file, $to_write);
//write dbname
$to_write = "DBNAME#".$dbname."\n";
fwrite($c_file, $to_write);
//write dbuser
$to_write = "DBLOGIN#".$dblogin."\n";
fwrite($c_file, $to_write);
//write dbpasswort
$to_write = "DBPW#".$dbpw."";
fwrite($c_file, $to_write);
$c_configtbool = fclose($c_file);
return ($cake_configtbool && $c_configtbool );
}
function build_DB($host,$user,$pass,$name,$path){
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
$sqlErrorCode = 0;
$f = fopen($path,"r+");
$sqlFile = fread($f,filesize($path));
$sqlArray = explode(';',$sqlFile);
foreach ($sqlArray as $stmt) {
if (strlen($stmt)>3 && !empty($stmt) && $stmt != " "){
$result = mysql_query($stmt);
if (!$result){
$sqlErrorCode = mysql_errno();
$sqlErrorText = mysql_error();
$sqlStmt = $stmt;
break;
}
}
}
return $sqlErrorCode;
}
?> | DHBW-Projekt/BeePublished | app/webroot/services/installation/index.php | PHP | gpl-3.0 | 2,644 |
package battlecode.world;
import battlecode.common.Direction;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.RobotType;
import battlecode.common.TerrainTile;
import battlecode.serial.GenericGameMap;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.Random;
/**
* The class represents the map in the game world on which
* objects interact.
*/
public class GameMap implements GenericGameMap {
private static final long serialVersionUID = -2068896916199851260L;
/**
* The default game seed.
*/
public static final int GAME_DEFAULT_SEED = 6370;
/**
* The default game maxiumum number of rounds.
*/
public static final int GAME_DEFAULT_MAX_ROUNDS = 10000;
/** The default game minimum number of points. */
//public static final int GAME_DEFAULT_MIN_POINTS = 5000;
/**
* The width and height of the map.
*/
private final int mapWidth, mapHeight;
/**
* The tiles on the map.
*/
private final TerrainTile[][] mapTiles;
/**
* The scalar field of neutral characters on the map.
*/
private final NeutralsMap neutralsMap;
/**
* The coordinates of the origin.
*/
private final int mapOriginX, mapOriginY;
/**
* The name of the map theme.
*/
private String mapTheme;
/**
* The random seed contained in the map file
*/
private final int seed;
/**
* The maximum number of rounds in the game
*/
private final int maxRounds;
/**
* The name of the map
*/
private final String mapName;
/** The minimum number of points needed to win the game */
//private final int minPoints;
/**
* Represents the various integer properties a GameMap
* can have.
*/
static enum MapProperties {
WIDTH, HEIGHT, SEED, MAX_ROUNDS, THEME /*, MIN_POINTS*/
}
public GameMap(GameMap gm) {
this.mapWidth = gm.mapWidth;
this.mapHeight = gm.mapHeight;
this.mapTiles = new TerrainTile[this.mapWidth][this.mapHeight];
this.neutralsMap = new NeutralsMap(gm.neutralsMap);
for (int i = 0; i < this.mapWidth; i++) {
System.arraycopy(gm.mapTiles[i], 0, this.mapTiles[i], 0, this.mapHeight);
}
this.mapOriginX = gm.mapOriginX;
this.mapOriginY = gm.mapOriginY;
this.mapTheme = gm.mapTheme;
this.seed = gm.seed;
this.maxRounds = gm.maxRounds;
this.mapName = gm.mapName;
//this.minPoints = gm.minPoints;
}
/**
* Creates a new GameMap from the given properties, tiles, and territory
* locations.
*
* @param mapProperties a map of MapProperties to their integer values containing dimensions, etc.
* @param mapTiles a matrix of TerrainTypes representing the map
* @param neutralsMap a NeutralsMap to copy
*/
GameMap(Map<MapProperties, Integer> mapProperties, TerrainTile[][] mapTiles, NeutralsMap neutralsMap, String mapName) {
if (mapProperties.containsKey(MapProperties.WIDTH))
this.mapWidth = mapProperties.get(MapProperties.WIDTH);
else
this.mapWidth = mapTiles[0].length;
if (mapProperties.containsKey(MapProperties.HEIGHT))
this.mapHeight = mapProperties.get(MapProperties.HEIGHT);
else
this.mapHeight = mapTiles.length;
if (mapProperties.containsKey(MapProperties.SEED))
this.seed = mapProperties.get(MapProperties.SEED);
else
this.seed = GAME_DEFAULT_SEED;
if (mapProperties.containsKey(MapProperties.MAX_ROUNDS))
this.maxRounds = mapProperties.get(MapProperties.MAX_ROUNDS);
else
this.maxRounds = GAME_DEFAULT_MAX_ROUNDS;
//if (mapProperties.containsKey(MapProperties.MIN_POINTS))
// this.minPoints = mapProperties.get(MapProperties.MIN_POINTS);
//else this.minPoints = GAME_DEFAULT_MIN_POINTS;
// Random rand = new Random(this.seed);
// this.mapOriginX = rand.nextInt(32000);
// this.mapOriginY = rand.nextInt(32000);
// Maps are normalized to 0,0 (2013 change)
this.mapOriginX = 0;
this.mapOriginY = 0;
this.mapTiles = mapTiles;
this.neutralsMap = neutralsMap;
this.mapName = mapName;
}
public void setTheme(String theme) {
this.mapTheme = theme;
}
/**
* Returns the width of this map.
*
* @return the width of this map
*/
public int getWidth() {
return mapWidth;
}
/**
* Returns the height of this map.
*
* @return the height of this map
*/
public int getHeight() {
return mapHeight;
}
/**
* Returns the name of the suggested map
* theme to use when displaying the map.
*
* @return the string name of the map theme
*/
public String getThemeName() {
return mapTheme;
}
public String getMapName() {
return mapName;
}
//public int getMinPoints() {
// return minPoints;
//}
/**
* Determines whether or not the location at the specified
* unshifted coordinates is on the map.
*
* @param x the (shifted) x-coordinate of the location
* @param y the (shifted) y-coordinate of the location
* @return true if the given coordinates are on the map,
* false if they're not
*/
private boolean onTheMap(int x, int y) {
return (x >= mapOriginX && y >= mapOriginY && x < mapOriginX + mapWidth && y < mapOriginY + mapHeight);
}
/**
* Determines whether or not the specified location is on the map.
*
* @param location the MapLocation to test
* @return true if the given location is on the map,
* false if it's not
*/
public boolean onTheMap(MapLocation location) {
return onTheMap(location.x, location.y);
}
/**
* Determines the type of the terrain on the map at the
* given location.
*
* @param location the MapLocation to test
* @return the TerrainTile at the given location
* of the map, and TerrainTile.OFF_MAP if the given location is
* off the map.
*/
public TerrainTile getTerrainTile(MapLocation location) {
if (!onTheMap(location))
return TerrainTile.OFF_MAP;
return mapTiles[location.x - mapOriginX][location.y - mapOriginY];
}
/**
* Returns a two-dimensional array of terrain data for this map.
*
* @return the map's terrain in a 2D array
*/
public TerrainTile[][] getTerrainMatrix() {
return mapTiles;
}
/**
* Updates the neutrals map for the next turn.
*/
public NeutralsMap getNeutralsMap() {
return neutralsMap;
}
/**
* Gets the maximum number of rounds for this game.
*
* @return the maximum number of rounds for this game
*/
public int getMaxRounds() {
return maxRounds;
}
public int getStraightMaxRounds() {
return maxRounds;
}
public int getSeed() {
return seed;
}
/**
* Gets the origin (i.e., upper left corner) of the map
*
* @return the origin of the map
*/
public MapLocation getMapOrigin() {
return new MapLocation(mapOriginX, mapOriginY);
}
public static class MapMemory {
// should be ge the max of all robot sensor ranges
private final static int BUFFER;
static {
int buf = 0;
for (RobotType t : RobotType.values()) {
if (t.sensorRadiusSquared > buf)
buf = t.sensorRadiusSquared;
}
BUFFER = buf;// + GameConstants.VISION_UPGRADE_BONUS;
}
private final boolean data[][];
private final GameMap map;
private final int Xwidth;
private final int Ywidth;
public MapMemory(GameMap map) {
this.map = map;
Xwidth = map.mapWidth + (2 * BUFFER);
Ywidth = map.mapHeight + (2 * BUFFER);
data = new boolean[Xwidth][Ywidth];
}
public void rememberLocations(MapLocation loc, int[] offsetsX, int[] offsetsY) {
int X = loc.x - map.mapOriginX + BUFFER;
int Y = loc.y - map.mapOriginY + BUFFER;
for (int i = 0; i < offsetsX.length; i++) {
data[X + offsetsX[i]][Y + offsetsY[i]] = true;
}
}
public TerrainTile recallTerrain(MapLocation loc) {
int X = loc.x - map.mapOriginX + BUFFER;
int Y = loc.y - map.mapOriginY + BUFFER;
if (X >= 0 && X < Xwidth && Y >= 0 && Y < Ywidth && data[X][Y])
return map.getTerrainTile(loc);
else
return null;
}
}
public static int[][] computeOffsets360(int radiusSquared) {
int[] XOffsets = new int[4 * radiusSquared + 7];
int[] YOffsets = new int[4 * radiusSquared + 7];
int nOffsets = 0;
for (int y = 0; y * y <= radiusSquared; y++) {
XOffsets[nOffsets] = 0;
YOffsets[nOffsets] = y;
nOffsets++;
if (y > 0) {
XOffsets[nOffsets] = 0;
YOffsets[nOffsets] = -y;
nOffsets++;
}
for (int x = 1; x * x + y * y <= radiusSquared; x++) {
MapLocation loc = new MapLocation(x, y);
XOffsets[nOffsets] = x;
YOffsets[nOffsets] = y;
nOffsets++;
XOffsets[nOffsets] = -x;
YOffsets[nOffsets] = y;
nOffsets++;
if (y > 0) {
XOffsets[nOffsets] = x;
YOffsets[nOffsets] = -y;
nOffsets++;
XOffsets[nOffsets] = -x;
YOffsets[nOffsets] = -y;
nOffsets++;
}
}
}
return new int[][]{Arrays.copyOf(XOffsets, nOffsets), Arrays.copyOf(YOffsets, nOffsets)};
}
public static Map<RobotType, int[][][]> computeVisibleOffsets() {
int MAX_RANGE;
final MapLocation CENTER = new MapLocation(0, 0);
Map<RobotType, int[][][]> offsets = new EnumMap<RobotType, int[][][]>(RobotType.class);
int[][][] offsetsForType;
int[] XOffsets = new int[169];
int[] YOffsets = new int[169];
int nOffsets;
for (RobotType type : RobotType.values()) {
offsetsForType = new int[9][][];
offsets.put(type, offsetsForType);
if ((type.sensorAngle >= 360.0)) {
// Same range of vision independent of direction;
// save memory by using the same array each time
int[][] tmpOffsets = computeOffsets360(type.sensorRadiusSquared);
for (int i = 0; i < 8; i++) {
offsetsForType[i] = tmpOffsets;
}
} else {
for (int i = 0; i < 8; i++) {
Direction dir = Direction.values()[i];
nOffsets = 0;
MAX_RANGE = (int) Math.sqrt(type.sensorRadiusSquared);
for (int y = -MAX_RANGE; y <= MAX_RANGE; y++) {
for (int x = -MAX_RANGE; x <= MAX_RANGE; x++) {
MapLocation loc = new MapLocation(x, y);
if (CENTER.distanceSquaredTo(loc) <= type.sensorRadiusSquared
&& GameWorld.inAngleRange(CENTER, dir, loc, type.sensorCosHalfTheta)) {
XOffsets[nOffsets] = x;
YOffsets[nOffsets] = y;
nOffsets++;
}
}
}
offsetsForType[i] = new int[][]{Arrays.copyOf(XOffsets, nOffsets), Arrays.copyOf(YOffsets, nOffsets)};
}
}
}
return offsets;
}
}
| bovard/battlecode-server-2014 | src/main/battlecode/world/GameMap.java | Java | gpl-3.0 | 12,224 |
'use strict';
const Stack = require('./_Stack');
const baseIsEqual = require('./_baseIsEqual');
/** Used to compose bitmasks for comparison styles. */
const UNORDERED_COMPARE_FLAG = 1;
const PARTIAL_COMPARE_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
let index = matchData.length;
const length = index;
const noCustomizer = !customizer;
let data;
if ((object === null || object === undefined)) {
return !length;
}
object = Object(object);
while (index--) {
data = matchData[index];
if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
const key = data[0];
const objValue = object[key];
const srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
const stack = new Stack();
let result;
if (customizer) {
result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
| rafa1231518/CommunityBot | lib/xml2js-req/xmlbuilder/lodash/_baseIsMatch.js | JavaScript | gpl-3.0 | 1,805 |
module.exports = publish
var url = require('url')
var semver = require('semver')
var Stream = require('stream').Stream
var assert = require('assert')
var fixer = require('normalize-package-data').fixer
var concat = require('concat-stream')
var ssri = require('ssri')
function escaped (name) {
return name.replace('/', '%2f')
}
function publish (uri, params, cb) {
assert(typeof uri === 'string', 'must pass registry URI to publish')
assert(params && typeof params === 'object', 'must pass params to publish')
assert(typeof cb === 'function', 'must pass callback to publish')
var access = params.access
assert(
(!access) || ['public', 'restricted'].indexOf(access) !== -1,
"if present, access level must be either 'public' or 'restricted'"
)
var auth = params.auth
assert(auth && typeof auth === 'object', 'must pass auth to publish')
if (!(auth.token ||
(auth.password && auth.username && auth.email))) {
var er = new Error('auth required for publishing')
er.code = 'ENEEDAUTH'
return cb(er)
}
var metadata = params.metadata
assert(
metadata && typeof metadata === 'object',
'must pass package metadata to publish'
)
try {
fixer.fixNameField(metadata, {strict: true, allowLegacyCase: true})
} catch (er) {
return cb(er)
}
var version = semver.clean(metadata.version)
if (!version) return cb(new Error('invalid semver: ' + metadata.version))
metadata.version = version
var body = params.body
assert(body, 'must pass package body to publish')
assert(body instanceof Stream, 'package body passed to publish must be a stream')
var client = this
var sink = concat(function (tarbuffer) {
putFirst.call(client, uri, metadata, tarbuffer, access, auth, cb)
})
sink.on('error', cb)
body.pipe(sink)
}
function putFirst (registry, data, tarbuffer, access, auth, cb) {
// optimistically try to PUT all in one single atomic thing.
// If 409, then GET and merge, try again.
// If other error, then fail.
var root = {
_id: data.name,
name: data.name,
description: data.description,
'dist-tags': {},
versions: {},
readme: data.readme || ''
}
if (access) root.access = access
if (!auth.token) {
root.maintainers = [{ name: auth.username, email: auth.email }]
data.maintainers = JSON.parse(JSON.stringify(root.maintainers))
}
root.versions[ data.version ] = data
var tag = data.tag || this.config.defaultTag
root['dist-tags'][tag] = data.version
var tbName = data.name + '-' + data.version + '.tgz'
var tbURI = data.name + '/-/' + tbName
var integrity = ssri.fromData(tarbuffer, {
algorithms: ['sha1', 'sha512']
})
data._id = data.name + '@' + data.version
data.dist = data.dist || {}
// Don't bother having sha1 in the actual integrity field
data.dist.integrity = integrity['sha512'][0].toString()
// Legacy shasum support
data.dist.shasum = integrity['sha1'][0].hexDigest()
data.dist.tarball = url.resolve(registry, tbURI)
.replace(/^https:\/\//, 'http://')
root._attachments = {}
root._attachments[ tbName ] = {
'content_type': 'application/octet-stream',
'data': tarbuffer.toString('base64'),
'length': tarbuffer.length
}
var fixed = url.resolve(registry, escaped(data.name))
var client = this
var options = {
method: 'PUT',
body: root,
auth: auth
}
this.request(fixed, options, function (er, parsed, json, res) {
var r409 = 'must supply latest _rev to update existing package'
var r409b = 'Document update conflict.'
var conflict = res && res.statusCode === 409
if (parsed && (parsed.reason === r409 || parsed.reason === r409b)) {
conflict = true
}
// a 409 is typical here. GET the data and merge in.
if (er && !conflict) {
client.log.error('publish', 'Failed PUT ' + (res && res.statusCode))
return cb(er)
}
if (!er && !conflict) return cb(er, parsed, json, res)
// let's see what versions are already published.
client.request(fixed + '?write=true', { auth: auth }, function (er, current) {
if (er) return cb(er)
putNext.call(client, registry, data.version, root, current, auth, cb)
})
})
}
function putNext (registry, newVersion, root, current, auth, cb) {
// already have the tardata on the root object
// just merge in existing stuff
var curVers = Object.keys(current.versions || {}).map(function (v) {
return semver.clean(v, true)
}).concat(Object.keys(current.time || {}).map(function (v) {
if (semver.valid(v, true)) return semver.clean(v, true)
}).filter(function (v) {
return v
}))
if (curVers.indexOf(newVersion) !== -1) {
return cb(conflictError(root.name, newVersion))
}
current.versions[newVersion] = root.versions[newVersion]
current._attachments = current._attachments || {}
for (var i in root) {
switch (i) {
// objects that copy over the new stuffs
case 'dist-tags':
case 'versions':
case '_attachments':
for (var j in root[i]) {
current[i][j] = root[i][j]
}
break
// ignore these
case 'maintainers':
break
// copy
default:
current[i] = root[i]
}
}
var maint = JSON.parse(JSON.stringify(root.maintainers))
root.versions[newVersion].maintainers = maint
var uri = url.resolve(registry, escaped(root.name))
var options = {
method: 'PUT',
body: current,
auth: auth
}
this.request(uri, options, cb)
}
function conflictError (pkgid, version) {
var e = new Error('cannot modify pre-existing version')
e.code = 'EPUBLISHCONFLICT'
e.pkgid = pkgid
e.version = version
return e
}
| lyy289065406/expcodes | java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-frontend/node/node_modules/npm/node_modules/npm-registry-client/lib/publish.js | JavaScript | gpl-3.0 | 5,905 |
<?php
$sLangName = "Deutsch";
$iLangNr = 0;
$aLang = array(
'charset' => 'ISO-8859-15',
'tbcluser_jxjiraconnect' => 'JIRA Vorgänge',
'tbclorder_jxjiraconnect' => 'JIRA Vorgänge',
'jxjiraconnect_menu' => 'JIRA Vorgänge',
'JXJIRA_OPENISSUE' => 'Vorgang offen',
'JXJIRA_OPENISSUES' => 'Vorgänge offen',
'JXJIRA_STATUSICON' => 'S',
'JXJIRA_KEY' => 'Schlüssel',
'JXJIRA_SUMMARY' => 'Zusammenfasung',
'JXJIRA_PRIORITY' => 'Priorität',
'JXJIRA_STATUS' => 'Status',
'JXJIRA_CREATED' => 'Erstellt',
'JXJIRA_CREATOR' => 'Autor',
'JXJIRA_DUEDATE' => 'Fällig am',
'JXJIRA_DESCRIPTION' => 'Beschreibung',
'JXJIRA_ISSUETYPE_ACCESS' => 'Zugriff',
'JXJIRA_ISSUETYPE_BUG' => 'Fehler/Mangel',
'JXJIRA_ISSUETYPE_FAULT' => 'Störung',
'JXJIRA_ISSUETYPE_PURCHASE' => 'Bestellung',
'JXJIRA_ISSUETYPE_TASK' => 'Aufgabe',
'JXJIRA_PRIORITY_1' => 'Blocker',
'JXJIRA_PRIORITY_2' => 'Kritisch',
'JXJIRA_PRIORITY_3' => 'Wichtig',
'JXJIRA_PRIORITY_4' => 'Unwesentlich',
'JXJIRA_PRIORITY_5' => 'Trivial',
'SHOP_MODULE_GROUP_JXJIRACONNECT_SERVER' => 'JIRA Server',
'SHOP_MODULE_sJxJiraConnectServerUrl' => 'Server URL',
'SHOP_MODULE_sJxJiraConnectProject' => 'JIRA Projekt Schlüssel',
'SHOP_MODULE_GROUP_JXJIRACONNECT_LOGIN' => 'JIRA-Anmeldung',
'SHOP_MODULE_sJxJiraConnectUser' => 'Benutzer',
'SHOP_MODULE_sJxJiraConnectPassword' => 'Passwort',
'SHOP_MODULE_GROUP_JXJIRACONNECT_DEFAULTS' => 'Standard Werte',
'SHOP_MODULE_sJxJiraConnectProject' => 'Projekt Schlüssel',
'SHOP_MODULE_sJxJiraConnectAssignee' => 'Bearbeiter',
'SHOP_MODULE_GROUP_JXJIRACONNECT_FIELDS' => 'Benutzerdefinierte Jira-Felder',
'SHOP_MODULE_sJxJiraConnectCustomerNumber' => 'Feld ID für Kundennummer',
'SHOP_MODULE_sJxJiraConnectCustomerEMail' => 'Feld ID für Kunden E-Mail',
);
| job963/jxJiraConnect | copy_this/modules/jxmods/jxjiraconnect/application/views/admin/de/jxjiraconnect_lang.php | PHP | gpl-3.0 | 2,614 |
<?php
//prohibit unauthorized access
require 'core/access.php';
$status_msg = '';
/* delete items from excludes list */
if(isset($_POST['del_exclude']) && is_numeric($_POST['del_exclude'])) {
$del_exclude = (int) $_POST['del_exclude'];
fc_delete_excludes($del_exclude);
}
if(isset($_POST['add_exclude_url'])) {
fc_write_exclude_url($_POST['exclude_url']);
}
if(isset($_POST['add_excludes'])) {
fc_write_exclude_elements($_POST['exclude_element'],$_POST['exclude_attribute']);
}
$exclude_items = fc_get_exclude_elements();
$exclude_urls = fc_get_exclude_urls();
echo '<div class="app-container">';
echo '<div class="subHeader">';
echo '<h3>Indexing</h3>';
echo '</div>';
echo '<div class="max-height-container">';
echo '<div class="row">';
echo '<div class="col-sm-8">';
if(isset($_POST['start_index_from']) && $_POST['start_index_from'] != '') {
fc_crawler($_POST['start_index_from']);
}
if(isset($_POST['start_update_page']) && $_POST['start_update_page'] != '') {
$fc_upi = fc_update_page_index($_POST['start_update_page']);
$status_msg = 'Script running '.$fc_upi['duration'].' seconds';
}
if(isset($_POST['remove_page']) && $_POST['remove_page'] != '') {
$fc_upi = fc_remove_page_from_index($_POST['remove_page']);
}
if(isset($_POST['start_index']) && $_POST['start_index'] != '') {
fc_crawler($_POST['start_index']);
}
if(isset($_POST['start_update_bulk'])) {
fc_update_bulk_page_index();
}
if(isset($_POST['start_index_bulk'])) {
fc_crawler_bulk();
}
if(isset($_POST['limit_index_items'])) {
$_SESSION['limit_index_items'] = (int) $_POST['limit_index_items'];
}
if(!isset($_SESSION['limit_index_items'])) {
$_SESSION['limit_index_items'] = 10;
}
// $active_btn10 ... $active_btn25 ... $active_btn0
${active_btn.$_SESSION['limit_index_items']} = 'active';
$cnt_all_indexed_entries = fc_get_nbr_of_indexed_pages();
$indexed_entries = fc_get_indexed_pages();
$cnt_get_indexed_entries = count($indexed_entries);
echo '<fieldset>';
echo '<legend>' . $lang['page_index'] . ' ('.$cnt_all_indexed_entries.')</legend>';
echo '<div class="well well-sm">';
echo '<form action="?tn=pages&sub=index" method="POST">';
echo '<button class="btn btn-fc '.$active_btn10.'" name="limit_index_items" value="10">10</button>';
echo '<button class="btn btn-fc '.$active_btn25.'" name="limit_index_items" value="25">25</button>';
echo '<button class="btn btn-fc '.$active_btn50.'" name="limit_index_items" value="50">50</button>';
echo '<button class="btn btn-fc '.$active_btn100.'" name="limit_index_items" value="100">100</button>';
echo '<button class="btn btn-fc '.$active_btn0.'" name="limit_index_items" value="0">All (slow)</button>';
echo '<input type="hidden" name="csrf_token" value="'.$_SESSION['token'].'">';
echo '</form>';
echo '</div>';
echo '<div class="scroll-box">';
echo '<div class="p-3">';
if($status_msg != '') {
echo '<div class="alert alert-info alert-dismissible fade show autoclose">'.$status_msg.'<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
}
$item_tpl = file_get_contents('templates/list-indexed-pages-item.tpl');
/* count all errors */
$ce_img_alt = 0;
$ce_img_title = 0;
$ce_links_title = 0;
$ce_h1 = 0;
$ce_h2 = 0;
$ce_description = 0;
$ce_title = 0;
for($i=0;$i<$cnt_get_indexed_entries;$i++) {
/* reset error counter for each page */
$ce_page_img_title = 0;
$ce_page_img_alt = 0;
$ce_page_img_file_not_found = 0;
$cnt_images_errors = 0;
$ce_page_link_title = 0;
$ce_page_img = 0;
$ce_page_link = 0;
$ce_page_headlines = 0;
$ce_page_h1 = 0;
$ce_page_h2 = 0;
$url = $indexed_entries[$i]['page_url'];
$title = $indexed_entries[$i]['page_title'];
$description = $indexed_entries[$i]['page_description'];
$indexed_time = $indexed_entries[$i]['indexed_time'];
if($title == '') {
$title = '<span class="text-danger">No Title</span>';
$ce_title++;
}
if($description == '') {
$description = '<span class="text-danger">No Description</span>';
$ce_description++;
}
$cnt_meta_errors = $cnt_error_meta_description+$cnt_error_meta_title;
if($indexed_time == '') {
$indexed_time = '<span class="text-danger">Not Indexed</span>';
} else {
$indexed_time = date('Y-m-d H:i',$indexed_time);
}
/**
* headlines
*/
/* h1 */
if($indexed_entries[$i]['page_h1'] != '') {
$h1s = explode('<|>', $indexed_entries[$i]['page_h1']);
$cnt_h1s = count($h1s);
} else {
$cnt_h1s = 0;
}
if($cnt_h1s > 0) {
$h1str = '<ul>';
foreach($h1s as $str) {
$h1str .= '<li>'.$str.'</li>';
}
$h1str .= '</ul>';
} else {
$h1str = '<span class="text-danger strong">'.$lang['msg_missing_headline'].'</span>';
$ce_page_h1++;
$ce_h1++;
}
/* h2 */
if($indexed_entries[$i]['page_h2'] != '') {
$h2s = explode('<|>', $indexed_entries[$i]['page_h2']);
$cnt_h2s = count($h2s);
} else {
$cnt_h2s = 0;
}
if($cnt_h2s > 0) {
$h2str = '';
foreach($h2s as $str) {
$h2str .= '<span class="badge badge-secondary">'.$str.'</span> ';
}
} else {
$h2str = '<span class="text-danger">'.$lang['msg_missing_headline'].'</span>';
$ce_page_h2++;
$ce_h2++;
}
/* h3 */
if($indexed_entries[$i]['page_h3'] != '') {
$h3s = explode('<|>', $indexed_entries[$i]['page_h3']);
$cnt_h3s = count($h3s);
} else {
$cnt_h3s = 0;
}
if($cnt_h3s > 0) {
$h3str = '';
foreach($h3s as $str) {
$h3str .= '<span class="badge badge-secondary">'.$str.'</span> ';
}
} else {
$h3str = $lang['msg_missing_headline'];
}
$cnt_headlines = $cnt_h1s+$cnt_h2s+$cnt_h3s;
$ce_page_headlines = $ce_page_h1+$ce_page_h2;
$headlines_str = '<table class="table table-sm table-striped">';
$headlines_str .= '<tr><td>H1 ('.$cnt_h1s.')</td><td>'.$h1str.'</td></tr>';
$headlines_str .= '<tr><td>H2 ('.$cnt_h2s.')</td><td>'.$h2str.'</td></tr>';
$headlines_str .= '<tr><td>H3 ('.$cnt_h3s.')</td><td>'.$h3str.'</td></tr>';
$headlines_str .= '</table>';
/* images */
$img_str = '';
$img_array = array_filter(explode('<|-|>', $indexed_entries[$i]['page_images']));
$cnt_images = count($img_array);
if(is_array($img_array) && count($img_array) > 0) {
$img_str = '<table class="table table-sm">';
$img_str .= '<tr><td>SRC</td><td>ALT</td><td>TITLE</td></tr>';
foreach($img_array as $k) {
$missing_img = false;
$this_img = explode('<|>', $k);
$img_str .= '<tr>';
if(substr($this_img[0], 0,4) == 'http') {
$file_headers = @get_headers($remote_filename);
if (stripos($file_headers[0],"404 Not Found") > 0 || (stripos($file_headers[0], "302 Found") > 0 && stripos($file_headers[7],"404 Not Found") > 0)) {
$img_str .= '<td>'.$this_img[0].' <span class="text-danger">(extern file not found)</span></td>';
$missing_img = true;
$ce_page_img_file_not_found++;
} else {
$img_str .= '<td><strong><a href="'.$this_img[0].'" data-fancybox="images">'.basename($this_img[0]).'</a></strong></td>';
}
} else {
if(!is_file('../'.FC_ROOT.$this_img[0])) {
$img_str .= '<td>'.FC_ROOT.$this_img[0].' <span class="text-danger">(file not found)</span></td>';
$missing_img = true;
$ce_page_img_file_not_found++;
} else {
$img_str .= '<td><strong><a href="'.$this_img[0].'" data-fancybox="images">'.basename($this_img[0]).'</a></strong></td>';
}
}
if($this_img[1] == '' && $missing_img === false) {
$this_img[1] = '<span class="text-danger">NULL</span>';
$ce_page_img_alt++;
$ce_img_alt++;
}
if($this_img[2] == '' && $missing_img === false) {
$this_img[2] = '<span class="text-danger">NULL</span>';
$ce_page_img_title++;
$ce_img_title++;
}
$img_str .= '<td>'.$this_img[1].'</td>';
$img_str .= '<td>'.$this_img[2].'</td>';
$img_str .= '</tr>';
}
$img_str .= '</table>';
$img_rerror_str = '<span class="text-danger">Errors:</span> ';
$img_rerror_str .= 'Title: '.$page_img_title_errors.' ';
$img_rerror_str .= 'Alt: '.$page_img_alt_errors. ' ';
$img_rerror_str .= 'Not found: '.$page_img_file_not_found;
$cnt_images_errors = $ce_page_img_title+$ce_page_img_alt+$ce_page_img_file_not_found;
}
/* links */
$link_str = '';
$link_array = array_filter(explode('<|-|>', $indexed_entries[$i]['page_links']));
$link_cnt = count($link_array);
if(is_array($link_array) && count($link_array) > 0) {
$link_str = '<table class="table table-sm">';
$link_str .= '<tr><td>href</td><td>Text</td><td>Title</td></tr>';
$maxChars = 25;
foreach($link_array as $k) {
$missing_title = false;
$this_link = explode('<|>', $k);
$link_text = $this_link[2];
$textLength = strlen($this_link[2]);
if($textLength > $maxChars) {
$link_text = substr_replace($this_link[2], ' ... ', $maxChars/2, $textLength-$maxChars);
}
$link_str .= '<tr>';
$link_str .= '<td><a href="'.$this_link[2].'" title="'.$this_link[2].'" class="">'.$link_text.'</a></td>';
if($this_link[1] == '') {
$this_link[1] = '<span class="text-danger">NULL</span>';
$ce_links_title++;
$ce_page_link_title++;
}
if($this_link[2] == '') {
$this_link[2] = '<span class="text-danger">NULL</span>';
}
$link_str .= '<td>'.$this_link[0].'</td>';
$link_str .= '<td>'.$this_link[1].'</td>';
$link_str .= '</tr>';
}
$link_str .= '</table>';
$link_errors_str = '<span class="text-danger">Errors:</span> Title: '.$page_link_title_errors.'<br>';
}
$tpl = $item_tpl;
$tpl = str_replace("{id}", $indexed_entries[$i]['page_id'], $tpl);
$tpl = str_replace("{url}", $url, $tpl);
$tpl = str_replace("{title}", $title, $tpl);
$tpl = str_replace("{description}", $description, $tpl);
$tpl = str_replace("{indexed_time}", $indexed_time, $tpl);
$tpl = str_replace("{page_content}", $indexed_entries[$i]['page_content'], $tpl);
$tpl = str_replace("{btn_update_info}", $icon['sync_alt'], $tpl);
$tpl = str_replace("{btn_start_index}", $icon['sitemap'], $tpl);
$tpl = str_replace("{btn_remove}", $icon['trash_alt'], $tpl);
$tpl = str_replace("{title_update_page_index}", $lang['btn_update_page_index'], $tpl);
$tpl = str_replace("{title_update_page_content}", $lang['btn_update_page_content'], $tpl);
$tpl = str_replace('{meta_str}', $meta_str, $tpl);
$tpl = str_replace('{cnt_meta_errors}', $cnt_meta_errors, $tpl);
$tpl = str_replace('{cnt_links}', $link_cnt, $tpl);
$tpl = str_replace('{cnt_links_errors}', $ce_page_link_title, $tpl);
$tpl = str_replace('{link_str}', $link_str, $tpl);
$tpl = str_replace('{headline_str}', $headlines_str, $tpl);
$tpl = str_replace('{cnt_headlines}', $cnt_headlines, $tpl);
$tpl = str_replace('{cnt_headline_errors}', $ce_page_headlines, $tpl);
$tpl = str_replace('{cnt_images}', $cnt_images, $tpl);
$tpl = str_replace('{cnt_images_errors}', $cnt_images_errors, $tpl);
$tpl = str_replace('{images_str}', $img_str, $tpl);
$tpl = str_replace('{csrf_token}', $hidden_csrf_token, $tpl);
echo $tpl;
}
echo '</div>';
echo '</div>';
echo '</fieldset>';
echo '</div>';
echo '<div class="col-sm-4">';
/**
* preferences for page index
*/
echo '<fieldset>';
echo '<legend>' . $lang['tab_page_preferences'] . '</legend>';
echo '<div class="scroll-box">';
echo '<div class="p-3">';
echo '<h5>Start</h5>';
echo '<form action="acp.php?tn=pages&sub=index" method="POST">';
echo '<div class="row">';
echo '<div class="col-8">';
echo '<input type="text" class="form-control" name="start_index" value="'.$fc_base_url.'">';
echo '</div>';
echo '<div class="col-4">';
echo '<button type="submit" name="start" class="btn btn-save w-100">'.$icon['sitemap'].'</button>';
echo '<input type="hidden" name="csrf_token" value="'.$_SESSION['token'].'">';
echo '</div>';
echo '</div>';
echo '</form>';
echo '<form action="?tn=pages&sub=index" method="POST">';
echo '<div class="btn-group d-flex mt-3" role="group">';
echo '<button name="start_index_bulk" class="btn btn-save">'.$icon['sitemap'].' '.$lang['btn_bulk_index'].'</button>';
echo '<button name="start_update_bulk" class="btn btn-save">'.$icon['sync_alt'].' '.$lang['btn_bulk_update'].'</button>';
echo '</div>';
echo $hidden_csrf_token;
echo '</form>';
echo '<hr>';
echo '<div class="well well-sm">';
echo '<table class="table table-sm">';
$ce_title_class = 'text-success';
if($ce_title > 0) {
$ce_title_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_title_class.'">'.$ce_title.'</td><td>'.$lang['label_missing_title'].'</td></tr>';
$ce_description_class = 'text-success';
if($ce_description > 0) {
$ce_description_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_description_class.'">'.$ce_description.'</td><td>'.$lang['label_missing_meta_description'].'</td></tr>';
$ce_img_alt_class = 'text-success';
if($ce_img_alt > 0) {
$ce_img_alt_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_img_alt_class.'">'.$ce_img_alt.'</td><td>'.$lang['label_missing_img_alt_tags'].'</td></tr>';
$ce_img_title_class = 'text-success';
if($ce_img_title > 0) {
$ce_img_title_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_img_title_class.'">'.$ce_img_title.'</td><td>'.$lang['label_missing_img_title_tags'].'</td></tr>';
$ce_links_title_class = 'text-success';
if($ce_links_title > 0) {
$ce_links_title_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_links_title_class.'">'.$ce_links_title.'</td><td>'.$lang['label_missing_link_title_tags'].'</td></tr>';
$ce_h1_class = 'text-success';
if($ce_h1 > 0) {
$ce_h1_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_h1_class.'">'.$ce_h1.'</td><td>'.$lang['label_missing_h1'].'</td></tr>';
$ce_h2_class = 'text-success';
if($ce_h2 > 0) {
$ce_h2_class = 'text-danger';
}
echo '<tr><td class="text-end '.$ce_h2_class.'">'.$ce_h2.'</td><td>'.$lang['label_missing_h2'].'</td></tr>';
echo '</table>';
echo '</div>';
echo '<h5 class="mt-3">Exclude elements</h5>';
echo '<form action="acp.php?tn=pages&sub=index" method="POST">';
echo '<table class="table table-sm">';
foreach($exclude_items as $ex_item) {
echo '<tr>';
echo '<td><code>'.$ex_item['item_element'].'</code></td>';
echo '<td><code>'.$ex_item['item_attributes'].'</code></td>';
echo '<td class="text-end">';
echo '<button name="del_exclude" value="'.$ex_item['item_id'].'" class="btn btn-danger btn-sm">'.$icon['trash_alt'].'</button>';
echo '</td>';
echo '<tr>';
}
echo '</table>';
echo $hidden_csrf_token;
echo '</form>';
/* form for exclude elements */
echo '<form action="acp.php?tn=pages&sub=index" method="POST">';
echo '<div class="row">';
echo '<div class="col-4">';
echo '<div class="form-group">';
echo '<label for="elements">Element</label>';
echo '<input type="text" class="form-control" name="exclude_element" id="elements" placeholder="div, span, footer ...">';
echo '</div>';
echo '</div>';
echo '<div class="col-4">';
echo '<div class="form-group">';
echo '<label for="attribute">ID/Class</label>';
echo '<input type="text" class="form-control" name="exclude_attribute" id="attribute" placeholder="#id, .class">';
echo '</div>';
echo '</div>';
echo '<div class="col-4">';
echo '<div class="form-group">';
echo '<label class="d-block"><br></label>';
echo '<input type="submit" name="add_excludes" value="'.$lang['save'].'" class="btn btn-save w-100">';
echo '<input type="hidden" name="csrf_token" value="'.$_SESSION['token'].'">';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</form><hr>';
echo '<h5>Exclude URLs</h5>';
echo '<form action="acp.php?tn=pages&sub=index" method="POST">';
echo '<table class="table table-sm">';
foreach($exclude_urls as $ex_url) {
echo '<tr>';
echo '<td><code>'.$ex_url['item_url'].'</code></td>';
echo '<td class="text-end">';
echo '<button name="del_exclude" value="'.$ex_url['item_id'].'" class="btn btn-danger btn-sm">'.$icon['trash_alt'].'</button>';
echo '</td>';
echo '<tr>';
}
echo '</table>';
echo $hidden_csrf_token;
echo '</form>';
/* form for exclude urls */
echo '<form action="acp.php?tn=pages&sub=index" method="POST">';
echo '<div class="row">';
echo '<div class="col-8">';
echo '<div class="form-group">';
echo '<label for="excludeUrls">URL</label>';
echo '<input type="text" name="exclude_url" class="form-control" id="excludeUrls" placeholder="/search/">';
echo '</div>';
echo '</div>';
echo '<div class="col-4">';
echo '<div class="form-group">';
echo '<label class="d-block"><br></label>';
echo '<input type="submit" name="add_exclude_url" value="'.$lang['save'].'" class="btn btn-save w-100">';
echo '<input type="hidden" name="csrf_token" value="'.$_SESSION['token'].'">';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</fieldset>';
echo '</div>';
echo '</div>';
echo '</div>'; // .max-height-container
echo '</div>'; // .app-container
?>
| flatCore/flatCore-CMS | acp/core/pages.index.php | PHP | gpl-3.0 | 16,732 |
<?php
// namespace Tests\AppBundle\Controller;
//
// use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
//
// class DefaultControllerTest extends WebTestCase
// {
// public function testIndex()
// {
// $client = static::createClient();
//
// $crawler = $client->request('GET', '/');
//
// $this->assertEquals(200, $client->getResponse()->getStatusCode());
// $this->assertContains('Welcome to Symfony', $crawler->filter('#container h1')->text());
// }
// }
| softwarejimenez/API_puja_por_tu_resi | tests/AppBundle/Controller/DefaultControllerTest.php | PHP | gpl-3.0 | 504 |
<?php
/**
* Modul pro konverzi textu
*
* @category Module
* @package Module
* @author onovy <onovy@nomi.cz>
*/
// Security
if (!defined('ONOVY_PHP_LIB')) die;
define('MODULE_I2HTML',1);
/**
* Konverze textu na HTML
*
* @param $input - vstupni text
* @param $typo - provadet typografickou upravu? true/false
* @return zkonvertovany text
*/
function i2html($input,$typo=true) {
$s=htmlspecialchars($input, null, 'ISO8859-1');
if ($typo && defined('MODULE_TYPO')) {
$s=typo($s);
}
$ends = array ("[a " => "[/a]",
"[a_nw " => "[/a]",
"[b]"=> "[/b]",
"[i]"=> "[/i]",
"[u]"=> "[/u]",
"[color "=> "[/color]",
"[size "=> "[/size]",
"[h1]"=> "[/h1]",
"[h2]"=> "[/h2]",
"[h3]"=> "[/h3]",
"[h4]"=> "[/h4]",
"[table]"=> "[/table]",
"[tr]"=> "[/tr]",
"[td]"=> "[/td]",
);
$s_low=strtolower($s);
foreach($ends as $begin => $end) {
$count = substr_count($s_low, $begin) - substr_count($s_low, $end);
if($count > 0)
$s .= str_repeat($end, $count);
}
$s=stri_replace("[b]","<strong>",$s);
$s=stri_replace("[/b]","</strong>",$s);
$s=stri_replace("[i]","<i>",$s);
$s=stri_replace("[/i]","</i>",$s);
$s=stri_replace("[u]","<span style='text-decoration: underline;'>",$s);
$s=stri_replace("[/u]","</span>",$s);
$s=stri_replace("[h1]","<h1>",$s);
$s=stri_replace("[/h1]","</h1>",$s);
$s=stri_replace("[h2]","<h2>",$s);
$s=stri_replace("[/h2]","</h2>",$s);
$s=stri_replace("[h3]","<h3>",$s);
$s=stri_replace("[/h3]","</h3>",$s);
$s=stri_replace("[h4]","<h4>",$s);
$s=stri_replace("[/h4]","</h4>",$s);
$s=stri_replace("[br]","<br />",$s);
$s=stri_replace("[table]","<table>",$s);
$s=stri_replace("[/table]","</table>",$s);
$s=stri_replace("[tr]","<tr>",$s);
$s=stri_replace("[/tr]","</tr>",$s);
$s=stri_replace("[td]","<td>",$s);
$s=stri_replace("[/td]","</td>",$s);
$s=preg_replace("/\[img (.*?)\]/i","<img src=\"/img/c/\\1\" alt='Obrazek' />",$s);
$s=preg_replace("/\[img_l (.*?)\]/i","<img src=\"/img/c/\\1\" class='left' alt='Obrazek' />",$s);
$s=preg_replace("/\[img_thumb (.*?)\]/i","<a href=\"/img/c/\\1\"><img src=\"/img/c/thumb/\\1\" alt='Obrazek' /></a>",$s);
$s=preg_replace("/\[a (.*?)\]/i","<a href=\"\\1\">",$s);
$s=preg_replace("/\[a_nw (.*?)\]/i","<a href=\"\\1\" onclick=\"window.open(this.href,'_blank');return false;\">",$s);
$s=preg_replace("/\[color (.*?)\]/i","<span style=\"color: \\1;\">",$s);
$s=preg_replace("/\[size (.*?)\]/i","<p style=\"font-size: \\1em\">",$s);
$s=stri_replace("[/a]","</a>",$s);
$s=stri_replace("[/color]","</span>",$s);
$s=stri_replace("[/size]","</p>",$s);
// aktivni promenne
if (strpos($s,'{poslední zmìna}')) {
$fa=db_fquery('SELECT DATE_FORMAT(last_action,"%d. %m. %Y") FROM admins ORDER BY admins.last_action DESC LIMIT 1');
$s=stri_replace("{poslední zmìna}",$fa[0],$s);
}
// seznamy
$arr=explode("\n",$s);
$open=false;
foreach ($arr as $pos=>$l) {
if (strlen($l)==1) {
$arr[$pos]="\n</p><p>\n";
} else {
$sub=substr($l[0],0,1);
if ($sub=='*' || $sub=='#') {
$open_type=$sub;
$arr[$pos]=substr($arr[$pos],1);
if (!$open) {
$open=true;
if ($sub=='*') {
$arr[$pos]="<ul><li>".$arr[$pos]."</li>";
} else {
$arr[$pos]="<ol><li>".$arr[$pos]."</li>";
}
} else {
$arr[$pos]="<li>".$arr[$pos]."</li>";
}
} else {
if ($open) {
if ($open_type=="*") {
$arr[$pos]="</ul>".$arr[$pos];
} else {
$arr[$pos]="</ol>".$arr[$pos];
}
}
$open=false;
$arr[$pos]=$arr[$pos]."<br />";
}
}
}
$s=implode("\n",$arr);
if ($open) $s.='</ul>';
return $s;
}
| onovy/KvizBot-web | onovyPHPlib/mlib/i2html.php | PHP | gpl-3.0 | 3,603 |
#include <QApplication>
#include "qtreversimenudialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ribi::reversi::QtReversiMenuDialog w;
w.show();
return a.exec();
}
| richelbilderbeek/Reversi | qtmain.cpp | C++ | gpl-3.0 | 201 |
<?php
namespace Code\Base\Paradigm\Helpers;
use Jarvis;
/**
* String utilities
*
* String related functions, particularly around token substitution
*
* PHP version 7.2+
*
* @category Utility
* @package Framework
* @author Rick Myers rick@enicity.com
* @since File available since Release 1.0.0
*/
class Str extends Helper implements \Countable, \ArrayAccess, \IteratorAggregate
{
private $string = null;
/**
* Constructor
*/
public function __construct($string=false, $exceptions = null) {
if ($string) {
$table = Jarvis::translateTable();
$this->string = (($table) ? str_replace($table['from'],$table['to'],$string) : $string);
}
}
/**
*
*
* @param array $strings
* @return array
*/
public static function createStrings(array $strings) {
foreach ($strings as &$string) {
$string = new static($string);
}
return $strings;
}
public function getIterator() {
return new ArrayIterator(static::createStrings(preg_split('#(?<!^)(?!$)#u'), $this->string));
}
public function length() {
return strlen($this->string);
}
public function part($start, $length = null) {
$this->string = substr($this->string, $start, $length);
return $this;
}
public function offsetExists($offset=false) {
return $this->length() >= $offset;
}
public function offsetSet($offset=false,$value) {
if ($this->length() < $offset) return;
$string = clone $this;
$start = $string->part(0, $offset);
$string = clone $this;
$end = $string->part($offset+1);
$this->string = $start.$value.$end;
return $this;
}
public function offsetGet($offset=false) {
$string = clone $this;
return $string->part($offset, 1);
}
public function offsetUnset($offset=false) {
$this->offsetSet($offset, '');
return $this;
}
public function append($string) {
$this->string .= $string;
return $this;
}
public function prepend($string) {
$this->string = $string.$this->string;
return $this;
}
public function lower() {
$this->string = strtolower($this->string);
return $this;
}
public function upper() {
$this->string = strtoupper($this->string);
return $this;
}
/**
* Multi-purpose function to return either the array length or string length of a passed in value or the default private string
*
* @param mixed $what
* @return int
*/
public function count($what=false) {
$total = 0;
$what = ($what) ? $what : ($this->string ? $this->string : null);
if ($what) {
$total = (is_array($what)) ? count($what) : strlen($what);
}
return $total;
}
public function __toString() {
return $this->string;
}
/**
* Formats a date to a standard output format
*
* @param type $arg
* @return string
*/
private function date($arg=false) {
$text = '??';
if ($arg) {
$text = date('m/d/Y',strtotime($arg));
}
return $text;
}
/**
* Formats a date to a standard output format
*
* @param type $arg
* @return string
*/
private function datetime($arg) {
$text = '??';
if ($arg) {
$text = date('m/d/Y H:i:s',strtotime($arg));
}
return $text;
}
/**
* A function has been detected in the activity message, parse it out and execute it
*
* @param type $text
*/
private function expandFunctions($text) {
$data = explode('@@',' '.$text);
$text = '';
for ($i = 0; $i < count($data); $i++) {
if (($i%2) == 0) {
$text .= $data[$i];
} else {
$func = explode('(',$data[$i]);
$arg = isset($func[1]) ? substr($func[1],0,strlen($func[1]-1)) : false;
if ($func[0] && $arg) {
eval('$text .= $this->'.$func[0].'('.$arg.');');
}
}
}
return $text;
}
/**
* Employs a substitution algorithm to replace parts of a string with segmented values
*
* @param type $text
* @param type $options
* @return type
*/
public function translate($text=false,$options=[]) {
$text = ($text) ? $text : ($this->string ? $this->string : '');
if (strpos($text,'%%') !== false) {
$data = explode('%%',' '.$text);
$text = '';
for ($i = 0; $i < count($data); $i++) {
if (($i%2) == 0) {
$text .= $data[$i];
} else {
$parts = explode('.',$data[$i]);
$var = '$options';
for ($j = 0; $j < count($parts); $j++) {
$var .= "['".$parts[$j]."']";
}
eval('$text .= '."$var".';');
}
}
}
if (strpos($text,'@@')!==false) {
$text = $this->expandFunctions($text);
}
return trim($text);
}
} | RickMyers/Jarvis | app/Code/Base/Paradigm/Helpers/Str.php | PHP | gpl-3.0 | 5,127 |
package abd.p1.model;
import java.util.Date;
import javax.persistence.*;
@Entity
public class MensajeAmistad extends Mensaje{
@Column
private boolean aceptado;
public MensajeAmistad(){
super();
}
public MensajeAmistad(Usuario usu, Usuario amigo){
super(usu, amigo);
aceptado = true;
}
public boolean isAceptado() {
return aceptado;
}
public void setAceptado(boolean aceptado) {
this.aceptado = aceptado;
}
@Override
public String toString() {
return "MensajeAmistad [aceptado=" + aceptado + "]";
}
}
| juanmont/ABD | practica1User/src/main/java/abd/p1/model/MensajeAmistad.java | Java | gpl-3.0 | 542 |
/*
* This file is part of trolCommander, http://www.trolsoft.ru/en/soft/trolcommander
* Copyright (C) 2014-2016 Oleg Trifonov
*
* trolCommander 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.
*
* trolCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.action.impl;
import com.mucommander.ui.action.AbstractActionDescriptor;
import com.mucommander.ui.action.ActionCategory;
import com.mucommander.ui.action.ActionDescriptor;
import com.mucommander.ui.action.MuAction;
import com.mucommander.ui.main.MainFrame;
import com.mucommander.ui.main.table.views.TableViewMode;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.util.Map;
/**
* @author Oleg Trifonov
* Created on 15/04/15.
*/
public class ToggleTableViewModeCompactAction extends MuAction {
/**
* Creates a new <code>ToggleTableViewModeCompactAction</code>
*
* @param mainFrame the MainFrame to associate with this new MuAction
* @param properties the initial properties to use in this action. The Hashtable may simply be empty if no initial
*/
ToggleTableViewModeCompactAction(MainFrame mainFrame, Map<String, Object> properties) {
super(mainFrame, properties);
}
@Override
public void performAction() {
getMainFrame().getActiveTable().setViewMode(TableViewMode.COMPACT);
}
@Override
public ActionDescriptor getDescriptor() {
return new Descriptor();
}
public static final class Descriptor extends AbstractActionDescriptor {
public static final String ACTION_ID = "ToggleTableViewModeCompact";
public String getId() { return ACTION_ID; }
public ActionCategory getCategory() { return ActionCategory.VIEW; }
public KeyStroke getDefaultAltKeyStroke() { return null; }
public KeyStroke getDefaultKeyStroke() {
return KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_DOWN_MASK);
}
public MuAction createAction(MainFrame mainFrame, Map<String, Object> properties) {
return new ToggleTableViewModeCompactAction(mainFrame, properties);
}
}
}
| Keltek/mucommander | src/main/com/mucommander/ui/action/impl/ToggleTableViewModeCompactAction.java | Java | gpl-3.0 | 2,674 |
# encoding: utf-8
module Gis::Model::Base::Status
def state_select
[["有効","enabled"],["無効","disabled"]]
end
def state_show
select = state_select
select.each{|a| return a[0] if a[1] == state}
return nil
end
def user_kind_select
[["個別ユーザ管理",1],["所属管理",2]]
end
def user_kind_show
select = user_kind_select
select.each{|a| return a[0] if a[1] == user_kind}
return nil
end
end
| joruri/joruri-maps | lib/gis/model/base/status.rb | Ruby | gpl-3.0 | 457 |
/*
* Copyright (c) 2004-2015 by Jakob Schröter <js@camaya.net>
* This file is part of the gloox library. http://camaya.net/gloox
*
* This software is distributed under a license. The full license
* agreement can be found in the file LICENSE in this distribution.
* This software may not be copied, modified, sold or distributed
* other than expressed in the named license agreement.
*
* This software is distributed without any warranty.
*/
#include "../../tag.h"
#include "../../util.h"
using namespace gloox;
#include <stdio.h>
#include <locale.h>
#include <string>
#include <cstdio> // [s]print[f]
int main( int /*argc*/, char** /*argv*/ )
{
int fail = 0;
std::string name;
Tag *t = new Tag( "toe" ); t->addAttribute( "foo", "bar" );
Tag *u = new Tag( t, "uni" ); u->addAttribute( "u3", "3u" );
Tag *v = new Tag( t, "vie" ); v->addAttribute( "v3", "3v" );
Tag *v2 = new Tag( t, "vie" ); v->addAttribute( "v32", "3v2" );
Tag *w = new Tag( u, "who" ); w->addAttribute( "w3", "3w" );
Tag *x = new Tag( v, "xep" ); x->addAttribute( "x3", "3x" );
Tag *y = new Tag( u, "yps" ); y->addAttribute( "y3", "3y" );
Tag *z = new Tag( w, "zoo" ); z->addAttribute( "z3", "3z" );
Tag *c = 0;
Tag *d = 0;
// -------
name = "simple ctor";
if( t->name() != "toe" )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
// -------
name = "cdata ctor";
c = new Tag( "cod", "foobar" );
if( c->name() != "cod" || c->cdata() != "foobar" )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
c = 0;
//-------
name = "clone test 1";
c = z->clone();
if( *z != *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
c = 0;
//-------
name = "clone test 2";
c = t->clone();
if( *t != *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
c = 0;
//-------
name = "operator== test 1";
c = new Tag( "name" );
if( *t == *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
c = 0;
//-------
name = "operator== test 2";
c = new Tag( "test" );
c->addAttribute( "me", "help" );
c->addChild( new Tag( "yes" ) );
if( *t == *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
c = 0;
//-------
name = "operator== test 3";
c = new Tag( "hello" );
c->addAttribute( "test", "bacd" );
c->addChild( new Tag( "hello" ) );
d = new Tag( "hello" );
d->addAttribute( "test", "bacd" );
d->addChild( new Tag( "helloo" ) );
if( *d == *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
delete d;
c = 0;
d = 0;
//-------
name = "operator!= test 1";
c = new Tag( "hello" );
c->addAttribute( "test", "bacd" );
c->addChild( new Tag( "hello" ) );
d = new Tag( "hello" );
d->addAttribute( "test", "bacd" );
d->addChild( new Tag( "hello" ) );
if( *d != *c )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
delete c;
delete d;
c = 0;
d = 0;
//-------
name = "findChildren test";
TagList l = t->findChildren( "vie" );
TagList::const_iterator it = l.begin();
if( l.size() != 2 || (*it) != v || *(++it) != v2 )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
//-------
name = "util::escape";
if ( util::escape( "&<>'\"" ) != "&<>'"" )
{
++fail;
fprintf( stderr, "test '%s' failed\n", name.c_str() );
}
//-------
name = "xml() 1";
if( t->xml() != "<toe foo='bar'><uni u3='3u'><who w3='3w'><zoo z3='3z'/></who><yps y3='3y'/>"
"</uni><vie v3='3v' v32='3v2'><xep x3='3x'/></vie><vie/></toe>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "xml() 2";
t->addAttribute( "test", "bacd" );
if( t->xml() != "<toe foo='bar' test='bacd'><uni u3='3u'><who w3='3w'><zoo z3='3z'/></who><yps y3='3y'/>"
"</uni><vie v3='3v' v32='3v2'><xep x3='3x'/></vie><vie/></toe>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "hasChild 1";
if( !t->hasChild( "uni" ) || !t->hasChild( "vie" ) || !u->hasChild( "who" ) || !w->hasChild( "zoo" )
|| !u->hasChild( "yps" ) )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "hasAttribute 1";
if( !t->hasAttribute( "test" ) || !t->hasAttribute( "test", "bacd" )
|| !t->hasAttribute( "foo" ) || !t->hasAttribute( "foo", "bar" ) )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findAttribute 1";
if( t->findAttribute( "test" ) != "bacd" || t->findAttribute( "foo" ) != "bar" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findChild 1";
c = t->findChild( "uni" );
if( c != u )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findChild 2";
c = t->findChild( "uni", "u3" );
if( c != u )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findChild 3";
c = t->findChild( "uni", "u3", "3u" );
if( c != u )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findChildWithAttrib 1";
c = t->findChildWithAttrib( "u3" );
if( c != u )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "findChildWithAttrib 2";
c = t->findChildWithAttrib( "u3", "3u" );
if( c != u )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t->xml().c_str() );
}
//-------
name = "attribute order";
c = new Tag( "abc" );
c->addAttribute( "abc", "def" );
c->addAttribute( "xyz", "123" );
d = c->clone();
if( *c != *d )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), d->xml().c_str() );
}
delete c;
c = 0;
delete d;
d = 0;
//-------
name = "mixed content 1";
c = new Tag( "abc" );
c->addCData( "cdata1" );
new Tag( c, "fgh" );
c->addCData( "cdata2" );
new Tag( c, "xyz" );
c->addCData( "cdata3" );
if( c->xml() != "<abc>cdata1<fgh/>cdata2<xyz/>cdata3</abc>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), c->xml().c_str() );
}
delete c;
c = 0;
//-------
name = "operator bool()";
Tag tag1( "" );
if( tag1 )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), tag1.xml().c_str() );
}
//-------
name = "bool operator!()";
Tag tag2( "abc" );
if( !tag2 )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), d->xml().c_str() );
}
//-------
{
name = "simple xmlns";
Tag t( "abc" );
t.setXmlns( "foo" );
if( t.xml() != "<abc xmlns='foo'/>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "deep xmlns";
Tag t( "abc" );
Tag* f = new Tag( &t, "def" );
f = new Tag( f, "ghi" );
t.setXmlns( "foo" );
if( t.xml() != "<abc xmlns='foo'><def><ghi/></def></abc>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "simple nested xmlns 2";
Tag t( "abc" );
t.setXmlns( "foo" );
Tag* d = new Tag( &t, "def" );
d->setXmlns( "foobar", "xyz" );
d->setPrefix( "xyz" );
if( t.xml() != "<abc xmlns='foo'><xyz:def xmlns:xyz='foobar'/></abc>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "attribute with xmlns";
Tag t( "abc" );
t.setXmlns( "foo", "xyz" );
Tag::Attribute* a = new Tag::Attribute( "foo", "bar", "foo" );
a->setPrefix( "xyz" );
t.addAttribute( a );
if( t.xml() != "<abc xmlns:xyz='foo' xyz:foo='bar'/>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "escape attribute value";
Tag t( "foo", "abc", "&" );
if( t.xml() != "<foo abc='&amp;'/>" )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "remove child 1";
Tag t( "foo" );
t.addChild( new Tag( "test", "xmlns", "foo" ) );
t.addChild( new Tag( "abc", "xmlns", "foobar" ) );
t.addAttribute( "attr1", "value1" );
t.addAttribute( "attr2", "value2" );
t.removeChild( "test" );
if( t.hasChild( "test" ) )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
name = "remove child 2";
t.removeChild( "abc", "foobar" );
if( t.hasChild( "abc", "xmlns", "foobar" ) )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
name = "remove attrib 1";
t.removeAttribute( "attr1" );
if( t.hasAttribute( "attr1", "value1") )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
name = "remove attrib 2";
t.removeAttribute( "attr2", "value2" );
if( t.hasAttribute( "attr2", "value2") )
{
++fail;
fprintf( stderr, "test '%s' failed: %s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "invalid chars 1";
Tag t( "foo" );
bool check = t.addAttribute( "nul", std::string( 1, 0x00 ) );
if( check || t.hasAttribute( "nul" ) )
{
++fail;
fprintf( stderr, "test '%s' failed:%s\n", name.c_str(), t.xml().c_str() );
}
}
//-------
{
name = "invalid chars 2";
for( int i = 0; i <= 0xff; ++i )
{
Tag::Attribute a( "test", std::string( 1, i ) );
if( ( i < 0x09 || i == 0x0b || i == 0x0c
|| ( i > 0x0d && i < 0x20 ) || i == 0xc0
|| i == 0xc1 || i >= 0xf5 ) && a )
{
++fail;
fprintf( stderr, "test '%s' (branch 1) failed (i == %02X)\n", name.c_str(), i );
}
else if( ( i == 0x09 || i == 0x0a || i == 0x0d
|| ( i >= 0x20 && i < 0xc0 )
|| ( i > 0xc1 && i < 0xf5 ) ) && !a )
{
++fail;
fprintf( stderr, "test '%s' (branch 2) failed (i == %02X)\n", name.c_str(), i );
}
// printf( "i: 0x%02X, a: %d, value: %s\n", i, (bool)a, std::string( 1, i ).c_str() );
}
}
delete t;
t = 0;
if( fail == 0 )
{
printf( "Tag: OK\n" );
return 0;
}
else
{
fprintf( stderr, "Tag: %d test(s) failed\n", fail );
return 1;
}
}
| naseef-07/gloox_lib_with_vs2013_project_file | src/tests/tag/tag_test.cpp | C++ | gpl-3.0 | 11,044 |
/* File: RA250.H 'C' structures for RemoteAccess 2.50 Gamma
Version: 0.3 (22/04/96)
Author: Damien Guard
Copyright: Envy Technologies, 1996.
Changes: 0.1 - Initial release
0.2 - Fixed some compile problems
Sorted enumeration types
0.3 - Added some examples
All new documentation (+Write format)
CRC routines
Notes: These are neither official structures nor authorised by
Wantree Development.
Always make sure "Allocate enums as int's" is OFF!
They should be allocated as CHAR.
This document formatted with tab's as three(3) characters
WARNING: These structures have not been fully tested.
I have only tested CONFIG.RA (CONFIGrecord) extensively.
Info: Please e-mail suggestions to : envy@guernsey.net
Latest version available at : http://www.guernsey.net/~envy
If you use this structure in your software please include something like
'This product uses the RA 'C' Developer Kit from Envy Technologies' -
it's not much to ask and using any part of the RACDK in your software
is free (in compiled form - see RACDK.DOC for more information)
*/
/* C <> Pascal string conversion macros from SNIPPETS 'C' library
C <> Pascal string copy macros by Damien Guard
Convert a string:
Pas2C(string) to convert string from Pascal to C (ie. after READING)
C2Pas(string) to convert string to Pascal from C (ie. before WRITING)
Copy a string:
cpyPas2C(destination,source) to copy from a Pascal string to a C string
cpyC2Pas(destination,source) to copy from a C string to a Pascal string */
typedef unsigned char UCHAR;
#define Pas2C(s) {UCHAR n = *(s); memmove((s), &(s)[1], n); s[n] = '\0';}
#define C2Pas(s) {int n = strlen(s); memmove(&(s)[1], (s), n); *(s) = n;}
#define cpyPas2C(d,s) {UCHAR n = *(s); memmove((d), &(s)[1], n); d[n] = '\0';}
#define cpyC2Pas(d,s) {int n = strlen(s); memmove(&(d)[1], (s), n); *(d) = n;}
/* Fake Pascal boolean type for clarity */
typedef unsigned char booleanf;
/* enums here for clarity - not sure if they work */
enum AskType {Yes, No, Ask, Only};
enum VideoType {Auto, Short, Long};
enum MsgType {LocalMail, NetMail, EchoMail, Internet, Newsgroup};
enum MsgKindsType {Both, Private, Public, ROnly, NoReply};
enum OrphanType {Ignore, Create, Kill };
enum ResetType {Never, Week, Month, Year};
/* Typedef the RemoteAccess 'types' */
typedef unsigned char FlagType[4];
typedef unsigned char TimeF[6]; /* Time format */
typedef unsigned char DateF[9]; /* Date format */
typedef unsigned char LongDate[10]; /* Long date format */
typedef unsigned char ByteArray32[32];
typedef unsigned char MSGTOIDXrecord[36];
typedef unsigned char MSGTXTrecord[256];
typedef unsigned int LASTREADrecord[200];
typedef unsigned int COMBINEDrecord[200];
/* Mail network address (internal) */
struct NetAddress {
unsigned int Zone,
Net,
Node,
Point;
};
/* Security limits (LIMITS.RA) */
struct LIMITSrecord {
unsigned int Security,
Ltime,
L300,
L1200,
L2400,
L4800,
L7200,
L9600,
L12000,
L14400,
L16800,
L19200,
L38400,
Llocal,
RatioNum,
RatioK;
float PerMinCost;
unsigned int L21600,
L24000,
L26400,
L28800,
L57600,
L64000;
float FlexiTime;
unsigned int LsessionTime,
ResetAmt;
enum ResetType ResetPeriod;
unsigned int ResetOffset,
L31200,
L33600;
unsigned char FreeSpace[14];
};
/* Languages (LANGUAGE.RA) */
struct LANGUAGErecord {
unsigned char Name[21],
Attribute,
DefName[61],
MenuPath[61],
TextPath[61],
QuesPath[61];
unsigned int Security;
FlagType Flags,
NotFlagsMask;
unsigned char FreeSpace[191];
};
/* Hudson message information (MSGINFO.BBS) */
struct MSGINFOrecord {
unsigned int LowMsg,
HighMsg,
TotalMsgs;
unsigned char TotalOnBoard[200];
};
/* Hudson message index (MSGIDX.BBS) */
struct HMBMSGIDXrecord {
unsigned int MsgNum;
unsigned char Board;
};
/* Hudson message headers (MSGHDR.BBS) */
struct HMBMSGHDRrecord {
unsigned int MsgNum,
PrevReply,
NextReply,
TimesRead,
StartBlock,
NumBlocks,
DestNet,
DestNode,
OrigNet,
OrigNode,
DestZone;
unsigned char OrigZone;
unsigned int Cost;
unsigned char MsgAttr,
NetAttr,
Board;
TimeF PostTime;
DateF PostDate;
MSGTOIDXrecord WhoTo,
WhoFrom;
unsigned char Subject[73];
};
/* Current online status (USERON.BBS) */
struct USERONrecord {
MSGTOIDXrecord Name,
Handle;
unsigned char Line;
unsigned int Baud;
unsigned char City[26],
Status,
/* 0 : Browsing/menu
1 : File transfer
2 : Messaging
3 : Door
4 : Sysop chat
5 : Questionnaire
6 : Real-time-conferencing
7 : New user logon
255 : User-defined - display StatDesc */
Attribute,
/* Bit 0 : Hidden
1 : Wants chat
2 : Reserved for RANETMGR (RA/Pro)
3 : Do not disturb flag
6 : Ready */
StatDesc[11],
FreeSpace[98];
unsigned int NoCalls;
};
/* Todays callers list (LASTCALL.BBS) */
struct LASTCALLrecord {
unsigned char Line;
MSGTOIDXrecord Name,
Handle;
unsigned char City[26];
unsigned int Baud;
long Times;
unsigned char LogOn[6],
LogOff[6];
unsigned char Attribute;
/* Bit 0 : Hidden */
};
/* File area header (FDBxxx.HDR) */
struct FILESHDRrecord {
unsigned char Name[13];
long Size,
CRC32;
unsigned char Uploader[36];
long UploadDate,
FileDate,
LastDL;
unsigned int TimesDL;
unsigned char Attrib,
/* Bit 0 : Deleted
1 : Unlisted
2 : Free - Does NOT affect "Cost"
3 : Not available (don't allow downloads)
4 : Locked (no kill)
5 : Missing/offline
6 : No time restrictions - always allow DL */
Password[16],
KeyWord [5] [16];
unsigned int Cost;
long LongDescPtr;
unsigned char FreeSpace[20];
};
/* File area index (FDBxxx.IDX) */
struct FILESIDXrecord {
unsigned char Name[13];
long UploadDate,
KeyWordCRC[5],
LongDescPtr;
};
/* User base index (USERSIDX.BBS) */
struct USERSIDXrecord {
long NameCRC32,
HandleCRC32;
};
/* User base (USERS.BBS) */
struct USERSrecord {
MSGTOIDXrecord Name;
unsigned char Location[26],
Organisation[51],
Address1[51],
Address2[51],
Address3[51],
Handle[36],
Comment[81];
long PasswordCRC;
unsigned char DataPhone[16],
VoicePhone[16];
TimeF LastTime;
DateF LastDate;
unsigned char Attribute,
/* Bit 0 : Flagged for delete
1 : Clear screen
2 : More? prompt
3 : ANSI emulation
4 : No-kill
5 : Xfer priority
6 : Full screen msg editor
7 : Quiet mode */
Attribute2;
/* Bit 0 : Hot-keys
1 : AVT/0 (Avatar)
2 : Full screen message viewer
3 : Hidden
4 : Page priority
5 : No echomail in mailbox scan
6 : Guest account
7 : Post bill enabled */
FlagType Flags;
long Credit,
Pending;
unsigned int MsgsPosted,
Security;
long LastRead,
NoCalls,
Uploads,
Downloads,
UploadsK,
DownloadsK,
TodayK;
int Elapsed;
unsigned int ScreenLength;
unsigned char LastPwdChange;
unsigned int Group;
COMBINEDrecord CombinedInfo;
DateF FirstDate,
BirthDate,
SubDate;
unsigned char ScreenWidth,
Language,
DateFormat,
ForwardTo[36];
unsigned int MsgArea,
FileArea;
unsigned char DefaultProtocol;
unsigned int FileGroup;
unsigned char LastDOBCheck,
Sex;
long XIrecord;
unsigned int MsgGroup;
unsigned char Attribute3,
/* Bit 0 : Mailbox check: scan selected areas only */
Password[16],
FreeSpace[31];
};
/* User base index (USERSXI.BBS) */
struct USERSXIrecord {
unsigned char FreeSpace[200];
};
/* System information (SYSINFO.BBS) */
struct SYSINFOrecord {
long TotalCalls;
MSGTOIDXrecord LastCaller,
LastHandle;
unsigned char ExtraSpace[92];
};
/* Timelog stat (TIMELOG.BBS) for EACH node */
struct TIMELOGrecord {
DateF StartDate;
unsigned int BusyPerHour[24],
BusyPerDay[7]; /* not implemented */
};
/* Menu (*.MNU) */
struct MNUrecord {
unsigned char Typ;
unsigned int Security,
MaxSec;
FlagType NotFlagsMask,
Flags;
unsigned int TimeLeft,
TimeUsed;
unsigned char Age,
TermAttrib;
/* Bit 0 : ANSI
1 : Avatar
2 : RIPscript */
long MinSpeed,
MaxSpeed,
Credit,
OptionCost,
PerMinCost;
ByteArray32 Node,
Group;
unsigned int StartTime[7],
StopTime[7];
unsigned char Display[136],
HotKey[9],
MiscData[136],
Foreground,
Background,
FreeSpace[50];
};
/* System events (EVENTS.RA) */
struct EVENTrecord {
unsigned char Status; /* 0=Deleted 1=Enabled 2=Disabled */
TimeF StartTime;
unsigned char ErrorLevel,
Days;
booleanf Forced;
DateF LastTimeRun;
};
struct EVENTrecord EVENTrecordArray[20];
/* Message area configuration (MESSAGES.RA) */
struct MESSAGErecord {
unsigned int AreaNum,
Unused;
unsigned char Name[41];
enum MsgType Typ;
enum MsgKindsType MsgKinds;
unsigned char Attribute,
/* Bit 0 : Enable EchoInfo
1 : Combined access
2 : File attaches
3 : Allow aliases
4 : Use SoftCRs as characters
5 : Force handle
6 : Allow deletes
7 : Is a JAM area */
DaysKill, /* Kill older than 'x' days */
RecvKill; /* Kill recv msgs, recv for more than 'x' days */
unsigned int CountKill,
ReadSecurity;
FlagType ReadFlags,
ReadNotFlags;
unsigned int WriteSecurity;
FlagType WriteFlags,
WriteNotFlags;
unsigned int SysopSecurity;
FlagType SysopFlags,
SysopNotFlags;
unsigned char OriginLine[61],
AkaAddress,
Age,
JAMbase[61];
unsigned int Group,
AltGroup[3];
unsigned char Attribute2;
/* Bit 0 : Include in all groups */
unsigned int NetmailArea;
unsigned char FreeSpace2[7];
};
/* Groups (MGROUPS.RA & FGROUPS.RA) */
struct GROUPrecord {
unsigned int AreaNum;
unsigned char Name[41];
unsigned int Security;
FlagType Flags,
NotFlagsMask;
unsigned char FreeSpace[100];
};
/* File area configuration (FILES.RA) */
struct FILESrecord {
unsigned int AreaNum,
Unused;
unsigned char Name[41],
Attrib,
/* Bit 0 : Include in new files scan
1 : Include in upload dupe scan
2 : Permit long descriptions
3 : Area is on CD-ROM
4 : All files are FREE
5 : Allow DLs not in FDB
6 : Allow users to password uploads
7 : Scan uploads */
FilePath[41];
unsigned int KillDaysDL,
KillDaysFD;
unsigned char Password[16];
unsigned int MoveArea;
unsigned char Age,
ConvertExt;
unsigned int Group;
unsigned char Attrib2;
/* Bit 0 : Include in all groups */
unsigned int DefCost,
UploadArea,
UploadSecurity;
FlagType UploadFlags,
UploadNotFlags;
unsigned int Security;
FlagType Flags,
NotFlags;
unsigned int ListSecurity;
FlagType ListFlags,
ListNotFlags;
unsigned int AltGroup[3];
unsigned char Device,
FreeSpace[13];
};
/* Multi-line conferencing (CONF.RA?) */
struct CONFrecord {
unsigned char Name[9],
Parent[9],
Desc[71],
Attr,
/* Bit 0 : Private
1 : Unlisted
2 : Global
3 : Permanent
4 : Use handles */
Moderator[36],
Language[21],
Password[16];
unsigned int Security;
FlagType Flags;
unsigned char NumNodes,
Active[250];
booleanf Child[250];
FlagType NotFlagsMask;
unsigned char FreeSpace[96];
};
/* Modem configuration (MODEM.RA) */
struct MODEMrecord {
unsigned char ComPort,
InitTries;
unsigned int BufferSize,
ModemDelay;
long MaxSpeed;
booleanf SendBreak,
LockModem,
AnswerPhone,
OffHook;
unsigned char InitStr[71],
InitStr2[71],
BusyStr[71],
InitResp[41],
BusyResp[41],
Connect300[41],
Connect1200[41],
Connect2400[41],
Connect4800[41],
Connect7200[41],
Connect9600[41],
Connect12k[41],
Connect14k[41],
Connect16k[41],
Connect19k[41],
Connect38k[41],
ConnectFax[41],
RingStr[21],
AnswerStr[21],
ErrorFreeString[16],
Connect21k[41],
Connect24k[41],
Connect26k[41],
Connect28k[41],
Connect57k[41],
Connect64k[41],
Connect31k[41],
Connect33k[41],
FreeSpace[100];
};
/* Archiver control (internal) */
struct ARCrecord {
unsigned char Extension[4],
UnpackCmd[61],
PackCmd[61];
};
/* Main configuration (CONFIG.RA) */
/* All fields prefixed with 'x' no longer in use */
struct CONFIGrecord {
unsigned int VersionID;
unsigned char xCommPort; /* unused - found in MODEM.RA */
long xBaud; /* unused - found in MODEM.RA */
unsigned char xInitTries, /* unused - found in MODEM.RA */
xInitStr[71], /* unused - found in MODEM.RA */
xBusyStr[71], /* unused - found in MODEM.RA */
xInitResp[41], /* unused - found in MODEM.RA */
xBusyResp[41], /* unused - found in MODEM.RA */
xConnect300[41], /* unused - found in MODEM.RA */
xConnect1200[41],/* unused - found in MODEM.RA */
xConnect2400[41],/* unused - found in MODEM.RA */
xConnect4800[41],/* unused - found in MODEM.RA */
xConnect9600[41],/* unused - found in MODEM.RA */
xConnect19k[41], /* unused - found in MODEM.RA */
xConnect38k[41]; /* unused - found in MODEM.RA */
booleanf xAnswerPhone; /* unused - found in MODEM.RA */
unsigned char xRing[21], /* unused - found in MODEM.RA */
xAnswerStr[21]; /* unused - found in MODEM.RA */
booleanf xFlushBuffer; /* unused - found in MODEM.RA */
int xModemDelay; /* unused - found in MODEM.RA */
unsigned int MinimumBaud,
GraphicsBaud,
TransferBaud;
TimeF SlowBaudTimeStart,
SlowBaudTimeEnd,
DownloadTimeStart,
DownloadTimeEnd,
PageStart[7],
PageEnd[7];
unsigned char SeriNum[23],
CustNum[23],
FreeSpace1[24];
unsigned int PwdExpiry;
unsigned char MenuPath[61],
TextPath[61],
AttachPath[61],
NodelistPath[61],
MsgBasePath[61],
SysPath[61],
ExternalEdCmd[61];
struct NetAddress
Address[10]; /* 0 = Main address, 1 = AKA 1... */
unsigned char SystemName[31];
unsigned int NewSecurity,
NewCredit;
FlagType NewFlags;
unsigned char OriginLine[61],
QuoteString[16],
Sysop[36],
LogFileName[61];
booleanf FastLogon,
AllowSysRem,
MonoMode,
StrictPwdChecking,
DirectWrite,
SnowCheck;
int CreditFactor;
unsigned int UserTimeOut,
LogonTime,
PasswordTries,
MaxPage,
PageLength;
booleanf CheckForMultiLogon,
ExcludeSysopFromList,
OneWordNames;
enum AskType CheckMail;
booleanf AskVoicePhone,
AskDataPhone,
DoFullMailCheck,
AllowFileShells,
FixUploadDates,
FreezeChat;
enum AskType ANSI, /* ANSI: Yes/no/ask new users */
ClearScreen, /* Clear: " " */
MorePrompt; /* More: " " */
booleanf UploadMsgs;
enum AskType KillSent; /* Kill/Sent " */
unsigned int CrashAskSec; /* Min sec# to ask 'Crash Mail ?' */
FlagType CrashAskFlags;
unsigned int CrashSec; /* Min sec# to always send crash mail */
FlagType CrashFlags;
unsigned int FAttachSec; /* " ask 'File Attach ?' */
FlagType FAttachFlags;
unsigned char NormFore, /* foreground & background colours */
NormBack,
StatFore,
StatBack,
HiBack,
HiFore,
WindFore,
WindBack,
ExitLocal, /* exit error levels - Unused?*/
Exit300,
Exit1200,
Exit2400,
Exit4800,
Exit9600,
Exit19k,
Exit38k;
booleanf MultiLine;
unsigned char MinPwdLen;
unsigned int MinUpSpace;
enum AskType HotKeys;
unsigned char BorderFore,
BorderBack,
BarFore,
BarBack,
LogStyle,
MultiTasker,
PwdBoard;
unsigned int xBufferSize; /* unused - found in MODEM.RA */
unsigned char FKeys[10] [61];
booleanf WhyPage;
unsigned char LeaveMsg;
booleanf ShowMissingFiles,
xLockModem; /* unused - found in MODEM.RA */
unsigned char FreeSpace2[10];
booleanf AllowNetmailReplies;
unsigned char LogonPrompt[41];
enum AskType CheckNewFiles;
unsigned char ReplyHeader[61];
unsigned char BlankSecs;
unsigned char ProtocolAttrib[6];
unsigned char xErrorFreeString[16], /* unused - found in MODEM.RA */
xDefaultCombined[25]; /* replaced with DefaultCombined */
unsigned int RenumThreshold;
unsigned char LeftBracket,
RightBracket;
booleanf AskForHandle,
AskForBirthDate;
unsigned int GroupMailSec;
booleanf ConfirmMsgDeletes;
unsigned char FreeSpace4[30],
TempScanDir[61];
enum AskType ScanNow;
unsigned char xUnknownArcAction, /* unused - found in ARCHIVE.RA ?*/
xFailedUnpackAction,/* unused - found in ARCHIVE.RA ?*/
FailedScanAction;
/* Bit 0 : Mark deleted,
1 : Mark unlisted,
2 : Mark not available */
unsigned int xUnknownArcArea, /* no longer in use */
xFailedUnpackArea, /* no longer in use */
FailedScanArea;
unsigned char ScanCmd[61];
booleanf xDeductIfUnknown; /* no longer in use */
unsigned char NewUserGroup;
enum AskType AVATAR;
unsigned char BadPwdArea,
Location[41],
DoAfterAction, /* 0 = wait for CR
else wait for x seconds */
OldFileLine[41], /* unused - replaced with FileLine*/
CRfore,
CRback,
LangHdr[41];
booleanf xSendBreak; /* unused - found in MODEM.RA */
unsigned char ListPath[61]; /* unused ??*/
enum AskType FullMsgView,
EMSI_Enable;
booleanf EMSI_NewUser;
unsigned char EchoChar[2],
xConnect7200[41], /* unused - found in MODEM.RA */
xConnect12000[41], /* unused - found in MODEM.RA */
xConnect14400[41], /* unused - found in MODEM.RA */
Exit7200,
Exit12000,
Exit14400,
ChatCommand[61];
enum AskType ExtEd;
unsigned char NewuserLanguage,
LanguagePrompt[41];
enum VideoType VideoMode;
booleanf AutoDetectANSI,
xOffHook; /* unused - found in MODEM.RA */
unsigned char NewUserDateFormat;
unsigned char KeyboardPwd[16];
booleanf CapLocation;
unsigned char NewuserSub,
PrinterName[5],
HilitePromptFore, /* note lowercase 'l' in hilite */
HiLitePromptBack,
xInitStr2[71]; /* unused - found in MODEM.RA */
booleanf AltJSwap;
unsigned char SemPath[61];
booleanf AutoChatCapture;
unsigned char FileBasePath[61];
booleanf NewFileTag,
IgnoreDupeExt;
unsigned char TempCDFilePath[61],
TagFore,
TagBack,
xConnect16k[41], /* unused - found in MODEM.RA */
Exit16k,
FilePayback,
FileLine[201],
FileMissingLine[201],
NewUserULCredit;
unsigned int NewUserULCreditK;
struct ARCrecord
ArcInfo[10];
unsigned char RAMGRAltFKeys [5] [61],
ArcViewCmd[61],
xConnectFax[41], /* unused - found in MODEM.RA */
ExitFax;
booleanf UseXMS,
UseEMS;
unsigned char CheckDOB;
enum AskType EchoCheck;
unsigned int ccSec,
ReturnRecSec;
booleanf HonourNetReq;
COMBINEDrecord DefaultCombined;
booleanf AskForSex,
AskForAddress;
enum AskType DLdesc;
booleanf NewPhoneScan;
unsigned char Exit21k,
Exit24k,
Exit26k,
Exit28k,
Exit57k,
Exit64k;
booleanf TagLogoffWarning, /* RA 2.5 - Warn if files are tagged
at log off */
LimitLocal, /* RA 2.5 - Turn off sysop control
keys for non-sysop local users*/
SavePasswords; /* RA 2.5 - Save user passwords */
unsigned char BlankLogins, /* RA 2.5 - Log off after x blank
logins (returns)*/
ripiconpath[61], /* RA 2.5 - Path to RIPscript icons */
Exit31k, /* RA 2.5 - Exit level for 31kbps */
Exit33k; /* RA 2.5 - Exit level for 33kbps */
booleanf IncludeNewCDareas;/* RA 2.5 - Include CD areas in new
files list */
unsigned char FutureExpansion[513];
};
/* Exit-info dropfile (EXITINFO.BBS) */
struct EXITINFOrecord {
unsigned int Baud;
struct SYSINFOrecord
SysInfo;
struct TIMELOGrecord
TimeLogInfo;
struct USERSrecord
UserInfo;
struct EVENTrecord
EventInfo;
booleanf NetMailEntered,
EchoMailEntered;
TimeF LoginTime;
DateF LoginDate;
unsigned int TimeLimit;
long LoginSec;
unsigned int UserRecord,
ReadThru,
NumberPages,
DownloadLimit;
TimeF TimeOfCreation;
long LogonPasswordCRC;
booleanf WantChat;
int DeductedTime;
unsigned char MenuStack [50] [9],
MenuStackPointer;
struct USERSXIrecord
UserXIinfo;
booleanf ErrorFreeConnect,
SysopNext,
EMSI_Session;
unsigned char EMSI_Crtdef[41],
EMSI_Protocols[41],
EMSI_Capabilities[41],
EMSI_Requests[41],
EMSI_Software[41],
Hold_Attr1,
Hold_Attr2,
Hold_Len,
PageReason[81],
StatusLine,
LastCostMenu[9];
unsigned int MenuCostPerMin;
booleanf DoesAVT,
RIPmode,
RIPVersion;
unsigned char ExtraSpace[85];
};
/* File transfer protocols (PROTOCOL.RA) */
struct PROTOCOLrecord {
unsigned char Name[16],
ActiveKey;
booleanf OpusTypeCtlFile,
BatchAvailable;
unsigned char Attribute,
/* 0=Disabled
1=Enabled */
LogFileName[81],
CtlFileName[81],
DnCmdString[81],
DnCtlString[81],
UpCmdString[81],
UpCtlString[81],
UpLogKeyword[21],
DnLogKeyword[21];
unsigned int XferDescWordNum,
XferNameWordNum;
}; | damieng/graveyard | remoteaccess-bbs/ra-cdk/RA250C.H | C++ | gpl-3.0 | 27,536 |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as f:
requirements = f.read().splitlines()
with open('cli-requirements.txt') as f:
cli_requirements = f.read().splitlines()
setuptools.setup(
name="uwg",
use_scm_version=True,
setup_requires=['setuptools_scm'],
author="Ladybug Tools",
author_email="info@ladybug.tools",
description="Python application for modeling the urban heat island effect.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ladybug-tools/uwg",
packages=setuptools.find_packages(exclude=["tests*", "resources*"]),
include_package_data=True,
install_requires=requirements,
extras_require={
'cli': cli_requirements
},
entry_points={
"console_scripts": ["uwg = uwg.cli:main"]
},
classifiers=[
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent"
],
)
| chriswmackey/UWG_Python | setup.py | Python | gpl-3.0 | 1,278 |
/*
* Copyright (C) 2014 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.support.v17.leanback.widget;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.ColorInt;
import android.support.v17.leanback.R;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
/**
* <p>A widget that draws a search affordance, represented by a round background and an icon.</p>
*
* The background color and icon can be customized.
*/
public class SearchOrbView extends FrameLayout implements View.OnClickListener {
private OnClickListener mListener;
private View mRootView;
private View mSearchOrbView;
private ImageView mIcon;
private Drawable mIconDrawable;
private Colors mColors;
private final float mFocusedZoom;
private final int mPulseDurationMs;
private final int mScaleDurationMs;
private final float mUnfocusedZ;
private final float mFocusedZ;
private ValueAnimator mColorAnimator;
/**
* A set of colors used to display the search orb.
*/
public static class Colors {
private static final float sBrightnessAlpha = 0.15f;
/**
* Constructs a color set using the given color for the search orb.
* Other colors are provided by the framework.
*
* @param color The main search orb color.
*/
public Colors(@ColorInt int color) {
this(color, color);
}
/**
* Constructs a color set using the given colors for the search orb.
* Other colors are provided by the framework.
*
* @param color The main search orb color.
* @param brightColor A brighter version of the search orb used for animation.
*/
public Colors(@ColorInt int color, @ColorInt int brightColor) {
this(color, brightColor, Color.TRANSPARENT);
}
/**
* Constructs a color set using the given colors.
*
* @param color The main search orb color.
* @param brightColor A brighter version of the search orb used for animation.
* @param iconColor A color used to tint the search orb icon.
*/
public Colors(@ColorInt int color, @ColorInt int brightColor, @ColorInt int iconColor) {
this.color = color;
this.brightColor = brightColor == color ? getBrightColor(color) : brightColor;
this.iconColor = iconColor;
}
/**
* The main color of the search orb.
*/
@ColorInt
public int color;
/**
* A brighter version of the search orb used for animation.
*/
@ColorInt
public int brightColor;
/**
* A color used to tint the search orb icon.
*/
@ColorInt
public int iconColor;
/**
* Computes a default brighter version of the given color.
*/
public static int getBrightColor(int color) {
final float brightnessValue = 0xff * sBrightnessAlpha;
int red = (int)(Color.red(color) * (1 - sBrightnessAlpha) + brightnessValue);
int green = (int)(Color.green(color) * (1 - sBrightnessAlpha) + brightnessValue);
int blue = (int)(Color.blue(color) * (1 - sBrightnessAlpha) + brightnessValue);
int alpha = (int)(Color.alpha(color) * (1 - sBrightnessAlpha) + brightnessValue);
return Color.argb(alpha, red, green, blue);
}
}
private final ArgbEvaluator mColorEvaluator = new ArgbEvaluator();
private final ValueAnimator.AnimatorUpdateListener mUpdateListener =
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
Integer color = (Integer) animator.getAnimatedValue();
setOrbViewColor(color.intValue());
}
};
private ValueAnimator mShadowFocusAnimator;
private final ValueAnimator.AnimatorUpdateListener mFocusUpdateListener =
new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setSearchOrbZ(animation.getAnimatedFraction());
}
};
private void setSearchOrbZ(float fraction) {
ShadowHelper.getInstance().setZ(mSearchOrbView,
mUnfocusedZ + fraction * (mFocusedZ - mUnfocusedZ));
}
public SearchOrbView(Context context) {
this(context, null);
}
public SearchOrbView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.searchOrbViewStyle);
}
public SearchOrbView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final Resources res = context.getResources();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRootView = inflater.inflate(getLayoutResourceId(), this, true);
mSearchOrbView = mRootView.findViewById(R.id.search_orb);
mIcon = (ImageView) mRootView.findViewById(R.id.icon);
mFocusedZoom = context.getResources().getFraction(
R.fraction.lb_search_orb_focused_zoom, 1, 1);
mPulseDurationMs = context.getResources().getInteger(
R.integer.lb_search_orb_pulse_duration_ms);
mScaleDurationMs = context.getResources().getInteger(
R.integer.lb_search_orb_scale_duration_ms);
mFocusedZ = context.getResources().getDimensionPixelSize(
R.dimen.lb_search_orb_focused_z);
mUnfocusedZ = context.getResources().getDimensionPixelSize(
R.dimen.lb_search_orb_unfocused_z);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.lbSearchOrbView,
defStyleAttr, 0);
Drawable img = a.getDrawable(R.styleable.lbSearchOrbView_searchOrbIcon);
if (img == null) {
img = res.getDrawable(R.drawable.lb_ic_in_app_search);
}
setOrbIcon(img);
int defColor = res.getColor(R.color.lb_default_search_color);
int color = a.getColor(R.styleable.lbSearchOrbView_searchOrbColor, defColor);
int brightColor = a.getColor(
R.styleable.lbSearchOrbView_searchOrbBrightColor, color);
int iconColor = a.getColor(R.styleable.lbSearchOrbView_searchOrbIconColor, Color.TRANSPARENT);
setOrbColors(new Colors(color, brightColor, iconColor));
a.recycle();
setFocusable(true);
setClipChildren(false);
setOnClickListener(this);
setSoundEffectsEnabled(false);
setSearchOrbZ(0);
// Icon has no background, but must be on top of the search orb view
ShadowHelper.getInstance().setZ(mIcon, mFocusedZ);
}
int getLayoutResourceId() {
return R.layout.lb_search_orb;
}
void scaleOrbViewOnly(float scale) {
mSearchOrbView.setScaleX(scale);
mSearchOrbView.setScaleY(scale);
}
float getFocusedZoom() {
return mFocusedZoom;
}
@Override
public void onClick(View view) {
if (null != mListener) {
mListener.onClick(view);
}
}
private void startShadowFocusAnimation(boolean gainFocus, int duration) {
if (mShadowFocusAnimator == null) {
mShadowFocusAnimator = ValueAnimator.ofFloat(0f, 1f);
mShadowFocusAnimator.addUpdateListener(mFocusUpdateListener);
}
if (gainFocus) {
mShadowFocusAnimator.start();
} else {
mShadowFocusAnimator.reverse();
}
mShadowFocusAnimator.setDuration(duration);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
animateOnFocus(gainFocus);
}
void animateOnFocus(boolean hasFocus) {
final float zoom = hasFocus ? mFocusedZoom : 1f;
mRootView.animate().scaleX(zoom).scaleY(zoom).setDuration(mScaleDurationMs).start();
startShadowFocusAnimation(hasFocus, mScaleDurationMs);
enableOrbColorAnimation(hasFocus);
}
/**
* Sets the orb icon.
* @param icon the drawable to be used as the icon
*/
public void setOrbIcon(Drawable icon) {
mIconDrawable = icon;
mIcon.setImageDrawable(mIconDrawable);
}
/**
* Returns the orb icon
* @return the drawable used as the icon
*/
public Drawable getOrbIcon() {
return mIconDrawable;
}
/**
* Sets the on click listener for the orb.
* @param listener The listener.
*/
public void setOnOrbClickedListener(OnClickListener listener) {
mListener = listener;
if (null != listener) {
setVisibility(View.VISIBLE);
} else {
setVisibility(View.INVISIBLE);
}
}
/**
* Sets the background color of the search orb.
* Other colors will be provided by the framework.
*
* @param color the RGBA color
*/
public void setOrbColor(int color) {
setOrbColors(new Colors(color, color, Color.TRANSPARENT));
}
/**
* Sets the search orb colors.
* Other colors are provided by the framework.
* @deprecated Use {@link #setOrbColors(Colors)} instead.
*/
@Deprecated
public void setOrbColor(@ColorInt int color, @ColorInt int brightColor) {
setOrbColors(new Colors(color, brightColor, Color.TRANSPARENT));
}
/**
* Returns the orb color
* @return the RGBA color
*/
@ColorInt
public int getOrbColor() {
return mColors.color;
}
/**
* Sets the {@link Colors} used to display the search orb.
*/
public void setOrbColors(Colors colors) {
mColors = colors;
mIcon.setColorFilter(mColors.iconColor);
if (mColorAnimator == null) {
setOrbViewColor(mColors.color);
} else {
enableOrbColorAnimation(true);
}
}
/**
* Returns the {@link Colors} used to display the search orb.
*/
public Colors getOrbColors() {
return mColors;
}
/**
* Enables or disables the orb color animation.
*
* <p>
* Orb color animation is handled automatically when the orb is focused/unfocused,
* however, an app may choose to override the current animation state, for example
* when an activity is paused.
* </p>
*/
public void enableOrbColorAnimation(boolean enable) {
if (mColorAnimator != null) {
mColorAnimator.end();
mColorAnimator = null;
}
if (enable) {
// TODO: set interpolator (material if available)
mColorAnimator = ValueAnimator.ofObject(mColorEvaluator,
mColors.color, mColors.brightColor, mColors.color);
mColorAnimator.setRepeatCount(ValueAnimator.INFINITE);
mColorAnimator.setDuration(mPulseDurationMs * 2);
mColorAnimator.addUpdateListener(mUpdateListener);
mColorAnimator.start();
}
}
private void setOrbViewColor(int color) {
if (mSearchOrbView.getBackground() instanceof GradientDrawable) {
((GradientDrawable) mSearchOrbView.getBackground()).setColor(color);
}
}
@Override
protected void onDetachedFromWindow() {
// Must stop infinite animation to prevent activity leak
enableOrbColorAnimation(false);
super.onDetachedFromWindow();
}
}
| syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/android/support/v17/leanback/widget/SearchOrbView.java | Java | gpl-3.0 | 12,627 |
using System;
namespace Server.Items
{
public class DaemonBloods : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods()
: base(0x122A)
{
}
public DaemonBloods(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DaemonBloods1 : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods1()
: base(0x122B)
{
}
public DaemonBloods1(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DaemonBloods2 : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods2()
: base(0x122C)
{
}
public DaemonBloods2(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DaemonBloods3 : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods3()
: base(0x122D)
{
}
public DaemonBloods3(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DaemonBloods4 : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods4()
: base(0x122E)
{
}
public DaemonBloods4(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class DaemonBloods5 : Item
{
public override int LabelNumber { get { return 1023965; } } // Daemon Blood
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
[Constructable]
public DaemonBloods5()
: base(0x122F)
{
}
public DaemonBloods5(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | GenerationOfWorlds/GOW | Scripts/Core/Mondains Legacy/Items/Magincia Invasion/DaemonBloods.cs | C# | gpl-3.0 | 4,575 |
namespace Maticsoft.ZipLib.Tar
{
using System;
using System.IO;
public class TarBuffer
{
private int blockFactor = 20;
public const int BlockSize = 0x200;
private int currentBlockIndex;
private int currentRecordIndex;
public const int DefaultBlockFactor = 20;
public const int DefaultRecordSize = 0x2800;
private Stream inputStream;
private bool isStreamOwner_ = true;
private Stream outputStream;
private byte[] recordBuffer;
private int recordSize = 0x2800;
protected TarBuffer()
{
}
public void Close()
{
if (this.outputStream != null)
{
this.WriteFinalRecord();
if (this.isStreamOwner_)
{
this.outputStream.Close();
}
this.outputStream = null;
}
else if (this.inputStream != null)
{
if (this.isStreamOwner_)
{
this.inputStream.Close();
}
this.inputStream = null;
}
}
public static TarBuffer CreateInputTarBuffer(Stream inputStream)
{
if (inputStream == null)
{
throw new ArgumentNullException("inputStream");
}
return CreateInputTarBuffer(inputStream, 20);
}
public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor)
{
if (inputStream == null)
{
throw new ArgumentNullException("inputStream");
}
if (blockFactor <= 0)
{
throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative");
}
TarBuffer buffer = new TarBuffer {
inputStream = inputStream,
outputStream = null
};
buffer.Initialize(blockFactor);
return buffer;
}
public static TarBuffer CreateOutputTarBuffer(Stream outputStream)
{
if (outputStream == null)
{
throw new ArgumentNullException("outputStream");
}
return CreateOutputTarBuffer(outputStream, 20);
}
public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor)
{
if (outputStream == null)
{
throw new ArgumentNullException("outputStream");
}
if (blockFactor <= 0)
{
throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative");
}
TarBuffer buffer = new TarBuffer {
inputStream = null,
outputStream = outputStream
};
buffer.Initialize(blockFactor);
return buffer;
}
[Obsolete("Use BlockFactor property instead")]
public int GetBlockFactor()
{
return this.blockFactor;
}
[Obsolete("Use CurrentBlock property instead")]
public int GetCurrentBlockNum()
{
return this.currentBlockIndex;
}
[Obsolete("Use CurrentRecord property instead")]
public int GetCurrentRecordNum()
{
return this.currentRecordIndex;
}
[Obsolete("Use RecordSize property instead")]
public int GetRecordSize()
{
return this.recordSize;
}
private void Initialize(int archiveBlockFactor)
{
this.blockFactor = archiveBlockFactor;
this.recordSize = archiveBlockFactor * 0x200;
this.recordBuffer = new byte[this.RecordSize];
if (this.inputStream != null)
{
this.currentRecordIndex = -1;
this.currentBlockIndex = this.BlockFactor;
}
else
{
this.currentRecordIndex = 0;
this.currentBlockIndex = 0;
}
}
public static bool IsEndOfArchiveBlock(byte[] block)
{
if (block == null)
{
throw new ArgumentNullException("block");
}
if (block.Length != 0x200)
{
throw new ArgumentException("block length is invalid");
}
for (int i = 0; i < 0x200; i++)
{
if (block[i] != 0)
{
return false;
}
}
return true;
}
[Obsolete("Use IsEndOfArchiveBlock instead")]
public bool IsEOFBlock(byte[] block)
{
if (block == null)
{
throw new ArgumentNullException("block");
}
if (block.Length != 0x200)
{
throw new ArgumentException("block length is invalid");
}
for (int i = 0; i < 0x200; i++)
{
if (block[i] != 0)
{
return false;
}
}
return true;
}
public byte[] ReadBlock()
{
if (this.inputStream == null)
{
throw new TarException("TarBuffer.ReadBlock - no input stream defined");
}
if ((this.currentBlockIndex >= this.BlockFactor) && !this.ReadRecord())
{
throw new TarException("Failed to read a record");
}
byte[] destinationArray = new byte[0x200];
Array.Copy(this.recordBuffer, this.currentBlockIndex * 0x200, destinationArray, 0, 0x200);
this.currentBlockIndex++;
return destinationArray;
}
private bool ReadRecord()
{
long num3;
if (this.inputStream == null)
{
throw new TarException("no input stream stream defined");
}
this.currentBlockIndex = 0;
int offset = 0;
for (int i = this.RecordSize; i > 0; i -= (int) num3)
{
num3 = this.inputStream.Read(this.recordBuffer, offset, i);
if (num3 <= 0L)
{
break;
}
offset += (int) num3;
}
this.currentRecordIndex++;
return true;
}
public void SkipBlock()
{
if (this.inputStream == null)
{
throw new TarException("no input stream defined");
}
if ((this.currentBlockIndex >= this.BlockFactor) && !this.ReadRecord())
{
throw new TarException("Failed to read a record");
}
this.currentBlockIndex++;
}
public void WriteBlock(byte[] block)
{
if (block == null)
{
throw new ArgumentNullException("block");
}
if (this.outputStream == null)
{
throw new TarException("TarBuffer.WriteBlock - no output stream defined");
}
if (block.Length != 0x200)
{
throw new TarException(string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", block.Length, 0x200));
}
if (this.currentBlockIndex >= this.BlockFactor)
{
this.WriteRecord();
}
Array.Copy(block, 0, this.recordBuffer, this.currentBlockIndex * 0x200, 0x200);
this.currentBlockIndex++;
}
public void WriteBlock(byte[] buffer, int offset)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (this.outputStream == null)
{
throw new TarException("TarBuffer.WriteBlock - no output stream stream defined");
}
if ((offset < 0) || (offset >= buffer.Length))
{
throw new ArgumentOutOfRangeException("offset");
}
if ((offset + 0x200) > buffer.Length)
{
throw new TarException(string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", buffer.Length, offset, this.recordSize));
}
if (this.currentBlockIndex >= this.BlockFactor)
{
this.WriteRecord();
}
Array.Copy(buffer, offset, this.recordBuffer, this.currentBlockIndex * 0x200, 0x200);
this.currentBlockIndex++;
}
private void WriteFinalRecord()
{
if (this.outputStream == null)
{
throw new TarException("TarBuffer.WriteFinalRecord no output stream defined");
}
if (this.currentBlockIndex > 0)
{
int index = this.currentBlockIndex * 0x200;
Array.Clear(this.recordBuffer, index, this.RecordSize - index);
this.WriteRecord();
}
this.outputStream.Flush();
}
private void WriteRecord()
{
if (this.outputStream == null)
{
throw new TarException("TarBuffer.WriteRecord no output stream defined");
}
this.outputStream.Write(this.recordBuffer, 0, this.RecordSize);
this.outputStream.Flush();
this.currentBlockIndex = 0;
this.currentRecordIndex++;
}
public int BlockFactor
{
get
{
return this.blockFactor;
}
}
public int CurrentBlock
{
get
{
return this.currentBlockIndex;
}
}
public int CurrentRecord
{
get
{
return this.currentRecordIndex;
}
}
public bool IsStreamOwner
{
get
{
return this.isStreamOwner_;
}
set
{
this.isStreamOwner_ = value;
}
}
public int RecordSize
{
get
{
return this.recordSize;
}
}
}
}
| 51zhaoshi/myyyyshop | Maticsoft.ZipLib_Source/Maticsoft.ZipLib.Tar/TarBuffer.cs | C# | gpl-3.0 | 10,590 |
package classifiers;
import java.io.File;
import java.io.PrintWriter;
import Utils.Utilities;
import stats.Statistics;
import tablInEx.Table;
import weka.classifiers.misc.InputMappedClassifier;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.SelectedTag;
import weka.core.stemmers.SnowballStemmer;
import weka.core.stopwords.WordsFromFile;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.StringToWordVector;
public class PragmaticClassifier {
private String ClassifierPath="";
//private Classifier classifier;
InputMappedClassifier classifier = new InputMappedClassifier();
public PragmaticClassifier(String path)
{
ClassifierPath = path;
try {
classifier.setModelPath(ClassifierPath);
classifier.setTrim(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String Classify(Table t)
{
String prediction = "";
Instances ins = null;
// Declare attributes
Attribute Attribute1 = new Attribute("num_of_rows");
Attribute Attribute2 = new Attribute("num_of_columns");
Attribute Attribute3 = new Attribute("num_of_header_rows");
Attribute Attribute4 = new Attribute("percentage_of_numeric_cells");
Attribute Attribute5 = new Attribute("percentage_of_seminumeric_cells");
Attribute Attribute6 = new Attribute("percentage_of_string_cells");
Attribute Attribute7 = new Attribute("percentage_of_empty_cells");
Attribute Attribute8 = new Attribute("header_strings",(FastVector)null);
Attribute Attribute9 = new Attribute("stub_strings",(FastVector)null);
Attribute Attribute10 = new Attribute("caption",(FastVector)null);
Attribute Attribute11 = new Attribute("footer",(FastVector)null);
FastVector fvClassVal = new FastVector(3);
fvClassVal.addElement("findings");
fvClassVal.addElement("settings");
fvClassVal.addElement("support-knowledge");
Attribute ClassAttribute = new Attribute("table_class", fvClassVal);
// Declare the feature vector
FastVector fvWekaAttributes = new FastVector(11);
String header = "";
String stub = "";
int empty = 0;
int string = 0;
int seminum = 0;
int num = 0;
int cells_num = 0;
if (t.cells != null)
for (int i = 0; i < t.cells.length; i++) {
for (int k = 0; k < t.cells[i].length; k++) {
cells_num++;
if(t.cells[i][k]==null||t.cells[i][k].getCell_content()==null)
continue;
if(Utilities.isSpaceOrEmpty(t.cells[i][k].getCell_content()))
{
empty++;
}
else if (t.cells[i][k].getCellType().equals("Partially Numeric"))
{
seminum++;
}
else if (t.cells[i][k].getCellType().equals("Numeric"))
{
num++;
}
else if (t.cells[i][k].getCellType().equals("Text"))
{
string++;
}
if (t.cells[i][k].isIs_header())
header += t.cells[i][k].getCell_content()
+ " ";
if (t.cells[i][k].isIs_stub())
stub += t.cells[i][k].getCell_content()
+ " ";
}
}
float perc_num = (float)num/(float)cells_num;
float perc_seminum = (float)seminum/(float)cells_num;
float perc_string = (float)string/(float)cells_num;
float perc_empty = (float)empty/(float)cells_num;
fvWekaAttributes.addElement(Attribute1);
fvWekaAttributes.addElement(Attribute2);
fvWekaAttributes.addElement(Attribute3);
fvWekaAttributes.addElement(Attribute4);
fvWekaAttributes.addElement(Attribute5);
fvWekaAttributes.addElement(Attribute6);
fvWekaAttributes.addElement(Attribute7);
fvWekaAttributes.addElement(Attribute8);
fvWekaAttributes.addElement(Attribute9);
fvWekaAttributes.addElement(Attribute10);
fvWekaAttributes.addElement(Attribute11);
fvWekaAttributes.addElement(ClassAttribute);
Instances Instances = new Instances("Rel", fvWekaAttributes, 0);
Instance iExample = new DenseInstance(12);
if(t.getTable_caption()==null)
{
t.setTable_caption("");
}
Attribute attribute = (Attribute)fvWekaAttributes.elementAt(0);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(0), t.getNum_of_rows());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(1), t.getNum_of_columns());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(2), t.stat.getNum_of_header_rows());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(3), perc_num);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(4), perc_seminum);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(5), perc_string);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(6), perc_empty);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(7), header);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(8), stub);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(9), t.getTable_caption());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(10), t.getTable_footer());
Instances.add(iExample);
Instances.setClassIndex(11);
StringToWordVector filter = new StringToWordVector();
filter.setAttributeIndices("first-last");
filter.setMinTermFreq(1);
filter.setIDFTransform(true);
filter.setTFTransform(true);
filter.setLowerCaseTokens(true);
filter.setNormalizeDocLength(new SelectedTag(StringToWordVector.FILTER_NORMALIZE_ALL, StringToWordVector.TAGS_FILTER));
filter.setOutputWordCounts(true);
SnowballStemmer stemmer = new SnowballStemmer();
//stemmer.setStemmer("English");
filter.setStemmer(stemmer);
WordsFromFile sw = new WordsFromFile();
sw.setStopwords(new File("Models/stop-words-english1.txt"));
filter.setStopwordsHandler(sw);
Instances newData;
try {
filter.setInputFormat(Instances);
filter.input(Instances.instance(0));
filter.batchFinished();
ins= Filter.useFilter(Instances,filter);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
double result = classifier.classifyInstance(ins.firstInstance());
ins.firstInstance().setClassValue(result);
prediction=ins.firstInstance().classAttribute().value((int)result);
t.PragmaticClass = prediction;
System.out.println(t.PragmaticClass);
new File(t.PragmaticClass).mkdirs();
PrintWriter writer = new PrintWriter(t.PragmaticClass+File.separator+t.getDocumentFileName()+t.getTable_title()+".html", "UTF-8");
writer.println(t.getXml());
writer.close();
Statistics.addPragmaticTableType(prediction);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return prediction;
}
public String Classify2(Table t,String class1, String class2)
{
String prediction = "";
Instances ins = null;
// Declare attributes
Attribute Attribute1 = new Attribute("num_of_rows");
Attribute Attribute2 = new Attribute("num_of_columns");
Attribute Attribute3 = new Attribute("num_of_header_rows");
Attribute Attribute4 = new Attribute("percentage_of_numeric_cells");
Attribute Attribute5 = new Attribute("percentage_of_seminumeric_cells");
Attribute Attribute6 = new Attribute("percentage_of_string_cells");
Attribute Attribute7 = new Attribute("percentage_of_empty_cells");
Attribute Attribute8 = new Attribute("header_strings",(FastVector)null);
Attribute Attribute9 = new Attribute("stub_strings",(FastVector)null);
Attribute Attribute10 = new Attribute("caption",(FastVector)null);
Attribute Attribute11 = new Attribute("footer",(FastVector)null);
FastVector fvClassVal = new FastVector(2);
fvClassVal.addElement(class1);
fvClassVal.addElement(class2);
Attribute ClassAttribute = new Attribute("table_class", fvClassVal);
// Declare the feature vector
FastVector fvWekaAttributes = new FastVector(11);
String header = "";
String stub = "";
int empty = 0;
int string = 0;
int seminum = 0;
int num = 0;
int cells_num = 0;
if (t.cells != null)
for (int i = 0; i < t.cells.length; i++) {
for (int k = 0; k < t.cells[i].length; k++) {
cells_num++;
if(t.cells[i][k]==null||t.cells[i][k].getCell_content()==null)
continue;
if(Utilities.isSpaceOrEmpty(t.cells[i][k].getCell_content()))
{
empty++;
}
else if (t.cells[i][k].getCellType().equals("Partially Numeric"))
{
seminum++;
}
else if (t.cells[i][k].getCellType().equals("Numeric"))
{
num++;
}
else if (t.cells[i][k].getCellType().equals("Text"))
{
string++;
}
if (t.cells[i][k].isIs_header())
header += t.cells[i][k].getCell_content()
+ " ";
if (t.cells[i][k].isIs_stub())
stub += t.cells[i][k].getCell_content()
+ " ";
}
}
float perc_num = (float)num/(float)cells_num;
float perc_seminum = (float)seminum/(float)cells_num;
float perc_string = (float)string/(float)cells_num;
float perc_empty = (float)empty/(float)cells_num;
fvWekaAttributes.addElement(Attribute1);
fvWekaAttributes.addElement(Attribute2);
fvWekaAttributes.addElement(Attribute3);
fvWekaAttributes.addElement(Attribute4);
fvWekaAttributes.addElement(Attribute5);
fvWekaAttributes.addElement(Attribute6);
fvWekaAttributes.addElement(Attribute7);
fvWekaAttributes.addElement(Attribute8);
fvWekaAttributes.addElement(Attribute9);
fvWekaAttributes.addElement(Attribute10);
fvWekaAttributes.addElement(Attribute11);
fvWekaAttributes.addElement(ClassAttribute);
Instances Instances = new Instances("Rel", fvWekaAttributes, 0);
Instance iExample = new DenseInstance(12);
Attribute attribute = (Attribute)fvWekaAttributes.elementAt(0);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(0), t.getNum_of_rows());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(1), t.getNum_of_columns());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(2), t.stat.getNum_of_header_rows());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(3), perc_num);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(4), perc_seminum);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(5), perc_string);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(6), perc_empty);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(7), header);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(8), stub);
iExample.setValue((Attribute)fvWekaAttributes.elementAt(9), t.getTable_caption());
iExample.setValue((Attribute)fvWekaAttributes.elementAt(10), t.getTable_footer());
Instances.add(iExample);
Instances.setClassIndex(11);
StringToWordVector filter = new StringToWordVector();
filter.setAttributeIndices("first-last");
filter.setMinTermFreq(1);
filter.setIDFTransform(true);
filter.setTFTransform(true);
filter.setLowerCaseTokens(true);
filter.setNormalizeDocLength(new SelectedTag(StringToWordVector.FILTER_NORMALIZE_ALL, StringToWordVector.TAGS_FILTER));
filter.setOutputWordCounts(true);
SnowballStemmer stemmer = new SnowballStemmer();
//stemmer.setStemmer("English");
filter.setStemmer(stemmer);
WordsFromFile sw = new WordsFromFile();
sw.setStopwords(new File("Models/stop-words-english1.txt"));
filter.setStopwordsHandler(sw);
Instances newData;
try {
filter.setInputFormat(Instances);
filter.input(Instances.instance(0));
filter.batchFinished();
ins= Filter.useFilter(Instances,filter);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
double result = classifier.classifyInstance(ins.firstInstance());
ins.firstInstance().setClassValue(result);
prediction=ins.firstInstance().classAttribute().value((int)result);
t.PragmaticClass = prediction;
System.out.println(t.PragmaticClass);
new File(t.PragmaticClass).mkdirs();
PrintWriter writer = new PrintWriter(t.PragmaticClass+File.separator+t.getDocumentFileName()+t.getTable_title()+".html", "UTF-8");
writer.println(t.getXml());
writer.close();
Statistics.addPragmaticTableType(prediction);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return prediction;
}
}
| nikolamilosevic86/TableAnnotator | src/classifiers/PragmaticClassifier.java | Java | gpl-3.0 | 12,768 |
package es.task.switcher.model.entities;
import com.mobandme.ada.Entity;
import com.mobandme.ada.annotations.Table;
import com.mobandme.ada.annotations.TableField;
@Table(name = "Category")
public class Category extends Entity{
@TableField(name = "name", datatype = DATATYPE_STRING, maxLength = 100)
public String name = "";
}
| jbeerdev/Switch- | src/es/task/switcher/model/entities/Category.java | Java | gpl-3.0 | 335 |
import re
import sys
import whoisSrvDict
import whoispy_sock
import parser_branch
OK = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def query(domainName):
rawMsg = ""
tldName = ""
whoisSrvAddr = ""
regex = re.compile('.+\..+')
match = regex.search(domainName)
if not match:
# Invalid domain
_display_fail("Invalid domain format")
return None
# Divice TLD
regex = re.compile('\..+')
match = regex.search(domainName)
if match:
tldName = match.group()
else:
_display_fail("Can not parse TLD")
return None
# Get TLD List
if not (tldName in whoisSrvDict.get_whoisSrvDict()):
_display_fail("Not Found TLD whois server")
return None
whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName)
rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43)
return parser_branch.get_parser(rawMsg, whoisSrvAddr)
# Display method
def _display_fail(msg):
sys.stdout.write( FAIL )
sys.stdout.write("%s\n" % msg)
sys.stdout.write( ENDC )
def _display_safe(msg):
sys.stdout.write( OK )
sys.stdout.write("%s\n" % msg)
sys.stdout.write( ENDC )
| nemumu/whoispy | whoispy/whoispy.py | Python | gpl-3.0 | 1,198 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.05.02 at 06:10:56 PM NZST
//
package mapContents;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="ref" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "nd")
public class Nd {
@XmlAttribute(name = "ref", required = true)
@XmlSchemaType(name = "unsignedLong")
protected BigInteger ref;
/**
* Gets the value of the ref property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getRef() {
return ref;
}
/**
* Sets the value of the ref property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRef(BigInteger value) {
this.ref = value;
}
}
| JDuligall/ZombieSim | honorsWorkspace/ZombieSim2/src/mapContents/Nd.java | Java | gpl-3.0 | 1,846 |
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "../../pyKey.h"
#pragma hdrstop
#include "pyHeekGame.h"
#include "pfGameMgr/pfGameMgr.h"
///////////////////////////////////////////////////////////////////////////////
//
// Base Heek game client class
//
pyHeekGame::pyHeekGame(): pyGameCli() {}
pyHeekGame::pyHeekGame(pfGameCli* client): pyGameCli(client)
{
if (client && (client->GetGameTypeId() != kGameTypeId_Heek))
gameClient = nil; // wrong type, just clear it out
}
bool pyHeekGame::IsHeekGame(plString& guid)
{
plUUID gameUuid(guid);
return gameUuid == kGameTypeId_Heek;
}
void pyHeekGame::JoinCommonHeekGame(pyKey& callbackKey, unsigned gameID)
{
pfGameMgr::GetInstance()->JoinCommonGame(callbackKey.getKey(), kGameTypeId_Heek, gameID, 0, NULL);
}
void pyHeekGame::PlayGame(int position, uint32_t points, std::wstring name)
{
if (gameClient)
{
pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient);
heek->PlayGame((unsigned)position, (uint32_t)points, name.c_str());
}
}
void pyHeekGame::LeaveGame()
{
if (gameClient)
{
pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient);
heek->LeaveGame();
}
}
void pyHeekGame::Choose(int choice)
{
if (gameClient)
{
pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient);
heek->Choose((EHeekChoice)choice);
}
}
void pyHeekGame::SequenceFinished(int seq)
{
if (gameClient)
{
pfGmHeek* heek = pfGmHeek::ConvertNoRef(gameClient);
heek->SequenceFinished((EHeekSeqFinished)seq);
}
}
| v1nc3ntm/Plasma | Sources/Plasma/FeatureLib/pfPython/Games/Heek/pyHeekGame.cpp | C++ | gpl-3.0 | 3,285 |
package org.cgiar.ccafs.marlo.data.model;
// Generated Jun 20, 2018 1:50:25 PM by Hibernate Tools 3.4.0.CR1
import org.cgiar.ccafs.marlo.data.IAuditLog;
import com.google.gson.annotations.Expose;
/**
* ReportSynthesisMeliaStudy generated by hbm2java
*/
public class ReportSynthesisKeyPartnershipPmu extends MarloAuditableEntity implements java.io.Serializable, IAuditLog {
private static final long serialVersionUID = 5761871053421733437L;
@Expose
private ReportSynthesisKeyPartnership reportSynthesisKeyPartnership;
@Expose
private ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal;
public ReportSynthesisKeyPartnershipPmu() {
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ReportSynthesisKeyPartnershipPmu other = (ReportSynthesisKeyPartnershipPmu) obj;
if (this.getReportSynthesisKeyPartnershipExternal() == null) {
if (other.getReportSynthesisKeyPartnershipExternal() != null) {
return false;
}
} else if (!this.getReportSynthesisKeyPartnershipExternal()
.equals(other.getReportSynthesisKeyPartnershipExternal())) {
return false;
}
if (this.getReportSynthesisKeyPartnership() == null) {
if (other.getReportSynthesisKeyPartnership() != null) {
return false;
}
} else if (!this.getReportSynthesisKeyPartnership().getId()
.equals(other.getReportSynthesisKeyPartnership().getId())) {
return false;
}
return true;
}
@Override
public String getLogDeatil() {
StringBuilder sb = new StringBuilder();
sb.append("Id : ").append(this.getId());
return sb.toString();
}
public ReportSynthesisKeyPartnership getReportSynthesisKeyPartnership() {
return reportSynthesisKeyPartnership;
}
public ReportSynthesisKeyPartnershipExternal getReportSynthesisKeyPartnershipExternal() {
return reportSynthesisKeyPartnershipExternal;
}
public void setReportSynthesisKeyPartnership(ReportSynthesisKeyPartnership reportSynthesisKeyPartnership) {
this.reportSynthesisKeyPartnership = reportSynthesisKeyPartnership;
}
public void setReportSynthesisKeyPartnershipExternal(
ReportSynthesisKeyPartnershipExternal reportSynthesisKeyPartnershipExternal) {
this.reportSynthesisKeyPartnershipExternal = reportSynthesisKeyPartnershipExternal;
}
}
| CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/ReportSynthesisKeyPartnershipPmu.java | Java | gpl-3.0 | 2,592 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2015 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.mrlolethan.butteredpd.effects.particles;
import com.watabou.noosa.particles.Emitter;
import com.watabou.noosa.particles.Emitter.Factory;
import com.watabou.noosa.particles.PixelParticle;
import com.watabou.utils.Random;
public class SmokeParticle extends PixelParticle {
public static final Factory FACTORY = new Factory() {
@Override
public void emit( Emitter emitter, int index, float x, float y ) {
((SmokeParticle)emitter.recycle( SmokeParticle.class )).reset( x, y );
}
};
public SmokeParticle() {
super();
color( 0x222222 );
acc.set( 0, -40 );
}
public void reset( float x, float y ) {
revive();
this.x = x;
this.y = y;
left = lifespan = Random.Float( 0.6f, 1f );
speed.set( Random.Float( -4, +4 ), Random.Float( -8, +8 ) );
}
@Override
public void update() {
super.update();
float p = left / lifespan;
am = p > 0.8f ? 2 - 2*p : p * 0.5f;
size( 16 - p * 8 );
}
} | mrlolethan/Buttered-Pixel-Dungeon | src/com/mrlolethan/butteredpd/effects/particles/SmokeParticle.java | Java | gpl-3.0 | 1,728 |
from vectores_oo import Vector
x = input('vector U componente X= ')
y = input('vector U componente X= ')
U = Vector(x,y)
m = input('vector V magnitud= ')
a = input('vector V angulo= ')
V = Vector(m=m, a=a)
E = input('Escalar= ')
print "U=%s" % U
print "V=%s" % V
print 'UxE=%s' % U.x_escalar(E)
print 'VxE=%s' % V.x_escalar(E)
print 'U+V=%s' % U.Suma(V)
print 'U.V=%s' % U.ProductoPunto(V)
print '|UxV|=%s' % U.Modulo_ProductoCruz(V)
| rgarcia-herrera/vectores | vectores.py | Python | gpl-3.0 | 446 |
<?php
/**
* Autor: Camilo Figueroa ( Crivera )
* Este archivo se crea para organizar inicialmente todo lo que tiene que ver con las combinaciones
* entre los diferentes elementos que al detalle generan un nuevo texto que ha de contener
* el número de calificación para esa combinación.
*/
include( "config.php" );
//Borramos todo lo de la tabla de calificaciones.
$sql = " TRUNCATE TABLE tb_calificaciones; ";
$conexion = mysqli_connect( $servidor, $usuario, $clave, $bd );
$resultado = $conexion->query( $sql );
$sql .= " ALTER TABLE tb_calificaciones AUTO_INCREMENT = 1; ";
$resultado = $conexion->query( $sql );
$sql = " INSERT INTO tb_calificaciones ( id, criterio, categoria, jurado, nombre_region ) ";
$sql .= " SELECT null, t3.criterio, t5.categoria, t2.jurado, t4.nombre_region ";
$sql .= " FROM tb_jurados t2, tb_criterios t3, tb_regiones t4, tb_categorias t5 ";
$sql .= " WHERE INSTR( t3.indicador_categoria, t5.acronimo_categoria ) > 0 ";
$sql .= " AND INSTR( t4.indicador_categoria, t5.acronimo_categoria ) > 0 ";
//$sql .= " AND INSTR( t2.indicador_categoria, t5.acronimo_categoria ) > 0 ";
$sql .= " ORDER BY t5.categoria, t2.jurado, t4.nombre_region; ";
$resultado = $conexion->query( $sql );
//Esto debe suceder si las tablas madre ya tienen organizados todos los registros.
//La única que debería estar vacía a este punto es la de imágenes y calificaciones.
$sql = " SELECT * FROM tb_calificaciones ORDER BY jurado, categoria, nombre_region, criterio ";
$resultado = $conexion->query( $sql );
//Para construir una tablita organizada en html.
$organizacion_visual = " <table border='1px'> ";
$contador_cambiante = 0;
$verificador_cambios = "";
$columnas_implicadas = "";
while( $fila = mysqli_fetch_array( $resultado ) )
{
$columnas_implicadas = $fila[ 2 ]." ".$fila[ 3 ];
if( $verificador_cambios != $columnas_implicadas )
{
$contador_cambiante = 1;
$verificador_cambios = $columnas_implicadas;
}else{
$contador_cambiante ++; //Afectamos el contador para esa fila.
}
$organizacion_visual .= " <tr> ";
//Se recorren las columnas de cada fila.
for( $i = 0; $i < mysqli_num_fields( $resultado ); $i ++ )
{
$organizacion_visual .= " <td> ";
if( $i != mysqli_num_fields( $resultado ) - 1 )
{
$organizacion_visual .= $fila[ $i ];
}else{
//Aquí se determina el número del text input que debe tener esa determinada
//combinación calificable.
$organizacion_visual .= $contador_cambiante;
$sql = " UPDATE tb_calificaciones SET text_input_name = 'texto".$contador_cambiante."' ";
$sql .= " WHERE id = ".$fila[ 0 ];
$conexion->query( $sql );
//echo $sql;
}
$organizacion_visual .= " </td> ";
}
$organizacion_visual .= " </tr> ";
}
$organizacion_visual .= " </table> ";
echo $organizacion_visual;
| camilofigueroa/CalificadorEventosArte | deploy/organizador_inicial.php | PHP | gpl-3.0 | 3,321 |
pref('devcache.debug', false);
pref('devcache.enabled', true);
pref('devcache.patterns', '');
| essentialed/DevCache | defaults/preferences/prefs.js | JavaScript | gpl-3.0 | 97 |
"""
RESTx: Sane, simple and effective data publishing and integration.
Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
"""
A sample template for RESTx components, written in Python.
"""
import urllib
import restx.components
import restx.settings as settings
from restx.platform_specifics import STORAGE_OBJECT
from restx.components.api import *
from org.mulesoft.restx.exception import *
class _ResourceCreateForm(BaseComponent):
# Name, description and doc string of the component as it should appear to the user.
NAME = "_ResourceCreateForm" # Names starting with a '_' are kept private
DESCRIPTION = "Allows creation of a new resource by displaying a resource creation form"
DOCUMENTATION = \
"""The resource gets the name of a component as parameter at run time.
It then reads information about the component and constructs a proper
HTML form suitable for resource creation.
The user submits the filled-out form and a new resource is created.
"""
PARAM_DEFINITION = {}
# A dictionary with information about each exposed service method (sub-resource).
SERVICES = {
"form" : {
"desc" : "Show the resource creation form",
"params" : {
"component_name" : ParameterDef(PARAM_STRING, "Name of the component", required=True),
"message" : ParameterDef(PARAM_STRING, "An error message", required=False, default=""),
"specialized" : ParameterDef(PARAM_BOOL, "Indicates if this is based on a specialized component", required=False, default=False),
},
"positional_params": [ "component_name" ]
},
}
def __create(self, input, component_name, specialized=False):
"""
Accept a resource creation form for a specified component.
"""
d = dict()
for name, value in input.items():
path_elems = name.split("__")
d2 = d
for i, pe in enumerate(path_elems):
if i < len(path_elems)-1:
# More elements to come later? We must create a dict
d2 = d2.setdefault(pe, dict())
else:
if value:
d2[pe] = value
try:
return (True, makeResource(component_name, d, specialized), d)
except RestxException, e:
return (False, e.msg, d)
def form(self, method, input, component_name, message="", specialized=False):
"""
Display a resource creation form for a specified component.
@param method: The HTTP request method.
@type method: string
@param input: Any data that came in the body of the request.
@type input: string
@param component_name: Name of the component for which to create the resource.
@type component_name: string
@param message: An error message to be displayed above the form.
@type message: string
@return: The output data of this service.
@rtype: Result
"""
input_params = dict()
input_rctp = dict()
if input and HttpMethod.POST:
flag, msg, input = self.__create(input, component_name, specialized)
if not flag:
message = msg
else:
return Result.created(msg['uri'], msg)
if input:
if type(input) is dict:
# We receive a dict of values if the 'create' method discovered an
# error. In that case, the values should be used to pre-populate
# the fields when the form is re-displayed (with the error messsage
# on top).
input_rctp = input.get('resource_creation_params', dict()) # Resource creation time parameters
input_params = input.get('params', dict()) # Other parameters
if specialized:
# Need to read the definition of the partial resource and get the
# component name from there.
specialized_code_name = component_name
specialized_def = STORAGE_OBJECT.loadResourceFromStorage(specialized_code_name, True)
component_uri = specialized_def['private']['code_uri']
elems = component_uri.split("/")
component_name = elems[len(elems)-1]
# Take the parameter map from the component
comp = restx.components.make_component(component_name)
if not comp:
return Result.notFound("Cannot find component '%s'" % component_name)
header = settings.HTML_HEADER
# Assemble the form elements for the parameters
params = dict()
params.update(comp.getParams()) # In case this is a Java component, we get a Python dict this way
if specialized:
fname = specialized_def['public']['name']
fdesc = specialized_def['public']['desc']
# Remove all parameters that have been specified in the specialized component resource
# definition already
spec_params = specialized_def['private'].get('params')
if spec_params:
for name in spec_params:
if name in params:
del params[name]
else:
fname = comp.getName()
fdesc = comp.getDesc()
param_fields_html = ""
if params:
param_field_names = params.keys()
param_field_names.sort()
for pname in param_field_names:
pdef = params[pname]
if not pdef.required:
opt_str = "<br>optional, default: %s" % pdef.getDefaultVal()
else:
opt_str = ""
values = input_params.get(pname)
if type(values) is not list and pdef.isList():
if values is None:
values = []
else:
values = [ values ]
param_fields_html += \
"""<tr>
<td valign=top id="%s_name">%s<br><small>(%s%s)</small></td>
<td valign=top>%s</td>
</tr>""" % (pname, pname, pdef.desc, opt_str, pdef.html_type("params__"+pname, values))
if message:
msg = "<b><i><font color=red>%s</font></i></b><br><p>" % message
else:
msg = ""
body = """
<h3>Resource creation form for: %s</h3>
<p><i>"%s"</i></p>
<hr>
Please enter the resource configuration...<br><p>
%s
<form id="resource_form" name="input" action="%s" method="POST">
<table>""" % (fname, fdesc, msg, "%s%s/form/%s%s" % (settings.DOCUMENT_ROOT, self.getMyResourceUri(),
component_name if not specialized else specialized_code_name, "?specialized=y" if specialized else ""))
# Gather any initial values of the resource creation time form fields
suggested_name_value = input_rctp.get("suggested_name", "")
if suggested_name_value:
suggested_name_value = 'value="%s" ' % suggested_name_value
desc_value = input_rctp.get("desc", "")
if desc_value:
desc_value = 'value="%s" ' % desc_value
specialized_value = "checked " if input_rctp.get("specialized") in [ "on", "ON" ] else " "
if not specialized:
body += """
<tr>
<td id="Make_this_a_specialized_component_name">Make this a specialized component:</td>
<td><input type="checkbox" %s id="resource_creation_params__specialized" name="resource_creation_params__specialized" /><label for=resource_creation_params__specialized><small>Can only be used as basis for other resources</small></label></td>
</tr>
""" % specialized_value
body += """
<tr>
<td id="Resource_name_name">Resource name:</td>
<td><input type="text" %sname="resource_creation_params__suggested_name" id="resource_creation_params__suggested_name" /></td>
</tr>
<tr>
<td id="Description_name">Description:<br><small>(optional)</small></td>
<td><input type="text" %sname="resource_creation_params__desc" id="resource_creation_params__desc" /></td>
</tr>
%s
<tr><td colspan=2 align=center><input id="submit_button" type="submit" value="Submit" /></tr>
</table>
</form>""" % (suggested_name_value, desc_value, param_fields_html)
footer = settings.HTML_FOOTER
return Result.ok(header + body + footer).addHeader("Content-type", "text/html; charset=UTF-8")
| jbrendel/RESTx | src/python/restx/components/_ResourceCreateForm.py | Python | gpl-3.0 | 9,666 |
/**************************************************************************
**
** Copyright (C) 2013 by Philip Schuchardt
** www.cavewhere.com
**
**************************************************************************/
#include "cwEdgeTile.h"
//Qt includes
#include <QDebug>
cwEdgeTile::cwEdgeTile()
{
}
void cwEdgeTile::generate() {
generateVertex();
generateIndexes();
}
void cwEdgeTile::generateIndexes() {
QVector<unsigned int> tempIndexes;
//Create all the geometry for normal geometry
int numVertices = numVerticesOnADimension();
for(int row = 0; row < numVertices - 1; row++) {
for(int column = 1; column < numVertices - 1; column++) {
//Triangle 1
tempIndexes.append(indexOf(column, row));
tempIndexes.append(indexOf(column + 1, row + 1));
tempIndexes.append(indexOf(column, row + 1));
//Triangle 2
tempIndexes.append(indexOf(column, row));
tempIndexes.append(indexOf(column + 1, row));
tempIndexes.append(indexOf(column + 1, row + 1));
}
}
unsigned int largestInt = indexOf(numVertices - 1, numVertices - 1) + 1;
unsigned int halfIndex1 = largestInt;
unsigned int halfIndex2 = halfIndex1 + 1;
//Create the geometry for the first column
for(int row = 0; row < tileSize(); row++) {
unsigned int bottomLeft = indexOf(0, row);
unsigned int bottomRight = indexOf(1, row);
unsigned int topLeft = indexOf(0, row + 1);
unsigned int topRight = indexOf(1, row + 1);
//Triangle 1
tempIndexes.append(bottomLeft);
tempIndexes.append(bottomRight);
tempIndexes.append(halfIndex2);
//Triangle 2
tempIndexes.append(bottomRight);
tempIndexes.append(topRight);
tempIndexes.append(halfIndex2);
//Triangle 3
tempIndexes.append(topRight);
tempIndexes.append(topLeft);
tempIndexes.append(halfIndex2);
//Triangle 4
tempIndexes.append(halfIndex1);
tempIndexes.append(halfIndex2);
tempIndexes.append(topLeft);
//Triangle 5
tempIndexes.append(bottomLeft);
tempIndexes.append(halfIndex2);
tempIndexes.append(halfIndex1);
halfIndex1 += 2;
halfIndex2 += 2;
}
Indexes.clear();
Indexes.reserve(tempIndexes.size());
Indexes.resize(tempIndexes.size());
//Can't get optimize faces working on windows
Indexes = tempIndexes;
// Forsyth::OptimizeFaces(tempIndexes.data(), tempIndexes.size(),
// halfIndex2 - 1,
// Indexes.data(),
// 24);
}
void cwEdgeTile::generateVertex() {
Vertices.clear();
//vertex spacing
double spacing = 1.0 / (double)tileSize();
int numVertexes = numVerticesOnADimension();
int totalSize = numVertexes * numVertexes;
Vertices.reserve(totalSize);
//Create the regualar mesh points
for(int y = 0; y < numVertexes; y++) {
for(int x = 0; x < numVertexes; x++) {
float xPos = x * spacing;
float yPos = y * spacing;
QVector2D vertex(xPos, yPos);
Vertices.append(vertex);
}
}
//Add the points for the half spacing
double halfSpacing = spacing / 2.0;
for(int row = 0; row < tileSize(); row++) {
float yPos = row * spacing + halfSpacing;
Vertices.append(QVector2D(0.0, yPos));
Vertices.append(QVector2D(halfSpacing, yPos));
}
}
| Cavewhere/cavewhere | src/cwEdgeTile.cpp | C++ | gpl-3.0 | 3,566 |
#!/usr/bin/env python
# Unix SMB/CIFS implementation.
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2010
# Copyright (C) Matthias Dieter Wallnoefer 2009
#
# Based on the original in EJS:
# Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
#
# 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/>.
#
"""Convenience functions for using the SAM."""
import samba
import ldb
import time
import base64
from samba import dsdb
from samba.ndr import ndr_unpack, ndr_pack
from samba.dcerpc import drsblobs, misc
__docformat__ = "restructuredText"
class SamDB(samba.Ldb):
"""The SAM database."""
hash_oid_name = {}
def __init__(self, url=None, lp=None, modules_dir=None, session_info=None,
credentials=None, flags=0, options=None, global_schema=True,
auto_connect=True, am_rodc=None):
self.lp = lp
if not auto_connect:
url = None
elif url is None and lp is not None:
url = lp.samdb_url()
super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
session_info=session_info, credentials=credentials, flags=flags,
options=options)
if global_schema:
dsdb._dsdb_set_global_schema(self)
if am_rodc is not None:
dsdb._dsdb_set_am_rodc(self, am_rodc)
def connect(self, url=None, flags=0, options=None):
if self.lp is not None:
url = self.lp.private_path(url)
super(SamDB, self).connect(url=url, flags=flags,
options=options)
def am_rodc(self):
return dsdb._am_rodc(self)
def domain_dn(self):
return str(self.get_default_basedn())
def enable_account(self, search_filter):
"""Enables an account
:param search_filter: LDAP filter to find the user (eg
samccountname=name)
"""
flags = samba.dsdb.UF_ACCOUNTDISABLE | samba.dsdb.UF_PASSWD_NOTREQD
self.toggle_userAccountFlags(search_filter, flags, on=False)
def toggle_userAccountFlags(self, search_filter, flags, on=True, strict=False):
"""toggle_userAccountFlags
:param search_filter: LDAP filter to find the user (eg
samccountname=name)
:flags: samba.dsdb.UF_* flags
:on: on=True (default) => set, on=False => unset
:strict: strict=False (default) ignore if no action is needed
strict=True raises an Exception if...
"""
res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=search_filter, attrs=["userAccountControl"])
if len(res) == 0:
raise Exception('Unable to find user "%s"' % search_filter)
assert(len(res) == 1)
account_dn = res[0].dn
old_uac = int(res[0]["userAccountControl"][0])
if on:
if strict and (old_uac & flags):
error = 'userAccountFlags[%d:0x%08X] already contain 0x%X' % (old_uac, old_uac, flags)
raise Exception(error)
new_uac = old_uac | flags
else:
if strict and not (old_uac & flags):
error = 'userAccountFlags[%d:0x%08X] not contain 0x%X' % (old_uac, old_uac, flags)
raise Exception(error)
new_uac = old_uac & ~flags
if old_uac == new_uac:
return
mod = """
dn: %s
changetype: modify
delete: userAccountControl
userAccountControl: %u
add: userAccountControl
userAccountControl: %u
""" % (account_dn, old_uac, new_uac)
self.modify_ldif(mod)
def force_password_change_at_next_login(self, search_filter):
"""Forces a password change at next login
:param search_filter: LDAP filter to find the user (eg
samccountname=name)
"""
res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=search_filter, attrs=[])
if len(res) == 0:
raise Exception('Unable to find user "%s"' % search_filter)
assert(len(res) == 1)
user_dn = res[0].dn
mod = """
dn: %s
changetype: modify
replace: pwdLastSet
pwdLastSet: 0
""" % (user_dn)
self.modify_ldif(mod)
def newgroup(self, groupname, groupou=None, grouptype=None,
description=None, mailaddress=None, notes=None, sd=None):
"""Adds a new group with additional parameters
:param groupname: Name of the new group
:param grouptype: Type of the new group
:param description: Description of the new group
:param mailaddress: Email address of the new group
:param notes: Notes of the new group
:param sd: security descriptor of the object
"""
group_dn = "CN=%s,%s,%s" % (groupname, (groupou or "CN=Users"), self.domain_dn())
# The new user record. Note the reliance on the SAMLDB module which
# fills in the default informations
ldbmessage = {"dn": group_dn,
"sAMAccountName": groupname,
"objectClass": "group"}
if grouptype is not None:
ldbmessage["groupType"] = self.normalise_int32(grouptype)
if description is not None:
ldbmessage["description"] = description
if mailaddress is not None:
ldbmessage["mail"] = mailaddress
if notes is not None:
ldbmessage["info"] = notes
if sd is not None:
ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
self.add(ldbmessage)
def deletegroup(self, groupname):
"""Deletes a group
:param groupname: Name of the target group
"""
groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
self.transaction_start()
try:
targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=groupfilter, attrs=[])
if len(targetgroup) == 0:
raise Exception('Unable to find group "%s"' % groupname)
assert(len(targetgroup) == 1)
self.delete(targetgroup[0].dn)
except Exception:
self.transaction_cancel()
raise
else:
self.transaction_commit()
def add_remove_group_members(self, groupname, listofmembers,
add_members_operation=True):
"""Adds or removes group members
:param groupname: Name of the target group
:param listofmembers: Comma-separated list of group members
:param add_members_operation: Defines if its an add or remove
operation
"""
groupfilter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (groupname, "CN=Group,CN=Schema,CN=Configuration", self.domain_dn())
groupmembers = listofmembers.split(',')
self.transaction_start()
try:
targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=groupfilter, attrs=['member'])
if len(targetgroup) == 0:
raise Exception('Unable to find group "%s"' % groupname)
assert(len(targetgroup) == 1)
modified = False
addtargettogroup = """
dn: %s
changetype: modify
""" % (str(targetgroup[0].dn))
for member in groupmembers:
targetmember = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression="(|(sAMAccountName=%s)(CN=%s))" % (member, member), attrs=[])
if len(targetmember) != 1:
continue
if add_members_operation is True and (targetgroup[0].get('member') is None or str(targetmember[0].dn) not in targetgroup[0]['member']):
modified = True
addtargettogroup += """add: member
member: %s
""" % (str(targetmember[0].dn))
elif add_members_operation is False and (targetgroup[0].get('member') is not None and str(targetmember[0].dn) in targetgroup[0]['member']):
modified = True
addtargettogroup += """delete: member
member: %s
""" % (str(targetmember[0].dn))
if modified is True:
self.modify_ldif(addtargettogroup)
except Exception:
self.transaction_cancel()
raise
else:
self.transaction_commit()
def newuser(self, username, password,
force_password_change_at_next_login_req=False,
useusernameascn=False, userou=None, surname=None, givenname=None,
initials=None, profilepath=None, scriptpath=None, homedrive=None,
homedirectory=None, jobtitle=None, department=None, company=None,
description=None, mailaddress=None, internetaddress=None,
telephonenumber=None, physicaldeliveryoffice=None, sd=None,
setpassword=True):
"""Adds a new user with additional parameters
:param username: Name of the new user
:param password: Password for the new user
:param force_password_change_at_next_login_req: Force password change
:param useusernameascn: Use username as cn rather that firstname +
initials + lastname
:param userou: Object container (without domainDN postfix) for new user
:param surname: Surname of the new user
:param givenname: First name of the new user
:param initials: Initials of the new user
:param profilepath: Profile path of the new user
:param scriptpath: Logon script path of the new user
:param homedrive: Home drive of the new user
:param homedirectory: Home directory of the new user
:param jobtitle: Job title of the new user
:param department: Department of the new user
:param company: Company of the new user
:param description: of the new user
:param mailaddress: Email address of the new user
:param internetaddress: Home page of the new user
:param telephonenumber: Phone number of the new user
:param physicaldeliveryoffice: Office location of the new user
:param sd: security descriptor of the object
:param setpassword: optionally disable password reset
"""
displayname = ""
if givenname is not None:
displayname += givenname
if initials is not None:
displayname += ' %s.' % initials
if surname is not None:
displayname += ' %s' % surname
cn = username
if useusernameascn is None and displayname is not "":
cn = displayname
user_dn = "CN=%s,%s,%s" % (cn, (userou or "CN=Users"), self.domain_dn())
dnsdomain = ldb.Dn(self, self.domain_dn()).canonical_str().replace("/", "")
user_principal_name = "%s@%s" % (username, dnsdomain)
# The new user record. Note the reliance on the SAMLDB module which
# fills in the default informations
ldbmessage = {"dn": user_dn,
"sAMAccountName": username,
"userPrincipalName": user_principal_name,
"objectClass": "user"}
if surname is not None:
ldbmessage["sn"] = surname
if givenname is not None:
ldbmessage["givenName"] = givenname
if displayname is not "":
ldbmessage["displayName"] = displayname
ldbmessage["name"] = displayname
if initials is not None:
ldbmessage["initials"] = '%s.' % initials
if profilepath is not None:
ldbmessage["profilePath"] = profilepath
if scriptpath is not None:
ldbmessage["scriptPath"] = scriptpath
if homedrive is not None:
ldbmessage["homeDrive"] = homedrive
if homedirectory is not None:
ldbmessage["homeDirectory"] = homedirectory
if jobtitle is not None:
ldbmessage["title"] = jobtitle
if department is not None:
ldbmessage["department"] = department
if company is not None:
ldbmessage["company"] = company
if description is not None:
ldbmessage["description"] = description
if mailaddress is not None:
ldbmessage["mail"] = mailaddress
if internetaddress is not None:
ldbmessage["wWWHomePage"] = internetaddress
if telephonenumber is not None:
ldbmessage["telephoneNumber"] = telephonenumber
if physicaldeliveryoffice is not None:
ldbmessage["physicalDeliveryOfficeName"] = physicaldeliveryoffice
if sd is not None:
ldbmessage["nTSecurityDescriptor"] = ndr_pack(sd)
self.transaction_start()
try:
self.add(ldbmessage)
# Sets the password for it
if setpassword:
self.setpassword("(samAccountName=%s)" % username, password,
force_password_change_at_next_login_req)
except Exception:
self.transaction_cancel()
raise
else:
self.transaction_commit()
def setpassword(self, search_filter, password,
force_change_at_next_login=False, username=None):
"""Sets the password for a user
:param search_filter: LDAP filter to find the user (eg
samccountname=name)
:param password: Password for the user
:param force_change_at_next_login: Force password change
"""
self.transaction_start()
try:
res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=search_filter, attrs=[])
if len(res) == 0:
raise Exception('Unable to find user "%s"' % (username or search_filter))
if len(res) > 1:
raise Exception('Matched %u multiple users with filter "%s"' % (len(res), search_filter))
user_dn = res[0].dn
setpw = """
dn: %s
changetype: modify
replace: unicodePwd
unicodePwd:: %s
""" % (user_dn, base64.b64encode(("\"" + password + "\"").encode('utf-16-le')))
self.modify_ldif(setpw)
if force_change_at_next_login:
self.force_password_change_at_next_login(
"(dn=" + str(user_dn) + ")")
# modify the userAccountControl to remove the disabled bit
self.enable_account(search_filter)
except Exception:
self.transaction_cancel()
raise
else:
self.transaction_commit()
def setexpiry(self, search_filter, expiry_seconds, no_expiry_req=False):
"""Sets the account expiry for a user
:param search_filter: LDAP filter to find the user (eg
samaccountname=name)
:param expiry_seconds: expiry time from now in seconds
:param no_expiry_req: if set, then don't expire password
"""
self.transaction_start()
try:
res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=search_filter,
attrs=["userAccountControl", "accountExpires"])
if len(res) == 0:
raise Exception('Unable to find user "%s"' % search_filter)
assert(len(res) == 1)
user_dn = res[0].dn
userAccountControl = int(res[0]["userAccountControl"][0])
accountExpires = int(res[0]["accountExpires"][0])
if no_expiry_req:
userAccountControl = userAccountControl | 0x10000
accountExpires = 0
else:
userAccountControl = userAccountControl & ~0x10000
accountExpires = samba.unix2nttime(expiry_seconds + int(time.time()))
setexp = """
dn: %s
changetype: modify
replace: userAccountControl
userAccountControl: %u
replace: accountExpires
accountExpires: %u
""" % (user_dn, userAccountControl, accountExpires)
self.modify_ldif(setexp)
except Exception:
self.transaction_cancel()
raise
else:
self.transaction_commit()
def set_domain_sid(self, sid):
"""Change the domain SID used by this LDB.
:param sid: The new domain sid to use.
"""
dsdb._samdb_set_domain_sid(self, sid)
def get_domain_sid(self):
"""Read the domain SID used by this LDB. """
return dsdb._samdb_get_domain_sid(self)
domain_sid = property(get_domain_sid, set_domain_sid,
"SID for the domain")
def set_invocation_id(self, invocation_id):
"""Set the invocation id for this SamDB handle.
:param invocation_id: GUID of the invocation id.
"""
dsdb._dsdb_set_ntds_invocation_id(self, invocation_id)
def get_invocation_id(self):
"""Get the invocation_id id"""
return dsdb._samdb_ntds_invocation_id(self)
invocation_id = property(get_invocation_id, set_invocation_id,
"Invocation ID GUID")
def get_oid_from_attid(self, attid):
return dsdb._dsdb_get_oid_from_attid(self, attid)
def get_attid_from_lDAPDisplayName(self, ldap_display_name,
is_schema_nc=False):
'''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
ldap_display_name, is_schema_nc)
def get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name):
'''return the syntax OID for a LDAP attribute as a string'''
return dsdb._dsdb_get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name)
def set_ntds_settings_dn(self, ntds_settings_dn):
"""Set the NTDS Settings DN, as would be returned on the dsServiceName
rootDSE attribute.
This allows the DN to be set before the database fully exists
:param ntds_settings_dn: The new DN to use
"""
dsdb._samdb_set_ntds_settings_dn(self, ntds_settings_dn)
def get_ntds_GUID(self):
"""Get the NTDS objectGUID"""
return dsdb._samdb_ntds_objectGUID(self)
def server_site_name(self):
"""Get the server site name"""
return dsdb._samdb_server_site_name(self)
def load_partition_usn(self, base_dn):
return dsdb._dsdb_load_partition_usn(self, base_dn)
def set_schema(self, schema):
self.set_schema_from_ldb(schema.ldb)
def set_schema_from_ldb(self, ldb_conn):
dsdb._dsdb_set_schema_from_ldb(self, ldb_conn)
def dsdb_DsReplicaAttribute(self, ldb, ldap_display_name, ldif_elements):
'''convert a list of attribute values to a DRSUAPI DsReplicaAttribute'''
return dsdb._dsdb_DsReplicaAttribute(ldb, ldap_display_name, ldif_elements)
def dsdb_normalise_attributes(self, ldb, ldap_display_name, ldif_elements):
'''normalise a list of attribute values'''
return dsdb._dsdb_normalise_attributes(ldb, ldap_display_name, ldif_elements)
def get_attribute_from_attid(self, attid):
""" Get from an attid the associated attribute
:param attid: The attribute id for searched attribute
:return: The name of the attribute associated with this id
"""
if len(self.hash_oid_name.keys()) == 0:
self._populate_oid_attid()
if self.hash_oid_name.has_key(self.get_oid_from_attid(attid)):
return self.hash_oid_name[self.get_oid_from_attid(attid)]
else:
return None
def _populate_oid_attid(self):
"""Populate the hash hash_oid_name.
This hash contains the oid of the attribute as a key and
its display name as a value
"""
self.hash_oid_name = {}
res = self.search(expression="objectClass=attributeSchema",
controls=["search_options:1:2"],
attrs=["attributeID",
"lDAPDisplayName"])
if len(res) > 0:
for e in res:
strDisplay = str(e.get("lDAPDisplayName"))
self.hash_oid_name[str(e.get("attributeID"))] = strDisplay
def get_attribute_replmetadata_version(self, dn, att):
"""Get the version field trom the replPropertyMetaData for
the given field
:param dn: The on which we want to get the version
:param att: The name of the attribute
:return: The value of the version field in the replPropertyMetaData
for the given attribute. None if the attribute is not replicated
"""
res = self.search(expression="dn=%s" % dn,
scope=ldb.SCOPE_SUBTREE,
controls=["search_options:1:2"],
attrs=["replPropertyMetaData"])
if len(res) == 0:
return None
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
str(res[0]["replPropertyMetaData"]))
ctr = repl.ctr
if len(self.hash_oid_name.keys()) == 0:
self._populate_oid_attid()
for o in ctr.array:
# Search for Description
att_oid = self.get_oid_from_attid(o.attid)
if self.hash_oid_name.has_key(att_oid) and\
att.lower() == self.hash_oid_name[att_oid].lower():
return o.version
return None
def set_attribute_replmetadata_version(self, dn, att, value,
addifnotexist=False):
res = self.search(expression="dn=%s" % dn,
scope=ldb.SCOPE_SUBTREE,
controls=["search_options:1:2"],
attrs=["replPropertyMetaData"])
if len(res) == 0:
return None
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
str(res[0]["replPropertyMetaData"]))
ctr = repl.ctr
now = samba.unix2nttime(int(time.time()))
found = False
if len(self.hash_oid_name.keys()) == 0:
self._populate_oid_attid()
for o in ctr.array:
# Search for Description
att_oid = self.get_oid_from_attid(o.attid)
if self.hash_oid_name.has_key(att_oid) and\
att.lower() == self.hash_oid_name[att_oid].lower():
found = True
seq = self.sequence_number(ldb.SEQ_NEXT)
o.version = value
o.originating_change_time = now
o.originating_invocation_id = misc.GUID(self.get_invocation_id())
o.originating_usn = seq
o.local_usn = seq
if not found and addifnotexist and len(ctr.array) >0:
o2 = drsblobs.replPropertyMetaData1()
o2.attid = 589914
att_oid = self.get_oid_from_attid(o2.attid)
seq = self.sequence_number(ldb.SEQ_NEXT)
o2.version = value
o2.originating_change_time = now
o2.originating_invocation_id = misc.GUID(self.get_invocation_id())
o2.originating_usn = seq
o2.local_usn = seq
found = True
tab = ctr.array
tab.append(o2)
ctr.count = ctr.count + 1
ctr.array = tab
if found :
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob,
ldb.FLAG_MOD_REPLACE,
"replPropertyMetaData")
self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def write_prefixes_from_schema(self):
dsdb._dsdb_write_prefixes_from_schema_to_ldb(self)
def get_partitions_dn(self):
return dsdb._dsdb_get_partitions_dn(self)
def set_minPwdAge(self, value):
m = ldb.Message()
m.dn = ldb.Dn(self, self.domain_dn())
m["minPwdAge"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdAge")
self.modify(m)
def get_minPwdAge(self):
res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdAge"])
if len(res) == 0:
return None
elif not "minPwdAge" in res[0]:
return None
else:
return res[0]["minPwdAge"][0]
def set_minPwdLength(self, value):
m = ldb.Message()
m.dn = ldb.Dn(self, self.domain_dn())
m["minPwdLength"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "minPwdLength")
self.modify(m)
def get_minPwdLength(self):
res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["minPwdLength"])
if len(res) == 0:
return None
elif not "minPwdLength" in res[0]:
return None
else:
return res[0]["minPwdLength"][0]
def set_pwdProperties(self, value):
m = ldb.Message()
m.dn = ldb.Dn(self, self.domain_dn())
m["pwdProperties"] = ldb.MessageElement(value, ldb.FLAG_MOD_REPLACE, "pwdProperties")
self.modify(m)
def get_pwdProperties(self):
res = self.search(self.domain_dn(), scope=ldb.SCOPE_BASE, attrs=["pwdProperties"])
if len(res) == 0:
return None
elif not "pwdProperties" in res[0]:
return None
else:
return res[0]["pwdProperties"][0]
def set_dsheuristics(self, dsheuristics):
m = ldb.Message()
m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
% self.get_config_basedn().get_linearized())
if dsheuristics is not None:
m["dSHeuristics"] = ldb.MessageElement(dsheuristics,
ldb.FLAG_MOD_REPLACE, "dSHeuristics")
else:
m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
"dSHeuristics")
self.modify(m)
def get_dsheuristics(self):
res = self.search("CN=Directory Service,CN=Windows NT,CN=Services,%s"
% self.get_config_basedn().get_linearized(),
scope=ldb.SCOPE_BASE, attrs=["dSHeuristics"])
if len(res) == 0:
dsheuristics = None
elif "dSHeuristics" in res[0]:
dsheuristics = res[0]["dSHeuristics"][0]
else:
dsheuristics = None
return dsheuristics
def create_ou(self, ou_dn, description=None, name=None, sd=None):
"""Creates an organizationalUnit object
:param ou_dn: dn of the new object
:param description: description attribute
:param name: name atttribute
:param sd: security descriptor of the object, can be
an SDDL string or security.descriptor type
"""
m = {"dn": ou_dn,
"objectClass": "organizationalUnit"}
if description:
m["description"] = description
if name:
m["name"] = name
if sd:
m["nTSecurityDescriptor"] = ndr_pack(sd)
self.add(m)
def normalise_int32(self, ivalue):
'''normalise a ldap integer to signed 32 bit'''
if int(ivalue) & 0x80000000:
return str(int(ivalue) - 0x100000000)
return str(ivalue)
| gwr/samba | source4/scripting/python/samba/samdb.py | Python | gpl-3.0 | 28,037 |
//
// MessageEventArgs.cs
//
// Authors:
// Alan McGovern alan.mcgovern@gmail.com
//
// Copyright (C) 2006 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoTorrent.Client
{
using System;
using System.Text;
using MonoTorrent.Common;
using MonoTorrent.Client.Messages;
/// <summary>
/// Provides the data needed to handle a PeerMessage event
/// </summary>
public class PeerMessageEventArgs : TorrentEventArgs
{
#region Member Variables
/// <summary>
/// The Peer message that was just sent/Received
/// </summary>
public PeerMessage Message
{
get { return this.message; }
}
private PeerMessage message;
/// <summary>
/// The direction of the message (outgoing/incoming)
/// </summary>
public Direction Direction
{
get { return this.direction; }
}
private Direction direction;
public PeerId ID
{
get { return this.id; }
}
private PeerId id;
#endregion
#region Constructors
/// <summary>
/// Creates a new PeerMessageEventArgs
/// </summary>
/// <param name="message">The peer message involved</param>
/// <param name="direction">The direction of the message</param>
internal PeerMessageEventArgs(TorrentManager manager, PeerMessage message, Direction direction, PeerId id)
:base(manager)
{
this.direction = direction;
this.id = id;
this.message = message;
}
#endregion
}
}
| aaronsace/MultiPoolMiner | MonoTorrent/MonoTorrent.Client/EventArgs/MessageEventArgs.cs | C# | gpl-3.0 | 2,711 |
package com.ftninformatika.bisis.opac.search;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author badf00d21 15.8.19.
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Sort {
private SortType type;
private Boolean ascending;
public SortType getType() {
return type;
}
public void setType(String st) {
switch (st) {
case "AU_sort" : this.type = SortType.SORT_AUTHOR; break;
case "PY_sort" : this.type = SortType.SORT_YEAR; break;
case "PU_sort" : this.type = SortType.SORT_PUBLISHER; break;
case "TI_sort" : this.type = SortType.SORT_TITLE; break;
default: this.type = null;
}
}
}
| ftninformatika/bisis-v5 | bisis-model/src/main/java/com/ftninformatika/bisis/opac/search/Sort.java | Java | gpl-3.0 | 788 |
/*
UTILIZZO DEL MODULO:
var mailer = require('percorso/per/questoFile.js');
mailer.inviaEmail(nome, cognome, emailDestinatario, oggetto, corpoInHtml);
OPPURE
mailer.inviaEmail(opzioniEmail);
dove opzioniEmail è un oggetto JSON formato così:
{
from: '"Nome Visualizzato" <mail@example.com>', // mail del mittente
to: 'info@contoso.com', // email destinatario, eventualmente può essere una lista con elementi separati da virgole
subject: 'Oggetto', // l'oggetto dell'email
text: 'Ciao', // email solo testo
html: '<h3>Ciao</h3>' // email HTML
}
L'indirizzo email usato per l'invio nel primo caso è quello del gruppo dei developer (creato ad hoc per il progetto) , ovvero
mail.sitotranquillo@gmail.com
Eventualmente basta cambiare i settaggi nel transporter
Un futuro lavoro potrebbe essere quello di fare in modo che anche il
transporter sia settabile a piacimento dall'applicazione stessa
*/
'use strict';
const nodemailer = require('nodemailer');
var jsonfile = require('jsonfile')
var file = './server/config/mailSettings.json';
var fs = require('fs');
var transporter;
//var passwords = require('../config/passwords');
var scriviFileDummy = function() {
var settaggi = {
host: 'smtp.example.org',
port: 465,
secure: 'true',
user: 'user@example.org',
pass: 'passwordExample'
};
// scrivo il file dummy
jsonfile.writeFileSync(file, settaggi);
return settaggi;
};
var impostaTransporter = function() {
var settaggi = leggiPrivate();
// svuoto il vecchio transporter e lo ricreo
transporter = null;
transporter = nodemailer.createTransport({
host: settaggi.host,
port: settaggi.port,
secure: settaggi.secure,
auth: {
user: settaggi.user,
pass: settaggi.pass
}
});
console.log('transporter impostato');
}
var leggiPrivate = function() {
if (fs.existsSync(file)) {
console.log('File exists');
return jsonfile.readFileSync(file)
} else {
// file does not exist
return scriviFileDummy();
}
}
exports.leggiSettaggi = function() {
console.log('chiamata dalla api al mailer')
if (fs.existsSync(file)) {
console.log('File exists');
return jsonfile.readFileSync(file)
} else {
// file does not exist
return scriviFileDummy();
}
}
exports.scriviSettaggi = function(obj) {
// se non ci sono settaggi li creo dummy
if (obj === null)
scriviFileDummy()
else jsonfile.writeFile(file, obj, function(err) {
if (err) return console.log('ERRORE NELLA SCRITTURA DEI SETTAGGI EMAIL');
impostaTransporter();
});
}
exports.inviaEmail = function(opzioniEmail) {
if (transporter === null || transporter === undefined) {
// lo popolo al volo
impostaTransporter();
}
transporter.sendMail(opzioniEmail, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
})
}
exports.inviaEmail = function(nome, cognome, emailDestinatario, oggetto, corpoInHtml) {
/*
FORMA JSON DELLE OPZIONI:
{
from: '"Fred Foo 👻" <foo@blurdybloop.com>', // indirizzo mittente
to: 'bar@blurdybloop.com, baz@blurdybloop.com', // lista riceventi
subject: 'Hello ✔', // Intestazione
text: 'Hello world ?', // email con testo normale
html: '<b>Hello world ?</b>' // email con testo in html
}
*/
if (transporter === null || transporter === undefined) {
// lo popolo al volo
impostaTransporter();
}
var opzioniEmail = {
from: '"Sito Tranquillo" <mail.sitotranquillo@gmail.com>',
to: emailDestinatario,
subject: oggetto,
html: corpoInHtml
}
transporter.sendMail(opzioniEmail, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
})
} | ecommerce-unicam/Sito-Tranquillo | server/utilities/mailer.js | JavaScript | gpl-3.0 | 4,054 |
/*
Free Download Manager Copyright (c) 2003-2016 FreeDownloadManager.ORG
*/
#include "stdafx.h"
#include "FDMCustomized.h"
#include "Dlg_Banner.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CDlg_Banner::CDlg_Banner(CWnd* pParent )
: CDialog(CDlg_Banner::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlg_Banner)
m_strFile = _T("");
m_strURL = _T("");
//}}AFX_DATA_INIT
}
void CDlg_Banner::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlg_Banner)
DDX_Text(pDX, IDC_FILE, m_strFile);
DDX_Text(pDX, IDC_URL, m_strURL);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlg_Banner, CDialog)
//{{AFX_MSG_MAP(CDlg_Banner)
ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CDlg_Banner::OnBrowse()
{
CFileDialog dlg (TRUE, NULL, m_strFile, OFN_HIDEREADONLY|OFN_NOCHANGEDIR,
"Banner's images (*.jpg,*.gif)|*.jpg;*.gif|All files (*.*)|*.*||", this);
if (dlg.DoModal () == IDOK)
{
m_strFile = dlg.GetPathName ();
SetDlgItemText (IDC_FILE, m_strFile);
}
}
| mirror/freedownload | FDMCustomized/Dlg_Banner.cpp | C++ | gpl-3.0 | 1,120 |
package jbse.tree;
public final class DecisionAlternative_XNEWARRAY_Wrong extends DecisionAlternative_XNEWARRAY {
private static final String WRONG_ID = "XNEWARRAY_Wrong";
private static final int HASH_CODE = 2;
DecisionAlternative_XNEWARRAY_Wrong(boolean isConcrete) {
super(isConcrete, (isConcrete ? 1 : HASH_CODE));
}
@Override
public boolean ok() {
return false;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
@Override
public int hashCode() {
return HASH_CODE;
}
@Override
public String toString() {
return WRONG_ID;
}
}
| chubbymaggie/jbse | src/jbse/tree/DecisionAlternative_XNEWARRAY_Wrong.java | Java | gpl-3.0 | 758 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace TTSSX.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| domints/TTSSX | TTSSX/TTSSX.UWP/App.xaml.cs | C# | gpl-3.0 | 3,858 |
<?php
/**
* Open Source Social Network
*
* @package (softlab24.com).ossn
* @author OSSN Core Team <info@softlab24.com>
* @copyright 2014-2017 SOFTLAB24 LIMITED
* @license Open Source Social Network License (OSSN LICENSE) http://www.opensource-socialnetwork.org/licence
* @link https://www.opensource-socialnetwork.org/
*/
$class = '';
if(isset($params['class'])){
$class = $params['class'];
}
if(empty($params['title'])){
return;
}
?>
<div class="ossn-widget <?php echo $class;?>">
<div class="widget-heading"><?php echo $params['title'];?></div>
<div class="widget-contents">
<?php echo $params['contents'];?>
</div>
</div> | Lablnet/Malik_Theme | plugins/default/widget/view.php | PHP | gpl-3.0 | 662 |
#include "Sub.h"
// manual_init - initialise manual controller
bool Sub::manual_init()
{
// set target altitude to zero for reporting
pos_control.set_alt_target(0);
// attitude hold inputs become thrust inputs in manual mode
// set to neutral to prevent chaotic behavior (esp. roll/pitch)
set_neutral_controls();
return true;
}
// manual_run - runs the manual (passthrough) controller
// should be called at 100hz or more
void Sub::manual_run()
{
// if not armed set throttle to zero and exit immediately
if (!motors.armed()) {
motors.set_desired_spool_state(AP_Motors::DESIRED_GROUND_IDLE);
attitude_control.set_throttle_out_unstabilized(0,true,g.throttle_filt);
return;
}
motors.set_desired_spool_state(AP_Motors::DESIRED_THROTTLE_UNLIMITED);
motors.set_roll(channel_roll->norm_input());
motors.set_pitch(channel_pitch->norm_input());
motors.set_yaw(channel_yaw->norm_input() * g.acro_yaw_p / ACRO_YAW_P);
motors.set_throttle(channel_throttle->norm_input());
motors.set_forward(channel_forward->norm_input());
motors.set_lateral(channel_lateral->norm_input());
}
| hamishwillee/ardupilot | ArduSub/control_manual.cpp | C++ | gpl-3.0 | 1,159 |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (2013) Alexander Stukowski
//
// This file is part of OVITO (Open Visualization Tool).
//
// OVITO 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.
//
// OVITO 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 <plugins/particles/Particles.h>
#include <core/viewport/Viewport.h>
#include <core/scene/pipeline/PipelineObject.h>
#include <core/animation/controller/Controller.h>
#include <core/reference/CloneHelper.h>
#include <core/gui/mainwin/MainWindow.h>
#include <core/gui/dialogs/LoadImageFileDialog.h>
#include <core/gui/properties/FloatParameterUI.h>
#include <core/gui/properties/Vector3ParameterUI.h>
#include <core/gui/properties/ColorParameterUI.h>
#include <core/gui/properties/BooleanParameterUI.h>
#include <core/gui/properties/CustomParameterUI.h>
#include <core/plugins/PluginManager.h>
#include <core/gui/dialogs/SaveImageFileDialog.h>
#include <core/rendering/SceneRenderer.h>
#include <core/viewport/ViewportConfiguration.h>
#include <plugins/particles/util/ParticlePropertyParameterUI.h>
#include "ColorCodingModifier.h"
namespace Ovito { namespace Particles { OVITO_BEGIN_INLINE_NAMESPACE(Modifiers) OVITO_BEGIN_INLINE_NAMESPACE(Coloring)
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingModifier, ParticleModifier);
SET_OVITO_OBJECT_EDITOR(ColorCodingModifier, ColorCodingModifierEditor);
DEFINE_REFERENCE_FIELD(ColorCodingModifier, _startValueCtrl, "StartValue", Controller);
DEFINE_REFERENCE_FIELD(ColorCodingModifier, _endValueCtrl, "EndValue", Controller);
DEFINE_REFERENCE_FIELD(ColorCodingModifier, _colorGradient, "ColorGradient", ColorCodingGradient);
DEFINE_PROPERTY_FIELD(ColorCodingModifier, _colorOnlySelected, "SelectedOnly");
DEFINE_PROPERTY_FIELD(ColorCodingModifier, _keepSelection, "KeepSelection");
DEFINE_PROPERTY_FIELD(ColorCodingModifier, _sourceProperty, "SourceProperty");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _startValueCtrl, "Start value");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _endValueCtrl, "End value");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _colorGradient, "Color gradient");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _colorOnlySelected, "Color only selected particles");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _keepSelection, "Keep particles selected");
SET_PROPERTY_FIELD_LABEL(ColorCodingModifier, _sourceProperty, "Source property");
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingGradient, RefTarget);
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingHSVGradient, ColorCodingGradient);
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingGrayscaleGradient, ColorCodingGradient);
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingHotGradient, ColorCodingGradient);
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingJetGradient, ColorCodingGradient);
IMPLEMENT_SERIALIZABLE_OVITO_OBJECT(Particles, ColorCodingImageGradient, ColorCodingGradient);
DEFINE_PROPERTY_FIELD(ColorCodingImageGradient, _image, "Image");
OVITO_BEGIN_INLINE_NAMESPACE(Internal)
IMPLEMENT_OVITO_OBJECT(Particles, ColorCodingModifierEditor, ParticleModifierEditor);
OVITO_END_INLINE_NAMESPACE
/******************************************************************************
* Constructs the modifier object.
******************************************************************************/
ColorCodingModifier::ColorCodingModifier(DataSet* dataset) : ParticleModifier(dataset),
_colorOnlySelected(false), _keepSelection(false)
{
INIT_PROPERTY_FIELD(ColorCodingModifier::_startValueCtrl);
INIT_PROPERTY_FIELD(ColorCodingModifier::_endValueCtrl);
INIT_PROPERTY_FIELD(ColorCodingModifier::_colorGradient);
INIT_PROPERTY_FIELD(ColorCodingModifier::_colorOnlySelected);
INIT_PROPERTY_FIELD(ColorCodingModifier::_keepSelection);
INIT_PROPERTY_FIELD(ColorCodingModifier::_sourceProperty);
_colorGradient = new ColorCodingHSVGradient(dataset);
_startValueCtrl = ControllerManager::instance().createFloatController(dataset);
_endValueCtrl = ControllerManager::instance().createFloatController(dataset);
}
/******************************************************************************
* Loads the user-defined default values of this object's parameter fields from the
* application's settings store.
******************************************************************************/
void ColorCodingModifier::loadUserDefaults()
{
ParticleModifier::loadUserDefaults();
// Load the default gradient type set by the user.
QSettings settings;
settings.beginGroup(ColorCodingModifier::OOType.plugin()->pluginId());
settings.beginGroup(ColorCodingModifier::OOType.name());
QString typeString = settings.value(PROPERTY_FIELD(ColorCodingModifier::_colorGradient).identifier()).toString();
if(!typeString.isEmpty()) {
try {
OvitoObjectType* gradientType = OvitoObjectType::decodeFromString(typeString);
if(!colorGradient() || colorGradient()->getOOType() != *gradientType) {
OORef<ColorCodingGradient> gradient = dynamic_object_cast<ColorCodingGradient>(gradientType->createInstance(dataset()));
if(gradient) setColorGradient(gradient);
}
}
catch(...) {}
}
}
/******************************************************************************
* Asks the modifier for its validity interval at the given time.
******************************************************************************/
TimeInterval ColorCodingModifier::modifierValidity(TimePoint time)
{
TimeInterval interval = ParticleModifier::modifierValidity(time);
if(_startValueCtrl) interval.intersect(_startValueCtrl->validityInterval(time));
if(_endValueCtrl) interval.intersect(_endValueCtrl->validityInterval(time));
return interval;
}
/******************************************************************************
* This method is called by the system when the modifier has been inserted
* into a pipeline.
******************************************************************************/
void ColorCodingModifier::initializeModifier(PipelineObject* pipeline, ModifierApplication* modApp)
{
ParticleModifier::initializeModifier(pipeline, modApp);
if(sourceProperty().isNull()) {
// Select the first available particle property from the input.
PipelineFlowState input = pipeline->evaluatePipeline(dataset()->animationSettings()->time(), modApp, false);
ParticlePropertyReference bestProperty;
for(DataObject* o : input.objects()) {
ParticlePropertyObject* property = dynamic_object_cast<ParticlePropertyObject>(o);
if(property && (property->dataType() == qMetaTypeId<int>() || property->dataType() == qMetaTypeId<FloatType>())) {
bestProperty = ParticlePropertyReference(property, (property->componentCount() > 1) ? 0 : -1);
}
}
if(!bestProperty.isNull())
setSourceProperty(bestProperty);
}
// Automatically adjust value range.
if(startValue() == 0 && endValue() == 0)
adjustRange();
}
/******************************************************************************
* This modifies the input object.
******************************************************************************/
PipelineStatus ColorCodingModifier::modifyParticles(TimePoint time, TimeInterval& validityInterval)
{
// Get the source property.
if(sourceProperty().isNull())
throw Exception(tr("Select a particle property first."));
ParticlePropertyObject* property = sourceProperty().findInState(input());
if(!property)
throw Exception(tr("The particle property with the name '%1' does not exist.").arg(sourceProperty().name()));
if(sourceProperty().vectorComponent() >= (int)property->componentCount())
throw Exception(tr("The vector component is out of range. The particle property '%1' contains only %2 values per particle.").arg(sourceProperty().name()).arg(property->componentCount()));
int vecComponent = std::max(0, sourceProperty().vectorComponent());
int stride = property->stride() / property->dataTypeSize();
if(!_colorGradient)
throw Exception(tr("No color gradient has been selected."));
// Get modifier's parameter values.
FloatType startValue = 0, endValue = 0;
if(_startValueCtrl) startValue = _startValueCtrl->getFloatValue(time, validityInterval);
if(_endValueCtrl) endValue = _endValueCtrl->getFloatValue(time, validityInterval);
// Get the particle selection property if enabled by the user.
ParticlePropertyObject* selProperty = nullptr;
const int* sel = nullptr;
std::vector<Color> existingColors;
if(colorOnlySelected()) {
selProperty = inputStandardProperty(ParticleProperty::SelectionProperty);
if(selProperty) {
sel = selProperty->constDataInt();
existingColors = inputParticleColors(time, validityInterval);
}
}
// Create the color output property.
ParticlePropertyObject* colorProperty = outputStandardProperty(ParticleProperty::ColorProperty);
OVITO_ASSERT(colorProperty->size() == property->size());
Color* c_begin = colorProperty->dataColor();
Color* c_end = c_begin + colorProperty->size();
Color* c = c_begin;
if(property->dataType() == qMetaTypeId<FloatType>()) {
const FloatType* v = property->constDataFloat() + vecComponent;
for(; c != c_end; ++c, v += stride) {
// If the "only selected" option is enabled, and the particle is not selected, use the existing particle color.
if(sel && !(*sel++)) {
*c = existingColors[c - c_begin];
continue;
}
// Compute linear interpolation.
FloatType t;
if(startValue == endValue) {
if((*v) == startValue) t = 0.5;
else if((*v) > startValue) t = 1.0;
else t = 0.0;
}
else t = ((*v) - startValue) / (endValue - startValue);
// Clamp values.
if(t < 0) t = 0;
else if(t > 1) t = 1;
*c = _colorGradient->valueToColor(t);
}
}
else if(property->dataType() == qMetaTypeId<int>()) {
const int* v = property->constDataInt() + vecComponent;
for(; c != c_end; ++c, v += stride) {
// If the "only selected" option is enabled, and the particle is not selected, use the existing particle color.
if(sel && !(*sel++)) {
*c = existingColors[c - c_begin];
continue;
}
// Compute linear interpolation.
FloatType t;
if(startValue == endValue) {
if((*v) == startValue) t = 0.5;
else if((*v) > startValue) t = 1.0;
else t = 0.0;
}
else t = ((*v) - startValue) / (endValue - startValue);
// Clamp values.
if(t < 0) t = 0;
else if(t > 1) t = 1;
*c = _colorGradient->valueToColor(t);
}
}
else
throw Exception(tr("The particle property '%1' has an invalid or non-numeric data type.").arg(property->name()));
// Clear particle selection if requested.
if(selProperty && !keepSelection())
output().removeObject(selProperty);
colorProperty->changed();
return PipelineStatus::Success;
}
/******************************************************************************
* Sets the start and end value to the minimum and maximum value
* in the selected particle property.
******************************************************************************/
bool ColorCodingModifier::adjustRange()
{
// Determine the minimum and maximum values of the selected particle property.
// Get the value data channel from the input object.
PipelineFlowState inputState = getModifierInput();
ParticlePropertyObject* property = sourceProperty().findInState(inputState);
if(!property)
return false;
if(sourceProperty().vectorComponent() >= (int)property->componentCount())
return false;
int vecComponent = std::max(0, sourceProperty().vectorComponent());
int stride = property->stride() / property->dataTypeSize();
// Iterate over all atoms.
FloatType maxValue = FLOATTYPE_MIN;
FloatType minValue = FLOATTYPE_MAX;
if(property->dataType() == qMetaTypeId<FloatType>()) {
const FloatType* v = property->constDataFloat() + vecComponent;
const FloatType* vend = v + (property->size() * stride);
for(; v != vend; v += stride) {
if(*v > maxValue) maxValue = *v;
if(*v < minValue) minValue = *v;
}
}
else if(property->dataType() == qMetaTypeId<int>()) {
const int* v = property->constDataInt() + vecComponent;
const int* vend = v + (property->size() * stride);
for(; v != vend; v += stride) {
if(*v > maxValue) maxValue = *v;
if(*v < minValue) minValue = *v;
}
}
if(minValue == +FLOATTYPE_MAX)
return false;
if(startValueController())
startValueController()->setCurrentFloatValue(minValue);
if(endValueController())
endValueController()->setCurrentFloatValue(maxValue);
return true;
}
/******************************************************************************
* Saves the class' contents to the given stream.
******************************************************************************/
void ColorCodingModifier::saveToStream(ObjectSaveStream& stream)
{
ParticleModifier::saveToStream(stream);
stream.beginChunk(0x02);
stream.endChunk();
}
/******************************************************************************
* Loads the class' contents from the given stream.
******************************************************************************/
void ColorCodingModifier::loadFromStream(ObjectLoadStream& stream)
{
ParticleModifier::loadFromStream(stream);
int version = stream.expectChunkRange(0, 0x02);
if(version == 0x01) {
ParticlePropertyReference pref;
stream >> pref;
setSourceProperty(pref);
}
stream.closeChunk();
}
/******************************************************************************
* Loads the given image file from disk.
******************************************************************************/
void ColorCodingImageGradient::loadImage(const QString& filename)
{
QImage image(filename);
if(image.isNull())
throw Exception(tr("Could not load image file '%1'.").arg(filename));
setImage(image);
}
/******************************************************************************
* Converts a scalar value to a color value.
******************************************************************************/
Color ColorCodingImageGradient::valueToColor(FloatType t)
{
if(image().isNull()) return Color(0,0,0);
QPoint p;
if(image().width() > image().height())
p = QPoint(std::min((int)(t * image().width()), image().width()-1), 0);
else
p = QPoint(0, std::min((int)(t * image().height()), image().height()-1));
return Color(image().pixel(p));
}
OVITO_BEGIN_INLINE_NAMESPACE(Internal)
/******************************************************************************
* Sets up the UI widgets of the editor.
******************************************************************************/
void ColorCodingModifierEditor::createUI(const RolloutInsertionParameters& rolloutParams)
{
// Create a rollout.
QWidget* rollout = createRollout(tr("Color coding"), rolloutParams, "particles.modifiers.color_coding.html");
// Create the rollout contents.
QVBoxLayout* layout1 = new QVBoxLayout(rollout);
layout1->setContentsMargins(4,4,4,4);
layout1->setSpacing(2);
ParticlePropertyParameterUI* sourcePropertyUI = new ParticlePropertyParameterUI(this, PROPERTY_FIELD(ColorCodingModifier::_sourceProperty));
layout1->addWidget(new QLabel(tr("Property:"), rollout));
layout1->addWidget(sourcePropertyUI->comboBox());
colorGradientList = new QComboBox(rollout);
layout1->addWidget(new QLabel(tr("Color gradient:"), rollout));
layout1->addWidget(colorGradientList);
colorGradientList->setIconSize(QSize(48,16));
connect(colorGradientList, (void (QComboBox::*)(int))&QComboBox::activated, this, &ColorCodingModifierEditor::onColorGradientSelected);
for(const OvitoObjectType* clazz : PluginManager::instance().listClasses(ColorCodingGradient::OOType)) {
if(clazz == &ColorCodingImageGradient::OOType)
continue;
colorGradientList->addItem(iconFromColorMapClass(clazz), clazz->displayName(), QVariant::fromValue(clazz));
}
colorGradientList->insertSeparator(colorGradientList->count());
colorGradientList->addItem(tr("Load custom color map..."));
_gradientListContainCustomItem = false;
// Update color legend if another modifier has been loaded into the editor.
connect(this, &ColorCodingModifierEditor::contentsReplaced, this, &ColorCodingModifierEditor::updateColorGradient);
layout1->addSpacing(10);
QGridLayout* layout2 = new QGridLayout();
layout2->setContentsMargins(0,0,0,0);
layout2->setColumnStretch(1, 1);
layout1->addLayout(layout2);
// End value parameter.
FloatParameterUI* endValuePUI = new FloatParameterUI(this, PROPERTY_FIELD(ColorCodingModifier::_endValueCtrl));
layout2->addWidget(endValuePUI->label(), 0, 0);
layout2->addLayout(endValuePUI->createFieldLayout(), 0, 1);
// Insert color legend display.
colorLegendLabel = new QLabel(rollout);
colorLegendLabel->setScaledContents(true);
layout2->addWidget(colorLegendLabel, 1, 1);
// Start value parameter.
FloatParameterUI* startValuePUI = new FloatParameterUI(this, PROPERTY_FIELD(ColorCodingModifier::_startValueCtrl));
layout2->addWidget(startValuePUI->label(), 2, 0);
layout2->addLayout(startValuePUI->createFieldLayout(), 2, 1);
// Export color scale button.
QToolButton* exportBtn = new QToolButton(rollout);
exportBtn->setIcon(QIcon(":/particles/icons/export_color_scale.png"));
exportBtn->setToolTip("Export color map to image file");
exportBtn->setAutoRaise(true);
exportBtn->setIconSize(QSize(42,22));
connect(exportBtn, &QPushButton::clicked, this, &ColorCodingModifierEditor::onExportColorScale);
layout2->addWidget(exportBtn, 1, 0, Qt::AlignCenter);
layout1->addSpacing(8);
QPushButton* adjustBtn = new QPushButton(tr("Adjust range"), rollout);
connect(adjustBtn, &QPushButton::clicked, this, &ColorCodingModifierEditor::onAdjustRange);
layout1->addWidget(adjustBtn);
layout1->addSpacing(4);
QPushButton* reverseBtn = new QPushButton(tr("Reverse range"), rollout);
connect(reverseBtn, &QPushButton::clicked, this, &ColorCodingModifierEditor::onReverseRange);
layout1->addWidget(reverseBtn);
layout1->addSpacing(8);
// Only selected particles.
BooleanParameterUI* onlySelectedPUI = new BooleanParameterUI(this, PROPERTY_FIELD(ColorCodingModifier::_colorOnlySelected));
layout1->addWidget(onlySelectedPUI->checkBox());
// Keep selection
BooleanParameterUI* keepSelectionPUI = new BooleanParameterUI(this, PROPERTY_FIELD(ColorCodingModifier::_keepSelection));
layout1->addWidget(keepSelectionPUI->checkBox());
connect(onlySelectedPUI->checkBox(), &QCheckBox::toggled, keepSelectionPUI, &BooleanParameterUI::setEnabled);
keepSelectionPUI->setEnabled(false);
}
/******************************************************************************
* Updates the display for the color gradient.
******************************************************************************/
void ColorCodingModifierEditor::updateColorGradient()
{
ColorCodingModifier* mod = static_object_cast<ColorCodingModifier>(editObject());
if(!mod) return;
// Create the color legend image.
int legendHeight = 128;
QImage image(1, legendHeight, QImage::Format_RGB32);
for(int y = 0; y < legendHeight; y++) {
FloatType t = (FloatType)y / (legendHeight - 1);
Color color = mod->colorGradient()->valueToColor(1.0 - t);
image.setPixel(0, y, QColor(color).rgb());
}
colorLegendLabel->setPixmap(QPixmap::fromImage(image));
// Select the right entry in the color gradient selector.
bool isCustomMap = false;
if(mod->colorGradient()) {
int index = colorGradientList->findData(QVariant::fromValue(&mod->colorGradient()->getOOType()));
if(index >= 0)
colorGradientList->setCurrentIndex(index);
else
isCustomMap = true;
}
else colorGradientList->setCurrentIndex(-1);
if(isCustomMap) {
if(!_gradientListContainCustomItem) {
_gradientListContainCustomItem = true;
colorGradientList->insertItem(colorGradientList->count() - 2, iconFromColorMap(mod->colorGradient()), tr("Custom color map"));
colorGradientList->insertSeparator(colorGradientList->count() - 3);
}
else {
colorGradientList->setItemIcon(colorGradientList->count() - 3, iconFromColorMap(mod->colorGradient()));
}
colorGradientList->setCurrentIndex(colorGradientList->count() - 3);
}
else if(_gradientListContainCustomItem) {
_gradientListContainCustomItem = false;
colorGradientList->removeItem(colorGradientList->count() - 3);
colorGradientList->removeItem(colorGradientList->count() - 3);
}
}
/******************************************************************************
* This method is called when a reference target changes.
******************************************************************************/
bool ColorCodingModifierEditor::referenceEvent(RefTarget* source, ReferenceEvent* event)
{
if(source == editObject() && event->type() == ReferenceEvent::ReferenceChanged &&
static_cast<ReferenceFieldEvent*>(event)->field() == PROPERTY_FIELD(ColorCodingModifier::_colorGradient)) {
updateColorGradient();
}
return ParticleModifierEditor::referenceEvent(source, event);
}
/******************************************************************************
* Is called when the user selects a color gradient in the list box.
******************************************************************************/
void ColorCodingModifierEditor::onColorGradientSelected(int index)
{
if(index < 0) return;
ColorCodingModifier* mod = static_object_cast<ColorCodingModifier>(editObject());
OVITO_CHECK_OBJECT_POINTER(mod);
const OvitoObjectType* descriptor = colorGradientList->itemData(index).value<const OvitoObjectType*>();
if(descriptor) {
undoableTransaction(tr("Change color gradient"), [descriptor, mod]() {
OORef<ColorCodingGradient> gradient = static_object_cast<ColorCodingGradient>(descriptor->createInstance(mod->dataset()));
if(gradient) {
mod->setColorGradient(gradient);
QSettings settings;
settings.beginGroup(ColorCodingModifier::OOType.plugin()->pluginId());
settings.beginGroup(ColorCodingModifier::OOType.name());
settings.setValue(PROPERTY_FIELD(ColorCodingModifier::_colorGradient).identifier(),
QVariant::fromValue(OvitoObjectType::encodeAsString(descriptor)));
}
});
}
else if(index == colorGradientList->count() - 1) {
undoableTransaction(tr("Change color gradient"), [this, mod]() {
LoadImageFileDialog fileDialog(container(), tr("Pick color map image"));
if(fileDialog.exec()) {
OORef<ColorCodingImageGradient> gradient(new ColorCodingImageGradient(mod->dataset()));
gradient->loadImage(fileDialog.imageInfo().filename());
mod->setColorGradient(gradient);
}
});
}
}
/******************************************************************************
* Is called when the user presses the "Adjust Range" button.
******************************************************************************/
void ColorCodingModifierEditor::onAdjustRange()
{
ColorCodingModifier* mod = static_object_cast<ColorCodingModifier>(editObject());
OVITO_CHECK_OBJECT_POINTER(mod);
undoableTransaction(tr("Adjust range"), [mod]() {
mod->adjustRange();
});
}
/******************************************************************************
* Is called when the user presses the "Reverse Range" button.
******************************************************************************/
void ColorCodingModifierEditor::onReverseRange()
{
ColorCodingModifier* mod = static_object_cast<ColorCodingModifier>(editObject());
if(mod->startValueController() && mod->endValueController()) {
undoableTransaction(tr("Reverse range"), [mod]() {
// Swap controllers for start and end value.
OORef<Controller> oldStartValue = mod->startValueController();
mod->setStartValueController(mod->endValueController());
mod->setEndValueController(oldStartValue);
});
}
}
/******************************************************************************
* Is called when the user presses the "Export color scale" button.
******************************************************************************/
void ColorCodingModifierEditor::onExportColorScale()
{
ColorCodingModifier* mod = static_object_cast<ColorCodingModifier>(editObject());
if(!mod || !mod->colorGradient()) return;
SaveImageFileDialog fileDialog(colorLegendLabel, tr("Save color map"));
if(fileDialog.exec()) {
// Create the color legend image.
int legendWidth = 32;
int legendHeight = 256;
QImage image(1, legendHeight, QImage::Format_RGB32);
for(int y = 0; y < legendHeight; y++) {
FloatType t = (FloatType)y / (FloatType)(legendHeight - 1);
Color color = mod->colorGradient()->valueToColor(1.0 - t);
image.setPixel(0, y, QColor(color).rgb());
}
QString imageFilename = fileDialog.imageInfo().filename();
if(!image.scaled(legendWidth, legendHeight, Qt::IgnoreAspectRatio, Qt::FastTransformation).save(imageFilename, fileDialog.imageInfo().format())) {
Exception ex(tr("Failed to save image to file '%1'.").arg(imageFilename));
ex.showError();
}
}
}
/******************************************************************************
* Returns an icon representing the given color map class.
******************************************************************************/
QIcon ColorCodingModifierEditor::iconFromColorMapClass(const OvitoObjectType* clazz)
{
/// Cache icons for color map types.
static std::map<const OvitoObjectType*, QIcon> iconCache;
auto entry = iconCache.find(clazz);
if(entry != iconCache.end())
return entry->second;
DataSet* dataset = mainWindow()->datasetContainer().currentSet();
OVITO_ASSERT(dataset);
if(dataset) {
try {
// Create a temporary instance of the color map class.
OORef<ColorCodingGradient> map = static_object_cast<ColorCodingGradient>(clazz->createInstance(dataset));
if(map) {
QIcon icon = iconFromColorMap(map);
iconCache.insert(std::make_pair(clazz, icon));
return icon;
}
}
catch(...) {}
}
return QIcon();
}
/******************************************************************************
* Returns an icon representing the given color map.
******************************************************************************/
QIcon ColorCodingModifierEditor::iconFromColorMap(ColorCodingGradient* map)
{
const int sizex = 48;
const int sizey = 16;
QImage image(sizex, sizey, QImage::Format_RGB32);
for(int x = 0; x < sizex; x++) {
FloatType t = (FloatType)x / (sizex - 1);
uint c = QColor(map->valueToColor(t)).rgb();
for(int y = 0; y < sizey; y++)
image.setPixel(x, y, c);
}
return QIcon(QPixmap::fromImage(image));
}
OVITO_END_INLINE_NAMESPACE
OVITO_END_INLINE_NAMESPACE
OVITO_END_INLINE_NAMESPACE
} // End of namespace
} // End of namespace
| bitzhuwei/OVITO_sureface | src/plugins/particles/modifier/coloring/ColorCodingModifier.cpp | C++ | gpl-3.0 | 27,106 |
/*
* Copyright (C) 2010- Peer internet solutions
*
* This file is part of mixare.
*
* 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.medankulinar.mgr.downloader;
/**
* This class establishes a connection and downloads the data for each entry in
* its todo list one after another.
*/
public interface DownloadManager {
/**
* Possible state of this Manager
*/
enum DownloadManagerState {
OnLine, //manage downlad request
OffLine, // No OnLine
Downloading, //Process some Download Request
Confused // Internal state not congruent
}
/**
* Reset all Request and Responce
*/
void resetActivity();
/**
* Submit new DownloadRequest
*
* @param job
* @return reference Of Job or null if job is rejected
*/
String submitJob(DownloadRequest job);
/**
* Get result of job if exist, null otherwise
*
* @param jobId reference of Job
* @return result
*/
DownloadResult getReqResult(String jobId);
/**
* Pseudo Iterator on results
* @return actual Download Result
*/
DownloadResult getNextResult();
/**
* Gets the number of downloaded results
* @return the number of results
*/
int getResultSize();
/**
* check if all Download request is done
*
* @return BOOLEAN
*/
Boolean isDone();
/**
* Request to active the service
*/
void switchOn();
/**
* Request to deactive the service
*/
void switchOff();
/**
* Request state of service
* @return
*/
DownloadManagerState getState();
} | januar/KulinARMedan | src/org/medankulinar/mgr/downloader/DownloadManager.java | Java | gpl-3.0 | 2,100 |
package de.voidnode.trading4j.strategyexpertadvisor;
import java.time.Instant;
import java.util.Optional;
import de.voidnode.trading4j.api.Broker;
import de.voidnode.trading4j.api.ExpertAdvisor;
import de.voidnode.trading4j.api.Failed;
import de.voidnode.trading4j.api.OrderEventListener;
import de.voidnode.trading4j.domain.marketdata.MarketData;
import de.voidnode.trading4j.domain.monetary.Price;
import de.voidnode.trading4j.domain.orders.BasicPendingOrder;
/**
* Creates and manages orders based on a strategy taken as input.
*
* @author Raik Bieniek
* @param <C>
* The concrete type of {@link MarketData}s that are used as input.
*/
public class StrategyExpertAdvisor<C extends MarketData> implements ExpertAdvisor<C>, OrderEventListener {
private final TradingStrategy<C> strategy;
private final PendingOrderCreator creator;
private final PendingOrderManager orderManager;
private final TradeManager tradeManager;
private State currentState = State.TRY_CREATE;
private Optional<Order> currentOrder;
/**
* Initial the expert advisor.
*
* @param strategy
* A calculator thats values should be updated when new market data arrives.
* @param broker
* The broker that should be used to execute orders.
*/
public StrategyExpertAdvisor(final TradingStrategy<C> strategy, final Broker<BasicPendingOrder> broker) {
this.strategy = strategy;
this.creator = new PendingOrderCreator(strategy, broker);
this.orderManager = new PendingOrderManager(strategy, broker);
this.tradeManager = new TradeManager(strategy);
}
/**
* Initializes the expert advisor.
*
* @param strategy
* A calculator thats values should be updated when new market data arrives.
* @param creator
* Used to place pending orders.
* @param orderManager
* Used to manage opened pending orders.
* @param tradeManager
* Used to manage active trades.
*/
StrategyExpertAdvisor(final TradingStrategy<C> strategy, final PendingOrderCreator creator,
final PendingOrderManager orderManager, final TradeManager tradeManager) {
this.strategy = strategy;
this.creator = creator;
this.orderManager = orderManager;
this.tradeManager = tradeManager;
}
@Override
public void newData(final C candleStick) {
strategy.update(candleStick);
switch (currentState) {
case TRY_CREATE:
currentOrder = creator.checkMarketEntry(this);
if (currentOrder.isPresent()) {
currentState = State.MANAGE_ORDER;
}
break;
case MANAGE_ORDER:
currentOrder = orderManager.manageOrder(currentOrder.get(), this);
if (!currentOrder.isPresent()) {
currentState = State.TRY_CREATE;
}
break;
case MANAGE_TRADE:
currentOrder = tradeManager.manageTrade(currentOrder.get());
if (!currentOrder.isPresent()) {
currentState = State.TRY_CREATE;
}
break;
default:
throw new IllegalStateException("Unhandled state " + currentState);
}
}
@Override
public void orderRejected(final Failed failure) {
currentState = State.TRY_CREATE;
}
@Override
public void orderOpened(final Instant time, final Price price) {
currentState = State.MANAGE_TRADE;
}
@Override
public void orderClosed(final Instant time, final Price price) {
currentState = State.TRY_CREATE;
}
/**
* The current state the strategy is in.
*/
private enum State {
TRY_CREATE, MANAGE_ORDER, MANAGE_TRADE
}
}
| rbi/trading4j | core/src/main/java/de/voidnode/trading4j/strategyexpertadvisor/StrategyExpertAdvisor.java | Java | gpl-3.0 | 3,923 |
// Generated from /mnt/hdd/Programming/Projects/Groovy/intellidots/src/main/antlr/R.g4 by ANTLR 4.2.2
package ua.edu.hneu.ast.parsers;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class RParser extends Parser {
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__53=1, T__52=2, T__51=3, T__50=4, T__49=5, T__48=6, T__47=7, T__46=8,
T__45=9, T__44=10, T__43=11, T__42=12, T__41=13, T__40=14, T__39=15, T__38=16,
T__37=17, T__36=18, T__35=19, T__34=20, T__33=21, T__32=22, T__31=23,
T__30=24, T__29=25, T__28=26, T__27=27, T__26=28, T__25=29, T__24=30,
T__23=31, T__22=32, T__21=33, T__20=34, T__19=35, T__18=36, T__17=37,
T__16=38, T__15=39, T__14=40, T__13=41, T__12=42, T__11=43, T__10=44,
T__9=45, T__8=46, T__7=47, T__6=48, T__5=49, T__4=50, T__3=51, T__2=52,
T__1=53, T__0=54, HEX=55, INT=56, FLOAT=57, COMPLEX=58, STRING=59, ID=60,
USER_OP=61, NL=62, WS=63;
public static final String[] tokenNames = {
"<INVALID>", "'->>'", "'!='", "'while'", "'{'", "'&&'", "'::'", "'='",
"'for'", "'^'", "'$'", "'('", "'Inf'", "','", "'repeat'", "'NA'", "'<-'",
"'FALSE'", "':::'", "'>='", "'[['", "'<'", "']'", "'~'", "'@'", "'function'",
"'NULL'", "'+'", "'TRUE'", "'/'", "'||'", "';'", "'}'", "'if'", "'?'",
"':='", "'<='", "'break'", "'&'", "'*'", "'->'", "'...'", "'NaN'", "':'",
"'['", "'|'", "'=='", "'>'", "'!'", "'in'", "'else'", "'next'", "')'",
"'-'", "'<<-'", "HEX", "INT", "FLOAT", "COMPLEX", "STRING", "ID", "USER_OP",
"NL", "WS"
};
public static final int
RULE_prog = 0, RULE_expr = 1, RULE_exprlist = 2, RULE_formlist = 3, RULE_form = 4,
RULE_sublist = 5, RULE_sub = 6;
public static final String[] ruleNames = {
"prog", "expr", "exprlist", "formlist", "form", "sublist", "sub"
};
@Override
public String getGrammarFileName() { return "R.g4"; }
@Override
public String[] getTokenNames() { return tokenNames; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public RParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class ProgContext extends ParserRuleContext {
public List<TerminalNode> NL() { return getTokens(RParser.NL); }
public List<ExprContext> expr() {
return getRuleContexts(ExprContext.class);
}
public TerminalNode EOF() { return getToken(RParser.EOF, 0); }
public ExprContext expr(int i) {
return getRuleContext(ExprContext.class,i);
}
public TerminalNode NL(int i) {
return getToken(RParser.NL, i);
}
public ProgContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_prog; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterProg(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitProg(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitProg(this);
else return visitor.visitChildren(this);
}
}
public final ProgContext prog() throws RecognitionException {
ProgContext _localctx = new ProgContext(_ctx, getState());
enterRule(_localctx, 0, RULE_prog);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(20);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 3) | (1L << 4) | (1L << 8) | (1L << 11) | (1L << 12) | (1L << 14) | (1L << 15) | (1L << 17) | (1L << 23) | (1L << 25) | (1L << 26) | (1L << 27) | (1L << 28) | (1L << 33) | (1L << 34) | (1L << 37) | (1L << 42) | (1L << 48) | (1L << 51) | (1L << 53) | (1L << HEX) | (1L << INT) | (1L << FLOAT) | (1L << COMPLEX) | (1L << STRING) | (1L << ID) | (1L << NL))) != 0)) {
{
setState(18);
switch (_input.LA(1)) {
case 3:
case 4:
case 8:
case 11:
case 12:
case 14:
case 15:
case 17:
case 23:
case 25:
case 26:
case 27:
case 28:
case 33:
case 34:
case 37:
case 42:
case 48:
case 51:
case 53:
case HEX:
case INT:
case FLOAT:
case COMPLEX:
case STRING:
case ID:
{
setState(14); expr(0);
setState(15);
_la = _input.LA(1);
if ( !(_la==31 || _la==NL) ) {
_errHandler.recoverInline(this);
}
consume();
}
break;
case NL:
{
setState(17); match(NL);
}
break;
default:
throw new NoViableAltException(this);
}
}
setState(22);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(23); match(EOF);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExprContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(RParser.ID, 0); }
public TerminalNode HEX() { return getToken(RParser.HEX, 0); }
public List<ExprContext> expr() {
return getRuleContexts(ExprContext.class);
}
public TerminalNode USER_OP() { return getToken(RParser.USER_OP, 0); }
public ExprContext expr(int i) {
return getRuleContext(ExprContext.class,i);
}
public SublistContext sublist() {
return getRuleContext(SublistContext.class,0);
}
public FormlistContext formlist() {
return getRuleContext(FormlistContext.class,0);
}
public TerminalNode STRING() { return getToken(RParser.STRING, 0); }
public ExprlistContext exprlist() {
return getRuleContext(ExprlistContext.class,0);
}
public TerminalNode INT() { return getToken(RParser.INT, 0); }
public TerminalNode COMPLEX() { return getToken(RParser.COMPLEX, 0); }
public TerminalNode FLOAT() { return getToken(RParser.FLOAT, 0); }
public ExprContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expr; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterExpr(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitExpr(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitExpr(this);
else return visitor.visitChildren(this);
}
}
public final ExprContext expr() throws RecognitionException {
return expr(0);
}
private ExprContext expr(int _p) throws RecognitionException {
ParserRuleContext _parentctx = _ctx;
int _parentState = getState();
ExprContext _localctx = new ExprContext(_ctx, _parentState);
ExprContext _prevctx = _localctx;
int _startState = 2;
enterRecursionRule(_localctx, 2, RULE_expr, _p);
int _la;
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(93);
switch ( getInterpreter().adaptivePredict(_input,3,_ctx) ) {
case 1:
{
setState(26);
_la = _input.LA(1);
if ( !(_la==27 || _la==53) ) {
_errHandler.recoverInline(this);
}
consume();
setState(27); expr(36);
}
break;
case 2:
{
setState(28); match(48);
setState(29); expr(30);
}
break;
case 3:
{
setState(30); match(23);
setState(31); expr(27);
}
break;
case 4:
{
setState(32); match(25);
setState(33); match(11);
setState(35);
_la = _input.LA(1);
if (_la==41 || _la==ID) {
{
setState(34); formlist();
}
}
setState(37); match(52);
setState(38); expr(24);
}
break;
case 5:
{
setState(39); match(14);
setState(40); expr(17);
}
break;
case 6:
{
setState(41); match(34);
setState(42); expr(16);
}
break;
case 7:
{
setState(43); match(4);
setState(44); exprlist();
setState(45); match(32);
}
break;
case 8:
{
setState(47); match(33);
setState(48); match(11);
setState(49); expr(0);
setState(50); match(52);
setState(51); expr(0);
}
break;
case 9:
{
setState(53); match(33);
setState(54); match(11);
setState(55); expr(0);
setState(56); match(52);
setState(57); expr(0);
setState(58); match(50);
setState(59); expr(0);
}
break;
case 10:
{
setState(61); match(8);
setState(62); match(11);
setState(63); match(ID);
setState(64); match(49);
setState(65); expr(0);
setState(66); match(52);
setState(67); expr(0);
}
break;
case 11:
{
setState(69); match(3);
setState(70); match(11);
setState(71); expr(0);
setState(72); match(52);
setState(73); expr(0);
}
break;
case 12:
{
setState(75); match(51);
}
break;
case 13:
{
setState(76); match(37);
}
break;
case 14:
{
setState(77); match(11);
setState(78); expr(0);
setState(79); match(52);
}
break;
case 15:
{
setState(81); match(ID);
}
break;
case 16:
{
setState(82); match(STRING);
}
break;
case 17:
{
setState(83); match(HEX);
}
break;
case 18:
{
setState(84); match(INT);
}
break;
case 19:
{
setState(85); match(FLOAT);
}
break;
case 20:
{
setState(86); match(COMPLEX);
}
break;
case 21:
{
setState(87); match(26);
}
break;
case 22:
{
setState(88); match(15);
}
break;
case 23:
{
setState(89); match(12);
}
break;
case 24:
{
setState(90); match(42);
}
break;
case 25:
{
setState(91); match(28);
}
break;
case 26:
{
setState(92); match(17);
}
break;
}
_ctx.stop = _input.LT(-1);
setState(149);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,5,_ctx);
while ( _alt!=2 && _alt!=ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
if ( _parseListeners!=null ) triggerExitRuleEvent();
_prevctx = _localctx;
{
setState(147);
switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) {
case 1:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(95);
if (!(precpred(_ctx, 39))) throw new FailedPredicateException(this, "precpred(_ctx, 39)");
setState(96);
_la = _input.LA(1);
if ( !(_la==6 || _la==18) ) {
_errHandler.recoverInline(this);
}
consume();
setState(97); expr(40);
}
break;
case 2:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(98);
if (!(precpred(_ctx, 38))) throw new FailedPredicateException(this, "precpred(_ctx, 38)");
setState(99);
_la = _input.LA(1);
if ( !(_la==10 || _la==24) ) {
_errHandler.recoverInline(this);
}
consume();
setState(100); expr(39);
}
break;
case 3:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(101);
if (!(precpred(_ctx, 37))) throw new FailedPredicateException(this, "precpred(_ctx, 37)");
setState(102); match(9);
setState(103); expr(38);
}
break;
case 4:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(104);
if (!(precpred(_ctx, 35))) throw new FailedPredicateException(this, "precpred(_ctx, 35)");
setState(105); match(43);
setState(106); expr(36);
}
break;
case 5:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(107);
if (!(precpred(_ctx, 34))) throw new FailedPredicateException(this, "precpred(_ctx, 34)");
setState(108); match(USER_OP);
setState(109); expr(35);
}
break;
case 6:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(110);
if (!(precpred(_ctx, 33))) throw new FailedPredicateException(this, "precpred(_ctx, 33)");
setState(111);
_la = _input.LA(1);
if ( !(_la==29 || _la==39) ) {
_errHandler.recoverInline(this);
}
consume();
setState(112); expr(34);
}
break;
case 7:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(113);
if (!(precpred(_ctx, 32))) throw new FailedPredicateException(this, "precpred(_ctx, 32)");
setState(114);
_la = _input.LA(1);
if ( !(_la==27 || _la==53) ) {
_errHandler.recoverInline(this);
}
consume();
setState(115); expr(33);
}
break;
case 8:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(116);
if (!(precpred(_ctx, 31))) throw new FailedPredicateException(this, "precpred(_ctx, 31)");
setState(117);
_la = _input.LA(1);
if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 2) | (1L << 19) | (1L << 21) | (1L << 36) | (1L << 46) | (1L << 47))) != 0)) ) {
_errHandler.recoverInline(this);
}
consume();
setState(118); expr(32);
}
break;
case 9:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(119);
if (!(precpred(_ctx, 29))) throw new FailedPredicateException(this, "precpred(_ctx, 29)");
setState(120);
_la = _input.LA(1);
if ( !(_la==5 || _la==38) ) {
_errHandler.recoverInline(this);
}
consume();
setState(121); expr(30);
}
break;
case 10:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(122);
if (!(precpred(_ctx, 28))) throw new FailedPredicateException(this, "precpred(_ctx, 28)");
setState(123);
_la = _input.LA(1);
if ( !(_la==30 || _la==45) ) {
_errHandler.recoverInline(this);
}
consume();
setState(124); expr(29);
}
break;
case 11:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(125);
if (!(precpred(_ctx, 26))) throw new FailedPredicateException(this, "precpred(_ctx, 26)");
setState(126); match(23);
setState(127); expr(27);
}
break;
case 12:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(128);
if (!(precpred(_ctx, 25))) throw new FailedPredicateException(this, "precpred(_ctx, 25)");
setState(129);
_la = _input.LA(1);
if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 1) | (1L << 7) | (1L << 16) | (1L << 35) | (1L << 40) | (1L << 54))) != 0)) ) {
_errHandler.recoverInline(this);
}
consume();
setState(130); expr(26);
}
break;
case 13:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(131);
if (!(precpred(_ctx, 41))) throw new FailedPredicateException(this, "precpred(_ctx, 41)");
setState(132); match(20);
setState(133); sublist();
setState(134); match(22);
setState(135); match(22);
}
break;
case 14:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(137);
if (!(precpred(_ctx, 40))) throw new FailedPredicateException(this, "precpred(_ctx, 40)");
setState(138); match(44);
setState(139); sublist();
setState(140); match(22);
}
break;
case 15:
{
_localctx = new ExprContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expr);
setState(142);
if (!(precpred(_ctx, 23))) throw new FailedPredicateException(this, "precpred(_ctx, 23)");
setState(143); match(11);
setState(144); sublist();
setState(145); match(52);
}
break;
}
}
}
setState(151);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,5,_ctx);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
unrollRecursionContexts(_parentctx);
}
return _localctx;
}
public static class ExprlistContext extends ParserRuleContext {
public List<TerminalNode> NL() { return getTokens(RParser.NL); }
public List<ExprContext> expr() {
return getRuleContexts(ExprContext.class);
}
public ExprContext expr(int i) {
return getRuleContext(ExprContext.class,i);
}
public TerminalNode NL(int i) {
return getToken(RParser.NL, i);
}
public ExprlistContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_exprlist; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterExprlist(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitExprlist(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitExprlist(this);
else return visitor.visitChildren(this);
}
}
public final ExprlistContext exprlist() throws RecognitionException {
ExprlistContext _localctx = new ExprlistContext(_ctx, getState());
enterRule(_localctx, 4, RULE_exprlist);
int _la;
try {
setState(163);
switch (_input.LA(1)) {
case 3:
case 4:
case 8:
case 11:
case 12:
case 14:
case 15:
case 17:
case 23:
case 25:
case 26:
case 27:
case 28:
case 33:
case 34:
case 37:
case 42:
case 48:
case 51:
case 53:
case HEX:
case INT:
case FLOAT:
case COMPLEX:
case STRING:
case ID:
enterOuterAlt(_localctx, 1);
{
setState(152); expr(0);
setState(159);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==31 || _la==NL) {
{
{
setState(153);
_la = _input.LA(1);
if ( !(_la==31 || _la==NL) ) {
_errHandler.recoverInline(this);
}
consume();
setState(155);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 3) | (1L << 4) | (1L << 8) | (1L << 11) | (1L << 12) | (1L << 14) | (1L << 15) | (1L << 17) | (1L << 23) | (1L << 25) | (1L << 26) | (1L << 27) | (1L << 28) | (1L << 33) | (1L << 34) | (1L << 37) | (1L << 42) | (1L << 48) | (1L << 51) | (1L << 53) | (1L << HEX) | (1L << INT) | (1L << FLOAT) | (1L << COMPLEX) | (1L << STRING) | (1L << ID))) != 0)) {
{
setState(154); expr(0);
}
}
}
}
setState(161);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
break;
case 32:
enterOuterAlt(_localctx, 2);
{
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FormlistContext extends ParserRuleContext {
public FormContext form(int i) {
return getRuleContext(FormContext.class,i);
}
public List<FormContext> form() {
return getRuleContexts(FormContext.class);
}
public FormlistContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_formlist; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterFormlist(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitFormlist(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitFormlist(this);
else return visitor.visitChildren(this);
}
}
public final FormlistContext formlist() throws RecognitionException {
FormlistContext _localctx = new FormlistContext(_ctx, getState());
enterRule(_localctx, 6, RULE_formlist);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(165); form();
setState(170);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==13) {
{
{
setState(166); match(13);
setState(167); form();
}
}
setState(172);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FormContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(RParser.ID, 0); }
public ExprContext expr() {
return getRuleContext(ExprContext.class,0);
}
public FormContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_form; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterForm(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitForm(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitForm(this);
else return visitor.visitChildren(this);
}
}
public final FormContext form() throws RecognitionException {
FormContext _localctx = new FormContext(_ctx, getState());
enterRule(_localctx, 8, RULE_form);
try {
setState(178);
switch ( getInterpreter().adaptivePredict(_input,10,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(173); match(ID);
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(174); match(ID);
setState(175); match(7);
setState(176); expr(0);
}
break;
case 3:
enterOuterAlt(_localctx, 3);
{
setState(177); match(41);
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SublistContext extends ParserRuleContext {
public SubContext sub(int i) {
return getRuleContext(SubContext.class,i);
}
public List<SubContext> sub() {
return getRuleContexts(SubContext.class);
}
public SublistContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_sublist; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterSublist(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitSublist(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitSublist(this);
else return visitor.visitChildren(this);
}
}
public final SublistContext sublist() throws RecognitionException {
SublistContext _localctx = new SublistContext(_ctx, getState());
enterRule(_localctx, 10, RULE_sublist);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(180); sub();
setState(185);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==13) {
{
{
setState(181); match(13);
setState(182); sub();
}
}
setState(187);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class SubContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(RParser.ID, 0); }
public ExprContext expr() {
return getRuleContext(ExprContext.class,0);
}
public TerminalNode STRING() { return getToken(RParser.STRING, 0); }
public SubContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_sub; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).enterSub(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof RListener ) ((RListener)listener).exitSub(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof RVisitor ) return ((RVisitor<? extends T>)visitor).visitSub(this);
else return visitor.visitChildren(this);
}
}
public final SubContext sub() throws RecognitionException {
SubContext _localctx = new SubContext(_ctx, getState());
enterRule(_localctx, 12, RULE_sub);
try {
setState(206);
switch ( getInterpreter().adaptivePredict(_input,12,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(188); expr(0);
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(189); match(ID);
setState(190); match(7);
}
break;
case 3:
enterOuterAlt(_localctx, 3);
{
setState(191); match(ID);
setState(192); match(7);
setState(193); expr(0);
}
break;
case 4:
enterOuterAlt(_localctx, 4);
{
setState(194); match(STRING);
setState(195); match(7);
}
break;
case 5:
enterOuterAlt(_localctx, 5);
{
setState(196); match(STRING);
setState(197); match(7);
setState(198); expr(0);
}
break;
case 6:
enterOuterAlt(_localctx, 6);
{
setState(199); match(26);
setState(200); match(7);
}
break;
case 7:
enterOuterAlt(_localctx, 7);
{
setState(201); match(26);
setState(202); match(7);
setState(203); expr(0);
}
break;
case 8:
enterOuterAlt(_localctx, 8);
{
setState(204); match(41);
}
break;
case 9:
enterOuterAlt(_localctx, 9);
{
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {
switch (ruleIndex) {
case 1: return expr_sempred((ExprContext)_localctx, predIndex);
}
return true;
}
private boolean expr_sempred(ExprContext _localctx, int predIndex) {
switch (predIndex) {
case 0: return precpred(_ctx, 39);
case 1: return precpred(_ctx, 38);
case 2: return precpred(_ctx, 37);
case 3: return precpred(_ctx, 35);
case 4: return precpred(_ctx, 34);
case 5: return precpred(_ctx, 33);
case 6: return precpred(_ctx, 32);
case 7: return precpred(_ctx, 31);
case 8: return precpred(_ctx, 29);
case 9: return precpred(_ctx, 28);
case 10: return precpred(_ctx, 26);
case 11: return precpred(_ctx, 25);
case 12: return precpred(_ctx, 41);
case 13: return precpred(_ctx, 40);
case 14: return precpred(_ctx, 23);
}
return true;
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3A\u00d3\4\2\t\2\4"+
"\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\3\2\3\2\3\2\3\2\7\2\25"+
"\n\2\f\2\16\2\30\13\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\5\3&\n\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\5\3`\n\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\7\3\u0096\n\3\f\3\16\3\u0099\13\3\3\4"+
"\3\4\3\4\5\4\u009e\n\4\7\4\u00a0\n\4\f\4\16\4\u00a3\13\4\3\4\5\4\u00a6"+
"\n\4\3\5\3\5\3\5\7\5\u00ab\n\5\f\5\16\5\u00ae\13\5\3\6\3\6\3\6\3\6\3\6"+
"\5\6\u00b5\n\6\3\7\3\7\3\7\7\7\u00ba\n\7\f\7\16\7\u00bd\13\7\3\b\3\b\3"+
"\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\5\b\u00d1"+
"\n\b\3\b\2\3\4\t\2\4\6\b\n\f\16\2\13\4\2!!@@\4\2\35\35\67\67\4\2\b\b\24"+
"\24\4\2\f\f\32\32\4\2\37\37))\7\2\4\4\25\25\27\27&&\60\61\4\2\7\7((\4"+
"\2 //\b\2\3\3\t\t\22\22%%**88\u0105\2\26\3\2\2\2\4_\3\2\2\2\6\u00a5\3"+
"\2\2\2\b\u00a7\3\2\2\2\n\u00b4\3\2\2\2\f\u00b6\3\2\2\2\16\u00d0\3\2\2"+
"\2\20\21\5\4\3\2\21\22\t\2\2\2\22\25\3\2\2\2\23\25\7@\2\2\24\20\3\2\2"+
"\2\24\23\3\2\2\2\25\30\3\2\2\2\26\24\3\2\2\2\26\27\3\2\2\2\27\31\3\2\2"+
"\2\30\26\3\2\2\2\31\32\7\2\2\3\32\3\3\2\2\2\33\34\b\3\1\2\34\35\t\3\2"+
"\2\35`\5\4\3&\36\37\7\62\2\2\37`\5\4\3 !\7\31\2\2!`\5\4\3\35\"#\7\33"+
"\2\2#%\7\r\2\2$&\5\b\5\2%$\3\2\2\2%&\3\2\2\2&\'\3\2\2\2\'(\7\66\2\2(`"+
"\5\4\3\32)*\7\20\2\2*`\5\4\3\23+,\7$\2\2,`\5\4\3\22-.\7\6\2\2./\5\6\4"+
"\2/\60\7\"\2\2\60`\3\2\2\2\61\62\7#\2\2\62\63\7\r\2\2\63\64\5\4\3\2\64"+
"\65\7\66\2\2\65\66\5\4\3\2\66`\3\2\2\2\678\7#\2\289\7\r\2\29:\5\4\3\2"+
":;\7\66\2\2;<\5\4\3\2<=\7\64\2\2=>\5\4\3\2>`\3\2\2\2?@\7\n\2\2@A\7\r\2"+
"\2AB\7>\2\2BC\7\63\2\2CD\5\4\3\2DE\7\66\2\2EF\5\4\3\2F`\3\2\2\2GH\7\5"+
"\2\2HI\7\r\2\2IJ\5\4\3\2JK\7\66\2\2KL\5\4\3\2L`\3\2\2\2M`\7\65\2\2N`\7"+
"\'\2\2OP\7\r\2\2PQ\5\4\3\2QR\7\66\2\2R`\3\2\2\2S`\7>\2\2T`\7=\2\2U`\7"+
"9\2\2V`\7:\2\2W`\7;\2\2X`\7<\2\2Y`\7\34\2\2Z`\7\21\2\2[`\7\16\2\2\\`\7"+
",\2\2]`\7\36\2\2^`\7\23\2\2_\33\3\2\2\2_\36\3\2\2\2_ \3\2\2\2_\"\3\2\2"+
"\2_)\3\2\2\2_+\3\2\2\2_-\3\2\2\2_\61\3\2\2\2_\67\3\2\2\2_?\3\2\2\2_G\3"+
"\2\2\2_M\3\2\2\2_N\3\2\2\2_O\3\2\2\2_S\3\2\2\2_T\3\2\2\2_U\3\2\2\2_V\3"+
"\2\2\2_W\3\2\2\2_X\3\2\2\2_Y\3\2\2\2_Z\3\2\2\2_[\3\2\2\2_\\\3\2\2\2_]"+
"\3\2\2\2_^\3\2\2\2`\u0097\3\2\2\2ab\f)\2\2bc\t\4\2\2c\u0096\5\4\3*de\f"+
"(\2\2ef\t\5\2\2f\u0096\5\4\3)gh\f\'\2\2hi\7\13\2\2i\u0096\5\4\3(jk\f%"+
"\2\2kl\7-\2\2l\u0096\5\4\3&mn\f$\2\2no\7?\2\2o\u0096\5\4\3%pq\f#\2\2q"+
"r\t\6\2\2r\u0096\5\4\3$st\f\"\2\2tu\t\3\2\2u\u0096\5\4\3#vw\f!\2\2wx\t"+
"\7\2\2x\u0096\5\4\3\"yz\f\37\2\2z{\t\b\2\2{\u0096\5\4\3 |}\f\36\2\2}~"+
"\t\t\2\2~\u0096\5\4\3\37\177\u0080\f\34\2\2\u0080\u0081\7\31\2\2\u0081"+
"\u0096\5\4\3\35\u0082\u0083\f\33\2\2\u0083\u0084\t\n\2\2\u0084\u0096\5"+
"\4\3\34\u0085\u0086\f+\2\2\u0086\u0087\7\26\2\2\u0087\u0088\5\f\7\2\u0088"+
"\u0089\7\30\2\2\u0089\u008a\7\30\2\2\u008a\u0096\3\2\2\2\u008b\u008c\f"+
"*\2\2\u008c\u008d\7.\2\2\u008d\u008e\5\f\7\2\u008e\u008f\7\30\2\2\u008f"+
"\u0096\3\2\2\2\u0090\u0091\f\31\2\2\u0091\u0092\7\r\2\2\u0092\u0093\5"+
"\f\7\2\u0093\u0094\7\66\2\2\u0094\u0096\3\2\2\2\u0095a\3\2\2\2\u0095d"+
"\3\2\2\2\u0095g\3\2\2\2\u0095j\3\2\2\2\u0095m\3\2\2\2\u0095p\3\2\2\2\u0095"+
"s\3\2\2\2\u0095v\3\2\2\2\u0095y\3\2\2\2\u0095|\3\2\2\2\u0095\177\3\2\2"+
"\2\u0095\u0082\3\2\2\2\u0095\u0085\3\2\2\2\u0095\u008b\3\2\2\2\u0095\u0090"+
"\3\2\2\2\u0096\u0099\3\2\2\2\u0097\u0095\3\2\2\2\u0097\u0098\3\2\2\2\u0098"+
"\5\3\2\2\2\u0099\u0097\3\2\2\2\u009a\u00a1\5\4\3\2\u009b\u009d\t\2\2\2"+
"\u009c\u009e\5\4\3\2\u009d\u009c\3\2\2\2\u009d\u009e\3\2\2\2\u009e\u00a0"+
"\3\2\2\2\u009f\u009b\3\2\2\2\u00a0\u00a3\3\2\2\2\u00a1\u009f\3\2\2\2\u00a1"+
"\u00a2\3\2\2\2\u00a2\u00a6\3\2\2\2\u00a3\u00a1\3\2\2\2\u00a4\u00a6\3\2"+
"\2\2\u00a5\u009a\3\2\2\2\u00a5\u00a4\3\2\2\2\u00a6\7\3\2\2\2\u00a7\u00ac"+
"\5\n\6\2\u00a8\u00a9\7\17\2\2\u00a9\u00ab\5\n\6\2\u00aa\u00a8\3\2\2\2"+
"\u00ab\u00ae\3\2\2\2\u00ac\u00aa\3\2\2\2\u00ac\u00ad\3\2\2\2\u00ad\t\3"+
"\2\2\2\u00ae\u00ac\3\2\2\2\u00af\u00b5\7>\2\2\u00b0\u00b1\7>\2\2\u00b1"+
"\u00b2\7\t\2\2\u00b2\u00b5\5\4\3\2\u00b3\u00b5\7+\2\2\u00b4\u00af\3\2"+
"\2\2\u00b4\u00b0\3\2\2\2\u00b4\u00b3\3\2\2\2\u00b5\13\3\2\2\2\u00b6\u00bb"+
"\5\16\b\2\u00b7\u00b8\7\17\2\2\u00b8\u00ba\5\16\b\2\u00b9\u00b7\3\2\2"+
"\2\u00ba\u00bd\3\2\2\2\u00bb\u00b9\3\2\2\2\u00bb\u00bc\3\2\2\2\u00bc\r"+
"\3\2\2\2\u00bd\u00bb\3\2\2\2\u00be\u00d1\5\4\3\2\u00bf\u00c0\7>\2\2\u00c0"+
"\u00d1\7\t\2\2\u00c1\u00c2\7>\2\2\u00c2\u00c3\7\t\2\2\u00c3\u00d1\5\4"+
"\3\2\u00c4\u00c5\7=\2\2\u00c5\u00d1\7\t\2\2\u00c6\u00c7\7=\2\2\u00c7\u00c8"+
"\7\t\2\2\u00c8\u00d1\5\4\3\2\u00c9\u00ca\7\34\2\2\u00ca\u00d1\7\t\2\2"+
"\u00cb\u00cc\7\34\2\2\u00cc\u00cd\7\t\2\2\u00cd\u00d1\5\4\3\2\u00ce\u00d1"+
"\7+\2\2\u00cf\u00d1\3\2\2\2\u00d0\u00be\3\2\2\2\u00d0\u00bf\3\2\2\2\u00d0"+
"\u00c1\3\2\2\2\u00d0\u00c4\3\2\2\2\u00d0\u00c6\3\2\2\2\u00d0\u00c9\3\2"+
"\2\2\u00d0\u00cb\3\2\2\2\u00d0\u00ce\3\2\2\2\u00d0\u00cf\3\2\2\2\u00d1"+
"\17\3\2\2\2\17\24\26%_\u0095\u0097\u009d\u00a1\u00a5\u00ac\u00b4\u00bb"+
"\u00d0";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | IsThisThePayneResidence/intellidots | src/main/java/ua/edu/hneu/ast/parsers/RParser.java | Java | gpl-3.0 | 34,879 |
/**
* Class: Webgl
* Description: Her goes description
*/
import {m, utils} from '../../js/main';
import * as THREE from './three.min.js'
import dat from './dat.gui.min.js'
import Detector from './Detector.js'
// GLOBAL
var EightBitMode = false;
export default class Webgl {
/**
* @param {number} param this is param.
* @return {number} this is return.
*/
constructor(config) { // put in defaults here
//defaults
this.config = $.extend({
el:'#snow'
},config);
this.$el = $(this.config.el);
this.renderer,
this.scene,
this.camera,
this.cameraRadius = 50.0,
this.cameraTarget,
this.cameraX = 0,
this.cameraY = 0,
this.cameraZ = this.cameraRadius,
this.particleSystem,
this.particleSystemHeight = 100.0,
this.wind = 2.5,
this.clock,
this.controls,
this.parameters,
this.onParametersUpdate,
this.texture,
this.loader;
this.init();
}
init() {
var self = this;
this.renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
this.renderer.setSize( window.innerWidth, window.innerHeight );
this.renderer.setClearColor( 0x000000, 0 );
this.renderer.sortObjects = false;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
this.cameraTarget = new THREE.Vector3( 0, 0, 0 );
this.loader = new THREE.TextureLoader();
this.loader.crossOrigin = '';
this.texture = this.loader.load(
'../assets/textures/snowflake.png',
// Resource is loaded
function ( texture ) {
// create the particles with the texture
self.createParticles( texture );
},
// Download progress
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// Download errors
function ( xhr ) {
console.log( 'An error happened during the loading of the texture ' );
}
);
}
createParticles( tex ) {
var numParticles = 2000,
width = 70,
height = this.particleSystemHeight,
depth = 80,
parameters = {
// color: 0xffffff,
color: 0xffffff,
height: this.particleSystemHeight,
radiusX: this.wind,
radiusZ: 2.5,
size: 100,
scale: 4.0,
opacity: 1,
speedH: 1.0,
speedV: 1.0
},
systemGeometry = new THREE.Geometry(),
systemMaterial = new THREE.ShaderMaterial({
uniforms: {
color: { type: 'c', value: new THREE.Color( parameters.color ) },
height: { type: 'f', value: parameters.height },
elapsedTime: { type: 'f', value: 0 },
radiusX: { type: 'f', value: parameters.radiusX },
radiusZ: { type: 'f', value: parameters.radiusZ },
size: { type: 'f', value: parameters.size },
scale: { type: 'f', value: parameters.scale },
opacity: { type: 'f', value: parameters.opacity },
texture: { type: 't', value: tex },
speedH: { type: 'f', value: parameters.speedH },
speedV: { type: 'f', value: parameters.speedV }
},
vertexShader: document.getElementById( 'snow_vs' ).textContent,
fragmentShader: document.getElementById( 'snow_fs' ).textContent,
blending: THREE.AdditiveBlending,
transparent: true,
depthTest: false
});
// Less particules for mobile
if( this.isMobileDevice ) {
numParticles = 200;
}
for( var i = 0; i < numParticles; i++ ) {
var vertex = new THREE.Vector3(
this.rand( width ),
Math.random() * height,
this.rand( depth )
);
systemGeometry.vertices.push( vertex );
}
this.particleSystem = new THREE.Points( systemGeometry, systemMaterial );
this.particleSystem.position.y = -height/2;
this.scene.add( this.particleSystem );
this.clock = new THREE.Clock();
document.getElementById("snow").appendChild( this.renderer.domElement );
this.bindEvents();
}
// Events --------------------------------------------------------------------------
bindEvents() {
// bind your events here.
var self = this;
document.addEventListener( 'mousemove', function( e ) {
var mouseX = e.clientX,
mouseY = e.clientY,
width = window.innerWidth,
halfWidth = width >> 1,
height = window.innerHeight,
halfHeight = height >> 1;
var targetX = self.cameraRadius * ( mouseX - halfWidth ) / halfWidth;
self.cameraX = targetX / 10;
//self.cameraY = self.cameraRadius * ( mouseY - halfHeight ) / halfHeight;
}, false );
// Activat e8 bit mode button
document.getElementById("eightbitmodebutton").addEventListener( 'click', this.activateEightBitMode, false );
// handle resize
this.handleWindowResize();
// Animate snow
this.animate();
}
activateEightBitMode() {
var self = this;
if( !EightBitMode ){
EightBitMode = true;
$('#activate-text').html("DEACTIVATE</br>X-MAS MODE");
emitter = new EightBit_Emitter().init();
} else {
EightBitMode = false;
$('#activate-text').html("ACTIVATE</br>X-MAS MODE");
$('#eightbits').empty();
}
}
handleWindowResize() {
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
}
animate() {
requestAnimationFrame( this.animate.bind(this) );
if( EightBitMode ) {
var delta = this.clock.getDelta(), elapsedTime = this.clock.getElapsedTime();
this.particleSystem.material.uniforms.elapsedTime.value = elapsedTime * 10;
this.camera.position.set( this.cameraX, this.cameraY, this.cameraZ );
this.camera.lookAt( this.cameraTarget );
this.renderer.clear();
this.renderer.render( this.scene, this.camera );
} else {
this.renderer.clear();
}
}
// Getters / Setters --------------------------------------------------------------------------
addWind() {
this.particleSystem.material.uniforms.radiusX.value = this.wind;
m.TweenMax.from(
this.particleSystem.material.uniforms.radiusX,
3,
{
value:30,
ease:Quad.easeOut
}
);
}
// Utils --------------------------------------------------------------------------
rand( v ) {
return (v * (Math.random() - 0.5));
}
// easy mobile device detection
isMobileDevice() {
if ( navigator === undefined || navigator.userAgent === undefined ) {
return true;
}
var s = navigator.userAgent;
if ( s.match( /iPhone/i )
|| s.match( /iPod/i )
|| s.match( /webOS/i )
|| s.match( /BlackBerry/i )
|| ( s.match( /Windows/i ) && s.match( /Phone/i ) )
|| ( s.match( /Android/i ) && s.match( /Mobile/i ) ) ) {
return true;
}
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
// 8 Bit Xmas Mode
///////////////////////////////////////////////////////////////////////////////
var indexes = 2500;
var prefix = '/assets/textures/';
var bitmaps = [
{ type:'moose', img:'moose.gif', w:64, h:64 },
{ type:'santa', img:'santa.gif', w:100, h:100 },
{ type:'mistletoe', img:'mistletoe1.png', w:109, h:99 },
{ type:'mistletoe', img:'mistletoe2.png', w:123, h:114 },
{ type:'gift', img:'kdo1.png', w:64, h:67 },
{ type:'gift', img:'kdo2.png', w:64, h:67 },
{ type:'gift', img:'kdo3.png', w:64, h:67 },
{ type:'mistletoe', img:'mistletoe1.png', w:109, h:99 },
{ type:'mistletoe', img:'mistletoe2.png', w:123, h:114 },
];
var emitter;
class EightBit_Emitter {
constructor(
$selector = '#eightbits',
maxParticles=10
) {
this.$emitter = document.querySelector($selector);
this.maxParticles = maxParticles;
}
init() {
var self = this;
this.newParticle();
}
newParticle() {
var self = this;
var timing = Math.floor( Math.random() * 5000 + 1000 );
// Element caracteristics
var pRand = Math.floor( Math.random() * bitmaps.length );
var life = Math.floor( Math.random() * 10 + 15 );
var particle = new EightBit_Particle( pRand, life );
// check if we are still on EightBit mode
if( EightBitMode ) {
// Wait if too many guys on the floor
if( $('#eightbits .particle').length <= this.maxParticles ) {
setTimeout( self.newParticle.bind( this ), timing );
}
}
}
handleWindowResize(){
var wWidth = window.innerWidth;
var wHeight = window.innerHeight;
}
}
class EightBit_Particle {
constructor( idx, life ) {
this.idx = idx;
this.life = life;
this._create();
}
_create() {
var self = this;
var wWidth = window.innerWidth;
var wHeight = window.innerHeight;
var pic = '<div class="particle" id="p-' + indexes + '"><img src="' + prefix + bitmaps[this.idx].img + '"></div>';
$('#eightbits').append( pic );
var part = $('#p-' + indexes);
indexes++;
var tweenObject;
if( this.idx <= 1 ) { // Moose & Santa
part.css({
top: ( wHeight - bitmaps[this.idx].h ) + "px",
left: ( wWidth + 100 ) + "px",
'z-index':indexes
});
tweenObject = {
left:-100,
// easing:Linear.easeNone,
onComplete:function(){
$(part).remove();
},
onCompleteParams:[part]
}
} else if ( this.idx > 1 ) { // falling stuff
part.css({
top: "-100px",
left: Math.floor( Math.random() * ( wWidth - 100 ) + 100 ) + "px",
'z-index':indexes
});
tweenObject = {
top:wHeight + 100,
// easing:Linear.easeNone,
// rotation:Math.floor( Math.random() * 90 ),
onComplete:function(){
$(part).remove();
},
onCompleteParams:[part]
}
}
m.TweenMax.to(
part,
self.life,
tweenObject
);
}
}
| GreatWorksCopenhagen/gw-xmascard | src/modules/webgl/webgl.js | JavaScript | gpl-3.0 | 10,063 |
#
# Copyright 2009-2010 Goran Sterjov
# This file is part of Myelin.
#
# Myelin 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.
#
# Myelin 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 Myelin. If not, see <http://www.gnu.org/licenses/>.
#
import ctypes
from type import Type
# get library
import myelin.library
_lib = myelin.library.get_library()
_types = []
def add_type (klass):
_types.append (klass)
def get_type (type):
for klass in _types:
if klass._class.get_type().get_atom() == type.get_atom():
return klass
return None
def get_types ():
return _types
class Value (object):
def __init__ (self, ptr = None):
if ptr is None:
ptr = _lib.myelin_value_new ()
self._ptr = ptr
def __del__ (self):
_lib.myelin_value_unref (self)
def __repr__ (self):
return ("<%s.%s object at %#x with an instance of type %s at %#x>" %
(self.__module__,
self.__class__.__name__,
id(self),
self.get_type().get_name(),
self.as_pointer()))
@classmethod
def from_pointer (cls, ptr):
if ptr is None:
raise ValueError ("Value pointer cannot be 'None'")
instance = cls (ptr)
_lib.myelin_value_ref (instance)
return instance
def from_param (self):
return self._ptr
def get (self):
# empty value
if self.is_empty(): return None
# get value type
type = self.get_type()
atom = type.get_atom()
# convert value types
if not type.is_pointer() and not type.is_reference():
# fundamental types
if atom == Type.type_bool (): return self.get_bool ()
elif atom == Type.type_char (): return self.get_char ()
elif atom == Type.type_uchar (): return self.get_uchar ()
elif atom == Type.type_int (): return self.get_int ()
elif atom == Type.type_uint (): return self.get_uint ()
elif atom == Type.type_long (): return self.get_long ()
elif atom == Type.type_ulong (): return self.get_ulong ()
elif atom == Type.type_int64 (): return self.get_int64 ()
elif atom == Type.type_uint64 (): return self.get_uint64 ()
elif atom == Type.type_float (): return self.get_float ()
elif atom == Type.type_double (): return self.get_double ()
# elif atom == Type.type_string (): return self.get_string ()
# convert value to meta class instance
class_type = get_type (type)
if class_type is not None:
return class_type (instance = self)
# dont know how to convert value so just return it as is
else:
return self
def set (self, value, atom = None):
from myelin.module import MetaObject
# convert python types
if type(value) is bool: self.set_bool (value)
# set the right integer type
elif type(value) is int or type(value) is long:
if atom is not None:
if atom == Type.type_char(): self.set_char (value)
elif atom == Type.type_uchar(): self.set_uchar (value)
elif atom == Type.type_int(): self.set_int (value)
elif atom == Type.type_uint(): self.set_uint (value)
elif atom == Type.type_long(): self.set_long (value)
elif atom == Type.type_ulong(): self.set_ulong (value)
# for long only
elif type(value) is long:
if atom == Type.type_int64(): self.set_int64 (value)
elif atom == Type.type_uint64(): self.set_uint64 (value)
else:
if type(value) is int: self.set_long (value)
else: self.set_int64 (value)
elif type(value) is float:
if atom is not None:
if atom == Type.type_float(): self.set_float (value)
elif atom == Type.type_double(): self.set_double (value)
else: self.set_double (value)
elif type(value) is str: self.set_string (value)
# set meta object instance
elif isinstance(value, MetaObject):
val = value._object.get_instance()
self.set_pointer (val.get_type(), val.as_pointer())
else:
raise TypeError ("Cannot determine an equivalent type for the " \
"value type '%s'. Conversion failed." %
type(value))
def get_type (self):
type = _lib.myelin_value_get_type (self)
return Type.from_pointer (type)
def is_empty (self):
return _lib.myelin_value_is_empty (self)
def clear (self):
_lib.myelin_value_clear (self)
def get_bool (self):
return _lib.myelin_value_get_bool (self)
def set_bool (self, value):
_lib.myelin_value_set_bool (self, value)
def get_char (self):
return _lib.myelin_value_get_char (self)
def set_char (self, value):
_lib.myelin_value_set_char (self, value)
def get_uchar (self):
return _lib.myelin_value_get_uchar (self)
def set_uchar (self, value):
_lib.myelin_value_set_uchar (self, value)
def get_int (self):
return _lib.myelin_value_get_int (self)
def set_int (self, value):
_lib.myelin_value_set_int (self, value)
def get_uint (self):
return _lib.myelin_value_get_uint (self)
def set_uint (self, value):
_lib.myelin_value_set_uint (self, value)
def get_long (self):
return _lib.myelin_value_get_long (self)
def set_long (self, value):
_lib.myelin_value_set_long (self, value)
def get_ulong (self):
return _lib.myelin_value_get_ulong (self)
def set_ulong (self, value):
_lib.myelin_value_set_ulong (self, value)
def get_int64 (self):
return _lib.myelin_value_get_int64 (self)
def set_int64 (self, value):
_lib.myelin_value_set_int64 (self, value)
def get_uint64 (self):
return _lib.myelin_value_get_uint64 (self)
def set_uint64 (self, value):
_lib.myelin_value_set_uint64 (self, value)
def get_float (self):
return _lib.myelin_value_get_float (self)
def set_float (self, value):
_lib.myelin_value_set_float (self, value)
def get_double (self):
return _lib.myelin_value_get_double (self)
def set_double (self, value):
_lib.myelin_value_set_double (self, value)
def get_string (self):
return _lib.myelin_value_get_string (self)
def set_string (self, value):
_lib.myelin_value_set_string (self, value)
def as_pointer (self):
return _lib.myelin_value_as_pointer (self)
def set_pointer (self, type, pointer):
_lib.myelin_value_set_pointer (self, type, pointer)
###############################################
# Prototypes #
###############################################
_lib.myelin_value_new.argtypes = None
_lib.myelin_value_new.restype = ctypes.c_void_p
_lib.myelin_value_ref.argtypes = [Value]
_lib.myelin_value_ref.restype = ctypes.c_void_p
_lib.myelin_value_unref.argtypes = [Value]
_lib.myelin_value_unref.restype = None
_lib.myelin_value_get_type.argtypes = [Value]
_lib.myelin_value_get_type.restype = ctypes.c_void_p
_lib.myelin_value_is_empty.argtypes = [Value]
_lib.myelin_value_is_empty.restype = ctypes.c_bool
_lib.myelin_value_clear.argtypes = [Value]
_lib.myelin_value_clear.restype = None
# boolean
_lib.myelin_value_get_bool.argtypes = [Value]
_lib.myelin_value_get_bool.restype = ctypes.c_bool
_lib.myelin_value_set_bool.argtypes = [Value, ctypes.c_bool]
_lib.myelin_value_set_bool.restype = None
# char
_lib.myelin_value_get_char.argtypes = [Value]
_lib.myelin_value_get_char.restype = ctypes.c_char
_lib.myelin_value_set_char.argtypes = [Value, ctypes.c_char]
_lib.myelin_value_set_char.restype = None
# uchar
_lib.myelin_value_get_uchar.argtypes = [Value]
_lib.myelin_value_get_uchar.restype = ctypes.c_ubyte
_lib.myelin_value_set_uchar.argtypes = [Value, ctypes.c_ubyte]
_lib.myelin_value_set_uchar.restype = None
# integer
_lib.myelin_value_get_int.argtypes = [Value]
_lib.myelin_value_get_int.restype = ctypes.c_int
_lib.myelin_value_set_int.argtypes = [Value, ctypes.c_int]
_lib.myelin_value_set_int.restype = None
# uint
_lib.myelin_value_get_uint.argtypes = [Value]
_lib.myelin_value_get_uint.restype = ctypes.c_bool
_lib.myelin_value_set_uint.argtypes = [Value, ctypes.c_uint]
_lib.myelin_value_set_uint.restype = None
# long
_lib.myelin_value_get_long.argtypes = [Value]
_lib.myelin_value_get_long.restype = ctypes.c_long
_lib.myelin_value_set_long.argtypes = [Value, ctypes.c_long]
_lib.myelin_value_set_long.restype = None
# ulong
_lib.myelin_value_get_ulong.argtypes = [Value]
_lib.myelin_value_get_ulong.restype = ctypes.c_ulong
_lib.myelin_value_set_ulong.argtypes = [Value, ctypes.c_ulong]
_lib.myelin_value_set_ulong.restype = None
# 64bit integer
_lib.myelin_value_get_int64.argtypes = [Value]
_lib.myelin_value_get_int64.restype = ctypes.c_int64
_lib.myelin_value_set_int64.argtypes = [Value, ctypes.c_int64]
_lib.myelin_value_set_int64.restype = None
# unsigned 64bit integer
_lib.myelin_value_get_uint64.argtypes = [Value]
_lib.myelin_value_get_uint64.restype = ctypes.c_uint64
_lib.myelin_value_set_uint64.argtypes = [Value, ctypes.c_uint64]
_lib.myelin_value_set_uint64.restype = None
# float
_lib.myelin_value_get_float.argtypes = [Value]
_lib.myelin_value_get_float.restype = ctypes.c_float
_lib.myelin_value_set_float.argtypes = [Value, ctypes.c_float]
_lib.myelin_value_set_float.restype = None
# double
_lib.myelin_value_get_double.argtypes = [Value]
_lib.myelin_value_get_double.restype = ctypes.c_double
_lib.myelin_value_set_double.argtypes = [Value, ctypes.c_double]
_lib.myelin_value_set_double.restype = None
# string
_lib.myelin_value_get_string.argtypes = [Value]
_lib.myelin_value_get_string.restype = ctypes.c_char_p
_lib.myelin_value_set_string.argtypes = [Value, ctypes.c_char_p]
_lib.myelin_value_set_string.restype = None
# pointer
_lib.myelin_value_as_pointer.argtypes = [Value]
_lib.myelin_value_as_pointer.restype = ctypes.c_void_p
_lib.myelin_value_set_pointer.argtypes = [Value, Type, ctypes.c_void_p]
_lib.myelin_value_set_pointer.restype = None
| gsterjov/Myelin | bindings/python/myelin/introspection/value.py | Python | gpl-3.0 | 11,453 |
package pl.edu.agh.idziak.asw.common;
import com.google.common.base.Preconditions;
/**
* Created by Tomasz on 13.07.2016.
*/
public class Pair<X, Y> {
private final X one;
private final Y two;
Pair(X one, Y two) {
this.one = Preconditions.checkNotNull(one);
this.two = Preconditions.checkNotNull(two);
}
public static <X, Y> Pair<X, Y> of(X one, Y two) {
return new Pair<>(one, two);
}
public static <T> SingleTypePair<T> ofSingleType(T one, T two) {
return new SingleTypePair<>(one, two);
}
public Y getTwo() {
return two;
}
public X getOne() {
return one;
}
@Override
public String toString() {
return "[" + one + ", " + two + ']';
}
}
| mastablasta1/a-star-w-algorithm | src/main/java/pl/edu/agh/idziak/asw/common/Pair.java | Java | gpl-3.0 | 765 |
from chiplotle.geometry.shapes.path import path
from chiplotle.geometry.transforms.perpendicular_displace \
import perpendicular_displace
def line_displaced(start_coord, end_coord, displacements):
'''Returns a Path defined as a line spanning points `start_coord` and
`end_coord`, displaced by scalars `displacements`.
The number of points in the path is determined by the lenght of
`displacements`.
'''
p = path([start_coord, end_coord])
perpendicular_displace(p, displacements)
return p
if __name__ == '__main__':
from chiplotle import *
import math
disp = [math.sin(i**0.7 / 3.14159 * 2) * 100 for i in range(200)]
line = line_displaced(Coordinate(0, 0), Coordinate(1000, 1000), disp)
io.view(line)
| drepetto/chiplotle | chiplotle/geometry/shapes/line_displaced.py | Python | gpl-3.0 | 763 |
import unittest
from bolt.discord.permissions import Permission
class TestPermission(unittest.TestCase):
def test_permission_from_list_to_list(self):
expected = ['MANAGE_WEBHOOKS', 'USE_EXTERNAL_EMOJIS']
permission = Permission(['MANAGE_WEBHOOKS', 'USE_EXTERNAL_EMOJIS'])
actual = permission.to_list()
self.assertListEqual(sorted(actual), sorted(expected))
def test_permission_from_int_to_list(self):
expected = ['ADMINISTRATOR', 'SEND_MESSAGES']
permission = Permission(2056)
actual = permission.to_list()
self.assertListEqual(sorted(actual), sorted(expected))
def test_permission_in_permission(self):
self.assertTrue("ADMINISTRATOR" in Permission(2056))
def test_permissions_in_permission(self):
self.assertTrue(["ADMINISTRATOR", "SEND_MESSAGES"] in Permission(2056))
def test_permission_not_in_permission(self):
self.assertTrue("USE_VAD" not in Permission(2056))
def test_permissions_not_in_permission(self):
self.assertTrue(["SPEAK", "MANAGE_EMOJIS"] not in Permission(2056))
def test_permission_add(self):
permission = Permission(2056)
self.assertTrue(permission.allows("ADMINISTRATOR"))
self.assertFalse(permission.allows("MENTION_EVERYONE"))
permission.add("MENTION_EVERYONE")
self.assertTrue(permission.allows("MENTION_EVERYONE"))
def test_permission_remove(self):
permission = Permission(2056)
self.assertTrue(permission.allows("ADMINISTRATOR"))
self.assertTrue(permission.allows("SEND_MESSAGES"))
permission.remove("SEND_MESSAGES")
self.assertFalse(permission.allows("SEND_MESSAGES"))
| Arcbot-Org/Arcbot | tests/discord/test_permission.py | Python | gpl-3.0 | 1,719 |
import requests
import hashlib
import json
import random
import sys
class ApiItemAmount(object):
def __new__(self, item_type, amount):
return {"type": item_type, "amount": amount}
class SagaAPI(object):
secret = ""
episodeLengths = {}
apiUrl = ""
clientApi = ""
unlockLevelItemId = -1
unlockLevelImage = ""
debug = True
def __init__(self, session, userId):
self.session = session
self.userId = userId
def api_get(self, method, params):
response = requests.get(self.apiUrl + "/" + method, params=params)
if self.debug:
print self.apiUrl + "/" + method + "\n"
print "===============================\n"
print response.text
print "\n"
return response
def hand_out_winnings(self, item_type, amount):
item = [
ApiItemAmount(item_type, amount)
]
params = {
"_session": self.session,
"arg0": json.dumps(item),
"arg1": 1,
"arg2": 1,
"arg3": "hash",
}
return self.api_get("handOutItemWinnings", params)
# gets the balance of all the items that the player has
def get_balance(self):
params = {"_session": self.session}
return self.api_get("getBalance", params)
def get_gameInitLight(self):
params = {"_session": self.session}
return self.api_get("gameInitLight", params)
# full list with level details
def get_gameInit(self):
params = {"_session": self.session}
return self.api_get("gameInit", params)
def add_life(self):
params = {"_session": self.session}
return self.api_get("addLife", params)
def is_level_unlocked(self, episode, level):
params = {"_session": self.session, "arg0": episode, "arg1": level}
response = self.api_get("isLevelUnlocked", params)
return response.text == "true"
def poll_episodeChampions(self, episode):
params = {"_session": self.session, "arg0": episode}
return self.api_get("getEpisodeChampions", params)
def poll_levelScores(self, episode, level):
params = {"_session": self.session, "arg0": episode, "arg1": level}
return self.api_get("getLevelToplist", params)
def post_unlockLevel(self, episode, level):
params = {"_session": self.session}
placement = "Map,%s,%s" % (episode, level)
payload = [{
"method": "ProductApi.purchase",
"id": 0,
"params": [{
"imageUrl": self.unlockLevelImage,
"orderItems": [{
"productPackageType": self.unlockLevelItemId,
"receiverCoreUserId": self.userId
}],
"placement": placement,
"title": "Level Unlock",
"description": "Buy your way to the next level.",
"currency": "KHC"
}]
}]
unlockAttempt = requests.post(self.clientApi, verify=False, params=params, data=json.dumps(payload)).json()
if self.debug:
print json.dumps(unlockAttempt, sort_keys = False, indent = 4)
return unlockAttempt[0]["result"]["status"] == "ok"
def start_game(self, episode, level):
params = {"_session": self.session, "arg0": episode, "arg1": level}
return self.api_get("gameStart", params).json()["seed"]
def end_game(self, episode, level, seed, score=None):
if score is None:
score = random.randrange(3000, 6000) * 100
dic = {
"timeLeftPercent": -1,
"episodeId": episode,
"levelId": level,
"score": score,
"variant": 0,
"seed": seed,
"reason": 0,
"userId": self.userId,
"secret": self.secret
}
dic["cs"] = hashlib.md5("%(episodeId)s:%(levelId)s:%(score)s:%(timeLeftPercent)s:%(userId)s:%(seed)s:%(secret)s" % dic).hexdigest()[:6]
params = {"_session": self.session, "arg0": json.dumps(dic)}
return self.api_get("gameEnd", params)
def print_scores(self, episode, level):
scores = self.poll_levelScores(episode, level).json()
print json.dumps(scores.values()[0][0], sort_keys = False, indent = 4)
print json.dumps(scores.values()[0][1], sort_keys = False, indent = 4)
print json.dumps(scores.values()[0][2], sort_keys = False, indent = 4)
def print_status(self):
print json.dumps(self.poll_status().json(), sort_keys = False, indent = 4)
def complete_level(self, level):
targetEpisode, targetLevel = self.get_episode_level(level)
is_unlocked = self.is_level_unlocked(targetEpisode, targetLevel)
if not is_unlocked:
self.complete_level(level - 1)
response = self.play_game(targetEpisode, targetLevel).json()
if response["episodeId"] == -1:
needUnlock = False
for event in response["events"]:
if event["type"] == "LEVEL_LOCKED":
needUnlock = True
break
if needUnlock:
self.post_unlockLevel(targetEpisode, targetLevel)
self.complete_level(level)
print "Beat episode {0} level {1}".format(targetEpisode, targetLevel)
def get_episode_level(self, level):
if len(self.episodeLengths) == 0:
response = self.get_gameInit()
episodeDescriptions = response.json()["universeDescription"]["episodeDescriptions"]
for episode in episodeDescriptions:
self.episodeLengths[episode["episodeId"]] = len(episode["levelDescriptions"])
targetEpisode = -1
targetLevel = level
currentEpisode = 1
while targetEpisode == -1:
if targetLevel > self.episodeLengths[currentEpisode]:
targetLevel = targetLevel - self.episodeLengths[currentEpisode]
currentEpisode = currentEpisode + 1
else:
targetEpisode = currentEpisode
break
return targetEpisode, targetLevel
def play_gameAutoScore(self, episode, level, starProgressions=None):
if starProgressions is not None:
minPoints = starProgressions["universeDescription"]["episodeDescriptions"][episode-1]["levelDescriptions"][level-1]["starProgressions"][2]["points"]
randomScore = 1
while (randomScore % 2 != 0):
# generate a random number at most 50000 points over the min 3 star and keep trying until it is even
randomScore = random.randrange(minPoints/10, minPoints/10+5000)
myScore = randomScore * 10
# print "Score: %s out of %s" % (myScore, minPoints)
else:
# revert to pulling the top scores. This probably won't work if none of your friends have made it to that level
scoreList = self.poll_levelScores(episode, level).json()
# take the top score and add 5000 points
myScore = scoreList.values()[0][0]["value"] + 5000
return self.play_game(episode, level, myScore)
def play_gameLoop(self, episode, level):
# create a JSON file full of tons and tons of data but only call it once since it is so large
starProgressions = self.get_gameInit().json()
while True:
try:
result = self.play_gameAutoScore(episode, level, starProgressions).json()
try:
# This is not quite right but it works since LEVEL_GOLD_REWARD still has a episodeId and levelId like LEVEL_UNLOCKED
# This only beats new levels that reported back the new unlocked level
data = json.loads(result["events"][0].values()[2])
data["episodeId"]
data["levelId"]
level = level + 1
except KeyError:
print "Next level wasn't reported, Trying to unlock episode %s..." % (episode+1)
self.post_unlockLevel(episode, level-1)
episode = episode + 1
level = 1
except:
print sys.exc_info()[0]
break
except IndexError:
print "Next level wasn't reported, Trying to unlock episode %s..." % (episode+1)
self.post_unlockLevel(episode, level-1)
episode = episode + 1
level = 1
except:
print sys.exc_info()[0]
break
def play_game(self, episode, level, score=None):
seed = self.start_game(episode, level)
return self.end_game(episode, level, seed, score) | boskee/regicide | regicide.py | Python | gpl-3.0 | 8,891 |
package com.harium.keel.filter.selection.skin;
import com.harium.keel.core.helper.ColorHelper;
import com.harium.keel.core.strategy.SelectionStrategy;
import com.harium.keel.filter.selection.SimpleToleranceStrategy;
/**
* Based on: Nusirwan Anwar bin Abdul Rahman, Kit Chong Wei and John See
* RGB-H-CbCr Skin Colour Model for Human Face Detection
*/
public class SkinColorRGBHCbCrStrategy extends SimpleToleranceStrategy implements SelectionStrategy {
public SkinColorRGBHCbCrStrategy() {
super();
}
public SkinColorRGBHCbCrStrategy(int tolerance) {
super(tolerance);
}
@Override
public boolean valid(int rgb, int j, int i) {
return isSkin(rgb, tolerance);
}
public static boolean isSkin(int rgb) {
return isSkin(rgb, 0);
}
public static boolean isSkin(int rgb, int tolerance) {
boolean ruleA = SkinColorKovacStrategy.isSkin(rgb);
final int R = ColorHelper.getRed(rgb);
final int G = ColorHelper.getGreen(rgb);
final int B = ColorHelper.getBlue(rgb);
//final int Y = ColorHelper.getY(R,G,B);
final int CB = ColorHelper.getCB(R, G, B);
final int CR = ColorHelper.getCR(R, G, B);
final float H = ColorHelper.getH(R, G, B);
boolean rule3 = CR <= 1.5862 * CB + 20;
boolean rule4 = CR >= 0.3448 * CB + 76.2069;
boolean rule5 = CR >= -4.5652 * CB + 234.5652;
boolean rule6 = CR <= -1.15 * CB + 301.75;
boolean rule7 = CR <= -2.2857 * CB + 432.8;
boolean ruleB = rule3 && rule4 && rule5 && rule6 && rule7;
boolean ruleC = H < 25 && H > 230;
return ruleA && ruleB && ruleC;
}
}
| yuripourre/e-motion | src/main/java/com/harium/keel/filter/selection/skin/SkinColorRGBHCbCrStrategy.java | Java | gpl-3.0 | 1,693 |
#!/usr/bin/python3
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from sklearn.cluster import KMeans
from sklearn import datasets
from PIL import Image, ImageChops
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
from random import randint
import time
import ephem
from PIL import Image
import cv2
import glob
import sys
import os
import numpy as np
import datetime
from pathlib import Path
import subprocess
from amscommon import read_config
import math
import time
from sklearn.cluster import Birch
from collections import deque
video_dir = "/mnt/ams2/SD/"
def stack_stack(pic1, pic2):
frame_pil = Image.fromarray(pic1)
stacked_image = pic2
if stacked_image is None:
stacked_image = frame_pil
else:
stacked_image=ImageChops.lighter(stacked_image,frame_pil)
return(stacked_image)
def compute_straight_line(x1,y1,x2,y2,x3,y3):
print ("COMP STRAIGHT", x1,y1,x2,y2,x3,y3)
if x2 - x1 != 0:
a = (y2 - y1) / (x2 - x1)
else:
a = 0
if x3 - x1 != 0:
b = (y3 - y1) / (x3 - x1)
else:
b = 0
straight_line = a - b
if (straight_line < 1):
straight = "Y"
else:
straight = "N"
return(straight_line)
def crop_center(img,cropx,cropy):
y,x = img.shape
startx = x//2-(cropx//2) +12
starty = y//2-(cropy//2) + 4
return img[starty:starty+cropy,startx:startx+cropx]
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h,4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def kmeans_cluster(points, num_clusters):
points = np.array(points)
print(points)
clusters = []
cluster_points = []
colors = ('r', 'g', 'b')
est = KMeans(n_clusters=num_clusters)
est.fit(points)
print (est.labels_)
print (len(points))
({i: np.where(est.labels_ == i)[0] for i in range(est.n_clusters)})
for i in set(est.labels_):
index = est.labels_ == i
cluster_idx = np.where(est.labels_ == i)
for idxg in cluster_idx:
for idx in idxg:
idx = int(idx)
point = points[idx]
#print ("IDX:",i, idx, point)
cluster_points.append(point)
clusters.append(cluster_points)
cluster_points = []
#print(points[:,0])
#print(points[:,1])
int_lb = est.labels_.astype(float)
#fig = gcf()
fig = Figure()
canvas = FigureCanvas(fig)
plot = fig.add_subplot(1,1,1)
plot.scatter(points[:,0], points[:,1], c=[plt.cm.Spectral(float(i) / 10) for i in est.labels_])
for cluster in clusters:
cxs = []
cys = []
for cp in cluster:
x,y,w,h = cp
cxs.append(x)
cys.append(y)
if len(cxs) > 3:
plot.plot(np.unique(cxs), np.poly1d(np.polyfit(cxs, cys, 1))(np.unique(cxs)))
plt.xlim(0,640)
plt.ylim(0,480)
plot.invert_yaxis()
fig.canvas.draw()
fig.savefig("/tmp/plot.png", dpi=fig.dpi)
#plt.show()
return(clusters)
def calc_dist(x1,y1,x2,y2):
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist
def find_angle(x1,x2,y1,y2):
if x2 - x1 != 0:
a1 = (y2 - y1) / (x2 - x1)
else:
a1 = 0
angle = math.atan(a1)
angle = math.degrees(angle)
return(angle)
def closest_node(node, nodes):
return nodes[cdist([node], nodes).argmin()]
def find_objects(index, points):
apoints = []
unused_points = []
cl_sort = []
sorted_points = []
last_angle = None
objects = []
group_pts = []
line_segments = []
stars = []
obj_points = []
big_cnts = []
count = 0
x1,y1,w1,h1 = points[index]
print ("Total Points found in image: ", len(points))
used_pts = {}
for i in range(0,len(points)-1):
x1,y1,w1,h1 = points[i]
for i in range(0,len(points)-1):
x2,y2,w2,h2 = points[i]
key = str(x1)+"."+str(y1)+"."+str(x2)+"."+str(y2)
used_pts[key] = 0
key2 = str(x2)+"."+str(y2)+"."+str(x1)+"."+str(y1)
used_pts[key2] = 0
possible_stars = []
for i in range(0,len(points)-1):
closest = []
x1,y1,w1,h1 = points[i]
for j in range(0,len(points)-1):
x2,y2,w2,h2 = points[j]
key = str(x1)+"."+str(y1)+"."+str(x2)+"."+str(y2)
key2 = str(x2)+"."+str(y2)+"."+str(x1)+"."+str(y1)
dist = calc_dist(x1,y1,x2,y2)
angle = find_angle(x1,y1,x2,y2)
if x1 != x2 and y1 != y2:
if used_pts[key] == 0 and used_pts[key2] == 0 :
#print("Closest Point:", (int(dist),int(angle),int(x1),int(y1),int(x2),int(y2)))
closest.append((int(dist),int(angle),int(x1),int(y1),int(x2),int(y2)))
used_pts[key] = 1
used_pts[key2] = 1
#print("Key has been used:", key, key2)
#else:
# print("Key already used try another one:", key, key2)
#else:
# print ("this point has already been used")
count = count + 1
# of all the close points, make sure that at least 2 points < 25 px dist exist.
conf_closest = []
for cls in closest:
if cls[0] < 100:
conf_closest.append(cls)
if len(closest) > 0:
distsort = np.unique(closest, axis=0)
dist,angle,x1,y1,x2,y2 = distsort[0]
if dist < 50 and len(conf_closest) > 1:
line_segments.append((int(dist),int(angle),int(x1),int(y1),int(x2),int(y2)))
obj_points.append((int(x1),int(y1), int(w1), int(h1)))
else:
possible_stars.append((int(x1),int(y1),int(w1),int(h1)))
#print("CLOSEST LINE SEGMENT FOR PT: ", distsort[0])
#else:
#print("ERROR! no close points to this one!", x1,y1)
if w1 > 15 or h1 > 15:
# print ("BIG!!! We have a big object here likely containing many line segments.")
big_cnts.append((int(x1),int(y1),int(w1),int(h1)))
for star in possible_stars:
close = 0
for line in line_segments:
dist,angle,x1,y1,x2,y2 = line
star_dist = calc_dist(star[0], star[1], x1,y1)
#print ("STARDIST: ", star_dist, star[0], star[1], x1,y1)
if star_dist < 60:
close = 1
if close == 1:
obj_points.append(star)
else:
stars.append(star)
#print ("OBJECT POINTS")
if len(line_segments) > 0:
sorted_lines = sorted(line_segments, key=lambda x: x[2])
else:
sorted_lines = []
#print ("LINE SEGMENTS:")
#for line in sorted_lines:
# print (line)
last_ang = 0
last_dist = 0
line_groups = []
line_group = []
orphan_lines = []
if len(sorted_lines) > 0:
for segment in sorted_lines:
dist,angle,x1,y1,x2,y2 = segment
if last_ang != 0 and (angle -5 < last_ang < angle + 5) and dist < 100:
#print ("Line Segment Part of Existing Group: ", segment)
line_group.append((dist,angle,x1,y1,x2,y2))
else:
#print ("New Group Started!", last_ang, angle )
# print ("Line Segment Part of New Group: ", segment)
if len(line_group) >= 3:
line_groups.append(line_group)
else:
#print("Last line segment was too small to be part of a group! These are random points or stars. Skip for now.")
for line in line_group:
orphan_lines.append(line)
line_group = []
line_group.append((dist,angle,x1,y1,x2,y2))
last_ang = angle
if len(line_group) >= 2:
line_groups.append(line_group)
else:
for line in line_group:
orphan_lines.append(line)
# now make sure all of the line segments in the line group can connect to at least one of the other segments
#print ("Total Line Groups as of now:", len(line_groups))
#print ("Total Orphan Lines as of now:", len(orphan_lines))
#print ("Confirm the line segments are all part of the same group", len(line_groups))
#print ("TOTAL POINTS: ", len(points))
#print ("TOTAL LINE GROUPS: ", len(line_groups))
#print ("ORPHAN GROUPS: ", len(orphan_lines))
#for point in points:
#print ("POINT: ", point)
gc = 1
if len(line_groups) > 0:
for line_group in line_groups:
lc = 1
for line in line_group:
#print("LINE:", line)
dist,ang,x1,y1,x2,y2 = line
#confirm_angle = find_angle(x1,y1,x2,y2)
#print ("GROUP", gc, lc, line, ang, confirm_angle)
lc = lc + 1
gc = gc + 1
#else:
#make sure the obj points are not false positives, if so move to stars.
(line_groups, orphan_lines, stars, obj_points, big_cnts) = conf_objs(line_groups, orphan_lines, stars, obj_points, big_cnts)
return(line_groups, orphan_lines, stars, obj_points, big_cnts)
def conf_objs(line_groups, orphan_lines, stars, obj_points, big_cnts):
print ("CONF OBJS")
print ("LINE GROUPS", len(line_groups))
print ("OBJ POINTS", len(obj_points))
conf_line_groups = []
mx = []
my = []
mw = []
mh = []
#first lets check the line groups and make sure at least 3 points are straight
for line_group in line_groups:
mx = []
my = []
mw = []
mh = []
lgc = 0
for dist,ang,x1,y1,x2,y2 in line_group:
mx.append(x1)
my.append(y1)
print (dist, ang, x1,y1,x2,y2)
print (lgc, "adding MX", x1, mx)
print (lgc, "adding MYs", y1, my)
#mx.append(x2)
#my.append(y2)
lgc = lgc + 1
if len(mx) > 2:
print ("MXs", mx)
print ("MYs", my)
st = compute_straight_line(mx[0],my[0],mx[1],my[1],mx[2],my[2])
else:
st = 100
if st <= 1:
print ("This group is straight")
conf_line_groups.append(line_group)
else:
print ("This group is NOT straight")
orphan_lines.append(line_group)
cc = 0
mx = []
my = []
mw = []
mh = []
for x,y,h,w in obj_points:
mx.append(x)
my.append(y)
mw.append(w)
mh.append(h)
cc = cc + 1
if len(mx) > 2:
st = compute_straight_line(mx[0],my[0],mx[1],my[1],mx[2],my[2])
else:
st = 100
if st <= 1:
print ("At least 3 of these are straight, we can continue.", st)
else:
print ("These 3 objects are not straight, and thus false!", st)
for x,y,h,w in obj_points:
stars.append((x,y,h,w))
obj_points = []
return(line_groups, orphan_lines, stars, obj_points, big_cnts)
def clean_line_groups(line_groups, orphan_lines):
cleaned_line_groups = []
cleaned_line_group = []
for line_group in line_groups:
if len(line_group) == 2:
# make sure these two groups are close enough to each other to be grouped.
(dist,angle,x1,y1,x2,y2) = line_group[0]
(xdist,xangle,xx1,xy1,xx2,xy2) = line_group[1]
group_dist = calc_dist(x1,y1,xx1,xy1)
if group_dist > 50 or (angle -5 < xangle < angle + 5):
orphan_lines.append(line_group[0])
orphan_lines.append(line_group[1])
else:
cleaned_line_group.append(line_group[0])
cleaned_line_group.append(line_group[1])
else:
cleaned_line_groups.append(line_group)
line_groups = cleaned_line_groups
print("CLG:", line_groups)
return(cleaned_line_groups, orphan_lines)
def confirm_cnts(crop):
crop = cv2.GaussianBlur(crop, (5, 5), 0)
avg_flux = np.average(crop)
max_flux = np.amax(crop)
thresh_limit = avg_flux / 2
_, crop_thresh = cv2.threshold(crop, thresh_limit, 255, cv2.THRESH_BINARY)
#(_, cnts, xx) = cv2.findContours(crop_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#if np.sum(crop_thresh) > (255 * 2):
#print ("CONFIRM:", max_flux, avg_flux, thresh_limit, np.sum(crop_thresh))
#cv2.imshow('pepe', crop_thresh)
#else:
# print ("FAILED:", max_flux, avg_flux, thresh_limit, np.sum(crop_thresh))
#cv2.imshow('pepe', crop)
#cv2.waitKey(100)
return(np.sum(crop_thresh))
def find_best_thresh(image, thresh_limit, type):
go = 1
while go == 1:
_, thresh = cv2.threshold(image, thresh_limit, 255, cv2.THRESH_BINARY)
(_, cnts, xx) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if type == 0:
cap = 80
else:
cap = 100
if len(cnts) > cap:
thresh_limit = thresh_limit + 1
else:
bad = 0
for (i,c) in enumerate(cnts):
x,y,w,h = cv2.boundingRect(cnts[i])
if w == image.shape[1]:
bad = 1
if type == 0 and (w >= 10 or h > 10):
bad = 1
if bad == 0:
go = 0
else:
thresh_limit = thresh_limit + 1
#print ("CNTs, BEST THRESH:", str(len(cnts)), thresh_limit)
return(thresh_limit)
def find_objects2(timage, tag, current_image, filename):
stars = []
big_cnts = []
obj_points = []
image = timage
thresh_limit = 10
thresh_limit = find_best_thresh(image, thresh_limit, 0)
# find best thresh limit code here!
line_objects = []
points = []
orphan_lines = []
_, thresh = cv2.threshold(image, thresh_limit, 255, cv2.THRESH_BINARY)
(_, cnts, xx) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#print ("CNTS:", len(cnts))
hit = 0
objects = []
if len(cnts) < 500:
for (i,c) in enumerate(cnts):
x,y,w,h = cv2.boundingRect(cnts[i])
if w > 1 and h > 1:
if (w < 10 and h <10):
nothing = 0
# cv2.rectangle(image, (x,y), (x+w+5, y+h+5), (255),1)
#cv2.circle(image, (x,y), 20, (120), 1)
#if w != h:
# cv2.rectangle(image, (x,y), (x+w+5, y+h+5), (255),1)
else:
#cv2.rectangle(image, (x,y), (x+w+5, y+h+5), (255),1)
# Convert big object into points and add each one to the points array.
crop = timage[y:y+h,x:x+w]
points.append((x,y,w,h))
if w < 600 and h < 400:
crop_points = find_points_in_crop(crop,x,y,w,h)
for x,y,w,h in crop_points:
print("adding some points",x,y,w,h)
points.append((x,y,w,h))
points.append((x,y,w,h))
#objects.append((x,y,w,h))
else:
image[y:y+h,x:x+w] = [0]
else:
print ("WAY TO MANY CNTS:", len(cnts))
thresh_limit = thresh_limit + 5
return(points)
# find line objects
if (len(objects) + len(points)) > 0:
line_groups, orphan_lines, stars, obj_points = find_objects(0, points)
else:
line_groups = []
final_group = []
final_groups = []
reject_group = []
reject_groups = []
line_segments = flatten_line_groups(line_groups)
line_segments = sorted(line_segments, key = lambda x: (x[0],x[1]))
if len(line_segments) > 0:
final_group, reject_group = regroup_lines(line_segments)
print ("MIKE!:", len(final_group))
if len(final_group) > 1:
final_groups.append(final_group)
else:
for line in final_group:
orphan_lines.append(line)
if len(reject_group) > 3:
print (len(reject_group), "rejects left. do it again.")
reject_group = sorted(reject_group, key = lambda x: (x[1],x[0]))
final_group, reject_group = regroup_lines(reject_group)
if len(final_group) > 1:
final_groups.append(final_group)
else:
for line in final_group:
orphan_lines.append(line)
print (len(reject_group), "rejects left after 2nd try")
if len(reject_group) > 3:
print (len(reject_group), "rejects left. do it again.")
final_group, reject_group = regroup_lines(reject_group)
if len(final_group) > 1:
final_groups.append(final_group)
else:
for line in final_group:
orphan_lines.append(line)
print (len(reject_group), "rejects left after 3rd try")
# try to adopt the orphans!
if len(orphan_lines) >= 1:
print (orphan_lines)
final_group, reject_group = regroup_lines(orphan_lines)
if len(final_group) > 1:
final_groups.append(final_group)
if len(final_group) > 0:
print ("Adopted! : ", final_group)
orphan_lines = reject_group
if len(orphan_lines) >= 1:
final_group, reject_group = regroup_lines(reject_group)
if len(final_group) > 1:
final_groups.append(final_group)
if len(final_group) > 0:
print ("Adopted! : ", final_group)
orphan_lines = reject_group
if len(orphan_lines) >= 1:
final_group, reject_group = regroup_lines(reject_group)
if len(final_group) > 1:
final_groups.append(final_group)
if len(final_group) > 0:
print ("Adopted! : ", final_group)
orphan_lines = reject_group
final_groups, orphan_lines = clean_line_groups(final_groups, orphan_lines)
clusters= []
clusters_ab= []
last_x = None
last_y = None
last_ang = None
ang = None
if len(points) > 3:
num_clusters = int(len(points)/3)
clusters = kmeans_cluster(points, num_clusters)
#print ("MIKE CLUSTERS", len(clusters))
for cluster in clusters:
cxs = []
cys = []
for cp in cluster:
x,y,w,h = cp
cxs.append(x)
cys.append(y)
if last_x is not None:
ang = find_angle(x,y,last_x,last_y)
print ("CLUSTER ANGLE:", x,y,last_x,last_y,ang)
if last_ang is not None:
if ang - 5 < last_ang < ang + 5:
cv2.line(image, (x,y), (last_x,last_y), (200), 4)
last_x = x
last_y = y
last_ang = ang
a, b = best_fit (cxs,cys)
mnx = min(cxs)
mny = min(cys)
mmx = max(cxs)
mmy = max(cys)
cv2.rectangle(image, (mnx,mny), (mmx, mmy), (255),1)
#print ("MIKE MIKE XS,", cxs)
#print ("MIKE MIKE YS,", cys)
clusters_ab.append((a,b))
print ("MIKE AB,", a,b)
print ("FINAL ANALYSIS")
print (final_groups)
print ("--------------")
print ("File Name: ", filename)
print ("Total Points:", len(points))
print ("Total Line Segments:", len(line_segments))
print ("Total Final Line Groups:", len(final_groups))
print ("Total Clusters:", len(clusters))
cl =0
for a,b in clusters_ab:
print ("Cluster " + str(cl + 1) + " " + str(len(clusters[cl])) + " points")
print ("LINE AB " + str(a) + " " + str(b))
cl = cl + 1
#print (final_groups)
print ("Total Rejected Lines:", len(reject_group))
gc = 1
xs = ys = []
for line_group in final_groups:
lc = 1
for line in line_group:
dist,angle,x1,y1,x2,y2 = line
xs.append(x1)
xs.append(x2)
ys.append(y1)
ys.append(y2)
#print (gc, lc, line)
lc = lc + 1
gc = gc + 1
if len(xs) > 0 and len(ys) > 0:
mnx = min(xs)
mxx = max(xs)
mny = min(ys)
mxy = max(ys)
cv2.rectangle(image, (mnx,mny), (mxx, mxy), (255),1)
print ("Total Orphaned Lines:", len(orphan_lines))
if len(line_groups) > 0:
line_segments = flatten_line_groups(line_groups)
find_line_nodes(line_segments)
gc = 1
for line_group in line_groups:
lc = 1
line_group = sorted(line_group, key = lambda x: (x[2],x[3]))
dist,angle,sx1,sy1,sx2,sy2 = line_group[0]
for line in line_group:
dist,angle,x1,y1,x2,y2 = line
#s_ang = find_angle(sx1,sy1,x1,y1)
#if angle - 5 < s_ang < angle + 5:
# print("FINAL GROUP:", gc,lc,line, angle, s_ang)
# final_group.append((dist,angle,x1,y1,x2,y2))
#else:
# print("REJECT GROUP:", gc,lc,line, angle, s_ang)
# reject_group.append((dist,angle,x1,y1,x2,y2))
#seg_dist = find_closest_segment(line, line_group)
cv2.line(image, (x1,y1), (x2,y2), (255), 2)
cv2.putText(image, "L " + str(lc), (x1+25,y1+10), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
lc = lc + 1
if len(line_group) > 0:
cv2.putText(image, "LG " + str(gc), (x1+25,y1), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
gc = gc + 1
for line in orphan_lines:
#print("ORPHAN:", line)
dist,angle,x1,y1,x2,y2 = line
cv2.line(image, (x1,y1), (x2,y2), (255), 1)
cv2.putText(image, "Orph" , (x1+25,y1), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
#cv2.ellipse(image,(ax,ay),(dist_x,dist_y),elp_ang,elp_ang,180,255,-1)
#a,b = best_fit(lxs, lys)
#plt.scatter(lxs,lys)
#plt.xlim(0,640)
#plt.ylim(0,480)
#yfit = [a + b * xi for xi in lxs]
#plt.plot(lxs,yfit)
#cv2.imshow('pepe', image)
#cv2.waitKey(1)
#plt.gca().invert_yaxis()
#plt.show()
#for x,y,w,h in points:
# if w > 25 or h > 25:
# cv2.rectangle(image, (x,y), (x+w+5, y+h+5), (255),1)
# else:
# cv2.circle(image, (x,y), 20, (120), 1)
edges = cv2.Canny(image.copy(),thresh_limit,255)
el = filename.split("/");
fn = el[-1]
cv2.putText(current_image, "File Name: " + fn, (10,440), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
cv2.putText(current_image, str(tag), (10,450), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
cv2.putText(current_image, "Points: " + str(len(points)), (10,460), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
cv2.putText(current_image, "Line Groups: " + str(len(final_groups)), (10,470), cv2.FONT_HERSHEY_SIMPLEX, .4, (255), 1)
blend = cv2.addWeighted(image, .2, current_image, .8,0)
np_plt = cv2.imread("/tmp/plot.png")
np_plt = cv2.cvtColor(np_plt, cv2.COLOR_BGR2GRAY)
hh, ww = np_plt.shape
crop = cv2.resize(np_plt, (0,0), fx=1.1, fy=1.1)
crop = crop_center(crop, 640,480)
#blend = cv2.addWeighted(blend, .5, crop, .5,0)
#for x,y in stars:
# cv2.circle(blend, (x,y), 5, (255), 1)
#exit()
return(line_groups, points, clusters)
def regroup_lines(line_segments):
final_group = []
reject_group = []
sangles = []
dist,angle,sx1,sy1,sx2,sy2 = line_segments[0]
for line in line_segments:
dist,angle,x1,y1,x2,y2 = line
s_ang = find_angle(sx1,sy1,x1,y1)
sangles.append(s_ang)
mean_angle = np.median(np.array(sangles))
if len(line_segments ) > 0:
dist,angle,sx1,sy1,sx2,sy2 = line_segments[0]
for line in line_segments:
dist,angle,x1,y1,x2,y2 = line
s_ang = find_angle(sx1,sy1,x1,y1)
if mean_angle - 10 <= s_ang <= mean_angle + 10:
#print("FINAL GROUP:", line, angle, s_ang, mean_angle)
found = 0
for (dd,aa,ax1,ay1,ax2,ay2) in final_group:
if ax1 == x1 and ay1 == y1:
found = 1
if found == 0:
final_group.append((dist,angle,x1,y1,x2,y2))
else:
#print("REJECT GROUP:",line, angle, s_ang, mean_angle)
reject_group.append((dist,angle,x1,y1,x2,y2))
if len(line_segments ) > 0:
sdist,sangle,sx1,sy1,sx2,sy2 = line_segments[0]
for line in line_segments:
dist,angle,x1,y1,x2,y2 = line
s_ang = find_angle(sx1,sy1,x1,y1)
tdist = calc_dist(x1,y1,sx1,sy1)
if sangle - 10 <= angle <= sangle + 10 and tdist < 20:
found = 0
for (dd,aa,ax1,ay1,ax2,ay2) in final_group:
if ax1 == x1 and ay1 == y1:
found = 1
if found == 0:
print("FINAL GROUP:", line, angle, s_ang, mean_angle)
final_group.append((dist,angle,x1,y1,x2,y2))
else:
#print("REJECT GROUP:",line, angle, s_ang, mean_angle)
reject_group.append((dist,angle,x1,y1,x2,y2))
return(final_group, reject_group)
def flatten_line_groups(line_groups):
line_segments = []
for line_group in line_groups:
for line in line_group:
dist,angle,x1,y1,x2,y2 = line
line_segments.append((dist,angle,x1,y1,x2,y2))
return(line_segments)
def log_node(nodes, line, closest):
if len(nodes) == 0:
nodes.append((line,closest))
return(nodes)
def find_line_nodes(line_segments):
nodes = []
seg_list = []
rest = line_segments
for line in line_segments:
#print("LENLINE", len(line))
#print(line)
dist,angle,x1,y1,x2,y2 = line
closest, rest = sort_segs(x1,y1,rest)
#nodes = log_node(nodes, line, closest)
def sort_segs(x,y,seg_dist):
sorted_lines = sorted(seg_dist, key=lambda x: x[0])
#for line in sorted_lines:
# print ("SORTED LINE", line)
closest = []
rest = []
already_found = 0
for line in sorted_lines:
if len(line) == 6:
dist,angle,x1,y1,x2,y2 = line
else:
print("WTF!:", line)
seg_dist = calc_dist(x,y,x1,y1)
if seg_dist != 0 and already_found != 1:
closest.append((dist,angle,x1,y1,x2,y2))
else:
rest.append((dist,angle,x1,y1,x2,y2))
return(closest, rest)
def find_closest_segment(this_line,line_group):
seg_dist = []
dist, angle, x1,y1,x2,y2 = this_line
cx = (x1 + x2) / 2
cy = (y1 + y2) / 2
for line in line_group:
xdist, xangle, xx1,xy1,xx2,xy2 = line
xcx = (xx1 + xx2) / 2
xcy = (xy1 + xy2) / 2
dist = calc_dist(cx,cy,xcx,xcy)
if dist > 0:
seg_dist.append((dist, x1,y1,x2,y2))
sorted_lines = sorted(seg_dist, key=lambda x: x[0])
#for line in sorted_lines:
# print("CLOSEST SEGMENTS:", line)
def find_points_in_crop(crop,x,y,w,h):
print ("cropping")
go = 1
cnt_pts = []
thresh_limit = 250
canvas = np.zeros([480,640], dtype=crop.dtype)
canvas[y:y+h,x:x+w] = crop
for i in range(x,x+w):
for j in range(y,y+w):
if i % 5 == 0:
canvas[0:480,i:i+3] = 0
if j % 5 == 0:
canvas[j:j+3,0:640] = 0
#print ("CROP", crop.shape[0])
#if crop.shape[0] > 25:
#cv2.imshow('pepe', canvas)
#cv2.waitKey(1000)
last_cnts = []
while go == 1:
_, thresh = cv2.threshold(canvas, thresh_limit, 255, cv2.THRESH_BINARY)
(_, cnts, xx) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt_limit = int((w + h) / 20)
if cnt_limit < 5:
cnt_limit = 5
if cnt_limit > 25:
cnt_limit = 25
#print ("CNTS at thresh:", len(cnts), thresh_limit)
thresh_limit = thresh_limit - 2
if len(cnts) >= cnt_limit:
for (i,c) in enumerate(cnts):
x,y,w,h = cv2.boundingRect(cnts[i])
if w > 1 and h > 1:
cnt_pts.append((x,y,w,h))
if len(last_cnts) >= len(cnt_pts) and len(last_cnts) > cnt_limit:
#cnt_pts = last_cnts
go = 0
if thresh_limit < 5:
cnt_pts = last_cnts
go = 0
if len(cnts) > 70:
go = 0
#print ("CNTS: ", len(cnts))
#print ("LAST CNTS: ", len(last_cnts))
#print ("THRESH LIMIT: ", thresh_limit)
#cv2.imshow('pepe', thresh)
#cv2.waitKey(100)
last_cnts = cnt_pts
return(cnt_pts)
def best_fit(X, Y):
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi,yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
b = numer / denum
a = ybar - b * xbar
print('best fit line:\ny = {:.2f} + {:.2f}x'.format(a, b))
return a, b
def diff_all(med_stack_all, background, median, before_image, current_image, after_image,filename ):
before_diff = cv2.absdiff(current_image.astype(current_image.dtype), before_image,)
after_diff = cv2.absdiff(current_image.astype(current_image.dtype), after_image,)
before_after_diff = cv2.absdiff(before_image.astype(current_image.dtype), after_image,)
median_three = np.median(np.array((before_image, after_image, current_image)), axis=0)
median = np.uint8(median)
median_sum = np.sum(median)
median_diff = cv2.absdiff(median_three.astype(current_image.dtype), median,)
blur_med = cv2.GaussianBlur(median, (5, 5), 0)
# find bright areas in median and mask them out of the current image
tm = find_best_thresh(blur_med, 30, 1)
_, median_thresh = cv2.threshold(blur_med, tm, 255, cv2.THRESH_BINARY)
#cv2.imshow('pepe', median_thresh)
#cv2.waitKey(1000)
(_, cnts, xx) = cv2.findContours(median_thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
hit = 0
real_cnts = []
print ("CNTS: ", len(cnts))
if len(cnts) < 1000:
for (i,c) in enumerate(cnts):
x,y,w,h = cv2.boundingRect(cnts[i])
if True:
w = w + 20
h = h + 20
x = x - 20
y = y - 20
if x < 0:
x = 0
if y < 0:
y = 0
if x+w > current_image.shape[1]:
x = current_image.shape[1]-1
if y+h > current_image.shape[0]:
y = current_image.shape[0]-1
if w > 0 and h > 0:
mask = current_image[y:y+h, x:x+w]
#cv2.rectangle(current_image, (x,y), (x+w+5, y+h+5), (255),1)
for xx in range(0, mask.shape[1]):
for yy in range(0, mask.shape[0]):
mask[yy,xx] = randint(0,6)
blur_mask = cv2.GaussianBlur(mask, (5, 5), 0)
current_image[y:y+h,x:x+w] = blur_mask
median[y:y+h,x:x+w] =blur_mask
# find the diff between the masked median and the masked current image
blur_cur = cv2.GaussianBlur(current_image, (5, 5), 0)
blur_med = cv2.GaussianBlur(median, (5, 5), 0)
cur_med_diff = cv2.absdiff(blur_cur.astype(blur_cur.dtype), blur_med,)
blend = cv2.addWeighted(current_image, .5, cur_med_diff, .5,0)
cur_med_diff =- median
#line_groups, points, clusters = find_objects2(blend, "Current Median Diff Blend", current_image, filename)
return(blend, current_image, filename)
#return(line_groups, points)
def inspect_image(med_stack_all, background, median, before_image, current_image, after_image, avg_cnt,avg_tot,avg_pts,filename):
rois = []
big_cnts = []
line_groups = []
orphan_lines = []
obj_points = []
stars = []
image_diff = cv2.absdiff(current_image.astype(current_image.dtype), background,)
orig_image = current_image
current_image = image_diff
blend, current_image, filename = diff_all(med_stack_all, background, median, before_image, current_image, after_image,filename)
points = find_objects2(blend, "Current Median Diff Blend", current_image, filename)
if len(points) > 2:
line_groups, orphan_lines, stars, obj_points, big_cnts = find_objects(0, points)
if len(obj_points) > 2:
line_groups, orphan_lines, stars2, obj_points, big_cnts = find_objects(0, obj_points)
stars = stars + stars2
print ("---FINAL ANALYSIS---")
print ("File: ", filename)
print ("Total Points: ", len(points))
print ("Line Groups: ", len(line_groups))
lg_points = 0
lg = 1
for line in line_groups:
print (" Group " + str(lg) + ": " + str(len(line)))
lg = lg + 1
lg_points = lg_points + len(line)
print ("Total Line Group Points: ", lg_points)
print ("Orphan Lines: ", len(line_groups))
print ("Stars: ", len(stars))
print ("Obj Points: ", len(obj_points))
print ("Big CNTS: ", len(big_cnts))
for x,y,w,h in big_cnts:
cv2.rectangle(blend, (x,y), (x+w+5, y+h+5), (255),1)
#for x,y,w,h in obj_points:
# if w > 25 or h > 25:
# cv2.rectangle(blend, (x,y), (x+w+5, y+h+5), (255),1)
# else:
# cv2.circle(blend, (x,y), 20, (120), 1)
#for x,y,w,h in stars:
# if w > 25 or h > 25:
# cv2.rectangle(blend, (x,y), (x+w+5, y+h+5), (255),1)
# else:
# cv2.circle(blend, (x,y), 5, (120), 1)
return(blend, points, line_groups, stars, obj_points, big_cnts)
def parse_file_date(orig_video_file):
#print(orig_video_file)
if ".mp4" in orig_video_file:
stacked_image_fn = orig_video_file.replace(".mp4", "-stack.jpg")
star_image_fn = orig_video_file.replace(".mp4", "-stars.jpg")
report_fn = orig_video_file.replace(".mp4", "-stack-report.txt")
video_report = orig_video_file.replace(".mp4", "-report.txt")
trim_file = orig_video_file.replace(".mp4", "-trim.mp4")
else:
stacked_image_fn = orig_video_file.replace(".avi", "-stack.jpg")
trim_file = orig_video_file.replace(".avi", "-trim.avi")
star_image_fn = orig_video_file.replace(".avi", "-stars.jpg")
report_fn = orig_video_file.replace(".avi", "-stack-report.txt")
el = orig_video_file.split("/")
file_name = el[-1]
file_name = file_name.replace("_", "-")
file_name = file_name.replace(".", "-")
#print ("FN", file_name)
xyear, xmonth, xday, xhour, xmin, xsec, xcam_num, ftype, xext = file_name.split("-")
cam_num = xcam_num.replace("cam", "")
date_str = xyear + "-" + xmonth + "-" + xday + " " + xhour + ":" + xmin + ":" + xsec
capture_date = date_str
return(capture_date)
def day_or_night(config, capture_date):
obs = ephem.Observer()
obs.pressure = 0
obs.horizon = '-0:34'
obs.lat = config['device_lat']
obs.lon = config['device_lng']
obs.date = capture_date
sun = ephem.Sun()
sun.compute(obs)
(sun_alt, x,y) = str(sun.alt).split(":")
saz = str(sun.az)
(sun_az, x,y) = saz.split(":")
#print ("SUN", sun_alt)
if int(sun_alt) < -1:
sun_status = "night"
else:
sun_status = "day"
return(sun_status, sun_alt)
def diff_stills(sdate, cam_num):
med_last_objects = []
last_objects = deque(maxlen=5)
diffed_files = []
config = read_config("conf/config-1.txt")
video_dir = "/mnt/ams2/SD/"
images = []
images_orig = []
images_blend = []
images_info = []
count = 0
last_image = None
last_thresh_sum = 0
hits = 0
avg_cnt = 0
avg_tot = 0
avg_pts = 0
count = 0
glob_dir = video_dir + "proc/" + sdate + "/" + "*cam" + str(cam_num) + "-stacked.jpg"
report_file = video_dir + "proc/" + sdate + "/" + sdate + "-cam" + str(cam_num) + "-report.txt"
master_stack_file = video_dir + "proc/" + sdate + "/" + sdate + "-cam" + str(cam_num) + "-master_stack.jpg"
#cv2.namedWindow('pepe')
mask_file = "conf/mask-" + str(cam_num) + ".txt"
file_exists = Path(mask_file)
mask_exists = 0
still_mask = [0,0,0,0]
if (file_exists.is_file()):
print("File found.")
ms = open(mask_file)
for lines in ms:
line, jk = lines.split("\n")
exec(line)
ms.close()
mask_exists = 1
(sm_min_x, sm_max_x, sm_min_y, sm_max_y) = still_mask
diffs = 0
image_list = []
file_list = []
sorted_list = []
print ("Loading still images from ", glob_dir)
fp = open(report_file, "w")
for filename in (glob.glob(glob_dir)):
capture_date = parse_file_date(filename)
sun_status, sun_alt = day_or_night(config, capture_date)
if sun_status != 'day' and int(sun_alt) <= -5:
#print("NIGHTTIME", capture_date, filename, sun_status)
file_list.append(filename)
else:
print ("This is a daytime or dusk file")
sorted_list = sorted(file_list)
for filename in sorted_list:
open_cv_image = cv2.imread(filename,0)
orig_image = open_cv_image
images_orig.append(orig_image)
print(filename)
open_cv_image[440:480, 0:640] = [0]
if mask_exists == 1:
open_cv_image[sm_min_y:sm_max_y, sm_min_x:sm_max_x] = [0]
images.append(open_cv_image)
#exit()
#time.sleep(5)
height , width = open_cv_image.shape
master_stack = None
# Define the codec and create VideoWriter object
#fourcc = cv2.VideoWriter_fourcc(*'H264')
#out = cv2.VideoWriter(outfile,fourcc, 5, (width,height),1)
#med_stack_all = np.median(np.array(images[50:150]), axis=0)
med_stack_all = np.median(np.array(images), axis=0)
#cv2.imshow('pepe', cv2.convertScaleAbs(med_stack_all))
#cv2.waitKey(1000)
objects = None
last_line_groups = []
last_points = []
for filename in sorted_list:
hit = 0
detect = 0
el = filename.split("/")
fn = el[-1]
#this_image = cv2.imread(filename,1)
this_image = images[count]
if count >= 1:
before_image = images[count-1]
else:
before_image = images[count+2]
if count >= len(file_list)-1:
after_image = images[count-2]
else:
after_image = images[count+1]
if count < 25:
median = np.median(np.array(images[0:count+25]), axis=0)
elif len(images) - count < 25:
median = np.median(np.array(images[count-25:count]), axis=0)
else:
median = np.median(np.array(images[count-25:count]), axis=0)
if count < 10:
background = images[count+1]
for i in range (0,10):
background = cv2.addWeighted(background, .8, images[count+i], .2,0)
else:
background = images[count-1]
for i in range (0,10):
background = cv2.addWeighted(background, .8, images[count-i], .2,0)
img_rpt_file = filename.replace("-stacked.jpg", "-stack-report.txt")
img_report = open(img_rpt_file, "w")
(blend, points, line_groups, stars, obj_points, big_cnts) = inspect_image(med_stack_all, background, median, before_image, this_image, after_image, avg_cnt,avg_tot,avg_pts, filename)
master_stack = stack_stack(blend, master_stack)
img_report.write("points=" + str(points) + "\n")
img_report.write("line_groups=" + str(line_groups) + "\n")
img_report.write("stars=" + str(stars) + "\n")
img_report.write("obj_points=" + str(obj_points) + "\n")
img_report.write("big_cnts=" + str(big_cnts) + "\n")
img_report.close()
images_blend.append(blend)
images_info.append((points, line_groups, stars, obj_points, big_cnts))
# block out the detections in the master image to remove it from the running mask
last_line_group = line_groups
last_points = points
for x,y,w,h in last_points:
images[count][y:y+h,x:x+w] = 5
count = count + 1
if len(big_cnts) > 0 or len(obj_points) >= 3:
hits = hits + 1
#cv2.imshow('pepe', blend)
#if len(line_groups) >= 1 or len(obj_points) > 3 or len(big_cnts) > 0:
#cv2.waitKey(1)
# while(1):
# k = cv2.waitKey(33)
# if k == 32:
# break
# if k == 27:
# exit()
#else:
#cv2.waitKey(1)
data = filename + "," + str(len(line_groups)) + "," + str(len(obj_points)) + "," + str(len(big_cnts)) + "\n"
fp.write(data)
print ("TOTAL: ", len(file_list))
print ("HITS: ", hits)
fp.close()
if master_stack is not None:
print("saving", master_stack_file)
master_stack.save(master_stack_file, "JPEG")
else:
print("Failed.")
hits = 1
for count in range(0, len(sorted_list) - 1):
file = sorted_list[count]
el = file.split("/")
st = el[-1]
report_str = st.replace("-stacked.jpg", "-report.txt")
video_str = st.replace("-stacked.jpg", ".mp4")
video_file = file.replace("-stacked.jpg", ".mp4")
(points, line_groups, stars, obj_points, big_cnts) = images_info[count]
if len(obj_points) > 3 or len(big_cnts) > 0:
for bc in big_cnts:
(x,y,w,h) = bc
obj_points.append((x,y,5,5))
obj_points.append((x+w,y+h,5,5))
np_obj_points = np.array(obj_points)
max_x = np.max(np_obj_points[:,0])
max_y = np.max(np_obj_points[:,1])
min_x = np.min(np_obj_points[:,0])
min_y = np.min(np_obj_points[:,1])
myimg = cv2.imread(sorted_list[count],0)
cv2.rectangle(myimg, (min_x,min_y), (max_x, max_y), (255),1)
#cv2.imshow('pepe', myimg)
#cv2.waitKey(1)
print ("-------")
print ("Count:", count)
print ("Hit:", hits)
print ("File:", sorted_list[count])
print ("Points:", str(len(points)))
print ("Line Groups:", str(len(line_groups)))
gc = 1
for line_group in line_groups:
for dist, ang, x1,y1,w1,h1 in line_group:
print ("GROUP: ", gc, dist, ang, x1,y1,w1,h1)
gc = gc + 1
print ("Stars:", str(len(stars)))
print ("Obj Points:", str(len(obj_points)))
print ("Big Cnts:", str(len(big_cnts)))
print ("Min/Max X/Y:", str(min_x), str(min_y), str(max_x), str(max_y))
print ("-------")
hits = hits + 1
video_report = video_file.replace(".mp4", "-report.txt")
file_exists = Path(video_report)
if (file_exists.is_file()):
print ("Already processed the video.")
#else:
# print("./PV.py " + video_file + " " + cam_num)
# os.system("./PV.py " + video_file + " " + cam_num)
else :
min_x = min_y = max_x = max_y = 0
#cmd = "grep \"Motion Frames:\" `find /mnt/ams2/SD/" + str(cam_num) + " |grep " + report_str + "`"
#output = subprocess.check_output(cmd, shell=True).decode("utf-8")
#output = output.replace("Motion Frames:", "motion_frames=")
#print (output)
#exec(output)
#if len(motion_frames) > 14:
# cmd = "find /mnt/ams2/SD/" + str(cam_num) + " |grep " + video_str
# video_file = subprocess.check_output(cmd, shell=True).decode("utf-8")
# print("This is probably a real event?")
# print(video_file)
sdate = sys.argv[1]
cam_num = sys.argv[2]
diff_stills(sdate, cam_num)
| mikehankey/fireball_camera | scan-stills2.py | Python | gpl-3.0 | 42,716 |
/*
* microMathematics - Extended Visual Calculator
* Copyright (C) 2014-2021 by Mikhail Kulesh
*
* 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.
*/
package com.mkulesh.micromath.properties;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import com.mkulesh.micromath.formula.FormulaList;
import com.mkulesh.micromath.math.AxisTypeConverter;
import com.mkulesh.micromath.plus.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import java.util.Locale;
public class AxisProperties implements Parcelable
{
private static final String XML_PROP_XLABELSNUMBER = "xLabelsNumber";
private static final String XML_PROP_YLABELSNUMBER = "yLabelsNumber";
private static final String XML_PROP_GRIDLINECOLOR = "gridLineColor";
private static final String XML_PROP_XTYPE = "xType";
private static final String XML_PROP_YTYPE = "yType";
public float scaleFactor = 1;
public int gridLineColor = Color.GRAY;
public int xLabelsNumber = 3;
public int yLabelsNumber = 3;
public AxisTypeConverter.Type xType = AxisTypeConverter.Type.LINEAR;
public AxisTypeConverter.Type yType = AxisTypeConverter.Type.LINEAR;
private int labelLineSize = 5;
private int labelTextSize = 20;
private int gridLineWidth = 1;
/**
* Parcelable interface
*/
private AxisProperties(Parcel in)
{
super();
readFromParcel(in);
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeInt(labelLineSize);
dest.writeInt(labelTextSize);
dest.writeInt(gridLineColor);
dest.writeInt(gridLineWidth);
dest.writeInt(xLabelsNumber);
dest.writeInt(yLabelsNumber);
dest.writeInt(xType.ordinal());
dest.writeInt(yType.ordinal());
}
private void readFromParcel(Parcel in)
{
labelLineSize = in.readInt();
labelTextSize = in.readInt();
gridLineColor = in.readInt();
gridLineWidth = in.readInt();
xLabelsNumber = in.readInt();
yLabelsNumber = in.readInt();
xType = AxisTypeConverter.Type.values()[in.readInt()];
yType = AxisTypeConverter.Type.values()[in.readInt()];
}
public static final Parcelable.Creator<AxisProperties> CREATOR = new Parcelable.Creator<AxisProperties>()
{
public AxisProperties createFromParcel(Parcel in)
{
return new AxisProperties(in);
}
public AxisProperties[] newArray(int size)
{
return new AxisProperties[size];
}
};
/**
* Default constructor
*/
public AxisProperties()
{
// empty
}
public void assign(AxisProperties a)
{
scaleFactor = a.scaleFactor;
gridLineColor = a.gridLineColor;
xLabelsNumber = a.xLabelsNumber;
yLabelsNumber = a.yLabelsNumber;
labelLineSize = a.labelLineSize;
labelTextSize = a.labelTextSize;
gridLineWidth = a.gridLineWidth;
xType = a.xType;
yType = a.yType;
}
public void initialize(TypedArray a)
{
labelLineSize = a.getDimensionPixelSize(R.styleable.PlotViewExtension_labelLineSize, labelLineSize);
labelTextSize = a.getDimensionPixelSize(R.styleable.PlotViewExtension_labelTextSize, labelTextSize);
gridLineColor = a.getColor(R.styleable.PlotViewExtension_gridLineColor, gridLineColor);
gridLineWidth = a.getDimensionPixelSize(R.styleable.PlotViewExtension_gridLineWidth, gridLineWidth);
xLabelsNumber = a.getInt(R.styleable.PlotViewExtension_xLabelsNumber, xLabelsNumber);
yLabelsNumber = a.getInt(R.styleable.PlotViewExtension_yLabelsNumber, yLabelsNumber);
xType = AxisTypeConverter.Type.LINEAR;
yType = AxisTypeConverter.Type.LINEAR;
}
public void readFromXml(XmlPullParser parser)
{
String attr = parser.getAttributeValue(null, XML_PROP_XLABELSNUMBER);
if (attr != null)
{
xLabelsNumber = Integer.parseInt(attr);
}
attr = parser.getAttributeValue(null, XML_PROP_YLABELSNUMBER);
if (attr != null)
{
yLabelsNumber = Integer.parseInt(attr);
}
attr = parser.getAttributeValue(null, XML_PROP_GRIDLINECOLOR);
if (attr != null)
{
gridLineColor = Color.parseColor(attr);
}
attr = parser.getAttributeValue(null, XML_PROP_XTYPE);
if (attr != null)
{
try
{
xType = AxisTypeConverter.Type.valueOf(attr.toUpperCase(Locale.ENGLISH));
}
catch (Exception e)
{
// nothing to do
}
}
attr = parser.getAttributeValue(null, XML_PROP_YTYPE);
if (attr != null)
{
try
{
yType = AxisTypeConverter.Type.valueOf(attr.toUpperCase(Locale.ENGLISH));
}
catch (Exception e)
{
// nothing to do
}
}
}
public void writeToXml(XmlSerializer serializer) throws Exception
{
serializer.attribute(FormulaList.XML_NS, XML_PROP_XLABELSNUMBER, String.valueOf(xLabelsNumber));
serializer.attribute(FormulaList.XML_NS, XML_PROP_YLABELSNUMBER, String.valueOf(yLabelsNumber));
serializer.attribute(FormulaList.XML_NS, XML_PROP_GRIDLINECOLOR, String.format("#%08X", gridLineColor));
serializer.attribute(FormulaList.XML_NS, XML_PROP_XTYPE, xType.toString().toLowerCase(Locale.ENGLISH));
serializer.attribute(FormulaList.XML_NS, XML_PROP_YTYPE, yType.toString().toLowerCase(Locale.ENGLISH));
}
public int getLabelLineSize()
{
return Math.round(labelLineSize * scaleFactor);
}
public int getLabelTextSize()
{
return Math.round(labelTextSize * scaleFactor);
}
public int getGridLineWidth()
{
return Math.round(gridLineWidth * scaleFactor);
}
}
| mkulesh/microMathematics | app/src/main/java/com/mkulesh/micromath/properties/AxisProperties.java | Java | gpl-3.0 | 6,711 |
from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
| rodgzilla/project-euler | problem_070/problem.py | Python | gpl-3.0 | 895 |
# ===============================================================================
# Copyright (C) 2010 Diego Duclos
#
# This file is part of eos.
#
# eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# eos 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 eos. If not, see <http://www.gnu.org/licenses/>.
# ===============================================================================
from sqlalchemy import Column, String, Integer, Boolean, ForeignKey, Table, Float
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relation, mapper, synonym, deferred
from sqlalchemy.orm.collections import attribute_mapped_collection
from eos.db import gamedata_meta
from eos.types import Icon, Attribute, Item, Effect, MetaType, Group, Traits
items_table = Table("invtypes", gamedata_meta,
Column("typeID", Integer, primary_key=True),
Column("typeName", String, index=True),
Column("description", String),
Column("raceID", Integer),
Column("factionID", Integer),
Column("volume", Float),
Column("mass", Float),
Column("capacity", Float),
Column("published", Boolean),
Column("marketGroupID", Integer, ForeignKey("invmarketgroups.marketGroupID")),
Column("iconID", Integer, ForeignKey("icons.iconID")),
Column("groupID", Integer, ForeignKey("invgroups.groupID"), index=True))
from .metaGroup import metatypes_table # noqa
from .traits import traits_table # noqa
mapper(Item, items_table,
properties={"group": relation(Group, backref="items"),
"icon": relation(Icon),
"_Item__attributes": relation(Attribute, collection_class=attribute_mapped_collection('name')),
"effects": relation(Effect, collection_class=attribute_mapped_collection('name')),
"metaGroup": relation(MetaType,
primaryjoin=metatypes_table.c.typeID == items_table.c.typeID,
uselist=False),
"ID": synonym("typeID"),
"name": synonym("typeName"),
"description": deferred(items_table.c.description),
"traits": relation(Traits,
primaryjoin=traits_table.c.typeID == items_table.c.typeID,
uselist=False)
})
Item.category = association_proxy("group", "category")
| Ebag333/Pyfa | eos/db/gamedata/item.py | Python | gpl-3.0 | 3,101 |
using System.Collections.Generic;
using CacheUtils.TranscriptCache.Comparers;
using ErrorHandling.Exceptions;
using VariantAnnotation.Interface.AnnotatedPositions;
namespace CacheUtils.Commands.GFF
{
public static class InternalGenes
{
public static IDictionary<IGene, int> CreateDictionary(IGene[] genes)
{
var geneComparer = new GeneComparer();
var geneToInternalId = new Dictionary<IGene, int>(geneComparer);
for (var geneIndex = 0; geneIndex < genes.Length; geneIndex++)
{
var gene = genes[geneIndex];
if (geneToInternalId.TryGetValue(gene, out int oldGeneIndex))
{
throw new UserErrorException($"Found a duplicate gene in the dictionary: {genes[geneIndex]} ({geneIndex} vs {oldGeneIndex})");
}
geneToInternalId[gene] = geneIndex;
}
return geneToInternalId;
}
}
}
| Illumina/Nirvana | CacheUtils/Commands/GFF/InternalGenes.cs | C# | gpl-3.0 | 1,018 |
package org.cleverframe.sys.controller;
import org.cleverframe.common.controller.BaseController;
import org.cleverframe.common.mapper.BeanMapper;
import org.cleverframe.common.persistence.Page;
import org.cleverframe.common.vo.response.AjaxMessage;
import org.cleverframe.sys.SysBeanNames;
import org.cleverframe.sys.SysJspUrlPath;
import org.cleverframe.sys.entity.Menu;
import org.cleverframe.sys.service.MenuService;
import org.cleverframe.sys.vo.request.*;
import org.cleverframe.webui.easyui.data.DataGridJson;
import org.cleverframe.webui.easyui.data.TreeGridNodeJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* Controller
* <p>
* 作者:LiZW <br/>
* 创建时间:2016-08-24 22:47:29 <br/>
*/
@SuppressWarnings("MVCPathVariableInspection")
@Controller
@RequestMapping(value = "/${base.mvcPath}/sys/menu")
public class MenuController extends BaseController {
@Autowired
@Qualifier(SysBeanNames.MenuService)
private MenuService menuService;
@RequestMapping("/Menu" + VIEW_PAGE_SUFFIX)
public ModelAndView getMenuJsp(HttpServletRequest request, HttpServletResponse response) {
return new ModelAndView(SysJspUrlPath.Menu);
}
/**
* 分页查询
*/
@RequestMapping("/findByPage")
@ResponseBody
public DataGridJson<Menu> findByPage(
HttpServletRequest request,
HttpServletResponse response,
@Valid MenuQueryVo menuQueryVo,
BindingResult bindingResult) {
DataGridJson<Menu> json = new DataGridJson<>();
Page<Menu> page = menuService.findByPage(new Page<>(request, response), menuQueryVo.getMenuType(), menuQueryVo.getName(), menuQueryVo.getOpenMode());
json.setRows(page.getList());
json.setTotal(page.getCount());
return json;
}
/**
* 查询所有菜单类型
*/
@RequestMapping("/findAllMenuType")
@ResponseBody
public List<Map<String, Object>> findAllMenuType(HttpServletRequest request, HttpServletResponse response) {
return menuService.findAllMenuType();
}
/**
* 查询菜单树
*/
@RequestMapping("/findMenuTreeByType")
@ResponseBody
public Object findMenuTreeByType(
HttpServletRequest request,
HttpServletResponse response,
@Valid MenuTreeQueryVo menuTreeQueryVo,
BindingResult bindingResult) {
AjaxMessage<String> message = new AjaxMessage<>(true, "查询菜单树成功", null);
if (!beanValidator(bindingResult, message)) {
return message;
}
DataGridJson<TreeGridNodeJson<Menu>> treeGrid = new DataGridJson<>();
List<Menu> menuList = menuService.findMenuByType(menuTreeQueryVo.getMenuType());
for (Menu menu : menuList) {
TreeGridNodeJson<Menu> node = new TreeGridNodeJson<>(menu.getParentId(), menu);
treeGrid.addRow(node);
}
return treeGrid;
}
/**
* 增加菜单信息
*/
@RequestMapping("/addMenu")
@ResponseBody
public AjaxMessage<String> addMenu(
HttpServletRequest request,
HttpServletResponse response,
@Valid MenuAddVo menuAddVo,
BindingResult bindingResult) {
AjaxMessage<String> message = new AjaxMessage<>(true, "新增菜单成功", null);
if (beanValidator(bindingResult, message)) {
Menu menu = BeanMapper.mapper(menuAddVo, Menu.class);
menuService.saveMenu(message, menu);
}
return message;
}
/**
* 更新菜单信息
*/
@RequestMapping("/updateMenu")
@ResponseBody
public AjaxMessage<String> updateMenu(
HttpServletRequest request,
HttpServletResponse response,
@Valid MenuUpdateVo menuUpdateVo,
BindingResult bindingResult) {
AjaxMessage<String> message = new AjaxMessage<>(true, "更新菜单成功", null);
if (beanValidator(bindingResult, message)) {
Menu menu = BeanMapper.mapper(menuUpdateVo, Menu.class);
if (!menuService.updateMenu(menu)) {
message.setSuccess(false);
message.setFailMessage("更新菜单失败");
}
}
return message;
}
/**
* 删除菜单
*/
@RequestMapping("/deleteMenu")
@ResponseBody
public AjaxMessage<String> deleteMenu(
HttpServletRequest request,
HttpServletResponse response,
@Valid MenuDeleteVo menuDeleteVoe,
BindingResult bindingResult) {
AjaxMessage<String> message = new AjaxMessage<>(true, "删除菜单成功", null);
if (beanValidator(bindingResult, message)) {
menuService.deleteMenu(message, menuDeleteVoe.getId());
}
return message;
}
}
| Lzw2016/cleverframe | clever-sys/src/main/java/org/cleverframe/sys/controller/MenuController.java | Java | gpl-3.0 | 5,364 |
<?php
namespace App\Models;
use Zizaco\Entrust\EntrustRole;
final class Role extends EntrustRole
{
protected $table = 'roles';
protected $hidden = ['id', 'description', 'updated_at', 'created_at', 'pivot'];
protected $appends = array('role_id');
protected $fillable = ['name', 'display_name', 'description'];
public function permissions()
{
return $this->belongsToMany(Permission::class, 'permission_role', 'role_id', 'permission_id');
}
public function getRoleIdAttribute()
{
return $this->attributes['id'];
}
}
| faiverson/prode | api/app/Models/Role.php | PHP | gpl-3.0 | 533 |
Vue.component('snackbar', require('./components/material/snackbar.vue'));
Vue.component('show-snackbar', require('./components/material/show-snackbar.vue'));
| authv/authv | resources/assets/js/authv.js | JavaScript | gpl-3.0 | 159 |
package com.technode.terrafirmastuff.core.proxy;
import com.bioxx.tfc.api.Tools.ChiselManager;
import com.technode.terrafirmastuff.handler.ServerTickHandler;
import com.technode.terrafirmastuff.tileentity.TEOilLampMod;
import com.technode.terrafirmastuff.tools.ChiselMode_Chiseled;
import com.technode.terrafirmastuff.tools.ChiselMode_Circle;
import com.technode.terrafirmastuff.tools.ChiselMode_Paver;
import com.technode.terrafirmastuff.tools.ChiselMode_Pillar;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.registry.GameRegistry;
public abstract class CommonProxy
{
public void registerChiselModes()
{
ChiselManager.getInstance().addChiselMode(new ChiselMode_Paver("Paver"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Circle("Circle"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Chiseled("Chiseled"));
ChiselManager.getInstance().addChiselMode(new ChiselMode_Pillar("Pillar"));
}
public void hideNEIItems() {}
public void registerRenderInformation()
{
// NOOP on server
}
public void registerWailaClasses()
{
FMLInterModComms.sendMessage("Waila", "register", "com.technode.terrafirmastuff.core.compat.WAILADataMod.onCallbackRegister");// Block
}
public void registerTileEntities(boolean b)
{
GameRegistry.registerTileEntity(TEOilLampMod.class, "Oil Lamp Mod");
}
public void registerTickHandler()
{
FMLCommonHandler.instance().bus().register(new ServerTickHandler());
}
}
| Bunsan/TerraFirmaStuff | src/main/java/com/technode/terrafirmastuff/core/proxy/CommonProxy.java | Java | gpl-3.0 | 1,619 |
/*
* LibrePCB - Professional EDA for everyone!
* Copyright (C) 2013 LibrePCB Developers, see AUTHORS.md for contributors.
* https://librepcb.org/
*
* 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/>.
*/
/*******************************************************************************
* Includes
******************************************************************************/
#include "cmdboardpolygonremove.h"
#include "../board.h"
#include "../items/bi_polygon.h"
#include <QtCore>
/*******************************************************************************
* Namespace
******************************************************************************/
namespace librepcb {
namespace project {
/*******************************************************************************
* Constructors / Destructor
******************************************************************************/
CmdBoardPolygonRemove::CmdBoardPolygonRemove(BI_Polygon& polygon) noexcept
: UndoCommand(tr("Remove polygon from board")),
mBoard(polygon.getBoard()),
mPolygon(polygon) {
}
CmdBoardPolygonRemove::~CmdBoardPolygonRemove() noexcept {
}
/*******************************************************************************
* Inherited from UndoCommand
******************************************************************************/
bool CmdBoardPolygonRemove::performExecute() {
performRedo(); // can throw
return true;
}
void CmdBoardPolygonRemove::performUndo() {
mBoard.addPolygon(mPolygon); // can throw
}
void CmdBoardPolygonRemove::performRedo() {
mBoard.removePolygon(mPolygon); // can throw
}
/*******************************************************************************
* End of File
******************************************************************************/
} // namespace project
} // namespace librepcb
| rnestler/LibrePCB | libs/librepcb/project/boards/cmd/cmdboardpolygonremove.cpp | C++ | gpl-3.0 | 2,452 |
/* -*- Mode: C++; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 2 -*- */
/*
* generallayout.h
* Copyright (C) 2015 Dejardin Gilbert <dejarding@gmail.com>
*
* audio 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.
*
* audio 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 _GENERALLAYOUT_H_
#define _GENERALLAYOUT_H_
#include <list>
#include <gtkmm/drawingarea.h>
#include "generalmodule.hpp"
//#include "vector2D.hpp"
class GeneralLayout: public Gtk::DrawingArea
{
public:
GeneralLayout();
virtual ~GeneralLayout();
void randomAllModulePosition();
std::list<GeneralModule*> mGMs;
protected:
virtual bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr);
bool on_timeout();
private:
double mZoom;
bool mautoZoom;
Vector2D mPan;
bool mautoPan;
};
#endif // _GENERALLAYOUT_H_
| Dagal/DagalTone | src/generallayout.hpp | C++ | gpl-3.0 | 1,330 |
Bitrix 16.5 Business Demo = 8363d6b7acdc0ffe32d47cf7b8ca36d0
Bitrix 17.0.9 Business Demo = ea7195812c63ac17d4ca29504d832888
| gohdan/DFC | known_files/hashes/bitrix/modules/sale/tools/basket_discount_convert.php | PHP | gpl-3.0 | 124 |
package com.aliyun.api.ess.ess20140828.response;
import com.aliyun.api.AliyunResponse;
import com.taobao.api.internal.mapping.ApiField;
/**
* TOP API: ess.aliyuncs.com.DetachInstances.2014-08-28 response.
*
* @author auto create
* @since 1.0, null
*/
public class DetachInstancesResponse extends AliyunResponse {
private static final long serialVersionUID = 3317111479582962569L;
/**
* 1
*/
@ApiField("RequestId")
private String requestId;
/**
* 伸缩活动id
*/
@ApiField("ScalingActivityId")
private String scalingActivityId;
public String getRequestId() {
return this.requestId;
}
public String getScalingActivityId() {
return this.scalingActivityId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public void setScalingActivityId(String scalingActivityId) {
this.scalingActivityId = scalingActivityId;
}
}
| kuiwang/my-dev | src/main/java/com/aliyun/api/ess/ess20140828/response/DetachInstancesResponse.java | Java | gpl-3.0 | 969 |
#!/usr/bin/env python
"""
A pure python ping implementation using raw socket.
Note that ICMP messages can only be sent from processes running as root.
Derived from ping.c distributed in Linux's netkit. That code is
copyright (c) 1989 by The Regents of the University of California.
That code is in turn derived from code written by Mike Muuss of the
US Army Ballistic Research Laboratory in December, 1983 and
placed in the public domain. They have my thanks.
Bugs are naturally mine. I'd be glad to hear about them. There are
certainly word - size dependenceies here.
Copyright (c) Matthew Dixon Cowles, <http://www.visi.com/~mdc/>.
Distributable under the terms of the GNU General Public License
version 2. Provided with no warranties of any sort.
Original Version from Matthew Dixon Cowles:
-> ftp://ftp.visi.com/users/mdc/ping.py
Rewrite by Jens Diemer:
-> http://www.python-forum.de/post-69122.html#69122
Rewrite by George Notaras:
-> http://www.g-loaded.eu/2009/10/30/python-ping/
Revision history
~~~~~~~~~~~~~~~~
November 8, 2009
----------------
Improved compatibility with GNU/Linux systems.
Fixes by:
* George Notaras -- http://www.g-loaded.eu
Reported by:
* Chris Hallman -- http://cdhallman.blogspot.com
Changes in this release:
- Re-use time.time() instead of time.clock(). The 2007 implementation
worked only under Microsoft Windows. Failed on GNU/Linux.
time.clock() behaves differently under the two OSes[1].
[1] http://docs.python.org/library/time.html#time.clock
May 30, 2007
------------
little rewrite by Jens Diemer:
- change socket asterisk import to a normal import
- replace time.time() with time.clock()
- delete "return None" (or change to "return" only)
- in checksum() rename "str" to "source_string"
November 22, 1997
-----------------
Initial hack. Doesn't do much, but rather than try to guess
what features I (or others) will want in the future, I've only
put in what I need now.
December 16, 1997
-----------------
For some reason, the checksum bytes are in the wrong order when
this is run under Solaris 2.X for SPARC but it works right under
Linux x86. Since I don't know just what's wrong, I'll swap the
bytes always and then do an htons().
December 4, 2000
----------------
Changed the struct.pack() calls to pack the checksum and ID as
unsigned. My thanks to Jerome Poincheval for the fix.
Last commit info:
~~~~~~~~~~~~~~~~~
$LastChangedDate: $
$Rev: $
$Author: $
"""
import os, socket, struct, select, time
# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
def checksum(source_string):
"""
I'm not too confident that this is right but testing seems
to suggest that it gives the same answers as in_cksum in ping.c
"""
sum = 0
countTo = (len(source_string)/2)*2
count = 0
while count<countTo:
thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
sum = sum + thisVal
sum = sum & 0xffffffff # Necessary?
count = count + 2
if countTo<len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff # Necessary?
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
# Swap bytes. Bugger me if I know why.
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def receive_one_ping(my_socket, ID, timeout):
"""
receive the ping from the socket.
"""
timeLeft = timeout
while True:
startedSelect = time.time()
whatReady = select.select([my_socket], [], [], timeLeft)
howLongInSelect = (time.time() - startedSelect)
if whatReady[0] == []: # Timeout
return
timeReceived = time.time()
recPacket, addr = my_socket.recvfrom(1024)
icmpHeader = recPacket[20:28]
type, code, checksum, packetID, sequence = struct.unpack(
"bbHHh", icmpHeader
)
if packetID == ID:
bytesInDouble = struct.calcsize("d")
timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
return timeReceived - timeSent
timeLeft = timeLeft - howLongInSelect
if timeLeft <= 0:
return
def send_one_ping(my_socket, dest_addr, ID):
"""
Send one ping to the given >dest_addr<.
"""
dest_addr = socket.gethostbyname(dest_addr)
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
my_checksum = 0
# Make a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytesInDouble = struct.calcsize("d")
data = (192 - bytesInDouble) * "Q"
data = struct.pack("d", time.time()) + data
# Calculate the checksum on the data and the dummy header.
my_checksum = checksum(header + data)
# Now that we have the right checksum, we put that in. It's just easier
# to make up a new header than to stuff it into the dummy.
header = struct.pack(
"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
)
packet = header + data
my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
def do_one(dest_addr, timeout):
"""
Returns either the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error, (errno, msg):
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
send_one_ping(my_socket, dest_addr, my_ID)
delay = receive_one_ping(my_socket, my_ID, timeout)
my_socket.close()
return delay
def verbose_ping(dest_addr, timeout = 2, count = 4):
"""
Send >count< ping to >dest_addr< with the given >timeout< and display
the result.
"""
for i in xrange(count):
print "ping %s..." % dest_addr,
try:
delay = do_one(dest_addr, timeout)
except socket.gaierror, e:
print "failed. (socket error: '%s')" % e[1]
break
if delay == None:
print "failed. (timeout within %ssec.)" % timeout
else:
delay = delay * 1000
print "get ping in %0.4fms" % delay
print
if __name__ == '__main__':
#verbose_ping("192.168.0.4",timeout=0.1,count=1)
result=do_one("192.168.0.4", 0.1)
print result
| jredrejo/controlaula | Backend/src/ControlAula/Utils/ping.py | Python | gpl-3.0 | 7,021 |
#!/usr/bin/python
from src.sqllist import GLOBALS
class BasicResolver(object):
"""General resolver class"""
def __init__(self, conn=None):
self.conn = conn
pass
def resolve(self, detections, sources):
"""Template resolve function.
Returns resolution status and an array of xtrsrcid-runcatid of
resolved pairs (if possible)."""
return False, []
def load_detections(self, group_id):
cursor = self.conn.get_cursor("""
select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err
from extractedsources e
where e.image_id = %s
and exists (select 1 from temp_associations ta
where ta.xtrsrc_id2 = e.xtrsrcid
and ta.image_id = e.image_id
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
detections = cursor.fetchall()
cursor.close()
return detections
def load_sources(self, group_id):
cursor = self.conn.get_cursor("""
select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err
from runningcatalog r,
runningcatalog_fluxes f,
images i
where i.imageid = %s
and f.band = i.band
and f.stokes = i.stokes
and r.runcatid = f.runcat_id
and exists (select 1 from temp_associations ta
where ta.runcat_id = r.runcatid
and ta.image_id = i.imageid
and ta.group_head_id = %s)""" % (GLOBALS['i'], group_id))
sources = cursor.fetchall()
cursor.close()
return sources
def run_resolve(self, group_id):
"""Get data from Database,
run resolver,
saev results to temp_associations"""
#--Run resolver--
is_ok, solutions = self.resolve(self.load_detections(group_id),
self.load_sources(group_id))
if is_ok:
#"delete" all associations from this group.
self.conn.execute("""
update temp_associations
set kind = -1
where image_id = %s
and group_head_id = %s;""" % (GLOBALS['i'], group_id))
#"restore" associations that are "ok"
for solution in solutions:
self.conn.execute("""update temp_associations
set kind = 1,
group_head_id = null
where image_id = %s
and group_head_id = %s
and xtrsrc_id2 = %s
and runcat_id = %s;""" % (GLOBALS['i'], group_id,
solution[0], solution[1]))
return is_ok
| jjdmol/LOFAR | CEP/GSM/bremen/src/resolve.py | Python | gpl-3.0 | 2,496 |
package net.minecraft.client.gui;
import java.io.IOException;
import java.util.Random;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.world.GameType;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.storage.ISaveFormat;
import net.minecraft.world.storage.WorldInfo;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard;
public class GuiCreateWorld extends GuiScreen
{
private final GuiScreen parentScreen;
private GuiTextField worldNameField;
private GuiTextField worldSeedField;
private String saveDirName;
private String gameMode = "survival";
/**
* Used to save away the game mode when the current "debug" world type is chosen (forcing it to spectator mode)
*/
private String savedGameMode;
private boolean generateStructuresEnabled = true;
/** If cheats are allowed */
private boolean allowCheats;
/**
* User explicitly clicked "Allow Cheats" at some point
* Prevents value changes due to changing game mode
*/
private boolean allowCheatsWasSetByUser;
private boolean bonusChestEnabled;
/** Set to true when "hardcore" is the currently-selected gamemode */
private boolean hardCoreMode;
private boolean alreadyGenerated;
private boolean inMoreWorldOptionsDisplay;
private GuiButton btnGameMode;
private GuiButton btnMoreOptions;
private GuiButton btnMapFeatures;
private GuiButton btnBonusItems;
private GuiButton btnMapType;
private GuiButton btnAllowCommands;
private GuiButton btnCustomizeType;
private String gameModeDesc1;
private String gameModeDesc2;
private String worldSeed;
private String worldName;
private int selectedIndex;
public String chunkProviderSettingsJson = "";
/** These filenames are known to be restricted on one or more OS's. */
private static final String[] DISALLOWED_FILENAMES = new String[] {"CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"};
public GuiCreateWorld(GuiScreen p_i46320_1_)
{
this.parentScreen = p_i46320_1_;
this.worldSeed = "";
this.worldName = I18n.format("selectWorld.newWorld", new Object[0]);
}
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
this.worldNameField.updateCursorCounter();
this.worldSeedField.updateCursorCounter();
}
/**
* Adds the buttons (and other controls) to the screen in question. Called when the GUI is displayed and when the
* window resizes, the buttonList is cleared beforehand.
*/
public void initGui()
{
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, I18n.format("selectWorld.create", new Object[0])));
this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, I18n.format("gui.cancel", new Object[0])));
this.btnGameMode = this.func_189646_b(new GuiButton(2, this.width / 2 - 75, 115, 150, 20, I18n.format("selectWorld.gameMode", new Object[0])));
this.btnMoreOptions = this.func_189646_b(new GuiButton(3, this.width / 2 - 75, 187, 150, 20, I18n.format("selectWorld.moreWorldOptions", new Object[0])));
this.btnMapFeatures = this.func_189646_b(new GuiButton(4, this.width / 2 - 155, 100, 150, 20, I18n.format("selectWorld.mapFeatures", new Object[0])));
this.btnMapFeatures.visible = false;
this.btnBonusItems = this.func_189646_b(new GuiButton(7, this.width / 2 + 5, 151, 150, 20, I18n.format("selectWorld.bonusItems", new Object[0])));
this.btnBonusItems.visible = false;
this.btnMapType = this.func_189646_b(new GuiButton(5, this.width / 2 + 5, 100, 150, 20, I18n.format("selectWorld.mapType", new Object[0])));
this.btnMapType.visible = false;
this.btnAllowCommands = this.func_189646_b(new GuiButton(6, this.width / 2 - 155, 151, 150, 20, I18n.format("selectWorld.allowCommands", new Object[0])));
this.btnAllowCommands.visible = false;
this.btnCustomizeType = this.func_189646_b(new GuiButton(8, this.width / 2 + 5, 120, 150, 20, I18n.format("selectWorld.customizeType", new Object[0])));
this.btnCustomizeType.visible = false;
this.worldNameField = new GuiTextField(9, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20);
this.worldNameField.setFocused(true);
this.worldNameField.setText(this.worldName);
this.worldSeedField = new GuiTextField(10, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20);
this.worldSeedField.setText(this.worldSeed);
this.showMoreWorldOptions(this.inMoreWorldOptionsDisplay);
this.calcSaveDirName();
this.updateDisplayState();
}
/**
* Determine a save-directory name from the world name
*/
private void calcSaveDirName()
{
this.saveDirName = this.worldNameField.getText().trim();
for (char c0 : ChatAllowedCharacters.ILLEGAL_FILE_CHARACTERS)
{
this.saveDirName = this.saveDirName.replace(c0, '_');
}
if (StringUtils.isEmpty(this.saveDirName))
{
this.saveDirName = "World";
}
this.saveDirName = getUncollidingSaveDirName(this.mc.getSaveLoader(), this.saveDirName);
}
/**
* Sets displayed GUI elements according to the current settings state
*/
private void updateDisplayState()
{
this.btnGameMode.displayString = I18n.format("selectWorld.gameMode", new Object[0]) + ": " + I18n.format("selectWorld.gameMode." + this.gameMode, new Object[0]);
this.gameModeDesc1 = I18n.format("selectWorld.gameMode." + this.gameMode + ".line1", new Object[0]);
this.gameModeDesc2 = I18n.format("selectWorld.gameMode." + this.gameMode + ".line2", new Object[0]);
this.btnMapFeatures.displayString = I18n.format("selectWorld.mapFeatures", new Object[0]) + " ";
if (this.generateStructuresEnabled)
{
this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + I18n.format("options.on", new Object[0]);
}
else
{
this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + I18n.format("options.off", new Object[0]);
}
this.btnBonusItems.displayString = I18n.format("selectWorld.bonusItems", new Object[0]) + " ";
if (this.bonusChestEnabled && !this.hardCoreMode)
{
this.btnBonusItems.displayString = this.btnBonusItems.displayString + I18n.format("options.on", new Object[0]);
}
else
{
this.btnBonusItems.displayString = this.btnBonusItems.displayString + I18n.format("options.off", new Object[0]);
}
this.btnMapType.displayString = I18n.format("selectWorld.mapType", new Object[0]) + " " + I18n.format(WorldType.WORLD_TYPES[this.selectedIndex].getTranslateName(), new Object[0]);
this.btnAllowCommands.displayString = I18n.format("selectWorld.allowCommands", new Object[0]) + " ";
if (this.allowCheats && !this.hardCoreMode)
{
this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + I18n.format("options.on", new Object[0]);
}
else
{
this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + I18n.format("options.off", new Object[0]);
}
}
/**
* Ensures that a proposed directory name doesn't collide with existing names.
* Returns the name, possibly modified to avoid collisions.
*/
public static String getUncollidingSaveDirName(ISaveFormat saveLoader, String name)
{
name = name.replaceAll("[\\./\"]", "_");
for (String s : DISALLOWED_FILENAMES)
{
if (name.equalsIgnoreCase(s))
{
name = "_" + name + "_";
}
}
while (saveLoader.getWorldInfo(name) != null)
{
name = name + "-";
}
return name;
}
/**
* Called when the screen is unloaded. Used to disable keyboard repeat events
*/
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
*/
protected void actionPerformed(GuiButton button) throws IOException
{
if (button.enabled)
{
if (button.id == 1)
{
this.mc.displayGuiScreen(this.parentScreen);
}
else if (button.id == 0)
{
this.mc.displayGuiScreen((GuiScreen)null);
if (this.alreadyGenerated)
{
return;
}
this.alreadyGenerated = true;
long i = (new Random()).nextLong();
String s = this.worldSeedField.getText();
if (!StringUtils.isEmpty(s))
{
try
{
long j = Long.parseLong(s);
if (j != 0L)
{
i = j;
}
}
catch (NumberFormatException var7)
{
i = (long)s.hashCode();
}
}
WorldSettings worldsettings = new WorldSettings(i, GameType.getByName(this.gameMode), this.generateStructuresEnabled, this.hardCoreMode, WorldType.WORLD_TYPES[this.selectedIndex]);
worldsettings.setGeneratorOptions(this.chunkProviderSettingsJson);
if (this.bonusChestEnabled && !this.hardCoreMode)
{
worldsettings.enableBonusChest();
}
if (this.allowCheats && !this.hardCoreMode)
{
worldsettings.enableCommands();
}
this.mc.launchIntegratedServer(this.saveDirName, this.worldNameField.getText().trim(), worldsettings);
}
else if (button.id == 3)
{
this.toggleMoreWorldOptions();
}
else if (button.id == 2)
{
if ("survival".equals(this.gameMode))
{
if (!this.allowCheatsWasSetByUser)
{
this.allowCheats = false;
}
this.hardCoreMode = false;
this.gameMode = "hardcore";
this.hardCoreMode = true;
this.btnAllowCommands.enabled = false;
this.btnBonusItems.enabled = false;
this.updateDisplayState();
}
else if ("hardcore".equals(this.gameMode))
{
if (!this.allowCheatsWasSetByUser)
{
this.allowCheats = true;
}
this.hardCoreMode = false;
this.gameMode = "creative";
this.updateDisplayState();
this.hardCoreMode = false;
this.btnAllowCommands.enabled = true;
this.btnBonusItems.enabled = true;
}
else
{
if (!this.allowCheatsWasSetByUser)
{
this.allowCheats = false;
}
this.gameMode = "survival";
this.updateDisplayState();
this.btnAllowCommands.enabled = true;
this.btnBonusItems.enabled = true;
this.hardCoreMode = false;
}
this.updateDisplayState();
}
else if (button.id == 4)
{
this.generateStructuresEnabled = !this.generateStructuresEnabled;
this.updateDisplayState();
}
else if (button.id == 7)
{
this.bonusChestEnabled = !this.bonusChestEnabled;
this.updateDisplayState();
}
else if (button.id == 5)
{
++this.selectedIndex;
if (this.selectedIndex >= WorldType.WORLD_TYPES.length)
{
this.selectedIndex = 0;
}
while (!this.canSelectCurWorldType())
{
++this.selectedIndex;
if (this.selectedIndex >= WorldType.WORLD_TYPES.length)
{
this.selectedIndex = 0;
}
}
this.chunkProviderSettingsJson = "";
this.updateDisplayState();
this.showMoreWorldOptions(this.inMoreWorldOptionsDisplay);
}
else if (button.id == 6)
{
this.allowCheatsWasSetByUser = true;
this.allowCheats = !this.allowCheats;
this.updateDisplayState();
}
else if (button.id == 8)
{
if (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.FLAT)
{
this.mc.displayGuiScreen(new GuiCreateFlatWorld(this, this.chunkProviderSettingsJson));
}
else
{
this.mc.displayGuiScreen(new GuiCustomizeWorldScreen(this, this.chunkProviderSettingsJson));
}
}
}
}
/**
* Returns whether the currently-selected world type is actually acceptable for selection
* Used to hide the "debug" world type unless the shift key is depressed.
*/
private boolean canSelectCurWorldType()
{
WorldType worldtype = WorldType.WORLD_TYPES[this.selectedIndex];
return worldtype != null && worldtype.getCanBeCreated() ? (worldtype == WorldType.DEBUG_WORLD ? isShiftKeyDown() : true) : false;
}
/**
* Toggles between initial world-creation display, and "more options" display.
* Called when user clicks "More World Options..." or "Done" (same button, different labels depending on current
* display).
*/
private void toggleMoreWorldOptions()
{
this.showMoreWorldOptions(!this.inMoreWorldOptionsDisplay);
}
/**
* Shows additional world-creation options if toggle is true, otherwise shows main world-creation elements
*/
private void showMoreWorldOptions(boolean toggle)
{
this.inMoreWorldOptionsDisplay = toggle;
if (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.DEBUG_WORLD)
{
this.btnGameMode.visible = !this.inMoreWorldOptionsDisplay;
this.btnGameMode.enabled = false;
if (this.savedGameMode == null)
{
this.savedGameMode = this.gameMode;
}
this.gameMode = "spectator";
this.btnMapFeatures.visible = false;
this.btnBonusItems.visible = false;
this.btnMapType.visible = this.inMoreWorldOptionsDisplay;
this.btnAllowCommands.visible = false;
this.btnCustomizeType.visible = false;
}
else
{
this.btnGameMode.visible = !this.inMoreWorldOptionsDisplay;
this.btnGameMode.enabled = true;
if (this.savedGameMode != null)
{
this.gameMode = this.savedGameMode;
this.savedGameMode = null;
}
this.btnMapFeatures.visible = this.inMoreWorldOptionsDisplay && WorldType.WORLD_TYPES[this.selectedIndex] != WorldType.CUSTOMIZED;
this.btnBonusItems.visible = this.inMoreWorldOptionsDisplay;
this.btnMapType.visible = this.inMoreWorldOptionsDisplay;
this.btnAllowCommands.visible = this.inMoreWorldOptionsDisplay;
this.btnCustomizeType.visible = this.inMoreWorldOptionsDisplay && (WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.FLAT || WorldType.WORLD_TYPES[this.selectedIndex] == WorldType.CUSTOMIZED);
}
this.updateDisplayState();
if (this.inMoreWorldOptionsDisplay)
{
this.btnMoreOptions.displayString = I18n.format("gui.done", new Object[0]);
}
else
{
this.btnMoreOptions.displayString = I18n.format("selectWorld.moreWorldOptions", new Object[0]);
}
}
/**
* Fired when a key is typed (except F11 which toggles full screen). This is the equivalent of
* KeyListener.keyTyped(KeyEvent e). Args : character (character on the key), keyCode (lwjgl Keyboard key code)
*/
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (this.worldNameField.isFocused() && !this.inMoreWorldOptionsDisplay)
{
this.worldNameField.textboxKeyTyped(typedChar, keyCode);
this.worldName = this.worldNameField.getText();
}
else if (this.worldSeedField.isFocused() && this.inMoreWorldOptionsDisplay)
{
this.worldSeedField.textboxKeyTyped(typedChar, keyCode);
this.worldSeed = this.worldSeedField.getText();
}
if (keyCode == 28 || keyCode == 156)
{
this.actionPerformed((GuiButton)this.buttonList.get(0));
}
((GuiButton)this.buttonList.get(0)).enabled = !this.worldNameField.getText().isEmpty();
this.calcSaveDirName();
}
/**
* Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton
*/
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
super.mouseClicked(mouseX, mouseY, mouseButton);
if (this.inMoreWorldOptionsDisplay)
{
this.worldSeedField.mouseClicked(mouseX, mouseY, mouseButton);
}
else
{
this.worldNameField.mouseClicked(mouseX, mouseY, mouseButton);
}
}
/**
* Draws the screen and all the components in it.
*/
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.create", new Object[0]), this.width / 2, 20, -1);
if (this.inMoreWorldOptionsDisplay)
{
this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterSeed", new Object[0]), this.width / 2 - 100, 47, -6250336);
this.drawString(this.fontRendererObj, I18n.format("selectWorld.seedInfo", new Object[0]), this.width / 2 - 100, 85, -6250336);
if (this.btnMapFeatures.visible)
{
this.drawString(this.fontRendererObj, I18n.format("selectWorld.mapFeatures.info", new Object[0]), this.width / 2 - 150, 122, -6250336);
}
if (this.btnAllowCommands.visible)
{
this.drawString(this.fontRendererObj, I18n.format("selectWorld.allowCommands.info", new Object[0]), this.width / 2 - 150, 172, -6250336);
}
this.worldSeedField.drawTextBox();
if (WorldType.WORLD_TYPES[this.selectedIndex].showWorldInfoNotice())
{
this.fontRendererObj.drawSplitString(I18n.format(WorldType.WORLD_TYPES[this.selectedIndex].getTranslatedInfo(), new Object[0]), this.btnMapType.xPosition + 2, this.btnMapType.yPosition + 22, this.btnMapType.getButtonWidth(), 10526880);
}
}
else
{
this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterName", new Object[0]), this.width / 2 - 100, 47, -6250336);
this.drawString(this.fontRendererObj, I18n.format("selectWorld.resultFolder", new Object[0]) + " " + this.saveDirName, this.width / 2 - 100, 85, -6250336);
this.worldNameField.drawTextBox();
this.drawString(this.fontRendererObj, this.gameModeDesc1, this.width / 2 - 100, 137, -6250336);
this.drawString(this.fontRendererObj, this.gameModeDesc2, this.width / 2 - 100, 149, -6250336);
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
/**
* Set the initial values of a new world to create, from the values from an existing world.
*
* Called after construction when a user selects the "Recreate" button.
*/
public void recreateFromExistingWorld(WorldInfo original)
{
this.worldName = I18n.format("selectWorld.newWorld.copyOf", new Object[] {original.getWorldName()});
this.worldSeed = original.getSeed() + "";
this.selectedIndex = original.getTerrainType().getWorldTypeID();
this.chunkProviderSettingsJson = original.getGeneratorOptions();
this.generateStructuresEnabled = original.isMapFeaturesEnabled();
this.allowCheats = original.areCommandsAllowed();
if (original.isHardcoreModeEnabled())
{
this.gameMode = "hardcore";
}
else if (original.getGameType().isSurvivalOrAdventure())
{
this.gameMode = "survival";
}
else if (original.getGameType().isCreative())
{
this.gameMode = "creative";
}
}
}
| MartyParty21/AwakenDreamsClient | mcp/src/minecraft/net/minecraft/client/gui/GuiCreateWorld.java | Java | gpl-3.0 | 21,756 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2019 khalim19
#
# 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.
"""
This module defines a custom widget holding an array of GUI elements. The widget
is used as the default GUI for `setting.ArraySetting` instances.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import *
import collections
import contextlib
import pygtk
pygtk.require("2.0")
import gtk
import gobject
from .. import utils as pgutils
from . import draganddropcontext as draganddropcontext_
__all__ = [
"ItemBox",
"ArrayBox",
"ItemBoxItem",
]
class ItemBox(gtk.ScrolledWindow):
"""
This base class defines a scrollable box holding a vertical list of items.
Each item is an instance of `_ItemBoxItem` class or one of its subclasses.
"""
ITEM_SPACING = 4
VBOX_SPACING = 4
def __init__(self, item_spacing=ITEM_SPACING, *args, **kwargs):
super().__init__(*args, **kwargs)
self._item_spacing = item_spacing
self._drag_and_drop_context = draganddropcontext_.DragAndDropContext()
self._items = []
self._vbox_items = gtk.VBox(homogeneous=False)
self._vbox_items.set_spacing(self._item_spacing)
self._vbox = gtk.VBox(homogeneous=False)
self._vbox.set_spacing(self.VBOX_SPACING)
self._vbox.pack_start(self._vbox_items, expand=False, fill=False)
self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.add_with_viewport(self._vbox)
self.get_child().set_shadow_type(gtk.SHADOW_NONE)
def add_item(self, item):
self._vbox_items.pack_start(item.widget, expand=False, fill=False)
item.button_remove.connect("clicked", self._on_item_button_remove_clicked, item)
item.widget.connect("key-press-event", self._on_item_widget_key_press_event, item)
self._setup_drag(item)
self._items.append(item)
return item
def reorder_item(self, item, position):
new_position = min(max(position, 0), len(self._items) - 1)
self._items.pop(self._get_item_position(item))
self._items.insert(new_position, item)
self._vbox_items.reorder_child(item.widget, new_position)
return new_position
def remove_item(self, item):
item_position = self._get_item_position(item)
if item_position < len(self._items) - 1:
next_item_position = item_position + 1
self._items[next_item_position].item_widget.grab_focus()
self._vbox_items.remove(item.widget)
item.remove_item_widget()
self._items.remove(item)
def clear(self):
for unused_ in range(len(self._items)):
self.remove_item(self._items[0])
def _setup_drag(self, item):
self._drag_and_drop_context.setup_drag(
item.item_widget,
self._get_drag_data,
self._on_drag_data_received,
[item],
[item],
self)
def _get_drag_data(self, dragged_item):
return str(self._items.index(dragged_item))
def _on_drag_data_received(self, dragged_item_index_str, destination_item):
dragged_item = self._items[int(dragged_item_index_str)]
self.reorder_item(dragged_item, self._get_item_position(destination_item))
def _on_item_widget_key_press_event(self, widget, event, item):
if event.state & gtk.gdk.MOD1_MASK: # Alt key
key_name = gtk.gdk.keyval_name(event.keyval)
if key_name in ["Up", "KP_Up"]:
self.reorder_item(
item, self._get_item_position(item) - 1)
elif key_name in ["Down", "KP_Down"]:
self.reorder_item(
item, self._get_item_position(item) + 1)
def _on_item_button_remove_clicked(self, button, item):
self.remove_item(item)
def _get_item_position(self, item):
return self._items.index(item)
class ItemBoxItem(object):
_HBOX_BUTTONS_SPACING = 3
_HBOX_SPACING = 3
def __init__(self, item_widget):
self._item_widget = item_widget
self._hbox = gtk.HBox(homogeneous=False)
self._hbox.set_spacing(self._HBOX_SPACING)
self._hbox_buttons = gtk.HBox(homogeneous=False)
self._hbox_buttons.set_spacing(self._HBOX_BUTTONS_SPACING)
self._event_box_buttons = gtk.EventBox()
self._event_box_buttons.add(self._hbox_buttons)
self._hbox.pack_start(self._item_widget, expand=True, fill=True)
self._hbox.pack_start(self._event_box_buttons, expand=False, fill=False)
self._event_box = gtk.EventBox()
self._event_box.add(self._hbox)
self._has_hbox_buttons_focus = False
self._button_remove = gtk.Button()
self._setup_item_button(self._button_remove, gtk.STOCK_CLOSE)
self._event_box.connect("enter-notify-event", self._on_event_box_enter_notify_event)
self._event_box.connect("leave-notify-event", self._on_event_box_leave_notify_event)
self._is_event_box_allocated_size = False
self._buttons_allocation = None
self._event_box.connect("size-allocate", self._on_event_box_size_allocate)
self._event_box_buttons.connect(
"size-allocate", self._on_event_box_buttons_size_allocate)
self._event_box.show_all()
self._hbox_buttons.set_no_show_all(True)
@property
def widget(self):
return self._event_box
@property
def item_widget(self):
return self._item_widget
@property
def button_remove(self):
return self._button_remove
def remove_item_widget(self):
self._hbox.remove(self._item_widget)
def _setup_item_button(self, item_button, icon, position=None):
item_button.set_relief(gtk.RELIEF_NONE)
button_icon = gtk.image_new_from_pixbuf(
item_button.render_icon(icon, gtk.ICON_SIZE_MENU))
item_button.add(button_icon)
self._hbox_buttons.pack_start(item_button, expand=False, fill=False)
if position is not None:
self._hbox_buttons.reorder_child(item_button, position)
item_button.show_all()
def _on_event_box_enter_notify_event(self, event_box, event):
if event.detail != gtk.gdk.NOTIFY_INFERIOR:
self._hbox_buttons.show()
def _on_event_box_leave_notify_event(self, event_box, event):
if event.detail != gtk.gdk.NOTIFY_INFERIOR:
self._hbox_buttons.hide()
def _on_event_box_size_allocate(self, event_box, allocation):
if self._is_event_box_allocated_size:
return
self._is_event_box_allocated_size = True
# Assign enough height to the HBox to make sure it does not resize when
# showing buttons.
if self._buttons_allocation.height >= allocation.height:
self._hbox.set_property("height-request", allocation.height)
def _on_event_box_buttons_size_allocate(self, event_box, allocation):
if self._buttons_allocation is not None:
return
self._buttons_allocation = allocation
# Make sure the width allocated to the buttons remains the same even if
# buttons are hidden. This avoids a problem with unreachable buttons when
# the horizontal scrollbar is displayed.
self._event_box_buttons.set_property(
"width-request", self._buttons_allocation.width)
self._hbox_buttons.hide()
class ArrayBox(ItemBox):
"""
This class can be used to edit `setting.ArraySetting` instances interactively.
Signals:
* `"array-box-changed"` - An item was added, reordered or removed by the user.
* `"array-box-item-changed"` - The contents of an item was modified by the
user. Currently, this signal is not invoked in this widget and can only be
invoked explicitly by calling `ArrayBox.emit("array-box-item-changed")`.
"""
__gsignals__ = {
b"array-box-changed": (gobject.SIGNAL_RUN_FIRST, None, ()),
b"array-box-item-changed": (gobject.SIGNAL_RUN_FIRST, None, ())}
_SIZE_HBOX_SPACING = 6
def __init__(
self,
new_item_default_value,
min_size=0,
max_size=None,
item_spacing=ItemBox.ITEM_SPACING,
max_width=None,
max_height=None,
*args,
**kwargs):
"""
Parameters:
* `new_item_default_value` - default value for new items.
* `min_size` - minimum number of elements.
* `max_size` - maximum number of elements. If `None`, the number of elements
is unlimited.
* `item_spacing` - vertical spacing in pixels between items.
* `max_width` - maximum width of the array box before the horizontal
scrollbar is displayed. The array box will resize automatically until the
maximum width is reached. If `max_width` is `None`, the width is fixed
to whatever width is provided by `gtk.ScrolledWindow`. If `max_width` is
zero or negative, the width is unlimited.
* `max_height` - maximum height of the array box before the vertical
scrollbar is displayed. For more information, see `max_width`.
"""
super().__init__(item_spacing=item_spacing, *args, **kwargs)
self._new_item_default_value = new_item_default_value
self._min_size = min_size if min_size >= 0 else 0
if max_size is None:
self._max_size = 2**32
else:
self._max_size = max_size if max_size >= min_size else min_size
self.max_width = max_width
self.max_height = max_height
self.on_add_item = pgutils.empty_func
self.on_reorder_item = pgutils.empty_func
self.on_remove_item = pgutils.empty_func
self._items_total_width = None
self._items_total_height = None
self._items_allocations = {}
self._locker = _ActionLocker()
self._init_gui()
def _init_gui(self):
self._size_spin_button = gtk.SpinButton(
gtk.Adjustment(
value=0,
lower=self._min_size,
upper=self._max_size,
step_incr=1,
page_incr=10,
),
digits=0)
self._size_spin_button.set_numeric(True)
self._size_spin_button.set_value(0)
self._size_spin_button_label = gtk.Label(_("Size"))
self._size_hbox = gtk.HBox()
self._size_hbox.set_spacing(self._SIZE_HBOX_SPACING)
self._size_hbox.pack_start(self._size_spin_button_label, expand=False, fill=False)
self._size_hbox.pack_start(self._size_spin_button, expand=False, fill=False)
self._vbox.pack_start(self._size_hbox, expand=False, fill=False)
self._vbox.reorder_child(self._size_hbox, 0)
self._size_spin_button.connect(
"value-changed", self._on_size_spin_button_value_changed)
def add_item(self, item_value=None, index=None):
if item_value is None:
item_value = self._new_item_default_value
item_widget = self.on_add_item(item_value, index)
item = _ArrayBoxItem(item_widget)
super().add_item(item)
item.widget.connect("size-allocate", self._on_item_widget_size_allocate, item)
if index is None:
item.label.set_label(self._get_item_name(len(self._items)))
if index is not None:
with self._locker.lock_temp("emit_array_box_changed_on_reorder"):
self.reorder_item(item, index)
if self._locker.is_unlocked("update_spin_button"):
with self._locker.lock_temp("emit_size_spin_button_value_changed"):
self._size_spin_button.spin(gtk.SPIN_STEP_FORWARD, increment=1)
return item
def reorder_item(self, item, new_position):
orig_position = self._get_item_position(item)
processed_new_position = super().reorder_item(item, new_position)
self.on_reorder_item(orig_position, processed_new_position)
self._rename_item_names(min(orig_position, processed_new_position))
if self._locker.is_unlocked("emit_array_box_changed_on_reorder"):
self.emit("array-box-changed")
def remove_item(self, item):
if (self._locker.is_unlocked("prevent_removal_below_min_size")
and len(self._items) == self._min_size):
return
if self._locker.is_unlocked("update_spin_button"):
with self._locker.lock_temp("emit_size_spin_button_value_changed"):
self._size_spin_button.spin(gtk.SPIN_STEP_BACKWARD, increment=1)
item_position = self._get_item_position(item)
super().remove_item(item)
if item in self._items_allocations:
self._update_height(-(self._items_allocations[item].height + self._item_spacing))
del self._items_allocations[item]
self.on_remove_item(item_position)
self._rename_item_names(item_position)
def set_values(self, values):
self._locker.lock("emit_size_spin_button_value_changed")
self._locker.lock("prevent_removal_below_min_size")
orig_on_remove_item = self.on_remove_item
self.on_remove_item = pgutils.empty_func
self.clear()
# This fixes an issue of items being allocated height of 1 when the array
# size was previously 0.
self.set_property("height-request", -1)
for index, value in enumerate(values):
self.add_item(value, index)
self.on_remove_item = orig_on_remove_item
self._size_spin_button.set_value(len(values))
self._locker.unlock("prevent_removal_below_min_size")
self._locker.unlock("emit_size_spin_button_value_changed")
def _setup_drag(self, item):
self._drag_and_drop_context.setup_drag(
# Using the entire item allows dragging only by the label rather than the
# widget itself. This avoids problems with widgets such as spin buttons
# that do not behave correctly when reordering and also avoids accidental
# clicking and modifying the widget by the user.
item.widget,
self._get_drag_data,
self._on_drag_data_received,
[item],
[item],
self)
def _on_size_spin_button_value_changed(self, size_spin_button):
if self._locker.is_unlocked("emit_size_spin_button_value_changed"):
self._locker.lock("update_spin_button")
new_size = size_spin_button.get_value_as_int()
if new_size > len(self._items):
num_elements_to_add = new_size - len(self._items)
for unused_ in range(num_elements_to_add):
self.add_item()
elif new_size < len(self._items):
num_elements_to_remove = len(self._items) - new_size
for unused_ in range(num_elements_to_remove):
self.remove_item(self._items[-1])
self.emit("array-box-changed")
self._locker.unlock("update_spin_button")
def _on_item_button_remove_clicked(self, button, item):
self._locker.lock("emit_size_spin_button_value_changed")
should_emit_signal = (
len(self._items) > self._min_size
or self._locker.is_locked("prevent_removal_below_min_size"))
super()._on_item_button_remove_clicked(button, item)
if should_emit_signal:
self.emit("array-box-changed")
self._locker.unlock("emit_size_spin_button_value_changed")
def _on_item_widget_size_allocate(self, item_widget, allocation, item):
if item in self._items_allocations:
self._update_width(allocation.width - self._items_allocations[item].width)
self._update_height(allocation.height - self._items_allocations[item].height)
else:
self._update_width(allocation.width)
self._update_height(allocation.height + self._item_spacing)
self._items_allocations[item] = allocation
def _update_width(self, width_diff):
if self._items_total_width is None:
self._items_total_width = self.get_allocation().width
if width_diff != 0:
self._update_dimension(
width_diff,
self._items_total_width,
self.max_width,
"width-request")
self._items_total_width = self._items_total_width + width_diff
def _update_height(self, height_diff):
if self._items_total_height is None:
self._items_total_height = self.get_allocation().height
if height_diff != 0:
self._update_dimension(
height_diff,
self._items_total_height,
self.max_height,
"height-request")
self._items_total_height = self._items_total_height + height_diff
def _update_dimension(
self,
size_diff,
total_size,
max_visible_size,
dimension_request_property):
if max_visible_size is None:
is_max_visible_size_unlimited = True
else:
is_max_visible_size_unlimited = max_visible_size <= 0
if not is_max_visible_size_unlimited:
visible_size = min(total_size, max_visible_size)
else:
visible_size = total_size
if (is_max_visible_size_unlimited
or (visible_size + size_diff <= max_visible_size
and total_size < max_visible_size)):
new_size = visible_size + size_diff
elif total_size >= max_visible_size and size_diff < 0:
if total_size + size_diff < max_visible_size:
new_size = total_size + size_diff
else:
new_size = max_visible_size
else:
new_size = max_visible_size
if max_visible_size is not None:
self.set_property(dimension_request_property, new_size)
def _rename_item_names(self, start_index):
for index, item in enumerate(self._items[start_index:]):
item.label.set_label(self._get_item_name(index + 1 + start_index))
@staticmethod
def _get_item_name(index):
return _("Element") + " " + str(index)
class _ArrayBoxItem(ItemBoxItem):
def __init__(self, item_widget):
super().__init__(item_widget)
self._label = gtk.Label()
self._label.show()
self._hbox.pack_start(self._label, expand=False, fill=False)
self._hbox.reorder_child(self._label, 0)
@property
def label(self):
return self._label
class _ActionLocker(object):
def __init__(self):
self._tokens = collections.defaultdict(int)
@contextlib.contextmanager
def lock_temp(self, key):
self.lock(key)
try:
yield
finally:
self.unlock(key)
def lock(self, key):
self._tokens[key] += 1
def unlock(self, key):
if self._tokens[key] > 0:
self._tokens[key] -= 1
def is_locked(self, key):
return self._tokens[key] > 0
def is_unlocked(self, key):
return self._tokens[key] == 0
gobject.type_register(ArrayBox)
| khalim19/gimp-plugin-export-layers | export_layers/pygimplib/gui/itembox.py | Python | gpl-3.0 | 18,637 |
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using FluentAssertions;
using GitUI;
using GitUI.UserControls.RevisionGrid.Graph;
using GitUIPluginInterfaces;
using NSubstitute;
using NUnit.Framework;
namespace GitUITests.UserControls.RevisionGrid.Graph
{
[TestFixture]
public class JunctionStylerTests
{
private IJunctionColorProvider _junctionColorProvider;
private JunctionStyler _junctionStyler;
[SetUp]
public void Setup()
{
_junctionColorProvider = Substitute.For<IJunctionColorProvider>();
_junctionColorProvider.NonRelativeColor.Returns(x => Color.Azure);
_junctionStyler = new JunctionStyler(_junctionColorProvider);
}
[Test]
public void GetLaneBrush_should_set_black_color_for_empty_junction_list()
{
_junctionStyler.GetLaneBrush().Should().Be(Brushes.Black);
}
[Test]
public void GetNodeBrush_should_return_black_brush_if_colors_cache_not_primed()
{
_junctionStyler.GetNodeBrush(Rectangle.Empty, false).Should().Be(Brushes.Black);
}
[Test]
public void GetNodeBrush_should_return_SolidBrush_for_single_primed_color()
{
// prime a single color
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var brush = _junctionStyler.GetNodeBrush(Rectangle.Empty, false);
brush.Should().BeOfType<SolidBrush>();
}
[Test]
public void GetNodeBrush_should_return_SolidBrush_with_first_primed_color_if_highlighted()
{
// prime a single color
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var brush = _junctionStyler.GetNodeBrush(Rectangle.Empty, true);
brush.Should().BeOfType<SolidBrush>();
((SolidBrush)brush).Color.Should().Be(_junctionStyler.GetJunctionColors().First());
}
[Test]
public void GetNodeBrush_should_return_SolidBrush_with_NonRelativeColor_if_not_highlighted()
{
// prime a single color
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var brush = _junctionStyler.GetNodeBrush(Rectangle.Empty, false);
brush.Should().BeOfType<SolidBrush>();
((SolidBrush)brush).Color.Should().Be(_junctionColorProvider.NonRelativeColor);
}
[Test]
public void GetNodeBrush_should_return_LinearGradientBrush_if_mutiple_colors_primed()
{
// prime a two color
var junctions = new List<Junction>
{
new Junction(new Node(ObjectId.WorkTreeId)),
new Junction(new Node(ObjectId.IndexId))
};
_junctionStyler.UpdateJunctionColors(junctions, RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var brush = _junctionStyler.GetNodeBrush(new Rectangle(0, 0, 1, 1), false);
brush.Should().BeOfType<LinearGradientBrush>();
}
[Test]
public void UpdateJunctionColors_should_reset_between_calls()
{
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
_junctionStyler.GetJunctionColors().Count().Should().Be(1);
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
_junctionStyler.GetJunctionColors().Count().Should().Be(1);
}
[Test]
public void UpdateJunctionColors_should_set_black_color_for_empty_junction_list()
{
_junctionStyler.UpdateJunctionColors(new List<Junction>(), RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var colors = _junctionStyler.GetJunctionColors().ToList();
colors.Count.Should().Be(1);
colors[0].Should().Be(Color.Black);
_junctionColorProvider.DidNotReceive().GetColor(Arg.Any<Junction>(), Arg.Any<RevisionGraphDrawStyleEnum>());
}
// NB: it would be simpler to use TestCase construct, however Junction type if marked as internal
[Test]
public void UpdateJunctionColors_should_prime_one_color_for_one_junction()
{
var junctions = new List<Junction> { new Junction(new Node(ObjectId.WorkTreeId)) };
_junctionStyler.UpdateJunctionColors(junctions, RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var colors = _junctionStyler.GetJunctionColors().ToList();
colors.Count.Should().Be(1);
_junctionColorProvider.Received(1).GetColor(junctions[0], RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
}
[Test]
public void UpdateJunctionColors_should_prime_two_colors_for_two_junctions()
{
var junctions = new List<Junction>
{
new Junction(new Node(ObjectId.WorkTreeId)),
new Junction(new Node(ObjectId.IndexId))
};
_junctionStyler.UpdateJunctionColors(junctions, RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var colors = _junctionStyler.GetJunctionColors().ToList();
colors.Count.Should().Be(2);
_junctionColorProvider.Received(1).GetColor(junctions[0], RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
_junctionColorProvider.Received(1).GetColor(junctions[1], RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
}
[Test]
public void UpdateJunctionColors_should_prime_only_two_colors_for_three_or_more_junctions()
{
var junctions = new List<Junction>
{
new Junction(new Node(ObjectId.WorkTreeId)),
new Junction(new Node(ObjectId.IndexId)),
new Junction(new Node(ObjectId.CombinedDiffId))
};
_junctionStyler.UpdateJunctionColors(junctions, RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
var colors = _junctionStyler.GetJunctionColors().ToList();
colors.Count.Should().Be(2);
_junctionColorProvider.Received(1).GetColor(junctions[0], RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
_junctionColorProvider.Received(1).GetColor(junctions[1], RevisionGraphDrawStyleEnum.DrawNonRelativesGray);
_junctionColorProvider.DidNotReceive().GetColor(junctions[2], Arg.Any<RevisionGraphDrawStyleEnum>());
}
}
} | jbialobr/gitextensions | UnitTests/GitUITests/UserControls/RevisionGrid/Graph/JunctionStylerTests.cs | C# | gpl-3.0 | 6,704 |
// Copyright 2016 The go-elementrem Authors.
// This file is part of go-elementrem.
//
// go-elementrem 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.
//
// go-elementrem 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 go-elementrem. If not, see <http://www.gnu.org/licenses/>.
// +build linux darwin netbsd openbsd solaris
package utils
import "syscall"
// raiseFdLimit tries to maximize the file descriptor allowance of this process
// to the maximum hard-limit allowed by the OS.
func raiseFdLimit(max uint64) error {
// Get the current limit
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return err
}
// Try to update the limit to the max allowance
limit.Cur = limit.Max
if limit.Cur > max {
limit.Cur = max
}
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return err
}
return nil
}
// getFdLimit retrieves the number of file descriptors allowed to be opened by this
// process.
func getFdLimit() (int, error) {
var limit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limit); err != nil {
return 0, err
}
return int(limit.Cur), nil
}
| elementrem/go-elementrem | cmd/utils/fdlimit_unix.go | GO | gpl-3.0 | 1,621 |
#ifndef MWGUI_ENCHANTINGDIALOG_H
#define MWGUI_ENCHANTINGDIALOG_H
#include "spellcreationdialog.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwmechanics/enchanting.hpp"
namespace MWGui
{
class ItemSelectionDialog;
class ItemWidget;
class EnchantingDialog : public WindowBase, public ReferenceInterface, public EffectEditorBase
{
public:
EnchantingDialog();
virtual ~EnchantingDialog();
virtual void open();
virtual void exit();
void setSoulGem (const MWWorld::Ptr& gem);
void setItem (const MWWorld::Ptr& item);
void startEnchanting(MWWorld::Ptr actor);
void startSelfEnchanting(MWWorld::Ptr soulgem);
virtual void resetReference();
protected:
virtual void onReferenceUnavailable();
virtual void notifyEffectsChanged ();
void onCancelButtonClicked(MyGUI::Widget* sender);
void onSelectItem (MyGUI::Widget* sender);
void onSelectSoul (MyGUI::Widget* sender);
void onItemSelected(MWWorld::Ptr item);
void onItemCancel();
void onSoulSelected(MWWorld::Ptr item);
void onSoulCancel();
void onBuyButtonClicked(MyGUI::Widget* sender);
void updateLabels();
void onTypeButtonClicked(MyGUI::Widget* sender);
ItemSelectionDialog* mItemSelectionDialog;
MyGUI::Button* mCancelButton;
ItemWidget* mItemBox;
ItemWidget* mSoulBox;
MyGUI::Button* mTypeButton;
MyGUI::Button* mBuyButton;
MyGUI::TextBox* mName;
MyGUI::TextBox* mEnchantmentPoints;
MyGUI::TextBox* mCastCost;
MyGUI::TextBox* mCharge;
MyGUI::TextBox* mPrice;
MyGUI::TextBox* mPriceText;
MWMechanics::Enchanting mEnchanting;
ESM::EffectList mEffectList;
};
}
#endif
| Demorde/openmw-android | apps/openmw/mwgui/enchantingdialog.hpp | C++ | gpl-3.0 | 1,852 |
package com.xminds.aws.cognito;
/**
* Maintains SDK configuration.
*/
public final class CognitoIdentityProviderClientConfig {
/**
* Maximum threshold for refresh tokens, in milli seconds.
*/
private static long REFRESH_THRESHOLD_MAX = 1800 * 1000;
/**
* Minimum threshold for refresh tokens, in milli seconds.
*/
private static long REFRESH_THRESHOLD_MIN = 0;
/**
* Threshold for refresh tokens, in milli seconds.
* Tokens are refreshed if the session is valid for less than this value.
*/
private static long refreshThreshold = 300 * 1000;
/**
* Set the threshold for token refresh.
*
* @param threshold REQUIRED: Threshold for token refresh in milli seconds.
* @throws CognitoParameterInvalidException
*/
public static void setRefreshThreshold(long threshold) throws CognitoParameterInvalidException {
if (threshold > REFRESH_THRESHOLD_MAX || threshold < REFRESH_THRESHOLD_MIN) {
throw new CognitoParameterInvalidException(String.format("The value of refreshThreshold must between %d and %d seconds",
REFRESH_THRESHOLD_MIN, REFRESH_THRESHOLD_MAX));
}
refreshThreshold = threshold;
}
public static long getRefreshThreshold() {
return refreshThreshold;
}
}
| xminds/cognitowrapper | src/main/java/com/xminds/aws/cognito/CognitoIdentityProviderClientConfig.java | Java | gpl-3.0 | 1,333 |
function changeQueryStr(name, value) {
var query = window.location.search.substring(1),
newQuery = '?', notFound = true,
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair == '' || pair[0] == 'page') continue;
if (pair[0] == name) { notFound = false; pair[1] = value; }
if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; }
}
if (notFound && value.length > 0) { newQuery += name + '=' + value; }
else if (newQuery.length == 1) { newQuery = ''; }
else { newQuery = newQuery.slice(0,-1); }
var loc = window.location,
ajaxurl = '/ajax' + loc.pathname + newQuery,
newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery;
$.get(ajaxurl).done(function(data){
$('#ajax-content').html(data);
init_pagination();
});
window.history.pushState({path:newurl},'',newurl);
}
function init_filtering_stories(jQuery) {
$('#filtering input').change(function(){
var input = $(this), name = input[0].name, value=input.val();
changeQueryStr(name, value);
});
}
function init_pagination(jQuery) {
$('.pager a').on('click', function(e){
e.preventDefault();
var value = $(this).closest('li').data('pageNum');
if (value) changeQueryStr('page', String(value));
});
}
$(document).ready(init_filtering_stories);
$(document).ready(init_pagination);
| RomanOsadchuk/GoStory | general/static/general/js/list_filtering.js | JavaScript | gpl-3.0 | 1,490 |
"""
Follow Me activity for Sugar
Copyright (C) 2010 Peter Hewitt
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 RC():
def __init__(self, nr, nc):
self.nr = nr
self.nc = nc
def inc_r(self, ind):
r, c = self.row_col(ind)
r += 1
if r == self.nr:
r = 0
if r == (self.nr - 1) and c == (self.nc - 1):
r = 0
return self.indx(r, c)
def dec_r(self, ind):
r, c = self.row_col(ind)
r -= 1
if r < 0:
r = self.nr - 1
if r == (self.nr - 1) and c == (self.nc - 1):
r = self.nr - 2
return self.indx(r, c)
def inc_c(self, ind):
r, c = self.row_col(ind)
c += 1
if c == self.nc:
c = 0
if r == (self.nr - 1) and c == (self.nc - 1):
c = 0
return self.indx(r, c)
def dec_c(self, ind):
r, c = self.row_col(ind)
c -= 1
if c < 0:
c = self.nc - 1
if r == (self.nr - 1) and c == (self.nc - 1):
c = self.nc - 2
return self.indx(r, c)
def row_col(self, ind):
i = 0
for r in range(self.nr):
for c in range(self.nc):
if i == ind:
return r, c
i += 1
def indx(self, r, c):
return r * self.nc + c
| walterbender/followme | rc_skip_last.py | Python | gpl-3.0 | 1,984 |
import Route from '@ember/routing/route'
import resetScroll from 'radio4000/mixins/reset-scroll'
export default Route.extend(resetScroll, {})
| internet4000/radio4000 | app/channels/route.js | JavaScript | gpl-3.0 | 143 |
# originally from
# http://code.google.com/p/django-syncr/source/browse/trunk/app/delicious.py
# supousse django-syncr should be installed as external app and this code
# inherit from that, but django-syncr have not a setup.py file (so can't be
# added in src/pinax/requirements/external_apps.txt) and is not migrated to git
# (so can add a setup.file in a different fork from svn trunk)
import time, datetime, calendar
import httplib
import urllib, urllib2
import base64
#from syncr.delicious.models import Bookmark
from bookmarks.models import Bookmark, BookmarkInstance
from bookmarks.forms import BookmarkInstanceForm
try:
import xml.etree.ElementTree as ET
except:
import elementtree.ElementTree as ET
class DeliciousAPI:
"""
DeliciousAPI is a bare-bones interface to the del.icio.us API. It's
used by DeliciousSyncr objects and it's not recommended to use it
directly.
"""
_deliciousApiHost = 'https://api.del.icio.us/'
_deliciousApiURL = 'https://api.del.icio.us/v1/'
def __init__(self, user, passwd):
"""
Initialize a DeliciousAPI object.
Required arguments
user: The del.icio.us username as a string.
passwd: The username's password as a string.
"""
self.user = user
self.passwd = passwd
# pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
# pm.add_password(None, 'https://' + self._deliciousApiHost, self.user, self.passwd)
# handler = urllib2.HTTPBasicAuthHandler(pm)
# self.opener = urllib2.build_opener(handler)
def _request(self, path, params=None):
# time.sleep(1.5)
# if params:
# post_data = urllib.urlencode(params)
# url = self._deliciousApiURL + path + post_data
# else:
# url = self._deliciousApiURL + path
# request = urllib2.Request(url)
# request.add_header('User-Agent', 'django/syncr.app.delicious')
# credentials = base64.encodestring("%s:%s" % (self.user, self.passwd))
# request.add_header('Authorization', ('Basic %s' % credentials))
# f = self.opener.open(request)
f = open('/home/julia/hacktivism/testing-parsing-bookmarks/all.xml')
return ET.parse(f)
class DeliciousSyncr:
"""
DeliciousSyncr objects sync del.icio.us bookmarks to the Django
backend. The constructor requires a username and password for
authenticated access to the API.
There are three ways to sync:
- All bookmarks for the user
- Only recent bookmarks for the user
- Bookmarks based on a limited search/query functionality. Currently
based on date, tag, and URL.
This app requires the excellent ElementTree, which is included in
Python 2.5. Otherwise available at:
http://effbot.org/zone/element-index.htm
"""
def __init__(self, username, password):
"""
Construct a new DeliciousSyncr.
Required arguments
username: a del.icio.us username
password: the user's password
"""
self.delicious = DeliciousAPI(username, password)
def clean_tags(self, tags):
"""
Utility method to clean up del.icio.us tags, removing double
quotes, duplicate tags and return a unicode string.
Required arguments
tags: a tag string
"""
tags = tags.lower().replace('\"', '').split(' ')
tags = set(tags)
tags = " ".join(tags)
return u'%s' % tags
def _syncPost(self, post_elem, user):
time_lst = time.strptime(post_elem.attrib['time'], "%Y-%m-%dT%H:%M:%SZ")
time_obj = datetime.datetime(*time_lst[0:7])
tags = self.clean_tags(post_elem.attrib['tag'])
try:
extended = post_elem.attrib['extended']
except KeyError:
extended = ''
default_dict = {
'description': post_elem.attrib['description'],
'tags': tags,
'url': post_elem.attrib['href'],
# Is post_hash attrib unique to the post/URL or post/username ?!
'post_hash': post_hash,
'saved_date': time_obj,
'extended_info': extended,
}
# Save only shared bookmarks
# try:
# is_shared = post_elem.attrib['shared'] # Only set, when it isn't shared
# except KeyError:
# obj, created = Bookmark.objects.get_or_create(
# post_hash=post_hash, defaults=default_dict)
# return obj
# return None
# to save pinax Bookmark
try:
unicode(default_dict['description'].decode('latin-1'))
except:
default_dict['description'] = ''
print default_dict['description']
bookmark_instance_form = BookmarkInstanceForm(user,default_dict)
if bookmark_instance_form.is_valid():
bookmark_instance = bookmark_instance_form.save(commit=False)
bookmark_instance.user = user
bookmark_instance.save()
print bookmark_instance
bookmark = bookmark_instance.bookmark
try:
headers = {
"Accept" : "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
"Accept-Language" : "en-us,en;q=0.5",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Connection" : "close",
##"User-Agent": settings.URL_VALIDATOR_USER_AGENT
}
req = urllib2.Request(bookmark.get_favicon_url(force=True), None, headers)
u = urllib2.urlopen(req)
has_favicon = True
except:
has_favicon = False
bookmark.has_favicon = has_favicon
bookmark.favicon_checked = datetime.datetime.now()
# bookmark.added = bookmark['add_date']
bookmark.save()
# print bookmark
else:
print "bookmark_instance_form no es valido"
return
def syncRecent(self, count=15, tag=None):
"""
Synchronize the user's recent bookmarks.
Optional arguments:
count: The number of bookmarks to return, default 15, max 100.
tag: A string. Limit to recent bookmarks that match this tag.
"""
params = {'count': count}
if tag: params['tag'] = tag
result = self.delicious._request('posts/recent?', params)
root = result.getroot()
for post in list(root):
self._syncPost(post)
def syncAll(self, user, tag=None):
"""
Synchronize all of the user's bookmarks. WARNING this may take
a while! Excessive use may get you throttled.
Optional arguments
tag: A string. Limit to all bookmarks that match this tag.
"""
params = dict()
if tag: params = {'tag': tag}
result = self.delicious._request('posts/all?', params)
root = result.getroot()
for post in list(root):
self._syncPost(post, user)
def datetime2delicious(self, dt):
"""
Utility method to convert a Python datetime to a string format
suitable for the del.icio.us API.
Required arguments
dt: a datetime object
"""
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
def syncBookmarks(self, **kwargs):
"""
Synchronize bookmarks. If no arguments are used, today's
bookmarks will be sync'd.
Optional keyword arguments
date: A datetime object. Sync only bookmarks from this date.
tag: A string. Limit to bookmarks matching this tag.
url: A string. Limit to bookmarks matching this URL.
"""
params = kwargs
if kwargs.has_key('date'):
params['date'] = self.datetime2delicious(params['date'])
result = self.delicious._request('posts/get?', )
root = result.getroot()
for post in list(root):
self._syncPost(post)
| duy/pinax-syncr-delicious | delicious/delicious.py | Python | gpl-3.0 | 8,100 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code 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.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
/*
============
idCmdArgs::operator=
============
*/
void idCmdArgs::operator=( const idCmdArgs &args )
{
int i;
argc = args.argc;
memcpy( tokenized, args.tokenized, MAX_COMMAND_STRING );
for( i = 0; i < argc; i++ )
{
argv[ i ] = tokenized + ( args.argv[ i ] - args.tokenized );
}
}
/*
============
idCmdArgs::Args
============
*/
const char *idCmdArgs::Args( int start, int end, bool escapeArgs ) const
{
static char cmd_args[MAX_COMMAND_STRING];
int i;
if( end < 0 )
{
end = argc - 1;
}
else if( end >= argc )
{
end = argc - 1;
}
cmd_args[0] = '\0';
if( escapeArgs )
{
strcat( cmd_args, "\"" );
}
for( i = start; i <= end; i++ )
{
if( i > start )
{
if( escapeArgs )
{
strcat( cmd_args, "\" \"" );
}
else
{
strcat( cmd_args, " " );
}
}
if( escapeArgs && strchr( argv[i], '\\' ) )
{
char *p = argv[i];
while( *p != '\0' )
{
if( *p == '\\' )
{
strcat( cmd_args, "\\\\" );
}
else
{
int l = strlen( cmd_args );
cmd_args[ l ] = *p;
cmd_args[ l + 1 ] = '\0';
}
p++;
}
}
else
{
strcat( cmd_args, argv[i] );
}
}
if( escapeArgs )
{
strcat( cmd_args, "\"" );
}
return cmd_args;
}
/*
============
idCmdArgs::TokenizeString
Parses the given string into command line tokens.
The text is copied to a separate buffer and 0 characters
are inserted in the appropriate place. The argv array
will point into this temporary buffer.
============
*/
void idCmdArgs::TokenizeString( const char *text, bool keepAsStrings )
{
idLexer lex;
idToken token, number;
int len, totalLen;
// clear previous args
argc = 0;
if( !text )
{
return;
}
lex.LoadMemory( text, strlen( text ), "idCmdSystemLocal::TokenizeString" );
lex.SetFlags( LEXFL_NOERRORS
| LEXFL_NOWARNINGS
| LEXFL_NOSTRINGCONCAT
| LEXFL_ALLOWPATHNAMES
| LEXFL_NOSTRINGESCAPECHARS
| LEXFL_ALLOWIPADDRESSES | ( keepAsStrings ? LEXFL_ONLYSTRINGS : 0 ) );
totalLen = 0;
while( 1 )
{
if( argc == MAX_COMMAND_ARGS )
{
return; // this is usually something malicious
}
if( !lex.ReadToken( &token ) )
{
return;
}
// check for negative numbers
if( !keepAsStrings && ( token == "-" ) )
{
if( lex.CheckTokenType( TT_NUMBER, 0, &number ) )
{
token = "-" + number;
}
}
// check for cvar expansion
if( token == "$" )
{
if( !lex.ReadToken( &token ) )
{
return;
}
if( idLib::cvarSystem )
{
token = idLib::cvarSystem->GetCVarString( token.c_str() );
}
else
{
token = "<unknown>";
}
}
len = token.Length();
if( totalLen + len + 1 > sizeof( tokenized ) )
{
return; // this is usually something malicious
}
// regular token
argv[argc] = tokenized + totalLen;
argc++;
idStr::Copynz( tokenized + totalLen, token.c_str(), sizeof( tokenized ) - totalLen );
totalLen += len + 1;
}
}
/*
============
idCmdArgs::AppendArg
============
*/
void idCmdArgs::AppendArg( const char *text )
{
if( !argc )
{
argc = 1;
argv[ 0 ] = tokenized;
idStr::Copynz( tokenized, text, sizeof( tokenized ) );
}
else
{
argv[ argc ] = argv[ argc - 1 ] + strlen( argv[ argc - 1 ] ) + 1;
idStr::Copynz( argv[ argc ], text, sizeof( tokenized ) - ( argv[ argc ] - tokenized ) );
argc++;
}
}
/*
============
idCmdArgs::GetArgs
============
*/
const char **idCmdArgs::GetArgs( int *_argc )
{
*_argc = argc;
return ( const char ** )&argv[0];
}
| revelator/MHDoom | neo/idlib/CmdArgs.cpp | C++ | gpl-3.0 | 5,010 |
/*
Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
This file is part of the Webcampak project.
Webcampak 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.
Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
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 Webcampak.
If not, see http://www.gnu.org/licenses/.
*/
console.log('Log: Load: Webcampak.view.dashboard.sourcepicturesizes.SourcesList');
//var rowEditing = Ext.create('Ext.grid.plugin.RowEditing');
Ext.define('Webcampak.view.dashboard.sourcepicturesizes.SourcesList' ,{
extend: 'Ext.form.ComboBox',
alias : 'widget.statssourceslistpicturesizes',
store: 'permissions.sources.Sources',
name: 'source',
valueField: 'id',
displayField: 'name',
typeAhead: true,
emptyText: i18n.gettext('Select another source...'),
style: 'text-align: center;',
width: 315
});
| Webcampak/v2.0 | src/www/interface/dev/app/view/dashboard/sourcepicturesizes/SourcesList.js | JavaScript | gpl-3.0 | 1,232 |
package uni.miskolc.ips.ilona.positioning.web;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculator;
import uni.miskolc.ips.ilona.measurement.model.measurement.MeasurementDistanceCalculatorImpl;
import uni.miskolc.ips.ilona.measurement.model.measurement.wifi.VectorIntersectionWiFiRSSIDistance;
import uni.miskolc.ips.ilona.positioning.service.PositioningService;
import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGateway;
import uni.miskolc.ips.ilona.positioning.service.gateway.MeasurementGatewaySIConfig;
import uni.miskolc.ips.ilona.positioning.service.impl.classification.bayes.NaiveBayesPositioningService;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNPositioning;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNSimplePositioning;
import uni.miskolc.ips.ilona.positioning.service.impl.knn.KNNWeightedPositioning;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "uni.miskolc.ips.ilona.positioning.controller")
public class IlonaPositioningApplicationContext extends WebMvcConfigurerAdapter {
@Bean
public VectorIntersectionWiFiRSSIDistance wifiDistanceCalculator() {
return new VectorIntersectionWiFiRSSIDistance();
}
@Bean
public MeasurementDistanceCalculator measurementDistanceCalculator() {
//TODO
double wifiDistanceWeight = 1.0;
double magnetometerDistanceWeight = 0.5;
double gpsDistanceWeight = 0.0;
double bluetoothDistanceWeight = 1.0;
double rfidDistanceWeight = 0.0;
return new MeasurementDistanceCalculatorImpl(wifiDistanceCalculator(), wifiDistanceWeight, magnetometerDistanceWeight, gpsDistanceWeight, bluetoothDistanceWeight, rfidDistanceWeight);
}
@Bean
public KNNPositioning positioningService() {
//TODO
MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
int k = 3;
return new KNNSimplePositioning(distanceCalculator, measurementGateway, k);
}
@Bean
public KNNPositioning knnpositioningService() {
//TODO
/* MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
MeasurementGateway measurementGateway = null;
int k = 3;
return new KNNSimplePositioning(distanceCalculator, measurementGateway, k);
*/
return positioningService();
}
@Bean
public KNNPositioning knnWpositioningService() {
//TODO
MeasurementDistanceCalculator distanceCalculator = measurementDistanceCalculator();
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
int k = 3;
return new KNNWeightedPositioning(distanceCalculator, measurementGateway, k);
}
@Bean
public PositioningService naivebayespositioningService() {
//TODO
int maxMeasurementDistance = 50;
ApplicationContext context = new AnnotationConfigApplicationContext(MeasurementGatewaySIConfig.class);
MeasurementGateway measurementGateway = context.getBean("MeasurementQueryGateway", MeasurementGateway.class);
MeasurementDistanceCalculator measDistanceCalculator = measurementDistanceCalculator();
return new NaiveBayesPositioningService(measurementGateway, measDistanceCalculator, maxMeasurementDistance);
}
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
return bean;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/img/**").addResourceLocations("/img/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/");
}
}
| ZsoltToth/ilona-positioning | web/src/main/java/uni/miskolc/ips/ilona/positioning/web/IlonaPositioningApplicationContext.java | Java | gpl-3.0 | 5,114 |
/*
* 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, or (at your option) any later version. This
* program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
package l2s.authserver.network.l2;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.interfaces.RSAPrivateKey;
import l2s.authserver.Config;
import l2s.authserver.accounts.Account;
import l2s.authserver.crypt.LoginCrypt;
import l2s.authserver.crypt.ScrambledKeyPair;
import l2s.authserver.network.l2.s2c.AccountKicked;
import l2s.authserver.network.l2.s2c.AccountKicked.AccountKickedReason;
import l2s.authserver.network.l2.s2c.L2LoginServerPacket;
import l2s.authserver.network.l2.s2c.LoginFail;
import l2s.authserver.network.l2.s2c.LoginFail.LoginFailReason;
import l2s.commons.net.nio.impl.MMOClient;
import l2s.commons.net.nio.impl.MMOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class L2LoginClient extends MMOClient<MMOConnection<L2LoginClient>>
{
private final static Logger _log = LoggerFactory.getLogger(L2LoginClient.class);
public static enum LoginClientState
{
CONNECTED,
AUTHED_GG,
AUTHED,
DISCONNECTED
}
private static final int PROTOCOL_VERSION = 0xc621;
private LoginClientState _state;
private LoginCrypt _loginCrypt;
private ScrambledKeyPair _scrambledPair;
private byte[] _blowfishKey;
private String _login;
private SessionKey _skey;
private Account _account;
private String _ipAddr;
private int _sessionId;
private boolean _passwordCorrect;
public L2LoginClient(MMOConnection<L2LoginClient> con)
{
super(con);
_state = LoginClientState.CONNECTED;
_scrambledPair = Config.getScrambledRSAKeyPair();
_blowfishKey = Config.getBlowfishKey();
_loginCrypt = new LoginCrypt();
_loginCrypt.setKey(_blowfishKey);
_sessionId = con.hashCode();
_ipAddr = getConnection().getSocket().getInetAddress().getHostAddress();
_passwordCorrect = false;
}
@Override
public boolean decrypt(ByteBuffer buf, int size)
{
boolean ret;
try
{
ret = _loginCrypt.decrypt(buf.array(), buf.position(), size);
}
catch(IOException e)
{
_log.error("", e);
closeNow(true);
return false;
}
if(!ret)
closeNow(true);
return ret;
}
@Override
public boolean encrypt(ByteBuffer buf, int size)
{
final int offset = buf.position();
try
{
size = _loginCrypt.encrypt(buf.array(), offset, size);
}
catch(IOException e)
{
_log.error("", e);
return false;
}
buf.position(offset + size);
return true;
}
public LoginClientState getState()
{
return _state;
}
public void setState(LoginClientState state)
{
_state = state;
}
public byte[] getBlowfishKey()
{
return _blowfishKey;
}
public byte[] getScrambledModulus()
{
return _scrambledPair.getScrambledModulus();
}
public RSAPrivateKey getRSAPrivateKey()
{
return (RSAPrivateKey) _scrambledPair.getKeyPair().getPrivate();
}
public String getLogin()
{
return _login;
}
public void setLogin(String login)
{
_login = login;
}
public Account getAccount()
{
return _account;
}
public void setAccount(Account account)
{
_account = account;
}
public SessionKey getSessionKey()
{
return _skey;
}
public void setSessionKey(SessionKey skey)
{
_skey = skey;
}
public void setSessionId(int val)
{
_sessionId = val;
}
public int getSessionId()
{
return _sessionId;
}
public void setPasswordCorrect(boolean val)
{
_passwordCorrect = val;
}
public boolean isPasswordCorrect()
{
return _passwordCorrect;
}
public void sendPacket(L2LoginServerPacket lsp)
{
if(isConnected())
getConnection().sendPacket(lsp);
}
public void close(LoginFailReason reason)
{
if(isConnected())
getConnection().close(new LoginFail(reason));
}
public void close(AccountKickedReason reason)
{
if(isConnected())
getConnection().close(new AccountKicked(reason));
}
public void close(L2LoginServerPacket lsp)
{
if(isConnected())
getConnection().close(lsp);
}
@Override
public void onDisconnection()
{
_state = LoginClientState.DISCONNECTED;
_skey = null;
_loginCrypt = null;
_scrambledPair = null;
_blowfishKey = null;
}
@Override
public String toString()
{
switch(_state)
{
case AUTHED:
return "[ Account : " + getLogin() + " IP: " + getIpAddress() + "]";
default:
return "[ State : " + getState() + " IP: " + getIpAddress() + "]";
}
}
public String getIpAddress()
{
return _ipAddr;
}
@Override
protected void onForcedDisconnection()
{
}
public int getProtocol()
{
return PROTOCOL_VERSION;
}
} | pantelis60/L2Scripts_Underground | authserver/src/main/java/l2s/authserver/network/l2/L2LoginClient.java | Java | gpl-3.0 | 5,175 |
"""
Module to handle distortions in diffraction patterns.
"""
import numpy as np
import scipy.optimize
def filter_ring(points, center, rminmax):
"""Filter points to be in a certain radial distance range from center.
Parameters
----------
points : np.ndarray
Candidate points.
center : np.ndarray or tuple
Center position.
rminmax : tuple
Tuple of min and max radial distance.
Returns
-------
: np.ndarray
List of filtered points, two column array.
"""
try:
# points have to be 2D array with 2 columns
assert(isinstance(points, np.ndarray))
assert(points.shape[1] == 2)
assert(len(points.shape) == 2)
# center can either be tuple or np.array
center = np.array(center)
center = np.reshape(center, 2)
rminmax = np.array(rminmax)
rminmax = np.reshape(rminmax, 2)
except:
raise TypeError('Something wrong with the input!')
# calculate radii
rs = np.sqrt( np.square(points[:,0]-center[0]) + np.square(points[:,1]-center[1]) )
# filter by given limits
sel = (rs>=rminmax[0])*(rs<=rminmax[1])
if sel.any():
return points[sel]
else:
return None
def points_topolar(points, center):
"""Convert points to polar coordinate system.
Can be either in pixel or real dim, but should be the same for points and center.
Parameters
----------
points : np.ndarray
Positions as two column array.
center : np.ndarray or tuple
Origin of the polar coordinate system.
Returns
-------
: np.ndarray
Positions in polar coordinate system as two column array (r, theta).
"""
try:
# points have to be 2D array with 2 columns
assert(isinstance(points, np.ndarray))
assert(points.shape[1] == 2)
assert(len(points.shape) == 2)
# center can either be tuple or np.array
center = np.array(center)
center = np.reshape(center, 2)
except:
raise TypeError('Something wrong with the input!')
# calculate radii
rs = np.sqrt( np.square(points[:,0]-center[0]) + np.square(points[:,1]-center[1]) )
# calculate angle
thes = np.arctan2(points[:,1]-center[1], points[:,0]-center[0])
return np.array( [rs, thes] ).transpose()
def residuals_center( param, data):
"""Residual function for minimizing the deviations from the mean radial distance.
Parameters
----------
param : np.ndarray
The center to optimize.
data : np.ndarray
The points in x,y coordinates of the original image.
Returns
-------
: np.ndarray
Residuals.
"""
# manually calculating the radii, as we do not need the thetas
rs = np.sqrt( np.square(data[:,0]-param[0]) + np.square(data[:,1]-param[1]) )
return rs-np.mean(rs)
def optimize_center(points, center, maxfev=1000, verbose=None):
"""Optimize the center by minimizing the sum of square deviations from the mean radial distance.
Parameters
----------
points : np.ndarray
The points to which the optimization is done (x,y coords in org image).
center : np.ndarray or tuple
Initial center guess.
maxfev : int
Max number of iterations forwarded to scipy.optimize.leastsq().
verbose : bool
Set to get verbose output.
Returns
-------
: np.ndarray
The optimized center.
"""
try:
# points have to be 2D array with 2 columns
assert(isinstance(points, np.ndarray))
assert(points.shape[1] == 2)
assert(len(points.shape) == 2)
# center can either be tuple or np.array
center = np.array(center)
center = np.reshape(center, 2)
except:
raise TypeError('Something wrong with the input!')
# run the optimization
popt, flag = scipy.optimize.leastsq(residuals_center, center, args=points, maxfev=maxfev)
if flag not in [1, 2, 3, 4]:
print('WARNING: center optimization failed.')
if verbose:
print('optimized center: ({}, {})'.format(center[0], center[1]))
return popt
def rad_dis(theta, alpha, beta, order=2):
"""Radial distortion due to ellipticity or higher order distortion.
Relative distortion, to be multiplied with radial distance.
Parameters
----------
theta : np.ndarray
Angles at which to evaluate. Must be float.
alpha : float
Orientation of major axis.
beta : float
Strength of distortion (beta = (1-r_min/r_max)/(1+r_min/r_max).
order : int
Order of distortion.
Returns
-------
: np.ndarray
Distortion factor.
"""
return (1.-np.square(beta))/np.sqrt(1.+np.square(beta)-2.*beta*np.cos(order*(theta+alpha)))
def residuals_dis(param, points, ns):
"""Residual function for distortions.
Parameters
----------
param : np.ndarray
Parameters for distortion.
points : np.ndarray
Points to fit to.
ns : tuple
List of orders to account for.
Returns
-------
: np.ndarray
Residuals.
"""
est = param[0]*np.ones(points[:, 1].shape)
for i in range(len(ns)):
est *=rad_dis(points[:, 1], param[i*2+1], param[i*2+2], ns[i])
return points[:, 0] - est
def optimize_distortion(points, ns, maxfev=1000, verbose=False):
"""Optimize distortions.
The orders in the list ns are first fitted subsequently and the result is refined in a final fit simultaneously fitting all orders.
Parameters
----------
points : np.ndarray
Points to optimize to (in polar coords).
ns : tuple
List of orders to correct for.
maxfev : int
Max number of iterations forwarded to scipy.optimize.leastsq().
verbose : bool
Set for verbose output.
Returns
-------
: np.ndarray
Optimized parameters according to ns.
"""
try:
assert(isinstance(points, np.ndarray))
assert(points.shape[1] == 2)
# check points to be sufficient for fitting
assert(points.shape[0] >= 3)
# check orders
assert(len(ns)>=1)
except:
raise TypeError('Something wrong with the input!')
# init guess for full fit
init_guess = np.ones(len(ns)*2+1)
init_guess[0] = np.mean(points[:,0])
# make a temporary copy
points_tmp = np.copy(points)
if verbose:
print('correction for {} order distortions.'.format(ns))
print('starting with subsequent fitting:')
# subsequently fit the orders
for i in range(len(ns)):
# optimize order to points_tmp
popt, flag = scipy.optimize.leastsq(residuals_dis, np.array((init_guess[0], 0.1, 0.1)),
args=(points_tmp, (ns[i],)), maxfev=maxfev)
if flag not in [1, 2, 3, 4]:
print('WARNING: optimization of distortions failed.')
# information
if verbose:
print('fitted order {}: R={} alpha={} beta={}'.format(ns[i], popt[0], popt[1], popt[2]))
# save for full fit
init_guess[i*2+1] = popt[1]
init_guess[i*2+2] = popt[2]
# do correction
points_tmp[:, 0] /= rad_dis(points_tmp[:, 1], popt[1], popt[2], ns[i])
# full fit
if verbose:
print('starting the full fit:')
popt, flag = scipy.optimize.leastsq(residuals_dis, init_guess, args=(points, ns), maxfev=maxfev)
if flag not in [1, 2, 3, 4]:
print('WARNING: optimization of distortions failed.')
if verbose:
print('fitted to: R={}'.format(popt[0]))
for i in range(len(ns)):
print('.. order={}, alpha={}, beta={}'.format(ns[i], popt[i*2+1], popt[i*2+2]))
return popt
| ercius/openNCEM | ncempy/algo/distortion.py | Python | gpl-3.0 | 8,278 |
#include "stdafx.h"
#include "Helper.h"
#include "common.h"
Helper::Helper(void)
{
x = rand() % wide;
y = 0;
type = rand() % 5;
exist = true;
}
Helper::~Helper(void)
{
}
//wide
//height
void Helper::get(Player* p)
{
y += 2;
if (y >= height)//ÅжÏÊÇ·ñ³öÁËÆÁÄ»
{
y = height-1;
exist = false;
}
if(exist && x >= p->x-p->size && x <= p->x + p->size && y >= p->y-p->size && y <= p->y+p->size)//ײÉÏÍæ¼Ò
{
if(type == 0){
p->BombState = 3;
}
else if(type == 1){
p->bombnum ++;
}
else if(type == 2){
p->BombState = 2;
//p->PlaneState = 0;
}
else if(type == 3){
p->hp ++;
}
else if(type == 4){
if(p->PlaneState <= 1)
p->PlaneState ++;
p->size = 40;
}
exist = false;
}
}
//Laser,Bomb,General,Hp,Protect
void Helper::update(Player* p)
{
get(p);//Laser
if(!exist) return;
if(type == 0){
SelectObject(bufdc ,Laser);
TransparentBltU(mdc , x, y ,20 , 20 , bufdc , 0, 0, 20, 20, RGB(255,255,255));
//BitBlt(mdc , x, y , 10 , 10 ,bufdc , 0 , 0 ,SRCCOPY);
}
else if(type == 1){
SelectObject(bufdc ,Bomb);
TransparentBltU(mdc , x, y ,20 , 20 , bufdc , 0, 0, 20, 20, RGB(255,255,255));
//BitBlt(mdc , x, y , 10 , 10 ,bufdc , 0 , 0 ,SRCCOPY);
}
else if(type == 2){
SelectObject(bufdc ,General);
TransparentBltU(mdc , x, y ,20 , 20 , bufdc , 0, 0, 20, 20, RGB(255,255,255));
//BitBlt(mdc , x, y , 10 , 10 ,bufdc , 0 , 0 ,SRCCOPY);
}
else if(type == 3){
SelectObject(bufdc ,Hp);
TransparentBltU(mdc , x, y ,20 , 20 , bufdc , 0, 0, 20, 20, RGB(255,255,255));
//BitBlt(mdc , x, y , 10 , 10 ,bufdc , 0 , 0 ,SRCCOPY);
}
else if(type == 4){
SelectObject(bufdc ,Protect);
TransparentBltU(mdc , x, y ,20 , 20 , bufdc , 0, 0, 20, 20, RGB(255,255,255));
//BitBlt(mdc , x, y , 10 , 10 ,bufdc , 0 , 0 ,SRCCOPY);
}
} | zhangry868/Aircraft-Game-MFC | Plane/Helper.cpp | C++ | gpl-3.0 | 1,790 |
global.should = require('should');
global.Breadboard = require('../lib'); | palra/breadboard | test/globalHooks.js | JavaScript | gpl-3.0 | 73 |
package net.therap.controller;
import net.therap.domain.Notification;
import net.therap.domain.User;
import net.therap.service.NotificationService;
import net.therap.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* @author rifatul.islam
* @since 8/12/14.
*/
@Controller
public class NotificationController {
@Autowired
private NotificationService notificationService;
@Autowired
private UserService userService;
@RequestMapping(value = "/notification/{receiverId}", method = RequestMethod.GET)
public ModelAndView showAllNotification(@PathVariable int receiverId) {
List<Notification> notificationList = notificationService.getAllNotification(receiverId);
ModelAndView modelAndView = new ModelAndView("user/notification");
modelAndView.addObject("notificationList", notificationList);
return modelAndView;
}
@RequestMapping("/getSenderImage/{userId}")
@ResponseBody
public byte[] getProfilePicture(@PathVariable int userId) {
User user = userService.getUserById(userId);
return user.getProfilePicture();
}
@RequestMapping(value = "/sendNotification", method = RequestMethod.POST)
@ResponseBody
public void sendNotification(@RequestParam("receiverId") int receiverId, @RequestParam("bookId") int bookId
, @RequestParam("type") int type, @RequestParam("isSeen") boolean isSeen, HttpSession session) {
User user = (User) session.getAttribute("user");
notificationService.addNewNotification(user.getUserId(), receiverId, bookId, type, isSeen);
}
@RequestMapping(value = "/updateNotification", method = RequestMethod.POST)
@ResponseBody
public void updateNotification(@RequestParam("id") int notificationId, @RequestParam("receiverId") int receiverId,
@RequestParam("bookId") int bookId, @RequestParam("type") int type,
@RequestParam("isSeen") boolean isSeen, HttpSession session) {
User user = (User) session.getAttribute("user");
notificationService.updateAndInsertNotification(notificationId,
user.getUserId(), receiverId, bookId, type, isSeen);
}
@RequestMapping(value = "/notification/getNotificationCounter", method = RequestMethod.GET)
@ResponseBody
public long getNotificationCounter(HttpSession session) {
User user = (User) session.getAttribute("user");
long total = notificationService.getUnseenNotification(user.getUserId());
System.out.println("total = " + total);
return total;
}
}
| shovonis/bookworm | application/book-worm/src/main/java/net/therap/controller/NotificationController.java | Java | gpl-3.0 | 2,867 |
<?php
if(!isset($_SESSION)) { session_start(); }
if(!isset($_SESSION['login'])) {
die('Please sign in');
} else {
if($_SERVER["HTTPS"] != "on")
{
die('Must use HTTPS');
}
}
session_write_close();
//var_dump($_REQUEST);
if(isset($_REQUEST['d'])&&isset($_REQUEST['s'])) {
$base_dir="/var/www/factorio/";
$html_dir="/var/www/html";
include('../../getserver.php');
if(isset($server_select)) {
if($_REQUEST['s']) {
$screen = $_REQUEST['s'];
$screenlog = '/var/www/factorio/'.$server_select.'/screenlog.0';
$chatlog = '/var/www/factorio/'.$server_select.'/chatlog.0';
$find=array("<", ">", "\\");
$repl=array("<", ">", "");
if($screen=="chat"&&file_exists($chatlog)) {
$output = shell_exec('cat '.$chatlog.' | tail -n 75');
$output = str_replace($find, $repl, $output);
echo str_replace(PHP_EOL, '', $output); //add newlines
} elseif($screen=="console"&&file_exists($screenlog)) {
$output = shell_exec('cat '.$screenlog.' | tail -n 75');
$output = str_replace($find, $repl, $output);
echo str_replace(PHP_EOL, '', $output); //add newlines
}
}
}
}
?>
| 3RaGaming/Web_Control | html/assets/api/console.php | PHP | gpl-3.0 | 1,136 |
package com.sigmasq.timely.solver;
public class CloudComputer {
private int cpuPower;
private int memory;
private int networkBandwidth;
private int cost;
public int getCpuPower() {
return cpuPower;
}
public int getMemory() {
return memory;
}
public int getNetworkBandwidth() {
return networkBandwidth;
}
public int getCost() {
return cost;
}
}
| oapa/timely | CalendarSync/src/com/sigmasq/timely/solver/CloudComputer.java | Java | gpl-3.0 | 431 |
#!/usr/bin/env python
# coding=utf-8
import flask
from flask import flash
from flask_login import login_required
from rpress.models import SiteSetting
from rpress.database import db
from rpress.runtimes.rpadmin.template import render_template, navbar
from rpress.runtimes.current_session import get_current_site, get_current_site_info
from rpress.forms import SettingsForm
app = flask.Blueprint('rpadmin_setting', __name__)
@app.route('/', methods=['GET', ])
@login_required
@navbar(level1='settings')
def list():
content = {
'site': get_current_site_info(),
}
return render_template('rpadmin/settings/list.html', content=content)
@app.route('/<string:key>/edit', methods=['GET', 'POST'])
@login_required
@navbar(level1='settings')
def edit(key):
site = get_current_site()
site_setting = SiteSetting.query.filter_by(site=site, key=key).order_by('created_time').first()
if site_setting is None:
site_setting = SiteSetting(
site_id=site.id,
key=key,
value=None,
)
form = SettingsForm(obj=site_setting)
if form.validate_on_submit():
form.populate_obj(site_setting)
db.session.add(site_setting)
db.session.commit()
flash("settings updated", "success")
else:
flash('settings edit error')
return render_template("rpadmin/settings/edit.html", form=form, site_setting=site_setting)
| rexzhang/rpress | rpress/views/rpadmin/settings.py | Python | gpl-3.0 | 1,428 |
namespace GoogleCast.Messages
{
/// <summary>
/// Interface for a message
/// </summary>
public interface IMessage
{
/// <summary>
/// Gets the message type
/// </summary>
string Type { get; }
}
}
| kakone/GoogleCast | GoogleCast/Messages/IMessage.cs | C# | gpl-3.0 | 256 |
function PingPongPaddle(x, y, z, radius) {
this.x = x;
this.y = y;
this.z = z;
this.radius = radius;
}
PingPongPaddle.prototype = {
rotation: new THREE.Vector3(0, 0, 0),
init: function(scene) {
var tableImage = THREE.ImageUtils.loadTexture('images/paddle_texture.jpg');
//var geometry = new THREE.CubeGeometry(this.radius, this.radius, .1);
var geometry = new THREE.CylinderGeometry(this.radius, this.radius, .1, 16, 1);
this.paddle = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
map: tableImage,
transparent: true,
opacity: .5
}));
//this.paddle.doubleSided = true;
this.rotate(Math.PI / 2, 0, 0);
this.paddle.position.x = this.x;
this.paddle.position.y = this.y;
this.paddle.position.z = this.z;
scene.add(this.paddle);
},
update: function() {
if (this.paddle.position.y > 20) {
direction = -1;
} else if (this.paddle.position.y < -20) {
direction = 1;
}
this.paddle.position.y += direction * .1;
},
hitPaddle: function(x, y, z, radius) {
if (Math.abs(this.paddle.position.x - x) < radius) {
return isBetween(y, this.paddle.position.y + this.radius / 2, this.paddle.position.y - this.radius / 2) && isBetween(z, this.paddle.position.z + this.radius / 2, this.paddle.position.z - this.radius / 2);
}
},
rotate: function(x, y, z) {
this.paddle.rotateOnAxis(new THREE.Vector3(1, 0, 0), x);
this.rotation.x += x;
this.paddle.rotateOnAxis(new THREE.Vector3(0, 1, 0), y);
this.rotation.y += y;
this.paddle.rotateOnAxis(new THREE.Vector3(0, 0, 1), z);
this.rotation.z += z;
}
}
var direction = 1;
function isBetween(x, x1, x2) {
return (x <= x1 && x >= x2) || (x >= x1 && x <= x2);
} | mryan23/PingPongServer | war/js/ping_pong_paddle.js | JavaScript | gpl-3.0 | 1,903 |
package com.fastaccess.data.dao.types;
import androidx.annotation.StringRes;
import com.fastaccess.R;
public enum IssueState {
open(R.string.opened),
closed(R.string.closed),
all(R.string.all);
int status;
IssueState(@StringRes int status) {
this.status = status;
}
@StringRes public int getStatus() {
return status;
}
} | k0shk0sh/FastHub | app/src/main/java/com/fastaccess/data/dao/types/IssueState.java | Java | gpl-3.0 | 374 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sudemax.Properties;
using Sudemax.FormExtension;
using Sudemax.DataGridViewExtension;
namespace Sudemax
{
public partial class PeliculaMainForm : Form
{
public PeliculaMainForm()
{
InitializeComponent();
Icon = Resources.applicationsMultimedia32x32;
dataGridView.AutoGenerateColumns = false;
initPeliculas();
}
private BindingList<Pelicula> peliculas;
private void initPeliculas()
{
using (PeliculaRepository repo = new PeliculaRepository())
{
peliculas = new BindingList<Pelicula>(repo.FindAll());
}
dataGridView.DataSource = peliculas;
}
private void onNewPelicula(object sender, EventArgs e)
{
using (PeliculaForm form = new PeliculaForm())
{
form.Text = "Agregando nueva película";
form.ConfigureAsDialog();
if (form.ShowDialog(this) == DialogResult.OK)
{
Pelicula pelicula = form.Pelicula;
peliculas.Add(pelicula);
dataGridView.SelectLastRowAndScroll();
}
}
}
private void onEditPelicula(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int selectedRowIndex = dataGridView.SelectedRows[0].Index;
try
{
using (PeliculaRepository repo = new PeliculaRepository())
{
using (PeliculaForm form = new PeliculaForm())
{
form.Text = "Editando película";
form.ConfigureAsDialog();
form.Pelicula = repo.FindById(peliculas[selectedRowIndex].Id);
if (form.ShowDialog(this) == DialogResult.OK)
{
peliculas[selectedRowIndex] = form.Pelicula;
}
}
}
}
catch (BusinessEntityRepositoryException ex)
{
this.ShowExceptionMessageBox(ex);
}
}
}
private void onDeletePelicula(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int selectedRowIndex = dataGridView.SelectedRows[0].Index;
Pelicula pelicula = peliculas[selectedRowIndex];
string msg = "Está a punto de eliminar \"" + pelicula.Titulo +
"\". ¿Está seguro de querer continuar?";
DialogResult dialogResult = MessageBox.Show(this, msg,
"Advertencia", MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
if (dialogResult == DialogResult.OK)
{
try
{
using (PeliculaRepository repo = new PeliculaRepository())
{
repo.Delete(pelicula);
}
peliculas.RemoveAt(selectedRowIndex);
MessageBox.Show(this, "\"" + pelicula.Titulo +
"\" eliminada correctamente.", "Información",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (BusinessEntityRepositoryException ex)
{
this.ShowExceptionMessageBox(ex);
}
}
}
}
private void onStartSimpleFind(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char) Keys.Enter
&& !string.IsNullOrWhiteSpace(findToolStripTextBox.Text))
{
findToolStripButton.PerformClick();
}
}
private void onFindMenuItemClick(object sender, EventArgs e)
{
findToolStripTextBox.Focus();
}
private void onSearchClean(object sender, EventArgs e)
{
findToolStripTextBox.Clear();
findToolStripTextBox.Focus();
initPeliculas();
}
private void onAdvancedFind(object sender, EventArgs e)
{
this.ShowNotImplementedMessageBox();
}
private void onColumnHeaderClick(object sender, DataGridViewCellMouseEventArgs e)
{
this.ShowNotImplementedMessageBox();
}
private void onSimpleFind(object sender, EventArgs e)
{
try
{
using (PeliculaRepository repo = new PeliculaRepository())
{
peliculas = new BindingList<Pelicula>(repo.FindByTitulos(findToolStripTextBox.Text));
}
}
catch (BusinessEntityRepositoryException ex)
{
this.ShowExceptionMessageBox(ex);
}
dataGridView.DataSource = peliculas;
}
}
}
| emegeve/Sudemax | Sudemax/PeliculaMainForm.cs | C# | gpl-3.0 | 5,507 |
// Copyright © 2011-2013 Yanick Castonguay
//
// This file is part of MPfm.
//
// MPfm 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.
//
// MPfm 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 MPfm. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace ProjectSync
{
public static class ProjectFileReader
{
public static List<string> ExtractProjectCompileFilePaths(string projectFilePath)
{
// Read XML content
List<string> filePaths = new List<string>();
string fileContents = File.ReadAllText(projectFilePath);
XDocument xdoc = XDocument.Parse(fileContents);
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XElement elProject = xdoc.Element(ns + "Project");
List<XElement> elItemGroups = xdoc.Descendants(ns + "ItemGroup").ToList();
List<XElement> elGlobalCompiles = xdoc.Descendants(ns + "Compile").ToList();
if(elProject == null)
throw new Exception("Could not find the Project xml node.");
foreach (XElement elItemGroup in elItemGroups)
{
List<XElement> elCompiles = elItemGroup.Descendants(ns + "Compile").ToList();
foreach (XElement elCompile in elCompiles)
{
XAttribute include = elCompile.Attribute("Include");
if (include != null)
{
filePaths.Add(include.Value);
}
}
}
return filePaths;
}
}
}
| ycastonguay/VSProjectSync | ProjectFileReader.cs | C# | gpl-3.0 | 2,148 |
/*
* Copyright © 2017 No0n3Left <no0n3left@gmail.com>
*
* This file is part of Remnant
*
* Remnant 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.
*
* Remnant 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 Remnant. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assimp/cimport.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <functional>
#include "opengl/mesh.h"
Mesh::Mesh(const std::string& filename, unsigned int index): hash(Mesh::pre_hash(filename, index))
{
const aiScene* scene = aiImportFile(filename.c_str(), aiProcess_Triangulate | aiProcess_CalcTangentSpace);
const aiMesh* mesh = scene->mMeshes[index];
this->name = mesh->mName.C_Str();
this->vertex_count = mesh->mNumVertices;
std::cout << "Vertices = " << this->vertex_count << std::endl;
if (mesh->HasPositions()) {
GLfloat* vertex_positions = new GLfloat[this->vertex_count * 3];
for (unsigned int i = 0; i < this->vertex_count; ++i) {
const aiVector3D* vertex_position = &(mesh->mVertices[i]);
vertex_positions[i * 3 + 0] = static_cast<GLfloat>(vertex_position->x);
vertex_positions[i * 3 + 1] = static_cast<GLfloat>(vertex_position->y);
vertex_positions[i * 3 + 2] = static_cast<GLfloat>(vertex_position->z);
}
this->position_vbo.set_data(3 * sizeof(GLfloat) * this->vertex_count, vertex_positions, GL_STATIC_DRAW);
this->position_vbo.bind();
this->vao.enable_attrib(0);
this->vao.attrib_pointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERRORDEBUG();
delete[] vertex_positions;
}
if (mesh->HasTextureCoords(0)) {
GLfloat* vertex_texcoords = new GLfloat[this->vertex_count * 2];
for (unsigned int i = 0; i < this->vertex_count; ++i) {
const aiVector3D* vertex_texcoord = &(mesh->mTextureCoords[0][i]);
vertex_texcoords[i * 2 + 0] = static_cast<GLfloat>(vertex_texcoord->x);
vertex_texcoords[i * 2 + 1] = static_cast<GLfloat>(vertex_texcoord->y);
}
this->texcoord_vbo.set_data(3 * sizeof(GLfloat) * this->vertex_count, vertex_texcoords, GL_STATIC_DRAW);
delete[] vertex_texcoords;
this->texcoord_vbo.bind();
this->vao.enable_attrib(1);
this->vao.attrib_pointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLERRORDEBUG();
}
if (mesh->HasNormals()) {
GLfloat* vertex_normals = new GLfloat[this->vertex_count * 3];
for (unsigned int i = 0; i < this->vertex_count; ++i) {
const aiVector3D* vertex_normal = &(mesh->mNormals[i]);
vertex_normals[i * 3 + 0] = static_cast<GLfloat>(vertex_normal->x);
vertex_normals[i * 3 + 1] = static_cast<GLfloat>(vertex_normal->y);
vertex_normals[i * 3 + 2] = static_cast<GLfloat>(vertex_normal->z);
}
this->normal_vbo.set_data(3 * sizeof(GLfloat) * this->vertex_count, vertex_normals, GL_STATIC_DRAW);
delete[] vertex_normals;
this->normal_vbo.bind();
this->vao.enable_attrib(2);
this->vao.attrib_pointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERRORDEBUG();
}
if(mesh->HasTangentsAndBitangents()) {
GLfloat* vertex_tangents = new GLfloat[this->vertex_count * 3];
for (unsigned int i = 0; i < this->vertex_count; ++i) {
const aiVector3D* vertex_tangent = &(mesh->mTangents[i]);
vertex_tangents[i * 3 + 0] = static_cast<GLfloat>(vertex_tangent->x);
vertex_tangents[i * 3 + 1] = static_cast<GLfloat>(vertex_tangent->y);
vertex_tangents[i * 3 + 2] = static_cast<GLfloat>(vertex_tangent->z);
}
this->tangent_vbo.set_data(3 * sizeof(GLfloat) * this->vertex_count, vertex_tangents, GL_STATIC_DRAW);
delete[] vertex_tangents;
this->tangent_vbo.bind();
this->vao.enable_attrib(3);
this->vao.attrib_pointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERRORDEBUG();
}
this->material = std::make_shared<Material>(scene->mMaterials[mesh->mMaterialIndex]);
aiReleaseImport(scene);
}
Mesh::Mesh(Mesh&& other)
: hash(std::move(other.hash)), material(std::move(other.material)), vao(std::move(other.vao)), vertex_count(std::move(other.vertex_count)),
position_vbo(std::move(other.position_vbo)), texcoord_vbo(std::move(other.texcoord_vbo)), normal_vbo(std::move(other.normal_vbo)), tangent_vbo(std::move(other.tangent_vbo)) {}
Mesh::~Mesh() {}
/*
Mesh& Mesh::operator=(Mesh&& other)
{
this->hash = std::move(other.hash);
this->material = std::move(other.material);
this->object_name = std::move(other.object_name);
this->vertex_count = std::move(other.vertex_count);
return *this;
}
*/
void Mesh::bind() const
{
this->vao.bind();
GLERRORDEBUG();
}
const std::shared_ptr<Material>& Mesh::get_material() const noexcept
{
return this->material;
}
GLuint Mesh::get_object_name() const noexcept
{
return this->vao.get_object_name();
}
unsigned int Mesh::get_vertex_count() const noexcept
{
return this->vertex_count;
}
std::size_t Mesh::pre_hash(const std::string& filename, unsigned int index)
{
return std::hash<std::string>()(filename); // XXX BAD REDO
}
| No0n3Left/Remnant | src/opengl/mesh.cpp | C++ | gpl-3.0 | 5,257 |
<?php
/**
* Copyright (C) 2007,2008 Arie Nugraha (dicarve@yahoo.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/* Biblio Topic Adding Pop Windows */
// key to authenticate
define('INDEX_AUTH', '1');
// main system configuration
require '../../../sysconfig.inc.php';
// IP based access limitation
require LIB.'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-bibliography');
// start the session
require SB.'admin/default/session.inc.php';
require SIMBIO.'simbio_GUI/table/simbio_table.inc.php';
require SIMBIO.'simbio_GUI/form_maker/simbio_form_table.inc.php';
require SIMBIO.'simbio_DB/simbio_dbop.inc.php';
// page title
$page_title = 'Subject List';
// check for biblioID in url
$biblioID = 0;
if (isset($_GET['biblioID']) AND $_GET['biblioID']) {
$biblioID = (integer)$_GET['biblioID'];
}
// utility function to check subject/topic
function checkSubject($str_subject, $str_subject_type = 't')
{
global $dbs;
$_q = $dbs->query('SELECT topic_id FROM mst_topic WHERE topic=\''.$str_subject.'\' AND topic_type=\''.$str_subject_type.'\'');
if ($_q->num_rows > 0) {
$_d = $_q->fetch_row();
// return the subject/topic ID
return $_d[0];
}
return false;
}
// start the output buffer
ob_start();
/* main content */
// biblio topic save proccess
if (isset($_POST['save']) AND (isset($_POST['topicID']) OR trim($_POST['search_str']))) {
$subject = trim($dbs->escape_string(strip_tags($_POST['search_str'])));
// create new sql op object
$sql_op = new simbio_dbop($dbs);
// check if biblioID POST var exists
if (isset($_POST['biblioID']) AND !empty($_POST['biblioID'])) {
$data['biblio_id'] = (integer)$_POST['biblioID'];
// check if the topic select list is empty or not
if (!empty($_POST['topicID'])) {
$data['topic_id'] = $_POST['topicID'];
} else if ($subject AND empty($_POST['topicID'])) {
// check subject
$subject_id = checkSubject($subject, $_POST['type']);
if ($subject_id !== false) {
$data['topic_id'] = $subject_id;
} else {
// adding new topic
$topic_data['topic'] = $subject;
$topic_data['topic_type'] = $_POST['type'];
$topic_data['input_date'] = date('Y-m-d');
$topic_data['last_update'] = date('Y-m-d');
// insert new topic to topic master table
$sql_op->insert('mst_topic', $topic_data);
// put last inserted ID
$data['topic_id'] = $sql_op->insert_id;
}
}
$data['level'] = intval($_POST['level']);
if ($sql_op->insert('biblio_topic', $data)) {
echo '<script type="text/javascript">';
echo 'alert(\'Topic succesfully updated!\');';
echo 'parent.setIframeContent(\'topicIframe\', \''.MWB.'bibliography/iframe_topic.php?biblioID='.$data['biblio_id'].'\');';
echo '</script>';
} else {
utility::jsAlert(__('Subject FAILED to Add. Please Contact System Administrator')."\n".$sql_op->error);
}
} else {
if (!empty($_POST['topicID'])) {
// add to current session
$_SESSION['biblioTopic'][$_POST['topicID']] = array($_POST['topicID'], intval($_POST['level']));
} else if ($subject AND empty($_POST['topicID'])) {
// check subject
$subject_id = checkSubject($subject);
if ($subject_id !== false) {
$last_id = $subject_id;
} else {
// adding new topic
$topic_data['topic'] = $subject;
$topic_data['topic_type'] = $_POST['type'];
$topic_data['input_date'] = date('Y-m-d');
$topic_data['last_update'] = date('Y-m-d');
// insert new topic to topic master table
$sql_op->insert('mst_topic', $topic_data);
$last_id = $sql_op->insert_id;
}
$_SESSION['biblioTopic'][$last_id] = array($last_id, intval($_POST['level']));
}
echo '<script type="text/javascript">';
echo 'alert(\''.__('Subject added!').'\');';
echo 'parent.setIframeContent(\'topicIframe\', \''.MWB.'bibliography/iframe_topic.php\');';
echo '</script>';
}
}
?>
<div class="popUpForm">
<form name="mainForm" action="pop_topic.php?biblioID=<?php echo $biblioID; ?>" method="post">
<div>
<strong><?php echo __('Add Subject'); ?></strong>
<hr />
<form name="searchTopic" method="post" style="display: inline;">
<?php
$ajax_exp = "ajaxFillSelect('../../AJAX_vocabolary_control.php', 'mst_topic', 'topic_id:topic:topic_type', 'topicID', $('#search_str').val())";
?>
<?php echo __('Keyword'); ?> : <input type="text" name="search_str" id="search_str" style="width: 30%;" onkeyup="<?php echo $ajax_exp; ?>" />
<select name="type" style="width: 20%;"><?php
foreach ($sysconf['subject_type'] as $type_id => $type) {
echo '<option value="'.$type_id.'">'.$type.'</option>';
}
?></select>
<select name="level" style="width: 20%;">
<?php
echo '<option value="1">Primary</option>';
echo '<option value="2">Additional</option>';
?>
</select>
</div>
<div class="popUpSubForm">
<div class="row" style="overflow-y:scroll; max-height:170px; margin-bottom: 10px; padding-left: 55px;">
<ul id="topicID">
<li><?php echo __('Type to search for existing topics or to add a new one'); ?></li>
</ul>
</div>
<?php if ($biblioID) { echo '<input type="hidden" name="biblioID" value="'.$biblioID.'" />'; } ?>
<input type="submit" name="save" value="<?php echo __('Insert To Bibliography'); ?>" class="popUpSubmit btn btn-primary" />
</div>
</form>
<script type="text/javascript">
$('#topicID').mouseover(function() {
$('.voc').mouseover(function() {
$(this).css({'cursor': 'pointer', 'background': '#b3e5fc'});
})
.mouseleave(function() {
$(this).css('background', 'none');
})
.click(function() {
var vocVal = $(this).text();
$('#search_str').val(vocVal);
ajaxFillSelect('../../AJAX_vocabolary_control.php', 'mst_topic', 'topic_id:topic:topic_type', 'topicID', vocVal);
});
});
</script>
</div>
<?php
/* main content end */
$content = ob_get_clean();
// include the page template
require SB.'/admin/'.$sysconf['admin_template']['dir'].'/notemplate_page_tpl.php';
| yuannet/slims8_akasia | admin/modules/bibliography/pop_topic.php | PHP | gpl-3.0 | 7,436 |
using System;
using Chronos.Model;
namespace Chronos.Java.BasicProfiler
{
[Serializable]
public sealed class ThreadInfo : UnitBase
{
public ThreadInfo(ThreadNativeInfo threadInfo)
: base(threadInfo)
{
}
private ThreadNativeInfo ThreadNativeInfo
{
get { return (ThreadNativeInfo)NativeUnit; }
}
public uint OsThreadId
{
get { return ThreadNativeInfo.OsThreadId; }
}
internal void SetDependencies()
{
}
}
}
| AndreiFedarets/chronosprofiler | source/Chronos.Java.BasicProfiler/Chronos.Java.BasicProfiler/ThreadInfo.cs | C# | gpl-3.0 | 560 |