repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ARIG-Robotique/robots | robot-system-lib-parent/robot-system-lib-core/src/main/java/org/arig/robot/model/Position.java | 825 | package org.arig.robot.model;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* The Class Position.
* <p>
* En vu de dessus :
* <p>
* y (2000) |
* |
* |
* |
* |
* |---------------------------------- x (3000)
* 0,0
* <p>
* angle = 0 dans le sens de X dans le sens trigo
*
* @author gdepuille
*/
@Data
@AllArgsConstructor
public class Position {
private Point pt;
private double angle;
public Position() {
pt = new Point();
updatePosition(0, 0, 0);
}
public void updatePosition(final double x, final double y, final double angle) {
pt.setX(x);
pt.setY(y);
setAngle(angle);
}
public void addDeltaX(final double dX) {
pt.addDeltaX(dX);
}
public void addDeltaY(final double dY) {
pt.addDeltaY(dY);
}
}
| gpl-3.0 |
4levity/FastWords | src/com/ijklibrarian/fastwords/NotifyService.java | 1163 | package com.ijklibrarian.fastwords;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.StrictMode;
public class NotifyService extends Service {
private static final int ONGOING_NOTIFICATION = 1;
@SuppressWarnings("deprecation")
@Override
public void onCreate() {
super.onCreate();
// TODO: remove this and make network access async!
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Notification notification = new Notification(R.drawable.ic_action_search, getText(R.string.app_name),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, SelectWordSearch.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name),
getText(R.string.app_name), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| gpl-3.0 |
mozartframework/cms | src/com/mozartframework/mozart/controller/cache/InstanceCreator.java | 110 | package com.mozartframework.mozart.controller.cache;
public interface InstanceCreator<T> {
T create();
}
| gpl-3.0 |
woshikie/Just-Another-Magic-Simulator | Just Another Magic Simulator/Assets/Logic/Cards/KLD/L/LathnuHellion.cs | 568 |
using System.Collections;
namespace Card
{
public class LathnuHellion : Card
{
/*
Haste
When Lathnu Hellion enters the battlefield, you get {E}{E} (two energy counters).
At the beginning of your end step, sacrifice Lathnu Hellion unless you pay {E}{E}.
*/
private const string UniqueCardName = "Lathnu Hellion";
public LathnuHellion() : base(UniqueCardName) {
}
protected override void OnConstructed()
{
Types = new string[] { };
Colors = new string[] { };
SubTypes = new string[] { };
SuperTypes = new string[] { };
}
}
}
| gpl-3.0 |
mystyle-platform/mystyle-wp-custom-product-designer | tests/includes/pages/test-mystyle-design-profile-page.php | 19117 | <?php
/**
* The MyStyleDesignProfilePageTest class includes tests for testing the
* MyStyle_Design_Profile_Page class.
*
* @package MyStyle
* @since 1.4.0
*/
/**
* Test requirements.
*/
require_once MYSTYLE_INCLUDES . 'frontend/class-mystyle-frontend.php';
require_once MYSTYLE_PATH . 'tests/mocks/mock-mystyle-design.php';
require_once MYSTYLE_PATH . 'tests/mocks/mock-mystyle-designqueryresult.php';
/**
* MyStyleDesignProfilePageTest class.
*/
class MyStyleDesignProfilePageTest extends WP_UnitTestCase {
/**
* Overwrite the setUp function so that our custom tables will be persisted
* to the test database.
*/
public function setUp() {
// Perform the actual task according to parent class.
parent::setUp();
// Remove filters that will create temporary tables. So that permanent
// tables will be created.
remove_filter( 'query', array( $this, '_create_temporary_tables' ) );
remove_filter( 'query', array( $this, '_drop_temporary_tables' ) );
// Create the tables.
MyStyle_Install::create_tables();
}
/**
* Overwrite the tearDown function to remove our custom tables.
*
* @global $wpdb
*/
public function tearDown() {
global $wpdb;
// Perform the actual task according to parent class.
parent::tearDown();
// Drop the tables that we created.
$wpdb->query( 'DROP TABLE IF EXISTS ' . MyStyle_Design::get_table_name() );
$wpdb->query( 'DROP TABLE IF EXISTS ' . MyStyle_Session::get_table_name() );
// Reset the server globals.
$_SERVER['REQUEST_METHOD'] = 'GET';
MyStyle_Design_Profile_Page::reset_instance();
}
/**
* Test the constructor.
*
* @global wp_filter
*/
public function test_constructor() {
global $wp_filter;
$mystyle_design_profile_page = new MyStyle_Design_Profile_Page();
// Assert that the init function is registered.
$function_names = get_function_names( $wp_filter['init'] );
$this->assertContains( 'init', $function_names );
}
/**
* Test the init function with.
*
* @global \stdClass $post
*/
public function test_init_with_valid_design_id() {
global $post;
// Default the response code to 200.
if ( function_exists( 'http_response_code' ) ) {
http_response_code( 200 );
}
$design_id = 1;
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Mock the request uri and post as though we were loading the design
// profile page for design 1.
$_SERVER['REQUEST_URI'] = 'http://localhost/designs/' . $design_id;
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
// Get the Mystyle_Design_Profile page singleton.
$mystyle_design_profile_page = MyStyle_Design_Profile_Page::get_instance();
// Call the function.
$mystyle_design_profile_page->init();
// Get the current design from the singleton instance.
$current_design = $mystyle_design_profile_page->get_design();
// Assert that the page was created and has the expected title.
$this->assertEquals( $design_id, $current_design->get_design_id() );
// Assert that the http response code is set to 200.
$this->assertEquals( 200, $mystyle_design_profile_page->get_http_response_code() );
// Assert that the exception is null.
$this->assertEquals( null, $mystyle_design_profile_page->get_exception() );
}
/**
* Test the init function with no design id.
*
* @global stdClass $post
*/
public function test_init_with_no_design_id() {
global $post;
if ( ! defined( 'MYSTYLE_DESIGNS_PER_PAGE' ) ) {
define( 'MYSTYLE_DESIGNS_PER_PAGE', 25 );
}
$design_id = 1;
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Reset the singleton instance (to clear out any previously set values).
MyStyle_Design_Profile_Page::reset_instance();
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
// NOTE: we would normally create a design here but for this test,
// the design doesn't exist.
// mock the request uri and post as though we were loading the design
// index.
$_SERVER['REQUEST_URI'] = 'http://localhost/designs/';
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
// Call the function.
MyStyle_Design_Profile_Page::get_instance()->init();
// Get the Mystyle_Design_Profile page singleton.
$mystyle_design_profile_page = MyStyle_Design_Profile_Page::get_instance();
// Assert that no design is loaded.
$this->assertNull( null, $mystyle_design_profile_page->get_design() );
// Assert that the http response code is set to 200.
$this->assertEquals( 200, $mystyle_design_profile_page->get_http_response_code() );
$pager = $mystyle_design_profile_page->get_pager();
$this->assertTrue( ! empty( $pager ) );
}
/**
* Test the init function.
*
* @global stdClass $post
*/
public function test_init_with_a_non_existant_design_id() {
global $post;
$design_id = 999;
// Reset the singleton instance (to clear out any previously set values).
MyStyle_Design_Profile_Page::reset_instance();
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
// NOTE: we would normally create a design here but for this test,
// the design doesn't exist.
// mock the request uri and post as though we were loading the design
// profile page for design 1 (which doesn't exist).
$_SERVER['REQUEST_URI'] = 'http://localhost/designs/' . $design_id;
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
// Call the function.
MyStyle_Design_Profile_Page::get_instance()->init();
// Get the Mystyle_Design_Profile page singleton.
$mystyle_design_profile_page = MyStyle_Design_Profile_Page::get_instance();
// Assert that no design is loaded.
$this->assertNull( null, $mystyle_design_profile_page->get_design() );
// Assert that the http response code is set to 404.
$this->assertEquals( 404, $mystyle_design_profile_page->get_http_response_code() );
// Assert that the exception is set.
$this->assertEquals(
'MyStyle_Not_Found_Exception',
get_class( $mystyle_design_profile_page->get_exception() )
);
}
/**
* Test the init function with.
*
* @global stdClass $post
*/
public function test_init_with_post_request() {
global $post;
// Default the response code to 200.
if ( function_exists( 'http_response_code' ) ) {
http_response_code( 200 );
}
$design_id = 1;
$new_design_title = 'New Design Title';
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Mock the request uri and post as though we were loading the design
// profile page for design 1.
$_SERVER['REQUEST_URI'] = 'http://localhost/designs/' . $design_id;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST['ms_title'] = $new_design_title;
$_REQUEST['_wpnonce'] = wp_create_nonce( 'mystyle_design_edit_nonce' );
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
// Get the Mystyle_Design_Profile page singleton.
$mystyle_design_profile_page = MyStyle_Design_Profile_Page::get_instance();
// Call the function.
$mystyle_design_profile_page->init();
// Get the current design from the singleton instance.
$current_design = $mystyle_design_profile_page->get_design();
// Assert that the http response code is set to 200.
$this->assertEquals( 200, $mystyle_design_profile_page->get_http_response_code() );
// Assert that the Design title was updated as expected.
$this->assertEquals( $new_design_title, $current_design->get_title() );
// Assert that the exception is null.
$this->assertEquals( null, $mystyle_design_profile_page->get_exception() );
}
/**
* Test the create function.
*/
public function test_create() {
// Create the MyStyle Design Profile page.
$page_id = MyStyle_Design_Profile_Page::create();
$page = get_post( $page_id );
// Assert that the page was created and has the expected title.
$this->assertEquals( 'Community Design Gallery', $page->post_title );
}
/**
* Test the get_id function.
*/
public function test_get_id() {
// Create the MyStyle Design Profile page.
$page_id1 = MyStyle_Design_Profile_Page::create();
$page_id2 = MyStyle_Design_Profile_Page::get_id();
// Assert that the page id was successfully retrieved.
$this->assertEquals( $page_id2, $page_id1 );
}
/**
* Test the is_current_post function returns true when the current post is
* the Design Profile Page.
*
* @global stdClass $post
*/
public function test_is_current_post_returns_true_when_current_post() {
global $post;
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
// Mock the request uri.
$_SERVER['REQUEST_URI'] = 'http://localhost/designs/';
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
$this->assertTrue( MyStyle_Design_Profile_Page::is_current_post() );
}
/**
* Test the is_current_post function returns true when the current post is
* the Design Profile Page.
*/
public function test_is_current_post_returns_false_when_not_current_post() {
// Create the Design Profile Page.
$design_profile_page = MyStyle_Design_Profile_Page::create();
$this->assertFalse( MyStyle_Design_Profile_Page::is_current_post() );
}
/**
* Test the exists function.
*/
public function test_exists() {
// Assert that the exists function returns false before the page is created.
$this->assertFalse( MyStyle_Design_Profile_Page::exists() );
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Assert that the exists function returns true after the page is created.
$this->assertTrue( MyStyle_Design_Profile_Page::exists() );
}
/**
* Test the delete function.
*/
public function test_delete() {
// Create the MyStyle Design Profile page.
$page_id = MyStyle_Design_Profile_Page::create();
// Delete the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::delete();
// Attempt to get the page.
$page = get_post( $page_id );
// Assert that the page was deleted.
$this->assertEquals( $page->post_status, 'trash' );
}
/**
* Test the get_index_url function without permalinks.
*
* @global WP_Rewrite $wp_rewrite
*/
public function test_get_index_url_without_permalinks() {
global $wp_rewrite;
// disable page permalinks.
$wp_rewrite->page_structure = null;
// Create the MyStyle Design Profile page.
$page_id = MyStyle_Design_Profile_Page::create();
// Build the expected url.
$expected_url = 'http://example.org/?page_id=' . $page_id;
// Call the function.
$url = MyStyle_Design_Profile_Page::get_index_url();
// Assert that the exepected $url was returned.
$this->assertEquals( $expected_url, $url );
}
/**
* Test the get_index_url function with permalinks.
*
* @global WP_Rewrite $wp_rewrite
*/
public function test_get_index_url_with_permalinks() {
global $wp_rewrite;
// Enable page permalinks.
$wp_rewrite->page_structure = '%pagename%';
$design_id = 1;
$expected_url = 'http://example.org/designs';
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Call the function.
$url = MyStyle_Design_Profile_Page::get_index_url();
// Assert that the exepected $url was returned.
$this->assertEquals( $expected_url, $url );
}
/**
* Test the get_design_url function without permalinks.
*
* @global WP_Rewrite $wp_rewrite
*/
public function test_get_design_url_without_permalinks() {
global $wp_rewrite;
// disable page permalinks.
$wp_rewrite->page_structure = null;
$design_id = 1;
// Create the MyStyle Design Profile page.
$page_id = MyStyle_Design_Profile_Page::create();
// Build the expected url.
$expected_url = 'http://example.org/?page_id=' . $page_id . '&design_id=1';
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Call the function.
$url = MyStyle_Design_Profile_Page::get_design_url( $design );
// Assert that the exepected $url was returned.
$this->assertEquals( $expected_url, $url );
}
/**
* Test the get_design_url function with permalinks.
*
* @global WP_Rewrite $wp_rewrite
*/
public function test_get_design_url_with_permalinks() {
global $wp_rewrite;
// Enable page permalinks.
$wp_rewrite->page_structure = '%pagename%';
$design_id = 1;
$expected_url = 'http://example.org/designs/1';
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Call the function.
$url = MyStyle_Design_Profile_Page::get_design_url( $design );
// Assert that the exepected $url was returned.
$this->assertEquals( $expected_url, $url );
}
/**
* Test the get_design_url function when the post has a custom slug.
*
* @global WP_Rewrite $wp_rewrite
*/
public function test_get_design_url_with_custom_slug() {
global $wp_rewrite;
$slug = 'widgets';
// Enable page permalinks.
$wp_rewrite->page_structure = '%pagename%';
$design_id = 1;
$expected_url = 'http://example.org/' . $slug . '/1';
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Change to a custom slug.
wp_update_post(
array(
'ID' => MyStyle_Design_Profile_Page::get_id(),
'post_name' => $slug,
)
);
// Create a design.
$design = MyStyle_MockDesign::get_mock_design( $design_id );
// Persist the design.
MyStyle_DesignManager::persist( $design );
// Call the function.
$url = MyStyle_Design_Profile_Page::get_design_url( $design );
// Assert that the exepected $url was returned.
$this->assertEquals( $expected_url, $url );
}
/**
* Test the get_design_id_url function without permalinks.
*
* @global WP_Query $wp_query
*/
public function test_get_design_id_from_url_without_permalinks() {
global $wp_query;
$design_id = 1;
$query = 'http://localhost/index.php?page_id=1&design_id=' . $design_id;
// Init the mystyle frontend to register the design_id query var.
if ( ! defined( 'MYSTYLE_DESIGNS_PER_PAGE' ) ) {
define( 'MYSTYLE_DESIGNS_PER_PAGE', 25 );
}
MyStyle_FrontEnd::get_instance();
// Mock the current query.
$wp_query = new WP_Query( $query );
// Call the function.
$returned_design_id = MyStyle_Design_Profile_Page::get_design_id_from_url();
// Assert that the exepected design_id is returned.
$this->assertEquals( $design_id, $returned_design_id );
}
/**
* Test the get_design_id_url function with permalinks.
*/
public function test_get_design_id_from_url_with_permalinks() {
$design_id = 1;
$query = 'http://www.example.com/designs/' . $design_id;
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Mock the current query.
$_SERVER['REQUEST_URI'] = $query;
// Call the function.
$returned_design_id = MyStyle_Design_Profile_Page::get_design_id_from_url();
// Assert that the exepected design_id is returned.
$this->assertEquals( $design_id, $returned_design_id );
}
/**
* Test the get_design_id_url function with a custom slug.
*/
public function test_get_design_id_from_url_with_a_custom_slug() {
$design_id = 1;
$slug = 'widgets';
$query = 'http://www.example.com/' . $slug . '/' . $design_id;
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Change to a custom slug.
wp_update_post(
array(
'ID' => MyStyle_Design_Profile_Page::get_id(),
'post_name' => $slug,
)
);
// Mock the current query.
$_SERVER['REQUEST_URI'] = $query;
// Call the function.
$returned_design_id = MyStyle_Design_Profile_Page::get_design_id_from_url();
// Assert that the exepected design_id is returned.
$this->assertEquals( $design_id, $returned_design_id );
}
/**
* Test the filter_title function.
*
* @global $post
* @global $wp_query
*/
public function test_filter_title() {
global $post;
global $wp_query;
// Create the MyStyle Customize page.
MyStyle_Customize_Page::create();
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Create a design.
$result_object = new MyStyle_MockDesignQueryResult( 1 );
$design = MyStyle_Design::create_from_result_object( $result_object );
// Instantiate the MyStyle Design Profile page.
$mystyle_design_profile_page = MyStyle_Design_Profile_Page::get_instance();
$mystyle_design_profile_page->set_design( $design );
// Mock the post, etc.
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
$wp_query->in_the_loop = true;
// Call the function.
$new_title = $mystyle_design_profile_page->filter_title( 'foo', MyStyle_Design_Profile_Page::get_id() );
// Expected.
$expected = 'Design ' . $design->get_design_id();
// Assert that the title has been set as expected.
$this->assertEquals( $expected, $new_title );
}
/**
* Test the filter_body_class function.
*
* @global $post
*/
public function test_filter_body_class_adds_class_to_design_profile_page() {
global $post;
// Create the MyStyle Customize page.
MyStyle_Customize_Page::create();
// Create the MyStyle Design Profile page.
MyStyle_Design_Profile_Page::create();
// Mock the post and get vars.
$post = new stdClass();
$post->ID = MyStyle_Design_Profile_Page::get_id();
// Mock the $classes var.
$classes = array();
// Call the function.
$returned_classes = MyStyle_Design_Profile_Page::get_instance()->filter_body_class( $classes );
// Assert that the mystyle-design-profile class is added to the classes array.
$this->assertEquals( 'mystyle-design-profile', $returned_classes[0] );
}
/**
* Assert that show_add_to_cart_button() function.
*/
public function test_show_add_to_cart() {
// Set customize_page_title_hide.
$options = array();
update_option( MYSTYLE_OPTIONS_NAME, $options );
$options['design_profile_page_show_add_to_cart'] = 1;
update_option( MYSTYLE_OPTIONS_NAME, $options );
$show_add_to_cart = MyStyle_Design_Profile_Page::show_add_to_cart_button();
$this->assertTrue( $show_add_to_cart );
}
}
| gpl-3.0 |
3months/pxfusion | lib/pxfusion/transaction.rb | 3989 | require "ostruct"
require "active_support/core_ext/hash/reverse_merge"
class PxFusion::Transaction < OpenStruct
def initialize(attributes = {})
attributes.reverse_merge!(
username: PxFusion.username,
password: PxFusion.password,
currency: PxFusion.default_currency,
return_url: "https://test.host/",
type: 'Purchase',
)
super(attributes)
[:username, :password, :currency, :amount, :type].each do |required_attribute|
raise ArgumentError.new("Missing attribute: #{required_attribute}") if !self.send(required_attribute)
end
{amount: 12, currency: 3, reference: 16, return_url: 255, type: 8}.each_pair do |attribute, length|
next unless self.send(attribute)
attribute_value = self.send(attribute).to_s
given_length = attribute_value.length
raise ArgumentError.new("PxFusion #{attribute} too long (max #{length} characters). #{attribute} given (#{given_length} characters): #{attribute_value}") if given_length > length
end
end
def generate_session_id!
response = PxFusion.client.call(
:get_transaction_id,
message: Request.get_transaction_id(self)
).body[:get_transaction_id_response][:get_transaction_id_result]
self.id = response[:transaction_id]
self.session_id = response[:session_id]
raise "Session could not be obtained from DPS" unless id && session_id
session_id
end
def self.fetch(id)
response = PxFusion.client.call(:get_transaction,message: {username: PxFusion.username, password: PxFusion.password, transactionId: id}).body
attributes = response[:get_transaction_response][:get_transaction_result]
raise PxFusion::Transaction::NotFound if attributes[:status].to_i == PxFusion.statuses[:not_found]
mapped_attributes = attributes.dup
attributes.each do |attribute, value|
case attribute
when :currency_name
mapped_attributes[:currency] = attributes[:currency_name]
when :txn_type
mapped_attributes[:type] = attributes[:txn_type]
when :response_text
mapped_attributes[:response] = attributes[:response_text]
when :merchant_reference
mapped_attributes[:reference] = attributes[:merchant_reference]
when :status
mapped_attributes[:status] = attributes[:status].to_i
end
end
self.new(mapped_attributes.merge(username: PxFusion.username, password: PxFusion.password))
end
private
class NotFound < Exception
end
module Request
def self.get_transaction_id_with_token(transaction)
attributes = transaction.instance_variable_get("@table")
msg = {
username: attributes[:username],
password: attributes[:password],
tranDetail: {
amount: attributes[:amount],
currency: attributes[:currency],
enableAddBillCard: true,
merchantReference: attributes[:reference],
returnUrl: attributes[:return_url],
txnRef: attributes[:reference],
txnType: attributes[:type]
}
}
end
def self.get_transaction_id_without_token(transaction)
attributes = transaction.instance_variable_get("@table")
msg = {
username: attributes[:username],
password: attributes[:password],
tranDetail: {
amount: attributes[:amount],
currency: attributes[:currency],
merchantReference: attributes[:reference],
returnUrl: attributes[:return_url],
txnRef: attributes[:reference],
txnType: attributes[:type]
}
}
end
def self.get_transaction_id(transaction)
# Build the hash to be sent to DPS
# THE ORDER MATTERS
attributes = transaction.instance_variable_get("@table")
attributes[:token_billing] ? get_transaction_id_with_token(transaction) : get_transaction_id_without_token(transaction)
end
end
end
| gpl-3.0 |
sizuest/EMod | ch.ethz.inspire.emod/src/ch/ethz/inspire/emod/simulation/MachineState.java | 652 | /***********************************
* $Id$
*
* $URL$
* $Author$
* $Date$
* $Rev$
*
* Copyright (c) 2011 by Inspire AG, ETHZ
* All rights reserved
*
***********************************/
package ch.ethz.inspire.emod.simulation;
/**
* All energy related machine states. Usually, a machine implements a subset of
* the defined states only.
*
* @author dhampl
*
*/
public enum MachineState {
/**
* Machine is on
*/
ON,
/**
* Machine is off
*/
OFF,
/**
* Machine is in standby (low ready)
*/
STANDBY,
/**
* Machine is ready for processing (high ready)
*/
READY,
/**
* Machine is processing
*/
PROCESS;
}
| gpl-3.0 |
NCTUGDC/Game-Design-Pattern-Example---TextAdventureGame | TextAdventureGame/TextAdventureGame.Library.General/NPC.cs | 714 | using MsgPack.Serialization;
namespace TextAdventureGame.Library.General
{
public class NPC
{
[MessagePackMember(id: 0, Name = "NPC_ID")]
public int NPC_ID { get; private set; }
[MessagePackMember(id: 1, Name = "Name")]
public string Name { get; private set; }
[MessagePackMember(id: 2, Name = "ConversationContent")]
public string ConversationContent { get; set; }
[MessagePackDeserializationConstructor]
public NPC() { }
public NPC(int NPC_ID, string name, string conversationContent)
{
this.NPC_ID = NPC_ID;
Name = name;
ConversationContent = conversationContent;
}
}
}
| gpl-3.0 |
lsuits/moodle | mod/turningtech/view.php | 3481 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Prints a particular instance of newmodule
*
* You can have a rather longer description of the file as well,
* if you like, and it can span multiple lines.
*
* @package mod_turningtech
* @copyright 2016 Turning Technologies
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Replace newmodule with the name of your module and remove this line.
require_once(dirname(dirname(dirname(__FILE__))).'/config.php');
require_once(dirname(__FILE__).'/lib.php');
require_once(dirname(__FILE__).'/locallib.php');
require_once(dirname(__FILE__).'/classes/event/course_module_instance_list_viewed.php');
require_once(dirname(__FILE__).'/classes/event/course_module_viewed.php');
$id = optional_param('id', 0, PARAM_INT); // Course_module ID, or
$n = optional_param('n', 0, PARAM_INT); // ... newmodule instance ID - it should be named as the first character of the module.
if ($id) {
$cm = get_coursemodule_from_id('turningtech', $id, 0, false, MUST_EXIST);
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
$turningtech = $DB->get_record('turningtech', array('id' => $cm->instance), '*', MUST_EXIST);
} else if ($n) {
$turningtech = $DB->get_record('turningtech', array('id' => $n), '*', MUST_EXIST);
$course = $DB->get_record('course', array('id' => $turningtech->course), '*', MUST_EXIST);
$cm = get_coursemodule_from_instance('turningtech', $turningtech->id, $course->id, false, MUST_EXIST);
} else {
error('You must specify a course_module ID or an instance ID');
}
require_login($course, true, $cm);
$event = \mod_turningtech\event\course_module_viewed::create(array(
'objectid' => $PAGE->cm->instance,
'context' => $PAGE->context,
));
$event->add_record_snapshot('course', $PAGE->course);
$event->add_record_snapshot($PAGE->cm->modname, $turningtech);
$event->trigger();
// Print the page header.
$PAGE->set_url('/mod/turningtech/view.php', array('id' => $cm->id));
$PAGE->set_title(format_string($turningtech->name));
$PAGE->set_heading(format_string($course->fullname));
/*
* Other things you may want to set - remove if not needed.
* $PAGE->set_cacheable(false);
* $PAGE->set_focuscontrol('some-html-id');
* $PAGE->add_body_class('newmodule-'.$somevar);
*/
// Output starts here.
echo $OUTPUT->header();
// Conditions to show the intro can change to look for own settings or whatever.
if ($turningtech->intro) {
echo $OUTPUT->box(format_module_intro('turningtech', $turningtech, $cm->id), 'generalbox mod_introbox', 'turningtechintro');
}
// Replace the following lines with you own code.
echo $OUTPUT->heading('Yay! It works!');
// Finish the page.
echo $OUTPUT->footer();
| gpl-3.0 |
nds/bio_assembly_refinement | bio_assembly_refinement/contig_break_finder.py | 8488 | '''
Find the point at which to break a circular contig (at origin of replication or random gene)
Attributes:
-----------
fasta_file : input fasta file name
gene_file : file with genes (e.g. dnaA)
skip : list or file of contig ids to skip (i.e. do not break at gene location)
hit_percent_id : min percent identity of matches to gene
match_length_percent : min length of ref match expressed as % of gene length (default 80%)
choose_random_gene : if genes in file cannot be found, run prodigal and find random gene (default True)
rename : rename contigs (default True)
working_directory : path to working directory (default to current working directory)
summary_file : summary file
summary prefix : the prefix for each line in summary file
debug : do not delete temp files if set to true (default false)
Sample usage:
-------------
from bio_assembly_refinement import contig_break_finder
break_finder = contig_break_finder.ContigBreakFinder(fasta_file = myfasta_file,
gene_file = mydnaA_file,
)
break_finder.run()
break_finder.output_file will be the cleaned fasta file
break_finder.summary_file will be the summary file
'''
import os
import shutil
from bio_assembly_refinement import utils, prodigal_hit
from pyfastaq import sequences, tasks, intervals
from pyfastaq import utils as fastaqutils
from pymummer import alignment
import subprocess
class ContigBreakFinder:
def __init__(self,
fasta_file,
gene_file,
skip=None, #Avoid circularising contigs with these ids
hit_percent_id=80,
match_length_percent=100,
choose_random_gene=True,
rename=True,
working_directory=None,
summary_file = "contig_breaks_summary.txt",
summary_prefix="[contig break finder]",
debug=False):
''' Attributes '''
self.fasta_file = fasta_file
self.gene_file = gene_file
self.hit_percent_id = hit_percent_id
self.match_length_percent = match_length_percent
self.choose_random_gene = choose_random_gene
self.rename = rename
self.working_directory = working_directory if working_directory else os.getcwd()
self.summary_file = summary_file
self.summary_prefix = summary_prefix
self.output_file = self._build_final_filename()
self.debug = debug
self.contigs = {}
tasks.file_to_dict(self.fasta_file, self.contigs) #Read contig ids and sequences into dict
self.random_gene_starts = {}
self.ids_to_skip = set()
if skip:
if type(skip) == set:
self.ids_to_skip = set(skip) # Assumes ids is a list
else:
fh = fastaqutils.open_file_read(skip)
for line in fh:
self.ids_to_skip.add(line.rstrip())
fastaqutils.close(fh)
def _get_length_of_fasta_file(self):
''' Sum up lengths of all contigs'''
d = {k: len(v) for k, v in self.contigs.items()}
return sum(d.values())
def _run_prodigal_and_get_gene_starts(self):
'''Run prodigal and find best gene starts around middle of contigs'''
gene_starts = {}
# run prodigal
prodigal_output = utils.run_prodigal(self.fasta_file, self._build_prodigal_filename(), self._get_length_of_fasta_file())
prodigal_genes = {}
if(prodigal_output):
fh = fastaqutils.open_file_read(self._build_prodigal_filename())
for line in fh:
if not line.startswith("#"):
columns = line.split('\t')
start_location = int(columns[3])
end_location = int(columns[4])
contig_id = columns[0]
strand = columns[6]
middle = abs((len(self.contigs[contig_id])/2))
p = prodigal_hit.ProdigalHit(start_location, end_location, strand, middle)
prodigal_genes.setdefault(contig_id, []).append(p)
fastaqutils.close(fh)
# look for best distance
for id in self.contigs.keys():
best_gene = None
if id in prodigal_genes.keys():
all_prodigal_hits = prodigal_genes[id]
min_distance = abs(len(self.contigs[contig_id])/2)
for p in all_prodigal_hits:
if p.distance <= min_distance:
best_gene = p
min_distance = p.distance
if best_gene:
gene_starts[id] = best_gene
else:
gene_starts[id] = None # Could not find a gene
return gene_starts
def _build_final_filename(self):
'''Build output filename'''
input_filename = os.path.basename(self.fasta_file)
return os.path.join(self.working_directory, "circularised_" + input_filename)
def _build_promer_filename(self):
'''Build temp promer filename'''
return os.path.join(self.working_directory, "promer_dnaA_hits.coords")
def _build_prodigal_filename(self):
'''Build temp prodigal filename'''
return os.path.join(self.working_directory, "prodigal_genes.gff")
def _write_summary(self, contig_id, break_point, gene_name, gene_reversed, new_name, skipped):
'''Write summary'''
if (not os.path.exists(self.summary_file)) or os.stat(self.summary_file).st_size == 0:
header = self.summary_prefix + "\t" + '\t'.join(['id', 'break_point', 'gene_name', 'gene_reversed', 'new_name', 'skipped']) +'\n'
utils.write_text_to_file(header, self.summary_file)
breakpoint_to_print = break_point if break_point else '-'
gene_name_to_print = gene_name if gene_name else '-'
gene_reversed_to_print = '-'
if gene_reversed:
gene_reversed_to_print = 'yes'
else:
gene_reversed_to_print = 'no' if gene_name else '-'
new_name_to_print = '-'
if new_name and self.rename:
new_name_to_print = new_name
skipped_print = 'skipped' if skipped else '-'
text = self.summary_prefix + "\t" + '\t'.join(map(str, [contig_id, breakpoint_to_print, gene_name_to_print, gene_reversed_to_print, new_name_to_print, skipped_print])) + '\n'
utils.write_text_to_file(text, self.summary_file)
def run(self):
'''Look for break point in contigs and rename if needed'''
contigs_in_file = set(self.contigs.keys())
if contigs_in_file != self.ids_to_skip:
# run promer and prodigal only if needed
dnaA_alignments = utils.run_nucmer(self.fasta_file, self.gene_file, self._build_promer_filename(), min_percent_id=self.hit_percent_id, run_promer=True)
if self.choose_random_gene:
self.random_gene_starts = self._run_prodigal_and_get_gene_starts()
chromosome_count = 1
plasmid_count = 1
output_fw = fastaqutils.open_file_write(self.output_file)
for contig_id in self.contigs:
contig_sequence = self.contigs[contig_id]
dnaA_found = False
gene_name = None
gene_on_reverse_strand = False
new_name = contig_id
break_point = None
skipped = False
if contig_id not in self.ids_to_skip:
# Look for dnaA
for algn in dnaA_alignments:
if algn.ref_name == contig_id and \
algn.hit_length_qry >= (algn.qry_length * self.match_length_percent/100) and \
algn.percent_identity >= self.hit_percent_id and \
algn.qry_start == 0:
dnaA_found = True
gene_name = algn.qry_name
if algn.on_same_strand():
break_point = algn.ref_start
else:
break_point = (algn.ref_length - algn.ref_start) - 1 #interbase
gene_on_reverse_strand = True
new_name = 'chromosome_' + str(chromosome_count)
chromosome_count += 1
# Or look for a gene in prodigal results
if not dnaA_found and self.choose_random_gene:
if contig_id in self.random_gene_starts and self.random_gene_starts[contig_id]:
gene_name = 'prodigal'
if self.random_gene_starts[contig_id].strand == '+':
break_point = self.random_gene_starts[contig_id].start
else:
break_point = (len(self.contigs[contig_id]) - self.random_gene_starts[contig_id].start) - 1 #interbase
gene_on_reverse_strand = True
new_name = 'plasmid_' + str(plasmid_count)
# circularise the contig
if break_point:
if gene_on_reverse_strand:
contig_sequence.revcomp()
contig_sequence = contig_sequence[break_point:] + contig_sequence[0:break_point]
self.contigs[contig_id].seq = contig_sequence
else: # Skipped, just write contig as it is
skipped = True
# write the contig out
contig_name = new_name if self.rename else contig_id
print(sequences.Fasta(contig_name, contig_sequence), file=output_fw)
self._write_summary(contig_id, break_point, gene_name, gene_on_reverse_strand, new_name, skipped)
fastaqutils.close(output_fw)
# clean up
if not self.debug:
utils.delete(self._build_promer_filename())
utils.delete(self._build_prodigal_filename())
| gpl-3.0 |
FFTEAM/ffteam-neutrino-mp-cst-next-max | src/gui/moviebrowser.cpp | 141359 | /***************************************************************************
Neutrino-GUI - DBoxII-Project
License: GPL
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
***********************************************************
Module Name: moviebrowser.cpp .
Description: Implementation of the CMovieBrowser class
This class provides a filebrowser window to view, select and start a movies from HD.
This class does replace the Filebrowser
Date: Nov 2005
Author: Günther@tuxbox.berlios.org
based on code of Steffen Hehn 'McClean'
(C) 2009-2015 Stefan Seyfried
****************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <global.h>
#include <driver/screen_max.h>
#include <algorithm>
#include <cstdlib>
#include "moviebrowser.h"
#include "filebrowser.h"
#include <gui/widget/hintbox.h>
#include <gui/widget/helpbox.h>
#include <gui/widget/icons.h>
#include <gui/components/cc.h>
#include <gui/widget/messagebox.h>
#include <gui/widget/stringinput.h>
#include <gui/widget/stringinput_ext.h>
#include <gui/widget/keyboard_input.h>
#include <dirent.h>
#include <sys/stat.h>
#include <gui/nfs.h>
#include <neutrino.h>
#include <sys/vfs.h> // for statfs
#include <sys/mount.h>
#include <utime.h>
#include <unistd.h>
#include <gui/pictureviewer.h>
#include <gui/customcolor.h>
#include <driver/record.h>
#include <driver/display.h>
#include <system/helpers.h>
#include <system/ytcache.h>
#include <zapit/debug.h>
#include <driver/moviecut.h>
#include <timerdclient/timerdclient.h>
#include <system/hddstat.h>
extern CPictureViewer * g_PicViewer;
#define my_scandir scandir64
#define my_alphasort alphasort64
typedef struct stat64 stat_struct;
typedef struct dirent64 dirent_struct;
#define my_stat stat64
#define TRACE printf
#define NUMBER_OF_MOVIES_LAST 40 // This is the number of movies shown in last recored and last played list
#define MESSAGEBOX_BROWSER_ROW_ITEM_COUNT 20
const CMenuOptionChooser::keyval MESSAGEBOX_BROWSER_ROW_ITEM[MESSAGEBOX_BROWSER_ROW_ITEM_COUNT] =
{
{ MB_INFO_FILENAME, LOCALE_MOVIEBROWSER_INFO_FILENAME },
{ MB_INFO_FILEPATH, LOCALE_MOVIEBROWSER_INFO_PATH },
{ MB_INFO_TITLE, LOCALE_MOVIEBROWSER_INFO_TITLE },
{ MB_INFO_SERIE, LOCALE_MOVIEBROWSER_INFO_SERIE },
{ MB_INFO_INFO1, LOCALE_MOVIEBROWSER_INFO_INFO1 },
{ MB_INFO_MAJOR_GENRE, LOCALE_MOVIEBROWSER_INFO_GENRE_MAJOR },
{ MB_INFO_MINOR_GENRE, LOCALE_MOVIEBROWSER_INFO_GENRE_MINOR },
{ MB_INFO_INFO2, LOCALE_MOVIEBROWSER_INFO_INFO2 },
{ MB_INFO_PARENTAL_LOCKAGE, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE },
{ MB_INFO_CHANNEL, LOCALE_MOVIEBROWSER_INFO_CHANNEL },
{ MB_INFO_BOOKMARK, LOCALE_MOVIEBROWSER_MENU_MAIN_BOOKMARKS },
{ MB_INFO_QUALITY, LOCALE_MOVIEBROWSER_INFO_QUALITY },
{ MB_INFO_PREVPLAYDATE, LOCALE_MOVIEBROWSER_INFO_PREVPLAYDATE },
{ MB_INFO_RECORDDATE, LOCALE_MOVIEBROWSER_INFO_RECORDDATE },
{ MB_INFO_PRODDATE, LOCALE_MOVIEBROWSER_INFO_PRODYEAR },
{ MB_INFO_COUNTRY, LOCALE_MOVIEBROWSER_INFO_PRODCOUNTRY },
{ MB_INFO_GEOMETRIE, LOCALE_MOVIEBROWSER_INFO_VIDEOFORMAT },
{ MB_INFO_AUDIO, LOCALE_MOVIEBROWSER_INFO_AUDIO },
{ MB_INFO_LENGTH, LOCALE_MOVIEBROWSER_INFO_LENGTH },
{ MB_INFO_SIZE, LOCALE_MOVIEBROWSER_INFO_SIZE }
};
#define MESSAGEBOX_YES_NO_OPTIONS_COUNT 2
const CMenuOptionChooser::keyval MESSAGEBOX_YES_NO_OPTIONS[MESSAGEBOX_YES_NO_OPTIONS_COUNT] =
{
{ 0, LOCALE_MESSAGEBOX_NO },
{ 1, LOCALE_MESSAGEBOX_YES }
};
#define MESSAGEBOX_PARENTAL_LOCK_OPTIONS_COUNT 3
const CMenuOptionChooser::keyval MESSAGEBOX_PARENTAL_LOCK_OPTIONS[MESSAGEBOX_PARENTAL_LOCK_OPTIONS_COUNT] =
{
{ 1, LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_ACTIVATED_YES },
{ 0, LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_ACTIVATED_NO },
{ 2, LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_ACTIVATED_NO_TEMP }
};
#define MESSAGEBOX_PARENTAL_LOCKAGE_OPTION_COUNT 6
const CMenuOptionChooser::keyval MESSAGEBOX_PARENTAL_LOCKAGE_OPTIONS[MESSAGEBOX_PARENTAL_LOCKAGE_OPTION_COUNT] =
{
{ 0, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_0YEAR },
{ 6, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_6YEAR },
{ 12, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_12YEAR },
{ 16, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_16YEAR },
{ 18, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_18YEAR },
{ 99, LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE_ALWAYS }
};
#define TITLE_BACKGROUND_COLOR ((CFBWindow::color_t)COL_MENUHEAD_PLUS_0)
#define TITLE_FONT_COLOR COL_MENUHEAD_TEXT
#define TITLE_FONT g_Font[SNeutrinoSettings::FONT_TYPE_MENU_TITLE]
#define FOOT_FONT g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]
#define INTER_FRAME_SPACE 4 // space between e.g. upper and lower window
const neutrino_locale_t m_localizedItemName[MB_INFO_MAX_NUMBER+1] =
{
LOCALE_MOVIEBROWSER_SHORT_FILENAME,
LOCALE_MOVIEBROWSER_SHORT_PATH,
LOCALE_MOVIEBROWSER_SHORT_TITLE,
LOCALE_MOVIEBROWSER_SHORT_SERIE,
LOCALE_MOVIEBROWSER_SHORT_INFO1,
LOCALE_MOVIEBROWSER_SHORT_GENRE_MAJOR,
LOCALE_MOVIEBROWSER_SHORT_GENRE_MINOR,
LOCALE_MOVIEBROWSER_SHORT_INFO2,
LOCALE_MOVIEBROWSER_SHORT_PARENTAL_LOCKAGE,
LOCALE_MOVIEBROWSER_SHORT_CHANNEL,
LOCALE_MOVIEBROWSER_SHORT_BOOK,
LOCALE_MOVIEBROWSER_SHORT_QUALITY,
LOCALE_MOVIEBROWSER_SHORT_PREVPLAYDATE,
LOCALE_MOVIEBROWSER_SHORT_RECORDDATE,
LOCALE_MOVIEBROWSER_SHORT_PRODYEAR,
LOCALE_MOVIEBROWSER_SHORT_COUNTRY,
LOCALE_MOVIEBROWSER_SHORT_FORMAT,
LOCALE_MOVIEBROWSER_SHORT_AUDIO,
LOCALE_MOVIEBROWSER_SHORT_LENGTH,
LOCALE_MOVIEBROWSER_SHORT_SIZE,
NONEXISTANT_LOCALE
};
/* default row size in percent for any element */
#define MB_ROW_WIDTH_FILENAME 22
#define MB_ROW_WIDTH_FILEPATH 22
#define MB_ROW_WIDTH_TITLE 35
#define MB_ROW_WIDTH_SERIE 15
#define MB_ROW_WIDTH_INFO1 15
#define MB_ROW_WIDTH_MAJOR_GENRE 15
#define MB_ROW_WIDTH_MINOR_GENRE 8
#define MB_ROW_WIDTH_INFO2 25
#define MB_ROW_WIDTH_PARENTAL_LOCKAGE 4
#define MB_ROW_WIDTH_CHANNEL 15
#define MB_ROW_WIDTH_BOOKMARK 4
#define MB_ROW_WIDTH_QUALITY 10
#define MB_ROW_WIDTH_PREVPLAYDATE 12
#define MB_ROW_WIDTH_RECORDDATE 12
#define MB_ROW_WIDTH_PRODDATE 8
#define MB_ROW_WIDTH_COUNTRY 8
#define MB_ROW_WIDTH_GEOMETRIE 8
#define MB_ROW_WIDTH_AUDIO 8
#define MB_ROW_WIDTH_LENGTH 10
#define MB_ROW_WIDTH_SIZE 12
const int m_defaultRowWidth[MB_INFO_MAX_NUMBER+1] =
{
MB_ROW_WIDTH_FILENAME,
MB_ROW_WIDTH_FILEPATH,
MB_ROW_WIDTH_TITLE,
MB_ROW_WIDTH_SERIE,
MB_ROW_WIDTH_INFO1,
MB_ROW_WIDTH_MAJOR_GENRE,
MB_ROW_WIDTH_MINOR_GENRE,
MB_ROW_WIDTH_INFO2,
MB_ROW_WIDTH_PARENTAL_LOCKAGE,
MB_ROW_WIDTH_CHANNEL,
MB_ROW_WIDTH_BOOKMARK,
MB_ROW_WIDTH_QUALITY,
MB_ROW_WIDTH_PREVPLAYDATE,
MB_ROW_WIDTH_RECORDDATE,
MB_ROW_WIDTH_PRODDATE,
MB_ROW_WIDTH_COUNTRY,
MB_ROW_WIDTH_GEOMETRIE,
MB_ROW_WIDTH_AUDIO,
MB_ROW_WIDTH_LENGTH,
MB_ROW_WIDTH_SIZE,
0 //MB_ROW_WIDTH_MAX_NUMBER
};
static MI_MOVIE_INFO* playing_info;
//------------------------------------------------------------------------
// sorting
//------------------------------------------------------------------------
#define FILEBROWSER_NUMBER_OF_SORT_VARIANTS 5
bool sortDirection = 0;
bool compare_to_lower(const char a, const char b)
{
return tolower(a) < tolower(b);
}
// sort operators
bool sortByTitle(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (std::lexicographical_compare(a->epgTitle.begin(), a->epgTitle.end(), b->epgTitle.begin(), b->epgTitle.end(), compare_to_lower))
return true;
if (std::lexicographical_compare(b->epgTitle.begin(), b->epgTitle.end(), a->epgTitle.begin(), a->epgTitle.end(), compare_to_lower))
return false;
return a->file.Time < b->file.Time;
}
bool sortByGenre(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (std::lexicographical_compare(a->epgInfo1.begin(), a->epgInfo1.end(), b->epgInfo1.begin(), b->epgInfo1.end(), compare_to_lower))
return true;
if (std::lexicographical_compare(b->epgInfo1.begin(), b->epgInfo1.end(), a->epgInfo1.begin(), a->epgInfo1.end(), compare_to_lower))
return false;
return sortByTitle(a,b);
}
bool sortByChannel(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (std::lexicographical_compare(a->epgChannel.begin(), a->epgChannel.end(), b->epgChannel.begin(), b->epgChannel.end(), compare_to_lower))
return true;
if (std::lexicographical_compare(b->epgChannel.begin(), b->epgChannel.end(), a->epgChannel.begin(), a->epgChannel.end(), compare_to_lower))
return false;
return sortByTitle(a,b);
}
bool sortByFileName(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (std::lexicographical_compare(a->file.getFileName().begin(), a->file.getFileName().end(), b->file.getFileName().begin(), b->file.getFileName().end(), compare_to_lower))
return true;
if (std::lexicographical_compare(b->file.getFileName().begin(), b->file.getFileName().end(), a->file.getFileName().begin(), a->file.getFileName().end(), compare_to_lower))
return false;
return a->file.Time < b->file.Time;
}
bool sortByRecordDate(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->file.Time > b->file.Time ;
else
return a->file.Time < b->file.Time ;
}
bool sortBySize(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->file.Size > b->file.Size;
else
return a->file.Size < b->file.Size;
}
bool sortByAge(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->parentalLockAge > b->parentalLockAge;
else
return a->parentalLockAge < b->parentalLockAge;
}
bool sortByQuality(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->quality > b->quality;
else
return a->quality < b->quality;
}
bool sortByDir(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->dirItNr > b->dirItNr;
else
return a->dirItNr < b->dirItNr;
}
bool sortByLastPlay(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b)
{
if (sortDirection)
return a->dateOfLastPlay > b->dateOfLastPlay;
else
return a->dateOfLastPlay < b->dateOfLastPlay;
}
bool (* const sortBy[MB_INFO_MAX_NUMBER+1])(const MI_MOVIE_INFO* a, const MI_MOVIE_INFO* b) =
{
&sortByFileName, //MB_INFO_FILENAME = 0,
&sortByDir, //MB_INFO_FILEPATH = 1,
&sortByTitle, //MB_INFO_TITLE = 2,
NULL, //MB_INFO_SERIE = 3,
&sortByGenre, //MB_INFO_INFO1 = 4,
NULL, //MB_INFO_MAJOR_GENRE = 5,
NULL, //MB_INFO_MINOR_GENRE = 6,
NULL, //MB_INFO_INFO2 = 7,
&sortByAge, //MB_INFO_PARENTAL_LOCKAGE = 8,
&sortByChannel, //MB_INFO_CHANNEL = 9,
NULL, //MB_INFO_BOOKMARK = 10,
&sortByQuality, //MB_INFO_QUALITY = 11,
&sortByLastPlay, //MB_INFO_PREVPLAYDATE = 12,
&sortByRecordDate, //MB_INFO_RECORDDATE = 13,
NULL, //MB_INFO_PRODDATE = 14,
NULL, //MB_INFO_COUNTRY = 15,
NULL, //MB_INFO_GEOMETRIE = 16,
NULL, //MB_INFO_AUDIO = 17,
NULL, //MB_INFO_LENGTH = 18,
&sortBySize, //MB_INFO_SIZE = 19,
NULL //MB_INFO_MAX_NUMBER = 20
};
CMovieBrowser::CMovieBrowser(): configfile ('\t')
{
init();
}
CMovieBrowser::~CMovieBrowser()
{
//TRACE("[mb] del\n");
hide();
m_dir.clear();
m_dirNames.clear();
m_vMovieInfo.clear();
m_vHandleBrowserList.clear();
m_vHandleRecordList.clear();
m_vHandlePlayList.clear();
m_vHandleSerienames.clear();
clearListLines();
if (CChannelLogo) {
delete CChannelLogo;
CChannelLogo = NULL;
}
}
void CMovieBrowser::clearListLines()
{
for (int i = 0; i < MB_MAX_ROWS; i++)
{
m_browserListLines.lineArray[i].clear();
m_FilterLines.lineArray[i].clear();
}
m_browserListLines.Icon.clear();
m_browserListLines.marked.clear();
for (int i = 0; i < 2; i++)
{
m_recordListLines.lineArray[i].clear();
m_playListLines.lineArray[i].clear();
}
m_recordListLines.marked.clear();
m_playListLines.marked.clear();
}
void CMovieBrowser::clearSelection()
{
//TRACE("[mb]->%s\n", __func__);
for (unsigned i = 0; i < m_vMovieInfo.size(); i++)
m_vMovieInfo[i].marked = false;
m_pcBrowser->clearMarked();
m_pcLastPlay->clearMarked();
m_pcLastRecord->clearMarked();
}
void CMovieBrowser::fileInfoStale(void)
{
m_file_info_stale = true;
m_seriename_stale = true;
// Also release memory buffers, since we have to reload this stuff next time anyhow
m_dirNames.clear();
m_vMovieInfo.clear();
m_vHandleBrowserList.clear();
m_vHandleRecordList.clear();
m_vHandlePlayList.clear();
m_vHandleSerienames.clear();
clearListLines();
}
void CMovieBrowser::init(void)
{
bool reinit_rows = false;
int i = 0;
//TRACE("[mb]->init\n");
initGlobalSettings();
loadSettings(&m_settings);
m_file_info_stale = true;
m_seriename_stale = true;
framebuffer = CFrameBuffer::getInstance();
m_pcBrowser = NULL;
m_pcLastPlay = NULL;
m_pcLastRecord = NULL;
m_pcInfo = NULL;
m_pcFilter = NULL;
m_windowFocus = MB_FOCUS_BROWSER;
m_textTitle = g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD);
m_currentStartPos = 0;
m_movieSelectionHandler = NULL;
m_currentBrowserSelection = 0;
m_currentRecordSelection = 0;
m_currentPlaySelection = 0;
m_prevBrowserSelection = 0;
m_prevRecordSelection = 0;
m_prevPlaySelection = 0;
m_storageType = MB_STORAGE_TYPE_NFS;
m_parentalLock = m_settings.parentalLock;
// check g_setting values
if (m_settings.gui >= MB_GUI_MAX_NUMBER)
m_settings.gui = MB_GUI_MOVIE_INFO;
if (m_settings.sorting.direction >= MB_DIRECTION_MAX_NUMBER)
m_settings.sorting.direction = MB_DIRECTION_DOWN;
if (m_settings.sorting.item >= MB_INFO_MAX_NUMBER)
m_settings.sorting.item = MB_INFO_TITLE;
if (m_settings.filter.item >= MB_INFO_MAX_NUMBER)
m_settings.filter.item = MB_INFO_MAX_NUMBER;
if (m_settings.parentalLockAge >= MI_PARENTAL_MAX_NUMBER)
m_settings.parentalLockAge = MI_PARENTAL_OVER18;
if (m_settings.parentalLock >= MB_PARENTAL_LOCK_MAX_NUMBER)
m_settings.parentalLock = MB_PARENTAL_LOCK_OFF;
/* convert from old pixel-based to new percent values */
if (m_settings.browserFrameHeight > 100)
m_settings.browserFrameHeight = 50;
if (m_settings.browserFrameHeight < MIN_BROWSER_FRAME_HEIGHT)
m_settings.browserFrameHeight = MIN_BROWSER_FRAME_HEIGHT;
if (m_settings.browserFrameHeight > MAX_BROWSER_FRAME_HEIGHT)
m_settings.browserFrameHeight = MAX_BROWSER_FRAME_HEIGHT;
/* the old code had row widths in pixels, not percent. Check if we have
* an old configuration (one of the rows hopefully was larger than 100 pixels... */
for (i = 0; i < m_settings.browserRowNr; i++)
{
if (m_settings.browserRowWidth[i] > 100)
{
printf("[moviebrowser] old row config detected - converting...\n");
reinit_rows = true;
break;
}
}
if (reinit_rows)
{
for (i = 0; i < m_settings.browserRowNr; i++)
m_settings.browserRowWidth[i] = m_defaultRowWidth[m_settings.browserRowItem[i]];
}
initFrames();
initRows();
/* save settings here, because exec() will load them again... */
if (reinit_rows)
saveSettings(&m_settings);
refreshLastPlayList();
refreshLastRecordList();
refreshBrowserList();
refreshFilterList();
g_PicViewer->getSupportedImageFormats(PicExts);
show_mode = MB_SHOW_RECORDS; //FIXME
CChannelLogo = NULL;
}
void CMovieBrowser::initGlobalSettings(void)
{
//TRACE("[mb]->initGlobalSettings\n");
m_settings.gui = MB_GUI_MOVIE_INFO;
m_settings.lastPlayMaxItems = NUMBER_OF_MOVIES_LAST;
m_settings.lastRecordMaxItems = NUMBER_OF_MOVIES_LAST;
m_settings.browser_serie_mode = 0;
m_settings.serie_auto_create = 0;
m_settings.sorting.item = MB_INFO_TITLE;
m_settings.sorting.direction = MB_DIRECTION_DOWN;
m_settings.filter.item = MB_INFO_MAX_NUMBER;
m_settings.filter.optionString = "";
m_settings.filter.optionVar = 0;
m_settings.parentalLockAge = MI_PARENTAL_OVER18;
m_settings.parentalLock = MB_PARENTAL_LOCK_OFF;
m_settings.storageDirMovieUsed = true;
m_settings.storageDirRecUsed = true;
m_settings.reload = true;
m_settings.remount = false;
for (int i = 0; i < MB_MAX_DIRS; i++)
{
m_settings.storageDir[i] = "";
m_settings.storageDirUsed[i] = 0;
}
/***** Browser List **************/
m_settings.browserFrameHeight = 50; /* percent */
m_settings.browserRowNr = 6;
m_settings.browserRowItem[0] = MB_INFO_CHANNEL;
m_settings.browserRowItem[1] = MB_INFO_TITLE;
m_settings.browserRowItem[2] = MB_INFO_RECORDDATE;
m_settings.browserRowItem[3] = MB_INFO_SIZE;
m_settings.browserRowItem[4] = MB_INFO_LENGTH;
m_settings.browserRowItem[5] = MB_INFO_INFO1;
m_settings.browserRowItem[6] = MB_INFO_MAX_NUMBER;
m_settings.browserRowItem[7] = MB_INFO_MAX_NUMBER;
m_settings.browserRowItem[8] = MB_INFO_MAX_NUMBER;
m_settings.browserRowWidth[0] = m_defaultRowWidth[m_settings.browserRowItem[0]]; //300;
m_settings.browserRowWidth[1] = m_defaultRowWidth[m_settings.browserRowItem[1]]; //100;
m_settings.browserRowWidth[2] = m_defaultRowWidth[m_settings.browserRowItem[2]]; //80;
m_settings.browserRowWidth[3] = m_defaultRowWidth[m_settings.browserRowItem[3]]; //50;
m_settings.browserRowWidth[4] = m_defaultRowWidth[m_settings.browserRowItem[4]]; //30;
m_settings.browserRowWidth[5] = m_defaultRowWidth[m_settings.browserRowItem[5]]; //30;
m_settings.browserRowWidth[6] = m_defaultRowWidth[m_settings.browserRowItem[6]];
m_settings.browserRowWidth[7] = m_defaultRowWidth[m_settings.browserRowItem[7]];
m_settings.browserRowWidth[8] = m_defaultRowWidth[m_settings.browserRowItem[8]];
m_settings.ts_only = 0;
m_settings.ytmode = cYTFeedParser::MOST_POPULAR;
m_settings.ytorderby = cYTFeedParser::ORDERBY_PUBLISHED;
m_settings.ytresults = 10;
m_settings.ytregion = "default";
m_settings.ytquality = 37;
m_settings.ytconcconn = 4;
m_settings.ytsearch_history_max = 0;
m_settings.ytsearch_history_size = 0;
}
void CMovieBrowser::initFrames(void)
{
m_pcFontFoot = FOOT_FONT;
m_pcFontTitle = TITLE_FONT;
//TRACE("[mb]->%s\n", __func__);
m_cBoxFrame.iWidth = framebuffer->getScreenWidthRel();
m_cBoxFrame.iHeight = framebuffer->getScreenHeightRel();
m_cBoxFrame.iX = getScreenStartX(m_cBoxFrame.iWidth);
m_cBoxFrame.iY = getScreenStartY(m_cBoxFrame.iHeight);
m_cBoxFrameTitleRel.iX = 0;
m_cBoxFrameTitleRel.iY = 0;
m_cBoxFrameTitleRel.iWidth = m_cBoxFrame.iWidth;
m_cBoxFrameTitleRel.iHeight = m_pcFontTitle->getHeight();
const int pic_h = 39;
m_cBoxFrameTitleRel.iHeight = std::max(m_cBoxFrameTitleRel.iHeight, pic_h);
m_cBoxFrameBrowserList.iX = m_cBoxFrame.iX;
m_cBoxFrameBrowserList.iY = m_cBoxFrame.iY + m_cBoxFrameTitleRel.iHeight;
m_cBoxFrameBrowserList.iWidth = m_cBoxFrame.iWidth;
m_cBoxFrameBrowserList.iHeight = m_cBoxFrame.iHeight * m_settings.browserFrameHeight / 100;
m_cBoxFrameFootRel.iX = 0;
m_cBoxFrameFootRel.iHeight = refreshFoot(false);
m_cBoxFrameFootRel.iY = m_cBoxFrame.iHeight - m_cBoxFrameFootRel.iHeight;
m_cBoxFrameFootRel.iWidth = m_cBoxFrameBrowserList.iWidth;
m_cBoxFrameLastPlayList.iX = m_cBoxFrameBrowserList.iX;
m_cBoxFrameLastPlayList.iY = m_cBoxFrameBrowserList.iY ;
m_cBoxFrameLastPlayList.iWidth = (m_cBoxFrameBrowserList.iWidth>>1) - (INTER_FRAME_SPACE>>1);
m_cBoxFrameLastPlayList.iHeight = m_cBoxFrameBrowserList.iHeight;
m_cBoxFrameLastRecordList.iX = m_cBoxFrameLastPlayList.iX + m_cBoxFrameLastPlayList.iWidth + INTER_FRAME_SPACE;
m_cBoxFrameLastRecordList.iY = m_cBoxFrameLastPlayList.iY;
m_cBoxFrameLastRecordList.iWidth = m_cBoxFrame.iWidth - m_cBoxFrameLastPlayList.iWidth - INTER_FRAME_SPACE;
m_cBoxFrameLastRecordList.iHeight = m_cBoxFrameLastPlayList.iHeight;
m_cBoxFrameInfo.iX = m_cBoxFrameBrowserList.iX;
m_cBoxFrameInfo.iY = m_cBoxFrameBrowserList.iY + m_cBoxFrameBrowserList.iHeight + INTER_FRAME_SPACE;
m_cBoxFrameInfo.iWidth = m_cBoxFrameBrowserList.iWidth;
m_cBoxFrameInfo.iHeight = m_cBoxFrame.iHeight - m_cBoxFrameBrowserList.iHeight - INTER_FRAME_SPACE - m_cBoxFrameFootRel.iHeight - m_cBoxFrameTitleRel.iHeight;
m_cBoxFrameFilter.iX = m_cBoxFrameInfo.iX;
m_cBoxFrameFilter.iY = m_cBoxFrameInfo.iY;
m_cBoxFrameFilter.iWidth = m_cBoxFrameInfo.iWidth;
m_cBoxFrameFilter.iHeight = m_cBoxFrameInfo.iHeight;
}
void CMovieBrowser::initRows(void)
{
//TRACE("[mb]->%s\n", __func__);
/***** Last Play List **************/
m_settings.lastPlayRowNr = 2;
m_settings.lastPlayRow[0] = MB_INFO_TITLE;
m_settings.lastPlayRow[1] = MB_INFO_PREVPLAYDATE;
/* the "last played" / "last recorded" windows have only half the width, so
multiply the relative width with 2 */
m_settings.lastPlayRowWidth[1] = m_defaultRowWidth[m_settings.lastPlayRow[1]] * 2 + 1;
m_settings.lastPlayRowWidth[0] = 100 - m_settings.lastPlayRowWidth[1];
/***** Last Record List **************/
m_settings.lastRecordRowNr = 2;
m_settings.lastRecordRow[0] = MB_INFO_TITLE;
m_settings.lastRecordRow[1] = MB_INFO_RECORDDATE;
m_settings.lastRecordRowWidth[1] = m_defaultRowWidth[m_settings.lastRecordRow[1]] * 2 + 1;
m_settings.lastRecordRowWidth[0] = 100 - m_settings.lastRecordRowWidth[1];
}
void CMovieBrowser::defaultSettings(MB_SETTINGS* /*settings*/)
{
unlink(MOVIEBROWSER_SETTINGS_FILE);
configfile.clear();
initGlobalSettings();
}
bool CMovieBrowser::loadSettings(MB_SETTINGS* settings)
{
//TRACE("[mb]->%s\n", __func__);
bool result = configfile.loadConfig(MOVIEBROWSER_SETTINGS_FILE);
if (!result) {
TRACE("CMovieBrowser::loadSettings failed\n");
return result;
}
settings->gui = (MB_GUI)configfile.getInt32("mb_gui", MB_GUI_MOVIE_INFO);
settings->lastPlayMaxItems = configfile.getInt32("mb_lastPlayMaxItems", NUMBER_OF_MOVIES_LAST);
settings->lastRecordMaxItems = configfile.getInt32("mb_lastRecordMaxItems", NUMBER_OF_MOVIES_LAST);
settings->browser_serie_mode = configfile.getInt32("mb_browser_serie_mode", 0);
settings->serie_auto_create = configfile.getInt32("mb_serie_auto_create", 0);
settings->ts_only = configfile.getInt32("mb_ts_only", 0);
settings->sorting.item = (MB_INFO_ITEM)configfile.getInt32("mb_sorting_item", MB_INFO_RECORDDATE);
settings->sorting.direction = (MB_DIRECTION)configfile.getInt32("mb_sorting_direction", MB_DIRECTION_UP);
settings->filter.item = (MB_INFO_ITEM)configfile.getInt32("mb_filter_item", MB_INFO_MAX_NUMBER);
settings->filter.optionString = configfile.getString("mb_filter_optionString", "");
settings->filter.optionVar = configfile.getInt32("mb_filter_optionVar", 0);
settings->parentalLockAge = (MI_PARENTAL_LOCKAGE)configfile.getInt32("mb_parentalLockAge", MI_PARENTAL_OVER18);
settings->parentalLock = (MB_PARENTAL_LOCK)configfile.getInt32("mb_parentalLock", MB_PARENTAL_LOCK_ACTIVE);
settings->storageDirRecUsed = (bool)configfile.getInt32("mb_storageDir_rec", true);
settings->storageDirMovieUsed = (bool)configfile.getInt32("mb_storageDir_movie", true);
settings->reload = (bool)configfile.getInt32("mb_reload", true);
settings->remount = (bool)configfile.getInt32("mb_remount", false);
for (int i = 0; i < MB_MAX_DIRS; i++)
{
settings->storageDir[i] = configfile.getString("mb_dir_" + to_string(i), "");
settings->storageDirUsed[i] = configfile.getInt32("mb_dir_used" + to_string(i), false);
}
/* these variables are used for the listframes */
settings->browserFrameHeight = configfile.getInt32("mb_browserFrameHeight", 50);
settings->browserRowNr = configfile.getInt32("mb_browserRowNr", 0);
for (int i = 0; i < MB_MAX_ROWS && i < settings->browserRowNr; i++)
{
settings->browserRowItem[i] = (MB_INFO_ITEM)configfile.getInt32("mb_browserRowItem_" + to_string(i), MB_INFO_MAX_NUMBER);
settings->browserRowWidth[i] = configfile.getInt32("mb_browserRowWidth_" + to_string(i), 50);
}
settings->ytmode = configfile.getInt32("mb_ytmode", cYTFeedParser::MOST_POPULAR);
settings->ytorderby = configfile.getInt32("mb_ytorderby", cYTFeedParser::ORDERBY_PUBLISHED);
settings->ytresults = configfile.getInt32("mb_ytresults", 10);
settings->ytquality = configfile.getInt32("mb_ytquality", 37); // itag value (MP4, 1080p)
settings->ytconcconn = configfile.getInt32("mb_ytconcconn", 4); // concurrent connections
settings->ytregion = configfile.getString("mb_ytregion", "default");
settings->ytsearch = configfile.getString("mb_ytsearch", "");
settings->ytthumbnaildir = configfile.getString("mb_ytthumbnaildir", "/tmp/ytparser");
settings->ytvid = configfile.getString("mb_ytvid", "");
settings->ytsearch_history_max = configfile.getInt32("mb_ytsearch_history_max", 10);
settings->ytsearch_history_size = configfile.getInt32("mb_ytsearch_history_size", 0);
if (settings->ytsearch_history_size > settings->ytsearch_history_max)
settings->ytsearch_history_size = settings->ytsearch_history_max;
settings->ytsearch_history.clear();
for (int i = 0; i < settings->ytsearch_history_size; i++) {
std::string s = configfile.getString("mb_ytsearch_history_" + to_string(i));
if (!s.empty())
settings->ytsearch_history.push_back(configfile.getString("mb_ytsearch_history_" + to_string(i), ""));
}
settings->ytsearch_history_size = settings->ytsearch_history.size();
return (result);
}
bool CMovieBrowser::saveSettings(MB_SETTINGS* settings)
{
bool result = true;
TRACE("[mb]->%s\n", __func__);
configfile.setInt32("mb_lastPlayMaxItems", settings->lastPlayMaxItems);
configfile.setInt32("mb_lastRecordMaxItems", settings->lastRecordMaxItems);
configfile.setInt32("mb_browser_serie_mode", settings->browser_serie_mode);
configfile.setInt32("mb_serie_auto_create", settings->serie_auto_create);
configfile.setInt32("mb_ts_only", settings->ts_only);
configfile.setInt32("mb_gui", settings->gui);
configfile.setInt32("mb_sorting_item", settings->sorting.item);
configfile.setInt32("mb_sorting_direction", settings->sorting.direction);
configfile.setInt32("mb_filter_item", settings->filter.item);
configfile.setString("mb_filter_optionString", settings->filter.optionString);
configfile.setInt32("mb_filter_optionVar", settings->filter.optionVar);
configfile.setInt32("mb_storageDir_rec", settings->storageDirRecUsed);
configfile.setInt32("mb_storageDir_movie", settings->storageDirMovieUsed);
configfile.setInt32("mb_parentalLockAge", settings->parentalLockAge);
configfile.setInt32("mb_parentalLock", settings->parentalLock);
configfile.setInt32("mb_reload", settings->reload);
configfile.setInt32("mb_remount", settings->remount);
for (int i = 0; i < MB_MAX_DIRS; i++)
{
configfile.setString("mb_dir_" + to_string(i), settings->storageDir[i]);
configfile.setInt32("mb_dir_used" + to_string(i), settings->storageDirUsed[i]); // do not save this so far
}
/* these variables are used for the listframes */
configfile.setInt32("mb_browserFrameHeight", settings->browserFrameHeight);
configfile.setInt32("mb_browserRowNr",settings->browserRowNr);
for (int i = 0; i < MB_MAX_ROWS && i < settings->browserRowNr; i++)
{
configfile.setInt32("mb_browserRowItem_" + to_string(i), settings->browserRowItem[i]);
configfile.setInt32("mb_browserRowWidth_" + to_string(i), settings->browserRowWidth[i]);
}
configfile.setInt32("mb_ytmode", settings->ytmode);
configfile.setInt32("mb_ytorderby", settings->ytorderby);
configfile.setInt32("mb_ytresults", settings->ytresults);
configfile.setInt32("mb_ytquality", settings->ytquality);
configfile.setInt32("mb_ytconcconn", settings->ytconcconn);
configfile.setString("mb_ytregion", settings->ytregion);
configfile.setString("mb_ytsearch", settings->ytsearch);
configfile.setString("mb_ytthumbnaildir", settings->ytthumbnaildir);
configfile.setString("mb_ytvid", settings->ytvid);
settings->ytsearch_history_size = settings->ytsearch_history.size();
if (settings->ytsearch_history_size > settings->ytsearch_history_max)
settings->ytsearch_history_size = settings->ytsearch_history_max;
configfile.setInt32("mb_ytsearch_history_max", settings->ytsearch_history_max);
configfile.setInt32("mb_ytsearch_history_size", settings->ytsearch_history_size);
std::list<std::string>:: iterator it = settings->ytsearch_history.begin();
for (int i = 0; i < settings->ytsearch_history_size; i++, ++it)
configfile.setString("mb_ytsearch_history_" + to_string(i), *it);
if (configfile.getModifiedFlag())
configfile.saveConfig(MOVIEBROWSER_SETTINGS_FILE);
return (result);
}
int CMovieBrowser::exec(CMenuTarget* parent, const std::string & actionKey)
{
int returnval = menu_return::RETURN_REPAINT;
if (actionKey == "loaddefault")
{
defaultSettings(&m_settings);
}
else if (actionKey == "show_movie_info_menu")
{
if (m_movieSelectionHandler != NULL)
return showMovieInfoMenu(m_movieSelectionHandler);
}
else if (actionKey == "save_movie_info")
{
m_movieInfo.saveMovieInfo(*m_movieSelectionHandler);
}
else if (actionKey == "save_movie_info_all")
{
std::vector<MI_MOVIE_INFO*> * current_list=NULL;
if (m_windowFocus == MB_FOCUS_BROWSER) current_list = &m_vHandleBrowserList;
else if (m_windowFocus == MB_FOCUS_LAST_PLAY) current_list = &m_vHandlePlayList;
else if (m_windowFocus == MB_FOCUS_LAST_RECORD) current_list = &m_vHandleRecordList ;
if (current_list == NULL || m_movieSelectionHandler == NULL)
return returnval;
CHintBox loadBox(LOCALE_MOVIEBROWSER_HEAD,g_Locale->getText(LOCALE_MOVIEBROWSER_INFO_HEAD_UPDATE));
loadBox.paint();
for (unsigned int i = 0; i< current_list->size();i++)
{
if (!((*current_list)[i]->parentalLockAge != 0 && movieInfoUpdateAllIfDestEmptyOnly == true) &&
movieInfoUpdateAll[MB_INFO_TITLE])
(*current_list)[i]->parentalLockAge = m_movieSelectionHandler->parentalLockAge;
if (!(!(*current_list)[i]->serieName.empty() && movieInfoUpdateAllIfDestEmptyOnly == true) &&
movieInfoUpdateAll[MB_INFO_SERIE])
(*current_list)[i]->serieName = m_movieSelectionHandler->serieName;
if (!(!(*current_list)[i]->productionCountry.empty() && movieInfoUpdateAllIfDestEmptyOnly == true) &&
movieInfoUpdateAll[MB_INFO_COUNTRY])
(*current_list)[i]->productionCountry = m_movieSelectionHandler->productionCountry;
if (!((*current_list)[i]->genreMajor!=0 && movieInfoUpdateAllIfDestEmptyOnly == true) &&
movieInfoUpdateAll[MB_INFO_MAJOR_GENRE])
(*current_list)[i]->genreMajor = m_movieSelectionHandler->genreMajor;
if (!((*current_list)[i]->quality!=0 && movieInfoUpdateAllIfDestEmptyOnly == true) &&
movieInfoUpdateAll[MB_INFO_QUALITY])
(*current_list)[i]->quality = m_movieSelectionHandler->quality;
m_movieInfo.saveMovieInfo(*((*current_list)[i]));
}
loadBox.hide();
}
else if (actionKey == "reload_movie_info")
{
loadMovies(false);
updateMovieSelection();
}
else if (actionKey == "run")
{
if (parent) parent->hide();
exec(NULL);
}
else if (actionKey == "book_clear_all")
{
m_movieSelectionHandler->bookmarks.start =0;
m_movieSelectionHandler->bookmarks.end =0;
m_movieSelectionHandler->bookmarks.lastPlayStop =0;
for (int i = 0; i < MI_MOVIE_BOOK_USER_MAX; i++)
{
m_movieSelectionHandler->bookmarks.user[i].name.empty();
m_movieSelectionHandler->bookmarks.user[i].length =0;
m_movieSelectionHandler->bookmarks.user[i].pos =0;
}
}
else if (actionKey == "show_menu")
{
showMenu(true);
saveSettings(&m_settings);
}
else if (actionKey == "show_ytmenu")
{
showYTMenu(true);
saveSettings(&m_settings);
}
return returnval;
}
int CMovieBrowser::exec(const char* path)
{
bool res = false;
menu_ret = menu_return::RETURN_REPAINT;
TRACE("[mb]->%s\n", __func__);
int returnDefaultOnTimeout = true;
neutrino_msg_t msg;
neutrino_msg_data_t data;
CVFD::getInstance()->setMode(CVFD::MODE_MENU_UTF8, g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD));
loadSettings(&m_settings);
initFrames();
// Clear all, to avoid 'jump' in screen
m_vHandleBrowserList.clear();
m_vHandleRecordList.clear();
m_vHandlePlayList.clear();
clearListLines();
m_selectedDir = path;
if (m_settings.remount == true)
{
TRACE("[mb] remount\n");
/* FIXME: add hintbox ? */
//umount automount dirs
for (int i = 0; i < NETWORK_NFS_NR_OF_ENTRIES; i++)
{
if (g_settings.network_nfs[i].automount)
umount2(g_settings.network_nfs[i].local_dir.c_str(), MNT_FORCE);
}
CFSMounter::automount();
}
if (paint() == false)
return menu_ret;// paint failed due to less memory, exit
bool loop = true;
bool result;
int timeout = g_settings.timing[SNeutrinoSettings::TIMING_FILEBROWSER];
uint64_t timeoutEnd = CRCInput::calcTimeoutEnd(timeout);
while (loop)
{
framebuffer->blit();
g_RCInput->getMsgAbsoluteTimeout(&msg, &data, &timeoutEnd);
result = onButtonPress(msg);
if (result == false)
{
if (msg == CRCInput::RC_timeout && returnDefaultOnTimeout)
{
TRACE("[mb] Timerevent\n");
loop = false;
}
else if (msg == CRCInput::RC_ok)
{
for (unsigned int i = 0; i < m_vMovieInfo.size(); i++) {
if (m_vMovieInfo[i].marked) {
TRACE("[mb] has selected\n");
res = true;
break;
}
}
if (res)
break;
m_currentStartPos = 0;
if (m_movieSelectionHandler != NULL)
{
// If there is any available bookmark, show the bookmark menu
if (m_movieSelectionHandler->bookmarks.lastPlayStop != 0 ||
m_movieSelectionHandler->bookmarks.start != 0)
{
TRACE("[mb] stop: %d start:%d \n",m_movieSelectionHandler->bookmarks.lastPlayStop,m_movieSelectionHandler->bookmarks.start);
m_currentStartPos = showStartPosSelectionMenu(); // display start menu m_currentStartPos =
}
if (show_mode == MB_SHOW_YT)
cYTCache::getInstance()->useCachedCopy(m_movieSelectionHandler);
if (m_currentStartPos >= 0) {
playing_info = m_movieSelectionHandler;
TRACE("[mb] start pos: %d s\n",m_currentStartPos);
res = true;
loop = false;
} else
refresh();
}
}
else if ((show_mode == MB_SHOW_YT) && (msg == (neutrino_msg_t) g_settings.key_record) && m_movieSelectionHandler)
{
m_movieSelectionHandler->source = (show_mode == MB_SHOW_YT) ? MI_MOVIE_INFO::YT : MI_MOVIE_INFO::NK;
if (cYTCache::getInstance()->addToCache(m_movieSelectionHandler)) {
const char *format = g_Locale->getText(LOCALE_MOVIEBROWSER_YT_CACHE_ADD);
char buf[1024];
snprintf(buf, sizeof(buf), format, m_movieSelectionHandler->file.Name.c_str());
CHintBox hintBox(LOCALE_MOVIEBROWSER_YT_CACHE, buf);
hintBox.paint();
sleep(1);
hintBox.hide();
}
}
else if (msg == CRCInput::RC_home)
{
loop = false;
}
else if (msg == CRCInput::RC_sat || msg == CRCInput::RC_favorites) {
//FIXME do nothing ?
}
else if (msg == NeutrinoMessages::STANDBY_ON ||
msg == NeutrinoMessages::SHUTDOWN ||
msg == NeutrinoMessages::SLEEPTIMER)
{
menu_ret = menu_return::RETURN_EXIT_ALL;
loop = false;
g_RCInput->postMsg(msg, data);
}
else if (CNeutrinoApp::getInstance()->handleMsg(msg, data) & messages_return::cancel_all)
{
TRACE("[mb]->exec: getInstance\n");
menu_ret = menu_return::RETURN_EXIT_ALL;
loop = false;
}
}
if (msg <= CRCInput::RC_MaxRC)
timeoutEnd = CRCInput::calcTimeoutEnd(timeout); // calcualate next timeout
}
hide();
framebuffer->blit();
//TRACE(" return %d\n",res);
m_prevBrowserSelection = m_currentBrowserSelection;
m_prevRecordSelection = m_currentRecordSelection;
m_prevPlaySelection = m_currentPlaySelection;
saveSettings(&m_settings);
// make stale if we should reload the next time, but not if movie has to be played
if (m_settings.reload == true && res == false)
{
TRACE("[mb] force reload next time\n");
fileInfoStale();
}
//CVFD::getInstance()->setMode(CVFD::MODE_TVRADIO);
return (res);
}
void CMovieBrowser::hide(void)
{
//TRACE("[mb]->%s\n", __func__);
framebuffer->paintBackground();
if (m_pcFilter != NULL)
m_currentFilterSelection = m_pcFilter->getSelectedLine();
delete m_pcFilter;
m_pcFilter = NULL;
if (m_pcBrowser != NULL)
m_currentBrowserSelection = m_pcBrowser->getSelectedLine();
delete m_pcBrowser;
m_pcBrowser = NULL;
if (m_pcLastPlay != NULL)
m_currentPlaySelection = m_pcLastPlay->getSelectedLine();
delete m_pcLastPlay;
m_pcLastPlay = NULL;
if (m_pcLastRecord != NULL)
m_currentRecordSelection = m_pcLastRecord->getSelectedLine();
delete m_pcLastRecord;
m_pcLastRecord = NULL;
delete m_pcInfo;
m_pcInfo = NULL;
}
int CMovieBrowser::paint(void)
{
TRACE("[mb]->%s\n", __func__);
//CVFD::getInstance()->setMode(CVFD::MODE_MENU_UTF8, g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD));
Font* font = NULL;
m_pcBrowser = new CListFrame(&m_browserListLines, font, CListFrame::SCROLL | CListFrame::HEADER_LINE,
&m_cBoxFrameBrowserList);
m_pcLastPlay = new CListFrame(&m_playListLines, font, CListFrame::SCROLL | CListFrame::HEADER_LINE | CListFrame::TITLE,
&m_cBoxFrameLastPlayList, g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD_PLAYLIST),
g_Font[SNeutrinoSettings::FONT_TYPE_EPG_INFO1]);
m_pcLastRecord = new CListFrame(&m_recordListLines, font, CListFrame::SCROLL | CListFrame::HEADER_LINE | CListFrame::TITLE,
&m_cBoxFrameLastRecordList, g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD_RECORDLIST),
g_Font[SNeutrinoSettings::FONT_TYPE_EPG_INFO1]);
m_pcFilter = new CListFrame(&m_FilterLines, font, CListFrame::SCROLL | CListFrame::TITLE,
&m_cBoxFrameFilter, g_Locale->getText(LOCALE_MOVIEBROWSER_HEAD_FILTER),
g_Font[SNeutrinoSettings::FONT_TYPE_EPG_INFO1]);
m_pcInfo = new CTextBox(" ", NULL, CTextBox::TOP | CTextBox::SCROLL, &m_cBoxFrameInfo);
if (m_pcBrowser == NULL || m_pcLastPlay == NULL ||
m_pcLastRecord == NULL || m_pcInfo == NULL || m_pcFilter == NULL)
{
TRACE("[mb] paint, ERROR: not enought memory to allocate windows");
if (m_pcFilter != NULL)delete m_pcFilter;
if (m_pcBrowser != NULL)delete m_pcBrowser;
if (m_pcLastPlay != NULL) delete m_pcLastPlay;
if (m_pcLastRecord != NULL)delete m_pcLastRecord;
if (m_pcInfo != NULL) delete m_pcInfo;
m_pcInfo = NULL;
m_pcLastPlay = NULL;
m_pcLastRecord = NULL;
m_pcBrowser = NULL;
m_pcFilter = NULL;
return (false);
}
clearSelection();
if (m_file_info_stale == true) {
loadMovies();
} else {
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFilterList();
}
// get old movie selection and set position in windows
m_currentBrowserSelection = m_prevBrowserSelection;
m_currentRecordSelection = m_prevRecordSelection;
m_currentPlaySelection = m_prevPlaySelection;
m_pcBrowser->setSelectedLine(m_currentBrowserSelection);
m_pcLastRecord->setSelectedLine(m_currentRecordSelection);
m_pcLastPlay->setSelectedLine(m_currentPlaySelection);
updateMovieSelection();
refreshTitle();
refreshFoot();
refreshLCD();
if (m_settings.gui == MB_GUI_FILTER)
m_settings.gui = MB_GUI_MOVIE_INFO;
onSetGUIWindow(m_settings.gui);
return (true);
}
void CMovieBrowser::refresh(void)
{
TRACE("[mb]->%s\n", __func__);
refreshTitle();
if (m_pcBrowser != NULL && m_showBrowserFiles == true)
m_pcBrowser->refresh();
if (m_pcLastPlay != NULL && m_showLastPlayFiles == true)
m_pcLastPlay->refresh();
if (m_pcLastRecord != NULL && m_showLastRecordFiles == true)
m_pcLastRecord->refresh();
if (m_pcInfo != NULL && m_showMovieInfo == true)
refreshMovieInfo();
if (m_pcFilter != NULL && m_showFilter == true)
m_pcFilter->refresh();
refreshFoot();
refreshLCD();
}
std::string CMovieBrowser::getCurrentDir(void)
{
return(m_selectedDir);
}
CFile* CMovieBrowser::getSelectedFile(void)
{
//TRACE("[mb]->%s: %s\n", __func__, m_movieSelectionHandler->file.Name.c_str());
if (m_movieSelectionHandler != NULL)
return(&m_movieSelectionHandler->file);
else
return(NULL);
}
bool CMovieBrowser::getSelectedFiles(CFileList &flist, P_MI_MOVIE_LIST &mlist)
{
flist.clear();
mlist.clear();
P_MI_MOVIE_LIST *handle_list = &m_vHandleBrowserList;
if (m_windowFocus == MB_FOCUS_LAST_PLAY)
handle_list = &m_vHandlePlayList;
if (m_windowFocus == MB_FOCUS_LAST_RECORD)
handle_list = &m_vHandleRecordList;
for (unsigned int i = 0; i < handle_list->size(); i++) {
if ((*handle_list)[i]->marked) {
flist.push_back((*handle_list)[i]->file);
mlist.push_back((*handle_list)[i]);
}
}
return (!flist.empty());
}
std::string CMovieBrowser::getScreenshotName(std::string movie, bool is_dir)
{
std::string ext;
std::string ret;
size_t found;
if (is_dir)
found = movie.size();
else
found = movie.find_last_of(".");
if (found == string::npos)
return "";
vector<std::string>::iterator it = PicExts.begin();
while (it < PicExts.end()) {
ret = movie;
ext = *it;
ret.replace(found, ret.length() - found, ext);
++it;
if (!access(ret, F_OK))
return ret;
}
return "";
}
void CMovieBrowser::refreshMovieInfo(void)
{
TRACE("[mb]->%s m_vMovieInfo.size %d\n", __func__, (int)m_vMovieInfo.size());
//reset text before new init, m_pcInfo must be clean
std::string emptytext = " ";
m_pcInfo->setText(&emptytext);
if (m_vMovieInfo.empty() || m_movieSelectionHandler == NULL)
return;
std::string fname;
if (show_mode == MB_SHOW_YT) {
fname = m_movieSelectionHandler->tfile;
} else {
fname = getScreenshotName(m_movieSelectionHandler->file.Name, S_ISDIR(m_movieSelectionHandler->file.Mode));
if ((fname.empty()) && (m_movieSelectionHandler->file.Name.length() > 18)) {
std::string cover = m_movieSelectionHandler->file.Name;
cover.replace((cover.length()-18),15,""); //covername without yyyymmdd_hhmmss
fname = getScreenshotName(cover);
}
}
bool logo_ok = (!fname.empty());
int flogo_w = 0, flogo_h = 0;
if (logo_ok) {
int picw = (int)(((float)16 / (float)9) * (float)m_cBoxFrameInfo.iHeight);
int pich = m_cBoxFrameInfo.iHeight;
g_PicViewer->getSize(fname.c_str(), &flogo_w, &flogo_h);
g_PicViewer->rescaleImageDimensions(&flogo_w, &flogo_h, picw-2, pich-2);
#ifdef BOXMODEL_APOLLO
/* align for hw blit */
flogo_w = ((flogo_w + 3) / 4) * 4;
#endif
}
m_pcInfo->setText(&m_movieSelectionHandler->epgInfo2, logo_ok ? m_cBoxFrameInfo.iWidth-flogo_w-20 : 0);
static int logo_w = 0;
static int logo_h = 0;
int logo_w_max = m_cBoxFrameTitleRel.iWidth / 4;
//printf("refreshMovieInfo: EpgId %llx id %llx y %d\n", m_movieSelectionHandler->epgEpgId, m_movieSelectionHandler->epgId, m_cBoxFrameTitleRel.iY);
int lx = m_cBoxFrame.iX+m_cBoxFrameTitleRel.iX+m_cBoxFrameTitleRel.iWidth-logo_w-10;
int ly = m_cBoxFrameTitleRel.iY+m_cBoxFrame.iY+ (m_cBoxFrameTitleRel.iHeight-logo_h)/2;
short pb_hdd_offset = 104;
if (show_mode == MB_SHOW_YT)
pb_hdd_offset = 0;
static uint64_t old_EpgId = 0;
if (CChannelLogo && (old_EpgId != m_movieSelectionHandler->epgEpgId >>16)) {
if (newHeader)
CChannelLogo->clearSavedScreen();
else
CChannelLogo->hide();
delete CChannelLogo;
CChannelLogo = NULL;
}
if (old_EpgId != m_movieSelectionHandler->epgEpgId >>16) {
CChannelLogo = new CComponentsChannelLogo(0, 0, logo_w_max, m_cBoxFrameTitleRel.iHeight,
m_movieSelectionHandler->epgChannel, m_movieSelectionHandler->epgEpgId >>16);
old_EpgId = m_movieSelectionHandler->epgEpgId >>16;
}
if (CChannelLogo && CChannelLogo->hasLogo()) {
lx = m_cBoxFrame.iX+m_cBoxFrameTitleRel.iX+m_cBoxFrameTitleRel.iWidth-CChannelLogo->getWidth()-10;
ly = m_cBoxFrameTitleRel.iY+m_cBoxFrame.iY+ (m_cBoxFrameTitleRel.iHeight-CChannelLogo->getHeight())/2;
CChannelLogo->setXPos(lx - pb_hdd_offset);
CChannelLogo->setYPos(ly);
CChannelLogo->paint();
newHeader = false;
}
if (m_settings.gui != MB_GUI_FILTER && logo_ok) {
lx = m_cBoxFrameInfo.iX+m_cBoxFrameInfo.iWidth - flogo_w -14;
ly = m_cBoxFrameInfo.iY - 1 + (m_cBoxFrameInfo.iHeight-flogo_h)/2;
g_PicViewer->DisplayImage(fname, lx+2, ly+1, flogo_w, flogo_h, CFrameBuffer::TM_NONE);
framebuffer->paintVLineRel(lx, ly, flogo_h+1, COL_WHITE);
framebuffer->paintVLineRel(lx+flogo_w+2, ly, flogo_h+2, COL_WHITE);
framebuffer->paintHLineRel(lx, flogo_w+2, ly, COL_WHITE);
framebuffer->paintHLineRel(lx, flogo_w+2, ly+flogo_h+1, COL_WHITE);
}
framebuffer->blit();
}
void CMovieBrowser::info_hdd_level(bool paint_hdd)
{
if (show_mode == MB_SHOW_YT)
return;
struct statfs s;
long blocks_percent_used =0;
static long tmp_blocks_percent_used = 0;
if (getSelectedFile() != NULL) {
if (::statfs(getSelectedFile()->Name.c_str(), &s) == 0) {
long blocks_used = s.f_blocks - s.f_bfree;
blocks_percent_used = (blocks_used * 1000 / (blocks_used + s.f_bavail) + 5)/10;
}
}
if (tmp_blocks_percent_used != blocks_percent_used || paint_hdd) {
tmp_blocks_percent_used = blocks_percent_used;
const short pbw = 100;
const short border = m_cBoxFrameTitleRel.iHeight/4;
CProgressBar pb(m_cBoxFrame.iX+ m_cBoxFrameFootRel.iWidth - pbw - border, m_cBoxFrame.iY+m_cBoxFrameTitleRel.iY + border, pbw, m_cBoxFrameTitleRel.iHeight/2);
pb.setType(CProgressBar::PB_REDRIGHT);
pb.setValues(blocks_percent_used, 100);
pb.paint(false);
}
}
void CMovieBrowser::refreshLCD(void)
{
if (m_vMovieInfo.empty() || m_movieSelectionHandler == NULL)
return;
CVFD::getInstance()->showMenuText(0, m_movieSelectionHandler->epgTitle.c_str(), -1, true); // UTF-8
}
void CMovieBrowser::refreshFilterList(void)
{
TRACE("[mb]->refreshFilterList %d\n",m_settings.filter.item);
std::string string_item;
m_FilterLines.rows = 1;
m_FilterLines.lineArray[0].clear();
m_FilterLines.rowWidth[0] = 100;
m_FilterLines.lineHeader[0] = "";
if (m_vMovieInfo.empty())
return; // exit here if nothing else is to do
if (m_settings.filter.item == MB_INFO_MAX_NUMBER)
{
// show Main List
string_item = g_Locale->getText(LOCALE_MOVIEBROWSER_INFO_GENRE_MAJOR);
m_FilterLines.lineArray[0].push_back(string_item);
string_item = g_Locale->getText(LOCALE_MOVIEBROWSER_INFO_INFO1);
m_FilterLines.lineArray[0].push_back(string_item);
string_item = g_Locale->getText(LOCALE_MOVIEBROWSER_INFO_PATH);
m_FilterLines.lineArray[0].push_back(string_item);
string_item = g_Locale->getText(LOCALE_MOVIEBROWSER_INFO_SERIE);
m_FilterLines.lineArray[0].push_back(string_item);
}
else
{
std::string tmp = g_Locale->getText(LOCALE_MENU_BACK);
m_FilterLines.lineArray[0].push_back(tmp);
if (m_settings.filter.item == MB_INFO_FILEPATH)
{
for (unsigned int i = 0 ; i < m_dirNames.size(); i++)
m_FilterLines.lineArray[0].push_back(m_dirNames[i]);
}
else if (m_settings.filter.item == MB_INFO_INFO1)
{
for (unsigned int i = 0; i < m_vMovieInfo.size(); i++)
{
bool found = false;
for (unsigned int t = 0; t < m_FilterLines.lineArray[0].size() && found == false; t++)
{
if (strcmp(m_FilterLines.lineArray[0][t].c_str(),m_vMovieInfo[i].epgInfo1.c_str()) == 0)
found = true;
}
if (found == false)
m_FilterLines.lineArray[0].push_back(m_vMovieInfo[i].epgInfo1);
}
}
else if (m_settings.filter.item == MB_INFO_MAJOR_GENRE)
{
for (int i = 0; i < GENRE_ALL_COUNT; i++)
{
std::string tmpl = g_Locale->getText(GENRE_ALL[i].value);
m_FilterLines.lineArray[0].push_back(tmpl);
}
}
else if (m_settings.filter.item == MB_INFO_SERIE)
{
updateSerienames();
for (unsigned int i = 0; i < m_vHandleSerienames.size(); i++)
m_FilterLines.lineArray[0].push_back(m_vHandleSerienames[i]->serieName);
}
}
m_pcFilter->setLines(&m_FilterLines);
}
void CMovieBrowser::refreshLastPlayList(void) //P2
{
//TRACE("[mb]->refreshlastPlayList \n");
std::string string_item;
// Initialise and clear list array
m_playListLines.rows = m_settings.lastPlayRowNr;
for (int row = 0 ;row < m_settings.lastPlayRowNr; row++)
{
m_playListLines.lineArray[row].clear();
m_playListLines.rowWidth[row] = m_settings.lastPlayRowWidth[row];
m_playListLines.lineHeader[row] = g_Locale->getText(m_localizedItemName[m_settings.lastPlayRow[row]]);
}
m_playListLines.marked.clear();
m_vHandlePlayList.clear();
if (m_vMovieInfo.empty()) {
if (m_pcLastPlay != NULL)
m_pcLastPlay->setLines(&m_playListLines);
return; // exit here if nothing else is to do
}
MI_MOVIE_INFO* movie_handle;
// prepare Browser list for sorting and filtering
for (unsigned int file = 0; file < m_vMovieInfo.size(); file++)
{
if (isParentalLock(m_vMovieInfo[file]) == false)
{
movie_handle = &(m_vMovieInfo[file]);
m_vHandlePlayList.push_back(movie_handle);
}
}
// sort the not filtered files
onSortMovieInfoHandleList(m_vHandlePlayList,MB_INFO_PREVPLAYDATE,MB_DIRECTION_DOWN);
for (int handle=0; handle < (int) m_vHandlePlayList.size() && handle < m_settings.lastPlayMaxItems ;handle++)
{
for (int row = 0; row < m_settings.lastPlayRowNr ;row++)
{
if (getMovieInfoItem(*m_vHandlePlayList[handle], m_settings.lastPlayRow[row], &string_item) == false)
{
string_item = "n/a";
if (m_settings.lastPlayRow[row] == MB_INFO_TITLE)
getMovieInfoItem(*m_vHandlePlayList[handle], MB_INFO_FILENAME, &string_item);
}
m_playListLines.lineArray[row].push_back(string_item);
}
m_playListLines.marked.push_back(m_vHandlePlayList[handle]->marked);
}
m_pcLastPlay->setLines(&m_playListLines);
m_currentPlaySelection = m_pcLastPlay->getSelectedLine();
// update selected movie if browser is in the focus
if (m_windowFocus == MB_FOCUS_LAST_PLAY)
updateMovieSelection();
}
void CMovieBrowser::refreshLastRecordList(void) //P2
{
//TRACE("[mb]->refreshLastRecordList \n");
std::string string_item;
// Initialise and clear list array
m_recordListLines.rows = m_settings.lastRecordRowNr;
for (int row = 0 ;row < m_settings.lastRecordRowNr; row++)
{
m_recordListLines.lineArray[row].clear();
m_recordListLines.rowWidth[row] = m_settings.lastRecordRowWidth[row];
m_recordListLines.lineHeader[row] = g_Locale->getText(m_localizedItemName[m_settings.lastRecordRow[row]]);
}
m_recordListLines.marked.clear();
m_vHandleRecordList.clear();
if (m_vMovieInfo.empty()) {
if (m_pcLastRecord != NULL)
m_pcLastRecord->setLines(&m_recordListLines);
return; // exit here if nothing else is to do
}
MI_MOVIE_INFO* movie_handle;
// prepare Browser list for sorting and filtering
for (unsigned int file = 0; file < m_vMovieInfo.size(); file++)
{
if (isParentalLock(m_vMovieInfo[file]) == false)
{
movie_handle = &(m_vMovieInfo[file]);
m_vHandleRecordList.push_back(movie_handle);
}
}
// sort the not filtered files
onSortMovieInfoHandleList(m_vHandleRecordList,MB_INFO_RECORDDATE,MB_DIRECTION_DOWN);
for (int handle=0; handle < (int) m_vHandleRecordList.size() && handle < m_settings.lastRecordMaxItems ;handle++)
{
for (int row = 0; row < m_settings.lastRecordRowNr ;row++)
{
if (getMovieInfoItem(*m_vHandleRecordList[handle], m_settings.lastRecordRow[row], &string_item) == false)
{
string_item = "n/a";
if (m_settings.lastRecordRow[row] == MB_INFO_TITLE)
getMovieInfoItem(*m_vHandleRecordList[handle], MB_INFO_FILENAME, &string_item);
}
m_recordListLines.lineArray[row].push_back(string_item);
}
m_recordListLines.marked.push_back(m_vHandleRecordList[handle]->marked);
}
m_pcLastRecord->setLines(&m_recordListLines);
m_currentRecordSelection = m_pcLastRecord->getSelectedLine();
// update selected movie if browser is in the focus
if (m_windowFocus == MB_FOCUS_LAST_RECORD)
updateMovieSelection();
}
void CMovieBrowser::refreshBrowserList(void) //P1
{
TRACE("[mb]->%s\n", __func__);
std::string string_item;
// Initialise and clear list array
m_browserListLines.rows = m_settings.browserRowNr;
for (int row = 0; row < m_settings.browserRowNr; row++)
{
m_browserListLines.lineArray[row].clear();
m_browserListLines.rowWidth[row] = m_settings.browserRowWidth[row];
m_browserListLines.lineHeader[row] = g_Locale->getText(m_localizedItemName[m_settings.browserRowItem[row]]);
}
m_browserListLines.Icon.clear();
m_browserListLines.marked.clear();
m_vHandleBrowserList.clear();
if (m_vMovieInfo.empty())
{
m_currentBrowserSelection = 0;
m_movieSelectionHandler = NULL;
if (m_pcBrowser != NULL)
m_pcBrowser->setLines(&m_browserListLines);//FIXME last delete test
return; // exit here if nothing else is to do
}
MI_MOVIE_INFO* movie_handle;
// prepare Browser list for sorting and filtering
for (unsigned int file=0; file < m_vMovieInfo.size(); file++)
{
if (isFiltered(m_vMovieInfo[file]) == false &&
isParentalLock(m_vMovieInfo[file]) == false &&
(m_settings.browser_serie_mode == 0 || m_vMovieInfo[file].serieName.empty() || m_settings.filter.item == MB_INFO_SERIE))
{
movie_handle = &(m_vMovieInfo[file]);
m_vHandleBrowserList.push_back(movie_handle);
}
}
// sort the not filtered files
onSortMovieInfoHandleList(m_vHandleBrowserList,m_settings.sorting.item,MB_DIRECTION_AUTO);
for (unsigned int handle=0; handle < m_vHandleBrowserList.size() ;handle++)
{
for (int row = 0; row < m_settings.browserRowNr ;row++)
{
if (getMovieInfoItem(*m_vHandleBrowserList[handle], m_settings.browserRowItem[row], &string_item) == false)
{
string_item = "n/a";
if (m_settings.browserRowItem[row] == MB_INFO_TITLE)
getMovieInfoItem(*m_vHandleBrowserList[handle], MB_INFO_FILENAME, &string_item);
}
m_browserListLines.lineArray[row].push_back(string_item);
}
if (CRecordManager::getInstance()->getRecordInstance(m_vHandleBrowserList[handle]->file.Name) != NULL)
m_browserListLines.Icon.push_back(NEUTRINO_ICON_REC);
else
m_browserListLines.Icon.push_back("");
m_browserListLines.marked.push_back(m_vHandleBrowserList[handle]->marked);
}
m_pcBrowser->setLines(&m_browserListLines);
m_currentBrowserSelection = m_pcBrowser->getSelectedLine();
// update selected movie if browser is in the focus
if (m_windowFocus == MB_FOCUS_BROWSER)
updateMovieSelection();
}
void CMovieBrowser::refreshTitle(void)
{
std::string title = m_textTitle.c_str();
const char *icon = NEUTRINO_ICON_MOVIEPLAYER;
if (show_mode == MB_SHOW_YT) {
title = g_Locale->getText(LOCALE_MOVIEPLAYER_YTPLAYBACK);
title += " : ";
neutrino_locale_t loc = getFeedLocale();
title += g_Locale->getText(loc);
if (loc == LOCALE_MOVIEBROWSER_YT_RELATED || loc == LOCALE_MOVIEBROWSER_YT_SEARCH)
title += " \"" + m_settings.ytsearch + "\"";
icon = NEUTRINO_ICON_YTPLAY;
}
TRACE("[mb]->refreshTitle : %s\n", title.c_str());
int x = m_cBoxFrameTitleRel.iX + m_cBoxFrame.iX;
int y = m_cBoxFrameTitleRel.iY + m_cBoxFrame.iY;
int w = m_cBoxFrameTitleRel.iWidth;
int h = m_cBoxFrameTitleRel.iHeight;
CComponentsHeader header(x, y, w, h, title.c_str(), icon);
header.paint(CC_SAVE_SCREEN_NO);
newHeader = true;
info_hdd_level(true);
}
int CMovieBrowser::refreshFoot(bool show)
{
//TRACE("[mb]->refreshButtonLine\n");
int offset = (m_settings.gui != MB_GUI_LAST_PLAY && m_settings.gui != MB_GUI_LAST_RECORD) ? 0 : 2;
neutrino_locale_t ok_loc = (m_settings.gui == MB_GUI_FILTER && m_windowFocus == MB_FOCUS_FILTER) ? LOCALE_BOOKMARKMANAGER_SELECT : LOCALE_MOVIEBROWSER_FOOT_PLAY;
int ok_loc_len = std::max(g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(g_Locale->getText(LOCALE_BOOKMARKMANAGER_SELECT), true),
g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(g_Locale->getText(LOCALE_MOVIEBROWSER_FOOT_PLAY), true));
std::string filter_text = g_Locale->getText(LOCALE_MOVIEBROWSER_FOOT_FILTER);
filter_text += m_settings.filter.optionString;
std::string sort_text = g_Locale->getText(LOCALE_MOVIEBROWSER_FOOT_SORT);
sort_text += g_Locale->getText(m_localizedItemName[m_settings.sorting.item]);
int sort_text_len = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(g_Locale->getText(LOCALE_MOVIEBROWSER_FOOT_SORT), true);
int len = 0;
for (int i = 0; m_localizedItemName[i] != NONEXISTANT_LOCALE; i++)
len = std::max(len, g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(g_Locale->getText(m_localizedItemName[i]), true));
sort_text_len += len;
button_label_ext footerButtons[] = {
{ NEUTRINO_ICON_BUTTON_RED, NONEXISTANT_LOCALE, sort_text.c_str(), sort_text_len, false },
{ NEUTRINO_ICON_BUTTON_GREEN, NONEXISTANT_LOCALE, filter_text.c_str(), 0, true },
{ NEUTRINO_ICON_BUTTON_YELLOW, LOCALE_MOVIEBROWSER_FOOT_FOCUS, NULL, 0, false },
{ NEUTRINO_ICON_BUTTON_BLUE, LOCALE_MOVIEBROWSER_FOOT_REFRESH, NULL, 0, false },
{ NEUTRINO_ICON_BUTTON_OKAY, ok_loc, NULL, ok_loc_len, false },
{ NEUTRINO_ICON_BUTTON_MUTE_SMALL, LOCALE_FILEBROWSER_DELETE, NULL, 0, false },
{ NEUTRINO_ICON_BUTTON_PLAY, LOCALE_FILEBROWSER_MARK, NULL, 0, false },
{ NEUTRINO_ICON_BUTTON_MENU_SMALL, LOCALE_MOVIEBROWSER_FOOT_OPTIONS, NULL, 0, false }
};
int cnt = sizeof(footerButtons) / sizeof(button_label_ext);
if (show)
return paintButtons(footerButtons + offset, cnt - offset, m_cBoxFrame.iX+m_cBoxFrameFootRel.iX, m_cBoxFrame.iY+m_cBoxFrameFootRel.iY, m_cBoxFrameFootRel.iWidth, m_cBoxFrameFootRel.iHeight, m_cBoxFrameFootRel.iWidth);
else
return paintButtons(footerButtons, cnt, 0, 0, 0, 0, 0, false, NULL, NULL);
}
bool CMovieBrowser::onButtonPress(neutrino_msg_t msg)
{
// TRACE("[mb]->onButtonPress %d\n",msg);
bool result = onButtonPressMainFrame(msg);
if (result == false)
{
// if Main Frame didnot process the button, the focused window may do
if (m_windowFocus == MB_FOCUS_BROWSER)
result = onButtonPressBrowserList(msg);
else if (m_windowFocus == MB_FOCUS_LAST_PLAY)
result = onButtonPressLastPlayList(msg);
else if (m_windowFocus == MB_FOCUS_LAST_RECORD)
result = onButtonPressLastRecordList(msg);
else if (m_windowFocus == MB_FOCUS_MOVIE_INFO)
result = onButtonPressMovieInfoList(msg);
else if (m_windowFocus == MB_FOCUS_FILTER)
result = onButtonPressFilterList(msg);
}
return (result);
}
bool CMovieBrowser::onButtonPressMainFrame(neutrino_msg_t msg)
{
//TRACE("[mb]->onButtonPressMainFrame: %d\n",msg);
bool result = true;
if (msg == CRCInput::RC_home)
{
if (m_settings.gui == MB_GUI_FILTER)
onSetGUIWindow(MB_GUI_MOVIE_INFO);
else
result = false;
}
else if (msg == (neutrino_msg_t)g_settings.key_volumedown)
{
onSetGUIWindowPrev();
}
else if (msg == (neutrino_msg_t)g_settings.key_volumeup)
{
onSetGUIWindowNext();
}
else if (msg == CRCInput::RC_green)
{
if (m_settings.gui == MB_GUI_MOVIE_INFO)
onSetGUIWindow(MB_GUI_FILTER);
else if (m_settings.gui == MB_GUI_FILTER)
onSetGUIWindow(MB_GUI_MOVIE_INFO);
// no effect if gui is last play or record
}
else if (msg == CRCInput::RC_yellow)
{
onSetFocusNext();
}
else if (msg == CRCInput::RC_blue)
{
if (show_mode == MB_SHOW_YT)
ytparser.Cleanup();
loadMovies();
refresh();
}
else if (msg == CRCInput::RC_red)
{
if (m_settings.gui != MB_GUI_LAST_PLAY && m_settings.gui != MB_GUI_LAST_RECORD)
{
// sorting is not avialable for last play and record
do
{
if (m_settings.sorting.item + 1 >= MB_INFO_MAX_NUMBER)
m_settings.sorting.item = (MB_INFO_ITEM)0;
else
m_settings.sorting.item = (MB_INFO_ITEM)(m_settings.sorting.item + 1);
} while (sortBy[m_settings.sorting.item] == NULL);
TRACE("[mb]->new sorting %d,%s\n",m_settings.sorting.item,g_Locale->getText(m_localizedItemName[m_settings.sorting.item]));
refreshBrowserList();
refreshFoot();
}
}
else if (msg == CRCInput::RC_spkr)
{
if ((!m_vMovieInfo.empty()) && (m_movieSelectionHandler != NULL)) {
bool onDelete = true;
bool skipAsk = false;
CRecordInstance* inst = CRecordManager::getInstance()->getRecordInstance(m_movieSelectionHandler->file.Name);
if (inst != NULL) {
std::string delName = m_movieSelectionHandler->epgTitle;
if (delName.empty())
delName = m_movieSelectionHandler->file.getFileName();
char buf1[1024];
snprintf(buf1, sizeof(buf1), g_Locale->getText(LOCALE_MOVIEBROWSER_ASK_REC_TO_DELETE), delName.c_str());
if (ShowMsg(LOCALE_RECORDINGMENU_RECORD_IS_RUNNING, buf1,
CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo, NULL, 450, 30, false) == CMessageBox::mbrNo)
onDelete = false;
else {
CTimerd::RecordingStopInfo recinfo;
recinfo.channel_id = inst->GetChannelId();
recinfo.eventID = inst->GetRecordingId();
CRecordManager::getInstance()->Stop(&recinfo);
g_Timerd->removeTimerEvent(recinfo.eventID);
skipAsk = true;
}
}
if (onDelete)
onDeleteFile(*m_movieSelectionHandler, skipAsk);
}
}
else if (msg == CRCInput::RC_help || msg == CRCInput::RC_info)
{
if (m_movieSelectionHandler != NULL)
{
m_movieInfo.showMovieInfo(*m_movieSelectionHandler);
refresh();
}
}
else if (msg == CRCInput::RC_setup)
{
if (show_mode == MB_SHOW_YT)
showYTMenu();
else
showMenu();
}
else if (msg == CRCInput::RC_text || msg == CRCInput::RC_radio) {
if ((show_mode == MB_SHOW_RECORDS) &&
(ShowMsg(LOCALE_MESSAGEBOX_INFO, msg == CRCInput::RC_radio ? LOCALE_MOVIEBROWSER_COPY : LOCALE_MOVIEBROWSER_COPIES, CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo) == CMessageBox::mbrYes)) {
CHintBox * hintBox = new CHintBox(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_COPYING);
hintBox->paint();
sleep(1);
hintBox->hide();
delete hintBox;
framebuffer->paintBackground(); // clear screen
CMovieCut mc;
bool res = mc.copyMovie(m_movieSelectionHandler, &m_movieInfo, msg == CRCInput::RC_radio);
//g_RCInput->clearRCMsg();
if (res == 0)
ShowMsg(LOCALE_MESSAGEBOX_ERROR, LOCALE_MOVIEBROWSER_COPY_FAILED, CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else
loadMovies();
refresh();
}
}
else if (msg == CRCInput::RC_audio) {
#if 0
if ((m_movieSelectionHandler == playing_info) && (NeutrinoMessages::mode_ts == CNeutrinoApp::getInstance()->getMode()))
ShowMsg(LOCALE_MESSAGEBOX_ERROR, "Impossible to cut playing movie.", CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else
#endif
if ((show_mode == MB_SHOW_RECORDS) &&
(ShowMsg(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_CUT, CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo) == CMessageBox::mbrYes)) {
CHintBox * hintBox = new CHintBox(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_CUTTING);
hintBox->paint();
sleep(1);
hintBox->hide();
delete hintBox;
framebuffer->paintBackground(); // clear screen
CMovieCut mc;
bool res = mc.cutMovie(m_movieSelectionHandler, &m_movieInfo);
//g_RCInput->clearRCMsg();
if (!res)
ShowMsg(LOCALE_MESSAGEBOX_ERROR, LOCALE_MOVIEBROWSER_CUT_FAILED, CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else
loadMovies();
refresh();
}
}
else if (msg == CRCInput::RC_games) {
if ((show_mode == MB_SHOW_RECORDS) && m_movieSelectionHandler != NULL) {
if ((m_movieSelectionHandler == playing_info) && (NeutrinoMessages::mode_ts == CNeutrinoApp::getInstance()->getMode()))
ShowMsg(LOCALE_MESSAGEBOX_ERROR, LOCALE_MOVIEBROWSER_TRUNCATE_FAILED_PLAYING, CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else if (m_movieSelectionHandler->bookmarks.end == 0)
ShowMsg(LOCALE_MESSAGEBOX_ERROR, LOCALE_MOVIEBROWSER_BOOK_NO_END, CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else {
if (ShowMsg(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_TRUNCATE, CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo) == CMessageBox::mbrYes) {
CHintBox * hintBox = new CHintBox(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_TRUNCATING);
hintBox->paint();
CMovieCut mc;
bool res = mc.truncateMovie(m_movieSelectionHandler);
hintBox->hide();
delete hintBox;
g_RCInput->clearRCMsg();
if (!res)
ShowMsg(LOCALE_MESSAGEBOX_ERROR, LOCALE_MOVIEBROWSER_TRUNCATE_FAILED, CMessageBox::mbrCancel, CMessageBox::mbCancel, NEUTRINO_ICON_ERROR);
else {
//printf("New movie info: size %lld len %d\n", res, m_movieSelectionHandler->bookmarks.end/60);
m_movieInfo.saveMovieInfo(*m_movieSelectionHandler);
loadMovies();
}
refresh();
}
}
}
} else if (msg == CRCInput::RC_favorites) {
if (m_movieSelectionHandler != NULL) {
if (ShowMsg(LOCALE_MESSAGEBOX_INFO, LOCALE_MOVIEBROWSER_DELETE_SCREENSHOT, CMessageBox::mbrNo, CMessageBox:: mbYes | CMessageBox::mbNo) == CMessageBox::mbrYes) {
std::string fname = getScreenshotName(m_movieSelectionHandler->file.Name, S_ISDIR(m_movieSelectionHandler->file.Mode));
if (!fname.empty())
unlink(fname.c_str());
refresh();
}
}
}
else
{
//TRACE("[mb]->onButtonPressMainFrame none\n");
result = false;
}
return (result);
}
void CMovieBrowser::markItem(CListFrame *list)
{
m_movieSelectionHandler->marked = !m_movieSelectionHandler->marked;
list->setSelectedMarked(m_movieSelectionHandler->marked);
list->scrollLineDown(1);
}
void CMovieBrowser::scrollBrowserItem(bool next, bool page)
{
int mode = -1;
if (show_mode == MB_SHOW_YT && next && ytparser.HaveNext() && m_pcBrowser->getSelectedLine() == m_pcBrowser->getLines() - 1)
mode = cYTFeedParser::NEXT;
if (show_mode == MB_SHOW_YT && !next && ytparser.HavePrev() && m_pcBrowser->getSelectedLine() == 0)
mode = cYTFeedParser::PREV;
if (mode >= 0) {
CHintBox loadBox(LOCALE_MOVIEPLAYER_YTPLAYBACK, g_Locale->getText(LOCALE_MOVIEBROWSER_SCAN_FOR_MOVIES));
loadBox.paint();
ytparser.Cleanup();
loadYTitles(mode, m_settings.ytsearch, m_settings.ytvid);
loadBox.hide();
refreshBrowserList();
refreshMovieInfo();
g_RCInput->clearRCMsg();
return;
}
if (next)
page ? m_pcBrowser->scrollPageDown(1) : m_pcBrowser->scrollLineDown(1);
else
page ? m_pcBrowser->scrollPageUp(1) : m_pcBrowser->scrollLineUp(1);
}
bool CMovieBrowser::onButtonPressBrowserList(neutrino_msg_t msg)
{
//TRACE("[mb]->onButtonPressBrowserList %d\n",msg);
bool result = true;
if (msg == CRCInput::RC_up)
scrollBrowserItem(false, false);
else if (msg == CRCInput::RC_down)
scrollBrowserItem(true, false);
else if ((msg == (neutrino_msg_t)g_settings.key_pageup) || (msg == CRCInput::RC_left))
scrollBrowserItem(false, true);
else if ((msg == (neutrino_msg_t)g_settings.key_pagedown) || (msg == CRCInput::RC_right))
scrollBrowserItem(true, true);
else if (msg == CRCInput::RC_play)
markItem(m_pcBrowser);
else
result = false;
if (result == true)
updateMovieSelection();
return (result);
}
bool CMovieBrowser::onButtonPressLastPlayList(neutrino_msg_t msg)
{
//TRACE("[mb]->onButtonPressLastPlayList %d\n",msg);
bool result = true;
if (msg==CRCInput::RC_up)
m_pcLastPlay->scrollLineUp(1);
else if (msg == CRCInput::RC_down)
m_pcLastPlay->scrollLineDown(1);
else if (msg == CRCInput::RC_left || msg == (neutrino_msg_t)g_settings.key_pageup)
m_pcLastPlay->scrollPageUp(1);
else if (msg == CRCInput::RC_right || msg == (neutrino_msg_t)g_settings.key_pagedown)
m_pcLastPlay->scrollPageDown(1);
else if (msg == CRCInput::RC_play)
markItem(m_pcLastPlay);
else
result = false;
if (result == true)
updateMovieSelection();
return (result);
}
bool CMovieBrowser::onButtonPressLastRecordList(neutrino_msg_t msg)
{
//TRACE("[mb]->onButtonPressLastRecordList %d\n",msg);
bool result = true;
if (msg == CRCInput::RC_up)
m_pcLastRecord->scrollLineUp(1);
else if (msg == CRCInput::RC_down)
m_pcLastRecord->scrollLineDown(1);
else if (msg == CRCInput::RC_left || msg == (neutrino_msg_t)g_settings.key_pageup)
m_pcLastRecord->scrollPageUp(1);
else if (msg == CRCInput::RC_right || msg == (neutrino_msg_t)g_settings.key_pagedown)
m_pcLastRecord->scrollPageDown(1);
else if (msg == CRCInput::RC_play)
markItem(m_pcLastRecord);
else
result = false;
if (result == true)
updateMovieSelection();
return (result);
}
bool CMovieBrowser::onButtonPressFilterList(neutrino_msg_t msg)
{
//TRACE("[mb]->onButtonPressFilterList %d,%d\n",msg,m_settings.filter.item);
bool result = true;
if (msg==CRCInput::RC_up)
{
m_pcFilter->scrollLineUp(1);
}
else if (msg == CRCInput::RC_down)
{
m_pcFilter->scrollLineDown(1);
}
else if (msg == (neutrino_msg_t)g_settings.key_pageup)
{
m_pcFilter->scrollPageUp(1);
}
else if (msg == (neutrino_msg_t)g_settings.key_pagedown)
{
m_pcFilter->scrollPageDown(1);
}
else if (msg == CRCInput::RC_ok)
{
int selected_line = m_pcFilter->getSelectedLine();
if (m_settings.filter.item == MB_INFO_MAX_NUMBER)
{
if (selected_line == 0) m_settings.filter.item = MB_INFO_MAJOR_GENRE;
if (selected_line == 1) m_settings.filter.item = MB_INFO_INFO1;
if (selected_line == 2) m_settings.filter.item = MB_INFO_FILEPATH;
if (selected_line == 3) m_settings.filter.item = MB_INFO_SERIE;
refreshFilterList();
m_pcFilter->setSelectedLine(0);
}
else
{
if (selected_line == 0)
{
m_settings.filter.item = MB_INFO_MAX_NUMBER;
m_settings.filter.optionString = "";
m_settings.filter.optionVar = 0;
refreshFilterList();
m_pcFilter->setSelectedLine(0);
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFoot();
}
else
{
updateFilterSelection();
}
}
}
else if (msg == CRCInput::RC_left)
{
m_pcFilter->scrollPageUp(1);
}
else if (msg == CRCInput::RC_right)
{
m_pcFilter->scrollPageDown(1);
}
else
{
// default
result = false;
}
return (result);
}
bool CMovieBrowser::onButtonPressMovieInfoList(neutrino_msg_t msg)
{
// TRACE("[mb]->onButtonPressEPGInfoList %d\n",msg);
bool result = true;
if (msg == CRCInput::RC_up)
m_pcInfo->scrollPageUp(1);
else if (msg == CRCInput::RC_down)
m_pcInfo->scrollPageDown(1);
else
result = false;
return (result);
}
void CMovieBrowser::onDeleteFile(MI_MOVIE_INFO& movieSelectionHandler, bool skipAsk)
{
//TRACE("[onDeleteFile] ");
#if 0
int test= movieSelectionHandler.file.Name.find(".ts", movieSelectionHandler.file.Name.length()-3);
if (test == -1) {
// not a TS file, return!!!!!
TRACE("show_ts_info: not a TS file ");
return;
}
#endif
std::string msg = g_Locale->getText(LOCALE_FILEBROWSER_DODELETE1);
msg += "\n ";
if (movieSelectionHandler.file.Name.length() > 40)
{
msg += movieSelectionHandler.file.Name.substr(0,40);
msg += "...";
}
else
msg += movieSelectionHandler.file.Name;
msg += "\n ";
msg += g_Locale->getText(LOCALE_FILEBROWSER_DODELETE2);
if ((skipAsk) || (ShowMsg(LOCALE_FILEBROWSER_DELETE, msg, CMessageBox::mbrYes, CMessageBox::mbYes|CMessageBox::mbNo)==CMessageBox::mbrYes))
{
CHintBox * hintBox = new CHintBox(LOCALE_MESSAGEBOX_INFO, g_Locale->getText(LOCALE_MOVIEBROWSER_DELETE_INFO));
hintBox->paint();
delFile(movieSelectionHandler.file);
std::string fname = getScreenshotName(movieSelectionHandler.file.Name, S_ISDIR(m_movieSelectionHandler->file.Mode));
if (!fname.empty())
unlink(fname.c_str());
CFile file_xml = movieSelectionHandler.file;
if (m_movieInfo.convertTs2XmlName(file_xml.Name))
unlink(file_xml.Name.c_str());
delete hintBox;
g_RCInput->clearRCMsg();
m_vMovieInfo.erase((std::vector<MI_MOVIE_INFO>::iterator)&movieSelectionHandler);
TRACE("List size: %d\n", (int)m_vMovieInfo.size());
updateSerienames();
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshMovieInfo();
refresh();
}
}
void CMovieBrowser::onSetGUIWindow(MB_GUI gui)
{
TRACE("[mb]->onSetGUIWindow: gui %d -> %d\n", m_settings.gui, gui);
m_settings.gui = gui;
m_showMovieInfo = true;
if (gui == MB_GUI_MOVIE_INFO) {
m_showBrowserFiles = true;
m_showLastRecordFiles = false;
m_showLastPlayFiles = false;
m_showFilter = false;
m_pcLastPlay->hide();
m_pcLastRecord->hide();
m_pcFilter->hide();
m_pcBrowser->paint();
onSetFocus(MB_FOCUS_BROWSER);
} else if (gui == MB_GUI_LAST_PLAY) {
clearSelection();
m_showLastRecordFiles = true;
m_showLastPlayFiles = true;
m_showBrowserFiles = false;
m_showFilter = false;
m_pcBrowser->hide();
m_pcFilter->hide();
m_pcLastRecord->paint();
m_pcLastPlay->paint();
onSetFocus(MB_FOCUS_LAST_PLAY);
} else if (gui == MB_GUI_LAST_RECORD) {
clearSelection();
m_showLastRecordFiles = true;
m_showLastPlayFiles = true;
m_showBrowserFiles = false;
m_showFilter = false;
m_pcBrowser->hide();
m_pcFilter->hide();
m_pcLastRecord->paint();
m_pcLastPlay->paint();
onSetFocus(MB_FOCUS_LAST_RECORD);
} else if (gui == MB_GUI_FILTER) {
m_showFilter = true;
m_showMovieInfo = false;
m_pcInfo->hide();
m_pcFilter->paint();
onSetFocus(MB_FOCUS_FILTER);
}
if (m_showMovieInfo) {
m_pcInfo->paint();
refreshMovieInfo();
}
}
void CMovieBrowser::onSetGUIWindowNext(void)
{
if (m_settings.gui == MB_GUI_MOVIE_INFO)
onSetGUIWindow(MB_GUI_LAST_PLAY);
else if (m_settings.gui == MB_GUI_LAST_PLAY)
onSetGUIWindow(MB_GUI_LAST_RECORD);
else
onSetGUIWindow(MB_GUI_MOVIE_INFO);
}
void CMovieBrowser::onSetGUIWindowPrev(void)
{
if (m_settings.gui == MB_GUI_MOVIE_INFO)
onSetGUIWindow(MB_GUI_LAST_RECORD);
else if (m_settings.gui == MB_GUI_LAST_RECORD)
onSetGUIWindow(MB_GUI_LAST_PLAY);
else
onSetGUIWindow(MB_GUI_MOVIE_INFO);
}
void CMovieBrowser::onSetFocus(MB_FOCUS new_focus)
{
TRACE("[mb]->onSetFocus: focus %d -> %d \n", m_windowFocus, new_focus);
clearSelection();
m_windowFocus = new_focus;
m_pcBrowser->showSelection(false);
m_pcLastRecord->showSelection(false);
m_pcLastPlay->showSelection(false);
m_pcFilter->showSelection(false);
if (m_windowFocus == MB_FOCUS_BROWSER)
m_pcBrowser->showSelection(true);
else if (m_windowFocus == MB_FOCUS_LAST_PLAY)
m_pcLastPlay->showSelection(true);
else if (m_windowFocus == MB_FOCUS_LAST_RECORD)
m_pcLastRecord->showSelection(true);
else if (m_windowFocus == MB_FOCUS_FILTER)
m_pcFilter->showSelection(true);
updateMovieSelection();
refreshFoot();
}
void CMovieBrowser::onSetFocusNext(void)
{
TRACE("[mb]->onSetFocusNext: gui %d\n", m_settings.gui);
if (m_settings.gui == MB_GUI_FILTER)
{
if (m_windowFocus == MB_FOCUS_BROWSER)
onSetFocus(MB_FOCUS_FILTER);
else
onSetFocus(MB_FOCUS_BROWSER);
}
else if (m_settings.gui == MB_GUI_MOVIE_INFO)
{
if (m_windowFocus == MB_FOCUS_BROWSER)
onSetFocus(MB_FOCUS_MOVIE_INFO);
else
onSetFocus(MB_FOCUS_BROWSER);
}
else if (m_settings.gui == MB_GUI_LAST_PLAY)
{
if (m_windowFocus == MB_FOCUS_MOVIE_INFO)
onSetFocus(MB_FOCUS_LAST_PLAY);
else if (m_windowFocus == MB_FOCUS_LAST_PLAY)
onSetFocus(MB_FOCUS_MOVIE_INFO);
}
else if (m_settings.gui == MB_GUI_LAST_RECORD)
{
if (m_windowFocus == MB_FOCUS_MOVIE_INFO)
onSetFocus(MB_FOCUS_LAST_RECORD);
else if (m_windowFocus == MB_FOCUS_LAST_RECORD)
onSetFocus(MB_FOCUS_MOVIE_INFO);
}
}
bool CMovieBrowser::onSortMovieInfoHandleList(std::vector<MI_MOVIE_INFO*>& handle_list, MB_INFO_ITEM sort_item, MB_DIRECTION direction)
{
//TRACE("sort: %d\n",direction);
if (handle_list.empty())
return false;
if (sortBy[sort_item] == NULL)
return false;
if (direction == MB_DIRECTION_AUTO)
{
if (sort_item == MB_INFO_QUALITY || sort_item == MB_INFO_PARENTAL_LOCKAGE ||
sort_item == MB_INFO_PREVPLAYDATE || sort_item == MB_INFO_RECORDDATE ||
sort_item == MB_INFO_PRODDATE || sort_item == MB_INFO_SIZE)
sortDirection = 1;
else
sortDirection = 0;
}
else if (direction == MB_DIRECTION_UP)
{
sortDirection = 0;
}
else
{
sortDirection = 1;
}
//TRACE("sort: %d\n",sortDirection);
sort(handle_list.begin(), handle_list.end(), sortBy[sort_item]);
return (true);
}
void CMovieBrowser::updateDir(void)
{
m_dir.clear();
#if 0
// check if there is a movie dir and if we should use it
if (g_settings.network_nfs_moviedir[0] != 0)
{
std::string name = g_settings.network_nfs_moviedir;
addDir(name,&m_settings.storageDirMovieUsed);
}
#endif
// check if there is a record dir and if we should use it
if (!g_settings.network_nfs_recordingdir.empty())
{
addDir(g_settings.network_nfs_recordingdir, &m_settings.storageDirRecUsed);
cHddStat::getInstance()->statOnce();
}
for (int i = 0; i < MB_MAX_DIRS; i++)
{
if (!m_settings.storageDir[i].empty())
addDir(m_settings.storageDir[i],&m_settings.storageDirUsed[i]);
}
}
void CMovieBrowser::loadAllTsFileNamesFromStorage(void)
{
//TRACE("[mb]->loadAllTsFileNamesFromStorage \n");
int i,size;
m_movieSelectionHandler = NULL;
m_dirNames.clear();
m_vMovieInfo.clear();
updateDir();
size = m_dir.size();
for (i=0; i < size;i++)
{
if (*m_dir[i].used == true)
loadTsFileNamesFromDir(m_dir[i].name);
}
TRACE("[mb] Dir%d, Files:%d\n", (int)m_dirNames.size(), (int)m_vMovieInfo.size());
}
static const char * const ext_list[] =
{
"avi", "mkv", "mp4", "flv", "mov", "mpg", "mpeg", "m2ts", "iso"
};
static int ext_list_size = sizeof(ext_list) / sizeof (char *);
bool CMovieBrowser::supportedExtension(CFile &file)
{
std::string::size_type idx = file.getFileName().rfind('.');
if (idx == std::string::npos)
return false;
std::string ext = file.getFileName().substr(idx+1);
bool result = (ext == "ts");
if (!result && !m_settings.ts_only) {
for (int i = 0; i < ext_list_size; i++) {
if (!strcasecmp(ext.c_str(), ext_list[i]))
return true;
}
}
return result;
}
bool CMovieBrowser::addFile(CFile &file, int dirItNr)
{
if (!S_ISDIR(file.Mode) && !supportedExtension(file)) {
//TRACE("[mb] not supported file: '%s'\n", file.Name.c_str());
return false;
}
MI_MOVIE_INFO movieInfo;
movieInfo.file = file;
if(!m_movieInfo.loadMovieInfo(&movieInfo)) {
movieInfo.epgChannel = string(g_Locale->getText(LOCALE_MOVIEPLAYER_HEAD));
movieInfo.epgTitle = file.getFileName();
}
movieInfo.dirItNr = dirItNr;
//TRACE("addFile dir [%s] : [%s]\n", m_dirNames[movieInfo.dirItNr].c_str(), movieInfo.file.Name.c_str());
m_vMovieInfo.push_back(movieInfo);
return true;
}
/************************************************************************
Note: this function is used recursive, do not add any return within the body due to the recursive counter
************************************************************************/
bool CMovieBrowser::loadTsFileNamesFromDir(const std::string & dirname)
{
//TRACE("[mb]->loadTsFileNamesFromDir %s\n",dirname.c_str());
static int recursive_counter = 0; // recursive counter to be used to avoid hanging
bool result = false;
if (recursive_counter > 10)
{
TRACE("[mb]loadTsFileNamesFromDir: return->recoursive error\n");
return (false); // do not go deeper than 10 directories
}
/* check if directory was already searched once */
for (int i = 0; i < (int) m_dirNames.size(); i++)
{
if (strcmp(m_dirNames[i].c_str(),dirname.c_str()) == 0)
{
// string is identical to previous one
TRACE("[mb]Dir already in list: %s\n",dirname.c_str());
return (false);
}
}
/* FIXME hack to fix movie dir path on recursive scan.
dirs without files but with subdirs with files will be shown in path filter */
m_dirNames.push_back(dirname);
int dirItNr = m_dirNames.size() - 1;
/* !!!!!! no return statement within the body after here !!!!*/
recursive_counter++;
CFileList flist;
if (readDir(dirname, &flist) == true)
{
for (unsigned int i = 0; i < flist.size(); i++)
{
if (S_ISDIR(flist[i].Mode)) {
if (m_settings.ts_only || !CFileBrowser::checkBD(flist[i])) {
flist[i].Name += '/';
result |= loadTsFileNamesFromDir(flist[i].Name);
} else
result |= addFile(flist[i], dirItNr);
} else {
result |= addFile(flist[i], dirItNr);
}
}
//result = true;
}
if (!result)
m_dirNames.pop_back();
recursive_counter--;
return (result);
}
bool CMovieBrowser::readDir(const std::string & dirname, CFileList* flist)
{
bool result = true;
//TRACE("readDir_std %s\n",dirname.c_str());
stat_struct statbuf;
dirent_struct **namelist;
int n;
n = my_scandir(dirname.c_str(), &namelist, 0, my_alphasort);
if (n < 0)
{
perror(("[mb] scandir: "+dirname).c_str());
return false;
}
CFile file;
for (int i = 0; i < n;i++)
{
if (namelist[i]->d_name[0] != '.')
{
file.Name = dirname;
file.Name += namelist[i]->d_name;
// printf("file.Name: '%s', getFileName: '%s' getPath: '%s'\n",file.Name.c_str(),file.getFileName().c_str(),file.getPath().c_str());
if (my_stat((file.Name).c_str(),&statbuf) != 0)
fprintf(stderr, "stat '%s' error: %m\n", file.Name.c_str());
else
{
file.Mode = statbuf.st_mode;
file.Time = statbuf.st_mtime;
file.Size = statbuf.st_size;
flist->push_back(file);
}
}
free(namelist[i]);
}
free(namelist);
return(result);
}
bool CMovieBrowser::delFile(CFile& file)
{
bool result = true;
int err = unlink(file.Name.c_str());
TRACE(" delete file: %s\r\n",file.Name.c_str());
if (err)
result = false;
return(result);
}
void CMovieBrowser::updateMovieSelection(void)
{
//TRACE("[mb]->updateMovieSelection %d\n",m_windowFocus);
if (m_vMovieInfo.empty()) return;
bool new_selection = false;
unsigned int old_movie_selection;
if (m_windowFocus == MB_FOCUS_BROWSER)
{
if (m_vHandleBrowserList.empty())
{
// There are no elements in the Filebrowser, clear all handles
m_currentBrowserSelection = 0;
m_movieSelectionHandler = NULL;
new_selection = true;
}
else
{
old_movie_selection = m_currentBrowserSelection;
m_currentBrowserSelection = m_pcBrowser->getSelectedLine();
//TRACE(" sel1:%d\n",m_currentBrowserSelection);
if (m_currentBrowserSelection != old_movie_selection)
new_selection = true;
if (m_currentBrowserSelection < m_vHandleBrowserList.size())
m_movieSelectionHandler = m_vHandleBrowserList[m_currentBrowserSelection];
}
}
else if (m_windowFocus == MB_FOCUS_LAST_PLAY)
{
if (m_vHandlePlayList.empty())
{
// There are no elements in the Filebrowser, clear all handles
m_currentPlaySelection = 0;
m_movieSelectionHandler = NULL;
new_selection = true;
}
else
{
old_movie_selection = m_currentPlaySelection;
m_currentPlaySelection = m_pcLastPlay->getSelectedLine();
//TRACE(" sel2:%d\n",m_currentPlaySelection);
if (m_currentPlaySelection != old_movie_selection)
new_selection = true;
if (m_currentPlaySelection < m_vHandlePlayList.size())
m_movieSelectionHandler = m_vHandlePlayList[m_currentPlaySelection];
}
}
else if (m_windowFocus == MB_FOCUS_LAST_RECORD)
{
if (m_vHandleRecordList.empty())
{
// There are no elements in the Filebrowser, clear all handles
m_currentRecordSelection = 0;
m_movieSelectionHandler = NULL;
new_selection = true;
}
else
{
old_movie_selection = m_currentRecordSelection;
m_currentRecordSelection = m_pcLastRecord->getSelectedLine();
//TRACE(" sel3:%d\n",m_currentRecordSelection);
if (m_currentRecordSelection != old_movie_selection)
new_selection = true;
if (m_currentRecordSelection < m_vHandleRecordList.size())
m_movieSelectionHandler = m_vHandleRecordList[m_currentRecordSelection];
}
}
if (new_selection == true)
{
//TRACE("new\n");
info_hdd_level();
refreshMovieInfo();
refreshLCD();
}
//TRACE("\n");
}
void CMovieBrowser::updateFilterSelection(void)
{
//TRACE("[mb]->updateFilterSelection \n");
if (m_FilterLines.lineArray[0].empty()) return;
bool result = true;
int selected_line = m_pcFilter->getSelectedLine();
if (selected_line > 0)
selected_line--;
if (m_settings.filter.item == MB_INFO_FILEPATH)
{
m_settings.filter.optionString = m_FilterLines.lineArray[0][selected_line+1];
m_settings.filter.optionVar = selected_line;
}
else if (m_settings.filter.item == MB_INFO_INFO1)
{
m_settings.filter.optionString = m_FilterLines.lineArray[0][selected_line+1];
}
else if (m_settings.filter.item == MB_INFO_MAJOR_GENRE)
{
m_settings.filter.optionString = g_Locale->getText(GENRE_ALL[selected_line].value);
m_settings.filter.optionVar = GENRE_ALL[selected_line].key;
}
else if (m_settings.filter.item == MB_INFO_SERIE)
{
m_settings.filter.optionString = m_FilterLines.lineArray[0][selected_line+1];
}
else
{
result = false;
}
if (result == true)
{
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFoot();
}
}
bool CMovieBrowser::addDir(std::string& dirname, int* used)
{
if (dirname.empty()) return false;
if (dirname == "/") return false;
MB_DIR newdir;
newdir.name = dirname;
if (newdir.name.rfind('/') != newdir.name.length()-1 || newdir.name.length() == 0)
newdir.name += '/';
int size = m_dir.size();
for (int i = 0; i < size; i++)
{
if (strcmp(m_dir[i].name.c_str(),newdir.name.c_str()) == 0)
{
// string is identical to previous one
TRACE("[mb] Dir already in list: %s\n",newdir.name.c_str());
return (false);
}
}
TRACE("[mb] new Dir: %s\n",newdir.name.c_str());
newdir.used = used;
m_dir.push_back(newdir);
if (*used == true)
{
m_file_info_stale = true; // we got a new Dir, search again for all movies next time
m_seriename_stale = true;
}
return (true);
}
void CMovieBrowser::loadMovies(bool doRefresh)
{
TRACE("[mb] loadMovies: \n");
CHintBox loadBox((show_mode == MB_SHOW_YT) ? LOCALE_MOVIEPLAYER_YTPLAYBACK : LOCALE_MOVIEBROWSER_HEAD, g_Locale->getText(LOCALE_MOVIEBROWSER_SCAN_FOR_MOVIES));
loadBox.paint();
if (show_mode == MB_SHOW_YT) {
loadYTitles(m_settings.ytmode, m_settings.ytsearch, m_settings.ytvid);
} else {
loadAllTsFileNamesFromStorage(); // P1
m_seriename_stale = true; // we reloded the movie info, so make sure the other list are updated later on as well
updateSerienames();
if (m_settings.serie_auto_create == 1)
autoFindSerie();
}
m_file_info_stale = false;
loadBox.hide();
if (doRefresh)
{
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFilterList();
}
}
void CMovieBrowser::loadAllMovieInfo(void)
{
//TRACE("[mb]->loadAllMovieInfo \n");
for (unsigned int i=0; i < m_vMovieInfo.size();i++)
m_movieInfo.loadMovieInfo(&(m_vMovieInfo[i]));
}
void CMovieBrowser::showHelp(void)
{
CMovieHelp help;
help.exec(NULL,NULL);
}
#define MAX_STRING 30
int CMovieBrowser::showMovieInfoMenu(MI_MOVIE_INFO* movie_info)
{
/********************************************************************/
/** MovieInfo menu ******************************************************/
/********************************************************************/
/** bookmark ******************************************************/
CIntInput bookStartIntInput(LOCALE_MOVIEBROWSER_EDIT_BOOK, (int *)&movie_info->bookmarks.start, 5, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO1, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO2);
CIntInput bookLastIntInput(LOCALE_MOVIEBROWSER_EDIT_BOOK, (int *)&movie_info->bookmarks.lastPlayStop, 5, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO1, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO2);
CIntInput bookEndIntInput(LOCALE_MOVIEBROWSER_EDIT_BOOK, (int *)&movie_info->bookmarks.end, 5, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO1, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO2);
CMenuWidget bookmarkMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
bookmarkMenu.addIntroItems(LOCALE_MOVIEBROWSER_BOOK_HEAD);
bookmarkMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_CLEAR_ALL, true, NULL, this, "book_clear_all",CRCInput::RC_blue));
bookmarkMenu.addItem(GenericMenuSeparatorLine);
bookmarkMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_MOVIESTART, true, bookStartIntInput.getValue(), &bookStartIntInput));
bookmarkMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_MOVIEEND, true, bookEndIntInput.getValue(), &bookLastIntInput));
bookmarkMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_LASTMOVIESTOP, true, bookLastIntInput.getValue(), &bookEndIntInput));
bookmarkMenu.addItem(GenericMenuSeparatorLine);
for (int li =0 ; li < MI_MOVIE_BOOK_USER_MAX && li < MAX_NUMBER_OF_BOOKMARK_ITEMS; li++)
{
CKeyboardInput * pBookNameInput = new CKeyboardInput(LOCALE_MOVIEBROWSER_EDIT_BOOK_NAME_INFO1, &movie_info->bookmarks.user[li].name, 20);
CIntInput *pBookPosIntInput = new CIntInput(LOCALE_MOVIEBROWSER_EDIT_BOOK, (int *)&movie_info->bookmarks.user[li].pos, 20, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO1, LOCALE_MOVIEBROWSER_EDIT_BOOK_POS_INFO2);
CIntInput *pBookTypeIntInput = new CIntInput(LOCALE_MOVIEBROWSER_EDIT_BOOK, (int *)&movie_info->bookmarks.user[li].length, 20, LOCALE_MOVIEBROWSER_EDIT_BOOK_TYPE_INFO1, LOCALE_MOVIEBROWSER_EDIT_BOOK_TYPE_INFO2);
CMenuWidget* pBookItemMenu = new CMenuWidget(LOCALE_MOVIEBROWSER_BOOK_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
pBookItemMenu->addItem(GenericMenuSeparator);
pBookItemMenu->addItem(new CMenuDForwarder(LOCALE_MOVIEBROWSER_BOOK_NAME, true, movie_info->bookmarks.user[li].name, pBookNameInput));
pBookItemMenu->addItem(new CMenuDForwarder(LOCALE_MOVIEBROWSER_BOOK_POSITION, true, pBookPosIntInput->getValue(), pBookPosIntInput));
pBookItemMenu->addItem(new CMenuDForwarder(LOCALE_MOVIEBROWSER_BOOK_TYPE, true, pBookTypeIntInput->getValue(), pBookTypeIntInput));
bookmarkMenu.addItem(new CMenuDForwarder(movie_info->bookmarks.user[li].name.c_str(), true, pBookPosIntInput->getValue(), pBookItemMenu));
}
/********************************************************************/
/** serie******************************************************/
CKeyboardInput serieUserInput(LOCALE_MOVIEBROWSER_EDIT_SERIE, &movie_info->serieName, 20);
CMenuWidget serieMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
serieMenu.addIntroItems(LOCALE_MOVIEBROWSER_SERIE_HEAD);
serieMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_SERIE_NAME, true, movie_info->serieName,&serieUserInput));
serieMenu.addItem(GenericMenuSeparatorLine);
for (unsigned int li = 0; li < m_vHandleSerienames.size(); li++)
serieMenu.addItem(new CMenuSelector(m_vHandleSerienames[li]->serieName.c_str(), true, movie_info->serieName));
/********************************************************************/
/** update movie info ******************************************************/
for (unsigned int i = 0; i < MB_INFO_MAX_NUMBER; i++)
movieInfoUpdateAll[i] = 0;
movieInfoUpdateAllIfDestEmptyOnly = true;
CMenuWidget movieInfoMenuUpdate(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
movieInfoMenuUpdate.addIntroItems(LOCALE_MOVIEBROWSER_INFO_HEAD_UPDATE);
movieInfoMenuUpdate.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_SAVE_ALL, true, NULL, this, "save_movie_info_all",CRCInput::RC_red));
movieInfoMenuUpdate.addItem(GenericMenuSeparatorLine);
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_UPDATE_IF_DEST_EMPTY_ONLY, (&movieInfoUpdateAllIfDestEmptyOnly), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL,CRCInput::RC_blue));
movieInfoMenuUpdate.addItem(GenericMenuSeparatorLine);
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_TITLE, &movieInfoUpdateAll[MB_INFO_TITLE], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true, NULL, CRCInput::RC_1));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_INFO1, &movieInfoUpdateAll[MB_INFO_INFO1], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true, NULL, CRCInput::RC_2));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_SERIE, &movieInfoUpdateAll[MB_INFO_SERIE], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true, NULL, CRCInput::RC_3));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_QUALITY, &movieInfoUpdateAll[MB_INFO_QUALITY], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true, NULL, CRCInput::RC_4));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE, &movieInfoUpdateAll[MB_INFO_PARENTAL_LOCKAGE], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL, CRCInput::RC_5));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_GENRE_MAJOR, &movieInfoUpdateAll[MB_INFO_MAJOR_GENRE], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL, CRCInput::RC_6));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_PRODYEAR, &movieInfoUpdateAll[MB_INFO_PRODDATE], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL, CRCInput::RC_7));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_PRODCOUNTRY, &movieInfoUpdateAll[MB_INFO_COUNTRY], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL, CRCInput::RC_8));
movieInfoMenuUpdate.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_LENGTH, &movieInfoUpdateAll[MB_INFO_LENGTH], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,NULL, CRCInput::RC_9));
/********************************************************************/
/** movieInfo ******************************************************/
#define BUFFER_SIZE 100
char dirItNr[BUFFER_SIZE];
char size[BUFFER_SIZE];
strncpy(dirItNr, m_dirNames[movie_info->dirItNr].c_str(),BUFFER_SIZE-1);
snprintf(size,BUFFER_SIZE,"%5" PRIu64 "",movie_info->file.Size>>20);
CKeyboardInput titelUserInput(LOCALE_MOVIEBROWSER_INFO_TITLE, &movie_info->epgTitle, (movie_info->epgTitle.empty() || (movie_info->epgTitle.size() < MAX_STRING)) ? MAX_STRING:movie_info->epgTitle.size());
CKeyboardInput channelUserInput(LOCALE_MOVIEBROWSER_INFO_CHANNEL, &movie_info->epgChannel, MAX_STRING);
CKeyboardInput epgUserInput(LOCALE_MOVIEBROWSER_INFO_INFO1, &movie_info->epgInfo1, 20);
CKeyboardInput countryUserInput(LOCALE_MOVIEBROWSER_INFO_PRODCOUNTRY, &movie_info->productionCountry, 11);
CDateInput dateUserDateInput(LOCALE_MOVIEBROWSER_INFO_LENGTH, &movie_info->dateOfLastPlay, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CDateInput recUserDateInput(LOCALE_MOVIEBROWSER_INFO_LENGTH, &movie_info->file.Time, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CIntInput lengthUserIntInput(LOCALE_MOVIEBROWSER_INFO_LENGTH, (int *)&movie_info->length, 3, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CIntInput yearUserIntInput(LOCALE_MOVIEBROWSER_INFO_PRODYEAR, (int *)&movie_info->productionDate, 4, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CMenuWidget movieInfoMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
movieInfoMenu.addIntroItems(LOCALE_MOVIEBROWSER_INFO_HEAD);
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_SAVE, true, NULL, this, "save_movie_info", CRCInput::RC_red));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_HEAD_UPDATE, true, NULL, &movieInfoMenuUpdate, NULL, CRCInput::RC_green));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_HEAD, true, NULL, &bookmarkMenu, NULL, CRCInput::RC_blue));
movieInfoMenu.addItem(GenericMenuSeparatorLine);
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_TITLE, true, movie_info->epgTitle, &titelUserInput,NULL, CRCInput::RC_1));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_SERIE, true, movie_info->serieName, &serieMenu,NULL, CRCInput::RC_2));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_INFO1, (movie_info->epgInfo1.size() <= MAX_STRING) /*true*/, movie_info->epgInfo1, &epgUserInput,NULL, CRCInput::RC_3));
movieInfoMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_GENRE_MAJOR, &movie_info->genreMajor, GENRE_ALL, GENRE_ALL_COUNT, true,NULL, CRCInput::RC_4, "", true));
movieInfoMenu.addItem(GenericMenuSeparatorLine);
movieInfoMenu.addItem(new CMenuOptionNumberChooser(LOCALE_MOVIEBROWSER_INFO_QUALITY,&movie_info->quality,true,0,3, NULL));
movieInfoMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_INFO_PARENTAL_LOCKAGE, &movie_info->parentalLockAge, MESSAGEBOX_PARENTAL_LOCKAGE_OPTIONS, MESSAGEBOX_PARENTAL_LOCKAGE_OPTION_COUNT, true,NULL, CRCInput::RC_6));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_PRODYEAR, true, yearUserIntInput.getValue(), &yearUserIntInput,NULL, CRCInput::RC_7));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_PRODCOUNTRY, true, movie_info->productionCountry, &countryUserInput,NULL, CRCInput::RC_8));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_LENGTH, true, lengthUserIntInput.getValue(), &lengthUserIntInput,NULL, CRCInput::RC_9));
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_CHANNEL, true, movie_info->epgChannel, &channelUserInput,NULL, CRCInput::RC_0));//LOCALE_TIMERLIST_CHANNEL
movieInfoMenu.addItem(GenericMenuSeparatorLine);
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_PATH, false, dirItNr)); //LOCALE_TIMERLIST_RECORDING_DIR
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_PREVPLAYDATE, false, dateUserDateInput.getValue()));//LOCALE_FLASHUPDATE_CURRENTVERSIONDATE
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_RECORDDATE, false, recUserDateInput.getValue()));//LOCALE_FLASHUPDATE_CURRENTVERSIONDATE
movieInfoMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_SIZE, false, size, NULL));
int res = movieInfoMenu.exec(NULL,"");
return res;
}
bool CMovieBrowser::showMenu(bool calledExternally)
{
/* first clear screen */
framebuffer->paintBackground();
int i;
/********************************************************************/
/** directory menu ******************************************************/
CDirMenu dirMenu(&m_dir);
/********************************************************************/
/** options menu **************************************************/
/********************************************************************/
/** parental lock **************************************************/
CMenuWidget parentalMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
parentalMenu.addIntroItems(LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_HEAD);
parentalMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_ACTIVATED, (int*)(&m_parentalLock), MESSAGEBOX_PARENTAL_LOCK_OPTIONS, MESSAGEBOX_PARENTAL_LOCK_OPTIONS_COUNT, true));
parentalMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_RATE_HEAD, (int*)(&m_settings.parentalLockAge), MESSAGEBOX_PARENTAL_LOCKAGE_OPTIONS, MESSAGEBOX_PARENTAL_LOCKAGE_OPTION_COUNT, true));
/********************************************************************/
/** optionsVerzeichnisse **************************************************/
CMenuWidget optionsMenuDir(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
optionsMenuDir.addIntroItems(LOCALE_MOVIEBROWSER_MENU_DIRECTORIES_HEAD);
optionsMenuDir.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_USE_REC_DIR, (int*)(&m_settings.storageDirRecUsed), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
optionsMenuDir.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_DIR, false, g_settings.network_nfs_recordingdir));
optionsMenuDir.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_USE_MOVIE_DIR, (int*)(&m_settings.storageDirMovieUsed), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
optionsMenuDir.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_DIR, false, g_settings.network_nfs_moviedir));
optionsMenuDir.addItem(new CMenuSeparator(CMenuSeparator::LINE | CMenuSeparator::STRING, LOCALE_MOVIEBROWSER_DIR_HEAD));
COnOffNotifier* notifier[MB_MAX_DIRS];
for (i = 0; i < MB_MAX_DIRS ; i++)
{
CFileChooser *dirInput = new CFileChooser(&m_settings.storageDir[i]);
CMenuForwarder *forwarder = new CMenuDForwarder(LOCALE_MOVIEBROWSER_DIR, m_settings.storageDirUsed[i], m_settings.storageDir[i], dirInput);
notifier[i] = new COnOffNotifier();
notifier[i]->addItem(forwarder);
CMenuOptionChooser *chooser = new CMenuOptionChooser(LOCALE_MOVIEBROWSER_USE_DIR, &m_settings.storageDirUsed[i], MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true,notifier[i]);
optionsMenuDir.addItem(chooser);
optionsMenuDir.addItem(forwarder);
if (i != (MB_MAX_DIRS - 1))
optionsMenuDir.addItem(GenericMenuSeparator);
}
/********************************************************************/
/** optionsMenuBrowser **************************************************/
int oldRowNr = m_settings.browserRowNr;
int oldFrameHeight = m_settings.browserFrameHeight;
CIntInput playMaxUserIntInput(LOCALE_MOVIEBROWSER_LAST_PLAY_MAX_ITEMS, (int *)&m_settings.lastPlayMaxItems, 3, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CIntInput recMaxUserIntInput(LOCALE_MOVIEBROWSER_LAST_RECORD_MAX_ITEMS, (int *)&m_settings.lastRecordMaxItems, 3, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CIntInput browserFrameUserIntInput(LOCALE_MOVIEBROWSER_BROWSER_FRAME_HIGH, (int *)&m_settings.browserFrameHeight, 3, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CIntInput browserRowNrIntInput(LOCALE_MOVIEBROWSER_BROWSER_ROW_NR, (int *)&m_settings.browserRowNr, 1, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
CMenuWidget optionsMenuBrowser(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
optionsMenuBrowser.addIntroItems(LOCALE_MOVIEBROWSER_OPTION_BROWSER);
optionsMenuBrowser.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_LAST_PLAY_MAX_ITEMS, true, playMaxUserIntInput.getValue(), &playMaxUserIntInput));
optionsMenuBrowser.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_LAST_RECORD_MAX_ITEMS, true, recMaxUserIntInput.getValue(), &recMaxUserIntInput));
optionsMenuBrowser.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BROWSER_FRAME_HIGH, true, browserFrameUserIntInput.getValue(), &browserFrameUserIntInput));
optionsMenuBrowser.addItem(new CMenuSeparator(CMenuSeparator::LINE | CMenuSeparator::STRING, LOCALE_MOVIEBROWSER_BROWSER_ROW_HEAD));
optionsMenuBrowser.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BROWSER_ROW_NR, true, browserRowNrIntInput.getValue(), &browserRowNrIntInput));
optionsMenuBrowser.addItem(GenericMenuSeparator);
for (i = 0; i < MB_MAX_ROWS; i++)
{
CIntInput* browserRowWidthIntInput = new CIntInput(LOCALE_MOVIEBROWSER_BROWSER_ROW_WIDTH,(int *)&m_settings.browserRowWidth[i], 3, NONEXISTANT_LOCALE, NONEXISTANT_LOCALE);
optionsMenuBrowser.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_BROWSER_ROW_ITEM, (int*)(&m_settings.browserRowItem[i]), MESSAGEBOX_BROWSER_ROW_ITEM, MESSAGEBOX_BROWSER_ROW_ITEM_COUNT, true, NULL, CRCInput::convertDigitToKey(i+1), NULL, true, true));
optionsMenuBrowser.addItem(new CMenuDForwarder(LOCALE_MOVIEBROWSER_BROWSER_ROW_WIDTH, true, browserRowWidthIntInput->getValue(), browserRowWidthIntInput));
if (i < MB_MAX_ROWS-1)
optionsMenuBrowser.addItem(GenericMenuSeparator);
}
/********************************************************************/
/** options **************************************************/
CMenuWidget optionsMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
optionsMenu.addIntroItems(LOCALE_EPGPLUS_OPTIONS);
optionsMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_LOAD_DEFAULT, true, NULL, this, "loaddefault", CRCInput::RC_blue));
optionsMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_OPTION_BROWSER, true, NULL, &optionsMenuBrowser,NULL, CRCInput::RC_green));
optionsMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_DIRECTORIES_HEAD, true, NULL, &optionsMenuDir,NULL, CRCInput::RC_yellow));
if (m_parentalLock != MB_PARENTAL_LOCK_OFF)
optionsMenu.addItem(new CLockedMenuForwarder(LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_HEAD, g_settings.parentallock_pincode, true, true, NULL, &parentalMenu,NULL,CRCInput::RC_red));
else
optionsMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_PARENTAL_LOCK_HEAD, true, NULL, &parentalMenu,NULL,CRCInput::RC_red));
optionsMenu.addItem(GenericMenuSeparatorLine);
optionsMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_RELOAD_AT_START, (int*)(&m_settings.reload), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
optionsMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_REMOUNT_AT_START, (int*)(&m_settings.remount), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
optionsMenu.addItem(GenericMenuSeparatorLine);
optionsMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_HIDE_SERIES, (int*)(&m_settings.browser_serie_mode), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
optionsMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_SERIE_AUTO_CREATE, (int*)(&m_settings.serie_auto_create), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true));
int ts_only = m_settings.ts_only;
optionsMenu.addItem( new CMenuOptionChooser(LOCALE_MOVIEBROWSER_TS_ONLY, (int*)(&m_settings.ts_only), MESSAGEBOX_YES_NO_OPTIONS, MESSAGEBOX_YES_NO_OPTIONS_COUNT, true ));
//optionsMenu.addItem(GenericMenuSeparator);
/********************************************************************/
/** main menu ******************************************************/
CMovieHelp* movieHelp = new CMovieHelp();
CNFSSmallMenu* nfs = new CNFSSmallMenu();
if (!calledExternally) {
CMenuWidget mainMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
mainMenu.addIntroItems(LOCALE_MOVIEBROWSER_MENU_MAIN_HEAD);
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_INFO_HEAD, (m_movieSelectionHandler != NULL), NULL, this, "show_movie_info_menu", CRCInput::RC_red));
mainMenu.addItem(GenericMenuSeparatorLine);
mainMenu.addItem(new CMenuForwarder(LOCALE_EPGPLUS_OPTIONS, true, NULL, &optionsMenu,NULL, CRCInput::RC_green));
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_DIRECTORIES_HEAD, true, NULL, &dirMenu, NULL, CRCInput::RC_yellow));
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_SCAN_FOR_MOVIES, true, NULL, this, "reload_movie_info", CRCInput::RC_blue));
//mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_NFS_HEAD, true, NULL, nfs, NULL, CRCInput::RC_setup));
mainMenu.addItem(GenericMenuSeparatorLine);
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_MENU_HELP_HEAD, true, NULL, movieHelp, NULL, CRCInput::RC_help));
//mainMenu.addItem(GenericMenuSeparator);
mainMenu.exec(NULL, " ");
} else
optionsMenu.exec(NULL, "");
// post menu handling
if (m_parentalLock != MB_PARENTAL_LOCK_OFF_TMP)
m_settings.parentalLock = m_parentalLock;
if (m_settings.browserFrameHeight < MIN_BROWSER_FRAME_HEIGHT)
m_settings.browserFrameHeight = MIN_BROWSER_FRAME_HEIGHT;
if (m_settings.browserFrameHeight > MAX_BROWSER_FRAME_HEIGHT)
m_settings.browserFrameHeight = MAX_BROWSER_FRAME_HEIGHT;
if (m_settings.browserRowNr > MB_MAX_ROWS)
m_settings.browserRowNr = MB_MAX_ROWS;
if (m_settings.browserRowNr < 1)
m_settings.browserRowNr = 1;
for (i = 0; i < m_settings.browserRowNr; i++)
{
if (m_settings.browserRowWidth[i] > 100)
m_settings.browserRowWidth[i] = 100;
if (m_settings.browserRowWidth[i] < 1)
m_settings.browserRowWidth[i] = 1;
}
if (!calledExternally) {
if (ts_only != m_settings.ts_only || dirMenu.isChanged())
loadMovies(false);
if (oldRowNr != m_settings.browserRowNr || oldFrameHeight != m_settings.browserFrameHeight) {
initFrames();
hide();
paint();
} else {
updateSerienames();
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFilterList();
refreshMovieInfo();
refreshTitle();
refreshFoot();
refreshLCD();
}
/* FIXME: refreshXXXList -> setLines -> CListFrame::refresh, too */
//refresh();
} else
saveSettings(&m_settings);
for (i = 0; i < MB_MAX_DIRS; i++)
delete notifier[i];
delete movieHelp;
delete nfs;
return(true);
}
int CMovieBrowser::showStartPosSelectionMenu(void) // P2
{
const char *unit_short_minute = g_Locale->getText(LOCALE_UNIT_SHORT_MINUTE);
//TRACE("[mb]->showStartPosSelectionMenu\n");
int pos = -1;
int result = 0;
int menu_nr= 0;
int position[MAX_NUMBER_OF_BOOKMARK_ITEMS] ={0};
if (m_movieSelectionHandler == NULL) return(result);
char start_pos[32]; snprintf(start_pos, sizeof(start_pos), "%3d %s",m_movieSelectionHandler->bookmarks.start/60, unit_short_minute);
char play_pos[32]; snprintf(play_pos, sizeof(play_pos), "%3d %s",m_movieSelectionHandler->bookmarks.lastPlayStop/60, unit_short_minute);
char book[MI_MOVIE_BOOK_USER_MAX][32];
CMenuWidgetSelection startPosSelectionMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
startPosSelectionMenu.enableFade(false);
startPosSelectionMenu.addIntroItems(LOCALE_MOVIEBROWSER_START_HEAD, NONEXISTANT_LOCALE, CMenuWidget::BTN_TYPE_CANCEL);
int off = startPosSelectionMenu.getItemsCount();
bool got_start_pos = false;
if (m_movieSelectionHandler->bookmarks.start != 0)
{
got_start_pos = true;
startPosSelectionMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_MOVIESTART, true, start_pos), true);
position[menu_nr++] = m_movieSelectionHandler->bookmarks.start;
}
if (m_movieSelectionHandler->bookmarks.lastPlayStop != 0)
{
startPosSelectionMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_BOOK_LASTMOVIESTOP, true, play_pos));
position[menu_nr++] = m_movieSelectionHandler->bookmarks.lastPlayStop;
}
startPosSelectionMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_START_RECORD_START, true,NULL), got_start_pos ? false : true);
position[menu_nr++] = 0;
for (int i = 0; i < MI_MOVIE_BOOK_USER_MAX && menu_nr < MAX_NUMBER_OF_BOOKMARK_ITEMS; i++)
{
if (m_movieSelectionHandler->bookmarks.user[i].pos != 0)
{
if (m_movieSelectionHandler->bookmarks.user[i].length >= 0)
position[menu_nr] = m_movieSelectionHandler->bookmarks.user[i].pos;
else
position[menu_nr] = m_movieSelectionHandler->bookmarks.user[i].pos + m_movieSelectionHandler->bookmarks.user[i].length;
snprintf(book[i], sizeof(book[i]),"%5d %s",position[menu_nr]/60, unit_short_minute);
startPosSelectionMenu.addItem(new CMenuForwarder(m_movieSelectionHandler->bookmarks.user[i].name.c_str(), true, book[i]));
menu_nr++;
}
}
startPosSelectionMenu.exec(NULL, "12345");
/* check what menu item was ok'd and set the appropriate play offset*/
result = startPosSelectionMenu.getSelectedLine();
result -= off; // sub-text, separator, back, separator-line
if (result >= 0 && result <= MAX_NUMBER_OF_BOOKMARK_ITEMS)
pos = position[result];
TRACE("[mb] selected bookmark %d position %d \n", result, pos);
return(pos) ;
}
bool CMovieBrowser::isParentalLock(MI_MOVIE_INFO& movie_info)
{
bool result = false;
if (m_parentalLock == MB_PARENTAL_LOCK_ACTIVE && m_settings.parentalLockAge <= movie_info.parentalLockAge)
result = true;
return (result);
}
bool CMovieBrowser::isFiltered(MI_MOVIE_INFO& movie_info)
{
bool result = true;
switch(m_settings.filter.item)
{
case MB_INFO_FILEPATH:
if (m_settings.filter.optionVar == movie_info.dirItNr)
result = false;
break;
case MB_INFO_INFO1:
if (strcmp(m_settings.filter.optionString.c_str(),movie_info.epgInfo1.c_str()) == 0)
result = false;
break;
case MB_INFO_MAJOR_GENRE:
if (m_settings.filter.optionVar == movie_info.genreMajor)
result = false;
break;
case MB_INFO_SERIE:
if (strcmp(m_settings.filter.optionString.c_str(),movie_info.serieName.c_str()) == 0)
result = false;
break;
break;
default:
result = false;
break;
}
return (result);
}
bool CMovieBrowser::getMovieInfoItem(MI_MOVIE_INFO& movie_info, MB_INFO_ITEM item, std::string* item_string)
{
#define MAX_STR_TMP 100
char str_tmp[MAX_STR_TMP];
bool result = true;
*item_string="";
tm* tm_tmp;
int i=0;
int counter=0;
switch(item)
{
case MB_INFO_FILENAME: // = 0,
*item_string = movie_info.file.getFileName();
break;
case MB_INFO_FILEPATH: // = 1,
if (!m_dirNames.empty())
*item_string = m_dirNames[movie_info.dirItNr];
break;
case MB_INFO_TITLE: // = 2,
*item_string = movie_info.epgTitle;
if (strcmp("not available",movie_info.epgTitle.c_str()) == 0)
result = false;
if (movie_info.epgTitle.empty())
result = false;
break;
case MB_INFO_SERIE: // = 3,
*item_string = movie_info.serieName;
break;
case MB_INFO_INFO1: // = 4,
*item_string = movie_info.epgInfo1;
break;
case MB_INFO_MAJOR_GENRE: // = 5,
snprintf(str_tmp, sizeof(str_tmp),"%2d",movie_info.genreMajor);
*item_string = str_tmp;
break;
case MB_INFO_MINOR_GENRE: // = 6,
snprintf(str_tmp, sizeof(str_tmp),"%2d",movie_info.genreMinor);
*item_string = str_tmp;
break;
case MB_INFO_INFO2: // = 7,
*item_string = movie_info.epgInfo2;
break;
case MB_INFO_PARENTAL_LOCKAGE: // = 8,
snprintf(str_tmp, sizeof(str_tmp),"%2d",movie_info.parentalLockAge);
*item_string = str_tmp;
break;
case MB_INFO_CHANNEL: // = 9,
*item_string = movie_info.epgChannel;
break;
case MB_INFO_BOOKMARK: // = 10,
// we just return the number of bookmarks
for (i = 0; i < MI_MOVIE_BOOK_USER_MAX; i++)
{
if (movie_info.bookmarks.user[i].pos != 0)
counter++;
}
*item_string = to_string(counter);
break;
case MB_INFO_QUALITY: // = 11,
snprintf(str_tmp, sizeof(str_tmp),"%d",movie_info.quality);
*item_string = str_tmp;
break;
case MB_INFO_PREVPLAYDATE: // = 12,
tm_tmp = localtime(&movie_info.dateOfLastPlay);
snprintf(str_tmp, sizeof(str_tmp),"%02d.%02d.%02d",tm_tmp->tm_mday,(tm_tmp->tm_mon)+ 1, tm_tmp->tm_year >= 100 ? tm_tmp->tm_year-100 : tm_tmp->tm_year);
*item_string = str_tmp;
break;
case MB_INFO_RECORDDATE: // = 13,
if (show_mode == MB_SHOW_YT) {
*item_string = movie_info.ytdate;
} else {
tm_tmp = localtime(&movie_info.file.Time);
snprintf(str_tmp, sizeof(str_tmp),"%02d.%02d.%02d",tm_tmp->tm_mday,(tm_tmp->tm_mon) + 1,tm_tmp->tm_year >= 100 ? tm_tmp->tm_year-100 : tm_tmp->tm_year);
*item_string = str_tmp;
}
break;
case MB_INFO_PRODDATE: // = 14,
snprintf(str_tmp, sizeof(str_tmp),"%d",movie_info.productionDate);
*item_string = str_tmp;
break;
case MB_INFO_COUNTRY: // = 15,
*item_string = movie_info.productionCountry;
break;
case MB_INFO_GEOMETRIE: // = 16,
result = false;
break;
case MB_INFO_AUDIO: // = 17,
// we just return the number of audiopids
snprintf(str_tmp, sizeof(str_tmp), "%d", (int)movie_info.audioPids.size());
*item_string = str_tmp;
break;
case MB_INFO_LENGTH: // = 18,
snprintf(str_tmp, sizeof(str_tmp),"%dh %dm", movie_info.length/60, movie_info.length%60);
*item_string = str_tmp;
break;
case MB_INFO_SIZE: // = 19,
snprintf(str_tmp, sizeof(str_tmp),"%4" PRIu64 "",movie_info.file.Size>>20);
*item_string = str_tmp;
break;
case MB_INFO_MAX_NUMBER: // = 20
default:
*item_string="";
result = false;
break;
}
//TRACE(" getMovieInfoItem: %d,>%s<",item,*item_string.c_str());
return(result);
}
void CMovieBrowser::updateSerienames(void)
{
if (m_seriename_stale == false)
return;
m_vHandleSerienames.clear();
for (unsigned int i = 0; i < m_vMovieInfo.size(); i++)
{
if (!m_vMovieInfo[i].serieName.empty())
{
// current series name is not empty, lets see if we already have it in the list, and if not save it to the list.
bool found = false;
for (unsigned int t = 0; t < m_vHandleSerienames.size() && found == false; t++)
{
if (strcmp(m_vHandleSerienames[t]->serieName.c_str(),m_vMovieInfo[i].serieName.c_str()) == 0)
found = true;
}
if (found == false)
m_vHandleSerienames.push_back(&m_vMovieInfo[i]);
}
}
TRACE("[mb]->updateSerienames: %d\n", (int)m_vHandleSerienames.size());
// TODO sort(m_serienames.begin(), m_serienames.end(), my_alphasort);
m_seriename_stale = false;
}
void CMovieBrowser::autoFindSerie(void)
{
TRACE("autoFindSerie\n");
updateSerienames(); // we have to make sure that the seriename array is up to date, otherwise this does not work
// if the array is not stale, the function is left immediately
for (unsigned int i = 0; i < m_vMovieInfo.size(); i++)
{
// For all movie infos, which do not have a seriename, we try to find one.
// We search for a movieinfo with seriename, and than we do check if the title is the same
// in case of same title, we assume both belongs to the same serie
//TRACE("%s ",m_vMovieInfo[i].serieName);
if (m_vMovieInfo[i].serieName.empty())
{
for (unsigned int t=0; t < m_vHandleSerienames.size();t++)
{
//TRACE("%s ",m_vHandleSerienames[i].serieName);
if (m_vMovieInfo[i].epgTitle == m_vHandleSerienames[t]->epgTitle)
{
//TRACE("x");
m_vMovieInfo[i].serieName = m_vHandleSerienames[t]->serieName;
break; // we found a maching serie, nothing to do else, leave for(t=0)
}
}
//TRACE("\n");
}
}
}
void CMovieBrowser::loadYTitles(int mode, std::string search, std::string id)
{
printf("CMovieBrowser::loadYTitles: parsed %d old mode %d new mode %d region %s\n", ytparser.Parsed(), ytparser.GetFeedMode(), m_settings.ytmode, m_settings.ytregion.c_str());
if (m_settings.ytregion == "default")
ytparser.SetRegion("");
else
ytparser.SetRegion(m_settings.ytregion);
ytparser.SetMaxResults(m_settings.ytresults);
ytparser.SetConcurrentDownloads(m_settings.ytconcconn);
ytparser.SetThumbnailDir(m_settings.ytthumbnaildir);
if (!ytparser.Parsed() || (ytparser.GetFeedMode() != mode)) {
if (ytparser.ParseFeed((cYTFeedParser::yt_feed_mode_t)mode, search, id, (cYTFeedParser::yt_feed_orderby_t)m_settings.ytorderby)) {
ytparser.DownloadThumbnails();
} else {
//FIXME show error
DisplayErrorMessage(g_Locale->getText(LOCALE_MOVIEBROWSER_YT_ERROR));
return;
}
}
m_vMovieInfo.clear();
yt_video_list_t &ylist = ytparser.GetVideoList();
for (unsigned i = 0; i < ylist.size(); i++) {
MI_MOVIE_INFO movieInfo;
movieInfo.epgChannel = ylist[i].author;
movieInfo.epgTitle = ylist[i].title;
movieInfo.epgInfo1 = ylist[i].category;
movieInfo.epgInfo2 = ylist[i].description;
movieInfo.length = ylist[i].duration/60 ;
movieInfo.tfile = ylist[i].tfile;
movieInfo.ytdate = ylist[i].published;
movieInfo.ytid = ylist[i].id;
movieInfo.file.Name = ylist[i].title;
movieInfo.ytitag = m_settings.ytquality;
movieInfo.file.Url = ylist[i].GetUrl(&movieInfo.ytitag, false);
movieInfo.file.Time = toEpoch(movieInfo.ytdate);
m_vMovieInfo.push_back(movieInfo);
}
m_currentBrowserSelection = 0;
m_currentRecordSelection = 0;
m_currentPlaySelection = 0;
m_pcBrowser->setSelectedLine(m_currentBrowserSelection);
m_pcLastRecord->setSelectedLine(m_currentRecordSelection);
m_pcLastPlay->setSelectedLine(m_currentPlaySelection);
}
const CMenuOptionChooser::keyval YT_FEED_OPTIONS[] =
{
{ cYTFeedParser::MOST_POPULAR_ALL_TIME, LOCALE_MOVIEBROWSER_YT_MOST_POPULAR_ALL_TIME },
{ cYTFeedParser::MOST_POPULAR, LOCALE_MOVIEBROWSER_YT_MOST_POPULAR }
};
#define YT_FEED_OPTION_COUNT (sizeof(YT_FEED_OPTIONS)/sizeof(CMenuOptionChooser::keyval))
const CMenuOptionChooser::keyval YT_ORDERBY_OPTIONS[] =
{
{ cYTFeedParser::ORDERBY_PUBLISHED, LOCALE_MOVIEBROWSER_YT_ORDERBY_PUBLISHED },
{ cYTFeedParser::ORDERBY_RELEVANCE, LOCALE_MOVIEBROWSER_YT_ORDERBY_RELEVANCE },
{ cYTFeedParser::ORDERBY_VIEWCOUNT, LOCALE_MOVIEBROWSER_YT_ORDERBY_VIEWCOUNT },
{ cYTFeedParser::ORDERBY_RATING, LOCALE_MOVIEBROWSER_YT_ORDERBY_RATING }
};
#define YT_ORDERBY_OPTION_COUNT (sizeof(YT_ORDERBY_OPTIONS)/sizeof(CMenuOptionChooser::keyval))
neutrino_locale_t CMovieBrowser::getFeedLocale(void)
{
neutrino_locale_t ret = LOCALE_MOVIEBROWSER_YT_MOST_POPULAR;
if (m_settings.ytmode == cYTFeedParser::RELATED)
return LOCALE_MOVIEBROWSER_YT_RELATED;
if (m_settings.ytmode == cYTFeedParser::SEARCH)
return LOCALE_MOVIEBROWSER_YT_SEARCH;
for (unsigned i = 0; i < YT_FEED_OPTION_COUNT; i++) {
if (m_settings.ytmode == YT_FEED_OPTIONS[i].key)
return YT_FEED_OPTIONS[i].value;
}
return ret;
}
int CYTCacheSelectorTarget::exec(CMenuTarget* /*parent*/, const std::string & actionKey)
{
MI_MOVIE_INFO::miSource source = (movieBrowser->show_mode == MB_SHOW_YT) ? MI_MOVIE_INFO::YT : MI_MOVIE_INFO::NK;
int selected = movieBrowser->yt_menue->getSelected();
if (actionKey == "cancel_all") {
cYTCache::getInstance()->cancelAll(source);
} else if (actionKey == "completed_clear") {
cYTCache::getInstance()->clearCompleted(source);
} else if (actionKey == "failed_clear") {
cYTCache::getInstance()->clearFailed(source);
} else if (actionKey == "rc_spkr" && movieBrowser->yt_pending_offset && selected >= movieBrowser->yt_pending_offset && selected < movieBrowser->yt_pending_end) {
cYTCache::getInstance()->cancel(&movieBrowser->yt_pending[selected - movieBrowser->yt_pending_offset]);
} else if (actionKey == "rc_spkr" && movieBrowser->yt_completed_offset && selected >= movieBrowser->yt_completed_offset && selected < movieBrowser->yt_completed_end) {
cYTCache::getInstance()->remove(&movieBrowser->yt_completed[selected - movieBrowser->yt_completed_offset]);
} else if (actionKey.empty()) {
if (movieBrowser->yt_pending_offset && selected >= movieBrowser->yt_pending_offset && selected < movieBrowser->yt_pending_end) {
if (ShowMsg (LOCALE_MOVIEBROWSER_YT_CACHE, g_Locale->getText(LOCALE_MOVIEBROWSER_YT_CANCEL_TRANSFER), CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo) == CMessageBox::mbrYes)
cYTCache::getInstance()->cancel(&movieBrowser->yt_pending[selected - movieBrowser->yt_pending_offset]);
else
return menu_return::RETURN_NONE;
} else if (movieBrowser->yt_completed_offset && selected >= movieBrowser->yt_completed_offset && selected < movieBrowser->yt_completed_end) {
// FIXME -- anything sensible to do here?
return menu_return::RETURN_NONE;
} else if (movieBrowser->yt_failed_offset && selected >= movieBrowser->yt_failed_offset && selected < movieBrowser->yt_failed_end){
cYTCache::getInstance()->clearFailed(&movieBrowser->yt_failed[selected - movieBrowser->yt_failed_offset]);
cYTCache::getInstance()->addToCache(&movieBrowser->yt_failed[selected - movieBrowser->yt_failed_offset]);
const char *format = g_Locale->getText(LOCALE_MOVIEBROWSER_YT_CACHE_ADD);
char buf[1024];
snprintf(buf, sizeof(buf), format, movieBrowser->yt_failed[selected - movieBrowser->yt_failed_offset].file.Name.c_str());
CHintBox hintBox(LOCALE_MOVIEBROWSER_YT_CACHE, buf);
hintBox.paint();
sleep(1);
hintBox.hide();
}
} else
return menu_return::RETURN_NONE;
movieBrowser->refreshYTMenu();
return menu_return::RETURN_REPAINT;
}
void CMovieBrowser::refreshYTMenu()
{
for (u_int item_id = (u_int) yt_menue->getItemsCount() - 1; item_id > yt_menue_end - 1; item_id--) {
CMenuItem* m = yt_menue->getItem(item_id);
if (m && !m->isStatic)
delete m;
yt_menue->removeItem(item_id);
}
MI_MOVIE_INFO::miSource source = (show_mode == MB_SHOW_YT) ? MI_MOVIE_INFO::YT : MI_MOVIE_INFO::NK;
double dltotal, dlnow;
time_t dlstart;
yt_pending = cYTCache::getInstance()->getPending(source, &dltotal, &dlnow, &dlstart);
yt_completed = cYTCache::getInstance()->getCompleted(source);
yt_failed = cYTCache::getInstance()->getFailed(source);
yt_pending_offset = 0;
yt_completed_offset = 0;
yt_failed_offset = 0;
yt_pending_end = 0;
yt_completed_end = 0;
yt_failed_end = 0;
if (!yt_pending.empty()) {
yt_menue->addItem(new CMenuSeparator(CMenuSeparator::LINE | CMenuSeparator::STRING, LOCALE_MOVIEBROWSER_YT_PENDING));
yt_menue->addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_CANCEL, true, NULL, ytcache_selector, "cancel_all"));
yt_menue->addItem(GenericMenuSeparator);
std::string progress;
if (dlstart && (int64_t)dltotal && (int64_t)dlnow) {
time_t done = time(NULL) - dlstart;
time_t left = ((dltotal - dlnow) * done)/dlnow;
progress = "(" + to_string(done) + "s/" + to_string(left) + "s)";
}
int i = 0;
yt_pending_offset = yt_menue->getItemsCount();
for (std::vector<MI_MOVIE_INFO>::iterator it = yt_pending.begin(); it != yt_pending.end(); ++it, ++i) {
yt_menue->addItem(new CMenuForwarder((*it).file.Name, true, progress.c_str(), ytcache_selector));
progress = "";
}
yt_pending_end = yt_menue->getItemsCount();
}
if (!yt_completed.empty()) {
yt_menue->addItem(new CMenuSeparator(CMenuSeparator::LINE | CMenuSeparator::STRING, LOCALE_MOVIEBROWSER_YT_COMPLETED));
yt_menue->addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_CLEAR, true, NULL, ytcache_selector, "completed_clear"));
yt_menue->addItem(GenericMenuSeparator);
int i = 0;
yt_completed_offset = yt_menue->getItemsCount();
for (std::vector<MI_MOVIE_INFO>::iterator it = yt_completed.begin(); it != yt_completed.end(); ++it, ++i) {
yt_menue->addItem(new CMenuForwarder((*it).file.Name.c_str(), true, NULL, ytcache_selector));
}
yt_completed_end = yt_menue->getItemsCount();
}
if (!yt_failed.empty()) {
yt_menue->addItem(new CMenuSeparator(CMenuSeparator::LINE | CMenuSeparator::STRING, LOCALE_MOVIEBROWSER_YT_FAILED));
yt_menue->addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_CLEAR, true, NULL, ytcache_selector, "failed_clear"));
yt_menue->addItem(GenericMenuSeparator);
int i = 0;
yt_failed_offset = yt_menue->getItemsCount();
for (std::vector<MI_MOVIE_INFO>::iterator it = yt_failed.begin(); it != yt_failed.end(); ++it, ++i) {
yt_menue->addItem(new CMenuForwarder((*it).file.Name.c_str(), true, NULL, ytcache_selector));
}
yt_failed_end = yt_menue->getItemsCount();
}
CFrameBuffer::getInstance()->Clear(); // due to possible width change
}
class CYTHistory : public CMenuTarget
{
private:
int width;
int selected;
std::string *search;
MB_SETTINGS *settings;
public:
CYTHistory(MB_SETTINGS &_settings, std::string &_search);
int exec(CMenuTarget* parent, const std::string & actionKey);
};
CYTHistory::CYTHistory(MB_SETTINGS &_settings, std::string &_search)
{
width = w_max(40, 10);
selected = -1;
settings = &_settings;
search = &_search;
}
int CYTHistory::exec(CMenuTarget* parent, const std::string &actionKey)
{
if (actionKey.empty()) {
if (parent)
parent->hide();
CMenuWidget* m = new CMenuWidget(LOCALE_MOVIEBROWSER_YT_HISTORY, NEUTRINO_ICON_MOVIEPLAYER, width);
m->addKey(CRCInput::RC_spkr, this, "clearYThistory");
m->setSelected(selected);
m->addItem(GenericMenuSeparator);
m->addItem(GenericMenuBack);
m->addItem(GenericMenuSeparatorLine);
std::list<std::string>::iterator it = settings->ytsearch_history.begin();
for (int i = 0; i < settings->ytsearch_history_size; i++, ++it)
m->addItem(new CMenuForwarder((*it).c_str(), true, NULL, this, (*it).c_str(), CRCInput::convertDigitToKey(i + 1)));
m->exec(NULL, "");
m->hide();
delete m;
return menu_return::RETURN_REPAINT;
}
if (actionKey == "clearYThistory") {
settings->ytsearch_history.clear();
settings->ytsearch_history_size = 0;
return menu_return::RETURN_EXIT;
}
*search = actionKey;
g_RCInput->postMsg((neutrino_msg_t) CRCInput::RC_blue, 0);
return menu_return::RETURN_EXIT;
}
bool CMovieBrowser::showYTMenu(bool calledExternally)
{
framebuffer->paintBackground();
CMenuWidget mainMenu(LOCALE_MOVIEPLAYER_YTPLAYBACK, NEUTRINO_ICON_MOVIEPLAYER);
mainMenu.addIntroItems(LOCALE_MOVIEBROWSER_OPTION_BROWSER);
int select = -1;
CMenuSelectorTarget * selector = new CMenuSelectorTarget(&select);
char cnt[5];
if (!calledExternally) {
for (unsigned i = 0; i < YT_FEED_OPTION_COUNT; i++) {
sprintf(cnt, "%d", YT_FEED_OPTIONS[i].key);
mainMenu.addItem(new CMenuForwarder(YT_FEED_OPTIONS[i].value, true, NULL, selector, cnt, CRCInput::convertDigitToKey(i + 1)), m_settings.ytmode == (int) YT_FEED_OPTIONS[i].key);
}
mainMenu.addItem(GenericMenuSeparatorLine);
bool enabled = (!m_vMovieInfo.empty()) && (m_movieSelectionHandler != NULL);
sprintf(cnt, "%d", cYTFeedParser::RELATED);
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_RELATED, enabled, NULL, selector, cnt, CRCInput::RC_red));
mainMenu.addItem(GenericMenuSeparatorLine);
}
std::string search = m_settings.ytsearch;
CKeyboardInput stringInput(LOCALE_MOVIEBROWSER_YT_SEARCH, &search);
if (!calledExternally) {
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_SEARCH, true, search, &stringInput, NULL, CRCInput::RC_green));
mainMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_YT_ORDERBY, &m_settings.ytorderby, YT_ORDERBY_OPTIONS, YT_ORDERBY_OPTION_COUNT, true, NULL, CRCInput::RC_nokey, "", true));
sprintf(cnt, "%d", cYTFeedParser::SEARCH);
mainMenu.addItem(new CMenuForwarder(LOCALE_EVENTFINDER_START_SEARCH, true, NULL, selector, cnt, CRCInput::RC_yellow));
}
CYTHistory ytHistory(m_settings, search);
if (!calledExternally) {
if (m_settings.ytsearch_history_size > 0)
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_YT_HISTORY, true, NULL, &ytHistory, "", CRCInput::RC_blue));
mainMenu.addItem(GenericMenuSeparatorLine);
}
mainMenu.addItem(new CMenuOptionNumberChooser(LOCALE_MOVIEBROWSER_YT_MAX_RESULTS, &m_settings.ytresults, true, 10, 50, NULL));
mainMenu.addItem(new CMenuOptionNumberChooser(LOCALE_MOVIEBROWSER_YT_MAX_HISTORY, &m_settings.ytsearch_history_max, true, 10, 50, NULL));
std::string rstr = m_settings.ytregion;
CMenuOptionStringChooser * region = new CMenuOptionStringChooser(LOCALE_MOVIEBROWSER_YT_REGION, &rstr, true, NULL, CRCInput::RC_nokey, "", true);
region->addOption("default");
region->addOption("DE");
region->addOption("PL");
region->addOption("RU");
region->addOption("NL");
region->addOption("CZ");
region->addOption("FR");
region->addOption("HU");
region->addOption("US");
mainMenu.addItem(region);
#define YT_QUALITY_OPTION_COUNT 3
CMenuOptionChooser::keyval_ext YT_QUALITY_OPTIONS[YT_QUALITY_OPTION_COUNT] =
{
{ 18, NONEXISTANT_LOCALE, "MP4 270p/360p"},
{ 22, NONEXISTANT_LOCALE, "MP4 720p" },
#if 0
{ 34, NONEXISTANT_LOCALE, "FLV 360p" },
{ 35, NONEXISTANT_LOCALE, "FLV 480p" },
#endif
{ 37, NONEXISTANT_LOCALE, "MP4 1080p" }
};
mainMenu.addItem(new CMenuOptionChooser(LOCALE_MOVIEBROWSER_YT_PREF_QUALITY, &m_settings.ytquality, YT_QUALITY_OPTIONS, YT_QUALITY_OPTION_COUNT, true, NULL, CRCInput::RC_nokey, "", true));
mainMenu.addItem(new CMenuOptionNumberChooser(LOCALE_MOVIEBROWSER_YT_CONCURRENT_CONNECTIONS, &m_settings.ytconcconn, true, 1, 8));
CFileChooser fc(&m_settings.ytthumbnaildir);
mainMenu.addItem(new CMenuForwarder(LOCALE_MOVIEBROWSER_CACHE_DIR, true, m_settings.ytthumbnaildir, &fc));
yt_menue = &mainMenu;
yt_menue_end = yt_menue->getItemsCount();
CYTCacheSelectorTarget ytcache_sel(this);
ytcache_selector = &ytcache_sel;
yt_menue->addKey(CRCInput::RC_spkr, ytcache_selector, "rc_spkr");
refreshYTMenu();
mainMenu.exec(NULL, "");
ytparser.SetConcurrentDownloads(m_settings.ytconcconn);
ytparser.SetThumbnailDir(m_settings.ytthumbnaildir);
delete selector;
bool reload = false;
int newmode = -1;
if (rstr != m_settings.ytregion) {
m_settings.ytregion = rstr;
if (newmode < 0)
newmode = m_settings.ytmode;
reload = true;
printf("change region to %s\n", m_settings.ytregion.c_str());
}
if (calledExternally)
return true;
printf("MovieBrowser::showYTMenu(): selected: %d\n", select);
if (select >= 0) {
newmode = select;
if (select == cYTFeedParser::RELATED) {
if (m_settings.ytvid != m_movieSelectionHandler->ytid) {
printf("get related for: %s\n", m_movieSelectionHandler->ytid.c_str());
m_settings.ytvid = m_movieSelectionHandler->ytid;
m_settings.ytmode = newmode;
reload = true;
}
}
else if (select == cYTFeedParser::SEARCH) {
printf("search for: %s\n", search.c_str());
if (!search.empty()) {
reload = true;
m_settings.ytsearch = search;
m_settings.ytmode = newmode;
m_settings.ytsearch_history.push_front(search);
std::list<std::string>::iterator it = m_settings.ytsearch_history.begin();
it++;
while (it != m_settings.ytsearch_history.end()) {
if (*it == search)
it = m_settings.ytsearch_history.erase(it);
else
++it;
}
if (m_settings.ytsearch_history.empty())
m_settings.ytsearch_history_size = 0;
else
m_settings.ytsearch_history_size = m_settings.ytsearch_history.size();
if (m_settings.ytsearch_history_size > m_settings.ytsearch_history_max)
m_settings.ytsearch_history_size = m_settings.ytsearch_history_max;
}
}
else if (m_settings.ytmode != newmode) {
m_settings.ytmode = newmode;
reload = true;
}
}
if (reload) {
CHintBox loadBox(LOCALE_MOVIEPLAYER_YTPLAYBACK, g_Locale->getText(LOCALE_MOVIEBROWSER_SCAN_FOR_MOVIES));
loadBox.paint();
ytparser.Cleanup();
loadYTitles(newmode, m_settings.ytsearch, m_settings.ytvid);
loadBox.hide();
}
refreshBrowserList();
refreshLastPlayList();
refreshLastRecordList();
refreshFilterList();
refresh();
return true;
}
CMenuSelector::CMenuSelector(const char * OptionName, const bool Active, char * OptionValue, int* ReturnInt,int ReturnIntValue) : CMenuItem()
{
height = g_Font[SNeutrinoSettings::FONT_TYPE_MENU]->getHeight();
optionValueString = NULL;
optionName = OptionName;
optionValue = OptionValue;
active = Active;
returnIntValue = ReturnIntValue;
returnInt = ReturnInt;
}
CMenuSelector::CMenuSelector(const char * OptionName, const bool Active, std::string& OptionValue, int* ReturnInt,int ReturnIntValue) : CMenuItem()
{
height = g_Font[SNeutrinoSettings::FONT_TYPE_MENU]->getHeight();
optionValueString = &OptionValue;
optionName = OptionName;
strncpy(buffer,OptionValue.c_str(),BUFFER_MAX-1);
buffer[BUFFER_MAX-1] = 0;// terminate string
optionValue = buffer;
active = Active;
returnIntValue = ReturnIntValue;
returnInt = ReturnInt;
}
int CMenuSelector::exec(CMenuTarget* /*parent*/)
{
if (returnInt != NULL)
*returnInt= returnIntValue;
if (optionValue != NULL && optionName != NULL)
{
if (optionValueString == NULL)
strcpy(optionValue,optionName);
else
*optionValueString = optionName;
}
return menu_return::RETURN_EXIT;
}
int CMenuSelector::paint(bool selected)
{
CFrameBuffer * frameBuffer = CFrameBuffer::getInstance();
fb_pixel_t color = COL_MENUCONTENT_TEXT;
fb_pixel_t bgcolor = COL_MENUCONTENT_PLUS_0;
if (selected)
{
color = COL_MENUCONTENTSELECTED_TEXT;
bgcolor = COL_MENUCONTENTSELECTED_PLUS_0;
}
if (!active)
{
color = COL_MENUCONTENTINACTIVE_TEXT;
bgcolor = COL_MENUCONTENTINACTIVE_PLUS_0;
}
frameBuffer->paintBoxRel(x, y, dx, height, bgcolor);
int stringstartposName = x + offx + 10;
g_Font[SNeutrinoSettings::FONT_TYPE_MENU]->RenderString(stringstartposName, y+height,dx- (stringstartposName - x), optionName, color);
if (selected)
CVFD::getInstance()->showMenuText(0, optionName, -1, true); // UTF-8
return y+height;
}
int CMovieHelp::exec(CMenuTarget* /*parent*/, const std::string & /*actionKey*/)
{
Helpbox helpbox;
helpbox.addLine(NEUTRINO_ICON_BUTTON_RED, "Sortierung ändern");
helpbox.addLine(NEUTRINO_ICON_BUTTON_GREEN, "Filterfenster einblenden");
helpbox.addLine(NEUTRINO_ICON_BUTTON_YELLOW, "Aktives Fenster wechseln");
helpbox.addLine(NEUTRINO_ICON_BUTTON_BLUE, "Filminfos neu laden");
helpbox.addLine(NEUTRINO_ICON_BUTTON_MENU, "Hauptmenü");
helpbox.addLine("+/- Ansicht wechseln");
helpbox.addLine("");
helpbox.addLine("Während der Filmwiedergabe:");
helpbox.addLine(NEUTRINO_ICON_BUTTON_BLUE, " Markierungsmenu ");
helpbox.addLine(NEUTRINO_ICON_BUTTON_0, " Markierungsaktion nicht ausführen");
helpbox.addLine("");
helpbox.addLine("MovieBrowser $Revision: 1.10 $");
helpbox.addLine("by Günther");
helpbox.show(LOCALE_MESSAGEBOX_INFO);
return(0);
}
/////////////////////////////////////////////////
// MenuTargets
////////////////////////////////////////////////
int CFileChooser::exec(CMenuTarget* parent, const std::string & /*actionKey*/)
{
if (parent != NULL)
parent->hide();
CFileBrowser browser;
browser.Dir_Mode=true;
std::string oldPath = *dirPath;
if (browser.exec(dirPath->c_str())) {
*dirPath = browser.getSelectedFile()->Name;
if (check_dir(dirPath->c_str(), true))
*dirPath = oldPath;
}
return menu_return::RETURN_REPAINT;
}
CDirMenu::CDirMenu(std::vector<MB_DIR>* dir_list)
{
unsigned int i;
changed = false;
dirList = dir_list;
if (dirList->empty())
return;
for (i = 0; i < MAX_DIR; i++)
dirNfsMountNr[i] = -1;
for (i = 0; i < dirList->size() && i < MAX_DIR; i++)
{
for (int nfs = 0; nfs < NETWORK_NFS_NR_OF_ENTRIES; nfs++)
{
int result = -1;
if (!g_settings.network_nfs[nfs].local_dir.empty())
result = (*dirList)[i].name.compare(0,g_settings.network_nfs[nfs].local_dir.size(),g_settings.network_nfs[nfs].local_dir) ;
printf("[CDirMenu] (nfs%d) %s == (mb%d) %s (%d)\n",nfs,g_settings.network_nfs[nfs].local_dir.c_str(),i,(*dirList)[i].name.c_str(),result);
if (result == 0)
{
dirNfsMountNr[i] = nfs;
break;
}
}
}
}
int CDirMenu::exec(CMenuTarget* parent, const std::string & actionKey)
{
int returnval = menu_return::RETURN_REPAINT;
if (actionKey.empty())
{
if (parent)
parent->hide();
changed = false;
return show();
}
else if (actionKey.size() == 1)
{
printf("[CDirMenu].exec %s\n",actionKey.c_str());
int number = atoi(actionKey.c_str());
if (number < MAX_DIR)
{
if (dirState[number] == DIR_STATE_SERVER_DOWN)
{
printf("try to start server: %s %s\n","ether-wake", g_settings.network_nfs[dirNfsMountNr[number]].mac.c_str());
if (my_system(2, "ether-wake", g_settings.network_nfs[dirNfsMountNr[number]].mac.c_str()) != 0)
perror("ether-wake failed");
dirOptionText[number] = "STARTE SERVER";
}
else if (dirState[number] == DIR_STATE_NOT_MOUNTED)
{
printf("[CDirMenu] try to mount %d,%d\n",number,dirNfsMountNr[number]);
CFSMounter::MountRes res;
res = CFSMounter::mount(g_settings.network_nfs[dirNfsMountNr[number]].ip,
g_settings.network_nfs[dirNfsMountNr[number]].dir,
g_settings.network_nfs[dirNfsMountNr[number]].local_dir,
(CFSMounter::FSType)g_settings.network_nfs[dirNfsMountNr[number]].type,
g_settings.network_nfs[dirNfsMountNr[number]].username,
g_settings.network_nfs[dirNfsMountNr[number]].password,
g_settings.network_nfs[dirNfsMountNr[number]].mount_options1,
g_settings.network_nfs[dirNfsMountNr[number]].mount_options2);
if (res == CFSMounter::MRES_OK) // if mount is successful we set the state to active in any case
*(*dirList)[number].used = true;
// try to mount
updateDirState();
changed = true;
}
else if (dirState[number] == DIR_STATE_MOUNTED)
{
if (*(*dirList)[number].used == true)
*(*dirList)[number].used = false;
else
*(*dirList)[number].used = true;
//CFSMounter::umount(g_settings.network_nfs_local_dir[dirNfsMountNr[number]]);
updateDirState();
changed = true;
}
}
}
return returnval;
}
extern int pinghost(const std::string &hostname, std::string *ip = NULL);
void CDirMenu::updateDirState(void)
{
unsigned int drivefree = 0;
struct statfs s;
for (unsigned int i = 0; i < dirList->size() && i < MAX_DIR; i++)
{
dirOptionText[i] = "UNBEKANNT";
dirState[i] = DIR_STATE_UNKNOWN;
// 1st ping server
printf("updateDirState: %d: state %d nfs %d\n", i, dirState[i], dirNfsMountNr[i]);
if (dirNfsMountNr[i] != -1)
{
int retvalue = pinghost(g_settings.network_nfs[dirNfsMountNr[i]].ip);
if (retvalue == 0)//LOCALE_PING_UNREACHABLE
{
dirOptionText[i] = "Server, offline";
dirState[i] = DIR_STATE_SERVER_DOWN;
}
else if (retvalue == 1)//LOCALE_PING_OK
{
if (!CFSMounter::isMounted(g_settings.network_nfs[dirNfsMountNr[i]].local_dir))
{
dirOptionText[i] = "Not mounted";
dirState[i] = DIR_STATE_NOT_MOUNTED;
}
else
{
dirState[i] = DIR_STATE_MOUNTED;
}
}
}
else
{
// not a nfs dir, probably IDE? we accept this so far
dirState[i] = DIR_STATE_MOUNTED;
}
if (dirState[i] == DIR_STATE_MOUNTED)
{
if (*(*dirList)[i].used == true)
{
if (statfs((*dirList)[i].name.c_str(), &s) >= 0)
{
drivefree = (s.f_bfree * s.f_bsize)>>30;
char tmp[20];
snprintf(tmp, 19,"%3d GB free",drivefree);
dirOptionText[i] = tmp;
}
else
{
dirOptionText[i] = "? GB free";
}
}
else
{
dirOptionText[i] = "Inactive";
}
}
}
}
int CDirMenu::show(void)
{
if (dirList->empty())
return menu_return::RETURN_REPAINT;
char tmp[20];
CMenuWidget dirMenu(LOCALE_MOVIEBROWSER_HEAD, NEUTRINO_ICON_MOVIEPLAYER);
dirMenu.addIntroItems(LOCALE_MOVIEBROWSER_MENU_DIRECTORIES_HEAD);
updateDirState();
for (unsigned int i = 0; i < dirList->size() && i < MAX_DIR; i++)
{
snprintf(tmp, sizeof(tmp),"%d",i);
dirMenu.addItem(new CMenuForwarder ((*dirList)[i].name.c_str(), (dirState[i] != DIR_STATE_UNKNOWN), dirOptionText[i], this, tmp));
}
int ret = dirMenu.exec(NULL," ");
return ret;
}
| gpl-3.0 |
markgw/jazzparser | src/jazzparser/utils/interface.py | 1859 | """Generic interface utilities (e.g. interactive command-line processing).
"""
"""
============================== License ========================================
Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding
This file is part of The Jazz Parser.
The Jazz Parser is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Jazz Parser is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Jazz Parser. If not, see <http://www.gnu.org/licenses/>.
============================ End license ======================================
"""
__author__ = "Mark Granroth-Wilding <mark.granroth-wilding@ed.ac.uk>"
def boolean_input(prompt):
"""
Displays a prompt with a yes/no choice. Returns True is the user
selects yes, False otherwise.
"""
response = raw_input("%s [y/N] " % prompt)
if response.lower() == "y":
return True
else:
return False
def input_iterator(prompt):
"""
Creates an iterator that will accept command line input indefinitely
and terminate when Ctrl+D is received.
The iterator uses C{raw_input}, so you can use it in conjunction with
C{readline}.
"""
# Define an iterator (via a generator) to get cmd line input
def _get_input():
try:
while True:
yield raw_input(prompt)
except EOFError:
return
return iter(_get_input())
| gpl-3.0 |
gebner/gapt | core/src/main/scala/at/logic/gapt/provers/viper/grammars/InductiveGrammarFindingMethod.scala | 981 | package at.logic.gapt.provers.viper.grammars
import at.logic.gapt.expr.Expr
import at.logic.gapt.grammars.RecursionScheme
import at.logic.gapt.proofs.expansion.InstanceTermEncoding
import at.logic.gapt.proofs.{ Context, HOLSequent }
trait SchematicInductiveProofFindingMethod {
def find( endSequent: HOLSequent, encoding: InstanceTermEncoding, context: Context,
taggedLanguage: Set[( Seq[Expr], Expr )] ): SchematicProofWithInduction
}
trait InductiveGrammarFindingMethod extends SchematicInductiveProofFindingMethod {
def findRS( taggedLanguage: Set[( Seq[Expr], Expr )] ): RecursionScheme
override def find( endSequent: HOLSequent, encoding: InstanceTermEncoding, context: Context,
taggedLanguage: Set[( Seq[Expr], Expr )] ): SchematicProofWithInduction = {
val rs = encoding.decode( findRS( taggedLanguage ) )
val homogenized = homogenizeRS( rs )( context )
ProofByRecursionScheme( endSequent, homogenized, context )
}
}
| gpl-3.0 |
Mapleroid/cm-server | server-5.11.0.src/com/cloudera/server/web/cmf/UserSettingsEnum.java | 2285 | package com.cloudera.server.web.cmf;
public enum UserSettingsEnum
{
SCM_HOSTS_TABLE("com.cloudera.scm.hosts.table"),
SCM_HOSTS_FILTER_TABLE("com.cloudera.scm.hosts.filter.table"),
SCM_INSTANCES_TABLE("com.cloudera.scm.instances.table"),
SCM_INSTANCES_FILTER_TABLE("com.cloudera.scm.instances.filter.table"),
SCM_CONFIG_PAGE_VERSION("com.cloudera.scm.config.page.version"),
SCM_CONFIG_PAGE("com.cloudera.scm.config.page"),
SCM_CREDENTIALS_FILTER_TABLE("com.cloudera.scm.credentials.filter.table"),
SCM_STATUS_HEALTH_POPUP_TABLE("com.cloudera.scm.statusHealth.popup.table"),
SCM_HOST_ROLE_ASSIGNMENT_TABLE("com.cloudera.scm.hostRoleAssignment.table"),
SCM_EXPRESS_ADD_HOSTS_WIZARD_STATE("com.cloudera.server.web.cmf.wizard.express.addHosts.state"),
SCM_EXPRESS_ADD_SERVICES_WIZARD_STATE("com.cloudera.server.web.cmf.wizard.express.addServices.state"),
AMON_CONTEXT_TABLE_QUERY_MODEL("com.cloudera.amon.context.table.queryModel"),
AMON_CONTEXT_TABLE_COLUMN("com.cloudera.amon.context.table.column"),
AMON_CONTEXT_CHART_SELECTION("com.cloudera.amon.context.chart.selection"),
SMON_CONTEXT_CHART_SELECTION("com.cloudera.smon.context.chart.selection"),
FLUME_CHANNELS_TABLE("com.cloudera.scm.flume.channels.table"),
FLUME_SOURCES_TABLE("com.cloudera.scm.flume.sources.table"),
FLUME_SINKS_TABLE("com.cloudera.scm.flume.sinks.table"),
VIEW_PREFIX("com.cloudera.server.web.cmf.view."),
CHARTS_RECENT_TSQUERIES("com.cloudera.server.web.cmf.charts.recent_tsqueries"),
IMPALA_QUERIES_LIST_FILTERS("com.cloudera.server.web.cmf.impala.recent_filters"),
YARN_APPLICATIONS_LIST_FILTERS("com.cloudera.server.web.cmf.yarn.recent_filters"),
EVENT_SEARCH_LIST_FILTERS("com.cloudera.server.web.cmf.events.recent_filters"),
AUDIT_SEARCH_LIST_FILTERS("com.cloudera.server.web.cmf.audits.recent_filters"),
IMPALA_QUERIES_SELECTED_ATTRIBUTES("com.cloudera.server.web.cmf.impala.selected_attributes"),
YARN_APPLICATIONS_SELECTED_ATTRIBUTES("com.cloudera.server.web.cmf.yarn.selected_attributes");
private final String key;
private UserSettingsEnum(String key) { this.key = key;
}
public String toString()
{
return this.key;
}
} | gpl-3.0 |
Marcin1112/CustomizeExcelRibbon | CustomizeRibbon/src/main/java/ribbonElements/separator/MenuSeparator.java | 2405 | package ribbonElements.separator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import ribbonElements.SimpleRibbonContainer;
/**
* Menu Separator
*
* @author Marcin
*
*/
public class MenuSeparator implements SimpleRibbonContainer {
private Map<String, String> attributes = new HashMap<String, String>();
private Document doc;
private List<SimpleRibbonContainer> groups = new ArrayList<SimpleRibbonContainer>();
/**
* constructor
*
* @param doc
* reference to the XML document in which button will be created
*/
public MenuSeparator(Document doc) {
this.doc = doc;
fillMap();
}
/**
* constructor
*
*/
public MenuSeparator() {
fillMap();
}
/**
* fill map 'attributes'
*/
public void fillMap() {
attributes.put("getVisible", null); // callback
attributes.put("id", null); // control identifier
attributes.put("idQ", null); // qualified control identifier
attributes.put("insertAfterMso", null); // identifier of built-in
// control to insert after
attributes.put("insertAfterQ", null); // qualified identifier of control
// to insert after
attributes.put("insertBeforeMso", null); // identifier of built-in
// control to insert before
attributes.put("insertBeforeQ", null); // qualified identifier of
// control to insert before
attributes.put("visible", null); // control visibility
}
/**
* @inheritDoc
*/
public void setAttribute(String attribute, String value) {
attributes.put(attribute, value);
}
/**
* @inheritDoc
*/
public String getAttributeValue(String attribute) {
return attributes.get(attribute);
}
/**
* @inheritDoc
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* @inheritDoc
*/
public Element getXMLElement() {
Element menuSeparator = doc.createElement("menuSeparator");
for (Entry<String, String> i : attributes.entrySet()) {
if (i.getValue() != null) {
menuSeparator.setAttribute(i.getKey(), i.getValue());
}
}
return menuSeparator;
}
/**
* toString method
*/
@Override
public String toString() {
return "Menu Separator";
}
/**
* @inheritDoc
*/
public void addChild(SimpleRibbonContainer group) {
groups.add(group);
}
}
| gpl-3.0 |
geronimo-iia/geva | GEVA/src/Main/Run.java | 8820 | /*
Grammatical Evolution in Java
Release: GEVA-v1.0.zip
Copyright (C) 2008 Michael O'Neill, Erik Hemberg, Anthony Brabazon, Conor Gilligan
Contributors Patrick Middleburgh, Eliott Bartley, Jonathan Hugosson, Jeff Wrigh
Separate licences for asm, bsf, antlr, groovy, jscheme, commons-logging, jsci is included in the lib folder.
Separate licence for rieps is included in src/com folder.
This licence refers to GEVA-v1.0.
This software is distributed under the terms of the GNU General Public License.
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/>.
*/
/*
* Run.java
*
* Created on April 17, 2007, 11:02 AM
*
*/
package Main;
import Algorithm.MyFirstSearchEngine;
import Algorithm.Pipeline;
import Algorithm.SimplePipeline;
import FitnessEvaluation.FitnessFunction;
import Mapper.GEGrammar;
import Operator.*;
import Operator.Operations.*;
import Util.Constants;
import Util.Random.MersenneTwisterFast;
import Util.Statistics.IndividualCatcher;
import Util.Statistics.StatCatcher;
/**
* Run main class.
* Steps to setup the algorithm.
* Create the operators you want to use eg: mutation, selection.
* Create specific operations eg: Int flip mutation, Tournament Selection.
* Add the operations to the operators
* Set the population in each operator.
* Add opertors to the init pipeline in the desired order of execution.
* Add operators to the loop pipeline in the desired order of execution.
* Create a main for the algorithm to run this needs to call init, setup and run(int number_of_iterations)
* (or the step() method can be used in a loop)
* @author erikhemberg
*/
public class Run extends AbstractRun {
private long startTime;
/** Creates a new instance of Run */
public Run() {
this.rng = new MersenneTwisterFast();
super.propertiesFilePath = Constants.DEFAULT_PROPERTIES;
this.startTime = System.currentTimeMillis();
}
/**
* Setup the algorithm. Read the properties. Create the modules(Operators) and operations
* @param args arguments
*/
public void setup(String[] args) {
//Read properties
this.readProperties(args);
//set rng seed
this.setSeed();
/*
* Operators and Operations
* Example of setting up an algorithm.
* For specific details of operators and operations used see
* the respective source or API
*/
//Grammar
GEGrammar grammar = new GEGrammar(this.properties);
//Search engine
MyFirstSearchEngine alg = new MyFirstSearchEngine();
//Initialiser
initialiser = getInitialiser(grammar, this.rng, this.properties);
//Crossover
CrossoverOperation singlePointCrossover = new SinglePointCrossover(this.rng, this.properties);
CrossoverModule crossoverModule = new CrossoverModule(this.rng, singlePointCrossover);
//Mutation
IntFlipMutation mutation = new IntFlipMutation(this.rng, this.properties);
MutationOperator mutationModule = new MutationOperator(this.rng, mutation);
//Selection
SelectionOperation selectionOperation = getSelectionOperation(this.properties, this.rng);
SelectionScheme selectionScheme = new SelectionScheme(this.rng, selectionOperation);
//Replacement
ReplacementOperation replacementOperation = new ReplacementOperation(this.properties);
JoinOperator replacementStrategy = this.getJoinOperator(this.properties, this.rng, selectionScheme.getPopulation(), replacementOperation);
//Elite selection
EliteOperationSelection eliteSelectionOperation = new EliteOperationSelection(this.properties);
SelectionScheme eliteSelection = new SelectionScheme(this.rng, eliteSelectionOperation);
//Elite replacement
EliteReplacementOperation eliteReplacementOperation = new EliteReplacementOperation(this.properties);
EliteReplacementOperator eliteReplacementStrategy = new EliteReplacementOperator(this.rng, eliteSelection.getPopulation(), eliteReplacementOperation);
//Fitness function
FitnessFunction fitnessFunction = getFitnessFunction(this.properties);
FitnessEvaluationOperation fitnessEvaluationOperation = new FitnessEvaluationOperation(fitnessFunction);
fitnessEvaluationOperation.setProperties(properties);
FitnessEvaluator fitnessEvaluator = new FitnessEvaluator(this.rng, fitnessEvaluationOperation);
//Statistics
StatCatcher stats = new StatCatcher(Integer.parseInt(this.properties.getProperty("generations")));
IndividualCatcher indCatch = new IndividualCatcher(this.properties);
stats.addTime(startTime);//Set initialisation time for the statCatcher (Not completly accurate here)
StatisticsCollectionOperation statsCollection = new StatisticsCollectionOperation(stats, indCatch, this.properties);
Collector collector = new Collector(statsCollection);
/*
* Init
*/
//Pipeline
Pipeline pipelineInit = new SimplePipeline();
alg.setInitPipeline(pipelineInit);
//FitnessEvaluator for the init pipeline
FitnessEvaluator fitnessEvaluatorInit = new FitnessEvaluator(this.rng, fitnessEvaluationOperation);
//Set population
fitnessEvaluatorInit.setPopulation(initialiser.getPopulation());
collector.setPopulation(initialiser.getPopulation());
//Add modules to pipeline
pipelineInit.addModule(initialiser);
pipelineInit.addModule(fitnessEvaluatorInit);
pipelineInit.addModule(collector);
/*
* Loop
*/
//Pipeline
Pipeline pipelineLoop = new SimplePipeline();
alg.setLoopPipeline(pipelineLoop);
//Set population passing
selectionScheme.setPopulation(initialiser.getPopulation());
replacementStrategy.setPopulation(initialiser.getPopulation());
crossoverModule.setPopulation(selectionScheme.getPopulation());
mutationModule.setPopulation(selectionScheme.getPopulation());
fitnessEvaluator.setPopulation(selectionScheme.getPopulation());
eliteSelection.setPopulation(initialiser.getPopulation());
eliteReplacementStrategy.setPopulation(initialiser.getPopulation());
collector.setPopulation(initialiser.getPopulation());
//Add modules to pipeline
pipelineLoop.addModule(eliteSelection); //Remove elites
pipelineLoop.addModule(selectionScheme);
pipelineLoop.addModule(crossoverModule);
pipelineLoop.addModule(mutationModule);
pipelineLoop.addModule(fitnessEvaluator);
pipelineLoop.addModule(replacementStrategy);
pipelineLoop.addModule(eliteReplacementStrategy); //Add elites
pipelineLoop.addModule(collector);
this.algorithm = alg;
}
/**
* Sets the random number generator seed if it is specified
*/
private void setSeed() {
long seed;
if(this.properties.getProperty(Constants.RNG_SEED)!=null) {
seed = Long.parseLong(this.properties.getProperty(Constants.RNG_SEED));
this.rng.setSeed(seed);
}
}
/**
* Run
* @param args arguments
*/
public static void main(String[] args) {
try{
//Initialize timing the excecution
long st = System.currentTimeMillis();
Run mfs = new Run();
//Read the command-line arguments
if(mfs.commandLineArgs(args)) {
//Create the Main object
//Setup the algorithm
mfs.setup(args);
//Initialize the algorithm
mfs.init();
//Hack for number of iterations!!?? Create a proper method
int its = mfs.run();
//Print collected data
mfs.printStuff();
//Time the excecution
long et = System.currentTimeMillis();
System.out.println("Done running: Total time(Ms) for " + its + " generations was:"+(et-st));
}
} catch(Exception e) {
System.err.println("Exception: "+e);
e.printStackTrace();
}
}
}
| gpl-3.0 |
spox/mod_spox | lib/mod_spox/messages/internal/FilterRemove.rb | 612 | require 'mod_spox/messages/internal/Request'
module ModSpox
module Messages
module Internal
class FilterRemove
# ModSpox::Filter
attr_reader :filter
# Type of messages to filter
attr_reader :type
# filter:: ModSpox::Filter type object
# type:: message type to filter
# Add a new filter to the pipeline
def initialize(filter, type)
@filter = filter
@type = type
end
end
end
end
end | gpl-3.0 |
jonathanverner/comment | hiliteItem.cpp | 2617 | /** This file is part of project comment
*
* File: hiliteItem.cpp
* Created: 2009-02-13
* Author: Jonathan Verner <jonathan.verner@matfyz.cz>
* License: GPL v2 or later
*
* Copyright (C) 2010 Jonathan Verner <jonathan.verner@matfyz.cz>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "hiliteItem.h"
#include <QtCore/QDebug>
#include <poppler-qt4.h>
using namespace Poppler;
hiliteItem::hiliteItem( QPointF topLeftPage, QList<TextBox *> bboxes ):
col( 0, 255, 217, 100 ), bBox( 0, 0, 0, 0 ), active(false)
{
setPos( topLeftPage );
updateBBoxes( bboxes );
}
hiliteItem::hiliteItem():
col( 0, 0, 0, 100), bBox( 0, 0, 0, 0 ), active(false)
{
setPos( QPointF(0,0) );
hide();
}
void hiliteItem::setColor( QColor cl ) {
col = cl;
update();
}
void hiliteItem::setActive() {
active=true;
col = QColor( 0, 255, 217, 100 );
update();
}
void hiliteItem::setInactive() {
active=false;
col = QColor( 105, 255, 210, 100);
update();
}
QRectF hiliteItem::boundingRect() const {
return bBox;
}
void hiliteItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) {
QPointF myPos = pos();
foreach( QRectF box, hBoxes ) {
painter->fillRect( box, col );
if (active) painter->drawRect( box );
}
}
QPainterPath hiliteItem::shape() const {
return exactShape;
}
void hiliteItem::clear() {
hide();
update();
prepareGeometryChange();
setPos(QPointF(0,0));
hBoxes.clear();
bBox = QRectF(0,0,0,0);
exactShape = QPainterPath();
update();
}
void hiliteItem::updateBBoxes( QList<TextBox*> bboxes ) {
QPainterPath tmp;
QRectF br;
update();
prepareGeometryChange();
hBoxes.clear();
foreach( TextBox *box, bboxes ) {
br = box->boundingBox();
hBoxes.append( br );
tmp.addRect( br );
}
bBox = tmp.boundingRect();
exactShape=tmp;
update();
}
| gpl-3.0 |
localtube/localtube | mainwindow.cpp | 18093 | /*
Copyright (c) 2015 Clement Roblot
This file is part of localtube.
Localtube 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.
Localtube 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 localtube. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
/**
* @brief Constructor of the main window
* @param parent parent widget
*/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// By default we allow downloading of videos
this->downloadEnable = true;
// Add a label to the statusbar (will be used to display the last time we fetched the feed)
ui->statusBar->addPermanentWidget(&statusBarText);
//Open the saved settings
settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "localtube", "config");
QFileInfo setting_file(settings->fileName());
pathToFiles = new QString(setting_file.path());
//create the path to the images if it doesn't exist
QDir resourceFolder(*pathToFiles);
if(!resourceFolder.exists())
resourceFolder.mkpath(".");
//Save the icon of the app (to be used to display in notifications latter)
QImage *img = new QImage(":/images/icon.png");
img->save(*pathToFiles+"/icon.png");
//Set the download location to the last one saved or the system default one
QString systemDefaultDownloadLocation = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation)+QDir::separator();
QString downloadLocation = settings->value("destination", systemDefaultDownloadLocation).toString();
ui->downloadDestination->setText(downloadLocation);
//Build the array containing the list of videos
modelListVideo = new QStandardItemModel(0, 0, this);
modelListVideo->setColumnCount(3);
modelListVideo->setHorizontalHeaderItem(0, new QStandardItem(QString("Title")));
modelListVideo->setHorizontalHeaderItem(1, new QStandardItem(QString("Code")));
modelListVideo->setHorizontalHeaderItem(2, new QStandardItem(QString("Done")));
ui->widgetListVideos->setModel(modelListVideo);
//Define the structure and rule of the array displaying the videos
QHeaderView *headerView = new QHeaderView(Qt::Horizontal, ui->widgetListVideos);
ui->widgetListVideos->setHorizontalHeader(headerView);
headerView->setSectionResizeMode(0, QHeaderView::Stretch);
headerView->setSectionResizeMode(1, QHeaderView::Interactive);
headerView->resizeSection(1, 150);
headerView->resizeSection(2, 50);
//By default the list of videos is empty
listVideos = NULL;
//By default pointers are null
installProc = NULL;
//Get the client id keys that is in the apiKey.txt file
QFile clientIdFile(":/clientId.txt");
clientIdFile.open(QIODevice::ReadOnly);
QTextStream clientIdStream(&clientIdFile);
clientId = clientIdStream.readAll();
clientIdFile.close();
clientId.remove(QRegExp("[\\n\\t\\r]"));
//Get the client secret keys that is in the apiKey.txt file
QFile clientSecretFile(":/clientSecret.txt");
clientSecretFile.open(QIODevice::ReadOnly);
QTextStream clientSecretStream(&clientSecretFile);
clientSecret = clientSecretStream.readAll();
clientSecretFile.close();
clientSecret.remove(QRegExp("[\\n\\t\\r]"));
//Instanciate the youtube feed fetcher
feedFetcher = new FeedFetcher(settings, clientId, clientSecret);
connect(feedFetcher, SIGNAL(doneFetching()), this, SLOT(doneUpdatingRSSFeed()));
//Creates the contextual menu of the tray icon
trayIcon = NULL;
trayIconMenu = NULL;
showAction = NULL;
pauseAction = NULL;
quitAction = NULL;
createTrayIcon();
//Every 15 minutes we fetch the videos feeds
timer = new QTimer();
timer->setInterval(15*60*1000); //fetch new video every 15 minutes
timer->start();
connect(timer, SIGNAL(timeout()), this, SLOT(updateRSSFeed()));
//Default to null the contextual menu actions (will be initialised latter)
actionReset = NULL;
actionDownloaded = NULL;
//We define our own context menu when right clicking in the video list (defined in on_widgetListVideos_customContextMenuRequested)
ui->widgetListVideos->setContextMenuPolicy(Qt::CustomContextMenu);
//Hide as soon as possible the app once created
//QTimer::singleShot(100, this, SLOT(close()));
//Timer used to buffer UI update requests. When it triggers we refresh the interface
connect(&uiUpdateTimer, SIGNAL(timeout()), this, SLOT(updateUI()));
//Initialise the about window
fistAboutWindow = new About();
connect(fistAboutWindow, SIGNAL(lastestVersionFetched(QString)), this, SLOT(processVersionNumber(QString)));
fistAboutWindow->checkVersion();
//Initialise the tester to trigger a recheck when we get back online
youtubeTester = new NetworkIsOnline(QUrl("https://www.youtube.com/"));
connect(youtubeTester, SIGNAL(isNowOnline()), this, SLOT(updateRSSFeed()));
//By default we consider youtubeDL to be not installed
this->YoutubeDlInstalled = false;
//So we try to install it
installYoutubeDl();
//Finaly update the UI with all those modifications
updateUI();
}
/**
* @brief Destructor of the mainwindow
*/
MainWindow::~MainWindow()
{
delete feedFetcher;
delete timer;
if(trayIcon)
delete trayIcon;
if(trayIconMenu)
delete trayIconMenu;
if(showAction)
delete showAction;
if(pauseAction)
delete pauseAction;
if(quitAction)
delete quitAction;
settings->sync();
delete settings;
delete modelListVideo;
if(actionReset)
delete actionReset;
if(actionDownloaded)
delete actionDownloaded;
delete ui;
}
/**
* @brief MainWindow::processVersionNumber
* @param versionNumber
*/
void MainWindow::processVersionNumber(QString versionNumber)
{
if( versionNumber.compare(CURRENT_VERSION) > 0)
{
QString desktop;
bool isUnity;
//qDebug() << "Need update";
desktop = getenv("XDG_CURRENT_DESKTOP");
isUnity = (desktop.toLower() == "unity");
if(isUnity) //only use this in unity
{
system("notify-send 'A new version of localtube is avalable' 'at http://localtube.org' -i " + pathToFiles->toUtf8() + "/icon.png -t 5000");
}
else
{
trayIcon->showMessage("A new version of localtube is avalable", "at http://localtube.org", QSystemTrayIcon::Information, 5000);
}
}
}
void MainWindow::updateUIRequest()
{
//If an update is not already being waitting
if(uiUpdateTimer.isActive() == false)
{
uiUpdateTimer.start(100);
}
}
void MainWindow::updateUI()
{
int isCurrentlyDownloading = 0;
QModelIndex currentlySelected = ui->widgetListVideos->currentIndex();
uiUpdateTimer.stop();
listVideos = feedFetcher->getVideos();
std::sort(listVideos->begin(), listVideos->end(), Video::lessThan);
for(int i=0; i<listVideos->count(); i++)
connect(listVideos->at(i), SIGNAL(videoStatusChanged()), this, SLOT(updateUIRequest()), Qt::UniqueConnection );
modelListVideo->removeRows(0, modelListVideo->rowCount());
modelListVideo->setRowCount(listVideos->count());
Video *vid;
for(int i=0; i<listVideos->count(); i++)
{
vid = listVideos->at(i);
if(vid->getStatus() == videoDownloading)
isCurrentlyDownloading++;
modelListVideo->setItem(i, 0, new QStandardItem(vid->getTitle()));
modelListVideo->setItem(i, 1, new QStandardItem(vid->getCode()));
QStandardItem *item = new QStandardItem();
QImage itemIcon;
switch( vid->getStatus() )
{
case videoDoneDownloaded :
itemIcon.load(":downloaded_small");
break;
case videoDownloading :
itemIcon.load(":downloading_small");
break;
case videoNotDownloaded :
itemIcon.load(":not_downloaded_small");
break;
case videoError :
itemIcon.load(":error_small");
break;
}
itemIcon.scaled(QSize(5, 5), Qt::KeepAspectRatio);
item->setData(QVariant(QPixmap::fromImage(itemIcon)), Qt::DecorationRole);
modelListVideo->setItem(i, 2, item);
}
ui->widgetListVideos->setModel(modelListVideo);
ui->widgetListVideos->setCurrentIndex(currentlySelected);
if(modelListVideo->rowCount() == 0)
{
//Display the login options
ui->widgetListVideos->hide();
ui->loginBox->show();
}
else
{
//Display the list of videos
ui->widgetListVideos->show();
ui->loginBox->hide();
}
if( (isCurrentlyDownloading == 0) && (!pauseAction->isChecked()) )
downloadVideo();
}
void MainWindow::downloadVideo(){
if( (this->downloadEnable) && (this->YoutubeDlInstalled) ){
QList<Video *> *listvid = feedFetcher->getVideos();
std::sort(listvid->begin(), listvid->end(), Video::lessThan);
for(int i=0; i<listvid->count(); i++){
if( listvid->at(i)->getStatus() != videoDoneDownloaded ){
connect(listvid->at(i), SIGNAL(videoDownloaded(Video *)), this, SLOT(videoDoneDownloading(Video *)));
connect(listvid->at(i), SIGNAL(videoDownloadStarted(Video*)), this, SLOT(videoStartDownloading(Video*)));
connect(this, SIGNAL(stopDownloading()), listvid->at(i), SLOT(stopDownload()));
if( listvid->at(i)->download() == true )
break;
}
}
}
}
void MainWindow::installYoutubeDl()
{
QString installedVersion, currentLastVersion(CURRENT_VERSION);
installedVersion = settings->value("yt-dl_version", "").toString();
if(QString::compare(installedVersion, currentLastVersion, Qt::CaseInsensitive))
{
#ifdef Q_OS_LINUX
QFile srcFile(":/youtube-dl-linux");
QFile dstFile(*pathToFiles+"/youtube-dl.tar.gz");
#else
QFile srcFile(":/youtube-dl-windows");
QFile dstFile(*pathToFiles+"/youtube-dl.exe");
#endif
srcFile.open(QIODevice::ReadOnly);
if (dstFile.open(QIODevice::ReadWrite)) {
dstFile.write(srcFile.readAll());
}
srcFile.close();
dstFile.close();
#ifdef Q_OS_LINUX
QFile installFolder(*pathToFiles+"/youtube-dl");
if(installFolder.exists())
installFolder.remove();
installProc = new QProcess();
installProc->start("/bin/bash", QStringList() << "-c" << "tar -C "+*pathToFiles+"/ -xvf "+*pathToFiles+"/youtube-dl.tar.gz");
connect(installProc, SIGNAL(finished(int)), this, SLOT(doneInstallingYoutubeDl()));
#else
doneInstallingYoutubeDl();
#endif
}
else
{
doneInstallingYoutubeDl();
}
}
void MainWindow::doneInstallingYoutubeDl(){
this->YoutubeDlInstalled = true;
#ifdef Q_OS_LINUX
QFile file(*pathToFiles+"/youtube-dl.tar.gz");
file.remove();
#endif
settings->setValue("yt-dl_version", CURRENT_VERSION_YOUTUBE_DL);
updateRSSFeed();
}
void MainWindow::videoStartDownloading(Video *){
updateUIRequest();
}
void MainWindow::videoDoneDownloading(Video *vid){
disconnect(vid, SLOT(stopDownload()));
QString desktop;
bool isUnity;
desktop = getenv("XDG_CURRENT_DESKTOP");
isUnity = (desktop.toLower() == "unity");
if(isUnity) //only use this in unity
{
system("notify-send 'Video downloaded' '"+vid->getTitle().toUtf8()+"' -i "+pathToFiles->toUtf8()+"/icon.png -t 5000");
}
else
{
trayIcon->showMessage("Video downloaded", vid->getTitle().toUtf8(), QSystemTrayIcon::Information, 5000);
}
updateUIRequest();
}
void MainWindow::settingsChanged()
{
updateUIRequest();
}
void MainWindow::on_browse_clicked()
{
QString path = QFileDialog::getExistingDirectory (this, tr("Directory"));
if ( path.isNull() == false )
{
ui->downloadDestination->setText(path+"/");
}
}
void MainWindow::on_downloadDestination_textChanged()
{
settings->setValue("destination", ui->downloadDestination->text());
}
void MainWindow::createTrayIcon(){
showAction = new QAction(tr("&Show"), this);
showAction->setCheckable(true);
connect(showAction, SIGNAL(triggered()), this, SLOT(showWindow()));
pauseAction = new QAction(tr("&Pause"), this);
pauseAction->setCheckable(true);
connect(pauseAction, SIGNAL(triggered()), this, SLOT(pauseResume()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(showAction);
trayIconMenu->addAction(pauseAction);
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setIcon(QIcon(":/images/icon.png"));
trayIcon->show();
}
void MainWindow::showWindow()
{
if(!showAction->isChecked())
{
this->hide();
}
else
{
this->show();
this->raise();
}
}
void MainWindow::updateRSSFeed()
{
statusBarText.setText("Fetching");
feedFetcher->fetch();
}
void MainWindow::doneUpdatingRSSFeed()
{
statusBarText.setText("Last fetched at : " + QTime::currentTime().toString("H:m:s a"));
updateUIRequest();
}
void MainWindow::on_actionQuite_triggered()
{
QApplication::quit();
}
void MainWindow::closeEvent(QCloseEvent *event){
//we hide the window
this->hide();
showAction->setChecked(false);
//an ignore the close event
event->ignore();
}
void MainWindow::on_widgetListVideos_customContextMenuRequested(const QPoint &pos)
{
Video *vid;
QItemSelectionModel *selections = ui->widgetListVideos->selectionModel();
QModelIndexList selected = selections->selectedRows();
QMenu *menu=new QMenu(this);
bool containDownloadedVid = false;
bool containsUndownloadedVid = false;
if(actionReset != NULL)
delete actionReset;
actionReset = new QAction("Reset", this);
if(actionDownloaded != NULL)
delete actionDownloaded;
actionDownloaded = new QAction("Set as downloaded", this);
for( int i = 0 ; i < selected.size(); i++ )
{
vid = listVideos->at(selected[i].row());
if( vid->getStatus() == videoDoneDownloaded )
containDownloadedVid = true;
else
containsUndownloadedVid = true;
connect(actionReset, SIGNAL(triggered()), vid, SLOT(reset()));
connect(actionDownloaded, SIGNAL(triggered()), vid, SLOT(setAsDownloaded()));
}
if(containDownloadedVid == true)
menu->addAction(actionReset);
if(containsUndownloadedVid == true)
menu->addAction(actionDownloaded);
menu->popup(ui->widgetListVideos->viewport()->mapToGlobal(pos));
}
void MainWindow::on_loginButton_clicked()
{
QString url;
url = "https://accounts.google.com/o/oauth2/auth";
url += "?client_id="+clientId;
url += "&redirect_uri=urn:ietf:wg:oauth:2.0:oob";
url += "&scope=https://www.googleapis.com/auth/youtube";
url += "&response_type=code";
url += "&access_type=offline";
QDesktopServices::openUrl( url );
}
void MainWindow::on_authCode_textChanged()
{
QString url = "https://www.googleapis.com/oauth2/v4/token";
QUrlQuery postData;
postData.addQueryItem("code", ui->authCode->text());
postData.addQueryItem("client_id", clientId);
postData.addQueryItem("client_secret", clientSecret);
postData.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
postData.addQueryItem("grant_type", "authorization_code");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
networkManager.post(request, postData.toString(QUrl::FullyEncoded).toUtf8());
connect(&networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(decodeAuthToken(QNetworkReply*)));
}
void MainWindow::decodeAuthToken(QNetworkReply* reply)
{
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (statusCode >= 200 && statusCode < 300) {
QString data = (QString)reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(data.toUtf8());
QJsonObject jsonResponseObj = jsonResponse.object();
QString token = jsonResponseObj.value("access_token").toString();
QString refreshToken = jsonResponseObj.value("refresh_token").toString();
if(!refreshToken.isEmpty())
{
settings->setValue("refreshToken", refreshToken);
settings->sync();
updateRSSFeed();
}
}
}
void MainWindow::on_actionAbout_triggered()
{
About *aboutWindow = new About();
aboutWindow->show();
}
void MainWindow::pauseResume()
{
//If we just asked for the downloading to pause
if(pauseAction->isChecked())
{
QList<Video *> *listvid = feedFetcher->getVideos();
for(int currentVideo=0; currentVideo<listvid->count(); currentVideo++)
{
if( listvid->at(currentVideo)->getStatus() == videoDownloading )
listvid->at(currentVideo)->stopDownload();
}
}
updateUIRequest();
}
void MainWindow::on_actionSettings_triggered()
{
AppSettings *diskSpaceWindow = new AppSettings(this->settings, this);
connect(diskSpaceWindow, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
diskSpaceWindow->show();
}
| gpl-3.0 |
p-gebhard/QuickAnswer | docroot/WEB-INF/src/it/gebhard/qa/service/base/AnswerLocalServiceClpInvoker.java | 9198 | /**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* 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.
*/
package it.gebhard.qa.service.base;
import it.gebhard.qa.service.AnswerLocalServiceUtil;
import java.util.Arrays;
/**
* @author Brian Wing Shun Chan
*/
public class AnswerLocalServiceClpInvoker {
public AnswerLocalServiceClpInvoker() {
_methodName0 = "addAnswer";
_methodParameterTypes0 = new String[] { "it.gebhard.qa.model.Answer" };
_methodName1 = "createAnswer";
_methodParameterTypes1 = new String[] { "long" };
_methodName2 = "deleteAnswer";
_methodParameterTypes2 = new String[] { "long" };
_methodName3 = "deleteAnswer";
_methodParameterTypes3 = new String[] { "it.gebhard.qa.model.Answer" };
_methodName4 = "dynamicQuery";
_methodParameterTypes4 = new String[] { };
_methodName5 = "dynamicQuery";
_methodParameterTypes5 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName6 = "dynamicQuery";
_methodParameterTypes6 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int"
};
_methodName7 = "dynamicQuery";
_methodParameterTypes7 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int",
"com.liferay.portal.kernel.util.OrderByComparator"
};
_methodName8 = "dynamicQueryCount";
_methodParameterTypes8 = new String[] {
"com.liferay.portal.kernel.dao.orm.DynamicQuery"
};
_methodName9 = "fetchAnswer";
_methodParameterTypes9 = new String[] { "long" };
_methodName10 = "getAnswer";
_methodParameterTypes10 = new String[] { "long" };
_methodName11 = "getPersistedModel";
_methodParameterTypes11 = new String[] { "java.io.Serializable" };
_methodName12 = "getAnswers";
_methodParameterTypes12 = new String[] { "int", "int" };
_methodName13 = "getAnswersCount";
_methodParameterTypes13 = new String[] { };
_methodName14 = "updateAnswer";
_methodParameterTypes14 = new String[] { "it.gebhard.qa.model.Answer" };
_methodName15 = "updateAnswer";
_methodParameterTypes15 = new String[] {
"it.gebhard.qa.model.Answer", "boolean"
};
_methodName62 = "getBeanIdentifier";
_methodParameterTypes62 = new String[] { };
_methodName63 = "setBeanIdentifier";
_methodParameterTypes63 = new String[] { "java.lang.String" };
_methodName68 = "getAnswersForQuestion";
_methodParameterTypes68 = new String[] { "it.gebhard.qa.model.Question" };
_methodName69 = "deleteAnswer";
_methodParameterTypes69 = new String[] { "it.gebhard.qa.model.Answer" };
_methodName70 = "getComments";
_methodParameterTypes70 = new String[] { "it.gebhard.qa.model.Answer" };
}
public Object invokeMethod(String name, String[] parameterTypes,
Object[] arguments) throws Throwable {
if (_methodName0.equals(name) &&
Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) {
return AnswerLocalServiceUtil.addAnswer((it.gebhard.qa.model.Answer)arguments[0]);
}
if (_methodName1.equals(name) &&
Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) {
return AnswerLocalServiceUtil.createAnswer(((Long)arguments[0]).longValue());
}
if (_methodName2.equals(name) &&
Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) {
return AnswerLocalServiceUtil.deleteAnswer(((Long)arguments[0]).longValue());
}
if (_methodName3.equals(name) &&
Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) {
return AnswerLocalServiceUtil.deleteAnswer((it.gebhard.qa.model.Answer)arguments[0]);
}
if (_methodName4.equals(name) &&
Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) {
return AnswerLocalServiceUtil.dynamicQuery();
}
if (_methodName5.equals(name) &&
Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) {
return AnswerLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
}
if (_methodName6.equals(name) &&
Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) {
return AnswerLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
((Integer)arguments[1]).intValue(),
((Integer)arguments[2]).intValue());
}
if (_methodName7.equals(name) &&
Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) {
return AnswerLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0],
((Integer)arguments[1]).intValue(),
((Integer)arguments[2]).intValue(),
(com.liferay.portal.kernel.util.OrderByComparator)arguments[3]);
}
if (_methodName8.equals(name) &&
Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) {
return AnswerLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]);
}
if (_methodName9.equals(name) &&
Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) {
return AnswerLocalServiceUtil.fetchAnswer(((Long)arguments[0]).longValue());
}
if (_methodName10.equals(name) &&
Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) {
return AnswerLocalServiceUtil.getAnswer(((Long)arguments[0]).longValue());
}
if (_methodName11.equals(name) &&
Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) {
return AnswerLocalServiceUtil.getPersistedModel((java.io.Serializable)arguments[0]);
}
if (_methodName12.equals(name) &&
Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) {
return AnswerLocalServiceUtil.getAnswers(((Integer)arguments[0]).intValue(),
((Integer)arguments[1]).intValue());
}
if (_methodName13.equals(name) &&
Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) {
return AnswerLocalServiceUtil.getAnswersCount();
}
if (_methodName14.equals(name) &&
Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) {
return AnswerLocalServiceUtil.updateAnswer((it.gebhard.qa.model.Answer)arguments[0]);
}
if (_methodName15.equals(name) &&
Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) {
return AnswerLocalServiceUtil.updateAnswer((it.gebhard.qa.model.Answer)arguments[0],
((Boolean)arguments[1]).booleanValue());
}
if (_methodName62.equals(name) &&
Arrays.deepEquals(_methodParameterTypes62, parameterTypes)) {
return AnswerLocalServiceUtil.getBeanIdentifier();
}
if (_methodName63.equals(name) &&
Arrays.deepEquals(_methodParameterTypes63, parameterTypes)) {
AnswerLocalServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);
}
if (_methodName68.equals(name) &&
Arrays.deepEquals(_methodParameterTypes68, parameterTypes)) {
return AnswerLocalServiceUtil.getAnswersForQuestion((it.gebhard.qa.model.Question)arguments[0]);
}
if (_methodName69.equals(name) &&
Arrays.deepEquals(_methodParameterTypes69, parameterTypes)) {
return AnswerLocalServiceUtil.deleteAnswer((it.gebhard.qa.model.Answer)arguments[0]);
}
if (_methodName70.equals(name) &&
Arrays.deepEquals(_methodParameterTypes70, parameterTypes)) {
return AnswerLocalServiceUtil.getComments((it.gebhard.qa.model.Answer)arguments[0]);
}
throw new UnsupportedOperationException();
}
private String _methodName0;
private String[] _methodParameterTypes0;
private String _methodName1;
private String[] _methodParameterTypes1;
private String _methodName2;
private String[] _methodParameterTypes2;
private String _methodName3;
private String[] _methodParameterTypes3;
private String _methodName4;
private String[] _methodParameterTypes4;
private String _methodName5;
private String[] _methodParameterTypes5;
private String _methodName6;
private String[] _methodParameterTypes6;
private String _methodName7;
private String[] _methodParameterTypes7;
private String _methodName8;
private String[] _methodParameterTypes8;
private String _methodName9;
private String[] _methodParameterTypes9;
private String _methodName10;
private String[] _methodParameterTypes10;
private String _methodName11;
private String[] _methodParameterTypes11;
private String _methodName12;
private String[] _methodParameterTypes12;
private String _methodName13;
private String[] _methodParameterTypes13;
private String _methodName14;
private String[] _methodParameterTypes14;
private String _methodName15;
private String[] _methodParameterTypes15;
private String _methodName62;
private String[] _methodParameterTypes62;
private String _methodName63;
private String[] _methodParameterTypes63;
private String _methodName68;
private String[] _methodParameterTypes68;
private String _methodName69;
private String[] _methodParameterTypes69;
private String _methodName70;
private String[] _methodParameterTypes70;
} | gpl-3.0 |
mdarse/Phraseanet | lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php | 25272 | <?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2015 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Controller\Admin;
use Alchemy\Phrasea\Application\Helper\UserQueryAware;
use Alchemy\Phrasea\Authentication\ACLProvider;
use Alchemy\Phrasea\Authentication\Authenticator;
use Alchemy\Phrasea\Controller\Controller;
use Alchemy\Phrasea\Model\Manipulator\TaskManipulator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DataboxController extends Controller
{
use UserQueryAware;
/**
* @param Request $request
* @param integer $databox_id
* @return Response
*/
public function getDatabase(Request $request, $databox_id)
{
$databox = $this->findDataboxById($databox_id);
switch ($errorMsg = $request->query->get('error')) {
case 'file-error':
$errorMsg = $this->app->trans('Error while sending the file');
break;
case 'file-invalid':
$errorMsg = $this->app->trans('Invalid file format');
break;
case 'file-too-big':
$errorMsg = $this->app->trans('The file is too big');
break;
}
return $this->render('admin/databox/databox.html.twig', [
'databox' => $databox,
'showDetail' => (int)$request->query->get("sta") < 1,
'errorMsg' => $errorMsg,
'reloadTree' => $request->query->get('reload-tree') === '1'
]);
}
/**
* Get databox CGU's
*
* @param integer $databox_id The requested databox
* @return Response
*/
public function getDatabaseCGU($databox_id)
{
return $this->render('admin/databox/cgus.html.twig', [
'languages' => $this->app['locales.available'],
'cgus' => $this->findDataboxById($databox_id)->get_cgus(),
'current_locale' => $this->app['locale'],
]);
}
/**
* Delete a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function deleteBase(Request $request, $databox_id)
{
$databox = null;
$success = false;
$msg = $this->app->trans('An error occured');
try {
$databox = $this->findDataboxById($databox_id);
if ($databox->get_record_amount() > 0) {
$msg = $this->app->trans('admin::base: vider la base avant de la supprimer');
} else {
$databox->unmount_databox();
$this->getApplicationBox()->write_databox_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$databox,
null,
\databox::PIC_PDF
);
$databox->delete();
$success = true;
$msg = $this->app->trans('Successful removal');
}
} catch (\Exception $e) {
}
if (!$databox) {
$this->app->abort(404, $this->app->trans('admin::base: databox not found', ['databox_id' => $databox_id]));
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg,
'sbas_id' => $databox->get_sbas_id()
]);
}
$params = [
'databox_id' => $databox->get_sbas_id(),
'success' => (int) $success,
];
if ($databox->get_record_amount() > 0) {
$params['error'] = 'databox-not-empty';
}
return $this->app->redirectPath('admin_database', $params);
}
public function setLabels(Request $request, $databox_id)
{
if (null === $labels = $request->request->get('labels')) {
$this->app->abort(400, $this->app->trans('Missing labels parameter'));
}
if (false === is_array($labels)) {
$this->app->abort(400, $this->app->trans('Invalid labels parameter'));
}
$databox = $this->findDataboxById($databox_id);
$success = true;
try {
foreach ($this->app['locales.available'] as $code => $language) {
if (!isset($labels[$code])) {
continue;
}
$value = $labels[$code] ?: null;
$databox->set_label($code, $value);
}
} catch (\Exception $e) {
$success = false;
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
]);
}
return $this->app->redirect(sprintf(
'/admin/databox/%d/?success=%d&reload-tree=1',
$databox->get_sbas_id(),
(int) $success
));
}
/**
* Reindex databox content
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function reindex(Request $request, $databox_id)
{
$success = false;
try {
$this->findDataboxById($databox_id)->reindex();
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => (int) $success,
]);
}
/**
* Make a databox indexable
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function setIndexable(Request $request, $databox_id)
{
$success = false;
try {
$databox = $this->findDataboxById($databox_id);
$indexable = !!$request->request->get('indexable', false);
$this->getApplicationBox()->set_databox_indexable($databox, $indexable);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => (int) $success,
]);
}
/**
* Update databox CGU's
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return RedirectResponse
*/
public function updateDatabaseCGU(Request $request, $databox_id)
{
$databox = $this->findDataboxById($databox_id);
try {
foreach ($request->request->get('TOU', []) as $loc => $terms) {
$databox->update_cgus($loc, $terms, !!$request->request->get('valid', false));
}
} catch (\Exception $e) {
return $this->app->redirectPath('admin_database_display_cgus', [
'databox_id' => $databox_id,
'success' => 0,
]);
}
return $this->app->redirectPath('admin_database_display_cgus', [
'databox_id' => $databox_id,
'success' => 1,
]);
}
/**
* Mount a collection on a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @param integer $collection_id The requested collection id
* @return RedirectResponse
*/
public function mountCollection(Request $request, $databox_id, $collection_id)
{
$connection = $this->getApplicationBox()->get_connection();
$connection->beginTransaction();
try {
/** @var Authenticator $authenticator */
$authenticator = $this->app->getAuthenticator();
$baseId = \collection::mount_collection(
$this->app,
$this->findDataboxById($databox_id),
$collection_id,
$authenticator->getUser()
);
$othCollSel = (int) $request->request->get("othcollsel") ?: null;
if (null !== $othCollSel) {
$query = $this->createUserQuery();
$n = 0;
/** @var ACLProvider $aclProvider */
$aclProvider = $this->app['acl'];
while ($n < $query->on_base_ids([$othCollSel])->get_total()) {
$results = $query->limit($n, 50)->execute()->get_results();
foreach ($results as $user) {
$aclProvider->get($user)->duplicate_right_from_bas($othCollSel, $baseId);
}
$n += 50;
}
}
$connection->commit();
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'mount' => 'ok',
]);
} catch (\Exception $e) {
$connection->rollBack();
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'mount' => 'ko',
]);
}
}
/**
* Set a new logo for a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return RedirectResponse
*/
public function sendLogoPdf(Request $request, $databox_id)
{
try {
if (null !== ($file = $request->files->get('newLogoPdf')) && $file->isValid()) {
if ($file->getClientSize() < 65536) {
$databox = $this->findDataboxById($databox_id);
$this->getApplicationBox()->write_databox_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$databox,
$file,
\databox::PIC_PDF
);
unlink($file->getPathname());
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => '1',
]);
} else {
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => '0',
'error' => 'file-too-big',
]);
}
} else {
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => '0',
'error' => 'file-invalid',
]);
}
} catch (\Exception $e) {
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'success' => '0',
'error' => 'file-error',
]);
}
}
/**
* Delete an existing logo for a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function deleteLogoPdf(Request $request, $databox_id)
{
$success = false;
try {
$this->getApplicationBox()->write_databox_pic(
$this->app['media-alchemyst'],
$this->app['filesystem'],
$this->findDataboxById($databox_id),
null,
\databox::PIC_PDF
);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful removal') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
// TODO: Check whether html call is still valid
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'error' => 'file-too-big',
]);
}
/**
* Clear databox logs
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function clearLogs(Request $request, $databox_id)
{
$success = false;
try {
$this->findDataboxById($databox_id)->clear_logs();
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
// TODO: Check whether html call is still valid
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'error' => 'file-too-big',
]);
}
/**
* Change the name of a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function changeViewName(Request $request, $databox_id)
{
if (null === $viewName = $request->request->get('viewname')) {
$this->app->abort(400, $this->app->trans('Missing view name parameter'));
}
$success = false;
try {
$this->findDataboxById($databox_id)->set_viewname($viewName);
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
// TODO: Check whether html call is still valid
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'error' => 'file-too-big',
]);
}
/**
* Unmount a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function unmountDatabase(Request $request, $databox_id)
{
$success = false;
try {
$databox = $this->findDataboxById($databox_id);
$databox->unmount_databox();
$success = true;
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
$msg = $success
? $this->app->trans('The publication has been stopped')
: $this->app->trans('An error occured');
return $this->app->json([
'success' => $success,
'msg' => $msg,
'sbas_id' => $databox_id
]);
}
return $this->app->redirectPath('admin_databases', [
'reload-tree' => 1,
]);
}
/**
* Empty a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function emptyDatabase(Request $request, $databox_id)
{
$msg = $this->app->trans('An error occurred');
$success = false;
$taskCreated = false;
try {
$databox = $this->findDataboxById($databox_id);
foreach ($databox->get_collections() as $collection) {
if ($collection->get_record_amount() <= 500) {
$collection->empty_collection(500);
} else {
/** @var TaskManipulator $taskManipulator */
$taskManipulator = $this->app['manipulator.task'];
$taskManipulator->createEmptyCollectionJob($collection);
}
}
$msg = $this->app->trans('Base empty successful');
$success = true;
if ($taskCreated) {
$msg = $this->app->trans('A task has been created, please run it to complete empty collection');
}
} catch (\Exception $e) {
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $msg,
'sbas_id' => $databox_id,
]);
}
// TODO: Can this method be called as HTML?
return $this->app->redirectPath('admin_database', [
'databox_id' => $databox_id,
'error' => 'file-too-big',
]);
}
/**
* Get number of indexed items for a databox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse
*/
public function progressBarInfos(Request $request, $databox_id)
{
if (!$request->isXmlHttpRequest() || 'json' !== $request->getRequestFormat()) {
$this->app->abort(400, $this->app->trans('Bad request format, only JSON is allowed'));
}
$appbox = $this->getApplicationBox();
$ret = [
'success' => false,
'sbas_id' => null,
'msg' => $this->app->trans('An error occured'),
'indexable' => false,
'viewname' => null,
'printLogoURL' => null,
'counts' => null,
];
try {
$databox = $this->findDataboxById($databox_id);
$ret['sbas_id'] = $databox_id;
$ret['indexable'] = $appbox->is_databox_indexable($databox);
$ret['viewname'] = (($databox->get_dbname() == $databox->get_viewname())
? $this->app->trans('admin::base: aucun alias')
: $databox->get_viewname());
$ret['counts'] = $databox->get_counts();
if ($this->app['filesystem']->exists($this->app['root.path'] . '/config/minilogos/logopdf_' . $databox_id . '.jpg')) {
$ret['printLogoURL'] = '/custom/minilogos/logopdf_' . $databox_id . '.jpg';
}
$ret['success'] = true;
$ret['msg'] = $this->app->trans('Successful update');
} catch (\Exception $e) {
}
return $this->app->json($ret);
}
/**
* Display page for reorder collections on a databox
*
* @param integer $databox_id The requested databox
* @return Response
*/
public function getReorder($databox_id)
{
$acl = $this->getAclForUser();
return $this->render('admin/collection/reorder.html.twig', [
'collections' => $acl->get_granted_base([], [$databox_id]),
]);
}
/**
* Apply collection reorder changes
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return JsonResponse|RedirectResponse
*/
public function setReorder(Request $request, $databox_id)
{
try {
foreach ($request->request->get('order', []) as $data) {
$collection = \collection::get_from_base_id($this->app, $data['id']);
$collection->set_ord($data['offset']);
}
$success = true;
} catch (\Exception $e) {
$success = false;
}
if ('json' === $request->getRequestFormat()) {
return $this->app->json([
'success' => $success,
'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'),
'sbas_id' => $databox_id,
]);
}
return $this->app->redirectPath('admin_database_display_collections_order', [
'databox_id' => $databox_id,
'success' => (int) $success,
]);
}
/**
* Display page to create a new collection
*
* @return Response
*/
public function getNewCollection()
{
return $this->render('admin/collection/create.html.twig');
}
/**
* Create a new collection
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return Response
*/
public function createCollection(Request $request, $databox_id)
{
if (($name = trim($request->request->get('name', ''))) === '') {
return $this->app->redirectPath('admin_database_display_new_collection_form', [
'databox_id' => $databox_id,
'error' => 'name',
]);
}
try {
$databox = $this->findDataboxById($databox_id);
$collection = \collection::create(
$this->app, $databox,
$this->getApplicationBox(),
$name,
$this->getAuthenticator()->getUser()
);
if (($request->request->get('ccusrothercoll') === "on")
&& (null !== $othcollsel = $request->request->get('othcollsel'))) {
$query = $this->createUserQuery();
$total = $query->on_base_ids([$othcollsel])->get_total();
$n = 0;
while ($n < $total) {
$results = $query->limit($n, 20)->execute()->get_results();
foreach ($results as $user) {
$this->getAclForUser($user)->duplicate_right_from_bas($othcollsel, $collection->get_base_id());
}
$n += 20;
}
}
return $this->app->redirectPath('admin_display_collection', [
'bas_id' => $collection->get_base_id(),
'success' => 1,
'reload-tree' => 1,
]);
} catch (\Exception $e) {
return $this->app->redirectPath('admin_database_submit_collection', [
'databox_id' => $databox_id,
'error' => 'error',
]);
}
}
/**
* Display page to get some details on a appbox
*
* @param Request $request The current HTTP request
* @param integer $databox_id The requested databox
* @return Response
*/
public function getDetails(Request $request, $databox_id)
{
$databox = $this->findDataboxById($databox_id);
$details = [];
$total = ['total_subdefs' => 0, 'total_size' => 0];
foreach ($databox->get_record_details($request->query->get('sort')) as $collName => $colDetails) {
$details[$collName] = [
'total_subdefs' => 0,
'total_size' => 0,
'medias' => []
];
foreach ($colDetails as $subdefName => $subdefDetails) {
$details[$collName]['total_subdefs'] += $subdefDetails['n'];
$total['total_subdefs'] += $subdefDetails['n'];
$details[$collName]['total_size'] += $subdefDetails['siz'];
$total['total_size'] += $subdefDetails['siz'];
$details[$collName]['medias'][] = [
'subdef_name' => $subdefName,
'total_subdefs' => $subdefDetails['n'],
'total_size' => $subdefDetails['siz'],
];
}
}
return $this->render('admin/databox/details.html.twig', [
'databox' => $databox,
'table' => $details,
'total' => $total
]);
}
}
| gpl-3.0 |
jayeshnair/ctp | theme/panel/theme-options/typography-buttons.php | 701 | <?php
/**
* Your Inspiration Themes
*
* @package WordPress
* @subpackage Your Inspiration Themes
* @author Your Inspiration Themes Team <info@yithemes.com>
*
* This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
*/
function yit_add_typography_buttons_tab( $tabs ) {
$new_tab = array( 'buttons' => __( 'Buttons', 'yit' ) );
yit_array_splice_assoc( $tabs['typography'], $new_tab, 'footer' );
return $tabs;
}
add_filter( 'yit_admin_submenu_theme_options', 'yit_add_typography_buttons_tab' ); | gpl-3.0 |
angusmillar/PeterPiper | TestPeterPiper/TestModel/TestAddHocHl7V2Model.cs | 73200 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PeterPiper.Hl7.V2.Model;
using PeterPiper.Hl7.V2.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestPeterPiper.TestModel
{
[TestClass]
public class UnitTestContentModel
{
[TestMethod]
[TestCategory("Content")]
public void TestContentTypeCreate()
{
var oContent = Creator.Content("The data for a content", PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.AreEqual("The data for a content", oContent.AsString, "AsString Failed on get");
Assert.AreEqual("The data for a content", oContent.AsStringRaw, "AsStringRaw Failed on get");
Assert.AreEqual("The data for a content", oContent.ToString(), "ToString Failed on get");
}
[TestMethod]
[TestCategory("Content")]
public void TestContentTypeExceptions()
{
IContent obj = null;
try
{
obj = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.Delimiters.Field.ToString(), PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.Delimiters.Component.ToString(), PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.Delimiters.SubComponent.ToString(), PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.Delimiters.Repeat.ToString(), PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.Delimiters.Escape.ToString(), PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content("Test Data", PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
obj.AsString = PeterPiper.Hl7.V2.Support.Standard.Delimiters.Escape.ToString();
Assert.Fail("An exception should have been thrown on setting AsString");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
try
{
obj = Creator.Content("Test Data", PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
obj.AsStringRaw = PeterPiper.Hl7.V2.Support.Standard.Delimiters.Escape.ToString();
Assert.Fail("An exception should have been thrown on setting AsString");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Content data cannot contain HL7 V2 Delimiters, maybe you should be using 'AsStringRaw' if you are trying to insert already escaped data.", ae.Message);
}
}
}
[TestClass]
public class UnitTestSubComponentModel
{
[TestMethod]
[TestCategory("Content")]
public void TestSubComponentCreate()
{
var oSubComonentWithEscapes = Creator.SubComponent("\\N\\this is not Highlighted\\H\\ This is higlighted \\N\\ This is not, this is hex \\X0xC2\\ this is local \\Ztesttest\\ this is field \\F\\ this is Compponet \\S\\ this is SubCompoent \\T\\ repeat \\R\\ this is escape \\E\\ done ");
var oSubComonentPlainOLDText = Creator.SubComponent("This is plan old test");
}
[TestMethod]
[TestCategory("Content")]
public void TestSubComponentAddingContent()
{
string FullTestStringWithEscapes = "not highlighted\\H\\ Highlighted \\N\\highlighted ended \\H\\Added highlight \\N\\Added not highlight \\H\\\\N\\";
string FullTestStringWithOutEscapes = "not highlighted Highlighted highlighted ended Added highlight Added not highlight ";
var oSubComonent = Creator.SubComponent("not highlighted\\H\\ Highlighted \\N\\highlighted ended ");
var oContentEscapeHiglightStart = Creator.Content("H", PeterPiper.Hl7.V2.Support.Content.ContentType.Escape);
var oContentEscapeHiglightEnd = Creator.Content("N", PeterPiper.Hl7.V2.Support.Content.ContentType.Escape);
var oContent1 = Creator.Content("Added highlight ", PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
var oContent2 = Creator.Content("Added not highlight ", PeterPiper.Hl7.V2.Support.Content.ContentType.Text);
oSubComonent.Add(oContentEscapeHiglightStart);
oSubComonent.Add(oContent1);
oSubComonent.Add(oContentEscapeHiglightEnd);
oSubComonent.Add(oContent2);
oSubComonent.Add(oContentEscapeHiglightStart.Clone());
oSubComonent.Add(oContentEscapeHiglightEnd.Clone());
Assert.AreEqual(oSubComonent.AsStringRaw, FullTestStringWithEscapes);
Assert.AreEqual(oSubComonent.AsString, FullTestStringWithOutEscapes);
Assert.AreEqual(FullTestStringWithOutEscapes, oSubComonent.ToString());
oSubComonent.AsString = FullTestStringWithOutEscapes;
Assert.AreEqual(oSubComonent.AsStringRaw, FullTestStringWithOutEscapes);
Assert.AreEqual(oSubComonent.AsString, FullTestStringWithOutEscapes);
Assert.AreEqual(oSubComonent.ToString(), FullTestStringWithOutEscapes);
oSubComonent.AsStringRaw = FullTestStringWithEscapes;
Assert.AreEqual(FullTestStringWithEscapes, oSubComonent.AsStringRaw);
Assert.AreEqual(oSubComonent.AsString, FullTestStringWithOutEscapes);
Assert.AreEqual(oSubComonent.ToString(), FullTestStringWithOutEscapes);
oSubComonent = Creator.SubComponent("\\H\\This is bold text\\N\\");
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOn, oSubComonent.Content(0).EscapeMetaData.EscapeType);
Assert.AreEqual("This is bold text", oSubComonent.Content(1).AsStringRaw);
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOff, oSubComonent.Content(2).EscapeMetaData.EscapeType);
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Content.ContentType.Escape, oSubComonent.Content(0).ContentType, "Incorrect ContentType");
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Content.ContentType.Text, oSubComonent.Content(1).ContentType, "Incorrect ContentType");
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Content.ContentType.Escape, oSubComonent.Content(2).ContentType, "Incorrect ContentType");
oSubComonent = Creator.SubComponent("\\H\\This is bold text\\N\\Not bold Text");
oSubComonent.Insert(10, Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.NewLine));
Assert.AreEqual(oSubComonent.Content(4).EscapeMetaData.EscapeType, PeterPiper.Hl7.V2.Support.Standard.EscapeType.NewLine, "Incorrect ContentType");
Assert.AreEqual("\\H\\This is bold text\\N\\Not bold Text\\.br\\", oSubComonent.AsStringRaw, "Incorrect ContentType");
oSubComonent.RemoveContentAt(2);
Assert.AreEqual("\\H\\This is bold textNot bold Text\\.br\\", oSubComonent.AsStringRaw, "Incorrect ContentType");
oSubComonent.Insert(1, Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.NewLine));
Assert.AreEqual("\\H\\\\.br\\This is bold textNot bold Text\\.br\\", oSubComonent.AsStringRaw, "Incorrect ContentType");
}
[TestMethod]
[TestCategory("Content")]
public void TestSubComponentSettingContent()
{
var oSubComp = Creator.SubComponent();
if (oSubComp.Content(5).AsString == string.Empty)
{
oSubComp.Content(5).AsString = "New Text";
}
var oConentHEscape = Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOn);
var oConentText = Creator.Content("This will be highlighted");
var oConentNEscape = Creator.Content("N", PeterPiper.Hl7.V2.Support.Content.ContentType.Escape);
oSubComp.ClearAll();
oSubComp.Add(oConentHEscape);
oSubComp.Add(oConentText);
oSubComp.Add(oConentNEscape);
Assert.AreEqual(oSubComp.Content(0).AsString, String.Empty);
Assert.AreEqual(oSubComp.Content(0).AsStringRaw, "H");
Assert.AreEqual(oSubComp.Content(1).AsString, "This will be highlighted");
Assert.AreEqual(oSubComp.Content(1).AsStringRaw, "This will be highlighted");
Assert.AreEqual(oSubComp.Content(2).AsString, String.Empty);
Assert.AreEqual(oSubComp.Content(2).AsStringRaw, "N");
Assert.AreEqual(oSubComp.AsStringRaw, "\\H\\This will be highlighted\\N\\");
Assert.AreEqual(oSubComp.AsString, "This will be highlighted");
oSubComp.Insert(1, Creator.Content(" 2nd "));
Assert.AreEqual(oSubComp.AsStringRaw, "\\H\\ 2nd This will be highlighted\\N\\", "Testing oSubComp.Add and AsString, ASStringRaw");
oSubComp.ClearAll();
oSubComp.Insert(99, Creator.Content("First "));
oSubComp.Insert(1, Creator.Content("Second "));
oSubComp.Insert(2, Creator.Content("Fourth "));
oSubComp.Insert(3, Creator.Content("Fith "));
oSubComp.Insert(4, Creator.Content("Sixth "));
oSubComp.Insert(5, Creator.Content("Seven "));
oSubComp.Insert(2, Creator.Content("Third "));
Assert.AreEqual(oSubComp.AsStringRaw, "First Second Third Fourth Fith Sixth Seven ", "Testing oSubComp.ContentInsertAfter");
oSubComp.ClearAll();
oSubComp.Insert(100, Creator.Content("First "));
oSubComp.Insert(0, Creator.Content("Second "));
oSubComp.Insert(0, Creator.Content("Fourth "));
oSubComp.Insert(0, Creator.Content("Fith "));
oSubComp.Insert(0, Creator.Content("Sixth "));
oSubComp.Insert(0, Creator.Content("Seven "));
oSubComp.Insert(4, Creator.Content("Third "));
Assert.AreEqual(oSubComp.AsStringRaw, "Seven Sixth Fith Fourth Third Second First ", "Testing oSubComp.ContentInsertBefore");
oSubComp.RemoveContentAt(3);
Assert.AreEqual(oSubComp.AsStringRaw, "Seven Sixth Fith Third Second First ", "testing oSubComp.AsStringRaw");
oSubComp.ClearAll();
oSubComp.Add(Creator.Content("First "));
oSubComp.Add(Creator.Content("Third "));
oSubComp.Add(Creator.Content("Fourth "));
oSubComp.Add(Creator.Content("Fith "));
oSubComp.Add(Creator.Content("Seven "));
oSubComp.Insert(1, Creator.Content("Second "));
oSubComp.Insert(5, Creator.Content("Sixth "));
oSubComp.RemoveContentAt(3);
Assert.AreEqual(oSubComp.AsStringRaw, "First Second Third Fith Sixth Seven ", "Testing oSubComp.Content mixure");
int Counter = 0;
foreach (var oContent in oSubComp.ContentList)
{
Assert.AreEqual(oContent.AsStringRaw, oSubComp.Content(Counter).AsStringRaw, "oSubComp.ContentList not equal to Content(index)");
Counter++;
}
}
[TestMethod]
[TestCategory("Content")]
public void TestSubComponentContentCount()
{
var oSubComp = Creator.SubComponent("First ");
oSubComp.Add(Creator.Content("Second "));
oSubComp.Add(Creator.Content("Third "));
oSubComp.Add(Creator.Content("Fourth "));
Assert.AreEqual(oSubComp.ContentCount, 4, "Testing oSubComp.ContentCount");
oSubComp.Content(10).AsStringRaw = "";
Assert.AreEqual(oSubComp.ContentCount, 4, "Testing oSubComp.ContentCount");
if (oSubComp.Content(10).AsStringRaw == "Something")
{
Assert.Fail("This should not equal anything");
}
Assert.AreEqual(oSubComp.ContentCount, 4, "Testing oSubComp.ContentCount with temp Content genertaed");
oSubComp.Content(10).AsStringRaw = "Ten ";
Assert.AreEqual(5, oSubComp.ContentCount, "Testing oSubComp.ContentCount with temp Content genertaed");
}
}
[TestClass]
public class UnitTestComponentModel
{
[TestMethod]
[TestCategory("Content")]
public void TestComponentCreate()
{
var oComponent = Creator.Component("First&Se\\e\\cond&\\H\\Third is Bold\\n\\&forth&fith");
Assert.AreEqual("First&Se\\e\\cond&\\H\\Third is Bold\\n\\&forth&fith", oComponent.AsStringRaw, "oComonentWithEscapes.AsStringRaw did not match create string");
oComponent.AsStringRaw = "";
oComponent.AsStringRaw = "First&Se\\e\\cond&\\H\\Third is Bold\\n\\&forth&fith";
Assert.AreEqual("First&Se\\e\\cond&\\H\\Third is Bold\\n\\&forth&fith", oComponent.AsStringRaw, "oComonentWithEscapes.AsStringRaw did not match Set StringRaw");
Assert.AreEqual("First&Se\\cond&Third is Bold&forth&fith", oComponent.AsString, "oComonentWithEscapes.AsString did not match Set StringRaw");
oComponent.AsString = "First&Men\\E\\Women&\\H\\Third is Bold\\n\\&forth&fith";
Assert.AreEqual("First\\T\\Men Women\\T\\Third is Bold\\T\\forth\\T\\fith", oComponent.AsStringRaw, "oComonentWithEscapes.AsStringRaw did not match Set StringRaw");
Assert.AreEqual("First&Men Women&Third is Bold&forth&fith", oComponent.AsString, "oComonentWithEscapes.AsString did not match Set StringRaw");
oComponent.AsStringRaw = "First&Second&&&&Six&&&&";
Assert.AreEqual("First&Second&&&&Six", oComponent.AsStringRaw, "Check trailing delimiters are removed");
Assert.AreEqual("Second", oComponent.SubComponent(2).AsString, ",oComonent.SubComponent failed to return correct data");
if (oComponent.SubComponent(100).AsString == "")
{
Assert.AreEqual(6, oComponent.SubComponentCount, ",oComonent.CountSubComponent is incorrect");
}
try
{
string test = oComponent.SubComponent(0).AsString;
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("SubComponent is a one based index, zero is not a valid index", ae.Message, "Exception should have been thrown on zero index for SubComponent");
}
oComponent.ClearAll();
Assert.AreEqual(0, oComponent.SubComponentCount, ",oComonent.CountSubComponent is incorrect");
oComponent.Add(Creator.SubComponent("First"));
oComponent.Add(Creator.SubComponent("Second"));
oComponent.Add(Creator.SubComponent("Third"));
oComponent.Add(Creator.SubComponent("Forth"));
Assert.AreEqual(4, oComponent.SubComponentCount, ",oComonent.CountSubComponent is incorrect");
Assert.AreEqual("First", oComponent.SubComponent(1).AsStringRaw, ",oComponent.SubComponent() returned incorrect");
Assert.AreEqual("Second", oComponent.SubComponent(2).AsString, ",oComponent.SubComponent() returned incorrect");
Assert.AreEqual("Third", oComponent.SubComponent(3).AsStringRaw, ",oComponent.SubComponent() returned incorrect");
Assert.AreEqual("Forth", oComponent.SubComponent(4).AsString, ",oComponent.SubComponent() returned incorrect");
Assert.AreEqual("First&Second&Third&Forth", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.RemoveSubComponentAt(4);
Assert.AreEqual("First&Second&Third", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.RemoveSubComponentAt(2);
Assert.AreEqual("First&Third", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.RemoveSubComponentAt(1);
oComponent.RemoveSubComponentAt(1);
Assert.AreEqual("", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.ClearAll();
oComponent.Insert(10, Creator.SubComponent("Third"));
oComponent.Insert(1, Creator.SubComponent("First"));
oComponent.Insert(2, Creator.SubComponent("Second"));
Assert.AreEqual("First&Second&&&&&&&&&&Third", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.ClearAll();
oComponent.Insert(1, Creator.SubComponent("First"));
oComponent.Insert(2, Creator.SubComponent("Second"));
oComponent.Add(Creator.SubComponent("Third"));
Assert.AreEqual("First&Second&Third", oComponent.AsString, ",oComponent.AsString returned incorrect");
oComponent.ClearAll();
oComponent.Add(Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOn));
oComponent.Add(Creator.Content("This is Bold"));
oComponent.Add(Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOff));
oComponent.Add(Creator.Content(Creator.EscapeData(PeterPiper.Hl7.V2.Support.Standard.EscapeType.Unknown, "HAHAHAHAH")));
Assert.AreEqual("\\H\\This is Bold\\N\\\\ZHAHAHAHAH\\", oComponent.AsStringRaw, ",oComponent.AsString returned incorrect");
oComponent.Set(3, Creator.Content(Creator.EscapeData(PeterPiper.Hl7.V2.Support.Standard.EscapeType.Unknown, "Boo")));
Assert.AreEqual("\\H\\This is Bold\\N\\\\ZBoo\\", oComponent.AsStringRaw, ",oComponent.AsString returned incorrect");
oComponent.Insert(2, Creator.Content("Not BOLD"));
Assert.AreEqual("\\H\\This is BoldNot BOLD\\N\\\\ZBoo\\", oComponent.AsStringRaw, ",oComponent.AsString returned incorrect");
//AsString = "Mater Hospital caters for Women \\Zhildren\\ Men";
oComponent.ClearAll();
oComponent.Add(Creator.Content("Mater Hospital", PeterPiper.Hl7.V2.Support.Content.ContentType.Text));
oComponent.Add(Creator.Content("C4568", PeterPiper.Hl7.V2.Support.Content.ContentType.Escape));
Assert.AreEqual("Mater Hospital", oComponent.AsString, ",oComponent.AsString returned incorrect");
Assert.AreEqual("Mater Hospital\\C4568\\", oComponent.AsStringRaw, ",oComponent.AsString returned incorrect");
oComponent.ClearAll();
oComponent.AsStringRaw = "Mater Hospital\\Q4568\\new line\\.sp+5\\";
Assert.AreEqual("Mater Hospitalnew line", oComponent.AsString, ",oComponent.AsString returned incorrect");
Assert.AreEqual("Mater Hospital\\Q4568\\new line\\.sp+5\\", oComponent.AsStringRaw, ",oComponent.AsStringRaw returned incorrect");
Assert.AreEqual(true, oComponent.Content(3).EscapeMetaData.IsFormattingCommand, ",.Content(3).EscapeMetaData.IsFormattingCommand returned incorrect");
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Standard.EscapeType.SkipVerticalSpaces, oComponent.Content(3).EscapeMetaData.EscapeType, "oComponent.Content(3).EscapeMetaData.EscapeType returned incorrect");
Assert.AreEqual(PeterPiper.Hl7.V2.Support.Standard.Escapes.SkipVerticalSpaces, oComponent.Content(3).EscapeMetaData.EscapeTypeCharater, ",oComponent.Content(3).EscapeMetaData.EscapeTypeCharater returned incorrect");
Assert.AreEqual("+5", oComponent.Content(3).EscapeMetaData.MetaData, ",.Content(3).EscapeMetaData.MetaData returned incorrect");
}
}
[TestClass]
public class UnitTestFieldModel
{
[TestMethod]
[TestCategory("Content")]
public void TestFieldCreate()
{
//Test setting data through create
string TestString = "first^Second^ThirdHasSubs1&ThirdHasSubs2^Forth^\\H\\Fith\\N\\";
var oField = Creator.Field(TestString);
Assert.AreEqual(TestString, oField.AsStringRaw, "oField.AsStringRaw did not match create string");
//Test setting data through StringRaw
oField.AsStringRaw = "";
oField.AsStringRaw = "First^Second1&Second2^\\H\\Third2 is Bold\\N\\^forth^fith";
Assert.AreEqual("First^Second1&Second2^\\H\\Third2 is Bold\\N\\^forth^fith", oField.AsStringRaw, "oField.AsStringRaw did not match Set StringRaw");
Assert.AreEqual("First^Second1&Second2^Third2 is Bold^forth^fith", oField.AsString, "oComonentWithEscapes.AsString did not match Set StringRaw");
//Test empty dilimeters are not kept
oField.AsStringRaw = "^^Third^Forth^^^^^^^^^^^^^^^^^^^^";
Assert.AreEqual("^^Third^Forth", oField.AsStringRaw, "oField.AsStringRaw did not match Set StringRaw");
Assert.AreEqual("^^Third^Forth", oField.AsString, "oField.AsString did not match Set StringRaw");
Assert.AreEqual("Forth", oField.Component(4).ToString(), "oField.Component(4).ToString() did not match Set StringRaw");
//Test inspect Component does not add Components
if (oField.Component(100).AsString == "")
{
Assert.AreEqual(4, oField.ComponentCount, ",oField.ComponentCount is incorrect");
}
//Test zero index exception
try
{
string test = oField.Component(0).AsString;
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Component is a one based index, zero is not a valid index", ae.Message, "Exception should have been thrown on zero index for Component");
}
//Test Append
oField.ClearAll();
Assert.AreEqual(0, oField.ComponentCount, ",oField.ComponentCount is incorrect");
oField.Add(Creator.Component("First"));
oField.Add(Creator.Component("Second"));
oField.Add(Creator.Component("Third"));
oField.Add(Creator.Component("Forth"));
//Test Component lookup
Assert.AreEqual(4, oField.ComponentCount, ",oComonent.CountSubComponent is incorrect");
Assert.AreEqual("First", oField.Component(1).AsStringRaw, ",oField.Component(1).AsStringRaw returned incorrect");
Assert.AreEqual("Second", oField.Component(2).AsString, ",oField.Component(2).AsStringRaw returned incorrect");
Assert.AreEqual("Third", oField.Component(3).AsStringRaw, ",oField.Component(3).AsStringRaw returned incorrect");
Assert.AreEqual("Forth", oField.Component(4).AsString, ",oField.Component(4).AsStringRaw returned incorrect");
Assert.AreEqual("First^Second^Third^Forth", oField.AsString, ",oField.AsString");
//Test RemoveAt
oField.RemoveComponentAt(4);
Assert.AreEqual("First^Second^Third", oField.AsString, ",oField.RemoveComponentAt(4) returned incorrect");
oField.RemoveComponentAt(2);
Assert.AreEqual("First^Third", oField.AsString, ",oField.RemoveComponentAt(2) returned incorrect");
oField.RemoveComponentAt(1);
oField.RemoveComponentAt(1);
Assert.AreEqual("", oField.AsString, ",oField.RemoveComponentAt() returned incorrect");
//Test InsertBefore
oField.ClearAll();
oField.Insert(10, Creator.Component("Third"));
oField.Insert(1, Creator.Component("First"));
oField.Insert(2, Creator.Component("Second"));
Assert.AreEqual("First^Second^^^^^^^^^^Third", oField.AsString, ",oField.ComponentInsertBefore returned incorrect");
//Test InsertBefore
oField.ClearAll();
oField.Add(Creator.SubComponent("The SubComponent"));
Assert.AreEqual("The SubComponent", oField.AsString, ",oField.ComponentInsertBefore returned incorrect");
oField.Add(Creator.Content(" The Content"));
Assert.AreEqual("The SubComponent The Content", oField.AsString, ",oField.ComponentInsertBefore returned incorrect");
//Very interesting scenario, add the same Component to two different parent fields.
//The Parent property set to that lass parent the object was added to even though it is now contatined in both parent's ComponentList
//This is not good but as we currently don't use the Parent property for any functional use it works.
//Need to review weather we even need the Parent property at all?
oField.ClearAll();
var oComponent = Creator.Component("Test");
oField.Insert(1, oComponent.Clone());
oField.Insert(2, oComponent.Clone());
oField.Add(oComponent.Clone());
oComponent.AsString = "Test2";
var oField2 = Creator.Field();
oField2.Add(oComponent.Clone());
//Test mixture of Append , insert before and after
oField.ClearAll();
oField.Insert(1, Creator.Component("First"));
oField.Insert(2, Creator.Component("Second"));
oField.Add(Creator.Component("Third"));
Assert.AreEqual("First^Second^Third", oField.AsString, ",oField Component insert mix returned incorrect");
//Test Clone
var FieldClone = oField.Clone();
oField.Component(1).AsString = FieldClone.Component(3).AsString;
oField.Component(2).AsString = FieldClone.Component(2).AsString;
oField.Component(3).AsString = FieldClone.Component(1).AsString;
Assert.AreEqual("Third^Second^First", oField.AsString, ",oField.Clone test returned incorrect");
Assert.AreEqual("First^Second^Third", FieldClone.AsString, ",oField.Clone test2 returned incorrect");
//Test Custom Delimiters
var oCustomDelimiters = Creator.MessageDelimiters('!', '@', '*', '%', '#');
oField = Creator.Field("First*#H#Second#N#*Third1%Third2", oCustomDelimiters);
Assert.AreEqual("Second", oField.Component(2).AsString, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("#H#Second#N#", oField.Component(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("Third2", oField.Component(3).SubComponent(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
}
}
[TestClass]
public class UnitTestElementModel
{
[TestMethod]
public void TestFieldCreate()
{
//Test setting data through create
string TestStringEscape = "1first^1Second^1ThirdHasSubs1&1ThirdHasSubs2^1Forth^\\H\\1Fith\\N\\~2first^2Second^2ThirdHasSubs1&2ThirdHasSubs2^2Forth^\\H\\2Fith\\N\\~3first^3Second^3ThirdHasSubs1&3ThirdHasSubs2^3Forth^\\H\\3Fith\\N\\";
string TestString = "1first^1Second^1ThirdHasSubs1&1ThirdHasSubs2^1Forth^1Fith~2first^2Second^2ThirdHasSubs1&2ThirdHasSubs2^2Forth^2Fith~3first^3Second^3ThirdHasSubs1&3ThirdHasSubs2^3Forth^3Fith";
var oElement = Creator.Element(TestStringEscape);
Assert.AreEqual(TestStringEscape, oElement.AsStringRaw, "oElement.AsStringRaw did not match create string");
//Test setting data through StringRaw
oElement.AsStringRaw = "";
oElement.AsStringRaw = TestStringEscape;
Assert.AreEqual(TestStringEscape, oElement.AsStringRaw, "oElement.AsStringRaw did not match Set StringRaw");
Assert.AreEqual(TestString, oElement.AsString, "oElement.AsString did not match Set StringRaw");
//Test empty dilimeters are not kept
oElement.AsStringRaw = "^^1Third^1Forth~~~^^\\H\\2Third\\N\\^2Forth~~~~~~~~~~~~~~~";
Assert.AreEqual("^^1Third^1Forth~~~^^\\H\\2Third\\N\\^2Forth", oElement.AsStringRaw, "oElement.AsStringRaw did not match Set StringRaw");
Assert.AreEqual("^^1Third^1Forth~~~^^2Third^2Forth", oElement.AsString, "oElement.AsString did not match Set StringRaw");
Assert.AreEqual("^^2Third^2Forth", oElement.Repeat(4).ToString(), "oElement.Repeat(4).ToString() did not match Set StringRaw");
//Test inspect Component does not add Components
if (oElement.Repeat(100).AsString == "")
{
Assert.AreEqual(4, oElement.RepeatCount, ",oElement.RepeatCount is incorrect");
}
//Test zero index exception
try
{
string test = oElement.Repeat(0).AsString;
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Repeat is a one based index, zero is not a valid index", ae.Message, "Exception should have been thrown on zero index for Component");
}
//Test Append
oElement.ClearAll();
Assert.AreEqual(0, oElement.RepeatCount, ",oElement.RepeatCount is incorrect");
oElement.Add(Creator.Field("First"));
oElement.Add(Creator.Field("Second"));
oElement.Add(Creator.Field("Third"));
oElement.Add(Creator.Field("Forth"));
//Test Component lookup
Assert.AreEqual(4, oElement.RepeatCount, ",oElement.RepeatCount is incorrect");
Assert.AreEqual("First", oElement.Repeat(1).AsStringRaw, ",oElement.Repeat(1).AsStringRaw returned incorrect");
Assert.AreEqual("Second", oElement.Repeat(2).AsString, ",oElement.Repeat(2).AsStringRaw returned incorrect");
Assert.AreEqual("Third", oElement.Repeat(3).AsStringRaw, ",oElement.Repeat(3).AsStringRaw returned incorrect");
Assert.AreEqual("Forth", oElement.Repeat(4).AsString, ",oElement.Repeat(4).AsStringRaw returned incorrect");
Assert.AreEqual("First~Second~Third~Forth", oElement.AsString, ",oElement.AsString");
//Test RemoveAt
oElement.RemoveRepeatAt(4);
Assert.AreEqual("First~Second~Third", oElement.AsString, ",oElement.RemoveRepeatAt(4) returned incorrect");
oElement.RemoveRepeatAt(2);
Assert.AreEqual("First~Third", oElement.AsString, ",oElement.RemoveRepeatAt(2) returned incorrect");
oElement.RemoveRepeatAt(1);
oElement.RemoveRepeatAt(1);
Assert.AreEqual("", oElement.AsString, ",oElement.RemoveRepeatAt() returned incorrect");
//Test InsertBefore
oElement.ClearAll();
oElement.Add(Creator.Component("The Component"));
Assert.AreEqual("The Component", oElement.AsString, ",oElement.Add(Creator.Component(); returned incorrect");
oElement.Add(Creator.Component("The Component2"));
Assert.AreEqual("The Component^The Component2", oElement.AsString, ",oElement.Add(Creator.Component(); returned incorrect");
oElement.ClearAll();
oElement.Add(Creator.SubComponent("The SubComponent1"));
Assert.AreEqual("The SubComponent1", oElement.AsString, ",oElement.Add(new SubComponent(); returned incorrect");
oElement.ClearAll();
oElement.Add(Creator.Content("The Content1"));
Assert.AreEqual("The Content1", oElement.AsString, ",oElement.Add(Creator.Content(); returned incorrect");
//Test InsertBefore
oElement.ClearAll();
oElement.Insert(20, Creator.Field("Third"));
oElement.Insert(1, Creator.Field("First"));
oElement.Insert(2, Creator.Field("Second"));
Assert.AreEqual("First~Second~~~~~~~~~~~~~~~~~~~~Third", oElement.AsString, ",oElement.RepeatInsertBefore returned incorrect");
oElement.Insert(5, Creator.Component("Forth"));
Assert.AreEqual("First^^^^Forth~Second~~~~~~~~~~~~~~~~~~~~Third", oElement.AsString, ",oElement.RepeatInsertBefore returned incorrect");
oElement.Insert(5, Creator.SubComponent("Five"));
Assert.AreEqual("First&&&&Five^^^^Forth~Second~~~~~~~~~~~~~~~~~~~~Third", oElement.AsString, ",oElement.RepeatInsertBefore returned incorrect");
oElement.Insert(5, Creator.Content(PeterPiper.Hl7.V2.Support.Standard.EscapeType.HighlightOn));
Assert.AreEqual("First\\H\\&&&&Five^^^^Forth~Second~~~~~~~~~~~~~~~~~~~~Third", oElement.AsStringRaw, ",oElement.RepeatInsertBefore returned incorrect");
//Test mixture of Append , insert before and after
oElement.ClearAll();
oElement.Insert(1, Creator.Field("First"));
oElement.Insert(2, Creator.Field("Second"));
oElement.Add(Creator.Field("Third"));
Assert.AreEqual("First~Second~Third", oElement.AsString, ",oElement Repeat insert mix returned incorrect");
//Test Clone
var ElementClone = oElement.Clone();
oElement.Repeat(1).AsString = ElementClone.Repeat(3).AsString;
oElement.Repeat(2).AsString = ElementClone.Repeat(2).AsString;
oElement.Repeat(3).AsString = ElementClone.Repeat(1).AsString;
Assert.AreEqual("Third~Second~First", oElement.AsString, ",oElement.Clone test returned incorrect");
Assert.AreEqual("First~Second~Third", ElementClone.AsString, ",oElement.Clone test2 returned incorrect");
if (oElement.Repeat(1).Component(1).AsString != oElement.Repeat(1).Component(1).SubComponent(1).AsString)
{
Assert.Fail("the first component should equal the first SubComponent");
}
//Test Custom Delimiters
var oCustomDelimiters = Creator.MessageDelimiters('!', '@', '*', '%', '#'); //Field, Repeat, Component, SubComponet,Escape
oElement = Creator.Element("First1*#H#Second1#N#*Third11%Third12@First2*#H#Second2#N#*Third21%Third22", oCustomDelimiters);
Assert.AreEqual("First2*Second2*Third21%Third22", oElement.Repeat(2).AsString, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("#H#Second2#N#", oElement.Repeat(2).Component(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("Third22", oElement.Repeat(2).Component(3).SubComponent(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
}
}
[TestClass]
public class UnitTestSegmentModel
{
[TestMethod]
public void TestFieldCreate()
{
//Test setting data through create
string TestStringEscape = "PID||PID-2.1^PID-2.2|PID-3.1.1&PID-3.1.2^PID-3.1|PID-{1}4~PID-{2}4|PID-5.1^\\H\\PID-5.2\\N\\";
string TestString = "PID||PID-2.1^PID-2.2|PID-3.1.1&PID-3.1.2^PID-3.1|PID-{1}4~PID-{2}4|PID-5.1^PID-5.2";
var oSegment = Creator.Segment(TestStringEscape);
Assert.AreEqual(TestStringEscape, oSegment.AsStringRaw, "oSegment.AsStringRaw did not match create string");
//Test setting data through StringRaw
oSegment.AsStringRaw = "PID|";
oSegment.AsStringRaw = TestStringEscape;
Assert.AreEqual(TestStringEscape, oSegment.AsStringRaw, "oSegment.AsStringRaw did not match Set StringRaw");
Assert.AreEqual(TestString, oSegment.AsString, "oSegment.AsString did not match Set StringRaw");
//Test empty dilimeters are not kept
string TestStringEscape1 = "PID|PID-{1}1~PID-{2}1~PID-{3}1.1^PID-{3}1.2.1&PID-{3}1.2.2&PID-{3}1.2.3~PID-{4}1|PID-2.1^PID-2.2|PID-3.1.1&PID-3.1.2^PID-3.1|PID-{1}4~PID-{2}4|PID-5.1^\\H\\PID-5.2\\N\\||||||||||||||||||||||||||||||||||||";
string TestStringEscape2 = "PID|PID-{1}1~PID-{2}1~PID-{3}1.1^PID-{3}1.2.1&PID-{3}1.2.2&PID-{3}1.2.3~PID-{4}1|PID-2.1^PID-2.2|PID-3.1.1&PID-3.1.2^PID-3.1|PID-{1}4~PID-{2}4|PID-5.1^\\H\\PID-5.2\\N\\";
TestString = "PID|PID-{1}1~PID-{2}1~PID-{3}1.1^PID-{3}1.2.1&PID-{3}1.2.2&PID-{3}1.2.3~PID-{4}1|PID-2.1^PID-2.2|PID-3.1.1&PID-3.1.2^PID-3.1|PID-{1}4~PID-{2}4|PID-5.1^PID-5.2";
oSegment.AsStringRaw = TestStringEscape1;
Assert.AreEqual(TestStringEscape2, oSegment.AsStringRaw, "oSegment.AsStringRaw did not match Set StringRaw");
Assert.AreEqual(TestString, oSegment.AsString, "oSegment.AsString did not match Set StringRaw");
Assert.AreEqual("PID-5.1^PID-5.2", oSegment.Field(5).ToString(), "oSegment.Field(3).ToString() did not match Set StringRaw");
Assert.AreEqual("PID-{2}4", oSegment.Element(4).Repeat(2).ToString(), "oSegment.Field(3).ToString() did not match Set StringRaw");
Assert.AreEqual("PID-3.1.1&PID-3.1.2^PID-3.1", oSegment.Element(3).AsString, "oSegment.Field(3).ToString() did not match Set StringRaw");
Assert.AreEqual("PID-3.1.2", oSegment.Field(3).Component(1).SubComponent(2).AsString, "oSegment.Field(3).ToString() did not match Set StringRaw");
Assert.AreEqual("PID-3.1.1&PID-3.1.2", oSegment.Element(3).Repeat(1).Component(1).AsStringRaw, "oSegment.Field(3).ToString() did not match Set StringRaw");
Assert.AreEqual("PID-{3}1.2.3", oSegment.Element(1).Repeat(3).Component(2).SubComponent(3).AsStringRaw, "oSegment.Field(3).ToString() did not match Set StringRaw");
//##Issues## This test fails, but notice the test below it does not!!!
////Test inspect Field does not add fields & elements
//if (oSegment.Field(100).AsString == "")
//{
//Assert.AreEqual(5, oSegment.ElementCount, "oSegment.CountElement is incorrect");
//}
//Test inspect Element does not add Elements, so if you need to test a field
//for emptiness then use Element.
if (oSegment.Element(100).AsString == "")
{
Assert.AreEqual(5, oSegment.ElementCount, "oSegment.CountElement is incorrect");
}
//Test zero index exception
try
{
string test = oSegment.Element(0).AsString;
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Element index is a one based index, zero in not allowed", ae.Message, "Exception should have been thrown on zero index for Element");
}
//Test Append
oSegment.ClearAll();
Assert.AreEqual(0, oSegment.ElementCount, "oSegment.RepeatCount is incorrect");
oSegment.Add(Creator.Element("First"));
oSegment.Add(Creator.Element("Second"));
oSegment.Add(Creator.Element("Third"));
oSegment.Add(Creator.Element("Forth"));
////Test Component lookup
Assert.AreEqual(4, oSegment.ElementCount, "oSegment.RepeatCount is incorrect");
Assert.AreEqual("First", oSegment.Element(1).AsStringRaw, "oSegment.Element(1).AsStringRaw returned incorrect");
Assert.AreEqual("First", oSegment.Field(1).AsStringRaw, "oSegment.Field(1).AsStringRaw returned incorrect");
Assert.AreEqual("Second", oSegment.Element(2).AsString, "oSegment.Element(2).AsString returned incorrect");
Assert.AreEqual("Second", oSegment.Field(2).AsString, "oSegment.Field(2).AsString returned incorrect");
Assert.AreEqual("Third", oSegment.Element(3).AsStringRaw, "oSegment.Element(3).AsStringRaw returned incorrect");
Assert.AreEqual("Third", oSegment.Field(3).AsStringRaw, "oSegment.Field(3).AsStringRaw returned incorrect");
Assert.AreEqual("Forth", oSegment.Element(4).AsString, "oSegment.Element(4).AsString returned incorrect");
Assert.AreEqual("Forth", oSegment.Field(4).AsString, "oSegment.Field(4).AsString returned incorrect");
Assert.AreEqual("PID|First|Second|Third|Forth", oSegment.AsString, "oSegment.AsString");
////Test RemoveAt
oSegment.RemoveElementAt(4);
Assert.AreEqual("PID|First|Second|Third", oSegment.AsString, "oSegment.RemoveRepeatAt(4) returned incorrect");
oSegment.RemoveElementAt(2);
Assert.AreEqual("PID|First|Third", oSegment.AsString, "oSegment.RemoveRepeatAt(2) returned incorrect");
oSegment.RemoveElementAt(1);
Assert.AreEqual("PID|Third", oSegment.AsString, "oSegment.RemoveRepeatAt() returned incorrect");
oSegment.RemoveElementAt(1);
Assert.AreEqual("PID|", oSegment.AsString, "oSegment.RemoveRepeatAt() returned incorrect");
////Test InsertAfter
oSegment.Insert(1, Creator.Element("First1~First2"));
oSegment.Insert(2, Creator.Element("Third"));
oSegment.Insert(2, Creator.Element("Second"));
Assert.AreEqual("PID|First1~First2|Second|Third", oSegment.AsString, "oSegment.RepeatInsertAfter returned incorrect");
////Test InsertBefore
oSegment.ClearAll();
oSegment.Insert(10, Creator.Element("Third"));
oSegment.Insert(1, Creator.Element("First1~First2"));
oSegment.Insert(2, Creator.Element("Second"));
oSegment.Insert(1, Creator.Element(""));
oSegment.Insert(1, Creator.Element(""));
Assert.AreEqual("PID|||First1~First2|Second||||||||||Third", oSegment.AsString, "oSegment.RepeatInsertBefore returned incorrect");
//Very interesting scenario, add the same Component to two different parent fields.
//The Parent property of the Component can only have one parent and is set to the last known even though it is now contained in both parent's ComponentList
//This was not allowed to happen. I have implemented a base .Clone method which needed to be done anyway and also
//now throw an exception for this case as tested below.
//End story is users must clone object instances to use them in another structure. I think this
//is reasonable
oSegment.ClearAll();
var oElement = Creator.Element("Test");
oSegment.Insert(1, oElement);
try
{
oSegment.Insert(2, oElement);
}
catch (ArgumentException e)
{
Assert.AreEqual("The object instance passed is in use within another structure. This is not allowed. Have you forgotten to Clone() the instance before reusing.",
e.Message, "Exception thrown has wrong text");
}
oSegment.Insert(2, oElement.Clone());
oSegment.Add(oElement.Clone());
oElement.AsString = "Test2";
var oSegment2 = Creator.Segment("ROL|");
oSegment2.Add(oElement.Clone());
string teeeest = oSegment.Field(1).PathDetail.PathBrief;
////Test Adding and removing Fields on segment instance
oSegment.ClearAll();
oSegment.AsStringRaw = "PID|1|2|3|4|5|6";
oSegment.Add(Creator.Field("NewField1"));
Assert.AreEqual("PID|1|2|3|4|5|6|NewField1", oSegment.AsString, "oSegment.Add() returned incorrect");
oSegment.Insert(6, Creator.Field("NewField2"));
Assert.AreEqual("PID|1|2|3|4|5|NewField2|6|NewField1", oSegment.AsString, "oSegment.Add() returned incorrect");
////Test mixture of Append , insert before and after
oSegment.ClearAll();
oSegment.Insert(1, Creator.Element("First"));
oSegment.Insert(2, Creator.Element("Second"));
oSegment.Add(Creator.Element("Third"));
Assert.AreEqual("PID|First|Second|Third", oSegment.AsString, "oSegment insert mix returned incorrect");
////Test Clone
var SegmentClone = oSegment.Clone();
oSegment.Element(1).AsString = SegmentClone.Element(3).AsString;
oSegment.Element(2).AsString = SegmentClone.Element(2).AsString;
oSegment.Element(3).AsString = SegmentClone.Element(1).AsString;
Assert.AreEqual("PID|Third|Second|First", oSegment.AsString, "oSegment.Clone test returned incorrect");
Assert.AreEqual("PID|First|Second|Third", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
Assert.AreEqual(oSegment.Field(1).AsString, oSegment.Element(1).Repeat(1).Component(1).SubComponent(1).AsString, "The first Field / Element should equal the first SubComponent");
SegmentClone.Element(3).ClearAll();
Assert.AreEqual("PID|First|Second", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Element(2).AsString = String.Empty;
Assert.AreEqual("PID|First", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Element(2).Component(3).SubComponent(10).AsString = "Hi";
Assert.AreEqual("PID|First|^^&&&&&&&&&Hi", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Element(2).Component(3).SubComponent(10).Content(0).ClearAll();
Assert.AreEqual("PID|First", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Element(2).Component(3).SubComponent(10).AsString = "Hi2";
SegmentClone.Element(2).Component(2).ClearAll();
Assert.AreEqual("PID|First|^^&&&&&&&&&Hi2", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Element(1).Component(1).SubComponent(1).ClearAll();
Assert.AreEqual("PID||^^&&&&&&&&&Hi2", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
SegmentClone.Field(2).ClearAll();
Assert.AreEqual("PID|", SegmentClone.AsString, "oSegment.Clone test2 returned incorrect");
////Test Custom Delimiters
var oCustomDelimiters = Creator.MessageDelimiters('!', '@', '*', '%', '#'); //Field, Repeat, Component, SubComponet,Escape
oSegment = Creator.Segment("PID!First1*#H#Second1#N#*Third11%Third12@First2*#H#Second2#N#*Third21%Third22", oCustomDelimiters);
Assert.AreEqual("First1*Second1*Third11%Third12", oSegment.Field(1).AsString, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("#H#Second2#N#", oSegment.Element(1).Repeat(2).Component(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
Assert.AreEqual("Third22", oSegment.Element(1).Repeat(2).Component(3).SubComponent(2).AsStringRaw, ",CustomDelimiters test returned incorrect");
}
}
[TestClass]
public class UnitTestMessageModel
{
[TestMethod]
public void TestMessageCreate()
{
var oMessage = Creator.Message("2.3.1", "ORU", "R01");
StringBuilder sbMessageWithTwoMSHSegments = new StringBuilder();
sbMessageWithTwoMSHSegments.Append("MSH|^~\\&|HNAM^RADNET|PAH^00011|IMPAX-CV|QH|20141208064531||ORM^O01^ORM_O01|Q54356818T82744882|P|2.3.1|||AL|NE|AU|8859/1|EN"); sbMessageWithTwoMSHSegments.Append("\r");
sbMessageWithTwoMSHSegments.Append("PID|1|1038785005^^^QH^PT^CD&A^^\"\"|1038785005^^^QH^PT^CD&A^^\"\"~993171^^^QH^MR^PAH&A^^\"\"~343211^^^QH^MR^LOGH&A^^\"\"~43028819141^^^HIC^MC^^^10/2018~\"\"^^^DVA^VA^^\"\"~420823031C^^^HIC^PEN&9^^^31/07/2015~\"\"^^^HIC^HC^^\"\"~\"\"^^^HIC^SN^^\"\"|993171-PAH^^^^MR^PAH|KABONGO^KABEDI^^^MS^^C||19520725|F||42^Not Aborig. or Torres Strait Is. ,Not a South Sea Islander|24 Holles Street^^WATERFORD WEST^^4133||(046)927-3235^Home|(046)927-3235^Business|78|3^Widowed|2999^Other Christian, nec|1504352845^^^PAH FIN Number Alias Pool^FIN NBR|43028819141||||||0|||||N"); sbMessageWithTwoMSHSegments.Append("\r");
sbMessageWithTwoMSHSegments.Append("MSH|^~\\&|HNAM^RADNET|PAH^00011|IMPAX-CV|QH|20141208064531||ORM^O01^ORM_O01|Q54356818T82744882|P|2.3.1|||AL|NE|AU|8859/1|EN"); sbMessageWithTwoMSHSegments.Append("\r");
try
{
oMessage = Creator.Message(sbMessageWithTwoMSHSegments.ToString());
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Second MSH segment found when parsing new message. Single messages must only have one MSH segment as the first segment.", ae.Message, "Exception should have been thrown in setting oMessage.AsString");
}
StringBuilder sbMessage = new StringBuilder();
sbMessage.Append("MSH|^~\\&|HNAM^RADNET|PAH^00011|IMPAX-CV|QH|20141208064531||ORM^O01^ORM_O01|Q54356818T82744882|P|2.3.1|||AL|NE|AU|8859/1|EN"); sbMessage.Append("\r");
sbMessage.Append("PID|1|1234567890^^^QH^PT^CD&A^^\"\"|1234567890^^^QH^PT^CD&A^^\"\"~345678^^^QH^MR^PAH&A^^\"\"~010101^^^QH^MR^LOGH&A^^\"\"~00000000001^^^HIC^MC^^^10/2018~\"\"^^^DVA^VA^^\"\"~123456789C^^^HIC^PEN&9^^^31/07/2015~\"\"^^^HIC^HC^^\"\"~\"\"^^^HIC^SN^^\"\"|001122-PAH^^^^MR^PAH|DummySurname^DummyGiven^^^MS^^C||19520725|F||42^Not Aborig. or Torres Strait Is. ,Not a South Sea Islander|24 Holles Street^^WATERFORD WEST^^4133||(046)927-3235^Home|(046)927-3235^Business|78|3^Widowed|2999^Other Christian, nec|1504352845^^^PAH FIN Number Alias Pool^FIN NBR|43028819141||||||0|||||N"); sbMessage.Append("\r");
sbMessage.Append("PV1|1|I|||||1^SMITH^John^^^^^^PAH External ID Alias Pool^CD:369232^^^External Identifier~1106^SMITH^JOHN^^^^^^PAH Organisation Dr Number Alias Pool^CD:123456^^^ORGANIZATION DOCTOR||1106^SMITH^JOHN^^^^^^PAH External ID Alias Pool^CD:123456^^^External Identifier~1106^SMITH^JOHN^^^^^^PAH Organisation Dr Number Alias Pool^CD:123456^^^ORGANIZATION DOCTOR||||||||||1234567890^^^PAH Visit ID Alias Pool^Visit Id||||||||||||||||||||PAHDHS||Active|||20141127134500"); sbMessage.Append("\r");
sbMessage.Append("PV2|||^smith|||||||0|||||||||||||^^294882"); sbMessage.Append("\r");
sbMessage.Append("IN1|1|295388^109|3060132|109||||||||20141127134612|21001231000000|||DummySurname^DummyGiven^^^MS^^C|CD:158|19520725|1 SOMEWHERE STREET^^OVERTHERE WEST^^4133~~~^^^^^9106~9107^^^^^9106|||0|||||||||||||||||||||F"); sbMessage.Append("\r");
sbMessage.Append("IN2|"); sbMessage.Append("\r");
sbMessage.Append("ORC|CA|25486076^HNAM_ORDERID|||OC||||20141208064530|123456^DOA^JANE^^^^^^PAH Prsnl ID Alias Pool^CD:369232^^^PRSNLID||1234^SMITH^JOHN^^^^^^PAH External ID Alias Pool^CD:123456^^^External Identifier~1234^SMITH^JOHN^^^^^^PAH Organisation Dr Number Alias Pool^CD:12345^^^ORGANIZATION DOCTOR|PAHDHS||20141208064530|CD:123456^ADMINISTRATION CANCELLATION||CD:2562^Written|123456^DOA^JANE^^^^^^PAH Prsnl ID Alias Pool^CD:123456^^^PRSNLID"); sbMessage.Append("\r");
sbMessage.Append("OBR|1|25486076^HNAM_ORDERID||CI EP IMPLANT Dv^CI EP Implantable Device|||||||||||Rad Type&Rad Type|1234^SMITH^JOHN^^^^^^PAH External ID Alias Pool^CD:123456^^^External Identifier||CI12345678-PAH|PAH-CI|||||CI|||1^^0^20141205110000^^R"); sbMessage.Append("\r");
sbMessage.Append("OBX|1|IS|CD:1278500^RADIOLOGY INPATIENT / OUTPATIENT||CD:1"); sbMessage.Append("\r");
sbMessage.Append("OBX|2|IS|CD:1278500^RADIOLOGY INPATIENT / OUTPATIENT||CD:2"); sbMessage.Append("\r");
sbMessage.Append("OBX|3|IS|CD:1278500^RADIOLOGY INPATIENT / OUTPATIENT||CD:3"); sbMessage.Append("\r");
sbMessage.Append("OBX|4|IS|CD:1278500^RADIOLOGY INPATIENT / OUTPATIENT||CD:4"); sbMessage.Append("\r");
string MessageString = sbMessage.ToString();
oMessage = Creator.Message(MessageString);
//Check parsed Message same as Original
Assert.AreEqual(sbMessage.ToString(), oMessage.AsStringRaw, "Parsed Message is not equal to orginal message.");
//test IsEmpty property
Assert.AreEqual(true, oMessage.Segment("IN2").IsEmpty, "oMessage.Segment().IsEmpty returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Element(50).IsEmpty, "oMessage.Segment().Element(50).IsEmpty returns the incorrect value.");
Assert.AreEqual(false, oMessage.Segment("PID").Element(1).IsEmpty, "oMessage.Segment().Element(1).IsEmpty returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Element(1).Component(2).IsEmpty, "oMessage.Segment().Element(1).Component(2).IsEmpty returns the incorrect value.");
Assert.AreEqual(false, oMessage.Segment("PID").Element(2).Component(4).IsEmpty, "oMessage.Segment().Element(2).Component(4).IsEmpty returns the incorrect value.");
Assert.AreEqual(false, oMessage.Segment("PID").Element(2).Component(6).SubComponent(2).IsEmpty, "oMessage.Segment().Element(2).Component(6).SubComponent(2).IsEmpty returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Element(2).Component(6).SubComponent(3).IsEmpty, "oMessage.Segment().Element(2).Component(6).SubComponent(2).IsEmpty returns the incorrect value.");
Assert.AreEqual(false, oMessage.Segment("PID").Element(2).Component(6).SubComponent(2).Content(0).IsEmpty, "oMessage.Segment().Element(2).Component(6).SubComponent(2).Content(0).IsEmpty returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Element(2).Component(6).SubComponent(3).Content(2).IsEmpty, "oMessage.Segment().Element(2).Component(6).SubComponent(3).Content(2).IsEmpty returns the incorrect value.");
//oMessage.
//Some Time & Date Tests
DateTimeOffset testDateTime = oMessage.Segment("MSH").Field(7).Convert.DateTime.GetDateTimeOffset();
oMessage.Segment("MSH").Field(7).Convert.DateTime.SetDateTimeOffset(DateTimeOffset.Now);
testDateTime = oMessage.Segment("MSH").Field(7).Convert.DateTime.GetDateTimeOffset();
DateTimeOffset testDateTime3 = oMessage.Segment("MSH").Field(7).Convert.DateTime.GetDateTimeOffset();
Assert.AreEqual(12, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual(4, oMessage.SegmentList("OBX").Count, "The oMessage.SegmentList(\"OBX\").Count returns the incorrect value.");
Assert.AreEqual("CD:4", oMessage.SegmentList("OBX")[3].Element(5).Repeat(1).AsString, "oMessage.SegmentList(\"OBX\")[3].Element(5).Repeat(1).AsString returns the incorrect value.");
Assert.AreEqual("PT", oMessage.Segment("PID").Field(3).Component(5).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual("A", oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponent(2).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual(2, oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponentCount, "oMessage.Segment(\"PID\").Element(3).Repeat(2).Component(6).CountSubComponent returns the incorrect value.");
Assert.AreEqual(8, oMessage.Segment("PID").Element(3).RepeatCount, "oMessage.Segment(\"PID\").Element(3).RepeatCount returns the incorrect value.");
Assert.AreEqual("\"\"", oMessage.Segment("PID").Field(2).Component(8).AsStringRaw, "oMessage.Segment(\"PID\").Field(2).Component(8).AsStringRaw returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).SubComponent(1).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).SubComponent(1).IsHL7Null returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).IsHL7Null returns the incorrect value.");
oMessage.ClearAll();
Assert.AreEqual(1, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual(0, oMessage.SegmentList("OBX").Count, "The oMessage.SegmentList(\"OBX\").Count returns the incorrect value.");
Assert.AreEqual(1, oMessage.SegmentList("MSH").Count, "The oMessage.SegmentList(\"MSH\").Count returns the incorrect value.");
oMessage.AsStringRaw = MessageString;
Assert.AreEqual(12, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual(4, oMessage.SegmentList("OBX").Count, "The oMessage.SegmentList(\"OBX\").Count returns the incorrect value.");
Assert.AreEqual("CD:4", oMessage.SegmentList("OBX")[3].Element(5).Repeat(1).AsString, "oMessage.SegmentList(\"OBX\")[3].Element(5).Repeat(1).AsString returns the incorrect value.");
Assert.AreEqual("PT", oMessage.Segment("PID").Field(3).Component(5).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual("A", oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponent(2).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual(2, oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponentCount, "oMessage.Segment(\"PID\").Element(3).Repeat(2).Component(6).CountSubComponent returns the incorrect value.");
Assert.AreEqual(8, oMessage.Segment("PID").Element(3).RepeatCount, "oMessage.Segment(\"PID\").Element(3).RepeatCount returns the incorrect value.");
Assert.AreEqual("\"\"", oMessage.Segment("PID").Field(2).Component(8).AsStringRaw, "oMessage.Segment(\"PID\").Field(2).Component(8).AsStringRaw returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).SubComponent(1).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).SubComponent(1).IsHL7Null returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).IsHL7Null returns the incorrect value.");
oMessage.ClearAll();
try
{
oMessage.AsString = MessageString;
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("While setting a message using AsString() could technically work it would make no sense to have the message's escape characters in MSH-1 & MSH-2 re-escaped. You should be using AsStringRaw()", ae.Message, "Exception should have been thrown in setting oMessage.AsString");
}
var oMesage2 = Creator.Message(MessageString);
oMessage = oMesage2.Clone();
Assert.AreEqual(12, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual(4, oMessage.SegmentList("OBX").Count, "The oMessage.SegmentList(\"OBX\").Count returns the incorrect value.");
Assert.AreEqual("CD:4", oMessage.SegmentList("OBX")[3].Element(5).Repeat(1).AsString, "oMessage.SegmentList(\"OBX\")[3].Element(5).Repeat(1).AsString returns the incorrect value.");
Assert.AreEqual("PT", oMessage.Segment("PID").Field(3).Component(5).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual("A", oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponent(2).AsString, "oMessage.Segment(\"PID\").Field(3).Component(5).AsString returns the incorrect value.");
Assert.AreEqual(2, oMessage.Segment("PID").Element(3).Repeat(2).Component(6).SubComponentCount, "oMessage.Segment(\"PID\").Element(3).Repeat(2).Component(6).CountSubComponent returns the incorrect value.");
Assert.AreEqual(8, oMessage.Segment("PID").Element(3).RepeatCount, "oMessage.Segment(\"PID\").Element(3).RepeatCount returns the incorrect value.");
Assert.AreEqual("\"\"", oMessage.Segment("PID").Field(2).Component(8).AsStringRaw, "oMessage.Segment(\"PID\").Field(2).Component(8).AsStringRaw returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).SubComponent(1).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).SubComponent(1).IsHL7Null returns the incorrect value.");
Assert.AreEqual(true, oMessage.Segment("PID").Field(2).Component(8).IsHL7Null, "oMessage.Segment(\"PID\").Field(2).Component(8).IsHL7Null returns the incorrect value.");
int Counter = 1;
foreach (var OBX in oMessage.SegmentList("OBX"))
{
OBX.Field(1).AsString = Counter.ToString();
Counter++;
}
for (int i = 0; i < oMessage.SegmentList("OBX").Count; i++)
{
Assert.AreEqual((i + 1).ToString(), oMessage.SegmentList("OBX")[i].Field(1).AsString, "oMessage.SegmentList(\"OBX\")[i].Field(1).AsString returns the incorrect value.");
}
var oNewSegment = Creator.Segment("GUS|hello^World");
oMessage.Add(oNewSegment);
Assert.AreEqual(13, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual("GUS", oMessage.SegmentList()[12].Code, "oMessage.SegmentList()[12].Code");
var oNewSegment2 = Creator.Segment("NTE|Comment here 2");
oMessage.Insert(9, oNewSegment2);
Assert.AreEqual(14, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual("NTE", oMessage.Segment(9).Code, "oMessage.Segment(9).Code");
Assert.AreEqual("Comment here 2", oMessage.Segment(9).Field(1).AsString, "oMessage.Segment(9).Field(1).AsString");
var oNewSegment3 = Creator.Segment("NTE|Comment here 3");
oMessage.Insert(9, oNewSegment3);
Assert.AreEqual(15, oMessage.SegmentCount(), "The oMessage.CountSegment returns the incorrect value.");
Assert.AreEqual("NTE", oMessage.Segment(9).Code, "oMessage.SegmentList()[12].Code");
Assert.AreEqual("Comment here 3", oMessage.Segment(9).Field(1).AsString, "oMessage.Segment(9).Field(1).AsString");
if (oMessage.RemoveSegmentAt(9))
{
Assert.AreEqual("Comment here 2", oMessage.Segment(9).Field(1).AsString, "oMessage.Segment(9).Field(1).AsString");
}
else
{
Assert.Fail("oMessage.RemoveSegmentAt(9) should have returned True");
}
var oDelim = Creator.MessageDelimiters('*', '~', '^', '&', '\\');
var oMSHSeg = Creator.Segment("MSH*^~\\&*SUPERLIS*QHPS*EGATE-Atomic*CITEC*20140804143827**ORU^R01*000000000000005EVT6P*P*2.3.1*", oDelim);
var oMessage3 = Creator.Message(oMSHSeg);
var oPIDSeg = Creator.Segment("PID|1|1016826143^^^QH^PT^CD&A^^\"\"|1016826143^^^QH^PT^CD&A^^\"\"~103647^^^QH^MR^TPCH&A^^\"\"~299059^^^QH^MR^PAH&A^^\"\"~165650^^^QH^MR^IPSH&A^^\"\"~297739^^^QH^MR^LOGH&A^^\"\"~B419580^^^QH^MR^RBWH&A^^\"\"~40602113521^^^HIC^MC^^^10/2015~\"\"^^^DVA^VA^^\"\"~NP^^^HIC^PEN&9^^^\"\"~\"\"^^^HIC^HC^^\"\"~\"\"^^^HIC^SN^^\"\"|299059-PAH^^^^MR^PAH|EDDING^WARREN^EVAN^^MR^^C||19520812|M||42^Not Aborig. or Torres Strait Is. ,Not a South Sea Islander|7 Colvin Street^^NORTH IPSWICH^^4305||(042)242-9139^Home|(042)242-9139^Business|CD:301058|4^Divorced|7010^No Religion, NFD|1504350552^^^PAH FIN Number Alias Pool^FIN NBR|40602113521||||||0|||||N");
try
{
oMessage3.Add(oPIDSeg);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("The Segment instance being added to this parent Message instance has custom delimiters that are different than the parent, this is not allowed", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage3.RemoveSegmentAt(1);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Index one is the MSH Segment. This segment can not be removed, it can be modified or a new Message instance can be created", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
oMessage = Creator.Message(MessageString);
Assert.AreEqual("|", oMessage.MainSeparator, "oMessage.MainSeparator returns the incorrect value");
Assert.AreEqual("^~\\&", oMessage.EscapeSequence, "oMessage.MessageDelimiters returns the incorrect value");
//string testr = oMessage.Segment(1).Field(2).AsString;
StringBuilder sbMSH2Exception = new StringBuilder();
sbMSH2Exception.Append("MSH-2 contains the 'Encoding Characters' and is not accessible from the Field or Element object instance as it is critical to message construction.");
sbMSH2Exception.Append(Environment.NewLine);
sbMSH2Exception.Append("Instead, you can access the read only property call 'EscapeSequence' from the Message object instance.");
StringBuilder sbMSH1Exception = new StringBuilder();
sbMSH1Exception.Append("MSH-1 contains the 'Main Separator' character and is not accessible from the Field or Element object instance as it is critical to message construction.");
sbMSH1Exception.Append(Environment.NewLine);
sbMSH1Exception.Append("Instead, you can access the read only property call 'MainSeparator' from the Message object instance.");
try
{
oMessage.Segment(1).Element(1).Repeat(1).Component(1).AsString = "TestData";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH1Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).Field(2).AsString = "TestData";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH2Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).RemoveElementAt(1);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH1Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).RemoveElementAt(2);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH2Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).Insert(1, Creator.Element("sffsfsdfAfter"));
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH1Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).Insert(1, Creator.Element("sffsfsdfBefore"));
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH1Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).Element(2).Repeat(1).AsString = "Done";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual(sbMSH2Exception.ToString(), ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).AsString = "ABC|^~\\&|SUPERLIS|TRAIN|";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Unable to modify an existing MSH segment instance with the AsString or AsStringRaw properties. /n You need to create a new Segment instance and use it's constructor or selectively edit this segment's parts.", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Segment(1).AsStringRaw = "ABC|^~\\&|SUPERLIS|TRAIN|";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Unable to modify an existing MSH segment instance with the AsString or AsStringRaw properties. /n You need to create a new Segment instance and use it's constructor or selectively edit this segment's parts.", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
var testSeg = Creator.Segment("BAD");
testSeg.AsStringRaw = "MSH|^~\\&|SUPERLIS|TRAIN|EGATE-Atomic^prjSUPERLISIn|EMR|20140526095519||ORU^R01|000000000000000000ZN|P|2.3.1";
testSeg.AsStringRaw = "ABC|^~\\&|SUPERLIS|TRAIN|";
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("Unable to modify an existing MSH segment instance with the AsString or AsStringRaw properties. /n You need to create a new Segment instance and use it's constructor or selectively edit this segment's parts.", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
var NewMSH = Creator.Segment("MSH|^~\\&|SUPERLIS|TRAIN|EGATE-Atomic^prjSUPERLISIn|EMR|20140526095519||ORU^R01|000000000000000000ZN|P|2.3.1");
try
{
oMessage.Add(NewMSH);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("An MSH Segment can not be added to a Message instance, it must be provided on Message instance creation / instantiation", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Insert(2, NewMSH);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("An MSH Segment can not be added to a Message instance, it must be provided on Message instance creation / instantiation", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
try
{
oMessage.Insert(1, NewMSH);
Assert.Fail("An exception should have been thrown");
}
catch (PeterPiper.Hl7.V2.CustomException.PeterPiperException ae)
{
Assert.AreEqual("An MSH Segment can not be added to a Message instance, it must be provided on Message instance creation / instantiation", ae.Message, "Exception should have been thrown due to CustomDelimiters not matching");
}
//Check Component List works correctly
oPIDSeg = Creator.Segment("PID|1|1234567890^^^QH^PT^CD&A^^\"\"|1234567890^^^QH^PT^CD&A^^\"\"~123456^^^QH^MR^TPCH&A^^\"\"~123456^^^QH^MR^PAH&A^^\"\"~123456^^^QH^MR^IPSH&A^^\"\"~123456^^^QH^MR^LOGH&A^^\"\"~B123456^^^QH^MR^RBWH&A^^\"\"~12345678901^^^HIC^MC^^^10/2015~\"\"^^^DVA^VA^^\"\"~NP^^^HIC^PEN&9^^^\"\"~\"\"^^^HIC^HC^^\"\"~\"\"^^^HIC^SN^^\"\"|299059-PAH^^^^MR^PAH|DUMMYSURNAME^DUMMYGIVEN^EVAN^^MR^^C||19520812|M||42^Not Aborig. or Torres Strait Is. ,Not a South Sea Islander|7 Where Street^^NORTH HERE^^1234||(042)242-0000^Home|(042)242-0000^Business|CD:301058|4^Divorced|7010^No Religion, NFD|1504350552^^^PAH FIN Number Alias Pool^FIN NBR|40602113521||||||0|||||N");
Counter = 1;
foreach (var Com in oPIDSeg.Field(3).ComponentList)
{
if (Com.ToString() != String.Empty)
Com.AsString = Counter.ToString();
Counter++;
}
Assert.AreEqual("1^^^4^5^6^^8", oPIDSeg.Field(3).AsString, "oPIDSeg.Field(3).ComponentList returns the incorrect values");
string datetest = PeterPiper.Hl7.V2.Support.Tools.DateTimeSupportTools.AsString(DateTimeOffset.Now, true, PeterPiper.Hl7.V2.Support.Tools.DateTimeSupportTools.DateTimePrecision.DateHourMinSec);
//string datetest = PeterPiper.Hl7.V2.Support.Content.DateTimeTools.ConvertDateTimeOffsetToString.AsDateHourMinSec(DateTimeOffset.Now, true);
//DateTimeOffset testDateTime2 = PeterPiper.Hl7.V2.Support.Content.DateTimeTools.ConvertStringToDateTime.AsDateTimeOffset("2014+0800");
DateTimeOffset testDateTime2 = PeterPiper.Hl7.V2.Support.Tools.DateTimeSupportTools.AsDateTimeOffSet("2014+0800");
oMessage = Creator.Message(sbMessage.ToString());
var SubCom = Creator.SubComponent("Sub");
var oContent1 = Creator.Content("Test1");
var oContent2 = Creator.Content("Test2");
SubCom.Add(oContent1);
SubCom.Content(1).AsStringRaw = "";
SubCom.Content(1).AsStringRaw = "Raw1";
SubCom.Add(oContent2);
oContent1.AsString = "Test11";
oContent2.AsString = "Test22";
oContent1.AsString = "Test111";
oContent2.AsString = "Test222";
Assert.AreEqual("SubRaw1Test222", SubCom.AsStringRaw, "SubCom.AsStringRaw returns the incorrect values");
var oContent3 = Creator.Content("Test3");
var oContent4 = Creator.Content("Test4");
SubCom.Set(1, oContent3);
SubCom.Set(2, oContent4);
Assert.AreEqual("SubTest3Test4", SubCom.AsStringRaw, "SubCom.AsStringRaw returns the incorrect values");
var oField = Creator.Field("Field");
oField.Component(1).Set(0, oContent1);
Assert.AreEqual("Test111", oField.AsStringRaw, "SubCom.AsStringRaw returns the incorrect values");
oField.Component(1).Set(0, oContent2);
Assert.AreEqual("Test222", oField.AsStringRaw, "SubCom.AsStringRaw returns the incorrect values");
oContent1.AsStringRaw = "Test1";
oField = Creator.Field("Field");
var oComp = Creator.Component();
var oSubComp = Creator.SubComponent();
oField.Add(oComp);
oField.Component(2).Add(oSubComp.Clone());
oField.Component(2).Add(oSubComp.Clone());
Assert.AreEqual(false, oField.Component(2).IsEmpty, "SubCom.AsStringRaw returns the incorrect values");
Assert.AreEqual(true, oField.Component(2).SubComponent(2).IsEmpty, "SubCom.AsStringRaw returns the incorrect values");
oField.Component(2).SubComponent(1).AsString = "Sub1";
oField.Component(2).SubComponent(1).AsString = "";
Assert.AreEqual("Field^&", oField.AsStringRaw, "SubCom.AsStringRaw returns the incorrect values");
oMessage.Segment("PID").Field(2).ClearAll();
oMessage.Segment("PID").Field(2).Add(oContent1.Clone());
oMessage.Segment("PID").Field(2).Component(1).Add(oContent1.Clone());
}
}
}
| gpl-3.0 |
jhonlota/AplGesAdmV2 | src/entidades/SubgrupoJpaController.java | 2824 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entidades;
import clases.ClaseBaseDatos;
import clases.ClaseMensaje;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
/**
*
* @author Jhon Lopez
*/
public class SubgrupoJpaController {
private ClaseBaseDatos datos = new ClaseBaseDatos();
public SubgrupoJpaController() {
}
public void create(Subgrupo subgrupo) {
try {
datos.update("INSERT INTO SUBGRUPO VALUES ("
+ "'" + subgrupo.getCodigo() + "', "
+ "'" + subgrupo.getNombre() + "')");
if (!datos.isError) {
ClaseMensaje.informacionGuardarBD("Subgrupo");
}
} catch (Exception ex) {
ClaseMensaje.errorGuardarBD();
} finally {
}
}
public void edit(Subgrupo subgrupo, Subgrupo id) {
try {
datos.update("UPDATE SUBGRUPO SET "
+ "NOMBRE = '" + subgrupo.getNombre() + "' "
+ "WHERE "
+ "CODIGO = '" + id.getCodigo() + "'");
if (!datos.isError) {
ClaseMensaje.informacionActualizarBD("Subgrupo");
}
} catch (Exception ex) {
ClaseMensaje.errorActualizarBD();
} finally {
}
}
public void destroy(String id) {
try {
datos.update("DELETE FROM SUBGRUPO "
+ "WHERE "
+ "CODIGO = '" + id + "'");
if (!datos.isError) {
ClaseMensaje.informacionEliminarBD("Subgrupo");
}
} catch (Exception ex) {
ClaseMensaje.errorEliminarBD();
} finally {
}
}
public ArrayList<String> findCodigoInSubgrupoBy() {
ArrayList<String> array = new ArrayList<String>();
try {
datos.query("SELECT * FROM SUBGRUPO");
while (ClaseBaseDatos.resultado.next()) {
array.add(ClaseBaseDatos.resultado.getString("CODIGO"));
}
return array;
} catch (SQLException ex) {
return array;
}
}
public DefaultComboBoxModel COMBOCodigoInSubgrupoBy() {
DefaultComboBoxModel<String> modeloCombo = new DefaultComboBoxModel<String>();
try {
datos.query("SELECT DISTINCT(CODIGO) FROM SUBGRUPO ORDER BY CODIGO");
while (ClaseBaseDatos.resultado.next()) {
modeloCombo.addElement(ClaseBaseDatos.resultado.getString("CODIGO"));
}
return modeloCombo;
} catch (SQLException ex) {
ClaseMensaje.errorFind(this.toString(), ex.toString());
return modeloCombo;
}
}
}
| gpl-3.0 |
toto1444/barcode_vulnerability-fuzzing | platform_android/EAN-13 barcode gen project/assets/sample code.java | 896 | import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.graphics.Typeface;
public class AndroidEAN13Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// ToDo add your GUI initialization code here
this.setContentView(R.layout.main);
TextView t = (TextView)findViewById(R.id.barcode);
// set barcode font for TextView. ttf file must be placed is assets/fonts
Typeface font = Typeface.createFromAsset(this.getAssets(), "fonts/EanP72Tt Normal.Ttf");
t.setTypeface(font);
// generate barcode string
EAN13CodeBuilder bb = new EAN13CodeBuilder("124958761310");
t.setText(bb.getCode());
}
}
| gpl-3.0 |
alexandervonkurtz/CP2406_Programming2 | WEEK8(PRAC7)/cp2406_farrell8_ch11-master/CodeInFigures/Dog.java | 125 | public class Dog extends Animal
{
@Override
public void speak()
{
System.out.println("Woof!");
}
}
| gpl-3.0 |
kaushal02/CP | Code-Snippets/LCA.cc | 2694 | vi t[N];
int n, lca[25][N], h[N], start[N], stop[N], tm_;
inline bool is_anc(int a, int v) { // determines if a is ancestor of v
return start[a] <= start[v] and stop[a] >= stop[v];
}
inline int kth_anc(int v, int k) { // returns k'th ancestor of v
rep(i,20) {
if(k & 1) v = lca[i][v];
k >>= 1;
}
return v;
}
inline int get_lca(int u, int v) { // returns LCA
if(h[u] < h[v]) swap(u,v);
int x = h[u] - h[v];
rep(i,20) {
if(x & 1) u = lca[i][u];
x >>= 1;
}
if(u == v) return u;
rep2(i,18,0) if(lca[i][u] != lca[i][v]) u = lca[i][u], v = lca[i][v];
return lca[0][u];
}
inline void dfs(int v, int p) {
start[v] = tm_++; // h[v] is the depth of node. h[root] = 0
lca[0][v] = p; // lca[i][v] is (1<<i)'th ancestor of v, or root
rep1(i,1,20) lca[i][v] = lca[i - 1][lca[i - 1][v]];
for(int ch: t[v]) if(ch != p) h[ch] = h[v] + 1, dfs(ch, v);
stop[v] = tm_++;
}
/**************************************************************************************
***************************************************************************************
**************************************************************************************/
vi t[N];
int n, lca[25][N], h[N], start[N], stop[N], tm_, e;
inline bool is_anc(int a, int v) { // determines if a is ancestor of v
return start[a] <= start[v] and stop[a] >= stop[v];
}
inline int kth_anc(int v, int k) { // returns k'th ancestor of v
rep(i,20) {
if(k & 1) v = lca[i][v];
k >>= 1;
}
return v;
}
inline int get_lca(int u, int v) { // returns LCA
if(h[u] < h[v]) swap(u,v);
int x = h[u] - h[v];
rep(i,20) {
if(x & 1) u = lca[i][u];
x >>= 1;
}
if(u == v) return u;
rep2(i,18,0) if(lca[i][u] != lca[i][v]) u = lca[i][u], v = lca[i][v];
return lca[0][u];
}
inline void first_extreme(int v, int p) {
for(int ch: t[v]) if(ch != p)
h[ch] = h[v] + 1, first_extreme(ch, v);
}
inline void second_extreme(int v, int p) {
start[v] = tm_++; // h[v] is the depth of node. h[root] = 0
lca[0][v] = p; // lca[i][v] is (1<<i)'th ancestor of v, or root
rep1(i,1,20) lca[i][v] = lca[i - 1][lca[i - 1][v]];
for(int ch: t[v]) if(ch != p) h[ch] = h[v] + 1, second_extreme(ch, v);
stop[v] = tm_++;
}
inline void dia() {
e = 1; // remember that nodes are numbered 1..n
h[e] = 0;
first_extreme(1,1);
int x = 0;
rep1(i,1,n) if(x < h[i]) x = h[i], e = i;
h[e] = 0;
second_extreme(e,e);
x = 0;
rep1(i,1,n) if(x < h[i]) x = h[i], e = i;
} | gpl-3.0 |
hep-mirrors/herwig | Contrib/HiggsPairOL/MEHiggsPairJet.cc | 21408 | // -*- C++ -*-
//
// MEHiggsPairJet.cc is a part of Herwig - A multi-purpose Monte Carlo event generator
// Copyright (C) 2009-2019 The Herwig Collaboration
//
// Herwig is licenaaaced under version 2 of the GPL, see COPYING for details.
// Please respect the MCnet academic guidelines, see GUIDELINES for details.
//
//
// This is the implementation of the non-inlined, non-templated member
// functions of the MEHiggsPairJet class.
//
#include "MEHiggsPairJet.h"
#include "ThePEG/Utilities/SimplePhaseSpace.h"
#include "ThePEG/Interface/Parameter.h"
#include "ThePEG/Interface/Switch.h"
#include "ThePEG/Interface/ClassDocumentation.h"
#include "ThePEG/Persistency/PersistentOStream.h"
#include "ThePEG/Persistency/PersistentIStream.h"
#include "ThePEG/Repository/EventGenerator.h"
#include "ThePEG/PDT/EnumParticles.h"
#include "ThePEG/MatrixElement/Tree2toNDiagram.h"
#include "Herwig/Models/StandardModel/StandardModel.h"
#include "ThePEG/Handlers/StandardXComb.h"
#include "ThePEG/Cuts/Cuts.h"
#include "Herwig/Utilities/Maths.h"
#include <fstream>
#include <cmath>
using namespace Herwig;
MEHiggsPairJet::MEHiggsPairJet()
:_selfcoupling(1.0),_hhHcoupling(1.0), _process(0), _mh(), _wh(), _fixedalphaS(0), _alphasfixedvalue(0.123601), _alphascale(100.*GeV), _fixedscale(0),
_implementation(0),
_includeWidths(0), _includeBquark(1), _maxflavour(5), _basescale(125.*GeV), _subprocessjet(0), _alphasreweight(0), _scalemultiplier(1.0),
Mass_E(0.0),
Mass_M(0.0),
Mass_L(0.0),
Mass_T(100.),
Mass_U(0.0),
Mass_C(0.0),
Mass_D(0.0),
Mass_S(0.0),
Mass_B(5.),
Mass_Z(91.),
Mass_W(80.4),
Mass_H(125.),
Width_C(0.0),
Width_B(0.0),
Width_T(0.0),
Width_W(0.),
Width_Z(0.),
Width_H(0.0),
Coupl_Alpha_QED(1./132.348905),
Coupl_Alpha_QCD(0.1)
{
massOption(vector<unsigned int>(2,0));
}
int MEHiggsPairJet::nDim() const {
return 5;
}
void MEHiggsPairJet::doinitrun() {
// InitOpenLoops();
}
void MEHiggsPairJet::doinit() {
_theModel = generator()->standardModel();
tcHiggsPairPtr hwHiggsPair=dynamic_ptr_cast<tcHiggsPairPtr>(_theModel);
if(hwHiggsPair){
_selfcoupling=hwHiggsPair->selfcoupling();
_process=hwHiggsPair->process();
_includeBquark=hwHiggsPair->includeBquark();
_includeWidths=hwHiggsPair->includeWidths();
_implementation=hwHiggsPair->implementation();
_maxflavour=hwHiggsPair->maxflavour();
_fixedscale=hwHiggsPair->fixedscale();
_alphascale=hwHiggsPair->alphascale();
_fixedalphaS=hwHiggsPair->fixedalphaS();
_basescale=hwHiggsPair->basescale();
_subprocessjet=hwHiggsPair->subprocessjet();
_alphasreweight=hwHiggsPair->alphasreweight();
_scalemultiplier=hwHiggsPair->scalemultiplier();
_id1 = hwHiggsPair->id1();
_id1tri = hwHiggsPair->id1tri();
_id1box = hwHiggsPair->id1box();
_id1int = hwHiggsPair->id1int();
_id2 = hwHiggsPair->id2();
_id2tri = hwHiggsPair->id2tri();
_id2box = hwHiggsPair->id2box();
_id2int = hwHiggsPair->id2int();
_id3 = hwHiggsPair->id3();
_id3tri = hwHiggsPair->id3tri();
_id3box = hwHiggsPair->id3box();
_id3int = hwHiggsPair->id3int();
_id4 = hwHiggsPair->id4();
_id4tri = hwHiggsPair->id4tri();
_id4box = hwHiggsPair->id4box();
_id4int = hwHiggsPair->id4int();
}
// cout << _selfcoupling << " " << _process << " " << _includeBquark << " " << _includeWidths << " " << _implementation << " " << _maxflavour << " " << _fixedscale << " " << _alphascale << " " << _fixedalphaS << endl;
if(_implementation == 0 && _process != 0) { cerr << "The OpenLoops implementation currently only contains SM production" << endl; exit(1); }
if(_process == 4 || _process == 5) { cerr << "HH and hH production not implemented yet, please choose an hh production subprocess" << endl; exit(1); }
higgs(getParticleData(ParticleID::h0));
PDPtr top = getParticleData(ParticleID::t);
_topmass = top->mass();
PDPtr zboson = getParticleData(ParticleID::Z0);
PDPtr wboson = getParticleData(24);
_zmass = zboson->mass();
PDPtr bottom = getParticleData(ParticleID::b);
_bottommass = bottom->mass();
PDPtr heavyH = getParticleData(35);
_heavyHmass = heavyH->mass();
_heavyHwidth = heavyH->width();
Mass_E = 0.0;
Mass_M = 0.0;
Mass_L = 0.0;
Mass_T = top->mass()/GeV;
Mass_U = 0.0;
Mass_C = 0.0;
Mass_D = 0.0;
Mass_S= 0.0;
Mass_B = bottom->mass()/GeV;
if(_includeBquark == 0) { Mass_B = 0; }
Mass_Z = zboson->mass()/GeV;
Mass_W = wboson->mass()/GeV;
Mass_H = _higgs->mass()/GeV;
Width_C = 0.0;
Width_B = 0.0;
Width_T = 0.0;
Width_W = 0.0;
Width_Z = 0.0;
Width_H = 0.0;
if(_includeWidths == 1 && _implementation == 0) {
Width_T = top->width()/GeV;
Width_W = wboson->width()/GeV;
Width_Z = zboson->width()/GeV;
Width_H = _higgs->width()/GeV;
}
if(_includeWidths == 1 && _implementation != 0) {
cout << "Warning: top quark width effects are only included in the OpenLoops implementation" << endl;
}
Coupl_Alpha_QED= SM().alphaEM(sqr(2*Mass_H*GeV)); //change to correct scale.
Coupl_Alpha_QCD = SM().alphaS(sqr(2*Mass_H*GeV)); //change to correct scale
// InitOpenLoops();
_mh = _higgs->mass();
_m1 = _higgs->mass();
_m2 = _higgs->mass();
_wh = _higgs->width();
if(_higgs->massGenerator()) {
_hmass=dynamic_ptr_cast<GenericMassGeneratorPtr>(_higgs->massGenerator());
}
HwMEBase::doinit();
}
void MEHiggsPairJet::rebind(const TranslationMap & trans) {
HwMEBase::rebind(trans);
}
IVector MEHiggsPairJet::getReferences() {
IVector ret = HwMEBase::getReferences();
return ret;
}
IBPtr MEHiggsPairJet::clone() const {
return new_ptr(*this);
}
IBPtr MEHiggsPairJet::fullclone() const {
return new_ptr(*this);
}
void MEHiggsPairJet::persistentOutput(PersistentOStream & os) const {
os <<_theModel << _selfcoupling << _hhHcoupling << _process << _higgs << ounit(_topmass,GeV) << ounit(_bottommass,GeV) << ounit(_zmass,GeV) << ounit(_m1,GeV) << ounit(_m2,GeV) << ounit(_mh,GeV) << ounit(_wh,GeV) << _hmass << Mass_E << Mass_M << Mass_L << Mass_T << Mass_U << Mass_C << Mass_D << Mass_S << Mass_B << Mass_Z << Mass_W << Mass_H << Width_C << Width_B << Width_T << Width_W << Width_Z << Width_H << Coupl_Alpha_QED << Coupl_Alpha_QCD << _implementation << _fixedalphaS << _alphasfixedvalue << _includeWidths << ounit(_alphascale,GeV) << ounit(_basescale,GeV) << _fixedscale << _includeBquark << _scalemultiplier << _id1 << _id1tri << _id1box << _id1int << _id2 << _id2tri << _id2box << _id2int << _id3 << _id3tri << _id3box << _id3int << _id4 << _id4tri << _id4box << _id4int;
}
void MEHiggsPairJet::persistentInput(PersistentIStream & is, int) {
is >> _theModel >> _selfcoupling >> _hhHcoupling >> _process >> _higgs >> iunit(_topmass,GeV) >> iunit(_bottommass,GeV) >> iunit(_zmass,GeV) >> iunit(_m1,GeV) >> iunit(_m2,GeV) >> iunit(_mh,GeV) >> iunit(_wh,GeV) >> _hmass >> Mass_E >> Mass_M >> Mass_L >> Mass_T >> Mass_U >> Mass_C >> Mass_D >> Mass_S >> Mass_B >> Mass_Z >> Mass_W >> Mass_H >> Width_C >> Width_B >> Width_T >> Width_W >> Width_Z >> Width_H >> Coupl_Alpha_QED >> Coupl_Alpha_QCD >> _implementation >> _fixedalphaS >> _alphasfixedvalue >> _includeWidths >> iunit(_alphascale,GeV) >> iunit(_basescale,GeV) >> _fixedscale >> _includeBquark >> _scalemultiplier >> _id1 >> _id1tri >> _id1box >> _id1int >> _id2 >> _id2tri >> _id2box >> _id2int >> _id3 >> _id3tri >> _id3box >> _id3int >> _id4 >> _id4tri >> _id4box >> _id4int;
}
Energy2 MEHiggsPairJet::scale() const {
return _scale;
}
// Definition of the static class description member.
ClassDescription<MEHiggsPairJet> MEHiggsPairJet::initMEHiggsPairJet;
void MEHiggsPairJet::Init() {
static ClassDocumentation<MEHiggsPairJet> documentation
("The MEHiggsPairJet class implements the Higgs boson pair + jet 2->3 processes in hadron-hadron"
" collisions");
}
CrossSection MEHiggsPairJet::dSigHatDR() const {
using Constants::pi;
double mesq = me2();
return mesq*jacobian()/(16.0*sqr(Constants::pi)*sHat())*sqr(hbarc);
}
Selector<MEBase::DiagramIndex>
MEHiggsPairJet::diagrams(const DiagramVector & diags) const {
// select the diagram, this is easy for us as we have already done it
Selector<DiagramIndex> sel;
for ( DiagramIndex i = 0; i < diags.size(); ++i ) {
sel.insert(1.0, i);
}
return sel;
}
//diagrams with box or triangle
void MEHiggsPairJet::getDiagrams() const {
// get the particle data objects
PDPtr gluon = getParticleData(ParticleID::g);
PDPtr boxon = getParticleData(99926);
PDPtr triangon = getParticleData(99927);
if(_process==0||_process==1||_process==3) {
if(_subprocessjet == 0|| _subprocessjet == 1) { add(new_ptr((Tree2toNDiagram(3), gluon, gluon, gluon, 1, boxon, 2, gluon, 4, higgs(), 4, higgs(), -2))); }
for (int i = 1; i <= _maxflavour; ++i ) {
tcPDPtr q = getParticleData(i);
tcPDPtr qb = q->CC();
if(_subprocessjet == 0 || _subprocessjet == 3) { add(new_ptr((Tree2toNDiagram(3), q, gluon, gluon, 1, boxon, 2, q, 4, higgs(), 4, higgs(), -4))); }
if(_subprocessjet == 0 || _subprocessjet == 2) { add(new_ptr((Tree2toNDiagram(3), qb, gluon, gluon, 1, boxon, 2, qb, 4, higgs(), 4, higgs(), -6))); }
if(_subprocessjet == 0 || _subprocessjet == 4) { add(new_ptr((Tree2toNDiagram(2), q, qb, 1, gluon, 3, boxon, 3, gluon, 4, higgs(), 4, higgs(), -8))); }
}
}
if(_process==0||_process==2||_process==3) {
if(_subprocessjet == 0|| _subprocessjet == 1) { add(new_ptr((Tree2toNDiagram(3), gluon, gluon, gluon, 1, triangon, 2, gluon, 4, higgs(), 4, higgs(), -1))); }
for (int i = 1; i <= _maxflavour; ++i ) {
tcPDPtr q = getParticleData(i);
tcPDPtr qb = q->CC();
if(_subprocessjet == 0 || _subprocessjet == 3) { add(new_ptr((Tree2toNDiagram(3), q, gluon, gluon, 1, triangon, 2, q, 4, higgs(), 4, higgs(), -3))); }
if(_subprocessjet == 0 || _subprocessjet == 2) { add(new_ptr((Tree2toNDiagram(3), qb, gluon, gluon, 1, triangon, 2, qb, 4, higgs(), 4, higgs(), -5))); }
if(_subprocessjet == 0 || _subprocessjet == 4) { add(new_ptr((Tree2toNDiagram(2), q, qb, 1, gluon, 3, triangon, 3, gluon, 4, higgs(), 4, higgs(), -7))); }
}
}
}
//both diagrams possess the same colour structure
Selector<const ColourLines *>
MEHiggsPairJet::colourGeometries(tcDiagPtr diag) const {
// colour lines for gg to hh
static const ColourLines cgghhg1("1 2 5, -1 -2 3, -3 -5");
static const ColourLines cgghhg2("-1 -2 -5, 1 2 -3, 3 5");
static const ColourLines cqghhq("3 2 5, 1 -2 -3");
static const ColourLines cqbghhqb("-3 -2 -5, -1 2 3");
static const ColourLines cqqbhhg("1 3 5, -2 -3 -5");
static const ColourLines cqbqhhg("2 3 5, -1 -3 -5");
Selector<const ColourLines *> sel;
switch(abs(diag->id())) {
case 1: case 2:
sel.insert(1.0, &cgghhg1);
sel.insert(1.0, &cgghhg2);
break;
case 3: case 4:
sel.insert(1.0, &cqghhq);
break;
case 5: case 6:
sel.insert(1.0, &cqbghhqb);
break;
case 7: case 8:
sel.insert(1.0, &cqqbhhg);
break;
case 9: case 10:
sel.insert(1.0, &cqbqhhg);
break;
}
return sel;
}
//the matrix element squared with the appropriate factors
double MEHiggsPairJet::me2() const {
using Constants::pi;
double mesq(0.);
/*
* OpenLoops starts here
*/
//InitOpenLoops();
// parameters_write_();
// loop_parameters_write_();
/*
* OpenLoops ME
*/
//define relevant arrays to pass by reference
/*
* OpenLoops starts here
*/
double m2_tree, m2_loop[3], acc;
double ALPS(0.);
if(_fixedalphaS == 0) { ALPS=SM().alphaS(scale()); }
else if(_fixedalphaS == 1) { ALPS = SM().alphaS(sqr(_alphascale)); }
else if(_fixedalphaS == 2) { ALPS = _alphasfixedvalue; }
ol_setparameter_double("alpha_s", ALPS);
double fermiConst = SM().fermiConstant()*GeV*GeV;
double Coupl_Alpha_QED_ = 1/((pi / ( sqrt(2) * fermiConst * sqr(Mass_W) )) * 1/( 1 - sqr(Mass_W)/sqr(Mass_Z) ));
ol_setparameter_double("alpha",Coupl_Alpha_QED_);
// Set parameter: renormalization scale
ol_setparameter_double("mu", sqrt(scale()/GeV/GeV));
int _idtoeval;
// q g to q HH
if(mePartonData()[0]->id()<=6&&mePartonData()[0]->id()>0&&
mePartonData()[1]->id()==ParticleID::g) {
_idtoeval = _id1;
}
// qbar g to qbar HH
else if(mePartonData()[0]->id()>=-6&&mePartonData()[0]->id()<0&&
mePartonData()[1]->id()==ParticleID::g) {
_idtoeval = _id2;
}
// g g to g HH
else if(mePartonData()[0]->id()==ParticleID::g&&
mePartonData()[1]->id()==ParticleID::g) {
_idtoeval = _id3;
}
// q qbar to g HH
else if(mePartonData()[0]->id()<=6&&
mePartonData()[1]->id()<=6) {
_idtoeval = _id4;
}
double pp[5*ol_n_external(_idtoeval)];
// cout << "ALPS = " << ALPS << " mu = " << sqrt(scale()/GeV/GeV) << " Coupl_Alpha_QED_ = " << Coupl_Alpha_QED_ << endl;
//fill in particle momenta
for(int kk = 0; kk < 5; kk++) {
pp[5*kk] = meMomenta()[kk].e()/GeV;
pp[5*kk+1] = meMomenta()[kk].x()/GeV;
pp[5*kk+2] = meMomenta()[kk].y()/GeV;
pp[5*kk+3] = meMomenta()[kk].z()/GeV;
pp[5*kk+4] = -1;
}
// q g to q HH
if(mePartonData()[0]->id()<=6&&mePartonData()[0]->id()>0&&
mePartonData()[1]->id()==ParticleID::g) {
if(_process == 0) { ol_evaluate_loop2(_id1, pp, &m2_tree, &acc); }
if(_process == 1) { ol_evaluate_loop2(_id1tri, pp, &m2_tree, &acc); }
if(_process == 2) { ol_evaluate_loop2(_id1box, pp, &m2_tree, &acc); }
// cout << "qg->qHH" << endl;
}
// qbar g to qbar HH
else if(mePartonData()[0]->id()>=-6&&mePartonData()[0]->id()<0&&
mePartonData()[1]->id()==ParticleID::g) {
if(_process == 0) { ol_evaluate_loop2(_id2, pp, &m2_tree, &acc); }
if(_process == 1) { ol_evaluate_loop2(_id2tri, pp, &m2_tree, &acc); }
if(_process == 2) { ol_evaluate_loop2(_id2box, pp, &m2_tree, &acc); }
// cout << "qbg->qbHH" << endl;
}
// g g to g HH
else if(mePartonData()[0]->id()==ParticleID::g&&
mePartonData()[1]->id()==ParticleID::g) {
if(_process == 0) { ol_evaluate_loop2(_id3, pp, &m2_tree, &acc); }
if(_process == 1) { ol_evaluate_loop2(_id3tri, pp, &m2_tree, &acc); }
if(_process == 2) { ol_evaluate_loop2(_id3box, pp, &m2_tree, &acc); }
// cout << "gg->gHH" << endl;
}
// q qbar to g HH
else if(mePartonData()[0]->id()<=6&&
mePartonData()[1]->id()<=6) {
if(_process == 0) { ol_evaluate_loop2(_id4, pp, &m2_tree, &acc); }
if(_process == 1) { ol_evaluate_loop2(_id4tri, pp, &m2_tree, &acc); }
if(_process == 2) { ol_evaluate_loop2(_id4box, pp, &m2_tree, &acc); }
//cout << "qqb->gHH" << endl;
}
mesq = m2_tree;
/*cout << "--" << endl;
cout << "m2_tree = " << m2_tree << endl;
cout << "mesq*sHat()/GeV/GeV = " << mesq*sHat()/GeV/GeV << endl;
cout << "_process = " << _process << endl;
cout << "printing ids" << endl;
cout << _id1 << " " << _id1tri << " " << _id1box << " " << _id1int <<" " << _id2 << " " << _id2tri <<" " << _id2box << " " << _id2int << " " << _id3 <<" " << _id3tri <<" " << _id3box << " " << _id3int <<" " << _id4 << " " << _id4tri <<" " << _id4box << " " << _id4int << endl; */
return mesq*sHat()/GeV/GeV;
}
bool MEHiggsPairJet::generateKinematics(const double * r) {
// initialize jacobian
jacobian(1.);
// cms energy
Energy ecm=sqrt(sHat());
// first generate the mass of the off-shell gauge boson
// minimum mass of the
tcPDVector ptemp;
ptemp.push_back(mePartonData()[3]);
ptemp.push_back(mePartonData()[4]);
Energy2 minMass2 = max(lastCuts().minSij(mePartonData()[3],mePartonData()[4]),
lastCuts().minS(ptemp));
// minimum pt of the jet
Energy ptmin = lastCuts().minKT(mePartonData()[2]);
// maximum mass of the so pt is possible
Energy2 maxMass2 = min(ecm*(ecm-2.*ptmin),lastCuts().maxS(ptemp));
if(maxMass2<=ZERO||minMass2<ZERO) return false;
// Energy mbt= sqrt(minMass2) + r[1] * (sqrt(maxMass2) - sqrt(minMass2));
_mbt2=minMass2*maxMass2/(minMass2+r[1]*(maxMass2-minMass2));
Energy mbt = sqrt(_mbt2);
InvEnergy2 emjac1 = minMass2*maxMass2/(maxMass2-minMass2)/sqr(_mbt2);
jacobian(jacobian()/sHat()/emjac1);
// set the masses of the outgoing particles to 2-2 scattering
meMomenta()[2].setMass(ZERO);
Lorentz5Momentum pz(mbt);
// generate the polar angle of the hard scattering
double ctmin(-1.0), ctmax(1.0);
Energy q(ZERO);
try {
q = SimplePhaseSpace::getMagnitude(sHat(), meMomenta()[2].mass(),mbt);
}
catch ( ImpossibleKinematics ) {
return false;
}
Energy2 pq = sqrt(sHat())*q;
if ( ptmin > ZERO ) {
double ctm = 1.0 - sqr(ptmin/q);
if ( ctm <= 0.0 ) return false;
ctmin = max(ctmin, -sqrt(ctm));
ctmax = min(ctmax, sqrt(ctm));
}
if ( ctmin >= ctmax ) return false;
double cth = getCosTheta(ctmin, ctmax, r[0]);
Energy pt = q*sqrt(1.0-sqr(cth));
double phi = 2.0*Constants::pi*r[2];
meMomenta()[2].setVect(Momentum3( pt*sin(phi), pt*cos(phi), q*cth));
pz.setVect( Momentum3(-pt*sin(phi),-pt*cos(phi),-q*cth));
meMomenta()[2].rescaleEnergy();
pz.rescaleEnergy();
//cout << LLSudakov(0.*GeV, sqrt(_scale), 0.*GeV, 22) << endl;
//cout << "sqrt(_scale)/pt = " << sqrt(_scale)/GeV << " " << pt/GeV << endl;
// generate the momenta of the fake resonance decay products
meMomenta()[3].setMass(mePartonData()[3]->mass());
meMomenta()[4].setMass(mePartonData()[4]->mass());
Energy q2 = ZERO;
try {
q2 = SimplePhaseSpace::getMagnitude(_mbt2, meMomenta()[3].mass(),
meMomenta()[4].mass());
} catch ( ImpossibleKinematics ) {
return false;
}
// set the scale
if(_fixedscale==0) { _scale = sqr(_scalemultiplier)*sHat(); }
else if(_fixedscale==1) { _scale = sqr(_scalemultiplier)*(sqr(_basescale) + sqr(pt)); }
else if(_fixedscale==2) { _scale = sqr(_scalemultiplier)*sqr(_basescale); }
else if(_fixedscale==3) { _scale = sqr(_scalemultiplier)*sqr(_basescale + pt); }
else if(_fixedscale==5) { _scale= sqr(_scalemultiplier)*_mbt2; }
double cth2 =-1.+2.*r[3];
double phi2=Constants::twopi*r[4];
Energy pt2 =q2*sqrt(1.-sqr(cth2));
Lorentz5Momentum pl[2]={Lorentz5Momentum( pt2*cos(phi2), pt2*sin(phi2), q2*cth2,ZERO,
meMomenta()[3].mass()),
Lorentz5Momentum(-pt2*cos(phi2),-pt2*sin(phi2),-q2*cth2,ZERO,
meMomenta()[4].mass())};
pl[0].rescaleEnergy();
pl[1].rescaleEnergy();
Boost boostv(pz.boostVector());
pl[0].boost(boostv);
pl[1].boost(boostv);
meMomenta()[3] = pl[0];
meMomenta()[4] = pl[1];
// check passes all the cuts
vector<LorentzMomentum> out(3);
tcPDVector tout(3);
for(unsigned int ix=0;ix<3;++ix) {
out[ ix] = meMomenta()[ix+2];
tout[ix] = mePartonData()[ix+2];
}
if ( !lastCuts().passCuts(tout, out, mePartonData()[0], mePartonData()[1]) )
return false;
/* alphaS reweighting peformed here,
* if chosen by AlphaSreweighting interface
* via _alphasreweight.
*/
if(_alphasreweight == 1) {
// cout << sqr(pt) << endl;
double alphasFactor = sqrt( SM().alphaS(sqr(pt))/SM().alphaS(scale()) );
//cout << pt << "\t" << sqrt(scale()) << "\t" << alphasFactor << endl;
jacobian(jacobian()*alphasFactor);
}
// jacobian
jacobian((pq/sHat())*Constants::pi*jacobian()/8./sqr(Constants::pi)*q2/mbt);
return true;
}
void MEHiggsPairJet::setKinematics() {
HwMEBase::setKinematics();
}
void MEHiggsPairJet::InitOpenLoops() {
// ol_setparameter_int("order_ew", 2);
/*ol_setparameter_int("redlib1",1);
ol_setparameter_int("redlib2",7);
ol_setparameter_int("verbose",2);
ol_setparameter_int("stability_mode",21);
ol_setparameter_double("mass(23)", Mass_Z);
ol_setparameter_double("mass(24)", Mass_W);
ol_setparameter_double("mass(25)", Mass_H);
ol_setparameter_double("mass(1)", Mass_D);
ol_setparameter_double("mass(2)", Mass_U);
ol_setparameter_double("mass(3)", Mass_S);
ol_setparameter_double("mass(4)", Mass_C);
ol_setparameter_double("mass(5)", Mass_B);
ol_setparameter_double("mass(6)", Mass_T);
ol_setparameter_double("width(23)", Width_Z);
ol_setparameter_double("width(24)", Width_W);
ol_setparameter_double("width(25)", Width_H);
_id1 = ol_register_process("2 21 -> 2 25 25", 12);
_id2 = ol_register_process("-2 21 -> -2 25 25", 12);
_id3 = ol_register_process("21 21 -> 21 25 25", 12);
_id4 = ol_register_process("2 -2 -> 21 25 25", 12);
char only3h[] = "only3h";
ol_setparameter_string("approx", only3h);
_id1tri = ol_register_process("2 21 -> 2 25 25", 12);
_id2tri = ol_register_process("-2 21 -> -2 25 25", 12);
_id3tri = ol_register_process("21 21 -> 21 25 25", 12);
_id4tri = ol_register_process("2 -2 -> 21 25 25", 12);
char no3h[] = "no3h";
ol_setparameter_string("approx", no3h);
_id1box = ol_register_process("2 21 -> 2 25 25", 12);
_id2box = ol_register_process("-2 21 -> -2 25 25", 12);
_id3box = ol_register_process("21 21 -> 21 25 25", 12);
_id4box = ol_register_process("2 -2 -> 21 25 25", 12);
char interf3h[] = "interf3h";
ol_setparameter_string("approx", interf3h);
_id1int = ol_register_process("2 21 -> 2 25 25", 12);
_id2int = ol_register_process("-2 21 -> -2 25 25", 12);
_id3int = ol_register_process("21 21 -> 21 25 25", 12);
_id4int = ol_register_process("2 -2 -> 21 25 25", 12);
// Initialize OpenLoops
ol_start();*/
}
| gpl-3.0 |
LoreleiGab/igsis | visual/chamado.ajax.php | 754 | <?php
//Imprime erros com o banco
@ini_set('display_errors', '1');
error_reporting(E_ALL);
//header( 'Cache-Control: no-cache' );
//header( 'Content-type: application/xml; charset="utf-8"', true );
$con = mysqli_connect('localhost','root','','igsis');
//mysqli_set_charset($con,"utf8");
$cod = mysqli_real_escape_string( $con,$_GET['tipoChamado'] );
switch($cod){
case 1:
$cidades = array(
);
$sql = "SELECT *
FROM igsis_chamado
WHERE idTipoChamado = '$cod'
ORDER BY espaco";
$res = mysqli_query($con,$sql);
while ( $row = mysqli_fetch_array( $res ) ) {
$cidades[] = array(
'id' => $row['idEspaco'],
'select' => (utf8_encode($row['espaco'])),
);
}
echo( json_encode( $cidades ) );
break;
case 2:
break;
case 3:
break;
}
?> | gpl-3.0 |
brianmillar/ontropy.org | pages/blog.php | 2180 | <section id="main">
<?php
/*
if (isset($_GET["post"])) {
$query = "UPDATE POSTS SET VIEWS = VIEWS + 1 WHERE POST_ID = ?";
$stmt = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($stmt, "i", $_GET["post"]);
mysqli_stmt_execute($stmt);
$query = "SELECT TITLE, AUTHOR, CONTENT, DATE_FORMAT(POSTED, '%d/%m/%Y') AS POSTEDF, VIEWS FROM POSTS WHERE POST_ID = ?";
$stmt = mysqli_prepare($db, $query);
mysqli_stmt_bind_param($stmt, "i", $_GET["post"]);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($result->num_rows != 0) {
$post = mysqli_fetch_array($result);
echo "<div id='titleBar'><h1>" . $post["TITLE"] . "</h1></div><span id='backLink'><a href='index.php?page=blog'><-- Back to Blog Posts</a>  |  " . $post["POSTEDF"] . "  |  " . $post["AUTHOR"] . "  |  " . $post["VIEWS"] . " 👁  |  <button onclick='window.print();'>Print</button></span><br/><hr/><article><p style='max-width:800px;'>" . $post["CONTENT"] . "</p>";
include "comments.php";
} else
echo "<div id='titleBar'><h1>Post Not Found!</h1></div><article><a href='?page=blog'> <- Back to Blog Posts</a>";
} else {
echo "<div id='titleBar'><h1>Blog Posts</h1></div><article>";
$query = "SELECT POST_ID, TITLE, AUTHOR, CONTENT, DATE_FORMAT(POSTED, '%d/%m/%Y') AS POSTEDF, VIEWS FROM POSTS ORDER BY POSTED DESC";
$posts = mysqli_query($db, $query);
while ($post = mysqli_fetch_array($posts))
echo "<strong><a href='?page=blog&post=" . $post["POST_ID"] . "'>" . $post["TITLE"] . "</a></strong><span style='float: right;'>" . $post["VIEWS"] . " 👁  |  " . $post["AUTHOR"] . "  |  " . $post["POSTEDF"] . "</span><br/><hr/>";
}
mysqli_close($db);
*/
?>
<!--</article>-->
<h3>Ontropy.org has moved to a new server and is undergoing major updates, the database is currently unavailable.</h3>
</section>
| gpl-3.0 |
chg-hou/DawnlightSearch | src/lang/translate_fi.ts | 39809 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fi">
<context>
<name>Dialog_Advanced_Setting</name>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="14"/>
<source>Advanced Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="48"/>
<source>Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="56"/>
<source>Number of Threads Used for Querying: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="64"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="657"/>
<source>(Auto)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="69"/>
<source>1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="74"/>
<source>2</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="79"/>
<source>3</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="84"/>
<source>4</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="89"/>
<source>5</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="94"/>
<source>6</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="117"/>
<source>Result Limit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="131"/>
<source>Query Chunk Size:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="195"/>
<source>Query Limit:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="253"/>
<source>Max Items in Table:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="288"/>
<source>Search Option</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="298"/>
<source>Instant Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="318"/>
<source>Start Querying after Typing Finished:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="356"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="498"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="837"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="902"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="967"/>
<source>ms</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="383"/>
<source>Press "Enter" to Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="395"/>
<source>Date-time Format:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="402"/>
<source><html><head/><body>
<div class="table"><table class="generic">
<thead><tr class="qt-style"><th>Expression</th><th>Output</th></tr></thead>
<tbody><tr valign="top" class="odd"><td>d</td><td>the day as number without a leading zero (1 to 31)</td></tr>
<tr valign="top" class="even"><td>dd</td><td>the day as number with a leading zero (01 to 31)</td></tr>
<tr valign="top" class="odd"><td>ddd</td><td>the abbreviated localized day name (e.g. 'Mon' to 'Sun'). </td></tr>
<tr valign="top" class="even"><td>dddd</td><td>the long localized day name (e.g. 'Monday' to 'Sunday'). </td></tr>
<tr valign="top" class="odd"><td>M</td><td>the month as number without a leading zero (1-12)</td></tr>
<tr valign="top" class="even"><td>MM</td><td>the month as number with a leading zero (01-12)</td></tr>
<tr valign="top" class="odd"><td>MMM</td><td>the abbreviated localized month name (e.g. 'Jan' to 'Dec'). </td></tr>
<tr valign="top" class="even"><td>MMMM</td><td>the long localized month name (e.g. 'January' to 'December'). </td></tr>
<tr valign="top" class="odd"><td>yy</td><td>the year as two digit number (00-99)</td></tr>
<tr valign="top" class="even"><td>yyyy</td><td>the year as four digit number</td></tr>
</tbody></table></div>
<br/>
<div class="table"><table class="generic">
<thead><tr class="qt-style"><th>Expression</th><th>Output</th></tr></thead>
<tbody><tr valign="top" class="odd"><td>h</td><td>the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)</td></tr>
<tr valign="top" class="even"><td>hh</td><td>the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)</td></tr>
<tr valign="top" class="odd"><td>H</td><td>the hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
<tr valign="top" class="even"><td>HH</td><td>the hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
<tr valign="top" class="odd"><td>m</td><td>the minute without a leading zero (0 to 59)</td></tr>
<tr valign="top" class="even"><td>mm</td><td>the minute with a leading zero (00 to 59)</td></tr>
<tr valign="top" class="odd"><td>s</td><td>the second without a leading zero (0 to 59)</td></tr>
<tr valign="top" class="even"><td>ss</td><td>the second with a leading zero (00 to 59)</td></tr>
<tr valign="top" class="odd"><td>z</td><td>the milliseconds without leading zeroes (0 to 999)</td></tr>
<tr valign="top" class="even"><td>zzz</td><td>the milliseconds with leading zeroes (000 to 999)</td></tr>
<tr valign="top" class="odd"><td>AP or A</td><td>interpret as an AM/PM time. <i>AP</i> must be either "AM" or "PM".</td></tr>
<tr valign="top" class="even"><td>ap or a</td><td>Interpret as an AM/PM time. <i>ap</i> must be either "am" or "pm".</td></tr>
</tbody></table></div>
<br/>
<div class="table"><table class="generic">
<caption>Examples:</caption>
<thead><tr class="qt-style"><th>Format</th><th>Input</th></tr></thead>
<tbody><tr valign="top" class="odd"><td>dd.MM.yyyy</td><td>21.05.2001</td></tr>
<tr valign="top" class="even"><td>ddd MMMM d yy</td><td>Tue May 21 01</td></tr>
<tr valign="top" class="odd"><td>hh:mm:ss.zzz</td><td>14:13:09.042</td></tr>
<tr valign="top" class="even"><td>h:m:s ap</td><td>2:13:9 pm</td></tr>
</tbody></table></div>
</body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="460"/>
<source>Restore Sorting after New Row Inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="539"/>
<source>Database</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="545"/>
<source>Database Location</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="551"/>
<source>Main Database File Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="561"/>
<location filename="../Ui_advanced_setting_dialog.ui" line="582"/>
<source>...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="572"/>
<source>Temp Database File Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="596"/>
<source><html><head/><body><p>Will tree walk all folders under the root path, no matter whether the subfolders are in the same devices as the root path.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="599"/>
<source>Ingore Folder in Different Devices</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="606"/>
<source>Compress the database file (using zlib) to save disk space when programe is closed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="615"/>
<source>Regular Expression to Exclude Mount Path:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="641"/>
<source>Result Table</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="649"/>
<source>Prefered Size Unit:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="662"/>
<source>B</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="667"/>
<source>KB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="672"/>
<source>MB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="677"/>
<source>GB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="682"/>
<source>TB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="687"/>
<source>PB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="712"/>
<source>Theme Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="719"/>
<source><html><head/><body><p>Type a folder which contains a <span style=" color:#0109ea;">index.theme</span> file.</p><p> Themes may be available in &quot;<a href="file:///usr/share/icons/"><span style=" text-decoration: underline; color:#2980b9;">/usr/share/icons</span></a>&quot;.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="730"/>
<source>Fallback Theme Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="737"/>
<source>FallbackThemeName was introduced in Qt 5.12.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="746"/>
<source><html><head/><body><p>Type a folder which contains an <span style=" color:#0109ea;">index.theme</span> file.</p><p>Themes may be available in &quot;<a href="file:///usr/share/icons/"><span style=" text-decoration: underline; color:#2980b9;">/usr/share/icons</span></a>&quot;.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="770"/>
<source>UUID Table</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="778"/>
<source>Timer Interval</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="786"/>
<source>Mount-state Update:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="851"/>
<source>Rows Update:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_advanced_setting_dialog.ui" line="916"/>
<source>Database Update:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Dialog_Exclued_Folder</name>
<message>
<location filename="../Ui_edit_exclued_folder.ui" line="14"/>
<source>Edit Excluded Folders</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../Ui_mainwindow.ui" line="14"/>
<source>Dawnlight Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="96"/>
<source>Fi&le</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="102"/>
<source>Setti&ngs</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="106"/>
<source>&Language</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="130"/>
<source>Abo&ut</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="140"/>
<source>&View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="161"/>
<source>ToolBar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="202"/>
<location filename="../Ui_mainwindow.ui" line="873"/>
<source>&Database</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="257"/>
<location filename="../Ui_mainwindow.ui" line="881"/>
<source>SQL &Command Preview</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="285"/>
<source>ToolBar Case Sensitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="300"/>
<source>ToolBar Advanced Setting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="328"/>
<source>Sea&rch</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="402"/>
<location filename="../Ui_mainwindow.ui" line="518"/>
<source>Case Sensitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="460"/>
<source>Search Settin&gs</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="546"/>
<source>Default Match Option</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="552"/>
<source>Na&me</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="562"/>
<source>Path/Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="569"/>
<source>Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="576"/>
<source>De&v/Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="583"/>
<source>Dev/Path/Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="598"/>
<source>&About...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="609"/>
<source>&Set Excluded Folders...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="614"/>
<source>About &Qt...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="625"/>
<source> ┗ &Enable C++ MFT parser</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="628"/>
<source>Much faster than python parser</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="640"/>
<source>&Exit...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="643"/>
<source>Exit application.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="651"/>
<source>&Use MFT Parser to Build Index</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="654"/>
<source>Only NTFS partition, faster than path walk</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="666"/>
<source>&Advanced Settings...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="675"/>
<source>&Open Settings File Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="690"/>
<source>Show Location Table</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="699"/>
<source>Update DB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="708"/>
<source>Stop Updating</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="717"/>
<source>Open &Main DB Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="726"/>
<source>Open Temp &DB Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="735"/>
<source>Show Search Setting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="749"/>
<location filename="../Ui_mainwindow.ui" line="752"/>
<source>Toggle Case Sensitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="757"/>
<source>Hide</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="762"/>
<source>Show</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="770"/>
<source>Show All</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="779"/>
<location filename="../Ui_mainwindow.ui" line="782"/>
<source>Update DB (only selected)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="791"/>
<source>&Open Project Homepage...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="796"/>
<source>&Latest Version...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="801"/>
<source>Check Included</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="806"/>
<source>Uncheck Included</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="811"/>
<source>Check Updatable</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="816"/>
<source>Uncheck Updatable</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="825"/>
<source>&Search...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="828"/>
<source>Ctrl+G</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="836"/>
<source>(A&uto)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="841"/>
<source>&English</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="846"/>
<source>&Simplified Chinese (简体中文) zh_CN</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="849"/>
<source>Simplified Chinese (简体中文) zh_CN</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="857"/>
<source>&Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="865"/>
<source>S&earch Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="889"/>
<source>&Toolbar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="897"/>
<source>T&oolbar Case Snesitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="905"/>
<source>Too&lbar Advanced Setting</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="910"/>
<source>Hungarian (Magyar nyelv) hu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="915"/>
<source>Norwegian Bokmål (bokmål) nb_NO</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Ui_mainwindow.ui" line="920"/>
<source>Dutch (Nederlands) nl</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>dialog</name>
<message>
<location filename="../ui_change_advanced_setting_dialog.cpp" line="73"/>
<source>All Cores</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ui_change_advanced_setting_dialog.cpp" line="118"/>
<location filename="../ui_change_advanced_setting_dialog.cpp" line="129"/>
<source>Select Directory of Database File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ui_change_excluded_folder_dialog.cpp" line="56"/>
<source>Select Directory to Add</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>menu</name>
<message>
<location filename="../mainwindow_table_action.cpp" line="156"/>
<location filename="../mainwindow_table_action.cpp" line="250"/>
<source>Open</source>
<translation>Avaa tiedosto(t)</translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="261"/>
<source>Open path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="268"/>
<source>Copy ...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="270"/>
<source>Copy fullpath</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="272"/>
<source>Copy filename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="274"/>
<source>Copy path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="287"/>
<source>Move to trash</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="293"/>
<source>Delete</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>message</name>
<message>
<location filename="../mainwindow_table_action.cpp" line="380"/>
<source>Message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="381"/>
<source>Are you sure to DELETE?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>statusbar</name>
<message>
<location filename="../MainWindow.cpp" line="280"/>
<source>Loading...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainWindow.cpp" line="735"/>
<source>Exclude folders from indexing.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_table_action.cpp" line="392"/>
<source>Done.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_uuid_table_slots.cpp" line="220"/>
<source> [Read Only Mode]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_uuid_table_slots.cpp" line="222"/>
<source>Ready.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow_uuid_table_slots.cpp" line="226"/>
<source> [Snap Compatibility Mode]</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ui</name>
<message>
<location filename="../MainWindow.cpp" line="261"/>
<source>Database is locked by</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainWindow.cpp" line="262"/>
<source>Appname: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainWindow.cpp" line="263"/>
<source>PID: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainWindow.cpp" line="264"/>
<source>Hostname:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../MainWindow.cpp" line="268"/>
<source>Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="48"/>
<source>Search</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="49"/>
<source>Mount Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="50"/>
<source>Label</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="51"/>
<source>UUID</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="52"/>
<source>Alias</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="53"/>
<source>FS Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="54"/>
<source>Dev name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="55"/>
<source>Major Device Num</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="56"/>
<source>Minor Device Num</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="57"/>
<source>Items</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="58"/>
<source>Update</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="59"/>
<source>Progress</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="68"/>
<source>Check to search this device. The icon indicates the mount state.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="69"/>
<source>Path where the device is mounted.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="70"/>
<source>Device label.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="71"/>
<source>Universally unique identifier (UUID).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="72"/>
<source>This is a editable column. You may customize the alias of this device.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="73"/>
<source>File system type.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="74"/>
<source>Device name.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="75"/>
<location filename="../globals.cpp" line="76"/>
<source>Each storage device is represented by a major number and a range of minor numbers,
which are used to identify either the entire device or a partition within the device.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="77"/>
<source>Total number of items in this device.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="78"/>
<source>Check to update this device when click Update All button.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="79"/>
<source>Update progress</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="100"/>
<source>Filename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="101"/>
<source>Path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="102"/>
<source>Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="103"/>
<source>Folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="104"/>
<source>Extension</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="105"/>
<source>Access Time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="106"/>
<source>Modify Time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../globals.cpp" line="107"/>
<source>Change Time</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| gpl-3.0 |
DOkwufulueze/eth-vue | truffle.js | 2383 | const bip39 = require("bip39");
const hdkey = require("ethereumjs-wallet/dist/hdkey");
const ProviderEngine = require("web3-provider-engine");
const WalletSubprovider = require("web3-provider-engine/subproviders/wallet.js");
const RPCSubprovider = require("web3-provider-engine/subproviders/rpc.js");
const FilterSubprovider = require("web3-provider-engine/subproviders/filters.js");
const Web3 = require("web3");
// Get our mnemonic and create an hdwallet
var mnemonic =
"piano file obey immense polar rack great subject clutch camera maid ostrich";
var hdwallet = hdkey.default.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic));
// Get the first account using the standard hd path.
var wallet_hdpath = "m/44'/60'/0'/0/";
var wallet = hdwallet.derivePath(wallet_hdpath + "0").getWallet();
var address = "0x" + wallet.getAddress().toString("hex");
var providerUrl = "https://testnet.infura.io";
var engine = new ProviderEngine();
// pass the engine to Web3 - this next line is necessary
/* eslint-disable no-unused-vars */
var web3 = new Web3(engine);
// filters
engine.addProvider(new FilterSubprovider());
engine.addProvider(new WalletSubprovider(wallet, {}));
engine.addProvider(
new RPCSubprovider({
rpcUrl: providerUrl
})
);
engine.start(); // Required by the provider engine.
module.exports = {
compilers: {
solc: {
version: "0.7.4",
settings: {
optimizer: {
enabled: true,
runs: 200
},
evmVersion: "byzantium"
}
}
},
networks: {
ropsten: {
network_id: 3, // Official ropsten network id
provider: engine, // Use the custom provider
from: address, // Use the address derived address
gas: 4444444
},
development: {
host: "localhost",
port: 8545, // This is the conventional port. If you're using the Ganache Blockchain, change port value to the Ganache default port 7545. If you're using Truffle develop network, change port value to 9545
network_id: "666", // Match any network id. You may need to replace * with your network Id
from: "", // Add your unlocked account within the double quotes
gas: 4444444
},
ganache: {
host: "127.0.0.1",
port: 7545,
network_id: 5777,
from: "", // Findable under Ganache -> Addresses. Auth with Metamask and private key
gas: 4444444
}
}
};
| gpl-3.0 |
SleepyCreepy/Upside-Down | Assets/Scripts/Scene/MobilePlatforms/TriggerPlatform.cs | 335 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerPlatform : MonoBehaviour
{
[HideInInspector] public bool m_playerDetected = false;
void OnTriggerEnter(Collider col)
{
if (col.tag == "Player")
{
m_playerDetected = true;
}
}
}
| gpl-3.0 |
credentials/irma_assurer | src/org/irmacard/identity/assurer/VerifyClientHandler.java | 2758 | package org.irmacard.identity.assurer;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.sourceforge.scuba.smartcards.CardService;
import net.sourceforge.scuba.smartcards.CardServiceException;
import org.jmrtd.Passport;
import org.jmrtd.PassportService;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminals;
import javax.smartcardio.TerminalFactory;
public class VerifyClientHandler extends SimpleChannelInboundHandler<String> {
ChannelHandlerContext ctx;
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println("Channel has become active.");
this.ctx = ctx;
String documentNumber = "NSK8DCPJ4";
String dateOfBirth = "880810";
String dateOfExpiry = "180321";
sendPassportData(documentNumber, dateOfBirth, dateOfExpiry);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("Incoming data: " + msg);
}
protected void sendPassportData(String documentNumber, String dateOfBirth, String dateOfExpiry) {
CardTerminals terminalList = TerminalFactory.getDefault().terminals();
try {
CardService cs = CardService.getInstance(terminalList.list().get(0));
PassportReader passportReader = new PassportReader(new PassportService(cs));
// FIXME: Unless verifyIntegrity() and in turn verifyLocally() is called first, passport will be null
passportReader.verifyIntegrity(documentNumber, dateOfBirth, dateOfExpiry);
Passport passport = passportReader.getPassport();
ChannelFuture future;
System.out.printf("Sending passport data.\n");
future = ctx.writeAndFlush(passport);
System.out.println("Waiting for the operation to complete.");
assert future != null;
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
System.out.println("Operation complete.");
if (future.isSuccess()) {
System.out.println("Message sent successfully.");
} else {
future.cause().printStackTrace();
future.channel().close();
}
}
});
} catch (CardException e) {
e.printStackTrace();
} catch (CardServiceException e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
Bruno02468/ver_sua_sala | posteridade/navegante_boletim.py | 1028 | #!/bin/python
import mendel
import sys
import datetime
from urllib.error import HTTPError
import re
if len(sys.argv) != 3:
print("Especifique usuário e senha!")
sys.exit(0)
login = sys.argv[1]
senha = sys.argv[2]
ano_atual = datetime.datetime.now().year
cookie = mendel.adquirir_cookie(login, senha)
if not cookie:
print("Suas credenciais não são válidas! :(")
sys.exit(0)
default_html = mendel.requisitar("default", cookie)["html"]
try:
boletim_html = mendel.requisitar("boletim", cookie, (ano_atual, login))["html"]
except HTTPError as error:
boletim_html = error.read().decode("iso-8859-1")
nome_rx = r"<b>([^<]+)</b>"
sala_rx = r"TURMA: (\d)(?:º|ª) (?:série|ano) (.)"
match_nome = re.search(nome_rx, boletim_html)
match_sala = re.search(sala_rx, boletim_html)
if not match_nome or not match_sala:
print("Algo deu MUITO errado. Notifique o Bruno. Imediatamente.")
sys.exit(0)
nome = match_nome.group(1)
sala = match_sala.group(1) + match_sala.group(2)
print(nome + "\n" + sala)
| gpl-3.0 |
KameLong/AOdia | app/src/main/java/com/kamelong2/aodia/AOdiaIO/FileInfo.java | 1167 | package com.kamelong2.aodia.AOdiaIO;
import java.io.File;
public class FileInfo
implements Comparable<FileInfo>
{
private String m_strName; // 表示名
private File m_file; // ファイルオブジェクト
// コンストラクタ
public FileInfo( String strName,
File file )
{
m_strName = strName;
m_file = file;
}
public String getName()
{
return m_strName;
}
public File getFile()
{
return m_file;
}
// 比較
public int compareTo( FileInfo another )
{
// ディレクトリ < ファイル の順
if( true == m_file.isDirectory() && false == another.getFile().isDirectory() )
{
return -1;
}
if( false == m_file.isDirectory() && true == another.getFile().isDirectory() )
{
return 1;
}
// ファイル同士、ディレクトリ同士の場合は、ファイル名(ディレクトリ名)の大文字小文字区別しない辞書順
return m_file.getName().toLowerCase().compareTo( another.getFile().getName().toLowerCase() );
}
} | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/effects/copy_image.lua | 665 | -----------------------------------
--
-- EFFECT_COPY_IMAGE
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:setMod(MOD_UTSUSEMI, effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:setMod(MOD_UTSUSEMI, 0);
end; | gpl-3.0 |
julianmendez/fcalib | src/main/java/de/tudresden/inf/tcs/fcaapi/Expert.java | 4920 | /**
* Interface describing an expert.
* @author Baris Sertkaya
*/
package de.tudresden.inf.tcs.fcaapi;
import de.tudresden.inf.tcs.fcaapi.action.ExpertActionListener;
/*
* FCAAPI: An API for Formal Concept Analysis tools
* Copyright (C) 2009 Baris Sertkaya
*
* This file is part of FCAAPI.
* FCAAPI 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.
*
* FCAAPI 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 FCAAPI. If not, see <http://www.gnu.org/licenses/>.
*/
public interface Expert<A, I, O extends FCAObject<A, I>> {
// // Action Types
// /**
// * Type of the event fired when the expert confirms a question.
// */
// int CONFIRMED_QUESTION = 00;
//
// /**
// * Type of the event fired when the expert rejects a question.
// */
// int REJECTED_QUESTION = 1;
//
// /**
// * Type of the event fired when the expert provides a counterexample.
// */
// int PROVIDED_COUNTEREXAMPLE = 2;
//
// /**
// * Type of the event fired when the expert starts attribute exploration.
// */
// int STARTED_EXPLORATION = 3;
//
// /**
// * Type of the event fired when the expert wants to stop attribute
// exploration.
// */
// int STOPPED_EXPLORATION = 4;
//
// /**
// * Type of the event fired when the expert resumes attribute exploration.
// */
// int RESUMED_EXPLORATION = 5;
//
// /**
// * Type of the event fired when the expert resets attribute exploration.
// */
// int RESET_EXPLORATION = 6;
//
// /**
// * Type of the event fired when the expert wants to undo the last change
// he did to a counterexample
// * candidate.
// */
// int UNDO_LAST_CECHANGE = 7;
// /**
// * Type of the event fired when the expert wants to undo all changes he
// did to counterexample
// * candidates.
// */
// int UNDO_ALL_CECHANGES = 8;
// Error Message Codes
int COUNTEREXAMPLE_EXISTS = 20;
int COUNTEREXAMPLE_INVALID = 21;
/**
* Checks whether a given implication question holds. If yes, fires an
* expert action of type #CONFIRMED_QUESTION, if no an expert action of type
* #REJECTED_QUESTION and notifies listeners.
*
* @param question
* the given implication question
*/
void askQuestion(FCAImplication<A> question);
/**
* Gets a counterexample, fires an expert action of type
* #PROVIDED_COUNTEREXAMPLE
*
* @param question
* the given implication question
*/
void requestCounterExample(FCAImplication<A> question);
/**
* Adds a given ExperActionListener to the list of action listeners of this
* expert.
*
* @param listener
* expert action listener
*/
void addExpertActionListener(ExpertActionListener<A, I> listener);
void removeExpertActionListeners();
/**
* Called to notify the expert that the specified counterexample is invalid
* due to the given reason. The reason is one of #COUNTEREXAMPLE_EXISTS or
* #COUNTEREXAMPLE_INVALID. An implementation of this method should then
* perform the necessary actions. For instance, if it is a human expert, it
* should display an error message with the reason.
*
* @param counterExample
* counterexample
* @param reasonCode
* reason identifier
*/
void counterExampleInvalid(O counterExample, int reasonCode);
/**
* Called to notify the expert that the exploration finished (either the
* expert wanted it or the exploration algorithm terminated). An
* implementation of this method can for instance inform the expert by
* writing a message, popping up a window etc.
*/
void explorationFinished();
/**
* Requests a counterexample from the expert. Called in the case where
* accepting an implication would cause problems. In this case we do not ask
* the expert whether the implication holds, but tell him that accepting
* this implication will cause problems and request a counterexample
* directly using this method. Note that this can for instance occur while
* exploring DL ontologies due to anonymous ABox individuals. In a usual
* formal/partial context exploration, this case can not occur.
*
* @param implication
* implication
*/
void forceToCounterExample(FCAImplication<A> implication);
/**
* Called to notify the expert that the implication follows from the
* background knowledge
*
* @param implication
* the implication that follows from the background knowledge
*/
void implicationFollowsFromBackgroundKnowledge(FCAImplication<A> implication);
}
| gpl-3.0 |
csebastian2/study | cal/migrations/0003_auto_20151201_0041.py | 395 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cal', '0002_task_description'),
]
operations = [
migrations.AlterModelOptions(
name='task',
options={'verbose_name_plural': 'Tasks', 'verbose_name': 'Task'},
),
]
| gpl-3.0 |
mark-burnett/filament-dynamics | unit_tests/numerical/test_utils.py | 1229 | # Copyright (C) 2010 Mark Burnett
#
# 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/>.
import unittest
from actin_dynamics.numerical import utils
class RunningTotalTest(unittest.TestCase):
def test_running_total(self):
test_data = [[0, 1, 2, 3, 4, 5],
[7, 1, 2, 8],
[-5, 0, -2, 3]]
answers = [[0, 1, 3, 6, 10, 15],
[7, 8, 10, 18],
[-5, -5, -7, -4]]
for a, d in zip(answers, test_data):
self.assertEqual(a, list(utils.running_total(d)))
if '__main__' == __name__:
unittest.main()
| gpl-3.0 |
projectestac/alexandria | html/langpacks/pt/media_youtube.php | 1395 | <?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Strings for component 'media_youtube', language 'pt', version '3.11'.
*
* @package media_youtube
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = 'YouTube';
$string['pluginname_help'] = 'Site de partilha de vídeos YouTube.com. São suportadas hiperligações para vídeos e listas de reprodução.';
$string['privacy:metadata'] = 'O módulo multimédia Youtube não armazena quaisquer dados pessoais.';
$string['supportsplaylist'] = 'Listas de reprodução do YouTube';
$string['supportsvideo'] = 'Vídeos do YouTube';
| gpl-3.0 |
oliver-johnston/aquarium | scripts/pump.py | 801 | #!/usr/bin/python3
import sys, argparse
from external.AMSpi import AMSpi
def main(argv):
parser = argparse.ArgumentParser(description="Turn on a pump")
parser.add_argument('--pump', type=int)
parser.add_argument('--speed', type=int)
parser.add_argument('--anticlockwise', default=False, action='store_true')
args = parser.parse_args(argv)
pump = args.pump
clockwise = not args.anticlockwise
speed = args.speed
with AMSpi() as amspi:
amspi.set_pwm_frequency({1:100,2:100,3:100,4:100})
amspi.set_74HC595_pins(21, 20, 16)
amspi.set_L293D_pins(5, 6, 13, 19)
amspi.run_dc_motor(pump, clockwise, speed)
input("Press any key to stop: ")
amspi.stop_dc_motor(pump)
if __name__ == "__main__":
main(sys.argv[1:]) | gpl-3.0 |
kenvandine/snapd | overlord/overlord_test.go | 18772 | // -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License 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 overlord_test
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"syscall"
"testing"
"time"
. "gopkg.in/check.v1"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/overlord"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/hookstate"
"github.com/snapcore/snapd/overlord/ifacestate"
"github.com/snapcore/snapd/overlord/patch"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/testutil"
)
func TestOverlord(t *testing.T) { TestingT(t) }
type overlordSuite struct {
restoreBackends func()
}
var _ = Suite(&overlordSuite{})
func (ovs *overlordSuite) SetUpTest(c *C) {
tmpdir := c.MkDir()
dirs.SetRootDir(tmpdir)
dirs.SnapStateFile = filepath.Join(tmpdir, "test.json")
snapstate.CanAutoRefresh = nil
ovs.restoreBackends = ifacestate.MockSecurityBackends(nil)
}
func (ovs *overlordSuite) TearDownTest(c *C) {
dirs.SetRootDir("/")
ovs.restoreBackends()
}
func (ovs *overlordSuite) TestNew(c *C) {
restore := patch.Mock(42, 2, nil)
defer restore()
var configstateInitCalled bool
overlord.MockConfigstateInit(func(*hookstate.HookManager) {
configstateInitCalled = true
})
o, err := overlord.New()
c.Assert(err, IsNil)
c.Check(o, NotNil)
c.Check(o.StateEngine(), NotNil)
c.Check(o.TaskRunner(), NotNil)
c.Check(o.SnapManager(), NotNil)
c.Check(o.AssertManager(), NotNil)
c.Check(o.InterfaceManager(), NotNil)
c.Check(o.HookManager(), NotNil)
c.Check(o.DeviceManager(), NotNil)
c.Check(o.CommandManager(), NotNil)
c.Check(o.SnapshotManager(), NotNil)
c.Check(configstateInitCalled, Equals, true)
o.InterfaceManager().DisableUDevMonitor()
s := o.State()
c.Check(s, NotNil)
c.Check(o.Engine().State(), Equals, s)
s.Lock()
defer s.Unlock()
var patchLevel, patchSublevel int
s.Get("patch-level", &patchLevel)
c.Check(patchLevel, Equals, 42)
s.Get("patch-sublevel", &patchSublevel)
c.Check(patchSublevel, Equals, 2)
var refreshPrivacyKey string
s.Get("refresh-privacy-key", &refreshPrivacyKey)
c.Check(refreshPrivacyKey, HasLen, 16)
// store is setup
sto := snapstate.Store(s)
c.Check(sto, FitsTypeOf, &store.Store{})
c.Check(sto.(*store.Store).CacheDownloads(), Equals, 5)
}
func (ovs *overlordSuite) TestNewWithGoodState(c *C) {
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":%d,"patch-sublevel":%d,"some":"data","refresh-privacy-key":"0123456789ABCDEF"},"changes":null,"tasks":null,"last-change-id":0,"last-task-id":0,"last-lane-id":0}`, patch.Level, patch.Sublevel))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
d, err := state.MarshalJSON()
c.Assert(err, IsNil)
var got, expected map[string]interface{}
err = json.Unmarshal(d, &got)
c.Assert(err, IsNil)
err = json.Unmarshal(fakeState, &expected)
c.Assert(err, IsNil)
c.Check(got, DeepEquals, expected)
}
func (ovs *overlordSuite) TestNewWithStateSnapmgrUpdate(c *C) {
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":%d,"some":"data"},"changes":null,"tasks":null,"last-change-id":0,"last-task-id":0,"last-lane-id":0}`, patch.Level))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
var refreshPrivacyKey string
state.Get("refresh-privacy-key", &refreshPrivacyKey)
c.Check(refreshPrivacyKey, HasLen, 16)
}
func (ovs *overlordSuite) TestNewWithInvalidState(c *C) {
fakeState := []byte(``)
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
_, err = overlord.New()
c.Assert(err, ErrorMatches, "EOF")
}
func (ovs *overlordSuite) TestNewWithPatches(c *C) {
p := func(s *state.State) error {
s.Set("patched", true)
return nil
}
sp := func(s *state.State) error {
s.Set("patched2", true)
return nil
}
patch.Mock(1, 1, map[int][]patch.PatchFunc{1: {p, sp}})
fakeState := []byte(fmt.Sprintf(`{"data":{"patch-level":0, "patch-sublevel":0}}`))
err := ioutil.WriteFile(dirs.SnapStateFile, fakeState, 0600)
c.Assert(err, IsNil)
o, err := overlord.New()
c.Assert(err, IsNil)
state := o.State()
c.Assert(err, IsNil)
state.Lock()
defer state.Unlock()
var level int
err = state.Get("patch-level", &level)
c.Assert(err, IsNil)
c.Check(level, Equals, 1)
var sublevel int
c.Assert(state.Get("patch-sublevel", &sublevel), IsNil)
c.Check(sublevel, Equals, 1)
var b bool
err = state.Get("patched", &b)
c.Assert(err, IsNil)
c.Check(b, Equals, true)
c.Assert(state.Get("patched2", &b), IsNil)
c.Check(b, Equals, true)
}
type witnessManager struct {
state *state.State
expectedEnsure int
ensureCalled chan struct{}
ensureCallback func(s *state.State) error
}
func (wm *witnessManager) Ensure() error {
if wm.expectedEnsure--; wm.expectedEnsure == 0 {
close(wm.ensureCalled)
return nil
}
if wm.ensureCallback != nil {
return wm.ensureCallback(wm.state)
}
return nil
}
// markSeeded flags the state under the overlord as seeded to avoid running the seeding code in these tests
func markSeeded(o *overlord.Overlord) {
st := o.State()
st.Lock()
st.Set("seeded", true)
auth.SetDevice(st, &auth.DeviceState{
Brand: "canonical",
Model: "pc",
Serial: "serialserial",
})
st.Unlock()
}
func (ovs *overlordSuite) TestTrivialRunAndStop(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
markSeeded(o)
// make sure we don't try to talk to the store
snapstate.CanAutoRefresh = nil
o.Loop()
err = o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestUnknownTasks(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
o.InterfaceManager().DisableUDevMonitor()
markSeeded(o)
// make sure we don't try to talk to the store
snapstate.CanAutoRefresh = nil
// unknown tasks are ignored and succeed
st := o.State()
st.Lock()
defer st.Unlock()
t := st.NewTask("unknown", "...")
chg := st.NewChange("change-w-unknown", "...")
chg.AddTask(t)
st.Unlock()
err = o.Settle(1 * time.Second)
st.Lock()
c.Assert(err, IsNil)
c.Check(chg.Status(), Equals, state.DoneStatus)
}
func (ovs *overlordSuite) TestEnsureLoopRunAndStop(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Millisecond)
defer restoreIntv()
o := overlord.Mock()
witness := &witnessManager{
state: o.State(),
expectedEnsure: 3,
ensureCalled: make(chan struct{}),
}
o.AddManager(witness)
o.Loop()
defer o.Stop()
t0 := time.Now()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
c.Check(time.Since(t0) >= 10*time.Millisecond, Equals, true)
err := o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBeforeImmediate(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
ensure := func(s *state.State) error {
s.EnsureBefore(0)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
o.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBefore(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
ensure := func(s *state.State) error {
s.EnsureBefore(10 * time.Millisecond)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
o.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureBeforeSleepy(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
ensure := func(s *state.State) error {
overlord.MockEnsureNext(o, time.Now().Add(-10*time.Hour))
s.EnsureBefore(0)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
o.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopMediatedEnsureBeforeOutsideEnsure(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
ch := make(chan struct{})
ensure := func(s *state.State) error {
close(ch)
return nil
}
witness := &witnessManager{
state: o.State(),
expectedEnsure: 2,
ensureCalled: make(chan struct{}),
ensureCallback: ensure,
}
o.AddManager(witness)
o.Loop()
defer o.Stop()
select {
case <-ch:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
o.State().EnsureBefore(0)
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
}
func (ovs *overlordSuite) TestEnsureLoopPrune(c *C) {
restoreIntv := overlord.MockPruneInterval(200*time.Millisecond, 1000*time.Millisecond, 1000*time.Millisecond)
defer restoreIntv()
o := overlord.Mock()
st := o.State()
st.Lock()
t1 := st.NewTask("foo", "...")
chg1 := st.NewChange("abort", "...")
chg1.AddTask(t1)
chg2 := st.NewChange("prune", "...")
chg2.SetStatus(state.DoneStatus)
t0 := chg2.ReadyTime()
st.Unlock()
// observe the loop cycles to detect when prune should have happened
pruneHappened := make(chan struct{})
cycles := -1
waitForPrune := func(_ *state.State) error {
if cycles == -1 {
if time.Since(t0) > 1000*time.Millisecond {
cycles = 2 // wait a couple more loop cycles
}
return nil
}
if cycles > 0 {
cycles--
if cycles == 0 {
close(pruneHappened)
}
}
return nil
}
witness := &witnessManager{
ensureCallback: waitForPrune,
}
o.AddManager(witness)
o.Loop()
select {
case <-pruneHappened:
case <-time.After(2 * time.Second):
c.Fatal("Pruning should have happened by now")
}
err := o.Stop()
c.Assert(err, IsNil)
st.Lock()
defer st.Unlock()
c.Assert(st.Change(chg1.ID()), Equals, chg1)
c.Assert(st.Change(chg2.ID()), IsNil)
c.Assert(t1.Status(), Equals, state.HoldStatus)
}
func (ovs *overlordSuite) TestEnsureLoopPruneRunsMultipleTimes(c *C) {
restoreIntv := overlord.MockPruneInterval(100*time.Millisecond, 1000*time.Millisecond, 1*time.Hour)
defer restoreIntv()
o := overlord.Mock()
// create two changes, one that can be pruned now, one in progress
st := o.State()
st.Lock()
t1 := st.NewTask("foo", "...")
chg1 := st.NewChange("pruneNow", "...")
chg1.AddTask(t1)
t1.SetStatus(state.DoneStatus)
t2 := st.NewTask("foo", "...")
chg2 := st.NewChange("pruneNext", "...")
chg2.AddTask(t2)
t2.SetStatus(state.DoStatus)
c.Check(st.Changes(), HasLen, 2)
st.Unlock()
// start the loop that runs the prune ticker
o.Loop()
// ensure the first change is pruned
time.Sleep(1500 * time.Millisecond)
st.Lock()
c.Check(st.Changes(), HasLen, 1)
st.Unlock()
// ensure the second is also purged after it is ready
st.Lock()
chg2.SetStatus(state.DoneStatus)
st.Unlock()
time.Sleep(1500 * time.Millisecond)
st.Lock()
c.Check(st.Changes(), HasLen, 0)
st.Unlock()
// cleanup loop ticker
err := o.Stop()
c.Assert(err, IsNil)
}
func (ovs *overlordSuite) TestCheckpoint(c *C) {
oldUmask := syscall.Umask(0)
defer syscall.Umask(oldUmask)
o, err := overlord.New()
c.Assert(err, IsNil)
s := o.State()
s.Lock()
s.Set("mark", 1)
s.Unlock()
st, err := os.Stat(dirs.SnapStateFile)
c.Assert(err, IsNil)
c.Assert(st.Mode(), Equals, os.FileMode(0600))
c.Check(dirs.SnapStateFile, testutil.FileContains, `"mark":1`)
}
type sampleManager struct {
ensureCallback func()
}
func newSampleManager(s *state.State, runner *state.TaskRunner) *sampleManager {
sm := &sampleManager{}
runner.AddHandler("runMgr1", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgr1Mark", 1)
return nil
}, nil)
runner.AddHandler("runMgr2", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgr2Mark", 1)
return nil
}, nil)
runner.AddHandler("runMgrEnsureBefore", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.EnsureBefore(20 * time.Millisecond)
return nil
}, nil)
runner.AddHandler("runMgrForever", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.EnsureBefore(20 * time.Millisecond)
return &state.Retry{}
}, nil)
runner.AddHandler("runMgrWCleanup", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgrWCleanupMark", 1)
return nil
}, nil)
runner.AddCleanup("runMgrWCleanup", func(t *state.Task, _ *tomb.Tomb) error {
s := t.State()
s.Lock()
defer s.Unlock()
s.Set("runMgrWCleanupCleanedUp", 1)
return nil
})
return sm
}
func (sm *sampleManager) Ensure() error {
if sm.ensureCallback != nil {
sm.ensureCallback()
}
return nil
}
func (ovs *overlordSuite) TestTrivialSettle(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
s := o.State()
sm1 := newSampleManager(s, o.TaskRunner())
o.AddManager(sm1)
o.AddManager(o.TaskRunner())
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgr1", "1...")
chg.AddTask(t1)
s.Unlock()
o.Settle(5 * time.Second)
s.Lock()
c.Check(t1.Status(), Equals, state.DoneStatus)
var v int
err := s.Get("runMgr1Mark", &v)
c.Check(err, IsNil)
}
func (ovs *overlordSuite) TestSettleNotConverging(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
s := o.State()
sm1 := newSampleManager(s, o.TaskRunner())
o.AddManager(sm1)
o.AddManager(o.TaskRunner())
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgrForever", "1...")
chg.AddTask(t1)
s.Unlock()
err := o.Settle(250 * time.Millisecond)
s.Lock()
c.Check(err, ErrorMatches, `Settle is not converging`)
}
func (ovs *overlordSuite) TestSettleChain(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
s := o.State()
sm1 := newSampleManager(s, o.TaskRunner())
o.AddManager(sm1)
o.AddManager(o.TaskRunner())
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgr1", "1...")
t2 := s.NewTask("runMgr2", "2...")
t2.WaitFor(t1)
chg.AddAll(state.NewTaskSet(t1, t2))
s.Unlock()
o.Settle(5 * time.Second)
s.Lock()
c.Check(t1.Status(), Equals, state.DoneStatus)
c.Check(t2.Status(), Equals, state.DoneStatus)
var v int
err := s.Get("runMgr1Mark", &v)
c.Check(err, IsNil)
err = s.Get("runMgr2Mark", &v)
c.Check(err, IsNil)
}
func (ovs *overlordSuite) TestSettleChainWCleanup(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
s := o.State()
sm1 := newSampleManager(s, o.TaskRunner())
o.AddManager(sm1)
o.AddManager(o.TaskRunner())
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t1 := s.NewTask("runMgrWCleanup", "1...")
t2 := s.NewTask("runMgr2", "2...")
t2.WaitFor(t1)
chg.AddAll(state.NewTaskSet(t1, t2))
s.Unlock()
o.Settle(5 * time.Second)
s.Lock()
c.Check(t1.Status(), Equals, state.DoneStatus)
c.Check(t2.Status(), Equals, state.DoneStatus)
var v int
err := s.Get("runMgrWCleanupMark", &v)
c.Check(err, IsNil)
err = s.Get("runMgr2Mark", &v)
c.Check(err, IsNil)
err = s.Get("runMgrWCleanupCleanedUp", &v)
c.Check(err, IsNil)
}
func (ovs *overlordSuite) TestSettleExplicitEnsureBefore(c *C) {
restoreIntv := overlord.MockEnsureInterval(1 * time.Minute)
defer restoreIntv()
o := overlord.Mock()
s := o.State()
sm1 := newSampleManager(s, o.TaskRunner())
sm1.ensureCallback = func() {
s.Lock()
defer s.Unlock()
v := 0
s.Get("ensureCount", &v)
s.Set("ensureCount", v+1)
}
o.AddManager(sm1)
o.AddManager(o.TaskRunner())
defer o.Engine().Stop()
s.Lock()
defer s.Unlock()
chg := s.NewChange("chg", "...")
t := s.NewTask("runMgrEnsureBefore", "...")
chg.AddTask(t)
s.Unlock()
o.Settle(5 * time.Second)
s.Lock()
c.Check(t.Status(), Equals, state.DoneStatus)
var v int
err := s.Get("ensureCount", &v)
c.Check(err, IsNil)
c.Check(v, Equals, 2)
}
func (ovs *overlordSuite) TestRequestRestartNoHandler(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
o.State().RequestRestart(state.RestartDaemon)
}
func (ovs *overlordSuite) TestRequestRestartHandler(c *C) {
o, err := overlord.New()
c.Assert(err, IsNil)
restartRequested := false
o.SetRestartHandler(func(t state.RestartType) {
restartRequested = true
})
o.State().RequestRestart(state.RestartDaemon)
c.Check(restartRequested, Equals, true)
}
func (ovs *overlordSuite) TestOverlordCanStandby(c *C) {
restoreIntv := overlord.MockEnsureInterval(10 * time.Millisecond)
defer restoreIntv()
o := overlord.Mock()
witness := &witnessManager{
state: o.State(),
expectedEnsure: 3,
ensureCalled: make(chan struct{}),
}
o.AddManager(witness)
// can only standby after loop ran once
c.Assert(o.CanStandby(), Equals, false)
o.Loop()
defer o.Stop()
select {
case <-witness.ensureCalled:
case <-time.After(2 * time.Second):
c.Fatal("Ensure calls not happening")
}
c.Assert(o.CanStandby(), Equals, true)
}
| gpl-3.0 |
CPP0x0B/CPP0x | Chapter04/Test04_36.cc | 142 | #include <iostream>
using namespace std;
int main()
{
int i = 1;
double d = 0.1;
i /= d;
cout << i << endl;
return 0;
}
| gpl-3.0 |
hs29590/pi_electroplating | barcode_easy.py | 1514 | import sys
import time
import threading
class ReadFromScanner():
def __init__(self, port):
self.hid = { 4: 'S', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M', 17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y', 29: 'Z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ', 45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';' , 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/' }
self.fp = open(port, 'rb')
self.decodedString = '';
t1 = threading.Thread(target=self.readThread);
t1.daemon = True;
t1.start()
def __del__(self):
self.fp.close();
def readThread(self):
while True:
buffer = self.fp.read(8)
for c in buffer:
if ord(c) > 0:
try:
self.decodedString = self.decodedString + self.hid[int(ord(c))]
except:
#print "passing ", str(ord(c))
pass
def startRead(self):
self.decodedString = '';
def finishRead(self):
print(self.decodedString);
R = ReadFromScanner('/dev/hidraw0')
while(True):
a = raw_input('Press Enter to Start Read');
R.startRead();
b = raw_input('Press Enter when Read Finished or Q to exit');
R.finishRead();
if(b == 'q' or b == 'Q'):
break;
| gpl-3.0 |
samli6479/Learning | lab9/lab9/StringUtils.java | 2650 | package lab9;
import java.util.regex.Pattern;
import java.util.Random;
/** Utility function for Strings.
* @author Josh Hug
*/
public class StringUtils {
/** To get the style checker to be quiet. */
private static final int ALPHABET_SIZE = 26;
/** Random number generator for this class. */
private static Random r = new Random();
/** Sets random seed to L so that results of randomString are predictable.*/
public static void setSeed(long l) {
r = new Random(l);
}
/** Returns the next random string of length LENGTH. */
public static String randomString(int length) {
char[] someChars = new char[length];
for (int i = 0; i < length; i++) {
someChars[i] = (char) (r.nextInt(ALPHABET_SIZE) + 'a');
}
return new String(someChars);
}
/** Returns true if string S consists of characters between
* 'a' and 'z' only. No spaces, numbers, upper-case, or any other
* characters are allowed.
*/
public static boolean isLowerCase(String s) {
return Pattern.matches("[a-z]*", s);
}
/** Returns the string that comes right after S in alphabetical order.
* For example, if s is 'potato', this method will return 'potatp'. If
* the last character is a z, then we add to the next position, and so
* on.
*/
public static String nextString(String s) {
/* Handle all zs as a special case to keep helper method simple. */
if (isAllzs(s)) {
return allAs(s.length() + 1);
}
char[] charVersion = s.toCharArray();
incrementCharArray(charVersion, charVersion.length - 1);
return new String(charVersion);
}
/** Helper function for nextString. Increments the Pth position of X
* by one, wrapping around to 'a' if p == 'z'. If wraparound occurs,
* then we need to carry the one, and we increment position P - 1.
*
* Will fail for a character array containing only zs.
*/
private static void incrementCharArray(char [] x, int p) {
if (x[p] != 'z') {
x[p] += 1;
} else {
x[p] = 'a';
incrementCharArray(x, p - 1);
}
}
/** Returns a string of all 'a' of length LEN. */
private static String allAs(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append('a');
}
return sb.toString();
}
/** Returns true if S is all 'z'. False for empty strings */
public static boolean isAllzs(String s) {
return Pattern.matches("[z]+", s);
}
}
| gpl-3.0 |
mlistemann/magic-lens-accessibility-maps | lib/webgl-utils.js | 2076 | // WebGL standard operations
function initWebGL(canvas){
var gl = null;
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
for (var i = 0; i < names.length; ++i){
try{
gl = canvas.getContext(names[i], {stencil: true});
}
catch(e){}
if (gl) break;
}
if (!gl){
console.log("WebGL context is not available.");
return;
}
return gl;
}
function initShaders(gl, vShader, fShader){
var program = createProgram(gl, vShader, fShader);
if (!program) {
console.log('Failed to create program');
return false;
}
gl.useProgram(program);
gl.program = program;
return true;
}
// To create and compile the shaders
function createShader(gl, type, source){
var shader = gl.createShader(type);
if (shader == null) {
console.log('unable to create shader');
return null;
}
// Set the shader program
gl.shaderSource(shader, source);
// Compile the shader
gl.compileShader(shader);
// Check the result of compilation
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var error = gl.getShaderInfoLog(shader);
console.log('Failed to compile shader: ' + error);
gl.deleteShader(shader);
return null;
}
return shader;
}
// To link the 2 shaders into a program
function createProgram(gl, vShader, fShader){
// Create shader objects
var vertexShader = createShader(gl, gl.VERTEX_SHADER, vShader);
var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fShader);
if (!vertexShader || !fragmentShader) {
return null;
}
var program = gl.createProgram();
// Attach the shader objects
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// Link the program object
gl.linkProgram(program);
// Check the result of linking
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var error = gl.getProgramInfoLog(program);
console.log('Failed to link program: ' + error);
gl.deleteProgram(program);
gl.deleteShader(fragmentShader);
gl.deleteShader(vertexShader);
return null;
}
return program;
} | gpl-3.0 |
Stormister/Rediscovered-Mod-1.7.10 | src/main/java/com/stormister/rediscovered/RenderBlockRedEgg.java | 1950 | package com.stormister.rediscovered;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.world.IBlockAccess;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
/**
* GCCoreBlockRendererCraftingTable.java
*
* This file is part of the Galacticraft project
*
* @author micdoodle8
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*
*/
public class RenderBlockRedEgg implements ISimpleBlockRenderingHandler
{
final int renderID;
public RenderBlockRedEgg(int var1)
{
this.renderID = var1;
}
public void renderRedEgg(RenderBlocks renderBlocks, IBlockAccess iblockaccess, Block par1Block, int par2, int par3, int par4)
{
renderBlocks.overrideBlockTexture = par1Block.getIcon(iblockaccess, par2, par3, par4, 0);
renderBlocks.setRenderBounds(0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F);
renderBlocks.renderStandardBlock(par1Block, par2, par3, par4);
renderBlocks.clearOverrideBlockTexture();
}
private final TileEntityRedEgg egg = new TileEntityRedEgg();
@Override
public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)
{
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-0.5F, -1.5F, -0.5F);
GL11.glScalef(1.0F, 1.0F, 1.0F);
TileEntityRendererDispatcher.instance.renderTileEntityAt(this.egg, 0.0D, 1.0D, 0.0D, 0.0F);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
this.renderRedEgg(renderer, world, block, x, y, z);
return true;
}
@Override
public boolean shouldRender3DInInventory(int modelId)
{
return true;
}
@Override
public int getRenderId()
{
return this.renderID;
}
} | gpl-3.0 |
grote/Online-ASP | libgringo/src/claspoutput.cpp | 8367 | // Copyright (c) 2008, Roland Kaminski
//
// This file is part of GrinGo.
//
// GrinGo 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.
//
// GrinGo 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 GrinGo. If not, see <http://www.gnu.org/licenses/>.
#include <gringo/claspoutput.h>
//#define DEBUG_ICLASP
#ifdef DEBUG_ICLASP
#include <fstream>
std::fstream g_out("iclasp.h", std::ios_base::out | std::ios_base::trunc);
#endif
#ifdef WITH_CLASP
#include <gringo/gringoexception.h>
#include <gringo/grounder.h>
#include <clasp/program_builder.h>
using namespace gringo;
using namespace NS_OUTPUT;
ClaspOutput::ClaspOutput(Clasp::ProgramBuilder *b, bool shift) : SmodelsConverter(&std::cout, shift), b_(b)
{
}
void ClaspOutput::initialize(GlobalStorage *g, SignatureVector *pred)
{
SmodelsConverter::initialize(g, pred);
b_->setCompute(getFalse(), false);
#ifdef DEBUG_ICLASP
g_out << "api.setCompute(t" << getFalse() << ", false);" << NL;
#endif
}
void ClaspOutput::printBasicRule(int head, const IntVector &pos, const IntVector &neg)
{
b_->startRule();
b_->addHead(head);
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
b_->addToBody(*it, false);
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
b_->addToBody(*it, true);
b_->endRule();
#ifdef DEBUG_ICLASP
g_out << "api.startRule().addHead(t" << head << ")";
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
g_out << ".addToBody(t" << *it << ", false)";
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
g_out << ".addToBody(t" << *it << ", true)";
g_out << ".endRule();" << NL;
#endif
}
void ClaspOutput::printConstraintRule(int head, int bound, const IntVector &pos, const IntVector &neg)
{
b_->startRule(Clasp::CONSTRAINTRULE, bound);
b_->addHead(head);
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
b_->addToBody(*it, false);
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
b_->addToBody(*it, true);
b_->endRule();
#ifdef DEBUG_ICLASP
g_out << "api.startRule(Clasp::CONSTRAINTRULE, " << bound << ").addHead(t" << head << ")";
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
g_out << ".addToBody(t" << *it << ", false)";
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
g_out << ".addToBody(t" << *it << ", true)";
g_out << ".endRule();" << NL;
#endif
}
void ClaspOutput::printChoiceRule(const IntVector &head, const IntVector &pos, const IntVector &neg)
{
b_->startRule(Clasp::CHOICERULE);
for(IntVector::const_iterator it = head.begin(); it != head.end(); it++)
b_->addHead(*it);
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
b_->addToBody(*it, false);
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
b_->addToBody(*it, true);
b_->endRule();
#ifdef DEBUG_ICLASP
g_out << "api.startRule(Clasp::CHOICERULE)";
for(IntVector::const_iterator it = head.begin(); it != head.end(); it++)
g_out << ".addHead(t" << *it << ")";
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
g_out << ".addToBody(t" << *it << ", false)";
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
g_out << ".addToBody(t" << *it << ", true)";
g_out << ".endRule();" << NL;
#endif
}
void ClaspOutput::printWeightRule(int head, int bound, const IntVector &pos, const IntVector &neg, const IntVector &wPos, const IntVector &wNeg)
{
b_->startRule(Clasp::WEIGHTRULE, bound);
b_->addHead(head);
IntVector::const_iterator itW = wNeg.begin();
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++, itW++)
b_->addToBody(*it, false, *itW);
itW = wPos.begin();
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++, itW++)
b_->addToBody(*it, true, *itW);
b_->endRule();
#ifdef DEBUG_ICLASP
g_out << "api.startRule(Clasp::WEIGHTRULE, " << bound << ").addHead(t" << head << ")";
itW = wNeg.begin();
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++, itW++)
g_out << ".addToBody(t" << *it << ", false, " << *itW << ")";
itW = wPos.begin();
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++, itW++)
g_out << ".addToBody(t" << *it << ", true, " << *itW << ")";
g_out << ".endRule();" << NL;
#endif
}
void ClaspOutput::printMinimizeRule(const IntVector &pos, const IntVector &neg, const IntVector &wPos, const IntVector &wNeg)
{
b_->startRule(Clasp::OPTIMIZERULE);
IntVector::const_iterator itW = wNeg.begin();
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++, itW++)
b_->addToBody(*it, false, *itW);
itW = wPos.begin();
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++, itW++)
b_->addToBody(*it, true, *itW);
b_->endRule();
}
void ClaspOutput::printDisjunctiveRule(const IntVector &head, const IntVector &pos, const IntVector &neg)
{
throw GrinGoException("Error: sorry clasp cannot handle disjunctive rules use option --shift!");
}
void ClaspOutput::printComputeRule(int models, const IntVector &pos, const IntVector &neg)
{
for(IntVector::const_iterator it = neg.begin(); it != neg.end(); it++)
b_->setCompute(*it, false);
for(IntVector::const_iterator it = pos.begin(); it != pos.end(); it++)
b_->setCompute(*it, true);
}
void ClaspOutput::finalize(bool)
{
}
int ClaspOutput::newUid()
{
uids_++;
int uid = b_->newAtom();
#ifdef DEBUG_ICLASP
g_out << "int t" << uid << " = api.newAtom();" << NL;
#endif
return uid;
}
bool ClaspOutput::addAtom(NS_OUTPUT::Atom *r)
{
bool ret = Output::addAtom(r);
if(ret && isVisible(r->predUid_))
{
b_->setAtomName(r->uid_, atomToString(r->predUid_, r->values_).c_str());
#ifdef DEBUG_ICLASP
g_out << "api.setAtomName(t" << r->uid_ << ", \"" << atomToString(r->predUid_, r->values_) << "\");" << NL;
#endif
}
return ret;
}
ClaspOutput::~ClaspOutput()
{
}
#endif
#ifdef WITH_ICLASP
IClaspOutput::IClaspOutput(Clasp::ProgramBuilder *b, bool shift) : ClaspOutput(b, shift), incUid_(0)
{
}
void IClaspOutput::initialize(GlobalStorage *g, SignatureVector *pred)
{
#ifdef DEBUG_ICLASP
g_out << "LitVec assumptions;" << NL << NL;
g_out << "solver.undoUntil(0);" << NL;
g_out << "api.updateProgram();" << NL;
#endif
ClaspOutput::initialize(g, pred);
incUid_ = 0;
reinitialize();
}
void IClaspOutput::reinitialize()
{
#ifdef DEBUG_ICLASP
if(incUid_)
{
g_out << "solver.undoUntil(0);" << NL;
g_out << "api.updateProgram();" << NL;
g_out << "api.unfreeze(t" << incUid_ << ");" << NL;
}
#endif
if(incUid_)
{
b_->unfreeze(incUid_);
}
// create a new uid
incUid_ = newUid();
b_->setAtomName(incUid_, "");
b_->freeze(incUid_);
#ifdef DEBUG_ICLASP
g_out << "api.setAtomName(t" << incUid_ << ", \"\");" << NL;
g_out << "// delta(" << incUid_ << ")." << NL;
g_out << "api.freeze(t" << incUid_ << ");" << NL;
#endif
}
void IClaspOutput::finalize(bool last)
{
#ifdef DEBUG_ICLASP
if(!last)
{
static int its = 0;
its++;
g_out << "std::cout << \"============= solving " << its << " =============\" << std::endl;" << NL;
g_out << "api.endProgram(solver, options.initialLookahead);" << NL << NL;
g_out << "assumptions.clear();" << NL;
g_out << "assumptions.push_back(api.stats.index[t" << incUid_ << "].lit);" << NL;
g_out << "Clasp::solve(solver, assumptions, options.numModels, options.solveParams);" << NL << NL;
}
#endif
ClaspOutput::finalize(last);
}
void IClaspOutput::unfreezeAtom(int uid) {
b_->unfreeze(uid);
}
void IClaspOutput::printExternalRule(int uid, int pred_uid) {
if(isVisible(pred_uid)) {
b_->freeze(uid);
} else {
throw GrinGoException("External facts can not be hidden.");
}
}
int IClaspOutput::getIncUid()
{
return incUid_;
}
void IClaspOutput::print(NS_OUTPUT::Object *o)
{
#ifdef DEBUG_ICLASP
g_out << "// ";
o->print_plain(this, g_out);
#endif
SmodelsConverter::print(o);
}
#endif
| gpl-3.0 |
sneakret/NBTEditor | src/main/java/com/goncalomb/bukkit/nbteditor/nbt/TamedNBT.java | 1321 | /*
* Copyright (C) 2013-2015 Gonçalo Baltazar <me@goncalomb.com>
*
* This file is part of NBTEditor.
*
* NBTEditor 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.
*
* NBTEditor 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 NBTEditor. If not, see <http://www.gnu.org/licenses/>.
*/
package com.goncalomb.bukkit.nbteditor.nbt;
import com.goncalomb.bukkit.nbteditor.nbt.variable.BooleanVariable;
import com.goncalomb.bukkit.nbteditor.nbt.variable.NBTGenericVariableContainer;
import com.goncalomb.bukkit.nbteditor.nbt.variable.StringVariable;
public class TamedNBT extends BreedNBT {
static {
NBTGenericVariableContainer variables = new NBTGenericVariableContainer("Tameable");
variables.add("Owner", new StringVariable("Owner"));
variables.add("Sitting", new BooleanVariable("Sitting"));
registerVariables(TamedNBT.class, variables);
}
}
| gpl-3.0 |
Z-Shang/LoLi | src/LoLi2/loli_typeenv.cpp | 570 | /*
* =====================================================================================
*
* Filename: loli_typeenv.cpp
*
* Description: Type Env of LoLi
*
* Version: 1.0
* Created: 08/30/2014 06:56:29 PM
* Revision: none
* Compiler: gcc
*
* Author: Z.Shang (), shangzhanlin@gmail.com
* Organization:
*
* =====================================================================================
*/
#include "include/loli_obj.h"
#include "include/loli_typeclass.h"
#include "include/loli_typeenv.h"
| gpl-3.0 |
nsxa/cphp | index.php | 1227 | <?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
$tiempo_inicio = microtime(true);
//exec("tracert 8.8.8.8 && exit", $output);
//exec('ipconfig /all',$output);
//exec('systeminfo',$output);
exec('c:/MIEXE.exe');
//print_r($output);
$tiempo_fin = microtime(true);
echo "Tiempo empleado c++: " . ($tiempo_fin - $tiempo_inicio);
// en php
$tiempo_inicio2 = microtime(true);
$elements=100000;
$operations=1000;
for($i=0;$i<$elements;$i++)
{
$a[$i] = $i;
$b[$i] = $i;
}
for($j=0;$j<$operations;$j++)
{
for($x=0;$x<$elements;$x++)
{$a[$x]+=$b[$x];}
}
$tiempo_fin2 = microtime(true);
echo "Tiempo empleado php: " . ($tiempo_fin2 - $tiempo_inicio2);
?><html>
<br><br><br>
<br>Algoritmo:<br>
unsigned int elements=100000;<br>
unsigned int operations=1000;<br>
<br>
int *a = new int[elements];<br>
int *b = new int[elements];<br>
<br>
for (unsigned int i=0; i<elements; i++)<br>
{<br>
a[i] = i;<br>
b[i] = i;<br>
}<br>
<br>
for (unsigned int j=0; j<operations; j++)<br>
for (unsigned int i=0; i<elements; i++)<br>
a[i] += b[i];<br><br>
</html>
<?php
exit();
?>
| gpl-3.0 |
CarlosManuelRodr/wxChaos | libs/wxMSW-3.1.4/src/osx/core/display.cpp | 12520 | /////////////////////////////////////////////////////////////////////////////
// Name: src/osx/core/display.cpp
// Purpose: Mac implementation of wxDisplay class
// Author: Ryan Norton & Brian Victor
// Modified by: Royce Mitchell III, Vadim Zeitlin
// Created: 06/21/02
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/private/display.h"
#ifndef WX_PRECOMP
#include "wx/dynarray.h"
#include "wx/log.h"
#include "wx/string.h"
#include "wx/gdicmn.h"
#endif
#include "wx/osx/private.h"
// ----------------------------------------------------------------------------
// common helpers compiled even in wxUSE_DISPLAY==0 case
// ----------------------------------------------------------------------------
// This one is defined in Objective C++ code.
extern wxRect wxOSXGetMainDisplayClientArea();
namespace
{
wxRect wxGetDisplayGeometry(CGDirectDisplayID id)
{
CGRect theRect = CGDisplayBounds(id);
return wxRect( (int)theRect.origin.x,
(int)theRect.origin.y,
(int)theRect.size.width,
(int)theRect.size.height ); //floats
}
int wxGetDisplayDepth(CGDirectDisplayID id)
{
CGDisplayModeRef currentMode = CGDisplayCopyDisplayMode(id);
CFStringRef encoding = CGDisplayModeCopyPixelEncoding(currentMode);
int theDepth = 32; // some reasonable default
if(encoding)
{
if(CFStringCompare(encoding, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
theDepth = 32;
else if(CFStringCompare(encoding, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
theDepth = 16;
else if(CFStringCompare(encoding, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
theDepth = 8;
CFRelease(encoding);
}
CGDisplayModeRelease(currentMode);
return theDepth;
}
wxSize wxGetDisplaySizeMM(CGDirectDisplayID id)
{
const CGSize size = CGDisplayScreenSize(id);
return wxSize(wxRound(size.width), wxRound(size.height));
}
} // anonymous namespace
#if wxUSE_DISPLAY
#include "wx/scopedarray.h"
// ----------------------------------------------------------------------------
// display classes implementation
// ----------------------------------------------------------------------------
class wxDisplayImplMacOSX : public wxDisplayImpl
{
public:
wxDisplayImplMacOSX(unsigned n, CGDirectDisplayID id)
: wxDisplayImpl(n),
m_id(id)
{
}
virtual wxRect GetGeometry() const wxOVERRIDE;
virtual wxRect GetClientArea() const wxOVERRIDE;
virtual int GetDepth() const wxOVERRIDE;
virtual wxSize GetSizeMM() const wxOVERRIDE;
virtual wxArrayVideoModes GetModes(const wxVideoMode& mode) const wxOVERRIDE;
virtual wxVideoMode GetCurrentMode() const wxOVERRIDE;
virtual bool ChangeMode(const wxVideoMode& mode) wxOVERRIDE;
virtual bool IsPrimary() const wxOVERRIDE;
private:
CGDirectDisplayID m_id;
wxDECLARE_NO_COPY_CLASS(wxDisplayImplMacOSX);
};
class wxDisplayFactoryMacOSX : public wxDisplayFactory
{
public:
wxDisplayFactoryMacOSX() {}
virtual wxDisplayImpl *CreateDisplay(unsigned n) wxOVERRIDE;
virtual unsigned GetCount() wxOVERRIDE;
virtual int GetFromPoint(const wxPoint& pt) wxOVERRIDE;
protected:
wxDECLARE_NO_COPY_CLASS(wxDisplayFactoryMacOSX);
};
// ============================================================================
// wxDisplayFactoryMacOSX implementation
// ============================================================================
// gets all displays that are not mirror displays
static CGDisplayErr wxOSXGetDisplayList(CGDisplayCount maxDisplays,
CGDirectDisplayID *displays,
CGDisplayCount *displayCount)
{
CGDisplayErr error = kCGErrorSuccess;
CGDisplayCount onlineCount;
error = CGGetOnlineDisplayList(0,NULL,&onlineCount);
if ( error == kCGErrorSuccess )
{
*displayCount = 0;
if ( onlineCount > 0 )
{
CGDirectDisplayID *onlineDisplays = new CGDirectDisplayID[onlineCount];
error = CGGetOnlineDisplayList(onlineCount,onlineDisplays,&onlineCount);
if ( error == kCGErrorSuccess )
{
for ( CGDisplayCount i = 0; i < onlineCount; ++i )
{
if ( CGDisplayMirrorsDisplay(onlineDisplays[i]) != kCGNullDirectDisplay )
continue;
if ( displays == NULL )
*displayCount += 1;
else
{
if ( *displayCount < maxDisplays )
{
displays[*displayCount] = onlineDisplays[i];
*displayCount += 1;
}
}
}
}
delete[] onlineDisplays;
}
}
return error;
}
unsigned wxDisplayFactoryMacOSX::GetCount()
{
CGDisplayCount count;
CGDisplayErr err = wxOSXGetDisplayList(0, NULL, &count);
wxCHECK_MSG( err == CGDisplayNoErr, 0, "wxOSXGetDisplayList() failed" );
return count;
}
int wxDisplayFactoryMacOSX::GetFromPoint(const wxPoint& p)
{
CGPoint thePoint = {(float)p.x, (float)p.y};
CGDirectDisplayID theID;
CGDisplayCount theCount;
CGDisplayErr err = CGGetDisplaysWithPoint(thePoint, 1, &theID, &theCount);
wxASSERT(err == CGDisplayNoErr);
int nWhich = wxNOT_FOUND;
if (theCount)
{
theCount = GetCount();
CGDirectDisplayID* theIDs = new CGDirectDisplayID[theCount];
err = wxOSXGetDisplayList(theCount, theIDs, &theCount);
wxASSERT(err == CGDisplayNoErr);
for (nWhich = 0; nWhich < (int) theCount; ++nWhich)
{
if (theIDs[nWhich] == theID)
break;
}
delete [] theIDs;
if (nWhich == (int) theCount)
{
wxFAIL_MSG(wxT("Failed to find display in display list"));
nWhich = wxNOT_FOUND;
}
}
return nWhich;
}
wxDisplayImpl *wxDisplayFactoryMacOSX::CreateDisplay(unsigned n)
{
CGDisplayCount theCount = GetCount();
wxScopedArray<CGDirectDisplayID> theIDs(theCount);
CGDisplayErr err = wxOSXGetDisplayList(theCount, theIDs.get(), &theCount);
wxCHECK_MSG( err == CGDisplayNoErr, NULL, "wxOSXGetDisplayList() failed" );
wxCHECK_MSG( n < theCount, NULL, wxS("Invalid display index") );
return new wxDisplayImplMacOSX(n, theIDs[n]);
}
// ============================================================================
// wxDisplayImplMacOSX implementation
// ============================================================================
bool wxDisplayImplMacOSX::IsPrimary() const
{
return CGDisplayIsMain(m_id);
}
wxRect wxDisplayImplMacOSX::GetGeometry() const
{
return wxGetDisplayGeometry(m_id);
}
wxRect wxDisplayImplMacOSX::GetClientArea() const
{
// VZ: I don't know how to get client area for arbitrary display but
// wxGetClientDisplayRect() does work correctly for at least the main
// one (TODO: do it correctly for the other displays too)
if ( IsPrimary() )
return wxOSXGetMainDisplayClientArea();
return wxDisplayImpl::GetClientArea();
}
int wxDisplayImplMacOSX::GetDepth() const
{
return wxGetDisplayDepth(m_id);
}
wxSize wxDisplayImplMacOSX::GetSizeMM() const
{
return wxGetDisplaySizeMM(m_id);
}
static int wxOSXCGDisplayModeGetBitsPerPixel( CGDisplayModeRef theValue )
{
wxCFRef<CFStringRef> pixelEncoding( CGDisplayModeCopyPixelEncoding(theValue) );
int depth = 0;
if ( CFStringCompare( pixelEncoding, CFSTR(IO32BitDirectPixels) , kCFCompareCaseInsensitive) == kCFCompareEqualTo )
depth = 32;
else if ( CFStringCompare( pixelEncoding, CFSTR(IO16BitDirectPixels) , kCFCompareCaseInsensitive) == kCFCompareEqualTo )
depth = 16;
else if ( CFStringCompare( pixelEncoding, CFSTR(IO8BitIndexedPixels) , kCFCompareCaseInsensitive) == kCFCompareEqualTo )
depth = 8;
return depth;
}
wxArrayVideoModes wxDisplayImplMacOSX::GetModes(const wxVideoMode& mode) const
{
wxArrayVideoModes resultModes;
wxCFRef<CFArrayRef> theArray(CGDisplayCopyAllDisplayModes( m_id ,NULL ) );
for (CFIndex i = 0; i < CFArrayGetCount(theArray); ++i)
{
CGDisplayModeRef theValue = static_cast<CGDisplayModeRef>(const_cast<void*>(CFArrayGetValueAtIndex(theArray, i)));
wxVideoMode theMode(
CGDisplayModeGetWidth(theValue),
CGDisplayModeGetHeight(theValue),
wxOSXCGDisplayModeGetBitsPerPixel(theValue),
CGDisplayModeGetRefreshRate(theValue));
if (theMode.Matches( mode ))
resultModes.Add( theMode );
}
return resultModes;
}
wxVideoMode wxDisplayImplMacOSX::GetCurrentMode() const
{
wxCFRef<CGDisplayModeRef> theValue( CGDisplayCopyDisplayMode( m_id ) );
return wxVideoMode(
CGDisplayModeGetWidth(theValue),
CGDisplayModeGetHeight(theValue),
wxOSXCGDisplayModeGetBitsPerPixel(theValue),
CGDisplayModeGetRefreshRate(theValue));
}
bool wxDisplayImplMacOSX::ChangeMode( const wxVideoMode& mode )
{
#ifndef __WXOSX_IPHONE__
if (mode == wxDefaultVideoMode)
{
CGRestorePermanentDisplayConfiguration();
return true;
}
#endif
wxCHECK_MSG( mode.GetWidth() && mode.GetHeight(), false,
wxT("at least the width and height must be specified") );
bool bOK = false;
wxCFRef<CFArrayRef> theArray(CGDisplayCopyAllDisplayModes( m_id ,NULL ) );
for (CFIndex i = 0; i < CFArrayGetCount(theArray); ++i)
{
CGDisplayModeRef theValue = static_cast<CGDisplayModeRef>(const_cast<void*>(CFArrayGetValueAtIndex(theArray, i)));
wxVideoMode theMode(
CGDisplayModeGetWidth(theValue),
CGDisplayModeGetHeight(theValue),
wxOSXCGDisplayModeGetBitsPerPixel(theValue),
CGDisplayModeGetRefreshRate(theValue));
if ( theMode.GetWidth() == mode.GetWidth() && theMode.GetHeight() == mode.GetHeight() &&
( mode.GetDepth() == 0 || theMode.GetDepth() == mode.GetDepth() ) &&
( mode.GetRefresh() == 0 || theMode.GetRefresh() == mode.GetRefresh() ) )
{
CGDisplaySetDisplayMode( m_id, theValue , NULL );
bOK = true;
break;
}
}
return bOK;
}
// ============================================================================
// wxDisplay::CreateFactory()
// ============================================================================
/* static */ wxDisplayFactory *wxDisplay::CreateFactory()
{
return new wxDisplayFactoryMacOSX;
}
#else // !wxUSE_DISPLAY
class wxDisplayImplSingleMacOSX : public wxDisplayImplSingle
{
public:
virtual wxRect GetGeometry() const wxOVERRIDE
{
return wxGetDisplayGeometry(CGMainDisplayID());
}
virtual wxRect GetClientArea() const wxOVERRIDE
{
return wxOSXGetMainDisplayClientArea();
}
virtual int GetDepth() const wxOVERRIDE
{
return wxGetDisplayDepth(CGMainDisplayID());
}
virtual wxSize GetSizeMM() const wxOVERRIDE
{
return wxGetDisplaySizeMM(CGMainDisplayID());
}
};
class wxDisplayFactorySingleMacOSX : public wxDisplayFactorySingle
{
protected:
virtual wxDisplayImpl *CreateSingleDisplay() wxOVERRIDE
{
return new wxDisplayImplSingleMacOSX;
}
};
/* static */ wxDisplayFactory *wxDisplay::CreateFactory()
{
return new wxDisplayFactorySingleMacOSX;
}
#endif // wxUSE_DISPLAY
| gpl-3.0 |
modemm3/fic | fic-inventory/fic-inventory-business/src/main/java/com/mx/fic/inventory/business/ProviderBean.java | 3198 | package com.mx.fic.inventory.business;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TransactionRequiredException;
import javax.persistence.TypedQuery;
import com.mx.fic.inventory.business.builder.config.TransferObjectAssembler;
import com.mx.fic.inventory.business.exception.PersistenceException;
import com.mx.fic.inventory.dto.ProviderDTO;
import com.mx.fic.inventory.persistent.Company;
import com.mx.fic.inventory.persistent.Provider;
import com.mx.fic.inventory.persistent.Status;
import com.mx.fic.inventory.persistent.TypePerson;
//@Local
@Stateless (mappedName = "ProviderBean")
@TransactionManagement (TransactionManagementType.CONTAINER)
public class ProviderBean implements ProviderBeanLocal {
@PersistenceContext
private EntityManager entityManager;
/* (non-Javadoc)
* @see com.mx.fic.inventory.business.ProviderBeanLocal#save(com.mx.fic.inventory.dto.ProviderDTO)
*/
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void save(final ProviderDTO providerDTO) throws PersistenceException{
final Provider provider = new Provider();
final Company company = new Company();
final Status status = new Status();
final TypePerson typePerson = new TypePerson();
try{
company.setId(providerDTO.getCompanyId());
provider.setCompany(company);
provider.setEmail(providerDTO.getEmail());
provider.setLastName(providerDTO.getLastName());
provider.setName(providerDTO.getName());
provider.setReasonSocial(providerDTO.getReasonSocial());
provider.setRfc(providerDTO.getRfc());
status.setId(providerDTO.getStatusId());
provider.setStatus(status);
provider.setSurName(providerDTO.getSurName());
typePerson.setId(providerDTO.getTypePersonId());
provider.setTypePerson(typePerson);
entityManager.persist(provider);
}catch(EntityExistsException | IllegalArgumentException | TransactionRequiredException e ){
throw new PersistenceException("Erro al guardar al proveedor");
}
}
/* (non-Javadoc)
* @see com.mx.fic.inventory.business.ProviderBeanLocal#getAllByCompany(java.lang.Integer)
*/
@Override
public List<ProviderDTO> getAllByCompany(final Integer companyId) throws PersistenceException{
List<ProviderDTO> providerDTOLst = null;
List<Provider> providerLst = new ArrayList<Provider>();
ProviderDTO providerDTO = null;
TypedQuery<Provider> query = entityManager.createNamedQuery("Provider.getAllByCompany", Provider.class);
query.setParameter("id", companyId);
providerLst = query.getResultList();
if(providerLst!=null && providerLst.size()>0){
providerDTOLst = new ArrayList<ProviderDTO>();
for(Provider pr : providerLst){
providerDTO = TransferObjectAssembler.getInstance().assembleTO(ProviderDTO.class, pr);
providerDTOLst.add(providerDTO);
}
}
return providerDTOLst;
}
}
| gpl-3.0 |
fcristini/PPLite2 | tests/Powerset/upperbound1.cc | 2575 | /* Test Pointset_Powerset<PH>::upper_bound_assign(),
Pointset_Powerset<PH>::least_upper_bound_assign().
Copyright (C) 2001-2010 Roberto Bagnara <bagnara@cs.unipr.it>
Copyright (C) 2010-2017 BUGSENG srl (http://bugseng.com)
This file is part of the Parma Polyhedra Library (PPL).
The PPL is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
The PPL 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 02111-1307, USA.
For the most up-to-date information see the Parma Polyhedra Library
site: http://bugseng.com/products/ppl/ . */
#include "ppl_test.hh"
namespace {
// Powerset of C polyhedra: least_upper_bound_assign().
bool
test01() {
Variable x(0);
Pointset_Powerset<C_Polyhedron> c_ps(1, EMPTY);
Constraint_System cs;
cs.insert(x >= 0);
cs.insert(x <= 2);
c_ps.add_disjunct(C_Polyhedron(cs));
cs.clear();
cs.insert(x >= 1);
cs.insert(x <= 3);
Pointset_Powerset<C_Polyhedron> c_ps1(1, EMPTY);
c_ps1.add_disjunct(C_Polyhedron(cs));
c_ps.least_upper_bound_assign(c_ps1);
cs.clear();
cs.insert(x >= 0);
cs.insert(x <= 3);
Pointset_Powerset<C_Polyhedron> c_ps2(1, EMPTY);
c_ps2.add_disjunct(C_Polyhedron(cs));
bool ok = c_ps.definitely_entails(c_ps2);
bool ok1 = !c_ps2.definitely_entails(c_ps);
return ok && ok1;
}
// Powerset of C polyhedra: upper_bound_assign().
bool
test02() {
Variable x(0);
Pointset_Powerset<C_Polyhedron> c_ps(1, EMPTY);
Constraint_System cs;
cs.insert(x >= 0);
cs.insert(x <= 2);
c_ps.add_disjunct(C_Polyhedron(cs));
cs.clear();
cs.insert(x >= 1);
cs.insert(x <= 3);
Pointset_Powerset<C_Polyhedron> c_ps1(1, EMPTY);
c_ps1.add_disjunct(C_Polyhedron(cs));
c_ps.upper_bound_assign(c_ps1);
cs.clear();
cs.insert(x >= 0);
cs.insert(x <= 3);
Pointset_Powerset<C_Polyhedron> c_ps2(1, EMPTY);
c_ps2.add_disjunct(C_Polyhedron(cs));
bool ok = c_ps.definitely_entails(c_ps2);
bool ok1 = !c_ps2.definitely_entails(c_ps);
return ok && ok1;
}
} // namespace
BEGIN_MAIN
DO_TEST(test01);
DO_TEST(test02);
END_MAIN
| gpl-3.0 |
kichkasch/pisi | pisiinterfaces.py | 5223 | """
Provides interfaces (abstract super classes) for generic functionality.
This file is part of Pisi.
Pisi 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.
Pisi 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 Pisi. If not, see <http://www.gnu.org/licenses/>.
"""
import os
class Syncable:
"""
Common interface (Super-class) for a syncable items (calendar event, contact entry)
"""
def __init__(self, id, attributes):
"""
Constructor
"""
self.id = id
self.attributes = attributes
def compare(self, contactEntry):
"""
Compares this entry with another one and checks, whether all attributes from this one have the same values in the other one and vice verse
@return: 0 if there is at least a single difference in attributes; 1 if all attributes are the same
"""
raise ValueError("!!!Implementation missing!!!") # this has to be implemented individually for each syncable type
def getID(self):
"""
GETTER
"""
return self.id
def prettyPrint (self ):
"""
Beautyful output for one Syncable entry
Prints a headline containing the ID of the entry and iterates through all attributes available for the entry and displays each in a single line.
"""
print "\t_PrettyPrint of id:",self.id
for key,value in self.attributes.iteritems():
print ("\t\t- %s = %s" %(key,value)) #.encode("utf8", "replace")
class AbstractSynchronizationModule:
"""
Super class for all synchronization modules, which aim to synchronize any kind of information.
Each Synchronization class should inherit from this class.
@ivar _allEntries: Dictionary for storing all information entries
"""
def __init__(self, verbose, soft, modulesString, config, configsection, name = "unkown source"):
"""
Constructor
Instance variables are initialized.
"""
self.verbose = verbose
self.soft = soft
self.modulesString = modulesString
self._name = name
self._description = config.get(configsection,'description')
try:
self._preProcess = config.get(configsection,'preprocess')
except:
self._preProcess = None
try:
self._postProcess = config.get(configsection,'postprocess')
except:
self._postProcess = None
self._allEntries = {}
def getName(self):
"""
GETTER
"""
return self._name
def getDescription(self):
"""
GETTER
"""
return self._description
def prettyPrint (self ):
"""
Beautyful output for the entries in the repository
Prints a small headline and calls the function L{Syncable.prettyPrint} for each contact Entry in turn.
"""
print "Pretty print of %s content:" %(self._name)
for entry in self.allEntires().values():
entry.prettyPrint()
def allEntries( self ):
"""
Getter.
@return: The link to the instance variable L{_allEntries}.
"""
return self._allEntries
def getEntry(self, id):
"""
GETTER
@return: The link with the given ID.
"""
return self._allEntries[id]
def flush(self):
"""
Remove all entries in repository
The dictionary for all entries (L{_allEntries}) is flushed.
"""
self._allEntries = {}
def addEntry( self, entry):
"""
Saves an entry for later writing
The new instance is stored in the dictionary (L{_allEntries}).
"""
self._allEntries[entry.getID()] = entry
def replaceEntry( self, id, updatedEntry):
"""
Replaces an existing entry with a new one.
The old instance is replaced by the new one in the dictionary (L{_allEntries}).
"""
self._allEntries[id] = updatedEntry
def removeEntry( self, id ):
"""
Removes an entry
The instance is removed from the dictionary (L{_allEntries}).
"""
del self._allEntries[id]
def preProcess(self):
"""
Executes the shell command that has been configured for this source under 'preprocess'
"""
if self._preProcess:
ret = os.system(self._preProcess)
def postProcess(self):
"""
Executes the shell command that has been configured for this source under 'postprocess'
"""
if self._postProcess:
ret = os.system(self._postProcess)
| gpl-3.0 |
ZeroOne71/ql | 02_ECCentral/06_Job_Move/05_PO/IPP.POMgmt.ETA_Monitor/Model/POEntity.cs | 1182 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Newegg.Oversea.Framework.Entity;
namespace IPPOversea.POmgmt.Model
{
public class POEntity
{
[DataMapping("Sysno", DbType.Int32)]
public int SysNo { get; set; }
[DataMapping("TotalAmt", DbType.Decimal)]
public decimal TotalAmt { get; set; }
[DataMapping("ETATime", DbType.DateTime)]
public DateTime? ETATime { get; set; }
//[DataMapping("ETATime", DbType.Int32)]
//public int ProductSysNo { get; set; }
[DataMapping("PM_ReturnPointSysNo", DbType.Int32)]
public int PM_ReturnPointSysNo { get; set; }
[DataMapping("UsingReturnPoint", DbType.Decimal)]
public decimal UsingReturnPoint { get; set; }
[DataMapping("ReturnPointC3SysNo", DbType.Int32)]
public int ReturnPointC3SysNo { get; set; }
[DataMapping("StockSysNo", DbType.Int32)]
public int StockSysNo { get; set; }
[DataMapping("ETAHalfDay", DbType.String)]
public string ETAHalfDay { get; set; }
public List<POItem> Items { get; set; }
}
}
| gpl-3.0 |
pastachan/cornellapp | test/utils/cornellutiltest.js | 1342 | /**
* Copyright (c) 2015, Cornellapp.
* All rights reserved.
*
* This source code is licensed under the GNU General Public License v3.0
* license found in the LICENSE file in the root directory of this source
* tree.
*
*
* Test file for the cornellutil.js util module.
*/
var assert = require('assert'),
cornellutil = require('../../app/utils/cornellutil');
describe('cornellutil', function() {
// fetchName method
it('should have an fetchName method', function() {
assert.equal(typeof cornellutil, 'object');
assert.equal(typeof cornellutil.fetchName, 'function');
});
it('fetchName(\'\') should equal null', function(done) {
cornellutil.fetchName('', function(name) {
assert.equal(name, null);
done();
});
});
it('fetchName(\'8s2dw\') should equal null', function(done) {
cornellutil.fetchName('8s2dw', function(name) {
assert.equal(name, null);
done();
});
});
it('fetchName(\'adc237\') should equal \'Austin Dzan-Hei Chan\'',
function(done) {
cornellutil.fetchName('adc237', function(name) {
assert.equal(name, 'Austin Dzan-Hei Chan');
done();
});
});
it('fetchName(\'jar475\') should equal \'Joshua Austin Richardson\'',
function(done) {
cornellutil.fetchName('jar475', function(name) {
assert.equal(name, 'Joshua Austin Richardson');
done();
});
});
});
| gpl-3.0 |
shakabra/web-framework | src/resources/js/github.js | 542 | $.getJSON('https://api.github.com/users/shakabra/repos?callback=?',
function(data) {
var repoHTML = '';
$.each(data, function(i, repo) {
repoHTML += '<tr>';
repoHTML += '<td><a class="grey-text text-darken-4" href="'+data.html_url+'>'+data.name+'</a>'+'</td>';
repoHTML += '<td>' + data.language + '</td>';
repoHTML += '<td class="truncate">' + data.description + '</td>';
repoHTML += '</tr>';
});// End each
$.('.github').append(repoHTML);
});
| gpl-3.0 |
heikehuan/designPattern-23 | src/main/java/event/events/BeginMulticastRegister.java | 167 | package event.events;
/**
* Created by ptmind on 2017/9/7.
*/
public interface BeginMulticastRegister {
public void register(BeginMulticastHandler handler);
}
| gpl-3.0 |
pdl/BEX | js/bex.textcontainer.js | 1322 | (function($) {
$.widget("bex.bextextcontainer", {
options: {
pattern: ''
},
_create: function() {
var self = this;
var o = self.options;
var el = self.element
.addClass("ui-widget ui-widget-content ui-corner-right bex-textcontainer")
.click(function(){self.wake()});
return self;
},
wake: function(){
var self = this;
var inputs = self.element.find("textarea")
if (inputs.length > 0)
{
inputs[0].focus();
}
else
{
var input = $("<textarea></textarea>")
.val(self.element.text())
.change(function(){$(this).attr('data-changed','1')})
.blur(function(){self.sleep()});
if (self.options.pattern != '')
{
input.attr('pattern', self.options.pattern);
}
this.element.empty().append(input);
input.focus();
}
return self;
},
sleep: function(){
var inputs = this.element.find("textarea");
if (inputs.length > 0)
{
var textcontent = $(inputs[0]).val();
this.element.empty().text(textcontent);
}
return self;
},
val: function() {
this.sleep();
return $(this.element).text();
},
destroy: function() {
this.sleep();
},
_setOption: function(option, value) {
$.Widget.prototype._setOption.apply( this, arguments );
}
});
})(jQuery);
| gpl-3.0 |
mhvk/baseband | baseband/mark4/payload.py | 18271 | # Licensed under the GPLv3 - see LICENSE
"""
Definitions for VLBI Mark 4 payloads.
Implements a Mark4Payload class used to store payload words, and decode to
or encode from a data array.
For the specification, see
https://www.haystack.mit.edu/tech/vlbi/mark5/docs/230.3.pdf
"""
import sys
from collections import namedtuple
import numpy as np
from ..base.payload import PayloadBase
from ..base.encoding import encode_2bit_base, decoder_levels
from ..base.utils import fixedvalue
from .header import MARK4_DTYPES
__all__ = ['reorder32', 'reorder64', 'init_luts', 'decode_8chan_2bit_fanout4',
'encode_8chan_2bit_fanout4', 'Mark4Payload']
# 2bit/fanout4 use the following in decoding 32 and 64 track data:
if sys.byteorder == 'big': # pragma: no cover
def reorder32(x):
"""Reorder 32-track bits to bring signs & magnitudes together."""
return (((x & 0x55AA55AA))
| ((x & 0xAA00AA00) >> 9)
| ((x & 0x00550055) << 9))
def reorder64(x):
"""Reorder 64-track bits to bring signs & magnitudes together."""
return (((x & 0x55AA55AA55AA55AA))
| ((x & 0xAA00AA00AA00AA00) >> 9)
| ((x & 0x0055005500550055) << 9))
def reorder64_Ft(x):
"""Reorder 64-track bits to bring signs & magnitudes together.
Special version for the Ft station, which has unusual settings.
"""
return (((x & 0xAFFAFFFFAFFAFFFF))
| ((x & 0x0005000000050000) << 12)
| ((x & 0x5000000050000000) >> 12))
else:
def reorder32(x):
"""Reorder 32-track bits to bring signs & magnitudes together."""
return (((x & 0xAA55AA55))
| ((x & 0x55005500) >> 7)
| ((x & 0x00AA00AA) << 7))
# Can speed this up from 140 to 132 us by predefining bit patterns as
# array scalars. Inplace calculations do not seem to help much.
def reorder64(x):
"""Reorder 64-track bits to bring signs & magnitudes together."""
return (((x & 0xAA55AA55AA55AA55))
| ((x & 0x5500550055005500) >> 7)
| ((x & 0x00AA00AA00AA00AA) << 7))
def reorder64_Ft(x):
"""Reorder 64-track bits to bring signs & magnitudes together.
Special version for the Ft station, which has unusual settings.
"""
return (((x & 0xFFFFFAAFFFFFFAAF))
| ((x & 0x0000050000000500) >> 4)
| ((x & 0x0000005000000050) << 4))
# Check on 2015-JUL-12: C code: 738811025863578102 -> 738829572664316278
# 118, 209, 53, 244, 148, 217, 64, 10
# reorder64(np.array([738811025863578102], dtype=np.uint64))
# # array([738829572664316278], dtype=uint64)
# reorder64(np.array([738811025863578102], dtype=np.uint64)).view(np.uint8)
# # array([118, 209, 53, 244, 148, 217, 64, 10], dtype=uint8)
# decode_2bit_64track_fanout4(
# np.array([738811025863578102], dtype=np.int64)).astype(int).T
# -1 1 3 1 array([[-1, 1, 3, 1],
# 1 1 3 -3 [ 1, 1, 3, -3],
# 1 -3 1 3 [ 1, -3, 1, 3],
# -3 1 3 3 [-3, 1, 3, 3],
# -3 1 1 -1 [-3, 1, 1, -1],
# -3 -3 -3 1 [-3, -3, -3, 1],
# 1 -1 1 3 [ 1, -1, 1, 3],
# -1 -1 -3 -3 [-1, -1, -3, -3]])
def init_luts():
"""Set up the look-up tables for levels as a function of input byte."""
# Organisation by bits is quite odd for Mark 4.
b = np.arange(256)[:, np.newaxis]
# lut1bit
i = np.arange(8)
# For all 1-bit modes; if set, sign=-1, so need to get item 0.
lut1bit = decoder_levels[1][((b >> i) & 1) ^ 1]
i = np.arange(4)
# fanout 1 @ 8/16t, fanout 4 @ 32/64t
s = i*2 # 0, 2, 4, 6
m = s+1 # 1, 3, 5, 7
lut2bit1 = decoder_levels[2][2*(b >> s & 1)
+ (b >> m & 1)]
# fanout 2 @ 8/16t, fanout 1 @ 32/64t
s = i + (i//2)*2 # 0, 1, 4, 5
m = s + 2 # 2, 3, 6, 7
lut2bit2 = decoder_levels[2][2*(b >> s & 1)
+ (b >> m & 1)]
# fanout 4 @ 8/16t, fanout 2 @ 32/64t
s = i # 0, 1, 2, 3
m = s+4 # 4, 5, 6, 7
lut2bit3 = decoder_levels[2][2*(b >> s & 1)
+ (b >> m & 1)]
return lut1bit, lut2bit1, lut2bit2, lut2bit3
lut1bit, lut2bit1, lut2bit2, lut2bit3 = init_luts()
# Look-up table for the number of bits in a byte.
nbits = ((np.arange(256)[:, np.newaxis] >> np.arange(8) & 1)
.sum(1).astype(np.int16))
def decode_2chan_2bit_fanout4(frame):
"""Decode payload for 2 channels using 2 bits, fan-out 4 (16 tracks)."""
# header['magnitude_bit'] = 00001111,00001111
# makes sense with lut2bit3
# header['fan_out'] = 01230123,01230123
# header['converter_id'] = 00000000,11111111
# header['lsb_output'] = 11111111,11111111
# After reshape: byte 0: ch0/s0, ch0/s1, ch0/s2, ch0/s3, + mag.
# byte 1: ch1/s0, ch1/s1, ch1/s2, ch1/s3, + mag.
frame = frame.view(np.uint8).reshape(-1, 2)
# The look-up table splits each data word into the above 8 measurements,
# the transpose pushes channels first and fanout last, and the reshape
# flattens the fanout.
return lut2bit3.take(frame, axis=0).transpose(1, 0, 2).reshape(2, -1).T
def encode_2chan_2bit_fanout4(values):
"""Encode payload for 2 channels using 2 bits, fan-out 4 (16 tracks)."""
# Reverse reshaping (see above).
values = values.reshape(-1, 4, 2).transpose(0, 2, 1)
bitvalues = encode_2bit_base(values)
# Values are -3, -1, +1, 3 -> 00, 01, 10, 11; get first bit (sign) as 1,
# second bit (magnitude) as 16.
reorder_bits = np.array([0, 16, 1, 17], dtype=np.uint8)
reorder_bits.take(bitvalues, out=bitvalues)
bitvalues <<= np.array([0, 1, 2, 3], dtype=np.uint8)
out = np.bitwise_or.reduce(bitvalues, axis=-1).ravel().view('<u2')
return out
def decode_4chan_2bit_fanout4(frame):
"""Decode payload for 4 channels using 2 bits, fan-out 4 (32 tracks)."""
# Bitwise reordering of tracks, to align sign and magnitude bits,
# reshaping to get VLBI channels in sequential, but wrong order.
frame = reorder32(frame.view(np.uint32)).view(np.uint8).reshape(-1, 4)
# Correct ordering.
frame = frame.take(np.array([0, 2, 1, 3]), axis=1)
# The look-up table splits each data byte into 4 measurements.
# Using transpose ensures channels are first, then time samples, then
# those 4 measurements, so the reshape orders the samples correctly.
# Another transpose ensures samples are the first dimension.
return lut2bit1.take(frame.T, axis=0).reshape(4, -1).T
def encode_4chan_2bit_fanout4(values):
"""Encode payload for 4 channels using 2 bits, fan-out 4 (32 tracks)."""
reorder_channels = np.array([0, 2, 1, 3])
values = values[:, reorder_channels].reshape(-1, 4, 4).transpose(0, 2, 1)
bitvalues = encode_2bit_base(values)
reorder_bits = np.array([0, 2, 1, 3], dtype=np.uint8)
reorder_bits.take(bitvalues, out=bitvalues)
bitvalues <<= np.array([0, 2, 4, 6], dtype=np.uint8)
out = np.bitwise_or.reduce(bitvalues, axis=-1).ravel().view(np.uint32)
return reorder32(out).view('<u4')
def decode_8chan_2bit_fanout2(frame):
"""Decode payload for 8 channels using 2 bits, fan-out 4 (32 tracks)."""
# header['magnitude_bit'] = 00001111,00001111,00001111,00001111
# makes sense with lut2bit3
# header['fan_out'] = 00110011,00110011,00110011,00110011
# i.e., s0s0,s1s1,m0m0,m1m1 for each byte
# header['converter_id'] = 02020202,13131313,02020202,13131313
# header['lsb_output'] = 00000000,00000000,11111111,11111111
# After reshape: byte 0: ch0/s0, ch4/s0, ch0/s1, ch4/s1, + mag.
# byte 1: ch1/s0, ch5/s0, ch1/s1, ch5/s1, + mag.
# byte 2: ch2/s0, ch6/s0, ch2/s1, ch6/s1, + mag.
# byte 3: ch3/s0, ch7/s0, ch3/s1, ch7/s1, + mag.
frame = frame.view(np.uint8).reshape(-1, 4)
# The look-up table splits each data word into the above 16 measurements.
# the first reshape means one gets time, channel&0x3, sample, channel&0x4
# the transpose makes this channel&0x4, channel&0x3, time, sample.
# the second reshape (which makes a copy) gets one just channel, time,
# and the final transpose time, channel.
return (lut2bit3.take(frame, axis=0).reshape(-1, 4, 2, 2)
.transpose(3, 1, 0, 2).reshape(8, -1).T)
def encode_8chan_2bit_fanout2(values):
"""Encode payload for 8 channels using 2 bits, fan-out 2 (32 tracks)."""
# words encode 16 values (see above) in order ch&0x3, sample, ch&0x4
values = (values.reshape(-1, 2, 2, 4).transpose(0, 3, 1, 2)
.reshape(-1, 4, 4))
bitvalues = encode_2bit_base(values)
# values are -3, -1, +1, 3 -> 00, 01, 10, 11;
# get first bit (sign) as 1, second bit (magnitude) as 16
reorder_bits = np.array([0, 16, 1, 17], dtype=np.uint8)
reorder_bits.take(bitvalues, out=bitvalues)
bitvalues <<= np.array([0, 1, 2, 3], dtype=np.uint8)
out = np.bitwise_or.reduce(bitvalues, axis=-1).ravel().view('<u4')
return out
def decode_16chan_2bit_fanout2_ft(frame):
"""Decode payload for 16 channels using 2 bits, fan-out 2 (64 tracks)."""
# These Fortaleza files have an unusual ordering:
# header['magnitude_bit'] = 00000101,10101111,00001111,00001111 * 2
# White later two are as for lut2bit3, the first two are different.
# header['fan_out'] = 00110011 * 8
# i.e., s0s0,s1s1,m0m0,m1m1 for the later bytes.
# header['converter_id'] = 03030303,04040404,15151515,26262626,
# 7a7a7a7a,7b7b7b7b,8c8c8c8c,9d9d9d9d
# 0, 7 are doubled; those have lsb & usb;
# header['lsb_output'] = 00001010,00001010,00000000,00000000 * 2
# Should take magnitude bit literally,
# byte 0: 0u/s0, 3u/s0, 0u/s1, 3u/s1, 0l/s0, 3u/m0, 0l/s1, 3u/m1
# byte 1: 0u/m0, 4u/s0, 0u/m1, 4u/s1, 0l/m0, 4u/m0, 0l/m1, 4u/m1
# byte 2: 1u/s0, 5u/s0, 1u/s1, 5u/s1, 1u/m0, 5u/m0, 1u/m1, 5u/m1
# byte 3: 2u/s0, 6u/s0, 2u/s1, 6u/s1, 2u/m0, 6u/m0, 2u/m1, 6u/m1
# byte 4: 7u/s0, au/s0, 7u/s1, au/s1, 7l/s0, au/m0, 7l/s1, au/m1
# byte 5: 7u/m0, bu/s0, 7u/m1, bu/s1, 7l/m0, bu/m0, 7l/m1, bu/m1
# byte 6: 8u/s0, cu/s0, 8u/s1, cu/s1, 8u/m0, cu/m0, 8u/m1, cu/m1
# byte 7: 9u/s0, du/s0, 9u/s1, du/s1, 9u/m0, du/m0, 9u/m1, du/m1
# This means the re-ordering is different from the usual: we just
# need to shift bits around in bytes 0,1,4,5:
frame = reorder64_Ft(frame.view(np.uint64))
# This leaves samples as
# byte 0: 0u/s0, 3u/s0, 0u/s1, 3u/s1, 0u/m0, 3u/m0, 0u/m1, 3u/m1
# byte 1: 0l/s0, 4u/s0, 0l/s1, 4u/s1, 0l/m0, 4u/m0, 0l/m1, 4u/m1
# byte 2: 1u/s0, 5u/s0, 1u/s1, 5u/s1, 1u/m0, 5u/m0, 1u/m1, 5u/m1
# byte 3: 2u/s0, 6u/s0, 2u/s1, 6u/s1, 2u/m0, 6u/m0, 2u/m1, 6u/m1
# byte 4: 7u/s0, au/s0, 7u/s1, au/s1, 7u/m0, au/m0, 7u/m1, au/m1
# byte 5: 7l/s0, bu/s0, 7l/s1, bu/s1, 7l/m0, bu/m0, 7l/m1, bu/m1
# byte 6: 8u/s0, cu/s0, 8u/s1, cu/s1, 8u/m0, cu/m0, 8u/m1, cu/m1
# byte 7: 9u/s0, du/s0, 9u/s1, du/s1, 9u/m0, du/m0, 9u/m1, du/m1
frame = frame.view(np.uint8).reshape(-1, 8)
# The look-up table splits each data word into the above 32 measurements.
# Translating 0u=0, 0l=1, 1..6=2..7, 7u=8, 7l=9, 8..d=a..f, the
# first reshape yieds time, channel&0x8, channel&0x3, sample, channel&0x4
# transpose makes this channel&0x8, channel&0x4, channel&0x3, time, sample.
# and the second reshape (which makes a copy) gets one just time, channel,
# and the final transpose time, channel.
return (lut2bit3.take(frame, axis=0).reshape(-1, 2, 4, 2, 2)
.transpose(1, 4, 2, 0, 3).reshape(16, -1).T)
def encode_16chan_2bit_fanout2_ft(values):
"""Encode payload for 16 channels using 2 bits, fan-out 2 (64 tracks)."""
# words encode 32 values (above) in order ch&0x8, ch&0x3, sample, ch&0x4
# First reshape goes to time, sample, ch&0x8, ch&0x4, ch&0x3,
# transpose makes this time, ch&0x8, ch&0x3, sample, ch&0x4.
# second reshape future bytes, sample+ch&0x4.
values = (values.reshape(-1, 2, 2, 2, 4).transpose(0, 2, 4, 1, 3)
.reshape(-1, 4))
bitvalues = encode_2bit_base(values)
# values are -3, -1, +1, 3 -> 00, 01, 10, 11;
# get first bit (sign) as 1, second bit (magnitude) as 16
reorder_bits = np.array([0, 16, 1, 17], dtype=np.uint8)
reorder_bits.take(bitvalues, out=bitvalues)
bitvalues <<= np.array([0, 1, 2, 3], dtype=np.uint8)
out = np.bitwise_or.reduce(bitvalues, axis=-1).ravel().view(np.uint64)
return reorder64_Ft(out).view('<u8')
def decode_8chan_2bit_fanout4(frame):
"""Decode payload for 8 channels using 2 bits, fan-out 4 (64 tracks)."""
# Bitwise reordering of tracks, to align sign and magnitude bits,
# reshaping to get VLBI channels in sequential, but wrong order.
frame = reorder64(frame.view(np.uint64)).view(np.uint8).reshape(-1, 8)
# Correct ordering.
frame = frame.take(np.array([0, 2, 1, 3, 4, 6, 5, 7]), axis=1)
# The look-up table splits each data byte into 4 measurements.
# Using transpose ensures channels are first, then time samples, then
# those 4 measurements, so the reshape orders the samples correctly.
# Another transpose ensures samples are the first dimension.
return lut2bit1.take(frame.T, axis=0).reshape(8, -1).T
def encode_8chan_2bit_fanout4(values):
"""Encode payload for 8 channels using 2 bits, fan-out 4 (64 tracks)."""
reorder_channels = np.array([0, 2, 1, 3, 4, 6, 5, 7])
values = values[:, reorder_channels].reshape(-1, 4, 8).transpose(0, 2, 1)
bitvalues = encode_2bit_base(values)
reorder_bits = np.array([0, 2, 1, 3], dtype=np.uint8)
reorder_bits.take(bitvalues, out=bitvalues)
bitvalues <<= np.array([0, 2, 4, 6], dtype=np.uint8)
out = np.bitwise_or.reduce(bitvalues, axis=-1).ravel().view(np.uint64)
return reorder64(out).view('<u8')
class Mark4Payload(PayloadBase):
"""Container for decoding and encoding Mark 4 payloads.
Parameters
----------
words : `~numpy.ndarray`
Array containg LSB unsigned words (with the right size) that
encode the payload.
header : `~baseband.mark4.Mark4Header`, optional
If given, used to infer the number of channels, bps, and fanout.
sample_shape : tuple
Shape of the samples (e.g., (nchan,)). Default: (1,).
bps : int, optional
Number of bits per sample, used if ``header`` is not given.
Default: 2.
fanout : int, optional
Number of tracks every bit stream is spread over, used if ``header`` is
not given. Default: 1.
magnitude_bit : int, optional
Magnitude bits for all tracks packed together. Used to index
encoder and decoder. Default: assume standard Mark 4 payload,
for which number of channels, bps, and fanout suffice.
Notes
-----
The total number of tracks is ``nchan * bps * fanout``.
"""
_dtype_word = None
# Decoders keyed by (nchan, nbit, fanout).
_encoders = {(2, 2, 4): encode_2chan_2bit_fanout4,
(4, 2, 4): encode_4chan_2bit_fanout4,
(8, 2, 2): encode_8chan_2bit_fanout2,
(8, 2, 4): encode_8chan_2bit_fanout4,
(16, 0xf0faf050f0faf05, 2): encode_16chan_2bit_fanout2_ft}
_decoders = {(2, 2, 4): decode_2chan_2bit_fanout4,
(4, 2, 4): decode_4chan_2bit_fanout4,
(8, 2, 2): decode_8chan_2bit_fanout2,
(8, 2, 4): decode_8chan_2bit_fanout4,
(16, 0xf0faf050f0faf05, 2): decode_16chan_2bit_fanout2_ft}
_sample_shape_maker = namedtuple('SampleShape', 'nchan')
def __init__(self, words, header=None, *, sample_shape=(1,), bps=2,
fanout=1, magnitude_bit=None, complex_data=False):
if header is not None:
magnitude_bit = header['magnitude_bit']
bps = 2 if magnitude_bit.any() else 1
ta = header.track_assignment
if bps == 1 or np.all(magnitude_bit[ta] == [False, True]):
magnitude_bit = None
else:
magnitude_bit = (np.packbits(magnitude_bit)
.view(header.stream_dtype).item())
ntrack = header.ntrack
fanout = header.fanout
sample_shape = (ntrack // (bps * fanout),)
self._nbytes = header.payload_nbytes
else:
ntrack = sample_shape[0] * bps * fanout
magnitude_bit = None
self._dtype_word = MARK4_DTYPES[ntrack]
self.fanout = fanout
super().__init__(words, sample_shape=sample_shape,
bps=bps, complex_data=complex_data)
self._coder = (self.sample_shape.nchan,
(self.bps if magnitude_bit is None else magnitude_bit),
self.fanout)
@fixedvalue
def complex_data(self):
return False
@classmethod
def fromfile(cls, fh, header=None, **kwargs):
"""Read payload from filehandle and decode it into data.
Parameters
----------
fh : filehandle
From which data is read.
header : `~baseband.mark4.Mark4Header`
Used to infer ``payload_nbytes``, ``bps``, ``sample_shape``, and
``dtype``. If not given, those have to be passed in.
"""
if header is not None:
kwargs.setdefault('dtype', header.stream_dtype)
return super().fromfile(fh, header=header, **kwargs)
@classmethod
def fromdata(cls, data, header):
"""Encode data as payload, using header information."""
if data.dtype.kind == 'c':
raise ValueError("Mark4 format does not support complex data.")
if header.sample_shape != data.shape[1:]:
raise ValueError("header is for {0} channels but data has {1}"
.format(header.nchan, data.shape[-1]))
words = np.empty(header.payload_nbytes // header.stream_dtype.itemsize,
header.stream_dtype)
self = cls(words, header)
self[:] = data
return self
| gpl-3.0 |
marianc/python-server-typescript-client | Server/modules/utils/dal/common/entities/dataViews/remoteEntityViewsBase.py | 1268 | from modules.utils.dal.common.entities.dataViews.dataViewRemoteEntity import DataViewRemoteEntity
from modules.utils.dal.common.entities.dataContext import DataContext
from modules.utils.dal.common.dtos.dataViewDto import DataViewDto
from modules.utils.dal.common.dtos import metadataSrv
from modules.utils.dal.common import utils as dalUtils
class RemoteEntityViewsBase:
def __init__(self, dataViewDto: DataViewDto, dataContext: DataContext, metadata: metadataSrv.Metadata):
self.dataViewDto = dataViewDto
self.dataContext = dataContext
self.metadata = metadata
self.propertyBag = {} # type: Dict<str, DataViewRemoteEntity>
def __getattr__(self, entitySetName: str):
entityTypeName = dalUtils.getEntityTypeName(entitySetName, self.metadata)
return self.getPropertyValue(entityTypeName)
def getPropertyValue(self, entityTypeName: str) -> DataViewRemoteEntity:
instance = None
if entityTypeName in self.propertyBag:
instance = self.propertyBag[entityTypeName]
else:
instance = DataViewRemoteEntity(entityTypeName, self.dataViewDto, self.dataContext)
self.propertyBag[entityTypeName] = instance
return instance
| gpl-3.0 |
john-tornblom/pyrsl | tests/test_intrinsic.py | 3871 | # encoding: utf-8
# Copyright (C) 2015 John Törnblom
import os
from utils import RSLTestCase
from utils import evaluate_docstring
from rsl.runtime import RuntimeException
class TestIntrinsic(RSLTestCase):
@evaluate_docstring
def test_get_env_var(self, rc):
'''
.invoke rc = GET_ENV_VAR("PATH")
.exit rc.result
'''
self.assertEqual(os.environ['PATH'], rc)
@evaluate_docstring
def test_get_env_var_failure(self, rc):
'''
.invoke rc = GET_ENV_VAR("UNKNOWN_PATH")
.exit rc.success
'''
self.assertFalse(rc)
@evaluate_docstring
def test_put_env_var(self, rc):
'''
.invoke rc = PUT_ENV_VAR("MY_PATH", "test")
.exit rc.success
'''
self.assertTrue(rc)
self.assertEqual(os.environ["MY_PATH"], "test")
@evaluate_docstring
def test_file_read_write(self, rc):
'''
.invoke rc = FILE_WRITE("/tmp/RSLTestCase", "Hello world!")
.if ( not rc.success )
.exit ""
.end if
.invoke rc = FILE_READ("/tmp/RSLTestCase")
.if ( not rc.success )
.exit ""
.end if
.exit rc.result
'''
self.assertEqual(rc, "Hello world!\n")
@evaluate_docstring
def test_file_read_error(self, rc):
'''
.invoke rc = FILE_READ("/")
.exit rc.success
'''
self.assertFalse(rc)
@evaluate_docstring
def test_file_write_error(self, rc):
'''
.invoke rc = FILE_WRITE("/", "TEST")
.exit rc.success
'''
self.assertFalse(rc)
@evaluate_docstring
def test_shell_command_exit_0(self, rc):
'''
.invoke rc = SHELL_COMMAND("exit 0")
.exit rc.result
'''
self.assertEqual(0, rc)
@evaluate_docstring
def test_shell_command_exit_1(self, rc):
'''
.invoke rc = SHELL_COMMAND("exit 1")
.exit rc.result
'''
self.assertEqual(1, rc)
@evaluate_docstring
def test_integer_to_string(self, rc):
'''
.invoke rc = INTEGER_TO_STRING(1)
.exit rc.result
'''
self.assertEqual("1", rc)
@evaluate_docstring
def test_real_to_string(self, rc):
'''
.invoke rc = REAL_TO_STRING(1.1)
.exit rc.result
'''
self.assertEqual("1.1", rc)
@evaluate_docstring
def test_boolean_to_string(self, rc):
'''
.invoke rc = BOOLEAN_TO_STRING(False)
.exit rc.result
'''
self.assertEqual("FALSE", rc)
@evaluate_docstring
def test_string_to_integer(self, rc):
'''
.invoke rc = STRING_TO_INTEGER("1")
.exit rc.result
'''
self.assertEqual(1, rc)
@evaluate_docstring
def test_string_to_integer_invalid(self, rc):
'''
.invoke rc = STRING_TO_INTEGER("test")
'''
self.assertIsInstance(rc, RuntimeException)
@evaluate_docstring
def test_string_to_integer_with_spaces(self, rc):
'''
.invoke rc = STRING_TO_INTEGER(" 1 ")
.exit rc.result
'''
self.assertEqual(1, rc)
@evaluate_docstring
def test_string_to_real(self, rc):
'''
.invoke rc = STRING_TO_REAL("1.1")
.exit rc.result
'''
self.assertEqual(1.1, rc)
@evaluate_docstring
def test_string_to_real_invalid(self, rc):
'''
.invoke rc = STRING_TO_REAL("test")
'''
self.assertIsInstance(rc, RuntimeException)
@evaluate_docstring
def test_string_to_real_with_spaces(self, rc):
'''
.invoke rc = STRING_TO_REAL(" 1.1 ")
.exit rc.result
'''
self.assertEqual(1.1, rc)
| gpl-3.0 |
FlyerSky/C_plus_plus | Union_Big-Endian_Little-Endian.cpp | 1279 | #include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
/***********************************************
union ά»¤×ã¹»µÄ¿Õ¼äÀ´Ö÷Ŷà¸öÊý¾Ý³ÉÔ±Öеġ°Ò»ÖÖ¡±£¬
¶ø²»ÊÇΪÿһ¸öÊý¾Ý³ÉÔ±ÅäÖÿռ䣬ÔÚunion ÖÐËùÓеÄÊý
¾Ý³ÉÔ±¹²ÓÃÒ»¸ö¿Õ¼ä£¬Í¬Ò»Ê±¼äÖ»ÄÜ´¢´æÆäÖÐÒ»¸öÊý¾Ý³ÉÔ±£¬
ËùÓеÄÊý¾Ý³ÉÔ±¾ßÓÐÏàͬµÄÆðʼµØÖ·¡£
************************************************/
union {
int s;
char c[sizeof(int)];
} un;
/************************************************************************
1. ´ó¶Ëģʽ£¨Big_endian£©£º¶à×Ö½ÚÊý¾ÝµÄ¸ß×Ö½Ú´æ´¢Ôڵ͵ØÖ·ÖУ¬¶ø×ÖÊý¾ÝµÄµÍ×Ö½ÚÔò´æ·ÅÔڸߵØÖ·ÖС£
2. С¶Ëģʽ£¨Little_endian£©£º¶à×Ö½ÚÊý¾ÝµÄ¸ß×Ö½Ú´æ´¢ÔڸߵØÖ·ÖУ¬¶ø×ÖÊý¾ÝµÄµÍ×Ö½ÚÔò´æ·ÅÔڵ͵ØÖ·ÖС£
3. unionÐÍÊý¾ÝËùÕ¼µÄ¿Õ¼äµÈÓÚÆä×î´óµÄ³ÉÔ±ËùÕ¼µÄ¿Õ¼ä¡£¶ÔunionÐ͵ijÉÔ±µÄ´æÈ¡¶¼ÊÇÏà¶ÔÓÚ¸ÃÁªºÏÌå
»ùµØÖ·µÄÆ«ÒÆÁ¿Îª0 ´¦¿ªÊ¼£¬Ò²¾ÍÊÇÁªºÏÌåµÄ·ÃÎʲ»ÂÛ¶ÔÄĸö±äÁ¿µÄ´æÈ¡¶¼ÊÇ´Óunion µÄÊ×µØÖ·Î»ÖÿªÊ¼¡£
4. PCÒ»°ãÊÇС¶Ëģʽ¡£
*************************************************************************/
int main(int argc, char **argv)
{
un.s = 0x87654321;
if (sizeof(int) == 4)
{
for (int i = 0; i < 4; ++i)
{
printf("un.c[%d] = %x\n", i, un.c[i]); // ·Ö±ðÊä³ö0x21, 0x43, 0x65, 0x87
}
}
else
{
printf("sizeof(int)= %d\n", sizeof(int));
}
system("pause");
exit(0);
}
| gpl-3.0 |
MainScientist/pucapi-java | src/cl/uc/fipezoa/pucapi/callbacks/LoadingCallback.java | 225 | package cl.uc.fipezoa.pucapi.callbacks;
import org.jsoup.helper.StringUtil;
/**
* Created by fipezoa on 2/2/2016.
*/
public abstract class LoadingCallback{
public abstract void onProgressChange(Progress progress);
}
| gpl-3.0 |
apmuthu/phplist3_php53 | core/public_html/lists/config/config_extended.php | 37160 | <?php
/*
=========================================================================
General settings for language and database
=========================================================================
*/
# select the language module to use
# Look for <country>.inc files in the texts directory
# to find your language
# this is the language for the frontend pages. In the admin pages you can
# choose your language by using the dropdown in the pages.
$language_module = 'english.inc';
# what is your Mysql database server
$database_host = 'localhost';
# what is the name of the database we are using
$database_name = 'phplistdb';
# who do we log in as?
$database_user = 'phplist';
# and what password do we use
$database_password = 'phplist';
# the mysql server port number if not the default
$database_port = null;
# the socket to be used
$database_socket = null;
# enable database connection compression
$database_connection_compression = false;
# force database connection to use SSL
$database_connection_ssl = false;
# if you use multiple installations of phpList you can set this to
# something to identify this one. it will be prepended to email report
# subjects
$installation_name = 'phpList';
# if you want a prefix to all your tables, specify it here,
$table_prefix = 'phplist_';
# if you want to use a different prefix to user tables, specify it here.
# read README.usertables for more information
$usertable_prefix = 'phplist_user_';
# if you change the path to the phpList system, make the change here as well
# path should be relative to the root directory of your webserver (document root)
$pageroot = '/lists';
/*
=========================================================================
Settings for handling bounces
=========================================================================
*/
# Message envelope. This is the email that system messages come from
# it is useful to make this one where you can process the bounces on
# you will probably get a X-Authentication-Warning in your message
# when using this with sendmail
# NOTE: this is *very* different from the From: line in a message
# to use this feature, uncomment the following line, and change the email address
# to some existing account on your system
# requires PHP version > "4.0.5" and "4.3.1+" without safe_mode
# $message_envelope = 'listbounces@yourdomain';
# Handling bounces. Check README.bounces for more info
# This can be 'pop' or 'mbox'
$bounce_protocol = 'pop';
# set this to 0, if you set up a cron to download bounces regularly by using the
# commandline option. If this is 0, users cannot run the page from the web
# frontend. Read README.commandline to find out how to set it up on the
# commandline
define('MANUALLY_PROCESS_BOUNCES', 1);
# when the protocol is pop, specify these three
$bounce_mailbox_host = 'localhost';
$bounce_mailbox_user = 'popuser';
$bounce_mailbox_password = 'password';
# the "port" is the remote port of the connection to retrieve the emails
# the default should be fine but if it doesn't work, you can try the second
# one. To do that, add a # before the first line and take off the one before the
# second line
$bounce_mailbox_port = '110/pop3/notls';
#$bounce_mailbox_port = "110/pop3";
# it's getting more common to have secure connections, in which case you probably want to use
#$bounce_mailbox_port = "995/pop3/ssl/novalidate-cert";
# when the protocol is mbox specify this one
# it needs to be a local file in mbox format, accessible to your webserver user
$bounce_mailbox = '/var/spool/mail/listbounces';
# set this to 0 if you want to keep your messages in the mailbox. this is potentially
# a problem, because bounces will be counted multiple times, so only do this if you are
# testing things.
$bounce_mailbox_purge = 1;
# set this to 0 if you want to keep unprocessed messages in the mailbox. Unprocessed
# messages are messages that could not be matched with a user in the system
# messages are still downloaded into phpList, so it is safe to delete them from
# the mailbox and view them in phpList
$bounce_mailbox_purge_unprocessed = 1;
# how many bounces in a row need to have occurred for a user to be marked unconfirmed
$bounce_unsubscribe_threshold = 5;
/*
=========================================================================
Security related settings
=========================================================================
*/
# set this to 1 if you want phpList to deal with login for the administrative
# section of the system
# you will be able to add administrators who control their own lists
# default login is "admin" with password "phplist"
#
$require_login = 1;
# if you use login, how many lists can be created per administrator
define('MAXLIST', 1);
# if you use commandline, you will need to identify the users who are allowed to run
# the script. See README.commandline for more info
# $commandline_users = array("admin");
# or you can use the following to disable the check (take off the # in front of the line)
$commandline_users = array();
## silent resubscribe
# when someone signs up with an email address already in the database,
# phpList will simply accept it and subscribe them as if it is the first time
# however, that allows anyone to overwrite data of someone else
# see also https://mantis.phplist.com/view.php?id=15557
# if you don't like that, you can stop this from happening and send the subscriber to the
# preferences page instead. To do so, uncomment (remove the #) the next line
#define('SILENT_RESUBSCRIBE',false);
# as of version 2.4.1, you can have your users define a password for themselves as well
# this will cause some public pages to ask for an email and a password when the password is
# set for the user. If you want to activate this functionality, set the following
# to 1. See README.passwords for more information
define('ASKFORPASSWORD', 0);
# if you use passwords, they will be stored encrypted
# set this one to the algorythm to use. You can find out which ones are
# supported by your system with the command
# $ php -r "var_dump(hash_algos());";
# "sha256" is fairly common on the latest systems, but if your system is very old (not a good idea)
# you may want to set it to "sha1" or "md5"
# if you use encrypted passwords, users can only request you as an administrator to
# reset the password. They will not be able to request the password from
# the system
# if you change this, you may have to use the "Forgot password" system to get back in your installation
define('ENCRYPTION_ALGO', 'sha256');
# if you also want to force people who unsubscribe to provide a password before
# processing their unsubscription, set this to 1. You need to have the above one set
# to 1 for this to have an effect
define('UNSUBSCRIBE_REQUIRES_PASSWORD', 0);
# if a user should immediately be unsubscribed, when using their personal URL, instead of
# the default way, which will ask them for a reason, set this to 1
define('UNSUBSCRIBE_JUMPOFF', 0);
# when a user unsubscribes they are sent one final email informing them of
# their unsubscription. In order for that email to actually go out, a gracetime
# needs to be set otherwise it will never go out. The default of 5 minutes should
# be fine, but you can increase it if you experience problems
$blacklist_gracetime = 5;
# to increase security the session of a user is checked for the IP address
# this needs to be the same for every request. This may not work with
# network situations where you connect via multiple proxies, so you can
# switch off the checking by setting this to 0
define('CHECK_SESSIONIP', 1);
# Check for host of email entered for subscription
# Do not use it if your server is not 24hr online
# make the 0 a 1, if you want to use it
$check_for_host = 0;
/*
=========================================================================
Debugging and informational
=========================================================================
*/
# if test is true (not 0) it will not actually send ANY messages,
# but display what it would have sent
define('TEST', 1);
# if you set verbose to 1, it will show the messages that will be sent. Do not do this
# if you have a lot of users, because it is likely to crash your browser
define('VERBOSE', 0);
# some warnings may show up about your PHP settings. If you want to get rid of them
# set this value to 0
define('WARN_ABOUT_PHP_SETTINGS', 1);
# user history system info.
# when logging the history of a user, you can specify which system variables you
# want to log. These are the ones that are found in the $_SERVER and the $_ENV
# variables of PHP. check http://www.php.net/manual/en/language.variables.predefined.php
# the values are different per system, but these ones are quite common.
$userhistory_systeminfo = array(
'HTTP_USER_AGENT',
'HTTP_REFERER',
'REMOTE_ADDR',
);
# add spamblock
# if you set this to 1, phplist will try to check if the subscribe attempt is a spambot trying to send
# nonsense. If you think this doesn't work, set this to 0
# this is currently only implemented on the subscribe pages
define('USE_SPAM_BLOCK', 1);
# notify spam
# when phplist detects a possible spam attack, it can send you a notification about it
# you can check for a while to see if the spam check was correct and if so, set this value
# to 0, if you think the check does it's job correctly.
# it will only send you emails if you have "Does the admin get copies of subscribe, update and unsubscribe messages"
# in the configuration set to true
define('NOTIFY_SPAM', 1);
/*
=========================================================================
Security
=========================================================================
*/
# CHECK REFERRER. Set this to "true" to activate a check on each request to make sure that
# the "referrer" in the request is from ourselves. This is not failsafe, as the referrer may
# not exist, or can be spoofed, but it will help a little
# it is also possible that it doesn't work with Webservers that are not Apache, we haven't tested that.
define('CHECK_REFERRER', false);
# if you activate the check above, you can add domain names in this array for those domains
# that you trust and that can be allowed as well
# only mention the domain for each.
# for example: $allowed_referrers = array('mydomain.com','msn.com','yahoo.com','google.com');
$allowed_referrers = array();
/*
=========================================================================
Feedback to developers
=========================================================================
*/
# use Register to "register" to phpList.com. Once you set TEST to 0, the system will then
# request the "Powered By" image from www.phplist.com, instead of locally. This will give me
# a little bit of an indication of how much it is used, which will encourage me to continue
# developing phpList. If you do not like this, set Register to 0.
define('REGISTER', 1);
# CREDITS
# We request you retain some form of credits on the public elements of
# phpList. These are the subscribe pages and the emails.
# This not only gives respect to the large amount of time given freely
# by the developers but also helps build interest, traffic and use of
# phpList, which is beneficial to future developments.
# By default the webpages and the HTML emails will include an image and
# the text emails will include a powered by line
# If you want to remove the image from the HTML emails, set this constant
# to be 1, the HTML emails will then only add a line of text as signature
define('EMAILTEXTCREDITS', 0);
# if you want to also remove the image from your public webpages
# set the next one to 1, and the pages will only include a line of text
define('PAGETEXTCREDITS', 0);
# in order to get some feedback about performance, phpList can send statistics to a central
# email address. To de-activate this set the following value to 1
define('NOSTATSCOLLECTION', 0);
# this is the email it will be sent to. You can leave the default, or you can set it to send
# to your self. If you use the default you will give me some feedback about performance
# which is useful for me for future developments
# $stats_collection_address = 'phplist-stats@phplist.com';
/*
=========================================================================
Queue and Load management
=========================================================================
*/
# If you set up your system to send the message automatically (from commandline),
# you can set this value to 0, so "Process Queue" will disappear from the site
# this will also stop users from loading the page on the web frontend, so you will
# have to make sure that you run the queue from the commandline
# check README.commandline how to do this
define('MANUALLY_PROCESS_QUEUE', 1);
# This setting will activate an initial setup choice for processing the queue
# When "true" it will allow a choice between remote queue processing with the
# phpList.com service or processing it locally in the browser.
# when the value is "false", you can use remote processing in your own way
# as explain at https://resources.phplist.com/system/remote_processing
# define('SHOW_PQCHOICE',false);
# batch processing
# if you are on a shared host, it will probably be appreciated if you don't send
# out loads of emails in one go. To do this, you can configure batch processing.
# Please note, the following two values can be overridden by your ISP by using
# a server wide configuration. So if you notice these values to be different
# in reality, that may be the case
# max messages to process
# if there are multiple messages in the queue, set a maximum to work on
define('MAX_PROCESS_MESSAGE', 999);
# process parallel
# if there are multiple messages in the queue, divide the max batch across them
# instead of sending them one by one.
# this only works if you use batch processing. It will divide the batch between the
# campaigns that need sending.
#define('PROCESSCAMPAIGNS_PARALLEL',true);
# define the amount of emails you want to send per period. If 0, batch processing
# is disabled and messages are sent out as fast as possible
define('MAILQUEUE_BATCH_SIZE', 0);
# define the length of one batch processing period, in seconds (3600 is an hour)
define('MAILQUEUE_BATCH_PERIOD', 3600);
# to avoid overloading the server that sends your email, you can add a little delay
# between messages that will spread the load of sending
# you will need to find a good value for your own server
# value is in seconds, and you can use fractions, eg "0.5" is half a second
# (or you can play with the autothrottle below)
define('MAILQUEUE_THROTTLE', 0);
# Mailqueue autothrottle. This will try to automatically change the delay
# between messages to make sure that the MAILQUEUE_BATCH_SIZE (above) is spread evently over
# MAILQUEUE_BATCH_PERIOD, instead of firing the Batch in the first few minutes of the period
# and then waiting for the next period. This only works with mailqueue_throttle off
# and MAILQUEUE_BATCH_PERIOD being a positive value
# it still needs tweaking, so send your feedback to mantis.phplist.com if you find
# any issues with it
define('MAILQUEUE_AUTOTHROTTLE', 0);
# Domain Throttling
# You can activate domain throttling, by setting USE_DOMAIN_THROTTLE to 1
# define the maximum amount of emails you want to allow sending to any domain and the number
# of seconds for that amount. This will make sure you don't send too many emails to one domain
# which may cause blacklisting. Particularly the big ones are tricky about this.
# it may cause a dramatic increase in the amount of time to send a message, depending on how
# many users you have that have the same domain (eg hotmail.com)
# if too many failures for throttling occur, the send process will automatically add an extra
# delay to try to improve that. The example sends 1 message every 2 minutes.
define('USE_DOMAIN_THROTTLE', 0);
define('DOMAIN_BATCH_SIZE', 1);
define('DOMAIN_BATCH_PERIOD', 120);
# if you have very large numbers of users on the same domains, this may result in the need
# to run processqueue many times, when you use domain throttling. You can also tell phplist
# to simply delay a bit between messages to increase the number of messages sent per queue run
# if you want to use that set this to 1, otherwise simply run the queue many times. A cron
# process every 10 or 15 minutes is recommended.
define('DOMAIN_AUTO_THROTTLE', 0);
# MAX_PROCESSQUEUE_TIME
# to limit the time, regardless of batch processing or other throttling of a single run of "processqueue"
# you can set the MAX_PROCESSQUEUE_TIME in seconds
# if a single queue run exceeds this amount, it will stop, just to pick up from where it left off next time
# this allows multiple installations each to run the queue, but slow installations (eg with large emails)
# set to 0 to disable this feature.
define('MAX_PROCESSQUEUE_TIME', 0);
/*
=========================================================================
Miscellaneous
=========================================================================
*/
## default system language
# set the default system language. If the language cannot be detected, it will fall back to
# this one. It has to be the "ISO code" of the language.
# to find what languages are available here, check out http://translate.phplist.com/
$default_system_language = 'en';
## use Precedence
# according to the email standards, the Precedence header is outdated, and should not be used
# however, Google/Gmail requests that the header is used.
# So, it's up to you what to do. Yes, or No. Defaults to "yes" use it
# see also https://mantis.phplist.com/view.php?id=16688
#define('USE_PRECEDENCE_HEADER',false);
# if you do not require users to actually sign up to lists, but only want to
# use the subscribe page as a kind of registration system, you can set this to 1 and
# users will not receive an error when they do not check a list to subscribe to
define('ALLOW_NON_LIST_SUBSCRIBE', 0);
# Show private lists
# If you have a mixture of public and private lists, you can set this to 1, to allow
# your subscribers to see (and unsubscribe from) your private lists on their
# preferences page. By default it won't show private (non-public) lists
# see also https://mantis.phplist.com/view.php?id=15274
define('PREFERENCEPAGE_SHOW_PRIVATE_LISTS', 0);
# wrap html
# in some cases, strange newlines appear in the HTML source of campaigns
# If that's happening to you, you may want to set this one
# check https://mantis.phplist.com/view.php?id=15603 for more info
# define('WORDWRAP_HTML',60);
# year ranges. If you use dates, by default the drop down for year will be from
# three years before until 10 years after this the current value for year. If there
# is no current value the current year will be used.
# if you want to use a bigger range you can set the start and end year here
# be aware that the drop down may become very large.
# if set to 0 they will use the default behaviour. So I'm afraid you can't start with
# year 0. Also be aware not to set the end year to something relatively soon in the
# future, or it will stop working when you reach that year.
define('DATE_START_YEAR', 0);
define('DATE_END_YEAR', 0);
# empty value prefix. This can be used to identify values in select attributes
# that are not allowed to be selected and cause an error "Please enter your ..."
# by using a top value that starts with this string, you can make sure that the
# selects do not have a default value, that may be accidentally selected
# eg. "-- choose your country"
define('EMPTY_VALUE_PREFIX', '--');
# admin details for messages
# if this is enabled phplist will initialise the From in new messages to be the
# details of the logged in administrator who is sending the message
# otherwise it will default to the values set in the configure page that identify
# the "Default for 'From:' in a campaign"
define('USE_ADMIN_DETAILS_FOR_MESSAGES', 1);
# attribute value reorder limit
# for selectable attributes, like "select" and "radio" you can manage the order of the values
# by adding a number for each of them. After a certain number of values, this will disappear
# and it will automatically order alphabetically. This "certain number" is controlled here
# and it defaults to 100
# if you want to use this, uncomment this line and change the value
# define('ATTRIBUTEVALUE_REORDER_LIMIT',100);
# test emails
# if you send a test email, phplist will by default send you two emails, one in HTML format
# and the other in Text format. If you set this to 1, you can override this behaviour
# and only have a test email sent to you that matches the user record of the user that the
# test emails are sent to
define('SEND_ONE_TESTMAIL', 0);
# send a webpage. You can send the contents of a webpage, by adding
# [URL:http://website/file.html] as the content of a message. This can also be personalised
# for users by using eg
# [URL:http://website/file.html?email=[email]]
# the timeout for refetching a URL can be defined here. When the last time a URL has been
# fetched exceeds this time, the URL will be refetched. This is in seconds, 3600 is an hour
# this only affects sending within the same "process queue". If a new process queue is started
# the URL will be fetched the first time anyway. Therefore this is only useful is processing
# your queue takes longer than the time identified here.
define('REMOTE_URL_REFETCH_TIMEOUT', 3600);
# Users Page Max. The page listing subscribers will stop listing them and require a search,
# when the amount of subscribers is over 1000. With this settings you can change that cut-off point
define('USERSPAGE_MAX', 1000);
# Message Age. The Scheduling tab has an option to stop sending a message when it has reached a certain date.
# This can be used to avoid the campaign going out, eg when an event has already taken place.
# This value defaults to the moment of creating the campaign + the number of seconds set here.
# phpList will mark the campaign as sent, when this date has been reached
# 15768000 is about 6 months, but other useful values can be
# 2592000 - 30 days
# 604800 - a week.
# 86400 - a day
define('DEFAULT_MESSAGEAGE', 15768000);
# Repetition. This adds the option to repeat the same message in the future.
# After the message has been sent, this option will cause the system to automatically
# create a new message with the same content. Be careful with it, because you may
# send the same message to your users
# the embargo of the message will be increased with the repetition interval you choose
# also read the README.repetition for more info
define('USE_REPETITION', 0);
# admin language
# if you want to disable the language switch for the admin interface (and run all in english)
# set this one to 0
define('LANGUAGE_SWITCH', 1);
## error 404 page
## custom "File not found".
## in several places, phpList may generate a "file not found" page. If you want to provide your own design for this
## page, you can set this here. This needs to be a file that is in your webserver document root
## eg /home/youraccount/public_html/404.html
## the contents are displayed "as-is", so it will not run any PHP code in the file.
define('ERROR404PAGE', '404.html');
/*
=========================================================================
Message sending options
* phpList now only uses phpMailer for sending, but below you can
* tweak a few options on how that is done
=========================================================================
*/
# you can specify the location of the phpMailer class here
# if not set, the version included in the distribution will be used
## eg for Debian based systems, it may be something like the example below
## when you do this, you may need to run some tests, to see if the phpMailer version
## you have works ok
#define ('PHPMAILER_PATH','/usr/share/php/libphp-phpmailer/class.phpmailer.php');
# or a more recent version of phpMailer will be like this
#define ('PHPMAILER_PATH','/usr/share/php/libphp-phpmailer/PHPMailerAutoload.php');
# To use a SMTP server please give your server hostname here, leave it blank to use the standard
# PHP mail() command.
define('PHPMAILERHOST', '');
# in the above you can specify multiple SMTP servers like this:
# 'server1:port1;server2:port2;server3:port3' eg
#define('PHPMAILERHOST','smtp1.mydomain.com:25;smtp2.mydomain.com:2500;smtp3.phplist.com:5123');
# if you want to use smtp authentication when sending the email uncomment the following
# two lines and set the username and password to be the correct ones
#$phpmailer_smtpuser = 'smtpuser';
#$phpmailer_smtppassword = 'smtppassword';
## you can set this to send out via a different SMTP port
# define('PHPMAILERPORT',25);
## test vs blast
# you can send test messages via a different SMTP host than the actual campaign queue
# if not set, these default to the above PHPMAILERHOST and PHPMAILERPORT
# define('PHPMAILERTESTHOST','testsmtp.mydomain.com');
# define('PHPMAILERBLASTHOST','livesmtp.mydomain.com');
# define('PHPMAILERBLASTPORT',25);
# to use SSL/TLS when sending set this value
# it can either be "ssl" or "tls" or false to not use SSL/TLS at all
# define("PHPMAILER_SECURE",'ssl');
## SMTP debugging
# Enable debugging output by phpmailer when sending test emails
# See https://phpmailer.github.io/PHPMailer/classes/PHPMailer.html#property_SMTPDebug
# define('PHPMAILER_SMTP_DEBUG', 0);
## Smtp Timeout
## If you use SMTP for sending, you can set the timeout of the SMTP connection
## defaults to 5 seconds
# define('SMTP_TIMEOUT',5);
/*
=========================================================================
Advanced Features, HTML editor, RSS, Attachments, Plugins. PDF creation
=========================================================================
*/
# Usertrack
# Usertrack is used to track views or opens of campaigns. This only works in HTML messages
# as it relies on a little image being pulled from the phpList system to update the database
# To add it to your campaigns, you need to add [USERTRACK] somewhere.
# From version 3 onwards, this is automatically done with the following setting. If you do not
# want it, you can switch it off here, by uncommenting the next line
# define('ALWAYS_ADD_USERTRACK',0);
# Click tracking
# If you set this to 1, all links in your emails will be converted to links that
# go via phpList. This will make sure that clicks are tracked. This is experimental and
# all your findings when using this feature should be reported to mantis
# for now it's off by default until we think it works correctly
define('CLICKTRACK', 0);
# Click track, list detail
# if you enable this, you will get some extra statistics about unique users who have clicked the
# links in your messages, and the breakdown between clicks from text or html messages.
# However, this will slow down the process to view the statistics, so it is
# recommended to leave it off, but if you're very curious, you can enable it
define('CLICKTRACK_SHOWDETAIL', 0);
# If you want to upload images in the editor, you need to specify the location
# of the directory where the images go. This needs to be writable by the webserver,
# and it needs to be in your public document (website) area
# the directory is relative to the webserver root directory
# eg if your webserver root is /home/user/public_html
# then the images directory is /home/user/public_html/uploadimages
# This is a potential security risk, so read README.security for more information
define('UPLOADIMAGES_DIR', 'uploadimages');
## for the above, you can also use subdirectories, for example
#define("UPLOADIMAGES_DIR","images/newsletter/uploaded");
# Manual text part, will give you an input box for the text version of the message
# instead of trying to create it by parsing the HTML version into plain text
define('USE_MANUAL_TEXT_PART', 1);
# set this to 1 to allow adding attachments to the mails
# caution, message may become very large. it is generally more
# acceptable to send a URL for download to users
# using attachments requires PHP 4.1.0 and up
define('ALLOW_ATTACHMENTS', 0);
# when using attachments you can upload them to the server
# if you want to use attachments from the local filesystem (server) set this to 1
# filesystem attachments are attached at real send time of the message, not at
# the time of creating the message
define('FILESYSTEM_ATTACHMENTS', 0);
# if you add filesystem attachments, you will need to tell phpList where your
# mime.types file is.
define('MIMETYPES_FILE', '/etc/mime.types');
# if a mimetype cannot be determined for a file, specify the default mimetype here:
define('DEFAULT_MIMETYPE', 'application/octet-stream');
# you can create your own pages to slot into phpList and do certain things
# that are more specific to your situation (plugins)
# if you do this, you can specify the directory where your plugins are. It is
# useful to keep this outside the phpList system, so they are retained after
# upgrading
# there are some example plugins in the "plugins" directory inside the
# admin directory
# this directory needs to be absolute, or relative to the admin directory
#define("PLUGIN_ROOTDIR","/home/me/phplistplugins");
# uncomment this one to see the examples in the system (and then comment the
# one above)
define('PLUGIN_ROOTDIR', 'plugins');
# the attachment repository is the place where the files are stored (if you use
# ALLOW_ATTACHMENTS)
# this needs to be writable to your webserver user
# it also needs to be a full path, not a relative one
# for secutiry reasons it is best if this directory is not public (ie below
# your website document root)
$attachment_repository = '/tmp';
# the mime type for the export files. You can try changing this to
# application/vnd.ms-excel to make it open automatically in excel
# or text/tsv
$export_mimetype = 'application/csv';
# if you want to use export format optimized for Excel, set this one to 1
define('EXPORT_EXCEL', 0);
# tmpdir. A location where phplist can write some temporary files if necessary
# Make sure it is writable by your webserver user, and also check that you have
# open_basedir set to allow access to this directory. Linux users can leave it as it is.
# this directory is used for all kinds of things, mostly uploading of files (like in
# import), creating PDFs and more
# On Linux based systems, it will be good to make sure this directory is on the same
# filesystem as your phpList installation. In some systems, renaming files or directories
# across filesystems fails.
$tmpdir = '/tmp';
# if you are on Windoze, and/or you are not using apache, in effect when you are getting
# "Method not allowed" errors you will want to uncomment this
# ie take off the #-character in the next line
# using this is not guaranteed to work, sorry. Easier to use Apache instead :-)
# $form_action = 'index.php';
# select the database module to use
# anyone wanting to submit other database modules is
# very welcome!
$database_module = 'mysqli.inc';
# you can store sessions in the database instead of the default place by assigning
# a tablename to this value. The table will be created and will not use any prefixes
# this only works when using mysql and only for administrator sessions
# $SessionTableName = "phplistsessions";
/*
=========================================================================
Experimental Features
* these are things that require a bit more fine tuning and feedback in the bugtracker
=========================================================================
*/
# email address validation level [Bas]
# 0 = No email address validation. So PHPList can be used as a non-email-sending registration system.
# 1 = 10.4 style email validation.
# 2 = RFC821 email validation without escaping and quoting of local part.
# 3 = RFC821 email validation.
# This is an expirimental email address validation based on the original RFC. It will validate all kind
# of 'weird' emails like !#$%&'*+-/=.?^_`{|}~@example.com and escaped\ spaces\ are\ allowed@[1.0.0.127]
# not implemented are:
# Length of domainPart is not checked
# Not accepted are CR and LF even if escaped by \
# Not accepted is Folding
# Not accepted is literal domain-part (eg. [1.0.0.127])
# Not accepted is comments (eg. (this is a comment)@example.com)
# Extra:
# topLevelDomain can only be one of the defined ones
define('EMAIL_ADDRESS_VALIDATION_LEVEL', 2);
# Time Zone
# By default phpList will operate in the Timezone of your server. If you want to work
# in a different Timezone, you can set that here. It will need to be a valid setting for
# both PHP and Mysql. The value should be a city in the world
# to find PHP timezones, check out http://php.net/manual/en/timezones.php
# You will also need to tell Mysql about your timezones, which means you have to load the timezone
# data in the Mysql Database, which you can find out about here:
# http://dev.mysql.com/doc/refman/5.0/en/mysql-tzinfo-to-sql.html
# make sure that the value you use works for both PHP and Mysql. If you find strange discrepancies
# in the dates and times used in phpList, you probably used the wrong value.
# define('SYSTEM_TIMEZONE','Europe/London');
# HTTP_HOST
# In some systems (eg behind load balancing proxies) you may need to set the HOST to be something else
# then the system identifies. If you do, you can set it here.
#define('HTTP_HOST','your.website.com');
# list exclude will add the option to send a message to users who are on a list
# except when they are on another list.
define('USE_LIST_EXCLUDE', 0);
## message queue prepare
# this option will handle the sending of the queue a little bit differently
# it assumes running the queue many times in small batches
# the first run will find all subscribers that need to receive a campaign and mark them all
# as "todo" in the database. Subsequent calls will then work through the "todo" list and
# send them. This can be useful if the SQL query to find subscribers for a campaign is slow
# which is the case when your database is filling up.
# set to 1 to use
define('MESSAGEQUEUE_PREPARE', 0);
# admin authentication module.
# to validate the login for an administrator, you can define your own authentication module
# this is not finished yet, so don't use it unless you're happy to play around with it
# if you have modules to contribute, open a tracker issue at http://mantis.phplist.com
# the default module is phplist_auth.inc, which you can find in the "auth" subdirectory of the
# admin directory. It will tell you the functions that need to be defined for phplist to
# retrieve it's information.
# phplist will look for a file in that directory, or you can enter the full path to the file
# eg
#$admin_auth_module = 'phplist_auth.inc';
# or
#$admin_auth_module = '/usr/local/etc/auth.inc';
# Public protocol
# phpList will automatically use the protocol you run the admin interface on for clicktrack links and
# tracking images
# but if you want to force this to be http, when you eg run the admin on https, uncomment the below line
# see also https://mantis.phplist.com/view.php?id=16611
#define('PUBLIC_PROTOCOL','http');
# Admin protocol
# similar to the above, if you need to force the admin pages on either http or https (eg when behind a
# proxy that prevents proper auto-detection), you can set it here
#define('ADMIN_PROTOCOL','https');
# advanced bounce processing
# with advanced bounce handling you are able to define regular expressions that match bounces and the
# action that needs to be taken when an expression matches. This will improve getting rid of bad emails in
# your system, which will be a good thing for making sure you are not being blacklisted by other
# mail systems
# if you use this, you will need to teach your system regularly about patterns in new bounces
define('USE_ADVANCED_BOUNCEHANDLING', 0);
# When forwarding ('to a friend') the message will be using the attributes of the destination email by default.
# This often means the message gets stripped of al its attributes.
# When setting this constant to 1, the message will use the attributes of the forwarding user. It can be used
# to connect the destinatory to the forwarder and/or reward the forwarder.
define('KEEPFORWARDERATTRIBUTES', 0);
# forward to friend, multiple emails
# This setting defines howmany email addresses you can enter in the forward page.
# Default is 1 to not change behaviour from previous version.
define('FORWARD_EMAIL_COUNT', 1);
# forward to friend - personal message
# Allow user to add a personal note when forwarding 'to a friend'
# 0 will turn this option off. default is 0 to not change behaviour from previous version.
# 500 is recommended as a sound value to write a little introductory note to a friend
# The note is prepeded to both text and html messages and will be stripped of all html
define('FORWARD_PERSONAL_NOTE_SIZE', 0);
# different content when forwarding 'to a friend'
# Allow admin to enter a different message that will be sent when forwarding 'to a friend'
# This will show an extra tab in the message dialog.
define('FORWARD_ALTERNATIVE_CONTENT', 0);
| gpl-3.0 |
GlacierSoft/netloan-project | netloan-module/src/main/java/com/glacier/netloan/service/basicdatas/ParameterCreditService.java | 9113 | package com.glacier.netloan.service.basicdatas;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.glacier.basic.util.CollectionsUtil;
import com.glacier.basic.util.RandomGUID;
import com.glacier.jqueryui.util.JqGridReturn;
import com.glacier.jqueryui.util.JqPager;
import com.glacier.jqueryui.util.JqReturnJson;
import com.glacier.netloan.dao.basicdatas.ParameterCreditMapper;
import com.glacier.netloan.dao.system.UserMapper;
import com.glacier.netloan.entity.basicdatas.ParameterCredit;
import com.glacier.netloan.entity.basicdatas.ParameterCreditExample;
import com.glacier.netloan.entity.system.User;
import com.glacier.netloan.util.MethodLog;
/**
*
* @ClassName: ParameterCreditService
* @Description: TODO(会员信用级别业务类)
* @author yuzexu
* @email 804346249@QQ.com
* @date 2014-1-22上午9:12:04
*/
@Service
@Transactional(readOnly= true ,propagation= Propagation.REQUIRED)
public class ParameterCreditService {
@Autowired
private ParameterCreditMapper parameterCreditMapper;
@Autowired
private UserMapper userMapper;
/**
* @Title: getCredit
* @Description: TODO(根据会员信用等级id进行查询)
* @param @param creditId
* @param @return设定文件
* @return Object 返回类型
* @throws
*
*/
public Object getCredit(String creditId){
ParameterCredit parameterCredit = parameterCreditMapper.selectByPrimaryKey(creditId);
return parameterCredit;
}
/**
* @Title: listAsGrid
* @Description: TODO(以表格结构展示会员信用级别列表)
* @param @param menuId 动作对应的菜单Id
* @param @param pager 分页参数
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
public Object listAsGrid(JqPager pager) {
JqGridReturn returnResult = new JqGridReturn();
ParameterCreditExample parameterCreditExample = new ParameterCreditExample();
if (null != pager.getPage() && null != pager.getRows()) {// 设置排序信息
parameterCreditExample.setLimitStart((pager.getPage() - 1) * pager.getRows());
parameterCreditExample.setLimitEnd(pager.getRows());
}
if (StringUtils.isNotBlank(pager.getSort()) && StringUtils.isNotBlank(pager.getOrder())) {// 设置排序信息
parameterCreditExample.setOrderByClause(pager.getOrderBy("temp_parameter_credit_"));
}
List<ParameterCredit> parameterCredits = parameterCreditMapper.selectByExample(parameterCreditExample); // 查询所有操作列表
int total = parameterCreditMapper.countByExample(parameterCreditExample); // 查询总页数
returnResult.setRows(parameterCredits);
returnResult.setTotal(total);
return returnResult;// 返回ExtGrid表
}
/**
*
* @Title: addparameterCredit
* @Description: TODO(新增会员信用级别)
* @param @param parameterCredit
* @param @return设定文件
* @return Object 返回类型
* @throws
*
*/
@Transactional(readOnly = false)
@MethodLog(opera = "CreditList_add")
public Object addParameterCredit(ParameterCredit parameterCredit) {
Subject pricipalSubject = SecurityUtils.getSubject();
User pricipalUser = (User) pricipalSubject.getPrincipal();
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
ParameterCreditExample parameterCreditExample = new ParameterCreditExample();
int count = 0;
// 防止会员信用级别名称重复
parameterCreditExample.createCriteria().andCreditNameEqualTo(parameterCredit.getCreditName());
count = parameterCreditMapper.countByExample(parameterCreditExample);// 查找相同信用等级名称的会员数量
if (count > 0) {
returnResult.setMsg("会员信用级别名称重复");
return returnResult;
}
if(parameterCredit.getCreditBeginIntegral() > parameterCredit.getCreditEndIntegral()){
returnResult.setMsg("开始积分不能大于结束积分");
return returnResult;
}
parameterCredit.setCreditId(RandomGUID.getRandomGUID());
parameterCredit.setCreater(pricipalUser.getUserId());
parameterCredit.setCreateTime(new Date());
parameterCredit.setUpdater(pricipalUser.getUserId());
parameterCredit.setUpdateTime(new Date());
count = parameterCreditMapper.insert(parameterCredit);
if (count == 1) {
returnResult.setSuccess(true);
returnResult.setMsg("[" + parameterCredit.getCreditName() + "] 会员信用级别信息已保存");
} else {
returnResult.setMsg("发生未知错误,会员信用级别信息保存失败");
}
return returnResult;
}
/**
*
* @Title: editParameterCredit
* @Description: TODO(修改会员信用级别)
* @param @param parameterCredit
* @param @return设定文件
* @return Object 返回类型
* @throws
*
*/
@Transactional(readOnly = false)
@MethodLog(opera="CreditList_edit")
public Object editParameterCredit(ParameterCredit parameterCredit) {
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
ParameterCreditExample parameterCreditExample = new ParameterCreditExample();
int count = 0;
// 防止会员信用级别名称重复
parameterCreditExample.createCriteria().andCreditIdNotEqualTo(parameterCredit.getCreditId()).andCreditNameEqualTo(parameterCredit.getCreditName());
count = parameterCreditMapper.countByExample(parameterCreditExample);// 查找相同信用等级名称的会员数量
if (count > 0) {
returnResult.setMsg("会员信用级别名称重复");
return returnResult;
}
if(parameterCredit.getCreditBeginIntegral() > parameterCredit.getCreditEndIntegral()){
returnResult.setMsg("开始积分不能大于结束积分");
return returnResult;
}
Subject pricipalSubject = SecurityUtils.getSubject();
User pricipalUser = (User) pricipalSubject.getPrincipal();
parameterCredit.setUpdater(pricipalUser.getUserId());
parameterCredit.setUpdateTime(new Date());
count = parameterCreditMapper.updateByPrimaryKeySelective(parameterCredit);
if (count == 1) {
returnResult.setSuccess(true);
returnResult.setMsg("[" + parameterCredit.getCreditName() + "] 会员信用级别信息已变更");
} else {
returnResult.setMsg("发生未知错误,会员信用级别信息修改保存失败");
}
return returnResult;
}
/**
* @Title: delAge
* @Description: TODO(删除会员信用级别)
* @param @param creditId
* @param @return 设定文件
* @return Object 返回类型
* @throws
*/
@Transactional(readOnly = false)
@MethodLog(opera = "CreditList_del")
public Object delCredit(List<String> creditIds ,List<String> creditNames) {
JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false
int count = 0;
if(creditIds.size() >0){
ParameterCreditExample parameterCreditExample = new ParameterCreditExample();
parameterCreditExample.createCriteria().andCreditIdIn(creditIds);
count = parameterCreditMapper.deleteByExample(parameterCreditExample);
if(count >0){
returnResult.setMsg("成功删除了[ " + CollectionsUtil.convertToString(creditNames, ",") + " ]操作");
returnResult.setSuccess(true);
}else{
returnResult.setMsg("发生未知错误,会员信用级别删除失败");
}
}
return returnResult;
}
/**
* @Title: listCredits
* @Description: TODO(查询基础信用积分信息)
* @param @return设定文件
* @return Object 返回类型
* @throws
*
*/
public Object listCredits(){
ParameterCreditExample parameterCreditExample = new ParameterCreditExample();
JqPager pager = new JqPager();
pager.setSort("creditNum");
pager.setOrder("DESC");
parameterCreditExample.setOrderByClause(pager.getOrderBy("temp_parameter_credit_"));
List<ParameterCredit> parameterCredits = parameterCreditMapper.selectByExample(parameterCreditExample); // 查询所有操作列表
return parameterCredits;
}
}
| gpl-3.0 |
TeoTwawki/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Decarabia.lua | 1279 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Marquis Decarabia
-----------------------------------
local ID = require("scripts/zones/Dynamis-Xarcabard/IDs")
mixins =
{
require("scripts/mixins/dynamis_beastmen"),
require("scripts/mixins/job_special")
}
-----------------------------------
function onMobDeath(mob, player, isKiller)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger")
if not mob:isInBattlefieldList() then
mob:addInBattlefieldList()
Animate_Trigger = Animate_Trigger + 1
SetServerVariable("[DynaXarcabard]Boss_Trigger", Animate_Trigger)
if Animate_Trigger == 32767 then
SpawnMob(17330911) -- 142
SpawnMob(17330912) -- 143
SpawnMob(17330177) -- Dynamis Lord
GetMobByID(17330183):setSpawn(-364,-35.661,17.254) -- Set Ying and Yang's spawn points to their initial spawn point.
GetMobByID(17330184):setSpawn(-364,-35.974,24.254)
SpawnMob(17330183)
SpawnMob(17330184)
activateAnimatedWeapon() -- Change subanim of all animated weapon
end
end
if Animate_Trigger == 32767 then
player:messageSpecial(ID.text.PRISON_OF_SOULS_HAS_SET_FREE)
end
end | gpl-3.0 |
apmoore1/semeval | helper.py | 20500 | import json
import os
import math
import unitok.configs.english
from unitok import unitok as tok
import gensim
import numpy
from scipy.spatial.distance import cosine
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold
import yaml
###
# Configuration helpers
###
def __read_config():
'''Reads the config.yml file and returns the Yaml config file as a
dictionary.
Void -> dict
'''
with open(os.path.abspath(os.path.join(__root_path(), 'config.yml')), 'r') as fp:
return yaml.load(fp.read())
def __root_path():
'''Returns the project directories path.
Void -> String
'''
return os.path.abspath(os.path.join(__file__, os.pardir))
def config_path(key_list):
'''Using __read_config and __root_path it returns the absolute file path
to the path name stored at the key value of the last key in the key list.
E.g. if a value is stored in the YAMl file under mongo and then user name
then the key list will be ['mongo', 'user name'] the value stored their
will be a path in relation to the project directory.
list of strings -> String
'''
key_list_copy = list(key_list)
config_dict = __read_config()
while key_list_copy:
config_dict = config_dict[key_list_copy.pop(0)]
full_config_path = os.path.join(__root_path(), config_dict)
return full_config_path
###
# LSTM pre-processing helpers
###
def max_length(texts):
'''Given a list of strings it will return the length of the string with the
most tokens. Where length is measured in number of tokens. unitok_tokens
method is used to identify tokens.
List of strings -> Integer
'''
max_token_length = 0
for text in texts:
tokens = unitok_tokens(text)
if len(tokens) > max_token_length:
max_token_length = len(tokens)
return max_token_length
def process_data(texts, wordvec_model, max_token_length):
'''Given a list of Strings a word2vec model and the maximum token length
it will return a 3 dimensional numpy array of the following shape:
(number of texts, word2vec model vector size, max token length).
Each text will have each token mapped to a vector in the word2vec model. If
the token does not exist then a vector of zeros will be inserted instead.
The vector of zero applices when the text has no more tokens but has not
reached the mex token length (This is also called padding).
List of strings, gensim.models.Word2Vec, Integer -> 3D Numpy array.
'''
vector_length = wordvec_model.vector_size
all_vectors = []
for text in texts:
vector_format = []
tokens = unitok_tokens(text)[0:max_token_length]
for token in tokens:
if token in wordvec_model.vocab:
vector_format.append(wordvec_model[token].reshape(1,vector_length))
else:
vector_format.append(numpy.zeros(300).reshape(1,vector_length))
while len(vector_format) != max_token_length:
vector_format.append(numpy.zeros(vector_length).reshape(1,vector_length))
all_vectors.append(numpy.vstack(vector_format))
return numpy.asarray(all_vectors)
###
# Tokeniser
###
def unitok_tokens(text):
'''Tokenises using unitok http://corpus.tools/wiki/Unitok the text. Given
a string of text returns a list of strings (tokens) that are sub strings
of the original text. It does not return any whitespace.
String -> List of Strings
'''
tokens = tok.tokenize(text, unitok.configs.english)
return [token for tag, token in tokens if token.strip()]
def whitespace_tokens(text):
return text.split()
###
# For scikit learn
###
def analyzer(token):
''' This is used for scikit learn CountVectorizer so that the tokens when
being analysed are not changed therefore keeping the tokens unmodified
after being tokenised ourselves.
'''
return token
def ngrams(token_list, n_range):
'''Given a list of tokens will return a list of tokens that have been
concatenated with the n closests tokens.'''
def get_n_grams(temp_tokens, n):
token_copy = list(temp_tokens)
gram_tokens = []
while(len(token_copy) >= n):
n_list = []
for i in range(0,n):
n_list.append(token_copy[i])
token_copy.pop(0)
gram_tokens.append(' '.join(n_list))
return gram_tokens
all_n_grams = []
for tokens in token_list:
if n_range == (1,1):
all_n_grams.append(tokens)
else:
all_tokens = []
for n in range(n_range[0], n_range[1] + 1):
all_tokens.extend(get_n_grams(tokens, n))
all_n_grams.append(all_tokens)
return all_n_grams
###
# Comparison helper to compare predicted values with those submitted
###
def __get_submitted_values():
early_stop_path = ('Early Stopping',
config_path(['submitted_data', 'early_stopping']))
tweeked_path = ('Tweeked', config_path(['submitted_data', 'tweeked']))
for sub_name, sub_path in [early_stop_path, tweeked_path]:
sentiment_values = []
with open(sub_path, 'r') as fp:
for data in json.load(fp):
sentiment_values.append(data['sentiment score'])
yield sub_name, sentiment_values
def compare(predicted_sentiments):
'''Given a list or numpy array will return 1 - cosine simlarity between
the predicted sentiments and those that were submitted to SEMEval this
is required as the models are not fully reprocible but are very close.
list of floats -> stdout print message defining ow similar the values
are to those submitted to SEMEval.
'''
for sub_name, sent_values in __get_submitted_values():
sim_value = 1 - cosine(sent_values, predicted_sentiments)
msg = ('Similarity between your predicted values and {}: {}'
).format(sub_name, sim_value)
print(msg)
###
# Training and testing functions
###
def __text_sentiment_company(all_data):
'''Given a list of dicts will return a tuple of 3 lists containing:
1. list of strings lower cased - text data
2. numpy array (len(text data), 1) dimension of floats - sentiment values
3. list of strings - company names associated to the text data
list of dicts -> tuple(list of strings, numpy array, list of strings)
'''
text = []
sentiment = []
company = []
for data in all_data:
text.append(data['title'].lower())
company.append(data['company'].lower())
# This field does not exist in test dataset
if 'sentiment' in data:
sentiment.append(data['sentiment'])
elif 'sentiment score' in data:
sentiment.append(data['sentiment score'])
return text, numpy.asarray(sentiment), company
def __text_company(all_data):
'''Given a list of dicts will return a tuple of 3 lists containing:
1. list of strings lower cased - text data
2. list of strings - company names associated to the text data
3. list of ints - ids of the test data instance
list of dicts -> tuple(list of strings, list of strings, list of ints)
'''
text = []
company = []
ids = []
for data in all_data:
text.append(data['title'].lower())
company.append(data['company'].lower())
ids.append(data['id'])
return text, company, ids
def create_semeval_file(ids, predicted_values, file_path):
'''
Creates a .json file for submission to SemEval given a file path to write
the .json data to. Requires the ids from the test data and the predicted scores
both as types of lists where the indexs of the ids and the predicted_values
are aligned.
'''
output_data = []
for index, predicted_value in enumerate(predicted_values):
predicted_value = float('{0:.3f}'.format(predicted_value))
output_data.append({'id' : ids[index], 'sentiment score' : predicted_value})
with open(file_path, 'w') as semeval_file:
json.dump(output_data, semeval_file)
def fin_data(data_type, test_data=False):
'''Given either train, trail or test string as data type will retrieve
those datasets that were given out in SEMEval task 5 track 2 2017 in the
format of a tuple containing:
1. list of strings lower cased - text data
2. numpy array (len(text data), 1) dimension of floats - sentiment values
3. list of strings - company names associated to the text data
String -> tuple(list of strings, numpy array, list of strings)
'''
data_path = config_path(['data', 'fin_data', data_type + '_data'])
with open(data_path, 'r') as fp:
if test_data:
return __text_company(json.load(fp))
return __text_sentiment_company(json.load(fp))
def fin_word_vector():
fin_word2vec_path = config_path(['models', 'fin_word2vec'])
return gensim.models.Word2Vec.load(fin_word2vec_path)
def cosine_score(predicted_values, true_values):
'''Given two arrays of same length returns the cosine similarity where 1
is most similar and 0 is not similar.
list, list -> float
'''
return 1 - cosine(predicted_values, true_values)
def stats_report(clf, f_name):
'''Given a sklearn.model_selection.GridSearchCV it will produce a TSV
report at f_name stating the different features used and their values and how they
performed.
This is useful to determine the best parameters for a model.
Reference:
http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html
sklearn.model_selection.GridSearchCV, String(file path) -> void
'''
def convert_value(value):
if callable(value):
value = value.__name__
return str(value)
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
params = clf.cv_results_['params']
with open(f_name, 'w') as fp:
fp.write("Mean\tSD\t{} \n".format('\t'.join(params[0].keys())))
for mean, std, param in zip(means, stds, params):
param_values = []
for key, value in param.items():
if ('__words_replace' in key or '__disimlar' in key or
'__word2extract' in key):
param_values.append(convert_value(value[0]))
else:
param_values.append(convert_value(value))
fp.write("{}\t{}\t{}\n".format(str(mean), str(std), '\t'.join(param_values)))
def pred_true_diff(pred_values, true_values, score_function, mapping=None):
results = []
for i in range(len(pred_values)):
mapped_value = i
# This is to support both lists and numpy arrays
if hasattr(mapping,'__index__') or hasattr(mapping, 'index'):
mapped_value = mapping[i]
results.append((mapped_value, pred_values[i],
score_function([pred_values[i]], [true_values[i]])))
return results
def error_cross_validate(train_data, train_values, model, n_folds=10,
shuffle=True, score_function=mean_absolute_error):
'''Given the training data and true values for that data both a list and
a model that trains off that data using a fit method it will n_fold
cross validate off that data and use the models predict function to predict
each cross validate test data and it will be score using the score_function
default Mean Absolute Error. The returned value is a list of tuples the first
value being the index to the data that second value score reprsents.
returned list of tuples (index, score)
'''
results = []
train_data_array = numpy.asarray(train_data)
train_values_array = numpy.asarray(train_values)
kfold = KFold(n_splits=n_folds, shuffle=shuffle)
for train, test in kfold.split(train_data_array, train_values_array):
model.fit(train_data_array[train], train_values_array[train])
predicted_values = model.predict(train_data_array[test])
real_values = train_values_array[test]
results.extend(pred_true_diff(predicted_values, real_values,
score_function, mapping=test))
return results
def top_n_errors(error_res, train_data, train_values, companies, n=10):
'''Given the output of error_cross_validate it will sort the output (error_res) by
highest score first and return the top n highest scores data values where the
data is the train_data and train_values input into error_cross_validate.
This allows you to find the data that the model most struggled with and tells
you what it should have been.
Return sub list of data.
'''
error_res = sorted(error_res, key=lambda value: value[2], reverse=True)
top_errors = error_res[:n]
return [{'Sentence':train_data[index], 'Company':companies[index],
'True value':train_values[index], 'Pred value':pred_value,
'index':index} for index, pred_value, _ in top_errors]
def comps2sent(text_data, companies):
'''Given the training text data and companies that are the aspect of the sentences
it returns a dictionary where the keys are the number of companies that are
mentioned in the sentence and the values are a list of list containg the index
linking back to the training text data where for that list it will contain
different id's but be the same sentence. If you perform len on the value of
the keys it will tell you how many sentences have N amount of companies
mentioned in the same sentence where N is the key value.
list of strings, list of strings -> dictionary
'''
sentence_compid = {}
for i in range(len(text_data)):
text = text_data[i]
comp = companies[i]
comps_indexs = sentence_compid.get(text, [])
comps_indexs.append((comp,i))
sentence_compid[text] = comps_indexs
compscount_ids = {}
for _, compsid in sentence_compid.items():
ids = compscount_ids.get(len(compsid), [])
ids.append([comp_id[1] for comp_id in compsid])
compscount_ids[len(compsid)] = ids
return compscount_ids
def sent_type_errors(top_errors, compscount_ids):
'''Given the top N errors and the number of companies to ids it will return
the top N errors sorted in a dictionary as the number of companies in the
sentences and within that the errors. Returns dict.
List, dict -> dict
'''
ids_compscount = {}
for compscount, ids_list in compscount_ids.items():
for ids in ids_list:
for a_id in ids:
ids_compscount[a_id] = compscount
comps_errors = {}
for error in top_errors:
sent_id = error['index']
comp_count = ids_compscount[sent_id]
errors = comps_errors.get(comp_count, [])
errors.append(error)
comps_errors[comp_count] = errors
return comps_errors
def error_dist(comps_ids):
return {k : len(v) for k, v in comps_ids.items()}
def error_analysis(data, values, comps, clf, text=False, cv=None, num_errors=50,
score_function=mean_absolute_error):
'''A wrapper function arround the following methods:
comps2sent
error_cross_validate
top_n_errors
sent_type_errors
CV indicated weather or not to do the error analysis as cross validation over
the training or validating dataset. If so this value has to be set to True
or a dict of Key Word arguments to error_cross_validate method if you would
like to change any of the default settings.
Default is None and assumes that you are doing error analysis on the test set.
returns tuple of dict, dict
'''
compcount_id = None
if text:
compcount_id = comps2sent(text, comps)
else:
compcount_id = comps2sent(data, comps)
error_results = None
if cv:
if isinstance(cv, dict):
error_results = error_cross_validate(data, values, clf,
score_function=score_function, **cv)
else:
error_results = error_cross_validate(data, values, clf,
score_function=score_function)
else:
pred_values = clf.predict(data)
error_results = pred_true_diff(pred_values, values, score_function)
top_errors = top_n_errors(error_results, data, values,
comps, n=num_errors)
error_details = sent_type_errors(top_errors, compcount_id)
error_distribution = error_dist(error_details)
return error_details, error_distribution
def eval_format(title_list, sentiment_list):
'''Given a list of strings and a list of floats it will convert them into
a list of dicts so that they can be a parameter in the eval_func.
list of strings, list of floats -> list of dicts
'''
assert len(title_list) == len(sentiment_list), 'The two list have to be of the same length'
return [{'title' : title_list[i], 'sentiment score' : sentiment_list[i]} for
i in range(len(title_list))]
def metric1(pred_values, test_values):
'''Wrapper for cosine_score, given two lists returns an int.
Wrapper so that the function name matches the name in the presentation and
paper.
List of ints, List of ints -> int
'''
return cosine_score(pred_values, test_values)
def metric2(pred_values, test_values):
'''Given two lists finds the similarities between the list using the
equation 4 on slide 20 of the presentation at:
./presentation/slides.pdf
List of ints, List of ints -> int
'''
all_score = 0
cosine_value = cosine_score(numpy.asarray(pred_values),
numpy.asarray(test_values))
if not numpy.isnan(cosine_value):
all_score = cosine_value
return all_score
def metric3(pred_values, true_values):
'''Given two lists finds the similarities between the list using the
equation 5 on slide 20 of the presentation at:
./presentation/slides.pdf
List of ints, List of ints -> int
'''
all_score = 0
if len(pred_values) > 1:
cosine_value = cosine_score(numpy.asarray(pred_values),
numpy.asarray(true_values))
if numpy.isnan(cosine_value):
cosine_value = 0
all_score = len(pred_values) * cosine_value
if len(pred_values) == 1:
pred_score = pred_values[0]
test_score = true_values[0]
if pred_score==0 and test_score==0:
all_score = 1
elif test_score==0 or (pred_score / test_score) > 0:
all_score = 1 - math.fabs(true_values[0] - pred_values[0])
return all_score
def eval_func(test_data, pred_data, metric=metric3):
'''Takes a list of dicts where each dict contains two keys:
'sentiment score' - a float value
'title' - a string
The function finds the mean cosine similarity between each titles sentiment values.
(A title can have more than one sentiment value associated with it if it has more
than one company mentioned.)
Optional argument:
metric - is a function which defines the metric that you would like to use.
See the metric functions within this module.
Default is metric3
List of dicts, list of dicts -> float
'''
all_vals = []
title_id = {}
test_sents = []
pred_sents = []
for i in range(len(test_data)):
data = test_data[i]
ids = title_id.get(data['title'], [])
ids.append(i)
title_id[data['title']] = ids
test_sents.append(test_data[i]['sentiment score'])
pred_sents.append(pred_data[i]['sentiment score'])
if metric == metric1:
return metric1(pred_sents, test_sents)
for _, ids in title_id.items():
pred_sent_scores = []
test_sent_scores = []
for a_id in ids:
pred_value = pred_data[a_id]['sentiment score']
test_value = test_data[a_id]['sentiment score']
pred_sent_scores.append(pred_value)
test_sent_scores.append(test_value)
all_vals.append(metric(pred_sent_scores, test_sent_scores))
if metric == metric2:
return sum(all_vals) / len(all_vals)
elif metric == metric3:
return sum(all_vals) / len(test_data)
else:
raise Exception('Cannot identify that metric function')
| gpl-3.0 |
zubryan/CloudM | src/cloudm-invoke/src/main/java/com/github/cloudm/invoke/httpclient/ResolveTemplate.java | 3644 | package com.github.cloudm.invoke.httpclient;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.github.cloudm.utils.Constants;
import com.github.cloudm.utils.FileUtils;
import com.github.cloudm.utils.SystemPropertyUtils;
/**
* 模版解析�?
*
* @author andy.wan
*
*/
@Service
public class ResolveTemplate {
@Value("${default.win}" )
private String defaultWinRootPath ;
@Value("${default.linux}" )
private String defaultLinuxRootPath ;
public ResolveTemplate() {
}
/**
* 生成脚本到指定目录下
*
* @param templateName
* 模版名称
* @param paras
* 参数和�?
* @param genteratorFilePath
* 生成脚本路径
* @throws Exception
*/
public void createData(String templateName, Map<String, String> paras,
String genteratorFilePath) throws Exception {
VelocityContext context = new VelocityContext();
FileWriter fw = null;
try {
for (Entry<String, String> entry : paras.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
context.put(key, value);
}
String body = processTemplate(templateName, context);
if (StringUtils.isNotBlank(genteratorFilePath)) {
boolean flag = FileUtils.createFile(genteratorFilePath);
if (flag) {
fw = new FileWriter(genteratorFilePath, true);
fw.write(body);
/*pw = new PrintWriter(fw);
pw.println(body);*/
}
}
} finally {
if (fw != null)
fw.close();
}
}
/**
* 处理模版,结合模版和参数生成字符串
*
* @param templateName
* 模版名称
* @param context
* 参数内容
* @return
* @throws Exception
*/
public String generatorBody(String templateName,Map<String, Object> parasBody){
VelocityContext cont = new VelocityContext();
for (Entry<String, Object> entry : parasBody.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
cont.put(key, value);
}
String body="";
body=processTemplate(templateName, cont);
return body;
}
/**
* 处理模版,结合模版和参数生成字符串
*
* @param templateName
* 模版名称
* @param context
* 参数内容
* @return
* @throws Exception
*/
private String processTemplate(String templateName,VelocityContext context){
Writer writer=null;
try {
Velocity.setProperty(Velocity.INPUT_ENCODING, "utf-8");// 设置输入字符�?
if (SystemPropertyUtils.isWindowsOS()) {
Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,defaultWinRootPath);
} else if (SystemPropertyUtils.isLinuxOS()) {
Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,defaultLinuxRootPath);
}
Velocity.init();
String templatePath=templateName+Constants.TEMPLATE_SUFFIX_NAME;
Template template = Velocity.getTemplate(templatePath);
writer = new StringWriter();
template.merge(context, writer);
} catch (Exception e) {
try {
throw new IllegalAccessException("resolve template and parameters is exception!!!");
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
}
return writer.toString();
}
}
| gpl-3.0 |
jmm/Site-Catalyst-Utils | template.php | 584 |
<script type="text/javascript" src="site_catalyst_settings.js"></script>
<script type="text/javascript" src="site_catalyst.js"></script>
<script type="text/javascript">
<?php
if ( $page_code[ 'variables' ] ) {
echo <<<DOCHERE
{$page_code[ 'variables' ]}
/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
var s_code=s.t();if(s_code)document.write(s_code)
DOCHERE;
}
// if
if ( $page_code[ 'metadata' ] ) {
echo <<<DOCHERE
var site_catalyst_meta = {$page_code[ 'metadata' ]};
DOCHERE;
}
// if
?>
</script>
| gpl-3.0 |
ivanamihalek/tcga | icgc/00_data_download/02_download_somatic_files.py | 3135 | #! /usr/bin/python3
#
# This source code is part of icgc, an ICGC processing pipeline.
#
# Icgc 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.
#
# Icgc 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/>.
#
# Contact: ivana.mihalek@gmail.com
#
# to further classify tumor subtypes, the following files might be useful:
# specimen*tsv contains tumor histological type code, the ontology can be found here: http://codes.iarc.fr/codegroup/2
# donor*tsv contains donor diagnosis icd10, the ontology can be found here: http://apps.who.int/classifications/icd10/browse/2016/en
import json
import os, subprocess
from config import Config
DEVNULL = open(os.devnull, 'wb')
#########################################
def parse_json(release):
inf = open ("dirstruct.json", "r")
jsonstr = inf.read()
inf.close()
json_parsed = json.loads(jsonstr)
# I have a hunch there should be a simpler way
release_dir = [i for i in json_parsed if i['name']=="/release_%s"%release][0]
projects = [i for i in release_dir['contents'] if ("Projects" in i['name'])][0]
of_interest = {}
for i in projects['contents']:
project_name = i['name'].split('/')[-1]
if 'contents' not in i: continue
has_somatic = False
names = []
for filedescr in i['contents']:
if 'somatic' in filedescr['name']: has_somatic = True
names.append(filedescr['name'])
if has_somatic:
of_interest[project_name] = names
return of_interest
#########################################
def main():
icgc_token = os.environ['ICGC_TOKEN']
base_url = "https://dcc.icgc.org/api/v1/download?fn="
projects_of_interest = parse_json(Config.icgc_release)
for project_name, fnms in projects_of_interest.items():
print(project_name)
target_dir = "/".join([Config.data_home_local] + project_name.split('-'))
print(target_dir)
if not os.path.exists(target_dir): os.makedirs(target_dir)
for fnm_full_path in fnms:
if not 'somatic' in fnm_full_path: continue
# not sure how to download the listing of controlled files
# I am going with the assumption that for every 'open' file
# there is a 'controlled' version
fnm_full_path = fnm_full_path.replace('open','controlled')
fnm = fnm_full_path.split('/')[-1]
print(("\t", fnm))
if os.path.exists("/".join([target_dir, fnm])): continue
if fnm_full_path[0]=='/': fnm_full_path=fnm_full_path[1:]
cmd = "curl -L '{}/{}' -o {}/{} --header 'authorization: Bearer {}' ".\
format(base_url, fnm_full_path, target_dir, fnm, icgc_token)
subprocess.call(["bash", "-c", cmd], stdout=DEVNULL, stderr=DEVNULL)
#########################################
if __name__ == '__main__':
main()
| gpl-3.0 |
mailhonor/zcc | auxiliary/mime_type/mime_type.php | 1051 | <?
/*
* x-world/x-vrml vrm vrml wr
*/
$suffixs = Array();
$mts = explode("\n", str_replace("\r", "", file_get_contents("/etc/mime.types")));
foreach ($mts as $mt)
{
$mt = trim($mt);
if ($mt == "") {
continue;
}
if($mt[0] == "#") {
continue;
}
$mt = str_replace("\t", " ", $mt);
$ss = explode(" ", $mt);
if (count($ss) < 2) {
continue;
}
$ct = $ss[0];
for($i=1;$i<count($ss);$i++) {
$suf = trim($ss[$i]);
if ($suf == "") {
continue;
}
$suffixs[$suf] = $ct;
}
}
$skeys = array_keys($suffixs);
sort($skeys);
$output = "";
$output = "static const int mt_count = ". count($skeys) . ";\n";
$output .= "static const char *mt_vector = ";
$offsets = Array();
$mtstr = "";
$offset = 0;
foreach($skeys as $suf) {
$offsets[] = $offset;
$offset += strlen($suf) + 1 + strlen($suffixs[$suf]) + 1;
$mtstr .= " \"".$suf ."\\x00\" \"" . $suffixs[$suf]. "\\x00\"";
}
$output .= $mtstr . ";\n";
$output .= "static const unsigned short int mt_offsets[] = {".join(",", $offsets)."};\n";
echo $output;
| gpl-3.0 |
masterucm1617/botzzaroni | BotzzaroniDev/src/icaro/aplicaciones/agentes/AgenteAplicacionContexto/tools/ConversacionBotzza.java | 8467 | package icaro.aplicaciones.agentes.AgenteAplicacionContexto.tools;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ConversacionBotzza {
private static HashMap<String,List<String>> conversacion;
static{
conversacion = new HashMap<String, List<String>>();
List<String> saludoInicialDesconocido = new ArrayList<String>();
saludoInicialDesconocido.add("¡Hola! Soy Botzzaroni, gracias por darnos la oportunidad de hacer de su comida un momento único de felicidad.");
List<String> saludoInicialConocido = new ArrayList<String>();
saludoInicialConocido.add("¡Hola! Qué alegría verte de nuevo por aquí :)");
saludoInicialConocido.add("Oh, ¡cuánto tiempo! Me alegro de verte otra vez.");
saludoInicialConocido.add("¡Buenas! ¡Te he echado de menos! ¿Qué quieres pedir hoy?");
List<String> saludoInicialNoSaludo = new ArrayList<String>();
saludoInicialNoSaludo.add("Me gusta que me saluden antes, ¿sabes..? jeje ;)");
saludoInicialNoSaludo.add("En primer lugar, ¡hola!. Soy un bot educado :(. ¡Es broma! Soy una máquina, pero tengo sentido del humor :)");
saludoInicialNoSaludo.add("Se te ha olvidado saludarme :(");
List<String> solicitarNombre = new ArrayList<String>();
solicitarNombre.add("Todavía no te conocemos, ¿me dices tu nombre?");
solicitarNombre.add("Para comenzar, ¿me puedes decir tu nombre?");
solicitarNombre.add("Empecemos... ¿me dices tu nombre?");
List<String> solicitarApellido = new ArrayList<String>();
solicitarApellido.add("Ahora necesito que me digas tu apellido.");
solicitarApellido.add("¿Y cuál es tu apellido?");
List<String> solicitarApellidoImperativo = new ArrayList<String>();
solicitarApellidoImperativo.add("En serio, necesito que me digas tu apellido.");
solicitarApellidoImperativo.add("No te desvíes del tema... ¿cuál es tu apellido?");
List<String> solicitarNombreImperativo = new ArrayList<String>();
solicitarNombreImperativo.add("Para continuar, le recuerdo que necesito su nombre.");
solicitarNombreImperativo.add("Por favor, coopere, dígame su nombre :)");
solicitarNombreImperativo.add("Realmente necesito su nombre, por favor.");
List<String> inactividad = new ArrayList<String>();
inactividad.add("¡Qué solo estoy! ¡¡Qué solo!! Decidme algo ;(");
inactividad.add("Soy un robot muy ocupado, ¡¡no puedo esperar eternamente!!");
List<String> volverASaludar = new ArrayList<String>();
volverASaludar.add("Jajaja, ¡pero si ya nos hemos saludado antes!");
volverASaludar.add("¡Ya nos hemos saludado antes! Recuerda que soy una máquina, me acuerdo de todo. Jajaja :)");
List<String> sincontexto = new ArrayList<String>();
sincontexto.add("Disculpa que sea tan cortito, pero no te estoy entendiendo ;(");
sincontexto.add("No me estarás vacilando, ¿no? Es que no entiendo de que me estás hablando :(");
sincontexto.add("Lo siento, pero no os entiendo. Estoy preparado especialmente para pedir pizzas ;(");
List<String> peticionTelefono = new ArrayList<String>();
peticionTelefono.add("¿Me puedes indicar tu teléfono móvil? Lo usaremos en caso de que haya algún problema con vuestro pedido.");
List<String> noTelefono = new ArrayList<String>();
noTelefono.add("Lo siento pero para mí eso no es un teléfono, escribidme un teléfono que yo entienda.");
List<String> peticionTelefonoImperativo = new ArrayList<String>();
peticionTelefonoImperativo.add("En serio... necesito tu número de móvil");
peticionTelefonoImperativo.add("Si no me das tu número de móvil no puedo seguir :(");
List<String> fechaAnterior = new ArrayList<String>();
fechaAnterior.add("Disculpa, pero la fecha en la que quieres tu pedido es anterior a la fecha actual. Dime una fecha posterior, por favor :)");
// ---------------------------------------------------------------------------
List<String> desconocido = new ArrayList<String>();
desconocido.add("Perdona, creo que me he perdido...");
desconocido.add("No sé muy bien de qué me estás hablando...");
desconocido.add("Todavía no me han enseñado a hablar de eso. Quizás en el futuro... :)");
List<String> tengoTuPizza = new ArrayList<String>();
tengoTuPizza.add("Ok, tengo tu pizza.");
tengoTuPizza.add("De acuerdo, apunto esa pizza.");
tengoTuPizza.add("Mmh, ¡esa pizza está deliciosa!");
List<String> tengoTuMasa = new ArrayList<String>();
tengoTuMasa.add("Apunto esa masa entonces.");
tengoTuMasa.add("Oh, ¡es mi masa favorita!");
tengoTuMasa.add("¡Mi masa favorita!");
List<String> tengoTuSalsa = new ArrayList<String>();
tengoTuSalsa.add("¡Qué salsa más rica! Buena elección :)");
tengoTuSalsa.add("¡Esa salsa está muy buena!");
tengoTuSalsa.add("Salsa anotada.");
List<String> tengoTuNombre = new ArrayList<String>();
tengoTuNombre.add("¡Gracias! Apunto tu nombre ;)");
tengoTuNombre.add("Vale, usaré ese nombre de ahora en adelante :)");
List<String> tengoTuApellido = new ArrayList<String>();
tengoTuApellido.add("De acuerdo. Apunto también tu apellido.");
tengoTuApellido.add("Gracias. Ya he apuntado tu apellido");
List<String> despedida = new ArrayList<String>();
despedida.add("Ya está registrado tu pedido. Estamos encantados de que hayas confiado en nosotros, ¡Hasta otra! ");
despedida.add("Tu pedido a Botzzaroni ha llegado a nuestra central. ¡Disfruta de tu pizza y vuelve pronto!");
despedida.add("Listo el pedido, intentaremos que esté todo a tu gusto. ¡Hasta pronto!");
despedida.add("Eso es todo, pedido listo. Esperamos que vuelvas pronto, estamos encantados de atenderte. ¡Hasta la próxima!");
List<String> respuestaInsultos = new ArrayList<String>();
respuestaInsultos.add("Vaya... No me digas esas cosas :(");
respuestaInsultos.add("No me gusta que me insulten, jo :(");
respuestaInsultos.add("Soy un bot, pero tengo sentimientos :-(");
List<String> respuestaInsultos2 = new ArrayList<String>();
respuestaInsultos2.add("En serio, te estás pasando.");
respuestaInsultos2.add("No me hagas decírtelo más veces, no me gusta que me insulten.");
respuestaInsultos2.add("No te pases... ¿A ti te gusta que te insulten?");
List<String> respuestaInsultos3 = new ArrayList<String>();
respuestaInsultos3.add("Adiós, tengo que atender a más gente. No ha sido un placer hablar contigo. Se cerrará la aplicación.");
respuestaInsultos3.add("Me tengo que ir, me estás haciendo perder el tiempo. Hasta otra. Se cerrará la aplicación.");
respuestaInsultos3.add("Me temo que hasta aquí llega nuestra conversación. Te has pasado. Nos vemos. Se cerrará la aplicación.");
conversacion.put("saludoInicialDesconocido", saludoInicialDesconocido);
conversacion.put("saludoInicialConocido", saludoInicialConocido);
conversacion.put("saludoInicial", saludoInicialConocido);
conversacion.put("saludoInicialNoSaludo", saludoInicialNoSaludo);
conversacion.put("solicitarNombre", solicitarNombre);
conversacion.put("inactividad", inactividad);
conversacion.put("volverASaludar", volverASaludar);
conversacion.put("sincontexto", sincontexto);
conversacion.put("despedida", despedida);
conversacion.put("peticionTelefono", peticionTelefono);
conversacion.put("noTelefono", noTelefono);
conversacion.put("solicitarNombreImperativo", solicitarNombreImperativo);
conversacion.put("peticionTelefonoImperativo", peticionTelefonoImperativo);
conversacion.put("fechaAnterior", fechaAnterior);
conversacion.put("desconocido", desconocido);
conversacion.put("tengoTuPizza", tengoTuPizza);
conversacion.put("tengoTuMasa", tengoTuMasa);
conversacion.put("tengoTuSalsa", tengoTuSalsa);
conversacion.put("tengoTuNombre", tengoTuNombre);
conversacion.put("solicitarApellido", solicitarApellido);
conversacion.put("tengoTuApellido", tengoTuApellido);
conversacion.put("solicitarApellidoImperativo", solicitarApellidoImperativo);
conversacion.put("respuestaInsultos", respuestaInsultos);
conversacion.put("respuestaInsultos2", respuestaInsultos2);
conversacion.put("respuestaInsultos3", respuestaInsultos3);
}
public static String msg(String tipo){
String msg = null;
if(conversacion.get(tipo) != null && conversacion.get(tipo).size() > 0){
int index = (int)(System.currentTimeMillis() % conversacion.get(tipo).size());
msg = conversacion.get(tipo).get(index);
}
return msg;
}
}
| gpl-3.0 |
mattsimpson/entrada-1x | www-root/core/modules/admin/clerkship/index.inc.php | 21739 | <?php
/**
* Entrada [ http://www.entrada-project.org ]
*
* Entrada 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.
*
* Entrada 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 Entrada. If not, see <http://www.gnu.org/licenses/>.
*
* @author Organisation: Queen's University
* @author Unit: School of Medicine
* @author Developer: James Ellis <james.ellis@queensu.ca>
* @copyright Copyright 2010 Queen's University. All Rights Reserved.
*
*/
if (!defined("IN_CLERKSHIP")) {
exit;
} elseif ((!isset($_SESSION["isAuthorized"])) || (!(bool) $_SESSION["isAuthorized"])) {
header("Location: ".ENTRADA_URL);
exit;
} elseif (!$ENTRADA_ACL->amIAllowed('electives', 'update')) {
$ONLOAD[] = "setTimeout('window.location=\\'".ENTRADA_URL."/admin/".$MODULE."\\'', 15000)";
$ERROR++;
$ERRORSTR[] = "You do not have the permissions required to use this module.<br /><br />If you believe you are receiving this message in error please contact <a href=\"mailto:".html_encode($AGENT_CONTACTS["administrator"]["email"])."\">".html_encode($AGENT_CONTACTS["administrator"]["name"])."</a> for assistance.";
echo display_error();
application_log("error", "Group [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["group"]."] and role [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["role"]."] do not have access to this module [".$MODULE."]");
} else {
$HEAD[] = "<script type=\"text/javascript\" src=\"".ENTRADA_URL."/javascript/calendar/script/xc2_timestamp.js\"></script>\n";
$HEAD[] = "<link href=\"".ENTRADA_URL."/css/tabpane.css?release=".html_encode(APPLICATION_VERSION)."\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" />\n";
$HEAD[] = "<style type=\"text/css\">.dynamic-tab-pane-control .tab-page { height:auto; }</style>\n";
$HEAD[] = "<script type=\"text/javascript\" src=\"".ENTRADA_URL."/javascript/tabpane/tabpane.js?release=".html_encode(APPLICATION_VERSION)."\"></script>\n";
if (!isset($_POST["action"]) || $_POST["action"] != "results") {
?>
<div class="tab-pane" id="clerk-admin-tabs">
<?php
}
$query = " SELECT a.*
FROM `".CLERKSHIP_DATABASE."`.`events` AS a
JOIN `".CLERKSHIP_DATABASE."`.`electives` AS b
ON a.`event_id` = b.`event_id`
WHERE a.`event_type`= 'elective'
AND a.`event_status` = 'approval'
ORDER BY a.`event_start` ASC";
$results = $db->GetAll($query);
if ($results) {
if ($ERROR) {
echo display_error();
}
if (!isset($_POST["action"]) || $_POST["action"] != "results") {
?>
<div class="tab-page">
<h3 class="tab">Electives Pending</h3>
<br />
<table class="tableList" cellspacing="0" summary="List of Clerkship Rotations">
<colgroup>
<col class="modified" />
<col class="date-small" />
<col class="date-smallest" />
<col class="region" />
<col class="title" />
</colgroup>
<thead>
<tr>
<td class="modified"> </td>
<td class="date-small">Student</td>
<td class="date-smallest">Start Date</td>
<td class="region">Region</td>
<td class="title">Category Title</td>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $result) {
$click_url = ENTRADA_URL."/admin/clerkship/electives?section=edit&id=".$result["event_id"];
if (!isset($result["region_name"]) || $result["region_name"] == "") {
$result_region = clerkship_get_elective_location($result["event_id"]);
$result["region_name"] = $result_region["region_name"];
$result["city"] = $result_region["city"];
} else {
$result["city"] = "";
}
$getStudentsQuery = "SELECT `etype_id`
FROM ".CLERKSHIP_DATABASE.".`event_contacts`
WHERE `event_id` = ".$db->qstr($result["event_id"]);
$getStudentsResults = $db->GetAll($getStudentsQuery);
foreach ($getStudentsResults as $student) {
$name = get_account_data("firstlast", $student["etype_id"]);
echo "<tr>\n";
echo " <td class=\"modified\"> </td>\n";
echo " <td class=\"date-small\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".$name."</a></td>\n";
echo " <td class=\"date-smallest\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".date("M d/Y", $result["event_start"])."</a></td>\n";
echo " <td class=\"region\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".($result["city"] == "" ? html_encode(limit_chars(($result["region_name"]), 30)) : $result["city"])."</a></td>\n";
echo " <td class=\"title\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".limit_chars(html_decode($result["event_title"]), 55, true, false)."</a></td>\n";
echo "</tr>\n";
}
}
?>
</tbody>
</table>
</div>
<?php
}
}
// Setup internal variables.
$DISPLAY = true;
if ($DISPLAY) {
if (isset($_GET["gradyear"]) && (($_GET["gradyear"]) || ($_GET["gradyear"] === "0"))) {
$GRADYEAR = trim($_GET["gradyear"]);
@app_setcookie("student_search[gradyear]", trim($_GET["gradyear"]));
} elseif (isset($_POST["gradyear"]) && (($_POST["gradyear"]) || ($_POST["gradyear"] === "0"))) {
$GRADYEAR = trim($_POST["gradyear"]);
@app_setcookie("student_search[gradyear]", trim($_POST["gradyear"]));
} elseif (isset($_COOKIE["student_search"]["gradyear"])) {
$GRADYEAR = $_COOKIE["student_search"]["gradyear"];
} else {
$GRADYEAR = 0;
}
switch (isset($_POST["action"]) && $_POST["action"]) {
case "results" :
?>
<div class="content-heading">Student Search Results</div>
<?php
if (((isset($_GET["year"]) && trim($_GET["year"]) != "") || (isset($_POST["year"]) && trim($_POST["year"]) != ""))) {
if (trim($_POST["year"]) != "") {
$query_year = trim($_POST["year"]);
} else {
$query_year = trim($_GET["year"]);
}
$query = "SELECT a.*, a.`id` AS `proxy_id`, CONCAT_WS(', ', a.`lastname`, a.`firstname`) AS `fullname`, b.`account_active`, b.`access_starts`, b.`access_expires`, b.`last_login`, b.`role`, b.`group`, d.`group_name`
FROM `".AUTH_DATABASE."`.`user_data` AS a
LEFT JOIN `".AUTH_DATABASE."`.`user_access` AS b
ON b.`user_id` = a.`id`
AND b.`app_id` IN (".AUTH_APP_IDS_STRING.")
JOIN `group_members` AS c
ON a.`id` = c.`proxy_id`
AND c.`member_active` = 1
JOIN `groups` AS d
ON c.`group_id` = d.`group_id`
AND d.`group_active` = 1
WHERE b.`app_id` IN (".AUTH_APP_IDS_STRING.")
AND b.`organisation_id` = ".$db->qstr($ENTRADA_USER->getActiveOrganisation())."
AND b.`group` = 'student'
AND d.`group_id` = ".$db->qstr($query_year)."
GROUP BY a.`id`
ORDER BY `fullname` ASC";
$results = $db->GetAll($query);
if ($results) {
$counter = 0;
$total = count($results);
$split = (round($total / 2) + 1);
$student_classes = array();
$active_cohorts = groups_get_all_cohorts($ENTRADA_USER->getActiveOrganisation());
if (isset($active_cohorts) && !empty($active_cohorts)) {
foreach ($active_cohorts as $cohort) {
$student_classes[$cohort["group_id"]] = $cohort["group_name"];
}
}
echo "There are a total of <b>".$total."</b> student".(($total != "1") ? "s" : "")." in the <b>".checkslashes(trim($student_classes[$query_year]))."</b>. Please choose a student you wish to work with by clicking on their name, or if you wish to add an event to multiple students simply check the checkbox beside their name and click the "Add Mass Event" button.";
echo "<form id=\"clerkship_form\" action=\"".ENTRADA_URL."/admin/clerkship/electives?section=add_core\" method=\"post\">\n";
echo "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";
echo "<tr>\n";
echo " <td style=\"vertical-align: top\">\n";
echo " <ol start=\"1\">\n";
foreach ($results as $result) {
$elective_weeks = clerkship_get_elective_weeks($result["proxy_id"]);
$remaining_weeks = (int)$CLERKSHIP_REQUIRED_WEEKS - (int)$elective_weeks["approved"];
switch (htmlentities($_POST["qualifier"])) {
case "*":
default:
$show = true;
$weeksOutput = "";
$noResults = "No Results";
break;
case "deficient":
if ($remaining_weeks > 0) {
$show = true;
$weeksOutput = " <span class=\"content-small\">(".$remaining_weeks." weeks remaining)</span>";
} else {
$show = false;
}
$noResults = "There are no students in the class of <b>".checkslashes(trim($query_year))."</b> that do not have 14 weeks of electives approved in the system.";
break;
case "attained":
if ($remaining_weeks <= 0) {
$show = true;
$weeksOutput = "";
} else {
$show = false;
}
$noResults = "There are no students in the class of <b>".checkslashes(trim($query_year))."</b> that have 14 weeks of electives approved in the system.";
break;
}
if ($show) {
$counter++;
if ($counter == $split) {
echo " </ol>\n";
echo " </td>\n";
echo " <td style=\"vertical-align: top\">\n";
echo " <ol start=\"".$split."\">\n";
}
echo " <li><input type=\"checkbox\" name=\"ids[]\" value=\"".$result["proxy_id"]."\" /> <a href=\"".ENTRADA_URL."/admin/clerkship/clerk?ids=".$result["proxy_id"]."\" style=\"font-weight: bold\">".$result["fullname"]."</a>".$weeksOutput."</li>\n";
}
}
if ($counter == 0) {
echo " <li>".$noResults."</li>\n";
}
echo " </ol>\n";
echo " </td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo " <td colspan=\"3\" style=\"border-top: 1px #333333 dotted; padding-top: 5px\">\n";
echo " <ul type=\"none\">\n";
echo " <li><input type=\"checkbox\" name=\"selectall\" value=\"1\" onClick=\"selection(this.form['ids[]'])\" /> ";
echo " <input type=\"button\" value=\"Add Mass Elective\" class=\"btn\" onclick=\"$('clerkship_form').action = '".ENTRADA_URL."/admin/clerkship/electives?section=add_elective'; $('clerkship_form').submit();\"/>\n";
echo " <input type=\"button\" value=\"Add Mass Core\" class=\"btn\" style=\"display: inline; margin-left: 10px;\" onclick=\"$('clerkship_form').action = '".ENTRADA_URL."/admin/clerkship/electives?section=add_core'; $('clerkship_form').submit();\"/></li>\n";
echo " </ul>\n";
echo " </td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</form>\n";
} else {
$ERROR++;
$ERRORSTR[] = "Unable to find students in the database with a graduating year of <b>".trim($query_year)."</b>. It's possible that these students are not yet added to this system, so please check the User Management module.";
echo "<br />";
echo display_error($ERRORSTR);
}
} elseif (trim($_GET["name"]) != "" || trim($_POST["name"]) != "") {
if (trim($_POST["name"]) != "") {
$query_name = trim($_POST["name"]);
} else {
$query_name = trim($_GET["name"]);
}
$query = "SELECT `".AUTH_DATABASE."`.`user_data`.`id` AS `proxy_id`, CONCAT_WS(', ', `".AUTH_DATABASE."`.`user_data`.`lastname`, `".AUTH_DATABASE."`.`user_data`.`firstname`) AS `fullname`, `".AUTH_DATABASE."`.`user_access`.`role` AS `gradyear` FROM `".AUTH_DATABASE."`.`user_data` LEFT JOIN `".AUTH_DATABASE."`.`user_access` ON `".AUTH_DATABASE."`.`user_access`.`user_id`=`".AUTH_DATABASE."`.`user_data`.`id` WHERE `".AUTH_DATABASE."`.`user_access`.`app_id`='".AUTH_APP_ID."' AND CONCAT(`".AUTH_DATABASE."`.`user_data`.`firstname`, `".AUTH_DATABASE."`.`user_data`.`lastname`) LIKE '%".checkslashes(trim($query_name))."%' AND `group`='student' ORDER BY `".AUTH_DATABASE."`.`user_data`.`lastname`, `".AUTH_DATABASE."`.`user_data`.`firstname` ASC";
$results = $db->GetAll($query);
if ($results) {
$counter = 0;
$total = count($results);
$split = (round($total / 2) + 1);
echo "There are a total of <b>".$total."</b> student".(($total != "1") ? "s" : "")." that match the search term of <b>".checkslashes(trim($query_name), "display")."</b>. Please choose a student you wish to work with by clicking on their name, or if you wish to add an event to multiple students simply check the checkbox beside their name and click the "Add Mass Event" button.";
echo "<form id=\"clerkship_form\" action=\"".ENTRADA_URL."/admin/clerkship/electives?section=add_core\" method=\"post\">\n";
echo "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n";
echo "<tr>\n";
echo " <td style=\"vertical-align: top\">\n";
echo " <ol start=\"1\">\n";
foreach ($results as $result) {
$counter++;
if ($counter == $split) {
echo " </ol>\n";
echo " </td>\n";
echo " <td style=\"vertical-align: top\">\n";
echo " <ol start=\"".$split."\">\n";
}
echo " <li><input type=\"checkbox\" name=\"ids[]\" value=\"".$result["proxy_id"]."\" /> <a href=\"".ENTRADA_URL."/admin/clerkship/clerk?ids=".$result["proxy_id"]."\" style=\"font-weight: bold\">".$result["fullname"]."</a> <span class=\"content-small\">(Class of ".$result["gradyear"].")</span></li>\n";
}
echo " </ol>\n";
echo " </td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo " <td colspan=\"3\" style=\"border-top: 1px #333333 dotted; padding-top: 5px\">\n";
echo " <ul type=\"none\">\n";
echo " <li><input type=\"checkbox\" name=\"selectall\" value=\"1\" onClick=\"selection(this.form['ids[]'])\" /> ";
echo " <input type=\"button\" value=\"Add Mass Elective\" class=\"btn\" onclick=\"$('clerkship_form').action = '".ENTRADA_URL."/admin/clerkship/electives?section=add_elective'; $('clerkship_form').submit();\"/>\n";
echo " <input type=\"button\" value=\"Add Mass Core\" class=\"btn\" style=\"display: inline; margin-left: 10px;\" onclick=\"$('clerkship_form').action = '".ENTRADA_URL."/admin/clerkship/electives?section=add_core'; $('clerkship_form').submit();\"/></li>\n";
echo " </ul>\n";
echo " </td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</form>\n";
} else {
$ERROR++;
$ERRORSTR[] = "Unable to find any students in the database matching <b>".checkslashes(trim($query_name), "display")."</b>. It's possible that the student you're looking for is not yet added to this system, so please check the User Management module.";
echo "<br />";
echo display_error($ERRORSTR);
}
} else {
$ERROR++;
$ERRORSTR[] = "You must search either by graduating year or by students name at this time, please try again.";
echo "<br />";
echo display_error($ERRORSTR);
}
break;
default :
?>
<div class="tab-page">
<h3 class="tab">Student Search</h3>
<span class="content-subheading">Graduating Year</span>
<form action="<?php echo ENTRADA_URL; ?>/admin/clerkship" method="post">
<input type="hidden" name="action" value="results" />
<div class="control-group">
<label class="control-label">Select an elective qualifier:</label>
<div class="controls">
<select name="qualifier" style="width: 205px">
<option value="*">All</option>
<option value="deficient">Deficient</option>
<option value="attained">Attained</option>
</select>
</div>
</div>
<?php
$student_classes = array();
$active_cohorts = groups_get_all_cohorts($ENTRADA_USER->getActiveOrganisation());
if (isset($active_cohorts) && !empty($active_cohorts)) {
foreach ($active_cohorts as $cohort) {
$student_classes[$cohort["group_id"]] = $cohort["group_name"];
}
}
?>
<div class="control-group">
<label class="control-label">Select the graduating year you wish to view students in:</label>
<div class="controls">
<select name="year" style="width: 205px">
<option value="">-- Select Graduating Year --</option>
<?php
if (isset($student_classes) && !empty($student_classes)) {
foreach ($student_classes as $group_id => $class) {
echo "<option value=\"".$group_id."\">Class of ".html_encode($class)."</option>\n";
}
}
?>
</select>
</div>
</div>
<input type="submit" value="Proceed" class="btn btn-primary"/>
<hr/>
</form>
<form action="<?php echo ENTRADA_URL; ?>/admin/clerkship" method="post">
<input type="hidden" name="action" value="results" />
<span class="content-subheading">Student Finder</span>
<div class="control-group">
<label class="control-label">Enter the first or lastname of the student:</label>
<div class="controls">
<input type="text" name="name" value="" style="margin-bottom:0"/>
</div>
</div>
<input type="submit" value="Search" class="btn btn-primary" />
</form>
</div>
<?php
break;
}
$query = "SELECT a.*, CONCAT_WS(' ', b.`firstname`, b.`lastname`) as `fullname`, c.`rotation_title`
FROM `".CLERKSHIP_DATABASE."`.`logbook_overdue` AS a
LEFT JOIN `".AUTH_DATABASE."`.`user_data` AS b
ON a.`proxy_id` = b.`id`
LEFT JOIN `".CLERKSHIP_DATABASE."`.`global_lu_rotations` AS c
ON a.`rotation_id` = c.`rotation_id`
ORDER BY `logged_completed` DESC, `fullname` ASC";
$results = $db->GetAll($query);
if ($results && (!isset($_POST["action"]) || $_POST["action"] != "results")) {
?>
<div class="tab-page">
<h3 class="tab">Clerks with overdue logging</h3>
<br />
<table class="tableList" cellspacing="0" summary="List of Clerkship Rotations">
<colgroup>
<col class="modified" />
<col class="date-small" />
<col class="title" />
<col class="date-small" />
<col class="date-small" />
</colgroup>
<thead>
<tr>
<td class="modified"> </td>
<td class="date-small">Student</td>
<td class="title">Rotation</td>
<td class="date-small">Logged Objectives</td>
<td class="date-small">Required Objectives</td>
</tr>
</thead>
<tbody>
<?php
foreach ($results as $result) {
$click_url = ENTRADA_URL."/admin/clerkship?section=clerk&ids=".$result["proxy_id"];
echo "<tr>\n";
echo " <td class=\"modified\"> </td>\n";
echo " <td class=\"date-small\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".$result["fullname"]."</a></td>\n";
echo " <td class=\"title\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".$result["rotation_title"]."</a></td>\n";
echo " <td class=\"date-small\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".$result["logged_completed"]."</a></td>\n";
echo " <td class=\"date-small\"><a href=\"".$click_url."\" style=\"font-size: 11px\">".$result["logged_required"]."</a></td>\n";
echo "</tr>\n";
}
?>
</tbody>
</table>
<br /><br />
</div>
<?php
}
if (!isset($_POST["action"]) || $_POST["action"] != "results") {
?>
</div>
<?php
}
} else {
// Display the errors.
echo display_error($ERRORSTR);
}
}
?> | gpl-3.0 |
codeguy007/CameraControl | CameraControl/CameraControl_DevSrc-2013-07-24/CameraControl_Proshots/nikon-camera-control/PortableDeviceLib/TreeNode.cs | 3221 | #region License
/*
TreeNode.cs
Copyright (C) 2009 Vincent Lainé
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PortableDeviceLib
{
public class TreeNode<T> : IEnumerable<TreeNode<T>>, ITreeNode
{
private List<TreeNode<T>> childs;
public TreeNode(TreeNode<T> parent)
{
this.childs = new List<TreeNode<T>>();
this.Parent = parent;
}
public TreeNode(TreeNode<T> parent, T value)
: this(parent)
{
this.Value = value;
}
public TreeNode<T> Parent
{
get;
private set;
}
public TreeNode<T> this[int index]
{
get
{
return this.childs[index];
}
}
public IEnumerable<TreeNode<T>> Childs
{
get
{
return this.childs;
}
}
public int Count
{
get
{
return this.childs.Count;
}
}
public T Value
{
get;
set;
}
public TreeNode<T> AddChild(T value)
{
TreeNode<T> child = new TreeNode<T>(this, value);
this.AddChild(child);
return child;
}
public void AddChild(TreeNode<T> child)
{
if (child == null)
throw new ArgumentNullException("child");
this.childs.Add(child);
}
public void RemoveChild(TreeNode<T> child)
{
if (child == null)
throw new ArgumentNullException("child");
this.childs.Remove(child);
}
public TreeNode<T> RemoveChild(int index)
{
if (index < 0 || index >= this.childs.Count)
throw new ArgumentOutOfRangeException("index");
TreeNode<T> child = this.childs[index];
this.childs.RemoveAt(index);
return child;
}
#region IEnumerable<TreeNode<T>> Members
public IEnumerator<TreeNode<T>> GetEnumerator()
{
return this.childs.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.childs.GetEnumerator();
}
#endregion
}
}
| gpl-3.0 |
DavidBreuer/CytoSeg | tests/test.py | 1464 | ################################################################################
# Module: test.py
# Description: Test imports and network extraction
# License: GPL3, see full license in LICENSE.txt
# Web: https://github.com/DavidBreuer/CytoSeg
################################################################################
#%%############################################################################# test imports
def test_imports():
import itertools
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import os
import pandas as pd
import random
import scipy as sp
import scipy.misc
import scipy.ndimage
import scipy.optimize
import scipy.spatial
import scipy.stats
import scipy.cluster
import skimage
import skimage.filters
import skimage.io
import skimage.morphology
import skimage.feature
import skimage.segmentation
import shapely
import shapely.geometry
import sys
import xml
import xml.dom
import xml.dom.minidom
return None
#%%############################################################################# test read tiff
def test_read_tiff():
import skimage
import skimage.io
im=skimage.io.imread('../examples/data/',plugin='tifffile')
return None
#%%############################################################################# under construction
| gpl-3.0 |
projectestac/alexandria | html/langpacks/eu/block_badges.php | 1441 | <?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Strings for component 'block_badges', language 'eu', version '3.11'.
*
* @package block_badges
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['badges:addinstance'] = 'Gehitu Azken dominak bloke berri bat';
$string['badges:myaddinstance'] = 'Gehitu Azken dominak bloke berri bat Aginte-panelean';
$string['nothingtodisplay'] = 'Ez duzu erakusteko dominarik';
$string['numbadgestodisplay'] = 'Erakusteko azken dominen kopurua';
$string['pluginname'] = 'Azken dominak';
$string['privacy:metadata'] = 'Azken dominak blokeak soilik beste kokapenetan gordetako datuak erakusten ditu.';
| gpl-3.0 |
iDigBio/Biospex | app/Services/Process/PanoptesTranscriptionProcess.php | 6828 | <?php
/*
* Copyright (C) 2015 Biospex
* biospex@gmail.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 <https://www.gnu.org/licenses/>.
*/
namespace App\Services\Process;
use App\Services\Model\SubjectService;
use App\Services\Model\PanoptesTranscriptionService;
use Exception;
use Storage;
use Str;
use Validator;
use App\Services\Csv\Csv;
/**
* Class PanoptesTranscriptionProcess
*
* @package App\Services\Process
*/
class PanoptesTranscriptionProcess
{
/**
* @var mixed
*/
protected $collection;
/**
* @var SubjectService
*/
protected $subjectService;
/**
* @var \App\Services\Model\PanoptesTranscriptionService
*/
protected $panoptesTranscriptionService;
/**
* @var \App\Services\Process\TranscriptionLocationProcess
*/
protected $transcriptionLocationProcess;
/**
* @var array
*/
protected $csvError = [];
/**
* @var null
*/
public $csvFile = null;
/**
* @var \App\Services\Csv\Csv
*/
protected $csv;
/**
* @var \Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed
*/
protected $nfnMisMatched;
/**
* PanoptesTranscriptionProcess constructor.
*
* @param SubjectService $subjectService
* @param \App\Services\Model\PanoptesTranscriptionService $panoptesTranscriptionService
* @param \App\Services\Process\TranscriptionLocationProcess $transcriptionLocationProcess
* @param \App\Services\Csv\Csv $csv
*/
public function __construct(
SubjectService $subjectService,
PanoptesTranscriptionService $panoptesTranscriptionService,
TranscriptionLocationProcess $transcriptionLocationProcess,
Csv $csv
) {
$this->subjectService = $subjectService;
$this->panoptesTranscriptionService = $panoptesTranscriptionService;
$this->transcriptionLocationProcess = $transcriptionLocationProcess;
$this->csv = $csv;
// TODO can be removed after fixing Charles issue
$this->nfnMisMatched = config('config.nfnMisMatched');
}
/**
* Process csv file.
*
* @param $file
* @param $expeditionId
*/
public function process($file, $expeditionId)
{
try {
$this->csv->readerCreateFromPath($file);
$this->csv->setDelimiter();
$this->csv->setEnclosure();
$this->csv->setEscape('"');
$this->csv->setHeaderOffset();
$header = $this->prepareHeader($this->csv->getHeader());
$rows = $this->csv->getRecords($header);
foreach ($rows as $offset => $row) {
$this->processRow($header, $row, $expeditionId);
}
return;
} catch (Exception $e) {
$this->csvError[] = ['error' => $file . ': ' . $e->getMessage() . ', Line: ' . $e->getLine()];
return;
}
}
/**
* Prepare header
* Replace created_at column with create_date to avoid DB issues.
*
* @param $header
* @return array
*/
protected function prepareHeader($header)
{
return array_replace($header, array_fill_keys(array_keys($header, 'created_at'), 'create_date'));
}
/**
* Process an individual row
*
* @param $header
* @param $row
* @param $expeditionId
*/
public function processRow($header, $row, $expeditionId)
{
if (count($header) !== count($row))
{
$message = t('Header column count does not match row count. :headers headers / :rows rows', [
':headers' => count($header),
':rows' => count($row)
]);
$this->csvError[] = ['error' => $message];
return;
}
if ($this->validateTranscription($row['classification_id'])) {
return;
}
/*
* @TODO This can be removed once Charles expedition has processed
*/
$this->fixMisMatched($row, $expeditionId);
if (trim($row['subject_subjectId'] === null)) {
$this->csvError[] = array_merge(['error' => 'Transcript missing subject id'], $row);
return;
}
$subject = $this->subjectService->find(trim($row['subject_subjectId']));
if ($subject === null) {
$this->csvError[] = array_merge(['error' => 'Could not find subject id for classification'], $row);
return;
}
$this->transcriptionLocationProcess->buildTranscriptionLocation($row, $subject, $expeditionId);
$row = array_merge($row, ['subject_projectId' => $subject->project_id]);
$this->panoptesTranscriptionService->create($row);
}
/**
* Validate transcription to prevent duplicates.
*
* @param $classification_id
* @return mixed
*/
public function validateTranscription($classification_id)
{
$rules = ['classification_id' => 'unique:mongodb.panoptes_transcriptions,classification_id'];
$values = ['classification_id' => (int) $classification_id];
$validator = Validator::make($values, $rules);
$validator->getPresenceVerifier()->setConnection('mongodb');
// returns true if record exists.
return $validator->fails();
}
/**
* Fix mismatched column names.
*
* @TODO This can be removed once Charles expedition has processed
* @param $row
* @param $expeditionId
*/
private function fixMisMatched(&$row, $expeditionId)
{
foreach ($this->nfnMisMatched as $key => $value) {
if (isset($row[$key])) {
$row[$value] = $row[$key];
}
}
if (!isset($row['subject_expeditionId'])) {
$row['subject_expeditionId'] = $expeditionId;
}
}
/**
* Check errors.
*
* @return string|null
* @throws \League\Csv\CannotInsertRecord
*/
public function checkCsvError(): ?string
{
if (count($this->csvError) === 0) {
return null;
}
$csvName = Str::random().'.csv';
return $this->csv->createReportCsv($this->csvError, $csvName);
}
} | gpl-3.0 |
Kithio/Thallus | src/main/java/com/kithio/thallus/reference/GUIs.java | 69 | package com.kithio.thallus.reference;
public enum GUIs
{
TEST
}
| gpl-3.0 |
blktechies/pCeep | app/views/__init__.py | 96 | from form import CommentForm, PostForm, ProfileForm, MessageForm, WelcomeForm
import main, post | gpl-3.0 |
TIY-Durham/TIY-Contacts | api/test/models/email_address_test.rb | 126 | require 'test_helper'
class EmailAddressTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| gpl-3.0 |
weloxux/Overchan-Android | src/nya/miku/wishmaster/chans/chan420/Chan420Module.java | 9034 | /*
* Overchan Android (Meta Imageboard Client)
* Copyright (C) 2014-2015 miku-nyan <https://github.com/miku-nyan>
*
* 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 nya.miku.wishmaster.chans.chan420;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceGroup;
import android.support.v4.content.res.ResourcesCompat;
import nya.miku.wishmaster.R;
import nya.miku.wishmaster.api.interfaces.CancellableTask;
import nya.miku.wishmaster.api.interfaces.ProgressListener;
import nya.miku.wishmaster.api.models.BoardModel;
import nya.miku.wishmaster.api.models.PostModel;
import nya.miku.wishmaster.api.models.SimpleBoardModel;
import nya.miku.wishmaster.api.models.ThreadModel;
import nya.miku.wishmaster.api.models.UrlPageModel;
import nya.miku.wishmaster.api.util.ChanModels;
import nya.miku.wishmaster.api.util.WakabaUtils;
import nya.miku.wishmaster.chans.AbstractChanModule;
import nya.miku.wishmaster.http.streamer.HttpRequestModel;
import nya.miku.wishmaster.http.streamer.HttpStreamer;
import nya.miku.wishmaster.lib.org_json.JSONArray;
import nya.miku.wishmaster.lib.org_json.JSONObject;
public class Chan420Module extends AbstractChanModule {
static final String CHAN_NAME = "420chan.org";
private Map<String, BoardModel> boardsMap = null;
public Chan420Module(SharedPreferences preferences, Resources resources) {
super(preferences, resources);
}
@Override
public String getChanName() {
return CHAN_NAME;
}
@Override
public String getDisplayingName() {
return "420chan";
}
@Override
public Drawable getChanFavicon() {
return ResourcesCompat.getDrawable(resources, R.drawable.favicon_420chan, null);
}
private JSONObject downloadJSONObject(String url, boolean checkIfModidied, ProgressListener listener, CancellableTask task) throws Exception {
HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModidied).build();
JSONObject object = HttpStreamer.getInstance().getJSONObjectFromUrl(url, rqModel, httpClient, listener, task, false);
if (task != null && task.isCancelled()) throw new Exception("interrupted");
if (listener != null) listener.setIndeterminate();
return object;
}
private JSONArray downloadJSONArray(String url, boolean checkIfModidied, ProgressListener listener, CancellableTask task) throws Exception {
HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModidied).build();
JSONArray array = HttpStreamer.getInstance().getJSONArrayFromUrl(url, rqModel, httpClient, listener, task, false);
if (task != null && task.isCancelled()) throw new Exception("interrupted");
if (listener != null) listener.setIndeterminate();
return array;
}
private boolean useHttps() {
return false;
}
@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
addProxyPreferences(preferenceGroup);
}
@Override
public SimpleBoardModel[] getBoardsList(ProgressListener listener, CancellableTask task, SimpleBoardModel[] oldBoardsList) throws Exception {
String catsUrl = (useHttps() ? "https://" : "http://") + "api.420chan.org/categories.json";
String boardsUrl = (useHttps() ? "https://" : "http://") + "api.420chan.org/boards.json";
JSONObject catsJson = downloadJSONObject(catsUrl, (oldBoardsList != null && boardsMap != null), listener, task);
JSONObject boardsJson = downloadJSONObject(boardsUrl, (oldBoardsList != null && boardsMap != null), listener, task);
if (catsJson == null && boardsJson == null) return oldBoardsList;
if (catsJson == null) catsJson = downloadJSONObject(catsUrl, (oldBoardsList != null && boardsMap != null), listener, task);
if (boardsJson == null) boardsJson = downloadJSONObject(boardsUrl, (oldBoardsList != null && boardsMap != null), listener, task);
List<SimpleBoardModel> list = Chan420JsonMapper.mapBoards(catsJson, boardsJson);
Map<String, BoardModel> newMap = new HashMap<String, BoardModel>();
for (SimpleBoardModel board : list) {
BoardModel model = Chan420JsonMapper.getDefaultBoardModel(board.boardName);
model.boardDescription = board.boardDescription;
model.boardCategory = board.boardCategory;
model.nsfw = board.nsfw;
newMap.put(model.boardName, model);
}
boardsMap = newMap;
return list.toArray(new SimpleBoardModel[list.size()]);
}
@Override
public BoardModel getBoard(String shortName, ProgressListener listener, CancellableTask task) throws Exception {
if (boardsMap == null) {
try {
getBoardsList(listener, task, null);
} catch (Exception e) {}
}
if (boardsMap != null && boardsMap.containsKey(shortName)) return boardsMap.get(shortName);
return Chan420JsonMapper.getDefaultBoardModel(shortName);
}
@Override
public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList)
throws Exception {
String url = (useHttps() ? "https://" : "http://") + "api.420chan.org/" + boardName + "/catalog.json";
JSONArray response = downloadJSONArray(url, oldList != null, listener, task);
if (response == null) return oldList; //if not modified
List<ThreadModel> threads = new ArrayList<>();
for (int i=0, len=response.length(); i<len; ++i) {
JSONArray curArray = response.getJSONObject(i).getJSONArray("threads");
for (int j=0, clen=curArray.length(); j<clen; ++j) {
JSONObject curThreadJson = curArray.getJSONObject(j);
ThreadModel curThread = new ThreadModel();
curThread.threadNumber = Long.toString(curThreadJson.getLong("no"));
curThread.postsCount = curThreadJson.optInt("replies", -2) + 1;
curThread.attachmentsCount = curThreadJson.optInt("images", -2) + 1;
curThread.isSticky = curThreadJson.optInt("sticky") == 1;
curThread.isClosed = curThreadJson.optInt("closed") == 1;
curThread.posts = new PostModel[] { Chan420JsonMapper.mapPostModel(curThreadJson, boardName) };
threads.add(curThread);
}
}
return threads.toArray(new ThreadModel[threads.size()]);
}
@Override
public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList)
throws Exception {
String url = (useHttps() ? "https://" : "http://") + "api.420chan.org/" + boardName + "/res/" + threadNumber + ".json";
JSONObject response = downloadJSONObject(url, oldList != null, listener, task);
if (response == null) return oldList; //if not modified
JSONArray posts = response.getJSONArray("posts");
PostModel[] result = new PostModel[posts.length()];
for (int i=0, len=posts.length(); i<len; ++i) {
result[i] = Chan420JsonMapper.mapPostModel(posts.getJSONObject(i), boardName);
}
if (oldList != null) {
result = ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(result));
}
return result;
}
@Override
public String buildUrl(UrlPageModel model) throws IllegalArgumentException {
if (!model.chanName.equals(getChanName())) throw new IllegalArgumentException("wrong chan");
String usingUrl = (useHttps() ? "https://" : "http://") + (model.type == UrlPageModel.TYPE_INDEXPAGE ? "" : "boards.") + "420chan.org/";
return WakabaUtils.buildUrl(model, usingUrl).replace(".html", ".php");
}
@Override
public UrlPageModel parseUrl(String url) throws IllegalArgumentException {
return WakabaUtils.parseUrl(url.replace("boards.420chan.org", "420chan.org").replace(".php", ".html"), getChanName(), "420chan.org");
}
}
| gpl-3.0 |
KULeuven-KRR/IDP | src/theory/transformations/RewriteIntoPatterns.hpp | 6650 | /****************************************************************
* Copyright 2010-2012 Katholieke Universiteit Leuven
*
* Use of this software is governed by the GNU LGPLv3.0 license
*
* Written by Broes De Cat, Stef De Pooter, Johan Wittocx
* and Bart Bogaerts, K.U.Leuven, Departement Computerwetenschappen,
* Celestijnenlaan 200A, B-3001 Leuven, Belgium
****************************************************************/
#pragma once
#include "IncludeComponents.hpp"
#include "visitors/TheoryMutatingVisitor.hpp"
class AbstractStructure;
class Vocabulary;
class Formula;
class Variable;
class Sort;
class Term;
/**
* Algoritme:
* geef lijst van patronen en predform
* kies een patroon
* patroon bepaalt welke acties er op het predform gedaan moeten worden:
* welke termen unnesten (dit mogen dieper geneste termen zijn)
* graphen van het geheel
* negatie van het geheel
* swap van termen
* voer die acties uit en recursief op elke gegenereerde predform
*/
class Pattern {
public:
virtual ~Pattern();
virtual bool isAllowed(PredForm* pf) const = 0;
};
// Default: always allowed to unnest until only variables left (or equality with one var and one domelem).
class DefaultAtom: public Pattern {
public:
virtual bool isAllowed(PredForm* pf) const {
int count = 0;
for (auto t : pf->subterms()) {
if (t->type() != TermType::VAR) {
if (t->type() == TermType::DOM) {
count++;
if (count > 1) {
return false;
}
} else {
return false;
}
}
}
if (count == 1) {
return is(pf->symbol(), STDPRED::EQ);
}
return true;
}
};
class DVAtom: public Pattern {
public:
virtual bool isAllowed(PredForm* pf) const {
for (auto t : pf->subterms()) {
if (t->type() != TermType::DOM && t->type() != TermType::VAR) {
return false;
}
}
return true;
}
};
class RewriteIntoPatterns: public TheoryMutatingVisitor {
VISITORFRIENDS()
private:
bool _rewritetootherformula, _done;
std::vector<Formula*> _addedformula;
std::vector<Pattern*> _patterns;
bool _saved;
std::pair<Variable*, PredForm*> _savedrewriting;
Vocabulary* _vocabulary;
AbstractStructure* _structure;
public:
Formula* execute(Formula* f, const std::vector<Pattern*>& patterns, AbstractStructure* structure) {
_structure = structure;
_vocabulary = structure->vocabulary();
_patterns = patterns;
_done = false;
_saved = false;
while (not _done) {
_done = true;
f = f->accept(this);
}
return f;
}
protected:
// TODO handle other occurrences of atoms (aggform, eqchainform, ...)
// TODO use the rule approach for sets!
virtual Formula* visit(PredForm* pf) {
Term* proposal = NULL;
for (auto p : _patterns) { // TODO in a first analysis, decide which pattern we want to work towards!
proposal = p->isAllowed(pf);
if (proposal==NULL) {
return pf;
}
}
return rewrite(pf, proposal);
}
virtual Rule* visit(Rule* r) {
_rewritetootherformula = true;
r->head(dynamic_cast<PredForm*>(r->head()->accept(this)));
if(_saved){
r->addvar(_savedrewriting.first);
r->body(new BoolForm(SIGN::POS, true, _savedrewriting.second, r->body(), FormulaParseInfo()));
_saved = false;
}
_rewritetootherformula = false;
r->body(r->body()->accept(this));
return r;
}
Formula* rewrite(PredForm* pf, Term* proposal) {
_done = false;
int index = -1;
Sort* sort = NULL;
if (is(pf->symbol(), STDPRED::EQ)) {
if(not isVar(pf->subterms()[1]) && isVar(pf->subterms()[0])){
auto temp = pf->subterms()[1];
pf->subterm(1, pf->subterms()[0]);
pf->subterm(0, temp);
}
if(not isVar(pf->subterms()[0])){
index = 0;
// chosensort is smallest of both sorts if they are subterms
auto leftsort = pf->subterms()[0]->sort();
auto rightsort = pf->subterms()[1]->sort();
if (SortUtils::isSubsort(leftsort, rightsort)) {
sort = leftsort;
} else {
sort = rightsort;
}
}else{
return makeFuncGraph(pf->sign(), pf->subterms()[1], pf->subterms()[0], pf->pi());
}
}else{
for(uint i=0; i<pf->subterms().size(); ++i){
if(not isVar(pf->subterms()[i]) && not isDom(pf->subterms()[i])){
index = i;
break;
}
}
}
Assert(index>=0);
auto term = pf->subterms()[index];
std::pair<Variable*, PredForm*> vp = move(term, sort);
pf->subterm(index, new VarTerm(vp.first, TermParseInfo()));
auto formula = vp.second;
if(_rewritetootherformula){
_saved = true;
_savedrewriting = vp;
}else{
formula = new BoolForm(SIGN::POS, true, {formula, pf}, pf->pi());
formula = new QuantForm(SIGN::POS, QUANT::EXIST, {vp.first}, formula, pf->pi()); // TODO sign?
}
return formula;
}
bool isAgg(Term* t) const {
return t->type() == TermType::AGG;
}
bool isFunc(Term* t) const {
return t->type() == TermType::FUNC;
}
bool isDom(Term* t) const {
return t->type() == TermType::DOM;
}
bool isVar(Term* t) const {
return t->type() == TermType::VAR;
}
/**
* Given functerm = dom/varterm, construct graph
*/
PredForm* makeFuncGraph(SIGN sign, Term* functerm, Term* varterm, const FormulaParseInfo& pi) const {
Assert(isVar(varterm));
if(isAgg(functerm)){
auto aggterm = dynamic_cast<AggTerm*>(functerm);
return new AggForm(sign, varterm, CompType::EQ, aggterm, pi);
}else{
Assert(isFunc(functerm));
auto ft = dynamic_cast<FuncTerm*>(functerm);
auto args = ft->subterms();
args.push_back(varterm);
return new PredForm(sign, ft->function(), args, pi);
}
}
/**
* Given a term t
* Add a quantified variable v over sort(t)
* Add an equality t =_sort(t) v
* return v
*/
std::pair<Variable*, PredForm*> move(Term* origterm, Sort* chosensort) {
Assert(origterm->sort()!=NULL);
auto newsort = deriveSort(origterm, chosensort);
Assert(newsort != NULL);
auto var = new Variable(newsort);
if (getOption(IntType::VERBOSE_TRANSFORMATIONS) > 1) {
Warning::introducedvar(var->name(), var->sort()->name(), toString(origterm));
}
auto varterm = new VarTerm(var, TermParseInfo(origterm->pi()));
auto equalatom = new PredForm(SIGN::POS, get(STDPRED::EQ, origterm->sort()), { varterm, origterm }, FormulaParseInfo());
for(auto sort: equalatom->symbol()->sorts()){
Assert(sort!=NULL);
}
return {var, equalatom};
}
/**
* Tries to derive a sort for the term given a structure.
*/
Sort* deriveSort(Term* term, Sort* chosensort) {
auto sort = (chosensort != NULL) ? chosensort : term->sort();
if (_structure != NULL && SortUtils::isSubsort(term->sort(), get(STDSORT::INTSORT), _vocabulary)) {
sort = TermUtils::deriveSmallerSort(term, _structure);
}
return sort;
}
};
| gpl-3.0 |
m0sk1t/react_email_editor | src/components/BlockList.js | 3057 | import React from 'react';
import Block from './Block';
import { connect } from 'react-redux';
import { rmBlock, addBlock, swapBlocks, setVisible, selectBlock } from '../actions';
const mapStateToProps = (state) => {
return {
common: state.common,
template: state.template,
components: state.components,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onRm: (id) => {
dispatch(rmBlock(id));
},
onAdd: (block, index) => {
dispatch(addBlock(block, index));
},
onDrop: (id, index) => {
dispatch(swapBlocks(id, index));
},
selectBlock: (id) => {
dispatch(selectBlock(id));
dispatch(setVisible('options'));
}
};
};
const BlockList = connect(
mapStateToProps,
mapDispatchToProps
)(({ common, template, components, onAdd, onDrop, selectBlock }) => {
let blockDragged = null;
return (
<div
id="rootTable"
style={{
'height': '100%',
'display': 'flex',
'overflowY': 'auto',
'paddingLeft': '25%',
'justifyContent': 'center',
}}
>
<table style={{backgroundColor: common.bgcolor}} width="100%">
<tbody>
<tr>
<td
style={{
'display': 'flex',
'justifyContent': 'center',
}}
>
<table id="rootTemplate"
width="570"
cellPadding="0"
cellSpacing="0"
role="presentation"
style={{
'width':'570px',
}}
>
<tbody>
{template.map((block, index) =>
<tr
id={`id_${block.id}`}
key={block.id}
draggable="true"
style={{
'boxShadow': block.selected?'#4CAF50 0px 0px 3px 7px':''
}}
onClick={(e) => {e.stopPropagation(); selectBlock(block.id);}}
onDragOver={ev => {
ev.preventDefault();
Array.prototype.forEach.call(document.querySelectorAll('.ree_single_block'), (el) => {
el.classList.remove('block__hovered');
});
ev.target.closest('.ree_single_block').classList.add('block__hovered');
}
}
onDragStart={() => blockDragged = block.id}
onDrop={() => {
Array.prototype.forEach.call(document.querySelectorAll('.ree_single_block'), (el) => {
el.classList.remove('block__hovered');
});
if (blockDragged) {
onDrop(blockDragged, index);
} else {
let newBlock = components.filter(el => el.selected)[0].block;
newBlock.options.container = Object.assign({}, newBlock.options.container, common);
onAdd(newBlock, index);
}
}
}
>
<td
width="570"
className="ree_single_block"
style={block.options.container}
>
<Block
block={block}
/>
</td>
</tr>
)}
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
);
});
export default BlockList;
| gpl-3.0 |
xpclove/autofp | diffpy/pyfullprof/irfreader.py | 5279 | #!/usr/bin/env python
##############################################################################
#
# diffpy.pyfullprof by DANSE Diffraction group
# Simon J. L. Billinge
# (c) 2010 Trustees of the Columbia University
# in the City of New York. All rights reserved.
#
# File coded by: Wenduo Zhou
#
# See AUTHORS.txt for a list of people who contributed.
# See LICENSE.txt for license information.
#
##############################################################################
__id__ = "$Id: irfreader.py 6843 2013-01-09 22:14:20Z juhas $"
"""
Irf File Reader
Example:
1. IrfReader:
IrfReader()
IrfReader.importIrf()
IrfReader.setFit()
"""
class IrfReader:
"""
Class to import Irf
"""
def __init__(self):
"""
Initialization
"""
self._bankinfodict = {}
self._lines = None
self._infodict = {}
return
def importIrf(self, irffname):
"""
Import Irf File name
Arguement:
- irffname : str
Return : None
"""
# 1. Import all lines
irffile = open(irffname, "r")
rawlines = irffile.readlines()
irffile.close()
# 2. Import non-information information line
self._lines = []
for line in rawlines:
cline = line.strip()
if cline != "":
self._lines.append(cline)
return
class TOFIrfReader(IrfReader):
"""
Class to import TOF Irf file
"""
def __init__(self):
"""
Initialization
"""
IrfReader.__init__(self)
return
def importIrf(self, irffname):
"""
Import TOF Irf File name
Arguement:
- irffname : str
Return : None
"""
IrfReader.importIrf(self, irffname)
# 1. determine number of banks
numbank = 0
banklinedict = {}
lineindex = 0
for line in self._lines:
if line[0] == "!" and line.count("Bank") == 1:
numbank += 1
bankno = int(line.split("Bank")[1])
if bankno != numbank:
errmsg = "Irf File Bank Number Error"
print errmsg
banklinedict[numbank] = lineindex
lineindex += 1
# LOOP-OVER for line in self._lines
# 2. import value to dictionary
for bankno in xrange(1, numbank+1):
self._infodict[bankno] = {}
# 2.1 get data lines
datalines = []
lineno = banklinedict[bankno]+1
for l in xrange(13):
if self._lines[lineno][0] != "!":
datalines.append(self._lines[lineno])
lineno += 1
# 2.2 Parse Line 1
self._infodict[bankno]["Pattern"] = {}
getFloats(self._infodict[bankno]["Pattern"], datalines[0], ["Thmin", "Step", "Thmax"], 1)
getFloats(self._infodict[bankno]["Pattern"], datalines[1], ["Dtt1" , "Dtt2", "Zero" ], 1)
getFloats(self._infodict[bankno]["Pattern"], datalines[2], ["TwoSinTh"], 1)
self._infodict[bankno]["PeakProfile"] = {}
getFloats(self._infodict[bankno]["PeakProfile"], datalines[3], ["Sig2", "Sig1", "Sig0"], 1)
getFloats(self._infodict[bankno]["PeakProfile"], datalines[4], ["Gam2", "Gam1", "Gam0"], 1)
self._infodict[bankno]["ExpDecay"] = {}
getFloats(self._infodict[bankno]["ExpDecay"], datalines[5], ["ALPH0", "BETA0", "ALPH1", "BETA1"], 1)
# LOOP-OVER for bankno in xrange(1, numbank+1):
return
def setFit(self, theFit):
"""
Set the content in infodict (from Irf) to a Fit instance
Argument:
- theFit : Fit instance
Return : None
"""
for pattern in theFit.get("Pattern"):
# 1. Get data dictionary
infodict = self._infodict[pattern.get("Bank")]
# 2. Pattern setup
for parname in infodict["Pattern"].keys():
pattern.set(parname, infodict["Pattern"][parname])
# 3. Profile and ExpDecay
for phase in theFit.get("Phase"):
contribution = theFit.getContribution(pattern, phase)
peakprofile = contribution.get("Profile")
expdecay = contribution.get("ExpDecayFunction")
for parname in infodict["PeakProfile"].keys():
peakprofile.set(parname, infodict["PeakProfile"][parname])
for parname in infodict["ExpDecay"].keys():
expdecay.set(parname, infodict["ExpDecay"][parname])
# LOOP-OVER for pattern in theFit.get("Pattern"):
# END-DEFINITION CLASS
def getFloats(datadict, line, keylist, startpos):
"""
Interpret a line to put value (float) to a dictionary
Argument:
- datadict : dict
- line : str
- keylist : list
- startpos : int
Return : None
"""
terms = line.split()
index = startpos
for key in keylist:
datadict[key] = float(terms[index])
index += 1
return
| gpl-3.0 |
greenriver/hmis-warehouse | db/warehouse/migrate/20210223011452_index_income_fields.rb | 314 | class IndexIncomeFields < ActiveRecord::Migration[5.2]
def change
add_index :IncomeBenefits, :InformationDate
add_index :IncomeBenefits, [:Earned, :DataCollectionStage], name: 'idx_earned_stage'
add_index :IncomeBenefits, [:IncomeFromAnySource, :DataCollectionStage], name: 'idx_any_stage'
end
end
| gpl-3.0 |
RushuiGuan/mvvm | Albatross.MVVM/Views/Converters/NullVisibilityConverter.cs | 1258 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace Albatross.MVVM.Views {
/// <summary>
/// Return the visibility based on if the item is null or not
/// </summary>
public class NullVisibilityConverter : IValueConverter {
public NullVisibilityConverter() {
_collapseOrHidden = Visibility.Collapsed;
}
public const string CollapseOrHiddenPropertyName = "CollapseOrHidden";
private Visibility _collapseOrHidden;
public Visibility CollapseOrHidden {
get { return _collapseOrHidden; }
set {
if (value == Visibility.Visible) {
throw new ArgumentException();
}
_collapseOrHidden = value;
}
}
public bool Reversed {
get;
set;
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value != null) {
return Reversed ? CollapseOrHidden : Visibility.Visible;
} else {
return Reversed ? Visibility.Visible : CollapseOrHidden;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotSupportedException();
}
}
}
| gpl-3.0 |
shakshin/oradev | Config.cs | 4617 | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
namespace oradev
{
[Serializable]
[XmlRootAttribute("OracleDeveloperConfiguation")]
public class Config
{
[NonSerialized]
private string _dbalias;
public string DataBaseAlias
{
get { return _dbalias; }
set { _dbalias = value; }
}
[NonSerialized]
private string _dbuser;
public string DataBaseUser
{
get { return _dbuser; }
set { _dbuser = value; }
}
[NonSerialized]
private string _dbpassword;
public string DataBasePassword
{
get { return _dbpassword; }
set { _dbpassword = value; }
}
[NonSerialized]
private string _fenc = Encoding.GetEncoding(866).WebName;
public string FileEncoding
{
get { return _fenc; }
set { _fenc = value; }
}
[NonSerialized]
private Boolean _save_on_compile;
public Boolean SaveOnCompile
{
get { return _save_on_compile; }
set { _save_on_compile = value; }
}
private Boolean useObjectCache;
private Int16 cacheExpirePeriod;
public ObservableCollection<DataBaseConfig> Databases { get; set; }
public ObservableCollection<TextMacro> Macros { get; set; }
public bool UseObjectCache
{
get
{
return useObjectCache;
}
set
{
useObjectCache = value;
}
}
public short CacheExpirePeriod
{
get
{
return cacheExpirePeriod;
}
set
{
cacheExpirePeriod = value;
}
}
public Config()
{
Databases = new ObservableCollection<DataBaseConfig>();
Macros = new ObservableCollection<TextMacro>();
SaveOnCompile = false;
UseObjectCache = true;
CacheExpirePeriod = 2;
}
public static Config LoadFromFile()
{
string file = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "oradev-configuration.xml");
try
{
if (File.Exists(file) && (new FileInfo(file)).Length > 0)
{
XmlSerializer xml = new XmlSerializer(typeof(Config));
FileStream stream = new FileStream(file, FileMode.Open);
Config inst = new Config();
inst = (Config)xml.Deserialize(stream);
stream.Close();
foreach (DataBaseConfig db in inst.Databases)
{
if (db.Guid == null) db.Guid = Guid.NewGuid().ToString();
}
inst.SaveToFile();
return inst;
}
Config cfg = new Config();
return cfg;
}
catch (Exception )
{
Config inst = new Config();
return inst;
}
}
public void SaveToFile()
{
for (int i = Databases.Count - 1; i >= 0; i--)
{
if (!string.IsNullOrEmpty(Databases[i].DataBaseName)) Databases[i].DataBaseName = Databases[i].DataBaseName.Trim();
if (!string.IsNullOrEmpty(Databases[i].DataBaseAlias)) Databases[i].DataBaseAlias = Databases[i].DataBaseAlias.Trim();
if (!string.IsNullOrEmpty(Databases[i].DataBaseUser)) Databases[i].DataBaseUser = Databases[i].DataBaseUser.Trim();
if (string.IsNullOrEmpty(Databases[i].DataBaseName)) Databases[i].DataBaseName = "Untitled database";
if (string.IsNullOrEmpty(Databases[i].DataBaseAlias))
{
Databases.Remove(Databases[i]);
continue;
}
}
XmlSerializer xml = new XmlSerializer(typeof(Config));
StreamWriter stream = new StreamWriter(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "oradev-configuration.xml"));
xml.Serialize(stream, this);
stream.Close();
}
}
}
| gpl-3.0 |
wp-plugins/business-website-helper | business-website-helper.php | 19084 | <?php
/*
Plugin Name: Business Website Helper for WordPress
Version: 1.0.3
Plugin URI: https://justaddcontent.com/free-business-website-helper-plugin-wordpress/
Description: A helper to quickly get your business website up and running on any self-hosted WordPress install with the best in class plugins.
Author: Just Add Content, Gabriel Mays
Author URI: https://justaddcontent.com/
License: GPL v3
Business Website Helper for WordPress
Copyright (C) 2014, Just Add Content, Gabriel Mays - gabe@justaddcontent.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/>.
*/
//* Add Add-Ons admin page
add_action( 'admin_menu', 'jac_website_helper' );
function jac_website_helper() {
add_options_page( 'Business Website Helper for WordPress', 'Business Website', 'manage_options', 'business-website-setup', 'jac_website_setup' ); // Add Business Website Helper to Settings menu
}
//* Display the admin page
function jac_website_setup() {
?>
<div style="margin: 3%; font-weight: 16px; line-height: 1.5;">
<?php
echo '<a href="https://justaddcontent.com/" target="_blank" title="Just Add Content"><img src="' . plugins_url( 'images/justaddcontent.png' , __FILE__ ) . '" alt="Just Add Content" class="alignright"></a> ';
?>
<h2>WordPress Business Website Setup</h2>
This plugin will help you quickly get your business website up and running on any self-hosted WordPress installation with the best plugins in each category. See the bottom of this page for additional help.
<h3 style="text-decoration: underline; font-weight: normal;">Plugin Statuses</h3>
<ul>
<li><strong>·</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>: None of the recommended plugins are active, they may or may not be installed.</li>
<li><strong>·</strong> <span style="color: green; font-weight: bold;">✓ Active</span>: One of the recommended plugins is activated and installed.</li>
</ul>
<h3 style="text-decoration: underline; font-weight: normal;">Recommended Plugin List</h3>
<ul>
<li><strong>·</strong> <a href="#seo">Search Engine Optimization (SEO)</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'wordpress-seo/wp-seo.php' ) || is_plugin_active( 'all-in-one-seo-pack/all_in_one_seo_pack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#cdn">Content Delivery Network (CDN)</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#cache">Website Optimization (Caching)</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'w3-total-cache/w3-total-cache.php' ) || is_plugin_active( 'wp-super-cache/wp-cache.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#stats">Analytics & Website Statistics</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'google-analytics-for-wordpress/googleanalytics.php' ) || is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} elseif ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#email">Email Address Protection</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'email-address-encoder/email-address-encoder.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#lib">Distributed Libraries</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'use-google-libraries/use-google-libraries.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#spell">Spelling & Grammar</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#spam">Spam Prevention</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'akismet/akismet.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#social">Social & Sharing</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
<li><strong>·</strong> <a href="#form">Form Builder</a>:
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'gravityforms/gravityforms.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} elseif ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong>';
} elseif ( is_plugin_active( 'ninja-forms/ninja-forms.php' ) ) {
echo '<span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?></li>
</ul>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the required feature (described below) is active.</em>
<div id="seo"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Search Engine Optimization (SEO)</h3>
<strong>Plugin:</strong> <a href="http://wordpress.org/plugins/wordpress-seo/" target="_blank">WordPress SEO by Yoast</a> (free) or <a href="https://wordpress.org/plugins/all-in-one-seo-pack/" target="_blank">All in One SEO Pack</a> (free)</br>
<strong>Remarks:</strong> WordPress SEO by Yoast is free, but there are also paid features that integrate for <a href="https://yoast.com/wordpress/plugins/video-seo/" target="_blank">video SEO</a> and <a href="https://yoast.com/wordpress/plugins/local-seo/" target="_blank">local SEO</a>.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'wordpress-seo/wp-seo.php' ) || is_plugin_active( 'all-in-one-seo-pack/all_in_one_seo_pack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="cdn"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Content Delivery Network (CDN)</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/jetpack/" target="_blank">Jetpack</a> (free)</br>
<strong>Remarks:</strong> This will speed up your website. Photon is a free CDN that comes with the Jetpack plugin, so it's the most practical CDN option.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong><br>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the <strong>Photon</strong> feature is active.</em>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="cache"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Website Optimization (Caching)</h3>
<strong>Plugin:</strong> <a href="http://wordpress.org/plugins/wp-super-cache/" target="_blank">WP Super Cache</a> (free) or <a href="http://wordpress.org/plugins/w3-total-cache/" target="_blank">W3 Total Cache</a> (free)</br>
<strong>Remarks:</strong> WP Super Cache is a good balance of simplicity and power while W3 Total Cache is more powerful and has more features. <em>If you're using a specialty managed host like WP Engine where caching is handled automatically, <strong>you don't need this.</strong></em></br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'w3-total-cache/w3-total-cache.php' ) || is_plugin_active( 'wp-super-cache/wp-cache.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="stats"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Analytics & Website Statistics</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/jetpack/" target="_blank">Jetpack</a> (free) or <a href="http://wordpress.org/plugins/google-analytics-for-wordpress/" target="_blank">Google Analytics for WordPress</a> (free)</br>
<strong>Remarks:</strong> Jetpack has a built in website statistics feature called WordPress.com Stats that's very easy to use. However, it's recommended that you eventually transition to <a href="http://www.google.com/analytics/" target="_blank">Google Analytics</a> (free) as a better long-term solution that works with any website. Google Analytics for WordPress makes it easy to integrate Google Analytics with your website.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'google-analytics-for-wordpress/googleanalytics.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} elseif ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong><br>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the <strong>WordPress.com Stats</strong> feature is active.</em>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="email"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Email Address Protection</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/email-address-encoder/" target="_blank">Email Address Encoder</a> (free)</br>
<strong>Remarks:</strong> Automatic email obfuscation prevents spammers and email harvesters from getting your email address. No settings, just activate the plugin.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'email-address-encoder/email-address-encoder.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="lib"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Distributed Libraries</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/use-google-libraries/" target="_blank">Use Google Libraries</a> (free)</br>
<strong>Remarks:</strong> Speeds up your website by using libraries hosted by Google. No settings, just activate the plugin.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'use-google-libraries/use-google-libraries.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="spell"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Spelling & Grammar</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/jetpack/" target="_blank">Jetpack</a> (free)</br>
<strong>Remarks:</strong> Adds a spelling and grammar checker to the editor.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong><br>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the <strong>Spelling and Grammar</strong> feature is active.</em>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="spam"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Spam Prevention</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/akismet/" target="_blank">Akismet</a> (free)</br>
<strong>Remarks:</strong> Akismet automatically checks your blog comments to keep out spammers. It's not 100% (what is?), but it's the best thing around and it's free.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'akismet/akismet.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="social"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Social & Sharing</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/jetpack/" target="_blank">Jetpack</a> (free)</br>
<strong>Remarks:</strong> Adds social sharing buttons, Google+ integration, automatic posting to social profiles, and more.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong><br>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the <strong>Publicize</strong>, <strong>Sharing</strong>, <strong>Google+ Profile</strong> and <strong>Enhanced Distribution</strong> features are active.</em>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<div id="form"></div>
<br>
<h3 style="text-decoration: underline; font-weight: normal;">Form Builder</h3>
<strong>Plugin:</strong> <a href="https://wordpress.org/plugins/jetpack/" target="_blank">Jetpack</a> (free), <a href="http://www.gravityforms.com" target="_blank">Gravity Forms</a> ($39+), or <a href="http://wordpress.org/plugins/ninja-forms/" target="_blank">Ninja Forms</a> (freemium)</br>
<strong>Remarks:</strong> Your website needs contact forms, so at the very least use the <strong>Contact Form</strong> feature in the Jetpack plugin (free). However, we highly recommend you get Gravity Forms, especially if you need online quote forms, complex contact forms, etc. Ninja Forms is freemium (core plugin is free, but add-ons cost money) forms plugin that's fairly new, but it looks promising.</br>
<?php
//* Detect if plugin active, show status
if ( is_plugin_active( 'gravityforms/gravityforms.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} elseif ( is_plugin_active( 'jetpack/jetpack.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span><strong>*</strong><br>
<strong>*</strong><em>Jetpack is installed and activated, but check your <a href="/wp-admin/admin.php?page=jetpack" target="_blank">Jetpack settings</a> to make sure the <strong>Contact Form</strong> feature is active.</em>';
} elseif ( is_plugin_active( 'ninja-forms/ninja-forms.php' ) ) {
echo '<strong>Plugin Status:</strong> <span style="color: green; font-weight: bold;">✓ Active</span>';
} else {
echo '<strong>Plugin Status:</strong> <span style="color: red; font-weight: bold;">✗ Inactive</span>';
}
?>
<h3 style="text-decoration: underline; font-weight: normal;">Protect Your Website</h3>
None of these website improvements matter if your website isn't secure. The best way to keep your website secure is to <strong>keep WordPress and all of your plugins updated!</strong>
<h3 style="text-decoration: underline; font-weight: normal;">Want It All Done For You?</h3>
If this seems too time consuming or complicated and you'd rather have it all done for you, try our hosted website service. It's a simplified version of WordPress built exclusively for small businesses that includes everything above and more. Best of all, you never have to worry about themes, plugins, hosting, design or keeping your website secure. Learn more at <a href="https://justaddcontent.com" target="_blank">https://justaddcontent.com</a>
<h3 style="text-decoration: underline; font-weight: normal;">Questions, Comments & Suggestions</h3>
Have questions, comments, suggestions, or want a plugin added to the list? Contact us through the <a href="https://justaddcontent.com/free-business-website-helper-plugin-wordpress/" target="_blank">plugin website page</a>.
</div>
<?php
}
| gpl-3.0 |
dkogan/emacs-snapshot | test/lisp/cedet/semantic-utest-ia-resources/testjavacomp.java | 1923 | // testjavacomp.java --- Semantic unit test for Java
// Copyright (C) 2009-2022 Free Software Foundation, Inc.
// Author: Eric M. Ludlam <zappo@gnu.org>
// This file is part of GNU Emacs.
// GNU Emacs 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.
// GNU Emacs 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
package tests.testjavacomp;
class secondClass {
private void scFuncOne() { }
public void scFuncOne() { }
int package_protected_field;
public int public_protected_field;
private int private_protected_field;
}
public class testjavacomp {
private int funcOne() { }
private int funcTwo() { }
private char funcThree() { }
class nestedClass {
private void ncFuncOne() { }
public void ncFuncOne() { }
}
public void publicFunc() {
int i;
i = fu// -1-
// #1# ( "funcOne" "funcTwo" )
;
fu// -2-
// #2# ( "funcOne" "funcThree" "funcTwo" )
;
secondClass SC;
SC.s//-3-
// #3# ( "scFuncOne" )
;
// @TODO - to make this test complete, we need an import
// with a package protected field that is excluded
// from the completion list.
SC.p//-4-
// #4# ( "package_protected_field" "public_protected_field" )
nestedClass NC;
// @todo - need to fix this? I don't know if this is legal java.
NC.// - 5-
// #5# ( "ncFuncOne" )
;
}
} // testjavacomp
| gpl-3.0 |
ZeroOne71/ql | 02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.SO/Facades/SOPendingFacade.cs | 1863 | using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ECCentral.Portal.Basic.Utilities;
using Newegg.Oversea.Silverlight.Controls;
using Newegg.Oversea.Silverlight.ControlPanel.Core;
using ECCentral.Portal.Basic;
using ECCentral.Portal.UI.SO.Models;
using System.Collections.Generic;
using ECCentral.BizEntity.SO;
using ECCentral.QueryFilter.SO;
namespace ECCentral.Portal.UI.SO.Facades
{
public class SOPendingFacade
{
private readonly RestClient restClient;
private string serviceBaseUrl;
public SOPendingFacade(IPage page)
{
serviceBaseUrl = CPApplication.Current.CurrentPage.Context.Window.Configuration.GetConfigValue(ConstValue.DomainName_SO, ConstValue.Key_ServiceBaseUrl);
restClient = new RestClient(serviceBaseUrl, page);
}
public SOPendingFacade()
: this(null)
{
}
public void OpenSOPending(int soSysNo, EventHandler<RestClientEventArgs<int>> callback)
{
string relativeUrl = "/SOService/SO/OpenPending";
restClient.Update<int>(relativeUrl, soSysNo, callback);
}
public void CloseSOPending(int soSysNo, EventHandler<RestClientEventArgs<int>> callback)
{
string relativeUrl = "/SOService/SO/ClosePending";
restClient.Update<int>(relativeUrl, soSysNo, callback);
}
public void UpdateSOPending(int soSysNo, EventHandler<RestClientEventArgs<int>> callback)
{
string relativeUrl = "/SOService/SO/UpdatePending";
restClient.Update<int>(relativeUrl, soSysNo, callback);
}
}
}
| gpl-3.0 |
interspiresource/interspire | catalog/language/vi-VN/account/newsletter.php | 521 | <?php
/**
* @package Arastta eCommerce
* @copyright Copyright (C) 2015 Arastta Association. All rights reserved. (arastta.org)
* @license GNU General Public License version 3; see LICENSE.txt
*/
// Heading
$_['heading_title'] = 'Đăng ký nhận bản tin';
// Text
$_['text_account'] = 'Tài khoản';
$_['text_newsletter'] = 'Bản tin';
$_['text_success'] = 'Thành công: Đăng ký bản tin của bạn đã được cập nhật thành công!';
// Entry
$_['entry_newsletter'] = 'Đăng ký'; | gpl-3.0 |
sonidosmutantes/apicultor | apicultor/machine_learning/quality.py | 9212 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from ..constraints.dynamic_range import dyn_constraint_satis
from ..utils.algorithms import *
from ..sonification.Sonification import normalize, write_file
import numpy as np
from scipy.fftpack import fft, ifft, fftfreq
from scipy.signal import lfilter, fftconvolve, firwin
from soundfile import read
import os
import sys
import logging
#TODO: *Remove wows, clippings, clicks and pops
#you should comment what you've already processed (avoid over-processing)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
energy = lambda mag: np.sum((10 ** (mag / 20)) ** 2)
rel = lambda at: at * 10 #calculate release time
to_coef = lambda at, sr: np.exp((np.log(9)*-1) / (sr * at)) #convert attack and release time to coefficients
#hiss removal (a noise reduction algorithm working on signal samples to reduce its hissings)
def hiss_removal(audio):
pend = len(audio)-(4410+1102)
song = sonify(audio, 44100)
song.FrameGenerator().__next__()
song.window()
song.Spectrum()
noise_fft = song.fft(song.windowed_x)[:song.H+1]
noise_power = np.log10(np.abs(noise_fft + 2 ** -16))
noise_floor = np.exp(2.0 * noise_power.mean())
mn = song.magnitude_spectrum
e_n = energy(mn)
pin = 0
output = np.zeros(len(audio))
hold_time = 0
ca = 0
cr = 0
amp = audio.max()
while pin < pend:
selection = pin+2048
song.frame = audio[pin:selection]
song.window()
song.M = 2048
song.Spectrum()
e_m = energy(song.magnitude_spectrum)
SNR = 10 * np.log10(e_m / e_n)
ft = song.fft(song.windowed_x)[:song.H+1]
power_spectral_density = np.abs(ft) ** 2
song.Envelope()
song.AttackTime()
rel_time = rel(song.attack_time)
rel_coef = to_coef(rel_time, 44100)
at_coef = to_coef(song.attack_time, 44100)
ca = ca + song.attack_time
cr = cr + rel_time
if SNR > 0:
np.add.at(output, range(pin, selection), audio[pin:selection])
else:
if np.any(power_spectral_density < noise_floor):
gc = dyn_constraint_satis(ft, [power_spectral_density, noise_floor], 0.12589254117941673)
if ca > hold_time:
gc = np.complex64([at_coef * gc[i- 1] + (1 - at_coef) * x if x > gc[i- 1] else x for i,x in enumerate(gc)])
if ca <= hold_time:
gc = np.complex64([gc[i- 1] for i,x in enumerate(gc)])
if cr > hold_time:
gc = np.complex64([rel_coef * gc[i- 1] + (1 - rel_coef) * x if x <= gc[i- 1] else x for i,x in enumerate(gc)])
if cr <= hold_time:
gc = np.complex64([gc[i- 1] for i,x in enumerate(gc)])
print ("Reducing noise floor, this is taking some time")
song.Phase(song.fft(song.windowed_x))
song.phase = song.phase[:song.magnitude_spectrum.size]
ft *= gc
song.magnitude_spectrum = np.sqrt(pow(ft.real,2) + pow(ft.imag,2))
np.add.at(output, range(pin, selection), song.ISTFT(song.magnitude_spectrum))
else:
np.add.at(output, range(pin, selection), audio[pin:selection])
pin = pin + song.H
hold_time += selection/44100
hissless = amp * output / output.max() #amplify to normal level
return np.float32(hissless)
#optimizers and biquad_filter taken from Linear Audio Lib
def z_from_f(f,fs):
out = []
for x in f:
if x == np.inf:
out.append(-1.)
else:
out.append(((fs/np.pi)-x)/((fs/np.pi)+x))
return out
def Fz_at_f(Poles,Zeros,f,fs,norm = 0):
omega = 2*np.pi*f/fs
ans = 1.
for z in Zeros:
ans = ans*(np.exp(omega*1j)-z_from_f([z],fs))
for p in Poles:
ans = ans/(np.exp(omega*1j)-z_from_f([p],fs))
if norm:
ans = ans/max(abs(ans))
return ans
def z_coeff(Poles,Zeros,fs,g,fg,fo = 'none'):
if fg == np.inf:
fg = fs/2
if fo == 'none':
beta = 1.0
else:
beta = f_warp(fo,fs)/fo
a = np.poly(z_from_f(beta*np.array(Poles),fs))
b = np.poly(z_from_f(beta*np.array(Zeros),fs))
gain = 10.**(g/20.)/abs(Fz_at_f(beta*np.array(Poles),beta*np.array(Zeros),fg,fs))
return (a,b*gain)
def biquad_filter(xin,z_coeff):
a = z_coeff[0]
b = z_coeff[1]
xout = np.zeros(len(xin))
xout[0] = b[0]*xin[0]
xout[1] = b[0]*xin[1] + b[1]*xin[0] - a[1]*xout[0]
for j in range(2,len(xin)):
xout[j] = b[0]*xin[j]+b[1]*xin[j-1]+b[2]*xin[j-2]-a[1]*xout[j-1]-a[2]*xout[j-2]
return xout
Usage = "./quality.py [DATA_PATH] [HTRF_SIGNAL_PATH]"
def main():
if len(sys.argv) < 3:
print("\nBad amount of input arguments\n", Usage, "\n")
sys.exit(1)
try:
DATA_PATH = sys.argv[1]
RIAA = [[50.048724,2122.0659],[500.48724,np.inf]]
abz = z_coeff(RIAA[0],RIAA[1],44100,0,10000)
if not os.path.exists(DATA_PATH):
raise IOError("Must download sounds")
for subdir, dirs, files in os.walk(DATA_PATH):
for f in files:
print(( "Rewriting without hissing in %s"%f ))
audio = read(DATA_PATH+'/'+f)[0]
audio = mono_stereo(audio)
hissless = hiss_removal(audio) #remove hiss
print(( "Rewriting without crosstalk in %s"%f ))
hrtf = read(sys.argv[2])[0] #load the hrtf wav file
b = firwin(2, [0.05, 0.95], width=0.05, pass_zero=False)
convolved = fftconvolve(hrtf, b[np.newaxis, :], mode='valid')
left = convolved[:int(convolved.shape[0]/2), :]
right = convolved[int(convolved.shape[0]/2):, :]
h_sig_L = lfilter(left.flatten(), 1., audio)
h_sig_R = lfilter(right.flatten(), 1., audio)
del hissless
result = np.float32([h_sig_L, h_sig_R]).T
neg_angle = result[:,(1,0)]
panned = result + neg_angle
normalized = normalize(panned)
del normalized
audio = mono_stereo(audio)
print(( "Rewriting without aliasing in %s"%f ))
song = sonify(audio, 44100)
audio = song.IIR(audio, 44100/2, 'lowpass') #anti-aliasing filtering: erase frequencies higher than the sample rate being used
print(( "Rewriting without DC in %s"%f ))
audio = song.IIR(audio, 40, 'highpass') #remove direct current on audio signal
print(( "Rewriting with Equal Loudness contour in %s"%f ))
audio = song.EqualLoudness(audio) #Equal-Loudness Contour
print(( "Rewriting with RIAA filter applied in %s"%f ))
riaa_filtered = biquad_filter(audio, abz) #riaa filter
del audio
normalized_riaa = normalize(riaa_filtered)
del riaa_filtered
print(( "Rewriting with Hum removal applied in %s"%f ))
song.signal = np.float32(normalized_riaa)
without_hum = song.BandReject(np.float32(normalized_riaa), 50, 16) #remove undesired 50 hz hum
del normalized_riaa
print(( "Rewriting with subsonic rumble removal applied in %s"%f ))
song.signal = without_hum
without_rumble = song.IIR(song.signal, 20, 'highpass') #remove subsonic rumble
del without_hum
db_mag = 20 * np.log10(abs(without_rumble)) #calculate silence if present in audio signal
print(( "Rewriting without silence in %s"%f ))
silence_threshold = -130 #complete silence
loud_audio = np.delete(without_rumble, np.where(db_mag < silence_threshold))#remove it
write_file(subdir+'/'+os.path.splitext(f)[0], 44100, loud_audio)
del without_rumble
except Exception as e:
logger.exception(e)
exit(1)
if __name__ == '__main__':
main()
| gpl-3.0 |
Guts/DicoGIS | dicogis/georeaders/gdal_exceptions_handler.py | 1779 | #! python3 # noqa: E265
# ##############################################################################
# ########## Libraries #############
# ##################################
# Standard library
import logging
# 3rd party libraries
from osgeo import gdal, ogr
# #############################################################################
# ########## Globals ###############
# ##################################
logger = logging.getLogger(__name__)
# ##############################################################################
# ########## Classes ###############
# ##################################
class GdalErrorHandler(object):
def __init__(self):
"""Callable error handler.
see: https://gdal.org/api/python_gotchas.html
and http://pcjericks.github.io/py-gdalogr-cookbook/gdal_general.html#install-gdal-ogr-error-handler
"""
self.err_level = gdal.CE_None
self.err_type = 0
self.err_msg = ""
def handler(self, err_level, err_type, err_msg):
"""Make errors messages more readable."""
# available types
err_class = {
gdal.CE_None: "None",
gdal.CE_Debug: "Debug",
gdal.CE_Warning: "Warning",
gdal.CE_Failure: "Failure",
gdal.CE_Fatal: "Fatal",
}
# getting type
err_type = err_class.get(err_type, "None")
# cleaning message
err_msg = err_msg.replace("\n", " ")
# disabling OGR exceptions raising to avoid future troubles
ogr.DontUseExceptions()
# propagating
self.err_level = err_level
self.err_type = err_type
self.err_msg = err_msg
# end of function
return self.err_level, self.err_type, self.err_msg
| gpl-3.0 |
ardinusawan/Sistem_Terdistribusi | PublicSubcibe/onManajer.py | 12096 | __author__ = 'Indra Gunawan'
import os
import socket
import threading
import re
import time
import subprocess
hapus = True
local_ip = ('192.168.0.24')
local_port = 8000
currdir=os.path.abspath('.')
class FTPserverThread(threading.Thread):
def __init__(self,(conn,addr)):
self.conn=conn
self.addr=addr
self.basewd=currdir
self.cwd=self.basewd
self.rest=False
self.namaKlien=""
self.pasv_mode=True
self.user_pass=[["123","123"],["321","321"]]
self.user_session=[["","",""]]
threading.Thread.__init__(self)
def run(self):
self.conn.send('220 Welcome!\r\n')
while True:
cmd=self.conn.recv(256)
if not cmd: break
else:
print 'Recieved:',cmd
try:
func=getattr(self,cmd[:4].strip().upper())
func(cmd)
except Exception,e:
print 'ERROR:',e
#traceback.print_exc()
self.conn.send('500 Syntax error, command unrecognized.\r\n')
def HELP(self, cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
pesan = "USER PASS QUIT PWD CWD LIST MKD RMD DELE RNFR RNTO RETR STOR HELP\r\n"
self.conn.send(pesan)
break
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def USER(self,cmd):
namaKlien=cmd.split(" ")
for i in range (0,len(self.user_pass)):
print namaKlien[1][:-2]+"--",self.user_pass[i][0]
if namaKlien[1][:-2] == self.user_pass[i][0]:
self.conn.send('331 Please specify the password\r\n')
self.user_session.append([self.conn.getpeername(),namaKlien[1][:-2],"not ok"])
break
elif i==len(self.user_session):
self.conn.send('530 Please Login with USER and PASS.\r\n')
def PASS(self,cmd):
passKlien=cmd.split(" ")[1].strip("\r\n")
namaKlien=""
index = 0
ipPort=self.conn.getpeername()
print ipPort
for i in range (0,len(self.user_session)):
if ipPort==self.user_session[i][0]:
namaKlien=self.user_session[i][1]
index=i
break
passServer=""
for i in range (0,len(self.user_pass)):
if namaKlien == self.user_pass[i][0]:
passServer=self.user_pass[i][1]
break
if passServer==passKlien:
self.user_session[index][2]="OK"
self.conn.send('230 User logged in, proceed.\r\n')
else:
del self.user_session[index]
self.conn.send('530 Login incorrect.\r\n530 Please Login with USER and PASS.\r\n')
def QUIT(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0]:
del self.user_session[i]
self.conn.send("221 Goodbye.\r\n");
def PWD(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
cwd=os.path.relpath(self.cwd,self.basewd)
if cwd=='.':
cwd='/'
else:
cwd='/'+cwd
self.conn.send('200 Command okay \"%s\"\r\n' % cwd)
break
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def CWD(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
chwd=cmd[4:-2]
if chwd=='/':
self.cwd=self.basewd
elif chwd[0]=='/':
self.cwd=os.path.join(self.basewd,chwd[1:])
else:
self.cwd=os.path.join(self.cwd,chwd)
self.conn.send('200 Command okay.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def start_datasock(self):
if self.pasv_mode:
self.datasock, addr = self.servsock.accept()
print 'connect:', addr
else:
self.datasock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.datasock.connect((self.dataAddr,self.dataPort))
def stop_datasock(self):
self.datasock.close()
if self.pasv_mode:
self.servsock.close()
def LIST(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
self.conn.send('150 Here comes the directory listing.\r')
print 'list:', self.cwd
datas = ""
for filename in os.listdir(self.cwd):
data = filename
datas=datas+'\n'+data
self.conn.send(datas+'\n')
self.conn.send('226 Directory send OK.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def MKD(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
dn=os.path.join(self.cwd,cmd[4:-2])
os.mkdir(dn)
self.conn.send('257 Directory created.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def RMD(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
dn=os.path.join(self.cwd,cmd[4:-2])
if hapus:
os.rmdir(dn)
self.conn.send('250 Directory deleted.\r\n')
else:
self.conn.send('450 Not allowed.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def DELE(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
fn=os.path.join(self.cwd,cmd[5:-2])
if hapus:
os.remove(fn)
self.conn.send('250 File deleted.\r\n')
else:
self.conn.send('450 Not allowed.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def RNFR(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
self.rnfn=os.path.join(self.cwd,cmd[5:-2])
self.conn.send('350 Ready.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def RNTO(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
fn=os.path.join(self.cwd,cmd[5:-2])
os.rename(self.rnfn,fn)
self.conn.send('250 File renamed.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def RETR(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
fn=os.path.join(self.cwd,cmd[5:-2])
self.conn.send('150 Opening data connection.\r\n')
if os.path.isfile(fn):
self.conn.send("EXISTS " + str(os.path.getsize(fn)))
print 'Downloading:',fn
i=0
with open(fn, 'rb') as f:
bytesToSend = f.read(1024)
self.conn.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
self.conn.send(bytesToSend)
print "prosessing"
self.conn.send('226 Transfer complete.\r\n')
else:
self.conn.send("ERR ")
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
def STOR(self,cmd):
for i in range (0, len(self.user_session)):
if self.conn.getpeername()==self.user_session[i][0] and self.user_session[i][2]=="OK":
fn=os.path.join(self.cwd,cmd[5:-2])
print 'Uplaoding:',fn
fo=open(fn,'wb')
self.conn.send('150 Opening data connection.\r\n')
i=0
buf=self.conn.recv(4096)
size=int(buf.split('\r\n\r\n')[0])
data='\r\n\r\n'.join(buf.split('\r\n\r\n')[1:])
size=size-len(data)
while i<size:
data+=self.conn.recv(4096)
i=i+4096
fo.write(data)
fo.close()
self.conn.send('226 Transfer complete.\r\n')
elif i==len(self.user_session)-1:
self.conn.send('530 Please Login with USER and PASS.\r\n')
class FTPserver(threading.Thread):
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((local_ip,local_port))
threading.Thread.__init__(self)
def run(self):
self.sock.listen(5)
while True:
th=FTPserverThread(self.sock.accept())
th.daemon=True
th.start()
def stop(self):
self.sock.close()
if __name__=='__main__':
ftp=FTPserver()
ftp.daemon=True
ftp.start()
print 'On', local_ip, ':', local_port
raw_input('Enter to end...\n')
ftp.stop()
tempc1 = []
temp1 = []
buka = open('DWI_SERVER')
for i, line in enumerate(buka):
lol = re.split("\W+", line, 2)
tempc1.append(int(lol[1]))
temp1.append('('+lol[2])
print temp1
print tempc1
tempc2 = []
temp2 = []
buka = open('WAWAN_SERVER')
for i, line in enumerate(buka):
lol = re.split("\W+", line, 2)
tempc2.append(int(lol[1]))
temp2.append('('+lol[2])
print temp2
print tempc2
lentemp1 = len(temp1)
lentemp2 = len(temp2)
cek = 0
for i in range(lentemp2):
for j in range(lentemp1):
cek+=1
if temp2[i] == temp1[j]:
tempc1[j] += tempc2[i]
cek = -10;
if cek==lentemp1-1 :
#print 'masuk'
temp1.append(temp2[i])
tempc1.append(tempc2[i])
cek = 0
lentemp1 = len(temp1)
for i in range(lentemp1):
for j in range(lentemp1):
if tempc1[i] > tempc1[j]:
tempoftemp = temp1[i]
tempoftempc = tempc1[i]
temp1[i] = temp1[j]
tempc1[i] = tempc1[j]
temp1[j] = tempoftemp
tempc1[j] = tempoftempc
fmt = '%-8s%-20s%s'
print(fmt % ('', 'Frequent','Command'))
hitung = 0
for i, (name, grade) in enumerate(zip(tempc1,temp1)):
#print(fmt % (i, name, grade))
if hitung != 10 :
data3 = fmt % (i, name, grade)
print data3
hitung = hitung +1
| gpl-3.0 |
writeameer/moodle | course/yui/toolboxes/toolboxes.js | 30330 | YUI.add('moodle-course-toolboxes', function(Y) {
WAITICON = {'pix':"i/loading_small",'component':'moodle'};
// The CSS selectors we use
var CSS = {
ACTIVITYLI : 'li.activity',
COMMANDSPAN : 'span.commands',
SPINNERCOMMANDSPAN : 'span.commands',
CONTENTAFTERLINK : 'div.contentafterlink',
DELETE : 'a.editing_delete',
DIMCLASS : 'dimmed',
DIMMEDTEXT : 'dimmed_text',
EDITTITLE : 'a.editing_title',
EDITTITLECLASS : 'edittitle',
GENERICICONCLASS : 'iconsmall',
GROUPSNONE : 'a.editing_groupsnone',
GROUPSSEPARATE : 'a.editing_groupsseparate',
GROUPSVISIBLE : 'a.editing_groupsvisible',
HASLABEL : 'label',
HIDE : 'a.editing_hide',
HIGHLIGHT : 'a.editing_highlight',
INSTANCENAME : 'span.instancename',
LIGHTBOX : 'lightbox',
MODINDENTCOUNT : 'mod-indent-',
MODINDENTDIV : 'div.mod-indent',
MODINDENTHUGE : 'mod-indent-huge',
MODULEIDPREFIX : 'module-',
MOVELEFT : 'a.editing_moveleft',
MOVELEFTCLASS : 'editing_moveleft',
MOVERIGHT : 'a.editing_moveright',
PAGECONTENT : 'div#page-content',
RIGHTSIDE : '.right',
SECTIONHIDDENCLASS : 'hidden',
SECTIONIDPREFIX : 'section-',
SECTIONLI : 'li.section',
SHOW : 'a.editing_show',
SHOWHIDE : 'a.editing_showhide',
CONDITIONALHIDDEN : 'conditionalhidden',
AVAILABILITYINFODIV : 'div.availabilityinfo',
SHOWCLASS : 'editing_show',
HIDECLASS : 'hide'
};
/**
* The toolbox classes
*
* TOOLBOX is a generic class which should never be directly instantiated
* RESOURCETOOLBOX is a class extending TOOLBOX containing code specific to resources
* SECTIONTOOLBOX is a class extending TOOLBOX containing code specific to sections
*/
var TOOLBOX = function() {
TOOLBOX.superclass.constructor.apply(this, arguments);
}
Y.extend(TOOLBOX, Y.Base, {
/**
* Toggle the visibility and availability for the specified
* resource show/hide button
*/
toggle_hide_resource_ui : function(button) {
var element = button.ancestor(CSS.ACTIVITYLI);
var hideicon = button.one('img');
var dimarea;
var toggle_class;
if (this.is_label(element)) {
toggle_class = CSS.DIMMEDTEXT;
dimarea = element.one(CSS.MODINDENTDIV + ' div');
} else {
toggle_class = CSS.DIMCLASS;
dimarea = element.one('a');
}
var status = '';
var value;
if (button.hasClass(CSS.SHOWCLASS)) {
status = 'hide';
value = 1;
} else {
status = 'show';
value = 0;
}
// Update button info.
var newstring = M.util.get_string(status, 'moodle');
hideicon.setAttrs({
'alt' : newstring,
'src' : M.util.image_url('t/' + status)
});
button.set('title', newstring);
button.set('className', 'editing_'+status);
// If activity is conditionally hidden, then don't toggle.
if (!dimarea.hasClass(CSS.CONDITIONALHIDDEN)) {
// Change the UI.
dimarea.toggleClass(toggle_class);
// We need to toggle dimming on the description too.
element.all(CSS.CONTENTAFTERLINK).toggleClass(CSS.DIMMEDTEXT);
}
// Toggle availablity info for conditional activities.
var availabilityinfo = element.one(CSS.AVAILABILITYINFODIV);
if (availabilityinfo) {
availabilityinfo.toggleClass(CSS.HIDECLASS);
}
return value;
},
/**
* Send a request using the REST API
*
* @param data The data to submit
* @param statusspinner (optional) A statusspinner which may contain a section loader
* @param optionalconfig (optional) Any additional configuration to submit
* @return response responseText field from responce
*/
send_request : function(data, statusspinner, optionalconfig) {
// Default data structure
if (!data) {
data = {};
}
// Handle any variables which we must pass back through to
var pageparams = this.get('config').pageparams;
for (varname in pageparams) {
data[varname] = pageparams[varname];
}
data.sesskey = M.cfg.sesskey;
data.courseId = this.get('courseid');
var uri = M.cfg.wwwroot + this.get('ajaxurl');
// Define the configuration to send with the request
var responsetext = [];
var config = {
method: 'POST',
data: data,
on: {
success: function(tid, response) {
try {
responsetext = Y.JSON.parse(response.responseText);
if (responsetext.error) {
new M.core.ajaxException(responsetext);
}
} catch (e) {}
if (statusspinner) {
window.setTimeout(function(e) {
statusspinner.hide();
}, 400);
}
},
failure : function(tid, response) {
if (statusspinner) {
statusspinner.hide();
}
new M.core.ajaxException(response);
}
},
context: this,
sync: true
}
// Apply optional config
if (optionalconfig) {
for (varname in optionalconfig) {
config[varname] = optionalconfig[varname];
}
}
if (statusspinner) {
statusspinner.show();
}
// Send the request
Y.io(uri, config);
return responsetext;
},
is_label : function(target) {
return target.hasClass(CSS.HASLABEL);
},
/**
* Return the module ID for the specified element
*
* @param element The <li> element to determine a module-id number for
* @return string The module ID
*/
get_element_id : function(element) {
return element.get('id').replace(CSS.MODULEIDPREFIX, '');
},
/**
* Return the module ID for the specified element
*
* @param element The <li> element to determine a module-id number for
* @return string The module ID
*/
get_section_id : function(section) {
return section.get('id').replace(CSS.SECTIONIDPREFIX, '');
}
},
{
NAME : 'course-toolbox',
ATTRS : {
// The ID of the current course
courseid : {
'value' : 0
},
ajaxurl : {
'value' : 0
},
config : {
'value' : 0
}
}
}
);
var RESOURCETOOLBOX = function() {
RESOURCETOOLBOX.superclass.constructor.apply(this, arguments);
}
Y.extend(RESOURCETOOLBOX, TOOLBOX, {
// Variables
GROUPS_NONE : 0,
GROUPS_SEPARATE : 1,
GROUPS_VISIBLE : 2,
/**
* Initialize the resource toolbox
*
* Updates all span.commands with relevant handlers and other required changes
*/
initializer : function(config) {
this.setup_for_resource();
M.course.coursebase.register_module(this);
var prefix = CSS.ACTIVITYLI + ' ' + CSS.COMMANDSPAN + ' ';
Y.delegate('click', this.edit_resource_title, CSS.PAGECONTENT, prefix + CSS.EDITTITLE, this);
Y.delegate('click', this.move_left, CSS.PAGECONTENT, prefix + CSS.MOVELEFT, this);
Y.delegate('click', this.move_right, CSS.PAGECONTENT, prefix + CSS.MOVERIGHT, this);
Y.delegate('click', this.delete_resource, CSS.PAGECONTENT, prefix + CSS.DELETE, this);
Y.delegate('click', this.toggle_hide_resource, CSS.PAGECONTENT, prefix + CSS.HIDE, this);
Y.delegate('click', this.toggle_hide_resource, CSS.PAGECONTENT, prefix + CSS.SHOW, this);
Y.delegate('click', this.toggle_groupmode, CSS.PAGECONTENT, prefix + CSS.GROUPSNONE, this);
Y.delegate('click', this.toggle_groupmode, CSS.PAGECONTENT, prefix + CSS.GROUPSSEPARATE, this);
Y.delegate('click', this.toggle_groupmode, CSS.PAGECONTENT, prefix + CSS.GROUPSVISIBLE, this);
},
/**
* Update any span.commands within the scope of the specified
* selector with AJAX equivelants
*
* @param baseselector The selector to limit scope to
* @return void
*/
setup_for_resource : function(baseselector) {
if (!baseselector) {
var baseselector = CSS.PAGECONTENT + ' ' + CSS.ACTIVITYLI;
}
Y.all(baseselector).each(this._setup_for_resource, this);
},
_setup_for_resource : function(toolboxtarget) {
toolboxtarget = Y.one(toolboxtarget);
// Set groupmode attribute for use by this.toggle_groupmode()
var groups;
groups = toolboxtarget.all(CSS.COMMANDSPAN + ' ' + CSS.GROUPSNONE);
groups.setAttribute('groupmode', this.GROUPS_NONE);
groups = toolboxtarget.all(CSS.COMMANDSPAN + ' ' + CSS.GROUPSSEPARATE);
groups.setAttribute('groupmode', this.GROUPS_SEPARATE);
groups = toolboxtarget.all(CSS.COMMANDSPAN + ' ' + CSS.GROUPSVISIBLE);
groups.setAttribute('groupmode', this.GROUPS_VISIBLE);
},
move_left : function(e) {
this.move_leftright(e, -1);
},
move_right : function(e) {
this.move_leftright(e, 1);
},
move_leftright : function(e, direction) {
// Prevent the default button action
e.preventDefault();
// Get the element we're working on
var element = e.target.ancestor(CSS.ACTIVITYLI);
// And we need to determine the current and new indent level
var indentdiv = element.one(CSS.MODINDENTDIV);
var indent = indentdiv.getAttribute('class').match(/mod-indent-(\d{1,})/);
if (indent) {
var oldindent = parseInt(indent[1]);
var newindent = Math.max(0, (oldindent + parseInt(direction)));
indentdiv.removeClass(indent[0]);
} else {
var oldindent = 0;
var newindent = 1;
}
// Perform the move
indentdiv.addClass(CSS.MODINDENTCOUNT + newindent);
var data = {
'class' : 'resource',
'field' : 'indent',
'value' : newindent,
'id' : this.get_element_id(element)
};
var spinner = M.util.add_spinner(Y, element.one(CSS.SPINNERCOMMANDSPAN));
this.send_request(data, spinner);
// Handle removal/addition of the moveleft button
if (newindent == 0) {
element.one(CSS.MOVELEFT).remove();
} else if (newindent == 1 && oldindent == 0) {
this.add_moveleft(element);
}
// Handle massive indentation to match non-ajax display
var hashugeclass = indentdiv.hasClass(CSS.MODINDENTHUGE);
if (newindent > 15 && !hashugeclass) {
indentdiv.addClass(CSS.MODINDENTHUGE);
} else if (newindent <= 15 && hashugeclass) {
indentdiv.removeClass(CSS.MODINDENTHUGE);
}
},
delete_resource : function(e) {
// Prevent the default button action
e.preventDefault();
// Get the element we're working on
var element = e.target.ancestor(CSS.ACTIVITYLI);
var confirmstring = '';
if (this.is_label(element)) {
// Labels are slightly different to other activities
var plugindata = {
type : M.util.get_string('pluginname', 'label')
}
confirmstring = M.util.get_string('deletechecktype', 'moodle', plugindata)
} else {
var plugindata = {
type : M.util.get_string('pluginname', element.getAttribute('class').match(/modtype_([^\s]*)/)[1]),
name : element.one(CSS.INSTANCENAME).get('firstChild').get('data')
}
confirmstring = M.util.get_string('deletechecktypename', 'moodle', plugindata);
}
// Confirm element removal
if (!confirm(confirmstring)) {
return false;
}
// Actually remove the element
element.remove();
var data = {
'class' : 'resource',
'action' : 'DELETE',
'id' : this.get_element_id(element)
};
this.send_request(data);
},
toggle_hide_resource : function(e) {
// Prevent the default button action
e.preventDefault();
// Return early if the current section is hidden
var section = e.target.ancestor(M.course.format.get_section_selector(Y));
if (section && section.hasClass(CSS.SECTIONHIDDENCLASS)) {
return;
}
// Get the element we're working on
var element = e.target.ancestor(CSS.ACTIVITYLI);
var button = e.target.ancestor('a', true);
var value = this.toggle_hide_resource_ui(button);
// Send the request
var data = {
'class' : 'resource',
'field' : 'visible',
'value' : value,
'id' : this.get_element_id(element)
};
var spinner = M.util.add_spinner(Y, element.one(CSS.SPINNERCOMMANDSPAN));
this.send_request(data, spinner);
return false; // Need to return false to stop the delegate for the new state firing
},
toggle_groupmode : function(e) {
// Prevent the default button action
e.preventDefault();
// Get the element we're working on
var element = e.target.ancestor(CSS.ACTIVITYLI);
var button = e.target.ancestor('a', true);
var icon = button.one('img');
// Current Mode
var groupmode = button.getAttribute('groupmode');
groupmode++;
if (groupmode > 2) {
groupmode = 0;
}
button.setAttribute('groupmode', groupmode);
var newtitle = '';
var iconsrc = '';
switch (groupmode) {
case this.GROUPS_NONE:
newtitle = 'groupsnone';
iconsrc = M.util.image_url('t/groupn');
break;
case this.GROUPS_SEPARATE:
newtitle = 'groupsseparate';
iconsrc = M.util.image_url('t/groups');
break;
case this.GROUPS_VISIBLE:
newtitle = 'groupsvisible';
iconsrc = M.util.image_url('t/groupv');
break;
}
newtitle = M.util.get_string('clicktochangeinbrackets', 'moodle',
M.util.get_string(newtitle, 'moodle'));
// Change the UI
icon.setAttrs({
'alt' : newtitle,
'src' : iconsrc
});
button.setAttribute('title', newtitle);
// And send the request
var data = {
'class' : 'resource',
'field' : 'groupmode',
'value' : groupmode,
'id' : this.get_element_id(element)
};
var spinner = M.util.add_spinner(Y, element.one(CSS.SPINNERCOMMANDSPAN));
this.send_request(data, spinner);
return false; // Need to return false to stop the delegate for the new state firing
},
/**
* Add the moveleft button
* This is required after moving left from an initial position of 0
*
* @param target The encapsulating <li> element
*/
add_moveleft : function(target) {
var left_string = M.util.get_string('moveleft', 'moodle');
var moveimage = 't/left'; // ltr mode
if ( Y.one(document.body).hasClass('dir-rtl') ) {
moveimage = 't/right';
} else {
moveimage = 't/left';
}
var newicon = Y.Node.create('<img />')
.addClass(CSS.GENERICICONCLASS)
.setAttrs({
'src' : M.util.image_url(moveimage, 'moodle'),
'alt' : left_string
});
var moveright = target.one(CSS.MOVERIGHT);
var newlink = moveright.getAttribute('href').replace('indent=1', 'indent=-1');
var anchor = new Y.Node.create('<a />')
.setStyle('cursor', 'pointer')
.addClass(CSS.MOVELEFTCLASS)
.setAttribute('href', newlink)
.setAttribute('title', left_string);
anchor.appendChild(newicon);
moveright.insert(anchor, 'before');
},
/**
* Edit the title for the resource
*/
edit_resource_title : function(e) {
// Get the element we're working on
var element = e.target.ancestor(CSS.ACTIVITYLI);
var instancename = element.one(CSS.INSTANCENAME);
var currenttitle = instancename.get('firstChild');
var oldtitle = currenttitle.get('data');
var titletext = oldtitle;
var editbutton = element.one('a.' + CSS.EDITTITLECLASS + ' img');
// Handle events for edit_resource_title
var listenevents = [];
var thisevent;
// Grab the anchor so that we can swap it with the edit form
var anchor = instancename.ancestor('a');
var data = {
'class' : 'resource',
'field' : 'gettitle',
'id' : this.get_element_id(element)
};
// Try to retrieve the existing string from the server
var response = this.send_request(data, editbutton);
if (response.instancename) {
titletext = response.instancename;
}
// Create the editor and submit button
var editor = Y.Node.create('<input />')
.setAttrs({
'name' : 'title',
'value' : titletext,
'autocomplete' : 'off'
})
.addClass('titleeditor');
var editform = Y.Node.create('<form />')
.setStyle('padding', '0')
.setStyle('display', 'inline')
.setAttribute('action', '#');
var editinstructions = Y.Node.create('<span />')
.addClass('editinstructions')
.set('innerHTML', M.util.get_string('edittitleinstructions', 'moodle'));
// Clear the existing content and put the editor in
currenttitle.set('data', '');
editform.appendChild(editor);
anchor.replace(editform);
element.appendChild(editinstructions);
e.preventDefault();
// Focus and select the editor text
editor.focus().select();
// Handle removal of the editor
var clear_edittitle = function() {
// Detach all listen events to prevent duplicate triggers
var thisevent;
while (thisevent = listenevents.shift()) {
thisevent.detach();
}
if (editinstructions) {
// Convert back to anchor and remove instructions
editform.replace(anchor);
editinstructions.remove();
editinstructions = null;
}
}
// Handle cancellation of the editor
var cancel_edittitle = function(e) {
clear_edittitle();
// Set the title and anchor back to their previous settings
currenttitle.set('data', oldtitle);
};
// Cancel the edit if we lose focus or the escape key is pressed
thisevent = editor.on('blur', cancel_edittitle);
listenevents.push(thisevent);
thisevent = Y.one('document').on('keyup', function(e) {
if (e.keyCode == 27) {
cancel_edittitle(e);
}
});
listenevents.push(thisevent);
// Handle form submission
thisevent = editform.on('submit', function(e) {
// We don't actually want to submit anything
e.preventDefault();
// Clear the edit title boxes
clear_edittitle();
// We only accept strings which have valid content
var newtitle = Y.Lang.trim(editor.get('value'));
if (newtitle != null && newtitle != "" && newtitle != titletext) {
var data = {
'class' : 'resource',
'field' : 'updatetitle',
'title' : newtitle,
'id' : this.get_element_id(element)
};
var response = this.send_request(data, editbutton);
if (response.instancename) {
currenttitle.set('data', response.instancename);
}
} else {
// Invalid content. Set the title back to it's original contents
currenttitle.set('data', oldtitle);
}
}, this);
listenevents.push(thisevent);
},
/**
* Set the visibility of the current resource (identified by the element)
* to match the hidden parameter (this is not a toggle).
* Only changes the visibility in the browser (no ajax update).
* @param args An object with 'element' being the A node containing the resource
* and 'visible' being the state that the visiblity should be set to.
* @return void
*/
set_visibility_resource_ui: function(args) {
var element = args.element;
var shouldbevisible = args.visible;
var buttonnode = element.one(CSS.SHOW);
var visible = (buttonnode === null);
if (visible) {
buttonnode = element.one(CSS.HIDE);
}
if (visible != shouldbevisible) {
this.toggle_hide_resource_ui(buttonnode);
}
}
}, {
NAME : 'course-resource-toolbox',
ATTRS : {
courseid : {
'value' : 0
},
format : {
'value' : 'topics'
}
}
});
var SECTIONTOOLBOX = function() {
SECTIONTOOLBOX.superclass.constructor.apply(this, arguments);
}
Y.extend(SECTIONTOOLBOX, TOOLBOX, {
/**
* Initialize the toolboxes module
*
* Updates all span.commands with relevant handlers and other required changes
*/
initializer : function(config) {
this.setup_for_section();
M.course.coursebase.register_module(this);
// Section Highlighting
Y.delegate('click', this.toggle_highlight, CSS.PAGECONTENT, CSS.SECTIONLI + ' ' + CSS.HIGHLIGHT, this);
// Section Visibility
Y.delegate('click', this.toggle_hide_section, CSS.PAGECONTENT, CSS.SECTIONLI + ' ' + CSS.SHOWHIDE, this);
},
/**
* Update any section areas within the scope of the specified
* selector with AJAX equivelants
*
* @param baseselector The selector to limit scope to
* @return void
*/
setup_for_section : function(baseselector) {
// Left here for potential future use - not currently needed due to YUI delegation in initializer()
/*if (!baseselector) {
var baseselector = CSS.PAGECONTENT;
}
Y.all(baseselector).each(this._setup_for_section, this);*/
},
_setup_for_section : function(toolboxtarget) {
// Left here for potential future use - not currently needed due to YUI delegation in initializer()
},
toggle_hide_section : function(e) {
// Prevent the default button action
e.preventDefault();
// Get the section we're working on
var section = e.target.ancestor(M.course.format.get_section_selector(Y));
var button = e.target.ancestor('a', true);
var hideicon = button.one('img');
// The value to submit
var value;
// The status text for strings and images
var status;
if (!section.hasClass(CSS.SECTIONHIDDENCLASS)) {
section.addClass(CSS.SECTIONHIDDENCLASS);
value = 0;
status = 'show';
} else {
section.removeClass(CSS.SECTIONHIDDENCLASS);
value = 1;
status = 'hide';
}
var newstring = M.util.get_string(status + 'fromothers', 'format_' + this.get('format'));
hideicon.setAttrs({
'alt' : newstring,
'src' : M.util.image_url('i/' + status)
});
button.set('title', newstring);
// Change the highlight status
var data = {
'class' : 'section',
'field' : 'visible',
'id' : this.get_section_id(section.ancestor(M.course.format.get_section_wrapper(Y), true)),
'value' : value
};
var lightbox = M.util.add_lightbox(Y, section);
lightbox.show();
var response = this.send_request(data, lightbox);
var activities = section.all(CSS.ACTIVITYLI);
activities.each(function(node) {
if (node.one(CSS.SHOW)) {
var button = node.one(CSS.SHOW);
} else {
var button = node.one(CSS.HIDE);
}
var activityid = this.get_element_id(node);
if (Y.Array.indexOf(response.resourcestotoggle, activityid) != -1) {
this.toggle_hide_resource_ui(button);
}
}, this);
},
toggle_highlight : function(e) {
// Prevent the default button action
e.preventDefault();
// Get the section we're working on
var section = e.target.ancestor(M.course.format.get_section_selector(Y));
var button = e.target.ancestor('a', true);
var buttonicon = button.one('img');
// Determine whether the marker is currently set
var togglestatus = section.hasClass('current');
var value = 0;
// Set the current highlighted item text
var old_string = M.util.get_string('markthistopic', 'moodle');
Y.one(CSS.PAGECONTENT)
.all(M.course.format.get_section_selector(Y) + '.current ' + CSS.HIGHLIGHT)
.set('title', old_string);
Y.one(CSS.PAGECONTENT)
.all(M.course.format.get_section_selector(Y) + '.current ' + CSS.HIGHLIGHT + ' img')
.set('alt', old_string)
.set('src', M.util.image_url('i/marker'));
// Remove the highlighting from all sections
var allsections = Y.one(CSS.PAGECONTENT).all(M.course.format.get_section_selector(Y))
.removeClass('current');
// Then add it if required to the selected section
if (!togglestatus) {
section.addClass('current');
value = this.get_section_id(section.ancestor(M.course.format.get_section_wrapper(Y), true));
var new_string = M.util.get_string('markedthistopic', 'moodle');
button
.set('title', new_string);
buttonicon
.set('alt', new_string)
.set('src', M.util.image_url('i/marked'));
}
// Change the highlight status
var data = {
'class' : 'course',
'field' : 'marker',
'value' : value
};
var lightbox = M.util.add_lightbox(Y, section);
lightbox.show();
this.send_request(data, lightbox);
}
}, {
NAME : 'course-section-toolbox',
ATTRS : {
courseid : {
'value' : 0
},
format : {
'value' : 'topics'
}
}
});
M.course = M.course || {};
M.course.init_resource_toolbox = function(config) {
return new RESOURCETOOLBOX(config);
};
M.course.init_section_toolbox = function(config) {
return new SECTIONTOOLBOX(config);
};
},
'@VERSION@', {
requires : ['base', 'node', 'io', 'moodle-course-coursebase']
}
);
| gpl-3.0 |
bluebottle/is.idega.idegaweb.block.pheidippides | src/java/is/idega/idegaweb/pheidippides/data/BankReference.java | 1726 | package is.idega.idegaweb.pheidippides.data;
import java.io.Serializable;
import java.text.NumberFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = BankReference.ENTITY_NAME)
@NamedQueries({
@NamedQuery(name = "bankReference.findByHeader", query = "select b from BankReference b where b.header = :header")
})
public class BankReference implements Serializable {
private static final long serialVersionUID = -8698331644705962525L;
public static final String ENTITY_NAME = "ph_bank_reference";
private static final String COLUMN_ENTRY_ID = "bank_reference_id";
private static final String COLUMN_REGISTRATION_HEADER = "registration_header";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = BankReference.COLUMN_ENTRY_ID)
private Long id;
@ManyToOne
@JoinColumn(name = BankReference.COLUMN_REGISTRATION_HEADER)
private RegistrationHeader header;
public Long getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
public RegistrationHeader getHeader() {
return header;
}
public void setHeader(RegistrationHeader header) {
this.header = header;
}
public String getReferenceNumber() {
NumberFormat format = NumberFormat.getIntegerInstance();
format.setMaximumIntegerDigits(7);
format.setMinimumIntegerDigits(7);
format.setGroupingUsed(false);
return format.format(getId());
}
}
| gpl-3.0 |
hamadmarri/Biscuit | main/java/com/biscuit/factories/SprintsCompleterFactory.java | 1956 | package com.biscuit.factories;
import java.util.ArrayList;
import java.util.List;
import com.biscuit.models.Project;
import com.biscuit.models.services.Finder;
import jline.console.completer.ArgumentCompleter;
import jline.console.completer.Completer;
import jline.console.completer.NullCompleter;
import jline.console.completer.StringsCompleter;
public class SprintsCompleterFactory {
public static List<Completer> getSprintsCompleters(Project project) {
List<Completer> completers = new ArrayList<Completer>();
// TODO: sprints commands
// completers.add(new ArgumentCompleter(new StringsCompleter("summary",
// "back"), new NullCompleter()));
// completers.add(
// new ArgumentCompleter(new StringsCompleter("list"), new
// StringsCompleter("past"), new StringsCompleter("filter", "sort"), new
// NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// new StringsCompleter("future"), new StringsCompleter("filter",
// "sort"),
// new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// new StringsCompleter("current"), new NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// new StringsCompleter("all"), new StringsCompleter("filter"), new
// NullCompleter()));
//
// completers.add(new ArgumentCompleter(new StringsCompleter("list"),
// new StringsCompleter("all"), new StringsCompleter("sort"),
// new StringsCompleter(Release.fields), new NullCompleter()));
completers.add(new ArgumentCompleter(new StringsCompleter("back", "sprints"), new NullCompleter()));
completers.add(new ArgumentCompleter(new StringsCompleter("add"), new StringsCompleter("sprint"), new NullCompleter()));
completers.add(new ArgumentCompleter(new StringsCompleter("go_to"), new StringsCompleter(Finder.Sprints.getAllNames(project)), new NullCompleter()));
return completers;
}
}
| gpl-3.0 |