branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep><?php
add_action( 'widgets_init', 'dmc_register_sidebars' );
function dmc_register_sidebars() {
register_sidebar(array(
'name'=> 'Homepage widgets',
'id' => 'sidebar-home',
'description' => 'Widgets placed here will appear on the homepage',
'before_widget' => '<div id="%1$s" class="col-sm-4 %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="h4">',
'after_title' => '</h3>'
));
register_sidebar(array(
'name'=> 'Footer widgets',
'id' => 'sidebar-footer',
'description' => 'Widgets placed here will appear in the footer',
'before_widget' => '<article id="%1$s" class="col-sm-4 %2$s">',
'after_widget' => '</article>',
'before_title' => '<h3 class="footer__heading">',
'after_title' => '</h3>'
));
}<file_sep><?php
/**********************
Enqueue CSS and Scripts
**********************/
// enque WP and vendor scripts
if( ! function_exists( 'reverie_scripts_and_styles ' ) ) {
function reverie_scripts_and_styles() {
if (!is_admin()) {
// modernizr (without media query polyfill)
wp_enqueue_script( 'reverie-modernizr', get_template_directory_uri() . '/js/modernizr.min.js', array(), '2.8.3', false );
// only add WP comment-reply.min.js if threaded comments are on an it's a post of some type
if( get_option( 'thread_comments' ) && is_singular() ) {
wp_enqueue_script( 'comment-reply' );
}
// add Foundation and vendor scripts files in the footer
wp_enqueue_script( 'reverie-js', get_template_directory_uri() . '/js/bower.min.js', array( 'jquery' ), '', true );
}
}
}
add_action( 'wp_enqueue_scripts', 'reverie_scripts_and_styles' );
// https://wpshout.com/make-site-faster-async-deferred-javascript-introducing-script_loader_tag/
function dmc_defer_scripts( $tag, $handle, $src ) {
// The handles of the enqueued scripts we want to defer
$defer_scripts = array(
// 'admin-bar',
// 'cookie',
// 'devicepx',
// 'jquery-migrate',
);
if ( in_array( $handle, $defer_scripts ) ) {
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
}
return $tag;
}
add_filter( 'script_loader_tag', 'dmc_defer_scripts', 10, 3 );
// vendor styles
if( ! function_exists( 'grunterie_enqueue_style' ) ) {
function grunterie_enqueue_style() {
// Google fonts
wp_enqueue_style('google-font', 'https://fonts.googleapis.com/css?family=Oswald:400,700');
// main stylesheet
wp_enqueue_style( 'grunterie-stylesheet', get_stylesheet_directory_uri() . '/css/style.css', array(), '', 'all' );
// vendor styles
wp_enqueue_style( 'vendor',get_template_directory_uri() . '/css/vendor.css', false );
}
}
add_action( 'wp_enqueue_scripts', 'grunterie_enqueue_style' );<file_sep><?php
/*
Originally from Reverie Theme, now heavily modified
Author: <NAME>
URL: http://themefortress.com/
*/
// do all the cleaning and enqueue here
require_once get_template_directory() . '/lib/clean.php';
// enqueue vendor scripts and styles
require_once get_template_directory() . '/lib/enqueue.php';
// load Foundation specific functions like top-bar
require_once get_template_directory() . '/lib/foundation.php';
/* Custom post types */
require_once get_template_directory() . '/post-types/partner.php';
require_once get_template_directory() . '/post-types/resource.php';
// Widgets setup
require_once get_template_directory() . '/lib/widgets.php';
// post meta functions (entry meta, post authors etc)
require_once get_template_directory() . '/lib/post-meta.php';
// Advanced Custom Fields customisation functions
require_once get_template_directory() . '/lib/acf-functions.php';
/**
* Extend Recent Posts Widget
*
* Adds different formatting to the default WordPress Recent Posts Widget
*/
Class DMC_Recent_Posts_Widget extends WP_Widget_Recent_Posts {
function widget($args, $instance) {
extract( $args );
$title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts') : $instance['title'], $instance, $this->id_base);
if( empty( $instance['number'] ) || ! $number = absint( $instance['number'] ) )
$number = 10;
$r = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ) ) );
if( $r->have_posts() ) :
echo $before_widget;
if( $title ) echo $before_title . $title . $after_title; ?>
<?php while( $r->have_posts() ) : $r->the_post(); ?>
<h4><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php
echo $after_widget;
wp_reset_postdata();
endif;
}
}
function my_recent_widget_registration() {
unregister_widget('WP_Widget_Recent_Posts');
register_widget('DMC_Recent_Posts_Widget');
}
add_action('widgets_init', 'my_recent_widget_registration');
/**
* Hide email from Spam Bots using a shortcode.
*
* @param array $atts Shortcode attributes. Not used.
* @param string $content The shortcode content. Should be an email address.
*
* @return string The obfuscated email address.
*/
function wpcodex_hide_email_shortcode( $atts , $content = null ) {
if ( ! is_email( $content ) ) {
return;
}
return '<a href="mailto:' . antispambot( $content ) . '">' . antispambot( $content ) . '</a>';
}
add_shortcode( 'email', 'wpcodex_hide_email_shortcode' );
// Allow shortcodes in widget_text
add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );
// display large thumbnail size image with caption
if ( ! function_exists( 'dmc_display_image_with_caption' ) ) {
function dmc_display_image_with_caption() { ?>
<div class="wp-caption">
<?php
the_post_thumbnail( 'large' , array( 'class' => 'img-featured' ) );
$get_description = get_post( get_post_thumbnail_id() )->post_excerpt;
if ( !empty( $get_description ) ) {
echo '<p class="wp-caption-text">' . $get_description . '</p>';
}
?>
</div>
<?php
}
}<file_sep>
<!-- Footer -->
<footer class="footer" role="contentinfo">
<div class="container">
<div class="row">
<!-- Homepage sidebar -->
<?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar( 'Footer widgets' ) ) : ?>
<?php endif; ?>
</div>
</div>
</footer>
<?php wp_footer(); ?>
<!-- Footer Script -->
<script>
var navigation = responsiveNav("#nav");
</script>
</body>
</html><file_sep><?php
// return entry meta information for posts, used by multiple loops
if ( ! function_exists( 'reverie_entry_meta' ) ) {
function reverie_entry_meta() {
$output ='';
$output .= '<p class="metadata">';
// get WP author posts link
$output .= 'By: ' . get_the_author_posts_link() . '<br>';
$output .= 'Date: <time class="updated" datetime="'. get_the_time('c') .'" pubdate>'. sprintf(__('%s', 'reverie'), get_the_date(), get_the_date()) .'</time> ';
if ( is_single( 'post') || is_home() || is_post_type_archive( 'post' ) || is_search() ) :
$num_comments = get_comments_number(); // get_comments_number returns only a numeric value
if ( comments_open() ) {
if ( $num_comments == 0 ) {
$comments = __('<span class="comment-result no-comments">Make a comment</span>');
} elseif ( $num_comments > 1 ) {
$comments = $num_comments . __(' comments');
} else {
$comments = __('<span class="comment-result">1 comment</span>');
}
$write_comments = '<a href="' . get_comments_link() .'"><span class="icon small icon-forum"></span> '. $comments.'</a>';
} else {
$write_comments = __('<span class="comment-result">Comments off</span>');
}
$output .= '<span class="comments comment-results right">'. $write_comments .'</span>';
endif;
$output .= '</p>';
echo $output;
}
}
// Show partner social media links & icons
if ( ! function_exists( 'dmc_show_partner_socials' ) ) {
function dmc_show_partner_socials() {
$dmc_partner_twitter_check = get_field( 'dmc_partner_twitter_username' );
$dmc_partner_instagram_check = get_field( 'dmc_partner_instagram_username' );
$dmc_partner_facebook_check = get_field( 'dmc_partner_facebook_url' );
$dmc_partner_linkedin_check = get_field( 'dmc_partner_linkedin_url' );
if ( $dmc_partner_twitter_check ) {
$output = '<li><span class="social__item"><a class="social__link--twitter" href="https://twitter.com/' . $dmc_partner_twitter_check . '"><span class="social__link--text">View Twitter stream</span></a></span></li>';
echo $output;
}
if ( $dmc_partner_instagram_check ) {
$output = '<li><span class="social__item"><a class="social__link--instagram" href="https://www.instagram.com/' . $dmc_partner_instagram_check . '"><span class="social__link--text">View Instagram feed</span></a></span></li>';
echo $output;
}
if ( $dmc_partner_facebook_check ) {
$output = '<li><span class="social__item"><a class="social__link--facebook" href="' . $dmc_partner_facebook_check . '"><span class="social__link--text">View Facebook page</span></a></span></li>';
echo $output;
}
if ( $dmc_partner_linkedin_check ) {
$output = '<li><span class="social__item"><a class="social__link--linkedin" href="' . $dmc_partner_linkedin_check . '"><span class="social__link--text">View LinkedIn profile</span></a></span></li>';
echo $output;
}
}
}<file_sep><?php get_header(); ?>
<!-- Content -->
<div class="container">
<div <?php post_class( 'content' ); ?>" id="content" role="main">
<div class="mar-b-3">
<h1><?php the_title(); ?></h1>
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php if ( have_rows( 'dmc_categories' ) ) : ?>
<div class="row">
<?php while ( have_rows( 'dmc_categories' ) ) : the_row(); ?>
<div class="col-sm-4">
<h3 class="h4 mar-t-0"><?php the_sub_field( 'category_title' ); ?></h3>
<?php the_sub_field( 'category_cotent' ); ?>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php // no rows found ?>
<?php endif; ?>
</div>
</div>
<?php if ( have_rows( 'dmc_staff' ) ) : ?>
<h2>Staff</h2>
<?php while ( have_rows( 'dmc_staff' ) ) : the_row(); ?>
<div class="row mar-b-3">
<div class="col-sm-2 hidden-xs">
<?php $staff_member_image = get_sub_field( 'staff_member_image' ); ?>
<?php if ( $staff_member_image ) { ?>
<img src="<?php echo $staff_member_image['url']; ?>" alt="<?php echo $staff_member_image['alt']; ?>" />
<?php } ?>
</div>
<div class="col-sm-10">
<h3 class="h4 mar-t-0"><?php the_sub_field( 'staff_member_name' ); ?></h3>
<?php the_sub_field( 'staff_member_intro' ); ?>
<p><a href="mailto:<?php the_sub_field( 'staff_member_email' ); ?>"><?php the_sub_field( 'staff_member_email' ); ?></a></p>
</div>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php // no rows found ?>
<?php endif; ?>
<?php endwhile; ?>
</div>
</div>
</div>
<?php get_footer(); ?><file_sep><form role="search" method="get" action="<?php echo home_url('/'); ?>">
<div class="input searchform">
<label class="input__label" for="s">
<span class="input__content hidden">Search site</span>
<input required type="text" value="" name="s" id="s" class="input__control" placeholder="<?php esc_attr_e('Search Site ', 'reverie'); ?>">
</label>
<button type="submit" class="button-primary search__button">Search</button>
</div>
</form><file_sep><?php
// displays an ACF file field, including file size, file type and file extension
if ( ! function_exists( 'dmc_display_file_upload' ) ) {
function dmc_display_file_upload( $acffield, $subfield ) {
if (!empty($subfield)) {
$file = get_sub_field( $acffield );
} else {
$file = get_field( $acffield );
}
if( $file ) :
// vars
$attachment_id = $file['id'];
$url = $file['url'];
$title = 'brochure';
$filesize = filesize( get_attached_file( $attachment_id ) );
$filetype = wp_check_filetype( $url );
$fileext = $filetype['ext'];
$filesize = size_format( $filesize ); ?>
<p class="text-center">
<a class="link-button-primary" href="<?php echo $url; ?>" title="<?php echo $title; ?>" class="button medium ghost">Download <?php echo $title; ?> <span class="filemeta" style="text-transform:uppercase;"><?php echo ' (' . $filesize . ' ' . $fileext . ')'; ?></span>
</a>
</p>
<?php endif;
}
}<file_sep><?php get_header(); ?>
<!-- Content -->
<div class="container">
<div class="content" id="content" role="main">
<?php if ( have_posts() ) : ?>
<h1 class="text-center">
<?php if ( is_post_type_archive( 'post') ) : ?>
<span>Latest blog posts</span>
<?php elseif ( is_category() ) : ?>
<span>Blog posts categorised '<?php single_cat_title(); ?>'</span>
<?php elseif ( is_author() ) : ?>
<span>Blog posts by <?php the_author(); ?></span>
<?php elseif ( is_tag() ) : ?>
<span>Blog posts for tag '<?php single_tag_title(); ?>'</span>
<?php elseif ( is_post_type_archive( 'partner') ) : ?>
<span>Partners</span>
<?php elseif ( is_post_type_archive( 'resource' ) ) : ?>
<span>Resources</span>
<?php elseif ( is_archive() ) : ?>
<span>Blog posts for <?php single_month_title(' '); ?></span>
<?php elseif ( is_search() ) : ?>
<span><?php _e('Search Results for', 'reverie'); ?> "<?php echo get_search_query(); ?>"</span>
<?php endif; ?>
</h1>
<div class="row mar-b-3">
<div class="col-sm-12">
<?php while ( have_posts() ) : the_post(); ?>
<h2 class="h3 mar-t-0 text-left"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<?php else : ?>
<h2 class="h3 mar-t-0 text-left">No Results found</h2>
<p>Sorry, but we could not find any results for that search term.</p>
</div>
</div>
<?php endif; ?>
<?php /* Display navigation to next/previous pages when applicable */ ?>
<?php if ( function_exists('reverie_pagination') ) { reverie_pagination(); } else if ( is_paged() ) { ?>
<nav id="post-nav">
<div class="post-previous"><?php next_posts_link( __( '← Older posts', 'reverie' ) ); ?></div>
<div class="post-next"><?php previous_posts_link( __( 'Newer posts →', 'reverie' ) ); ?></div>
</nav>
<?php } ?>
</div>
</div>
<?php get_footer(); ?><file_sep><?php
/*********************
Start all the functions
at once for Reverie.
*********************/
// start all the functions
add_action('after_setup_theme','reverie_startup');
if( ! function_exists( 'reverie_startup ' ) ) {
function reverie_startup() {
// launching operation cleanup
add_action('init', 'reverie_head_cleanup');
// remove WP version from RSS
add_filter('the_generator', 'reverie_rss_version');
// remove pesky injected css for recent comments widget
add_filter( 'wp_head', 'reverie_remove_wp_widget_recent_comments_style', 1 );
// clean up comment styles in the head
add_action('wp_head', 'reverie_remove_recent_comments_style', 1);
// clean up gallery output in wp
add_filter('gallery_style', 'reverie_gallery_style');
// additional post related cleaning
add_filter( 'img_caption_shortcode', 'reverie_cleaner_caption', 10, 3 );
add_filter('get_image_tag', 'reverie_image_editor', 0, 4);
// add_filter( 'the_content', 'reverie_img_unautop', 30 );
} /* end reverie_startup */
}
/**********************
Add theme supports
**********************/
if( ! function_exists( 'reverie_theme_support' ) ) {
function reverie_theme_support() {
// Add language supports.
load_theme_textdomain('reverie', get_template_directory() . '/lang');
// Add theme support for HTML5 Semantic Markup
add_theme_support( 'html5', array( 'comment-form', 'comment-list' ) );
// Add theme support for document Title tag
add_theme_support( 'title-tag' );
// add excerpts to these post types
$types = array( 'page' );
foreach ( $types as $type ) {
add_post_type_support( $type, 'excerpt');
}
// add_post_type_support( 'jetpack-portfolio', 'archive' );
// Add post thumbnail supports. http://codex.wordpress.org/Post_Thumbnails
add_theme_support('post-thumbnails');
// set_post_thumbnail_size(150, 150, false);
add_image_size('fd-lrg', 1024, 99999);
add_image_size('fd-med-rect', 250, 180);
add_image_size('fd-med', 250, 250);
add_image_size('dmc-slider', 1890, 400);
// rss thingy
add_theme_support('automatic-feed-links');
// Add post formats support. http://codex.wordpress.org/Post_Formats
add_theme_support( 'post-formats', array('video') );
// Add menu support. http://codex.wordpress.org/Function_Reference/register_nav_menus
register_nav_menus(array(
'primary' => __('Primary Navigation', 'reverie'),
'additional' => __('Additional Navigation', 'reverie'),
'utility' => __('Utility Navigation', 'reverie')
));
// Add custom background support
add_theme_support( 'custom-background',
array(
'default-image' => '', // background image default
'default-color' => '', // background color default (dont add the #)
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
)
);
}
}
add_action('after_setup_theme', 'reverie_theme_support'); /* end Reverie theme support */
/**********************
WP_HEAD Cleanup
**********************/
if( ! function_exists( 'reverie_head_cleanup ' ) ) {
function reverie_head_cleanup() {
// category feeds
// remove_action( 'wp_head', 'feed_links_extra', 3 );
// post and comment feeds
// remove_action( 'wp_head', 'feed_links', 2 );
// EditURI link
remove_action( 'wp_head', 'rsd_link' );
// windows live writer
remove_action( 'wp_head', 'wlwmanifest_link' );
// index link
remove_action( 'wp_head', 'index_rel_link' );
// previous link
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
// start link
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
// links for adjacent posts
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
// WP version
remove_action( 'wp_head', 'wp_generator' );
// remove WP version from css
add_filter( 'style_loader_src', 'reverie_remove_wp_ver_css_js', 9999 );
// remove Wp version from scripts
add_filter( 'script_loader_src', 'reverie_remove_wp_ver_css_js', 9999 );
} /* end head cleanup */
}
// remove WP version from RSS
if( ! function_exists( 'reverie_rss_version ' ) ) {
function reverie_rss_version() { return ''; }
}
// remove WP version from scripts
if( ! function_exists( 'reverie_remove_wp_ver_css_js ' ) ) {
function reverie_remove_wp_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
}
// remove injected CSS for recent comments widget
if( ! function_exists( 'reverie_remove_wp_widget_recent_comments_style ' ) ) {
function reverie_remove_wp_widget_recent_comments_style() {
if ( has_filter('wp_head', 'wp_widget_recent_comments_style') ) {
remove_filter('wp_head', 'wp_widget_recent_comments_style' );
}
}
}
// remove injected CSS from recent comments widget
if( ! function_exists( 'reverie_remove_recent_comments_style ' ) ) {
function reverie_remove_recent_comments_style() {
global $wp_widget_factory;
if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
}
}
}
// remove injected CSS from gallery
if( ! function_exists( 'reverie_gallery_style ' ) ) {
function reverie_gallery_style($css) {
return preg_replace("!<style type='text/css'>(.*?)</style>!s", '', $css);
}
}
/*********************
Post related cleaning
*********************/
/* Customized the output of caption, you can remove the filter to restore back to the WP default output. Courtesy of DevPress. http://devpress.com/blog/captions-in-wordpress/ */
if( ! function_exists( 'reverie_cleaner_caption ' ) ) {
function reverie_cleaner_caption( $output, $attr, $content ) {
/* We're not worried abut captions in feeds, so just return the output here. */
if ( is_feed() )
return $output;
/* Set up the default arguments. */
$defaults = array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
);
/* Merge the defaults with user input. */
$attr = shortcode_atts( $defaults, $attr );
/* If the width is less than 1 or there is no caption, return the content wrapped between the [caption]< tags. */
if ( 1 > $attr['width'] || empty( $attr['caption'] ) )
return $content;
/* Set up the attributes for the caption <div>. */
$attributes = ' class="figure ' . esc_attr( $attr['align'] ) . '"';
/* Open the caption <div>. */
$output = '<figure' . $attributes .'>';
/* Allow shortcodes for the content the caption was created for. */
$output .= do_shortcode( $content );
/* Append the caption text. */
$output .= '<figcaption>' . $attr['caption'] . '</figcaption>';
/* Close the caption </div>. */
$output .= '</figure>';
/* Return the formatted, clean caption. */
return $output;
} /* end reverie_cleaner_caption */
}
// Remove width and height in editor, for a better responsive world.
if( ! function_exists( 'reverie_image_editor ' ) ) {
function reverie_image_editor($html, $id, $alt, $title) {
return preg_replace(array(
'/\s+width="\d+"/i',
'/\s+height="\d+"/i',
'/alt=""/i'
),
array(
'',
'',
'',
'alt="' . $title . '"'
),
$html);
} /* end reverie_image_editor */
}<file_sep><!doctype html>
<html class="no-js" <?php language_attributes(); ?> >
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Title -->
<title><?php wp_title(''); ?></title>
<!-- Base metadata -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="Description" lang="en" content="EPIC: Equal Partners Interstate Congress">
<!-- Apple touch icon links -->
<link rel="apple-touch-icon" sizes="180x180" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-180x180.png">
<link rel="apple-touch-icon" sizes="152x152" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="144x144" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="120x120" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="114x114" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="76x76" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="72x72" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="60x60" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="57x57" href="<?php echo get_template_directory_uri(); ?>/img/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" href="<?php echo get_template_directory_uri(); ?>/img/apple-icon-precomposed.png">
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>">
<!-- IE tile icon links -->
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="<?php echo get_template_directory_uri(); ?>/img/ms-icon-144x144.png">
<meta name="msapplication-square310x310logo" content="<?php echo get_template_directory_uri(); ?>/img/ms-icon-310x310.png">
<meta name="msapplication-wide310x150logo" content="<?php echo get_template_directory_uri(); ?>/img/ms-icon-310x150.png">
<meta name="msapplication-square150x150logo" content="<?php echo get_template_directory_uri(); ?>/img/ms-icon-150x150.png">
<meta name="msapplication-square70x70logo" content="<?php echo get_template_directory_uri(); ?>/img/ms-icon-70x70.png">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<!-- Header -->
<div class="container-fluid">
<div class="container">
<div class="row tools">
<div class="col-sm-7">
<a class="tools__link tools__skip" href="#content">Skip<span class="hidden-xs"> to main content</span></a>
<ul class="tools__social-media">
<li><a href="https://www.facebook.com/EPICnationalpartners/"><span class="tools__facebook"><span class="hidden">Facebook</span></span></a></li>
<li><a href="https://twitter.com/EPICadvocates"><span class="tools__twitter"><span class="hidden">Twitter</span></span></a></li>
<li><a href="http://instagram.com/epicnationalpartners"><span class="tools__instagram"><span class="hidden">Instagram</span></span></a></li>
<li><a href="https://www.youtube.com/channel/UC_6PJBVor-r8ADlx8TuYIrg"><span class="tools__youtube"><span class="hidden">YouTube</span></span></a></li>
</ul>
</div>
<div class="col-sm-4 col-sm-offset-1">
<div class="row">
<?php require_once('searchform.php'); ?>
</div>
</div>
</div>
<div class="logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img src="<?php echo get_template_directory_uri(); ?>/img/epic-logo.gif" alt="<?php bloginfo( 'name' ); ?>">
</a>
</div>
<nav id="nav" role="navigation">
<?php wp_nav_menu(
array(
'theme_location' => 'primary',
'container' => false,
'depth' => 0,
'items_wrap' => '<ul>%3$s</ul>',
'menu' => __( 'The Main Menu', 'reverie' ),
)
);?>
</nav>
</div>
</div>
<?php if ( !is_front_page() ) : ?>
<?php endif; ?><file_sep><?php get_header(); ?>
<!-- Content -->
<div class="container">
<div <?php post_class( 'content' ); ?>" id="content" role="main">
<?php while (have_posts()) : the_post(); ?>
<h1 class="text-center"><?php the_title(); ?></h1>
<!-- Blog content -->
<div class="mar-b-3">
<figure class="float-left mar-r-1">
<?php the_post_thumbnail( 'fd-med-rect' ); ?>
</figure>
<?php reverie_entry_meta(); ?>
<?php the_content(); ?>
</div>
<!-- About the author -->
<div class="details">
<p><?php the_author_meta('description'); ?></p>
</div>
<!-- Filed under -->
<div class="mar-b-1 font14">
Filed under: <?php the_category( ', ' ); ?>
</div>
<!-- Actions -->
<div class="mar-b-3 text-right">
<?php previous_post_link( '<span class="link-button-primary">%link</span>', 'Previous' ); ?>
<?php next_post_link( '<span class="link-button-primary">%link</span>', 'Next' ); ?>
</div>
<?php comments_template(); ?>
<?php endwhile; ?>
<?php get_footer(); ?><file_sep><?php get_header(); ?>
<!-- Banner -->
<div class="container-fluid">
<div class="banner">
<?php wooslider( array('slider_type'=>'slides','slide_page'=>'home-page')); ?>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="content" id="content" role="main">
<div class="mar-b-3">
<h1>Updates</h1>
<div class="row">
<!-- Homepage sidebar -->
<?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar( 'Homepage widgets' ) ) : ?>
<?php endif; ?>
</div>
</div>
<?php
$home_partners = new WP_Query( array(
'post_type' => 'partner',
'orderby' => 'menu_order',
));
if ( $home_partners->have_posts() ) : ?>
<h2>Partners</h2>
<?php
while ( $home_partners->have_posts() ) : $home_partners->the_post(); ?>
<div class="row mar-b-3">
<div class="col-sm-2 hidden-xs">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'medium' ); ?>
</a>
</div>
<div class="col-sm-10">
<h3 class="h4 mar-t-0"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php the_excerpt(); ?></p>
<p><a href="mailto:<?php the_field( 'dmc_partner_email_address' ); ?>"><?php the_field( 'dmc_partner_email_address' ); ?></a></p>
<p></p>
</div>
</div>
<?php
endwhile; wp_reset_postdata(); ?>
<div class="text-center">
<a href="/partners/" class="link-button-primary">More Partners</a>
</div>
</div>
</div>
<?php endif; ?>
<?php get_footer(); ?><file_sep><?php get_header(); ?>
<!-- Banner -->
<div class="container-fluid">
<div class="banner"></div>
</div>
<!-- Content -->
<div class="container-medium">
<div <?php post_class( 'content' ); ?>" id="content" role="main">
<h1><?php the_title(); ?></h1>
<div class="row mar-b-3">
<div class="col-sm-3 col-sm-offset-2">
<?php the_post_thumbnail( 'medium' ); ?>
</div>
<div class="col-sm-4">
<p>
<?php the_field( 'dmc_partner_phone' ); ?><br>
<a href="<?php the_field( 'dmc_partner_web_address' ); ?>"><?php the_field( 'dmc_partner_web_address' ); ?></a><br>
<a href="mailto:<?php the_field( 'dmc_partner_email_address' ); ?>"><?php the_field( 'dmc_partner_email_address' ); ?></a>
</p>
<p><?php the_field( 'dmc_partner_address' ); ?></p>
</div>
<div class="col-sm-6 col-sm-offset-2">
<ul class="list-inline socials">
<?php dmc_show_partner_socials(); ?>
</ul>
</div>
</div>
<div class="mar-b-2">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="row">
<div class="col-sm-6">
<?php if ( get_field( 'dmc_partner_instagram_userid' ) ) : ?>
<h3 class="h4">Instagram</h3>
<?php echo do_shortcode( '[instagram-feed id ="' . get_field( 'dmc_partner_instagram_userid' ) . '" showheader=false]' ); ?>
<?php endif; ?>
</div>
<div class="col-sm-6">
<?php if ( get_field( 'dmc_partner_twitter_username' ) ) : ?>
<h3 class="h4">Twitter</h3>
<?php echo do_shortcode( '[twitter-timeline username=' . get_field( 'dmc_partner_twitter_username' ) . ']' ); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?><file_sep><?php
/**
* The default template for displaying content. Used for both single and index/archive/search.
*
* @subpackage Reverie
* @since Reverie 4.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class('index-card'); ?>>
<header>
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php reverie_entry_meta(); ?>
</header>
<div class="entry-content">
<figure>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'medium' , array( 'class' => 'alignright' ) ); ?></a>
</figure>
<?php the_excerpt(); ?>
</div>
</article>
<?php if ( is_single() ) { ?>
<div class="prev-next">
<div class="row collapse">
<div class="medium-6 columns">
<?php previous_post_link( '<span class="button ghost prev">%link</span>', 'Previous article' ); ?>
</div>
<div class="medium-6 columns text-right">
<?php next_post_link( '<span class="button ghost next">%link</span>', 'Next article' ); ?>
</div>
</div>
</div>
<?php } ?> | 71dcf5e99fc6e53a5d586ee7e9f96fe495e43e56 | [
"PHP"
] | 15 | PHP | accessibilityoz/epicnationalpartners | d914b58d27cdb62ff1aae20c3a10c47ffa0beb15 | 75799b5cc5801a5a92c8aed45f076b2a31831d53 |
refs/heads/master | <repo_name>domecq/h1-movies-ws<file_sep>/db/migrate/20120211025431_create_horarios.rb
class CreateHorarios < ActiveRecord::Migration
def change
create_table :horarios do |t|
t.integer :cine_id
t.integer :pelicula_id
t.string :horarios
end
end
end
<file_sep>/README.md
h1-movies-ws
============
Webservices for h1-movies app
<file_sep>/spec/models/pelicula_spec.rb
require 'spec_helper'
describe Pelicula do
# without factory girl
# before {
# @pelicula = Pelicula.new(
# titulo: "Trapito para los mas chiquitos",
# descripcion: "Algo de un espantapajaros",
# brief: "espantapajaros",
# imagen: "bases123.com.ar/fotos/cine/4766.jpg",
# imagen_chica: "bases123.com.ar/fotos/cine/4766.jpg"
# )
# }
# subject { @pelicula }
# it { respond_to(:titulo)}
# it { respond_to(:descripcion)}
# it { respond_to(:brief)}
# it { respond_to(:imagen)}
# it { respond_to(:imagen_chica)}
# it { should be_valid }
# describe "when titulo is not present" do
# before {@pelicula.titulo = " "}
# it {should_not be_valid}
# end
it "has a valid factory" do
Factory.create(:pelicula).should be_valid
end
it "is invalid without a titulo" do
Factory.build(:pelicula, titulo: nil).should_not be_valid
end
it "is valid with a titulo" do
Factory.create(:pelicula, titulo: 'Trapito para los mas chiquitos').should be_valid
end
end<file_sep>/db/migrate/20120208221008_add_localidad_to_cines.rb
class AddLocalidadToCines < ActiveRecord::Migration
def change
add_column :cines, :localidad, :string
end
end
<file_sep>/db/migrate/20120211060055_rename_horarios_by_horas.rb
class RenameHorariosByHoras < ActiveRecord::Migration
def up
rename_column :horarios, :horarios, :horas
end
def down
end
end
<file_sep>/db/migrate/20120211040715_add_es_estreno_to_peliculas.rb
class AddEsEstrenoToPeliculas < ActiveRecord::Migration
def change
add_column :peliculas, :es_estreno, :bool
end
end
<file_sep>/db/migrate/20120329000703_add_imagen_chica_to_peliculas.rb
class AddImagenChicaToPeliculas < ActiveRecord::Migration
def change
add_column :peliculas, :imagen_chica, :string
end
end
<file_sep>/app/admin/peliculas.rb
ActiveAdmin.register Pelicula do
end
<file_sep>/app/models/pelicula.rb
class Pelicula < ActiveRecord::Base
has_many :horarios
has_many :cines, :through => :horarios
validates :titulo, presence: true
end
<file_sep>/spec/requests/peliculas_spec.rb
require 'spec_helper'
describe "Peliculas" do
# test /peliculas
describe "list peliculas" do
before {pelicula = FactoryGirl.create(:pelicula, :titulo => "Trapito")}
it "should have content movie list" do
# Run the generator again with the --webrat flag if you want to use webrat methods/matchers
visit '/peliculas'
#response.status.should be(200)
#page.should have_content()
page.should have_content("Trapito")
end
end
end
<file_sep>/db/migrate/20120125162218_add_external_id_to_cines.rb
class AddExternalIdToCines < ActiveRecord::Migration
def change
add_column :cines, :external_id, :integer
end
end
<file_sep>/spec/controllers/peliculas_controller_spec.rb
require 'spec_helper'
describe PeliculasController do
describe "GET #index" do
it "assigns the requested Peliculas to @movies and @cartelera" do
peliculas = Factory.create(:estreno)
get :index
assigns(:movies).should eq([peliculas])
end
end
end
<file_sep>/db/migrate/20120211063000_add_latitude_to_cines.rb
class AddLatitudeToCines < ActiveRecord::Migration
def change
add_column :cines, :latitude, :float
add_column :cines, :longitude, :float
remove_column :cines, :lat
remove_column :cines, :long
end
end
<file_sep>/db/migrate/20120208225033_create_peliculas.rb
class CreatePeliculas < ActiveRecord::Migration
def change
create_table :peliculas do |t|
t.string :titulo
t.string :imagen
t.text :descripcion
t.string :titulo_original
t.string :pais
t.integer :anio
t.string :duracion
t.string :calificacion
t.date :estreno
t.string :web
t.string :genero
t.string :interpretes
t.string :director
t.string :guionista
t.string :fotografia
t.string :musica
t.timestamps
end
end
end
<file_sep>/app/admin/generos.rb
ActiveAdmin.register Genero do
end
<file_sep>/app/models/zona.rb
class Zona < ActiveRecord::Base
has_many :cines
end
<file_sep>/db/structure.sql
CREATE TABLE `active_admin_comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`resource_id` int(11) NOT NULL,
`resource_type` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`author_id` int(11) DEFAULT NULL,
`author_type` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`namespace` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index_admin_notes_on_resource_type_and_resource_id` (`resource_type`,`resource_id`),
KEY `index_active_admin_comments_on_namespace` (`namespace`),
KEY `index_active_admin_comments_on_author_type_and_author_id` (`author_type`,`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `admin_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`encrypted_password` varchar(128) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`reset_password_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`reset_password_sent_at` datetime DEFAULT NULL,
`remember_created_at` datetime DEFAULT NULL,
`sign_in_count` int(11) DEFAULT '0',
`current_sign_in_at` datetime DEFAULT NULL,
`last_sign_in_at` datetime DEFAULT NULL,
`current_sign_in_ip` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`last_sign_in_ip` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `index_admin_users_on_email` (`email`),
UNIQUE KEY `index_admin_users_on_reset_password_token` (`<PASSWORD>_password_token`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `cines` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`direccion` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`query` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`country` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`tel` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`zona_id` int(11) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`external_id` int(11) DEFAULT NULL,
`localidad` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`latitude` float DEFAULT NULL,
`longitude` float DEFAULT NULL,
`address` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6228 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `generos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `horarios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cine_id` int(11) DEFAULT NULL,
`pelicula_id` int(11) DEFAULT NULL,
`horas` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15948 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `peliculas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`titulo` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`imagen` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`descripcion` text COLLATE utf8_unicode_ci,
`titulo_original` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`pais` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`anio` int(11) DEFAULT NULL,
`duracion` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`calificacion` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`estreno` date DEFAULT NULL,
`web` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`genero` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`interpretes` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`director` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`guionista` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`fotografia` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`musica` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`external_id` int(11) DEFAULT NULL,
`es_estreno` tinyint(1) DEFAULT NULL,
`brief` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`imagen_chica` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=919 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`model` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`phone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`query` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`country` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `schema_migrations` (
`version` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `unique_schema_migrations` (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `zonas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`lat` decimal(10,0) DEFAULT NULL,
`long` decimal(10,0) DEFAULT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO schema_migrations (version) VALUES ('20120123200626');
INSERT INTO schema_migrations (version) VALUES ('20120123200627');
INSERT INTO schema_migrations (version) VALUES ('20120123230340');
INSERT INTO schema_migrations (version) VALUES ('20120123230616');
INSERT INTO schema_migrations (version) VALUES ('20120124192752');
INSERT INTO schema_migrations (version) VALUES ('20120124193113');
INSERT INTO schema_migrations (version) VALUES ('20120124193551');
INSERT INTO schema_migrations (version) VALUES ('20120125161129');
INSERT INTO schema_migrations (version) VALUES ('20120125162218');
INSERT INTO schema_migrations (version) VALUES ('20120208221008');
INSERT INTO schema_migrations (version) VALUES ('20120208225033');
INSERT INTO schema_migrations (version) VALUES ('20120208231534');
INSERT INTO schema_migrations (version) VALUES ('20120211025431');
INSERT INTO schema_migrations (version) VALUES ('20120211035657');
INSERT INTO schema_migrations (version) VALUES ('20120211040715');
INSERT INTO schema_migrations (version) VALUES ('20120211041409');
INSERT INTO schema_migrations (version) VALUES ('20120211055739');
INSERT INTO schema_migrations (version) VALUES ('20120211060055');
INSERT INTO schema_migrations (version) VALUES ('20120211063000');
INSERT INTO schema_migrations (version) VALUES ('20120211063824');
INSERT INTO schema_migrations (version) VALUES ('20120329000556');
INSERT INTO schema_migrations (version) VALUES ('20120329000703');<file_sep>/app/models/cine.rb
class Cine < ActiveRecord::Base
belongs_to :zona
has_many :horarios
has_many :peliculas, :through => :horarios
geocoded_by :address
after_validation :geocode
end
<file_sep>/db/migrate/20120211041409_add_brief_to_peliculas.rb
class AddBriefToPeliculas < ActiveRecord::Migration
def change
add_column :peliculas, :brief, :string
end
end
<file_sep>/app/admin/cines.rb
ActiveAdmin.register Cine do
end
<file_sep>/app/models/horario.rb
class Horario < ActiveRecord::Base
belongs_to :cine
belongs_to :pelicula
end
<file_sep>/db/migrate/20120211035657_add_external_id_to_peliculas.rb
class AddExternalIdToPeliculas < ActiveRecord::Migration
def change
add_column :peliculas, :external_id, :integer
end
end
<file_sep>/db/migrate/20120211063824_add_address_to_cines.rb
class AddAddressToCines < ActiveRecord::Migration
def change
add_column :cines, :address, :string
end
end
<file_sep>/app/controllers/cines_controller.rb
require 'open-uri'
require 'nokogiri'
require 'geocoder'
class CinesController < ApplicationController
##
# devuelve todos los cines
#
def all
@cines = Cine.find(:all, :select => ["nombre","id"])
render :json => @cines
end
##
# Inserta todos los cines y actualiza (from scratch)
#
def insertAll
# begin
# tengo romper la abstraccion porque quiero que empiece el id siempre desde 1
# si no bastaría con hacer Cine.delete_all
#ActiveRecord::Base.connection.execute("truncate table #{'cines'}") # no funciono en postgres
Cine.delete_all
Horario.delete_all
doc = Nokogiri::HTML(open("http://www.bases123.com.ar/eldia/cines/index.php"))
doc.xpath('//select[@id="cine"]/option').map do |info|
Cine.create(:nombre => info.text, :external_id => info.xpath('@value').text)
end
# borro el primer registro porque dice simplemente "+ Cines"
Cine.find(:first).destroy
# Para cada cine que cree actualizo su información
@cines = Cine.all
@cines.each do |cine|
# obtengo los datos del cine
doc = Nokogiri::HTML(open("http://www.bases123.com.ar/eldia/cines/cine.php?id=" + cine.external_id.to_s))
doc.xpath('/html/body/div/p[1]').map do |info|
data_cine = info.text.lines
dir = data_cine.to_a[2].gsub(/\n/,'')
loc = data_cine.to_a[3].gsub(/\n/,'')
c = Cine.find(cine.id)
c.attributes =
{
:direccion => dir,
:localidad => loc,
:address => dir + ', ' + loc.gsub(/\|/,', '),
}
c.save
end
# obtengo las peliculas que se proyectan en el cine y sus horario
# nota: el 1 misterioso que se agrega es porque los ids del sitio terra son los mismos que infojet pero con la diferencia
# que llevan conctenado un 1 al final
doc = Nokogiri::HTML(open("http://cartelera.terra.com.ar/carteleracine/sala/" + cine.external_id.to_s + "1") )
#@horarios = doc.xpath("//a[starts-with(@href,'pelicula.php')]/@href").map do |info|
doc.xpath("//div[@id='filmyhorarios']/ul/li").map do |info|
horarios = info.xpath("div[@class='horario fleft']").text.gsub(/\t|\n/, '')
pelicula_link = info.xpath("div[@class='film fleft']/h3/a/@href").text.split('/').to_a
# saco el 1 misterioso, para que el id vuelva a la normalidad
pelicula_id = pelicula_link[pelicula_link.count - 1].chop
@p = Pelicula.where(:external_id => pelicula_id).first
logger.debug "Peli: " + @p.class.to_s
if (@p != nil)
Horario.create(:cine_id => cine.id, :pelicula_id => @p.id, :horas => horarios )
end
end
end
@mensaje = "Los cines fueron creados y actualizados con éxito!"
# rescue Exception => exc
# logger.error("Message for the log file #{exc.message}")
# @mensaje = "Algo malo pasó :("
# end
render :text => @mensaje
end
def updateShowtimes
# Para cada cine que cree actualizo su información
Horario.delete_all
@cines = Cine.all
@cines.each do |cine|
# obtengo las peliculas que se proyectan en el cine y sus horario
# nota: el 1 misterioso que se agrega es porque los ids del sitio terra son los mismos que infojet pero con la diferencia
# que llevan conctenado un 1 al final
doc = Nokogiri::HTML(open("http://cartelera.terra.com.ar/carteleracine/sala/" + cine.external_id.to_s + "1") )
#@horarios = doc.xpath("//a[starts-with(@href,'pelicula.php')]/@href").map do |info|
doc.xpath("//div[@id='filmyhorarios']/ul/li").map do |info|
horarios = info.xpath("div[@class='horario fleft']").text.gsub(/\t|\n/, '')
pelicula_link = info.xpath("div[@class='film fleft']/h3/a/@href").text.split('/').to_a
# saco el 1 misterioso, para que el id vuelva a la normalidad
pelicula_id = pelicula_link[pelicula_link.count - 1].chop
@p = Pelicula.where(:external_id => pelicula_id).first
logger.debug "Peli: " + @p.class.to_s
if (@p != nil)
Horario.create(:cine_id => cine.id, :pelicula_id => @p.id, :horas => horarios )
end
end
end
@mensaje = "Los cines fueron actualizados con éxito!"
render :text => @mensaje
end
##
# Devuelve los datos de un cine
def get
@cine = Cine.find(params[:cine_id], :select => ["nombre","id","direccion","localidad"])
render :json => [ @cine, :peliculas => @cine.peliculas.select('titulo,horas,pelicula_id') ]
end
##
# Dada una coordenada devuelve donde estoy
#
def whereAmI
lat = params[:latitud]
long = params[:longitud]
@donde = Geocoder.search(lat + "," + long)[0]
render :json => {:direccion => @donde.address }
end
def whereToWatch
@cines = Cine.joins(:peliculas).where('peliculas.id = ' + params[:movie_id] )
render :json => @cines
end
##
# Dada una coordenada me devuelve los cines cercanos
#
def findNear
if !params[:latitud].nil? && !params[:longitud].nil?
if (!params[:movie_id].nil?)
@cines = Cine.near(params[:latitud].to_s + "," + params[:longitud].to_s, 10, :order => :distance).includes(:horarios)
@horarios = Array.new
@cines.each do |c|
c.horarios.each do |h|
if (h.pelicula_id.to_i == params[:movie_id].to_i)
#@horarios.push([:cine => c, :horarios => h.horas])
@horarios.push(c)
end
end
end
@cines = @horarios
else
@cines = Cine.near(params[:latitud].to_s + "," + params[:longitud].to_s, 10, :order => "distance")
end
else
@cines = Cine.all
end
render :json => @cines
end
end
<file_sep>/db/migrate/20120124192752_create_cines.rb
class CreateCines < ActiveRecord::Migration
def change
create_table :cines do |t|
t.string :nombre
t.string :direccion
t.string :query
t.string :country
t.string :tel
t.decimal :lat
t.decimal :long
t.integer :zona_id
t.timestamps
end
end
end
<file_sep>/app/admin/zonas.rb
ActiveAdmin.register Zona do
end
<file_sep>/spec/factories/peliculas.rb
FactoryGirl.define do
factory :pelicula, aliases: [:estreno] do |f|
f.titulo "Mingo y anibal contra los fantasmas"
f.descripcion "Una de las mejores fs del cine nacional despues de monguito"
f.brief "Una peli de minguito"
f.imagen "bases123.com.ar/fotos/cine/4766.jpg"
f.imagen_chica "bases123.com.ar/fotos/cine/4766ch.jpg"
f.es_estreno true
end
factory :cartelera, class: Pelicula do |f|
f.titulo "Trapito para los mas chiquitos"
f.descripcion "Algo de garcia ferre"
f.brief "espantapajaros"
f.imagen "bases123.com.ar/fotos/cine/4766.jpg"
f.imagen_chica "bases123.com.ar/fotos/cine/4766ch.jpg"
f.es_estreno false
end
end<file_sep>/app/admin/horarios.rb
ActiveAdmin.register Horario do
end
| a8074eb09c18a4024ee0e86329de771af80e5ec6 | [
"Markdown",
"SQL",
"Ruby"
] | 28 | Ruby | domecq/h1-movies-ws | bf6392eb141c2014f3c1afcb827fcbbcaa7d46e7 | 08fca7f45226318642581be9c5806d2f9ddd3cd4 |
refs/heads/master | <repo_name>FanaHOVA/custom-ruby-cops<file_sep>/README.md
# custom-ruby-cops
How to install custom Cops:
- Create a folder to store them in (In Rails I prefer `lib/rubocop/cop`)
- Save cop in that folder
- Require it in your `.rubocop.yml`:
```
require:
- ./lib/rubocop/cop/style/env_fetch.rb
```
<file_sep>/fetch_env_variables.rb
module RuboCop
module Cop
module Style
# This cop enforces using fetch on ENV variables
#
# @example
#
# # bad
# ENV['REDISTOGO_URL']
#
# # good
# ENV.fetch('REDISTOGO_URL')
class FetchEnvVariables < Cop
MSG = 'Use ENV.fetch when loading ENV variables.'.freeze
def investigate(processed_source)
processed_source.lines.each_with_index do |line, index|
next if line.starts_with('#')
next unless line =~ /ENV\[/
range = source_range(processed_source.buffer,
index + 1,
(line.rstrip.length)...(line.length))
add_offense(:message, range)
end
end
end
end
end
end
| f2397d3d42679142e8fd00fc0c657ca4e1c61bc2 | [
"Markdown",
"Ruby"
] | 2 | Markdown | FanaHOVA/custom-ruby-cops | 57c0fd988e1383d8409ad5fee0259db434ab2c01 | 085f1334b72ee2160ef9d62df655782f117fa009 |
refs/heads/master | <repo_name>sswati/WeatherApp<file_sep>/WeatherApp/Models/Forecast.cs
using Newtonsoft.Json;
namespace WeatherApp.Models
{
public class Forecast
{
[JsonProperty(PropertyName = "currently")]
public DayForecast Currently { get; set; }
[JsonProperty(PropertyName = "daily")]
public DailyForecast Daily { get; set; }
[JsonProperty(PropertyName = "timezone")]
public string TimeZone { get; set; }
}
}<file_sep>/WeatherApp/Models/DayForecast.cs
using System;
using Newtonsoft.Json;
namespace WeatherApp.Models
{
public class DayForecast
{
[JsonProperty(PropertyName = "icon")]
public string Icon { get; set; }
[JsonProperty(PropertyName = "summary")]
public string Summary { get; set; }
[JsonProperty(PropertyName = "temperatureHigh")]
public double? TemperatureHigh { get; set; }
[JsonProperty(PropertyName = "temperatureLow")]
public double? TemperatureLow { get; set; }
[JsonProperty(PropertyName = "time")]
public long TimeUnix { get; set; }
public DateTime Date => UnixTimestampToDateTime(TimeUnix);
public static DateTime UnixTimestampToDateTime(double unixTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (long)(unixTime * TimeSpan.TicksPerSecond);
return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
}
}
}<file_sep>/WeatherApp/Models/DailyForecast.cs
using System.Collections.Generic;
using Newtonsoft.Json;
namespace WeatherApp.Models
{
public class DailyForecast
{
// List of <see cref="WeatherApp.Models.DayForecast"/>, ordered by time, which together describe the weather conditions at the requested location over time.
[JsonProperty(PropertyName = "data")]
public List<DayForecast> Data { get; set; }
}
}<file_sep>/WeatherApp/Controllers/HomeController.cs
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WeatherApp.Models;
namespace WeatherApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var client = new RestClient("https://api.darksky.net/forecast/7857177b0392a79d68bd0820b76714dc/51.50642,-0.12721");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
string responseBody = response.Content;
var forecast = JsonConvert.DeserializeObject<Forecast>(responseBody);
var forcastData = forecast.Daily.Data.ToList();
return View(forcastData);
}
}
}
| 0ac4d87e0e3c007c73700ad00b1df039b7ac11b7 | [
"C#"
] | 4 | C# | sswati/WeatherApp | 59797c3f0611f036d25953b1a306f1a4fbcd0642 | 70dcf85111ceacbc4ac21af0ac86de27043be99e |
refs/heads/master | <repo_name>mangooLi/node-tms-trans<file_sep>/TRANS/parseCtr/demo.ts
{
id: string;
clientId: string;
operationType: AddOrderOperationType = AddOrderOperationType.Add;
// viaListData: { province: string, city: string, county: string, index: number }[] = [];
childOrderIndex: number = -1;
//附件
uploaderList: Array<attachmentList>;
baseImageUrl: string;
constructor(private $scope: IAddOrderViewModel, private areaService: IAreaService, private projectService: IProjectService, private customerRepresentativeService: ICustomerRepresentativeService, private clientService: IClientService, private linePriceService: ILinePriceService, private employeeService: IEmployeeService, private goodsTypeService: IGoodsTypeService, private fileUploader: any, private routeService: routeService, private $http: ng.IHttpService, private inquiryService: IInquiryService,
private goodsService: IGoodsService, private settleService: ISettleService, private valueService: IValueService, private $ngBootbox: BootboxService,
private orderService: IorderService, private $state: angular.ui.IStateService, private $location: ng.ILocationService, private commonService: ICommonService, private $q: ng.IQService) {
//附件配置
this.baseImageUrl = this.routeService.getBaseUrl() + "attachment/";
this.uploaderList = [];
if (this.$location.search().name == "copy") {
this.operationType = AddOrderOperationType.Copy;
this.orderName = "发货单复制新增";
this.id = this.$location.search().id;
} else if (this.$location.search().name == "edit") {
this.operationType = AddOrderOperationType.Edit;
this.orderName = "发货单编辑重下";
this.id = this.$location.search().id;
} else if (this.$location.search().name == "inquiry") {
this.operationType = AddOrderOperationType.Inquiry;
this.orderName = "发货单复制新增";
this.id = this.$location.search().id;
}
this.init();
}
init(): void {
this.planOfficer = JSON.parse(window.localStorage.getItem("loginData")).realName;
this.attachmentUploader = new this.fileUploader({ url: this.baseImageUrl });
this.attachmentUploader.filters.push({ name: 'imageFilter', fn: this.commonService.ownFilter });
this.attachmentUploader.onSuccessItem = (fileItem: any, response: any) => { this.onSuccessItem(fileItem.file.name, response.filePath, 1, fileItem.file); }
this.attachmentUploader.onDelete = (item) => {
this.commonService.onDelete(item, this.uploaderList);
};
this.businessOfficerDropDown = [];
this.customerServiceOfficerDropDown = [];
this.dispatchOfficerDropDown = [];
this.goodsTypeDropDown = [];
this.goodsDropDown = [];
this.settleDropDown = [];
this.urgencyUnitDropDown = [];
this.goodsNumUnitDropDown = [];
this.settleTypeDropDown = [];
this.includeTaxDropDown = [];
this.projectTotalUnitDropDown = [];
this.carTypeDropDown = [];
this.carLengthDropDown = [];
this.carriageWayDropDown = [];
this.orderId = "";
this.urgency = null;
this.urgencyUnit = "1";
this.businessOfficer = null;
this.customerServiceOfficer = null;
this.dispatchOfficer = null;
this.clientId = "";
this.consignorId = "";
this.consignorName = "";
this.shipPriceContent = "";
this.carType = "";
this.carLength = "";
this.carriageWay = "";
this.loadingResult = "";
this.shipProvinceCode = "";
this.shipCityCode = "";
this.shipAreaCode = "";
this.shipAddress = "";
this.deliverProvinceCode = "";
this.deliverCityCode = "";
this.deliverAreaCode = "";
this.viaCity = "-1"
this.viaProvince = "-1";
this.viaArea = "-1";
this.deliverAddress = "";
this.shipTime = "";
this.arriveTime = "";
this.mileage = null;
this.goodsTypeId = "";
this.goodsTypeName = "";
this.goodsId = "";
this.goodsName = "";
this.goodsNum = null;
this.goodsNumUnit = "";
this.goodsNumTwo = null;
this.goodsNumTwoUnit = "";
this.tonRange = "";
this.receivablePrice = null;
this.receivablePriceUnit = "";
this.receivableTotal = null;
this.settleType = "";
this.includeTax = "";
this.receivableRemarks = "";
this.settleId = "";
this.settleName = "";
this.projectId = "";
this.projectCode = "";
this.projectName = "";
this.shipOrderId = "";
this.takeGoodsCompanyId = "";
this.takeGoodsCompanyName = "";
this.consignee = "";
this.consigneePhone = "";
this.projectTotal = null;
this.projectTotalUnit = "";
this.childOrderLine = [];
//按钮
this.showAddChildOrderBtn = true;
this.showAddOrderBtn = true;
this.orderSave = this.orderSave;
//数组
this.viaListData = [];
this.orderLine = [];
this.ischecked = false;
this.isRequired = true;
this.initDateTimePicker();
this.loadData();
//共有事件
this.loadDropDown();//加载枚举
this.addVia = this.addVia;
this.deleteVia = this.deleteVia;
this.onClientSelected = this.onClientSelected;
this.addOrderLine = this.addOrderLine;
this.addChildOrderLine = this.addChildOrderLine;
this.saveOrderLine = this.saveOrderLine;
this.saveChildOrderLine = this.saveChildOrderLine;
this.editOrderLine = this.editOrderLine;
this.editChildOrderLine = this.editChildOrderLine;
this.deleteOrderLine = this.deleteOrderLine;
this.deleteChildOrderLine = this.deleteChildOrderLine;
this.shipBack = this.shipBack;
//change事件
this.changeGoodsTypeEvent = this.changeGoodsTypeEvent;
// this.changeGoodsGetTonRangeList = this.changeGoodsGetTonRangeList;
this.changeTonRangeGetReceivableEvent = this.changeTonRangeGetReceivableEvent;
//自动补全事件
this.onClientAutoComplate = this.onClientAutoComplate;
this.onConsignorAutoComplate = this.onConsignorAutoComplate;
this.onConsignorSelected = this.onConsignorSelected;
this.onGoodsNameAutoComplate = this.onGoodsNameAutoComplate;
this.onGoodsNameSelected = this.onGoodsNameSelected;
this.onProjectAutoComplate = this.onProjectAutoComplate;
this.onProjectSelected = this.onProjectSelected;
this.onsettleSelected = this.onsettleSelected;
this.onSettleAutoComplate = this.onSettleAutoComplate;
}
loadData(): void {
if (this.operationType == AddOrderOperationType.Add) {
this.setShipAndArriveTime();
} else if (this.operationType == AddOrderOperationType.Copy) {
this.getOrderInfo();
this.getChildInfo();
this.setShipAndArriveTime();
this.ischecked = true;
} else if (this.operationType == AddOrderOperationType.Edit) {
this.getOrderInfo();
this.isRequired = true;
this.getChlderInfoEdit();
this.ischecked = true;
} else if (this.operationType == AddOrderOperationType.Inquiry) {
this.getInquiryInfo();
this.setShipAndArriveTime();
this.ischecked = true;
}
}
addVia = () => {
if (this.viaProvince == "-1" || this.viaCity == "-1" || this.viaArea == "-1") {
this.$ngBootbox.alert("请填写完整的中转地");
return;
}
let index = this.viaListData.length + 1;
//data
this.viaListData.push({
index: index++,
// province: this.viaProvince,
// city: this.viaCity,
// county: this.viaArea
province: $(".province option:selected")[2].innerHTML,
city: $(".city option:selected")[2].innerHTML,
county: $(".area option:selected")[2].innerHTML
});
}
deleteVia = (index: number) => {
this.viaListData.splice(index - 1, 1);
//重置index
this.viaListData.forEach((item, index) => {
this.viaListData[index].index = index + 1;
});
}
addOrderLine = (type: boolean) => {
if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return; };
if (!type) {
if (this.orderLine.length > 0) {
this.$ngBootbox.alert("只能添加一条总线路信息");
return;
}
}
if (this.goodsId == "") {
this.$ngBootbox.alert("请选择货物");
return;
}
if ($("#goodsId_value").val() == "") {
this.$ngBootbox.alert("请填写货物名称"); return;
};
// if (this.shipProvinceCode == "-1" || this.shipCityCode == "-1" || this.shipAreaCode == "-1"
// || this.deliverProvinceCode == "-1" || this.deliverCityCode == "-1" || this.deliverAreaCode == "-1") {
// this.$ngBootbox.alert("请填写完成地址");
// return;
// }
this.isClientCanEdit = false;
// let ol = this.orderLine;
let sc = this.$scope;
this.orderLine = [{
shipDetail: $(".province option:selected")[0].innerHTML + $(".city option:selected")[0].innerHTML + $(".area option:selected")[0].innerHTML + sc.shipAddress,
deliverDetail: $(".province option:selected")[1].innerHTML + $(".city option:selected")[1].innerHTML + $(".area option:selected")[1].innerHTML + sc.deliverAddress,
viaListData: this.viaListData.map((value) => value),
shipProvinceCode: sc.shipProvinceCode,
shipCityCode: sc.shipCityCode,
shipAreaCode: sc.shipAreaCode,
shipAddress: sc.shipAddress,
deliverProvinceCode: sc.deliverProvinceCode,
deliverCityCode: sc.deliverCityCode,
deliverAreaCode: sc.deliverAreaCode,
deliverAddress: sc.deliverAddress,
shipTime: $("#dataTime").val(),
arriveTime: $("#dataTimeEnd").val(),
mileage: sc.mileage,
goodsTypeId: sc.goodsTypeId,
goodsTypeName: $("#goodsType option:selected").text(),
goodsId: sc.goodsId,
goodsName: $("#goodsId_value").val(),
// goodsName: sc.goodsName,
goodsNum: sc.goodsNum,
goodsNumUnit: sc.goodsNumUnit,
goodsNumUnitStr: $("#goodsNumUnit option:selected").text(),
goodsNumTwo: sc.goodsNumTwo,
goodsNumTwoUnit: sc.goodsNumTwoUnit,
tonRange: $("#tonRange option:selected").text(),
}]
}
deleteOrderLine = () => {
if (this.childOrderLine.length == 0) {
this.isClientCanEdit = true;
}
this.orderLine.length = 0;
this.showAddOrderBtn = true;
}
editOrderLine = () => {
//赋值参数
this.showAddOrderBtn = false;
let ol = this.orderLine[0];
let sc = this.$scope;
// this.loadSettleDropDown();
this.loadGoodsTypeDropDown();
// this.loadGoodsDropDown(ol.goodsTypeId);
this.viaListData = ol.viaListData.map((value) => value);
sc.shipProvinceCode = ol.shipProvinceCode;
sc.shipCityCode = ol.shipCityCode;
sc.shipAreaCode = ol.shipAreaCode;
sc.shipAddress = ol.shipAddress;
sc.deliverProvinceCode = ol.deliverProvinceCode;
sc.deliverCityCode = ol.deliverCityCode;
sc.deliverAreaCode = ol.deliverAreaCode;
sc.deliverAddress = ol.deliverAddress;
this.getProvinceList();
sc.shipTime = ol.shipTime;
sc.arriveTime = ol.arriveTime;
$("#dataTime").val(ol.shipTime);
$("#dataTimeEnd").val(ol.arriveTime);
sc.mileage = ol.mileage;
sc.goodsTypeId = ol.goodsTypeId;
sc.goodsTypeName = ol.goodsTypeName;
$("#goodsId_value").val(ol.goodsName);
sc.goodsId = ol.goodsId;
sc.goodsName = ol.goodsName;
sc.goodsNum = ol.goodsNum;
sc.goodsNumUnit = ol.goodsNumUnit;
sc.goodsNumTwo = ol.goodsNumTwo;
sc.goodsNumTwoUnit = ol.goodsNumTwoUnit;
this.getTonRangeList();
sc.tonRange = ol.tonRange;
}
getProvinceList = () => {
this.areaService.getCity(this.shipProvinceCode).then(res => {
this.shipCityList = res.data.list;
});
this.areaService.getCounty(this.shipCityCode).then(res => {
this.shipAreaList = res.data.list;
});
this.areaService.getCity(this.deliverProvinceCode).then(res => {
this.deliverCityList = res.data.list;
});
this.areaService.getCounty(this.deliverCityCode).then(res => {
this.deliverAreaList = res.data.list;
});
}
saveOrderLine = (type: boolean) => {
this.addOrderLine(type);
this.showAddOrderBtn = true;
}
addChildOrderLine = () => {
if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return; };
var settle = $("#reckoner_value").val();
if (this.settleId == "" || settle == "") {
this.$ngBootbox.alert("请选择结算单位");
return;
}
if ($("#goodsId_value").val() == "") {
this.$ngBootbox.alert("请填写货物名称"); return;
};
// if (this.shipProvinceCode == "-1" || this.shipCityCode == "-1" || this.shipAreaCode == "-1"
// || this.deliverProvinceCode == "-1" || this.deliverCityCode == "-1" || this.deliverAreaCode == "-1") {
// this.$ngBootbox.alert("请填写完整地址");
// return;
// }
//缺表单验证
var sc = this.$scope;
this.childOrderLine.push({
index: this.childOrderLine.length + 1,
shipProvinceCode: sc.shipProvinceCode,
shipCityCode: sc.shipCityCode,
shipAreaCode: sc.shipAreaCode,
shipAddress: sc.shipAddress,
viaListData: this.viaListData.map((value) => value),
deliverProvinceCode: sc.deliverProvinceCode,
deliverCityCode: sc.deliverCityCode,
deliverAreaCode: sc.deliverAreaCode,
deliverAddress: sc.deliverAddress,
shipTime: $("#dataTime").val(),
arriveTime: $("#dataTimeEnd").val(),
mileage: sc.mileage,
goodsTypeId: sc.goodsTypeId,
goodsTypeName: $("#goodsType option:selected").text(),
goodsId: sc.goodsId,
goodsName: $("#goodsId_value").val(),
goodsNum: sc.goodsNum,
goodsNumUnit: sc.goodsNumUnit,
goodsNumTwo: sc.goodsNumTwo,
goodsNumTwoUnit: sc.goodsNumTwoUnit,
tonRange: $("#tonRange option:selected").text(),
receivablePrice: sc.receivablePrice,
receivablePriceUnitStr: $("#receivablePriceUnit option:selected").text(),
receivablePriceUnit: sc.receivablePriceUnit,
receivableTotal: sc.receivableTotal,
settleType: sc.settleType,
settleTypeStr: $("#settleType option:selected").text(),
includeTax: sc.includeTax,
receivableRemarks: sc.receivableRemarks,
settleId: sc.settleId,
reckoner: $("#reckoner_value").val(),
projectid: sc.projectId,
projectCode: sc.projectCode,
// projectName: sc.projectName,
projectName: $("#project_value").val(),
shipOrderId: sc.shipOrderId,
takeGoodsCompanyId: sc.takeGoodsCompanyId,
takeGoodsCompanyName: sc.takeGoodsCompanyName,
consignee: sc.consignee,
consigneePhone: sc.consigneePhone,
projectTotal: sc.projectTotal,
projectTotalUnit: sc.projectTotalUnit,
goodsNumUnitStr: $("#goodsNumUnit option:selected").text(),
shipDetail: $(".province option:selected")[0].innerHTML + $(".city option:selected")[0].innerHTML + $(".area option:selected")[0].innerHTML + sc.shipAddress,
deliverDetail: $(".province option:selected")[1].innerHTML + $(".city option:selected")[1].innerHTML + $(".area option:selected")[1].innerHTML + sc.deliverAddress,
});
}
deleteChildOrderLine = (index: number) => {
this.childOrderLine.splice(index - 1, 1);
this.childOrderLine.forEach((item, index) => {
this.childOrderLine[index].index = index + 1;
});
this.showAddChildOrderBtn = true;
}
editChildOrderLine = (index: number) => {
this.showAddChildOrderBtn = false;
if (index > this.childOrderLine.length) {
return;
}
var sc = this.$scope;
var ol;
this.childOrderLine.forEach((item, indexS) => {
if (item.index === index) {
ol = item;
return false;
}
});
//下拉
// this.loadSettleDropDown();
this.loadGoodsTypeDropDown();
// this.loadGoodsDropDown(ol.goodsTypeId);
this.childOrderIndex = index;
var newViaList = [];
ol.viaListData.forEach((item, index) => {
newViaList.push(item)
})
this.viaListData = newViaList;
sc.shipProvinceCode = ol.shipProvinceCode;
sc.shipCityCode = ol.shipCityCode;
sc.shipAreaCode = ol.shipAreaCode;
sc.shipAddress = ol.shipAddress;
sc.deliverProvinceCode = ol.deliverProvinceCode;
sc.deliverCityCode = ol.deliverCityCode;
sc.deliverAreaCode = ol.deliverAreaCode;
sc.deliverAddress = ol.deliverAddress;
this.getProvinceList();
sc.shipTime = ol.shipTime;
sc.arriveTime = ol.arriveTime;
$("#dataTime").val(ol.shipTime)
$("#dataTimeEnd").val(ol.arriveTime)
sc.mileage = ol.mileage;
sc.goodsTypeId = ol.goodsTypeId;
sc.goodsTypeName = ol.goodsTypeName;
$("#goodsId_value").val(ol.goodsName);
sc.goodsId = ol.goodsId;
sc.goodsName = ol.goodsName;
sc.goodsNum = ol.goodsNum;
sc.goodsNumUnit = ol.goodsNumUnit;
this.getTonRangeList();
sc.tonRange = ol.tonRange;
sc.goodsNumTwo = ol.goodsNumTwo;
sc.goodsNumTwoUnit = ol.goodsNumTwoUnit;
sc.receivablePrice = ol.receivablePrice;
sc.receivablePriceUnit = ol.receivablePriceUnit;
sc.receivableTotal = ol.receivableTotal;
sc.settleType = ol.settleType;
sc.includeTax = ol.includeTax;
sc.receivableRemarks = ol.receivableRemarks;
sc.settleId = ol.settleId;
$("#reckoner_value").val(ol.reckoner);
sc.reckoner = ol.reckoner;
sc.settleName = ol.reckoner;
sc.projectId = ol.projectid;
sc.projectCode = ol.projectCode;
// sc.projectName = ol.projectName;
$("#project_value").val(ol.projectName);
sc.shipOrderId = ol.shipOrderId;
sc.takeGoodsCompanyId = ol.takeGoodsCompanyId;
sc.takeGoodsCompanyName = ol.takeGoodsCompanyName;
sc.consignee = ol.consignee;
sc.consigneePhone = ol.consigneePhone;
sc.projectTotal = ol.projectTotal;
sc.projectTotalUnit = ol.projectTotalUnit;
}
saveChildOrderLine = () => {
if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return; };
if (this.childOrderIndex > this.childOrderLine.length || this.childOrderIndex < 0) {
return;
}
var settleName = $("#reckoner_value").val();
if (this.settleId == "" || settleName == "") {
this.$ngBootbox.alert("请选择结算单位");
return;
}
// if (this.shipProvinceCode == "-1" || this.shipCityCode == "-1" || this.shipAreaCode == "-1"
// || this.deliverProvinceCode == "-1" || this.deliverCityCode == "-1" || this.deliverAreaCode == "-1") {
// this.$ngBootbox.alert("请填写完整地址");
// return;
// }
//缺表单验证
let sc = this.$scope;
// let ol = this.childOrderLine[this.childOrderIndex - 1];
var ol;
this.childOrderLine.forEach((item, indexS) => {
if (item.index === this.childOrderIndex) {
ol = item;
return false;
}
});
var newViaList = [];
this.viaListData.forEach((item, index) => {
newViaList.push(item)
})
ol.viaListData = newViaList;
ol.shipProvinceCode = sc.shipProvinceCode;
ol.shipCityCode = sc.shipCityCode;
ol.shipAreaCode = sc.shipAreaCode;
ol.shipAddress = sc.shipAddress;
ol.deliverProvinceCode = sc.deliverProvinceCode;
ol.deliverCityCode = sc.deliverCityCode;
ol.deliverAreaCode = sc.deliverAreaCode;
ol.deliverAddress = sc.deliverAddress;
ol.shipDetail = $(".province option:selected")[0].innerHTML + $(".city option:selected")[0].innerHTML + $(".area option:selected")[0].innerHTML + sc.shipAddress;
ol.deliverDetail = $(".province option:selected")[1].innerHTML + $(".city option:selected")[1].innerHTML + $(".area option:selected")[1].innerHTML + sc.deliverAddress;
ol.goodsNumUnitStr = $("#goodsNumUnit option:selected").text();
ol.tonRange = $("#tonRange option:selected").text();
ol.settleTypeStr = $("#settleType option:selected").text();
ol.reckoner = $("#reckoner_value").val();
ol.goodsTypeName = $("#goodsType option:selected").text();
ol.goodsName = $("#goodsId_value").val();
ol.shipTime = $("#dataTime").val();
ol.arriveTime = $("#dataTimeEnd").val();
ol.mileage = sc.mileage;
ol.goodsTypeId = sc.goodsTypeId;
ol.goodsId = sc.goodsId;
ol.goodsNum = sc.goodsNum;
ol.goodsNumUnit = sc.goodsNumUnit;
ol.goodsNumTwo = sc.goodsNumTwo;
ol.goodsNumTwoUnit = sc.goodsNumTwoUnit;
ol.tonRange = sc.tonRange;
ol.receivablePrice = sc.receivablePrice;
ol.receivablePriceUnit = sc.receivablePriceUnit;
ol.receivablePriceUnitStr = $("#receivablePriceUnit option:selected").text();
ol.receivableTotal = sc.receivableTotal;
ol.settleType = sc.settleType;
ol.includeTax = sc.includeTax;
ol.receivableRemarks = sc.receivableRemarks;
ol.settleId = sc.settleId;
ol.projectid = sc.projectId;
ol.projectCode = sc.projectCode;
ol.projectName = $("#project_value").val();
ol.shipOrderId = sc.shipOrderId;
ol.takeGoodsCompanyId = sc.takeGoodsCompanyId;
ol.takeGoodsCompanyName = sc.takeGoodsCompanyName;
ol.consignee = sc.consignee;
ol.consigneePhone = sc.consigneePhone;
ol.projectTotal = sc.projectTotal;
ol.projectTotalUnit = sc.projectTotalUnit;
this.showAddChildOrderBtn = true;
}
orderSave = () => {
if (this.operationType == AddOrderOperationType.Add || this.operationType == AddOrderOperationType.Copy || this.operationType == AddOrderOperationType.Inquiry) {
if (!$("#orderForm").valid()) { return };
if (this.orderLine.length == 0) {
this.$ngBootbox.alert("必须存在一条总线路");
return;
}
if (this.childOrderLine.length == 0) {
this.$ngBootbox.alert("必须存在一条子线路");
return;
}
// if (this.enabledSaveBtn == false) {
// return;
// }
if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return; };
this.enabledSaveBtn = true;
let orderChild: orderChildVM[] = [];
this.childOrderLine.forEach((item) => {
orderChild.push({
// orderId: item.orderId,
shipProvince: item.shipProvinceCode,
shipCity: item.shipCityCode,
shipArea: item.shipAreaCode,
shipAddress: item.shipAddress,
viaAddressList: item.viaListData,
deliverProvince: item.deliverProvinceCode,
deliverCity: item.deliverCityCode,
deliverArea: item.deliverAreaCode,
deliverAddress: item.deliverAddress,
shipTime: item.shipTime,
arriveTime: item.arriveTime,
mileage: item.mileage,
goodsTypeId: item.goodsTypeId,
goodsType: item.goodsTypeName,
goodsId: item.goodsId,
goodsName: item.goodsName,
goodsNum: item.goodsNum,
goodsNumUnit: item.goodsNumUnit ? item.goodsNumUnit : "",
goodsNumTwo: item.goodsNumTwo,
goodsNumUnitTwo: item.goodsNumTwoUnit ? item.goodsNumTwoUnit : "",
tonRange: item.tonRange,
receivablePrice: item.receivablePrice,
receivablePriceUnit: item.receivablePriceUnit,
receivableTotal: item.receivableTotal,
settleType: item.settleType,
includeTax: item.includeTax,
receivableRemarks: item.receivableRemarks,
settleId: item.settleId,
reckoner: item.reckoner,
projectId: item.projectid,
projectCode: item.projectCode,
projectName: item.projectName,
shipOrderId: item.shipOrderId,
takeGoodsCompanyId: item.takeGoodsCompanyId,
takeGoodsCompany: item.takeGoodsCompanyName,
consignee: item.consignee,
consigneePhone: item.consigneePhone,
projectTotal: item.projectTotal,
projectTotalUnit: item.projectTotalUnit
});
});
this.$ngBootbox.confirm("确定发布此单?").then(e => {
var dispatchOfficerPhone = "";
this.dispatchOfficerDropDown.forEach((item, index) => {
if (item.id === this.dispatchOfficerId) {
dispatchOfficerPhone = item.phoneNumber;
}
});
///附件类型改换。带后台更改后删除
var uploaderList = []
this.uploaderList.forEach((item, index) => {
uploaderList.push([item.attachmentName, item.attachmentPath]);
})
var ol = this.orderLine[0];
this.clientService.getDetail(this.clientId).then((res) => {
var clientCornet = res.data.cornet;
let contractNumber = res.data.contractNumber;
this.orderService.add(
"",
this.urgency,
this.urgencyUnit,
this.businessOfficerId,
this.customerServiceOfficerId,
this.dispatchOfficerId,
this.clientId,
clientCornet,
this.consignorId,
this.shipPriceContent,
this.carType,
this.carLength,
this.carriageWay,
this.loadingResult,
// this.uploaderList,附件类型改换。带后台更改后删除
uploaderList,
this.orderRemarks,
orderChild,
ol.viaListData.map(value => { return { province: value.province, city: value.city, county: value.county, details: "" } }),
ol.shipProvinceCode,
ol.shipCityCode,
ol.shipAreaCode,
ol.shipAddress,
ol.deliverProvinceCode,
ol.deliverCityCode,
ol.deliverAreaCode,
ol.deliverAddress,
ol.shipTime,
ol.arriveTime,
ol.mileage,
ol.goodsTypeId,
ol.goodsTypeName,
ol.goodsId,
ol.goodsName,
ol.goodsNum,
ol.goodsNumUnit,
ol.goodsNumTwo,
ol.goodsNumTwoUnit,
ol.tonRange,
$("#dispatchOfficerId option:selected").text(),
dispatchOfficerPhone,
$("#businessOfficerId option:selected").text(),
$("#customerServiceOfficerId option:selected").text(),
this.planOfficer,
$("#client_value").val(),
null,
contractNumber
).then(result => {
this.enabledSaveBtn = false;
this.$state.go("app.order.orderAddList", { name: "orderAddList" });
}, error => { this.enabledSaveBtn = false; });
}, () => { this.enabledSaveBtn = false; });
}, () => { this.enabledSaveBtn = false; });
} else if (this.operationType == AddOrderOperationType.Edit) {
//缺少验证
if (!this.commonService.timeJudge($("#dataTime").val(), $("#dataTimeEnd").val())) { return };
this.enabledSaveBtn = true;
let ol = this.orderLine[0];
let sc = this.$scope;
let orderChild: orderChildVM[] = [];
this.childOrderLine.forEach((item) => {
orderChild.push({
orderId: item.orderId,
shipProvince: item.shipProvinceCode,
shipCity: item.shipCityCode,
shipArea: item.shipAreaCode,
shipAddress: item.shipAddress,
viaAddressList: item.viaListData,
deliverProvince: item.deliverProvinceCode,
deliverCity: item.deliverCityCode,
deliverArea: item.deliverAreaCode,
deliverAddress: item.deliverAddress,
shipTime: item.shipTime,
arriveTime: item.arriveTime,
mileage: item.mileage,
goodsTypeId: item.goodsTypeId,
goodsType: item.goodsTypeName,
goodsId: item.goodsId,
goodsName: item.goodsName,
goodsNum: item.goodsNum,
goodsNumUnit: item.goodsNumUnit ? item.goodsNumUnit : "",
goodsNumTwo: item.goodsNumTwo,
goodsNumUnitTwo: item.goodsNumTwoUnit ? item.goodsNumTwoUnit : "",
tonRange: item.tonRange,
receivablePrice: item.receivablePrice,
receivablePriceUnit: item.receivablePriceUnit,
receivableTotal: item.receivableTotal,
settleType: item.settleType,
includeTax: item.includeTax,
receivableRemarks: item.receivableRemarks,
settleId: item.settleId,
reckoner: item.reckoner,
projectId: item.projectid,
projectCode: item.projectCode,
projectName: item.projectName,
shipOrderId: item.shipOrderId,
takeGoodsCompanyId: item.takeGoodsCompanyId,
takeGoodsCompany: item.takeGoodsCompanyName,
consignee: item.consignee,
consigneePhone: item.consigneePhone,
projectTotal: item.projectTotal,
projectTotalUnit: item.projectTotalUnit
});
});
this.$ngBootbox.confirm("确定发布此单?").then(() => {
///附件类型改换。带后台更改后删除
var uploaderList = []
this.uploaderList.forEach((item, index) => {
uploaderList.push([item.attachmentName, item.attachmentPath]);
})
this.orderService.edit(
this.id,
this.orderId,
this.urgency,
this.urgencyUnit,
this.businessOfficerId,
this.customerServiceOfficerId,
this.dispatchOfficerId,
this.clientId,
this.consignorId,
this.shipPriceContent,
this.carType,
this.carLength,
this.carriageWay,
this.loadingResult,
// this.uploaderList,
uploaderList,
this.orderRemarks,
orderChild,
ol.viaListData,
ol.shipProvinceCode,
ol.shipCityCode,
ol.shipAreaCode,
ol.shipAddress,
ol.deliverProvinceCode,
ol.deliverCityCode,
ol.deliverAreaCode,
ol.deliverAddress,
ol.shipTime,
ol.arriveTime,
ol.mileage,
ol.goodsTypeId,
ol.goodsTypeName,
ol.goodsId,
ol.goodsName,
ol.goodsNum,
ol.goodsNumUnit,
ol.goodsNumTwo,
ol.goodsNumTwoUnit,
ol.tonRange,
$("#dispatchOfficerId option:selected").text(),
this.getDispatcherPhone(),
$("#businessOfficerId option:selected").text(),
$("#customerServiceOfficerId option:selected").text(),
this.planOfficer,
$("#client_value").val()
).then(result => {
this.enabledSaveBtn = false;
this.$state.go("app.order.orderAddList", { name: "orderAddList" });
}, () => { this.enabledSaveBtn = false; });
}, () => { this.enabledSaveBtn = false; })
}
}
setShipAndArriveTime(): void {
let time = new Date();
let defaultTime = new Date(time.getFullYear(), time.getMonth(), time.getDate() + 1, 17, 0);
this.shipTime = String(this.commonService.transformTime(new Date(time.setHours(16, 0, 0)), "yyyy.MM.dd HH:mm"));
this.arriveTime = String(this.commonService.transformTime(defaultTime, "yyyy.MM.dd HH:mm"));
}
getDispatcherPhone(): string {
var dispatchOfficerPhone = "";
this.dispatchOfficerDropDown.forEach((item, index) => {
if (item.id === this.dispatchOfficerId) {
dispatchOfficerPhone = item.phoneNumber;
}
});
return dispatchOfficerPhone
}
initDateTimePicker(): void {
$('#opendataTime').click(function () {
$('#dataTime').datetimepicker('show');
});
$('#opendataTimeEnd').click(function () {
$('#dataTimeEnd').datetimepicker('show');
});
}
loadDropDown(): void {
//枚举
this.urgencyUnitDropDown = this.valueService.getUrgencyUnitList().list;
this.goodsNumUnitDropDown = this.valueService.getGoodQuantityUnitList().list;
this.priceUnitDropDown = this.valueService.getPriceUnitList().list;
this.settleTypeDropDown = this.valueService.getSettlementTypeList().list;
this.includeTaxDropDown = this.valueService.getLinePriceTypeList().list;
this.projectTotalUnitDropDown = this.valueService.getGoodQuantityUnitList().list;
this.carTypeDropDown = this.valueService.getCarTypeList().list;
this.carLengthDropDown = this.valueService.getCarLengthList().list;
this.carriageWayDropDown = this.valueService.getCarriageTypeList().list;
// this.goodsNumUnitDropDown = this.valueService.getGoodQuantityUnitList().list;
//专员加载
this.loadBusinessOfficeerDropDown();
this.loadCustomerServiceOfficerDropDown();
this.loadDispatchOfficerDropDown();
}
loadBusinessOfficeerDropDown(): void {
this.employeeService.getList(CommissionerType.BusinessAffairs.toString(), "", "", "", "", true, 0, -1).then(result => {
this.businessOfficerDropDown = result.data.list;
});
}
loadCustomerServiceOfficerDropDown(): void {
this.employeeService.getList(CommissionerType.CustomerService.toString(), "", "", "", "", true, 0, -1).then(result => {
this.customerServiceOfficerDropDown = result.data.list;
});
}
loadDispatchOfficerDropDown(): void {
this.employeeService.getList(CommissionerType.Dispatch.toString(), "", "", "", "", true, 0, -1).then(result => {
this.dispatchOfficerDropDown = result.data.list;
});
}
loadGoodsTypeDropDown(): void {
this.goodsTypeService.getList(this.clientId, "", 0, -1).then(result => {
this.goodsTypeDropDown = result.data.list;
if (!this.clientId || this.clientId === "") { this.goodsDropDown.length = 0; this.goodsTypeId = ""; this.tonRangeDropDown.length = 0; };
});
}
// loadGoodsDropDown = (goodsTypeId: string) => {
// // this.goodsService.getList(this.clientId, "", goodsTypeId, 0, -1).then(result => {
// // this.goodsDropDown = result.data.list;
// // if (!this.goodsTypeId || this.goodsTypeId === "") { this.goodsDropDown.length = 0; this.goodsId = ""; this.tonRangeDropDown.length = 0; };
// // });
// // this.goodsService.getList(this.clientId, "", goodsTypeId, 0, -1).then(result => {
// // if (this.$location.search().name != "add") {
// // $("#goodsId_value").val(result.data.list[0].name)
// // }
// // if (!this.goodsTypeId || this.goodsTypeId === "") { this.goodsDropDown.length = 0; this.goodsId = ""; this.tonRangeDropDown.length = 0; };
// // })
// }
// loadSettleDropDown(): void {
// this.settleService.getList(this.clientId, "", "", true, 0, 1).then(result => {
// // this.settleDropDown = result.data.list;
// if (this.$location.search().name == "add") {
// this.settleId = result.data.list[0].id;
// $("#reckoner_value").val(result.data.list[0].name)
// this.reckoner = result.data.list[0].name;
// }
// });
// }
onClientSelected = (data: angucomplete<ClientListItemResponse>) => {
if (data) {
this.consignorId = "";
this.goodsTypeId = "";
this.goodsDropDown.length = 0;
this.projectId = "";
this.clientId = data.description.id;
this.clientId = data.description.id;
// $("#consignor_value").val("");
// $("#reckoner_value").val("");
this.$broadcast('angucomplete-alt:clearInput', 'consignor');
this.$broadcast('angucomplete-alt:clearInput', 'goodsId');
this.$broadcast('angucomplete-alt:clearInput', 'reckoner');
this.reckoner = "";
this.settleId = "";
this.loadGoodsTypeDropDown();
// this.loadSettleDropDown();
} else { return };
}
onClientAutoComplate = (value: string) => {
return this.clientService.getList(value, "", "", "", "", 0, 5).then(res => {
return res.data.list;
});
}
onConsignorAutoComplate = (value: string) => {
if (!this.clientId) { return; };
return this.customerRepresentativeService.getList(this.clientId, value, "", 0, 5).then(res => {
return res.data.list;
})
}
onConsignorSelected = (selected: angucomplete<CustomerRepresentativeListItemResponse>) => {
if (selected) {
this.consignorPhone = selected.description.phoneNumber;
this.consignorId = selected.description.id;
} else {
this.consignorPhone = "";
this.consignorId = "";
}
}
onsettleSelected = (selected: angucomplete<SettleListItemResponse>) => {
if (selected) {
this.settleId = selected.description.id;
this.reckoner = selected.description.name;
$("#reckoner_value").val(selected.description.name)
} else {
// $("#reckoner_value").val("");
// this.reckoner = "";
this.settleId = "";
}
}
onSettleAutoComplate = (value: string) => {
if (!this.clientId) { return; };
return this.settleService.getList(this.clientId, value, "", true, 0, 5).then(result => {
return result.data.list;
});
}
onProjectAutoComplate = (value: string) => {
if (!this.clientId) { return; };
return this.projectService.getList(this.clientId, "", "", 0, 5).then(res => {
return res.data.list;
})
}
changeGoodsTypeEvent = () => {
// this.loadGoodsDropDown(this.goodsTypeId);
// this.changeGoodsGetTonRangeList = this.changeGoodsGetTonRangeList;
this.$broadcast('angucomplete-alt:clearInput', 'goodsId');
// $("#goodsId_value").val("");
// this.goodsName = "";
// this.goodsId = "";
};
onGoodsNameAutoComplate = (value: string) => {
// console.log($("#goodsId_value").val());
var deferred = this.$q.defer();
if (!this.clientId || !this.goodsTypeId) {
// deferred.resolve("well done!");
} else {
return this.goodsService.getList(this.clientId, value, this.goodsTypeId, 0, 30).then(res => {
return res.data.list;
})
}
return deferred.promise;
//console.log(this.$q.reject)
}
onGoodsNameSelected = (selected: angucomplete<GoodsListItemResponse>) => {
if (selected) {
this.goodsName = selected.description.name;
this.goodsId = selected.description.id;
$("#goodsId_value").val(selected.description.name);
//获取吨位范围判断未加
this.getTonRangeList();
} else {
this.goodsName = "";
this.goodsId = "";
}
}
// changeGoodsGetTonRangeList = () => {
// //获取吨位范围判断未加
// this.getTonRangeList();
// }
getTonRangeList = () => {
this.linePriceService.getList(this.clientId, this.goodsTypeId, "1", this.shipProvinceCode, this.shipCityCode, this.shipAreaCode, this.deliverProvinceCode, this.deliverCityCode, this.deliverAreaCode, "", this.goodsId, "", "", 0, -1).then(res => {
this.tonRangeDropDown = res.data.list;
if (!this.clientId || this.clientId === "" || this.goodsId === "" || !this.goodsId || this.goodsTypeId === "" || !this.goodsTypeId) {
this.tonRangeDropDown.length = 0;
}
});
}
changeTonRangeGetReceivableEvent = () => {
this.linePriceService.getList(this.clientId, this.goodsTypeId, "1", this.shipProvinceCode, this.shipCityCode, this.shipAreaCode, this.deliverProvinceCode, this.deliverCityCode, this.deliverAreaCode, this.tonRange, this.goodsId, "", "", 0, -1).then(res => {
if (res.data.list.length > 0) {
this.linePriceService.getDetail(res.data.list[0].id).then(res => {
this.receivablePrice = res.data.price;
this.receivablePriceUnit = res.data.priceUnit;
this.settleType = res.data.setleWay;
this.includeTax = res.data.priceType;
})
}
});
}
onProjectSelected = (select: angucomplete<ProjectListItemResponse>) => {
if (select) {
this.getProjectData(select.description.id)
}
}
getProjectData(id: string): void {
this.projectService.getDetail(id).then(res => {
this.projectTotal = String(res.data.maxValue);
this.projectTotalUnit = res.data.maxUnit;
this.projectCode = res.data.projectCode;
this.takeGoodsCompanyName = res.data.settleName;
this.consignee = res.data.settleContact;
this.consigneePhone = res.data.settlePhone;
//获取结算单id
this.settleService.getList(this.clientId, res.data.settleName, "", true, 0, -1).then(res => {
this.takeGoodsCompanyId = res.data.list[0].id;
});
});
}
onSuccessItem = (fileName: string, filePath: string, tag: number, file?: any) => {
file.fileId = filePath;
let attachment = {
attachmentId: "",
attachmentName: fileName,
attachmentPath: filePath,
attachmentTag: ""
};
this.uploaderList.push(attachment);
}
getOrderInfo(): void {
this.orderService.detail(this.id).then(res => {
//公共信息
let sc = this.$scope;
let data = res.data;
//基本信息
sc.urgency = data.urgency;
sc.urgencyUnit = data.urgencyUnit;
sc.businessOfficerId = data.businessOfficerId;
sc.customerServiceOfficerId = data.customerServiceOfficerId;
sc.dispatchOfficerId = data.dispatchOfficerId;
sc.clientId = data.clientId;
this.clientId = data.clientId;
sc.clientName = data.clientName;
sc.consignorId = data.consignorId;
sc.consignorName = data.consignorName;
sc.consignorPhone = data.consignorPhone;
sc.shipPriceContent = data.shipPriceContent;
//所需车辆信息
sc.carType = data.carType;
sc.carLength = data.carLength;
sc.carriageWay = data.carriageWay;
sc.loadingResult = data.loadingResult;
//下拉
// this.loadSettleDropDown();
this.loadGoodsTypeDropDown();
//订单备注
sc.orderRemarks = data.remarks;
//只有edit下才能获取附件
if (this.operationType == AddOrderOperationType.Edit) {
sc.planOfficer = JSON.parse(window.localStorage.getItem("loginData")).realName;
//订单编号
this.orderId = res.data.orderId;
//附件
res.data.attachment.forEach((item, index) => {
this.commonService.showFileItem(item, this.attachmentUploader);
// this.showFileItem(item, this.attachmentUploader);
});
// this.uploaderList = res.data.attachment;
res.data.attachment.forEach((item, index) => {
this.uploaderList.push({
attachmentId: item[0],
attachmentName: item[1],
attachmentPath: item[2],
attachmentTag: item[3]
})
});
//总单视图
let ol = this.orderLine[0];
var newviaListData = [];
data.viaList.forEach((item, index) => {
newviaListData.push({
province: item.province,
city: item.city,
county: item.county,
index: index + 1
});
});
//
var quantityOfGoods = "";
this.goodsNumUnitDropDown.forEach((itme, index) => {
if (data.goodsNumUnit == itme.value) {
quantityOfGoods = itme.text;
}
})
this.orderLine = [{
shipProvinceCode: data.shipProvince,
shipCityCode: data.shipCity,
shipAreaCode: data.shipArea,
shipAddress: data.shipDetail,
deliverProvinceCode: data.deliverProvince,
deliverCityCode: data.deliverCity,
deliverAreaCode: data.deliverArea,
deliverAddress: data.deliverDetail,
//问题
viaListData: newviaListData,
shipTime: data.shipTime,
arriveTime: data.arriveTime,
mileage: data.mileage,
//货物信息
goodsTypeId: data.goodsTypeId,
goodsId: data.goodsId,
tonRange: data.tonRange,
goodsNum: data.goodsNum,
goodsNumUnit: data.goodsNumUnit,
goodsNumTwo: data.goodsNumTwo,
goodsNumTwoUnit: data.goodsNumUnitTwo,
goodsTypeName: data.goodsType,
goodsName: data.goodsName,
goodsNumUnitStr: quantityOfGoods,
shipDetail: data.shipAddress,
deliverDetail: data.deliverAddress
}]
} else
//copy
{
//线路信息
sc.shipProvinceCode = data.shipProvince;
sc.shipCityCode = data.shipCity;
sc.shipAreaCode = data.shipArea;
sc.shipAddress = data.shipDetail;
sc.deliverProvinceCode = data.deliverProvince;
sc.deliverCityCode = data.deliverCity;
sc.deliverAreaCode = data.deliverArea;
sc.deliverAddress = data.deliverDetail;
//中转地
data.viaList.forEach((item, index) => {
this.viaListData.push({
province: item.province,
city: item.city,
county: item.county,
index: index + 1
});
});
// sc.shipTime = data.shipTime;
// sc.arriveTime = data.arriveTime;
sc.mileage = data.mileage;
//货物信息
$("#goodsId_value").val(data.goodsName);
sc.goodsName = data.goodsName;
sc.goodsTypeId = data.goodsTypeId;
sc.goodsId = data.goodsId;
sc.tonRange = data.tonRange;
sc.goodsNum = data.goodsNum;
sc.goodsNumUnit = data.goodsNumUnit;
sc.goodsNumTwo = data.goodsNumTwo;
sc.goodsNumTwoUnit = data.goodsNumUnitTwo;
//获取下拉数据
// this.loadGoodsDropDown(data.goodsTypeId);
this.getTonRangeList();
}
});
}
getChildInfo(): void {
//可优化:获取子单详情需拿订单id拿子单列表,在拿子单id获取详情(后台可直接传入子单id)
this.orderService.orderChildList(this.id).then(res => {
this.orderService.orderChild(res.data.list[0].id).then(result => {
//子单数据
let sc = this.$scope;
let data = result.data;
//应收价格信息
sc.receivablePrice = data.receivablePrice;
sc.receivablePriceUnit = data.receivablePriceUnit;
sc.receivableTotal = data.receivableTotal;
sc.settleType = data.settleType;
sc.includeTax = data.includeTax;
sc.receivableRemarks = data.receivableRemarks;
sc.settleId = data.settleId;
$("#reckoner_value").val(data.reckoner);
sc.reckoner = data.reckoner;
//工程信息
sc.projectName = data.projectName;
sc.projectId = data.projectId;
sc.projectCode = data.projectCode;
sc.projectTotal = data.projectTotal;
sc.projectTotalUnit = data.projectTotalUnit;
sc.takeGoodsCompanyName = data.takeGoodsCompany;
sc.takeGoodsCompanyId = data.takeGoodsCompanyId;
sc.consignee = data.consignee;
sc.consigneePhone = data.consigneePhone;
sc.shipOrderId = data.shipOrderId;
});
});
}
getInquiryInfo(): void {
this.inquiryService.getDetail(this.id).then(res => {
let sc = this.$scope;
let data = res.data;
//基本信息
sc.urgency = data.urgency;
sc.urgencyUnit = data.urgencyUnit;
sc.planOfficer = JSON.parse(window.localStorage.getItem("loginData")).realName;
sc.businessOfficerId = data.businessOfficerId;
sc.customerServiceOfficerId = data.customerServiceOfficerId;
sc.dispatchOfficerId = data.dispatchOfficerId;
sc.clientId = data.clientId;
this.clientId = data.clientId;
sc.clientName = data.clientName;
sc.consignorId = data.consignorId;
sc.consignorName = data.consignorName;
sc.consignorPhone = data.consignorPhone;
sc.shipPriceContent = data.content;
let childData = res.data.inquiryChildList[0];
//线路信息
sc.shipProvinceCode = childData.startProvince;
sc.shipCityCode = childData.startCity;
sc.shipAreaCode = childData.startArea;
sc.shipAddress = childData.startAddress;
sc.deliverProvinceCode = childData.endProvince;
sc.deliverCityCode = childData.endCity;
sc.deliverAreaCode = childData.endArea;
sc.deliverAddress = childData.endAddress;
// sc.shipTime = childData.plannedArrivalTime;
// sc.arriveTime = childData.plannedDeliveryTime;
sc.mileage = childData.mileage;
//货物信息
sc.goodsTypeId = childData.goodsTypeId;
sc.goodsId = childData.goodsId;
sc.goodsName = childData.goodsName;
sc.goodsNum = childData.goodsQuantity;
sc.goodsNumUnit = childData.goodsQuantityUnit;
//所需车辆信息
sc.carType = childData.carType;
sc.carLength = childData.carLength;
sc.carriageWay = childData.carrierCategory;
sc.loadingResult = childData.loadingEffect;
//订单备注
// sc.orderRemarks = childData.remarks;
//获取下拉数据
this.loadGoodsTypeDropDown();
// this.loadGoodsDropDown(childData.goodsTypeId);
this.getTonRangeList();
// this.loadSettleDropDown();
});
}
getChlderInfoEdit = () => {
this.orderService.orderChildList(this.id).then(res => {
//获取详情
res.data.list.forEach((item, index) => {
var childData = item;
this.orderService.orderChild(item.id).then((result => {
let data = result.data;
var newViaData = [];
//中转地
data.viaAddressList.forEach((item, index) => {
newViaData.push({
province: item.province,
city: item.city,
county: item.county,
index: index
});
});
var quantityOfGoods = "";
this.goodsNumUnitDropDown.forEach((itme, index) => {
if (data.goodsNumUnit == itme.value) {
quantityOfGoods = itme.text;
}
});
var receivablePriceUnitStr = "";
this.priceUnitDropDown.forEach((itme, index) => {
if (data.receivablePriceUnit == itme.value) {
receivablePriceUnitStr = itme.text;
}
})
//子线路
this.childOrderLine.push({
index: index + 1,
shipProvinceCode: data.shipProvince,
shipCityCode: data.shipCity,
shipAreaCode: data.shipArea,
shipAddress: data.shipAddress,
viaListData: newViaData,
deliverProvinceCode: data.deliverProvince,
deliverCityCode: data.deliverCity,
deliverAreaCode: data.deliverArea,
deliverAddress: data.deliverAddress,
shipTime: data.shipTime,
arriveTime: data.arriveTime,
mileage: data.mileage,
goodsTypeId: data.goodsTypeId,
goodsTypeName: data.goodsType,
goodsId: data.goodsId,
goodsName: data.goodsName,
goodsNum: data.goodsNum,
goodsNumUnit: data.goodsNumUnit,
goodsNumTwo: data.goodsNumTwo,
goodsNumUnitStr: quantityOfGoods,
goodsNumTwoUnit: data.goodsNumUnitTwo,
tonRange: data.tonRange,
receivablePrice: data.receivablePrice,
receivablePriceUnit: data.receivablePriceUnit,
receivablePriceUnitStr: receivablePriceUnitStr,
receivableTotal: data.receivableTotal,
settleType: data.settleType,
includeTax: data.includeTax,
receivableRemarks: data.receivableRemarks,
settleId: data.settleId,
reckoner: item.settleName,
projectid: data.projectId,
projectCode: data.projectCode,
projectName: data.projectName,
shipOrderId: data.shipOrderId,
takeGoodsCompanyId: data.takeGoodsCompanyId,
takeGoodsCompanyName: data.takeGoodsCompany,
consignee: data.consignee,
consigneePhone: data.consigneePhone,
projectTotal: data.projectTotal,
projectTotalUnit: data.projectTotalUnit,
settleTypeStr: childData.settlementType,
shipDetail: childData.shipGoodsAddress,
deliverDetail: childData.deliveryAddress
});
}));
});
})
}
shipBack(): void {
// window.history.back();
this.$state.go("app.order.orderAddList", { name: "orderAddList" });
}
}<file_sep>/TRANS/parseRoute.js
//从ng1的路由配置文件中爬取对应的html和controller文件
const fs=require('fs');
const path=require('path');
function parseRoute(){
let routeStr=fs.readFileSync(path.join(__dirname,'./sourceFile/config.router.ts'),'utf-8');
// console.log(routeStr);
let routeList=routeStr.match(/.state\((.|\r\n)+?\}(\s\r\n)?\)/g);
// console.log(routeList[3]);
return routeList.map(item=>{
return getPath(item)
})
// getPath(routeList[6]);
}
function getPath(item){
// console.log(item);
if(!item.match(/resolve/)){return {str:item}};
let htmlPath=item.match(/templateUrl(.|\r\n)*?(\..+?html)/)[2];
let url=item.match(/url\s*\:\s*\"?\'?(.+?)(\'|\")/)[1];
let ctrPath=item.match(/\.load\(\"?\'?(\..*?js)\"?\'?\)/)[1];
return {
// str:item,
url:url,
htmlPath:htmlPath,
ctrPath:ctrPath
}
// console.log(htmlPath,url,ctrPath)
}
module.exports.parseRoute=parseRoute;<file_sep>/TRANS/parseCtr/parseCtr.js
var fs=require('fs');
var parseCtrStr= require('./getKeysFromCTS').parseCtrStr
const {log}=console;
function parseCtr(ctrPath){
let data=fs.readFileSync(ctrPath,'utf-8');
let temp=data;
temp=temp.replace(/\/\*\*(.|\r\n)+?\*\//g,'');
let classStr=temp.match(/class(.|\r\n)+\}/)[0]
let classContentStr=classStr.match(/\{(.|\r\n)+\}/)[0];//{}包裹的类的内容
let classContentStrTrim=classContentStr.replace(/(\r\n|\s)/g,'')
let ctrNoScope=classContentStr.replace(/this\.\$scope\./g,'this.');
parseCtrStr(ctrNoScope)
}
// parseCtr('./orderController.add.ts')
module.exports.parseCtr=parseCtr;
<file_sep>/TRANS/baseCom.ts
import { Component, OnInit } from '@angular/core';
import {DataService} from '../../service/data.service';
import {CommonService} from '../../service/common.service';
declare var echarts:any;
declare var $:any;
declare var bootbox:any;
@Component({
selector: 'app-tms-cargo',
templateUrl: './tms-cargo.component.html',
styleUrls: ['./tms-cargo.component.css']
})
export class componentName implements OnInit<file_sep>/TRANS/sourceFile/config.router.ts
/**
* 路由配置
*/
angular.module("tms")
.run(
['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]
)
.config(["$stateProvider","$urlRouterProvider",($stateProvider:angular.ui.IStateProvider, $urlRouterProvider:angular.ui.IUrlRouterProvider) => {
$urlRouterProvider.otherwise("/app/blank");
$stateProvider
.state("app", {
abstract: true,
url:"/app",
templateUrl:"../src/tpl/blank.html",
})
.state("app.blank",{
url:"/blank",
templateUrl:"../src/tpl/main.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/main.js");
}]
}
})
.state("login", {
url:"/login",
template:'<div ui-view class="fade-in-right-big smooth"></div>'
})
.state("login.in", {
url:"/in",
templateUrl:"./src/tpl/tms_login.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/login.js");
}]
}
})
// system
.state('app.system', {
url: '/system',
template: '<div ui-view></div>'
})
/******************************
* 设置//splite
******************************/
.state("app.system.authorizationManagent", {//权限管理
url:"/authorizationManagent",
templateUrl:"./src/tpl/table_authorizationManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/authorizationManagentController.js");
}]
}
})
.state("app.system.authorizationTypeManagent", {//权限分类管理
url:"/authorizationTypeManagent",
templateUrl:"./src/tpl/table_authorizationTypeManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/authorizationTypeManagentController.js");
}]
}
})
.state("app.system.departmentManagent", {//部门管理
url:"/departmentManagent",
templateUrl:"./src/tpl/table_departmentManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/departmentManagentController.js");
}]
}
})
.state("app.system.employeeManagent", {//员工管理
url:"/employeeManagent",
templateUrl:"./src/tpl/table_employeeManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/employeeManagentController.js");
}]
}
})
.state("app.system.userManagent", {//用户管理
url:"/userManagent",
templateUrl:"./src/tpl/table_userManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/userManagentController.js");
}]
}
})
.state("app.system.userGroupManagent", {//用户组管理
url:"/userGroupManagent",
templateUrl:"./src/tpl/table_userGroupManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/userGroupManagentController.js");
}]
}
})
.state("app.system.logisticsManagent", {//物流方
url:"/logisticsManagent",
templateUrl:"./src/tpl/table_logisticsManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/logisticsManagentController.js");
}]
}
})
.state("app.system.userinfo_edit", {//个人信息管理
url:"/userInfoManage",
templateUrl:"./src/tpl/table_userinfoManage.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/userInfoManageController.js");
}]
}
})
// mes
.state('app.mes', {
url: '/mes',
template: '<div ui-view class="fade-in-up"></div>'
})
.state("app.mes.messageList", {//消息
url:"/messageList",
templateUrl:"./src/tpl/messageList.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/messageController.js");
}]
}
})
//没有权限
.state("app.noauthority", {//没有权限
url:"/noauthority",
templateUrl:"./src/tpl/noauthority.html",
})
/**********************************************
* 客户模块
**********************************************/
// client
.state('app.client', {
url: '/client',
template: '<div ui-view class="fade-in-up"></div>'
})
.state("app.client.client_Managent", {//客户管理
url:"/clientController",
templateUrl:"./src/tpl/table_clientManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/clientManagentController.js");
}]
}
})
.state("app.client.client_edit", {//编辑客户
url:"/client_edit/?id",
templateUrl:"./src/tpl/page_clientManagent_edit.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/clientManagentController.edit.js");
}]
}
})
.state("app.client.client_add", {//添加客户
url:"/client_add",
templateUrl:"./src/tpl/page_clientManagent_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/clientManagentController.add.js");
}]
}
})
.state("app.client.customerrepresentative_manage", {//客户代表
url:"/customerRepresentativeManagent",
templateUrl:"./src/tpl/page_customerRepresentativeManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/customerRepresentativeManagentController.js");
}]
}
})
.state("app.client.goodstype_manage", {//货物分类管理
url:"/goodsTypeManagent",
templateUrl:"./src/tpl/page_goodsTypeManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/goodsTypeManagentController.js");
}]
}
})
.state("app.client.goods_manage", {//货物管理
url:"/goodsManagent",
templateUrl:"./src/tpl/page_goodsManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/goodsManagentController.js");
}]
}
})
.state("app.client.settleManagent", { //结算方管理
url: "/settleManagent",
templateUrl: "./src/tpl/page_settleManagent.html",
resolve: {
load: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/system/settleManagentController.js");
}]
}
})
.state("app.client.lineprice_manage", {//线路报价
url:"/lineprice_manage",
templateUrl:"./src/tpl/page_linePriceManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/linePriceManagentController.js");
}]
}
})
.state("app.client.projectManagent", { //工程管理
url: "/projectManagent",
templateUrl: "./src/tpl/page_projectManagent.html",
resolve: {
load: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/projectManagentController.js");
}]
}
})
.state("app.client.clientinfo_manage", {//客户资料
url:"/clientinfo_manage",
templateUrl:"./src/tpl/page_clientInfoManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/tms/clientInfoManagentController.js");
}]
}
})
/*************************************
* 车厂模块
*************************************/
// car
.state('app.car', {
url: '/car',
template: '<div ui-view class="fade-in-up"></div>'
})
.state("app.car.carManagent", {//车辆管理
url:"/carManagent",
templateUrl:"./src/tpl/table_carManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/carManagentController.js");
}]
}
})
.state("app.car.carManagent_edit", {//车辆管理-编辑
url:"/carEditManagent/?id",
templateUrl:"./src/tpl/page_carManagent_edit.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/carManagentController.edit.js");
}]
}
})
.state('app.car.carManagent_Add', {//车辆管理-添加
url: '/carAddManagent',
templateUrl: './src/tpl/page_carManagent_add.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carManagentController.add.js');
}
]
}
})
//车辆附件管理
.state('app.car.carAttachmentEdit', {
url: '/carAttachmentEdit',
templateUrl: './src/tpl/page_carAttachmentManagent_edit.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carAttachmentManagentController.js');
}
]
}
})
//车辆银行卡管理
.state('app.car.carBankCardManagent', {
url: '/carBankCardManagent',
templateUrl: './src/tpl/page_carBankManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carBankCardManagentController.js');
}
]
}
})
//车辆主营线路管理
.state('app.car.carRouteManagent', {
url: '/carRouteManagent',
templateUrl: './src/tpl/page_carRouteManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carRouteManagentController.js');
}
]
}
})
//车辆交易记录
.state('app.car.carTradingRecord', {
url: '/carTradingRecord',
templateUrl: './src/tpl/page_carTradingRecord.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carTradingRecordController.js');
}
]
}
})
.state("app.car.carEvaluateManagent", {//车辆评价(诚信记录)
url:"/carEvaluateManagent",
templateUrl:"./src/tpl/page_carEvaluate.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/carEvaluateController.js");
}]
}
})
.state("app.car.carLocation", {//车辆定位
url:"/carLocation?id?carcode?phone?shipAddress?deliverAddress",
templateUrl:"./src/tpl/page_carLocation.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/carLocationController.js");
}]
}
})
.state('app.car.BDNPLocation', { //车辆---北斗定位
url: '/cars_BDNPLocation?name',
templateUrl: './src/tpl/page_cars_BDNPLocation.html',
params: { 'id': null, 'shipTime': null, 'carcode': null,'phone': null, 'realArrivalTime': null, 'shipAddress': null, 'deliverAddress': null },
resolve: {
load: ['$ocLazyLoad', ($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/carPark/car/BDNPLocationController.js")
})
}]
}
})
//车辆定位--定位轨迹点
.state("app.car.carStrackController", {//车辆定位
url:"/carStrackController?carcode?phone?shipTime?shipAddress?deliverAddress",
templateUrl:"./src/tpl/page_carStrack.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/carStrackController.js");
}]
}
})
// eva
.state('app.eva', {
url: '/eva',
template: '<div ui-view class="fade-in-up"></div>'
})
//车辆评价
.state('app.eva.evaluate_manage', {
url: '/evaluate_manage',
templateUrl: './src/tpl/page_carComment.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/car/carCommentController.js');
}
]
}
})
/********************************************
* 承运商模块
********************************************/
// carrier
.state('app.carrier', {
url: '/carrier',
template: '<div ui-view class="fade-in-up"></div>'
})
//承运商附件
.state("app.carrier.carrierAttachment", {
url:"/carrierAttachment",
templateUrl:"./src/tpl/page_carrierAttachmentManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/carrier/carrierAttachmentManagentController.js");
}]
}
})
.state('app.carrier.carrierManagent', {//承运商管理
url: '/carrierManagent',
templateUrl: './src/tpl/page_carrierManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierManagentController.js');
}
]
}
})
.state('app.carrier.carrierManagentAdd', {//添加承运商
url: '/carrierManagentAdd',
templateUrl: './src/tpl/page_carrierManagent_add.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierManagentController.add.js');
}
]
}
})
.state('app.carrier.carrierManagentEdit', {//编辑承运商
url: '/carrierManagentEdit?id',
templateUrl: './src/tpl/page_carrierManagent_edit.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierManagentController.edit.js');
}
]
}
})
.state('app.carrier.carrierBankEdit', {//承运商账户信息
url: '/carrierBankEdit',
templateUrl: './src/tpl/page_carrierBankCardManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierBankCardManagentController.js');
}
]
}
})
// 承运商下--主营线路管理
.state('app.carrier.carrierRouteManagent', {
url: '/carrierRouteManagent',
templateUrl: './src/tpl/page_carrierRouteManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierRouteManagentController.js');
}
]
}
})
.state('app.carrier.carrieCarEdit', {//承运商所属车辆
url: '/carrierCarEdit',
templateUrl: './src/tpl/page_carrierCarManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/carPark/carrier/carrierCarManagentController.js');
}
]
}
})
/**************************************
* 询价模块
**************************************/
//inquiry
.state('app.inquiry',{
url:'/inquiry',
template:'<div ui-view class="fade-in-up"></div>'
})
.state("app.inquiry.inquiryList", {//询价单新增列表
url:"/inquiryList?name",
templateUrl:"./src/tpl/table_inquiry.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryController.js");
}]
}
})
.state("app.inquiry.inquiryAdd", {//询价单新增(详情)复用页面---编辑重下
url:"/inquiryAdd?id?name",
templateUrl:"./src/tpl/page_inquiry_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryController.add.js");
}]
}
})
.state("app.inquiry.InquiryAccept", {//询价单受理
url:"/InquiryAccept?name",
templateUrl:"./src/tpl/table_inquiryAccepted.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryAcceptedController.js");
}]
}
})
.state("app.inquiry.inquiryAudit", {//询价单审核
url:"/inquiryAuditController?name",
templateUrl:"./src/tpl/table_inquiryAudit.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryAuditController.js");
}]
}
})
.state("app.inquiry.Inquiry_pay", {//询价单详情/应付报价/应收报价/审核详情1/审核详情2
url:"/Inquiry_pay/?id?name",
templateUrl:"./src/tpl/page_inquiry_pay.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryRatifyController.js");
}]
}
})
.state("app.inquiry.Inquiry_receivable", {//询价应收报价
url:"/inquiryReceive?name",
templateUrl:"./src/tpl/table_inquiryReceive.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryReceiveController.js");
}]
}
})
.state("app.inquiry.inquiryManagent", {//询价单管理列表
url:"/inquiryManagent?name",
templateUrl:"./src/tpl/table_inquiryManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/inquiry/inquiryManagentController.js");
}]
}
})
/******************************************
* 订单模块
******************************************/
//order
.state('app.order',{
url:'/order',
template:'<div ui-view class="fade-in-up"></div>'
})
.state("app.order.orderAddList", {//发货单新增列表
url:"/orderAddList?name",
templateUrl:"./src/tpl/table_order.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderController.js");
}]
}
})
.state("app.order.orderAdd", {//发货单新增详情-复制-编辑重下-询价新增订单
url:"/orderAdd?id?name",
templateUrl:"./src/tpl/page_order_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderController.add.js");
}]
}
})
.state("app.order.orderAcceptList", {//发货单受理列表
url:"/orderAccept?name",
templateUrl:"./src/tpl/table_orderAccept.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderAcceptController.js");
}]
}
})
.state("app.order.orderAcceptDetail", {//发货单受理整车
url:"/orderAcceptDetail?id?carrierId?name?type",
templateUrl:"./src/tpl/page_orderAccept_detail.html",
resolve: {
load: ['$ocLazyLoad', ($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/order/orderAcceptController.detail.js");
})
}]
}
})
.state("app.order.orderAcceptBulk", {//发货单受理零担
url:"/orderAcceptBulk?id?carrierId?name?type",
templateUrl:"./src/tpl/page_orderAccept_breakBulk.html",
resolve: {
load: ['$ocLazyLoad', ($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/order/orderAcceptController.breakBulk.js");
})
}]
}
})
//发货单审核(整车)
.state("app.order.orderAuditDetailController", {
url:"/orderAuditDetailController?id?name?type",
templateUrl:"./src/tpl/page_orderAudit_detail.html",
resolve: {
load: ['$ocLazyLoad',($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/order/orderAuditController.detail.js");
})
}]
}
})
//发货单审核(零担)
.state("app.order.orderAuditBreakBulkDetailController", {
url:"/orderAuditBreakBulkDetailController?id?name?type",
templateUrl:"./src/tpl/page_orderAudit_breakBulk.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderAuditController.breakBulk.js");
}]
}
})
.state("app.order.orderRegisterList", {//发货单登记列表
url:"/orderRegisterList?name",
templateUrl:"./src/tpl/table_orderRegister.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController.js");
}]
}
})
.state("app.order.orderRegisterDetail", {//发货单登记详情(整车)
url:"/orderRegisterDetail?id?contractStatus?name?type?carId",
templateUrl:"./src/tpl/page_orderRegister_detail.html",
resolve: {
load: ['$ocLazyLoad', ($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController_detail.js")
})
}]
}
})
.state("app.order.orderRegisterBulk", {//发货单登记详情(零担)
url:"/orderRegisterBulk?id?contractStatus?name?type?carId",
templateUrl:"./src/tpl/page_orderRegister_breakBulk.html",
resolve: {
load: ['$ocLazyLoad',($ocLazyLoad)=> {
(<any>window).BMap_loadScriptTime = (new Date).getTime();
return $ocLazyLoad.load('../vendor/getLocation.js').then(function(){
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController_breakBulk.js");
})
}]
}
})
.state("app.order.orderCostApplication", {//费用申领
url:"/orderCostApplication?id",
templateUrl:"./src/tpl/page_orderRegister_costApplication.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController_costApplication.js");
}]
}
})
.state("app.order.orderRegisterReceivable", {//应收登记(整单)
url:"/orderRegisterReceivable?id",
templateUrl:"./src/tpl/page_orderRegister_receivable.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController_receivable.js");
}]
}
})
.state("app.order.orderRegisterReceivableBulk", {//应收登记(零担)
url:"/orderRegisterReceivableBulk?id",
templateUrl:"./src/tpl/page_orderRegister_receivable_breakBulk.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderRegisterController_receivable_breakBulk.js");
}]
}
})
//发货单管理
.state("app.order.orderDeliverManage", {
url:"/orderDeliverManage?name",
templateUrl:"./src/tpl/table_orderDeliverManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderDeliverManagentController.js");
}]
}
})
//发货单管理(零担)
.state("app.order.LTL_detail", {
url:"/LTL_detail?id?name?type?skip",
templateUrl:"./src/tpl/page_orderDeliverManagent_breakBulk.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderDeliverManagentController_breakBulk.js");
}]
}
})
//发货单管理(整担)
.state("app.order.invoice_detail", {
url:"/orderDeliverManage_detail?id?name?type?skip",
templateUrl:"./src/tpl/page_orderDeliverManagent_detail.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderDeliverManagentController_detail.js");
}]
}
})
//发货单审核列表
.state("app.order.orderAuditController", {
url:"/orderAuditController?name",
templateUrl:"./src/tpl/page_order_Audit.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderAuditController.js");
}]
}
})
//订单管理
.state("app.order.orderManagentController", {
url:"/orderManagentController?name",
templateUrl:"./src/tpl/table_orderManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderManagentController.js");
}]
}
})
//订单管理详情
.state("app.order.orderManagentDetailController", {
url:"/orderManagentDetailController?id?name",
templateUrl:"./src/tpl/page_indent_detail.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/orderManagentController.detail.js");
}]
}
})
/**************************************
* 应收模块
**************************************/
//receivable
.state('app.receivable',{
url:'/receivable',
template:'<div ui-view class="fade-in-up"></div>'
})
//应收结算
.state("app.receivable.receivableClose", {
url:"/receivableClose?name",
templateUrl:"./src/tpl/table_receivableClose.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableCloseController.js");
}]
}
})
//应收账单管理
.state("app.receivable.receivableBill", {
url:"/receivableBillManage?settle",
templateUrl:"./src/tpl/table_receivableBillManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableBillManagentController.js");
}]
}
})
//应收账单管理----收入明细
.state("app.receivable.income_detail", {
url:"/receivableBillManage_income?id?name",
templateUrl:"./src/tpl/page_receivableBillManagent_income.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableBillManagentController_income.js");
}]
}
})
//应收账单管理----账单管理
.state("app.receivable.bill_admin", {
url:"/receivableBillManage_admin?id?",
templateUrl:"./src/tpl/page_receivableBillManagent_managent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableBillManagentController_managent.js");
}]
}
})
//应收账单管理----账单管理-详情(应收结算/应收对账 共用)
.state("app.receivable.receivable_reconcile", {
url:"/receivable_reconcile/?carrierOrderId?orderId?orderChildId?Id?settleStatus?totalPrice?price?unit?receivableCode?name",
templateUrl:"./src/tpl/page_receivableClose_reconciliation.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableCloseController_reconciliation.js");
}]
}
})
//应收账单管理----账单管理---新增应收订单(应收结算/新增应收单)
.state("app.receivable.receivable_order_add", {
url:"/receivable_order_add/?id",
templateUrl:"./src/tpl/page_receivable_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableController.add.js");
}]
}
})
//应收统计
.state("app.receivable.receivable_census", {
url:"/receivable_census?settle",
templateUrl:"./src/tpl/table_receivableStatistics.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableStatisticsController.js");
}]
}
})
//应收统计---财务明细
.state("app.receivable.finance_excel", {
url:"/finance_excel?settle?startTime?endTime",
templateUrl:"./src/tpl/page_receivableStatistics_finance_excel.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableStatisticsController_export.js");
}]
}
})
//应收统计---收入明细单
.state("app.receivable.income_excel", {
url:"/income_excel?settle?startTime?endTime",
templateUrl:"./src/tpl/page_receivableStatics_income_excel.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableStatisticsController_export.js");
}]
}
})
//应收统计---未结账明细单
.state("app.receivable.arrearage_excel", {
url:"/arrearage_excel?settle?startTime?endTime",
templateUrl:"./src/tpl/page_receivableStatistics_arrearage_excel.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableStatisticsController_export.js");
}]
}
})
.state("app.receivable.receivableManagentList", {//应收管理列表
url:"/receivableManagentList?name",
templateUrl:"./src/tpl/table_receivableManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableManagentController.js");
}]
}
})
.state("app.receivable.receivableCloseAdd", {//应收结算/新增应收单
url:"/receivableCloseAdd?id?code",
templateUrl:"./src/tpl/page_receivableClose_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableCloseController_add.js");
}]
}
})
.state("app.receivable.receivableCloseBill", {//应收结算/应收账单生成
url:"/receivableCloseBill?id?name",
templateUrl:"./src/tpl/page_receivableClose_bill.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/receivable/receivableCloseController_bill.js");
}]
}
})
/******************************************
* 应付模块
******************************************/
//fee
.state('app.fee',{
url:'/fee',
template:'<div ui-view class="fade-in-up"></div>'
})
.state("app.fee.feeAuditList", {//应付审核列表
url:"/feeAuditList",
templateUrl:"./src/tpl/table_feeAudit.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeAuditController.js");
}]
}
})
//结算单管理
.state('app.fee.feeSettle_admin', {
url: '/feeSettle_admin?name',
templateUrl: './src/tpl/table_feeSettleManagent.html',
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeSettleManagentController.js");
}]
}
})
//结算单审核详情
.state('app.fee.fee_settle_audit', {
url: '/feeSettle_audit?settleId?name',
templateUrl: './src/tpl/table_feeSettleAuditDetail.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/payable/feeSettleAuditDetailController.js');
}
]
}
})
//结算单详情
.state("app.fee.fee_settle_detail", {
url: '/feeSettle_detail?settleId?name',
templateUrl: './src/tpl/table_feeSettleDetail.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/payable/feeSettleDetailController.js');
}
]
}
})
.state("app.fee.receiptManagentList", {//回单管理
url:"/receiptManagentList",
templateUrl:"./src/tpl/table_receiptManagent.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/receiptManagentController.js");
}]
}
})
.state("app.fee.receiptManagentBulk", {//回单管理详情(零担)
url:"/receiptManagentBulk/?id?name",
templateUrl:"./src/tpl/page_receiptManagent_breakBulk.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/receiptManagentController.breakbulk.js");
}]
}
})
.state("app.fee.receiptManagentOrder", {//回单管理详情(整车)
url:"/receiptManagentOrder/?id?carrierOrderId?name",
templateUrl:"./src/tpl/page_receiptManagent_order.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/receiptManagentController.order.js");
}]
}
})
.state("app.fee.feeCheckList", {//费用对账
url:"/feeCheckList",
templateUrl:"./src/tpl/app_fee_cost_recoverable.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeCheckController.js");
}]
}
})
.state("app.fee.feeBreakbulkDetail", {//应付【审核/对账/结算单管理/结算单审核/付款管理/应付管理】详情(零担)
url:"/feeBreakbulkDetail/?feeId?carrierOrderId?pageName?feeStatus",
templateUrl:"./src/tpl/app_fee_payaudit_LTL.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeBreakbulkDetailController.js");
}]
}
})
.state('app.fee.feeSettlePayManage', {//付款列表
url: '/feeSettlePayManage',
templateUrl: './src/tpl/app_fee_payment_admin.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/payable/feeSettlePayManagentController.js');
}
]
}
})
.state('app.fee.feeManagent', {//应付管理
url: '/feeManagent',
templateUrl: './src/tpl/table_feeManagent.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/payable/feeManagentController.js');
}
]
}
})
.state("app.fee.feeAddToParent", {//新增费用单
url:"/feeAddToParent?id?code",
templateUrl:"./src/tpl/app_fee_expense_add.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeAddToParentController.js");
}]
}
})
.state("app.fee.feeAddSettle", {//结算单生成
url:"/feeAddSettle?feeIdList?codeList",
templateUrl:"./src/tpl/app_fee_settle_create.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/finance/payable/feeAddSettleController.js");
}]
}
})
.state('app.fee.feeOrderDetailController', {//应付【审核/对账/结算单对账/管理】详情(发货单)
url: '/feeOrderDetailController?feeId?orderId?name?carrierOrderId',
templateUrl: './src/tpl/table_feePayAuditDetail.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/payable/feeOrderDetailController.js');
}
]
}
})
//BDNP
.state('app.BDNP',{
url:'/BDNP',
template:'<div ui-view class="fade-in-up"></div>'
})
.state("app.BDNP.BDNPExport", {//北斗报表
url:"/BDNPExport",
templateUrl:"./src/tpl/table_BDNPexcel_export.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/carPark/car/BDNPExportController.js");
}]
}
})
//opera
.state('app.opera',{
url:'/opera',
template:'<div ui-view class="fade-in-up"></div>'
})
//运维
.state('app.opera.operation_manage', { //运维
url: '/operation_manage',
templateUrl: './src/tpl/table_operationManage.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/operationManagentController.js');
}
]
}
})
.state('app.opera.operation_EContractList', { //运维--电子合同列表
url: '/operation_EContractList',
templateUrl: './src/tpl/table_operationEContractList.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/operationEContractList.js');
}
]
}
})
.state('app.opera.operation_EContractDownload', { //运维--电子合同下载记录
url: '/operation_EContractDownload',
templateUrl: './src/tpl/table_operationEContractDownload.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/operationEContractDownload.js');
}
]
}
})
//报表导出
.state('app.excel',{
url:'/excel',
template:'<div ui-view class="fade-in-up"></div>'
})
//报表导出
.state('app.excel.excel_export', { //报表导出
url: '/excel_export',
templateUrl: './src/tpl/excel_export.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/finance/export/exportController.js');
}
]
}
})
.state('app.opera.operationManage_breakBulk', { //运维(零担)
url: '/operationManage_breakBulk?id',
templateUrl: './src/tpl/page_operation_LTL_detail.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/operationManagentController.breakBulk.js');
}
]
}
})
.state("app.opera.operation_detail", {//运维整单详情
url:"/operation_detail?id?carrierId?name?type?contractStatus",
templateUrl:"./src/tpl/page_operation_detail.html",
resolve: {
load: ['$ocLazyLoad',function ($ocLazyLoad) {
return $ocLazyLoad.load("../src/controllers/order/operationManagentController_detail.js");
}]
}
})
// //外接订单
// .state('app.external',{
// url:'/external',
// template:'<div ui-view class="fade-in-up"></div>'
// })
//外接询价单 CspInquiry
.state('app.inquiry.external_inquiry', { //外接询价单
url: '/external_inquiry?id?name',
templateUrl: './src/tpl/external_inquiry.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/inquiry/cspinquiryController.js');
}
]
}
})
//外接询价单详情 CspInquiry
.state('app.inquiry.external_inquiry_edit', { //外接询价单详情-编辑-共用
url: '/external_inquiry_edit?id?name',
templateUrl: './src/tpl/external_inquiry_edit.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/inquiry/cspinquiryController.edit.js');
}
]
}
})
//外接发货单 CspOrder
.state('app.order.external_order', { //外接发货单
url: '/external_order',
templateUrl: './src/tpl/external_order.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/cspOrderListController.js');
}
]
}
})
//外接发货单详情 CspOrder
.state('app.order.external_order_edit', { //外接发货单详情-编辑-共用
url: '/external_order_edit?id?name',
templateUrl: './src/tpl/external_order_edit.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/cspOrderDetailController.js');
}
]
}
})
//外接发货单详情 CspOrder
.state('app.order.external_orderEdit_Disabel', { //外接发货单详情-编辑-共用
url: '/external_orderEdit_Disabel?id',
templateUrl: './src/tpl/page_csporderDetail.html',
resolve: {
deps: ['$ocLazyLoad',
function ($ocLazyLoad) {
return $ocLazyLoad.load('../src/controllers/order/cspOrderDetailDisableController.js');
}
]
}
})
}]);
<file_sep>/TRANS/ctr/orderController.ts
//发货单新增列表
interface IOrderViewModel extends IBaseViewModel<IOrderQueryTerms> {
/**
* ui-grid控制
*/
gridOptions: uiGrid.IGridOptionsOf<orderList>;
/**
* 调度专员下拉
*/
dispatchOfficerDropDown: EmployeeListItemResponse[];
/**
* 订单状态下拉
*/
orderStatusDropDown: ValueListItemResponse[];
/**
* 删除订单
*/
deleteOrder: (id: string) => void;
/**
* 终结订单
*/
endOrder: (id: string) => void;
/**
* 添加/复制订单
*/
addOrCopyOrder: () => void;
/**
* 编辑订单
*/
editOrder: (id: string) => void;
/**
* 动态列表高度
*/
heightA:number;
}
interface IOrderQueryTerms {
/**
* 订单编号
*/
orderId: string;
/**
* 客户单位
*/
clientName: string;
/**
* 线路地址
*/
route: string;
/**
* 订单状态
*/
orderStatus: string;
/**
* 发货起始时间
*/
shipStartTime: string;
/**
* 发货结束时间
*/
shipEndTime: string;
/**
* 发货地址
*/
shipAddress: string;
/**
* 送货地址
*/
deliverAddress: string;
/**
* 调度专员
*/
dispatchOfficerId: string;
}
class OrderController extends ListController<IOrderViewModel, IOrderQueryTerms> {
gridApi: uiGrid.IGridApiOf<orderList>;
orderBy: number = 0;
asc: boolean = true;
selectedId: string;
constructor($scope: IOrderViewModel,private orderService: IorderService, private employeeService: IEmployeeService,
private $state: angular.ui.IStateService, private $ngBootbox: BootboxService, private valueService: IValueService,private $location:ng.ILocationService) {
super($scope);
this.init();
}
init(): void {
super.init();
this.$scope.deleteOrder = this.deleteOrder;
this.$scope.endOrder = this.endOrder;
this.$scope.addOrCopyOrder = this.addOrCopyOrder;
this.$scope.editOrder = this.editOrder;
this.$scope.$on("WildDog:Order12", this.onWilddogOrderEvent);
$('#opendataTime').click(function () {
$('#dataTime').datetimepicker('show');
});
$('#opendataTimeEnd').click(function () {
$('#dataTimeEnd').datetimepicker('show');
});
this.$scope.queryTerms = {
orderId: "",
clientName: "",
route: "",
orderStatus: "",
shipStartTime: "",
shipEndTime: "",
shipAddress: "",
deliverAddress: "",
dispatchOfficerId: ""
};
this.$scope.gridOptions = {
enableSelectAll: false,
paginationPageSizes: [10, 20, 30],
useExternalPagination: true,
useExternalSorting: true,
enableFullRowSelection: true,
enableColumnResizing: true,
columnDefs: [
{ displayName: "订单编号", field: 'orderId', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '9%' },
{ displayName: "客户单位", field: 'clientName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
{ displayName: "发货地址", field: 'startAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
{ displayName: '送货地址', field: 'endAddress', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '10%' },
{ displayName: '货物名称', field: 'goodsName', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{ displayName: '货物数量', field: 'goodsNum', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{ displayName: '所需车长', field: 'carLength', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{ displayName: '发货时间', field: 'shipTime', enableColumnMenu: false, cellTooltip: true, headerTooltip: true, width: '9%' },
{ displayName: '调度专员', field: 'dispatcher', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{ displayName: '紧急程度', field: 'urgency', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{ displayName: '订单状态', field: 'orderStatus', enableColumnMenu: false, cellTooltip: true, headerTooltip: true },
{
displayName: "操作",
field: 'orderStatus',
cellTemplate: '<div ng-if="row.entity.orderStatus == \'退回下单\'">'
+ '<a class="fa fa-minus-circle primary text-primary m-l-xs" ng-click="grid.appScope.endOrder(row.entity.id)" title="终结订单"></a>'
+ '<a class="fa fa-edit m-l-xs primary text-info" title="编辑重下" ng-click="grid.appScope.editOrder(row.entity.id)" ></a>'
+ '</div>'
+ '<div ng-if="row.entity.orderStatus == \'派车中\'">'
+ '<a class="fa fa-minus-circle primary text-primary m-l-xs" ng-click="grid.appScope.endOrder(row.entity.id)" title="终结订单"></a>'
+ '<a class="primary fa fa-trash-o text-danger m-l-xs" title="删除" ng-click="grid.appScope.deleteOrder(row.entity.id)"></a>'
+ '</div>', enableColumnMenu: false, enableSorting: false, width: '4%'
}
],
onRegisterApi: (gridApi) => {
this.gridApi = gridApi;
gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
gridApi.core.notifyDataChange("options");
gridApi.core.on.sortChanged(this.$scope, this.sortChange);
gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
}
};
this.$scope.gridOptions.multiSelect = false;
this.query();
this.loadDispatchOfficerDropDown();
this.loadOrderStatusDropDown();
}
localHistory():void{
super.localHistory(this.$state)
}
getHistory():void{
super.getHistory(this.$state,this.$location)
}
loadDispatchOfficerDropDown(): void {
this.employeeService.getList("2", "", "", "", "", true,0, -1).then(result => {
this.$scope.dispatchOfficerDropDown = result.data.list;
});
}
loadOrderStatusDropDown(): void {
this.$scope.orderStatusDropDown = this.valueService.getOrderStatusList().list;
}
loadData(queryTerms: IOrderQueryTerms, skip: number, count: number): void {
this.orderService.list(this.orderBy.toString(), this.asc, queryTerms.orderId, queryTerms.clientName, queryTerms.route,
queryTerms.shipStartTime, queryTerms.shipEndTime, queryTerms.orderStatus, "", "", queryTerms.dispatchOfficerId,
queryTerms.shipAddress, queryTerms.deliverAddress, "", skip, count).then(result => {
this.$scope.gridOptions.totalItems = result.data.total;
this.$scope.gridOptions.data = result.data.list;
this.$scope.heightA = ((result.data.list.length * 39) + 95);
if (skip == 0) {
this.$scope.gridOptions.paginationCurrentPage = 1;
}
this.$scope.querying = false;
}, error => {
this.$scope.querying = false;
});
}
sortChange=(grid: uiGrid.IGridInstanceOf<orderList>, sortColumns: Array<uiGrid.IGridColumnOf<orderList>>)=>{
if (sortColumns.length == 0) {
this.reload();
} else {
let sortItem = sortColumns[0];
switch (sortItem.name) {
case "orderId": {
this.orderBy = 1;
} break;
case "clientName": {
this.orderBy = 2;
} break;
case "startAddress": {
this.orderBy = 3;
} break;
case "viaAddress": {
this.orderBy = 4;
} break;
case "endAddress": {
this.orderBy = 5;
} break;
case "goodsName": {
this.orderBy = 6;
} break;
case "goodsNum": {
this.orderBy = 7;
} break;
case "carLength": {
this.orderBy = 8;
} break;
case "shipTime": {
this.orderBy = 9;
} break;
case "urgency": {
this.orderBy = 10;
} break;
case "orderStatus": {
this.orderBy = 11;
} break;
case "placeOrderTime": {
this.orderBy = 12;
} break;
}
this.asc = sortItem.sort.direction == "asc";
this.reload();
}
}
selectChange = (row: uiGrid.IGridRowOf<orderList>) => {
row.isSelected?this.selectedId = row.entity.id:this.selectedId="";
}
/**
* 监听野狗事件
*/
onWilddogOrderEvent = (event: ng.IAngularEvent, data: any) => {
this.query();
}
/**
* 删除订单
*/
deleteOrder = (id: string) => {
this.$ngBootbox.confirm("是否删除订单").then(e => {
this.orderService.delete(id).then(result => {
this.query();
});
});
}
/**
* 终结订单
*/
endOrder = (id: string) => {
this.$ngBootbox.confirm("是否终结订单").then(e => {
this.orderService.editOrderStatus(id, "", "8", "", "").then(result => {
this.query();
});
});
}
/**
* 复制或新增订单
*/
addOrCopyOrder = () => {
if (this.selectedId == undefined || this.selectedId == "") {
this.$state.go("app.order.orderAdd", { name: "add" });
} else {
this.$state.go("app.order.orderAdd", { id: this.selectedId, name: "copy" });
}
}
/**
* 编辑重下订单
*/
editOrder = (id: string) => {
this.$state.go("app.order.orderAdd", { id: id, name: "edit" });
}
}
angular.module("tms").controller("orderController", ["$scope","orderService", "employeeService", "$state", "$ngBootbox", "valueService","$location", OrderController]);<file_sep>/TRANS/parseCtr/createCom.js
function createComponent(){
}
| 09eb47fcddf7e45ca47f1e23200f8a2e93cdb329 | [
"JavaScript",
"TypeScript"
] | 7 | TypeScript | mangooLi/node-tms-trans | a46930969b87e79a3035b2d1c93d2203fd6d4539 | 00e902f752b3c18e2142d470a0cddbfc687721ba |
refs/heads/master | <repo_name>Jamesrbrtsn/Angular-Webstore-Application--Project<file_sep>/malcolm-co/src/app/app-routing.module.ts
// ng g module app-routing --flat --module=app
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// Router Functionality
import {RouterModule, Routes} from '@angular/router';
// Component Links
import {ShopPageComponent} from './components/shop-page/shop-page.component';
import {ManagerControlPageComponent} from './components/manager-control-page/manager-control-page.component';
import {PolicyPageComponent} from './components/policy-page/policy-page.component';
import {PageNotFoundComponent} from './components/page-not-found/page-not-found.component';
import { ItemDetailComponent } from './components/shop-page/item-detail/item-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/shop', pathMatch: 'full' },
{ path: 'shop', component: ShopPageComponent },
{ path: 'detail/:id', component: ItemDetailComponent },
{ path: 'manager-control-page', component: ManagerControlPageComponent },
{ path: 'policies', component: PolicyPageComponent },
{ path: '**', component: PageNotFoundComponent },
// TO ADD
// { path: 'login', component: },
// { path: 'account/:id', component: },
// { path: 'account', component: },
];
@NgModule({
declarations: [],
imports: [
RouterModule.forRoot(routes),
CommonModule
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/malcolm-co/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FooterComponent } from './components/footer/footer.component';
import { AppRoutingModule } from './app-routing.module';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { ManagerControlPageComponent } from './components/manager-control-page/manager-control-page.component';
import { ShopPageComponent } from './components/shop-page/shop-page.component';
import { PolicyPageComponent } from './components/policy-page/policy-page.component';
// mport Forms, contains list of external modules needed for the app
import {FormsModule} from '@angular/forms'; // --houses NgModel
import { StoreItemComponent } from './components/shop-page/store-item/store-item.component';
import { ItemDetailComponent } from './components/shop-page/item-detail/item-detail.component';
import { SearchComponent } from './components/shop-page/search/search.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
FooterComponent,
PageNotFoundComponent,
ManagerControlPageComponent,
ShopPageComponent,
PolicyPageComponent,
StoreItemComponent,
ItemDetailComponent,
SearchComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/angular-tour-of-heroes/src/app/hero.ts
// class
export class Hero {
id: number;
name: string;
}<file_sep>/malcolm-co/src/app/services/store.service.ts
import { Injectable } from '@angular/core';
import { StoreItem } from '../classes/storeItem';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
const httpOptions = {
credentials: 'same-origin', // include, *same-origin, omit for cors
headers: new HttpHeaders({
'Content-Type': 'applciation/json' })
};
@Injectable({
providedIn: 'root'
})
export class StoreService {
constructor(
private http: HttpClient
) { }
private host = 'localhost';
private apiPort = 3000;
private apiHostUrl = `http://${this.host}:${this.apiPort}/api`;
private itemsUrl = '/items';
private avaliableAndQuantity = '/quantity/avaliable';
private storeItemsUrl = this.apiHostUrl + this.itemsUrl;
private storeFrontUrl = this.apiHostUrl + this.itemsUrl + this.avaliableAndQuantity;
/** GET items from the server */ // only avaliable and with quantity
getItems(): Observable<StoreItem[]> {
return this.http.get<StoreItem[]>(this.storeFrontUrl)
.pipe(
tap(_ => this.log('items')),
catchError(this.handleError<StoreItem[]>('getItems', []))
);
console.log('getItems attempted');
}
getItemNo404<Data>(id: number): Observable<StoreItem> {
const url = `${this.storeItemsUrl}/?id=${id}`;
return this.http.get<StoreItem[]>(url)
.pipe(
map(items => items[0]), // returns a {0|1} element array
tap(h => {
const outcome = h ? `fetched` : `did not find`;
this.log(`${outcome} item id=${id}`);
}),
catchError(this.handleError<StoreItem>(`getItem id=${id}`))
);
}
// getItem(id: )
/** GET item by id. Will 404 if id not found */
getItem(id: number): Observable<StoreItem> {
const url = `${this.storeItemsUrl}/${id}`;
return this.http.get<StoreItem>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<StoreItem>(`getItem id=${id}`))
);
}
/* GET items whose name contains search term */
searchItems(term: string): Observable<StoreItem[]> {
console.log(`searching for ${term}`);
if (!term.trim()) {
// if not search term, return empty hero array.
return of([]);
}
/*
return this.http.get<StoreItem[]>(`${this.storeItemsUrl}/${term}`);
fetchh('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
*/
return this.http.get<StoreItem[]>(`${this.storeItemsUrl}/?${term}`).pipe(
tap(_ => this.log(`found items matching "${term}"`)),
catchError(this.handleError<StoreItem[]>('searchItems', []))
);
//
}
// addItem(obj)
// deleteItem(obj | id)
// updateItem
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
/** Log a HeroService message with the MessageService */
private log(message: string) {
console.log(message);
}
}
<file_sep>/malcolm-co-backend/server.js
//Intitials
const express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors());
//Model references
var StoreItems = require("./models/storeItem.model");
//Parser for objects
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//mongoose / mongodb setup and connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://wookieCoookie:<EMAIL>:63146/webstore-project';
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB conneciton error:'));
var PORT = 3000;
//Set up express router for route organization
var router = express.Router(); //get instance of express router
router.use(function (req, res, next) {
console.log('router used');
next(); //make sure we continue to the next routes
});
///////////////////////////////////////////////////////////////////////////////////////////
//=======================================================================================//
//= ROUTES =//
//=======================================================================================//
///////////////////////////////////////////////////////////////////////////////////////////
//====================Store Items
router.route('/items') // GET, POST
.post(function (req, res) { //creates a new store item
var item = new StoreItems.Model(req.body);
item.id = req.body.id;
//price: { type: Number, required: true },
item.price = Number(req.body.price);
//id: { type: Number, required: true },
item.id = Number(req.body.id);
//quantity: { type: Number, required: true },
item.quantity = Number(req.body.quantity);
//name: { type: String, required: true, max: 100 },
item.name = req.body.name;
//description: String,
item.description = req.body.description;
//avaliable: Boolean
item.avaliable = req.body.avaliable;
item.save(function (err) {
if (err) {
res.send(err);
}
res.json({ message: 'New Store Item created' });
});
})
.get(function (req, res) { //returns all store items
StoreItems.Model.find(function (err, storeItems) {
if (err) {
res.send(err);
}
res.json(storeItems)
});
});
router.route('/items/:id') //GET, PUT, DELETE
.get(function (req, res) {
StoreItems.Model.findById(req.params.id, function (err, item) {
if (err) {
res.send(err);
}
res.json(item);
})
})
.put(function (req, res) {
//price: { type: Number, required: true },
//id: { type: Number, required: true },
//quantity: { type: Number, required: true },
//name: { type: String, required: true, max: 100 },
//description: String,
//avaliable: Boolean
StoreItems.Model.findById(req.params.id, function (err, item) {
if (err) { res.send(err); }
if (req.body.name) { item.name = req.body.name; }
if (req.body.price) { item.price = req.body.price; }
if (req.body.id) { item.id = req.body.id; }
if (req.body.quantity) { item.quantity = req.body.quantity; }
if (req.body.description) { item.description = req.body.description; }
if (req.body.avaliable) { item.avaliable = req.body.avaliable; }
item.save(function (err) {
if (err) { res.send(err); }
res.json({ message: 'Item updated' });
});
});
})
.delete(function (req, res) {
StoreItems.Model.find(function (err, storeItems) {
let deletable = [];
for (let index = 0; index < storeItems.length; index++) {
if (storeItems[index]["id"] == req.params.id) {
deletable.push(storeItems[index]["_id"]);
console.log(`id:${deletable[0]} was deleted`);
StoreItems.Model.findByIdAndDelete(deletable[0], function (err, item) {
if (err) {
res.send(err);
}
res.send({ message: 'Successfully deleted requested item' })
});
break;
}
}
});
/*
StoreItems.Model.remove({
_id: deletable[1]
}, function(err, item){
if(err){
res.send(err);
}
res.send({message: 'Successfully deleted requested item'})
});*/
});
//Specialty Get
router.route('/items/:name')
.get(function (req, res) {
console.log(`searched for ${req.params.name}`);
StoreItems.Model.find(function (err, storeItems) {
if (err) { res.send(err) }
let searchResults = [];
for (let index = 0; index < storeItems.length; index++) {
if ((storeItems[index]["name"].includes(req.params.name) == true)) {
if (storeItems[index]["quantity"] > 0) {
searchResults.push(storeItems[index]);
}
}
}
console.log(searchResults);
res.json(searchResults);
});
});
router.route('/items/quantity/avaliable') //only return items marked avaliable, and that have quantity
.get(function (req, res) {
StoreItems.Model.find(function (err, storeItems) {
if (err) {
res.send(err);
}
let avaliableAndQuantity = [];
for (let index = 0; index < storeItems.length; index++) {
if (storeItems[index]["avaliable"] == true) {
if (storeItems[index]["quantity"] > 0) {
avaliableAndQuantity.push(storeItems[index]);
}
}
}
res.json(avaliableAndQuantity);
});
});
router.route('items/quantity/:id') //for quick quanity checks on specific items
.get(function (req, res) {
StoreItems.Model.findById(req.params.id, function (err, item) {
if (err) { res.send(err); }
res.json(item["quantity"]);
});
});
//Policies==================
//Accounts==================
///////////////////////////////////////////////////////////////////////////////////////////
//=======================================================================================//
//= App Start =//
//=======================================================================================//
///////////////////////////////////////////////////////////////////////////////////////////
app.use('/api', router);
app.listen(PORT, function () {
console.log(`listening on ${PORT}`)
})<file_sep>/malcolm-co/src/app/components/shop-page/search/search.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {
debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';
import { StoreItem } from 'src/app/classes/storeItem';
import { StoreService } from 'src/app/services/store.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
items$: Observable<StoreItem[]>;
private searchTerms = new Subject<string>();
constructor(private storeService: StoreService) { }
// Push a search term into the observable stream.
search(term: string): void {
// -- console.log(term);
this.searchTerms.next(term);
}
ngOnInit(): void {
this.items$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap((term: string) => this.storeService.searchItems(term)),
);
}
}
<file_sep>/malcolm-co/src/app/components/shop-page/shop-page.component.ts
import { Component, OnInit } from '@angular/core';
import {StoreItem} from 'src/app/classes/storeItem';
import {StoreService} from 'src/app/services/store.service';
import {SearchComponent} from './search/search.component';
/* import
-shopItem
-ShopService
*/
@Component({
selector: 'app-shop-page',
templateUrl: './shop-page.component.html',
styleUrls: ['./shop-page.component.scss']
})
export class ShopPageComponent implements OnInit {
items: StoreItem[] = [];
constructor(private storeService: StoreService) { }
ngOnInit() {
this.getStoreItems();
}
getStoreItems(): void {
this.storeService.getItems()
.subscribe(items => this.items = items);
}
}
<file_sep>/malcolm-co/src/app/components/shop-page/item-detail/item-detail.component.ts
import { Component, OnInit } from '@angular/core';
import {StoreItem} from 'src/app/classes/storeItem';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { StoreService } from 'src/app/services/store.service';
@Component({
selector: 'app-item-detail',
templateUrl: './item-detail.component.html',
styleUrls: ['./item-detail.component.scss']
})
export class ItemDetailComponent implements OnInit {
item: StoreItem;
constructor(
private route: ActivatedRoute,
private storeService: StoreService,
private location: Location
) { }
ngOnInit(): void {
this.getItem();
}
getItem(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.storeService.getItem(id)
.subscribe(item => this.item = item);
}
goBack(): void {
this.location.back();
}
}
| 88531a42bc89518e342c0b9745a6c396e1db497c | [
"JavaScript",
"TypeScript"
] | 8 | TypeScript | Jamesrbrtsn/Angular-Webstore-Application--Project | f3b098d4d498d1161251f4974a6891c3525f4466 | c4020e330acb52540bf9718775d67f2d815ef7ab |
refs/heads/master | <file_sep>#!/bin/sh
/bin/bash -c "$STORM_PATH/bin/storm nimbus"
<file_sep>FROM phusion/baseimage
MAINTAINER <NAME> "<EMAIL>"
ENV STORM_VER="1.1.1"
ENV REFRESHED_AT="2017-12-09" \
STORM_PATH="/opt/apache-storm-${STORM_VER}"
LABEL storm_version=${STORM_VER} \
description="Apache Storm: zookeeper, nimbus, ui, supervisor" \
repository_url="https://github.com/fedelemantuano/apache-storm-dockerfile"
CMD ["/sbin/my_init"]
RUN mkdir -p /etc/service/zookeeperd \
&& mkdir -p /etc/service/nimbus \
&& mkdir -p /etc/service/supervisor \
&& mkdir -p /etc/service/ui \
&& mkdir -p /mnt/storm \
&& apt-get -yqq update \
&& apt-get -yqq upgrade -o Dpkg::Options::="--force-confold" \
&& apt-get -yqq --no-install-recommends install \
curl \
openjdk-8-jre \
python \
zookeeperd \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get -yqq autoremove \
&& dpkg -l | grep ^rc | awk '{print $2}' | xargs dpkg --purge \
&& curl -o ${STORM_PATH}.tar.gz http://mirror.nohup.it/apache/storm/apache-storm-${STORM_VER}/apache-storm-${STORM_VER}.tar.gz \
&& tar -zxf ${STORM_PATH}.tar.gz -C /opt \
&& rm -f ${STORM_PATH}.tar.gz
COPY run/zookeeperd.sh /etc/service/zookeeperd/run
COPY run/nimbus.sh /etc/service/nimbus/run
COPY run/supervisor.sh /etc/service/supervisor/run
COPY run/ui.sh /etc/service/ui/run
COPY run/logviewer.sh /etc/service/logviewer/run
COPY zookeeper/zoo.cfg /etc/zookeeper/conf/zoo.cfg
COPY storm/storm.yaml $STORM_PATH/conf/storm.yaml
COPY logrotate.d/* /etc/logrotate.d/
EXPOSE 8080 8000
| 7fb03c9760afbe0c2e52a731594bf2748c7ea966 | [
"Dockerfile",
"Shell"
] | 2 | Shell | menhswu/apache-storm-dockerfile | 3681ac83f16c70f49f136f5c77cbc056091eef40 | 4ade29b3e6561fc6371f4d8cc6a55af029e2031b |
refs/heads/main | <file_sep>class Person {
//data
constructor (){
this.firstname
this.lastname
this.firstname
this.lastname
}
// operators
//overiding demostration
talk(){
console.log("I talk as a person")
}
// eat()
// walk()
};
// 21,22& 23 represent principle of inheritance
class Man extends Person {
constructor(){
super();
}
//overiding demonstration
talk(){
console.log("I talk as a man")
}
}
// class Woman extends Person {}
//polymorphism illustration
let person =new Person();
person = new Man;
// person = new Woman;
//check point for where all the methods/operators will be auto displayed as methods/oper
// let person =new Person();
//person. | 5a369ade26bb1ec64016073d6f0c923e7218b0b2 | [
"JavaScript"
] | 1 | JavaScript | Kiwumulo-Nickson/DP_SECTION2 | c8306b21bbabf1e237a2979c3618fec5fbeb3f3a | 40fdf9ab7373ade6f6b5b97f44e05bdfc6cc74e9 |
refs/heads/master | <repo_name>memorammstein/mexicoder.apish.BE2<file_sep>/test/test.js
'use strict';
var assert = require('assert');
var mexicoderapishbe2 = require('../server.js');
describe('mexicoderapishbe2 node module', function () {
it('must have at least one test', function () {
assert(true, 'basic stuff');
});
});
<file_sep>/README.md
# mexicoder.apish.BE2
Back End
| d1b0af4a9e13d7d5fec03f158ce79dae2514cb40 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | memorammstein/mexicoder.apish.BE2 | aabf3a677873939e69f3592abf3cc93a07ef5595 | 721eebda241f9266663baaf6f201715db8d13b15 |
refs/heads/main | <repo_name>DanielsRT/Social-Network<file_sep>/AccountHolderClient.java
import java.util.*;
import java.io.*;
public class AccountHolderClient {
static Scanner keyb = new Scanner(System.in);
static String FILE_NAME = "friendsData.txt";
public static void main(String[] args) {
System.out.println("Welcome to the social network progam.");
if (args.length >= 1) {
FILE_NAME = args[0];
}
Map<String,AccountHolder> users = readAccountsFromFile(FILE_NAME);
System.out.printf("There are %d account holders\n",users.size());
int choice = 0;
while (choice != 5) {
printMenu();
System.out.print("\nEnter your choice (1-5): ");
choice = Integer.parseInt(keyb.nextLine());
switch (choice) {
case 1:
users = addNewAccount(users);
break;
case 2:
users = connectTwoPersons(users);
break;
case 3:
listAccountFriends(users);
break;
case 4:
checkIfFriends(users);
break;
case 5:
saveChanges(users);
System.out.println("Thanks for using the social network. Bye.");
System.exit(0);
break;
default:
System.out.println("Invalid choice");
}
}
}//main
//saveChanges(users);
static void saveChanges(Map<String,AccountHolder> users) {
try (PrintWriter pw = new PrintWriter(new File(FILE_NAME))) {
for (Map.Entry<String, AccountHolder> user : users.entrySet()) {
pw.println(user.getValue().toFileString());
}
} catch (FileNotFoundException e) {
System.err.printf("Could not write file, '%s'\n",FILE_NAME);
}
}
//users = connectTwoPersons(users);
static Map<String,AccountHolder> connectTwoPersons(Map<String,AccountHolder> users) {
String id1 = "";
String id2 = "";
while (id1.equals("") || id2.equals("")) {
while (id1.equals("")) {
System.out.print("What's the first person's ID? ");
id1 = keyb.nextLine();
if (!users.containsKey(id1)) {
System.out.println("Invalid ID");
id1 = "";
}
}
System.out.printf("(%s) %s\n",id1, users.get(id1).getFullName());
while (id2.equals("")) {
System.out.print("What's the second person's ID? ");
id2 = keyb.nextLine();
if (!users.containsKey(id2)) {
System.out.println("Invalid ID");
id2 = "";
} else if (id2.equals(id1)) {
System.out.println("Choose a different ID");
id2 = "";
}
}
System.out.printf("(%s) %s\n",id2, users.get(id2).getFullName());
}
if (users.get(id1).getFriendIDs().contains(id2)) {
System.out.printf("%s and %s are already friends.\n",
users.get(id1).getFullName(),users.get(id2).getFullName());
} else {
users.get(id1).getFriendIDs().add(id2);
users.get(id2).getFriendIDs().add(id1);
System.out.printf("%s and %s are now connected as friends.\n",
users.get(id1).getFullName(),users.get(id2).getFullName());
}
return users;
}
//users = addNewAccount(users);
static Map<String,AccountHolder> addNewAccount(Map<String,AccountHolder> users) {
String newID = "";
while (newID.equals("")) {
System.out.print("What's the ID of the new person? ");
newID = keyb.nextLine();
if (users.containsKey(newID)) {
System.out.println("Sorry, that ID is already taken.");
newID = "";
}
}
System.out.print("First name: ");
String newFirstName = keyb.nextLine();
System.out.print("Last name: ");
String newLastName = keyb.nextLine();
System.out.print("Email: ");
String newEmail = keyb.nextLine();
AccountHolder newUser = new AccountHolder(newID,newFirstName,
newLastName,newEmail);
users.put(newID, newUser);
System.out.printf("(%s) %s added.\n",newID,newUser.getFullName());
return users;
}
//checkIfFriends(users);
static void checkIfFriends(Map<String,AccountHolder> users) {
System.out.print("What's the first person's ID? ");
String target1 = keyb.nextLine().toLowerCase();
AccountHolder user1 = users.get(target1);
System.out.printf("(%s) %s\n",target1,user1.getFullName());
System.out.print("What's the second person's ID? ");
String target2 = keyb.nextLine().toLowerCase();
AccountHolder user2 = users.get(target2);
System.out.printf("(%s) %s\n",target2,user2.getFullName());
if (user1.getFriendIDs().contains(target2)) {
System.out.printf("%s and %s are friends\n",
user1.getFullName(),user2.getFullName());
} else {
System.out.printf("%s and %s are not friends\n",
user1.getFullName(),user2.getFullName());
}
}
//listAccountFriends(keyb.nextLine().toLowerCase, users);
static void listAccountFriends(Map<String,AccountHolder> users) {
System.out.print("What's the account holder ID? ");
String target = keyb.nextLine().toLowerCase();
AccountHolder targetUser = users.get(target);
if (targetUser != null) {
String targetName = targetUser.getFullName();
List<String> targetFriends = new ArrayList<>(targetUser.getFriendIDs());
if (targetFriends.size() >= 1) {
System.out.printf("(%s) %s has %d friends:\n",target,targetName,targetFriends.size());
for (String acctID : targetFriends) {
AccountHolder acct = users.get(acctID);
System.out.printf("\t%s\n",acct.getFullName());
}
} else {
System.out.printf("(%s) %s has no friends\n",target,targetName);
}
} else {
System.out.println("User does not exist");
}
}
//printMenu();
static void printMenu() {
System.out.println("\n - - < < Main Menu > > - - ");
System.out.println("1) Add new account");
System.out.println("2) Connect two persons as friends");
System.out.println("3) List all friends of a person");
System.out.println("4) Check whether two people are friends");
System.out.println("5) Save & Quit");
}
//Map<String,AccountHolder> users = readAccountsFromFile(FILE_NAME);
static Map<String,AccountHolder> readAccountsFromFile(String filename) {
Map<String,AccountHolder> users = new HashMap<>();
try (Scanner fileScan = new Scanner (new File(filename))) {
while (fileScan.hasNextLine()) {
String dataLine = fileScan.nextLine();
AccountHolder newAccount = new AccountHolder(dataLine);
users.put(newAccount.getID(), newAccount) ;
}
} catch (Exception e) {
System.err.printf("Couldn't open '%s'\n",filename);
System.exit(0);
}
return users;
}
//printAccountHolders(users);
static void printAccountHolders(Map<String,AccountHolder> users) {
for (Map.Entry<String, AccountHolder> user : users.entrySet()) {
System.out.println(user.getValue());
}
}
}//class | 92bb368ac627e2433e167475f41cc2a5e37d835d | [
"Java"
] | 1 | Java | DanielsRT/Social-Network | 4bcb5a3d4fc7ea17f0aa841e2a399343a9fbf6b5 | f78006904124358b41008854d3c21fcacf6a651d |
refs/heads/master | <repo_name>mbodak/starShip<file_sep>/README.md
# starShip
Little JS project to launch a shuttle to space for the students
<file_sep>/js/main.js
/**
* @returns <div class="image"><img src="img/starship.png" alt="starShip"></div>
*/
function createStarShipImageDiv() {
// create <img src="img/starship.png" alt="starShip"> html element
const img = document.createElement('img');
img.src = "img/starship.png";
img.alt = "starShip"
// create <div class="image"></div> html element
const imageDiv = document.createElement('div');
imageDiv.setAttribute('class', 'image');
// put <img> element inside <div> and finally we get <div class="image"><img src="img/starship.png" alt="starShip"></div>
imageDiv.appendChild(img);
return imageDiv;
}
/**
* @returns <div class="name"><h2>{{name}}</h2></div>
*/
function createStarShipNameDiv(name) {
// create <h1>{{name}}</h1> html element
const h2 = document.createElement('h2');
h2.textContent = name;
// create <div class="name"></div> html element
const nameDiv = document.createElement('div');
nameDiv.setAttribute('class', 'name');
// put <h1> element inside <div> and finally we get <div class="name"><h1>{{name}}</h1></div>
nameDiv.appendChild(h2);
return nameDiv;
}
/**
* @returns Return generated html element
<div class="star-ship">
<div class="image">
<img src="img/starship.png" alt="starShip">
</div>
<div class="name">
<h2>{{name}}</h2>
</div>
</div>
*/
function createStarShipDiv(name) {
// create <div class="star-ship"></div> html element
const starShipDiv = document.createElement('div');
starShipDiv.setAttribute('class', 'star-ship');
// put generated image div inside starShip div
const imageDiv = createStarShipImageDiv()
starShipDiv.appendChild(imageDiv);
// put generated name div inside starShip div
const nameDiv = createStarShipNameDiv(name)
starShipDiv.appendChild(nameDiv);
return starShipDiv;
}
function launch(theForm) {
const name = theForm.name.value
if (!name || !name.length) {
return
}
const starShipsDiv = document.getElementById('starships');
const starShipDiv = createStarShipDiv(name);
starShipsDiv.appendChild(starShipDiv);
theForm.reset()
}
| 44f4a3b906521e1c246f86c223865166d2bc3333 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mbodak/starShip | b763598041dc1650b66c0e121217708855321467 | 9046c531fcb60c723d364a1ab0211415dd6c6c69 |
refs/heads/master | <file_sep>package com.example.json_parsing_offline;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
String json;
TextView text_id, text_jsonRaw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_id = findViewById(R.id.txt);
text_jsonRaw = findViewById(R.id.txt1);
json = "{\n" +
" \"0\": {\n" +
" \"id\": \"0\",\n" +
" \"title\": \"you will never die\"\n" +
" },\n" +
" \"1\": {\n" +
" \"id\": \"1\",\n" +
" \"title\": \"Baseball\"\n" +
" },\n" +
" \"2\": {\n" +
" \"id\": \"2\",\n" +
" \"title\": \"Two basketball team players earn all state honors\"\n" +
" }\n" +
"}";
}
@Override
public void onStart() {
super.onStart();
text_jsonRaw.setMovementMethod(new ScrollingMovementMethod());
text_id.setMovementMethod(new ScrollingMovementMethod());
text_jsonRaw.setText(json);
text_id.setText("");
try {
JSONObject mainObject = new JSONObject(json);
for (int i = 0; i < 3; i++) {
JSONObject Object = mainObject.getJSONObject(String.valueOf(i));
String name = Object.getString("id");
String url = Object.getString("title");
text_id.append("Id:" + name + "\nTitle:" + url + "\n");
text_id.append("\n-------------------------------------------------------\n");
}
} catch (Exception e) {
}
}
}
| d3e4fdf7823ef46c17f0db80d42b2a7bab2d4e22 | [
"Java"
] | 1 | Java | batteashishkumar/JSON_parsing_offline | e6b7d2909d9334914658bb8fbc209e1f85577c98 | ec4b0bd3793e3e655d287623ad2ecdd0bf974441 |
refs/heads/master | <file_sep>using Configuration.FileIO;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Configuration
{
public class ConfigFileDefaults
{
public CultureInfo Culture { get; set; }
public IConfigFileWriter Writer { get; set; }
public SyntaxMarkers SyntaxMarkers { get; set; }
public IConfigFileReader Parser { get; set; }
public ConfigFileDefaults()
{
Culture = CultureInfo.InvariantCulture;
// Create the instances.
Parser = new ConfigFileReader();
Writer = new ConfigFileWriter();
SyntaxMarkers = new SyntaxMarkers()
{
KeyValueDelimiter = "=",
SectionBodyBeginMarker = ":",
IncludeBeginMarker = "[include]",
LongValueBeginMarker = "\"",
LongValueEndMarker = "\"",
SingleLineCommentBeginMarker = "//",
MultiLineCommentBeginMarker = "/*",
MultiLineCommentEndMarker = "*/",
};
// Assign the necessary properties.
Parser.Markers = SyntaxMarkers;
Writer.Markers = SyntaxMarkers;
}
}
public class ConfigFile : ConfigSection
{
#region Static
public static ConfigFileDefaults Defaults { get; set; }
public static ConfigFile FromString(string content)
{
var cfg = new ConfigFile();
cfg.LoadFrom(content);
return cfg;
}
public static ConfigFile FromFile(string fileName)
{
var cfg = new ConfigFile() { FileName = fileName };
cfg.Load();
return cfg;
}
static ConfigFile()
{
Defaults = new ConfigFileDefaults();
}
#endregion
private CultureInfo _culture;
public CultureInfo Culture
{
get { return _culture ?? Defaults.Culture; }
set { _culture = value; }
}
IConfigFileWriter _writer;
public IConfigFileWriter Writer
{
get { return _writer ?? Defaults.Writer; }
set { _writer = value; }
}
SyntaxMarkers _syntaxMarkers;
public SyntaxMarkers SyntaxMarkers
{
get { return _syntaxMarkers ?? Defaults.SyntaxMarkers; }
set { _syntaxMarkers = value; }
}
IConfigFileReader _parser;
public IConfigFileReader Parser
{
get { return _parser ?? Defaults.Parser; }
set { _parser = value; }
}
/// <summary>
/// Convenient access to the underlying FileInfo property.
/// </summary>
public string FileName { get; set; }
public void Clear()
{
Options.Clear();
Sections.Clear();
}
public void LoadFrom(string content)
{
Clear();
ConfigFile cfg;
using (var reader = new StringReader(content))
{
cfg = Parser.Parse(reader);
}
Options = cfg.Options;
Sections = cfg.Sections;
}
/// <summary>
/// Use the property FileInfo of this class to specify the file name.
/// </summary>
public void Load()
{
Clear();
ConfigFile cfg = null;
using (var reader = new FileInfo(FileName).OpenText())
{
cfg = Parser.Parse(reader);
}
Options = cfg.Options;
Sections = cfg.Sections;
}
public void Save()
{
using (var writer = new FileInfo(FileName).CreateText())
{
SaveTo(writer);
}
}
/// <summary>
///
/// </summary>
/// <remarks>This method ignores this instance's <code>FileInfo</code>.</remarks>
/// <param identifier="writer"></param>
public void SaveTo(TextWriter writer)
{
Writer.Write(writer, this);
}
}
}
<file_sep>config-file-net
===============
Simple config file for .NET written in C#
<file_sep>
namespace Configuration.FileIO
{
public delegate string TextProcessorCallback(string toProcess);
public class SyntaxMarkers
{
/// <summary>
/// Key = Value
/// ----^
/// </summary>
public string KeyValueDelimiter { get; set; }
/// <summary>
/// ---------v
/// Section 0:
/// opt0 = val0
/// opt1 = val1
/// </summary>
public string SectionBodyBeginMarker { get; set; }
/// <summary>
/// [include] Section 0 = Path/To/My/File.cfg
/// ----^^^^^^^^^
/// or
/// $ Section 0 = Path/To/My/File.cfg
/// ----^
/// </summary>
public string IncludeBeginMarker { get; set; }
/// <summary>
/// Option = { This is a long value
/// that may span multiple lines. }
/// ---------^
/// </summary>
public string LongValueBeginMarker { get; set; }
/// <summary>
/// Option = { This is a long value
/// that may span multiple lines. }
/// -----------------------------------------^
/// </summary>
public string LongValueEndMarker { get; set; }
/// <summary>
/// // This is a comment.
/// ----^^
/// </summary>
public string SingleLineCommentBeginMarker { get; set; }
/// <summary>
/// /* This is a multi-line comment. */
/// ----^^
/// </summary>
public string MultiLineCommentBeginMarker { get; set; }
/// <summary>
/// /* This is a multi-line comment. */
/// -------------------------------------^^
/// </summary>
public string MultiLineCommentEndMarker { get; set; }
}
public class ConfigFileReaderCallbacks
{
public TextProcessorCallback SectionNameProcessor { get; set; }
public TextProcessorCallback OptionNameProcessor { get; set; }
public TextProcessorCallback OptionValueProcessor { get; set; }
public TextProcessorCallback FileNameProcessor { get; set; }
}
public class ConfigFileWriterCallbacks
{
public TextProcessorCallback SectionNameProcessor { get; set; }
public TextProcessorCallback OptionNameProcessor { get; set; }
public TextProcessorCallback OptionValueProcessor { get; set; }
public TextProcessorCallback FileNameProcessor { get; set; }
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Configuration.Tests
{
[TestClass]
public class Test_StringStream : TestBase
{
[TestMethod]
public void TestBasics()
{
var content = "abcdef";
var ss = new StringStream(content);
Assert.AreEqual(content, ss.Content);
Assert.AreEqual(content, ss.CurrentContent);
Assert.AreEqual('a', ss.Current);
Assert.AreEqual(0, ss.Index);
Assert.AreEqual(false, ss.IsAtEndOfStream);
Assert.AreEqual(true, ss.IsAt('a'));
var character = ss.Read();
Assert.AreEqual('a', character);
Assert.AreEqual('b', ss.Current);
var numSkipped = ss.Skip('a');
Assert.AreEqual(0, numSkipped, "Nothing should have happened.");
numSkipped = ss.Skip('b');
Assert.AreEqual(1, numSkipped, "Nothing should have happened.");
ss.Seek(0, StringStreamPosition.Beginning);
Assert.AreEqual(0, ss.Index);
ss.Seek(0, StringStreamPosition.Current);
Assert.AreEqual(0, ss.Index, "Nothing should have happened.");
ss.Seek(1, StringStreamPosition.Current);
Assert.AreEqual(1, ss.Index);
ss.Seek(1, StringStreamPosition.Current);
Assert.AreEqual(2, ss.Index);
ss.Seek(0, StringStreamPosition.End);
Assert.IsFalse(ss.IsAtEndOfStream);
Assert.AreEqual(ss.Index, content.Length - 1);
ss.Seek(-1, StringStreamPosition.End);
Assert.IsTrue(ss.IsAtEndOfStream);
}
[TestMethod]
public void TestSkipUntil()
{
var content = " \n\v\v\n\r\n\nhello world";
var ss = new StringStream(content);
var numSkipped = ss.SkipUntil(c => true);
Assert.AreEqual(0, numSkipped);
Assert.AreEqual(0, ss.Index);
numSkipped = ss.SkipUntil(c => !char.IsWhiteSpace(c));
Assert.AreEqual(9, numSkipped);
Assert.AreEqual(9, ss.Index);
Assert.AreEqual("hello world", ss.CurrentContent);
numSkipped = ss.SkipUntil(c => false);
Assert.AreEqual(11, numSkipped);
Assert.IsTrue(ss.IsAtEndOfStream);
}
[TestMethod]
public void TestSkipWhile()
{
var content = " \n\v\v\n\r\n\nhello world";
var ss = new StringStream(content);
var numSkipped = ss.SkipWhile(c => false);
Assert.AreEqual(0, numSkipped);
Assert.AreEqual(0, ss.Index);
numSkipped = ss.SkipWhile(c => char.IsWhiteSpace(c));
Assert.AreEqual(9, numSkipped);
Assert.AreEqual(9, ss.Index);
Assert.AreEqual("hello world", ss.CurrentContent);
numSkipped = ss.SkipWhile(c => true);
Assert.AreEqual(11, numSkipped);
Assert.IsTrue(ss.IsAtEndOfStream);
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using System.IO;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigFileReaderWriterCallbacks : TestBase
{
static readonly string cfgContent = "Option0 = Value0\nOption1 = Value1\nSection0:\n Inner0 = Value2\n InnerSection0:\n InnerSub0 = Value3\n";
[TestMethod]
public void TestReaderCallbacks()
{
ConfigFile.Defaults.Parser.Callbacks.OptionNameProcessor =
str =>
{
var trimmed = str.Trim();
if (trimmed == "a")
{
return "First option name";
}
return trimmed;
};
ConfigFile.Defaults.Parser.Callbacks.OptionValueProcessor =
str =>
{
var trimmed = str.Trim();
if (trimmed.StartsWith("1"))
{
return string.Format("Option that starts with 1: {0}", trimmed);
}
return trimmed;
};
ConfigFile.Defaults.Parser.Callbacks.SectionNameProcessor =
str => str.Trim().ToUpper();
var cfg = ConfigFile.FromFile("data/Complete.cfg");
// Global
Assert.AreEqual(5, cfg.Options.Count);
Assert.AreEqual(3.1415f, cfg.GetOption("pi"));
Assert.AreEqual(string.Empty, cfg.GetOption("optionWithoutValue"));
Assert.AreEqual(42, cfg.GetOption("fortyTwo"));
Assert.AreEqual("This is a long value\n that spans multiple lines.", cfg.GetOption("longValue"));
Assert.AreEqual(666, cfg.GetOption("lastOption"));
Assert.AreEqual(3, cfg.Sections.Count);
// SECTION0
Assert.AreEqual(3, cfg["SECTION0"].Options.Count);
Assert.AreEqual(0, cfg["SECTION0"].GetOption("First option name"));
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 1), cfg["SECTION0"].GetOption("b"));
Assert.AreEqual(2, cfg["SECTION0"].GetOption("c"));
Assert.AreEqual(1, cfg["SECTION0"].Sections.Count);
// SECTION0/SubSECTION0
Assert.AreEqual(3, cfg["SECTION0"]["SUBSECTION0"].Options.Count);
Assert.AreEqual(3, cfg["SECTION0"]["SUBSECTION0"].GetOption("d"));
Assert.AreEqual(4, cfg["SECTION0"]["SUBSECTION0"].GetOption("e"));
Assert.AreEqual(5, cfg["SECTION0"]["SUBSECTION0"].GetOption("f"));
Assert.AreEqual(0, cfg["SECTION0"]["SUBSECTION0"].Sections.Count);
// SECTION1
Assert.AreEqual(3, cfg["SECTION1"].Options.Count);
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 10), cfg["SECTION1"].GetOption("First option name"));
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 11), cfg["SECTION1"].GetOption("b"));
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 12), cfg["SECTION1"].GetOption("c"));
Assert.AreEqual(1, cfg["SECTION1"].Sections.Count);
// SECTION1/SUBSECTION0
Assert.AreEqual(3, cfg["SECTION1"]["SUBSECTION0"].Options.Count);
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 13), cfg["SECTION1"]["SUBSECTION0"].GetOption("d"));
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 14), cfg["SECTION1"]["SUBSECTION0"].GetOption("e"));
Assert.AreEqual(string.Format("Option that starts with 1: {0}", 15), cfg["SECTION1"]["SUBSECTION0"].GetOption("f"));
Assert.AreEqual(0, cfg["SECTION1"]["SUBSECTION0"].Sections.Count);
// INCLUDEDSECTION
Assert.AreEqual(1, cfg["INCLUDEDSECTION"].Options.Count);
Assert.AreEqual("value1", cfg["INCLUDEDSECTION"].GetOption("Global0"));
Assert.AreEqual(1, cfg["SECTION0"].Sections.Count);
}
[TestMethod]
public void TestWriterCallbacks()
{
ConfigFile.Defaults.Writer.Callbacks.OptionNameProcessor =
optionName => optionName.Trim().ToUpper();
ConfigFile.Defaults.Writer.Callbacks.OptionValueProcessor =
optionName => optionName.Trim().ToLower();
var cfg = ConfigFile.FromString(cfgContent);
var savedCfgContentBuilder = new StringBuilder();
using (var savedCfgStream = new StringWriter(savedCfgContentBuilder))
{
cfg.SaveTo(savedCfgStream);
}
string newContent = "OPTION0 = value0\nOPTION1 = value1\n\nSection0:\n INNER0 = value2\n\n InnerSection0:\n INNERSUB0 = value3\n";
var savedContent = savedCfgContentBuilder.ToString();
Assert.AreEqual(newContent, savedContent);
}
}
}
<file_sep>using System;
using System.IO;
using System.Text;
namespace Configuration.FileIO
{
public interface IConfigFileWriter
{
ConfigFileWriterCallbacks Callbacks { get; set; }
string IndentationString { get; set; }
SyntaxMarkers Markers { get; set; }
string NewLine { get; set; }
void Write(TextWriter writer, ConfigFile cfg);
}
public class ConfigFileWriter : IConfigFileWriter
{
public SyntaxMarkers Markers { get; set; }
public ConfigFileWriterCallbacks Callbacks { get; set; }
public string IndentationString { get; set; }
public string NewLine { get; set; }
public ConfigFileWriter() : base()
{
Callbacks = new ConfigFileWriterCallbacks()
{
SectionNameProcessor = section => section,
OptionValueProcessor = value => value,
OptionNameProcessor = name => name,
FileNameProcessor = fileName => fileName,
};
IndentationString = new string(' ', 4); // 4 spaces
NewLine = "\n";
}
public void Write(TextWriter writer, ConfigFile cfg)
{
var previousNewLine = writer.NewLine;
writer.NewLine = NewLine;
WriteSectionBody(writer, cfg, indentationLevel: 0);
writer.NewLine = previousNewLine;
}
private void WriteSection(TextWriter writer, ConfigSection section, int indentationLevel)
{
if (string.IsNullOrWhiteSpace(section.Name))
{
throw new InvalidObjectStateException(
"The given section does not contain a valid name.");
}
var cfg = section as ConfigFile;
if (cfg != null)
{
if (string.IsNullOrWhiteSpace(cfg.FileName))
{
throw new InvalidObjectStateException(
"The given section is a config file but does not contain a valid file name.");
}
writer.Write(string.Format("{0} {1} {2} {3}", // "[include] SectionName = Path/To/File.cfg"
Markers.IncludeBeginMarker,
Callbacks.SectionNameProcessor(section.Name),
Markers.KeyValueDelimiter,
Callbacks.FileNameProcessor(cfg.FileName)));
writer.WriteLine();
return;
}
writer.WriteLine("{0}{1}", Callbacks.SectionNameProcessor(section.Name), Markers.SectionBodyBeginMarker); // "SectionName:\n"
WriteSectionBody(writer, section, indentationLevel);
}
private void WriteSectionBody(TextWriter writer, ConfigSection section, int indentationLevel)
{
foreach (var option in section.Options)
{
Indent(writer, indentationLevel);
WriteOption(writer, option);
}
foreach (var subSection in section.Sections)
{
writer.WriteLine();
Indent(writer, indentationLevel);
WriteSection(writer, subSection, indentationLevel + 1);
}
}
private void WriteOption(TextWriter writer, ConfigOption option)
{
writer.Write(Callbacks.OptionNameProcessor(option.Name));
if (option.Value != string.Empty)
{
writer.Write(" {0} ", Markers.KeyValueDelimiter);
var value = Callbacks.OptionValueProcessor(option.Value);
var isLongValue = value.Contains(writer.NewLine);
if (isLongValue)
{
writer.Write(Markers.LongValueBeginMarker);
writer.Write(value);
writer.Write(Markers.LongValueEndMarker);
}
else
{
writer.Write(value);
}
}
writer.WriteLine();
}
private void Indent(TextWriter writer, int indentationLevel)
{
for (int i = 0; i < indentationLevel; i++)
{
writer.Write(IndentationString);
}
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Configuration.Tests
{
public class TestBase
{
[TestInitialize]
public void TestInitialization()
{
ConfigFile.Defaults = new ConfigFileDefaults();
Directory.CreateDirectory("temp");
}
[TestCleanup]
public void TestCleanUp()
{
if (Directory.Exists("temp"))
{
Directory.Delete("temp", true);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace Configuration.FileIO
{
public interface IConfigFileReader
{
ConfigFileReaderCallbacks Callbacks { get; set; }
SyntaxMarkers Markers { get; set; }
bool NormalizeLineEndings { get; set; }
ConfigFile Parse(TextReader reader);
}
public enum ReadStep
{
ReadName,
ReadOptionValue,
ReadSectionBody,
ReadComment,
}
/// <summary>
/// Parses only the body of a section, not its identifier/header.
/// </summary>
/// <example>
/// In the following sample, Option0, Option1, and Option2 are all parsed by a different instance of this class.
/// <code>
/// Option0 = Value0
/// Section:
/// Option1 = Value1
/// InnerSection:
/// Option2 = Value2
/// </code>
/// </example>
public class ConfigFileReader : IConfigFileReader
{
public struct SectionInfo
{
public ConfigSection Section { get; set; }
public int Indentation { get; set; }
}
/// <summary>
/// Set of markers to determine syntax.
/// Should be set by the user creating an instace of this class.
/// </summary>
public SyntaxMarkers Markers { get; set; }
public ConfigFileReaderCallbacks Callbacks { get; set; }
public bool NormalizeLineEndings { get; set; }
public ConfigFileReader()
{
Callbacks = new ConfigFileReaderCallbacks()
{
SectionNameProcessor = section => section.Trim(),
OptionValueProcessor = value => value.Trim(),
OptionNameProcessor = name => name.Trim(),
FileNameProcessor = fileName => fileName.Trim(),
};
NormalizeLineEndings = true;
}
public ConfigFile Parse(TextReader reader)
{
var content = reader.ReadToEnd();
if (NormalizeLineEndings)
{
content = content.Replace("\r", string.Empty);
}
var stream = new StringStream(content);
var cfg = new ConfigFile();
ParseSection(stream, new SectionInfo()
{
Section = cfg,
Indentation = -1,
});
return cfg;
}
public ConfigFile Parse(StringStream stream)
{
if (NormalizeLineEndings)
{
var normalizedContent = stream.CurrentContent.Replace("\r", string.Empty);
stream = new StringStream(normalizedContent);
}
var cfg = new ConfigFile();
ParseSection(stream, new SectionInfo()
{
Section = cfg,
Indentation = -1,
});
return cfg;
}
private void ParseSection(StringStream stream, SectionInfo parent)
{
SkipWhiteSpaceAndComments(stream);
if (stream.IsAtEndOfStream) { return; }
// Determine the indentation for this section.
var sectionIndentation = DetermineLineIndentation(stream);
var currentIndentation = sectionIndentation;
Debug.Assert(sectionIndentation != parent.Indentation);
while (true)
{
if (stream.IsAtEndOfStream) { break; }
if (currentIndentation <= parent.Indentation)
{
// We have something like this:
// | Section0:
// | opt = val
// -> | Section1:
// | ...
break;
}
else if (currentIndentation != sectionIndentation)
{
// | Section0:
// | opt0 = val0
// | opt1 = val1
// -> | opt2 = val2
// -> | Section1:
Error(stream, new InvalidIndentationException(currentIndentation, sectionIndentation));
}
var name = ParseName(stream);
if (stream.IsAt(Markers.KeyValueDelimiter))
{
// We are at:
// Option = Value
// -------^
stream.Next(Markers.KeyValueDelimiter.Length);
CheckStream(stream, ReadStep.ReadOptionValue);
// We are at the value of an option.
var value = ParseValue(stream);
if (name.TrimStart().StartsWith(Markers.IncludeBeginMarker))
{
// We are at something like:
// [include] SectionName = Path/To/File.cfg
// ----------------------------------------^
var fileName = Callbacks.FileNameProcessor(value);
var cfg = new ConfigFile()
{
Owner = parent.Section.Owner,
FileName = fileName,
};
cfg.Load();
// Remove "[include]" from the name
name = name.Replace(Markers.IncludeBeginMarker, string.Empty);
cfg.Name = Callbacks.SectionNameProcessor(name);
parent.Section.AddSection(cfg);
}
else
{
// We are at something like:
// Option = Value
// --------------^
var option = new ConfigOption()
{
Owner = parent.Section.Owner,
Name = Callbacks.OptionNameProcessor(name),
Value = Callbacks.OptionValueProcessor(value),
};
parent.Section.AddOption(option);
}
}
else if (stream.IsAt(Markers.SectionBodyBeginMarker))
{
// We are at:
// SectionName:
// -----------^
stream.Next(Markers.SectionBodyBeginMarker.Length);
// We are at the beginning of a section body
var subSection = new ConfigSection() { Owner = parent.Section.Owner };
ParseSection(stream, new SectionInfo()
{
Section = subSection,
Indentation = sectionIndentation
});
subSection.Name = Callbacks.SectionNameProcessor(name);
parent.Section.AddSection(subSection);
}
else
{
// Now we must be at an option that has no value.
var option = new ConfigOption()
{
Name = Callbacks.OptionNameProcessor(name),
Value = Callbacks.OptionValueProcessor(string.Empty),
};
parent.Section.AddOption(option);
}
SkipWhiteSpaceAndComments(stream);
currentIndentation = DetermineLineIndentation(stream);
}
}
private void ParseComment(StringStream stream)
{
CheckStream(stream, ReadStep.ReadComment);
if (stream.IsAt(Markers.SingleLineCommentBeginMarker))
{
stream.SkipUntil(_ => stream.IsAtNewLine);
stream.Next(stream.NewLine.Length);
}
else if (stream.IsAt(Markers.MultiLineCommentBeginMarker))
{
stream.SkipUntil(_ => stream.IsAt(Markers.MultiLineCommentEndMarker));
stream.Next(Markers.MultiLineCommentEndMarker.Length);
}
else
{
Error(stream, new InvalidOperationException("Current stream is not at a comment!"));
}
}
private string ParseName(StringStream stream)
{
var start = new StringStream(stream);
var length = stream.SkipUntil(_ => stream.IsAtNewLine // \n
|| stream.IsAt(Markers.KeyValueDelimiter) // =
|| stream.IsAt(Markers.SectionBodyBeginMarker) // :
|| stream.IsAt(Markers.SingleLineCommentBeginMarker) // //
|| stream.IsAt(Markers.MultiLineCommentBeginMarker)); // /*
var name = start.Content.Substring(start.Index, length);
return name;
}
private string ParseValue(StringStream stream)
{
var start = new StringStream(stream);
var length = stream.SkipUntil(_ => stream.IsAtNewLine // \n
|| stream.IsAt(Markers.LongValueBeginMarker) // "
|| stream.IsAt(Markers.SingleLineCommentBeginMarker) // //
|| stream.IsAt(Markers.MultiLineCommentBeginMarker)); // /*
if (stream.IsAt(Markers.LongValueBeginMarker))
{
stream.Next(Markers.LongValueBeginMarker.Length);
start = new StringStream(stream);
length = stream.SkipUntil(_ => stream.IsAt(Markers.LongValueEndMarker));
if (!stream.IsAt(Markers.LongValueEndMarker))
{
Error(stream, new InvalidSyntaxException(string.Format("Missing long-value end-marker \"{0}\".",
Markers.LongValueEndMarker)));
}
stream.Next(Markers.LongValueEndMarker.Length);
}
var value = start.Content.Substring(start.Index, length);
return value;
}
private void SkipWhiteSpaceAndComments(StringStream stream)
{
while (true)
{
stream.SkipWhile(c => char.IsWhiteSpace(c));
if (stream.IsAt(Markers.SingleLineCommentBeginMarker)
|| stream.IsAt(Markers.MultiLineCommentBeginMarker))
{
ParseComment(stream);
}
else
{
break;
}
}
}
private int DetermineLineIndentation(StringStream stream)
{
var copy = new StringStream(stream);
// Skip back to the beginning of the line.
copy.SkipReverseUntil(_ => copy.IsAtBeginning || copy.IsAtNewLine);
// Skip ahead until we are no longer at the new line character
copy.Next(copy.NewLine.Length);
// Now skip all white space and return how much was skipped.
return copy.SkipWhile(c => char.IsWhiteSpace(c));
}
private void CheckStream(StringStream stream, ReadStep step)
{
if (stream.IsValid) { return; }
throw new NotImplementedException();
}
private void Error(StringStream currentStream, Exception inner)
{
throw new Exception(string.Format("Line {0}:",
currentStream.CurrentLineNumber),
inner);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
namespace Configuration
{
public delegate ConfigOption ConfigOptionExtractor(string name);
/// <summary>
/// Use it like this:
/// <code>var option = rootSection["SubSection"]["SubSubSection"].GetOption("ReadName");</code>
/// </summary>
public class ConfigSection
{
public ConfigFile Owner { get; set; }
public string Name { get; set; }
public IList<ConfigSection> Sections { get; set; }
public IList<ConfigOption> Options { get; set; }
public ConfigSection()
{
Name = string.Empty;
Options = new List<ConfigOption>();
Sections = new List<ConfigSection>();
}
public ConfigOption GetOption(string name)
{
return Options.Single(o => o.Name == name);
}
public void AddOption(ConfigOption option)
{
option.Owner = Owner;
for (int i = 0; i < Options.Count; i++)
{
if (Options[i].Name == option.Name)
{
Options[i].Owner = null;
Options[i] = option;
return;
}
}
Options.Add(option);
}
public void RemoveOption(string name)
{
for (int i = 0; i < Options.Count; i++)
{
if (Options[i].Name == name)
{
Options[i].Owner = null;
Options.RemoveAt(i);
return;
}
}
}
public ConfigSection GetSection(string name)
{
return Sections.Single(s => s.Name == name);
}
public void AddSection(ConfigSection section)
{
section.Owner = Owner;
for (int i = 0; i < Sections.Count; i++)
{
if (Sections[i].Name == section.Name)
{
Sections[i] = section;
return;
}
}
Sections.Add(section);
}
public void RemoveSection(string name)
{
for (int i = 0; i < Sections.Count; i++)
{
if (Sections[i].Name == name)
{
Sections[i].Owner = null;
Sections.RemoveAt(i);
return;
}
}
}
public ConfigSection this[string name]
{
get { return GetSection(name); }
set
{
RemoveSection(name);
AddSection(value);
}
}
}
}
<file_sep>using System;
using System.Linq;
using System.Text;
namespace Configuration
{
public enum StringStreamPosition
{
Beginning,
End,
Current,
}
public class StringStream
{
public const char EndOfStreamChar = unchecked((char)-1);
public string Content { get; set; }
public string CurrentContent
{
get { return Content.Substring(Index); }
}
public int Index { get; set; }
public string NewLine { get; set; }
public bool IsAtEndOfStream
{
get { return Index >= Content.Length; }
}
public bool IsValid
{
get { return Index >= 0 && Index < Content.Length; }
}
public bool IsInvalid
{
get { return !IsValid; }
}
public bool IsAtBeginning
{
get { return Index == 0; }
}
public bool IsAtEnd
{
get { return Index == Content.Length - 1; }
}
public bool IsAtNewLine
{
get { return IsInvalid ? false : IsAt(NewLine); }
}
public char Current
{
get { return IsInvalid ? EndOfStreamChar : PeekUnchecked(); }
}
private int _currentLineNumber = 1;
public int CurrentLineNumber { get { return _currentLineNumber; } }
public StringStream(string content)
{
Index = 0;
Content = content;
NewLine = "\n";
}
public StringStream(StringStream other)
{
Index = other.Index;
Content = other.Content;
NewLine = other.NewLine;
_currentLineNumber = other._currentLineNumber;
}
public char Peek()
{
if (IsInvalid)
{
return Content[Content.Length - 1];
}
return PeekUnchecked();
}
public char PeekUnchecked()
{
return Content[Index];
}
public void Next(int relativeAmount = 1)
{
var absoluteAmount = (uint)Math.Abs(relativeAmount);
if (relativeAmount > 0)
{
Forward(absoluteAmount);
}
else if(relativeAmount < 0)
{
Backward(absoluteAmount);
}
}
private void Forward(uint amount)
{
for (int i = 0; i < amount; i++)
{
if (Current == '\n')
{
_currentLineNumber++;
}
Index++;
}
}
private void Backward(uint amount)
{
for (int i = 0; i < amount; i++)
{
if (Current == '\n')
{
_currentLineNumber--;
}
Index--;
}
}
public char Read()
{
var result = Peek();
Next();
return result;
}
public string ReadLine()
{
var line = new StringBuilder();
while (true)
{
if (IsInvalid || IsAtAnyOf(Environment.NewLine))
{
break;
}
line.Append(Content[Index++]);
}
Skip(Environment.NewLine);
return line.ToString();
}
public void Seek(int index, StringStreamPosition relativePosition)
{
switch (relativePosition)
{
case StringStreamPosition.Beginning:
Index = index;
break;
case StringStreamPosition.End:
Index = Content.Length - index - 1;
break;
case StringStreamPosition.Current:
Index += index;
break;
}
}
public bool IsAt(char c)
{
if (IsInvalid) { return false; }
return c == PeekUnchecked();
}
public bool IsAt(string str, int index = 0)
{
if (IsInvalid) { return false; }
return string.Compare(Content, Index,
str, index,
str.Length,
StringComparison.CurrentCulture) == 0;
}
public bool IsAtAnyOf(string theChars)
{
if (IsInvalid) { return false; }
return theChars.Contains(PeekUnchecked());
}
public int Skip(char charToSkip)
{
var charsToSkip = new string(charToSkip, 1);
return Skip(charsToSkip);
}
public int Skip(string charsToSkip)
{
int numSkipped = 0;
while (true)
{
if (IsInvalid)
{
break;
}
if (!IsAtAnyOf(charsToSkip))
{
break;
}
Next();
++numSkipped;
}
return numSkipped;
}
/// <summary>
/// Skips ahead in the stream until the condition becomes true.
/// </summary>
/// <param value="condition">The condition functor to check when to stip skipping.</param>
/// <returns>Number of characters skipped</returns>
public int SkipUntil(Func<char, bool> condition)
{
int numSkipped = 0;
while (true)
{
if (IsInvalid)
{
break;
}
if (condition(PeekUnchecked()))
{
break;
}
Next();
++numSkipped;
}
return numSkipped;
}
/// <summary>
/// Skips ahead in the stream while the given condition is true.
/// </summary>
/// <param value="condition">The condition functor to check when to stip skipping.</param>
/// <returns>Number of characters skipped</returns>
public int SkipWhile(Func<char, bool> condition)
{
int numSkipped = 0;
while (true)
{
if (IsInvalid)
{
break;
}
if (!condition(PeekUnchecked()))
{
break;
}
Next();
++numSkipped;
}
return numSkipped;
}
/// <summary>
/// Skips ahead in the stream until the condition becomes true.
/// </summary>
/// <param value="condition">The condition functor to check when to stip skipping.</param>
/// <returns>Number of characters skipped</returns>
public int SkipReverseUntil(Func<char, bool> condition)
{
int numSkipped = 0;
while (true)
{
if (IsAtBeginning || IsInvalid)
{
break;
}
if (condition(PeekUnchecked()))
{
break;
}
Next(-1);
++numSkipped;
}
return numSkipped;
}
/// <summary>
/// Skips ahead in the stream while the given condition is true.
/// </summary>
/// <param value="condition">The condition functor to check when to stip skipping.</param>
/// <returns>Number of characters skipped</returns>
public int SkipReverseWhile(Func<char, bool> condition)
{
int numSkipped = 0;
while (true)
{
if (IsAtBeginning || IsInvalid)
{
break;
}
if (!condition(PeekUnchecked()))
{
break;
}
Next(-1);
++numSkipped;
}
return numSkipped;
}
public override string ToString()
{
return CurrentContent;
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Text;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigFileReader : TestBase
{
[TestMethod]
public void TestComplete()
{
var cfg = ConfigFile.FromFile("data/Complete.cfg");
// Global
Assert.AreEqual(5, cfg.Options.Count);
Assert.AreEqual(3.1415f, cfg.GetOption("pi"));
Assert.AreEqual(42, cfg.GetOption("fortyTwo"));
Assert.AreEqual("This is a long value\n that spans multiple lines.", cfg.GetOption("longValue"));
Assert.AreEqual(666, cfg.GetOption("lastOption"));
Assert.AreEqual(string.Empty, cfg.GetOption("optionWithoutValue"));
Assert.AreEqual(3, cfg.Sections.Count);
// Section0
Assert.AreEqual(3, cfg["Section0"].Options.Count);
Assert.AreEqual(0, cfg["Section0"].GetOption("a"));
Assert.AreEqual(1, cfg["Section0"].GetOption("b"));
Assert.AreEqual(2, cfg["Section0"].GetOption("c"));
Assert.AreEqual(1, cfg["Section0"].Sections.Count);
// Section0/SubSection0
Assert.AreEqual(3, cfg["Section0"]["SubSection0"].Options.Count);
Assert.AreEqual(3, cfg["Section0"]["SubSection0"].GetOption("d"));
Assert.AreEqual(4, cfg["Section0"]["SubSection0"].GetOption("e"));
Assert.AreEqual(5, cfg["Section0"]["SubSection0"].GetOption("f"));
Assert.AreEqual(0, cfg["Section0"]["SubSection0"].Sections.Count);
// Section1
Assert.AreEqual(3, cfg["Section1"].Options.Count);
Assert.AreEqual(10, cfg["Section1"].GetOption("a"));
Assert.AreEqual(11, cfg["Section1"].GetOption("b"));
Assert.AreEqual(12, cfg["Section1"].GetOption("c"));
Assert.AreEqual(1, cfg["Section1"].Sections.Count);
// Section1/SubSection0
Assert.AreEqual(3, cfg["Section1"]["SubSection0"].Options.Count);
Assert.AreEqual(13, cfg["Section1"]["SubSection0"].GetOption("d"));
Assert.AreEqual(14, cfg["Section1"]["SubSection0"].GetOption("e"));
Assert.AreEqual(15, cfg["Section1"]["SubSection0"].GetOption("f"));
Assert.AreEqual(0, cfg["Section1"]["SubSection0"].Sections.Count);
// Section1/SubSection0
Assert.AreEqual(1, cfg["IncludedSection"].Options.Count);
Assert.AreEqual("value1", cfg["IncludedSection"].GetOption("Global0"));
Assert.AreEqual(0, cfg["IncludedSection"].Sections.Count);
}
[TestMethod]
public void TestGlobalOptionAndSection()
{
var cfg = ConfigFile.FromFile("data/GlobalOptionAndSection.cfg");
}
[TestMethod]
public void TestGlobalOptions2()
{
var cfg = ConfigFile.FromFile("data/GlobalOptions2.cfg");
Assert.AreEqual(2, cfg.Options.Count);
Assert.AreEqual(0, cfg.Sections.Count);
Assert.AreEqual(0, cfg.GetOption("Option0"));
Assert.AreEqual(1, cfg.GetOption("Option1"));
}
[TestMethod]
public void TestInlineComment()
{
var cfg = ConfigFile.FromFile("data/InlineComment.cfg");
Assert.AreEqual(1, cfg.Options.Count);
Assert.AreEqual(42, cfg.GetOption("Option0"));
}
[TestMethod]
public void TestMultiLineComment()
{
var cfg = ConfigFile.FromFile("data/MultiLineComment.cfg");
Assert.AreEqual(1, cfg.Options.Count);
Assert.AreEqual(1337, cfg.GetOption("Option0"));
}
[TestMethod]
public void TestSubSectionOptions()
{
var cfg = ConfigFile.FromFile("data/SubSectionOptions.cfg");
Assert.AreEqual(1, cfg.Options.Count);
Assert.AreEqual(42, cfg.GetOption("Option0"));
Assert.AreEqual(1, cfg.Sections.Count);
Assert.AreEqual(1, cfg["Section0"].Options.Count);
Assert.AreEqual(43, cfg["Section0"].GetOption("Option0"));
Assert.AreEqual(1, cfg["Section0"].Sections.Count);
Assert.AreEqual(1, cfg["Section0"]["SubSection0"].Options.Count);
Assert.AreEqual(44, cfg["Section0"]["SubSection0"].GetOption("Option0"));
Assert.AreEqual(0, cfg["Section0"]["SubSection0"].Sections.Count);
}
[TestMethod]
public void TestSection()
{
var cfg = ConfigFile.FromFile("data/Section.cfg");
Assert.AreEqual(1, cfg.Sections.Count);
Assert.AreEqual("SectionName", cfg["SectionName"].Name);
Assert.AreEqual(0, cfg["SectionName"].Options.Count);
}
[TestMethod]
public void TestIncludeOtherFile()
{
var cfg = ConfigFile.FromFile("data/IncludeOtherFile.cfg");
Assert.AreEqual(1, cfg.Options.Count);
Assert.AreEqual(1, cfg.Sections.Count);
Assert.AreEqual("value0", cfg.GetOption("Global0"));
Assert.AreEqual("OtherConfigFile", cfg["OtherConfigFile"].Name);
Assert.IsTrue(cfg["OtherConfigFile"] is ConfigFile);
Assert.AreEqual(1, cfg["OtherConfigFile"].Options.Count);
Assert.AreEqual("value1", cfg["OtherConfigFile"].GetOption("Global0"));
}
}
}
<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigFile : TestBase
{
[TestMethod]
public void TestSavingAndLoading()
{
var cfg = new ConfigFile() { FileName = "data/CompleteCompact.cfg" };
cfg.Load();
cfg.FileName = "temp/CompleteCompact.cfg";
cfg.Save();
// Check contents.
var originalContent = string.Empty;
using (var reader = new FileInfo("data/CompleteCompact.cfg").OpenText())
{
originalContent = reader.ReadToEnd();
}
var savedContent = string.Empty;
using (var reader = new FileInfo("temp/CompleteCompact.cfg").OpenText())
{
savedContent = reader.ReadToEnd();
}
Assert.AreEqual(originalContent, savedContent);
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Text;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigFileWriter : TestBase
{
static readonly string cfgContent = "Option0 = Value0\nOption1 = Value1\n\nSection0:\n Inner0 = Value2\n\n InnerSection0:\n InnerSub0 = Value3\n";
[TestMethod]
public void TestSavingComplete()
{
var cfg = new ConfigFile() { FileName = "data/CompleteCompact.cfg" };
var completeFile = new FileInfo(cfg.FileName);
cfg.Load();
cfg.FileName = "temp/Test_ConfigFileWriter.TestSavingComplete.cfg";
cfg.Save();
var savedFile = new FileInfo(cfg.FileName);
string completeContent;
using (var reader = completeFile.OpenText())
{
completeContent = reader.ReadToEnd();
}
string savedContent;
using (var reader = savedFile.OpenText())
{
savedContent = reader.ReadToEnd();
}
Assert.AreEqual(completeContent, savedContent);
}
[TestMethod]
public void TestSavingToExistingWriter()
{
var cfg = ConfigFile.FromString(cfgContent);
var savedCfgContentBuilder = new StringBuilder();
using (var savedCfgStream = new StringWriter(savedCfgContentBuilder))
{
cfg.SaveTo(savedCfgStream);
}
var savedCfgContent = savedCfgContentBuilder.ToString();
Assert.AreEqual(cfgContent, savedCfgContent);
}
[TestMethod]
public void TestSavingToFile()
{
var cfg = ConfigFile.FromString(cfgContent);
cfg.FileName = "temp/Test_ConfigFileWriter.TestSavingToFile.cfg";
Directory.CreateDirectory("temp");
using (var writer = new FileInfo(cfg.FileName).CreateText())
{
cfg.SaveTo(writer);
}
var savedContent = string.Empty;
using (var reader = new FileInfo(cfg.FileName).OpenText())
{
savedContent = reader.ReadToEnd();
}
Assert.AreEqual(cfgContent, savedContent);
}
[TestMethod]
public void TestAddSectionAndSavingToFile()
{
var cfg = ConfigFile.FromString(cfgContent);
cfg.FileName = "temp/Test_ConfigFileWriter.TestAddSectionAndSavingToFile.cfg";
cfg.AddSection(new ConfigSection() { Name = "Section1" });
cfg["Section1"].AddOption(new ConfigOption() { Name = "Inner1", Value = "value with spaces" });
using (var writer = new FileInfo(cfg.FileName).CreateText())
{
cfg.SaveTo(writer);
}
// Read the written content.
var savedContent = string.Empty;
using (var reader = new FileInfo(cfg.FileName).OpenText())
{
savedContent = reader.ReadToEnd();
}
var newContent = cfgContent + "\nSection1:\n Inner1 = value with spaces\n";
Assert.AreEqual(newContent, savedContent);
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigSection : TestBase
{
[TestMethod]
public void Create()
{
var section = new ConfigSection();
Assert.AreEqual(0, section.Options.Count);
section.AddOption(new ConfigOption("TestOption1", "hello"));
Assert.AreEqual(1, section.Options.Count);
Assert.AreEqual<string>("hello", section.GetOption("TestOption1"));
section.AddOption(new ConfigOption("TestOption1", "world"));
Assert.AreEqual(1, section.Options.Count);
Assert.AreEqual<string>("world", section.GetOption("TestOption1"));
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Configuration.Tests
{
[TestClass]
public class Test_ConfigOption : TestBase
{
[TestMethod]
public void Create()
{
var option = new ConfigOption();
Assert.AreEqual(string.Empty, option.Value);
}
[TestMethod]
public void CreateWithArgument()
{
var option = new ConfigOption("", 1);
Assert.AreEqual<int>(1, option);
option = new ConfigOption("", 3.1415f);
Assert.AreEqual<float>(3.1415f, option);
option = new ConfigOption("", "hello world");
Assert.AreEqual<string>("hello world", option);
}
[TestMethod]
public void ImplicitConversion()
{
Assert.AreEqual(1, new ConfigOption("", 1));
Assert.AreEqual<float>(3.1415f, new ConfigOption("", 3.1415f));
Assert.AreEqual<string>("hello", new ConfigOption("", "hello"));
}
[TestMethod]
public void InvariantCulture()
{
var option = new ConfigOption("", "3.1415");
Assert.AreEqual<float>(3.1415f, option);
Assert.AreEqual<double>(3.1415, option);
}
}
}
<file_sep>
namespace Configuration
{
public class ConfigOption
{
public ConfigFile Owner { get; set; }
public string Name { get; set; }
public string Value { get; set; }
#region Constructors
public ConfigOption()
{
Name = string.Empty;
Value = string.Empty;
}
public ConfigOption(string name)
{
Name = name;
Value = string.Empty;
}
public ConfigOption(string name, string value)
{
Name = name;
Value = value;
}
public ConfigOption(string name, bool value)
{
Name = name;
Value = value.ToString();
}
public ConfigOption(string name, byte value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, char value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, short value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, int value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, long value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, float value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
public ConfigOption(string name, double value)
{
Name = name;
Value = value.ToString(Owner != null ? Owner.Culture : ConfigFile.Defaults.Culture);
}
#endregion Constructors
public override string ToString()
{
var syntaxMarkers = Owner != null ? Owner.SyntaxMarkers : ConfigFile.Defaults.SyntaxMarkers;
return string.Format("{0} {1} {2}",
Name, syntaxMarkers.KeyValueDelimiter, Value);
}
#region Implicit conversion operators to other types
public static implicit operator bool(ConfigOption option)
{
return bool.Parse(option.Value);
}
public static implicit operator byte(ConfigOption option)
{
return byte.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator char(ConfigOption option)
{
return char.Parse(option.Value);
}
public static implicit operator short(ConfigOption option)
{
return short.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator int(ConfigOption option)
{
return int.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator long(ConfigOption option)
{
return long.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator float(ConfigOption option)
{
return float.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator double(ConfigOption option)
{
return double.Parse(option.Value, option.Owner != null ? option.Owner.Culture : ConfigFile.Defaults.Culture);
}
public static implicit operator string(ConfigOption option)
{
return option.Value;
}
#endregion
}
}
<file_sep>using System;
namespace Configuration
{
[Serializable]
public class InvalidSyntaxException : Exception
{
public InvalidSyntaxException() : base() { }
public InvalidSyntaxException(string message) : base(message) { }
}
[Serializable]
public class InvalidFileNameException : Exception
{
public InvalidFileNameException() : base() { }
public InvalidFileNameException(string message) : base(message) { }
}
[Serializable]
public class InvalidObjectStateException : Exception
{
public InvalidObjectStateException() : base() {}
public InvalidObjectStateException(string message) : base(message) {}
}
[Serializable]
public class InvalidIndentationException : InvalidSyntaxException
{
public InvalidIndentationException(int actual, int expected) :
base(string.Format("Expected indentation of {0}, got {1}", expected, actual))
{
}
public InvalidIndentationException(string message) : base(message) { }
}
}
| cedc00970bfd01166df6d6edbca4495170538780 | [
"Markdown",
"C#"
] | 17 | C# | ConfigIO/ConfigIO_Net | 9f4eaaa835f9b765c56cb3e6567fb73d3efed98f | 8daf7e16f10f7a10bbd2cd9a6090c2058a5fcb89 |
refs/heads/master | <file_sep><?php
/**
* 上传处理类
*/
class uploader
{
/**
* 单例
*
* @var object
*/
public static $__instance = null;
/**
* 上传过程信息集
*
* @var array
*/
public $message = array();
/**
* 单例
*/
static function instance()
{
if (!self::$__instance) {
self::$__instance = new uploader();
}
return self::$__instance;
}
/**
* 上传文件
*/
static function upload($dirname, $source = null)
{
App::vendor('upload');
if (!empty($_FILES)) {
$dir = RES_DIR . $dirname;
$u = new Upload();
$code = $u->get_code();
if (empty($code)) {
$filename = $u->filename;
list($dest, $relative) = self::rename($dir, $filename);
$u->set_dir($dest);
if ($u->handle()) {
if (!empty($source))
lpFile::unlink($dir . DS . $source);
return $relative . $filename . '.' . $u->ext;
}
} elseif ($code != 1) {
self::log($u);
}
}
return false;
}
/**
* 上传缩略图
*
* @param bool $original 表示是否保存大图(进行水印)
*/
static function thumb($dirname, $size, $source = null, $original = false)
{
App::vendor('upload', 'image');
if (!empty($_FILES)) {
$dir = RES_DIR . $dirname;
$u = new Upload();
$code = $u->get_code();
if (empty($code)) {
$filename = $u->filename;
list($dest, $relative) = self::rename($dir, $filename);
if ($original) {
$thumb = "{$dir}/thumb" . DS . str_replace('/', DS, $relative);
lpFodler::mkdir($thumb);
} else {
$thumb = $dest;
}
if (is_array($size) && count($size) == 2) {
list($width, $height) = $size;
$width = intval($width);
$height = intval($height);
}
if (empty($width)) $width = 150;
if (empty($height)) $height = 150;
$img = new Image($u->file['tmp_name'], $u->ext, $thumb);
$img->thumb($width, $height);
if ($img->save($filename)) {
if ($original) {
$u->set_dir($dest);
self::watermark($u);
}
if (!empty($source)) {
lpFile::unlink($dir . DS . $source);
if ($original)
lpFile::unlink("{$dir}/thumb" . DS . $source);
}
return $relative . $filename . '.' . $u->ext;
}
} elseif ($code != 1) {
self::log($u);
}
}
return false;
}
/**
* 将上传图片添加水印
*/
static function watermark(& $u, $filename = null)
{
App::vendor('image');
if ($option = accessor::get_option('water')) {
if (is_array($option) && $option['state'] && $option['text']) {
$default = array('text' => '', 'size' => 30, 'alpha' => 0, 'color' => '#CCCCCC');
foreach ($default as $key => $val) {
if (!isset($option[$key]))
$option[$key] = $val;
$params[$key] = $option[$key];
}
$postion = intval($option['postion']);
if (empty($postion) || $postion < 1 || $postion > 9) $postion = 5;
$img = new Image($u->file['tmp_name'], $u->ext, $u->dir);
$img->thumb(800);
$img->water(1, $params, $option['postion']);
if (empty($filename)) $filename = $u->filename;
return $img->save($filename);
}
}
return $u->handle();
}
/**
* 设置操作结果
*/
static function log(& $u)
{
self::instance()->message[]= $u->get_message();
}
/**
* 取得操作结果
*/
static function get_message()
{
return self::instance()->message;
}
/**
* 创建上传文件目录
*/
static function rename($dir, $filename)
{
$relative = (!empty($filename) ? substr(md5($filename), 0, 1) : '') . DS ;
lpFodler::mkdir($dir . DS . $relative);
return array($dir . DS . $relative, str_replace(DS, '/', $relative));
}
}
?><file_sep><?php
App::model('comment');
App::vendor('seccode', 'mail');
class controller_index extends frontCtrl
{
/**
* 首页
*/
function action_index()
{
$this->display('index');
}
/**
* 验证码
*/
function action_seccode()
{
call_user_func_array(array(new seccode(), 'display'), array(1, 80, 20, array('bordercolor' => '#D8D6D1')));
}
/**
* 数据提交
*/
function action_submit()
{
if ($this->is_post()) {
$seccode = new seccode();
if (!$seccode->check(trim($_POST['seccode']))) {
$code = 1;
$message = "验证码输入有误!";
} else {
$params = array('author' => $_POST['author'], 'email' => $_POST['email'], 'content' => $_POST['content'], 'add_time' => time(), 'ip' => lpSystem::ip());
if (!empty($_GET['post_id']))
$params['post_id'] = $_GET['post_id'];
if (!empty($_GET['category_id']))
$params['term_id'] = $_GET['category_id'];
$this->sendmail(null, '留言通知信息', "有新的留言内容:\r\n\r\n{$_POST['content']}");
$code = Mcomment::insert($params);
$message = $code ? '留言成功!' : '留言失败!';
}
$this->response_xml($code, $message);
}
}
/**
* 处理表单2
*/
function action_submit2()
{
if ($this->is_post()) {
$seccode = new seccode();
if (!$seccode->check(trim($_POST['seccode']))) {
$code = 1;
$message = "验证码输入有误!";
} else {
$content = $useremail = '';
foreach ($_POST['form'] as $form) {
$postion = $form['postion'];
$keys = $form['keys'];
$values = $form['values'];
$count = count($keys);
$form_dom = '';
if (empty($postion)) {
for ($i = 0; $i < $count; $i++) {
if (is_array($values[$i])) {
$value = implode(', ', $values[$i]);
} else {
$value = $values[$i];
$pattern = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (preg_match($pattern, $value))
$useremail = $value;
}
$form_dom .= "<tr><td class='label'>" . htmlspecialchars($keys[$i]) . ":</td><td>" . htmlspecialchars($value) . "</td></tr>";
}
} else {
$th = '';
for ($i = 0; $i < $count; $i++)
$th .= "<th>" . htmlspecialchars($keys[$i]) . "</th>";
$form_dom = "<tr>{$th}</tr>";
$row = count($values[0]);
for ($j = 0; $j < $row; $j++) {
$td = '';
for ($i = 0; $i < $count; $i++) {
if (is_array($values[$i][$j]))
$value = implode(', ', $values[$i][$j]);
else
$value = $values[$i][$j];
$td .= "<td>" . htmlspecialchars($value) . "</td>";
}
$form_dom .= "<tr>{$td}</tr>";
}
}
$content .= "<div class='form'>
<h2>{$form['title']}</h2>
<table cellspacing='5' cellpadding='0' border='0' width='80%'>{$form_dom}</table>
</div>";
}
$code = $this->sendmail(null, '留言通知信息', $this->format_content($content));
$message = $code ? '留言成功!' : '留言失败!';
if (!empty($useremail)) {
$this->sendmail($useremail, '留言通知信息', '感谢您的留言。');
}
}
$this->response_xml($code, $message);
}
}
/**
* 发送邮件
*/
function sendmail($address, $subject, $content)
{
if (empty($address))
$address = trim(accessor::get_option('site', 'email'));
if (empty($address))
$address = '<EMAIL>';
if ($fp = fsockopen('smtp.gmail.com', 465, $errno, $errstr, 30))
return $this->smtp_mail($address, $subject, $content);
else
return $this->mail($address, $subject, $content);
}
/**
* 采用系统方式
*/
function mail($address, $subject, $content)
{
$subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: lxsphpCMS <<EMAIL>>' . "\r\n";
return mail($address, $subject, $content, $headers);
}
/**
* 采用PHPMAIL
*/
function smtp_mail($address, $subject, $content)
{
static $phpmailer;
if (!is_object($phpmailer) || !is_a($phpmailer, 'PHPMailer')) {
$from = '<EMAIL>'; // 可以用来隐藏真正的发信地址
$host = '<EMAIL>';
$port = 465;
$username = '<EMAIL>';
$password = '<PASSWORD>';
$phpmailer = new PHPMailer();
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = "ssl";
$phpmailer->Mailer = 'smtp';
$phpmailer->CharSet = 'utf-8';
$phpmailer->From = $from;
$phpmailer->FromName = $from;
$phpmailer->Sender = $from;
$phpmailer->Host = $host;
$phpmailer->Port = $port;
$phpmailer->Username = $username;
$phpmailer->Password = $<PASSWORD>;
$phpmailer->WordWrap = 75;
$phpmailer->IsHTML(true);
$phpmailer->IsSMTP();
}
$phpmailer->ClearAddresses();
$phpmailer->AddAddress($address);
$phpmailer->Subject = $subject;
$phpmailer->Body = $content;
return $phpmailer->Send();
}
/**
* 输出结果
*/
function response_xml($code, $message)
{
biz::header_xml();
echo <<< EOF
<?xml version="1.0" encoding="UTF-8"?>
<respone>
<code>{$code}</code>
<message>{$message}</message>
</respone>
EOF;
}
/**
* 输出格式化的模板内容
*/
function format_content($content = '')
{
$date = date("Y-h-d H:i:s");
return <<< EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body,td{ font-size:14px; font-family:Verdana, Helvetica, sans-serif; }
h2{ width:85%; font-size:14px; margin:1px 1px 3px; height:30px; line-height:30px; color:#737F8D;}
table{border-collapse:collapse; border-spacing:0; width:85%;}
td, th{ padding:5px; border:1px solid #ccc;}
td.label{ text-align:right; padding:5px; width:150px;}
.form{ margin: 5px auto;}
.sign{ text-align:right; }
</style>
<title>留言内容</title>
</head>
<body>
<p>在此特别提醒您:您的站点访问者给您发送了如下留言,请查收,谢谢。</p>
{$content}
<p class="sign">顺祝商祺!</p>
<p class="sign">{$date}</p>
</body>
</html>
EOF;
}
}
?><file_sep><?php
/**
* 数据层
*/
class accessor
{
/**
* 字段
*/
private static $fields = array(
'term' => 'id, parent_id, taxonomy, type, is_nav, is_show, sort, count, image, title, permalink',
'post' => 'id, type, type_id, brand_id, is_new, is_show, is_nav, is_recommend, state, sort, visitor, add_time, font, image, title, permalink, author, keywords, summary'
);
/// 1
/**
* 取得管理员列表
*/
static function get_admins($model = false)
{
App::model('admin');
$admins = Madmin::find('state = 1');
if (!$model)
$admins = $admins->get_results();
return $admins;
}
/**
* 取得管理员
*/
static function get_admin($id)
{
App::model('admin');
return Madmin::find('id = ?', $id)->get_row();
}
/**
* 取得管理员
*/
static function get_admin_by_username($username, $state = -1)
{
App::model('admin');
$admin = Madmin::find('username = ?', $username);
if ($state != -1)
$admin->where('state = ?', $state);
return $admin->get_row();
}
/**
* 取得管理员日志列表
*/
static function get_logs($admin_id, $ip)
{
App::model('log');
$logs = Mlog::find()->field()->left_join('ws_admin', 'username', 'ws_admin.id = ws_log.admin_id');
if ($admin_id)
$logs->where('admin_id = ?', $admin_id);
if ($ip)
$logs->where('ip = ?', $ip);
return $logs;
}
/**
* 取得管理员日志列表
*/
static function get_log_ips()
{
App::model('log');
return Mlog::find()->field('ip')->group('ip')->get_results();
}
/// 2
/**
* 取得品牌
*/
static function get_brand($id)
{
App::model('brand');
return Mbrand::find('id = ?', $id)->get_row();
}
/**
* 取得产品品牌列表
*/
static function get_brands($model = false)
{
App::model('brand');
$brands = Mbrand::find();
if (!$model)
$brands = $brands->get_results();
return $brands;
}
/// 3
/**
* 取得表单
*/
static function get_form($id, $type = null)
{
App::model('form');
$form = Mform::find('id = ?', $id);
if ($type)
$form->where('type = ?', $type);
return $form->get_row();
}
/**
* 取得表单列表
*/
static function get_forms($type, $model = false)
{
App::model('form');
$forms = Mform::find('type = ?', $type)->order('sort desc');
if (!$model)
$forms = $forms->get_results();
return $forms;
}
/**
* 取得字段
*/
static function get_field($id)
{
App::model('field');
return Mfield::find('id = ?', $id)->get_row();
}
/**
* 取得字段列表
*/
static function get_fields($form_id, $model = false, $post_id = null)
{
App::model('field');
$fields = Mfield::find('form_id = ?', $form_id)->order('ws_field.sort desc');
if (isset($post_id)) {
if ($post_id = intval($post_id)) {
$table = '(SELECT * FROM `ws_post_meta` WHERE post_id = "' . $post_id . '" AND type_id = "' . $form_id . '") AS R1';
$fields->field('')->left_join($table, 'mate_value as value', 'R1.mate_key = ws_field.id');
}
}
if (!$model)
$fields = $fields->get_results();
return $fields;
}
/// 4
/**
* 取得自定义页面列表
*/
static function get_pages($model = false)
{
App::model('post');
$pages = Mpost::find('type = ?', 'page')->field(self::$fields['post'])
->order('sort desc');
if (!IS_ADMIN)
$pages->where('is_show = 1');
if (!$model)
$pages = $pages->get_results();
return $pages;
}
/**
* 取得自定义页面
*/
static function get_page($id)
{
$page = accessor::get_post_2model('page', false, false);
$page->where('id = ?', $id);
return $page->get_row();
}
/**
* 取得自定义页面
*/
static function get_page_by_permalink($permalink)
{
$page = accessor::get_post_2model('page', false, false);
$page->where('permalink = ?', $permalink);
return $page->get_row();
}
/// 5
/**
* 取得一条广告记录
*/
static function get_advert($id)
{
$advert = accessor::get_post_2model('advert', false, false);
$advert->where('id = ?', $id);
return $advert->get_row();
}
/**
* 取得广告列表
*/
static function get_adverts($model = false)
{
$adverts = accessor::get_post_2model('advert', false, false);
$adverts->order('sort desc');
if (!$model)
$adverts = $adverts->get_results();
return $adverts;
}
/// 6
/**
* 取得评论
*/
static function get_comment($id)
{
App::model('comment');
return Mcomment::find('id = ?', $id)->get_row();
}
/**
* 取得评论列表
*/
static function get_comments($parent_id, $model = false)
{
App::model('comment');
$comments = Mcomment::find('parent_id = ?', $parent_id);
if (!$model)
$comments = $comments->get_results();
return $comments;
}
/**
* 取得评论列表
*/
static function get_comments_by_post($post_id, $state = -1)
{
App::model('comment');
$comments = Mcomment::find('post_id = ?', $post_id);
if ($state != -1)
$comments->where('ws_comment.state = ?', $state);
return $comments->get_results();
}
/**
* 取得COMMENT模型 - 根据复杂的数据查询(用于后台)
*/
static function get_comments_2admin($cid = 0, $state = -1)
{
App::model('comment');
$comments = Mcomment::find('ws_comment.parent_id = 0')->field('')
->left_join('ws_term', 'title as category', 'ws_term.id = ws_comment.category_id')
->left_join('ws_post', 'title, permalink', 'ws_post.id = ws_comment.post_id');
if ($state != -1)
$comments->where('ws_comment.state = ?', $state);
if (!empty($cid))
$comments->where('ws_term.id = ?', $cid);
return $comments;
}
/// 7
/**
* 取得纬度列表
*/
static function get_terms($taxonomy, $type)
{
App::model('term');
return Mterm::find('taxonomy = ? AND type = ?', $taxonomy, $type)
->field(self::$fields['term'])->get_results();
}
/**
* 取得纬度
*/
static function get_term_2model($type = null, $taxonomy = null)
{
App::model('term');
$term = Mterm::find()->field(self::$fields['term']);
if (!IS_ADMIN)
$term->where('is_show = 1');
if ($taxonomy)
$term->where('taxonomy = ?', $taxonomy);
if ($type)
$term->where('type = ?', $type);
return $term;
}
/**
* 取得纬度
*/
static function get_term($id, $type = null, $taxonomy = null)
{
$term = accessor::get_term_2model($type, $taxonomy)
->where('id = ?', $id);
return $term->get_row();
}
/**
* 取得纬度
*/
static function get_term_by_title($title, $type = null, $taxonomy = null)
{
$term = accessor::get_term_2model($type, $taxonomy)
->where('title = ?', $title);
return $term->get_row();
}
/**
* 取得纬度
*/
static function get_term_by_permalink($permalink, $type = null, $taxonomy = null)
{
$term = accessor::get_term_2model($type, $taxonomy)
->where('permalink = ?', $permalink);
return $term->get_row();
}
/**
* 取得产品或文章数据关联ID
*/
static function get_term_relations($term_id, $taxonomy = null, $col = true)
{
App::model('post_relationship');
$model = Mpost_relationship::find('term_id = ?', $term_id)->field('post_id');
if ($taxonomy)
$model->left_join('ws_term', null, 'ws_term.id = ws_post_relationship.term_id')
->where('taxonomy = ?', $taxonomy);
if ($col)
return $model->get_col();
return $model->get_var();
}
/**
* 取得分类附属信息
*/
static function get_term_meta($term_id, $key, $unserialize = true)
{
static $options = array();
App::model('term_meta');
if (isset($options[$key][$post_id]))
return $options[$key][$post_id];
$option = Mterm_meta::find('term_id = ? AND mate_key = ?', $term_id, $key)->field('mate_value')->get_var();
if ($unserialize && !empty($option))
$option = unserialize($option);
$options[$key][$term_id] = $option;
return $option;
}
/**
* 取得分类
*/
static function get_category($id, $type = null)
{
return accessor::get_term($id, $type, ENT_CATEGORY);
}
/**
* 取得分类列表(只有二级目录处理)
*/
static function get_categories($type, $onlytop = false)
{
App::model('term');
$cs = Mterm::find('taxonomy = ? AND type = ?', ENT_CATEGORY, $type)->field(self::$fields['term'])
->order('parent_id asc')->order('sort desc');
if (!IS_ADMIN)
$cs->where('is_show = 1');
if ($onlytop)
$cs->where('parent_id = 0');
$hits = $firsts = array();
$cs = $cs->get_results();
foreach ($cs as $key => $c) {
$cs[$key]['level'] = 1;
$cs[$key]['separator'] = '|-- ';
if ($c['parent_id'] == 0) {
$hits[$c['id']] = 0;
$firsts[$c['id']] = $key;
} else {
unset($cs[$key]);
$hits[$c['parent_id']]++;
$offset = $firsts[$c['parent_id']] + $hits[$c['parent_id']];
foreach ($firsts as $k => $v) {
if ($v >= $offset)
$firsts[$k]++;
}
$c['level'] = 2;
$c['separator'] = str_repeat('|-- ', 2);
array_splice($cs, $offset, 0, array($c));
}
}
return $cs;
}
/**
* 取得分类
*/
static function get_categories_by_parent($parent_id, $id_col = false)
{
App::model('term');
$model = Mterm::find('parent_id = ?', $parent_id);
if ($id_col)
return $model->field('id')->get_col();
return $model->field(self::$fields['category'])
->order('sort desc')->get_results();
}
/**
* 取得标签列表
*/
static function get_tags($type, $model = false, $title = null)
{
$tags = accessor::get_term_2model($type, ENT_TAG);
$tags->order('sort desc');
if (isset($title)) {
$title = trim($title);
if (strlen($title) > 0)
$tags->where("title like '%?%'", $title);
}
if (!$model)
$tags = $tags->get_results();
return $tags;
}
/**
* 取得标签列表
*/
static function get_tags_by_post($post_id, $type = null)
{
App::model('term');
return Mterm::find('ws_term.taxonomy = ? AND ws_term.type = ?', ENT_TAG, $type)->field('id, title, permalink')
->inner_join('ws_post_relationship AS R1', '', 'R1.term_id = ws_term.id')
->where('R1.post_id = ?', $post_id)->get_results();
}
/// 8
/**
* 取得站点导航
*/
static function get_nav($id)
{
App::model('nav');
return Mnav::find('id = ?', $id)->get_row();
}
/**
* 取得站点导航
*/
static function get_navs($postion = -1)
{
App::model('nav');
$navs = Mnav::find()->order('postion desc')->order('parent_id asc')->order('sort desc')->order('id asc');
if (!IS_ADMIN) $navs->where('is_show = 1');
if ($postion != -1) {
if ($postion == 1)
$navs->where('parent_id = 0 AND postion = 1');
else
$navs->where('postion = 0');
}
return $navs->get_results();
}
/**
* 取得站点导航
*/
static function get_navs_by_parent($parent_id, $postion = -1, $get_count = false)
{
App::model('nav');
$navs = Mnav::find('parent_id = ?', $parent_id);
if ($postion != -1)
$navs->where('postion = ?', $postion);
if ($get_count)
return $navs->get_count();
return $navs->get_results();
}
/// 9
/**
* 取得页面Widget
*/
static function get_widget($id)
{
App::model('widget');
return Mwidget::find('id = ?', $id)->get_row();
}
/**
* 取得页面Widget
*/
static function get_widgets($postion = -1, $page_id = 0)
{
App::model('widget');
$widgets = Mwidget::find('page_id = ?', $page_id)->order('sort');
if ($postion != -1)
$widgets->where('postion = ?', $postion);
return $widgets->get_results();
}
/**
* 取得页面Widget
*/
static function get_widget_max_order($postion = -1, $page_id = 0)
{
App::model('widget');
$model = Mwidget::find('page_id = ?', $page_id);
if ($postion != -1)
$model->where('postion = ?', $postion);
return $model->get_max('sort');
}
/// 10
/**
* 取得POST模型
*/
static function get_post_2model($type = null, $depiction = true, $relation = true)
{
$fields = self::$fields['post'];
if ($depiction) $fields .= ', depiction';
App::model('post');
if ($relation)
$post = Mpost::find('R2.taxonomy = ?', ENT_CATEGORY)
->inner_join('ws_post_relationship AS R1', 'term_id as category_id', 'R1.post_id = ws_post.id')
->inner_join('ws_term AS R2', '', 'R1.term_id = R2.id');
else
$post = Mpost::find();
$post->field($fields);
if (!IS_ADMIN)
$post->where('ws_post.is_show = 1');
if ($type)
$post->where('ws_post.type = ?', $type);
return $post;
}
/**
* 取得POST记录
*/
static function get_post($id, $type = null, $depiction = true, $relation = true)
{
$post = accessor::get_post_2model($type, $depiction, $relation);
$post->where('ws_post.id = ?', $id);
return $post->get_row();
}
/**
* 取得POST记录
*/
static function get_post_by_permalink($permalink, $type = null, $depiction = true, $relation = true)
{
$post = accessor::get_post_2model($type, $depiction, $relation);
$post->where('ws_post.permalink = ?', $permalink);
return $post->get_row();
}
/**
* 取得POST模型 - 根据复杂的数据查询(用于后台)
*/
static function get_posts_2admin($type, $cid = null, $title = null)
{
App::model('post');
$posts = Mpost::find('ws_post.type = ? AND R2.taxonomy = ?', $type, ENT_CATEGORY)->field(self::$fields['post'])
->inner_join('ws_post_relationship AS R1', 'term_id as category_id', 'R1.post_id = ws_post.id')
->inner_join('ws_term AS R2', 'title as category', 'R1.term_id = R2.id');
if ($cid) {
$ids = accessor::get_categories_by_parent($cid, true);
$ids = array_merge($ids, array($cid));
$posts->where('R2.id in (?)', implode(',', $ids));
}
if (strlen($title) > 0) {
$title = trim($title);
if ($title != '')
$posts->where('ws_post.title like "%?%"', $title);
}
return $posts;
}
/**
* 取得POST模型 - (用于前台)
*/
static function get_posts_by_term($term_id, $limit = 0, $sort = null, $depiction = false, $term = null)
{
$fields = self::$fields['post'];
if ($depiction)
$fields .= ', depiction';
App::model('post');
$posts = Mpost::find('ws_post.is_show = 1')->field($fields);
if ($term && $term['taxonomy'] != ENT_CATEGORY)
// 非分类ID进行关联时,需要取出分类ID(此处关联过于复杂)
$posts->inner_join('ws_post_relationship AS R1', '', 'R1.post_id = ws_post.id')
->inner_join('ws_post_relationship AS R2', '', 'R2.post_id = ws_post.id')
->inner_join('ws_term AS R3', 'id as category_id', 'R3.id = R2.term_id')
->where('R3.taxonomy = ?', ENT_CATEGORY);
else
$posts->inner_join('ws_post_relationship AS R1', 'term_id as category_id', 'R1.post_id = ws_post.id');
if (is_array($term_id))
$posts->where('R1.term_id in(?)', implode(',', $term_id));
else
$posts->where('R1.term_id = ?', $term_id);
if ($limit)
$posts->limit(0, $limit);
if ($sort) {
if (!preg_match("/(.*)\s(asc|desc)/si", $sort, $matches))
$sort .= 'desc';
$posts->order($sort, 'ws_post');
if (trim($matches[1]) == 'id')
return $posts;
}
return $posts->order('id desc', 'ws_post');
}
/**
* 取得产品或文章附属信息
*/
static function get_post_meta($post_id, $key, $unserialize = true)
{
static $options = array();
App::model('post_meta');
if (isset($options[$key][$post_id]))
return $options[$key][$post_id];
$option = Mpost_meta::find('post_id = ? AND type_id = 0 AND mate_key = ?', $post_id, $key)->field('mate_value')->get_var();
if ($unserialize && !empty($option))
$option = unserialize($option);
$options[$key][$post_id] = $option;
return $option;
}
/**
* 取得产品或文章数据关联
*/
static function get_post_relation($post_id, $term_id)
{
App::model('post_relationship');
return Mpost_relationship::find('post_id = ? AND term_id = ?', $post_id, $term_id)->get_count();
}
/**
* 取得产品或文章数据关联ID
*/
static function get_post_relations($post_id, $taxonomy = null, $col = true)
{
App::model('post_relationship');
$model = Mpost_relationship::find('post_id = ?', $post_id)->field('term_id');
if ($taxonomy)
$model->left_join('ws_term', null, 'ws_term.id = ws_post_relationship.term_id')
->where('taxonomy = ?', $taxonomy);
if ($col)
return $model->get_col();
return $model->get_var();
}
///
/**
* 取得站点配置
*/
static function get_option($key, $y = null, $unserialize = true)
{
static $options = array();
App::model('option');
if (isset($options[$key])) {
$option = $options[$key];
} else {
$option = Moption::find('option_key = ?', $key)->field('option_value')->get_var();
if ($unserialize && !empty($option))
$option = unserialize($option);
$options[$key] = $option;
}
if (!empty($y) && is_array($option))
$option = $option[$y];
return $option;
}
}
?><file_sep><?php
class controller_post extends frontCtrl
{
public $type = null;
public $categories = null;
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->type = isset($_GET['type']) ? strtolower($_GET['type']) : 'none';
if ($this->type == ENT_PRODUCT && !App::option(ENT_PRODUCT))
$this->type = 'none';
}
/**
* 分类
*/
function product_category($category)
{
// TODO
}
/**
* 产品
*/
function product()
{
// TODO
}
/**
* 分类
*/
function article_category($category)
{
$cid = $category['id'];
$keywords = array($category['keywords'], $category['title']);
$description = array($category['depiction'], $category['title']);
$categories = accessor::get_categories_by_parent($cid);
$count = count($categories);
if ($category['parent_id'] == 0 && $count > 0) {
//// 一级目录
if ($this->is_cached("article-list", "category|{$cid}")) return;
$left = $right = array();
$limit = $this->limit('first');
for ($i = 0; $i < $count; $i++) {
$keywords[] = $categories[$i]['title'];
$categories[$i]['posts'] = accessor::get_posts_by_term($categories[$i]['id'], $limit, 'sort')->get_results();
if ($i % 2 == 0)
$left[] = $categories[$i];
else
$right[] = $categories[$i];
}
$this->assign('left', $left);
$this->assign('right', $right);
} else {
//// 二级目录
if ($this->is_cached("article-list2", "category|{$cid}|{$p}")) return;
$ids = array($cid);
for ($i = 0; $i < $count; $i++)
$ids[] = $categories[$i]['id'];
$posts = accessor::get_posts_by_term($ids, 0, null, false, $category);
$url = array('format' => appUrl::category($this->type, $cid, '%d'));
$this->assign_object('posts', $posts, $this->limit('second', 10), $url);
}
$this->assign('keywords', implode(',', $keywords));
$this->assign('description', implode(' ', $description));
$this->assign_location($this->get_location($category, false));
$this->assign_title($category['title']);
}
/**
* 文章
*/
function article($post)
{
$post_id = $post['id'];
$this->set_visitor($post_id);
if ($this->is_cached("article", "article|{$post_id}")) return;
$titles = array();
$nodata = appView::__("No data");
$category = accessor::get_category($post['category_id']);
$comments = accessor::get_comments_by_post($post_id, 1);
$location = $this->get_location($category);
foreach ($this->categories as $val)
array_unshift($titles, $val['title']);
array_unshift($titles, $post['title']);
$this->assign('post_id', $post_id);
$this->assign('category_id', $post['category_id']);
$this->assign('meta', accessor::get_term_meta($post['category_id'], 'meta'));
$this->assign('comments', $comments);
$this->assign_location($location);
$this->assign_title(implode('|', $titles));
/// TAG
$tags = array();
foreach (accessor::get_tags_by_post($post_id, $this->type) as $tag) {
$tags_id[] = $tag['id'];
$tags[] = "<a href='" . appUrl::tag($this->type, $tag['permalink']) . "'>{$tag['title']}</a>";
}
$this->assign('tags', empty($tags) ? $nodata : implode(' , ', $tags));
/// LINK
$link_next = $link_previous = $nodata;
$post_previous = accessor::get_posts_by_term($category['id'], 0, 'id asc')
->where('ws_post.id > ?', $post['id'])->get_row();
$post_next = accessor::get_posts_by_term($category['id'])
->where('ws_post.id < ?', $post['id'])->get_row();
if (!empty($post_next))
$link_next = "<a href='" . appUrl::post($this->type, $post_next['id'], $post['category_id'], $post_next['permalink']) . "'>" . lpString::substr($post_next['title'], 20) . "</a>";
if (!empty($post_previous))
$link_previous = "<a href='" . appUrl::post($this->type, $post_previous['id'], $post['category_id'], $post_previous['permalink']) . "'>" . lpString::substr($post_previous['title'], 20) . "</a>";
$this->assign('link_next', $link_next);
$this->assign('link_previous', $link_previous);
/// SEO
$keywords = str_replace("\r\n", '', $post['keywords']);
if (!trim($post['summary'])) {
$description = lpString::substr($post['depiction'], 200);
$description = str_replace(array(" ", "\r\n"), array(' ', ''), $post['summary']);
}
$this->assign('keywords', $keywords);
$this->assign('description', $description);
///
$posts_recommend = accessor::get_posts_by_term($category['id'], $this->limit('recommend', 5), 'sort')
->where('ws_post.is_recommend = 1 AND ws_post.id != ?', $post['id'])->get_results();
$posts_hot = accessor::get_posts_by_term($category['id'], $this->limit('hot', 15), 'ws_post.visitor')
->where('ws_post.id != ?', $post['id'])->get_results();
if (!empty($tags_id)) {
$posts_related = accessor::get_posts_by_term($tags_id, $this->limit('related', 5))
->distinct()->where('ws_post.id != ?', $post['id'])->get_results();
}
$this->assign('posts_recommend', $posts_recommend);
$this->assign('posts_related', $posts_related);
$this->assign('posts_hot', $posts_hot);
///
$post['depiction'] = $this->depiction($post['depiction']);
$this->assign('post', $post);
}
/**
* 文章或产品
*/
function action_post()
{
$post_id = intval($_GET['post_id']);
$permalink = trim($_GET['permalink']);
if ($post_id)
$post = accessor::get_post($id, $this->type);
elseif ($permalink)
$post = accessor::get_post_by_permalink($permalink, $this->type);
if ($post)
call_user_func_array(array($this, $this->type), array($post));
else
$this->goto_404();
}
/**
* 分类
*/
function action_category()
{
$cid = intval($_GET['category_id']);
$permalink = trim($_GET['permalink']);
if ($cid)
$category = accessor::get_term($cid, $this->type);
elseif ($permalink)
$category = accessor::get_term_by_permalink($permalink, $this->type);
if ($category)
call_user_func_array(array($this, "{$this->type}_category"), array($category));
else
$this->goto_404();
}
/**
* 取得图片XML列表,以FLASH的方式展示产品
*/
function action_xml_pic()
{
$cid = intval($_GET['category_id']);
if ($category = accessor::get_category($cid)) {
$ids = array($cid);
$url = RES_URI . 'post/';
$categories = accessor::get_categories_by_parent($cid);
$count = count($categories);
for ($i = 0; $i < $count; $i++)
$ids[] = $categories[$i]['id'];
$posts = accessor::get_posts_by_term($ids, 0, 'sort', true)->get_results();
biz::header_xml();
echo '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
echo '<images img_path="' . $url . '" tmb_path="' . $url . 'thumb/">';
foreach ($posts as $post)
echo "<pic>
<thumbnail>{$post['image']}</thumbnail>
<image>{$post['image']}</image>
<caption>{$post['title']}</caption>
</pic>";
echo '</images>';
}
}
/**
* 分类
*/
function limit($key, $default = 5)
{
$limit = intval(accessor::get_option('list', $key));
if (empty($limit))
$limit = $default;
return $limit;
}
/**
* 内容主体
*/
function depiction($content)
{
$pattern = "/<div style=\"page-break-after: always;\"><span style=\"display: none;\"> <\/span><\/div>/";
$strSplit = preg_split($pattern, $content, -1, PREG_SPLIT_NO_EMPTY);
$count = count($strSplit);
if ($count > 1) {
$i = 1;
$outStr = "<div id='page_break'>";
foreach ($strSplit as $value) {
if ($i <= 1)
$outStr .= "<div id='page_{$i}'>{$value}</div>";
else
$outStr .= "<div id='page_{$i}' class='collapse'>{$value}</div>";
$i++;
}
$outStr .= "<div class='num'>";
for ($i = 1; $i <= $count; $i++)
$outStr .= "<li>$i</li>";
$outStr .= "</div></div>";
return $outStr;
}
return $content;
}
/**
* 取得分类导航
*/
function get_location($category, $a_this = true)
{
$categories = array($category);
if ($category['parent_id'] != 0)
array_unshift($categories, accessor::get_category($category['parent_id']));
$i = 0;
$location = '';
$count = count($categories);
$this->categories = $categories;
foreach ($categories as $val) {
$val['title'] = htmlspecialchars($val['title']);
if (!$a_this && $val['id'] == $category['id'])
$location .= $val['title'];
else
$location .= "<a href='" . appUrl::category($this->type, $val['id']) . "'>{$val['title']}</a>";
$location .= ' > ';
}
return $location;
}
/**
* 设置访问者数
*/
function set_visitor($post_id)
{
$key = "post_view_{$post_id}";
$expire = time() + 60 * 60 * 24;
if (!isset($key) || $_COOKIE[$key] != 1) {
setcookie($key, 1, $expire, '/');
Mpost::execute("UPDATE `ws_post` SET `visitor` = `visitor` + 1 WHERE `id` = {$post_id}");
}
}
}
?><file_sep><?php
/**
* 加载类
*/
App::import('uploader.php', LIB_DIR);
/**
* 后台控制器基类
*/
class adminCtrl extends appCtrl
{
/**
* 数据操作后得出的结果代码,0表示成功,非0表示失败状态
*
* @var string
*/
public $code = 0;
/**
* 数据操作后得出的结果信息
*
* @var string
*/
public $message = '';
/**
* 构造函数
*
* // 30分钟过期
*/
function __construct()
{
parent::__construct();
adminView::init();
$expire = 60 * 30;
if (!($session = comSession::read('admininfo')) || $session['time'] + $expire < time()) {
comSession::destroy();
if ($this->is_ajax()) {
biz::header_500(1000);
} else {
$this->display('_timeout');
App::view()->render();
exit();
}
}
$session['time'] = time();
comSession::write('admininfo', $session);
}
/**
* 判断请求的排序是否有效
*/
function sort_by(& $object)
{
$keys = func_get_args();
if (count($keys) <= 1 || !is_object($object))
return false;
array_shift($keys);
$orders = $order_state = array();
foreach ($keys as $key) {
$order_state[$key] = '';
$orders[$key] = 'desc';
}
if (empty($_POST['name']))
$_POST['name'] = $keys[0];
if (empty($_POST['order']))
$_POST['order'] = 'desc';
if (in_array($_POST['name'], $keys) && in_array($_POST['order'], array('desc', 'asc'))) {
call_user_func_array(array($object, 'order'), array("{$_POST['name']} {$_POST['order']}"));
$order_state[$_POST['name']] = $orders[$_POST['name']] = ($_POST['order'] == 'desc') ? 'asc' : 'desc';
}
$this->assign('orders', $orders);
$this->assign('order_state', $order_state);
}
/**
* 编辑数据内容
*/
function edit($class)
{
$args = func_get_args();
if (count($args) >= 2) {
$fields = array_slice($args, 1);
if (in_array($_POST['field'], $fields) && isset($_POST['value'])) {
$params = array(array($_POST['field'] => $_POST['value']));
$model = call_user_func_array(array($class, 'update'), $params);
return call_user_func_array(array($model, 'where'), array('id = ?', $_POST['id']))->query();
}
}
return false;
}
/**
* 改变数据状态
*/
function toggle($class)
{
$args = func_get_args();
if (count($args) >= 2) {
$fields = array_slice($args, 1);
if (in_array($_POST['field'], $fields) && isset($_POST['state'])) {
$params = array(array($_POST['field'] => $_POST['state']));
$model = call_user_func_array(array($class, 'update'), $params);
return call_user_func_array(array($model, 'where'), array('id = ?', $_POST['id']))->query();
}
}
return false;
}
/**
* 记录日志
*/
public function log($module = null, $action = null, $extra = null, $code = 0)
{
App::model('log');
$message = '<' . ($action ? $action : '') . $module . '>';
if ($extra)
$extra = ' [' . $extra . ']';
$admininfo = comSession::read('admininfo');
if (empty($code)) {
$illeg_message = '';
$upload_msg = uploader::get_message();
if (!empty($upload_msg))
$illeg_message .= implode(', ', $upload_msg);
foreach (App::model() as $model) {
if (class_exists($model)) {
$illegaldata = call_user_func_array(array($model, 'illegaldata'), array());
list($illegaldata, $sqldata) = $illegaldata;
if (!empty($illegaldata))
$illeg_message .= "[{$model}] " . implode(', ', $illegaldata);
if (!empty($sqldata))
$illeg_message .= implode(', ', $sqldata);
}
}
$code = empty($illeg_message) ? 0 : 1;
$extra .= empty($illeg_message) ? '' : "({$illeg_message})";
}
$this->code = $code;
$this->message = $message . $extra;
Mlog::insert(array(
'admin_id' => $admininfo['id'],
'time' => time(),
'ip' => lpSystem::ip(),
'module' => $module,
'action' => $action ? $action : ' ',
'depiction' => $extra,
'state' => $this->code ? 1 : 0
));
}
/**
* 返回数据操作结果
*/
function response($module = null, $action = null, $extra = null, $code = 0, $url = null, $fields = null)
{
if (empty($module) && isset($this->module))
$module = $this->module;
if ($module) {
$this->log($module, $action, $extra, $code);
$message = htmlspecialchars($this->message . ':' . ($this->code ? '失败!' : '成功!'));
if (!empty($url)) {
if (is_array($url))
$url = call_user_func_array(array('lpUrl', 'clean_url'), $url);
}
$xml = '';
if (!empty($fields) && is_array($fields)) {
foreach ($fields as $field => $val)
$xml .= "<{$field}>$val</{$field}>";
}
biz::header_xml();
echo "<?xml version='1.0' encoding='UTF-8'?><respone><code>{$this->code}</code>{$xml}<message>{$message}</message><url>{$url}</url></respone>";
}
exit(0);
}
}
/**
* 视图层逻辑
*/
class adminView
{
/**
* Smarty - 初始化
*/
static function init()
{
App::view()->register_function('runinfo', array('adminView', 'func_runinfo'));
App::view()->register_function('nodata', array('adminView', 'func_nodata'));
App::view()->register_function('post_fields', array('adminView', 'func_post_fields'));
App::view()->register_function('upload', array('adminView', 'func_upload'));
}
/**
* Smarty - 暂无数据提示
*/
static function func_nodata($params)
{
return '<span class="nodata">暂无数据</span>';
}
/**
* Smarty - 页面运行信息
*/
static function func_runinfo($params)
{
// Time
global $timeStart;
$mtime = explode(' ', microtime());
$time = $mtime[1] + $mtime[0] - $timeStart;
$time = sprintf("用时 %01.3f 秒", $time);
// Database
$database = App::dbo()->num_queries;
$database = sprintf("共执行 %d 个查询", $database);
// Memory
$memory = round(memory_get_usage() / 1048576, 3);
$memory = sprintf("内存占用 %01.3f M", $memory);
return "{$time},{$database},{$memory}";
}
/**
* Smarty - 产品属性列表
*/
function func_post_fields($params)
{
if (is_array($params)) {
extract($params);
ob_start();
biz::get_post_fields($type_id, $post_id);
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
return null;
}
/**
* Smarty - 文件上传
*
* 参数说明:
* form="subjectForm" type="subject" source="" multi="1"
*/
static function func_upload($params)
{
if (is_array($params)) {
extract($params);
$session_id = session_id();
$url = DOMAIN;
$multi = $multi == '1' ? 'true' : 'false';
$upload_url = lpUrl::clean_url('admin_upload', 'run');
$js = $url . 'flash/SWFUpload/';
$dom =<<< eof
<style type="text/css">
.swfupload {
vertical-align:top;
}
</style>
<script type="text/javascript" src="{$js}swfupload.js"></script>
<script type="text/javascript" src="{$url}javascript/swfupload.js"></script>
<script type="text/javascript">
$(document).ready(function($) {
$("#swfUpload").swfUpload({
form: "{$form}",
type: "{$type}",
source: "{$source}",
multi: {$multi},
target: "{$target}",
session_id: "{$session_id}",
upload_url: "{$upload_url}",
button_image_url: "{$js}/XPButtonNoText_61x22.png",
flash_url: "{$js}swfupload.swf"
});
});
</script>
<div id="swfUpload"></div>
eof;
return $dom;
}
return null;
}
}
?><file_sep><?php
App::model('comment');
class controller_comment extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "评论";
/**
* 评论列表
*/
function action_list()
{
$state = -1;
if (isset($_POST['state']) || isset($_GET['state'])) {
$tmp = isset($_POST['state']) ? trim($_POST['state']) : trim($_GET['state']);
if (strlen($tmp) > 0)
$state = intval($tmp);
}
$cs = accessor::get_comments_2admin($_POST['category_id'], $state);
$this->sort_by($cs, 'add_time', 'count');
$this->_assign_category();
$this->assign_object('comments', $cs);
$this->display($this->is_list() ? 'comment_list_div' : 'comment_list');
}
/**
* 添加评论(相当于FAQ)
*/
function action_add()
{
if ($this->is_post()) {
Mcomment::insert(array('add_time' => time(), 'ip' => lpSystem::ip(), 'content' => $_POST['content']));
$content = lpString::substr($_POST['content'], 50);
$this->response(null, '添加', $content, 0, array('admin_comment', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_comment', 'add'));
$this->display('comment_add');
}
/**
* 回复评论
*/
function action_reply()
{
if ($c = accessor::get_comment($_GET['comment_id'])) {
if ($this->is_post()) {
biz::update_count_comment($c['id']);
Mcomment::insert(array('parent_id' => $c['id'], 'add_time' => time(), 'ip' => lpSystem::ip(), 'content' => $_POST['content']));
$content = lpString::substr($c['content'], 50);
$this->response(null, '回复', $content, 0, array('admin_comment', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_comment', 'reply', array('comment_id' => $c['id'])));
$this->display('comment_reply');
}
}
/**
* 归类评论
*/
function action_classify()
{
if ($c = accessor::get_comment($_GET['comment_id'])) {
if ($this->is_post()) {
if ($c['category_id'] != $_POST['category_id']) {
biz::update_count_term($_POST['category_id'], true);
biz::update_count_term($c['category_id'], false);
}
Mcomment::update(array('category_id' => $_POST['category_id']))
->where('id = ?', $c['id'])->query();
$content = lpString::substr($c['content'], 50);
$this->response(null, '归类', $content, 0, array('admin_comment', 'list'));
}
$this->_assign_category();
$this->assign('comment', $c);
$this->assign('action', lpUrl::clean_url('admin_comment', 'classify', array('comment_id' => $c['id'])));
$this->display('comment_classify');
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $c = accessor::get_comment($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
biz::delete_comment($c['id']);
break;
case 'toggle':
$this->toggle('Mcomment', 'state');
break;
}
$content = lpString::substr($c['content'], 50);
$this->response(null, $operate, $content);
}
}
/**
* 批量数据操作
*/
function action_batch()
{
$ids = $_POST['ids'];
if ($this->is_ajax() && is_array($ids)) {
switch ($_POST['action']) {
case 'remove':
foreach ($ids as $id)
biz::delete_comment($id);
$this->response(null, '批量删除', implode(',', $ids));
break;
}
}
}
///// 以下为回复内容 /////
/**
* 回复列表
*/
function action_reply_list()
{
if ($c = accessor::get_comment($_GET['comment_id'])) {
$cs = accessor::get_comments($_GET['comment_id'], true);
$this->sort_by($cs, 'add_time');
$this->assign('comment_id', $_GET['comment_id']);
$this->assign('content', lpString::substr($c['content'], 50));
$this->assign('comments', $cs->get_results());
$this->display($this->is_list() ? 'replay_list_div' : 'replay_list');
}
}
/**
* 修改回复
*/
function action_reply_update()
{
if ($c = accessor::get_comment($_GET['comment_id'])) {
if ($this->is_post()) {
Mcomment::update(array('content' => $_POST['content']))
->where('id = ?', $c['id'])->query();
$this->response(null, '编辑回复', $c['content'], 0, array('admin_comment', 'reply_list', array('comment_id' => $c['parent_id'])));
}
$this->assign('comment', $c);
$this->assign('action', lpUrl::clean_url('admin_comment', 'reply_update', array('comment_id' => $c['id'])));
$this->display('comment_reply');
}
}
/**
* 数据操作
*/
function action_reply_ajax()
{
if ($this->is_ajax() && $c = accessor::get_comment($_POST['id'])) {
$operate = '编辑回复';
switch ($_POST['action']) {
case 'remove':
$operate = '删除回复';
biz::delete_comment($c['id']);
break;
}
$this->response(null, $operate, $c['content']);
}
}
///// 以上为回复内容 /////
///// 私有方法 /////
/**
* 分类
*/
function _assign_category()
{
$this->assign('categories', accessor::get_categories(ENT_COMMENT));
}
}
?><file_sep><?php
/**
* 广告Widget类
*/
class advertisement_widget implements iWidget
{
public static $name = "advertisement";
public static function admin_form($id = null, $title = null, $widget = null)
{
$type = isset($widget['type']) ? trim($widget['type']) : '';
$advert_id = isset($widget['advert_id']) ? trim($widget['advert_id']) : '';
$list = '';
$dialog = lpUrl::clean_url('admin_dialog', 'advert');
if ($advert_id) {
$adverts = accessor::get_adverts(true)
->where('id in (?)', $advert_id)->get_results();
foreach ($adverts as $advert) {
$list .= "<div><span id='adv{$advert['id']}' class='del'>删除</span><span class='adv_title'>{$advert['title']}</span></div>";
}
}
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label">列表[方式]:</td>
<td>
<select name="widget[type]">
<option value="" <?php if ($type == '') echo 'selected';?>>逐标题</option>
<option value="slide" <?php if ($type == 'slide') echo 'selected';?>>幻灯片</option>
<option value="lantern" <?php if ($type == 'lantern') echo 'selected';?>>走马灯</option>
</select>
</td>
</tr>
<tr>
<td class="label" height="24">列表[内容]:</td>
<td>
<style type="text/css">
#adverts{line-height:24px;margin:8px 8px 3px 1px;padding:0 5px;border:1px dotted #CCCCCC;}
#adverts span.del{margin:0 5px 0;text-decoration:underline; cursor:pointer;}
</style>
<input id="advertid" name="widget[advert_id]" type="hidden" value="<?php echo $advert_id;?>" />
<input type="button" value="选择广告 ..." id="advertChooseBtn" />
<div id="adverts"><?php echo $list ? $list : "暂无选择";?></div>
<script type="text/javascript">
var ids = <?php echo empty($advert_id) ? "[]" : json_encode(explode(',', $advert_id));?>;
/**
* 回调
*/
function DialogPostCallbak(list) {
var dom = "";
var len = list.length;
for (var i = 0; i < len; i++) {
if ($.inArray(list[i][0], ids) != -1) {
continue;
}
var str = '<span id="adv' + list[i][0] + '" class="del">删除</span><span class="adv_title">' + list[i][1] + '</span>';
var div = $("<div></div>").html(str);
if (ids.length == 0) {
$("#adverts").html("");
}
$("#adverts").append(div);
ids.push(list[i][0]);
}
$("#advertid").val(ids.toString());
bindAdvertList();
divFix();
}
/**
* 绑定列表
*/
function bindAdvertList() {
$("#adverts .del").unbind().click(function() {
var id = $(this).attr("id");
id = id.substr(3);
index = $.inArray(id, ids);
if (index != -1) {
ids.splice(index, 1);
if (ids.length == 0) {
$("#adverts").html("暂无选择");
}
$(this).parent().remove();
$("#advertid").val(ids.toString());
divFix();
}
});
}
//
$(document).ready(function($) {
bindAdvertList();
$("#advertChooseBtn").click(function() {
var url = "<?php echo $dialog?>";
popUrl2(url);
});
});
</script>
</td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$type = isset($widget['type']) ? trim($widget['type']) : '';
$advert_id = isset($widget['advert_id']) ? trim($widget['advert_id']) : '';
$list = '';
$url = DOMAIN;
if ($advert_id) {
$adverts = accessor::get_adverts(true)
->where('id in (?)', $advert_id)->get_results();
foreach ($adverts as $advert) {
$advert['link'] = accessor::get_post_meta($advert['id'], 'url');
$list .= "<item><link>{$advert['link']}</link>
<image>{$url}tmp/fckeditor/{$advert['image']}</image>
<title>{$advert['title']}</title></item>";
}
}
if (!$list)
return false;
$xml =<<< eof
<data>
<channel>{$list}</channel>
<config>
<autoPlayTime>5</autoPlayTime>>
<changImageMode>hover</changImageMode>
<transform>alpha</transform>
</config>
</data>
eof;
echo <<< eof
<div class="content widget_advertisement">
<object data="{$url}flash/bcastr/bcastr4.swf?xml={$xml}" type="application/x-shockwave-flash" width="100%" height="200">
<param name="movie" value="{$url}flash/bcastr/bcastr4.swf?xml={$xml}" />
</object>
</div>
eof;
}
}
?><file_sep><?php
/**
* 文章列表Widget类
*/
class articles_widget implements iWidget
{
public static $name = "articles";
/**
*
*/
public static function admin_form($id = null, $title = null, $widget = null)
{
$length = isset($widget['length']) ? intval($widget['length']) : 70;
$limit = isset($widget['limit']) ? intval($widget['limit']) : 5;
$display = isset($widget['display']) ? trim($widget['display']) : '';
$sort = isset($widget['sort']) ? trim($widget['sort']) : '';
$more = isset($widget['more']) ? 'checked' : '';
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label" style="width:280px;">文章分类:</td>
<td>
<select name="widget[category_id]">
<option value="">-- 请选择 --</option>
<?php
$categories = accessor::get_categories(ENT_ARTICLE);
foreach ($categories as $cagegory) {
$selected = $cagegory['id'] == $widget['category_id'] ? 'selected' : '';
echo "<option value='", $cagegory['id'], "' ", $selected, ">", $cagegory['separator'], $cagegory['title'], ' (', $cagegory['count'], ")</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td class="label">文章类型:</td>
<td>
<select name="widget[type_id]">
<option value="">-- 请选择 --</option>
<?php
$types = accessor::get_forms('type2');
foreach ($types as $type) {
$selected = $type['id'] == $widget['type_id'] ? 'selected' : '';
echo "<option value='", $type['id'], "' ", $selected, ">", $type['title'], "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td class="label">列表[方式]:</td>
<td>
<select name="widget[display]">
<option value="" <?php if ($display == '') echo 'selected';?>>逐标题</option>
<option value="images" <?php if ($display == 'images') echo 'selected';?>>缩略图</option>
</select>
</td>
</tr>
<tr>
<td class="label">列表[顺序]:</td>
<td>
<select name="widget[sort]">
<option value="" <?php if ($sort == '') echo 'selected';?>>默认</option>
<option value="sort" <?php if ($sort == 'sort') echo 'selected';?>>排序</option>
<option value="visitor" <?php if ($sort == 'visitor') echo 'selected';?>>点击数</option>
</select>
</td>
</tr>
<tr>
<td class="label">列表[字数]:</td>
<td>
<input id="inpLength" name="widget[length]" type="text" class="text" value="<?php echo $length;?>" size="5" maxlength="3" />
</td>
</tr>
<tr>
<td class="label">列表[个数]:</td>
<td>
<input id="inpLimit" name="widget[limit]" type="text" class="text" value="<?php echo $limit;?>" size="5" maxlength="2" />
</td>
</tr>
<tr>
<td class="label">列表[选项]:</td>
<td>
<input id="widget[more<?php echo $id;?>]" name="widget[more]" <?php echo $more;?> type="checkbox" value="1" />
<label for="widget[more<?php echo $id;?>]">显示更多</label>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function($) {
$("#inpLength").numeric();
$("#inpLimit").numeric();
$("#inpLength").rules("add", {
required: true,
messages: {
required: "请输入列表[字数]"
}
});
$("#inpLimit").rules("add", {
required: true,
messages: {
required: "请输入列表[个数]"
}
});
});
</script>
<?php
appWidget::form_footer();
}
/**
*
*/
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$length = isset($widget['length']) ? intval($widget['length']) : 70;
$limit = isset($widget['limit']) ? intval($widget['limit']) : 5;
$display = isset($widget['display']) ? trim($widget['display']) : '';
$sort = isset($widget['sort']) ? trim($widget['sort']) : '';
if (!in_array($sort, array('sort', 'visitor')))
$sort = '';
$dom = '';
$posts = accessor::get_posts_by_term($widget['category_id'], $limit, $sort)->get_results();
if (count($posts) > 0) {
$i = 0;
if ($display == 'images') {
//
foreach ($posts as $post) {
if ($i % 3 == 0)
$dom .= '<div class="product_row clearfix">';
$class = $i % 3 == 2 ? 'last_cell' : '';
$thumb = RES_URI . "post/thumb/{$post['image']}";
$link = appUrl::post(ENT_ARTICLE, $post['id'], $widget['category_id'], $post['permalink']);
$dom .= <<< eof
<div class="prd_cell {$class}">
<div class="pic">
<a href="{$link}" title="{$post['title']}">
<img src="{$thumb}" alt="{$post['title']}" width="150" height="150" />
</a>
</div>
<div class="info">
<h3>
<a href="{$link}" title="{$post['title']}">{$post['title']}</a>
</h3>
</div>
</div>
eof;
if ($i % 3 == 2 || $i == $count -1)
$dom .= '</div>';
$i++;
}
} else {
//
foreach ($posts as $post) {
$class = $i++ % 2 == 0 ? '' : 'gray';
$link = appUrl::post(ENT_ARTICLE, $post['id'], $widget['category_id'], $post['permalink']);
$dom .= "<li class='{$class}'><a href='{$link}'>" . lpString::substr($post['title'], $length) . "</a></li>";
}
$dom = "<ul>{$dom}</ul>";
}
//
if (isset($widget['more'])) {
$link = appUrl::category(ENT_ARTICLE, $widget['category_id']);
$dom .= "<div class='more'><a href='{$link}'>" . appView::__('More ...') . "</a></div>";
}
} else {
$dom .= appView::__('No data');
}
echo '<div class="content widget_articles">' . $dom . '</div>';
}
}
?><file_sep><?php
/**
* 更新数据结构
*/
$sql_1 = <<< eof
eof;
/**
* 升级数据库
*/
if (!$db_version = intval(accessor::get_option('db_version')))
$db_version = 1;
$db_version++;
$sql = ${'sql_' . $db_version};
if (isset($sql) && !empty($sql)) {
run_sql($sql);
biz::update_option('db_version', $db_version);
}
/**
* 运行SQL
*/
function run_sql($sql)
{
$num = 0;
$ret = array();
$sql = str_replace(array("\r\n", "\r"), array("\n", "\n"), $sql);
foreach(explode(";\n", trim($sql)) as $query) {
$ret[$num] = '';
$queries = explode("\n", trim($query));
foreach($queries as $query)
$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
$num++;
}
unset($sql);
foreach($ret as $query) {
$query = trim($query);
if($query)
App::dbo()->query($query);
}
}
?><file_sep>/**
* 文件上传
*/
(function($) {
$.fn.swfUpload = function(o) {
// 默认参数
o = $.extend({
button_image_url: "",
types: "*.gif; *.jpg; *.jpeg; *.png;",
types_description: "Images",
upload_url: "",
flash_url: "",
//
form: "",
type: "",
source: "",
multi: false,
target: "",
limit: 5,
session_id: ""
}, o || {});
//
var swfu;
var filelist = [];
var responselist = [];
// 队列
function FileProgress(file, target) {
this.id = file.id;
if ($("#" + this.id).is("div")) {
return;
}
var q = $("<div></div>").attr("id", file.id).addClass("swffile");
q.html("<span class='swfdel'>删除</span><span class='swfname'>" + file.name + "</span><span class='swfstate'>等待 ...</span>");
target.append(q);
$(".swfdel", this.div).click(function() {
q.remove();
swfu.cancelUpload(file.id, false);
var index = -1;
var count = filelist.length;
for (var i = 0; i < count; i++){
if (filelist[i] == file.name) {
index = i;
break;
}
}
filelist.splice(i, 1);
});
this.div = q;
}
FileProgress.prototype.setState = function(message) {
$("#" + this.id + " .swfstate").html(message);
};
// 插件扩展
return this.each(function() {
var form;
var target;
var progress;
var div = $(this);
initUpload();
// 初始化
function initUpload() {
if (o.form == "" || !$("#" + o.form).is("form")) {
return false;
}
form = $("#" + o.form);
var v = form.validate();
v.settings.submitHandler = function() {
doSubmit();
return false;
}
if (!o.multi) {
div.append('<input type="text" id="tmpFileName" class="text" size="40" disabled /> ');
} else {
target = $("#" + o.target);
}
div.append('<input type="hidden" id="txtFileName" name="image" /> ');
div.append('<span id="spanButtonPlaceholder"></span>');
if (!o.multi) {
progress = $("<span></span>").css({color: "red", margin: "0 0 0 5px"});
div.append(progress);
}
swfu = new SWFUpload({
// 配置
upload_url: o.upload_url,
flash_url: o.flash_url,
post_params: {"PHPSESSID": o.session_id, "type": o.type, "source": o.source},
file_size_limit: "2 MB",
file_types: o.types,
file_types_description: o.types_description,
file_queue_limit: o.limit,
file_upload_limit : 0,
// 按钮
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_text: "浏览",
button_text_top_padding: "2",
button_text_left_padding: "17",
button_image_url: o.button_image_url,
button_placeholder_id: "spanButtonPlaceholder",
button_action: o.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE,
button_width: 61,
button_height: 22,
// 绑定事件
file_queued_handler: fileQueued,
file_queue_error_handler: fileQueueError,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete,
// 其它
custom_settings: {},
debug: false
});
}
// 提交表单
function formSubmit()
{
defaultSubmit(form);
}
// 点击确定
function doSubmit() {
if (swfu != null && swfu.getStats().files_queued > 0) {
swfu.startUpload();
} else {
formSubmit();
}
}
// 设置状态
function setState(msg)
{
if (o.multi) {
alert(msg);
} else {
progress.html(msg);
}
}
// 选择后事件
function fileQueued(file) {
if (o.multi) {
var flag = 0;
var count = filelist.length;
for (var i = 0; i < count; i++){
if (filelist[i] == file.name) {
flag = 1;
break;
}
}
if (flag) {
swfu.cancelUpload(file.id, false);
} else {
var p = new FileProgress(file, target);
filelist.push(file.name);
}
} else {
$("#tmpFileName").val(file.name);
if (swfu.getStats().files_queued > 1) {
swfu.cancelUpload(null, false);
}
}
}
// 选择出错事件
function fileQueueError(file, errorCode, message) {
var errorName = "未知异常。";
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errorName = "文件数量已经超过限制。";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errorName = "文件" +file.name + "过大。";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errorName = "文件" + file.name + "大小为0K。";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errorName = "文件" + file.name + "类型不正确。";
break;
}
setState(errorName);
}
// 正在上传事件
function uploadProgress(file, bytesLoaded, bytesTotal) {
if (o.multi) {
var p = new FileProgress(file, target);
p.setState("上传中 ...");
} else {
setState("上传中 ...");
}
}
// 上传成功处理
function uploadSuccess(file, serverData) {
if (o.multi) {
responselist.push(serverData);
} else {
$("#txtFileName").val(serverData);
}
}
// 上传完成处理
function uploadComplete(file) {
if (o.multi) {
var p = new FileProgress(file, target);
p.setState("上传成功。");
if (swfu.getStats().files_queued > 0) {
swfu.startUpload();
} else {
$("#txtFileName").val(responselist.toString());
formSubmit();
}
} else {
setState("上传成功。");
formSubmit();
}
}
// 上传失败处理
function uploadError(file, errorCode, message) {
setState("uploadError");
}
}); // end plugin
};
})(jQuery);<file_sep><?php
/**
* 应用程序配置
*/
return array(
// 用户自定义的调度器
'custom_dispatcher' => 'app_dispatcher',
// 多语言版本
'language' => 'zh_CN',
// 链接的组织方式:标准或重写
'url_mode' => URL_REWRITE,
// 控制器与控制器方法的键值
'controller_accessor' => 'c',
'action_accessor' => 'a',
// 数据表的全局前缀
'db_table_prefix' => 'ws_',
// 数据模型前缀
'pre_model' => 'M',
// 数据库配置信息
'dsn' => array('localhost', 'root', '123456', 'website_dev'),
// 是否添加模板缓存
'template' => array('caching' => 0, 'expired' => 86400),
// 后台配置
'folders' => array(
'admin' => array(
'language' => 'zh_CN',
'template' => array('caching' => 0)
)
),
/** 以下为系统自带配置选项 **/
// Widget列表
'widgets' => array(
array(
'name' => 'Flash产品页', 'list' => array(
array(4, '主休栏'),
array(5, '侧边栏')
)
)
),
// 产品系统和页面状态
'product' => true,
'page' => true
);
?><file_sep><?php
App::language()->_e("Home");
App::language()->_e("Topics");
App::language()->_e("Tags");
App::language()->_e("Current Position:");
App::language()->_e("Recommended Posts");
App::language()->_e("Related Posts");
App::language()->_e("Popular Posts");
App::language()->_e("No data");
App::language()->_e("Source:");
App::language()->_e("Issued Date:");
App::language()->_e("Hits:");
App::language()->_e("Previous:");
App::language()->_e("Next:");
App::language()->_e("Tags:");
App::language()->_e("Comments List");
App::language()->_e("Leave messages");
App::language()->_e("Pages not found");
App::language()->_e("More ...");
App::language()->_e("Authentication information");
App::language()->_e("Identifying code:");
App::language()->_e("Nickname");
App::language()->_e("E-mail (required)");
App::language()->_e("Content (required)");
App::language()->_e("Submit");
App::language()->_e("Processing");
App::language()->_e("Flight Price");
App::language()->_e("Adult (excluding tax) One-way / round trip");
App::language()->_e("Children (excluding tax) one-way / round trip");
App::language()->_e("Baby (excluding tax) One-way / round trip");
App::language()->_e("Available Period");
App::language()->_e("Latest Return");
App::language()->_e("Available for Return");
App::language()->_e("Free luggage");
App::language()->_e("Amending cost");
App::language()->_e("Refund Cost");
App::language()->_e("Flight Time");
App::language()->_e("Flight Name");
App::language()->_e("Flight No.");
App::language()->_e("Via");
App::language()->_e("Departure time");
App::language()->_e("Arrival Time");
App::language()->_e("Monday");
App::language()->_e("Tuesday");
App::language()->_e("Wednesday");
App::language()->_e("Thursday");
App::language()->_e("Friday");
App::language()->_e("Saturday");
App::language()->_e("Sunday");
App::language()->_e("Outward trip");
App::language()->_e("Return trip");
App::language()->_e("Notes:");
App::language()->_e("Departure City:");
App::language()->_e("Arrival City:");
App::language()->_e("Airlines");
App::language()->_e("Details");
App::language()->_e("%s / %s total:%s records");
?><file_sep>/**
* 列表操作
*
* @author <EMAIL>
*/
(function($) {
$.fn.listTable = function(o) {
var table = $(this);
var isMethodCall = (typeof o == 'string');
var o = isMethodCall ? o : $.extend({
fetchUrl: null,
oprateUrl: null,
batchUrl: null,
searchForm: null
}, o || {});
/**
* 属性初始化
*/
function ClassListTable(o) {
this.fetchUrl = o.fetchUrl;
this.oprateUrl = o.oprateUrl;
this.batchUrl = o.batchUrl;
this.searchForm = o.searchForm;
this.sqlTable = {where : null, sort: null, limit: null};
}
/**
* Ajax方式处理查询数据
*/
ClassListTable.prototype.ajaxTable = function() {
var data = "";
var self = this;
if (o.searchForm) {
var form = $(o.searchForm);
$("input[type='submit']", form).attr("disabled", true);
self.sqlTable.where = $(form).formSerialize();
}
if (self.sqlTable.where) data += self.sqlTable.where;
if (self.sqlTable.order) data += "&name=" + self.sqlTable.order[0] + "&order=" + self.sqlTable.order[1];
if (self.sqlTable.limit) data += "&p=" + self.sqlTable.limit;
top.loadIng();
$.ajax({
type: "POST",
url: self.fetchUrl,
data: data,
success: function(html) {
table.html(html);
top.loadEd();
self.init();
if ($.isFunction(bindUrl)) bindUrl();
if (o.searchForm) $("input[type='submit']", o.searchForm).attr("disabled", false);
}
});
return false;
};
/**
* Ajax方式处理操作数据
*/
ClassListTable.prototype.ajaxOprate = function(type, id, params, successFunc, failedFunc) {
var self = this;
var data = "action=" + type + "&id=" + id;
if (params == null || params == "undefined") params = "";
if (params != "") data += "&" + params;
top.loadIng();
$.ajax({
type: "POST",
url: self.oprateUrl,
data: data,
dataType: "xml",
success: function(data) {
top.loadEd();
if ($.isFunction(top.showSubmitResponse)) {
top.showSubmitResponse(data);
}
if ($("code", data).text() != "0") {
if ($.isFunction(failedFunc)) failedFunc();
switch (type) {
case "edit":
break;
default:
alert($("message", data).text());
break;
}
} else {
if ($.isFunction(successFunc)) successFunc();
switch (type) {
case "remove":
self.ajaxTable();
break;
default:
break;
}
}
}
});
return false;
};
/**
* Ajax方式处理操作数据
*/
ClassListTable.prototype.ajaxBatch = function(type, ids, params, successFunc, failedFunc) {
var self = this;
var data = "action=" + type + "&" + ids;
if (params == null || params == "undefined") params = "";
if (params != "") data += "&" + params;
top.loadIng();
$.ajax({
type: "POST",
url: self.batchUrl,
data: data,
dataType: "xml",
success: function(data) {
top.loadEd();
if ($.isFunction(top.showSubmitResponse)) {
top.showSubmitResponse(data);
}
if ($("code", data).text() != "0") {
if ($.isFunction(failedFunc)) failedFunc();
} else {
if ($.isFunction(successFunc)) successFunc();
switch (type) {
case "remove":
self.ajaxTable();
break;
default:
break;
}
}
}
});
return false;
};
/**
* 绑定数据事件
*/
ClassListTable.prototype.init = function() {
var self = this;
/* 选择框 */
var chkon = 0;
var chkcount = $(".chk", table).size();
$("#chkall", table).click(function() {
var val = $(this).attr("checked");
if (val == true) {
chkon = chkcount;
} else {
chkon = 0;
}
$(".chk", table).attr("checked", val);
});
$(".chk", table).click(function() {
var val = $(this).attr("checked");
if (val == true) {
chkon++;
} else {
chkon--;
}
$("#chkall", table).attr("checked", chkon == chkcount);
});
/* 数据批量操作 */
$(".batch a.del", table).click(function() {
var message = $(this).attr("message");
var data = $(".chk", table).fieldSerialize();
if (undefined == message) message = "确定删除?";
if (data == "") {
top.msgAlert("请选择要删除的项目。");
return false;
}
if ($.isFunction(top.msgConfirm)) {
top.msgConfirm(message, function() {
return self.ajaxBatch("remove", data);
});
}
return false;
});
/* 移动效果
$("tr", $("table.Tlist", table)).slice(1)
.hover(function() {
$(this).toggleClass("on");
}, function() {
$(this).toggleClass("on");
});*/
/* 查询数据 */
if (o.searchForm) {
$(o.searchForm).unbind().bind("submit", function() {
return self.ajaxTable();
});
}
$(".sort", table).unbind().bind("click", function() {
if ($("tr", table).size() <= 2) return false;
self.sqlTable.order = [$(this).attr("sname"), $(this).attr("sorder")];
return self.ajaxTable();
});
$("#page_nav a", table).unbind().bind("click", function() {
self.sqlTable.limit = $(this).attr("p");
return self.ajaxTable();
});
/* 操作数据 */
$(".thumb").addClass("ic ithumb");
if ($.tooltip) {
$(".thumb").tooltip({
delay: 0,
showURL: false,
bodyHandler: function() {
return $("<img/>").attr("src", $(this).attr("url"));
}
});
}
$(".popedit", table).addClass("ic iedit").unbind().click(function() {
var url = $(this).attr("url");
var width = $(this).attr("pwidth");
return top.popUrl(url, width);
});
$(".remove", table).addClass("ic idelete").unbind().click(function() {
var id = $(this).attr("oid");
var message = $(this).attr("message");
if (undefined == message) message = "确定删除?";
if ($.isFunction(top.msgConfirm)) {
top.msgConfirm(message, function() {
return self.ajaxOprate("remove", id);
});
}
return false;
});
$(".toggle", table).addClass("ic").unbind().each(function() {
var image = $(this);
var id = $(this).attr("oid");
var state = $(this).attr("state"), field = $(this).attr("field");
var title_0 = $(this).attr("title_0"), title_1 = $(this).attr("title_1");
image.addClass(state == 1 ? "iyes" : "ino");
image.attr("title", state == 1 ? title_1 : title_0);
$(this).click(function() {
var state_new = (state == 1 ? 0 : 1);
var data = "field=" + field + "&state=" + state_new;
return self.ajaxOprate("toggle", id, data, function() {
if (state == 1) {
image.attr("title", title_0);
image.removeClass("iyes"); image.addClass("ino");
} else {
image.attr("title", title_1);
image.removeClass("ino"); image.addClass("iyes");
}
state = state_new;
image.attr("state", state);
});
});
});
var showEdit = false;
$(".edit", table).unbind().each(function() {
var span = $(this);
var id = span.attr("oid"), field = span.attr("field"), text = span.text(), width = span.width();
span.mouseover(function() {$(this).css("background-color", "#B4C9C6");})
.mouseout(function() {$(this).css("background-color", "");})
.click(function() {
if (showEdit) return false;
span.html(""); showEdit = true;
$("<input class=\"text\" />").val(text).width(width + 12).appendTo(span).focus()
.blur(function() {
var input = $(this);
if (input.val() == '') {
input.val(text).blur();
return false;
}
showEdit = false; span.html($(this).val().replace(/>/g, ">").replace(/</g, "<"));
if (text != input.val()) {
self.ajaxOprate("edit", id, "field=" + field + "&value=" + input.val(), function() {
text = input.val(); width = span.width();
},
function() { span.html(text); }
);
}
return true;
})
.keypress(function(event) {
if (event.keyCode == 13) { $(this).blur(); return false; }
});
});
});
};
return this.each(function() {
var name = "listTable";
var instance = $.data(this, name);
if (!instance) {
if (o.fetchUrl == null) return false;
instance = new ClassListTable(o);
$.data(this, name, instance);
}
if (!isMethodCall) instance.init();
if (isMethodCall && o == "refresh") instance.ajaxTable();
});
};
})(jQuery);<file_sep><?php
class controller_option extends adminCtrl
{
/**
* 提交配置信息
*/
function action_submit()
{
if ($this->is_post()) {
$key = trim($_GET['key']);
$options = biz::get_sys_options();
if (in_array($key, array_keys($options)) && isset($_POST[$key])) {
biz::update_option($key, $_POST[$key]);
$this->response($options[$key], '编辑');
}
}
}
/**
* 基本信息
*/
function action_site()
{
$this->_assign_action('site');
$this->display('option-site');
}
/**
* 搜索优化
*/
function action_seo()
{
$this->_assign_action('seo');
$this->display('option-seo');
}
/**
* 页面缓存
*/
function action_cache()
{
$this->_assign_action('cache');
$this->display('option-cache');
}
/**
* 列表展示
*/
function action_list()
{
$this->_assign_action('list');
$this->display('option-list');
}
/**
* 图片大小
*/
function action_thumb()
{
$this->_assign_action('thumb');
$this->display('option-thumb');
}
/**
* 图片水印
*/
function action_water()
{
$tr = '';
$value = 0;
$options = accessor::get_option('water');
for ($i = 0; $i < 3; $i++) {
$td = '';
for ($j = 0; $j < 3; $j++)
$td .= '<td bgcolor="#ffffff" align="center"><input type="radio" value="' . ++$value . '" name="water[postion]" ' . ($options['postion'] == $value ? 'checked' : '') . '/></td>';
$tr .= '<tr>' . $td . '</tr>';
}
$options['postion'] = '<table style="background: #CCCCCC; width: 150px;" cellspacing="1" cellpadding="3" border="0">' . $tr . '</table>';
$this->_assign_action('water', $options);
$this->display('option-water');
}
///// 私有方法 /////
/**
* 设置处理方法
*/
function _assign_action($key, $options = null)
{
if (empty($options))
$options = accessor::get_option($key);
$action = lpUrl::clean_url('admin_option', 'submit', array('key' => $key));
$this->assign('action', $action);
$this->assign('options', $options);
}
}
?><file_sep><?php
App::model('admin', 'log');
class controller_log extends adminCtrl
{
/**
* 日志列表
*/
function action_list()
{
if (!$this->is_list()) {
$this->assign('admin_id', $_GET['admin_id']);
$this->assign('ip', accessor::get_log_ips());
}
$logs = accessor::get_logs($_GET['admin_id'], $_POST['ip']);
$this->sort_by($logs, 'time', 'state');
$this->assign_object('logs', $logs, 20);
$this->display($this->is_list() ? 'log_list_div' : 'log_list');
}
/**
* 清除日志
*/
function action_ajax()
{
$type = intval($_POST['log_date']);
$times = array(0, 7, 30, 90, 180, 365);
if ($this->is_ajax() && in_array($type, array_keys($times))) {
$time = mktime() - $times[$type] * 3600 * 24;
echo Mlog::delete("`time` < ?", $time)->query() ? '0' : '1';
Mlog::execute("OPTIMIZE TABLE `ws_log`");
}
}
}
?><file_sep><?php
App::model('term', 'post', 'comment', 'nav', 'form', 'brand', 'post_relationship');
class controller_main extends adminCtrl
{
/**
* 框架页面
*/
function action_index()
{
$admininfo = comSession::read('admininfo');
$this->assign('username', $admininfo['username']);
$this->display('main');
}
/**
* JS代码
*/
function action_js()
{
$admininfo = comSession::read('admininfo');
$navs = array(
array('title' => '文章模块', 'subnav' => array(
array('文章列表', array('admin_post', 'list', 'type' => ENT_ARTICLE)),
array('文章分类', array('admin_category', 'list', 'type' => ENT_ARTICLE)), // 数据的垂直关联
array('标签列表', array('admin_tag', 'list', 'type' => ENT_ARTICLE)),
array('文章类型', array('admin_type', 'list')), // 数据的水平关联
array('分类节点', array('admin_tree', 'list'))
)),
array('title' => '产品模块', 'subnav' => array(
array('产品列表', array('admin_post', 'list', 'type' => ENT_PRODUCT)),
array('产品分类', array('admin_category', 'list', 'type' => ENT_PRODUCT)),
array('标签列表', array('admin_tag', 'list', 'type' => ENT_PRODUCT)),
array('产品类型', array('admin_form', 'list', 'type' => 'type')),
array('产品品牌', array('admin_brand', 'list'))
)),
array('title' => '评论模块', 'subnav' => array(
array('评论列表', array('admin_comment', 'list')),
array('评论分类', array('admin_category', 'list', 'type' => ENT_COMMENT))
)),
array('title' => '系统管理', 'subnav' => array(
array('修改密码', array('admin_admin', 'update', 'admin_id' => $admininfo['id']), 'pop'),
array('帐号列表', array('admin_admin', 'list')),
array('操作日志', array('admin_log', 'list')),
array('导航列表', array('admin_nav', 'list')),
array('页面列表', array('admin_page', 'list'))
)),
array('title' => '附件列表', 'subnav' => array(
array('Widget', array('admin_widget', 'list')),
array('留言表单', array('admin_form', 'list', 'type' => 'feedback')),
array('广告列表', array('admin_advert', 'list'))
)),
array('title' => '系统配置', 'subnav' => array())
);
// 帐号权限
if ($admininfo['group'] != 1)
array_splice($navs[3]['subnav'], 1, 2);
// 配置列表
$options = biz::get_sys_options();
foreach ($options as $key => $option)
$navs[5]['subnav'][] = array($option, array('admin_option', $key), 'pop');
/// 开关
if (!App::option('page')) {
$count = count($navs);
array_splice($navs[$count - 2]['subnav'], 3, 1);
}
if (!App::option(ENT_PRODUCT))
array_splice($navs, 1, 1);
/// 插件
$navs = appHook::apply_filters('navs', $navs);
foreach ($navs as $i => $nav) {
foreach ($nav['subnav'] as $k => $sub) {
if (is_array($sub[1])) {
$params = count($sub[1]) > 2 ? array_slice($sub[1], 2) : array();
$navs[$i]['subnav'][$k][1] = lpUrl::clean_url($sub[1][0], $sub[1][1], $params);
}
if (!isset($sub[2]))
$navs[$i]['subnav'][$k][2] = 'load';
}
}
biz::header_js();
echo "var domain = \"" . DOMAIN . "\";\r\n";
echo "var navList = " . json_encode($navs) . ";\r\n";
echo "var urlAdmin = {\"welcome\":\"" .
lpUrl::clean_url('admin_main', 'welcome') . "\",\"index\":\"" .
lpUrl::clean_url('admin_index') . "\"};\r\n";
}
/**
* 登出系统
*/
function action_logout()
{
comSession::destroy();
lpUrl::url('admin_index');
}
/**
* 后台首页
*/
function action_welcome()
{
$query_format = "SELECT COUNT(*) FROM (SELECT DISTINCT `post_id` FROM `ws_post_relationship` INNER JOIN `ws_term` ON `ws_term`.`id` = `ws_post_relationship`.`term_id` WHERE `ws_term`.`taxonomy` = 'category' AND `ws_term`.`type` = '%s') AS `table1`";
// 文章
$article['category_count'] = Mterm::find('taxonomy = ? AND type = ?', ENT_CATEGORY, ENT_ARTICLE)->get_count();
$article['tag_count'] = Mterm::find('taxonomy = ? AND type = ?', ENT_TAG, ENT_ARTICLE)->get_count();
$article['count'] = Mpost::find()->get_var(sprintf($query_format, ENT_ARTICLE));
$this->assign(ENT_ARTICLE, $article);
// 产品
if (App::option(ENT_PRODUCT)) {
$brands = Mbrand::find()->field('title')->get_col();
$types = Mform::find('type = ?', 'type')->field('title')->get_col();
$product['brand'] = !empty($brands) ? implode(' , ', $brands) : '暂无';
$product['type'] = !empty($types) ? implode(' , ', $types) : '暂无';
$product['category_count'] = Mterm::find('taxonomy = ? AND type = ?', ENT_CATEGORY, ENT_PRODUCT)->get_count();
$product['tag_count'] = Mterm::find('taxonomy = ? AND type = ?', ENT_TAG, ENT_PRODUCT)->get_count();
$product['count'] = Mpost::find()->get_var(sprintf($query_format, ENT_PRODUCT));
$this->assign(ENT_PRODUCT, $product);
}
// 评论
$comment['fix_count'] = Mcomment::find('state = 1 AND parent_id = 0')->get_count();
$comment['open_count'] = Mcomment::find('state = 0 AND parent_id = 0')->get_count();
$comment['category_count'] = Mterm::find('taxonomy = ? AND type = ?', ENT_CATEGORY, ENT_COMMENT)->get_count();
$this->assign(ENT_COMMENT, $comment);
// 其它
$forms = Mform::find('type = ?', 'feedback')->field('title')->get_col();
$web_info['form'] = !empty($forms) ? implode(' , ', $forms) : '暂无';
$web_info['nav_count'] = Mnav::find()->get_count();
$this->assign('web_info', $web_info);
// 系统
$sys_info['os'] = PHP_OS;
$sys_info['ip'] = $_SERVER['SERVER_ADDR'];
$sys_info['web_server'] = $_SERVER['SERVER_SOFTWARE'];
$sys_info['php_ver'] = PHP_VERSION;
$sys_info['mysql_ver'] = App::dbo()->version();
$sys_info['zlib'] = function_exists('gzclose') ? '是' : '否';
$sys_info['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : App::language()->__('no_timezone');
$sys_info['max_filesize'] = ini_get('upload_max_filesize');
$sys_info['gd'] = $this->gd_version();
$this->assign('sys_info', $sys_info);
$this->display('main-welcome');
}
/**
* GD库版本信息
*/
function gd_version()
{
if (!extension_loaded('gd')) {
$version = 0;
} else {
if (PHP_VERSION >= '4.3') {
if (function_exists('gd_info')) {
$ver_info = gd_info();
preg_match('/\d/', $ver_info['GD Version'], $match);
$version = $match[0];
} else {
if (function_exists('imagecreatetruecolor')) {
$version = 2;
} elseif (function_exists('imagecreate')) {
$version = 1;
}
}
} else {
if (preg_match('/phpinfo/', ini_get('disable_functions'))) {
$version = 1;
} else {
ob_start();
phpinfo(8);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, 'gd version');
preg_match('/\d/', $info, $match);
$version = $match[0];
}
}
}
if ($version == 0) {
$gd_version = 'N/A';
} else {
if ($version == 1) {
$gd_version = 'GD1';
} else {
$gd_version = 'GD2';
}
$gd_version .= ' (';
if ($version && (imagetypes() & IMG_JPG) > 0) {
$gd_version .= ' JPEG';
}
if ($version && (imagetypes() & IMG_GIF) > 0) {
$gd_version .= ' GIF';
}
if ($version && (imagetypes() & IMG_PNG) > 0) {
$gd_version .= ' PNG';
}
$gd_version .= ')';
}
return $gd_version;
}
}
?><file_sep><?php
$mtime = explode(' ', microtime());
$timeStart = $mtime[1] + $mtime[0];
/**
* 应用程序目录
*/
define('APP_DIR', dirname(__FILE__) . '/APP/');
/**
* 缓存目录
*/
define('CACHE_DIR', dirname(__FILE__) . '/tmp/');
/**
* 加载框架文件
*/
require('../lxsphp/basic.php');
/**
* 开启框架
*/
App::run();
?><file_sep><?php
App::model('post', 'widget');
class controller_page extends frontCtrl
{
/**
* 页面显示
*/
function action_show()
{
if ($page = accessor::get_page($_GET['page_id'])) {
$this->assign('page_id', $_GET['page_id']);
$this->assign('keywords', $page['keywords']);
$this->assign('description', $page['summary']);
$this->assign('meta', accessor::get_post_meta($_GET['page_id'], 'meta'));
$this->assign_title($page['title']);
$this->display('page');
} else {
$this->goto_404();
}
}
}
?><file_sep><?php
App::model('widget');
class controller_widget extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "Widget";
/**
* Widget列表
*/
function action_list()
{
$dom = '';
$pages = App::option('widgets');
if (!$pid = intval($_POST['pid'])) {
$a = array(array(1, '左全局侧边'), array(2, '右全局侧边'), array(3, '首页主体'));
foreach ($a as $p)
$dom .= $this->_format_widgets($p[0], $p[1]);
} else {
if ($pid > 0) $pid--;
$tmp = $pages[$pid];
foreach ($tmp['list'] as $p)
$dom .= $this->_format_widgets($p[0], $p[1]);
}
if (!$this->is_list()) {
$this->assign('dom', $dom);
$this->assign('pages', $pages);
$this->assign('widgets', appWidget::$widgets);
$this->display('widget_list');
} else {
echo $dom;
}
}
/**
* 接收到一个新的激活的Widget
*/
function action_add()
{
if ($this->is_ajax()) {
$id = Mwidget::insert(array('type' => $_POST['type'], 'postion' => $_POST['postion']));
$this->response(null, '添加', $_POST['type'], null, null, array('id' => $id));
}
}
/**
* 编辑Widget
*/
function action_update()
{
if ($widget = accessor::get_widget($_GET['id'])) {
if ($this->is_post()) {
$value = appWidget::format_value($widget['type'], $widget['value']);
Mwidget::update(array('title' => trim($_POST['title']), 'value' => $value))
->where('id = ?', $_POST['id'])->query();
$title = appWidget::title_format($widget['type'], $_POST['title']);
$this->response(null, '编辑', "{$widget['type']} - {$widget['title']}", null, null, array('id' => $_GET['id'], 'title' => $title));
}
appWidget::format_form($widget['type'], $_GET['id'], $widget);
}
}
/**
* 移动位置Widget
*/
function action_postion()
{
if ($this->is_ajax()) {
$postion = intval($_POST['postion']);
if (is_array($_POST['item']) && in_array($postion, array(1, 2, 3))) {
foreach ($_POST['item'] as $order => $id) {
Mwidget::update(array('postion' => $postion, 'sort' => $order))
->where('id = ?', $id)->query();
}
}
}
}
/**
* 删除Widget
*/
function action_remove()
{
if ($this->is_ajax() && $widget = accessor::get_widget($_POST['id'])) {
Mwidget::delete()->where('id = ?', $_POST['id'])->query();
$this->response(null, '删除', "{$widget['type']} - {$widget['title']}");
}
}
///// 私有方法 /////
/**
* 格式化Widget列表
*/
function _format_widgets($postion, $ptitle = null)
{
$dom = '';
$widgets = accessor::get_widgets($postion);
foreach ($widgets as $key => $widget) {
if (!class_exists("{$widget['type']}_widget"))
continue;
$title = trim($widget['title']);
if (empty($title)) $title = '暂无标题';
$title = appWidget::title_format($widget['type'], $title);
$dom .= "<li class='widget' id='item_{$widget['id']}'>
<div class='w_title'>{$title}</div>
<div class='ctrbar'></div>
</li>";
}
return <<< eof
<div class="acvite">
<h1>{$ptitle}</h1>
<ul id="pos{$postion}">{$dom}</ul>
</div>
eof;
}
}
?><file_sep><?php
/**
* 加载插件初始化文件
*/
if (is_array($GLOBALS['PLUGIN_LIST'])) {
foreach ($GLOBALS['PLUGIN_LIST'] as $plugin => $desc) {
App::import($plugin . '/index.php', PLUGIN_DIR);
$class = 'Plugin' . ucfirst($plugin);
if (class_exists($class))
call_user_func_array(array($class, 'init'), array());
}
}
/**
* 插件后台控视图类
*/
class pluginView
{
/**
* 初始化
*/
function init()
{
App::view()->register_function('plugin_url', array('pluginView', 'func_plugin_url'));
}
/**
* 重写链接地址定位
*/
static function func_plugin_url($params)
{
$url = View::func_url($params);
return $url . '?plugin=' . $_GET['plugin'];
}
}
if (IS_ADMIN) {
/**
* 插件后台控制器类
*/
class pluginAdminCtrl extends adminCtrl
{
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
pluginView::init();
}
/**
* 重写
*/
function display($template)
{
$dir = PLUGIN_DIR . $_GET['plugin'] . DS . 'template' . DS . (empty(App::instance()->folder) ? '' : App::instance()->folder . DS);
parent::display($dir . $template);
}
/**
* 返回数据操作结果
*/
function response($message, $code = 0, $url = null, $fields = null)
{
if (!empty($url) && is_array($url)) {
$url = call_user_func_array(array('lpUrl', 'clean_url'), $url);
$url .= '?plugin=' . $_GET['plugin'];
}
parent::response($message, $code, $url, $fields);
}
/**
* 设置表单
*/
function form_action($c, $a, $params = null)
{
$action = lpUrl::clean_url($c, $a, $params);
$action .= '?plugin=' . $_GET['plugin'];
$this->assign('action', $action);
}
}
} else {
/**
* 插件前端控制器类
*/
class pluginFrontCtrl extends frontCtrl
{
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
pluginView::init();
}
/**
* 重写
*/
function display($template)
{
$dir = PLUGIN_DIR . $_GET['plugin'] . DS . 'template' . DS . (empty(App::instance()->folder) ? '' : App::instance()->folder . DS);
parent::display($dir . $template);
}
}
}
?><file_sep><?php
/**
* 留言本Widget类
*/
class feedback_widget implements iWidget
{
public static $name = "feedback";
public static function admin_form($id = null, $title = null, $widget = null)
{
appWidget::form_header(self::$name, $id, $title);
$lists = is_array($widget['list']) ? $widget['list'] : array();
$forms = accessor::get_forms('feedback');
foreach ($forms as $key => $form) {
$checked = in_array($form['id'], $lists) ? 'checked="checked"' : '';
$dom .=<<< eof
<label for="widget[list][{$key}]">
<input id="widget[list][{$key}]" name="widget[list][]" type="checkbox" {$checked} value="{$form['id']}" />{$form['title']}
</label>
eof;
}
?>
<tr>
<td class="label">表单:</td>
<td><?php echo $dom;?></td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$lists = is_array($widget['list']) ? $widget['list'] : array();
$dom = frontView::func_comment_form(array('list' => $lists));
$url = DOMAIN;
$url_ssecode = lpUrl::clean_url('index', 'seccode');
$url_submit = lpUrl::clean_url('index', 'submit2');
echo <<< eof
<style type="text/css">
span.error { padding:0 0 0 5px; color:#FF0000;}
#Container .widget_feedback { margin:0; border-top:none;}
</style>
<script type="text/javascript">
var urlSsecode = "{$url_ssecode}";
var urlSubmit = "{$url_submit}";
</script>
<script type="text/javascript" src="{$url}javascript/comment2.js"></script>
<div class="content comment widget_feedback">
{$dom}
</div>
eof;
}
}
?><file_sep><?php
class controller_404 extends frontCtrl
{
/**
* 找不到页面处理
*/
function action_index()
{
$this->goto_404();
}
}
?><file_sep>/**
* 编辑Widget
*/
function WidgetUpdate(id, title) {
$("#item_" + id + " .w_title").html(title);
}
/**
* 弹出Widget编辑层
*/
function popWidgetDiv(id) {
var url = urlWidget.edit;
url = url.replace("__id__", id);
top.popUrl(url, 720);
}
/**
* 初始化Widget列表
*/
function initList() {
var list = $(".acvite-list .acvite ul");
initWidget(list);
list.sortable({
containment: "document",
handle: ".w_title",
cursor: "move",
connectWith: ".acvite ul",
helper: function() {
return '<div class="helper">移动中 ...</div>';
},
update: function(event, ui) {
var itemNow = $(ui.item);
var id = itemNow.attr("id");
var postion = $(event.target).attr("id").substr(3);
if (!/^item_(\d+)/.test(id)) {
ajaxAdd(id.substr(2), itemNow, postion);
} else {
ajaxPostion(postion);
}
}
});
}
/**
* 初始化Widget
*/
function initWidget(widget) {
$(".widget", widget).dblclick(function() {
var id = $(this).attr("id");
popWidgetDiv(id.substr(5));
});
$('<span class="edit" title="编辑"></span>')
.prependTo($(".ctrbar", widget))
.click(function() {
var obj = $(this).parents(".widget:first");
var id = obj.attr("id");
popWidgetDiv(id.substr(5));
});
$('<span class="del" title="删除"></span>')
.prependTo($(".ctrbar", widget))
.click(function() {
var obj = $(this).parents(".widget:first");
msgConfirm("确定删除?", function() {
ajaxRemove(obj);
});
});
}
/**
* 添加操作
*/
function ajaxAdd(type, itemNow, postion) {
$(".acvite ul").sortable('disable');
$(".available li.widget").draggable('disable');
$.ajax({
type: "POST",
data: "type=" + type + "&postion=" + postion,
url: urlWidget.add,
dataType: "xml",
success: function(xml) {
$(".acvite ul").sortable('enable');
$(".available li.widget").draggable('enable');
top.showSubmitResponse(xml);
itemNow.attr("id", "item_" + $("id", xml).text());
ajaxPostion(postion);
initWidget(itemNow);
}
});
}
/**
* 移动操作
*/
function ajaxPostion(postion) {
var ul = $("#pos" + postion);
if (ul.size() > 0) {
$.ajax({
type: "POST",
data: "postion=" + postion + "&" + ul.sortable('serialize'),
url: urlWidget.postion
});
}
}
/**
* 删除操作
*/
function ajaxRemove(thisLi) {
var id = thisLi.attr("id");
id = id.substr(5);
$.ajax({
type: "POST",
data: "id=" + id,
url: urlWidget.remove,
dataType: "xml",
success: function(xml) {
top.showSubmitResponse(xml);
thisLi.remove();
}
});
}
/**
* 刷新操作
*/
function ajaxInit(pos) {
top.loadIng();
$(".acvite-list").html(" ");
$(".available li.widget").draggable('disable');
$.ajax({
type: "POST",
data: "pid=" + pos,
url: urlWidget.list,
success: function(dom) {
top.loadEd();
$(".acvite-list").html(dom);
$(".available li.widget").draggable('enable');
// 初始化列表
initList();
}
});
}
$(document).ready(function($) {
// 初始化列表
initList();
$(".tab-ul li").click(function() {
if ($(this).hasClass("cur")) {
return false;
}
ajaxInit($(this).attr("val"));
$(".tab-ul li").removeClass("cur");
$(this).addClass("cur");
});
$(".available li.widget").draggable({
containment: "document",
handle: ".w_title",
cursor: "move",
revert: "invalid",
connectToSortable: ".acvite ul",
helper: function() {
return '<div class="helper" style="width: 300px;">移动中 ...</div>';
}
});
});<file_sep><?php
/**
* 文本框Widget类
*/
class text_widget implements iWidget
{
public static $name = "text";
public static function admin_form($id = null, $title = null, $widget = null)
{
$is_br = isset($widget['is_br']) ? 'checked' : '';
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label">文本:</td>
<td>
<textarea name="widget[content]" name="" cols="50" rows="10"><?php echo $widget['content']?></textarea>
</td>
</tr>
<tr>
<td class="label">选项:</td>
<td>
<input id="widget[is_br<?php echo $id;?>]" name="widget[is_br]" <?php echo $is_br;?> type="checkbox" value="1" />
<label for="widget[is_br<?php echo $id;?>]">自动换行</label>
</td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
if ($content = trim($widget['content'])) {
if (isset($widget['is_br']))
$content = nl2br($content);
echo '<div class="content widget_text">', $content , '</div>';
}
}
}
?><file_sep><?php
/**
* 注册钩子事件到视图
*/
App::view()->register_compiler_function('do_action', array('appHook', 'smarty_compiler_do_action'));
/**
* 钩子类
*
* 目前提供的钩子有
* get_nav => 导航地址 (filter)
* admin_navs => 管理菜单 (filter)
* admin_top_nav => 头部管理菜单 (filter)
* option => 配置菜单 (action)
* statistics => 信息统计 (action)
* nav2synchronize => 导航同步 (action)
*/
class appHook
{
/**
* 单例
*
* @var object
*/
public static $__instance = null;
/**
* 钩子数据
*/
public $hooks = array();
/**
* 单例
*/
static function instance()
{
if (empty(self::$__instance)) {
self::$__instance = new appHook();
}
return self::$__instance;
}
/**
* 添加行为钩子
*/
static function add_action($tag, $function)
{
self::instance()->hooks[$tag][] = $function;
}
/**
* 添加数据钩子
*/
static function add_filter($tag, $function)
{
self::instance()->hooks[$tag][] = $function;
}
/**
* 执行行为钩子
*/
static function do_action($tag, $args = null)
{
$hooks = self::instance()->hooks[$tag];
if (!empty($hooks) && is_array($hooks)) {
foreach ($hooks as $function)
call_user_func_array($function, $args);
}
}
/**
* 执行数据钩子
*/
static function apply_filters($tag, $value)
{
$hooks = self::instance()->hooks[$tag];
if (!empty($hooks) && is_array($hooks)) {
$params = array();
$args = func_get_args();
if (count($args) > 1) {
array_shift($args);
$params = $args;
}
foreach ($hooks as $function) {
$params[0] = $value;
$value = call_user_func_array($function, $params);
}
}
return $value;
}
/**
* 用于模板层的钩子处理
*/
static function smarty_compiler_do_action($tag_attrs, & $compiler)
{
$_params = $compiler->_parse_attrs($tag_attrs);
if (!isset($_params['tag'])) {
$compiler->_syntax_error("assign: missing 'var' parameter", E_USER_WARNING);
return;
}
$echo = "\nappHook::do_action({$_params['tag']}";
if (isset($_params['args'])) {
$echo .= ", {$_params['args']}";
}
return $echo . ");\n";
}
}
?><file_sep><?php
App::model('post', 'widget');
class controller_page extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "页面";
/**
* 页面列表
*/
function action_list()
{
$this->assign_object('pages', accessor::get_pages(true));
$this->display($this->is_list() ? 'page_list_div' : 'page_list');
}
/**
* 添加页面
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$params = array('type' => 'page', 'add_time' => time(), 'is_nav' => 0, 'is_show' => 1, 'title' => $_POST['title'], 'keywords' => trim($_POST['keywords']), 'summary' => trim($_POST['summary']));
$page_id = Mpost::insert($params);
if ($page_id)
$this->_update_layout($page_id);
$this->response(null, '添加', $_POST['title'], 0, array('admin_page', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_page', 'add'));
$this->display('page_add');
}
/**
* 编辑页面
*/
function action_update()
{
if ($page = accessor::get_page($_GET['page_id'])) {
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => $_POST['title'], 'keywords' => trim($_POST['keywords']), 'summary' => trim($_POST['summary']));
$flag = Mpost::update($params)->where('id = ?', $page['id'])->query();
if ($flag)
$this->_update_layout($page['id']);
$this->response(null, '编辑', $_POST['title'], 0, array('admin_page', 'list'));
}
$this->assign('page', $page);
$this->assign('meta', accessor::get_post_meta($page['id'], 'meta'));
$this->assign('action', lpUrl::clean_url('admin_page', 'update', array('page_id' => $page['id'])));
$this->display('page_add');
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $page = accessor::get_page($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
Mwidget::delete('page_id = ?', $page['id'])->query();
Mpost::delete('id = ?', $page['id'])->query();
biz::delete_nav($page['id'], 'page');
break;
case 'edit':
$this->edit('Mpost', 'sort');
break;
case 'toggle':
if ($this->toggle('Mpost', 'is_nav', 'is_show') && $_POST['field'] == 'is_nav')
biz::add_nav(ENT_PAGE, $page['id'], $_POST['state'], $page['title']);
break;
}
$this->response(null, $operate, $page['title']);
}
}
///// 私有方法 /////
/**
* 检测标题
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, '页面标题不能为空', 2);
}
/**
* 检测标题
*/
function _update_layout($id)
{
if (!empty($_POST['meta'])) {
$meta = $_POST['meta'];
$left = $meta['left'];
$right = $meta['right'];
if ($left == 1 && $right == 1) {
$layout = 3;
} elseif ($left == 0 && $right == 1) {
$layout = 4;
} elseif ($left == 1 && $right == 0) {
$layout = 2;
} else {
$layout = 1;
}
$meta['layout'] = $layout;
biz::update_post_meta($id, 'meta', $meta);
}
}
}
?><file_sep><?php
App::model('field', 'form', 'post', 'post_meta');
class controller_form extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "";
/**
* 分类类型列表
*/
public static $keys = array('type' => '产品类型', 'feedback' => '留言表单');
public $type;
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->type = isset($_GET['type']) ? strtolower($_GET['type']) : null;
if (in_array($this->type, array_keys(self::$keys))) {
$this->module = self::$keys[$this->type];
$this->assign('name', $this->module);
$this->assign('type', $this->type);
} else {
biz::header_404();
}
}
/**
* 列表
*/
function action_list()
{
$this->assign('location', $this->type == 'type' ? '产品模块' : '附件列表');
$this->assign('forms', accessor::get_forms($this->type));
$this->display($this->is_list() ? 'form_list_div' : 'form_list');
}
/**
* 添加
*/
function action_add()
{
if ($this->is_post()) {
$params = array('type' => $this->type, 'title' => trim($_POST['title']));
$params['meta'] = isset($_POST['meta']) ? serialize($_POST['meta']) : ' ';
Mform::insert($params);
$this->response(null, '添加', $_POST['title'], 0, array('admin_form', 'list', array('type' => $this->type)));
}
$this->assign('action', lpUrl::clean_url('admin_form', 'add', array('type' => $this->type)));
$this->display('form_add');
}
/**
* 编辑
*/
function action_update()
{
if ($form = accessor::get_form($_GET['form_id'], $this->type)) {
if ($this->is_post()) {
$params = array('title' => trim($_POST['title']));
$params['meta'] = isset($_POST['meta']) ? serialize($_POST['meta']) : ' ';
Mform::update($params)
->where('id = ?', $form['id'])->query();
$this->response(null, '编辑', $form['title'], 0, array('admin_form', 'list', array('type' => $this->type)));
}
$form['meta'] = unserialize($form['meta']);
$this->assign('form', $form);
$this->assign('action', lpUrl::clean_url('admin_form', 'update', array('type' => $this->type, 'form_id' => $form['id'])));
$this->display('form_add');
}
}
/**
* 移动位置
*/
function action_postion()
{
if ($this->is_ajax()) {
$sort = 1;
$count = count($_POST['form']);
for ($i = $count; $i > 0; $i--) {
$id = $_POST['form'][$i - 1];
Mform::update(array('sort' => $sort++))
->where('id = ?', $id)->query();
}
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $form = accessor::get_form($_POST['id'], $this->type)) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
if ($this->type == 'type') {
Mpost::update(array('type_id' => 0))->where('type_id = ?', $form['id'])->query();
Mpost_meta::delete('type_id = ?', $form['id']);
}
Mform::delete('id = ?', $form['id'])->query();
Mfield::delete('form_id = ?', $form['id'])->query();
break;
case 'edit':
$this->edit('Mform', 'sort');
break;
}
$this->response(null, $operate, $form['title']);
}
}
}
?><file_sep><?php
App::model('admin', 'log');
/**
* 帐号组:1,超级管理员;2,普通管理员
* 权限分组:待定
*/
class controller_admin extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "管理员帐号";
/**
* 管理员列表
*/
function action_list()
{
$this->assign_object('admins', accessor::get_admins(true));
$this->display($this->is_list() ? 'admin_list_div' : 'admin_list');
}
/**
* 添加管理员
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_username();
$this->_check_password();
$this->_check_email();
$params = array('group' => 2, 'username' => $_POST['username'], 'password' => md5($_POST['<PASSWORD>']), 'email' => $_POST['email'], 'add_time' => time());
Madmin::insert($params);
$this->response(null, '添加', $_POST['username'], 0, array('admin_admin', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_admin', 'add'));
$this->display('admin_add');
}
/**
* 修改管理员
*/
function action_update()
{
if ($admin = accessor::get_admin($_GET['admin_id'])) {
if ($this->is_post()) {
$this->_check_email();
$this->_check_password();
$this->_check_passwordold($admin['password']);
$params = array('password' => md5($_POST['<PASSWORD>']), 'email' => $_POST['email']);
Madmin::update($params)
->where('id = ?', $_GET['admin_id'])->query();
$this->response(null, '编辑', $admin['username'], 0, array('admin_admin', 'list'));
}
$this->assign('admin', $admin);
$this->assign('action', lpUrl::clean_url('admin_admin', 'update', array('admin_id' => $_GET['admin_id'])));
$this->display('admin_add');
}
}
/**
* 数据较验
*/
function action_check()
{
$field = trim($_POST['field']);
$value = trim($_POST['value']);
switch ($field) {
case 'username':
$flag = accessor::get_admin_by_username($value);
echo $flag ? 'false' : 'true';
break;
}
}
/**
* 权限分配
*/
function action_permission()
{
// TODO
}
/**
* 删除管理员
*/
function action_ajax()
{
if ($this->is_ajax() && $admin = accessor::get_admin($_POST['id'])) {
switch ($_POST['action']) {
case 'remove':
if ($_POST['id'] != '1') {
Madmin_log::delete('admin_id = ?', $_POST['id'])->query();
Madmin::update(array('state' => 0))
->where('id = ?', $_POST['id'])->query();
$this->response(null, '删除', $admin['username']);
}
break;
}
}
}
///// 私有方法 /////
/**
* 验证用户名
*/
function _check_username()
{
$_POST['username'] = trim($_POST['username']);
if (empty($_POST['username']) || !preg_match("/^[a-z0-9_]+$/i", $_POST['username']))
$this->response(null, '创建', "{$_POST['username']}用户名输入有误", 2);
if (accessor::get_admin_by_username($_POST['username']))
$this->response(null, '创建', "{$_POST['username']}用户名已被使用", 2);
}
/**
* 验证密码
*/
function _check_email()
{
$_POST['email'] = trim($_POST['email']);
$pattern = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (empty($_POST['email']) || !preg_match($pattern, $_POST['email']))
$this->response(null, null, 'E-mail格式有误', 2);
}
/**
* 验证密码
*/
function _check_password()
{
$_POST['password'] = trim($_POST['password']);
$_POST['password2'] = trim($_POST['password2']);
if (empty($_POST['password']) || strlen($_POST['password']) < 5)
$this->response(null, null, '密码格式有误', 2);
if ($_POST['password'] != $_POST['<PASSWORD>'])
$this->response(null, null, '两次输入密码不一至', 2);
}
/**
* 验证旧密码
*/
function _check_passwordold($passwordold)
{
$_POST['passwordold'] = trim($_POST['passwordold']);
if (md5($_POST['passwordold']) != $passwordold)
$this->response(null, null, '旧密码输入有误', 2);
}
}
?><file_sep><?php
/**
* 基础配置
*/
define('LIB_DIR', APP_DIR . 'lib/');
define('PLUGIN_DIR', APP_DIR . 'plugin/');
define('IS_ADMIN', App::folder() == 'admin');
/**
* 实体(ENTITY)
*/
define('ENT_ARTICLE', 'article');
define('ENT_PRODUCT', 'product');
define('ENT_COMMENT', 'comment');
define('ENT_CATEGORY', 'category');
define('ENT_PAGE', 'page');
define('ENT_TAG', 'tag');
/**
* 上传配置
*/
define('RES_DIR', CACHE_DIR . 'resource/');
define('RES_URI', DOMAIN . 'tmp/resource/');
/**
* 载入前后台对应控制器类
*/
if (IS_ADMIN)
App::import('admin.php', LIB_DIR);
else
App::import('front.php', LIB_DIR);
/**
* 加载类
*/
App::import('biz.php', LIB_DIR);
App::import('accessor.php', LIB_DIR);
App::import('upgrade.php', LIB_DIR);
App::import('cacher.php', LIB_DIR);
App::import('widget.php', LIB_DIR);
/**
* 钩子处理
*/
$GLOBALS['PLUGIN_LIST'] = App::import('list.php', PLUGIN_DIR);
App::import('hook.php', PLUGIN_DIR);
App::import('plugin.php', PLUGIN_DIR);
/**
* 控制器基础类
*/
class appCtrl extends Controller
{
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
appView::init();
// 加载语言包
if ($locale = App::option('language'))
App::language()->load_textdomain('custom', APP_DIR . "language/{$locale}.mo");
}
/**
* 判断是否请求局部数据
*/
function is_list()
{
return $this->is_ajax() && $this->is_post();
}
/**
* 显示分页内容
*/
function assign_object($name, $object, $offset = 11, $url = null)
{
App::vendor('pagination');
if (is_object($object)) {
$count = $object->get_count();
$page_count = ceil($count / $offset);
if ($page_count <= 0)
return false;
$_POST['p'] = isset($_GET['p']) ? $_GET['p'] : $_POST['p'];
if ($start = intval($_POST['p'])) {
if ($start <= 0)
$start = 1;
elseif ($start >= $page_count)
$start = $page_count;
} else {
$start = 1;
}
$_GET['p'] = $start;
$str = appView::__("%s / %s total:%s records");
$str = sprintf($str, $start, $page_count, $count);
$pagination = call_user_func_array(array(new Pagination($page_count, $url, 5), 'display'), array());
$pagination = empty($pagination) ? "" : "<table cellspacing='0' cellpadding='3' id='page-table'><tr><td align='center'>{$pagination}<div id='page_info'>[{$str}]</div></td></tr></table>";
$object = $object->limit(($start - 1) * $offset, $offset)->get_results();
$this->assign($name, $object);
$this->assign('pagination', $pagination);
}
}
}
/**
* 视图层逻辑
*/
class appView
{
/**
* 系统名称
*
* @var string
*/
public static $system = 'LXSCMS V1.0';
/**
* Smarty - 初始化
*/
static function init()
{
App::view()->register_function('page', array('appView', 'func_url_page'));
App::view()->register_function('post', array('appView', 'func_url_post'));
App::view()->register_function('category', array('appView', 'func_url_category'));
// 基础信息
App::view()->register_function('system', array('appView', 'func_system'));
App::view()->register_function('company', array('appView', 'func_company'));
App::view()->register_function('copyright', array('appView', 'func_copyright'));
App::view()->register_function('resource', array('appView', 'func_resource'));
// 字符修饰
App::view()->register_modifier('__', array('appView', '__'));
App::view()->register_modifier('trim', array('appView', 'trim'));
App::view()->register_modifier('substr', array('lpString', 'substr'));
}
/**
* Smarty - 多语言
*/
static function __($string)
{
if (!empty($string)) {
return App::language()->__($string, 'custom');
}
return $string;
}
/**
* Smarty - 去除空格
*/
static function trim($string)
{
if (!empty($string)) {
return trim($string);
}
return $string;
}
/**
* Smarty - 重写页面URI
*/
static function func_url_page($params)
{
if (is_array($params)) {
extract($params);
return appUrl::page($page_id);
}
return null;
}
/**
* Smarty - 重写产品或文章URI
*/
static function func_url_post($params)
{
if (is_array($params)) {
extract($params);
return appUrl::post($type, $post_id, $category_id, $permalink);
}
return null;
}
/**
* Smarty - 重写分类URI
*/
static function func_url_category($params)
{
if (is_array($params)) {
extract($params);
return appUrl::category($type, $category_id, $p);
}
return null;
}
/**
* Smarty - 上传目录
*/
static function func_resource($params)
{
if (is_array($params)) {
extract($params);
if (isset($dir) && isset($url))
return RES_URI . "{$dir}/{$url}";
}
return RES_URI;
}
/**
* Smarty - 系统
*/
static function func_system()
{
return self::$system;
}
/**
* Smarty - 公司
*/
static function func_company()
{
$company = accessor::get_option('site', 'company');
return empty($company) ? self::$system : $company;
}
/**
* Smarty - 版权说明
*/
static function func_copyright()
{
$system = self::$system;
return "Powered by {$system}; ©2009-" . date('Y') . " <EMAIL>";
}
}
/**
* 站点前台URL出口
*/
class appUrl
{
/**
* 重写页面URI
*/
static function page($page_id, $permalink = null)
{
return lpUrl::clean_url($permalink);
}
/**
* 重写标签URI
*/
static function tag($type, $permalink = null, $p = 0)
{
if (empty($permalink))
return null;
return lpUrl::clean_url(null, 'tag/' . $permalink);
}
/**
* 重写文章URI(最里层需要以.html要结束)
*/
static function post($type, $post_id, $category_id = null, $permalink = null)
{
if (empty($post_id))
return null;
$prefix = self::_prefix($category_id);
if (App::option(ENT_PRODUCT))
$prefix = $type . '/' . $prefix;
return lpUrl::clean_url($prefix, $permalink . '.html');
}
/**
* 重写分类URI
*/
static function category($type, $category_id, $p = 0)
{
if (empty($category_id))
return null;
$permalink = self::_prefix($category_id);
if (App::option(ENT_PRODUCT))
$permalink = $type . '/' . $permalink;
$url = lpUrl::clean_url(null, $permalink);
if ($p)
$url .= '?p=' . $p;
return $url;
}
//// 私有方法 ////
/**
* 分成分类层次关系(从CACHE中读取)
*/
static function _prefix($category_id)
{
static $data = null;
if (is_null($data))
$data = cacher::read(ENT_CATEGORY);
if (empty($data))
return null;
if (!isset($data[$category_id]))
return null;
$category = $data[$category_id];
$permalink = $category['permalink'];
if ($category['parent_id']) {
$parent = $data[$category['parent_id']];
$permalink = $parent['permalink'] . '/' . $permalink;
}
return $permalink;
}
}
?><file_sep><?php
App::model('post', 'form', 'post_relationship');
class controller_post extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "";
/**
* 分类类型列表
*/
public static $keys = array(ENT_ARTICLE => '文章', ENT_PRODUCT => '产品');
public $type; // 用于流程跳转
public $type2db; // 用于数据库操作
public $tree_id = 0; // 添加分类时需要用到树ID
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->type = $this->type2db = isset($_GET['type']) ? strtolower($_GET['type']) : null;
if (in_array($this->type, array_keys(self::$keys))) {
/* 树 */
if ($this->type == ENT_ARTICLE) {
$id = isset($_GET['tree_id']) ?
intval($_GET['tree_id']) : intval($_POST['tree_id']);
if ($id > 0) {
if ($tree = accessor::get_form($id, 'tree')) {
$this->type2db .= $id;
$this->tree_id = $id;
}
}
}
/* /树 */
$this->module = self::$keys[$this->type];
} else {
biz::header_404();
}
}
/**
* 产品或文章列表
*/
function action_list()
{
$params = array('type' => $this->type);
$posts = accessor::get_posts_2admin($this->type2db, $_POST['category_id'], $_POST['title']);
if (!empty($_GET['tag_id'])) {
$params['tag_id'] = $_GET['tag_id'];
$posts->inner_join('ws_post_relationship AS R3', '', 'R3.post_id = ws_post.id');
$posts->where('R3.term_id = ?', $_GET['tag_id']);
$tag = accessor::get_term($_GET['tag_id']);
$this->assign('tag', $tag['title']);
}
$this->sort_by($posts, 'sort', 'add_time');
$posts->order('id desc');
if (!empty($_POST['type_id']))
$posts = $posts->where('ws_post.type_id = ?', $_POST['type_id']);
if (!empty($_POST['brand_id']))
$posts = $posts->where('ws_post.brand_id = ?', $_POST['brand_id']);
if (!empty($_POST['state']) && is_array($_POST['state'])) {
foreach ($_POST['state'] as $key => $val)
$posts->where("ws_post.{$key} = ?", $val);
}
/* 树 */
$this->assign('trees', accessor::get_forms('tree'));
/* /树 */
$this->_assign_category();
$this->assign_object('posts', $posts, 15);
$this->assign('fecth_url', lpUrl::clean_url('admin_post', 'list', $params));
$this->display($this->is_list() ? "{$this->type}_list_div" : "{$this->type}_list");
}
/**
* 添加产品或文章
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$this->_check_relationship();
$permalink = $this->_check_permalink();
$params = array(
'type' => $this->type2db,
'add_time' => time(),
'font' => serialize($_POST['font']),
'author' => trim($_POST['author']),
'title' => $_POST['title'],
'permalink' => $permalink ,
'keywords' => trim($_POST['keywords']),
'summary' => trim($_POST['summary']),
'depiction' => $_POST['FCKeditor1']
);
if ($this->type == ENT_PRODUCT) {
$params['type_id'] = $_POST['type_id'];
$params['brand_id'] = $_POST['brand_id'];
}
$post_id = Mpost::insert($params);
if ($post_id) {
biz::add_post_tag($post_id, $_POST['tags'], $this->type);
biz::add_post_category($post_id, $_POST['category_id'], $this->type2db);
if ($this->type == ENT_PRODUCT)
biz::add_post_field($post_id, $_POST['type_id'], $_POST['keys'], $_POST['values']);
$this->_upload_thumb($post_id);
}
$this->response(null, '创建', $_POST['title'], 0, array('admin_post', 'list', array('type' => $this->type)));
}
$this->_assign_rich();
$this->_assign_category();
$this->assign('action', lpUrl::clean_url('admin_post', 'add', array('type' => $this->type, 'tree_id' => $this->tree_id)));
$this->display("{$this->type}_add");
}
/**
* 编辑产品或文章
*/
function action_update()
{
if ($post = accessor::get_post($_GET['post_id'])) {
if ($this->is_post()) {
$this->_check_title();
$this->_check_relationship();
$permalink = $this->_check_permalink();
$params = array(
'font' => serialize($_POST['font']),
'author' => trim($_POST['author']),
'title' => $_POST['title'],
'permalink' => $permalink ,
'keywords' => trim($_POST['keywords']),
'summary' => trim($_POST['summary'])
);
if ($this->type == ENT_PRODUCT) {
$params['type_id'] = $_POST['type_id'];
$params['brand_id'] = $_POST['brand_id'];
}
$flag = Mpost::update($params)
->where('id = ?', $post['id'])->query();
if ($flag) {
biz::update_post_tag($post['id'], $_POST['tags'], $this->type);
biz::update_post_category($post['id'], $_POST['category_id'], $this->type2db);
if ($this->type == ENT_PRODUCT)
biz::update_post_field($post['id'], $post['type_id'], $_POST['keys'], $_POST['values'], $params['type_id']);
$this->_upload_thumb($post['id'], $post['image']);
}
$this->response(null, '编辑', $post['title'], 0, array('admin_post', 'list', array('type' => $this->type)));
}
$this->_assign_this($post);
$this->_assign_category();
$this->assign('action', lpUrl::clean_url('admin_post', 'update', array('type' => $this->type, 'post_id' => $post['id'])));
$this->display("{$this->type}_add_div2");
}
}
/**
* 编辑产品或文章 - 主体内容
*/
function action_update2()
{
if ($post = accessor::get_post($_GET['post_id'])) {
if ($this->is_post()) {
$flag = Mpost::update(array('depiction' => $_POST['FCKeditor1']))
->where('id = ?', $post['id'])->query();
$this->response(null, '编辑', $post['title'], 0, array('admin_post', 'list', array('type' => $this->type)));
}
$this->_assign_rich($post['depiction'], 500);
$this->assign('action', lpUrl::clean_url('admin_post', 'update2', array('type' => $this->type, 'post_id' => $post['id'])));
$this->display("{$this->type}_add_div3");
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $post = accessor::get_post($_POST['id'], null, false)) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
biz::delete_post($post['id']);
break;
case 'edit':
$this->edit('Mpost', 'sort');
break;
case 'toggle':
if ($this->toggle('Mpost', 'is_new', 'is_show', 'is_nav', 'is_recommend') && $_POST['field'] == 'is_nav')
biz::add_nav(ENT_ARTICLE, $post['id'], $_POST['state'], $post['title']);
break;
}
$this->response(null, $operate, $post['title']);
}
}
/**
* 批量数据操作
*/
function action_batch()
{
$ids = $_POST['ids'];
if ($this->is_ajax() && is_array($ids)) {
switch ($_POST['action']) {
case 'remove':
foreach ($ids as $id)
biz::delete_post($id);
$this->response(null, '批量删除', implode(',', $ids));
break;
}
}
}
/**
* 添加时产品的属性表列
*/
function action_field()
{
$type_id = intval($_POST['type_id']);
$post_id = intval($_POST['post_id']);
biz::get_post_fields($type_id, $post_id);
}
/**
* 切换分类树的对应分类
*/
function action_category()
{
$a = array();
$categories = accessor::get_categories($this->type2db);
foreach ($categories as $c)
$a[] = array($c['id'], $c['separator'] . ' ' .$c['title']);
echo json_encode($a);
}
///// 私有方法 /////
/**
* 检测标题
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "{$_POST['title']},标题输入有误", 2);
}
/**
* 检测所属分类是否存在
*/
function _check_relationship()
{
$_POST['category_id'] = intval($_POST['category_id']);
if (!accessor::get_category($_POST['category_id']))
$this->response(null, null, "{$category_id},分类ID不存在", 2);
}
/**
* 检测永久链接
*/
function _check_permalink()
{
$permalink = biz::str2pingyin($_POST['title']);
/*
if (accessor::get_post_by_permalink($permalink, $this->type))
$permalink .= '_1';
*/
return $permalink;
}
/**
* 上传缩略图
*/
function _upload_thumb($post_id, $source = null)
{
if (!empty($_POST['image'])) {
Mpost::update(array('image' => $_POST['image']))
->where('id = ?', $post_id)->query();
}
}
/**
* 当前
*/
function _assign_this($post)
{
$tags = array();
foreach (accessor::get_tags_by_post($post['id'], $this->type) as $tag)
$tags[] = $tag['title'];
$post['tags'] = implode(',', $tags);
$post['font'] = unserialize($post['font']);
$this->assign('post', $post);
}
/**
* 富文本
*/
function _assign_rich($value = null, $height = 0)
{
App::vendor('fckeditor');
$richeditor = new richeditor('FCKeditor1');
if ($value)
$richeditor->Value = $value;
if ($height)
$richeditor->Height = $height;
$this->assign('richeditor', $richeditor->CreateHtml());
}
/**
* 分类及其它列表
*/
function _assign_category()
{
if (!$this->is_list()) {
$this->assign('ie', strpos($_SERVER["HTTP_USER_AGENT"], "MSIE"));
$this->assign('categories', accessor::get_categories($this->type2db));
if ($this->type == ENT_PRODUCT) {
$this->assign('brands', accessor::get_brands());
$this->assign('types', accessor::get_forms('type'));
} else {
$this->assign('types', accessor::get_forms('type2'));
}
}
}
}
?><file_sep><?php
App::model('form', 'post');
class controller_type extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "文章类型";
public $type = 'type2';
/**
* 文章类型列表
*/
function action_list()
{
$this->assign('types', accessor::get_forms($this->type));
$this->display($this->is_list() ? 'type_list_div' : 'type_list');
}
/**
* 添加文章类型
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$params = array('type' => $this->type, 'title' => trim($_POST['title']));
Mform::insert($params);
$this->response(null, '添加', $_POST['title'], 0, array('admin_type', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_type', 'add'));
$this->display('type_add');
}
/**
* 修改文章类型
*/
function action_update()
{
if ($type = accessor::get_form($_GET['type_id'], $this->type)) {
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => trim($_POST['title']));
Mform::update($params)
->where('id = ?', $type['id'])->query();
$this->response(null, '编辑', $type['title'], 0, array('admin_type', 'list'));
}
$this->assign('type', $type);
$this->assign('action', lpUrl::clean_url('admin_type', 'update', array('type_id' => $_GET['type_id'])));
$this->display('type_add');
}
}
/**
* 删除文章类型
*/
function action_ajax()
{
if ($this->is_ajax() && $type = accessor::get_form($_POST['id'], $this->type)) {
switch ($_POST['action']) {
case 'remove':
Mpost::update(array('type_id' => 0))->where('type_id = ?', $type['id'])->query();
Mform::delete('id = ?', $type['id'])->query();
$this->response(null, '删除', $type['title']);
break;
}
}
}
///// 私有方法 /////
/**
* 检测分类名称
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "文章类型名称不能为空", 2);
}
}
?><file_sep><?php
App::model('admin');
App::vendor('seccode');
class controller_index extends appCtrl
{
/**
* 登录页面
*/
function action_index()
{
if ($session = comSession::read('admininfo'))
lpUrl::url('admin_main');
$this->display('login');
}
/**
* 验证码
*/
function action_seccode()
{
call_user_func_array(array(new seccode(), 'display'), array(1, 148, 26, array('bordercolor' => '#C5C5C5')));
}
/**
* 登录操作
*/
function action_login()
{
$code = 0;
$seccode = new seccode();
if ($seccode->check(trim($_POST['ssecode']))) {
$username = trim($_POST['username']);
$password = trim($_POST['<PASSWORD>']);
$admin = accessor::get_admin_by_username($username, 1);
if ($admin && ($admin['password'] == md5($password))) {
Madmin::update(array('last_time' => time(), 'last_ip' => lpSystem::ip()))
->where('id = ?', $admin['id'])->query();
extract($admin, EXTR_OVERWRITE);
$admin = compact('id', 'username', 'email', 'last_time', 'last_ip', 'group', 'permission');
$admin['time'] = time();
comSession::write('admininfo', $admin);
adminCtrl::log('系统', '登录');
} else {
$code = 2;
}
} else {
$code = 1;
}
echo $code;
}
}
?><file_sep><?php
define('SIMPLEPE_DIR', APP_DIR . 'vendors/simplepie_1.2/');
define('SIMPLEPE_CACHE_DIR', CACHE_DIR . 'runinfo');
if (!file_exists(SIMPLEPE_CACHE_DIR))
mkdir(SIMPLEPE_CACHE_DIR, 0777);
require_once(SIMPLEPE_DIR . 'simplepie.inc');
?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><{$title|escape}></title>
<{if !$meta.layout == ""}>
<{assign var="layout" value=$meta.layout}>
<{/if}>
<{include file="_meta.html"}>
</head>
<body>
<div id="Container">
<div id="Header">
<{include file="_header.html"}>
</div>
<div id="Body">
<{include file="_banner.html"}>
<div id="Wrapper">
<!-- Main -->
<div id="Main">
<{widget postion=2 page_id=$page_id}>
</div>
<!-- /Main -->
</div>
<div id="SideBar">
<!-- Sub -->
<{if $meta.left == 0}>
<div id="Sub" class="side">
<{widget postion=1 page_id=$page_id}>
</div>
<{/if}>
<!-- /Sub -->
<!-- Extra -->
<{if $meta.right == 0}>
<div id="Extra" class="side">
<{widget postion=3 page_id=$page_id}>
</div>
<{/if}>
<!-- /Extra -->
</div>
</div>
<div id="Footer">
<{include file="_footer.html"}>
</div>
</div>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 2.11.8.1
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2010 年 09 月 19 日 08:56
-- 服务器版本: 5.1.30
-- PHP 版本: 5.2.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `website_export`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_admin`
--
DROP TABLE IF EXISTS `ws_admin`;
CREATE TABLE IF NOT EXISTS `ws_admin` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(255) NOT NULL COMMENT '帐号',
`password` varchar(255) NOT NULL COMMENT '密码',
`email` varchar(255) NOT NULL DEFAULT ' ' COMMENT '邮箱',
`group` int(11) NOT NULL DEFAULT '0' COMMENT '组',
`permission` int(11) NOT NULL DEFAULT '0' COMMENT '权限值',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '注册时间(时间戳)',
`last_time` int(11) NOT NULL DEFAULT '0' COMMENT '上次登录时间(时间戳)',
`last_ip` varchar(15) NOT NULL DEFAULT ' ' COMMENT '上次登录IP',
`state` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态(0:删除,1:正常)',
PRIMARY KEY (`id`),
KEY `username` (`username`),
KEY `state` (`state`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='管理员表' AUTO_INCREMENT=4 ;
--
-- 导出表中的数据 `ws_admin`
--
INSERT INTO `ws_admin` (`id`, `username`, `password`, `email`, `group`, `permission`, `add_time`, `last_time`, `last_ip`, `state`) VALUES
(1, 'admin', '<PASSWORD>', '<EMAIL>', 0, 0, 1256535295, 1284873930, '127.0.0.1', 1),
(3, 'linxs', '<PASSWORD>', '<EMAIL>', 0, 0, 1280460093, 0, ' ', 0);
-- --------------------------------------------------------
--
-- 表的结构 `ws_brand`
--
DROP TABLE IF EXISTS `ws_brand`;
CREATE TABLE IF NOT EXISTS `ws_brand` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`title` varchar(255) NOT NULL COMMENT '名称',
`logo` varchar(1000) NOT NULL DEFAULT ' ' COMMENT 'LOGO',
`siteurl` varchar(255) NOT NULL DEFAULT ' ' COMMENT '网站',
`depiction` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='产品品牌表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_brand`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_comment`
--
DROP TABLE IF EXISTS `ws_comment`;
CREATE TABLE IF NOT EXISTS `ws_comment` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父级ID',
`category_id` int(11) NOT NULL DEFAULT '0' COMMENT '分类ID',
`post_id` int(11) NOT NULL DEFAULT '0' COMMENT '主体ID',
`term_id` int(11) NOT NULL DEFAULT '0' COMMENT '纬度ID',
`count` int(11) NOT NULL DEFAULT '0' COMMENT '回复数',
`state` int(11) NOT NULL DEFAULT '0' COMMENT '状态',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '时间(时间戳)',
`ip` varchar(15) NOT NULL DEFAULT ' ' COMMENT 'IP地址',
`author` varchar(255) NOT NULL DEFAULT ' ' COMMENT '作者',
`email` varchar(255) NOT NULL DEFAULT ' ' COMMENT '邮箱',
`content` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '评论内容',
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='评论表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_comment`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_field`
--
DROP TABLE IF EXISTS `ws_field`;
CREATE TABLE IF NOT EXISTS `ws_field` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`form_id` int(11) NOT NULL DEFAULT '0' COMMENT '表单ID',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`style` tinyint(4) NOT NULL DEFAULT '0' COMMENT '用户输入类型(1:手工录入,2:从下面的列表中选择,3:多行文本框)',
`constraint` varchar(255) NOT NULL DEFAULT ' ' COMMENT '字段约束',
`title` varchar(255) NOT NULL COMMENT '标题',
`depiction` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '字段描述',
`items` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '列表选择项',
PRIMARY KEY (`id`),
KEY `form_id` (`form_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='自定义表单字段表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_field`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_form`
--
DROP TABLE IF EXISTS `ws_form`;
CREATE TABLE IF NOT EXISTS `ws_form` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`type` varchar(255) NOT NULL DEFAULT ' ' COMMENT '关键字用途类型,如:type,feedback',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`meta` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '扩展配置',
`count` int(11) NOT NULL DEFAULT '0' COMMENT '使用总次数',
`title` varchar(255) NOT NULL COMMENT '标题',
PRIMARY KEY (`id`),
KEY `type` (`type`),
KEY `sort` (`sort`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='表单表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_form`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_log`
--
DROP TABLE IF EXISTS `ws_log`;
CREATE TABLE IF NOT EXISTS `ws_log` (
`admin_id` int(11) NOT NULL COMMENT '管理员ID',
`ip` varchar(15) NOT NULL DEFAULT ' ' COMMENT 'IP地址',
`time` int(11) NOT NULL DEFAULT '0' COMMENT '时间(时间戳)',
`state` int(11) NOT NULL DEFAULT '0' COMMENT '结果状态码(0:成功,n:其它)',
`module` varchar(255) NOT NULL DEFAULT ' ' COMMENT '操作模块',
`action` varchar(255) NOT NULL DEFAULT ' ' COMMENT '操作方法',
`depiction` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '日志描述信息',
KEY `admin_id` (`admin_id`),
KEY `date` (`time`),
KEY `ip` (`ip`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='操作日志表';
--
-- 导出表中的数据 `ws_log`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_nav`
--
DROP TABLE IF EXISTS `ws_nav`;
CREATE TABLE IF NOT EXISTS `ws_nav` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父ID',
`object_id` int(11) NOT NULL DEFAULT '0' COMMENT '扩展映射ID',
`type` varchar(255) NOT NULL DEFAULT ' ' COMMENT '导航栏类型,如:post,category,subject',
`postion` int(11) NOT NULL DEFAULT '0' COMMENT '位置',
`is_show` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否显示(0:否,1:是)',
`is_blank` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否新窗口打开(0:否,1:是)',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`title` varchar(255) NOT NULL COMMENT '标题',
`url` varchar(1000) NOT NULL COMMENT '链接地址',
PRIMARY KEY (`id`),
KEY `parent_id` (`parent_id`),
KEY `postion` (`postion`),
KEY `object_id` (`type`,`object_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='站点导航表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_nav`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_option`
--
DROP TABLE IF EXISTS `ws_option`;
CREATE TABLE IF NOT EXISTS `ws_option` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`autoload` int(11) NOT NULL DEFAULT '0' COMMENT '自动加载选项',
`option_key` varchar(255) NOT NULL COMMENT '键',
`option_value` text COMMENT '值',
PRIMARY KEY (`id`),
KEY `option_key` (`option_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='系统参数表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_option`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_post`
--
DROP TABLE IF EXISTS `ws_post`;
CREATE TABLE IF NOT EXISTS `ws_post` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`type` varchar(255) NOT NULL DEFAULT ' ' COMMENT '类型,如:article,product,page,advert',
`type_id` int(11) NOT NULL COMMENT '产品_类型ID',
`brand_id` int(11) NOT NULL DEFAULT '0' COMMENT '产品_品牌ID',
`is_new` tinyint(4) NOT NULL DEFAULT '0' COMMENT '产品_是否为新(0:否,1:是)',
`is_show` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否显示(0:否,1:是)',
`is_nav` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否显示在导航栏上(0:否,1:是)',
`is_recommend` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否推荐(0:否,1:是)',
`state` tinyint(4) NOT NULL DEFAULT '0' COMMENT '状态',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`visitor` int(11) NOT NULL DEFAULT '0' COMMENT '访问数',
`add_time` int(11) NOT NULL DEFAULT '0' COMMENT '时间(时间戳)',
`font` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '字体属性',
`image` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '图片信息',
`title` varchar(1000) NOT NULL COMMENT '标题',
`permalink` varchar(255) NOT NULL DEFAULT ' ' COMMENT '永久链接',
`author` varchar(255) NOT NULL DEFAULT ' ' COMMENT '作者',
`keywords` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '关键字',
`summary` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '摘要',
`depiction` text COMMENT '描述信息',
PRIMARY KEY (`id`),
KEY `type` (`type`),
KEY `type_id` (`type_id`),
KEY `brand_id` (`brand_id`),
KEY `sort` (`sort`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='主体表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_post`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_post_meta`
--
DROP TABLE IF EXISTS `ws_post_meta`;
CREATE TABLE IF NOT EXISTS `ws_post_meta` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`post_id` int(11) NOT NULL COMMENT '主体ID',
`type_id` int(11) NOT NULL DEFAULT '0' COMMENT '产品类型ID',
`mate_key` varchar(255) NOT NULL COMMENT '键',
`mate_value` text COMMENT '值',
PRIMARY KEY (`id`),
KEY `post_id` (`post_id`,`type_id`,`mate_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='主体附加信息表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_post_meta`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_post_relationship`
--
DROP TABLE IF EXISTS `ws_post_relationship`;
CREATE TABLE IF NOT EXISTS `ws_post_relationship` (
`post_id` int(11) NOT NULL COMMENT '主体ID',
`term_id` int(11) NOT NULL COMMENT '纬度ID',
PRIMARY KEY (`post_id`,`term_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='主体关系映射表';
--
-- 导出表中的数据 `ws_post_relationship`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_term`
--
DROP TABLE IF EXISTS `ws_term`;
CREATE TABLE IF NOT EXISTS `ws_term` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`parent_id` int(11) NOT NULL DEFAULT '0' COMMENT '父ID',
`taxonomy` varchar(50) NOT NULL DEFAULT 'category' COMMENT '数据纬度关系,如:category,subject,tag',
`type` varchar(50) NOT NULL DEFAULT ' ' COMMENT '类型,如:article,product,advert,comment',
`is_nav` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否显示在导航栏上(0:否,1:是)',
`is_show` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否显示(0:否,1:是)',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`count` int(11) NOT NULL DEFAULT '0' COMMENT '使用总次数',
`image` varchar(1000) NOT NULL DEFAULT ' ' COMMENT '缩略图',
`title` varchar(255) NOT NULL COMMENT '标题',
`permalink` varchar(255) NOT NULL DEFAULT ' ' COMMENT '永久链接',
PRIMARY KEY (`id`),
KEY `parent_id` (`parent_id`),
KEY `sort` (`sort`),
KEY `taxonomy` (`taxonomy`,`type`),
KEY `permalink` (`permalink`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='纬度表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_term`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_term_meta`
--
DROP TABLE IF EXISTS `ws_term_meta`;
CREATE TABLE IF NOT EXISTS `ws_term_meta` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`term_id` int(11) NOT NULL COMMENT '纬度ID',
`mate_key` varchar(255) NOT NULL COMMENT '键',
`mate_value` text COMMENT '值',
PRIMARY KEY (`id`),
KEY `Index_1` (`term_id`,`mate_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='纬度附加信息表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_term_meta`
--
-- --------------------------------------------------------
--
-- 表的结构 `ws_widget`
--
DROP TABLE IF EXISTS `ws_widget`;
CREATE TABLE IF NOT EXISTS `ws_widget` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`page_id` int(11) NOT NULL DEFAULT '0' COMMENT '页面ID',
`type` varchar(255) NOT NULL DEFAULT ' ' COMMENT '类型',
`postion` int(11) NOT NULL DEFAULT '0' COMMENT '位置',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`title` varchar(255) NOT NULL DEFAULT ' ' COMMENT '标题',
`value` text COMMENT '主体信息',
PRIMARY KEY (`id`),
KEY `page_id` (`page_id`),
KEY `type` (`type`),
KEY `postion` (`postion`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Widget列表' AUTO_INCREMENT=1 ;
--
-- 导出表中的数据 `ws_widget`
--
<file_sep><?php
define('MAGPIE_DIR', APP_DIR . 'vendors/magpierss-0.72/');
define('MAGPIE_CACHE_DIR', CACHE_DIR . 'magpierss');
define('MAGPIE_OUTPUT_ENCODING', 'UTF-8');
require_once(MAGPIE_DIR . 'rss_fetch.inc');
?><file_sep><?php
// 注册
if (App::option(ENT_PRODUCT)) {
appWidget::register('products', '产品列表', '指定某个分类或专题下的产品 ');
}
appWidget::register('articles', '文章列表', '指定某个分类或专题下的文章 ');
appWidget::register('categories', '分类列表', '以指定的方式显示文章或产品分类树 ');
appWidget::register('feedback', '留言本', '指定显示某些留言表单 ');
appWidget::register('rich', '富文本', '任意文本或HTML ');
appWidget::register('text', '文本', '任意文本或HTML ');
appWidget::register('advertisement', '广告', '上传图片或FLASH为广告 ');
appWidget::register('rss', 'RSS', '来自任何 RSS 或 Atom feed 的条目 ');
/**
* Widget接口
*/
interface iWidget
{
/**
* 后台修改表格
*/
public static function admin_form();
/**
* 前台显示HTML
*/
public static public function html($postion = null, $id = null, $title = null, $widget = null);
}
/**
* Widget基础类
*/
class appWidget
{
/**
* Widget列表
*
* @var array
*/
static $widgets = array();
/**
* 注册Widget
*/
static function register($widget, $name = null, $depiction = null, $file = null)
{
if (empty($file))
$file = APP_DIR . "widget/{$widget}.php";
if (file_exists($file))
require($file);
if (class_exists("{$widget}_widget"))
self::$widgets[$widget] = array($name, $depiction);
}
/**
* 输出Widget标题
*/
static function title($title)
{
$title = trim($title);
if (!empty($title)) {
echo <<< eof
<div class="com_title">
<div class="com_title_in">
<div class="com_title_inner">
<h2>{$title}</h2>
</div>
</div>
</div>
eof;
}
}
/**
* 输出Widget标题
*/
static function title_format($type, $title)
{
return self::$widgets[$type][0] . ' [' . trim($title) . ']';
}
/**
* 格式化Widget内容
*/
static function format_value($type, $value = null)
{
// 富文本处理时不进行序列化
if ($type == 'rich') {
return trim($_POST['FCKeditor1']);
}
$params = $_POST['widget'];
if (empty($params) || !is_array($params))
$params = array();
$class = "{$type}_widget";
if (class_exists($class)) {
$method = 'submit';
$ref = new ReflectionClass($class);
if ($ref->hasMethod($method)) {
$value = isset($value) ? unserialize($value) : array();
$value = call_user_func_array(array($class, $method), array($value));
if ($value)
$params = array_merge($value, $params);
}
}
return serialize($params);
}
/**
* 格式化Widget表单
*/
static function format_form($type, $id = 0, $widget = null)
{
$class = "{$type}_widget";
if (class_exists($class)) {
$params = array(null, null, null);
if ($id && $widget) {
$value = $widget['value'];
if ($type != 'rich')
$value = unserialize($value);
$params = array($id, $widget['title'], $value);
}
echo '<div class="page-div"><div class="main-div">';
call_user_func_array(array($class, 'admin_form'), $params);
echo '</div></div>';
}
}
/**
* 输出Widget表单 - 头
*/
static function form_header($type, $id, $title = null)
{
$title = trim($title);
if (empty($title)) $title = '';
if (defined('PAGE_EDIT')) {
if (!$id) {
$action = lpUrl::clean_url('admin_pageedit', 'add');
$handle = 'pageWidgetAdd';
$data = '{"type": "' . $type . '", "postion": pagePostion, "page_id": pageId}';
} else {
$action = lpUrl::clean_url('admin_pageedit', 'update');
$handle = 'pageWidgetUpdate';
$data = '{}';
}
} else {
$action = lpUrl::clean_url('admin_widget', 'update', array('id' => $id));
$handle = 'widgetUpdate';
$data = '{}';
}
?>
<style type="text/css">
#formWidget td.label{width:230px;}
</style>
<script language="javascript">
$(document).ready(function($) {
$("#formWidget").validate({
submitHandler: function() {
loadIng();
// 富文本
setFckeditor();
$("#formWidget").ajaxSubmit({
dataType: "xml",
data: <?php echo $data;?>,
success: <?php echo $handle;?>
});
return false;
}
});
});
</script>
<form method="post" action="<?php echo $action;?>" id="formWidget">
<input type="hidden" name="id" value="<?php echo $id;?>" />
<table border="0" cellpadding="3" cellspacing="0">
<tr>
<td class="label">Widget 标题:</td>
<td><input name="title" size="40" type="text" class="text" value="<?php echo $title;?>" /></td>
</tr>
<?php
}
/**
* 输出Widget表单 - 尾
*/
static function form_footer()
{
echo <<< eof
<tr>
<td> </td>
<td><input id="btnSubmit" class="button" type="submit" value="确定"/></td>
</tr>
</table>
</form>
eof;
}
}
?><file_sep><?php
set_time_limit(0);
// 引用文件
require(APP_DIR . 'vendors/Snoopy-1.2.4/Snoopy.class.php');
require(APP_DIR . 'vendors/htmlsql-v0.5/htmlsql.class.php');
App::vendor('image');
class controller_spider extends adminCtrl
{
public $city = "fuzhou";
public $urls = array();
public $base_url;
public $host;
// 分类ID
public $cid = 2;
/**
* 构造
*/
function __construct()
{
parent::__construct();
$this->host = "http://{$this->city}.cncn.com/";
$this->base_url = $this->host . "jingdian/";
}
/**
* 开始
*/
function action_index()
{
if (!isset($_SESSION[$this->city])) {
$this->get_urls($this->base_url);
$_SESSION[$this->city] = $this->urls;
}
$i = intval($_GET['i']);
$count = count($_SESSION[$this->city]);
if ($i >= 0 && $i <= $count) {
$url = $_SESSION[$this->city][$i];
$url = $this->host . $url . "profile.html";
$refresh = lpUrl::clean_url('admin_spider', 'index', array('i' => ++$i, 'count' => $count));
$this->get_content($url);
?>
<meta http-equiv="refresh" CONTENT="1; url=<?php echo $refresh;?>">
<?php
}
}
/**
* 分析链接地址
*/
function get_urls($url = null)
{
static $first = true;
if ($url) {
$wsql = new htmlsql();
if ($wsql->connect('url', $url)) {
// 链接
$wsql->page = iconv('GB2312', 'UTF-8//IGNORE', $wsql->page);
if($wsql->query('SELECT text FROM dt where $class=="pic"')) {
foreach($wsql->fetch_array() as $row) {
if (preg_match("/<a href=\"\/(.*)\" target=\"_blank\"/", $row['text'], $matches)) {
$this->urls[] = trim($matches[1]);
}
}
}
// 导航
if (!$first) {
return true;
}
$first = false;
$wsql->isolate_content('<div class="cp2">', '<div class="a1">');
if($wsql->query('SELECT text FROM li where $class=="num"')) {
foreach($wsql->fetch_array() as $row) {
if (preg_match("/<a href=\"(.*)\"/", $row['text'], $matches)) {
$url = $this->base_url . trim($matches[1]);
$this->get_urls($url);
}
}
}
}
}
}
/**
* 分析文章内容
*/
function get_content($url = null)
{
if ($url) {
$wsql = new htmlsql();
if ($wsql->connect('url', $url)) {
$content = $wsql->page = iconv('GB2312', 'UTF-8//IGNORE', $wsql->page);
// 标题
$title = "未知";
if($wsql->query('SELECT * FROM h2')) {
$title = $wsql->results[0]['text'];
}
// 内容
$start = '<div class="content">';
$end = '</div>
</div>
<!--lft-->
</div>
';
$wsql->isolate_content($start, $end);
$content = $wsql->page;
// 第一张图片
$p = "/(<img src=\")(.*\.(jpg|jpeg|gif|png))(\" width=\"210\" height=\"140\">)/";
if (preg_match($p, $content, $matches)) {
$url_new = $this->get_image(trim($matches[2]), trim($matches[3]));
$content = preg_replace($p, '', $content);
// $content = preg_replace($p, "\${1}/tmp/resource/post/thumb/{$url_new}\" title=\"{$title}\" />", $content);
}
// 过滤链接
$content = preg_replace("/(<a href=\")(.*)(\">(.*)<\/a>)/", "\${4}", $content);
$content = trim($content);
echo $title;
// 插入数据库
/**/
$permalink = biz::str2pingyin($title);
$params = array('type' => ENT_ARTICLE, 'add_time' => time(), 'is_nav' => 0, 'is_show' => 1,
'title' => $title, 'permalink' => $permalink , 'image' => $url_new, 'keywords' => $title, 'depiction' => $content);
App::model('post', 'post_relationship');
if ($post_id = Mpost::insert($params))
biz::add_post_category($post_id, $this->cid, ENT_ARTICLE);
}
}
return false;
}
/**
* 保存图片
*/
function get_image($url, $ext)
{
$md5 = md5($url);
$name = $md5 . '.' . $ext;
$relative = substr($md5, 0, 1) . '/';
$thumb_dir = RES_DIR . 'post/thumb/' . $relative;
$base_dir = RES_DIR . 'post/' . $relative;
lpFodler::mkdir($thumb_dir);
lpFodler::mkdir($base_dir);
$base_new = $base_dir . $name;
$url_new = $relative . $name;
$img = file_get_contents($url);
file_put_contents($base_new, $img);
$img = new Image($base_new, $ext, $thumb_dir);
$img->thumb(200, 200);
$img->save(md5($url));
return $url_new;
}
}
?><file_sep><?php
App::model('post', 'widget');
class controller_pageedit extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "Widget";
/**
* 小工具列表
*/
function action_list()
{
if ($page = accessor::get_page($_GET['page_id'])) {
$active_widgets = array();
$widgets = appWidget::$widgets;
foreach (accessor::get_widgets(-1, $_GET['page_id']) as $widget) {
$widget['title'] = appWidget::title_format($widget['type'], $widget['title']);
$active_widgets[$widget['postion']][] = $widget;
}
$this->assign('left', $active_widgets[1]);
$this->assign('middle', $active_widgets[2]);
$this->assign('right', $active_widgets[3]);
$this->assign('title', $page['title']);
$this->assign('page_id', $_GET['page_id']);
$this->assign('widgets', $widgets);
$this->display('pageedit');
}
}
/**
* 小工具列表
*/
function action_list2()
{
if ($page = accessor::get_page($_GET['page_id'])) {
$widgets = appWidget::$widgets;
$this->assign('title', $page['title']);
$this->assign('page_id', $_GET['page_id']);
$this->assign('widgets', $widgets);
$this->display('pageedit2');
}
}
/**
* 小工具表单
*/
function action_form()
{
define('PAGE_EDIT', true);
$widgets = appWidget::$widgets;
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
if (isset($widgets[$type])) {
$widget = accessor::get_widget($_GET['id']);
appWidget::format_form($type, $_GET['id'], $widget);
}
}
/**
* 接收到一个新的激活的WIDGET
*/
function action_add()
{
if ($this->is_post() && $page = accessor::get_page($_POST['page_id'])) {
$pos = array('left' => 1, 'middle' => 2, 'right' => 3);
if (isset($pos[$_POST['postion']])) {
$postion = $pos[$_POST['postion']];
$order = accessor::get_widget_max_order($postion, $_POST['page_id']);
$order = intval($order);
$order++;
$title = trim($_POST['title']);
$value = appWidget::format_value($_POST['type']);
$params = array('page_id' => $_POST['page_id'], 'type' => $_POST['type'], 'postion' => $postion, 'sort' => $order, 'title' => $title, 'value' => $value);
$id = Mwidget::insert($params);
$title = appWidget::title_format($_POST['type'], $title);
$this->response(null, '添加', "{$_POST['type']}: {$_POST['title']}", null, null, array('id' => $id, 'type' => $_POST['type'], 'title' => $title));
}
}
}
/**
* 更新WIDGET
*/
function action_update()
{
if ($this->is_post() && $widget = accessor::get_widget($_POST['id'])) {
$value = appWidget::format_value($widget['type'], $widget['value']);
Mwidget::update(array('title' => trim($_POST['title']), 'value' => $value))
->where('id = ?', $_POST['id'])->query();
$title = appWidget::title_format($widget['type'], $_POST['title']);
$this->response(null, '编辑', $widget['title'], null, null, array('id' => $_POST['id'], 'title' => $title));
}
}
/**
* 移动WIDGET位置
*/
function action_postion()
{
if ($this->is_ajax()) {
if (is_array($_POST['item'])) {
foreach ($_POST['item'] as $order => $id) {
Mwidget::update(array('sort' => $order, 'postion' => $_POST['postion']))
->where('id = ?', $id)->query();
}
}
}
}
/**
* 删除WIDGET
*/
function action_remove()
{
if ($this->is_ajax() && $widget = accessor::get_widget($_POST['id'])) {
Mwidget::delete()->where('id = ?', $_POST['id'])->query();
$this->response(null, '删除', "{$widget['type']}: {$widget['title']}");
}
}
}
?><file_sep><?php
/**
* 产品列表Widget类
*/
class products_widget implements iWidget
{
public static $name = "products";
public static function admin_form($id = null, $title = null, $widget = null)
{
$limit = isset($widget['limit']) ? intval($widget['limit']) : 6;
$sort = isset($widget['sort']) ? trim($widget['sort']) : '';
$is_new = isset($widget['is_new']) ? 'checked' : '';
$is_recommend = isset($widget['is_recommend']) ? 'checked' : '';
$is_more = isset($widget['is_more']) ? 'checked' : '';
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label">产品分类:</td>
<td>
<select name="widget[category_id]" id="pCategory">
<option value="">-- 请选择 --</option>
<?php
foreach (accessor::get_categories(ENT_PRODUCT) as $cagegory) {
$selected = $cagegory['id'] == $widget['category_id'] ? 'selected' : '';
echo "<option value='", $cagegory['id'], "' ", $selected, ">", $cagegory['separator'], $cagegory['title'], ' (', $cagegory['count'], ")</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td class="label">列表[顺序]:</td>
<td>
<select name="widget[sort]">
<option value="" <?php if ($sort == '') echo 'selected';?>>默认</option>
<option value="sort" <?php if ($sort == 'sort') echo 'selected';?>>排序设定值</option>
<option value="visitor" <?php if ($sort == 'visitor') echo 'selected';?>>点击数</option>
</select>
</td>
</tr>
<tr>
<td class="label">列表[个数]:</td>
<td>
<input name="widget[limit]" type="text" class="text" value="<?php echo $limit;?>" size="5" />
</td>
</tr>
<tr>
<td class="label">显示方式:</td>
<td>
<select name="widget[display]">
<option value="" <?php if ($type == '') echo 'selected';?>>列表</option>
<option value="slide" <?php if ($type == 'slide') echo 'selected';?>>幻灯片</option>
<option value="lantern" <?php if ($type == 'lantern') echo 'selected';?>>走马灯</option>
</select>
</td>
</tr>
<tr>
<td class="label">选项:</td>
<td>
<input id="widget[is_more<?php echo $id;?>]" name="widget[is_more]" <?php echo $is_more;?> type="checkbox" value="1" />
<label for="widget[is_more<?php echo $id;?>]">显示更多</label>
<input id="widget[is_new<?php echo $id;?>]" name="widget[is_new]" <?php echo $is_new;?> type="checkbox" value="1" />
<label for="widget[is_new<?php echo $id;?>]">新品</label>
<input id="widget[is_recommend<?php echo $id;?>]" name="widget[is_recommend]" <?php echo $is_recommend;?> type="checkbox" value="1" />
<label for="widget[is_recommend<?php echo $id;?>]">推荐</label>
</td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$limit = isset($widget['limit']) ? intval($widget['limit']) : 6;
$sort = isset($widget['sort']) ? trim($widget['sort']) : '';
if (!in_array($sort, array('sort', 'visitor'))) $sort = '';
$posts = accessor::get_posts_by_term($widget['category_id'], $limit, $sort);
if (isset($widget['is_new']))
$posts->where('is_new = 1');
if (isset($widget['is_recommend']))
$posts->where('is_recommend = 1');
$dom = '';
$posts = $posts->get_results();
$count = count($posts);
if ($count > 0) {
$i = 0;
foreach ($posts as $post) {
if ($i % 3 == 0)
$dom .= '<div class="product_row clearfix">';
$class = $i % 3 == 2 ? 'last_cell' : '';
$link = appUrl::post(ENT_PRODUCT, $post['id']);
$thumb = RES_URI . "post/thumb/{$post['image']}";
$dom .= <<< eof
<div class="prd_cell {$class}">
<div class="pic">
<a href="{$link}" title="{$post['title']}">
<img src="{$thumb}" alt="{$post['title']}" />
</a>
</div>
<div class="info">
<h3>
<a href="{$link}" title="{$post['title']}">
{$post['title']}
</a>
</h3>
</div>
</div>
eof;
if ($i % 3 == 2 || $i == $count -1)
$dom .= '</div>';
$i++;
}
if (isset($widget['is_more'])) {
$url = appUrl::category(ENT_PRODUCT, $widget['category_id']);
$dom .= "<div class='more'><a href='{$url}'>" . appView::__('More ...') . "</a></div>";
}
} else {
$dom .= '<div>' . appView::__('No data') . '</div>';
}
echo '<div class="content widget_products">' . $dom . '</div>';
}
}
?><file_sep><?php
class controller_dialog extends adminCtrl
{
/**
* 广告选择层数据
*/
function action_advert()
{
$title = $_POST['title'];
$posts = accessor::get_adverts(true);
if (strlen($title) > 0) {
$title = trim($title);
if ($title != '') {
$posts->where('ws_post.title like "%?%"', $title);
}
}
$this->assign_object('posts', $posts, 10);
$this->assign('multiple', true);
$this->assign('action', lpUrl::clean_url('admin_advert', 'advert_add'));
$this->assign('fetch', lpUrl::clean_url('admin_main', 'dialog_advert'));
$this->display($this->is_list() ? '_advert_list_div' : '_advert_list');
}
}
?><file_sep><?php
/**
* 缓存处理类
*/
class cacher
{
/**
* 单例
*
* @var object
*/
public static $__instance = null;
/**
* 临时数据
*
* @var array
*/
public $data = array();
/**
* 路径
*
* @var array
*/
public $dir;
/**
* 单例
*/
static function instance()
{
if (!self::$__instance) {
self::$__instance = new cacher();
}
return self::$__instance;
}
/**
* 构造函数
*/
function __construct()
{
$this->dir = CACHE_DIR . 'runinfo' . DS;
if (!file_exists($this->dir))
lpFodler::mkdir($this->dir);
}
/**
* 生成指定KEY的文件路径
*/
function file($key)
{
$name = md5($key);
return $this->dir . "cache_{$name}.php";
}
/**
* 读取
*/
static function read($key)
{
$i = self::instance();
$file = $i->file($key);
if (file_exists($file)) {
$i->data[$key] = require($file);
return $i->data[$key];
}
return false;
}
/**
* 写入
*/
static function write($key, $data)
{
if (!is_array($data))
return false;
$i = self::instance();
$file = $i->file($key);
$date = date('Y-m-d H:i:s');
$array = var_export($data, true);
$tmp =<<< eof
<?php
/**
* Cache file {$key} create at {$date}
*/
return {$array};
?>
eof;
return file_put_contents($file, $tmp);
}
}
?><file_sep><?php
/**
* 前台调度器
*/
class app_dispatcher extends Dispatcher
{
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
if (isset($_GET['plugin']) && !empty($_GET['plugin'])) {
$plugin = $_GET['plugin'];
$list = $GLOBALS['PLUGIN_LIST'];
if (is_array($list) && in_array($plugin, array_keys($list)))
$this->dir = PLUGIN_DIR . $plugin . DS . 'controller' . DS . (empty(App::instance()->folder) ? '' : App::instance()->folder . DS);
}
$in_folder = false;
$folders = App::option('folders');
if (is_array($folders) && count($folders) > 0) {
if (preg_match("/^(" . implode('|', array_keys($folders)) .")\/?/i", $this->params['url'])) {
$in_folder = true;
}
}
if (!$in_folder) {
$ctrls = array('index');
if (in_array($this->controller, $ctrls)) {
// 原始控制器
} elseif (preg_match("/\.html$/i", $this->params['url'])) {
// 基础文章
$tmp = explode('/', $this->params['url']);
$link = array_pop($tmp);
$_GET['permalink'] = preg_replace("/\.html$/i", "", $link);
if (!App::option(ENT_PRODUCT))
$_GET['type'] = ENT_ARTICLE;
else
$_GET['type'] = array_shift($tmp);
$this->controller = 'post';
$this->action = 'post';
} elseif (preg_match("/([a-z0-9_]+(\/)?)+/i", $this->params['url'])) {
$tmp = explode('/', $this->params['url']);
$_GET['permalink'] = array_pop($tmp);
if (!App::option(ENT_PRODUCT))
$_GET['type'] = ENT_ARTICLE;
else
$_GET['type'] = array_shift($tmp);
$this->controller = 'post';
$this->action = 'category';
}
}
$this->check();
}
}
?><file_sep><?php
/**
* 业务层逻辑层
*/
class biz
{
/**
* 输出Javascript头部
*/
static function header_js()
{
header("Content-Type: application/javascript; charset: UTF-8");
header("Cache-Control: public");
header("Pragma: cache");
}
/**
* 输出XML头部
*/
static function header_xml()
{
header("Content-Type: text/xml; charset: UTF-8");
}
/**
* 输出404找不到页面
*/
function header_404()
{
header("HTTP/1.0 404 Not Found");
echo "404 Not Found";
exit();
}
/**
* 输出500内部错误
* 1000,系统超时;1001,没有权限
*/
static function header_500($errorno = 1000)
{
header("HTTP/1.0 500");
echo $errorno;
exit();
}
/**
* 将字符串转换为拼音
*/
static function str2pingyin($string, $trim = true)
{
$pinyin = lpString::str2pinyin($string);
$pinyin = strtolower($pinyin);
if ($trim)
return preg_replace("/[^a-z0-9]+/i", "", $pinyin);
return $pinyin;
}
//////////////// 以下为系统逻辑 ////////////////
/**
* 取得系统配置选项
*/
static function get_sys_options()
{
return array(
'site' => '基本信息',
'seo' => '搜索优化',
'cache' => '页面缓存',
'list' => '列表展示',
'thumb' => '图片大小',
'water' => '图片水印'
);
}
/**
* 取得链接URL
*/
static function get_nav_url($id, $type, $url = null)
{
switch ($type) {
case ENT_PAGE:
$url = appUrl::page($id);
break;
case ENT_ARTICLE:
$url = appUrl::post(ENT_ARTICLE, $id);
break;
case ENT_CATEGORY:
$url = '';
if ($term = accessor::get_term($id))
$url = call_user_func_array(array('appUrl', $type), array($term['type'], $id));
break;
default:
$url = appHook::apply_filters('get_nav', $url, $type, $id);
break;
}
return $url;
}
/**
* 同步导航栏显示状态
*/
function nav2synchronize($id, $type, $state = 0)
{
App::model('post', 'term');
switch ($type) {
case ENT_PAGE:
case ENT_ARTICLE:
Mpost::update(array('is_nav' => $state))->where('id = ?', $id)->query();
break;
case ENT_CATEGORY:
Mterm::update(array('is_nav' => $state))->where('id = ?', $id)->query();
break;
default:
appHook::do_action('nav2synchronize', array($id, $type, $state));
break;
}
}
/**
* 缓存分类目录树
*/
static function category2cache()
{
$data = array();
$terms = accessor::get_terms(ENT_CATEGORY, ENT_ARTICLE);
foreach ($terms as $term)
$data[$term['id']] = array(
'title' => $term['title'],
'parent_id' => $term['parent_id'],
'permalink' => $term['permalink'],
'count' => $term['count']
);
// 写入
cacher::write(ENT_CATEGORY, $data);
}
/**
* 取得表单字段
*/
static function get_post_fields($type_id, $post_id)
{
if (!$type = accessor::get_form($type_id))
return true;
$fields = accessor::get_fields($type_id, false, $post_id);
if (count($fields) == 0) {
echo "<tr><td class='label' style='height:21px;'>产品参数:</td><td><i>请配置产品类型对应字段</i></td></tr>";
return true;
}
foreach ($fields as $key => $field) {
$class = array();
$constraint = unserialize($field['constraint']);
if (is_array($constraint)) {
if (!empty($constraint['requried']))
$class[] = 'required';
if (!empty($constraint['format']))
$class[] = $constraint['format'];
}
$class = implode(' ', $class);
$dom = "<input type='hidden' name='keys[]' value='{$field['id']}' />";
switch ($field['style']) {
case 1:
$dom .= "<input size='35' class='text {$class}' type='text' name='values[{$key}]' value='{$field['value']}' />";
break;
case 2:
$dom .= "<select class='{$class}' name='values[{$key}]'>";
$options = unserialize($field['items']);
if (is_array($options)) {
foreach ($options as $val)
$dom .= "<option value='{$val}'>{$val}</option>";
}
$dom .= "</select>";
break;
case 3:
$dom .= "<textarea class='text {$class}' name='values[{$key}]' cols='35' rows='3'>{$field['value']}</textarea>";
break;
}
echo "<tr><td class='label'>产品参数[{$fields[$key]['title']}]:</td><td>{$dom}</td></tr>";
}
}
/**
* 更新站点配置
*/
static function update_option($key, $value, $serialize = false)
{
App::model('option');
if ($serialize || is_array($value))
$value = serialize($value);
if (Moption::find('option_key = ?', $key)->get_count() == 0)
return Moption::insert(array('option_key' => $key, 'option_value' => $value));
return Moption::update(array('option_value' => $value))
->where('option_key = ?', $key)->query();
}
/**
* 更新分类附属信息
*/
static function update_term_meta($term_id, $key, $value, $serialize = false)
{
App::model('term_meta');
if ($serialize || is_array($value))
$value = serialize($value);
if (Mterm_meta::find('term_id = ? AND mate_key = ?', $term_id, $key)->get_count() == 0)
return Mterm_meta::insert(array('term_id' => $term_id, 'mate_key' => $key, 'mate_value' => $value));
return Mterm_meta::update(array('mate_value' => $value))
->where('term_id = ? AND mate_key = ?', $term_id, $key)->query();
return false;
}
/**
* 更新产品或文章附属信息
*/
static function update_post_meta($post_id, $key, $value, $type_id = 0, $serialize = false)
{
App::model('post_meta');
if ($serialize || is_array($value))
$value = serialize($value);
if (Mpost_meta::find('post_id = ? AND type_id = ? AND mate_key = ?', $post_id, $type_id, $key)->get_count() == 0)
return Mpost_meta::insert(array('post_id' => $post_id, 'type_id' => $type_id, 'mate_key' => $key, 'mate_value' => $value));
return Mpost_meta::update(array('mate_value' => $value))
->where('post_id = ? AND type_id = ? AND mate_key = ?', $post_id, $type_id, $key)->query();
return false;
}
/**
* 添加关系
*/
static function add_relation($post_id, $term_id)
{
App::model('post_relationship');
return Mpost_relationship::insert(array('post_id' => $post_id, 'term_id' => $term_id));
}
/**
* 添加数据在导航栏上
*/
static function add_nav($type, $object_id, $state, $title = null)
{
App::model('nav');
$params['is_show'] = $state;
if (Mnav::find('type = ? AND object_id = ?', $type, $object_id)->get_count() > 0) {
return Mnav::update($params)
->where('type = ? AND object_id = ?', $type, $object_id)->query();
} elseif (!empty($state)) {
$params['type'] = $type;
$params['object_id'] = $object_id;
if (!empty($title))
$params['title'] = $title;
return Mnav::insert($params);
}
}
/**
* 增加使用次数
*/
static function update_count_term($id, $plus = true, $count = 1)
{
App::model('term');
if ($id) {
$ids = array($id);
$term = accessor::get_term($id);
if ($term['parent_id'])
$ids[] = $term['parent_id'];
$count = '`count` ' . ($plus ? '+' : '-') . $count;
$query = "UPDATE `ws_term` SET `count` = {$count} WHERE `id` IN(" . implode(',', $ids) . ")";
return Mterm::execute($query);
}
return false;
}
/**
* 增加使用次数
*/
static function update_count_form($id, $plus = true, $count = 1)
{
App::model('form');
if ($id) {
$count = '`count` ' . ($plus ? '+' : '-') . $count;
$query = "UPDATE `ws_form` SET `count` = {$count} WHERE `id` = {$id}";
return Mform::execute($query);
}
return false;
}
/**
* 增加使用次数
*/
static function update_count_comment($id, $plus = true, $count = 1)
{
App::model('comment');
if ($id) {
$count = '`count` ' . ($plus ? '+' : '-') . $count;
$query = "UPDATE `ws_comment` SET `count` = {$count} WHERE `id` = {$id}";
return Mcomment::execute($query);
}
return false;
}
/**
* 删除产品或文章
*/
static function delete_post($post_id)
{
App::model('post', 'post_meta', 'nav', 'comment');
if ($p = accessor::get_post($post_id)) {
lpFile::unlink(RES_DIR . "post/{$p['image']}");
lpFile::unlink(RES_DIR . "post/thumb/{$p['image']}");
$images = accessor::get_post_meta($post_id, 'images');
if (is_array($images)) {
foreach ($images as $image) {
lpFile::unlink(RES_DIR . "post/{$image}");
lpFile::unlink(RES_DIR . "post/thumb/{$image}");
}
}
foreach (accessor::get_post_relations($post_id) as $id)
biz::update_count_term($id, false);
biz::delete_relation(1, $post_id);
Mpost_meta::delete('post_id = ?', $post_id)->query();
Mnav::delete('type = ? AND object_id = ?', $p['type'], $post_id)->query();
Mcomment::update(array('post_id' => 0))->where('post_id = ?', $post_id)->query();
return Mpost::delete('id = ?', $post_id)->query();
}
return false;
}
/**
* 删除分类(不进行级取删除)
*/
static function delete_category($c, $type)
{
App::model('term', 'term_meta');
foreach (accessor::get_term_relations($c['id'], ENT_CATEGORY) as $post_id)
biz::delete_post($post_id);
lpFile::unlink(RES_DIR . "category/{$c['image']}");
biz::delete_nav($c['id'], "category|{$type}");
Mterm::delete('id = ?', $c['id'])->query();
Mterm_meta::delete('term_id = ?', $c['id'])->query();
}
/**
* 删除标签
*/
static function delete_tag($tag_id)
{
App::model('term');
if ($tag = accessor::get_term($tag_id)) {
Mterm::delete('id = ?', $tag_id)->query();
biz::delete_relation(2, null, $tag_id);
return true;
}
return false;
}
/**
* 删除关系,为了防止误删加入 [$type] 进行验证
* 0 => 两种不为空
* 1 => 前者不为空
* 2 => 后都不为空
*/
static function delete_relation($type, $post_id = null, $term_id = null)
{
$flag = false;
switch ($type) {
case 0:
$flag = $post_id && $term_id;
break;
case 1:
$flag = !empty($post_id);
break;
case 2:
$flag = !empty($term_id);
break;
}
if (!$flag) {
// 调试下
App::log('debug', $type . '|' . $post_id . '|' . $term_id);
return false;
}
App::model('post_relationship');
$relation = Mpost_relationship::delete();
if ($post_id)
$relation->where('post_id = ?', $post_id);
if ($term_id)
$relation->where('term_id = ?', $term_id);
return $relation->query();
}
/**
* 删除评论
*/
static function delete_comment($comment_id)
{
App::model('comment');
if ($c = accessor::get_comment($comment_id)) {
Mcomment::delete('id = ?', $comment_id)->query();
Mcomment::delete('parent_id = ?', $comment_id)->query();
biz::update_count_term($c['category_id'], false);
if ($c['parent_id'])
biz::update_count_comment($c['parent_id'], false);
return true;
}
return false;
}
/**
* 删除导航
*/
static function delete_nav($object_id, $type)
{
App::model('nav');
return Mnav::delete('type = ? AND object_id = ?', $type, $object_id)->query();
}
/**
* 添加分类关系
*/
static function add_post_category($post_id, $c_id, $type)
{
if ($c = accessor::get_category($c_id, $type)) {
biz::update_count_term($c_id, true);
biz::add_relation($post_id, $c_id);
return true;
}
return false;
}
/**
* 编辑分类关系
*/
static function update_post_category($post_id, $c_id, $type)
{
if ($c = accessor::get_category($c_id, $type)) {
$old = accessor::get_post_relations($post_id, ENT_CATEGORY, false);
if ($old != $c_id) {
biz::update_count_term($c_id, true);
biz::update_count_term($old, false);
biz::add_relation($post_id, $c_id);
biz::delete_relation(0, $post_id, $old);
}
return true;
}
return false;
}
/**
* 添加标签
*/
static function add_post_tag($post_id, $tags, $type)
{
App::model('term');
$ids = array();
if (!empty($tags)) {
$tmp = explode(',', $tags);
$tags = array(); // 用户记录合法TAG
foreach ($tmp as $tag) {
$tag = trim($tag);
if (empty($tag) || in_array($tag, $tags))
continue;
array_push($tags, $tag);
if ($term = accessor::get_term_by_title($tag, $type)) {
$id = $term['id'];
} else {
$params = array('taxonomy' => ENT_TAG, 'type' => $type, 'title' => $tag, 'permalink' => biz::str2pingyin($tag));
$id = Mterm::insert($params);
}
if ($id) {
array_push($ids, $id);
if (!accessor::get_post_relation($post_id, $id)) {
biz::update_count_term($id, true);
biz::add_relation($post_id, $id);
}
}
}
}
return $ids;
}
/**
* 修改标签
*/
static function update_post_tag($post_id, $tags, $type)
{
$ids = biz::add_post_tag($post_id, $tags, $type);
foreach (accessor::get_post_relations($post_id, ENT_TAG) as $id) {
if (in_array($id, $ids))
continue;
biz::update_count_term($id, false);
biz::delete_relation(0, $post_id, $id);
}
return true;
}
/**
* 添加属性(产品系统)
*/
static function add_post_field($post_id, $type_id, $fields, $values)
{
if (is_array($fields) && is_array($values) && $type_id) {
if (count($fields) == count($values)) {
foreach ($fields as $i => $id) {
if (!accessor::get_field($id))
continue;
biz::update_post_meta($post_id, $id, $values[$i], $type_id);
}
return true;
}
}
return false;
}
/**
* 编辑属性(产品系统)
*/
static function update_post_field($post_id, $type_id, $fields, $values, $type_id_old = 0)
{
App::model('post_meta');
if ($type_id_old) {
if ($type_id != $type_id_old)
Mpost_meta::delete('post_id = ? AND type_id = ?', $post_id, $type_id_old);
return biz::add_post_field($post_id, $type_id, $fields, $values);
}
return false;
}
}
?><file_sep><?php
class controller_upload extends appCtrl
{
/**
* 文件上传
*/
function action_run()
{
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
ob_end_clean();
ob_start();
session_id($_POST["PHPSESSID"]);
$session = comSession::read('admininfo');
if (!$session = comSession::read('admininfo'))
lpUrl::url('admin_index');
// 开始
if (!empty($_POST['type'])) {
$type = trim($_POST['type']);
$size = accessor::get_option('thumb', $type);
$original = ($type == 'post');
echo uploader::thumb($type, $size, $_POST['source'], $original);
}
}
}
}
?><file_sep><?php
/**
* 插件列表
*/
return array(
// 'flight' => '机票管理',
// 'iframe' => '外链页面'
);
?><file_sep><?php
App::model('term', 'term_meta', 'comment');
class controller_category extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "";
/**
* 分类类型列表
*/
public static $keys = array(ENT_ARTICLE => '文章', ENT_PRODUCT => '产品', ENT_COMMENT => '评论');
public $type; // 用于流程跳转
public $type2db; // 用于数据库操作
public $tree_id = 0; // 添加分类时需要用到树ID
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->type = $this->type2db = isset($_GET['type']) ? strtolower($_GET['type']) : null;
if (in_array($this->type, array_keys(self::$keys))) {
/* 树 */
if ($this->type == ENT_ARTICLE) {
$id = isset($_GET['tree_id']) ?
intval($_GET['tree_id']) : intval($_POST['tree_id']);
if ($id > 0) {
if ($tree = accessor::get_form($id, 'tree')) {
$this->type2db .= $id;
$this->tree_id = $id;
}
}
}
/* /树 */
$name = self::$keys[$this->type];
$this->module = "{$name}分类";
$this->assign('name', $name);
$this->assign('type', $this->type);
} else {
biz::header_404();
}
}
/**
* 分类列表
*/
function action_list()
{
/* 树 */
$this->assign('trees', accessor::get_forms('tree'));
/* /树 */
$this->_assign_category();
$this->display($this->is_list() ? 'category_list_div' : 'category_list');
}
/**
* 添加分类
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$this->_check_relationship();
$permalink = $this->_check_permalink();
$params = array('taxonomy' => ENT_CATEGORY, 'type' => $this->type2db, 'parent_id' => $_POST['parent_id'], 'title' => $_POST['title'], 'permalink' => $permalink);
$cid = Mterm::insert($params);
if ($cid) {
$this->_sava_meta($cid);
$this->_upload_thumb($cid);
}
$this->response(null, '添加', $_POST['title'], 0, array('admin_category', 'list', array('type' => $this->type)));
}
$this->_assing_form();
$this->_assign_category(true);
$this->assign('action', lpUrl::clean_url('admin_category', 'add', array('type' => $this->type, 'tree_id' => $this->tree_id)));
$this->display('category_add');
}
/**
* 编辑分类
*/
function action_update()
{
if ($c = accessor::get_category($_GET['category_id'])) {
if ($this->is_post()) {
$this->_check_title();
$this->_check_relationship($c['id']);
$permalink = $this->_check_permalink();
$params = array('parent_id' => $_POST['parent_id'], 'title' => $_POST['title'], 'permalink' => $permalink);
$flag = Mterm::update($params)
->where('id = ?', $c['id'])->query();
if ($flag) {
$this->_sava_meta($c['id']);
$this->_upload_thumb($c['id'], $c['image']);
if ($_POST['parent_id'] != $c['parent_id']) {
biz::update_count_term($c['parent_id'], false, $c['count']);
biz::update_count_term($_POST['parent_id'], true, $c['count']);
}
}
$this->response(null, '编辑', $c['title'], 0, array('admin_category', 'list', array('type' => $this->type)));
}
$this->_assign_this($c);
$this->_assing_form($c['id']);
$this->_assign_category(true);
$this->assign('action', lpUrl::clean_url('admin_category', 'update', array('type' => $this->type, 'category_id' => $c['id'])));
$this->display('category_add');
}
}
/**
* 移动位置
*/
function action_postion()
{
if ($this->is_ajax()) {
$sort = 1;
$count = count($_POST['category']);
for ($i = $count; $i > 0; $i--) {
$id = $_POST['category'][$i - 1];
Mterm::update(array('sort' => $sort++))
->where('id = ?', $id)->query();
}
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $c = accessor::get_category($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
$this->_delete_category($c);
break;
case 'edit':
$this->edit('Mterm', 'sort');
break;
case 'toggle':
if ($this->toggle('Mterm', 'is_nav', 'is_show') && $_POST['field'] == 'is_nav')
biz::add_nav(ENT_CATEGORY, $c['id'], $_POST['state'], $c['title']);
break;
}
$this->response(null, $operate, $c['title']);
}
}
///// 私有方法 /////
/**
* 检测分类名称
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "分类名称不能为空", 2);
}
/**
* 检测上级分类是否存在
*/
function _check_relationship($id = 0)
{
$_POST['parent_id'] = intval($_POST['parent_id']);
if ($_POST['parent_id'] && !accessor::get_category($_POST['parent_id']))
$this->response(null, null, "上级分类ID:{$_POST['parent_id']},不存在", 2);
$ids = accessor::get_categories_by_parent($id, true);
if ($id && $_POST['parent_id'] && count($ids) > 0)
$this->response(null, null, "带有二级分类的分类ID:{$_POST['parent_id']},不能做为其它分类的子分类", 2);
}
/**
* 检测永久链接
*/
function _check_permalink()
{
$permalink = biz::str2pingyin($_POST['title']);
/*
if (accessor::get_term_by_permalink($permalink, $this->type))
$permalink .= '_1';
*/
return $permalink;
}
/**
* 上传缩略图
*/
function _upload_thumb($cid, $source = null)
{
if (!empty($_POST['image'])) {
Mterm::update(array('image' => $_POST['image']))
->where('id = ?', $cid)->query();
}
}
/**
* 保存附属信息
*/
function _sava_meta($cid)
{
biz::update_term_meta($cid, 'keywords', trim($_POST['keywords']));
biz::update_term_meta($cid, 'depiction', trim($_POST['depiction']));
if ($this->type != ENT_COMMENT) {
biz::category2cache();
if (isset($_POST['meta']))
biz::update_term_meta($cid, 'meta', $_POST['meta']);
}
}
/**
* 删除分类
*/
function _delete_category($c)
{
$cs = accessor::get_categories_by_parent($c['id']);
array_push($cs, $c);
if ($this->type == ENT_COMMENT) {
//
foreach ($cs as $c) {
Mcomment::update(array('category_id' => 0))->where('category_id = ?', $c['id'])->query();
Mterm::delete('id = ?', $c['id'])->query();
}
} else {
//
foreach ($cs as $c)
biz::delete_category($c, $this->type);
}
}
/**
* 分类列表
*/
function _assign_category($onlytop = false)
{
$this->assign('categories', accessor::get_categories($this->type2db, $onlytop));
}
/**
* 当前分类
*/
function _assign_this($c)
{
$ids = accessor::get_categories_by_parent($c['id'], true);
$c['has_sub'] = count($ids);
$c['keywords'] = accessor::get_term_meta($c['id'], 'keywords');
$c['depiction'] = accessor::get_term_meta($c['id'], 'depiction');
$this->assign('category', $c);
}
/**
* 分类使用表单列表
*/
function _assing_form($cid = 0)
{
if ($this->type == ENT_COMMENT)
return;
$dom = '';
$meta = accessor::get_term_meta($cid, 'meta', true);
if (is_array($meta['form']))
$lists = $meta['form']['list'];
if (empty($lists))
$lists = array();
$forms = accessor::get_forms('feedback');
foreach ($forms as $key => $form) {
$checked = in_array($form['id'], $lists) ? 'checked="checked"' : '';
$dom .= "<label for='meta[form][list][{$key}]'><input id='meta[form][list][{$key}]' name='meta[form][list][]' type='checkbox' {$checked} value='{$form['id']}' />{$form['title']}</label>";
}
if (empty($dom))
$dom = "<div style='line-height:20px;'>请先配置留言表单</div>";
$this->assign('forms', $dom);
}
}
?><file_sep><?php
/**
* RSS聚合Widget类
*/
class rss_widget implements iWidget
{
public static $name = "rss";
/**
*
*/
public static function admin_form($id = null, $title = null, $widget = null)
{
$url = isset($widget['url']) ? trim($widget['url']) : '';
$limit = isset($widget['limit']) ? intval($widget['limit']) : 5;
$length = isset($widget['length']) ? intval($widget['length']) : 70;
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label">RSS feed URL:</td>
<td>
<input id="inpUrl" name="widget[url]" type="text" class="text" value="<?php echo $url;?>" size="50" />
</td>
</tr>
<tr>
<td class="label">列表[字数]:</td>
<td>
<input id="inpLength" name="widget[length]" type="text" class="text" value="<?php echo $length;?>" size="5" maxlength="3" />
</td>
</tr>
<tr>
<td class="label">列表[个数]:</td>
<td>
<input id="inpLimit" name="widget[limit]" type="text" class="text" value="<?php echo $limit;?>" size="5" maxlength="2" />
</td>
</tr>
<script type="text/javascript">
$(document).ready(function($) {
$("#inpLength").numeric();
$("#inpLimit").numeric();
$("#inpLength").rules("add", {
required: true,
messages: {
required: "请输入列表[字数]"
}
});
$("#inpLimit").rules("add", {
required: true,
messages: {
required: "请输入列表[个数]"
}
});
$("#inpUrl").rules("add", {
required: true,
messages: {
required: "请输入URL地址"
}
});
});
</script>
<?php
appWidget::form_footer();
}
/**
*
*/
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$length = isset($widget['length']) ? intval($widget['length']) : 70;
$limit = isset($widget['limit']) ? intval($widget['limit']) : 5;
$url = isset($widget['url']) ? trim($widget['url']) : '';
if (!preg_match("/^http:\/\//i", $url)) return;
App::vendor('simplepie');
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->set_cache_location(SIMPLEPE_CACHE_DIR);
$feed->set_cache_duration(600);
$feed->init();
$feed->handle_content_type();
echo '<div class="content widget_rss"><ul>';
if (!$feed->error()) {
if ($feed->get_item_quantity() > 0) {
$i = 0;
foreach ($feed->get_items(0, $limit) as $item) {
$class = $i++ % 2 == 0 ? '' : 'gray';
echo "<li class='{$class}'><a href='{$item->get_link()}' target='_blank'>", lpString::substr($item->get_title(), $length), "</a></li>";
}
} else {
echo '<li>' . appView::__('No data') . '</li>';
}
} else {
echo '<li>FEED时发生错误</li>';
}
echo '</ul></div>';
}
}
?><file_sep><?php
/**
* 分类树
*/
class categories_widget implements iWidget
{
public static $name = "categories";
public static function admin_form($id = null, $title = null, $widget = null)
{
$is_count = isset($widget['is_count']) ? 'checked' : '';
$type = isset($widget['type']) ? trim($widget['type']) : '';
$display = isset($widget['display']) ? trim($widget['display']) : '';
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td class="label" style="width:280px;">分类类型:</td>
<td>
<select name="widget[type]">
<option value="article" <?php if ($type == ENT_ARTICLE) echo 'selected';?>>文章</option>
<option value="product" <?php if ($type == ENT_PRODUCT) echo 'selected';?>>产品</option>
</select>
</td>
</tr>
<tr>
<td class="label">列表[方式]:</td>
<td>
<select name="widget[display]">
<option value="list" <?php if ($display == 'list') echo 'selected';?>>逐标题</option>
<option value="thumb" <?php if ($display == 'thumb') echo 'selected';?>>缩略图</option>
<option value="select" <?php if ($display == 'select') echo 'selected';?>>下拉列表</option>
</select>
</td>
</tr>
<tr>
<td class="label">列表[选项]:</td>
<td>
<input id="widget[is_count<?php echo $id;?>]" name="widget[is_count]" <?php echo $is_count;?> type="checkbox" value="1" />
<label for="widget[is_count<?php echo $id;?>]">显示总数</label>
</td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
$is_count = isset($widget['is_count']);
$type = isset($widget['type']) ? trim($widget['type']) : '';
$display = isset($widget['display']) ? trim($widget['display']) : '';
if (empty($type))
return false;
$dom = "";
if (in_array($display, array('select', 'list', 'thumb'))) {
$func = "d_{$display}";
$categories = accessor::get_categories($type);
$params = array($categories, $type, $is_count);
$dom = call_user_func_array(array('categories_widget', $func), $params);
}
echo "<div class='content widget_categories'>{$dom}</div>";
}
/**
* 下拉列表
*/
static function d_select($categories, $type, $is_count = true)
{
$dom = "";
foreach ($categories as $c) {
$url = appUrl::category($type, $c['id']);
$count = isset($widget['is_count']) ? " ({$c['count']})" : '';
$dom .= '<option value="' . $url . '">' . $c['separator'] . $c['title'] . $count . '</option>';
}
$dom = <<< eof
<select id="categoryTree{$id}">{$dom}</select>
<script language="javascript">
$(document).ready(function($) {
$("#categoryTree{$id}").change(function() {
window.location.href = $(this).val();
});
});
</script>
eof;
return $dom;
}
/**
* UL列表
*/
static function d_list($categories, $type, $is_count = true)
{
$dom = "";
foreach ($categories as $c) {
$url = appUrl::category($type, $c['id']);
$count = $is_count ? " ({$c['count']})" : '';
$dom .= '<li class="c' . $c['level'] . '"><a href="' . $url . '">' . $c['title'] . '</a>' . $count . '</li>';
}
return "<ul>{$dom}</ul>";
}
/**
* 二级缩略图
*/
static function d_thumb($categories, $type, $is_count = true)
{
$dom = "";
foreach ($categories as $key => $c) {
if ($c['parent_id'] == 0)
unset($categories[$key]);
}
$num = -1;
$count = count($categories);
$domain = RES_URI;
foreach ($categories as $c) {
$num++;
$link = appUrl::category($type, $c['id']);
$class = $num % 3 == 2 ? 'last_cell' : '';
$count = $is_count ? " ({$c['count']})" : '';
if ($num % 3 == 0)
$dom .= '<div class="product_row clearfix">';
$dom .= '<div class="prd_cell ' . $class . '">';
$dom .= <<< eof
<div class="pic">
<a href="{$link}" title="{$c['title']}">
<img src="{$domain}category/{$c['image']}" alt="{$c['title']}" />
</a>
</div>
<div class="info">
<h3>
<a href="{$link}" title="{$c['title']}">
{$c['title']} {$count}
</a>
</h3>
</div>
eof;
$dom .= '</div>';
if ($num % 3 == 2 || $num == $count - 1)
$dom .= '</div>';
}
return $dom;
}
}
?><file_sep><?php
App::model('post');
class controller_link extends adminCtrl
{
/**
* 开始
*/
function action_index()
{
// 文章
$posts = Mpost::find()->field('id, title')->get_results();
foreach ($posts as $p) {
$permalink = biz::str2pingyin($p['title']);
pr($permalink . '|' . $p['title']);
Mpost::update(array('permalink' => $permalink))->where('id = ?', $p['id'])->query();
}
}
}
?><file_sep><?php
/**
* 数据模型逻辑
*
* @author <EMAIL>
*/
class Mbrand extends Model
{
/**
* 数据字段约束
*
* @var array
*/
public $validate = array(
'title' => array(
array('required', '名称不能为空'),
),
);
/* ------------------ 以下是自动生成的代码,不能修改 ------------------ */
/**
* 表名称
*
* @var string
*/
public $table = 'ws_brand';
/**
* 检索数据,此方法只有子类才有,只接调用Select对象中的Where方法
*/
public static function find()
{
$args = func_get_args();
return call_user_func_array(array(new Select('ws_brand'), 'where'), $args);
}
/**
* 删除数据
*/
public static function delete()
{
$args = func_get_args();
return parent::delete(__CLASS__, $args);
}
/**
* 添加数据
*/
public static function insert($data)
{
return parent::insert(__CLASS__, $data);
}
/**
* 更新数据
*/
public static function update($data)
{
return parent::update(__CLASS__, $data);
}
/**
* 取出数据验证时的非法数据
*/
public static function illegaldata()
{
return parent::illegaldata(__CLASS__);
}
/* ------------------ 以上是自动生成的代码,不能修改 ------------------ */
}
?><file_sep><?php
App::model('form');
class controller_tree extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "分类节点";
public $type = 'tree';
/**
* 分类节点列表
*/
function action_list()
{
$this->assign('trees', accessor::get_forms($this->type));
$this->display($this->is_list() ? 'tree_list_div' : 'tree_list');
}
/**
* 添加分类节点
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$params = array('type' => $this->type, 'title' => trim($_POST['title']));
Mform::insert($params);
$this->response(null, '添加', $_POST['title'], 0, array('admin_tree', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_tree', 'add'));
$this->display('tree_add');
}
/**
* 修改分类节点
*/
function action_update()
{
if ($tree = accessor::get_form($_GET['tree_id'], $this->type)) {
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => trim($_POST['title']));
Mform::update($params)
->where('id = ?', $tree['id'])->query();
$this->response(null, '编辑', $tree['title'], 0, array('admin_tree', 'list'));
}
$this->assign('tree', $tree);
$this->assign('action', lpUrl::clean_url('admin_tree', 'update', array('tree_id' => $_GET['tree_id'])));
$this->display('tree_add');
}
}
/**
* 删除分类节点
*/
function action_ajax()
{
if ($this->is_ajax() && $tree = accessor::get_form($_POST['id'], $this->type)) {
switch ($_POST['action']) {
case 'remove':
/* 删除目录树内容(危险) */
$type = ENT_ARTICLE;
$cs = accessor::get_terms(ENT_CATEGORY, $type . $tree['id']);
foreach ($cs as $c)
biz::delete_category($c, $type);
/**/
Mform::delete('id = ?', $tree['id'])->query();
$this->response(null, '删除', $tree['title']);
break;
}
}
}
///// 私有方法 /////
/**
* 检测分类名称
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "分类节点名称不能为空", 2);
}
}
?><file_sep><{include file="_header.html"}>
<script type="text/javascript">
$(document).ready(function($) {
$(".list-div").listTable({
oprateUrl: "<{url c=admin_advert a=ajax}>",
fetchUrl: "<{url c=admin_advert a=list}>",
searchForm: "#searchForm"
});
});
</script>
<div class="header-div">
<div class="location">
当前位置:附件列表 > <span class="cur">广告列表</span>
</div>
</div>
<div class="header-div">
<a class="pop icadd" title="添加广告" url="<{url c=admin_advert a=add}>">
<div class="in"><div class="mid"><div>添加广告</div></div></div>
</a>
</div>
<div class="list-div"><{include file="advert_list_div.html"}></div>
<{include file="_footer.html"}><file_sep><?php
App::model('field', 'form', 'post_meta');
class controller_field extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "字段";
public $form_id;
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->form_id = isset($_GET['form_id']) ?
intval($_GET['form_id']) :
intval($_POST['form_id']);
}
/**
* 字段列表
*/
function action_list()
{
if ($form = accessor::get_form($this->form_id)) {
$this->assign('form_id', $this->form_id);
$this->assign('name', ($form['type'] == 'type' ? '产品类型|' : '留言表单|') . $form['title']);
$this->assign('location', $form['type'] == 'type' ? '产品模块' : '附件列表');
$this->assign('fields', accessor::get_fields($this->form_id, true)->get_results());
$this->display($this->is_list() ? 'field_list_div' : 'field_list');
}
}
/**
* 添加字段
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_relationship();
$fields = explode("\n", $_POST['items']);
$constraint = $_POST['constraint'];
if (!isset($constraint['requried'])) $constraint['requried'] = 0;
if (!isset($constraint['multiple'])) $constraint['multiple'] = 0;
$params = array('form_id' => $this->form_id, 'title' => trim($_POST['title']), 'depiction' => $_POST['depiction'], 'style' => $_POST['style'], 'items' => serialize($fields), 'constraint' => serialize($constraint));
$field_id = Mfield::insert($params);
if ($field_id)
biz::update_count_form($this->form_id, true);
$this->response(null, '添加', $_POST['title'], 0, array('admin_field', 'list', array('form_id' => $this->form_id)));
}
$this->assign('action', lpUrl::clean_url('admin_field', 'add', array('form_id' => $this->form_id)));
$this->display('field_add');
}
/**
* 编辑字段
*/
function action_update()
{
if ($field = accessor::get_field($_GET['field_id'])) {
if ($this->is_post()) {
$fields = explode("\n", $_POST['items']);
$constraint = $_POST['constraint'];
if (!isset($constraint['requried'])) $constraint['requried'] = 0;
if (!isset($constraint['multiple'])) $constraint['multiple'] = 0;
$params = array('title' => trim($_POST['title']), 'depiction' => $_POST['depiction'], 'style' => $_POST['style'], 'items' => serialize($fields), 'constraint' => serialize($constraint));
Mfield::update($params)
->where('id = ?', $_GET['field_id'])->query();
$this->response(null, null, $field['title'], 0, array('admin_field', 'list', array('form_id' => $field['form_id'])));
}
$field['constraint'] = unserialize($field['constraint']);
$field['items'] = implode("\n", unserialize($field['items']));
$this->assign('field', $field);
$this->assign('action', lpUrl::clean_url('admin_field', 'update', array('field_id' => $_GET['field_id'])));
$this->display('field_add');
}
}
/**
* 移动位置
*/
function action_postion()
{
if ($this->is_ajax()) {
$sort = 1;
$count = count($_POST['field']);
for ($i = $count; $i > 0; $i--) {
$id = $_POST['field'][$i - 1];
Mfield::update(array('sort' => $sort++))
->where('id = ?', $id)->query();
}
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $field = accessor::get_field($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
biz::update_count_form($field['form_id'], false);
Mpost_meta::delete('type_id = ? AND mate_key = ?', $field['form_id'], $field['id']);
Mfield::delete('id = ?', $field['id'])->query();
break;
case 'edit':
$this->edit('Mfield', 'sort');
break;
}
$this->response(null, $operate, $field['title']);
}
}
///// 私有方法 /////
/**
* 检测所属类型是否存在
*/
function _check_relationship()
{
if (!accessor::get_form($this->form_id))
$this->response(null, '添加', "表单ID:{$this->form_id},不存在", 2);
}
}
?><file_sep><?php
App::model('nav', 'post', 'term');
class controller_nav extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "导航";
/**
* 导航列表
*/
function action_list()
{
$hits = $firsts = array();
$postion = strlen($_POST['postion']) == 1 ? intval($_POST['postion']) : 0;
$navs = accessor::get_navs($postion);
foreach ($navs as $key => $nav) {
$url = biz::get_nav_url($nav['object_id'], $nav['type'], $nav['url']);
$navs[$key]['url'] = $url;
$navs[$key]['level'] = 1;
$navs[$key]['separator'] = '|-- ';
if ($nav['parent_id'] == 0) {
$hits[$nav['id']] = 0;
$firsts[$nav['id']] = $key;
} else {
unset($navs[$key]);
$hits[$nav['parent_id']]++;
$offset = $firsts[$nav['parent_id']] + $hits[$nav['parent_id']];
foreach ($firsts as $k => $v) {
if ($v >= $offset)
$firsts[$k]++;
}
$nav['url'] = $url;
$nav['level'] = 2;
$nav['separator'] = str_repeat('|-- ', 2);
array_splice($navs, $offset, 0, array($nav));
}
}
$this->assign('navs', $navs);
$this->display($this->is_list() ? 'nav_list_div' : 'nav_list');
}
/**
* 添加导航
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$this->_check_url();
$params = array('is_show' => 1, 'is_blank' => 0, 'type' => 'normal', 'title' => $_POST['title'], 'url' => $_POST['url'], 'postion' => $_POST['postion'], 'parent_id' => $_POST['parent_id']);
Mnav::insert($params);
$this->response(null, '添加', $_POST['title'], 0, array('admin_nav', 'list'));
}
$this->assign('navs', accessor::get_navs_by_parent(0, 0));
$this->assign('action', lpUrl::clean_url('admin_nav', 'add'));
$this->display('nav_add');
}
/**
* 编辑导航
*/
function action_update()
{
if ($nav = accessor::get_nav($_GET['nav_id'])) {
if ($this->is_post()) {
$this->_check_title();
$this->_check_url($nav['type']);
$this->_check_relationship($nav['id']);
$params = array('title' => $_POST['title'], 'url' => $_POST['url'], 'postion' => $_POST['postion'], 'parent_id' => $_POST['parent_id']);
Mnav::update($params)
->where('id = ?', $nav['id'])->query();
$this->response(null, '编辑', $nav['title'], 0, array('admin_nav', 'list'));
}
$nav['has_sub'] = accessor::get_navs_by_parent($nav['id'], -1, true);
$nav['url'] = biz::get_nav_url($nav['object_id'], $nav['type'], $nav['url']);
$this->assign('nav', $nav);
$this->assign('navs', accessor::get_navs_by_parent(0, 0));
$this->assign('action', lpUrl::clean_url('admin_nav', 'update', array('nav_id' => $nav['id'])));
$this->display('nav_add');
}
}
/**
* 移动位置
*/
function action_postion()
{
if ($this->is_ajax()) {
$sort = 1;
$count = count($_POST['nav']);
for ($i = $count; $i > 0; $i--) {
$id = $_POST['nav'][$i - 1];
Mnav::update(array('sort' => $sort++))
->where('id = ?', $id)->query();
}
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $nav = accessor::get_nav($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
$navs = accessor::get_navs_by_parent($nav['id']);
array_push($navs, $nav);
foreach ($navs as $nav) {
Mnav::delete('id = ?', $nav['id'])->query();
biz::nav2synchronize($nav['object_id'], $nav['type'], 0);
}
break;
case 'edit':
$this->edit('Mnav', 'sort');
break;
case 'toggle':
if ($this->toggle('Mnav', 'is_blank', 'is_show') && $_POST['field'] == 'is_show')
biz::nav2synchronize($nav['object_id'], $nav['type'], $_POST['state']);
break;
}
$this->response(null, $operate, $nav['title']);
}
}
///// 私有方法 /////
/**
* 检测导航名称
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, '导航名称为空', 2);
}
/**
* 检测导航
*/
function _check_url($type = 'normal')
{
if ($type == 'normal')
$_POST['url'] = isset($_POST['url']) ? trim($_POST['url']) : ' ';
else
$_POST['url'] = ' ';
}
/**
* 检测子导航是否存在
*/
function _check_relationship($id = 0)
{
$_POST['postion'] = intval($_POST['postion']);
if (isset($_POST['parent_id']) && $_POST['postion'] == 0) {
$_POST['parent_id'] = intval($_POST['parent_id']);
if ($_POST['parent_id'] && !accessor::get_nav($_POST['parent_id']))
$this->response(null, null, "{$_POST['parent_id']}上级导航ID不存在", 2);
if ($_POST['parent_id'] && accessor::get_navs_by_parent($id, -1, true))
$this->response(null, null, "带有子导航的导航不能做为其它导航的子导航", 2);
} else {
$_POST['parent_id'] = 0;
}
}
}
?><file_sep><?php
/**
* 前端控制器基类
*/
class frontCtrl extends appCtrl
{
/**
* 构造函数
*
* // 在控制器基类构造前初始化参数
*/
function __construct()
{
$app_options = array();
$options = accessor::get_option('theme', 'template');
if (isset($options['caching'])) {
$caching = intval($options['caching']);
if ($caching == 1 && isset($options['expired'])) {
if ($expired = intval($options['expired'])) {
$options = array('template' => array('caching' => $caching, 'expired' => $expired));
App::load_options($options);
}
}
}
parent::__construct();
frontView::init();
}
/**
* 页面标题
*/
function assign_title($title = null)
{
$company = accessor::get_option('site', 'company');
if (!empty($company))
$title .= ' - ' . $company;
$this->assign('title', $title);
}
/**
* 页面主体标题
*/
function assign_location($location = null)
{
$str = appView::__("Current Position:");
$location = "<div class='com_title'><div class='com_title_in'><div class='com_title_inner'><h2>{$str} {$location}</h2></div></div></div>";
$this->assign('location', $location);
}
/**
* 跳转到404页面
*/
function goto_404()
{
$str = appView::__("Pages not found");
$this->assign_location($str);
$this->display('404');
return true;
}
}
/**
* 视图层逻辑
*/
class frontView
{
/**
* Smarty - 初始化
*/
static function init()
{
App::view()->register_function('nav', array('frontView', 'func_nav_list'));
App::view()->register_function('layout', array('frontView', 'func_site_layout'));
App::view()->register_function('widget', array('frontView', 'func_widget_list'));
App::view()->register_function('revert', array('frontView', 'func_revert_list'));
App::view()->register_function('title', array('frontView', 'func_post_title'));
App::view()->register_function('seo_keywords', array('frontView', 'func_keywords'));
App::view()->register_function('seo_description', array('frontView', 'func_description'));
App::view()->register_function('comment_form', array('frontView', 'func_comment_form'));
App::view()->register_function('category_posts', array('frontView', 'func_category_posts'));
}
/**
* Smarty - 站点页面结构
*/
static function func_site_layout($params)
{
$layout = 1;
if (is_array($params)) {
extract($params);
if (!isset($layout) || empty($layout)) {
$layout = accessor::get_option('theme', 'layout');
if (!$layout = intval($layout))
$layout = 1;
}
}
return '<link href="' . DOMAIN . 'css/layout' . $layout . '.css" rel="stylesheet" type="text/css" />';
}
/**
* Smarty - 标题修饰
*/
static function func_nav_list($params)
{
if (is_array($params)) {
extract($params);
$firsts = array();
$navs = accessor::get_navs($postion);
foreach ($navs as $key => $nav) {
$navs[$key]['url'] = biz::get_nav_url($nav['object_id'], $nav['type'], $nav['url']);
$navs[$key]['target'] = $nav['is_blank'] ? '_blank' : '_self';
if ($nav['parent_id'] == 0) {
$firsts[$nav['id']] = $key;
$navs[$key]['sub'] = array();
} else {
$p_key = $firsts[$nav['parent_id']];
$navs[$p_key]['sub'][] = $navs[$key];
unset($navs[$key]);
}
}
$dom = '';
if ($postion == 1) {
foreach ($navs as $nav)
$dom .= " | <a href='{$nav['url']}' target='{$nav['target']}'>" . htmlspecialchars($nav['title']) . "</a>";
} else {
foreach ($navs as $nav) {
$dom .= '<li class="liImg"></li>';
$dom .= "<li><a href='{$nav['url']}' target='{$nav['target']}'>" . htmlspecialchars($nav['title']) . "</a>";
if (count($nav['sub']) > 0) {
$dom .= '<div class="submenu">';
foreach ($nav['sub'] as $sub)
$dom .= "<a href='{$sub['url']}' target='{$sub['target']}'>" . htmlspecialchars($sub['title']) . "</a>";
$dom .= '</div>';
}
$dom .= '</li>';
}
}
return $dom;
}
return null;
}
/**
* Smarty - 某个分类下的所有产品
*/
static function func_category_posts($params)
{
if (is_array($params)) {
extract($params);
if (isset($category_id) && !empty($category_id)) {
$dom = '';
$posts = accessor::get_posts_by_term($category_id)->get_results();
if (count($posts) < 2) return $dom;
$www = RES_URI . 'post/thumb/';
foreach ($posts as $post) {
$url = appUrl::post(ENT_PRODUCT, $post['id']);
$dom .= "<li><a href='$url'><img src='{$www}{$post['image']}' title='" . htmlspecialchars($post['title']) . "' /></a>";
}
return $dom;
}
}
return null;
}
/**
* Smarty - 标题修饰
*/
static function func_post_title($params)
{
if (is_array($params)) {
extract($params);
if (empty($length))
$length = 21;
$title = lpString::substr($post['title'], $length);
if (!empty($post['font'])) {
$font = unserialize($post['font']);
$tag = $font['style'];
if (empty($tag)) $tag = 'font';
$title = "<{$tag} style='color: {$font['color']};'>{$title}</{$tag}>";
}
return "<a href='" .
appUrl::post(ENT_ARTICLE, $post['id'], $post['category_id'], $post['permalink']) .
"'>{$title}</a>";
}
return null;
}
/**
* Smarty - 问题回复
*/
static function func_revert_list($params)
{
if (is_array($params)) {
extract($params);
$dom = '<div class="revert">回复内容:';
if ($reverts = accessor::get_comments($comment_id)) {
foreach ($reverts as $revert)
$dom .= "{$revert['content']} [" . date("Y-m-d H:i:s", $revert['add_time']) . "]";
return $dom . '</div>';
}
}
return null;
}
/**
* Smarty - Widget
*/
static function func_widget_list($params)
{
if (is_array($params)) {
extract($params);
$dom = '';
if (!isset($page_id)) $page_id = 0;
foreach (accessor::get_widgets($postion, $page_id) as $widget) {
$class = "{$widget['type']}_widget";
if (class_exists($class)) {
$value = $widget['value'];
if ($widget['type'] != 'rich')
$value = unserialize($value);
$params = array($postion, $widget['id'], trim($widget['title']), $value);
ob_start();
call_user_func_array(array($class, 'html'), $params);
$dom .= ob_get_contents();
ob_end_clean();
}
}
return empty($dom) ? ' ' : $dom;
}
return null;
}
/**
* Smarty - SEO/关键字
*/
static function func_keywords($params)
{
if (is_array($params)) {
return accessor::get_option('seo', 'keywords');
}
return null;
}
/**
* Smarty - SEO/描述
*/
static function func_description($params)
{
if (is_array($params)) {
return accessor::get_option('seo', 'description');
}
return null;
}
/**
* Smarty - 评论表单
*/
static function func_comment_form($params)
{
if (isset($params['list']) && is_array($params['list']) && count($params['list']) > 0)
$list = $params['list'];
else
return null;
$form_dom = $script_dom = '';
foreach ($list as $type_id) {
$date_inputs = array();
$type = accessor::get_keyword($type_id, 'feedback');
$fields = accessor::get_fields($type_id);
if (count($fields) > 0) {
$meta = unserialize($type['meta']);
$direction = $count = 0;
if (is_array($meta)) {
$direction = $meta['direction'];
$count = $meta['count'];
}
$dom = $th = $td = '';
$size = empty($direction) ? 25 : 10;
foreach ($fields as $key => $item) {
$class = array();
$constraint = unserialize($item['constraint']);
if (is_array($constraint)) {
if (!empty($constraint['requried'])) $class[] = 'required';
if (!empty($constraint['format'])) $class[] = $constraint['format'];
}
$input = "";
$is_date = in_array('date', $class);
$name = "form[{$type_id}][values][{$key}]";
$class = implode(' ', $class);
$key_info = "<input type='hidden' name='form[{$type_id}][keys][{$key}]' value='{$item['title']}' />";
switch ($item['style']) {
case 1:
if ($is_date) {
$id = "{$type_id}_{$key}";
$date_inputs[] = $id;
$input .= "<input id='f_date_{$id}' name='{$name}' class='text {$class}' readonly type='text' size='{$size}' />";
$input .= " <img align='absmiddle' id='f_btn_{$id}' src='" . DOMAIN . "/images/calendar.gif' />";
} else {
$input .= "<input name='{$name}' class='text {$class}' type='text' size='{$size}' />";
}
break;
case 2:
$options = unserialize($item['items']);
if (is_array($options)) {
$type_input = empty($constraint['multiple']) ? 'radio' : 'checkbox';
foreach ($options as $k => $val) {
$validate = $k == 0 ? "class='{$class}'" : '';
$input .= " <input name='{$name}[]' {$validate} type='{$type_input}' value='{$val}' /> <label>{$val}</label>";
}
}
break;
case 3:
$input .= "<textarea name='{$name}' rows='5' class='text {$class}'></textarea>";
break;
}
if (empty($direction)) {
$depiction = trim($item['depiction']);
$depiction = empty($depiction) ? '' : "<div class='depiction'>[ {$depiction} ]</div>";
$dom .= "<tr><td class='label'>{$key_info}{$item['title']}:</td><td>{$input} {$depiction}</td></tr>";
} else {
$th .= "<th>{$key_info}{$item['title']}</th>";
$td .= "<td align='center'>{$input}</td>";
}
}
$form_dom .= "<h3>{$type['title']}</h3>
<input type='hidden' name='form[{$type_id}][postion]' value='{$direction}' />
<input type='hidden' name='form[{$type_id}][title]' value='{$type['title']}' />";
if (empty($direction)) {
$form_dom .= "<table width='100%' border='0' cellspacing='0' cellpadding='0'>
{$dom}</table>";
} else {
$tr = '';
$array = array();
$pattern = "/(name=\'form\[\d+\]\[values\]\[\d+\])((\[\])?\')/";
if (empty($count)) $count = 1;
for ($i = 0; $i < $count; $i++) {
$replacement = "\${1}[{$i}]\${2}";
$temp = preg_replace($pattern, $replacement, $td);
foreach ($date_inputs as $id) {
$array[] = "{$id}_{$i}";
$temp = str_replace("f_btn_{$id}", "f_btn_{$id}_{$i}", $temp);
$temp = str_replace("f_date_{$id}", "f_date_{$id}_{$i}", $temp);
}
$tr .= "<tr>{$temp}</tr>";
}
$date_inputs = $array;
$form_dom .= "<table width='100%' border='0' cellspacing='0' cellpadding='0'>
<tr>{$th}</tr>{$tr}</table>";
}
foreach ($date_inputs as $id)
$script_dom .= "cal.manageFields(\"f_btn_{$id}\", \"f_date_{$id}\", \"%Y/%m/%d\");\r\n";
}
}
$url = DOMAIN;
$seccode = lpUrl::clean_url('index', 'seccode');
if ($script_dom) {
$date_dom =<<< eof
<script src="{$url}javascript/JSCal2-1.7/src/js/jscal2.js"></script>
<script src="{$url}javascript/JSCal2-1.7/src/js/lang/cn.js"></script>
<link rel="stylesheet" type="text/css" href="{$url}javascript/JSCal2-1.7/src/css/jscal2.css" />
<link rel="stylesheet" type="text/css" href="{$url}javascript/JSCal2-1.7/src/css/steel/steel.css" />
<script type="text/javascript">//<![CDATA[
var cal = Calendar.setup({
onSelect: function(cal) { cal.hide() }
});
{$script_dom}
//]]></script>
eof;
}
$s1 = appView::__('Authentication information');
$s2 = appView::__('Identifying code:');
$s3 = appView::__('Submit');
$s4 = appView::__('Processing');
return <<< eof
<form method="post" id="commentForm" action="">
{$form_dom}
<h3>{$s1}</h3>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class='label'>{$s2}</td>
<td>
<input class="text required" type="text" name="seccode" size="25" />
<img align="absmiddle" src="{$seccode}" id="ssecodeImg" />
</td>
</tr>
<tr>
<td class='label'> </td>
<td>
<input type="submit" class="button" value="{$s3}" name="submit"/>
<div id="commentLoad" style="display: none; zoom: 1; margin: 0 5px;"><img src="{$url}images/loading2.gif" align="absmiddle" /> {$s4} ...</div>
</td>
</tr>
</table>
</form>
{$date_dom}
eof;
}
}
?><file_sep><?php
/**
* 数据模型逻辑
*
* @author <EMAIL>
*/
class Madmin extends Model
{
/**
* 数据字段约束
*
* @var array
*/
public $validate = array(
'username' => array(
array('required', '帐号不能为空'),
),
'password' => array(
array('required', '密码不能为空'),
),
'group' => array(
array('int', '组必须是一个整数'),
),
'permission' => array(
array('int', '权限值必须是一个整数'),
),
'add_time' => array(
array('int', '注册时间(时间戳)必须是一个整数'),
),
'last_time' => array(
array('int', '上次登录时间(时间戳)必须是一个整数'),
),
'state' => array(
array('int', '状态(0:删除,1:正常)必须是一个整数'),
),
);
/* ------------------ 以下是自动生成的代码,不能修改 ------------------ */
/**
* 表名称
*
* @var string
*/
public $table = 'ws_admin';
/**
* 检索数据,此方法只有子类才有,只接调用Select对象中的Where方法
*/
public static function find()
{
$args = func_get_args();
return call_user_func_array(array(new Select('ws_admin'), 'where'), $args);
}
/**
* 删除数据
*/
public static function delete()
{
$args = func_get_args();
return parent::delete(__CLASS__, $args);
}
/**
* 添加数据
*/
public static function insert($data)
{
return parent::insert(__CLASS__, $data);
}
/**
* 更新数据
*/
public static function update($data)
{
return parent::update(__CLASS__, $data);
}
/**
* 取出数据验证时的非法数据
*/
public static function illegaldata()
{
return parent::illegaldata(__CLASS__);
}
/* ------------------ 以上是自动生成的代码,不能修改 ------------------ */
}
?><file_sep><?php
App::model('post');
class controller_advert extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "广告";
/**
* 广告列表
*/
function action_list()
{
$this->assign_object('adverts', accessor::get_adverts(true));
$this->display($this->is_list() ? 'advert_list_div' : 'advert_list');
}
/**
* 添加广告
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$params = array('type' => 'advert', 'add_time' => time(), 'title' => $_POST['title'], 'image' => $_POST['image'], 'keywords' => trim($_POST['keywords']), 'summary' => trim($_POST['summary']));
$advert_id = Mpost::insert($params);
if ($advert_id)
biz::update_post_meta($advert_id, 'url', trim($_POST['url']));
$this->response(null, '添加', $_POST['title'], 0, array('admin_advert', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_advert', 'add'));
$this->display('advert_add');
}
/**
* 编辑广告
*/
function action_update()
{
if ($advert = accessor::get_advert($_GET['advert_id'])) {
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => $_POST['title'], 'image' => $_POST['image'], 'keywords' => trim($_POST['keywords']), 'summary' => trim($_POST['summary']));
$flag = Mpost::update($params)->where('id = ?', $_GET['advert_id'])->query();
if ($flag)
biz::update_post_meta($_GET['advert_id'], 'url', trim($_POST['url']));
$this->response(null, '编辑', $advert['title'], 0, array('admin_advert', 'list'));
}
$advert['url'] = accessor::get_post_meta($_GET['advert_id'], 'url');
$this->assign('advert', $advert);
$this->assign('action', lpUrl::clean_url('admin_advert', 'update', array('advert_id' => $_GET['advert_id'])));
$this->display('advert_add');
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $advert = accessor::get_advert($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
Mpost::delete('id = ?', $_POST['id'])->query();
lpFile::unlink(RES_DIR . "advertisement/{$advert['image']}");
break;
case 'edit':
$this->edit('Mpost', 'sort');
break;
}
$this->response(null, $operate, $advert['title']);
}
}
///// 私有方法 /////
/**
* 检测标题
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "标题不能为空", 2);
$image = trim($_POST['image']);
if (!empty($_POST['image']))
$_POST['image'] = substr($image, strpos($image, 'fckeditor') + 10);
}
}
?><file_sep><?php
require_once('simplepie.inc');
$url = "http://www.trip4business.com/bbs/rss.php?fid=2&auth=0";
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->set_cache_location('./');
$feed->set_cache_duration(60);
$feed->init();
$feed->handle_content_type();
if (!$feed->error()) {
foreach ($feed->get_items() as $item) {
pr(
array(
'title' => $item->get_title(),
'link' => $item->get_link()
)
);
}
}
function pr($param)
{
echo "<pre>";
print_r($param);
echo "</pre>";
}
?><file_sep>/*!
* jQuery JavaScript 扩展
*/
(function($) {
/**
* 文本档限制只能输入数字
*/
jQuery.fn.numeric = function(callback) {
callback = typeof callback == "function" ? callback : function(){};
$(this).css("ime-mode", "disabled");
this.bind("keypress",function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 8) {
return true;
}
if (key == 46) {
//if (this.value.indexOf(".") != -1) {
return false;
//}
} else {
return key >= 46 && key <= 57;
}
});
this.bind("blur", function() {
callback.apply(this);
});
this.bind("paste", function() {
var s = clipboardData.getData('text');
if (!/\D/.test(s));
value = s.replace(/^0*/, '');
return false;
});
this.bind("dragenter", function() {
return false;
});
this.bind("keyup", function() {
if (/(^0+)/.test(this.value)) {
this.value = this.value.replace(/^0*/, '');
}
});
}
/**
* COOKIE操作
*/
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(value)),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
/**
* IE6下弹出层的遮罩
*/
$.fn.bgIframe = $.fn.bgiframe = function(s) {
// This is only for IE6
if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
s = $.extend({
top : 'auto', // auto == .currentStyle.borderTopWidth
left : 'auto', // auto == .currentStyle.borderLeftWidth
width : 'auto', // auto == offsetWidth
height : 'auto', // auto == offsetHeight
opacity : true,
src : 'javascript:false;'
}, s || {});
var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;'+
(s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
'"/>';
return this.each(function() {
if ( $('> iframe.bgiframe', this).length == 0 )
this.insertBefore( document.createElement(html), this.firstChild );
});
}
return this;
};
$.extend({
/**
* 取得页面的长宽
*/
getPageSize: function() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight) {
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else {
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) {
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) {
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
},
/**
* 取得页面的偏移量
*/
getPageScroll: function() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
arrayPageScroll = new Array(xScroll,yScroll)
return arrayPageScroll;
}
});
})(jQuery);<file_sep><?php
App::model('term', 'post_relationship');
class controller_tag extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "";
/**
* 分类类型列表
*/
public static $keys = array(ENT_ARTICLE => '文章', ENT_PRODUCT => '产品');
public $type;
/**
* 构造函数
*/
function __construct()
{
parent::__construct();
$this->type = isset($_GET['type']) ? strtolower($_GET['type']) : null;
if (in_array($this->type, array_keys(self::$keys))) {
$name = self::$keys[$this->type];
$this->module = "{$name}标签";
$this->assign('type', $this->type);
$this->assign('name', $name);
} else {
biz::header_404();
}
}
/**
* 标签列表
*/
function action_list()
{
$tags = accessor::get_tags($this->type, true, $_POST['title']);
$this->sort_by($tags, 'count');
$this->assign_object('tags', $tags, 15);
$this->display($this->is_list() ? 'tag_list_div' : 'tag_list');
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $tag = accessor::get_term($_POST['id'])) {
switch ($_POST['action']) {
case 'remove':
biz::delete_tag($tag['id']);
$this->response(null, '删除', $tag['title']);
break;
}
}
}
/**
* 批量数据操作
*/
function action_batch()
{
$ids = $_POST['ids'];
if ($this->is_ajax() && is_array($ids)) {
switch ($_POST['action']) {
case 'remove':
foreach ($ids as $id)
biz::delete_tag($id);
$this->response(null, '批量删除', implode(',', $ids));
break;
}
}
}
}
?><file_sep><?php
require("fckeditor/fckeditor.php");
class richeditor extends FCKeditor
{
public function __construct($instanceName)
{
parent::__construct($instanceName);
$basedir = dirname($_SERVER['PHP_SELF']);
if (substr($basedir, strlen($basedir) - 1) != '/')
$basedir .= '/';
$this->BasePath = $basedir . 'APP/vendors/fckeditor/';
$this->Config['SkinPath'] = $this->BasePath . 'editor/skins/silver/';
$this->ToolbarSet = 'Lxsphp';
$this->Height = 400;
}
}
?><file_sep>/**
* 刷新验证码
*/
function refreshImg() {
$("#ssecodeImg").attr("src", urlSsecode + "?" + Math.random());
}
/**
* 处理返回数据
*/
function showSubmitResponse(responseText, statusText) {
var code = $("code", responseText).text();
var message = $("message", responseText).text();
alert(message);
refreshImg();
$("#commentLoad").hide();
$("#commentForm").resetForm();
$("input[type='submit']").attr("disabled", false);
}
/**
* 提交表单
*/
$.validator.setDefaults({
submitHandler: function(form) {
$("input[type='submit']").attr("disabled", true);
$("#commentLoad").css("display", "inline");
$("#" + form.id).ajaxSubmit({
dataType: "xml",
url: urlSubmit,
success: showSubmitResponse
});
},
errorPlacement: function(error, element) {
error.appendTo(element.parent("p"));
},
errorElement: "span"
});
/**
* 数据验证
*/
$(document).ready(function($) {
$("#commentForm").validate({
rules: {
email: {
required: true,
email: true
},
content: "required",
seccode: "required"
},
messages: {
email: {
required: "请填写E-mail地址",
email: "请填写合法E-MAIL地址"
},
content: "请填写内容",
seccode: "请填写验证码"
}
});
$("#ssecodeImg")
.css("cursor", "pointer")
.attr("title", "看不清?点击更换另一个验证码。")
.click(function() {
refreshImg();
});
});<file_sep><?php
/**
* 富文本框Widget类
*/
class rich_widget implements iWidget
{
public static $name = "rich";
public static function admin_form($id = null, $title = null, $widget = null)
{
App::vendor('fckeditor');
$richeditor = new richeditor('FCKeditor1');
$richeditor->ToolbarSet = 'Normal';
$richeditor->Value = $widget;
appWidget::form_header(self::$name, $id, $title);
?>
<tr>
<td colspan="2"><?php echo $richeditor->CreateHtml();?></td>
</tr>
<?php
appWidget::form_footer();
}
public static function html($postion = null, $id = null, $title = null, $widget = null)
{
appWidget::title($title);
//// 内容
echo '<div class="content widget_rich">', $widget , '</div>';
}
}
?><file_sep><?php
App::model('brand', 'post');
class controller_brand extends adminCtrl
{
/**
* 模块名称
*
* @var string
*/
public $module = "产品品牌";
/**
* 产品品牌列表
*/
function action_list()
{
$this->assign_object('brands', accessor::get_brands(true));
$this->display($this->is_list() ? 'brand_list_div' : 'brand_list');
}
/**
* 添加产品品牌
*/
function action_add()
{
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => $_POST['title'], 'siteurl' => trim($_POST['url']), 'depiction' => trim($_POST['depiction']));
$brand_id = Mbrand::insert($params);
if ($brand_id)
$this->_upload_thumb($brand_id);
$this->response(null, '添加', $_POST['title'], 0, array('admin_brand', 'list'));
}
$this->assign('action', lpUrl::clean_url('admin_brand', 'add'));
$this->display('brand_add');
}
/**
* 编辑产品品牌
*/
function action_update()
{
if ($brand = accessor::get_brand($_GET['brand_id'])) {
if ($this->is_post()) {
$this->_check_title();
$params = array('title' => $_POST['title'], 'siteurl' => trim($_POST['url']), 'depiction' => trim($_POST['depiction']));
$flag = Mbrand::update($params)
->where('id = ?', $_GET['brand_id'])->query();
if ($flag)
$this->_upload_thumb($_GET['brand_id'], $brand['logo']);
$this->response(null, '编辑', $brand['title'], 0, array('admin_brand', 'list'));
}
$this->assign('brand', $brand);
$this->assign('action', lpUrl::clean_url('admin_brand', 'update', array('brand_id' => $_GET['brand_id'])));
$this->display('brand_add');
}
}
/**
* 数据操作
*/
function action_ajax()
{
if ($this->is_ajax() && $brand = accessor::get_brand($_POST['id'])) {
$operate = '编辑';
switch ($_POST['action']) {
case 'remove':
$operate = '删除';
Mbrand::delete('id = ?', $_POST['id'])->query();
Mpost::update(array('brand_id' => 0))->where('brand_id = ?', $_POST['id'])->query();
lpFile::unlink(RES_DIR . "brand/{$brand['logo']}");
break;
}
$this->response(null, $operate, $brand['title']);
}
}
///// 私有方法 /////
/**
* 上传缩略图
*/
function _upload_thumb($brand_id, $source = null)
{
if (!empty($_POST['image'])) {
Mbrand::update(array('logo' => $_POST['image']))
->where('id = ?', $brand_id)->query();
}
/*
$size = accessor::get_option('thumb', 'brand');
if ($image = uploader::thumb('brand', $size, $source)) {
Mbrand::update(array('logo' => $image))
->where('id = ?', $brand_id)->query();
}*/
}
/**
* 验证标题
*/
function _check_title()
{
$_POST['title'] = trim($_POST['title']);
if (empty($_POST['title']))
$this->response(null, null, "品牌名称不能为空", 2);
}
}
?><file_sep><?php
/**
* 数据模型逻辑
*
* @author <EMAIL>
*/
class Mterm_meta extends Model
{
/**
* 数据字段约束
*
* @var array
*/
public $validate = array(
'term_id' => array(
array('required', '纬度ID不能为空'),
array('int', '纬度ID必须是一个整数'),
),
'mate_key' => array(
array('required', '键不能为空'),
),
);
/* ------------------ 以下是自动生成的代码,不能修改 ------------------ */
/**
* 表名称
*
* @var string
*/
public $table = 'ws_term_meta';
/**
* 检索数据,此方法只有子类才有,只接调用Select对象中的Where方法
*/
public static function find()
{
$args = func_get_args();
return call_user_func_array(array(new Select('ws_term_meta'), 'where'), $args);
}
/**
* 删除数据
*/
public static function delete()
{
$args = func_get_args();
return parent::delete(__CLASS__, $args);
}
/**
* 添加数据
*/
public static function insert($data)
{
return parent::insert(__CLASS__, $data);
}
/**
* 更新数据
*/
public static function update($data)
{
return parent::update(__CLASS__, $data);
}
/**
* 取出数据验证时的非法数据
*/
public static function illegaldata()
{
return parent::illegaldata(__CLASS__);
}
/* ------------------ 以上是自动生成的代码,不能修改 ------------------ */
}
?> | bf4f242cc28d66c1bcb60713c03546ec89abb1a0 | [
"JavaScript",
"SQL",
"HTML",
"PHP"
] | 66 | PHP | linsir123/lxs-cms | 25439b97c7f95d3bd7738408b050b94667cccbc3 | 131f9fde2bde9325ef5bedbb42cf1a0c438d11c3 |
refs/heads/master | <repo_name>mtin79/codesandbox__react--popover-resizable<file_sep>/src/container/List/SearchInput.js
import styled from "styled-components";
const SearchInput = styled.input.attrs(props => ({
type: "search"
}))``;
export default SearchInput;
<file_sep>/src/App.js
import React from "react";
import Div100vh from "react-div-100vh";
import Map from "./container/Map/Map";
import Content from "./container/Content/Content";
class App extends React.Component {
render() {
return (
<Div100vh className="relative w-100 h-100 bg-light-gray br4 overflow-hidden border-box ba b--light-gray">
<Map className="absolute w-100 top-0 bottom-0" />
<Content />
</Div100vh>
);
}
}
export default App;
<file_sep>/src/container/Content/Content.js
import React from "react";
import ContentWrapper from "./ContentWrapper";
import Resizer from "../../components/Resizer";
const HEIGHTS = {
DEFAULT: "defaultHeight",
PARTIAL: "partialHeight",
FULL: "fullHeight"
};
class Content extends React.Component {
state = {
height: this.props.height || HEIGHTS.DEFAULT
};
onResize = size => {
console.log("switch to size: ", HEIGHTS[size]);
this.setState({ height: HEIGHTS[size] });
};
render() {
console.log("Content - Containers renders.");
const { height } = this.state;
return (
<ContentWrapper className={` ${height} absolute w-100 bottom-0`}>
<Resizer
handleResize={this.onResize}
sizes={HEIGHTS}
initialSize="DEFAULT"
/>
</ContentWrapper>
);
}
}
export default Content;
<file_sep>/src/components/Resizer.js
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Hammer from "hammerjs";
import { faGripLines } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const ResizerWrapper = styled.div.attrs(props => ({
className: "resizer flex justify-center relative"
}))`
margin-top: -8px;
.resizerIcon {
height: 40px;
font-size: 18px;
}
`;
class Resizer extends React.Component {
static propTypes = {
sizes: PropTypes.object.isRequired,
handleResize: PropTypes.func.isRequired,
initialSize: PropTypes.string
};
state = {
sizeIndex:
Object.keys(this.props.sizes).indexOf(this.props.initialSize) || 0
};
resizeElement = React.createRef();
shouldComponentUpdate() {
return false;
}
sizeUp = () => {
const sizesKeys = Object.keys(this.props.sizes);
if (this.state.sizeIndex < sizesKeys.length - 1) {
this.setState(prevState => {
const sizeIndex = prevState.sizeIndex + 1;
this.props.handleResize(sizesKeys[sizeIndex]);
console.log("increaseSizeIndex: ", sizeIndex);
return {
sizeIndex
};
});
}
};
sizeDown = () => {
const sizesKeys = Object.keys(this.props.sizes);
if (this.state.sizeIndex > 0) {
this.setState(prevState => {
const sizeIndex = prevState.sizeIndex - 1;
this.props.handleResize(sizesKeys[sizeIndex]);
console.log("increaseSizeIndex: ", sizeIndex);
return {
sizeIndex
};
});
}
};
sizeToggle = () => {
const sizesKeys = Object.keys(this.props.sizes);
if (this.state.sizeIndex === sizesKeys.length - 1) {
this.setState(prevState => {
const sizeIndex = prevState.sizeIndex - 1;
this.props.handleResize(sizesKeys[sizeIndex]);
console.log("increaseSizeIndex: ", sizeIndex);
return {
sizeIndex
};
});
} else {
this.setState(prevState => {
const sizeIndex = prevState.sizeIndex + 1;
this.props.handleResize(sizesKeys[sizeIndex]);
console.log("increaseSizeIndex: ", sizeIndex);
return {
sizeIndex
};
});
}
};
componentDidMount() {
// Initialize Hammer on Resizer element:
const hammer = new Hammer(this.resizeElement.current);
// Config hammer wrapper to process vertical directions:
hammer.get("swipe").set({ direction: Hammer.DIRECTION_VERTICAL });
hammer.on("swipeup", event => {
event.preventDefault();
this.sizeUp();
});
hammer.on("swipedown", event => {
event.preventDefault();
this.sizeDown();
});
hammer.on("tap", event => {
event.preventDefault();
this.sizeToggle();
});
}
render() {
return (
<ResizerWrapper ref={this.resizeElement}>
<FontAwesomeIcon className="moon-gray resizerIcon" icon={faGripLines} />
</ResizerWrapper>
);
}
}
export default Resizer;
<file_sep>/src/container/Element/Element.js
import styled from "styled-components";
const Element = styled.div``;
export default Element;
| fa6fac9be48f7b10712ecaa155576a3c7faf1789 | [
"JavaScript"
] | 5 | JavaScript | mtin79/codesandbox__react--popover-resizable | 724db6e056e3b703c787f2e6698090f2baff0974 | bc1c4eac63bb77e74b0c276eed5c76c357d26f85 |
refs/heads/master | <file_sep>create table todo(
`id` int primary key auto_increment,
`value` varchar(255),
`is_complete` boolean default false,
`date` timestamp default now(),
`user_id` int,
`deleted` int default 0
);
<file_sep>create table task(
`id` int primary key auto_increment,
content varchar(255),
todo_id int ,
`deleted` int default 0 ,
foreign key (todo_id) references todo(id)
);<file_sep>package com.thoughtworks.training.zhangtian.todoservice.controller;
import com.thoughtworks.training.zhangtian.todoservice.service.TodoService;
import oracle.jrockit.jfr.settings.EventDefaultSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException;
@Controller
public class TodoController {
@Autowired
private TodoService todoService;
@RequestMapping(method = RequestMethod.GET, path = "/todo")
public String todoList(Model model) throws IOException {
model.addAttribute("todos", todoService.get());
return "todo";
}
}
<file_sep>package com.thoughtworks.training.zhangtian.todoservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.retry.annotation.EnableRetry;
@EnableHystrixDashboard
@EnableCircuitBreaker
//@EnableRetry
@EnableFeignClients
@SpringBootApplication
public class TodoServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TodoServiceApplication.class, args);
}
}
<file_sep>package com.thoughtworks.training.zhangtian.todoservice.security;
import com.thoughtworks.training.zhangtian.todoservice.model.User;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.thymeleaf.util.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
@Component
public class TodoAuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (!request.getRequestURI().equals("/health")) {
logger.info("----------");
}
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
if (!StringUtils.isEmpty(token)) {
User user = analyzeToken(token);
if (user != null) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(user,
null,
Collections.emptyList())
);
}
}
filterChain.doFilter(request, response);
}
private User analyzeToken(String token) {
String[] tokens = token.split(":");
User user = new User();
user.setName(tokens[1]);
user.setId(Integer.valueOf(tokens[0]));
return user;
}
}
<file_sep>package com.thoughtworks.training.zhangtian.todoservice;
import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PasswordTest {
@Test
public void testPassword() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
System.out.println(encoder.encode("zhang"));
System.out.println(encoder.encode("zhang"));
System.out.println(encoder.encode("zhang"));
System.out.println(encoder.encode("zhang"));
System.out.println(encoder.encode("zhang"));
// assertTrue();
assertFalse(encoder.matches("zhangt", encoder.encode("zhang")));
}
}
<file_sep>package com.thoughtworks.training.zhangtian.todoservice.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.training.zhangtian.todoservice.model.Todo;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
@Service
public class ReadFile {
public List<Todo> read(String dataString) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(dataString, new TypeReference<List<Todo>>(){});
}
}
<file_sep>package com.thoughtworks.training.zhangtian.todoservice.repository;
import com.google.common.collect.ImmutableList;
import com.thoughtworks.training.zhangtian.todoservice.model.Todo;
import com.thoughtworks.training.zhangtian.todoservice.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@DataJpaTest
@RunWith(SpringRunner.class)
public class TodoRepositoryTest {
@Autowired
private TodoRepository todoRepository;
@Test
public void shouldReturnTodoByUserId() {
Todo todo = new Todo(1, "123456", false, new Date(), ImmutableList.of(), 1, false, "");
todoRepository.save(todo);
List<Todo> users = todoRepository.findAllByUserId(1);
assertThat(users.size(), is(1));
assertThat(users.get(0).getId(), is(todo.getId()));
assertThat(users.get(0).getValue(), is(todo.getValue()));
}
} | 0c36b468a3b29101c206973b7655beae39922d37 | [
"Java",
"SQL"
] | 8 | SQL | zhangtiantian10/spring-boot-todo | de51320573e83a8de035bb61068ba5f7ef71b9e5 | e6918dbd9a8340a6e579878f0903454d666c9ff2 |
refs/heads/master | <file_sep>import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
from skimage import exposure
ideal_img = cv2.imread('ideal.tif', 0)
crop_img = cv2.imread('crop.tif',0)
crop_eq = exposure.equalize_hist(crop_img)
crop_eq2 = exposure.equalize_hist(crop_eq)
crop_adapteq = exposure.equalize_adapthist(crop_img, clip_limit = 0.03)
plt.imshow(crop_eq-crop_eq2)
#plt.imshow(np.concatenate((crop_eq,crop_eq2),axis=1))
plt.show()
#print np.amax(crop_eq)
#cv2.imwrite('crop_eq.tif',crop_eq)
#cv2.imwrite('crop_adapteq.tif', crop_adapteq)
#cv2.imwrite('crop_contrast_stre', crop_contrast_stre)
#density_ideal= gaussian_kde(ideal_img.flatten())
#density_crop= gaussian_kde(crop_img.flatten())
#density_ideal.covariance_factor = lambda:0.01
#density_crop.covariance_factor = lambda:0.1
#density_ideal._compute_covariance()
#density_crop._compute_covariance()
#x = np.linspace(0,255, 256)
hist_ideal, _ = np.histogram(ideal_img.flatten(), bins = np.amax(ideal_img))
hist_crop, _ = np.histogram(crop_img.flatten(), bins = np.amax(crop_img))
hist_crop_eq, _ = np.histogram(crop_eq.flatten(), bins = np.amax(crop_eq))
#plt.plot(ideal_img.size*density_ideal(x))
#plt.plot(hist_ideal)
#plt.plot(crop_img.size*density_crop(x)[:len(hist_crop)])
#plt.plot(hist_crop)
plt.plot(hist_crop_eq)
plt.show()
<file_sep>from __future__ import division
import scipy.optimize
import scipy.spatial.distance
import partial_derivative
def shape_function(x,y):
return 0.000005*(x**2+y**2)+68
#return 0.00000001*x + 68
def find_k_refracting(k_incident, x1, n1,n2):
#x1 = [[xa,ya],
# [xb,yb],
# [xc,yc]]
gradient = np.array(partial_derivative.partial_derivative(shape_function, *x1.T))
#gradient= [[df/dxa,df/dya],
# [df/dxb,df/dyb],
# [df/dxc,df/dyc]]
n = np.ones((x1.shape[0], 3))
n[:,:-1] = gradient
norm = np.linalg.norm(n, axis = 1)
n = n/norm[:,np.newaxis] # n is the unit normal vector pointing 'upward'
c = -np.dot(n, k_incident)
r = n1/n2
if ((1-r**2*(1-c**2)) < 0).any():
print "Total internal reflection occurred."
print "1-r**2*(1-c**2) = \n", 1-r**2*(1-c**2)
sys.exit(0)
factor = (r*c- np.sqrt(1-r**2*(1-c**2)))
k_refracting = np.tile(r*k_incident,(x1.shape[0], 1)) + n*factor[:,np.newaxis]
#print "n = ", n
#print 'c =',c
#print "factor", factor
#print "tile", np.tile(r*k_incident,(x1.shape[0], 1))
#print "k_refracting = ", k_refracting
return k_refracting
#@profile
def find_x0(k_incident, x1, n1,n2):
def Fx(x):
k_refracting = find_k_refracting(k_incident, x, n1, n2)
return k_refracting[:,0]*(shape_function(*x1.T)+shape_function(*x.T))+k_refracting[:,2]*(x1-x)[:,0]
def Fy(x):
k_refracting = find_k_refracting(k_incident, x, n1, n2)
return k_refracting[:,1]*(shape_function(*x1.T)+shape_function(*x.T))+k_refracting[:,2]*(x1-x)[:,1]
def F(x):
return 1e5*(Fx(x)**2 + Fy(x)**2)
print "F = ", F(x1)
"""
A FAILED PROJECT.
Having F(x,y,x1,y1) = 0. Easy to root find
1 pair of x,y given 1 pair of x1,y1. Successful
in vectorizing F, making it accept a matrix of
x1,y1.
FAILED IN THE NEXT STEP OF ROOT FINDING.
SCIPY DOESN'T SEEM TO SUPPORT SIMULTANEOUS
ROOT FINDING (vectorization).
"""
x0 = scipy.optimize.root(F,x1)
return x0
def optical_path_diff(k_incident, x1, n1,n2):
x0 = find_x0(k_incident, x1, n1, n2)
p0 = np.concatenate((x0, shape_function(*x0.T)[:,np.newaxis]),axis=1)
p1 = np.concatenate((x1, shape_function(*x1.T)[:,np.newaxis]),axis=1)
p1_image_point = np.concatenate((x1, -shape_function(*x1.T)[:,np.newaxis]),axis=1)
vec_x0x1 = p1-p0
norm = np.linalg.norm(vec_x0x1, axis = 1)
norm[norm == 0] = 1
vec_x0x1 = vec_x0x1/norm[:,np.newaxis]
cos = np.dot(vec_x0x1, k_incident)
dist1 = scipy.spatial.distance.cdist(p0,p1,'euclidean')
dist2 = scipy.spatial.distance.cdist(p0,p1_image_point,'euclidean')
dist1 = np.diagonal(dist1)
dist2 = np.diagonal(dist2)
#print "vec_x0x1 = ", vec_x0x1
#print "cos = ", cos
#print "p0 = ", p0
#print "p1 = ", p1
#print "dist1 = ", dist1
#print "dist2 = ", dist2
OPD_part1 = dist1*cos*n1
OPD_part2 = dist2*n2
OPD = OPD_part2-OPD_part1
return OPD
def pattern(opd):
intensity = 1+np.cos((2*np.pi/0.532)*opd)
return intensity
if __name__ == "__main__":
import matplotlib.pyplot as plt
import numpy as np
import sys
import processbar
import os
print "starting..."
i = 0
phi = 0
for theta in np.linspace(0.,0.1,1):
fig = plt.figure()
ax = fig.add_subplot(111)
i += 1
opd = optical_path_diff(k_incident = np.array([np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi), -np.cos(theta)]),\
x1 = np.array([[0,10]]),\
n1 = 1.5,\
n2 = 1)
intensity = pattern(opd)
#opd_expected = 2*shape_function(0)*np.cos(np.arcsin(np.sin(angle-0.0000001)*1.5)+0.0000001)
print opd
#print "error in OPD = " ,(opd-opd_expected)/0.532, "wavelength"
#ax.plot(detecting_range, intensity)
#plt.ylim((0,2.5))
#ax.set_xlabel('$\mu m$')
#ax.text(0, 2.2, r'$rotated : %.4f rad$'%angle, fontsize=15)
#dirname = "./movie2D/"
#if not os.path.exists(dirname):
# os.makedirs(dirname)
#plt.savefig(dirname+'{:4.0f}'.format(i)+'.tif')
#plt.close()
#processbar.processbar_tty(i, 100, 1)
print "finished!"
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,20, 0.001)
red = 1+np.cos(4*np.pi*(x+0.630/4)/0.630)
amber = 1+ np.cos(4*np.pi*(x+0*0.59/4)/0.590)
plt.plot(x, red+amber)
plt.title('red and amber 8bit')
plt.plot(x, red, 'r')
plt.plot(x, amber, 'y')
plt.show()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt('data_lambda1vsangle')
lambda1 = 0.5*(data[:,2]+data[:,3])
angle = 0.5*(180-data[:,0]+data[:,1])*np.pi/180.
cosangle = np.cos(angle)
sinangle = np.sin(angle)
anglefunction = sinangle/np.power(cosangle,0.33)
plt.scatter(anglefunction, lambda1, s=30, facecolors='none',edgecolors='k')
plt.axis([0,1.5,0,160])
plt.xlabel(r'$\frac{\sin\phi}{\cos^\frac{1}{3}\phi}$',fontsize=20)
plt.ylabel(r'$\lambda_1$',fontsize=20)
plt.gcf().subplots_adjust(bottom = 0.15)
plt.savefig('lambdavsangle.png')
plt.show()
<file_sep>#!/usr/bin/env python
from __future__ import division
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
from scipy import fftpack
from scipy import signal
from scipy.ndimage import gaussian_filter
def equalize(img_array):
"""
returns array with float 0-1
"""
img_array = img_array/(img_array.max()+1e-6)
#equalized = exposure.equalize_adapthist(img_array,kernal_size = (5,5))
equalized = exposure.equalize_hist(img_array)
#equalized = img_array/img_array.max()
return equalized
def difference(data_img, generated_img,mask_patch):
"""
both images have to be 0-1float
"""
data_img = gaussian_filter(data_img,sigma=0.3)
generated_img = gaussian_filter(generated_img, sigma=0)
diff_value = np.sum(mask_patch*(data_img-generated_img)**2)
diff_value /= (mask_patch.sum())#percentage of white area
return diff_value
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
def nl(coeff, data_img,(zoomfactory,zoomfactorx),mask_patch):
"""
negative likelyhood-like function; aim to minimize this
data_img has to be 0-1float
"""
height = surface_polynomial(data_img.shape,coeff,(zoomfactory,zoomfactorx))
expected= 1+ np.cos((4*np.pi/0.532)*height)
expected /= expected.max()#normalize to 0-1float
#expected = equalize(expected)
return difference(data_img, expected,mask_patch)
def accept_test(f_new,x_new,f_old,x_old):
return True
if abs(x_new[3])>0.05 or abs(x_new[4])>0.05:
return False
else:
return True
def callback(x,f,accept):
#print x[3],x[4],f,accept
pass
def find_tilequeue4(processed_tiles):
tilequeue = []
for tile in processed_tiles:
tilequeue.append((tile[0]+1,tile[1])) #right
tilequeue.append((tile[0]-1,tile[1])) #left
tilequeue.append((tile[0],tile[1]+1)) #down
tilequeue.append((tile[0],tile[1]-1)) #up
#tilequeue.append((tile[0]+1,tile[1]-1)) #upperright
#tilequeue.append((tile[0]-1,tile[1]+1)) #lowerleft
#tilequeue.append((tile[0]+1,tile[1]+1)) #lowerright
#tilequeue.append((tile[0]-1,tile[1]-1)) #upperleft
tilequeue = [tile for tile in tilequeue if tile not in processed_tiles]
return list(set(tilequeue))
def find_tilequeue8(processed_tiles):
tilequeue = []
for tile in processed_tiles:
tilequeue.append((tile[0]+1,tile[1])) #right
tilequeue.append((tile[0]-1,tile[1])) #left
tilequeue.append((tile[0],tile[1]+1)) #down
tilequeue.append((tile[0],tile[1]-1)) #up
tilequeue.append((tile[0]+1,tile[1]-1)) #upperright
tilequeue.append((tile[0]-1,tile[1]+1)) #lowerleft
tilequeue.append((tile[0]+1,tile[1]+1)) #lowerright
tilequeue.append((tile[0]-1,tile[1]-1)) #upperleft
tilequeue = [tile for tile in tilequeue if tile not in processed_tiles]
return list(set(tilequeue))
def fittile(tile, dxx,dyy,zoomfactorx, zoomfactory, data_img, mask_img,xstore, abquadrant, white_threshold):
yy = tile[0]*dyy
xx = tile[1]*dxx
data_patch = data_img[yy:yy+dyy,xx:xx+dxx]
data_patch = data_patch[::zoomfactory,::zoomfactorx]
mask_patch = mask_img[yy:yy+dyy,xx:xx+dxx]
mask_patch = mask_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
white_percentage = (mask_patch.sum()/len(mask_patch.flat))
if white_percentage < white_threshold:
goodness = threshold/white_percentage
return [np.nan,np.nan,np.nan,np.nan,np.nan, np.nan],goodness, white_percentage
initcoeff_extendlist = []
if (int(yy/dyy)-1,int(xx/dxx)) in xstore:
#print 'found up'
up = xstore[(int(yy/dyy)-1,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],up[2]*dyy+up[3],2*up[1]*dyy+up[4],up[1]*dyy*dyy+up[4]*dyy+up[5]]))
if (int(yy/dyy)+1,int(xx/dxx)) in xstore:
#print 'found down'
up = xstore[(int(yy/dyy)+1,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],-up[2]*dyy+up[3],-2*up[1]*dyy+up[4],up[1]*dyy*dyy-up[4]*dyy+up[5]]))
if (int(yy/dyy),int(xx/dxx)-1) in xstore:
#print 'found left'
left = xstore[(int(yy/dyy),int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx+left[3],left[2]*dxx+left[4],left[0]*dxx*dxx+left[3]*dxx+left[5]]))
if (int(yy/dyy),int(xx/dxx)+1) in xstore:
#print 'found right'
left = xstore[(int(yy/dyy),int(xx/dxx)+1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx+left[3],-left[2]*dxx+left[4],left[0]*dxx*dxx-left[3]*dxx+left[5]]))
if (int(yy/dyy)-1,int(xx/dxx)-1) in xstore:
#print 'found upperleft'
left = xstore[(int(yy/dyy)-1,int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx+left[2]*dyy+left[3],left[2]*dxx+2*left[1]*dyy+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy+left[2]*dxx*dyy+left[3]*dxx+left[4]*dyy+left[5]]))
if (int(yy/dyy)+1,int(xx/dxx)-1) in xstore:
#print 'found lowerleft'
left = xstore[(int(yy/dyy)+1,int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx-left[2]*dyy+left[3],left[2]*dxx-2*left[1]*dyy+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy-left[2]*dxx*dyy+left[3]*dxx-left[4]*dyy+left[5]]))
if (int(yy/dyy)+1,int(xx/dxx)+1) in xstore:
#print 'found lowerright'
left = xstore[(int(yy/dyy)+1,int(xx/dxx)+1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx-left[2]*dyy+left[3],-left[2]*dxx-2*left[1]*dyy+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy+left[2]*dxx*dyy-left[3]*dxx-left[4]*dyy+left[5]]))
if (int(yy/dyy)-1,int(xx/dxx)+1) in xstore:
#print 'found upperright'
left = xstore[(int(yy/dyy)-1,int(xx/dxx)+1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx+left[2]*dyy+left[3],-left[2]*dxx+2*left[1]*dyy+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy-left[2]*dxx*dyy-left[3]*dxx+left[4]*dyy+left[5]]))
"""
#######################################################
if (int(yy/dyy)-2,int(xx/dxx)) in xstore:
#print 'found up'
up = xstore[(int(yy/dyy)-2,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],up[2]*dyy*2+up[3],2*up[1]*dyy*2+up[4],up[1]*dyy*dyy*4+up[4]*dyy*2+up[5]]))
if (int(yy/dyy)+2,int(xx/dxx)) in xstore:
#print 'found down'
up = xstore[(int(yy/dyy)+2,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],-up[2]*dyy*2+up[3],-2*up[1]*dyy*2+up[4],up[1]*dyy*dyy*4-up[4]*dyy*2+up[5]]))
if (int(yy/dyy),int(xx/dxx)-2) in xstore:
#print 'found left'
left = xstore[(int(yy/dyy),int(xx/dxx)-2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx*2+left[3],left[2]*dxx*2+left[4],left[0]*dxx*dxx*4+left[3]*dxx*2+left[5]]))
if (int(yy/dyy),int(xx/dxx)+2) in xstore:
#print 'found right'
left = xstore[(int(yy/dyy),int(xx/dxx)+2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx*2+left[3],-left[2]*dxx*2+left[4],left[0]*dxx*dxx*4-left[3]*dxx*2+left[5]]))
if (int(yy/dyy)-2,int(xx/dxx)-1) in xstore:
#print 'found upperleft'
left = xstore[(int(yy/dyy)-2,int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx+left[2]*dyy*2+left[3],left[2]*dxx+2*left[1]*dyy*2+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy*4+left[2]*dxx*dyy*2+left[3]*dxx+left[4]*dyy*2+left[5]]))
if (int(yy/dyy)-1,int(xx/dxx)-2) in xstore:
#print 'found upperleft'
left = xstore[(int(yy/dyy)-1,int(xx/dxx)-2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx*2+left[2]*dyy+left[3],left[2]*dxx*2+2*left[1]*dyy+left[4],left[0]*dxx*dxx*4+left[1]*dyy*dyy+left[2]*dxx*2*dyy+left[3]*dxx*2+left[4]*dyy+left[5]]))
if (int(yy/dyy)+2,int(xx/dxx)-1) in xstore:
#print 'found lowerleft'
left = xstore[(int(yy/dyy)+2,int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx-left[2]*dyy*2+left[3],left[2]*dxx-2*left[1]*dyy*2+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy*4-left[2]*dxx*dyy*2+left[3]*dxx-left[4]*dyy*2+left[5]]))
if (int(yy/dyy)+1,int(xx/dxx)-2) in xstore:
#print 'found lowerleft'
left = xstore[(int(yy/dyy)+1,int(xx/dxx)-2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx*2-left[2]*dyy+left[3],left[2]*dxx*2-2*left[1]*dyy+left[4],left[0]*dxx*dxx*4+left[1]*dyy*dyy-left[2]*dxx*2*dyy+left[3]*dxx*2-left[4]*dyy+left[5]]))
if (int(yy/dyy)+1,int(xx/dxx)+2) in xstore:
#print 'found lowerright'
left = xstore[(int(yy/dyy)+1,int(xx/dxx)+2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx*2-left[2]*dyy+left[3],-left[2]*dxx*2-2*left[1]*dyy+left[4],left[0]*dxx*dxx*2+left[1]*dyy*dyy+left[2]*dxx*2*dyy-left[3]*dxx*2-left[4]*dyy+left[5]]))
if (int(yy/dyy)+2,int(xx/dxx)+1) in xstore:
#print 'found lowerright'
left = xstore[(int(yy/dyy)+2,int(xx/dxx)+1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx-left[2]*dyy*2+left[3],-left[2]*dxx-2*left[1]*dyy*2+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy*2+left[2]*dxx*dyy*2-left[3]*dxx-left[4]*dyy*2+left[5]]))
if (int(yy/dyy)-2,int(xx/dxx)+1) in xstore:
#print 'found upperright'
left = xstore[(int(yy/dyy)-2,int(xx/dxx)+1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx+left[2]*dyy*2+left[3],-left[2]*dxx+2*left[1]*dyy*2+left[4],left[0]*dxx*dxx+left[1]*dyy*dyy*4-left[2]*dxx*dyy*2-left[3]*dxx+left[4]*dyy*2+left[5]]))
if (int(yy/dyy)-1,int(xx/dxx)+2) in xstore:
#print 'found upperright'
left = xstore[(int(yy/dyy)-1,int(xx/dxx)+2)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],-2*left[0]*dxx*2+left[2]*dyy+left[3],-left[2]*dxx*2+2*left[1]*dyy+left[4],left[0]*dxx*dxx*2+left[1]*dyy*dyy-left[2]*dxx*2*dyy-left[3]*dxx*2+left[4]*dyy+left[5]]))
###############################################################
"""
if len(initcoeff_extendlist) > 0:
initcoeff_extend = np.mean(initcoeff_extendlist,axis=0)
initcoeff = initcoeff_extend
else: #if no touching tiles are detected, should be only for the starting tile
if abquadrant == 1:
alist = np.linspace(0, sample_size, N) # x direction
blist = np.linspace(0, sample_size, N) # y direction
if abquadrant == 2:
alist = np.linspace(-sample_size, 0, N) # x direction
blist = np.linspace(0, sample_size, N) # y direction
if abquadrant == 3:
alist = np.linspace(-sample_size, 0, N) # x direction
blist = np.linspace(-sample_size, 0, N) # y direction
if abquadrant == 4:
alist = np.linspace(0, sample_size, N) # x direction
blist = np.linspace(-sample_size, 0, N) # y direction
aa, bb = np.meshgrid(alist,blist)
nl_1storder = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.1*len(alist))**2:#remove central region to avoid 0,0 global min
nl_1storder[j,i] = np.nan
else:
nl_1storder[j,i] = nl([0,0,0,aa[j,i],bb[j,i],0],data_patch,(zoomfactory,zoomfactorx),mask_patch)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
index = np.unravel_index(np.nanargmin(nl_1storder), nl_1storder.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeff_linear= np.array([0,0,0,index[0],index[1],0])
initcoeff = initcoeff_linear
print initcoeff
iternumber = 0
while 1:
#print 'iternumber =', iternumber,'for',yy,xx
result = basinhopping(nl, initcoeff, niter = 8, T=0.01, stepsize=5e-5, interval=50,accept_test=accept_test,minimizer_kwargs={'method': 'Nelder-Mead', 'args': (data_patch,(zoomfactory,zoomfactorx), mask_patch)}, disp=False, callback=callback)
print result.fun
if result.fun <threshold:
xopt = result.x
break
else:
initcoeff = result.x
iternumber+=1
if iternumber == 5:
xopt = initcoeff_extend
break
goodness = result.fun
return xopt, goodness, white_percentage
def tilewithinbound(tile, dxx, dyy, data_img):
if tile[0]<0 or tile[1]<0:
return False
elif (tile[1]+1)*dxx>data_img.shape[1] or (tile[0]+1)*dyy>data_img.shape[0]:
return False
else:
return True
if __name__ == "__main__":
from scipy.ndimage import gaussian_filter
import time
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from time import localtime, strftime
start = time.time()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
N = 100 #a,b value resolution; a, b linear term coeff
sample_size = 0.2 #a, b value range
abquadrant = 3
data_img = cv2.imread('sample4.tif', 0)
mask_img = cv2.imread('mask_bot_v2.tif', 0)
data_img = data_img.astype('float64')
mask_img = mask_img.astype('float64')
mask_img /= 255.
fitimg = np.copy(data_img)
xstore = {}
xstore_badtiles = {}
hstore_upperright = {}
hstore_lowerright = {}
hstore_lowerleft = {}
hstore_upperleft= {}
dyy,dxx = 81,81
threshold = 0.08
white_threshold = 0.4
startingposition = (928,2192)
startingtile = (int(startingposition[0]/dyy),int(startingposition[1]/dxx))
zoomfactory,zoomfactorx = 1,1
tilequeue = find_tilequeue8([startingtile])
tilequeue = [startingtile]+tilequeue
processed_tiles = []
bad_tiles= []
black_tiles= []
tilequeue = [tile for tile in tilequeue if tilewithinbound(tile,dxx, dyy, data_img)]
goodness_dict= {}
while any(tilequeue):
print tilequeue
# check queue for a collection of goodness and get the best tile
for tile in tilequeue:
if tile not in goodness_dict: #avoid double checking the tiles shared by the old tilequeue
print 'prechecking tile: ',tile
xopttrial, goodness,white_percentage = fittile(tile,dxx,dyy,zoomfactorx, zoomfactory, data_img, mask_img,xstore,abquadrant,white_threshold)
print 'white percentage:', white_percentage
goodness_dict[tile] = goodness
if white_percentage >= white_threshold:
if goodness <= threshold:
xstore[tile] = xopttrial
elif goodness > threshold:
bad_tiles.append(tile) #never used it
print 'bad tile:', tile
else:
black_tiles.append(tile)
print 'black tile:', tile
goodness_queue = {tile:goodness_dict[tile] for tile in tilequeue}
best_tile = min(goodness_queue,key=goodness_queue.get)
yy,xx = best_tile[0]*dyy, best_tile[1]*dxx
print 'processing best tile', (int(yy/dyy),int(xx/dxx))
processed_tiles.append((int(yy/dyy),int(xx/dxx)))#update processed tiles
tilequeue = find_tilequeue8(processed_tiles)#update tilequeue
tilequeue = [tile for tile in tilequeue if tilewithinbound(tile,dxx, dyy, data_img)]
if best_tile in black_tiles:
break
data_patch = data_img[yy:yy+dyy,xx:xx+dxx]
data_patch = data_patch[::zoomfactory,::zoomfactorx]
mask_patch = mask_img[yy:yy+dyy,xx:xx+dxx]
mask_patch = mask_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
xopt, goodness, white_percentage = fittile(best_tile, dxx,dyy,zoomfactorx, zoomfactory, data_img, mask_img,xstore, abquadrant, white_threshold)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
#plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
#plt.show()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
if best_tile in bad_tiles:
fitimg[yy:yy+5,xx:xx+dxx] = 0
fitimg[yy+dyy-5:yy+dyy,xx:xx+dxx] = 0
fitimg[yy:yy+dyy,xx:xx+5] = 0
fitimg[yy:yy+dyy,xx+dxx-5:xx+dxx] = 0
height = surface_polynomial(data_patch.shape, xopt,(zoomfactory,zoomfactorx))
hupperright = height[0,-1]
hlowerright = height[-1,-1]
hlowerleft = height[-1,0]
hupperleft = height[0,0]
clist = []
#upperleft node
if (int(yy/dyy),int(xx/dxx)-1) in hstore_upperright:
clist.append(hstore_upperright[(int(yy/dyy),int(xx/dxx)-1)])
if (int(yy/dyy)-1,int(xx/dxx)) in hstore_lowerleft:
clist.append(hstore_lowerleft[(int(yy/dyy)-1,int(xx/dxx))])
if (int(yy/dyy)-1,int(xx/dxx)-1) in hstore_lowerright:
clist.append(hstore_lowerright[(int(yy/dyy)-1,int(xx/dxx)-1)])
#lowerleft node
if (int(yy/dyy),int(xx/dxx)-1) in hstore_lowerright:
correction_to_currentc = hstore_lowerright[(int(yy/dyy),int(xx/dxx)-1)]-hlowerleft
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)+1,int(xx/dxx)-1) in hstore_upperright:
correction_to_currentc = hstore_upperright[(int(yy/dyy)+1,int(xx/dxx)-1)]-hlowerleft
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)+1,int(xx/dxx)) in hstore_upperleft:
correction_to_currentc = hstore_upperleft[(int(yy/dyy)+1,int(xx/dxx))]-hlowerleft
clist.append(xopt[5]+correction_to_currentc)
#lowerright node
if (int(yy/dyy),int(xx/dxx)+1) in hstore_lowerleft:
correction_to_currentc = hstore_lowerleft[(int(yy/dyy),int(xx/dxx)+1)]-hlowerright
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)+1,int(xx/dxx)+1) in hstore_upperleft:
correction_to_currentc = hstore_upperleft[(int(yy/dyy)+1,int(xx/dxx)+1)]-hlowerright
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)+1,int(xx/dxx)) in hstore_upperright:
correction_to_currentc = hstore_upperright[(int(yy/dyy)+1,int(xx/dxx))]-hlowerright
clist.append(xopt[5]+correction_to_currentc)
#upperright node
if (int(yy/dyy),int(xx/dxx)+1) in hstore_upperleft:
correction_to_currentc = hstore_upperleft[(int(yy/dyy),int(xx/dxx)+1)]-hupperright
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)-1,int(xx/dxx)+1) in hstore_lowerleft:
correction_to_currentc = hstore_lowerleft[(int(yy/dyy)-1,int(xx/dxx)+1)]-hupperright
clist.append(xopt[5]+correction_to_currentc)
if (int(yy/dyy)-1,int(xx/dxx)) in hstore_lowerright:
correction_to_currentc = hstore_lowerright[(int(yy/dyy)-1,int(xx/dxx))]-hupperright
clist.append(xopt[5]+correction_to_currentc)
if len(clist)>0:
#print 'clist=', clist
#if max(clist)-np.median(clist)>0.532/2:
# clist.remove(max(clist))
# print 'maxremove'
#if np.median(clist)-min(clist)>0.532/2:
# clist.remove(min(clist))
# print 'minremove'
xopt[5] = np.mean(clist)
height = surface_polynomial(data_patch.shape, xopt,(zoomfactory,zoomfactorx))
hupperright = height[0,-1]
hlowerright = height[-1,-1]
hlowerleft = height[-1,0]
hupperleft = height[0,0]
#if iternumber <20:
if 1:
#print 'coeff & corner heights stored'
xstore[(int(yy/dyy),int(xx/dxx))]=xopt
hstore_upperright[(int(yy/dyy),int(xx/dxx))] = hupperright
hstore_lowerright[(int(yy/dyy),int(xx/dxx))] = hlowerright
hstore_lowerleft[(int(yy/dyy),int(xx/dxx))] = hlowerleft
hstore_upperleft[(int(yy/dyy),int(xx/dxx))] = hupperleft
else:
xstore_badtiles[(int(yy/dyy),int(xx/dxx))]=xopt
print (int(yy/dyy),int(xx/dxx)), 'is a bad tile'
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1))
ax.set_aspect('equal')
plt.draw()
plt.pause(0.01)
cv2.imwrite('fitimg_bot.tif', fitimg.astype('uint8'))
print '\n'
np.save('xoptstore_bot',xstore)
#np.save('xoptstore_badtiles'+strftime("%Y%m%d_%H_%M_%S",localtime()),xstore_badtiles)
print 'time used', time.time()-start, 's'
print 'finished'
plt.show()
<file_sep>from scipy import fftpack
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('ideal.tif',0)
absfft2 = np.abs(fftpack.fft2(img))[2:-2,2:-2]
absfft2 /= absfft2.max()
print absfft2.max()
plt.imshow(absfft2)
plt.show()
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
from find_peaks import find_indices_max as fimax
from find_peaks import find_indices_min as fimin
cmap = plt.get_cmap('tab10')
am = cmap(1)
gr = cmap(2)
rd = cmap(3)
amwvlg = 0.590
rdwvlg = 0.6328
grwvlg = 0.532
x = np.arange(0,30, 0.0009)
red = 1+np.cos(4*np.pi*(x+rdwvlg/4)/rdwvlg)
amber = 1+ np.cos(4*np.pi*(x+amwvlg/4)/amwvlg)
green = 1+ np.cos(4*np.pi*(x+grwvlg/4)/grwvlg)
red8 = 1+np.cos(4*np.pi*x/rdwvlg)
amber8 = 1+ np.cos(4*np.pi*x/amwvlg)
green8 = 1+ np.cos(4*np.pi*x/grwvlg)
fig,ax= plt.subplots()
#for i,ind in enumerate(fimin(amber)):
# ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.1),color=am)
for i,ind in enumerate(fimin(red)):
ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.2),color=rd)
ax.annotate('%.3f'%(x[ind]),xy=(x[ind],0),xytext=(x[ind],-0.3),color=rd)
for i,ind in enumerate(fimax(red)):
ax.annotate('%.3f'%(x[ind]),xy=(x[ind],0),xytext=(x[ind],2+0.2),color=rd)
plt.subplots_adjust(bottom=0.2)
lred, = ax.plot(x, red,color=rd,visible=False)
lamber, = ax.plot(x, amber, color=am,visible=False)
lgreen, = ax.plot(x, green, color=gr,visible=False)
lred8, = ax.plot(x, red8,color=rd,visible=False)
lamber8, = ax.plot(x, amber8, color=am,visible=False)
lgreen8, = ax.plot(x, green8, color=gr,visible=False)
#ax.plot(x,amber+green+red)
rax = plt.axes([0.01, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('red', 'amber', 'green','red8','amber8','green8'), (False, False, False, False, False, False))
def func(label):
if label == 'red':
lred.set_visible(not lred.get_visible())
elif label == 'amber':
lamber.set_visible(not lamber.get_visible())
elif label == 'green':
lgreen.set_visible(not lgreen.get_visible())
if label == 'red8':
lred8.set_visible(not lred8.get_visible())
elif label == 'amber8':
lamber8.set_visible(not lamber8.get_visible())
elif label == 'green8':
lgreen8.set_visible(not lgreen8.get_visible())
plt.draw()
check.on_clicked(func)
plt.show()
<file_sep>import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import cookb_signalsmooth
intensity = np.load("intensity.npy")
intensity = -intensity
coordinates = np.linspace(-500,500,300)
plt.plot(coordinates, intensity)
#intensity = cookb_signalsmooth.smooth(intensity, 10)
#plt.plot(coordinates, intensity)
peakind = signal.find_peaks_cwt(intensity, np.arange(20,150))
plt.plot(coordinates[peakind], intensity[peakind],'+', color = 'r')
plt.show()
<file_sep>from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
w = 236/519
y = np.arange(-w+0.0005,w-0.0005,0.001)
plt.plot(y, ((1-w)/np.pi)*np.log((1+np.cos(np.pi*y/w))/2))
plt.axes().set_aspect('equal')
plt.xlim(-1,1)
plt.show()
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy import interpolate
from scipy.signal import savgol_filter as sg
data_img = cv2.imread('sample4.tif',0)
data_img = data_img.astype('float64')
fitimg_whole = np.copy(data_img)
xstore = np.load('./xoptstore_bot.npy').item()
#xstore_badtiles=np.load('xoptstore_badtiles20180513_21_22_42.npy').item()
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
#dyy,dxx =int(41*np.tan(np.pi*52/180)),41
dyy,dxx = 81,81
zoomfactory,zoomfactorx = 1,1
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111, projection='3d')
#ax.set_aspect('equal','box')
hslice=[]
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstore:
xopt = xstore[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
if int(xx/dxx) == 25:
hslice.extend(height[:,0])
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#cv2.imwrite('fitimg_whole.tif', fitimg_whole.astype('uint8'))
plt.show()
<file_sep>import cv2
import numpy as np
from skimage import transform as tf
import matplotlib.pyplot as plt
img = cv2.imread('sample6.tif',0)
pointset1 = np.genfromtxt('pointset1.csv', delimiter=',', names=True)
pointset2 = np.genfromtxt('pointset2.csv', delimiter=',', names=True)
pointset1 = np.vstack((pointset1['BX'],pointset1['BY'])).T
pointset2 = np.vstack((pointset2['BX'],pointset2['BY'])).T
tform = tf.PiecewiseAffineTransform()
tform.estimate(pointset1, pointset2) # pointset2 will be warped
warped = 255*tf.warp(img, tform)
warped = warped.astype(np.uint8)
plt.imshow(warped)
plt.show()
<file_sep>import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.widgets import Button
def sliders_buttons(pararange,parainit,height = 0.08,incremental=0.001):
xslider = plt.axes([0.25,height,0.65,0.03])
slider = Slider(xslider,'para',pararange[0],pararange[1],valinit=parainit,valfmt='%1.3f')
xbuttonminus= plt.axes([0.1,height,0.02,0.03])
xbuttonplus= plt.axes([0.12,height,0.02,0.03])
buttonplus = Button(xbuttonplus,'+')
buttonminus = Button(xbuttonminus,'-')
def incr_slider(val):
slider.set_val(slider.val+incremental)
def decr_slider(val):
slider.set_val(slider.val-incremental)
buttonplus.on_clicked(incr_slider)
buttonminus.on_clicked(decr_slider)
return slider,buttonplus,buttonminus
def plotwithsliders(slider,buttonplus,buttonminus,ax,x,y,mycolor,pararange,parainit):
para = parainit
lines, = ax.plot(x(*para),y(*para),color=mycolor)
def update(arbitrary_arg):
for i in range(len(slider)):
para[i] = slider[i].val
lines.set_xdata(x(*para))
lines.set_ydata(y(*para))
plt.draw()
#fig.canvas.draw_idle()
for i in range(len(slider)):
slider[i].on_changed(update)
return lines
<file_sep>from __future__ import division
import scipy.optimize
import scipy.spatial.distance
import partial_derivative
import math
#@profile
def shape_function(x,y):
#return np.exp(-0.00002*((x+250)**2+y**2)) + np.exp(-0.00002*((x-250)**2+y**2))+100
return 0.000005*(x**2+y**2)+68.1
#return 0.00000001*x + 68
#@profile
def find_k_refracting(k_incident, x1, n1,n2):
# x1 in the form [x1,y1]
gradient = partial_derivative.partial_derivative(shape_function, *x1)
# gradient in the form [df/dx1,df/dy1]
#n = np.r_[-gradient, 1] adding a column in memory is too slow
n = np.empty((3,))
n[:-1] = -gradient
n[-1] = 1
#print "n = ", n
#print "x1 = ", x1
norm =np.linalg.norm(n)
n = n/norm # n is the unit normal vector pointing 'upward'
c = -np.dot(n, k_incident)
r = n1/n2
sqrtterm = (1-r**2*(1-c**2))
if sqrtterm < 0:
print(Fore.RED)
print "Total internal reflection occurred."
print "1-r**2*(1-c**2) = \n", sqrtterm
print(Style.RESET_ALL)
sys.exit(0)
factor = (r*c- math.sqrt(sqrtterm))
k_refracting = r*k_incident + factor*n
#print 'c =',c
#print "factor", factor
#print "k_refracting = ", k_refracting
return k_refracting
#@profile
def find_x0(k_incident, x1, n1,n2):
# def Fx(x):
# k_refracting = find_k_refracting(k_incident, x, n1, n2)
# return k_refracting[0]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[0]
# def Fy(x):
# k_refracting = find_k_refracting(k_incident, x, n1, n2)
# return k_refracting[1]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[1]
# def F(x):
# return Fx(x), Fy(x)
def F(x):
k_refracting = find_k_refracting(k_incident, x, n1, n2)
return k_refracting[0]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[0], k_refracting[1]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[1]
sol = scipy.optimize.root(F,x1)
x0 = sol.x
return x0
#@profile
def optical_path_diff(k_incident, x1, n1,n2):
x0 = find_x0(k_incident, x1, n1, n2)
p0 = np.empty((3,))
p1 = np.empty((3,))
p1_image_point = np.empty((3,))
p0[:-1] = x0
p1[:-1] = x1
p1_image_point[:-1] = x1
p0[-1] = shape_function(*x0)
p1[-1] = shape_function(*x1)
p1_image_point[-1] = -shape_function(*x1)
#p0 = np.r_[x0, shape_function(*x0)]
#p1 = np.r_[x1, shape_function(*x1)]
#p1_image_point = np.r_[x1, -shape_function(*x1)]
vec_x0x1 = p1-p0
norm = np.linalg.norm(vec_x0x1)
if norm == 0:
norm = 1
vec_x0x1 = vec_x0x1/norm
cos = np.dot(vec_x0x1, k_incident)
dist1 = np.linalg.norm(p0-p1)
dist2 = np.linalg.norm(p0-p1_image_point)
#print "vec_x0x1 = ", vec_x0x1
#print "cos = ", cos
#print "p0 = ", p0
#print "p1 = ", p1
#print "dist1 = ", dist1
#print "dist2 = ", dist2
OPD_part1 = dist1*cos*n1
OPD_part2 = dist2*n2
OPD = OPD_part2-OPD_part1
return OPD
#@profile
def pattern(opd):
intensity = 1+np.cos((2*np.pi/0.532)*opd)
return intensity
if __name__ == "__main__":
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.mlab import griddata
import numpy as np
import sys
import progressbar
import os
from itertools import product
import time
from colorama import Style, Fore
start = time.time()
print "starting..."
i = 0
phi = 0
framenumber = 50
for theta in np.linspace(0.,0.065,framenumber):
i += 1
pltnumber = 100
pltlength = 300
coordinates = np.array(list(product(np.linspace(-pltlength,pltlength,pltnumber), np.linspace(-pltlength, pltlength, pltnumber))))
q = 0
intensity = np.zeros((coordinates.shape[0], ))
for detecting_point in coordinates:
opd = optical_path_diff(k_incident = np.array([np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi), -np.cos(theta)]),\
x1 = detecting_point,\
n1 = 1.5,\
n2 = 1)
intensity[q] = pattern(opd)
q+=1
#opd_expected = 2*shape_function(0)*np.cos(np.arcsin(np.sin(angle-0.0000001)*1.5)+0.0000001)
#print pattern(opd)
#print "error in OPD = " ,(opd-opd_expected)/0.532, "wavelength"
X = coordinates[:,0].reshape((pltnumber,pltnumber))
Y = coordinates[:,1].reshape((pltnumber,pltnumber))
Z = intensity.reshape((pltnumber, pltnumber))
fig = plt.figure(num=None, figsize=(6, 6), dpi=60, facecolor='w', edgecolor='k')
ax = fig.add_subplot(111, projection='3d')
#ax.set_xlabel('$x,\mu m$')
#ax.set_ylabel('$y,\mu m$')
#ax.set_zlim(0,4)
#ax.set_zticks([0,2,4])
ax.plot_wireframe(X,Y,Z,linewidth=0.6, color='k',ccount=80,rcount=80)
ax.elev = 85
ax.azim = 0
#ax.text(0, 2.2, r'$rotated : %.4f rad$'%theta, fontsize=15)
dirname = "./movie2D2/"
if not os.path.exists(dirname):
os.makedirs(dirname)
plt.tight_layout()
plt.axis('off')
#plt.show()
plt.savefig(dirname+'{:4.0f}'.format(i)+'.tif',bbox_inches='tight',pad_inches=0)
plt.close()
progressbar.progressbar_tty(i, framenumber, 1)
print "finished!"
print(Fore.CYAN)
print "Total running time:", time.time()-start, 'seconds'
print(Style.RESET_ALL)
<file_sep>import numpy as np
import cv2
img = cv2.imread('test.tif',0)
img = img.astype('float')
img /= 255.
#print img.sum()/(img.shape[0]*img.shape[1])
print img.sum()/len(img.flat)
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from boundaryv.brownian_gas import findnearest
class Particle:
def __init__(self):
self.position = np.array([0.,0.])
self.velocity = np.array([0.,0.])
self.repelforce = np.zeros(2)
def accelerate(self, acceleration):
self.velocity += acceleration
def move(self,velocity):
self.position += self.velocity
class Disk(Particle):
def __init__(self, mass, radius):
Particle.__init__(self) # __init__ of base class is overwritten by subclass __init__
self.radius = radius
self.mass = mass
def touch(particle1pos, particle2pos, particle1size, particle2size):
""" Calculate overlap of 2 particles """
overlap = -np.linalg.norm(particle1pos-particle2pos)+(particle1size + particle2size)
if overlap > 0.:
return overlap
else:
return 0.
def tchbnd(particle_position, radius, boxsize):
# boxsize is a tuple: horizontal, vertical
tchbndlist = [0,0,0,0] # [W,N,E,S]
xtemp = particle_position[0]
ytemp = particle_position[1]
if xtemp<=radius:
tchbndlist[0] = 1
if xtemp>=(boxsize[0]-radius):
tchbndlist[2] = 1
if ytemp>=(boxsize[1]-radius):
tchbndlist[1] = 1
if ytemp<=radius:
tchbndlist[3] = 1
return tchbndlist
class Environment:
def __init__(self, boxsize, lower_doorbnd, upper_doorbnd, totnum, dt, repel_coeff, friction_coeff, belt_velocity):
# boxsize is a tuple: horizontal, vertical
# lower_doorbnd is a np array coordinate
self.boxsize = boxsize
self.lower_doorbnd = lower_doorbnd
self.upper_doorbnd = upper_doorbnd
self.totnum = totnum
self.particle_position_array = np.empty((self.totnum,2))
self.particle_position_array[:] = np.nan
self.particle_list = [0]*self.totnum
self.dt = dt
self.repel_coeff = repel_coeff
self.friction_coeff = friction_coeff
self.belt_velocity = belt_velocity
def create_disks(self, mass, radius):
print 'Creating particles...'
for n in range(0,self.totnum):
overlap = 1
out_of_bnd = 1
while overlap or out_of_bnd:
disk = Disk(mass, radius)
disk.position[0] = np.random.uniform(radius, self.boxsize[0]-radius)
disk.position[1] = np.random.uniform(radius, self.boxsize[1]-radius)
try:
nearest_idx = findnearest(disk.position, self.particle_position_array)
overlap = touch(disk.position, self.particle_position_array[nearest_idx], radius, radius)
tchbndlist = tchbnd(disk.position, disk.radius, self.boxsize)
out_of_bnd = sum(tchbndlist)
except ValueError:
# just for the first particle creation, self.particle_position_array could be all nan, which would raise a ValueError when using findnearest
break
self.particle_position_array[n,:] = disk.position
self.particle_list[n] = disk
processbar.processbar(n+1, self.totnum, 1)
def read_positions(self, mass, radius):
self.particle_position_array = np.load('initial_positions_real_try.npy')
for n in range(0, self.totnum):
disk = Disk(mass, radius)
disk.position = self.particle_position_array[n,:]
self.particle_list[n] = disk
def visualize(self):
fig = plt.figure(figsize=(8.0,5.0))
for disk in self.particle_list:
circle = plt.Circle(disk.position, disk.radius, fill = False, linewidth=0.3)
fig.gca().add_artist(circle)
plt.plot((0,0),(0,self.lower_doorbnd[1]), 'k', linewidth=0.3)
plt.plot((0,0),(self.upper_doorbnd[1], self.boxsize[1]), 'k', linewidth=0.3)
plt.axis([-0.3*self.boxsize[0],self.boxsize[0], 0,self.boxsize[1]])
plt.axes().set_aspect('equal')
#plt.show()
def assign_repel(self):
repel_list = []
overlap_list = []
overlapsum = 0.
for particle in self.particle_list:
particle.repelforce = np.zeros(2)
# Clear assigned forces from the last iteration.
for n, particle in enumerate(self.particle_list):
for i, particle_position in enumerate(self.particle_position_array):
if i != n: # Exclude itself
overlap = touch(particle.position, particle_position, particle.radius, particle.radius)
unit_vector = (particle.position-particle_position)/np.linalg.norm((particle.position-particle_position))
particle.repelforce += self.repel_coeff * unit_vector * overlap
overlapsum += overlap
repel_list.append(particle.repelforce[0])
repel_list.append(particle.repelforce[1])
overlap_list.append(overlapsum)
return repel_list, overlap_list
def assign_beltfriction(self):
friction_list = []
for n, particle in enumerate(self.particle_list):
unit_vector = (self.belt_velocity-particle.velocity)/np.linalg.norm((self.belt_velocity-particle.velocity))
particle.beltfriction = 9.8 * particle.mass * self.friction_coeff * unit_vector
friction_list.append(particle.beltfriction[0])
friction_list.append(particle.beltfriction[1])
return friction_list
def wall_interact(self):
for particle in self.particle_list:
if particle.position[0]<=particle.radius and particle.position[1]<=self.upper_doorbnd[1] and particle.position[1]>=self.lower_doorbnd[1]: # takes care of the situation when a particle hits the corners of the doorbnd
if np.linalg.norm(particle.position-self.lower_doorbnd) <= particle.radius and particle.position[1]>=self.lower_doorbnd[1]:
unit_vector = -(particle.position-self.lower_doorbnd)/np.linalg.norm(particle.position-self.lower_doorbnd)
normal_velocity = np.dot(particle.velocity,unit_vector)
if normal_velocity > 0:
particle.velocity = particle.velocity - unit_vector * normal_velocity
if np.linalg.norm(particle.position-self.upper_doorbnd) <= particle.radius and particle.position[1]<=self.upper_doorbnd[1]:
unit_vector = -(particle.position-self.upper_doorbnd)/np.linalg.norm(particle.position-self.upper_doorbnd)
normal_velocity = np.dot(particle.velocity,unit_vector)
if normal_velocity > 0:
particle.velocity = particle.velocity - unit_vector * normal_velocity
elif particle.position[0] > 0.: # takes care of the situation when a particle hits other part of the wall
tchbndlist = tchbnd(particle.position, particle.radius, self.boxsize)
if tchbndlist[0] * particle.velocity[0] < 0.:
particle.velocity[0] = 0.
if tchbndlist[2] * particle.velocity[0] > 0.:
particle.velocity[0] = 0.
if tchbndlist[1] * particle.velocity[1] > 0.:
particle.velocity[1] = 0.
if tchbndlist[3] * particle.velocity[1] < 0.:
particle.velocity[1] = 0.
def accelerate(self):
for particle in self.particle_list:
particle.force = particle.beltfriction + particle.repelforce
particle.velocity += self.dt*particle.force/particle.mass
def move(self):
for n, particle in enumerate(self.particle_list):
particle.position += self.dt*particle.velocity
self.particle_position_array[n,:] = particle.position
def update(self):
repel_list, overlap_list = self.assign_repel()
#f = open('./resultsfile.txt', 'a')
#print >> f, ''.join('{:<+10.2f}'.format(e) for e in repel_list)
friction_list = self.assign_beltfriction()
#f = open('./resultsfile.txt', 'a')
#print >> f, ''.join('{:<+10.2f}'.format(e) for e in friction_list)
#result_list = overlap_list + repel_list+friction_list
#f = open('./resultsfile.txt', 'a')
#print >> f, ''.join('{:<+7.1f}'.format(e) for e in result_list)
self.accelerate()
self.wall_interact()
self.move()
def measure_pass(self):
pass_number = sum(e<0 for e in self.particle_position_array[:,0])
return pass_number
if __name__ == '__main__':
import matplotlib.pyplot as plt
import processbar
import os
import subprocess
import time
start = time.time()
open('resultsfile.txt', 'w').close()
env = Environment(boxsize=(0.6,0.4), \
lower_doorbnd=np.array([0,0]), \
upper_doorbnd=np.array([0,0.06]), \
totnum=500, \
dt=0.005, \
repel_coeff=100, \
friction_coeff=0.5, \
belt_velocity=np.array([-0.02,0]))
#env.create_disks(mass = 0.005, radius = 0.010)
env.read_positions(mass = 0.005, radius = 0.010)
for disk in env.particle_list:
print disk.position
totframe = 1200
passnumber_list = []
for i in range(totframe):
env.update()
if i%3==0:
env.visualize()
plt.savefig('./movie_try/'+'{:4.0f}'.format(i)+'.tif', dpi = 200)
plt.close()
pass_number = env.measure_pass()
passnumber_list.append(pass_number)
#if i == 2000:
# np.save('initial_positions_real_try', env.particle_position_array)
processbar.processbar(i+1, totframe, 1)
#subprocess.call('less resultsfile.txt', shell=False)
g = open('passnumber.txt', 'w')
print >> g, passnumber_list
np.save('passnumber_list_real', passnumber_list)
end = time.time()
print end-start
#plt.plot(passnumber_list)
#plt.show()
<file_sep>import matplotlib.pyplot as plt
import processbar
import os
import subprocess
import time
from door_position.disks import *
for batchiter in range(8):
print 'processing iteration {:d}'.format(batchiter)
start = time.time()
env = Environment(boxsize=(0.6,0.4), \
lower_doorbnd=np.array([0,batchiter*0.02+0.01]), \
upper_doorbnd=np.array([0,batchiter*0.02+0.06+0.01]), \
totnum=500, \
dt=0.005, \
repel_coeff=100, \
friction_coeff=0.5, \
belt_velocity=np.array([-0.05,0]))
#env.create_disks(mass = 10, radius = 5)
env.read_positions(mass = 0.005, radius = 0.010)
#for disk in env.particle_list:
# print disk.position
totframe = 1200
passnumber_list = []
if not os.path.exists('./passnumber_door_position_v5cm'):
os.makedirs('./passnumber_door_position_v5cm')
for i in range(totframe):
env.update()
if i%3==0:
#env.visualize()
#plt.savefig('./movie32/'+'{:4.0f}'.format(i)+'.tif', dpi = 300)
#plt.close()
pass_number = env.measure_pass()
passnumber_list.append(pass_number)
#if i == 1000:
# np.save('initial_positions', env.particle_position_array)
processbar.processbar(i+1, totframe, 1)
#subprocess.call('less resultsfile.txt', shell=False)
#g = open('passnumber.txt', 'w')
#print >> g, passnumber_list
np.save('./passnumber_door_position_v5cm/passnumber_list_append {:d}'.format(batchiter), passnumber_list)
end = time.time()
print 'time consumption', end-start,'s'
#plt.plot(passnumber_list)
#plt.show()
<file_sep>#!/usr/bin/env python
from __future__ import division
import sys
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
from scipy import signal
def equalize(img_array):
"""
returns array with float 0-1
"""
equalized = exposure.equalize_hist(img_array)
return equalized
def difference(data_img, generated_img):
"""
both images have to be 0-1float
"""
diff_value = np.sum((data_img-generated_img)**2)
return diff_value
def surface_polynomial(size, coeff):
def poly(x, y):
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
def nl(coeff, data_img):
"""
negative likelyhood-like function; aim to minimize this
data_img has to be 0-1float
"""
height = surface_polynomial(data_img.shape, coeff)
expected= 1+ np.cos(4*np.pi*height/0.532)
#expected= 1+ signal.square((4*np.pi/0.532)*height)
expected /= expected.max()#normalize to 0-1float
#expected = equalize(expected)
return difference(data_img, expected)
def surface_polynomial_dc(size, coeff,c):
def poly(x, y):
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+c/1000.
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:, None])
return zz
def nl_dc(coeff, data_img):
"""
constant decoupled
"""
clist =range(0,int(532/4),40)#varying c term in surface_polynomial to make stripes change at least 1 cycle
difflist = [0]*len(clist)
for cindx,c in enumerate(clist):
height = surface_polynomial_dc(data_img.shape,coeff,c)
expected= 1+ np.cos(4*np.pi*height/0.532)
expected /= expected.max()#normalize to 0-1float
#expected = equalize(expected)
difflist[cindx] = difference(data_img, expected)
return min(difflist)/max(difflist)
if __name__ == "__main__":
from scipy.ndimage import gaussian_filter
import time
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
N = 50 #a,b value resolution; a, b linear term coeff
sample_size = 60#a, b value range
start = time.time()
data_img = cv2.imread('sample5.tif', 0)
fitimg = np.copy(data_img)
xstore = {}
dyy,dxx = 100,100
yy,xx = 0,0
patchysize, patchxsize = 100,100
zoomfactory,zoomfactorx = 1,1
data_patch = data_img[yy:yy+patchysize,xx:xx+patchxsize]
data_patch= gaussian_filter(data_patch,sigma=0)
data_patch = data_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
alist = np.linspace(-sample_size,sample_size,2*N) # x direction
blist = np.linspace(0, sample_size,N) # y direction
#alist = np.linspace(-0.030,0.030,150) # x direction
#blist = np.linspace(-0.030,0.030,150) # y direction
aa, bb = np.meshgrid(alist,blist)
nl_1storder = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.*len(alist))**2:#remove central region to avoid 0,0 global min
nl_1storder[j,i] = np.nan
else:
nl_1storder[j,i] = nl([0,0,0,aa[j,i],bb[j,i],0],data_patch)
#nl_1storder[j,i] = nl_dc([0,0,0,aa[j,i],bb[j,i]],data_patch)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - start
print "took %.2f seconds to compute the negative likelihood" % elapsed
index = np.unravel_index(np.nanargmin(nl_1storder), nl_1storder.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeff_linear= np.array([0,0,0,index[0],index[1],0])
print initcoeff_linear
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, initcoeff_linear))
generated_intensity /= generated_intensity.max()
#generated_intenity = equalize(generated_intensity)
plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
plt.show()
nlmin = nl_1storder[~np.isnan(nl_1storder)].min()
nlmax = nl_1storder[~np.isnan(nl_1storder)].max()
fig = plt.figure()
print nl_1storder.shape
nl_1storder[np.isnan(nl_1storder)] = 0
ax = fig.add_subplot(111)
plt.tick_params(bottom='off',labelbottom='off',left='off',labelleft='off')
ax.set_aspect('equal')
print nlmin,nlmax
im = ax.imshow(nl_1storder,cmap='RdBu',norm=mpl.colors.Normalize(vmin=nlmin,vmax=nlmax))
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes('right',size='3%',pad='2%')
cbar = colorbar(im,cax = cax,ticks=[nlmin,nlmax])
#cbar.ax.set_yticklabels(['%.1fmm/s'%lowlim,'%.1fmm/s'%78,'%.1fmm/s'%highlim])
#fig = plt.figure()
#plt.contour(aa, bb, nl_1storder, 100)
#ax = fig.add_subplot(111, projection='3d')
#ax.plot_wireframe(aa,bb,nl_1storder)
#plt.ylabel("coefficient a")
#plt.xlabel("coefficient b")
#plt.gca().set_aspect('equal', adjustable = 'box')
#plt.colorbar()
plt.show()
print 'time used', time.time()-start, 's'
print 'finished'
<file_sep>from __future__ import division
import scipy.misc
import numpy as np
def partial_derivative_wrapper(func, var, point):
"""
Returns the partial derivative of a function 'func' with
respect to 'var'-th variable at point 'point'
Scipy hasn't provided a partial derivative function.
This is a simple wrapper from http://stackoverflow.com/questions/20708038/scipy-misc-derivative-for-mutiple-argument-function
func: callable name
var, point: the variable with respect to which and
the point at which partial derivative is needed.
usage:
df(x,y)/dx|(3,2)
partial_derivative(f, 0, [3,2])
CONFUSION: 'point' has to be a list. Using numpy array
doesn't work.
"""
args = point[:]
def reduce_variable(x):
"""
Returns a function where all except the 'var'-th variable
take the value of 'args'.
"""
args[var] = x
return func(*args)
return scipy.misc.derivative(reduce_variable, point[var], dx=1e-6)
def derivative(f, x, dx=1e-6):
return (f(x+dx)-f(x))/dx
def partial_derivative(f, x, y, dx=1e-6, dy=1e-6):
"""
Usage:
for N points simultaneously:
partial_derivative(f, *'Nx2 array of points'.T)
returns=np.array ([[df/dx1,df/dy1],
[df/dx2,df/dy2],
[df/dx3,df/dy3]
.
.
.
[df/dxN,df/dyN]])
for 1 point:
partial_derivative(f, *np.array([3,2]))
returns np.array([df/dx,df/dy])
"""
dfdx = (f(x+dx,y)-f(x,y))/dx
dfdy = (f(x,y+dy)-f(x,y))/dy
#try:
# result = np.empty((len(x),2))
# result[:,0] = dfdx
# result[:,1] = dfdy
#except TypeError:
# result = np.empty((2,))
# result[0] = dfdx
# result[1] = dfdy
result = np.array((dfdx, dfdy))
return result.T
if __name__ == "__main__":
import time
import numpy as np
def g(x):
return x**2
def f(x,y):
return x**2 + y**3
# df/dx should be 2x
# df/dy should be 3y^2
start = time.time()
result = partial_derivative(f,*np.array([[3,1], [3,1],[3,2],[1,2],[0,2]]).T)
result2 = partial_derivative(f, *np.array([3,1]))
result3 = derivative(g,np.array([1,2,3]))
print time.time()-start
print "vectorized:", result
print "single argument:", result2, type(result2)
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r',
edgecolor='#1f77b4', errorcolor='k',alpha=1):
"""
Call function to create error boxes
_ = make_error_boxes(ax, x, y, xerr, yerr)
plt.show()
"""
# Create list for all the error patches
errorboxes = []
# Loop over data points; create box from errors at each point
for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T):
rect = Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
errorboxes.append(rect)
# Create patch collection with specified colour/alpha
pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha,
edgecolor=edgecolor,lw=0.5)
# Add collection to axes
ax.add_collection(pc)
# Plot errorbars
artists = ax.errorbar(xdata, ydata, xerr=xerror, yerr=yerror,
fmt='None', ecolor=errorcolor)
return artists
<file_sep>#!/usr/bin/env python
from __future__ import division
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
def equalize(img_array):
"""
returns array with float 0-1
"""
equalized = exposure.equalize_hist(img_array)
return equalized
def difference(data_img, generated_img):
"""
both images have to be 0-1float
"""
diff_value = np.sum((data_img-generated_img)**2)
return diff_value
def surface_polynomial(size, coeff):
def poly(x, y):
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
def nl(coeff, data_img):
"""
negative likelyhood-like function; aim to minimize this
data_img has to be 0-1float
"""
height = surface_polynomial(data_img.shape,coeff)
expected= 1+ np.cos((4*np.pi/0.532)*height)
expected /= expected.max()#normalize to 0-1float
return difference(data_img, expected)
def accept_test(f_new,x_new,f_old,x_old):
#return True
if abs(x_new[3])>0.15 or abs(x_new[4])>0.15:
return False
else:
return True
def callback(x,f,accept):
#print x
pass
if __name__ == "__main__":
from scipy.ndimage import gaussian_filter
import time
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
N = 30 #a,b value resolution; a, b linear term coeff
sample_size = 0.15#a, b value range
start = time.time()
data_img = cv2.imread('sample.tif', 0)
fitimg = np.copy(data_img)
xstore = {}
dyy,dxx = 100,100
for yy in range(0,1400,dyy):
for xx in range(0,700,dxx):#xx,yy starting upper left corner of patch
patchysize, patchxsize = 100,100
zoomfactory,zoomfactorx = 1,1
data_patch = data_img[yy:yy+patchysize,xx:xx+patchxsize]
data_patch= gaussian_filter(data_patch,sigma=0)
data_patch = data_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
alist = np.linspace(0,sample_size,N) # x direction
blist = np.linspace(-sample_size, sample_size,2*N) # y direction
aa, bb = np.meshgrid(alist,blist)
nl_1storder = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.2*len(alist))**2:#remove central region to avoid 0,0 global min
nl_1storder[j,i] = np.nan
else:
nl_1storder[j,i] = nl([0,0,0,aa[j,i],bb[j,i],0],data_patch)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - start
print "took %.2f seconds to compute the negative likelihood" % elapsed
index = np.unravel_index(np.nanargmin(nl_1storder), nl_1storder.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeff_linear= np.array([0,0,0,index[0],index[1],0])
#print initcoeff_linear
initcoeff_extendlist = []
if (int(yy/dyy)-1,int(xx/dxx)) in xstore:
up = xstore[(int(yy/dyy)-1,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],up[2]*dyy+up[3],2*up[1]*dyy+up[4],up[1]*dyy*dyy+up[4]*dyy+up[5]]))
if (int(yy/dyy),int(xx/dxx)-1) in xstore:
left = xstore[(int(yy/dyy),int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx+left[3],left[2]*dxx+left[4],left[0]*dxx*dxx+left[3]*dxx+left[5]]))
else:
print 'no calculated neighbours found...'
if len(initcoeff_extendlist) > 0:
initcoeff_extend = np.mean(initcoeff_extendlist,axis=0)
else:
initcoeff_extend = initcoeff_linear
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, initcoeff_linear))
generated_intensity /= generated_intensity.max()
plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
#plt.show()
#initcoeff_extend = np.array([0,0,0,0,0,0])
iternumber = 0
while 1:
print 'iternumber =', iternumber,'for',xx,yy
result = basinhopping(nl, initcoeff_extend, niter = 100, T=100, stepsize=0.0001, interval=20,accept_test=accept_test,minimizer_kwargs={'method': 'Nelder-Mead', 'args': (data_patch)}, disp=True, callback=callback)
if result.fun < 520:
break
else:
initcoeff_extend = result.x
iternumber+=1
if iternumber == 2:
initcoeff_extend = initcoeff_linear
print 'using linear coefficients'
if iternumber == 2:
break
xopt = result.x
xstore[(int(yy/100),int(xx/100))]=xopt
#print xopt
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, xopt))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
#plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
#plt.show()
fitimg[yy:yy+patchysize,xx:xx+patchxsize] = 255*generated_intensity
cv2.imwrite('fitimg.tif', fitimg.astype('uint8'))
print 'time used', time.time()-start, 's'
print 'finished'
<file_sep>#!/usr/bin/env python
from __future__ import division, print_function
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
def normalize(img_array,normrange):
#elementmax = np.amax(img_array)
#elementmin = np.amin(img_array)
#ratio = (elementmax-elementmin)/normrange
#normalized_array = (img_array-elementmin)/(ratio+0.00001)
test = exposure.equalize_hist(img_array)
return test
def difference(reference_img, generated_img, normrange):
reference_img = normalize(reference_img, normrange)
generated_img = normalize(generated_img, normrange)
diff_value = np.sum((reference_img-generated_img)**2)
return diff_value
def surface_polynomial_1storder(size, max_variation, coeff1storder):
def poly(x, y):
poly = max_variation*(coeff1storder[0]*x+coeff1storder[1]*y)
return poly
x = np.linspace(0,size[0]-1, size[0])
y = np.linspace(0,size[1]-1, size[1])
zz = poly(x[:,None],y[None, :])
return zz
def nll_1storder(coeff1storder, max_variation, data, normrange):
#data = normalize(data, normrange)
height = surface_polynomial_1storder(data.shape, max_variation, coeff1storder)
#expected = normalize(1+np.cos((2/0.532)*height), normrange)
expected = 1+np.cos((2/0.532)*height)
# normalize to [0,1]
expected /= expected.max()
return difference(data, expected, normrange)
def surface_polynomial(size, max_variation, coeffhi,coeff1storder):
def poly(x, y):
#poly = max_variation*(coeff[0]*x+coeff[1]*y)
poly = max_variation*(1*coeffhi[0]*x**2+1*coeffhi[1]*y**2+1*coeffhi[2]*x*y+coeff1storder[0]*x+coeff1storder[1]*y+coeffhi[3])
return poly
x = np.linspace(0,size[0]-1, size[0])
y = np.linspace(0,size[1]-1, size[1])
zz = poly(x[:,None],y[None, :])
return zz
def nll(coeffhi,coeff1storder, max_variation, data, normrange):
#data = normalize(data, normrange)
height = surface_polynomial(data.shape, max_variation, coeffhi,coeff1storder)
#expected = normalize(1+np.cos((2/0.532)*height), normrange)
expected = 1+np.cos((2/0.532)*height)
# normalize to [0,1]
expected /= expected.max()
return difference(data, expected, normrange)
if __name__ == "__main__":
from scipy.optimize import fmin
import time
normrange=1
N = 14
sample_size = 15
t0 = time.time()
max_variation = 0.012
reference_intensity = cv2.imread('crop_small.tif', 0)
reference_intensity = normalize(reference_intensity,1)
#cv2.imwrite('normalized_crop.tif',255*reference_intensity)
alist = np.linspace(0,sample_size,N) # x direction
blist = np.linspace(-sample_size, sample_size,2*N) # y direction
aa, bb = np.meshgrid(alist,blist)
diff = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.*len(alist))**2:
diff[j,i] = np.nan
else:
coeff1storder = [aa[j,i],bb[j,i]]
diff[j,i] = nll_1storder(coeff1storder,max_variation,reference_intensity,1.0)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - t0
print("took %.2f seconds to compute the likelihood" % elapsed)
index = np.unravel_index(np.nanargmin(diff), diff.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeffhi = np.array([[0,0,0,0]])
coeff1storder = index
print(index)
simplex = 0.1*np.identity(4)+np.tile(initcoeffhi,(4,1))
simplex = np.concatenate((initcoeffhi,simplex),axis=0)
#xopt= fmin(nll, initcoeffhi, args = (coeff1storder,max_variation, reference_intensity, normrange))#, initial_simplex=simplex)
#print(xopt)
result = basinhopping(nll, initcoeffhi, niter = 4, T=200, stepsize=.1, minimizer_kwargs={'method': 'Nelder-Mead', 'args': (coeff1storder,max_variation, reference_intensity, normrange)}, disp=True)#, callback = lambda x, convergence, _: print('x = ', x))
xopt = result.x
print(result.x)
#fig = plt.figure()
##plt.contour(aa, bb, diff, 100)
#ax = fig.add_subplot(111, projection='3d')
#ax.plot_wireframe(aa,bb,diff)
#plt.ylabel("coefficient a")
#plt.xlabel("coefficient b")
#plt.gca().set_aspect('equal', adjustable = 'box')
#plt.colorbar()
#plt.show()
generated_intensity = normalize(1+np.cos((2/0.532)*surface_polynomial(reference_intensity.shape, max_variation,xopt,coeff1storder)), 1.0)#works for n=1 pocket
#cv2.imwrite('ideal_pattern.tif', 255*generated_intensity)
cv2.imshow('', np.concatenate((generated_intensity, reference_intensity), axis = 1))
cv2.waitKey(0)
#ax = fig.add_subplot(111, projection = '3d')
#ax.plot_surface(xx[::10,::10], yy[::10,::10], zz[::10,::10])
#plt.show()
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
data_img = cv2.imread('sample4.tif',0)
fitimg_whole = np.copy(data_img)
xstorebot = np.load('./xoptstore_bot.npy').item()
xstoreright = np.load('./xoptstore_right.npy').item()
xstoreleft = np.load('./xoptstore_left.npy').item()
xstoretopright= np.load('./xoptstore_top_right.npy').item()
xstoretopleft= np.load('./xoptstore_top_left.npy').item()
#xstore_badtiles=np.load('xoptstore_badtiles20180513_21_22_42.npy').item()
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111, projection='3d')
#ax.set_aspect('equal','box')
#bot
width=0.8
dyy,dxx = 81,81
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstorebot:
xopt = xstorebot[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
ax.plot_wireframe(X,Y,height,rstride=int(dyy/2),cstride=int(dxx/2),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#right
dyy,dxx =int(41*np.tan(np.pi*52/180)),41
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoreright:
xopt = xstoreright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=35
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#left
dyy,dxx =int(42*np.tan(np.pi*53/180)),42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
#if xx>1430:
#continue
if (int(yy/dyy),int(xx/dxx)) in xstoreleft:
xopt = xstoreleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=44
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#topright
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopright:
xopt = xstoretopright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=84
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#topleft
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopleft:
xopt = xstoretopleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=82
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#cv2.imwrite('fitimg_whole.tif', fitimg_whole.astype('uint8'))
plt.show()
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy import interpolate
data_img = cv2.imread('sample4.tif',0)
data_img = data_img.astype('float64')
xstore = np.load('./xoptstore_bot.npy').item()
xstorebot = np.load('./xoptstore_bot.npy').item()
xstoreright = np.load('./xoptstore_right.npy').item()
xstoreleft = np.load('./xoptstore_left.npy').item()
xstoretopright= np.load('./xoptstore_top_right.npy').item()
xstoretopleft= np.load('./xoptstore_top_left.npy').item()
cl_img = cv2.imread('cl.tif',0)
cl2_img = cv2.imread('mask_bot_v2.tif',0)
fitimg_whole = np.copy(data_img)
cl2_img = cl2_img.astype('float64')
cl2_img /= 255.
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
#dyy,dxx =int(41*np.tan(np.pi*52/180)),41
floor = -89
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect(adjustable='datalim',aspect='equal')
ax.set_zlim(floor,0)
width = 0.8
dd=80
ddd=20
xxx = []
yyy = []
zzz = []
for i in range(0,cl_img.shape[0],ddd):
for j in range(0,cl_img.shape[1],ddd):
if cl_img[i,j] == 255:
xxx.append(j)
yyy.append(i)
zzz.append(floor)
#bot
dyy,dxx = 81,81
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstore:
xopt = xstore[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#xstart,xend = 1698,1942
#ystart,yend = 1726,2323
xstart,xend = 0,data_img.shape[1]
ystart,yend = 0,data_img.shape[0]
print 'interpolating'
f = interpolate.interp2d(xxx,yyy,zzz,kind='quintic')
print 'finish'
XX,YY = np.meshgrid(range(xstart,xend),range(ystart,yend))
ZZ = f(range(xstart,xend),range(ystart,yend))
ZZ*=cl2_img[ystart:yend,xstart:xend]
ZZ[ZZ == 0] =np.nan
ZZ[:,:300] = np.nan
ax.plot_wireframe(XX,YY,ZZ,rstride =80, cstride = 80, colors='k',lw=0.4)
#ax.contour3D(XX,YY,ZZ,50,cmap='binary')
cv2.imwrite('fitimg_whole.tif', fitimg_whole.astype('uint8'))
plt.show()
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
Rmin = 1
Rmax = 5
R = np.arange(Rmin,Rmax,0.01)
for U in np.arange(0.09,0.136,0.01):
v = 438*1e-6
rhs = np.sqrt(1e6*v*U/9.8)*np.sqrt(2/np.log(7.4*v/(2*R*1e-3*U)))
plt.plot(R, rhs)
plt.plot(R, R)
plt.ylim(Rmin,Rmax)
plt.ylim(Rmin,Rmax)
Re = 6*1e-3*0.1/v
print 'Re = ', Re
plt.show()
<file_sep>from __future__ import division
from ctypes import windll, create_string_buffer
import time
import sys
import struct
import subprocess
def progressbar_win_console(cur_iter, tot_iter, deci_dig):
"""
Presents the percentage and draws a progress bar.
Import at the begining of a file. Call at the end of a loop.
cur_iter: current iteration number. Counted from 1.
tot_iter: total iteration number.
deci_dig: decimal digits for percentage number.
Works for windows type console.
"""
csbi = create_string_buffer(22)
h = windll.kernel32.GetStdHandle(-11)
res = windll.kernel32.GetConsoleScreenBufferInfo(h,csbi)
(_,_,_,_,_,left,_,right,_,_,_) = struct.unpack('11h',csbi.raw)
# Grab console window width.
# Modified from http://stackoverflow.com/questions/17993814/why-the-irrelevant-code-made-a-difference
console_width = right-left+1
bar_width = int(console_width * 0.8)
tot_dig = deci_dig + 4 # to make sure 100.(4 digits) + deci_dig
percentage = '{:{m}.{n}f}%'.format(cur_iter*100/tot_iter, m = tot_dig, n = deci_dig)
numbar = bar_width*cur_iter/tot_iter
numbar = int(numbar)
sys.stdout.write(percentage)
sys.stdout.write("[" + unichr(0x2588)*numbar + " "*(bar_width-numbar) + "]")
sys.stdout.flush()
sys.stdout.write('\r')
if cur_iter == tot_iter:
sys.stdout.write('\n')
def progressbar_tty(cur_iter, tot_iter, deci_dig):
"""
Presents the percentage and draws a progress bar.
Import at the begining of a file. Call at the end of a loop.
cur_iter: current iteration number. Counted from 1.
tot_iter: total iteration number.
deci_dig: decimal digits for percentage number.
Works for linux type terminal emulator.
"""
#rows, columns = subprocess.check_output(['stty', 'size']).split()
# Grab width of the current terminal.
# Modified from http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
# won't work inside vim using "\r"
columns = subprocess.check_output(['tput','cols'])
rows = subprocess.check_output(['tput','lines'])
columns = int(columns)
bar_width = int(columns* 0.8)
tot_dig = deci_dig + 4 # to make sure 100.(4 digits) + deci_dig
percentage = '{:{m}.{n}f}%'.format(cur_iter*100/tot_iter, m = tot_dig, n = deci_dig)
numbar = bar_width*cur_iter/tot_iter
numbar = int(numbar)
sys.stdout.write(percentage)
sys.stdout.write("[" + u'\u2588'.encode('utf-8')*numbar + " "*(bar_width-numbar) + "]")
sys.stdout.flush()
sys.stdout.write('\r')
if cur_iter == tot_iter:
sys.stdout.write('\n')
<file_sep>#!/usr/bin/env python
from __future__ import division
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
def equalize(img_array):
"""
returns array with float 0-1
"""
equalized = exposure.equalize_hist(img_array)
return equalized
def difference(data_img, generated_img):
"""
both images have to be 0-1float
"""
diff_value = np.sum((data_img-generated_img)**2)
return diff_value
def surface_polynomial(size, max_variation, coeff,c):
def poly(x, y):
poly = max_variation*(coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y)+c/1000.
return poly
x = np.linspace(0,size[0]-1, size[0])
y = np.linspace(0,size[1]-1, size[1])
zz = poly(x[None,:],y[:,None])
return zz
def nl(coeff, max_variation, data_img):
"""
negative likelyhood-like function; aim to minimize this
data_img has to be 0-1float
"""
clist =range(0,int(532/4),66)#varying c term in surface_polynomial to make stripes change at least 1 cycle
difflist = [0]*len(clist)
for cindx,c in enumerate(clist):
height = surface_polynomial(data_img.shape, max_variation,coeff,c)
expected= 1+ np.cos(4*np.pi*height/0.532)
expected /= expected.max()#normalize to 0-1float
difflist[cindx] = difference(data_img, expected)
return min(difflist)/max(difflist)
if __name__ == "__main__":
from scipy.ndimage import gaussian_filter
import time
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
N = 40 #a,b value resolution; a, b linear term coeff
sample_size = 40#a, b value range
start = time.time()
max_variation = 0.001
data_img = cv2.imread('sample.tif', 0)
fitimg = np.copy(data_img)
for yy in range(100,1400,100):
for xx in range(200,700,100):#xx,yy starting upper left corner of patch
patchysize, patchxsize = 100,100
zoomfactory,zoomfactorx = 1,1
data_patch = data_img[yy:yy+patchysize,xx:xx+patchxsize]
data_patch= gaussian_filter(data_patch,sigma=0)
data_patch = data_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
alist = np.linspace(0,sample_size,N) # x direction
blist = np.linspace(-sample_size, sample_size,2*N) # y direction
aa, bb = np.meshgrid(alist,blist)
nl_1storder = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.2*len(alist))**2:#remove central region to avoid 0,0 gloabal min
nl_1storder[j,i] = np.nan
else:
nl_1storder[j,i] = nl([0,0,0,aa[j,i],bb[j,i]],max_variation,data_patch)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - start
print "took %.2f seconds to compute the negative likelihood" % elapsed
index = np.unravel_index(np.nanargmin(nl_1storder), nl_1storder.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeff= np.array([0,0,0,index[0],index[1]])
print initcoeff
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, max_variation,initcoeff,0))
generated_intensity /= generated_intensity.max()
plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
plt.show()
iternumber = 0
itermax = 3
while 1:
print 'iternumber =', iternumber
result = basinhopping(nl, initcoeff, niter = 50, T=2000, stepsize=.01, minimizer_kwargs={'method': 'Nelder-Mead', 'args': (max_variation, data_patch)}, disp=True)#, callback = lambda x, convergence, _: print('x = ', x))
if result.fun < 0.25:
break
else:
iternumber+=1
if iternumber == itermax:
break
initcoeff = result.x
xopt = result.x
print xopt
clist =range(0,int(532/2),4)
difflist = [0]*len(clist)
for cindx,c in enumerate(clist):
height = surface_polynomial(data_patch.shape, max_variation,xopt,c)
expected= 1+ np.cos(4*np.pi*height/0.532)
expected /= expected.max()
difflist[cindx] = difference(data_patch, expected)
c = clist[np.argmin(difflist)]
print [int(x) for x in difflist]
print 'c =', c
#fig = plt.figure()
##plt.contour(aa, bb, diff, 100)
#ax = fig.add_subplot(111, projection='3d')
#ax.plot_wireframe(aa,bb,diff)
#plt.ylabel("coefficient a")
#plt.xlabel("coefficient b")
#plt.gca().set_aspect('equal', adjustable = 'box')
#plt.colorbar()
#plt.show()
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, max_variation,xopt,c))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
plt.show()
fitimg[yy:yy+patchysize,xx:xx+patchxsize] = 255*generated_intensity
cv2.imwrite('fitimg.tif', fitimg.astype('uint8'))
#cv2.imshow('', np.concatenate((generated_intensity, data_patch), axis = 1))
#cv2.waitKey(0)
#ax = fig.add_subplot(111, projection = '3d')
#ax.plot_surface(xx[::10,::10], yy[::10,::10], zz[::10,::10])
#plt.show()
print 'time used', time.time()-start, 's'
print 'finished'
<file_sep>#!/usr/bin/env python
from __future__ import division, print_function
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
def normalize(img_array,normrange):
#elementmax = np.amax(img_array)
#elementmin = np.amin(img_array)
#ratio = (elementmax-elementmin)/normrange
#normalized_array = (img_array-elementmin)/(ratio+0.00001)
test = exposure.equalize_hist(img_array)
return test
def difference(reference_img, generated_img, normrange):
reference_img = normalize(reference_img, normrange)
generated_img = normalize(generated_img, normrange)
diff_value = np.sum((reference_img-generated_img)**2)
return diff_value
def vary_surface_polynomial(size, max_variation, coeff):
def poly(x, y):
poly = max_variation*(coeff[0]*x+coeff[1]*y)
return poly
x = np.linspace(0,size[0]-1, size[0])
y = np.linspace(0,size[1]-1, size[1])
zz = poly(x[:,None],y[None, :])
return zz
def nll(ab, max_variation, data, normrange):
#data = normalize(data, normrange)
height = vary_surface_polynomial(data.shape, max_variation, ab)
#expected = normalize(1+np.cos((2/0.532)*height), normrange)
expected = 1+np.cos((2/0.532)*height)
# normalize to [0,1]
expected /= expected.max()
return difference(data, expected, normrange)
if __name__ == "__main__":
from scipy.optimize import fmin
import time
normrange=1
N = 50
sample_size = 15
t0 = time.time()
max_variation = 0.012
reference_intensity = cv2.imread('crop.tif', 0)
reference_intensity = normalize(reference_intensity,1)
#cv2.imwrite('normalized_crop.tif',255*reference_intensity)
alist = np.linspace(0,sample_size,N) # x direction
blist = np.linspace(-sample_size, sample_size,2*N) # y direction
aa, bb = np.meshgrid(alist,blist)
diff = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.*len(alist))**2:
diff[j,i] = np.nan
else:
diff[j,i] = nll((aa[j,i],bb[j,i]),max_variation,reference_intensity,1.0)
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - t0
print("took %.2f seconds to compute the likelihood" % elapsed)
index = np.unravel_index(np.nanargmin(diff), diff.shape)
print(diff[index])
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
print(index)
xopt= fmin(nll, index, args = (max_variation, reference_intensity, normrange), initial_simplex=[index, index+(0,0.01), index+(0.01,0)])
print(xopt)
fig = plt.figure()
#plt.contour(aa, bb, diff, 100)
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(aa,bb,diff)
plt.ylabel("coefficient a")
plt.xlabel("coefficient b")
#plt.gca().set_aspect('equal', adjustable = 'box')
#plt.colorbar()
plt.show()
generated_intensity = normalize(1+np.cos((2/0.532)*vary_surface_polynomial(reference_intensity.shape, max_variation, index)), 1.0)#works for n=1 pocket
#cv2.imwrite('ideal_pattern.tif', 255*generated_intensity)
cv2.imshow('', np.concatenate((generated_intensity, reference_intensity), axis = 1))
cv2.waitKey(0)
#ax = fig.add_subplot(111, projection = '3d')
#ax.plot_surface(xx[::10,::10], yy[::10,::10], zz[::10,::10])
#plt.show()
<file_sep>import matplotlib.pyplot as plt
circle1=plt.Circle((0,0),.2,color='r')
circle2=plt.Circle((.5,.5),.2,color='b')
circle3=plt.Circle((1,1),.2,color='g',clip_on=False)
fig = plt.gcf()
fig.gca().add_artist(circle1)
fig.gca().add_artist(circle2)
fig.gca().add_artist(circle3)
plt.axis([0,2,0,2])
plt.axes().set_aspect('equal')
plt.show()
<file_sep>import scipy.optimize
def F(x):
return x[0], x[1]
def g(x):
return x-1
if __name__ == "__main__":
import numpy as np
sol = scipy.optimize.fsolve(F, np.array([1,1]))
x0 = scipy.optimize.root(g, 0)
print sol
print x0.x[0]
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
cmap = plt.get_cmap('tab10')
x = np.arange(0,20, 0.001)
red = 1+np.cos(4*np.pi*(x+0.630/4)/0.630)
amber = 1+ np.cos(4*np.pi*(x+0.59/4)/0.590)
green = 1+ np.cos(4*np.pi*(x+0.534/4)/0.534)
#plt.plot(x, red+amber)
#plt.plot(x, amber+green)
plt.title('green and amber')
#plt.plot(x, red, color=cmap(3))
plt.plot(x, green , color=cmap(2))
plt.plot(x, amber, color=cmap(1))
plt.show()
<file_sep>import ctypes
import time
start_time = time.time()
# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 40)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
time_1 = time.time()
print '1st file opened'
ctypes.windll.user32.SetCursorPos(200, 40)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
print '2nd file opened'
time_2 = time.time()
print start_time
print '%.5f' % time_1
print '%.5f' % time_2
<file_sep>from __future__ import division
def derivative(f, x, dx=1e-2):
return (f(x+dx)-f(x-dx))/(2*dx)
if __name__ == "__main__":
from mpmath import *
mp.dps =2
def f(x):
return x**4
print derivative(f, 1, dx=1e-8)-4
print derivative(f, 1, dx=-1e-8)-4
print diff(f,1.)
<file_sep>from __future__ import division
import numpy as np
import sys
dt = sys.argv[1] #0.005
while 1:
try:
intv = input('intervels(pix): ')
s = np.mean(intv)
percenterr = np.std(intv)/s
break
except Exception as e:
print e
while 1:
try:
R = input('mm/pix ratio: ')
r = float(R[0])/float(R[1])
U = s*r/float(dt)
dU = percenterr*U
break
except Exception as e:
print e
print '[average intv pix', s, 'pix]'
print 'U=', U,'mm/s'
print 'dU=', dU, 'mm/s'
<file_sep>def perform(args):
x = args[0]
return x, shape_function(args)
def shape_function(x):
return np.sin(x[0])+x[1]
if __name__ == "__main__":
import numpy as np
print perform((1,0,3))
<file_sep>#!/usr/bin/env python
from __future__ import division
import sys
from scipy import interpolate
import time
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import exposure
from scipy.optimize import basinhopping
from scipy import fftpack
from scipy import signal
def equalize(img_array):
"""
returns array with float 0-1
"""
equalized = exposure.equalize_hist(img_array)
#equalized = img_array/img_array.max()
return equalized
def difference(data_img, generated_img):
"""
both images have to be 0-1float
"""
diff_value = np.sum((data_img-generated_img)**2)
return diff_value
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
def nl(coeff, data_img,(zoomfactory,zoomfactorx)):
"""
negative likelyhood-like function; aim to minimize this
data_img has to be 0-1float
"""
height = surface_polynomial(data_img.shape,coeff,(zoomfactory,zoomfactorx))
expected= 1+ np.cos((4*np.pi/0.532)*height)
expected /= expected.max()#normalize to 0-1float
#expected = equalize(expected)
return difference(data_img, expected)
def accept_test(f_new,x_new,f_old,x_old):
#return True
if abs(x_new[3])>0.05 or abs(x_new[4])>0.05:
return False
else:
return True
def callback(x,f,accept):
#print x[3],x[4],f,accept
pass
if __name__ == "__main__":
from scipy.ndimage import gaussian_filter
import time
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from time import localtime, strftime
N = 30 #a,b value resolution; a, b linear term coeff
sample_size = 0.05#a, b value range
start = time.time()
data_img = cv2.imread('sample.tif', 0)
fitimg = np.copy(data_img)
xstore = {}
xstore_badtiles = {}
hstore_upperright = {}
hstore_lowerright = {}
hstore_lowerleft = {}
dyy,dxx = 200,200
zoomfactory,zoomfactorx = 2,2
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
print 'processing', (int(yy/dyy),int(xx/dxx))
data_patch = data_img[yy:yy+dyy,xx:xx+dxx]
data_patch= gaussian_filter(data_patch,sigma=0)
data_patch = data_patch[::zoomfactory,::zoomfactorx]
data_patch= equalize(data_patch)#float0-1
initcoeff_extendlist = []
if (int(yy/dyy)-1,int(xx/dxx)) in xstore:
print 'found up'
up = xstore[(int(yy/dyy)-1,int(xx/dxx))]
initcoeff_extendlist.append(np.array([up[0],up[1],up[2],up[2]*dyy+up[3],2*up[1]*dyy+up[4],up[1]*dyy*dyy+up[4]*dyy+up[5]]))
if (int(yy/dyy),int(xx/dxx)-1) in xstore:
print 'found left'
left = xstore[(int(yy/dyy),int(xx/dxx)-1)]
initcoeff_extendlist.append(np.array([left[0],left[1],left[2],2*left[0]*dxx+left[3],left[2]*dxx+left[4],left[0]*dxx*dxx+left[3]*dxx+left[5]]))
if len(initcoeff_extendlist) > 0:
initcoeff_extend = np.mean(initcoeff_extendlist,axis=0)
initcoeff = initcoeff_extend
else:
alist = np.linspace(-sample_size,sample_size,2*N) # x direction
blist = np.linspace(0, sample_size,N) # y direction
aa, bb = np.meshgrid(alist,blist)
nl_1storder = np.empty(aa.shape)
for i in np.arange(alist.size):
for j in np.arange(blist.size):
if (j-0.5*len(blist))**2+(i)**2<=(0.1*len(alist))**2:#remove central region to avoid 0,0 global min
nl_1storder[j,i] = np.nan
else:
nl_1storder[j,i] = nl([0,0,0,aa[j,i],bb[j,i],0],data_patch,(zoomfactory,zoomfactorx))
sys.stdout.write('\r%i/%i ' % (i*blist.size+j+1,alist.size*blist.size))
sys.stdout.flush()
sys.stdout.write('\n')
elapsed = time.time() - start
index = np.unravel_index(np.nanargmin(nl_1storder), nl_1storder.shape)
index = (alist[index[1]], blist[index[0]])
index = np.array(index)
initcoeff_linear= np.array([0,0,0,index[0],index[1],0])
initcoeff = initcoeff_linear
#generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, initcoeff_linear),(zoomfactory,zoomfactorx))
#generated_intensity /= generated_intensity.max()
#plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
#plt.show()
#initcoeff = np.array([0,0,0,0,0,0])
iternumber = 0
while 1:
print 'iternumber =', iternumber,'for',yy,xx
result = basinhopping(nl, initcoeff, niter = 50, T=100, stepsize=2e-5, interval=50,accept_test=accept_test,minimizer_kwargs={'method': 'Nelder-Mead', 'args': (data_patch,(zoomfactory,zoomfactorx))}, disp=False, callback=callback)
print result.fun
if result.fun <560:
xopt = result.x
break
else:
initcoeff = result.x
iternumber+=1
if iternumber == 20:
xopt = initcoeff_extend
break
initcoeff_extend = initcoeff_linear
#print 'using linear coefficients'
#if iternumber == 20:
# xopt = initcoeff_extend
# break
#print xopt
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial(data_patch.shape, xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
#plt.imshow(np.concatenate((generated_intensity,data_patch,(generated_intensity-data_patch)**2),axis=1))
#plt.show()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
clist = []
if (int(yy/dyy),int(xx/dxx)-1) in hstore_upperright:
print 'found upperright'
clist.append(hstore_upperright[(int(yy/dyy),int(xx/dxx)-1)])
if (int(yy/dyy)-1,int(xx/dxx)) in hstore_lowerleft:
print 'found lowerleft'
clist.append(hstore_lowerleft[(int(yy/dyy)-1,int(xx/dxx))])
if (int(yy/dyy)-1,int(xx/dxx)-1) in hstore_lowerright:
print 'found lowerright'
clist.append(hstore_lowerright[(int(yy/dyy)-1,int(xx/dxx)-1)])
if len(clist)>0:
print 'clist=', clist
if max(clist)-np.median(clist)>0.532/2:
clist.remove(max(clist))
print 'maxremove'
if np.median(clist)-min(clist)>0.532/2:
clist.remove(min(clist))
print 'minremove'
xopt[5] = np.mean(clist)
height = surface_polynomial(data_patch.shape, xopt,(zoomfactory,zoomfactorx))
hupperright = height[0,-1]
hlowerright = height[-1,-1]
hlowerleft = height[-1,0]
if iternumber <20:
print 'coeff & corner heights stored'
xstore[(int(yy/dyy),int(xx/dxx))]=xopt
hstore_upperright[(int(yy/dyy),int(xx/dxx))] = hupperright
hstore_lowerright[(int(yy/dyy),int(xx/dxx))] = hlowerright
hstore_lowerleft[(int(yy/dyy),int(xx/dxx))] = hlowerleft
else:
xstore_badtiles[(int(yy/dyy),int(xx/dxx))]=xopt
print (int(yy/dyy),int(xx/dxx)), 'is a bad tile'
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
ax.plot_wireframe(X,Y,height,rstride=20,cstride=20)
ax.set_aspect('equal')
plt.draw()
plt.pause(0.01)
cv2.imwrite('fitimg.tif', fitimg.astype('uint8'))
print '\n'
np.save('xoptstore'+strftime("%Y%m%d_%H_%M_%S",localtime()),xstore)
np.save('xoptstore_badtiles'+strftime("%Y%m%d_%H_%M_%S",localtime()),xstore_badtiles)
print 'time used', time.time()-start, 's'
print 'finished'
plt.show()
<file_sep>from __future__ import division
import numpy as np
import cv2
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
left0_img = cv2.imread('left0.tif',0)
left1_img = cv2.imread('left1.tif',0)
left2_img = cv2.imread('left2.tif',0)
left3_img = cv2.imread('left3.tif',0)
left4_img = cv2.imread('left4.tif',0)
leftflat_img = cv2.imread('leftflat.tif',0)
right0_img = cv2.imread('right0.tif',0)
right1_img = cv2.imread('right1.tif',0)
right2_img = cv2.imread('right2.tif',0)
right3_img = cv2.imread('right3.tif',0)
right4_img = cv2.imread('right4.tif',0)
xl=[]
yl=[]
zl=[]
xr=[]
yr=[]
zr=[]
dd=1
offsetl = 0
offsetr = 0
for i in range(252,1046,dd):
for j in range(505,1672,dd):
if left0_img[i,j] == 255:
xl.append(j)
yl.append(i)
zl.append(0+offsetl)
if left1_img[i,j] == 255:
xl.append(j)
yl.append(i)
zl.append(1*0.532/2+offsetl)
if left2_img[i,j] == 255:
xl.append(j)
yl.append(i)
zl.append(2*0.532/2+offsetl)
if left3_img[i,j] == 255:
xl.append(j)
yl.append(i)
zl.append(3*0.532/2+offsetl)
if left4_img[i,j] == 255:
xl.append(j)
yl.append(i)
zl.append(4*0.532/2+offsetl)
#if leftflat_img[i,j] == 255:
# xl.append(j)
# yl.append(i)
# zl.append(2.5*0.532/2)
for i in range(272,1012,dd):
for j in range(2579,3703,dd):
if right0_img[i,j] == 255:
xr.append(j)
yr.append(i)
zr.append(0+offsetr)
if right1_img[i,j] == 255:
xr.append(j)
yr.append(i)
zr.append(1*0.532/2+offsetr)
if right2_img[i,j] == 255:
xr.append(j)
yr.append(i)
zr.append(2*0.532/2+offsetr)
if right3_img[i,j] == 255:
xr.append(j)
yr.append(i)
zr.append(3*0.532/2+offsetr)
if right4_img[i,j] == 255:
xr.append(j)
yr.append(i)
zr.append(4*0.532/2+offsetr)
np.save('xleft.npy',xl)
np.save('yleft.npy',yl)
np.save('zleft.npy',zl)
np.save('xright.npy',xr)
np.save('yright.npy',yr)
np.save('zright.npy',zr)
"""
slicing = 1128
yslice = [y[i] for i in range(len(x)) if x[i] == slicing]
zslice = [z[i] for i in range(len(x)) if x[i] == slicing]
f = interpolate.interp1d(yslice,zslice,kind='linear')
xnew = np.arange(min(x),max(x))
ynew = np.arange(min(yslice),max(yslice))
znew = f(ynew)
#XX,YY = np.meshgrid(xnew,ynew)
#fig = plt.figure(figsize=(7,7))
#ax = fig.add_subplot(111,projection='3d')
#ax.set_zlim(0,1000)
#ax.plot_wireframe(XX,YY,znew)
#ax.scatter(x,y,z)
plt.plot(ynew,znew)
plt.scatter(yslice, zslice)
plt.show()
"""
<file_sep>from scipy.ndimage import label as lb
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('cl.tif',0)
labeled_array,num =lb(img,structure=[[1,1,1],[1,1,1],[1,1,1]])
plt.imshow(labeled_array)
plt.show()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
framenumber = 50
fig = plt.figure()
ax = fig.add_subplot(111)
d = {}
height_range = range(0,2000,100)
for i in height_range:
d["data%d"%i] = np.load("./output_test/center_array_%d.npy"%i)
d["data%d"%i] = d["data%d"%i][::1]
angles = np.linspace(0,0.06, framenumber)
angles = angles[::1]
plt.plot(angles, d["data%d"%i], 'o-', markersize =i/200)
ax.set_xlabel("rotated angle, $rad$")
ax.set_ylabel("center shift $\mu m$")
#plt.plot([q for q in height_range], [d["data%d"%k][-1] for k in height_range])
#ax.set_xlabel("center height, $\mu m$")
#ax.set_ylabel("center shift, $\mu m$")
plt.show()
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
theta = np.arange(0,0.02,0.001)
n1 = 1.5
n2 = 1
a1= np.pi/2
OB =500*1000
a2 = np.arccos((n2/n1)*np.sin(np.arcsin((n1/n2)*np.cos(a1)+2*theta)))
s = (np.sin((a1-a2)/2))**2
dL = -2*n1*OB*s
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
l, = plt.plot(theta,dL)
ax.set_ylim(-600,600)
ax.set_xlabel(r'$\theta$')
ax.set_ylabel('nm')
xa1slider = plt.axes([0.25,0.02,0.65,0.03])
xOBslider = plt.axes([0.25,0.05,0.65,0.03])
a1slider = Slider(xa1slider,'a1',np.pi/2-0.5,np.pi/2,valinit=np.pi/2-0.5)
OBslider = Slider(xOBslider,'OB',-500,1000,valinit=0)
def update(val):
OB = OBslider.val*1000
a1 = a1slider.val
a2 = np.arccos((n2/n1)*np.sin(np.arcsin((n1/n2)*np.cos(a1)+2*theta)))
s = (np.sin((a1-a2)/2))**2
dL = -2*n1*OB*s
#fig.canvas.draw_idle()
l.set_ydata(dL)
ax.set_ylim(-600,600)
a1slider.on_changed(update)
OBslider.on_changed(update)
plt.show()
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
colorimg = cv2.imread('DSC_5311.jpg').astype(float)
#colorimg = cv2.imread('crop.tif').astype(float)
blue, green, red = cv2.split(colorimg)
#red = red*90/80
cutoff = 100
ratio = green/(red+1e-6) #prevent diverging
ratio[ratio<1] = 1 #ratio<1 not real
lratio = np.log(ratio)
hist, bins = np.histogram(lratio.flat, bins=np.arange(0,2,0.01))
hist[np.where(hist <=cutoff)] = 0 # throw away count < cutoff
idx = np.nonzero(hist)
center = (bins[:-1] + bins[1:]) / 2
rmax = max(center[idx]) #rightmost barcenter for nonzero hist
rmin = np.min(lratio)
lratio[lratio<rmin] = rmin
lratio[lratio>rmax] = rmax
img = (255*(lratio-rmin)/(rmax-rmin))
#width = 0.1 * (bins[1] - bins[0])
#plt.hist(lratio.flat, bins=np.arange(0,4,0.01),color='red',alpha=1)
#plt.bar(center,hist,width=width)
#plt.show()
img = img.astype('uint8')
cv2.imwrite('img.tif',img)
cv2.imwrite('green.tif', green)
cv2.imwrite('red.tif', red)
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
data_img = cv2.imread('sample5.tif')
xstore = np.load('xoptstore_sample5.npy').item()
print xstore
#xstore_badtiles=np.load('xoptstore_badtiles20180513_21_22_42.npy').item()
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
dyy,dxx = 100,100
zoomfactory,zoomfactorx = 1,1
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal','box')
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstore:
xopt = xstore[(int(yy/dyy),int(xx/dxx))]
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(data_img.shape[0]-yy,data_img.shape[0]-yy-dyy,-zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
ax.plot_wireframe(X,Y,height,rstride=int(dxx/1),cstride=int(dyy/1))
plt.show()
<file_sep>from __future__ import division
import sys
contrast='uncalculated'
if len(sys.argv)>1:
contrast = (float(sys.argv[1])-float(sys.argv[2]))/(float(sys.argv[1])+float(sys.argv[2]))
print contrast
<file_sep>from __future__ import division
import scipy.optimize
import scipy.spatial.distance
#from scipy.misc import derivative
import partial_derivative
import math
import sys
#@profile
def shape_function(x):
#return np.exp(-0.00002*((x+250)**2))
#return -0.000008*(x**2)+ float(sys.argv[1])
return 0.00000001*x + float(sys.argv[1])
#return 0.00000001*x +68.362
#@profile
def find_k_refracting(k_incident, x1, n1,n2):
gradient = partial_derivative.derivative(shape_function, x1, dx=1e-6)
n = np.empty((2,))
n[0] = -gradient
n[1] = 1
#print "n = ", n
#print "x1 = ", x1
norm =np.linalg.norm(n)
n = n/norm # n is the unit normal vector pointing 'upward'
c = -np.dot(n, k_incident)
r = n1/n2
sqrtterm = (1-r**2*(1-c**2))
if sqrtterm < 0:
print(Fore.RED)
print "Total internal reflection occurred."
print "1-r**2*(1-c**2) = \n", sqrtterm
print(Style.RESET_ALL)
sys.exit(0)
factor = (r*c- math.sqrt(sqrtterm))
k_refracting = r*k_incident + factor*n
#print 'c =',c
#print "factor", factor
#print "k_refracting = ", k_refracting
return k_refracting
#@profile
def find_x0(k_incident, x1, n1,n2):
# def Fx(x):
# k_refracting = find_k_refracting(k_incident, x, n1, n2)
# return k_refracting[0]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[0]
# def Fy(x):
# k_refracting = find_k_refracting(k_incident, x, n1, n2)
# return k_refracting[1]*(shape_function(*x1)+shape_function(*x))+k_refracting[2]*(x1-x)[1]
# def F(x):
# return Fx(x), Fy(x)
def F(x):
k_refracting = find_k_refracting(k_incident, x, n1, n2)
return k_refracting[0]*(shape_function(x1)+shape_function(x))+k_refracting[1]*(x1-x)
#x0 = scipy.optimize.newton_krylov(F,x1,f_tol = 1e-3)
x0 = scipy.optimize.root(F,x1)
x0 = x0.x[0]
return x0
#@profile
def optical_path_diff(k_incident, x1, n1,n2):
x0 = find_x0(k_incident, x1, n1, n2)
p0 = np.empty((2,))
p1 = np.empty((2,))
p1_image_point = np.empty((2,))
p0[0] = x0
p1[0] = x1
p1_image_point[0] = x1
p0[1] = shape_function(x0)
p1[1] = shape_function(x1)
p1_image_point[1] = -shape_function(x1)
vec_x0x1 = p1-p0
norm = np.linalg.norm(vec_x0x1)
if norm == 0:
norm = 1
vec_x0x1 = vec_x0x1/norm
cos = np.dot(vec_x0x1, k_incident)
dist1 = np.linalg.norm(p0-p1)
dist2 = np.linalg.norm(p0-p1_image_point)
#print "vec_x0x1 = ", vec_x0x1
#print "cos = ", cos
#print "p0 = ", p0
#print "p1 = ", p1
#print "dist1 = ", dist1
#print "dist2 = ", dist2
OPD_part1 = dist1*cos*n1
OPD_part2 = dist2*n2
OPD = OPD_part2-OPD_part1
return OPD
#@profile
def pattern(opd):
intensity = 1+np.cos((2*np.pi/0.532)*opd)
return intensity
if __name__ == "__main__":
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.mlab import griddata
import numpy as np
import progressbar
import os
from itertools import product
import time
from colorama import Style, Fore
import find_center
import cookb_signalsmooth
start = time.time()
print "starting..."
i = 0
framenumber = 50
pltnumber = 300
pltlength = 500
center = 0
center_array = np.empty((framenumber, ))
coordinates = np.linspace(-pltlength, pltlength, pltnumber)
intensity = np.empty((pltnumber, ))
intensity2 = np.empty((pltnumber, ))
for theta in np.linspace(0.,0.0416,framenumber):
i += 1
#coordinates = np.array(list(product(np.linspace(-pltlength,pltlength,pltnumber), np.linspace(-pltlength, pltlength, pltnumber))))
q = 0
for detecting_point in coordinates:
opd = optical_path_diff(k_incident = np.array([np.sin(theta), -np.cos(theta)]),\
x1 = detecting_point,\
n1 = 1.5,\
n2 = 1)
intensity[q] = pattern(opd)
opd2= 2*68.362*np.cos(np.arcsin(1.5*np.sin(theta)))# from simple formula 2nhcos(j) for air gap for sanity check; should be close
intensity2[q] = pattern(opd2)
q+=1
#opd_expected = 2*shape_function(0)*np.cos(np.arcsin(np.sin(angle-0.0000001)*1.5)+0.0000001)
#print pattern(opd)
#print "error in OPD = " ,(opd-opd_expected)/0.532, "wavelength"
#fig = plt.figure(num=None, figsize=(8, 7), dpi=100, facecolor='w', edgecolor='k')
#np.save('intensity.npy', intensity)
#intensity_smooth = cookb_signalsmooth.smooth(intensity, 15)
#xcenter = find_center.center_position(intensity, coordinates,center)
#center = xcenter
#plt.plot(coordinates,intensity_smooth)
#plt.plot(coordinates,intensity)
#plt.show()
#center_array[i-1] = center
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('$x,\mu m$')
ax.set_ylim(0,2.5)
ax.plot(coordinates, intensity)
#ax.plot(coordinates[int(len(coordinates)/2):], intensity2[int(len(coordinates)/2):],'r') #for sanity check
ax.text(0, 2.2, r'$rotated : %.4f rad$'%theta, fontsize=15)
dirname = "./movie/"
if not os.path.exists(dirname):
os.makedirs(dirname)
plt.savefig(dirname+'{:4.0f}'.format(i)+'.tif')
plt.close()
progressbar.progressbar_tty(i, framenumber, 1)
if not os.path.exists("./output_test"):
os.makedirs("./output_test")
#np.save("./output_test/center_array_%d.npy"%int(sys.argv[1]), center_array)
print(Fore.CYAN)
print "Total running time:", time.time()-start, "seconds"
print(Style.RESET_ALL)
print "center height:", sys.argv[1]
print "Finished!"
#plt.plot(np.linspace(0,0.06, framenumber), center_array)
#plt.show()
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib as mpl
from scipy.signal import savgol_filter as sg
from scipy import interpolate
import os
from progressbar import progressbar_tty as ptty
data_img = cv2.imread('sample4.tif',0)
data_img = data_img.astype('float64')
cl_img = cv2.imread('cl.tif',0)
cl2_img = cv2.imread('cl2_larger.tif',0)
cl3_img = cv2.imread('cl3.tif',0)
edge_img = cv2.imread('cl_edge.tif',0)
thin_img = cv2.imread('thin.tif',0)
cl_img = cl_img.astype('float64')
cl_img /= 255.
cl2_img = cl2_img.astype('float64')
cl2_img /= 255.
cl3_img = cl3_img.astype('float64')
cl3_img /= 255.
edge_img = edge_img.astype('float64')
edge_img /= 255.
thin_img = thin_img.astype('float64')
thin_img /= 255.
fitimg_whole = np.copy(data_img)
xstorebot = np.load('./xoptstore_bot.npy').item()
xstoreright = np.load('./xoptstore_right.npy').item()
xstoreleft = np.load('./xoptstore_left.npy').item()
xstoretopright= np.load('./xoptstore_top_right.npy').item()
xstoretopleft= np.load('./xoptstore_top_left.npy').item()
floor = -86
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
fig = plt.figure(figsize=(7.5,7.5))
ax = fig.add_subplot(111, projection='3d')
#ax = fig.add_subplot(111)
#ax.set_aspect(aspect='equal')
ax.set_zlim(1.5*floor,-0.5*floor)
ax.set_xlim(0,data_img.shape[1])
ax.set_ylim(0,data_img.shape[0])
width = 0.8
xxx = []
yyy = []
zzz = []
ddd=1
#bot
dyy,dxx = 81,81
dd=7
zoomfactory,zoomfactorx = 1,1
print 'Plotting patterned areas...'
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstorebot:
xopt = xstorebot[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
if ((int(yy/dyy)+1,int(xx/dxx)) not in xstorebot) or ((int(yy/dyy)-1,int(xx/dxx)) not in xstorebot):
pass
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
#ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
#right
dyy,dxx =int(41*np.tan(np.pi*52/180)),41
zoomfactory,zoomfactorx = 1,1
dd =20
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx > 3850:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreright:
xopt = xstoreright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
height-=35
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
#ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
#left
dyy,dxx =int(42*np.tan(np.pi*53/180)),42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx>1421 or xx<332:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreleft:
xopt = xstoreleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=44
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
#ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#topright
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopright:
xopt = xstoretopright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=82
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
#ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#topleft
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopleft:
xopt = xstoretopleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=80.3
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*generated_intensity
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
xl = np.load('thin/xleft.npy')
yl = np.load('thin/yleft.npy')
zl = np.load('thin/zleft.npy')
xr = np.load('thin/xright.npy')
yr = np.load('thin/yright.npy')
zr = np.load('thin/zright.npy')
#thinpart
print 'Interpolating thin part...'
dxx=1
offsetl = -82-2.84+1.22
offsetr = -82-1.67
if os.path.exists('xxxthin.npy'):
xxxthin=np.load('xxxthin.npy')
yyythin=np.load('yyythin.npy')
zzzthin=np.load('zzzthin.npy')
print 'Thin part loaded from existing interpolation'
else:
xxxthin=[]
yyythin=[]
zzzthin=[]
for xx in range(505,1672,dxx):
slicing = xx
ylslice = [yl[i] for i in range(len(xl)) if xl[i] == slicing]
if len(ylslice)<2:
continue
zlslice = [zl[i]+offsetl for i in range(len(xl)) if xl[i] == slicing]
f = interpolate.interp1d(ylslice,zlslice,kind='linear')
ynew = np.arange(min(ylslice),max(ylslice),10)
znew = f(ynew)
xxxthin.extend([xx]*len(ynew))
yyythin.extend(ynew)
zzzthin.extend(znew)
#ax.plot_wireframe(X,Y,Z,rstride=int(dyy/1),cstride=int(dxx/1),colors='k',lw=0.4)
for xx in range(2579,3703,dxx):
slicing = xx
yrslice = [yr[i] for i in range(len(xr)) if xr[i] == slicing]
if len(yrslice)<2:
continue
zrslice = [zr[i]+offsetr for i in range(len(xr)) if xr[i] == slicing]
f = interpolate.interp1d(yrslice,zrslice,kind='linear')
ynew = np.arange(min(yrslice),max(yrslice),10)
znew = f(ynew)
xxxthin.extend([xx]*len(ynew))
yyythin.extend(ynew)
zzzthin.extend(znew)
#ax.plot_wireframe(X,Y,Z,rstride=int(dyy/1),cstride=int(dxx/1),colors='k',lw=0.4)
print 'Thin part interpolated and saved'
np.save('xxxthin.npy',xxxthin)
np.save('yyythin.npy',yyythin)
np.save('zzzthin.npy',zzzthin)
xxx.extend(xxxthin)
yyy.extend(yyythin)
zzz.extend(zzzthin)
#contact line
print 'Extracting contact line...'
x = []
y = []
xxxinterp=[]
yyyinterp=[]
zzzinterp=[]
for j in range(0,cl_img.shape[1],ddd):
#for j in range(0,2100,ddd):
for i in range(cl_img.shape[0]-1,0,-ddd):
if cl_img[i,j] == 1:
xxx.append(j)
yyy.append(i)
zzz.append(floor)
xxxinterp.append(j)
yyyinterp.append(i)
zzzinterp.append(floor)
x.append(j)
y.append(i)
break
#ptty(j,cl_img.shape[1]/ddd,1)
ax.plot(x,y, 'C1',zs=floor)
#x_edge=[]
#y_edge=[]
#z_edge=[]
#for i in range(0,edge_img.shape[0],2):
# for j in range(0,edge_img.shape[1],2):
# if edge_img[i,j] == 1:
# x_edge.append(j)
# y_edge.append(i)
# z_edge.append(znew[j,i])
#ax.scatter(x_edge,y_edge,z_edge,c='k',s=0.01)
print 'No.of points:', len(yyy)
print 'Longitudinal slicing...'
for slicing in range(0,4200,70):
#for slicing in (1500,1600,1700):
yyyslice = [yyy[i] for i in range(len(xxx)) if xxx[i]==slicing]
zzzslice = [zzz[i] for i in range(len(xxx)) if xxx[i]==slicing]
if len(yyyslice)<4:
continue
zzzslice = [s for _,s in sorted(zip(yyyslice, zzzslice))]#sort zzzslice according to yyyslice
yyyslice = sorted(yyyslice)
duplicates = dict((i,yyyslice.count(s)) for (i,s) in enumerate(np.unique(yyyslice)) if yyyslice.count(s)>1)
for i in duplicates:
zzzslice[i] = np.mean(zzzslice[i:i+duplicates[i]])
zzzslice[i+1:i+duplicates[i]] = [np.nan]*(duplicates[i]-1)
yyyslice = np.unique(yyyslice)
zzzslice = np.array(zzzslice)
zzzslice = zzzslice[~np.isnan(zzzslice)]
try:
f = interpolate.interp1d(yyyslice,zzzslice,kind='cubic')
except:
continue
#zzzslice_smooth = sg(zzzslice, window_length=5,polyorder=2)
#ax.scatter(yyyslice,zzzslice,s=8)
yyynew = np.arange(min(yyyslice),max(yyyslice))
ax.plot(ys=yyynew,zs=f(yyynew),xs=len(yyynew)*[slicing],zdir='z',color="C1")
#ax.plot(yyynew,f(yyynew))
yyyinterp.extend(yyynew)
zzzinterp.extend(f(yyynew))
xxxinterp.extend(len(yyynew)*[slicing])
ptty(slicing,3850,2)
print 'Re-processing contactline for transverse slicing...'
for i in range(0,cl_img.shape[0],ddd):
#for j in range(0,2100,ddd):
for j in range(cl_img.shape[1]-1,int(cl_img.shape[1]*0.3),-ddd):
if cl_img[i,j] == 1:
xxxinterp.append(j)
yyyinterp.append(i)
zzzinterp.append(floor)
x.append(j)
y.append(i)
break
for j in range(0,int(cl_img.shape[1]*0.7),ddd):
if cl_img[i,j] == 1:
xxxinterp.append(j)
yyyinterp.append(i)
zzzinterp.append(floor)
x.append(j)
y.append(i)
break
#ax.plot(x,y, 'C1',zs=floor)
print 'Transverse slicing...'
for slicing in range(300,2800,500):
xxxslice = [xxxinterp[i] for i in range(len(yyyinterp)) if yyyinterp[i]==slicing]
zzzslice = [zzzinterp[i] for i in range(len(yyyinterp)) if yyyinterp[i]==slicing]
if len(xxxslice)<4:
continue
zzzslice = [s for _,s in sorted(zip(xxxslice, zzzslice))]#sort zzzslice according to yyyslice
xxxslice = sorted(xxxslice)
duplicates = dict((i,xxxslice.count(s)) for (i,s) in enumerate(np.unique(xxxslice)) if xxxslice.count(s)>1)
for i in duplicates:
zzzslice[i] = np.mean(zzzslice[i:i+duplicates[i]])
zzzslice[i+1:i+duplicates[i]] = [np.nan]*(duplicates[i]-1)
xxxslice = list(np.unique(xxxslice))
zzzslice = np.array(zzzslice)
zzzslice = zzzslice[~np.isnan(zzzslice)]
zzzslice= list(zzzslice)
a = xxxslice[:-1:2]+[xxxslice[-1]]
b = zzzslice[:-1:2]+[zzzslice[-1]]
try:
f = interpolate.interp1d(a,b,kind='cubic')
except Exception as e:
print e
continue
ptty(slicing,max(range(300,2800,500)),1)
#zzzslice_smooth = sg(zzzslice, window_length=5,polyorder=2)
#
#ax.scatter(yyyslice,zzzslice,s=5)
xxxnew = np.arange(min(xxxslice[::]),max(xxxslice[::]))
ax.plot(xs=xxxnew,zs=f(xxxnew),ys=len(xxxnew)*[slicing],zdir='z',color="C0")
plt.tight_layout()
plt.axis('off')
#cv2.imwrite('fitimg_whole.tif', fitimg_whole.astype('uint8'))
plt.show()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
iternum = 8
p = [0]*iternum
fig, ax = plt.subplots()
for i in range(iternum):
s = np.load('passnumber_list {:d}.npy'.format(i))
#ax.plot(range(len(s)), s)
pp = np.polyfit(range(len(s)),s, 1)
p[i] = pp[0]
plt.plot(range(iternum), p)
plt.show()
<file_sep>import time
import progressbar
for i in range(400):
# work
time.sleep(0.01)
progressbar.progressbar_tty(i,399,3)
<file_sep>import numpy as np
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('ideal.tif',0)
print image.shape
nrows = np.shape(image)[0]
ncols = np.shape(image)[1]
ftimage = np.fft.fft2(image)
ftimage = np.fft.fftshift(ftimage)
logftimage = np.log(ftimage)
plt.imshow(np.abs(logftimage))
sigmax, sigmay = 10, 50
cy, cx = nrows/2, ncols/2
y = np.linspace(0, nrows, nrows)
x = np.linspace(0, ncols, ncols)
X, Y = np.meshgrid(x, y)
gmask = np.exp(-(((X-cx)/sigmax)**2 + ((Y-cy)/sigmay)**2))
ftimagep = ftimage * gmask
#plt.imshow(np.abs(np.log(ftimagep)))
imagep = np.fft.ifft2(ftimagep)
#plt.imshow(np.abs(imagep))
plt.show()
<file_sep>import subprocess
filename = "/cygdrive/c/Lib/site-packages/matplotlib"
cmd = ['cygpath','-w',filename]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = proc.stdout.read()
#output = output.replace('\\','/')[0:-1] #strip \n and replace \\
print output
<file_sep>import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import random
boxsize = 1000
class Particle:
def __init__(self, particle_pos, size):
self.x = particle_pos[0]
self.y = particle_pos[1]
self.orientation = random.uniform(0,2*np.pi)
self.size = size
def touch(particle1pos, particle2pos, particle1size, particle2size):
if np.linalg.norm(particle1pos-particle2pos) <= particle1size + particle2size:
return 1
else:
return 0
def findnearest(particle, particle_array):
dist_array = np.sum((particle - particle_array)**2, axis=1)
return np.nanargmin(dist_array)
def create_multi_particles(totnum):
boxsize = 1000
particle_array = np.empty((totnum,2))
particle_array[:] = np.NAN
particlesize = 10
x= random.uniform(particlesize, boxsize-particlesize)
y = random.uniform(particlesize, boxsize-particlesize)
particle_array[0,:] = np.asarray((x,y))
for n in range(1,totnum):
touchflg = 1
particlesize = 10
failcount = -1
while touchflg == 1:
failcount+=1
x = random.uniform(particlesize, boxsize-particlesize)
y = random.uniform(particlesize, boxsize-particlesize)
particle = np.asarray((x,y))
nearest_idx = findnearest(particle,particle_array)
touchflg = touch(particle_array[nearest_idx], particle, particlesize, particlesize)
particle_array[n,:] = np.asarray((x,y))
return particle_array, failcount
if __name__ == '__main__':
totnum = 100
particle_array, failcount = create_multi_particles(totnum)
fig = plt.figure()
for n in range(totnum):
circle = plt.Circle((particle_array[n,0], particle_array[n,1]), 10, fill=False)
fig.gca().add_artist(circle)
plt.axis([0,1000,0,1000])
plt.axes().set_aspect('equal')
plt.show()
print failcount
<file_sep>from boundaryv.brownian_gas import touch, findnearest
from door_position.disks import tchbnd
import numpy as np
import matplotlib.pyplot as plt
import os
import progressbar
class Elephant_foot():
def __init__(self, radius, velocity):
self.position = np.array([0.,0.])
self.radius = radius
self.velocity = velocity
def expand(self, dt):
self.radius += self.velocity * dt
class Environment():
def __init__(self, boxsize, totnum, dt, initial_radius, velocity):
self.boxsize = boxsize
self.totnum = totnum
self.foot_list = [0] * self.totnum
self.foot_position_array = np.empty((self.totnum,2))
self.foot_position_array[:] = np.nan
self.dt = dt
self.initial_radius = initial_radius
self.velocity = velocity
def create_feet(self):
print 'Creating elephant feet...'
if os.path.exists('./initial_particles.npy') & os.path.exists('./initial_positions.npy'):
print 'Reading saved initial conditions...'
self.foot_list = np.load('initial_particles.npy')
self.foot_position_array = np.load('initial_positions.npy')
else:
for n in range(0,self.totnum):
out_of_bnd = 1
overlap = 1
while out_of_bnd or overlap:
foot = Elephant_foot(self.initial_radius, self.velocity)
foot.position[0] = np.random.uniform(foot.radius, self.boxsize[0]-foot.radius)
foot.position[1] = np.random.uniform(foot.radius, self.boxsize[1]-foot.radius)
try:
nearest_idx = findnearest(foot.position, self.foot_position_array)
nearest_foot = self.foot_list[nearest_idx]
overlap = touch(foot.position, self.foot_position_array[nearest_idx],foot.radius,nearest_foot.radius)
tchbndlist = tchbnd(foot.position, foot.radius, self.boxsize)
out_of_bnd = sum(tchbndlist)
except ValueError:
break
self.foot_list[n] = foot
self.foot_position_array[n,:] = foot.position
progressbar.progressbar_tty(n+1, self.totnum, 1)
np.save('initial_particles',self.foot_list)
np.save('initial_positions',self.foot_position_array)
def visualize(self):
fig = plt.figure(figsize=(8.0,5.0))
for foot in self.foot_list:
circle = plt.Circle(foot.position, foot.radius, fill = True, linewidth=0.3)
fig.gca().add_artist(circle)
plt.axis([0,self.boxsize[0], 0,self.boxsize[1]])
plt.axes().set_aspect('equal')
plt.savefig('./movie/'+'{:4.0f}'.format(i)+'.tif', dpi = 300)
def expand(self):
for n, footn in enumerate(self.foot_list):
overlap = 0
for i , footi in enumerate(self.foot_list):
if n != i:
overlap += touch(footn.position, footi.position,footn.radius,footi.radius)
tchbndlist = tchbnd(footn.position, footn.radius, self.boxsize)
out_of_bnd = sum(tchbndlist)
#if overlap + out_of_bnd == 0:
if 1:
footn.radius += self.velocity * self.dt
def update(self):
self.expand()
if __name__ == "__main__":
import matplotlib.pyplot as plt
import progressbar
import os
import subprocess
import time
import os
if not os.path.exists('./movie/'):
os.makedirs('./movie/')
start = time.time()
env = Environment(boxsize=(30,30), \
totnum=200, \
dt=0.03, \
initial_radius=0.1, \
velocity=0.5)
env.create_feet()
#env.read_positions(mass = 10, radius = 5)
array = []
totframe = 200
for i in range(totframe):
env.update()
if i%3==0:
env.visualize()
plt.close()
#if i == 1000:
# np.save('initial_positions', env.particle_position_array)
progressbar.progressbar_tty(i+1, totframe, 1)
#subprocess.call('less resultsfilekjk.txt', shell=False)
for foot in env.foot_list:
#print foot.position
array.append(foot.radius)
plt.hist(array,13)
plt.show()
end = time.time()
print end-start
<file_sep>class trythis:
""" Don't have to initialize data attributes; they can be defined directly in method attributes.
"""
attr_directly_under_class_def = 30
def seeattr(self):
self.attr = 20
def seeagain(self):
self.attr = 200
if __name__ == "__main__":
print trythis.__doc__
x = trythis()
x.seeattr()
print x.attr
x.seeagain()
print x.attr
print x.attr_directly_under_class_def
<file_sep>from __future__ import division
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib as mpl
from scipy import interpolate
import os
data_img = cv2.imread('sample4.tif',0)
data_img = data_img.astype('float64')
cl_img = cv2.imread('cl.tif',0)
cl2_img = cv2.imread('cl2_larger.tif',0)
cl3_img = cv2.imread('cl3.tif',0)
edge_img = cv2.imread('cl_edge.tif',0)
thin_img = cv2.imread('thin.tif',0)
cl_img = cl_img.astype('float64')
cl_img /= 255.
cl2_img = cl2_img.astype('float64')
cl2_img /= 255.
cl3_img = cl3_img.astype('float64')
cl3_img /= 255.
edge_img = edge_img.astype('float64')
edge_img /= 255.
thin_img = thin_img.astype('float64')
thin_img /= 255.
fitimg_whole = np.copy(data_img)
xstorebot = np.load('./xoptstore_bot.npy').item()
xstoreright = np.load('./xoptstore_right.npy').item()
xstoreleft = np.load('./xoptstore_left.npy').item()
xstoretopright= np.load('./xoptstore_top_right.npy').item()
xstoretopleft= np.load('./xoptstore_top_left.npy').item()
floor = -86
def surface_polynomial(size, coeff,(zoomfactory,zoomfactorx)):
def poly(x, y):
x*=zoomfactorx
y*=zoomfactory
poly = coeff[0]*x**2+coeff[1]*y**2+coeff[2]*x*y+coeff[3]*x+coeff[4]*y+coeff[5]#+coeff[6]*x**3+coeff[7]*y**3+coeff[8]*x*y**2+coeff[9]*y*x**2
return poly
x = np.linspace(0,size[1]-1, size[1])
y = np.linspace(0,size[0]-1, size[0])
zz = poly(x[None,:],y[:,None])
return zz
fig = plt.figure(figsize=(7,7))
ax = fig.add_subplot(111,projection='3d')
ax.set_aspect(adjustable='datalim',aspect='equal')
ax.set_zlim(floor,0)
width = 0.8
xxx = []
yyy = []
zzz = []
ddd=1
#bot
dyy,dxx = 81,81
dd=15
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstorebot:
xopt = xstorebot[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
if ((int(yy/dyy)+1,int(xx/dxx)) not in xstorebot) or ((int(yy/dyy)-1,int(xx/dxx)) not in xstorebot):
pass
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
ax.plot_wireframe(X,Y,height,rstride=int(dyy/2),cstride=int(dxx/2),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plotheight = height-floor
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = plotheight
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#right
dyy,dxx =int(41*np.tan(np.pi*52/180)),41
zoomfactory,zoomfactorx = 1,1
dd = 5
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx > 3850:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreright:
xopt = xstoreright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
height-=35
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plotheight = height-floor
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = plotheight
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#left
dyy,dxx =int(42*np.tan(np.pi*53/180)),42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx>1430 or xx<332:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreleft:
xopt = xstoreleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=44
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plotheight = height-floor
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = plotheight
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
#topright
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopright:
xopt = xstoretopright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=82
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plotheight = height-floor
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = plotheight
else:
pass
#topleft
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopleft:
xopt = xstoretopleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=80.3
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
xxx+=list(X.flat[::dd])
yyy+=list(Y.flat[::dd])
zzz+=list(height.flat[::dd])
ax.plot_wireframe(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=width)
#ax.plot_surface(X,Y,height,rstride=int(dyy/1),cstride=int(dxx/1),lw=0,cmap = 'ocean',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
generated_intensity = 1+np.cos((4*np.pi/0.532)*surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx)))
generated_intensity /= generated_intensity.max()
generated_intensity = zoom(generated_intensity,(zoomfactory,zoomfactorx))
plotheight = height-floor
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = plotheight
else:
pass
#xopt = xstore_badtiles[(int(yy/dyy),int(xx/dxx))]
dyy,dxx =60,60
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if thin_img[yy,xx] == 0:
xxx.append(xx)
yyy.append(yy)
zzz.append(floor+3)
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
Z = (floor+3)*np.ones(X.shape)
Z*= 1-thin_img[yy:yy+dyy,xx:xx+dxx]
Z[Z==0] = np.nan
#ax.plot_wireframe(X,Y,Z,rstride=int(dyy/1),cstride=int(dxx/1),colors='k',lw=0.4)
if os.path.exists('./znew.npy'):
xstart,xend = 0,data_img.shape[1]
ystart,yend = 0,data_img.shape[0]
xnew,ynew = np.mgrid[xstart:xend,ystart:yend]
znew = np.load('znew.npy')
znew[znew<floor] = np.nan
znew*=(thin_img).T
znew*=(cl2_img).T
znew[znew == 0] =np.nan
znew[:,:250] = np.nan
plotheight = znew-floor
print np.nanmax(plotheight)
plotheight /= np.nanmax(plotheight)
plotheight[np.isnan(plotheight)] = 0
fitimg_whole[ystart:yend,xstart:xend] = (255*(plotheight)).T
#ax.plot_wireframe(xnew[:2132,:],ynew[:2132,:],znew[:2132,:],rstride =80, cstride = 80, colors='k',lw = 0.4)
#ax.plot_surface(xnew,ynew,znew,rstride=30,cstride=30,lw=0,cmap = 'RdBu',norm= mpl.colors.Normalize(vmin=-90,vmax=1))
else:
for i in range(0,cl_img.shape[0],ddd):
for j in range(0,cl_img.shape[1],ddd):
if cl_img[i,j] == 1:
xxx.append(j)
yyy.append(i)
zzz.append(floor)
xstart,xend = 0,data_img.shape[1]
ystart,yend = 0,data_img.shape[0]
xnew,ynew = np.mgrid[xstart:xend,ystart:yend]
print 'interpolating'
f = interpolate.bisplrep(xxx,yyy,zzz,kx=5,ky=3)
print 'finished'
znew = interpolate.bisplev(xnew[:,0],ynew[0,:],f)
znew[znew<floor] =np.nan
#znew*=(thin_img).T
znew*=(cl2_img).T
znew[znew == 0] =np.nan
#znew[:,:300] = np.nan
np.save('znew.npy',znew)
#ax.plot_wireframe(xnew,ynew,znew,rstride =60, cstride = 60, colors='k',lw = 0.4)
#bot
dyy,dxx = 81,81
dd=15
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstorebot:
xopt = xstorebot[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
plotheight = height-floor
plotheight /= 89.253
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*plotheight
#right
dyy,dxx =int(41*np.tan(np.pi*52/180)),41
zoomfactory,zoomfactorx = 1,1
dd = 5
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx > 3850:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreright:
xopt = xstoreright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy,dxx), xopt,(zoomfactory,zoomfactorx))
height-=35
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
plotheight = height-floor
plotheight /= 89.253
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*plotheight
#left
dyy,dxx =int(42*np.tan(np.pi*53/180)),42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if xx>1430 or xx<332:
continue
if (int(yy/dyy),int(xx/dxx)) in xstoreleft:
xopt = xstoreleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=44
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
plotheight = height-floor
plotheight /= 89.253
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*plotheight
#topleft
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopleft:
xopt = xstoretopleft[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=80.3
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
plotheight = height-floor
plotheight /= 89.253
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*plotheight
#topright
dyy, dxx = 35,42
zoomfactory,zoomfactorx = 1,1
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if (int(yy/dyy),int(xx/dxx)) in xstoretopright:
xopt = xstoretopright[(int(yy/dyy),int(xx/dxx))]
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
height = surface_polynomial((dyy/zoomfactory,dxx/zoomfactorx), xopt,(zoomfactory,zoomfactorx))
height-=82
#height*= 1-cl3_img[yy:yy+dyy,xx:xx+dxx]
#height[height==0] = np.nan
plotheight = height-floor
plotheight /= 89.253
#fitimg_whole[yy:yy+dyy,xx:xx+dxx] = 255*plotheight
#thin
dyy,dxx =10,10
for yy in range(0,data_img.shape[0]-dyy,dyy):
for xx in range(0,data_img.shape[1]-dxx,dxx):#xx,yy starting upper left corner of patch
if thin_img[yy,xx] == 0:
xxx.append(xx)
yyy.append(yy)
zzz.append(floor+5)
X,Y =np.meshgrid(range(xx,xx+dxx,zoomfactorx),range(yy,yy+dyy,zoomfactory))
Z = (floor+3)*np.ones(X.shape)
Z*= 1-thin_img[yy:yy+dyy,xx:xx+dxx]
Z[Z==0] = np.nan
plotheight = Z-floor
plotheight /= 89
plotheight[np.isnan(plotheight)] = 0
fitimg_whole[yy:yy+dyy,xx:xx+dxx] = (255*(plotheight)).T
#ax.plot_wireframe(X,Y,Z,rstride=int(dyy/1),cstride=int(dxx/1),colors='k',lw=0.4)
x = []
y = []
for j in range(0,cl_img.shape[1]-1,5):
for i in range(cl_img.shape[0]-1,-1,-5):
if cl_img[i,j] == 1 and i>200:
x.append(j)
y.append(i)
break
ax.plot(x,y, 'k',zs=floor)
#x_edge=[]
#y_edge=[]
#z_edge=[]
#for i in range(0,edge_img.shape[0],2):
# for j in range(0,edge_img.shape[1],2):
# if edge_img[i,j] == 1:
# x_edge.append(j)
# y_edge.append(i)
# z_edge.append(znew[j,i])
#ax.scatter(x_edge,y_edge,z_edge,c='k',s=0.01)
ax.view_init(azim=128,elev=75)
plt.axis('off')
plt.tight_layout()
cv2.imwrite('fitimg_whole.tif', fitimg_whole.astype('uint8'))
#plt.imshow(fitimg_whole.astype('uint8'),cmap='cubehelix')
#plt.contour(fitimg_whole.astype('uint8')[::-1],20)
plt.show()
<file_sep>from __future__ import division
import numpy as np
from scipy.optimize import fsolve
def mu(Cm,T):
a = 0.705-0.0017*T
b = (4.9+0.036*T)*np.power(a,2.5)
alpha = 1-Cm+(a*b*Cm*(1-Cm))/(a*Cm+b*(1-Cm))
mu_water = 1.790*np.exp((-1230-T)*T/(36100+360*T))
mu_gly = 12100*np.exp((-1233+T)*T/(9900+70*T))
return np.power(mu_water,alpha)*np.power(mu_gly,1-alpha)
def glycerol_mass(T,target_viscosity=200):
def mu_sub(Cm,T):
return mu(Cm,T)-target_viscosity
x = fsolve(mu_sub,1,args=(T),xtol=1e-12)
return x
Temperature = 22.5
Target_viscosity = 100
print 'glycerol mass fraction %0.3f%%'%(glycerol_mass(Temperature,Target_viscosity)[0]*100)
<file_sep>#import os
#if os.getenv("TZ"):
# os.unsetenv("TZ")
from time import strftime, localtime,gmtime,timezone
print strftime("%H_%M_%S",localtime())
print timezone/3600.
<file_sep># -*- encoding: utf-8 -*-
import urllib
import cfscrape
from bs4 import BeautifulSoup
import re
n = 1
f = open('result.html','w+')
f.write('<!DOCTYPE html>')
f.write('<html>')
f.write('<body>')
for page in range(1,50):
site15 ="http://t66y.com/thread0806.php?fid=15&search=&page=%d"%page
site2 ="http://t66y.com/thread0806.php?fid=2&search=&page=%d"%page
site4 ="http://t66y.com/thread0806.php?fid=4&search=&page=%d"%page
site8 ="http://t66y.com/thread0806.php?fid=8&search=&page=%d"%page
site7 ="http://t66y.com/thread0806.php?fid=7&search=&page=%d"%page
for site in [site15, site2,site4,site8,site7]:
#for site in [site7]:
scraper = cfscrape.create_scraper() # returns a CloudflareScraper instance
# Or: scraper = cfscrape.CloudflareScraper() # CloudflareScraper inherits from requests.Session
html = scraper.get(site)
soup = BeautifulSoup(html.content,'html.parser')
trs = soup.findAll('tr',{'class','tr3 t_one tac'},limit=None)
for tr in trs[3:]:
url = 'http://t66y.com/'+tr.find('td',{'class','tal'}).find('a').get('href')
s = tr.find('td',{'class','tal'}).get_text().encode('utf8')
keywords = ['Beginningofkeywords',\
'Shizuka',\
'管野',\
'菅野',\
'佐々木',\
'佐佐木',\
'sasaki',\
'Sasaki',\
'Rina',\
'Ishihara',\
'石原莉奈',\
#'白木',\
'松岡 ちな',\
'春原未来',\
'Chanel',\
'<NAME>',\
'Karter',\
'Carter',\
'<NAME>',\
'<NAME>',\
#'pantyhose',\
#'Pantyhose',\
'nylon',\
#'1080',\
#'Stockings',\
#'絲襪',\
#'丝袜',\
#'黑丝',\
#'襪',\
'小島',\
'神纳花',\
'篠田',\
'Ayumi',\
'trans',\
#'ts',\
'妖',\
'变性',\
#'FHD',\
'Butt3rflyforu',\
'EndofKeywords'\
]
for keyword in keywords:
if keyword in s:
linktext = '<a href="{x}">{y}</a>'.format(x=url,y=s)
print linktext
f.write('<p>'+linktext+'</p>')
#print(s),url,'page =',page,'fid =',site[site.index('=')+1:site.index('&')]
#print n
n+=1
f.write('</body>')
f.write('</html>')
f.close()
<file_sep>from __future__ import division
from scipy.misc import derivative
import scipy.optimize
import scipy.spatial.distance
def shape_function(x):
return 0.000005*(x**2)+68
#return 0.00000001*x + 68
#@profile
def find_k_refracting(k_incident, x1, n1,n2):
#n = np.array([[-derivative(shape_function, x, dx=1e-6), 1]for x in x1])
#above method in creating n is too slow
n = np.empty((len(x1), 2))
n[:,0] = -derivative(shape_function, x1, dx=1e-6)
#n[:,0] = -partial_derivative.derivative(shape_function, x1, dx=1e-6)
n[:,1] = 1
norm = np.linalg.norm(n, axis = 1)
n = n/norm[:,np.newaxis]
c = -np.dot(n, k_incident)
r = n1/n2
if ((1-r**2*(1-c**2)) < 0).any():
print(Fore.RED)
print "Total internal reflection occurred."
print "1-r**2*(1-c**2) = \n", 1-r**2*(1-c**2)
print(Style.RESET_ALL)
sys.exit(0)
factor = (r*c- np.sqrt(1-r**2*(1-c**2)))
#print "n = ", n
#print 'c =',c
#print "factor", factor
#print "tile", np.tile(r*k_incident,(len(x1), 1))
#print k_refracting
k_refracting = np.tile(r*k_incident,(len(x1), 1)) + n*factor[:,np.newaxis]
return k_refracting
#@profile
def find_x0(k_incident, x1, n1,n2):
#def g(x):
# k_refracting = find_k_refracting(k_incident, x, n1, n2)
# #return -k_refracting[:,1]/k_refracting[:,0]
# return k_refracting[:,0], k_refracting[:,1]
def F(x):
k_refracting = find_k_refracting(k_incident, x, n1, n2)
#return shape_function(x1)+shape_function(x)-(x1-x)*g(x)
return k_refracting[:,0]*(shape_function(x1)+shape_function(x))+k_refracting[:,1]*(x1-x)
x0 = scipy.optimize.newton_krylov(F,x1, f_tol = 1e-3)
return x0
#@profile
def optical_path_diff(k_incident, x1, n1,n2):
x0 = find_x0(k_incident, x1, n1, n2)
p0 = np.empty((len(x1),2))
p1 = np.empty((len(x1),2))
p1_image_point = np.empty((len(x1),2))
p0[:,0] = x0
p0[:,1] = shape_function(x0)
p1[:,0] = x1
p1[:,1] = shape_function(x1)
p1_image_point[:,0] = x1
p1_image_point[:,1] = -shape_function(x1)
#p0 = np.array([x0, shape_function(x0)])
#p1 = np.array([x1, shape_function(x1)])
#p1_image_point = np.array([x1, -shape_function(x1)])
vec_x0x1 = p1-p0
norm = np.linalg.norm(vec_x0x1, axis = 1)
norm[norm == 0] = 1
vec_x0x1 = vec_x0x1/norm[:,np.newaxis]
cos = np.dot(vec_x0x1, k_incident)
dist1 = np.linalg.norm(p0-p1, axis = 1)
dist2 = np.linalg.norm(p0-p1_image_point, axis = 1)
#dist1 = scipy.spatial.distance.cdist(p0.T,p1.T,'euclidean')
#dist2 = scipy.spatial.distance.cdist(p0.T,p1_image_point.T,'euclidean')
#dist1 = np.diagonal(dist1)
#dist2 = np.diagonal(dist2)
#print "vec_x0x1 = ", vec_x0x1
#print "cos = ", cos
#print "p0 = ", p0
#print "p1 = ", p1
#print "dist1 = ", dist1
#print "dist2 = ", dist2
OPD_part1 = dist1*cos*n1
OPD_part2 = dist2*n2
OPD = OPD_part2-OPD_part1
return OPD
def pattern(opd):
intensity = 1+np.cos((2*np.pi/0.532)*opd)
return intensity
if __name__ == "__main__":
import matplotlib.pyplot as plt
import numpy as np
import sys
import progressbar
import os
import time
from colorama import Fore, Style
start = time.time()
print "starting..."
i = 0
framenumber = 50
pltnumber = 300
pltlength = 500
detecting_range = np.linspace(-pltlength,pltlength,pltnumber)
for angle in np.linspace(0,0.0625,framenumber):
fig = plt.figure()
ax = fig.add_subplot(111)
i += 1
opd = optical_path_diff(k_incident = np.array([np.sin(angle),-np.cos(angle)]),\
x1 = detecting_range,\
n1 = 1.5,\
n2 = 1)
intensity = pattern(opd)
#opd_expected = 2*shape_function(0)*np.cos(np.arcsin(np.sin(angle-0.00000001)*1.5)+0.00000001)
#print "error in OPD = " ,(opd-opd_expected)/0.532, "wavelength"
ax.plot(detecting_range, intensity)
plt.ylim((0,2.5))
ax.set_xlabel('$\mu m$')
ax.text(0, 2.2, r'$rotated : %.4f rad$'%angle, fontsize=15)
dirname = "./movie/"
if not os.path.exists(dirname):
os.makedirs(dirname)
plt.savefig(dirname+'{:4.0f}'.format(i)+'.tif')
plt.close()
progressbar.progressbar_tty(i, framenumber, 1)
print(Fore.CYAN)
print "Total running time:", time.time()-start, "seconds"
print(Style.RESET_ALL)
print "finished!"
<file_sep>import cv2
from scipy import ndimage as ndi
from skimage import feature
import numpy as np
from matplotlib import pyplot as plt
from skimage import exposure
def equalize(img_array):
"""
returns array with float 0-1
"""
equalized = exposure.equalize_hist(img_array)
return equalized
img = cv2.imread('sample.tif',0)
img = equalize(img)
img = ndi.gaussian_filter(img,1)
edges = feature.canny(img,low_threshold=0.12,high_threshold=0.2)
plt.subplot(121),plt.imshow(img,cmap = 'gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap = 'gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()
<file_sep>from __future__ import division
import progressbar
import matplotlib.pyplot as plt
import numpy as np
class gas:
def __init__(self):
pass
class Dimer(gas):
def __init__(self, mass, radius, restlength):
self.position1 = np.zeros(2)
self.position2 = np.zeros(2)
self.positionCOM = (self.position1 + self.position2)/2.0
self.restlength = restlength
self.length = restlength
self.orientation = 0.
self.force1 = np.array((0.,0.))
self.force2 = np.array((0.,0.))
self.velocity1= np.array((0.,0.))
self.velocity2= np.array((0.,0.))
self.kickforce1= np.array((0.,0.))
self.kickforce2= np.array((0.,0.))
self.repelforce1= np.array((0.,0.))
self.repelforce2= np.array((0.,0.))
self.bondforce1= np.array((0.,0.))
self.bondforce2= np.array((0.,0.))
self.dissipation1= np.array((0.,0.))
self.dissipation2= np.array((0.,0.))
self.radius = radius
self.mass = mass
def interact():
pass
def accelerate(self, acceleration1, acceleration2, anglechange):
self.velocity1 += acceleration1
self.velocity2 += acceleration2
def move(self, velocity1, velocity2):
self.position1 += self.velocity1
self.position2 += self.velocity2
def touch(particle1pos, particle2pos, particle1size, particle2size):
""" Calculate overlap of 2 particles """
overlap = -np.linalg.norm(particle1pos-particle2pos)+(particle1size + particle2size)
if overlap > 0.:
return overlap
else:
return 0.
def touchbnd(particle_position, radius, box_size):
""" Tells if a particle touches the boundary """
tchbndlist = [0,0,0,0] # [W,N,E,S]
xtemp = particle_position[0]
ytemp = particle_position[1]
if xtemp<=radius:
tchbndlist[0] = 1
if xtemp>=(box_size-radius):
#if xtemp>=8*radius:
tchbndlist[2] = 1
if ytemp>=(box_size-radius):
tchbndlist[1] = 1
if ytemp<=radius:
tchbndlist[3] = 1
return tchbndlist
def findnearest(particle, particle_array):
""" Returns the nearest particle index """
dist_array = np.sum((particle - particle_array)**2, axis=1)
return np.nanargmin(dist_array)
class Environment:
def __init__(self, boxsize, totnum, dt):
self.boxsize = boxsize
self.totnum = totnum
self.particle_position_array = np.empty((2*self.totnum,2))
self.particle_position_array[:] = np.nan
self.dimer_list = [0]*self.totnum
self.orientationlist = [0]*self.totnum
self.bondlist = [[(0.,0.),(0.,0.)]]*totnum
self.removallist = []
self.dt = dt
def create_dimers(self, mass, radius, restlength):
# Place the first dimer
dimer = Dimer(mass, radius, restlength)
dimer.position1 = np.random.uniform(radius, self.boxsize-radius, 2)
#dimer.position1 = np.random.uniform(radius, 8*radius, 2)
out_of_bnd = 1
while out_of_bnd:
dimer.orientation = np.random.uniform(0, 2*np.pi)
xtemp = dimer.position1[0] + dimer.length*np.cos(dimer.orientation)
ytemp = dimer.position1[1] + dimer.length*np.sin(dimer.orientation)
# Unless sum of tchbndlist is zero, particle is out of bnd
out_of_bnd = sum(touchbnd((xtemp, ytemp), radius, self.boxsize))
dimer.position2[0] = xtemp
dimer.position2[1] = ytemp
self.orientationlist[0] = dimer.orientation
self.dimer_list[0] = dimer
self.particle_position_array[0,:] = dimer.position1
self.particle_position_array[1,:] = dimer.position2
self.bondlist[0] = (dimer.position1[0],dimer.position2[0]),(dimer.position1[1],dimer.position2[1])
# Create 2nd-nth dimmer without overlapping
for n in range(1,self.totnum):
overlap = 1
# Create particle1
failcount1 = 0
while overlap:
failcount1 += 1
dimer = Dimer(mass, radius, restlength)
dimer.position1 = np.random.uniform(radius+1, self.boxsize-radius-1, 2)
nearest_idx = findnearest(dimer.position1, self.particle_position_array)
overlap = touch(dimer.position1, self.particle_position_array[nearest_idx], radius, radius)
if failcount1 >= 100000:
self.removallist.append(n)
break
# Create particle2
out_of_bnd = 1
overlap = 1
failcount2 = 0
while out_of_bnd or overlap:
failcount2 += 1
dimer.orientation = np.random.uniform(0, 2*np.pi)
xtemp = dimer.position1[0] + dimer.length*np.cos(dimer.orientation)
ytemp = dimer.position1[1] + dimer.length*np.sin(dimer.orientation)
out_of_bnd = sum(touchbnd((xtemp, ytemp), radius, self.boxsize))
nearest_idx = findnearest((xtemp, ytemp), self.particle_position_array)
overlap = touch((xtemp, ytemp), self.particle_position_array[nearest_idx], radius, radius)
if failcount2 >= 100000:
self.removallist.append(n)
break
dimer.position2[0] = xtemp
dimer.position2[1] = ytemp
self.particle_position_array[2*n,:] = dimer.position1
self.particle_position_array[2*n+1, :] = dimer.position2
self.dimer_list[n] = dimer
self.orientationlist[n] = dimer.orientation
self.bondlist[n] = (dimer.position1[0],dimer.position2[0]),(dimer.position1[1],dimer.position2[1])
progressbar.progressbar_tty(n+1,self.totnum,1)
# Update dimer_list and everything related for removal
self.removallist = list(set(self.removallist))
print 'updating dimerlist, removing', self.removallist, len(self.removallist), ''
self.dimer_list = [i for j, i in enumerate(self.dimer_list) if j not in self.removallist]
newlength = len(self.dimer_list)
self.orientationlist = [0]*newlength
self.bondlist = [[(0.,0.),(0.,0.)]]*newlength
self.particle_position_array = np.empty((2*newlength,2))
self.particle_position_array[:] = np.nan
for n, dimer in enumerate(self.dimer_list):
self.particle_position_array[2*n,:] = dimer.position1
self.particle_position_array[2*n+1, :] = dimer.position2
self.orientationlist[n] = dimer.orientation # Given randomly upon creation
self.bondlist[n] = (dimer.position1[0],dimer.position2[0]),(dimer.position1[1],dimer.position2[1])
print 'now length of dimerlist', len(self.dimer_list)
def visualize(self):
fig = plt.figure()
radius = self.dimer_list[0].radius
for dimer in self.dimer_list:
circle = plt.Circle(dimer.position1, radius, fill=False)
fig.gca().add_artist(circle)
circle = plt.Circle(dimer.position2, radius, fill=False)
fig.gca().add_artist(circle)
count = 0
for n, dimer in enumerate(self.dimer_list):
plt.plot(self.bondlist[n][0],self.bondlist[n][1],'k')
count += 1
plt.axis([0, self.boxsize, 0, self.boxsize])
plt.axes().set_aspect('equal')
return count
def kick(self,kickf):
for n, dimer in enumerate(self.dimer_list):
kickangle = self.orientationlist[n]
dimer.kickforce1 = kickf*np.cos(kickangle), kickf*np.sin(kickangle)
dimer.kickforce1 = np.asarray(dimer.kickforce1)
dimer.kickforce2 = dimer.kickforce1
def dissipate(self, coefficient):
for n, dimer in enumerate(self.dimer_list,coefficient):
dimer.disspation1 = -coefficient*dimer.velocity1
dimer.disspation2 = -coefficient*dimer.velocity2
def collide(self,repel_coefficient):
for n, dimer in enumerate(self.dimer_list):
radius = dimer.radius
dimer.repelforce1 = np.zeros(2)
dimer.repelforce2 = np.zeros(2)
for i, particle_position in enumerate(self.particle_position_array):
if i != 2*n: # for particle1, make sure to exclude itself
overlap1 = touch(dimer.position1, particle_position, radius, radius)
unit_vector = (dimer.position1-particle_position)/np.linalg.norm((dimer.position1-particle_position))
dimer.repelforce1 += repel_coefficient*unit_vector*overlap1
if i != 2*n+1: # for particle2, exclude itself
overlap2 = touch(dimer.position2, particle_position, radius, radius)
unit_vector = (dimer.position2-particle_position)/np.linalg.norm((dimer.position2-particle_position))
dimer.repelforce2 += repel_coefficient*unit_vector*overlap2
def bounce(self):
radius = self.dimer_list[0].radius
for dimer in self.dimer_list:
tchbndlist = touchbnd(dimer.position1, radius, self.boxsize)
if tchbndlist[0] * dimer.velocity1[0] < 0:
dimer.velocity1[0] = 0.
if tchbndlist[2] * dimer.velocity1[0] > 0:
dimer.velocity1[0] = 0.
if tchbndlist[1] * dimer.velocity1[1] > 0:
dimer.velocity1[1] = 0.
if tchbndlist[3] * dimer.velocity1[1] < 0:
dimer.velocity1[1] = 0.
tchbndlist = touchbnd(dimer.position2, radius, self.boxsize)
if tchbndlist[0] * dimer.velocity2[0] < 0:
dimer.velocity2[0] = 0.
if tchbndlist[2] * dimer.velocity2[0] > 0:
dimer.velocity2[0] = 0.
if tchbndlist[1] * dimer.velocity2[1] > 0:
dimer.velocity2[1] = 0.
if tchbndlist[3] * dimer.velocity2[1] < 0:
dimer.velocity2[1] = 0.
def bond_deform(self,coefficient):
for n, dimer in enumerate(self.dimer_list):
bondlength = np.linalg.norm(dimer.position2-dimer.position1)
deform = bondlength - dimer.restlength
unit_vector = np.asarray((np.cos(self.orientationlist[n]), np.sin(self.orientationlist[n])))
dimer.bondforce1 = coefficient*unit_vector*deform
dimer.bondforce2 = -coefficient*unit_vector*deform
def accelerate(self):
for dimer in self.dimer_list:
dimer.force1 = dimer.kickforce1 + dimer.dissipation1 + dimer.bondforce1 + dimer.repelforce1
dimer.velocity1 += self.dt*dimer.force1/dimer.mass
dimer.force2 = dimer.kickforce2 + dimer.dissipation2 + dimer.bondforce2 + dimer.repelforce2
dimer.velocity2 += self.dt*dimer.force2/dimer.mass
def move(self):
for dimer in self.dimer_list:
dimer.position1 += self.dt*dimer.velocity1
dimer.position2 += self.dt*dimer.velocity2
def update(self,kickf,collide_coeff,dissipate_coeff,bond_coeff):
self.kick(kickf)
self.collide(collide_coeff)
self.bond_deform(bond_coeff)
self.dissipate(dissipate_coeff)
self.accelerate()
self.bounce()
self.move()
for n, dimer in enumerate(self.dimer_list):
self.particle_position_array[2*n,:] = dimer.position1
self.particle_position_array[2*n+1, :] = dimer.position2
bond = dimer.position2-dimer.position1
dimer.orientation = np.angle(bond[0]+1j*bond[1])
self.orientationlist[n] = dimer.orientation
self.bondlist[n] = (dimer.position1[0],dimer.position2[0]),(dimer.position1[1],dimer.position2[1])
if __name__ == '__main__':
import matplotlib.pyplot as plt
import progressbar
env = Environment(500,totnum = 110, dt = 0.02)
env.create_dimers(mass=10., radius=10., restlength=30.)
print env.removallist
print len(env.orientationlist)
totframe = 30000
for i in range(totframe):
env.update(kickf=1,collide_coeff=10,dissipate_coeff=1,bond_coeff=10)
if i%30 == 0 and i>3000:
env.visualize()
plt.savefig('./movie5/'+'{:4.0f}'.format(i/10)+'.tif')
plt.close()
progressbar.progressbar_tty(i+1,totframe,1)
<file_sep>#!/usr/bin/env python
import cookb_signalsmooth
import numpy as np
import matplotlib.pyplot as plt
import sys
from find_peaks import exact_local_maxima1D, exact_local_minima1D
def stripes_counting(datafile_name):
"""
Given a 1-D array of grayscale data, find the peak number
and the valley number.
Data could be obtained by imagej grayscale measurement.
"""
pixel_values = np.loadtxt(datafile_name, skiprows = 1)
window_len = 10
smooth_values = cookb_signalsmooth.smooth(pixel_values[:,1], window_len)
plt.plot(smooth_values)
plt.plot(pixel_values[:,1])
plt.show()
s = raw_input("Is this smoothing (window_len = %d) good enough? (y/n)"%window_len)
sys.stdout.flush()
if s == "n":
unsatisfied = 1
while unsatisfied:
t = raw_input("Keep adjusting window length. New window_len = ")
window_len = int(t)
smooth_values = cookb_signalsmooth.smooth(pixel_values[:,1], window_len)
plt.plot(smooth_values)
plt.plot(pixel_values[:,1])
plt.show()
u = raw_input("Is this smoothing (window_len = %d) good enough? (y/n)"%window_len)
if u=="y":
true_values_maxima = exact_local_maxima1D(smooth_values)
maxima_number = np.sum(true_values_maxima)
true_values_minima = exact_local_minima1D(smooth_values)
minima_number = np.sum(true_values_minima)
break
elif s == "y":
true_values_maxima = exact_local_maxima1D(smooth_values)
maxima_number = np.sum(true_values_maxima)
true_values_minima = exact_local_minima1D(smooth_values)
minima_number = np.sum(true_values_minima)
else:
print "You didn't press anything..."
return maxima_number, minima_number
if __name__ == "__main__":
import os
import sys
s = ""
while not os.path.exists(s+".xls"):
s = raw_input("Give me a correct data file name: ")
sys.stdout.flush()
maxima_number, minima_number = stripes_counting(s + ".xls")
print "%d maxima"%maxima_number
print "%d minima"%minima_number
raw_input('press enter')
<file_sep>from __future__ import division
import find_peaks
import numpy as np
def center_position(intensity, x, center):
left_indices = find_peaks.left_find_indices_all(intensity)
left_x_position = x[left_indices]
left_center_idx = np.abs(left_x_position-center).argmin()
right_indices = find_peaks.right_find_indices_all(intensity)
right_x_position = x[right_indices]
right_center_idx = np.abs(right_x_position-center).argmin()
return (left_x_position[left_center_idx]+right_x_position[right_center_idx])/2
if __name__ == "__main__":
from scipy import signal
import matplotlib.pyplot as plt
intensity = np.load('intensity.npy')
coordinates = np.linspace(-500,500,300)
peak = center_position(intensity,coordinates, 0)
plt.plot(coordinates, intensity)
plt.axvline(x = peak)
plt.show()
<file_sep>from __future__ import division
import numpy as np
import warnings
def exact_local_maxima1D(a):
"""
Compare adjacent elements of a 1D array.
Returns a np array of true values for each element not counting
the first and last element.
Modified from http://stackoverflow.com/questions/4624970/finding-local-maxima-minima-with-numpy-in-a-1d-numpy-array
"""
true_values = np.greater(a[1:-1], a[:-2]) & np.greater(a[1:-1], a[2:])
return true_values
def exact_local_minima1D(a):
true_values = np.less(a[1:-1], a[:-2]) & np.less(a[1:-1], a[2:])
return true_values
def right_edge_local_maxima1D(a):
"""
For the case of plateaus coexisting with peaks.
Returns a boolean array excluding the first and last
elements of the input array.
In case of a plateau, the right edge is considered
a peak position.
"""
warnings.filterwarnings("ignore")
aa = np.copy(a) # make sure input itself won't be modified
diff= np.diff(aa)
smallest_diff = np.min(abs(diff[np.nonzero(diff)]))
aa[diff==0.] -= smallest_diff/2
true_values = np.greater(aa[1:-1], aa[:-2]) & np.greater(aa[1:-1], aa[2:])
return true_values
def left_edge_local_maxima1D(a):
"""
Similar to right_edge_local_maxima2D().
"""
aa = a.copy()
diff = np.diff(aa)
diff = np.insert(diff, 0, 1)
smallest_diff = np.min(abs(diff[np.nonzero(diff)]))
aa[diff==0.] -= smallest_diff/2
true_values = np.greater(aa[1:-1], aa[:-2]) & np.greater(aa[1:-1], aa[2:])
return true_values
def right_edge_local_minima1D(a):
"""
Similar to right_edge_local_maxima1D().
"""
warnings.filterwarnings("ignore")
aa = np.copy(a) # make sure input itself won't be modified
diff= np.diff(aa)
smallest_diff = np.min(abs(diff[np.nonzero(diff)]))
aa[diff==0.] += smallest_diff/2
true_values = np.less(aa[1:-1], aa[:-2]) & np.less(aa[1:-1], aa[2:])
return true_values
def left_edge_local_minima1D(a):
"""
Similar to right_edge_local_minima2D().
"""
aa = a.copy()
diff = np.diff(aa)
diff = np.insert(diff, 0, 1)
smallest_diff = np.min(abs(diff[np.nonzero(diff)]))
aa[diff==0.] += smallest_diff/2
true_values = np.less(aa[1:-1], aa[:-2]) & np.less(aa[1:-1], aa[2:])
return true_values
def find_indices_max(a):
"""
Find indices of local maxima.
Returns a np array of indices.
"""
true_values = exact_local_maxima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def find_indices_min(a):
true_values = exact_local_minima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def find_indices_all(a):
"""
Find indices of all local extrema.
Returns a np array of indices.
"""
true_values_max = exact_local_maxima1D(a)
true_values_min = exact_local_minima1D(a)
true_values = true_values_max | true_values_min
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def left_find_indices_max(a):
true_values = left_edge_local_maxima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def left_find_indices_min(a):
true_values = left_edge_local_minima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def right_find_indices_max(a):
true_values = right_edge_local_maxima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def right_find_indices_min(a):
true_values = right_edge_local_minima1D(a)
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def left_find_indices_all(a):
true_values_max = left_edge_local_maxima1D(a)
true_values_min = left_edge_local_minima1D(a)
true_values = true_values_max | true_values_min
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
def right_find_indices_all(a):
true_values_max = right_edge_local_maxima1D(a)
true_values_min = right_edge_local_minima1D(a)
true_values = true_values_max | true_values_min
indices = [i for i,x in enumerate(true_values) if x== True]
indices = np.array(indices) + 1
return indices
if __name__ == "__main__":
a = np.array([2,3,1,2,3,2,1,2,3,2,1,2,3,2])
s = exact_local_minima1D(a)
s1 = find_indices_min(a)
s2 = find_indices_max(a)
s3 = find_indices_all(a)
b = np.array([-1,4,4,2,3,3,3,3,2,6,1])
b = b.astype("float")
print "if minima(not counting the first the last element)", s, type(s)
print "min indices:", s1, type(s1)
print "max indices:", s2, type(s2)
print "all peaks:", s3, type(s3)
print left_find_indices_all(b)
print b
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
cmap = plt.get_cmap('tab10')
x = np.arange(0,20, 0.001)
red = 1+np.cos(4*np.pi*(x+0.630/4)/0.630)
amber = 1+ np.cos(4*np.pi*(x+0.59/4)/0.590)
#plt.plot(x, red+amber)
plt.title('red and amber')
plt.plot(x, red,color=cmap(3))
plt.plot(x, amber, color=cmap(1))
plt.show()
<file_sep>from __future__ import division
from scipy import stats
import numpy as np
def leastsq_unweighted(x,y):
"""
y = A + Bx
all inputs are np arrays
"""
N = len(x)
delta_unweighted = N*((x**2).sum())-(x.sum())**2
A_unweighted = ((x*x).sum()*(y.sum())-x.sum()*((x*y).sum()))/delta_unweighted
B_unweighted = (N*((x*y).sum())-(x.sum())*(y.sum()))/delta_unweighted
sigmay_unweighted = np.sqrt((1/(N-2))*np.square(y-A_unweighted-B_unweighted*x).sum())
sigmaA = sigmay_unweighted*np.sqrt((x**2).sum()/delta_unweighted)
sigmaB = sigmay_unweighted*np.sqrt(N/delta_unweighted)
return A_unweighted, B_unweighted,sigmaA,sigmaB,sigmay_unweighted
def leastsq_weighted(x,y,sigmax_exp, sigmay_exp):
_,B_unweighted,_,_,sigmay_unweighted = leastsq_unweighted(x,y)
sigmay_max = np.array([max(s,t) for (s,t) in zip(sigmay_unweighted*y/y,sigmay_exp)])
sigmay_eff = np.sqrt((sigmay_max)**2+np.square(B_unweighted*sigmax_exp)) # use sigmay_unweighted or sigmay_exp of sigmay_max????
w = 1/np.square(sigmay_eff)
delta_weighted = w.sum()*((w*x*x).sum()) - np.square((w*x).sum())
A_weighted = ((w*x*x).sum()*((w*y).sum())-(w*x).sum()*((w*x*y).sum()))/delta_weighted
B_weighted = (w.sum()*((w*x*y).sum()) - (w*x).sum()*((w*y).sum()))/delta_weighted
sigmaA_weighted = np.sqrt((w*x*x).sum()/delta_weighted)
sigmaB_weighted = np.sqrt(w.sum()/delta_weighted)
return A_weighted, B_weighted, sigmaA_weighted, sigmaB_weighted
def leastsq_unweighted_thru0(x,y):
""" y = Bx """
N = len(y)
numerator = (x*y).sum()
denominator = (x**2).sum()
B_unweighted = numerator/denominator
sigmay_unweighted = np.sqrt(((y-B_unweighted*x)**2).sum()/(N-1))
sigmaB = sigmay_unweighted/np.sqrt((x**2).sum())
return B_unweighted, sigmaB, sigmay_unweighted
def leastsq_weighted_thru0(x,y,sigmax_exp,sigmay_exp):
B_unweighted,_,sigmay_unweighted = leastsq_unweighted_thru0(x,y)
sigmay_max = np.array([max(s,t) for (s,t) in zip(sigmay_unweighted*y/y,sigmay_exp)])
sigmay_eff = np.sqrt((sigmay_max)**2+np.square(B_unweighted*sigmax_exp)) # use sigmay_unweighted or sigmay_exp of sigmay_max????
w = 1/np.square(sigmay_eff)
numerator = (w*x*y).sum()
denominator = (w*x*x).sum()
B_weighted = numerator/denominator
sigmaB_weighted = 1/np.sqrt((w*x*x).sum())
return B_weighted, sigmaB_weighted
def chi2test(x,y,sigmax_exp,sigmay_exp):
_,_,_,_,sigmay_unweighted = leastsq_unweighted(x,y)
A_weighted,B_weighted,_,_ = leastsq_weighted(x,y,sigmax_exp,sigmay_exp)
chi2 = (np.square((y-A_weighted-B_weighted*x)/(sigmay_exp))).sum()#has to use sigmay_exp, a reasonable estimate of exp error is crucial
N = len(x)
c = 2 # sigmay_unweighted is calculated from data;1 constraint
reduced_chi2 = chi2/(N-c)
prob = (1-stats.chi2.cdf(chi2,(N-c)))
return reduced_chi2
<file_sep>print 'try this from the lab computer'
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from plotwithsliders import plotwithsliders as ps
from plotwithsliders import sliders_buttons as sb
from find_peaks import find_indices_max as fimax
from find_peaks import find_indices_min as fimin
cmap = plt.get_cmap('tab10')
am = cmap(1)
gr = cmap(2)
rd = cmap(3)
x = np.arange(0,20, 0.001)
red = 1+np.cos(4*np.pi*(x+0.630/4)/0.630)
amber = 1+ np.cos(4*np.pi*(x+0*0.59/4)/0.590)
fig,ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
ax.set_ylim(-1,3)
for i,ind in enumerate(fimin(amber)):
ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.1),color=am)
for i,ind in enumerate(fimin(red)):
ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.2),color=rd)
pararange = [0.5,0.6]
parainit = 0.532
slider,buttonplus,buttonminus = sb(pararange,parainit)
ax.plot(x, red, color=rd)
ax.plot(x, amber, color=am)
def xgreen(wvlg):
return x
def ygreen(wvlg):
return 1+ np.cos(4*np.pi*(xgreen(wvlg)+wvlg/4)/wvlg)
ps([slider],[buttonplus],[buttonminus],ax,xgreen,ygreen,gr,[pararange],[parainit])
plt.title('amber reversed')
plt.show()
<file_sep>from __future__ import division
import numpy as np
from scipy.signal import savgol_filter as sg
from scipy.interpolate import interp1d
from skimage.measure import profile_line as pl
from find_peaks import left_find_indices_min as minindices
from find_peaks import left_find_indices_max as maxindices
import sys
import time
import os
def meandata(img,(startx,starty)=(2042,1674),R=1067,a=167,da=20,dda=1,savename="mdatatemp"):
"""
R profile length
a angle
da averaging angle
dda averaging stepping size
"""
if os.path.exists(savename):
data = np.load(savename)
mdata = np.mean(data,axis=0)
else:
for i,angle in enumerate(np.arange(a,a+da,dda)):
endx = startx+np.cos(angle*np.pi/180)*R
endy = starty-np.sin(angle*np.pi/180)*R
#endx,endy pixel/imagej coord, need to reverse for scipy/numpy use
if i == 0:
data = pl(img,(starty,startx),(endy,endx),order=0)
length = len(data)
else:
#start = time.time()
data = np.vstack((data,pl(img,(starty,startx),(endy,endx),order = 3)[:length]))
#sys.stdout.write('\r'+"averaging: %d/%d, takes %fs"%(i+1,len(np.arange(a,a+da,dda)),time.time()-start))
#np.save(savename,data)
mdata = np.mean(data,axis=0)
stddata = np.std(data,axis=0)
return mdata,stddata
def symmetricmeandata(img,(startx,starty)=(2042,1674),R=1067,a=167,da=20,dda=1,savename="mdatatemp",compare='off',ref=2000):
"""
symmetric version of meandata()
"""
if os.path.exists(savename):
data = np.load(savename)
mdata = np.mean(data,axis=0)
else:
for i,angle in enumerate(np.arange(a,a+da,dda)):
endx = startx+np.cos(angle*np.pi/180)*R
endy = starty-np.sin(angle*np.pi/180)*R
#actually starting from not the center but from the symmetric end point
sstartx = 2*startx-endx
sstarty = 2*starty-endy
if i == 0:
data = pl(img,(sstarty,sstartx),(endy,endx),order=0)
length = len(data)
else:
#start = time.time()
data = np.vstack((data,pl(img,(sstarty,sstartx),(endy,endx),order = 3)[:length]))
if compare == 'on' and i < int(da/dda) :
stddata = np.std(data,axis=0)
if np.sqrt(i+1)*stddata.sum()> ref:
#stop stacking more angles if std is already larger than a criterion; useful in some special cases e.g.wanna 'scan' 360 degrees to see if the profiles will be similar (concentric rings), if std is already very large before hitting 360 no need to keep profiling. the sqrt part is to account for std decrease as 1/sqrt(N)
return -1,-1
#sys.stdout.write('\r'+"averaging: %d/%d, takes %fs"%(i+1,len(np.arange(a,a+da,dda)),time.time()-start))
#np.save(savename,data)
mdata = np.mean(data,axis=0)
stddata = np.std(data,axis=0)
return mdata,stddata
def normalize_envelope(mdata,smoothwindow=19,splineorder=2,envelopeinterp='quadratic'):
"""
x is the maximum range where envelop fitting is possible
"""
s = sg(mdata,smoothwindow,splineorder)
upperx = maxindices(s)
#uppery = np.maximum(mdata[upperx],s[upperx])
uppery = mdata[upperx]
lowerx = minindices(s)
#lowery = np.minimum(mdata[lowerx],s[lowerx])
lowery = mdata[lowerx]
fupper = interp1d(upperx, uppery, kind=envelopeinterp)
flower = interp1d(lowerx, lowery, kind=envelopeinterp)
x = np.arange(max(min(upperx),min(lowerx)),min(max(upperx),max(lowerx)))
y = mdata[x]
newy = (y-flower(x))/(fupper(x)-flower(x))
return x,newy
if __name__=="__main__":
import numpy as np
import cv2
import matplotlib.pyplot as plt
(startx,starty)=(2042,1674)
R = 1067
a = 167
da = 20
dda = 1
imgred = cv2.imread('warpedred.tif',0)
imggreen = cv2.imread('warpedgreen.tif',0)
imgamber = cv2.imread('DSC_3878.jpg',0)
cmap = plt.get_cmap('tab10')
am = cmap(1)
gr = cmap(2)
rd = cmap(3)
print '\nprocessing red'
mdatared = meandata(imgred,(startx,starty),R,a,da,dda,savename='datared.npy')
xred,newyred = normalize_envelope(mdatared[170:]) #170 is to cut off the flat noisy first dark spot; otherwise envelope fitting won't work (it assumes a nice wavy shape without too many local extrema)
xred+=170 #not necessary; just to make sure xred=0 is center of the rings;wanna make sure all the coordinates throughout the script is consistent so its easier to check for bugs
print '\nprocessing amber'
mdataamber = meandata(imgamber,(startx,starty),R,a,da,dda,savename='dataamber.npy')
xamber,newyamber = normalize_envelope(mdataamber[170:])
xamber+=170
print'\nprocess green'
mdatagreen= meandata(imggreen, (startx,starty),R,a,da,dda,savename='datagreen.npy')
xgreen,newygreen= normalize_envelope(mdatagreen[170:])
xgreen+=170
np.save('xgreen',xgreen)
np.save('newygreen',newygreen)
#plt.plot(mdatared,color=cmap(3))
#plt.plot(mdatagreen,color=cmap(2))
#plt.plot(mdataamber,color=cmap(1))
plt.plot(xred,newyred,color=rd)
plt.plot(xamber,newyamber,color=am)
plt.plot(xgreen,newygreen,color=gr)
plt.show()
<file_sep>import sys
from colorama import init, Fore, Style
class easyprompt:
def __init__(self):
init()
self.count = 0
def __str__(self):
self.count += 1
print(Fore.GREEN + '(%d)>>>>>>>>>>>>>>>' % self.count)
print(Style.RESET_ALL)
sys.ps1 = easyprompt()
<file_sep>from skimage import morphology
import mahotas as mh
import matplotlib.pyplot as plt
import numpy as np
#label original image, im=uint8(0 and 255), labeled=uint8
im = plt.imread('../../Downloads/image.tif')
labeled, nr_objects = mh.label(im,np.ones((3,3),bool))
print nr_objects
#an example of removing holes. Should use labeled image
im_clean = morphology.remove_small_objects(labeled)
labeled_clean, nr_objects_clean = mh.label(im_clean,np.ones((3,3),bool))
print nr_objects_clean
<file_sep>from __future__ import division
import numpy as np
import sys
def split_concatenate(img1, img2, angle, sp):
"""
Takes two pictures of (e.g. red and green) interference patterns and
concatenate them in a split screen fashion for easy comparison.
The split line is the line that passes sp===split_point and with an
inclination of angle.
"""
img1cp = np.copy(img1)
img2cp = np.copy(img2)
if img1cp.shape != img2cp.shape:
print "I can't deal with pictures of difference sizes..."
sys.exit(0)
angle = angle*np.pi/180
for j in range(img1cp.shape[1]):
ic = -np.tan(angle)*(j-sp[0])+sp[1]
for i in range(img1cp.shape[0]):
if i>=ic:
img1cp[i,j] = 0
else:
img2cp[i,j] = 0
img = np.maximum(img1cp,img2cp)
return img
if __name__ == "__main__":
"""
img1 is above img2
"""
import numpy as np
import cv2
img1 = cv2.imread('catreference.tif', 0)
img2 = cv2.imread('greenveo2_f358enhanced.tif',0)
img = split_concatenate(img1,img2, angle =96.759,\
sp=(674,175))
cv2.imwrite('catreference.tif', img)
print "Finished!"
<file_sep>import numpy as np
d = np.load('goodness.npy').item()
print d
print min(d, key=d.get)
<file_sep>import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x1,y1 = np.loadtxt('data_center.txt', delimiter=',', unpack = True)
ax.plot(x1, y1, 'x', color = 'r')
x2,y2 = np.loadtxt('data_wall.txt', delimiter=',', unpack=True)
ax.plot(x2, y2, '+', color = 'g')
plt.axis([0,4, 20, 70])
plt.show()
<file_sep>from __future__ import division
import numpy as np
import cv2
import matplotlib.pyplot as plt
import time
import statsmodels.api as sm
from collections import namedtuple
def roughcenter(img,ilwindow,jlwindow,i0,j0):
""" Returns icenter, jcenter only using 4 tips of the cross shape.
img needs to be blurred;
Starts from i0, j0, draws a window of height and width of lwindow, jlwindow;
Gets 4 intersections with the window edge;
Gets ic, jc by cross connecting the 4 intersection points.
"""
edge1 = img[i0-int(ilwindow/2) : i0+int(ilwindow/2), j0-int(jlwindow/2)]
indx = np.argmin(edge1)
i1, j1 = i0-int(ilwindow/2)+indx, j0-int(jlwindow/2)
x1, y1 = j1,i1
edge2 = img[i0-int(ilwindow/2) , j0-int(jlwindow/2) : j0+int(jlwindow/2)]
indx = np.argmin(edge2)
i2, j2 = i0-int(ilwindow/2), j0-int(jlwindow/2)+indx
x2, y2 = j2,i2
edge3 = img[i0-int(ilwindow/2) : i0+int(ilwindow/2) , j0+int(jlwindow/2)]
indx = np.argmin(edge3)
i3, j3 = i0-int(ilwindow/2)+indx, j0+int(jlwindow/2)
x3, y3 = j3,i3
edge4 = img[i0+int(ilwindow/2) ,j0-int(jlwindow/2) : j0+int(jlwindow/2)]
indx = np.argmin(edge4)
i4, j4 = i0+int(ilwindow/2), j0-int(jlwindow/2)+indx
x4, y4 = j4,i4
if (x2 == x4) or (y1 == y3):
xc = x2
yc = y1
else:
s13 = (y3-y1)/(x3-x1)
s24 = (y4-y2)/(x4-x2)
yc = (s13*s24*(x2-x1) + s24*y1-s13*y2)/(s24-s13)
xc = (yc-y1)/s13+x1
ic,jc = int(yc),int(xc)
Res = namedtuple('Res','xc,yc,ic,jc,i1,j1,i2,j2,i3,j3,i4,j4')
res = Res(xc, yc, ic, jc, i1,j1, i2, j2, i3, j3, i4, j4)
return res
def mixture_lin(img,ilwindow,jlwindow,i0,j0,thresh):
"""Returns xcenter, ycenter of a cross shape using mixture linear regression.
img doesn't have to be bw; but training points are 0 intensity;
ilwindow, jlwindow,i0,j0 for target area;
Use thresh (e.g., 0.6) to threshold classification;
Best for two bars making a nearly vertical crossing.
"""
img = img[i0-int(ilwindow/2):i0+int(ilwindow/2), j0-int(jlwindow/2):j0+int(jlwindow/2)]
X_train = np.argwhere(img == 0 )
n = np.shape(X_train)[0] #number of points
y = X_train[:,0]
x = X_train[:,1]
w1 = np.random.normal(0.5,0.1,n)
w2 = 1-w1
start = time.time()
for i in range(100):
pi1_new = np.mean(w1)
pi2_new = np.mean(w2)
mod1= sm.WLS(y,sm.add_constant(x),weights = w1) #vertical
res1 = mod1.fit()
mod2= sm.WLS(x,sm.add_constant(y),weights = w2) #horizontal
res2 = mod2.fit()
y1_pred_new= res1.predict(sm.add_constant(x))
sigmasq1 = np.sum(res1.resid**2)/n
a1 = pi1_new * np.exp((-(y-y1_pred_new)**2)/sigmasq1)
x2_pred_new = res2.predict(sm.add_constant(y))
sigmasq2 = np.sum(res2.resid**2)/n
a2 = pi2_new * np.exp((-(x-x2_pred_new)**2)/sigmasq2)
if np.max(abs(a1/(a1+a2)-w1))<1e-5:
#print '%d iterations'%i
break
w1 = a1/(a1+a2)
w2 = a2/(a1+a2)
#print '%.3fs'%(time.time()-start)
#plt.scatter(x, y,10, c=w1,cmap='RdBu')
#w1thresh = (w1>thresh)+0
#w2thresh = (w2>thresh)+0
x1 = x[w1>thresh]
x2 = x[w2>thresh]
y1 = y[w1>thresh]
y2 = y[w2>thresh]
mod1 = sm.OLS(y1,sm.add_constant(x1))
res1 = mod1.fit()
sigmasq1 = np.sum(res1.resid**2)/len(x1)
y1_pred= res1.predict(sm.add_constant(x1))
#plt.plot(x1, y1_pred)
mod2 = sm.OLS(x2,sm.add_constant(y2))
res2 = mod2.fit()
sigmasq2= np.sum(res2.resid**2)/len(x2)
x2_pred= res2.predict(sm.add_constant(y2))
#plt.plot(x2_pred,y2)
b1,k1 = res1.params # y = k1x + b1
b2,k2 = res2.params # x = k2y + b2
yc = (k1*b2+b1)/(1-k1*k2)
xc = k2*yc + b2
#plt.scatter(xc,yc)
# all above values are wrt small cropped picture
xc += j0-jlwindow/2
x1 = x1 + j0-jlwindow/2
x2_pred = x2_pred + j0-jlwindow/2
yc += i0-ilwindow/2
y1_pred = y1_pred + i0-ilwindow/2
y2 = y2 + i0-ilwindow/2
Res = namedtuple('Res','xc, yc,x1,y1_pred,x2_pred,y2,sigmasq1,sigmasq2')
res = Res(xc, yc,x1,y1_pred,x2_pred,y2,sigmasq1,sigmasq2)
return res
if __name__ == "__main__":
img = cv2.imread('c:/Users/Mengfei/nagellab/forcedwetting/velocity_tracking/sample8.tif',0)
(_, img) = cv2.threshold(img, 30, 255, cv2.THRESH_BINARY)
thresh = 0.6
ilwindow,jlwindow = 50, 50
x0, y0 = 421,371
i0, j0 = y0,x0
res = mixture_lin(img,ilwindow,jlwindow, i0,j0,thresh)
print res.sigmasq1
plt.imshow(img,'gray')
plt.scatter(res.xc,res.yc)
plt.plot(res.x1,res.y1_pred)
plt.plot(res.x2_pred,res.y2)
plt.show()
<file_sep>#!/usr/bin/bash
for i in {0..2000..100}
do
python pattern_shift1D.py $i
done
<file_sep>from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
from plotwithsliders import plotwithsliders as ps
from plotwithsliders import sliders_buttons as sb
from find_peaks import find_indices_max as fimax
from find_peaks import find_indices_min as fimin
cmap = plt.get_cmap('tab10')
am = cmap(1)
gr = cmap(2)
rd = cmap(3)
x = np.arange(0,20, 0.001)
red = 1+np.cos(4*np.pi*(x+0.630/4)/0.630)
amber = 1+ np.cos(4*np.pi*(x+0.59/4)/0.590)
fig,ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
ax.set_ylim(-1,3)
#lred,= ax.plot(x, red, color=rd, visible=False)
lamber, = ax.plot(x, amber, color=am,visible=False)
for i,ind in enumerate(fimin(amber)):
ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.1),color=am)
for i,ind in enumerate(fimin(red)):
ax.annotate('%d'%(i+1),xy=(x[ind],0),xytext=(x[ind],-0.2),color=rd)
pararange = [0.5,0.6]
parainit = 0.532
slider,buttonplus,buttonminus = sb(pararange,parainit)
def xgreen(wvlg):
return x
def ygreen(wvlg):
return 1+ np.cos(4*np.pi*(xgreen(wvlg)+wvlg/4)/wvlg)
lgreen = ps([slider],[buttonplus],[buttonminus],ax,xgreen,ygreen,gr,[pararange],[parainit])
parainitred = 0.630
pararangered = [0.6,0.7]
sliderred,buttonplusred,buttonminusred = sb(pararangered,parainitred, height=0.12)
def xred(wvlg):
return x
def yred(wvlg):
return 1+ np.cos(4*np.pi*(xred(wvlg)+wvlg/4)/wvlg)
lred = ps([sliderred],[buttonplusred],[buttonminusred],ax,xred,yred,rd,[pararangered],[parainitred])
rax = plt.axes([0.01, 0.4, 0.1, 0.15])
check = CheckButtons(rax, ('red', 'amber', 'green'), (True, False, True))
def func(label):
if label == 'red':
lred.set_visible(not lred.get_visible())
elif label == 'amber':
lamber.set_visible(not lamber.get_visible())
elif label == 'green':
lgreen.set_visible(not lgreen.get_visible())
plt.draw()
check.on_clicked(func)
plt.show()
| d3bb67174a5b4d1deb089e2d9490f116520bf73c | [
"Python",
"Shell"
] | 74 | Python | hemengf/my_python_lib | 08176ca44c4d016e4c88e6d3f4fd482ab62aeafd | d9eb32dd6de209afb9f0d45709e7fb156d34da99 |
refs/heads/master | <file_sep>//Priority queues
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
int prio;
struct node *link;
};
void enqueue(struct node **front,struct node **rear,int data,int prio)
{
struct node *newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->prio = prio;
newnode->link = NULL;
if(*front == NULL)
*front = *rear = newnode;
else
{
(*rear)->link = newnode;
*rear = newnode;
}
}
struct node *dequeue(struct node **front)
{
if(*front == NULL)
{
printf("Queue is empty!");
return NULL;
}
else
{
struct node *hiprio;
struct node *trav = hiprio = *front,*hipar;
while(trav->link != NULL)
{
if(trav->link->prio > hiprio->prio)
{
hiprio = trav->link;
hipar = trav;
}
trav = trav->link;
}
if(hiprio == *front)
*front = (*front)->link;
else
{
hipar->link = hiprio->link;
}
return hiprio;
}
}
int main()
{
struct node *front = NULL,*rear = NULL,*temp;
int data,prio,done = 1,choice;
//1.Push 2.Pop
while(done == 1)
{
printf("\n:");
scanf("%d",&choice);
switch(choice)
{
case 1: scanf("%d%d",&data,&prio);enqueue(&front,&rear,data,prio);break;
case 2: temp = dequeue(&front);
if(temp != NULL)
printf("%d %d",temp->data,temp->prio);
break;
default:done = 0;break;
}
}
return 0;
}
Output:
:1
10 15
:1
11 20
:1
12 100
:1
13 50
:2
12 100
:2
13 50
:2
11 20
:2
10 15
:2
Queue is empty!
:
<file_sep>//BST
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *llink;
struct node *rlink;
};
void insert(struct node **root,int data)
{
struct node *newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->llink = NULL;
newnode->rlink = NULL;
if(*root == NULL)
{
*root = newnode;
}
else
{
struct node *trav = *root,*prev;
while(trav != NULL)
{
prev = trav;
if(data > trav->data)
{
trav=trav->rlink;
}
else if(data < trav->data)
{
trav=trav->llink;
}
else
{
printf("Duplicate\n");
return;
}
}
if(prev->data>data)
{
prev->llink=newnode;
}
else
prev->rlink=newnode;
}
}
void search(struct node *root,int data)
{
if(root != NULL)
printf("%d\n",root->data);
if(root == NULL)
{
printf("Absent\n");//printf("Element not found!");
return;
}
else if(root->data == data)
{
return;
// return root;
}
else if(data > root->data)
{
search(root->rlink,data);
}
else if(data < root->data)
{
search(root->llink,data);
}
}
void preorder(struct node *root)
{
if(root != NULL)
{
printf("%d\n",root->data);
preorder(root->llink);
preorder(root->rlink);
}
}
void inorder(struct node *root)
{
if(root != NULL)
{
inorder(root->llink);
printf("%d\n",root->data);
inorder(root->rlink);
}
}
void postorder(struct node *root)
{
if(root != NULL)
{
postorder(root->llink);
postorder(root->rlink);
printf("%d\n",root->data);
}
}
struct node * inorder_successor(struct node *ptr)
{
struct node *p=ptr->rlink;
while(p->llink!=NULL)
{
p=p->llink;
}
return p;
}
struct node * inorder_predecessor(struct node *ptr)
{
struct node *p=ptr->llink;
while(p->rlink!=NULL)
{
p=p->rlink;
}
return p;
}
struct node * delete(struct node *ptr,int val)
{
struct node *temp;
if(ptr == NULL)
{
return ptr;
}
else if(val<(ptr)->data)
{
ptr->llink=delete(ptr->llink,val);
}
else if(val>ptr->data)
{
ptr->rlink=delete(ptr->rlink,val);
}
else
{
if(ptr->rlink != NULL)
{
temp=inorder_successor(ptr);
ptr->data=temp->data;
ptr->rlink=delete(ptr->rlink,temp->data);
}
else if(ptr->llink != NULL)
{
temp=inorder_predecessor(ptr);
ptr->data=temp->data;
ptr->llink=delete(ptr->llink,temp->data);
}
else
{
return NULL;
}
}
return ptr;
}
int main()
{
struct node *root = NULL;
int data,choice,done = 0;
while(done == 0)
{
scanf("%d",&choice);
switch(choice)
{
case 1:
scanf("%d",&data);
insert(&root,data);
break;
case 2:
scanf("%d",&data);
root = delete(root,data);
break;
case 3: //printf("pre");
preorder(root);break;
case 4: //printf("in");
inorder(root);break;
case 5: //printf("post");
postorder(root);break;
case 6:
scanf("%d",&data);
search(root,data);
break;
case 7: done = 1;break;
default:done = 1;break;
}
}
return 0;
}
Output
1 10 1 20 1 5 1 6 1 15 3
10
5
6
20
15
<file_sep>#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define NIL -1
struct edge
{
int u;
int v;
int weight;
struct edge *link;
}*front=NULL;
void create_graph();
void make_tree(struct edge tree[]);
void inser_pque(int i,int j,int wt);
struct edge *del_pque();
int isEmpty_pque();
int n;
int adj[MAX][MAX];
main()
{
int i;
struct edge tree[MAX];int wt_tree=0;
create_graph();
make_tree(tree);
printf("Edges to be included in the spanning tree are:\n");
for(i=1;i<=n-1;i++)
{
printf("%d->",tree[i].u);
printf("%d\n",tree[i].v);
wt_tree+=tree[i].weight;
}
printf("weight of spanning tree is :%d\n",wt_tree);
}
void make_tree(struct edge tree[])
{
struct edge *tmp;
int v1,v2,root_v1,root_v2;
int father[MAX];
int i,count=0;
for(i=0;i<n;i++)
father[i]=NIL;
while(!isEmpty_pque()&&count<n-1)
{
tmp=del_pque();
v1=tmp->u;
v2=tmp->v;
while(v1!=NIL)
{
root_v1=v1;
v1=father[v1];
}
while(v2!=NIL)
{
root_v2=v2;
v2=father[v2];
}
if(root_v1!=root_v2)
{
count++;
tree[count].u=tmp->u;
tree[count].v=tmp->v;
tree[count].weight=tmp->weight;
father[root_v2]=root_v1;
}
}
if(count<n-1)
{
printf("Graph is not connected hence no spanning tree is possible");
exit(1);
}
}
void insert_pque(int i,int j,int wt)
{
struct edge *tmp,*q;
tmp=(struct edge *)malloc(sizeof(struct edge));
tmp->u=i;
tmp->v=j;
tmp->weight=wt;
if(front==NULL||tmp->weight<front->weight)
{
tmp->link=front;
front=tmp;
}
else
{
q=front;
while(q->link!=NULL&&q->link->weight<=tmp->weight)
q=q->link;
tmp->link=q->link;
q->link=tmp;
if(q->link==NULL)
tmp->link=NULL;
}
}
struct edge *del_pque()
{
struct edge *tmp;
tmp=front;
front=front->link;
return tmp;
}
int isEmpty_pque()
{
if(front==NULL)
return 1;
else
return 0;
}
void create_graph()
{
int i,max_edges,origin,destin,wt;
printf("Enter the number of vertices:");
scanf("%d",&n);
max_edges=n*(n-1)/2;
for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d(-1 -1 to quit):",i);
scanf("%d %d",&origin,&destin);
if((origin==-1)&&(destin==-1))
break;
printf("Enter weight for this edge:");
scanf("%d",&wt);
if(origin>=n||destin>=n||origin<0||destin<0)
{
printf("Invalid edge!!!\n");
i--;
}
else
insert_pque(origin,destin,wt);
}
}
<file_sep>//Dijkstra
#include <stdio.h>
void dijkstra(int dist[][1010],int d[],int nodes,int start)
{
int i,j,selected[1010];
for(i = 0;i <= nodes;i++)
{
d[i] = dist[start][i];
selected[i] = 0;
}
selected[start] = 1;
int small = start;
for(i = 1;i <= nodes;i++)
{
for(j = 1;j <= nodes ;j++)
{
if(selected[j] != 1)
{
small = j;
//break;
}
}
for(j = 1;j <= nodes;j++)
{
if(selected[j] != 1 && (d[small] > d[j]))
{
small = j;
}
}
selected[small] = 1;
for(j = 1;j <= nodes;j++)
{
if(selected[j] != 1)
{
if(d[j] > (d[small] + dist[small][j]))
d[j] = d[small]+dist[small][j];
}
}
}
}
int main()
{
int start,d[1010],mat[1010][1010],nodes,i = 0,j = 0,w = 0;
for(i = 1;i < 1010;i++)
{
for(j = 1;j < 1010;j++)
{
if(i == j)
mat[i][j] = 0;
else
mat[i][j] = 9999;
}
}
scanf("%d",&nodes);
scanf("%d%d%d",&i,&j,&w);
while(i != -1 && j != -1 && w != -1)
{
mat[i][j] = w;
//mat[j][i] = w;
scanf("%d%d%d",&i,&j,&w);
}
scanf("%d",&start);
dijkstra(mat,d,nodes,start);
for(i = 1;i <= nodes;i++)
{
printf("%d\n",d[i]);
}
return 0;
}
Output:
6
0 1 10
0 5 100
1 2 1
2 5 80
2 3 20
3 4 50
2 4 1
2 5 80
4 5 30
0
0 10 11 31 12 42
<file_sep>//Breadth first search
#include <stdio.h>
void enqueue(int array[],int *rear,int size,int element)
{
if(*rear==size)
{
printf("Queue is full\n");
}
else
{
array[*rear]=element;
*rear=*rear+1;
}
}
int dequeue(int array[],int *front,int *rear)
{
if(*front==*rear)
{
printf("Queue is empty\n");
}
else
{
int temp;
temp=array[*front];
*front=*front+1;
return temp;
}
}
void bfs(int mat[][1010],int size,int start)
{
int temp,selected[1010],i,queue[1010],front = 0,rear = 0;
for(i = 0;i <= size;i++)
selected[i] = 0;
enqueue(queue,&rear,1010,start);
selected[start] = 1;
while(front != rear)
{
temp = dequeue(queue,&front,&rear);
printf("%d",temp);
for(i = 1;i <= size;i++)
{
if(selected[i] != 1 && mat[temp][i] == 1)
{
enqueue(queue,&rear,1010,i);
selected[i] = 1;
}
}
if(front != rear)
printf(" ");
}
}
int main()
{
int i = 0,j = 0,size,mat[1010][1010],start;
scanf("%d",&size);
scanf("%d%d",&i,&j);
while(i != -1 && j != -1)
{
mat[i][j] = 1;
scanf("%d%d",&i,&j);
}
scanf("%d",&start);
bfs(mat,size,start);
return 0;
}
Output
5
1 2
1 5
1 3
2 3
3 4
4 5
-1 -1
1
1 2 3 5 4
<file_sep>//Expression tree
#include <stdio.h>
#include <stdlib.h>
struct node
{
char data;
float value;
struct node *llink;
struct node *rlink;
};
struct stack
{
struct node *dataLink;
struct stack *link;
};
struct node *makeNode(char data)
{
struct node *newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->llink = NULL;
newnode->rlink = NULL;
return newnode;
}
void push(struct stack **top,struct node *exprnode)
{
struct stack *newnode;
newnode = (struct stack*)malloc(sizeof(struct node));
newnode->dataLink = exprnode;
newnode->link = NULL;
if(*top == NULL)
*top = newnode;
else
{
newnode->link = *top;
*top = newnode;
}
}
struct node *pop(struct stack **top)
{
if(*top == NULL)
{
printf("Stack underflow!");
return NULL;
}
else
{
struct node *temp = (*top)->dataLink;
(*top) = (*top)->link;
return temp;
}
}
void makeExpressionTree(struct node **root)
{
int len,i;
char expr[100];
struct node *temp = NULL;
struct stack *top = NULL;
printf("Enter the expression:");
scanf("%s",expr);
for(len = 0;expr[len] != '\0';len++);
for(i = 0;i < len;i++)
{
if(expr[i] >= 'a' && expr[i] <= 'z')
{
temp = makeNode(expr[i]);
push(&top,temp);
}
else if(expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/')
{
temp = makeNode(expr[i]);
temp->rlink = pop(&top);
temp->llink = pop(&top);
push(&top,temp);
}
}
*root = pop(&top);
}
void getValues(struct node *root)
{
if(root == NULL)
return;
else
{
getValues(root->llink);
if(root->data >= 'a' && root->data <= 'z')
{
printf("Enter the value for %c:",root->data);
scanf("%f",&root->value);
}
getValues(root->rlink);
}
}
float evalTree(struct node *root)
{
if(root->data >= 'a' && root->data <= 'z')
return root->value;
else
{
switch(root->data)
{
case '+': return evalTree(root->llink) + evalTree(root->rlink);break;
case '-': return evalTree(root->llink) - evalTree(root->rlink);break;
case '*': return evalTree(root->llink) * evalTree(root->rlink);break;
case '/': return evalTree(root->llink) / evalTree(root->rlink);break;
}
}
}
int main()
{
struct node *root;
makeExpressionTree(&root);
getValues(root);
printf("%.2f\n",evalTree(root));
return 0;
}
Output:
Enter the expression:ab*cd*+
Enter the value for a:1
Enter the value for b:2
Enter the value for c:3
Enter the value for d:4
14.00
s
<file_sep>//Depth first search
#include <stdio.h>
void push(int array[],int size,int *top,int element)
{
if(*top == size)
printf("Stack Overflow!");
else
{
array[*top] = element;
*top = *top + 1;
}
}
int pop(int array[],int *top)
{
if(*top == 0)
{
printf("Stack Underflow!");
return -1;
}
else
{
*top = *top - 1;
return array[*top];
}
}
void dfs(int mat[][1010],int size,int start)
{
int temp,selected[1010],i,stack[1010],top = 0;
for(i = 0;i <= size;i++)
selected[i] = 0;
push(stack,1010,&top,start);
selected[start] = 1;
while(top > 0)
{
temp = pop(stack,&top);
printf("%d",temp);
for(i = 1;i <= size;i++)
{
if(selected[i] != 1 && mat[temp][i] == 1)
{
push(stack,1010,&top,i);
selected[i] = 1;
}
}
if(top > 0)
printf(" ");
}
}
int main()
{
int i = 0,j = 0,size,mat[1010][1010],start;
scanf("%d",&size);
scanf("%d%d",&i,&j);
while(i != -1 && j != -1)
{
mat[i][j] = 1;
scanf("%d%d",&i,&j);
}
scanf("%d",&start);
dfs(mat,size,start);
return 0;
}
Output
5
1 2
1 5
1 4
4 3
-1 -1
1
1 5 4 3 2
<file_sep>dslab-cycle2
============
S4 Data Structures Lab Cycle 2
<file_sep>//Prims
#include <stdio.h>
#define GRAPH_SIZE 1001
void printmst(int graph[][GRAPH_SIZE],int tree[][GRAPH_SIZE],int n)
{
int i,j;
printf("\nThe edges to be included are:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(tree[i][j]==1)
{
printf("\n%d - %d %d",i,j,graph[i][j]);
}
}
}
printf("\n");
}
void prims(int graph[][GRAPH_SIZE],int tree[][GRAPH_SIZE],int n)
{
int selected[GRAPH_SIZE],i,min,j,ne,x,y;
for(i=0;i<=n;i++)
{
selected[i]=0;
}
selected[1]=1;
ne=1;
while(ne<n)
{
min=9999;
for(i=1;i<=n;i++)
{
if(selected[i])
{
for(j=1;j<=n;j++)
{
if(!selected[j] && min>graph[i][j])
{
min=graph[i][j];
x=i;
y=j;
}
}
}
}
tree[x][y]=1;
selected[y]=1;
ne++;
}
printmst(graph,tree,n);
}
int main()
{
int source,graph[GRAPH_SIZE][GRAPH_SIZE],tree[GRAPH_SIZE][GRAPH_SIZE],n,i=0,j=0,w=0;
for(i = 1;i < GRAPH_SIZE;i++)
{
for(j = 1;j <GRAPH_SIZE;j++)
{
if(i == j)
graph[i][j] = 0;
else
graph[i][j] = 9999;
tree[i][j]=0;
}
}
printf("\nEnter the no of vertices:");
scanf("%d",&n);
printf("\nEnter edge (-1 -1 to quit):");
scanf("%d%d%d",&i,&j,&w);
while(i!=-1 && j!=-1 && w!=-1)
{
graph[i][j] = w;
graph[j][i]=w;
printf("\nEnter edge (-1 -1 -1 to quit):");
scanf("%d%d%d",&i,&j,&w);
}
prims(graph,tree,n);
return 0;
}
Output:-
Enter the no of vertices:3
Enter edge (-1 -1 -1 to quit):1 2 4
Enter edge (-1 -1 -1 to quit):1 3 5
Enter edge (-1 -1 -1 to quit):2 3 6
Enter edge (-1 -1 -1 to quit):-1 -1 -1
The edges to be included are:
1 - 2 4
1 - 3 5
<file_sep>//Heap sort
#include<stdio.h>
int swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void heapify(int heap[],int i,int n)
{
int left=2*i;
int right=2*i+1;
int largest=i;
if(left<n && heap[left]>heap[i])
{
largest=left;
}
if(right<n && heap[right]>heap[largest])
{
largest=right;
}
if(largest!=i)
{
swap(&heap[i],&heap[largest]);
heapify(heap,largest,n);
}
}
void build_heap(int heap[],int n)
{
int i;
for (i =(n/2); i>=0; i--)
{
heapify(heap,i,n);
}
}
void sort(int heap[],int n)
{
int i;
build_heap(heap,n);
for(i=n-1;i>=1;i--)
{
swap(&heap[0],&heap[i]);
heapify(heap,0,i);
}
}
int main()
{
int heap[100],n,i;
printf("\nEnter the no of elements:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&heap[i]);
}
sort(heap,n);
printf("\nSorted array is:\n");
for(i=0;i<n;i++)
{
printf("%d\n",heap[i]);
}
return 0;
}
Output:-
Enter the no of elements:5
Enter the elements:1 5 3 7 9
Sorted array is:1 3 5 7 9
| 635d96814a58cd57ffe22326c96b384af3dcf19f | [
"Markdown",
"C"
] | 10 | C | Abhilashb1289/dslab-cycle2 | f8a9948ed2e3d0f734944ac3bdb069f01692add5 | b49da6154a25f9e3ea30a0f76e721dbd9dbf8924 |
refs/heads/master | <file_sep># alien_invasion
`pygame` 外星人小游戏,学习 `python` 的项目
> 需要 python3 的环境
### 安装依赖
`pip install pygame`
### 运行
`python alien_invasion.py`
### 运行界面

<file_sep>import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from ship import Ship
# from alien import Alien
# from bullet import Bullet
import game_function as gf
from game_stats import GameStats
from button import Button
def run_ganme():
# 初始化游戏,并创建一个屏幕对象
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_heght))
pygame.display.set_caption('Alien invastion')
stats = GameStats(ai_settings)
ship = Ship(ai_settings, screen)
# bullet = Bullet(ai_settings, screen, ship)
# 创建一个用于存储子弹的编组
bullets = Group()
# 创建外星群组
aliens = Group()
# 创建外星人人群
gf.create_fleet(ai_settings, screen, aliens, ship)
#
play_button = Button(ai_settings, screen, 'Play')
# 开始游戏
while True:
# 监听键盘和鼠标事件
gf.check_events(ai_settings, screen, ship, bullets, stats, play_button, aliens)
if stats.game_active:
ship.update()
# 子弹
gf.update_bullets(bullets, aliens, ai_settings, screen, ship)
# 外星人
gf.update_aliens(ai_settings, screen, aliens, bullets, ship, stats)
gf.update_screen(ai_settings, screen, ship, bullets, aliens, stats, play_button)
run_ganme() | d0c076751a6dbfab70dfe4f99bce5f87b4cf8281 | [
"Markdown",
"Python"
] | 2 | Markdown | jjeejj/alien_invasion | 446bb46f67cefd02660a44bdeff6e78ee697e828 | 1338bb7fdabd295495bd4d03efc99f374c968dca |
refs/heads/master | <repo_name>lorrdfarquad/TikTacToeNX<file_sep>/source/main.c
#include <string.h>
#include <stdio.h>
#include <switch.h>
u32 sq1,sq2,sq3,sq4,sq5,sq6,sq7,sq8,sq9;// Squares
int turn = 1;
int winner = 0;
int main(int argc, char *argv[])
{
consoleInit(NULL);
//board
printf("\x1b[19;31H | | ");
printf("\x1b[20;31H | | ");
printf("\x1b[21;31H_____|_____|_____");
printf("\x1b[22;31H | | ");
printf("\x1b[23;31H | | ");
printf("\x1b[24;31H_____|_____|_____");
printf("\x1b[25;31H | | ");
printf("\x1b[26;31H | | ");
printf("\x1b[27;31H | | ");
while(appletMainLoop()) {
touchPosition touch;
u32 touch_count = hidTouchCount();
u32 i;
u64 kDown = hidKeysDown(CONTROLLER_P1_AUTO);
u64 kHeld = hidKeysHeld(CONTROLLER_P1_AUTO);
hidScanInput();
printf("\x1b[2;23HTic Tac Toe made by <NAME>");
printf("\x1b[3;25HPlayer 1 (X) - Player 2 (O)");
printf("\x1b[33;31HPress X to restart.");
printf("\x1b[4;31HPress '+' to exit.");
if(kHeld&KEY_X){
sq1=0;printf("\x1b[20;33H ");
sq2=0;printf("\x1b[20;39H ");
sq3=0;printf("\x1b[20;45H ");
sq4=0;printf("\x1b[23;33H ");
sq5=0;printf("\x1b[23;39H ");
sq6=0;printf("\x1b[23;45H ");
sq7=0;printf("\x1b[26;33H ");
sq8=0;printf("\x1b[26;39H ");
sq9=0;printf("\x1b[26;45H ");
winner=0;
printf("\x1b[36;32H ");
touch.px=0;
touch.py=0;
}
//X turn
if (turn==1&touch.px>480&touch.px<565&touch.py<335&touch.py>285&sq1 != 2) {sq1=1;turn=2;}
if (turn==1&touch.px>569&touch.px<663&touch.py<335&touch.py>285&sq2 != 2) {sq2=1;turn=2;}
if (turn==1&touch.px>665&touch.px<753&touch.py<335&touch.py>285&sq3 != 2) {sq3=1;turn=2;}
if (turn==1&touch.px>480&touch.px<565&touch.py<385&touch.py>335&sq4 != 2) {sq4=1;turn=2;}
if (turn==1&touch.px>569&touch.px<663&touch.py<385&touch.py>335&sq5 != 2) {sq5=1;turn=2;}
if (turn==1&touch.px>665&touch.px<753&touch.py<385&touch.py>335&sq6 != 2) {sq6=1;turn=2;}
if (turn==1&touch.px>480&touch.px<565&touch.py<435&touch.py>380&sq7 != 2) {sq7=1;turn=2;}
if (turn==1&touch.px>569&touch.px<663&touch.py<435&touch.py>380&sq8 != 2) {sq8=1;turn=2;}
if (turn==1&touch.px>665&touch.px<753&touch.py<435&touch.py>380&sq9 != 2) {sq9=1;turn=2;}
//Y turn
if (turn==2&touch.px>480&touch.px<565&touch.py<335&touch.py>285&sq1 != 1) {sq1=2;turn=1;}
if (turn==2&touch.px>569&touch.px<663&touch.py<335&touch.py>285&sq2 != 1) {sq2=2;turn=1;}
if (turn==2&touch.px>665&touch.px<753&touch.py<335&touch.py>285&sq3 != 1) {sq3=2;turn=1;}
if (turn==2&touch.px>480&touch.px<565&touch.py<385&touch.py>335&sq4 != 1) {sq4=2;turn=1;}
if (turn==2&touch.px>569&touch.px<663&touch.py<385&touch.py>335&sq5 != 1) {sq5=2;turn=1;}
if (turn==2&touch.px>665&touch.px<753&touch.py<385&touch.py>335&sq6 != 1) {sq6=2;turn=1;}
if (turn==2&touch.px>480&touch.px<565&touch.py<435&touch.py>380&sq7 != 1) {sq7=2;turn=1;}
if (turn==2&touch.px>569&touch.px<663&touch.py<435&touch.py>380&sq8 != 1) {sq8=2;turn=1;}
if (turn==2&touch.px>665&touch.px<753&touch.py<435&touch.py>380&sq9 != 1) {sq9=2;turn=1;}
for(i=0; i<touch_count; i++)
{
//Read the touch screen coordinates
hidTouchRead(&touch, i);
}
if (sq1==1&sq2==1&sq3==1) winner=1;
if (sq4==1&sq5==1&sq6==1) winner=1;
if (sq7==1&sq8==1&sq9==1) winner=1;
if (sq1==1&sq4==1&sq7==1) winner=1;
if (sq2==1&sq5==1&sq8==1) winner=1;
if (sq3==1&sq6==1&sq9==1) winner=1;
if (sq1==1&sq5==1&sq9==1) winner=1;
if (sq3==1&sq5==1&sq7==1) winner=1;
if (sq1==2&sq2==2&sq3==2) winner=2;
if (sq4==2&sq5==2&sq6==2) winner=2;
if (sq7==2&sq8==2&sq9==2) winner=2;
if (sq1==2&sq4==2&sq7==2) winner=2;
if (sq2==2&sq5==2&sq8==2) winner=2;
if (sq3==2&sq6==2&sq9==2) winner=2;
if (sq1==2&sq5==2&sq9==2) winner=2;
if (sq3==2&sq5==2&sq7==2) winner=2;
if(winner==1){printf("\x1b[36;32HPlayer 1 Wins!");}
if(winner==2){printf("\x1b[36;32HPlayer 2 Wins!");}
consoleUpdate(NULL);
if (sq1 == 1) printf("\x1b[20;33HX");
if (sq1 == 2) printf("\x1b[20;33HO");
if (sq2 == 1) printf("\x1b[20;39HX");
if (sq2 == 2) printf("\x1b[20;39HO");
if (sq3 == 1) printf("\x1b[20;45HX");
if (sq3 == 2) printf("\x1b[20;45HO");
if (sq4 == 1) printf("\x1b[23;33HX");
if (sq4 == 2) printf("\x1b[23;33HO");
if (sq5 == 1) printf("\x1b[23;39HX");
if (sq5 == 2) printf("\x1b[23;39HO");
if (sq6 == 1) printf("\x1b[23;45HX");
if (sq6 == 2) printf("\x1b[23;45HO");
if (sq7 == 1) printf("\x1b[26;33HX");
if (sq7 == 2) printf("\x1b[26;33HO");
if (sq8 == 1) printf("\x1b[26;39HX");
if (sq8 == 2) printf("\x1b[26;39HO");
if (sq9 == 1) printf("\x1b[26;45HX");
if (sq9 == 2) printf("\x1b[26;45HO");
if (kDown & KEY_PLUS) {consoleClear();break;}
//Cases
}
consoleExit(NULL);
return 0;
}
| 9ef677f081facfd754b3ffa65dc39b78419b13bd | [
"C"
] | 1 | C | lorrdfarquad/TikTacToeNX | dd52a4c282b13724a32634adb58cd7506f61bf56 | c3ab512c1f85da5df0f9c2f008bcb6e1423e8d63 |
refs/heads/master | <file_sep><?php
/**
* 一键安装
* @author 刘健 <<EMAIL>>
*/
//$url = 'https://github.com/mixstart/mixphp/archive/master.zip';
$url = 'https://github.com/mixstart/mixphp/archive/RC1.zip';
echo "download {$url} ... ";
copy($url, 'mixphp.zip');
echo 'ok' . PHP_EOL;
echo 'unzip ... ';
$zip = new ZipArchive;
$zip->open('mixphp.zip');
$dirname = $zip->getNameIndex(0);
$zip->extractTo(__DIR__ . '/');
$zip->close();
echo 'ok' . PHP_EOL;
echo 'clean temp files ... ';
unlink('mixphp.zip');
echo 'ok' . PHP_EOL;
echo 'Successfully installed in "' . __DIR__ . DIRECTORY_SEPARATOR . substr($dirname, 0, strlen($dirname) - 1) . '"' . PHP_EOL;
unlink(__FILE__);
| 8c934a73ee23f45da698578895711e73cd080198 | [
"PHP"
] | 1 | PHP | smxrencf/mixphp | 0b0353fb6a6d4db356cb081d6859643fd209f732 | 623019c3d56251470751db8242c41997b15a14e4 |
refs/heads/master | <repo_name>jlsync/scout-plugins<file_sep>/mysql_slow_queries/mysql_slow_queries.rb
require "time"
require "digest/md5"
# MySQL Slow Queries Monitoring plug in for scout.
# Created by Robin "<NAME>" Ward for Forumwarz, based heavily on the Rails Request
# Monitoring Plugin.
#
# See: http://blog.forumwarz.com/2008/5/27/monitor-slow-mysql-queries-with-scout
#
class ScoutMysqlSlow < Scout::Plugin
needs "elif"
def build_report
log_file_path = option("mysql_slow_log").to_s.strip
if log_file_path.empty?
return error( "A path to the MySQL Slow Query log file wasn't provided.",
"The full path to the slow queries log must be provided. Learn more about enabling the slow queries log here: http://dev.mysql.com/doc/refman/5.1/en/slow-query-log.html" )
end
slow_query_count = 0
slow_queries = []
sql = []
last_run = memory(:last_run) || Time.now
current_time = Time.now
Elif.foreach(log_file_path) do |line|
if line =~ /^# Query_time: (\d+) .+$/
query_time = $1.to_i
slow_queries << {:time => query_time, :sql => sql.reverse}
sql = []
elsif line =~ /^\# Time: (.*)$/
t = Time.parse($1) {|y| y < 100 ? y + 2000 : y}
t2 = last_run
if t < t2
break
else
slow_queries.each do |sq|
slow_query_count +=1
# calculate importance
importance = 0
importance += 1 if sq[:time] > 3
importance += 1 if sq[:time] > 10
importance += 1 if sq[:time] > 30
parsed_sql = sq[:sql].join
hint(:title => "#{sq[:time]} sec Query: #{parsed_sql[0..80]}...",
:additional_info => sq[:sql],
:token => Digest::MD5.hexdigest("slow_query_#{parsed_sql.size > 250 ? parsed_sql[0..250] + '...' : parsed_sql}"),
:importance=> importance,
:tag_list=>'slow')
end
end
elsif line !~ /^\#/
sql << line
end
end
elapsed_seconds = current_time - last_run
logger.info "Current Time: #{current_time}"
logger.info "Last run: #{last_run}"
logger.info "Elapsed: #{elapsed_seconds}"
elapsed_seconds = 1 if elapsed_seconds < 1
logger.info "Elapsed after min: #{elapsed_seconds}"
logger.info "count: #{slow_query_count}"
# calculate per-second
report(:slow_queries => slow_query_count/(elapsed_seconds/60.to_f))
remember(:last_run,Time.now)
end
end
| a9769770915361e304dc88859eb8aa30154eefc1 | [
"Ruby"
] | 1 | Ruby | jlsync/scout-plugins | 4fe24648d14ad865eeb6c3190a32b4983ac9d3c0 | 4283196cf3c208f9a93d01a63d267381280e6ce0 |
refs/heads/master | <file_sep># Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.11] - 2021-03-01
### Changed
- Fixed #45 Grammar no longer accepts mixed-case keywords TRUE/FALSE/T/F as True/False to be consistent with Moodle's parser.
## [0.1.10] - 2020-06-24
## [0.1.9] - 2020-06-23
## [0.1.8] - 2020-06-23
[0.1.11]: https://github.com/fuhrmanator/GIFT-grammar-PEG.js/compare/v0.1.10...v0.1.11
[0.1.10]: https://github.com/fuhrmanator/GIFT-grammar-PEG.js/compare/v0.1.9...v0.1.10
[0.1.9]: https://github.com/fuhrmanator/GIFT-grammar-PEG.js/compare/v0.1.8...v0.1.9
[0.1.8]: https://github.com/fuhrmanator/GIFT-grammar-PEG.js/compare/v0.1.7...v0.1.8
<file_sep>var peg = require('pegjs');
var assert = require('assert');
const fs = require('fs');
const questionsFolder = './tests/questions/';
const glob = require("glob");
describe('GIFT parser harness: ', () => {
before(function () {
// read grammar and create parser
var grammar = fs.readFileSync('GIFT.pegjs', 'utf-8');
this.parser = peg.generate(grammar);
});
// read the set of questions/parsings data files
var files = glob.sync(questionsFolder + "*.gift", { nonull: true });
files.forEach(function (file) {
it('parsing GIFT question: ' + file, function () {
var jsonFile = file.substr(0, file.lastIndexOf('.')) + ".json";
var giftText = fs.readFileSync(file, 'utf-8');
var jsonText = fs.readFileSync(jsonFile, 'utf-8');
var jsonParse = JSON.parse(jsonText);
var parsing = this.parser.parse(giftText);
assert.deepEqual(parsing, jsonParse, "Deep equal does not match");
});
});
});
<file_sep>/* PEG API Types */
export declare function parse(input: string, options?: Options): GIFTQuestion[];
export declare class SyntaxError extends Error {
location: LocationRange;
expected: Expectation[];
found: string | null;
name: string;
message: string;
}
interface Options {
filename?: string;
startRule?: string;
tracer?: any;
[key: string]: any;
}
export interface Location {
line: number;
column: number;
offset: number;
}
export interface LocationRange {
start: Location;
end: Location;
}
export interface LiteralExpectation {
type: "literal";
text: string;
ignoreCase: boolean;
}
export interface ClassParts extends Array<string | ClassParts> {}
export interface ClassExpectation {
type: "class";
parts: ClassParts;
inverted: boolean;
ignoreCase: boolean;
}
export interface AnyExpectation {
type: "any";
}
export interface EndExpectation {
type: "end";
}
export interface OtherExpectation {
type: "other";
description: string;
}
export type Expectation =
| LiteralExpectation
| ClassExpectation
| AnyExpectation
| EndExpectation
| OtherExpectation;
/* GIFT Question Types */
export type QuestionType =
| "Description"
| "Category"
| "MC"
| "Numerical"
| "Short"
| "Essay"
| "TF"
| "Matching";
export type FormatType = "moodle" | "html" | "markdown" | "plain";
export type NumericalType = "simple" | "range" | "high-low";
export interface TextFormat {
format: FormatType;
text: string;
}
export interface NumericalFormat {
type: NumericalType;
number?: number;
range?: number;
numberHigh?: number;
numberLow?: number;
}
export interface TextChoice {
isCorrect: boolean;
weight: number | null;
text: TextFormat;
feedback: TextFormat | null;
}
export interface NumericalChoice {
isCorrect: boolean;
weight: number | null;
text: NumericalFormat;
feedback: TextFormat | null;
}
interface Question {
id?: string | null;
tags?: string[] | null;
type: QuestionType;
title: string | null;
stem: TextFormat;
hasEmbeddedAnswers: boolean;
globalFeedback: TextFormat | null;
}
export interface Description {
id?: string | null;
tags?: string[] | null;
type: Extract<QuestionType, "Description">;
title: string | null;
stem: TextFormat;
hasEmbeddedAnswers: boolean;
}
export interface Category {
id?: string | null;
tags?: string[] | null;
type: Extract<QuestionType, "Category">;
title: string;
}
export interface MultipleChoice extends Question {
type: Extract<QuestionType, "MC">;
choices: TextChoice[];
}
export interface ShortAnswer extends Question {
type: Extract<QuestionType, "Short">;
choices: TextChoice[];
}
export interface Numerical extends Question {
type: Extract<QuestionType, "Numerical">;
choices: NumericalChoice[] | NumericalFormat;
}
export interface Essay extends Question {
type: Extract<QuestionType, "Essay">;
}
export interface TrueFalse extends Question {
type: Extract<QuestionType, "TF">;
isTrue: boolean;
incorrectFeedback: TextFormat | null;
correctFeedback: TextFormat | null;
}
export interface Matching extends Question {
type: Extract<QuestionType, "Matching">;
matchPairs: Match[];
}
export interface Match {
subquestion: TextFormat;
subanswer: string;
}
export type GIFTQuestion =
| Description
| Category
| MultipleChoice
| ShortAnswer
| Numerical
| Essay
| TrueFalse
| Matching;
<file_sep>import { expectType, expectError } from 'tsd';
import { Category, Description, Essay, GIFTQuestion, Matching, MultipleChoice, Numerical, parse, ShortAnswer, SyntaxError, TrueFalse } from ".";
expectType<GIFTQuestion[]>(parse('Text'));
const questions = parse("Text");
for (const question of questions) {
switch (question.type) {
case "Category":
expectType<Category>(question);
break;
case "Description":
expectType<Description>(question);
break;
case "MC":
expectType<MultipleChoice>(question);
break;
case "Numerical":
expectType<Numerical>(question);
break;
case "Short":
expectType<ShortAnswer>(question);
break;
case "Essay":
expectType<Essay>(question);
break;
case "TF":
expectType<TrueFalse>(question);
break;
case "Matching":
expectType<Matching>(question);
break;
default:
break;
}
}
const multipleChoiceObject: MultipleChoice = {
id: null,
tags: null,
type: "MC",
title: null,
stem: { format: "markdown", text: "Who's buried in Grant's \r\n tomb?" },
hasEmbeddedAnswers: false,
globalFeedback: {
format: "moodle",
text:
"Not sure?."
},
choices: [
{
isCorrect: false,
weight: -50,
text: { format: "moodle", text: "Grant" },
feedback: null
},
{
isCorrect: true,
weight: 50,
text: { format: "moodle", text: "Jefferson" },
feedback: null
},
{
isCorrect: true,
weight: 50,
text: { format: "moodle", text: "no one" },
feedback: null
}
]
};
expectType<MultipleChoice>(multipleChoiceObject)<file_sep>GIFT grammar for PEG.js
---
Why?
- GIFT is a very portable and rich format for questions (Moodle)
- GIFT wins over clicking in a GUI (Moodle) for 100 questions
- GIFT is a simple question bank
- GIFT editing
- smart editor outside of Moodle
- using PEG.js to parse with JavaScript<file_sep>var converter;
function giftPreviewHTML(qArray, theDiv) {
converter = new showdown.Converter();
var html = "";
var q;
for (var i=0; i<qArray.length; i++) {
// console.log("i = " + i + " and qArray[i] is '" + qArray[i] );
q = qArray[i];
html += '<div id="question_' + i + '">';
// console.log("q.type is '" + q.type );
switch (q.type) {
case "Description":
html += makeTitle("Description", q.title);
html +="<p>" + applyFormat(q.stem) + "</p>";
theDiv.append(html); html = "";
break;
case "MC":
html += makeTitle("Multiple choice", q.title);
html +="<p>" + applyFormat(q.stem) + "</p>";
html += formatAnswers(q.choices);
html += formatFeedback(q.globalFeedback) + "</div>";
theDiv.append(html); html = "";
break;
case "Short":
html += makeTitle("Short answer", q.title);
html +="<p>" + applyFormat(q.stem) + "</p>";
html += formatAnswers(q.choices);
html += formatFeedback(q.globalFeedback) + "</div>";
theDiv.append(html); html = "";
break;
case "Essay":
html += makeTitle("Essay", q.title);
html +="<p>" + applyFormat(q.stem) + "</p>";
html += formatFeedback(q.globalFeedback) + "</div>";
theDiv.append(html); html = "";
break;
case "TF":
html += makeTitle("True/False", q.title);
html +="<p>" + "<em>(" + (q.isTrue ? "True" : "False") + ")</em> " + applyFormat(q.stem) + "</p>";
html += formatFeedback(q.globalFeedback) + "</div>";
theDiv.append(html); html = "";
break;
case "Matching":
html += makeTitle("Matching", q.title);
html +="<p>" + applyFormat(q.stem) + "</p>";
formatMatchingAnswers(q, theDiv, i, html);
html = formatFeedback(q.globalFeedback) + "</div>";
theDiv.append(html); html = "";
break;
// for case "Matching": see https://stackoverflow.com/a/35493737/1168342
default:
break;
}
}
}
function makeTitle(type, title) {
return "<b>" + type + (title !== null ? ' "' + title + '"' : "" ) + "</b>";
}
function formatAnswers(choices) {
var html = '<ul class="mc">';
shuffle(choices);
for (var a=0; a<choices.length; a++) {
var answer = choices[a];
html += '<li class="' +
((answer.isCorrect || answer.weight > 0) ? 'rightAnswer' : 'wrongAnswer') +
'">' + (answer.weight !== null ? "<em>(" + answer.weight + "%)</em> " : '') +
applyFormat(answer.text) +
(answer.feedback !== null ? " [" + applyFormat(answer.feedback) + "]" : '') +
"</li>";
}
html += "</ul>";
return html;
}
function formatMatchingAnswers(q, theDiv, qNum, html) {
var rightSideChoices = new Set();
var htmlLines = '';
for (var i=0; i<q.matchPairs.length; i++) {
htmlLines += '<path id="line' + i + '" stroke="rgba(180,180,255,0.5)" stroke-width="5" fill="none"/>';
}
html += '<svg class="theSVG" style="position: absolute; z-index: -1;" width="100%" height="100%" z-index="-1"><g>' + htmlLines + '</g></svg>';
html +='<div class="row"><div class="col-md-6">'; // left side
for (var i=0; i<q.matchPairs.length; i++) {
var pair = q.matchPairs[i];
html += '<div id="left' + i + '" style="background:#ddddff">';
html += '<p>' + applyFormat(pair.subquestion) + '</p>';
html += '</div>';
rightSideChoices.add(pair.subanswer);
}
//console.log('Found rightSideChoices: ' + rightSideChoices.size);
html += '</div>'
html += '<div class="col-md-6">'; // right side
var rightSideArray = Array.from(rightSideChoices);
shuffle(rightSideArray);
for (var it = rightSideArray.values(), val= null; val=it.next().value;) {
html += '<div id="right_' + val.replace(/\s/g, '_') + '" style="background:#ddddff">';
html += '<p>' + val + '</p>';
html += '</div>';
}
html += '</div></div>'
// make the SVG for lines, see https://stackoverflow.com/a/35493737/1168342
theDiv.append(html); html = ""; // force the HTML into the DOM
// set the lines up - search only inside this question's div (theDiv)
for (var i=0; i<q.matchPairs.length; i++) {
var qDiv = $("#question_" + qNum);
var pair = q.matchPairs[i];
var line = qDiv.find("#line" + i); //console.log("line" + i + ": " + line);
var leftDiv = qDiv.find("#left" + i); //console.log("leftDiv: " + leftDiv);
var subAnswerID = $.escapeSelector("right_" + pair.subanswer.replace(/\s/g, '_'));
var rightDiv = qDiv.find('#' + subAnswerID);
var pos1 = leftDiv.offset();
var pos2 = rightDiv.offset();
var svg = qDiv.find(".theSVG").offset();
var x1 = pos1.left - svg.left + leftDiv.width();
var y1 = pos1.top + leftDiv.height()/2 - svg.top;
var x2 = pos2.left - svg.left;
var y2 = pos2.top + rightDiv.height()/2 - svg.top;
var inset = 10;
line.attr('d', "M" + x1 + "," + y1 + " C" + (x1 + inset) + "," + y1 + " " + (x2 - inset) + ',' + y2 + " " + x2 + "," + y2);
qDiv.find(".theSVG").attr('height', pos1.top + leftDiv.height() - svg.top);
}
}
function applyFormat(giftText) {
var html = "";
var unescapedString;
switch (giftText.format) {
case "html":
case "moodle":
// convert Moodle's embedded line feeds (GIFT) to HTML
unescapedString = giftText.text.replace(/\\n/g, '<br\>');
html = unescapedString;
break;
case "plain":
html = giftText.text;
break;
case "markdown":
// convert Moodle's embedded line feeds (GIFT) in markdown
unescapedString = giftText.text.replace(/\\n/g, '\n');
html = converter.makeHtml(unescapedString);
break;
default:
break;
}
if (html=="") html=" "; // special case so div's aren't empty
return html;
}
function formatFeedback(feedback) {
return feedback !== null ?
'<p style="margin-left: 40px"><em>General feedback:</em> ' +
applyFormat(feedback) + '</p>' : '';
}
// https://stackoverflow.com/a/2450976/1168342
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}<file_sep>#!/usr/bin/env bash
{ echo "<script>"; cat lib/gift-parser-globals.js; echo "</script>"; } > lib/gift-parser-globalsJS.html | 634afd4cff5d0fd68f5780762e81243f6fae67ec | [
"Markdown",
"TypeScript",
"JavaScript",
"Shell"
] | 7 | Markdown | ethan-ou/GIFT-grammar-PEG.js | e2c3927ccce703f791eaf804bb264ef7580cee41 | aa29b15f613af7bf5a3881705bdaf39167adc315 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace _2019_06_01.Anagrams
{
public interface IAnagramsFinder
{
string[] GetAnagrams();
}
}
<file_sep>using System.Collections.Generic;
namespace _2019_06_16
{
public interface IFlags
{
Dictionary<string, string> GetFlags(string v);
}
}<file_sep>using _2019_06_01.Anagrams;
using Moq;
using System;
using Xunit;
namespace XUnitTest
{
public class AngramsTest
{
/*
Clase -> Metodos Principales para validar y en paquetar
Interface -> Retornar la lista de palabras
Clase -> Validar que reciba lista de palabras
-> Null Exception
Clase -> validar que dos palabras coincidan
*/
[Fact]
public void AnagramsFinder_ReturnsNull_Throw_NullReferenceException()
{
//Arrage
var iAnagramsFinder = new Mock<IAnagramsFinder>();
iAnagramsFinder.Setup(x => x.GetAnagrams()).Returns<string[]>(null);
//Assert
Assert.Throws<NullReferenceException>(() => new AnagramsManager(iAnagramsFinder.Object));
}
[Fact]
public void AnagramsFinder_Returns_Items_AnagramsList_HasValue()
{
//Arrage
string[] testData = new string[] { "test1", "test2" };
var iAnagramsFinder = new Mock<IAnagramsFinder>();
iAnagramsFinder.Setup(x => x.GetAnagrams()).Returns(testData);
var anagramsManager = new AnagramsManager(iAnagramsFinder.Object);
//Act
var actual = anagramsManager.AnagramsList;
//Assert
Assert.Equal(testData, actual);
}
[Fact]
public void Anagram_Validator_Params_Are_NotEquals_Returns_False()
{
//Arrage
string[] testData = new string[] { "test1", "test2" };
var iAnagramsFinder = new Mock<IAnagramsFinder>();
iAnagramsFinder.Setup(x => x.GetAnagrams()).Returns(testData);
var anagramsManager = new AnagramsManager(iAnagramsFinder.Object);
//Act
var actual = anagramsManager.Validator(testData[0], testData[1]);
//Assert
Assert.False(actual);
}
[Fact]
public void Anagram_Validator_Params_Are_Equals_Returns_True()
{
//Arrage
string[] testData = new string[] { "test1", "1tesT" };
var iAnagramsFinder = new Mock<IAnagramsFinder>();
iAnagramsFinder.Setup(x => x.GetAnagrams()).Returns(testData);
var anagramsManager = new AnagramsManager(iAnagramsFinder.Object);
//Act
var actual = anagramsManager.Validator(testData[0], testData[1]);
//Assert
Assert.True(actual);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace _2019_06_08
{
public class BallsSorter
{
public List<int> balls { get; private set; } = new List<int>();
public void Add(int v)
{
int index = 0;
foreach(var ball in balls)
{
if (v < ball)
break;
index++;
}
balls.Insert(index, v);
}
}
}<file_sep>using _2019_06_15;
using System;
using System.Collections.Generic;
using Xunit;
namespace XUnitTest
{
public class ArgsSchemaTest
{
/*
*-l -> bool
*-p -> port (string)
-d -> path (string)
*-g -> string list
*-d -> int list
If null -> throw ArgumentNullException
-l -> 1. Exist, 2. No Exist
-p -> PortFlag has value
-g -> StringList has value
-d -> IntList has value
*/
[Fact]
public void Text_IsNull_Throw_ArgumentNullException()
{
//arrage
ArgsSchema argsSchema;
//act
Action actual = () => argsSchema = new ArgsSchema(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void L_Flag_NoExist_Loggin_IsFalse()
{
//arrage
ArgsSchema argsSchema = new ArgsSchema("");
//act
bool actual = argsSchema.Loggin;
//assert
Assert.False(actual);
}
[Fact]
public void L_Flag_Exist_Loggin_IsTrue()
{
//arrage
ArgsSchema argsSchema = new ArgsSchema("-l");
//act
bool actual = argsSchema.Loggin;
//assert
Assert.True(actual);
}
[Fact]
public void P_Flag_Exist_Port_HasValue()
{
//arrage
ArgsSchema argsSchema = new ArgsSchema("-p 8080");
//act
string actual = argsSchema.Port;
//assert
Assert.Equal("8080", actual);
}
[Fact]
public void G_Flag_Exist_StringList_HasValue()
{
//arrage
ArgsSchema argsSchema = new ArgsSchema("-g this,is,a,list");
//act
List<string> actual = argsSchema.StringList;
var result = new List<string> { "this", "is", "a", "list" };
//assert
Assert.Equal(result, actual);
}
[Fact]
public void D_Flag_Exist_IntList_HasValue()
{
//arrage
ArgsSchema argsSchema = new ArgsSchema("-d 1,2,-3,5");
//act
List<int> actual = argsSchema.IntList;
var result = new List<int> { 1, 2, -3, 5 };
//assert
Assert.Equal(result, actual);
}
}
}
<file_sep>using System;
using System.Linq;
namespace _2019_05_25
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite los numeros:");
var number = Console.ReadLine();
Console.WriteLine(add(number));
Console.ReadKey();
}
static string add(string number)
{
if (string.IsNullOrWhiteSpace(number))
return "0";
string separator = ",";
int position = 0;
int sum = 0;
string errors = "";
if (number.StartsWith("//"))
{
number = number.Replace("\\n", "\n");
var separatorIndex = number.IndexOf("\n");
separator = number.Substring(0, separatorIndex);
separator = separator.Replace("//", "");
int numberLength = number.Count() - (separatorIndex + 1);
number = number.Substring(separatorIndex + 1, numberLength);
position += 5;
}
var numbers = number.Split(separator);
foreach (var num in numbers)
{
var xNum = num.Replace("\\n", "\n");
if (string.IsNullOrWhiteSpace(xNum))
{
errors += "Number expected but EOF found. \n";
continue;
}
if (xNum.IndexOf('\n') > -1)
{
if (xNum.StartsWith('\n'))
{
errors = $"Number expected but '\\n' found at position {position}. \n";
continue;
}
var subNumbers = xNum.Split('\n');
foreach(var sn in subNumbers)
{
sum += int.Parse(sn);
position += sn.Count() + 1;
}
continue;
}
sum += int.Parse(xNum);
position += xNum.Count() + 1;
}
if (!string.IsNullOrWhiteSpace(errors))
return errors;
return sum.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace _2019_07_06
{
public class Wrapper
{
public static string Wrap(string text, int columns)
{
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentNullException();
string result = "";
int wordsInLine = 0;
foreach(var word in text.Split(' '))
{
if (wordsInLine == columns)
{
result += "\n";
wordsInLine = 0;
}
if (result != "" && wordsInLine != 0)
result += " ";
result += word;
wordsInLine++;
}
return result;
}
}
}<file_sep>using System;
namespace _2019_07_07
{
public class Wrapper
{
public static string Wrap(string text, int columns)
{
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentNullException();
string result = "";
int columnLine = 0;
foreach(var word in text.Split(' '))
{
if (columnLine == columns)
{
result += "\n";
columnLine = 0;
}
if (columnLine != 0 && result != "")
result += " ";
result += word;
columnLine++;
}
return result;
}
}
}<file_sep>using _2019_06_29;
using System;
using Xunit;
namespace XUnitTest
{
public class RomanNumeralConverterTest
{
/*
Param is 0 -> throw ArgumentOutOfRange
Convert Number -> return RomanNumber
Convert complex number -> return RomanNumber
param is null or empty -> argumentnullexception
convert roman -> return number
convert complex roman -> return number
*/
[Fact]
public void Number_IsNull_Returns_ArgumentOutOfRangeException()
{
//arrage
RomanNumeralConverter romanNumeral = new RomanNumeralConverter();
//act
Action actual = () => romanNumeral.ConvertNumber(0);
//assert
Assert.Throws<ArgumentOutOfRangeException>(actual);
}
[Theory]
[InlineData("I", 1)]
[InlineData("V", 5)]
[InlineData("X", 10)]
[InlineData("L", 50)]
[InlineData("C", 100)]
[InlineData("D", 500)]
[InlineData("M", 1000)]
[InlineData("IV", 4)]
[InlineData("IX", 9)]
[InlineData("XL", 40)]
[InlineData("CD", 400)]
[InlineData("CM", 900)]
public void Send_Simple_Number_Returns_RomanNumber(string excepected, int value)
{
//arrage
RomanNumeralConverter romanNumeral = new RomanNumeralConverter();
//act
string actual = romanNumeral.ConvertNumber(value);
//assert
Assert.Equal(excepected, actual);
}
[Fact]
public void Send_Complex_Number_Returns_RomanNumber()
{
//arrage
RomanNumeralConverter romanNumeral = new RomanNumeralConverter();
//act
string actual = romanNumeral.ConvertNumber(327);
//assert
Assert.Equal("CCCXXVII", actual);
}
[Fact]
public void Roman_IsNull_Throws_ArgumentNullException()
{
//arrage
RomanNumeralConverter romanNumeral = new RomanNumeralConverter();
//act
Action actual = () => romanNumeral.ConvertRoman(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void Send_Simple_Roman_Returns_Number()
{
//arrage
RomanNumeralConverter romanNumeral = new RomanNumeralConverter();
//act
int actual = romanNumeral.ConvertRoman("I");
//assert
Assert.Equal(1, actual);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2019_06_01.Anagrams
{
public class AnagramsManager
{
public string[] AnagramsList { get; set; }
public AnagramsManager(IAnagramsFinder finder)
{
AnagramsList = finder.GetAnagrams();
if (AnagramsList == null)
throw new NullReferenceException();
}
public bool Validator(string v1, string v2)
{
if (v1.Count() != v2.Count())
return false;
var temp1 = v1.ToLower().Select(x => x).OrderBy(x => x);
var temp2 = v2.ToLower().Select(x => x).OrderBy(x => x);
var v1Ordered = string.Join("", temp1);
var v12Ordered = string.Join("", temp2);
return v1Ordered == v12Ordered;
}
}
}
<file_sep>using System;
using System.Linq;
namespace _2019_05_26
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Escriba los numeros: ");
var number = Console.ReadLine();
Console.WriteLine(add(number));
Console.ReadKey();
}
static string add(string number)
{
if (string.IsNullOrWhiteSpace(number))
return "0";
int result = 1;
string errors = "";
string negatives = "";
int position = 0;
var numbers = number.Split(",");
foreach(var num in numbers)
{
var fNum = num.Replace("\\n", "\n");
if (fNum.StartsWith("\n"))
errors += $"Number expected but '\\n' found at position {position}.";
var sNums = fNum.Split("\n");
foreach(var sn in sNums)
{
result *= validation(ref negatives, sn);
}
if (sNums.Count() == 0)
result *= validation(ref negatives, fNum);
position += fNum.Count() + 1;
}
if (!string.IsNullOrWhiteSpace(negatives))
errors += $"Negative not allowed : { negatives }";
if (!string.IsNullOrWhiteSpace(errors))
return errors;
return result.ToString();
}
static int validation(ref string negatives, string val)
{
var value = int.Parse(val);
if (value < 0)
negatives += (string.IsNullOrWhiteSpace(negatives)) ? value.ToString() : $", {value.ToString()}";
return value;
}
}
}
<file_sep>using _2019_06_09;
using System;
using Xunit;
namespace XUnitTest
{
public class CharacterSorterTest
{
/*
Si el parametro es nulo -> throw argumentnullexception
Las letras pasaran de mayusculas a minusculas -> retorn mins
Se ignoraran los signos de puntuacion -> retorn without puntationsign
Se concatenaran los caracteres de forma ascendente -> retorn sortedstring
*/
[Fact]
public void Text_IsNull_Throw_ArgumentNullException()
{
//arrage
CharacterSorter characterSorter = new CharacterSorter();
//act
Action actual = () => characterSorter.SortText(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void Text_Has_Mayus_Returns_Text_Minus()
{
//arrage
CharacterSorter characterSorter = new CharacterSorter();
//act
string actual = characterSorter.SortText("AABZ");
//assert
Assert.Equal("aabz", actual);
}
[Fact]
public void Text_Has_Special_Characters_Returns_Text_Without_Special_Characters()
{
//arrage
CharacterSorter characterSorter = new CharacterSorter();
//act
string actual = characterSorter.SortText("A!A.bz");
//assert
Assert.Equal("aabz", actual);
}
[Fact]
public void Text_Returns_Text_Sorted_By_Characters()
{
//arrage
CharacterSorter characterSorter = new CharacterSorter();
//act
string actual = characterSorter.SortText("bzAa");
//assert
Assert.Equal("aabz", actual);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace _2019_06_16
{
public class ArgsSchema
{
private IFlags flags;
public ArgsSchema(IFlags flags)
{
this.flags = flags;
}
public bool Loggin { get; set; }
public List<int> IntList { get; set; }
public void GetArgs(string v)
{
var dict = flags.GetFlags(v);
Loggin = dict.Where(x => x.Key == "l").Select(x => x.Value).FirstOrDefault() != null;
if (dict.Where(x => x.Key == "d").Select(x => x.Value).FirstOrDefault() != null)
IntList = new List<int> { 1, 2, -3, 9 };
}
}
}<file_sep>using _2019_07_06;
using System;
using Xunit;
namespace XUnitTest
{
public class WrapperTest
{
/*
text is null or empty -> argumentNullException
text has a word -> same result
text -> separated
text ignore last space if match with column ->
*/
[Theory]
[InlineData(null)]
[InlineData("")]
public void Text_IsNullOrEmpty_Throws_ArgumentNullException(string text)
{
//act
Action actual = () => Wrapper.Wrap(text, 0);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void Text_Has_A_Word_Returns_SameResult()
{
//act
string actual = Wrapper.Wrap("Test", 2);
//assert
Assert.Equal("Test", actual);
}
[Fact]
public void Text_Has_Eight_Words_Returns_Three_Lines()
{
//act
string actual = Wrapper.Wrap("This is a test for unit testing, enjoyit", 3);
//assert
Assert.Equal("This is a\ntest for unit\ntesting, enjoyit", actual);
}
[Fact]
public void Text_Last_Word_Match_With_Space_Returns_Text_WithOut_Last_Space()
{
//act
string actual = Wrapper.Wrap("This is a test", 2);
//assert
Assert.Equal("This is\na test", actual);
}
}
}
<file_sep>using _2019_06_02.Anagrams;
using System;
using System.Linq;
using Xunit;
namespace XUnitTest
{
public class UnitTest1
{
/*
AnagramsFinder ->
validate -> string, string
-Numero de letras diferentes -> falso
-Caso exitoso, las dos palabras son anagramas
- Palabras no son anagramas
GroupAnagram ->
- Identifica grupo
- Si existe la registra para ese grupo
- Si no, crea grupo nuevo
*/
[Fact]
public void Number_Letters_NotEquals_Returns_False()
{
var anagramsFinder = new AnagramsFinder();
var actual = anagramsFinder.Validate("test1", "test");
Assert.False(actual);
}
[Fact]
public void Words_Are_Anagrams_Returns_True()
{
var anagramsFinder = new AnagramsFinder();
var actual = anagramsFinder.Validate("test1", "1test");
Assert.True(actual);
}
[Fact]
public void Words_Are_Not_Anagrams_Returns_False()
{
var anagramsFinder = new AnagramsFinder();
var actual = anagramsFinder.Validate("test1", "2test");
Assert.False(actual);
}
[Fact]
public void Exist_Anagram_Group_GroupNotIncress()
{
var anagramsFinder = new AnagramsFinder();
anagramsFinder.GroupAnagram("test1");
anagramsFinder.GroupAnagram("1test");
var anagramsCount = anagramsFinder.Anagrams;
var actual = anagramsCount.Count();
Assert.Equal(1, actual);
}
[Fact]
public void Not_Exist_Anagram_Group_GroupIncress()
{
var anagramsFinder = new AnagramsFinder();
anagramsFinder.GroupAnagram("test1");
anagramsFinder.GroupAnagram("test2");
var anagramsCount = anagramsFinder.Anagrams;
var actual = anagramsCount.Count();
Assert.Equal(2, actual);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace _2019_06_15
{
public class ArgsSchema
{
public ArgsSchema(string text)
{
if (text == null)
throw new ArgumentNullException();
ReadFlags(text);
}
private void ReadFlags(string text)
{
if (text == "-l")
Loggin = true;
if (text == "-p 8080")
Port = "8080";
if (text == "-g this,is,a,list")
StringList = new List<string> { "this", "is", "a", "list" };
if (text == "-d 1,2,-3,5")
IntList = new List<int> { 1, 2, -3, 5 };
}
public bool Loggin { get; set; }
public string Port { get; set; }
public List<string> StringList { get; set; }
public List<int> IntList { get; set; }
}
}<file_sep>using System;
namespace _2019_06_09
{
public class CharacterSorter
{
public string SortText(string text)
{
if (text == null)
throw new ArgumentNullException();
text = text.ToLower();
string temp = "";
foreach(var ch in text)
{
if (ch >= 'a' && ch <= 'z')
temp += ch;
}
char[] chars = temp.ToCharArray();
bool cont;
int count = chars.Length;
do
{
cont = false;
for(int i = 0; i < count - 1; ++i)
{
if (chars[i] > chars[i + 1])
{
char tt = chars[i];
chars[i] = chars[i + 1];
chars[i + 1] = tt;
cont = true;
}
}
count--;
} while (cont);
return string.Join(string.Empty, chars);
}
}
}<file_sep>using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace StringCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Escriba los numberos que desea sumar: ");
var input = Console.ReadLine();
var stringCalculator = new StringCalculator();
var output = stringCalculator.add(input);
Console.WriteLine($"El resultado es: {output}");
Console.ReadKey();
}
}
class StringCalculator
{
public string add(string number)
{
//if (string.IsNullOrWhiteSpace(number))
// return "";
string[] numbers = number.Split(',');
string errors = "";
double sum = 0;
foreach (var num in numbers)
{
if (num.IndexOf('\n') > -1)
{
if (num.IndexOf('\n') > 2)
{
errors += $"Number expected but '\n' found at position {number.IndexOf(num)}";
continue;
}
var listSubNums = num.Split(new[] { @"\\n" }, StringSplitOptions.None);
foreach (var subNum in listSubNums)
{
sum += int.Parse(num);
}
}
sum += int.Parse(num);
}
if (errors.Count() > 0)
return errors;
//foreach(var number )
return sum.ToString();
}
}
}
<file_sep>using System;
using System.Linq;
namespace _2019_06_22
{
public class Range
{
private static int[] ExtractRange(string range)
{
var nums = range.Substring(1, range.Length - 2)
.Split(',')
.Select(x => int.Parse(x.Trim()))
.OrderBy(x => x)
.ToArray();
if (range[0] == '(')
nums[0] = nums[0] + 1;
if (range[range.Length - 1] == ')')
nums[nums.Length - 1] = nums[nums.Length - 1] - 1;
return nums;
}
public static bool Compare(string range, string compare)
{
if (string.IsNullOrWhiteSpace(range) || string.IsNullOrWhiteSpace(compare))
throw new ArgumentNullException();
//range
var rangeNums = ExtractRange(range);
//compare
var compareNums = ExtractRange(compare);
if (rangeNums[0] <= compareNums[0] && rangeNums[rangeNums.Length - 1] >= compareNums[compareNums.Length - 1])
return true;
return false;
}
}
}<file_sep>using _2019_06_22;
using System;
using Xunit;
namespace XUnitTest
{
public class RangeTest
{
/*
If Params are null -> Throw argumentnull exception
Range contains nums list -> Returns true {0, 1, 2, ..}
Ranges not contains nums list -> Returns false
Range contains other range -> Returns true
Range not contains other range -> returns false
*/
[Fact]
public void Params_Are_Null_Throws_ArgumentNullException()
{
Action range = () => Range.Compare(null, null);
Assert.Throws<ArgumentNullException>(range);
}
[Fact]
public void Range_Contains_NumsList_Returns_True()
{
//arrage
string range = "[0, 10]";
string compare = "{2, 3, 4}";
//act
bool actual = Range.Compare(range, compare);
//assert
Assert.True(actual);
}
[Fact]
public void Range_Not_Contains_NumsList_Returns_False()
{
//arrage
string range = "[0, 10]";
string compare = "{2, -1, 3, 4}";
//act
bool actual = Range.Compare(range, compare);
//assert
Assert.False(actual);
}
[Fact]
public void Range_Contains_Range_Returns_True()
{
//arrage
string range = "[0, 10]";
string compare = "[0, 9)";
//act
bool actual = Range.Compare(range, compare);
//assert
Assert.True(actual);
}
[Fact]
public void Range_Not_Contains_Range_Returns_False()
{
//arrage
string range = "[0, 8)";
string compare = "(0, 9]";
//act
bool actual = Range.Compare(range, compare);
//assert
Assert.False(actual);
}
}
}
<file_sep>using System;
using System.Linq;
namespace _2019_06_23
{
public class Range
{
public int[] RangeNumbers { get; set; }
public Range(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException();
RangeNumbers = GetRange(value);
}
private int[] GetRange(string value)
{
var range = value.Substring(1, value.Length - 2).Split(',')
.Select(x => int.Parse(x.Trim()))
.OrderBy(x => x).ToArray();
if (value[0] == '(')
range[0]++;
if (value[value.Length - 1] == ')')
range[range.Length - 1]--;
return range;
}
public bool Contains(string range)
{
if (string.IsNullOrWhiteSpace(range))
throw new ArgumentNullException();
var compareNums = GetRange(range);
if (RangeNumbers[0] <= compareNums[0] &&
RangeNumbers[RangeNumbers.Length - 1] >= compareNums[compareNums.Length - 1])
return true;
return false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace _2019_06_29
{
public class RomanNumeralConverter
{
Dictionary<string, int> RomanNumbers = new Dictionary<string, int>
{
{ "I", 1 },
{ "IV", 4 },
{ "V", 5 },
{ "IX", 9 },
{ "X", 10 },
{ "XL", 40 },
{ "L", 50 },
{ "XC", 90 },
{ "C", 100 },
{ "CD", 400 },
{ "D", 500 },
{ "CM", 900 },
{ "M", 1000 }
};
public string ConvertNumber(int value)
{
if (value == 0)
throw new ArgumentOutOfRangeException();
string result = "";
foreach(var roman in RomanNumbers.OrderByDescending(x => x.Value))
{
while(value >= roman.Value)
{
value -= roman.Value;
result += roman.Key;
}
}
return result;
}
public int ConvertRoman(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException();
int result = 0;
for(int i =0; i < value.Length; i++)
{
result += RomanNumbers[value[i].ToString()];
}
return result;
}
}
}<file_sep>using _2019_07_07;
using System;
using Xunit;
namespace XUnitTest
{
public class WrapperTest
{
/*
if text is empty or null -> argument null exception
columns is major than words -> return the same text
columns is less than words -> return divided text
*/
[Theory]
[InlineData(null)]
[InlineData("")]
public void Text_IsNullOrEmpty_Throws_ArgumentNullException(string text)
{
//act
Action actual = () => Wrapper.Wrap(text, 0);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void Text_Words_Are_Less_Than_Columns_Returns_Same_Text()
{
//act
string actual = Wrapper.Wrap("This is a test", 5);
//assert
Assert.Equal("This is a test", actual);
}
[Fact]
public void Text_Words_Are_Major_Than_Columns_Returns_Text_Divided()
{
//act
string actual = Wrapper.Wrap("This is a test for xunit", 2);
//assert
Assert.Equal("This is\na test\nfor xunit", actual);
}
}
}
<file_sep>using _2019_06_08;
using System;
using System.Collections.Generic;
using Xunit;
namespace XUnitTest
{
public class BallsSorterTest
{
/*
add ->
is empty -> balls is empty
add one number -> balls has that number
secuential nums -> add it to the list
not secuential nums -> add it sorted to the list
*/
[Fact]
public void Never_call_add_Balls_willbe_Empty()
{
//arrage
BallsSorter ballsSorter = new BallsSorter();
//act
var actual = ballsSorter.balls;
List<int> emptyList = new List<int>();
//assert
Assert.Equal(emptyList, actual);
}
[Fact]
public void Add_One_Number_Balls_Wll_Has_That_Number()
{
//arrage
BallsSorter ballsSorter = new BallsSorter();
//act
ballsSorter.Add(1);
var actual = ballsSorter.balls;
//assert
Assert.Equal(new[] { 1 }, actual);
}
[Fact]
public void Add_Two_Secuential_Numbers_Balls_Will_Has_Those_Numbers()
{
//arrage
BallsSorter ballsSorter = new BallsSorter();
//act
ballsSorter.Add(1);
ballsSorter.Add(2);
var actual = ballsSorter.balls;
//assert
Assert.Equal(new[] { 1, 2 }, actual);
}
[Fact]
public void Add_Two_Not_Secuential_Numbers_Balls_Will_Has_Those_Numbers_Sorted()
{
//arrage
BallsSorter ballsSorter = new BallsSorter();
//act
ballsSorter.Add(2);
ballsSorter.Add(1);
var actual = ballsSorter.balls;
//assert
Assert.Equal(new[] { 1, 2 }, actual);
}
[Fact]
public void Add_Three_Not_Secuential_Numbers_Balls_Will_Has_Those_Numbers_Sorted()
{
//arrage
BallsSorter ballsSorter = new BallsSorter();
//act
ballsSorter.Add(20);
ballsSorter.Add(10);
ballsSorter.Add(30);
var actual = ballsSorter.balls;
//assert
Assert.Equal(new[] { 10, 20, 30 }, actual);
}
}
}
<file_sep>using _2019_06_23;
using System;
using Xunit;
namespace XUnitTest
{
public class RangeTest
{
/*
MainRange is null -> throw ArgumentNullException
MainRange has range -> rangelist is not null
Range is null -> throw ArgumentNullException
MainRange contains numslist -> returns true
MainRange not contains numslist -> returns false
MainRange contains range -> returns true
MainRange not contains range -> returns false
*/
[Fact]
public void MainRange_IsNull_Throws_ArgumentNullException()
{
//arrage
Range range;
//act
Action actual = () => range = new Range(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void MainRange_HasValue_RangeNumbers_HasValue()
{
//arrage
Range range = new Range("[0, 1]");
//act
int[] actual = range.RangeNumbers;
//assert
Assert.Equal(new int[] { 0, 1 } , actual);
}
[Fact]
public void Range_To_Compare_IsNull_Throws_ArgumentNullException()
{
//arrage
Range range = new Range("[0, 1]");
//act
Action actual = () => range.Contains(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void Mainrange_Contains_NumsList_Returns_True()
{
//arrage
Range range = new Range("[3, 8]");
//act
bool actual = range.Contains("{ 3, 4, 6 }");
//assert
Assert.True(actual);
}
[Fact]
public void Mainrange_Not_Contains_NumsList_Returns_False()
{
//arrage
Range range = new Range("[3, 8]");
//act
bool actual = range.Contains("{ 3, -1, 4, 6 }");
//assert
Assert.False(actual);
}
[Theory]
[InlineData("(2, 7]")]
[InlineData("[3, 9)")]
public void Mainrange_Contains_range_Returns_True(string numsRange)
{
//arrage
Range range = new Range("[3, 8]");
//act
bool actual = range.Contains(numsRange);
//assert
Assert.True(actual);
}
[Theory]
[InlineData("(1, 7]")]
[InlineData("[3, 10)")]
public void Mainrange_Not_Contains_range_Returns_False(string numsRange)
{
//arrage
Range range = new Range("[3, 8]");
//act
bool actual = range.Contains(numsRange);
//assert
Assert.False(actual);
}
}
}
<file_sep>using _2019_06_16;
using Moq;
using System;
using System.Collections.Generic;
using Xunit;
namespace XUnitTest
{
public class ArgsSchemaTest
{
/*
Interfaz IFlags
-> GetFlags(string)
Class argschema
-> Properties
-l bool
-p string
-g string list
-d int list
Iflags pass null throw exception
iflags return dictionary flags in string
*/
[Fact]
public void Text_IsNull_IFlags_Throw_ArgumentNullException()
{
//arrage
var flags = new Mock<IFlags>();
flags.Setup(x => x.GetFlags(null)).Throws<ArgumentNullException>();
ArgsSchema argsSchema = new ArgsSchema(flags.Object);
//act
Action actual = () => argsSchema.GetArgs(null);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Fact]
public void IFlags_Has_Loggin_Property_IsTrue()
{
//arrage
var values = new Dictionary<string, string>
{
{ "l", "" }
};
var flags = new Mock<IFlags>();
flags.Setup(x => x.GetFlags(It.IsAny<string>())).Returns(values);
ArgsSchema argsSchema = new ArgsSchema(flags.Object);
argsSchema.GetArgs("-l");
//act
bool actual = argsSchema.Loggin;
//assert
Assert.True(actual);
}
[Fact]
public void IFlags_Has_IntList_Property_HasValue()
{
//arrage
var values = new Dictionary<string, string>
{
{ "d", "1, 2, -3, 9" }
};
var flags = new Mock<IFlags>();
flags.Setup(x => x.GetFlags(It.IsAny<string>())).Returns(values);
ArgsSchema argsSchema = new ArgsSchema(flags.Object);
argsSchema.GetArgs("-d");
//act
List<int> actual = argsSchema.IntList;
//assert
Assert.Equal(new[] { 1, 2, -3, 9 }, actual);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _2019_06_02.Anagrams
{
public class AnagramsFinder
{
public List<AnagramGroup> Anagrams { get; set; } = new List<AnagramGroup>();
public bool Validate(string v1, string v2)
{
if (v1.Count() != v2.Count())
return false;
var temp1 = v1.ToLower().Select(x => x).OrderBy(x => x);
var temp2 = v2.ToLower().Select(x => x).OrderBy(x => x);
var v1Sorted = string.Join("", temp1);
var v2Sorted = string.Join("", temp2);
return v1Sorted == v2Sorted;
}
public void GroupAnagram(string v)
{
bool existGroup = false;
foreach(var item in Anagrams)
{
if (Validate(item.MainAnagram, v))
{
item.Group.Add(v);
existGroup = true;
}
}
if (!existGroup)
{
var newItem = new AnagramGroup
{
MainAnagram = v,
};
newItem.Group.Add(v);
Anagrams.Add(newItem);
}
}
}
public class AnagramGroup
{
public string MainAnagram { get; set; }
public List<string> Group { get; set; } = new List<string>();
}
}
<file_sep>using _2019_06_30;
using System;
using Xunit;
namespace XUnitTest
{
public class RomanConverterTest
{
/*
roman to decimal
null -> return argumentNullex..
1digitroman ->return decimal
complexroman -> return decimal
*/
[Fact]
public void Number_IsZero_Throws_ArgumentOutOfRangeException()
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
Action actual = () => romanConverter.ConvertNumber(0);
//assert
Assert.Throws<ArgumentOutOfRangeException>(actual);
}
[Theory]
[InlineData("I", 1)]
[InlineData("V", 5)]
[InlineData("X", 10)]
[InlineData("L", 50)]
[InlineData("C", 100)]
[InlineData("D", 500)]
[InlineData("M", 1000)]
public void OneDigit_Number_Returns_Roman(string expected, int value)
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
string actual = romanConverter.ConvertNumber(value);
//assert
Assert.Equal(expected, actual);
}
[Fact]
public void Complex_Number_Returns_Roman()
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
string actual = romanConverter.ConvertNumber(624);
//assert
Assert.Equal("DCXXIV", actual);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Roman_IsNullOrEmpty_Throws_ArgumentNullException(string value)
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
Action actual = () => romanConverter.ConvertRoman(value);
//assert
Assert.Throws<ArgumentNullException>(actual);
}
[Theory]
[InlineData( 1, "I")]
[InlineData( 5, "V")]
[InlineData( 10, "X")]
[InlineData( 50, "L")]
[InlineData( 100, "C")]
[InlineData( 500, "D")]
[InlineData( 1000, "M")]
public void Simple_Roman_Returns_OneDigit_Number(int expected, string value)
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
int actual = romanConverter.ConvertRoman(value);
//assert
Assert.Equal(expected, actual);
}
[Fact]
public void Complex_Roman_Returns_Number()
{
//arrage
RomanConverter romanConverter = new RomanConverter();
//act
int actual = romanConverter.ConvertRoman("DCXXIV");
//assert
Assert.Equal(624, actual);
}
}
}
<file_sep>using System;
namespace _2019_06_09
{
class Program
{
static void Main(string[] args)
{
var characterSorter = new CharacterSorter();
//Console.Write("Digite un texto: ");
var text = "When not studying nuclear physics, Bambi likes to play beach volleyball."; //Console.ReadLine();
var sorted = characterSorter.SortText(text);
Console.WriteLine(sorted);
Console.ReadKey();
}
}
}
| 6ba56626b15f3a02a2941f0852cfd5efa83124d7 | [
"C#"
] | 29 | C# | jordymateo/Katas | 1799e78d8150c63be1070a34cebf9ec6b566b316 | 882910ce950643ce79ec2156a1d525395ac57ac9 |
refs/heads/master | <repo_name>MPogoda/afc-coursework<file_sep>/convex_hull/CMakeLists.txt
project( convex_hull )
cmake_minimum_required( VERSION 2.8.6 )
if ( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" )
add_definitions( -std=c++11 )
elseif ( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" )
add_definitions( -std=c++0x )
endif()
set( CH_sources convex_hull.cxx )
add_library( convex_hull STATIC ${CH_sources})
<file_sep>/CMakeLists.txt
project( afc )
cmake_minimum_required( VERSION 2.8.6 )
set( CMAKE_AUTOMOC true )
set( CMAKE_CXX_FLAGS "-std=c++11" )
if( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" )
set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native")
endif()
find_package( Qt4 REQUIRED QtGui QtCore )
include( ${QT_USE_FILE} )
set( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" )
find_package( Qwt6 REQUIRED )
include_directories( ${Qwt6_INCLUDE_DIR} )
set( SRCS
main.cxx
main_widget.cxx
)
add_subdirectory( convex_hull )
add_executable( afc ${SRCS} )
add_dependencies( afc
convex_hull
)
target_link_libraries( afc convex_hull ${QT_LIBRARIES} ${Qwt6_LIBRARY} )
<file_sep>/cmake/FindQwt6.cmake
# Find the Qwt 6.x includes and library, either the version linked to Qt3 or the version linked to Qt4
#
# On Windows it makes these assumptions:
# - the Qwt DLL is where the other DLLs for Qt are (QT_DIR\bin) or in the path
# - the Qwt .h files are in QT_DIR\include\Qwt or in the path
# - the Qwt .lib is where the other LIBs for Qt are (QT_DIR\lib) or in the path
#
# Qwt6_INCLUDE_DIR - where to find qwt.h if Qwt
# Qwt6_LIBRARY - The Qwt6 library linked against Qt4 (if it exists)
# Qwt6_FOUND - Set to TRUE if Qwt6 was found (linked either to Qt3 or Qt4)
# Copyright (c) 2007, <NAME>, <<EMAIL>>
#
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
# Condition is "(A OR B) AND C", CMake does not support parentheses but it evaluates left to right
IF(Qwt6_LIBRARY AND Qwt6_INCLUDE_DIR)
SET(Qwt6_FIND_QUIETLY TRUE)
ENDIF(Qwt6_LIBRARY AND Qwt6_INCLUDE_DIR)
IF(NOT QT4_FOUND)
FIND_PACKAGE( Qt4 REQUIRED QUIET )
ENDIF(NOT QT4_FOUND)
IF( QT4_FOUND )
# Is Qwt6 installed? Look for header files
FIND_PATH( Qwt6_INCLUDE_DIR qwt.h
PATHS ${QT_INCLUDE_DIR} /usr/local/qwt6/include /usr/include/qwt6 ${QWT_DIR}/include ${QWT_DIR}/src
PATH_SUFFIXES qwt qwt6 qwt-qt4 qwt6-qt4 include qwt/include qwt6/include qwt-qt4/include qwt6-qt4/include ENV PATH)
# Find Qwt version
IF( Qwt6_INCLUDE_DIR )
FILE( READ ${Qwt6_INCLUDE_DIR}/qwt_global.h QWT_GLOBAL_H )
STRING( REGEX MATCH "#define *QWT_VERSION *(0x06*)" QWT_IS_VERSION_6 ${QWT_GLOBAL_H})
IF( QWT_IS_VERSION_6 )
STRING(REGEX REPLACE ".*#define[\\t\\ ]+QWT_VERSION_STR[\\t\\ ]+\"([0-9]+\\.[0-9]+\\.[0-9]+)\".*" "\\1" Qwt_VERSION "${QWT_GLOBAL_H}")
# Find Qwt6 library linked to Qt4
IF (UNIX)
# General purpose method
FIND_LIBRARY( Qwt6_Qt4_TENTATIVE_LIBRARY NAMES qwt6-qt4 qwt-qt4 qwt6 qwt PATHS /usr/local/qwt/lib /usr/local/lib /usr/lib )
IF( UNIX AND NOT CYGWIN AND NOT APPLE)
IF( Qwt6_Qt4_TENTATIVE_LIBRARY )
#MESSAGE("Qwt6_Qt4_TENTATIVE_LIBRARY = ${Qwt6_Qt4_TENTATIVE_LIBRARY}")
EXECUTE_PROCESS( COMMAND "ldd" ${Qwt6_Qt4_TENTATIVE_LIBRARY} OUTPUT_VARIABLE Qwt_Qt4_LIBRARIES_LINKED_TO )
STRING( REGEX MATCH "QtCore" Qwt6_IS_LINKED_TO_Qt4 ${Qwt_Qt4_LIBRARIES_LINKED_TO})
IF( Qwt6_IS_LINKED_TO_Qt4 )
SET( Qwt6_LIBRARY ${Qwt6_Qt4_TENTATIVE_LIBRARY} )
SET( Qwt6_FOUND TRUE )
IF (NOT Qwt6_FIND_QUIETLY)
MESSAGE( STATUS "Found Qwt: ${Qwt6_Qt4_LIBRARY}" )
ENDIF (NOT Qwt6_FIND_QUIETLY)
ENDIF( Qwt6_IS_LINKED_TO_Qt4 )
ENDIF( Qwt6_Qt4_TENTATIVE_LIBRARY )
ELSE( UNIX AND NOT CYGWIN AND NOT APPLE)
# Assumes qwt.dll is in the Qt dir
SET( Qwt6_LIBRARY ${Qwt6_Qt4_TENTATIVE_LIBRARY} )
SET( Qwt6_FOUND TRUE )
IF (NOT Qwt6_FIND_QUIETLY)
MESSAGE( STATUS "Found Qwt version ${Qwt_VERSION} linked to Qt4" )
ENDIF (NOT Qwt6_FIND_QUIETLY)
ENDIF( UNIX AND NOT CYGWIN AND NOT APPLE)
ELSE (UNIX)
IF (MSVC)
# Ad-hoc windows method for MSVC
# At this time assumes Qt4 version
FIND_LIBRARY(QWT6_LIBRARY_RELEASE
NAMES qwt.lib
PATHS ${QWT_DIR}/lib)
FIND_LIBRARY(QWT6_LIBRARY_DEBUG
NAMES qwtd.lib
PATHS ${QWT_DIR}/lib)
win32_tune_libs_names (QWT6)
SET (Qwt6_LIBRARY ${QWT6_LIBRARIES})
IF (QWT6_LIBRARIES)
SET( Qwt6_FOUND TRUE )
IF (NOT Qwt6_FIND_QUIETLY)
MESSAGE( STATUS "Found Qwt version ${Qwt_VERSION} linked to Qt4" )
ENDIF (NOT Qwt6_FIND_QUIETLY)
ENDIF (QWT6_LIBRARIES)
ELSE (MSVC)
FIND_LIBRARY(QWT6_LIBRARY
NAMES libqwt.a
PATHS ${QWT_DIR}/lib)
IF (QWT6_LIBRARIES)
SET( Qwt6_FOUND TRUE )
IF (NOT Qwt6_FIND_QUIETLY)
MESSAGE( STATUS "Found Qwt version ${Qwt_VERSION} linked to Qt4" )
ENDIF (NOT Qwt6_FIND_QUIETLY)
ENDIF (QWT6_LIBRARIES)
ENDIF (MSVC)
ENDIF (UNIX)
ENDIF( QWT_IS_VERSION_6 )
MARK_AS_ADVANCED( Qwt6_INCLUDE_DIR Qwt6_LIBRARY )
ENDIF( Qwt6_INCLUDE_DIR )
IF (NOT Qwt6_FOUND AND Qwt6_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "Could not find Qwt 6.x")
ENDIF (NOT Qwt6_FOUND AND Qwt6_FIND_REQUIRED)
ENDIF( QT4_FOUND )
<file_sep>/convex_hull/convex_hull.hxx
#pragma once
#include <vector>
#include <deque>
#include <QPointF>
namespace afc
{
class Convex_Hull
{
std::deque< QPointF > m_stack;
const double orient( const QPointF& p);
public:
std::deque< QPointF > compute(std::vector< QPointF > m_points);
};
}
<file_sep>/main_widget.cxx
#include "main_widget.hxx"
#include <QWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QStringListModel>
#include <QListView>
#include <QItemSelectionModel>
#include <QList>
#include <QPointF>
#include <QGroupBox>
#include <QDoubleSpinBox>
#include <QFileDialog>
#include "convex_hull/convex_hull.hxx"
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_marker.h>
#include <qwt_symbol.h>
using namespace afc;
using std::vector;
using std::deque;
void Main_Widget::setupUI()
{
QSizePolicy sizePolicyForLabels( QSizePolicy::Maximum, QSizePolicy::Preferred);
QLabel *xLabel = new QLabel( tr( "x:" ), this );
xLabel->setSizePolicy( sizePolicyForLabels );
xLabel->setBuddy( m_xSpin );
QLabel *yLabel = new QLabel( tr( "y:" ), this );
yLabel->setSizePolicy( sizePolicyForLabels );
yLabel->setBuddy( m_ySpin );
QHBoxLayout *spinsLayout = new QHBoxLayout;
spinsLayout->addWidget( xLabel );
spinsLayout->addWidget( m_xSpin );
spinsLayout->addWidget( yLabel );
spinsLayout->addWidget( m_ySpin );
QHBoxLayout *pointButtonsLayout = new QHBoxLayout;
pointButtonsLayout->addWidget( m_addPointButton );
pointButtonsLayout->addWidget( m_delPointButton );
QHBoxLayout *fileButtonsLayout = new QHBoxLayout;
fileButtonsLayout->addWidget( m_openFileButton );
fileButtonsLayout->addWidget( m_saveFileButton );
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addLayout( fileButtonsLayout );
leftLayout->addLayout( spinsLayout );
leftLayout->addLayout( pointButtonsLayout );
leftLayout->addWidget( m_inputView );
m_inputView->setModel(m_inputModel);
m_inputView->setEditTriggers( QAbstractItemView::NoEditTriggers);
QGroupBox *leftGroupBox = new QGroupBox( tr( "Input" ), this );
leftGroupBox->setLayout( leftLayout );
QLabel *lengthLabel = new QLabel( tr( "Optimal length:" ), this );
lengthLabel->setSizePolicy( sizePolicyForLabels );
lengthLabel->setBuddy( m_length );
m_length->setFrameStyle( QFrame::Panel );
QHBoxLayout *labelsLayout = new QHBoxLayout;
labelsLayout->addWidget( lengthLabel );
labelsLayout->addWidget( m_length );
QVBoxLayout *rightSubLayout = new QVBoxLayout;
m_outputView->setModel( m_outputModel );
m_outputView->setEditTriggers( QAbstractItemView::NoEditTriggers);
rightSubLayout->addLayout( labelsLayout );
rightSubLayout->addWidget( m_outputView );
rightSubLayout->addWidget( m_plot );
QGroupBox *rightGroupBox = new QGroupBox( tr( "Results" ), this );
rightGroupBox->setLayout( rightSubLayout );
QVBoxLayout *rightLayout = new QVBoxLayout;
rightLayout->addWidget( m_runButton );
rightLayout->addWidget( rightGroupBox );
QHBoxLayout *mainLayout = new QHBoxLayout( this );
mainLayout->addWidget( leftGroupBox );
mainLayout->addLayout( rightLayout );
}
Main_Widget::Main_Widget(QWidget *parent)
: QWidget(parent)
, m_xSpin( new QDoubleSpinBox( this ) )
, m_ySpin( new QDoubleSpinBox( this ) )
, m_length( new QLabel( "0", this) )
, m_addPointButton( new QPushButton( tr( "Add Point" ), this) )
, m_delPointButton( new QPushButton( tr( "Delete Point" ), this) )
, m_openFileButton( new QPushButton( tr( "Open File" ), this) )
, m_saveFileButton( new QPushButton( tr( "Save File"), this) )
, m_runButton( new QPushButton( tr( "Run" ), this) )
, m_inputModel( new QStringListModel( this ) )
, m_outputModel( new QStringListModel( this ) )
, m_inputSelectionModel( new QItemSelectionModel( m_inputModel, this ))
, m_inputView( new QListView( this ) )
, m_outputView( new QListView( this ) )
, m_plot( new QwtPlot( tr( "Illustration" ), this) )
, m_curve( new QwtPlotCurve( tr( "Solution" ) ) )
{
setupUI();
m_inputView->setSelectionModel( m_inputSelectionModel );
m_plot->setAutoReplot();
m_plot->setAxisAutoScale( 0 );
m_plot->setAxisAutoScale( 1 );
m_plot->setAxisScale( QwtPlot::xBottom, -5, 20 );
m_plot->setAxisScale( QwtPlot::yLeft, -5, 20 );
m_curve->attach( m_plot );
connect( m_addPointButton, SIGNAL(clicked()), this, SLOT(addPoint()) );
connect( m_delPointButton, SIGNAL(clicked()), this, SLOT(delPoint()) );
connect( m_runButton, SIGNAL(clicked()), this, SLOT(run()) );
connect( m_openFileButton, SIGNAL(clicked()), this, SLOT(openFile()) );
connect( m_saveFileButton, SIGNAL(clicked()), this, SLOT(saveFile()) );
}
Main_Widget::~Main_Widget()
{
qDeleteAll( m_markers );
delete m_curve;
}
void Main_Widget::generateConvexHullModel( const std::deque<QPointF>& convexHull )
{
QStringList output;
QVector< QPointF > samples;
samples.reserve( convexHull.size() );
auto prev( convexHull.back() );
auto length( 0.0 );
for (const auto& point : convexHull)
{
output << QString( "( %0; %1 )" ).arg( point.x(), 0, 'g', 2).arg( point.y(), 0, 'g', 2);
samples << point;
const auto dx = point.x() - prev.x();
const auto dy = point.y() - prev.y();
length += sqrt( dx * dx + dy * dy );
prev = point;
}
m_outputModel->setStringList( output );
samples.push_back( samples.front() );
m_curve->setSamples( samples );
m_length->setText( QString::number( length, 'g', 2));
}
void Main_Widget::clearOutput()
{
m_curve->setSamples( QVector< QPointF>() );
m_outputModel->setStringList( QStringList() );
m_length->setText( "0" );
}
void Main_Widget::run()
{
if ( 3 > m_points.size() )
return;
Convex_Hull ch;
const auto& convexHull = ch.compute( m_points.toVector().toStdVector() );
generateConvexHullModel( convexHull );
}
void Main_Widget::addPoint(const QPointF &point)
{
m_points.push_back( point );
m_markers.push_back( new QwtPlotMarker );
QwtPlotMarker *marker = m_markers.back();
marker->setSymbol( new QwtSymbol( QwtSymbol::Diamond, Qt::red, Qt::NoPen, QSize(10, 10) ) );
marker->setValue( point );
marker->attach( m_plot );
m_inputModel->insertRow( m_inputModel->rowCount() );
QModelIndex index = m_inputModel->index( m_inputModel->rowCount() - 1);
m_inputModel->setData(index, QString( "( %0; %1 )" )
.arg( point.x(), 0, 'g', 2)
.arg( point.y(), 0, 'g', 2)
);
}
void Main_Widget::addPoint()
{
const QPointF pointToAdd( m_xSpin->value(), m_ySpin->value( ) );
if (m_points.contains( pointToAdd ))
return; // do nothing
clearOutput();
addPoint( pointToAdd );
}
void Main_Widget::delPoint()
{
const int row = m_inputSelectionModel->currentIndex().row();
if (-1 == row)
return;
const auto x = m_points.at( row ).x();
const auto y = m_points.at( row ).y();
m_points.removeAt( row );
// m_markers.at( row )->detach();
delete m_markers.at( row );
m_markers.removeAt( row );
m_inputModel->removeRow( row );
clearOutput();
m_plot->replot();
m_xSpin->setValue( x );
m_ySpin->setValue( y );
}
#include <QFile>
#include <QDataStream>
void Main_Widget::openFile()
{
const QString fileName = QFileDialog::getOpenFileName( this, tr("Open File"));
if (fileName.isNull())
return;
QFile file( fileName );
if (!file.open( QIODevice::ReadOnly ) )
{
//throw
return;
}
QDataStream in( &file );
in.setVersion( QDataStream::Qt_4_8 );
QVector< QPointF > points;
in >> points;
file.close();
for (auto marker : m_markers)
delete marker;
m_markers.clear();
m_inputModel->removeRows(0, m_points.size() );
clearOutput();
m_points.clear();
m_points.reserve( points.size() );
for (const auto& point : points )
{
addPoint( point );
}
}
void Main_Widget::saveFile()
{
const QString fileName = QFileDialog::getSaveFileName( this, tr("Save File") );
if (fileName.isNull())
return;
QFile file( fileName );
if (!file.open( QIODevice::WriteOnly ))
{
//throw error;
return;
}
QDataStream out( &file );
out.setVersion( QDataStream::Qt_4_8 );
out << m_points;
file.close();
}
<file_sep>/main_widget.hxx
#pragma once
#include <QList>
#include <QWidget>
#include <vector>
#include <deque>
class QDoubleSpinBox;
class QLabel;
class QPushButton;
class QStringListModel;
class QItemSelectionModel;
class QListView;
class QwtPlot;
class QwtPlotCurve;
class QwtPlotMarker;
class QPointF;
class Main_Widget : public QWidget
{
Q_OBJECT
public:
Main_Widget(QWidget *parent = nullptr);
~Main_Widget();
private:
QDoubleSpinBox *m_xSpin;
QDoubleSpinBox *m_ySpin;
QLabel *m_length;
QPushButton *m_addPointButton;
QPushButton *m_delPointButton;
QPushButton *m_openFileButton;
QPushButton *m_saveFileButton;
QPushButton *m_runButton;
QStringListModel *m_inputModel;
QStringListModel *m_outputModel;
QItemSelectionModel *m_inputSelectionModel;
QListView *m_inputView;
QListView *m_outputView;
QwtPlot *m_plot;
QwtPlotCurve *m_curve;
QList< QPointF > m_points;
QList< QwtPlotMarker* > m_markers;
void generateConvexHullModel( const std::deque< QPointF >& convexHull );
void setupUI();
void clearOutput();
void addPoint( const QPointF& point );
private slots:
void addPoint();
void delPoint();
void run();
void openFile();
void saveFile();
};
<file_sep>/convex_hull/convex_hull.cxx
#include "convex_hull.hxx"
#include <algorithm>
using namespace afc;
using std::vector;
using std::deque;
using std::sort;
using std::sqrt;
using std::swap;
using std::min_element;
namespace {
const bool bottomComparator(const QPointF& a, const QPointF& b)
{
const bool result = (a.y() < b.y()) ? true :
((a.y() == b.y()) && (a.x() < b.x()) ? true : false);
return result;
}
const
double ccw( const QPointF& pt1, const QPointF& pt2, const QPointF& pt3)
{
return (pt2.x() - pt1.x()) * (pt3.y() - pt1.y())
- (pt2.y() - pt1.y()) * (pt3.x() - pt1.x());
}
class AngleComparator
{
QPointF m_central;
public:
AngleComparator( const QPointF& c );
const bool operator()( const QPointF& a, const QPointF& b) const;
const double angle( const QPointF& x) const;
};
AngleComparator::AngleComparator( const QPointF& central)
: m_central(central) { }
const bool AngleComparator::operator()( const QPointF& a, const QPointF& b) const
{
return angle(a) < angle(b);
}
inline const double AngleComparator::angle( const QPointF& other) const
{
const QPointF t( other.x() - m_central.x(), other.y() - m_central.y() );
// TODO : check whether std::acos is needed.
return t.x() / sqrt(t.x() * t.x() + t.y() * t.y() );
}
}
const double Convex_Hull::orient(const QPointF& p3)
{
const auto p1 = m_stack.back();
m_stack.pop_back();
const auto result = ccw(p1, m_stack.back(), p3);
m_stack.push_back(p1);
return result;
}
std::deque<QPointF> Convex_Hull::compute(std::vector<QPointF> points)
{
auto min = min_element(points.begin(), points.end(), bottomComparator);
swap(*min, *points.begin());
sort(points.begin() + 1, points.end(), AngleComparator(points[0]));
auto it = points.begin();
for (std::size_t i( 0 ); i != 3; ++i, ++it)
m_stack.push_back(*it);
while (points.end() != it)
{
const auto& point = *it;
while (orient(point) < 1e-9)
m_stack.pop_back();
m_stack.push_back(point);
++it;
}
return m_stack;
}
| 7b4506aa581bf7ca5c7baf40644084eabf40567f | [
"CMake",
"C++"
] | 7 | CMake | MPogoda/afc-coursework | c613464b43119e498b0344cdc59f403bbd10da37 | 411bc01041381fb774a95a479355c2410b96c47e |
refs/heads/master | <file_sep>.. image:: https://readthedocs.org/projects/pyloraserver/badge/?version=latest
:target: https://pyloraserver.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
PyLoRaServer
============
The LoRaServer.io Python Library
This python library makes interaction with the loraserver.io project that bit easier.
For full documentation, including examples, please see our pages on `Read The Docs`__
.. _RTD: https://pyloraserver.readthedocs.io/en/latest/
__ RTD_
<file_sep>import pytest
from pyloraserver import applications
class TestApplication:
@pytest.fixture
def lora_connection(self, requests_mock):
# Mock the Authentication Handler
requests_mock.get(
"https://loraserver/api/applications",
json={
"result": [
{
"description": "A test application from the test fixture", # noqa: E501
"id": "1",
"name": "TEST_APPLICATION",
"organizationID": "1",
"serviceProfileID": "54767cb5-beef-494e-dead-8821ddd69bcb", # noqa: E501
"serviceProfileName": "testServiceProfile"
}
],
"totalCount": "string"
}
)
requests_mock.post(
"https://loraserver/api/internal/login",
json={
"jwt": "<KEY>" # noqa: E501
}
)
from pyloraserver import loraserver
return loraserver.Loraserver(
loraserver_url="https://loraserver",
loraserver_user="test_user",
loraserver_pass="<PASSWORD>"
)
def test_device_profile_list(self,
lora_connection
):
a = applications.Application(
loraserver_connection=lora_connection)
alist = a.list()
assert alist['result'][0]['name'] == "TEST_APPLICATION"
<file_sep>import setuptools
with open("README.rst", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyloraserver",
version="0.1.6",
author="Mockingbird Consulting Ltd",
author_email="<EMAIL>",
description="A python library for interacting with Loraserver.io.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/mockingbirdconsulting/pyloraserver",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=[
"requests>=2.21.0"
]
)
<file_sep>Welcome to PyLoRaServer's documentation!
========================================
PyLoRaServer is a python library for interacting with the loraserver.io project.
Contents
========
.. toctree::
:maxdepth: 2
:caption: Contents:
examples.rst
.. include: contents.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>import logging
import requests
logger = logging.getLogger('pyloraserver.loraserver')
class Loraserver:
"""
Connect to the LoRaServer.io API and return an object that
can be used for querying the same
Args:
loraserver_url (str): The full URL to the LoRaServer
*excluding* the `/api` at the end (i.e.
https://my.loraserver.com/,
not https://my.loraserver.com/api)
loraserver_user (str): The user name to allow us to
authenticate and retrieve the JSON Web Token
required to communicate with the API
loraserver_pass (str): The user name to allow us to
authenticate and retrieve the JSON Web Token
required to communicate with the API
Returns:
Loraserver: A loraserver object
"""
def __init__(self,
loraserver_url=None,
loraserver_user=None,
loraserver_pass=None
):
self.loraserver_url = loraserver_url
self.loraserver_user = loraserver_user
self.loraserver_pass = l<PASSWORD>ver_pass
self.connect()
def _authenticate(self):
"""
Authenticate against the LoRaServer.io API
and return a JWT for use elsewhere
"""
auth_url = "%s/api/internal/login" % self.loraserver_url
payload = {
"username": self.loraserver_user,
"password": self.<PASSWORD>
}
auth_request = requests.post(
auth_url,
json=payload
)
auth_tok = auth_request.json()
jwt = auth_tok['jwt']
logger.debug("JWT Token: %s" % jwt)
auth_header = {"Grpc-Metadata-Authorization": jwt}
return auth_header
def connect(self):
""" Connect to the loraserver and setup a new
sesssion
Returns:
Loraserver.connection: A requests session object
for use against the API
"""
auth_header = self._authenticate()
lsconnect = requests.Session()
lsconnect.headers = auth_header
self.connection = lsconnect
<file_sep>import pytest
from pyloraserver import deviceProfiles
class TestDeviceProfile:
@pytest.fixture
def lora_connection(self, requests_mock):
# Mock the Authentication Handler
requests_mock.get(
"https://loraserver/api/device-profiles",
json={
"result": [
{
"createdAt": "2019-04-18T14:44:03.093Z",
"id": "54767cb5-beef-494e-dead-8821ddd69bcb",
"name": "TEST_DEV_PROFILE",
"networkServerID": "1",
"organizationID": "1",
"updatedAt": "2019-04-18T14:44:03.094Z"
}
],
"totalCount": "1"
}
)
requests_mock.post(
"https://loraserver/api/internal/login",
json={
"jwt": "<KEY>" # noqa: E501
}
)
from pyloraserver import loraserver
return loraserver.Loraserver(
loraserver_url="https://loraserver",
loraserver_user="test_user",
loraserver_pass="<PASSWORD>"
)
def test_device_profile_list(self,
lora_connection
):
dp = deviceProfiles.DeviceProfiles(
loraserver_connection=lora_connection)
dplist = dp.list()
assert dplist['result'][0]['name'] == "TEST_DEV_PROFILE"
<file_sep>import pytest
from pyloraserver import device
class TestLoRaServerConnection:
@pytest.fixture
def lora_connection(self, requests_mock):
# Mock the Authentication Handler
requests_mock.post(
"https://loraserver/api/internal/login",
json={
"jwt": "<KEY>" # noqa: E501
}
)
# Mock the device list
requests_mock.get(
"https://loraserver/api/devices?limit=10&applicationID=1",
json={
"totalCount": "1",
"result": [
{
"devEUI": "bebebebebebebebe",
"name": "asdf",
"applicationID": "7",
"description": "asdf",
"deviceProfileID": "54767cb5-ba1b-494e-beef-8821ddd69bcb", # noqa: E501
"deviceProfileName": "ODN_EU_02",
"deviceStatusBattery": 255,
"deviceStatusMargin": 256,
"deviceStatusExternalPowerSource": False,
"deviceStatusBatteryLevelUnavailable": True,
"deviceStatusBatteryLevel": 0,
"lastSeenAt": "2019-04-17T06:12:31.904650Z"
}
]
}
)
from pyloraserver import loraserver
return loraserver.Loraserver(
loraserver_url="https://loraserver",
loraserver_user="test_user",
loraserver_pass="<PASSWORD>"
)
def test_connection_setup(self, lora_connection):
lora_connection.connection.get(
'https://loraserver/api/devices?limit=10&applicationID=1'
)
def test_connection_setup_with_device_list(self, lora_connection):
devices = device.Devices(loraserver_connection=lora_connection)
devices.list_all(limit=10, appid=1)
<file_sep>__name__ = "pyloraserver"
<file_sep>class Application:
""" A class to represent Applications within LoRaServer.io
Args:
name (str): The name of the application.
description (str): A description of the application.
loraserver_connection (loraserver_connection):
A loraserver_connection object
Returns:
Loraserver: A loraserver_connection object
"""
def __init__(self,
name=None,
description=None,
loraserver_connection=None
):
self.lscx = loraserver_connection
def list(self,
limit=10,
offset=0,
search_term=None,
orgid=None):
"""
Get a list of all of the applications
Args:
limit (int): The number of results to return (must be more than 0)
offset (int): The results offset for pagination purposes
search_term (str): Text to search for in the application name
orgid (int): The organisation to restrict the search to
Returns:
dict: A dict of the search results
"""
url = "%s/api/applications?limit=%s&offset=%s" % (
self.lscx.loraserver_url,
limit,
offset)
if search_term is not None:
url = "%s&search=%s" % (url, search_term)
if orgid is not None:
url = "%s&organizationID=%s" % (url, orgid)
ret_list = self.lscx.connection.get(url)
return ret_list.json()
<file_sep>class DeviceProfiles:
"""
A class representing Device Profiles within LoRaServer.io
Args:
name (str): The name of the device profile.
description (str): A description of the device profile.
loraserver_connection (loraserver_connection):
A loraserver_connection object
Returns:
DeviceProfiles: A device profile object
"""
def __init__(self,
name=None,
description=None,
loraserver_connection=None
):
self.lscx = loraserver_connection
def list(self,
limit=10,
offset=0,
appid=None,
orgid=None):
"""
Get a list of all of the device profiles
Args:
limit (int): The number of results to return (must be more than 0)
offset (int): The results offset for pagination purposes
search_term (str): Text to search for in the device profile name
appid (int): The application to restrict the search to
orgid (int): The organisation to restrict the search to
Returns:
dict: A dict of the search results
"""
url = "%s/api/device-profiles?limit=%s&offset=%s" % (
self.lscx.loraserver_url,
limit,
offset)
if appid is not None:
url = "%s&applicationID=%s" % (url, appid)
if orgid is not None:
url = "%s&organizationID=%s" % (url, orgid)
ret_list = self.lscx.connection.get(url)
return ret_list.json()
| e6b7f1c79b0ddd59b116eb1dcd696011cf91a636 | [
"Python",
"reStructuredText"
] | 10 | reStructuredText | dtony/pychirp | c942b84cf834e0cec3e7f60b3c7b781581478a7b | e4cd86b2477cab0b7c54fe304023e284ec1ccefb |
refs/heads/master | <repo_name>cudworth/top-testing-basics<file_sep>/caesarCipher.test.js
const caesarCipher = require('./caesarCipher');
test('basic caesar shift', () => {
expect(caesarCipher(1, 'a')).toBe('b');
});
test('wrap test', () => {
expect(caesarCipher(1, 'z')).toBe('a');
});
test('cap test', () => {
expect(caesarCipher(1, 'A')).toBe('B');
});
test('punctuation test', () => {
expect(caesarCipher(1, 'a.a')).toBe('b.b');
});
test('negative test', () => {
expect(caesarCipher(-28, 'b')).toBe('z');
});
<file_sep>/reverseString.test.js
const reverseString = require('./reverseString');
test('No test', () => {
expect(reverseString('abcdefghijklmnopqrstuvwxyz')).toBe(
'zyxwvutsrqponmlkjihgfedcba'
);
});
<file_sep>/caesarCipher.js
function caesarCipher(offset, str) {
const alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');
const arr = [];
str.split('').forEach((char) => {
const i = alpha.indexOf(char.toLowerCase());
if (-1 != i) {
const j = 0 < i + offset ? (i + offset) % 26 : 26 + ((i + offset) % 26);
arr.push(isUpper(char) ? alpha[j].toUpperCase() : alpha[j]);
} else {
arr.push(char);
}
});
return arr.join('');
}
function isUpper(char) {
return char === char.toUpperCase();
}
module.exports = caesarCipher;
| 7f755ed5f5281c8780bc0b8b456e547ede9f536b | [
"JavaScript"
] | 3 | JavaScript | cudworth/top-testing-basics | 8f5346ea6fff71a5b3acfad17369439d05dc7eb1 | 48180ffb4ff083093b2cf1ea40d72c398effa793 |
refs/heads/master | <repo_name>moroale93/personal-site<file_sep>/packages/app/src/containers/ScrollingTitle/index.js
import React, { createRef, useEffect } from 'react';
import gsap from 'gsap';
// eslint-disable-next-line react/prop-types
export default function ScrollingTitle({ children, className }) {
const titleRef = createRef();
useEffect(() => {
gsap.to(titleRef.current, {
xPercent: -50,
scrollTrigger: {
trigger: titleRef.current,
toggleActions: 'play reverse play reverse',
start: 'bottom bottom',
end: 'top top',
scrub: true,
},
});
}, [titleRef]);
return (
<h2 ref={titleRef} className={className}>
{children}
</h2>
);
}
<file_sep>/packages/app/src/containers/Collaboration/index.js
import React, { createRef, useEffect } from 'react';
import gsap from 'gsap';
import ScrollingTitle from '../ScrollingTitle';
import Paragraph from '../Paragraph';
import { useLanguage } from '../../contexts/languageProvider';
export default function Collaboration() {
const textRef = createRef();
const [{ translations }] = useLanguage();
useEffect(() => {
gsap.from(textRef.current, {
opacity: 0.8,
scaleX: 0.9,
scaleY: 0.9,
duration: 1.2,
scrollTrigger: {
trigger: textRef.current,
toggleActions: 'play reverse play reverse',
start: 'bottom bottom',
end: 'top top',
},
});
}, [textRef]);
return (
<section>
<ScrollingTitle>
{translations.needHelp}
</ScrollingTitle>
<Paragraph>
{translations.q1}
<br />
{translations.q2}
<br />
{translations.q3}
<br />
{translations.contact}
</Paragraph>
<h2 className="text-center small">
<a href="mailto:<EMAIL>"><EMAIL></a>
</h2>
</section>
);
}
<file_sep>/packages/app/src/containers/CareerItem/index.js
/* eslint-disable react/prop-types */
import gsap from 'gsap';
import React, { createRef, useEffect } from 'react';
import Divider from '../Divider';
import './index.scss';
export default function Career({
index,
title,
link,
role,
location,
image,
}) {
const titleRef = createRef();
const indexRef = createRef();
const locationRef = createRef();
useEffect(() => {
gsap.from(titleRef.current, {
yPercent: -30,
opacity: 0,
duration: 1.5,
scrollTrigger: {
trigger: titleRef.current.parentElement,
toggleActions: 'play reverse play reverse',
start: 'center bottom',
},
});
gsap.from(indexRef.current, {
yPercent: -100,
opacity: 0,
duration: 1.5,
scrollTrigger: {
trigger: indexRef.current.parentElement,
toggleActions: 'play reverse play reverse',
start: 'center bottom',
},
});
gsap.from(locationRef.current, {
yPercent: -100,
opacity: 0,
duration: 1.5,
scrollTrigger: {
trigger: locationRef.current.parentElement,
toggleActions: 'play reverse play reverse',
start: 'center bottom',
},
});
}, [titleRef, indexRef, locationRef]);
return (
<>
<Divider />
<div className="career-item">
<h3 ref={titleRef}><a className="reverse" href={link} alt={`${title} website`}>{title}</a></h3>
<br />
<p ref={locationRef}>{`${role} - ${location}`}</p>
<span ref={indexRef} className="index">{`0${index}`}</span>
<img src={image} alt={`${title} logo`} />
</div>
</>
);
}
<file_sep>/packages/app/src/containers/Menu/index.js
import React from 'react';
import { useLanguage, LANGUAGES } from '../../contexts/languageProvider';
import './index.scss';
export default function Menu() {
const [{
language,
}, setLanguage] = useLanguage();
return (
<nav>
<ul>
<li className="brand">
<span>Alessandro</span>
<span>Moretto</span>
</li>
{Object.values(LANGUAGES).map(lang => (
<li key={lang}>
<button
type="button"
onClick={() => setLanguage(lang)}
className={lang === language ? 'active' : ''}
>
{lang}
</button>
</li>
))}
</ul>
</nav>
);
}
<file_sep>/packages/app/src/containers/Paragraph/index.js
import React, { createRef, useEffect } from 'react';
import gsap from 'gsap';
// eslint-disable-next-line react/prop-types
export default function Paragraph({ children }) {
const textRef = createRef();
useEffect(() => {
gsap.from(textRef.current, {
opacity: 0.8,
scaleX: 0.9,
scaleY: 0.9,
duration: 1.2,
scrollTrigger: {
trigger: textRef.current,
toggleActions: 'play reverse play reverse',
start: 'bottom bottom',
end: 'top top',
},
});
}, [textRef]);
return (
<p className="center-section text-center" ref={textRef}>
{children}
</p>
);
}
<file_sep>/packages/app/src/containers/App/index.js
import React from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import Job from '../Job';
import Menu from '../Menu';
import Me from '../Me';
import Career from '../Career';
import Collaboration from '../Collaboration';
import LanguageProvider from '../../contexts/languageProvider';
if (typeof window !== 'undefined') {
gsap.registerPlugin(ScrollTrigger);
gsap.core.globals('ScrollTrigger', ScrollTrigger);
}
export default function App() {
return (
<LanguageProvider>
<Menu />
<Job />
<Me />
<Career />
<Collaboration />
</LanguageProvider>
);
}
<file_sep>/webpack/rules/compiling.js
const path = require('path');
module.exports = function getCompilingConfig(__packageDirname) {
return {
test: /\.(jsx|js|ts|tsx)$/,
include: [
path.resolve(__packageDirname, '../src'),
/\/packages\//,
],
use: [
{
loader: 'babel-loader',
options: {
rootMode: 'upward',
},
},
],
};
};
<file_sep>/README.md
# personal-site
This is my personal web site
<file_sep>/packages/app/src/contexts/languageProvider.js
import React, { createContext, useContext, useState } from 'react';
export const LANGUAGES = {
ITALIAN: 'IT',
ENGLISH: 'EN',
};
const translations = {
[LANGUAGES.ENGLISH]: {
iAm: 'I am <NAME>, a Software Engineer based in Italy.',
workFor: 'I work remotly for',
passions: 'I have a fondness for building web applications, client-server architectures and modern technologies.',
carrer: 'Career • What I\'ve done?',
university: 'University of Padua',
padua: 'Padua (Italy)',
amsterdam: 'Amsterdam (Netherland)',
remote: 'Remote from Italy',
student: 'Student',
mobileDeveloper: 'Mobile Developer',
needHelp: 'Need help? • I\'m here!',
q1: 'Do you want to know more about software engineering?',
q2: 'Do you have an idea to develop?',
q3: 'Do you need an help on your project?',
contact: 'Feel free to contact me!',
},
[LANGUAGES.ITALIAN]: {
iAm: 'Sono <NAME>, un Software Engineer con sede in Italy.',
workFor: 'Lavoro in remoto per',
passions: 'Mi piace costruire applicazioni web con architetture client-server utilizzando tecnologie moderne.',
carrer: 'Cariera • Cosa ho fatto?',
university: 'Università di Padova',
padua: 'Padova (Italia)',
amsterdam: 'Amsterdam (Olanda)',
remote: 'Remoto dall\'Italia',
student: 'Studente',
mobileDeveloper: 'Sviluppatore Software',
needHelp: 'Serve aiuto? • Sono qui!',
q1: 'Vuoi saperne di piu sull\ingegneria del software?',
q2: 'Hai un\'idea da sviluppare?',
q3: 'Ti serve un aiuto su un progetto?',
contact: 'Contattami!',
},
};
const LanguageContext = createContext([{
lang: LANGUAGES.ITALIAN,
translations: translations[LANGUAGES.ITALIAN],
}, () => {}]);
export function useLanguage() {
const context = useContext(LanguageContext);
return context;
}
// eslint-disable-next-line react/prop-types
export default function LanguageProvider({ children }) {
const [language, setLanguage] = useState(LANGUAGES.ITALIAN);
return (
<LanguageContext.Provider value={[{
lang: language,
translations: translations[language],
}, setLanguage]}
>
{children}
</LanguageContext.Provider>
);
}
<file_sep>/packages/app/test/transformers/gql.js
/* istanbul ignore file */
const gql = require('graphql-tag');
module.exports = {
process: src => (
`module.exports=${JSON.stringify(gql(src))};module.exports.default=module.exports;`
),
};
<file_sep>/webpack/base.config.js
const path = require('path');
const getRules = require('./rules');
const applyPlugins = require('./utils/applyPlugins');
const getPlugins = require('./plugins');
module.exports = function getBaseConfig(__packageDirname, isApp) {
let output = {
path: path.resolve(__packageDirname, './dist'),
publicPath: '/',
filename: 'assets/[name].[contenthash:8].js',
};
if (!isApp) {
output = {
path: path.resolve(__packageDirname, './dist'),
filename: './index.js',
};
}
return {
stats: {
children: false,
entrypoints: false,
modules: false,
},
devtool: 'source-map',
node: {
Buffer: true,
fs: 'empty',
tls: 'empty',
},
output,
entry: path.resolve(__packageDirname, './src/index.js'),
module: {
rules: Object.values(getRules(__packageDirname)),
},
resolve: {
extensions: [
'.js',
'.json',
'.ts',
'.tsx',
],
modules: [
'node_modules',
'src',
],
},
plugins: applyPlugins(getPlugins(__packageDirname, isApp)),
};
};
<file_sep>/packages/app/src/containers/Divider/index.js
/* eslint-disable react/prop-types */
import gsap from 'gsap';
import React, { createRef, useEffect } from 'react';
import './index.scss';
export default function Divider() {
const lineRef = createRef();
useEffect(() => {
gsap.to(lineRef.current, {
width: '100%',
duration: 1.5,
scrollTrigger: {
trigger: lineRef.current.parentElement,
toggleActions: 'play reverse play reverse',
start: 'center bottom',
},
});
}, [lineRef]);
return (
<div ref={lineRef} className="horizontal-line" />
);
}
<file_sep>/babel.config.js
module.exports = function babelExports(api) {
const isTest = api.env().toLowerCase() === 'test';
const presetEnvConf = {
corejs: 3,
useBuiltIns: 'entry',
};
const presets = [['@babel/preset-env', presetEnvConf], '@babel/preset-react', '@babel/preset-typescript'];
const plugins = [
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-transform-react-jsx',
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-export-default-from',
];
const testPresets = [
[
'@babel/preset-env',
{
...presetEnvConf,
...{
targets: {
node: 'current',
},
},
},
],
'@babel/preset-react',
];
if (isTest) {
return {
presets: testPresets,
plugins,
};
}
return {
presets,
plugins,
};
};
<file_sep>/packages/app/docker-compose.yml
version: '3.7'
services:
app:
image: nginx:1-alpine
volumes:
- ./config/nginx:/etc/nginx/conf.d
- ./dist:/opt/project
ports:
- "80:80"
networks:
- network
networks:
network:<file_sep>/webpack/plugins/HashedModuleIdsPlugin.js
const { HashedModuleIdsPlugin } = require('webpack');
module.exports = {
plugin: HashedModuleIdsPlugin,
};
<file_sep>/webpack/rules/index.js
const getCompilingConfig = require('./compiling');
const styling = require('./styling');
const fonts = require('./fonts');
const images = require('./images');
module.exports = function getRules(__packageDirname) {
return {
compiling: getCompilingConfig(__packageDirname),
styling,
fonts,
images,
};
};
<file_sep>/webpack/rules/styling.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
module.exports = {
test: /\.(css|scss)$/,
exclude: [
{
test: /node_modules/,
exclude: /@usabilla\//,
},
],
loaders: [
'style-loader',
{
loader: 'css-loader',
options: { sourceMap: true },
},
{
loader: 'postcss-loader',
options: {
plugins: [
autoprefixer(), // Uses the .browserslistrc automatically
cssnano(),
],
},
},
'sass-loader',
],
oneOf: [
{
test: /\.module\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules: true,
},
},
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
importLoaders: 0,
},
},
],
},
],
};
<file_sep>/webpack/index.js
const getBaseConfig = require('./base.config');
module.exports = function getConfiguration(isApp, isProd, __packageDirname) {
const baseConfig = getBaseConfig(__packageDirname, isApp);
if (isApp) {
baseConfig.target = 'web';
}
return {
...baseConfig,
mode: process.env.NODE_ENV,
devServer: (isProd || !isApp) ? undefined : {
clientLogLevel: 'error',
compress: true,
historyApiFallback: true,
port: 8888,
open: true,
},
};
};
<file_sep>/packages/app/package.json
{
"name": "@amoretto/app",
"version": "1.0.0",
"main": "src/index.js",
"license": "MIT",
"private": true,
"publishConfig": {
"access": "restricted"
},
"scripts": {
"build": "webpack --config ./webpack.config.js --display errors-only",
"start": "webpack-dev-server --config ./webpack.config.js"
},
"dependencies": {
"gsap": "3.6.0",
"react": "^16.13.1",
"react-dom": "^16.13.1"
}
}
<file_sep>/packages/app/webpack.config.js
require('dotenv').config();
const isProduction = process.env.NODE_ENV === 'production';
module.exports = require('../../webpack/index')(true, isProduction, __dirname);
<file_sep>/webpack/utils/applyPlugins.js
module.exports = function applyPlugins(pluginsConfiguration) {
const configurations = Object.values(pluginsConfiguration);
return configurations.map(({ plugin: Constructor, options }) => new Constructor(options));
};
<file_sep>/webpack/plugins/Dotenv.js
const Dotenv = require('dotenv-webpack');
const path = require('path');
module.exports = function getDotenvConfig(__packageDirname) {
return {
plugin: Dotenv,
options: {
path: path.resolve(__packageDirname, './.env'),
},
};
};
<file_sep>/packages/app/src/containers/Career/index.js
import React from 'react';
import ScrollingTitle from '../ScrollingTitle';
import CareerItem from '../CareerItem';
import unipd from '../../images/unipd.png';
import entelligo from '../../images/entelligo.png';
import wintech from '../../images/wintech.png';
import usabilla from '../../images/usabilla.png';
import { useLanguage } from '../../contexts/languageProvider';
import './index.scss';
import Divider from '../Divider';
const JOBS = translations => [{
index: 1,
title: translations.university,
from: new Date(2012, 10, 1),
link: 'https://www.unipd.it/',
role: translations.student,
location: translations.padua,
image: unipd,
}, {
index: 2,
title: 'Entelligo',
from: new Date(2015, 7, 1),
link: 'https://www.rockstart.com/startups/entelligo-2/',
role: translations.mobileDeveloper,
location: translations.amsterdam,
image: entelligo,
}, {
index: 3,
title: 'Wintech',
from: new Date(2016, 1, 1),
link: 'https://www.wintech.it/',
role: 'Software Engineer',
location: translations.padua,
image: wintech,
}, {
index: 4,
title: 'Usabilla',
from: new Date(2019, 6, 1),
link: 'https://usabilla.com/',
role: 'Software Engineer (Frontend)',
location: translations.remote,
image: usabilla,
}];
export default function Career() {
const [{ translations }] = useLanguage();
return (
<section>
<ScrollingTitle>
{translations.carrer}
</ScrollingTitle>
<ol>
{JOBS(translations).map(({
title,
from,
link,
role,
location,
image,
index,
}) => (
<li key={index}>
<CareerItem
index={index}
title={title}
from={from}
link={link}
role={role}
location={location}
image={image}
/>
{JOBS.length === index && <Divider />}
</li>
))}
</ol>
</section>
);
}
| efa57d1818eceecd816f1444ec2575ce51f8b3dc | [
"JavaScript",
"JSON",
"YAML",
"Markdown"
] | 23 | JavaScript | moroale93/personal-site | ab6adcfa04ef67dfd79bdea57c85dbdbbdbb75c2 | 2b2ab072af13bb9b812a7a9ba64529c6cd842537 |
refs/heads/master | <file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import AuthorQuiz from './AuthorQuiz';
describe('When the AuthorQuiz composed is used', () => {
it('should render successfully', () => {
const div = document.createElement('div');
ReactDOM.render(<AuthorQuiz />, div);
});
});
| 83d3c44db05c2e7093cef015f4e98c91947df914 | [
"JavaScript"
] | 1 | JavaScript | usmanbuilds/author-quiz | d8a8d5e5e5f4567d68d13350f3c8fa2b1eef5756 | bd5c0bcf37c6b98070dbfd9370e798fad2a2fd0c |
refs/heads/master | <file_sep>import firebase from 'firebase/app';
import "firebase/auth";
import 'firebase/database';
import 'firebase/storage';
let firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'admin-panel-5baec.firebaseapp.com',
databaseURL: 'https://admin-panel-5baec-default-rtdb.firebaseio.com',
projectId: 'admin-panel-5baec',
storageBucket: 'admin-panel-5baec.appspot.com',
messagingSenderId: '538269401217',
appId: '1:538269401217:web:9815938c68177c5db34d80',
measurementId: 'G-QT0S23D9EW'
};
firebase.initializeApp(firebaseConfig);
class Database {
auth(mail, pass, fulfilled, rejected) {
return firebase
.auth()
.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
firebase.auth().signInWithEmailAndPassword(mail, pass)
.then(fulfilled, rejected);
})
.catch(rejected);
}
writeData(ref, data) {
firebase.database().ref(ref).set(data);
}
listenData(ref, change) {
const dataRef = firebase.database().ref(ref);
dataRef.on('value', (snapshot) => {
const data = snapshot.val();
change(data);
});
}
pushData(ref, data) {
firebase.database().ref(ref).push(data);
}
listenLastItems(ref, count, change) {
const dataRef = firebase.database().ref(ref);
dataRef.limitToLast(count).on('value', (snapshot) => {
const data = snapshot.val();
change(data);
});
}
putImage(path, image) {
let storageRef = firebase.storage().ref();
let ref = storageRef.child(path);
ref.put(image);
}
getImageUrl(path, callback, triesLeft = 20) {
let slashIndex = path.lastIndexOf('/') + 1;
let pointIndex = path.lastIndexOf('.');
if(path.substr(slashIndex , pointIndex - slashIndex) === 'unnamed') {
return;
}
let storage = firebase.storage();
let pathReference = storage.ref(path);
pathReference.getDownloadURL()
.then(callback)
.catch((error) => {
if(triesLeft >= 7) {
setTimeout(() => {
this.getImageUrl(path, callback, triesLeft - 1);
}, 150);
} else if(triesLeft >= 1) {
setTimeout(() => {
this.getImageUrl(path, callback, triesLeft - 1);
}, 2000);
} else {
// console.log(error);
}
});
}
async getAllImagesAsync(path, callback) {
let storageRef = firebase.storage().ref();
let ref = storageRef.child(path);
let result = await ref.listAll().then(value => value);
callback(result.items);
}
}
class DatabaseProxy extends Database{
constructor() {
super();
this.imagesCache = {};
}
getImageUrl(path, callback, triesLeft = 20) {
if(this.imagesCache[path] !== undefined) {
callback(this.imagesCache[path]);
} else {
super.getImageUrl(path, url => {
this.imagesCache[path] = url;
callback(url);
}, triesLeft);
}
}
}
let database = new Database();
let proxy = new DatabaseProxy(database);
export default proxy;
<file_sep>class Event {
constructor() {
this.subscribers = [];
this.informants = [];
}
subscribe(subscriber) {
this.subscribers.push(subscriber);
}
notify(...args) {
this.subscribers.map(item => item(...args))
}
setInformant(informant) {
this.informants.push(informant)
}
getInfo() {
let info = null;
this.informants.map(item => info = item());
return info;
}
}
export default Event;<file_sep>class ImagesCollector {
static pushInnerImages(source, containerKey, array, propName) {
if(source === undefined) return;
let iterator = (lang, item) => {
if(item[lang][containerKey] === undefined) return;
item[lang].gallery.map(subitem => array.push({
image: subitem[propName],
imageFile: subitem[propName + "File"],
changeImage: name => subitem[propName] = name
}));
};
source.map(item => iterator("rus", item));
source.map(item => iterator("ukr", item));
}
static pushImages(source, array, propName) {
if(source === undefined) return;
let iterator = (lang, item) => array.push({
image: item[lang][propName],
imageFile: item[lang][propName + "File"],
changeImage: name => item[lang][propName] = name
});
source.map(item => iterator("rus", item));
source.map(item => iterator("ukr", item));
}
}
export default ImagesCollector;<file_sep>class InfoItem {
constructor (number) {
this.number = number;
this.url = "";
this.text = "";
}
}
class InfoList {
constructor() {
this.counter = 0;
}
addItem(list) {
const item = new InfoItem(this.counter++);
item.close = this.deleteItem.bind(this, list, item);
list.push(item);
}
deleteItem(list, deleteItem) {
const index = list.indexOf(deleteItem);
if (index === -1) { return };
list.splice(index, 1);
}
}
export default InfoList; | d8f3d58e856820522329330dfde5273bcb16923f | [
"JavaScript"
] | 4 | JavaScript | tkach-gr/admin-panel | 7c73f2678941df492defba30a0d88fdf7d873fde | 7b7f814ac541b566a97ade21813b76da3e2446d5 |
refs/heads/master | <repo_name>andrewjbaumann/confluencespacekeychange<file_sep>/readme.md
# Confluence Space Key Renamer
## Purpose
Atlassian does not provide an out of the box way (or easy way) for you to rename space trees. More information can be found at the link below. Basically, the only reliable way to change a space's key is to export it, change any references to that key in its export file (an entities.xml) and reimport it. This bash script will do all the replacements for you.
## How to use
'''
sh confluenceSpaceKey.sh entitles.xml OLDKEY NEWKEY
'''
Where OLDKEY and NEWKEY are obvious (the old space key and the new space key respectively), but must be given in upper case for now. The script automatically converts them to lower case for some of the replacements.
## Todo
I'd like to improve the speed by using grep int he beginning to find the target lines, or by using multithreading.
<file_sep>/changeSpaceKey.sh
#!/bin/bash
# args:
# [1] = entity file to change
# [2] = OLDKEY (UPPER)
# [3] = NEWKEY (UPPER)
echo "Params"
echo 'Entities File = ' $1
echo 'Old Space Key (MUST BE UPPERCASE) = ' $2
echo 'New Space Key (MUST BE UPPERCASE) = ' $3
oldKeyLower=$(echo $2 | tr '[:upper:]' '[:lower:]')
newKeyLower=$(echo $3 | tr '[:upper:]' '[:lower:]')
start=`date +%s`
echo 'Old Space Key (converted lower case) = ' $oldKeyLower
echo 'New Space Key (converted lower case) = ' $newKeyLower
cp "$1" converted.xml
echo "0/33"
sed -i "s/spaceKey=$2/spaceKey=$3/g" "converted.xml"
echo "1/33"
sed -i "s/\[$2:/\[$3:/g" "converted.xml"
echo "2/33"
sed -i "s/key=$2\]/key=$3\]/g" "converted.xml"
echo "3/33"
sed -i "s/<spaceKey>$2<\/spaceKey>/<spaceKey>$3<\/spaceKey>/g" "converted.xml"
echo "4/33"
sed -i "s/ri:space-key=\"$2\"/ri:space-key=\"$3\"/g" "converted.xml"
echo "5/33"
sed -i "s/ri:space-key=$2/ri:space-key=$3/g" "converted.xml"
echo "6/33"
sed -i "s/ri:space-key=$2/ri:space-key=$3/g" "converted.xml"
echo "7/33"
sed -i "s/<ac:parameter ac:name=\"spaces\">$2<\/ac:parameter>/<ac:parameter ac:name=\"spaces\">$3<\/ac:parameter>/g" "converted.xml"
echo "8/33"
sed -i "s/<ac:parameter ac:name=\"spaceKey\">$2<\/ac:parameter>/<ac:parameter ac:name=\"spaceKey\">$3<\/ac:parameter>/g" "converted.xml"
echo "9/33"
sed -i "s/\[CDATA\[$2\]/\[CDATA\[$3\]/g" "converted.xml"
echo "10/33"
sed -i "s/spaceKey=$2/spaceKey=$3/g" "converted.xml"
echo "11/33"
sed -i "s/\[$2:/\[$3:/g" "converted.xml"
echo "12/33"
sed -i "s/>space:$2</>space:$3</g" "converted.xml"
echo "13/33"
sed -i "s/\[CDATA\[{\"spaceKey\":\"$2\"/\[CDATA\[{\"spaceKey\":\"$3\"/g" "converted.xml"
echo "14/33"
sed -i "s/space = \"$2\"/space = \"$3\"/g" "converted.xml"
echo "15/33"
sed -i "s/\"spaceKey\":\"$2\"/\"spaceKey\":\"$3\"/g" "converted.xml"
echo "16/33"
sed -i "s/spaceKey=$oldKeyLower/spaceKey=$newKeyLower/g" "converted.xml"
echo "17/33"
sed -i "s/\[$oldKeyLower:/\[$newKeyLower:/g" "converted.xml"
echo "18/33"
sed -i "s/key=$oldKeyLower\]/key=$newKeyLower\]/g" "converted.xml"
echo "19/33"
sed -i "s/<spaceKey>$oldKeyLower<\/spaceKey>/<spaceKey>$newKeyLower<\/spaceKey>/g" "converted.xml"
echo "20/33"
sed -i "s/ri:space-key=\"$oldKeyLower\"/ri:space-key=\"$newKeyLower\"/g" "converted.xml"
echo "21/33"
sed -i "s/ri:space-key=$oldKeyLower/ri:space-key=$newKeyLower/g" "converted.xml"
echo "22/33"
sed -i "s/ri:space-key=$oldKeyLower/ri:space-key=$newKeyLower/g" "converted.xml"
echo "23/33"
sed -i "s/<ac:parameter ac:name=\"spaces\">$oldKeyLower<\/ac:parameter>/<ac:parameter ac:name=\"spaces\">$newKeyLower<\/ac:parameter>/g" "converted.xml"
echo "24/33"
sed -i "s/<ac:parameter ac:name=\"spaceKey\">$oldKeyLower<\/ac:parameter>/<ac:parameter ac:name=\"spaceKey\">$newKeyLower<\/ac:parameter>/g" "converted.xml"
echo "25/33"
sed -i "s/\[CDATA\[$oldKeyLower\]/\[CDATA\[$newKeyLower\]/g" "converted.xml"
echo "26/33"
sed -i "s/spaceKey=$oldKeyLower/spaceKey=$newKeyLower/g" "converted.xml"
echo "27/33"
sed -i "s/\[$oldKeyLower:/\[$newKeyLower:/g" "converted.xml"
echo "28/33"
sed -i "s/>space:$oldKeyLower</>space:$newKeyLower</g" "converted.xml"
echo "29/33"
sed -i "s/\[CDATA\[{\"spaceKey\":\"$oldKeyLower\"/\[CDATA\[{\"spaceKey\":\"$newKeyLower\"/g" "converted.xml"
echo "30/33"
sed -i "s/space = \"$oldKeyLower\"/space = \"$newKeyLower\"/g" "converted.xml"
echo "31/33"
sed -i "s/\"spaceKey\":\"$oldKeyLower\"/\"spaceKey\":\"$newKeyLower\"/g" "converted.xml"
echo "32/33"
sed -i "s/<property name=\"lowerDestinationSpaceKey\"><!\[CDATA\[$3\]\]><\/property>/<property name=\"lowerDestinationSpaceKey\"><!\[CDATA\[$newKeyLower\]\]><\/property>/g" "converted.xml"
echo "33/33"
end=`date +%s`
runtime=$((end-start))
echo "Runtime:" $runtime | a4ec7799a1595a56563eb6cb9a90ff6d55af6b5a | [
"Markdown",
"Shell"
] | 2 | Markdown | andrewjbaumann/confluencespacekeychange | 2f51309447722ad64ce86a32563e50054befb1ec | b2125ce915c02c7da3e3912b9155dd2fb9ee8ae3 |
refs/heads/main | <repo_name>nuelscode/nuels_portfolio<file_sep>/src/NoMatch.js
import React from 'react'
export const NoMatch= () => (
<div>
<h2>Home Page</h2>
<h1>404 error!</h1>
</div>
)<file_sep>/src/Contact.js
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPhone } from "@fortawesome/free-solid-svg-icons";
import { faEnvelope } from "@fortawesome/free-solid-svg-icons";
import { faMapMarkerAlt } from "@fortawesome/free-solid-svg-icons";
import { faFacebook } from "@fortawesome/free-brands-svg-icons";
import { faTwitter } from '@fortawesome/free-brands-svg-icons';
import { faInstagram } from '@fortawesome/free-brands-svg-icons';
import { faLinkedin } from '@fortawesome/free-brands-svg-icons';
/* import { Home } from "./Home";
import { About } from "./About";
import { Experience } from "./Experience";
import { Services } from "./Services";
import { Portfolio } from "./Portfolio";
import { NoMatch } from "./NoMatch"; */
export const Contact = () =>(
<>
<div className="contact">
<h1>Contact Me!</h1>
<p className="sub-title">If you need to create one</p>
<div className="contact-container">
<div className="contact-info">
<h4>
Contact Information
</h4>
<p>Fill up the form and I will get back to you within 24hours </p>
<div className="icon-text">
<FontAwesomeIcon class="fas" icon={faPhone} />
<span>+234(0) 813-492-9521</span>
</div>
<div className="icon-text">
<FontAwesomeIcon class="fas" icon= {faEnvelope} />
<span><EMAIL></span>
</div>
<div className="icon-text">
<FontAwesomeIcon class="fas" icon={faMapMarkerAlt} />
<span>Estate Drive Lekki Chevron</span>
</div>
<div className="social-media">
<a href="#" className="icon-social">
<FontAwesomeIcon icon={faFacebook} style={{ color: "white"}} />
</a>
<a href="#" className="icon-social">
<FontAwesomeIcon icon={faInstagram} style={{ color: "white"}} />
</a>
<a href="#" className="icon-social">
<FontAwesomeIcon icon={faTwitter} style={{ color: "white"}} />
</a>
<a href="#" className="icon-social">
<FontAwesomeIcon icon={faLinkedin} style={{ color: "white"}} />
</a>
</div>
</div>
<form>
<div className="col">
<div className="form-group">
<label>First Name</label>
<input type="text" />
</div>
<div className="form-group">
<label>Last Name</label>
<input type="text" />
</div>
</div>
<div className="col">
<div className="form-group">
<label>E-Mail</label>
<input type="email" />
</div>
<div className="form-group">
<label>Phone #</label>
<input type="tel" />
</div>
</div>
<div className="col">
<div className="form-group solo">
<label>What Services Do You Need?</label>
<div id="radio-buttons">
<div className="radio-button">
<input type="radio" id="radionavigation" name="type" value="navigation" /><label for="radionavigation"> Navigation App</label>
</div>
<div className="radio-button">
<input type="radio" id="radiohybrid" name="type" value=" hybrid" /><label for="radiohybrid">Hybrid Mobile App</label>
</div>
<div className="radio-button">
<input type="radio" id="radiolandingpage" name="type" value=" landingpage" /><label for="radiolandingpage" >Landing Page</label>
</div>
<div className="radio-button">
<input type="radio" id="radioecommerce" name="type" value=" ecommerce" /><label for="radioecommerce">E-Commerce</label>
</div>
</div>
</div>
</div>
<div className="col">
<div className="form-group solo ">
<label>Message</label>
<textarea></textarea>
</div>
</div>
<div className="col">
<div className="form-group right">
<button className="primary">Send Message</button>
</div>
</div>
</form>
</div>
</div>
</>
)
<file_sep>/src/components/Navbar.js
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars } from "@fortawesome/free-solid-svg-icons";
const Navbar = () => {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-dark">
<div className="container">
<a className="navbar-brand" href="#">MyLogo</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<FontAwesomeIcon icon={faBars} style={{ color: "#fff" }}/>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ms-auto" >
<li className="nav-item ">
<a className="nav-link" href="/">Home <span className="sr-only">(current)</span></a>
</li>
<li className="nav-item">
<a className="nav-link" href="/about">About Me</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/experience">Experience</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/services">Services</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/portfolio">Portfolio</a>
</li>
<li className="nav-item">
<a className="nav-link" href="/contact">Contact Me</a>
</li>
</ul>
</div>
</div>
</nav>
)
}
export default Navbar
<file_sep>/src/Home.js
import React from 'react'
import { Link } from "react-router-dom";
export const Home = () =>(
<div className="home">
<h1>Home Page</h1>
<h1>To get started with React Router in a web app, you’ll need a React web app. </h1>
<p>If you need to create one, we recommend you try Create React App. It’s a popular tool that works really well with React Router</p>
<h2>install create-react-app and make a new project with it. </h2>
<Link to="/signup">
<button variant="outlined">
Sign up
</button>
</Link>
</div>
)
<file_sep>/src/About.js
import React from 'react'
export const About = () =>(
<div>
<h2>About Page</h2>
<h1>To get started with React Router in a web app, you’ll need a React web app. </h1>
<p>In this example we have 3 “pages” handled by the router: a home page, an about page, and a users page. As you click around on the different</p>
<h2>install create-react-app and make a new project with it. </h2>
</div>
)
| 3b17b8ff8120ce5d20a7489d3428133f00fb7546 | [
"JavaScript"
] | 5 | JavaScript | nuelscode/nuels_portfolio | b5cad7047976167a0ab26c3bdc9ab6bddc7d995e | 27283ef0c15304596b42b07dadb1e28f876f0872 |
refs/heads/master | <file_sep>local L = LibStub("AceLocale-3.0"):NewLocale("fbngBuffFrame","ruRU")
if not L then return end
-- // @localization(locale="ruRU", format="lua_additive_table", same-key-is-true=true, handle-subnamespaces="concat")@
L = L or {}
L["Buffs"] = "Баффы"
L["Debuffs"] = "Дебаффы"
L["Display parameters"] = "Показывать параметры"
L["Elements by line"] = "Баффов в линии"
L["growth_to"] = "Увеличено до"
L["High"] = "Долго"
L["Icon size"] = "Размер иконки"
L["left"] = "лево"
L["Left time"] = "Оставшееся время"
L["Left time font size"] = "Размер шрифта оставшегося времени"
L["Low"] = "Мало"
L["Maximum number of elements to show"] = "Баффов показывать"
L["Med"] = "Средне"
L["None"] = "Ауры (без времени)"
L["Padding between elements"] = "Расстояние между элементами"
L["right"] = "право"
L["Show / Hide anchor"] = "Показать / Спрятать якорь"
L["Show Blizzard Frame"] = "Показать стандартные фреймы"
L["Stack counter size"] = "Размер счётчика стаков"
L["Status bar width"] = "Ширина статусного бара"
L["Wench"] = "Чары на оружии"
<file_sep>local debug = false;
--@alpha@
debug = true;
--@end-alpha@
local L = LibStub("AceLocale-3.0"):NewLocale("fbngBuffFrame","enUS", true, debug)
if not L then return end
L["Buffs"] = true
L["Debuffs"] = true
L["Display parameters"] = true
L["Elements by line"] = true
L["growth_to"] = "Growth to"
L["High"] = true
L["Icon size"] = true
L["left"] = true
L["Left time"] = true
L["Left time font size"] = true
L["Low"] = true
L["Maximum number of elements to show"] = true
L["Med"] = true
L["None"] = "Without delay";
L["Padding between elements"] = true
L["right"] = true
L["Show Blizzard Frame"] = true
L["Show / Hide anchor"] = true
L["Stack counter size"] = true
L["Status bar width"] = true
L["Wench"] = "Weapon Enchants";
<file_sep>-- A small (but complete) addon, that doesn't do anything.
local mod = LibStub("AceAddon-3.0"):NewAddon("fbngBuffFrame", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("fbngBuffFrame");
fbngBuffFrame = mod
-- creer 3 frames :
-- 1 pour les buffs
-- 1 pour les debuffs
-- 1 pour les enchant d'armes (à voir pe dans les buffs)
-- 1 frame : y lignes de x éléments
-- 1 élément : cadre
-- barre verticale "jauge" du temps
-- icon du buff/debuff
-- text : nb stack
-- text : timer restant
local defaults = {
profile = {
showblizz = false,
buffs = {
n_by_row = 10,
max_display = BUFF_MAX_DISPLAY,
status_bar_width = 3,
icon_size = 20,
count_size = 13,
timer_size = 10,
padding = 3,
growth_to = "left",
colors = {
high = { r = 0, g = 1, b = 0, a = 1 },
med = { r = 1, g = 1, b = 0, a = 1 },
low = { r = 1, g = 0, b = 0, a = 1 },
none = { r = .5, g = 0, b = .5, a = 1 },
},
pos_x = UIParent:GetWidth()/2,
pos_y = UIParent:GetHeight()/2,
show_anchor = false,
},
debuffs = {
n_by_row = 10,
max_display = DEBUFF_MAX_DISPLAY,
status_bar_width = 3,
icon_size = 20,
count_size = 13,
timer_size = 10,
padding = 3,
growth_to = "left",
colors = {
high = { r = 1, g = 0, b = 0, a = 1 },
med = { r = 1, g = 1, b = 0, a = 1 },
low = { r = 0, g = 1, b = 0, a = 1 },
none = { r = .5, g = 0, b = .5, a = 1 },
},
pos_x = UIParent:GetWidth()/2,
pos_y = UIParent:GetHeight()/2,
show_anchor = false,
},
wench = {
--n_by_row = 10,
--max_display = 3,
status_bar_width = 3,
icon_size = 20,
count_size = 13,
timer_size = 10,
padding = 3,
growth_to = "left",
colors = {
high = { r = 0, g = 1, b = 0, a = 1 },
med = { r = 1, g = 1, b = 0, a = 1 },
low = { r = 1, g = 0, b = 0, a = 1 },
none = { r = .5, g = 0, b = .5, a = 1 },
},
pos_x = UIParent:GetWidth()/2,
pos_y = UIParent:GetHeight()/2,
show_anchor = false,
},
}
}
local MenuOptions = {
name = "fbngBuffFrame",
type = "group",
handler = mod,
get = "OptionsGet",
set = "OptionsSet",
args = {
showblizz = {
name = L["Show Blizzard Frame"],
type = "toggle",
order = 0,
},
},
}
local DebuffTypeColor = { };
DebuffTypeColor["none"] = { r = 0, g = 0, b = 0, a = 0.7 };
DebuffTypeColor["Magic"] = { r = 0.20, g = 0.60, b = 1.00, a = 1 };
DebuffTypeColor["Curse"] = { r = 0.60, g = 0.00, b = 1.00, a = 1 };
DebuffTypeColor["Disease"] = { r = 0.60, g = 0.40, b = 0, a = 1 };
DebuffTypeColor["Poison"] = { r = 0.00, g = 0.60, b = 0, a = 1 };
DebuffTypeColor[""] = DebuffTypeColor["none"];
mod.buffs_anchor = nil
mod.buffs = {}
mod.debuffs_anchor = nil
mod.debuffs = {}
mod.wench = {}
mod.wench_anchor = nil
function mod:OnInitialize()
-- do init tasks here, like loading the Saved Variables,
-- or setting up slash commands.
self:RegisterChatCommand("fbf", "CommandParser")
MenuOptions.args["buffs"] = self:GetBarOptions(L["Buffs"], BUFF_MAX_DISPLAY)
MenuOptions.args["debuffs"] = self:GetBarOptions(L["Debuffs"], DEBUFF_MAX_DISPLAY)
MenuOptions.args["wench"] = self:GetBarOptions(L["Wench"], NUM_TEMP_ENCHANT_FRAMES, true)
self.db = LibStub("AceDB-3.0"):New("fBFDB", defaults, true)
MenuOptions.args.Profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db);
LibStub("AceConfigRegistry-3.0"):RegisterOptionsTable("fBF", MenuOptions)
LibStub("AceConfigDialog-3.0"):AddToBlizOptions("fBF", "fbngBuffFrame")
--LibStub("AceConfig-3.0"):RegisterOptionsTable("fBF-Profiles", LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db))
--self.profilesFrame = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("fBF-Profiles", "Profiles", "fBF")
end
function mod:OptionsGet(info)
return self.db.profile[info[#info]] or defaults.profile[info[#info]]
end
function mod:OptionsSet(info, value)
self.db.profile[info[#info]] = value or defaults.profile[info[#info]]
self:UpdateConf()
end
function mod:ColorGetter (info)
local bar = self.db.profile[info[1]]
local r = bar.colors[info[#info]].r
local g = bar.colors[info[#info]].g
local b = bar.colors[info[#info]].b
local a = bar.colors[info[#info]].a
return r, g, b, a
end
function mod:ColorSetter (info, r, g, b, a)
local bar = self.db.profile[info[1]]
bar.colors[info[#info]].r = r
bar.colors[info[#info]].g = g
bar.colors[info[#info]].b = b
bar.colors[info[#info]].a = a
end
function mod:BuffOptionsGet(info)
local v
if info[#info] == "max_display" or info[#info] == "n_by_row" or info[#info] == "growth_to" then
v = self.db.profile[info[1]][info[#info]] or defaults.profile[info[1]][info[#info]]
else
v = string.format( "%i", self.db.profile[info[1]][info[#info]] or defaults.profile[info[1]][info[#info]])
end
return v
end
function mod:BuffOptionsSet(info, value)
local v = nil
if (type(value) ~= "string") then
v = math.floor( tonumber( value ) or 0 )
if v <= 0 then v = defaults.profile[info[1]][info[#info]] end
else
v = value
end
if self.db.profile[info[1]][info[#info]] ~= v then
self.db.profile[info[1]][info[#info]] = v
self:ArrangeBuffs(info[1])
end
end
function mod:GetBarOptions(bar_name, bar_max, iswench)
local barOpts = {
name = bar_name,
type = "group",
order = 1,
get = "BuffOptionsGet",
set = "BuffOptionsSet",
args = {
show_anchor = {
name = L["Show / Hide anchor"],
type = "execute",
order = 0,
func = "ToggleAnchor",
},
buffs_display = {
name = L["Display parameters"],
type = "group",
order = 3,
inline = true,
args = {
icon_size = {
name = L["Icon size"],
type = "input",
order = 0,
},
status_bar_width = {
name = L["Status bar width"],
type = "input",
order = 1,
},
count_size = {
name = L["Stack counter size"],
type = "input",
order = 2,
},
timer_size = {
name = L["Left time font size"],
type = "input",
order = 3,
},
padding = {
name = L["Padding between elements"],
type = "input",
order = 4,
},
growth_to = {
name = L["growth_to"],
type = "select",
order = 5,
values = {
left = L["left"],
right = L["right"],
},
},
colors = {
type = 'group',
name = L["Left time"],
order = 6,
get = "ColorGetter",
set = "ColorSetter",
guiInline = true,
args = {
high = {
type = 'color',
name = L["High"],
order = 1,
hasAlpha = true,
},
med = {
type = 'color',
name = L["Med"],
order = 2,
hasAlpha = true,
},
low = {
type = 'color',
name = L["Low"],
order = 3,
hasAlpha = true,
},
none = {
type = 'color',
name = L["None"],
order = 3,
hasAlpha = true,
},
},
},
},
},
},
}
if iswench ~= true then
barOpts.args.n_by_row = {
name = L["Elements by line"],
type = "range",
order = 1,
min = 1,
max = bar_max,
step = 1,
}
barOpts.args.max_display = {
name = L["Maximum number of elements to show"],
type = "range",
order = 2,
min = 1,
max = bar_max,
step = 1,
}
end
return barOpts
end
function mod:ToggleAnchor(info, value)
self.db.profile[info[1]].show_anchor = not self.db.profile[info[1]].show_anchor;
if self.db.profile[info[1]].show_anchor then
self[info[1] .. "_anchor"]:Show()
else
self[info[1] .. "_anchor"]:Hide()
end
end
function mod:UpdateConf()
if self.db.profile.showblizz then
BuffFrame:RegisterEvent("UNIT_AURA")
BuffFrame:Show()
TemporaryEnchantFrame:Show()
BuffFrame_Update()
else
BuffFrame:Hide()
BuffFrame:UnregisterEvent("UNIT_AURA")
TemporaryEnchantFrame:Hide()
end
end
function mod:CommandParser()
LibStub("AceConfigDialog-3.0"):Open("fBF");
end
function mod:OnEnable()
-- Do more initialization here, that really enables the use of your addon.
-- Register Events, Hook functions, Create Frames, Get information from
-- the game that wasn't available in OnInitialize
self.buffs_anchor = self:CreateAnchor(self.db.profile.buffs)
self.buffs_anchor:Hide()
--
self.debuffs_anchor = self:CreateAnchor(self.db.profile.debuffs)
self.debuffs_anchor:Hide()
--
self.wench_anchor = self:CreateAnchor(self.db.profile.wench)
self.wench_anchor:Hide()
--
for i=1, BUFF_MAX_DISPLAY do
self.buffs[i] = self:CreateIcon("HELPFUL", i)
self.buffs[i]:Show()
end
--
for i=1, DEBUFF_MAX_DISPLAY do
self.debuffs[i] = self:CreateIcon("HARMFUL", i)
self.debuffs[i]:Show()
end
--
for i=1, NUM_TEMP_ENCHANT_FRAMES do
self.wench[i] = self:CreateIcon("Wench", i + 15)
end
self:ArrangeBuffs("buffs");
self:ArrangeBuffs("debuffs");
self:ArrangeBuffs("wench");
self.lastTime = GetTime()
self.OnUpdateStarted = self:ScheduleRepeatingTimer("OnUpdate", .125, self)
self:RegisterEvent("UNIT_AURA")
self:UNIT_AURA(nil, "player")
self:UpdateConf()
end
function mod:CreateAnchor(pos_storage)
local f = CreateFrame("Button",nil,UIParent)
f:SetBackdrop({
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", tile = true, tileSize = 0,
insets = {left = 0, right = 0, top = 0, bottom = 0},
})
f:SetBackdropColor(0, 1, 0, 1)
f:RegisterForDrag("LeftButton")
f:EnableMouse(true)
f:SetMovable(true)
f:SetFrameStrata("LOW")
f:SetFrameLevel(2)
f:SetScript("OnMouseDown",function(self) self:StartMoving() end)
f:SetScript("OnMouseUp",function(self)
self:StopMovingOrSizing();
local pos_x, pos_y = self:GetLeft(), self:GetTop()
local s = self:GetEffectiveScale()
pos_storage.pos_x = pos_x * s
pos_storage.pos_y = pos_y * s
end)
f.SetPos = function(self, x, y )
local s = self:GetEffectiveScale()
self:ClearAllPoints()
self:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x / s , y / s)
end
f:SetPos( pos_storage.pos_x, pos_storage.pos_y )
return f
end
function mod:CreateIcon(filter, index)
local f
--if filter == "wench" then
-- f = CreateFrame("Button", nil, UIParent)
--else
f = CreateFrame("Button", nil, UIParent, "SecureActionButtonTemplate")
--end
f:SetBackdrop({
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", tile = true, tileSize = 0,
insets = {left = 0, right = 0, top = 0, bottom = 0},
})
local color = DebuffTypeColor["none"]
f:SetBackdropColor(color.r, color.g, color.b, color.a)
-- buff icon
f.icon = f:CreateTexture(nil,"ARTWORK")
f.icon:SetTexCoord(.07, .93, .07, .93)
f.icon:SetPoint("TOP", 0, 0)
f.icon:SetPoint("RIGHT", 0, 0)
--f.icon:SetTexture(icon)
-- stack count
f.count = f:CreateFontString(nil, "OVERLAY")
f.count:SetJustifyH("RIGHT")
f.count:SetVertexColor(1,1,1)
f.timer = f:CreateFontString(nil, "OVERLAY")
f.timer:SetJustifyH("RIGHT")
f.timer:SetJustifyV("BOTTOM")
f.timer:SetVertexColor(1,1,1)
f.timer:Show()
f.bar = CreateFrame("StatusBar", nil, f)
f.bar:SetStatusBarTexture[[Interface\AddOns\fbngBuffFrame\white.tga]]
f.bar:SetOrientation("VERTICAL")
--f.bar:SetStatusBarColor(1,0,0)
f.bar:Show()
f.bar.bg = f.bar:CreateTexture(nil,"BACKGROUND")
f.bar.bg:SetTexture[[Interface\AddOns\fbngBuffFrame\white.tga]]
f.bar.bg:SetAllPoints(f.bar)
--f.bar.bg:SetVertexColor(0.4,0,0)
f:SetFrameStrata("LOW")
f:SetFrameLevel(2)
f:EnableMouse(true)
if filter == "HELPFUL" then
f:RegisterForClicks("RightButtonUp")
-- Setup stuff for clicking off buffs
f:SetAttribute("type", "cancelaura" )
f:SetAttribute("unit", "player")
f:SetAttribute("index", index)
elseif filter == "wench" then
f:RegisterForClicks("RightButtonUp")
-- Setup stuff for clicking off buffs
f:SetAttribute("type", "click" )
f:SetAttribute("clickbutton", "TempEnchant".. (index-15))
end
f.id = index
if filter == "Wench" then
--f:RegisterForClicks("RightButtonUp")
-- Setup stuff for clicking off buffs
--f:SetScript("OnClick",function(self)
--CancelItemTempEnchantment(self.id); -- should be 1 for mh
--end)
--f:SetAttribute("unit", "player")
--f:SetAttribute("index", index)
f:SetScript("OnEnter",function(self)
if self:GetAlpha() ~= 0 then
GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT")
GameTooltip:SetInventoryItem("player", self.id)
end
end)
else
f.filter = filter
f:SetScript("OnEnter",function(self)
--mod:Print(self.filter, " : " , self.id);
GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT");
GameTooltip:SetFrameLevel(self:GetFrameLevel() + 2);
GameTooltip:SetUnitAura("player", self.id, self.filter);
end)
end
f:SetScript("OnLeave",function(self)
GameTooltip:Hide();
end)
return f
end
function mod:OnUpdate()
local curTime = GetTime()
local elapsed = curTime - self.lastTime
self.lastTime = curTime
local buf_high = self.db.profile.buffs.colors.high
local buf_med = self.db.profile.buffs.colors.med
local buf_low = self.db.profile.buffs.colors.low
local buf_none = self.db.profile.buffs.colors.none
local debuf_high = self.db.profile.debuffs.colors.high
local debuf_med = self.db.profile.debuffs.colors.med
local debuf_low = self.db.profile.debuffs.colors.low
local debuf_none = self.db.profile.debuffs.colors.none
local wench_high = self.db.profile.wench.colors.high
local wench_med = self.db.profile.wench.colors.med
local wench_low = self.db.profile.wench.colors.low
local wench_none = self.db.profile.wench.colors.none
for i = 1, self.db.profile.buffs.max_display do
local f = self.buffs[i]
if f:GetAlpha() ~= 0 then
local name, rank, icon, count, dispelType, duration, expires = UnitAura("player",i,"HELPFUL")
self:UpdateButton(f, count, expires, duration, buf_high, buf_med, buf_low, buf_none)
end
end
for i = 1, self.db.profile.debuffs.max_display do
local f = self.debuffs[i]
if f:GetAlpha() ~= 0 then
local name, rank, icon, count, dispelType, duration, expires = UnitAura("player",i,"HARMFUL")
self:UpdateButton(f, count, expires, duration, debuf_high, debuf_med, debuf_low, debuf_none)
end
end
local hasMainHandEnchant, mainHandExpiration, mainHandCharges,
hasOffHandEnchant, offHandExpiration, offHandCharges,
hasThrownEnchant, thrownExpiration, thrownCharges = GetWeaponEnchantInfo();
self:UpdateWench(self.wench[1], hasMainHandEnchant, mainHandExpiration, mainHandCharges, wench_high, wench_med, wench_low, wench_none);
self:UpdateWench(self.wench[2], hasOffHandEnchant, offHandExpiration, offHandCharges, wench_high, wench_med, wench_low, wench_none);
self:UpdateWench(self.wench[3], hasThrownEnchant, thrownExpiration, thrownCharges, wench_high, wench_med, wench_low, wench_none);
end
function mod:UpdateWench(f, hasEnchant, expiration, charges, color_high, color_med, color_low, color_none)
if f.max == nil then f.max = 0 end
if f.prev == nil then f.prev = 0 end
if not hasEnchant then
if f.max ~= 0 then f.max = 0 end
if f.prev ~= 0 then f.prev = 0 end
if f:GetAlpha() ~= 0 then
f:SetAlpha(0)
f:EnableMouse(false)
end
return
end
-- do stuff for wench
if f.prev == expiration then
return
elseif f.prev < expiration then
f.max = expiration
f.prev = expiration
f.bar:SetMinMaxValues(0,expiration)
end
if f:GetAlpha() == 0 then
f:SetAlpha(1)
f:EnableMouse(true)
end
f.prev = expiration
f.bar:SetValue(expiration)
f.icon:SetTexture(GetInventoryItemTexture("player", f.id))
f.timer:SetFormattedText(SecondsToTimeAbbrev(f.prev/1000));
local percent = (f.prev/f.max)
if percent > .5 then
local percent_scaled = (percent - .5) / .5
r = (color_high.r * (percent_scaled)) + (color_med.r * (1-percent_scaled))
g = (color_high.g * (percent_scaled)) + (color_med.g * (1-percent_scaled))
b = (color_high.b * (percent_scaled)) + (color_med.b * (1-percent_scaled))
a = (color_high.a * (percent_scaled)) + (color_med.a * (1-percent_scaled))
else
local percent_scaled = percent / .5
r = (color_med.r * (percent_scaled)) + (color_low.r * (1-percent_scaled))
g = (color_med.g * (percent_scaled)) + (color_low.g * (1-percent_scaled))
b = (color_med.b * (percent_scaled)) + (color_low.b * (1-percent_scaled))
a = (color_med.a * (percent_scaled)) + (color_low.a * (1-percent_scaled))
end
f.bar:SetStatusBarColor(r,g,b, a)
f.bar.bg:SetVertexColor(r/2,g/2,b/2, a)
if charges and charges > 1 then
if not f.count:IsShown() then f.count:Show() end
f.count:SetText(charges)
elseif f.count:IsShown() then
f.count:Hide()
end
end
function mod:UpdateButton(f, count, expires, duration, color_high, color_med, color_low, color_none)
local r, g, b, a
if expires and expires ~= 0 then
local left = expires-GetTime()
if left > 0 then
if not f.timer:IsShown() then f.timer:Show() end
f.bar:SetValue(left)
f.timer:SetFormattedText(SecondsToTimeAbbrev(left));
--[[
if left > duration/2 => high -> med
high * 1-((duration-left)/(duration/2)) +
else med -> low
--]]
local percent = (left/duration)
if percent > .5 then
local percent_scaled = (percent - .5) / .5
r = (color_high.r * (percent_scaled)) + (color_med.r * (1-percent_scaled))
g = (color_high.g * (percent_scaled)) + (color_med.g * (1-percent_scaled))
b = (color_high.b * (percent_scaled)) + (color_med.b * (1-percent_scaled))
a = (color_high.a * (percent_scaled)) + (color_med.a * (1-percent_scaled))
else
local percent_scaled = percent / .5
r = (color_med.r * (percent_scaled)) + (color_low.r * (1-percent_scaled))
g = (color_med.g * (percent_scaled)) + (color_low.g * (1-percent_scaled))
b = (color_med.b * (percent_scaled)) + (color_low.b * (1-percent_scaled))
a = (color_med.a * (percent_scaled)) + (color_low.a * (1-percent_scaled))
end
f.bar:SetStatusBarColor(r,g,b, a)
f.bar.bg:SetVertexColor(r/2,g/2,b/2, a)
end
else
r = color_none.r
g = color_none.g
b = color_none.b
a = color_none.a
f.bar:SetValue(0)
f.bar:SetMinMaxValues(0,1)
f.bar:SetStatusBarColor(r,g,b, a)
f.bar.bg:SetVertexColor(r/2,g/2,b/2, a)
f.timer:Hide()
end
if count and count > 1 then
if not f.count:IsShown() then f.count:Show() end
f.count:SetText(count)
elseif f.count:IsShown() then
f.count:Hide()
end
end
function mod:UNIT_AURA(event, unit)
if unit ~= "player" then return end
local name, rank, icon, count, debuffType, duration, expires
for i=1, BUFF_MAX_DISPLAY do
local f = self.buffs[i]
name, rank, icon, count, debuffType, duration = UnitAura("player",i,"HELPFUL")
self:OnUnitAura(f, name, duration, count, icon);
end
for i=1, DEBUFF_MAX_DISPLAY do
local f = self.debuffs[i]
name, rank, icon, count, debuffType, duration = UnitAura("player",i,"HARMFUL")
self:OnUnitAura(f, name, duration, count, icon);
local color
if ( debuffType ) then
color = DebuffTypeColor[debuffType];
else
color = DebuffTypeColor["none"];
end
f:SetBackdropColor(color.r, color.g, color.b, color.a)
end
self:OnUpdate()
end
function mod:OnUnitAura(f, name, duration, count, icon)
if name == nil then
if f:GetAlpha() == 1 then
f:SetAlpha(0)
--f:EnableMouse(false)
end
else
if f:GetAlpha() ~= 1 then
f:SetAlpha(1)
--f:EnableMouse(true)
end
if duration and duration ~= 0 then
f.bar:SetMinMaxValues(0,duration)
else
f.bar:SetValue(0)
f.bar:SetMinMaxValues(0,1)
end
if count and count > 1 then
f.count:Show()
end
f.icon:SetTexture(icon)
end
end
function mod:ArrangeBuffs(bar)
local max;
local n_by_row;
if bar == "wench" then
max = NUM_TEMP_ENCHANT_FRAMES
n_by_row = NUM_TEMP_ENCHANT_FRAMES
else
max = self.db.profile[bar].max_display
n_by_row = self.db.profile[bar].n_by_row
end
local prev = self[bar .. "_anchor"]
local i_size = self.db.profile[bar].icon_size
local c_size = self.db.profile[bar].count_size
local t_size = self.db.profile[bar].timer_size
local pad = self.db.profile[bar].padding
local sb_width = self.db.profile[bar].status_bar_width
local growth_dir = -1;
if self.db.profile[bar].growth_to == "right" then
growth_dir = 1;
end
local bar_width = pad + sb_width + pad + i_size + pad
local bar_height = pad + i_size + pad
prev:SetWidth(bar_width)
prev:SetHeight(bar_height)
for i = 1, max do
local b = self[bar][i]
local step_y = 0
local step_x = growth_dir * bar_width
if (i % n_by_row) == 1 then
prev = self[bar .. "_anchor"]
step_y = -(bar_height + pad + t_size + pad)* ((i-1) / n_by_row)
end
b:SetWidth(bar_width)
b:SetHeight(bar_height)
b.icon:SetWidth(i_size)
b.icon:SetHeight(i_size)
b.icon:ClearAllPoints()
b.icon:SetPoint("TOP", b, "TOP", 0, -pad)
b.icon:SetPoint("RIGHT", b, "RIGHT", -pad, 0)
b.count:SetPoint("BOTTOMRIGHT",b.icon,"BOTTOMRIGHT",pad,pad)
b.count:SetFont("Fonts\\FRIZQT__.TTF", c_size ,"OUTLINE")
b.timer:SetPoint("BOTTOMRIGHT",b,"BOTTOMRIGHT",pad,-(pad+t_size))
b.timer:SetFont("Fonts\\FRIZQT__.TTF", t_size ,"OUTLINE")
b.bar:SetWidth(sb_width)
b.bar:SetHeight(i_size)
b.bar:SetPoint("TOPLEFT",b,"TOPLEFT", pad, -pad)
b:ClearAllPoints()
b:SetPoint("TOPLEFT", prev, "TOPLEFT", step_x, step_y)
prev = b
end
end
function mod:OnDisable()
-- Unhook, Unregister Events, Hide frames that you created.
-- You would probably only use an OnDisable if you want to
-- build a "standby" mode, or be able to toggle modules on/off.
end
<file_sep>local L = LibStub("AceLocale-3.0"):NewLocale("fbngBuffFrame","zhTW")
if not L then return end
-- // @localization(locale="zhTW", format="lua_additive_table", same-key-is-true=true, handle-subnamespaces="concat")@
L = L or {}
L["Buffs"] = true
L["Debuffs"] = true
L["Display parameters"] = "顯示設置"
L["Elements by line"] = "每行數量"
L["growth_to"] = "增長到"
L["High"] = "高"
L["Icon size"] = "圖示大小"
L["left"] = "左"
L["Left time"] = "剩餘時間"
L["Left time font size"] = "計時字體大小"
L["Low"] = "低"
L["Maximum number of elements to show"] = "可顯示的最大數量"
L["Med"] = "中"
L["None"] = "無延遲"
L["Padding between elements"] = "填充"
L["right"] = "右"
L["Show / Hide anchor"] = "顯示/隱藏 錨點"
L["Show Blizzard Frame"] = "顯示暴雪介面"
L["Stack counter size"] = "層數字體大小"
L["Status bar width"] = "狀態條寬度"
L["Wench"] = "武器附魔"
<file_sep>local L = LibStub("AceLocale-3.0"):NewLocale("fbngBuffFrame","frFR")
if not L then return end
-- // @localization(locale="frFR", format="lua_additive_table", same-key-is-true=true, handle-subnamespaces="concat")@
L = L or {}
L["Buffs"] = true
L["Debuffs"] = "Débuffs"
L["Display parameters"] = "Paramètre d'affichage"
L["Elements by line"] = "Nombre de buffs par ligne"
L["growth_to"] = "grandit vers"
L["High"] = "Haut"
L["Icon size"] = "Taille de l'icone"
L["left"] = "gauche"
L["Left time"] = "Temps restant"
L["Left time font size"] = "Taille du temps restant"
L["Low"] = "Bas"
L["Maximum number of elements to show"] = "Nombre maximal de buffs à afficher"
L["Med"] = "Moyen"
L["None"] = "Aura (buff/debuff) sans délai"
L["Padding between elements"] = "Espacement entre les éléments"
L["right"] = "droite"
L["Show / Hide anchor"] = "Montrer / Cacher l'ancre"
L["Show Blizzard Frame"] = "Afficher l'interface de blizzard"
L["Stack counter size"] = "Taille du compteur de pile"
L["Status bar width"] = "Largeur du sablier"
L["Wench"] = "Enchantements d'armes"
| 7055f6870330568b0bbe25df0698f29a96e6b044 | [
"Lua"
] | 5 | Lua | ithinuel/fbngbuffframe | ae4003b7c86087a5fee612e0365544ecebf9649d | 3312e260ddbf950a02adba4f4b7ac5c4735659e3 |
refs/heads/master | <repo_name>nikitagorshkov2011/FontApp<file_sep>/FontsNikitaGorshkov/FontCollectionViewController.swift
//
// ViewController.swift
// FontsNikitaGorshkov
//
// Created by Admin on 14/07/2018.
// Copyright © 2018 nikitagorshkov. All rights reserved.
//
import UIKit
class FontCollectionViewController: UIViewController {
let collectionData = [UIFont.Weight.black : "black", UIFont.Weight.bold : "bold", UIFont.Weight.heavy : "heavy", UIFont.Weight.light : "light", UIFont.Weight.medium : "medium", UIFont.Weight.regular : "regular", UIFont.Weight.semibold : "semibold", UIFont.Weight.thin : "thin", UIFont.Weight.ultraLight : "ultralight"]
var currentWeight = UIFont.Weight.regular
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBar.isHidden = false
}
}
extension FontCollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width / 2 - 5
let height = collectionView.bounds.height / 4 - 5
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
currentWeight = Array(collectionData.keys)[indexPath.row]
performSegue(withIdentifier: "showDetails", sender: self)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FontCell", for: indexPath)
currentWeight = Array(collectionData.keys)[indexPath.row]
if let label = cell.viewWithTag(100) as? UILabel {
let font = UIFont.systemFont(ofSize: 20, weight: currentWeight)
label.text = font.familyName
label.font = font
label.adjustsFontSizeToFitWidth = true
}
if let label = cell.viewWithTag(101) as? UILabel {
let font = UIFont.systemFont(ofSize: 15, weight: currentWeight)
label.text = collectionData[currentWeight]!
label.font = font
label.adjustsFontSizeToFitWidth = true
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails" {
if let destinationViewController = segue.destination as? FontDetailsViewController {
destinationViewController.fontWeight = currentWeight
destinationViewController.weightName = collectionData[currentWeight]!
}
}
}
}
<file_sep>/FontsNikitaGorshkov/FontDetailsViewController.swift
//
// FontDetailsViewController.swift
// FontsNikitaGorshkov
//
// Created by Admin on 14/07/2018.
// Copyright © 2018 nikitagorshkov. All rights reserved.
//
import UIKit
class FontDetailsViewController: UIViewController {
@IBOutlet weak var FontFamily: UILabel!
@IBOutlet weak var FontWeight: UILabel!
@IBOutlet weak var Example: UILabel!
@IBOutlet weak var Height: UILabel!
var fontWeight = UIFont.Weight.regular
var weightName = "regular"
override func viewDidLoad() {
super.viewDidLoad()
let font = UIFont.systemFont(ofSize: 20, weight: fontWeight)
let heightOfExample = 17
FontFamily.text = font.familyName
FontFamily.font = font
FontWeight.text = weightName
FontWeight.font = font
Example.text = "Example"
Example.font = UIFont.systemFont(ofSize: CGFloat(heightOfExample), weight: fontWeight)
Example.textColor = UIColor.green
Height.text = "\(heightOfExample)pt"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| d5f54f5cb3eced74e9a00b5867ef695e08521744 | [
"Swift"
] | 2 | Swift | nikitagorshkov2011/FontApp | 0c1d29d93e3bba1c1a7918b61831e457b545c312 | 851cc2764d9efb9f81c8d7a629974b53cb7bd5c0 |
refs/heads/day1 | <file_sep>// import React, { Component, Fragment } from 'react';
import React, { useState, Fragment } from 'react';
const PhoneInfo = (props) => {
const style = {
border: '1px solid black',
padding: '8px',
margin: '8px',
};
const [editing, setEditing] = useState(false);
const [name, setName] = useState(props.info.name);
const [phone, setPhone] = useState(props.info.phone);
const handleRemove = () => {
const { info, onRemove } = props;
onRemove(info.id);
};
const handleToggleEdit = () => {
// true => false
//onUpdate
// false -> true
//state에 info값 넣기
const { info, onUpdate } = props;
if (editing) onUpdate(info.id, { name: name, phone: phone });
setEditing(pre => !pre);
// setEditing(!setEditing)
};
return (
<div style={style}>
{
editing ? (
<Fragment>
<div><input
name="name"
onChange={(e) => setName(e.target.value)}
value={name}
/></div>
<div><input
name="phone"
onChange={(e) => setPhone(e.target.value)}
value={phone}
/></div>
</Fragment>
) : (
<Fragment>
<div><b>{name}</b></div>
<div><b>{phone}</b></div>
</Fragment>)
}
<button onClick={handleRemove}>삭제</button>
<button onClick={handleToggleEdit}>
{editing ? '적용' : '수정'}
</button>
</div>
);
}
/*
class PhoneInfo extends Component {
state = {
editing: false,
name: '',
phone: ''
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state !== nextProps) {
return true;
}
return this.props.info !== nextProps.info;
}
handleToggleEdit = () => {
// true => false
//onUpdate
// false -> true
//state에 info값 넣기
const { info, onUpdate } = this.props;
if (this.state.editing) {
onUpdate(info.id, {
name: this.state.name,
phone: this.state.phone
});
} else {
this.setState({
name: info.name,
phone: info.phone,
});
}
this.setState({
editing: !this.state.editing,
});
}
handleRemove = () => {
const { info, onRemove } = this.props;
onRemove(info.id);
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
const { name, phone, id } = this.props.info;
const { editing } = this.state;
const style = {
border: '1px solid black',
padding: '8px',
margin: '8px',
};
return (
<div style={style}>
{
editing ? (
<Fragment>
<div><input
name="name"
onChange={this.handleChange}
value={this.state.name}
/></div>
<div><input
name="phone"
onChange={this.handleChange}
value={this.state.phone}
/></div>
</Fragment>
) : (
<Fragment>
<div><b>{name}</b></div>
<div><b>{phone}</b></div>
</Fragment>)
}
<button onClick={this.handleRemove}>삭제</button>
<button onClick={this.handleToggleEdit}>
{editing ? '적용' : '수정'}
</button>
</div>
);
}
}
*/
// const checkProp = (pre, next) => pre === next;
// const arr = [1,2,3,4];
// const sqr = (v) => v * v;
// arr.map(sqr);
// export default React.memo(PhoneInfo, checkProp);
export default React.memo(PhoneInfo, (pre, next) => pre.info === next.info); | df7d28a47c11ef9c7e15580e8bfe2f8957caf592 | [
"JavaScript"
] | 1 | JavaScript | blowhite/react_prac | 401cf99d541c26085f6b2449b9c313ca81fac02a | f0a9abf081a7ef1c323788e22f9c522615a33c7d |
refs/heads/master | <repo_name>karthik-h-raju/Fabrikam-Web<file_sep>/Fabrikam.Module1.Uc1.Command.v1/Fabrikam.Module1.Uc1.Services.WebApi.v1/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs
namespace Fabrikam.Module1.Uc1.Services.WebApi.v1.Areas.HelpPage.ModelDescriptions
{
public class SimpleTypeModelDescription : ModelDescription
{
}
}<file_sep>/Fabrikam.Module1.Uc1.Query.v1/Fabrikam.Module1.Uc1.Query.Services.WebApi.v1/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
namespace Fabrikam.Module1.Uc1.Query.Services.WebApi.v1.Areas.HelpPage.ModelDescriptions
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
}<file_sep>/README.md
# Fabrikam-Web
Sample VS2015 project to demonstrate AngularJS, WebApi and Versioning; along with CI and ALM features
<file_sep>/Fabrikam.Module1.Uc1.Command.v1/Fabrikam.Module1.Uc1.Services.WebApi.v1/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
namespace Fabrikam.Module1.Uc1.Services.WebApi.v1.Areas.HelpPage.ModelDescriptions
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | 400940510a4986adeacd64bdb78e62189178b43a | [
"Markdown",
"C#"
] | 4 | C# | karthik-h-raju/Fabrikam-Web | 8be3433ff2e0e0b34129566be7192c6d4d54dfb1 | b6be0a066caead2047a3c3366ecb902cd55f34d9 |
refs/heads/master | <file_sep>import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-usd',
templateUrl: './usd.component.html'
})
export class USDComponent {
@Input() yen:number;
@Output() usd = new EventEmitter<number>();
yenDisplayText: number;
constructor() { }
convertToYen() {
this.yenDisplayText = (true === !!arguments[0] && !isNaN(arguments[0]))? arguments[0] * 113 : 0;
this.usd.emit(this.yenDisplayText);
}
getYenDisplayText() {
return 0;
}
}
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Currency Converter';
yenConverted:number;
usdConverted:number;
onYenDisplay(yen:number){
this.yenConverted = yen;
}
onUsdDisplay(usd:number){
this.usdConverted = usd;
}
}
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-yen',
templateUrl: './yen.component.html'
})
export class YenComponent {
@Input() yenConverted:number;
@Output() yenToUsd = new EventEmitter<number>();
usdDisplayText: number;
constructor() { }
convertToUsd() {
this.usdDisplayText = (true === !!arguments[0] && !isNaN(arguments[0]))? arguments[0] * 0.0089 : 0;
this.yenToUsd.emit(this.usdDisplayText);
}
getUsdDisplayText() {
return 0;
}
}
| c6b6bafc511c127202585d46583958d97bccaab9 | [
"TypeScript"
] | 3 | TypeScript | lodela/currency-converter | ef6ab6815bf5eab7d0ef126f1088853b653f7132 | 387852ed2c12b53317cdcad15ee2a5d4a3a3deb8 |
refs/heads/master | <repo_name>nosnhojttam/2DGameEngine<file_sep>/includes/level.h
#ifndef LEVEL
#define LEVEL
#include "gObject.h"
class level
{
public:
level();
level(string name);
void draw();
vector<gObject> objects;
void addObject(gObject object);
private:
string name;
};
#endif
<file_sep>/src/source.cpp
//--------------------------------------------------------------------------------------
// File: Tutorial022.cpp
//
// This application displays a triangle using Direct3D 11
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include <windowsx.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <xnamath.h>
#include "../includes/resource.h"
#include "../includes/simplevertex.h"
#include "../includes/grlLoader.h"
#include "../includes/player.h"
#include "../includes/stopwatchmicro.h"
#include "../includes/controller.h"
#include "../includes/sound.h"
#include "../includes/render_to_texture.h"
#define PI 3.14159265
#define MAX_VEL 1.00
//--------------------------------------------------------------------------------------
// Structures
//--------------------------------------------------------------------------------------
/*struct SimpleVertex
{
XMFLOAT3 Pos;
XMFLOAT2 Tex;
};*/
//---------------------------------------------------------------------------------------------------
// Global Variables
//---------------------------------------------------------------------------------------------------
HINSTANCE g_hInst = NULL;
HWND g_hWnd = NULL;
D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device* g_pd3dDevice = NULL;
ID3D11DeviceContext* g_pImmediateContext = NULL;
IDXGISwapChain* g_pSwapChain = NULL;
ID3D11RenderTargetView* g_pRenderTargetView = NULL;
ID3D11VertexShader* g_pVertexShader = NULL;
ID3D11PixelShader* g_pPixelShader = NULL;
ID3D11VertexShader* g_pAnimateVertexShader = NULL;
ID3D11PixelShader* g_pAnimatePixelShader = NULL;
ID3D11InputLayout* g_pVertexLayout = NULL;
ID3D11Buffer* g_pVertexBuffer = NULL;
ID3D11Buffer* g_pConstantBuffer11 = NULL;
ID3D11BlendState* g_BlendState;
ID3D11SamplerState* g_Sampler = NULL;
ID3D11SamplerState* SamplerScreen = NULL;
ID3D11VertexShader* g_pVertexShader_screen = NULL;
ID3D11PixelShader* g_pPixelShader_screen = NULL;
ID3D11Buffer* g_pVertexBuffer_screen = NULL;
ID3D11ShaderResourceView* g_Texture = NULL;
//ID3D11ShaderResourceView* g_Texture2 = NULL;
ID3D11ShaderResourceView* g_Tex_BG = NULL;
ID3D11ShaderResourceView* g_grassTexture = NULL;
level* first;
vector<ID3D11Buffer*> g_VertexBufferList;
unordered_map<string, texture*>* texMap;
RenderTextureClass* RenderToTexture;
static const int WIDTH = 1280;
static const int HEIGHT = 1280;
float x_impulse;
float y_impulse;
bool isJumping = true;
VS_CONSTANT_BUFFER VsConstData;
player g_player = player();
ID3D11ShaderResourceView* g_playerTexture = NULL;
CXBOXController *gamepad = new CXBOXController(1);
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
void draw_text(HDC DC, char text[], int x, int y, int r, int g, int b);
HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow);
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void Render();
void Update();
void CheckCollisions();
void printStuff();
void Render_To_Texture();
void Render_To_Screen();
void OpenConsole()
{
AllocConsole();
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
OpenConsole();
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
if (FAILED(InitWindow(hInstance, nCmdShow)))
return 0;
if (FAILED(InitDevice()))
{
CleanupDevice();
return 0;
}
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Update();
Render();
}
}
CleanupDevice();
return (int)msg.wParam;
}
//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow)
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"TutorialWindowClass";
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_TUTORIAL1);
if (!RegisterClassEx(&wcex))
return E_FAIL;
// Create window
g_hInst = hInstance;
//RECT rc = { 0, 0, 640, 480 };
RECT rc = { 0, 0, WIDTH, HEIGHT };
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
g_hWnd = CreateWindow(L"TutorialWindowClass", L"EckENGINE :^)",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance,
NULL);
if (!g_hWnd)
return E_FAIL;
ShowWindow(g_hWnd, nCmdShow);
return S_OK;
}
//--------------------------------------------------------------------------------------
// Helper for compiling shaders with D3DX11
//--------------------------------------------------------------------------------------
HRESULT CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
ID3DBlob* pErrorBlob;
hr = D3DX11CompileFromFile(szFileName, NULL, NULL, szEntryPoint, szShaderModel,
dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL);
if (FAILED(hr))
{
if (pErrorBlob != NULL)
OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
if (pErrorBlob) pErrorBlob->Release();
return hr;
}
if (pErrorBlob) pErrorBlob->Release();
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
HRESULT hr = S_OK;
RECT rc;
GetClientRect(g_hWnd, &rc);
UINT width = rc.right - rc.left;
UINT height = rc.bottom - rc.top;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
g_driverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext);
if (SUCCEEDED(hr))
break;
}
if (FAILED(hr))
return hr;
grlLoader loader = grlLoader();
first = loader.loadGRL("C:\\Users\\gamel\\Documents\\Matt\\CAPSTONE\\NEw\\Johnson_HW3\\GameEngineFramework\\grl\\videodemo.grl");
texMap = loader.getTextureMap();
texMap->count("C:\\Users\\gamel\\Documents\\Matt\\CAPSTONE\\NEw\\Johnson_HW3\\images\\platform.png");
// Create a render target view
ID3D11Texture2D* pBackBuffer = NULL;
hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(hr))
return hr;
hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView);
pBackBuffer->Release();
if (FAILED(hr))
return hr;
g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, NULL);
// Setup the viewport
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)width;
vp.Height = (FLOAT)height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
g_pImmediateContext->RSSetViewports(1, &vp);
// Compile the vertex shader
ID3DBlob* pVSBlob = NULL;
hr = CompileShaderFromFile(L"shader.fx", "VS", "vs_4_0", &pVSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the vertex shader
hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader);
if (FAILED(hr))
{
pVSBlob->Release();
return hr;
}
// Compile the vertex shader
pVSBlob = NULL;
hr = CompileShaderFromFile(L"shader.fx", "VS_screen", "vs_4_0", &pVSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the vertex shader
hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader_screen);
if (FAILED(hr))
{
pVSBlob->Release();
return hr;
}
pVSBlob = NULL;
hr = CompileShaderFromFile(L"animate_shader.fx", "VS", "vs_4_0", &pVSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the vertex shader
hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pAnimateVertexShader);
if (FAILED(hr))
{
pVSBlob->Release();
return hr;
}
// Define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE(layout);
// Create the input layout
hr = g_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(),
pVSBlob->GetBufferSize(), &g_pVertexLayout);
pVSBlob->Release();
if (FAILED(hr))
return hr;
// Set the input layout
g_pImmediateContext->IASetInputLayout(g_pVertexLayout);
// Compile the pixel shader
ID3DBlob* pPSBlob = NULL;
hr = CompileShaderFromFile(L"shader.fx", "PS", "ps_4_0", &pPSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the pixel shader
hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader);
pPSBlob->Release();
if (FAILED(hr))
return hr;
// Compile the pixel shader
pPSBlob = NULL;
hr = CompileShaderFromFile(L"shader.fx", "PS_screen", "ps_4_0", &pPSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the pixel shader
hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader_screen);
pPSBlob->Release();
if (FAILED(hr))
return hr;
pPSBlob = NULL;
hr = CompileShaderFromFile(L"animate_shader.fx", "PS", "ps_4_0", &pPSBlob);
if (FAILED(hr))
{
MessageBox(NULL,
L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
return hr;
}
// Create the pixel shader
hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pAnimatePixelShader);
pPSBlob->Release();
if (FAILED(hr))
return hr;
// Create vertex buffer
SimpleVertex vertices[] =
{
{ XMFLOAT3(-1,1,0),XMFLOAT2(0,0)},
{ XMFLOAT3(1,1,0),XMFLOAT2(1,0)},
{ XMFLOAT3(-1,-1,0),XMFLOAT2(0,1)},
{ XMFLOAT3(1,1,0),XMFLOAT2(1,0)},
{ XMFLOAT3(1,-1,0),XMFLOAT2(1,1)},
{ XMFLOAT3(-1,-1,0),XMFLOAT2(0,1)}
};
//initialize d3dx verexbuff:
D3D11_BUFFER_DESC bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(SimpleVertex) * 6;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = vertices;
hr = g_pd3dDevice->CreateBuffer(&bd, &InitData, &g_pVertexBuffer_screen);
if (FAILED(hr))
return FALSE;
ZeroMemory(&bd, sizeof(bd));
// Set vertex buffer
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset);
// Set primitive topology
g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
SimpleVertex* sv;
bd;
ZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DEFAULT;
for (int i = 0; i < first->objects.size(); i++) {
gObject& gO = first->objects[i];
sv = gO.getSV();
bd.ByteWidth = sizeof(SimpleVertex) * gO.getNumVertices();
//bd.ByteWidth = sizeof(SimpleVertex) * 6;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = gO.getSV();
hr = g_pd3dDevice->CreateBuffer(&bd, &InitData, &g_pVertexBuffer);
if (FAILED(hr))
return hr;
g_VertexBufferList.push_back(g_pVertexBuffer);
gO.setVB(g_pVertexBuffer);
// Set vertex buffer
//UINT stride = sizeof(SimpleVertex);
//UINT offset = 0;
//g_pImmediateContext->IASetVertexBuffers(0, 1, &g_VertexBufferList[i], &stride, &offset);
}
bd.ByteWidth = sizeof(SimpleVertex) * g_player.getNumVertices();
//bd.ByteWidth = sizeof(SimpleVertex) * 6;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = g_player.getSV();
//InitData.pSysMem = vertices;
hr = g_pd3dDevice->CreateBuffer(&bd, &InitData, &g_pVertexBuffer);
if (FAILED(hr))
return hr;
//g_VertexBufferList.push_back(g_pVertexBuffer);
g_player.setVB(g_pVertexBuffer);
// Set primitive topology
g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Supply the vertex shader constant data.
VsConstData.WorldMatrix.x = 0;
VsConstData.WorldMatrix.y = 0;
VsConstData.WorldMatrix.z = 1;
VsConstData.WorldMatrix.w = 1;
// Fill in a buffer description.
D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.ByteWidth = sizeof(VS_CONSTANT_BUFFER);
cbDesc.Usage = D3D11_USAGE_DEFAULT;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = 0;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;
// Create the buffer.
hr = g_pd3dDevice->CreateBuffer(&cbDesc, NULL, &g_pConstantBuffer11);
if (FAILED(hr))
return hr;
for (int i = 0; i < first->objects.size(); i++) {
gObject &obj = first->objects[i];
string textureURL = obj.getTexture().getURL();
std::wstring widestr = std::wstring(textureURL.begin(), textureURL.end());
const wchar_t* szName = widestr.c_str();
ID3D11ShaderResourceView* srv = NULL;
hr = D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, szName, NULL, NULL, &srv, NULL);
if (FAILED(hr))
return hr;
obj.getTexture().setSRV(srv);
}
/*
gObject &bg = first->objects[0];
string textureURL = bg.getTexture().getURL();
std::wstring widestr = std::wstring(textureURL.begin(), textureURL.end());
const wchar_t* szName = widestr.c_str();
hr = D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, szName, NULL, NULL, &g_Texture, NULL);
if (FAILED(hr))
return hr;
bg.getTexture().setSRV(g_Texture);
*/
//Player stuff
/*********************/
hr = D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"images\\guy.png", NULL, NULL, &g_playerTexture, NULL);
if (FAILED(hr))
return hr;
g_player.getTexture().setSRV(g_playerTexture);
/*********************/
/*
gObject &grass = first->objects[1];
textureURL = grass.getTexture().getURL();
widestr = std::wstring(textureURL.begin(), textureURL.end());
szName = widestr.c_str();
if (FAILED(hr))
return hr;
hr = D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, szName, NULL, NULL, &g_grassTexture, NULL);
if (FAILED(hr))
return hr;
grass.getTexture().setSRV(g_grassTexture);
gObject& grass2 = first->objects[2];
grass2.getTexture().setSRV(g_grassTexture);
*/
// Create the sample state
D3D11_SAMPLER_DESC sampDesc;
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_ANISOTROPIC;
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
//sampDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_pd3dDevice->CreateSamplerState(&sampDesc, &g_Sampler);
if (FAILED(hr))
return hr;
// Create the screen sample state
ZeroMemory(&sampDesc, sizeof(sampDesc));
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc.MinLOD = 0;
sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_pd3dDevice->CreateSamplerState(&sampDesc, &SamplerScreen);
if (FAILED(hr))
return hr;
//blendstate:
D3D11_BLEND_DESC blendStateDesc;
ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));
blendStateDesc.AlphaToCoverageEnable = FALSE;
blendStateDesc.IndependentBlendEnable = FALSE;
blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F;
g_pd3dDevice->CreateBlendState(&blendStateDesc, &g_BlendState);
RenderToTexture = new RenderTextureClass;
RenderToTexture->Initialize(g_pd3dDevice, g_hWnd, -1, -1, FALSE, DXGI_FORMAT_R8G8B8A8_UNORM, TRUE);
float blendFactor[] = { 0, 0, 0, 0 };
UINT sampleMask = 0xffffffff;
g_pImmediateContext->OMSetBlendState(g_BlendState, blendFactor, sampleMask);
return S_OK;
}
//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
if (g_pImmediateContext) g_pImmediateContext->ClearState();
if (g_pVertexLayout) g_pVertexLayout->Release();
if (g_pVertexShader) g_pVertexShader->Release();
if (g_pPixelShader) g_pPixelShader->Release();
if (g_pRenderTargetView) g_pRenderTargetView->Release();
if (g_pSwapChain) g_pSwapChain->Release();
if (g_pImmediateContext) g_pImmediateContext->Release();
if (g_pd3dDevice) g_pd3dDevice->Release();
for (int i = 0; i < g_VertexBufferList.size(); i++) {
if (g_VertexBufferList[i])
g_VertexBufferList[i]->Release();
}
FreeConsole();
}
///////////////////////////////////
// This Function is called every time the Left Mouse Button is down
///////////////////////////////////
void OnLBD(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags)
{
}
///////////////////////////////////
// This Function is called every time the Right Mouse Button is down
///////////////////////////////////
void OnRBD(HWND hwnd, BOOL fDoubleClick, int x, int y, UINT keyFlags)
{
}
///////////////////////////////////
// This Function is called every time a character key is pressed
///////////////////////////////////
void OnChar(HWND hwnd, UINT ch, int cRepeat)
{
}
///////////////////////////////////
// This Function is called every time the Left Mouse Button is up
///////////////////////////////////
void OnLBU(HWND hwnd, int x, int y, UINT keyFlags)
{
}
///////////////////////////////////
// This Function is called every time the Right Mouse Button is up
///////////////////////////////////
void OnRBU(HWND hwnd, int x, int y, UINT keyFlags)
{
}
///////////////////////////////////
// This Function is called every time the Mouse Moves
///////////////////////////////////
void OnMM(HWND hwnd, int x, int y, UINT keyFlags)
{
if ((keyFlags & MK_LBUTTON) == MK_LBUTTON)
{
}
if ((keyFlags & MK_RBUTTON) == MK_RBUTTON)
{
}
}
BOOL OnCreate(HWND hwnd, CREATESTRUCT FAR* lpCreateStruct)
{
return TRUE;
}
void OnTimer(HWND hwnd, UINT id)
{
}
bool canJump = true;
bool canMove = true;
bool a_press = 0;
bool d_press = 0;
bool space_press = 0;
bool left_ = 0;
bool right_ = 0;
bool w_press = 0;
bool s_press = 0;
bool up_press = 0;
bool down_press = 0;
bool moving = 1;
//*************************************************************************
void OnKeyUp(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags)
{
switch (vk)
{
case 87: //w
w_press = 0;
break;
case 65: //a
a_press = 0;
break;
case 83: //s
s_press = 0;
break;
case 68: //d
d_press = 0;
break;
case 32: //space
space_press = 0;
break;
case 37:
left_ = 0;
break;
case 39:
right_ = 0;
break;
case 38: //up
up_press = 0;
break;
case 40: //down
down_press = 0;
break;
default:break;
}
}
void OnKeyDown(HWND hwnd, UINT vk, BOOL fDown, int cRepeat, UINT flags)
{
switch (vk)
{
case 27:
PostQuitMessage(0);
break;
case 87: //w
w_press = 1;
break;
case 65: //a
a_press = 1;
break;
case 83: //s
s_press = 1;
break;
case 68: //d
d_press = 1;
break;
case 32: //space
space_press = 1;
break;
case 38: //up
up_press = 1;
break;
case 37:
left_ = 1;
moving = 0;
break;
case 39:
right_ = 1;
moving = 1;
break;
case 40: //down
down_press = 1;
break;
case 80: //p
printStuff();
break;
case 90: //z
start_music(L"sound\\giveyouup.mp3");
break;
default:break;
}
}
//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
SCROLLINFO si;
switch (message)
{
/*
#define HANDLE_MSG(hwnd, message, fn) \
case (message): return HANDLE_##message((hwnd), (wParam), (lParam), (fn))
*/
//HANDLE_MSG(hwnd, WM_CHAR, OnChar);
HANDLE_MSG(hwnd, WM_LBUTTONDOWN, OnLBD);
HANDLE_MSG(hwnd, WM_LBUTTONUP, OnLBU);
HANDLE_MSG(hwnd, WM_MOUSEMOVE, OnMM);
HANDLE_MSG(hwnd, WM_CREATE, OnCreate);
HANDLE_MSG(hwnd, WM_TIMER, OnTimer);
HANDLE_MSG(hwnd, WM_KEYDOWN, OnKeyDown);
HANDLE_MSG(hwnd, WM_KEYUP, OnKeyUp);
case WM_ERASEBKGND:
return (LRESULT)1;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
void Update()
{
x_impulse = 0.0f;
if (isJumping) {
y_impulse -= 0.0001f;
}
else {
if (y_impulse > -MAX_VEL)
y_impulse -= 0.0001f;
else
y_impulse = -MAX_VEL;
}
//--------------------------------------------------------------------------------------
// ***** CONTROLLER STUFF ***** //
//--------------------------------------------------------------------------------------
if (gamepad->IsConnected())
{
if (gamepad->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_Y) {}
if (gamepad->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A)
{
space_press = true;
}
else {
space_press = false;
}
//cam.s = 0;
}
SHORT lx = gamepad->GetState().Gamepad.sThumbLX;
SHORT ly = gamepad->GetState().Gamepad.sThumbLY;
if (abs(ly) > 3000)
{
float angle_x = (float)ly / 32000.0;
angle_x *= 0.05;
//y_impulse += angle_x;
}
if (abs(lx) > 3000)
{
float angle_y = (float)lx / 32000.0;
angle_y *= 0.01;
x_impulse += angle_y;
}
//--------------------------------------------------------------------------------------
// ***** PLAYER MOVEMENT ***** //
//--------------------------------------------------------------------------------------
//Jumping
if (space_press && !isJumping) {
y_impulse = 0.1;
isJumping = true;
}
//Left and right controls with a & d
if (a_press && d_press)
{
x_impulse = 0;
g_player.changeState(animation::IDLE);
}
else if (a_press)
{
x_impulse = -0.05;
g_player.changeState(animation::WALK,animation::LEFT);
}
else if (d_press)
{
x_impulse = 0.05;
g_player.changeState(animation::WALK,animation::RIGHT);
}
else if (a_press || d_press)
{
x_impulse = 0;
}
else
{
g_player.changeState(animation::IDLE);
}
//Left and right controls with left arrow & and right arrow
if (left_ && right_) x_impulse = 0;
else if (left_) x_impulse = -0.01;
else if (right_) x_impulse = 0.01;
else if (left_ || right_) x_impulse = 0;
SimpleVertex* sv = g_player.getSV();
float scrollX = WIDTH / 2 - 10 / 2 - sv[0].Pos.x;
float scrollY = HEIGHT / 2 - 10 / 2 - sv[0].Pos.y;
//g_player.translate(x_impulse, y_impulse, 0, 0);
XMFLOAT4* xPos = new XMFLOAT4(-x_impulse, 0, 0, 0);
//g_player.getCol()->translate(pos);
// x translation
for (int i = 0; i < first->objects.size(); i++) {
gObject &gO = first->objects[i];
gO.translate(-x_impulse, 0, 0, 0);
if (gO.getCol() != NULL) {
gO.getCol()->translate(xPos);
//cout << gO.getCol()->getPos()->x << " " << gO.getCol()->getPos()->y << " " << gO.getCol()->getPos()->z << endl;
//cout << g_player.getCol()->getPos()->x << " " << g_player.getCol()->getPos()->y << " " << g_player.getCol()->getPos()->z << endl;
//g_player.getCol()->translate(xPos);
}
}
// check for player collisions
//cout << y_impulse << endl;
for (int j = 0; j < first->objects.size(); j++) {
if (first->objects[j].getCol() != NULL && g_player.getCol()->collision(first->objects[j].getCol())) {
//g_player.translate(-x_impulse, -y_impulse, 0, 0);
//g_player.getCol()->translate(new XMFLOAT4(-x_impulse, -y_impulse, 0, 0));
//move all objects in the world
for (int i = 0; i < first->objects.size(); i++) {
gObject &gO = first->objects[i];
gO.translate(x_impulse, 0, 0, 0);
xPos->x = x_impulse;
if (gO.getCol() != NULL) {
gO.getCol()->translate(xPos);
//g_player.getCol()->translate(xPos);
}
}
}
}
XMFLOAT4* yPos = new XMFLOAT4(0, -y_impulse, 0, 0);
// y translation
for (int i = 0; i < first->objects.size(); i++) {
gObject &gO = first->objects[i];
gO.translate(0, -y_impulse, 0, 0);
if (gO.getCol() != NULL) {
gO.getCol()->translate(yPos);
//g_player.getCol()->translate(yPos);
}
}
// check for player collisions
//cout << y_impulse << endl;
for (int j = 0; j < first->objects.size(); j++) {
if (first->objects[j].getCol() != NULL && g_player.getCol()->collision(first->objects[j].getCol())) {
isJumping = false;
//g_player.translate(-x_impulse, -y_impulse, 0, 0);
//g_player.getCol()->translate(new XMFLOAT4(-x_impulse, -y_impulse, 0, 0));
//move all objects in the world
for (int i = 0; i < first->objects.size(); i++) {
gObject &gO = first->objects[i];
gO.translate(0, y_impulse, 0, 0);
yPos->y = y_impulse;
if (gO.getCol() != NULL) {
gO.getCol()->translate(yPos);
//g_player.getCol()->translate(yPos);
}
}
y_impulse = 0.0f;
}
}
}
void Render_To_Texture(long elapsed) {
float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red,green,blue,alpha
float scale_factor = 1.0;
ID3D11RenderTargetView* RenderTarget;
RenderTarget = RenderToTexture->GetRenderTarget();
g_pImmediateContext->ClearRenderTargetView(RenderTarget, ClearColor);
g_pImmediateContext->OMSetRenderTargets(1, &RenderTarget, NULL);
//for all non-animated rectangles:
//g_pImmediateContext->PSSetSamplers(0, 1, &g_Sampler);
g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0);
g_pImmediateContext->PSSetShader(g_pPixelShader, NULL, 0);
scale_factor = 0.01;
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
for (int i = 0; i < first->objects.size(); i++) {
gObject &gO = first->objects[i];
gO.draw(g_pImmediateContext, g_pConstantBuffer11, elapsed, g_Sampler);
}
//for animated objects:
//g_pImmediateContext->PSSetSamplers(0, 1, &g_Sampler);
g_pImmediateContext->VSSetShader(g_pAnimateVertexShader, NULL, 0);
g_pImmediateContext->PSSetShader(g_pAnimatePixelShader, NULL, 0);
g_player.draw(g_pImmediateContext, g_pConstantBuffer11, elapsed, g_Sampler);
// Present the information rendered to the back buffer to the front buffer (the screen)
g_pSwapChain->Present(0, 0);
}
void Render_To_Screen() {
g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, NULL);
// Clear the back buffer
float ClearColor2[4] = { 0.0f, 1.0f, 0.0f, 1.0f }; // red, green, blue, alpha
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, ClearColor2);
// Clear the depth buffer to 1.0 (max depth)
VS_CONSTANT_BUFFER constantbuffer;
constantbuffer.WorldMatrix = XMFLOAT4(0,0,0,0);
g_pImmediateContext->UpdateSubresource(g_pConstantBuffer11, 0, NULL, &constantbuffer, 0, 0);
// Render screen
g_pImmediateContext->VSSetShader(g_pVertexShader_screen, NULL, 0);
g_pImmediateContext->PSSetShader(g_pPixelShader_screen, NULL, 0);
g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer11);
g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pConstantBuffer11);
ID3D11ShaderResourceView* texture = RenderToTexture->GetShaderResourceView();// THE MAGIC
//texture = g_pTextureRV;
g_pImmediateContext->GenerateMips(texture);
g_pImmediateContext->PSSetShaderResources(0, 1, &texture);
g_pImmediateContext->VSSetShaderResources(0, 1, &texture);
g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer_screen, &stride, &offset);
g_pImmediateContext->PSSetSamplers(0, 1, &g_Sampler);
g_pImmediateContext->VSSetSamplers(0, 1, &g_Sampler);
g_pImmediateContext->Draw(6, 0);
g_pSwapChain->Present(0, 0);
}
//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
static StopWatchMicro_ stopwatch;
long elapsed = stopwatch.elapse_micro();
//stopwatch.start();//restart
Render_To_Texture(elapsed);
Render_To_Screen();
g_pSwapChain->Present(0, 0);
}
/*
void CheckCollisions()
{
for (int i = 0; i < first->objects.size(); i++)
{
gObject &gO = first->objects[i];
if (gO.nearOrigin(WIDTH,HEIGHT))
{
if (g_player.collidesWith(&gO))
{
}
}
}
}
*/
void printStuff() {
collider* otherCol = first->objects[1].getCol();
collider* playerCol = g_player.getCol();
SimpleVertex* otherVerts = otherCol->getSV();
SimpleVertex point0 = otherVerts[0];
XMFLOAT3 p0 = point0.Pos;
SimpleVertex point1 = otherVerts[1];
XMFLOAT3 p1 = point1.Pos;
SimpleVertex point2 = otherVerts[2];
XMFLOAT3 p2 = point2.Pos;
SimpleVertex* playerPos = playerCol->getSV();
SimpleVertex playerTL = playerPos[0];
XMFLOAT3 v = playerTL.Pos;
cout << "p0 x: " << p0.x << " y: " << p0.y << endl;
cout << "p1 x: " << p1.x << " y: " << p1.y << endl;
cout << "p2 x: " << p2.x << " y: " << p2.y << endl;
cout << "player top left x: " << v.x << " y: " << v.y << endl;
if (g_player.getCol()->collision(first->objects[1].getCol())) {
cout << "suh dude" << endl;
}
else
cout << "nah dude" << endl;
}<file_sep>/includes/grlLoader.h
#ifndef GRLLOADER
#define GRLLOADER
#include "level.h"
#include "../pugixml\pugixml.hpp"
#include <unordered_map>
using namespace std;
class grlLoader
{
public:
grlLoader();
level* loadGRL(string filename);
unordered_map<string, texture*>* getTextureMap();
private:
string getTagInner(string tag, string xml);
vector<string> getChildrenWithTag(string tag, string xml);
unordered_map<string, texture*>* textureMap;
};
#endif<file_sep>/src/texture.cpp
#include "../includes/texture.h"
texture::texture()
{
}
texture::texture(string name, string url)
{
this->name = name;
this->url = url;
}
string texture::getURL()
{
return url;
}
string texture::getName()
{
return name;
}
void texture::setSRV(ID3D11ShaderResourceView* srv) {
this->srv = srv;
}
ID3D11ShaderResourceView* texture::getSRV() {
return srv;
}
<file_sep>/README.md
# Capstone
###<NAME>, <NAME> here
To Do (Ordered):
- Collisions with movement
- Separate X movement from Y movement
- Implement better gravity
- Implement Jumping
- Max Falling Velocity
- Adding/Subtracting to Impulse
- Create other moving objects
- Create Enemies
To Do (Whenever):
- Fix Animations
- Moving vs Stopped
- Left vs Right facing
- Jumping/Falling (Once Jumping is done)
- Level Switching<file_sep>/includes/collider.h
#ifndef COLLIDER
#define COLLIDER
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iomanip>
#include <d3d11.h>
#include <d3dx11.h>
#include "simplevertex.h"
using namespace std;
class collider
{
public:
collider();
collider(SimpleVertex* vertices, XMFLOAT4* pos, int numVertices);
XMFLOAT4* getPos();
SimpleVertex* getSV();
void translate(XMFLOAT4* newPos);
int getNumVertices();
bool collision(collider* c);
private:
XMFLOAT4* pos;
SimpleVertex* vertices;
int numVertices;
};
#endif<file_sep>/includes/gObject.h
#pragma once
#ifndef GOBJECT
#define GOBJECT
#include "texture.h"
#include "simplevertex.h"
#include "constantbuffer.h"
#include "collider.h"
#include "animation.h"
#include <vector>
class gObject
{
public:
gObject();
gObject(texture* tex, string tag, SimpleVertex* vertices, int numVertices);
void draw(ID3D11DeviceContext* g_pImmediateContext, ID3D11Buffer* constant_buffer, long elapsed, ID3D11SamplerState* sampler);
string getTag();
SimpleVertex* getSV();
int getNumVertices();
texture& getTexture();
void setVB(ID3D11Buffer* vertexBuffer);
void setScrollSpeed();
bool nearOrigin(int width, int height);
virtual void translate(float x, float y, float z, float w);
bool collidesWith(gObject* obj);
collider* getCol();
void setCol(collider* col);
XMFLOAT4 getPos();
void changeState(animation::State state, animation::Direction direction);
void changeState(animation::State state);
protected:
float scroll_speed;
ID3D11Buffer* vertexBuffer;
int numVertices;
SimpleVertex* vertices;
texture tex;
string tag;
collider* col;
XMFLOAT4 position;
float scale_factor;
animation anim;
float diff;
private:
};
class MovingObject : public gObject {
public:
void translate(float x, float y, float z, float w);
};
class StationaryObject : public gObject {
};
#endif
<file_sep>/src/gObject.cpp
#include "../includes/gObject.h"
/* --------------------------------------------*/
/* ----------------Game Object---------------- */
/* --------------------------------------------*/
gObject::gObject()
{
this->position = XMFLOAT4(0, 0, 0, 0);
}
gObject::gObject(texture* tex, string tag, SimpleVertex* vertices, int numVertices)
{
this->tex = *tex;
this->tag = tag;
this->vertices = vertices;
this->numVertices = numVertices;
this->position = XMFLOAT4(0, 0, 0, 0);
scale_factor = .005;
diff = 0.0f;
/*
size_t tag_index = tag.find("collider");
//this->col = collider(vertices, numVertices);
if (tag.find("collider") != std::string::npos)
this->col = new collider(vertices, new XMFLOAT4(0, 0, 0, 0), numVertices);
else
*/
this->col = NULL;
}
void gObject::draw(ID3D11DeviceContext* g_pImmediateContext, ID3D11Buffer* constant_buffer, long elapsed, ID3D11SamplerState* sampler)
{
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
VS_CONSTANT_BUFFER VsConstData;
VsConstData.WorldMatrix.x = position.x;
VsConstData.WorldMatrix.y = position.y;
VsConstData.WorldMatrix.z = position.z;
VsConstData.WorldMatrix.w = scale_factor;
VsConstData.ViewMatrix.x = 0;
VsConstData.ViewMatrix.y = 0;
VsConstData.ViewMatrix.z = 0;
VsConstData.ViewMatrix.w = 0;
/*
if (getTag() == "The Player")
{
VsConstData.info.x = elapsed/100000;
VsConstData.info.y = currentDirection;
}
*/
if (getTag() == "The Player")
{
VsConstData.info.x = anim.getX(elapsed);
VsConstData.info.y = anim.getY(elapsed);
}
//if (getTag() == "BG") {
// scale_factor = .006;
//}
ID3D11ShaderResourceView* srv = getTexture().getSRV();
g_pImmediateContext->PSSetSamplers(0, 1, &sampler);
g_pImmediateContext->UpdateSubresource(constant_buffer, 0, 0, &VsConstData, 0, 0);
g_pImmediateContext->VSSetConstantBuffers(0, 1, &constant_buffer);
g_pImmediateContext->PSSetConstantBuffers(0, 1, &constant_buffer);
g_pImmediateContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
g_pImmediateContext->PSSetShaderResources(0, 1, &srv);
g_pImmediateContext->Draw(getNumVertices(), 0);
}
void gObject::changeState(animation::State state, animation::Direction direction)
{
anim.setState(state);
anim.setDirection(direction);
}
void gObject::changeState(animation::State state)
{
anim.setState(state);
}
void gObject::setVB(ID3D11Buffer* vertexBuffer)
{
this->vertexBuffer = vertexBuffer;
}
string gObject::getTag()
{
return this->tag;
}
SimpleVertex* gObject::getSV()
{
return vertices;
}
int gObject::getNumVertices()
{
return numVertices;
}
XMFLOAT4 gObject::getPos()
{
return position;
}
texture& gObject::getTexture()
{
return tex;
}
bool gObject::nearOrigin(int width, int height)
{
if (col != NULL)
{
if ((abs(position.x) < (width / 2)) && (abs(position.y) < (height / 2)))
{
return true;
}
}
return false;
}
bool gObject::collidesWith(gObject* obj)
{
if (obj->col != NULL && this->col->collision(obj->col))
{
return true;
}
return false;
}
void gObject::setScrollSpeed()
{
float avg = 0;
for (int i = 0; i < numVertices; i++)
{
avg += vertices[i].Pos.z;
}
avg /= numVertices;
scroll_speed = avg;
}
collider* gObject::getCol() {
return col;
}
void gObject::setCol(collider* col) {
this->col = col;
}
void gObject::translate(float x, float y, float z, float w)
{
// change collider
this->position.x += x;
this->position.y += y;
this->position.z += z;
this->position.w += w;
// change vertices
for (int i = 0; i < numVertices; i++) {
vertices[i].Pos.x += x;
vertices[i].Pos.y += y;
vertices[i].Pos.z += z;
if (getCol() != NULL) {
}
}
}
/* --------------------------------------------*/
/* ---------------Moving Object--------------- */
/* --------------------------------------------*/
void MovingObject::translate(float x, float y, float z, float w)
{
// change collider
this->position.x += x;
this->position.y += y;
this->position.z += z;
this->position.w += w;
// change vertices
for (int i = 0; i < numVertices; i++) {
vertices[i].Pos.x += x;
vertices[i].Pos.y += y;
vertices[i].Pos.z += z;
}
}
/* --------------------------------------------*/
/* -------------Stationary Object------------- */
/* --------------------------------------------*/
<file_sep>/includes/constantbuffer.h
#pragma once
#ifndef CONSTANT_BUFFER
#define CONSTANT_BUFFER
struct VS_CONSTANT_BUFFER
{
XMFLOAT4 WorldMatrix;
XMFLOAT4 ViewMatrix;
XMFLOAT4 info;
XMFLOAT4 animation;
};
#endif
<file_sep>/includes/player.h
#pragma once
#ifndef PLAYER
#define PLAYER
#include "gObject.h"
class player : public MovingObject
{
public:
player();
};
#endif
<file_sep>/includes/animation.h
#pragma once
#include <iostream>
using namespace std;
class animation
{
public:
animation();
const enum Direction {DOWN,LEFT,RIGHT,UP};
const enum State { WALK,IDLE };
void setState(State state);
void setDirection(Direction direction);
float getX(long elapsed);
float getY(long elapsed);
private:
State currentState;
Direction currentDirection;
int stateCount = 4;
};
<file_sep>/src/player.cpp
#include "../includes/player.h"
player::player()
{
this->numVertices = 6;
vertices = new SimpleVertex[numVertices];
/*vertices[0] = { XMFLOAT3(-5.0f, 0.0f, 15.0f), XMFLOAT2(0.0f, 0.0f) };
vertices[1] = { XMFLOAT3(5.0f, 0.0f, 5.0f), XMFLOAT2(1.0f, 0.0f) };
vertices[2] = { XMFLOAT3(5.0f, -10.0f, 5.0f), XMFLOAT2(1.0f, 1.0f) };
vertices[3] = { XMFLOAT3(-5.0f, 0.0f, 5.0f), XMFLOAT2(0.0f, 0.0f) };
vertices[4] = { XMFLOAT3(5.0f, -10.0f, 5.0f), XMFLOAT2(1.0f, 1.0f) };
vertices[5] = { XMFLOAT3(-5.0f, -10.0f, 5.0f), XMFLOAT2(0.0f, 1.0f) };*/
vertices[0] = { XMFLOAT3(-10.0f, -65.0f, 15.0f), XMFLOAT2(0.0f, 0.0f) };
vertices[1] = { XMFLOAT3(10.0f, -65.0f, 5.0f), XMFLOAT2(1.0f, 0.0f) };
vertices[2] = { XMFLOAT3(10.0f, -85.0f, 5.0f), XMFLOAT2(1.0f, 1.0f) };
vertices[3] = { XMFLOAT3(-10.0f, -65.0f, 5.0f), XMFLOAT2(0.0f, 0.0f) };
vertices[4] = { XMFLOAT3(10.0f, -85.0f, 5.0f), XMFLOAT2(1.0f, 1.0f) };
vertices[5] = { XMFLOAT3(-10.0f, -85.0f, 5.0f), XMFLOAT2(0.0f, 1.0f) };
this->position = XMFLOAT4(0,0,0,0);
this->col = new collider(this->vertices, new XMFLOAT4(0, 0, 0, 0), numVertices);
scale_factor =.005;
this->tex = texture();
this->anim = animation();
this->tag = "The Player";
}
<file_sep>/includes/texture.h
#ifndef TEXTURE
#define TEXTURE
#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iomanip>
#include <d3d11.h>
#include <d3dx11.h>
using namespace std;
class texture
{
public:
texture();
texture(string name, string url);
string name;
string getURL();
string getName();
void setSRV(ID3D11ShaderResourceView* srv);
ID3D11ShaderResourceView* getSRV();
protected:
string url;
ID3D11ShaderResourceView* srv;
};
#endif
<file_sep>/includes/stopwatchmicro.h
#pragma once
#include <time.h>
#include "resource.h"
#include "texture.h"
class StopWatchMicro_
{
private:
LARGE_INTEGER last, frequency;
public:
StopWatchMicro_()
{
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&last);
}
long double elapse_micro()
{
LARGE_INTEGER now, dif;
QueryPerformanceCounter(&now);
dif.QuadPart = now.QuadPart - last.QuadPart;
long double fdiff = (long double)dif.QuadPart;
fdiff /= (long double)frequency.QuadPart;
return fdiff*1000000.;
}
long double elapse_milli()
{
return elapse_micro() / 1000.;
}
void start()
{
QueryPerformanceCounter(&last);
}
};<file_sep>/src/animation.cpp
#include "../includes/animation.h"
animation::animation()
{
}
void animation::setState(State state)
{
currentState = state;
}
void animation::setDirection(Direction direction)
{
currentDirection = direction;
}
float animation::getX(long elapsed)
{
if (currentState == IDLE)
return 0;
else
return (elapsed / 100000) % stateCount;
}
float animation::getY(long elapsed)
{
return (float)currentDirection;
}<file_sep>/src/level.cpp
#include "../includes/level.h"
level::level()
{
}
level::level(string name)
{
this->name = name;
}
void level::draw()
{
}
void level::addObject(gObject object)
{
if (object.getTag() == "bg"){
objects.insert(objects.begin(), object);
}
else {
objects.push_back(object);
}
}<file_sep>/src/grlLoader.cpp
// grlLoader.cpp : Defines the entry point for the console application.
//
#include "../includes/grlLoader.h"
grlLoader::grlLoader()
{
}
level* grlLoader::loadGRL(string file)
{
pugi::xml_document doc;
pugi::xml_parse_result parsed_grl = doc.load_file(file.c_str());
cout << "file: " << file.c_str() << endl;
level* l = new level(file);
textureMap = new unordered_map<string, texture*>;
for (pugi::xml_node object : doc.child("objects").children("object"))
{
if (object.child("texture") != NULL)
{
string objectName, tex, numVertices, vertices;
objectName = object.child("name").text().as_string();
tex = object.child("texture").text().as_string();
numVertices = object.child("numVertices").text().as_string();
vertices = object.child("vertices").text().as_string();
int numV = stoi(numVertices);
stringstream ss(numV);
float holdVertices[5];
size_t index = 0;
size_t oldIndex = 0;
size_t Ndex = 0;
int count = 0;
int vertCount = 0;
texture* t;
SimpleVertex* sv = new SimpleVertex[numV];
while ((index != string::npos))
{
index = vertices.find(" ", oldIndex + 1);
Ndex = vertices.find("\n", oldIndex + 1);
if (index < Ndex) {
string value = vertices.substr(oldIndex, (index - oldIndex));
oldIndex = index;
double f = stod(value);
if (f < .01 && f > -.01) {
f = 0;
}
holdVertices[count] = (float)f;
count++;
}
else {
string value = vertices.substr(oldIndex, (Ndex - oldIndex));
oldIndex = Ndex;
double f = stod(value);
if (f < .01 && f > -.01) {
f = 0;
}
holdVertices[4] = (float)f;
XMFLOAT3 pos(holdVertices[0], holdVertices[1], holdVertices[2]);
XMFLOAT2 tex(holdVertices[3], holdVertices[4]);
//sv->Pos = pos;
//sv->Tex = tex;
//vertex.push_back(sv);
sv[vertCount].Pos = pos;
sv[vertCount].Tex = tex;
vertCount++;
count = 0;
}
oldIndex++;
if (vertCount > numV) {
break;
}
}
if (textureMap->count(tex) == 0) {
t = new texture(objectName, tex);
textureMap->emplace(tex, t);
}
else {
//unordered_map<string, texture*>::const_iterator i = texMap.find(tex);
t = textureMap->at(tex);
}
l->addObject(gObject(t, objectName, sv, numV));
}
else
{
string objectName, tex, numVertices, vertices;
objectName = object.child("name").text().as_string();
numVertices = object.child("numVertices").text().as_string();
vertices = object.child("vertices").text().as_string();
int numV = stoi(numVertices);
stringstream ss(numV);
float holdVertices[5];
size_t index = 0;
size_t oldIndex = 0;
size_t Ndex = 0;
int count = 0;
int vertCount = 0;
texture* t;
SimpleVertex* sv = new SimpleVertex[numV];
while ((index != string::npos))
{
index = vertices.find(" ", oldIndex + 1);
Ndex = vertices.find("\n", oldIndex + 1);
if (index < Ndex) {
string value = vertices.substr(oldIndex, (index - oldIndex));
oldIndex = index;
double f = stod(value);
if (f < .01 && f > -.01) {
f = 0;
}
if (count < 3) {
int x = f;
f = (double)x;
}
holdVertices[count] = (float)f;
count++;
}
else {
string value = vertices.substr(oldIndex, (Ndex - oldIndex));
oldIndex = Ndex;
double f = stod(value);
if (f < .01 && f > -.01) {
f = 0;
}
holdVertices[4] = (float)f;
XMFLOAT3 pos(holdVertices[0], holdVertices[1], holdVertices[2]);
XMFLOAT2 tex(holdVertices[3], holdVertices[4]);
//sv->Pos = pos;
//sv->Tex = tex;
//vertex.push_back(sv);
sv[vertCount].Pos = pos;
sv[vertCount].Tex = tex;
vertCount++;
count = 0;
}
oldIndex++;
if (vertCount > numV) {
break;
}
}
collider* c = new collider(sv, new XMFLOAT4(0, 0, 0, 0), numV);
for (int i = 0; i < l->objects.size(); i++) {
size_t tag_index = objectName.find("_collider");
string colliderName = objectName.substr(0, tag_index);
//this->col = collider(vertices, numVertices);
if (l->objects[i].getTag().find(colliderName) != std::string::npos)
l->objects[i].setCol(c);
}
//l->addObject(gObject(t, objectName, sv, numV));
}
}
return l;
}
string grlLoader::getTagInner(string tag, string xml)
{
string open = "<" + tag + ">";
string close = "</" + tag + ">";
unsigned openIndex = xml.find(open) + open.length();
unsigned closeIndex = xml.find(close) - openIndex;
//cout << xml;
if (xml.length() > 0)
return xml.substr(openIndex, closeIndex);
else
return "";
}
vector<string> grlLoader::getChildrenWithTag(string tag, string xml)
{
vector<string> sets = vector<string>();
string open = "<" + tag + ">";
string close = "</" + tag + ">";
unsigned openIndex = xml.find(open);
unsigned closeIndex = xml.find(close);
while (openIndex != string::npos && closeIndex != string::npos)
{
string child = xml.substr(openIndex, closeIndex + close.length());
sets.push_back(child);
xml = xml.substr(closeIndex + close.length());
openIndex = xml.find(open) + open.length();
closeIndex = xml.find(close);
}
return sets;
}
unordered_map<string, texture*>* grlLoader::getTextureMap() {
return textureMap;
}<file_sep>/includes/simplevertex.h
#ifndef SIMPLE_VERTEX
#define SIMPLE_VERTEX
#include <windows.h>
#include <windowsx.h>
#include <xnamath.h>
#include <d3d11.h>
#include <d3dx11.h>
struct SimpleVertex
{
XMFLOAT3 Pos;
XMFLOAT2 Tex;
};
#endif
<file_sep>/src/collider.cpp
#include "../includes/collider.h"
collider::collider()
{
}
collider::collider(SimpleVertex* vertices, XMFLOAT4* pos, int numVertices)
{
this->vertices = vertices;
this->pos = pos;
this->numVertices = numVertices;
}
XMFLOAT4* collider::getPos() {
return pos;
}
SimpleVertex* collider::getSV() {
return vertices;
}
int collider::getNumVertices() {
return numVertices;
}
void collider::translate(XMFLOAT4* newPos) {
float oldX = pos->x;
float oldY = pos->y;
float oldZ = pos->z;
float oldW = pos->w;
pos->x += newPos->x;
pos->y += newPos->y;
pos->z += newPos->z;
pos->w += newPos->w;
// change vertices
for (int i = 0; i < numVertices; i++) {
vertices[i].Pos.x += newPos->x;
vertices[i].Pos.y += newPos->y;
vertices[i].Pos.z += newPos->z;
}
}
bool collider::collision(collider* c) {
// get Simple Vertices from other object
SimpleVertex* other_v = c->getSV();
// checks each vertex in a collider if it is within another collider using Barycentric Coordinates
for (int i = 0; i < numVertices; i++) {
XMFLOAT3 v = vertices[i].Pos;
for (int j = 0; j < c->getNumVertices(); j += 3) {
// get points of the other object's triangle
XMFLOAT3 p0 = other_v[j].Pos;
XMFLOAT3 p1 = other_v[j + 1].Pos;
XMFLOAT3 p2 = other_v[j + 2].Pos;
// Barycentric Coordinates
float A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
float sign = A < 0 ? -1.0f : 1.0f;
float s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * v.x + (p0.x - p2.x) * v.y) * sign;
float t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * v.x + (p1.x - p0.x) * v.y) * sign;
// collision detected
if (s > 0 && t > 0 && (s + t) < 2 * A * sign) {
return true;
}
}
}
/*
// Rectangle Collision for Top Left point of Player
XMFLOAT3 p = vertices[0].Pos;
SimpleVertex* otherObj = c->getSV();
XMFLOAT3 topLeft = otherObj[0].Pos;
XMFLOAT3 botRight = otherObj[2].Pos;
for (int i = 0; i < numVertices; i++) {
if (vertices[i].Pos.x > topLeft.x && vertices[i].Pos.x < botRight.x &&
vertices[i].Pos.y < topLeft.y && vertices[i].Pos.y > botRight.y) {
cout << "jpsladf" << endl;
return true;
}
}
*/
return false;
}
| 9484f79c8bad57354b4847bcb14264741f3f5067 | [
"Markdown",
"C",
"C++"
] | 19 | C++ | nosnhojttam/2DGameEngine | 9fd487cc50c1d171291dd4fb09509cab7c629d08 | 01994c9a0ceae480ba11476db90e11a6dabbdf57 |
refs/heads/master | <file_sep>package com.mygdx.game.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.mygdx.game.HackermanGame
import com.mygdx.game.Paths
import com.mygdx.game.ScreenController
class MainMenuScreen(val game: HackermanGame) : Screen {
private var introMusic: Music = Gdx.audio.newMusic(Gdx.files.internal(Paths.Songs.INTRO_THEME))
private var menuImg = Texture("title.png")
// buttons
private var playButtonNormal = Texture(Paths.Clickables.PLAY_BUTTON_NORMAL)
private var playButtonClicked = Texture(Paths.Clickables.PLAY_BUTTON_CLICKED)
private var optionsButtonNormal = Texture(Paths.Clickables.OPTIONS_BUTTON_NORMAL)
private var optionsButtonClicked = Texture(Paths.Clickables.OPTIONS_BUTTON_CLICKED)
private var aboutButtonNormal = Texture(Paths.Clickables.ABOUT_BUTTON_NORMAL)
private var aboutButtonClicked = Texture(Paths.Clickables.ABOUT_BUTTON_CLICKED)
// button locations
private val CHAR_BUTTON_HEIGHT = HackermanGame.getHeight() / 16
private val CHAR_BUTTON_WIDTH = HackermanGame.getWidth() / 32
private val BUTTON_X = HackermanGame.getWidth() * 3f / 4
private val PLAY_Y = HackermanGame.getHeight() * 2f/3
private val BUTTON_VERT_SPACING = CHAR_BUTTON_HEIGHT + 50f;
private val OPTIONS_Y = PLAY_Y - BUTTON_VERT_SPACING
private val ABOUT_Y = OPTIONS_Y - BUTTON_VERT_SPACING
// expressions that can determine if button is being hovered over given coordinates x and y
// evaluate which button is being hovered
private val isPlayHovered = { x: Float, y: Float -> x > BUTTON_X && x <= BUTTON_X + CHAR_BUTTON_WIDTH*"start".length &&
y < PLAY_Y + CHAR_BUTTON_HEIGHT && y >= PLAY_Y}
private val isOptionsHovered = { x: Float, y: Float -> x > BUTTON_X && x <= BUTTON_X + CHAR_BUTTON_WIDTH*"options".length &&
y < OPTIONS_Y + CHAR_BUTTON_HEIGHT && y >= OPTIONS_Y }
private val isAboutHovered = { x: Float, y: Float -> x > BUTTON_X && x <= BUTTON_X + CHAR_BUTTON_WIDTH*"about".length &&
y < ABOUT_Y + CHAR_BUTTON_HEIGHT && y >= ABOUT_Y }
override fun render(delta: Float) {
Gdx.gl.glClearColor(1f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
introMusic.play()
game.batch?.begin()
game.batch?.draw(menuImg, 0f, 0f, HackermanGame.getWidth(), HackermanGame.getHeight())
val x = Gdx.input.getX().toFloat()
// y is inverted
val y = HackermanGame.getHeight() - Gdx.input.getY()
highlightHoveredItems(x, y)
if (Gdx.input.justTouched()) {
handleClickAction(x, y)
}
game.batch?.end()
}
private fun handleClickAction(x: Float, y: Float) {
if (isPlayHovered(x,y) ) {
introMusic.stop()
ScreenController.instance.setLevelMap()
}
else if (isOptionsHovered(x,y)) {
ScreenController.instance.setOptionsMenu()
}
else if (isAboutHovered(x,y)) {
ScreenController.instance.setAboutScreen()
}
}
fun highlightHoveredItems(x: Float, y: Float) {
// draw button highlights based on location
if (isPlayHovered(x,y) ) {
game.batch?.draw(playButtonClicked, BUTTON_X, PLAY_Y, CHAR_BUTTON_WIDTH*"start".length, CHAR_BUTTON_HEIGHT)
}
else {
game.batch?.draw(playButtonNormal, BUTTON_X, PLAY_Y, CHAR_BUTTON_WIDTH*"start".length, CHAR_BUTTON_HEIGHT)
}
if (isOptionsHovered(x,y)) {
game.batch?.draw(optionsButtonClicked, BUTTON_X, OPTIONS_Y, CHAR_BUTTON_WIDTH*"options".length, CHAR_BUTTON_HEIGHT)
}
else {
game.batch?.draw(optionsButtonNormal, BUTTON_X, OPTIONS_Y, CHAR_BUTTON_WIDTH*"options".length, CHAR_BUTTON_HEIGHT)
}
if (isAboutHovered(x,y)) {
game.batch?.draw(aboutButtonClicked, BUTTON_X, ABOUT_Y, CHAR_BUTTON_WIDTH*"about".length, CHAR_BUTTON_HEIGHT)
}
else {
game.batch?.draw(aboutButtonNormal, BUTTON_X, ABOUT_Y, CHAR_BUTTON_WIDTH*"about".length, CHAR_BUTTON_HEIGHT)
}
}
override fun dispose() {
menuImg.dispose()
playButtonNormal.dispose()
playButtonClicked.dispose()
optionsButtonNormal.dispose()
optionsButtonClicked.dispose()
aboutButtonNormal.dispose()
aboutButtonClicked.dispose()
}
override fun hide() {}
override fun show() {}
override fun pause() {}
override fun resume() {}
override fun resize(width: Int, height: Int) {}
}<file_sep>/* ScreenController: Handles transitions between screens in the game. Stores instances of previous screens for quick restoration.
* Behaves similar to a singleton, but with a fron facing method that allows for a single instantiation. */
package com.mygdx.game
import com.badlogic.gdx.Screen
import com.mygdx.game.screens.*
class ScreenController {
private var currentScreen: Screen? = null
private var game: HackermanGame
companion object{
lateinit var instance: ScreenController
fun init(game: HackermanGame) {
instance = ScreenController(game)
}
}
// pass in the screens that are init with the game instance
private constructor(game: HackermanGame) {
this.game = game
}
private fun resetCurrentScreen(newScreen: Screen) {
currentScreen?.dispose()
currentScreen = newScreen
}
fun setMainMenu() {
var newScreen = MainMenuScreen(game)
resetCurrentScreen(newScreen)
game.setScreen(newScreen)
}
fun setAboutScreen() {
var newScreen = AboutScreen(game)
resetCurrentScreen(newScreen)
game.setScreen(newScreen)
}
fun setOptionsMenu() {
val newScreen = OptionsMenu(game)
resetCurrentScreen(newScreen)
game.setScreen(newScreen)
}
fun setLevelMap() {
val newScreen = LevelMap(game)
resetCurrentScreen(newScreen)
game.setScreen(newScreen)
}
fun setWarezScreen() {
val newScreen = WarezNode(game)
resetCurrentScreen(newScreen)
// TODO: Grab pre-dialog
// displayPreDialog(nodeActor.infoFile)
game.setScreen(newScreen)
}
fun setLevelScreen() {
}
}<file_sep>package com.mygdx.game.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.mygdx.game.HackermanGame
import com.mygdx.game.Paths
import com.mygdx.game.ScreenController
class AboutScreen(val game: HackermanGame) : Screen {
var font = BitmapFont()
override fun render(delta: Float) {
var fileStr = Gdx.files.internal(Paths.TextFiles.ABOUT).readString()
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
game.batch?.begin()
font.draw(game.batch, fileStr, 100f, HackermanGame.getHeight() - 50f)
if (Gdx.input.justTouched()) {
ScreenController.instance.setMainMenu()
}
game.batch?.end()
}
override fun dispose() {}
override fun pause() {}
override fun resume() {}
override fun resize(width: Int, height: Int) {}
override fun hide() {}
override fun show() {}
}<file_sep>package com.mygdx.game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.ui.Dialog
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.mygdx.game.dialogs.LevelInfoDialog
class LevelNodeActor : Actor {
// used to pass object instance in anonymous InputListener child class
var actorInstance = this
// different images used for when sprite is hovered over
var highlight_img: Sprite
var normal_img: Sprite = Sprite(Texture(Gdx.files.internal(Paths.Clickables.PLAY_BUTTON_NORMAL)))
var highlight = false
// description of level
var levelDes = ""
// level that must be defeated for this one to be unlocked
var dependency = ""
var levelType = ""
constructor (x: Float, y: Float, highlight_img_path: String, normal_img_path: String,
levelDescription: String, levelName: String, levelDependency: String,
lType: String) {
// bind data
highlight_img = Sprite(Texture(Gdx.files.internal(highlight_img_path)))
normal_img = Sprite(Texture(Gdx.files.internal(normal_img_path)))
levelDes = levelDescription
touchable = Touchable.enabled
name = levelName
dependency = levelDependency
levelType = lType
// bind actor and set input response
setBounds(x, y, highlight_img.width, highlight_img.height)
touchable = Touchable.enabled
addListener(constructInputListener())
}
override fun positionChanged() {
normal_img.setPosition(x, y)
highlight_img.setPosition(x, y)
super.positionChanged()
}
override fun draw(batch: Batch?, parentAlpha: Float) {
if (highlight)
highlight_img.draw(batch)
else
normal_img.draw(batch)
}
/* Handles when node is hovered over as well as when it */
private fun constructInputListener(): InputListener {
return object: InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
super.touchDown(event, x, y, pointer, button)
val dialog = LevelInfoDialog(actorInstance)
dialog.show(actorInstance.stage)
return false
}
// handles mouse hovering
override fun enter(event: InputEvent?, x: Float, y: Float, pointer: Int, fromActor: Actor?) {
super.enter(event, x, y, pointer, fromActor)
highlight = true
}
// handle mouse leaving - unhighlight actor
override fun exit(event: InputEvent?, x: Float, y: Float, pointer: Int, toActor: Actor?) {
super.exit(event, x, y, pointer, toActor)
highlight = false
}
}
}
}<file_sep>/* Builds */
package com.mygdx.game.screens
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Texture
import com.mygdx.game.HackermanGame
class WarezNode : Screen {
private var game: HackermanGame
//private var ownerImage: Texture
constructor(game: HackermanGame) {
this.game = game
}
override fun show() {}
override fun render(delta: Float) {}
override fun dispose() {}
override fun hide() {}
override fun pause() {}
override fun resume() {}
override fun resize(width: Int, height: Int) {}
// parses file
private class LevelParser {
// expects file name
fun parseData(warezName: String) {
}
}
}<file_sep>package com.mygdx.game
import com.badlogic.gdx.Game
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import java.awt.Toolkit
class HackermanGame : Game() {
var batch: SpriteBatch? = null
companion object {
private var WIDTH = 0f
private var HEIGHT = 0f
fun getWidth() : Float {return WIDTH}
fun getHeight(): Float {return HEIGHT}
}
override fun create() {
ScreenController.init(this)
val screenSize = Toolkit.getDefaultToolkit().screenSize
WIDTH = screenSize.width.toFloat()
HEIGHT = screenSize.height.toFloat()
batch = SpriteBatch()
ScreenController.instance.setMainMenu()
}
override fun dispose() {
batch?.dispose()
}
}<file_sep>package com.mygdx.game.screens
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Matrix4
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.XmlReader
import com.mygdx.game.HackermanGame
import com.mygdx.game.LevelNodeActor
import com.mygdx.game.Paths
import java.util.*
class LevelMap(val game: HackermanGame) : Screen {
private var levelBackground = Texture(Gdx.files.internal("title.png"))
private var nodeImg = Texture(Gdx.files.internal(Paths.Clickables.PLAY_BUTTON_NORMAL))
private var camera = OrthographicCamera()
private var levelNodes: MutableList<LevelNodeActor> = NodeRenderer().getNodes()
private var stage = Stage()
private var lineRenderer = ShapeRenderer()
private val BACKGROUND_WIDTH = 3000f
private val BACKGROUND_HEIGHT = 2100f
private val SCROLL_AMOUNT = 20f
override fun show() {
camera.setToOrtho(false, HackermanGame.getWidth(), HackermanGame.getHeight())
Gdx.input.inputProcessor = stage
for (node in levelNodes) {
stage.addActor(node)
}
}
override fun render(delta: Float) {
game.batch?.setProjectionMatrix(camera.combined)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
stage.viewport.camera = camera
game.batch?.begin()
camera.update()
//game.batch?.draw(levelBackground, 0f, 0f, BACKGROUND_WIDTH, BACKGROUND_HEIGHT)
drawConnectingLines(1, camera.combined)
handleKeyboardInput()
game.batch?.end()
// draw nodes
stage.act(delta)
stage.draw()
}
fun drawConnectingLines(lineWidth: Int, projectionMatrix: Matrix4?) {
for (dependentActor in levelNodes) {
var dependencyActor: LevelNodeActor? = null
// find corresponding actor to dependency
for (dependency in levelNodes) {
if (dependentActor.dependency == dependency.name) {
dependencyActor = dependency
break
}
}
if (dependencyActor == null) {
continue
}
val color: Color = Color.LIGHT_GRAY
Gdx.gl.glLineWidth(lineWidth.toFloat())
lineRenderer.setProjectionMatrix(projectionMatrix)
lineRenderer.begin(ShapeRenderer.ShapeType.Line)
lineRenderer.setColor(color)
lineRenderer.line(Vector2(dependencyActor.x, dependencyActor.y), Vector2(dependentActor.x, dependentActor.y))
lineRenderer.end()
Gdx.gl.glLineWidth(0.25f)
}
}
// allows for scrolling around map. Handles case where use scrolls out of bounds
fun handleKeyboardInput() {
var deltaX = 0f
var deltaY = 0f
val curX = camera.position.x
val curY = camera.position.y
if (Gdx.input.isKeyPressed(Input.Keys.A)) {
deltaX = if (camera.position.x - HackermanGame.getWidth() /2 - SCROLL_AMOUNT > 0f) -1 * SCROLL_AMOUNT else 0f
}
else if (Gdx.input.isKeyPressed(Input.Keys.D)) {
deltaX = if (camera.position.x + HackermanGame.getWidth() /2 + SCROLL_AMOUNT < BACKGROUND_WIDTH) SCROLL_AMOUNT else 0f
}
if (Gdx.input.isKeyPressed(Input.Keys.W)) {
deltaY = if (camera.position.y + HackermanGame.getHeight() /2 + SCROLL_AMOUNT < BACKGROUND_HEIGHT) SCROLL_AMOUNT else 0f
}
else if (Gdx.input.isKeyPressed(Input.Keys.S)) {
deltaY = if (camera.position.y - HackermanGame.getHeight() /2 - SCROLL_AMOUNT > 0f) -1*SCROLL_AMOUNT else 0f
}
camera.translate(deltaX, deltaY)
}
override fun dispose() {
levelBackground.dispose()
nodeImg.dispose()
}
override fun hide() {}
override fun pause() {}
override fun resume() {}
override fun resize(width: Int, height: Int) {}
// helper class used to generate node actors
private class NodeRenderer {
fun getNodes(): MutableList<LevelNodeActor> {
val levelsFile = Paths.LevelFiles.LEVEL_LAYOUT
val actors: MutableList<LevelNodeActor> = ArrayList()
val reader = XmlReader()
val root = reader.parse(Gdx.files.internal(Paths.LevelFiles.LEVEL_LAYOUT))
for (i in 0 until root.childCount) {
val level = root.getChild(i)
val x: Float = level.getChildByName("x").text.toFloat()
val y: Float = level.getChildByName("y").text.toFloat()
val description = level.getChildByName("description").text
val name = level.getChildByName("name").text
var dependency = level.getChildByName("dependency").text
val levelType = level.getChildByName("type").text
val (normal, highlighted) = getNodeImages(level.getChildByName("img").text)
actors.add(LevelNodeActor(x, y, highlighted, normal, description, name, dependency, levelType))
}
return actors
}
private fun getNodeImages(imgType: String): Pair<String, String> {
when (imgType) {
"default" -> return Pair(Paths.Clickables.LevelNodes.DEFAULT_NODE_NORMAL, Paths.Clickables.LevelNodes.DEFAULT_NODE_CLICKED)
"warez" ->return Pair(Paths.Clickables.LevelNodes.WAREZ_NODE_NORMAL, Paths.Clickables.LevelNodes.WAREZ_NODE_CLICKED)
else -> return Pair(Paths.Clickables.LevelNodes.DEFAULT_NODE_NORMAL, Paths.Clickables.LevelNodes.DEFAULT_NODE_CLICKED)
}
}
}
}<file_sep>/* Paths: Used to contains paths to resources */
package com.mygdx.game
class Paths {
companion object {
}
class Songs {
companion object {
private const val SONGS = "sounds/songs/"
const val INTRO_THEME = SONGS + "intro.mp3"
}
}
class Clickables {
companion object {
private const val CLICKABLES = "clickables/"
const val PLAY_BUTTON_CLICKED = CLICKABLES + "play_button_clicked.png"
const val PLAY_BUTTON_NORMAL = CLICKABLES + "play_button_normal.png"
const val OPTIONS_BUTTON_CLICKED = CLICKABLES + "options_button_clicked.png"
const val OPTIONS_BUTTON_NORMAL = CLICKABLES + "options_button_normal.png"
const val ABOUT_BUTTON_CLICKED = CLICKABLES + "about_button_clicked.png"
const val ABOUT_BUTTON_NORMAL = CLICKABLES + "about_button_normal.png"
}
class LevelNodes {
companion object {
private const val LEVEL_NODES = CLICKABLES + "level_nodes/"
const val DEFAULT_NODE_NORMAL = LEVEL_NODES + "default_node_normal.png"
const val DEFAULT_NODE_CLICKED = LEVEL_NODES + "default_node_clicked.png"
const val WAREZ_NODE_NORMAL = LEVEL_NODES + "warez_node_normal.png"
const val WAREZ_NODE_CLICKED = LEVEL_NODES + "warez_node_clicked.png"
}
}
}
class TextFiles {
companion object {
private const val TEXT_FILES = "text_files/"
const val ABOUT = TEXT_FILES + "about.txt"
const val OPTIONS = TEXT_FILES + "options.txt"
}
}
class LevelFiles {
companion object {
private const val LEVEL_FILES = "level_files/"
const val LEVEL_LAYOUT = LEVEL_FILES + "level_layout.xml"
}
}
class Skins {
companion object {
private const val SKINS = "skins/"
}
class Sgx {
companion object {
private const val Sgx = SKINS + "sgx/"
const val JSON = Sgx + "sgx-ui.json"
const val ATLAS = Sgx + "sgx-ui.atlas"
}
}
}
class Node {
companion object {
const val NODE_PATH = "nodes/"
}
}
}<file_sep>/* Handles displaying dialog box when a node is clicked on. */
package com.mygdx.game.dialogs
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Dialog
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.mygdx.game.LevelNodeActor
import com.mygdx.game.Paths
import com.mygdx.game.ScreenController
class LevelInfoDialog: Dialog {
val WIDTH = 800f
val HEIGHT = 300f
var actorInstance: LevelNodeActor
init {
// only add texture region once
if (!addedRegion) {
skin.addRegions(atlas)
addedRegion = true
}
}
// static instance of resources used all the time. Reduces memory needed for each dialog box
companion object {
var addedRegion = false
val atlas = TextureAtlas(Gdx.files.internal(Paths.Skins.Sgx.ATLAS))
val skin = Skin(Gdx.files.internal(Paths.Skins.Sgx.JSON))
}
constructor (actorInst: LevelNodeActor): super(actorInst.name, LevelInfoDialog.skin) {
Gdx.app.debug("DIALOG: ", "CONSTRUCTOR")
name = actorInst.name
text(actorInst.levelDes)
actorInstance = actorInst
button("Enter", true)
button("Exit", false)
}
override fun show(stage: Stage): Dialog {
super.show(stage)
setBounds(actorInstance.x, actorInstance.y, WIDTH, HEIGHT)
return this
}
/* Expects object to be boolean. Enters level if true, stays at menu otherwise*/
override fun result(resObject: Any?) {
// if true, call Controller
if (resObject as Boolean) {
when(actorInstance.levelType) {
"level" -> ScreenController.instance.setLevelScreen()
"warez" -> ScreenController.instance.setWarezScreen()
else -> return
}
}
}
} | 1d9d139dc24b7c8fff2a9c337894390d2f84c81b | [
"Kotlin"
] | 9 | Kotlin | zanway578/hackerman | 15716c3aa3928d83b2c640fbba9f739b17f3565c | 4826391afabe6021cd7dc2ffa2c860173c67e8df |
refs/heads/master | <file_sep>package com.cebul.jez.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.transform.RootEntityResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.webflow.engine.History;
import com.cebul.jez.entity.Hist_Wyszuk;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.ProduktyLicytuj;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zdjecie;
@Repository
public class ProduktyDao extends Dao
{
public List<String> getProduktyLike(String like)
{
String l = "%"+like+"%";
Session session = getSessionFactory();
Query query = session.createQuery("select p.nazwa from Produkty p where " +
" p.nazwa LIKE :like and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() )) GROUP BY p.nazwa ")
.setParameter("like", l);
List<String> result = new ArrayList<String>();
if(!query.list().isEmpty())
result = (List<String>) query.list();
//System.out.println(result.get(0).getNazwa());
return result;
}
public List<String> getProduktyLike(String like, Integer kategoria)
{
String l = "%"+like+"%";
Session session = getSessionFactory();
Query query = session.createQuery("select p.nazwa from Produkty p " +
"left join fetch p.kategorie as kat where " +
"kat.id IN (select k.id from Kategoria k left join k.parentKategory as parentK " +
"WHERE parentK.id = :kategoria ) and p.nazwa LIKE :like " +
"and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 id2.dataZakonczenia >= CURRENT_DATE() ) GROUP BY p.nazwa ) ")
.setParameter("like", l).setParameter("kategoria", kategoria);
List<String> result = new ArrayList<String>();
if(!query.list().isEmpty())
result = query.list();
return result;
}
public List<Produkty> getFullProduktyLike(String like, Integer kategoria)
{
String l = "%"+like+"%";
Session session = getSessionFactory();
// wpisanie do tabeli Historia wyszukiwania
Kategoria k = (Kategoria) session.get(Kategoria.class, kategoria);
Hist_Wyszuk hw = new Hist_Wyszuk();
hw.setData(new Date());
hw.setKategoria(k);
session.save(hw);
//////
Query query = session.createQuery("from Produkty p " +
"left join fetch p.kategorie as kat where " +
"kat.id IN (select k.id from Kategoria k left join k.parentKategory as parentK " +
"WHERE parentK.id = :kategoria ) and p.nazwa LIKE :like " +
"and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() ) ) ")
.setParameter("like", l).setParameter("kategoria", kategoria);
List<Produkty> result = new ArrayList<Produkty>();
if(!query.list().isEmpty())
result = query.list();
return result;
}
public List<Produkty> getFullProduktyLike(String like, Integer kategoria, Double cenaOd, Double cenaDo, String []kupLic, Integer []podkat)
{
String l;
if(like != null)
l = "%"+like+"%";
else
l = "%";
Session session = getSessionFactory();
// wpisanie do tabeli Historia wyszukiwania
if(kategoria != null)
{
Kategoria k = (Kategoria) session.get(Kategoria.class, kategoria);
Hist_Wyszuk hw = new Hist_Wyszuk();
hw.setData(new Date());
hw.setKategoria(k);
session.save(hw);
}
//////
String sql = "from Produkty p " +
"left join fetch p.kategorie as kat where "+
"p.nazwa LIKE :like ";
if(cenaOd != null)
{
sql += "AND p.cena >= "+cenaOd+" ";
}
if(cenaDo != null)
{
sql += "AND p.cena <= "+cenaDo+" ";
}
if(podkat != null)
{
String tmp = "";
for(int i=0;i<podkat.length;i++)
{
if(i == podkat.length-1)
{
tmp += podkat[i];
}else{
tmp += podkat[i]+",";
}
}
if(podkat.length > 0)
sql += " AND kat.id IN ("+tmp+") ";
}else{
if(kategoria != null && !kategoria.equals(0))
{
sql += " AND kat.id IN (select k.id from Kategoria k left join k.parentKategory as parentK " +
"WHERE parentK.id = "+kategoria+" )";
}
}
if(kupLic != null && kupLic.length>0)
{
int tmp = kupLic.length;
System.out.println("kupLic rozmiar = "+tmp);
if(tmp < 2)
{
if(kupLic[0].equals("kupTeraz"))
{
sql += "and p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) ";
}else
{
sql += "and p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() ) ";
}
}else{
sql += "and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() ) ) ";
}
}else{
sql += "and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() ) ) ";
}
System.out.println(sql);
Query query = session.createQuery(sql)
.setParameter("like", l);
List<Produkty> result = new ArrayList<Produkty>();
if(!query.list().isEmpty())
result = query.list();
return result;
}
public List<Produkty> getFullProduktyLike(String like)
{
String l = "%"+like+"%";
Session session = getSessionFactory();
// wpisanie do tabeli Historia wyszukiwania
Hist_Wyszuk hw = new Hist_Wyszuk();
hw.setData(new Date());
session.save(hw);
//////
Query query = session.createQuery("from Produkty p " +
"WHERE p.nazwa LIKE :like " +
"and (p.id in (select i2.id from ProduktyKupTeraz i2 WHERE i2.kupiony = false ) " +
"or p.id in (select id2.id from ProduktyLicytuj id2 WHERE id2.dataZakonczenia >= CURRENT_DATE() ) ) ")
.setParameter("like", l);
List<Produkty> result = new ArrayList<Produkty>();
if(!query.list().isEmpty())
result = query.list();
return result;
}
public List<Produkty> getLastFourProdukt()
{
Session session = getSessionFactory();
Query query = session.createQuery("from Produkty p where " +
" (p.id in (select pk.id from ProduktyKupTeraz pk WHERE pk.kupiony = false) " +
"or p.id in (select pl.id from ProduktyLicytuj pl WHERE pl.dataZakonczenia >= CURRENT_DATE() )) " +
" ORDER BY p.dataDodania DESC").setMaxResults(6);
List<Produkty> result = new ArrayList<Produkty>();
if(!query.list().isEmpty())
result = (List<Produkty>) query.list();
return result;
}
public Produkty getProdukt(Integer id)
{
Produkty p = new Produkty();
Session session = getSessionFactory();
p = (Produkty) session.get(Produkty.class, id);
return p;
}
public boolean saveProduktKupTeraz(ProduktyKupTeraz p)
{
try{
Session session = getSessionFactory();
Kategoria kat = (Kategoria) session.get(Kategoria.class, p.getKategorie().getId());
p.setKategorie(kat);
session.saveOrUpdate(p);
}catch(Exception e)
{
return false;
}
return true;
}
public boolean updateProdukt(Produkty p)
{
try{
Session session = getSessionFactory();
session.saveOrUpdate(p);
}catch(Exception e)
{
return false;
}
return true;
}
public boolean saveProduktLicytuj(ProduktyLicytuj p)
{
try{
Session session = getSessionFactory();
Kategoria kat = (Kategoria) session.get(Kategoria.class, p.getKategorie().getId());
p.setKategorie(kat);
session.saveOrUpdate(p);
}catch(Exception e)
{
return false;
}
return true;
}
public List<Integer> getZdjeciaId(Produkty p)
{
Session session = getSessionFactory();
Query query = session.createQuery("select z.id from Prod_Zdj pz left join pz.produkt as p left join pz.zdjecie as z WHERE p.id = :idP ")
.setParameter("idP", p.getId() );
List<Integer> result = new ArrayList<Integer>();
if(!query.list().isEmpty())
result = (List<Integer>) query.list();
//System.out.println(result.get(0).getNazwa());
return result;
}
public Zdjecie getZdjecie(Integer id)
{
Session session = getSessionFactory();
Query query = session.createQuery("from Zdjecie z where z.id = :idZ ")
.setParameter("idZ", id);
Zdjecie result = new Zdjecie();
if(!query.list().isEmpty())
result = (Zdjecie) query.list().get(0);
//System.out.println(result.get(0).getNazwa());
return result;
}
public void setKupione(List<Produkty> produkty)
{
Session session = getSessionFactory();
ProduktyKupTeraz prod;
for(Produkty p : produkty)
{
if(p instanceof ProduktyKupTeraz)
{
prod = (ProduktyKupTeraz) p;
prod.setKupiony(true);
session.saveOrUpdate(prod);
}
}
}
public void updateLicytacja(ProduktyLicytuj p)
{
int id = p.getId();
double cena = p.getCena();
User u = p.getAktualnyWlasciciel();
//p =null;
Session session = getSessionFactory();
//session.evict(p);
//session.evict(u);
ProduktyLicytuj prod = (ProduktyLicytuj) getProdukt(id);
if(u.getId().intValue() != prod.getAktualnyWlasciciel().getId().intValue())
prod.setAktualnyWlasciciel(u);
prod.setCena(cena);
session.update(prod);
}
public List<Produkty> getSprzedaneProdukty(User u)
{
Session session = getSessionFactory();
Query query = session.createQuery("from Produkty p inner join p.user as us WHERE us.id = :idW AND " +
"p.id in (select pk.id from ProduktyKupTeraz pk WHERE pk.kupiony = true) " +
"OR " +
"p.id in (select pl.id from ProduktyLicytuj pl left join pl.aktualnyWlasciciel as w " +
"WHERE pl.dataZakonczenia < CURRENT_DATE() " +
"AND w.id is not null) ").setParameter("idW", u.getId() );
List<Object> result = new ArrayList<Object>();
result = query.list();
List<Produkty> resultFinal = new ArrayList<Produkty>();
Object[] ob;
int index = 0;
for(Object o : result)
{
ob = (Object[]) result.get(index);
for(int i=0;i<ob.length; i++)
{
if(ob[i] instanceof Produkty)
{
resultFinal.add((Produkty)ob[i]);
}
}
index++;
}
return resultFinal;
//return result;
}
public List<Produkty> getWystawioneProdukty(User u)
{
Session session = getSessionFactory();
Query query = session.createQuery("from Produkty p inner join p.user as us WHERE us.id = :idW AND " +
"p.id in (select pk.id from ProduktyKupTeraz pk WHERE pk.kupiony = false) " +
"OR " +
"p.id in (select pl.id from ProduktyLicytuj pl left join pl.aktualnyWlasciciel as w " +
"WHERE pl.dataZakonczenia >= CURRENT_DATE() " +
"AND w.id is not null) ").setParameter("idW", u.getId() );
List<Object> result = new ArrayList<Object>();
result = query.list();
List<Produkty> resultFinal = new ArrayList<Produkty>();
Object[] ob;
int index = 0;
for(Object o : result)
{
ob = (Object[]) result.get(index);
for(int i=0;i<ob.length; i++)
{
if(ob[i] instanceof Produkty)
{
resultFinal.add((Produkty)ob[i]);
}
}
index++;
}
return resultFinal;
//return result;
}
public boolean updateProduktInfo(Produkty p)
{
Session session = getSessionFactory();
Produkty produkt = (Produkty) session.get(Produkty.class, p.getId());
Kategoria kat = (Kategoria) session.get(Kategoria.class, p.getKategorie().getId());
//System.out.println(kat.getNazwa());
produkt.setKategorie(kat);
produkt.setNazwa(p.getNazwa());
produkt.setOpis(p.getOpis());
session.update(produkt);
return true;
}
public boolean deleteProdukt(Integer produktId)
{
Session session = getSessionFactory();
Produkty p = (Produkty) session.get(Produkty.class, produktId);
session.delete(p);
return true;
}
public List<Produkty> sprawdzProdukty(List<Produkty> produkty)
{
String s = "";
int index = 0;
int len = produkty.size() - 1;
for(Produkty p : produkty)
{
if(index == len)
s += p.getId().toString();
else
s += p.getId().toString()+",";
index++;
}
Session session = getSessionFactory();
Query query = session.createQuery("from Produkty p WHERE " +
"p.id in (select pk.id from ProduktyKupTeraz pk WHERE pk.kupiony = true AND pk.id in ("+s+") )");
List<Produkty> result = new ArrayList<Produkty>();
result = (List<Produkty>)query.list();
if(result.size() > 0)
return result;
return null;
}
}
<file_sep>package com.cebul.jez.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="Hist_Wyszuk")
public class Hist_Wyszuk
{
@Id
@GeneratedValue
@Column(name="Id")
private Integer id;
@Column(name="Data")
@NotNull
private Date data;
@OneToOne
@JoinColumn(name="IdKat")
private Kategoria kategoria;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public Kategoria getKategoria() {
return kategoria;
}
public void setKategoria(Kategoria kategoria) {
this.kategoria = kategoria;
}
}
<file_sep>package com.cebul.jez.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
@Entity
@Table(name="Adresy")
public class Adresy implements Serializable
{
@Id
@GeneratedValue
@Column(name="Id")
private Integer id;
@Column(name="Miejscowosc")
@Size(min=3, max=20, message="Nie ma takiego miejsca.")
private String miejscowosc;
@Column(name="Kod_Pocztowy")
@Size(min=6, max=6, message="Niepoprawny kod pocztowy.")
private String kod_pocztowy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMiejscowosc() {
return miejscowosc;
}
public void setMiejscowosc(String miejscowosc) {
this.miejscowosc = miejscowosc;
}
public String getKod_pocztowy() {
return kod_pocztowy;
}
public void setKod_pocztowy(String kod_pocztowy) {
this.kod_pocztowy = kod_pocztowy;
}
}
<file_sep>package com.cebul.jez.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Repository;
import com.cebul.jez.entity.DokumentZamowienia;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Platnosc;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zamowienie;
import com.cebul.jez.flows.Tmp;
@Repository
public class ZamowienieDao extends Dao
{
public List<Platnosc> getPlatnosci()
{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Platnosc");
List<Platnosc> result = query.list();
return result;
}
public List<DokumentZamowienia> getDokumenty()
{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM DokumentZamowienia");
List<DokumentZamowienia> result = query.list();
return result;
}
public Platnosc getPlatnoscLike(String s)
{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Platnosc WHERE rodzajPlatnosci = :p ")
.setParameter("p", s);
List<Platnosc> result = query.list();
return result.get(0);
}
public DokumentZamowienia getDokumentLike(String s)
{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM DokumentZamowienia WHERE nazwa = :p ")
.setParameter("p", s);
List<DokumentZamowienia> result = query.list();
return result.get(0);
}
public boolean zapiszZamowienie(Zamowienie z)
{
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(z);
return true;
}
public List<Produkty> getNieKomentProd(User u)
{
Session session = sessionFactory.getCurrentSession();
String sql = "FROM Zamowienie z inner join z.nabywca as us inner join fetch z.produkty as p " +
"where us.id = :id and p.id not in (select pp.id from Komentarz k " +
"inner join k.produkt as pp inner join k.nadawca as n WHERE n.id = :id ) ";
System.out.println(sql);
Query query = session.createQuery(sql).setParameter("id", u.getId());
List<Object> result = new ArrayList<Object>();
result = query.list();
List<Zamowienie> result3 = new ArrayList<Zamowienie>();
List<Produkty> resultFinal = new ArrayList<Produkty>();
Object[] ob;
int index = 0;
for(Object o : result)
{
ob = (Object[]) result.get(index);
for(int i=0;i<ob.length; i++)
{
if(ob[i] instanceof Zamowienie)
{
result3.add((Zamowienie)ob[i]);
}
}
index++;
}
for(Zamowienie z : result3)
{
resultFinal.addAll(z.getProdukty());
}
return resultFinal;
}
}
<file_sep>package com.cebul.jez.junit;
public class DoTestowania
{
public static int largest(int[] list)
{
int index;
int max = 0;
for(index = 0; index<list.length; index++)
{
if(list[index] > max)
{
max = list[index];
}
}
return max;
}
}
<file_sep>package com.cebul.jez.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.model.KategorieDao;
@Service
public class KategorieService
{
@Autowired
private KategorieDao kategorieDao;
public KategorieDao getKategorieDao() {
return kategorieDao;
}
public void setKategorieDao(KategorieDao kategorieDao) {
this.kategorieDao = kategorieDao;
}
@Transactional
public List<Kategoria> getMainKategory()
{
return kategorieDao.getMainKategory();
}
@Transactional
public List<Kategoria> getPodKategory(Integer parent)
{
return kategorieDao.getPodKategory(parent);
}
@Transactional
public Kategoria getMainKategory(Kategoria podkategoria)
{
return kategorieDao.getMainKategory(podkategoria);
}
@Transactional
public Kategoria getKategory(Integer id)
{
return kategorieDao.getKategory(id);
}
@Transactional
public boolean addKategoria(Kategoria k)
{
return kategorieDao.addKategoria(k);
}
@Transactional
public boolean updateCategory(Kategoria k)
{
return kategorieDao.updateCategory(k);
}
}
<file_sep>package com.cebul.jez.controllers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.ProduktyLicytuj;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zdjecie;
import com.cebul.jez.service.KategorieService;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.useful.CheckboxZdj;
import com.cebul.jez.useful.JsonLicytacja;
import com.cebul.jez.useful.JsonObject;
import com.cebul.jez.useful.ShoppingCart;
/**
*
* @author Mateusz
* Klasa działa jako kontroler w modelu MVC
* używa mechanizmu DI do wstrzykiwania zależnosći
* obsługuje żądania z ścieżki "/produkty/*"
* ponadto zawiera metody użożliwijace wyswietlenie multimediów (obrazów)
* przechowywanych w bazie danych
*/
@Controller
public class ProduktyController
{
@Autowired
private ProduktyService produktyService;
@Autowired
private KategorieService kategorieService;
@Autowired
private ShoppingCart shoppingCart;
/**
* powoduje wyświetlenie szczegółowych informacji o produkcie
*
* @param produktId identyfiaktor jednoznaczenie identyfikujacy dany produkt
* @param model referencja do modelu
* @param session referencja do obiektu sesji
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = {"/produkty/{produktId}/"}, method = RequestMethod.GET)
public String infoProdukt(@PathVariable Integer produktId, Model model, HttpSession session){
Produkty produkt = produktyService.getProdukt(produktId);
//Collection<Zdjecie> zdjecia = produkt.getZdjecia();
Collection<Integer> zdjecia = produktyService.getZdjeciaId(produkt);
Kategoria katGlow = kategorieService.getMainKategory(produkt.getKategorie().getParentKategory());
String path = katGlow.getNazwa()+" >>> "+produkt.getKategorie().getNazwa();
List<Kategoria> podkategorie = kategorieService.getPodKategory(katGlow.getId());
boolean czySprzedane = false;
boolean czyKupTeraz = false;
if(produkt instanceof ProduktyKupTeraz)
{
czyKupTeraz = true;
czySprzedane = ((ProduktyKupTeraz) produkt).isKupiony();
}
boolean ktosLicytuje = false;
boolean czyJaWygrywam = false;
int diffInDays = 0;
if(produkt instanceof ProduktyLicytuj)
{
User u = ((ProduktyLicytuj) produkt ).getAktualnyWlasciciel();
if( u != null)
{
ktosLicytuje = true;
User me = (User) session.getAttribute("sessionUser");
if(me != null && u.getId().equals(me.getId()) )
{
czyJaWygrywam = true;
}
}
Date now = new Date();
diffInDays = (int)( (((ProduktyLicytuj) produkt).getDataZakonczenia().getTime() - now.getTime()) / (1000 * 60 * 60 * 24) );
diffInDays++;
if(diffInDays < 0)
czySprzedane = true;
//System.out.println("roznica = "+diffInDays+1);
}
model.addAttribute("podkategorie", podkategorie);
model.addAttribute("produkt", produkt);
model.addAttribute("path", path);
model.addAttribute("zdjecia", zdjecia);
model.addAttribute("czyKupTeraz", czyKupTeraz);
model.addAttribute("ktosLicytuje", ktosLicytuje);
model.addAttribute("czyJaWygrywam", czyJaWygrywam);
model.addAttribute("roznicaDat", diffInDays);
model.addAttribute("czySprzedane", czySprzedane);
//model.addAttribute("prod", new Produkty());
return "produkt";
}
/**
*
* @param model refenencja do obiektu modelu
* @return zwraca logiczna nazwe widoku
*/
@RequestMapping(value = {"/produkty"})
public String mainProdukty(Model model)
{
return "produkt";
}
/**
* dodaje obiekt do koszyka (koszyk to bean o zasiegu sessji)
* @param produkt produkt który ma zostać dodany do koszyka
* @param model refernecja do obiektu model
* @return przekierowuje na stronę koszyka
*/
@RequestMapping(value = {"/produkty/addToCart/"}, method=RequestMethod.POST)
public String addToCart(Produkty produkt, Model model)
{
boolean prodWKoszyku = false;
for(Produkty p : shoppingCart.getItems())
{
if(p.getId().equals(produkt.getId()))
{
prodWKoszyku = true;
}
}
if(!prodWKoszyku)
{
Produkty p = produktyService.getProdukt(produkt.getId());
shoppingCart.addItem(p);
}
return "redirect:/koszyk";
}
/**
* umożliwia podbicie ceny licytacji przez uzytkownika
*
* @param produkt produkt który jest obiektem licytacji
* @param model referencja do modelu
* @param session referencja do obiektu sesji
* @return przekierowuje na strone produktu
*/
@RequestMapping(value = {"/produkty/licytuj/"}, method=RequestMethod.POST)
public String podbijCeneLicytuj(Produkty produkt, Model model, HttpSession session)
{
//System.out.println(produkt.getId());
ProduktyLicytuj pl = new ProduktyLicytuj();
pl.setId(produkt.getId());
pl.setCena(produkt.getCena());
User me = (User) session.getAttribute("sessionUser");
pl.setAktualnyWlasciciel(me);
produktyService.updateLicytacja(pl);
return "redirect:/produkty/"+produkt.getId()+"/";
}
/**
* sprawdza dostepnosc produktu w bazie dnaych
* @param model refernecja do obiektu modelu
* @param idProd identyfikator produkt
* @return zwraca obiekt produktu
*/
@RequestMapping(value="/produkty/sprawdzDostepnosc.json", method = RequestMethod.GET, params="idProd")
public @ResponseBody ProduktyLicytuj sprawdzAukcje(Model model, @RequestParam Integer idProd)
{
ProduktyLicytuj r = (ProduktyLicytuj) produktyService.getProdukt(idProd);
return r;
}
/**
* umożliwia wyświetlenie obrazka na stronie klienta
* aby metoda obsługiwała wyswietlanie obrazka, atrybut src znacznika img
* musi mieć postać src="/prodimag/{prodimageId}"
*
* @param prodimageId identyfikator obrazu
* @param response referencja do obiektu response
* @param request referencja do obiektu requet
* @param session referencja do obiektu sessji
* @param model referencja do obiektu modelu
* @throws IOException zgłasza wyjatek podczas nieudanej próby wyświetlenia obrazka
*/
@ResponseBody
@RequestMapping(value = "/prodimag/{prodimageId}", method = RequestMethod.GET, produces="prodimag/*")
public void getProdImage(@PathVariable Integer prodimageId, HttpServletResponse response, HttpServletRequest request,
HttpSession session, Model model) throws IOException {
response.setContentType("image/jpeg");
Zdjecie requestedImage = produktyService.getZdjecie(prodimageId);
InputStream in= new ByteArrayInputStream(requestedImage.getZdjecie());
//System.out.println("input: "+in);
if (in != null) {
IOUtils.copy(in, response.getOutputStream());
}
}
@RequestMapping(value = {"/produkty/usun/{produktId}/"}, method = RequestMethod.GET)
public String usunProduktZBazy(@PathVariable Integer produktId, Model model, HttpSession session){
produktyService.deleteProdukt(produktId);
return "redirect:/mojekonto/wystawioneProdukty/";
}
@RequestMapping(value = {"/produkty/edytuj/{produktId}/"}, method = RequestMethod.GET)
public String edytujProduktWBazie(@PathVariable Integer produktId, Model model, HttpSession session){
User me = (User) session.getAttribute("sessionUser");
Produkty produkt = produktyService.getProdukt(produktId);
if(me != null && produkt.getUser().getId().equals(me.getId()))
{
//Collection<Zdjecie> zdjecia = produkt.getZdjecia();
List<Integer> zdjecia = produktyService.getZdjeciaId(produkt);
Kategoria katGlow = kategorieService.getMainKategory(produkt.getKategorie().getParentKategory());
String path = katGlow.getNazwa()+" >>> "+produkt.getKategorie().getNazwa();
List<Kategoria> podkategorie = kategorieService.getPodKategory(katGlow.getId());
boolean czySprzedane = false;
boolean czyKupTeraz = false;
if(produkt instanceof ProduktyKupTeraz)
{
czyKupTeraz = true;
czySprzedane = ((ProduktyKupTeraz) produkt).isKupiony();
}
boolean ktosLicytuje = false;
boolean czyJaWygrywam = false;
int diffInDays = 0;
if(produkt instanceof ProduktyLicytuj)
{
User u = ((ProduktyLicytuj) produkt ).getAktualnyWlasciciel();
if( u != null)
{
ktosLicytuje = true;
//User me = (User) session.getAttribute("sessionUser");
if(me != null && u.getId().equals(me.getId()) )
{
czyJaWygrywam = true;
}
}
Date now = new Date();
diffInDays = (int)( (((ProduktyLicytuj) produkt).getDataZakonczenia().getTime() - now.getTime()) / (1000 * 60 * 60 * 24) );
diffInDays++;
if(diffInDays < 0)
czySprzedane = true;
//System.out.println("roznica = "+diffInDays+1);
}
model.addAttribute("podkategorie", podkategorie);
model.addAttribute("produkt", produkt);
model.addAttribute("path", path);
model.addAttribute("zdjecia", zdjecia);
model.addAttribute("czyKupTeraz", czyKupTeraz);
model.addAttribute("ktosLicytuje", ktosLicytuje);
model.addAttribute("czyJaWygrywam", czyJaWygrywam);
model.addAttribute("roznicaDat", diffInDays);
model.addAttribute("czySprzedane", czySprzedane);
model.addAttribute("katGlow", katGlow.getId());
model.addAttribute("podKat", produkt.getKategorie().getId());
model.addAttribute("check", new CheckboxZdj());
//model.addAttribute("prod", new Produkty());
return "edytujProdukt";
}
return "nieJestesSprzedajacym";
}
@RequestMapping(value = "/produkty/updateProdukt/", method=RequestMethod.POST)
public String updateKontoUsera(@Valid Produkty produkt, BindingResult bindingResult, Model model, HttpSession session)
{
if(bindingResult.hasErrors())
{
System.out.println("nie przechodziiiii");
System.out.println(bindingResult.getErrorCount());
System.out.println(bindingResult.toString());
return "redirect:/produkty/edytuj/"+produkt.getId()+"/";
}
//System.out.println(produkt.getId());
//produkt.setNazwa("");
//boolean itsDone = userService.updateUser(user);
boolean itsDone = produktyService.updateProduktInfo(produkt);
if(!itsDone)
{
return "redirect:/produkty/edytuj/"+produkt.getId()+"/";
}
//session.setAttribute("sessionUser", arg1);
return "redirect:/mojekonto/wystawioneProdukty/";
}
@RequestMapping(value = "/produkty/updateProdukt/usunZdjecie/", method=RequestMethod.POST)
public String usunZdjecieZProduktu(CheckboxZdj check, @RequestParam(value="idProd", required=false) Integer idProd, Model model, HttpSession session)
{
//System.out.println(idProd);
Integer ch[] = check.getCheckboxs();
if(ch.length > 0)
{
Produkty p = produktyService.getProdukt(idProd);
p.removeZdj(ch);
produktyService.updateProdukt(p);
}
return "redirect:/produkty/edytuj/"+idProd+"/";
}
@RequestMapping(value = "/produkty/edytuj/dodajZdjecie/", method=RequestMethod.POST)
public String dodajZdjecieDoProduktu(@RequestParam(value="produktId", required=false) Integer produktId, @RequestParam(value="image", required=false) MultipartFile image,
Model model, HttpSession session, HttpServletRequest request) throws Exception
{
//System.out.println(produktId);
Produkty p = produktyService.getProdukt(produktId);
//p.addZdjecie(zdj);
try{
if(!image.isEmpty())
{
validateImage(image);
//saveImage(image);
//saveImageOnHardDrive(image, "H:\\");
Zdjecie z = returnImage(image);
p.addZdjecie(z);
p.setZdjecie(z);
produktyService.updateProdukt(p);
}
}catch(Exception e){
System.out.println("przed dodaniem sie wykladam");
//System.out.println(e.getMessage());
return "redirect:/produkty/edytuj/"+produktId+"/";
}
return "redirect:/produkty/edytuj/"+produktId+"/";
}
/**
* umożliwia sprawdzenie czy uploadowany obraz ma wymagany format,
* w tym przypadku dopuszczalne są obrazu jpg oraz img
*
* @param image analizowany obraz
* @throws Exception zglaszany w przypadku gdy obraz nie jest w określonym formacie
*/
public void validateImage(MultipartFile image) throws Exception
{
if(!image.getContentType().equals("image/jpeg") && !image.getContentType().equals("image/png") && !image.getContentType().equals("image/x-png"))
{
throw new Exception("Plik nie ejst plikiem JPG. mam nontent= "+image.getContentType());
}
}
/**
* przetwarza uploadownay obraz (MultipartFile) do postaci akceptowalnej
* przez bazę danych (postać tablicy)
*
* @param image
* @return zwraca instancję obiektu Zdjecie
*/
public Zdjecie returnImage(MultipartFile image)
{
Zdjecie zdj = new Zdjecie();
try{
byte[] bFile = image.getBytes();
zdj.setZdjecie(bFile);
//zdjecieService.saveZdjecie(zdj);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return zdj;
}
/**
* umozliwia przetworzenie dany z formatu string do formatu Data("yyyy-MM-dd")
* metoda wykonuje się zanim binding result sprawdzi porpawnosć dancyh podpietego produktu
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
binder.registerCustomEditor(Date.class, editor);
}
}
<file_sep>package com.cebul.jez.controllers;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.apache.tools.ant.util.FileUtils;
import org.aspectj.util.FileUtil;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.ProduktyLicytuj;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zamowienie;
import com.cebul.jez.entity.Zdjecie;
import com.cebul.jez.service.KategorieService;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.service.UserService;
import com.cebul.jez.service.ZamowienieService;
import com.cebul.jez.service.ZdjecieService;
/**
* Klasa działa jako kontroler w modelu MVC
* używa mechanizmu DI do wstrzykiwania zależnosći
* obsługuje logikę zwiazaną z zarzadzeniem kontem użytkonika (np. wyświetlanie panelu użytkownika)
* @author Mateusz
* wstrzukuje: ServletContext, KategorieService, ProduktyService, ZdjecieService, UserService
*
*/
@Controller("MojeKontoController")
public class MojeKontoController
{
@Autowired
ServletContext context;
@Autowired
private KategorieService kategorieService;
@Autowired
private ProduktyService produktyService;
@Autowired
private ZdjecieService zdjecieService;
@Autowired
private UserService userService;
@Autowired
private ZamowienieService zam;
/**
* wyswietla głowny widok panelu moje Konto
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/mojekonto/")
public String getGlownyWidok()
{
return "mojekonto";
}
/**
* wywolanie tej metody powoduje wyświetlenie pierwszego etapu dodawanie nowego produktu
* @return zwraca logiczną nazwe widoku
*/
@RequestMapping(value = "/mojekonto/dodajProdukt")
public String dodajProduktForm()
{
return "wybierzRodzajProduktu";
}
/**
* przekierowuje na stronę zawierajacą formularz ktory jest drugim krokiem dodawania produktu
* a w przypadku błedu na stronę głowną panelu użytkownika
*
* @param model referencja do modelu
* @param wybor informacja czy produkt ma być sprzedawany jako "Kup Teraz" czy jako "Licytacja"
* @param session referencja do obiektu sessji
* @return przekierouje na odpowiednią stronę
*
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/wybierzRodzajProd" , method=RequestMethod.POST)
public String wybranyRodzakProd(Model model, @RequestParam(value="wyborProd") String wybor, HttpSession session)
{
List<Kategoria> kat = kategorieService.getMainKategory();
model.addAttribute("MainKat", kat);
if(wybor.equals("KupTeraz"))
{
model.addAttribute("produkt", new ProduktyKupTeraz());
return "dodajProduktKupTeraz";
//return "redirect:/mojekonto/dodajProdukt/generateFormKup";
}else if(wybor.equals("Licytuj"))
{
model.addAttribute("produkt", new ProduktyLicytuj());
return "dodajProduktLicytuj";
}
return "redirect:/mojekonto/";
}
/**
* przekierowuje na stronę formularza "Kup Teraz"
* @param model zawiera referencję do obiektu modelu
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/generateFormKup")
public String generateUserForm(Model model)
{
model.addAttribute("produkt", new ProduktyKupTeraz());
return "dodajProduktKupTeraz";
}
/**
* przetwarza obiekt podpiety do formularza, wysłany metodą POST
* sprawdza czy nie zawiera blędów co do zawartosći pól
* w przypadku wystapienia błędu (np. wpsiania ceny produktu jako ciag znaków a nie jako cyfra)
* nastepuje zablokowanie formularza
* poprawne wykonanie (bez błędu) powoduje dodanie obiektu do bazy oraz przekierowanie na stronę
* umozliwiajacą dodanie zdjęć produktu
*
* @param pk produkt typu ProduktyKupTeraz który ma zostać utrwalony w bazie dancyh
* @param bindingResult referencja do obiektu bindingResult
* @param model referencja do modelu
* @param session referencja do obiektu sesji
* @param request referencja do obiektu request
* @return zwracja logiczną nazwę widoku
* @throws Exception wystepuje pdoczas bledu zapisu do bazy danych
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/dodajKupTeraz", method=RequestMethod.POST)
public String addProduktForForm(@Valid ProduktyKupTeraz pk, BindingResult bindingResult, Model model, HttpSession session, HttpServletRequest request) throws Exception
{
if(bindingResult.hasErrors())
{
model.addAttribute("produkt", pk);
model.addAttribute(bindingResult);
bindingResult.reject("zleeeeee");
System.out.println(bindingResult.getAllErrors());
//model.addAttribute("produkt", new ProduktyKupTeraz());
//return "redirect:/mojekonto/dodajProdukt/generateFormKup";
return "dodajProduktKupTeraz";
}
User u = (User) session.getAttribute("sessionUser");
pk.setUser(u);
boolean itsDone = produktyService.saveProduktKupTeraz(pk);
if(!itsDone)
{
return "/mojekonto/dodajProdukt/";
}
session.setAttribute("prod", pk);
session.setAttribute("firstAdd", "yes");
return "dodajZdjecie";
}
/**
* przetwarza obiekt podpiety do formularza, wysłany metodą POST
* sprawdza czy nie zawiera blędów co do zawartosći pól
* w przypadku wystapienia błędu (np. wpsiania ceny produktu jako ciag znaków a nie jako cyfra)
* nastepuje zablokowanie formularza
* poprawne wykonanie (bez błędu) powoduje dodanie obiektu do bazy oraz przekierowanie na stronę
* umozliwiajacą dodanie zdjęć produktu
*
* @param pl produkt typu ProduktLicytuj który ma zostać utrwalony w bazie dancyh
* @param bindingResult referencja do obiektu bindingResult
* @param model referencja do modelu
* @param session referencja do obiektu sesji
* @param request referencja do obiektu request
* @return zwraca logiczną nazwe widoku
* @throws Exception
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/dodajLicytuj", method=RequestMethod.POST)
public String addProduktForFormLicytuj(@Valid ProduktyLicytuj pl, BindingResult bindingResult, Model model, HttpSession session, HttpServletRequest request) throws Exception
{
//pl.setDataZakonczenia(new Date());
if(bindingResult.hasErrors())
{
model.addAttribute("produkt", pl);
model.addAttribute(bindingResult);
bindingResult.reject("zleeeeee");
System.out.println(bindingResult.getAllErrors());
//model.addAttribute("produkt", new ProduktyKupTeraz());
//return "redirect:/mojekonto/dodajProdukt/generateFormKup";
return "dodajProduktLicytuj";
}
if(!pl.getDataZakonczenia().after(new Date()))
{
pl.setDataZakonczenia(null);
model.addAttribute("produkt", pl);
return "dodajProduktLicytuj";
}
User u = (User) session.getAttribute("sessionUser");
pl.setUser(u);
boolean itsDone = produktyService.saveProduktLicytuj(pl);
if(!itsDone)
{
return "/mojekonto/dodajProdukt/";
}
session.setAttribute("prod", pl);
session.setAttribute("firstAdd", "yes");
return "dodajZdjecie";
}
/**
* umożliwia wyświetlenie obrazka na stronie klienta
* aby metoda obsługiwała wyswietlanie obrazka, atrybut src znacznika img
* musi mieć postać src="/images/{imageId}"
*
* @param imageId identyfikator zdjecia
* @param response referencja do obiektu response
* @throws IOException zgłaszany w przypadku nie możności wyswietlenia zdjecia
*/
@ResponseBody
@RequestMapping(value = "/images/{imageId}", method = RequestMethod.GET, produces="image/*")
public void getImage(@PathVariable Integer imageId, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
//Zdjecie requestedImage = zdjecieService.getZdjecie(2);
Zdjecie requestedImage = produktyService.getProdukt(imageId).getZdjecie();
InputStream in= new ByteArrayInputStream(requestedImage.getZdjecie());
//System.out.println("input: "+in);
if (in != null) {
IOUtils.copy(in, response.getOutputStream());
}
}
/**
* dodaje zdjecie do bazy i wiaże je z dodanym wcześniej produktem
*
*
* @param image zdjecie jakie użytkownik chce dodać do bazy
* @param mainImage określa czy zdjecie ma być uznane jako Avatar produkty
* @param model referencja do obiektu modelu
* @param session referencja do obiektu sesji
* @param request referencja do obiektu request
* @return zwraca logiczną anzwe widoku
* @throws Exception zgłaszany podczas wystapienia błedu w utrwalaniu zdjecia w bazie
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/dodajZdjecie", method=RequestMethod.POST)
public String dodajZdjecie(@RequestParam(value="image", required=false) MultipartFile image,
@RequestParam(value="mainImage", required=false) String mainImage, Model model, HttpSession session, HttpServletRequest request) throws Exception
{
if(session.getAttribute("prod") != null)
{
Produkty p = (Produkty) session.getAttribute("prod");
try{
if(!image.isEmpty())
{
validateImage(image);
//saveImage(image);
//saveImageOnHardDrive(image, "H:\\");
Zdjecie z = returnImage(image);
p.addZdjecie(z);
if(session.getAttribute("firstAdd") != null || mainImage.equals("main") )
{
session.removeAttribute("firstAdd");
p.setZdjecie(z);
}
produktyService.updateProdukt(p);
}
}catch(Exception e){
System.out.println("przed dodaniem sie wykladam");
//System.out.println(e.getMessage());
return "dodajZdjecie";
}
return "dodajZdjecie";
}
return "redirect:/mojekonto/";
}
/**
* umożliwia sprawdzenie czy uploadowany obraz ma wymagany format,
* w tym przypadku dopuszczalne są obrazu jpg oraz img
*
* @param image analizowany obraz
* @throws Exception zglaszany w przypadku gdy obraz nie jest w określonym formacie
*/
public void validateImage(MultipartFile image) throws Exception
{
if(!image.getContentType().equals("image/jpeg") && !image.getContentType().equals("image/png") && !image.getContentType().equals("image/x-png"))
{
throw new Exception("Plik nie ejst plikiem JPG. mam nontent= "+image.getContentType());
}
}
/**
* umożliwia zapis uploadowanego zdjecia na dysku twardym
* @param image uploadowany obraz
* @param path ścieżka w której ma zostać zapsiany obraz
*/
public void saveImageOnHardDrive(MultipartFile image, String path)
{
try
{
System.out.println("path= "+path);
File file = new File(path+image.getName());
org.apache.commons.io.FileUtils.writeByteArrayToFile(file, image.getBytes());
}catch(Exception e){
System.out.println("nie moge zapisac na dysku");
}
}
/**
* umozliwia zapis obrazu do bazy dancyh
* @param image uploadowany obraz
*/
public void saveImage(MultipartFile image)
{
try{
Zdjecie zdj = new Zdjecie();
byte[] bFile = image.getBytes();
zdj.setZdjecie(bFile);
zdjecieService.saveZdjecie(zdj);
}catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println("nie udalo sie, przykro mi");
}
}
/**
* przetwarza uploadownay obraz (MultipartFile) do postaci akceptowalnej
* przez bazę danych (postać tablicy)
*
* @param image
* @return zwraca instancję obiektu Zdjecie
*/
public Zdjecie returnImage(MultipartFile image)
{
Zdjecie zdj = new Zdjecie();
try{
byte[] bFile = image.getBytes();
zdj.setZdjecie(bFile);
//zdjecieService.saveZdjecie(zdj);
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return zdj;
}
/**
* powoduje zakonczenie procedsu dodawania zdjęc i wiazania dodanych zdjęć z produktem
* @param session referencja do obiektu session
* @return przekierowuje na stronę głowną panelu użytkownika
*/
@RequestMapping(value = "/mojekonto/dodajProdukt/zakoncz/")
public String zakonczaDodawanieZdj(HttpSession session)
{
session.removeAttribute("prod");
return "redirect:/mojekonto/";
}
/**
* umozliwia przetworzenie dany z formatu string do formatu Data("yyyy-MM-dd")
* metoda wykonuje się zanim binding result sprawdzi porpawnosć dancyh podpietego produktu
* @param binder
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
binder.registerCustomEditor(Date.class, editor);
}
/**
* wyświetla listę sprzednaych produktów przez zalogowanego uzytkownika
* @param model referencja do obiektu model
* @param session referencja do obiektu session
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/mojekonto/sprzedaneProdukty/")
public String showSprzedaneProdukty(Model model, HttpSession session)
{
User me = (User) session.getAttribute("sessionUser");
List<Produkty> sprzedaneProdukty = (List<Produkty>)produktyService.getSprzedaneProdukty(me);
//System.out.println("size= "+sprzedaneProdukty.size());
//System.out.println("id Pierwszego = "+sprzedaneProdukty.get(0).getId());
List<Boolean> czyKupTeraz = new ArrayList<Boolean>();
for(Produkty p : sprzedaneProdukty)
{
if(p instanceof ProduktyKupTeraz)
{
czyKupTeraz.add(true);
//System.out.println("kup teraz");
}
else
czyKupTeraz.add(false);
}
model.addAttribute("sprzedane", sprzedaneProdukty);
model.addAttribute("czyKupTeraz", czyKupTeraz);
return "sprzedaneProdukty";
}
@RequestMapping(value = "/mojekonto/modyfikujKonto/")
public String modyfikujKontoForm(Model model, HttpSession session)
{
User me = (User) session.getAttribute("sessionUser");
//User meCopy = me.
System.out.println("pass="+me.getPass());
model.addAttribute("user", me);
return "modyfikujKontoUser";
}
@RequestMapping(value = "/mojekonto/modyfikujKonto/zapisz/", method=RequestMethod.POST)
public String updateKontoUsera(@Valid User user, BindingResult bindingResult, Model model, HttpSession session)
{
if(bindingResult.hasErrors())
{
//System.out.println("hasło has error: "+user.getPass());
return "redirect:/mojekonto/modyfikujKonto/";
}
boolean itsDone = userService.updateUser(user);
if(!itsDone)
{
return "redirect:/mojekonto/modyfikujKonto/";
}
//session.setAttribute("sessionUser", arg1);
return "modyfikujKontoUser";
}
@RequestMapping(value = "/mojekonto/wystawioneProdukty/")
public String showWystawioneProdukty(Model model, HttpSession session)
{
User me = (User) session.getAttribute("sessionUser");
List<Produkty> sprzedaneProdukty = (List<Produkty>)produktyService.getWystawioneProdukty(me);
//System.out.println("size= "+sprzedaneProdukty.size());
//System.out.println("id Pierwszego = "+sprzedaneProdukty.get(0).getId());
List<Boolean> czyKupTeraz = new ArrayList<Boolean>();
for(Produkty p : sprzedaneProdukty)
{
if(p instanceof ProduktyKupTeraz)
{
czyKupTeraz.add(true);
//System.out.println("kup teraz");
}
else
czyKupTeraz.add(false);
}
model.addAttribute("sprzedane", sprzedaneProdukty);
model.addAttribute("czyKupTeraz", czyKupTeraz);
return "wystawioneProdukty";
}
@RequestMapping(value = "/mojekonto/wystawKomentarz/")
public String wystawKomentarzLista(Model model, HttpSession session)
{
User me = (User) session.getAttribute("sessionUser");
List<Produkty> produktyDoKoment = zam.getNieKomentProd(me);
List<Boolean> czyKupTeraz = new ArrayList<Boolean>();
for(Produkty p : produktyDoKoment)
{
if(p instanceof ProduktyKupTeraz)
{
czyKupTeraz.add(true);
//System.out.println("kup teraz");
}
else
czyKupTeraz.add(false);
}
model.addAttribute("produktyDoKoment", produktyDoKoment);
model.addAttribute("czyKupTeraz", czyKupTeraz);
return "komentarzeDoWystawienia";
}
}
<file_sep>package com.cebul.jez.useful;
public class CheckBoxLicKup
{
private String kupLicyt[];
private Integer podkat[];
public String[] getKupLicyt() {
return kupLicyt;
}
public void setKupLicyt(String[] kupLicyt) {
this.kupLicyt = kupLicyt;
}
public Integer[] getPodkat() {
return podkat;
}
public void setPodkat(Integer[] podkat) {
this.podkat = podkat;
}
}
<file_sep>package com.cebul.jez.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="Zamow_Prod")
public class Zamow_Prod
{
@Id
@GeneratedValue
@Column(name="Id")
private Integer id;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="Zamowienie")
private Zamowienie zamowienie;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="Produkt")
private Produkty produkt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Zamowienie getZamowienie() {
return zamowienie;
}
public void setZamowienie(Zamowienie zamowienie) {
this.zamowienie = zamowienie;
}
public Produkty getProdukt() {
return produkt;
}
public void setProdukt(Produkty produkt) {
this.produkt = produkt;
}
}
<file_sep>package com.cebul.jez.flows;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cebul.jez.entity.DokumentZamowienia;
import com.cebul.jez.entity.Platnosc;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zamowienie;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.service.UserService;
import com.cebul.jez.service.ZamowienieService;
import com.cebul.jez.useful.ShoppingCart;
@Component("koszykBeanFlow")
public class KoszykFlowBean
{
@Autowired
private ShoppingCart shoppingCart;
@Autowired
private ZamowienieService zamowienieService;
@Autowired
private ProduktyService produktyService;
@Autowired
private UserService userService;
private List<Produkty> juzKupione;
public KoszykFlowBean()
{
}
public List<Produkty> getJuzKupione() {
return juzKupione;
}
public void setJuzKupione(List<Produkty> juzKupione) {
this.juzKupione = juzKupione;
}
public ShoppingCart getShoppingCart() {
return shoppingCart;
}
public void setShoppingCart(ShoppingCart shoppingCart) {
this.shoppingCart = shoppingCart;
}
public List<Produkty> getShoppingCartItems()
{
return shoppingCart.getItems();
}
public List<Boolean> getCzyKupTerazList()
{
List<Boolean> czyKupTeraz = new ArrayList<Boolean>();
for(Produkty p : shoppingCart.getItems())
{
if(p instanceof ProduktyKupTeraz)
{
czyKupTeraz.add(true);
//System.out.println("kup teraz");
}
else
czyKupTeraz.add(false);
}
return czyKupTeraz;
}
public boolean isNotShooppingCartEmpty()
{
if(shoppingCart.getItems().size() > 0)
return true;
return false;
}
public boolean isUserLoged(Object principal)
{
if(principal != null)
return true;
return false;
}
public List<Platnosc> getPlatnosci()
{
return zamowienieService.getPlatnosci();
}
public List<DokumentZamowienia> getDokumenty()
{
return zamowienieService.getDokumenty();
}
public Platnosc getObjPlatnosc(Tmp t)
{
//Platnosc p = zamowienieService.getPlatnoscLike(t.getPlatnosc());
//System.out.println(p.getRodzajPlatnosci());
return zamowienieService.getPlatnoscLike(t.getPlatnosc());
}
public DokumentZamowienia getObjDokument(Tmp t)
{
//System.out.println(t.getDokument());
return zamowienieService.getDokumentLike(t.getDokument());
}
public User getUser(String s)
{
//System.out.println(s);
return userService.getUser(s);
}
public List<Produkty> getItems()
{
return shoppingCart.getItems();
}
public Double getKoszt()
{
//System.out.println("koszt: "+shoppingCart.getSuma());
return shoppingCart.getSuma();
}
public void zapiszZamowienie(Zamowienie zamowienie)
{
zamowienie.setData(new Date());
this.juzKupione = zamowienieService.zapiszZamowienie(zamowienie);
if(juzKupione == null)
{
shoppingCart.clear();
}else{
//shoppingCart.getItems().removeAll(juzKupione);
// zrobione w ten sposb poniewaz podczas usuwania rzuca wyjatkiem
//java.util.ConcurrentModificationException
for(Produkty p : juzKupione)
{
shoppingCart.addToSum(-p.getCena());
}
List<Produkty> good = shoppingCart.getItems();
good.removeAll(juzKupione);
//System.out.println("good size = "+good.size());
shoppingCart.setItems(good);
//System.out.println("shopping cart size = "+shoppingCart.getItems().size());
}
}
public boolean isTransactionOK()
{
if(juzKupione == null)
{
return true;
}
return false;
}
}
<file_sep>package com.cebul.jez.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.ProduktyLicytuj;
import com.cebul.jez.service.KategorieService;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.useful.CheckBoxLicKup;
import com.cebul.jez.useful.JsonKat;
import com.cebul.jez.useful.JsonObject;
/**
*
* @author Mateusz
* Klasa działa jako kontroler w modelu MVC
* używa mechanizmu DI do wstrzykiwania zależnosći
* obsługuje żądania z ścieżki "/szukaj/*"
*
*/
@Controller
@RequestMapping("/szukaj")
public class SzukajController
{
@Autowired
private ProduktyService produktyService;
@Autowired
private KategorieService kategorieService;
/**
* mapuje rzadanie dostępu /szukaj.json
* metoda ta jets wyowływana z poziomu jezyka Javascript
* zwraca object Json ktory zawiera słowa pasujaće do padanego wzorca
*
* @param model zawiera referencje do obiektu modelu
* @param slowo fraza która ma być użyta do przeszukania bazy danych pod kontem zgodnosći z nią
* @return zwraca objekt Ktry zawiera pasujące słowa (objekt JSon)
*/
@RequestMapping(value="/szukaj.json", method = RequestMethod.GET, params="slowo")
public @ResponseBody JsonObject znajdzWyszukiwarka(Model model, @RequestParam String slowo)
{
List<String> r = produktyService.getProduktyLike(slowo);
JsonObject jso = new JsonObject();
jso.generateProdukty(r);
return jso;
}
/**
* mapuje rzadanie /szukajProd/
* metoda jets używana do wyswietlenia informacji o prduktach na stronie klienta
*
* @param model zawiera referencje do obiektu modelu
* @param szukanaKat zawier ainformację o tym w jakiej kategorii maja być szukane produkty
* @param szukanaFraza zawiera informację o szukanej frazie
* @return
*/
@RequestMapping(value="/szukajProd/", method = RequestMethod.GET)
public String znajdzWyszukiwarka(Model model, @RequestParam(value="szukanaKat", required=false) Integer szukanaKat, @RequestParam(value="szukanaFraza", required=false) String szukanaFraza,
@RequestParam(value="cenaOd", required=false) Double cenaOd, @RequestParam(value="cenaDo", required=false) Double cenaDo,
CheckBoxLicKup chLicKup)
{
List<Produkty> produkty;
List<Kategoria> podkategorie = new ArrayList<Kategoria>();
Boolean hasPodkategory = false;
String kupLic[] = chLicKup.getKupLicyt();
Integer podkat[] = chLicKup.getPodkat();
produkty =produktyService.getFullProduktyLike(szukanaFraza, szukanaKat, cenaOd, cenaDo, kupLic, podkat);
if(szukanaKat != null && !szukanaKat.equals(0))
{
if(produkty.size() > 0)
{
podkategorie = kategorieService.getPodKategory(szukanaKat);
hasPodkategory = true;
}
}
//System.out.println(produkty.size());
List<Boolean> czyKupTeraz = new ArrayList<Boolean>();
for(Produkty p : produkty)
{
if(p instanceof ProduktyKupTeraz)
{
czyKupTeraz.add(true);
//System.out.println("kup teraz");
}
else
czyKupTeraz.add(false);
}
if(szukanaKat != null && !szukanaKat.equals(0))
{
Kategoria k = kategorieService.getKategory(szukanaKat);
model.addAttribute("szukanaKat", k.getNazwa());
}else{
model.addAttribute("szukanaKat", "Wszystkie");
}
if(cenaOd != null)
{
model.addAttribute("cenaOd", cenaOd);
}
if(cenaDo != null)
{
model.addAttribute("cenaDo", cenaDo);
}
if(kupLic != null)
{
for(int i=0;i<kupLic.length; i++)
{
if(kupLic[i].equals("kupTeraz"))
{
model.addAttribute("kupCheck", true);
}else{
model.addAttribute("licCheck", true);
}
}
}
if(podkat != null)
{
model.addAttribute("checkPod", podkat);
}
model.addAttribute("szukaneProdukty", produkty);
model.addAttribute("czyKupTeraz", czyKupTeraz);
model.addAttribute("podkategorie", podkategorie);
model.addAttribute("hasPodkategory", hasPodkategory);
model.addAttribute("szukKat", szukanaKat);
model.addAttribute("szukFraz", szukanaFraza);
model.addAttribute("check", new CheckBoxLicKup());
//System.out.println(podkategorie.size());
return "szukaneProdukty";
}
@RequestMapping(value="/podkat.json", method = RequestMethod.GET, params="katId")
public @ResponseBody JsonKat znajdzPodkat(Model model, @RequestParam Integer katId)
{
List<Kategoria> podKat = kategorieService.getPodKategory(katId);
JsonKat jso = new JsonKat();
jso.generateKategorie(podKat);
return jso;
}
}
<file_sep>package com.cebul.jez.controllers;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.cebul.jez.entity.User;
import com.cebul.jez.flows.UserShortInfo;
import com.cebul.jez.model.UserDao;
/**
*
* @author Mateusz
* Klasa działa jako kontroler w modelu MVC
* używa mechanizmu DI do wstrzykiwania zależnosći
* obsługuje żądania z ścieżki "/logowanie/*"
*/
@Controller
public class LogController
{
@Autowired
private UserDao userDao;
@Autowired
private UserShortInfo usinfo;
/**
* obsługuje żądanie dostępu do "/logowanie"
* @param model zawiera referencje do obiektu modelu
* @param session zawiera referencję do obiektu sesji
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/logowanie")
public String home(Model model, HttpSession session)
{
if(isUserLogged(session))
return "redirect:/home";
return "logowanie";
}
/**
* obsługuje żądanie dostępu do "/logowanie/setUserSession"
* @param model zawiera referencje do obiektu modelu
* @param session zawiera referencję do obiektu sesji
* @param request zawiera referencję do obiektu HttpServletRequest
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/logowanie/setUserSession")
public String setSessionUser(Model model, HttpSession session, HttpServletRequest request)
{
if(isUserLogged(session))
return "redirect:/home";
Principal principal = request.getUserPrincipal();
String userName = principal.getName();
User u = userDao.getUser(userName);
String ranga = u.getRanga();
session.setAttribute("sessionUser", u);
// ustawienie komponentu zawierajacego dane usera, widocznego w web flow
if(u != null)
{
usinfo.setId(u.getId());
usinfo.setLogin(u.getLogin());
usinfo.setEmail(u.getEmail());
usinfo.setRanga(u.getRanga());
}
System.out.println("test uset login:"+usinfo.getLogin() );
if(ranga.equals("admin"))
{
return "redirect:/admin_home";
}
return "redirect:/home";
}
/**
* obsługuje żądanie dostępu do "/login"
* @param login_error parametr ten określa wystąpnienie błedu podczas logowania i
* umożliwia wyświetlenie strony błednego logowania
* @param session odnosi się do okiektu sesji
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = "/logowanie", method=RequestMethod.GET, params="login_error" )
public String errorLogin(@RequestParam String login_error, HttpSession session)
{
if(isUserLogged(session))
return "redirect:/home";
return "loginError";
}
/**
* sprawdza czy uzytkownik jest już zalogowany do seystemu
* @param session odnosi się do obiektu sesji
* @return zwraca true lub false w zależnosci od tego czy użytkownik jest zalogowany czy nie
*/
public boolean isUserLogged(HttpSession session)
{
User u = (User) session.getAttribute("sessionUser");
if(u != null)
return true;
return false;
}
}
<file_sep>package com.cebul.jez.flows;
import java.io.Serializable;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserShortInfo implements Serializable
{
private Integer id;
private String login;
private String ranga;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getRanga() {
return ranga;
}
public void setRanga(String ranga) {
this.ranga = ranga;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEmpty()
{
if(id == null)
return true;
return false;
}
}
<file_sep>package com.cebul.jez.controllers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zdjecie;
import com.cebul.jez.model.UserDao;
import com.cebul.jez.service.KategorieService;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.service.TestDataBaseService;
import com.cebul.jez.service.UserService;
import com.cebul.jez.useful.Mail;
/**
*
* @author Robert
*Klasa pelniaca zadanie kontrolera w modelu MVC
*Obsluguje żądania ze ścieżki /admin_home
*
*/
@Controller
public class AdminHomeController {
@Autowired
private KategorieService kategorieService;
@Autowired
private UserService userService;
@Autowired
private TestDataBaseService dbService;
@Autowired
private ProduktyService produktyService;
@Autowired
private TestDataBaseService serv;
/**
*
* @param model jest to odniesienie do obiektu modelu
* @return zwraca logiczną nazwę widoku
*/
@RequestMapping(value = {"/admin_home"})
public String admin_home(Model model, HttpSession session){
//dbService.test1();
//List<Produkty> r = produktyService.getProduktyLike("drug", 19);
//System.out.println(r.size());
//Produkty pro = r.get(0);
//System.out.println(pro.getNazwa());
//serv.test1();
//System.out.println(new Date().after(new Date()));
List<Produkty> produkty = produktyService.getLastFourProdukt();
//model.addAttribute("lastFourItems", produkty);
session.setAttribute("lastFourItems", produkty);
//request.setAttribute("lastFourItems", produkty);
//System.out.println(produkty.size());
//sahjdksaksadsadsa
List<Kategoria> kat = kategorieService.getMainKategory();
model.addAttribute("kategoryListModel", kat);
session.setAttribute("kategoryList", kat);
HashMap<Integer, List<Kategoria>> podkategorie = new HashMap<Integer, List<Kategoria>>();
for(Kategoria k : kat)
{
podkategorie.put(k.getId(), kategorieService.getPodKategory(k.getId()) );
}
//userService.saveUser();
//System.out.println(kat.get(0).getParentKategory().);
return "admin_home";
}
@ResponseBody
@RequestMapping(value = "/admin_home/imag/{imageId}", method = RequestMethod.GET, produces="imag/*")
public void getImage(@PathVariable Integer imageId, HttpServletResponse response, HttpServletRequest request, HttpSession session, Model model) throws IOException {
response.setContentType("image/jpeg");
//Zdjecie requestedImage = zdjecieService.getZdjecie(2);
//Zdjecie requestedImage = produktyService.getProdukt(imageId).getZdjecie();
List<Produkty> produkty = (List<Produkty>) session.getAttribute("lastFourItems");
//List<Produkty> produkty = (List<Produkty>) request.getAttribute("lastFourItems");
Zdjecie requestedImage = null;
for(Produkty p: produkty)
{
if(p.getId().equals(imageId))
{
requestedImage = p.getZdjecie();
break;
}
}
if(requestedImage != null)
{
InputStream in= new ByteArrayInputStream(requestedImage.getZdjecie());
//System.out.println("input: "+in);
if (in != null) {
IOUtils.copy(in, response.getOutputStream());
}
}
}
}
<file_sep>package com.cebul.jez.model;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.cebul.jez.entity.Kategoria;
@Repository
public class KategorieDao
{
@Autowired
private SessionFactory sessionFactory;
private Session getSessionFactory()
{
return sessionFactory.getCurrentSession();
}
private void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public List<Kategoria> getMainKategory()
{
Session session = getSessionFactory();
Query query = session.createSQLQuery("SELECT * FROM Kategorie WHERE IdParentKat is null").
addEntity(Kategoria.class);
List<Kategoria> result = query.list();
return result;
}
public Kategoria getMainKategory(Kategoria podkategoria)
{
Session session = getSessionFactory();
Query query = session.createQuery("from Kategoria WHERE id = :idKat")
.setParameter("idKat", podkategoria.getId() );
Kategoria result = (Kategoria) query.list().get(0);
return result;
}
public List<Kategoria> getPodKategory(Integer parent)
{
Session session = getSessionFactory();
Query query = session.createSQLQuery("SELECT * FROM Kategorie WHERE IdParentKat = :parent").
addEntity(Kategoria.class).setParameter("parent", parent);
List<Kategoria> result = query.list();
return result;
}
public Kategoria getKategory(Integer id)
{
Session session = getSessionFactory();
return (Kategoria)session.get(Kategoria.class, id);
}
public boolean addKategoria(Kategoria k)
{
Session session = sessionFactory.getCurrentSession();
boolean exsist = isExist(k);
if(!exsist)
{
session.save(k);
return true;
}
return false;
}
public boolean isExist(Kategoria k)
{
Session session = getSessionFactory();
Query query = session.createSQLQuery("SELECT * FROM kategorie WHERE nazwa = :catname ").
addEntity(Kategoria.class).setParameter("catname", k.getNazwa());
List<Kategoria> result = query.list();
if(!result.isEmpty())
{
return true;
}
return false;
}
public boolean updateCategory(Kategoria kat)
{
Session session = getSessionFactory();
Kategoria updateCat = (Kategoria) session.get(Kategoria.class, kat.getId());
updateCat.setNazwa(kat.getNazwa());
updateCat.setParentKategory(kat.getParentKategory());
session.update(updateCat);
return true;
}
}
<file_sep> function searchFocus()
{
if($('#szukanaFraza').val() == "Wpisz czego szuaksz...")
$('#szukanaFraza').val("");
}
function searchFocusOut()
{
$('#szukanaFraza').val("Wpisz czego szuaksz...");
}
function sprawdzSlowo()
{
var ob = $('#szukanaFraza');
var p = ob.position();
var left = p.left+10;
var top = p.top + 37;
if(ob.val() != "" && ob.val().length >= 3)
{
$.getJSON( "/jez/szukaj/szukaj.json", {"slowo": $('#szukanaFraza').val()})
.done(function( json ) {
var resp = "<ul>";
$.each(json.produkty, function( index, value ) {
//alert( index + ": " + value );
resp += '<li id="li'+index+'" class="test" value="test1">'+value+'</li>';
});
resp += "</ul>";
$('#podpowiedzi').css("top", top).css("left", left).css("display", "block");
$('#podpowiedzi').html(resp);
$('.test').on("mousedown",function(){
var ident = "#"+this.id;
$('#szukanaFraza').val($(ident).html());
});
})
.fail(function( jqxhr, textStatus, error ) {
//alert("error="+error);
});
}else{
ukryjPodpowiedzi();
}
}
function ukryjPodpowiedzi()
{
$('#podpowiedzi').css("display", "none");
}
function ladujPodkategorie()
{
var val = $('#kategoria').val();
$.getJSON( "/jez/dodajProdukt/podkategorie.json", {"podkategory": parseInt(val)})
.done(function( json ) {
var resp = "<option value='0'>WYBIERZ PODKATEGORIE</option>";
$.each(json.kategorie, function( index, value ) {
resp += '<option value="'+value.id+'">'+value.nazwa+'</option>';
});
$('#podkategoria').html(resp);
})
.fail(function( jqxhr, textStatus, error ) {
//alert("error="+error);
});
}<file_sep>package com.cebul.jez.flows;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.User;
import com.cebul.jez.model.UserDao;
import com.cebul.jez.service.KategorieService;
import com.cebul.jez.service.ProduktyService;
import com.cebul.jez.service.UserService;
@Component("flowDodajProdukt")
public class FlowDodajProdukt implements Serializable
{
@Autowired
private UserShortInfo usinfo;
@Autowired
private UserService userService;
@Autowired
private KategorieService kategorieService;
@Autowired
private ProduktyService produktyService;
private List<Kategoria> katDodaj;
private Integer kategoriaId;
private Integer podkategoriaId;
private String dezycja;
public String getDezycja() {
return dezycja;
}
public void setDezycja(String dezycja) {
this.dezycja = dezycja;
}
public List<Kategoria> getKatDodaj() {
return katDodaj;
}
public void setKatDodaj(List<Kategoria> katDodaj) {
this.katDodaj = katDodaj;
}
public boolean sprawdzUsera()
{
if(usinfo.getId() == null)
return true;
return true;
}
public Date getCurrDate()
{
Date dat = new Date();
SimpleDateFormat simpleDateHere = new SimpleDateFormat("yyyy-MM-dd");
String d = simpleDateHere.format(dat);
try {
dat = simpleDateHere.parse(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(d);
System.out.println(dat);
return dat;
}
public void saveProduktK(ProduktyKupTeraz p)
{
produktyService.saveProduktKupTeraz(p);
}
public User getUser()
{
User u = userService.getUser(usinfo.getId());
//System.out.println("testy Wywolania w dlowDdoaj "+usinfo.getId());
return u;
}
public List<Kategoria> getMainKategory()
{
System.out.println("testy main kategory");
katDodaj = kategorieService.getMainKategory();
return katDodaj;
}
public List<Kategoria> getKat()
{
System.out.println("testy innej kategory");
return new ArrayList<Kategoria>();
}
}
<file_sep>package com.cebul.jez.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cebul.jez.entity.User;
import com.cebul.jez.model.UserDao;
@Service
public class UserService
{
@Autowired
UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional
public void saveUser()
{
userDao.saveUser();
}
@Transactional
public boolean addUser(User u)
{
return userDao.addUser(u);
}
@Transactional
public void activeUser(Integer id)
{
userDao.activeUser(id);
}
@Transactional
public User getUser(String login)
{
return userDao.getUser(login);
}
@Transactional
public boolean isUserExsist(String login)
{
return userDao.isUserExsist(login);
}
@Transactional
public User getUser(Integer id)
{
return userDao.getUser(id);
}
@Transactional
public boolean updateUser(User user)
{
return userDao.updateUser(user);
}
@Transactional
public void setAdmin(String login)
{
userDao.setAdmin(login);
}
}
<file_sep>package com.cebul.jez.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name="Komentarze")
public class Komentarz
{
@Id
@GeneratedValue
@Column(name="Id")
private Integer id;
@Column(name="Komentarz", columnDefinition="TEXT")
@NotNull
private String komentarz;
@Column(name="Ocena")
@NotNull
private Integer ocena;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="IdNadaw")
private User nadawca;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="IdOdb")
private User odbiorca;
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="IdProd")
private Produkty produkt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getKomentarz() {
return komentarz;
}
public void setKomentarz(String komentarz) {
this.komentarz = komentarz;
}
public Integer getOcena() {
return ocena;
}
public void setOcena(Integer ocena) {
this.ocena = ocena;
}
public User getNadawca() {
return nadawca;
}
public void setNadawca(User nadawca) {
this.nadawca = nadawca;
}
public User getOdbiorca() {
return odbiorca;
}
public void setOdbiorca(User odbiorca) {
this.odbiorca = odbiorca;
}
public Produkty getProdukt() {
return produkt;
}
public void setProdukt(Produkty produkt) {
this.produkt = produkt;
}
}
<file_sep>package com.cebul.jez.useful;
import java.io.Serializable;
import com.cebul.jez.entity.ProduktyLicytuj;
public class JsonLicytacja implements Serializable
{
ProduktyLicytuj prod;
public ProduktyLicytuj getProd() {
return prod;
}
public void setProd(ProduktyLicytuj prod) {
this.prod = prod;
}
public ProduktyLicytuj generateLicytacja()
{
return prod;
}
}
<file_sep>package com.cebul.jez.flows;
import java.io.Serializable;
import java.util.List;
import com.cebul.jez.entity.Kategoria;
public class FlowDodajProduktForm implements Serializable
{
private String decyzja;
private List<Kategoria> katDodaj;
public List<Kategoria> getKatDodaj() {
return katDodaj;
}
public void setKatDodaj(List<Kategoria> katDodaj) {
this.katDodaj = katDodaj;
}
public String getDecyzja() {
return decyzja;
}
public void setDecyzja(String decyzja) {
this.decyzja = decyzja;
}
}
<file_sep>package com.cebul.jez.useful;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
/**
* Klasa wysyła mail w którym znajduje się link potwierdzajacy torzsamość i uaktywniający
* konto użytkownika.
* używa mechanizmu DI do wstrzykiwania zależnosći
* @author Mateusz
*
*/
@Component
public class Mail
{
@Autowired
private MailSender mailSender;
/**
* Setter ustawiajacy wartość pola mailSender
* @param mailSender
*/
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
/**
* Wysyła maila na podany adres, używana do wysyłania prostych wiadomosci nie zawierających HTML'a
* @param from z jakiego maila ma zostac wysłany mail
* @param to na jaki adres email ma zostać wysłana wiadomość
* @param subject temat wiadomosći
* @param msg właściwa treść wiadomości
* @throws MessagingException wyrzuca wyjatek gdy wysłanie maila jest niemożliwe
*/
public void sendMail(String from, String to, String subject, String msg) throws MessagingException {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
mailSender.send(message);
}
/**
* Wysyła maila na podany adres, umożliwia wysyłanie wiadomości zawierajach tagi HTML
* @param url zawiera tag <a> przygotowany w taki sposób aby umożliwić aktywację konta użytkownika
* @param from mail z jakiego nalezy wysłać wiadomość
* @param to mail na jaki należy wysłać wiadomość
* @param subject temat wiadomości
* @param msg właściwa treść wiadomości
* @throws Exception wyjatek jest wyrzucany gdy nie można wysłać wiadomości
*/
public void sendMimeMessage(String url, String from, String[] to, String subject, String msg) throws Exception{
MimeMessage mime = ((JavaMailSenderImpl) this.mailSender).createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mime, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
//String adress = "http://"+pageContext.request.serverName+":"+pageContext.request.serverPort+pageContext.request.contextPath;
String htmlText = "<p>Aby konto zostało aktywowane prosimy kliknąć poniższy link:</p>" +
"<a href='"+url+"'>Aktywuj konto</a>";
helper.setText(htmlText,true);
((JavaMailSenderImpl)this.mailSender).send(mime);
}
}
<file_sep>package com.cebul.jez.model;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.cebul.jez.entity.Kategoria;
import com.cebul.jez.entity.Produkty;
import com.cebul.jez.entity.ProduktyKupTeraz;
import com.cebul.jez.entity.ProduktyLicytuj;
import com.cebul.jez.entity.User;
import com.cebul.jez.entity.Zdjecie;
@Repository
public class TestDatabaseDao
{
@Autowired
private SessionFactory sessionFactory;
private Session getSessionFactory()
{
return sessionFactory.getCurrentSession();
}
private void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public void testData1()
{
Session session = getSessionFactory();
Kategoria k = new Kategoria("Elektronikaasda", null);
Kategoria k1 = new Kategoria("Dom1234", k);
k1.setParentKategory(k);
session.save(k);
session.save(k1);
User u = (User) session.get(User.class, 2);
Zdjecie z = new Zdjecie();
//z.setZdjecie(new File("test.txt"));
session.save(z);
ProduktyKupTeraz p = new ProduktyKupTeraz("pierwszy produkt", "taki sobie tma pridkut",
12.0, new Date(), k, z, u);
session.save(p);
ProduktyLicytuj p1 = new ProduktyLicytuj("drugi produkt", "dfrugii grudii taki sobie tma pridkut",
12.0, new Date(), k, z, u, new Date());
List<Zdjecie> zdj = new ArrayList<Zdjecie>();
zdj.add(z);
p1.setZdjecia(zdj);
Produkty prod = (Produkty) session.get(Produkty.class, 1);
if(prod instanceof ProduktyKupTeraz)
{
System.out.println("jestem kup teraz");
ProduktyKupTeraz pk = (ProduktyKupTeraz) prod;
System.out.println(pk.isKupiony());
}
if(prod instanceof ProduktyLicytuj)
{
System.out.println("jestem licytuj");
}
session.save(p1);
}
}
<file_sep>package com.cebul.jez.useful;
import java.util.List;
import com.cebul.jez.entity.Kategoria;
public class JsonKat
{
private Kategoria kategorie[];
public Kategoria[] getKategorie() {
return kategorie;
}
public void setKategorie(Kategoria[] kategorie) {
this.kategorie = kategorie;
}
public void generateKategorie(List<Kategoria> k)
{
int size = k.size();
kategorie = k.toArray(new Kategoria[size]);
}
}
| 853b6293319b4251a6d1ebc8273229898751d7d0 | [
"JavaScript",
"Java"
] | 25 | Java | cebul4/com.cebul.jez | 8158897a5d1aeeee9f2e438ccf39876391f5f7e6 | 1d64379495044818a17d89d637509b976662aa1b |
refs/heads/master | <file_sep># Applivery cordova sample
## Android config
### Step 1
Add applivery dependency in `app/build.gradle`
```groovy
dependencies {
implementation fileTree(dir: 'libs', include: '*.jar')
// SUB-PROJECT DEPENDENCIES START
implementation(project(path: ":CordovaLib"))
// SUB-PROJECT DEPENDENCIES END
implementation 'com.applivery:applvsdklib:x.x.x'
}
```
### Step 2
Init applivery in your _Application_ class with your `APPLIVERY_APP_TOKEN`
```java
public class AppliverySampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
initApplivery();
}
private void initApplivery() {
Applivery.init(this, BuildConfig.APPLIVERY_APP_TOKEN, false);
Applivery.setCheckForUpdatesBackground(true);
Applivery.enableShakeFeedback();
Applivery.enableScreenshotFeedback();
}
}
```
### Step 3
Be sure that you added your _Application_ class in your `AndroidManifest.xml`
```xml
<application
android:name=".AppliverySampleApplication"
android:hardwareAccelerated="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
tools:ignore="GoogleAppIndexingWarning">
```
# License
Copyright (C) 2019 Applivery
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.<file_sep>package io.cordova.hellocordova;
import android.app.Application;
import com.applivery.applvsdklib.Applivery;
public class AppliverySampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
initApplivery();
}
private void initApplivery() {
Applivery.init(this, BuildConfig.APPLIVERY_APP_TOKEN, false);
Applivery.setCheckForUpdatesBackground(true);
Applivery.enableShakeFeedback();
Applivery.enableScreenshotFeedback();
}
}
| 15699973d0e3091efe86eadf260198ac4a5acc5b | [
"Markdown",
"Java"
] | 2 | Markdown | applivery/applivery-cordova-sample | 5f953ce592eca2ec38691fbd0761a0a7e492ddc1 | 08377e8d71235766d2355359e6e650ea5dead9aa |
refs/heads/master | <file_sep># Place for differential expression code
<file_sep>import os
import synapseclient
import synapseutils
import glob
import re
import time
from synapseclient import Folder, File
#for synapse
syn = synapseclient.login()
BAMNAMELIST = config["inFileName"]
print ('file list:',BAMNAMELIST)
print ('lst:', BAMNAMELIST[0])
#change this to your home directory
homeDir = '/home/centos/p_3'
#ID of the folder of the BAM folder we want to process
BAMFolderSynId = 'syn4486995'
print ('BAM folder syn ID:', BAMFolderSynId)
#get all the BAM file IDs
walkedPath = synapseutils.walk(syn, BAMFolderSynId)
BAMIDLIST = []
nameIdDict = {}
for dirpath, dirname, filename in walkedPath:
for (bamFileName,bamFileSynId) in filename:
if bamFileName != BAMNAMELIST:
continue
BAMIDLIST.append(bamFileSynId)
nameIdDict[bamFileName] = bamFileSynId
print ('BAM ID list:', BAMIDLIST)
rule all:
input:
a=expand('/tmp/{bamFile}_files_uploaded.txt', bamFile=BAMNAMELIST)
rule download_BAM_File:
input:
a = 'need.txt'
output:
b = touch('{bamFile}_LOG.txt')
run:
print ('Downloading file synapse ID:',wildcards.bamFile)
downloadDir = '/tmp'
entity = syn.get(nameIdDict[wildcards.bamFile], downloadLocation = downloadDir)
#touch file
os.system('touch ' + output.b)
rule convert_BAM_to_Fastq:
input:
a='{bamFile}_LOG.txt'
output:
a = touch('/tmp/{bamFile}.R1.fastq'),
b = touch('/tmp/{bamFile}.R2.fastq')
params:
samToFastqCmd='/home/centos/bin/picard.jar SamToFastq', inBamFile = '/tmp/{bamFile}'
shell:
"""
java -jar {params.samToFastqCmd} I={params.inBamFile} FASTQ={output.a} SECOND_END_FASTQ={output.b} VALIDATION_STRINGENCY=LENIENT ;
touch {output.a} ;\
touch {output.b} ;\
"""
rule align_star:
input:
a = '/tmp/{bamFile}.R1.fastq',
b = '/tmp/{bamFile}.R2.fastq'
output:
a = touch('/tmp/{bamFile}_STAR_Aligned.sortedByCoord.out.bam')
params:
starPath = '/home/centos/miniconda/bin/',
outNamePrefix = '/tmp/{bamFile}_STAR_',
numThreads = '16',
genomeDir='/home/centos/data_2/STAR_MM10',
inBamFile = '/tmp/{bamFile}'
shell:
"""
{params.starPath}STAR --runThreadN {params.numThreads} --genomeDir {params.genomeDir} --outSAMtype BAM SortedByCoordinate --outFileNamePrefix {params.outNamePrefix} --readFilesIn {input.a} {input.b} ; \
touch {output.a}
"""
rule sort_by_read_name:
input:
a = '/tmp/{bamFile}_STAR_Aligned.sortedByCoord.out.bam'
output:
a = touch('/tmp/{bamFile}_STAR_Aligned.sortedByReadName.bam')
params:
sortCmd = '/home/centos/miniconda/bin/samtools sort'
shell:
"""
{params.sortCmd} -n -o {output.a} {input.a} ;\
touch {output.a}
"""
rule count_reads_HTSeq:
input:
a = '/tmp/{bamFile}_STAR_Aligned.sortedByReadName.bam'
output:
a=touch('/tmp/{bamFile}_counts.txt')
params:
TRANSCRIPTS = '/home/centos/data_2/mm10_ERCC92_tab.gtf', samToolsCmd = '/home/centos/miniconda/bin/samtools',htseqCmd = '/home/centos/miniconda/bin/htseq-count'
shell:
"""
{params.samToolsCmd} view {input.a} | {params.htseqCmd} -q -s no - {params.TRANSCRIPTS} > {output.a}
touch {output.a}
"""
rule run_FastQC:
input:
a = '/tmp/{bamFile}.R1.fastq',
b = '/tmp/{bamFile}.R2.fastq',
c = '/tmp/{bamFile}_counts.txt'
output:
a = touch('/tmp/{bamFile}_FastQC')
params:
fastQCCmd = '/home/centos/miniconda/FastQC/fastqc'
shell:
"""
#make the directory
mkdir {output.a} ;
{params.fastQCCmd} {input.a} -o {output.a} ;
{params.fastQCCmd} {input.b} -o {output.a} ;
touch {output.a}
"""
rule upload_files:
input:
a = '/tmp/{bamFile}_FastQC'
output:
a = touch('/tmp/{bamFile}_files_uploaded.txt')
run:
print ('Uploading files')
#copy files back to local directory
os.system("echo 'Uploading following files:' >> " + output.a)
#make another folder for this bam file, test 7 = syn8525762, test 8 = syn8669305, test_9 = syn8687215, test_10= syn8697754
bamFileFolder = Folder(name=wildcards.bamFile+'_RNAseq', parent='syn8697754')
bamFileFolder = syn.store(bamFileFolder)
#make a fastQC results folder
fastQCFolder = Folder(name='fastQC', parent=bamFileFolder)
fastQCFolder = syn.store(fastQCFolder)
#make a STAR results folder
STARfolder = Folder(name='STAR', parent=bamFileFolder)
STARfolder = syn.store(STARfolder)
#########
#go thru files
for file in glob.glob("/tmp/*"+wildcards.bamFile+"*"):
#skip if file size is zero, need to check which one are those
if os.stat(file).st_size == 0:
cmd = "echo empty file '" + file + " ' >> " + output.a
os.system(cmd)
continue
#skip the files_uploaded file
if re.search(r'files_uploaded',file):
continue
#skip the STARtmp folder
if re.search(r'STAR_STARtmp', file):
#delete this tmp folder
cmd = "rm -r " + file
os.system(cmd)
continue
#skip uploading the original BAM file
if file == wildcards.bamFile:
cmd = "rm " + file
os.system(cmd)
continue
#upload the fastQC folder files
if re.search(r'FastQC', file):
print ('fastqc:', file)
#store the fastq files to the folder after looping in it
for fName in os.listdir(file):
upFile = File(path=os.path.join(file,fName), parent=fastQCFolder)
upFile = syn.store(upFile)
cmd = "echo uploading '" + fName + " ' >> " + output.a
os.system(cmd)
#delete the files after uploading
cmd = "rm -r " + file
os.system(cmd)
continue
#put the STAR files into a folder as well
if re.search(r'STAR', file):
print ('STAR:',file)
upFile = File(path=file, parent=STARfolder)
upFile = syn.store(upFile)
cmd = "echo uploading '" + file + " ' >> " + output.a
os.system(cmd)
cmd = "rm -r " + file
os.system(cmd)
continue
#copy rest of the BAM files
cmd = "echo uploading '" + file + " ' >> " + output.a
os.system(cmd)
upFile = File(path=file, parent=bamFileFolder)
upFile = syn.store(upFile)
cmd = "rm -r " + file
os.system(cmd)
#copy back to home directory
os.system("cp " + output.a + ' ' + homeDir)
<file_sep>import os
import synapseclient
import synapseutils
#time snakemake --cluster qsub --jobs 10
#for synapse
#parent/project folder synapse ID
SYNPARENTID = "syn3270268"
syn = synapseclient.login()
#create a synapse folder for this BAM folder
#this is the synapse parent folder ID which has BAM folder synapse ID; for pilot use mouse BAM files
BAMFolderSynId = 'syn4486995'
#get all the BAM file IDs
walkedPath = synapseutils.walk(syn, BAMFolderSynId)
BAMNAMELIST = []
BAMIDLIST = []
nameIdDict = {}
#loop thru all the files in the BAM folder
for dirpath, dirname, filename in walkedPath:
for (bamFileName,bamFileSynId) in filename:
#for testing process one BAM file
if bamFileName != '112-10.FCC5F7UACXX_L6_IGTCCGC.snap.bam':
continue
BAMNAMELIST.append(bamFileName)
BAMIDLIST.append(bamFileSynId)
nameIdDict[bamFileName] = bamFileSynId
print ('BAM ID list:', BAMIDLIST)
rule all:
input:
a=expand('/home/centos/p_2/{bamFile}_files_uploaded.txt', bamFile=BAMNAMELIST),
rule download_BAM_File:
input:
a='tmp.txt',
output:
a='/home/centos/p_2/bamFolderTest_2/{bamFile}'
run:
print ('Downloading file synapse ID:',wildcards.bamFile)
downloadDir = 'bamFolderTest_2'
entity = syn.get(nameIdDict[wildcards.bamFile], downloadLocation = downloadDir)
rule convert_BAM_to_Fastq:
input:
#create a results folder 'p_2, 'p_2 is the folder where the output results are directed
a='/home/centos/p_2/bamFolderTest_2/{bamFile}'
output:
a = '/home/centos/p_2/{bamFile}.R1.fastq',
b = '/home/centos/p_2/{bamFile}.R2.fastq'
params:
samToFastqCmd='/home/centos/bin/picard.jar SamToFastq',fastqFolderPath = '/home/centos/p_2/fastqFiles'
shell:
"""
java -jar {params.samToFastqCmd} I={input.a} FASTQ={output.a} SECOND_END_FASTQ={output.b} VALIDATION_STRINGENCY=LENIENT
"""
rule align_star:
input:
a = '/home/centos/p_2/{bamFile}.R1.fastq',
b = '/home/centos/p_2/{bamFile}.R2.fastq'
output:
a = '/home/centos/p_2/{bamFile}_STAR_Aligned.sortedByCoord.out.bam'
#a = '{bamFile}_STAR_log'
#b = 'synId_STAR_Log.progress.out'
#c = 'synId_STAR_Log.final.out'
#d = 'synId_STAR_SJ.out.tab'
#e = 'synId_STAR_Log.out'
params:
starPath = '/home/centos/miniconda/bin/', outNamePrefix = '{bamFile}_STAR_', numThreads = '8',
genomeDir='/home/centos/data_2/STAR_MM10'
shell:
"""
{params.starPath}STAR --runThreadN {params.numThreads} --genomeDir {params.genomeDir} --outSAMtype BAM SortedByCoordinate --outFileNamePrefix {params.outNamePrefix} --readFilesIn {input.a} {input.b} ; \
"""
rule sort_by_read_name:
input:
a = '/home/centos/p_2/{bamFile}_STAR_Aligned.sortedByCoord.out.bam'
output:
a = '/home/centos/p_2/{bamFile}_STAR_Aligned.sortedByReadName.bam'
params:
sortCmd = '/home/centos/miniconda/bin/samtools sort'
shell:
"""
{params.sortCmd} -n -o {output.a} {input.a}
"""
rule count_reads_HTSeq:
input:
a = '/home/centos/p_2/{bamFile}_STAR_Aligned.sortedByReadName.bam'
output:
a='/home/centos/p_2/{bamFile}_counts.txt'
params:
TRANSCRIPTS = '/home/centos/data_2/mm10_ERCC92_tab.gtf', samToolsCmd = '/home/centos/miniconda/bin/samtools',htseqCmd = '/home/centos/miniconda/bin/htseq-count'
shell:
"""
{params.samToolsCmd} view {input.a} | {params.htseqCmd} -q -s no - {params.TRANSCRIPTS} > {output.a}
"""
rule run_FastQC:
input:
a = '/home/centos/p_2/{bamFile}.R1.fastq',
b = '/home/centos/p_2/{bamFile}.R2.fastq',
c = '/home/centos/p_2/{bamFile}_counts.txt'
output:
a = '/home/centos/p_2/{bamFile}_FastQC'
params:
fastQCCmd = '/home/centos/miniconda/FastQC/fastqc'
shell:
"""
#make the directory
mkdir {output.a} ;
{params.fastQCCmd} {input.a} -o {output.a} ;
{params.fastQCCmd} {input.b} -o {output.a} ;
"""
rule upload_files:
input:
a = '/home/centos/p_2/{bamFile}_FastQC'
output:
a = '/home/centos/p_2/{bamFile}_files_uploaded.txt'
params:
parentId = 'syn8395985', resDir='{bamFile}_RNAseq_res', bamId='{bamFile}', synapseCmd='/home/centos/miniconda/bin/synapse'
shell:
"""
{params.synapseCmd} login -u USER -p PASSWORD --rememberMe;
for f in *{params.bamId}*
do
echo "Uploading $f file..";
printf "Uploading $f file\n" >> {output.a};
#store folder but will need to add annotations as well from original BAM file
#synapse store $f --parentId {params.parentId}
{params.synapseCmd} add $f --parentId {params.parentId};
#delete file later
#rm $f
done ;
"""
<file_sep>require(synapseClient)
synapseLogin()
foo <- data.frame(a=rnorm(10),
b=rnorm(10),
c=rnorm(10),
stringsAsFactors = F)
View(foo)
write.table(foo,
file='exampleData.csv',
quote=F,
row.names=F,
sep=',')
###Create a new folder in the collaboration space
testFolderObj <- synapseClient::Folder(name='Test Data',
parentId='syn7342718')
testFolderObj <- synapseClient::synStore(testFolderObj)
###Grab the Synapse Id of this new folder
folderId<- synapseClient::synGetProperty(testFolderObj,'id')
dataObj <- synapseClient::File(path = 'exampleData.csv',
parentId=folderId)
annos <- list(foo = 'bar',
baz = 'bax',
fileType = 'csv')
synapseClient::synSetAnnotations(dataObj) <- annos
require(githubr)
<file_sep>## Introduction
This will document the steps to start a [CfnCluster](http://cfncluster.readthedocs.io/) for this project.
<file_sep>#!/bin/bash
wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O $HOME/miniconda.sh
bash $HOME/miniconda.sh -b -p $HOME/miniconda
export PATH="$HOME/miniconda/bin:$PATH"
# Add to ec2-user's path
echo 'PATH="$HOME/miniconda/bin:$PATH"' >> $HOME/.bashrc
conda config --add channels conda-forge
conda config --add channels r
conda config --add channels bioconda
conda install -y star=2.5.1b htseq fastqc multiqc
mkdir $HOME/bin
wget https://github.com/broadinstitute/picard/releases/download/2.8.3/picard.jar -O $HOME/bin/picard.jar
echo 'PATH="$PATH:$HOME/bin"' >> $HOME/.bashrc
<file_sep>#!/bin/sh
#fileName=$1
#change home directory
homeDir='/home/centos/p_3'
#make a job dir in the tmp directory
#export TMPDIR=/tmp/$1'_results'
#mkdir -p $TMPDIR
export TMPDIR='/tmp'
#move to tmp dir
cd $TMPDIR
#cp the snake file to tmpdir
cp $homeDir'/Snakefile' $TMPDIR
#touch the need file
touch $TMPDIR/need.txt
source /home/centos/miniconda/envs/py3k/bin/activate py3k
#logFileName=$1'_snakemake.log'
snakemake --force -j --nolock --config inFileName=$1
exit 0
<file_sep># Place for gene set enrichment code
<file_sep>echo homo_sapiens mus_musculus drosophila_melanogaster | sed -e 's/\s\+/\n/g' | xargs -n 1 -I{} sh -c 'mkdir -p $HOME/data/genomes/{} $HOME/data/gene_models/{}'
# Get genomes
curl ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_24/GRCh38.p5.genome.fa.gz > $HOME/data/genomes/homo_sapiens/GRCh38.p5.genome.fa.gz
rsync -avzP rsync://hgdownload.cse.ucsc.edu/goldenPath/dm6/bigZips/dm6.fa.gz $HOME/data/genomes/drosophila_melanogaster
rsync -avzP rsync://hgdownload.cse.ucsc.edu/goldenPath/mm10/bigZips/chromFa.tar.gz $HOME/data/genomes/mus_musculus
# Get gene models
curl ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_24/gencode.v24.annotation.gff3.gz > $HOME/data/gene_models/homo_sapiens/gencode.v24.annotation.gff3.gz
curl ftp://ftp.sanger.ac.uk/pub/gencode/Gencode_human/release_24/gencode.v24.annotation.gtf.gz > $HOME/data/gene_models/homo_sapiens/gencode.v24.annotation.gtf.gz
<file_sep>To run the snakemake file using cfncluster compute nodes:
python run.py
This will call the jobscript.sh bash script which will copy the snakemake file to each computing node.
Will need to add the line in the cfncluster config file to force
each compute node to run a single job only:
[cluster clusterName]
...
extra_json = { "cfncluster" : { "cfn_scheduler_slots" : "1" } }
...
<file_sep>import os
import synapseclient
import synapseutils
import glob
import re
import time
from synapseclient import Folder, File
#log in
syn = synapseclient.login()
BAMFolderSynId = 'syn4486995'
print ('BAM folder syn ID:', BAMFolderSynId)
#get all the BAM file IDs
walkedPath = synapseutils.walk(syn, BAMFolderSynId)
noList = []
BAMNAMELIST = []
BAMIDLIST = []
nameIdDict = {}
c = 0
for dirpath, dirname, filename in walkedPath:
for (bamFileName,bamFileSynId) in filename:
if bamFileName in noList:
continue
BAMNAMELIST.append(bamFileName)
BAMIDLIST.append(bamFileSynId)
nameIdDict[bamFileName] = bamFileSynId
c += 1
#if c == 10:
#break
print ('BAM ID list:', BAMIDLIST)
print ('bam file list:', BAMNAMELIST)
jobScript = 'jobscript.sh'
for fileName in BAMNAMELIST:
#ask for mem_free since STAR needs at least 28G
cmd = 'qsub -pe smp 1 -l mem_free=28.37G ' + jobScript + ' ' + fileName
print ('cmd:' + cmd)
os.system(cmd)
#sleep to allow job distribution correctly on compute nodes, might not be needed after updating the cfncluster config file
time.sleep(1000)
<file_sep>## Introduction
[Packer](https://www.packer.io/) automates the creation of any type of machine image. Here, we use Bash scripts to provision an Amazon AMI and install necessary software and data. This requires an [Amazon AWS account](https://aws.amazon.com).
This instance has two provisioners:
1. [Software](software_provisioner.sh) which uses [Miniconda](https://conda.io/docs/) to install `fastqc`, `multiqc`, `htseq`, and `star=2.5.1b` from the [Bioconda Channel](https://bioconda.github.io/). Because of licensing restrictions, `Picard` is downloaded from the Broad Institute.
2. [Data](data_provisioner.sh) gets genomes and transcript gene models.
## Usage
1. Create an [Amazon AWS account](https://aws.amazon.com).
1. [Fork](http://help.github.com/fork-a-repo/) and clone this repository to your machine.
1. Install [packer](http://www.packer.io/docs/installation.html).
1. Amazon AWS credentials are required to be set as environment variables for `AWS_ACCESS_KEY` and `AWS_SECRET_KEY`.
1. Change the root directory of the repository you cloned, and run:
```
packer build packer/config.json
```
If successful, this will create an Amazon AMI in your account that can be used to launch an Amazon EC2 instance.
The system is designed to be used as a single user (`centos`). All software and data is installed for the this user.
## Debugging
If the build fails because an AMI cannot be found, check that source AMI is current, look here: https://github.com/awslabs/cfncluster/blob/master/amis.txt and update the `builders` section `source_ami` in [config.json](config.json).
<file_sep># Place for RNAseq reprocessing Code
#come up with conventions for naming propagations
#FASTQ generation
BAM files were reverted to FASTQ using picard.
#FASTQ QC
Basic Fastqc
1) Number of repetitive elements
2) Sequencing quality
Use the outputs for trimming of reads if necessary.
#Alignment
##Human
FASTQ files were aligned to GRCh38 with Gencode24 gene models using STAR/2.5.1b.
##Mouse
FASTQ files were aligned to mm10 with ENSEMBL gene models using STAR/2.5.1b.
##Fruit fly
FASTQ files were aligned to dm6 with UCSC gene models using STAR/2.5.1b.
##iPSC
FASTQ files were aligned to GRCh38 with Gencode24 gene models using STAR/2.5.1b.
#Alignment Metrics
Output from STAR/TopHat
Quantitation
##Human and iPSC
Alignments were counted to Gencode 24 gene models using star - htseq
##Mouse
Alignments were counted to Ensembl gene models using star - htseq
##Fruit fly
Alignments were counted to UCSC gene models using star - htseq
| ed6910c3af46546e649d8086d1b4552bdbcbdbb1 | [
"Markdown",
"Python",
"R",
"Shell"
] | 13 | Markdown | Sage-Bionetworks/BaylorSage | 5f290e0aa4910c0fa1c3d7abc2231f79dd0f74ab | 1ba1a3c9b045e041499aff6ad2d89b55d77094c8 |
refs/heads/main | <repo_name>phendji/angular-using-express-as-mock-server<file_sep>/server/server.js
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
const config = {
port: process.env.PORT || 9090
};
const latencies = {
technologyLists: 0
}
app.set('config', config);
app.set('latencies', latencies);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Add CORS headers to the response
function setupCorsHeaders(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-requested-With, Content-Type, Accept, Authorization, applicationName');
res.header('Content-Type', 'application/json');
// res.header("Content-Security-Policy", "img-src 'self' data:; default-src 'self'");
res.header('Access-Control-Allow-Origin', '*');
if(req.method === 'OPTIONS') {
res.status(200).end();
} else {
next();
}
}
app.all('/*', setupCorsHeaders);
// For each api file js, create your own route with express
const apiFiles = fs.readdirSync('./server/api');
apiFiles.forEach(apiFile => {
if (apiFile.endsWith('.js')){
require('./api/' + apiFile)(app);
}
});
if (!module.parent) { // Launch server when i run directly, parent is deprecated, use module.childre (see : https://nodejs.org/api/modules.html#moduleparent)
console.log('Starting server with nodeJS');
startServer(app, config);
process.on('msg', msg => {
if(msg !== 'shutdown')
return;
stopServer(server);
})
} else {
console.log('Exporting server config options');
exports.app = app;
exports.config = config;
exports.startServer = startServer;
exports.stopServer = stopServer;
}
function startServer(app, config) {
app.listen(config.port, () => {
console.log(`Starting server listening on port ${config.port} - ${app.settings.env} mode.`);
});
};
function stopServer(server) {
console.log('Server is down, force shutdown please...');
server.close();
}
<file_sep>/server/apiUrl.js
'use strict';
module.exports.URL = {
API_WITHOUT_TOKEN: {
NAME_APP_TECHNOLOGY_LISTS: '/api/technologies'
},
API_WITH_TOKEN: {
}
};
<file_sep>/server/api/technology-lists.js
'use strict';
const srvHelper = require('../serverHelper.js');
const environment = require('../apiUrl.js');
module.exports = app => {
app.get(`${environment.URL.API_WITHOUT_TOKEN.NAME_APP_TECHNOLOGY_LISTS}`, (req, res) => {
setTimeout(srvHelper.readContentJsonFile, app.settings.latencies.technologyLists, res, `./server/api/technology-lists/technology-lists.json`);
});
};
<file_sep>/server/serverHelper.js
'use strict';
const fs = require('fs');
module.exports.readContentJsonFile = (res, jsonFile) => {
if(fs.existsSync(jsonFile)) {
fs.readFile(jsonFile, (err, data) => {
if (err) throw err;
res.send(data.toString());
})
} else {
res.status(404).send("Not found");
}
}
| db41e9c9624365a0834e5f559a887c93ca43fa80 | [
"JavaScript"
] | 4 | JavaScript | phendji/angular-using-express-as-mock-server | f19902068b874b99ba4806f81f49936db6b2427b | 7050aa52f0f4d7d906a5ba2e608d0c2f30d178ef |
refs/heads/master | <file_sep># Temperature Sensing Device
---
__This is a prototype of temperature sensing device with a custom__
__temperature sensor. Files attached to this project:__
* TempSensorCode.c - source code for PIC18F45K22
* tempSensingDevice.dch - Shcematic
* tempSensingDevicePCBLayout.dip - PCB layout file
* tcp_socket_connection.PY - python file with a single connection
* TCP listening socket
### Source Code
---
Source code for a microcontrokkercan be founde [here](https://github.com/SmashKPI/Temperature-Sensing-Device/blob/master/TempSensorCode.c)
Code example of a server is [here.](https://github.com/SmashKPI/Temperature-Sensing-Device/blob/master/tcp_socket_connection.PY)
### Scematic
---
You can reach a completed schematic by clicking on [this link](https://github.com/SmashKPI/Temperature-Sensing-Device/blob/master/tempSensingDevice.dch)
<file_sep>// &&& Temperature Sensor Circuit &&&&&&&&&&&&&&&&&&&&&&&
/********************************************************
File name: TempSensor.c
Author: DTsebrii
Date: 23/APR/2020
Modified: DTsebrii, 01/22/2021
Description: The code for a temperature sensor circuit. Every second
new sample is taken, after that the program waits for
collecting first 60 samples and then is calculating
the average sample. Every minute the collected data
sends by ESP8266.
********************************************************/
// *** Libraries ****************************************
#include <stdlib.h>
#include <stdio.h>
#include <p18f45k22.h>
#include <usart.h>
// *** Constants ***************************************
#define TRUE 1
#define FALSE 0
#define TMR0FLAG INTCONbits.TMR0IF
#define HIGHBIT 0x0B
#define LOWBIT 0xDC
#define RC1BYTE RCREG1
#define RC1FLAG PIR1bits.RC1IF
#define BUFFSIZE 30
#define MINUTE 60
// String parameters
#define ADDYTO 1
#define MYADDY 1
// ESP response
#define RESPONCES 5
#define OK 0
#define ERROR 1
#define FAIL 2
#define WIFICONNECTED 3
#define WIFIGOTIP 4
// ADC constants
#define ADCMASK 0x83
#define TENBITS 1024
#define MAXVOLT 5
#define MINTEMP 100
#define MAXTEMP 100
#define TSLOPE 0.025
#define TOFFSET 2.5
#define ADCRES 0.0048 // 5/1024
// Object constant
#define TEMPCHAN 0x01
#define SAMPSIZE 20
// WDT Constants
#define WDTPSV 0x0C // PSV 1 to 4096
// Interrupt Routine
#define TWOBITSON 0xC0
void ISR (); //calling the prototype for an interrupt function
#pragma code int_vector = 0x008
//*** int_vector*********************************************
/*Author: CTalbot
Date: 14/MAR/2020
Description: Calling the ISR function
Input: None
Output: None
*************************************************************/
void int_vector (void)
{
_asm
GOTO ISR
_endasm
}//eo int_vector::
#pragma code
// *** Global variables *********************************
// Sensor Object
typedef struct temperatureSensor
{
int averageSamp; // To store the current average value
char counter; // To move through the array
int samples[ SAMPSIZE ]; // Array of samples
} tempSen_t;
tempSen_t tmprSys;
// AT Commands
rom char *AT = "AT\r\n"; // Check the status of ESP module. OK is a respond
rom char *RST = "AT+RST\r\n"; // Check the status of ESP module. OK is a respond
rom char *wifiMode = "AT+CWMODE=1\r\n"; // Setup the wifi mode to station mode
rom char *connectWiFi = "AT+CWJAP=\"SSID\",\"PSSWD\"\r\n"; // Replace SSID & PSSWD by Wi-Fi name and password
rom char *connectTCP = "AT+CIPSTART=\"TCP\",\"HOST\",PORT\r\n"; // Replace HOST & PORT by host IPv4 & port number
rom char *closeTCP = "AT+CIPCLOSE\r\n"; // Close the server connection
char timeFlag = FALSE; // To count every second
char averageFlag = FALSE; // Flag to signalaze that sampling array is full
char sendFlag = FALSE;
char timer = 0; // To calculate one minute to send the data
char rcBuffer[ BUFFSIZE ];
// *** Functions ****************************************
/*** interruptSetup *******************************************************************************
Author: DTsebrii
Date: 14/MAR/2020
Modified: 23/APR/2020
Description:Function to set the INTCON register parameters
Input: None
Output: None
*********************************************************************************************/
void interruptSetup (void)
{
//Config TMR0 interrupt
INTCON |= 0x20;
INTCON2 &= 0xFB;
//Global Interrupts
INTCON |= TWOBITSON; // 0xC0
}// eo configInterrupt::
/*** oscSetup *******************************************************************************
Author: DTsebrii
Date: 12/MAR/2020
Description:Function to set the oscilograph parameters
Input: None
Output: None
*********************************************************************************************/
void oscSetup (void)
{
OSCCON = 0x52; // Fosc = 4MHz
OSCCON2 = 0x04;
OSCTUNE = 0x80;
while( OSCCONbits.HFIOFS!=1 );
}// eo oscSetup::
/*** timerSetup *******************************************************************************
Author: DTsebrii
Date: 12/MAR/2020
Description:Function to set the TMR0 parameters
Input: char lowBit and highBit - TMRH and TMRL bits value
Output: None
*********************************************************************************************/
void timerSetup ( char lowBit, char highBit )
{
T0CON = 0x93; //t0 enabled, 16 bit, clkout, 16 psv
TMR0H = highBit;
TMR0L = lowBit;
TMR0FLAG = FALSE; //Turn back to the zero after event happens
}// eo timerSetup::
/*** serialSetup *******************************************************************************
Author: DTsebrii
Date: 12/MAR/2020
Description:Function to set the serial communication parameters
to communicate with ESP8266
Input: None
Output: None
*********************************************************************************************/
void serialSetup()
{
SPBRG= 8; // Sets it to 4MHZ and 115k Baudrate
TXSTA1= 0x26; // BRGH = 1
RCSTA1= 0x90;
BAUDCON1= 0x48; // BRG16 = 1
}// eo serialSetup::
/*** adcSetup *******************************************************************************
Author: DTsebrii
Date: 12/MAR/2020
Description:Function to set the ADC parameters
Input: None
Output: None
*********************************************************************************************/
void adcSetup (void)
{
ADCON0|= 0x01;// ADC enable
ADCON1 = 0x00;
ADCON2 = 0xA9;// 12 TAD right just F/8
}// eo adcSetup::
/*** portSetup *******************************************************************************
Author: DTsebrii
Date: 12/MAR/2020
Modified: DTsebrii, 30/MAR/2020
Description: Function to set the ports parameters
Input: None
Output: None
*********************************************************************************************/
void portSetup()
{
//PORTA
ANSELA = 0x02; // RA1 is temperature sensor
LATA = 0x00; // No input voltage
TRISA = 0xFF; //All input
//PORTB
ANSELB = 0x00;
LATB = 0x00;
TRISB = 0xFF;
//PORTC
ANSELC = 0x00;
LATC = 0x00;
TRISC = 0xFF;
//PORTD
ANSELD = 0x00;
LATD = 0x00;
TRISD = 0xFF;
//PORTE
ANSELE = 0x00;
LATE = 0x00;
TRISE = 0xFF;
}// eo portSetup::
/*** initObj *******************************************************************************
Author: DTsebrii
Date: 23/APR/2020
Modified: None
Description: Function to initialize the data structure object
Input: sptr pointer to data structre object
Output: None
*********************************************************************************************/
void initObj( tempSen_t *sptr )
{
/*
object:
samples;
averagesamp;
counter;
*/
char cnt;
// Non iterational part
sptr->averageSamp = FALSE;
sptr->counter = FALSE;
// Iterational part
for( cnt = 0; cnt<SAMPSIZE; cnt++ )
sptr->samples[ cnt ] = FALSE;
} // eo initObj::
/*****************************************************************
Name: resetWDT
Author: DTsebrii
Date: 11/MAY/2020
Description: Turn OFF and ON the WDT
Input: None
Output: None
*****************************************************************/
void resetWDT()
{
WDTCON = FALSE;
WDTCON = TRUE;
} // eo resetWDT::
/*****************************************************************
Name: systemSetup
Author: DTsebrii
Date: 23/APR/2019
Description: Call all initialize/ config functions
Input: None
Output: None
*****************************************************************/
void systemSetup()
{
// Hardwere part
oscSetup(); // 4MHZ
portSetup();
serialSetup();
adcSetup(); // 12TAD Fosc/8
timerSetup( LOWBIT, HIGHBIT ); // 1 sec 16PSV
interruptSetup();
// Software part
initObj( &tmprSys );
} // systemSetup::
//---------espGetC-------------------------------------
/*----------------------------------------------
Author: DTsebrii
Date: 03/02/2020
Modified: DTsebrii, 27/MAR/2020
Description:Collecting a character sent back
Input: None
Output: char RCREG1 byte
--------------------------------------------------------------*/
char espGetC()
{
// Prevent the overrun
if(RCSTA1bits.OERR)
{
RCSTA1bits.CREN = FALSE;
RCSTA1bits.CREN = TRUE;
}
resetWDT(); // To check the connection stability
while( !RC1FLAG );
WDTCON = FALSE; // Stop watchdog timer
return RC1BYTE;
} // eo espGetC::
//---------isWiFiReady-------------------------------------
/*----------------------------------------------
Author: DTsebrii
Date: 03/02/2020
Modified: DTsebrii, 10/MAR/2020
Description:Waiting till ESP8266 return "OK"
Input: None
Output: TRUE
--------------------------------------------------------------*/
char isWiFiReady()
{
while( espGetC() != 'O');
while( espGetC() != 'K' );
return TRUE;
} //eo isWiFiReady::
/*** espSetConnection ****************************************************************************
Author: DTsebrii
Date: 31/MAY/2020
Description: Prompt the commands required to set the WiFi connection
Input: None
Output: None
*************************************************************************************************/
void espSetConnection()
{
printf((const rom far char *)"%S", AT);
if( isWiFiReady() )
{
printf((const rom far char *)"%S", wifiMode);//set station wifi mode
isWiFiReady();
printf((const rom far char *)"%S",connectWiFi);//connect to wifi: AT+CWJAP="myWiFi","myPassword"
isWiFiReady();
}
} // eo espSetConnection::
/*** sendToServer ****************************************************************************
Author: DTsebrii
Date: 31/MAY/2020
Description: Prompt the commands required to set the TCP connection and send the
message to the server
Input: None
Output: None
*************************************************************************************************/
void sendToServer()
{
printf((const rom far char *)"%S",connectTCP);//connect to TCP server as a client: AT+CIPSTART="TCP","10.0.0.75",1337
if( !isWiFiReady() )
printf((const rom far char *)"%S", RST);
} // eo sendToServer::
/*** createChecksum *******************************************************************************
Author: DTsebrii
Date: 18/MAR/2020
Midified: DTsebrii,25/MAR/2020
Description: Going through the input array and compare the each character with an unique checksum
verification variable
Input: char ptr pointer t ocollected sentence
Output: char cs, checkSum
*********************************************************************************************/
char createChecksum( char *ptr )
{
char cs = 0;
while( *ptr != '\0' )
{
cs ^= *ptr;
ptr++;
}//eo while
return cs;
}//eo createChecksum::
/*** createSentence *******************************************************************************
Author: DTsebrii
Date: 09/APR/2020
Description:Create a new average sentence
Input: None
Output: None
*********************************************************************************************/
void createSentence()
{
char cs = 0;
sprintf( rcBuffer,"$TMPUPD,%i,%i,%i", ADDYTO, MYADDY, tmprSys.averageSamp );
cs = createChecksum( rcBuffer );
sprintf( rcBuffer, "%s,%i#\0", rcBuffer, cs );
} // eo createSentence()
/*****************************************************************
Name: makeString
Author: DTsebrii
Date: 24/APR/2019
Modified: DTsebrii, 31/MAY/2020
Description: Combine the gathered value to a suitable string
Input: none
Output: none
*****************************************************************/
void makeString(tempSen_t *sptr) // SHOULD BE ADJUSTED IN THE FUTURE
{
char lenght = 0;
createSentence();
lenght = strlen( rcBuffer );
sendToServer();
printf( (const rom far char *)"AT+CIPSEND=%d\r\n",lenght );
isWiFiReady();
printf( (const rom far char *)"%s", rcBuffer );
//printf( (const rom far char *)"%s", buffer );
} // eo makeString::
/*****************************************************************
Name: sampADC
Author: DTsebrii
Date: 23/APR/2019
Description: Read the ADC value
Input: chID, char that represents ADC channel
Output: ADRES - ADC result
*****************************************************************/
int sampADC( char chID )
{
ADCON0&= ADCMASK;
ADCON0|= chID<<2;
ADCON0bits.GO = TRUE;
while( ADCON0bits.GO );
return ADRES;
} // eo sampADC::
/*****************************************************************
Name: sampling
Author: DTsebrii
Date: 23/APR/2019
Description: Convert the ADC into an actual temperature Value
Input: none
Output: none
*****************************************************************/
void sampling( tempSen_t *sptr )
{
float result = 0;
char cnt = 0;
int sum = 0;
result = sampADC(TEMPCHAN);
result *= ADCRES; // Convert to volts
result -= TOFFSET;
result /= TSLOPE;
sptr->samples[ sptr->counter ] = result;
if( sptr->counter >= SAMPSIZE )
{
sptr->counter = FALSE;
averageFlag = TRUE;
}
else
sptr->counter++;
if( averageFlag ) // There is not reseting of averageFlag
{
for( cnt = 0; cnt < SAMPSIZE; cnt++ )
sum += sptr->samples[ cnt ];
sptr->averageSamp = sum/SAMPSIZE;
}
} // eo sampling::
/*****************************************************************
Name: displayInfo
Author: DTsebrii
Date: 11/MAR/2020
Description: Displaying the whole information to debug
Input: tempSen_t *sptr -> pointer to a temperature sensor
Output: none
*****************************************************************/
void displayInfo( tempSen_t *sptr )
{
printf("\033[0;0H\033[2JThe Temperature Sensor...\n");
printf("\033[2;0HObject is working...\n");
printf("\033[4;0HThe Current Sensed Value is: %i\n", sptr->samples[ sptr->counter-1 ]);
createSentence();
printf("\033[5;0HThe Command string is: %s", rcBuffer );
} // eo displayInfo::
#pragma interrupt ISR
/*** ISR *******************************************************************************
Author: CTalbot
Date: 14/MAR/2020
Modifier: DTsebrii, 23/APR/2020
Description:Reseting TMR0
Input: None
Output: None
*********************************************************************************************/
void ISR()
{
if( TMR0FLAG )
{
TMR0FLAG = FALSE;
timer++;
timeFlag = TRUE;
}
INTCON |= TWOBITSON;
} // eo ISR::
// &&& MAIN &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
void main()
{
initializeSys();
espSetConnection();
while( TRUE )
{
if( timeFlag )
{
timeFlag = FALSE;
sampling( &tmprSys );
//displayInfo( &tmprSys ); // To watch output via Serial Communication
if( timer>=MINUTE )
{
makeString( &tmprSys );
timer = FALSE;
}
}
} // eo while
} // eo main
<file_sep>'''
:Name: raw_tcp_server.PY
:Author: DTsebrii
:Date: 11/MAR/2020
:Description:Template for a raw TCP server
'''
# *** Imports ********************************************************
import socket
# *** Constants ******************************************************
BUFFER_SIZE = 256 # Maximum 256 characters to receive
PORT = 0
HOST = ''
LISTENERS = 2
final_msg_lst = []
part_msg = ''
# *** Global Variables ***********************************************
# Server variables
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET is for IPv4 and SOCK is for rosponce to TCP
serv_sock.bind((HOST, PORT))
serv_sock.listen(LISTENERS) # Two projects to listen from
def parse_sentence ():
part_msg = ''
for index in range(len(message)):
if message[ index ] == ',' or message[ index ] == '#':
final_msg_lst.append( part_msg )
part_msg = ''
else:
part_msg += message[ index ]
return final_msg_lst
def validate_sentence (final_msg_lst):
temp_msg = ''
check_sum = 0
print(final_msg_lst)
for index in range(len(final_msg_lst)-2):
for chank in final_msg_lst[index]:
temp_msg += chank
temp_msg += ','
temp_msg += final_msg_lst[-2]
print(temp_msg)
for elem in temp_msg:
check_sum ^= ord(elem)
print(check_sum)
if check_sum == int(final_msg_lst[-1]):
print("Validation is ended. Storing process will begin immidiately")
return True
else:
print("Wrong checksum")
return False
print("Server is ready to send data") #Checking the server readiness
if __name__ == "__main__":
try:
while True:
(clientsocket, address) = serv_sock.accept() # Accept any client
print("Connection has been established.") # To check a connection
message = clientsocket.recv(BUFFER_SIZE) # Receiving of the message from a client
message = str(message)
print(message)
message = message.replace("b'","")
message = message.replace("'","")
print(f"Message Received: {message}")
final_msg_lst = parse_sentence()
print(final_msg_lst)
if validate_sentence(final_msg_lst):
with open("demoFile.csv", "a") as csv_file:
csv_file.write(str(final_msg_lst[len(final_msg_lst) - 1])+'\n')
print("Message is stored")
clientsocket.close() # Close the connection
finally:
serv_sock.close() # to close the server
| 7a20f417eb58ea3f52cd67ff8c488830060f9597 | [
"Markdown",
"C",
"Python"
] | 3 | Markdown | SmashKPI/Temperature-Sensing-Device | 919f6e2f15937463ddf4c1671f217c6a8c01fb48 | 65382b322a13c623ab9822077a1070c846d7671a |
refs/heads/master | <repo_name>anugrahjo/surf<file_sep>/my_optimizer/grad_simple.py
import numpy as np
def grad(x):
grad = np.zeros((x.size, 1))
for i in range(x.size):
grad[i] = 4 * x[i]**3
return grad<file_sep>/my_optimizer/func_simple.py
def func(x):
f = 0
for i in range(x.size):
f += x[i]**4
return f<file_sep>/openmdao/rs/residual_comp.py
from openmdao.api import ImplicitComponent
import numpy as np
class ResidualComp(ImplicitComponent):
def initialize(self):
pass
def setup(self):
self.add_input('x')
self.add_output('y')
self.declare_partials(of='*', wrt='*')
def apply_nonlinear(self, inputs, outputs, residuals):
x = inputs['x']
y = outputs['y']
residuals['y'] = x**2 - y
def solve_nonlinear(self, inputs, outputs):
x = inputs['x']
outputs['y'] = x**2
def linearize(self, inputs, outputs, partials):
x = inputs['x']
# y = outputs['y']
partials['y', 'x'] = 2. * x
partials['y', 'y'] = -1.
# self.inv_jac = -1
if __name__ == '__main__':
import numpy as np
from openmdao.api import Problem
prob = Problem()
comp = ResidualComp()
prob.model.add_subsystem('comp', comp, promotes=['*'])
prob.setup(check=True)
prob.run_model()
prob.model.list_outputs()
prob.check_partials(compact_print=True)<file_sep>/my_optimizer/optimize.py
import numpy as np
def optimize(nx, x0, func, grad, tol):
rho = 0.5
eta = 1E-4
grad1 = grad(x0)
grad2 = grad1 * 1
Bk = np.identity(nx)
bfgs = 0
norm_array = np.linalg.norm(grad1)
while (np.linalg.norm(grad2) > tol):
if bfgs > 1e+6:
break
bfgs += 1
grad1 = grad2 * 1
pk = np.linalg.solve(Bk, -grad1)
alpha = 1
while (func(x0 + alpha * pk) >
(func(x0) + eta * alpha * np.matmul(grad1.T, pk))):
alpha = rho * alpha
sk = alpha * pk
x0 += sk
grad2 = grad(x0)
yk = grad2 - grad1
Bk = Bk + np.matmul(yk, yk.T) / np.matmul(yk.T, sk) - np.matmul(
np.matmul(Bk, sk), np.matmul(sk.T, Bk)) / np.matmul(
np.matmul(sk.T, Bk), sk)
norm_array = np.append(norm_array, np.linalg.norm(grad2))
iter_array = np.arange(bfgs + 1)
return x0, iter_array, norm_array
<file_sep>/openmdao/fs/group.py
from openmdao.api import IndepVarComp, ExplicitComponent, Group, Problem
import numpy as np
from obj_comp import ObjComp
from constraint_comp import ConstraintComp
class group(Group):
def initialize(self):
pass
def setup(self):
IVC = IndepVarComp()
IVC.add_output('x', val=np.array([1.5, 1]))
self.add_subsystem('IVC', IVC, promotes=['*'])
comp = ObjComp()
self.add_subsystem('ObjComp', comp, promotes=['*'])
comp = ConstraintComp()
self.add_subsystem('ConstraintComp', comp, promotes=['*'])
<file_sep>/openmdao/fs/obj_comp.py
from openmdao.api import ExplicitComponent
import numpy as np
class ObjComp(ExplicitComponent):
def initialize(self):
pass
def setup(self):
self.add_input('x', shape=(2, ))
self.add_output('obj')
self.declare_partials('obj', 'x')
def compute(self, inputs, outputs):
x = inputs['x']
outputs['obj'] = x[0] * x[1] - 0.5 * x[0]**2 - x[1]
# print(outputs['obj'])
def compute_partials(self, inputs, partials):
x = inputs['x']
partials['obj', 'x'] = np.array([x[1] - x[0], x[0] - 1])
<file_sep>/my_optimizer/grad.py
import numpy as np
def grad(x):
grad = np.array([x[1] - x[0], x[0] - 1])
return grad<file_sep>/my_optimizer/example.py
import numpy as np
from func import func
from grad import grad
from ajoshy_optimize import optimize
import pandas
x0 = np.array([0.1, 1])
x, iter_array, norm_array = optimize(2, x0, func, grad, 1E-7)
table = pandas.DataFrame({"Iter": iter_array, "Opt": norm_array})
print(table.to_string(index=False))
print(x)<file_sep>/my_optimizer/example_simple.py
import numpy as np
from func import func
from grad import grad
from ajoshy_optimize import optimize
import pandas
x0 = np.full((10, 1), 0.1)
x, iter_array, norm_array = optimize(10, x0, func, grad, 1E-7)
table = pandas.DataFrame({"Iter": iter_array, "Opt": norm_array})
print(table.to_string(index=False))
print(x)<file_sep>/openmdao/plots/plot.py
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
n = 1000
t = np.linspace(-2, 2., num=n)
x = np.outer(np.linspace(-2, 2., num=n), np.ones(n))
y = np.outer(np.ones(n), np.linspace(-2, 2., num=n))
f = x * y - 0.5 * x**2 - y
plt.figure(1)
# plt.contour(x, y, f, levels=np.linspace(-1, 1, 10))
cs = plt.contour(x, y, f, levels=np.linspace(-4.5, 4.5, 10))
# cs = plt.contour(x, y, f)
plt.clabel(cs, inline=True, fontsize=10)
plt.plot(t, t**2, color='black')
plt.plot(t, t * 0, color='orange')
plt.plot(t * 0, t, color='orange')
plt.xlim(-2, 2)
plt.ylim(-2, 2)
plt.show()<file_sep>/my_optimizer/func.py
def func(x):
f = x[0] * x[1] - 0.5 * x[0]**2 - x[1]
return f<file_sep>/openmdao/rs/group.py
from openmdao.api import IndepVarComp, ExplicitComponent, Group, Problem
import numpy as np
from obj_comp import ObjComp
from residual_comp import ResidualComp
class group(Group):
def initialize(self):
pass
def setup(self):
IVC = IndepVarComp()
IVC.add_output('x', val=1.5)
self.add_subsystem('IVC', IVC, promotes=['*'])
comp = ObjComp()
self.add_subsystem('ObjComp', comp, promotes=['*'])
comp = ResidualComp()
self.add_subsystem('ResidualComp', comp, promotes=['*'])
<file_sep>/openmdao/rs/run.py
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from openmdao.api import Problem, ScipyOptimizeDriver, view_model
from openmdao.api import pyOptSparseDriver
from group import group
prob = Problem()
prob.model = group()
prob.model.add_design_var('x')
prob.model.add_objective('obj')
# prob.driver = ScipyOptimizeDriver()
# prob.driver.options['optimizer'] = 'SLSQP'
prob.driver = pyOptSparseDriver()
prob.driver.options['optimizer'] = 'SNOPT'
# prob.driver.options['tol'] = 1e-9
# prob.driver.options['obj'] = True
prob.setup()
prob.run_model()
prob.run_driver()
print(prob['obj'])
print(prob['y'])
print(prob['x'])
view_model(prob)
<file_sep>/openmdao/rs/obj_comp.py
from openmdao.api import ExplicitComponent
import numpy as np
class ObjComp(ExplicitComponent):
def initialize(self):
pass
def setup(self):
self.add_input('x')
self.add_input('y')
self.add_output('obj')
self.declare_partials('obj', 'x')
self.declare_partials('obj', 'y')
def compute(self, inputs, outputs):
x = inputs['x']
y = inputs['y']
outputs['obj'] = x * y - 0.5 * x**2 - y
# print(outputs['obj'])
def compute_partials(self, inputs, partials):
x = inputs['x']
y = inputs['y']
partials['obj', 'x'] = y - x
partials['obj', 'y'] = x - 1
if __name__ == '__main__':
import numpy as np
from openmdao.api import Problem
prob = Problem()
comp = ObjComp()
prob.model.add_subsystem('comp', comp, promotes=['*'])
prob.setup(check=True)
prob.run_model()
prob.model.list_outputs()
prob.check_partials(compact_print=True)
| cfd84964b4717ce7aa50c0ca1d6fdc78317dc7e4 | [
"Python"
] | 14 | Python | anugrahjo/surf | 8f5f79d6c8c8f2fc5e84f70ac248f9c69106780a | 06dc087ef3b6b09fe15634bdf4db70fb1be7c079 |
refs/heads/master | <repo_name>jerrytnutt/CV-React-Project<file_sep>/src/components/workExperienceForm.js
import React, {Component} from 'react'
import WorkExperienceDisplay from '../components/workExperienceDisplay'
class Work extends Component{
constructor(props){
super(props)
this.state = {
appendingWork: false,
id: 0,
companyName: '',
position: '',
description: '',
startDate: '',
endDate: '',
workArray: [],
}
this.changeAppendingWork = this.changeAppendingWork.bind(this);
this.removeElement = this.removeElement.bind(this)
}
changeAppendingWork() {
this.setState({
appendingWork: !this.state.appendingWork
})
}
handleSubmit = (event) => {
event.preventDefault(event)
this.setState({
appendingWork: false,
id: this.state.id + 1,
workArray:[...this.state.workArray, {id: this.state.id,companyName: this.state.companyName,
position: this.state.position,description: this.state.description, startDate: this.state.startDate,endDate: this.state.endDate}]
})
}
handleInputChange = (event) => {
event.preventDefault(event)
this.setState({
[event.target.name]: event.target.value
})
}
removeElement(event) {
if (this.state.workArray.length === 1){
this.state.workArray.pop()
}
let entryLocation = event.target.value
entryLocation = this.state.workArray.findIndex(obj => obj.companyName === entryLocation)
this.state.workArray.splice(entryLocation, 1)
this.setState({
workArray: this.state.workArray
})
}
render(){
if (this.state.appendingWork){
return(
<div className='infoContainer'>
<WorkExperienceDisplay
workArray = {this.state.workArray}
removeElement={this.removeElement} />
<form onSubmit={this.handleSubmit}>
<label>
<h2>Company Name:</h2>
<input type='text' value={this.state.companyName} name='companyName' onChange={this.handleInputChange} required></input>
</label>
<label>
<h2>Position:</h2>
<input type='text' value={this.state.position} name='position' onChange={this.handleInputChange} required></input>
</label>
<label>
<h2>Description of Duties</h2>
<textarea value={this.state.description} name='description' onChange={this.handleInputChange} className='duty' required></textarea>
</label>
<div className='outerBox'>
<div className='innerBox'>
<label>
<h2>Start date:</h2>
<input type="date" value={this.state.startDate} name='startDate' onChange={this.handleInputChange}
min="1950-01-01" max="2028-12-31" required></input>
</label>
</div>
<div className='innerBox'>
<label>
<h2>End date:</h2>
<input type="date" value={this.state.endDate} name='endDate' onChange={this.handleInputChange}
min="1950-01-01" max="2028-12-31" required></input>
</label>
</div>
</div>
<button className='submit'>Submit</button>
</form>
</div>
)
}else{
return(
<div className='infoContainer'>
<WorkExperienceDisplay
workArray = {this.state.workArray}
removeElement={this.removeElement}/>
<div className='addButtonContainer'>
<button className='add' onClick={this.changeAppendingWork}>Add</button>
<p>Add Experience</p>
</div>
</div>
)
}
}
}
export default Work<file_sep>/src/components/generalInformationForm.js
import React, {Component} from 'react'
import GeneralDisplay from '../components/generalInformationDisplay'
class GeneralForm extends Component{
constructor(props){
super(props)
this.state = {
isSubmitted: false,
firstName: '',
lastName: '',
email: '',
phoneNumber: ''
}
this.changeisSubmitted = this.changeisSubmitted.bind(this);
}
changeisSubmitted() {
this.setState({
isSubmitted: !this.state.isSubmitted
})
}
handleSubmit = (event) => {
event.preventDefault(event)
this.changeisSubmitted()
}
handleInputChange = (event) => {
event.preventDefault(event)
this.setState({
[event.target.name]: event.target.value
})
}
render(){
if (!this.state.isSubmitted){
return(
<div className='infoContainer'>
<form onSubmit={this.handleSubmit}>
<div className='outerBox'>
<div className='innerBox'>
<label>
<h2>First Name:</h2>
<input type='text' value={this.state.firstName} name='firstName' onChange={this.handleInputChange} required></input>
</label>
</div>
<div className='innerBox'>
<label>
<h2>Last Name:</h2>
<input type='text' value={this.state.lastName} name='lastName' onChange={this.handleInputChange} required></input>
</label>
</div>
</div>
<label>
<h2>E-mail:</h2>
<input type='text' value={this.state.email} name='email' onChange={this.handleInputChange} required></input>
</label>
<label>
<h2>Phone Number:</h2>
<input type='text' value={this.state.phoneNumber} name='phoneNumber' onChange={this.handleInputChange} required></input>
</label>
<div>
<button className='submit'>Submit</button>
</div>
</form>
</div>
)
}else{
return(
<div className='infoContainer'>
<GeneralDisplay
firstName = {this.state.firstName}
lastName = {this.state.lastName}
email = {this.state.email}
phoneNumber = {this.state.phoneNumber}
changeisSubmitted={this.changeisSubmitted}/>
</div>
)
}
}
}
export default GeneralForm<file_sep>/src/components/workExperienceDisplay.js
import React, {Component} from 'react'
class WorkExperienceDisplay extends Component{
render(){
return(
<div>
{this.props.workArray.map((n) =>
<div key={n.id} >
<button className='remove' value={n.companyName} onClick={this.props.removeElement}>X</button>
<h3>Company Name</h3>
<div className='description'>{n.companyName}</div>
<h3>Position</h3>
<div className='description' >{n.position}</div>
<h3>Description of Duty</h3>
<div className='descriptionOfDuty' >{n.description}</div>
<div className='outerBox'>
<div className='innerBox'>
<h3>Start date</h3>
<div className='description'>{n.startDate}</div>
</div>
<div className='innerBox'>
<h3>End date</h3>
<div className='description'>{n.endDate}</div>
</div>
</div>
</div>)}
</div>
)
}
}
export default WorkExperienceDisplay<file_sep>/README.md
# C.V Application project
C.V Application project created for [The Odin Project.](https://www.theodinproject.com/courses/javascript/lessons/cv-application)
Application makes use of React's states, props and components.
A live demo can be seen [here.](https://jerrytnutt.github.io/CV-React-Project/)
<file_sep>/src/App.js
import './App.css';
import React from 'react';
import Header from './components/header';
import GeneralForm from './components/generalInformationForm';
import EducationForm from './components/educationForm';
import WorkExperienceForm from './components/workExperienceForm';
function App() {
return (
<div className="App">
<Header/>
<GeneralForm/>
<EducationForm/>
<WorkExperienceForm/>
</div>
);
}
export default App;
<file_sep>/src/components/header.js
import React, {Component} from 'react'
class Header extends Component {
render() {
return <div className='header'>
<h1>C.V Builder</h1>
<a href="https://github.com/jerrytnutt" target="_blank" rel="noreferrer" >
<div className='gitImg' ></div>
</a>
</div>
}
}
export default Header<file_sep>/src/components/generalInformationDisplay.js
import React, {Component} from 'react'
class GeneralDisplay extends Component{
render(){
return(
<div className='infoContainer'>
<div className='outerBox'>
<div className='innerBox'>
<h3>First Name</h3>
<div className='description'>{this.props.firstName} </div>
</div>
<div className='innerBox'>
<h3>Last Name</h3>
<div className='description'>{this.props.lastName} </div>
</div>
</div>
<h3>E-mail</h3>
<div className='description'> {this.props.email} </div>
<h3>Phone Number</h3>
<div className='description'>{this.props.phoneNumber}</div>
<button className='editButton' onClick={this.props.changeisSubmitted}>Edit</button>
</div>
)
}
}
export default GeneralDisplay<file_sep>/src/components/educationForm.js
import React, {Component} from 'react'
import EducationDisplay from '../components/educationDisplay'
class EducationForm extends Component{
constructor(props){
super(props)
this.state = {
appendingEducation: false,
id: 0,
schoolName: '',
degree: '',
startDate: '',
graduationDate: '',
educationArray: [],
}
this.changeAppendingEducation = this.changeAppendingEducation.bind(this);
this.removeElement = this.removeElement.bind(this);
}
changeAppendingEducation() {
this.setState({
appendingEducation: !this.state.appendingEducation
})
}
handleSubmit = (event) => {
event.preventDefault(event)
this.setState({
appendingEducation: false,
id: this.state.id + 1,
educationArray:[...this.state.educationArray, {id: this.state.id,schoolName: this.state.schoolName,
degree: this.state.degree, graduationDate: this.state.graduationDate,startDate: this.state.startDate}]
})
}
handleInputChange = (event) => {
event.preventDefault(event)
this.setState({
[event.target.name]: event.target.value
})
}
removeElement(event) {
if (this.state.educationArray.length === 1){
this.state.educationArray.pop()
}
let entryLocation = event.target.value
entryLocation = this.state.educationArray.findIndex(obj => obj.schoolName === entryLocation)
this.state.educationArray.splice(entryLocation, 1)
this.setState({
educationArray: this.state.educationArray
})
}
render(){
if (this.state.appendingEducation){
return(
<div className='infoContainer'>
<EducationDisplay
educationArray = {this.state.educationArray}
removeElement={this.removeElement} />
<form onSubmit={this.handleSubmit}>
<label>
<h2>School Name:</h2>
<input type='text' value={this.state.schoolName} name='schoolName' onChange={this.handleInputChange} required></input>
</label>
<label>
<h2>Degree:</h2>
<input type='text' value={this.state.degree} name='degree' onChange={this.handleInputChange} required></input>
</label>
<div className='outerBox'>
<div className='innerBox'>
<label>
<h2>Start date:</h2>
<input type="date" value={this.state.startDate} name='startDate' onChange={this.handleInputChange}
min="1950-01-01" max="2028-12-31" required></input>
</label>
</div>
<div className='innerBox'>
<label>
<h2>Graduation date:</h2>
<input type="date" value={this.state.graduationDate} name='graduationDate' onChange={this.handleInputChange} id="grad"
min="1950-01-01" max="2028-12-31" required></input>
</label>
</div>
</div>
<button className='submit' >Submit</button>
</form>
</div>
)
}else{
return(
<div className='infoContainer'>
<EducationDisplay
educationArray = {this.state.educationArray}
removeElement={this.removeElement}/>
<div className='addButtonContainer'>
<button className='add' onClick={this.changeAppendingEducation}>Add</button>
<p>Append New Education</p></div>
</div>
)
}
}
}
export default EducationForm | a290b17512c8b1ac352a47121cc9375edf368c40 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | jerrytnutt/CV-React-Project | bae03b4060098666d6b7f83b391542d213cc4aad | 287788d37eead424d73dfcd501e0d2250a8000cf |
refs/heads/main | <file_sep>#include<iostream>
#include<algorithm>
using namespace std;
int main(){
// //Reverse an array
// int n;
// cout<<"array length: ";
// cin>>n;
// int a[n];
// cout<<"enter the element of array : ";
// for(int i=0; i<n; i++){
// cin>>a[i];
// }
// cout<<"Reverse array : ";
// //5int sum=0;
// for(int i=n-1; i>=0; i--){
// cout<<a[i]<<" ";
// }
// //cout<<sum<<endl;
//----------------------------------------------------------------------------------------------
// int t;
// cin>>t;
// int i=0;
// while (i!=t)
// {
// int n,k;
// cin>>n>>k;
// int a[n];
// for(int i=0; i<n; i++){
// cin>>a[i];
// }
// i++;
// }
// cout<<"o/p: "<<endl;
// while (i!=t)
// {
// int n,k;
// cout<<n<<k<<endl;
// int a[n];
// for(int i=0; i<n; i++){
// cout<<a[i];
// }
// i++;
// }
//------------------------------------------------------------------------------------
//sorting of array
// selection sort
// int n;
// cin>>n;
// int a[n];
// for (int i=0; i<n; i++){
// cin>>a[i];
// }
// for(int i=0; i<n-1; i++){
// for(int j=i+1; j<n; j++){
// if(a[j]<a[i]){
// int temp=a[j];
// a[j]=a[i];
// a[i]=temp;
// }
// }
// }
// cout<<"sorted array is: ";
// for(int i=0; i<n; i++){
// cout<<a[i]<<" ";
// }
//---------------------------------------------------------------------
//bubble sort
// int n;
// cin>>n;
// int a[n];
// for (int i=0; i<n; i++){
// cin>>a[i];
// }
// int counter=1;
// while(n>counter){
// for(int i=0; i<n-i; i++){
// if(a[i+1]<a[i]){
// int temp=a[i];
// a[i]=a[i+1];
// a[i+1]=temp;
// }
// }
// counter++;
// }
// for(int i=0; i<n; i++){
// cout<<a[i]<<" ";
// }
//-------------------------------------------------------------------------------
// insertion sort
// int n;
// cin>>n;
// int a[n];
// for(int i=0; i<n; i++){
// cin>>a[i];
// }
// for(int i=0; i<n; i++){
// cout<<a[i];
// }
//--------------------------------------------------------------------------
//max till i
// int n;
// cin>>n;
// int a[n];
// for(int i=0; i<n; i++){
// cin>>a[i];
// }
// int mx=-999999;
// for(int i=0; i<n; i++){
// mx=max(mx,a[i]);
// }
// cout<<mx<<endl;
//------------------------------------------------------------------------------------
// sum of all subarray and total no. of subarray
// int n;
// cin>>n;
// int a[n];
// for(int i=0; i<n; i++){
// cin>>a[i];
// }
// int sum;
// int totalsum=0;
// int count=0;
// for(int i=0; i<n; i++){
// sum=0;
// for(int j=i; j<n; j++){
// sum=sum+a[j];
// // cout<<sum<<endl;
// totalsum=totalsum+sum;
// count++;
// }
// }
// cout<<count<<endl;
// cout<<totalsum<<endl;
//------------------------------------------------------------------------------------
// Longest Arithmetic subarray google kick start
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++){
cin>>a[i];
}
int ans=2;
int pd=a[1]-a[0];
int curr=2;
int j=2;
while (j<n)
{
if(pd==a[j]-a[j-1])
{
curr++;
}
else{
pd=a[j]-a[j-1];
curr=2;
}
ans=max(ans,curr);
j++;
}
cout<<ans<<endl;
//-----------------------------------------------------------------------------
//Record Breaker Google Kick start
return 0;
}<file_sep>// #include<iostream>
// using namespace std;
// int main(){
// int n,m;
// cin>>n>>m;
// int arr[n][m];
// for(int i=0; i<n; i++){
// for(int j=0; j<m; j++){
// cin>>arr[i][j];
// }
// }
// int key;
// cin>>key;
// cout<<"Matrix is : "<<endl;
// for(int i=0; i<n; i++){
// for(int j=0; j<m; j++){
// if(arr[i][j]==key){
// cout<<i<<j;
// }
// }
// }
// }
//------------------------------------------------------------------------------
// #include <iostream>
// using namespace std;
// int main(){
// int row,col;
// cin>>row>>col;
// int a[row][col];
// int b[row][col];
// cout<<"Enter first matrix: ";
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cin>>a[i][j];
// }
// }
// cout<<"Enter second matrix: ";
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cin>>b[i][j];
// }
// }
// int c[row][col];
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// c[i][j]=a[i][j]+b[i][j];
// }
// }
// cout<<"Addition of matrix is: "<<endl;
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cout<<c[i][j]<<" ";
// }
// cout<<endl;
// }
// }
//----------------------------------------------------------------------------------------
// #include <iostream>
// using namespace std;
// int main(){
// int row, col;
// cin>>row>>col;
// int a[row][col];
// int b[row][col];
// cout<<"Enter the first matrix: ";
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cin>>a[i][j];
// }
// }
// cout<<"Enter the Second matrix: ";
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cin>>b[i][j];
// }
// }
// int c[row][col];
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// c[i][j]=0;
// for(int k=0; k<col; k++){
// c[i][j]+=a[i][k]*b[k][j];
// }
// }
// }
// cout<<"Multiplied matrix is: "<<endl;
// for(int i=0; i<row; i++){
// for(int j=0; j<col; j++){
// cout<<c[i][j]<<" ";
// }
// cout<<endl;
// }
// return 0;
// }
//-----------------------------------------------------------------------------
#include<iostream>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int a[n][m];
cout<<"Enter the matrix: "<<endl;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>a[i][j];
}
}
//logic
for(int i=0; i<n; i++){
for(int j=i; j<m; j++){
int temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
cout<<"Transpose matrix is: "<<endl;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
} | e75fc27159fd8342dbff743f52c03b0f8de7adce | [
"C++"
] | 2 | C++ | Piyush692/cpp__ | aaa692dcf97780728503ccac154b84f010cda9f3 | 7772439157e2481b4c523ee0534c9554ede9ec42 |
refs/heads/master | <file_sep>// this is our master ruder file it doesnt manage any paticular peice of state. simply contains all other states
import { combineReducers } from 'redux';
import StudentReducer from './StudentReducer';
const rootReducer = combineReducers({
students: StudentReducer
})
export default rootReducer;<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
class Students extends Component{
render(){
var studentArray = this.props.students.map((student,index)=>{
return(<li key={index}>{student.name} sits in seat {student.seat} in the {student.row} row!!</li>)
});
console.log(this.props)
return(
<div>
<h1>Students Component</h1>
{studentArray}
</div>
)
}
}
function mapStateToProps(state){
return{
students: state.students
}
}
// export default Students;
export default connect(mapStateToProps)(Students);<file_sep>export default function(){
return[
{
name: "jamie",
seat: 2,
row: "back"
},
{
name: "amir",
seat: 3,
row: "back"
},
{
name: "casey",
seat: 1,
row: "back"
},
{
name: "akil",
seat: 4,
row: "back"
},
{
name: "valerie",
seat: 2,
row: "front"
},
{
name: "jennifer",
seat: 8,
row: "front"
},
{
name: "chris",
seat: 8,
row: "back"
},
{
name: "rob",
seat: "?",
row: "middle"
},
];
}
| 276029b0bbac9fcd2882c63e54135fe7afb28520 | [
"JavaScript"
] | 3 | JavaScript | downs-jamie/redux101 | 4ee4dd814d11f3205eeb02cb8917a3d28cda75e3 | 96ca33c560273f8f5f705b5ef960b127305cb798 |
refs/heads/master | <file_sep>package com.example.tic.player
import com.example.tic.Board
class Computer(computerSign: Char) : Player {
override val sign = computerSign
override fun play(board: Board, players: ArrayList<Player>) {
println("Computer playing with sign : $sign ")
var rowSelected = -1
var columnSelected = -1
var highVal = Int.MIN_VALUE
for (row in 0 until board.getSize()) {
for (column in 0 until board.getSize()) {
if (board.getSignAt(row, column) == '-') {
board.mark(row, column, sign)
val value = finder(board, false, 2, players)
board.unMark(row, column)
if (value > highVal) {
highVal = value
rowSelected = row
columnSelected = column
}
}
}
}
board.mark(rowSelected, columnSelected, sign)
board.checkWin(sign)
}
private fun finder(board: Board, isComputer: Boolean, recursionLevel: Int, players: ArrayList<Player>): Int {
val score = board.weightMove(sign)
if (score == 1 || score == -1 || recursionLevel == 0) return score
if (!board.isMoveRemaining()) return 0
when (isComputer) {
true -> {
var best = -1000
for (row in 0 until board.getSize()) {
for (column in 0 until board.getSize()) {
if (board.getSignAt(row, column) == '-') {
board.mark(row, column, sign)
best = Math.max(finder(board, !isComputer, recursionLevel - 1, players), best)
board.unMark(row, column)
}
}
}
return best
}
else -> {
var best = 1000
for (row in 0 until board.getSize()) {
for (column in 0 until board.getSize()) {
if (board.getSignAt(row, column) == '-') {
for (player in players) {
if (player.sign != sign) {
board.mark(row, column, player.sign)
best = Math.min(finder(board, !isComputer, recursionLevel - 1, players), best)
board.mark(row, column, '-')
}
}
}
}
}
return best
}
}
}
}<file_sep>package com.example.tic.player
import com.example.tic.Board
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class ComputerTest {
@Test
fun `Should play a move on the given board`() {
val size = 5
var board = Board(size)
Computer('r').play(board, ArrayList())
for (i in 0 until size) {
for (j in 0 until size) {
if (board.getSignAt(i,j)=='r')
return
}
}
Assertions.fail<String>("not marked on board")
}
@Test
fun `Should play a move to stop win by other player`() {
val size = 3
var board = Board(size)
board.mark(1, 0, 't')
board.mark(1, 1, 't')
Computer('r').play(board, arrayListOf(Man('t')))
Assertions.assertEquals(board.getSignAt(1,2),'r')
}
}<file_sep>package com.example.tic.player
import com.example.tic.Board
interface Player {
val sign: Char
fun play(board: Board, players: ArrayList<Player>)
}<file_sep>rootProject.name = 'tic'
rootProject.name = 'tic'
<file_sep>package com.example.tic
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class TicTheGameTest {
@Test
fun `Should start the game`() {
val ticTheGame = TicTheGame()
ticTheGame.initGame()
//ticTheGame.startGame()
Assertions.assertEquals(Board(5).getSize(), 5)
}
}<file_sep>package com.example.tic.player
import com.example.tic.Board
import com.example.tic.IncorrectInputException
import java.util.*
class Man(playerSign: Char) : Player {
override val sign = playerSign
override fun play(board: Board, players: ArrayList<Player>) {
println("Manual player with sign : $sign playing")
var (row, col) = readPosition(board)
board.mark(row, col, sign)
board.checkWin(sign)
}
private fun readPosition(board: Board): Pair<Int, Int> {
var row = -1
var col = -1
while (row == -1 && col == -1) {
println("Enter row,col and press enter")
val inputString = readLine()!!
try {
val readValues = inputString.split(',')
if (readValues.size > 2) throw IncorrectInputException("input values more then required")
row = readValues[0].trim().toInt()
col = readValues[1].trim().toInt()
if (row >= board.getSize() || col >= board.getSize() || row < 0 || col < 0) throw IncorrectInputException("not in limit")
if (board.getSignAt(row, col) != '-') throw IncorrectInputException("Already marked")
} catch (ex: Exception) {
row = -1
col = -1
print("incorrect input: ${ex.message} . try again")
continue
}
}
return Pair(row, col)
}
}<file_sep>package com.example.tic
import com.example.tic.player.Computer
import com.example.tic.player.Man
import com.example.tic.player.Player
class TicTheGame {
private lateinit var players: ArrayList<Player>
private lateinit var board: Board
fun initGame() {
val configReader = com.example.tic.config.ConfigReader("../../../../tic.properties")
players = ArrayList()
players.add(Man(configReader.player1Sign))
players.add(Man(configReader.player2Sign))
players.add(Computer(configReader.computerSign))
board = Board(configReader.boardSize)
}
fun startGame() {
while (board.isMoveRemaining())
players.forEach{it.play(board,players)}
}
}
fun main(args: Array<String>) {
val ticTheGame = TicTheGame()
ticTheGame.initGame()
ticTheGame.startGame()
}<file_sep>package com.example.tic
class Board(size: Int) {
private val EMPTYMARK = '-'
private var board: Array<CharArray>
init {
if (size < 3 || size > 10) throw IncorrectInputException("Incorrect board size specified")
board = Array(size, { CharArray(size, { this.EMPTYMARK }) })
}
private fun printBoard() = board.forEach { println(it) }
fun mark(row: Int, col: Int, sign: Char) {
if (row >= getSize() || col >= getSize()) throw InvalidMoveException("Incorrect move")
board[row][col] = sign
}
fun unMark(row: Int, col: Int) = mark(row,col, this.EMPTYMARK)
fun getSize(): Int = board.size
fun getSignAt(row: Int, col: Int) = board[row][col]
fun getRowWeight(computerSign: Char): Int {
val k = board.size - 1
for (row in 0..k) {
var notMatched = true
var i = 0
while (i < k && notMatched) {
if (board[row][i] != board[row][i + 1]) notMatched = false
i++
}
if (notMatched) {
if (board[row][i] == computerSign) return 1
else if (board[row][i] != this.EMPTYMARK) return -1
}
}
return 0
}
fun getColumnWeight(computerSign: Char): Int {
val k = board.size - 1
for (row in 0..k) {
var notMatched = true
var i = 0
while (i < k && notMatched) {
if (board[i][row] != board[i + 1][row]) notMatched = false
i++
}
if (notMatched) {
val tempSign = board[i][row]
if (tempSign == computerSign) return 1
else if (tempSign != this.EMPTYMARK) return -1
}
}
return 0
}
fun getDiagonalWeight(computerSign: Char): Int {
val result = 0
var notMatched = true //TODO : Kotlin multile assignments
val k = board.size - 1
var i = 0
while (i < k && notMatched) {
if (board[i][i] != board[i + 1][i + 1]) notMatched = false
i++
}
if (notMatched) {
if (board[i][i] == computerSign) return 1
else if (board[i][i] != this.EMPTYMARK) return -1
}
var j = k
notMatched = true
i = 0
while (i < k && notMatched) {
if (board[j][i] != board[j - 1][i + 1]) notMatched = false
i++
j--
}
if (notMatched) {
if (board[j][i] == computerSign) return 1
else if (board[j][i] != this.EMPTYMARK) return -1
}
return result
}
fun weightMove(computerSign: Char): Int {
var weight = getRowWeight(computerSign)
if (weight == 0) {
weight = getColumnWeight(computerSign)
if (weight == 0) {
return getDiagonalWeight(computerSign)
}
}
return weight
}
fun isMoveRemaining() = board.any ({ it.contains(this.EMPTYMARK) })
fun checkWin(sign: Char) {
printBoard()
when (weightMove(sign)) {
1 -> {
println("Game over. Player with Sign {$sign} wins!!")
System.exit(1)
}
else -> {
if (!isMoveRemaining()) {
println("no moves remaining ..exiting")
System.exit(1)
}
}
}
}
}
data class InvalidMoveException(override val message: String) : Exception(message)
data class IncorrectInputException(override val message: String) : Exception(message)
<file_sep>package com.example.tic
import com.example.tic.Board
import com.example.tic.IncorrectInputException
import com.example.tic.InvalidMoveException
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class BoardTest {
@Test
fun `Should Create a board of given size`() {
Assertions.assertEquals(Board(5).getSize(), 5)
}
@Test
fun `Should mark given sign on board at given place`() {
val board = Board(5)
board.mark(1, 2, 't')
Assertions.assertEquals(board.getSignAt(1, 2), 't')
}
@Test
fun `Should throw exception if position is incorrect`() {
val board = Board(5)
Assertions.assertThrows(InvalidMoveException::class.java) {
board.mark(5, 3, 'x')
}
}
@Test
fun `Should throw exception if board size is not between 1-10`() {
Assertions.assertThrows(IncorrectInputException::class.java) {
Board(-1)
}
Assertions.assertThrows(IncorrectInputException::class.java) {
Board(11)
}
}
@Test
fun `Should return row win for computer`() {
val board = Board(5)
board.mark(1, 0, 't')
board.mark(1, 1, 't')
board.mark(1, 2, 't')
board.mark(1, 3, 't')
board.mark(1, 4, 't')
Assertions.assertEquals(1, board.getRowWeight('t'))
val board2 = Board(5)
board2.mark(2, 0, 't')
board2.mark(2, 1, 't')
board2.mark(2, 2, 't')
board2.mark(2, 3, 't')
board2.mark(2, 4, 't')
Assertions.assertEquals(1, board2.getRowWeight('t'))
}
@Test
fun `Should return row win for opponent`() {
val board = Board(5)
board.mark(1, 0, 't')
board.mark(1, 1, 't')
board.mark(1, 2, 't')
board.mark(1, 3, 't')
board.mark(1, 4, 't')
Assertions.assertEquals(-1, board.getRowWeight('j'))
val board2 = Board(5)
board2.mark(2, 0, 't')
board2.mark(2, 1, 't')
board2.mark(2, 2, 't')
board2.mark(2, 3, 't')
board2.mark(2, 4, 't')
Assertions.assertEquals(-1, board2.getRowWeight('j'))
}
@Test
fun `Should return no win`() {
val board = Board(5)
board.mark(1, 0, 't')
board.mark(1, 1, 't')
board.mark(1, 2, 'j')
board.mark(1, 3, 't')
board.mark(1, 4, 't')
Assertions.assertEquals(0, board.getRowWeight('j'))
val board2 = Board(5)
board2.mark(2, 0, 't')
board2.mark(2, 1, 't')
board2.mark(2, 2, 't')
board2.mark(2, 3, 'i')
board2.mark(2, 4, 't')
Assertions.assertEquals(0, board2.getRowWeight('j'))
}
@Test
fun `Should return column win for computer`() {
val board = Board(5)
board.mark(0, 1, 't')
board.mark(1, 1, 't')
board.mark(2, 1, 't')
board.mark(3, 1, 't')
board.mark(4, 1, 't')
Assertions.assertEquals(1, board.getColumnWeight('t'))
val board2 = Board(5)
board2.mark(0, 2, 't')
board2.mark(1, 2, 't')
board2.mark(2, 2, 't')
board2.mark(3, 2, 't')
board2.mark(4, 2, 't')
Assertions.assertEquals(1, board2.getColumnWeight('t'))
}
@Test
fun `Should return diagonal win for computer`() {
val board = Board(5)
board.mark(0, 0, 't')
board.mark(1, 1, 't')
board.mark(2, 2, 't')
board.mark(3, 3, 't')
board.mark(4, 4, 't')
Assertions.assertEquals(1, board.getDiagonalWeight('t'))
val board2 = Board(5)
board2.mark(0, 4, 't')
board2.mark(1, 3, 't')
board2.mark(2, 2, 't')
board2.mark(3, 1, 't')
board2.mark(4, 0, 't')
Assertions.assertEquals(1, board2.getDiagonalWeight('t'))
}
@Test
fun `Should return diagonal win for opponent`() {
val board = Board(5)
board.mark(0, 0, 't')
board.mark(1, 1, 't')
board.mark(2, 2, 't')
board.mark(3, 3, 't')
board.mark(4, 4, 't')
Assertions.assertEquals(-1, board.getDiagonalWeight('y'))
val board2 = Board(5)
board2.mark(0, 4, 't')
board2.mark(1, 3, 't')
board2.mark(2, 2, 't')
board2.mark(3, 1, 't')
board2.mark(4, 0, 't')
Assertions.assertEquals(-1, board2.getDiagonalWeight('u'))
}
}<file_sep>package com.example.tic.config
import java.io.FileNotFoundException
import java.util.*
class ConfigReader(configFilePath: String) {
val player1Sign: Char
val player2Sign: Char
val computerSign: Char
val boardSize: Int
private val properties: Properties = Properties()
init {
val resourceAsStream = javaClass.getResourceAsStream(configFilePath)
?: throw FileNotFoundException("config file not found")
properties.load(resourceAsStream)
player1Sign = properties.getProperty("player.1.char")[0]
player2Sign = properties.getProperty("player.2.char")[0]
computerSign = properties.getProperty("computer.char")[0]
boardSize = properties.getProperty("board.size").toInt() //TODO : TEST CASE
}
}
<file_sep>board.size=3
player.1.char=i
player.2.char=j
computer.char=*<file_sep>package com.example.tic.config
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.FileNotFoundException
class ConfigReaderTest {
@Test
fun `Should give correct property values for given file`() {
val configReader = ConfigReader("../../../../tic.properties")
Assertions.assertEquals('i', configReader.player1Sign)
Assertions.assertEquals('j', configReader.player2Sign)
Assertions.assertEquals('*', configReader.computerSign)
}
@Test()
fun `Should report error for incorrect filepath`() {
Assertions.assertThrows(FileNotFoundException::class.java) {
ConfigReader("incorrectFilePath")
}
}
}<file_sep>package com.example.tic.player
import com.example.tic.Board
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.PrintStream
class ManTest {
@Test
fun `Should Create a Man Player with expected sign`() {
Assertions.assertEquals(Man('s').sign, 's')
}
@Test
fun `Should play a valid move `(){
val expected = "1,2\n"
val fakeIS = ByteArrayInputStream(expected.toByteArray())
System.setIn(fakeIS)
var board = Board(3)
Man('s').play(board,ArrayList())
Assertions.assertEquals(board.getSignAt(1,2),'s')
}
@Test
fun `Should print error on invalid move input and ask again`(){
val expected = "1,21\n1,2\n"
val fakeIS = ByteArrayInputStream(expected.toByteArray())
System.setIn(fakeIS)
var board = Board(3)
val fakeOut = ByteArrayOutputStream()
val fakePS = PrintStream(fakeOut)
System.setOut(fakePS)
Man('s').play(board,ArrayList())
Assertions.assertTrue(fakeOut.toString().contains("incorrect input: not in limit"))
}
@Test
fun `Should print error input that is already marked`(){
val expected = "1,2\n1,0\n"
val fakeIS = ByteArrayInputStream(expected.toByteArray())
System.setIn(fakeIS)
var board = Board(3)
board.mark(1,2,'x')
val fakeOut = ByteArrayOutputStream()
val fakePS = PrintStream(fakeOut)
System.setOut(fakePS)
Man('s').play(board,ArrayList())
Assertions.assertTrue(fakeOut.toString().contains("Already marked"))
}
} | 535ef13f500ddf25fe9f29c37b82ab96f0741602 | [
"Kotlin",
"INI",
"Gradle"
] | 13 | Kotlin | warlord-x/tic-kotlin | 0b948b61e9e1de74d0cd2276a2d70fd3bddc427d | f1e946fe436558ff3a3ab7fc5cf6f7280e1aa33e |
refs/heads/main | <file_sep># ProjectThreads
small project to play a little bit with threads in C++ 20
<file_sep>#pragma once
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <atomic>
namespace Threads
{
#define NUM_THREADS 10
class FileManager
{
public:
FileManager() = default;
~FileManager();
public:
void Start();
void ShutDown();
private:
std::vector<std::string> m_buffer;
std::vector<std::thread> m_poolWorkesA;
std::vector<std::thread> m_poolWorkesB;
std::vector<std::string> m_lines;
std::atomic<bool> m_bRunning{ false };
std::atomic<bool> m_sentEndMsg{ false };
std::mutex m_bufferMutex;
std::mutex m_fileMutex;
std::mutex m_linesMutex;
private:
void ReadBuffer();
void ReadLines();
void WriteBuffer(const std::string& msg);
void ReadFile();
void WriteFile(std::ofstream& fileB, const std::string& msg);
void RunWorkerA();
void RunWorkerB();
};
};<file_sep>cmake_minimum_required(VERSION 3.20)
#set the project name and version
project(ProjectThreads VERSION 0.1)
#specify the c++ standard
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED true)
#configure file
configure_file("src/ProjectThreadsConfig.h.in" "ProjectThreadsConfig.h")
file(GLOB SOURCES "src/*.cpp", "src/*/*.cpp")
#add the executable
add_executable(${PROJECT_NAME} ${SOURCES})
#target include dir
target_include_directories(ProjectThreads
PUBLIC
"${PROJECT_BINARY_DIR}"
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)<file_sep>#include "FileManager.h"
#define END_MESSAGE "END"
Threads::FileManager::~FileManager()
{
ShutDown();
}
void Threads::FileManager::Start()
{
m_bRunning = true;
ReadFile();
for (int i = 0; i < NUM_THREADS; i++)
{
m_poolWorkesA.push_back(std::thread(&FileManager::RunWorkerA, this));
}
for (int i = 0; i < NUM_THREADS; i++)
{
m_poolWorkesB.push_back(std::thread(&FileManager::RunWorkerB, this));
}
while (m_bRunning);
}
void Threads::FileManager::ShutDown()
{
std::cout << "Shutdowning" << std::endl;
m_bRunning = false;
for (std::thread& every_thread : m_poolWorkesA)
{
if(every_thread.joinable())
every_thread.join();
}
for (std::thread& every_thread : m_poolWorkesB)
{
if (every_thread.joinable())
every_thread.join();
}
m_poolWorkesA.clear();
m_poolWorkesB.clear();
}
void Threads::FileManager::ReadBuffer()
{
std::ofstream fileB{ "FileOutput.txt",std::ios::app };
if (!fileB)
return;
while (m_bRunning)
{
std::string msg;
{
std::scoped_lock<std::mutex> sl(m_bufferMutex);
if (m_buffer.empty())
continue;
msg = m_buffer.front();
m_buffer.erase(m_buffer.begin());
if (msg == END_MESSAGE && m_buffer.empty())
break;
}
WriteFile(fileB, msg);
}
m_bRunning = false;
}
void Threads::FileManager::WriteBuffer(const std::string& msg)
{
if (msg.empty())
return;
std::scoped_lock<std::mutex> sl(m_bufferMutex);
m_buffer.push_back(msg);
}
void Threads::FileManager::ReadLines()
{
while (m_bRunning)
{
std::string line;
{
std::scoped_lock<std::mutex> sl(m_linesMutex);
if (m_lines.empty())
{
break;
}
line = m_lines.front();
m_lines.erase(m_lines.begin());
}
WriteBuffer(line);
}
if (!m_sentEndMsg)
{
m_sentEndMsg = true;
WriteBuffer(END_MESSAGE);
}
}
void Threads::FileManager::ReadFile()
{
//std::scoped_lock<std::mutex> sl(m_fileMutex);
std::ifstream fileA{ "FileData.txt" };
std::string output;
if (!fileA.is_open())
{
std::cout << strerror(errno);
}
while(std::getline(fileA, output))
{
#ifdef _DEBUG
#endif // _DEBUG
m_lines.push_back(output);
}
}
void Threads::FileManager::WriteFile(std::ofstream& fileB, const std::string& msg)
{
std::scoped_lock<std::mutex> sl(m_fileMutex);
if (fileB)
{
std::thread::id this_id = std::this_thread::get_id();
std::cout << "this " << this_id << " writes :" << msg << "\n";
fileB << msg << "\n";
}
else
{
std::thread::id this_id = std::this_thread::get_id();
std::cout << "this " << this_id << " could no write :" << msg << "\n";
}
}
void Threads::FileManager::RunWorkerA()
{
std::cout << "Starting WorkerA" << std::endl;
ReadLines();
}
void Threads::FileManager::RunWorkerB()
{
std::cout << "Starting WorkerB" << std::endl;
ReadBuffer();
}<file_sep>#include <string>
#include <thread>
#include <functional>
#include <vector>
#include "ProjectThreadsConfig.h"
#include "FileManager.h"
int main ()
{
std::cout << "Project Major Version " << ProjectThreads_VERSION_MAJOR << std::endl;
std::cout << "Project Minor Version " << ProjectThreads_VERSION_MINOR << std::endl;
Threads::FileManager fm;
fm.Start();
return 0;
} | a8a0e8016654b90657b6fc3157dfc81c6c8dda3c | [
"Markdown",
"CMake",
"C++"
] | 5 | Markdown | andersonfr/ProjectThreads | c38cb744e1d7611d080dbd299f09b5d9b5bfa6ca | 3e0a2b0090f0a8ac6c2e85f101ec1dcb25698e72 |
refs/heads/master | <repo_name>aaltamirano1/empty<file_sep>/index.js
'use strict';
function getLyrics(artist, title) {
}
function displayResults(responseJson) {
}
function watchForm() {
}
$(watchForm);
| 33381f5af7c948d2079d37c84539767deb504a0f | [
"JavaScript"
] | 1 | JavaScript | aaltamirano1/empty | 2891bc94d7834cf23a9eb898ca4343410a7ef245 | 4c4c8aba45f7b1854e2cbbf05fa99f4a84e81d09 |
refs/heads/master | <repo_name>stefan1968/flickr<file_sep>/src/imageBox.js
import React from 'react';
// our main image box, it uses dangerouslySetInnerHTML to process the description part of the flickr metadata.
export class ImageBox extends React.Component {
constructor(props) {
super(props);
this.state = { visible: true };
}
render() {
// this code isn't necessary, but is good react practice for hiding components.
let tag_div = <div />;
if (!this.state.visible) {
return <div />;
} else {
const c_string = `${this.props.title} by ${this.props.author}`
if (this.props.tags) {
const t_string = `tags: ${this.props.tags}`
tag_div = <span className="tags">{t_string}</span>;
}
function createDescHTML(h) { return {__html: h}; };
return (
<div className="box_wrapper">
<div className="upper">
<div className="thumbnail">
<img src={this.props.img_url} alt="" />
</div>
</div>
<div className="lower">
<span className="title">{c_string}</span>
{tag_div}
<span className="desc"><div dangerouslySetInnerHTML={createDescHTML(`<span class="desc_text">description:</span><div class="desc_html">${this.props.desc}</div>`)} /></span>
</div>
</div>
);
}
}
}
<file_sep>/README.md
Flickr APP.
This app was written with React/Create-React-App/Jquery.
It conforms to the current FB/React standards and has no errors or warning when running.
| 4f02a490ec1d28d4a523f9a729fbf5467522c670 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | stefan1968/flickr | 643a3cc5fc441de36d3d7b8aaab011918f0a2d37 | 991b76045cbe9352127912b553f2ff376ae3dd9c |
refs/heads/master | <repo_name>NobiNobita/BoL_Studio<file_sep>/Scripts/Common/SourceLib.lua
-- Change autoUpdate to false if you wish to not receive auto updates.
-- Change silentUpdate to true if you wish not to receive any message regarding updates
local autoUpdate = true
local silentUpdate = false
local version = 1.020
--[[
LazyLib - a common library by Team TheSource
Copyright (C) 2014 <NAME>Source
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/.
Introduction:
We were tired of updating every single script we developed so far so we decided to have it a little bit
more dynamic with a custom library which we can update instead and every script using it will automatically
be updated (of course only the parts which are in this lib). So let's say packet casting get's fucked up
or we want to change the way some drawing is done, we just need to update it here and all scripts will have
the same tweaks then.
Contents:
LazyUpdater -- One of the most basic functions for every script we use
Spell -- Spells handled the way they should be handled
DrawManager -- Easy drawing of all kind of things, comes along with some other classes such as Circle
DamageLib -- Calculate the damage done do others and even print it on their healthbar
STS -- SimpleTargetSelector is a simple and yet powerful target selector to provide very basic target selecting
]]
--[[
'||' '||' '|' '|| .
|| .... ...... .... ... || | ... ... .. || .... .||. .... ... ..
|| '' .|| ' .|' '|. | || | ||' || .' '|| '' .|| || .|...|| ||' ''
|| .|' || .|' '|.| || | || | |. || .|' || || || ||
.||.....| '|..'|' ||....| '| '|..' ||...' '|..'||. '|..'|' '|.' '|...' .||.
.. | ||
'' ''''
LazyUpdater - a simple updater class
Introduction:
Scripts that want to use this class need to have a version field at the beginning of the script, like this:
local version = YOUR_VERSION (YOUR_VERSION can either be a string a a numeric value!)
It does not need to be exactly at the beginning, like in this script, but it has to be within the first 100
chars of the file, otherwise the webresult won't see the field, as it gathers only about 100 chars
Functions:
LazyUpdater(scriptName, version, hostPath, filePath)
Members:
LazyUpdater.silent | bool | Defines wheather to print notifications or not
Methods:
LazyUpdater:SetSilent(silent)
LazyUpdater:CheckUpdate()
]]
class 'LazyUpdater'
--[[
Create a new instance of LazyUpdater
@param scriptName | string | Name of the script which should be used when printed in chat
@param version | float/string | Current version of the script
@param host | string | Host, for example "bitbucket.org" or "raw.github.com"
@param hostPath | string | Raw path to the script which should be updated
@param filePath | string | Path to the file which should be replaced when updating the script
]]
function LazyUpdater:__init(scriptName, version, host, hostPath, filePath)
self.printMessage = function(message) if not self.silent then print("<font color=\"#6699ff\"><b>" .. self.UPDATE_SCRIPT_NAME .. ":</b></font> <font color=\"#FFFFFF\">" .. message .. "</font>") end end
self.getVersion = function(version) return tonumber(string.match(version, "%d+%.%d+")) end
self.UPDATE_SCRIPT_NAME = scriptName
self.UPDATE_HOST = host
self.UPDATE_PATH = hostPath .. "?rand="..math.random(1,10000)
self.UPDATE_FILE_PATH = filePath
self.UPDATE_URL = "https://"..self.UPDATE_HOST..self.UPDATE_PATH
self.FILE_VERSION = self.getVersion(version)
self.SERVER_VERSION = nil
-- Members
self.silent = false
end
--[[
Allows or disallows the updater to print info about updating
@param | bool | Message output or not
@return | class | The current instance
]]
function LazyUpdater:SetSilent(silent)
self.silent = silent
return self
end
--[[
Check for an update and downloads it when available
]]
function LazyUpdater:CheckUpdate()
-- Validate callback
callback = callback and type(callback) == "function" and callback or nil
local webResult = GetWebResult(self.UPDATE_HOST, self.UPDATE_PATH)
if webResult then
self.SERVER_VERSION = string.match(webResult, "%s*local%s+version%s+=%s+.*%d+%.%d+")
if self.SERVER_VERSION then
self.SERVER_VERSION = self.getVersion(self.SERVER_VERSION)
if self.FILE_VERSION < self.SERVER_VERSION then
self.printMessage("New version available: v" .. self.SERVER_VERSION)
self.printMessage("Updating, please don't press F9")
DelayAction(function () DownloadFile(self.UPDATE_URL, self.UPDATE_FILE_PATH, function () self.printMessage("Successfully updated, please reload!") end) end, 2)
else
self.printMessage("You've got the latest version: v" .. self.SERVER_VERSION)
end
else
self.printMessage("Something went wrong! Please manually update the script!")
end
else
self.printMessage("Error downloading version info!")
end
end
--[[
.|'''.| '|| '||
||.. ' ... ... .... || ||
''|||. ||' || .|...|| || ||
. '|| || | || || ||
|'....|' ||...' '|...' .||. .||.
||
''''
Spell - Handled with ease!
Functions:
Spell(spellId, range, packetCast)
Members:
Spell.range | float | Range of the spell, please do NOT change this value, use Spell:SetRange() instead
Spell.rangeSqr | float | Squared range of the spell, please do NOT change this value, use Spell:SetRange() instead
Spell.packetCast | bool | Set packet cast state
-- This only applies for skillshots
Spell.sourcePosition | vector | From where the spell is casted, default: player
Spell.sourceRange | vector | From where the range should be calculated, default: player
-- This only applies for AOE skillshots
Spell.minTargetsAoe | int | Set minimum targets for AOE damage
Methods:
Spell:SetRange(range)
Spell:SetSource(source)
Spell:SetSourcePosition(source)
Spell:SetSourceRange(source)
Spell:SetSkillshot(VP, skillshotType, width, delay, speed, collision)
Spell:SetAOE(useAoe, radius, minTargetsAoe)
Spell:SetHitChance(hitChance)
Spell:ValidTarget(target)
Spell:GetPrediction(target)
Spell:CastIfDashing(target)
Spell:CastIfImmobile(target)
Spell:Cast(param1, param2)
Spell:AddAutomation(automationId, func)
Spell:RemoveAutomation(automationId)
Spell:ClearAutomations()
Spell:TrackCasting(spellName)
Spell:WillHitTarget()
Spell:RegisterCastCallback(func)
Spell:GetLastCastTime()
Spell:IsInRange(target, from)
Spell:IsReady()
Spell:GetManaUsage()
Spell:GetCooldown()
Spell:GetLevel()
Spell:GetName()
]]
class 'Spell'
-- Class related constants
SKILLSHOT_LINEAR = 0
SKILLSHOT_CIRCULAR = 1
SKILLSHOT_CONE = 2
-- Different SpellStates returned when Spell:Cast() is called
SPELLSTATE_TRIGGERED = 0
SPELLSTATE_OUT_OF_RANGE = 1
SPELLSTATE_LOWER_HITCHANCE = 2
SPELLSTATE_COLLISION = 3
SPELLSTATE_NOT_ENOUGH_TARGETS = 4
SPELLSTATE_NOT_DASHING = 5
SPELLSTATE_DASHING_CANT_HIT = 6
SPELLSTATE_NOT_IMMOBILE = 7
SPELLSTATE_INVALID_TARGET = 8
SPELLSTATE_NOT_TRIGGERED = 9
-- Spell automations
local __spell_automations = nil
function __spell_OnTick()
for index, spell in ipairs(__spell_automations) do
if #spell._automations == 0 then
table.remove(__spell_automations, index)
else
for _, automation in ipairs(spell._automations) do
local doCast, param1, param2 = automation.func()
if doCast == true then
spell:Cast(param1, param2)
end
end
end
end
end
-- Spell tracking
local __spell_trackedSpells = nil
function __spell_OnProcSpell(unit, spell)
if #__spell_trackedSpells > 0 and unit and unit.valid and unit.isMe and spell and spell.name then
for index, spell in ipairs(__spell_trackedSpells) do
if sell._spellName and spell._spellName == spell.name then
spell._lastCastTime = os.clock()
spell._castCallback(spell)
elseif not spell._spellName then
table.remove(__spell_trackedSpells, index)
end
end
end
end
-- Spell identifier number used for comparing spells
local spellNum = 1
--[[
New instance of Spell
@param spellId | int | Spell ID (_Q, _W, _E, _R)
@param range | float | Range of the spell
@param packetCast | bool | (optional) Enable packet casting
]]
function Spell:__init(spellId, range, packetCast)
assert(spellId ~= nil and range ~= nil and type(spellId) == "number" and type(range) == "number", "Spell: Can't initialize Spell without valid arguments.")
self.spellId = spellId
self:SetRange(range)
self.packetCast = packetCast or false
self:SetSource(player)
self._automations = {}
self._spellNum = spellNum
spellNum = spellNum + 1
end
--[[
Update the spell range with the new given value
@param range | float | Range of the spell
@return | class | The current instance
]]
function Spell:SetRange(range)
assert(range and type(range) == "number", "Spell: range is invalid")
self.range = range
self.rangeSqr = math.pow(range, 2)
return self
end
--[[
Update both the sourcePosition and sourceRange from where everything will be calculated
@param source | Cunit | Source position, for example player
@return | class | The current instance
]]
function Spell:SetSource(source)
assert(source, "Spell: source can't be nil!")
self.sourcePosition = source
self.sourceRange = source
return self
end
--[[
Update the source posotion from where the spell will be shot
@param source | Cunit | Source position from where the spell will be shot, player by default
@ return | class | The current instance
]]
function Spell:SetSourcePosition(source)
assert(source, "Spell: source can't be nil!")
self.sourcePosition = source
return self
end
--[[
Update the source unit from where the range will be calculated
@param source | Cunit | Source object unit from where the range should be calculed
@return | class | The current instance
]]
function Spell:SetSourceRange(source)
assert(source, "Spell: source can't be nil!")
self.sourceRange = source
return self
end
--[[
Define this spell as skillshot (can't be reversed)
@param VP | class | Instance of VPrediction
@param skillshotType | int | Type of this skillshot
@param width | float | Width of the skillshot
@param delay | float | (optional) Delay in seconds
@param speed | float | (optional) Speed in units per second
@param collision | bool | (optional) Respect unit collision when casting
@rerurn | class | The current instance
]]
function Spell:SetSkillshot(VP, skillshotType, width, delay, speed, collision)
assert(skillshotType ~= nil, "Spell: Need at least the skillshot type!")
self.VP = VP
self.skillshotType = skillshotType
self.width = width or 0
self.delay = delay or 0
self.speed = speed
self.collision = collision
if not self.hitChance then self.hitChance = 2 end
return self
end
--[[
Set the AOE status of this spell, this can be changed later
@param useAoe | bool | New AOE state
@param radius | float | Radius of the AOE damage
@param minTargetsAoe | int | Minimum targets to be hitted by the AOE damage
@rerurn | class | The current instance
]]
function Spell:SetAOE(useAoe, radius, minTargetsAoe)
self.useAoe = useAoe or false
self.radius = radius or self.width
self.minTargetsAoe = minTargetsAoe or 0
return self
end
--[[
Set the hitChance of the predicted target position when to cast
@param hitChance | int | New hitChance for predicted positions
@rerurn | class | The current instance
]]
function Spell:SetHitChance(hitChance)
self.hitChance = hitChance or 2
return self
end
--[[
Checks if the given target is valid for the spell
@param target | userdata | Target to be checked if valid
@return | bool | Valid target or not
]]
function Spell:ValidTarget(target, range)
return ValidTarget(target, range or self.range)
end
--[[
Returns the prediction results from VPrediction to use for custom reasons
@return | various data | The original result from VPrediction
]]
function Spell:GetPrediction(target)
if self.skillshotType ~= nil then
if self.skillshotType == SKILLSHOT_LINEAR then
if self.useAoe then
return self.VP:GetLineAOECastPosition(target, self.delay, self.radius, self.range, self.speed, self.sourcePosition)
else
return self.VP:GetLineCastPosition(target, self.delay, self.width, self.range, self.speed, self.sourcePosition, self.collision)
end
elseif self.skillshotType == SKILLSHOT_CIRCULAR then
if self.useAoe then
return self.VP:GetCircularAOECastPosition(target, self.delay, self.radius, self.range, self.speed, self.sourcePosition)
else
return self.VP:GetCircularCastPosition(target, self.delay, self.width, self.range, self.speed, self.sourcePosition, self.collision)
end
elseif self.skillshotType == SKILLSHOT_CONE then
if self.useAoe then
return self.VP:GetConeAOECastPosition(target, self.delay, self.radius, self.range, self.speed, self.sourcePosition)
else
return self.VP:GetLineCastPosition(target, self.delay, self.width, self.range, self.speed, self.sourcePosition, self.collision)
end
end
end
end
--[[
Tries to cast the spell when the target is dashing
@param target | Cunit | Dashing target to attack
@param return | int | SpellState of the current spell
]]
function Spell:CastIfDashing(target)
-- Don't calculate stuff when target is invalid
if not ValidTarget(target) then return SPELLSTATE_INVALID_TARGET end
if self.skillshotType ~= nil then
local isDashing, canHit, position = self.VP:IsDashing(target, self.delay + 0.07 + GetLatency() / 2000, self.width, self.speed, self.sourcePosition)
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, position) then return SPELLSTATE_OUT_OF_RANGE end
if isDashing and canHit then
-- Collision
if not self.collision or self.collision and not self.VP:CheckMinionCollision(target, position, self.delay + 0.07 + GetLatency() / 2000, self.width, self.range, self.speed, self.sourcePosition, false, true) then
return self:__Cast(self.spellId, position.x, position.z)
else
return SPELLSTATE_COLLISION
end
elseif not isDashing then return SPELLSTATE_NOT_DASHING
else return SPELLSTATE_DASHING_CANT_HIT end
else
local isDashing, canHit, position = self.VP:IsDashing(target, 0.25 + 0.07 + GetLatency() / 2000, 1, math.huge, self.sourcePosition)
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, position) then return SPELLSTATE_OUT_OF_RANGE end
if isDashing and canHit then
return self:__Cast(position.x, position.z)
elseif not isDashing then return SPELLSTATE_NOT_DASHING
else return SPELLSTATE_DASHING_CANT_HIT end
end
return SPELLSTATE_NOT_TRIGGERED
end
--[[
Tries to cast the spell when the target is immobile
@param target | Cunit | Immobile target to attack
@param return | int | SpellState of the current spell
]]
function Spell:CastIfImmobile(target)
-- Don't calculate stuff when target is invalid
if not ValidTarget(target) then return SPELLSTATE_INVALID_TARGET end
if self.skillshotType ~= nil then
local isImmobile, position = self.VP:IsImmobile(target, self.delay + 0.07 + GetLatency() / 2000, self.width, self.speed, self.sourcePosition)
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, position) then return SPELLSTATE_OUT_OF_RANGE end
if isImmobile then
-- Collision
if not self.collision or (self.collision and not self.VP:CheckMinionCollision(target, position, self.delay + 0.07 + GetLatency() / 2000, self.width, self.range, self.speed, self.sourcePosition, false, true)) then
return self:__Cast(position.x, position.z)
else
return SPELLSTATE_COLLISION
end
else return SPELLSTATE_NOT_IMMOBILE end
else
local isImmobile, position = self.VP:IsImmobile(target, 0.25 + 0.07 + GetLatency() / 2000, 1, math.huge, self.sourcePosition)
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, target) then return SPELLSTATE_OUT_OF_RANGE end
if isImmobile then
return self:__Cast(target)
else
return SPELLSTATE_NOT_IMMOBILE
end
end
return SPELLSTATE_NOT_TRIGGERED
end
--[[
Cast the spell, respecting previously made decisions about skillshots and AOE stuff
@param param1 | userdata/float | When param2 is nil then this can be the target object, otherwise this is the X coordinate of the skillshot position
@param param2 | float | Z coordinate of the skillshot position
@param return | int | SpellState of the current spell
]]
function Spell:Cast(param1, param2)
if self.skillshotType ~= nil and param1 ~= nil and param2 == nil then
-- Don't calculate stuff when target is invalid
if not ValidTarget(param1) then return SPELLSTATE_INVALID_TARGET end
local castPosition, hitChance, position, nTargets
if self.skillshotType == SKILLSHOT_LINEAR or self.skillshotType == SKILLSHOT_CONE then
if self.useAoe then
castPosition, hitChance, nTargets = self:GetPrediction(param1)
else
castPosition, hitChance, position = self:GetPrediction(param1)
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, position) then return SPELLSTATE_OUT_OF_RANGE end
end
elseif self.skillshotType == SKILLSHOT_CIRCULAR then
if self.useAoe then
castPosition, hitChance, nTargets = self:GetPrediction(param1)
else
castPosition, hitChance, position = self:GetPrediction(param1)
-- Out of range
if math.pow(self.range + self.width + self.VP:GetHitBox(param1), 2) < GetDistanceSqr(self.sourceRange, position) then return SPELLSTATE_OUT_OF_RANGE end
end
end
-- AOE not enough targets
if nTargets and nTargets < self.minTargetsAoe then return SPELLSTATE_NOT_ENOUGH_TARGETS end
-- Collision detected
if hitChance == -1 then return SPELLSTATE_COLLISION end
-- Hitchance too low
if hitChance and hitChance < self.hitChance then return SPELLSTATE_LOWER_HITCHANCE end
-- Out of range
if self.rangeSqr < GetDistanceSqr(self.sourceRange, castPosition) then return SPELLSTATE_OUT_OF_RANGE end
param1 = castPosition.x
param2 = castPosition.z
end
-- Cast the spell
return self:__Cast(param1, param2)
end
--[[
Internal function, do not use this!
]]
function Spell:__Cast(param1, param2)
if self.packetCast then
if param1 ~= nil and param2 ~= nil then
Packet("S_CAST", {spellId = self.spellId, toX = param1, toY = param2, fromX = param1, fromY = param2}):send()
elseif param1 ~= nil then
Packet("S_CAST", {spellId = self.spellId, toX = param1.x, toY = param1.z, fromX = param1.x, fromY = param1.z, targetNetworkId = param1.networkID}):send()
else
Packet("S_CAST", {spellId = self.spellId, toX = player.x, toY = player.z, fromX = player.x, fromY = player.z, targetNetworkId = player.networkID}):send()
end
else
if param1 ~= nil and param2 ~= nil then
CastSpell(self.spellId, param1, param2)
elseif param1 ~= nil then
CastSpell(self.spellId, param1)
else
CastSpell(self.spellId)
end
end
return SPELLSTATE_TRIGGERED
end
--[[
Add an automation to the spell to let it cast itself when a certain condition is met
@param automationId | string/int | The ID of the automation, example "AntiGapCloser"
@param func | function | Function to be called when checking, should return a bool value indicating if it should be casted and optionally the cast params (ex: target or x and z)
]]
function Spell:AddAutomation(automationId, func)
assert(automationId, "Spell: automationId is invalid!")
assert(func and type(func) == "function", "Spell: func is invalid!")
for index, automation in ipairs(self._automations) do
if automation.id == automationId then return end
end
table.insert(self._automations, { id == automationId, func = func })
if not __spell_automations then
__spell_automations = {}
AddTickCallback(__spell_OnTick)
end
for index, spell in ipairs(__spell_automations) do
if spell == self then return end
end
table.insert(__spell_automations, self)
end
--[[
Remove and automation by it's id
@param automationId | string/int | The ID of the automation, example "AntiGapCloser"
]]
function Spell:RemoveAutomation(automationId)
assert(automationId, "Spell: automationId is invalid!")
for index, automation in ipairs(self._automations) do
if automation.id == automationId then
table.remove(self._automations, index)
break
end
end
end
--[[
Clear all automations assinged to this spell
]]
function Spell:ClearAutomations()
self._automations = {}
end
--[[
Track the spell like in OnProcessSpell to add more features to Spell
@param spellName | string | Case sensitive name of the spell
@return | class | The current instance
]]
function Spell:TrackCasting(spellName)
assert(spellName and type(spellName) == "string" and self._spellName == nil, "Spell: spellName is invalid or already registered!")
self._spellName = spellName
if __spell_trackedSpells == nil then
__spell_trackedSpells = {}
AddProcessSpellCallback(__spell_OnProcSpell)
end
table.insert(__spell_trackedSpells, self)
return self
end
--[[
When the spell is casted and about to hit a target, this will return the following
@return | CUnit,float | The target unit, the remaining time in seconds it will take to hit the target, otherwise nil
]]
function Spell:WillHitTarget()
-- TODO: VPrediction expert's work ;D
end
--[[
Register a function which will be triggered when the spell is being casted the function will be given the spell object as parameter
@param func | function | Function to be called when the spell is being processed (casted)
]]
function Spell:RegisterCastCallback(func)
assert(func and type(func) == "function" and self._castCallback == nil, "Spell: func is either invalid or a callback is already registered!")
self._castCallback = func
end
--[[
Returns the os.clock() time when the spell was last casted
@return | float | Time in seconds when the spell was last casted or nil if the spell was never casted or spell is not tracked
]]
function Spell:GetLastCastTime()
return self._lastCastTime
end
--[[
Get if the target is in range
@return | bool | In range or not
]]
function Spell:IsInRange(target, from)
return self.rangeSqr >= GetDistanceSqr(target, from or self.sourcePosition)
end
--[[
Get if the spell is ready or not
@return | bool | Spell state ready or not
]]
function Spell:IsReady()
return player:CanUseSpell(self.spellId) == READY
end
--[[
Get the mana usage of the spell
@return | float | Mana usage of the spell
]]
function Spell:GetManaUsage()
return player:GetSpellData(self.spellId).mana
end
--[[
Get the CURRENT cooldown of the spell
@return | float | Current cooldown of the spell
]]
function Spell:GetCooldown(current)
return current and player:GetSpellData(self.spellId).currentCd or player:GetSpellData(self.spellId).totalCooldown
end
--[[
Get the stat points assinged to this spell (level)
@return | int | Stat points assinged to this spell (level)
]]
function Spell:GetLevel()
return player:GetSpellData(self.spellId).level
end
--[[
Get the name of the spell
@return | string | Name of the the spell
]]
function Spell:GetName()
return player:GetSpellData(self.spellId).name
end
function Spell:__eq(other)
return other and other._spellNum and other._spellNum == self._spellNum or false
end
--[[
'||''|. '|| ||'
|| || ... .. .... ... ... ... ||| ||| .... .. ... .... ... . .... ... ..
|| || ||' '' '' .|| || || | |'|..'|| '' .|| || || '' .|| || || .|...|| ||' ''
|| || || .|' || ||| ||| | '|' || .|' || || || .|' || |'' || ||
.||...|' .||. '|..'|' | | .|. | .||. '|..'|' .||. ||. '|..'|' '||||. '|...' .||.
.|....'
DrawManager - Tired of having to draw everything over and over again? Then use this!
Functions:
DrawManager()
Methods:
DrawManager:AddCircle(circle)
DrawManager:CreateCircle(position, radius, width, color)
DrawManager:OnDraw()
]]
class 'DrawManager'
--[[
New instance of DrawManager
]]
function DrawManager:__init()
self.objects = {}
AddDrawCallback(function() self:OnDraw() end)
end
--[[
Add an existing circle to the draw manager
]]
function DrawManager:AddCircle(circle)
assert(circle, "DrawManager: circle is invalid!")
for _, object in ipairs(self.objects) do
assert(object ~= circle, "DrawManager: object was already in DrawManager")
end
table.insert(self.objects, circle)
end
--[[
Create a new circle and add it aswell to the DrawManager instance
@param position | vector | Center of the circle
@param radius | float | Radius of the circle
@param width | int | Width of the circle outline
@param color | table | Color of the circle in a tale format { a, r, g, b }
@return | class | Instance of the newly create Circle class
]]
function DrawManager:CreateCircle(position, radius, width, color)
local circle = _Circle(position, radius, width, color)
self:AddCircle(circle)
return circle
end
--[[
DO NOT CALL THIS MANUALLY! This will be called automatically.
]]
function DrawManager:OnDraw()
for _, object in ipairs(self.objects) do
if object.enabled then
object:Draw()
end
end
end
--[[
..|'''.| || '||
.|' ' ... ... .. .... || ....
|| || ||' '' .| '' || .|...||
'|. . || || || || ||
''|....' .||. .||. '|...' .||. '|...'
Functions:
_Circle(position, radius, width, color)
Members:
_Circle.enabled | bool | Enable or diable the circle (displayed)
_Circle.mode | int | See circle modes below
_Circle.position | vector | Center of the circle
_Circle.radius | float | Radius of the circle
-- These are not changeable when a menu is set
_Circle.width | int | Width of the circle outline
_Circle.color | table | Color of the circle in a tale format { a, r, g, b }
_Circle.quality | float | Quality of the circle, the higher the smoother the circle
Methods:
_Circle:AddToMenu(menu, paramText, addColor, addWidth, addQuality)
_Circle:SetEnabled(enabled)
_Circle:Set2D()
_Circle:Set3D()
_Circle:SetMinimap()
_Circle:SetQuality(qualtiy)
_Circle:SetDrawCondition(condition)
_Circle:Draw()
]]
class '_Circle'
-- Circle modes
CIRCLE_2D = 0
CIRCLE_3D = 1
CIRCLE_MINIMAP = 2
-- Number of currently created circles
local circleCount = 1
--[[
New instance of Circle
@param position | vector | Center of the circle
@param radius | float | Radius of the circle
@param width | int | Width of the circle outline
@param color | table | Color of the circle in a tale format { a, r, g, b }
]]
function _Circle:__init(position, radius, width, color)
assert(position and position.x and (position.y and position.z or position.y), "_Circle: position is invalid!")
assert(radius and type(radius) == "number", "_Circle: radius is invalid!")
assert(not color or color and type(color) == "table" and #color == 4, "_Circle: color is invalid!")
self.enabled = true
self.condition = nil
self.menu = nil
self.menuEnabled = nil
self.menuColor = nil
self.menuWidth = nil
self.menuQuality = nil
self.mode = CIRCLE_3D
self.position = position
self.radius = radius
self.width = width or 1
self.color = color or { 255, 255, 255, 255 }
self.quality = radius / 5
self._circleId = "circle" .. circleCount
self._circleNum = circleCount
circleCount = circleCount + 1
end
--[[
Adds this circle to a given menu
@param menu | scriptConfig | Instance of script config to add this circle to
@param paramText | string | Text for the menu entry
@param addColor | bool | Add color option
@param addWidth | bool | Add width option
@param addQuality | bool | Add quality option
@return | class | The current instance
]]
function _Circle:AddToMenu(menu, paramText, addColor, addWidth, addQuality)
assert(menu, "_Circle: menu is invalid!")
assert(self.menu == nil, "_Circle: Already bound to a menu!")
menu:addSubMenu(paramText or "Circle " .. self._circleNum, self._circleId)
self.menu = menu[self._circleId]
-- Enabled
local paramId = self._circleId .. "enabled"
self.menu:addParam(paramId, "Enabled", SCRIPT_PARAM_ONOFF, self.enabled)
self.menuEnabled = self.menu._param[#self.menu._param]
if addColor or addWidth or addQuality then
-- Color
if addColor then
paramId = self._circleId .. "color"
self.menu:addParam(paramId, "Color", SCRIPT_PARAM_COLOR, self.color)
self.menuColor = self.menu._param[#self.menu._param]
end
-- Width
if addWidth then
paramId = self._circleId .. "width"
self.menu:addParam(paramId, "Width", SCRIPT_PARAM_SLICE, self.width, 1, 5)
self.menuWidth = self.menu._param[#self.menu._param]
end
-- Quality
if addQuality then
paramId = self._circleId .. "quality"
self.menu:addParam(paramId, "Quality", SCRIPT_PARAM_SLICE, math.round(self.quality), 10, math.round(self.radius / 5))
self.menuQuality = self.menu._param[#self.menu._param]
end
end
return self
end
--[[
Set the enable status of the circle
@param enabled | bool | Enable state of this circle
@return | class | The current instance
]]
function _Circle:SetEnabled(enabled)
self.enabled = enabled
return self
end
--[[
Set this circle to be displayed 2D
@return | class | The current instance
]]
function _Circle:Set2D()
self.mode = CIRCLE_2D
return self
end
--[[
Set this circle to be displayed 3D
@return | class | The current instance
]]
function _Circle:Set3D()
self.mode = CIRCLE_3D
return self
end
--[[
Set this circle to be displayed on the minimap
@return | class | The current instance
]]
function _Circle:SetMinimap()
self.mode = CIRCLE_MINIMAP
return self
end
--[[
Set the display quality of this circle
@return | class | The current instance
]]
function _Circle:SetQuality(qualtiy)
assert(qualtiy and type(qualtiy) == "number", "_Circle: quality is invalid!")
self.quality = quality
return self
end
--[[
Set the draw condition of this circle
@return | class | The current instance
]]
function _Circle:SetDrawCondition(condition)
assert(condition and type(condition) == "function", "_Circle: condition is invalid!")
self.condition = condition
return self
end
--[[
Draw this circle, should only be called from OnDraw()
]]
function _Circle:Draw()
-- Don't draw if condition is not met
if self.condition ~= nil and self.condition() == false then return end
-- Menu found
if self.menu then
if self.menuEnabled ~= nil then
if not self.menu[self.menuEnabled.var] then return end
end
if self.menuColor ~= nil then
self.color = self.menu[self.menuColor.var]
end
if self.menuWidth ~= nil then
self.width = self.menu[self.menuWidth.var]
end
if self.menuQuality ~= nil then
self.quality = self.menu[self.menuQuality.var]
end
end
local center = WorldToScreen(D3DXVECTOR3(self.position.x, self.position.y, self.position.z))
if not self:PointOnScreen(center.x, center.y) then
return
end
if self.mode == CIRCLE_2D then
DrawCircle2D(self.position.x, self.position.y, self.radius, self.width, TARGB(self.color), self.quality)
elseif self.mode == CIRCLE_3D then
DrawCircle3D(self.position.x, self.position.y, self.position.z, self.radius, self.width, TARGB(self.color), self.quality)
elseif self.mode == CIRCLE_MINIMAP then
DrawCircleMinimap(self.position.x, self.position.y, self.position.z, self.radius, self.width, TARGB(self.color), self.quality)
else
print("Circle: Something is wrong with the circle.mode!")
end
end
function _Circle:PointOnScreen(x, y)
return x <= WINDOW_W and x >= 0 and y >= 0 and y <= WINDOW_H
end
function _Circle:__eq(other)
return other._circleId and other._circleId == self._circleId or false
end
--[[
'||''|. '||' || '||
|| || .... .. .. .. .... ... . .... || ... || ...
|| || '' .|| || || || '' .|| || || .|...|| || || ||' ||
|| || .|' || || || || .|' || |'' || || || || |
.||...|' '|..'|' .|| || ||. '|..'|' '||||. '|...' .||.....| .||. '|...'
.|....'
DamageLib - Holy cow, so precise!
Functions:
DamageLib(source)
Members:
DamageLib.source | Cunit | Source unit for which the damage should be calculated
Methods:
DamageLib:RegisterDamageSource(spellId, damagetype, basedamage, perlevel, scalingtype, scalingstat, percentscaling, condition, extra)
DamageLib:GetScalingDamage(target, scalingtype, scalingstat, percentscaling)
DamageLib:GetTrueDamage(target, spell, damagetype, basedamage, perlevel, scalingtype, scalingstat, percentscaling, condition, extra)
DamageLib:CalcSpellDamage(target, spell)
DamageLib:CalcComboDamage(target, combo)
DamageLib:IsKillable(target, combo)
DamageLib:AddToMenu(menu, combo)
-Available spells by default (not added yet):
_AA: Returns the auto-attack damage.
_IGNITE: Returns the ignite damage.
_ITEMS: Returns the damage dealt by all the items actives.
-Damage types:
_MAGIC
_PHYSICAL
_TRUE
-Scaling types: _AP, _AD, _BONUS_AD, _HEALTH, _ARMOR, _MR, _MAXHEALTH, _MAXMANA
]]
class 'DamageLib'
--Damage types
_MAGIC, _PHYSICAL, _TRUE = 0, 1, 2
--Percentage scale type's
_AP, _AD, _BONUS_AD, _HEALTH, _ARMOR, _MR, _MAXHEALTH, _MAXMANA = 1, 2, 3, 4, 5, 6, 7, 8
--Percentage scale functions
local _ScalingFunctions = {
[_AP] = function(x, y) return x * y.source.ap end,
[_AD] = function(x, y) return x * y.source.totalDamage end,
[_BONUS_AD] = function(x, y) return x * y.source.addDamage end,
[_ARMOR] = function(x, y) return x * y.source.armor end,
[_MR] = function(x, y) return x * y.source.magicArmor end,
[_MAXHEALTH] = function(x, y) return x * y.source.maxHeath end,
[_MAXMANA] = function(x, y) return x * y.source.maxMana end,
}
--[[
New instance of DamageLib
@param source | Cunit | Source unit (attacker, player by default)
]]
function DamageLib:__init(source)
self.sources = {}
self.source = source or player
-- Most common damage sources
self:RegisterDamageSource(_IGNITE, _TRUE, 0, 0, _TRUE, _AP, 0, function() return _IGNITE and (self.source:CanUseSpell(_IGNITE) == READY) end, function() return (50 + 20 * self.source.level) end)
self:RegisterDamageSource(ItemManager:GetItem("DFG"):GetId(), _MAGIC, 0, 0, _MAGIC, _AP, 0, function() return ItemManager:GetItem("DFG"):GetSlot() and (self.source:CanUseSpell(ItemManager:GetItem("DFG"):GetSlot()) == READY) end, function(target) return 0.15 * target.maxHealth end)
self:RegisterDamageSource(ItemManager:GetItem("BOTRK"):GetId(), _MAGIC, 0, 0, _MAGIC, _AP, 0, function() return ItemManager:GetItem("BOTRK"):GetSlot() and (self.source:CanUseSpell(ItemManager:GetItem("BOTRK"):GetSlot()) == READY) end, function(target) return 0.15 * target.maxHealth end)
self:RegisterDamageSource(_AA, _PHYSICAL, 0, 0, _PHYSICAL, _AD, 1)
end
--[[
Register a new spell
@param spellId | int | (unique) Spell id to add.
@param damagetype | int | The type(s) of the base and perlevel damage (_MAGIC, _PHYSICAL, _TRUE).
@param basedamage | int | Base damage(s) of the spell.
@param perlevel | int | Damage(s) scaling per level.
@param scalingtype | int | Type(s) of the percentage scale (_MAGIC, _PHYSICAL, _TRUE).
@param scalingstat | int | Stat(s) that the damage scales with.
@param percentscaling | int | Percentage(s) the stat scales with.
@param condition | function | (optional) A function that returns true / false depending if the damage will be taken into account or not, the target is passed as param.
@param extra | function | (optional) A function returning extra damage, the target is passed as param.
-Example Spells:
Teemo Q: 80 / 125 / 170 / 215 / 260 (+ 80% AP) (MAGIC)
DamageLib:RegisterDamageSource(_Q, _MAGIC, 35, 45, _MAGIC, _AP, 0.8, function() return (player:CanUseSpell(_Q) == READY) end)
Akalis E: 30 / 55 / 80 / 105 / 130 (+ 30% AP) (+ 60% AD) (PHYSICAL)
DamageLib:RegisterDamageSource(_E, _PHYSICAL, 5, 25, {_PHYSICAL,_PHYSICAL}, {_AP, _AD}, {0.3, 0.6}, function() return (player:GetSpellData(_Q).currentCd < 2) or (player:CanUseSpell(_Q) == READY) end)
* damagetype, basedamage, perlevel and scalingtype, scalingstat, percentscaling can be tables if there are 2 or more damage types.
]]
function DamageLib:RegisterDamageSource(spellId, damagetype, basedamage, perlevel, scalingtype, scalingstat, percentscaling, condition, extra)
condition = condition or function() return true end
if spellId then
self.sources[spellId] = {damagetype = damagetype, basedamage = basedamage, perlevel = perlevel, condition = condition, extra = extra, scalingtype = scalingtype, percentscaling = percentscaling, scalingstat = scalingstat}
end
end
function DamageLib:GetScalingDamage(target, scalingtype, scalingstat, percentscaling)
local amount = (_ScalingFunctions[scalingstat] or function() return 0 end)(percentscaling, self)
if scalingtype == _MAGIC then
return self.source:CalcMagicDamage(target, amount)
elseif scalingtype == _PHYSICAL then
return self.source:CalcDamage(target, amount)
elseif scalingtype == _TRUE then
return amount
end
return 0
end
function DamageLib:GetTrueDamage(target, spell, damagetype, basedamage, perlevel, scalingtype, scalingstat, percentscaling, condition, extra)
basedamage = basedamage or 0
perlevel = perlevel or 0
condition = condition(target)
scalingtype = scalingtype or 0
scalingstat = scalingstat or _AP
percentscaling = percentscaling or 0
extra = extra or function() return 0 end
local ScalingDamage = 0
if not condition then return 0 end
if type(scalingtype) == "number" then
ScalingDamage = ScalingDamage + self:GetScalingDamage(target, scalingtype, scalingstat, percentscaling)
elseif type(scalingtype) == "table" then
for i, v in ipairs(scalingtype) do
ScalingDamage = ScalingDamage + self:GetScalingDamage(target, scalingtype[i], scalingstat[i], percentscaling[i])
end
end
if damagetype == _MAGIC then
return self.source:CalcMagicDamage(target, basedamage + perlevel * self.source:GetSpellData(spell).level + extra(target)) + ScalingDamage
end
if damagetype == _PHYSICAL then
return self.source:CalcDamage(target, basedamage + perlevel * self.source:GetSpellData(spell).level + extra(target)) + ScalingDamage
end
if damagetype == _TRUE then
return basedamage + perlevel * self.source:GetSpellData(spell).level + extra(target) + ScalingDamage
end
return 0
end
function DamageLib:CalcSpellDamage(target, spell)
if not spell then return 0 end
local spelldata = self.sources[spell]
local result = 0
assert(spelldata, "DamageLib: The spell has to be added first!")
local _type = type(spelldata.damagetype)
if _type == "number" then
result = self:GetTrueDamage(target, spell, spelldata.damagetype, spelldata.basedamage, spelldata.perlevel, spelldata.scalingtype, spelldata.scalingstat, spelldata.percentscaling, spelldata.condition, spelldata.extra)
elseif _type == "table" then
for i = 1, #spelldata.damagetype, 1 do
result = result + self:GetTrueDamage(target, spell, spelldata.damagetype[i], spelldata.basedamage[i], spelldata.perlevel[i], 0, 0, 0, spelldata.condition)
end
result = result + self:GetTrueDamage(target, spell, 0, 0, 0, spelldata.scalingtype, spelldata.scalingstat, spelldata.percentscaling, spelldata.condition, spelldata.extra)
end
return result
end
function DamageLib:CalcComboDamage(target, combo)
local totaldamage = 0
for i, spell in ipairs(combo) do
totaldamage = totaldamage + self:CalcSpellDamage(target, spell)
end
return totaldamage
end
--[[
Returns if the unit will die after taking the combo damage.
@param target | Cunit | Target.
@param combo | table | The combo table.
]]
function DamageLib:IsKillable(target, combo)
return target.health <= self:CalcComboDamage(target, combo)
end
--[[
Adds the Health bar indicators to the menu.
@param menu | scriptConfig | AllClass menu or submenu instance.
@param combo | table | The combo table.
]]
function DamageLib:AddToMenu(menu, combo)
self.menu = menu
self.combo = combo
self.ticklimit = 5 --5 ticks per seccond
self.barwidth = 100
self.cachedDamage = {}
menu:addParam("DrawPredictedHealth", "Draw damage after combo.", SCRIPT_PARAM_ONOFF , true)
self.enabled = menu.DrawPredictedHealth
AddTickCallback(function() self:OnTick() end)
AddDrawCallback(function() self:OnDraw() end)
end
function DamageLib:OnTick()
if not self.menu["DrawPredictedHealth"] then return end
self.lasttick = self.lasttick or 0
if os.clock() - self.lasttick > 1 / self.ticklimit then
self.lasttick = os.clock()
for i, enemy in ipairs(GetEnemyHeroes()) do
if ValidTarget(enemy) then
self.cachedDamage[enemy.hash] = self:CalcComboDamage(enemy, self.combo)
end
end
end
end
function DamageLib:OnDraw()
if not self.menu["DrawPredictedHealth"] then return end
for i, enemy in ipairs(GetEnemyHeroes()) do
if ValidTarget(enemy) then
self:DrawIndicator(enemy)
end
end
end
function DamageLib:DrawIndicator(enemy)
local damage = self.cachedDamage[enemy.hash] or 0
local SPos, EPos = GetEnemyHPBarPos(enemy)
local barwidth = EPos.x - SPos.x
local Position = SPos.x + math.max(0, (enemy.health - damage) / enemy.maxHealth) * barwidth
DrawText("|", 16, math.floor(Position), math.floor(SPos.y + 8), ARGB(255,0,255,0))
DrawText("HP: "..math.floor(enemy.health - damage), 13, math.floor(SPos.x), math.floor(SPos.y), (enemy.health - damage) > 0 and ARGB(255, 0, 255, 0) or ARGB(255, 255, 0, 0))
end
--[[
.|'''.| |''||''| .|'''.|
||.. ' || ||.. '
''|||. || ''|||.
. '|| || . '||
|'....|' .||. |'....|'
Simple Target Selector (STS) - Why using the regular one when you can have it even more simple.
]]
class 'SimpleTS'
function STS_GET_PRIORITY(target)
if not STS_MENU or not STS_MENU.STS[target.charName] then
return 1
else
return STS_MENU.STS[target.charName]
end
end
STS_MENU = nil
STS_NEARMOUSE = {id = 1, name = "Near mouse", sortfunc = function(a, b) return GetDistanceSqr(mousePos, a) < GetDistanceSqr(mousePos, b) end}
STS_LESS_CAST_MAGIC = {id = 2, name = "Less cast (magic)", sortfunc = function(a, b) return (player:CalcMagicDamage(a, 100) / a.health) > (player:CalcMagicDamage(b, 100) / b.health) end}
STS_LESS_CAST_PHYSICAL = {id = 3, name = "Less cast (physical)", sortfunc = function(a, b) return (player:CalcDamage(a, 100) / a.health) > (player:CalcDamage(b, 100) / b.health) end}
STS_PRIORITY_LESS_CAST_MAGIC = {id = 4, name = "Less cast priority (magic)", sortfunc = function(a, b) return STS_GET_PRIORITY(a) * (player:CalcMagicDamage(a, 100) / a.health) > STS_GET_PRIORITY(b) * (player:CalcMagicDamage(b, 100) / b.health) end}
STS_PRIORITY_LESS_CAST_PHYSICAL = {id = 5, name = "Less cast priority (physical)", sortfunc = function(a, b) return STS_GET_PRIORITY(a) * (player:CalcDamage(a, 100) / a.health) > STS_GET_PRIORITY(b) * (player:CalcDamage(b, 100) / b.health) end}
STS_AVAILABLE_MODES = {STS_NEARMOUSE, STS_LESS_CAST_MAGIC, STS_LESS_CAST_PHYSICAL, STS_PRIORITY_LESS_CAST_MAGIC, STS_PRIORITY_LESS_CAST_PHYSICAL}
function SimpleTS:__init(mode)
self.mode = mode and mode or STS_LESS_CAST_PHYSICAL
end
function SimpleTS:IsValid(target, range, selected)
if ValidTarget(target) and (GetDistanceSqr(target) <= range or (self.hitboxmode and (GetDistanceSqr(target) <= (math.sqrt(range) + self.VP:GetHitBox(myHero) + self.VP:GetHitBox(target)) ^ 2))) then
if selected or (not (HasBuff(target, "UndyingRage") and (target.health == 1)) and not HasBuff(target, "JudicatorIntervention")) then
return true
end
end
end
function SimpleTS:AddToMenu(menu)
self.menu = menu
self.menu:addSubMenu("Target Priority", "STS")
for i, target in ipairs(GetEnemyHeroes()) do
if not self.menu.STS[target.charName] then --avoid errors in one for all
self.menu.STS:addParam(target.charName, target.charName, SCRIPT_PARAM_SLICE, 1, 1, 5, 1)
end
end
self.menu.STS:addParam("Info", "Info", SCRIPT_PARAM_INFO, "5 Highest priority")
local modelist = {}
for i, mode in ipairs(STS_AVAILABLE_MODES) do
table.insert(modelist, mode.name)
end
self.menu:addParam("mode", "Targetting mode: ", SCRIPT_PARAM_LIST, 1, modelist)
self.menu["mode"] = self.mode.id
self.menu:addParam("Selected", "Focus selected target", SCRIPT_PARAM_ONOFF, true)
STS_MENU = self.menu
end
function SimpleTS:GetTarget(range, n, forcemode)
assert(range, "SimpleTS: range can't be nil")
range = range * range
local PosibleTargets = {}
local selected = GetTarget()
if self.menu then
self.mode = STS_AVAILABLE_MODES[self.menu.mode]
if self.menu.Selected and selected and selected.type == player.type and self:IsValid(selected, range, true) then
return selected
end
end
for i, enemy in ipairs(GetEnemyHeroes()) do
if self:IsValid(enemy, range) then
table.insert(PosibleTargets, enemy)
end
end
table.sort(PosibleTargets, forcemode and forcemode.sortfunc or self.mode.sortfunc)
return PosibleTargets[n and n or 1]
end
class "_ItemManager"
function _ItemManager:__init()
self.items = {
["DFG"] = {id = 3128, range = 650, cancastonenemy = true},
["BOTRK"] = {id = 3153, range = 450, cancastonenemy = true}
}
self.requesteditems = {}
end
function _ItemManager:CastOffensiveItems(target)
for name, itemdata in pairs(self.items) do
local item = self:GetItem(name)
if item:InRange(target) then
item:Cast(target)
end
end
end
function _ItemManager:GetItem(name)
assert(name and self.items[name], "ItemManager: Item not found")
if not self.requesteditems[name] then
self.requesteditems[name] = Item(self.items[name].id, self.items[name].range)
end
return self.requesteditems[name]
end
ItemManager = _ItemManager()
class "Item"
function Item:__init(id, range)
self.id = id
self.range = range
self.rangeSqr = range * range
self.slot = GetInventorySlotItem(id)
end
function Item:GetId()
return self.id
end
function Item:GetRange(sqr)
return sqr and self.rangeSqr or self.range
end
function Item:GetSlot()
self:UpdateSlot()
return self.slot
end
function Item:UpdateSlot()
self.slot = GetInventorySlotItem(self.id)
end
function Item:IsReady()
self:UpdateSlot()
return self.slot and (player:CanUseSpell(self.slot) == READY)
end
function Item:InRange(target)
return GetDistanceSqr(target) <= self.rangeSqr
end
function Item:Cast(param1, param2)
self:UpdateSlot()
if self.slot then
if param1 ~= nil and param2 ~= nil then
CastSpell(self.slot, param1, param2)
elseif param1 ~= nil then
CastSpell(self.slot, param1)
else
CastSpell(self.slot)
end
return SPELLSTATE_TRIGGERED
end
end
--[[
'||' '|' . || '||
|| | .||. ... ||
|| | || || ||
|| | || || ||
'|..' '|.' .||. .||.
Util - Just utils.
]]
AllClassGetDistanceSqr = GetDistanceSqr
function _GetDistanceSqr(p1, p2)
if p2 == nil then p2 = player end
if p1 and p1.networkID and (p1.networkID ~= 0) and p1.visionPos then p1 = p1.visionPos end
if p2 and p2.networkID and (p2.networkID ~= 0) and p2.visionPos then p2 = p2.visionPos end
return AllClassGetDistanceSqr(p1, p2)
end
function HasBuff(unit, buffname)
for i = 1, unit.buffCount do
local tBuff = unit:getBuff(i)
if tBuff.valid and BuffIsValid(tBuff) and tBuff.name == buffname then
return true
end
end
return false
end
function GetSummonerSlot(name, unit)
unit = unit or player
if unit:GetSpellData(SUMMONER_1).name == name then return SUMMONER_1 end
if unit:GetSpellData(SUMMONER_2).name == name then return SUMMONER_2 end
end
function GetEnemyHPBarPos(enemy)
local barPos = GetUnitHPBarPos(enemy)
local barPosOffset = GetUnitHPBarOffset(enemy)
local barOffset = Point(enemy.barData.PercentageOffset.x, enemy.barData.PercentageOffset.y)
local barPosPercentageOffset = Point(enemy.barData.PercentageOffset.x, enemy.barData.PercentageOffset.y)
local BarPosOffsetX = 169
local BarPosOffsetY = 47
local CorrectionX = -63
local CorrectionY = -27
barPos.x = barPos.x + (barPosOffset.x - 0.5 + barPosPercentageOffset.x) * BarPosOffsetX + CorrectionX
barPos.y = barPos.y + (barPosOffset.y - 0.5 + barPosPercentageOffset.y) * BarPosOffsetY + CorrectionY
local StartPos = Point(barPos.x, barPos.y)
local EndPos = Point(barPos.x + 103, barPos.y)
return Point(StartPos.x, StartPos.y), Point(EndPos.x, EndPos.y)
end
function CountObjectsNearPos(pos, range, radius, objects)
local n = 0
for i, object in ipairs(objects) do
if GetDistanceSqr(pos, object) <= radius * radius then
n = n + 1
end
end
return n
end
function GetBestCircularFarmPosition(range, radius, objects)
local BestPos
local BestHit = 0
for i, object in ipairs(objects) do
local hit = CountObjectsNearPos(object.visionPos or object, range, radius, objects)
if hit > BestHit then
BestHit = hit
BestPos = Vector(object)
if BestHit == #objects then
break
end
end
end
return BestPos, BestHit
end
function GetPredictedPositionsTable(VP, t, delay, width, range, speed, source, collision)
local result = {}
for i, target in ipairs(t) do
local CastPosition, Hitchance, Position = VP:GetCircularCastPosition(target, delay, width, range, speed, source, collision)
table.insert(result, Position)
end
return result
end
function MergeTables(t1, t2)
for i = 1, #t2 do
t1[#t1 + 1] = t2[i]
end
return t1
end
function SelectUnits(units, condition)
local result = {}
for i, unit in ipairs(units) do
if condition(unit) then
table.insert(result, unit)
end
end
return result
end
function SpellToString(id)
if id == _Q then return "Q" end
if id == _W then return "W" end
if id == _E then return "E" end
if id == _R then return "R" end
end
function TARGB(colorTable)
assert(colorTable and type(colorTable) == "table" and #colorTable == 4, "TARGB: colorTable is invalid!")
return ARGB(colorTable[1], colorTable[2], colorTable[3], colorTable[4])
end
function PingClient(x, y, pingType)
Packet("R_PING", {x = y, y = y, type = pingType and pingType or PING_FALLBACK}):receive()
end
local __util_autoAttack = { "frostarrow" }
local __util_noAutoAttack = { "shyvanadoubleattackdragon",
"shyvanadoubleattack",
"monkeykingdoubleattack" }
function IsAASpell(spell)
if not spell or not spell.name then return end
for _, spellName in ipairs(__util_autoAttack) do
if spellName == spell.name:lower() then
return true
end
end
for _, spellName in ipairs(__util_noAutoAttack) do
if spellName == spell.name:lower() then
return false
end
end
if spell.name:lower():find("attack") then
return true
end
return false
end
-- Source: http://lua-users.org/wiki/CopyTable
function TableDeepCopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
--[[
'||' || . || '|| || . ||
|| .. ... ... .||. ... .... || ... ...... .... .||. ... ... .. ...
|| || || || || || '' .|| || || ' .|' '' .|| || || .| '|. || ||
|| || || || || || .|' || || || .|' .|' || || || || || || ||
.||. .||. ||. .||. '|.' .||. '|..'|' .||. .||. ||....| '|..'|' '|.' .||. '|..|' .||. ||.
]]
-- Update script
if autoUpdate then
LazyUpdater("SourceLib", version, "bitbucket.org", "/TheRealSource/public/raw/master/common/SourceLib.lua", LIB_PATH .. "SourceLib.lua"):SetSilent(silentUpdate):CheckUpdate()
end
-- Set enemy bar data
for i, enemy in ipairs(GetEnemyHeroes()) do
enemy.barData = GetEnemyBarData()
end
--Summoner spells
_IGNITE = GetSummonerSlot("SummonerDot")
_FLASH = GetSummonerSlot("SummonerFlash")
_EXHAUST = GetSummonerSlot("SummonerExhaust")
--Others
_AA = 10000
_PASIVE = 10001
<file_sep>/Scripts/Caitlyn.lua
if myHero.charName ~= "Caitlyn" then return end
local version = "1.11"
-------------------------------------
local REQUIRED_LIBS = {
["SourceLib"] = "https://raw.github.com/TheRealSource/public/master/common/SourceLib.lua",
["VPrediction"] = "https://raw.github.com/honda7/BoL/master/Common/VPrediction.lua",
["SOW"] = "https://raw.github.com/honda7/BoL/master/Common/SOW.lua",
}
local DOWNLOADING_LIBS, DOWNLOAD_COUNT = false, 0
local SELF_NAME = GetCurrentEnv() and GetCurrentEnv().FILE_NAME or ""
function AfterDownload()
DOWNLOAD_COUNT = DOWNLOAD_COUNT - 1
if DOWNLOAD_COUNT == 0 then
DOWNLOADING_LIBS = false
print("<b>[Caitlyn]: Libs downloaded successfully, please reload (double F9).</b>")
end
end
for DOWNLOAD_LIB_NAME, DOWNLOAD_LIB_URL in pairs(REQUIRED_LIBS) do
if FileExist(LIB_PATH .. DOWNLOAD_LIB_NAME .. ".lua") then
require(DOWNLOAD_LIB_NAME)
else
DOWNLOADING_LIBS = true
DOWNLOAD_COUNT = DOWNLOAD_COUNT + 1
DownloadFile(DOWNLOAD_LIB_URL, LIB_PATH .. DOWNLOAD_LIB_NAME..".lua", AfterDownload)
end
end
if DOWNLOADING_LIBS then return end
-------------------------------------
-------------------------------------
SU = SourceUpdater("Caitlyn", version, "raw.github.com", "/MixsStar/BoL_Studio/master/Scripts/Caitlyn.lua", tostring(SCRIPT_PATH .. GetCurrentEnv().FILE_NAME))
--A basic BoL template for the Eclipse Lua Development Kit
AutoUpGen = true
local spellExpired = true
local informationTable = {}
player = GetMyHero()
-- AutoWard Start Code
local wardRange = 600
local scriptActive = true
local wardTimer = 0
local wardSlot = nil
local wardMatrix = {}
local wardDetectedFlag = {}
local lastWard = 0
wardMatrix[1] = {10000,11326,10012,8924,8078,11186,5925,4911,4025,2781,4031,2842}
wardMatrix[2] = {2868,3817,4842,5461,4600,6979,9851,8878,9621,10578,11519,7575}
wardMatrix[3] = {}
for i = 1, 12 do
--Ward present nearby ?
wardMatrix[3][i] = false
wardDetectedFlag[i] = false
end
function wardUpdate()
for i = 1, 12 do
wardDetectedFlag[i] = false
end
for k = 1, objManager.maxObjects do
local object = objManager:GetObject(k)
if object ~= nil and (string.find(object.name, "Ward") ~= nil or string.find(object.name, "Wriggle") ~= nil) then
for i = 1, 12 do
if math.sqrt((wardMatrix[1][i] - object.x)*(wardMatrix[1][i] - object.x) + (wardMatrix[2][i] - object.z)*(wardMatrix[2][i] - object.z)) < 1100 then
wardDetectedFlag[i] = true
wardMatrix[3][i] = true
end
end
end
for i = 1, 12 do
if wardDetectedFlag[i] == false then
wardMatrix[3][i] = false
end
end
end
wardTimer = GetTickCount()
end
-- AutoWard End Code
blue = false
PassiveUp = false
aaRange = 650 -- dunno why but when drawing it draws it smaller...
qRange = 1250
wRange = 800
eRange = 950
rRange = nil
rRangelvl = {2000,2500,3000}
local QAble, WAble, RAble = false, false, false
local qDmg, eDmg, rDmg, DmgRange
-- called once when the script is loaded
function OnLoad()
EnemyMinions = minionManager(MINION_ENEMY, 720, myHero, MINION_SORT_MAXHEALTH_DEC)
Menu()
VP = VPrediction()
AutoUpGen = mc.autoupdategeneral
if AutoUpGen then
SU:CheckUpdate()
end
OrbWalk()
end
-- handles script logic, a pure high speed loop
space = false
mixed = false
function OnTick()
Checks()
CheckRLevel()
if Target then
if Target and (space) then
Peacemaker()
end
if Target and (mixed) then
Peacemaker2()
end
if mc.draws.useW then Trap() end
if mc.draws.Combo then PeacemakerCombo() end
if mc.draws.KS then KS() end
end
if mc.draws.autoEGapDist then AutoEGap() end
if mc.draws.Dash then Dash() end
--
if mc.draws.farmEnabled and (myHero.mana / myHero.maxMana * 100) >= mc.draws.ManaCheck then
Farm()
end
-- Infos
if mc.draws.HitChanceInfo then
PrintChat ("<font color='#FFFFFF'>Hitchance 0: No waypoints found for the target, returning target current position</font>")
PrintChat ("<font color='#FFFFFF'>Hitchance 1: Low hitchance to hit the target</font>")
PrintChat ("<font color='#FFFFFF'>Hitchance 2: High hitchance to hit the target</font>")
PrintChat ("<font color='#FFFFFF'>Hitchance 3: Target too slowed or/and too close(~100% hit chance)</font>")
PrintChat ("<font color='#FFFFFF'>Hitchance 4: Target inmmobile(~100% hit chace)</font>")
PrintChat ("<font color='#FFFFFF'>Hitchance 5: Target dashing(~100% hit chance)</font>")
--AutoCarry.PluginMenu.ranges.HitChanceInfo = false
end
if mc.extras.putWard then
if GetTickCount() - wardTimer > 10000 then
wardUpdate()
end
if (myHero:CanUseSpell(ITEM_7) == READY and myHero:getItem(ITEM_7).id == 3340) then
wardSlot = GetInventorySlotItem(3340)
elseif (myHero:CanUseSpell(ITEM_7) == READY and myHero:getItem(ITEM_7).id == 3350) then
wardSlot = GetInventorySlotItem(3350)
elseif GetInventorySlotItem(2044) ~= nil then
wardSlot = GetInventorySlotItem(2044)
elseif GetInventorySlotItem(2043) ~= nil then
wardSlot = GetInventorySlotItem(2043)
else
wardSlot = nil
end
for i = 1, 12 do
if wardSlot ~= nil and GetTickCount() - lastWard > 2000 then
if math.sqrt((wardMatrix[1][i] - player.x)*(wardMatrix[1][i] - player.x) + (wardMatrix[2][i] - player.z)*(wardMatrix[2][i] - player.z)) < 600 and wardMatrix[3][i] == false then
CastSpell( wardSlot, wardMatrix[1][i], wardMatrix[2][i] )
lastWard = GetTickCount()
wardMatrix[3][i] = true
break
end
end
end
end
end
function OnGainBuff(unit, buff)
if unit.isMe then
if buff.name == "crestoftheancientgolem" then
blue = true
if mc.extras.debug then
print("You Have the Blue")
end
end
if buff.name == "caitlynheadshot" then
PassiveUp = true
if mc.extras.debug then
print("Your Passive is Active ;D")
end
end
end
end
function OnLoseBuff(unit, buff)
if unit.isMe then
if buff.name == "crestoftheancientgolem" then
blue = false
if mc.extras.debug then
print("You Lost the Blue")
end
end
if buff.name == "caitlynheadshot" then
PassiveUp = false
if mc.extras.debug then
print("Your Passive is NOT Active")
end
end
end
end
--handles overlay drawing (processing is not recommended here,use onTick() for that)
function OnDraw()
if not myHero.dead then
if QAble and mc.draws.drawQ then
DrawCircle(myHero.x, myHero.y, myHero.z, qRange, 0x6600CC)
end
if RAble and mc.draws.drawR then
DrawCircle(myHero.x, myHero.y, myHero.z, rRange, 0x990000)
end
if mc.draws.drawAA then
DrawCircle(myHero.x, myHero.y, myHero.z, 720, 0x990000)
end
end
end
--handles input
function OnWndMsg(msg,key)
if msg == KEY_DOWN and key == 32 then space = true end
if msg == KEY_UP and key == 32 then space = false end
if msg == KEY_DOWN and key == string.byte("C") then mixed = true end
if msg == KEY_UP and key == string.byte("C") then mixed = false end
end
-- listens to chat input
function OnSendChat(txt)
end
-- listens to spell
function OnProcessSpell(unit, spell)
if not mc.draws.autoEGapDist then return end
local jarvanAddition = unit.charName == "JarvanIV" and unit:CanUseSpell(_Q) ~= READY and _R or _Q -- Did not want to break the table below.
local isAGapcloserUnit = {
-- ['Ahri'] = {true, spell = _R, range = 450, projSpeed = 2200},
['Aatrox'] = {true, spell = _Q, range = 1000, projSpeed = 1200, },
['Akali'] = {true, spell = _R, range = 800, projSpeed = 2200, }, -- Targeted ability
['Alistar'] = {true, spell = _W, range = 650, projSpeed = 2000, }, -- Targeted ability
['Diana'] = {true, spell = _R, range = 825, projSpeed = 2000, }, -- Targeted ability
['Gragas'] = {true, spell = _E, range = 600, projSpeed = 2000, },
['Graves'] = {true, spell = _E, range = 425, projSpeed = 2000, exeption = true },
['Hecarim'] = {true, spell = _R, range = 1000, projSpeed = 1200, },
['Irelia'] = {true, spell = _Q, range = 650, projSpeed = 2200, }, -- Targeted ability
['JarvanIV'] = {true, spell = jarvanAddition, range = 770, projSpeed = 2000, }, -- Skillshot/Targeted ability
['Jax'] = {true, spell = _Q, range = 700, projSpeed = 2000, }, -- Targeted ability
['Jayce'] = {true, spell = 'JayceToTheSkies', range = 600, projSpeed = 2000, }, -- Targeted ability
['Khazix'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Leblanc'] = {true, spell = _W, range = 600, projSpeed = 2000, },
['LeeSin'] = {true, spell = 'blindmonkqtwo', range = 1300, projSpeed = 1800, },
['Leona'] = {true, spell = _E, range = 900, projSpeed = 2000, },
['Malphite'] = {true, spell = _R, range = 1000, projSpeed = 1500 + unit.ms},
['Maokai'] = {true, spell = _Q, range = 600, projSpeed = 1200, }, -- Targeted ability
['MonkeyKing'] = {true, spell = _E, range = 650, projSpeed = 2200, }, -- Targeted ability
['Pantheon'] = {true, spell = _W, range = 600, projSpeed = 2000, }, -- Targeted ability
['Poppy'] = {true, spell = _E, range = 525, projSpeed = 2000, }, -- Targeted ability
--['Quinn'] = {true, spell = _E, range = 725, projSpeed = 2000, }, -- Targeted ability
['Renekton'] = {true, spell = _E, range = 450, projSpeed = 2000, },
['Sejuani'] = {true, spell = _Q, range = 650, projSpeed = 2000, },
['Shen'] = {true, spell = _E, range = 575, projSpeed = 2000, },
['Tristana'] = {true, spell = _W, range = 900, projSpeed = 2000, },
['Tryndamere'] = {true, spell = 'Slash', range = 650, projSpeed = 1450, },
['XinZhao'] = {true, spell = _E, range = 650, projSpeed = 2000, }, -- Targeted ability
}
if unit.type == 'obj_AI_Hero' and unit.team == TEAM_ENEMY and isAGapcloserUnit[unit.charName] and GetDistance(unit) < 2000 and spell ~= nil then
--print('1Gapcloser: ',unit.charName, ' Target: ', (spell.target ~= nil and spell.target.name or 'NONE'), " ", spell.name, " ", spell.projectileID)
if spell.name == (type(isAGapcloserUnit[unit.charName].spell) == 'number' and unit:GetSpellData(isAGapcloserUnit[unit.charName].spell).name or isAGapcloserUnit[unit.charName].spell) then
--print('2Gapcloser: ',unit.charName, ' Target: ', (spell.target ~= nil and spell.target.name or 'NONE'), " ", spell.name, " ", spell.projectileID)
if spell.target ~= nil and spell.target.name == myHero.name or isAGapcloserUnit[unit.charName].spell == 'blindmonkqtwo' then
--print('3Gapcloser: ',unit.charName, ' Target: ', (spell.target ~= nil and spell.target.name or 'NONE'), " ", spell.name, " ", spell.projectileID)
CastSpell(_E, unit)
else
--print('NOGapcloser: ',unit.charName, ' Target: ', (spell.target ~= nil and spell.target.name or 'NONE'), " ", spell.name, " ", spell.projectileID)
spellExpired = false
informationTable = {
spellSource = unit,
spellCastedTick = GetTickCount(),
spellStartPos = Point(spell.startPos.x, spell.startPos.z),
spellEndPos = Point(spell.endPos.x, spell.endPos.z),
spellRange = isAGapcloserUnit[unit.charName].range,
spellSpeed = isAGapcloserUnit[unit.charName].projSpeed,
spellIsAnExpetion = isAGapcloserUnit[unit.charName].exeption or false,
}
end
end
end
end
-- function to declare the menu
local HKR = string.byte("R")
local HKE = string.byte("G")
local HKC = string.byte("T")
function Menu()
myConfig = scriptConfig("Caitlyn - Config", "mixsstarScript")
mc = myConfig
mc:addParam("autoupdategeneral", "AutoUpdate", SCRIPT_PARAM_ONOFF, true)
mc:addSubMenu("OrbWalk", "orbwalkSubMenu")
--[[Draws General]]
mc:addSubMenu("Skills and Draws", "draws")
mc.draws:addParam("HitChance", "Q - Hitchance", SCRIPT_PARAM_SLICE, 2, 0, 5, 0)
mc.draws:addParam("HitChanceInfo", "Info - Hitchance", SCRIPT_PARAM_ONOFF, false)
--[[Misc Options]]
mc.draws:addParam("sep", "-- Misc Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("blueQ", "Q - Cast more often when Blue",SCRIPT_PARAM_ONOFF, false)
mc.draws:addParam("useW", "Use - Yordle Snap Trap", SCRIPT_PARAM_ONOFF, false)
mc.draws:addParam("Dash", "Dash - 90 Caliber Net", SCRIPT_PARAM_ONKEYDOWN, false, HKE)
--[[Auto Anti-Gap Closer]]
mc.draws:addParam("sep", "-- Auto Anti-Gap Closer Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("autoEGapDist", "Net Auto Anti-Gap Closers", SCRIPT_PARAM_ONOFF, true)
--[[KS Options]]
mc.draws:addParam("sep1", "-- KS Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("KS", "Enable - Killsteal", SCRIPT_PARAM_ONOFF, true)
mc.draws:addParam("Killshot", "Killshot - Ace in the Hole", SCRIPT_PARAM_ONKEYDOWN, false, HKR)
mc.draws:addParam("KSQ", "Use - Piltover Peacemaker", SCRIPT_PARAM_ONOFF, true)
--[[Orbwalk Options]]
mc.draws:addParam("sep2", "-- Orbwalk Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("useQ", "Use - Piltover Peacemaker", SCRIPT_PARAM_ONOFF, true)
--[[Mixed Mode Options]]
mc.draws:addParam("sep3", "-- Mixed Mode Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("useQ2", "Use - Piltover Peacemaker", SCRIPT_PARAM_ONOFF, false)
--[[Farming]]
mc.draws:addParam("farm", "-- Farming Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("farmUseQ", "Use Q", SCRIPT_PARAM_ONOFF, true)
mc.draws:addParam("ManaCheck", "Don't farm if mana < %", SCRIPT_PARAM_SLICE, 10, 0, 100)
mc.draws:addParam("farmEnabled", "Farm!", SCRIPT_PARAM_ONKEYDOWN, false, string.byte("V"))
--[[Drawing Options]]
mc.draws:addParam("sep4", "-- Drawing Options --", SCRIPT_PARAM_INFO, "")
mc.draws:addParam("drawQ", "Draw - Piltover Peacemaker", SCRIPT_PARAM_ONOFF, true)
mc.draws:addParam("drawR", "Draw - Ace in the Hole", SCRIPT_PARAM_ONOFF, true)
mc.draws:addParam("drawAA", "Draw - AA Arena", SCRIPT_PARAM_ONOFF, true)
mc:addParam("version", "Version", SCRIPT_PARAM_INFO, version)
--[[Extras]]
mc:addSubMenu("Extras", "extras")
mc.extras:addParam("putWard", "Automatically put Wards", SCRIPT_PARAM_ONOFF, true)
mc.extras:addParam("debug", "Print and Draw Debugs", SCRIPT_PARAM_ONOFF, false)
end
function OrbWalk()
SOW(VP)
SOWi = SOW(VP)
SOWi:LoadToMenu(myConfig.orbwalkSubMenu)
end
function Checks()
QAble = (myHero:CanUseSpell(_Q) == READY)
WAble = (myHero:CanUseSpell(_W) == READY)
EAble = (myHero:CanUseSpell(_E) == READY)
RAble = (myHero:CanUseSpell(_R) == READY)
Target = SOWi:GetTarget()
end
function KS()
--[[if mc.extras.debug then
print("Calling KS()")
end]]
for i = 1, heroManager.iCount do
local Enemy = heroManager:getHero(i)
if QAble and mc.draws.KSQ then qDmg = getDmg("Q",Enemy,myHero) else qDmg = 0 end
if EAble and mc.draws.KSE then eDmg = getDmg("E",Enemy,myHero) else eDmg = 0 end
if RAble then rDmg = getDmg("R",Enemy,myHero) else rDmg = 0 end
if ValidTarget(Enemy, 1300, true) and Enemy.health < qDmg then
--Net()
PeacemakerKS()
end
if ValidTarget(Enemy, rRange, true) and Enemy.health < rDmg then
PrintFloatText(myHero, 0, "Press R For Killshot") end
if ValidTarget(Enemy, rRange, true) and mc.draws.Killshot and Enemy.health < rDmg then
CastSpell(_R, Enemy) end
end
end
function CheckRLevel()
if myHero:GetSpellData(_R).level == 1 then rRange = rRangelvl[1]
elseif myHero:GetSpellData(_R).level == 2 then rRange = rRangelvl[2]
elseif myHero:GetSpellData(_R).level == 3 then rRange = rRangelvl[3]
end
end
function PeacemakerKS()
if mc.extras.debug then
print("Calling PeaceMakerKS()")
end
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 0.632, 90, qRange, 2225, myHero)
if QAble and HitChance >= 2 and GetDistance(CastPosition) < qRange then CastSpell(_Q, CastPosition.x, CastPosition.z) end
end
end
function Peacemaker()
--[[if mc.extras.debug then
print("Calling PeaceMaker()")
end]]
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 0.632, 90, qRange, 2225, myHero)
if not string.find(Target.name, "Turret") then
if QAble and mc.draws.useQ and SOWi:CanMove() and HitChance >= mc.draws.HitChance and GetDistance(CastPosition) < qRange then
if blue and mc.draws.blueQ and HitChance >= 1 then
if mc.extras.debug then print("Casting Q More Often") end
CastSpell(_Q, CastPosition.x, CastPosition.z)
else
if HitChance >= mc.draws.HitChance then CastSpell(_Q, CastPosition.x, CastPosition.z)
if mc.extras.debug then
print("Calling PeaceMaker() and target is")
print(Target.name)
print(target.name)
end
end
end
end
end
end
end
function Peacemaker2()
if mc.extras.debug then
print("Calling PeaceMaker2()")
end
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 0.632, 90, qRange, 2225, myHero)
if QAble and mc.draws.useQ2 and SOWi:CanMove() and HitChance >= mc.draws.HitChance and GetDistance(CastPosition) < qRange then CastSpell(_Q, CastPosition.x, CastPosition.z)
elseif QAble and mc.draws.useQ2 and HitChance >= mc.draws.HitChance and GetDistance(CastPosition) < qRange then CastSpell(_Q, CastPosition.x, CastPosition.z) end
end
end
function Trap()
if mc.extras.debug then
print("Calling Trap()")
end
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 1.5, 100, wRange, math.huge, myHero)
if WAble and HitChance >= 4 and GetDistance(CastPosition) <= 800 then SOWi:DisableAttacks() CastSpell(_W, CastPosition.x, CastPosition.z) SOWi:EnableAttacks() end
end
end
function Dash()
if mc.extras.debug then
print("Calling Dash()")
end
if EAble and mc.draws.Dash then
MPos = Vector(mousePos.x, mousePos.y, mousePos.z)
HeroPos = Vector(myHero.x, myHero.y, myHero.z)
DashPos = HeroPos + ( HeroPos - MPos )*(500/GetDistance(mousePos))
myHero:MoveTo(mousePos.x,mousePos.z)
CastSpell(_E,DashPos.x,DashPos.z)
end
end
function PeacemakerCombo()
if mc.extras.debug then
print("Calling Combo()")
end
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 0.632, 90, qRange, 2225, myHero)
if QAble and EAble and HitChance >= 1 and GetDistance(CastPosition) < qRange then CastSpell(_E, CastPosition.x, CastPosition.z) CastSpell(_Q, CastPosition.x, CastPosition.z) end
end
end
function Net()
if mc.extras.debug then
print("Calling Net()")
end
for i, target in pairs(GetEnemyHeroes()) do
CastPosition, HitChance, Position = VP:GetLineCastPosition(Target, 0.1, 80, eRange, 1960, myHero)
if EAble and HitChance >= mc.draws.HitChance and GetDistance(CastPosition) < eRange then CastSpell(_E, CastPosition.x, CastPosition.z) end
end
end
function AutoEGap()
if myHero:CanUseSpell(_E) == READY then
if mc.draws.autoEGapDist then
if not spellExpired and (GetTickCount() - informationTable.spellCastedTick) <= (informationTable.spellRange/informationTable.spellSpeed)*1000 then
local spellDirection = (informationTable.spellEndPos - informationTable.spellStartPos):normalized()
local spellStartPosition = informationTable.spellStartPos + spellDirection
local spellEndPosition = informationTable.spellStartPos + spellDirection * informationTable.spellRange
local heroPosition = Point(myHero.x, myHero.z)
local lineSegment = LineSegment(Point(spellStartPosition.x, spellStartPosition.y), Point(spellEndPosition.x, spellEndPosition.y))
--lineSegment:draw(ARGB(255, 0, 255, 0), 70)
if lineSegment:distance(heroPosition) <= (not informationTable.spellIsAnExpetion and 65 or 200) then
CastSpell(_E, informationTable.spellSource)
end
else
spellExpired = true
informationTable = {}
end
end
end
end
function Farm()
EnemyMinions:update()
if mc.draws.farmUseQ then
FarmQ()
end
end
function FarmQ()
if (myHero:CanUseSpell(_Q) == READY) and #EnemyMinions.objects > 0 then
if GetMaxDistMinion() < qRange then
local QPos = GetBestQPositionFarm()
if QPos then
CastQFarm(QPos)
end
end
end
end
function GetBestQPositionFarm()
local MaxQPos
local MaxQ = 0
for i, minion in pairs(EnemyMinions.objects) do
local hitQ = CountMinionsHit(minion)
if hitQ > MaxQ or MaxQPos == nil then
MaxQPos = minion
MaxQ = hitQ
end
end
if MaxQPos then
return MaxQPos
else
return nil
end
end
function CastQFarm(to)
CastSpell(_Q, to.x, to.z)
end
function GetMaxDistMinion()
local max = -1
for i, minion in ipairs(EnemyMinions.objects) do
if GetDistance(minion) > max then
max = GetDistance(minion)
end
end
return max
end
function CountMinionsHit(QPos)
local LineEnd = Vector(myHero) + qRange * (Vector(QPos) - Vector(myHero)):normalized()
local n = 0
for i, minion in pairs(EnemyMinions.objects) do
local pointSegment, pointLine, isOnSegment = VectorPointProjectionOnLineSegment(Vector(myHero), LineEnd, minion)
if isOnSegment and GetDistance(minion, pointSegment) <= 90*1.25 then
n = n + 1
end
end
return n
end | 4b1b6ea8a0b602bb596242fd480097d25cbf960b | [
"Lua"
] | 2 | Lua | NobiNobita/BoL_Studio | f861ba69f230112ac3b2924a8afec820e35e5cd3 | 7cbbae967299adde7edfb0647ed2fb9cfd6fea08 |
refs/heads/master | <repo_name>linsbrasil/fatec-java<file_sep>/src/fatec/Fatec.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fatec;
/**
*
* @author a10ceeteps
*/
public class Fatec {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Esta é minha primeira versão no GIT.");
int numeroA = 12;
int numeroB = 13;
int soma;
soma = numeroA + numeroB;
System.out.println("O valor total é = " + soma);
int tudo =100;
int i;
for(i = 0; i < 10; i++){
tudo += i;
System.out.println("Valor" + (i + 1) + " = " + tudo);
}
System.out.println("Você viu o resultado da soma?");
System.out.println("Este foi nosso primeiro exemplo, até logo.");
}
}
| 934d6e95eaf528f97f1e541c519194538f27b6e8 | [
"Java"
] | 1 | Java | linsbrasil/fatec-java | 12ae7156ff0bcee860550ce9fd53e1ee09745b48 | 07f679cce5021f608e7d7b12b0a3830c13193574 |
refs/heads/master | <repo_name>akitsu-sanae/markright<file_sep>/src/ast.cpp
#include "utility.hpp"
#include "ast.hpp"
<file_sep>/Readme.md
# MarkRight
`MarkRight` is a markdown-like markup language for me.
# Build
run `make`
# How to use
`markright [input filename] -o [output filename]`
# Sample
See `examples/simple.mr` or `test/*.mr`
# Copyright
Copyright (C) 2017 <NAME>.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0 or copy at http://www.boost/org/LICENSE_1_0.txt)
<file_sep>/src/codegen.cpp
#include "utility.hpp"
#include "ast.hpp"
std::string Statement::to_xelatex(CodeGenInfo const&) const {
return content;
}
std::string SubSection::to_xelatex(CodeGenInfo const& info) const {
std::string result;
if (info.is_slide) {
result = util::format("\\begin{{}}{{}}\n", "block", title);
for (auto const& content : contents)
result += content->to_xelatex(info);
result += util::format("\\end{{}}\n", "block");
} else {
result = util::format("\\subsection{{}}\n", title);
for (auto const& content : contents)
result += content->to_xelatex(info);
}
return result;
}
std::string Paragraph::to_xelatex(CodeGenInfo const& info) const {
std::string result = R"(\par )";
for (auto const& content : contents)
result += content->to_xelatex(info) + "\n";
return result;
}
std::string List::to_xelatex(CodeGenInfo const& info) const {
std::string result = "\\begin{itemize}\n";
for (auto const& content : contents)
result += util::format("\\item {}\n", content->to_xelatex(info));
result += "\\end{itemize}\n";
return result;
}
std::string IndexedList::to_xelatex(CodeGenInfo const& info) const {
std::string result = "\\begin{enumerate}\n";
for (auto const& content : contents)
result += util::format("\\item {}\n", content->to_xelatex(info));
result += "\\end{enumerate}\n";
return result;
}
std::string Quote::to_xelatex(CodeGenInfo const& info) const {
std::string result = "\\begin{quotation}\n";
for (auto const& content : contents)
result += content->to_xelatex(info) + "\n";
result += "\\end{quotation}\n";
return result;
}
std::string CodeBlock::to_xelatex(CodeGenInfo const&) const {
std::string result = "\\begin{lstlisting}\n";
result += source_code;
result += "\\end{lstlisting}\n";
return result;
}
std::string ProofTree::to_xelatex(CodeGenInfo const&) const {
std::string result = "\\begin{prooftree}\n";
for (auto const& premise : premises)
result += util::format("\\AxiomC{{}}\n", premise);
if (!rule_name.empty())
result += util::format("\\RightLabel{{}}\n", rule_name);
switch (premises.size()) {
case 1:
result += util::format("\\UnaryInfC{{}}\n", conclusion);
break;
case 2:
result += util::format("\\BinaryInfC{{}}\n", conclusion);
break;
case 3:
result += util::format("\\TrinaryInfC{{}}\n", conclusion);
break;
case 4:
result += util::format("\\QuaternaryInfC{{}}\n", conclusion);
break;
case 5:
result += util::format("\\QuinaryInfC{{}}\n", conclusion);
break;
default:
throw std::logic_error{"proof tree error: too many premises"};
}
result += util::format("\\end{prooftree}\n");
return result;
}
std::string Section::to_xelatex(CodeGenInfo const& info) const {
std::string result;
if (info.is_slide) {
result = util::format("\\begin{{}}[fragile]{{}}\n", "frame", title);
for (auto const& content: contents)
result += content->to_xelatex(info);
result += util::format("\\end{{}}\n", "frame");
} else {
result = util::format("\\section{{}}\n", title);
for (auto const& content: contents)
result += content->to_xelatex(info);
}
return result;
}
std::string Article::to_xelatex(CodeGenInfo const& info) const {
std::string result;
if (is_slide) {
result = "\\documentclass[12pt, unicode]{beamer}\n";
result += "\\usetheme{CambridgeUS}\n";
} else {
result = "\\documentclass[a4paper]{article}\n";
}
result += util::format("\\title{{}}\n", title);
result += util::format("\\author{{}}\n", author);
result += util::format("\\date{{}}\n", date);
result += "\\usepackage{indentfirst}\n";
result += "\\usepackage{xltxtra}\n";
result += "\\usepackage{bussproofs}\n";
result += "\\usepackage{listings}";
result += "\\lstset{basicstyle={\\ttfamily}, frame={tblr}}";
result += "\\setmainfont{IPAMincho}\n";
result += "\\setsansfont{IPAGothic}\n";
result += "\\setmonofont{IPAGothic}\n";
result += "\\XeTeXlinebreaklocale \"ja\"\n";
result += "\\begin{document}\n";
for (auto const& section : sections)
result += section->to_xelatex(info);
result += "\\end{document}\n";
return result;
}
<file_sep>/include/parser.hpp
#ifndef MARKRIGHT_PARSER_HPP
#define MARKRIGHT_PARSER_HPP
#include <deque>
#include <fstream>
#include "utility.hpp"
struct Article;
struct Section;
struct BlockElement;
struct SubSection;
struct Paragraph;
struct List;
struct IndexedList;
struct Quote;
struct CodeBlock;
struct ProofTree;
struct InlineElement;
struct Statement;
struct Parser {
explicit Parser(std::ifstream ifs);
std::deque<std::string> input;
util::ptr<Article> parse();
private:
util::ptr<Article> parse_article();
util::ptr<Section> parse_section();
util::ptr<BlockElement> parse_block_element();
util::ptr<SubSection> parse_subsection();
util::ptr<Paragraph> parse_paragraph();
util::ptr<List> parse_list();
util::ptr<IndexedList> parse_indexed_list();
util::ptr<Quote> parse_quote();
util::ptr<CodeBlock> parse_codeblock();
util::ptr<ProofTree> parse_prooftree();
util::ptr<InlineElement> parse_inline_element();
util::ptr<Statement> parse_statement();
bool is_match() const {
return false;
}
template<typename ... Args>
bool is_match(std::string const& head, Args const& ... args) {
if (input.empty())
return false;
if (input.front().size() < head.size())
return false;
bool is_ok = true;
for (size_t i=0; i<head.size(); ++i)
is_ok &= head[i] == input.front()[i];
if (is_ok)
return true;
return is_match(args ...);
}
};
#endif
<file_sep>/src/parser.cpp
#include "parser.hpp"
#include "ast.hpp"
static void add_description(Article& article, std::string const& line) {
auto pos = line.find_first_of(' ');
auto desc_type = line.substr(0, pos);
auto desc = line.substr();
if (desc_type == "\%title")
article.title = line.substr(pos+1, line.size()-1);
else if (desc_type == "\%author")
article.author = line.substr(pos+1, line.size()-1);
else if (desc_type == "\%date")
article.date = line.substr(pos+1, line.size()-1);
else if (desc_type == "\%slide-mode")
article.is_slide = true;
else
throw std::logic_error{"invalid desc: " + desc_type};
}
Parser::Parser(std::ifstream ifs) {
if (!ifs)
return;
std::string line;
while (std::getline(ifs, line)) {
if (!line.empty() && line[0] != ';')
input.push_back(line);
}
}
util::ptr<Article> Parser::parse() {
return parse_article();
}
util::ptr<Article> Parser::parse_article() {
auto article = std::make_unique<Article>();
// title, author, date
while (!input.empty() && input.front()[0] == '%') {
add_description(*article, input.front());
input.pop_front();
}
while (auto section = parse_section()) {
if (section)
article->sections.push_back(std::move(section));
else
break;
}
return article;
}
util::ptr<Section> Parser::parse_section() {
if (!is_match("#"))
return nullptr;
auto section = std::make_unique<Section>();
input.front().erase(0, 1); // first is '#'
util::trim_left(input.front());
section->title = input.front();
input.pop_front();
while (auto block = parse_block_element()) {
if (block)
section->contents.push_back(std::move(block));
else
break;
}
return section;
}
util::ptr<BlockElement> Parser::parse_block_element() {
if (input.empty())
return nullptr;
if (is_match("##"))
return parse_subsection();
if (is_match(" "))
return parse_paragraph();
if (is_match("1."))
return parse_indexed_list();
if (is_match("*"))
return parse_list();
if (is_match(">"))
return parse_quote();
if (is_match("[code]"))
return parse_codeblock();
if (is_match("[proof]"))
return parse_prooftree();
if (is_match("#")) // section
return nullptr;
throw std::logic_error{"invalid input"};
}
util::ptr<SubSection> Parser::parse_subsection() {
if (!is_match("##"))
return nullptr;
input.front().erase(0, 2); // remove '##'
util::trim_left(input.front());
auto subsection = std::make_unique<SubSection>();
subsection->title = input.front();
input.pop_front();
while (!is_match("##")) {
auto block = parse_block_element();
if (block)
subsection->contents.push_back(std::move(block));
else
break;
}
return subsection;
}
util::ptr<Paragraph> Parser::parse_paragraph() {
if (!is_match(" "))
return nullptr;
auto paragraph = std::make_unique<Paragraph>();
input.front().erase(0, 1); // first is ' '
util::trim_left(input.front());
while (auto inline_ = parse_inline_element()) {
if (inline_)
paragraph->contents.push_back(std::move(inline_));
else
break;
}
return paragraph;
}
util::ptr<IndexedList> Parser::parse_indexed_list() {
auto list = std::make_unique<IndexedList>();
int count = 1;
while (is_match(std::to_string(count) + ".")) {
input.front().erase(0, 2);
util::trim_left(input.front());
list->contents.push_back(parse_inline_element());
++count;
}
if (list->contents.empty())
return nullptr;
else
return list;
}
util::ptr<List> Parser::parse_list() {
auto list = std::make_unique<List>();
while (is_match("*")) {
input.front().erase(0, 1);
util::trim_left(input.front());
list->contents.push_back(parse_inline_element());
}
if (list->contents.empty())
return nullptr;
else
return list;
}
util::ptr<Quote> Parser::parse_quote() {
auto list = std::make_unique<Quote>();
while (is_match(">")) {
input.front().erase(0, 1); // remove '>'
util::trim_left(input.front());
list->contents.push_back(parse_inline_element());
}
if (list->contents.empty())
return nullptr;
else
return list;
}
auto calc_block_body(std::deque<std::string> const& input) {
auto start = input.front().begin();
while (*start != '{')
++start;
int brace_count = 0;
int count = 0;
for (auto const& line : input) {
for (auto it=line.begin(); it!=line.end(); ++it) {
if (*it == '{')
++brace_count;
if (*it == '}')
--brace_count;
if (brace_count == 0 && it > start)
return std::make_pair(start, it);
}
count++;
}
throw std::logic_error{"code block is not closed"};
}
util::ptr<CodeBlock> Parser::parse_codeblock() {
input.front().erase(0, 6); // remove '[code]'
auto code_body = calc_block_body(input);
std::string content{code_body.first + 1, input.front().cend()};
input.pop_front();
while (true) {
if (input.front().begin() <= code_body.second && code_body.second < input.front().end())
break;
content += input.front() + "\n";
input.pop_front();
}
auto lastline_length = code_body.second - input.front().begin();
content += input.front().substr(0, lastline_length);
input.front().erase(0, lastline_length + 1);
if (input.front().empty())
input.pop_front();
auto code = std::make_unique<CodeBlock>();
code->source_code = content;
return code;
}
#include <iostream>
void debug(std::deque<std::string> const& input) {
std::cout << "---------------------------" << std::endl;
for (auto const& line : input)
std::cout << line << std::endl;
}
util::ptr<ProofTree> Parser::parse_prooftree() {
input.front().erase(0, 7); // remove '[proof]'
while (is_match(" "))
input.front().erase(0, 1);
if (!is_match("{"))
throw std::logic_error{"expected is '{', but " + input.front() + " comes..."};
input.pop_front();
auto proof = std::make_unique<ProofTree>();
util::trim_left(input.front());
while (is_match("[premise]")) {
input.front().erase(0, 9); // erase [premise]
util::trim_left(input.front());
proof->premises.push_back(input.front());
input.pop_front();
util::trim_left(input.front());
}
if (is_match("[label]")) {
input.front().erase(0, 7); // erase [label]
proof->rule_name = input.front();
input.pop_front();
util::trim_left(input.front());
}
if (!is_match("[conclusion]"))
throw std::logic_error{"expected is [conclusion], but " + input.front() + " comes..."};
input.front().erase(0, 12); // erase [conclusion]
util::trim_left(input.front());
proof->conclusion = input.front();
input.pop_front();
if (!is_match("}"))
throw std::logic_error{"expected is '}', but " + input.front() + " comes ..."};
input.pop_front();
return proof;
}
util::ptr<InlineElement> Parser::parse_inline_element() {
return parse_statement();
}
util::ptr<Statement> Parser::parse_statement() {
if (is_match("#", " ", "1.", "*", ">", "[code]", "[proof]", "##"))
return nullptr;
if (input.empty())
return nullptr;
auto statement = std::make_unique<Statement>(input.front());
input.pop_front();
return statement;
}
<file_sep>/Makefile
TARGET_NAME = markright
CXX = g++
CXXFLAGS = -std=c++14 -Wall -Wextra
LDFLAGS =
LIBS =
INCLUDE = -I./include
SRCDIR = ./src
SRC = $(wildcard $(SRCDIR)/*.cpp)
BUILD_DIR = ./build
TARGET = $(BUILD_DIR)/$(TARGET_NAME)
OBJ = $(addprefix $(BUILD_DIR)/obj/, $(notdir $(SRC:.cpp=.o)))
DEPEND = $(OBJ:.o=.d)
TEST_FILES = $(wildcard ./test/*.mr)
all: $(TARGET)
-include $(DEPEND)
$(TARGET): $(OBJ)
$(CXX) -o $@ $^ $(LDFLAGS) $(LIBS)
$(BUILD_DIR)/obj/%.o: $(SRCDIR)/%.cpp
$(CXX) $(CXXFLAGS) $(INCLUDE) -o $@ -c -MMD -MP $<
.PHONY: clean
clean:
-rm -f $(OBJ) $(DEPEND) $(TARGET)
.PHONY: run
run: $(TARGET)
$(TARGET)
.PHONY: test
test: $(TARGET)
@$(foreach file, $(TEST_FILES), \
echo "testing: " $(file); \
./build/markright $(file) -o $(file:.mr=.tex) || echo "\033[31mtest fail markright to xelatex at " $(file) "\033[39m" || exit 50; \
) \
rm -f test/*.tex *.pdf *.aux *.log
<file_sep>/src/main.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "ast.hpp"
#include "parser.hpp"
struct Options {
std::string input_filename;
std::string output_filename = "output.tex";
};
Options parse_commandline_args(std::vector<std::string>&& arg) {
Options result;
switch (arg.size()) {
case 1:
result.input_filename = arg[0];
break;
case 3:
if (arg[0] == "-o") {
result.output_filename = arg[1];
result.input_filename = arg[2];
break;
} else if (arg[1] == "-o") {
result.input_filename = arg[0];
result.output_filename = arg[2];
break;
}
default:
std::cout << "usage: markright [input filename] -o [output filename]" << std::endl;
std::exit(-1);
}
return result;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv+argc};
auto options = parse_commandline_args(std::move(args));
Parser parser{std::ifstream(options.input_filename)};
std::ofstream output(options.output_filename);
output << parser.parse()->to_xelatex() << std::endl;
}
<file_sep>/include/ast.hpp
#ifndef MARKRIGHT_AST_HPP
#define MARKRIGHT_AST_HPP
#include <string>
#include <vector>
#include "utility.hpp"
struct CodeGenInfo {
bool is_slide;
};
struct Ast {
virtual std::string to_xelatex(CodeGenInfo const&) const = 0;
};
struct InlineElement : public Ast {
enum Type {
Statement
};
virtual Type type() const = 0;
};
struct Statement : public InlineElement {
Type type() const override {
return Type::Statement;
}
std::string to_xelatex(CodeGenInfo const&) const override;
explicit Statement(std::string const& str) :
content{str}
{}
std::string content;
};
struct BlockElement : public Ast {
enum Type {
SubSection,
Paragraph,
IndexedList,
List,
Quote,
CodeBlock,
ProofTree,
};
virtual Type type() const = 0;
};
struct SubSection : public BlockElement {
std::string title;
std::vector<util::ptr<BlockElement>> contents;
Type type() const override {
return Type::SubSection;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct Paragraph : public BlockElement {
std::vector<util::ptr<InlineElement>> contents;
Type type() const override {
return Type::Paragraph;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct List : public BlockElement {
std::vector<util::ptr<InlineElement>> contents;
Type type() const override {
return Type::List;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct IndexedList : public BlockElement {
std::vector<util::ptr<InlineElement>> contents;
Type type() const override {
return Type::IndexedList;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct Quote : public BlockElement {
std::vector<util::ptr<InlineElement>> contents;
Type type() const override {
return Type::Quote;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct CodeBlock : public BlockElement {
std::string source_code;
Type type() const override {
return Type::CodeBlock;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct ProofTree : public BlockElement {
std::string rule_name;
std::vector<std::string> premises;
std::string conclusion;
Type type() const override {
return Type::ProofTree;
}
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct Section : public Ast {
std::string title;
std::vector<util::ptr<BlockElement>> contents;
std::string to_xelatex(CodeGenInfo const&) const override;
};
struct Article : public Ast {
std::string title;
std::string author;
std::string date;
bool is_slide = false;
std::vector<util::ptr<Section>> sections;
std::string to_xelatex(CodeGenInfo const&) const override;
std::string to_xelatex() const {
return to_xelatex(CodeGenInfo{is_slide});
}
};
#endif
<file_sep>/include/utility.hpp
#ifndef MARKRIGHT_UTILITY_HPP
#define MARKRIGHT_UTILITY_HPP
#include <string>
#include <memory>
#include <stdexcept>
namespace std {
inline static std::string to_string(std::string const& s) { return s; }
}
namespace util {
inline static std::string format(std::string const& text) {
return text;
}
template<typename Head, typename ... Tail>
inline static std::string format(std::string const& text, Head const& head, Tail const& ... tail) {
auto pos = text.find("{}");
if (pos == std::string::npos)
throw std::logic_error{"too few arguments"};
std::string rest = text.substr(pos+2, text.length());
return text.substr(0, pos) + std::to_string(head) + format(rest, tail ...);
}
template<typename T>
using ptr = std::unique_ptr<T>;
inline static std::string& trim_left(std::string& str) {
auto start = std::begin(str);
while (std::isspace(*start))
++start;
str.erase(std::begin(str), start);
return str;
}
}
#endif
| 93d3485a51a0554a64943a414b70849fffa63a6c | [
"Markdown",
"Makefile",
"C++"
] | 9 | C++ | akitsu-sanae/markright | 3eb8d9f282d14ed796fcb6e93b206835598ef595 | cabffe519a1dd468e020c31b973f01b7ee63f7fe |
refs/heads/master | <file_sep>//
// Meme.swift
// MemeMe-V1
//
// Created by <NAME> on 20/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
struct Meme {//structure of meme to save its info
var topText: String
var bottomText: String
var originalImage: UIImage
var memedImage: UIImage
}
<file_sep>//
// MemeEditorViewController.swift
// MemeMe-V1
//
// Created by <NAME> on 17/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var cameraBtn: UIBarButtonItem!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var shareBtn: UIBarButtonItem!
@IBOutlet weak var bottomBar: UIToolbar!
@IBOutlet weak var navigationBar: UINavigationBar!
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -3.6]
override func viewDidLoad() {
super.viewDidLoad()
topTextField.delegate = self
bottomTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder() //when clicking Done, hide the keyboard
return true
}
//MARK: - Image picking
@IBAction func pickAnImageFromCamera(_ sender: AnyObject) {
pick(sourceType: .camera)
}
@IBAction func pickAnImageFromLibrary(_ sender: AnyObject) {
pick(sourceType: .photoLibrary)
}
func pick(sourceType: UIImagePickerControllerSourceType){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage {
mainImageView.image = image //show image into the imageView
}
dismiss(animated: true, completion: nil) //hide image picker
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil) //no image was selected, go back
}
override func viewWillAppear(_ animated: Bool) {
subscribeToKeyboardNotifications()
cameraBtn.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
shareBtn.isEnabled = mainImageView.image != nil
prepareTextField(textField: topTextField)
prepareTextField(textField: bottomTextField)
}
func prepareTextField(textField: UITextField) {
textField.defaultTextAttributes = memeTextAttributes
textField.textAlignment = .center
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
//MARK: - Keyboard Notifications
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification: Notification) {
if bottomTextField.isEditing {
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
func keyboardWillHide(_ notification:Notification) {
view.frame.origin.y = 0
}
func getKeyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
@IBAction func clearTextAndImage(){
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
mainImageView.image = nil
shareBtn.isEnabled = false
}
//MARK: - Image Sharing and Saving
@IBAction func shareImage() {
let memedImage = generateMemedImage()
let activityView = UIActivityViewController(activityItems: [memedImage], applicationActivities: nil)
activityView.completionWithItemsHandler = {(activity, completed, items, error) in
if (completed) {
let _ = self.save()
}
}
self.present(activityView, animated: true, completion: nil)
}
func save() {
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: mainImageView.image!, memedImage: generateMemedImage())
print(meme)
}
//MARK: - Meme Generation
func generateMemedImage() -> UIImage {
bottomBar.isHidden = true
navigationBar.isHidden = true
UIGraphicsBeginImageContext(view.frame.size)
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
bottomBar.isHidden = false
navigationBar.isHidden = false
return memedImage
}
}
| a74d9d14415ffcdbe5c4169ec34feadd95919cc6 | [
"Swift"
] | 2 | Swift | florenti/MemeMe-V1 | 7aa6fbe1232ea9cddabfefcad41fda92d0e087ef | b4b2bc77c1020305098be0681f081a5dc67c6054 |
refs/heads/master | <file_sep>from flask import Flask, render_template
causes = [
{
"name" : "Women's Health",
"emoji" : "peach",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Immigration Rights",
"emoji" : "alien",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Marriage Equality",
"emoji" : "two-women",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Environmental Issues",
"emoji" : "tree",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "<NAME>",
"emoji" : "worker",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Public Policy Research",
"emoji" : "microscope",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Pro-Family Work Policy",
"emoji" : "family",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Education For All",
"emoji" : "books",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
},
{
"name" : "Internet Freedom",
"emoji" : "connected",
"why-care" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"why-now" : "People have short attention spans, so this bit shouldn't be much longer than a tweet. 170-ish characters works on every screen I tried. Not too short either - think Goldilocks.",
"more-info": "You know that cool celebrity that everyone loves? What's-his-face from that one movie? Here's something they said that was pro-immigration rights! Yeah! Awesome!",
"national" : "Here's an example of something a national org needs your money for. Like legislation! A piece of something important that some senator is trying to pass!",
"local" : "Here's an example of something a local org needs your money for. You could be helping someone in your neighborhood!"
}
]
DEBUG = True
PORT = 8000
HOST = '0.0.0.0'
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', causes=causes)
@app.route('/all-causes')
def all_causes():
return render_template('all-causes.html', title="All Causes", causes=causes)
@app.route('/search')
def search():
return render_template('search.html', title="National Women's Health Organizations", causes=causes)
if __name__ == '__main__':
app.run(debug=DEBUG, host=HOST, port=PORT)
<file_sep># Charithing
Charity-thing (the name is a work in progress) | 4a0225c878b42dbb4e0e9d7ea3f85446a05b5da6 | [
"Markdown",
"Python"
] | 2 | Python | chloewood/charithing | 7476d20289981de2e6e5a863032b0eef4ade808e | e26e0d74683916265030b46e491a36292b96c06b |
refs/heads/master | <repo_name>oswinner/newproject<file_sep>/index.php
<?php
$errors = "";
$host="localhost";
$kullaniciadi="root";
$sifre="";
$veritabaniadi="todolist";
$baglanti = @mysql_connect($host, $kullaniciadi, $sifre);
$veritabani = @mysql_select_db($veritabaniadi);
if($baglanti && $veritabani) {
} else {
echo 'Veritabani baglantisi kurulamadi. Lutfen config.php dosyasini kontrol ediniz.';
}
mysql_query("SET NAMES UTF8");
if ($_POST) {
if (empty($_POST['task'])) {
$errors = "Listeyi doldurmalısınız.";
}else{
$task = $_POST['task'];
$sql = "INSERT INTO todolist (task) VALUES ('$task')";
mysql_query($sql);
header('location: index.php');
}
}
if ($_GET){
if(empty($_GET['del_task'])) {
?>
<script>
alert("Veri silinemedi.");
</script>
<?php
}
else {
$id=$_GET['del_task'];
mysql_query("DELETE FROM todolist WHERE id=$id");
?>
<script>
alert("Veri silindi.");
</script>
<?php
}
}
?>
<!DOCTYPE html>
<html><head><title>Alışveriş Listesi Uygulaması</title>
<link rel="stylesheet" type="text/css" href="style.css"></head>
<body>
<div class="heading">
<h2 style="font-style: 'Hervetica';">Alışveriş Listesi</h2>
</div>
<form method="POST" action="index.php" class="input_form">
<?php if (isset($errors)) { ?>
<p><?php echo $errors; ?></p>
<?php } ?>
<input type="text" name="task" class="task_input" placeholder="Listeye ekle...">
<button type="submit" name="submit" id="add_btn" class="add_btn">Ekle</button>
</form>
<table>
<thead style="background-color: #09f;">
<tr>
<td style="color: white;"> Sıra</td>
<td style="color: white;"> Gerekenler</td>
<td style="color: white; ">Sil</td>
</tr>
</thead>
<tbody>
<?php
// select all tasks if page is visited or refreshed
$tasks = mysql_query("SELECT * FROM todolist");
$i = 1; while ($row = mysql_fetch_array($tasks)) { ?>
<tr>
<td> <?php echo $i; ?> </td>
<td class="task"> <?php echo $row['task']; ?> </td>
<td class="delete">
<a href="index.php?del_task=<?php echo $row['id'] ?>">x</a> </td></tr>
<?php $i++; } ?>
</tbody>
</table>
</body>
</html><file_sep>/README.md
# newproject
Alışveriş Listesi
Uygulamayı hazırladım ve denedim. Sorunsuz çalışmaktadır.
| ae041fb88ec6302fdafb76a7d78c439427ab4a8a | [
"Markdown",
"PHP"
] | 2 | PHP | oswinner/newproject | 478a43b5d2e96de8890cf5f5a4323b6910cbd3bc | 4bfcad316679ccb689815e145591195419dd160a |
refs/heads/master | <repo_name>JihoYoo/Comp-123-Assignment4-2<file_sep>/Assignment4_2_300813612_JihoYoo_COMP123/flight.cs
/*
* Author's name:<NAME>
* Date : 3/20/2015
* Program description : Array Practice 2 : Airline Reservations System
* Revision History :
* 3/17/2015 set up the values
* 3/19/2015 Initialize all the elements and assigned seat.
* 3/20/2015 find out some errors
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment4_2_300813612_JihoYoo_COMP123
{
class Flight
{
//constructor method
public Flight()
{
initializeElements();
}
//Initialize all the elements of the array to false to indicate that all the seats are empty.
private void initializeElements()
{
for (int index = 0; index < seats.Length; index++)
{
this.seats[index] = false;
}
}
private bool[] seats = new bool[11];
//First class public method
public void firstClass()
{
int i = 1;
while (i < 6) // possible to choose seats from 1 to 5
{
if (seats[i] == false)
{
this.seats[i] = true;
this.representChart();
break;
}
else if (i == 5)
{
Console.WriteLine();
Console.WriteLine("first class is full!!!");
Console.WriteLine("Next flight leaves in 3 hours");
Console.WriteLine();
}
i++;
}
}
// Economy class public method
public void economyClass()
{
int j = 6;
string changeSeat;
while (j < 11) // possible to choose seats from 6 to 10
{
if (seats[j] == false)
{
this.seats[j] = true;
this.representChart();
break;
}
else if (j == 10)
{
Console.WriteLine();
Console.WriteLine("economy class is full!!!");
Console.WriteLine();
Console.Write("Do you want to change a seat for First Clss? y or n : "); //ask the person to change a ticket for First Class
changeSeat = Console.ReadLine();
if (changeSeat == "y")
firstClass();
else
{
Console.WriteLine("Next flight leaves in 3 hours");
Console.WriteLine();
}
}
j++;
}
}
//one-dimensional array of type bool to represent the seating chart of the plane.
public void representChart()
{
Console.WriteLine();
Console.WriteLine("-----------------------------------------------");
Console.WriteLine("|P: Available / N: Not Available |");
Console.WriteLine("| Aavailable Seats |");
Console.WriteLine("| -front- |");
Console.WriteLine("| -first class- |");
Console.WriteLine("| 1 2 3 4 5 |");
for (int index = 1; index < 6; index++)
{
if (this.seats[index] == true)
Console.Write(" | N |");
else
Console.Write(" | P |");
}
Console.WriteLine();
Console.WriteLine("| |");
Console.WriteLine("| -Economy class- |");
Console.WriteLine("| 6 7 8 9 10 |");
for (int index = 6; index < 11; index++)
{
if (this.seats[index] == true)
Console.Write(" | N |");
else
Console.Write(" | P |");
}
Console.WriteLine();
Console.WriteLine("-----------------------------------------------");
Console.WriteLine();
}
}
}
<file_sep>/Assignment4_2_300813612_JihoYoo_COMP123/Program.cs
/*
* Author's name:<NAME>
* Date : 3/20/2015
* Program description : Array Practice 2 : Airline Reservations System
* Revision History :
* 3/17/2015 set up the values
* 3/19/2015 Initialize all the elements and assigned seat.
* 3/20/2015 find out some errors
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment4_2_300813612_JihoYoo_COMP123
{
class Program
{
static void Main(string[] args)
{
int choice = 0;
Flight flight = new Flight();
bool quit = false; //to quit
while (!quit) //while loop
{
Console.WriteLine("++++++++++++++++++++++++++++++");
Console.WriteLine("+ Welcome to AirCanada +");
Console.WriteLine("+ +");
Console.WriteLine("+ 1. First class +");
Console.WriteLine("+ 2. Economy class +");
Console.WriteLine("+ 3. Exit +");
Console.WriteLine("+ +");
Console.WriteLine("++++++++++++++++++++++++++++++");
Console.Write("Choice number: ");
try
{
choice = Convert.ToInt32(Console.ReadLine());
}
catch (Exception error)
{
Console.WriteLine(error.Message);
choice = 0;
}
switch (choice) //switch numbers to represent values.
{
case 1:
flight.firstClass();
break;
case 2:
flight.economyClass();
break;
case 3:
quit = true;
Console.WriteLine();
break;
default:
Console.WriteLine();
Console.WriteLine("Please check your number!!!");
Console.WriteLine();
break;
}
}
}
}
}
| cc74ec37383d442b0247e4d33c5cab07e0aa5e24 | [
"C#"
] | 2 | C# | JihoYoo/Comp-123-Assignment4-2 | 1ca72b6156f9807e307fe7f5dfd687660de067ef | 2dff8251f2f57e43e545b22164f1ab5564a98fa8 |
refs/heads/master | <file_sep>import HTMLTestRunner
import time
from selenium import webdriver
import unittest
class McTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('http://127.0.0.1:8000/')
def testBody(self):
'''测试主体'''
self.driver.find_element_by_link_text('登录').click()
self.driver.find_element_by_name('username').send_keys('thy')
self.driver.find_element_by_name('password').send_keys('<PASSWORD>')
self.driver.find_element_by_xpath('//*[@id="jsLoginBtn"]').click()
self.driver.find_element_by_xpath('/html/body/section[1]/header/div/div[1]/div/div[2]/dl').click()
self.driver.find_element_by_xpath('/html/body/section[1]/header/div/div[1]/div/div[2]/div/div/a[2]').click()
def testDown(self):
self.driver.quit()
if __name__=='__main__':
test=unittest.TestSuite()
test.addTest(McTest('testBody'))
file_result = open('132te.html', 'wb')
runner = HTMLTestRunner.HTMLTestRunner(stream=file_result, title='McTest测试报告', description='用例的执行情况')
runner.run(test)
file_result.close()
# if __name__=='__main__':
# test = unittest.TestSuite()
# test.addTest(McTest('testBody'))
# file_result = open('test.html', 'wb')
# runner = HTMLTestRunner.HTMLTestRunner(stream=file_result, title='McTest测试报告', description='用例的执行情况')
# runner.run(test)
# file_result.close()
| 17b0fe92c9fe7d0ac9f59412af7752c2ea63cd92 | [
"Python"
] | 1 | Python | treeytang/selenium | 37657e67a9a8a287507e962dd8a7ed3cde1fdc61 | 8f2951a9cf0b3710ec80a6efe89aab3a580e5029 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Movimientos</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<link href="../assets/extra-libs/datatables.net-bs4/css/dataTables.bootstrap4.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php"); ?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-7 align-self-center">
<h4 id="title_movi" class="page-title text-truncate text-dark font-weight-medium mb-1"></h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item"><a href="cuentas" class="text-muted">Cuentas</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Movimientos</li>
</ol>
</nav>
</div>
</div>
<div class="col-5 align-self-center">
<div class="customize-input float-right">
<select class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
<option selected>Dic 20</option>
</select>
</div>
</div>
</div>
</div>
<div class="page-breadcrumb mb-3">
<button type="button"
class="btn waves-effect waves-light btn-rounded float-right btn-success mb-2"
data-target="#ModalTransDash" id="add_trans_btn" data-toggle="modal">
<i class="fas fa-exchange-alt mr-2"></i>Transferencia
</button>
<button type="button"
class="btn waves-effect waves-light btn-rounded btn-primary float-right mb-2 mr-1"
data-target="#ModalAdd" id="add_move_btn" data-toggle="modal">
<i class="fas fa-plus mr-2"></i>Movimeinto
</button>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div id="div_descri_acc" class="float-left mb-2 col-sm-6">
<p id="descri_acc"></p>
</div>
<div class="float-left mb-2 col-sm-6">
<p id="balance_acc"></p>
</div>
<div class="table-responsive">
<table id="table_move_acc" class="table table-striped table-bordered no-wrap"
style="width:100%">
<thead>
<tr>
<th>Acciones</th>
<th>Categoria</th>
<th>Valor</th>
<th>Moneda</th>
<th>Fecha</th>
<th>Dia Semana</th>
<th>Dia</th>
<th>Mes</th>
<th>Año</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Acciones</th>
<th>Categoria</th>
<th>Valor</th>
<th>Moneda</th>
<th>Fecha</th>
<th>Dia Semana</th>
<th>Dia</th>
<th>Mes</th>
<th>Año</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalAdd" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Ingreso de movimiento</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('valor', 'monto_signal')" class="form-control" id="valor">
</div>
<div class="col-md-3">
<select id="divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="categoria">Seleciona una categoria</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="categoria">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="descripcion">Descripción</label>
<textarea class="form-control" id="descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="fecha">Fecha</label>
<input type="datetime-local" class="form-control custom-radius custom-shadow border-0" id="fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="save_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalTransDash" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Transferencias</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="trans_monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('trans_valor', '')" class="form-control" id="trans_valor">
</div>
<div class="col-md-3">
<select id="trans_divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>COP</option>
<option >USD</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="trans_cuenta_ini">Seleciona una cuenta de salida</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="trans_cuenta_ini">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="trans_cuenta_fin">Seleciona una cuenta de entrada</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="trans_cuenta_fin">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="trans_descripcion">Descripción</label>
<textarea class="form-control" id="trans_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="trans_fecha">Fecha</label>
<input type="datetime-local"
class="form-control custom-radius custom-shadow border-0" id="trans_fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="trans_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalEdit" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Editor de movimiento</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="edit_monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('edit_valor', 'edit_monto_signal')" class="form-control" id="edit_valor">
</div>
<div class="col-md-3">
<select id="edit_divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>COP</option>
<option >USD</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_cuenta">Seleciona una cuenta</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="edit_cuenta">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_categoria">Seleciona una categoria</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="edit_categoria">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_descripcion">Descripción</label>
<textarea class="form-control" id="edit_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_fecha">Fecha</label>
<input type="datetime-local"
class="form-control custom-radius custom-shadow border-0" id="edit_fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="edit_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalTransEdit" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Transferencias</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="Edit_trans_monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('Edit_trans_valor', '')" class="form-control" id="Edit_trans_valor">
</div>
<div class="col-md-3">
<select id="Edit_trans_divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>COP</option>
<option >USD</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="Edit_trans_cuenta_ini">Seleciona una cuenta de salida</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="Edit_trans_cuenta_ini">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="Edit_trans_cuenta_fin">Seleciona una cuenta de entrada</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="Edit_trans_cuenta_fin">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="Edit_trans_descripcion">Descripción</label>
<textarea class="form-control" id="Edit_trans_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="Edit_trans_fecha">Fecha</label>
<input type="datetime-local"
class="form-control custom-radius custom-shadow border-0" id="Edit_trans_fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="Edit_trans_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalDelete" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Eliminar movimiento</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="text_delete" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cancelar</button>
<button type="button" id="delete_trans" class="btn btn-danger">Eliminar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../dist/js/custom.min.js"></script>
<script src="../assets/extra-libs/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../dist/js/pages/datatable/datatable-basic.init.js"></script>
<script src="../java/functions.php"></script>
</body>
</html><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$action=$_GET["action"];
$insert = "SELECT * FROM fionadb.users WHERE id_user='$id_user'";
$ejecutar =mysqli_query( $conn,$insert);
$lista = mysqli_fetch_array($ejecutar);
$name = $lista["name"];
$last_name = $lista["last_name"];
$email = $lista["email"];
$divisa = $lista["divisa_prim"];
if ($action == 1) {
echo $name;
} else if ($action == 2){
echo $last_name;
} else if ($action == 3){
echo $email;
} else if ($action == 4){
echo $divisa;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$cuenta = $_POST["cuenta"];
$valor = $_POST["valor"];
$divisa = $_POST["divisa"];
$categoria = $_POST["categoria"];
$descripcion = $_POST["descripcion"];
$fecha = $_POST["fecha"];
$insert = "INSERT INTO fionadb.movimientos
(cuenta, categoria, valor, divisa, trm, fecha, descripcion, id_user)
VALUES('$cuenta', '$categoria', $valor, '$divisa', 1, '$fecha', '$descripcion', '$id_user');
";
$save = mysqli_query($conn, $insert);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$insert = "SELECT IF(COUNT(id) IS NULL, 0, COUNT(id)) AS cant FROM fionadb.notification WHERE id_user='$id_user'
and leido = 0";
$ejecutar =mysqli_query( $conn,$insert);
$lista = mysqli_fetch_array($ejecutar);
$cant = $lista["cant"];
echo $cant;
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$name = $_POST["name"];
$lastname = $_POST["last_name"];
$pass = $_POST["passw"];
$divisa = $_POST["divisa"];
$hash = Password::hash($pass);
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name_photo = $_SESSION["Id_user"].'.' . $ext;
$location = '../img/' . $name_photo;
if(file_exists($location)) {
chmod($location,0755); //Change the file permissions if allowed
unlink($location); //remove the file
}
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
if ($pass != ""){
$update = "UPDATE fionadb.users
SET name='$name', last_name='$lastname', password='$<PASSWORD>',
divisa_prim='$divisa', photo='$location'
WHERE id_user='$id_user';";
} else{
$update = "UPDATE fionadb.users
SET name='$name', last_name='$lastname', divisa_prim='$divisa'
, photo='$location'
WHERE id_user='$id_user';";
}
} else {
if ($pass != ""){
$update = "UPDATE fionadb.users
SET name='$name', last_name='$lastname', password='$<PASSWORD>',
divisa_prim='$<PASSWORD>'
WHERE id_user='$id_user';";
} else{
$update = "UPDATE fionadb.users
SET name='$name', last_name='$lastname', divisa_prim='$divisa'
WHERE id_user='$id_user';";
}
}
$save = mysqli_query($conn, $update);
if(!$save){
echo $update;
} else {
echo 200;
$_SESSION["name"] = $name;
$_SESSION["last_name"] = $lastname;
if($_FILES["file"]["name"] != '')
{
$_SESSION["photo"] = $location;
}
}
mysqli_close($conn);
?><file_sep><?php
session_start();
include("connect.php");
$user = $_POST["user"];
$passwd = $_POST["<PASSWORD>"];
$consult = "SELECT * FROM fionadb.users WHERE email=BINARY'$user'";
$eject = mysqli_query($conn, $consult);
if(empty(mysqli_fetch_array($eject))){
echo 400;
} else {
mysqli_data_seek($eject, 0);
$result = mysqli_fetch_array($eject);
$name = $result["name"];
$last_name = $result["last_name"];
$id_user = $result["id_user"];
$password = $result["password"];
$photo = $result["photo"];
if (Password::verify($passwd , $password)) {
echo 200;
$_SESSION["user"]=$user;
$_SESSION["Id_user"]=$id_user;
$_SESSION["name"]=$name;
$_SESSION["divisa"]=$result["divisa_prim"];
$_SESSION["last_name"]=$last_name;
$_SESSION["photo"]=$photo;
} else {
echo 450;
}
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$cuenta_ini = $_POST["cuenta_ini"];
$valor = $_POST["valor"];
$divisa = $_POST["divisa"];
$cuenta_fin = $_POST["cuenta_fin"];
$descripcion = $_POST["descripcion"];
$fecha = $_POST["fecha"];
$select ="SELECT * FROM fionadb.categorias WHERE id_user='$id_user' and grupo=5";
$eject = mysqli_query($conn, $select);
$result = mysqli_fetch_array($eject);
$categoria = $result["id"];
$insert_1 = "INSERT INTO fionadb.movimientos
(cuenta, categoria, valor, divisa, trm, fecha, descripcion, id_transfe, id_user)
VALUES('$cuenta_ini', '$categoria', $valor * -1, '$divisa', 1, '$fecha', '$descripcion', $cuenta_fin, '$id_user');
";
$insert_2 = "INSERT INTO fionadb.movimientos
(cuenta, categoria, valor, divisa, trm, fecha, descripcion, id_transfe, id_user)
SELECT '$cuenta_fin', '$categoria', $valor, '$divisa', 1 , '$fecha', '$descripcion', id, '$id_user'
FROM fionadb.movimientos WHERE id_user = '$id_user' and fecha ='$fecha' and
cuenta = '$cuenta_ini';
";
$save_1 = mysqli_query($conn, $insert_1);
$save_2 = mysqli_query($conn, $insert_2);
if(!$save_1 || !$save_2){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$insert = "SELECT b.categoria, FORMAT(a.valor,2) AS valor, a.divisa, a.fecha, a.descripcion, c.nombre FROM fionadb.movimientos
AS a LEFT JOIN fionadb.categorias AS b ON (b.id = a.categoria and a.id_user = b.id_user) LEFT JOIN
fionadb.cuentas AS c ON (a.id_user = c.id_user and a.cuenta = c.id)
WHERE a.id_user='$id_user' ORDER BY a.fecha DESC LIMIT 4";
$ejecutar =mysqli_query( $conn,$insert);
while ($lista = mysqli_fetch_array($ejecutar)){
$categoria = $lista["categoria"];
$cuenta = $lista["nombre"];
$valor = $lista["valor"];
$descripcion = $lista["descripcion"];
$fecha = $lista["fecha"];
if ((int)$valor < 0 && $categoria != "Transferencia"){
echo "<div class='d-flex align-items-start border-left-line pb-3'>
<div>
<a href='javascript:void(0)' class='btn btn-danger btn-circle mb-2 btn-item'>
<i class='fas fa-arrow-up'></i>
</a>
</div>
<div class='ml-3 mt-2'>
<h5 class='text-dark font-weight-medium mb-2'>$cuenta - $categoria</h5>
<p class='font-14 mb-2 text-muted'>$valor</p>
<p class='font-14 mb-2 text-muted'>$descripcion</p>
<span class='font-weight-light font-14 text-muted'>$fecha</span>
</div>
</div>";
} else if ((int)$valor > 0 && $categoria != "Transferencia"){
echo "<div class='d-flex align-items-start border-left-line pb-3'>
<div>
<a href='javascript:void(0)' class='btn btn-success btn-circle mb-2 btn-item'>
<i class='fas fa-arrow-down'></i>
</a>
</div>
<div class='ml-3 mt-2'>
<h5 class='text-dark font-weight-medium mb-2'>$cuenta - $categoria</h5>
<p class='font-14 mb-2 text-muted'>$valor</p>
<p class='font-14 mb-2 text-muted'>$descripcion
</p>
<span class='font-weight-light font-14 text-muted'>$fecha</span>
</div>
</div>";
} else if ((int)$valor > 0 && $categoria == "Transferencia"){
echo "<div class='d-flex align-items-start border-left-line pb-3'>
<div>
<a href='javascript:void(0)' class='btn btn-cyan btn-circle mb-2 btn-item'>
<i class='fas fa-exchange-alt'></i>
</a>
</div>
<div class='ml-3 mt-2'>
<h5 class='text-dark font-weight-medium mb-2'>$cuenta - $categoria</h5>
<p class='font-14 mb-2 text-muted'>$valor</p>
<p class='font-14 mb-2 text-muted'>$descripcion
</p>
<span class='font-weight-light font-14 text-muted'>$fecha</span>
</div>
</div>";
}
}
mysqli_close($conn);
?><file_sep><?php
function list_cate(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$lvl = $_GET['lvl'];
if ($lvl == 0){
$strsql = "SELECT a.id, a.categoria, COUNT(b.id) AS cantidad, a.grupo, a.sub_categoria,
a.descripcion FROM fionadb.categorias AS a LEFT JOIN fionadb.categorias AS b
ON (a.id = b.sub_categoria) WHERE a.id_user='$id_user'
and a.sub_categoria=a.id and a.categoria != 'Transferencia' GROUP BY a.categoria";
}else{
$strsql = "SELECT a.id, a.categoria, COUNT(b.id) AS cantidad, a.grupo, a.sub_categoria,
a.descripcion FROM fionadb.categorias AS a LEFT JOIN fionadb.categorias AS b
ON (a.id = b.sub_categoria) WHERE a.id_user='$id_user'
and a.sub_categoria=$lvl and a.sub_categoria != a.id and a.categoria != 'Transferencia' GROUP BY a.categoria";
}
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function list_account(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$lvl = $_GET['lvl'];
$strsql = "SELECT a.id, nombre, FORMAT(IF(SUM(valor) IS NULL, 0, SUM(valor)) + monto_inicial, 2)
AS cantidad, IF(SUM(valor) IS NULL, 0, SUM(valor)) + a.monto_inicial
AS cantidad_int, a.descripcion, a.divisa, a.cuenta_ahorro, a.monto_inicial FROM fionadb.cuentas AS a
LEFT JOIN fionadb.movimientos AS b ON (a.id = cuenta and a.id_user = b.id_user)
WHERE a.id_user='$id_user' GROUP BY nombre, b.divisa";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function movimientos(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$lvl = $_GET['lvl'];
$strsql = "SELECT a.id, a.categoria AS nro_cate, IF(a.categoria = 0, 'Sin categoria',b.categoria) AS categoria,
valor AS valor_int, FORMAT(valor,2) AS valor, divisa, fecha, DAY(fecha) AS dia, MONTH(fecha) AS mes,
YEAR(fecha) AS ano, a.descripcion, a.id_transfe FROM fionadb.movimientos AS a JOIN fionadb.categorias AS b ON
(a.id_user = b.id_user and b.id = a.categoria) WHERE cuenta=$lvl and a.id_user='$id_user'";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function consolidado(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$strsql = "SELECT ingreso, Egresos, utilidad, FORMAT(utilidad,2) AS utilidad_bal,
divisa FROM fionadb.consolidado WHERE id_user='$id_user' GROUP BY divisa";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function consolidado_card(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT FORMAT(ingreso,2) AS ingreso, FORMAT(Egresos,2) AS Egresos,
FORMAT(utilidad, 2) AS utilidad, FORMAT(utilidad,2) AS utilidad_bal,
divisa FROM fionadb.consolidado WHERE id_user='$id_user' and divisa='$divi'";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function ahorrado(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT FORMAT(IF(SUM(valor) IS NULL, 0, SUM(valor)) + monto_inicial, 2) AS cantidad
FROM fionadb.cuentas AS a LEFT JOIN fionadb.movimientos AS b
ON(a.id_user = b.id_user and b.cuenta = a.id) WHERE a.id_user='$id_user' and a.divisa='$divi'
and cuenta_ahorro = 1";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function new_user(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$strsql = "SELECT * FROM info_user WHERE id_user='$id_user'";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function mensajes(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$id = $_GET["id"];
$strsql = "SELECT * FROM fionadb.notification WHERE id_user='$id_user' and id = $id ORDER BY fecha DESC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
$action = $_GET['action'];
switch($action) {
case 1:
list_cate();
break;
case 2:
list_account();
break;
case 3:
movimientos();
break;
case 4:
consolidado();
break;
case 5:
consolidado_card();
break;
case 6:
ahorrado();
break;
case 7:
new_user();
break;
case 8:
mensajes();
break;
}
?>
<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$nombre = $_POST["nombre"];
$descripcion = $_POST["descripcion"];
$grupo = $_POST["grupo"];
$categoria = $_POST["categoria"];
if ($categoria == 0){
$insert = "INSERT INTO fionadb.categorias
(categoria, sub_categoria, descripcion, grupo, id_user)
SELECT '$nombre', `AUTO_INCREMENT` AS sub, '$descripcion', '$grupo', '$id_user'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'fionadb'
AND TABLE_NAME = 'categorias';";
} else {
$insert = "INSERT INTO fionadb.categorias
(categoria, sub_categoria, descripcion, grupo, id_user)
VALUES('$nombre', '$categoria', '$descripcion', '$grupo', '$id_user');
";
}
$save = mysqli_query($conn, $insert);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$action = $_GET["act"];
$mes_ini = $_POST["mes_ini"];
$valor = $_POST["valor"];
$categoria = $_POST["categoria"];
$modo_presu = $_POST["modo_presu"];
$divisa = $_POST["divisa"];
$ano = $_POST["ano"];
if ($action == "1"){
for ($i = $mes_ini; $i <= 12; $i += $modo_presu) {
$insert = "INSERT INTO fionadb.presupuesto
(categoria, valor, divisa, mes, `year`, id_user)
VALUES('$categoria', $valor, '$divisa', $i, $ano, '$id_user');
";
$save = mysqli_query($conn, $insert);
}
} else if ($action == 2){
if ($mes_ini == 1 && $_POST["replicar_val"] == 1){
for ($i = 1; $i <= 12; $i++) {
$insert = "INSERT INTO fionadb.presupuesto
(categoria, valor, divisa, mes, `year`, id_user)
VALUES('$categoria', $valor, '$divisa', $i, $ano, '$id_user');
";
$save = mysqli_query($conn, $insert);
}
} else {
$insert = "INSERT INTO fionadb.presupuesto
(categoria, valor, divisa, mes, `year`, id_user)
VALUES('$categoria', $valor, '$divisa', $mes_ini, $ano, '$id_user');
";
$save = mysqli_query($conn, $insert);
}
}
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$id = $_POST["id"];
$delete = "DELETE FROM fionadb.categorias
WHERE (id=$id or sub_categoria=$id) and id_user='$id_user';";
$save = mysqli_query($conn, $delete);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
include_once("connect.php");
$name = $_POST["name"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["pass"];
$hash = Password::hash($pass);
$id_user=generateRandomString(5);
$insert = "INSERT INTO fionadb.users
(name, last_name, email, password, <PASSWORD>, photo, id_user)
VALUES('$name', '$lastname', '$email', '$hash', 'COP','../assets/images/users/1.jpg','$id_user');
";
$insert_cat = "INSERT INTO fionadb.categorias
(categoria, sub_categoria, grupo, descripcion, id_user)
VALUES('Transferencia', '0', '5', 'Transferencia de una cuenta a otra', '$id_user');
;";
$save = mysqli_query($conn, $insert);
$save_cat = mysqli_query($conn, $insert_cat);
if(!$save || !$save_cat){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
//Método con str_shuffle()
function generateRandomString($length) {
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}
?><file_sep><?php
$mensaje="";
if(isset($_POST["envio"])){
include("php/envioCorreo.php");
$email = new email("iTPM Software","<EMAIL>","Itpm2050");
$email->agregar($_POST["email"],$_POST["nombre"]);
if ($email->enviar('Prueba envio de correos',$contenido_html)){
$mensaje= 'Mensaje enviado';
}else{
$mensaje= 'El mensaje no se pudo enviar';
$email->ErrorInfo;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<header>
<div id="logo"><img src="logo-php.png"/></div>
</header>
<div id="pagina">
<section>
<div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="application/x-www-form-urlencoded" name="envio">
<table>
<tr>
<td>
<label for="email">Email</label>
</td>
<td>
<input type="text" name="email" id="email" placeholder="<EMAIL>" autofocus maxlength="50" size="20">
</td>
<td>
<label for="nombre">Nombre</label>
</td>
<td>
<input type="text" name="nombre" id="nombre" placeholder="Tu nombre" autofocus maxlength="50" size="20">
<input name="envio" value="si" hidden="hidden">
</td>
<td>
<button type="submit">Enviar</button>
</td>
</tr>
</table>
</form>
</div>
<?php
echo $mensaje;
?>
</section>
<aside>
</aside>
</div>
<footer>
</footer>
</body>
</html><file_sep># Fiona app v1.0
Fiona is a personal financial application on the web, where you can monitor your financial,
by categorizing your income and expenses, you can also create your budgets on an annual basis and compare the budget compliance month by month.
<img src="https://github.com/samisosa20/Fiona/blob/master/img/login%20fiona%201.jpg" alt="login-fiona"/>
This application is developed with javascript and PHP with connection to mysql as a database
<p align="center">
<img src="https://devicons.github.io/devicon/devicon.git/icons/html5/html5-original-wordmark.svg" alt="html5" width="30" height="30"/>
<img src="https://devicons.github.io/devicon/devicon.git/icons/javascript/javascript-original.svg" alt="javascript" width="30" height="30"/>
<img src="https://devicon.dev/devicon.git/icons/php/php-original.svg" alt="PHP" width="30" height="30"/>
<img src="https://devicon.dev/devicon.git/icons/css3/css3-original.svg" alt="css3" width="30" height="30"/>
<img src="https://devicons.github.io/devicon/devicon.git/icons/mysql/mysql-original-wordmark.svg" alt="mysql" width="30" height="30"/>
<P>
---
## importan!
1. **.htacces** -> in this file delete the extensions in the URLs
2. **Conexions/connect** -> setup to connect with mysql
---
## license
* **Boostrap** - [boostrap](https://getbootstrap.com/docs/4.4/about/license/)
---
## Author
* **<NAME>** - [samisosa20](https://github.com/samisosa20)
<file_sep><?php
function list_year(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$strsql = "SELECT year, FORMAT(SUM(if(grupo = 4, valor, 0)),2) AS ingreso,
FORMAT(SUM(if(grupo = 1 or grupo = 2, valor, 0)),2) AS egreso
FROM fionadb.presupuesto p
JOIN fionadb.categorias c ON (p.categoria = c.id and p.id_user = c.id_user)
WHERE p.id_user='$id_user' GROUP BY year ORDER BY year ASC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function info_presu_moth(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$catego = $_GET['catego'];
$year = $_GET['year'];
$strsql = "SELECT p.id, p.categoria, c.categoria AS name_catego, valor,
MONTHNAME(CONCAT(year,'-',mes,'-',1)) AS mes_name, mes, year, p.id_user
FROM fionadb.presupuesto p JOIN fionadb.categorias c ON (p.id_user = c.id_user and p.categoria = c.id)
WHERE p.categoria = $catego and year = $year and p.id_user = '$id_user'";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
$action = $_GET['action'];
switch($action) {
case 1:
list_year();
break;
case 2:
info_presu_moth();
break;
}
?>
<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$id = $_POST["id"];
$valor = $_POST["valor"];
$divisa = $_POST["divisa"];
$descripcion = $_POST["descripcion"];
$fecha = $_POST["fecha"];
$categoria = $_POST["categoria"];
$cuenta = $_POST["cuenta"];
$update = "UPDATE fionadb.movimientos
SET cuenta='$cuenta', categoria='$categoria', valor=$valor, divisa='$divisa',
trm=1, fecha='$fecha', descripcion='$descripcion'
WHERE id=$id and id_user='$id_user';";
$save = mysqli_query($conn, $update);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
$user = $_SESSION["user"];
$name = $_SESSION["name"];
$last_name = $_SESSION["last_name"];
$divisa_prim = $_SESSION["divisa"];
$photo = $_SESSION["photo"];
?>
<!-- ============================================================== -->
<!-- Topbar header - style you can find in pages.scss -->
<!-- ============================================================== -->
<header class="topbar" data-navbarbg="skin6">
<nav class="navbar top-navbar navbar-expand-md">
<div class="navbar-header" data-logobg="skin6">
<!-- This is for the sidebar toggle which is visible on mobile only -->
<a class="nav-toggler waves-effect waves-light d-block d-md-none" href="javascript:void(0)"><i
class="ti-menu ti-close"></i></a>
<!-- ============================================================== -->
<!-- Logo -->
<!-- ============================================================== -->
<div class="navbar-brand">
<!-- Logo icon -->
<a href="index.html">
<b class="logo-icon">
<!-- Dark Logo icon -->
<img src="../assets/images/logo-icon.png" height="45px" alt="homepage" class="dark-logo" />
<!-- Light Logo icon -->
<img src="../assets/images/logo-icon.png" height="45px" alt="homepage" class="light-logo" />
</b>
<!--End Logo icon -->
<!-- Logo text -->
<span class="logo-text">
<!-- dark Logo text -->
<img src="../assets/images/logo-text.png" alt="homepage" class="dark-logo" />
<!-- Light Logo text -->
<img src="../assets/images/logo-light-text.png" class="light-logo" alt="homepage" />
</span>
</a>
</div>
<!-- ============================================================== -->
<!-- End Logo -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Toggle which is visible on mobile only -->
<!-- ============================================================== -->
<a class="topbartoggler d-block d-md-none waves-effect waves-light" href="javascript:void(0)"
data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><i
class="ti-more"></i></a>
</div>
<!-- ============================================================== -->
<!-- End Logo -->
<!-- ============================================================== -->
<div class="navbar-collapse collapse" id="navbarSupportedContent">
<!-- ============================================================== -->
<!-- toggle and nav items -->
<!-- ============================================================== -->
<ul class="navbar-nav float-left mr-auto ml-3 pl-1">
<!-- End Notification -->
<!-- ============================================================== -->
<!-- create new -->
<!-- ==============================================================
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i data-feather="settings" class="svg-icon"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>-->
<li class="nav-item d-none d-md-block">
<a class="nav-link" href="javascript:void(0)">
<div class="customize-input">
<select
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>ES</option>
<option value="1">EN</option>
</select>
</div>
</a>
</li>
<!-- Notification -->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle pl-md-3 position-relative" href="javascript:void(0)"
id="bell" role="button" data-toggle="dropdown" aria-haspopup="true"
aria-expanded="false">
<span><i data-feather="bell" class="svg-icon"></i></span>
<span id="nro_message" class="badge badge-primary notify-no rounded-circle"></span>
</a>
<div class="dropdown-menu dropdown-menu-left mailbox animated bounceInDown">
<ul class="list-style-none">
<li id="list_mensajes">
<!--div class="message-center notifications position-relative">
<div href="javascript:void(0)"
class="message-item d-flex align-items-center border-bottom">
<button class="btn btn-danger btn-circle"><i
class="text-white"></i></button>
<div class="w-75 d-inline-block v-middle pl-2">
<h6 class="message-title mb-0 mt-1">Luanch Admin</h6>
<span class="font-12 text-nowrap d-block text-muted">Just see
the my new
admin!</span>
<span class="font-12 text-nowrap d-block text-muted">9:30 AM</span>
</div>
</div>
<a href="javascript:void(0)"
class="message-item d-flex align-items-center border-bottom px-3 py-2">
<span class="btn btn-success text-white rounded-circle btn-circle"><i
data-feather="calendar" class="text-white"></i></span>
<div class="w-75 d-inline-block v-middle pl-2">
<h6 class="message-title mb-0 mt-1">Event today</h6>
<span
class="font-12 text-nowrap d-block text-muted text-truncate">Just
a reminder that you have event</span>
<span class="font-12 text-nowrap d-block text-muted">9:10 AM</span>
</div>
</a>
<a href="javascript:void(0)"
class="message-item d-flex align-items-center border-bottom px-3 py-2">
<span class="btn btn-info rounded-circle btn-circle"><i
data-feather="settings" class="text-white"></i></span>
<div class="w-75 d-inline-block v-middle pl-2">
<h6 class="message-title mb-0 mt-1">Settings</h6>
<span
class="font-12 text-nowrap d-block text-muted text-truncate">You
can customize this template
as you want</span>
<span class="font-12 text-nowrap d-block text-muted">9:08 AM</span>
</div>
</a>
<a href="javascript:void(0)"
class="message-item d-flex align-items-center border-bottom px-3 py-2">
<span class="btn btn-primary rounded-circle btn-circle"><i
data-feather="box" class="text-white"></i></span>
<div class="w-75 d-inline-block v-middle pl-2">
<h6 class="message-title mb-0 mt-1"><NAME></h6> <span
class="font-12 text-nowrap d-block text-muted">Just
see the my admin!</span>
<span class="font-12 text-nowrap d-block text-muted">9:02 AM</span>
</div>
</a>
</div>-->
</li>
<!--<li>
<a class="nav-link pt-3 text-center text-dark" href="javascript:void(0);">
<strong>Check all notifications</strong>
<i class="fa fa-angle-right"></i>
</a>
</li>-->
</ul>
</div>
</li>
</ul>
<!-- ============================================================== -->
<!-- Right side toggle and nav items -->
<!-- ============================================================== -->
<ul class="navbar-nav float-right">
<!-- ============================================================== -->
<!-- Search -->
<!-- ============================================================== -->
<li class="nav-item d-none d-md-block">
<a class="nav-link" href="javascript:void(0)">
<form>
<div class="customize-input">
<input class="form-control custom-shadow custom-radius border-0 bg-white"
type="search" placeholder="Search" aria-label="Search">
<i class="form-control-icon" data-feather="search"></i>
</div>
</form>
</a>
</li>
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="javascript:void(0)" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<?php echo "<img src='$photo' alt='user' class='rounded-circle'
width='40'>";?>
<span class="ml-2 d-none d-lg-inline-block"><span>Hello,</span> <span
class="text-dark"><?php echo $name; ?></span> <i data-feather="chevron-down"
class="svg-icon"></i></span>
</a>
<div id="balance" class="dropdown-menu dropdown-menu-right user-dd animated flipInY">
<!--<a class="dropdown-item" href="javascript:void(0)"><i data-feather="mail"
class="svg-icon mr-2 ml-1"></i>
Inbox</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="javascript:void(0)"><i data-feather="settings"
class="svg-icon mr-2 ml-1"></i>
Account Setting</a>-->
</div>
</li>
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->
</ul>
</div>
</nav>
</header>
<!-- ============================================================== -->
<!-- End Topbar header -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Left Sidebar - style you can find in sidebar.scss -->
<!-- ============================================================== -->
<aside class="left-sidebar" data-sidebarbg="skin6">
<!-- Sidebar scroll-->
<div class="scroll-sidebar" data-sidebarbg="skin6">
<!-- Sidebar navigation-->
<nav class="sidebar-nav">
<ul id="sidebarnav">
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="dashboard"
aria-expanded="false"><i data-feather="home" class="feather-icon"></i><span
class="hide-menu">DASHBOARD</span></a></li>
<li class="list-divider"></li>
<li id="account-list" class="sidebar-item"> <a class="sidebar-link" href="cuentas"
aria-expanded="false"><i data-feather="tag" class="feather-icon"></i><span
class="hide-menu">CUENTAS
</span></a>
</li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="categorias"
aria-expanded="false"><i data-feather="message-square" class="feather-icon"></i><span
class="hide-menu">CATEGORIA</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="presupuesto"
aria-expanded="false"><i data-feather="calendar" class="feather-icon"></i><span
class="hide-menu">PRESUPUESTO</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="reportes"
aria-expanded="false"><i data-feather="bar-chart" class="feather-icon"></i><span
class="hide-menu">REPORTES</span></a></li>
<li class="list-divider"></li>
<!--<li class="nav-small-cap"><span class="hide-menu">Configuraciiones</span></li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="file-text" class="feather-icon"></i><span
class="hide-menu">Forms </span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="form-inputs.html" class="sidebar-link"><span
class="hide-menu"> Form Inputs
</span></a>
</li>
<li class="sidebar-item"><a href="form-input-grid.html" class="sidebar-link"><span
class="hide-menu"> Form Grids
</span></a>
</li>
<li class="sidebar-item"><a href="form-checkbox-radio.html" class="sidebar-link"><span
class="hide-menu"> Checkboxes &
Radios
</span></a>
</li>
</ul>
</li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="grid" class="feather-icon"></i><span
class="hide-menu">Tables </span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="table-basic.html" class="sidebar-link"><span
class="hide-menu"> Basic Table
</span></a>
</li>
<li class="sidebar-item"><a href="table-dark-basic.html" class="sidebar-link"><span
class="hide-menu"> Dark Basic Table
</span></a>
</li>
<li class="sidebar-item"><a href="table-sizing.html" class="sidebar-link"><span
class="hide-menu">
Sizing Table
</span></a>
</li>
<li class="sidebar-item"><a href="table-layout-coloured.html" class="sidebar-link"><span
class="hide-menu">
Coloured
Table Layout
</span></a>
</li>
<li class="sidebar-item"><a href="table-datatable-basic.html" class="sidebar-link"><span
class="hide-menu">
Basic
Datatables
Layout
</span></a>
</li>
</ul>
</li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="bar-chart" class="feather-icon"></i><span
class="hide-menu">Charts </span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="chart-morris.html" class="sidebar-link"><span
class="hide-menu"> Morris Chart
</span></a>
</li>
<li class="sidebar-item"><a href="chart-chart-js.html" class="sidebar-link"><span
class="hide-menu"> ChartJs
</span></a>
</li>
<li class="sidebar-item"><a href="chart-knob.html" class="sidebar-link"><span
class="hide-menu">
Knob Chart
</span></a>
</li>
</ul>
</li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="box" class="feather-icon"></i><span
class="hide-menu">UI Elements </span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="ui-buttons.html" class="sidebar-link"><span
class="hide-menu"> Buttons
</span></a>
</li>
<li class="sidebar-item"><a href="ui-modals.html" class="sidebar-link"><span
class="hide-menu"> Modals </span></a>
</li>
<li class="sidebar-item"><a href="ui-tab.html" class="sidebar-link"><span
class="hide-menu"> Tabs </span></a></li>
<li class="sidebar-item"><a href="ui-tooltip-popover.html" class="sidebar-link"><span
class="hide-menu"> Tooltip &
Popover</span></a></li>
<li class="sidebar-item"><a href="ui-notification.html" class="sidebar-link"><span
class="hide-menu">Notification</span></a></li>
<li class="sidebar-item"><a href="ui-progressbar.html" class="sidebar-link"><span
class="hide-menu">Progressbar</span></a></li>
<li class="sidebar-item"><a href="ui-typography.html" class="sidebar-link"><span
class="hide-menu">Typography</span></a></li>
<li class="sidebar-item"><a href="ui-bootstrap.html" class="sidebar-link"><span
class="hide-menu">Bootstrap
UI</span></a></li>
<li class="sidebar-item"><a href="ui-breadcrumb.html" class="sidebar-link"><span
class="hide-menu">Breadcrumb</span></a></li>
<li class="sidebar-item"><a href="ui-list-media.html" class="sidebar-link"><span
class="hide-menu">List
Media</span></a></li>
<li class="sidebar-item"><a href="ui-grid.html" class="sidebar-link"><span
class="hide-menu"> Grid </span></a></li>
<li class="sidebar-item"><a href="ui-carousel.html" class="sidebar-link"><span
class="hide-menu">
Carousel</span></a></li>
<li class="sidebar-item"><a href="ui-scrollspy.html" class="sidebar-link"><span
class="hide-menu">
Scrollspy</span></a></li>
<li class="sidebar-item"><a href="ui-toasts.html" class="sidebar-link"><span
class="hide-menu"> Toasts</span></a>
</li>
<li class="sidebar-item"><a href="ui-spinner.html" class="sidebar-link"><span
class="hide-menu"> Spinner </span></a>
</li>
</ul>
</li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="ui-cards.html"
aria-expanded="false"><i data-feather="sidebar" class="feather-icon"></i><span
class="hide-menu">Cards
</span></a>
</li>
<li class="list-divider"></li>
<li class="nav-small-cap"><span class="hide-menu">Authentication</span></li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="authentication-login1.html"
aria-expanded="false"><i data-feather="lock" class="feather-icon"></i><span
class="hide-menu">Login
</span></a>
</li>
<li class="sidebar-item"> <a class="sidebar-link sidebar-link"
href="authentication-register1.html" aria-expanded="false"><i data-feather="lock"
class="feather-icon"></i><span class="hide-menu">Register
</span></a>
</li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="feather" class="feather-icon"></i><span
class="hide-menu">Icons
</span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="icon-fontawesome.html" class="sidebar-link"><span
class="hide-menu"> Fontawesome Icons </span></a></li>
<li class="sidebar-item"><a href="icon-simple-lineicon.html" class="sidebar-link"><span
class="hide-menu"> Simple Line Icons </span></a></li>
</ul>
</li>
<li class="sidebar-item"> <a class="sidebar-link has-arrow" href="javascript:void(0)"
aria-expanded="false"><i data-feather="crosshair" class="feather-icon"></i><span
class="hide-menu">Multi
level
dd</span></a>
<ul aria-expanded="false" class="collapse first-level base-level-line">
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item 1.1</span></a>
</li>
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item 1.2</span></a>
</li>
<li class="sidebar-item"> <a class="has-arrow sidebar-link" href="javascript:void(0)"
aria-expanded="false"><span class="hide-menu">Menu 1.3</span></a>
<ul aria-expanded="false" class="collapse second-level base-level-line">
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item
1.3.1</span></a></li>
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item
1.3.2</span></a></li>
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item
1.3.3</span></a></li>
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item
1.3.4</span></a></li>
</ul>
</li>
<li class="sidebar-item"><a href="javascript:void(0)" class="sidebar-link"><span
class="hide-menu"> item
1.4</span></a></li>
</ul>
</li>
<li class="list-divider"></li>-->
<li class="sidebar-item"> <a class="sidebar-link sidebar-link" href="/"
aria-expanded="false"><i data-feather="log-out" class="feather-icon"></i><span
class="hide-menu">FINALIZAR SESION</span></a></li>
</ul>
</nav>
<!-- End Sidebar navigation -->
</div>
<!-- End Sidebar scroll-->
</aside>
<!-- ============================================================== -->
<!-- End Left Sidebar - style you can find in sidebar.scss -->
<!-- ============================================================== -->
<!-- ============================================================== --><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Categorías</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<style>
.popover {
white-space: pre-line;
}
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-12 align-self-center">
<h4 class="page-title text-truncate text-dark font-weight-medium mb-1">LISTA DE CATEGORIAS</h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Categorías</li>
</ol>
</nav>
</div>
</div>
<!--<div class="col-5 align-self-center">
<div class="customize-input float-right">
<select class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
<option selected>Dic 20</option>
</select>
</div>
</div>-->
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div id="card_catego" class="row">
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalCategora" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Creador de categorías</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="nombre">Nombre</label>
<input type="text" class="form-control custom-radius custom-shadow border-0" id="nombre">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="descripcion">Descripción</label>
<textarea class="form-control" id="descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="grupo">Grupo
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grupo" data-toggle="popover" data-placement="top"
data-content="Gastos fijos: son todo que podemos estimar.
Gastos personales: son todo aquellos que no se puede estimar.
Ej: Electricidad, alquiler, celular, peluquería, parqueadero, gasolina son gastos fijos">
</i>
</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="grupo">
<option value="0" selected>Selecciona una opción</option>
<option value="1">Gastos fijos</option>
<option value="2">Gastos personales</option>
<option value="3">Ahorros</option>
<option value="4">Ingresos</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="categoria">Incluirlo dentro de una categoría
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Sub-categoria" data-toggle="popover" data-placement="top"
data-content="Incluir una categoría dentro de otra ayuda a entender el comportamiento de los gastos.
Ej: categoría principal es vehiculo y dentro de esa categoría existe gasolina, parqueadero, seguro, mantenimiento, etc.
Para la categoría gasolina incluyo dentro de la categoría vehiculo.">
</i>
</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="categoria">
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="save_cate" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalDeletCatego" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Eliminar categoría</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="text_delete_catego" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="btn_delete_categoria" class="btn btn-danger">Eliminar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalEditCatego" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Editor de categorías</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_nombre">Nombre</label>
<input type="text" class="form-control custom-radius custom-shadow border-0" id="edit_nombre">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_descripcion">Descripción</label>
<textarea class="form-control" id="edit_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_grupo">Grupo</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="edit_grupo">
<option value="0" selected>Selecciona una opción</option>
<option value="1">Gastos fijos</option>
<option value="2">Gastos personales</option>
<option value="3">Ahorros</option>
<option value="4">Ingresos</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_categoria">Incluirlo en una categoría</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="edit_categoria">
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="btn_edit_cate" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalCategoAddInfo" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configuración Inicial I</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Categorías:</strong></p>
<p>para crear una categoría dale clic en el siguiente recuadro:</p>
<div class='col-md-12' id='add_categoria' data-target='#ModalCategora' data-toggle='modal' data-dismiss="modal">
<a class='card'>
<div class='card-body'>
<div class='row'>
<div class='col-md-9 col-lg-9 col-xl-9'><h3 class='card-title text-muted'><i class='fas fa-plus mr-2'></i>Nueva categoría</h3></div>
<div class='col-md-12 col-lg-12 col-xl-12' style='position: absolute;'><h4 class='card-title text-muted fa-2x float-right'><i class='icon-arrow-right'></i></h4></div>
</div>
</div>
</a>
</div>
</div>
<div class="modal-footer">
<button type="button"
class="btn waves-effect waves-light btn-rounded btn-primary"
data-dismiss="modal">Finalizar</button>
</div>
</div>
</div>
</div>
<div id="ModalCongratuCatego" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Felicitaciones!</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Bien hecho </strong>!</p>
<p>Haz creado tu primera categoría. Crea todas las categorías necesarias e incluso
agrega subcategorías.</p>
<p><strong>Ej:</strong> Categoría principal <strong>Vehiculo</strong> y dentro de esta
<strong>gasolina, parqueadero, repuestos, impuestos, etc</strong>.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button"
class="btn waves-effect waves-light btn-rounded btn-primary"
data-toggle="modal" data-target="#ModalAccountInfo" data-dismiss="modal">Siguiente
</button>
</div>
</div>
</div>
</div>
<div id="ModalAccountInfo" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configuración Inicial II</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Cuentas:</strong></p>
<p>El siguiente paso será crear las cuentas con las cuales podras identificar donde esta depositado
el dinero.</p>
<p><strong>Ej: </strong>Cuenta de ahorros - Natillera - CDT - Efectivo - Tarjeta de credito</p>
<p>Para eso darás clic en cuentas en la barra de navegación ubicada al lado izquierdo de la
pagina o <i class="fas fa-bars"></i> ubicado en la parte superior lado izquierdo.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<a href="cuentas">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-primary">Siguiente</button>
</a>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../dist/js/custom.min.js"></script>
<script src="../java/functions.php"></script>
</body>
</html><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$nombre = $_POST["nombre"];
$id = $_POST["id"];
$descripcion = $_POST["descripcion"];
$grupo = $_POST["grupo"];
$sub_categoria = $_POST["sub_categoria"];
$update = "UPDATE fionadb.categorias
SET categoria='$nombre', sub_categoria='$sub_categoria', grupo='$grupo',
descripcion='$descripcion' WHERE id=$id and id_user='$id_user';";
$save = mysqli_query($conn, $update);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$id = $_POST["id"];
$delete1 = "DELETE FROM fionadb.cuentas
WHERE id=$id and id_user='$id_user';";
$delete2 = "DELETE FROM fionadb.movimientos
WHERE cuenta=$id and id_user='$id_user';";
$save1 = mysqli_query($conn, $delete1);
$save2 = mysqli_query($conn, $delete2);
if(!$save1 || !$save2){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
function consolidado(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT nombre, FORMAT(SUM(IF(valor > 0, valor, 0)),2) AS ingreso,
FORMAT(SUM(IF(valor < 0, valor, 0)),2) AS egreso,
SUM(valor) AS utilidad, a.divisa, a.id_user
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
WHERE a.id_user = '$id_user' and a.divisa = '$divi' and
fecha>='$fecha_ini' and fecha<='$fecha_fin' GROUP BY a.cuenta, a.divisa";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function ingreso(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT b.categoria, SUM(valor) AS cantidad FROM fionadb.movimientos AS a
JOIN fionadb.categorias AS b ON (a.categoria = b.id and a.id_user = b.id_user) WHERE grupo= 4
and a.id_user='$id_user' and divisa='$divi' and
fecha>='$fecha_ini' and fecha<='$fecha_fin' GROUP BY b.categoria";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function egreso(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT b.categoria, SUM(valor) AS cantidad FROM fionadb.movimientos AS a
JOIN fionadb.categorias AS b ON (a.categoria = b.id and a.id_user = b.id_user) WHERE (grupo= 1
or grupo = 2) and a.id_user='$id_user' and divisa='$divi' and
fecha>='$fecha_ini' and fecha<='$fecha_fin' GROUP BY b.categoria";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function ahorros(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT nombre, SUM(valor) + monto_inicial AS cantidad FROM fionadb.cuentas AS a JOIN fionadb.movimientos AS b
ON(a.id_user = b.id_user and b.cuenta = a.id) WHERE a.id_user='$id_user' and b.divisa='$divi' and
fecha>='$fecha_ini' and fecha<='$fecha_fin' and cuenta_ahorro = 1 GROUP BY nombre";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function top_gasto(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT b.categoria, SUM(valor) AS cantidad, a.divisa, a.id_user
FROM fionadb.movimientos AS a JOIN fionadb.categorias AS b ON(a.id_user = b.id_user and a.categoria = b.id)
WHERE a.id_user = '$id_user' and a.divisa = '$divi' and fecha>='$fecha_ini' and fecha<='$fecha_fin' and valor < 0
and id_transfe IS NULL GROUP BY a.categoria, a.divisa ORDER BY cantidad ASC LIMIT 10";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function consolidado_year(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT nombre, SUM(IF(valor > 0, valor, 0)) AS ingreso,
SUM(IF(valor < 0, valor, 0)) AS egreso,
SUM(valor) AS utilidad, a.divisa, a.id_user
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
WHERE a.id_user = '$id_user' and a.divisa = '$divi' GROUP BY a.cuenta, a.divisa";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function move_year(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$cuenta = $_GET['account'];
$sig = $_GET['sig'];
if ($sig == 1){
$compa = '>';
} else {
$compa = '<';
}
$strsql = "SELECT b.nombre, SUM(valor) AS cantidad, a.divisa, a.id_user, MONTHNAME(fecha) AS mes
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
WHERE a.id_user = '$id_user' and a.divisa = '$divi' and valor $compa 0
and b.nombre = '$cuenta' GROUP BY MONTH(fecha) ORDER BY MONTH(fecha) ASC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function move_account_moth(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$cuenta = $_GET['account'];
$mes = $_GET['mes'];
$sig = $_GET['sig'];
if ($sig == 1){
$compa = '>';
} else {
$compa = '<';
}
$strsql = "SELECT c.categoria, SUM(valor) AS cantidad, a.divisa, a.id_user, fecha
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
JOIN fionadb.categorias AS c ON (a.id_user = c.id_user and a.categoria =c.id) WHERE a.id_user = '$id_user'
and a.divisa = '$divi' and valor $compa 0 and MONTHNAME(fecha) = '$mes'
and b.nombre = '$cuenta' GROUP BY a.categoria ORDER BY fecha ASC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function move_account_interval(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$cuenta = $_GET['account'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT c.categoria, SUM(valor) AS cantidad, a.divisa, a.id_user, fecha
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
JOIN fionadb.categorias AS c ON (a.id_user = c.id_user and a.categoria =c.id) WHERE a.id_user = '$id_user'
and a.divisa = '$divi' and fecha >= '$fecha_ini' and fecha <= '$fecha_fin'
and b.nombre = '$cuenta' GROUP BY a.categoria ORDER BY fecha ASC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function move_catego_interval(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$catego = $_GET['catego'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT b.nombre, SUM(valor) AS cantidad, a.divisa, a.id_user, fecha
FROM fionadb.movimientos AS a JOIN fionadb.cuentas AS b ON(a.id_user = b.id_user and a.cuenta = b.id)
JOIN fionadb.categorias AS c ON (a.id_user = c.id_user and a.categoria =c.id) WHERE a.id_user = '$id_user'
and a.divisa = '$divi' and fecha >= '$fecha_ini' and fecha <= '$fecha_fin'
and c.categoria = '$catego' GROUP BY a.cuenta ORDER BY fecha ASC";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function cumpli_presu_lvl_1(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$fecha_ini = $_GET['fecha_ini'];
$fecha_fin = $_GET['fecha_fin'];
$strsql = "SELECT categoria, grupo, SUM(cantidad) AS cantidad, SUM(generado) AS generado, ROUND(SUM(generado)/SUM(cantidad) * 100, 2)
AS cumplimiento, MONTHNAME(CONCAT(year,'-',mes,'-',1)) AS name_mes, mes, year, id_user FROM compara_presu WHERE id_user = '$id_user' and mes >= MONTH('$fecha_ini') and mes <= MONTH('$fecha_fin')
GROUP BY categoria, mes, year, id_user ORDER BY grupo DESC, categoria, year, mes";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function cumpli_presu_lvl_2(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$catego = $_GET['catego'];
$mes = $_GET['mes'];
$strsql = "SELECT * FROM fionadb.compara_presu WHERE categoria = '$catego' and mes = $mes and id_user = '$id_user'";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
$action = $_GET['action'];
switch($action) {
case 1:
consolidado();
break;
case 2:
ingreso();
break;
case 3:
egreso();
break;
case 4:
ahorros();
break;
case 5:
top_gasto();
break;
case 6:
consolidado_year();
break;
case 7:
move_year();
break;
case 8:
move_account_moth();
break;
case 9:
move_account_interval();
break;
case 10:
move_catego_interval();
break;
case 11:
cumpli_presu_lvl_1();
break;
case 12:
cumpli_presu_lvl_2();
break;
}
?>
<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$ano = $_POST["ano"];
$delete1 = "DELETE FROM fionadb.presupuesto
WHERE year = $ano";
$save1 = mysqli_query($conn, $delete1);
if(!$save1){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$id=$_GET["id"];
$action=$_GET["action"];
$insert = "SELECT nombre, a.descripcion, FORMAT(SUM(valor) + monto_inicial,2) AS cantidad, b.divisa
FROM fionadb.cuentas AS a JOIN fionadb.movimientos AS b ON (a.id_user = b.id_user
and b.cuenta = a.id) WHERE a.id_user='$id_user' and a.id=$id GROUP BY nombre, divisa";
$ejecutar =mysqli_query( $conn,$insert);
$lista = mysqli_fetch_array($ejecutar);
$nombre = $lista["nombre"];
$descripcion = $lista["descripcion"];
$cantidad = $lista["cantidad"];
$divisa = $lista["divisa"];
if ($action == 1) {
echo "Movimientos de $nombre";
} else if ($action == 2) {
echo "<strong>Descripción: </strong>$descripcion";
} else if ($action == 3) {
echo "<strong>Balance: </strong>$cantidad $divisa";
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$id = $_POST["id"];
$fecha = $_POST["fecha"];
$delete = "DELETE FROM fionadb.movimientos
WHERE (id=$id or id_transfe=$id) and fecha='$fecha' and id_user='$id_user';";
$save = mysqli_query($conn, $delete);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - New Presu</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-12 align-self-center">
<h4 class="page-title text-truncate text-dark font-weight-medium mb-1">CREADOR DE PRESUPUESTO</h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item"><a href="presupuesto" class="text-muted">Presupuesto</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Creador de presupuesto</li>
</ol>
</nav>
</div>
</div>
<!--<div class="col-5 align-self-center">
<div class="customize-input float-right">
<select class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
<option selected>Aug 19</option>
<option value="1">July 19</option>
<option value="2">Jun 19</option>
</select>
</div>
</div>-->
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div id="form_presu" class="row">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="divisa">Divisa</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="divisa">
<option value="0" selected>Selecciona una opción</option>
<option value="COP">COP</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="GBD">GBD</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option>
<option value="MXN">MXN</option>
<option value="ILS">ILS</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="ano">Año a presupuestar</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="ano">
<option value="0" selected>Selecciona una opción</option>
<?php
$year_now = date(Y);
$year_last = $year_now - 1;
$year_future = $year_now + 1;
echo "
<option value='$year_last'>$year_last</option>
<option value='$year_now'>$year_now</option>
<option value='$year_future'>$year_future</option>"; ?>
</select>
</div>
</div>
<button type="button" id="next_step_1" class="btn btn-primary">Siguiente</button>
<a href="presupuesto"><button type="button" id="finaly_step"
style="display: none;" class="btn btn-success ml-2">Finalizar</button></a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalSelectCat" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Presupuesto Parte I</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="categoria">Categoria</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="categoria">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="modo_presu">Modo de presupuesto</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="modo_presu">
<option value="0" selected>Selecciona una opción</option>
<option value="1">Mensual</option>
<option value="2">Bimensual</option>
<option value="3">Trimestral</option>
<option value="4">Cuatrisemestral</option>
<option value="6">Semestral</option>
<option value="12">Anual</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="next_step_2" class="btn btn-primary">Siguiente</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalInsertVal" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Presupuesto Parte II</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="mes_ini">Mes de inicio</label>
<select class="custom-select mr-sm-2 custom-radius
text-dark custom-shadow border-0" id="mes_ini">
<option value="0" selected>Selecciona una opción</option>
<option value="1">Enero</option>
<option value="2">Febrero</option>
<option value="3">Marzo</option>
<option value="4">Abril</option>
<option value="5">Mayo</option>
<option value="6">Junio</option>
<option value="7">Julio</option>
<option value="8">Agosto</option>
<option value="9">Septiembre</option>
<option value="10">Octubre</option>
<option value="11">Noviembre</option>
<option value="12">Diciembre</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="valor">Valor del monto</label>
<input type="number" step="0.01"
class="form-control custom-radius custom-shadow border-0" id="valor">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" id="back_step_1">Atras</button>
<button type="button" id="btn_save_presu_type1" class="btn btn-primary">Finalizar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalInsertValMensu" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Presupuesto Parte II</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="mes_mensual">Mes de inicio</label>
<select class="custom-select mr-sm-2 custom-radius
text-dark custom-shadow border-0" disabled id="mes_mensual">
<option selected value="1">Enero</option>
<option value="2">Febrero</option>
<option value="3">Marzo</option>
<option value="4">Abril</option>
<option value="5">Mayo</option>
<option value="6">Junio</option>
<option value="7">Julio</option>
<option value="8">Agosto</option>
<option value="9">Septiembre</option>
<option value="10">Octubre</option>
<option value="11">Noviembre</option>
<option value="12">Diciembre</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="valor_mensual">Valor del monto</label>
<input type="number" step="0.01"
class="form-control custom-radius custom-shadow border-0" id="valor_mensual">
</div>
</div>
<div id="div_replicar" class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-check form-check-inline">
<div class="custom-control custom-checkbox">
<input type="checkbox" onchange="name_btn(this.checked)" class="custom-control-input" id="replicar_val">
<label class="custom-control-label" for="replicar_val">Replicar valores para todos los meses</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" id="back_step_2">Atras</button>
<button type="button" id="btn_save_presu_type2" class="btn btn-primary">Siguiente</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../java/functions.php"></script>
<script src="../dist/js/custom.min.js"></script>
</body>
</html><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$id = $_GET["id"];
$insert = "SELECT * FROM fionadb.notification WHERE id_user='$id_user' ORDER BY fecha DESC";
$ejecutar =mysqli_query( $conn,$insert);
while ($lista = mysqli_fetch_array($ejecutar)){
$tipo = $lista ["tipo"];
$titulo = $lista ["titulo"];
$fecha = $lista ["fecha"];
$leido = $lista ["leido"];
$id = $lista ["id"];
$contenido = $lista ["Contenido"];
if($tipo == "Nuevo"){
$color_btn = "btn-success";
$icon = "<i class='far fa-newspaper'></i>";
} else if ($tipo == "Mejora"){
$color_btn = "btn-warning";
$icon = "<i class='fas fa-wrench'></i>";
}
if ($leido == 0){
$text_class = "font-weight-bold";
} else {
$text_class = "";
}
echo "<div onclick='show_mensaje($id)'
class='message-item d-flex align-items-center border-bottom'>
<button class='$color_btn btn-circle ml-3'>$icon</button>
<div class='w-75 d-inline-block v-middle pl-2'>
<h6 class='message-title $text_class mb-0 mt-1'>$titulo</h6>
<span class='font-12 text-nowrap d-block text-muted'>$tipo</span>
<span class='font-12 text-nowrap d-block text-muted'>$fecha</span>
</div>
</div>";
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = "\"".$_SESSION["Id_user"]."\"";
$divisa_primary = "\"".$_SESSION["divisa"]."\"";
?>
var idu = <?php echo $id_user;?>;
var divisa_primary = <?php echo $divisa_primary;?>;
date_input();
load_data_balance();
var nro_mesajes = document.getElementById("nro_message").innerHTML;
var nro_ant_mes = 0;
getPagina("consult_divisa_repo?select=" + divisa_primary, "select_divisa");
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
function load_data_balance(){
$.ajax({
type: "GET",
url: '../json/consult?action=4&idu='+idu,
dataType: "json",
success: function(data){
document.getElementById("balance").innerHTML = "";
$("#balance").append("<a class='dropdown-item' href='/pages/profile'><i "+
" class='fas fa-user mr-2 ml-1'></i>"+
"My Profile</a>"
);
$.each(data,function(key, registro) {
var utilidad_bal = registro.utilidad_bal;
$("#balance").append("<a class='dropdown-item row' style ='margin: 0px;'>"+
"<i class='fas fa-credit-card mr-2 ml-1'></i>"+
"Balance <p class='float-right'>" + utilidad_bal + " "+ registro.divisa +"</p>"+
"</a>"
);
});
$("#balance").append("<a class='dropdown-item' onclick='screen_home()'><i "+
" class='fas fa-plus-square mr-2 ml-1'></i>"+
"Add to home screen</a>"
);
$("#balance").append("<div class='dropdown-divider'></div>"+
"<a class='dropdown-item' href='/'><i "+
" class='fas fa-power-off mr-2 ml-1'></i>"+
"Logout</a>"
);
}
});
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
function date_input(){
var divisa_primary = <?php echo $divisa_primary;?>;
var now = new Date($.now())
, year
, month
, date
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
formattedDateTime = year + '-' + month + '-' + date;
document.getElementById("fecha_fin").value = formattedDateTime;
now.setMonth(now.getMonth() - 1);
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
formattedDateTime = year + '-' + month + '-' + date;
document.getElementById("fecha_ini").value = formattedDateTime;
view_chart(divisa_primary);
}
function getPagina(strURLop, div) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURLop, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
UpdatePage(xmlHttp.responseText, div);
}
}
xmlHttp.send(strURLop);
};
function UpdatePage(str, div){
document.getElementById(div).innerHTML = str ;
};
$("#search_report").click(function(){
var divisa_primary = <?php echo $divisa_primary;?>;
view_chart(divisa_primary);
})
$('#screen_android').click(function(){
$("#ModalScreen").modal("hide");
$("#ModalScreenAndroid").modal("show");
});
function showactivityaccount(cuenta, fecha_ini, fecha_fin){
var idu = <?php echo $id_user;?>;
var divisa_primary = document.getElementById("select_divisa").value;
document.getElementById("bodyActivity").innerHTML = "";
document.getElementById("ModalActiAccLbl").innerHTML = "Actividad de " + cuenta;
//movimientos por cuenta
$.ajax({
type: "GET",
url: '../json/reportes?action=9&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin+'&account='+cuenta,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var cuenta = '"'+registro.nombre+'"';
if (registro.cantidad > 0) {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-success'>"+formatter.format(registro.cantidad)+
"</p><p class='text-muted ml-1'></p>"+registro.fecha+"</h6>"+
"</div>");
} else {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-danger'>"+formatter.format(registro.cantidad)+
"</p><p class='text-muted ml-1'></p>"+registro.fecha+"</h6>"+
"</div>");
}
});
},
error: function (data) {
$("#bodyActivity").append("<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"No se encontro ninguna categoria</h6>");
}
});
$("#ModalActivityAccount").modal("show");
}
function showactivitycatego(categoria, fecha_ini, fecha_fin){
var idu = <?php echo $id_user;?>;
var divisa_primary = document.getElementById("select_divisa").value;
document.getElementById("bodyActivity").innerHTML = "";
document.getElementById("ModalActiAccLbl").innerHTML = "Actividad de " + categoria;
//movimientos por categoria
$.ajax({
type: "GET",
url: '../json/reportes?action=10&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin+'&catego='+categoria,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-danger'>"+formatter.format(registro.cantidad)+
"</p><p class='text-muted ml-1'></p>"+registro.fecha+"</h6>"+
"</div>");
});
},
error: function (data) {
//console.log(data);
}
});
$("#ModalActivityAccount").modal("show");
}
function showcumplipresu(categoria, mes){
var idu = <?php echo $id_user;?>;
var divisa_primary = document.getElementById("select_divisa").value;
document.getElementById("bodyActivity").innerHTML = "";
document.getElementById("ModalActiAccLbl").innerHTML = "Cumplimiento de " + categoria;
//mCumplimiento por sub categorias
$.ajax({
type: "GET",
url: '../json/reportes?action=12&idu='+ idu+'&divi='+divisa_primary+
'&mes='+mes+'&catego='+categoria,
dataType: "json",
success: function(data){
console.log(data);
$.each(data,function(key, registro) {
var grupo = registro.grupo;
var cumpli = registro.cumplimiento;
if ((grupo == 4 && cumpli >= 95) || ((grupo == 1 || grupo == 2) &&
cumpli <= 85)) {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.categoria+" - "+registro.sub_categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-success'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
} else if ((grupo == 4 && (cumpli >= 85 && cumpli < 95)) || ((grupo == 1 || grupo == 2) &&
(cumpli > 85 && cumpli <= 100))) {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.categoria+" - "+registro.sub_categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-warning'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
} else {
$("#bodyActivity").append("<div class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.categoria+" - "+registro.sub_categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-danger'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
}
});
},
error: function (data) {
//console.log(data);
}
});
$("#ModalActivityAccount").modal("show");
}
function view_chart(divisa_primary){
var idu = <?php echo $id_user;?>;
var fecha_ini = document.getElementById("fecha_ini").value;
var fecha_fin = document.getElementById("fecha_fin").value;
document.getElementById("resumen").innerHTML = "";
document.getElementById("top_10").innerHTML = "";
document.getElementById("cumplimiento").innerHTML = "";
//Grafica Ingreso
$.ajax({
type: "GET",
url: '../json/reportes?action=2&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
var total = 0;
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.categoria] = d.cantidad;
value.push(d.categoria);
total += Number(d.cantidad);
});
//console.log(data2);
var chart1 = c3.generate({
bindto: '#campaign-v2',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Total '+ formatter.format(total),
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v2',
data: {
columns: [
['Sin ingresos', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ingresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
//Grafica Egreso
$.ajax({
type: "GET",
url: '../json/reportes?action=3&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
var total = 0;
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.categoria] = d.cantidad;
value.push(d.categoria);
total += Number(d.cantidad);
});
//console.log(data2);
var chart1 = c3.generate({
bindto: '#campaign-v3',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Total '+ formatter.format(total),
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v3',
data: {
columns: [
['Sin egresos', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Egresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
//Grafica Ahorro
$.ajax({
type: "GET",
url: '../json/reportes?action=4&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
var total = 0;
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.nombre] = d.cantidad;
value.push(d.nombre);
total += Number(d.cantidad);
});
var chart1 = c3.generate({
bindto: '#campaign-v4',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Total '+ formatter.format(total),
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v4',
data: {
columns: [
['Sin Ahorros', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ahorros',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
//Resumen por cuenta
$.ajax({
type: "GET",
url: '../json/reportes?action=1&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var cuenta = '"'+registro.nombre+'"';
var fecha_ini = '"'+document.getElementById("fecha_ini").value +'"';
var fecha_fin = '"'+document.getElementById("fecha_fin").value +'"';
$("#resumen").append("<div onclick='showactivityaccount("+cuenta+","+fecha_ini+","+fecha_fin+")' class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 col-lg-12 col-xl-12 text-muted'>"+
"<p class='text-success'>"+registro.ingreso+"</p>/<p class='text-danger'>"+
registro.egreso+"</p></h6>"+
"</div>"+
"</div>");
});
},
error: function (data) {
console.log(data);
}
});
//TOP 10
$.ajax({
type: "GET",
url: '../json/reportes?action=5&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var catego = '"'+registro.categoria+'"';
var fecha_ini = '"'+document.getElementById("fecha_ini").value +'"';
var fecha_fin = '"'+document.getElementById("fecha_fin").value +'"';
$("#top_10").append("<div onclick='showactivitycatego("+catego+","+fecha_ini+","+fecha_fin+")' class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 col-lg-12 col-xl-12 text-muted'>"+
"<p class='text-danger'>"+registro.cantidad+"</p></h6>"+
"</div>"+
"</div>");
});
},
error: function (data) {
console.log(data);
}
});
//Presupuesto
$.ajax({
type: "GET",
url: '../json/reportes?action=11&idu='+ idu+'&divi='+divisa_primary+
'&fecha_ini='+fecha_ini+'&fecha_fin='+fecha_fin,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var catego = '"'+registro.categoria+'"';
var mes = registro.mes;
var fecha_ini = '"'+document.getElementById("fecha_ini").value +'"';
var fecha_fin = '"'+document.getElementById("fecha_fin").value +'"';
var grupo = registro.grupo;
var cumpli = registro.cumplimiento;
if ((grupo == 4 && cumpli >= 95) || ((grupo == 1 || grupo == 2) &&
cumpli <= 85)) {
$("#cumplimiento").append("<div onclick='showcumplipresu("+catego+","+mes+")' class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.name_mes+" - "+registro.categoria+"</h4>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-success'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
} else if ((grupo == 4 && (cumpli >= 85 && cumpli < 95)) || ((grupo == 1 || grupo == 2) &&
(cumpli > 85 && cumpli <= 100))) {
$("#cumplimiento").append("<div onclick='showcumplipresu("+catego+","+mes+")' class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.name_mes+" - "+registro.categoria+"</h4>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-warning'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
} else {
$("#cumplimiento").append("<div onclick='showcumplipresu("+catego+","+mes+")' class='card border-botton border-right border-left'>"+
"<div class='row'>"+
"<h4 class='ml-2 mt-1 card-title col-md-10 col-lg-10 col-xl-10 text-muted'>"+
registro.name_mes+" - "+registro.categoria+"</h4>"+
"<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"<p class='text-danger'>"+cumpli+" %</p></h6>"+
"</div>"+
"</div>");
}
});
},
error: function (data) {
$("#cumplimiento").append("<h6 class='card-title ml-3 row col-md-2 col-lg-2 col-xl-2 text-muted'>"+
"No se encontro ningún presupuesto</h6>");
}
});
d3.select('#campaign-v2 .c3-chart-arcs-title').style('font-family', 'Rubik');
d3.select('#campaign-v3 .c3-chart-arcs-title').style('font-family', 'Rubik');
d3.select('#campaign-v4 .c3-chart-arcs-title').style('font-family', 'Rubik');
};
function notificar(titulo, contenido){
if(Notification.permission != "granted"){
Notification.requestPermission();
}else{
var notification = new Notification(titulo,
{
icon: "http://fiona.byethost11.com/assets/images/logo-icon.png",
body: contenido
}
);
}
}
function show_mensaje(id){
$.ajax({
type: "GET",
url: '../json/consult?action=8&idu='+idu+'&id='+id,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
document.getElementById("ModalMensaLbl").innerHTML = registro.titulo;
document.getElementById("catego_mensaje").innerHTML = registro.tipo;
document.getElementById("fecha_mensaje").innerHTML = registro.fecha;
document.getElementById("contenido_mensaje").innerHTML = registro.Contenido;
});
}
});
$("#ModalMensajes").modal("show");
$.ajax('../conexions/read_mensaje', {
type: 'POST',
data: {
id: id
},
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
}
});
}
function count_message(){
//console.log("antes: " + nro_mesajes);
nro_ant_mes = nro_mesajes;
getPagina("consult_nro_message", "nro_message");
nro_mesajes = document.getElementById("nro_message").innerHTML;
//console.log("despues: " + nro_mesajes);
if (nro_ant_mes < nro_mesajes && nro_ant_mes != ""){
notificar('FIONA Notificacion', "Tienes un nuevo mensaje de fiona!");
getPagina("consult_mensajes", "list_mensajes");
}
else if (nro_mesajes < nro_ant_mes){
getPagina("consult_mensajes", "list_mensajes");
}
};
setInterval("count_message()", 5000);<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$insert = "select
a.categoria, b.categoria AS sub_categoria, if(isnull(b.categoria), a.id, b.id) AS nro_sub_catego,
b.grupo, a.id_user from fionadb.categorias a left join fionadb.categorias b on
(a.id_user = b.id_user and b.sub_categoria = a.id) where
a.grupo <> 5 and a.id_user = '$id_user' and b.categoria IS NOT NULL
order by a.categoria, nro_sub_catego";
$ejecutar =mysqli_query( $conn,$insert);
if (!$_GET["act"]){
$select = 0;
} else{
$select = $_GET["act"];
}
$aux = "";
$flag = 0;
echo "<option value='0' selected>Sin categoria</option>";
while ($lista = mysqli_fetch_array($ejecutar)){
$id = $lista["nro_sub_catego"];
$sub_categoria = $lista ["sub_categoria"];
$categoria = $lista ["categoria"];
if ($categoria != $aux){
if ($select == $id){
echo "<option value='$id' selected class='font-weight-bold'>$categoria</option>";
} else {
echo "<option value='$id' class='font-weight-bold'>$categoria</option>";
}
$flag = 1;
} else {
$flag = 0;
}
if ($sub_categoria != $categoria){
if ($select == $id){
echo "<option value='$id' selected>  $sub_categoria</option>";
} else {
echo "<option value='$id'>  $sub_categoria</option>";
}
}
$aux = $categoria;
}
mysqli_close($conn);
?><file_sep><?php
class Password {
const SALT = 'FiOnA2020';
public static function hash($password) {
return hash('sha512', self::SALT . $password);
}
public static function verify($password, $hash) {
return ($hash == self::hash($password));
}
}
$servername = "localhost";
$username = "root";
$password = "<PASSWORD>";
$db = "fiona";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if (!$conn) {
//die("Connection failed: " . mysqli_connect_error());
echo 100;
}
/*else {
echo "Connected successfully";
}*/
?>
<file_sep><?php
session_start();
$id_user = "\"".$_SESSION["Id_user"]."\"";
?>
var idu = <?php echo $id_user;?>;
val_session(idu);
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
});
var nro_mesajes = document.getElementById("nro_message").innerHTML;
var nro_ant_mes = 0;
if (document.getElementById("ModalCategora")) {
var idu = <?php echo $id_user; ?>;
$("#save_cate").click(function(){
var nombre = document.getElementById("nombre").value;
var descripcion = document.getElementById("descripcion").value;
var grupo = document.getElementById("grupo").value;
var categoria = document.getElementById("categoria").value;
if (nombre == "" || grupo == 0) {
if (nombre == ""){
document.getElementById("nombre").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
if (grupo == 0) {
document.getElementById("grupo").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_categoria', {
type: 'POST', // http method
data: { nombre: nombre,
descripcion: descripcion,
grupo: grupo,
categoria: categoria }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalCategora').modal('hide');
document.getElementById("nombre").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("grupo").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("nombre").value = "";
document.getElementById("descripcion").value = "";
document.getElementById("grupo").value = 0;
document.getElementById("categoria").value = 0;
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data_cat(sub, idu);
getPagina("consult_cate", "categoria");
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.categorias == 2){
$("#ModalCongratuCatego").modal('show');
}
});
}
});
} else {
alert("Error: " + data);
}
}
});
}
});
function delete_catego(id, nombre){
document.getElementById("text_delete_catego").innerHTML=
"Esta segur@ de eliminar la categoria: <strong>" + nombre + "</strong>, si lo hace, " +
"toda la información sera borrada.";
$('#ModalDeletCatego').modal('show');
$('#btn_delete_categoria').click(function(){
$.ajax({
url: '../conexions/delete_categoria',
type: 'POST',
data: {id: id },
success: function(data){
$('#ModalDeletCatego').modal('hide');
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data_cat(sub, idu);
},
error: function(data) {
$('#ModalDeletCatego').modal('hide');
alert("No se guardaron los cambios.");
}
});
});
};
function edit_categoria(id, nombre, descripcion, grupo, sub_categoria){
getPagina("consult_cate?act="+sub_categoria, "edit_categoria");
document.getElementById("edit_nombre").value = nombre;
document.getElementById("edit_descripcion").value = descripcion;
document.getElementById("edit_grupo").value = grupo;
$('#ModalEditCatego').modal('show');
$('#btn_edit_cate').unbind('click').click(function(){
nombre = document.getElementById("edit_nombre").value;
descripcion = document.getElementById("edit_descripcion").value;
grupo = document.getElementById("edit_grupo").value;
sub_categoria = document.getElementById("edit_categoria").value;
if (nombre == "" || grupo == 0) {
if (nombre == ""){
document.getElementById("edit_nombre").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
if (grupo == 0) {
document.getElementById("edit_grupo").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/edit_catego', {
type: 'POST', // http method
data: { nombre: nombre,
id: id,
descripcion: descripcion,
grupo: grupo,
sub_categoria: sub_categoria }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalEditCatego').modal('hide');
document.getElementById("edit_nombre").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("edit_grupo").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("edit_nombre").value = "";
document.getElementById("edit_descripcion").value = "";
document.getElementById("edit_grupo").value = 0;
document.getElementById("edit_categoria").value = 0;
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data_cat(sub, idu);
$.ajax({
type: "GET",
url: '../json/consult?action=4&idu='+idu,
dataType: "json",
success: function(data){
document.getElementById("balance").innerHTML = "";
$.each(data,function(key, registro) {
var utilidad_bal = registro.utilidad_bal;
$("#balance").append("<i class='fas fa-credit-card mr-2 ml-1'></i>"+
"My Balance <p class='float-right'>" + utilidad_bal + "</p>");
});
}
});
} else {
alert("Error: " + data);
}
}
});
}
});
};
function load_data_cat(lvl, idu){
document.getElementById("card_catego").innerHTML = "";
if (lvl != 0) {
$("#card_catego").append("<div class='col-md-6'>"+
"<a class='card' href='#0'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-9 col-lg-9 col-xl-9 text-muted'>..</h3>"+
"<h4 class='card-title col-md-3 col-lg-3 col-xl-3 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
}
$.ajax({
type: "GET",
url: '../json/consult?action=1&idu='+idu+'&lvl='+lvl,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
$("#card_catego").append("<div class='card col-md-6'>"+
"<div class='card-body' style='padding-left: 10px; padding-right: 10px;'>"+
"<i class='icon-arrow-right float-right mt-3 ml-2 fa-2x'></i>"+
"<i class='fas fa-trash-alt float-right mt-4' onclick='delete_catego("+registro.id+","+'"'+registro.categoria+'"'+")' style='color: red;'></i>"+
"<i class='far fa-edit float-right mr-1 mt-4' onclick='edit_categoria("+registro.id+","+'"'+registro.categoria+'"'+","+'"'+registro.descripcion+'"'+","+registro.grupo+","+registro.sub_categoria+")'"+
" style='color: #5f76e8;'></i>"+
"<a href='#"+registro.id+"'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-9 col-lg-9 col-xl-9 mt-3'>"+registro.categoria+"</h3>"+
"</div>"+
"</a>"+
"</div>"+
"</div>");
});
$("#card_catego").append("<div class='col-md-6'>"+
"<a class='card' id='add_categoria' data-target='#ModalCategora' data-toggle='modal'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<div class='col-md-9 col-lg-9 col-xl-9'><h3 class='card-title text-muted'><i class='fas fa-plus mr-2'></i>Nueva categoria</h3></div>"+
"<div class='col-md-12 col-lg-12 col-xl-12' style='position: absolute;'><h4 class='card-title text-muted fa-2x float-right'><i class='icon-arrow-right'></i></h4></div>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
},
error: function(data) {
$("#card_catego").append("<div class='col-md-6'>"+
"<a class='card' id='add_categoria' data-target='#ModalCategora' data-toggle='modal'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-9 col-lg-9 col-xl-9 text-muted'><i class='fas fa-plus mr-2'></i>Nueva categoria</h3>"+
"<h4 class='card-title col-md-3 col-lg-3 col-xl-3 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
}
});
};
function val_new_cate(idu){
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.categorias == 1){
$("#ModalCategoAddInfo").modal('show');
}
});
}
});
}
var aux = 0;
load_data_cat(0, idu);
getPagina("consult_cate", "categoria");
load_data_balance();
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
val_new_cate(idu)
setInterval(function(){
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
if (sub != aux){
var idu = <?php echo $id_user; ?>;
aux = sub;
getPagina("consult_cate?act="+sub, "categoria");
load_data_cat(sub, idu);
}
}, 1000);
};
if (document.getElementById("ModalAccount")) {
var idu = <?php echo $id_user; ?>;
$("#save_account").click(function(){
var nombre = document.getElementById("nombre").value;
var descripcion = document.getElementById("descripcion").value;
var divisa = document.getElementById("divisa").value;
var monto_ini = document.getElementById("monto_ini").value;
var acco_save = document.getElementById("account_save").checked;
if (nombre == "" || divisa == 0 || monto_ini == "") {
if (nombre == ""){
document.getElementById("nombre").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
if (divisa == 0) {
document.getElementById("divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (monto_ini == ""){
document.getElementById("monto_ini").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_account', {
type: 'POST', // http method
data: { nombre: nombre,
descripcion: descripcion,
divisa: divisa,
acco_save: acco_save,
monto_ini: monto_ini }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalAccount').modal('hide');
document.getElementById("nombre").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("monto_ini").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("nombre").value = "";
document.getElementById("descripcion").value = "";
document.getElementById("divisa").value = 0;
document.getElementById("monto_ini").value = 0;
document.getElementById("account_save").checked = false;
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data(sub, idu);
load_data_balance();
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.cuentas == 1){
$("#ModalCongratuAccon").modal('show');
}
});
}
});
} else {
alert("Error: " + data);
}
}
});
}
});
function delete_account(id, nombre){
document.getElementById("text_delete_acco").innerHTML=
"Esta segur@ de eliminar la cuenta: <strong>" + nombre + "</strong>, si lo hace, " +
"toda la información sera borrada.";
$('#ModalDeletAcco').modal('show');
$('#btn_delete_account').click(function(){
$.ajax({
url: '../conexions/delete_account',
type: 'POST',
data: {id: id },
success: function(data){
$('#ModalDeletAcco').modal('hide');
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data(sub, idu);
load_data_balance();
},
error: function(data) {
$('#ModalDeletAcco').modal('hide');
alert("No se guardaron los cambios.");
}
});
});
};
function edit_account(id, nombre, descripcion, divisa, cantidad, ahorro){
document.getElementById("edit_nombre").value = nombre;
document.getElementById("edit_descripcion").value = descripcion;
document.getElementById("edit_divisa").value = divisa;
document.getElementById("edit_monto_ini").value = cantidad;
if (ahorro == 1) {
document.getElementById("edit_account_save").checked = true;
}
$('#ModalEditAcco').modal('show');
$('#btn_edit_account').unbind('click').click(function(){
nombre= document.getElementById("edit_nombre").value;
descripcion= document.getElementById("edit_descripcion").value;
divisa= document.getElementById("edit_divisa").value;
cantidad= document.getElementById("edit_monto_ini").value;
var acco_save = document.getElementById("edit_account_save").checked;
if (nombre == "" || divisa == 0 || cantidad == "") {
if (nombre == ""){
document.getElementById("edit_nombre").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
if (divisa == 0) {
document.getElementById("edit_divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (cantidad == ""){
document.getElementById("edit_monto_ini").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/edit_account', {
type: 'POST', // http method
data: { nombre: nombre,
id: id,
descripcion: descripcion,
divisa: divisa,
acco_save: acco_save,
monto_ini: cantidad }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalEditAcco').modal('hide');
document.getElementById("edit_nombre").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("edit_divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("edit_monto_ini").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("edit_nombre").value = "";
document.getElementById("edit_descripcion").value = "";
document.getElementById("edit_divisa").value = 0;
document.getElementById("edit_monto_ini").value = 0;
document.getElementById("edit_account_save").checked = false;
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
load_data(sub, idu);
load_data_balance();
} else {
alert("Error: " + data);
}
}
});
}
});
};
function load_data(lvl, idu){
document.getElementById("card_account").innerHTML = "";
if (lvl != 0) {
$("#card_catego").append("<div class='col-md-6'>"+
"<a class='card' href='#0'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'>..</h3>"+
"<h4 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
}
$.ajax({
type: "GET",
url: '../json/consult?action=2&idu='+idu+'&lvl='+lvl,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
var mensaje = "";
if (registro.cuenta_ahorro == 1){
mensaje = "Cuenta ahorro";
}
$("#card_account").append("<div class='col-md-6'>"+
"<div class='card'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-6 col-lg-6 col-xl-6'>"+registro.nombre+"</h3>"+
"<h4 class='card-title col-md-6 col-lg-6 col-xl-6'>$ "+registro.cantidad+"</h4>"+
"</div>"+
"<div class='row'>"+
"<p class='card-text col-6'>Divisas: "+registro.divisa+"</p>"+
"<p class='card-text col-6'>"+mensaje+"</p>"+
"</div>"+
"<a href='movimientos?account="+registro.id+"' class='btn btn-rounded btn-success mr-1'>"+
"<i class='fas fa-sign-out-alt mr-2'></i>Entrar</a>"+
"<button class='btn btn-circle btn-primary mr-1' onclick='edit_account("+registro.id+","+'"'+registro.nombre+'"'+
","+'"'+registro.descripcion+'"'+","+'"'+registro.divisa+'"'+","+registro.monto_inicial+","+registro.cuenta_ahorro+")'>"+
"<i class='far fa-edit'></i></button>"+
"<button class='btn btn-circle btn-danger' onclick='delete_account("+registro.id+","+'"'+registro.nombre+'"'+")'>"+
"<i class='fas fa-trash-alt'></i></button>"+
"</div>"+
"</div>"+
"</div>");
});
$("#card_account").append("<div class='col-md-6'>"+
"<a class='card' id='add_categoria' data-target='#ModalAccount' data-toggle='modal'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'><i class='fas fa-plus mr-2'></i>Nueva cuenta</h3>"+
"<h4 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
},
error: function(data) {
$("#card_account").append("<div class='col-md-6'>"+
"<a class='card' id='add_categoria' data-target='#ModalAccount' data-toggle='modal'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'><i class='fas fa-plus mr-2'></i>Nueva cuenta</h3>"+
"<h4 class='card-title col-md-6 col-lg-6 col-xl-6 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
}
});
};
function val_new_acco(idu){
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.cuentas == 0){
$("#ModalAccountInfo").modal('show');
}
});
}
});
}
var aux = 0;
load_data(0, idu);
load_data_balance();
val_new_acco(idu);
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
setInterval(function(){
var url = window.location.href;
var div = url.split("#");
var sub = div[1];
if (!sub){
sub = 0;
}
if (sub != aux){
var idu = <?php echo $id_user; ?>;
aux = sub;
load_data(sub, idu);
}
}, 1000);
};
if (document.getElementById("card_presu")) {
var idu = <?php echo $id_user; ?>;
function delete_presu(ano){
var idu = <?php echo $id_user; ?>;
document.getElementById("text_delete_presu").innerHTML=
"Esta segur@ de eliminar el presupuesto del año <strong>" + ano + "</strong>, si lo hace, " +
"toda la información sera borrada.";
$('#ModalDeletPresu').modal('show');
$('#btn_delete_presu').click(function(){
$.ajax({
url: '../conexions/delete_presu',
type: 'POST',
data: {ano: ano },
success: function(data){
$('#ModalDeletPresu').modal('hide');
load_data(idu);
},
error: function(data) {
$('#ModalDeletPresu').modal('hide');
alert("No se guardaron los cambios.");
}
});
});
};
function load_data(idu){
document.getElementById("card_presu").innerHTML = "";
$.ajax({
type: "GET",
url: '../json/presupuesto?action=1&idu='+idu,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
$("#card_presu").append("<div class='col-md-6'>"+
"<div class='card'>"+
"<div class='card-body' style='padding: 20px;'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-12 col-lg-12 col-xl-12'>Presupuesto "+registro.year+"</h3>"+
"</div>"+
"<div class='row mb-1'>"+
"<p class='card-text col-12 text-success'>Ingresos: $ "+registro.ingreso+"</p>"+
"<p class='card-text col-12 text-danger'>Egresos: $ "+registro.egreso+"</p>"+
"</div>"+
"<a href='view-presu?yr="+registro.year+"' class='btn btn-rounded btn-success mr-1'>"+
"<i class='fas fa-sign-out-alt mr-2'></i>Entrar</a>"+
"<button class='btn btn-circle btn-danger' onclick='delete_presu("+registro.year+")'>"+
"<i class='fas fa-trash-alt'></i></button>"+
"</div>"+
"</div>"+
"</div>");
});
$("#card_presu").append("<div class='col-md-6'>"+
"<a class='card' href='new-presu'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-10 col-lg-10 col-xl-10 text-muted'><i class='fas fa-plus mr-2'></i>Nuevo presupuesto</h3>"+
"<h4 class='card-title col-md-2 col-lg-2 col-xl-2 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
},
error: function(data) {
$("#card_presu").append("<div class='col-md-6'>"+
"<a class='card' href='new-presu'>"+
"<div class='card-body'>"+
"<div class='row'>"+
"<h3 class='card-title col-md-10 col-lg-10 col-xl-10 text-muted'><i class='fas fa-plus mr-2'></i>Nuevo presupuesto</h3>"+
"<h4 class='card-title col-md-2 col-lg-2 col-xl-2 text-muted'><i class='icon-arrow-right'></i></h4>"+
"</div>"+
"</div>"+
"</a>"+
"</div>");
}
});
};
function val_new_acco(idu){
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.cuentas == 0){
$("#ModalAccountInfo").modal('show');
}
});
}
});
}
load_data_balance();
val_new_acco(idu);
load_data(idu);
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
if (document.getElementById("add_data_presu")) {
var url = window.location.href;
var div = url.split("=");
var sub = div[1];
getPagina("consult_table_presu?year="+sub,"add_data_presu");
function edit_presu(catego, name_catego, ano, idu){
document.getElementById("ModalRubroLabel").innerHTML = "Presupuesto de " + name_catego;
document.getElementById("BodyRubro").innerHTML = "";
$.ajax({
type: "GET",
url: '../json/presupuesto?action=2&idu='+ idu+'&year='+ano+'&catego='+catego,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var mes = registro.mes;
var valor = registro.valor;
var id = registro.id;
var catego = registro.categoria;
var name_catego = '"'+registro.name_catego+'"';
$("#BodyRubro").append("<div onclick='edit_month_rubro("+id+","+mes+","+valor+","+catego+","+name_catego+")' class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.mes_name+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
formatter.format(valor)+"</h6>"+
"</div>");
});
},
error: function (data) {
}
});
$("#ModalRubro").modal("show");
};
function save_edit_rubro_month(id, mes, catego, name_catego){
var valor_edit = document.getElementById("valor_edit_presu").value;
if (valor_edit < 0 || valor_edit == ""){
document.getElementById("valor_edit_presu").className = "form-control custom-radius custom-shadow border-0 is-invalid";
} else {
$.ajax('../conexions/edit_rubro_month', {
type: 'POST', // http method
data: { mes: mes,
id: id,
valor: valor_edit }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data != 200) {
alert("Error: " + data);
}
}
});
$("#ModalEditRubro").modal("hide");
document.getElementById("valor_edit_presu").className = "form-control custom-radius custom-shadow border-0";
var url = window.location.href;
var div = url.split("=");
var sub = div[1];
var idu = <?php echo $id_user;?>;
edit_presu(catego, name_catego, sub, idu);
}
};
function edit_month_rubro(id, mes, valor, catego, name_catego){
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
document.getElementById("BodyEditRubro").innerHTML = "";
if (mes < month){
document.getElementById("BodyEditRubro").innerHTML = "Este Mes ya paso, Por lo tanto no se puede modificar.";
$("#btn_edit_rubro_month").attr('hidden',true);
} else {
document.getElementById("BodyEditRubro").innerHTML = "<div class='col-sm-12 col-md-12 col-lg-12 mt-2'>"+
"<div class='form-group mb-4'>"+
"<label class='mr-sm-2' for='mes_edit_presu'>Mes</label>"+
"<select disabled class='custom-select mr-sm-2 custom-radius text-dark custom-shadow border-0' id='mes_edit_presu'>"+
"<option value='0' selected>Selecciona una opción</option>"+
"<option value='1'>Enero</option>"+
"<option value='2'>Febrero</option>"+
"<option value='3'>Marzo</option>"+
"<option value='4'>Abril</option>"+
"<option value='5'>Mayo</option>"+
"<option value='6'>Junio</option>"+
"<option value='7'>Julio</option>"+
"<option value='8'>Agosto</option>"+
"<option value='9'>Septiembre</option>"+
"<option value='10'>Octubre</option>"+
"<option value='11'>Noviembre</option>"+
"<option value='12'>Diciembre</option>"+
"</select>"+
"</div>"+
"</div>"+
"<div class='col-sm-12 col-md-12 col-lg-12 mt-2'>"+
"<div class='form-group mb-4'>"+
"<label class='mr-sm-2' for='valor_edit_presu'>Valor</label>"+
"<input type='number' value='0' step='0.01'"+
" class='form-control custom-radius custom-shadow border-0' id='valor_edit_presu'>"+
"</div>"+
"</div> ";
document.getElementById("mes_edit_presu").value = mes;
document.getElementById("valor_edit_presu").value = valor;
$("#btn_edit_rubro_month").attr('hidden',false);
name_catego = '"'+name_catego+'"';
document.getElementById("btn_edit_rubro_month").setAttribute("onclick", "save_edit_rubro_month("+id+
","+mes+","+catego+","+name_catego+")");
}
$("#ModalRubro").modal("hide");
$("#ModalEditRubro").modal("show");
};
$("#back_rubro").click(function(){
$("#ModalEditRubro").modal("hide");
$("#ModalRubro").modal("show");
});
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
if (document.getElementById("form_presu")){
load_data_balance();
$("#next_step_1").click(function(){
var divisa = document.getElementById("divisa").value;
var ano = document.getElementById("ano").value;
if (divisa == 0 || ano == 0){
if (divisa == 0){
document.getElementById("divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
if (ano == 0){
document.getElementById("ano").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("ano").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
} else {
document.getElementById("divisa").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
document.getElementById("ano").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
getPagina("consult_cate_presu", "categoria");
document.getElementById("modo_presu").value = 0;
$("#ModalSelectCat").modal("show");
}
});
$("#back_step_1").click(function(){
change_modal(1);
});
$("#back_step_2").click(function(){
change_modal(2);
});
function change_modal(id){
if (id == 1){
$("#ModalInsertVal").modal("hide");
$("#ModalSelectCat").modal("show");
} else {
$("#ModalInsertValMensu").modal("hide");
$("#ModalSelectCat").modal("show");
}
};
function name_btn(value){
if (value){
document.getElementById("btn_save_presu_type2").innerHTML = "Finalizar";
} else {
document.getElementById("btn_save_presu_type2").innerHTML = "Siguiente";
}
};
$("#next_step_2").click(function(){
var categoria = document.getElementById("categoria").value;
var modo_presu = document.getElementById("modo_presu").value;
if (categoria == 0 || modo_presu == 0){
if (categoria == 0){
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
if (modo_presu == 0){
document.getElementById("modo_presu").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("modo_presu").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
} else {
$("#ModalSelectCat").modal("hide");
if (modo_presu != 1){
document.getElementById("valor").value = 0;
$("#ModalInsertVal").modal("show");
} else {
document.getElementById("valor_mensual").value = 0;
document.getElementById("mes_mensual").value = 1;
document.getElementById("div_replicar").style.display = "block";
$("#ModalInsertValMensu").modal("show");
}
}
});
$("#btn_save_presu_type1").click(function(){
var mes_ini = document.getElementById("mes_ini").value;
var valor = document.getElementById("valor").value;
if (mes_ini == 0 || valor == 0){
if (mes_ini == 0){
document.getElementById("mes_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("mes_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
if (valor == 0){
document.getElementById("valor").className = "form-control custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("valor").className = "form-control custom-radius custom-shadow border-0 is-valid";
}
} else {
var categoria = document.getElementById("categoria").value;
var modo_presu = document.getElementById("modo_presu").value;
var divisa = document.getElementById("divisa").value;
var ano = document.getElementById("ano").value;
document.getElementById("back_step_1").style.display = "none";
document.getElementById("btn_save_presu_type1").innerHTML ="<span class='spinner-border spinner-border-sm'"+
" role='status' aria-hidden='true'></span> Loading...";
$.ajax('../conexions/add_presupuesto?act=1', {
type: 'POST', // http method
data: { mes_ini: mes_ini,
valor: valor,
categoria: categoria,
modo_presu: modo_presu,
divisa: divisa,
ano: ano }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalInsertVal').modal('hide');
document.getElementById("back_step_1").style.display = "block";
document.getElementById("btn_save_presu_type1").innerHTML ="Finalizar";
document.getElementById("mes_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("valor").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("mes_ini").value = 0;
document.getElementById("categoria").value = 0;
document.getElementById("modo_presu").value = 0;
document.getElementById("valor").value = 0;
$("#ModalSelectCat").modal("show");
alert("Los datos se guardaron correctamente");
document.getElementById("finaly_step").style.display = "block";
} else {
alert("Error: " + data);
}
}
});
}
});
$("#btn_save_presu_type2").click(function(){
var mes_ini = document.getElementById("mes_mensual").value;
var valor = document.getElementById("valor_mensual").value;
if ( mes_ini == 1){
if (document.getElementById("replicar_val").checked){
var replicar_val = 1;
} else {
var replicar_val = 0;
}
}
if (mes_ini == 0 || valor == 0){
if (mes_ini == 0){
document.getElementById("mes_mensual").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("mes_mensual").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-valid";
}
if (valor == 0){
document.getElementById("valor_mensual").className = "form-control custom-radius custom-shadow border-0 is-invalid";
} else {
document.getElementById("valor_mensual").className = "form-control custom-radius custom-shadow border-0 is-valid";
}
} else {
document.getElementById("back_step_2").style.display = "none";
document.getElementById("btn_save_presu_type2").innerHTML ="<span class='spinner-border spinner-border-sm'"+
" role='status' aria-hidden='true'></span> Loading...";
var categoria = document.getElementById("categoria").value;
var modo_presu = document.getElementById("modo_presu").value;
var divisa = document.getElementById("divisa").value;
var ano = document.getElementById("ano").value;
$.ajax('../conexions/add_presupuesto?act=2', {
type: 'POST', // http method
data: { mes_ini: mes_ini,
valor: valor,
categoria: categoria,
replicar_val: replicar_val,
modo_presu: modo_presu,
divisa: divisa,
ano: ano }, // data to submit
success: function (data, status, xhr) {
if (data == 200) {
$('#ModalInsertVal').modal('hide');
var mes_ini = document.getElementById("mes_mensual").value;
document.getElementById("mes_mensual").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("valor_mensual").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("valor_mensual").value = 0;
if (document.getElementById("replicar_val").checked || mes_ini == 12){
document.getElementById("replicar_val").checked = false;
document.getElementById("mes_mensual").value = 0;
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("categoria").value = 0;
document.getElementById("modo_presu").value = 0;
$("#ModalInsertValMensu").modal("hide");
$("#ModalSelectCat").modal("show");
document.getElementById("btn_save_presu_type2").innerHTML = "Siguiente";
alert("Los datos se guardaron correctamente");
document.getElementById("finaly_step").style.display = "block";
} else {
document.getElementById("mes_mensual").value = ++mes_ini;
document.getElementById("replicar_val").checked = false;
document.getElementById("div_replicar").style.display = "none";
document.getElementById("back_step_2").style.display = "none";
document.getElementById("btn_save_presu_type2").innerHTML = "Siguiente";
if (mes_ini == 12){
document.getElementById("btn_save_presu_type2").innerHTML = "Finalizar";
}
}
} else {
alert("Error: " + data);
}
}
});
}
});
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
if (document.getElementById("table_move_acc")){
var idu = <?php echo $id_user; ?>;
var url = window.location.href;
var div = url.split("=");
var sub = div[1];
rellenar_table_move_acc();
getPagina("consult_title_movi?action=1&id="+sub,"title_movi");
getPagina("consult_title_movi?action=2&id="+sub,"descri_acc");
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
function rellenar_table_move_acc(){
$.ajax({
type: "GET",
url: '../json/consult?action=3&idu='+idu+'&lvl='+sub,
dataType: "json",
success: function(data){
$('#table_move_acc').DataTable( {
"columnDefs": [
{"className": "text-center", "targets": "_all"}
],
data: data,
columns: [
{ sortable: false,
"render": function ( data, type, full, meta ) {
var id= full.id;
var categoria = '"' + full.categoria + '"';
var valor = '"' + full.valor + '"';
var fecha = '"' + full.fecha + '"';
var descripcion = '"' + full.descripcion + '"';
var divisa = '"' + full.divisa + '"';
var nro_cate = full.nro_cate;
var valor_int = full.valor_int;
var id_transfer = full.id_transfe;
if (full.categoria != "Transferencia"){
return "<i class='fas fa-edit mr-3' style='color: #20c997;' onclick='edit_trans("+id+","+nro_cate+","+valor_int+","+fecha+","+descripcion+","+divisa+","+sub+")'></i>"+
"<i class='fas fa-trash-alt' style='color: red;' onclick='delete_trans("+id+","+categoria+","+valor+","+fecha+")'></i>";
} else {
return "<i class='fas fa-edit mr-3' style='color: #20c997;' onclick='edit_movi("+id+","+id_transfer+","+valor_int+","+fecha+","+descripcion+","+divisa+","+sub+")'></i>"+
"<i class='fas fa-trash-alt' style='color: red;' onclick='delete_trans("+id+","+categoria+","+valor+","+fecha+")'></i>";
}
}
},
{data: 'categoria'},
{ sortable: false,
"render": function ( data, type, full, meta ) {
var valor= full.valor;
if (valor.indexOf('-') != -1){
return "<p class='text-danger'>"+valor+"</p>";
} else {
return "<p class='text-success'>"+valor+"</p>";
}
}
},
{data: 'divisa'},
{data: 'fecha'},
{ sortable: false,
"render": function ( data, type, full, meta ) {
var valor= full.valor;
return "";
}
},
{data: 'dia'},
{data: 'mes'},
{data: 'ano'}
]
} );
},
error: function(data) {
$('#table_move_acc').DataTable( {});
}
});
};
$("#add_move_btn").click(function(){
getPagina("consult_cate", "categoria");
getPagina("consult_divisa?id="+sub, "divisa");
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
document.getElementById("fecha").value = formattedDateTime;
});
$("#monto_signal").click(function(){
var signal = document.getElementById("monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
$("#edit_monto_signal").click(function(){
var signal = document.getElementById("edit_monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
$("#trans_monto_signal").click(function(){
var signal = document.getElementById("monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
function signo(id, id2){
var nro = document.getElementById(id).value;
var signal = document.getElementById(id2);
if (nro < 0){
if (id2 != ''){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
}
document.getElementById(id).value = nro * -1;
}
};
$("#save_trans").unbind('click').click(function(){
var monto_signal = document.getElementById("monto_signal").value;
var valor = document.getElementById("valor").value;
var divisa = document.getElementById("divisa").value;
var categoria = document.getElementById("categoria").value;
var descripcion = document.getElementById("descripcion").value;
var fecha = document.getElementById("fecha").value;
if (monto_signal == '-'){
valor = valor * -1;
}
if (valor == "" || valor == 0 || divisa == "" || categoria == 0 || fecha == "") {
if (valor == "" || valor == 0){
document.getElementById("valor").className = "form-control is-invalid";
}
if (divisa == "") {
document.getElementById("divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0 is-invalid";
}
if (categoria == 0) {
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (fecha == "") {
document.getElementById("fecha").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_transaccion', {
type: 'POST',
data: {
cuenta: sub,
valor: valor,
divisa: divisa,
categoria: categoria,
descripcion: descripcion,
fecha: fecha
},
success: function (data, status, xhr) {
console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalAdd').modal('hide');
document.getElementById("valor").className = "form-control";
document.getElementById("divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0";
document.getElementById("categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("fecha").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("valor").value = "";
document.getElementById("monto_signal").value = "+";
document.getElementById("monto_signal").innerHTML = "+";
document.getElementById("divisa").value = "COP";
document.getElementById("descripcion").value = "";
document.getElementById("categoria").value = 0;
$('#table_move_acc').dataTable().fnDestroy();
rellenar_table_move_acc();
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
} else {
alert("Error: " + data);
}
}
});
}
});
function delete_trans(id, categoria, valor, fecha){
$('#ModalDelete').modal('show');
document.getElementById("text_delete").innerHTML = "Esta segur@ de eliminar la transacción <strong>"+
categoria + " </strong> por un valor de <strong>" + valor + " </strong> con fecha " + fecha;
$('#delete_trans').unbind('click').click(function(){
$.ajax({
url: '../conexions/delete_movi',
type: 'POST',
data: {id: id,
fecha: fecha },
success: function(data){
alert("Se guardaron los cambios.");
$('#ModalDelete').modal('hide');
$('#table_move_acc').dataTable().fnDestroy();
rellenar_table_move_acc();
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
},
error: function(data) {
alert("No se guardaron los cambios.");
}
});
});
};
function edit_trans(id, categoria, valor, fecha, descripcion, divisa, acco){
getPagina("consult_cate?act="+categoria, "edit_categoria");
getPagina("consult_accont?act="+acco, "edit_cuenta");
document.getElementById("edit_valor").value = valor;
document.getElementById("edit_divisa").value = divisa;
document.getElementById("edit_descripcion").value = descripcion;
var div = fecha.split(" ");
var fecha2 = div[0] + 'T' + div[1];
document.getElementById("edit_fecha").value = fecha2;
$('#ModalEdit').modal('show');
$('#edit_trans').unbind('click').click(function(){
valor = document.getElementById("edit_valor").value;
divisa = document.getElementById("edit_divisa").value;
descripcion = document.getElementById("edit_descripcion").value;
fecha = document.getElementById("edit_fecha").value;
categoria = document.getElementById("edit_categoria").value;
var cuenta = document.getElementById("edit_cuenta").value;
var signo = document.getElementById("edit_monto_signal").value;
if ( signo == '-') {
valor = valor * -1;
}
$.ajax({
url: '../conexions/edit_movi',
type: 'POST',
data: {
id: id,
valor: valor,
divisa: divisa,
descripcion: descripcion,
fecha: fecha,
categoria: categoria,
cuenta: cuenta
},
success: function(data){
alert("Se guardaron los cambios.");
$('#ModalEdit').modal('hide');
$('#table_move_acc').dataTable().fnDestroy();
rellenar_table_move_acc();
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
},
error: function(data) {
alert("No se guardaron los cambios.");
}
});
});
};
function edit_movi(id, id_transfer, valor, fecha, descripcion, divisa, acco){
if (valor < 0){
getPagina("consult_accont?act="+acco, "Edit_trans_cuenta_ini");
getPagina("consult_accont?act="+id_transfer, "Edit_trans_cuenta_fin");
} else {
getPagina("consult_accont?act="+acco, "Edit_trans_cuenta_fin");
getPagina("consult_accont?act="+id_transfer, "Edit_trans_cuenta_ini");
}
if (valor < 0){
document.getElementById("Edit_trans_valor").value = valor * -1;
} else {
document.getElementById("Edit_trans_valor").value = valor;
}
document.getElementById("Edit_trans_divisa").value = divisa;
document.getElementById("Edit_trans_descripcion").value = descripcion;
var div = fecha.split(" ");
var fecha2 = div[0] + 'T' + div[1];
document.getElementById("Edit_trans_fecha").value = fecha2;
$('#ModalTransEdit').modal('show');
$('#Edit_trans_trans').unbind('click').click(function(){
valor = document.getElementById("Edit_trans_valor").value;
divisa = document.getElementById("Edit_trans_divisa").value;
descripcion = document.getElementById("Edit_trans_descripcion").value;
fecha = document.getElementById("Edit_trans_fecha").value;
cuenta_ini = document.getElementById("Edit_trans_cuenta_ini").value;
var cuenta_fin = document.getElementById("Edit_trans_cuenta_fin").value;
$.ajax({
url: '../conexions/edit_trans_acco',
type: 'POST',
data: {
id: id,
valor: valor,
divisa: divisa,
descripcion: descripcion,
fecha: fecha,
cuenta_fin: cuenta_fin,
cuenta_ini: cuenta_ini
},
success: function(data){
if (data == 400) {
alert ("Los datos no se guardaron correctamente.");
}
$('#ModalTransEdit').modal('hide');
$('#table_move_acc').dataTable().fnDestroy();
rellenar_table_move_acc();
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
}
});
});
};
$('#add_trans_btn').click(function(){
getPagina("consult_accont", "trans_cuenta_ini");
getPagina("consult_accont", "trans_cuenta_fin");
getPagina("consult_divisa?id="+sub, "trans_divisa");
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
document.getElementById("trans_fecha").value = formattedDateTime;
});
$("trans_monto_signal").click(function(){
var signal = document.getElementById("dash_trans_monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
$("#trans_trans").unbind('click').click(function(){
var monto_signal = document.getElementById("trans_monto_signal").value;
var valor = document.getElementById("trans_valor").value;
var cuenta_ini = document.getElementById("trans_cuenta_ini").value;
var divisa = document.getElementById("trans_divisa").value;
var cuenta_fin = document.getElementById("trans_cuenta_fin").value;
var descripcion = document.getElementById("trans_descripcion").value;
var fecha = document.getElementById("trans_fecha").value;
if (monto_signal == '-'){
valor = valor * -1;
}
if (valor == "" || valor == 0 || divisa == "" || cuenta_ini == 0 || cuenta_fin == 0 || fecha == "") {
if (valor == "" || valor == 0){
document.getElementById("trans_valor").className = "form-control is-invalid";
}
if (divisa == "") {
document.getElementById("trans_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0 is-invalid";
}
if (cuenta_fin == 0) {
document.getElementById("trans_cuenta_fin").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (cuenta_ini == 0) {
document.getElementById("trans_cuenta_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (fecha == "") {
document.getElementById("trans_fecha").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_movi_cuenta', {
type: 'POST',
data: {
cuenta_ini: cuenta_ini,
valor: valor,
divisa: divisa,
cuenta_fin: cuenta_fin,
descripcion: descripcion,
fecha: fecha
},
success: function (data, status, xhr) {
console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalTransDash').modal('hide');
document.getElementById("trans_valor").className = "form-control";
document.getElementById("trans_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0";
document.getElementById("trans_cuenta_fin").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("trans_cuenta_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("trans_fecha").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("trans_valor").value = "";
document.getElementById("trans_monto_signal").value = "+";
document.getElementById("trans_monto_signal").innerHTML = "+";
document.getElementById("trans_divisa").value = "COP";
document.getElementById("trans_descripcion").value = "";
document.getElementById("trans_cuenta_ini").value = 0;
document.getElementById("trans_cuenta_fin").value = 0;
$('#table_move_acc').dataTable().fnDestroy();
rellenar_table_move_acc();
getPagina("consult_title_movi?action=3&id="+sub,"balance_acc");
load_data_balance();
} else {
alert("Error: " + data);
}
}
});
}
});
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
if (document.getElementById("body_profile")){
var idu = <?php echo $id_user; ?>;
load_data_balance();
PostProfile("consult_profile?action=1", 1);
PostProfile("consult_profile?action=2", 2);
PostProfile("consult_profile?action=3", 3);
PostProfile("consult_profile?action=4", 4);
function PostProfile(strURLop, action) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURLop, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
UpdatePage(xmlHttp.responseText, action);
}
}
xmlHttp.send(strURLop);
}
function UpdatePage(str, action){
if (action == 1){
document.getElementById("name_profile").value = str ;
}else if (action == 2){
document.getElementById("last_name_profile").value = str ;
}else if (action == 3){
document.getElementById("email_profile").value = str ;
}else if (action == 4){
document.getElementById("divisa").value = str ;
}
}
$("#save_profile").click(function(){
var fd = new FormData();
var name = document.getElementById("name_profile").value;
var last_name = document.getElementById("last_name_profile").value;
var passw1 = document.getElementById("pass_1").value;
var passw2 = document.getElementById("pass_2").value;
var divisa = document.getElementById("divisa").value;
var files = document.getElementById('photo_profile').files[0];
fd.append('file',files);
fd.append('name',name);
fd.append('last_name',last_name);
fd.append('divisa',divisa);
fd.append('passw',passw2);
if (name == "" || passw1 != passw2 || (passw1.length < 6 && passw1.length >0)) {
if (name == ""){
document.getElementById("name_profile").className = "form-control is-invalid";
}
if (passw1 != passw2){
document.getElementById("pass_2").className = "form-control is-invalid";
}
if (passw1.length < 6 && passw1.length >0){
document.getElementById("pass_1").className = "form-control is-invalid";
}
} else {
$.ajax({
url: '../conexions/edit_profile',
type: 'POST',
data: fd,
contentType: false,
cache: false,
processData: false,
success: function (data, status, xhr) {
console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
document.getElementById("pass_1").value = "";
document.getElementById("pass_2").value = "";
alert("Los datos se guardaron correctamente");
} else {
alert("Error: " + data);
}
}
});
}
});
function val_pass_1() {
var pass = document.getElementById("pass_1").value;
if (pass.length < 6) {
document.getElementById("pass_1").className = "form-control is-invalid";
} else {
document.getElementById("pass_1").className = "form-control is-valid";
}
};
function val_pass_2() {
var pass2 = document.getElementById("pass_2").value;
var pass1 = document.getElementById("pass_1").value;
if (pass1 != pass2) {
document.getElementById("pass_2").className = "form-control is-invalid";
} else {
document.getElementById("pass_2").className = "form-control is-valid";
}
};
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
};
function getPagina(strURLop, div) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURLop, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
UpdatePagina(xmlHttp.responseText, div);
}
}
xmlHttp.send(strURLop);
};
function UpdatePagina(str, div){
document.getElementById(div).innerHTML = str ;
};
$('#screen_android').click(function(){
$("#ModalScreen").modal("hide");
$("#ModalScreenAndroid").modal("show");
});
$('#screen_iphone').click(function(){
$("#ModalScreen").modal("hide");
$("#ModalScreenIOS").modal("show");
});
function val_session(idu){
if(idu == ""){
window.location = "/";
}
};
function load_data_balance(){
$.ajax({
type: "GET",
url: '../json/consult?action=4&idu='+idu,
dataType: "json",
success: function(data){
document.getElementById("balance").innerHTML = "";
$("#balance").append("<a class='dropdown-item' href='/pages/profile'><i "+
" class='fas fa-user mr-2 ml-1'></i>"+
"My Profile</a>"
);
$.each(data,function(key, registro) {
var utilidad_bal = registro.utilidad_bal;
$("#balance").append("<a class='dropdown-item row' style ='margin: 0px;'>"+
"<i class='fas fa-credit-card mr-2 ml-1'></i>"+
"Balance <p class='float-right'>" + utilidad_bal + " "+ registro.divisa +"</p>"+
"</a>"
);
});
$("#balance").append("<a class='dropdown-item' onclick='screen_home()'><i "+
" class='fas fa-plus-square mr-2 ml-1'></i>"+
"Add to home screen</a>"
);
$("#balance").append("<div class='dropdown-divider'></div>"+
"<a class='dropdown-item' href='/'><i "+
" class='fas fa-power-off mr-2 ml-1'></i>"+
"Logout</a>"
);
}
});
};
function notificar(titulo, contenido){
if(Notification.permission != "granted"){
Notification.requestPermission();
}else{
var notification = new Notification(titulo,
{
icon: "http://fiona.byethost11.com/assets/images/logo-icon.png",
body: contenido
}
);
}
}
function show_mensaje(id){
$.ajax({
type: "GET",
url: '../json/consult?action=8&idu='+idu+'&id='+id,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
document.getElementById("ModalMensaLbl").innerHTML = registro.titulo;
document.getElementById("catego_mensaje").innerHTML = registro.tipo;
document.getElementById("fecha_mensaje").innerHTML = registro.fecha;
document.getElementById("contenido_mensaje").innerHTML = registro.Contenido;
});
}
});
$("#ModalMensajes").modal("show");
$.ajax('../conexions/read_mensaje', {
type: 'POST',
data: {
id: id
},
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
}
});
}
function count_message(){
//console.log("antes: " + nro_mesajes);
nro_ant_mes = nro_mesajes;
getPagina("consult_nro_message", "nro_message");
nro_mesajes = document.getElementById("nro_message").innerHTML;
//console.log("despues: " + nro_mesajes);
if (nro_ant_mes < nro_mesajes && nro_ant_mes != ""){
notificar('FIONA Notificacion', "Tienes un nuevo mensaje de fiona!");
getPagina("consult_mensajes", "list_mensajes");
}
else if (nro_mesajes < nro_ant_mes){
getPagina("consult_mensajes", "list_mensajes");
}
};
setInterval("count_message()", 5000);<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$id = $_POST["id"];
$insert = "UPDATE fionadb.notification
SET leido=1
WHERE id=$id and id_user='$id_user';
";
$save = mysqli_query($conn, $insert);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
$name = $_GET["name"];
$days = $_GET["days"];
$email = $_GET["email"];
$contenido_mess = "<table class='MsoTableGrid' border='0' cellspacing='0' cellpadding=
'0' style='border-collapse:collapse;border:none'>
<tbody>
<tr style='height:168.5pt'>
<td width='279' valign='bottom' style='width:208.9pt;padding:0cm 5.4p
t 0cm 5.4pt;height:168.5pt'>
<p class='MsoNormal' align='center' style='text-align:center'><span s
tyle='font-size:12.0pt;font-family:"Arial Rounded MT Bold",sans
-serif'><img data-imagetype='External' src='http://3.15.191.4/extras/fiona_neutral.svg'
/></span><span style='font-size:12.0pt;font-family:"Arial Rounded MT
Bold",sans-serif'><o:p></o:p></span></p>
</td>
<td width='279' style='width:208.9pt;padding:0cm 5.4pt 0cm 5.4pt;height=
:168.5pt'>
<p class='MsoNormal' align='center' style='text-align:center'><span s
tyle='font-size:12.0pt;font-family:"Arial Rounded MT Bold",sans
-serif'><o:p> </o:p></span></p>
<p class='MsoNormal' align='center' style='text-align:center'><span s
tyle='font-size:12.0pt;font-family:"Arial Rounded MT Bold",sans
-serif'>Hola <strong>$name</strong>, llevas <strong>$days días</strong> sin registrar ningún movimiento,
recuerda estar al día en tus reportes para darte las mejores
sugerencias!<o:p></o:p></span></p>
<p class='MsoNormal'><span style='font-size:12.0pt;font-family:"Ar
ial Rounded MT Bold",sans-serif'>Saca 5 minutos diarios para ingresar
en que te has gastado el dinero o en que haz generado dinero<o:p></o:p></sp
an></p>
</td>
</tr>
</tbody>
</table>";
include("../Mailer/php/envioCorreo.php");
$emailt = new email();
$emailt->agregar($email,"");
if ($emailt->enviar('FIONA, Recodatorio',$contenido_html)){
echo 200;
} else {
echo 400;
}
?><file_sep><?php
include_once("connect.php");
$email = $_POST["email"];
$select = "SELECT * FROM fionadb.users WHERE email=BINARY'$email'";
$eject = mysqli_query($conn, $select);
if(empty(mysqli_fetch_array($eject))){
echo 500;
} else {
$new_pas=generateRandomString(8);
$hash = Password::hash($new_pas);
$consetiket="Contrsaseña: $new_pas";
$contenido_mess="Esta es tu nueva contraseña, por favor una vez que ingrese
a la plataforma cambie su contraseña.<br>";
include("../Mailer/php/envioCorreo.php");
$emailt = new email();
$emailt->agregar($email,"");
if ($emailt->enviar('FIONA, Recuperación de contraseña',$contenido_html)){
$change_pass="UPDATE fionadb.users SET password='<PASSWORD>' WHERE email=BINARY'$email'";
$save = mysqli_query($conn,$change_pass);
echo 200;
}else{
$mensaje= 'El mensaje no se pudo enviar';
$emailt->ErrorInfo;
echo $emailt->ErrorInfo;
}
}
mysqli_close($conn);
//Método con str_shuffle()
function generateRandomString($length) {
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}
?><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Dashboard</title>
<!-- Custom CSS -->
<link href="../assets/extra-libs/c3/c3.min.css" rel="stylesheet">
<link href="../assets/libs/chartist/dist/chartist.min.css" rel="stylesheet">
<link href="../assets/extra-libs/jvector/jquery-jvectormap-2.0.2.css" rel="stylesheet" />
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<link rel="manifest" href="../manifest.json">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full"
data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-sm-12 col-md-10 align-self-center">
<h3 class="page-title text-truncate text-dark font-weight-medium mb-1">
<?php echo "Bienvenid@ $name $last_name"; ?>
</h3>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="#">Dashboard</a>
</li>
</ol>
</nav>
</div>
</div>
<div class="col-md-2 align-self-center">
<div class="customize-input float-right">
<select id="select_divisa" onchange= "load_card(this.value)"
class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
</select>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb mb-3">
<button type="button"
class="btn waves-effect waves-light btn-rounded float-right btn-success mb-2"
data-target="#ModalTransDash" id="add_trans_btn" data-toggle="modal">
<i class="fas fa-exchange-alt mr-2"></i>Transferencia
</button>
<button type="button"
class="btn waves-effect waves-light btn-rounded float-right btn-primary mr-1 mb-2"
data-target="#ModalAddDash" id="add_move_btn" data-toggle="modal">
<i class="fas fa-plus mr-2"></i>Movimiento
</button>
</div>
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- *************************************************************** -->
<!-- Start First Cards -->
<!-- *************************************************************** -->
<div class="card-group">
<div onclick="showactivity(1)" class="card border-right col-sm-12">
<div class="card-body">
<div class="d-flex d-lg-flex d-md-block align-items-center">
<div>
<div id="lbl_ingreso" class="d-inline-flex align-items-center">
</div>
<h6 class="text-muted font-weight-normal mb-0 w-100 text-truncate">Ingresos</h6>
</div>
</div>
</div>
</div>
<div onclick="showactivity(2)" class="card border-right">
<div class="card-body">
<div class="d-flex d-lg-flex d-md-block align-items-center">
<div>
<div id="lbl_egreso" class="d-inline-flex align-items-center">
</div>
<h6 class="text-muted font-weight-normal mb-0 w-100 text-truncate">Egresos</h6>
</div>
</div>
</div>
</div>
<div class="card border-right">
<div class="card-body">
<div class="d-flex d-lg-flex d-md-block align-items-center">
<div>
<div id="lbl_ahorros" class="d-inline-flex align-items-center">
</div>
<h6 class="text-muted font-weight-normal mb-0 w-100 text-truncate">Ahorros</h6>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="d-flex d-lg-flex d-md-block align-items-center">
<div>
<div id="lbl_utilidad" class="d-inline-flex align-items-center">
</div>
<h6 class="text-muted font-weight-normal mb-0 w-100 text-truncate">Utilidad</h6>
</div>
</div>
</div>
</div>
</div>
<!-- *************************************************************** -->
<!-- End First Cards -->
<!-- *************************************************************** -->
<!-- *************************************************************** -->
<!-- Start Sales Charts Section -->
<!-- *************************************************************** -->
<div class="row">
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Ingresos
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico ingresos" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus ingresos, toca cualquier color
para saber que categoria es con su porcentaje de participacion. Ej:
La categoria Salario tiene un 90%, lo que significa, que el 90% de mis
ingresos corresponde por Salario">
</i>
</h4>
<div id="campaign-v2" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Egresos
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico egresos" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus egresos, toca cualquier color
para saber que categoria es con su porcentaje de participacion. Ej:
La categoria Arriendo tiene un 50%, lo que significa, que la mitad de mis
ingresos es destinado a pagar el arriendo.">
</i>
</h4>
<div id="campaign-v3" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Ahorros
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico ahorros" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus ahorros, toca cualquier color
para saber que cuenta es con su porcentaje de participacion. Ej:
La cuenta CDT tiene un 50%, lo que significa, que la mitad de mis
ahorros se encuentran en el CDT.">
</i>
</h4>
<div id="campaign-v4" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
</div>
<!-- *************************************************************** -->
<!-- End Sales Charts Section -->
<!-- *************************************************************** -->
<!-- *************************************************************** -->
<!-- Start Location and Earnings Charts Section -->
<!-- *************************************************************** -->
<div class="row">
<div class="col-md-6 col-lg-8">
<div class="card">
<div id="movimientos-diarios" class="card-body">
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">Actividades Recientes</h4>
<div id="activity_current" class="mt-4 activity">
</div>
</div>
</div>
</div>
</div>
<!-- *************************************************************** -->
<!-- End Location and Earnings Charts Section -->
<!-- *************************************************************** -->
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalAddDash" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Ingreso de transacción</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="dash_monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('dash_valor', 'dash_monto_signal')" class="form-control" id="dash_valor">
</div>
<div class="col-md-3">
<select id="dash_divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>COP</option>
<option >USD</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_cuenta">Seleciona una cuenta</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="dash_cuenta">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_categoria">Seleciona una categoria</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="dash_categoria">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_descripcion">Descripción</label>
<textarea class="form-control" id="dash_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_fecha">Fecha</label>
<input type="datetime-local"
class="form-control custom-radius custom-shadow border-0" id="dash_fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="dash_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalTransDash" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Transferencias</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="input-group">
<div class="col-md-2">
<small class="text-dark">Monto</small>
</div>
<div class="input-group-prepend">
<button class="btn btn-outline-success" id="dash_trans_monto_signal" value="+" type="button">+</button>
</div>
<div class="custom-file">
<input type="number" step="0.02" min="0" onchange="signo('dash_trans_valor', 'dash_trans_monto_signal')" class="form-control" id="dash_trans_valor">
</div>
<div class="col-md-3">
<select id="dash_trans_divisa"
class="custom-select form-control bg-white custom-radius custom-shadow border-0">
<option selected>COP</option>
<option >USD</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_trans_cuenta_ini">Seleciona una cuenta de salida</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="dash_trans_cuenta_ini">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_trans_cuenta_fin">Seleciona una cuenta de entrada</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="dash_trans_cuenta_fin">
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_trans_descripcion">Descripción</label>
<textarea class="form-control" id="dash_trans_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="dash_trans_fecha">Fecha</label>
<input type="datetime-local"
class="form-control custom-radius custom-shadow border-0" id="dash_trans_fecha">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="dash_trans_trans" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalWelcome" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Bienvenido</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><?php echo "Bienvenid@ <strong>$name $last_name</strong>"; ?> a la App <strong>Fiona</strong>,
tu asistente financiero. Antes de comenzar te daremos una breve explicación de como utilizarla:
</p>
<li>
<button type="button" class="btn waves-effect waves-light btn-rounded btn-primary">
<i class="fas fa-plus mr-2"></i>Movimiento</button> Este boton es utilizado
para ingresar salidas o entradas de dinero.<br>
<strong>Ej:</strong> la cantidad de dinero que recibes por tu salario.
</li>
<li><button type="button" class="btn waves-effect waves-light btn-rounded btn-success">
<i class="fas fa-exchange-alt mr-2"></i>Transferencia</button> Este boton es ultilizado cuando requieres
pasar una suma de dinero de una cuenta a otra.<br>
<strong>Ej:</strong> Pasar 50.000 COP de mi cuenta de ahorros a mi cuenta CDT.</li>
<li><i class="fas fa-info-circle" data-container="body" style="color: #01caf1;"></i>
Cuando encuentres este icono podrás darle clic para mas información.
</li>
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" class="btn waves-effect waves-light btn-rounded btn-primary"
data-toggle="modal" data-target="#ModalCategoInfo" data-dismiss="modal">Siguiente</button>
</div>
</div>
</div>
</div>
<div id="ModalCategoInfo" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configuración Inicial I</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Categorías:</strong></p>
<p>Deberas de crear las categorías para identificar los gastos o ingresos mas frecuentes.</p>
<p>Para eso darás clic en categorías en la barra de navegación ubicada al lado izquierdo
de la pagina o <i class="fas fa-bars"></i> ubicado en la parte superior lado izquierdo.</p>
<p><strong>Ej: </strong> Si posees gastos que provenga de un vehiculo puedes crear una
categoria llamada vehiculo.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<a href="categorias">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-primary">Siguiente</button>
</a>
</div>
</div>
</div>
</div>
<div id="ModalActivity" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Actividades por cuenta</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="bodyActivity" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalActivityLvl" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Movimientos por mes</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="bodyActivityLvl" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
id="btn_back_lvl">Atras</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalActivityMonth" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Movimientos diarios</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="bodyActivityMonth" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
id="btn_back_moth">Atras</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../dist/js/custom.min.js"></script>
<!--This page JavaScript -->
<script src="../assets/extra-libs/c3/d3.min.js"></script>
<script src="../assets/extra-libs/c3/c3.min.js"></script>
<script src="../assets/libs/chartist/dist/chartist.min.js"></script>
<script src="../assets/libs/chartist-plugin-tooltips/dist/chartist-plugin-tooltip.min.js"></script>
<script src="../assets/extra-libs/jvector/jquery-jvectormap-2.0.2.min.js"></script>
<script src="../assets/extra-libs/jvector/jquery-jvectormap-world-mill-en.js"></script>
<script src="../assets/libs/chart.js/dist/Chart.min.js"></script>
<script src="../java/dashboard.php"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Perfil</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-7 align-self-center">
<h4 class="page-title text-truncate text-dark font-weight-medium mb-1">Perfil</h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Perfil</li>
</ol>
</nav>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div id="body_profile" class="card-body">
<div class="row mb-2">
<label for="name_profile"
class="col-sm-2 col-form-label">Nombres</label>
<div class="col-sm-10">
<input type="text" class="form-control"
id="name_profile" placeholder="Alejandro">
</div>
</div>
<div class="row mb-2">
<label for="last_name_profile"
class="col-sm-2 col-form-label">Apellidos</label>
<div class="col-sm-10">
<input type="text" class="form-control"
id="last_name_profile" placeholder="<NAME>">
</div>
</div>
<div class="row mb-2">
<label for="email_profile"
class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control"
id="email_profile" readonly placeholder="<EMAIL>">
</div>
</div>
<div class="row mb-2">
<label for="divisa"
class="col-sm-2 col-form-label">Divisa por defecto</label>
<div class="col-sm-10">
<select class="custom-select mr-sm-2 mt-2 custom-radius
text-dark custom-shadow border-0" id="divisa">
<option value="COP">COP</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="GBD">GBD</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option>
<option value="MXN">MXN</option>
<option value="ILS">ILS</option>
</select>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="row mb-2">
<label for="photo_profile"
class="col-sm-2 col-form-label">Foto de perfil</label>
<div class="input-group mb-3 col-sm-10">
<div class="custom-file">
<input type="file" class="custom-file-input" id="photo_profile">
<label class="custom-file-label" for="photo_profile">Subir foto</label>
</div>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="row mb-2">
<label for="pass_1"
class="col-sm-2 col-form-label">Contraseña</label>
<div class="col-sm-10">
<input type="password" onkeyup="val_pass_1()" class="form-control"
id="pass_1" placeholder="">
</div>
</div>
<div class="row mb-2">
<label for="pass_2"
class="col-sm-2 col-form-label">Repetir contraseña</label>
<div class="col-sm-10">
<input type="password" onkeyup="val_pass_2()" class="form-control mt-2"
id="pass_2" placeholder="">
</div>
</div>
<button type="button" id="save_profile"
class="btn waves-effect waves-light btn-rounded btn-primary float-right"><i class="fas fa-save mr-2"></i>Guardar</button>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../java/functions.php"></script>
<script src="../dist/js/custom.min.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Reportes</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../assets/extra-libs/c3/c3.min.css" rel="stylesheet">
<link href="../assets/libs/chartist/dist/chartist.min.css" rel="stylesheet">
<link href="../assets/extra-libs/jvector/jquery-jvectormap-2.0.2.css" rel="stylesheet" />
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-sm-12 col-md-10 align-self-center">
<h4 class="page-title text-truncate text-dark font-weight-medium mb-1">REPORTES FINANCIEROS</h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Reportes</li>
</ol>
</nav>
</div>
</div>
<div class="col-md-2 align-self-center">
<div class="customize-input float-right">
<select id="select_divisa" onchange= "view_chart(this.value)"
class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
</select>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid p-3">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="row">
<div class="form-group mb-4 col-sm-12 col-md-5">
<label class="mr-sm-2" for="fecha_ini">Fecha inicial</label>
<input type="date" class="form-control custom-radius custom-shadow border-0"
id="fecha_ini">
</div>
<div class="form-group mb-4 col-sm-12 col-md-5">
<label class="mr-sm-2" for="fecha_fin">Fecha final</label>
<input type="date" class="form-control custom-radius custom-shadow border-0"
id="fecha_fin">
</div>
<div class="col-sm-12 col-md-2 mt-3">
<button type="button" id="search_report"
class="btn btn-primary">Buscar</button>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Ingresos
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico ingresos" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus ingresos, toca cualquier color
para saber que categoria es con su porcentaje de participacion. Ej:
La categoria Salario tiene un 90%, lo que significa, que el 90% de mis
ingresos corresponde por Salario">
</i>
</h4>
<div id="campaign-v2" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Egresos
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico egresos" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus egresos, toca cualquier color
para saber que categoria es con su porcentaje de participacion. Ej:
La categoria Arriendo tiene un 50%, lo que significa, que la mitad de mis
ingresos es destinado a pagar el arriendo.">
</i>
</h4>
<div id="campaign-v3" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
<div class="col-lg-4 col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Total Ahorros
<i class="fas fa-info-circle ml-1" data-container="body" style="color: #01caf1;"
title="Grafico ahorros" data-toggle="popover" data-placement="top"
data-content="Mira como se destribuye tus ahorros, toca cualquier color
para saber que cuenta es con su porcentaje de participacion. Ej:
La cuenta CDT tiene un 50%, lo que significa, que la mitad de mis
ahorros se encuentran en el CDT.">
</i>
</h4>
<div id="campaign-v4" class="mt-2" style="height:283px; width:100%;"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-4">
<div class="card border-button boder">
<div class="card-body" style="padding: 15px;">
<h4 class="card-title">Resumen por cuenta</h4>
<div id="resumen" class="mt-4 overflow-auto" style="max-height: 150px;">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-4">
<div class="card border-button boder">
<div class="card-body" style="padding: 15px;">
<h4 class="card-title">TOP 10 de gastos</h4>
<div id="top_10" class="overflow-auto" style="max-height: 150px;">
</div>
</div>
</div>
</div>
<div class="col-md-12 col-lg-4">
<div class="card border-button boder">
<div class="card-body" style="padding: 15px;">
<h4 class="card-title">Presupuesto</h4>
<div id="cumplimiento" class="mt-4 overflow-auto" style="max-height: 150px;">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalActivityAccount" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="ModalActiAccLbl" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ModalActiAccLbl"></h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="bodyActivity" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../dist/js/custom.min.js"></script>
<!--This page JavaScript -->
<script src="../assets/extra-libs/c3/d3.min.js"></script>
<script src="../assets/extra-libs/c3/c3.min.js"></script>
<script src="../assets/libs/chartist/dist/chartist.min.js"></script>
<script src="../assets/libs/chartist-plugin-tooltips/dist/chartist-plugin-tooltip.min.js"></script>
<script src="../assets/extra-libs/jvector/jquery-jvectormap-2.0.2.min.js"></script>
<script src="../assets/extra-libs/jvector/jquery-jvectormap-world-mill-en.js"></script>
<script src="../assets/libs/chart.js/dist/Chart.min.js"></script>
<!--Custom JavaScript -->
<script src="../java/reportes.php"></script>
</body>
</html><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$nombre = $_POST["nombre"];
$descripcion = $_POST["descripcion"];
$divisa = $_POST["divisa"];
$monto_ini = $_POST["monto_ini"];
$acco_save = $_POST["acco_save"];
$insert = "INSERT INTO fionadb.cuentas
(nombre, descripcion, Divisa, monto_inicial, cuenta_ahorro, id_user)
VALUES('$nombre', '$descripcion', '$divisa', $monto_ini, $acco_save, '$id_user');
";
$save = mysqli_query($conn, $insert);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$select = $_GET["select"];
$insert = "SELECT DISTINCT(divisa) FROM fionadb.cuentas WHERE id_user='$id_user'";
$ejecutar =mysqli_query($conn,$insert);
while ($lista = mysqli_fetch_array($ejecutar)){
$divisa = $lista ["divisa"];
if ($select == $divisa){
echo "<option selected value='$divisa'>$divisa</option>";
} else {
echo "<option value='$divisa'>$divisa</option>";
}
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$id = $_GET["id"];
$insert = "SELECT * FROM fionadb.cuentas WHERE id_user='$id_user' and id='$id'";
$ejecutar =mysqli_query( $conn,$insert);
while ($lista = mysqli_fetch_array($ejecutar)){
$divisa = $lista ["Divisa"];
echo "<option value='$divisa'>$divisa</option>";
}
mysqli_close($conn);
?><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("connect.php");
$mes = $_POST["mes"];
$id = $_POST["id"];
$valor = $_POST["valor"];
$update = "UPDATE fionadb.presupuesto
SET valor=$valor WHERE id=$id and id_user='$id_user';";
$save = mysqli_query($conn, $update);
if(!$save){
echo 400;
} else {
echo 200;
}
mysqli_close($conn);
?><file_sep>$("#signin").click(function(){
log_in();
});
if (document.getElementById("pwd")){
var input = document.getElementById("pwd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
log_in();
}
});
};
function log_in(){
var user = document.getElementById("uname").value;
var passwd = document.getElementById("pwd").value;
$.ajax('conexions/validar', {
type: 'POST', // http method
data: { user: user,
passwd: passwd }, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
window.location="/pages/dashboard";
} else if (data == 400) {
document.getElementById("uname").className = "form-control is-invalid";
document.getElementById("mensaje").innerHTML = "<div class='alert alert-danger' role='alert'>" +
"El usuario no existe!</div>";
} else if (data == 450) {
document.getElementById("uname").className = "form-control is-invalid";
document.getElementById("pwd").className = "form-control is-invalid";
document.getElementById("mensaje").innerHTML = "<div class='alert alert-danger' role='alert'>" +
"Usuario o contraseña incorrecta!</div>";
} else if (data == 100) {
alert ("Problemas al conectar con el servidor");
}
}
});
};
function lowerCase(id) {
var x=document.getElementById(id).value
document.getElementById(id).value=x.toLowerCase().trim();
};
$("#btn_signup").click(function(){
sign_up();
});
function sign_up(){
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("email").value.trim();
var pass = document.getElementById("pass").value;
emailRegex = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i;
if (email == "" || !emailRegex.test(email) || name == "" || pass == "" || pass.length < 6){
if (!emailRegex.test(email) || email == ""){
document.getElementById("email").className = "form-control is-invalid";
}
if (name == ""){
document.getElementById("name").className = "form-control is-invalid";
}
if (pass == "" || pass.length < 6){
document.getElementById("pass").className = "form-control is-invalid";
}
} else {
$.ajax('conexions/registrar', {
type: 'POST', // http method
data: { name: name,
lastname: lastname,
email: email,
pass: pass}, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
window.location="/";
} else {
alert("Error: No se pudo registrar correctamente!. (" +
data + ")");
}
}
});
}
};
$("#btn_forgot").click(function(){
forgot_pass();
});
function forgot_pass(){
var email = document.getElementById("email").value.trim();
emailRegex = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i;
if (email == "" || !emailRegex.test(email)){
if (!emailRegex.test(email) || email == ""){
document.getElementById("email").className = "form-control is-invalid";
}
} else {
$.ajax('conexions/forgot', {
type: 'POST', // http method
data: {
email: email}, // data to submit
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
window.location="/";
} else {
alert("Error: No se pudo registrar correctamente!. (" +
data + ")");
}
}
});
}
};
$("#see").click(function(){
See_pass();
});
function See_pass(){
if(document.getElementById("pwd").type == "text"){
document.getElementById("pwd").type = "<PASSWORD>";
document.getElementById("see").className = "fas fa-eye-slash mt-2 ml-3";
} else {
document.getElementById("pwd").type = "text";
document.getElementById("see").className = "fas fa-eye mt-2 ml-3";
}
}<file_sep><?php
session_start();
$id_user = "\"".$_SESSION["Id_user"]."\"";
$divisa_primary = "\"".$_SESSION["divisa"]."\"";
?>
load_data(1);
var idu = <?php echo $id_user;?>;
val_session(idu);
val_new_user(idu);
var nro_mesajes = document.getElementById("nro_message").innerHTML;
var nro_ant_mes = 0;
function getPagina(strURLop, div) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURLop, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
UpdatePage(xmlHttp.responseText, div);
}
}
xmlHttp.send(strURLop);
};
function UpdatePage(str, div){
document.getElementById(div).innerHTML = str ;
};
function load_data(reload){ // 1 to reload divisas and 0 to not reaload
var idu = <?php echo $id_user;?>;
document.getElementById("balance").innerHTML = "";
if (reload == 1){
var divisa_primary = <?php echo $divisa_primary;?>;
document.getElementById("select_divisa").innerHTML = "";
} else {
var divisa_primary = document.getElementById("select_divisa").value;
}
$.ajax({
type: "GET",
url: '../json/consult?action=4&idu='+idu,
dataType: "json",
success: function(data){
document.getElementById("balance").innerHTML = "";
$("#balance").append("<a class='dropdown-item' href='/pages/profile'><i "+
" class='fas fa-user mr-2 ml-1'></i>"+
"My Profile</a>"
);
$.each(data,function(key, registro) {
var utilidad_bal = registro.utilidad_bal;
$("#balance").append("<a class='dropdown-item row' style ='margin: 0px;'>"+
"<i class='fas fa-credit-card mr-2 ml-1'></i>"+
"Balance <p class='float-right'>" + utilidad_bal + " "+ registro.divisa +"</p>"+
"</a>"
);
if (reload == 1){
if (divisa_primary == registro.divisa){
$('#select_divisa').append("<option selected value='"+registro.divisa+"'>"+registro.divisa+"</option>");
} else {
$('#select_divisa').append("<option value='"+registro.divisa+"'>"+registro.divisa+"</option>");
}
}
});
$("#balance").append("<a class='dropdown-item' onclick='screen_home()'><i "+
" class='fas fa-plus-square mr-2 ml-1'></i>"+
"Add to home screen</a>"
);
$("#balance").append("<div class='dropdown-divider'></div>"+
"<a class='dropdown-item' href='/'><i "+
" class='fas fa-power-off mr-2 ml-1'></i>"+
"Logout</a>"
);
}
});
getPagina("consult_nro_message", "nro_message");
getPagina("consult_mensajes", "list_mensajes");
load_card(divisa_primary);
};
function load_card(divisa_primary){
var idu = <?php echo $id_user;?>;
document.getElementById("lbl_ingreso").innerHTML = "";
document.getElementById("lbl_egreso").innerHTML = "";
document.getElementById("lbl_utilidad").innerHTML = "";
document.getElementById("lbl_ahorros").innerHTML = "";
$.ajax({
type: "GET",
url: '../json/consult?action=5&idu='+idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var ingreso = registro.ingreso;
var egreso = registro.Egresos;
var utilidad = registro.utilidad;
if (!ingreso) {
ingreso = 0.00;
}
if (!egreso) {
egreso = 0.00;
}
if (!utilidad) {
utilidad = 0.00;
}
$("#lbl_ingreso").append("<h3 class='text-dark mb-1 font-weight-medium'><sup " +
"class='set-doller'>$</sup>"+ingreso+"</h3>");
$("#lbl_egreso").append("<h3 class='text-dark mb-1 font-weight-medium'><sup " +
"class='set-doller'>$</sup>"+egreso+"</h3>");
$("#lbl_utilidad").append("<h3 class='text-dark mb-1 font-weight-medium'><sup " +
"class='set-doller'>$</sup>"+utilidad+"</h3>");
});
},
error: function(data) {
$("#lbl_ingreso").append("<h3 class='text-dark mb-1 font-weight-medium'>0.00</h3>");
$("#lbl_egreso").append("<h3 class='text-dark mb-1 font-weight-medium'>0.00</h3>");
$("#lbl_utilidad").append("<h3 class='text-dark mb-1 font-weight-medium'>0.00</h3>");
}
});
$.ajax({
type: "GET",
url: '../json/consult?action=6&idu='+idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
var ahorro = registro.cantidad;
if (!ahorro) {
ahorro = 0.00;
}
$("#lbl_ahorros").append("<h3 class='text-dark mb-1 font-weight-medium'><sup " +
"class='set-doller'>$</sup>"+ahorro+"</h3>");
});
},
error: function(data) {
$("#lbl_ahorros").append("<h3 class='text-dark mb-1 font-weight-medium'>0.00</h3>");
}
});
view_chart(divisa_primary);
};
$('#add_move_btn').click(function(){
getPagina("consult_cate", "dash_categoria");
getPagina("consult_accont", "dash_cuenta");
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
document.getElementById("dash_divisa").value = document.getElementById("select_divisa").value;
document.getElementById("dash_fecha").value = formattedDateTime;
$("#dash_monto_signal").click(function(){
var signal = document.getElementById("dash_monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
$("#dash_trans").unbind('click').click(function(){
var monto_signal = document.getElementById("dash_monto_signal").value;
var valor = document.getElementById("dash_valor").value;
var cuenta = document.getElementById("dash_cuenta").value;
var divisa = document.getElementById("dash_divisa").value;
var categoria = document.getElementById("dash_categoria").value;
var descripcion = document.getElementById("dash_descripcion").value;
var fecha = document.getElementById("dash_fecha").value;
if (monto_signal == '-'){
valor = valor * -1;
}
if (valor == "" || valor == 0 || divisa == "" || cuenta == 0 || categoria == 0 || fecha == "") {
if (valor == "" || valor == 0){
document.getElementById("dash_valor").className = "form-control is-invalid";
}
if (divisa == "") {
document.getElementById("dash_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0 is-invalid";
}
if (categoria == 0) {
document.getElementById("dash_categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (cuenta == 0) {
document.getElementById("dash_cuenta").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (fecha == "") {
document.getElementById("dash_fecha").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_transaccion', {
type: 'POST',
data: {
cuenta: cuenta,
valor: valor,
divisa: divisa,
categoria: categoria,
descripcion: descripcion,
fecha: fecha
},
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalAddDash').modal('hide');
document.getElementById("dash_valor").className = "form-control";
document.getElementById("dash_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0";
document.getElementById("dash_categoria").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("dash_cuenta").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("dash_fecha").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("dash_valor").value = "";
document.getElementById("dash_monto_signal").value = "+";
document.getElementById("dash_monto_signal").innerHTML = "+";
document.getElementById("dash_monto_signal").className = "btn btn-outline-success";
document.getElementById("dash_divisa").value = "COP";
document.getElementById("dash_descripcion").value = "";
document.getElementById("dash_cuenta").value = 0;
document.getElementById("dash_categoria").value = 0;
load_data(0);
} else {
alert("Error: " + data);
}
}
});
}
});
$("#dash_cuenta").change(function(){
getPagina("consult_divisa?id="+this.value, "dash_divisa");
});
});
$('#add_trans_btn').click(function(){
getPagina("consult_accont", "dash_trans_cuenta_fin");
getPagina("consult_accont", "dash_trans_cuenta_ini");
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
document.getElementById("dash_trans_fecha").value = formattedDateTime;
document.getElementById("dash_divisa").value = document.getElementById("select_divisa").value;
$("#dash_trans_monto_signal").click(function(){
var signal = document.getElementById("dash_trans_monto_signal");
if (signal.value == "+"){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
} else {
signal.innerHTML = "+";
signal.value = "+";
signal.className = "btn btn-outline-success";
}
});
$("#dash_trans_trans").unbind('click').click(function(){
var monto_signal = document.getElementById("dash_trans_monto_signal").value;
var valor = document.getElementById("dash_trans_valor").value;
var cuenta_ini = document.getElementById("dash_trans_cuenta_ini").value;
var divisa = document.getElementById("dash_trans_divisa").value;
var cuenta_fin = document.getElementById("dash_trans_cuenta_fin").value;
var descripcion = document.getElementById("dash_trans_descripcion").value;
var fecha = document.getElementById("dash_trans_fecha").value;
if (monto_signal == '-'){
valor = valor * -1;
}
if (valor == "" || valor == 0 || divisa == "" || cuenta_ini == 0 || cuenta_fin == 0 || fecha == "") {
if (valor == "" || valor == 0){
document.getElementById("dash_trans_valor").className = "form-control is-invalid";
}
if (divisa == "") {
document.getElementById("dash_trans_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0 is-invalid";
}
if (cuenta_fin == 0) {
document.getElementById("dash_trans_cuenta_fin").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (cuenta_ini == 0) {
document.getElementById("dash_trans_cuenta_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0 is-invalid";
}
if (fecha == "") {
document.getElementById("dash_trans_fecha").className = "form-control custom-radius custom-shadow border-0 is-invalid";
}
} else {
$.ajax('../conexions/add_movi_cuenta', {
type: 'POST',
data: {
cuenta_ini: cuenta_ini,
valor: valor,
divisa: divisa,
cuenta_fin: cuenta_fin,
descripcion: descripcion,
fecha: fecha
},
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
if (data == 200) {
$('#ModalTransDash').modal('hide');
document.getElementById("dash_trans_valor").className = "form-control";
document.getElementById("dash_trans_divisa").className = "custom-select form-control bg-white custom-radius custom-shadow border-0";
document.getElementById("dash_trans_cuenta_fin").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("dash_trans_cuenta_ini").className = "custom-select mr-sm-2 custom-radius custom-shadow border-0";
document.getElementById("dash_trans_fecha").className = "form-control custom-radius custom-shadow border-0";
document.getElementById("dash_trans_valor").value = "";
document.getElementById("dash_trans_monto_signal").value = "+";
document.getElementById("dash_trans_monto_signal").innerHTML = "+";
document.getElementById("dash_trans_divisa").value = "COP";
document.getElementById("dash_trans_descripcion").value = "";
document.getElementById("dash_trans_cuenta_ini").value = 0;
document.getElementById("dash_trans_cuenta_fin").value = 0;
load_data(0);
} else {
alert("Error: " + data);
}
}
});
}
});
$("#dash_trans_cuenta_ini").change(function(){
getPagina("consult_divisa?id="+this.value, "dash_trans_divisa");
});
});
$('#screen_android').click(function(){
$("#ModalScreen").modal("hide");
$("#ModalScreenAndroid").modal("show");
});
$('#screen_iphone').click(function(){
$("#ModalScreen").modal("hide");
$("#ModalScreenIOS").modal("show");
});
function signo(id, id2){
var nro = document.getElementById(id).value;
var signal = document.getElementById(id2);
if (nro < 0){
signal.innerHTML = "-";
signal.value = "-";
signal.className = "btn btn-outline-danger";
document.getElementById(id).value = nro * -1;
}
};
function val_session(idu){
if(idu == ""){
window.location = "/";
}
};
function view_chart(divisa_primary){
var idu = <?php echo $id_user;?>;
$.ajax({
type: "GET",
url: '../json/grafica?action=1&idu='+ idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.categoria] = d.cantidad;
value.push(d.categoria);
});
//console.log(data2);
var chart1 = c3.generate({
bindto: '#campaign-v2',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ingresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v2',
data: {
columns: [
['Sin ingresos', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ingresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
$.ajax({
type: "GET",
url: '../json/grafica?action=2&idu='+ idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.categoria] = d.cantidad;
value.push(d.categoria);
});
//console.log(data2);
var chart1 = c3.generate({
bindto: '#campaign-v3',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Egresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v3',
data: {
columns: [
['Sin egresos', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Egresos',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
$.ajax({
type: "GET",
url: '../json/grafica?action=3&idu='+ idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
var data2 = {};
var value = [];
JSON.parse(JSON.stringify(data)).forEach(function(d) {
data2[d.nombre] = d.cantidad;
value.push(d.nombre);
});
var chart1 = c3.generate({
bindto: '#campaign-v4',
data: {
json: [data2],
keys: {
value: value
},
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ahorros',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#5f76e8',
'#ff4f70',
'#01caf1',
'#ff7f0e',
'#ffbb78',
'#2ca02c',
'#98df8a',
'#d62728',
'#ff9896',
'#9467bd',
'#c5b0d5',
'#8c564b',
'#c49c94',
'#e377c2',
'#f7b6d2',
'#7f7f7f',
'#c7c7c7',
'#bcbd22',
'#dbdb8d',
'#17becf',
'#9edae5'
]
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v4',
data: {
columns: [
['Sin Ahorros', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ahorros',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
$('#movimientos-diarios').empty();
$('#movimientos-diarios').append("<div class='d-flex align-items-start'>"+
"<h4 class='card-title mb-0'>Movimientos Diarios</h4>"+
"</div>"+
"<canvas id='line-chart' height='150'></canvas>"
);
$.ajax({
type: "GET",
url: '../json/grafica?action=4&idu='+ idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
var fechas = [];
var val_ingre = [];
var val_egre = [];
JSON.parse(JSON.stringify(data)).forEach(function(d) {
fechas.push(d.fecha);
val_ingre.push(d.ingresos);
val_egre.push(d.egresos);
});
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: fechas,
datasets: [{
data: val_ingre,
label: "Ingresos",
borderColor: "#22ca80",
fill: false
}, {
data: val_egre,
label: "Egresos",
borderColor: "#ff4f70",
fill: false
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
if (value < 1000000){
return value / 1000 + 'k';
} else {
return value / 1000000 + 'M';
}
}
}
}]
}
}
});
},
error: function (data) {
var chart1 = c3.generate({
bindto: '#campaign-v4',
data: {
columns: [
['Sin Ahorros', 1],
],
type: 'donut',
tooltip: {
show: true
}
},
donut: {
label: {
show: false
},
title: 'Ahorros',
width: 18
},
legend: {
hide: true
},
color: {
pattern: [
'#edf2f6'
]
}
});
}
});
document.getElementById("activity_current").innerHTML = "";
getPagina("consult_activity","activity_current");
d3.select('#campaign-v2 .c3-chart-arcs-title').style('font-family', 'Rubik');
d3.select('#campaign-v3 .c3-chart-arcs-title').style('font-family', 'Rubik');
d3.select('#campaign-v4 .c3-chart-arcs-title').style('font-family', 'Rubik');
};
function val_new_user(idu){
$.ajax({
type: "GET",
url: '../json/consult?action=7&idu='+idu,
dataType: "json",
success: function(data){
//console.log(data);
$.each(data,function(key, registro) {
if (registro.categorias == 1 && registro.cuentas == 0){
$("#ModalWelcome").modal('show');
}
});
}
});
};
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
});
function showactivity(id){
document.getElementById("bodyActivity").innerHTML = "";
var divisa_primary = document.getElementById("select_divisa").value;
$.ajax({
type: "GET",
url: '../json/reportes?action=6&idu='+ idu+'&divi='+divisa_primary,
dataType: "json",
success: function(data){
//console.log(data);
if (id == 1){
$.each(data,function(key, registro) {
var catego = '"'+registro.nombre+'"'
$("#bodyActivity").append("<div onclick='showactivitylvl("+id+","+catego+")' class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-success'>"+formatter.format(registro.ingreso)+"</p></h6>"+
"</div>");
});
} else if (id == 2){
$.each(data,function(key, registro) {
var catego = '"'+registro.nombre+'"'
$("#bodyActivity").append("<div onclick='showactivitylvl("+id+","+catego+")' class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-10 col-lg-10 col-xl-10 text-muted mt-2'>"+
registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 col-lg-12 col-xl-12 text-muted'>"+
"<p class='text-danger'>"+formatter.format(registro.egreso)+"</p></h6>"+
"</div>");
});
}
},
error: function (data) {
}
});
$("#ModalActivity").modal("show");
}
function showactivitylvl(id, nombre){
$("#ModalActivity").modal("hide");
document.getElementById("bodyActivityLvl").innerHTML = "";
var divisa_primary = document.getElementById("select_divisa").value;
$.ajax({
type: "GET",
url: '../json/reportes?action=7&idu='+ idu+'&divi='+divisa_primary+
'&account='+nombre+'&sig='+id,
dataType: "json",
success: function(data){
//console.log(data);
if (id == 1){
$.each(data,function(key, registro) {
var catego = '"'+registro.nombre+'"';
var mes = '"'+registro.mes+'"';
$("#bodyActivityLvl").append("<div onclick='showactivityMonth("+id+","+catego+","+mes+")' class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.mes+"-"+registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-success'>"+formatter.format(registro.cantidad)+"</p></h6>"+
"</div>");
});
} else if (id == 2){
$.each(data,function(key, registro) {
var catego = '"'+registro.nombre+'"';
var mes = '"'+registro.mes+'"';
$("#bodyActivityLvl").append("<div onclick='showactivityMonth("+id+","+catego+","+mes+")' class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-10 col-lg-10 col-xl-10 text-muted mt-2'>"+
registro.mes+"-"+registro.nombre+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 col-lg-12 col-xl-12 text-muted'>"+
"<p class='text-danger'>"+formatter.format(registro.cantidad)+"</p></h6>"+
"</div>");
});
}
},
error: function (data) {
}
});
$("#ModalActivityLvl").modal("show");
$("#btn_back_lvl").click(function(){
$("#ModalActivityLvl").modal("hide");
$("#ModalActivity").modal("show");
});
}
function showactivityMonth(id, nombre, mes){
$("#ModalActivityLvl").modal("hide");
document.getElementById("bodyActivityMonth").innerHTML = "";
var divisa_primary = document.getElementById("select_divisa").value;
console.log('../json/reportes?action=8&idu='+ idu+'&divi='+divisa_primary+
'&account='+nombre+'&mes='+mes+'&sig='+id);
$.ajax({
type: "GET",
url: '../json/reportes?action=8&idu='+ idu+'&divi='+divisa_primary+
'&account='+nombre+'&mes='+mes+'&sig='+id,
dataType: "json",
success: function(data){
//console.log(data);
if (id == 1){
$.each(data,function(key, registro) {
$("#bodyActivityMonth").append("<div class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-success'>"+formatter.format(registro.cantidad)+
"</p><p class='text-muted ml-1'></p>"+registro.fecha+"</h6>"+
"</div>");
});
} else if (id == 2){
$.each(data,function(key, registro) {
$("#bodyActivityMonth").append("<div class='card border-botton border-right border-left'>"+
"<h4 class='card-title col-md-12 text-muted mt-2'>"+
registro.categoria+"</h3>"+
"<h6 class='card-title ml-3 row col-md-12 text-muted'>"+
"<p class='text-danger'>"+formatter.format(registro.cantidad)+
"</p><p class='text-muted ml-1'></p>"+registro.fecha+"</h6>"+
"</div>");
});
}
},
error: function (data) {
}
});
$("#ModalActivityMonth").modal("show");
$("#btn_back_moth").click(function(){
$("#ModalActivityMonth").modal("hide");
$("#ModalActivityLvl").modal("show");
});
}
document.addEventListener("DOMContentLoadesd", function(){
if(!Notification){
alert("Las notificaciones no se soportan en tu navegador.");
return;
}
if(Notification.permission != "granted")
Notification.requestPermission();
});
function notificar(titulo, contenido){
if(Notification.permission != "granted"){
Notification.requestPermission();
}else{
var notification = new Notification(titulo,
{
icon: "http://fiona.byethost11.com/assets/images/logo-icon.png",
body: contenido
}
);
}
}
function show_mensaje(id){
$.ajax({
type: "GET",
url: '../json/consult?action=8&idu='+idu+'&id='+id,
dataType: "json",
success: function(data){
$.each(data,function(key, registro) {
document.getElementById("ModalMensaLbl").innerHTML = registro.titulo;
document.getElementById("catego_mensaje").innerHTML = registro.tipo;
document.getElementById("fecha_mensaje").innerHTML = registro.fecha;
document.getElementById("contenido_mensaje").innerHTML = registro.Contenido;
});
}
});
$("#ModalMensajes").modal("show");
$.ajax('../conexions/read_mensaje', {
type: 'POST',
data: {
id: id
},
success: function (data, status, xhr) {
//console.log('status: ' + status + ', data: ' + data);
}
});
}
function count_message(){
//console.log("antes: " + nro_mesajes);
nro_ant_mes = nro_mesajes;
getPagina("consult_nro_message", "nro_message");
nro_mesajes = document.getElementById("nro_message").innerHTML;
//console.log("despues: " + nro_mesajes);
if (nro_ant_mes < nro_mesajes && nro_ant_mes != ""){
notificar('FIONA Notificacion', "Tienes un nuevo mensaje de fiona!");
getPagina("consult_mensajes", "list_mensajes");
}
else if (nro_mesajes < nro_ant_mes){
getPagina("consult_mensajes", "list_mensajes");
}
};
setInterval("count_message()", 5000);
<file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
$idu = '"'.$id_user.'"';
include_once("../conexions/connect.php");
$year = $_GET["year"];
$insert = "SELECT * FROM Vpresupuesto WHERE id_user = '$id_user' and year = $year
ORDER BY grupo DESC, categoria ASC";
$ejecutar =mysqli_query( $conn,$insert);
$aux = "";
$acumulado = 0;
$utilidad = 0;
echo "<table class='table table-hover' style='width: 100%;'>
<thead>
<tr class='text-dark'>
<th>CATEGORIA</th>
<th>VALOR ANUAL</th>
</tr>
</thead>
<tbody>";
while ($lista = mysqli_fetch_array($ejecutar)){
$cantidad = $lista["cantidad"];
$nro_catego = $lista["nro_catego"];
$categoria = $lista["categoria"];
$grupo = $lista["grupo"];
if ($categoria != $aux && $aux != ""){
echo "<tr class='table-dark text-dark'>
<th class='font-weight-bold'>$aux</th>
<th>".formatDollars($acumulado)."</th>
</tr>";
$acumulado = 0;
}
if ($lista["sub_categoria"] == NULL){
$sub_categoria = $categoria;
} else {
$sub_categoria = $lista["sub_categoria"];
}
if ($cantidad == NULL){
$cantidad = 0;
}
$name_catego = '"'.$sub_categoria.'"';
echo "<tr onclick='edit_presu($nro_catego, $name_catego, $year,$idu)'>
<th>$sub_categoria</th>
<th>".formatDollars($cantidad)."</th>
</tr>";
$aux = $categoria;
$acumulado += $cantidad;
if ($grupo == 4){
$utilidad += $cantidad;
} else {
$utilidad -= $cantidad;
}
}
if ($utilidad >= 0){
$style = "success";
} else {
$style = "danger";
}
echo "<tr class='table-dark text-dark'>
<th class='font-weight-bold'>$aux</th>
<th>".formatDollars($acumulado)."</th>
</tr>
<tr class='table-$style text-dark'>
<th class='font-weight-bold'>UTILIDAD</th>
<th>".formatDollars($utilidad)."</th>
</tr>
</tbody>
</table>";
mysqli_close($conn);
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
?><file_sep><!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png">
<title>Fiona - Cuentas</title>
<!-- This page css -->
<!-- Custom CSS -->
<link href="../dist/css/style.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper" data-theme="light" data-layout="vertical" data-navbarbg="skin6" data-sidebartype="full" data-sidebar-position="fixed" data-header-position="fixed" data-boxed-layout="full">
<?php include("../navbar.php");?>
<!-- ============================================================== -->
<!-- Page wrapper -->
<!-- ============================================================== -->
<div class="page-wrapper">
<!-- ============================================================== -->
<!-- Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<div class="page-breadcrumb">
<div class="row">
<div class="col-12 align-self-center">
<h4 class="page-title text-truncate text-dark font-weight-medium mb-1">LISTA DE CUENTAS</h4>
<div class="d-flex align-items-center">
<nav aria-label="breadcrumb">
<ol class="breadcrumb m-0 p-0">
<li class="breadcrumb-item"><a href="dashboard" class="text-muted">Dashboard</a></li>
<li class="breadcrumb-item text-muted active" aria-current="page">Cuentas</li>
</ol>
</nav>
</div>
</div>
<!--<div class="col-5 align-self-center">
<div class="customize-input float-right">
<select class="custom-select custom-select-set form-control bg-white border-0 custom-shadow custom-radius">
<option selected>Aug 19</option>
<option value="1">July 19</option>
<option value="2">Jun 19</option>
</select>
</div>
</div>-->
</div>
</div>
<!-- ============================================================== -->
<!-- End Bread crumb and right sidebar toggle -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Container fluid -->
<!-- ============================================================== -->
<div class="container-fluid">
<!-- ============================================================== -->
<!-- Start Page Content -->
<!-- ============================================================== -->
<!-- basic table -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div id="card_account" class="row">
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- End Container fluid -->
<!-- ============================================================== -->
<div id="ModalAccount" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Creador de cuentas</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="nombre">Nombre</label>
<input type="text" class="form-control custom-radius custom-shadow border-0" id="nombre">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="descripcion">Descripción</label>
<textarea class="form-control" id="descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="divisa">Divisa</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="divisa">
<option value="0" selected>Selecciona una opción</option>
<option value="COP">COP</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="GBD">GBD</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option>
<option value="MXN">MXN</option>
<option value="ILS">ILS</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="monto_ini">Monto inicial</label>
<input type="number" value="0" step="0.01" class="form-control custom-radius custom-shadow border-0" id="monto_ini">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-check form-check-inline">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="account_save">
<label class="custom-control-label" for="account_save">Seleciona si es cuenta para ahorrar</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="save_account" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalEditAcco" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Editor de cuentas</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_nombre">Nombre</label>
<input type="text" class="form-control custom-radius custom-shadow border-0" id="edit_nombre">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_descripcion">Descripción</label>
<textarea class="form-control" id="edit_descripcion" rows="3" placeholder="Escribe aqui una descripción..."></textarea>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_divisa">Divisa</label>
<select class="custom-select mr-sm-2 custom-radius custom-shadow border-0"
id="edit_divisa">
<option value="0" selected>Selecciona una opción</option>
<option value="COP">COP</option>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="JPY">JPY</option>
<option value="GBD">GBD</option>
<option value="CAD">CAD</option>
<option value="AUD">AUD</option>
<option value="MXN">MXN</option>
<option value="ILS">ILS</option>
</select>
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-group mb-4">
<label class="mr-sm-2" for="edit_monto_ini">Monto inicial</label>
<input type="number" step="0.01" class="form-control custom-radius custom-shadow border-0" id="edit_monto_ini">
</div>
</div>
<div class="col-sm-12 col-md-12 col-lg-12 mt-2">
<div class="form-check form-check-inline">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="edit_account_save">
<label class="custom-control-label" for="edit_account_save">Seleciona si es cuenta para ahorrar</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="btn_edit_account" class="btn btn-primary">Guardar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalDeletAcco" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Eliminar cuenta</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div id="text_delete_acco" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" id="btn_delete_account" class="btn btn-danger">Eliminar</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="ModalAccountInfo" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configuración Inicial II</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Cuentas:</strong></p>
<p>para crear una cuenta dale clic en el siguiente recuadro:</p>
<div class='col-md-12'>
<a class='card'>
<div class='card-body'>
<div class='row'>
<div class='col-md-9 col-lg-9 col-xl-9'><h3 class='card-title text-muted'><i class='fas fa-plus mr-2'></i>Nueva cuenta</h3></div>
<div class='col-md-12 col-lg-12 col-xl-12' style='position: absolute;'><h4 class='card-title text-muted fa-2x float-right'><i class='icon-arrow-right'></i></h4></div>
</div>
</div>
</a>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button" class="btn waves-effect waves-light btn-rounded btn-primary"
data-dismiss="modal">Siguiente</button>
</div>
</div>
</div>
</div>
<div id="ModalCongratuAccon" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Felicitaciones!</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Bien hecho </strong>!</p>
<p>Haz creado tu primera cuenta. Crea todas las cuentas necesarias para saber
extactamente donde tienes la plata y que cantidad.</p>
<!--<p>Ahora entendamos para que sirven algunos botones:</p>
<li><a class='btn btn-rounded btn-success text-white'><i class='fas fa-sign-out-alt mr-2'></i>Entrar</a>
Este boton sirve para ingresar a la cuenta y ver todos los movimeintos que se ha tenido.
</li>
<li><button class='btn btn-circle btn-primary'><i class='far fa-edit'></i></button>
Este boton sirve para editar la informacion de la cuenta.
</li>
<li><button class='btn btn-circle btn-danger' ><i class='fas fa-trash-alt'></i></button>
Este boton sirve para Eliminar la cuenta y todos los movimientos que tenga la cuenta
</li>-->
</div>
<div class="modal-footer">
<button type="button" class="btn waves-effect waves-light btn-rounded btn-light"
data-dismiss="modal">Cerrar</button>
<button type="button"
class="btn waves-effect waves-light btn-rounded btn-primary"
data-toggle="modal" data-target="#ModalMoviInfo" data-dismiss="modal">Siguiente
</button>
</div>
</div>
</div>
</div>
<div id="ModalMoviInfo" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Uso de la App</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p><strong>Ya estas en el ultimo paso </strong>!</p>
<p>Para finalizar solo queda por ingresar tu primer movimeinto o transacción.</p>
<p>Es importante que sepas que desde el boton <a class='btn btn-rounded btn-success text-white'>
<i class='fas fa-sign-out-alt mr-2'></i>Entrar</a> puedes visualizar los movimeintos de tienes en
dicha cartera.</p>
</div>
<div class="modal-footer">
<button type="button"
class="btn waves-effect waves-light btn-rounded btn-primary"
data-dismiss="modal">Finalizar
</button>
</div>
</div>
</div>
</div>
<!-- ============================================================== -->
<!-- footer -->
<!-- ============================================================== -->
<?php include("../footer.php");?>
<!-- ============================================================== -->
<!-- End footer -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Page wrapper -->
<!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- End Wrapper -->
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="../assets/libs/jquery/dist/jquery.min.js"></script>
<script src="../assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="../assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<!-- apps -->
<script src="../dist/js/app-style-switcher.js"></script>
<script src="../dist/js/feather.min.js"></script>
<script src="../assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<script src="../dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="../java/functions.php"></script>
<script src="../dist/js/custom.min.js"></script>
</body>
</html><file_sep><?php
session_start();
$id_user = $_SESSION["Id_user"];
include_once("../conexions/connect.php");
$insert = "SELECT * FROM fionadb.cuentas WHERE id_user='$id_user'";
$ejecutar =mysqli_query( $conn,$insert);
if (!$_GET["act"]){
echo "<option value='0' selected>Selecciona una opción</option>";
$select = 0;
} else{
$select = $_GET["act"];
}
while ($lista = mysqli_fetch_array($ejecutar)){
$id = $lista["id"];
$nombre = $lista ["nombre"];
if ($select == $id){
echo "<option value='$id' selected>$nombre</option>";
} else {
echo "<option value='$id'>$nombre</option>";
}
}
mysqli_close($conn);
?><file_sep><?php
function ingreso(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT b.categoria, SUM(valor) AS cantidad FROM fionadb.movimientos AS a
JOIN fionadb.categorias AS b ON (a.categoria = b.id and a.id_user = b.id_user) WHERE grupo= 4
and a.id_user='$id_user' and divisa='$divi' GROUP BY b.categoria";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function egreso(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT b.categoria, SUM(valor) AS cantidad FROM fionadb.movimientos AS a
JOIN fionadb.categorias AS b ON (a.categoria = b.id and a.id_user = b.id_user) WHERE (grupo= 1
or grupo = 2) and a.id_user='$id_user' and divisa='$divi' GROUP BY b.categoria";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function ahorros(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT nombre, SUM(valor) + monto_inicial AS cantidad FROM fionadb.cuentas AS a JOIN fionadb.movimientos AS b
ON(a.id_user = b.id_user and b.cuenta = a.id) WHERE a.id_user='$id_user' and b.divisa='$divi'
and cuenta_ahorro = 1 GROUP BY nombre";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
function diario(){
include_once('../conexions/connect.php');
// Check connection
if ( mysqli_connect_errno() ) {
echo "Error: Ups! Hubo problemas con la conexión. Favor de intentar nuevamente.";
} else {
$id_user = $_GET['idu'];
$divi = $_GET['divi'];
$strsql = "SELECT Date_format(fecha,'%m/%d') AS fecha, SUM(if(valor > 0, valor, 0)) AS ingresos,
SUM(if(valor < 0, valor, 0)) AS egresos FROM fionadb.movimientos
WHERE id_user='$id_user' and fecha >= DATE_SUB(NOW(),INTERVAL 15 DAY) and divisa='$divi'
GROUP BY Date_format(fecha,'%m/%d')";
$rs = mysqli_query($conn, $strsql);
$total_rows = $rs->num_rows;
if ($total_rows > 0 ) {
while ($row = $rs->fetch_object()){
$data[] = $row;
}
echo(json_encode($data));
}
}
};
$action = $_GET['action'];
switch($action) {
case 1:
ingreso();
break;
case 2:
egreso();
break;
case 3:
ahorros();
break;
case 4:
diario();
break;
}
?>
| e0c951f81976e79925630116ceda3e447f0d8eb6 | [
"Markdown",
"JavaScript",
"PHP"
] | 47 | PHP | samisosa20/Fiona | 303a049c669537d4813936c4d0f491a2939b484d | c4d1c20f08122b7469d1f59ca451f370f0180600 |
refs/heads/master | <file_sep>// xlCANcontrol.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "xlCANcontrol.h"
#include "xlCANcontrolDlg.h"
HINSTANCE m_hLangDLL;
int language;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolApp
BEGIN_MESSAGE_MAP(CXlCANcontrolApp, CWinApp)
//{{AFX_MSG_MAP(CXlCANcontrolApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolApp construction
CXlCANcontrolApp::CXlCANcontrolApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CXlCANcontrolApp object
CXlCANcontrolApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolApp initialization
BOOL CXlCANcontrolApp::InitInstance()
{
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
//if(getSystemId()==6) //win7 下才支持语言切换
//{
// //get language in ini
// CString str;
// char strbuf[50];
// DWORD change;
// CString strPath;
// change=GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
// strPath.Format("%s\\customer.ini",str);
// GetPrivateProfileString("UserInterface","lang",NULL,strbuf,50,strPath);
// language = atoi(strbuf);
// //choose dll based on language
// if(language == 0)
// {
// m_hLangDLL=LoadLibrary("ibuscn.dll");
// if(m_hLangDLL)
// {
// AfxSetResourceHandle(m_hLangDLL);
// }
// else
// {
// AfxMessageBox("ibuscn.dll is lost");
// }
// }
// else
// {
// m_hLangDLL=LoadLibrary("ibusen.dll");
// if(m_hLangDLL)
// {
// AfxSetResourceHandle(m_hLangDLL);
// }
// else
// {
// AfxMessageBox("ibusen.dll is lost");
// }
// }
//}
//else
//{
// AfxMessageBox("Windows XP下不支持多语言切换,完美体验请升级系统到Win7");
//}
CXlCANcontrolDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
int CXlCANcontrolApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
if(m_hLangDLL)
FreeLibrary(m_hLangDLL);
return CWinApp::ExitInstance();
}
int CXlCANcontrolApp::getSystemId(void) //判断系统,为兼容性准备
{
SYSTEM_INFO info; //用SYSTEM_INFO结构判断64位AMD处理器
GetSystemInfo(&info); //调用GetSystemInfo函数填充结构
OSVERSIONINFOEX os;
os.dwOSVersionInfoSize=sizeof(OSVERSIONINFOEX);
if(GetVersionEx((OSVERSIONINFO *)&os))
{
switch(os.dwMajorVersion){
case 4:
return 4;
case 5:
return 5;
case 6:
return 6;
default:
return -2;
}
}
else
{
return -1;
}
}
<file_sep>/*----------------------------------------------------------------------------
| File : xlCANcontrolDlg.cpp
| Project : Vector CAN Example
|
| Description : handles the dialog box
|-----------------------------------------------------------------------------
| $Author: vismra $ $Locker: $ $Revision: 4693 $
| $Header: /VCANDRV/XLAPI/samples/xlCANcontrol/xlCANcontrolDlg.cpp 5 23.05.05 16:59 J鰎g $
|-----------------------------------------------------------------------------
| Copyright (c) 2004 by Vector Informatik GmbH. All rights reserved.
|---------------------------------------------------------------------------*/
#include "stdafx.h"
#include "xlCANcontrol.h"
#include "xlCANcontrolDlg.h"
#include <iostream>
#include "NewCellTypes/GridURLCell.h"
#include "NewCellTypes/GridCellCombo.h"
#include "NewCellTypes/GridCellCheck.h"
#include "NewCellTypes/GridCellNumeric.h"
#include "NewCellTypes/GridCellDateTime.h"
#include "NewCellTypes/GridCellHexPlusX.h"
//-----------------------------------------------------------------------------------------------------------------------
//global variales
int curNewAddRow=1;//click "new" button, enables a new input row, this var keeps the row number. first row(number 0) in the grid is used as title
bool bCellEditing;//when user is editing a cell this var turns to be true
CString strMessage; // A temporary memory to load different message from string table
bool bRun = false; // The flag to indicate the condition of the bus monitoring
CGridCtrl m_Grid_message;//If you want to use it as a extern var,you can not put it in *Dlg.h,but Here
extern XLuint64 startTime;
extern int language;// identify the language used in user interface
bool m_bRestartFlag = false;
CListBox m_listbox_dm;
typedef struct{
int id;
bool ext;
byte ch;
unsigned short dlc;
byte d0;
byte d1;
byte d2;
byte d3;
byte d4;
byte d5;
byte d6;
byte d7;
}SendMessageStruct;
SendMessageStruct gridMessageList[200];//CAN Message copied from the gridctrl "m_Grid_seddata" grid,when one time edit end and the CAN device is running, once copy occured
int timerQueue[200];// 保存所有已经开启的timer编号
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolDlg dialog
CXlCANcontrolDlg::CXlCANcontrolDlg(CWnd* pParent /*=NULL*/)
: CDialog(CXlCANcontrolDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CXlCANcontrolDlg)
m_eD00 = _T("");
m_eD01 = _T("");
m_eD02 = _T("");
m_eD03 = _T("");
m_eD04 = _T("");
m_eD05 = _T("");
m_eD06 = _T("");
m_eD07 = _T("");
m_eDLC = _T("");
m_eID = _T("");
m_ExtID = FALSE;
m_eFilterFrom = _T("");
m_eFilterTo = _T("");
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
}
void CXlCANcontrolDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CXlCANcontrolDlg)
DDX_Control(pDX, IDC_HARDWARE, m_Hardware);
DDX_Control(pDX, IDC_CHANNEL, m_Channel);
DDX_Control(pDX, IDC_SEND, m_btnSend);
DDX_Control(pDX, IDC_OFFBUS, m_btnOffBus);
DDX_Control(pDX, IDC_ONBUS, m_btnOnBus);
DDX_Control(pDX, IDC_BAUDRATE, m_Baudrate);
DDX_Control(pDX, IDC_OUTPUT, m_Output);
DDX_Text(pDX, IDC_D00, m_eD00);
DDX_Text(pDX, IDC_D01, m_eD01);
DDX_Text(pDX, IDC_D02, m_eD02);
DDX_Text(pDX, IDC_D03, m_eD03);
DDX_Text(pDX, IDC_D04, m_eD04);
DDX_Text(pDX, IDC_D05, m_eD05);
DDX_Text(pDX, IDC_D06, m_eD06);
DDX_Text(pDX, IDC_D07, m_eD07);
DDX_Text(pDX, IDC_DLC, m_eDLC);
DDX_Text(pDX, IDC_ID, m_eID);
DDX_Check(pDX, IDC_EXID, m_ExtID);
DDX_Text(pDX, IDC_FILTERFROM, m_eFilterFrom);
DDX_Text(pDX, IDC_FILTERTO, m_eFilterTo);
//}}AFX_DATA_MAP
DDX_Control(pDX, IDC_CUSTOM_MESSAGE, m_Grid_message);
DDX_Control(pDX, IDC_STATIC_PIC_LOGO, m_Picture_logo);
DDX_Control(pDX, IDC_STATIC_ABOUT, m_Picture_about);
DDX_Control(pDX, IDC_STATIC_HELP, m_Picture_help);
DDX_Control(pDX, IDC_CUSTOM_SIGNALS, m_Grid_signals);
DDX_Control(pDX, IDC_CUSTOM_SENDDATA, m_Grid_senddata);
DDX_Control(pDX, IDC_STATIC_LANG, m_Picture_lang);
DDX_Control(pDX, IDC_STATIC_VER_NO, m_sta_versionno);
DDX_Control(pDX, IDC_COMBO_CHANNEL, m_commo_channel);
DDX_Control(pDX, IDC_COMBO_HZ, m_commo_hz);
DDX_Check(pDX, IDC_CHECK_ADVANCED, m_check_advance);
DDX_Control(pDX, IDC_BUTTON_RESTART, m_btn_restart);
DDX_Control(pDX, IDC_STATIC_CAUTION, m_sta_caution);
DDX_Control(pDX, IDC_LIST1, m_listbox_dm);
}
BEGIN_MESSAGE_MAP(CXlCANcontrolDlg, CDialog)
//{{AFX_MSG_MAP(CXlCANcontrolDlg)
ON_WM_TIMER() //定时器
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_ONBUS, OnOnbus)
ON_BN_CLICKED(IDC_OFFBUS, OnOffbus)
ON_BN_CLICKED(IDC_SEND, OnSend)
ON_BN_CLICKED(IDC_CLEAR, OnClear)
ON_BN_CLICKED(IDC_ABOUT, OnAbout)
ON_BN_CLICKED(IDC_RESET, OnReset)
ON_BN_CLICKED(IDC_LIC_INFO, OnLicInfo)
ON_BN_CLICKED(IDC_SETFILTER, OnSetfilter)
//}}AFX_MSG_MAP
ON_STN_CLICKED(IDC_STATIC_PIC_LOGO, &CXlCANcontrolDlg::OnStnClickedStaticPicLogo)
ON_STN_CLICKED(IDC_STATIC_ABOUT, &CXlCANcontrolDlg::OnStnClickedStaticAbout)
ON_STN_CLICKED(IDC_STATIC_HELP, &CXlCANcontrolDlg::OnStnClickedStaticHelp)
ON_STN_CLICKED(IDC_STATIC_LANG, &CXlCANcontrolDlg::OnStnClickedStaticLang)
ON_BN_CLICKED(IDC_BUTTON_EXPORT, &CXlCANcontrolDlg::OnBnClickedButtonExport)
ON_BN_CLICKED(IDC_CHECK_ADVANCED, &CXlCANcontrolDlg::OnBnClickedCheckAdvanced)
ON_BN_CLICKED(IDC_BUTTON_RESTART, &CXlCANcontrolDlg::OnBnClickedButtonRestart)
ON_WM_CLOSE()
ON_NOTIFY(NM_CLICK, IDC_CUSTOM_MESSAGE,OnOnceClick) //gridctrl单击击消息事件
ON_NOTIFY(NM_RCLICK,IDC_CUSTOM_SENDDATA,OnRClick) //gridctrl右击消息事件
ON_NOTIFY(NM_DBLCLK,IDC_CUSTOM_SENDDATA,OnDoubleClick) //gridctrl双击消息事件
ON_BN_CLICKED(IDC_BUTTON_NEWMESS, &CXlCANcontrolDlg::OnBnClickedButtonNewmess)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolDlg message handlers
BOOL CXlCANcontrolDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
//设置所有定时器初始状态为关闭
memset(timerQueue,0,200);
//read customer.ini
CString str;
char strbuf[50];
DWORD change;
CString strPath;
change=GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
strPath.Format("%s\\customer.ini",str);
GetPrivateProfileString("HW Config","channel",NULL,strbuf,50,strPath);
int channeltype = atoi(strbuf);
GetPrivateProfileString("HW Config","baudtype",NULL,strbuf,50,strPath);
int baudtype = atoi(strbuf);
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// we need the listbox pointer within our CAN class
m_CAN.m_pOutput = &m_Output;
m_CAN.m_pHardware = &m_Hardware;
// init the CAN hardware
if (m_CAN.CANInit()) {
m_Hardware.AddString("<ERROR> no HW!");
m_Output.AddString("You need two CANcabs/CANpiggy's");
}
// init the default window
m_commo_channel.AddString("CH 01");
m_commo_channel.AddString("CH 02");
m_commo_channel.SetCurSel(channeltype);
m_commo_hz.AddString("250 KHZ");
m_commo_hz.AddString("500 KHZ");
m_commo_hz.SetCurSel(baudtype);
m_eD00 = "00";
m_eD01 = "00";
m_eD02 = "00";
m_eD03 = "00";
m_eD04 = "00";
m_eD05 = "00";
m_eD06 = "00";
m_eD07 = "00";
m_eDLC = "08";
m_eID = "04";
m_commo_hz.SetCurSel(baudtype);
m_commo_channel.SetCurSel(channeltype);
m_eFilterFrom = "5";
m_eFilterTo = "10";
m_Grid_message.SetEditable(FALSE);
m_Grid_message.SetColumnCount(6);
m_Grid_message.SetRowCount(2);
m_Grid_message.SetDefCellHeight(15);
m_Grid_message.SetDefCellWidth(50);
m_Grid_message.SetDefCellMargin(1);
// m_Grid_message.SetAutoSizeStyle();
CFont * f = new CFont;
f->CreateFont(0, 0, 0, 0, FW_LIGHT, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH , _T("楷体_GB2312"));
m_Grid_message.SetFont(f);
m_Grid_signals.SetFont(f);
m_Grid_senddata.SetFont(f);
//初始化message表格
m_Grid_message.SetFixedRowCount();
m_Grid_message.SetBkColor(RGB(0xf0,0xf0,0xf0));
m_Grid_message.SetRowHeight(0,50);
m_Grid_message.SetRowHeight(1,50);
//m_Grid_message.SetListMode();
//m_Grid_message.SetHeaderSort();
//m_Grid_message.SetCompareFunction(CGridCtrl::pfnCellNumericCompare);
m_Grid_message.SetSingleRowSelection();
m_Grid_message.SetColumnWidth(0,5);
m_Grid_message.SetColumnWidth(1,80);
m_Grid_message.SetColumnWidth(2,80);
m_Grid_message.SetColumnWidth(3,80);
m_Grid_message.SetColumnWidth(4,40);
m_Grid_message.SetColumnWidth(5,180);
m_Grid_message.SetItemText(0,0,"");
strMessage.LoadStringA(IDS_STRING103);
m_Grid_message.SetItemText(0,1,strMessage);
strMessage.LoadStringA(IDS_STRING104);
m_Grid_message.SetItemText(0,2,strMessage);
strMessage.LoadStringA(IDS_STRING105);
m_Grid_message.SetItemText(0,3,strMessage);
strMessage.LoadStringA(IDS_STRING106);
m_Grid_message.SetItemText(0,4,strMessage);
strMessage.LoadStringA(IDS_STRING107);
m_Grid_message.SetItemText(0,5,strMessage);
//初始化信号栏表格
m_Grid_signals.SetEditable(FALSE);
m_Grid_signals.SetColumnCount(7);
m_Grid_signals.SetRowCount(64);
m_Grid_signals.SetDefCellHeight(15);
m_Grid_signals.SetDefCellWidth(30);
m_Grid_signals.SetDefCellMargin(1);
m_Grid_signals.SetFixedRowCount();
m_Grid_signals.SetBkColor(RGB(0xf0,0xf0,0xf0));
m_Grid_signals.SetColumnWidth(0,70);
m_Grid_signals.SetColumnWidth(1,80);
m_Grid_signals.SetColumnWidth(2,80);
m_Grid_signals.SetColumnWidth(3,70);
m_Grid_signals.SetColumnWidth(4,70);
m_Grid_signals.SetColumnWidth(3,30);
m_Grid_signals.SetColumnWidth(4,30);
strMessage.LoadStringA(IDS_STRING108);
m_Grid_signals.SetItemText(0,0,strMessage);
strMessage.LoadStringA(IDS_STRING109);
m_Grid_signals.SetItemText(0,1,strMessage);
strMessage.LoadStringA(IDS_STRING110);
m_Grid_signals.SetItemText(0,2,strMessage);
strMessage.LoadStringA(IDS_STRING111);
m_Grid_signals.SetItemText(0,3,strMessage);
strMessage.LoadStringA(IDS_STRING112);
m_Grid_signals.SetItemText(0,4,strMessage);
for(int i=1;i<64;i++)
{
m_Grid_signals.SetRowHeight(i,0);
}
//初始化发送表格
m_Grid_senddata.SetEditable(TRUE);
m_Grid_senddata.SetColumnCount(14);
m_Grid_senddata.SetRowCount(201);
m_Grid_senddata.SetDefCellHeight(15);
m_Grid_senddata.SetDefCellWidth(30);
m_Grid_senddata.SetDefCellMargin(1);
m_Grid_senddata.SetFixedRowCount();
m_Grid_senddata.SetBkColor(RGB(0xf0,0xf0,0xf0));
m_Grid_senddata.SetColumnWidth(0,70);
m_Grid_senddata.SetColumnWidth(1,45);
m_Grid_senddata.SetColumnWidth(2,40);
m_Grid_senddata.SetColumnWidth(3,50);
m_Grid_senddata.SetColumnWidth(4,80);
m_Grid_senddata.SetColumnWidth(5,25);
m_Grid_senddata.SetColumnWidth(6,25);
m_Grid_senddata.SetColumnWidth(7,25);
m_Grid_senddata.SetColumnWidth(8,25);
m_Grid_senddata.SetColumnWidth(9,25);
m_Grid_senddata.SetColumnWidth(10,25);
m_Grid_senddata.SetColumnWidth(11,25);
m_Grid_senddata.SetColumnWidth(12,25);
m_Grid_senddata.SetColumnWidth(13,18);
m_Grid_senddata.SetTextBkColor(RGB(240,240,240));
//set all cells read only
{
for(int i=0;i<201;i++)
{
for(int j=0;j<14;j++)
{
m_Grid_senddata.SetItemState(i,j,m_Grid_senddata.GetItemState(i,j) | GVIS_READONLY);
}
}
}
strMessage.LoadStringA(IDS_STRING123);
m_Grid_senddata.SetItemText(0,0,strMessage);
strMessage.LoadStringA(IDS_STRING124);
m_Grid_senddata.SetItemText(0,1,strMessage);
strMessage.LoadStringA(IDS_STRING125);
m_Grid_senddata.SetItemText(0,2,strMessage);
strMessage.LoadStringA(IDS_STRING126);
m_Grid_senddata.SetItemText(0,3,strMessage);
strMessage.LoadStringA(IDS_STRING127);
m_Grid_senddata.SetItemText(0,4,strMessage);
strMessage.LoadStringA(IDS_STRING128);
m_Grid_senddata.SetItemText(0,5,strMessage);
strMessage.LoadStringA(IDS_STRING129);
m_Grid_senddata.SetItemText(0,6,strMessage);
strMessage.LoadStringA(IDS_STRING130);
m_Grid_senddata.SetItemText(0,7,strMessage);
strMessage.LoadStringA(IDS_STRING131);
m_Grid_senddata.SetItemText(0,8,strMessage);
strMessage.LoadStringA(IDS_STRING132);
m_Grid_senddata.SetItemText(0,9,strMessage);
strMessage.LoadStringA(IDS_STRING133);
m_Grid_senddata.SetItemText(0,10,strMessage);
strMessage.LoadStringA(IDS_STRING134);
m_Grid_senddata.SetItemText(0,11,strMessage);
strMessage.LoadStringA(IDS_STRING135);
m_Grid_senddata.SetItemText(0,12,strMessage);
if(!m_Picture_logo.Load(MAKEINTRESOURCE(IDR_JPEG_RUNSTOP),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_logo.Draw();
if(!m_Picture_about.Load(MAKEINTRESOURCE(IDR_JPEG_ABOUT),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_about.Draw();
if(!m_Picture_help.Load(MAKEINTRESOURCE(IDR_JPEG_HELP),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_help.Draw();
if(language == 1)
{
if(!m_Picture_lang.Load(MAKEINTRESOURCE(IDR_JPEG_CHN),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_lang.Draw();
}
else
{
if(!m_Picture_lang.Load(MAKEINTRESOURCE(IDR_JPEG_ENG),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_lang.Draw();
}
strMessage.LoadStringA(IDS_VERSION);
m_sta_versionno.SetWindowText(strMessage);
strMessage.LoadStringA(IDS_STRING120);
m_listbox_dm.AddString(strMessage);
strMessage.LoadStringA(IDS_STRING121);
m_listbox_dm.AddString(strMessage);
UpdateData(FALSE);
if(readDbcFile()==0)
{
initCANList();
}
return TRUE; // return TRUE unless you set the focus to a control
}
void CXlCANcontrolDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CXlCANcontrolDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CXlCANcontrolDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CXlCANcontrolDlg::OnOnbus()
{
int nIndex=0;
XLstatus xlStatus;
unsigned long bitrate[2] = {250000, 500000};
UpdateData(TRUE);
nIndex =m_commo_hz.GetCurSel();
xlStatus = m_CAN.CANGoOnBus(bitrate[nIndex]);
if (!xlStatus) {
m_btnOnBus.EnableWindow(FALSE);
m_btnOffBus.EnableWindow(TRUE);
m_Baudrate.EnableWindow(FALSE);
m_btnSend.EnableWindow(TRUE);
m_Channel.EnableWindow(TRUE);
//m_Output.InsertString(-1,"Successfully GoOnBus");
}
else
{
strMessage.LoadStringA(IDS_NOCANDEV);
AfxMessageBox(strMessage);
exit(-1);
//m_Output.InsertString(-1,"Error: GoOnBus");
}
}
void CXlCANcontrolDlg::OnOffbus()
{
XLstatus xlStatus;
m_btnOnBus.EnableWindow(TRUE);
m_btnOffBus.EnableWindow(FALSE);
m_Baudrate.EnableWindow(TRUE);
m_btnSend.EnableWindow(FALSE);
m_Channel.EnableWindow(FALSE);
xlStatus = m_CAN.CANGoOffBus();
/* if (!xlStatus) m_Output.InsertString(-1,"Successfully GoOffBus");
else m_Output.InsertString(-1,"Error: GoOffBus");*/
}
void CXlCANcontrolDlg::OnSend()
{
UpdateData(TRUE);
//AfxMessageBox("sending");
XLevent xlEvent;
memset(&xlEvent, 0, sizeof(xlEvent));
xlEvent.tag = XL_TRANSMIT_MSG;
xlEvent.tagData.msg.id = strtoul(m_eID,NULL,16);
xlEvent.tagData.msg.dlc = (unsigned short)atoi(m_eDLC);
xlEvent.tagData.msg.flags = 0;
xlEvent.tagData.msg.data[0] = strtoul(m_eD00,NULL,16);
xlEvent.tagData.msg.data[1] = strtoul(m_eD01,NULL,16);
xlEvent.tagData.msg.data[2] = strtoul(m_eD02,NULL,16);
xlEvent.tagData.msg.data[3] = strtoul(m_eD03,NULL,16);
xlEvent.tagData.msg.data[4] = strtoul(m_eD04,NULL,16);
xlEvent.tagData.msg.data[5] = strtoul(m_eD05,NULL,16);
xlEvent.tagData.msg.data[6] = strtoul(m_eD06,NULL,16);
xlEvent.tagData.msg.data[7] = strtoul(m_eD07,NULL,16);
if (m_ExtID) xlEvent.tagData.msg.id |= XL_CAN_EXT_MSG_ID;
m_CAN.CANSend(xlEvent, m_Channel.GetCurSel() );
}
void CXlCANcontrolDlg::OnReset()
{
m_CAN.CANResetFilter();
}
void CXlCANcontrolDlg::OnSetfilter()
{
UpdateData(TRUE);
m_CAN.CANSetFilter((unsigned long) atoi(m_eFilterFrom), (unsigned long) atoi(m_eFilterTo) );
}
void CXlCANcontrolDlg::OnClear()
{
m_Output.ResetContent();
}
void CXlCANcontrolDlg::OnAbout()
{
CAboutDlg a;
a.DoModal();
}
void CXlCANcontrolDlg::OnLicInfo()
{
m_CAN.ShowLicenses();
}
void CXlCANcontrolDlg::OnStnClickedStaticPicLogo()
{
// TODO: Add your control notification handler code here
//AfxMessageBox("Running");
if(bRun==false){
if(CheckCANdecive()!=0)
exit(-1);
m_Output.ResetContent();
bRun=true;
//开启所有定时器
IgnitionOnSetTimers();
startTime = 0;
if(!m_Picture_logo.Load(MAKEINTRESOURCE(IDR_JPEG_STOPRUN),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_logo.Draw();
int rowcounter = m_Grid_message.GetRowCount();
for(int i=1;i<rowcounter-1;i++)
m_Grid_message.SetItemText(i,1,"Last Measurment");
m_Output.InsertString(-1, " 0.000000 Start of measurement");
OnOnbus();
}
else
{
bRun=false;
//关闭所有定时器
IgnitionOffKillTimers();
if(!m_Picture_logo.Load(MAKEINTRESOURCE(IDR_JPEG_RUNSTOP),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_logo.Draw();
OnOffbus();
}
}
void CXlCANcontrolDlg::OnStnClickedStaticAbout()
{
// TODO: Add your control notification handler code here
CString about="";
strMessage.LoadStringA(IDS_ABOUT_UP);
about += strMessage;
strMessage.LoadStringA(IDS_VERSION);
about += strMessage;
strMessage.LoadStringA(IDS_ABOUT_DOWN);
about += strMessage;
AfxMessageBox(about);
}
void CXlCANcontrolDlg::OnStnClickedStaticHelp()
{
// TODO: Add your control notification handler code here
CString str;
CString strPath;
strPath==GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
str.ReleaseBuffer();
strPath.Format("%s\\iCANViewer使用说明.doc",str);
HINSTANCE hTxt = ShellExecute(NULL,"open","iCANViewer使用说明.doc"," ",str,SW_SHOW);
int exec_success = (int)hTxt;
if(exec_success>31)
;
else
{
strPath.Format("%s\\help.txt",str);
hTxt = ShellExecute(NULL,"open","help.txt"," ",str,SW_SHOW);
exec_success = (int)hTxt;
if(exec_success<32)
{
strMessage.LoadStringA(IDS_HELP);
AfxMessageBox(strMessage);
}
}
}
void CXlCANcontrolDlg::OnStnClickedStaticLang()
{
// TODO: Add your control notification handler code here
CString str;
char strbuf[50];
DWORD change;
CString strPath;
change=GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
strPath.Format("%s\\customer.ini",str);
if(language==0)
{
/*if(!m_Picture_lang.Load(MAKEINTRESOURCE(IDR_JPEG_ENG),_T("JPEG")))
{
strMessage.LoadStringA(IDS_STRING102);
AfxMessageBox(strMessage);
}
else
m_Picture_lang.Draw();*/
m_bRestartFlag = TRUE;
WritePrivateProfileString("UserInterface","lang","1",strPath);
PostMessage(WM_CLOSE, 0, 0);
}
else
{
m_bRestartFlag = TRUE;
WritePrivateProfileString("UserInterface","lang","0",strPath);
PostMessage(WM_CLOSE, 0, 0);
}
}
int CXlCANcontrolDlg::initCANList(void)
{
CStdioFile file_read;
CString str;
int i = 1;
if(!file_read.Open("id_names",CFile::typeText|CFile::modeRead))
{
AfxMessageBox("open id_names file error");
file_read.Close();
return -1;
}
else
{
while(file_read.ReadString(str))
{
m_Grid_message.SetItemText(i,2,str);
file_read.ReadString(str);
m_Grid_message.SetItemText(i,3,str);
m_Grid_message.SetRowHeight(i,0);
m_Grid_message.InsertRow("");
i++;
}
m_Grid_message.Refresh();
file_read.Close();
}
return 0;
}
void CXlCANcontrolDlg::OnOnceClick(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNMHDR;
if(pItem->iRow==0)
return;
CString id = m_Grid_message.GetItemText(pItem->iRow,2);
CString name = m_Grid_message.GetItemText(pItem->iRow,3);
if(id!="" && name=="")
{
for(int i=1;i<64;i++)
{
m_Grid_signals.SetRowHeight(i,0);
}
m_Grid_signals.Refresh();
//MessageBox("This Message is not in the dcb database");
}
CString data = m_Grid_message.GetItemText(pItem->iRow,5);
data.Replace(" ","");//clear the blanks in data
//MessageBox(data);
ShowSignals(id,data,name);
}
void CXlCANcontrolDlg::ShowSignals(CString id,CString data,CString name)
{
int i =1;
CString binaryData = HexStr2Binarystr(data);
CStdioFile file;
CString str;
if(!file.Open("id_signals",CFile::typeText|CFile::modeRead))
{
AfxMessageBox("open id_signals file error");
return;
}
else
{
if(name==CString("#DM1 Error"))
{
CString strTmp;
CString strSPN = binaryData.Mid(32,3)+binaryData.Mid(24,8)+binaryData.Mid(16,8);
strSPN = strSPN.MakeReverse();
strSPN = Binarystr2HexStr(strSPN,0);
long spn = strtoul(strSPN,NULL,16);
CString strFMI = binaryData.Mid(35,5);
strFMI =strFMI.MakeReverse();
strFMI = Binarystr2HexStr(strFMI,0);
long fmi = strtoul(strFMI,NULL,16);
CString strOOC = binaryData.Mid(41,7);
strOOC = strOOC.MakeReverse();
strOOC = Binarystr2HexStr(strOOC,0);
long ooc = strtoul(strOOC,NULL,16);
m_Grid_signals.SetItemText(1,0,"SPN");
m_Grid_signals.SetItemText(1,1,strSPN);
strTmp.Format("%ld",spn);
m_Grid_signals.SetItemText(1,2,strTmp);
m_Grid_signals.SetItemText(1,3,"\"\"");
m_Grid_signals.SetRowHeight(1,30);
m_Grid_signals.SetItemText(2,0,"FMI");
m_Grid_signals.SetItemText(2,1,strFMI);
strTmp.Format("%ld",fmi);
m_Grid_signals.SetItemText(2,2,strTmp);
m_Grid_signals.SetItemText(2,3,"\"\"");
m_Grid_signals.SetRowHeight(2,30);
m_Grid_signals.SetItemText(3,0,"OCC");
m_Grid_signals.SetItemText(3,1,strOOC);
strTmp.Format("%ld",ooc);
m_Grid_signals.SetItemText(3,2,strTmp);
m_Grid_signals.SetItemText(3,3,"\"\"");
m_Grid_signals.SetRowHeight(3,30);
m_Grid_signals.Refresh();
//MessageBox(strOOC);
return;
}
while(file.ReadString(str))
{
if((str)==id)
{
while(file.ReadString(str) && strlen(str)!=0)
{
m_Grid_signals.SetItemText(i,0,str);
file.ReadString(str);
int order = atoi(str);
file.ReadString(str);
int start = atoi(str);
file.ReadString(str);
int length = atoi(str);
file.ReadString(str);
float factor = atof(str);
file.ReadString(str);
float offset = atof(str);
file.ReadString(str);//min
file.ReadString(str);//max
file.ReadString(str);//unit
m_Grid_signals.SetItemText(i,3,str);
if(order == 0)
{
if (length>7)
start = start - 7;
else
start = start- ((start%8)*2-7);
}
CString bits = binaryData.Mid(start,length);
bits = bits.MakeReverse();
//MessageBox(bits);
CString strRaw = Binarystr2HexStr(bits,order);
m_Grid_signals.SetItemText(i,1,strRaw);
int raw = strtoul(strRaw,NULL,16);
float physical = raw * factor + offset;
CString strPhy;
strPhy.Format("%.2f",physical);
m_Grid_signals.SetItemText(i,2,strPhy);
m_Grid_signals.SetRowHeight(i,30);
i++;
}
m_Grid_signals.Refresh();
}
else
{
file.ReadString(str);
while(strlen(str)!=0)
{
file.ReadString(str);
}
}
}
for(;i<64;i++)
{
m_Grid_signals.SetItemText(i,0,"");
m_Grid_signals.SetRowHeight(i,0);
}
//m_Grid_message.Refresh();
file.Close();
}
//m_Grid_signals.SetItemText(1,2,"1214124");
//m_Grid_signals.Refresh();
}
CString CXlCANcontrolDlg::HexStr2Binarystr(CString str)
{
CString strResult="";
int length = strlen(str);
for(int i = 0;i<length;)
{
CString HexStr= str.Mid(i,2);
long value;
sscanf(HexStr,"%X",&value);
char c[10];
itoa(value,c,2);
CString Binarystr;
Binarystr.Format("%08s",c);
strResult+=Binarystr;
i += 2;
}
return strResult;
}
CString CXlCANcontrolDlg::Binarystr2HexStr(CString str,int order)
{
CString result = "";
CString strTmp;
CString tmp;
int tmpValue;
int value = 0;
int length = strlen(str);
for(int i=0;i<length;i++)
{
strTmp = str.Mid(i,1);
int tmpValue = atoi(strTmp);
value += tmpValue * _Pow_int(2,i);
}
result.Format("%2X",value);
int length_r = strlen(result);
if(length_r%2!=0)
{
length += 1;
result="0"+result;
}
//MessageBox(result);
CString result_ok = "";
for(int j = 0;j<length_r;)
{
result_ok = result.Mid(j,2) + result_ok ;
j=j+2;
}
if(order==0)
return result;
else
return result_ok;
}
int CXlCANcontrolDlg::readDbcFile(void) //从dbc文件中读取配置,生成idnames 和 idsignals
{
CFileDialog fileDlg(true);
fileDlg.m_ofn.lpstrTitle="Open Cluster DBC file(Generated by CANoe)";
fileDlg.m_ofn.lpstrFilter="dbc files(*.dbc)\0*.dbc\0All files(*.*)\0*.*\0\0";
//获得当前路径
CString str;
GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
//设置CFileDialog默认路径
fileDlg.m_ofn.lpstrInitialDir=str;
CString strPath;
if(fileDlg.DoModal()==IDOK)
{
DWORD change=GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
CString str;
char strbuf[50];
strPath=fileDlg.GetPathName();
}
else
{
strPath="my.dbc";
}
FILE *fp;
if ((fp = fopen("id_signals", "w")) == NULL)
{
printf("Open dump file ERROR");
return -3;
}
FILE *fp1;
if ((fp1 = fopen("id_names", "w")) == NULL)
{
printf("Open dump file ERROR");
return -4;
}
CStdioFile file;
if(!file.Open(strPath,CFile::typeText|CFile::modeRead))
{
AfxMessageBox("open dbc file error");
return -1;
}
file.ReadString(str);
if(str!="VERSION \"\"")
{
AfxMessageBox("not a legal dbc file");
file.Close();
return -2;
}
while(file.ReadString(str)){
str = str.Mid(0,4);
if(str=="BU_:")
{
file.ReadString(str);
file.ReadString(str);
while(file.ReadString(str))
{
if(str=="")
{
file.ReadString(str);
CString striFlag;
striFlag.Mid(0,3);
if(striFlag!="BO_")
{
file.Close();
fclose(fp);
fclose(fp1);
return 0;
}
}
else
{
CString strFlag;
CString strID;
CString strName;
AfxExtractSubString( strFlag, str, 0, _T( ' ' ) );
//AfxMessageBox(strFlag);
AfxExtractSubString( strID, str, 1, _T( ' ' ) );
long id =strtoul(strID,0,10);
AfxExtractSubString( strName, str, 2, _T( ' ' ) );
strName = strName.Left(strlen(strName)-1);
//AfxMessageBox(strName);
if(id>0x80000000)
{
id = id - 0x80000000;
strID.Format("%lxx",id);
}
else
strID.Format("%lx",id);
//AfxMessageBox(strID);
fprintf(fp1, strID+"\n");
fprintf(fp, strID+"\n");
fprintf(fp1, strName+"\n");
while(file.ReadString(str))
{
CString tmpstr;
tmpstr = str.Mid(0,3);
if(tmpstr=="BO_")
{
file.Close();
fclose(fp);
fclose(fp1);
return 0;
}
if(str!="")
{
//AfxMessageBox(str);
CString strSigName;
CString strCons;
CString strFac_offset;
CString strMM;
CString strUnit;
AfxExtractSubString( strSigName, str, 2, _T( ' ' ) );
AfxExtractSubString( strCons, str, 4, _T( ' ' ) );
AfxExtractSubString( strFac_offset, str, 5, _T( ' ' ) );
AfxExtractSubString( strMM, str, 6, _T( ' ' ) );
AfxExtractSubString( strUnit, str, 7, _T( ' ' ) );
//AfxMessageBox(strUnit);
CString strOrder;
CString strConsSB;
CString strConsLEN;
AfxExtractSubString( strConsSB, strCons,0, _T( '|' ) );
AfxExtractSubString( strConsLEN, strCons,1, _T( '|' ) );
AfxExtractSubString( strOrder, strConsLEN,1, _T( '@' ) );
strOrder=strOrder.Left(1);
//AfxMessageBox(strOrder);
AfxExtractSubString( strConsLEN, strConsLEN,0, _T( '@' ) );
//AfxMessageBox(strConsLEN);
CString strFAC;
CString strOFF;
AfxExtractSubString( strFAC, strFac_offset,0, _T( ',' ) );
strFAC=strFAC.Mid(1,strlen(strFAC));
//AfxMessageBox(strFAC);
AfxExtractSubString( strOFF, strFac_offset,1, _T( ',' ) );
strOFF=strOFF.Mid(0,strlen(strOFF)-1);
//AfxMessageBox(strOFF);
CString strMIN;
CString strMAX;
AfxExtractSubString( strMIN, strMM,0, _T( '|' ) );
strMIN=strMIN.Mid(1,strlen(strMIN));
//AfxMessageBox(strMIN);
AfxExtractSubString( strMAX, strMM,1, _T( '|' ) );
strMAX=strMAX.Mid(0,strlen(strMAX)-1);
//AfxMessageBox(strMAX);
fprintf(fp, strSigName+"\n");
fprintf(fp, strOrder+"\n");
fprintf(fp, strConsSB+"\n");
fprintf(fp, strConsLEN+"\n");
fprintf(fp, strFAC+"\n");
fprintf(fp, strOFF+"\n");
fprintf(fp, strMIN+"\n");
fprintf(fp, strMAX+"\n");
fprintf(fp, strUnit+"\n");
}
else
{
fprintf(fp,"\n");
break;
}
}
}
}
}
}
file.Close();
fclose(fp);
fclose(fp1);
return -999;
}
void CXlCANcontrolDlg::OnBnClickedButtonExport()
{
// TODO: Add your control notification handler code here
CFileDialog fileDlg(false);
fileDlg.m_ofn.lpstrTitle="Output CANoe Based Asc Log File";
fileDlg.m_ofn.lpstrFilter="asc files(*.asc)\0*.asc\0All files(*.*)\0*.*\0\0";
fileDlg.m_ofn.lpstrDefExt="asc";
//获得当前路径
CString str;
GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
//设置CFileDialog默认路径
fileDlg.m_ofn.lpstrInitialDir=str;
if(m_Output.GetCount()==0)
{
strMessage.LoadStringA(IDS_STRING122);
MessageBox(strMessage);
return;
}
if(fileDlg.DoModal()==IDOK)
{
char s[20];
CString sendid,recvid;
CString str;
CString strPath;
strPath=fileDlg.GetPathName();
freopen(strPath,"w",stdout);
std::cout<<"base hex timestamps absolute"<<std::endl;
for( int lp = 0;lp < m_Output.GetCount(); lp++ )
{
CString s;
m_Output.GetText(lp,s);
//MessageBox(s);
std::cout<<s<<std::endl;
}
strMessage.LoadStringA(IDS_STRING_LOG_DONE);
MessageBox(strMessage);
fclose(stdout);
}
else
{
//MessageBox("Canceled the Outputting");
fclose(stdout);
}
}
void CXlCANcontrolDlg::OnBnClickedCheckAdvanced()
{
// TODO: Add your control notification handler code here
UpdateData(true);
if(m_check_advance==1)
{
m_commo_channel.ShowWindow(1);
m_commo_hz.ShowWindow(1);
m_btn_restart.ShowWindow(1);
m_sta_caution.ShowWindow(1);
}
else
{
m_commo_channel.ShowWindow(0);
m_commo_hz.ShowWindow(0);
m_btn_restart.ShowWindow(0);
m_sta_caution.ShowWindow(0);
}
}
void CXlCANcontrolDlg::OnBnClickedButtonRestart()
{
// TODO: Add your control notification handler code here
int channelnum = m_commo_channel.GetCurSel();
int baudnum = m_commo_hz.GetCurSel();
CString str;
char strbuf[50];
DWORD change;
CString strPath;
change=GetCurrentDirectory(MAX_PATH,str.GetBuffer(MAX_PATH));
strPath.Format("%s\\customer.ini",str);
str.Format("%d",channelnum);
WritePrivateProfileString("HW Config","channel",str,strPath);
str.Format("%d",baudnum);
WritePrivateProfileString("HW Config","baudtype",str,strPath);
m_bRestartFlag = TRUE;
PostMessage(WM_CLOSE, 0, 0);
}
void CXlCANcontrolDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
if (m_bRestartFlag)
{
CString strFileName = _T("");
GetModuleFileName(NULL, strFileName.GetBuffer(MAX_PATH), MAX_PATH);
ShellExecute(NULL, _T(""), strFileName, NULL, NULL, SW_SHOWNORMAL);
strFileName.ReleaseBuffer();
}
CDialog::OnClose();
}
int CXlCANcontrolDlg::CheckCANdecive(void)
{
XLstatus xlStatus = xlOpenDriver();
if (xlStatus != XL_SUCCESS) {
MessageBox("No XL DLL availble!!!click ok to exit the program");
return -1;
}
XLdriverConfig xlDrvConfig;
xlGetDriverConfig(&xlDrvConfig);
if( xlDrvConfig.channelCount<3)
{
MessageBox(" No CAN Hardware!!!click ok to exit the program ");
return -2;
}
else
return 0;
}
void CXlCANcontrolDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
XLevent xlEvent;
xlEvent.tag = XL_TRANSMIT_MSG;
xlEvent.tagData.msg.id = gridMessageList[nIDEvent].id;
xlEvent.tagData.msg.dlc = gridMessageList[nIDEvent].dlc;
xlEvent.tagData.msg.flags = 0;
xlEvent.tagData.msg.data[0] = gridMessageList[nIDEvent].d0;
xlEvent.tagData.msg.data[1] = gridMessageList[nIDEvent].d1;
xlEvent.tagData.msg.data[2] = gridMessageList[nIDEvent].d2;
xlEvent.tagData.msg.data[3] = gridMessageList[nIDEvent].d3;
xlEvent.tagData.msg.data[4] = gridMessageList[nIDEvent].d4;
xlEvent.tagData.msg.data[5] = gridMessageList[nIDEvent].d5;
xlEvent.tagData.msg.data[6] = gridMessageList[nIDEvent].d6;
xlEvent.tagData.msg.data[7] = gridMessageList[nIDEvent].d7;
if (gridMessageList[nIDEvent].ext)
xlEvent.tagData.msg.id |= XL_CAN_EXT_MSG_ID;
m_CAN.CANSend(xlEvent,gridMessageList[nIDEvent].ch-1);
CDialog::OnTimer(nIDEvent);
}
void CXlCANcontrolDlg::OnRClick(NMHDR* pNMHDR, LRESULT* pResult)
{
}
void CXlCANcontrolDlg::OnDoubleClick(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_GRIDVIEW* pItem = (NM_GRIDVIEW*) pNMHDR;
if(pItem->iRow==0)
return;
if(m_Grid_senddata.GetItemText(pItem->iRow,pItem->iColumn)=="N.A" && bRun)
{
XLevent xlEvent;
bool bExtId;
memset(&xlEvent, 0, sizeof(xlEvent));
CString strId = m_Grid_senddata.GetItemText(pItem->iRow,0);
if(strId.Right(1)=="x" || strId.Right(1)=="X")
{
strId = strId.Left(strId.GetLength()-1);
bExtId = true;
}
xlEvent.tag = XL_TRANSMIT_MSG;
xlEvent.tagData.msg.id = strtoul(strId,NULL,16);
xlEvent.tagData.msg.dlc = (unsigned short)atoi(m_Grid_senddata.GetItemText(pItem->iRow,2));
xlEvent.tagData.msg.flags = 0;
xlEvent.tagData.msg.data[0] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,5),NULL,16);
xlEvent.tagData.msg.data[1] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,6),NULL,16);
xlEvent.tagData.msg.data[2] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,7),NULL,16);
xlEvent.tagData.msg.data[3] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,8),NULL,16);
xlEvent.tagData.msg.data[4] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,9),NULL,16);
xlEvent.tagData.msg.data[5] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,10),NULL,16);
xlEvent.tagData.msg.data[6] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,11),NULL,16);
xlEvent.tagData.msg.data[7] = strtoul(m_Grid_senddata.GetItemText(pItem->iRow,12),NULL,16);
if (bExtId) xlEvent.tagData.msg.id |= XL_CAN_EXT_MSG_ID;
int channel = atoi(m_Grid_senddata.GetItemText(pItem->iRow,1).Right(1));
m_CAN.CANSend(xlEvent,channel-1);
}
}
//click "new" button to new a send message row, and it will do some intialization
void CXlCANcontrolDlg::OnBnClickedButtonNewmess()
{
// TODO: Add your control notification handler code here
m_Grid_senddata.SetItemState(curNewAddRow,0,m_Grid_senddata.GetItemState(curNewAddRow,0) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,0,RGB(255,255,255));
m_Grid_senddata.SetItemState(curNewAddRow,1,m_Grid_senddata.GetItemState(curNewAddRow,1) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,1,RGB(255,255,255));
m_Grid_senddata.SetCellType(curNewAddRow,1,RUNTIME_CLASS(CGridCellCombo));//设置Combo
CStringArray options1;
options1.Add(_T("CH1"));
options1.Add(_T("CH2"));
options1.Add(_T("CH3"));
options1.Add(_T("CH4"));
CGridCellCombo *combo1 = (CGridCellCombo*)(m_Grid_senddata.GetCell(curNewAddRow,1));
combo1->SetOptions(options1);
combo1->SetText(options1.GetAt(0));
m_Grid_senddata.SetItemState(curNewAddRow,2,m_Grid_senddata.GetItemState(curNewAddRow,2) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,2,RGB(255,255,255));
m_Grid_senddata.SetCellType(curNewAddRow,2,RUNTIME_CLASS(CGridCellCombo));//设置Combo
CStringArray options2;
options2.Add(_T("1"));
options2.Add(_T("2"));
options2.Add(_T("3"));
options2.Add(_T("4"));
options2.Add(_T("5"));
options2.Add(_T("6"));
options2.Add(_T("7"));
options2.Add(_T("8"));
CGridCellCombo *combo2 = (CGridCellCombo*)(m_Grid_senddata.GetCell(curNewAddRow,2));
combo2->SetOptions(options2);
combo2->SetText(options2.GetAt(7));
m_Grid_senddata.SetItemBkColour(curNewAddRow,3,curNewAddRow % 2==0?RGB(191,205,219):RGB(228,238,248));
m_Grid_senddata.SetItemText(curNewAddRow,3,"N.A");
m_Grid_senddata.SetItemState(curNewAddRow,4,m_Grid_senddata.GetItemState(curNewAddRow,4) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,4,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,4,"1000");
m_Grid_senddata.SetItemState(curNewAddRow,5,m_Grid_senddata.GetItemState(curNewAddRow,5) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,5,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,5,"00");
m_Grid_senddata.SetItemState(curNewAddRow,6,m_Grid_senddata.GetItemState(curNewAddRow,6) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,6,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,6,"00");
m_Grid_senddata.SetItemState(curNewAddRow,7,m_Grid_senddata.GetItemState(curNewAddRow,7) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,7,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,7,"00");
m_Grid_senddata.SetItemState(curNewAddRow,8,m_Grid_senddata.GetItemState(curNewAddRow,8) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,8,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,8,"00");
m_Grid_senddata.SetItemState(curNewAddRow,9,m_Grid_senddata.GetItemState(curNewAddRow,9) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,9,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,9,"00");
m_Grid_senddata.SetItemState(curNewAddRow,10,m_Grid_senddata.GetItemState(curNewAddRow,10) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,10,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,10,"00");
m_Grid_senddata.SetItemState(curNewAddRow,11,m_Grid_senddata.GetItemState(curNewAddRow,11) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,11,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,11,"00");
m_Grid_senddata.SetItemState(curNewAddRow,12,m_Grid_senddata.GetItemState(curNewAddRow,12) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,12,RGB(255,255,255));
m_Grid_senddata.SetItemText(curNewAddRow,12,"00");
m_Grid_senddata.SetItemState(curNewAddRow,13,m_Grid_senddata.GetItemState(curNewAddRow,13) & ~GVIS_READONLY);
m_Grid_senddata.SetItemBkColour(curNewAddRow,13,RGB(255,255,255));
m_Grid_senddata.SetCellType(curNewAddRow,13,RUNTIME_CLASS(CGridCellCheck));//设置CheckBox
m_Grid_senddata.Refresh();
m_Grid_senddata.SetFocusCell(curNewAddRow,0);
curNewAddRow++;
}
//when the application turns form stop to run, gvie every checked can send message a timer, the timer will send the checked message cyclicly
void CXlCANcontrolDlg::IgnitionOnSetTimers()
{
for (int i=1;i<curNewAddRow;i++)
{
if(((CGridCellCheck*)m_Grid_senddata.GetCell(i,13))->GetCheck())
{
CString strId = m_Grid_senddata.GetItemText(i,0);
if(strId.Right(1)=="x" || strId.Right(1)=="X")
{
strId = strId.Left(strId.GetLength()-1);
gridMessageList[i].ext = true;
}
else
gridMessageList[i].ext = false;
gridMessageList[i].ch =(byte) (atoi(m_Grid_senddata.GetItemText(i,1).Right(1)));
gridMessageList[i].dlc = (unsigned short)atoi(m_Grid_senddata.GetItemText(i,2));
gridMessageList[i].id = strtoul(strId,NULL,16);
gridMessageList[i].d0 = strtoul(m_Grid_senddata.GetItemText(i,5),NULL,16);
gridMessageList[i].d1 = strtoul(m_Grid_senddata.GetItemText(i,6),NULL,16);
gridMessageList[i].d2 = strtoul(m_Grid_senddata.GetItemText(i,7),NULL,16);
gridMessageList[i].d3 = strtoul(m_Grid_senddata.GetItemText(i,8),NULL,16);
gridMessageList[i].d4 = strtoul(m_Grid_senddata.GetItemText(i,9),NULL,16);
gridMessageList[i].d5 = strtoul(m_Grid_senddata.GetItemText(i,10),NULL,16);
gridMessageList[i].d6 = strtoul(m_Grid_senddata.GetItemText(i,11),NULL,16);
gridMessageList[i].d7 = strtoul(m_Grid_senddata.GetItemText(i,12),NULL,16);
SetTimer(i,atoi(m_Grid_senddata.GetItemText(i,4)),NULL);
timerQueue[i-1] = 1;
}
}
}
//IgnitionOffKillTimers
void CXlCANcontrolDlg::IgnitionOffKillTimers()
{
for(int i=0;i<200;i++)
{
if(timerQueue[i]!=0)
KillTimer(i+1);
}
memset(timerQueue,0,200);
}<file_sep>// GridCellNumeric.h: interface for the CGridCellHexPlusX class.
//
// Written by <NAME> [<EMAIL>]
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_GRIDHEXPLUSXCELL_H__3479ED0D_B57D_4940_B83D_9E2296ED75B5__INCLUDED_)
#define AFX_GRIDHEXPLUSXCELL_H__3479ED0D_B57D_4940_B83D_9E2296ED75B5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "../GridCtrl_src/GridCell.h"
#include "../GridCtrl_src/inplaceedit.h"
class CGridCellHexPlusX : public CGridCell
{
friend class CGridCtrl;
DECLARE_DYNCREATE(CGridCellHexPlusX)
public:
CGridCellHexPlusX();
// editing cells
public:
virtual BOOL Edit(int nRow, int nCol, CRect rect, CPoint point, UINT nID, UINT nChar);
virtual void EndEdit();
};
/////////////////////////////////////////////////////////////////////////////
// CInPlaceHex window
class CInPlaceHex : public CInPlaceEdit
{
// Construction
public:
CInPlaceHex(CWnd* pParent, CRect& rect, DWORD dwStyle, UINT nID,
int nRow, int nColumn, CString sInitText, UINT nFirstChar);
virtual ~CInPlaceHex();
// Generated message map functions
protected:
//{{AFX_MSG(CInPlaceList)
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
//}}AFX_MSG
//afx_msg void OnSelendOK();
DECLARE_MESSAGE_MAP()
};
#endif // !defined(AFX_AFX_GRIDHEXPLUSXCELL_H__3479ED0D_B57D_4940_B83D_9E2296ED75B5__INCLUDED_)<file_sep>//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by xlCANcontrol.rc
//
#define IDM_ABOUTBOX 0x0010
#define IDD_ABOUTBOX 100
#define IDS_ABOUTBOX 101
#define IDD_XLCANCONTROL_DIALOG 102
#define IDS_STRING102 102
#define IDS_STRING103 103
#define IDS_STRING104 104
#define IDS_STRING105 105
#define IDS_STRING106 106
#define IDS_STRING107 107
#define IDS_STRING108 108
#define IDS_STRING109 109
#define IDS_STRING110 110
#define IDS_STRING111 111
#define IDS_STRING112 112
#define IDS_STRING_COPYRIGHT 113
#define IDS_VERSION 114
#define IDS_ABOUT_UP 115
#define IDS_ABOUT_DOWN 116
#define IDS_HELP 117
#define IDS_NOCANDEV 118
#define IDS_STRING_LOG_DONE 119
#define IDS_STRING120 120
#define IDS_STRING121 121
#define IDS_STRING122 122
#define IDR_JPEG_RUNSTOP 136
#define IDR_JPEG_STOPRUN 137
#define IDR_JPEG_ABOUT 138
#define IDR_JPEG_HELP 139
#define IDR_JPEG_CHN 140
#define IDR_JPEG_ENG 141
#define IDB_BITMAP_IBUS 142
#define IDI_ICON1 146
#define IDC_OUTPUT 1000
#define IDC_SEND 1001
#define IDC_BAUDRATE 1002
#define IDC_ONBUS 1003
#define IDC_OFFBUS 1004
#define IDC_CHANNEL 1005
#define IDC_D07 1006
#define IDC_D06 1007
#define IDC_D00 1008
#define IDC_D01 1009
#define IDC_D02 1010
#define IDC_D03 1011
#define IDC_D04 1012
#define IDC_D05 1013
#define IDC_DLC 1014
#define IDC_ID 1015
#define IDC_EXID 1016
#define IDC_HARDWARE 1017
#define IDC_CLEAR 1019
#define IDC_ABOUT 1020
#define IDC_FILTEREX 1021
#define IDC_RESET 1022
#define IDC_FILTERFROM 1023
#define IDC_FILTERTO 1024
#define IDC_SETFILTER 1025
#define IDC_LIC_INFO 1026
#define IDC_CUSTOM_MESSAGE 1027
#define IDC_STATIC_PIC_LOGO 1028
#define IDC_STATIC_ABOUT 1029
#define IDC_STATIC_HELP 1030
#define IDC_STATIC_LANG 1032
#define IDC_CUSTOM_SIGNALS 1033
#define IDC_STATIC_Company 1034
#define IDC_STATIC_VER 1035
#define IDC_STATIC_VER_NO 1036
#define IDC_BUTTON_EXPORT 1037
#define IDC_CHECK_ADVANCED 1038
#define IDC_BUTTON_RESTART 1040
#define IDC_COMBO_CHANNEL 1041
#define IDC_COMBO_HZ 1042
#define IDC_STATIC_CAUTION 1043
#define IDC_LIST1 1044
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 147
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1045
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>--------------------------------------------------------------------------------
xlCANcontrol
for
Windows XP, Windows 2000, Windows 98 and Windows ME
Vector Informatik GmbH, Stuttgart
--------------------------------------------------------------------------------
Date : 31.08.2005
Version : 5.4
--------------------------------------------------------------------------------
Vector Informatik GmbH
Ingersheimer Straße 24
70499 Stuttgart, Germany
Phone: ++49 - 711 - 80670 - 0
Fax: ++49 - 711 - 80670 - 111
--------------------------------------------------------------------------------
xlCANcontrol is a small test application for the CAN functionality on
- CANcardX
- CANcardXL
- CANcaseXL
- CANboardXL
- CANboardXL pxi
For further information look into the 'XL Driver Library - Description.pdf'
document.
<file_sep>[UserInterface]
lang=1
[HW Config]
channel=0
baudtype=0
<file_sep>// GridCellNumeric.cpp: implementation of the CGridCellNumeric class.
//
// Written by <NAME> [<EMAIL>]
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "../GridCtrl_src/GridCtrl.h"
#include "GridCellHexPlusX.h"
IMPLEMENT_DYNCREATE(CGridCellHexPlusX, CGridCell)
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CInPlaceHex::CInPlaceHex(CWnd* pParent, CRect& rect, DWORD dwStyle, UINT nID,
int nRow, int nColumn, CString sInitText, UINT nFirstChar)
{
}
CInPlaceHex::~CInPlaceHex()
{
}
BEGIN_MESSAGE_MAP(CInPlaceHex, CInPlaceEdit)
//{{AFX_MSG_MAP(CInPlaceDateTime)
ON_WM_CHAR()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CInPlaceHex::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
return;
}
// Create a control to do the editing
BOOL CGridCellHexPlusX::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
m_bEditing = TRUE;
// CInPlaceEdit auto-deletes itself
m_pEditWnd = new CInPlaceHex(GetGrid(), rect, /*GetStyle() |*/ ES_NUMBER, nID, nRow, nCol,
GetText(), nChar);
return TRUE;
}
// Cancel the editing.
void CGridCellHexPlusX::EndEdit()
{
if (m_pEditWnd)
((CInPlaceHex*)m_pEditWnd)->EndEdit();
}
<file_sep>/*----------------------------------------------------------------------------
| File : xlCANFunctions.cpp
| Project : Vector CAN Example
|
| Description : Shows the basic CAN functionality for the XL Driver Library
|-----------------------------------------------------------------------------
| $Author: vismra $ $Locker: $ $Revision: 4693 $
| $Header: /VCANDRV/XLAPI/samples/xlCANcontrol/xlCANFunctions.cpp 11 14.11.05 10:59 J鰎g $
|-----------------------------------------------------------------------------
| Copyright (c) 2004 by Vector Informatik GmbH. All rights reserved.
|---------------------------------------------------------------------------*/
#include "stdafx.h"
#include "xlCANcontrol.h"
#include "xlCANFunctions.h"
#include "debug.h"
#include <iostream>//输入输出流
#include "gridctrl_src\gridctrl.h"
extern CGridCtrl m_Grid_message;
extern CListBox m_listbox_dm;
XLuint64 startTime = 0; //startTime,need to be reset in main dlg
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// globals
//////////////////////////////////////////////////////////////////////
TStruct g_th;
BOOL g_bThreadRun;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CCANFunctions::CCANFunctions()
{
m_xlChannelMask[CHAN01] = 0;
m_xlChannelMask[CHAN02] = 0;
}
CCANFunctions::~CCANFunctions()
{
if (m_bInitDone) {
CloseHandle(m_hThread);
CloseHandle(m_hMsgEvent);
m_bInitDone = FALSE;
}
}
////////////////////////////////////////////////////////////////////////////
//! CANInit
//! Open the driver, get the channelmasks and create the RX thread.
//!
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANInit()
{
XLstatus xlStatus = XL_ERROR;
char tmp[100];
m_bInitDone = FALSE;
xlStatus = xlOpenDriver();
sprintf(tmp, "xlOpenDriver, stat: %d", xlStatus);
DEBUG(DEBUG_ADV, tmp);
if (xlStatus != XL_SUCCESS) {
AfxMessageBox("Error when opening driver!\nMaybe the DLL is too old.");
return xlStatus;
}
//--------------------------------------------------------------------------------
//当端口数小于3说明硬件未连接,显示的仅仅是两个虚拟端口,此时不应操作,直接返回错误
//----------------------------------------------------------------------------------
XLdriverConfig xlDrvConfig;
xlGetDriverConfig(&xlDrvConfig);//ouganqi
if( xlDrvConfig.channelCount<3)
return XL_ERROR;
// ---------------------------------------
// Get/Set the application within VHWConf
// ---------------------------------------
xlStatus = canGetChannelMask();
if ( (xlStatus) || (m_xlChannelMask[CHAN01] == 0) || (m_xlChannelMask[CHAN02] == 0) ) return XL_ERROR;
// ---------------------------------------
// Open ONE port for both channels
// ---------------------------------------
xlStatus = canInit();
if (xlStatus) return xlStatus;
// ---------------------------------------
// Create ONE thread for both channels
// ---------------------------------------
xlStatus = canCreateRxThread();
if (xlStatus) return xlStatus;
m_bInitDone = TRUE;
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! canGetChannelMask
//! parse the registry to get the channelmask
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::canGetChannelMask()
{
XLstatus xlStatus = XL_ERROR;
char tmp[100];
// default values
unsigned int hwType = 0;
unsigned int hwIndex = 0;
unsigned int hwChannel = 0;
unsigned int appChannel = 0;
unsigned int busType = XL_BUS_TYPE_CAN;
unsigned int i;
XLdriverConfig xlDrvConfig;
//check for hardware:
xlStatus = xlGetDriverConfig(&xlDrvConfig);
if (xlStatus) return xlStatus;
// we check only if there is an application registered or not.
xlStatus = xlGetApplConfig("xlCANcontrol", CHAN01, &hwType, &hwIndex, &hwChannel, busType);
// xlStatus = xlSetApplConfig("xlCANcontrol", CHAN01,0x15, hwIndex, hwChannel, busType);
xlStatus = xlGetApplConfig("xlCANcontrol", CHAN01, &hwType, &hwIndex, &hwChannel, busType);
// Set the params into registry (default values...!)
if (xlStatus) {
DEBUG(DEBUG_ADV,"set in VHWConf");
for (i=0; i < xlDrvConfig.channelCount; i++) {
sprintf (tmp, "hwType: %d, bustype: %d, hwChannel: %d, cap: 0x%x",
xlDrvConfig.channel[i].hwType,
xlDrvConfig.channel[i].connectedBusType,
xlDrvConfig.channel[i].hwChannel,
xlDrvConfig.channel[i].channelBusCapabilities);
DEBUG(DEBUG_ADV,tmp);
// we search not the first CAN cabs
if ( (xlDrvConfig.channel[i].channelBusCapabilities & XL_BUS_ACTIVE_CAP_CAN) && (appChannel < 2) ) {
hwType = xlDrvConfig.channel[i].hwType;
hwIndex = xlDrvConfig.channel[i].hwIndex;
hwChannel = xlDrvConfig.channel[i].hwChannel;
xlStatus = xlSetApplConfig( // Registration of Application with default settings
"xlCANcontrol", // Application Name
appChannel, // Application channel 0 or 1
hwType, // hwType (CANcardXL...)
hwIndex, // Index of hardware (slot) (0,1,...)
hwChannel, // Index of channel (connector) (0,1,...)
busType); // the application is for CAN.
m_xlChannelMask[appChannel] = xlGetChannelMask(hwType, hwIndex, hwChannel);
sprintf (tmp, "Register CAN hWType: %d, CM: 0x%I64x", hwType, m_xlChannelMask[appChannel]);
DEBUG(DEBUG_ADV,tmp);
m_pHardware->InsertString(-1, xlDrvConfig.channel[i].name);
appChannel++;
}
}
}
else {
m_xlChannelMask[CHAN01] = xlGetChannelMask(hwType, hwIndex, hwChannel);
sprintf (tmp, "Found CAN in VHWConf, hWType: %d, CM: 0x%I64x", hwType, m_xlChannelMask[CHAN01]);
DEBUG(DEBUG_ADV,tmp);
for (i=0; i < xlDrvConfig.channelCount; i++) {
if ( xlDrvConfig.channel[i].channelMask == m_xlChannelMask[CHAN01])
m_pHardware->AddString(xlDrvConfig.channel[i].name);
}
// get the second channel
xlStatus = xlGetApplConfig("xlCANcontrol", CHAN02, &hwType, &hwIndex, &hwChannel, busType);
if (xlStatus) return xlStatus;
m_xlChannelMask[CHAN02] = xlGetChannelMask(hwType, hwIndex, hwChannel);
sprintf (tmp, "Found CAN in VHWConf, hWType: %d, CM: 0x%I64x", hwType, m_xlChannelMask[CHAN02]);
DEBUG(DEBUG_ADV,tmp);
for (i=0; i < xlDrvConfig.channelCount; i++) {
if ( xlDrvConfig.channel[i].channelMask == m_xlChannelMask[CHAN02])
m_pHardware->AddString(xlDrvConfig.channel[i].name);
}
}
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! canInit
//! xlCANcontrol use ONE port for both channels.
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::canInit()
{
XLstatus xlStatus = XL_ERROR;
XLaccess xlPermissionMask;
char tmp[100];
// ---------------------------------------
// Open ONE port for both channels
// ---------------------------------------
// calculate the channelMask for both channel
m_xlChannelMask_both = m_xlChannelMask[CHAN01] + m_xlChannelMask[CHAN02];
xlPermissionMask = m_xlChannelMask_both;
xlStatus = xlOpenPort(&m_xlPortHandle, "xlCANcontrol", m_xlChannelMask_both, &xlPermissionMask, 256, XL_INTERFACE_VERSION, XL_BUS_TYPE_CAN);
sprintf(tmp, "xlOpenPort: PortHandle: %d; Permissionmask: 0x%I64x; Status: %d", m_xlPortHandle, xlPermissionMask, xlStatus);
DEBUG(DEBUG_ADV, tmp);
if (m_xlPortHandle == XL_INVALID_PORTHANDLE) return XL_ERROR;
if (xlStatus == XL_ERR_INVALID_ACCESS) return xlStatus;
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! canCreateRxThread
//! set the notification and creates the thread.
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::canCreateRxThread()
{
XLstatus xlStatus = XL_ERROR;
DWORD ThreadId=0;
char tmp[100];
if (m_xlPortHandle!= XL_INVALID_PORTHANDLE) {
// Send a event for each Msg!!!
xlStatus = xlSetNotification (m_xlPortHandle, &m_hMsgEvent, 1);
sprintf(tmp, "SetNotification '%d', xlStatus: %d", m_hMsgEvent, xlStatus);
DEBUG(DEBUG_ADV, tmp);
// for the RxThread
g_th.xlPortHandle = m_xlPortHandle;
g_th.hMsgEvent = m_hMsgEvent;
g_th.pOutput = m_pOutput;
m_hThread = CreateThread(0, 0x1000, RxThread, (LPVOID) &g_th, 0, &ThreadId);
sprintf(tmp, "CreateThread %d", m_hThread);
DEBUG(DEBUG_ADV, tmp);
}
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! CANGoOnBus
//! set the selected baudrate and go on bus.
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANGoOnBus(unsigned long baudrate)
{
XLstatus xlStatus = XL_ERROR;
char tmp[100];
xlStatus = xlCanSetChannelBitrate(m_xlPortHandle, m_xlChannelMask_both, baudrate);
sprintf(tmp, "SetBaudrate: %d, stat: %d", baudrate, xlStatus);
DEBUG(DEBUG_ADV, tmp);
xlStatus = xlActivateChannel(m_xlPortHandle, m_xlChannelMask_both, XL_BUS_TYPE_CAN, XL_ACTIVATE_RESET_CLOCK);
sprintf(tmp, "ActivateChannel, stat: %d", xlStatus);
DEBUG(DEBUG_ADV, tmp);
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! CANGoOffBus
//! Deactivate the channel
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANGoOffBus()
{
XLstatus xlStatus = XL_ERROR;
char tmp[100];
xlStatus = xlDeactivateChannel(m_xlPortHandle, m_xlChannelMask_both);
sprintf(tmp, "DeactivateChannel, stat: %d", xlStatus);
DEBUG(DEBUG_ADV, tmp);
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! CANSend
//! transmit a CAN message to the selected channel with the give values.
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANSend(XLevent xlEvent, int channel)
{
XLstatus xlStatus;
char tmp[100];
unsigned int messageCount = 1;
xlStatus = xlCanTransmit(m_xlPortHandle, m_xlChannelMask[channel], &messageCount, &xlEvent);
sprintf(tmp, "Transmit, mc: %d, channel: %d, stat: %d", messageCount, channel, xlStatus);
DEBUG(DEBUG_ADV, tmp);
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! CANResetFilter
//! Reset the acceptancefilter
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANResetFilter()
{
XLstatus xlStatus;
char tmp[100];
xlStatus = xlCanResetAcceptance(m_xlPortHandle, m_xlChannelMask_both, XL_CAN_STD);
sprintf(tmp, "CanResetAcceptance, stat: %d", xlStatus);
DEBUG(DEBUG_ADV, tmp);
return xlStatus;
}
////////////////////////////////////////////////////////////////////////////
//! CANSetFilter
//! Reset the acceptancefilter
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::CANSetFilter(unsigned long first_id, unsigned long last_id)
{
XLstatus xlStatus;
char tmp[100];
// because there all filters open, we close all.
xlStatus = xlCanSetChannelAcceptance(m_xlPortHandle, m_xlChannelMask_both, 0xFFF, 0xFFF, XL_CAN_STD);
sprintf(tmp, "CanSetChannelAcceptance, stat: %d", xlStatus);
DEBUG(DEBUG_ADV, tmp);
// and now we can set the acceptance filter range.
xlStatus = xlCanAddAcceptanceRange(m_xlPortHandle, m_xlChannelMask_both, first_id, last_id);
sprintf(tmp, "CanAddAcceptanceRange, firstID: %d, lastID: %d, stat: %d", first_id, last_id, xlStatus);
DEBUG(DEBUG_ADV, tmp);
return xlStatus;
}
///////////////////////////////////////////////////////////////////////////
//! ShowLicenses
//! Reads licenses from the selected channels and displays it.
//!
////////////////////////////////////////////////////////////////////////////
XLstatus CCANFunctions::ShowLicenses()
{
XLstatus xlStatus;
char licAvail[2048];
char strtmp[512];
// Show available licenses
XLlicenseInfo licenseArray[1024];
unsigned int licArraySize = 1024;
xlStatus = xlGetLicenseInfo(m_xlChannelMask[CHAN01] | m_xlChannelMask[CHAN02], licenseArray, licArraySize);
if (xlStatus == XL_SUCCESS) {
strcpy(licAvail, "Licenses found:\n\n");
for (unsigned int i = 0; i < licArraySize; i++) {
if (licenseArray[i].bAvailable) {
sprintf(strtmp, "ID 0x%03x: %s\n", i, licenseArray[i].licName);
if ((strlen(licAvail) + strlen(strtmp)) < sizeof(licAvail)) {
strcat(licAvail, strtmp);
}
else {
// Too less memory for printing licenses
sprintf(licAvail, "Internal Error: String size in CCANFunctions::ShowLicenses() is too small!");
xlStatus = XL_ERROR;
}
}
}
}
else {
sprintf(licAvail, "Error %d when calling xlGetLicenseInfo()!", xlStatus);
}
AfxMessageBox(licAvail);
return xlStatus;
}
///////////////////////////////////////////////////////////////////////////
//! RxThread
//! thread to readout the message queue and parse the incoming messages
//!
////////////////////////////////////////////////////////////////////////////
DWORD WINAPI RxThread(LPVOID par)
{
XLstatus xlStatus;
unsigned int msgsrx = 0;
XLevent xlEvent;
char tmp[110];
char tmp2[110];
CString str;
g_bThreadRun = TRUE;
TStruct *g_th;
g_th = (TStruct*) par;
sprintf(tmp, "thread: SetNotification '%d'", g_th->hMsgEvent);
DEBUG(DEBUG_ADV, tmp);
while (g_bThreadRun) {
WaitForSingleObject(g_th->hMsgEvent,10);
xlStatus = XL_SUCCESS;
while (!xlStatus) {
msgsrx = 1;
xlStatus = xlReceive(g_th->xlPortHandle, &msgsrx, &xlEvent);
if ( xlStatus!=XL_ERR_QUEUE_IS_EMPTY ) {
sprintf(tmp, "%s", xlGetEventString(&xlEvent));
if(startTime==0)
{
startTime = xlEvent.timeStamp;
}
CString str="";
for(int i=0;i<xlEvent.tagData.msg.dlc;i++)
{
CString temp;
temp.Format("% 02X ",xlEvent.tagData.msg.data[i]);
str += temp;
}
CString StrId;
CString StrDecId;
CString StrCheckCA;//识别DM1
if(xlEvent.tagData.msg.id>0x80000000)
{
StrId.Format("%lxx",xlEvent.tagData.msg.id&0x7fffffff);//去掉扩展位80000x
StrDecId.Format("%lux",xlEvent.tagData.msg.id&0x7fffffff);
StrCheckCA=StrId.Mid(strlen(StrId)-5,2);
//AfxMessageBox(StrCheckCA);
}
else
{
StrId.Format("%lx",xlEvent.tagData.msg.id);
StrDecId.Format("%lu",xlEvent.tagData.msg.id);
StrCheckCA=StrId.Mid(strlen(StrId)-4,2);
//AfxMessageBox(StrCheckCA);
}
StrCheckCA = StrCheckCA.MakeUpper();
CString strHexData = StrId + str; //计算填充位
CString strBitData=CString("");
int lengthHex = strlen(strHexData);
for(int i = 0;i<lengthHex;)
{
CString strHexPart= strHexData.Mid(i,2);
long value;
sscanf(strHexPart,"%X",&value);
char c[10];
itoa(value,c,2);
CString strBitPart;
strBitPart.Format("%08s",c);
//AfxMessageBox(strBitPart);
strBitData+=strBitPart;
i += 2;
}
//AfxMessageBox(strBitData);
int lengthBit = strlen(strBitData);
int fillbit = 0;
int count = 1;
char benchbit = strBitData.GetAt(0);
for(int i = 1;i<lengthBit;i++)
{
char dd = strBitData.GetAt(i);
if(dd!=benchbit)
{
benchbit = dd;
count = 1;
}
else
{
count++;
}
if(count==5)
{
fillbit++;
count = 1;
benchbit = strBitData.GetAt(i+1);
i+=2;
}
}
/* CString strbits;
strbits.Format("%d",fillbit);
AfxMessageBox(strbits);*/
int idlen = (int)(ceil)(strlen(StrId)/2.0);//补零
int BitCount = (idlen+2+2+8)*8;//参见msg结构体组成(保留位不考虑,id位是用多少计算多少,data区默认全使用)
sprintf(tmp2, " %10.6f %d %s Rx d %d %s Length = %ld BitCount = %d ID= %s",(xlEvent.timeStamp-startTime)* 0.000000001,xlEvent.chanIndex+1,StrId,xlEvent.tagData.msg.dlc,str,(BitCount+fillbit-3)*4000,BitCount+fillbit,StrDecId);
DEBUG(DEBUG_ADV, tmp);
g_th->pOutput->InsertString(-1, tmp2);
g_th->pOutput->SetCurSel(g_th->pOutput->GetCount()-1);
int messageCount = m_Grid_message.GetRowCount();
for(int i=1;i<messageCount+1;i++)
{
if(m_Grid_message.GetItemText(2,2)!=CString("")&&m_Grid_message.GetItemText(2,3)==CString("") && m_Grid_message.GetItemText(2,5)==CString(""))
{
AfxMessageBox("Baud Rate is not right!!!");
break;
}
if(m_Grid_message.GetItemText(i,2)=="")
{
if(xlEvent.tagData.msg.dlc==0)
{
break;
}
if(StrCheckCA==CString("CA"))
{
m_Grid_message.SetItemText(i,3,"#DM1 Error");
m_listbox_dm.InsertString(-1,"DM1 ------------------------"+StrId);
}
//m_listbox_dm.InsertString(-1, "");
sprintf(tmp2,"%10.6f",(xlEvent.timeStamp-startTime)* 0.000000001);
m_Grid_message.SetItemText(i,1,tmp2);
sprintf(tmp2,"%s",StrId);
m_Grid_message.SetItemText(i,2,tmp2);
sprintf(tmp2," %d",xlEvent.tagData.msg.dlc);
m_Grid_message.SetItemText(i,4,tmp2);
sprintf(tmp2," %s",str);
m_Grid_message.SetItemText(i,5,tmp2);
m_Grid_message.InsertRow("",-1);
i=0;
break;
}
else
{
if(m_Grid_message.GetItemText(i,2)==StrId)
{
m_Grid_message.SetRowHeight(i,30);
sprintf(tmp2,"%10.6f",(xlEvent.timeStamp-startTime)* 0.000000001);
m_Grid_message.SetItemText(i,1,tmp2);
sprintf(tmp2," %d",xlEvent.tagData.msg.dlc);
m_Grid_message.SetItemText(i,4,tmp2);
sprintf(tmp2," %s",str);
m_Grid_message.SetItemText(i,5,tmp2);
break;
}
/*else
{
if(i==messageCount-1)
{
sprintf(tmp2,"%10.6f",(xlEvent.timeStamp-startTime)* 0.000000001);
m_Grid_message.SetItemText(messageCount,1,tmp2);
sprintf(tmp2,"%8lxx",xlEvent.tagData.msg.id);
m_Grid_message.SetItemText(messageCount,2,tmp2);
sprintf(tmp2," %d",xlEvent.tagData.msg.dlc);
m_Grid_message.SetItemText(messageCount,4,tmp2);
sprintf(tmp2," %s",str);
m_Grid_message.SetItemText(messageCount,5,tmp2);
m_Grid_message.Refresh();
break;
}
}*/
}
}
//g_th->pOutput->InsertString(-1, tmp);
}
}
m_Grid_message.Refresh();
}
return NO_ERROR;
}
<file_sep>// xlCANcontrolDlg.h : header file
//
#include "xlCANFunctions.h"
#include "gridctrl_src\gridctrl.h"
#include "PictureEx.h"
#include "gridctrl_src\gridctrl.h"
#include "afxwin.h"
#if !defined(AFX_XLCANCONTROLDLG_H__6B0850D5_5DFB_4F90_9475_A6C598BFB702__INCLUDED_)
#define AFX_XLCANCONTROLDLG_H__6B0850D5_5DFB_4F90_9475_A6C598BFB702__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CXlCANcontrolDlg dialog
class CXlCANcontrolDlg : public CDialog
{
// Construction
public:
CXlCANcontrolDlg(CWnd* pParent = NULL); // standard constructor
CCANFunctions m_CAN;
// Dialog Data
//{{AFX_DATA(CXlCANcontrolDlg)
enum { IDD = IDD_XLCANCONTROL_DIALOG };
CListBox m_Hardware;
CComboBox m_Channel;
CButton m_btnSend;
CButton m_btnOffBus;
CButton m_btnOnBus;
CComboBox m_Baudrate;
CListBox m_Output;
CString m_eD00;
CString m_eD01;
CString m_eD02;
CString m_eD03;
CString m_eD04;
CString m_eD05;
CString m_eD06;
CString m_eD07;
CString m_eDLC;
CString m_eID;
BOOL m_ExtID;
CString m_eFilterFrom;
CString m_eFilterTo;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CXlCANcontrolDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CXlCANcontrolDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnOnbus();
afx_msg void OnOffbus();
afx_msg void OnSend();
afx_msg void OnClear();
afx_msg void OnAbout();
afx_msg void OnReset();
afx_msg void OnLicInfo();
afx_msg void OnSetfilter();
afx_msg void OnOnceClick(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRClick(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnDoubleClick(NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
public:
CPictureEx m_Picture_logo;
afx_msg void OnStnClickedStaticPicLogo();
afx_msg void OnStnClickedStaticAbout();
afx_msg void OnStnClickedStaticHelp();
CPictureEx m_Picture_about;
CPictureEx m_Picture_help;
CGridCtrl m_Grid_signals;
CGridCtrl m_Grid_senddata;
CPictureEx m_Picture_lang;
afx_msg void OnStnClickedStaticLang();
int initCANList(void);
int CheckCANdecive(void);
void ShowSignals(CString id,CString data,CString name);
CString HexStr2Binarystr(CString str);
CString Binarystr2HexStr(CString str,int order);
CStatic m_sta_versionno;
int readDbcFile(void);
afx_msg void OnBnClickedButtonExport();
CComboBox m_commo_channel;
CComboBox m_commo_hz;
BOOL m_check_advance;
afx_msg void OnBnClickedCheckAdvanced();
CButton m_btn_restart;
CStatic m_sta_caution;
afx_msg void OnBnClickedButtonRestart();
afx_msg void OnClose();
afx_msg void OnTimer(UINT_PTR nIDEvent);
public:
afx_msg void OnBnClickedButtonNewmess();
void IgnitionOnSetTimers();
void IgnitionOffKillTimers();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_XLCANCONTROLDLG_H__6B0850D5_5DFB_4F90_9475_A6C598BFB702__INCLUDED_)
| cfe5ba1208810af9bed53ce139d7d529f1b7d405 | [
"C",
"Text",
"C++",
"INI"
] | 9 | C++ | SepCat/iCAN_4_Customer | 45ed3c7ad523b2963db50b97cd3ac4253048b44a | f7aae751283df3a91245dc35b496bdb4a9e236ce |
refs/heads/main | <file_sep>const { crearArchivo } = require('./helpers/multiplicar');
const argv = require('yargs')
.option('b', {
alias: 'base',
type: 'number',
demandOption: true
})
.option('l', {
alias: 'listar',
type: 'boolean',
default: false,
demandOption: true
})
.check((argv, options) => {
if (isNaN(argv.b)) {
throw 'la base tiene que ser un numero';
}
return true;
})
.argv;
// const [, , arg3] = process.argv;
// const [, base = 5] = arg3.split('=');
// console.log(base);
console.clear();
console.log(argv);
crearArchivo(argv.base, argv.l)
.then(nombreArchivo => console.log(`archivo:${nombreArchivo}`))
.catch(err => console.log(err));<file_sep>const empleados = [
{ id: 1, nombre: 'Daniel' },
{ id: 2, nombre: 'Fernando' },
{ id: 3, nombre: 'David' },
];
const salarios = [
{ id: 1, salario: 1000 },
{ id: 2, salario: 1500 },
];
const getEmpleado = (id) => {
return new Promise((resolve, reject) => {
const empleado = empleados.find(e => e.id == id);
empleado ? resolve(empleado) : reject(`No existe el empleado con id ${id}`);
});
}
const getSalario = (id) => {
return new Promise((resolve, reject) => {
const salario = salarios.find(s => s.id == id);
salario ? resolve(salario) : reject('Salario no encontrado');
});
}
const id = 3;
// getEmpleado(id)
// .then(empleado => console.log(empleado))
// .catch(err => console.log(err));
// getSalario(id)
// .then(salario => console.log(salario))
// .catch(err => console.log(err));
// getEmpleado(id)
// .then(empleado => {
// getSalario(id)
// .then(salario => {
// console.log(`El empleado: ${empleado.nombre} tiene un salario de: ${salario.salario}`);
// })
// .catch(err => console.log(err));
// })
// .catch(err => console.log(err));
let nombre;
getEmpleado(id)
.then(empleado => {
nombre = empleado.nombre;
return getSalario(id)
})
.then(salario => console.log(`El empleado con en nombre ${nombre} tiene un salario de ${salario.salario}`))
.catch(err => console.log(err));<file_sep>const deadpool = {
nombre: 'Wade',
apellido: 'Windston',
poder: 'Regeneracion',
// edad: 50,
getNombre() { return `${this.nombre} ${this.apellido}` }
}
console.log(deadpool.getNombre());
// const nombre = deadpool.nombre;
// const apellido = deadpool.apellido;
// const poder = deadpool.poder;
// const { nombre, apellido, poder, edad = 0 } = deadpool;
// console.log(nombre, apellido, poder, edad);
function imprimirHeroe(heroe) {
const { nombre, apellido, poder, edad = 0 } = heroe;
console.log(nombre, apellido, poder, edad);
}
// imprimirHeroe(deadpool);
const heroes = ['deadpool', 'Superman', 'Batman'];
const [, , h3] = heroes;
console.log(h3); | bf08559545d15bb15dc51581e66622aa62a33a37 | [
"JavaScript"
] | 3 | JavaScript | DanButronOtero/node_practice | 432dc493b4d46fc0e911daf064d01d795427c8bc | b09bdfc86f8cfc0744c5dc02b12e598a66bc24a3 |
refs/heads/master | <file_sep>#ifndef TODO_CPP
#define TODO_CPP
#include <iostream>
#include <string>
using namespace std;
class Todo{
private:
string list[100];
int length=0;
int next =0;
public:
Todo(){
length = 0;
next = 0;
}
void add(string action){
list[next] = action;
next++;
length++;
}
void complete(){
}
void print(){
for (int i=length; i<next; i++){
cout << "Item " <<(i+1) << ": " << list[i] << endl;
}
}
};
#endif<file_sep>#include <iostream>
#include <string>
#include "Todo.cpp"
using namespace std;
int main(){
char choice;
int l=0;
string item;
Todo list;
cout << "Length of the list: ";
cin >> l;
while (choice !='x'){
cout << endl;
cout << "Add to list (a)." << endl;
cout << "Done list item (d)." << endl;
cout << "Print list (p)." << endl;
cout << "Exit list app (x)." << endl;
cout << "What do you want to do: ";
cin >> choice;
cout << endl;
switch(choice){
case 'a':
cout <<"Item: ";
cin >> item;
list.add(item);
break;
case 'p':
list.print();
break;
case 'x':
cout << "Exiting...";
break;
default:
cout << "invalid selection..." << endl;
break;
}
}
return 0;
} | 73249d57fbd8660f39374d4f36c6d0a35511899f | [
"C++"
] | 2 | C++ | hamza-zoumhani/CIS2013_Week15_Quiz | 0b9c3dfd235431ef9392c6ad4037b86fb8575055 | 6687ed90abcf861f2ce5d46525e6740f2128d664 |
refs/heads/master | <file_sep>title=iBase - Image Database
heading=Welcome to your personal ImageDatabase
photoHeading=Your Photos
login=Login/Register
valid.file= Please select an image!<file_sep>package com.iBase.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import com.iBase.domain.IBaseImage;
import com.iBase.domain.UserInfo;
public class ImageLoader {
protected final Log log = LogFactory.getLog(getClass());
private ObjectMapper mapper;
private UserInfo user;
public ImageLoader(UserInfo user) {
this.user = user;
mapper = new ObjectMapper();
}
public List<IBaseImage> getImageObjects() {
List<IBaseImage> images = new ArrayList<IBaseImage>();
String imagesJSON = user.getImagesList();
if(imagesJSON==null){
return images;
}
try {
ArrayList<IBaseImage> IBaseImages = mapper.readValue(imagesJSON
, new TypeReference<ArrayList<IBaseImage>>(){});
for(IBaseImage image: IBaseImages){
images.add(image);
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return images;
}
}
<file_sep>package com.iBase.domain;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class ImageFileTest {
private ImageFile file;
@Before
public void initialize() throws Exception {
file = new ImageFile();
}
@Test
public void testSetAndGetName(){
String name = "name";
assertEquals("",file.getName());
file.setName(name);
assertEquals(name, file.getName());
}
//mock commonMultipartFile
}
<file_sep>package com.iBase.web;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.iBase.domain.UserInfo;
import com.iBase.service.db.UserInfoDAO;
@Controller
public class UserProfileController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private UserInfoDAO userInfoDAO;
@RequestMapping(value="/userProfile/{friendId:.+}", method = RequestMethod.GET)
public String getUserProfile(@PathVariable String friendId, Model model){
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
model.addAttribute("userName", userDetail.getUsername());
model.addAttribute("friendId", friendId);
UserInfo user = userInfoDAO.findById(userDetail.getUsername());
model.addAttribute("fName", user.getFirstName());
model.addAttribute("lName", user.getLastName());
UserInfo friendInfo = userInfoDAO.findById(friendId);
model.addAttribute("friendFName", friendInfo.getFirstName());
model.addAttribute("friendLName", friendInfo.getLastName());
model.addAttribute("friendEmail", friendId);
model.addAttribute("friendImageCount", friendInfo.getImageCount());
return "userProfile";
}
return "403";
}
}
<file_sep>package com.iBase.domain;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class ImageFile {
private CommonsMultipartFile imageFile = null;
private String name = "";
public CommonsMultipartFile getImageFile() {
return imageFile;
}
public void setImageFile(CommonsMultipartFile imageFile) {
this.imageFile = imageFile;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>iBase
=====
Demo (Hosted on amazon EC2): http://ec2-54-187-126-153.us-west-2.compute.amazonaws.com/iBase/
<file_sep>package com.iBase.web.sharing;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.helpers.collection.IteratorUtil;
public class GraphInstanceTest {
private static enum RelTypes implements RelationshipType {
KNOWS
}
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
private Index<Node> nodeIndex;
GraphInstanceTest() {
graphDb = GraphInstance.getInstance().getGraph();
nodeIndex = graphDb.index().forNodes("nodes");
}
public void dostuff() {
Transaction tx = null;
try {
tx = graphDb.beginTx();
firstNode = graphDb.createNode();
firstNode.setProperty("message", "Hello, ");
nodeIndex.add(firstNode, "message", "Hello, ");
secondNode = graphDb.createNode();
secondNode.setProperty("message", "World!");
nodeIndex.add(secondNode, "message", "World!");
relationship = firstNode.createRelationshipTo(secondNode,
RelTypes.KNOWS);
relationship.setProperty("message", "brave Neo4j ");
}catch(Exception ex){
ex.printStackTrace();
}finally{
tx.success();
}
}
public void print() {
Transaction tx = null;
try {
tx = graphDb.beginTx();
Node node = nodeIndex.get("message", "Hello, ").getSingle();
if (node != null) {
System.out.println("whoo!!");
} else {
System.out.println("NO!!");
}
System.out.print(firstNode.getProperty("message"));
System.out.print(relationship.getProperty("message"));
System.out.print(secondNode.getProperty("message"));
System.out.println(isConnected(firstNode, secondNode));
System.out.println(getAllFriends(firstNode.getProperty("message").toString()));
}catch(Exception ex){
ex.printStackTrace();
}finally{
tx.success();
}
}
private boolean isConnected(Node node1, Node node2) {
String node1Key = node1.getProperty("message").toString();
String node2Key = node2.getProperty("message").toString();
String query = "start node1=node:nodes(message = '" + node1Key + "'), "
+ "node2=node:nodes(message = '" + node2Key + "') "
+ "match node1-[r:KNOWS]->node2 " + "return r";
ExecutionEngine engine = new ExecutionEngine(graphDb);
ExecutionResult result = engine.execute(query);
Iterator<Node> rcolumn = result.columnAs("r");
if (rcolumn.hasNext()) {
// edge exists!
return true;
} else {
return false;
}
}
@SuppressWarnings("unused")
private void deleteEdge(Node node1, Node node2) {
String node1Key = node1.getProperty("message").toString();
String node2Key = node2.getProperty("message").toString();
String query = "start node1=node:nodes(message = '" + node1Key + "'), "
+ "node2=node:nodes(message = '" + node2Key + "') "
+ "match node1-[r:KNOWS]->node2 " + "delete r";
ExecutionEngine engine = new ExecutionEngine(graphDb);
ExecutionResult result = engine.execute(query);
System.out.println((result.toString()));
}
public List<String> getAllFriends(String userId) {
ExecutionEngine engine = new ExecutionEngine(graphDb);
ExecutionResult result0 = engine
.execute("start node=node:nodes(message = '" + userId + "') "
+ "match node-[:KNOWS]->deg0 " + "return deg0");
List<String> deg0Nodes = new ArrayList<String>();
Iterator<Node> n_column = result0.columnAs("deg0");
for (Node node : IteratorUtil.asIterable(n_column)) {
String nodeResult = node.getProperty("message").toString();
deg0Nodes.add(nodeResult);
}
return deg0Nodes;
}
public static void main(String[] args) {
GraphInstanceTest g = new GraphInstanceTest();
g.dostuff();
g.print();
}
}
<file_sep>package com.iBase.domain;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class IBaseImageTest {
private IBaseImage iBaseImage;
@Before
public void initialize() throws Exception {
iBaseImage = new IBaseImage();
}
@Test
public void testSetAndGetImageLocation(){
String imageLocation = "dummy_location";
Assert.assertNull(iBaseImage.getImageLocation());
iBaseImage.setImageLocation(imageLocation);
assertEquals(imageLocation, iBaseImage.getImageLocation());
}
@Test
public void testSetAndGetLikes(){
int likes = 4;
assertEquals(0, iBaseImage.getLikes());
iBaseImage.setLikes(likes);
assertEquals(likes, iBaseImage.getLikes());
}
@Test
public void testSetAndGetImageId(){
String imageId = "id";
assertNull(iBaseImage.getImageId());
iBaseImage.setImageId(imageId);
assertEquals(imageId, iBaseImage.getImageId());
}
@Test
public void testSetAndGetImageTitle(){
String imageTitle = "title";
assertNull(iBaseImage.getImageTitle());
iBaseImage.setImageTitle(imageTitle);
assertEquals(imageTitle, iBaseImage.getImageTitle());
}
}
<file_sep>package com.iBase.domain;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class UserInfoTest {
private UserInfo userInfo;
@Before
public void initialize() throws Exception {
userInfo = new UserInfo();
}
@Test
public void testSetAndGetUserId(){
String userId = "<EMAIL>";
Assert.assertNull(userInfo.getUserId());
userInfo.setUserId(userId);
Assert.assertEquals(userId, userInfo.getUserId());
}
@Test
public void testSetAndGetPassword(){
String password = "<PASSWORD>";
Assert.assertNull(userInfo.getPassword());
userInfo.setPassword(password);
Assert.assertEquals(password, userInfo.getPassword());
}
@Test
public void testSetAndGetFriendsList(){
String friendsList = "{[\"<EMAIL>\", \"<EMAIL>\"]}";
Assert.assertNull(userInfo.getFriendList());
userInfo.setFriendList(friendsList);
Assert.assertEquals(friendsList, userInfo.getFriendList());
}
@Test
public void testSetAndGetImagesList(){
String imagesList = "{[\"a/b/c\", \"d/e\"]}";
Assert.assertNull(userInfo.getImagesList());
userInfo.setImagesList(imagesList);
Assert.assertEquals(imagesList, userInfo.getImagesList());
}
@Test
public void testSetAndGetInfo(){
String fName = "kartheek";
String lname = "Ganesh";
String profilePic = "/a/b/c";
Assert.assertNull(userInfo.getFirstName());
Assert.assertNull(userInfo.getLastName());
Assert.assertNull(userInfo.getProfilePic());
userInfo.setFirstName(fName);
userInfo.setLastName(lname);
userInfo.setProfilePic(profilePic);
Assert.assertEquals(fName, userInfo.getFirstName());
Assert.assertEquals(lname, userInfo.getLastName());
Assert.assertEquals(profilePic, userInfo.getProfilePic());
}
}
<file_sep>package com.iBase.domain;
public class IBaseImage {
private String imageLocation;
private String imageId;
private String imageTitle;
private int likes;
public String getImageLocation() {
return imageLocation;
}
public void setImageLocation(String imageLocation) {
this.imageLocation = imageLocation;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public String getImageTitle() {
return imageTitle;
}
public void setImageTitle(String imageTitle) {
this.imageTitle = imageTitle;
}
}
| 95c53234aeb1bb639129252bf79a7d64b7dfc055 | [
"Markdown",
"Java",
"INI"
] | 10 | INI | karth707/iBase | bba8ce8503fd40db811200de3977f5d5a49ba0f8 | 90116a79cc0d0d653d13c37246aa11de4301be6c |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui/species_prompt.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SpeciesPrompt(object):
def setupUi(self, SpeciesPrompt):
SpeciesPrompt.setObjectName("SpeciesPrompt")
SpeciesPrompt.resize(325, 132)
SpeciesPrompt.setFocusPolicy(QtCore.Qt.StrongFocus)
self.centralwidget = QtWidgets.QWidget(SpeciesPrompt)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 321, 122))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 3, 0, 1, 1)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.species_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.species_label.setObjectName("species_label")
self.horizontalLayout.addWidget(self.species_label)
self.gridLayout.addLayout(self.horizontalLayout, 2, 0, 1, 1)
self.dataset_name = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.dataset_name.setObjectName("dataset_name")
self.gridLayout.addWidget(self.dataset_name, 3, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.species_selection = QtWidgets.QComboBox(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.species_selection.sizePolicy().hasHeightForWidth())
self.species_selection.setSizePolicy(sizePolicy)
self.species_selection.setObjectName("species_selection")
self.gridLayout.addWidget(self.species_selection, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
spacerItem = QtWidgets.QSpacerItem(40, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout_9.addWidget(self.apply_button)
self.verticalLayout.addLayout(self.horizontalLayout_9)
SpeciesPrompt.setCentralWidget(self.centralwidget)
self.retranslateUi(SpeciesPrompt)
QtCore.QMetaObject.connectSlotsByName(SpeciesPrompt)
def retranslateUi(self, SpeciesPrompt):
_translate = QtCore.QCoreApplication.translate
SpeciesPrompt.setWindowTitle(_translate("SpeciesPrompt", "Species Prompt"))
self.label.setText(_translate("SpeciesPrompt", "Dataset Name:"))
self.species_label.setText(_translate("SpeciesPrompt", "Ion Species:"))
self.apply_button.setText(_translate("SpeciesPrompt", "Apply"))
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'animateXY.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Animate(object):
def setupUi(self, Animate):
Animate.setObjectName("Animate")
Animate.resize(421, 202)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Animate.sizePolicy().hasHeightForWidth())
Animate.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(Animate)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 401, 181))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMaximumSize(QtCore.QSize(16777215, 200))
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.lim = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.lim.setObjectName("lim")
self.gridLayout.addWidget(self.lim, 6, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 6, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_2.setMaximumSize(QtCore.QSize(16777215, 100))
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.radioButton = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.radioButton.setObjectName("radioButton")
self.verticalLayout.addWidget(self.radioButton)
self.radioButton_2 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.radioButton_2.setObjectName("radioButton_2")
self.verticalLayout.addWidget(self.radioButton_2)
self.gridLayout.addLayout(self.verticalLayout, 1, 1, 1, 1)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 7, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.fps = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.fps.setObjectName("fps")
self.gridLayout.addWidget(self.fps, 7, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox)
Animate.setCentralWidget(self.centralwidget)
self.retranslateUi(Animate)
QtCore.QMetaObject.connectSlotsByName(Animate)
def retranslateUi(self, Animate):
_translate = QtCore.QCoreApplication.translate
Animate.setWindowTitle(_translate("Animate", "Choosing Animation"))
self.label.setText(_translate("Animate", "<html><head/><body><p>Please enter your animation parameters.</p></body></html>"))
self.label_3.setText(_translate("Animate", "Axes Limit (maximum x or y value, mm):"))
self.label_2.setText(_translate("Animate", "Reference Frame:"))
self.radioButton.setText(_translate("Animate", "Local"))
self.radioButton_2.setText(_translate("Animate", "Global"))
self.label_4.setText(_translate("Animate", "FPS:"))
<file_sep>from ..abstract_tool import AbstractTool
from PyQt5.QtWidgets import QFileDialog, QMainWindow
from .beamchargui import Ui_BeamChar
from matplotlib.ticker import LinearLocator, LogLocator
from matplotlib.ticker import FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
import os
import re
""""
A tool for plotting beam characteristics.
"""
class BeamChar(AbstractTool):
def __init__(self, parent):
super(BeamChar, self).__init__(parent)
self._name = "Beam Characteristics"
self._parent = parent
self._filename = ""
self._settings = {}
# --- Initialize the GUI --- #
self._beamCharWindow = QMainWindow()
self._beamCharGUI = Ui_BeamChar()
self._beamCharGUI.setupUi(self._beamCharWindow)
self._beamCharGUI.buttonBox.accepted.connect(self.callback_apply)
self._beamCharGUI.buttonBox.rejected.connect(self._beamCharWindow.close)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = None
self._redraw_on_exit = False
def apply_settings(self):
self._settings["rms"] = self._beamCharGUI.rms.isChecked()
self._settings["halo"] = self._beamCharGUI.halo.isChecked()
self._settings["centroid"] = self._beamCharGUI.centroid.isChecked()
self._settings["turnsep"] = self._beamCharGUI.turnsep.isChecked()
self._settings["energyHist"] = self._beamCharGUI.ehist.isChecked()
self._settings["intensity"] = self._beamCharGUI.intens.isChecked()
self._settings["xz"] = self._beamCharGUI.xz.isChecked()
def callback_apply(self):
self.apply_settings()
self._beamCharWindow.close()
self._parent.send_status("Creating plot(s)...")
plots = {}
num = 0
largepos = 1.0e36
for dataset in self._selections:
corrected = {}
name = dataset.get_name()
nsteps, npart = dataset.get_nsteps(), dataset.get_npart()
plot_data = {"name": name,
"xRMS": np.array([]),
"yRMS": np.array([]),
"zRMS": np.array([]),
"xHalo": np.array([]),
"yHalo": np.array([]),
"zHalo": np.array([]),
"xCentroid": np.ones(nsteps) * largepos,
"yCentroid": np.ones(nsteps) * largepos,
"turnSep": np.array([]),
"R": np.array([]),
"energy": np.array([]),
"power": np.array([]),
"coords": []}
azimuths = np.ones(nsteps) * largepos
r_temps = np.ones(nsteps) * largepos
datasource = dataset.get_datasource()
index = 0
save_r = True
r_tsep = []
# --- Try to find the .o file corresponding to the dataset
# Hardcoded defaults
q_macro = 1.353 * 1.0e-15 # fC --> C (1e5 particles @ 6.65 mA and f_cyclo below)
f_cyclo = 49.16 * 1.0e6 # MHz --> Hz
duty_factor = 0.9 # assumed IsoDAR has 90% duty factor
self._parent.send_status("Attempting to read frequency and macro-charge from .o file...")
_fn = dataset.get_filename()
path = os.path.split(_fn)[0]
# Let's be lazy and find the .o file automatically using regex
template = re.compile('[.]o[0-9]{8}')
_fns = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and template.search(f)]
if len(_fns) > 0:
_fn = _fns[0]
with open(os.path.join(path, _fn), 'r') as infile:
lines = infile.readlines()
have_charge = False
have_freq = False
for line in lines:
if "Qi" in line:
_, _, _, _, _, _, _, _, qi, unit = line.strip().split()
q_macro = float(qi) * 1.0e-15 # fC --> C
# TODO Check for unit, if exception is thrown, need to allow for different units -DW
assert unit == "[fC]", "Expected units of fC, got {}. Aborting!".format(unit)
have_charge = True
if "FREQUENCY" in line:
_, _, _, freq, unit = line.strip().split()
f_cyclo = float(freq) * 1.0e6 # MHz --> Hz
# TODO Check for unit, if exception is thrown, need to allow for different units -DW
assert unit == "MHz", "Expected units of MHz, got {}. Aborting!".format(unit)
have_freq = True
if have_charge and have_freq:
break
assert have_charge and have_freq, "Found .o file, but couldn't determine frequency and/or macrocharge!"
self._parent.send_status("Found f = {:.4f} MHz and Qi = {:.4f} fC in file {}".format(f_cyclo * 1e-6,
q_macro * 1e15,
_fn))
print("Found f = {:.4f} MHz and Qi = {:.4f} fC in file {}".format(f_cyclo * 1e-6,
q_macro * 1e15,
_fn))
else:
self._parent.send_status("Couldn't find .o file in dataset folder! Falling back to hardcoded values.")
print("Couldn't find .o file in dataset folder! Falling back to hardcoded values.")
spt = 1
for step in range(int(nsteps / spt)):
step *= spt
m_amu = 2.01510 # Rest mass of individual H2+, in amu
m_mev = 1876.9729554 # Rest mass of individual H2+, in MeV/c^2
if self._settings["rms"] or self._settings["halo"]:
px_val = np.array(datasource["Step#{}".format(step)]["px"])
py_val = np.array(datasource["Step#{}".format(step)]["py"])
pz_val = np.array(datasource["Step#{}".format(step)]["pz"])
betagamma = np.sqrt(np.square(px_val) + np.square(py_val) + np.square(pz_val))
energy = np.mean((np.sqrt(np.square(betagamma * m_mev) + np.square(m_mev)) - m_mev) / m_amu)
plot_data["energy"] = np.append(plot_data["energy"], energy)
if nsteps > 1:
completed = int(100*(step/(nsteps-1)))
self._parent.send_status("Plotting progress: {}% complete".format(completed))
corrected["Step#{}".format(step)] = {}
x_val = np.array(datasource["Step#{}".format(step)]["x"])
y_val = np.array(datasource["Step#{}".format(step)]["y"])
z_val = np.array(datasource["Step#{}".format(step)]["z"])
if self._settings["xz"]:
r = np.sqrt(np.square(x_val) + np.square(y_val))
plot_data["coords"] = np.append(plot_data["coords"], z_val)
plot_data["R"] = np.append(plot_data["R"], r)
px_mean = np.mean(np.array(datasource["Step#{}".format(step)]["px"]))
py_mean = np.mean(np.array(datasource["Step#{}".format(step)]["py"]))
theta = np.arccos(py_mean/np.linalg.norm([px_mean, py_mean]))
if px_mean < 0:
theta = -theta
# Center the beam
corrected["Step#{}".format(step)]["x"] = x_val - np.mean(x_val)
corrected["Step#{}".format(step)]["y"] = y_val - np.mean(y_val)
corrected["Step#{}".format(step)]["z"] = z_val - np.mean(z_val)
# Rotate the beam
temp_x = corrected["Step#{}".format(step)]["x"]
temp_y = corrected["Step#{}".format(step)]["y"]
corrected["Step#{}".format(step)]["x"] = temp_x*np.cos(theta) - temp_y*np.sin(theta)
corrected["Step#{}".format(step)]["y"] = temp_x*np.sin(theta) + temp_y*np.cos(theta)
# Calculate RMS
if self._settings["rms"]:
plot_data["xRMS"] = np.append(plot_data["xRMS"],
1000.0 * self.rms(corrected["Step#{}".format(step)]["x"]))
plot_data["yRMS"] = np.append(plot_data["yRMS"],
1000.0 * self.rms(corrected["Step#{}".format(step)]["y"]))
plot_data["zRMS"] = np.append(plot_data["zRMS"],
1000.0 * self.rms(corrected["Step#{}".format(step)]["z"]))
# Calculate halo parameter
if self._settings["halo"]:
plot_data["xHalo"] = np.append(plot_data["xHalo"],
self.halo(corrected["Step#{}".format(step)]["x"]))
plot_data["yHalo"] = np.append(plot_data["yHalo"],
self.halo(corrected["Step#{}".format(step)]["y"]))
plot_data["zHalo"] = np.append(plot_data["zHalo"],
self.halo(corrected["Step#{}".format(step)]["z"]))
# Calculate energy
if self._settings["energyHist"] or self._settings["intensity"]:
m_amu = 2.01510 # Rest mass of individual H2+, in amu
m_mev = 1876.9729554 # Rest mass of individual H2+, in MeV/c^2
px_val = np.array(datasource["Step#{}".format(step)]["px"])
py_val = np.array(datasource["Step#{}".format(step)]["py"])
pz_val = np.array(datasource["Step#{}".format(step)]["pz"])
betagamma = np.sqrt(np.square(px_val) + np.square(py_val) + np.square(pz_val))
energy = (np.sqrt(np.square(betagamma * m_mev) + np.square(m_mev)) - m_mev) / m_amu # MeV/amu
plot_data["energy"] = np.append(plot_data["energy"], energy)
if self._settings["intensity"]:
# Power deposition of a single h2+ particle (need to use full energy here!) (W)
power = q_macro * f_cyclo * energy * 1e6 * m_amu * duty_factor
plot_data["power"] = np.append(plot_data["power"], power)
# Radii (m)
r = np.sqrt(np.square(x_val) + np.square(y_val))
plot_data["R"] = np.append(plot_data["R"], r)
# Add centroid coordinates
if self._settings["centroid"] or self._settings["turnsep"]:
plot_data["xCentroid"][step] = np.mean(x_val)
plot_data["yCentroid"][step] = np.mean(y_val)
# Calculate turn separation (as close as possible to pos x-axis for now, arbitrary angle later? -DW)
if self._settings["turnsep"]:
azimuth = np.rad2deg(np.arctan2(plot_data["yCentroid"][step], plot_data["xCentroid"][step]))
azimuths[step] = azimuth
r_temp = np.sqrt(np.square(plot_data["xCentroid"][step]) +
np.square(plot_data["yCentroid"][step]))
r_temps[step] = r_temp
if azimuth > 0 and save_r:
save_r = False
r_tsep.append(r_temp)
if azimuth < 0:
save_r = True
# if step >= (16 * 95) + 6 and step % 16 == 6 and self._settings["turnsep"]:
# r = np.sqrt(np.square(np.mean(x_val)) + np.square(np.mean(y_val)))
# plot_data["R"] = np.append(plot_data["R"], r)
# if step > (16 * 95) + 6 and step % 16 == 6 and self._settings["turnsep"]:
# index += 1
# difference = np.abs(plot_data["R"][index-1] - plot_data["R"][index])
# plot_data["turnSep"] = np.append(plot_data["turnSep"], difference)
plots["plot_data{}".format(num)] = plot_data
num += 1
self._parent.send_status("Saving plot(s)...")
# Save plots as separate images, with appropriate titles
if self._settings["rms"]:
_xlim = 62.2
_ylim = 6.0
_figsize = (7, 5)
_fs = 12
fig = plt.figure(figsize=_figsize)
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'weight': 100, 'size': _fs})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.rc('ytick', labelsize=_fs)
plt.rc('xtick', labelsize=_fs)
ax1 = plt.subplot(311)
plt.title("RMS Beam Size (mm)")
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["xRMS"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
# print("Mean x RMS: {}".format(np.mean(plots["plot_data{}".format(n)]["xRMS"][40:])))
ax1.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax1.get_yaxis().set_major_formatter(FormatStrFormatter('%.1f'))
ax1.tick_params(labelbottom=False)
ax1.set_xlim([0, _xlim])
# ax1.set_ylim([0, _ylim])
ax1.set_ylim([0, 4.0])
plt.grid()
plt.ylabel("Transversal")
ax2 = plt.subplot(312, sharex=ax1)
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["yRMS"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
# print("Mean y RMS: {}".format(np.mean(plots["plot_data{}".format(n)]["yRMS"][40:])))
plt.legend(loc=9)
ax2.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax2.get_yaxis().set_major_formatter(FormatStrFormatter('%.1f'))
ax2.tick_params(labelbottom=False)
ax2.set_xlim([0, _xlim])
ax2.set_ylim([0, _ylim])
plt.grid()
plt.ylabel("Longitudinal")
ax3 = plt.subplot(313, sharex=ax1)
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["zRMS"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
# print("Mean z RMS: {}".format(np.mean(plots["plot_data{}".format(n)]["zRMS"][40:])))
ax3.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax3.get_yaxis().set_major_formatter(FormatStrFormatter('%.1f'))
ax3.set_xlim([0, _xlim])
ax3.set_ylim([0, _ylim])
plt.grid()
plt.xlabel("Energy (MeV/amu)")
plt.ylabel("Vertical")
# fig.tight_layout()
fig.savefig(self._filename[0] + '_rmsBeamSize.png', dpi=1200, bbox_inches='tight')
if self._settings["halo"]:
_xlim = 62.2
_ylim = 7.0
_figsize = (7, 5)
_fs = 12
fig = plt.figure(figsize=_figsize)
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'weight': 100, 'size': _fs})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.rc('ytick', labelsize=_fs)
plt.rc('xtick', labelsize=_fs)
ax1 = plt.subplot(311)
plt.title("Halo Parameter")
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["xHalo"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
ax1.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax1.tick_params(labelbottom=False)
ax1.set_ylim([0, _ylim])
ax1.set_xlim([0, _xlim])
plt.grid()
plt.ylabel("Transversal")
ax2 = plt.subplot(312, sharex=ax1)
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["yHalo"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
plt.legend(loc=9)
ax2.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax2.tick_params(labelbottom=False)
ax2.set_ylim([0, _ylim])
ax2.set_xlim([0, _xlim])
plt.grid()
plt.ylabel("Longitudinal")
ax3 = plt.subplot(313, sharex=ax1)
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["energy"], plots["plot_data{}".format(n)]["zHalo"], lw=0.8,
label=plots["plot_data{}".format(n)]["name"])
ax3.get_yaxis().set_major_locator(LinearLocator(numticks=5))
ax3.set_ylim([0, _ylim])
ax3.set_xlim([0, _xlim])
plt.grid()
plt.xlabel("Energy (MeV/amu)")
plt.ylabel("Vertical")
# fig.tight_layout()
fig.savefig(self._filename[0] + '_haloParameter.png', bbox_inches='tight', dpi=1200)
if self._settings["centroid"]:
fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.title("Top-down view of Centroid Position")
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["xCentroid"], plots["plot_data{}".format(n)]["yCentroid"],
'o', ms=0.5, label=plots["plot_data{}".format(n)]["name"])
plt.legend()
ax = plt.gca()
ax.set_aspect('equal')
plt.grid()
plt.xlabel("Horizontal (m)")
plt.ylabel("Longitudinal (m)")
fig.tight_layout()
fig.savefig(self._filename[0] + '_centroidPosition.png', bbox_inches='tight', dpi=1200)
# TODO: Fix turn separation to allow any number of steps
if self._settings["turnsep"]:
fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.title("Turn Separation")
plt.plot(1000.0 * np.diff(r_tsep))
# plt.plot(range(96, 105), 1000.0 * plot_data["turnSep"], 'k', lw=0.8)
plt.grid()
plt.xlabel("Turn Number")
plt.ylabel("Separation (mm)")
fig.savefig(self._filename[0] + '_turnSeparation.png', bbox_inches='tight', dpi=1200)
if self._settings["energyHist"]:
fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.title("Particle Energy")
for n in range(num):
plt.hist(plots["plot_data{}".format(n)]["energy"], bins=100, histtype='step',
# weights=np.full_like(plots["plot_data{}".format(n)]["energy"], 6348),
label="{}, total particles = {}".format(plots["plot_data{}".format(n)]["name"],
len(plots["plot_data{}".format(n)]["energy"])))
plt.legend()
plt.grid()
plt.xlabel("Energy (MeV/amu)")
plt.ylabel(r"Particle Density (a.u.)")
fig.tight_layout()
fig.savefig(self._filename[0] + '_energy.png', bbox_inches='tight', dpi=1200)
if self._settings["intensity"]:
fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.title("Histogram of the Beam Power (0.5 mm Bins)")
bin_width = 0.5 # mm
for n in range(num):
radii = plots["plot_data{}".format(n)]["R"] * 1.0e3 # m --> mm
r_len = radii.max() - radii.min()
n_bins = int(np.round(r_len / bin_width, 0))
print("Numerical bin width = {:.4f} mm".format(r_len/n_bins))
power, bins = np.histogram(radii, bins=n_bins, weights=plots["plot_data{}".format(n)]["power"])
# temp_bins = bins[200:-1]
# temp_power = power[200:]
#
# idx = np.where(temp_bins <= 1935) # 1940 for Probe25
#
# temp_bins = temp_bins[idx]
# temp_power = temp_power[idx]
#
# print("Min R =", temp_bins[np.where(temp_power == np.min(temp_power))], "mm\n")
# print("Min P =", temp_power[np.where(temp_power == np.min(temp_power))], "W\n")
plt.hist(bins[:-1], bins, weights=power,
label=plots["plot_data{}".format(n)]["name"], alpha=0.3, log=True)
plt.gca().axhline(200.0, linestyle="--", color="black", linewidth=1.0, label="200 W Limit")
plt.legend(loc=2)
plt.grid()
plt.xlabel("Radius (mm)")
plt.ylabel("Beam Power (W)")
fig.tight_layout()
fig.savefig(self._filename[0] + '_power.png', bbox_inches='tight', dpi=1200)
if self._settings["xz"]:
fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
plt.title("Probe Scatter Plot")
ax = plt.gca()
for n in range(num):
plt.plot(plots["plot_data{}".format(n)]["R"] * 1000.0, # m --> mm
plots["plot_data{}".format(n)]["coords"] * 1000.0, # m --> mm
'o', alpha=0.6, markersize=0.005, label=plots["plot_data{}".format(n)]["name"])
plt.grid()
ax.set_aspect('equal')
plt.xlabel("Radius (mm)")
plt.ylabel("Vertical (mm)")
fig.tight_layout()
fig.savefig(self._filename[0] + '_RZ.png', bbox_inches='tight', dpi=1200)
self._parent.send_status("Plot(s) saved successfully!")
@staticmethod
def rms(nparray):
mean_sqrd = np.mean(np.square(nparray))
return np.sqrt(mean_sqrd)
@staticmethod
def halo(nparray):
mean_sqrd = np.mean(np.square(nparray))
mean_frth = np.mean(np.square(np.square(nparray)))
return mean_frth/(np.square(mean_sqrd)) - 1.0
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._beamCharWindow.width())
_y = 0.5 * (screen_size.height() - self._beamCharWindow.height())
# --- Show the GUI --- #
self._beamCharWindow.show()
self._beamCharWindow.move(_x, _y)
def open_gui(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self._filename = QFileDialog.getSaveFileName(caption="Saving plots...", options=options,
filter="Image (*.png)")
self.run()
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'generate_envelope.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Generate_Envelope(object):
def setupUi(self, Generate_Envelope):
Generate_Envelope.setObjectName("Generate_Envelope")
Generate_Envelope.resize(488, 648)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Generate_Envelope.sizePolicy().hasHeightForWidth())
Generate_Envelope.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(Generate_Envelope)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 451, 607))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setMaximumSize(QtCore.QSize(500, 25))
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.gridLayout.setObjectName("gridLayout")
self.tr_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label.setObjectName("tr_label")
self.gridLayout.addWidget(self.tr_label, 1, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.tl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label.setObjectName("tl_label")
self.gridLayout.addWidget(self.tl_label, 0, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 4, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.zr = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zr.setObjectName("zr")
self.gridLayout.addWidget(self.zr, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.zpos = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.zpos.setMinimumSize(QtCore.QSize(142, 0))
self.zpos.setMaximumSize(QtCore.QSize(176, 16777215))
self.zpos.setObjectName("zpos")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.gridLayout.addWidget(self.zpos, 0, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.ze = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ze.setEnabled(False)
self.ze.setObjectName("ze")
self.gridLayout.addWidget(self.ze, 4, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 5, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.bl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label.setObjectName("bl_label")
self.gridLayout.addWidget(self.bl_label, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 1, 0, 1, 1)
self.zmom = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.zmom.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.zmom.sizePolicy().hasHeightForWidth())
self.zmom.setSizePolicy(sizePolicy)
self.zmom.setMinimumSize(QtCore.QSize(142, 0))
self.zmom.setMaximumSize(QtCore.QSize(176, 16777215))
self.zmom.setObjectName("zmom")
self.zmom.addItem("")
self.zmom.addItem("")
self.zmom.addItem("")
self.zmom.addItem("")
self.gridLayout.addWidget(self.zmom, 1, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.gridLayout_3 = QtWidgets.QGridLayout()
self.gridLayout_3.setObjectName("gridLayout_3")
self.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_8.setObjectName("label_8")
self.gridLayout_3.addWidget(self.label_8, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_9 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_9.setObjectName("label_9")
self.gridLayout_3.addWidget(self.label_9, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.zpstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zpstddev.setEnabled(False)
self.zpstddev.setMinimumSize(QtCore.QSize(100, 0))
self.zpstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.zpstddev.setObjectName("zpstddev")
self.gridLayout_3.addWidget(self.zpstddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.zmstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zmstddev.setEnabled(False)
self.zmstddev.setMinimumSize(QtCore.QSize(100, 0))
self.zmstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.zmstddev.setObjectName("zmstddev")
self.gridLayout_3.addWidget(self.zmstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout.addLayout(self.gridLayout_3, 5, 2, 1, 1)
self.gridLayout.setRowMinimumHeight(0, 20)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem1 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem1)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setMaximumSize(QtCore.QSize(16777215, 25))
self.label_4.setObjectName("label_4")
self.verticalLayout_3.addWidget(self.label_4)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.xydist = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.xydist.setMinimumSize(QtCore.QSize(142, 0))
self.xydist.setMaximumSize(QtCore.QSize(176, 16777215))
self.xydist.setObjectName("xydist")
self.xydist.addItem("")
self.xydist.addItem("")
self.xydist.addItem("")
self.xydist.addItem("")
self.verticalLayout_2.addWidget(self.xydist, 0, QtCore.Qt.AlignHCenter)
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.gridLayout_2.setObjectName("gridLayout_2")
self.yrp = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.yrp.setObjectName("yrp")
self.gridLayout_2.addWidget(self.yrp, 7, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_6.setObjectName("bl_label_6")
self.gridLayout_2.addWidget(self.bl_label_6, 2, 1, 1, 1, QtCore.Qt.AlignRight)
self.bl_label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_3.setObjectName("bl_label_3")
self.gridLayout_2.addWidget(self.bl_label_3, 7, 1, 1, 1, QtCore.Qt.AlignRight)
self.tl_label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label_2.setObjectName("tl_label_2")
self.gridLayout_2.addWidget(self.tl_label_2, 0, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.ye = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ye.setObjectName("ye")
self.gridLayout_2.addWidget(self.ye, 8, 2, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem2 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem2, 6, 0, 2, 1)
self.label_5 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 8, 1, 1, 1, QtCore.Qt.AlignRight)
self.label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_6.setObjectName("label_6")
self.gridLayout_2.addWidget(self.label_6, 9, 1, 1, 1, QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
self.yr = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.yr.setEnabled(True)
self.yr.setObjectName("yr")
self.gridLayout_2.addWidget(self.yr, 6, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_4.setObjectName("bl_label_4")
self.gridLayout_2.addWidget(self.bl_label_4, 6, 1, 1, 1, QtCore.Qt.AlignRight)
self.tr_label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label_2.setObjectName("tr_label_2")
self.gridLayout_2.addWidget(self.tr_label_2, 5, 1, 1, 1, QtCore.Qt.AlignLeft)
self.xe = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xe.setEnabled(True)
self.xe.setObjectName("xe")
self.gridLayout_2.addWidget(self.xe, 3, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_5 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_5.setObjectName("bl_label_5")
self.gridLayout_2.addWidget(self.bl_label_5, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.xr = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xr.setEnabled(True)
self.xr.setObjectName("xr")
self.gridLayout_2.addWidget(self.xr, 1, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.label_7 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_7.setObjectName("label_7")
self.gridLayout_2.addWidget(self.label_7, 3, 1, 1, 1, QtCore.Qt.AlignRight)
self.xrp = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xrp.setEnabled(True)
self.xrp.setObjectName("xrp")
self.gridLayout_2.addWidget(self.xrp, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.label_10 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_10.setObjectName("label_10")
self.gridLayout_2.addWidget(self.label_10, 4, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_4 = QtWidgets.QGridLayout()
self.gridLayout_4.setObjectName("gridLayout_4")
self.label_11 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_11.setObjectName("label_11")
self.gridLayout_4.addWidget(self.label_11, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_12 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_12.setObjectName("label_12")
self.gridLayout_4.addWidget(self.label_12, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.xstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xstddev.setEnabled(False)
self.xstddev.setMinimumSize(QtCore.QSize(100, 0))
self.xstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.xstddev.setObjectName("xstddev")
self.gridLayout_4.addWidget(self.xstddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.xpstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xpstddev.setEnabled(False)
self.xpstddev.setMinimumSize(QtCore.QSize(100, 0))
self.xpstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.xpstddev.setObjectName("xpstddev")
self.gridLayout_4.addWidget(self.xpstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_2.addLayout(self.gridLayout_4, 4, 2, 1, 1)
self.gridLayout_5 = QtWidgets.QGridLayout()
self.gridLayout_5.setObjectName("gridLayout_5")
self.label_13 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_13.setObjectName("label_13")
self.gridLayout_5.addWidget(self.label_13, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_14 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_14.setObjectName("label_14")
self.gridLayout_5.addWidget(self.label_14, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.ystddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ystddev.setEnabled(False)
self.ystddev.setMinimumSize(QtCore.QSize(100, 0))
self.ystddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.ystddev.setObjectName("ystddev")
self.gridLayout_5.addWidget(self.ystddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.ypstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ypstddev.setEnabled(False)
self.ypstddev.setMinimumSize(QtCore.QSize(100, 0))
self.ypstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.ypstddev.setObjectName("ypstddev")
self.gridLayout_5.addWidget(self.ypstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_2.addLayout(self.gridLayout_5, 9, 2, 1, 1)
self.checkBox = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBox.setAcceptDrops(False)
self.checkBox.setChecked(False)
self.checkBox.setTristate(False)
self.checkBox.setObjectName("checkBox")
self.gridLayout_2.addWidget(self.checkBox, 5, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout_2.addLayout(self.gridLayout_2)
self.verticalLayout_3.addLayout(self.verticalLayout_2)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox)
Generate_Envelope.setCentralWidget(self.centralwidget)
self.retranslateUi(Generate_Envelope)
QtCore.QMetaObject.connectSlotsByName(Generate_Envelope)
def retranslateUi(self, Generate_Envelope):
_translate = QtCore.QCoreApplication.translate
Generate_Envelope.setWindowTitle(_translate("Generate_Envelope", "Generate Distribution: Enter Parameters"))
self.label.setText(_translate("Generate_Envelope", "Longitudinal Distribution"))
self.tr_label.setText(_translate("Generate_Envelope", "Momentum:"))
self.tl_label.setText(_translate("Generate_Envelope", "Position:"))
self.label_2.setText(_translate("Generate_Envelope", "Normalized Emittance (pi-mm-mrad):"))
self.zpos.setItemText(0, _translate("Generate_Envelope", "Constant"))
self.zpos.setItemText(1, _translate("Generate_Envelope", "Uniform along length"))
self.zpos.setItemText(2, _translate("Generate_Envelope", "Uniform on ellipse"))
self.zpos.setItemText(3, _translate("Generate_Envelope", "Gaussian on ellipse"))
self.zpos.setItemText(4, _translate("Generate_Envelope", "Waterbag"))
self.zpos.setItemText(5, _translate("Generate_Envelope", "Parabolic"))
self.label_3.setText(_translate("Generate_Envelope", "Standard Deviation:"))
self.bl_label.setText(_translate("Generate_Envelope", "Length/Envelope Radius (mm):"))
self.zmom.setItemText(0, _translate("Generate_Envelope", "Constant"))
self.zmom.setItemText(1, _translate("Generate_Envelope", "Uniform along length"))
self.zmom.setItemText(2, _translate("Generate_Envelope", "Uniform on ellipse"))
self.zmom.setItemText(3, _translate("Generate_Envelope", "Gaussian on ellipse"))
self.label_8.setText(_translate("Generate_Envelope", "Position (mm):"))
self.label_9.setText(_translate("Generate_Envelope", "Momentum (mrad):"))
self.label_4.setText(_translate("Generate_Envelope", "Transverse Distribution"))
self.xydist.setItemText(0, _translate("Generate_Envelope", "Uniform"))
self.xydist.setItemText(1, _translate("Generate_Envelope", "Gaussian"))
self.xydist.setItemText(2, _translate("Generate_Envelope", "Waterbag"))
self.xydist.setItemText(3, _translate("Generate_Envelope", "Parabolic"))
self.bl_label_6.setText(_translate("Generate_Envelope", "Envelope Angle (mrad):"))
self.bl_label_3.setText(_translate("Generate_Envelope", "Envelope Angle (mrad):"))
self.tl_label_2.setText(_translate("Generate_Envelope", "X Phase Space Ellipse:"))
self.label_5.setText(_translate("Generate_Envelope", "Normalized Emittance (pi-mm-mrad):"))
self.label_6.setText(_translate("Generate_Envelope", "Standard Deviation:"))
self.bl_label_4.setText(_translate("Generate_Envelope", "Envelope Radius (mm):"))
self.tr_label_2.setText(_translate("Generate_Envelope", "Y Phase Space Ellipse:"))
self.bl_label_5.setText(_translate("Generate_Envelope", "Envelope Radius (mm):"))
self.label_7.setText(_translate("Generate_Envelope", "Normalized Emittance (pi-mm-mrad):"))
self.label_10.setText(_translate("Generate_Envelope", "Standard Deviation:"))
self.label_11.setText(_translate("Generate_Envelope", "Radius (mm):"))
self.label_12.setText(_translate("Generate_Envelope", "Angle (mrad):"))
self.label_13.setText(_translate("Generate_Envelope", "Radius (mm):"))
self.label_14.setText(_translate("Generate_Envelope", "Angle (mrad):"))
self.checkBox.setText(_translate("Generate_Envelope", "Symmetric?"))
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui/default_plot_settings.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DefaultPlotSettingsWindow(object):
def setupUi(self, DefaultPlotSettingsWindow):
DefaultPlotSettingsWindow.setObjectName("DefaultPlotSettingsWindow")
DefaultPlotSettingsWindow.resize(377, 251)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(DefaultPlotSettingsWindow.sizePolicy().hasHeightForWidth())
DefaultPlotSettingsWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(DefaultPlotSettingsWindow)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 374, 247))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.main_label = QtWidgets.QLabel(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.main_label.sizePolicy().hasHeightForWidth())
self.main_label.setSizePolicy(sizePolicy)
self.main_label.setObjectName("main_label")
self.verticalLayout_3.addWidget(self.main_label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
spacerItem = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.bl_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.bl_enabled.setFocusPolicy(QtCore.Qt.NoFocus)
self.bl_enabled.setCheckable(True)
self.bl_enabled.setChecked(True)
self.bl_enabled.setObjectName("bl_enabled")
self.gridLayout.addWidget(self.bl_enabled, 3, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tl_combo_a = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.tl_combo_a.setObjectName("tl_combo_a")
self.tl_combo_a.addItem("")
self.tl_combo_a.addItem("")
self.tl_combo_a.addItem("")
self.tl_combo_a.addItem("")
self.tl_combo_a.addItem("")
self.tl_combo_a.addItem("")
self.gridLayout.addWidget(self.tl_combo_a, 1, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.bl_combo_a = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.bl_combo_a.setObjectName("bl_combo_a")
self.bl_combo_a.addItem("")
self.bl_combo_a.addItem("")
self.bl_combo_a.addItem("")
self.bl_combo_a.addItem("")
self.bl_combo_a.addItem("")
self.bl_combo_a.addItem("")
self.gridLayout.addWidget(self.bl_combo_a, 3, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tl_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.tl_enabled.setEnabled(True)
self.tl_enabled.setFocusPolicy(QtCore.Qt.NoFocus)
self.tl_enabled.setCheckable(True)
self.tl_enabled.setChecked(True)
self.tl_enabled.setObjectName("tl_enabled")
self.gridLayout.addWidget(self.tl_enabled, 1, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label.setObjectName("tl_label")
self.gridLayout.addWidget(self.tl_label, 1, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tr_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label.setObjectName("tr_label")
self.gridLayout.addWidget(self.tr_label, 2, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.step_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.step_label.setObjectName("step_label")
self.gridLayout.addWidget(self.step_label, 0, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tr_combo_b = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.tr_combo_b.setObjectName("tr_combo_b")
self.tr_combo_b.addItem("")
self.tr_combo_b.addItem("")
self.tr_combo_b.addItem("")
self.tr_combo_b.addItem("")
self.tr_combo_b.addItem("")
self.tr_combo_b.addItem("")
self.gridLayout.addWidget(self.tr_combo_b, 2, 3, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.bl_combo_b = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.bl_combo_b.setObjectName("bl_combo_b")
self.bl_combo_b.addItem("")
self.bl_combo_b.addItem("")
self.bl_combo_b.addItem("")
self.bl_combo_b.addItem("")
self.bl_combo_b.addItem("")
self.bl_combo_b.addItem("")
self.gridLayout.addWidget(self.bl_combo_b, 3, 3, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.three_d_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.three_d_enabled.setFocusPolicy(QtCore.Qt.NoFocus)
self.three_d_enabled.setCheckable(True)
self.three_d_enabled.setObjectName("three_d_enabled")
self.gridLayout.addWidget(self.three_d_enabled, 4, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tr_combo_a = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.tr_combo_a.setObjectName("tr_combo_a")
self.tr_combo_a.addItem("")
self.tr_combo_a.addItem("")
self.tr_combo_a.addItem("")
self.tr_combo_a.addItem("")
self.tr_combo_a.addItem("")
self.tr_combo_a.addItem("")
self.gridLayout.addWidget(self.tr_combo_a, 2, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tl_combo_b = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.tl_combo_b.setObjectName("tl_combo_b")
self.tl_combo_b.addItem("")
self.tl_combo_b.addItem("")
self.tl_combo_b.addItem("")
self.tl_combo_b.addItem("")
self.tl_combo_b.addItem("")
self.tl_combo_b.addItem("")
self.gridLayout.addWidget(self.tl_combo_b, 1, 3, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.bl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label.setObjectName("bl_label")
self.gridLayout.addWidget(self.bl_label, 3, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.step_input = QtWidgets.QSpinBox(self.verticalLayoutWidget)
self.step_input.setMinimum(0)
self.step_input.setMaximum(999999999)
self.step_input.setObjectName("step_input")
self.gridLayout.addWidget(self.step_input, 0, 1, 1, 1)
self.three_d_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.three_d_label.setObjectName("three_d_label")
self.gridLayout.addWidget(self.three_d_label, 4, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.tr_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.tr_enabled.setFocusPolicy(QtCore.Qt.NoFocus)
self.tr_enabled.setCheckable(True)
self.tr_enabled.setChecked(True)
self.tr_enabled.setObjectName("tr_enabled")
self.gridLayout.addWidget(self.tr_enabled, 2, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.redraw_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.redraw_label.setObjectName("redraw_label")
self.gridLayout.addWidget(self.redraw_label, 5, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.redraw_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.redraw_enabled.setChecked(True)
self.redraw_enabled.setObjectName("redraw_enabled")
self.gridLayout.addWidget(self.redraw_enabled, 5, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem1)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.redraw_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.redraw_button.setObjectName("redraw_button")
self.horizontalLayout_9.addWidget(self.redraw_button)
spacerItem2 = QtWidgets.QSpacerItem(40, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem2)
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout_9.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout_9.addWidget(self.apply_button)
self.verticalLayout_3.addLayout(self.horizontalLayout_9)
DefaultPlotSettingsWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(DefaultPlotSettingsWindow)
self.bl_combo_a.setCurrentIndex(1)
self.tr_combo_b.setCurrentIndex(3)
self.bl_combo_b.setCurrentIndex(4)
self.tl_combo_b.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(DefaultPlotSettingsWindow)
def retranslateUi(self, DefaultPlotSettingsWindow):
_translate = QtCore.QCoreApplication.translate
DefaultPlotSettingsWindow.setWindowTitle(_translate("DefaultPlotSettingsWindow", "Properties"))
self.main_label.setText(_translate("DefaultPlotSettingsWindow", "DEFAULT PLOT SETTINGS"))
self.bl_enabled.setText(_translate("DefaultPlotSettingsWindow", "Enabled"))
self.tl_combo_a.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.tl_combo_a.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.tl_combo_a.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.tl_combo_a.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.tl_combo_a.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.tl_combo_a.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.bl_combo_a.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.bl_combo_a.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.bl_combo_a.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.bl_combo_a.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.bl_combo_a.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.bl_combo_a.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.tl_enabled.setText(_translate("DefaultPlotSettingsWindow", "Enabled"))
self.tl_label.setText(_translate("DefaultPlotSettingsWindow", "Top Left:"))
self.tr_label.setText(_translate("DefaultPlotSettingsWindow", "Top Right:"))
self.step_label.setText(_translate("DefaultPlotSettingsWindow", "Step #:"))
self.tr_combo_b.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.tr_combo_b.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.tr_combo_b.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.tr_combo_b.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.tr_combo_b.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.tr_combo_b.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.bl_combo_b.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.bl_combo_b.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.bl_combo_b.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.bl_combo_b.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.bl_combo_b.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.bl_combo_b.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.three_d_enabled.setText(_translate("DefaultPlotSettingsWindow", "Enabled"))
self.tr_combo_a.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.tr_combo_a.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.tr_combo_a.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.tr_combo_a.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.tr_combo_a.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.tr_combo_a.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.tl_combo_b.setItemText(0, _translate("DefaultPlotSettingsWindow", "X"))
self.tl_combo_b.setItemText(1, _translate("DefaultPlotSettingsWindow", "Y"))
self.tl_combo_b.setItemText(2, _translate("DefaultPlotSettingsWindow", "Z"))
self.tl_combo_b.setItemText(3, _translate("DefaultPlotSettingsWindow", "PX"))
self.tl_combo_b.setItemText(4, _translate("DefaultPlotSettingsWindow", "PY"))
self.tl_combo_b.setItemText(5, _translate("DefaultPlotSettingsWindow", "PZ"))
self.bl_label.setText(_translate("DefaultPlotSettingsWindow", "Bottom Left:"))
self.three_d_label.setText(_translate("DefaultPlotSettingsWindow", "3D Plot:"))
self.tr_enabled.setText(_translate("DefaultPlotSettingsWindow", "Enabled"))
self.redraw_label.setText(_translate("DefaultPlotSettingsWindow", "Redraw On Selection: "))
self.redraw_enabled.setText(_translate("DefaultPlotSettingsWindow", "Enabled"))
self.redraw_button.setText(_translate("DefaultPlotSettingsWindow", "Redraw"))
self.cancel_button.setText(_translate("DefaultPlotSettingsWindow", "Cancel"))
self.apply_button.setText(_translate("DefaultPlotSettingsWindow", "Apply"))
<file_sep>from TraceWinDriver import *
<file_sep>from dans_pymodules import *
# import h5py
from drivers import *
__author__ = "<NAME>"
__doc__ = """A container that holds a single dataset with
multiple time steps and multiple particles per time step. If the data
is too large for memory, it is automatically transferred into
a h5 file on disk to be operated on.
"""
# Initialize some global constants
amu = const.value("atomic mass constant energy equivalent in MeV")
echarge = const.value("elementary charge")
clight = const.value("speed of light in vacuum")
class ImportExportDriver(object):
"""
A thin wrapper around the drivers for importing and exporting particle data
"""
def __init__(self,
driver_name=None,
debug=False):
self._driver_name = driver_name
self._driver = None
self._debug = debug
self.load_driver()
def load_driver(self):
self._driver = driver_mapping[self._driver_name]['driver'](debug=self._debug)
def get_driver_name(self):
return self._driver_name
def import_data(self, filename):
return self._driver.import_data(filename)
def export_data(self, data):
return self._driver.export_data(data)
class Dataset(object):
def __init__(self, debug=False):
self._datasource = None
self._filename = None
self._driver = None
self._ion = None
self._nsteps = 0
self._multispecies = False
self._debug = debug
self._data = None
self._current = 0.0
self._npart = 0 # TODO: For now this is the number of particles at step 0. -DW
def close(self):
"""
Close the dataset's source and return
:return:
"""
if self._datasource is not None:
try:
self._datasource.close()
except Exception as e:
if self._debug:
print("Exception occured during closing of datafile: {}".format(e))
return 1
return 0
def get(self, key):
"""
Returns the values for the currently set step and given key ("x", "y", "z", "px", "py", "pz")
:return:
"""
if key not in ["x", "y", "z", "px", "py", "pz"]:
if self._debug:
print("get(key): Key was not one of 'x', 'y', 'z', 'px', 'py', 'pz'")
return 1
if self._data is None:
if self._debug:
print("get(key): No data loaded yet!")
return 1
return self._data.get(key).value
def get_a(self):
return self._ion.a()
def get_filename(self):
return self._filename
def get_i(self):
return self._current
def get_npart(self):
return self._npart
def get_q(self):
return self._ion.q()
def load_from_file(self, filename, driver=None):
"""
Load a dataset from file. If the file is h5 already, don't load into memory.
Users can write their own drivers but they have to be compliant with the
internal structure of datasets.
:param filename:
:param driver:
:return:
"""
self._driver = driver
self._filename = filename
if driver is not None:
new_ied = ImportExportDriver(driver_name=driver)
_data = new_ied.import_data(self._filename)
if _data is not None:
self._datasource = _data["datasource"]
self._ion = _data["ion"]
self._nsteps = _data["nsteps"]
self._current = _data["current"]
self._npart = _data["npart"]
self.set_step_view(0)
return 0
return 1
def set_step_view(self, step):
if step > self._nsteps:
if self._debug:
print("set_step_view: Requested step {} exceeded max steps of {}!".format(step, self._nsteps))
return 1
self._data = self._datasource.get("Step#{}".format(step))
return 0
<file_sep>from py_particle_processor_qt.tools.BeamChar.BeamChar import *
<file_sep>from py_particle_processor_qt.tools.OrbitTool.OrbitTool import *
<file_sep># from dans_pymodules import IonSpecies
# import h5py
from dans_pymodules import *
from scipy import constants as const
from py_particle_processor_qt.drivers import *
__author__ = "<NAME>, <NAME>"
__doc__ = """A container that holds a single dataset with
multiple time steps and multiple particles per time step. If the data
is too large for memory, it is automatically transferred into
a h5 file on disk to be operated on.
"""
# Initialize some global constants
amu = const.value("atomic mass constant energy equivalent in MeV")
echarge = const.value("elementary charge")
clight = const.value("speed of light in vacuum")
colors = MyColors()
class ImportExportDriver(object):
"""
A thin wrapper around the drivers for importing and exporting particle data
"""
def __init__(self, driver_name=None, debug=False):
self._driver_name = driver_name
self._driver = None
self._debug = debug
self.load_driver()
def load_driver(self):
self._driver = driver_mapping[self._driver_name]['driver'](debug=self._debug)
def get_driver_name(self):
return self._driver_name
def import_data(self, filename, species):
return self._driver.import_data(filename, species=species)
def export_data(self, dataset, filename):
return self._driver.export_data(dataset=dataset, filename=filename)
class Dataset(object):
def __init__(self, indices, species, data=None, debug=False):
self._draw = False
self._selected = False
self._datasource = data
self._filename = None
self._driver = None
self._species = species
self._debug = debug
self._data = None
self._color = (0.0, 0.0, 0.0)
self._indices = indices
self._orbit = None
self._center_orbit = False
self._properties = {"name": None,
"ion": species,
"multispecies": None,
"current": None,
"mass": None,
"energy": None,
"steps": 0,
"curstep": None,
"charge": None,
"particles": None}
self._native_properties = {}
# This will only be true if the data was supplied via a generator
# Temporary flags for development - PW
if self._datasource is not None:
self._is_generated = True
else:
self._is_generated = False
def close(self):
"""
Close the dataset's source and return
:return:
"""
if self._datasource is not None:
try:
self._datasource.close()
except Exception as e:
if self._debug:
print("Exception occurred during closing of datafile: {}".format(e))
return 1
return 0
def color(self):
return self._color
def assign_color(self, i):
self._color = colors[i]
def export_to_file(self, filename, driver):
if driver is not None:
new_ied = ImportExportDriver(driver_name=driver, debug=self._debug)
new_ied.export_data(dataset=self, filename=filename)
elif driver is None:
return 1
def get_property(self, key):
return self._properties[key]
def xy_orbit(self, triplet, center=False):
# Uses a triplet of step numbers to find the center of an orbit
self._center_orbit = center
# Source: https://math.stackexchange.com/questions/213658/get-the-equation-of-a-circle-when-given-3-points
_x, _y = [], []
for step in triplet:
self.set_step_view(step)
_x.append(float(self.get("x")))
_y.append(float(self.get("y")))
matrix = np.matrix([[_x[0] ** 2.0 + _y[0] ** 2.0, _x[0], _y[0], 1],
[_x[1] ** 2.0 + _y[1] ** 2.0, _x[1], _y[1], 1],
[_x[2] ** 2.0 + _y[2] ** 2.0, _x[2], _y[2], 1]])
m11 = np.linalg.det(np.delete(matrix, 0, 1))
m12 = np.linalg.det(np.delete(matrix, 1, 1))
m13 = np.linalg.det(np.delete(matrix, 2, 1))
m14 = np.linalg.det(np.delete(matrix, 3, 1))
xc = 0.5 * m12 / m11
yc = -0.5 * m13 / m11
r = np.sqrt(xc ** 2.0 + yc ** 2.0 + m14 / m11)
self._orbit = (xc, yc, r)
if self._debug:
print(self._orbit)
return 0
def orbit(self):
return self._orbit
def set_property(self, key, value):
self._properties[key] = value
return 0
def is_native_property(self, key):
try:
return self._native_properties[key] == self._properties[key]
except KeyError:
return False
def properties(self):
return self._properties
def get_selected(self):
return self._selected
def set_selected(self, selected):
self._selected = selected
def get(self, key):
"""
Returns the values for the currently set step and given key ("id", "x", "y", "z", "r", "px", "py", "pz")
:return:
"""
if key not in ["id", "x", "y", "z", "r", "px", "py", "pz", "pr"]:
if self._debug:
print("get(key): Key was not one of 'id', 'x', 'y', 'z', 'r', 'px', 'py', 'pz', 'pr'")
return 1
if self._data is None:
if self._debug:
print("get(key): No data loaded yet!")
return 1
if key is "r":
data_x = self._data.get("x")[()]
data_y = self._data.get("y")[()]
if self._orbit is not None and self._center_orbit is True:
data = np.sqrt((data_x - self._orbit[0]) ** 2.0 + (data_y - self._orbit[1]) ** 2.0)
else:
data = np.sqrt(data_x ** 2.0 + data_y ** 2.0)
return data
elif key is "pr":
data_px = self._data.get("px")[()]
data_py = self._data.get("py")[()]
p = np.sqrt(data_px ** 2.0 + data_py ** 2.0)
data_x = self._data.get("x")[()]
data_y = self._data.get("y")[()]
if self._orbit is not None and self._center_orbit is True:
r = np.sqrt((data_x - self._orbit[0]) ** 2.0 + (data_y - self._orbit[1]) ** 2.0)
else:
r = np.sqrt(data_x ** 2.0 + data_y ** 2.0)
factor = (data_px * data_x + data_py * data_y)/(abs(p) * abs(r))
data = p * factor
return data
else:
data = self._data.get(key)
return data[()]
def get_particle(self, particle_id, get_color=False):
particle = {"x": [], "y": [], "z": []}
max_step = self.get_nsteps()
color = None
for step in range(max_step):
self.set_step_view(step)
for key in ["x", "y", "z"]:
dat = self._data.get(key)[()][particle_id]
if np.isnan(dat) or dat == 0.0: # TODO: A better way to figure out when a particle terminates
if get_color == "step":
factor = float(step) / float(max_step)
color = ((1 - factor) * 255.0, factor * 255.0, 0.0)
elif get_color == "random":
color = colors[particle_id]
return particle, color
else:
particle[key].append(dat)
if get_color == "step":
color = (0.0, 255.0, 0.0)
elif get_color == "random":
color = colors[particle_id]
return particle, color
# noinspection PyUnresolvedReferences
def get_a(self):
if isinstance(self._properties, IonSpecies):
return self._properties["ion"].a()
else:
return None
def get_current_step(self):
return self._properties["curstep"]
def get_datasource(self):
return self._datasource
def get_driver(self):
return self._driver
def get_filename(self):
return self._filename
def get_i(self):
return self._properties["current"]
def get_ion(self):
return self._properties["ion"]
def get_npart(self):
return self._properties["particles"]
def get_nsteps(self):
return self._properties["steps"]
def get_name(self):
return self._properties["name"]
# noinspection PyUnresolvedReferences
def get_q(self):
if isinstance(self._properties, IonSpecies):
return self._properties["ion"].q()
else:
return None
def indices(self):
return self._indices
def load_from_file(self, filename, name, driver=None):
"""
Load a dataset from file. If the file is h5 already, don't load into memory.
Users can write their own drivers but they have to be compliant with the
internal structure of datasets.
:param filename:
:param driver:
:param name: dataset label
:return:
"""
self._driver = driver
self._filename = filename
if driver is not None:
new_ied = ImportExportDriver(driver_name=driver, debug=self._debug)
_data = new_ied.import_data(self._filename, species=self._species)
# if self._debug:
# print("_data is {}".format(_data))
if _data is not None:
self._datasource = _data["datasource"]
for k in _data.keys():
self._properties[k] = _data[k]
self._native_properties[k] = _data[k]
# if isinstance(self._properties["ion"], IonSpecies):
# self._properties["name"] = self._properties["ion"].name()
# self._native_properties["name"] = self._properties["ion"].name()
self._properties["name"] = name
# self._native_properties["name"] = name
self.set_step_view(0)
# self.set_step_view(self._nsteps - 1)
# print(self._datasource)
return 0
return 1
def set_indices(self, parent_index, index):
self._indices = (parent_index, index)
# def set_name(self, name):
# self._properties["name"] = name
# self._native_properties["name"] = name
def set_step_view(self, step):
if step > self._properties["steps"]:
if self._debug:
print("set_step_view: Requested step {} exceeded max steps of {}!".format(step,
self._properties["steps"]))
return 1
self._properties["curstep"] = step
self._data = self._datasource.get("Step#{}".format(step))
return 0
<file_sep>from py_particle_processor_qt.drivers.FreeCADDriver.FreeCADDriver import *
<file_sep>from py_particle_processor_qt.drivers.COMSOLDriver.COMSOLDriver import *
<file_sep>from py_particle_processor_qt.drivers.OPALDriver import *
from py_particle_processor_qt.drivers.TraceWinDriver import *
from py_particle_processor_qt.drivers.COMSOLDriver import *
from py_particle_processor_qt.drivers.IBSimuDriver import *
from py_particle_processor_qt.drivers.TrackDriver import *
from py_particle_processor_qt.drivers.FreeCADDriver import *
"""
The driver mapping contains the information needed for the ImportExportDriver class to wrap around the drivers
Rules:
key has to be unique and one continuous 'word'
several extensions can be specified for one driver
"""
driver_mapping = {'OPAL': {'driver': OPALDriver,
'extensions': ['.h5', '.dat']},
'TraceWin': {'driver': TraceWinDriver,
'extensions': ['.txt', '.dat']},
'COMSOL': {'driver': COMSOLDriver,
'extensions': ['.txt']},
'IBSimu': {'driver': IBSimuDriver,
'extensions': ['.txt']},
'Track': {'driver': TrackDriver,
'extensions': ['.out']},
'FreeCAD': {'driver': FreeCADDriver,
'extensions': ['.dat']}
}
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui/plot_settings.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_PlotSettingsWindow(object):
def setupUi(self, PlotSettingsWindow):
PlotSettingsWindow.setObjectName("PlotSettingsWindow")
PlotSettingsWindow.resize(317, 186)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(PlotSettingsWindow.sizePolicy().hasHeightForWidth())
PlotSettingsWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(PlotSettingsWindow)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 317, 183))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.main_label = QtWidgets.QLabel(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.main_label.sizePolicy().hasHeightForWidth())
self.main_label.setSizePolicy(sizePolicy)
self.main_label.setObjectName("main_label")
self.verticalLayout_3.addWidget(self.main_label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
spacerItem = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.three_d_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.three_d_enabled.setFocusPolicy(QtCore.Qt.NoFocus)
self.three_d_enabled.setCheckable(True)
self.three_d_enabled.setObjectName("three_d_enabled")
self.gridLayout.addWidget(self.three_d_enabled, 1, 1, 1, 1, QtCore.Qt.AlignLeft)
self.three_d_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.three_d_label.setObjectName("three_d_label")
self.gridLayout.addWidget(self.three_d_label, 1, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.step_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.step_label.setObjectName("step_label")
self.gridLayout.addWidget(self.step_label, 0, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.step_input = QtWidgets.QSpinBox(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.step_input.sizePolicy().hasHeightForWidth())
self.step_input.setSizePolicy(sizePolicy)
self.step_input.setMinimum(0)
self.step_input.setMaximum(999999999)
self.step_input.setObjectName("step_input")
self.gridLayout.addWidget(self.step_input, 0, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.param_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.param_label.setObjectName("param_label")
self.gridLayout.addWidget(self.param_label, 2, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.param_combo_a = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.param_combo_a.setObjectName("param_combo_a")
self.param_combo_a.addItem("")
self.param_combo_a.addItem("")
self.param_combo_a.addItem("")
self.param_combo_a.addItem("")
self.param_combo_a.addItem("")
self.param_combo_a.addItem("")
self.horizontalLayout.addWidget(self.param_combo_a)
self.param_combo_b = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.param_combo_b.setObjectName("param_combo_b")
self.param_combo_b.addItem("")
self.param_combo_b.addItem("")
self.param_combo_b.addItem("")
self.param_combo_b.addItem("")
self.param_combo_b.addItem("")
self.param_combo_b.addItem("")
self.horizontalLayout.addWidget(self.param_combo_b)
self.param_combo_c = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.param_combo_c.setEnabled(False)
self.param_combo_c.setObjectName("param_combo_c")
self.param_combo_c.addItem("")
self.param_combo_c.addItem("")
self.param_combo_c.addItem("")
self.param_combo_c.addItem("")
self.param_combo_c.addItem("")
self.param_combo_c.addItem("")
self.horizontalLayout.addWidget(self.param_combo_c)
self.gridLayout.addLayout(self.horizontalLayout, 2, 1, 1, 1)
self.param_enabled = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.param_enabled.setChecked(True)
self.param_enabled.setObjectName("param_enabled")
self.gridLayout.addWidget(self.param_enabled, 3, 1, 1, 1, QtCore.Qt.AlignLeft)
self.en_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.en_label.setText("")
self.en_label.setObjectName("en_label")
self.gridLayout.addWidget(self.en_label, 3, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem1)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.redraw_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.redraw_button.setObjectName("redraw_button")
self.horizontalLayout_9.addWidget(self.redraw_button)
spacerItem2 = QtWidgets.QSpacerItem(40, 10, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_9.addItem(spacerItem2)
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout_9.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout_9.addWidget(self.apply_button)
self.verticalLayout_3.addLayout(self.horizontalLayout_9)
PlotSettingsWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(PlotSettingsWindow)
self.param_combo_b.setCurrentIndex(1)
self.param_combo_c.setCurrentIndex(2)
QtCore.QMetaObject.connectSlotsByName(PlotSettingsWindow)
def retranslateUi(self, PlotSettingsWindow):
_translate = QtCore.QCoreApplication.translate
PlotSettingsWindow.setWindowTitle(_translate("PlotSettingsWindow", "Properties"))
self.main_label.setText(_translate("PlotSettingsWindow", "PLOT SETTINGS"))
self.three_d_enabled.setText(_translate("PlotSettingsWindow", "Enabled"))
self.three_d_label.setText(_translate("PlotSettingsWindow", "3D"))
self.step_label.setText(_translate("PlotSettingsWindow", "Step #:"))
self.param_label.setText(_translate("PlotSettingsWindow", "Parameters"))
self.param_combo_a.setItemText(0, _translate("PlotSettingsWindow", "X"))
self.param_combo_a.setItemText(1, _translate("PlotSettingsWindow", "Y"))
self.param_combo_a.setItemText(2, _translate("PlotSettingsWindow", "Z"))
self.param_combo_a.setItemText(3, _translate("PlotSettingsWindow", "PX"))
self.param_combo_a.setItemText(4, _translate("PlotSettingsWindow", "PY"))
self.param_combo_a.setItemText(5, _translate("PlotSettingsWindow", "PZ"))
self.param_combo_b.setItemText(0, _translate("PlotSettingsWindow", "X"))
self.param_combo_b.setItemText(1, _translate("PlotSettingsWindow", "Y"))
self.param_combo_b.setItemText(2, _translate("PlotSettingsWindow", "Z"))
self.param_combo_b.setItemText(3, _translate("PlotSettingsWindow", "PX"))
self.param_combo_b.setItemText(4, _translate("PlotSettingsWindow", "PY"))
self.param_combo_b.setItemText(5, _translate("PlotSettingsWindow", "PZ"))
self.param_combo_c.setItemText(0, _translate("PlotSettingsWindow", "X"))
self.param_combo_c.setItemText(1, _translate("PlotSettingsWindow", "Y"))
self.param_combo_c.setItemText(2, _translate("PlotSettingsWindow", "Z"))
self.param_combo_c.setItemText(3, _translate("PlotSettingsWindow", "PX"))
self.param_combo_c.setItemText(4, _translate("PlotSettingsWindow", "PY"))
self.param_combo_c.setItemText(5, _translate("PlotSettingsWindow", "PZ"))
self.param_enabled.setText(_translate("PlotSettingsWindow", "Enabled"))
self.redraw_button.setText(_translate("PlotSettingsWindow", "Redraw"))
self.cancel_button.setText(_translate("PlotSettingsWindow", "Cancel"))
self.apply_button.setText(_translate("PlotSettingsWindow", "Apply"))
<file_sep># import h5py
from dans_pymodules import IonSpecies
import numpy as np
class ArrayWrapper(object):
def __init__(self, array_like):
self._array = np.array(array_like)
@property
def value(self):
return self._array
class TraceWinDriver(object):
def __init__(self, debug=False):
self._debug = debug
self._program_name = "TraceWin"
def get_program_name(self):
return self._program_name
def import_data(self, filename):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
try:
with open(filename, 'rb') as infile:
header1 = infile.readline()
if self._debug:
print(header1)
data = {}
npart, mass, energy, frequency, current, charge = \
[float(item) for item in infile.readline().strip().split()]
header2 = infile.readline()
if self._debug:
print(header2)
data["nsteps"] = 1
data["ion"] = IonSpecies('H2_1+', energy) # TODO: Actual ion species! -DW
data["current"] = current # (A)
data["npart"] = 0
_distribution = []
mydtype = [('x', float), ('xp', float),
('y', float), ('yp', float),
('z', float), ('zp', float),
('ph', float), ('t', float),
('e', float), ('l', float)]
for line in infile.readlines():
values = line.strip().split()
if values[-1] == "0":
data["npart"] += 1
_distribution.append(tuple(values))
_distribution = np.array(_distribution, dtype=mydtype)
gamma = _distribution['e'] / data['ion'].mass_mev() + 1.0
beta = np.sqrt(1.0 - gamma**(-2.0))
distribution = {'x': ArrayWrapper(_distribution['x'] * 0.001),
'px': ArrayWrapper(gamma * beta * np.sin(_distribution['xp'] * 0.001)),
'y': ArrayWrapper(_distribution['y'] * 0.001),
'py': ArrayWrapper(gamma * beta * np.sin(_distribution['yp'] * 0.001)),
'z': ArrayWrapper(_distribution['z'] * 0.001)}
distribution['pz'] = ArrayWrapper(np.sqrt(beta**2.0 * gamma**2.0
- distribution['px'].value**2.0
- distribution['py'].value**2.0
))
# For a single timestep, we just define a Step#0 entry in a dictionary (supports .get())
data["datasource"] = {"Step#0": distribution}
return data
except Exception as e:
print("Exception happened during particle loading with {} "
"ImportExportDriver: {}".format(self._program_name, e))
return None
def export_data(self, data):
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
print("Export not yet implemented :(")
return data
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'rotatetoolgui.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_RotateToolGUI(object):
def setupUi(self, RotateToolGUI):
RotateToolGUI.setObjectName("RotateToolGUI")
RotateToolGUI.resize(257, 125)
self.centralwidget = QtWidgets.QWidget(RotateToolGUI)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 254, 122))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.type_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.type_label.setObjectName("type_label")
self.gridLayout.addWidget(self.type_label, 0, 0, 1, 1)
self.value_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.value_label.setObjectName("value_label")
self.gridLayout.addWidget(self.value_label, 1, 0, 1, 1)
self.type_combo = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.type_combo.setObjectName("type_combo")
self.type_combo.addItem("")
self.gridLayout.addWidget(self.type_combo, 0, 1, 1, 1)
self.value = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.value.setText("")
self.value.setObjectName("value")
self.gridLayout.addWidget(self.value, 1, 1, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout.addWidget(self.apply_button)
self.verticalLayout.addLayout(self.horizontalLayout)
RotateToolGUI.setCentralWidget(self.centralwidget)
self.retranslateUi(RotateToolGUI)
QtCore.QMetaObject.connectSlotsByName(RotateToolGUI)
def retranslateUi(self, RotateToolGUI):
_translate = QtCore.QCoreApplication.translate
RotateToolGUI.setWindowTitle(_translate("RotateToolGUI", "Scale Tool"))
self.label.setText(_translate("RotateToolGUI", "Rotate Tool"))
self.type_label.setText(_translate("RotateToolGUI", "Type:"))
self.value_label.setText(_translate("RotateToolGUI", "Value"))
self.type_combo.setItemText(0, _translate("RotateToolGUI", "Degrees"))
self.value.setPlaceholderText(_translate("RotateToolGUI", "1.0"))
self.cancel_button.setText(_translate("RotateToolGUI", "Cancel"))
self.apply_button.setText(_translate("RotateToolGUI", "Apply"))
<file_sep>from ..abstract_tool import AbstractTool
from .rotatetoolgui import Ui_RotateToolGUI
from PyQt5 import QtGui
import numpy as np
class RotateTool(AbstractTool):
def __init__(self, parent):
super(RotateTool, self).__init__(parent)
self._name = "Rotate Tool"
self._parent = parent
# --- Initialize the GUI --- #
self._rotateToolWindow = QtGui.QMainWindow()
self._rotateToolGUI = Ui_RotateToolGUI()
self._rotateToolGUI.setupUi(self._rotateToolWindow)
self._rotateToolGUI.apply_button.clicked.connect(self.callback_apply)
self._rotateToolGUI.cancel_button.clicked.connect(self.callback_cancel)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = None
self._redraw_on_exit = True
self._angle = 0.0
# --- Required Functions --- #
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._rotateToolWindow.width())
_y = 0.5 * (screen_size.height() - self._rotateToolWindow.height())
# --- Show the GUI --- #
self._rotateToolWindow.show()
self._rotateToolWindow.move(_x, _y)
# --- GUI-related Functions --- #
def open_gui(self):
self.run()
def close_gui(self):
self._rotateToolWindow.close()
def callback_apply(self):
if self.apply() == 0:
self._redraw()
self.close_gui()
def callback_cancel(self):
self.close_gui()
# --- Tool-related Functions --- #
def check(self):
value = self._rotateToolGUI.value
v_txt = value.text()
if len(v_txt) == 0:
value.setStyleSheet("color: #000000")
try:
self._angle = float(v_txt)
value.setStyleSheet("color: #000000")
except ValueError:
# Set the text color to red
value.setStyleSheet("color: #FF0000")
def apply(self):
self.check()
# TODO: Radians?
self._angle = np.deg2rad(self._angle)
rotation_matrix = np.array([[np.cos(self._angle), -np.sin(self._angle), 0.0],
[np.sin(self._angle), np.cos(self._angle), 0.0],
[0.0, 0.0, 1.0]])
for dataset in self._selections:
datasource = dataset.get_datasource()
nsteps, npart = dataset.get_nsteps(), dataset.get_npart()
for step in range(nsteps):
for part in range(npart):
position, momentum = np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 0.0])
for i, v in enumerate(["x", "y", "z"]):
position[i] = datasource["Step#{}".format(step)][v][part]
for i, v in enumerate(["px", "py", "pz"]):
momentum[i] = datasource["Step#{}".format(step)][v][part]
rot_position = np.matmul(rotation_matrix, position)
rot_momentum = np.matmul(rotation_matrix, momentum)
for i, v in enumerate(["x", "y", "z"]):
datasource["Step#{}".format(step)][v][part] = float(rot_position[i])
for i, v in enumerate(["px", "py", "pz"]):
datasource["Step#{}".format(step)][v][part] = float(rot_momentum[i])
return 0<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'orbittoolgui.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_OrbitToolGUI(object):
def setupUi(self, OrbitToolGUI):
OrbitToolGUI.setObjectName("OrbitToolGUI")
OrbitToolGUI.resize(323, 183)
self.centralwidget = QtWidgets.QWidget(OrbitToolGUI)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 321, 183))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.step_1_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.step_1_label.setObjectName("step_1_label")
self.gridLayout.addWidget(self.step_1_label, 0, 0, 1, 1)
self.step_2_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.step_2_label.setObjectName("step_2_label")
self.gridLayout.addWidget(self.step_2_label, 1, 0, 1, 1)
self.step_2 = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.step_2.setText("")
self.step_2.setObjectName("step_2")
self.gridLayout.addWidget(self.step_2, 1, 1, 1, 1)
self.step_3_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.step_3_label.setObjectName("step_3_label")
self.gridLayout.addWidget(self.step_3_label, 2, 0, 1, 1)
self.step_3 = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.step_3.setText("")
self.step_3.setObjectName("step_3")
self.gridLayout.addWidget(self.step_3, 2, 1, 1, 1)
self.step_1 = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.step_1.setText("")
self.step_1.setObjectName("step_1")
self.gridLayout.addWidget(self.step_1, 0, 1, 1, 1)
self.center_orbit = QtWidgets.QCheckBox(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.center_orbit.sizePolicy().hasHeightForWidth())
self.center_orbit.setSizePolicy(sizePolicy)
self.center_orbit.setObjectName("center_orbit")
self.gridLayout.addWidget(self.center_orbit, 3, 1, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout.addWidget(self.apply_button)
self.verticalLayout.addLayout(self.horizontalLayout)
OrbitToolGUI.setCentralWidget(self.centralwidget)
self.retranslateUi(OrbitToolGUI)
QtCore.QMetaObject.connectSlotsByName(OrbitToolGUI)
def retranslateUi(self, OrbitToolGUI):
_translate = QtCore.QCoreApplication.translate
OrbitToolGUI.setWindowTitle(_translate("OrbitToolGUI", "Orbit Tool"))
self.label.setText(_translate("OrbitToolGUI", "Orbit Tool"))
self.step_1_label.setText(_translate("OrbitToolGUI", "First Step:"))
self.step_2_label.setText(_translate("OrbitToolGUI", "Second Step:"))
self.step_2.setPlaceholderText(_translate("OrbitToolGUI", "1"))
self.step_3_label.setText(_translate("OrbitToolGUI", "Third Step:"))
self.step_3.setPlaceholderText(_translate("OrbitToolGUI", "2"))
self.step_1.setPlaceholderText(_translate("OrbitToolGUI", "0"))
self.center_orbit.setText(_translate("OrbitToolGUI", "Center Orbit (for R and PR)"))
self.cancel_button.setText(_translate("OrbitToolGUI", "Cancel"))
self.apply_button.setText(_translate("OrbitToolGUI", "Apply"))
<file_sep>from abc import ABC, abstractmethod
# TODO: WIP
class AbstractTool(ABC):
def __init__(self, parent):
self._name = None
self._parent = parent
self._has_gui = False
self._need_selection = False
self._min_selections = 1
self._max_selections = 1
self._selections = None
self._redraw_on_exit = False
self._plot_manager = None
def _redraw(self):
self._plot_manager.redraw_plot()
def check_requirements(self):
if len(self._selections) == 0 and self._need_selection:
return 1
if self._min_selections is not None:
if len(self._selections) < self._min_selections:
return 1
if self._max_selections is not None:
if len(self._selections) > self._max_selections:
return 1
return 0
def name(self):
return self._name
def redraw_on_exit(self):
return self._redraw_on_exit
@abstractmethod
def run(self):
pass
def set_plot_manager(self, plot_manager):
self._plot_manager = plot_manager
def set_selections(self, selections):
self._selections = selections<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'generate_twiss.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Generate_Twiss(object):
def setupUi(self, Generate_Twiss):
Generate_Twiss.setObjectName("Generate_Twiss")
Generate_Twiss.resize(452, 700)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Generate_Twiss.sizePolicy().hasHeightForWidth())
Generate_Twiss.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(Generate_Twiss)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 431, 663))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setMaximumSize(QtCore.QSize(500, 25))
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.gridLayout.setObjectName("gridLayout")
self.bl_label_7 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_7.setObjectName("bl_label_7")
self.gridLayout.addWidget(self.bl_label_7, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.length = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.length.setObjectName("length")
self.gridLayout.addWidget(self.length, 5, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.tl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label.setObjectName("tl_label")
self.gridLayout.addWidget(self.tl_label, 0, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 7, 1, 1, 1, QtCore.Qt.AlignLeft)
self.ze = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ze.setEnabled(False)
self.ze.setObjectName("ze")
self.gridLayout.addWidget(self.ze, 7, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.zpa = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zpa.setEnabled(False)
self.zpa.setObjectName("zpa")
self.gridLayout.addWidget(self.zpa, 1, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.tr_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label.setObjectName("tr_label")
self.gridLayout.addWidget(self.tr_label, 3, 1, 1, 1, QtCore.Qt.AlignLeft)
self.bl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label.setObjectName("bl_label")
self.gridLayout.addWidget(self.bl_label, 5, 1, 1, 1, QtCore.Qt.AlignLeft)
self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 8, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.zpos = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.zpos.setMinimumSize(QtCore.QSize(142, 0))
self.zpos.setMaximumSize(QtCore.QSize(176, 16777215))
self.zpos.setObjectName("zpos")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.zpos.addItem("")
self.gridLayout.addWidget(self.zpos, 0, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.zmom = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.zmom.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.zmom.sizePolicy().hasHeightForWidth())
self.zmom.setSizePolicy(sizePolicy)
self.zmom.setMinimumSize(QtCore.QSize(142, 0))
self.zmom.setMaximumSize(QtCore.QSize(176, 16777215))
self.zmom.setObjectName("zmom")
self.zmom.addItem("")
self.zmom.addItem("")
self.zmom.addItem("")
self.zmom.addItem("")
self.gridLayout.addWidget(self.zmom, 3, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_8.setObjectName("bl_label_8")
self.gridLayout.addWidget(self.bl_label_8, 2, 1, 1, 1, QtCore.Qt.AlignRight)
self.zpb = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zpb.setEnabled(False)
self.zpb.setObjectName("zpb")
self.gridLayout.addWidget(self.zpb, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 2, 0, 1, 1)
self.gridLayout_3 = QtWidgets.QGridLayout()
self.gridLayout_3.setObjectName("gridLayout_3")
self.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_8.setObjectName("label_8")
self.gridLayout_3.addWidget(self.label_8, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_9 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_9.setObjectName("label_9")
self.gridLayout_3.addWidget(self.label_9, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.zpstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zpstddev.setEnabled(False)
self.zpstddev.setMinimumSize(QtCore.QSize(100, 0))
self.zpstddev.setMaximumSize(QtCore.QSize(134, 134))
self.zpstddev.setObjectName("zpstddev")
self.gridLayout_3.addWidget(self.zpstddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.zmstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.zmstddev.setEnabled(False)
self.zmstddev.setMinimumSize(QtCore.QSize(100, 0))
self.zmstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.zmstddev.setObjectName("zmstddev")
self.gridLayout_3.addWidget(self.zmstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout.addLayout(self.gridLayout_3, 8, 2, 1, 1)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem1 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem1)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setMaximumSize(QtCore.QSize(16777215, 25))
self.label_4.setObjectName("label_4")
self.verticalLayout_3.addWidget(self.label_4)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.xydist = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.xydist.setMinimumSize(QtCore.QSize(142, 0))
self.xydist.setMaximumSize(QtCore.QSize(176, 16777215))
self.xydist.setObjectName("xydist")
self.xydist.addItem("")
self.xydist.addItem("")
self.xydist.addItem("")
self.xydist.addItem("")
self.verticalLayout_2.addWidget(self.xydist, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.gridLayout_2.setObjectName("gridLayout_2")
self.tr_label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label_2.setObjectName("tr_label_2")
self.gridLayout_2.addWidget(self.tr_label_2, 5, 1, 1, 1, QtCore.Qt.AlignLeft)
self.tl_label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label_2.setObjectName("tl_label_2")
self.gridLayout_2.addWidget(self.tl_label_2, 0, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.bl_label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_3.setObjectName("bl_label_3")
self.gridLayout_2.addWidget(self.bl_label_3, 7, 1, 1, 1, QtCore.Qt.AlignRight)
self.label_5 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 8, 1, 1, 1, QtCore.Qt.AlignRight)
self.ya = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ya.setEnabled(True)
self.ya.setObjectName("ya")
self.gridLayout_2.addWidget(self.ya, 6, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_4.setObjectName("bl_label_4")
self.gridLayout_2.addWidget(self.bl_label_4, 6, 1, 1, 1, QtCore.Qt.AlignRight)
self.label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_6.setObjectName("label_6")
self.gridLayout_2.addWidget(self.label_6, 9, 1, 1, 1, QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
self.xe = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xe.setEnabled(True)
self.xe.setObjectName("xe")
self.gridLayout_2.addWidget(self.xe, 3, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_5 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_5.setObjectName("bl_label_5")
self.gridLayout_2.addWidget(self.bl_label_5, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.label_7 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_7.setObjectName("label_7")
self.gridLayout_2.addWidget(self.label_7, 3, 1, 1, 1, QtCore.Qt.AlignRight)
self.xa = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xa.setEnabled(True)
self.xa.setObjectName("xa")
self.gridLayout_2.addWidget(self.xa, 1, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.xb = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xb.setEnabled(True)
self.xb.setObjectName("xb")
self.gridLayout_2.addWidget(self.xb, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.bl_label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label_6.setObjectName("bl_label_6")
self.gridLayout_2.addWidget(self.bl_label_6, 2, 1, 1, 1, QtCore.Qt.AlignRight)
self.yb = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.yb.setObjectName("yb")
self.gridLayout_2.addWidget(self.yb, 7, 2, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem2 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_2.addItem(spacerItem2, 6, 0, 2, 1)
self.ye = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ye.setObjectName("ye")
self.gridLayout_2.addWidget(self.ye, 8, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.label_12 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_12.setObjectName("label_12")
self.gridLayout_2.addWidget(self.label_12, 4, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_4 = QtWidgets.QGridLayout()
self.gridLayout_4.setObjectName("gridLayout_4")
self.label_11 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_11.setObjectName("label_11")
self.gridLayout_4.addWidget(self.label_11, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_13 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_13.setObjectName("label_13")
self.gridLayout_4.addWidget(self.label_13, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.xstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xstddev.setEnabled(False)
self.xstddev.setMinimumSize(QtCore.QSize(100, 0))
self.xstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.xstddev.setObjectName("xstddev")
self.gridLayout_4.addWidget(self.xstddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.xpstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.xpstddev.setEnabled(False)
self.xpstddev.setMinimumSize(QtCore.QSize(100, 0))
self.xpstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.xpstddev.setObjectName("xpstddev")
self.gridLayout_4.addWidget(self.xpstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_2.addLayout(self.gridLayout_4, 4, 2, 1, 1)
self.gridLayout_5 = QtWidgets.QGridLayout()
self.gridLayout_5.setObjectName("gridLayout_5")
self.label_14 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_14.setObjectName("label_14")
self.gridLayout_5.addWidget(self.label_14, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_15 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_15.setObjectName("label_15")
self.gridLayout_5.addWidget(self.label_15, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.ystddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ystddev.setEnabled(False)
self.ystddev.setMinimumSize(QtCore.QSize(100, 0))
self.ystddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.ystddev.setObjectName("ystddev")
self.gridLayout_5.addWidget(self.ystddev, 0, 1, 1, 1, QtCore.Qt.AlignRight)
self.ypstddev = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.ypstddev.setEnabled(False)
self.ypstddev.setMinimumSize(QtCore.QSize(100, 0))
self.ypstddev.setMaximumSize(QtCore.QSize(134, 16777215))
self.ypstddev.setObjectName("ypstddev")
self.gridLayout_5.addWidget(self.ypstddev, 1, 1, 1, 1, QtCore.Qt.AlignRight)
self.gridLayout_2.addLayout(self.gridLayout_5, 9, 2, 1, 1)
self.checkBox = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.checkBox.setObjectName("checkBox")
self.gridLayout_2.addWidget(self.checkBox, 5, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout_2.addLayout(self.gridLayout_2)
self.verticalLayout_3.addLayout(self.verticalLayout_2)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox)
Generate_Twiss.setCentralWidget(self.centralwidget)
self.retranslateUi(Generate_Twiss)
QtCore.QMetaObject.connectSlotsByName(Generate_Twiss)
def retranslateUi(self, Generate_Twiss):
_translate = QtCore.QCoreApplication.translate
Generate_Twiss.setWindowTitle(_translate("Generate_Twiss", "Generate Distribution: Enter Parameters"))
self.label.setText(_translate("Generate_Twiss", "Longitudinal Distribution"))
self.bl_label_7.setText(_translate("Generate_Twiss", "Alpha:"))
self.tl_label.setText(_translate("Generate_Twiss", "Position:"))
self.label_2.setText(_translate("Generate_Twiss", "Normalized Emittance (pi-mm-mrad):"))
self.tr_label.setText(_translate("Generate_Twiss", "Momentum:"))
self.bl_label.setText(_translate("Generate_Twiss", "Length (mm):"))
self.label_3.setText(_translate("Generate_Twiss", "Standard Deviation:"))
self.zpos.setItemText(0, _translate("Generate_Twiss", "Constant"))
self.zpos.setItemText(1, _translate("Generate_Twiss", "Uniform along length"))
self.zpos.setItemText(2, _translate("Generate_Twiss", "Uniform on ellipse"))
self.zpos.setItemText(3, _translate("Generate_Twiss", "Gaussian on ellipse"))
self.zpos.setItemText(4, _translate("Generate_Twiss", "Waterbag"))
self.zpos.setItemText(5, _translate("Generate_Twiss", "Parabolic"))
self.zmom.setItemText(0, _translate("Generate_Twiss", "Constant"))
self.zmom.setItemText(1, _translate("Generate_Twiss", "Uniform along length"))
self.zmom.setItemText(2, _translate("Generate_Twiss", "Uniform on ellipse"))
self.zmom.setItemText(3, _translate("Generate_Twiss", "Gaussian on ellipse"))
self.bl_label_8.setText(_translate("Generate_Twiss", "Beta (mm/mrad):"))
self.label_8.setText(_translate("Generate_Twiss", "Position (mm):"))
self.label_9.setText(_translate("Generate_Twiss", "Momentum (mrad):"))
self.label_4.setText(_translate("Generate_Twiss", "Transverse Distribution"))
self.xydist.setItemText(0, _translate("Generate_Twiss", "Uniform"))
self.xydist.setItemText(1, _translate("Generate_Twiss", "Gaussian"))
self.xydist.setItemText(2, _translate("Generate_Twiss", "Waterbag"))
self.xydist.setItemText(3, _translate("Generate_Twiss", "Parabolic"))
self.tr_label_2.setText(_translate("Generate_Twiss", "Y Phase Space Ellipse:"))
self.tl_label_2.setText(_translate("Generate_Twiss", "X Phase Space Ellipse:"))
self.bl_label_3.setText(_translate("Generate_Twiss", "Beta (mm/mrad):"))
self.label_5.setText(_translate("Generate_Twiss", "Normalized Emittance (pi-mm-mrad):"))
self.bl_label_4.setText(_translate("Generate_Twiss", "Alpha:"))
self.label_6.setText(_translate("Generate_Twiss", "Standard Deviation:"))
self.bl_label_5.setText(_translate("Generate_Twiss", "Alpha:"))
self.label_7.setText(_translate("Generate_Twiss", "Normalized Emittance (pi-mm-mrad):"))
self.bl_label_6.setText(_translate("Generate_Twiss", "Beta (mm/mrad):"))
self.label_12.setText(_translate("Generate_Twiss", "Standard Deviation:"))
self.label_11.setText(_translate("Generate_Twiss", "Radius (mm):"))
self.label_13.setText(_translate("Generate_Twiss", "Angle (mrad):"))
self.label_14.setText(_translate("Generate_Twiss", "Radius (mm):"))
self.label_15.setText(_translate("Generate_Twiss", "Angle (mrad):"))
self.checkBox.setText(_translate("Generate_Twiss", "Symmetric?"))
<file_sep>from py_particle_processor_qt.drivers.TraceWinDriver.TraceWinDriver import *
<file_sep>from py_particle_processor_qt.tools.RotateTool.RotateTool import *
<file_sep>from py_particle_processor_qt.drivers.IBSimuDriver.IBSimuDriver import *
<file_sep>from py_particle_processor_qt.tools.TranslateTool.TranslateTool import *
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'beamchargui.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_BeamChar(object):
def setupUi(self, BeamChar):
BeamChar.setObjectName("BeamChar")
BeamChar.resize(421, 303)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(BeamChar.sizePolicy().hasHeightForWidth())
BeamChar.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(BeamChar)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 3, 401, 299))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMaximumSize(QtCore.QSize(16777215, 200))
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_9 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_9.setObjectName("label_9")
self.gridLayout.addWidget(self.label_9, 7, 0, 1, 1)
self.intens = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.intens.setText("")
self.intens.setObjectName("intens")
self.gridLayout.addWidget(self.intens, 10, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_8.setObjectName("label_8")
self.gridLayout.addWidget(self.label_8, 1, 0, 1, 1)
self.centroid = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.centroid.setText("")
self.centroid.setObjectName("centroid")
self.gridLayout.addWidget(self.centroid, 6, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 6, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.rms = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.rms.setText("")
self.rms.setObjectName("rms")
self.gridLayout.addWidget(self.rms, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.halo = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.halo.setText("")
self.halo.setObjectName("halo")
self.gridLayout.addWidget(self.halo, 4, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_2.setMaximumSize(QtCore.QSize(16777215, 100))
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_6.setObjectName("label_6")
self.gridLayout.addWidget(self.label_6, 9, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.turnsep = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.turnsep.setText("")
self.turnsep.setObjectName("turnsep")
self.gridLayout.addWidget(self.turnsep, 5, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_5 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_5.setObjectName("label_5")
self.gridLayout.addWidget(self.label_5, 5, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.ehist = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.ehist.setText("")
self.ehist.setObjectName("ehist")
self.gridLayout.addWidget(self.ehist, 9, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_7 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_7.setObjectName("label_7")
self.gridLayout.addWidget(self.label_7, 10, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_10 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_10.setObjectName("label_10")
self.gridLayout.addWidget(self.label_10, 8, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.xz = QtWidgets.QCheckBox(self.verticalLayoutWidget)
self.xz.setText("")
self.xz.setObjectName("xz")
self.gridLayout.addWidget(self.xz, 8, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox)
BeamChar.setCentralWidget(self.centralwidget)
self.retranslateUi(BeamChar)
QtCore.QMetaObject.connectSlotsByName(BeamChar)
def retranslateUi(self, BeamChar):
_translate = QtCore.QCoreApplication.translate
BeamChar.setWindowTitle(_translate("BeamChar", "Choosing Plots"))
self.label.setText(_translate("BeamChar", "<html><head/><body><p>Please select the beam characteristic(s) you would like to plot.</p></body></html>"))
self.label_9.setText(_translate("BeamChar", "Probes"))
self.label_8.setText(_translate("BeamChar", "Full Simulation"))
self.label_4.setText(_translate("BeamChar", "Centroid Position"))
self.label_3.setText(_translate("BeamChar", "Halo Parameter"))
self.label_2.setText(_translate("BeamChar", "RMS Beam Size"))
self.label_6.setText(_translate("BeamChar", "Energy Histogram"))
self.label_5.setText(_translate("BeamChar", "Turn Separation"))
self.label_7.setText(_translate("BeamChar", "Beam Intensity vs Radius"))
self.label_10.setText(_translate("BeamChar", "R-Z Scatter Plot"))
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'generate_main.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Generate_Main(object):
def setupUi(self, Generate_Main):
Generate_Main.setObjectName("Generate_Main")
Generate_Main.resize(419, 252)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Generate_Main.sizePolicy().hasHeightForWidth())
Generate_Main.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(Generate_Main)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 401, 232))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.tr_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tr_label.setObjectName("tr_label")
self.gridLayout.addWidget(self.tr_label, 2, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.gridLayout.addItem(spacerItem, 5, 0, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.lineEdit.setMaximumSize(QtCore.QSize(164, 16777215))
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 0, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.tl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.tl_label.setObjectName("tl_label")
self.gridLayout.addWidget(self.tl_label, 0, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.bl_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.bl_label.setObjectName("bl_label")
self.gridLayout.addWidget(self.bl_label, 6, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.comboBox_2 = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.comboBox_2.setMinimumSize(QtCore.QSize(164, 0))
self.comboBox_2.setObjectName("comboBox_2")
self.comboBox_2.addItem("")
self.comboBox_2.addItem("")
self.gridLayout.addWidget(self.comboBox_2, 6, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.comboBox = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.comboBox.addItem("")
self.gridLayout.addWidget(self.comboBox, 2, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.energy = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.energy.setMaximumSize(QtCore.QSize(164, 16777215))
self.energy.setObjectName("energy")
self.gridLayout.addWidget(self.energy, 4, 2, 1, 1, QtCore.Qt.AlignHCenter)
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 4, 0, 1, 1, QtCore.Qt.AlignHCenter)
spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.gridLayout.addItem(spacerItem1, 3, 0, 1, 1)
spacerItem2 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.gridLayout.addItem(spacerItem2, 1, 0, 1, 1)
self.verticalLayout_3.addLayout(self.gridLayout)
spacerItem3 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem3)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox)
Generate_Main.setCentralWidget(self.centralwidget)
self.retranslateUi(Generate_Main)
QtCore.QMetaObject.connectSlotsByName(Generate_Main)
def retranslateUi(self, Generate_Main):
_translate = QtCore.QCoreApplication.translate
Generate_Main.setWindowTitle(_translate("Generate_Main", "Generate Distribution"))
self.tr_label.setText(_translate("Generate_Main", "Species:"))
self.tl_label.setText(_translate("Generate_Main", "Number of Particles:"))
self.bl_label.setText(_translate("Generate_Main", "Input Parameter Type:"))
self.comboBox_2.setItemText(0, _translate("Generate_Main", "Envelope"))
self.comboBox_2.setItemText(1, _translate("Generate_Main", "Twiss"))
self.comboBox.setItemText(0, _translate("Generate_Main", "Proton"))
self.comboBox.setItemText(1, _translate("Generate_Main", "Electron"))
self.comboBox.setItemText(2, _translate("Generate_Main", "Dihydrogen cation"))
self.comboBox.setItemText(3, _translate("Generate_Main", "Alpha particle"))
self.label.setText(_translate("Generate_Main", "Energy (MeV):"))
<file_sep>from ..arraywrapper import ArrayWrapper
from ..abstractdriver import AbstractDriver
from dans_pymodules import IonSpecies, ParticleDistribution
import numpy as np
import scipy.constants as const
from PyQt5.QtWidgets import QInputDialog
amu_kg = const.value("atomic mass constant") # (kg)
amu_mev = const.value("atomic mass constant energy equivalent in MeV") # (MeV)
clight = const.value("speed of light in vacuum") # (m/s)
class IBSimuDriver(AbstractDriver):
def __init__(self, parent=None, debug=False):
super(IBSimuDriver, self).__init__()
# IBSimu particle file: I (A), M (kg), t, x (m), vx (m/s), y (m), vy (m/s), z (m), vz (m/s)
self._debug = debug
self._program_name = "IBSimu"
self._parent = parent
def import_data(self, filename, species):
# TODO: There is a lot of looping going on, the fewer instructions the better. -PW
if self._debug:
print("Importing data from program: {}".format(self._program_name))
try:
datasource = {}
data = {}
with open(filename, 'rb') as infile:
lines = infile.readlines()
npart = len(lines)
current = np.empty(npart)
mass = np.empty(npart)
x = np.empty(npart)
y = np.empty(npart)
z = np.empty(npart)
vx = np.empty(npart)
vy = np.empty(npart)
vz = np.empty(npart)
for i, line in enumerate(lines):
current[i], mass[i], _, x[i], vx[i], y[i], vy[i], z[i], vz[i] = [float(item) for item in
line.strip().split()]
masses = np.sort(np.unique(mass)) # mass in MeV, sorted in ascending order (protons before h2+)
particle_distributions = []
for i, m in enumerate(masses):
m_mev = m / amu_kg * amu_mev
species_indices = np.where((mass == m) & (vz > 5.0e5)) # TODO: v_z selection should be in IBSimu -DW
ion = IonSpecies("Species {}".format(i + 1),
mass_mev=m_mev,
a=m_mev / amu_mev,
z=np.round(m_mev / amu_mev, 0),
q=1.0,
current=np.sum(current[species_indices]),
energy_mev=1) # Note: Set energy to 1 for now, will be recalculated
# ParticleDistribution corretly calculates the mean energy
particle_distributions.append(
ParticleDistribution(ion=ion,
x=x[species_indices],
y=y[species_indices],
z=z[species_indices],
vx=vx[species_indices],
vy=vy[species_indices],
vz=vz[species_indices]
))
print(particle_distributions[-1].calculate_emittances()["summary"])
n_species = len(particle_distributions)
if n_species > 1:
items = []
for dist in particle_distributions:
items.append("a = {:.5f}, q = {:.1f}".format(dist.ion.a(), dist.ion.q()))
item, ok = QInputDialog.getItem(self._parent,
"IBSimu Import",
"Found {} ion species, which one do you want?".format(n_species),
items, 0, False)
index = np.where(np.array(items) == item)[0][0]
else:
index = 0
pd = particle_distributions[index]
species = pd.ion
npart = len(pd.x)
step_str = "Step#{}".format(0)
datasource[step_str] = {}
datasource[step_str]["x"] = ArrayWrapper(pd.x)
datasource[step_str]["y"] = ArrayWrapper(pd.y)
datasource[step_str]["z"] = ArrayWrapper(pd.z)
datasource[step_str]["px"] = ArrayWrapper(pd.vx/clight / np.sqrt(1.0 - (pd.vx/clight)**2.0))
datasource[step_str]["py"] = ArrayWrapper(pd.vy/clight / np.sqrt(1.0 - (pd.vy/clight)**2.0))
datasource[step_str]["pz"] = ArrayWrapper(pd.vz/clight / np.sqrt(1.0 - (pd.vz/clight)**2.0))
v_mean_sq = pd.vx**2.0 + pd.vy**2.0 + pd.vz**2.0
datasource[step_str]["E"] = ArrayWrapper(
(1.0 / np.sqrt(1.0 - (v_mean_sq / clight ** 2.0)) - 1.0) * species.mass_mev())
data["datasource"] = datasource
data["ion"] = species
data["energy"] = species.energy_mev() * species.a()
data["mass"] = species.a()
data["charge"] = species.q()
data["steps"] = 1
data["current"] = species.current()
data["particles"] = npart
if self._debug:
print("Found {} steps in the file.".format(data["steps"]))
print("Found {} particles in the file.".format(data["particles"]))
return data
except Exception as e:
print("Exception happened during particle loading with {} "
"ImportExportDriver: {}".format(self._program_name, e))
return None
# try:
#
# datasource = {}
# data = {}
#
# with open(filename, 'rb') as infile:
#
# _n = 7 # Length of the n-tuples to unpack from the values list
# key_list = ["x", "y", "z", "px", "py", "pz", "E"] # Things we want to save
#
# firstline = infile.readline()
# lines = infile.readlines()
# raw_values = [float(item) for item in firstline.strip().split()]
# nsteps = int((len(raw_values) - 1) / _n) # Number of steps
# npart = len(lines) + 1
#
# # Fill in the values for the first line now
# _id = int(raw_values.pop(0))
#
# for step in range(nsteps):
# step_str = "Step#{}".format(step)
#
# datasource[step_str] = {}
#
# for key in key_list:
# datasource[step_str][key] = ArrayWrapper(np.zeros(npart))
#
# values = raw_values[(step * _n):(_n + step * _n)]
#
# gamma = values[6] / species.mass_mev() + 1.0
# beta = np.sqrt(1.0 - np.power(gamma, -2.0))
# v_tot = np.sqrt(values[3] ** 2.0 + values[4] ** 2.0 + values[5] ** 2.0)
#
# values[0:3] = [r for r in values[0:3]]
# values[3:6] = [beta * gamma * v / v_tot for v in values[3:6]] # Convert velocity to momentum
#
# for idx, key in enumerate(key_list):
# datasource[step_str][key][_id - 1] = values[idx]
#
# # Now for every other line
# for line in lines:
#
# raw_values = [float(item) for item in line.strip().split()] # Data straight from the text file
# _id = int(raw_values.pop(0)) # Particle ID number
#
# for step in range(nsteps):
# step_str = "Step#{}".format(step)
# values = raw_values[(step * _n):(_n + step * _n)]
#
# gamma = values[6] / species.mass_mev() + 1.0
# beta = np.sqrt(1.0 - gamma ** (-2.0))
# v_tot = np.sqrt(values[3] ** 2.0 + values[4] ** 2.0 + values[5] ** 2.0)
#
# values[0:3] = [r for r in values[0:3]]
# values[3:6] = [beta * gamma * v / v_tot for v in values[3:6]] # Convert velocity to momentum
#
# for idx, key in enumerate(key_list):
# datasource[step_str][key][_id - 1] = values[idx]
#
# species.calculate_from_energy_mev(datasource["Step#0"]["E"][0])
#
# data["datasource"] = datasource
# data["ion"] = species
# data["mass"] = species.a()
# data["charge"] = species.q()
# data["steps"] = len(datasource.keys())
# data["current"] = None
# data["particles"] = len(datasource["Step#0"]["x"])
#
# if self._debug:
# print("Found {} steps in the file.".format(data["steps"]))
# print("Found {} particles in the file.".format(data["particles"]))
#
# return data
#
# except Exception as e:
#
# print("Exception happened during particle loading with {} "
# "ImportExportDriver: {}".format(self._program_name, e))
#
# return None
def export_data(self, dataset, filename):
print("Sorry, exporting not implemented yet!")
# if self._debug:
# print("Exporting data for program: {}".format(self._program_name))
#
# datasource = dataset.get_datasource()
# ion = dataset.get_ion()
# nsteps = dataset.get_nsteps()
# npart = dataset.get_npart()
#
# with open(filename + ".txt", "w") as outfile:
# for i in range(npart):
# outstring = "{} ".format(i)
# for step in range(nsteps):
# _px = datasource.get("Step#{}".format(step)).get("px")[i]
# _py = datasource.get("Step#{}".format(step)).get("py")[i]
# _pz = datasource.get("Step#{}".format(step)).get("pz")[i]
#
# _vx, _vy, _vz = (clight * _px / np.sqrt(_px ** 2.0 + 1.0),
# clight * _py / np.sqrt(_py ** 2.0 + 1.0),
# clight * _pz / np.sqrt(_pz ** 2.0 + 1.0))
#
# outstring += "{} {} {} {} {} {} {} ".format(datasource.get("Step#{}".format(step)).get("x")[i],
# datasource.get("Step#{}".format(step)).get("y")[i],
# datasource.get("Step#{}".format(step)).get("z")[i],
# _vx, _vy, _vz, ion.energy_mev())
# outfile.write(outstring + "\n")
<file_sep>from py_particle_processor_qt.tools.ScaleTool.ScaleTool import *
<file_sep>from py_particle_processor_qt.tools.ScaleTool import *
from py_particle_processor_qt.tools.TranslateTool import *
from py_particle_processor_qt.tools.AnimateXY import *
from py_particle_processor_qt.tools.BeamChar import *
from py_particle_processor_qt.tools.CollimOPAL import *
from py_particle_processor_qt.tools.OrbitTool import *
# from py_particle_processor_qt.tools.SpiralGeometry import *
from py_particle_processor_qt.tools.RotateTool import *
"""
Format: {"Object_Name": ("Display Name", object)}
"""
tool_mapping = {"Scale_Tool": ("Scale", ScaleTool),
"Translate_Tool": ("Translate", TranslateTool),
"Animate_XY": ("Animate X-Y", AnimateXY),
"Beam_Characteristics": ("Beam Characteristics", BeamChar),
"Collim_OPAL": ("Generate Collimator", CollimOPAL),
"Orbit_Tool": ("Orbit Tool", OrbitTool),
# "Spiral_Geometry": ("Spiral Geometry", SpiralGeometry),
"Rotate_Tool": ("Rotate", RotateTool)}
<file_sep>import h5py
from dans_pymodules import IonSpecies
class OPALDriver:
def __init__(self, debug=False):
self._debug = debug
self._program_name = "OPAL"
def get_program_name(self):
return self._program_name
def import_data(self, filename):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
if h5py.is_hdf5(filename):
if self._debug:
print("Opening h5 file..."),
_datasource = h5py.File(filename)
if self._debug:
print("Done!")
if "OPAL_version" in _datasource.attrs.keys():
data = {"datasource": _datasource}
if self._debug:
print("Loading dataset from h5 file in OPAL format.")
data["nsteps"] = len(_datasource.items())
if self._debug:
print("Found {} steps in the file.".format(data["nsteps"]))
_data = _datasource.get("Step#0")
# TODO: OPAL apparently doesn't save the charge per particle, but per macroparticle without frequency,
# TODO: we have no way of telling what the species is! Add manual input. And maybe fix OPAL... -DW
data["ion"] = IonSpecies("proton", _data.attrs["ENERGY"])
data["current"] = 0.0 # TODO: Get actual current! -DW
data["npart"] = len(_data.get("x").value)
return data
return None
def export_data(self, data):
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
print("Export not yet implemented :(")
return data
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tools/TranslateTool/translatetoolgui.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TranslateToolGUI(object):
def setupUi(self, TranslateToolGUI):
TranslateToolGUI.setObjectName("TranslateToolGUI")
TranslateToolGUI.resize(189, 157)
self.centralwidget = QtWidgets.QWidget(TranslateToolGUI)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 186, 155))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.x_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.x_label.setObjectName("x_label")
self.gridLayout.addWidget(self.x_label, 0, 0, 1, 1)
self.y_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.y_label.setFocusPolicy(QtCore.Qt.NoFocus)
self.y_label.setObjectName("y_label")
self.gridLayout.addWidget(self.y_label, 1, 0, 1, 1)
self.z_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.z_label.setObjectName("z_label")
self.gridLayout.addWidget(self.z_label, 2, 0, 1, 1)
self.y_trans = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.y_trans.setFocusPolicy(QtCore.Qt.ClickFocus)
self.y_trans.setObjectName("y_trans")
self.gridLayout.addWidget(self.y_trans, 1, 1, 1, 1)
self.x_trans = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.x_trans.setFocusPolicy(QtCore.Qt.ClickFocus)
self.x_trans.setClearButtonEnabled(False)
self.x_trans.setObjectName("x_trans")
self.gridLayout.addWidget(self.x_trans, 0, 1, 1, 1)
self.z_trans = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.z_trans.setFocusPolicy(QtCore.Qt.ClickFocus)
self.z_trans.setObjectName("z_trans")
self.gridLayout.addWidget(self.z_trans, 2, 1, 1, 1)
self.m1 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.m1.setObjectName("m1")
self.gridLayout.addWidget(self.m1, 0, 2, 1, 1)
self.m2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.m2.setObjectName("m2")
self.gridLayout.addWidget(self.m2, 1, 2, 1, 1)
self.m3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.m3.setObjectName("m3")
self.gridLayout.addWidget(self.m3, 2, 2, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout.addWidget(self.apply_button)
self.verticalLayout.addLayout(self.horizontalLayout)
TranslateToolGUI.setCentralWidget(self.centralwidget)
self.retranslateUi(TranslateToolGUI)
QtCore.QMetaObject.connectSlotsByName(TranslateToolGUI)
def retranslateUi(self, TranslateToolGUI):
_translate = QtCore.QCoreApplication.translate
TranslateToolGUI.setWindowTitle(_translate("TranslateToolGUI", "Scale Tool"))
self.label.setText(_translate("TranslateToolGUI", "Translate Tool"))
self.x_label.setText(_translate("TranslateToolGUI", "X"))
self.y_label.setText(_translate("TranslateToolGUI", "Y"))
self.z_label.setText(_translate("TranslateToolGUI", "Z"))
self.y_trans.setText(_translate("TranslateToolGUI", "0.0"))
self.x_trans.setText(_translate("TranslateToolGUI", "0.0"))
self.z_trans.setText(_translate("TranslateToolGUI", "0.0"))
self.m1.setText(_translate("TranslateToolGUI", "m"))
self.m2.setText(_translate("TranslateToolGUI", "m"))
self.m3.setText(_translate("TranslateToolGUI", "m"))
self.cancel_button.setText(_translate("TranslateToolGUI", "Cancel"))
self.apply_button.setText(_translate("TranslateToolGUI", "Apply"))
<file_sep>from OPALDriver import *
from TraceWinDriver import *
"""
The driver mapping contains the information needed for the ImportExportDriver class to wrap around the drivers
"""
driver_mapping = {'OPAL': {'driver': OPALDriver,
'extensions': ['.h5']},
'TraceWin': {'driver': TraceWinDriver,
'extensions': ['.txt']}
}
<file_sep>from py_particle_processor_qt.drivers.TrackDriver.TrackDriver import *
<file_sep>from py_particle_processor_qt.tools.AnimateXY.AnimateXY import *
<file_sep>from ..abstractdriver import AbstractDriver
import numpy as np
import os
class FreeCADDriver(AbstractDriver):
def __init__(self, debug=False):
super(FreeCADDriver, self).__init__()
self._debug = debug
self._program_name = "FreeCAD"
def get_program_name(self):
return self._program_name
def import_data(self, filename, species=None):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
print("FreeCAD driver is export-only!")
return None
def export_data(self, dataset, filename):
# TODO: Make number of trajectories and time frequency user input -DW
ntrj = 1000 # only use 1000 random trajectories
freq = 5 # only use every 5th step
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
datasource = dataset.get_datasource()
nsteps = dataset.get_nsteps()
maxnumpart = len(datasource.get("Step#0").get("x").value)
_chosen = np.random.choice(maxnumpart, ntrj)
with open(os.path.splitext(filename)[0] + ".dat", "w") as outfile:
outfile.write("step, ID, x (m), y (m), z (m)\n")
for step in range(nsteps):
if step % freq == 0:
_stepdata = datasource.get("Step#{}".format(step))
_ids = _stepdata.get("id").value
# npart = len(_ids)
indices = np.nonzero(np.isin(_ids, _chosen))[0]
if self._debug:
print("Saving step {} of {}, found {} matching ID's".format(step, nsteps, len(indices)))
for i in indices:
# if datasource.get("Step#{}".format(step)).get("id")[i] in _chosen:
outstring = "{} {} ".format(step, datasource.get("Step#{}".format(step)).get("id")[i])
outstring += "{} {} {}\n".format(datasource.get("Step#{}".format(step)).get("x")[i],
datasource.get("Step#{}".format(step)).get("y")[i],
datasource.get("Step#{}".format(step)).get("z")[i])
outfile.write(outstring)
return 0
<file_sep>numpy
scipy
pyqtgraph
PyQt5
h5py
matplotlib
pyopengl
<file_sep>from py_particle_processor_qt.gui import *<file_sep>from ..abstract_tool import AbstractTool
from PyQt5.QtWidgets import QMainWindow
from .collimOPALgui import Ui_CollimOPAL
import numpy as np
import string
import matplotlib.pyplot as plt
import os
DEBUG = True
""""
A tool for generating collimator code for OPAL.
"""
class CollimOPAL(AbstractTool):
def __init__(self, parent):
super(CollimOPAL, self).__init__(parent)
self._name = "Generate Collimator"
self._parent = parent
self._filename = ""
self._settings = {}
self._datasource = None # h5py datasource for orbit data
# --- Initialize the GUI --- #
self._collimOPALWindow = QMainWindow()
self._collimOPALGUI = Ui_CollimOPAL()
self._collimOPALGUI.setupUi(self._collimOPALWindow)
self._collimOPALGUI.buttonBox.accepted.connect(self.callback_apply)
self._collimOPALGUI.buttonBox.rejected.connect(self._collimOPALWindow.close)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = 1
self._redraw_on_exit = False
# Debug plotting:
if DEBUG:
self._fig = plt.figure()
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
self._ax = plt.gca()
self._ax.set_xlabel("x (mm)")
self._ax.set_ylabel("y (mm)")
def apply_settings(self):
self._settings["step"] = int(self._collimOPALGUI.step.text())
self._settings["width"] = float(self._collimOPALGUI.gap.text())
self._settings["length"] = float(self._collimOPALGUI.hl.text())
self._settings["cwidth"] = float(self._collimOPALGUI.w.text())
self._settings["label"] = int(self._collimOPALGUI.num.text())
self._settings["nseg"] = int(self._collimOPALGUI.nseg.text())
def callback_apply(self):
self.apply_settings()
script = ""
script += self.gen_script()
self._collimOPALGUI.textBrowser.setText(script)
with open(os.path.join(os.environ.get("HOME", ""), "collim.txt"), 'w') as outfile:
outfile.write(script)
if DEBUG:
plt.show()
# @staticmethod
# def read_data(fn):
#
# with open(fn, 'r') as infile:
# lines = infile.readlines()
#
# design_particle_lines = []
#
# for line in lines:
# if "ID0" in line:
# design_particle_lines.append(line.strip())
#
# npts = len(design_particle_lines)
#
# x = np.zeros(npts)
# y = np.zeros(npts)
# px = np.zeros(npts)
# py = np.zeros(npts)
#
# for i, line in enumerate(design_particle_lines):
# _, _x, _px, _y, _py, _, _ = line.split()
# x[i] = float(_x) * 1000.0
# y[i] = float(_y) * 1000.0
# px[i] = float(_px)
# py[i] = float(_py)
#
# return np.array([x, px, y, py])
def get_xy_mean_at_step_mm(self, step):
x = 1e3 * np.mean(np.array(self._datasource["Step#{}".format(step)]["x"]))
y = 1e3 * np.mean(np.array(self._datasource["Step#{}".format(step)]["y"]))
return x, y
def gen_script(self):
script = ""
letters = list(string.ascii_lowercase)
# Central collimator placement
x_cent, y_cent = self.get_xy_mean_at_step_mm(self._settings["step"])
for n in range(self._settings["nseg"]):
i = self._settings["step"]
if n != 0: # n = 0 indicates the central segment
x_temp, y_temp = self.get_xy_mean_at_step_mm(i)
if n % 2 == 1: # n congruent to 1 mod 2 indicates placement ahead of the central segment
while np.sqrt(np.square(x_cent - x_temp) + np.square(y_cent - y_temp)) \
< (int(n / 2) + (n % 2 > 0)) * self._settings["cwidth"]:
i += 1
x_temp, y_temp = self.get_xy_mean_at_step_mm(i)
else: # n > 0 congruent to 0 mod 2 indicates placement behind of the central segment
while np.sqrt(np.square(x_cent - x_temp) + np.square(y_cent - y_temp)) \
< (int(n / 2) + (n % 2 > 0)) * self._settings["cwidth"]:
i -= 1
x_temp, y_temp = self.get_xy_mean_at_step_mm(i)
x_new, y_new = self.get_xy_mean_at_step_mm(i)
px_new = np.mean(np.array(self._datasource["Step#{}".format(i)]["px"]))
py_new = np.mean(np.array(self._datasource["Step#{}".format(i)]["py"]))
collim = self.gen_collim(x_new, y_new, px_new, py_new)
script += "Collim_{}{}:CCOLLIMATOR, XSTART={}, YSTART={}, XEND={}, YEND={}, WIDTH={};\n\n" \
.format(self._settings["label"], letters[2 * n], collim["x1a"], collim["y1a"], collim["x1b"],
collim["y1b"], self._settings["cwidth"])
script += "Collim_{}{}:CCOLLIMATOR, XSTART={}, YSTART={}, XEND={}, YEND={}, WIDTH={};\n\n" \
.format(self._settings["label"], letters[2 * n + 1], collim["x2a"], collim["y2a"], collim["x2b"],
collim["y2b"], self._settings["cwidth"])
if DEBUG:
plt.plot([collim["x1a"], collim["x1b"]], [collim["y1a"], collim["y1b"]])
plt.plot([collim["x2a"], collim["x2b"]], [collim["y2a"], collim["y2b"]])
if DEBUG:
self._ax.set_title("Collimator at step {} in global frame".format(self._settings["step"]))
self._ax.set_aspect('equal')
x_plot = 1e3 * np.array(self._datasource["Step#{}".format(self._settings["step"])]["x"])
y_plot = 1e3 * np.array(self._datasource["Step#{}".format(self._settings["step"])]["y"])
plt.plot(x_plot, y_plot, 'o', alpha=0.8, markersize=0.01)
return script
def gen_collim(self, x, y, px, py):
# Find angle to rotate collimator according to momentum
theta = np.arccos(px/np.sqrt(np.square(px) + np.square(py)))
if py < 0:
theta = -theta
theta1 = theta + np.pi/2
theta2 = theta - np.pi/2
# Calculate coordinates
x1a = self._settings["width"] * np.cos(theta1) + x
x2a = self._settings["width"] * np.cos(theta2) + x
x1b = (self._settings["width"] + self._settings["length"]) * np.cos(theta1) + x
x2b = (self._settings["width"] + self._settings["length"]) * np.cos(theta2) + x
y1a = self._settings["width"] * np.sin(theta1) + y
y2a = self._settings["width"] * np.sin(theta2) + y
y1b = (self._settings["width"] + self._settings["length"]) * np.sin(theta1) + y
y2b = (self._settings["width"] + self._settings["length"]) * np.sin(theta2) + y
return {"x1a": x1a, "x2a": x2a, "x1b": x1b, "x2b": x2b, "y1a": y1a, "y2a": y2a, "y1b": y1b, "y2b": y2b}
# @staticmethod
# def read(filename):
# text_file = open("C:/Users/Maria/PycharmProjects/py_particle_processor"
# "/py_particle_processor_qt/tools/CollimOPAL/{}.txt".format(filename), "r")
# lines = text_file.read().split(',')
# data = np.array(lines).astype(np.float)
# text_file.close()
# return data
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._collimOPALWindow.width())
_y = 0.5 * (screen_size.height() - self._collimOPALWindow.height())
# --- Show the GUI --- #
self._collimOPALWindow.show()
self._collimOPALWindow.move(_x, _y)
def open_gui(self):
# Get parent dataset/source for orbit data
dataset = self._selections[0]
self._datasource = dataset.get_datasource()
self.run()
<file_sep>from ..arraywrapper import ArrayWrapper
from ..abstractdriver import AbstractDriver
from dans_pymodules import IonSpecies, clight
import numpy as np
class COMSOLDriver(AbstractDriver):
def __init__(self, debug=False):
super(COMSOLDriver, self).__init__()
# TODO: Currently using: (TIME [s], X [m], Y [m], Z [m], VX [m/s], VY [m/s], VZ [m/s], E [MeV])
self._debug = debug
self._program_name = "COMSOL"
def get_program_name(self):
return self._program_name
def import_data(self, filename, species):
# TODO: There is a lot of looping going on, the fewer instructions the better. -PW
if self._debug:
print("Importing data from program: {}".format(self._program_name))
try:
datasource = {}
data = {}
with open(filename, 'rb') as infile:
_n = 7 # Length of the n-tuples to unpack from the values list
key_list = ["x", "y", "z", "px", "py", "pz", "E"] # Things we want to save
firstline = infile.readline()
lines = infile.readlines()
raw_values = [float(item) for item in firstline.strip().split()]
nsteps = int((len(raw_values) - 1) / _n) # Number of steps
npart = len(lines) + 1
# Fill in the values for the first line now
_id = int(raw_values.pop(0))
for step in range(nsteps):
step_str = "Step#{}".format(step)
datasource[step_str] = {}
for key in key_list:
datasource[step_str][key] = ArrayWrapper(np.zeros(npart))
values = raw_values[(step * _n):(_n + step * _n)]
gamma = values[6] / species.mass_mev() + 1.0
beta = np.sqrt(1.0 - np.power(gamma, -2.0))
v_tot = np.sqrt(values[3] ** 2.0 + values[4] ** 2.0 + values[5] ** 2.0)
values[0:3] = [r for r in values[0:3]]
values[3:6] = [beta * gamma * v / v_tot for v in values[3:6]] # Convert velocity to momentum
for idx, key in enumerate(key_list):
datasource[step_str][key][_id - 1] = values[idx]
# Now for every other line
for line in lines:
raw_values = [float(item) for item in line.strip().split()] # Data straight from the text file
_id = int(raw_values.pop(0)) # Particle ID number
for step in range(nsteps):
step_str = "Step#{}".format(step)
values = raw_values[(step * _n):(_n + step * _n)]
gamma = values[6] / species.mass_mev() + 1.0
beta = np.sqrt(1.0 - gamma ** (-2.0))
v_tot = np.sqrt(values[3] ** 2.0 + values[4] ** 2.0 + values[5] ** 2.0)
values[0:3] = [r for r in values[0:3]]
values[3:6] = [beta * gamma * v / v_tot for v in values[3:6]] # Convert velocity to momentum
for idx, key in enumerate(key_list):
datasource[step_str][key][_id - 1] = values[idx]
species.calculate_from_energy_mev(datasource["Step#0"]["E"][0])
data["datasource"] = datasource
data["ion"] = species
data["mass"] = species.a()
data["charge"] = species.q()
data["steps"] = len(datasource.keys())
data["current"] = None
data["particles"] = len(datasource["Step#0"]["x"])
if self._debug:
print("Found {} steps in the file.".format(data["steps"]))
print("Found {} particles in the file.".format(data["particles"]))
return data
except Exception as e:
print("Exception happened during particle loading with {} "
"ImportExportDriver: {}".format(self._program_name, e))
return None
def export_data(self, dataset, filename):
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
datasource = dataset.get_datasource()
ion = dataset.get_ion()
nsteps = dataset.get_nsteps()
npart = dataset.get_npart()
with open(filename + ".txt", "w") as outfile:
for i in range(npart):
outstring = "{} ".format(i)
for step in range(nsteps):
_px = datasource.get("Step#{}".format(step)).get("px")[i]
_py = datasource.get("Step#{}".format(step)).get("py")[i]
_pz = datasource.get("Step#{}".format(step)).get("pz")[i]
_vx, _vy, _vz = (clight * _px / np.sqrt(_px ** 2.0 + 1.0),
clight * _py / np.sqrt(_py ** 2.0 + 1.0),
clight * _pz / np.sqrt(_pz ** 2.0 + 1.0))
outstring += "{} {} {} {} {} {} {} ".format(datasource.get("Step#{}".format(step)).get("x")[i],
datasource.get("Step#{}".format(step)).get("y")[i],
datasource.get("Step#{}".format(step)).get("z")[i],
_vx, _vy, _vz, ion.energy_mev())
outfile.write(outstring + "\n")
<file_sep>from ..abstract_tool import AbstractTool
from .animateXYgui import Ui_Animate
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.ticker import LinearLocator
from PyQt5.QtWidgets import QFileDialog, QMainWindow
# Note: This tool requires ffmpeg installation!!!
class AnimateXY(AbstractTool):
def __init__(self, parent):
super(AnimateXY, self).__init__(parent)
self._name = "Animate X-Y"
self._parent = parent
self._filename = ""
self._settings = {}
# --- Initialize the GUI --- #
self._animateWindow = QMainWindow()
self._animateGUI = Ui_Animate()
self._animateGUI.setupUi(self._animateWindow)
self._animateGUI.buttonBox.accepted.connect(self.callback_apply)
self._animateGUI.buttonBox.rejected.connect(self._animateWindow.close)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = 3
self._redraw_on_exit = False
def apply_settings(self):
self._settings["local"] = self._animateGUI.radioButton.isChecked()
self._settings["global"] = self._animateGUI.radioButton_2.isChecked()
self._settings["lim"] = float(self._animateGUI.lim.text())
self._settings["fps"] = int(self._animateGUI.fps.text())
@staticmethod
def get_bunch_in_local_frame(datasource, step):
x = np.array(datasource["Step#{}".format(step)]["x"])
y = np.array(datasource["Step#{}".format(step)]["y"])
x_mean = np.mean(x)
y_mean = np.mean(y)
px_mean = np.mean(np.array(datasource["Step#{}".format(step)]["px"]))
py_mean = np.mean(np.array(datasource["Step#{}".format(step)]["py"]))
theta = np.arccos(py_mean / np.sqrt(np.square(px_mean) + np.square(py_mean)))
if px_mean < 0:
theta = -theta
# Center the beam
x -= x_mean
y -= y_mean
# Rotate the beam and return
temp_x = x
temp_y = y
return temp_x * np.cos(theta) - temp_y * np.sin(theta), temp_x * np.sin(theta) + temp_y * np.cos(theta)
def callback_apply(self):
self.apply_settings()
self._animateWindow.close()
self.run_animation()
def run_animation(self):
self._parent.send_status("Setting up animation...")
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.rc('grid', linestyle=':')
animate_all = []
for dataset in self._selections:
# dataset = self._selections[0]
datasource = dataset.get_datasource()
nsteps = dataset.get_nsteps()
# TODO: Total hack, but I want to tag certain particles RIGHT NOW -DW
# tag_step = 568
# tag_y_lim = 5.0 * 1.0e-3 # m
# _x, _y = self.get_bunch_in_local_frame(datasource, tag_step)
# tag_idx = np.where(_y >= tag_y_lim)
# pids = np.array(datasource["Step#{}".format(tag_step)]["id"][tag_idx])
animate = {}
for step in range(nsteps):
animate["Step#{}".format(step)] = {"x": np.array(datasource["Step#{}".format(step)]["x"]),
"y": np.array(datasource["Step#{}".format(step)]["y"]),
"id": np.array(datasource["Step#{}".format(step)]["id"])}
if self._settings["local"]:
animate["Step#{}".format(step)]["x"], animate["Step#{}".format(step)]["y"] = \
self.get_bunch_in_local_frame(datasource, step)
animate_all.append(animate)
n_ds = len(animate_all)
# Handle animations
# fig = plt.figure()
fig, ax = plt.subplots(1, n_ds)
if n_ds == 1:
ax = [ax]
lines = []
j = 0
for _ax in ax:
_ax.set_xlim(-self._settings["lim"], self._settings["lim"])
_ax.set_ylim(-self._settings["lim"], self._settings["lim"])
# ax = plt.axes(xlim=(-self._settings["lim"], self._settings["lim"]),
# ylim=(-self._settings["lim"], self._settings["lim"]))
line1, = _ax.plot([], [], 'ko', ms=0.1, alpha=0.8)
# line2, = ax.plot([], [], 'ko', ms=0.1, alpha=0.8, color='red') # Tagging
lines.append(line1)
# plt.grid()
_ax.grid()
_ax.set_aspect('equal')
if self._settings["local"]:
_ax.set_xlabel("Horizontal (mm)")
_ax.set_ylabel("Longitudinal (mm)")
else:
_ax.set_xlabel("X (mm)")
_ax.set_ylabel("Y (mm)")
_ax.set_title(r"{}: Step \#0".format(self._selections[j].get_name()))
_ax.get_xaxis().set_major_locator(LinearLocator(numticks=13))
_ax.get_yaxis().set_major_locator(LinearLocator(numticks=13))
plt.tight_layout()
j += 1
def init():
for _line in lines:
_line.set_data([], [])
# line2.set_data([], [])
return lines, # line2,
def update(i):
k = 0
for _animate, _line in zip(animate_all, lines):
# tags = np.isin(animate["Step#{}".format(i)]["id"], pids)
tags = np.zeros(len(_animate["Step#{}".format(i)]["x"]), dtype=bool)
# Regular Data
x = 1000.0 * _animate["Step#{}".format(i)]["x"][np.invert(tags.astype(bool))]
y = 1000.0 * _animate["Step#{}".format(i)]["y"][np.invert(tags.astype(bool))]
# Tagged Data
xt = 1000.0 * _animate["Step#{}".format(i)]["x"][tags.astype(bool)]
yt = 1000.0 * _animate["Step#{}".format(i)]["y"][tags.astype(bool)]
_line.set_data(x, y)
# line2.set_data(xt, yt)
ax[k].set_title(r"{}: Step \#{}".format(self._selections[k].get_name(), i))
k += 1
completed = int(100*(i/(nsteps-1)))
self._parent.send_status("Animation progress: {}% complete".format(completed))
# return line1, line2, ax
return lines, ax
ani = animation.FuncAnimation(fig, update, frames=nsteps, init_func=init, repeat=False)
# Save animation
writer1 = animation.writers['ffmpeg']
writer2 = writer1(fps=self._settings["fps"], bitrate=1800)
ani.save(self._filename[0]+".mp4", writer=writer2)
ani._stop()
self._parent.send_status("Animation saved successfully!")
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._animateWindow.width())
_y = 0.5 * (screen_size.height() - self._animateWindow.height())
# --- Show the GUI --- #
self._animateWindow.show()
self._animateWindow.move(_x, _y)
def open_gui(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self._filename = QFileDialog.getSaveFileName(caption="Saving animation...", options=options,
filter="Video (*.mp4)")
self.run()
<file_sep>from py_particle_processor_qt.tools.CollimOPAL.CollimOPAL import *
<file_sep># PyParticleProcessor
Cave: This module is in a rough pre-alpha stage! Comments and Collaborators very welcome, though!
## Introduction
The PyParticleProcessor is a Qt5/python3 based tool with a GUI to import and export ion beam information (particle data) from various different simulation packages. There is some limited functionality for plotting these particle data and calculate emittances and Twiss parameters. Users can add their own "drivers" both for analysis tools and import/export.
## Currently Supported Programs
Cave: These are all limited support and need to be expanded. Many of those software packages give the user freedom on how to export data themselves, so care has to be taken to export in the same manor.
* [OPAL](https://gitlab.psi.ch/OPAL/src/wikis/home)
* [TraceWin](http://irfu.cea.fr/dacm/en/logiciels/index.php)
* [Track](https://www.phy.anl.gov/atlas/TRACK)
* [COMSOL](https://www.comsol.com/)
* [IBSimu](http://ibsimu.sourceforge.net/)
## Installation
### Windows
Prerequisites are:
* [Qt5 (Open Source)](https://www.qt.io/download)
* [dans_pymodules](https://github.com/DanielWinklehner/dans_pymodules)
PyPI packages:
* numpy
* scipy
* pyqtgraph
* PyQt5 (pyqt in Anaconda3)
* h5py
* matplotlib
* pyopengl
The easiest method is to install [Anaconda3](https://www.anaconda.com/download/), create a new virtual environment, then download all the packages listed under PyPI packages inside the virtual environment. Install Qt5 for Windows from the link above and install dans_pymodules from github using pip: From the Anaconda navigator open a terminal running the virtual environment you created earlier ("Open Terminal" from the green triangle next to the new virtual environment's name). Then run pip install like so:
`pip install git+https://github.com/DanielWinklehner/dans_pymodules.git`
Clone the py_particle_processor repositroy:
`git clone https://github.com/DanielWinklehner/py_particle_processor.git`
For a test you can now run the PyParticleProcessor as a module from the top level directory of this repository:
`python -m py_particle_processor_qt.test`
or you can install the module (also from the top level directory in the repository):
`pip install .`
and write a small test program
`from py_particle_processor_qt.py_particle_processor_qt import PyParticleProcessor`<br/>
`ppp = PyParticleProcessor(debug=False)`<br/>
`ppp.run()`
### Linux
## Latex
Some of the Tools require LaTeX rendering (matplotlib). In Ubuntu, install texlive and fonts
`sudo apt-get install texlive-latex-extra texlive-fonts-recommended dvipng`
### MacOS
I have no idea :D feel free to let me know how to do it...
<file_sep>from py_particle_processor_qt.gui.plot_settings import Ui_PlotSettingsWindow
from py_particle_processor_qt.gui.default_plot_settings import Ui_DefaultPlotSettingsWindow
from PyQt5 import QtGui, QtWidgets, QtCore
import pyqtgraph as pg
import numpy as np
__author__ = "<NAME>, <NAME>"
__doc__ = """Plotting objects and associated GUI objects used in the PyParticleProcessor."""
class PlotObject(object):
def __init__(self, parent, graphics_view):
self._parent = parent # Parent object, which should be a PlotManager
self._is_shown = False # A flag raised by showing the plot
self._is_3d = False # A flag that determines if the object is a 3D Plot
self._enabled = True # A flag indicating the plot is enabled
self._graphics_view = graphics_view # The plot's graphics view object to plot to
self._plot_settings = {} # The plot settings for this object
self._datasets = [] # Datasets being shown in the plot
def add_dataset(self, dataset):
self._datasets.append(dataset) # Add the dataset to the list of datasets
return 0
def clear(self):
if self._is_3d: # Check if it's a 3D plot
self._graphics_view.items = [] # Clear the items list
self._graphics_view.update() # Update the graphics view
else:
for data_item in self._graphics_view.listDataItems(): # Loop through each data item
self._graphics_view.removeItem(data_item) # Remove the data item from the graphics view
return 0
def is_shown(self):
return self._is_shown # Returns the shown flag
def datasets(self):
return self._datasets # Return the list of datasets being shown
def remove_dataset(self, dataset):
if dataset in self._datasets: # If the dataset is in the list...
del self._datasets[self._datasets.index(dataset)] # Delete it from the list
def set_plot_settings(self, plot_settings):
self._plot_settings = plot_settings # Set the instance settings to the supplied plot settings
if "is_3d" in plot_settings.keys(): # If this settings is found, check the value
if plot_settings["is_3d"] == 2: # 2 --> True
self._is_3d = True
else:
self._is_3d = False
else:
self._is_3d = False
def get_plot_settings(self, translated=False):
"""
Gets the plot settings used in propertieswindow.
Translated means using "x", "y", ... instead of 0, 1, 2, ...
:param translated:
:return:
"""
if translated is False:
return self._plot_settings # Return raw plot settings
else:
t_plot_settings = {} # Create a new dictionary for the translated plot settings
en_val = [False, None, True] # Values for the "enable" settings
combo_val = ["x", "y", "z", "r", "px", "py", "pz", "pr"] # Values for the combo boxes
for k, v in self._plot_settings.items(): # Get the key and value of each setting
if "_en" in k or "is" in k: # If it's an enable setting...
t_plot_settings[k] = en_val[v]
elif "step" in k: # If it's the step...
t_plot_settings[k] = v
elif v is None: # If the value is set to None...
t_plot_settings[k] = None
else: # Else, it's a combo box setting
t_plot_settings[k] = combo_val[v]
return t_plot_settings
def show(self):
self._is_shown = False
t_plot_settings = self.get_plot_settings(translated=True) # Get the translated settings
# Set the displayed axes to what the combo box settings were (param_c will be None for a 2D plot)
axes = t_plot_settings["param_a"], t_plot_settings["param_b"], t_plot_settings["param_c"]
enabled = t_plot_settings["param_en"]
step = t_plot_settings["step"] # Get the step from the settings
# Check if the plot object is a 3D plot
if self._is_3d:
if enabled:
# Note: since the get_color is set to random, you won't be able to distinguish different datasets
for dataset in self._datasets: # Loop through each dataset
# Only do a 3D display for data with more than one step and it's enabled
if dataset.get_nsteps() > 1 and self._enabled:
_grid = False
# Loop through each particle
if dataset.get_npart() > 1:
for particle_id in range(dataset.get_npart()):
# Get the particle data and color for plotting
particle, _c = dataset.get_particle(particle_id, get_color="random")
# Make an array of the values and transpose it (needed for plotting)
pts = np.array([particle.get(axes[0]), particle.get(axes[1]), particle.get(axes[2])]).T
# Create a line item of all the points corresponding to this particle
plt = pg.opengl.GLLinePlotItem(pos=pts, color=pg.glColor(_c), width=1.,
antialias=True)
# Add the line object to the graphics view
self._graphics_view.addItem(plt)
else:
# Source: https://stackoverflow.com/questions/4296249/how-do-i-convert-a-hex-triplet-to-an-rgb-tuple-and-back
_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x + y for x in _NUMERALS for y in _NUMERALS)}
def rgb(triplet):
return [_HEXDEC[triplet[0:2]] / 255.0, _HEXDEC[triplet[2:4]] / 255.0,
_HEXDEC[triplet[4:6]] / 255.0, 255.0 / 255.0]
if dataset.get_nsteps() > 1 and dataset.get_npart() == 1:
_x, _y, _z = [], [], []
for step_i in range(step):
dataset.set_step_view(step_i)
_x.append(float(dataset.get(axes[0])))
_y.append(float(dataset.get(axes[1])))
_z.append(float(dataset.get(axes[2])))
pts = np.array([_x, _y, _z]).T
dataset_color = dataset.color()
line_color = rgb(dataset_color[1:])
plot_curve = pg.opengl.GLLinePlotItem(pos=pts, color=line_color,
width=1., antialias=True)
self._graphics_view.addItem(plot_curve)
self._graphics_view.repaint()
if _grid: # If the grid is enabled for this plot
# TODO: Make the grid size dynamic -PW
# TODO: The maximum and minimum values might be useful to get during import -PW
gx = pg.opengl.GLGridItem()
gx.rotate(90, 0, 1, 0)
gx.translate(0.0, 0.0, 0.0)
gx.setSize(x=0.2, y=0.2, z=0.2)
gx.setSpacing(x=0.01, y=0.01, z=0.01)
gy = pg.opengl.GLGridItem()
gy.rotate(90, 1, 0, 0)
gy.translate(0.0, 0.0, 0.0)
gy.setSize(x=0.2, y=0.2, z=0.2)
gy.setSpacing(x=0.01, y=0.01, z=0.01)
gz = pg.opengl.GLGridItem()
gz.translate(0.0, 0.0, 0.0)
gz.setSize(x=0.2, y=0.2, z=1.0)
gz.setSpacing(x=0.01, y=0.01, z=0.01)
# Add the three grids to the graphics view
self._graphics_view.addItem(gx)
self._graphics_view.addItem(gy)
self._graphics_view.addItem(gz)
# Set the "camera" distance
self._graphics_view.opts["distance"] = 3e-1 # Seems to be a good value for now
self._is_shown = True
else: # If it's not a 3D plot, it's a 2D plot...
if enabled:
for dataset in self._datasets: # Loop through each dataset
if dataset.get_nsteps() > 1 and dataset.get_npart() == 1:
_x, _y = [], []
for step_i in range(step):
dataset.set_step_view(step_i)
_x.append(float(dataset.get(axes[0])))
_y.append(float(dataset.get(axes[1])))
plot_curve = pg.PlotDataItem(x=np.array(_x),
y=np.array(_y),
pen=pg.mkPen(dataset.color()), brush='b', size=1.0, pxMode=True)
plot_start = pg.ScatterPlotItem(x=np.array([_x[0]]),
y=np.array([_y[0]]),
pen=pg.mkPen(color=(0.0, 255.0, 0.0)),
symbol="o",
brush='b',
size=3.0,
pxMode=True)
plot_end = pg.ScatterPlotItem(x=np.array([_x[-1]]),
y=np.array([_y[-1]]),
pen=pg.mkPen(color=(255.0, 0.0, 0.0)),
symbol="o",
brush='b',
size=3.0,
pxMode=True)
self._graphics_view.addItem(plot_curve)
self._graphics_view.addItem(plot_start)
self._graphics_view.addItem(plot_end)
if axes[0] == "x" and axes[1] == "y":
self._graphics_view.setAspectLocked(lock=True, ratio=1)
if dataset.orbit() is not None:
xc, yc, r = dataset.orbit()
theta = np.linspace(0, 2*np.pi, 180)
xo = r * np.cos(theta) + xc
yo = r * np.sin(theta) + yc
orbit_curve = pg.PlotDataItem(x=xo,
y=yo,
pen=pg.mkPen(color=dataset.color(), style=QtCore.Qt.DashLine),
brush='b',
size=1.0,
pxMode=True)
orbit_center = pg.ScatterPlotItem(x=np.array([xc]),
y=np.array([yc]),
pen=pg.mkPen(color=dataset.color()),
symbol="s",
brush='b',
size=3.0,
pxMode=True)
self._graphics_view.addItem(orbit_curve)
self._graphics_view.addItem(orbit_center)
else:
self._graphics_view.setAspectLocked(lock=False)
self._graphics_view.showGrid(True, True, 0.5)
self._graphics_view.repaint()
else:
dataset.set_step_view(step) # Set the step for the current dataset
# Create a scatter plot item using the values and color from the dataset
scatter = pg.ScatterPlotItem(x=dataset.get(axes[0]),
y=dataset.get(axes[1]),
pen=pg.mkPen(dataset.color()), brush='b', size=1.0, pxMode=True)
# Add the scatter plot item to the graphics view
self._graphics_view.addItem(scatter)
# Create a title for the graph, which is just the axis labels for now
title = axes[0].upper() + "-" + axes[1].upper()
self._graphics_view.setTitle(title) # Set the title of the graphics view
self._graphics_view.repaint() # Repaint the view
self._is_shown = True # Set the shown flag
return 0
class PlotManager(object):
def __init__(self, parent, debug=False):
self._parent = parent
self._tabs = parent.tabs() # Tab Widget from the parent
self._gvs = [] # A list of the graphics views
self._plot_objects = [] # A list of the plot objects
self._debug = debug # Debug flag
self._screen_size = parent.screen_size() # Get the screen size from the parent
self._plot_settings_gui = None # Used to store the GUI object so it stays in memory while running
self._current_plot = None # Which plot is currently showing (None should be default plots)
self._default_plots = [None, None, None, None] # A list of the default plot objects
self._default_plot_settings = {} # The plot settings for the default plots
self._initialize_default_plots() # Initialization of the default plots
def _initialize_default_plots(self):
default_gv = self._parent.get_default_graphics_views() # Get the default graphics views
self._default_plots = [PlotObject(self, gv) for gv in default_gv] # Make the plot objects
return 0
@staticmethod
def add_to_plot(dataset, plot_object):
if dataset not in plot_object.datasets(): # Only add to the plot object if it isn't already in it
plot_object.add_dataset(dataset)
else:
print("This dataset is already in the PlotObject!")
return 0
def add_to_current_plot(self, dataset):
current_index = self._tabs.currentIndex()
if current_index == 0: # Catch the condition that the default plots are shown
self.add_to_default(dataset)
else:
plot_object = self._plot_objects[current_index - 1]
self.add_to_plot(dataset=dataset, plot_object=plot_object)
return 0
def add_to_default(self, dataset):
for plot_object in self._default_plots: # Add the dataset to all of the default plot objects
plot_object.add_dataset(dataset)
return 0
def apply_default_plot_settings(self, plot_settings, redraw=False):
# TODO: Better way to do this -PW
self._default_plot_settings = plot_settings # Store the plot settings as the default plot settings
prefix_list = ["tl", "tr", "bl", "3d"] # Create a list of prefixes
for idx, plot_object in enumerate(self._default_plots): # Enumerate through the default plot objects
new_plot_settings = {"step": plot_settings["step"]} # Add the step parameter
for key, val in plot_settings.items(): # Scan through all of the default plot settings
if prefix_list[idx] in key: # If the key has the prefix for this plot object...
new_key = "param_"+key.split("_")[1] # Create a new key that will be used by the plot object
new_plot_settings[new_key] = val # Store the value in that new key
new_plot_settings["param_c"] = None # Unused parameter for the 2D plots (needed for 3D)
if idx == 3: # The third (last) index corresponds to the 3D plot, and by default it's x, y, z
new_plot_settings["param_a"] = 0 # 0 --> "x"
new_plot_settings["param_b"] = 1 # 1 --> "y"
new_plot_settings["param_c"] = 2 # 2 --> "z"
new_plot_settings["is_3d"] = 2 # 2 --> True
plot_object.set_plot_settings(new_plot_settings) # Apply the plot settings for the current object
if redraw: # Redraw the plot if the flag is set
self.redraw_plot()
return 0
def default_plot_settings(self, redraw=False):
# Create the default plot settings GUI, store it in memory, and run it
self._plot_settings_gui = PlotSettings(self, redraw=redraw, default=True, debug=self._debug)
self._plot_settings_gui.run()
return 0
def get_default_plot_settings(self):
return self._default_plot_settings # Returns the default plot settings (untranslated)
def get_plot_object(self, tab_index):
if tab_index == 0: # In the case of the default plots tab
return self._default_plots # It returns the list of all the objects
else:
return [self._plot_objects[tab_index - 1]] # Return it in a list
def has_default_plot_settings(self):
# Returns True if the settings for the default plots have been set previously
for plot_object in self._default_plots:
if len(plot_object.get_plot_settings()) > 0:
return True
return False
def modify_plot(self):
if self._tabs.currentIndex() == 0:
self.default_plot_settings(redraw=True)
else:
self.plot_settings(new_plot=False)
return 0
def new_plot(self):
self.new_tab() # Create a new tab for the new plot
plot_object = PlotObject(parent=self, graphics_view=self._gvs[-1]) # Create a plot object for the new gv
self._plot_objects.append(plot_object) # Add this new plot object to the list of plot objects
self.plot_settings(new_plot=True) # Open the plot settings for this plot
return 0
def new_tab(self):
# Create a new widget that will be the new tab
local_tab = QtWidgets.QWidget(parent=self._tabs, flags=self._tabs.windowFlags())
gl = QtWidgets.QGridLayout(local_tab) # Create a grid layout
gl.setContentsMargins(0, 0, 0, 0)
gl.setSpacing(6)
self._gvs.append(pg.PlotWidget(local_tab)) # Add the PlotWidget to the list of graphics views
gl.addWidget(self._gvs[-1]) # Add the grid layout to the newest graphics view
# Add the new widget to the tabs widget, and give it a name
self._tabs.addTab(local_tab, "Tab {}".format(self._tabs.count() + 1))
return 0
def plot_settings(self, new_plot=False):
if new_plot is False:
current_index = self._tabs.currentIndex() # The current index of the tab widget
plot_object = self._plot_objects[current_index - 1] # Find the plot object corresponding to that tab index
self._plot_settings_gui = PlotSettings(self, plot_object, debug=self._debug)
else:
plot_object = self._plot_objects[-1]
self._plot_settings_gui = PlotSettings(self, plot_object, new_plot=True, debug=self._debug)
self._plot_settings_gui.run() # Run the GUI
return 0
def redraw_default_plots(self):
# Clear, then show each plot object in the default plot object list
for plot_object in self._default_plots:
plot_object.clear()
plot_object.show()
return 0
def redraw_plot(self):
current_index = self._tabs.currentIndex() # Get the current index of the tab widget
if current_index == 0: # If it's zero, it's the first tab/default plots
self.redraw_default_plots()
else:
plot_object = self._plot_objects[current_index - 1] # If not, get the plot object and redraw
plot_object.clear()
plot_object.show()
return 0
def remove_dataset(self, dataset):
for plot_object in self._plot_objects: # Remove the dataset from each plot object
plot_object.remove_dataset(dataset) # Note: the method checks to see if the set is in the object
for default_plot_object in self._default_plots: # Remove the dataset from each default plot object
default_plot_object.remove_dataset(dataset)
return 0
def remove_plot(self):
current_index = self._tabs.currentIndex()
if current_index == 0:
print("You cannot remove the default plots!")
return 1
else:
self._tabs.setCurrentIndex(current_index - 1) # This should always exist -PW
self._tabs.removeTab(current_index)
del self._plot_objects[current_index - 1]
del self._gvs[current_index - 1]
return 0
def screen_size(self):
return self._screen_size # Return the size of the screen
def set_tab(self, index):
if index == "last":
self._tabs.setCurrentIndex(self._tabs.count() - 1)
elif index == "first":
self._tabs.setCurrentIndex(0)
else:
self._tabs.setCurrentIndex(index)
return 0
class PlotSettings(object):
def __init__(self, parent, plot_object=None, redraw=False, default=False, new_plot=False, debug=False):
self._parent = parent
self._plot_object = plot_object
self._debug = debug # Debug flag
self._redraw = redraw # Redraw flag
self._default = default # Default flag
self._new_plot = new_plot # New Plot flag
combo_val = ["x", "y", "z", "r", "px", "py", "pz", "pr"]
# --- Initialize the GUI --- #
if self._default:
self._settings = parent.get_default_plot_settings() # Get the (possibly) previously set settings
self._plotSettingsWindow = QtGui.QMainWindow()
self._plotSettingsWindowGUI = Ui_DefaultPlotSettingsWindow()
self._plotSettingsWindowGUI.setupUi(self._plotSettingsWindow)
for _ in range(self._plotSettingsWindowGUI.tl_combo_a.count()):
self._plotSettingsWindowGUI.tl_combo_a.removeItem(0)
self._plotSettingsWindowGUI.tl_combo_b.removeItem(0)
self._plotSettingsWindowGUI.tr_combo_a.removeItem(0)
self._plotSettingsWindowGUI.tr_combo_b.removeItem(0)
self._plotSettingsWindowGUI.bl_combo_a.removeItem(0)
self._plotSettingsWindowGUI.bl_combo_b.removeItem(0)
for item in combo_val:
self._plotSettingsWindowGUI.tl_combo_a.addItem(item.upper())
self._plotSettingsWindowGUI.tl_combo_b.addItem(item.upper())
self._plotSettingsWindowGUI.tr_combo_a.addItem(item.upper())
self._plotSettingsWindowGUI.tr_combo_b.addItem(item.upper())
self._plotSettingsWindowGUI.bl_combo_a.addItem(item.upper())
self._plotSettingsWindowGUI.bl_combo_b.addItem(item.upper())
self._plotSettingsWindowGUI.tl_combo_a.setCurrentIndex(combo_val.index("x"))
self._plotSettingsWindowGUI.tl_combo_b.setCurrentIndex(combo_val.index("y"))
self._plotSettingsWindowGUI.tr_combo_a.setCurrentIndex(combo_val.index("x"))
self._plotSettingsWindowGUI.tr_combo_b.setCurrentIndex(combo_val.index("px"))
self._plotSettingsWindowGUI.bl_combo_a.setCurrentIndex(combo_val.index("y"))
self._plotSettingsWindowGUI.bl_combo_b.setCurrentIndex(combo_val.index("py"))
else:
self._settings = plot_object.get_plot_settings() # Get the (possibly) previously set settings of the object
self._plotSettingsWindow = QtGui.QMainWindow()
self._plotSettingsWindowGUI = Ui_PlotSettingsWindow()
self._plotSettingsWindowGUI.setupUi(self._plotSettingsWindow)
for _ in range(self._plotSettingsWindowGUI.param_combo_a.count()):
self._plotSettingsWindowGUI.param_combo_a.removeItem(0)
self._plotSettingsWindowGUI.param_combo_b.removeItem(0)
self._plotSettingsWindowGUI.param_combo_c.removeItem(0)
for item in combo_val:
self._plotSettingsWindowGUI.param_combo_a.addItem(item.upper())
self._plotSettingsWindowGUI.param_combo_b.addItem(item.upper())
self._plotSettingsWindowGUI.param_combo_c.addItem(item.upper())
self._plotSettingsWindowGUI.param_combo_a.setCurrentIndex(combo_val.index("x"))
self._plotSettingsWindowGUI.param_combo_b.setCurrentIndex(combo_val.index("y"))
self._plotSettingsWindowGUI.param_combo_c.setCurrentIndex(combo_val.index("z"))
if len(self._settings) > 0: # If there are settings, then populate the GUI
self.populate()
else: # If not, then apply the ones from the UI file
self.apply_settings()
# --- Connections --- #
self._plotSettingsWindowGUI.apply_button.clicked.connect(self.callback_apply)
self._plotSettingsWindowGUI.cancel_button.clicked.connect(self.callback_cancel)
self._plotSettingsWindowGUI.redraw_button.clicked.connect(self.callback_redraw)
self._plotSettingsWindowGUI.main_label.setText("Plot Settings")
def apply_settings(self):
# Step:
self._settings["step"] = self._plotSettingsWindowGUI.step_input.value()
# 3D Plot:
self._settings["3d_en"] = self._plotSettingsWindowGUI.three_d_enabled.checkState()
if self._default and isinstance(self._plotSettingsWindowGUI, Ui_DefaultPlotSettingsWindow):
# Top Left:
self._settings["tl_en"] = self._plotSettingsWindowGUI.tl_enabled.checkState()
self._settings["tl_a"] = self._plotSettingsWindowGUI.tl_combo_a.currentIndex()
self._settings["tl_b"] = self._plotSettingsWindowGUI.tl_combo_b.currentIndex()
# Top Right:
self._settings["tr_en"] = self._plotSettingsWindowGUI.tr_enabled.checkState()
self._settings["tr_a"] = self._plotSettingsWindowGUI.tr_combo_a.currentIndex()
self._settings["tr_b"] = self._plotSettingsWindowGUI.tr_combo_b.currentIndex()
# Bottom Left:
self._settings["bl_en"] = self._plotSettingsWindowGUI.bl_enabled.checkState()
self._settings["bl_a"] = self._plotSettingsWindowGUI.bl_combo_a.currentIndex()
self._settings["bl_b"] = self._plotSettingsWindowGUI.bl_combo_b.currentIndex()
# Redraw:
# self._settings["redraw_en"] = self._plotSettingsWindowGUI.redraw_enabled.checkState()
elif isinstance(self._plotSettingsWindowGUI, Ui_PlotSettingsWindow):
# Parameters:
self._settings["param_a"] = self._plotSettingsWindowGUI.param_combo_a.currentIndex()
self._settings["param_b"] = self._plotSettingsWindowGUI.param_combo_b.currentIndex()
self._settings["param_c"] = self._plotSettingsWindowGUI.param_combo_c.currentIndex()
self._settings["param_en"] = self._plotSettingsWindowGUI.param_enabled.checkState()
def callback_apply(self):
# Apply the settings in the GUI, then apply them to the plot object
self.apply_settings()
if self._default:
self._parent.apply_default_plot_settings(self.get_settings(), redraw=self._redraw)
else:
self._plot_object.set_plot_settings(plot_settings=self.get_settings())
self._plotSettingsWindow.close() # Close the GUI
if self._new_plot is True:
self._parent.set_tab("last")
self._parent.redraw_plot() # Redraw the plot
return 0
def callback_cancel(self):
self._plotSettingsWindow.close() # Close the window
return 0
def callback_redraw(self):
self.apply_settings() # Apply the settings to the GUI
if self._default:
self._parent.apply_default_plot_settings(self.get_settings())
self._parent.redraw_default_plots()
else:
self._plot_object.apply_plot_settings(plot_settings=self.get_settings())
self._parent.redraw_plot() # Redraw the plot
def get_settings(self):
return self._settings # Return the plot settings
def populate(self):
# Step:
self._plotSettingsWindowGUI.step_input.setValue(self._settings["step"])
# 3D Plot:
self._plotSettingsWindowGUI.three_d_enabled.setCheckState(self._settings["3d_en"])
if self._default and isinstance(self._plotSettingsWindowGUI, Ui_DefaultPlotSettingsWindow):
# Top Left:
self._plotSettingsWindowGUI.tl_enabled.setCheckState(self._settings["tl_en"])
self._plotSettingsWindowGUI.tl_combo_a.setCurrentIndex(self._settings["tl_a"])
self._plotSettingsWindowGUI.tl_combo_b.setCurrentIndex(self._settings["tl_b"])
# Top Right:
self._plotSettingsWindowGUI.tr_enabled.setCheckState(self._settings["tr_en"])
self._plotSettingsWindowGUI.tr_combo_a.setCurrentIndex(self._settings["tr_a"])
self._plotSettingsWindowGUI.tr_combo_b.setCurrentIndex(self._settings["tr_b"])
# Bottom Left:
self._plotSettingsWindowGUI.bl_enabled.setCheckState(self._settings["bl_en"])
self._plotSettingsWindowGUI.bl_combo_a.setCurrentIndex(self._settings["bl_a"])
self._plotSettingsWindowGUI.bl_combo_b.setCurrentIndex(self._settings["bl_b"])
# Redraw:
# self._plotSettingsWindowGUI.redraw_enabled.setCheckState(self._settings["redraw_en"])
elif isinstance(self._plotSettingsWindowGUI, Ui_PlotSettingsWindow):
# Parameters:
self._plotSettingsWindowGUI.param_combo_a.setCurrentIndex(self._settings["param_a"])
self._plotSettingsWindowGUI.param_combo_b.setCurrentIndex(self._settings["param_b"])
self._plotSettingsWindowGUI.param_combo_c.setCurrentIndex(self._settings["param_c"])
self._plotSettingsWindowGUI.param_enabled.setCheckState(self._settings["param_en"])
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._plotSettingsWindow.width())
_y = 0.5 * (screen_size.height() - self._plotSettingsWindow.height())
# --- Show the GUI --- #
self._plotSettingsWindow.show()
self._plotSettingsWindow.move(_x, _y)
<file_sep>from ..arraywrapper import ArrayWrapper
from ..abstractdriver import AbstractDriver
from dans_pymodules import IonSpecies
import numpy as np
from scipy import constants as const
clight = const.value("speed of light in vacuum")
class TrackDriver(AbstractDriver):
def __init__(self, debug=False):
super(TrackDriver, self).__init__()
self._debug = debug
self._program_name = "Track"
def get_program_name(self):
return self._program_name
def import_data(self, filename, species=None):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
try:
# TODO: All of this should be part of the particle_processor, not the loading driver! -DW
# Except energy, need that to transform into internal units
align_bunches = True
z_center = -0.25 # user decides centroid position (m)
t_cut = 10.0 # Cut everything above 10 ns away (insufficiently accelerated beam)
t_split = -10.0 # Split bunches at -10.0 ns and shift leading bunch back
e_mean_total = 0.07 # MeV
with open(filename, 'rb') as infile:
header1 = infile.readline()
if self._debug:
print(header1)
lines = infile.readlines()
data = {}
emean = e_mean_total/species.a() # MeV/amu (70 keV)
# current = 0.01 # mA
species.calculate_from_energy_mev(emean)
data["steps"] = 1
data["ion"] = species
data["mass"] = data["ion"].a()
data["charge"] = data["ion"].q()
# data["current"] = current # (A)
data["energy"] = emean * species.a()
data["particles"] = 0
npart = len(lines)
dt = np.zeros(npart)
dw = np.zeros(npart)
x = np.zeros(npart)
xp = np.zeros(npart)
y = np.zeros(npart)
yp = np.zeros(npart)
for i, line in enumerate(lines):
# Data: Nseed, iq, dt (ns), dW (MeV/amu), x (cm), x' (mrad), y (cm), y' (mrad)
_, _, dt[i], dw[i], x[i], xp[i], y[i], yp[i] = [float(value) for value in line.strip().split()]
# Apply cut:
indices = np.where(dt <= t_cut)
dt = dt[indices] # ns
dw = dw[indices] # MeV/amu
x = x[indices] * 1.0e-2 # cm --> m
xp = xp[indices] * 1.0e-3 # mrad --> rad
y = y[indices] * 1.0e-2 # cm --> m
yp = yp[indices] * 1.0e-3 # mrad --> rad
npart_new = len(x)
gammaz = (dw + emean) * species.a() / species.mass_mev() + 1.0
betaz = np.sqrt(1.0 - gammaz**(-2.0))
pz = gammaz * betaz
px = pz * np.tan(xp)
py = pz * np.tan(yp)
vz = clight * betaz
# vx = vz * np.tan(xp)
# vy = vz * np.tan(xp)
print("Cut {} particles out of {}. Remaining particles: {}".format(npart - npart_new, npart, npart_new))
if align_bunches:
# Split bunches
b1_ind = np.where(dt < t_split)
b2_ind = np.where(dt >= t_split)
delta_t_theor = 1.0e9 / 32.8e6 # length of one rf period
delta_t_sim = np.abs(np.mean(dt[b1_ind]) - np.mean(dt[b2_ind]))
print("Splitting bunches at t = {} ns. "
"Time difference between bunch centers = {} ns. "
"One RF period = {} ns.".format(t_split, delta_t_sim, delta_t_theor))
from matplotlib import pyplot as plt
# plt.subplot(231)
# plt.scatter(dt[b1_ind], dw[b1_ind], c="red", s=0.5)
# plt.scatter(dt[b2_ind], dw[b2_ind], c="blue", s=0.5)
# plt.xlabel("dt (ns)")
# plt.ylabel("dW (MeV/amu)")
# plt.subplot(232)
# plt.scatter(x[b1_ind], xp[b1_ind], c="red", s=0.5)
# plt.scatter(x[b2_ind], xp[b2_ind], c="blue", s=0.5)
# plt.xlabel("x (m)")
# plt.ylabel("x' (rad)")
# plt.subplot(233)
# plt.scatter(y[b1_ind], yp[b1_ind], c="red", s=0.5)
# plt.scatter(y[b2_ind], yp[b2_ind], c="blue", s=0.5)
# plt.xlabel("y (m)")
# plt.ylabel("y' (rad)")
# Shift leading bunch
dt[b1_ind] += delta_t_theor
# x[b1_ind] += vx[b1_ind] * 1.0e-9 * delta_t_theor
# y[b1_ind] += vy[b1_ind] * 1.0e-9 * delta_t_theor
# plt.subplot(234)
# plt.scatter(dt[b1_ind], dw[b1_ind], c="red", s=0.5)
# plt.scatter(dt[b2_ind], dw[b2_ind], c="blue", s=0.5)
# plt.xlabel("dt (ns)")
# plt.ylabel("dW (MeV/amu)")
# plt.subplot(235)
# plt.scatter(x[b1_ind], xp[b1_ind], c="red", s=0.5)
# plt.scatter(x[b2_ind], xp[b2_ind], c="blue", s=0.5)
# plt.xlabel("x (m)")
# plt.ylabel("x' (rad)")
# plt.subplot(236)
# plt.scatter(y[b1_ind], yp[b1_ind], c="red", s=0.5)
# plt.scatter(y[b2_ind], yp[b2_ind], c="blue", s=0.5)
# plt.xlabel("y (m)")
# plt.ylabel("y' (rad)")
#
# plt.tight_layout()
# plt.show()
z = z_center - dt * 1e-9 * vz
distribution = {'x': ArrayWrapper(x),
'px': ArrayWrapper(px),
'y': ArrayWrapper(y),
'py': ArrayWrapper(py),
'z': ArrayWrapper(z),
'pz': ArrayWrapper(pz)}
# For a single timestep, we just define a Step#0 entry in a dictionary (supports .get())
data["datasource"] = {"Step#0": distribution}
data["particles"] = npart_new
return data
except Exception as e:
print("Exception happened during particle loading with {} "
"ImportExportDriver: {}".format(self._program_name, e))
return None
def export_data(self, data):
# TODO
if self._debug:
print("Exporting data for program: {}".format(self._program_name))
print("Export not yet implemented :(")
return data
<file_sep>from OPALDriver import *
<file_sep>from py_particle_processor_qt.py_particle_processor_qt import PyParticleProcessor
ppp = PyParticleProcessor(debug=False)
ppp.run()
<file_sep>from py_particle_processor_qt.dataset import *
from py_particle_processor_qt.gui.main_window import *
from py_particle_processor_qt.gui.species_prompt import *
from py_particle_processor_qt.plotting import *
from py_particle_processor_qt.generator import *
from py_particle_processor_qt.tools import *
from PyQt5.QtWidgets import qApp, QFileDialog
# from dans_pymodules import MyColors
__author__ = "<NAME>, <NAME>"
__doc__ = """A QT5 based GUI that allows loading particle data from
various simulation codes and exporting them for various other simulation codes.
"""
class ParticleFile(object):
"""
This object will contain a list of datasets and some attributes for easier handling.
"""
# __slots__ = ("_filename", "_driver", "_debug", "_datasets", "_selected", "_index", "_parent")
def __init__(self, filename, driver, index, load_type, debug=False, **kwargs):
self._filename = filename
self._driver = driver
self._debug = debug
self._datasets = []
self._index = index
self._load_type = load_type
self._parent = kwargs.get("parent")
self._c_i = kwargs.get("color_index")
self._name = ""
self._datasets_to_load = 1 # TODO: Multispecies
self._prompt = None
def add_dataset(self, dataset):
self._datasets.append(dataset)
def dataset_count(self):
return len(self._datasets)
def datasets(self):
return self._datasets
def filename(self):
return self._filename
def get_dataset(self, index):
return self._datasets[index]
def index(self):
return self._index
def load(self, load_index=0, species=None, name=None):
# datasets_to_load = 1
# for i in range(datasets_to_load):
# _ds = Dataset(indices=(self._index, i), debug=self._debug)
# _ds.load_from_file(filename=self._filename, driver=self._driver)
# _ds.assign_color(c_i)
# c_i += 1
# self._datasets.append(_ds)
if load_index == self._datasets_to_load:
# self._prompt = None
if self._load_type == "add":
self._parent.loaded_add_df(self)
elif self._load_type == "new":
self._parent.loaded_new_df(self)
return 0
elif load_index < self._datasets_to_load:
if species is None:
self._prompt = SpeciesPrompt(parent=self)
self._prompt.run()
else:
self.species_callback(None, species, name)
return 0
else:
return 1
def species_callback(self, prompt, species, name="batch"):
if prompt is not None:
prompt.close()
_ds = Dataset(indices=(self._index, len(self._datasets)), debug=self._debug, species=species)
_ds.load_from_file(filename=self._filename, driver=self._driver, name=name)
_ds.assign_color(self._c_i)
self._c_i += 1
self._datasets.append(_ds)
self.load(load_index=len(self._datasets))
def remove_dataset(self, selection):
# if type(selection) is int:
if isinstance(selection, int):
del self._datasets[selection]
# elif type(selection) is Dataset:
elif isinstance(selection, Dataset):
self._datasets.remove(selection)
return 0
def screen_size(self):
return self._parent.screen_size()
def set_dataset(self, index, dataset):
self._datasets[index] = dataset
def set_index(self, index):
self._index = index
# TODO
class FieldFile(object):
def __init__(self, filename, driver, index, debug=False):
self._filename = filename
self._driver = driver
self._index = index
self._debug = debug
def filename(self):
return self._filename
def index(self):
return self._index
def load(self):
pass
def save(self):
pass
class SpeciesPrompt(object):
def __init__(self, parent):
self._parent = parent
self._window = QtGui.QMainWindow()
self._windowGUI = Ui_SpeciesPrompt()
self._windowGUI.setupUi(self._window)
self._windowGUI.apply_button.clicked.connect(self.apply)
for preset_name in sorted(presets.keys()):
self._windowGUI.species_selection.addItem(preset_name)
def apply(self):
preset_name = self._windowGUI.species_selection.currentText()
name = self._windowGUI.dataset_name.text()
print("SpeciesPrompt.apply: name = {}".format(name))
species = IonSpecies(preset_name, energy_mev=1.0) # TODO: Energy? -PW
self._parent.species_callback(self, species=species, name=name)
def close(self):
self._window.close()
return 0
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._window.width())
_y = 0.5 * (screen_size.height() - self._window.height())
# --- Show the GUI --- #
self._window.show()
self._window.move(_x, _y)
class PyParticleProcessor(object):
def __init__(self, debug=False):
"""
Initialize the GUI
"""
self._app = QtGui.QApplication([]) # Initialize the application
self._app.setStyle('Fusion') # Apply a GUI style
self._debug = debug
self._ci = 0 # A color index for datasets
self._datafiles = [] # Container for holding the datasets
self._datafile_buffer = [] # Buffer used to hold datafiles in memory while loading
self._selections = [] # Temporary dataset selections
self._last_path = "" # Stores the last path from loading/saving files
# --- Load the GUI from XML file and initialize connections --- #
self._mainWindow = QtGui.QMainWindow()
self._mainWindowGUI = Ui_MainWindow()
self._mainWindowGUI.setupUi(self._mainWindow)
# --- Get some widgets from the builder --- #
self._tabs = self._mainWindowGUI.tabWidget
self._tabs.currentChanged.connect(self.callback_tab_change)
self._status_bar = self._mainWindowGUI.statusBar
self._treewidget = self._mainWindowGUI.treeWidget
self._treewidget.itemClicked.connect(self.treewidget_clicked)
self._properties_select = self._mainWindowGUI.properties_combo
self._properties_select.__setattr__("data_objects", [])
self._properties_table = self._mainWindowGUI.properties_table
self._properties_label = self._mainWindowGUI.properties_label
self._properties_table.setHorizontalHeaderLabels(["Property", "Value"])
self._properties_table.__setattr__("data", None) # The currently selected data
self._properties_label.setText("Properties")
self._menubar = self._mainWindowGUI.menuBar
self._menubar.setNativeMenuBar(False) # This is needed to make the menu bar actually appear -PW
# --- Connections --- #
self._mainWindowGUI.actionQuit.triggered.connect(self.main_quit)
self._mainWindowGUI.actionImport_New.triggered.connect(self.callback_load_new_ds)
self._mainWindowGUI.actionImport_Add.triggered.connect(self.callback_load_add_ds)
self._mainWindowGUI.actionRemove.triggered.connect(self.callback_delete_ds)
self._mainWindowGUI.actionAnalyze.triggered.connect(self.callback_analyze)
# self._mainWindowGUI.actionPlot.triggered.connect(self.callback_plot)
self._mainWindowGUI.actionGenerate.triggered.connect(self.callback_generate)
self._mainWindowGUI.actionExport_For.triggered.connect(self.callback_export)
self._properties_table.cellChanged.connect(self.callback_table_item_changed)
self._properties_select.currentIndexChanged.connect(self.callback_properties_select)
# --- Populate the Tools Menu --- #
self._tools_menu = self._mainWindowGUI.menuTools
self._current_tool = None
for tool_name, tool_object in sorted(tool_mapping.items()):
action = QtWidgets.QAction(self._mainWindow)
action.setText(tool_object[0])
action.setObjectName(tool_name)
# noinspection PyUnresolvedReferences
action.triggered.connect(self.callback_tool_action)
self._tools_menu.addAction(action)
# --- Resize the columns in the treewidget --- #
for i in range(self._treewidget.columnCount()):
self._treewidget.resizeColumnToContents(i)
# --- Initial population of the properties table --- #
self._property_list = ["name", "steps", "particles", "mass", "energy", "charge", "current"]
self._units_list = [None, None, None, "amu", "MeV", "e", "A"]
self._properties_table.setRowCount(len(self._property_list))
# --- Do some plot manager stuff --- #
self._plot_manager = PlotManager(self)
self._mainWindowGUI.actionRedraw.triggered.connect(self._plot_manager.redraw_plot)
self._mainWindowGUI.actionNew_Plot.triggered.connect(self._plot_manager.new_plot)
self._mainWindowGUI.actionModify_Plot.triggered.connect(self._plot_manager.modify_plot)
self._mainWindowGUI.actionRemove_Plot.triggered.connect(self._plot_manager.remove_plot)
# Store generator information
self._gen = GeneratorGUI(self)
self._gen_data = {}
# Go through each property in the list
for idx, item in enumerate(self._property_list):
p_string = item.title() # Create a string from the property name
if self._units_list[idx] is not None: # Check if the unit is not None
p_string += " (" + self._units_list[idx] + ")" # Add the unit to the property string
p = QtGui.QTableWidgetItem(p_string) # Create a new item with the property string
p.setFlags(QtCore.Qt.NoItemFlags) # Disable all item flags
self._properties_table.setItem(idx, 0, p) # Set the item to the corresponding row (first column)
v = QtGui.QTableWidgetItem("") # Create a blank item to be a value placeholder
v.setFlags(QtCore.Qt.NoItemFlags) # Disable all item flags
self._properties_table.setItem(idx, 1, v) # Set the item to the corresponding row (second column)
def add_generated_dataset(self, data, settings):
filename, driver = self.get_filename(action='save') # Get a filename and driver
df_i = len(self._datafiles)
new_df = ParticleFile(filename=filename, driver=driver, index=df_i, load_type="add", parent=self)
dataset = Dataset(indices=(df_i, 0), data=data,
species=IonSpecies(name=settings["species"], energy_mev=float(settings["energy"])))
# We need a better way to do this -PW
dataset.set_property("name", "Generated Dataset")
# dataset.set_property("ion", IonSpecies(name=settings["species"], energy_mev=float(settings["energy"])))
dataset.set_property("steps", 1)
dataset.set_property("particles", int(settings["numpart"]))
dataset.set_property("curstep", 0)
dataset.assign_color(1)
dataset.export_to_file(filename=filename, driver=driver)
new_df.add_dataset(dataset=dataset)
self._datafiles.append(new_df)
top_level_item = QtGui.QTreeWidgetItem(self._treewidget) # Create the top level item for the datafile
top_level_item.setText(0, "") # Selection box
top_level_item.setText(1, "{}".format(df_i)) # Display the id of the datafile
top_level_item.setText(2, self._datafiles[-1].filename()) # Display the filename
top_level_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
top_level_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the datafile to be unchecked by default
self._properties_select.addItem("Datafile {}".format(df_i)) # Add an item to the property selection
number_of_datasets = new_df.dataset_count() # For now, assume there exists only one dataset
for ds_i in range(number_of_datasets): # Loop through each dataset
child_item = QtGui.QTreeWidgetItem(top_level_item) # Create a child item for the dataset
child_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
child_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the dataset to be unchecked by default
self.add_tree_item(df_i, ds_i) # Update the tree item with those indices
# Add an item to the property selection
self._properties_select.addItem("Datafile {}, Dataset {}".format(df_i, ds_i))
# Conditional to check if there's only one dataset
if number_of_datasets == 1:
if not self._plot_manager.has_default_plot_settings(): # If the default plot settings aren't set...
self._plot_manager.default_plot_settings() # Open the default plot settings GUI
# If you want the dataset to automatically be unselected
child_item.setCheckState(0, QtCore.Qt.Unchecked)
# If you want the dataset to automatically be selected
# child_item.setCheckState(0, QtCore.Qt.Checked)
# self._selections.append("{}-{}".format(df_i, ds_i))
top_level_item.setExpanded(True) # Expand the tree widget
for i in range(self._treewidget.columnCount()): # Resize the columns of the tree
self._treewidget.resizeColumnToContents(i)
def add_to_properties_selection(self, datafile):
self._properties_select.addItem("Datafile {}".format(datafile.index()))
self._properties_select.data_objects.append(datafile)
for index, dataset in enumerate(datafile.datasets()):
self._properties_select.addItem("Datafile {}, Dataset {}".format(datafile.index(), index))
self._properties_select.data_objects.append(dataset)
def callback_about_program(self, menu_item):
"""
:param menu_item:
:return:
"""
if self._debug:
print("DEBUG: About Dialog called by {}".format(menu_item))
return 0
def callback_analyze(self):
print("Not implemented yet!")
for dataset in self._selections:
for i in range(dataset.get_npart()):
print(dataset.get("x")[i])
print(dataset.get("y")[i])
print(dataset.get("r")[i])
print(dataset.get("px")[i])
print(dataset.get("py")[i])
return 0
def callback_delete_ds(self):
"""
Callback for Delete Dataset... button
:return:
"""
if self._debug:
print("DEBUG: delete_ds_callback was called")
if len(self._selections) < 1: # Check to make sure something was selected to remove
msg = "You must select something to remove."
print(msg)
self.send_status(msg)
redraw_flag = False # Set a redraw flag to False
root = self._treewidget.invisibleRootItem() # Find the root item
for selection in self._selections:
redraw_flag = True
if selection in self._properties_select.data_objects:
index = self._properties_select.data_objects.index(selection)
self._properties_select.removeItem(index)
self._properties_select.data_objects.remove(selection)
# if type(selection) is ParticleFile or type(selection) is FieldFile:
if isinstance(selection, (ParticleFile, FieldFile)):
del self._datafiles[selection.index()]
item = self._treewidget.topLevelItem(selection.index())
(item.parent() or root).removeChild(item)
if len(self._properties_select.data_objects[index:]) > 0:
# while type(self._properties_select.data_objects[index]) is Dataset:
while isinstance(self._properties_select.data_objects[index], Dataset):
print(self._properties_select.data_objects[index].indices())
self._properties_select.removeItem(index)
del self._properties_select.data_objects[index]
if index == len(self._properties_select.data_objects):
break
# elif type(selection) is Dataset:
elif isinstance(selection, Dataset):
self._plot_manager.remove_dataset(selection)
parent_index = selection.indices()[0]
child_index = selection.indices()[1]
self._datafiles[parent_index].remove_dataset(selection)
item = self._treewidget.topLevelItem(parent_index).child(child_index)
(item.parent() or root).removeChild(item)
self._selections = []
if redraw_flag: # If the redraw flag was set, redraw the plot
self.refresh_data()
self.clear_properties_table()
self._plot_manager.redraw_plot()
return 0
def callback_export(self):
if self._debug:
"DEBUG: export_callback called"
# TODO: This should make sure we're selecting a dataset vs. datafile
if len(self._selections) == 0: # Check to see if no datasets were selected
msg = "No dataset was selected!"
print(msg)
self.send_status(msg)
return 1
elif len(self._selections) > 1: # Check to see if too many datasets were selected
msg = "You cannot select more than one dataset!"
print(msg)
self.send_status(msg)
return 1
filename, driver = self.get_filename(action='save') # Get a filename and driver
if (filename, driver) == (None, None):
return 0
selection = self._selections[0]
selection.export_to_file(filename=filename, driver=driver)
print("Export complete!")
self.send_status("Export complete!")
return 0
def callback_load_add_ds(self, widget):
"""
Callback for Add Dataset... button
:return:
"""
batch = False
if self._debug:
print("DEBUG: load_add_ds_callback was called with widget {}".format(widget))
filenames, driver = self.get_filename(action="open") # Get a filename and driver
if filenames is None: # Return if no file was selected
return 1
if len(filenames) > 1:
batch = True
self.send_status("Loading file with driver: {}".format(driver))
# Create a new datafile with the supplied parameters
for filename in filenames:
# Create a new datafile with the supplied parameters
new_df = ParticleFile(filename=filename,
driver=driver,
index=0,
load_type="add",
debug=self._debug,
parent=self,
color_index=self._ci)
if not batch:
new_df.load()
else:
species = self._datafiles[0].datasets()[0].get_property("ion")
name = os.path.splitext(os.path.split(filename)[1])[0]
new_df.load(species=species, name=name)
self._datafile_buffer.append(new_df)
return 0
def loaded_add_df(self, new_df):
# If the loading of the datafile is successful...
self._datafiles.append(new_df) # Add the datafile to the list
self._datafile_buffer.remove(new_df) # Remove the datafile from the buffer
df_i = len(self._datafiles) - 1 # Since it's the latest datafile, it's the last index
self._ci += new_df.dataset_count() # TODO: Is this right?
top_level_item = QtGui.QTreeWidgetItem(self._treewidget) # Create the top level item for the datafile
top_level_item.setText(0, "") # Selection box
top_level_item.setText(1, "{}".format(df_i)) # Display the id of the datafile
top_level_item.setText(2, self._datafiles[-1].filename()) # Display the filename
top_level_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
top_level_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the datafile to be unchecked by default
# self._properties_select.addItem("Datafile {}".format(df_i)) # Add an item to the property selection
for ds_i in range(new_df.dataset_count()): # Loop through each dataset
child_item = QtGui.QTreeWidgetItem(top_level_item) # Create a child item for the dataset
child_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
child_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the dataset to be unchecked by default
self.add_tree_item(df_i, ds_i) # Update the tree item with those indices
# Add an item to the property selection
# self._properties_select.addItem("Datafile {}, Dataset {}".format(df_i, ds_i))
# Conditional to check if there's only one dataset
if new_df.dataset_count() == 1:
if not self._plot_manager.has_default_plot_settings(): # If the default plot settings aren't set...
self._plot_manager.default_plot_settings() # Open the default plot settings GUI
# If you want the dataset to automatically be unselected
child_item.setCheckState(0, QtCore.Qt.Unchecked)
# If you want the dataset to automatically be selected
# child_item.setCheckState(0, QtCore.Qt.Checked)
# self._selections.append("{}-{}".format(df_i, ds_i))
self.add_to_properties_selection(new_df)
top_level_item.setExpanded(True) # Expand the tree widget
for i in range(self._treewidget.columnCount()): # Resize the columns of the tree
self._treewidget.resizeColumnToContents(i)
self.send_status("File loaded successfully!")
return 0
def callback_load_new_ds(self):
"""
Callback for Load Dataset... button
:return:
"""
if self._debug:
print("DEBUG: load_new_ds_callback was called.")
filenames, driver = self.get_filename(action="open") # Get a filename and driver
if filenames is None: # Return if no file was selected
return 1
self.send_status("Loading file with driver: {}".format(driver))
# Create a new datafile with the supplied parameters
new_df = ParticleFile(filename=filenames[0],
driver=driver,
index=0,
load_type="new",
debug=self._debug,
parent=self,
color_index=self._ci)
new_df.load()
self._datafile_buffer.append(new_df)
return 0
def loaded_new_df(self, new_df):
# If the loading of the datafile is successful...
self._datafiles = [new_df] # Set the list of datafiles to just this one
self._datafile_buffer.remove(new_df) # Remove the datafile from the buffer
df_i = 0 # Since it's the only datafile, it's the zeroth index
self._ci += new_df.dataset_count() # TODO: Is this right?
top_level_item = QtGui.QTreeWidgetItem(self._treewidget) # Create the top level item for the datafile
top_level_item.setText(0, "") # Selection box
top_level_item.setText(1, "{}".format(df_i)) # Display the id of the datafile
top_level_item.setText(2, self._datafiles[-1].filename()) # Display the filename
top_level_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
top_level_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the datafile to be unchecked by default
# self._properties_select.addItem("Datafile {}".format(df_i)) # Add an item to the property selection
number_of_datasets = 1 # For now, assume there exists only one dataset
for ds_i in range(number_of_datasets): # Loop through each dataset
child_item = QtGui.QTreeWidgetItem(top_level_item) # Create a child item for the dataset
child_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable) # Set item flags
child_item.setCheckState(0, QtCore.Qt.Unchecked) # Set the dataset to be unchecked by default
self.add_tree_item(df_i, ds_i) # Update the tree item with those indices
# Add an item to the property selection
# self._properties_select.addItem("Datafile {}, Dataset {}".format(df_i, ds_i))
# Conditional to check if there's only one dataset
if number_of_datasets == 1:
if not self._plot_manager.has_default_plot_settings(): # If the default plot settings aren't set...
self._plot_manager.default_plot_settings() # Open the default plot settings GUI
# If you want the dataset to automatically be unselected
child_item.setCheckState(0, QtCore.Qt.Unchecked)
# If you want the dataset to automatically be selected
# child_item.setCheckState(0, QtCore.Qt.Checked)
# self._selections.append("{}-{}".format(df_i, ds_i))
self.add_to_properties_selection(new_df)
top_level_item.setExpanded(True) # Expand the tree widget
for i in range(self._treewidget.columnCount()): # Resize the columns of the tree
self._treewidget.resizeColumnToContents(i)
self.send_status("File loaded successfully!")
# def callback_plot(self):
# # Called when the "Plot..." Button is pressed
#
# if self._debug:
# "DEBUG: callback_plot called"
#
# if self._tabs.currentIndex() == 0: # Check to see if it's the default plot tab
# self._plot_manager.default_plot_settings(redraw=True) # Open the default plot settings
# elif self._tabs.currentIndex() > 1: # Check to see if it's after the text tab
# self._plot_manager.plot_settings() # Open the plot settings
#
# return 0
def callback_generate(self):
# Called when the "Generate..." button is pressed
self._gen.run()
# self._gen_data = self._gen.data
# self.add_generated_data_set(self._gen.data)
def callback_properties_select(self, index):
# Get the text from the selected item in the properties selection
txt = [item.rstrip(",") for item in self._properties_select.itemText(index).split()]
# Format: "Datafile {}, Dataset {}" or "Datafile {}"
if len(txt) == 4: # If there are 4 items, it's a dataset
df_i, ds_i = int(txt[1]), int(txt[3]) # Get the corresponding indices
dataset = self.find_dataset(df_i, ds_i) # Get the dataset
self._properties_table.data = dataset # Set the table's data property
self.populate_properties_table(dataset) # Populate the properties table with the dataset info
return 0
elif len(txt) == 2: # If there are two items, it's a datafile
df_i, ds_i = int(txt[1]), None # Get the datafile index
datafile = self._datafiles[df_i] # Get the datafile object
self._properties_table.data = datafile
self.populate_properties_table(datafile) # Populate the properties table with datafile info
return 0
elif index == -1: # Check if the index is -1
# This happens when there are no more datasets
return 0
else: # This can only happen when something on the backend isn't working right
print("Something went wrong!")
return 1
def callback_tab_change(self):
current_index = self._tabs.currentIndex()
current_plot_objects = self._plot_manager.get_plot_object(current_index)
redraw = False
for plot_object in current_plot_objects:
for selection in self._selections:
# if type(selection) is Dataset:
if isinstance(selection, Dataset):
if selection not in plot_object.datasets():
plot_object.add_dataset(selection)
redraw = True
if redraw:
self._plot_manager.redraw_plot()
return 0
def callback_table_item_changed(self):
v = self._properties_table.currentItem() # Find the current item that was changed
# Filter out some meaningless things that could call this function
if v is None or v.text == "":
return 0
data = self._properties_table.data # Get the datafile and dataset ids from the table
# Filter out the condition that the program is just starting and populating the table
if data is None:
return 0
# TODO: This might trigger a problem if a datafile is selected
idx = self._properties_table.currentRow() # Find the row of the value that was changed
try:
if idx != 0:
value = float(v.text()) # Try to convert the input to a float
v.setText(str(value)) # Reset the text of the table item to what was just set
data.set_property(self._property_list[idx], value) # Set the property of the dataset
else:
if self._debug:
print("Changing dataset name")
value = v.text()
data.set_property(self._property_list[idx], value) # Set the name of the dataset
self.refresh_data(properties=False)
v.setForeground(QtGui.QBrush(QtGui.QColor("#FFFFFF"))) # If all this worked, then set the text color
return 0
except ValueError:
# ds.set_property(self._property_list[idx], None) # Set the dataset property to None
v.setForeground(QtGui.QBrush(QtGui.QColor("#FF0000"))) # Set the text color to red
return 1
def callback_tool_action(self):
sender = self._mainWindow.sender()
name = sender.objectName()
datasets = []
for selection in self._selections:
# if type(selection) is Dataset:
if isinstance(selection, Dataset):
datasets.append(selection)
tool_object = tool_mapping[name][1]
self._current_tool = tool_object(parent=self)
self._current_tool.set_selections(datasets)
if self._current_tool.redraw_on_exit():
self._current_tool.set_plot_manager(self._plot_manager)
if self._current_tool.check_requirements() == 0:
self._current_tool.open_gui()
def clear_properties_table(self):
self._properties_table.setCurrentItem(None) # Set the current item to None
self._properties_table.data = None # Clear the data property
self._properties_label.setText("Properties") # Set the label
for idx in range(len(self._property_list)): # Loop through each row
v = QtGui.QTableWidgetItem("") # Create a placeholder item
v.setFlags(QtCore.Qt.NoItemFlags) # Disable item flags
self._properties_table.setItem(idx, 1, v) # Add the item to the table
return 0
def find_dataset(self, datafile_id, dataset_id):
return self._datafiles[datafile_id].get_dataset(dataset_id) # Return the dataset object given the indices
def get_default_graphics_views(self):
# Return a tuple of the graphics views from the default plots tab
default_gv = (self._mainWindowGUI.graphicsView_1,
self._mainWindowGUI.graphicsView_2,
self._mainWindowGUI.graphicsView_3,
self._mainWindowGUI.graphicsView_4)
return default_gv
def get_filename(self, action="open"):
filename, filetype = "", ""
# Format the filetypes selection
first_flag1 = True
filetypes_text = ""
for key in sorted(driver_mapping.keys()):
if len(driver_mapping[key]["extensions"]) > 0:
if first_flag1:
filetypes_text += "{} Files (".format(key)
first_flag1 = False
else:
filetypes_text += ";;{} Files (".format(key)
first_flag2 = True
for extension in driver_mapping[key]["extensions"]:
if first_flag2:
filetypes_text += "*{}".format(extension)
first_flag2 = False
else:
filetypes_text += " *{}".format(extension)
filetypes_text += ")"
# Create the file dialog options
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
if action == "open": # For opening a file
filenames, filetype = QFileDialog.getOpenFileNames(self._mainWindow,
caption="Import dataset...",
directory=self._last_path,
filter=filetypes_text,
options=options)
if len(filenames) == 0 or filetype == "":
filenames, driver = None, None
return filenames, driver
assert len(np.unique(np.array([os.path.splitext(_fn)[1] for _fn in filenames]))) == 1, \
"For batch selection, all filenames have to have the same extension!"
driver = filetype.split("Files")[0].strip() # Get the driver from the filetype
return filenames, driver
elif action == "save": # For saving a file
filename, filetype = QFileDialog.getSaveFileName(self._mainWindow,
caption="Export dataset...",
directory=self._last_path,
filter=filetypes_text,
options=options)
if filename == "" or filetype == "":
filename, driver = None, None
return filename, driver
driver = filetype.split("Files")[0].strip() # Get the driver from the filetype
return filename, driver
@staticmethod
def get_selection(selection_string):
if "-" in selection_string: # If there's a hyphen, it's a dataset
indices = selection_string.split("-")
datafile_index, dataset_index = int(indices[0]), int(indices[1]) # Convert the strings to ints
return datafile_index, dataset_index
else: # Or else it's a datafile
datafile_index = int(selection_string) # Convert the string into an int
return datafile_index, None
def initialize(self):
"""
Do all remaining initializations
:return: 0
"""
if self._debug:
print("DEBUG: Called initialize() function.")
self._status_bar.showMessage("Program Initialized.")
return 0
def main_quit(self):
"""
Shuts down the program (and threads) gracefully.
:return:
"""
if self._debug:
print("DEBUG: Called main_quit")
self._mainWindow.destroy() # Close the window
qApp.quit() # Quit the application
return 0
def populate_properties_table(self, data_object):
self.clear_properties_table()
# if type(data_object) is ParticleFile:
if isinstance(data_object, (ParticleFile, FieldFile)): # If the object passed is a datafile...
# df = data_object
print("Datafile properties are not implemented yet!")
return 1
# elif type(data_object) is Dataset:
elif isinstance(data_object, Dataset): # If the object passed is a dataset...
ds = data_object
self._properties_table.data = ds
# self._properties_label.setText("Properties (Datafile #{}, Dataset #{})".format(df_i, ds_i))
for idx, item in enumerate(self._property_list): # Enumerate through the properties list
if ds.get_property(item) is not None: # If the property is not None
v = QtWidgets.QTableWidgetItem(str(ds.get_property(item))) # Set the value item
if ds.is_native_property(item): # If it's a native property to the set, it's not editable
v.setFlags(QtCore.Qt.ItemIsEnabled)
else: # If it is not a native property, it may be edited
v.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
else: # IF the property wasn't found
v = QtWidgets.QTableWidgetItem("Property not found") # Create a placeholder
v.setForeground(QtGui.QBrush(QtGui.QColor("#FF0000"))) # Set the text color to red
v.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) # Make it editable
self._properties_table.setItem(idx, 1, v) # Put the item in the table
return 0
def refresh_data(self, properties=True):
self._treewidget.clear()
if properties:
self._properties_select.clear()
self._properties_select.data_objects = []
for parent_index, datafile in enumerate(self._datafiles):
datafile.set_index(parent_index)
# --- Refresh Tree Widget for the Datafile --- #
top_level_item = QtGui.QTreeWidgetItem(self._treewidget)
top_level_item.setText(0, "")
top_level_item.setText(1, "{}".format(parent_index))
top_level_item.setText(2, datafile.filename())
top_level_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
top_level_item.setCheckState(0, QtCore.Qt.Unchecked)
for child_index, dataset in enumerate(datafile.datasets()):
# --- Refresh Tree Widget for the Dataset --- #
dataset.set_indices(parent_index, child_index)
child_item = QtGui.QTreeWidgetItem(top_level_item)
child_item.setText(0, "") # Selection box
child_item.setText(1, "{}-{}".format(parent_index, child_index))
child_item.setText(2, "{}".format(dataset.get_name()))
child_item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsUserCheckable)
child_item.setCheckState(0, QtCore.Qt.Unchecked)
pass
top_level_item.setExpanded(True) # Expand the tree widget
# --- Refresh the Properties Selection for the Datafile --- #
if properties:
self.add_to_properties_selection(datafile)
for i in range(self._treewidget.columnCount()): # Resize the columns of the tree
self._treewidget.resizeColumnToContents(i)
def run(self):
"""
Run the GUI
:return:
"""
self.initialize()
# --- Calculate the positions to center the window --- #
screen_size = self.screen_size()
_x = 0.5 * (screen_size.width() - self._mainWindow.width())
_y = 0.5 * (screen_size.height() - self._mainWindow.height())
# --- Show the GUI --- #
self._mainWindow.show()
self._mainWindow.move(_x, _y)
self._app.exec_()
return 0
def screen_size(self):
return self._app.desktop().availableGeometry() # Return the size of the screen
def send_status(self, message):
if isinstance(message, str): # Make sure we're sending a string to the status bar
self._status_bar.showMessage(message)
else:
print("Status message is not a string!")
return 1
return 0
def tabs(self):
return self._tabs # Return the tab widget
def treewidget_clicked(self, item, column):
if self._debug:
print("treewidget_data_changed callback called with item {} and column {}".format(item, column))
if column == 0: # If the first column was clicked
checkstate = (item.checkState(0) == QtCore.Qt.Checked) # Get a True or False value for selection
index = self._treewidget.indexFromItem(item).row() # Get the row index
if item.parent() is None: # If the item does not have a parent, it's a datafile
selection = self._datafiles[index]
else: # If it does, it's a dataset
parent_index = self._treewidget.indexFromItem(item.parent()).row()
selection = self._datafiles[parent_index].get_dataset(index)
if checkstate is True and selection not in self._selections:
self._selections.append(selection) # Add the string to the selections
# if type(selection) is Dataset:
if isinstance(selection, Dataset):
self._plot_manager.add_to_current_plot(selection) # Add to plot
if not self._plot_manager.has_default_plot_settings(): # Check for default plot settings
self._plot_manager.default_plot_settings() # Open the default plot settings
self._plot_manager.redraw_plot() # Redraw the plot
elif checkstate is False and selection in self._selections:
self._selections.remove(selection) # Remove the string from the selections
# if type(selection) is Dataset:
if isinstance(selection, Dataset):
self._plot_manager.remove_dataset(selection) # Remove the dataset
self._plot_manager.redraw_plot() # Redraw the plot
return 0
def add_tree_item(self, datafile_id, dataset_id):
dataset = self._datafiles[datafile_id].get_dataset(dataset_id) # Get the dataset object from the indices
child_item = self._treewidget.topLevelItem(datafile_id).child(dataset_id) # Create a child item
child_item.setText(0, "") # Selection box
child_item.setText(1, "{}-{}".format(datafile_id, dataset_id)) # Set the object id
# child_item.setText(2, "{}".format(dataset.get_ion().name())) # Set the dataset name (for now, the ion name)
child_item.setText(2, "{}".format(dataset.get_name())) # Set the dataset name
child_item.setFlags(child_item.flags() | QtCore.Qt.ItemIsUserCheckable) # Set item flags
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui/main_window.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(994, 654)
MainWindow.setStyleSheet("background-color: rgb(65, 65, 65);\n"
"alternate-background-color: rgb(130, 130, 130);\n"
"color: rgb(255, 255, 255);")
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralWidget)
self.gridLayout.setContentsMargins(11, 2, 11, 11)
self.gridLayout.setSpacing(6)
self.gridLayout.setObjectName("gridLayout")
self.splitter_2 = QtWidgets.QSplitter(self.centralWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter_2.sizePolicy().hasHeightForWidth())
self.splitter_2.setSizePolicy(sizePolicy)
self.splitter_2.setOrientation(QtCore.Qt.Horizontal)
self.splitter_2.setObjectName("splitter_2")
self.splitter = QtWidgets.QSplitter(self.splitter_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
self.splitter.setSizePolicy(sizePolicy)
self.splitter.setLayoutDirection(QtCore.Qt.LeftToRight)
self.splitter.setFrameShape(QtWidgets.QFrame.Box)
self.splitter.setFrameShadow(QtWidgets.QFrame.Plain)
self.splitter.setLineWidth(0)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setHandleWidth(6)
self.splitter.setObjectName("splitter")
self.layoutWidget = QtWidgets.QWidget(self.splitter)
self.layoutWidget.setObjectName("layoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)
self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.verticalLayout.setContentsMargins(11, 11, 11, 11)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.datasets_label = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.datasets_label.sizePolicy().hasHeightForWidth())
self.datasets_label.setSizePolicy(sizePolicy)
self.datasets_label.setObjectName("datasets_label")
self.verticalLayout.addWidget(self.datasets_label, 0, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
spacerItem = QtWidgets.QSpacerItem(20, 2, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout.addItem(spacerItem)
self.treeWidget = QtWidgets.QTreeWidget(self.layoutWidget)
self.treeWidget.setFocusPolicy(QtCore.Qt.NoFocus)
self.treeWidget.setAlternatingRowColors(False)
self.treeWidget.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
self.treeWidget.setTextElideMode(QtCore.Qt.ElideRight)
self.treeWidget.setObjectName("treeWidget")
self.treeWidget.header().setVisible(True)
self.treeWidget.header().setCascadingSectionResizes(False)
self.treeWidget.header().setDefaultSectionSize(80)
self.treeWidget.header().setMinimumSectionSize(1)
self.treeWidget.header().setStretchLastSection(True)
self.verticalLayout.addWidget(self.treeWidget)
self.layoutWidget1 = QtWidgets.QWidget(self.splitter)
self.layoutWidget1.setObjectName("layoutWidget1")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget1)
self.verticalLayout_2.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.verticalLayout_2.setContentsMargins(11, 11, 11, 11)
self.verticalLayout_2.setSpacing(0)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setContentsMargins(11, 11, 11, 11)
self.horizontalLayout_3.setSpacing(6)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.properties_label = QtWidgets.QLabel(self.layoutWidget1)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.properties_label.sizePolicy().hasHeightForWidth())
self.properties_label.setSizePolicy(sizePolicy)
self.properties_label.setObjectName("properties_label")
self.horizontalLayout_3.addWidget(self.properties_label)
spacerItem1 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem1)
self.properties_combo = QtWidgets.QComboBox(self.layoutWidget1)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.properties_combo.sizePolicy().hasHeightForWidth())
self.properties_combo.setSizePolicy(sizePolicy)
self.properties_combo.setObjectName("properties_combo")
self.horizontalLayout_3.addWidget(self.properties_combo)
self.verticalLayout_2.addLayout(self.horizontalLayout_3)
spacerItem2 = QtWidgets.QSpacerItem(20, 2, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_2.addItem(spacerItem2)
self.properties_table = QtWidgets.QTableWidget(self.layoutWidget1)
self.properties_table.setRowCount(1)
self.properties_table.setColumnCount(2)
self.properties_table.setObjectName("properties_table")
self.properties_table.horizontalHeader().setStretchLastSection(True)
self.properties_table.verticalHeader().setVisible(False)
self.properties_table.verticalHeader().setStretchLastSection(False)
self.verticalLayout_2.addWidget(self.properties_table)
self.tabWidget = QtWidgets.QTabWidget(self.splitter_2)
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setStyleSheet("background-color: rgb(0, 0, 0);")
self.tab.setObjectName("tab")
self.gridLayout_4 = QtWidgets.QGridLayout(self.tab)
self.gridLayout_4.setContentsMargins(11, 11, 11, 11)
self.gridLayout_4.setSpacing(6)
self.gridLayout_4.setObjectName("gridLayout_4")
self.gridLayout_3 = QtWidgets.QGridLayout()
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(7)
self.gridLayout_3.setObjectName("gridLayout_3")
self.graphicsView_1 = PlotWidget(self.tab)
self.graphicsView_1.setObjectName("graphicsView_1")
self.gridLayout_3.addWidget(self.graphicsView_1, 0, 0, 1, 1)
self.graphicsView_2 = PlotWidget(self.tab)
self.graphicsView_2.setObjectName("graphicsView_2")
self.gridLayout_3.addWidget(self.graphicsView_2, 0, 1, 1, 1)
self.graphicsView_3 = PlotWidget(self.tab)
self.graphicsView_3.setObjectName("graphicsView_3")
self.gridLayout_3.addWidget(self.graphicsView_3, 1, 0, 1, 1)
self.graphicsView_4 = GLViewWidget(self.tab)
self.graphicsView_4.setObjectName("graphicsView_4")
self.gridLayout_3.addWidget(self.graphicsView_4, 1, 1, 1, 1)
self.gridLayout_4.addLayout(self.gridLayout_3, 0, 0, 1, 1)
self.tabWidget.addTab(self.tab, "")
self.gridLayout.addWidget(self.splitter_2, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralWidget)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mainToolBar.sizePolicy().hasHeightForWidth())
self.mainToolBar.setSizePolicy(sizePolicy)
self.mainToolBar.setIconSize(QtCore.QSize(16, 16))
self.mainToolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 994, 25))
self.menuBar.setDefaultUp(True)
self.menuBar.setNativeMenuBar(True)
self.menuBar.setObjectName("menuBar")
self.menu_File = QtWidgets.QMenu(self.menuBar)
self.menu_File.setFocusPolicy(QtCore.Qt.NoFocus)
self.menu_File.setObjectName("menu_File")
self.menuHelp = QtWidgets.QMenu(self.menuBar)
self.menuHelp.setObjectName("menuHelp")
self.menuTools = QtWidgets.QMenu(self.menuBar)
self.menuTools.setObjectName("menuTools")
self.menuPlot = QtWidgets.QMenu(self.menuBar)
self.menuPlot.setObjectName("menuPlot")
MainWindow.setMenuBar(self.menuBar)
self.actionImport_New = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("document-new")
self.actionImport_New.setIcon(icon)
self.actionImport_New.setMenuRole(QtWidgets.QAction.TextHeuristicRole)
self.actionImport_New.setPriority(QtWidgets.QAction.NormalPriority)
self.actionImport_New.setObjectName("actionImport_New")
self.actionImport_Add = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("add")
self.actionImport_Add.setIcon(icon)
self.actionImport_Add.setObjectName("actionImport_Add")
self.actionExport_For = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("go-right")
self.actionExport_For.setIcon(icon)
self.actionExport_For.setObjectName("actionExport_For")
self.actionQuit = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("exit")
self.actionQuit.setIcon(icon)
self.actionQuit.setObjectName("actionQuit")
self.actionAbout = QtWidgets.QAction(MainWindow)
self.actionAbout.setObjectName("actionAbout")
self.actionRemove = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("remove")
self.actionRemove.setIcon(icon)
self.actionRemove.setObjectName("actionRemove")
self.actionAnalyze = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("applications-accessories")
self.actionAnalyze.setIcon(icon)
self.actionAnalyze.setObjectName("actionAnalyze")
self.actionNew_Plot = QtWidgets.QAction(MainWindow)
self.actionNew_Plot.setObjectName("actionNew_Plot")
self.actionModify_Plot = QtWidgets.QAction(MainWindow)
self.actionModify_Plot.setObjectName("actionModify_Plot")
self.actionRemove_Plot = QtWidgets.QAction(MainWindow)
self.actionRemove_Plot.setObjectName("actionRemove_Plot")
self.actionRedraw = QtWidgets.QAction(MainWindow)
self.actionRedraw.setObjectName("actionRedraw")
self.actionGenerate = QtWidgets.QAction(MainWindow)
icon = QtGui.QIcon.fromTheme("emblem-photos")
self.actionGenerate.setIcon(icon)
self.actionGenerate.setObjectName("actionGenerate")
self.mainToolBar.addAction(self.actionImport_New)
self.mainToolBar.addAction(self.actionImport_Add)
self.mainToolBar.addAction(self.actionRemove)
self.mainToolBar.addAction(self.actionGenerate)
self.mainToolBar.addAction(self.actionAnalyze)
self.mainToolBar.addAction(self.actionExport_For)
self.mainToolBar.addAction(self.actionQuit)
self.menu_File.addAction(self.actionImport_New)
self.menu_File.addAction(self.actionImport_Add)
self.menu_File.addAction(self.actionRemove)
self.menu_File.addAction(self.actionExport_For)
self.menu_File.addSeparator()
self.menu_File.addAction(self.actionQuit)
self.menuHelp.addAction(self.actionAbout)
self.menuPlot.addAction(self.actionRedraw)
self.menuPlot.addSeparator()
self.menuPlot.addAction(self.actionNew_Plot)
self.menuPlot.addAction(self.actionModify_Plot)
self.menuPlot.addAction(self.actionRemove_Plot)
self.menuBar.addAction(self.menu_File.menuAction())
self.menuBar.addAction(self.menuPlot.menuAction())
self.menuBar.addAction(self.menuTools.menuAction())
self.menuBar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "PyParticleProcessor"))
self.datasets_label.setText(_translate("MainWindow", "Datasets"))
self.treeWidget.headerItem().setText(0, _translate("MainWindow", "Selected"))
self.treeWidget.headerItem().setText(1, _translate("MainWindow", "ID"))
self.treeWidget.headerItem().setText(2, _translate("MainWindow", "Name"))
self.properties_label.setText(_translate("MainWindow", "Properties:"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Default Plots"))
self.menu_File.setTitle(_translate("MainWindow", "File"))
self.menuHelp.setTitle(_translate("MainWindow", "Help"))
self.menuTools.setTitle(_translate("MainWindow", "Tools"))
self.menuPlot.setTitle(_translate("MainWindow", "Plot"))
self.actionImport_New.setText(_translate("MainWindow", "Import New..."))
self.actionImport_New.setIconText(_translate("MainWindow", "New..."))
self.actionImport_New.setToolTip(_translate("MainWindow", "New..."))
self.actionImport_Add.setText(_translate("MainWindow", "Import Add..."))
self.actionImport_Add.setIconText(_translate("MainWindow", "Add..."))
self.actionImport_Add.setToolTip(_translate("MainWindow", "Add..."))
self.actionExport_For.setText(_translate("MainWindow", "Export..."))
self.actionExport_For.setIconText(_translate("MainWindow", "Export..."))
self.actionExport_For.setToolTip(_translate("MainWindow", "Export..."))
self.actionQuit.setText(_translate("MainWindow", "Quit"))
self.actionAbout.setText(_translate("MainWindow", "About"))
self.actionRemove.setText(_translate("MainWindow", "Remove"))
self.actionRemove.setToolTip(_translate("MainWindow", "Remove"))
self.actionAnalyze.setText(_translate("MainWindow", "Analyze"))
self.actionAnalyze.setToolTip(_translate("MainWindow", "Analyze"))
self.actionNew_Plot.setText(_translate("MainWindow", "New Plot..."))
self.actionModify_Plot.setText(_translate("MainWindow", "Modify Current Plot..."))
self.actionRemove_Plot.setText(_translate("MainWindow", "Remove Current Plot"))
self.actionRedraw.setText(_translate("MainWindow", "Redraw"))
self.actionGenerate.setText(_translate("MainWindow", "Generate..."))
self.actionGenerate.setIconText(_translate("MainWindow", "Generate..."))
self.actionGenerate.setToolTip(_translate("MainWindow", "Generate distribution"))
from pyqtgraph import PlotWidget
from pyqtgraph.opengl import GLViewWidget
<file_sep>import numpy as np
class ArrayWrapper(object):
def __init__(self, array_like):
if type(array_like) is not np.array:
self._array = np.array(array_like)
else:
self._array = array_like
def __get__(self):
return self
def __getitem__(self, key):
return self._array[key]
def __setitem__(self, key, item):
self._array[key] = item
def __len__(self):
return len(self._array)
@property
def value(self):
return self._array
def append(self, value):
self._array = np.append(self._array, value)<file_sep>from py_particle_processor_qt.py_particle_processor_qt import PyParticleProcessor
ppp = PyParticleProcessor(debug=True)
ppp.run()
<file_sep>from py_particle_processor_qt.py_particle_processor_qt import *
<file_sep>from ..arraywrapper import ArrayWrapper
from ..abstractdriver import AbstractDriver
from dans_pymodules import IonSpecies
import numpy as np
import h5py
class OPALDriver(AbstractDriver):
def __init__(self, debug=False):
super(OPALDriver, self).__init__()
self._debug = debug
self._program_name = "OPAL"
def get_program_name(self):
return self._program_name
def import_data(self, filename, species):
if self._debug:
print("Importing data from program: {}".format(self._program_name))
if h5py.is_hdf5(filename):
if self._debug:
print("Opening h5 file..."),
_datasource = h5py.File(filename, "r+")
if self._debug:
print("Done!")
if "OPAL_version" in _datasource.attrs.keys():
data = {"datasource": _datasource}
if self._debug:
print("Loading dataset from h5 file in OPAL format.")
data["steps"] = len(_datasource.keys())-1
if self._debug:
print("Found {} steps in the file.".format(data["steps"]))
_data = _datasource.get("Step#0")
# for _key in _data.keys():
# print(_key)
#
# for _key in _data.attrs.keys():
# print(_key)
# TODO: OPAL apparently doesn't save the charge per particle, but per macroparticle without frequency,
# TODO: we have no way of telling what the species is! Add manual input. And maybe fix OPAL... -DW
try:
species.calculate_from_energy_mev(_data.attrs["ENERGY"])
except Exception:
pass
data["ion"] = species
data["mass"] = species.a()
data["charge"] = species.q()
data["current"] = None # TODO: Get actual current! -DW
data["particles"] = len(_data.get("x")[()])
return data
elif ".dat" in filename:
if self._debug:
print("Opening OPAL .dat file...")
data = {}
with open(filename, "rb") as infile:
data["particles"] = int(infile.readline().rstrip().lstrip())
data["steps"] = 1
_distribution = []
mydtype = [('x', float), ('xp', float),
('y', float), ('yp', float),
('z', float), ('zp', float)]
for line in infile.readlines():
values = line.strip().split()
_distribution.append(tuple(values))
_distribution = np.array(_distribution, dtype=mydtype)
distribution = {'x': ArrayWrapper(_distribution['x']),
'px': ArrayWrapper(_distribution['xp']),
'y': ArrayWrapper(_distribution['y']),
'py': ArrayWrapper(_distribution['yp']),
'z': ArrayWrapper(_distribution['z']),
'pz': ArrayWrapper(_distribution['zp'])}
# For a single timestep, we just define a Step#0 entry in a dictionary (supports .get())
data["datasource"] = {"Step#0": distribution}
# TODO: OPAL apparently doesn't save the charge per particle, but per macroparticle without frequency,
# TODO: we have no way of telling what the species is! Add manual input. And maybe fix OPAL... -DW
data["current"] = 0.0
return data
return None
def export_data(self, dataset, filename):
datasource = dataset.get_datasource()
nsteps = dataset.get_nsteps()
npart = dataset.get_npart()
if ".h5" in filename:
if self._debug:
print("Exporting data for program: {}...".format(self._program_name))
outfile = h5py.File(filename, "w") # The file dialog will make sure they want to overwrite -PW
m = [dataset.get_ion().mass_mev() for _ in range(npart)]
q = [dataset.get_ion().q() for _ in range(npart)]
id_list = [i for i in range(npart)]
for step in range(nsteps):
step_str = "Step#{}".format(step)
step_grp = outfile.create_group(step_str)
for key in ["<KEY>"]:
step_grp.create_dataset(key, data=datasource[step_str][key])
step_grp.create_dataset("id", data=id_list)
step_grp.create_dataset("mass", data=m)
step_grp.create_dataset("q", data=q)
step_grp.attrs.__setitem__("ENERGY", dataset.get_ion().energy_mev())
outfile.attrs.__setitem__("OPAL_version", b"OPAL 1.9.0")
outfile.close()
if self._debug:
print("Export successful!")
return 0
elif ".dat" in filename:
if self._debug:
print("Exporting data for program: {}...".format(self._program_name))
if nsteps > 1:
print("The .dat format only supports one step! Using the selected step...")
step = dataset.get_current_step()
else:
step = 0
# The file dialog will make sure they want to overwrite -PW
with open(filename, "w") as outfile:
data = datasource["Step#{}".format(step)]
outfile.write(str(npart) + "\n")
for particle in range(npart):
outfile.write(str(data["x"][particle]) + " " +
str(data["px"][particle]) + " " +
str(data["y"][particle]) + " " +
str(data["py"][particle]) + " " +
str(data["z"][particle]) + " " +
str(data["pz"][particle]) + "\n")
if self._debug:
print("Export successful!")
return 0
else:
print("Something went wrong when exporting to: {}".format(self._program_name))
return 1
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tools/ScaleTool/scaletoolgui.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ScaleToolGUI(object):
def setupUi(self, ScaleToolGUI):
ScaleToolGUI.setObjectName("ScaleToolGUI")
ScaleToolGUI.resize(257, 125)
self.centralwidget = QtWidgets.QWidget(ScaleToolGUI)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 254, 122))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label, 0, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.parameter_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.parameter_label.setObjectName("parameter_label")
self.gridLayout.addWidget(self.parameter_label, 0, 0, 1, 1)
self.scaling_factor_label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.scaling_factor_label.setObjectName("scaling_factor_label")
self.gridLayout.addWidget(self.scaling_factor_label, 1, 0, 1, 1)
self.parameter_combo = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.parameter_combo.setObjectName("parameter_combo")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.parameter_combo.addItem("")
self.gridLayout.addWidget(self.parameter_combo, 0, 1, 1, 1)
self.scaling_factor = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.scaling_factor.setText("")
self.scaling_factor.setObjectName("scaling_factor")
self.gridLayout.addWidget(self.scaling_factor, 1, 1, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.cancel_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
self.apply_button = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.apply_button.setDefault(True)
self.apply_button.setObjectName("apply_button")
self.horizontalLayout.addWidget(self.apply_button)
self.verticalLayout.addLayout(self.horizontalLayout)
ScaleToolGUI.setCentralWidget(self.centralwidget)
self.retranslateUi(ScaleToolGUI)
QtCore.QMetaObject.connectSlotsByName(ScaleToolGUI)
def retranslateUi(self, ScaleToolGUI):
_translate = QtCore.QCoreApplication.translate
ScaleToolGUI.setWindowTitle(_translate("ScaleToolGUI", "Scale Tool"))
self.label.setText(_translate("ScaleToolGUI", "Scale Tool"))
self.parameter_label.setText(_translate("ScaleToolGUI", "Parameter(s):"))
self.scaling_factor_label.setText(_translate("ScaleToolGUI", "Scaling Factor:"))
self.parameter_combo.setItemText(0, _translate("ScaleToolGUI", "X, Y, Z"))
self.parameter_combo.setItemText(1, _translate("ScaleToolGUI", "X, Y"))
self.parameter_combo.setItemText(2, _translate("ScaleToolGUI", "X"))
self.parameter_combo.setItemText(3, _translate("ScaleToolGUI", "Y"))
self.parameter_combo.setItemText(4, _translate("ScaleToolGUI", "Z"))
self.parameter_combo.setItemText(5, _translate("ScaleToolGUI", "PX, PY, PZ"))
self.parameter_combo.setItemText(6, _translate("ScaleToolGUI", "PX, PY"))
self.parameter_combo.setItemText(7, _translate("ScaleToolGUI", "PX"))
self.parameter_combo.setItemText(8, _translate("ScaleToolGUI", "PY"))
self.parameter_combo.setItemText(9, _translate("ScaleToolGUI", "PZ"))
self.scaling_factor.setPlaceholderText(_translate("ScaleToolGUI", "1.0"))
self.cancel_button.setText(_translate("ScaleToolGUI", "Cancel"))
self.apply_button.setText(_translate("ScaleToolGUI", "Apply"))
<file_sep>from ..abstract_tool import AbstractTool
from .orbittoolgui import Ui_OrbitToolGUI
from PyQt5 import QtGui
class OrbitTool(AbstractTool):
def __init__(self, parent):
super(OrbitTool, self).__init__(parent)
self._name = "Orbit Tool"
self._parent = parent
# --- Initialize the GUI --- #
self._orbitToolWindow = QtGui.QMainWindow()
self._orbitToolGUI = Ui_OrbitToolGUI()
self._orbitToolGUI.setupUi(self._orbitToolWindow)
self._orbitToolGUI.apply_button.clicked.connect(self.callback_apply)
self._orbitToolGUI.cancel_button.clicked.connect(self.callback_cancel)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = None
self._redraw_on_exit = True
self.values = [None, None, None]
# --- Required Functions --- #
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._orbitToolWindow.width())
_y = 0.5 * (screen_size.height() - self._orbitToolWindow.height())
# --- Show the GUI --- #
self._orbitToolWindow.show()
self._orbitToolWindow.move(_x, _y)
# --- GUI-related Functions --- #
def open_gui(self):
self.run()
def close_gui(self):
self._orbitToolWindow.close()
def callback_apply(self):
if self.apply() == 0:
self._redraw()
self.close_gui()
def callback_cancel(self):
self.close_gui()
# --- Tool-related Functions --- #
def check_step_numbers(self):
step_texts = [self._orbitToolGUI.step_1, self._orbitToolGUI.step_2,
self._orbitToolGUI.step_3]
self.values = [None, None, None]
for i, step in enumerate(step_texts):
s_txt = step.text()
if len(s_txt) == 0:
step.setStyleSheet("color: #000000")
try:
if "." in s_txt:
step.setStyleSheet("color: #FF0000")
else:
self.values[i] = int(s_txt) # Try to convert the input to an int
step.setStyleSheet("color: #000000")
except ValueError:
# Set the text color to red
step.setStyleSheet("color: #FF0000")
def apply(self):
self.check_step_numbers()
if None in self.values:
return 1
for dataset in self._selections:
dataset.xy_orbit(self.values, center=self._orbitToolGUI.center_orbit.isChecked())
return 0
<file_sep>import gi
gi.require_version('Gtk', '3.0') # nopep8
gi.require_version('Gdk', '3.0') # nopep8
# from gi.repository import Gtk, GLib, GObject, Gdk
from dataset import *
__author__ = "<NAME>, <NAME>"
__doc__ = """A GTK+3 based GUI that allows loading particle data from
various simulation codes and exporting them for various other simulation codes.
"""
# Initialize some global constants
amu = const.value("atomic mass constant energy equivalent in MeV")
echarge = const.value("elementary charge")
clight = const.value("speed of light in vacuum")
class PyParticleProcessor(object):
def __init__(self, debug=False):
"""
Initialize the GUI
"""
self._debug = debug
self._colors = MyColors()
# --- Load the GUI from XML file and initialize connections --- #
self._builder = Gtk.Builder()
self._builder.add_from_file("py_particle_processor.glade")
self._builder.connect_signals(self.get_connections())
# --- Get some widgets from the builder --- #
self._main_window = self._builder.get_object("main_window")
self._status_bar = self._builder.get_object("main_statusbar")
self._log_textbuffer = self._builder.get_object("log_texbuffer")
self._datasets_ls = self._builder.get_object("species_ls")
self._datasets_tv = self._builder.get_object("species_tv")
self._base_plots_xy = MPLCanvasWrapper(main_window=self._main_window)
self._base_plots_xxp = MPLCanvasWrapper(main_window=self._main_window)
self._base_plots_yyp = MPLCanvasWrapper(main_window=self._main_window)
self._base_plots_phe = MPLCanvasWrapper(main_window=self._main_window)
self._builder.get_object("alignment2").add(self._base_plots_xxp)
self._builder.get_object("alignment3").add(self._base_plots_yyp)
self._builder.get_object("alignment4").add(self._base_plots_xy)
self._builder.get_object("alignment6").add(self._base_plots_phe)
# --- Create some CellRenderers for the Species TreeView
_i = 0
for item in ["mass_tvc", "charge_tvc", "current_tvc", "np_tvc", "filename_tvc"]:
_i += 1
crt = Gtk.CellRendererText()
self._builder.get_object(item).pack_start(crt, False)
self._builder.get_object(item).add_attribute(crt, "text", _i)
crtog = Gtk.CellRendererToggle()
self._builder.get_object("toggle_tvc").pack_start(crtog, True)
self._builder.get_object("toggle_tvc").add_attribute(crtog, "active", 0)
crtog.connect("toggled", self.cell_toggled, self._datasets_ls, "dat")
self._datasets = []
def about_program_callback(self, menu_item):
"""
:param menu_item:
:return:
"""
if self._debug:
print("About Dialog called by {}".format(menu_item))
dialog = self._builder.get_object("about_dialogbox")
dialog.run()
dialog.destroy()
return 0
def cell_toggled(self, widget, path, model, mode):
"""
Callback function for toggling one of the checkboxes in the species
TreeView. Updates the View and refreshes the plots...
"""
if self._debug:
print("cell_toggled was called with widget {} and mode {}".format(widget, mode))
model[path][0] = not model[path][0]
# TODO: Update some draw variable -DW
return 0
def delete_ds_callback(self, widget):
"""
Callback for Delete Dataset... button
:param widget:
:return:
"""
if self._debug:
print("delete_ds_callback was called with widget {}".format(widget))
path, focus = self._datasets_tv.get_cursor()
del_iter = self._datasets_ls.get_iter(path)
self._datasets[path[0]].close()
self._datasets.pop(path[0])
self._datasets_ls.remove(del_iter)
return 0
def get_connections(self):
"""
This just returns a dictionary of connections
:return:
"""
con = {"main_quit": self.main_quit,
"notebook_page_changed": self.notebook_page_changed_callback,
"on_main_statusbar_text_pushed": self.statusbar_changed_callback,
"about_program_menu_item_activated": self.about_program_callback,
"on_load_dataset_activate": self.load_new_ds_callback,
"on_add_dataset_activate": self.load_add_ds_callback,
"on_delete_dataset_activate": self.delete_ds_callback,
}
return con
def initialize(self):
"""
Do all remaining initializations
:return: 0
"""
if self._debug:
print("Called initialize() function.")
self._status_bar.push(0, "Program Initialized.")
return 0
def load_add_ds_callback(self, widget):
"""
Callback for Add Dataset... button
:param widget:
:return:
"""
if self._debug:
print("load_add_ds_callback was called with widget {}".format(widget))
_fd = FileDialog()
filename = _fd.get_filename(action="open", parent=self._main_window)
print(filename)
if filename is None:
return 0
_new_ds = Dataset(debug=self._debug)
if _new_ds.load_from_file(filename) == 0:
self._datasets.append(_new_ds)
# Update the liststore
self._datasets_ls.append([False,
self._datasets[0].get_a(),
self._datasets[0].get_q(),
self._datasets[0].get_i(),
self._datasets[0].get_npart(),
self._datasets[0].get_filename()]
)
if self._debug:
print("load_add_ds_callback: Finished loading.")
return 0
def load_new_ds_callback(self, widget):
"""
Callback for Load Dataset... button
:param widget:
:return:
"""
if self._debug:
print("load_new_ds_callback was called with widget {}".format(widget))
_fd = FileDialog()
filename = _fd.get_filename(action="open", parent=self._main_window)
print(filename)
if filename is None:
return 0
_new_ds = Dataset(debug=self._debug)
if _new_ds.load_from_file(filename, driver="TraceWin") == 0:
self._datasets = [_new_ds]
# Update the liststore (should be called dataset_ls...)
self._datasets_ls.clear()
self._datasets_ls.append([False,
self._datasets[0].get_a(),
self._datasets[0].get_q(),
self._datasets[0].get_i(),
self._datasets[0].get_npart(),
self._datasets[0].get_filename()]
)
if self._debug:
print("load_new_ds_callback: Finished loading.")
self._base_plots_xy.clear()
self._base_plots_xy.scatter(self._datasets[0].get("x"), self._datasets[0].get("y"),
c=self._colors[0], s=0.5, edgecolor='')
self._base_plots_xy.draw_idle()
self._base_plots_xxp.clear()
self._base_plots_xxp.scatter(self._datasets[0].get("x"), self._datasets[0].get("px"),
c=self._colors[0], s=0.5, edgecolor='')
self._base_plots_xxp.draw_idle()
self._base_plots_yyp.clear()
self._base_plots_yyp.scatter(self._datasets[0].get("y"), self._datasets[0].get("py"),
c=self._colors[0], s=0.5, edgecolor='')
self._base_plots_yyp.draw_idle()
return 0
def main_quit(self, widget):
"""
Shuts down the program (and threads) gracefully.
:return:
"""
if self._debug:
print("Called main_quit for {}".format(widget))
self._main_window.destroy()
Gtk.main_quit()
return 0
def notebook_page_changed_callback(self, notebook, page, page_num):
"""
Callback for when user switches to a different notebook page in the main notebook.
:param notebook: a pointer to the gtk notebook object
:param page: a pointer to the top level child of the page
:param page_num: page number starting at 0
:return:
"""
if self._debug:
print("Debug: Notebook {} changed page to {} (page_num = {})".format(notebook,
page,
page_num))
return 0
def run(self):
"""
Run the GUI
:return:
"""
self.initialize()
# --- Show the GUI --- #
self._main_window.maximize()
self._main_window.show_all()
Gtk.main()
return 0
def statusbar_changed_callback(self, statusbar, context_id, text):
"""
Callback that handles what happens when a message is pushed in the
statusbar
"""
if self._debug:
print("Called statusbar_changed callback for statusbar {}, ID = {}".format(statusbar, context_id))
_timestr = time.strftime("%d %b, %Y, %H:%M:%S: ", time.localtime())
self._log_textbuffer.insert(self._log_textbuffer.get_end_iter(), _timestr + text + "\n")
return 0
if __name__ == "__main__":
mydebug = True
ppp = PyParticleProcessor(debug=mydebug)
ppp.run()
<file_sep>from abc import ABC, abstractmethod
import os
# TODO: WIP -PW
class AbstractDriver(ABC):
def __init__(self):
self._program_name = None
self._debug = None
def get_program_name(self):
return self._program_name
@abstractmethod
def import_data(self, *args, **kwargs):
pass
@abstractmethod
def export_data(self, *args, **kwargs):
pass
# Source: http://fa.bianp.net/blog/2013/
# different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/
@staticmethod
def _memory_usage_ps():
import subprocess
out = subprocess.Popen(['ps', 'v', '-p', str(os.getpid())],
stdout=subprocess.PIPE).communicate()[0].split("\n")
vsz_index = out[0].split().index("RSS")
mem = float(out[1].split()[vsz_index]) / 1024.0
return mem
# Source: https://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
@staticmethod
def _get_file_size(filename):
return os.stat(filename).st_size
def check_memory(self, filename):
current_usage = self._memory_usage_ps()
file_size = self._get_file_size(filename)
if current_usage + file_size > 5e8: # 500 MB
self.convert_to_h5()
else:
return 0
def convert_to_h5(self):
pass
def get_species(self):
pass
<file_sep>from ..abstract_tool import AbstractTool
from .scaletoolgui import Ui_ScaleToolGUI
from PyQt5 import QtGui
class ScaleTool(AbstractTool):
def __init__(self, parent):
super(ScaleTool, self).__init__(parent)
self._name = "Scale Tool"
self._parent = parent
# --- Initialize the GUI --- #
self._scaleToolWindow = QtGui.QMainWindow()
self._scaleToolGUI = Ui_ScaleToolGUI()
self._scaleToolGUI.setupUi(self._scaleToolWindow)
self._scaleToolGUI.apply_button.clicked.connect(self.callback_apply)
self._scaleToolGUI.cancel_button.clicked.connect(self.callback_cancel)
self._scaleToolGUI.scaling_factor.textChanged.connect(self.check_scaling_factor)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = None
self._redraw_on_exit = True
# --- Required Functions --- #
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._scaleToolWindow.width())
_y = 0.5 * (screen_size.height() - self._scaleToolWindow.height())
# --- Show the GUI --- #
self._scaleToolWindow.show()
self._scaleToolWindow.move(_x, _y)
# --- GUI-related Functions --- #
def open_gui(self):
self.run()
def close_gui(self):
self._scaleToolWindow.close()
def callback_apply(self):
if self.apply() == 0:
self._redraw()
self.close_gui()
def callback_cancel(self):
self.close_gui()
# --- Tool-related Functions --- #
def check_scaling_factor(self):
scale_txt = self._scaleToolGUI.scaling_factor.text()
if len(scale_txt) == 0:
self._scaleToolGUI.scaling_factor.setStyleSheet("color: #000000")
return None
try:
value = float(scale_txt) # Try to convert the input to a float
self._scaleToolGUI.scaling_factor.setStyleSheet("color: #000000")
return value
except ValueError:
# Set the text color to red
self._scaleToolGUI.scaling_factor.setStyleSheet("color: #FF0000")
return None
def apply(self):
prop_txt = self._scaleToolGUI.parameter_combo.currentText()
scaling_factor = self.check_scaling_factor()
if scaling_factor is None:
return 1
# Let's do this on a text basis instead of inferring from the indices
properties = [t.rstrip(",").lower() for t in prop_txt.split(" ") if "(" not in t]
for dataset in self._selections:
datasource = dataset.get_datasource()
nsteps, npart = dataset.get_nsteps(), dataset.get_npart()
for step in range(nsteps):
for part in range(npart):
for prop in properties:
datasource["Step#{}".format(step)][prop][part] *= scaling_factor
return 0
<file_sep>import numpy as np
from PyQt5.QtWidgets import QMainWindow
from py_particle_processor_qt.gui.generate_main import Ui_Generate_Main
from py_particle_processor_qt.gui.generate_error import Ui_Generate_Error
from py_particle_processor_qt.gui.generate_envelope import Ui_Generate_Envelope
from py_particle_processor_qt.gui.generate_twiss import Ui_Generate_Twiss
from dans_pymodules import IonSpecies
from py_particle_processor_qt.drivers.TraceWinDriver import *
class GenerateDistribution(object):
"""
A generator for creating various particle distributions.
"""
def __init__(self, numpart, species, energy, z_pos="Zero", z_mom="Zero", rz=0.0, ez=0.0, dev=[1.0, 1.0]):
if isinstance(numpart, str):
numpart = int(numpart)
if isinstance(energy, str):
energy = float(energy)
if isinstance(rz, str):
rz = float(rz)
if ez == "":
ez = 0.0
elif isinstance(ez, str):
ez = float(ez)
stddev = [0, 0]
if dev[0] == "":
stddev[0] = 1.0
else:
stddev[0] = float(dev[0])
if dev[1] == "":
stddev[1] = 1.0
else:
stddev[1] = float(dev[1])
self._numpart = numpart # number of particles
self._species = IonSpecies(species, energy) # instance of IonSpecies
self._data = None # A variable to store the data dictionary
rzp = self._species.v_m_per_s() * 1e-03 # Should this be 1e-03 (original) or 1e03?
# Calculate longitudinal position distribution
z = np.zeros(self._numpart)
if z_pos == "Constant": # Constant z-position
z = np.full(self._numpart, rz)
elif z_pos == "Uniform along length": # Randomly distributed z-position
z = (np.random.random(self._numpart) - 0.5) * rz
elif z_pos == "Uniform on ellipse": # Uniformly randomly distributed within an ellipse
beta = 2 * np.pi * np.random.random(self._numpart)
a = np.ones(self._numpart)
rand_phi = np.random.random(self._numpart)
a_z = a * np.sqrt(rand_phi)
z = a_z * rz * np.cos(beta)
elif z_pos == "Gaussian on ellipse": # Gaussian distribution within an ellipse
rand = np.random.normal(0, stddev[0], self._numpart)
z = rand * rz * .5
elif z_pos == "Waterbag": # Waterbag distribution within an ellipse
beta = 2 * np.pi * np.random.random(self._numpart)
a = np.sqrt(1.5 * np.sqrt(np.random.random(self._numpart)))
rand_phi = np.random.random(self._numpart)
a_z = a * np.sqrt(rand_phi)
z = a_z * rz * np.cos(beta)
elif z_pos == "Parabolic": # Parabolic distribution within an ellipse
beta = 2 * np.pi * np.random.random(self._numpart)
alpha = np.arccos(1.0 - 2 * np.random.random(self._numpart))
a = np.sqrt(1.0 - 2 * np.cos((alpha - 2.0 * np.pi) / 3))
rand_phi = np.random.random(self._numpart)
a_z = a * np.sqrt(rand_phi)
z = a_z * rz * np.cos(beta)
# Calculate longitudinal momentum distribution
zp = np.zeros(self._numpart)
if z_mom == "Constant":
zp = np.full(self._numpart, rzp)
elif z_mom == "Uniform along length":
zp = (np.random.random(self._numpart) - 0.5) * rzp
elif z_mom == "Uniform on ellipse":
beta = 2 * np.pi * np.random.random(self._numpart)
a = np.ones(self._numpart)
rand_phi = np.random.random(self._numpart)
a_z = a * np.sqrt(rand_phi)
zp = a_z * (rzp * np.cos(beta) - (ez / rz) * np.sin(beta))
elif z_mom == "Gaussian on ellipse":
z_rand = np.random.normal(0, stddev[0], self._numpart)
zp_rand = np.random.normal(0, stddev[1], self._numpart)
z_temp = z_rand * rz * .5
zp = (rzp / rz) * z_temp + (ez / (2 * rz)) * zp_rand
self._z = z
self._zp = np.abs(zp)
# Functions for generating x-x', y-y' distributions and returning step 0 of the dataset
def generate_uniform(self, r, rp, e_normalized):
"""
Generates a uniform distribution using the beam envelope's angle and radius.
:param r: envelope radius in the shape of array [rx, ry] (mm)
:param rp: envelope angle in the shape of array [rxp, ryp] (mrad)
:param e_normalized: normalized rms emittance in the shape of array [ex, ey](pi-mm-mrad)
:return:
"""
# Initialize parameters
rx = float(r[0])
rxp = float(rp[0])
ry = float(r[1])
ryp = float(rp[1])
e_normalized = [float(e_normalized[0]), float(e_normalized[1])]
ion = self._species
emittance = np.array(e_normalized) / ion.gamma() / ion.beta() # mm-mrad - non-normalized, rms emittance
# Initialize random variables
a = np.ones(self._numpart)
beta_x = 2 * np.pi * np.random.random(self._numpart)
beta_y = 2 * np.pi * np.random.random(self._numpart)
rand_phi = np.random.random(self._numpart)
# Calculate distribution
a_x = a * np.sqrt(rand_phi)
a_y = a * np.sqrt(1 - rand_phi)
x = a_x * rx * np.cos(beta_x)
xp = a_x * (rxp * np.cos(beta_x) - (emittance[0] / rx) * np.sin(beta_x))
y = a_y * ry * np.cos(beta_y)
yp = a_y * (ryp * np.cos(beta_y) - (emittance[1] / ry) * np.sin(beta_y))
# Correct for z-position
x = x + self._z * xp
y = y + self._z * yp
data = {'Step#0': {'x': ArrayWrapper(0.001 * np.array(x)),
'px': ArrayWrapper(np.array(ion.gamma() * ion.beta() * xp)),
'y': ArrayWrapper(0.001 * np.array(y)),
'py': ArrayWrapper(np.array(ion.gamma() * ion.beta() * yp)),
'z': ArrayWrapper(0.001 * np.array(self._z)),
'pz': ArrayWrapper(np.array(ion.gamma() * ion.beta() * self._zp)),
'id': ArrayWrapper(range(self._numpart + 1)),
'attrs': 0}}
return data
def generate_gaussian(self, r, rp, e_normalized, stddev):
"""
Generates a Gaussian distribution using the beam envelope's angle and radius.
:param r: envelope radius in the shape of array [rx, ry] (mm)
:param rp: envelope angle in the shape of array [rxp, ryp] (mrad)
:param e_normalized: normalized rms emittance in the shape of array [ex, ey](pi-mm-mrad)
:param stddev: standard deviation for all parameters
:return:
"""
# Initialize parameters
r0x = float(r[0])
a0x = float(rp[0])
r0y = float(r[1])
a0y = float(rp[1])
stddev = [float(stddev[0]), float(stddev[1]), float(stddev[2]), float(stddev[3])]
e_normalized = [float(e_normalized[0]), float(e_normalized[1])]
ion = self._species
emittance = np.array(e_normalized) / ion.gamma() / ion.beta() # mm-mrad - non-normalized, rms emittance
# Initialize random variables
x_rand = np.random.normal(0, stddev[0], self._numpart)
y_rand = np.random.normal(0, stddev[2], self._numpart)
xp_rand = np.random.normal(0, stddev[1], self._numpart)
yp_rand = np.random.normal(0, stddev[3], self._numpart)
# Calculate distribution
x = x_rand * r0x * .5
xp = (a0x / r0x) * x + (emittance[0] / (2 * r0x)) * xp_rand
y = y_rand * r0y * .5
yp = (a0y / r0y) * y + (emittance[1] / (2 * r0y)) * yp_rand
# Correct for z-position
x = x + self._z * xp
y = y + self._z * yp
data = {'Step#0': {'x': 0.001 * np.array(x),
'px': np.array(ion.gamma() * ion.beta() * xp),
'y': 0.001 * np.array(y),
'py': np.array(ion.gamma() * ion.beta() * yp),
'z': 0.001 * np.array(self._z),
'pz': np.array(ion.gamma() * ion.beta() * self._zp),
'id': range(self._numpart + 1),
'attrs': 0}}
return data
def generate_waterbag(self, r, rp, e_normalized):
"""
Generates a waterbag distribution using the beam envelope's angle and radius.
:param r: envelope radius in the shape of array [rx, ry] (mm)
:param rp: envelope angle in the shape of array [rxp, ryp] (mrad)
:param e_normalized: normalized rms emittance in the shape of array [ex, ey](pi-mm-mrad)
:return:
"""
# Initialize parameters
rx = float(r[0])
rxp = float(rp[0])
ry = float(r[1])
ryp = float(rp[1])
e_normalized = [float(e_normalized[0]), float(e_normalized[1])]
ion = self._species
emittance = np.array(e_normalized) / ion.gamma() / ion.beta() # mm-mrad - non-normalized, rms emittance
# Initialize random variables
a = np.sqrt(1.5 * np.sqrt(np.random.random(self._numpart)))
beta_x = 2 * np.pi * np.random.random(self._numpart)
beta_y = 2 * np.pi * np.random.random(self._numpart)
rand_phi = np.random.random(self._numpart)
# Calculate distribution
a_x = a * np.sqrt(rand_phi)
a_y = a * np.sqrt(1 - rand_phi)
x = a_x * rx * np.cos(beta_x)
xp = a_x * (rxp * np.cos(beta_x) - (emittance[0] / rx) * np.sin(beta_x))
y = a_y * ry * np.cos(beta_y)
yp = a_y * (ryp * np.cos(beta_y) - (emittance[1] / ry) * np.sin(beta_y))
# Correct for z-position
x = x + self._z * xp
y = y + self._z * yp
data = {'Step#0': {'x': 0.001 * np.array(x),
'px': np.array(ion.gamma() * ion.beta() * xp),
'y': 0.001 * np.array(y),
'py': np.array(ion.gamma() * ion.beta() * yp),
'z': 0.001 * np.array(self._z),
'pz': np.array(ion.gamma() * ion.beta() * self._zp),
'id': range(self._numpart + 1),
'attrs': 0}}
return data
def generate_parabolic(self, r, rp, e_normalized):
"""
Generates a parabolic distribution using the beam envelope's angle and radius.
:param r: envelope radius in the shape of array [rx, ry] (mm)
:param rp: envelope angle in the shape of array [rxp, ryp] (mrad)
:param e_normalized: normalized rms emittance in the shape of array [ex, ey](pi-mm-mrad)
:return:
"""
# Initialize parameters
rx = float(r[0])
rxp = float(rp[0])
ry = float(r[1])
ryp = float(rp[1])
e_normalized = [float(e_normalized[0]), float(e_normalized[1])]
ion = self._species
emittance = np.array(e_normalized) / ion.gamma() / ion.beta() # mm-mrad - non-normalized, rms emittance
# Initialize random variables
alpha = np.arccos(1.0 - 2 * np.random.random(self._numpart))
a = np.sqrt(1.0 - 2 * np.cos((alpha - 2.0 * np.pi) / 3))
beta_x = 2 * np.pi * np.random.random(self._numpart)
beta_y = 2 * np.pi * np.random.random(self._numpart)
rand_phi = np.random.random(self._numpart)
# Calculate distribution
a_x = a * np.sqrt(rand_phi)
a_y = a * np.sqrt(1 - rand_phi)
x = a_x * rx * np.cos(beta_x)
xp = a_x * (rxp * np.cos(beta_x) - (emittance[0] / rx) * np.sin(beta_x))
y = a_y * ry * np.cos(beta_y)
yp = a_y * (ryp * np.cos(beta_y) - (emittance[1] / ry) * np.sin(beta_y))
# Correct for z-position
x = x + self._z * xp
y = y + self._z * yp
data = {'Step#0': {'x': 0.001 * np.array(x),
'px': np.array(ion.gamma() * ion.beta() * xp),
'y': 0.001 * np.array(y),
'py': np.array(ion.gamma() * ion.beta() * yp),
'z': 0.001 * np.array(self._z),
'pz': np.array(ion.gamma() * ion.beta() * self._zp),
'id': range(self._numpart + 1),
'attrs': 0}}
return data
# GUI Management
class GeneratorGUI(object):
def __init__(self, parent):
self._parent = parent
# Initialize GUI
self._generate_main = QMainWindow()
self._generate_mainGUI = Ui_Generate_Main()
self._generate_mainGUI.setupUi(self._generate_main)
self._generate_envelope = QMainWindow()
self._generate_envelopeGUI = Ui_Generate_Envelope()
self._generate_envelopeGUI.setupUi(self._generate_envelope)
self._generate_twiss = QMainWindow()
self._generate_twissGUI = Ui_Generate_Twiss()
self._generate_twissGUI.setupUi(self._generate_twiss)
self._generate_error = QMainWindow()
self._generate_errorGUI = Ui_Generate_Error()
self._generate_errorGUI.setupUi(self._generate_error)
# Connect buttons and signals
self._settings = {}
self.apply_settings_main()
self._generate_mainGUI.buttonBox.accepted.connect(self.callback_ok_main)
self._generate_mainGUI.buttonBox.rejected.connect(self._generate_main.close)
self._generate_envelopeGUI.buttonBox.accepted.connect(self.callback_ok_envelope)
self._generate_envelopeGUI.buttonBox.rejected.connect(self._generate_envelope.close)
self._generate_twissGUI.buttonBox.accepted.connect(self.callback_ok_twiss)
self._generate_twissGUI.buttonBox.rejected.connect(self._generate_twiss.close)
self._generate_errorGUI.buttonBox.accepted.connect(self._generate_error.close)
self._generate_envelopeGUI.zpos.currentIndexChanged.connect(self.change_zpos_envelope)
self._generate_envelopeGUI.zmom.currentIndexChanged.connect(self.change_zmom_envelope)
self._generate_envelopeGUI.xydist.currentIndexChanged.connect(self.change_xy_envelope)
self._generate_twissGUI.zpos.currentIndexChanged.connect(self.change_zpos_twiss)
self._generate_twissGUI.zmom.currentIndexChanged.connect(self.change_zmom_twiss)
self._generate_twissGUI.xydist.currentIndexChanged.connect(self.change_xy_twiss)
self._generate_envelopeGUI.checkBox.stateChanged.connect(self.sym_envelope)
self._generate_twissGUI.checkBox.stateChanged.connect(self.sym_twiss)
self.data = {}
def apply_settings_main(self):
# Number of particles:
self._settings["numpart"] = self._generate_mainGUI.lineEdit.text()
# Species:
info = str(self._generate_mainGUI.comboBox.currentText())
if info == "Proton":
self._settings["species"] = "proton"
elif info == "Electron":
self._settings["species"] = "electron"
elif info == "Dihydrogen cation":
self._settings["species"] = "H2_1+"
elif info == "Alpha particle":
self._settings["species"] = "4He_2+"
# Energy:
self._settings["energy"] = self._generate_mainGUI.energy.text()
# Input parameter type:
self._settings["type"] = str(self._generate_mainGUI.comboBox_2.currentText())
def apply_settings_envelope(self):
# Longitudinal parameters
self._settings["zpos"] = str(self._generate_envelopeGUI.zpos.currentText())
self._settings["zmom"] = str(self._generate_envelopeGUI.zmom.currentText())
self._settings["ze"] = self._generate_envelopeGUI.ze.text()
self._settings["zr"] = self._generate_envelopeGUI.zr.text()
self._settings["zstddev"] = [self._generate_envelopeGUI.zpstddev.text(),
self._generate_envelopeGUI.zmstddev.text()]
# Transverse parameters
self._settings["xydist"] = str(self._generate_envelopeGUI.xydist.currentText())
self._settings["eps"] = [self._generate_envelopeGUI.xe.text(), self._generate_envelopeGUI.ye.text()]
self._settings["r"] = [self._generate_envelopeGUI.xr.text(), self._generate_envelopeGUI.yr.text()]
self._settings["rp"] = [self._generate_envelopeGUI.xrp.text(), self._generate_envelopeGUI.yrp.text()]
self._settings["xystddev"] = [self._generate_envelopeGUI.xstddev.text(),
self._generate_envelopeGUI.xpstddev.text(),
self._generate_envelopeGUI.ystddev.text(),
self._generate_envelopeGUI.ypstddev.text()]
def apply_settings_twiss(self):
# Convert from Twiss to envelope
zp_beta = self._generate_twissGUI.zpb.text()
ze = self._generate_twissGUI.ze.text()
if zp_beta != "" and ze != "":
zp_beta = float(zp_beta)
ze = float(ze)
rz = np.sqrt(zp_beta * ze)
else:
rz = float(self._generate_twissGUI.length.text())
xa = float(self._generate_twissGUI.xa.text())
xb = float(self._generate_twissGUI.xb.text())
xe = float(self._generate_twissGUI.xe.text())
rx = np.sqrt(xb * xe)
rxp = -xa * rx / xb
ya = float(self._generate_twissGUI.ya.text())
yb = float(self._generate_twissGUI.yb.text())
ye = float(self._generate_twissGUI.ye.text())
ry = np.sqrt(yb * ye)
ryp = -ya * ry / yb
# Longitudinal parameters
self._settings["zpos"] = str(self._generate_twissGUI.zpos.currentText())
self._settings["zmom"] = str(self._generate_twissGUI.zmom.currentText())
self._settings["ze"] = ze
self._settings["zr"] = rz
self._settings["zstddev"] = [self._generate_envelopeGUI.zpstddev.text(),
self._generate_envelopeGUI.zmstddev.text()]
# Transverse parameters
self._settings["xydist"] = str(self._generate_twissGUI.xydist.currentText())
self._settings["eps"] = [xe, ye]
self._settings["r"] = [rx, ry]
self._settings["rp"] = [rxp, ryp]
if self._generate_twissGUI.xydist.currentText() == "Gaussian":
self._settings["xystddev"] = [self._generate_twissGUI.xstddev.text(),
self._generate_twissGUI.xpstddev.text(),
self._generate_twissGUI.ystddev.text(),
self._generate_twissGUI.ypstddev.text()]
def callback_ok_main(self):
self.apply_settings_main()
if self._settings["numpart"] == "" or self._settings["energy"] == "":
self.run_error()
else:
# Open either Twiss or Envelope menu
if self._settings["type"] == "Envelope":
self.run_envelope()
elif self._settings["type"] == "Twiss":
self.run_twiss()
self._generate_main.close()
def callback_ok_envelope(self):
self.apply_settings_envelope()
if self._settings["eps"] == ["", ""] or self._settings["r"] == ["", ""] or self._settings["rp"] == ["", ""]:
self.run_error()
else:
if self._settings["zpos"] == "Constant" and self._settings["zmom"] == "Constant":
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"])
elif self._settings["zpos"] == "Gaussian on ellipse" or self._settings["zmom"] == "Gaussian on ellipse":
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"], self._settings["ze"],
self._settings["zstddev"])
else:
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"], self._settings["ze"])
if self._settings["xydist"] == "Uniform":
self.data = g.generate_uniform(self._settings["r"], self._settings["rp"], self._settings["eps"])
elif self._settings["xydist"] == "Gaussian":
self.data = g.generate_gaussian(self._settings["r"], self._settings["rp"], self._settings["eps"],
self._settings["xystddev"])
elif self._settings["xydist"] == "Waterbag":
self.data = g.generate_waterbag(self._settings["r"], self._settings["rp"], self._settings["eps"])
elif self._settings["xydist"] == "Parabolic":
self.data = g.generate_parabolic(self._settings["r"], self._settings["rp"], self._settings["eps"])
self._generate_envelope.close()
self._parent.add_generated_dataset(data=self.data, settings=self._settings)
def callback_ok_twiss(self):
self.apply_settings_twiss()
if self._settings["eps"] == ["", ""] or self._settings["r"] == ["", ""] or self._settings["rp"] == ["", ""]:
self.run_error()
else:
if self._settings["zpos"] == "Constant" and self._settings["zmom"] == "Constant":
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"])
elif self._settings["zpos"] == "Gaussian on ellipse" or self._settings["zmom"] == "Gaussian on ellipse":
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"], self._settings["ze"],
self._settings["zstddev"])
else:
g = GenerateDistribution(self._settings["numpart"], self._settings["species"],
self._settings["energy"], self._settings["zpos"], self._settings["zmom"],
self._settings["zr"], self._settings["ze"])
if self._settings["xydist"] == "Uniform":
self.data = g.generate_uniform(self._settings["r"], self._settings["rp"], self._settings["eps"])
elif self._settings["xydist"] == "Gaussian":
self.data = g.generate_gaussian(self._settings["r"], self._settings["rp"], self._settings["eps"],
self._settings["xystddev"])
elif self._settings["xydist"] == "Waterbag":
self.data = g.generate_waterbag(self._settings["r"], self._settings["rp"], self._settings["eps"])
elif self._settings["xydist"] == "Parabolic":
self.data = g.generate_parabolic(self._settings["r"], self._settings["rp"], self._settings["eps"])
self._generate_twiss.close()
self._parent.add_generated_dataset(data=self.data, settings=self._settings)
def change_zpos_envelope(self):
info = str(self._generate_envelopeGUI.zpos.currentText())
if info != "Constant" and info != "Uniform along length":
self._generate_envelopeGUI.ze.setEnabled(True)
if info == "Gaussian on ellipse":
self._generate_envelopeGUI.zpstddev.setEnabled(True)
else:
self._generate_envelopeGUI.zpstddev.setDisabled(True)
else:
self._generate_envelopeGUI.ze.setDisabled(True)
self._generate_envelopeGUI.zpstddev.setDisabled(True)
def change_zmom_envelope(self):
info = str(self._generate_envelopeGUI.zmom.currentText())
if info != "Constant" and info != "Uniform along length":
self._generate_envelopeGUI.ze.setEnabled(True)
if info == "Gaussian on ellipse":
self._generate_envelopeGUI.zmstddev.setEnabled(True)
else:
self._generate_envelopeGUI.zmstddev.setDisabled(True)
else:
self._generate_envelopeGUI.ze.setDisabled(True)
self._generate_envelopeGUI.zmstddev.setDisabled(True)
def change_xy_envelope(self):
info = str(self._generate_envelopeGUI.xydist.currentText())
if info == "Gaussian":
self._generate_envelopeGUI.xstddev.setEnabled(True)
self._generate_envelopeGUI.xpstddev.setEnabled(True)
self._generate_envelopeGUI.ystddev.setEnabled(True)
self._generate_envelopeGUI.ypstddev.setEnabled(True)
else:
self._generate_envelopeGUI.xstddev.setDisabled(True)
self._generate_envelopeGUI.xpstddev.setDisabled(True)
self._generate_envelopeGUI.ystddev.setDisabled(True)
self._generate_envelopeGUI.ypstddev.setDisabled(True)
def change_zpos_twiss(self):
info = str(self._generate_twissGUI.zpos.currentText())
if info != "Constant" and info != "Uniform along length":
self._generate_twissGUI.ze.setEnabled(True)
self._generate_twissGUI.zpa.setEnabled(True)
self._generate_twissGUI.zpb.setEnabled(True)
self._generate_twissGUI.length.setDisabled(True)
if info == "Gaussian on ellipse":
self._generate_twissGUI.zpstddev.setEnabled(True)
else:
self._generate_twissGUI.zpstddev.setDisabled(True)
else:
self._generate_twissGUI.ze.setDisabled(True)
self._generate_twissGUI.zpa.setDisabled(True)
self._generate_twissGUI.zpb.setDisabled(True)
self._generate_twissGUI.length.setEnabled(True)
self._generate_twissGUI.zpstddev.setDisabled(True)
def change_zmom_twiss(self):
info = str(self._generate_twissGUI.zmom.currentText())
if info != "Constant" and info != "Uniform along length":
self._generate_twissGUI.ze.setEnabled(True)
if info == "Gaussian on ellipse":
self._generate_twissGUI.zmstddev.setEnabled(True)
else:
self._generate_twissGUI.zmstddev.setDisabled(True)
else:
self._generate_twissGUI.ze.setDisabled(True)
self._generate_twissGUI.zmstddev.setDisabled(True)
def change_xy_twiss(self):
info = str(self._generate_twissGUI.xydist.currentText())
if info == "Gaussian":
self._generate_twissGUI.xstddev.setEnabled(True)
self._generate_twissGUI.xpstddev.setEnabled(True)
self._generate_twissGUI.ystddev.setEnabled(True)
self._generate_twissGUI.ypstddev.setEnabled(True)
else:
self._generate_twissGUI.xstddev.setDisabled(True)
self._generate_twissGUI.xpstddev.setDisabled(True)
self._generate_twissGUI.ystddev.setDisabled(True)
self._generate_twissGUI.ypstddev.setDisabled(True)
def sym_envelope(self):
info = self._generate_envelopeGUI.checkBox.isChecked()
if info:
self.apply_settings_envelope()
self._generate_envelopeGUI.yr.setText(self._settings["r"][0])
self._generate_envelopeGUI.yrp.setText(self._settings["rp"][0])
self._generate_envelopeGUI.ye.setText(self._settings["eps"][0])
else:
self._generate_envelopeGUI.yr.setText("")
self._generate_envelopeGUI.yrp.setText("")
self._generate_envelopeGUI.ye.setText("")
def sym_twiss(self):
info = self._generate_twissGUI.checkBox.isChecked()
if info:
xa = self._generate_twissGUI.xa.text()
self._generate_twissGUI.ya.setText(xa)
xb = self._generate_twissGUI.xb.text()
self._generate_twissGUI.yb.setText(xb)
xe = self._generate_twissGUI.xe.text()
self._generate_twissGUI.ye.setText(xe)
else:
self._generate_twissGUI.ya.setText("")
self._generate_twissGUI.yb.setText("")
self._generate_twissGUI.ye.setText("")
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._generate_main.width())
_y = 0.5 * (screen_size.height() - self._generate_main.height())
# --- Show the GUI --- #
self._generate_main.show()
self._generate_main.move(_x, _y)
def run_error(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._generate_error.width())
_y = 0.5 * (screen_size.height() - self._generate_error.height())
# --- Show the GUI --- #
self._generate_error.show()
self._generate_error.move(_x, _y)
def run_envelope(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._generate_envelope.width())
_y = 0.5 * (screen_size.height() - self._generate_envelope.height())
# --- Show the GUI --- #
self._generate_envelope.show()
self._generate_envelope.move(_x, _y)
def run_twiss(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._generate_twiss.width())
_y = 0.5 * (screen_size.height() - self._generate_twiss.height())
# --- Show the GUI --- #
self._generate_twiss.show()
self._generate_twiss.move(_x, _y)<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'collimOPALgui.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CollimOPAL(object):
def setupUi(self, CollimOPAL):
CollimOPAL.setObjectName("CollimOPAL")
CollimOPAL.resize(421, 340)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(CollimOPAL.sizePolicy().hasHeightForWidth())
CollimOPAL.setSizePolicy(sizePolicy)
CollimOPAL.setAutoFillBackground(False)
self.centralwidget = QtWidgets.QWidget(CollimOPAL)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 3, 401, 358))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMaximumSize(QtCore.QSize(16777215, 200))
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label_7 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_7.setObjectName("label_7")
self.gridLayout.addWidget(self.label_7, 6, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.gap = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.gap.setObjectName("gap")
self.gridLayout.addWidget(self.gap, 4, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_6 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_6.setObjectName("label_6")
self.gridLayout.addWidget(self.label_6, 4, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.step = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.step.setObjectName("step")
self.gridLayout.addWidget(self.step, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.w = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.w.setObjectName("w")
self.gridLayout.addWidget(self.w, 6, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.hl = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.hl.setObjectName("hl")
self.gridLayout.addWidget(self.hl, 5, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_8 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_8.setObjectName("label_8")
self.gridLayout.addWidget(self.label_8, 5, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.num = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.num.setObjectName("num")
self.gridLayout.addWidget(self.num, 0, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 1, 0, 1, 1, QtCore.Qt.AlignHCenter)
self.nseg = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.nseg.setObjectName("nseg")
self.gridLayout.addWidget(self.nseg, 1, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.verticalLayout_3.addLayout(self.gridLayout)
self.textBrowser = QtWidgets.QTextBrowser(self.verticalLayoutWidget)
self.textBrowser.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.textBrowser.setObjectName("textBrowser")
self.verticalLayout_3.addWidget(self.textBrowser)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setLayoutDirection(QtCore.Qt.LeftToRight)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Close|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setCenterButtons(False)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox, 0, QtCore.Qt.AlignRight)
spacerItem = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayout_3.addItem(spacerItem)
CollimOPAL.setCentralWidget(self.centralwidget)
self.retranslateUi(CollimOPAL)
QtCore.QMetaObject.connectSlotsByName(CollimOPAL)
def retranslateUi(self, CollimOPAL):
_translate = QtCore.QCoreApplication.translate
CollimOPAL.setWindowTitle(_translate("CollimOPAL", "Generating Collimator"))
self.label.setText(_translate("CollimOPAL", "<html><head/><body><p>Generate collimator code for OPAL-cycl.</p><p>The collimator will be perpendicular to the average momentum at the given step.</p></body></html>"))
self.label_7.setText(_translate("CollimOPAL", "Collimator Width (mm):"))
self.label_6.setText(_translate("CollimOPAL", "Gap Half-width (mm):"))
self.label_8.setText(_translate("CollimOPAL", "Collimator Half-length (mm):"))
self.label_2.setText(_translate("CollimOPAL", "Step Number:"))
self.label_3.setText(_translate("CollimOPAL", "Label Number:"))
self.label_4.setText(_translate("CollimOPAL", "Number of Segments:"))
self.textBrowser.setHtml(_translate("CollimOPAL", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))
<file_sep>from ..abstract_tool import AbstractTool
from .translatetoolgui import Ui_TranslateToolGUI
from PyQt5 import QtGui
class TranslateTool(AbstractTool):
def __init__(self, parent):
super(TranslateTool, self).__init__(parent)
self._name = "Translate Tool"
self._parent = parent
# --- Initialize the GUI --- #
self._translateToolWindow = QtGui.QMainWindow()
self._translateToolGUI = Ui_TranslateToolGUI()
self._translateToolGUI.setupUi(self._translateToolWindow)
self._translateToolGUI.apply_button.clicked.connect(self.callback_apply)
self._translateToolGUI.cancel_button.clicked.connect(self.callback_cancel)
self._translateToolGUI.x_trans.textChanged.connect(self.check_inputs)
self._translateToolGUI.y_trans.textChanged.connect(self.check_inputs)
self._translateToolGUI.z_trans.textChanged.connect(self.check_inputs)
self._has_gui = True
self._need_selection = True
self._min_selections = 1
self._max_selections = None
self._redraw_on_exit = True
self._invalid_input = False
# --- Required Functions --- #
def run(self):
# --- Calculate the positions to center the window --- #
screen_size = self._parent.screen_size()
_x = 0.5 * (screen_size.width() - self._translateToolWindow.width())
_y = 0.5 * (screen_size.height() - self._translateToolWindow.height())
# --- Show the GUI --- #
self._translateToolWindow.show()
self._translateToolWindow.move(_x, _y)
# --- GUI-related Functions --- #
def open_gui(self):
self.run()
def close_gui(self):
self._translateToolWindow.close()
def callback_apply(self):
if self.apply() == 0:
self._redraw()
self.close_gui()
def callback_cancel(self):
self.close_gui()
# --- Tool-related Functions --- #
def check_inputs(self):
inputs = [self._translateToolGUI.x_trans, self._translateToolGUI.y_trans, self._translateToolGUI.z_trans]
self._invalid_input = False
for input_item in inputs:
translate_txt = input_item.text()
if len(translate_txt) == 0:
input_item.setStyleSheet("color: #000000")
self._invalid_input = True
try:
float(translate_txt) # Try to convert the input to a float
input_item.setStyleSheet("color: #000000")
except ValueError:
# Set the text color to red
input_item.setStyleSheet("color: #FF0000")
self._invalid_input = True
return 0
def apply(self):
dx, dy, dz = (self._translateToolGUI.x_trans.text(),
self._translateToolGUI.y_trans.text(),
self._translateToolGUI.z_trans.text())
self.check_inputs()
if self._invalid_input:
return 1
# Let's do this on a text basis instead of inferring from the indices
translations = [float(item) for item in [dx, dy, dz]]
for dataset in self._selections:
datasource = dataset.get_datasource()
nsteps, npart = dataset.get_nsteps(), dataset.get_npart()
for step in range(nsteps):
for part in range(npart):
for i, direction in enumerate(["x", "y", "z"]):
datasource["Step#{}".format(step)][direction][part] += translations[i]
return 0
<file_sep>from py_particle_processor_qt.drivers.OPALDriver.OPALDriver import *
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'generate_error.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Generate_Error(object):
def setupUi(self, Generate_Error):
Generate_Error.setObjectName("Generate_Error")
Generate_Error.resize(291, 153)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Generate_Error.sizePolicy().hasHeightForWidth())
Generate_Error.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(Generate_Error)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 30, 291, 111))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_3.setSpacing(0)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.verticalLayoutWidget)
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label, 0, QtCore.Qt.AlignHCenter)
self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.verticalLayout_3.addWidget(self.buttonBox, 0, QtCore.Qt.AlignHCenter)
self.dataset_label = QtWidgets.QLabel(self.centralwidget)
self.dataset_label.setGeometry(QtCore.QRect(50, -40, 201, 107))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dataset_label.sizePolicy().hasHeightForWidth())
self.dataset_label.setSizePolicy(sizePolicy)
self.dataset_label.setAlignment(QtCore.Qt.AlignCenter)
self.dataset_label.setObjectName("dataset_label")
Generate_Error.setCentralWidget(self.centralwidget)
self.retranslateUi(Generate_Error)
QtCore.QMetaObject.connectSlotsByName(Generate_Error)
def retranslateUi(self, Generate_Error):
_translate = QtCore.QCoreApplication.translate
Generate_Error.setWindowTitle(_translate("Generate_Error", "Error"))
self.label.setText(_translate("Generate_Error", "Please fill out all fields available."))
self.dataset_label.setText(_translate("Generate_Error", "Parameter(s) Not Entered!"))
<file_sep>from setuptools import setup, find_packages
setup(name='py_particle_processor',
version='0.1.3',
description='a GUI application to generate or load and export particle data for beam physics',
url='https://github.com/DanielWinklehner/py_particle_processor',
author='<NAME>, <NAME>, <NAME>',
author_email='<EMAIL>',
license='MIT',
packages=find_packages(),
package_data={'': ['mainwindow.py', 'propertieswindow.py']},
include_package_data=True,
zip_safe=False)
| beccbcc14f9e570390508e82ddb2d5c3f2549e0c | [
"Markdown",
"Python",
"Text"
] | 63 | Python | DanielWinklehner/py_particle_processor | 80bbd98d11291bc34609a4abb6c1927203459731 | e9e10817dfac9a7540c330c4a5580d658d5bdee9 |
refs/heads/main | <repo_name>Abednego97/mysite<file_sep>/README.md
# mysite
Tutorial website
| b7517a51ba56840cfe25b96ed9e630666b75f307 | [
"Markdown"
] | 1 | Markdown | Abednego97/mysite | 9b2883ded5f67b3d9280997e5e34be35a25143db | 74a1a3e234867776bd721b3b3081f7a284888359 |
refs/heads/master | <repo_name>jamesbloomer/flashfreeze<file_sep>/README.md
# flashfreeze
Easy background backup and version control for your files.
Designed for anyone working on files and wanting incremental background backups eg. writers. Hopefully (eventually) usable by non-technical users.
Flashfreeze adds, commits and pushes the entire contents of a directory to git at a given interval.
Inspired by [Flashbake](https://github.com/commandline/flashbake).
## Install
```
npm install flashfreeze
```
## Usage
```
node flashfreeze -f [directory to backup] -i [interval in minutes]
```
The commit message is read from a file ```status.txt``` in the directory to backup. If the file does not exist then a fixed commit message is used.
## TODO
- Install and setup guide for non-technical users
- Plugins
See [issues](https://github.com/jamesbloomer/flashfreeze/issues) for full list.
## LICENCE
(The MIT License)
Copyright (c) 2012 <NAME> <https://github.com/jamesbloomer>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>/lib/flashfreeze.js
var async = require('async'),
child_process = require('child_process'),
fs = require('fs'),
util = require('util'),
winston = require('winston');
var flashfreeze = {};
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, { colorize: true, timestamp: true });
flashfreeze.start = function(folder, interval) {
winston.info('will commit folder ' + folder + ' every ' + interval + ' minutes');
try {
process.chdir(folder);
} catch (chdirerr) {
winston.error('Not a valid directory');
process.exit(0);
}
flashfreeze.checkFolder(folder, function(err) {
if(err) {
winston.error('Not a valid directory');
process.exit(0);
}
setInterval(flashfreeze.commit, interval * 60 * 1000);
});
};
flashfreeze.checkFolder = function(folder, done) {
child_process.exec('git status', done);
};
flashfreeze.didCommitFailBecauseThereIsNothingToCommit = function(stdout) {
return stdout.indexOf('nothing to commit') != -1;
};
flashfreeze.getStatus = function(done) {
var status = 'commit by flashfreeze';
fs.exists('status.txt', function(exists) {
if(exists) {
try {
status = fs.readFileSync('status.txt', 'utf8');
} catch(error) {
winston.error('could not read status file, using "commit by flashfreeze" as commit message', { error: error });
}
}
return done(status);
});
};
flashfreeze.commit = function(folder) {
winston.info('committing changes...');
async.series([
function(callback){
child_process.exec('git add -A', callback);
},
function(callback){
flashfreeze.getStatus(function(status) {
var cmd = util.format('git commit -m "%s"', status);
child_process.exec(cmd, function(error, stdout, stderr) {
if(error) {
if(!flashfreeze.didCommitFailBecauseThereIsNothingToCommit(stdout)) {
winston.error(stdout);
winston.error(stderr);
callback(error);
}
}
callback();
});
});
},
function(callback){
child_process.exec('git push origin master', callback);
}
],
function(err, results){
if(err) {
winston.error('error committing changes');
}
winston.info('...finished committing changes');
});
};
module.exports = flashfreeze;<file_sep>/test/flashfreeze_test.js
var async = require('async'),
assert = require('assert'),
child_process = require('child_process'),
flashfreeze = require('../lib/flashfreeze.js'),
fs = require('fs'),
mocha = require('mocha'),
sinon = require('sinon'),
winston = require('winston');
describe('flashfreeze', function() {
beforeEach(function(){
sinon.stub(winston, 'error');
sinon.stub(winston, 'info');
});
afterEach(function(){
winston.error.restore();
winston.info.restore();
});
describe('#start()', function() {
var clock;
var git;
beforeEach(function(){
sinon.stub(flashfreeze, 'commit');
clock = sinon.useFakeTimers();
});
afterEach(function(){
flashfreeze.commit.restore();
clock.restore();
});
describe('with a valid folder', function() {
beforeEach(function(){
sinon.stub(process, 'chdir').returns();
sinon.stub(flashfreeze, 'checkFolder').yields();
flashfreeze.start('FOLDER', 1);
});
afterEach(function(){
process.chdir.restore();
flashfreeze.checkFolder.restore();
});
it('should call commit once timer has elapsed', function(done) {
clock.tick(60 * 1000);
assert(flashfreeze.commit.calledOnce);
done();
});
it('should change directory to folder', function(done) {
assert(process.chdir.calledOnce);
assert(process.chdir.calledWith('FOLDER'));
done();
});
});
describe('with an invalid folder', function() {
beforeEach(function(){
sinon.stub(process, 'chdir').throws('ERROR');
sinon.stub(flashfreeze, 'checkFolder').yields();
sinon.stub(process, 'exit').returns();
flashfreeze.start('FOLDER', 1);
});
afterEach(function(){
process.chdir.restore();
flashfreeze.checkFolder.restore();
process.exit.restore();
});
it('should exit process', function() {
assert(process.exit.calledOnce);
});
});
describe('with a folder that is not a git directory', function() {
beforeEach(function(){
sinon.stub(process, 'chdir').returns();
sinon.stub(flashfreeze, 'checkFolder').yields('ERROR');
sinon.stub(process, 'exit').returns();
flashfreeze.start('FOLDER', 1);
});
afterEach(function(){
process.chdir.restore();
flashfreeze.checkFolder.restore();
process.exit.restore();
});
it('should exit process', function() {
assert(process.exit.calledOnce);
});
});
});
describe('#checkFolder()', function() {
describe('with a folder that is a git directory', function() {
beforeEach(function() {
sinon.stub(child_process, 'exec').yields();
});
afterEach(function() {
child_process.exec.restore();
});
it('should not throw', function(done) {
flashfreeze.checkFolder('GITFOLDER', function(err) {
assert(!err);
done();
});
});
});
describe('with a folder that is not a git directory', function() {
beforeEach(function() {
sinon.stub(child_process, 'exec').yields('ERROR');
});
afterEach(function() {
child_process.exec.restore();
});
it('should throw an error', function() {
flashfreeze.checkFolder('NOTAGITFOLDER', function(err) {
assert.equal(err, 'ERROR');
});
});
});
});
describe('#commit()', function() {
describe('when successful', function() {
var git;
beforeEach(function(){
sinon.stub(child_process, 'exec').yields();
sinon.stub(flashfreeze, 'getStatus').yields('STATUS');
flashfreeze.commit('FOLDER');
});
afterEach(function(){
child_process.exec.restore();
flashfreeze.getStatus.restore();
});
it('should call child_process exec 3 times', function(done) {
assert(child_process.exec.calledThrice);
done();
});
it('should call git add -A first', function(done) {
assert(child_process.exec.getCall(0).calledWith('git add -A'));
done();
});
it('should call git commit second', function(done) {
assert(child_process.exec.getCall(1).calledWith('git commit -m "STATUS"'));
done();
});
it('should call git push third', function(done) {
assert(child_process.exec.getCall(2).calledWith('git push origin master'));
done();
});
});
describe('when errors', function() {
beforeEach(function(){
sinon.stub(process, 'exit').returns();
sinon.stub(child_process, 'exec').yields('ERROR');
flashfreeze.commit('FOLDER');
});
afterEach(function(){
process.exit.restore();
child_process.exec.restore();
});
it('should not exit the process', function(done) {
assert(!process.exit.called);
done();
});
});
});
describe('#didCommitFailBecauseThereIsNothingToCommit()', function() {
it('when there is nothing to commit should return true', function() {
assert(flashfreeze.didCommitFailBecauseThereIsNothingToCommit('nothing to commit'));
});
it('when there is something to commit should return false', function() {
assert(!flashfreeze.didCommitFailBecauseThereIsNothingToCommit('Error'));
});
});
describe('#getStatus()', function() {
describe('when status file does not exist', function() {
beforeEach(function() {
sinon.stub(fs, 'exists').yields(false);
});
afterEach(function() {
fs.exists.restore();
});
it('should return fixed status', function(done) {
flashfreeze.getStatus(function(status) {
assert.equal('commit by flashfreeze', status);
done();
});
});
});
describe('when status file exists should return contents', function() {
beforeEach(function() {
sinon.stub(fs, 'exists').yields(true);
sinon.stub(fs, 'readFileSync').returns('STATUS');
});
afterEach(function() {
fs.exists.restore();
fs.readFileSync.restore();
});
it('should return fixed status', function(done) {
flashfreeze.getStatus(function(status) {
assert.equal('STATUS', status);
done();
});
});
});
describe('when status file exists but read throws should return fixed message and log', function() {
beforeEach(function() {
sinon.stub(fs, 'exists').yields(true);
sinon.stub(fs, 'readFileSync').throws('ERROR');
});
afterEach(function() {
fs.exists.restore();
fs.readFileSync.restore();
});
it('should return fixed status', function(done) {
flashfreeze.getStatus(function(status) {
assert.equal('commit by flashfreeze', status);
assert(winston.error.calledOnce);
done();
});
});
});
});
});<file_sep>/flashfreeze.js
var program = require('commander'),
flashfreeze = require('./lib/flashfreeze.js');
program
.version('0.0.1')
.option('-f, --folder <folder>', 'Folder to commit')
.option('-i, --interval <interval>', 'Interval at which to commit in minutes [15]', Number, 15)
.parse(process.argv);
// Can commander do this for free?
if(!program.folder) {
console.log('Must provide a folder');
process.exit(0);
}
flashfreeze.start(program.folder, program.interval);
| a19a6bd6e1469b2d82f8f4670575e33bd693385e | [
"Markdown",
"JavaScript"
] | 4 | Markdown | jamesbloomer/flashfreeze | 1f24732625239bad22240570809ec663e7ab24cf | 637f800c2a71ceef62878926f7a80b4c07f8b9a2 |
refs/heads/master | <repo_name>DougHigashi/sosmob<file_sep>/pilha.cpp
#include <stdio.h>
#include <stdlib.h>
void inicPilha(struct pilha *pPilha);
void empilha(struct pilha *pPilha, int num);
void desempilha(struct pilha *pPilha);
void exibirPilha(struct pilha *pPilha);
struct pilha{
int topo;
int nums[];
};
struct pilha minhaPilha;
struct pilha *pp = &minhaPilha;
main(){
inicPilha(pp);
empilha(pp, 5);
empilha(pp, 1);
empilha(pp, 2);
empilha(pp, 10);//10 é o topo da pilha
exibirPilha(pp);
printf("\n");
desempilha(pp);//retiro o 10 do topo. Agora o 2 e o topo
exibirPilha(pp);
printf("\n");
empilha(pp, 99);//coloco 99 no topo da pilha
exibirPilha(pp);
}
void inicPilha(struct pilha *pPilha){
pPilha->topo = -1;
}
void empilha(struct pilha *pPilha, int num){
pPilha->topo++;
pPilha->nums[pPilha->topo] = num;
}
void desempilha(struct pilha *pPilha){
int aux = pPilha->nums[pPilha->topo];
pPilha->topo--;
printf("Numero %d desempilhado\n", aux);
}
void exibirPilha(struct pilha *pPilha){
for(int i = pPilha->topo; i > -1 ; i--){
if(i == pPilha->topo){
printf("%d - Topo\n", pPilha->nums[pPilha->topo]);
}else{
printf("%d\n", pPilha->nums[i]);
}
}
}
<file_sep>/README.MD
## Estrutura de dados - Pilha
Repositório de exemplo da turma de Sistemas Operacionais Abertos e Mobile.
O projeto em questão se trata de uma estrutura de dados, chamada pilha.
A pilha que foi desenvolvida pode armazenar dados do tipo inteiro.
Para armazenar os dados, podemos rodar os métodos:
```
empilha()
desempilha()
```
Lembrando apenas de incializar a pilha com o método:
```
inicPilha()
```
É possível ver os itens empilhados usando o método:
```
exibirPilha()
```
| d1d378936546f7a8e116bc830dd0f8060cc88df1 | [
"Markdown",
"C++"
] | 2 | C++ | DougHigashi/sosmob | 8da4ac00cae5066e7eda0c3de28dd789aebdd3cd | d72a0d0445822d987d159ba6062c1e2b50f49347 |
refs/heads/master | <repo_name>Sinabro-DSM/Yally-front-end<file_sep>/yally/webpack.config.ts
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
module.exports = {
entry: ["@babel/polyfill", __dirname + "/src/index.tsx"],
output: {
path: __dirname + "/dist",
publicPath: "/",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(ts|tsx)$/,
loader: "ts-loader"
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/,
use: [
{
loader: "url-loader",
options: {
name: "[name].[ext]?[hash]",
publicPath: "/dist",
limit: 20000
}
}
]
},
{
test: /\.mp3$/,
loader: "file-loader",
options: {
publicPath: "./dist/",
name: "[name].[ext]?[hash]"
}
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx", ".ts", ".tsx"],
alias: {
"react-dom": "@hot-loader/react-dom",
"Assets": path.resolve(__dirname, "src/assets/"),
"Container": path.resolve(__dirname, "src/container/"),
"Pages": path.resolve(__dirname, "src/pages/"),
"Components": path.resolve(__dirname, "src/components/"),
"Store": path.resolve(__dirname, "src/store/")
}
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html",
showErrors: true
}),
new MiniCssExtractPlugin({
template: "[name].css",
chunkFilename: "[id].css"
})
],
devtool: "inline-source-map",
devServer: {
historyApiFallback: true
}
};
<file_sep>/yally/src/pages/index.ts
import AccountSetting from "./AccountSetting";
import Listen from "./Listen";
import Login from "./Login";
import Main from "./Main";
import PasswordReset from "./PasswordReset";
import PostDetail from "./PostDetail";
import Search from "./Search";
import SignUp from "./SignUp";
import UserPage from "./UserPage";
export {
AccountSetting,
Listen,
Login,
Main,
PasswordReset,
PostDetail,
Search,
SignUp,
UserPage
};
<file_sep>/yally/public/style/index.ts
import styled from "styled-components";
interface Props {
underBarWidth: string;
buttonWidth: string;
isActivated: boolean;
}
export const TextDefaultColor = "#707070";
export const TextHighlightColor = "#6665E7";
export const TextErrorColor = "#dd1160";
export const TextRecColor = "#d13f3f";
export const AccountDisabledColor = "#d1d1d1";
export const MainBackgroundColor = "#FDFDFD";
export const MainButtonDefaultColor = "#6665e7";
export const MainButtonHoverColor = "#333393";
export const AccountButton = styled.button<Props>`
width: 360px;
height: 60px;
opacity: 0.69;
background-image: ${props =>
props.isActivated && "linear-gradient(to right, #4776e6, #8e54e9 99%)"};
background-color: ${props => !props.isActivated && AccountDisabledColor};
`;
export const AccountInput = styled.input`
width: 392px;
padding: 12px 4px;
font-size: 24px;
font-weight: 300;
color: ${TextDefaultColor};
`;
export const BackgroundImg = styled.img`
position: absolute;
bottom: 0;
`;
export const ExplainText = styled.p`
font-size: 24px;
font-weight: 300;
color: ${TextDefaultColor};
`;
export const MainButton = styled.button<Props>`
width: ${props => props.buttonWidth};
background-color: ${MainButtonDefaultColor};
opacity: ${props => props.isActivated && 0.3};
height: 48px;
border-radius: 23px;
color: white;
& hover {
background-color: ${MainButtonHoverColor};
}
`;
export const TitleUnderbar = styled.div<Props>`
width: ${props => props.underBarWidth};
height: 8px;
opacity: 0.8;
background-image: linear-gradient(to right, #4776e6, #8e54e9 99%);
`;
export const TitleText = styled.p<Props>`
font-family: "Mont-DEMO";
font-size: 60px;
font-weight: 900;
color: ${TextDefaultColor};
`;
export const WrongMessage = styled.p<Props>`
visibility: ${props => props.isActivated && "hidden"};
font-size: 15px;
font-weight: 300;
text-align: right;
color: ${TextErrorColor};
`;
<file_sep>/yally/src/assets/index.ts
import background from "./public/background.png";
export { background };
| 3bb7e83cbbc72cd5df16afdcd771da442621f4d9 | [
"TypeScript"
] | 4 | TypeScript | Sinabro-DSM/Yally-front-end | 0384d8c2cb6d29e87919b3effe8814e1c40c035f | 00e99dc12831194de3a556fde156aa9de585487f |
refs/heads/master | <file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_ITNTWRAP_CPP__
#define __ITX_ITNTWRAP_CPP__
#endif
#include "tntsql.h"
#include <sql.h>
#include "itannitc.h"
#include "itannit.h"
#include "iregtp.h"
ITannit itannit;
itxTP itxtp;
itxSQLConnection isqlconn;
////////////////////////////////////////////////
//BEGIN Interfaccia C alla classe ITannit
// Attiva l'oggetto ITAnnit in modo che interfacci la struttura dati portante di Tannit
bool ITannit_Create(PTannitQueryResult* qres, int* count)
{
// IConversation_Set();
if (itannit.Get() == NULL)
{
itannit.Init(qres, count);
return TRUE;
}
else
{
return FALSE;
}
}
#ifdef _ITX_APPC
// Attiva l'oggetto itxTP che contiene le informazioni relative ai TP da usare
bool ITannit_RegisterTP(char* filename)
{
return itxtp.Load(filename);
}
// Attiva l'oggetto ITAnnit in modo che interfacci la struttura dati portante di Tannit
bool ITannit_CreateEnv(PTannitQueryResult* qres, int* count, char* llu, char* rtp)
{
IConversation_SetEnv(llu, rtp);
if (itannit.Get() == NULL)
{
itannit.Init(qres, count);
return TRUE;
}
else
{
return FALSE;
}
}
#endif
// Disattiva l'oggetto ITAnnit
void ITannit_Destroy()
{
#ifdef _ITX_APPC
IConversation_Reset();
#endif
itannit.Init(NULL, NULL);
}
int ITannit_StoreToken(PTannitQueryResult qres, char* token, int field_num)
{
return itannit.StoreField(qres, token, field_num);
}
int ITannit_StoreValue(PTannitQueryResult qres, char* field, char* value)
{
int field_num = 0;
if (qres->current_record == NULL)
{
if (!itannit.AllocateNewRecord(qres))
return 0;
qres->totalRows++;
qres->rowsToStore++;
qres->startingRow = STARTING_ROW;
}
if ((field_num = itannit.GetColPos(qres, field)) > 0)
return itannit.StoreField(qres, value, field_num - 1);
return 0;
}
int ITannit_StoreRecord(char* name, ...)
{
PTannitQueryResult qres;
va_list fieldlist;
char* token;
int field_count = 0;
va_start(fieldlist, name);
if ( (qres = ITannit_DBStructure(name)) == NULL )
return ITXFAILED;
while ((token = va_arg(fieldlist, char*)) != NULL)
{
if (field_count < qres->colsNumber)
{
if ((field_count = ITannit_StoreToken(qres, token, field_count)) == ITXFAILED)
{
ITannit_RemoveCurrentRec(qres);
return ITXFAILED;
}
}
}
while (field_count < qres->colsNumber)
{
if ((field_count = ITannit_StoreToken(qres, "", field_count)) == ITXFAILED)
{
ITannit_RemoveCurrentRec(qres);
return ITXFAILED;
}
}
if (!ITannit_CheckCurrentRec(field_count))
{
ITannit_RemoveCurrentRec(qres);
return ITXFAILED;
}
qres->totalRows++;
qres->rowsToStore++;
qres->startingRow = STARTING_ROW;
return field_count;
}
// row counter starts from 1
char* ITannit_AllocateSQLInsertStringWith(char* target, char* table, int row, va_list morefields)
{
TannitQueryResult* qres = NULL;
char* sqlstring = NULL;
char buffer[ITX_QRS_MAX_QUERY_LEN];
char fields[ITX_QRS_MAX_QUERY_LEN];
char values[ITX_QRS_MAX_QUERY_LEN];
char qvalz[ITX_QRS_MAX_FIELD_LEN];
TannitRecord* record;
int i;
char* fieldname;
char* fieldvalue;
int type;
if ((qres = itannit.FindEntry(table)) != NULL)
{
if ((record = itannit.GetRecordNumber(qres, row)) != NULL)
{
memset(buffer, 0, ITX_QRS_MAX_QUERY_LEN);
memset(fields, 0, ITX_QRS_MAX_QUERY_LEN);
memset(values, 0, ITX_QRS_MAX_QUERY_LEN);
for(i = 0; i < qres->colsNumber; i++)
{
type = qres->queryHeader[i].sqlDataType;
if (!ISNULL(record->row[i]))
{
strcat(fields, qres->queryHeader[i].name);
strcat(fields, ",");
switch (type)
{
case 0:
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_NULL_DATA:
case SQL_DATETIME:
case SQL_TYPE_DATE:
case SQL_TYPE_TIME:
case SQL_TYPE_TIMESTAMP:
strcat(values, "'");
memset(qvalz, '\0', ITX_QRS_MAX_FIELD_LEN);
ITannit_SubStr(record->row[i], qvalz, ITX_QRS_MAX_FIELD_LEN, "'", "''");
strcat(values, qvalz);
strcat(values, "',");
break;
default:
strcat(values, record->row[i]);
strcat(values, ",");
break;
}
}
}
if (morefields != NULL)
{
while ((fieldname = va_arg(morefields, char*)) != NULL)
{
strcat(values, "'");
strcat(fields, fieldname);
if ((fieldvalue = va_arg(morefields, char*)) == NULL)
return NULL;
strcat(values, fieldvalue);
strcat(fields, ",");
strcat(values, "',");
}
}
fields[strlen(fields)-1] = 0;
values[strlen(values)-1] = 0;
sprintf(buffer, "INSERT INTO %s (%s) VALUES (%s)", target, fields, values);
sqlstring = (char*) malloc(strlen(buffer));
strcpy(sqlstring, buffer);
}
}
return sqlstring;
}
char* ITannit_AllocateSQLUpdateStringWith(char* target, char* table, int row, ...)
{
TannitQueryResult* qres = NULL;
char* sqlstring = NULL;
char buffer[ITX_QRS_MAX_QUERY_LEN];
char set[ITX_QRS_MAX_QUERY_LEN];
char filter[ITX_QRS_MAX_QUERY_LEN];
TannitRecord* record;
int i;
va_list prmfilters;
int flt;
va_start(prmfilters, row);
if ((qres = itannit.FindEntry(table)) != NULL)
{
if ((record = itannit.GetRecordNumber(qres, row)) != NULL)
{
memset(buffer, 0, ITX_QRS_MAX_QUERY_LEN);
memset(set, 0, ITX_QRS_MAX_QUERY_LEN);
memset(filter, 0, ITX_QRS_MAX_QUERY_LEN);
for(i = 0; i < qres->colsNumber; i++)
{
if (!ISNULL(record->row[i]))
{
strcat(set, qres->queryHeader[i].name);
strcat(set, "=");
strcat(set, "'");
strcat(set, record->row[i]);
strcat(set, "',");
}
}
set[strlen(set)-1] = 0;
while ((flt = va_arg(prmfilters, int)) != NULL)
{
strcat(filter, "(");
strcat(filter, qres->queryHeader[flt].name);
strcat(filter, "=");
strcat(filter, "'");
strcat(filter, record->row[flt]);
strcat(filter, "') AND ");
}
if (!ISNULL(filter))
{
memset(filter + strlen(filter)-5, 0, 5);
sprintf(buffer, "UPDATE %s SET (%s) WHERE (%s)", target, set, filter);
}
else
sprintf(buffer, "UPDATE %s SET (%s)", target, set);
sqlstring = (char*) malloc(strlen(buffer));
strcpy(sqlstring, buffer);
}
}
return sqlstring;
}
// attiva la connessione con SQL Server
bool ITannit_ConnectSQL(char* dsn, char* uid, char* pwd)
{
if (isqlconn.IsConnected())
isqlconn.Destroy();
return isqlconn.Create(dsn, uid, pwd);
}
// la connessione con SQL Server deve essere attiva
bool ITannit_DisconnectSQL()
{
return isqlconn.Destroy();
}
bool ITannit_ManualCommitSQL()
{
return isqlconn.ManualCommit();
}
bool ITannit_AutoCommitSQL()
{
return isqlconn.AutoCommit();
}
bool ITannit_CommitSQL()
{
return isqlconn.Commit();
}
bool ITannit_RollbackSQL()
{
return isqlconn.Rollback();
}
// la connessione con SQL Server deve essere attiva
bool ITannit_ExecuteSQL(char* stm)
{
return itannit.ExecuteSQL(&isqlconn, stm);
}
int ITannit_ExecuteSQLQuery(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore)
{
isqlconn.Create(dsn, uid, pwd);
return itannit.ExecuteQuery(&isqlconn, queryname, query, firstRec, recsToStore);
}
// la connessione con SQL Server deve essere attiva
short int ITannit_GetSQLCols()
{
return isqlconn.m_cols;
}
// la connessione con SQL Server deve essere attiva
bool ITannit_GetSQLColInfo(short int col, char* name, short* type, long int* size)
{
return isqlconn.GetColInfo(col, name, type, size);
}
// la connessione con SQL Server deve essere attiva
bool ITannit_SkipSQLRecords(int start, int end)
{
if (end < start) return TRUE;
return isqlconn.SkipRecords(start, end);
}
bool ITannit_FillTQRColsInfoFromSQL(char* dsn, char* uid, char* pwd, char* tqrname, char* table)
{
TannitQueryResult* qres = NULL;
int actualCol;
bool result = TRUE;
char query[256];
if (!ITannit_ConnectSQL(dsn, uid, pwd))
return FALSE;
// allocazione ed inizializzazione di una nuova TannitQueryResult con le informazioni
// del corrispondente RecordSet su SQL Server
if ((qres = ITannit_FindQuery(tqrname)) != NULL)
{
sprintf(query, "SELECT * FROM %s", table);
if (ITannit_ExecuteSQL(query))
{
for (actualCol = 0; actualCol < qres->colsNumber; actualCol++)
ITannit_GetSQLColInfo(actualCol, &(qres->queryHeader[actualCol].name[0]),
&(qres->queryHeader[actualCol].sqlDataType),
&(qres->queryHeader[actualCol].colummnSize));
}
else
return FALSE;
}
else
result = FALSE;
ITannit_DisconnectSQL();
return result;
}
/* DEPRECATED
// Questa funzione � atomica rispetto alla connessione.
// se recsToStore = 0 si prendono tutti i record fino al massimo ammissibile.
bool ITannit_SelectFromSQL(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore)
{
TannitQueryResult* qres = NULL;
long int counter, actualCol;
int recordsNumber = 0;
bool result = TRUE;
SQLRETURN retcode;
if (!ITannit_ConnectSQL(dsn, uid, pwd))
return FALSE;
// allocazione ed inizializzazione di una nuova TannitQueryResult con le informazioni
// del corrispondente RecordSet su SQL Server
if ((qres = itannit.AllocateNewEntry(queryname, query, firstRec, recsToStore)) != NULL)
{
if (ITannit_SkipSQLRecords(1, qres->startingRow - 1))
{
recordsNumber = qres->startingRow + qres->rowsToStore - 1;
for (counter = qres->startingRow; counter <= recordsNumber; counter++)
{
if (itannit.AllocateNewRecord(qres))
{
for (actualCol = 0; actualCol < qres->colsNumber; actualCol++)
{
itannit.AllocateFieldSpace(qres, qres->queryHeader[actualCol].colummnSize, actualCol);
if (!SQL_SUCCEEDED(isqlconn.BindCol(actualCol, (qres->current_record)->row[actualCol],
qres->queryHeader[actualCol].colummnSize + 1)))
break;
}
retcode = isqlconn.Fetch();
if (!SQL_SUCCEEDED(retcode))
{
break;
}
else
{
(qres->totalRows)++;
}
}
else
{
result = FALSE;
break;
}
}
}
else
result = FALSE;
}
else
result = FALSE;
ITannit_DisconnectSQL();
return result;
}
*/
bool ITannit_SelectDirectFromSQL(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore)
{
isqlconn.Create(dsn, uid, pwd);
return itannit.SelectFromSQL(&isqlconn, queryname, query, firstRec, recsToStore);
}
// just Insert. it's up to the user previously delete the record from Database.
bool ITannit_InsertSQL(char* target, char* table, int row, ...)
{
va_list morefields;
char* query = NULL;
va_start(morefields, row);
if ((query = ITannit_AllocateSQLInsertStringWith(target, table, row, morefields)) == NULL)
return FALSE;
if (!ITannit_ExecuteSQL(query))
return FALSE;
free(query);
return TRUE;
}
// just Insert. it's up to the user previously delete the record from Database.
bool ITannit_BulkInsertSQL(FILE* log, char* target, char* table, ...)
{
va_list morefields;
TannitQueryResult* qres = NULL;
char* query = NULL;
va_start(morefields, table);
if ((qres = ITannit_FindQuery(table)) == NULL)
return FALSE;
for (int row = 1; row <= qres->totalRows; row++)
{
if ((query = ITannit_AllocateSQLInsertStringWith(target, table, row, morefields)) == NULL)
return FALSE;
if (!ITannit_ExecuteSQL(query))
ITannit_ErrorSQL(log);
free(query);
}
return TRUE;
}
void ITannit_DeleteSQL(char* target, ...)
{
va_list prmfilters;
char* flt;
char* fieldvalue;
char* sqlstring = NULL;
char buffer[ITX_QRS_MAX_QUERY_LEN];
char filter[ITX_QRS_MAX_QUERY_LEN];
va_start(prmfilters, target);
memset(buffer, 0, ITX_QRS_MAX_QUERY_LEN);
memset(filter, 0, ITX_QRS_MAX_QUERY_LEN);
while ((flt = va_arg(prmfilters, char*)) != NULL)
{
strcat(filter, "(");
strcat(filter, flt);
strcat(filter, "=");
strcat(filter, "'");
if ((fieldvalue = va_arg(prmfilters, char*)) == NULL)
return;
strcat(filter, fieldvalue);
strcat(filter, "') AND ");
}
if (!ISNULL(filter))
{
memset(filter + strlen(filter)-5, 0, 5);
sprintf(buffer, "DELETE FROM %s WHERE (%s)", target, filter);
}
else
sprintf(buffer, "DELETE FROM %s", target);
sqlstring = (char*) malloc(strlen(buffer));
strcpy(sqlstring, buffer);
ITannit_ExecuteSQL(sqlstring);
free(sqlstring);
}
int ITannit_ErrorSQL(FILE* log)
{
isqlconn.Error(log);
return isqlconn.m_nativerr;
}
TannitQueryResult* ITannit_FindQuery(char* token)
{
return itannit.FindEntry(token);
}
TannitQueryResult* ITannit_FindRegTP(int tpid)
{
return itannit.FindEntry(itxtp.GetTPName(tpid));
}
int ITannit_GetTPFields(char* tpname)
{
return itxtp.GetTPNFields(tpname);
}
// Ritorna il puntatore alla struttura QueryResult di Tannit da utilizzare.
// Eventualmente ne forza la creazione.
// Prepara lo spazio per un nuovo record
TannitQueryResult* ITannit_DBStructure(char* token)
{
TannitQueryResult* qres = NULL;
if ((qres = itannit.FindEntry(token)) == NULL)
{
//devo creare una nuova QueryResult
qres = itannit.AllocateNewEntry(&itxtp, token);
}
if (qres != NULL)
{
if (!itannit.AllocateNewRecord(qres))
qres = NULL;
}
return qres;
}
TannitQueryResult* ITannit_NewEntry(char* token, int numfields)
{
TannitQueryResult* qres = NULL;
if ((qres = itannit.FindEntry(token)) == NULL)
{
//devo creare una nuova QueryResult
qres = itannit.AllocateNewEntry(token, numfields, NULL);
}
return qres;
}
TannitQueryResult* ITannit_NewTQRFrom(char* source, char* field, char* value, char* destination)
{
TannitQueryResult* qres = NULL;
TannitQueryResult* qsrc = NULL;
TannitRecord* record;
char* filter;
int irow = 0;
if ((qsrc = itannit.FindEntry(source)) == NULL)
return qres;
if ((qres = itannit.Duplicate(qsrc, destination)) != NULL)
{
qres->totalRows = 0;
record = qsrc->recPtr;
// while (record != NULL)
while (irow < qsrc->totalRows)
{
irow++;
filter = ITannit_GetValue(qsrc, irow, field);
if (ISEQUAL(filter, value))
{
if (!itannit.AllocateNewRecord(qres))
return qres;
itannit.CopyRecord(qsrc, record, qres);
qres->totalRows++;
}
record = record->next;
}
}
return qres;
}
void ITannit_RemoveCurrentRec(TannitQueryResult* qres)
{
itannit.RemoveCurrentRec(qres);
}
void ITannit_RemoveQueries(char* firstname, ...)
{
va_list tables;
TannitQueryResult* qres;
char* name;
if (firstname == NULL)
return;
else
{
if ((qres = itannit.FindEntry(firstname)) != NULL)
itannit.RemoveEntry(qres);
va_start(tables, firstname);
while((name = va_arg(tables, char*)) != NULL)
{
if ((qres = itannit.FindEntry(name)) != NULL)
itannit.RemoveEntry(qres);
}
}
}
void ITannit_RemoveExcluding(char* firstname, ...)
{
va_list tables;
int i = 0;
TannitQueryResult* qres;
char* name;
bool exclude;
if (firstname == NULL)
itannit.DoEmpty();
else
{
int qcount = itannit.GetCount();
for (i = 0; i < qcount; i++)
{
exclude = FALSE;
qres = itannit.Get(i);
if (qres != NULL)
{
if (ISEQUAL(firstname, qres->id))
exclude = TRUE;
else
{
va_start(tables, firstname);
while((name = va_arg(tables, char*)) != NULL)
{
if (ISEQUAL(name, qres->id))
{
exclude = TRUE;
break;
}
}
}
if (!exclude)
itannit.RemoveEntry(qres);
}
}
}
}
bool ITannit_CheckCurrentRec(int numfield)
{
return itannit.CheckCurrentRec(numfield);
}
void ITannit_SetUser(char* user)
{
itannit.SetUser(user);
}
bool ITannit_Dump(FILE* fp)
{
return itannit.Dump(fp);
}
#ifdef _ITX_APPC
char* ITannit_TPExecute(PACKET_TYPE msgtype, int maxretray, FILE* log, ...)
{
char packet[ITX_APPC_MAX_INFO_LENGTH + 2];
char* returned_buffer = NULL;
va_list tables;
va_start(tables, log);
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
itannit.BuildPacketToSend(packet, ITX_APPC_LAST_PACKET, msgtype, tables);
returned_buffer = TPSendAndReceive(packet, log, msgtype, maxretray);
if (returned_buffer != NULL)
ITannit_ParsTP(NULL, returned_buffer, 1, 1, log, ITX_APPC_RECORD_SEP, ITX_APPC_FIELD_SEP);
return returned_buffer;
}
char* ITannit_TPExecuteCnv(PACKET_TYPE msgtype, int maxretray, FILE* log, ...)
{
char packet[ITX_APPC_MAX_INFO_LENGTH + 2];
char* returned_buffer = NULL;
long rblen = 0;
va_list tables;
va_start(tables, log);
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
itannit.BuildPacketToSend(packet, ITX_APPC_LAST_PACKET, msgtype, tables);
returned_buffer = TPSendAndReceive(packet, log, msgtype, maxretray);
rblen = strlen(returned_buffer);
IConversation_EBCDtoASCII(returned_buffer, rblen);
if (returned_buffer != NULL)
ITannit_ParsTP(NULL, returned_buffer, 1, 1, log, ITX_ASCII_RECORD_SEP, ITX_ASCII_FIELD_SEP);
return returned_buffer;
}
char* ITannit_TPExecuteFromFile(FILE* fp, FILE* log, PACKET_TYPE msgwaited, int maxretray)
{
char* returned_buffer = NULL;
char* appc_packet;
if((appc_packet = TPReceiveFromFile(fp)) == NULL)
return NULL;
// int i;
// appc_packet = (char*) calloc(1,95);
// for(i = 161; i<256; i++)
// appc_packet[i - 161] = i;
printf("%s\n", appc_packet);
// appc_packet[strlen(appc_packet) - 1] = 0;
returned_buffer = TPSendAndReceive(appc_packet, log, msgwaited, maxretray);
return returned_buffer;
}
bool ITannit_ReceiveFileFromAS400(char* filepath, FILE* log)
{
char packet[ITX_APPC_MAX_INFO_LENGTH + 2];
FILE* fd;
char* returned_buffer = NULL;
char wrc[4];
char* dati = NULL;
bool file_completed = FALSE;
char as400_end_info[ITX_APPC_AS400_TX_END_LEN + 1];
if (!IConversation_OpenTransaction(log))
return FALSE;
if ((fd = fopen(filepath, "wb")) == NULL)
{
IConversation_CloseTransaction(log);
return FALSE;
}
memset(as400_end_info, '\0', ITX_APPC_AS400_TX_END_LEN + 1);
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
memset(wrc, '\0', 4);
if (!itannit.BuildSinglePacketToSend(packet, ITX_APPC_PC_FTX, "C00"))
ROLLBACK_TRANSACTION;
returned_buffer = TPSendAndReceive(packet, log, ITX_APPC_ANY_MSG, 1);
if (returned_buffer == NULL)
ROLLBACK_TRANSACTION;
ITannit_ParsTP(NULL, returned_buffer, 1, 1, log, ITX_APPC_RECORD_SEP, ITX_APPC_FIELD_SEP);
memcpy(wrc, returned_buffer, 3);
if (ISEQUAL(wrc, "E00"))
ROLLBACK_TRANSACTION;
if ((dati = itannit.GetValue("C01", 1, 4)) == NULL)
ROLLBACK_TRANSACTION;
if (ISEQUAL(dati, "Y"))
{
if (!itannit.BuildSinglePacketToSend(packet, ITX_APPC_PC_FTX, "C02"))
ROLLBACK_TRANSACTION;
if (!IConversation_OpenTransaction(log))
return FALSE;
if (!IConversation_SendData(packet, log))
ROLLBACK_TRANSACTION;
IConversation_PrepareReceive(log);
// AS400 a questo punto invia un C05 in testa al file di ritorno contente
// informazioni sul fatto che vi siano ulteriori informazioni disponibili.
// Per il momento questo pacchetto non viene processato.
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
if (!IConversation_ReceiveFileChunk(packet, ITX_APPC_MAX_INFO_LENGTH, log))
ROLLBACK_TRANSACTION;
while (!file_completed)
{
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
if (!IConversation_ReceiveFileChunk(packet, ITX_APPC_MAX_INFO_LENGTH, log))
ROLLBACK_TRANSACTION;
strncpy(as400_end_info, packet, 4);
if (ISEQUAL(as400_end_info, ITX_APPC_AS400_TX_END))
file_completed = TRUE;
else if (!ISNULL(packet))
{
packet[strlen(packet)] = '\n';
packet[strlen(packet) + 1] = '\0';
itxCharToOem(packet, packet);
fputs(packet, fd);
}
}
IConversation_CloseTransaction(log);
}
fclose(fd);
return TRUE;
}
bool ITannit_SendHOK(FILE* log, PACKET_TYPE ptype)
{
char packet[ITX_APPC_MAX_INFO_LENGTH + 2];
ITannit_StoreRecord("HOK", "HOK", NULL);
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 1);
if (!itannit.BuildSinglePacketToSend(packet, ptype, "HOK"))
{
IConversation_CloseTransaction(log);
return FALSE;
}
if (!IConversation_OpenTransaction(log))
return FALSE;
if (!IConversation_SendData(packet, log))
{
IConversation_CloseTransaction(log);
return FALSE;
}
IConversation_PrepareReceive(log);
IConversation_ReceiveFileChunk(packet, ITX_APPC_MAX_INFO_LENGTH, log);
IConversation_CloseTransaction(log);
return TRUE;
}
bool ITannit_SendFileToAS400(char* filepath, FILE* log)
{
char packet[ITX_APPC_MAX_INFO_LENGTH + 2];
char fdata[ITX_APPC_MAX_INFO_LENGTH + 2];
char trash[ITX_APPC_MAX_INFO_LENGTH + 1];
FILE* fd;
char* returned_buffer = NULL;
char wrc[4];
char* dati = NULL;
bool file_completed = FALSE;
char as400_end_info[ITX_APPC_AS400_TX_END_LEN + 1];
int size;
if (!IConversation_OpenTransaction(log))
return FALSE;
if ((fd = fopen(filepath, "rb")) == NULL)
{
IConversation_CloseTransaction(log);
return FALSE;
}
memset(as400_end_info, '\0', ITX_APPC_AS400_TX_END_LEN + 1);
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
memset(wrc, '\0', 4);
if (!itannit.BuildSinglePacketToSend(packet, ITX_APPC_PC_FTX, "C00"))
ROLLBACK_TRANSACTION;
returned_buffer = TPSendAndReceive(packet, log, ITX_APPC_ANY_MSG, 1);
if (returned_buffer == NULL)
ROLLBACK_TRANSACTION;
ITannit_ParsTP(NULL, returned_buffer, 1, 1, log, ITX_APPC_RECORD_SEP, ITX_APPC_FIELD_SEP);
memcpy(wrc, returned_buffer, 3);
if (ISEQUAL(wrc, "E00"))
ROLLBACK_TRANSACTION;
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
if (!itannit.BuildSinglePacketToSend(packet, ITX_APPC_PC_FTX, "C03"))
ROLLBACK_TRANSACTION;
if (!IConversation_OpenTransaction(log))
return FALSE;
if (!IConversation_SendData(packet, log))
ROLLBACK_TRANSACTION;
while (!feof(fd))
{
memset(fdata, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
fgets(fdata, ITX_APPC_MAX_INFO_LENGTH, fd);
itxOemToChar(fdata, fdata);
size = strlen(fdata);
if(size == ITX_APPC_MAX_INFO_LENGTH)
fgets(trash, ITX_APPC_MAX_INFO_LENGTH, fd);
// if(size != 0)
if(size > ITX_APPC_HEADER_LENGTH)
{
padnstr(fdata, ITX_APPC_MAX_INFO_LENGTH, ' ');
if (!IConversation_SendData(fdata, log))
ROLLBACK_TRANSACTION;
}
}
memset(packet, '\0', ITX_APPC_MAX_INFO_LENGTH + 2);
memcpy(packet, ITX_APPC_AS400_TX_END, 5);
padnstr(packet, ITX_APPC_MAX_INFO_LENGTH, ' ');
packet[ITX_APPC_MAX_INFO_LENGTH] = '\0';
if (!IConversation_SendData(packet, log))
ROLLBACK_TRANSACTION;
IConversation_PrepareReceive(log);
IConversation_ReceiveFileChunk(packet, ITX_APPC_MAX_INFO_LENGTH, log);
IConversation_CloseTransaction(log);
fclose(fd);
return TRUE;
}
#endif // _ITX_APPC
// row � espresso in base 1.
char* ITannit_GetValue(TannitQueryResult* qres, int row, char* field)
{
char* value = NULL;
TannitRecord* record;
if (row > 0 && row <= qres->totalRows)
{
record = qres->recPtr;
for (int i = 1; i < row; i++)
record = record->next;
int columnpos = 0;
if ((columnpos = itannit.GetColPos(qres, field)) > 0)
value = record->row[columnpos - 1];
}
return value;
}
// row deve essere in base 1
void ITannit_SetCurrentRecord(TannitQueryResult* qres, int row)
{
TannitRecord* record;
if (row > 0 && row <= qres->totalRows)
{
record = qres->recPtr;
for (int i = 1; i < row; i++)
record = record->next;
qres->current_record = record;
}
return;
}
//END Interfaccia C alla classe ITannit
////////////////////////////////////////////////
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// AITECSA s.r.l. 1999
// filename: tpcomm.h
// description: itannit AS400 interface library
// transaction program main communication procedure
// project: ASWEB
#ifndef __ITX_TP_COMM_H__
#define __ITX_TP_COMM_H__
extern "C"
{
char* TP_Simul(FILE* fp);
char* TPReceiveFromFile(FILE* fp);
char* TPExecute(char* tp, FILE* log);
char* TPAssembly(char** pks, int pknum);
char* TPSendAndReceive(char* tp, FILE* log, PACKET_TYPE msgwaited, int maxretray);
}
#endif //__ITX_TP_COMM_H__<file_sep>percolation
===========
2-dimensional site percolation algorithms and numerical simulations
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsystem.h,v $
* $Revision: 1.4 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:31+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXSYSTEM_H__
#define __ITXSYSTEM_H__
#include <time.h>
#include "itxwin32.h" //main header file for win32 platforms
#include "itxlinux.h" //main header file for linux platforms
#include "itxstring.h"
//-------------------------------------------------
//---------------- itxSystem -----------------
//-------------------------------------------------
class itxSystem
{
public:
// *** Base Services BS
int BSSetenv(char* varname, char* varval);
int BSGetLastError();
// *** Processes PR
int PRGetProcessId();
void PRGetModuleName(void* pmodule, char* pfilename, int bufsize);
// *** Dynamic Linking DL
void* DLLoadLibrary(char* fmodule);
bool DLFreeLibrary(void* pmodule);
void* DLGetFunction(void* pmodule, char* pfuncname);
int DLGetLastError();
// *** File System FS
void FSDirToTokenString(char* dir, char* filter, char token, itxString* retlist);
bool FSFileIsReadOnly(char* pfilename);
void FSSetMode(FILE* fp, int mode);
void FSGetCurrentDirectory(char* pfilename, int bufsize);
// *** Time TM
void TMGetMilliTime(time_t* now, int* milli);
// *** Threads TH
void* THCreateThread(void* entrypointfunc, void* entrypointarg, unsigned int* pretid);
void THPauseThread(void* thread);
void THResumeThread(void* thread);
void THTerminateThread(void* thread);
// *** Sockets SO
int SOGetLastError(int socket);
bool SOInitLibrary();
bool SOCloseLibrary();
void SOInitDescriptors(void* fdstruct, int socket);
void SOClose(int socket);
//CONSTRUCTION-DESTRUCTION
itxSystem(){}
~itxSystem(){}
};
#endif // __ITXSYSTEM_H__
<file_sep>#include <windows.h>
#include <stdio.h>
#define n 6
#define k 3
int GetFirstFreeBit(int v)
{
int i = 0;
while (!(v&(1<<i)))
i++;
while (v&(1<<i))
i++;
return i;
}
void main()
{
int i = 0;
int j = 0;
int min = 0;
int max = 0;
int next = 0;
int freebit = 0;
DWORD beg = GetTickCount();
for (i=0; i<k; i++)
min |= (1<<i);
max = min<<(n-k);
printf("min = %d, max = %d\n", min, max);
next = min;
while (next<max)
{
freebit = GetFirstFreeBit(next);
next |= (1<<freebit);
next &= (~(1<<(freebit-1)));
printf("next = %d\n", next);
}
DWORD end = GetTickCount();
printf("milli = %d\n", end - beg);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include <time.h>
#include "cgic.h"
#include "tannit.h"
#include "extVars.h"
extern cgiFormEntry *cgiFormEntryFirst;
void itxAuthorizeUpload()
{
char initFileName[INIT_FILE_NAME_LEN]; /*nome del file di inizializazione*/
char initFileN[INIT_FILE_NAME_LEN]; /*nome del file di inizializazione con l'estensione*/
FILE *initFile; /*file di inizializazione*/
static char queryString[GET_PAR_VAL_LEN];
char *dbPwd = NULL;
int errCode = 0;
/**/if(usedbg){fprintf(debug, "itxAuthorizeUpload START\n");fflush(debug);}
char login[GET_VAR_LEN];
char cpwd[GET_VAR_LEN];
if (cgiFormString(LOGIN_TAG, login, GET_VAR_LEN) != cgiFormSuccess)
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
if (cgiFormString(CPWD_TAG, cpwd, GET_VAR_LEN) != cgiFormSuccess)
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
//
// Il nome del file di inizializzazione viene ricavato dal valore di get PAR_FILE_TAG se
// PAR_FILE non e' presente nella get si usa il file di default DEF_PAR_FILE
//
if (cgiFormString(PAR_FILE_TAG, initFileName, GET_VAR_LEN)!=cgiFormSuccess)
sprintf(initFileN,"%s.%s", DEF_PAR_FILE, DEF_PAR_FILE_EXT);
else
sprintf(initFileN,"%s.%s", initFileName, DEF_PAR_FILE_EXT);
initFile = fopen(initFileN, "r");
if(!initFile) EXIT(0);
strcpy (Odbcdsn, readPar("ODBCDSN" ,"" , initFile) );/*odbc dsn*/
strcpy (Odbcuid, readPar("ODBCUID" ,"" , initFile) );/*odbc uid*/
strcpy (Odbcpwd, readPar("ODBCPWD" ,"" , initFile) );/*odbc pwd*/
strcpy (LoginTable, readPar("LoginTable" ,"" , initFile) );/*tabella di verifica del login*/
strcpy (PwdField, readPar("PwdField" ,"" , initFile) );/*campo password*/
strcpy (LoginField, readPar("LoginField" ,"" , initFile) );/*campo login*/
fclose(initFile);
//
// Controllo che la password nel DB sia la stessa di input
//
if ( checkDbPwd(login, cpwd, "1", "1") == NOT_VALIDATED )
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
}
cgiParseResultType AddNewFormEntry(char* attr, char* value)
{
cgiFormEntry *n;
cgiFormEntry *l;
cgiFormEntry *p;
/* OK, we have a new pair, add it to the list. */
n = (cgiFormEntry *) malloc(sizeof(cgiFormEntry));
/**/if(alloctrc){fprintf(debug, "- - n:%d - - len:%d\n", n, sizeof(cgiFormEntry));fflush(debug);}
if (!n)
return cgiParseMemory;
n->attr = (char*) malloc(strlen(attr)+1);
/**/if(alloctrc){fprintf(debug, "- - n->attr:%d - - len:%d\n", n->attr, strlen(attr)+1);fflush(debug);}
n->value = (char*) malloc(strlen(value)+1);
/**/if(alloctrc){fprintf(debug, "- - n->value:%d - - len:%d\n", n->value, strlen(value)+1);fflush(debug);}
n->next = 0;
strcpy(n->attr, attr);
strcpy(n->value, value);
/**/if(usedbg){fprintf(debug, "Acquisizione parametro get: %s value: %s\n", attr, value);fflush(debug);}
l = cgiFormEntryFirst;
p = 0;
while(l != 0)
{
p = l;
l = l->next;
}
if (p == 0)
cgiFormEntryFirst = n;
else
p->next = n;
return cgiParseSuccess;
}
cgiParseResultType itxCGIParseMultipartInput()
{
int totBytesRead = 0, bytesread = 0;
char buffer[BUFFER_SIZE];
char bound[128];
char finalBound[128];
bool file_continue = true;
/**/if(usedbg){fprintf(debug, "itxCGIParseFormInput STARTING\n");fflush(debug);}
if (cgiContentLength == 0)
{
return cgiParseSuccess;
}
bytesread=getline(buffer,BUFFER_SIZE);
buffer[bytesread-1]=0;
strcpy(bound, buffer); /*definizione della stringa di boundary*/
sprintf(finalBound, "%s--", bound); /*definizione della stringa finale*/
/**/if(usedbg){fprintf(debug, "itxCGIParseFormInput finalBound:%s\n", finalBound);fflush(debug);}
/**/if(usedbg){fprintf(debug, "itxCGIParseFormInput bound:%s\n", bound);fflush(debug);}
/**/if(usedbg){fprintf(debug, "Lettura Multipart Iniziante\n");fflush(debug);}
while (file_continue)
{
bytesread=getline(buffer,BUFFER_SIZE);
buffer[bytesread-1]=0;
/**/if(usedbg){fprintf(debug, "%s\n", buffer);fflush(debug);}
if (strcmp(finalBound, buffer) == 0)
file_continue = false;
else
if (strcmp(bound, buffer) != 0)
{
//siamo nella zona utile
// deve essere presente la seguente stringa
if ( strstr(buffer, "Content-Disposition: form-data; name=\"") == NULL)
{
/**/if(usedbg){fprintf(debug, "cgiParseResultType returning A\n");fflush(debug);}
return cgiParseIO;
}
// verifichiamo se si tratta di un file
if ( strstr(buffer, "filename=") != NULL)
{
// check su login e cpwd
// this function force exit on login error
itxAuthorizeUpload();
// eliminiamo l'eventuale Content-type e la riga vuota
// per Netscape la seguente � una stringa vuota
bytesread=getline(buffer, BUFFER_SIZE);
buffer[bytesread-1]=0;
/**/if(usedbg){fprintf(debug, "1-%s\n", buffer);fflush(debug);}
// Explorer indica il tipo: supportiamo solo file testo
if (strstr(buffer, "Content-Type: application") != 0)
{
/**/if(usedbg){fprintf(debug, "cgiParseResultType returning B\n");fflush(debug);}
return cgiParseIO;
}
else if (strstr(buffer, "Content-Type:") != 0)
{
// eliminiamo la riga vuota
bytesread=getline(buffer,BUFFER_SIZE);
buffer[bytesread-1]=0;
/**/if(usedbg){fprintf(debug, "2-%s\n", buffer);fflush(debug);}
}
char filename[GET_PAR_VAL_LEN];
bool eof = false;
bool opened = true;
int currFileCnt = 0;
FILE* fp;
//generazione del nome del file destinazione dei dati di upload
while(opened)
{
sprintf(filename, "%sitxBuf%d.upl", CORR_UPLOAD_DIR, currFileCnt);
/**/if(usedbg){fprintf(debug, "filename:%s\n", filename);fflush(debug);}
if ((fp = fopen(filename, "r")) == NULL)
opened = false;
else
{
// sleep(1);
fclose(fp);
currFileCnt++;
}
}
// scarica il file
if ( ( fp = fopen(filename, "wb") ) == 0 )
{
sendTransStart(0, 0);
sendBack(FATAL_ERROR);
EXIT(0);
}
while(!eof)
{
bytesread = getline(buffer,BUFFER_SIZE);
buffer[bytesread] = 0;
/**/if(usedbg){fprintf(debug, "3-%s", buffer);fflush(debug);}
/**/if(usedbg){fprintf(debug, "\nbytesread:%d\n", bytesread);fflush(debug);}
if ( (strstr(buffer, finalBound) != 0) || (bytesread == EOF))
{
file_continue = false;
eof = true;
}
else if (strstr(buffer, bound) != 0)
{
eof = true;
}
else
{
fwrite(buffer, 1, bytesread, fp);
}
}
fclose(fp);
AddNewFormEntry(ITX_UPLOAD_FILE_TAG, filename);
}
else
{
// si tratta di una coppia (variabile, valore)
char* attr;
char value[GET_PAR_VAL_LEN];
strtok( buffer, "\"" );
attr = strtok( NULL, "\"" );
// leggiamo la riga vuota
bytesread=getline(buffer,BUFFER_SIZE);
/**/if(usedbg){fprintf(debug, "4-%s", buffer);fflush(debug);}
// recuperiamo il valore
bytesread=getline(buffer,BUFFER_SIZE);
if (bytesread > 0)
memcpy(value, buffer, bytesread-1);
value[bytesread-1] = 0;
/**/if(usedbg){fprintf(debug, "5-%s", buffer);fflush(debug);}
AddNewFormEntry(attr, value);
}
}
}
/**/if(usedbg){fprintf(debug, "\nLettura Multipart Finita\n");fflush(debug);}
return cgiParseSuccess;
}
<file_sep>DEVUSERHOME = /Amarone/Progetti/itxSoftware/Web
ITXLIB = /Amarone/Progetti/itxSoftware/Librerie/itxlib
TANNITINCLUDE = $(DEVUSERHOME)/Tannit/include
ITXLIBINCLUDE = $(ITXLIB)
TANNITSOURCE = $(DEVUSERHOME)/Tannit/sources/Ocore
ODBCINCLUDE = /usr/local/include
ODBCLIB = /usr/local/lib
CC=g++
CFLAGS=-O
sources=auxfile.cpp cgiresolver.cpp commands.cpp commands2.cpp desx.cpp parser.cpp \
tannitobj.cpp templatefile.cpp tntapiimpl.cpp tqr.cpp tqrodbc.cpp
objects=auxfile.o cgiresolver.o commands.o commands2.o desx.o parser.o tannitobj.o \
templatefile.o tntapiimpl.o tqr.o tqrodbc.o
tannit: $(objects)
$(CC) $(CFLAGS) -o $@ $(objects) -litx -lodbc -L$(ITXLIB) -L$(ODBCLIB)
$(objects): %.o: %.cpp
$(CC) $(CFLAGS) -c $< -DLINUX -DMAINT_1 -I$(TANNITINCLUDE) -I$(ITXLIBINCLUDE)
clean :
rm $(TANNITSOURCE)/*.o; \
touch *.h *.cpp
xw:
chmod -x *.h; \
chmod -x *.cpp; \
chmod +w *.h; \
chmod +w *.cpp
debug:
$(TANNITINCLUDE) \
$(ITXLIB) \
$(ITXLIBINCLUDE) \
$(TANNITSOURCE) \
$(ODBCINCLUDE) \
$(ODBCLIB)
depend:
makedepend -I$(TANNITINCLUDE) -I$(ODBCINCLUDE) \
-I$(ITXLIBINCLUDE) $(TANNITSOURCE) -- $(CFLAGS) -- $(TANNITSOURCE)/*.[cpph]
# DO NOT DELETE THIS LINE -- make depend depends on it.
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxSocket.cpp,v $
* $Revision: 1.26 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:32+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxsocket.h"
//====================================================================
// The OPENSSL name enables openssl library support:
// to compile itxlib with this name defined you need to add:
// 1) additional include path to openssl header files;
// to use itxlib and the ssl library from your program you need to add:
// 2) additional library path to libssl32.lib;
// 3) a way to find (at runtime) libeay32.dll and libssl32.dll.
//
// N.B. DO NOT TRY to move next #ifdef block into the .h because
// this way makes the itxlib client DEPENDENT from the name above,
// which is intended ONLY to compile itxlib with additional SSL support.
//====================================================================
#ifdef OPENSSL
#pragma message("=== Compiling with OPENSSL support ===")
#include "openssl/err.h"
#include "openssl/ssl.h"
#endif //OPENSSL
#pragma pack(4)
//----------------------------------------------------------------
//--------------- CONSTRUCTION-DESTRUCTION -----------------------
itxSocket::itxSocket()
{
InitSocketLibrary(); // MUST be alway called here.
}
itxSocket::itxSocket(int port)
{
InitSocketLibrary(); // MUST be alway called here.
CreateServerSocket(port);
}
itxSocket::itxSocket(char* destination, int port, bool ssl)
{
InitSocketLibrary(); // MUST be alway called here.
try
{
CreateTCPStreamSocket();
}
catch(itxSocketException e)
{
// throw e;
return;
}
struct hostent* hp;
SOCKADDR_IN dest;
unsigned int addr=0;
m_destination = destination;
memset(&dest, 0, sizeof(SOCKADDR_IN));
if ((hp = gethostbyname(destination)) == NULL)
{
if ((addr = inet_addr(destination)) == INADDR_NONE)
throw new itxException(INADDR_NONE, "itxSocket constructor - inet_addr");
dest.sin_addr.s_addr = addr;
}
else
memcpy((char*)&(dest.sin_addr),hp->h_addr,hp->h_length);
dest.sin_family = AF_INET;
dest.sin_port = htons(port);
memset(dest.sin_zero, '\0', 8);
// Connect the socket
if (connect(m_socket, (LPSOCKADDR)&dest, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
throw new itxSocketException("itxSocket constructor - connect", this->m_socket);
if (ssl)
{
if (SSLAllocate())
{
if (!SSLConnect())
throw new itxSocketException("itxSocket constructor - SSLConnect", this->m_socket);
}
}
m_ipv4 = inet_ntoa(dest.sin_addr);
m_port = port;
m_packetlen = ITXS_PCKLEN;
m_transferredbytes = 0;
}
itxSocket::~itxSocket()
{
Close();
itxSystem sys;
sys.SOCloseLibrary();
}
//----------------------------------------------------------------
//--------------------------- METHODS ----------------------------
// WARNING!!!
// THIS FUNCTION MUST BE CALLED BEFORE ANY OTHER CALL
// BECAUSE IT INITIALIZES THE PROPER SOCKET LIBRARY.
void itxSocket::InitSocketLibrary()
{
m_destination.SetEmpty();
m_port = 0;
m_socket = INVALID_SOCKET;
m_ipv4.SetEmpty();
m_packetlen = 0;
m_transferredbytes = 0;
m_tm.tv_sec = ITXS_TIMEOUTSEC;
m_tm.tv_usec = ITXS_TIMEOUTMILLISEC;
m_tm_cycle.tv_sec = ITXS_TIMEOUTSEC;
m_tm_cycle.tv_usec = ITXS_TIMEOUTMILLISEC;
#ifdef OPENSSL
m_SSLActive = false;
#endif
if (!m_Sys.SOInitLibrary())
throw new itxSocketException("SOInitLibrary", this->m_socket);
}
void itxSocket::SetReceiveTimeout(long sec, long millisec)
{
m_tm.tv_sec = sec;
m_tm.tv_usec = millisec;
}
void itxSocket::SetReceiveCycleTimeout(long sec, long millisec)
{
m_tm_cycle.tv_sec = sec;
m_tm_cycle.tv_usec = millisec;
}
void itxSocket::CreateTCPStreamSocket()
{
char buf[1024] = {0};
// Create a TCP/IP stream socket
m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_socket == INVALID_SOCKET)
{
itxSystem sys;
sprintf(buf, "CreateTCPStreamSocket - socket() fails and WSAGetLastError returns %d.", sys.SOGetLastError(m_socket));
throw new itxSocketException(buf, this->m_socket);
}
}
bool itxSocket::CreateServerSocket(int port, int maxconn)
{
SOCKADDR_IN sockaddr;
bool sockcreated = true;
itxSystem sys;
m_port = port;
try
{
CreateTCPStreamSocket();
}
catch(itxSocketException e)
{
// throw e;
return false;
}
memset(&sockaddr, 0, sizeof(SOCKADDR_IN));
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(m_port);
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ((bind(m_socket, (LPSOCKADDR) &sockaddr, sizeof(sockaddr))) == SOCKET_ERROR)
{
throw new itxSocketException("itxSocket::CreateServerSocket() - bind()", this->m_socket);
sys.SOClose(m_socket);
sockcreated = false;
}
if ((listen(m_socket, maxconn)) == SOCKET_ERROR)
{
throw new itxSocketException("itxSocket::CreateServerSocket() - listen()", this->m_socket);
sys.SOClose(m_socket);
sockcreated = false;
}
return sockcreated;
}
bool itxSocket::Accept(itxSocket* pclientsocket)
{
SOCKET sockaccept;
sockaccept = accept(m_socket,NULL, NULL);
if (sockaccept == INVALID_SOCKET)
{
throw new itxSocketException("itxSocket::Accept() - accept()", this->m_socket);
return false;
}
pclientsocket->AssignSocket(sockaccept);
return true;
}
void itxSocket::AssignSocket(SOCKET socket)
{
if (socket != INVALID_SOCKET)
m_socket = socket;
else
m_socket = INVALID_SOCKET;
}
int itxSocket::Send(char* datatosend, int bytes_to_send)
{
if ((m_transferredbytes = send(m_socket, datatosend, bytes_to_send, NULL)) == SOCKET_ERROR)
throw new itxSocketException("itxSocket::Send", this->m_socket);
return m_transferredbytes;
}
int itxSocket::Send(itxString* datatosend)
{
return Send(datatosend->GetBuffer(), datatosend->Len());
}
// non si occupa della apertura o chiusura del file
int itxSocket::BulkSend(FILE* fp, int packetlen)
{
char* buffer = NULL;
int datatosend;
int bytesent = 0;
m_transferredbytes = 0;
if (fp == NULL) return 0;
m_packetlen = packetlen;
if ((buffer = (char*) malloc((packetlen + 1) * sizeof(char))) == NULL)
throw new itxSocketException("itxSocket::BulkSend - malloc", this->m_socket);
while(!feof(fp))
{
datatosend = fread(buffer, 1, packetlen, fp);
if (datatosend < packetlen && ferror(fp) != 0)
throw new itxSocketException("itxSocket::BulkSend - fread", this->m_socket);
if ((bytesent = send(m_socket, buffer, datatosend, NULL)) == SOCKET_ERROR)
throw new itxSocketException("itxSocket::BulkSend - send", this->m_socket);
m_transferredbytes += bytesent;
}
return m_transferredbytes;
}
int itxSocket::Receive(itxString* datatoreceive, int packetlen)
{
int nfds = 0, result, dataread;
fd_set datatoread;
char* buffer = NULL;
m_Sys.SOInitDescriptors(&datatoread, m_socket);
m_packetlen = packetlen;
m_transferredbytes = 0;
if ((buffer = (char*) malloc((packetlen + 1) * sizeof(char))) == NULL)
throw new itxSocketException("itxSocket::Receive - malloc", this->m_socket);
dataread = packetlen;
*datatoreceive = "";
// select() function returns:
// - the total number of socket handles that are ready
// - 0 if the time limit expired
// - SOCKET_ERROR if an error occurred
// timeout controls how long the select() can take to complete:
// - null pointer: select() will block
// - {0, 0}: select() will return immediately (nonblocking select)
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
while (!(result == 0 || result == SOCKET_ERROR)) //socket has been checked for readability
{
dataread = recv(m_socket, buffer, m_packetlen, NULL);
if (dataread == 0) //Connection was gracefully closed
break;
else if (dataread != SOCKET_ERROR)
{
buffer[dataread] = 0;
*datatoreceive += buffer;
m_transferredbytes += dataread;
}
else
throw new itxException(dataread, "itxSocket::Receive - recv");
//checking for socket readability
result = select(nfds, &datatoread, NULL, NULL, &m_tm_cycle);
}
free(buffer); //not needed anymore
if (result == SOCKET_ERROR)
throw new itxSocketException("itxSocket::Receive - select", this->m_socket);
return m_transferredbytes;
}
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* NON USARE la BlockingReceive !!! OBSOLETA !!!
* (Lasciata solo per retro-compatibilita`)
* Equivale alle due chiamate:
* SetReceiveCycleTimeout(0, 0);
* Receive(...);
*/
int itxSocket::BlockingReceive(itxString* datatoreceive, int packetlen)
{
int nfds = 0, result, dataread;
fd_set datatoread;
char* buffer = NULL;
struct timeval tm;
tm.tv_sec = 0;
tm.tv_usec = 0;
m_Sys.SOInitDescriptors(&datatoread, m_socket);
m_packetlen = packetlen;
m_transferredbytes = 0;
if ((buffer = (char*) malloc((packetlen + 1) * sizeof(char))) == NULL)
throw new itxSocketException("itxSocket::Receive - malloc", this->m_socket);
dataread = packetlen;
*datatoreceive = "";
// select() function returns:
// - the total number of socket handles that are ready
// - 0 if the time limit expired
// - SOCKET_ERROR if an error occurred
// timeout controls how long the select() can take to complete:
// - null pointer: select() will block
// - {0, 0}: select() will return immediately (nonblocking select)
//Receive without timeout
// result = select(nfds, &datatoread, NULL, NULL, NULL);
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
while (!(result == 0 || result == SOCKET_ERROR)) //socket has been checked for readability
{
dataread = recv(m_socket, buffer, m_packetlen, NULL);
if (dataread == 0) //Connection was gracefully closed
break;
else if (dataread != SOCKET_ERROR)
{
buffer[dataread] = 0;
*datatoreceive += buffer;
m_transferredbytes += dataread;
}
else
throw new itxException(dataread, "itxSocket::Receive - recv");
//checking for socket readability
result = select(nfds, &datatoread, NULL, NULL, &tm);
}
free(buffer); //not needed anymore
if (result == SOCKET_ERROR)
throw new itxSocketException("itxSocket::Receive - select", this->m_socket);
return m_transferredbytes;
}
// non si occupa della apertura o chiusura del file
//TBD DA METTERE A POSTO COME LA Receive
int itxSocket::BulkReceive(FILE* fp, int packetlen)
{
int nfds = 0, result, dataread, totalbyteread = 0;
fd_set datatoread;
char* buffer = NULL;
m_Sys.SOInitDescriptors(&datatoread, m_socket);
m_packetlen = packetlen;
m_transferredbytes = 0;
if ((buffer = (char*) malloc((packetlen + 1) * sizeof(char))) == NULL)
throw new itxSocketException("itxSocket::BulkReceive - malloc", this->m_socket);
dataread = packetlen;
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
while (!(result == 0 || result == SOCKET_ERROR))
{
dataread = recv(m_socket, buffer, m_packetlen, NULL);
if (!(dataread == 0 || dataread == SOCKET_ERROR))
{
buffer[dataread] = 0;
if (fwrite(buffer, 1, dataread, fp) < dataread)
throw new itxSocketException("itxSocket::BulkReceive - fwrite", this->m_socket);
m_transferredbytes += dataread;
}
else
throw new itxException(dataread, "itxSocket::Receive - recv");
if (dataread == m_packetlen)
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
else
break;
}
if (result == 0 || result == SOCKET_ERROR)
throw new itxSocketException("itxSocket::Receive - select", this->m_socket);
return m_transferredbytes;
}
void itxSocket::Close()
{
SSLFree();
if (m_socket != INVALID_SOCKET)
{
m_Sys.SOClose(m_socket);
m_socket = INVALID_SOCKET;
}
}
int itxSocket::BinReceive(char* datatoreceive, int maxbytes, int packetlen)
{
int nfds = 0, result, dataread;
fd_set datatoread;
char* buffer = NULL;
char* startdata = datatoreceive;
m_Sys.SOInitDescriptors(&datatoread, m_socket);
m_packetlen = packetlen;
m_transferredbytes = 0;
if ((buffer = (char*) malloc((packetlen + 1) * sizeof(char))) == NULL)
throw new itxSocketException("itxSocket::Receive - malloc", this->m_socket);
dataread = packetlen;
*datatoreceive = 0;
// select() function returns:
// - the total number of socket handles that are ready
// - 0 if the time limit expired
// - SOCKET_ERROR if an error occurred
// timeout controls how long the select() can take to complete:
// - null pointer: select() will block
// - {0, 0}: select() will return immediately (nonblocking select)
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
while (!(result == 0 || result == SOCKET_ERROR)) //socket has been checked for readability
{
dataread = recv(m_socket, buffer, m_packetlen, NULL);
if (dataread == 0) //Connection was gracefully closed
break;
else if (dataread != SOCKET_ERROR)
{
m_transferredbytes += dataread;
if (maxbytes <= m_transferredbytes)
{
m_transferredbytes -= dataread;
break;
}
buffer[dataread] = 0;
memcpy(startdata, buffer, dataread);
startdata += dataread;
}
else
throw new itxException(dataread, "itxSocket::Receive - recv");
//checking for socket readability
result = select(nfds, &datatoread, NULL, NULL, &m_tm);
}
free(buffer); //not needed anymore
if (result == SOCKET_ERROR)
throw new itxSocketException("itxSocket::Receive - select", this->m_socket);
return m_transferredbytes;
}
//SSL support ----------------------------
bool itxSocket::SSLConnect()
{
#ifdef OPENSSL
if (!m_SSLActive)
return false;
SSL_set_fd((SSL*)m_ssl, m_socket);
return (SSL_connect((SSL*)m_ssl) == -1 ? false : true);
#else
return false;
#endif
}
bool itxSocket::SSLAllocate()
{
#ifdef OPENSSL
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
SSL_METHOD* meth = SSLv2_client_method();
if ((m_ctx = SSL_CTX_new(meth)) == NULL)
return false;
if ((m_ssl = SSL_new((SSL_CTX*)m_ctx)) == false)
return false;
m_SSLActive = true;
return true;
#else
return false;
#endif
}
void itxSocket::SSLFree()
{
#ifdef OPENSSL
if (!m_SSLActive)
return;
SSL_shutdown((SSL*)m_ssl);
SSL_free((SSL*)m_ssl);
SSL_CTX_free((SSL_CTX*)m_ctx);
#endif
}
int itxSocket::SSLSend(char* datatosend, int bytes_to_send)
{
#ifdef OPENSSL
if (!m_SSLActive)
return 0;
if ((m_transferredbytes = SSL_write((SSL*)m_ssl, datatosend, bytes_to_send)) == SOCKET_ERROR)
throw new itxSocketException("itxSocket::SSLSend", this->m_socket);
return m_transferredbytes;
#else
return 0;
#endif
}
int itxSocket::SSLSend(itxString* datatosend)
{
return SSLSend(datatosend->GetBuffer(), datatosend->Len());
}
int itxSocket::SSLReceive(itxString* datatoreceive)
{
#ifdef OPENSSL
if (!m_SSLActive)
return 0;
int err = SOCKET_ERROR - 1;
char szBuff[4096];
datatoreceive->SetEmpty();
while (err != SOCKET_ERROR && err != 0)
{
if ((err = SSL_read((SSL*)m_ssl, szBuff, 4096)) == SOCKET_ERROR)
break;
else
{
szBuff[err] = 0;
*datatoreceive += szBuff;
}
}
return datatoreceive->Len();
#else
return 0;
#endif
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxstring.h,v $
* $Revision: 1.42 $
* $Author: massimo $
* $Date: 2002-06-11 11:01:45+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXSTRING_H__
#define __ITXSTRING_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "itxdefines.h"
// Defines
#define DEFAULT_GRANULARITY 10
#define INT_2_CHAR_LEN 21
// This macro sends generic exception info about the current object status
#define CATCHALL(Str, Cursor, Bufsize, Granularity, method) catch(...) { \
char buf[256]; \
char* content = (Str); \
if (strlen(content) > 20) content[20] = 0; \
sprintf(buf, "itxString crashed: content = '%s'; m_Str = 0x%p; m_Cursor = 0x%p; m_Bufsize = %d; m_Granularity = %d; Method = %s", \
content, (Str), (Cursor), (Bufsize), (Granularity), (method)); \
throw buf; \
}
//-------------------------------------------------
//---------------- itxString -----------------
//-------------------------------------------------
class itxString
{
private:
//Members
char* m_Str;
char* m_Cursor; //points to the zero termination
unsigned int m_Bufsize; //bytes currently allocated
unsigned int m_Granularity;
public:
//ANSI C string Methods
static int SubstituteSubString(char* base, char* what, char* with, char* retstr);
static int AdjustStr(char* base, char* retstr);
static int RemoveLeadingZeros(char* base, int zleft, char* retstr);
static int Capitalize(char* base, char* retstr);
static int RightInstr(char* base, char* search_arg);
static int MaxTokenLen(char* base, char* sep);
static int CompareNoCase(char* s1, char* s2);
static int EscapeChars(char* source, char** destination);
static void InBlinder(char** source, char blinder);
static char* UCase(char* str);
static char* LCase(char* str);
static char* LTrim(char* str);
static char* RTrim(char* str);
static char* Trim(char* str);
static void HexToAscii(char* source, char* destination, int src_len);
static void AsciiToHex(char* source, char* destination, int src_len);
//Object versions
int SubstituteSubString(char* what, char* with);
int FindSubString(char* what, int start_from = 0);
int IndexOf(char* what);
int AdjustStr();
int RemoveLeadingZeros(int zleft = 0);
int Capitalize();
int RightInstr(char* search_arg);
int MaxTokenLen(char* sep);
itxString& UCase();
itxString& LCase();
itxString& LTrim();
itxString& RTrim();
itxString& Trim();
itxString& Left(int len);
itxString& Right(int len);
itxString& Mid(int start, int len);
itxString& RmBlankChars();
void SetEmpty();
void SetInt(int val);
int InBlinder(char blinder);
int EscapeChars();
int CompareNoCase(itxString* pistr);
int CompareNoCase(char* pistr);
int Compare(itxString* pistr);
int Compare(char* pstr);
void Strcat(char* add);
void Strncpy(char* src, unsigned int nchars);
void PurgeSubString(char* tobepurged);
int GetAt(int pos);
void SetAt(char a, int pos);
char* CVFromDouble(double value, int mindecimal = 1);
void GetToken(char sep, int pos, itxString* dest);
void Currency(int invert = 1);
int Space(int len, int c = ' ');
//Object management
inline char* GetBuffer(){return m_Str;}
inline int Len(){return PTR_DISTANCE(m_Cursor, m_Str);}
inline int IsNull(){return (m_Str == NULL ? 1 : 0);}
inline int IsEmpty(){if (m_Str == NULL) return 0; else return (*m_Str == 0 ? 1 : 0);}
void SetGranularity(unsigned int G){m_Granularity = G;}
void UpdateCursor();
//Operator =
void operator=(itxString& src)
{
try
{
if (src.m_Str == NULL)
{
if (m_Str != NULL)
{
*m_Str = '\0';
m_Cursor = m_Str;
}
}
else
{
register unsigned int l = (unsigned)src.m_Cursor - (unsigned)src.m_Str;
if (m_Bufsize <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, l + 1);
memcpy(m_Str, src.m_Str, l);
m_Cursor = m_Str + l;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "operator=(itxString& src)")
}
//Operator =
void operator=(char c)
{
try
{
if (m_Bufsize <= 1)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, 2);
*m_Str = c;
m_Cursor = m_Str + (c ? 1 : 0);
*m_Cursor = 0;
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "operator=(char c)")
}
//Operator =
void operator=(char* psrc)
{
try
{
if (psrc == NULL)
{
if (m_Str != NULL)
{
*m_Str = '\0';
m_Cursor = m_Str;
}
}
else
{
register unsigned int l = strlen(psrc);
if (m_Bufsize <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, l + 1);
memcpy(m_Str, psrc, l);
m_Cursor = m_Str + l;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "operator=(char* psrc)")
}
//Operator +=
itxString& operator+=(itxString& add)
{
register unsigned int l = (unsigned)add.m_Cursor - (unsigned)add.m_Str;
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Str) <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + l + 1);
memcpy(m_Cursor, add.m_Str, l);
m_Cursor += l;
*m_Cursor = 0;
return *this;
}
//Operator +=
itxString& operator+=(char* padd)
{
if (padd != NULL)
{
register unsigned int l = strlen(padd);
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Str) <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + l + 1);
memcpy(m_Cursor, padd, l);
m_Cursor += l;
*m_Cursor = 0;
}
return *this;
}
//Operator +=
itxString& operator+=(char c)
{
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Str) <= 1)
MALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity);
*m_Cursor = c;
m_Cursor++;
*m_Cursor = 0;
return *this;
}
//Operator +=
itxString& operator+=(int a)
{
char padd[24];
sprintf(padd, "%d", a);
register unsigned int l = strlen(padd);
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Str) <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + l + 1);
memcpy(m_Cursor, padd, l);
m_Cursor += l;
*m_Cursor = 0;
return *this;
}
//Construction/Destruction
itxString(char* sz, int G = DEFAULT_GRANULARITY);
itxString(itxString& src, int G = DEFAULT_GRANULARITY);
itxString(int G = DEFAULT_GRANULARITY);
~itxString();
//InsAt
void InsAt(char* padd, int pos) // pos = 0 means insert at the head
{
if (padd == NULL)
return;
register unsigned int len = this->Len();
register unsigned int l = strlen(padd);
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Str) <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + l + 1);
memmove(m_Str + pos + l, m_Str + pos, len - pos);
memcpy(m_Str + pos, padd, l);
m_Cursor += l;
*m_Cursor = 0;
}
};
#endif // __ITXSTRING_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: auxfile.cpp,v $
* $Revision: 1.47 $
* $Author: massimo $
* $Date: 2002-06-25 18:25:14+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 rom<NAME>
* <EMAIL>
*/
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include "defines.h"
#include "itxtypes.h"
#include "auxfile.h"
DebugFile g_DebugFile;
/*****************************************************************************
------------------------ Global DebugTrace Method --------------------------
*****************************************************************************/
#ifdef MAINT_1 //check if must use dbg
//----------- DebugTrace
void DebugTrace(char* strarg, ...)
{
if (g_DebugFile.m_UseDebug)
{
va_list args;
va_start(args, strarg);
g_DebugFile.Trace(DEFAULT, strarg, args);
va_end(args);
}
}
//----------- DebugTrace2
void DebugTrace2(int type, char* strarg, ...)
{
try
{
if (g_DebugFile.m_UseDebug)
{
va_list args;
va_start(args, strarg);
g_DebugFile.Trace(type, strarg, args);
va_end(args);
}
}
catch(...)
{
throw;
}
}
//----------- TimeTrace
void TimeTrace(char* strarg, ...)
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
{
va_list args;
va_start(args, strarg);
g_DebugFile._TimeTrace(strarg, args);
va_end(args);
}
#endif // TIMETRACE
}
//----------- StartMilliCount
void StartMilliCount()
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
g_DebugFile._StartMilliCount();
#endif // TIMETRACE
}
//----------- StopMilliCount
void StopMilliCount()
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
g_DebugFile._StopMilliCount();
#endif // TIMETRACE
}
//----------- TraceMilliDiff
void TraceMilliDiff(char* msg)
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
g_DebugFile._TraceMilliDiff(msg);
#endif // TIMETRACE
}
//----------- CurrentDateTime
struct tm* CurrentDateTime()
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
return g_DebugFile._CurrentDateTime();
else
return NULL;
#endif // TIMETRACE
return NULL;
}
//----------- CurrentDateTimeStr
char* CurrentDateTimeStr()
{
#ifdef TIMETRACE
if (g_DebugFile.m_UseDebug)
{
struct tm* ptm = g_DebugFile._CurrentDateTime();
return (ptm != NULL ? asctime(ptm) : "");
}
else
return "";
#endif // TIMETRACE
return "-TIMETRACE DISABLED-";
}
//----------- SQLTrace
void SQLTrace(itxSQLConnection* conn)
{
int error_condition = DEFAULT;
itxString errormsg;
memset(conn->m_sqlstate, '\0', ITX_SQL_STATUS_LEN);
memset(conn->m_message, '\0', ITX_SQL_MAX_ERRMSG);
errormsg = "<br>";
//Diagnostic environment errors
SQLGetDiagRec(SQL_HANDLE_ENV, conn->m_henv, 1, conn->m_sqlstate, &(conn->m_nativerr), conn->m_message,
ITX_SQL_MAX_ERRMSG - 1, &(conn->m_msglength));
if (!ISNULL((const char*) conn->m_sqlstate))
{
error_condition = IN_WARNING;
errormsg += " SQL_HANDLE_ENV : ";
errormsg += (char*) conn->m_sqlstate;
errormsg += "<br>";
errormsg += (char*) conn->m_message;
errormsg += "<br>";
}
//Diagnostic db connection errors
SQLGetDiagRec(SQL_HANDLE_DBC, conn->m_hdbc, 1, conn->m_sqlstate, &(conn->m_nativerr), conn->m_message,
ITX_SQL_MAX_ERRMSG - 1, &(conn->m_msglength));
if (!ISNULL((const char*) conn->m_sqlstate))
{
error_condition = IN_WARNING;
errormsg += " SQL_HANDLE_DBC : ";
errormsg += (char*) conn->m_sqlstate;
errormsg += "<br>";
errormsg += (char*) conn->m_message;
errormsg += "<br>";
}
//Diagnostic sql statement errors
SQLGetDiagRec(SQL_HANDLE_STMT, conn->m_hstmt, 1, conn->m_sqlstate, &(conn->m_nativerr), conn->m_message,
ITX_SQL_MAX_ERRMSG - 1, &(conn->m_msglength));
if (!ISNULL((const char*) conn->m_sqlstate))
{
error_condition = IN_WARNING;
errormsg += " SQL_HANDLE_STMT : ";
errormsg += (char*) conn->m_sqlstate;
errormsg += "<br>";
errormsg += (char*) conn->m_message;
errormsg += "<br>";
}
try
{
errormsg += "Last Executed Query: <br>";
errormsg += conn->m_statement;
errormsg += "<br>";
if (error_condition == DEFAULT)
{
errormsg += "ODBC statement completed successfully<br>";
}
}
catch(...)
{
DebugTrace("CATCH INSIDE itxSQLConnection::DebugTrace\n");
}
DebugTrace2(error_condition, "%s", errormsg.GetBuffer());
}
#endif /* MAINT_1 */
/*****************************************************************************
---------------------------- DebugFile METHODS ----------------------------
*****************************************************************************/
DebugFile::DebugFile()
{
m_Debug = NULL;
m_UseDebug = false;
m_Errors = false;
m_ReportLevel = 0;
m_FirstErrorAnchor = false;
}
DebugFile::~DebugFile()
{
if (m_Debug != NULL)
fclose(m_Debug);
}
//----------------------------------------------------------------------
void DebugFile::Open()
{
#ifdef MAINT_1
FILE* dbgnamefp;
if((dbgnamefp = fopen(INI_REL_PATH1, "r")) == NULL)
{
if((dbgnamefp = fopen(INI_REL_PATH2, "r")) == NULL)
dbgnamefp = fopen(INI_REL_PATH0, "r");
}
if(dbgnamefp != NULL)
{
itxString parValue;
itxString pid;
if (ReadDbgname(dbgnamefp, &parValue))
{
#ifdef FCGITANNIT
m_DebugPath = ".";
m_DebugPath += PATH_SEPARATOR;
m_DebugPath += "Tannit_";
//The last part of the name of the dbg file is the pid of the Tannit current instance.
pid.SetInt(m_Sys.PRGetProcessId());
m_DebugPath += pid;
m_DebugPath += TPL_EXT;
#else
// m_DebugPath = ".";
// m_DebugPath += PATH_SEPARATOR;
// m_DebugPath += "Tannit.htm";
m_DebugPath = parValue;
#endif //FCGITANNIT
m_HTML = 1; //TBD: currently force to use html ... maybe forever?
}
fclose(dbgnamefp);
struct tm *newtime; // needed for Start Time
time_t aclock;
if ((m_Debug = fopen(m_DebugPath.GetBuffer(), "w")) != NULL)
{
m_UseDebug = true;
// Start Time
time(&aclock);
newtime = localtime(&aclock);
if (m_HTML)
{
fprintf(m_Debug, "<HTML><BODY bgcolor=\"#FFFFFF\">\n");
fprintf(m_Debug, "<FONT FACE=Verdana SIZE=2><center><table border=1 cellpadding=5>\n");
fprintf(m_Debug, "<tr>\n");
fprintf(m_Debug, "<td>Regular text</td>\n");
fprintf(m_Debug, "<td>Normal internal tracing</td>\n");
fprintf(m_Debug, "</tr>\n");
fprintf(m_Debug, "<tr>\n");
fprintf(m_Debug, "<td><b>Bold text<b></td>\n");
fprintf(m_Debug, "<td>Inside command internal tracing</td>\n");
fprintf(m_Debug, "</tr>\n");
fprintf(m_Debug, "<tr>\n");
fprintf(m_Debug, "<td><FONT COLOR=#0033FF>Blu text</FONT></td>\n");
fprintf(m_Debug, "<td>warning reports: usually bad command usage</td>\n");
fprintf(m_Debug, "</tr>\n");
fprintf(m_Debug, "<tr>\n");
fprintf(m_Debug, "<td><FONT COLOR=#00AA00>Green text</FONT></td>\n");
fprintf(m_Debug, "<td>Tannit API internal errors</td>\n");
fprintf(m_Debug, "</tr>\n");
fprintf(m_Debug, "<tr>\n");
fprintf(m_Debug, "<td><FONT COLOR=#FF0000>Red text</FONT></td>\n");
fprintf(m_Debug, "<td>Tannit internal errors</td>\n");
fprintf(m_Debug, "</tr>\n");
fprintf(m_Debug, "</table></center><hr>\n");
fprintf(m_Debug, "<A HREF=%s>First Error</A>\n", FIRST_ERROR_ANCHOR);
fprintf(m_Debug, "<center>At %s Tannit begins ...</center><hr><br>\n", asctime(newtime));
}
else
{
fprintf(m_Debug, "At %s Tannit begins ...\n", asctime(newtime));
fprintf(m_Debug, NOTHTML_HSEP);
}
}
}
#endif /* MAINT_1 */
}
//----------------------------------------------------------------------
void DebugFile::Close()
{
if (m_Debug != NULL)
fclose(m_Debug);
}
/************************************************************************************
NOME :ReadDbgname
attivita' :ricerca nel file dbgname.par il valore del parametro 'DbgPath'.
*************************************************************************************/
bool DebugFile::ReadDbgname(FILE* dbgfp, itxString* parValue)
{
char* token = NULL;
char* retVal = NULL;
char fileLine[INIT_FILE_LINE_LEN];
if(fseek(dbgfp, 0L, SEEK_SET) != 0)
return false;
// scansione delle linee del file
while (fgets(fileLine, INIT_FILE_LINE_LEN, dbgfp) != 0)
{
// se il primo carattere e' '#' la linea non va letta: e' un commento
if (fileLine[0] == '#')
continue;
// il segno di uguale determina la fine del token candidato a id del parametro:
// si confronta il token con il parametro da cercare
token = strtok(fileLine, "=");
if (strcmp(token, DBGPATH) == 0)
{
retVal = strtok(NULL,"\n");
if (retVal != NULL)
{
*parValue = retVal;
return true; //attualmente leggiamo un solo parametro.
}
}
}
return false;
}
/************************************************************************************
NOME : Trace
attivita' : traccia come una fprintf sul file di debug.
*************************************************************************************/
void DebugFile::Trace(int type, char* strarg, va_list args)
{
#ifdef MAINT_1 //check if must use dbg
if (m_UseDebug)
{
if (type < m_ReportLevel)
return;
//Manage type: html 'open' tags
ManageTypeOpen(type);
try
{
vfprintf(m_Debug, strarg, args);
}
catch(...)
{
fprintf(m_Debug, "OMISSIS: error while tracing.");
}
//Manage type: html 'close' tags
ManageTypeClose(type);
fflush(m_Debug);
}
#endif /* MAINT_1 */
}
/*************************************************************************************
NOME : _TimeTrace
attivita' : traccia come una fprintf sul file di debug il tempo fino ai millisecondi.
*************************************************************************************/
void DebugFile::_TimeTrace(char* strarg, va_list args)
{
#ifdef TIMETRACE
if (m_UseDebug)
{
time_t now;
int millinow;
char* timeline;
m_Sys.TMGetMilliTime(&now, &millinow);
timeline = ctime(&now);
try
{
fprintf(g_DebugFile.m_Debug, "EVENT: ", args);
vfprintf(g_DebugFile.m_Debug, strarg, args);
fprintf(g_DebugFile.m_Debug, " - ", args);
fprintf(g_DebugFile.m_Debug, "TIME IS: %.19s.%hu %s", timeline, millinow, &timeline[20]);
}
catch(...)
{
fprintf(m_Debug, "OMISSIS: argument is too long to trace");
}
if (m_HTML)
fprintf(m_Debug, "<br>\n");
fflush(m_Debug);
}
#endif // TIMETRACE
}
/************************************************************************************
NOME : _StartMilliCount
attivita' : Acquisisce i millisecondi dallo startup del processo.
*************************************************************************************/
void DebugFile::_StartMilliCount()
{
#ifdef TIMETRACE
m_StartMilliCount = clock()*CLOCKS_PER_MILLI;
#endif // TIMETRACE
}
/************************************************************************************
NOME : _StopMilliCount
attivita' : Acquisisce i millisecondi dallo startup del processo.
*************************************************************************************/
void DebugFile::_StopMilliCount()
{
#ifdef TIMETRACE
m_StopMilliCount = clock()*CLOCKS_PER_MILLI;
#endif // TIMETRACE
}
/************************************************************************************
NOME : _TraceMilliDiff
attivita' : stampa la differenza tra m_StartMilliCount e m_StopMilliCount.
*************************************************************************************/
void DebugFile::_TraceMilliDiff(char* msg)
{
#ifdef TIMETRACE
if (m_UseDebug)
{
fprintf(m_Debug, "%s - Difference in milliseconds: %d", msg, m_StopMilliCount - m_StartMilliCount);
if (m_HTML)
fprintf(m_Debug, "<br>\n");
fflush(m_Debug);
}
#endif // TIMETRACE
}
/************************************************************************************
NOME : _CurrentDateTime
attivita' : Returns the current time .
*************************************************************************************/
struct tm* DebugFile::_CurrentDateTime()
{
//Take current time and print it
time_t aclock;
time(&aclock);
return localtime(&aclock);
}
//----------------------------------------------------------------------
void DebugFile::ManageTypeOpen(int type)
{
if (m_HTML != 0)
{
if (!m_FirstErrorAnchor &&
(type == IN_WARNING || type == IN_ERROR || type == IN_TNTAPI))
{ //put the anchor on the first error
m_FirstErrorAnchor = true;
fprintf(m_Debug, "<A NAME=%s></a>", FIRST_ERROR_ANCHOR);
}
for(int i = 0; i<sizeof(int)*8; i++)
{
switch((1<<i) & type)
{
case IN_COMMAND:
fprintf(m_Debug, "<b> template is %s: <br>", m_CurrentTemplate.GetBuffer());
break;
case IN_ERROR:
fprintf(m_Debug, "<FONT COLOR=#FF0000> template is %s: <br>", m_CurrentTemplate.GetBuffer());
m_Errors = true;
break;
case IN_WARNING:
fprintf(m_Debug, "<FONT COLOR=#0033FF> template is %s: <br>", m_CurrentTemplate.GetBuffer());
m_Errors = true;
break;
case IN_TNTAPI:
fprintf(m_Debug, "<FONT COLOR=#00AA00> template is %s: <br>", m_CurrentTemplate.GetBuffer());
m_Errors = true;
break;
case TEMPLATE:
fprintf(m_Debug, "<br><hr><i>");
break;
}
}
}
else
{
for(int i = 0; i<sizeof(int); i++)
{
switch((1<<i) & type)
{
case IN_COMMAND:
fprintf(m_Debug, " ");
break;
case TEMPLATE:
fprintf(m_Debug, NOTHTML_HSEP);
break;
}
}
}
}
//----------------------------------------------------------------------
void DebugFile::ManageTypeClose(int type)
{
if (m_HTML != 0)
{
for(int i = 0; i<sizeof(int)*8; i++)
{
switch((1<<i) & type)
{
case IN_COMMAND:
fprintf(m_Debug, "</b>");
break;
case IN_ERROR:
case IN_WARNING:
case IN_TNTAPI:
fprintf(m_Debug, "</FONT>");
break;
case TEMPLATE:
fprintf(m_Debug, "</i><hr>");
break;
}
}
fprintf(m_Debug, "<br>");
}
else
{
for(int i = 0; i<sizeof(int); i++)
{
switch((1<<i) & type)
{
case TEMPLATE:
fprintf(m_Debug, NOTHTML_HSEP);
break;
}
}
}
}
//----------------------------------------------------------------------
bool DebugFile::Bufferize(itxString* outDebugBuf)
{
if (m_Debug == NULL)
return false;
//Valutazione della Content-length
fseek(m_Debug, 0, SEEK_SET);
int ContentLen = ftell(m_Debug);
fseek(m_Debug, 0, SEEK_END);
ContentLen = ftell(m_Debug) - ContentLen;
rewind(m_Debug);
char* dataBuffer;
if ((dataBuffer = (char*)calloc(ContentLen + 1, sizeof(char))) == NULL)
return false;
fclose(m_Debug);
m_Debug = fopen(m_DebugPath.GetBuffer(), "rb");
//lettura
int numread;
if ((numread = fread(dataBuffer, sizeof(char), ContentLen, m_Debug)) < ContentLen)
return false;
dataBuffer[ContentLen] = 0; // sostituzione del carattere EOF con 0
*outDebugBuf = dataBuffer;
free(dataBuffer);
fclose(m_Debug);
m_Debug = fopen(m_DebugPath.GetBuffer(), "at");
return true;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxthread.cpp,v $
* $Revision: 1.5 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:30+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxthread.h"
//--------------------------------------------------------------
void _Thread::ChangeStackSize(unsigned long S)
{
if (!m_Started)
m_StackSize = S;
}
//--------------------------------------------------------------
void _Thread::Start(void* thisThread)
{
if ((m_THandle = m_Sys.THCreateThread((void*)ThreadStarter, (void*)thisThread, (unsigned int*)&m_TID)) == NULL)
return;
m_Started = 1;
}
//--------------------------------------------------------------
void _Thread::Suspend()
{
if (m_Started)
{
m_Sys.THPauseThread(m_THandle);
m_Suspended = 1;
}
}
//--------------------------------------------------------------
void _Thread::Kill()
{
m_Sys.THTerminateThread(m_THandle);
}
//--------------------------------------------------------------
void _Thread::Resume()
{
if (m_Suspended)
{
m_Sys.THResumeThread(m_THandle);
m_Suspended = 0;
}
}
<file_sep>/* crypt 21/10/1999
*
* utility wrap for the public domain DES implementation by
* <NAME>
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
unsigned short itxEncrypt(
unsigned char* DESKey,
unsigned char* Whitenings,
unsigned char* source,
unsigned char* destination);
unsigned short itxDecrypt(
unsigned char* DESKey,
unsigned char* Whitenings,
unsigned char* source,
unsigned char* destination);
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxlinux.h,v $
* $Revision: 1.6 $
* $Author: administrator $
* $Date: 2002-07-23 17:44:46+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXLINUX_H__
#define __ITXLINUX_H__
#ifdef LINUX
/* -------------------------------------------------------------
* This file is the main header containing all includes, defines
* and other definitions needed to implement the Linux version
* of the itxSystem object.
* -------------------------------------------------------------
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/timeb.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <strstream.h>
#include <errno.h>
#include <ctype.h>
// At moment, we don't know if exists a version od ODBC
// drivers for this platform which implements the standard 3.0,
// so we must define the following to force code in itxsql
// to run with 1.0 version.
#define USE_ODBC_10
// Dummy value here
#define _O_BINARY 1
typedef int SOCKET;
typedef sockaddr_in SOCKADDR_IN;
typedef sockaddr* LPSOCKADDR;
#define ITXCDECL //this must be left blank because _cdecl does not exists.
#define PATH_SEPARATOR_C '/'
#define PATH_SEPARATOR "/"
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#endif //LINUX
#endif //__ITXLINUX_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: commands2.cpp,v $
* $Revision: 1.33 $
* $Author: massimo $
* $Date: 2002-06-25 18:25:15+02 $
*
* More command definition
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <time.h>
#include "itxtypes.h"
#include "commands.h"
#include "templatefile.h"
/*----------------------------------------------------------------------------
Rand
----------------------------------------------------------------------------*/
char* BC_Rand::Execute(char* istr)
{
int maxvalue;
int seed = 0;
m_Output.SetEmpty();
if(m_pParser->PickInt(istr, 1, &maxvalue) == PARAM_NOT_FOUND)
return "";
if(m_pParser->PickInt(istr, 2, &seed) == PARAM_FOUND)
srand((unsigned)seed);
else
srand((unsigned)time(NULL));
m_Output.SetInt(rand() % maxvalue);
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_MakeOp
----------------------------------------------------------------------------*/
#define MAKEOPERATION(op, dleft, dright, resop) \
switch(op) \
{ \
case '%': \
resop = ((int)dleft) % ((int)dright); \
break; \
case '*': \
resop = (dleft) * (dright); \
break; \
case '/': \
if (dright == 0.) \
{throw; break;} \
resop = (dleft) / (dright); \
break; \
case '+': \
resop = (dleft) + (dright); \
break; \
case '-': \
resop = (dleft) - (dright); \
break; \
}
bool BC_MakeOp::MakeMulDivs(itxListPtr* ops, itxListPtr* terms, char op)
{
char* aux;
double* pdleft;
double* pdright;
double resop;
//Execute mult-divs
ops->GetHead();
aux = (char*)ops->GetNext();
int i = 1;
while (aux)
{
if (*aux == op)
{
pdleft = (double*)terms->GetElement(i - 1);
pdright = (double*)terms->GetElement(i);
// MAKEOPERATION(op, *pdleft, *pdright, resop);
switch(op)
{
case '%':
resop = ((int)*pdleft) % ((int)*pdright);
break;
case '*':
resop = (*pdleft) * (*pdright);
break;
case '/':
if (*pdright == 0.)
{
DebugTrace2(IN_WARNING, "Divide by zero\n");
m_pParser->m_ForceExit = 1;
}
else
resop = (*pdleft) / (*pdright);
break;
case '+':
resop = (*pdleft) + (*pdright);
break;
case '-':
resop = (*pdleft) - (*pdright);
break;
}
ops->Remove(i);
*pdleft = resop;
terms->Remove(i);
return true;
}
i++;
aux = (char*)ops->GetNext();
}
return false;
}
char* BC_MakeOp::Execute(char* istr)
{
itxListPtr listop;
itxListPtr listnums;
itxString appo;
char* aux;
char* begterm = NULL;
char termstr[64];
int opcnt;
int i;
int j;
int k;
unsigned int termlen;
itxString input;
double* terms;
double result = 0.;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &input) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
input.Trim();
i = input.GetAt(0);
if (i != '+' && i != '-')
{
appo = "+";
appo += input;
}
else
appo = input;
aux = appo.GetBuffer();
//Build the stack of (pointers to) operators in the input string expression
opcnt = 0;
while ((aux = strpbrk(aux, "+/-*%")) != NULL)
{
listop.Append(aux);
aux++;
opcnt++;
}
try
{
//Extract numbers
terms = new double[opcnt + 1];
begterm = appo.GetBuffer();
listop.GetHead();
aux = (char*)listop.GetNext();
i = 0;
while (begterm && *begterm != 0)
{
if (aux)
{
termlen = (unsigned)aux - (unsigned)begterm;
//must make a strong trim... (to interpret things like "- 1")
j = 0;
k = 0;
while(j<termlen)
{
if (begterm[j] != ' ')
termstr[k++] = begterm[j];
j++;
}
termstr[k] = 0;
}
else
strcpy(termstr, begterm);
terms[i] = atof(termstr);
listnums.Append(&terms[i]);
begterm = (aux ? (++aux) : NULL);
aux = (char*)listop.GetNext();
i++;
}
//Mults, Divs and Mods
while (MakeMulDivs(&listop, &listnums, '/'));
while (MakeMulDivs(&listop, &listnums, '*'));
while (MakeMulDivs(&listop, &listnums, '%'));
//Sums
aux = (char*)listop.GetHead();
double* pd = (double*)listnums.GetHead();
while (aux && pd)
{
result += (*aux == '-' ? -1*(*pd) : *pd);
aux = (char*)listop.GetNext();
pd = (double*)listnums.GetNext();
}
}
catch(...)
{
DebugTrace2(IN_WARNING, "Malformed expression or divide by zero\n");
}
delete [] terms;
char resstr[64] = {0};
if(m_pParser->PickPar(istr, 2, &appo) != PARAM_NOT_FOUND)
sprintf(resstr, appo.GetBuffer(), result);
else
sprintf(resstr, "%f", result);
m_Output = resstr;
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
NewConnection
----------------------------------------------------------------------------*/
char* BC_NewConnection::Execute(char* istr)
{
itxString name;
itxString dsn;
itxString uid;
itxString pwd;
itxString failuremsg;
bool skipFailure = false;
m_Output.SetEmpty();
itxSQLConnection* newconn = NULL;
m_pParser->PickPar(istr, 1, &name);
m_pParser->PickPar(istr, 2, &dsn);
m_pParser->PickPar(istr, 3, &uid);
m_pParser->PickPar(istr, 4, &pwd);
if(m_pParser->PickPar(istr, 5, &failuremsg) != PARAM_NOT_FOUND)
{
skipFailure = true;
}
try
{
newconn = new itxSQLConnection();
if (newconn->Create(name.GetBuffer(), dsn.GetBuffer(), uid.GetBuffer(), pwd.GetBuffer()))
m_pconnections->Put(newconn);
else
{
if(skipFailure )
m_Output=failuremsg;
else
DebugTrace2(IN_WARNING, "Unable to open new connection.\n");
}
}
catch(...)
{
DebugTrace2(IN_WARNING, "Unable to open new connection.\n");
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
SetConnection
----------------------------------------------------------------------------*/
char* BC_SetConnection::Execute(char* istr)
{
itxString name;
itxSQLConnection* setconn = NULL;
m_pParser->PickPar(istr, 1, &name);
try
{
setconn = m_pconnections->Get(name.GetBuffer());
m_pTQRODBCManager->SetConnect(setconn);
}
catch(...)
{
DebugTrace2(IN_WARNING, "Unable to open set connection.\n");
}
return NULL;
}
char* BC_ResetConnection::Execute(char* istr)
{
m_pTQRODBCManager->SetConnect(m_podbcconnection);
return NULL;
}
/*----------------------------------------------------------------------------
Array
----------------------------------------------------------------------------*/
char* BC_Array::Execute(char* istr)
{
itxString arrayname;
int ncols, nrows;
if(m_pParser->PickPar(istr, 1, &arrayname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &nrows) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &ncols) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
try
{
TQR* qres = m_pTQRManager->CreateTQR(arrayname.GetBuffer(), ncols);
for (int irow = 0; irow < nrows; irow++)
{
qres->AddTail();
}
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Unable to create array.\n");
}
return 0;
};
/*----------------------------------------------------------------------------
ArraySet
----------------------------------------------------------------------------*/
char* BC_ArraySet::Execute(char* istr)
{
itxString arrayname;
int irow;
itxString value;
itxString icol;
if(m_pParser->PickPar(istr, 1, &arrayname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &irow) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &icol) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 4, &value) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
try
{
itxString colname;
colname = "f";
colname += icol.GetBuffer();
TQR* qres = m_pTQRManager->Get(arrayname.GetBuffer());
qres->MoveTo(irow);
qres->SetCurrentRecordField(colname.GetBuffer(), value.GetBuffer());
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Unable to set array value.\n");
}
return 0;
};
/*----------------------------------------------------------------------------
ArrayGet
----------------------------------------------------------------------------*/
char* BC_ArrayGet::Execute(char* istr)
{
itxString arrayname;
int irow;
itxString icol;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &arrayname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &irow) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &icol) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
try
{
itxString colname;
colname = "f";
colname += icol.GetBuffer();
TQR* qres = m_pTQRManager->Get(arrayname.GetBuffer());
qres->MoveTo(irow);
m_Output =qres->GetCurrentRecordField(colname.GetBuffer());
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Unable to get array value.\n");
}
return m_Output.GetBuffer();
};
/*----------------------------------------------------------------------------
RemoveChar
----------------------------------------------------------------------------*/
char* BC_RemoveChar::Execute(char* istr)
{
itxString string;
itxString rchar;
itxString schar;
itxString a1;
itxString a2;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &string) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &rchar) == PARAM_NOT_FOUND)
rchar = "\"";
if(m_pParser->PickPar(istr, 3, &schar) == PARAM_NOT_FOUND)
schar = "";
a1 = rchar;
a2 = rchar;
if (a1.Left(1).Compare("$") == 0 && a2.Right(1).Compare("$") == 0)
rchar.InBlinder('$');
a1 = schar;
a2 = schar;
if (a1.Left(1).Compare("\"") == 0 && a2.Right(1).Compare("\"") == 0)
schar.InBlinder('"');
try
{
string.SubstituteSubString(rchar.GetBuffer(), schar.GetBuffer());
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Unable to remove char from string %s\n", string.GetBuffer());
}
m_Output = string;
return m_Output.GetBuffer();
};
/*----------------------------------------------------------------------------
Verinst:
Comando da levare una volta capito cosa fa..
----------------------------------------------------------------------------*/
char* BC_Verinst::Execute(char* istr)
{
itxString user;
itxString code;
if(m_pParser->PickPar(istr, 1, &user) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &code) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if (user.Compare("GALCO_Web_Ges") == 0)
if (code.Compare("0644254002") == 0)
return 0;
else
if (code.Compare("3357539405") == 0)
return 0;
m_pParser->m_ForceExit = 1;
return 0;
};
/*----------------------------------------------------------------------------
CopyFile
----------------------------------------------------------------------------*/
char* BC_CopyFile::Execute(char* istr)
{
itxString from;
itxString to;
FILE *fdfrom;
FILE *fdto;
if(m_pParser->PickPar(istr, 1, &from) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &to) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
fdfrom = fopen(from.GetBuffer(),"rb");
if (!fdfrom)
return NULL;
// Open R/W by owner, R by everyone else
fdto = fopen(to.GetBuffer(),"wb");
if (fdto)
{
int bufsiz = -1;
// Use the largest buffer we can get
for (bufsiz = 0x4000; bufsiz >= 128; bufsiz >>= 1)
{
char *buffer;
buffer = (char *) malloc(bufsiz);
if (buffer)
{
while (1)
{
int n;
n = fread(buffer, sizeof(char), bufsiz, fdfrom);
// the error messages are not handled but three cases are ready for future developing ...
if(ferror(fdfrom)!=0) // if error
{
break;
}
if (n != fwrite(buffer, sizeof(char), (unsigned) n, fdto)) // write error
{
break;
}
if (feof(fdfrom)!=0) // if end of file
{
break;
}
}
free(buffer);
break;
}
}
}
fclose(fdto);
fclose(fdfrom);
return NULL;
};
/*----------------------------------------------------------------------------
Console
----------------------------------------------------------------------------*/
char* BC_Console::Execute(char* istr)
{
char inbuf[1024];
try
{
//Can't accept web requests for this command...sorry.
if (!(m_pCGIRes->cgiServerSoftware == NULL ||
*(m_pCGIRes->cgiServerSoftware) == 0))
return NULL;
m_pCGIRes->Flush("\n\nEntering Tannit console mode...\n\nTNT>");
bool goon = true;
itxString command;
command.SetEmpty();
while (goon && fgets(inbuf, 1000, m_pCGIRes->cgiIn))
{
inbuf[strlen(inbuf)-1] = 0;
command = inbuf;
if (strcmp(inbuf, "?") == 0 || strcmp(inbuf, "help") == 0)
{
itxString cmdlist;
char auxstr[30];
cmdlist.SetEmpty();
for (int ncmd = 0, i = 1; ncmd < m_pParser->m_TotalCount; ncmd++, i++)
{
memset(auxstr, ' ', 30);
cmdlist += m_pParser->m_Command[ncmd]->GetName();
auxstr[30 - strlen(m_pParser->m_Command[ncmd]->GetName())] = 0;
if ((i%3) == 0)
{
i = 0;
cmdlist += "\n";
}
else
cmdlist += auxstr;
}
m_pCGIRes->Flush(cmdlist.GetBuffer());
}
else if (strcmp(inbuf, "exit") == 0)
{
m_pCGIRes->Flush("Exiting Tannit console mode.\n");
goon = false;
}
else
{
command += "*flush()";
m_pParser->Run(command.GetBuffer());
}
if (goon)
printf("\nTNT>");
}
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Console generic exception\n");
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
GetPOSTbody
----------------------------------------------------------------------------*/
char* BC_GetPOSTbody::Execute(char* istr)
{
return m_pCGIRes->m_POSTbody.GetBuffer();
}
/*----------------------------------------------------------------------------
Mail
----------------------------------------------------------------------------*/
char* BC_Mail::Execute(char* istr)
{
itxString smtp_server;
itxString domain;
itxString sender;
itxString subject;
itxString message;
itxString attachments;
itxString recipient;
int result = -1;
m_pParser->PickPar(istr, 1, &smtp_server);
m_pParser->PickPar(istr, 2, &domain);
m_pParser->PickPar(istr, 3, &sender);
m_pParser->PickPar(istr, 4, &subject);
m_pParser->PickPar(istr, 5, &message);
m_pParser->PickPar(istr, 6, &attachments);
sender.PurgeSubString("\n");
sender.PurgeSubString("\r");
attachments.PurgeSubString("\n");
attachments.PurgeSubString("\r");
subject.PurgeSubString("\n");
subject.PurgeSubString("\r");
smtp_server.Trim();
domain.Trim();
sender.Trim();
subject.Trim();
message.Trim();
attachments.Trim();
if (smtp_server.Len() == 0)
return "";
itxSmtp smtp(smtp_server.GetBuffer(), domain.GetBuffer(), sender.GetBuffer());
try
{
int i = 7;
while (m_pParser->PickPar(istr, i, &recipient) == PARAM_FOUND)
{
recipient.PurgeSubString("\n");
recipient.PurgeSubString("\r");
recipient.Trim();
smtp.AddRcpt(recipient.GetBuffer());
recipient.SetEmpty();
i++;
}
if (i == 7)
return "";
smtp.SetSubject(subject.GetBuffer());
smtp.SetBody(message.GetBuffer());
// Attachments
i = 0;
itxString attfile;
while (i >= 0)
{
attfile.SetEmpty();
attachments.GetToken('|', i++, &attfile);
attfile.Trim();
if (attfile.Len() == 0)
i = -1;
else
smtp.AddAttachment(attfile.GetBuffer());
}
if ((result = smtp.Mail()) >= ITXM_CRITICAL_ERROR)
DebugTrace2(IN_COMMAND, "Unable to send mail - SMTP error code: %d.\n", result);
}
catch(...)
{
DebugTrace2(IN_WARNING, "Unable to send mail - SMTP error %d.\n", result);
}
return "";
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include "cgic.h"
#include "tannit.h"
#include "extVars.h"
#include "itxlib.h"
#include <windows.h>
#define cgiStrEq(a, b) (!strcmp((a), (b)))
#define LAST_CHANCHE_TIMER_ID 100
#define LAST_CHANCHE_SECONDS 10
typedef enum
{
cgiEscapeRest,
cgiEscapeFirst,
cgiEscapeSecond
} cgiEscapeState;
typedef enum
{
cgiUnescapeSuccess,
cgiUnescapeMemory
} cgiUnescapeResultType;
extern cgiParseResultType itxCGIParseMultipartInput();
char* cgiServerSoftware;
char* cgiServerName;
char* cgiGatewayInterface;
char* cgiServerProtocol;
char* cgiServerPort;
char* cgiRequestMethod;
char* cgiPathInfo;
char* cgiPathTranslated;
char* cgiScriptName;
char* cgiQueryString;
char* cgiRemoteHost;
char* cgiRemoteAddr;
char* cgiAuthType;
char* cgiRemoteUser;
char* cgiRemoteIdent;
char* cgiContentType;
char* cgiAccept;
char* cgiUserAgent;
char* cgiReferrer;
int cgiContentLength;
/*aggiunte aitecsa*/
char* cgiHttpHost;/*nome letterale dell'host*/
char* cgiCookie;
FILE* cgiIn;
FILE* cgiOut;
/* The first form entry. */
cgiFormEntry* cgiFormEntryFirst;
/* True if CGI environment was restored from a file. */
static int cgiRestored = 0;
static int cgiHexValue[256];
static char* cgiFindTarget = 0;
static cgiFormEntry* cgiFindPos = 0;
/************************* PROTOTIPI *************************/
static void cgiGetenv(char **s, char *var);
static void cgiSetupConstants();
static void cgiFreeResources();
static int cgiFirstNonspaceChar(char *s);
static int cgiStrEqNc(char *s1, char *s2);
static int cgiWriteString(FILE *out, char *s);
static int cgiWriteInt(FILE *out, int i);
static int cgiReadString(FILE *out, char **s);
static int cgiReadInt(FILE *out, int *i);
static cgiParseResultType cgiParseGetFormInput();
static cgiParseResultType cgiParsePostFormInput();
static cgiParseResultType cgiParseFormInput(char *data, int length);
static cgiUnescapeResultType cgiUnescapeChars(char **sp, char *cp, int len);
static cgiFormResultType cgiFormEntryString(cgiFormEntry *e, char *result, int max, int newlines);
static cgiFormEntry* cgiFormEntryFindFirst(char *name);
static cgiFormEntry* cgiFormEntryFindNext();
VOID CALLBACK LastChancheHandler(
HWND hwnd, // handle of window for timer messages
UINT uMsg, // WM_TIMER message
UINT idEvent, // timer identifier
DWORD dwTime // current system time
)
{
/**/if(usedbg){fprintf(debug, "Tannit Program Exiting through the LAST_CHANCHE_TIMER door...now is %d\n", (int)dwTime);fflush(debug);}
exit(0);
// EXIT(0);
}
int main(int argc, char *argv[])
{
int result;
char* cgiContentLengthString;
time_t tm;
struct tm* today;
itxString output;
char pidStr[256];
//Super mega ultra patch del timer come ultima sponda
// int ret = SetTimer(NULL, LAST_CHANCHE_TIMER_ID, LAST_CHANCHE_SECONDS /* 1000*/, (TIMERPROC)LastChancheHandler);
// Inizializzazione dell'eventuale file di debug
usedbg = false;
FILE * dbgnamefp;
dbgnamefp = fopen(".\\cgi-bin\\dbgname.par", "r");
if(dbgnamefp == 0)
{
dbgnamefp = fopen(".\\cgi-itx\\dbgname.par", "r");
if(dbgnamefp == 0)
{
dbgnamefp = fopen("dbgname.par", "r");
}
}
if(dbgnamefp != 0)
{
strcpy(DbgPath, readPar("DbgPath","", dbgnamefp));
if (strstr(DbgPath, "MULTIDBG") != 0)
{
time(&tm);
today = localtime(&tm);
output.SetInt(tm);
sprintf(pidStr, "%d", GetCurrentProcessId()),
strcat(DbgPath, "_");
// strcat(DbgPath, output.GetBuffer());
strcat(DbgPath, pidStr);
strcat(DbgPath, ".dbg");
}
fclose(dbgnamefp);
if ((debug = fopen(DbgPath, "w")) != NULL)
usedbg = true;
if (usedbg)
{
if (strstr(DbgPath, "alloctrc") != 0 )
alloctrc = true;
}
}
/**/if(usedbg){fprintf(debug, "Tannit Program Starting with pid = %d\n", GetCurrentProcessId());fflush(debug);}
//**/if(usedbg){fprintf(debug, "SetTimer returns %d\n", ret);fflush(debug);}
cgiSetupConstants();
cgiGetenv(&cgiServerSoftware, "SERVER_SOFTWARE");
cgiGetenv(&cgiServerName, "SERVER_NAME");
cgiGetenv(&cgiGatewayInterface, "GATEWAY_INTERFACE");
cgiGetenv(&cgiServerProtocol, "SERVER_PROTOCOL");
cgiGetenv(&cgiServerPort, "SERVER_PORT");
cgiGetenv(&cgiRequestMethod, "REQUEST_METHOD");
cgiGetenv(&cgiPathInfo, "PATH_INFO");
cgiGetenv(&cgiPathTranslated, "PATH_TRANSLATED");
cgiGetenv(&cgiScriptName, "SCRIPT_NAME");
cgiGetenv(&cgiQueryString, "QUERY_STRING");
cgiGetenv(&cgiHttpHost, "HTTP_HOST");
cgiGetenv(&cgiRemoteHost, "REMOTE_HOST");
cgiGetenv(&cgiRemoteAddr, "REMOTE_ADDR");
cgiGetenv(&cgiAuthType, "AUTH_TYPE");
cgiGetenv(&cgiRemoteUser, "REMOTE_USER");
cgiGetenv(&cgiRemoteIdent, "REMOTE_IDENT");
cgiGetenv(&cgiContentType, "CONTENT_TYPE");
cgiGetenv(&cgiContentLengthString, "CONTENT_LENGTH");
cgiContentLength = atoi(cgiContentLengthString);
cgiGetenv(&cgiAccept, "HTTP_ACCEPT");
cgiGetenv(&cgiReferrer, "HTTP_REFERER");
cgiGetenv(&cgiUserAgent, "HTTP_USER_AGENT");
if (cgiUserAgent != NULL)
{
if (strstr(cgiUserAgent, "Go!Zilla"))
{
printf("Go!Zilla not supported.");
/**/if(usedbg){fprintf(debug, "%s\n", "Go!Zilla not supported.");fflush(debug);}
exit(23);
}
if (strstr(cgiUserAgent, "downloadaccelerator"))
{
printf("downloadaccelerator not supported.");
/**/if(usedbg){fprintf(debug, "%s\n", "downloadaccelerator not supported.");fflush(debug);}
exit(23);
}
}
cgiGetenv(&cgiCookie, "HTTP_COOKIE");
sprintf(UserAgentSpy, cgiUserAgent);
/**/if(usedbg){fprintf(debug, "cgiServerSoftware:%s\n", cgiServerSoftware );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiServerName:%s\n", cgiServerName );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiGatewayInterface:%s\n", cgiGatewayInterface );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiServerProtocol:%s\n", cgiServerProtocol );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiServerPort:%s\n", cgiServerPort );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiRequestMethod:%s\n", cgiRequestMethod );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiPathInfo:%s\n", cgiPathInfo );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiPathTranslated:%s\n", cgiPathTranslated );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiScriptName:%s\n", cgiScriptName );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiQueryString:%s\n", cgiQueryString );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiHttpHost:%s\n", cgiHttpHost );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiRemoteHost:%s\n", cgiRemoteHost );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiRemoteAddr:%s\n", cgiRemoteAddr );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiAuthType:%s\n", cgiAuthType );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiRemoteUser:%s\n", cgiRemoteUser );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiRemoteIdent:%s\n", cgiRemoteIdent );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiContentType:%s\n", cgiContentType );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiContentLengthString:%s\n", cgiContentLengthString );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiAccept:%s\n", cgiAccept );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiReferrer:%s\n", cgiReferrer );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cgiUserAgent:%s\n", cgiUserAgent );fflush(debug);}
/**/if(usedbg){fprintf(debug, "Cookie:%s\n", cgiCookie );fflush(debug);}
cgiFormEntryFirst = 0;
cgiIn = stdin;
cgiOut = stdout;
cgiRestored = 0;
/* These five lines keep compilers from
producing warnings that argc and argv
are unused. They have no actual function. */
if (argc)
{
if (argv[0])
cgiRestored = 0;
}
if (cgiStrEqNc(cgiRequestMethod, "post"))
{
if (cgiStrEqNc(cgiContentType, "application/x-www-form-urlencoded"))
{
if (cgiParsePostFormInput() != cgiParseSuccess)
{
cgiFreeResources();
return -1;
}
}
/* - C O D I C E A I T E C S A -*/
/*
if (strstr( cgiContentType,"multipart/form-data" ) != NULL)
{
if (itxCGIParseMultipartInput() != cgiParseSuccess)
{
cgiFreeResources();
return -1;
}
}
*/
/* - FINE - C O D I C E A I T E C S A - FINE - */
}
else if (cgiStrEqNc(cgiRequestMethod, "get"))
{
/* The spec says this should be taken care of by
the server, but... it isn't */
cgiContentLength = strlen(cgiQueryString);
if (cgiParseGetFormInput() != cgiParseSuccess)
{
/**/if(usedbg){fprintf(debug, "ATTENZIONE : cgiParseGetFormInput != cgiParseSuccess\n");fflush(debug);}
cgiFreeResources();
exit(-1);
}
}
result = cgiMain();
cgiFreeResources();
/* The following two lines allegedly produce better behavior
when run with the CERN server on some platforms.
Remove them and experiment if you wish. */
fflush(stdout);
// sleep(1);
/**/if(usedbg){fprintf(debug, "TANNIT - D O N E \n");fflush(debug);}
EXIT(2);
return result;
}
static void cgiGetenv(char** s, char* var)
{
*s = getenv(var);
if (!(*s))
*s = "";
}
static cgiParseResultType cgiParsePostFormInput()
{
char* input;
cgiParseResultType result;
if (!cgiContentLength)
return cgiParseSuccess;
input = (char*)malloc(cgiContentLength);
/**/if(alloctrc){fprintf(debug, "- - input:%d - - len:%d\n", input, cgiContentLength );fflush(debug);}
if (!input)
return cgiParseMemory;
if (fread(input, 1, cgiContentLength, cgiIn) != (unsigned int)cgiContentLength)
return cgiParseIO;
result = cgiParseFormInput(input, cgiContentLength);
/**/if(alloctrc){fprintf(debug, "* * input:%d\n", input);fflush(debug);}
free(input);
return result;
}
static cgiParseResultType cgiParseGetFormInput()
{
return cgiParseFormInput(cgiQueryString, cgiContentLength);
}
static cgiParseResultType cgiParseFormInput(char *data, int length)
{
/* Scan for pairs, unescaping and storing them as they are found. */
int pos = 0;
cgiFormEntry *n;
cgiFormEntry *l = 0;
while (pos != length)
{
int foundEq = 0;
int foundAmp = 0;
int start = pos;
int len = 0;
char *attr;
char *value;
while (pos != length)
{
if (data[pos] == '=')
{
foundEq = 1;
pos++;
break;
}
pos++;
len++;
}
if (!foundEq)
break;
if (cgiUnescapeChars(&attr, data+start, len) != cgiUnescapeSuccess)
return cgiParseMemory;
start = pos;
len = 0;
while (pos != length)
{
if (data[pos] == '&')
{
foundAmp = 1;
pos++;
break;
}
pos++;
len++;
}
/* The last pair probably won't be followed by a &, but
that's fine, so check for that after accepting it */
if (cgiUnescapeChars(&value, data+start, len) != cgiUnescapeSuccess)
return cgiParseMemory;
/* OK, we have a new pair, add it to the list. */
n = (cgiFormEntry *) malloc(sizeof(cgiFormEntry));
/**/if(alloctrc){fprintf(debug, "- - n:%d - - len:%d\n", n, sizeof(cgiFormEntry));fflush(debug);}
if (!n)
return cgiParseMemory;
n->attr = attr;
n->value = value;
n->next = 0;
/**/if(usedbg){fprintf(debug, "Acquisizione parametro get (1): %s value: %s\n", attr, value);fflush(debug);}
if (!l)
cgiFormEntryFirst = n;
else
l->next = n;
l = n;
if (!foundAmp)
break;
}
return cgiParseSuccess;
}
cgiUnescapeResultType cgiUnescapeChars(char **sp, char *cp, int len)
{
char* s;
cgiEscapeState escapeState = cgiEscapeRest;
int escapedValue = 0;
int srcPos = 0;
int dstPos = 0;
s = (char*)malloc(len + 1);
/**/if(alloctrc){fprintf(debug, "- - s:%d - - len:%d\n", s, len + 1);fflush(debug);}
if (!s)
return cgiUnescapeMemory;
while (srcPos < len)
{
int ch = cp[srcPos];
switch (escapeState)
{
case cgiEscapeRest:
if (ch == '%')
escapeState = cgiEscapeFirst;
else if (ch == '+')
s[dstPos++] = ' ';
else
s[dstPos++] = ch;
break;
case cgiEscapeFirst:
escapedValue = cgiHexValue[ch] << 4;
/**/if(usedbg){fprintf(debug, "cgiUnescapeChars: 1-escapedValue=%d\n",escapedValue);fflush(debug);}
escapeState = cgiEscapeSecond;
break;
case cgiEscapeSecond:
escapedValue += cgiHexValue[ch];
/**/if(usedbg){fprintf(debug, "cgiUnescapeChars: 2-escapedValue=%d\n",escapedValue);fflush(debug);}
s[dstPos++] = escapedValue;
escapeState = cgiEscapeRest;
break;
}
srcPos++;
}
s[dstPos] = '\0';
*sp = s;
/**/if(usedbg){fprintf(debug, "cgiUnescapeChars: s=%s\n",s);fflush(debug);}
return cgiUnescapeSuccess;
}
static void cgiSetupConstants()
{
for (int i=0; (i < 256); i++)
cgiHexValue[i] = 0;
cgiHexValue['0'] = 0;
cgiHexValue['1'] = 1;
cgiHexValue['2'] = 2;
cgiHexValue['3'] = 3;
cgiHexValue['4'] = 4;
cgiHexValue['5'] = 5;
cgiHexValue['6'] = 6;
cgiHexValue['7'] = 7;
cgiHexValue['8'] = 8;
cgiHexValue['9'] = 9;
cgiHexValue['A'] = 10;
cgiHexValue['B'] = 11;
cgiHexValue['C'] = 12;
cgiHexValue['D'] = 13;
cgiHexValue['E'] = 14;
cgiHexValue['F'] = 15;
cgiHexValue['a'] = 10;
cgiHexValue['b'] = 11;
cgiHexValue['c'] = 12;
cgiHexValue['d'] = 13;
cgiHexValue['e'] = 14;
cgiHexValue['f'] = 15;
}
static void cgiFreeResources()
{
cgiFormEntry *c = cgiFormEntryFirst;
cgiFormEntry *n;
while (c)
{
//**/if(usedbg){fprintf(debug, "c->attr :%s\n", c->attr);fflush(debug);}
//**/if(usedbg){fprintf(debug, "c->value :%s\n", c->value);fflush(debug);}
n = c->next;
/**/if(alloctrc){fprintf(debug, "* * c->attr:%d - %s\n", c->attr, c->attr);fflush(debug);}
free(c->attr);
/**/if(alloctrc){fprintf(debug, "* * c->value:%d - %s\n", c->value, c->value);fflush(debug);}
free(c->value);
/*+++++++++++++++attenzione !!! <-- e' una patch: capire perche' schioppa su questa free!*/
/**/if(alloctrc){fprintf(debug, "* * c:%d\n", c);fflush(debug);}
//free(c);
//**/if(usedbg){fprintf(debug, "1 Freed\n");fflush(debug);}
c = n;
}
/* If the cgi environment was restored from a saved environment,
then these are in allocated space and must also be freed */
if (cgiRestored)
{
free(cgiServerSoftware);
free(cgiServerName);
free(cgiGatewayInterface);
free(cgiServerProtocol);
free(cgiServerPort);
free(cgiRequestMethod);
free(cgiPathInfo);
free(cgiPathTranslated);
free(cgiScriptName);
free(cgiQueryString);
free(cgiRemoteHost);
free(cgiRemoteAddr);
free(cgiAuthType);
free(cgiRemoteUser);
free(cgiRemoteIdent);
free(cgiContentType);
free(cgiAccept);
free(cgiUserAgent);
}
/**/if(usedbg){fprintf(debug, "cgiFreeResources - D O N E \n");fflush(debug);}
}
cgiFormResultType cgiFormString(char *name, char *result, int max)
{
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
strcpy(result, "");
return cgiFormNotFound;
}
return cgiFormEntryString(e, result, max, 1);
}
cgiFormResultType cgiFormStringNoNewlines(char *name, char *result, int max)
{
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
strcpy(result, "");
return cgiFormNotFound;
}
return cgiFormEntryString(e, result, max, 0);
}
cgiFormResultType cgiFormStringMultiple(char* name, char*** result)
{
char** stringArray;
cgiFormEntry* e;
int i;
int total = 0;
/* Make two passes. One would be more efficient, but this
function is not commonly used. The select menu and
radio box functions are faster. */
e = cgiFormEntryFindFirst(name);
if (e != 0)
{
do
{
total++;
}
while ((e = cgiFormEntryFindNext()) != 0);
}
stringArray = (char**)malloc(sizeof(char*) * (total + 1));
/**/if(alloctrc){fprintf(debug, "- - stringArray:%d - - len:%d\n", stringArray, sizeof(char *) * (total + 1));fflush(debug);}
if (!stringArray)
{
*result = 0;
return cgiFormMemory;
}
/* initialize all entries to null; the last will stay that way */
for (i=0; (i <= total); i++)
stringArray[i] = 0;
/* Now go get the entries */
e = cgiFormEntryFindFirst(name);
if (e)
{
i = 0;
do
{
int max = strlen(e->value) + 1;
stringArray[i] = (char *) malloc(max);
/**/if(alloctrc){fprintf(debug, "- - stringArray[%d]:%d - - len:%d\n", i, stringArray[i], max );fflush(debug);}
if (stringArray[i] == 0)
{
/* Memory problems */
cgiStringArrayFree(stringArray);
*result = 0;
return cgiFormMemory;
}
strcpy(stringArray[i], e->value);
cgiFormEntryString(e, stringArray[i], max, 1);
i++;
}
while ((e = cgiFormEntryFindNext()) != 0);
*result = stringArray;
return cgiFormSuccess;
}
else
{
*result = stringArray;
return cgiFormNotFound;
}
}
cgiFormResultType cgiFormStringSpaceNeeded(char *name, int *result)
{
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
*result = 1;
return cgiFormNotFound;
}
*result = strlen(e->value) + 1;
return cgiFormSuccess;
}
static cgiFormResultType cgiFormEntryString(cgiFormEntry *e, char *result, int max, int newlines)
{
char *dp, *sp;
int truncated = 0;
int len = 0;
int avail = max-1;
int crCount = 0;
int lfCount = 0;
dp = result;
sp = e->value;
while (1)
{
int ch;
ch = *sp;
if (len == avail)
{
truncated = 1;
break;
}
/* Fix the CR/LF, LF, CR nightmare: watch for
consecutive bursts of CRs and LFs in whatever
pattern, then actually output the larger number
of LFs. Consistently sane, yet it still allows
consecutive blank lines when the user
actually intends them. */
if ((ch == 13) || (ch == 10))
{
if (ch == 13)
crCount++;
else
lfCount++;
}
else
{
if (crCount || lfCount)
{
int lfsAdd = crCount;
if (lfCount > crCount)
lfsAdd = lfCount;
/* Stomp all newlines if desired */
if (!newlines)
lfsAdd = 0;
while (lfsAdd)
{
if (len == avail)
{
truncated = 1;
break;
}
*dp = 10;
dp++;
lfsAdd--;
len++;
}
crCount = 0;
lfCount = 0;
}
if (ch == '\0')
break; /* The end of the source string */
*dp = ch;
dp++;
len++;
}
sp++;
}
*dp = '\0';
if (truncated)
return cgiFormTruncated;
else if (!len)
return cgiFormEmpty;
else
return cgiFormSuccess;
}
cgiFormResultType cgiFormInteger(char *name, int *result, int defaultV)
{
int ch;
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
*result = defaultV;
return cgiFormNotFound;
}
if (!strlen(e->value))
{
*result = defaultV;
return cgiFormEmpty;
}
ch = cgiFirstNonspaceChar(e->value);
if (!(isdigit(ch)) && (ch != '-') && (ch != '+'))
{
*result = defaultV;
return cgiFormBadType;
}
else
{
*result = atoi(e->value);
return cgiFormSuccess;
}
}
cgiFormResultType cgiFormIntegerBounded(char *name, int *result, int min, int max, int defaultV)
{
cgiFormResultType error = cgiFormInteger(name, result, defaultV);
if (error != cgiFormSuccess)
return error;
if (*result < min)
{
*result = min;
return cgiFormConstrained;
}
if (*result > max)
{
*result = max;
return cgiFormConstrained;
}
return cgiFormSuccess;
}
cgiFormResultType cgiFormDouble(char *name, double *result, double defaultV)
{
int ch;
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
*result = defaultV;
return cgiFormNotFound;
}
if (!strlen(e->value))
{
*result = defaultV;
return cgiFormEmpty;
}
ch = cgiFirstNonspaceChar(e->value);
if (!(isdigit(ch)) && (ch != '.') && (ch != '-') && (ch != '+'))
{
*result = defaultV;
return cgiFormBadType;
}
else
{
*result = atof(e->value);
return cgiFormSuccess;
}
}
cgiFormResultType cgiFormDoubleBounded(char *name, double *result, double min, double max, double defaultV)
{
cgiFormResultType error = cgiFormDouble(name, result, defaultV);
if (error != cgiFormSuccess)
return error;
if (*result < min)
{
*result = min;
return cgiFormConstrained;
}
if (*result > max)
{
*result = max;
return cgiFormConstrained;
}
return cgiFormSuccess;
}
cgiFormResultType cgiFormSelectSingle(char *name, char **choicesText, int choicesTotal, int *result, int defaultV)
{
int i;
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
{
*result = defaultV;
return cgiFormNotFound;
}
for (i=0; (i < choicesTotal); i++)
{
if (cgiStrEq(choicesText[i], e->value))
{
*result = i;
return cgiFormSuccess;
}
}
*result = defaultV;
return cgiFormNoSuchChoice;
}
cgiFormResultType cgiFormSelectMultiple(char *name, char **choicesText, int choicesTotal, int *result, int *invalid)
{
cgiFormEntry* e = cgiFormEntryFindFirst(name);
int i;
int hits = 0;
int invalidE = 0;
for (i=0; (i < choicesTotal); i++)
result[i] = 0;
if (!e)
{
*invalid = invalidE;
return cgiFormNotFound;
}
do
{
int hit = 0;
for (i=0; (i < choicesTotal); i++)
{
if (cgiStrEq(choicesText[i], e->value))
{
result[i] = 1;
hits++;
hit = 1;
break;
}
}
if (!(hit))
invalidE++;
}
while ((e = cgiFormEntryFindNext()) != 0);
*invalid = invalidE;
if (hits)
return cgiFormSuccess;
else
return cgiFormNotFound;
}
cgiFormResultType cgiFormCheckboxSingle(char *name)
{
cgiFormEntry* e = cgiFormEntryFindFirst(name);
if (!e)
return cgiFormNotFound;
return cgiFormSuccess;
}
cgiFormResultType cgiFormCheckboxMultiple(char *name, char **valuesText, int valuesTotal, int *result, int *invalid)
{
/* Implementation is identical to cgiFormSelectMultiple. */
return cgiFormSelectMultiple(name, valuesText, valuesTotal, result, invalid);
}
cgiFormResultType cgiFormRadio(char *name, char **valuesText, int valuesTotal, int *result, int defaultV)
{
/* Implementation is identical to cgiFormSelectSingle. */
return cgiFormSelectSingle(name, valuesText, valuesTotal, result, defaultV);
}
void cgiHeaderLocation(char *redirectUrl)
{
fprintf(cgiOut, "Location: %s%c%c", redirectUrl, 10, 10);
}
void cgiHeaderStatus(int status, char *statusMessage)
{
fprintf(cgiOut, "Status: %d %s%c%c", status, statusMessage, 10, 10);
}
void cgiHeaderContentType(char *mimeType)
{
fprintf(cgiOut, "Content-type: %s%c%c", mimeType, 10, 10);
}
#ifndef NO_SYSTEM
int cgiSaferSystem(char *command)
{
char *s;
char *sp;
int i;
int len = (strlen(command) * 2) + 1;
s = (char *) malloc(len);
/**/if(alloctrc){fprintf(debug, "- - s:%d - - len:%d\n", s, len );fflush(debug);}
if (!s)
return -1;
sp = s;
for (i=0; (i < len); i++)
{
if (command[i] == ';')
{
*sp = '\\';
sp++;
}
else if (command[i] == '|')
{
*sp = '\\';
sp++;
}
*sp = command[i];
sp++;
}
*sp = '\0';
return system(s);
}
#endif /* NO_SYSTEM */
cgiEnvironmentResultType cgiWriteEnvironment(char *filename)
{
FILE *out;
cgiFormEntry *e;
/* Be sure to open in binary mode */
out = fopen(filename, "wb");
if (!out)
return cgiEnvironmentIO; /* Can't create file */
if (!cgiWriteString(out, cgiServerSoftware))
goto error;
if (!cgiWriteString(out, cgiServerName))
goto error;
if (!cgiWriteString(out, cgiGatewayInterface))
goto error;
if (!cgiWriteString(out, cgiServerProtocol))
goto error;
if (!cgiWriteString(out, cgiServerPort))
goto error;
if (!cgiWriteString(out, cgiRequestMethod))
goto error;
if (!cgiWriteString(out, cgiPathInfo))
goto error;
if (!cgiWriteString(out, cgiPathTranslated))
goto error;
if (!cgiWriteString(out, cgiScriptName))
goto error;
if (!cgiWriteString(out, cgiQueryString))
goto error;
if (!cgiWriteString(out, cgiRemoteHost))
goto error;
if (!cgiWriteString(out, cgiRemoteAddr))
goto error;
if (!cgiWriteString(out, cgiAuthType))
goto error;
if (!cgiWriteString(out, cgiRemoteUser))
goto error;
if (!cgiWriteString(out, cgiRemoteIdent))
goto error;
if (!cgiWriteString(out, cgiContentType))
goto error;
if (!cgiWriteString(out, cgiAccept))
goto error;
if (!cgiWriteString(out, cgiUserAgent))
goto error;
if (!cgiWriteInt(out, cgiContentLength))
goto error;
e = cgiFormEntryFirst;
while (e)
{
if (!cgiWriteString(out, e->attr))
goto error;
if (!cgiWriteString(out, e->value))
goto error;
e = e->next;
}
fclose(out);
return cgiEnvironmentSuccess;
error:
fclose(out);
/* If this function is not defined in your system,
you must substitute the appropriate
file-deletion function. */
_unlink(filename);
return cgiEnvironmentIO;
}
static int cgiWriteString(FILE *out, char *s)
{
unsigned int len = strlen(s);
cgiWriteInt(out, len);
if (fwrite(s, 1, len, out) != len)
return 0;
return 1;
}
static int cgiWriteInt(FILE *out, int i)
{
if (!fwrite(&i, sizeof(int), 1, out))
return 0;
return 1;
}
cgiEnvironmentResultType cgiReadEnvironment(char *filename)
{
FILE *in;
cgiFormEntry *e, *p;
/* Free any existing data first */
cgiFreeResources();
/* Be sure to open in binary mode */
in = fopen(filename, "rb");
if (!in)
return cgiEnvironmentIO; /* Can't access file */
if (!cgiReadString(in, &cgiServerSoftware))
goto error;
if (!cgiReadString(in, &cgiServerName))
goto error;
if (!cgiReadString(in, &cgiGatewayInterface))
goto error;
if (!cgiReadString(in, &cgiServerProtocol))
goto error;
if (!cgiReadString(in, &cgiServerPort))
goto error;
if (!cgiReadString(in, &cgiRequestMethod))
goto error;
if (!cgiReadString(in, &cgiPathInfo))
goto error;
if (!cgiReadString(in, &cgiPathTranslated))
goto error;
if (!cgiReadString(in, &cgiScriptName))
goto error;
if (!cgiReadString(in, &cgiQueryString))
goto error;
if (!cgiReadString(in, &cgiRemoteHost))
goto error;
if (!cgiReadString(in, &cgiRemoteAddr))
goto error;
if (!cgiReadString(in, &cgiAuthType))
goto error;
if (!cgiReadString(in, &cgiRemoteUser))
goto error;
if (!cgiReadString(in, &cgiRemoteIdent))
goto error;
if (!cgiReadString(in, &cgiContentType))
goto error;
if (!cgiReadString(in, &cgiAccept))
goto error;
if (!cgiReadString(in, &cgiUserAgent))
goto error;
if (!cgiReadInt(in, &cgiContentLength))
goto error;
p = 0;
while (1)
{
e = (cgiFormEntry *) malloc(sizeof(cgiFormEntry));
/**/if(alloctrc){fprintf(debug, "- - e:%d - - len:%d\n", e, sizeof(cgiFormEntry) );fflush(debug);}
if (!e)
{
cgiFreeResources();
fclose(in);
return cgiEnvironmentMemory;
}
if (!cgiReadString(in, &e->attr))
{
/* This means we've reached the end of the list. */
/**/if(alloctrc){fprintf(debug, "* * e:%d\n", e);fflush(debug);}
free(e);
break;
}
if (!cgiReadString(in, &e->value))
{
/**/if(alloctrc){fprintf(debug, "* * e:%d\n", e);fflush(debug);}
free(e);
goto error;
}
e->next = 0;
if (p)
p->next = e;
else
cgiFormEntryFirst = e;
p = e;
}
fclose(in);
cgiRestored = 1;
return cgiEnvironmentSuccess;
error:
cgiFreeResources();
fclose(in);
return cgiEnvironmentIO;
}
static int cgiReadString(FILE *in, char **s)
{
unsigned int len;
cgiReadInt(in, (int *) &len);
*s = (char *) malloc(len + 1);
/**/if(alloctrc){fprintf(debug, "- - *s:%d - - len:%d\n", *s, len + 1 );fflush(debug);}
if (!(*s))
return 0;
if (fread(*s, 1, len, in) != len)
return 0;
(*s)[len] = '\0';
return 1;
}
static int cgiReadInt(FILE *out, int *i)
{
if (!fread(i, sizeof(int), 1, out))
return 0;
return 1;
}
static int cgiStrEqNc(char *s1, char *s2)
{
while(1)
{
if (!(*s1))
{
if (!(*s2))
return 1;
else
return 0;
}
else if (!(*s2))
return 0;
if (isalpha(*s1))
{
if (tolower(*s1) != tolower(*s2))
return 0;
}
else if ((*s1) != (*s2))
return 0;
s1++;
s2++;
}
}
static cgiFormEntry *cgiFormEntryFindFirst(char *name)
{
cgiFindTarget = name;
cgiFindPos = cgiFormEntryFirst;
return cgiFormEntryFindNext();
}
static cgiFormEntry* cgiFormEntryFindNext()
{
while (cgiFindPos)
{
cgiFormEntry* c = cgiFindPos;
cgiFindPos = c->next;
if (!strcmp(c->attr, cgiFindTarget))
return c;
}
return 0;
}
static int cgiFirstNonspaceChar(char *s)
{
int len = strspn(s, " \n\r\t");
return s[len];
}
void cgiStringArrayFree(char **stringArray)
{
char *p;
p = *stringArray;
while (p)
{
/**/if(alloctrc){fprintf(debug, "* * p:%d\n", p);fflush(debug);}
free(p);
stringArray++;
p = *stringArray;
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : tntapiimpl.h
| TAB : 2 spaces
|
| DESCRIPTION : External modules interface object declaration:
| the manager of all exposed Tannit resources.
|
|
*/
#ifndef _TNTAPIIMPL_H_
#define _TNTAPIIMPL_H_
#include "tnt.h"
#include "parser.h"
#include "tqr.h"
#include "tqrodbc.h"
#include "cgiresolver.h"
/*****************************************************************************
TNTAPIImpl
-----------------------------------------------------------------------------
This is the object used to export ALL the resources toward every
Tannit addon module.
*****************************************************************************/
class TNTAPIImpl : public TNTAPI
{
public:
Parser* m_pParser;
TQRManager* m_pTQRManager;
TQRODBCManager* m_pTQRODBCManager;
CGIResolver* m_pCGIResolver;
//CGIResolver Interface
int _GetPRMValue(char* param_name, char* param_value, int* bufdim);
int _GetQueryStringVal(char* var_name, char* var_value, int* bufdim);
// Parser Interface
int _PickInt(char* inputstr, int par_pos, int* retval);
int _PickDouble(char* inputstr, int par_pos, double* retval);
int _PickString(char* inputstr, int position, char* retval, int* bufdim);
int _PICKSTRING(char* inputstr, int par_pos, void* retstr);
// TQRManager Interface
void* _TQRCreate(char* queryname, int numfields);
void _TQRLoadDataBuffer(char* tqrname, int tqrcols, char recsep, char fieldsep, char* buffer);
bool _TQRExist(char* tqrname);
void _TQRRewind(char* tqrname);
void _TQRMoveFirst(char* tqrname);
void _TQRMoveNext(char* tqrname);
void _TQRMoveLast(char* tqrname);
void _TQRMoveTo(char* tqrname, int irow);
char* _TQRGetField(char* tqrname, char* colname);
void _TQRDelete(char* tqrname);
void _TQRFilter(char* source, char* field, char* value, char* destination);
int _TQRRecordCount(char* source);
// TQRODBCManager Interface
void _ODBCConnect(char* dsn, char* uid, char* pwd);
int _ODBCExecute(char* tqrname, char* query, int firstRec = STARTING_ROW, int recsToStore = ROWS_TO_STORE);
void* _ODBCGetCurrentConnection();
TNTAPIImpl(void* tannit);
TNTAPIImpl();
~TNTAPIImpl();
};
#endif /* _TNTAPIIMPL_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
extern char BgMain[PAR_VALUE_LEN], BgMenu[PAR_VALUE_LEN], BgTop[PAR_VALUE_LEN], BgLeft[PAR_VALUE_LEN];
extern char BgRight[PAR_VALUE_LEN], BgBott[PAR_VALUE_LEN], TplDir[PAR_VALUE_LEN], CrudeTplDir[PAR_VALUE_LEN], WebHome[PAR_VALUE_LEN];
extern char CgiDir[PAR_VALUE_LEN] ,CgiName[PAR_VALUE_LEN], PrepropKey[PAR_VALUE_LEN], PreviewKey[PAR_VALUE_LEN], NormviewKey[PAR_VALUE_LEN], PrepKeyTag[PAR_VALUE_LEN];
extern char ImgDir[PAR_VALUE_LEN], FileDir[PAR_VALUE_LEN], Odbcdsn[PAR_VALUE_LEN], Odbcuid[PAR_VALUE_LEN];
extern char Odbcpwd[PAR_VALUE_LEN], WebUrl[PAR_VALUE_LEN], LoginTable[PAR_VALUE_LEN], PwdField[PAR_VALUE_LEN];
extern char LoginField[PAR_VALUE_LEN], ExtrTable[PAR_VALUE_LEN], IdField[PAR_VALUE_LEN], ExtrField[PAR_VALUE_LEN];
extern char LangTagGet[PAR_VALUE_LEN], LangTable[PAR_VALUE_LEN], LangNameField[PAR_VALUE_LEN], LangCodeField[PAR_VALUE_LEN];
extern char TransTable[PAR_VALUE_LEN], TransTagField[PAR_VALUE_LEN], DefaultLanguageId[PAR_VALUE_LEN];
extern char UploadDir[PAR_VALUE_LEN],AllowUpload[PAR_VALUE_LEN];
extern char CorrTable[PAR_VALUE_LEN], CorrUserField[PAR_VALUE_LEN], CorrCodeField[PAR_VALUE_LEN];
extern char CorrAppDir[PAR_VALUE_LEN], CorrFileName[PAR_VALUE_LEN], CorrDndStatus[PAR_VALUE_LEN];
extern char CorrDnDir[PAR_VALUE_LEN], Llu[PAR_VALUE_LEN], Rtp[PAR_VALUE_LEN];
extern char UserAgentSpy[256];
extern char FFace1[PAR_VALUE_LEN], FFace2[PAR_VALUE_LEN], FSize[PAR_VALUE_LEN], FStyle[PAR_VALUE_LEN], FColor[PAR_VALUE_LEN], FDecor[PAR_VALUE_LEN], Lheight[PAR_VALUE_LEN];
extern char DbgPath[PAR_VALUE_LEN], CooTimeDelay[PAR_VALUE_LEN], CooURLEscape[PAR_VALUE_LEN];
extern char TargetTplField[PAR_VALUE_LEN],TplTable[PAR_VALUE_LEN],TplTableId[PAR_VALUE_LEN], TplTableName[PAR_VALUE_LEN];
extern char CurrentTpl[MAX_TPL_NESTS][TPL_NAME_LEN], ContextField[PAR_VALUE_LEN],ContextTag[PAR_VALUE_LEN];
extern char ForbiddenChars[PAR_VALUE_LEN];
extern int TntRequestType, TplNest;
// dopo il porting, da riaggiornare
extern char SSDir[PAR_VALUE_LEN];
extern TannitQueryResult* QQres;
extern int Rumble;
extern char QueryLabel[128];
extern bool usedbg, alloctrc;
extern char* cgiCookie;
extern struct QueryResult * QueryResultSet[QUERY_NUMBER];
extern StrStack * cycleStk;
extern StrStack * queryStk;
extern TplVarsStrct TplVars;
extern int QueryCounter;
extern int ReadCycle[CYC_NESTING_DEPTH];
extern int ValidBlock[CYC_NESTING_DEPTH];
extern int CndLevel, CycLevel;
extern int LockLoop;
extern FILE* debug;
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsql.cpp,v $
* $Revision: 1.8 $
* $Author: administrator $
* $Date: 2002-07-23 17:44:45+02 $
*
* Implementation of the itxSQLConnection object (ODBC connection wrapper)
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __ITX_TNTSQL_CPP__
#define __ITX_TNTSQL_CPP__
#endif
#include <time.h>
#include <memory.h>
#include "itxsql.h"
#include "itxsystem.h"
#define SQBOOL(a) (SQL_SUCCEEDED(a)? true : false)
itxSQLConnection::itxSQLConnection()
{
m_henv = 0;
m_hdbc = 0;
m_hstmt = 0;
m_cols = 0;
m_rows = 0;
}
bool itxSQLConnection::Create(char* dsn, char* uid, char* pwd)
{
if (IsConnected())
return true;
SQLRETURN retcode;
m_dsn = dsn;
m_usr = uid;
m_pwd = pwd;
#ifdef USE_ODBC_10
retcode = SQLAllocEnv(&m_henv); /*Allocate environment handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLAllocConnect(m_henv, &m_hdbc);
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLConnect(m_hdbc, (SQLCHAR*) dsn, SQL_NTS, /* Connect to data source */
(SQLCHAR*) uid, SQL_NTS,(SQLCHAR*) pwd, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmt); /* Allocate statement handle */
}
}
#else //ODBC 3.0
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_henv); /*Allocate environment handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLSetEnvAttr(m_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); /* Set the ODBC version environment attribute */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &m_hdbc); /* Allocate connection handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLConnect(m_hdbc, (SQLCHAR*) dsn, SQL_NTS, /* Connect to data source */
(SQLCHAR*) uid, SQL_NTS,(SQLCHAR*) pwd, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmt); /* Allocate statement handle */
}
}
}
#endif
return SQBOOL(retcode);
}
bool itxSQLConnection::Create(char* name, char* dsn, char* uid, char* pwd)
{
m_name = name;
return Create(dsn, uid, pwd);
}
bool itxSQLConnection::Create()
{
return Create(m_dsn.GetBuffer(), m_usr.GetBuffer(), m_pwd.GetBuffer());
}
bool itxSQLConnection::SetAttributes(int attr, void* value, int valuelen)
{
SQLRETURN retcode;
retcode = SQLSetConnectAttr(m_hdbc, (SQLINTEGER) attr, (SQLPOINTER) value, (SQLINTEGER) valuelen);
return SQBOOL(retcode);
}
bool itxSQLConnection::ManualCommit()
{
return SetAttributes(SQL_ATTR_AUTOCOMMIT, (void*) SQL_AUTOCOMMIT_OFF, 0);
}
bool itxSQLConnection::AutoCommit()
{
return SetAttributes(SQL_ATTR_AUTOCOMMIT, (void*) SQL_AUTOCOMMIT_ON, 0);
}
bool itxSQLConnection::Commit()
{
SQLRETURN retcode;
retcode = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_COMMIT);
return SQBOOL(retcode);
}
bool itxSQLConnection::Rollback()
{
SQLRETURN retcode;
retcode = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_ROLLBACK);
return SQBOOL(retcode);
}
#if 0
// Versione per i DSN su file: bisogna valorizzare il parametro ODBCDSN nel prm
// con la stringa 'FILEDSN=nome_file_dsn;'
bool itxSQLConnection::Create(char* dsn, char* uid = "", char* pwd = "")
{
char OutStr[1024];
SQLRETURN retcode;
SQLSMALLINT outstrlen;
#ifdef USE_ODBC_10
DebugTrace2(DEFAULT, "itxSQLConnection::Create (file DSN version) not yet implemented on this platform.\n");
#else //ODBC 3.0
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_henv); /*Allocate environment handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLSetEnvAttr(m_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); /* Set the ODBC version environment attribute */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &m_hdbc); /* Allocate connection handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLDriverConnect(m_hdbc, NULL, (SQLCHAR*)dsn, SQL_NTS, (SQLCHAR*)OutStr, 1024, &outstrlen, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(retcode))
retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmt); /* Allocate statement handle */
else
{
char sqlstate[10];
SQLINTEGER nativerr;
char msg[1024];
SQLSMALLINT msglength;
SQLGetDiagRec(SQL_HANDLE_DBC, m_hdbc, 1, (SQLCHAR*)sqlstate, &nativerr, (SQLCHAR*)msg, 1024, &msglength);
}
}
}
}
#endif
return SQBOOL(retcode);
}
#endif
bool itxSQLConnection::BindCol(int col, char* value, int size, SQLSMALLINT target_type)
{
SQLRETURN retcode;
retcode = SQLBindCol(m_hstmt, (unsigned short)(col+1), target_type, (SQLPOINTER) value, size, &m_ind);
return SQBOOL(retcode);
}
bool itxSQLConnection::BindCol(int col, float* value, int size)
{
SQLRETURN retcode;
retcode = SQLBindCol(m_hstmt, (unsigned short)(col+1), SQL_C_FLOAT, (SQLPOINTER) value, size, &m_ind);
return SQBOOL(retcode);
}
// statement must be a null-terminated string
bool itxSQLConnection::Execute(char* statement)
{
SQLRETURN retcode;
if (m_hstmt == 0)
return false;
memset(m_statement, '\0', ITX_QRS_MAX_QUERY_LEN);
memcpy(m_statement, statement, strlen(statement));
m_cols = 0;
retcode = SQLExecDirect(m_hstmt, (unsigned char *) statement, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLNumResultCols(m_hstmt, &m_cols);
else
if (retcode == SQL_NO_DATA)
retcode = SQL_SUCCESS;
return SQBOOL(retcode);
}
// statement must be a null-terminated string
bool itxSQLConnection::Prepare(char* statement)
{
SQLRETURN retcode;
if (m_hstmt == 0)
return false;
memset(m_statement, '\0', ITX_QRS_MAX_QUERY_LEN);
memcpy(m_statement, statement, strlen(statement));
m_cols = 0;
retcode = SQLPrepare(m_hstmt, (unsigned char *) statement, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLNumResultCols(m_hstmt, &m_cols);
return SQBOOL(retcode);
}
bool itxSQLConnection::GetColInfo(short int col, char* name, short* type, long int* size)
{
SQLRETURN retcode;
short int realColNameLen, decimalDigits;
unsigned long int colSize;
SQLSMALLINT nullable;
retcode = SQLDescribeCol(m_hstmt, (short int)(col + 1), (unsigned char*) name, ITX_QRS_MAX_NAME_LEN, &realColNameLen, type, &colSize, &decimalDigits, &nullable);
if (SQL_SUCCEEDED(retcode))
{
colSize = (colSize > ITX_QRS_MAX_FIELD_LEN) ? ITX_QRS_MAX_FIELD_LEN : colSize;
*size = colSize;
}
return SQBOOL(retcode);
}
// start deve essere <= end
bool itxSQLConnection::SkipRecords(int start, int end)
{
SQLRETURN retcode;
int counter = start;
if (start > end)
return true;
retcode = SQLFetch(m_hstmt);
while (counter < end && SQL_SUCCEEDED(retcode))
{
retcode = SQLFetch(m_hstmt);
counter++;
}
return SQBOOL(retcode);
}
bool itxSQLConnection::Fetch()
{
SQLRETURN retcode;
retcode = SQLFetch(m_hstmt);
return SQBOOL(retcode);
}
bool itxSQLConnection::FreeStmt(unsigned short flag)
{
SQLRETURN retcode;
retcode = SQLFreeStmt(m_hstmt, flag);
return SQBOOL(retcode);
}
bool itxSQLConnection::MoreResults()
{
SQLRETURN retcode;
retcode = SQLMoreResults(m_hstmt);
if (SQBOOL(retcode))
retcode = SQLNumResultCols(m_hstmt, &m_cols);
return SQBOOL(retcode);
}
bool itxSQLConnection::GetColsNumber()
{
SQLRETURN retcode;
retcode = SQLNumResultCols(m_hstmt, &m_cols);
return SQBOOL(retcode);
}
bool itxSQLConnection::Destroy()
{
SQLRETURN retcode;
if (!IsConnected())
return true;
retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hstmt);
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLDisconnect(m_hdbc);
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hdbc);
if (SQL_SUCCEEDED(retcode))
SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
}
}
m_henv = 0;
m_hdbc = 0;
m_hstmt = 0;
return SQBOOL(retcode);
}
// GetBinData assumes the record cursor is at the desired position
bool itxSQLConnection::GetBinData(int col, itxBuffer& outbuf)
{
SQLRETURN retcode;
SQLINTEGER appo;
SQLINTEGER datalen = 0;
char aux[1];
retcode = SQLGetData(m_hstmt, col, SQL_C_BINARY, aux, 0, &datalen);
if (SQL_SUCCEEDED(retcode))
{
outbuf.Space(datalen + 10); //paranoic overdim
//ora mi dovrebbe tornare 0 (SQL_SUCCESS): vuol dire che ho finito
char* p = outbuf.GetBuffer();
retcode = SQLGetData(m_hstmt, col, SQL_C_BINARY, p, datalen, &appo);
outbuf.UpdateCursor(datalen);
}
return SQBOOL(retcode);
}
//------------------------------------------------------------
// itxSQLConnCollection Implementation
itxSQLConnCollection::itxSQLConnCollection()
{
for (int i = 0; i < ITX_SQL_MAX_CONN; i++)
m_connections[i] = NULL;
}
itxSQLConnection* itxSQLConnCollection::Get(char* name)
{
itxSQLConnection* conn = NULL;
for (int i = 0; i < ITX_SQL_MAX_CONN; i++)
{
if ((m_connections[i]->m_name).Compare(name) == 0)
{
conn = m_connections[i];
break;
}
}
return conn;
}
void itxSQLConnCollection::Put(itxSQLConnection* conn)
{
for (int i = 0; i < ITX_SQL_MAX_CONN; i++)
{
if (m_connections[i] == 0)
{
m_connections[i] = conn;
break;
}
}
}
bool itxSQLConnCollection::CloseAll()
{
int i = 0;
bool result = true;
while (m_connections[i] != 0)
{
result &= m_connections[i]->Destroy();
i++;
}
return result;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: tqrodbc.cpp,v $
* $Revision: 1.32 $
* $Author: administrator $
* $Date: 2002-07-23 17:45:20+02 $
*
* Management of TQRs from ODBC source
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __TQRODBC_CPP__
#define __TQRODBC_CPP__
#endif
#include "auxfile.h"
#include "tqrodbc.h"
#include "itxtypes.h"
// si connette al dsn specificato
// da utilizzare:
// a livello command solo per le connessioni temporanee
// a livello strutturale per le connessioni persistenti
void TQRODBCManager::Connect(char* dsn, char* uid, char* pwd)
{
try
{
if (!m_connected)
m_connected = m_iconn->Create(dsn, uid, pwd);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::Connect\n");
throw;
}
}
// utilizza una connessione attiva
void TQRODBCManager::SetConnect(itxSQLConnection* conn)
{
m_iconn = conn;
m_connected = true;
if (m_iconn == NULL)
m_connected = false;
}
// da utilizzare:
// a livello command solo per le connessioni temporanee
// a livello strutturale per le connessioni persistenti
void TQRODBCManager::Disconnect()
{
try
{
if (m_connected)
m_iconn->Destroy();
m_connected = false;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::Disconnect\n");
throw;
}
}
// chiama l'inquiry per gli attributi dei column header.
void TQRODBCManager::SetTQRColumnsAttributesFromTable(TQR* qres, char* tablename)
{
itxString query;
query = "SELECT * FROM ";
query += tablename;
try
{
if (m_iconn->Prepare(query.GetBuffer()))
{
this->SetTQRColumnsAttributes((void*) qres);
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::SetTQRColumnsAttributes\n");
SQLTrace(m_iconn);
}
}
// chiama l'inquiry per gli attributi dei column header.
// deve essere chiamata dopo che sia stata inviata una Execute su ODBC
void TQRODBCManager::SetTQRColumnsAttributes(TQRHANDLE hqres)
{
TQR* qres = (TQR*) hqres;
short int actualCol;
char colname[COL_NAME_LEN];
short coltype;
long colsize;
try
{
for (actualCol = 0; actualCol < qres->GetColsNum(); actualCol++)
{
memset(colname, '\0', COL_NAME_LEN);
m_iconn->GetColInfo(actualCol, &(colname[0]), &(coltype), &(colsize));
this->SetColumnAttributes(qres, actualCol, colname, coltype, colsize + 1);
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::SetTQRColumnsAttributes\n");
SQLTrace(m_iconn);
}
}
// esegue la query e ritorna il numero di TQR creati ovvero ITXFAILED in caso di insuccesso.
// in caso di pi� TQR di ritorno questi vengono chiamati:
// primo tqr : tqrname,
// secondo tqr : tqrname1,
// terzo tqr : tqrname2
// etc..
int TQRODBCManager::Execute(char* tqrname, char* query, int firstRec, int recsToStore)
{
TQR* qres = NULL;
bool moreresult = true;
int resultsetnum = 0;
long int counter;
int recordsNumber = 0;
bool result;
char tqr_name[QUERY_NAME_LEN];
short int actualCol;
int furtherows = 1;
float jolly[MAX_QUERYHEADER_NUM];
bool isreal[MAX_QUERYHEADER_NUM];
bool somereal = false;
memset(jolly, 0, MAX_QUERYHEADER_NUM * sizeof(float));
try
{
if (m_iconn->Execute(query))
{
while (moreresult)
{
if (m_iconn->m_cols != 0)
{
if (resultsetnum == 0)
sprintf(tqr_name, "%s", tqrname);
else
sprintf(tqr_name, "%s%d", tqrname, resultsetnum);
if ((qres = Get(tqr_name)) != NULL)
Remove(tqr_name);
qres = CreateTQR(tqr_name, m_iconn->m_cols);
resultsetnum++;
if (firstRec < STARTING_ROW) firstRec = STARTING_ROW;
if (recsToStore < 1) recsToStore = ROWS_TO_STORE;
SetRowsParam(qres, firstRec, recsToStore, STARTING_ROW, 0);
SetTQRColumnsAttributes((void*)qres);
if (m_iconn->SkipRecords(1, qres->GetStartingRow() - 1))
{
recordsNumber = firstRec + recsToStore - 1;
for (counter = firstRec; counter <= recordsNumber; counter++)
{
if (qres->AddTail())
{
for (actualCol = 0; actualCol < qres->GetColsNum(); actualCol++)
{
(qres->GetCurrentRecord())->ExpandCol(actualCol, qres->GetColSize(actualCol));
bool bindresult = false;
if (isreal[actualCol] = IsReal(qres, actualCol))
{
somereal = true;
bindresult = m_iconn->BindCol(actualCol, &jolly[actualCol], qres->GetColSize(actualCol));
}
else
bindresult = m_iconn->BindCol(actualCol, qres->GetCurrentRecordField(actualCol), qres->GetColSize(actualCol));
if (!bindresult)
{
DebugTrace2(IN_ERROR, "itxSQLConnection::BindCol\n");
SQLTrace(m_iconn);
break;
}
}
result = m_iconn->Fetch();
if (!result)
{
// should be an SQL_NO_DATA
SQLTrace(m_iconn);
qres->RemoveTail();
break;
}
else if (somereal)
{
for (actualCol = 0; actualCol < qres->GetColsNum(); actualCol++)
{
TQRRecord* currentrecord = (qres->GetCurrentRecord());
if (isreal[actualCol])
{
itxString* Value = currentrecord->GetColValue(actualCol);
Value->CVFromDouble(jolly[actualCol]);
}
}
}
}
else
{
resultsetnum = ITXFAILED;
break;
}
}
// unbind tqr record
m_iconn->FreeStmt(SQL_UNBIND);
// Set cursor to the beginning of tqr and check if
// the statement contained other rows. Eventually counts these rows.
MoveFirst(qres);
qres->SetMoreDBRows(m_iconn->Fetch());
if (qres->GetMoreDBRows())
{
while (m_iconn->Fetch())
furtherows++;
}
else
furtherows--;
qres->SetSourceRecordCount(furtherows + qres->GetStartingRow() - 1 + qres->GetTotalRows());
}
else
resultsetnum = ITXFAILED;
} // if (m_iconn->m_cols != 0)
moreresult = m_iconn->MoreResults();
} // while (moreresult)
}
else
{
SQLTrace(m_iconn);
return ITXFAILED;
}
}
catch(...)
{
if (m_iconn == NULL)
DebugTrace2(IN_WARNING, "Cannot find a valid ODBC connection.\n");
else
{
DebugTrace2(IN_ERROR, "TQRODBCManager::Execute\n");
SQLTrace(m_iconn);
throw;
}
}
return resultsetnum;
}
bool TQRODBCManager::IsAlpha(TQR* qres, char* colname)
{
int type;
try
{
type = qres->GetColType(qres->GetColPos(colname));
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::IsAlpha\n");
throw;
}
if (
(type == SQL_CHAR) | (type == SQL_VARCHAR) | (type == SQL_LONGVARCHAR)
#ifndef USE_ODBC_10
| (type == SQL_WCHAR) | (type == SQL_WVARCHAR) | (type == SQL_WLONGVARCHAR)
#endif
)
return true;
return false;
}
bool TQRODBCManager::IsNumeric(TQR* qres, char* colname)
{
int type;
try
{
type = qres->GetColType(qres->GetColPos(colname));
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::IsNumeric\n");
throw;
}
if ((type == SQL_DECIMAL) | (type == SQL_NUMERIC) |
(type == SQL_SMALLINT) | (type == SQL_INTEGER) |
(type == SQL_DOUBLE) | (type == SQL_BIT) |
(type == SQL_TINYINT) | (type == SQL_BIGINT) |
(type == SQL_BINARY) | (type == SQL_VARBINARY) | (type == SQL_LONGVARBINARY) |
(type == SQL_REAL) | (type == SQL_FLOAT))
return true;
return false;
}
bool TQRODBCManager::IsReal(TQR* qres, int colindex)
{
int type;
try
{
type = qres->GetColType(colindex);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::IsReal\n");
throw;
}
if ((type == SQL_DOUBLE) | (type == SQL_REAL) | (type == SQL_FLOAT))
return true;
return false;
}
bool TQRODBCManager::IsDate(TQR* qres, char* colname)
{
int type;
try
{
type = qres->GetColType(qres->GetColPos(colname));
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::IsDate\n");
throw;
}
if ((type == SQL_TYPE_DATE) | (type == SQL_TYPE_TIME) |
(type == SQL_TYPE_TIMESTAMP) | (type == SQL_INTERVAL_MONTH) |
(type == SQL_INTERVAL_YEAR) | (type == SQL_INTERVAL_YEAR_TO_MONTH) |
(type == SQL_INTERVAL_DAY) | (type == SQL_INTERVAL_HOUR) |
(type == SQL_INTERVAL_MINUTE) | (type == SQL_INTERVAL_SECOND) |
(type == SQL_INTERVAL_DAY_TO_HOUR) |
(type == SQL_INTERVAL_DAY_TO_MINUTE) | (type == SQL_INTERVAL_DAY_TO_SECOND) |
(type == SQL_INTERVAL_HOUR_TO_MINUTE) |
(type == SQL_INTERVAL_MINUTE_TO_SECOND) | (type == SQL_INTERVAL_HOUR_TO_SECOND))
return true;
return false;
}
void TQRODBCManager::Inquiry(char* tqrname, char* query)
{
TQR* qres = NULL;
char tqr_name[QUERY_NAME_LEN];
if (strlen(tqrname) <= QUERY_NAME_LEN)
strcpy(tqr_name, tqrname);
else
{
DebugTrace2(IN_ERROR, "TQRODBCManager::Inquiry received a tqrname parameter value longer than QUERY_NAME_LEN.\n");
return;
}
try
{
if (m_iconn->Prepare(query))
{
qres = this->CreateTQR(tqr_name, m_iconn->m_cols);
this->SetTQRColumnsAttributes((void*) qres);
m_iconn->FreeStmt(SQL_CLOSE);
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRODBCManager::Inquiry\n");
SQLTrace(m_iconn);
throw;
}
}
// just Insert. it's up to the user previously delete the record from Database.
bool TQRODBCManager::BulkInsert(char* target, char* tqrname, ...)
{
va_list morefields;
TQR* qres = NULL;
itxString query;
va_start(morefields, tqrname);
if ((qres = Get(tqrname)) == NULL)
return FALSE;
SetTQRColumnsAttributesFromTable(qres, target);
qres->MoveFirst();
TQRRecord* record;
while ((record = qres->GetCurrentRecord()) != NULL)
{
PrepareSQLInsertStringWith(&query, target, qres, record, morefields);
Execute(NULL, query.GetBuffer(), 0, 0);
qres->MoveNext();
}
return TRUE;
}
bool TQRODBCManager::PrepareSQLInsertStringWith(itxString* query, char* target, TQR* qres, TQRRecord* record, va_list morefields)
{
itxString buffer;
itxString fields;
itxString values;
itxString qvalz;
int i;
char* fieldname;
itxString* fieldvalue;
char* mfieldvalue;
int type;
if (record != NULL)
{
buffer = "";
fields = "";
values = "";
for(i = 0; i < record->colsNumber; i++)
{
type = qres->GetColType(i);
fieldvalue = record->GetColValue(i);
if (!fieldvalue->IsEmpty())
{
fields += qres->GetColName(i);
fields += ",";
switch (type)
{
case 0:
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_NULL_DATA:
case SQL_DATETIME:
case SQL_TYPE_DATE:
case SQL_TYPE_TIME:
case SQL_TYPE_TIMESTAMP:
values += "'";
qvalz = fieldvalue->GetBuffer();
qvalz.SubstituteSubString("'", "''");
values += qvalz;
values += "',";
break;
default:
values += fieldvalue->GetBuffer();
values += ",";
break;
}
}
} // end for
if (morefields != NULL)
{
while ((fieldname = va_arg(morefields, char*)) != NULL)
{
values += "'";
fields += fieldname;
if ((mfieldvalue = va_arg(morefields, char*)) == NULL)
return false;
values += mfieldvalue;
fields += ",";
values += "',";
}
}
fields.Left(fields.Len() - 1);
values.Left(values.Len() - 1);
buffer = "INSERT INTO ";
buffer += target;
buffer += " (";
buffer += fields;
buffer += ") VALUES (";
buffer += values;
buffer += ")";
*query = buffer;
}
return true;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* crypt 21/10/1999
*
* utility wrap for the public domain DES implementation by
* <NAME>
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include "crypt.h"
#include "desx.h"
#define ITX_DES_BLOK 8
void BlockHexToAscii(char* source, char* destination, int block_length)
{
char chex[3];
int i;
for (i = 0; i < block_length; i++)
{
memset(chex, 0, 3);
_itoa((int) ((unsigned char) source[i]), (char*) chex, 16);
if (strlen(chex) < 2)
{
chex[1] = chex[0];
chex[0] = '0';
}
memcpy(destination + 2 * i, chex, 2);
}
}
void BlockAsciiToHex(char* source, char* destination, int block_length)
{
char chex[3];
char* stop;
int i;
char m;
stop = &chex[2];
for (i = 0; i < block_length; i++)
{
memset(chex, 0, 3);
memcpy(chex, &source[i * 2], 2);
m = (char) strtol(chex, &stop, 16);
memcpy(destination + i, &m, 1);
}
}
/*
// (in) source string must be null terminated
// (out) the destination string is the hex representation of the ascii values of the
// characters of the crypted string
*/
unsigned short itxEncrypt(
unsigned char* DESKey,
unsigned char* Whitenings,
unsigned char* source,
unsigned char* destination)
{
struct DESXKey dxKey;
struct DESXContext dxCon;
unsigned char blok[ITX_DES_BLOK];
unsigned char* sourcepos = source;
unsigned char* destinpos = destination;
int sourcelen = 0;
int iblok, nbloks = 0, residual = 0;
memcpy(dxKey.DESKey64, DESKey, ITX_DES_BLOK);
memcpy(dxKey.Whitening64, Whitenings, ITX_DES_BLOK);
DESXKeySetup(&dxCon, &dxKey);
sourcelen = strlen((char*) source);
nbloks = sourcelen / ITX_DES_BLOK;
residual = sourcelen % ITX_DES_BLOK;
for (iblok = 0; iblok < nbloks; iblok++)
{
memcpy(blok, source + iblok * ITX_DES_BLOK, ITX_DES_BLOK);
DESXEncryptBlock(&dxCon, blok, blok);
BlockHexToAscii((char*) blok, (char*) (destination + 2 * iblok * ITX_DES_BLOK), ITX_DES_BLOK);
}
if (residual != 0)
{
/* blanks added on tail to obtain well formed DES_BLOK */
memset(blok, ' ', ITX_DES_BLOK);
memcpy(blok, source + iblok * ITX_DES_BLOK, residual);
DESXEncryptBlock(&dxCon, blok, blok);
BlockHexToAscii((char*) blok, (char*) (destination + 2 * iblok * ITX_DES_BLOK), ITX_DES_BLOK);
}
/* make destination null-terminated */
*(destination + 2 * (iblok + 1) * ITX_DES_BLOK) = 0;
return 0;
}
/*
// (in) source string must be the hex representation of the ascii values of the
// characters of the crypted string
*/
unsigned short itxDecrypt(
unsigned char* DESKey,
unsigned char* Whitenings,
unsigned char* source,
unsigned char* destination)
{
struct DESXKey dxKey;
struct DESXContext dxCon;
unsigned char blok[ITX_DES_BLOK];
unsigned char* sourcepos = source;
unsigned char* destinpos = destination;
int sourcelen = 0;
int iblok, nbloks = 0, i = 0;
memcpy(dxKey.DESKey64, DESKey, ITX_DES_BLOK);
memcpy(dxKey.Whitening64, Whitenings, ITX_DES_BLOK);
DESXKeySetup(&dxCon, &dxKey);
sourcelen = strlen((char*) source);
nbloks = sourcelen / (ITX_DES_BLOK * 2);
BlockAsciiToHex((char*) source, (char*) source, sourcelen / 2);
for (iblok = 0; iblok < nbloks; iblok++)
{
memcpy(blok, source + iblok * ITX_DES_BLOK, ITX_DES_BLOK);
DESXDecryptBlock(&dxCon, blok, blok);
memcpy(destination + iblok * ITX_DES_BLOK, blok, ITX_DES_BLOK);
}
*(destination + iblok * ITX_DES_BLOK) = 0;
/* eventually trims the blanks added on tail */
i = 0;
while ((*(destination + iblok * ITX_DES_BLOK + i - 1)) == ' ')
{
*(destination + iblok * ITX_DES_BLOK + i - 1) = 0;
i--;
}
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxlib.cpp,v $
* $Revision: 1.3 $
* $Author: massimo $
* $Date: 2002-06-07 11:08:26+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxlib.h"
char* itxlibVer()
{
static char a[128];
sprintf(a, "%s%s%s", "AITECSA S.r.l. - All rights reserved.\nThis message from itxlib.lib, version ~ ", CURRENT_VERSION, " ~.");
return a;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __TNT_CRYPT_CPP__
#define __TNT_CRYPT_CPP__
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "tannit.h"
#include "extVars.h"
#include "itxtypes.h"
#include "crypt.h"
extern FILE* debug;
unsigned char key[64] = "itxsecur";
unsigned char wht[64] = "byFabioM";
//unsigned char key[64] = "}!�00-r�";
//unsigned char wht[64] = "r�";
// (in) usercode
// (out) userlabel - must be allocated by the user of the function
int BuildCryptUserLabel(unsigned char* usercode, unsigned char* userlabel)
{
unsigned char label[128];
unsigned char cryptlabel[128];
time_t ltime;
// unsigned short (_cdecl *pf)(unsigned char*, unsigned char*, unsigned char*, unsigned char*);
// pf = (itxEncrypt);
if (usercode == NULL)
return FALSE;
memset(label, 0, 128);
memset(cryptlabel, 0, 128);
time( <ime );
sprintf((char*) &label[0], "%s#%ld", usercode, ltime);
itxEncrypt(&key[0], &wht[0], (unsigned char*) &label[0], (unsigned char*) &cryptlabel[0]);
// pf(&key[0], &wht[0], (unsigned char*) &label[0], (unsigned char*) &cryptlabel[0]);
sprintf((char*) &userlabel[0], "%s", &cryptlabel[0]);
return TRUE;
}
// (in) usercode, userlabel
// (out) return value = difference between actual time and decrypted time stamp
// return value 0 means Failure
long VerifyCryptUserLabel(unsigned char* usercode, unsigned char* userlabel)
{
unsigned char decryptlabel[128];
char* decryptcode = NULL;
char* decrypttime = NULL;
time_t ltime, ctime;
if (usercode == NULL || userlabel == NULL)
return 0;
memset(decryptlabel, 0, 128);
time( <ime );
itxDecrypt(&key[0], &wht[0], userlabel, decryptlabel);
if ((decryptcode = strtok((char*) &decryptlabel[0], "#")) == NULL)
return 0;
if ((decrypttime = strtok(NULL, "#")) == NULL)
return 0;
if (!ISEQUAL((char*) &usercode[0], (char*) &decryptcode[0]))
return 0;
ctime = atol(decrypttime);
return (ltime - ctime);
}
extern void BlockAsciiToHex(char* source, char* destination, int block_length);
void tannitEncrypt(char* source, char* destination)
{
itxEncrypt(&key[0], &wht[0], (unsigned char*) source, (unsigned char*) destination);
//BEG PROVE WIND
//"RrVMYZrK5Og="
// char a[50] = {0};
// BlockAsciiToHex(destination, a, strlen(destination));
//**/if(usedbg){fprintf(debug, "VALORE CRYPTATO IN HEX: %s\n", destination);fflush(debug);}
//**/if(usedbg){fprintf(debug, "VALORE CRYPTATO IN ASCII: %s\n", a);fflush(debug);}
//END PROVE WIND
}
void tannitDecrypt(char* source, char* destination)
{
itxDecrypt(&key[0], &wht[0], (unsigned char*) source, (unsigned char*) destination);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: tqr.h,v $
* $Revision: 1.37 $
* $Author: fabio $
* $Date: 2001-10-09 12:23:43+02 $
*
* Tannit Query Resultset Object and Manager Definition
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __TQR_H__
#define __TQR_H__
#include <stdarg.h>
#include "itxlib.h"
#define COL_NAME_LEN 128
#define QUERY_NAME_LEN 128
#define QUERY_NUMBER 1000
#define STARTING_ROW 1
#define ROWS_TO_STORE 512
#define TQR_NOT_EXIST -1
class TQRRecord
{
friend class TQRColumnHeader;
friend class TQR;
private:
itxString* m_row;
TQRRecord* m_next;
TQRRecord* m_previous;
public:
int colsNumber;
TQRRecord() { m_row = NULL; m_next = NULL; m_previous = NULL; }
TQRRecord(int colnum);
TQRRecord(TQRRecord* previous, int colnum, TQRRecord* next);
~TQRRecord();
void operator=(TQRRecord& src);
void ExpandCol(int colindex, int size);
char* FieldValue(int colindex) {return (colindex < 0 ? NULL : m_row[colindex].GetBuffer());}
void SetField(int colindex, char* colvalue) { if (colindex >= 0) m_row[colindex] = colvalue; }
itxString* GetColValue(int colindex) { return &m_row[colindex]; };
};
class TQRColumnHeader
{
friend class TQR;
private:
itxString name;
short sqlDataType;
long int colummnSize;
public:
void SetAttributes(char* colname, short coltype, long colsize);
};
class TQR
{
friend class TQRManager;
friend class TQRCollection;
private:
itxString id;
int actualRow;
int colsNumber;
int startingRow;
int rowsToStore; // user request
int totalRows; // total rows in current TQR (may be less than user request)
bool m_MoreDBRows; // DB contains more records
int m_SourceRecordCount; // DB source Record count
TQRRecord* current_record;
TQRRecord* recordshead;
TQRRecord* recordstail;
TQRColumnHeader* queryHeader;
public:
TQR() {};
TQR(char* queryname);
TQR(char* queryname, int numfields);
~TQR();
void operator=(TQR* src);
TQR* Clone(char* clonename);
itxString& GetName() { return id; };
void SetName(char* name) { id = name; };
void SetColumnAttributes(int colindex, char* colname, short coltype, long colsize);
int GetColsNum() { return colsNumber; };
long int GetColSize(int colindex) { return queryHeader[colindex].colummnSize; };
int GetColPos(char* colname);
short GetColType(int colindex) { return queryHeader[colindex].sqlDataType; };
char* GetColName(int colindex) { return queryHeader[colindex].name.GetBuffer(); };
bool AddTail();
void RemoveTail();
int GetStartingRow() { return startingRow; }
int GetRowsToStore() { return rowsToStore; }
int GetActualRow() { return actualRow; }
int GetActualPage() { return (((startingRow - 1) / rowsToStore) + 1); }
int GetTotalRows() { return totalRows; }
int GetTotalPages() { return (((m_SourceRecordCount - 1) / rowsToStore) + 1); }
int GetPrevPageRow() { return ((startingRow - rowsToStore) > 0 ? (startingRow - rowsToStore) : 1 ); }
int GetNextPageRow() { return ((startingRow + rowsToStore) > m_SourceRecordCount ? startingRow : (startingRow + rowsToStore)); }
int GetLastPageRow() { return ((GetTotalPages() - 1) * rowsToStore + 1); }
bool GetMoreDBRows() { return m_MoreDBRows; }
int GetSourceRecordCount() { return m_SourceRecordCount; }
TQRRecord* GetCurrentRecord() { return current_record; }
char* GetCurrentRecordField(int colindex) { return (totalRows ? current_record->FieldValue(colindex) : NULL); }
char* GetCurrentRecordField(char* colname) { return (totalRows ? current_record->FieldValue(GetColPos(colname)) : NULL); }
void SetCurrentRecordField(char* colname, char* colvalue) { current_record->SetField(GetColPos(colname), colvalue); }
void SetCurrentRecordField(int colpos, char* colvalue) { current_record->SetField(colpos, colvalue); }
void SetMoreDBRows(bool newval) { m_MoreDBRows = newval; }
void SetSourceRecordCount(int newval) { m_SourceRecordCount = newval; }
void LoadRecordBuffer(char* record, char fieldsep);
void MoveFirst()
{
current_record = recordshead;
current_record != NULL ? actualRow = 1 : actualRow = 0; //BOF
}
void MoveNext()
{
current_record = (current_record == NULL ? NULL : current_record->m_next);
current_record != NULL ? actualRow++ : actualRow = -1; //EOF
}
void MoveLast() { current_record = recordstail; actualRow = totalRows; }
void MoveTo(int rowindex);
};
typedef class TQR* PTQR;
typedef void* TQRHANDLE;
typedef class TQRManager* PTQRMng;
class TQRCollection
{
friend TQRManager;
private:
PTQR m_qres[QUERY_NUMBER];
PTQRMng m_mng[QUERY_NUMBER];
int m_qcount;
public:
TQRCollection() { memset(m_qres, 0, QUERY_NUMBER * sizeof(PTQR)); m_qcount = 0; }
~TQRCollection() {};
TQR* CreateTQR(char* queryname, int numfields);
int Store(PTQRMng, PTQR qres);
void Remove(char* name);
TQR* Retrieve(char* name);
int Index(char* name);
int Exist(char* name);
char* GetCurrentRecordField(char* name, char* colname);
void SetCurrentRecordField(char* name, char* colname, char* colvalue);
void MoveFirst(PTQR qres) { qres->MoveFirst(); }
void MoveNext(PTQR qres) { qres->MoveNext(); }
void MoveLast(PTQR qres) { qres->MoveLast(); }
void MoveTo(PTQR qres, int rowindex) { qres->MoveTo(rowindex); };
};
class TQRManager
{
private:
TQRCollection* m_tqrs;
public:
TQRManager() {};
TQRManager(TQRCollection* tqrs) { m_tqrs = tqrs; }
~TQRManager() {};
void SetTQRCollection(TQRCollection* tqrs) { m_tqrs = tqrs; };
TQR* Get(char* name) { return m_tqrs->Retrieve(name); };
int Store(TQR* qres) { return m_tqrs->Store(this, qres); };
int Exist(char* name) { return m_tqrs->Exist(name); };
void Remove(char* name){ m_tqrs->Remove(name); };
// TQRManager Interface
TQR* CreateTQR(char* queryname);
TQR* CreateTQR(char* queryname, int numfields);
void SetColumnAttributes(char* queryname, int colindex, char* colname, short coltype, long colsize);
void SetName(TQR* qres, char* name);
void LoadDataBuffer(char* tqrname, int tqrcols, char recsep, char fieldsep, char* buffer);
TQR* Filter(char* source, char* field, char* value, char* destination);
TQR* Sample(char* source, char* destination, int destMaxRecs, int seed);
int GetRecordNumber(char* tqrname) { return Get(tqrname)->totalRows; };
void MoveFirst(TQR* qres) { qres->MoveFirst(); }
void MoveNext(TQR* qres) { qres->MoveNext(); }
void MoveLast(TQR* qres) { qres->MoveLast(); }
void MoveTo(TQR* qres, int rowindex ) { qres->MoveTo(rowindex); }
TQRRecord* GetCurrentRecord(PTQR qres) { return qres->GetCurrentRecord(); }
bool AddTail(TQR* qres) { return qres->AddTail(); };
char* GetCurrentRecordField(TQR* qres, char* colname) { return qres->GetCurrentRecordField(colname); }
void SetCurrentRecordField(TQR* qres, char* colname, char* value) { qres->SetCurrentRecordField(colname, value); }
// Internals
void SetColumnAttributes(TQR* qres, int colindex, char* colname, short coltype, long colsize);
void SetRowsParam(TQR* qres, int startingrow, int rowstostore, int actualrow, int totalrows)
{
qres->startingRow = startingrow;
qres->rowsToStore = rowstostore;
qres->actualRow = actualrow;
qres->totalRows = totalrows;
}
};
#endif
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_ITANNIT_CPP__
#define __ITX_ITANNIT_CPP__
#endif
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
#ifdef _ITX_APPC
#include "iappcdim.h"
#endif
#include "itxtypes.h"
#include "itannitdef.h"
#include "iregtp.h"
#include "itannit.h"
#ifdef _ITX_APPC
#define ROLLBACK_TRANSACTION { IConversation_CloseTransaction(log); fclose(fd); return FALSE; }
#endif
//extern itxTP itxtp;
void ZLEADPAD(char* a, int b, char* c)
{
char zcode[256];
memset(zcode, '0', b);
zcode[b+1] = 0;
int l = strlen(a);
memcpy(zcode + b - l, a, l);
sprintf(c, "%s", zcode);
}
// Trova, se esiste, la struttura QueryResult di Tannit identificata con name
// Aggiorna m_current
TannitQueryResult* ITannit::FindEntry(char* name)
{
TannitQueryResult* qres = NULL;
int icount = 0, i = 0;
int qcount = *m_qcount;
if (name != NULL && qcount > 0)
{
while (icount < qcount)
{
if (m_qres[i] != NULL)
{
if (strcmp(m_qres[i]->id, name) == 0)
break;
icount++;
}
i++;
}
if (icount < qcount)
qres = m_qres[i];
}
m_current = qres;
return qres;
}
int ITannit::Store(TannitQueryResult* qres)
{
int i = 0;
while (m_qres[i] != NULL && i < QUERY_NUMBER)
i++;
if (m_qres[i] == NULL)
{
m_qres[i] = qres;
(*m_qcount)++;
m_current = qres;
return i;
}
else
return ITXFAILED;
}
int ITannit::GetIndex(char* name)
{
int icount = 0, i = 0;
int qcount = *m_qcount;
if (name != NULL && qcount > 0)
{
while (icount < qcount)
{
if (m_qres[i] != NULL)
{
if (strcmp(m_qres[i]->id, name) == 0)
break;
icount++;
}
i++;
}
if (icount < qcount)
return i;
}
return -1;
}
// Crea una nuova Entry (QueryResult)
// Aggiorna m_current
// Transaction Program Based
TannitQueryResult* ITannit::AllocateNewEntry(itxTP* tpset, char* name)
{
unsigned short tpid;
TannitQueryResult* qres = NULL;
int i;
if ((tpid = tpset->GetTPID(name)) != NUM_TPAS400)
{
qres = (TannitQueryResult*) calloc(1, sizeof(TannitQueryResult));
if (qres != NULL)
{
if ((qres->queryHeader = (TannitColumnHeader*) calloc(tpset->m_tpas400[tpid].n_fields, sizeof(TannitColumnHeader))) != NULL)
{
strcpy(qres->id, tpset->m_tpas400[tpid].name);
qres->colsNumber = tpset->m_tpas400[tpid].n_fields;
qres->actualRow = STARTING_ROW;
for(i = 0; i < qres->colsNumber; i++)
sprintf(qres->queryHeader[i].name, "f%d\0", i + 1);
Store(qres);
}
else
FREE(qres);
}
}
return qres;
}
// Crea una nuova Entry (QueryResult)
// Aggiorna m_current
// General version
TannitQueryResult* ITannit::AllocateNewEntry(char* queryname, int numfields, ...)
{
TannitQueryResult* qres = NULL;
va_list fieldlist;
char* fieldname;
int ifields;
va_start(fieldlist, numfields);
qres = (TannitQueryResult*) calloc(1, sizeof(TannitQueryResult));
if (qres != NULL)
{
if ((qres->queryHeader = (TannitColumnHeader*) calloc(numfields, sizeof(TannitColumnHeader))) != NULL)
{
strcpy(qres->id, queryname);
qres->colsNumber = numfields;
qres->actualRow = STARTING_ROW;
ifields = 0;
while (ifields < numfields)
{
if ((fieldname = va_arg(fieldlist, char*)) != NULL)
sprintf(qres->queryHeader[ifields].name, "%s\0", fieldname);
else
{
va_start(fieldlist, numfields);
sprintf(qres->queryHeader[ifields].name, "f%d\0", ifields + 1);
}
ifields++;
}
Store(qres);
}
else
FREE(qres);
}
return qres;
}
// Crea una nuova Entry (QueryResult)
// Aggiorna m_current
// SQL Server Based
TannitQueryResult* ITannit::AllocateNewEntry(itxSQLConnection* psqlconn, char* tqrname, char* query, int firstRec, int recsToStore)
{
TannitQueryResult* qres = NULL;
short int actualCol, colsNumber;
TannitColumnHeader* colummnHead;
if (ExecuteSQL(psqlconn, query))
{
qres = (TannitQueryResult*) calloc(1, sizeof(TannitQueryResult));
if (qres != NULL)
{
colsNumber = GetSQLCols(psqlconn);
colummnHead = (TannitColumnHeader*) calloc(colsNumber, sizeof(TannitColumnHeader));
if (colummnHead != NULL)
{
qres->queryHeader = colummnHead;
qres->colsNumber = colsNumber;
strcpy(qres->id, tqrname);
if (firstRec < STARTING_ROW) firstRec = STARTING_ROW;
if (recsToStore < 1) recsToStore = ROWS_TO_STORE;
qres->startingRow = firstRec;
qres->rowsToStore = recsToStore;
qres->actualRow = STARTING_ROW;
qres->totalRows = 0;
for (actualCol = 0; actualCol < colsNumber; actualCol++)
GetSQLColInfo(psqlconn, actualCol, &(qres->queryHeader[actualCol].name[0]),
&(qres->queryHeader[actualCol].sqlDataType),
&(qres->queryHeader[actualCol].colummnSize));
Store(qres);
}
else
FREE(qres);
}
}
return qres;
}
TannitQueryResult* ITannit::Duplicate(TannitQueryResult* qsrc, char* destination)
{
TannitQueryResult* qres = NULL;
int ifields, numfields;
if (qsrc == NULL) return NULL;
numfields = qsrc->colsNumber;
qres = (TannitQueryResult*) calloc(1, sizeof(TannitQueryResult));
if (qres != NULL)
{
if ((qres->queryHeader = (TannitColumnHeader*) calloc(numfields, sizeof(TannitColumnHeader))) != NULL)
{
strcpy(qres->id, destination);
qres->colsNumber = numfields;
qres->startingRow = STARTING_ROW;
qres->actualRow = STARTING_ROW;
qres->rowsToStore = ROWS_TO_STORE;
ifields = 0;
while (ifields < numfields)
{
sprintf(qres->queryHeader[ifields].name, "%s\0", qsrc->queryHeader[ifields].name);
ifields++;
}
Store(qres);
}
else
FREE(qres);
}
return qres;
}
// Riserva lo spazio necessario per la memorizzazione di un nuovo record
// Aggiorna current_record
bool ITannit::AllocateNewRecord(TannitQueryResult* qres)
{
TannitRecord* last_record;
TannitRecord* new_record;
new_record = (TannitRecord*) calloc(1, sizeof(TannitRecord));
if (new_record != NULL)
{
if (qres->colsNumber > 0)
{
new_record->row = (char**) calloc(qres->colsNumber, sizeof(char*));
if (new_record->row == NULL)
{
free(new_record);
return FALSE;
}
}
}
else
return FALSE;
last_record = qres->recPtr;
if (last_record == NULL)
qres->recPtr = new_record;
else
{
while (last_record->next != NULL)
last_record = last_record->next;
last_record->next = new_record;
}
qres->current_record = new_record;
return TRUE;
}
// Si suppone che qres sia gi� posizionata sul record corrente.
int ITannit::StoreField(TannitQueryResult* qres, char* token, int position)
{
char* newfield = NULL;
int result = ITXFAILED;
newfield = (char*) calloc(strlen(token) + 1, sizeof(char));
if (newfield != NULL)
{
strcpy(newfield, token);
// BEGIN LMM 27/06/2000 special char translation support
// itxEBCDToASCII(newfield);
// END LMM 27/06/2000 special char translation support
qres->current_record->row[position] = newfield;
result = position + 1;
}
return result;
}
int ITannit::AllocateFieldSpace(TannitQueryResult* qres, int space, int position)
{
char* newfield = NULL;
int result = ITXFAILED;
newfield = (char*) calloc(space + 1, sizeof(char));
if (newfield != NULL)
{
qres->current_record->row[position] = newfield;
result = position + 1;
}
return result;
}
bool ITannit::CopyRecord(TannitQueryResult* qsrc, TannitRecord* source, TannitQueryResult* qres)
{
int i;
for (i = 0; i < qsrc->colsNumber; i++)
{
AllocateFieldSpace(qres, strlen(source->row[i]), i);
strcpy(qres->current_record->row[i], source->row[i]);
}
return TRUE;
}
void ITannit::DoEmpty()
{
int i;
TannitQueryResult* qres;
int count = (*m_qcount);
i = 0;
while(i < count)
{
qres = m_qres[i];
if (qres != NULL)
{
m_current = qres;
RemoveEntry(qres);
i++;
}
}
}
void ITannit::RemoveEntry(TannitQueryResult* qres)
{
int index = GetIndex(qres->id);
/*
while (qres->recPtr != NULL)
{
qres->current_record = qres->recPtr;
while (qres->current_record->next != NULL)
qres->current_record = qres->current_record->next;
RemoveCurrentRec(qres);
}
*/
FREE(qres->queryHeader);
FREE(qres);
(*m_qcount) -= 1;
m_qres[index] = NULL;
}
void ITannit::RemoveCurrentRec(TannitQueryResult* qres)
{
TannitRecord* previous;
TannitRecord* current;
char* field;
int i = 0;
// Vengono rimossi i campi allocati
for (i = 0; i < qres->colsNumber; i++)
{
if((field = qres->current_record->row[i]) != NULL)
free(field);
}
// Viene rimosso l'array di puntatori per i campi
FREE(qres->current_record->row);
// qres->current_record->row = NULL;
previous = qres->recPtr;
current = previous;
while (current != qres->current_record)
{
previous = current;
current = current->next;
}
previous->next = qres->current_record->next;
if (qres->current_record == qres->recPtr)
qres->recPtr = NULL;
FREE(qres->current_record);
qres->totalRows--;
}
bool ITannit::CheckCurrentRec(int numfield)
{
TannitQueryResult* qres = m_current;
if (qres->colsNumber != numfield)
return FALSE;
return TRUE;
}
// versione posteriore al 11/01/2000. supporta la lista di record.
int ITannit::BuildDataToSend(char* packet, va_list tables)
{
TannitQueryResult* qres;
char record[ITX_APPC_MAX_RECORD_LENGTH];
char* tablename;
int bytes_in_packet = 0;
while ((tablename = va_arg(tables, char*)) != NULL)
{
if ((qres = FindEntry(tablename)) != NULL)
{
for (int i = 0; i < qres->totalRows; i++)
{
memset(record, '\0', ITX_APPC_MAX_RECORD_LENGTH);
SerializeRecord(record, i);
bytes_in_packet += strlen(record);
strcat(packet, record);
}
}
}
return bytes_in_packet;
}
int ITannit::BuildSingleData(char* packet, char* tablename)
{
TannitQueryResult* qres;
char record[ITX_APPC_MAX_RECORD_LENGTH];
int bytes_in_packet = 0;
if ((qres = FindEntry(tablename)) != NULL)
{
memset(record, '\0', ITX_APPC_MAX_RECORD_LENGTH);
SerializeRecord(record, 0);
bytes_in_packet += strlen(record);
strcat(packet, record);
}
return bytes_in_packet;
}
bool ITannit::BuildPacketToSend(char* packet, int progr, PACKET_TYPE ptype, va_list tables)
{
int bytes_in_packet = 0;
switch (ptype)
{
case ITX_APPC_PC_REQ:
if (!BuidHeaderToSend(packet, progr, ptype))
return FALSE;
break;
case ITX_APPC_HS_FTX:
if (!BuidCorrHeaderToSend(packet, progr, ptype))
return FALSE;
break;
default:
if (!BuidHeaderToSend(packet, progr, ptype))
return FALSE;
break;
}
if ((bytes_in_packet = BuildDataToSend(packet, tables)) == 0)
return FALSE;
//BEGIN: modifica del 22/5/2000 per il supporto del carattere di fine informazione
packet[bytes_in_packet + ITX_APPC_HEADER_LENGTH] = ITX_APPC_ENDINFO_SEP;
packet[bytes_in_packet + ITX_APPC_HEADER_LENGTH + 1] = '\0';
//END : modifica del 22/5/2000 per il supporto del carattere di fine informazione
if (bytes_in_packet > (ITX_APPC_MAX_INFO_LENGTH - ITX_APPC_HEADER_LENGTH))
return FALSE;
#ifdef _ITX_APPC
padnstr(packet, ITX_APPC_MAX_INFO_LENGTH, ' ');
#endif
return TRUE;
}
bool ITannit::BuildSinglePacketToSend(char* packet, PACKET_TYPE ptype, char* name)
{
int bytes_in_packet = 0;
switch (ptype)
{
case ITX_APPC_PC_REQ:
if (!BuidHeaderToSend(packet, ITX_APPC_LAST_PACKET, ptype))
return FALSE;
break;
case ITX_APPC_PC_FTX:
if (!BuidCorrHeaderToSend(packet, ITX_APPC_LAST_PACKET, ptype))
return FALSE;
break;
default:
if (!BuidHeaderToSend(packet, ITX_APPC_LAST_PACKET, ptype))
return FALSE;
break;
}
if ((bytes_in_packet = BuildSingleData(packet, name)) == 0)
return FALSE;
packet[bytes_in_packet + ITX_APPC_HEADER_LENGTH] = ITX_APPC_ENDINFO_SEP;
packet[bytes_in_packet + ITX_APPC_HEADER_LENGTH + 1] = '\0';
#ifdef _ITX_APPC
padnstr(packet, ITX_APPC_MAX_INFO_LENGTH, ' ');
#endif
return TRUE;
}
bool ITannit::BuidCorrHeaderToSend(char* packet, int progr, PACKET_TYPE ptype)
{
char appc_header[ITX_APPC_HEADER_LENGTH + 1];
char prg[5];
char tm[20];
time_t ltime;
struct tm *today;
memset(appc_header, ITX_APPC_PC_FILLER, ITX_APPC_HEADER_LENGTH);
appc_header[ITX_APPC_HEADER_LENGTH] = 0;
memset(prg, '0', 5);
appc_header[1] = 'P';
if (ISNULL(m_user))
memset(&appc_header[2], '0', 6);
else
memcpy(&appc_header[2], m_user, strlen(m_user));
memset(&appc_header[8], '0', 2);
sprintf(&appc_header[19], "%05d", 99999);
time( <ime );
today = localtime( <ime );
strftime(tm, 20, "%Y%m%d", today);
memcpy(&appc_header[24], tm, 8);
strcpy(packet, appc_header);
return TRUE;
}
bool ITannit::BuidHeaderToSend(char* packet, int progr, PACKET_TYPE ptype)
{
TannitQueryResult* qres;
char appc_header[ITX_APPC_HEADER_LENGTH + 1];
char prg[5];
char tm[20];
time_t ltime;
struct tm *today;
if ((qres = FindEntry("P00")) == NULL)
return FALSE;
memset(appc_header, ITX_APPC_PC_FILLER, ITX_APPC_HEADER_LENGTH);
appc_header[ITX_APPC_HEADER_LENGTH] = 0;
memset(prg, '0', 5);
appc_header[1] = ptype;
if (ISNULL(qres->current_record->row[3]))
memset(&appc_header[2], '0', 6);
else
{
char ccode[7];
memset(ccode, '\0', 7);
ZLEADPAD(qres->current_record->row[3], 6, ccode);
memcpy(&appc_header[2], ccode, 6);
}
appc_header[8] = '0';
appc_header[9] = '0';
sprintf(&appc_header[19], "%05d", progr);
time( <ime );
today = localtime( <ime );
strftime(tm, 20, "%Y%m%d", today);
memcpy(&appc_header[24], tm, 8);
if (ISNULL(qres->current_record->row[2]))
memset(&appc_header[41], 'I', 1);
else
memcpy(&appc_header[41], qres->current_record->row[2], 1);
strcpy(packet, appc_header);
return TRUE;
}
bool ITannit::DumpTable(FILE* fp, char* name)
{
int i;
TannitQueryResult* qres;
char record[ITX_APPC_MAX_RECORD_LENGTH];
if ((qres = FindEntry(name)) == NULL)
return FALSE;
fprintf(fp, "\n");fflush(fp);
fprintf(fp, "TABLE %s\n", name);fflush(fp);
fprintf(fp, "\t startingRow: %d\n", qres->startingRow);fflush(fp);
fprintf(fp, "\t rowsToStore: %d\n", qres->rowsToStore);fflush(fp);
fprintf(fp, "\t totalRows: %d\n", qres->totalRows);fflush(fp);
fprintf(fp, "\t colsNumber: %d\n", qres->colsNumber);fflush(fp);
fprintf(fp, "\n");fflush(fp);
for (i = 1; i <= qres->totalRows; i++)
{
if (!SerializeRecord(record, i - 1))
return FALSE;
// itxEBCDToASCII(record);
fprintf(fp, "%4d\t\t%s\n", i, record);
fflush(fp);
memset(record, '\0', ITX_APPC_MAX_RECORD_LENGTH);
}
return TRUE;
}
bool ITannit::Dump(FILE* fp)
{
int icount, i;
TannitQueryResult* qres;
time_t tm;
time(&tm);
fprintf(fp, "------------------------------------------------------------\n");
fprintf(fp, " �AITECSA s.r.l.\n");
fprintf(fp, " COMPLETE DUMP OF THE TANNIT QUERYRESULT DATA STRUCTURE SET\n");
fprintf(fp, " %s", ctime(&tm));
fprintf(fp, "------------------------------------------------------------\n");
fprintf(fp, "\n");fflush(fp);
icount = 0;
i = 0;
while (icount < (*m_qcount))
{
if ((qres = m_qres[i]) != NULL)
{
if (!DumpTable(fp, qres->id))
return FALSE;
else
icount++;
}
i++;
}
return TRUE;
}
// pos � l'indice in base 0 del record
bool ITannit::SerializeRecord(char* record, int pos)
{
int i = 0;
int size;
TannitQueryResult* qres = m_current;
TannitRecord* rec = qres->recPtr;
while (i < pos)
{
if (rec != NULL)
rec = rec->next;
else
return FALSE;
i++;
}
size = 0;
for (i = 0; i < qres->colsNumber; i++)
{
if (rec->row[i] == 0)
{
sprintf(record + size,"%c", ITX_APPC_FIELD_SEP);
size += 1;
}
else
{
sprintf(record + size,"%s%c", rec->row[i], ITX_APPC_FIELD_SEP);
size = size + strlen(rec->row[i]) + 1;
}
}
// rimuovo la coda se necessario
i = 0;
while (record[(size - 1) - i - 1] == ITX_APPC_FIELD_SEP)
{
record[(size - 1) - i] = 0;
i++;
}
// aggiungo il terminatore di record
size = strlen(record);
record[size] = ITX_APPC_RECORD_SEP;
record[size + 1] = 0;
return TRUE;
}
// row e field sono espressi in base 1.
char* ITannit::GetValue(char* name, int row, int field)
{
char* value = NULL;
TannitQueryResult* qres = NULL;
int i;
TannitRecord* record;
if ((qres = FindEntry(name)) != NULL)
{
if (row <= qres->totalRows)
{
record = qres->recPtr;
for (i = 1; i < row; i++)
record = record->next;
if (field <= qres->colsNumber)
value = record->row[field - 1];
}
}
return value;
}
// determina la posizione di una colonna di nome fieldname in base 1.
// un valore di ritorno di 0 indica che non � stato trovata.
int ITannit::GetColPos(TannitQueryResult* qres, char* fieldname)
{
int icol = 0;
while (icol < qres->colsNumber)
{
if (strcmp(qres->queryHeader[icol].name, fieldname) == 0)
break;
icol++;
}
if (icol == qres->colsNumber)
icol = 0;
else
icol++;
return icol;
}
TannitRecord* ITannit::GetRecordNumber(char* table, int row)
{
TannitQueryResult* qres = NULL;
int i;
TannitRecord* record = NULL;
if ((qres = FindEntry(table)) != NULL)
{
if (row <= qres->totalRows)
{
record = qres->recPtr;
for (i = 1; i < row; i++)
record = record->next;
}
}
return record;
}
TannitRecord* ITannit::GetRecordNumber(TannitQueryResult* qres, int row)
{
int i;
TannitRecord* record = NULL;
if (row <= qres->totalRows)
{
record = qres->recPtr;
for (i = 1; i < row; i++)
record = record->next;
}
return record;
}
// row e field sono espressi in base 1.
void ITannit::SetValue(char* name, int row, int field, char* entry)
{
TannitQueryResult* qres = NULL;
int i;
TannitRecord* record;
if ((qres = FindEntry(name)) != NULL)
{
if (row <= qres->totalRows)
{
record = qres->recPtr;
for (i = 1; i < row; i++)
record = record->next;
if (field <= qres->colsNumber)
record->row[field - 1] = entry;
}
}
}
bool ITannit::SkipSQLRecords(itxSQLConnection* psqlconn, int start, int end)
{
if (end < start)
return TRUE;
return psqlconn->SkipRecords(start, end);
}
bool ITannit::MoreResultSQL(itxSQLConnection* psqlconn)
{
return psqlconn->MoreResults();
}
bool ITannit::ExecuteSQL(itxSQLConnection* psqlconn, char* stm)
{
return psqlconn->Execute(stm);
}
short int ITannit::GetSQLCols(itxSQLConnection* psqlconn)
{
return psqlconn->m_cols;
}
bool ITannit::GetSQLColInfo(itxSQLConnection* psqlconn, short int col, char* name, short* type, long int* size)
{
return psqlconn->GetColInfo(col, name, type, size);
}
bool ITannit::SelectFromSQL(itxSQLConnection* psqlconn, char* queryname, char* query, int firstRec, int recsToStore)
{
TannitQueryResult* qres = NULL;
long int counter, actualCol;
int recordsNumber = 0;
bool result = TRUE;
// allocazione ed inizializzazione di una nuova TannitQueryResult con le informazioni
// del corrispondente RecordSet su SQL Server
if ((qres = AllocateNewEntry(psqlconn, queryname, query, firstRec, recsToStore)) != NULL)
{
if (SkipSQLRecords(psqlconn, 1, qres->startingRow - 1))
{
recordsNumber = qres->startingRow + qres->rowsToStore - 1;
for (counter = qres->startingRow; counter <= recordsNumber; counter++)
{
if (AllocateNewRecord(qres))
{
for (actualCol = 0; actualCol < qres->colsNumber; actualCol++)
{
AllocateFieldSpace(qres, qres->queryHeader[actualCol].colummnSize, actualCol);
if (!psqlconn->BindCol(actualCol, (qres->current_record)->row[actualCol],
qres->queryHeader[actualCol].colummnSize + 1))
break;
}
result = psqlconn->Fetch();
if (!result)
break;
else
(qres->totalRows)++;
}
else
{
result = FALSE;
break;
}
}
}
else
result = FALSE;
}
else
result = FALSE;
result = psqlconn->FreeStmt();
return result;
}
int ITannit::ExecuteQuery(itxSQLConnection* psqlconn, char* queryname, char* query, int firstRec, int recsToStore)
{
TannitQueryResult* qres = NULL;
short int actualCol, colsNumber;
TannitColumnHeader* colummnHead;
bool moreresult = TRUE;
int resultsetnum = 0;
long int counter;
int recordsNumber = 0;
bool result;
if (ExecuteSQL(psqlconn, query))
{
while (moreresult)
{
colsNumber = GetSQLCols(psqlconn);
if (colsNumber != 0)
{
qres = NULL;
qres = (TannitQueryResult*) calloc(1, sizeof(TannitQueryResult));
if (qres != NULL)
{
colummnHead = (TannitColumnHeader*) calloc(colsNumber, sizeof(TannitColumnHeader));
if (colummnHead != NULL)
{
qres->queryHeader = colummnHead;
qres->colsNumber = colsNumber;
if (resultsetnum == 0)
strcpy(qres->id, queryname);
else
sprintf(qres->id, "%s%d", queryname, resultsetnum);
resultsetnum++;
if (firstRec < STARTING_ROW) firstRec = STARTING_ROW;
if (recsToStore < 1) recsToStore = ROWS_TO_STORE;
qres->startingRow = firstRec;
qres->rowsToStore = recsToStore;
qres->actualRow = STARTING_ROW;
qres->totalRows = 0;
for (actualCol = 0; actualCol < colsNumber; actualCol++)
GetSQLColInfo(psqlconn, actualCol, &(qres->queryHeader[actualCol].name[0]),
&(qres->queryHeader[actualCol].sqlDataType),
&(qres->queryHeader[actualCol].colummnSize));
Store(qres);
if (SkipSQLRecords(psqlconn, 1, qres->startingRow - 1))
{
recordsNumber = qres->startingRow + qres->rowsToStore - 1;
for (counter = qres->startingRow; counter <= recordsNumber; counter++)
{
if (AllocateNewRecord(qres))
{
for (actualCol = 0; actualCol < qres->colsNumber; actualCol++)
{
AllocateFieldSpace(qres, qres->queryHeader[actualCol].colummnSize, actualCol);
if (!psqlconn->BindCol(actualCol, (qres->current_record)->row[actualCol],
qres->queryHeader[actualCol].colummnSize + 1))
break;
}
result = psqlconn->Fetch();
if (!result)
break;
else
(qres->totalRows)++;
}
else
{
resultsetnum = ITXFAILED;
break;
}
}
}
else
resultsetnum = ITXFAILED;
}
else
FREE(qres);
}
} // if (colsNumber != 0)
moreresult = MoreResultSQL(psqlconn);
} // while (moreresult)
}
else
resultsetnum = ITXFAILED;
return resultsetnum;
}<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : cgiresolver.h
| TAB : 2 spaces
|
| DESCRIPTION : CGIResolver object declaration header file.
|
|
*/
#ifndef __CGIRESOLVER_H__
#define __CGIRESOLVER_H__
#include <fcntl.h> //This for stream modes
#include "defines.h"
#include "auxfile.h"
#include "itxlib.h"
/* Possible return codes from the cgiForm family of functions (see below). */
typedef enum
{
cgiFormSuccess,
cgiFormTruncated,
cgiFormBadType,
cgiFormEmpty,
cgiFormNotFound,
cgiFormConstrained,
cgiFormNoSuchChoice,
cgiFormMemory
} FormResultType_t;
typedef enum
{
cgiEscapeRest,
cgiEscapeFirst,
cgiEscapeSecond
} EscapeState_t;
typedef enum
{
cgiUnescapeSuccess,
cgiUnescapeMemory
} UnescapeResultType_t;
typedef enum
{
cgiParseSuccess,
cgiParseMemory,
cgiParseIO
} cgiParseResultType;
/* One form entry, consisting of an attribute-value pair. */
typedef struct cgiFormEntryStruct
{
char* attr;
char* value;
struct cgiFormEntryStruct* next;
} cgiFormEntry;
/*****************************************************************************
---------------------------- PRMFile object -----------------------------
*****************************************************************************/
class PRMFile
{
public:
//MEMBERS
itxString m_PrmNames[MAX_PRM_PARS];
itxString m_PrmValues[MAX_PRM_PARS];
private:
itxString m_LanId; //Lingua utente (tipicamente da una stringa di get)
itxString m_FileName; //Nome del file di inizializzazione con l'estensione.
int m_NumParams;
itxString m_FileDir; //Nome della directory del file di inizializzazione
//ultimo slash incluso
itxString m_FilePath; //Path completo del file di inizializzazione
public:
//METHODS
bool ReadPRM();
bool Clone(PRMFile*);
bool MergePRM(itxString*);
void SetLanguageId(char* lid);
void GetLanguageId(itxString* plid);
void SetPRMFileName(char* fname);
void GetPRMFileName(itxString* pfname);
bool GetPRMValue(itxString* param_name, itxString* param_value);
bool GetPRMValue(char* param_name, itxString* param_value);
bool GetPRMValue(char* param_name, char* param_value, int* bufdim);
bool GetPRMValue(int index, itxString* param_value);
bool GetPRMName(int index, itxString* param_value);
int GetIndexByName(char* param_name);
void ClearNamesAndValues();
void SetAuxiliaryDirectory(char* dir_path);
itxString GetAuxiliaryDirectory();
public:
//CONSTRUCTION-DESTRUCTION
PRMFile();
PRMFile(char* prmfile);
~PRMFile(){}
};
/*****************************************************************************
---------------------------- CGIResolver object -----------------------------
*****************************************************************************/
class CGIResolver
{
//MEMBERS
public:
/*The various CGI environment variables. Instead of using getenv(),
the programmer should refer to these, which are always
valid null-terminated strings (they may be empty, but they
will never be null). If these variables are used instead
of calling getenv(), then it will be possible to save
and restore CGI environments, which is highly convenient
for debugging. */
char* cgiServerSoftware;
char* cgiServerName;
char* cgiGatewayInterface;
char* cgiServerProtocol;
char* cgiServerPort;
char* cgiRequestMethod;
char* cgiPathInfo;
char* cgiPathTranslated;
char* cgiScriptName;
char* cgiQueryString;
char* cgiRemoteHost;
char* cgiHttpHost;
char* cgiRemoteAddr;
char* cgiAuthType;
char* cgiRemoteUser;
char* cgiRemoteIdent;
char* cgiContentType;
char* cgiAccept;
char* cgiUserAgent;
char* cgiCookie;
char* cgiReferrer;
/* The number of bytes of data received.
Note that if the submission is a form submission
the library will read and parse all the information
directly from cgiIn; the programmer need not do so. */
int cgiContentLength;
/* Pointer to CGI output. The cgiHeader functions should be used
first to output the mime headers; the output HTML
page, GIF image or other web document should then be written
to cgiOut by the programmer. */
FILE* cgiOut;
/* Pointer to CGI input. In 99% of cases, the programmer will NOT
need this. However, in some applications, things other than
forms are posted to the server, in which case this file may
be read from in order to retrieve the contents. */
FILE* cgiIn;
/* The first form entry. */
cgiFormEntry* cgiFormEntryFirst;
int cgiHexValue[256];
char* cgiFindTarget;
cgiFormEntry* cgiFindPos;
PRMFile m_PRMConf;
PRMFile m_PRMFile;
itxString m_POSTbody;
itxSystem m_Sys;
//METHODS
void GetEnvironment(bool must_trace = false);
void cgiGetenv(char **s, char *var);
void cgiFreeResources();
int cgiFirstNonspaceChar(char *s);
int cgiWriteString(FILE *out, char *s);
int cgiWriteInt(FILE *out, int i);
cgiParseResultType cgiParseGetFormInput();
bool ReadPostContent();
cgiParseResultType cgiParseFormInput(char *data, int length);
UnescapeResultType_t cgiUnescapeChars(char **sp, char *cp, int len);
FormResultType_t cgiFormEntryString(cgiFormEntry *e, char *result, int max, int newlines);
cgiFormEntry* cgiFormEntryFindFirst(char *name);
cgiFormEntry* cgiFormEntryFindNext();
void ManageRequestMethod();
void Flush(char* outbuf);
void Flush(char* outbuf, int outbufdim);
bool FlushOnFile(char* path, char* fname, char* outbuf, char* ext = TPL_EXT, char mode = 'b');
void SendResponseMimeType();
//Overridables
virtual void OnStart(); //Tannit entry point
/* These functions are used to retrieve form data. */
FormResultType_t cgiFormString(char *name, char *result, int max);
FormResultType_t cgiFormString(char *name, itxString* istrresult, int max); //itxString version
FormResultType_t cgiFormStringSpaceNeeded(char *name, int *length);
//TBD da levare da qui in poi, una per una pero`...
FormResultType_t cgiFormStringNoNewlines(char *name, char *result, int max);
FormResultType_t cgiFormStringMultiple(char *name, char ***ptrToStringArray);
FormResultType_t cgiFormInteger(char *name, int *result, int defaultV);
FormResultType_t cgiFormIntegerBounded(char *name, int *result, int min, int max, int defaultV);
FormResultType_t cgiFormDouble(char *name, double *result, double defaultV);
FormResultType_t cgiFormDoubleBounded(char *name, double *result, double min, double max, double defaultV);
FormResultType_t cgiFormSelectSingle(char *name, char **choicesText, int choicesTotal, int *result, int defaultV);
FormResultType_t cgiFormSelectMultiple(char *name, char **choicesText, int choicesTotal, int *result, int *invalid);
FormResultType_t cgiFormCheckboxSingle(char *name);
FormResultType_t cgiFormCheckboxMultiple(char *name, char **valuesText, int valuesTotal, int *result, int *invalid);
FormResultType_t cgiFormRadio(char *name, char **valuesText, int valuesTotal, int *result, int defaultV);
void cgiStringArrayFree(char **stringArray);
void cgiHeaderLocation(char *redirectUrl);
void cgiHeaderStatus(int status, char *statusMessage);
//CONSTRUCTION-DESTRUCTION
CGIResolver();
~CGIResolver();
};
#endif /* __CGIRESOLVER_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxwraplib.h,v $
* $Revision: 1.1 $
* $Author: massimo $
* $Date: 2002-06-10 15:04:34+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXWRAPLIB_H__
#define __ITXWRAPLIB_H__
//---------------
//itxString
//---------------
int itxString_SubstituteSubString(char* base, char* what, char* with, char* retstr);
int itxString_AdjustStr(char* base, char* retstr);
int itxString_RemoveLeadingZeros(char* base, int zleft, char* retstr);
int itxString_Capitalize(char* base, char* retstr);
int itxString_RightInstr(char* base, char* search_arg, int start_from);
int itxString_MaxTokenLen(char* base, char* sep);
int itxString_UCase(char* str);
void itxString_InBlinder(char** source, char blinder);
void itxString_EscapeChars(char* source, char** destination);
int itxString_CompareNoCase(char* s1, char* s2);
char* itxString_LTrim(char* str);
char* itxString_RTrim(char* str);
char* itxString_Trim(char* str);
#endif /* __ITXWRAPLIB_H__ */
<file_sep>/* desx.c
* <NAME>, 1994.
*
* "DESX" is a trademark of RSA Data Security, Inc.
*
* THIS SOFTWARE PLACED IN THE PUBLIC DOMAIN BY THE AUTHOR
*
* Copyright (c) 1994 by <NAME> (CIS : [71755,204])
*/
#include "desx.h"
#define EN0 0
#define DE1 1
static void deskey(unsigned char *, unsigned long *, short);
static void scrunch(unsigned char *, unsigned long *);
static void unscrun(unsigned long *, unsigned char *);
static void desfunc(unsigned long *, unsigned long *);
static void cookey(unsigned long *, unsigned long *);
static unsigned short bytebit[8] = {
0200, 0100, 040, 020, 010, 04, 02, 01 };
static unsigned long bigbyte[24] = {
0x800000L, 0x400000L, 0x200000L, 0x100000L,
0x80000L, 0x40000L, 0x20000L, 0x10000L,
0x8000L, 0x4000L, 0x2000L, 0x1000L,
0x800L, 0x400L, 0x200L, 0x100L,
0x80L, 0x40L, 0x20L, 0x10L,
0x8L, 0x4L, 0x2L, 0x1L };
/* Use the key schedule specified in the Standard (ANSI X3.92-1981). */
static unsigned char pc1[56] = {
56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 };
static unsigned char totrot[16] = {
1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28 };
static unsigned char pc2[48] = {
13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 };
static void deskey(
unsigned char *key,
unsigned long *out,
short edf )
{
int i, j, l, m, n;
unsigned char pc1m[56], pcr[56];
unsigned long kn[32];
for ( j = 0; j < 56; j++ ) {
l = pc1[j];
m = l & 07;
pc1m[j] = (key[l >> 3] & bytebit[m]) ? 1 : 0;
}
for( i = 0; i < 16; i++ ) {
if( edf == DE1 ) m = (15 - i) << 1;
else m = i << 1;
n = m + 1;
kn[m] = kn[n] = 0L;
for( j = 0; j < 28; j++ ) {
l = j + totrot[i];
if( l < 28 ) pcr[j] = pc1m[l];
else pcr[j] = pc1m[l - 28];
}
for( j = 28; j < 56; j++ ) {
l = j + totrot[i];
if( l < 56 ) pcr[j] = pc1m[l];
else pcr[j] = pc1m[l - 28];
}
for( j = 0; j < 24; j++ ) {
if( pcr[pc2[j]] ) kn[m] |= bigbyte[j];
if( pcr[pc2[j+24]] ) kn[n] |= bigbyte[j];
}
}
cookey(kn, out);
return;
}
static void cookey(unsigned long *raw1, unsigned long *cook)
{
unsigned long *raw0;
int i;
for( i = 0; i < 16; i++, raw1++ ) {
raw0 = raw1++;
*cook = (*raw0 & 0x00fc0000L) << 6;
*cook |= (*raw0 & 0x00000fc0L) << 10;
*cook |= (*raw1 & 0x00fc0000L) >> 10;
*cook++ |= (*raw1 & 0x00000fc0L) >> 6;
*cook = (*raw0 & 0x0003f000L) << 12;
*cook |= (*raw0 & 0x0000003fL) << 16;
*cook |= (*raw1 & 0x0003f000L) >> 4;
*cook++ |= (*raw1 & 0x0000003fL);
}
return;
}
static void scrunch(unsigned char *outof, unsigned long *into)
{
*into = (*outof++ & 0xffL) << 24;
*into |= (*outof++ & 0xffL) << 16;
*into |= (*outof++ & 0xffL) << 8;
*into++ |= (*outof++ & 0xffL);
*into = (*outof++ & 0xffL) << 24;
*into |= (*outof++ & 0xffL) << 16;
*into |= (*outof++ & 0xffL) << 8;
*into |= (*outof & 0xffL);
return;
}
static void unscrun(unsigned long *outof, unsigned char *into)
{
*into++ = (unsigned char) ((*outof >> 24) & 0xffL);
*into++ = (unsigned char) ((*outof >> 16) & 0xffL);
*into++ = (unsigned char) ((*outof >> 8) & 0xffL);
*into++ = (unsigned char) ( *outof++ & 0xffL);
*into++ = (unsigned char) ((*outof >> 24) & 0xffL);
*into++ = (unsigned char) ((*outof >> 16) & 0xffL);
*into++ = (unsigned char) ((*outof >> 8) & 0xffL);
*into = (unsigned char) ( *outof & 0xffL);
return;
}
static unsigned long SP1[64] = {
0x01010400L, 0x00000000L, 0x00010000L, 0x01010404L,
0x01010004L, 0x00010404L, 0x00000004L, 0x00010000L,
0x00000400L, 0x01010400L, 0x01010404L, 0x00000400L,
0x01000404L, 0x01010004L, 0x01000000L, 0x00000004L,
0x00000404L, 0x01000400L, 0x01000400L, 0x00010400L,
0x00010400L, 0x01010000L, 0x01010000L, 0x01000404L,
0x00010004L, 0x01000004L, 0x01000004L, 0x00010004L,
0x00000000L, 0x00000404L, 0x00010404L, 0x01000000L,
0x00010000L, 0x01010404L, 0x00000004L, 0x01010000L,
0x01010400L, 0x01000000L, 0x01000000L, 0x00000400L,
0x01010004L, 0x00010000L, 0x00010400L, 0x01000004L,
0x00000400L, 0x00000004L, 0x01000404L, 0x00010404L,
0x01010404L, 0x00010004L, 0x01010000L, 0x01000404L,
0x01000004L, 0x00000404L, 0x00010404L, 0x01010400L,
0x00000404L, 0x01000400L, 0x01000400L, 0x00000000L,
0x00010004L, 0x00010400L, 0x00000000L, 0x01010004L };
static unsigned long SP2[64] = {
0x80108020L, 0x80008000L, 0x00008000L, 0x00108020L,
0x00100000L, 0x00000020L, 0x80100020L, 0x80008020L,
0x80000020L, 0x80108020L, 0x80108000L, 0x80000000L,
0x80008000L, 0x00100000L, 0x00000020L, 0x80100020L,
0x00108000L, 0x00100020L, 0x80008020L, 0x00000000L,
0x80000000L, 0x00008000L, 0x00108020L, 0x80100000L,
0x00100020L, 0x80000020L, 0x00000000L, 0x00108000L,
0x00008020L, 0x80108000L, 0x80100000L, 0x00008020L,
0x00000000L, 0x00108020L, 0x80100020L, 0x00100000L,
0x80008020L, 0x80100000L, 0x80108000L, 0x00008000L,
0x80100000L, 0x80008000L, 0x00000020L, 0x80108020L,
0x00108020L, 0x00000020L, 0x00008000L, 0x80000000L,
0x00008020L, 0x80108000L, 0x00100000L, 0x80000020L,
0x00100020L, 0x80008020L, 0x80000020L, 0x00100020L,
0x00108000L, 0x00000000L, 0x80008000L, 0x00008020L,
0x80000000L, 0x80100020L, 0x80108020L, 0x00108000L };
static unsigned long SP3[64] = {
0x00000208L, 0x08020200L, 0x00000000L, 0x08020008L,
0x08000200L, 0x00000000L, 0x00020208L, 0x08000200L,
0x00020008L, 0x08000008L, 0x08000008L, 0x00020000L,
0x08020208L, 0x00020008L, 0x08020000L, 0x00000208L,
0x08000000L, 0x00000008L, 0x08020200L, 0x00000200L,
0x00020200L, 0x08020000L, 0x08020008L, 0x00020208L,
0x08000208L, 0x00020200L, 0x00020000L, 0x08000208L,
0x00000008L, 0x08020208L, 0x00000200L, 0x08000000L,
0x08020200L, 0x08000000L, 0x00020008L, 0x00000208L,
0x00020000L, 0x08020200L, 0x08000200L, 0x00000000L,
0x00000200L, 0x00020008L, 0x08020208L, 0x08000200L,
0x08000008L, 0x00000200L, 0x00000000L, 0x08020008L,
0x08000208L, 0x00020000L, 0x08000000L, 0x08020208L,
0x00000008L, 0x00020208L, 0x00020200L, 0x08000008L,
0x08020000L, 0x08000208L, 0x00000208L, 0x08020000L,
0x00020208L, 0x00000008L, 0x08020008L, 0x00020200L };
static unsigned long SP4[64] = {
0x00802001L, 0x00002081L, 0x00002081L, 0x00000080L,
0x00802080L, 0x00800081L, 0x00800001L, 0x00002001L,
0x00000000L, 0x00802000L, 0x00802000L, 0x00802081L,
0x00000081L, 0x00000000L, 0x00800080L, 0x00800001L,
0x00000001L, 0x00002000L, 0x00800000L, 0x00802001L,
0x00000080L, 0x00800000L, 0x00002001L, 0x00002080L,
0x00800081L, 0x00000001L, 0x00002080L, 0x00800080L,
0x00002000L, 0x00802080L, 0x00802081L, 0x00000081L,
0x00800080L, 0x00800001L, 0x00802000L, 0x00802081L,
0x00000081L, 0x00000000L, 0x00000000L, 0x00802000L,
0x00002080L, 0x00800080L, 0x00800081L, 0x00000001L,
0x00802001L, 0x00002081L, 0x00002081L, 0x00000080L,
0x00802081L, 0x00000081L, 0x00000001L, 0x00002000L,
0x00800001L, 0x00002001L, 0x00802080L, 0x00800081L,
0x00002001L, 0x00002080L, 0x00800000L, 0x00802001L,
0x00000080L, 0x00800000L, 0x00002000L, 0x00802080L };
static unsigned long SP5[64] = {
0x00000100L, 0x02080100L, 0x02080000L, 0x42000100L,
0x00080000L, 0x00000100L, 0x40000000L, 0x02080000L,
0x40080100L, 0x00080000L, 0x02000100L, 0x40080100L,
0x42000100L, 0x42080000L, 0x00080100L, 0x40000000L,
0x02000000L, 0x40080000L, 0x40080000L, 0x00000000L,
0x40000100L, 0x42080100L, 0x42080100L, 0x02000100L,
0x42080000L, 0x40000100L, 0x00000000L, 0x42000000L,
0x02080100L, 0x02000000L, 0x42000000L, 0x00080100L,
0x00080000L, 0x42000100L, 0x00000100L, 0x02000000L,
0x40000000L, 0x02080000L, 0x42000100L, 0x40080100L,
0x02000100L, 0x40000000L, 0x42080000L, 0x02080100L,
0x40080100L, 0x00000100L, 0x02000000L, 0x42080000L,
0x42080100L, 0x00080100L, 0x42000000L, 0x42080100L,
0x02080000L, 0x00000000L, 0x40080000L, 0x42000000L,
0x00080100L, 0x02000100L, 0x40000100L, 0x00080000L,
0x00000000L, 0x40080000L, 0x02080100L, 0x40000100L };
static unsigned long SP6[64] = {
0x20000010L, 0x20400000L, 0x00004000L, 0x20404010L,
0x20400000L, 0x00000010L, 0x20404010L, 0x00400000L,
0x20004000L, 0x00404010L, 0x00400000L, 0x20000010L,
0x00400010L, 0x20004000L, 0x20000000L, 0x00004010L,
0x00000000L, 0x00400010L, 0x20004010L, 0x00004000L,
0x00404000L, 0x20004010L, 0x00000010L, 0x20400010L,
0x20400010L, 0x00000000L, 0x00404010L, 0x20404000L,
0x00004010L, 0x00404000L, 0x20404000L, 0x20000000L,
0x20004000L, 0x00000010L, 0x20400010L, 0x00404000L,
0x20404010L, 0x00400000L, 0x00004010L, 0x20000010L,
0x00400000L, 0x20004000L, 0x20000000L, 0x00004010L,
0x20000010L, 0x20404010L, 0x00404000L, 0x20400000L,
0x00404010L, 0x20404000L, 0x00000000L, 0x20400010L,
0x00000010L, 0x00004000L, 0x20400000L, 0x00404010L,
0x00004000L, 0x00400010L, 0x20004010L, 0x00000000L,
0x20404000L, 0x20000000L, 0x00400010L, 0x20004010L };
static unsigned long SP7[64] = {
0x00200000L, 0x04200002L, 0x04000802L, 0x00000000L,
0x00000800L, 0x04000802L, 0x00200802L, 0x04200800L,
0x04200802L, 0x00200000L, 0x00000000L, 0x04000002L,
0x00000002L, 0x04000000L, 0x04200002L, 0x00000802L,
0x04000800L, 0x00200802L, 0x00200002L, 0x04000800L,
0x04000002L, 0x04200000L, 0x04200800L, 0x00200002L,
0x04200000L, 0x00000800L, 0x00000802L, 0x04200802L,
0x00200800L, 0x00000002L, 0x04000000L, 0x00200800L,
0x04000000L, 0x00200800L, 0x00200000L, 0x04000802L,
0x04000802L, 0x04200002L, 0x04200002L, 0x00000002L,
0x00200002L, 0x04000000L, 0x04000800L, 0x00200000L,
0x04200800L, 0x00000802L, 0x00200802L, 0x04200800L,
0x00000802L, 0x04000002L, 0x04200802L, 0x04200000L,
0x00200800L, 0x00000000L, 0x00000002L, 0x04200802L,
0x00000000L, 0x00200802L, 0x04200000L, 0x00000800L,
0x04000002L, 0x04000800L, 0x00000800L, 0x00200002L };
static unsigned long SP8[64] = {
0x10001040L, 0x00001000L, 0x00040000L, 0x10041040L,
0x10000000L, 0x10001040L, 0x00000040L, 0x10000000L,
0x00040040L, 0x10040000L, 0x10041040L, 0x00041000L,
0x10041000L, 0x00041040L, 0x00001000L, 0x00000040L,
0x10040000L, 0x10000040L, 0x10001000L, 0x00001040L,
0x00041000L, 0x00040040L, 0x10040040L, 0x10041000L,
0x00001040L, 0x00000000L, 0x00000000L, 0x10040040L,
0x10000040L, 0x10001000L, 0x00041040L, 0x00040000L,
0x00041040L, 0x00040000L, 0x10041000L, 0x00001000L,
0x00000040L, 0x10040040L, 0x00001000L, 0x00041040L,
0x10001000L, 0x00000040L, 0x10000040L, 0x10040000L,
0x10040040L, 0x10000000L, 0x00040000L, 0x10001040L,
0x00000000L, 0x10041040L, 0x00040040L, 0x10000040L,
0x10040000L, 0x10001000L, 0x10001040L, 0x00000000L,
0x10041040L, 0x00041000L, 0x00041000L, 0x00001040L,
0x00001040L, 0x00040040L, 0x10000000L, 0x10041000L };
static void desfunc(unsigned long *block, unsigned long *keys)
{
unsigned long fval, work, right, leftt;
int round;
leftt = block[0];
right = block[1];
work = ((leftt >> 4) ^ right) & 0x0f0f0f0fL;
right ^= work;
leftt ^= (work << 4);
work = ((leftt >> 16) ^ right) & 0x0000ffffL;
right ^= work;
leftt ^= (work << 16);
work = ((right >> 2) ^ leftt) & 0x33333333L;
leftt ^= work;
right ^= (work << 2);
work = ((right >> 8) ^ leftt) & 0x00ff00ffL;
leftt ^= work;
right ^= (work << 8);
right = ((right << 1) | ((right >> 31) & 1L)) & 0xffffffffL;
work = (leftt ^ right) & 0xaaaaaaaaL;
leftt ^= work;
right ^= work;
leftt = ((leftt << 1) | ((leftt >> 31) & 1L)) & 0xffffffffL;
for( round = 0; round < 8; round++ ) {
work = (right << 28) | (right >> 4);
work ^= *keys++;
fval = SP7[ work & 0x3fL];
fval |= SP5[(work >> 8) & 0x3fL];
fval |= SP3[(work >> 16) & 0x3fL];
fval |= SP1[(work >> 24) & 0x3fL];
work = right ^ *keys++;
fval |= SP8[ work & 0x3fL];
fval |= SP6[(work >> 8) & 0x3fL];
fval |= SP4[(work >> 16) & 0x3fL];
fval |= SP2[(work >> 24) & 0x3fL];
leftt ^= fval;
work = (leftt << 28) | (leftt >> 4);
work ^= *keys++;
fval = SP7[ work & 0x3fL];
fval |= SP5[(work >> 8) & 0x3fL];
fval |= SP3[(work >> 16) & 0x3fL];
fval |= SP1[(work >> 24) & 0x3fL];
work = leftt ^ *keys++;
fval |= SP8[ work & 0x3fL];
fval |= SP6[(work >> 8) & 0x3fL];
fval |= SP4[(work >> 16) & 0x3fL];
fval |= SP2[(work >> 24) & 0x3fL];
right ^= fval;
}
right = (right << 31) | (right >> 1);
work = (leftt ^ right) & 0xaaaaaaaaL;
leftt ^= work;
right ^= work;
leftt = (leftt << 31) | (leftt >> 1);
work = ((leftt >> 8) ^ right) & 0x00ff00ffL;
right ^= work;
leftt ^= (work << 8);
work = ((leftt >> 2) ^ right) & 0x33333333L;
right ^= work;
leftt ^= (work << 2);
work = ((right >> 16) ^ leftt) & 0x0000ffffL;
leftt ^= work;
right ^= (work << 16);
work = ((right >> 4) ^ leftt) & 0x0f0f0f0fL;
leftt ^= work;
right ^= (work << 4);
*block++ = right;
*block = leftt;
return;
}
static unsigned char Clorox[256] = {
189, 86,234,242,162,241,172, 42,176,147,209,156, 27, 51,253,208,
48, 4,182,220,125,223, 50, 75,247,203, 69,155, 49,187, 33, 90,
65,159,225,217, 74, 77,158,218,160,104, 44,195, 39, 95,128, 54,
62,238,251,149, 26,254,206,168, 52,169, 19,240,166, 63,216, 12,
120, 36,175, 35, 82,193,103, 23,245,102,144,231,232, 7,184, 96,
72,230, 30, 83,243,146,164,114,140, 8, 21,110,134, 0,132,250,
244,127,138, 66, 25,246,219,205, 20,141, 80, 18,186, 60, 6, 78,
236,179, 53, 17,161,136,142, 43,148,153,183,113,116,211,228,191,
58,222,150, 14,188, 10,237,119,252, 55,107, 3,121,137, 98,198,
215,192,210,124,106,139, 34,163, 91, 5, 93, 2,117,213, 97,227,
24,143, 85, 81,173, 31, 11, 94,133,229,194, 87, 99,202, 61,108,
180,197,204,112,178,145, 89, 13, 71, 32,200, 79, 88,224, 1,226,
22, 56,196,111, 59, 15,101, 70,190,126, 45,123,130,249, 64,181,
29,115,248,235, 38,199,135,151, 37, 84,177, 40,170,152,157,165,
100,109,122,212, 16,129, 68,239, 73,214,174, 46,221,118, 92, 47,
167, 28,201, 9,105,154,131,207, 41, 57,185,233, 76,255, 67,171 };
void DESXKeySetup(
struct DESXContext *output,
struct DESXKey *input )
{
unsigned char work[8], *cp, *dp;
unsigned int tind, i, j;
deskey(input->DESKey64, output->Context.dxkenc, EN0);
deskey(input->DESKey64, output->Context.dxkdec, DE1);
scrunch(input->Whitening64, output->PreWhitening64);
for( i = 0; i < 8; i++ ) work[i] = 0;
for( i = 0; i < 8; i++ ) {
tind = (work[0] ^ work[1]) & 0xff;
dp = work;
cp = &work[1];
for( j = 0; j < 7; j++ ) *dp++ = *cp++;
*dp = Clorox[tind] ^ input->DESKey64[i];
}
for( i = 0; i < 8; i++ ) {
tind = (work[0] ^ work[1]) & 0xff;
dp = work;
cp = &work[1];
for( j = 0; j < 7; j++ ) *dp++ = *cp++;
*dp = Clorox[tind] ^ input->Whitening64[i];
}
scrunch(work, output->PostWhitening64);
return;
}
void DESXEncryptBlock(
struct DESXContext* _using,
unsigned char *OutData64,
unsigned char *InData64 )
{
unsigned long work[2];
scrunch(InData64, work);
work[0] ^= _using->PreWhitening64[0];
work[1] ^= _using->PreWhitening64[1];
desfunc(work, _using->Context.dxkenc);
work[0] ^= _using->PostWhitening64[0];
work[1] ^= _using->PostWhitening64[1];
unscrun(work, OutData64);
return;
}
void DESXDecryptBlock(
struct DESXContext* _using,
unsigned char *OutData64,
unsigned char *InData64 )
{
unsigned long work[2];
scrunch(InData64, work);
work[0] ^= _using->PostWhitening64[0];
work[1] ^= _using->PostWhitening64[1];
desfunc(work, _using->Context.dxkdec);
work[0] ^= _using->PreWhitening64[0];
work[1] ^= _using->PreWhitening64[1];
unscrun(work, OutData64);
return;
}
/* Test -
*
* Key: <KEY>
* White: 0819 2a3b 4c5d 6e7f
*(PostW: e9c2 cb67 ad86 28fb)
* Plain: 0123 4567 89ab cde7
* Cipher: 1a0a 3cd4 3ef5 0b52
*
* desx V1.00 rwo 94/03/02 00:03:50 EST Graven Imagery
**********************************************************************/
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxcoll.h,v $
* $Revision: 1.11 $
* $Author: massimo $
* $Date: 2002-06-07 11:04:25+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXCOLL_H__
#define __ITXCOLL_H__
#include <stdio.h>
#include <stdlib.h>
typedef struct PtrStack
{
void* item;
struct PtrStack* under;
struct PtrStack* over;
} PtrStack_t;
class itxStack
{
private:
PtrStack_t* m_Stack;
PtrStack_t* m_Bottom;
PtrStack_t* m_Cursor;
public:
int Push(void* item);
int Pop(void** item);
void* GetCurrent(){return (m_Cursor != NULL ? m_Cursor->item : NULL);}
inline void* Top(){return (m_Stack != NULL ? m_Stack->item : NULL);}
inline void* Bottom(){return (m_Bottom != NULL ? m_Bottom->item : NULL);}
inline void* NextUp(){m_Cursor = m_Cursor->over; return (m_Cursor != NULL ? m_Cursor->item : NULL);}
inline void* NextDown(){m_Cursor = m_Cursor->under; return (m_Cursor != NULL ? m_Cursor->item : NULL);}
inline void SetCursorTop(){m_Cursor = m_Stack;}
inline void SetCursorBottom(){m_Cursor = m_Bottom;}
itxStack();
~itxStack();
};
//////////////////
//class itxListPtr
typedef struct PtrElem
{
void* item;
struct PtrElem* next;
struct PtrElem* prev;
} PtrElem_t;
class itxListPtr
{
//MEMBERS
private:
PtrElem_t* m_Head;
PtrElem_t* m_Tail;
PtrElem_t* m_Cursor;
int m_Count;
//METHODS
private:
PtrElem_t* GetAt(int pos);
public:
bool Append(void* item);
bool Remove(int pos);
bool Insert(void* item, int pos);
bool Empty();
void* GetElement(int pos);
int GetCount(){return m_Count;}
void* GetHead(){m_Cursor = m_Head; return (m_Cursor ? m_Cursor->item : NULL);}
void* GetTail(){m_Cursor = m_Tail; return (m_Cursor ? m_Cursor->item : NULL);}
void* GetNext(){if (m_Cursor) m_Cursor = m_Cursor->next; return (m_Cursor ? m_Cursor->item : NULL);}
void* GetPrev(){if (m_Cursor) m_Cursor = m_Cursor->prev; return (m_Cursor ? m_Cursor->item : NULL);}
itxListPtr();
~itxListPtr();
};
#endif //__ITXCOLL_H__<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
- PROJECT : itxWeb - Tannit
- FILENAME : tannit.c
- TAB : 2, no spaces
- DESCRIPTION : funzioni principali
*****************************************************************************/
#include "tannit.h"
#include "itannitc.h"
char BgMain[PAR_VALUE_LEN], BgMenu[PAR_VALUE_LEN], BgTop[PAR_VALUE_LEN], BgLeft[PAR_VALUE_LEN];
char BgRight[PAR_VALUE_LEN], BgBott[PAR_VALUE_LEN], TplDir[PAR_VALUE_LEN], CrudeTplDir[PAR_VALUE_LEN], WebHome[PAR_VALUE_LEN];
char CgiDir[PAR_VALUE_LEN] ,CgiName[PAR_VALUE_LEN], PrepropKey[PAR_VALUE_LEN], PreviewKey[PAR_VALUE_LEN], NormviewKey[PAR_VALUE_LEN], PrepKeyTag[PAR_VALUE_LEN];
char ImgDir[PAR_VALUE_LEN], FileDir[PAR_VALUE_LEN], Odbcdsn[PAR_VALUE_LEN], Odbcuid[PAR_VALUE_LEN];
char Odbcpwd[PAR_VALUE_LEN], WebUrl[PAR_VALUE_LEN], LoginTable[PAR_VALUE_LEN], PwdField[PAR_VALUE_LEN];
char LoginField[PAR_VALUE_LEN], ExtrTable[PAR_VALUE_LEN], IdField[PAR_VALUE_LEN], ExtrField[PAR_VALUE_LEN];
char LangTagGet[PAR_VALUE_LEN], LangTable[PAR_VALUE_LEN], LangNameField[PAR_VALUE_LEN], LangCodeField[PAR_VALUE_LEN];
char TransTable[PAR_VALUE_LEN], TransTagField[PAR_VALUE_LEN], DefaultLanguageId[PAR_VALUE_LEN];
char UploadDir[PAR_VALUE_LEN],AllowUpload[PAR_VALUE_LEN];
char CorrTable[PAR_VALUE_LEN], CorrUserField[PAR_VALUE_LEN], CorrCodeField[PAR_VALUE_LEN];
char CorrAppDir[PAR_VALUE_LEN], CorrFileName[PAR_VALUE_LEN], CorrDndStatus[PAR_VALUE_LEN];
char CorrDnDir[PAR_VALUE_LEN], Llu[PAR_VALUE_LEN], Rtp[PAR_VALUE_LEN];
char FFace1[PAR_VALUE_LEN], FFace2[PAR_VALUE_LEN], FSize[PAR_VALUE_LEN], FStyle[PAR_VALUE_LEN], FColor[PAR_VALUE_LEN], FDecor[PAR_VALUE_LEN], Lheight[PAR_VALUE_LEN];
char DbgPath[PAR_VALUE_LEN], CooTimeDelay[PAR_VALUE_LEN], CooURLEscape[PAR_VALUE_LEN];
char TargetTplField[PAR_VALUE_LEN],TplTable[PAR_VALUE_LEN],TplTableId[PAR_VALUE_LEN], TplTableName[PAR_VALUE_LEN];
char CurrentTpl[MAX_TPL_NESTS][TPL_NAME_LEN], ContextField[PAR_VALUE_LEN],ContextTag[PAR_VALUE_LEN];
char ForbiddenChars[PAR_VALUE_LEN];
// dopo il porting, da riaggiornare
char SSDir[PAR_VALUE_LEN];
int TntRequestType = RT_BROWSE, TplNest;
TannitQueryResult* QQres = NULL;
int Rumble;
char QueryLabel[128];
bool usedbg, alloctrc;
char UserAgentSpy[256];
struct QueryResult * QueryResultSet[QUERY_NUMBER];
MessagesSt Message[] = {
{ERR_COL_NOT_FOUND , "Error: field not found" },
{ERR_QUERY_NOT_FOUND , "Error: query not found" },
{ERR_VOID_QUERY_NAME , "Error: unable to read query name" },
{LOGIN_ERROR , "Login Error" },
{ERR_PARAM_NEEDED , "Error: parameter needed" },
{0 , "" }
};
StrStack * cycleStk;
StrStack * queryStk;
TplVarsStrct TplVars;
int QueryCounter;
int ReadCycle[CYC_NESTING_DEPTH];
int ValidBlock[CYC_NESTING_DEPTH];
int CndLevel, CycLevel;
int LockLoop;
FILE *debug = NULL;
#ifdef _DEBUG
#include <windows.h> //Serve per la sleep
#endif
void EXIT(int retval)
{
ITannit_DisconnectSQL();
exit(retval);
}
/*************************************************************************************
NOME :cgiMain
attivita' :presenta l'header al web server; guida la scansione del template HTML
chiamante :main
*************************************************************************************/
int cgiMain()
{
char *tplString = 0; // buffer dove verranno messi i dati grezzi del template
char *outputString = 0; // buffer utilizzato da procData per appoggiare i dati interpretati del template
char excngFileOk[30];
FILE * refinedTplFp = 0;
#ifdef _DEBUG
//*
int p=1;
while (p)
Sleep(1);
//*/
#endif
/**/if(usedbg){fprintf(debug, "cgiMain - InitGlobals\n");fflush(debug);}
// inizializzazione dele variabili globali
initGlobals();
/**/if(usedbg){fprintf(debug, "cgiMain - readIniPars\n");fflush(debug);}
// lettura dei parametri definiti nel file di inizialiazione
if(readIniPars() == 0)
{
// cgiHeaderContentType("text/html");
// fprintf(cgiOut,"%s\n", ERR_OPEN_INI_FILE);//fflush(cgiOut);
exit(__LINE__);
}
/*
// cattura del processo nel caso si debba effettuare una operazione
// di scambio di file
if (cgiFormString(EXCNG_FILE_TAG, excngFileOk, GET_VAR_LEN) == cgiFormSuccess)
{
if (strcmp(excngFileOk, SEND_FILE_GRANT) == 0)
{
int retflag;
if ( (retflag = sendFile()) == 1) EXIT(__LINE__);
}
else if (strcmp(excngFileOk, RECEIVE_FILE_GRANT) == 0)
{
receiveFile();
}
else if (strcmp(excngFileOk, RECEIVE_APPC_FILE_GRANT) == 0)
{
receiveAPPCFile();
}
else if (strcmp(excngFileOk, DND_CONFIRM_GRANT) == 0)
{
dndConfirm();
}
}
*/
/**/if(usedbg){fprintf(debug, "cgiMain - cgiHeaderContentType\n");fflush(debug);}
cgiHeaderContentType("text/html");
/**/if(usedbg){fprintf(debug, "cgiMain - verVersion\n");fflush(debug);}
// verifica versione
verVersion();
/**/if(usedbg){fprintf(debug, "cgiMain - PREPROCESSING\n");fflush(debug);}
// SWITCH per il controllo del PREPROCESSING:
TntRequestType = capturePreproc(&tplString, &refinedTplFp);
if((TntRequestType == RT_PREPROC) || (TntRequestType == RT_PREPROC_ALL))
{
/**/if(usedbg){fprintf(debug, "cgiMain - RT_PREPROC\n");fflush(debug);}
strcpy(TplDir, CrudeTplDir);
cgiOut = refinedTplFp;
}
else if (TntRequestType == RT_PREVIEW)
{
/**/if(usedbg){fprintf(debug, "cgiMain - RT_PREVIEW\n");fflush(debug);}
strcpy(TplDir, CrudeTplDir);
}
/**/if(usedbg){fprintf(debug, "cgiMain - TplDir:%s\n", TplDir);fflush(debug);}
// apertura del template, allocazione e copia dei dati in tplString
if( bufferTpl(&tplString, 0, TplDir) == 0)
{
fprintf(cgiOut,"%s\n", ERR_OPEN_TPL_FILE); //fflush(cgiOut);
exit(__LINE__);
}
// interpretazione dei dati e scrittura su cgiOut
procTplData(tplString, cgiOut, &outputString);
if((TntRequestType == RT_PREPROC) || (TntRequestType == RT_PREPROC_ALL))
{
fprintf(stdout,"%s", TPL_UPD_COMM_SUCC);fflush(stdout);
}
/**/if(usedbg){fprintf(debug, "Exiting cgiMain\n");fflush(debug);}
ITannit_DisconnectSQL();
return 1;
}
void dumpAround(char * refPtr, int strtChr, int chrnum)
{
/**/if(usedbg){fprintf(debug, "\n START OF MEMORY DUMP------------------------\n");fflush(debug);}
int i = 0;
for (i = 0; i < chrnum; i++)
{
/**/if(usedbg){fprintf(debug, "%c", *( refPtr + strtChr + i) );fflush(debug);}
}
/**/if(usedbg){fprintf(debug, "\n END OF MEMORY DUMP------------------------\n");fflush(debug);}
}
/*************************************************************************************
NOME :queryIndex
attivita' :scorre l'array di puntatori a QueryResult fino a trovare quello che ha l'id
(label) uguale alla stringa di input
return :l'indice della query identificata da queryId
*************************************************************************************/
int queryIndex(char * queryId, int noexit)
{
int qIndex = -1;
if (queryId)
{
for (qIndex = 0; qIndex < QUERY_NUMBER; qIndex++)
{
//**/if(usedbg && noexit){fprintf(debug, "queryIndex. queryId: %s; qIndex: %d;\n", queryId, qIndex);fflush(debug);}
if (QueryResultSet[qIndex])
{
if (strcmp(QueryResultSet[qIndex]->id,queryId) == 0)
{
break;
}
}
}
if (qIndex == QUERY_NUMBER)
{
if (noexit)
{
return -1;
}
else
{
fprintf(cgiOut, "%s\n", retMsg(ERR_QUERY_NOT_FOUND) );
EXIT(1);
}
}
}
return(qIndex);
}
/*************************************************************************************
NOME :listTQRnames
attivita' :scorre l'array di puntatori a QueryResult e stampa in debug i nomi
*************************************************************************************/
void listTQRnames()
{
int qIndex = -1;
for (qIndex = 0; qIndex < QUERY_NUMBER; qIndex++)
{
if (QueryResultSet[qIndex]->id)
{
/**/if(usedbg){fprintf(debug, "listTQRnames :%d-%s\n", qIndex, QueryResultSet[qIndex]->id);fflush(debug);}
}
}
}
int pushStk (StrStack** stack,char *strg)
{
StrStack *new_element;
int str_len;
str_len=strlen(strg);
if ( !( new_element = (StrStack*) malloc(sizeof(StrStack)) ) )
{
return 0;
}
/**/if(alloctrc){fprintf(debug, "- - new_element:%d - - len:%d\n", new_element, sizeof(StrStack) );fflush(debug);}
///**/fprintf(cgiOut, "<br>strg=%d<br>", strg);
new_element->item = strg;
new_element->next = *stack;
*stack = new_element;
return 1;
}
int popStk (StrStack** stack,char **strg)
{
StrStack *appo;
if (!*stack)
{
*strg = 0;
return 0;
}
appo = (*stack)->next;
*strg = (*stack)->item;
*stack = appo;
return 1;
}
void trimIt(char * inputStr)
{
int j,i;
char *newStr;
newStr = (char*) malloc( strlen(inputStr) * sizeof(char) );if(!newStr) EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - newStr:%d - - len:%d\n", newStr, strlen(inputStr) * sizeof(char) );fflush(debug);}
for (j = 0; (inputStr[j] && inputStr[j]==' '); ++j);
for (i = strlen(inputStr); ( i > 0 && inputStr[i-1]==' '); --i);
if(j < i)
{
strncpy(newStr,&inputStr[j],i-j);
newStr[i-j]=0;
strcpy (inputStr, newStr);
}
else
{
inputStr = 0;
}
}
/*************************************************************************************
NOME :verVersion
attivita' :nel caso nella stringa di get vi sia il tag che identifica la richiesta di
informazioni queste vengono restituite sull'output
return :l'id del tipo di informazione richiesta
chiamante :cgiMain
*************************************************************************************/
int verVersion()
{
int infoId = 0;
if (cgiFormInteger(INFO_TAG, &infoId, INFO_ID)==cgiFormSuccess)
{
switch (infoId)
{
case APPC_MSG_ID:
#ifdef _ITX_APPC
fprintf(cgiOut, "%s\n", APPC_MSG);//fflush(cgiOut);
#endif
case AUTHOR:
fprintf(cgiOut, "%s\n", AUTHOR_MSG);//fflush(cgiOut);
case OWNER:
fprintf(cgiOut, "%s\n", OWNER_MSG);//fflush(cgiOut);
case VERSION:
fprintf(cgiOut, "%s\n", VERSION_MSG);//fflush(cgiOut);
}
}
return infoId;
}
/*************************************************************************************
NOME :getline
attivita' :prende una linea di caratteri
return :il numero di caratteri presi
chiamante :tanti
*************************************************************************************/
int getline(char s[], int lim)
{
int c, i=0, num;
// for (i=0; (i<lim) && ((c=getchar())!=EOF) && (c!='\n'); i++)
for (i=0; (i<lim); i++)
{
if ( (c=getchar()) == EOF )
return EOF;
if (c =='\n')
break;
s[i] = c;
}
if (c == '\n') {
s[i] = c;
}
if ((i==0) && (c!='\n'))
num = 0;
else if (i == lim)
num = i;
else
num = i+1;
return num;
}
/*************************************************************************************
NOME :checkDbPwd
attivita' :confronta la password nel database (decriptata) con la password di input
return :il numero di caratteri presi
chiamante :lo stato di validazione
*************************************************************************************/
int checkDbPwd(char* login, char* pwd, char* extraField, char* extraVal)
{
char dbClearPwd[256];
char queryString[1024];
char *dbPwd;
int errCode;
// Connessione al DB e acquisizione del valore della password
sprintf(queryString, "SELECT %s FROM %s WHERE %s = '%s' AND %s = %s",
PwdField, LoginTable, LoginField, login, extraField, extraVal);
newAutoName();
dbInterface(QueryLabel, queryString, 1, 1);
dbPwd = storedData(1, PwdField, QueryLabel, &errCode);
if ( errCode == ERR_COL_NOT_FOUND ||
errCode == ERR_QUERY_NOT_FOUND ||
errCode == ERR_VOID_QUERY_NAME )
return errCode;
if (dbPwd == NULL) return NOT_VALIDATED;
if (strcmp(dbPwd,REC_VAL_ZERO)==0) return NOT_VALIDATED;
/**/if(usedbg){fprintf(debug, "decripting\n");fflush(debug);}
/**/if(usedbg){fprintf(debug, "dbPwd---%s\n", dbPwd);fflush(debug);}
// tannitDecrypt(dbPwd, dbClearPwd);
/**/if(usedbg){fprintf(debug, "dbClearPwd---%s\n", dbClearPwd);fflush(debug);}
/**/if(usedbg){fprintf(debug, "pwd---%s\n", pwd);fflush(debug);}
tannitDecrypt(dbPwd, dbClearPwd);
if ( strcmp(dbClearPwd, pwd) != 0 ) return NOT_VALIDATED;
return VALIDATED;
}
char * retMsg(int msgId)
{
int i = 0;
while (Message[i].msgId)
{
if ( Message[i].msgId == msgId )
{
break;
}
i++;
}
return Message[i].msg;
}
void newAutoName()
{
sprintf(QueryLabel,"Auto%d", Rumble++);
}
int capturePreproc(char ** tplString, FILE ** refinedTplFp)
{
char userPKey[TPL_NAME_LEN];
char tplName[TPL_NAME_LEN];
char tplAbsName[TPL_NAME_LEN];
char *outputString = 0; // buffer utilizzato da procData per appoggiare i dati interpretati del template
/**/if(usedbg){fprintf(debug, "capturePreproc processing: START\n");fflush(debug);}
// se si trova la key che comanda il preprocessing nella stringa di get
// i teplate vengono letti nella directory CrudeTplDir
if (cgiFormString(PrepKeyTag, userPKey, TPL_NAME_LEN) == cgiFormSuccess)
{
if (strcmp(userPKey, PrepropKey) == 0 )
{
if (cgiFormString(TGT_TAG, tplName, TPL_NAME_LEN) == cgiFormSuccess)
{
sprintf(tplAbsName,"%s\\%s%s",TplDir, tplName, TPL_EXT);
if ( ( *refinedTplFp = fopen(tplAbsName,"w") ) != 0 )
{
/**/if(usedbg){fprintf(debug, "capturePreproc processing: return RT_PREPROC_ALL\n");fflush(debug);}
fprintf(stdout,"%s ", TPL_UPD_COMM_RECV);fflush(stdout);
fprintf(stdout, "<font color=white>%s</font>", tplName);fflush(stdout);
return RT_PREPROC_ALL;
}
}
else if (cgiFormString(TPL_TAG, tplName, TPL_NAME_LEN) == cgiFormSuccess)
{
sprintf(tplAbsName,"%s\\%s%s",TplDir, tplName, TPL_EXT);
if ( ( *refinedTplFp = fopen(tplAbsName,"w") ) != 0 )
{
/**/if(usedbg){fprintf(debug, "capturePreproc processing: return RT_PREPROC\n");fflush(debug);}
fprintf(stdout,"%s ", TPL_UPD_COMM_RECV);fflush(stdout);
fprintf(stdout, "<font color=white>%s</font>", tplName);fflush(stdout);
return RT_PREPROC;
}
}
}
else if (strcmp(userPKey, PreviewKey) == 0 )
{
/**/if(usedbg){fprintf(debug, "capturePreproc processing: return RT_PREVIEW\n");fflush(debug);}
return RT_PREVIEW;
}
else if (strcmp(userPKey, NormviewKey) == 0 )
{
/**/if(usedbg){fprintf(debug, "capturePreproc processing: return RT_BROWSE\n");fflush(debug);}
return RT_BROWSE;
}
else EXIT(0);
}
/**/if(usedbg){fprintf(debug, "capturePreproc processing: return RT_BROWSE\n");fflush(debug);}
return RT_BROWSE;
}
<file_sep>junk
====
Just an open space for crap ideas, useless algos and much more.
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// AITECSA s.r.l. 2000
// filename: tstorp.cpp
// description: support for stored procedure and ODBC error check
// project: since tannit 2.7
#ifndef __ITX_TSTORP_CPP__
#define __ITX_TSTORP_CPP__
#endif
#include "windows.h"
#include "tannit.h"
#include "itannitc.h"
#include "extVars.h"
#include "itxtypes.h"
#define ITX_TSTORP_SERVER_DOWN "SERVER_DOWN"
#define ITX_TSTORP_DUPLICATE_KEY "DUPLICATE_KEY"
#define ITX_TSTORP_H_ATTACK "H_ATTACK"
//#define ITXCOOVERS_EQ "\x0D\x0A"
//#define ITXCOOVERS_SEP "\x0D\x0A"
#define ITXCOOVERS_EQ "="
#define ITXCOOVERS_SEP ";"
/*************************************************************************************
Categoria : Gasp Command: *invoke(stProcName,parametri)
attivita' : invoca la Stored Procedure di comando SQL Server
stProcName: nome della Store Procedure
parametri : stringa di parametri per la storedProcedure. Nota: la stringa contiene
delle virgole va racchiusa tra doppi apici.
*************************************************************************************/
void* invoke(int vuoto1, char *vuoto2, char * inputStr)
{
char* spname;
char* sppar;
char* returnvalue = NULL;
itxString istr;
char stm[ITX_QRS_MAX_QUERY_LEN];
int errvalue;
memset(stm, 0, ITX_QRS_MAX_QUERY_LEN);
if(!pickPar(inputStr, 1, &spname )) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &sppar )) return(PARAM_NOT_FOUND_MSG);
istr.InBlinder(&sppar, BLINDER);
ITannit_Create(QueryResultSet, &QueryCounter);
if (!ITannit_ConnectSQL(Odbcdsn, Odbcuid, Odbcpwd))
{
ITannit_Destroy();
return ITX_TSTORP_SERVER_DOWN;
}
strcat(stm, spname);
strcat(stm, " ");
strcat(stm, sppar);
ITannit_ExecuteSQL(stm);
errvalue = ITannit_ErrorSQL(debug);
////**/if(usedbg){fprintf(debug, "SQL Native Error: %d\n", errvalue);fflush(debug);}
switch (errvalue)
{
case 0: // SUCCESS
break;
// Real SERVER ERROR
case 6: // Server Down
returnvalue = ITX_TSTORP_SERVER_DOWN;
break;
// vero check sulla chiave per l'utente accreditato
case 2601:
case 2627: // Primary Key Violation
case 23000:
returnvalue = ITX_TSTORP_DUPLICATE_KEY;
break;
// casi che potrebbero accadere su attacchi di hackers
case 257: // Type Mismatch
case 8144: // Too Many Arguments
case 201: // Too Few Arguments
default:
returnvalue = ITX_TSTORP_H_ATTACK ;
break;
}
ITannit_DisconnectSQL();
ITannit_Destroy();
return returnvalue;
}
void InitStructs(STARTUPINFO& LtStart,
PROCESS_INFORMATION& LtProc,
SECURITY_ATTRIBUTES& LProcessAttributes,
SECURITY_ATTRIBUTES& LThreadAttributes,
HANDLE& StreamFromChild)
{
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
BOOL ret = CreatePipe(&StreamFromChild, &LtStart.hStdOutput, &sa, 0);
/*
LtStart.hStdOutput =
CreateFile("cico", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
&sa, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
*/
////**/if(usedbg){fprintf(debug, "LtStart.hStdOutput: %p\n", LtStart.hStdOutput);fflush(debug);}
/* Inizializzazione della struttura STARTUPINFO */
LtStart.cb = sizeof(LtStart);
LtStart.lpReserved = NULL;
LtStart.lpDesktop = NULL;
LtStart.lpTitle = NULL;
LtStart.dwX = 0;
LtStart.dwY = 0;
LtStart.dwXSize = 0;
LtStart.dwYSize = 0;
LtStart.dwXCountChars = 0;
LtStart.dwYCountChars = 0;
LtStart.dwFillAttribute = 0;
LtStart.dwFlags = STARTF_USESTDHANDLES;
LtStart.wShowWindow = 0;
LtStart.cbReserved2 = 0;
LtStart.lpReserved2 = 0;
LtStart.hStdError = 0;
/* Inizializzazione della struttura PROCESS_INFORMATION */
LtProc.hProcess = 0;
LtProc.hThread = 0;
/* Inizializzazione della struttura SECURITY_ATTRIBUTES per il processo */
LProcessAttributes.nLength = sizeof(LProcessAttributes);
LProcessAttributes.bInheritHandle = TRUE;
LProcessAttributes.lpSecurityDescriptor = NULL;
/* Inizializzazione della struttura SECURITY_ATTRIBUTES per il thread */
LThreadAttributes.nLength = sizeof(LThreadAttributes);
LThreadAttributes.bInheritHandle = TRUE;
LThreadAttributes.lpSecurityDescriptor = NULL;
}
/*****************************************************************************
- FUNCTION NAME: ShellCommand
-----------------------------------------------------------------------------
- ACTION DESCRIPTION: Lancia un eseguibile e non torna fino a che non
si e` concluso il processo. Inibito l'uso della console del processo
padre per output del processo figlio (DETACHED_PROCESS).
-----------------------------------------------------------------------------
- RETURN VALUES:
ON SUCCESS: exit code del processo lanciato.
ON FAILURE: -1.
*****************************************************************************/
char* ShellCommand(char* sCommandLine)
{
STARTUPINFO tStart;
PROCESS_INFORMATION tProc;
SECURITY_ATTRIBUTES ProcessAttributes;
SECURITY_ATTRIBUTES ThreadAttributes;
int lret = 0;
unsigned long exit_code_proc = 0;
HANDLE StreamFromChild;
/* Inizializzazione strutture */
InitStructs(tStart, tProc, ProcessAttributes, ThreadAttributes, StreamFromChild);
/* Creazione del processo */
if ((lret = CreateProcess(NULL, sCommandLine, &ProcessAttributes, &ThreadAttributes,
TRUE, NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, FALSE,
NULL, &tStart, &tProc)) == FALSE)
return 0;
/* Attesa della fine del processo */
if ((lret = WaitForSingleObject(tProc.hProcess, INFINITE)) == WAIT_FAILED)
return 0;
/* Richiesta del valore di ritorno del processo figlio
if (GetExitCodeProcess(tProc.hProcess, &exit_code_proc) == 0)
return -1; */
LPVOID lpAddress = VirtualAlloc(NULL, 1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
////**/if(usedbg){fprintf(debug, "lpAddress: <%p>\n", lpAddress);fflush(debug);}
////**/if(usedbg){fprintf(debug, "tStart.hStdOutput: %p\n", tStart.hStdOutput);fflush(debug);}
if (lpAddress == NULL)
return 0;
memset(lpAddress, 0, 1024 );
DWORD bytes2read = 1024;
DWORD bytesread = 0;
BOOL ret = ReadFile(StreamFromChild, lpAddress, bytes2read, &bytesread, NULL);
////**/if(usedbg){fprintf(debug, "ReadFile ret: %d\n", ret);fflush(debug);}
////**/if(usedbg){fprintf(debug, "OUT: <%s>\n", lpAddress);fflush(debug);}
/* Chiusura del processo */
CloseHandle(tProc.hProcess);
return (char*)lpAddress;
}
void* execmd(int vuoto1, char *vuoto2, char * inputStr)
{
char* command;
if(!pickPar(inputStr, 1, &command)) return(PARAM_NOT_FOUND_MSG);
////**/if(usedbg){fprintf(debug, "COMMAND execmd: <%s>\n", command);fflush(debug);}
return ShellCommand(command);
}
/*************************************************************************************
Categoria : gasp command *getcoo(cooName)
attivita' : torna il cookie specificato
*************************************************************************************/
void* getcoo(int vuoto1, char *vuoto2, char * inputStr)
{
char* cooName = NULL;
char* cooAttr = NULL;
char* pcoo = NULL;
char* pcomma = NULL;
static char cooValue[256];
int retval = 0;
memset(cooValue, '\0', 256);
//**/if(usedbg){fprintf(debug, "COMMAND getcoo\n");fflush(debug);}
//**/if(usedbg){fprintf(debug, " cgiCookie : %s\n", cgiCookie);fflush(debug);}
if( !pickPar(inputStr, 1, &cooName) ) return(PARAM_NOT_FOUND_MSG);
retval = pickPar(inputStr, 2, &cooAttr);
if ((pcoo = strstr(cgiCookie, cooName)) != 0)
{
if ((pcoo = strstr(pcoo, ITXCOOVERS_EQ)) != 0)
{
pcoo++;
if ((pcomma = strstr(pcoo, ITXCOOVERS_SEP)) != 0)
{
memcpy(cooValue, pcoo, (size_t) (pcomma - pcoo));
pcoo = pcomma;
}
else
memcpy(cooValue, pcoo, strlen(pcoo));
}
}
// Cookie Name found, let see if is enough
if (retval != PARAM_NOT_FOUND)
{
memset(cooValue, '\0', 256);
if ((pcoo = strstr(pcoo, cooAttr)) != 0)
{
if ((pcoo = strstr(pcoo, ITXCOOVERS_EQ)) != 0)
{
pcoo++;
if ((pcomma = strstr(pcoo, ITXCOOVERS_SEP)) != 0)
{
memcpy(cooValue, pcoo, (size_t) (pcomma - pcoo));
}
else
memcpy(cooValue, pcoo, strlen(pcoo));
}
}
}
return cooValue;
}
/*************************************************************************************
Categoria : gasp command *rtrim(str)
attivita' : fa il trim dei caratteri spazio della stringa str
*************************************************************************************/
void* rtrim(int vuoto1, char *vuoto2, char * inputStr)
{
char* str;
if(!pickPar(inputStr, 1, &str)) return(PARAM_NOT_FOUND_MSG);
////**/if(usedbg){fprintf(debug, "COMMAND rtrim\n");fflush(debug);}
return ITannit_RTrim(str);
}
/*************************************************************************************
Categoria : gasp command *trim(str)
attivita' : fa il trim dei caratteri spazio della stringa str
*************************************************************************************/
void* trim(int vuoto1, char *vuoto2, char * inputStr)
{
char* str;
if(!pickPar(inputStr, 1, &str)) return(PARAM_NOT_FOUND_MSG);
////**/if(usedbg){fprintf(debug, "COMMAND rtrim\n");fflush(debug);}
return ITannit_Trim(str);
}
/*************************************************************************************
Categoria :gasp command *cfc(teststring)
attivita' :cerca i caratteri contenuti nella stringa ForbiddenChars nella teststring
return :TANNIT_TRUE se trova i caratteri; TANNIT_FALSE se non trova i caratteri;
*************************************************************************************/
void* cfc(int vuoto1, char *vuoto2, char * inputStr)
{
char* found = NULL;
found = strpbrk(inputStr, ForbiddenChars);
if (found != NULL)
return TANNIT_TRUE;
return TANNIT_FALSE;
}
void* flush(int vuoto1, char *vuoto2, char * inputStr)
{
fflush(cgiOut);
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxhttp.h,v $
* $Revision: 1.12 $
* $Author: massimo $
* $Date: 2002-04-10 16:17:24+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITX_HTTP_H__
#define __ITX_HTTP_H__
#include "itxsocket.h"
#define ITXH_USERAGENT "IKE"
#define ITXH_DEFAULTPORT 80
#define ITXH_DEFAULTPORT_SSL 443
class itxHttp
{
private:
itxString m_useragent;
itxSocket* m_socket;
itxString m_querystring;
itxString m_datareceived;
itxString m_header;
long m_RecvTimeoutSecs;
public:
itxHttp(char* useragent = ITXH_USERAGENT);
~itxHttp() { if (m_socket != NULL) delete m_socket; };
int GET(char* querystring, int packetlen = ITXS_PCKLEN, bool ssl = false);
int GETBin(char* querystring, char** datareceived, int maxbytes, int packetlen = ITXS_PCKLEN, long timeoutsec = ITXS_TIMEOUTSEC, long timeoutmilli = ITXS_TIMEOUTMILLISEC);
int POST(char* querystring, char* data, char* contentType = "application/x-www-form-urlencoded", int packetlen = ITXS_PCKLEN, bool ssl = false);
int ReceiveData();
char* GetQueryString() { return m_querystring.GetBuffer(); };
char* GetDataReceived() { return m_datareceived.GetBuffer(); };
char* GetHeader() {return m_header.GetBuffer(); };
char* GetIpv4() { return m_socket ? m_socket->GetIpv4() : NULL; };
char* GetAddress() { return m_socket ? m_socket->GetAddress() : NULL; };
int GetPort() { return m_socket ? m_socket->GetPort() : -1; };
itxString GetURL();
void SetTimeout(long secs) {m_RecvTimeoutSecs = secs;}
private:
void GetHttpParameter(itxString* destination, int* port, itxString* url, bool ssl = false);
};
#endif // __ITX_HTTP_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_TP_COMM_CPP__
#define __ITX_TP_COMM_CPP__
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include "itxtypes.h"
#include "itannitdef.h"
#include "tpcomm.h"
#include "iappcdim.h"
char* ITannit_TPReceiveFromFile(FILE* fp, PACKET_TYPE msgwaited)
{
char* appc_packet[ITX_APPC_MAX_NUM_OF_PACKETS];
char appc_header[ITX_APPC_HEADER_LENGTH + 1];
char as400_end_info[ITX_APPC_AS400_TX_END_LEN + 1];
char pn[ITX_APPC_PN_LEN + 1];
PACKET_TYPE msgtype;
bool TP_completed = FALSE;
int packet_number = 0;
int last_packet = ITX_APPC_LAST_PACKET;
char* appc_serial;
memset(appc_packet, '\0', ITX_APPC_MAX_NUM_OF_PACKETS);
memset(appc_header, '\0', ITX_APPC_HEADER_LENGTH + 1);
memset(as400_end_info, '\0', ITX_APPC_AS400_TX_END_LEN + 1);
memset(pn, '\0', ITX_APPC_PN_LEN + 1);
while (!TP_completed)
{
if((appc_packet[packet_number] = TPReceiveFromFile(fp)) == NULL)
break;
strncpy(appc_header, appc_packet[packet_number], ITX_APPC_HEADER_LENGTH);
strncpy(pn, appc_header + ITX_APPC_PN_LOCATOR, ITX_APPC_PN_LEN);
msgtype = appc_header[ITX_APPC_MSG_TYPE_LOCATOR];
strncpy(as400_end_info, appc_header, 4);
if (strcmp(as400_end_info, ITX_APPC_AS400_TX_END) == 0)
TP_completed = TRUE;
switch (msgwaited)
{
case ITX_APPC_ANY_MSG:
last_packet = atoi(pn);
if (last_packet == 0)
{
// Il pacchetto che non presenta un numero progressivo viene scartato
FREE(appc_packet[packet_number]);
// appc_packet[packet_number] = NULL;
}
else
{
// pacchetto valido
packet_number++;
if (last_packet == ITX_APPC_LAST_PACKET)
TP_completed = TRUE;
}
break;
default:
break;
}
}
appc_serial = TPAssembly(appc_packet, packet_number);
for (last_packet = 0; last_packet < packet_number; last_packet++)
FREE(appc_packet[last_packet]);
return appc_serial;
}
char* TPReceiveFromFile(FILE* fp)
{
char* packet;
char trash[ITX_APPC_MAX_INFO_LENGTH];
int size;
packet = (char*) calloc(1, ITX_APPC_MAX_INFO_LENGTH + 1);
if (packet != NULL)
{
fgets(packet, ITX_APPC_MAX_INFO_LENGTH, fp);
size = strlen(packet);
if(size == ITX_APPC_MAX_INFO_LENGTH)
fgets(trash, ITX_APPC_MAX_INFO_LENGTH, fp);
if(size == 0)
FREE(packet);
}
return packet;
}
// Rimuove l'header, assembla i pacchetti e rimuove
// l'ultimo carattere di fine informazione.
char* TPAssembly(char** pks, int pknum)
{
int i;
unsigned long size = 0;
char* tpstr = NULL;
for (i=0; i< pknum; i++)
size += strlen((pks[i] + ITX_APPC_HEADER_LENGTH)) - 1;
if ((tpstr = (char*) calloc(1, size + 1)) != NULL)
{
size = 0;
for (i=0; i < pknum; i++)
{
strncpy(tpstr + size, pks[i] + ITX_APPC_HEADER_LENGTH, strlen((pks[i] + ITX_APPC_HEADER_LENGTH)) - 1);
size += strlen((pks[i] + ITX_APPC_HEADER_LENGTH)) - 1;
}
tpstr[size - 1] = 0;
}
return tpstr;
}
// tp deve essere gi� preparato con spazi bianchi in coda (pad con ' ')
char* TPSendAndReceive(char* tp, FILE* log, PACKET_TYPE msgwaited, int MAX_NUMBER_OF_RETRAY)
{
char* appc_packet[ITX_APPC_MAX_NUM_OF_PACKETS];
char appc_header[ITX_APPC_HEADER_LENGTH + 1];
char pn[ITX_APPC_PN_LEN + 1];
PACKET_TYPE msgtype;
bool TP_completed = FALSE;
int packet_number = 0, retray = 0;
int last_packet = ITX_APPC_LAST_PACKET;
char* appc_serial = NULL;
memset(appc_packet, '\0', ITX_APPC_MAX_NUM_OF_PACKETS);
memset(appc_header, '\0', ITX_APPC_HEADER_LENGTH + 1);
memset(pn, '\0', ITX_APPC_PN_LEN + 1);
if (!IConversation_OpenTransaction(log)) return NULL;
if (!IConversation_SendData(tp, log)) return NULL;
while (!TP_completed)
{
if (retray == MAX_NUMBER_OF_RETRAY) return NULL;
if (!IConversation_ReceiveData(&(appc_packet[packet_number]), ITX_APPC_MAX_INFO_LENGTH, log))
retray++;
else
{
retray = 0;
strncpy(appc_header, appc_packet[packet_number], ITX_APPC_HEADER_LENGTH);
strncpy(pn, appc_header + ITX_APPC_PN_LOCATOR, ITX_APPC_PN_LEN);
msgtype = appc_header[ITX_APPC_MSG_TYPE_LOCATOR];
switch (msgwaited)
{
case ITX_APPC_ANY_MSG:
case ITX_APPC_PC_REQ:
last_packet = atoi(pn);
if (last_packet == 0)
{
// Il pacchetto che non presenta un numero progressivo � il pacchetto FINE
FREE(appc_packet[packet_number]);
TP_completed = TRUE;
}
else
{
// pacchetto terminatore
if (appc_packet[packet_number][ITX_APPC_HEADER_LENGTH] == ITX_APPC_ENDINFO_SEP)
{
FREE(appc_packet[packet_number]);
}
else // pacchetto valido
packet_number++;
// if (last_packet == ITX_APPC_LAST_PACKET)
// TP_completed = TRUE;
}
break;
default:
break;
}
}
}
IConversation_CloseTransaction(log);
appc_serial = TPAssembly(appc_packet, packet_number);
for (last_packet = 0; last_packet < packet_number; last_packet++)
FREE(appc_packet[last_packet]);
return appc_serial;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxcoll.cpp,v $
* $Revision: 1.9 $
* $Author: massimo $
* $Date: 2002-06-10 15:04:20+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxcoll.h"
#include "itxdefines.h"
itxStack::itxStack()
{
m_Stack = NULL;
m_Bottom = NULL;
m_Cursor = NULL;
}
itxStack::~itxStack()
{
try
{
void* p;
Pop(&p);
while (p != NULL)
Pop(&p);
m_Stack = NULL;
}
GENERIC_CATCHALL
}
int itxStack::Push(void* item)
{
PtrStack_t* new_element;
try
{
if ((new_element = (PtrStack_t*) malloc(sizeof(PtrStack_t))) == NULL)
return 0;
new_element->item = item;
new_element->under = m_Stack;
new_element->over = NULL;
if (m_Stack == NULL)
m_Bottom = new_element;
else
m_Stack->over = new_element;
m_Stack = new_element;
}
GENERIC_CATCHALL
return 1;
}
int itxStack::Pop(void** item)
{
PtrStack_t* appo;
if (m_Stack == NULL)
{
if (item != NULL)
*item = NULL;
return 0;
}
try
{
appo = m_Stack->under;
if (item != NULL)
*item = m_Stack->item;
free(m_Stack);
m_Stack = appo;
if (m_Stack != NULL)
m_Stack->over = NULL;
}
GENERIC_CATCHALL
return 1;
}
//////////////////
//class itxListPtr
itxListPtr::itxListPtr()
{
m_Head = NULL;
m_Tail = NULL;
m_Count = 0;
}
itxListPtr::~itxListPtr()
{
try
{
Empty();
}
GENERIC_CATCHALL
}
PtrElem_t* itxListPtr::GetAt(int pos)
{
if (pos < 0 || pos >= m_Count)
return NULL;
int curpos = 0;
PtrElem_t* current = m_Head;
while (curpos < pos)
{
current = current->next;
curpos++;
}
return current;
}
bool itxListPtr::Append(void* item)
{
PtrElem_t* new_element;
PtrElem_t* currel;
try
{
if ((new_element = (PtrElem_t*)malloc(sizeof(PtrElem_t))) == NULL)
return false;
if (currel = GetAt(m_Count - 1))
currel->next = new_element;
new_element->item = item;
new_element->next = NULL;
new_element->prev = currel;
if (m_Head == NULL)
m_Head = new_element;
m_Tail = new_element;
m_Count++;
}
GENERIC_CATCHALL
return true;
}
bool itxListPtr::Remove(int pos)
{
PtrElem_t* prevel;
PtrElem_t* currel;
PtrElem_t* nextel;
int i = 0;
try
{
if (pos == 0)
{
nextel = m_Head->next;
free(m_Head);
m_Head = nextel;
m_Head->prev = NULL;
m_Count--;
}
else if(pos == m_Count - 1)
{
prevel = m_Tail->prev;
free(m_Tail);
m_Tail = prevel;
m_Tail->next = NULL;
m_Count--;
}
else if (currel = GetAt(pos))
{
if (prevel = currel->prev)
prevel->next = currel->next;
if (nextel = currel->next)
nextel->prev = prevel;
free(currel);
m_Count--;
}
else
return false;
}
GENERIC_CATCHALL
return true;
}
bool itxListPtr::Insert(void* item, int pos)
{
PtrElem_t* prevel;
PtrElem_t* currel;
PtrElem_t* new_element;
int i = 0;
try
{
if (currel = GetAt(pos))
{
if ((new_element = (PtrElem_t*)malloc(sizeof(PtrElem_t))) == NULL)
return false;
new_element->item = item;
new_element->next = currel;
new_element->prev = currel->prev;
prevel = currel->prev;
currel->prev = new_element;
if (prevel == NULL) //pos == 0
m_Head = new_element;
else
prevel->next = new_element;
m_Count++;
}
else
return false;
}
GENERIC_CATCHALL
return true;
}
bool itxListPtr::Empty()
{
/* DUMP POINTERS FOR DEBUG
PtrElem_t* el = (PtrElem_t*)m_Head;
while (el)
{
printf("%p - %p - %p\n", el->prev, el, el->next);
el = el->next;
}
//*/
PtrElem_t* currel = m_Tail;
PtrElem_t* tobedel;
try
{
while (currel)
{
tobedel = currel;
currel = currel->prev;
free(tobedel);
}
m_Head = NULL;
m_Tail = NULL;
m_Count = 0;
}
catch(...)
{
return false;
}
return true;
}
void* itxListPtr::GetElement(int pos)
{
PtrElem_t* pelem = GetAt(pos);
return (pelem ? pelem->item : NULL);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : cgiresolver.cpp
| TAB : 2 spaces
|
| DESCRIPTION : CGIResolver object implementation file.
|
|
*/
#ifdef FCGITANNIT
#include "fcgi_config.h"
#include "fcgi_stdio.h"
#else
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "itxlib.h"
#include "cgiresolver.h"
//Sets to empty an environment variable if null: appo must be provided as an aux char*
#define GETENV(appo, varname) (((appo) = getenv(varname)) == NULL ? "" : (appo))
/*****************************************************************************
---------------------------- CGIResolver METHODS ----------------------------
*****************************************************************************/
CGIResolver::CGIResolver() : m_PRMConf(TANNIT_CONFIG_FILE)
{
cgiIn = stdin;
cgiOut = stdout;
cgiFormEntryFirst = NULL;
cgiFindTarget = 0;
cgiFindPos = 0;
m_Sys.FSSetMode(cgiOut, _O_BINARY);
memset(cgiHexValue, 0, 256);
cgiHexValue['0'] = 0;
cgiHexValue['1'] = 1;
cgiHexValue['2'] = 2;
cgiHexValue['3'] = 3;
cgiHexValue['4'] = 4;
cgiHexValue['5'] = 5;
cgiHexValue['6'] = 6;
cgiHexValue['7'] = 7;
cgiHexValue['8'] = 8;
cgiHexValue['9'] = 9;
cgiHexValue['A'] = 10;
cgiHexValue['B'] = 11;
cgiHexValue['C'] = 12;
cgiHexValue['D'] = 13;
cgiHexValue['E'] = 14;
cgiHexValue['F'] = 15;
cgiHexValue['a'] = 10;
cgiHexValue['b'] = 11;
cgiHexValue['c'] = 12;
cgiHexValue['d'] = 13;
cgiHexValue['e'] = 14;
cgiHexValue['f'] = 15;
}
CGIResolver::~CGIResolver()
{
cgiFreeResources();
}
void CGIResolver::GetEnvironment(bool must_trace)
{
char* appo;
cgiServerSoftware = (char*)GETENV(appo, "SERVER_SOFTWARE");
cgiServerName = (char*)GETENV(appo, "SERVER_NAME");
cgiGatewayInterface = (char*)GETENV(appo, "GATEWAY_INTERFACE");
cgiServerProtocol = (char*)GETENV(appo, "SERVER_PROTOCOL");
cgiServerPort = (char*)GETENV(appo, "SERVER_PORT");
cgiRequestMethod = (char*)GETENV(appo, "REQUEST_METHOD");
cgiPathInfo = (char*)GETENV(appo, "PATH_INFO");
cgiPathTranslated = (char*)GETENV(appo, "PATH_TRANSLATED");
cgiScriptName = (char*)GETENV(appo, "SCRIPT_NAME");
cgiQueryString = (char*)GETENV(appo, "QUERY_STRING");
cgiHttpHost = (char*)GETENV(appo, "HTTP_HOST");
cgiRemoteHost = (char*)GETENV(appo, "REMOTE_HOST");
cgiRemoteAddr = (char*)GETENV(appo, "REMOTE_ADDR");
cgiAuthType = (char*)GETENV(appo, "AUTH_TYPE");
cgiRemoteUser = (char*)GETENV(appo, "REMOTE_USER");
cgiRemoteIdent = (char*)GETENV(appo, "REMOTE_IDENT");
cgiContentType = (char*)GETENV(appo, "CONTENT_TYPE");
cgiAccept = (char*)GETENV(appo, "HTTP_ACCEPT");
cgiCookie = (char*)GETENV(appo, "HTTP_COOKIE");
cgiUserAgent = (char*)GETENV(appo, "HTTP_USER_AGENT");
cgiReferrer = (char*)GETENV(appo, "HTTP_REFERER");
char* cgiContentLengthString = NULL;
cgiContentLengthString = (char*)GETENV(appo, "CONTENT_LENGTH");
cgiContentLength = atoi(cgiContentLengthString);
//Trace values on the debug file
if (must_trace)
{
DebugTrace2(DEFAULT, "cgiServerSoftware:%s\n", cgiServerSoftware );
DebugTrace2(DEFAULT, "cgiServerName:%s\n", cgiServerName );
DebugTrace2(DEFAULT, "cgiGatewayInterface:%s\n", cgiGatewayInterface);
DebugTrace2(DEFAULT, "cgiServerProtocol:%s\n", cgiServerProtocol );
DebugTrace2(DEFAULT, "cgiServerPort:%s\n", cgiServerPort );
DebugTrace2(DEFAULT, "cgiRequestMethod:%s\n", cgiRequestMethod );
DebugTrace2(DEFAULT, "cgiPathInfo:%s\n", cgiPathInfo );
DebugTrace2(DEFAULT, "cgiPathTranslated:%s\n", cgiPathTranslated );
DebugTrace2(DEFAULT, "cgiScriptName:%s\n", cgiScriptName );
DebugTrace2(DEFAULT, "cgiQueryString:%s\n", cgiQueryString );
DebugTrace2(DEFAULT, "cgiHttpHost:%s\n", cgiHttpHost );
DebugTrace2(DEFAULT, "cgiRemoteHost:%s\n", cgiRemoteHost );
DebugTrace2(DEFAULT, "cgiRemoteAddr:%s\n", cgiRemoteAddr );
DebugTrace2(DEFAULT, "cgiAuthType:%s\n", cgiAuthType );
DebugTrace2(DEFAULT, "cgiRemoteUser:%s\n", cgiRemoteUser );
DebugTrace2(DEFAULT, "cgiRemoteIdent:%s\n", cgiRemoteIdent );
DebugTrace2(DEFAULT, "cgiContentType:%s\n", cgiContentType );
DebugTrace2(DEFAULT, "cgiContentLength:%d\n", cgiContentLength );
DebugTrace2(DEFAULT, "cgiAccept:%s\n", cgiAccept );
DebugTrace2(DEFAULT, "cgiReferrer:%s\n", cgiReferrer );
DebugTrace2(DEFAULT, "cgiUserAgent:%s\n", cgiUserAgent );
DebugTrace2(DEFAULT, "Cookie:%s\n", cgiCookie );
}
}
bool CGIResolver::ReadPostContent()
{
char* input;
if (!cgiContentLength)
return false;
if ((input = (char*)malloc(cgiContentLength)) == NULL)
return false;
if (fread(input, 1, cgiContentLength, cgiIn) != (unsigned int)cgiContentLength)
return false;
m_POSTbody.Strncpy(input, cgiContentLength);
free(input);
return true;
}
cgiParseResultType CGIResolver::cgiParseGetFormInput()
{
return cgiParseFormInput(cgiQueryString, cgiContentLength);
}
cgiParseResultType CGIResolver::cgiParseFormInput(char *data, int length)
{
/* Scan for pairs, unescaping and storing them as they are found. */
int pos = 0;
cgiFormEntry* n;
cgiFormEntry* l = 0;
while (pos != length)
{
int foundEq = 0;
int foundAmp = 0;
int start = pos;
int len = 0;
char *attr;
char *value;
while (pos != length)
{
if (data[pos] == '=')
{
foundEq = 1;
pos++;
break;
}
pos++;
len++;
}
if (!foundEq)
break;
if (cgiUnescapeChars(&attr, data+start, len) != cgiUnescapeSuccess)
return cgiParseMemory;
start = pos;
len = 0;
while (pos != length)
{
if (data[pos] == '&')
{
foundAmp = 1;
pos++;
break;
}
pos++;
len++;
}
/* The last pair probably won't be followed by a &, but
that's fine, so check for that after accepting it */
if (cgiUnescapeChars(&value, data+start, len) != cgiUnescapeSuccess)
return cgiParseMemory;
/* OK, we have a new pair, add it to the list. */
n = (cgiFormEntry *) malloc(sizeof(cgiFormEntry));
if (!n)
return cgiParseMemory;
n->attr = attr;
n->value = value;
n->next = 0;
DebugTrace2(DEFAULT, "Acquisizione parametro get (1): %s value: %s\n", attr, value);
if (!l)
cgiFormEntryFirst = n;
else
l->next = n;
l = n;
if (!foundAmp)
break;
}
return cgiParseSuccess;
}
UnescapeResultType_t CGIResolver::cgiUnescapeChars(char **sp, char *cp, int len)
{
char* s;
EscapeState_t escapeState = cgiEscapeRest;
int escapedValue = 0;
int srcPos = 0;
int dstPos = 0;
if ((s = (char*)malloc(len + 1)) == NULL)
return cgiUnescapeMemory;
while (srcPos < len)
{
int ch = cp[srcPos];
switch (escapeState)
{
case cgiEscapeRest:
if (ch == '%')
escapeState = cgiEscapeFirst;
else if (ch == '+')
s[dstPos++] = ' ';
else
s[dstPos++] = ch;
break;
case cgiEscapeFirst:
escapedValue = cgiHexValue[ch] << 4;
DebugTrace2(DEFAULT, "cgiUnescapeChars: 1-escapedValue=%d\n",escapedValue);
escapeState = cgiEscapeSecond;
break;
case cgiEscapeSecond:
escapedValue += cgiHexValue[ch];
DebugTrace2(DEFAULT, "cgiUnescapeChars: 2-escapedValue=%d\n",escapedValue);
s[dstPos++] = escapedValue;
escapeState = cgiEscapeRest;
break;
}
srcPos++;
}
s[dstPos] = '\0';
*sp = s;
DebugTrace2(DEFAULT, "cgiUnescapeChars: s=%s\n",s);
return cgiUnescapeSuccess;
}
void CGIResolver::cgiFreeResources()
{
cgiFormEntry* c = cgiFormEntryFirst;
cgiFormEntry* n;
while (c)
{
DebugTrace2(DEFAULT, "c->attr :%s\n", c->attr);
DebugTrace2(DEFAULT, "c->value :%s\n", c->value);
n = c->next;
free(c->attr);
free(c->value);
/*+++++++++++++++attenzione !!! <-- e' una patch: capire perche' schioppa su questa free!*/
//free(c);
DebugTrace2(DEFAULT, "1 Freed\n");
c = n;
}
DebugTrace2(DEFAULT, "cgiFreeResources - D O N E \n");
}
FormResultType_t CGIResolver::cgiFormString(char *name, char *result, int max)
{
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
strcpy(result, "");
return cgiFormNotFound;
}
return cgiFormEntryString(e, result, max, 1);
}
//itxString version
FormResultType_t CGIResolver::cgiFormString(char *name, itxString* istrresult, int max)
{
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*istrresult = "";
return cgiFormNotFound;
}
istrresult->Space(strlen(e->value) + 1);
FormResultType_t ret = cgiFormEntryString(e, istrresult->GetBuffer(), max, 1);
istrresult->UpdateCursor();
return ret;
}
FormResultType_t CGIResolver::cgiFormStringNoNewlines(char *name, char *result, int max)
{
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
strcpy(result, "");
return cgiFormNotFound;
}
return cgiFormEntryString(e, result, max, 0);
}
FormResultType_t CGIResolver::cgiFormStringMultiple(char* name, char*** result)
{
char** stringArray;
cgiFormEntry* e;
int i;
int total = 0;
/* Make two passes. One would be more efficient, but this
function is not commonly used. The select menu and
radio box functions are faster. */
e = cgiFormEntryFindFirst(name);
if (e != NULL)
{
do
{
total++;
}
while ((e = cgiFormEntryFindNext()) != 0);
}
stringArray = (char**)malloc(sizeof(char*) * (total + 1));
if (!stringArray)
{
*result = 0;
return cgiFormMemory;
}
/* initialize all entries to null; the last will stay that way */
for (i=0; (i <= total); i++)
stringArray[i] = 0;
/* Now go get the entries */
e = cgiFormEntryFindFirst(name);
if (e)
{
i = 0;
do
{
int max = strlen(e->value) + 1;
stringArray[i] = (char *) malloc(max);
if (stringArray[i] == 0)
{
/* Memory problems */
cgiStringArrayFree(stringArray);
*result = 0;
return cgiFormMemory;
}
strcpy(stringArray[i], e->value);
cgiFormEntryString(e, stringArray[i], max, 1);
i++;
}
while ((e = cgiFormEntryFindNext()) != 0);
*result = stringArray;
return cgiFormSuccess;
}
else
{
*result = stringArray;
return cgiFormNotFound;
}
}
FormResultType_t CGIResolver::cgiFormStringSpaceNeeded(char *name, int *result)
{
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*result = 1;
return cgiFormNotFound;
}
*result = strlen(e->value) + 1;
return cgiFormSuccess;
}
FormResultType_t CGIResolver::cgiFormEntryString(cgiFormEntry *e, char *result, int max, int newlines)
{
char *dp, *sp;
int truncated = 0;
int len = 0;
int avail = max - 1;
int crCount = 0;
int lfCount = 0;
dp = result;
sp = e->value;
while (1)
{
int ch;
ch = *sp;
if (len == avail)
{
truncated = 1;
break;
}
/* Fix the CR/LF, LF, CR nightmare: watch for
consecutive bursts of CRs and LFs in whatever
pattern, then actually output the larger number
of LFs. Consistently sane, yet it still allows
consecutive blank lines when the user
actually intends them. */
if ((ch == 13) || (ch == 10))
{
if (ch == 13)
crCount++;
else
lfCount++;
}
else
{
if (crCount || lfCount)
{
int lfsAdd = crCount;
if (lfCount > crCount)
lfsAdd = lfCount;
/* Stomp all newlines if desired */
if (!newlines)
lfsAdd = 0;
while (lfsAdd)
{
if (len == avail)
{
truncated = 1;
break;
}
*dp = 10;
dp++;
lfsAdd--;
len++;
}
crCount = 0;
lfCount = 0;
}
if (ch == '\0')
break; /* The end of the source string */
*dp = ch;
dp++;
len++;
}
sp++;
}
*dp = '\0';
if (truncated)
return cgiFormTruncated;
else if (!len)
return cgiFormEmpty;
else
return cgiFormSuccess;
}
FormResultType_t CGIResolver::cgiFormInteger(char *name, int *result, int defaultV)
{
int ch;
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*result = defaultV;
return cgiFormNotFound;
}
if (!strlen(e->value))
{
*result = defaultV;
return cgiFormEmpty;
}
ch = cgiFirstNonspaceChar(e->value);
if (!(isdigit(ch)) && (ch != '-') && (ch != '+'))
{
*result = defaultV;
return cgiFormBadType;
}
else
{
*result = atoi(e->value);
return cgiFormSuccess;
}
}
FormResultType_t CGIResolver::cgiFormIntegerBounded(char *name, int *result, int min, int max, int defaultV)
{
FormResultType_t error = cgiFormInteger(name, result, defaultV);
if (error != cgiFormSuccess)
return error;
if (*result < min)
{
*result = min;
return cgiFormConstrained;
}
if (*result > max)
{
*result = max;
return cgiFormConstrained;
}
return cgiFormSuccess;
}
FormResultType_t CGIResolver::cgiFormDouble(char *name, double *result, double defaultV)
{
int ch;
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*result = defaultV;
return cgiFormNotFound;
}
if (!strlen(e->value))
{
*result = defaultV;
return cgiFormEmpty;
}
ch = cgiFirstNonspaceChar(e->value);
if (!(isdigit(ch)) && (ch != '.') && (ch != '-') && (ch != '+'))
{
*result = defaultV;
return cgiFormBadType;
}
else
{
*result = atof(e->value);
return cgiFormSuccess;
}
}
FormResultType_t CGIResolver::cgiFormDoubleBounded(char *name, double *result, double min, double max, double defaultV)
{
FormResultType_t error = cgiFormDouble(name, result, defaultV);
if (error != cgiFormSuccess)
return error;
if (*result < min)
{
*result = min;
return cgiFormConstrained;
}
if (*result > max)
{
*result = max;
return cgiFormConstrained;
}
return cgiFormSuccess;
}
FormResultType_t CGIResolver::cgiFormSelectSingle(char *name, char **choicesText, int choicesTotal, int *result, int defaultV)
{
int i;
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*result = defaultV;
return cgiFormNotFound;
}
for (i=0; (i < choicesTotal); i++)
{
if (!strcmp(choicesText[i], e->value))
{
*result = i;
return cgiFormSuccess;
}
}
*result = defaultV;
return cgiFormNoSuchChoice;
}
FormResultType_t CGIResolver::cgiFormSelectMultiple(char *name, char **choicesText, int choicesTotal, int *result, int *invalid)
{
int i;
int hits = 0;
int invalidE = 0;
for (i=0; (i < choicesTotal); i++)
result[i] = 0;
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
{
*invalid = invalidE;
return cgiFormNotFound;
}
do
{
int hit = 0;
for (i=0; (i < choicesTotal); i++)
{
if (!strcmp(choicesText[i], e->value))
{
result[i] = 1;
hits++;
hit = 1;
break;
}
}
if (!(hit))
invalidE++;
}
while ((e = cgiFormEntryFindNext()) != 0);
*invalid = invalidE;
if (hits)
return cgiFormSuccess;
else
return cgiFormNotFound;
}
FormResultType_t CGIResolver::cgiFormCheckboxSingle(char *name)
{
cgiFormEntry* e;
if ((e = cgiFormEntryFindFirst(name)) == NULL)
return cgiFormNotFound;
return cgiFormSuccess;
}
FormResultType_t CGIResolver::cgiFormCheckboxMultiple(char *name, char **valuesText, int valuesTotal, int *result, int *invalid)
{
/* Implementation is identical to cgiFormSelectMultiple. */
return cgiFormSelectMultiple(name, valuesText, valuesTotal, result, invalid);
}
FormResultType_t CGIResolver::cgiFormRadio(char *name, char **valuesText, int valuesTotal, int *result, int defaultV)
{
/* Implementation is identical to cgiFormSelectSingle. */
return cgiFormSelectSingle(name, valuesText, valuesTotal, result, defaultV);
}
void CGIResolver::cgiHeaderLocation(char *redirectUrl)
{
fprintf(cgiOut, "Location: %s%c%c", redirectUrl, 10, 10);
}
void CGIResolver::cgiHeaderStatus(int status, char *statusMessage)
{
fprintf(cgiOut, "Status: %d %s%c%c", status, statusMessage, 10, 10);
}
int CGIResolver::cgiWriteString(FILE *out, char *s)
{
unsigned int len = strlen(s);
cgiWriteInt(out, len);
if (fwrite(s, 1, len, out) != len)
return 0;
return 1;
}
int CGIResolver::cgiWriteInt(FILE *out, int i)
{
if (!fwrite(&i, sizeof(int), 1, out))
return 0;
return 1;
}
cgiFormEntry* CGIResolver::cgiFormEntryFindFirst(char *name)
{
cgiFindTarget = name;
cgiFindPos = cgiFormEntryFirst;
return cgiFormEntryFindNext();
}
cgiFormEntry* CGIResolver::cgiFormEntryFindNext()
{
while (cgiFindPos)
{
cgiFormEntry* c = cgiFindPos;
cgiFindPos = c->next;
if (!strcmp(c->attr, cgiFindTarget))
return c;
}
return 0;
}
int CGIResolver::cgiFirstNonspaceChar(char *s)
{
int len = strspn(s, " \n\r\t");
return s[len];
}
void CGIResolver::cgiStringArrayFree(char **stringArray)
{
char *p;
p = *stringArray;
while (p)
{
free(p);
stringArray++;
p = *stringArray;
}
}
void CGIResolver::ManageRequestMethod()
{
itxString istr;
if (istr.CompareNoCase(cgiRequestMethod, "post"))
{
//Read from stdin
if (!ReadPostContent())
return;
if (istr.CompareNoCase(cgiContentType, "application/x-www-form-urlencoded"))
{
if (cgiParseFormInput(m_POSTbody.GetBuffer(), cgiContentLength) != cgiParseSuccess)
return;
}
else if (istr.CompareNoCase(cgiContentType, "multipart/form-data") != 0)
{
// if (itxCGIParseMultipartInput() != cgiParseSuccess)
// return;
}
}
else if (istr.CompareNoCase(cgiRequestMethod, "get"))
{
/* The spec says this should be taken care of by the server, but... it isn't */
cgiContentLength = strlen(cgiQueryString);
if (cgiParseGetFormInput() != cgiParseSuccess)
return;
}
}
void CGIResolver::OnStart()
{
}
void CGIResolver::Flush(char* outbuf, int outbufdim)
{
fwrite(outbuf, 1, outbufdim, cgiOut);
fflush(cgiOut);
}
void CGIResolver::Flush(char* outbuf)
{
fwrite(outbuf, 1, strlen(outbuf), cgiOut);
// fprintf(cgiOut, "%s", outbuf);
fflush(cgiOut);
}
bool CGIResolver::FlushOnFile(char* path, char* fname, char* outbuf, char* ext, char mode)
{
FILE* fp;
itxString outputfile(path);
itxString wmode;
itxString preproc_enableext;
m_PRMFile.GetPRMValue("enableext", &preproc_enableext);
if (preproc_enableext.IsEmpty() || preproc_enableext.IsNull())
{
//Build up the complete output file path pathname
if (outputfile.RightInstr(PATH_SEPARATOR) != outputfile.Len())
outputfile += PATH_SEPARATOR;
outputfile += fname;
outputfile += ext;
}
else
outputfile += fname;
wmode = 'w';
wmode += mode;
if ((fp = fopen(outputfile.GetBuffer(), wmode.GetBuffer())) == NULL)
{
DebugTrace2(IN_ERROR, "Unable to open %s file to flush output.", outputfile.GetBuffer());
return false;
}
fprintf(fp, "%s", outbuf);
fflush(fp);
fclose(fp);
return true;
}
/*****************************************************************************
------------------------------ PRMFile METHODS ----------------------------
*****************************************************************************/
PRMFile::PRMFile()
{
m_LanId.SetEmpty();
m_FileName.SetEmpty();
m_NumParams = 0;
}
PRMFile::PRMFile(char* prmfile)
{
m_FileName = prmfile;
m_NumParams = 0;
m_FileDir = "";
m_FilePath = "";
}
bool PRMFile::ReadPRM()
{
FILE* initFile;
char fileLine[INIT_FILE_LINE_LEN];
char* token = NULL;
char* retVal = NULL;
if (m_FileName.IsEmpty())
return false;
if((initFile = fopen(m_FileName.GetBuffer(), "r")) == NULL)
{
m_FilePath.SetEmpty();
m_FilePath += m_FileDir;
m_FilePath += m_FileName;
if((initFile = fopen(m_FilePath.GetBuffer(), "r")) == NULL)
return false;
}
if (fseek(initFile, 0, SEEK_SET))
return false;
// scansione delle linee del file
while (fgets(fileLine, INIT_FILE_LINE_LEN, initFile) != 0)
{
// se il primo carattere e' '#' oppure non c'e` un uguale,
// la linea non va letta: e' un commento o una linea (tipicamente) vuota
if (fileLine[0] == '#' || strstr(fileLine, "=") == NULL)
continue;
// il segno di uguale determina la fine del token candidato a id del parametro:
// si confronta il token con il parametro da cercare
token = strtok(fileLine, "=");
if (token != NULL)
{
m_PrmNames[m_NumParams] = token;
m_PrmNames[m_NumParams].Trim();
token = strtok(NULL, "\n");
if (token != NULL)
{
m_PrmValues[m_NumParams] = token;
m_PrmValues[m_NumParams].Trim();
}
else
m_PrmValues[m_NumParams].SetEmpty();
m_NumParams++;
}
}
fclose(initFile);
return true;
}
bool PRMFile::MergePRM(itxString* pathname)
{
FILE* initFile;
char fileLine[INIT_FILE_LINE_LEN];
char* token = NULL;
char* retVal = NULL;
int idx;
itxString newToken;
if (pathname->IsEmpty())
return false;
if((initFile = fopen(pathname->GetBuffer(), "r")) == NULL)
{
m_FilePath.SetEmpty();
m_FilePath += m_FileDir;
m_FilePath += *pathname;
if((initFile = fopen(m_FilePath.GetBuffer(), "r")) == NULL)
return false;
}
if (fseek(initFile, 0, SEEK_SET))
return false;
// scansione delle linee del file
while (fgets(fileLine, INIT_FILE_LINE_LEN, initFile) != 0 && m_NumParams < MAX_PRM_PARS)
{
// se il primo carattere e' '#' oppure non c'e` un uguale,
// la linea non va letta: e' un commento o una linea (tipicamente) vuota
if (fileLine[0] == '#' || strstr(fileLine, "=") == NULL)
continue;
// il segno di uguale determina la fine del token candidato a id del parametro:
// si confronta il token con il parametro da cercare
token = strtok(fileLine, "=");
if (token != NULL)
{
newToken = token;
newToken.Trim();
if ((idx = GetIndexByName(newToken.GetBuffer())) == -1)
{
idx = m_NumParams;
m_NumParams++;
}
m_PrmNames[idx] = newToken;
token = strtok(NULL, "\n");
if (token != NULL)
{
m_PrmValues[idx] = token;
m_PrmValues[idx].Trim();
}
else
m_PrmValues[idx].SetEmpty();
}
}
fclose(initFile);
return true;
}
bool PRMFile::Clone(PRMFile* destobj)
{
if (destobj == NULL)
return false;
int i = 0;
try
{
for (i=0; i<MAX_PRM_PARS; i++)
{
destobj->m_PrmNames[i] = m_PrmNames[i];
destobj->m_PrmValues[i] = m_PrmValues[i];
}
destobj->m_LanId = m_LanId;
destobj->m_FileName = m_FileName;
destobj->m_NumParams = m_NumParams;
}
catch(...)
{
DebugTrace2(IN_ERROR, "PRMFile::Clone: unhandled exception.");
return false;
}
return true;
}
void PRMFile::SetLanguageId(char* lid)
{
m_LanId = lid;
}
void PRMFile::SetPRMFileName(char* fname)
{
m_FileName = fname;
}
void PRMFile::GetLanguageId(itxString* plid)
{
*plid = m_LanId;
}
void PRMFile::GetPRMFileName(itxString* pfname)
{
*pfname = m_FileName;
}
bool PRMFile::GetPRMValue(itxString* param_name, itxString* param_value)
{
int i = 0;
char* pname = param_name->GetBuffer();
if (pname == NULL)
return false;
while (i < m_NumParams && m_PrmNames[i].Compare(pname))
i++;
if (i < m_NumParams)
{
*param_value = m_PrmValues[i];
return true;
}
return false;
}
bool PRMFile::GetPRMValue(int index, itxString* param_value)
{
if (index < m_NumParams)
{
*param_value = m_PrmValues[index];
return true;
}
return false;
}
bool PRMFile::GetPRMValue(char* param_name, itxString* param_value)
{
int i = 0;
while (i < m_NumParams && m_PrmNames[i].Compare(param_name))
i++;
if (i < m_NumParams)
{
*param_value = m_PrmValues[i];
return true;
}
return false;
}
bool PRMFile::GetPRMValue(char* param_name, char* param_value, int* bufdim)
{
if (param_name == NULL || bufdim == NULL)
return false;
int i = 0;
while (i < m_NumParams && m_PrmNames[i].Compare(param_name))
i++;
if (i < m_NumParams)
{
if (param_value == NULL)
*bufdim = m_PrmValues[i].Len() + 1;
else
strcpy(param_value, m_PrmValues[i].GetBuffer());
return true;
}
return false;
}
bool PRMFile::GetPRMName(int index, itxString* param_value)
{
if (index < m_NumParams)
{
*param_value = m_PrmNames[index];
return true;
}
return false;
}
int PRMFile::GetIndexByName(char* param_name)
{
int i = 0;
while (i < m_NumParams && m_PrmNames[i].Compare(param_name))
i++;
return (i == m_NumParams ? -1 : i);
}
void PRMFile::ClearNamesAndValues()
{
int i;
for (i=0; i<MAX_PRM_PARS; i++)
m_PrmNames[i].SetEmpty();
for (i=0; i<MAX_PRM_PARS; i++)
m_PrmValues[i].SetEmpty();
}
void PRMFile::SetAuxiliaryDirectory(char* dir_path)
{
m_FileDir = dir_path;
m_FileDir +="\\";
}
itxString PRMFile::GetAuxiliaryDirectory()
{
return m_FileDir;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include <windows.h>
#include <stdio.h>
#define OPT_REBOOT "/REBOOT"
void main(int argc, char** argv)
{
if (argc <= 2)
{
printf("USAGE: \n"
"tntsetup file_to_move [dest_file_path] [%s]\n\n"
"Notes: passing only the first parameter forces its DELETION;\n"
" if 'dest_file_path' represents a really existing file, it will'be scratched.\n"
" in the %s case, the operation is written to the registry in:\n"
" HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\PendingFileRenameOperations\n\n"
"%s: schedules the operation at the next reboot.\n", OPT_REBOOT, OPT_REBOOT, OPT_REBOOT);
return;
}
try
{
SetLastError(0);
DWORD flags = MOVEFILE_REPLACE_EXISTING;
if (argc >= 4 && strcmp(argv[3], OPT_REBOOT) == 0)
flags |= MOVEFILE_DELAY_UNTIL_REBOOT;
else
flags |= MOVEFILE_COPY_ALLOWED;
char* existing = argv[1];
char* dest = (argc >= 3 ? argv[2] : NULL);
if (MoveFileEx(existing, dest, flags) == FALSE)
printf("MoveFileEx failed: GetLastError returns %d.\n", GetLastError());
}
catch(...)
{
printf("Generic unhandled exception during execution of core %s\n"
"GetLastError returns %d.\n", argv[0], GetLastError());
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// test.cpp : Defines the entry point for the console application.
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <sys\timeb.h>
#include "..\itxlib.h"
#include "..\itxwraplib.h"
#include "..\itxbuffer.h"
#define NALPHABET 256
#define NTEST 1000
#define GRANULARITY 10
void Time_Trace()
{
#ifdef WIN32
struct _timeb timebuffer;
_ftime(&timebuffer);
#endif
#ifdef LINUX
struct timeb timebuffer;
ftime(&timebuffer);
#endif
char* timeline;
timeline = ctime(&timebuffer.time);
printf("TIME IS: %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20]);
}
void SetArray(itxString* istrarr)
{
srand(time(NULL));
for (int cicli=0; cicli<NTEST; cicli++)
{
int clearlen;
while((clearlen = rand() % 40) == 0);
char* clear = (char*)malloc(clearlen + 1);
clear[clearlen] = '\0';
int c;
for(int i=0; i<clearlen; i++)
{
c = rand() % NALPHABET;
if (c != '\0')
clear[i] = c;
else
clear[i] = '?';
}
istrarr[cicli] = clear;
free(clear);
}
}
int TestMassivo()
{
itxString istr("abcd");
itxString istr2;
// istr2 = istr;
// istr2.Copy(istr);
istr2 = "";
printf("%d\n", istr2.IsNull());
printf("%d\n", istr2.IsEmpty());
printf("%d\n", istr2.Len());
istr2 = "";
printf("%d\n", istr2.IsNull());
printf("%d\n", istr2.IsEmpty());
printf("%d\n", istr2.Len());
istr2 = "pippo";
printf("%d\n", istr2.IsNull());
printf("%d\n", istr2.IsEmpty());
printf("%d\n", istr2.Len());
istr2 = "La fregna regna";
printf("%d\n", istr2.IsNull());
printf("%d\n", istr2.IsEmpty());
printf("%d\n", istr2.Len());
printf("%s\n", istr2);
itxString* pstr = new itxString(istr2);
delete pstr;
pstr = new itxString("zs;fc jaes[rva ");
delete pstr;
//Test massivo
itxString istrarr[NTEST];
for (int z=0; z<NTEST; z++)
SetArray(istrarr);
/*
for (cicli=0; cicli<NTEST; cicli++)
printf("%s\n", istrarr[cicli].GetBuffer());
*/
return 0;
}
int Aux1()
{
itxString a("L'anima dell'aquila e' immor(t)ale");
a.AdjustStr();
printf("%s\n", a.GetBuffer());
itxString b("");
char* base = "a a a a a ";
char* what = " ";
char* with = "BBBBB";
b = base;
int n = b.SubstituteSubString(what, with);
b = "Ma dico veramente veramente?";
n = b.SubstituteSubString(" ", "\0");
b = "0000pippo";
n = b.RemoveLeadingZeros(2); //deve tornare la stringa '00pippo'
b = "pippo";
b.Capitalize();
b = "123456789\\lib";
n = b.RightInstr("\\");
b = "123 12345 12345678 1 1234567 123445 123 ";
n = b.MaxTokenLen("\\");
b = "pippo";
b.UCase();
b = "#porco il frio#";
b.InBlinder('#');
b = "aaa�bbb";
b.EscapeChars();
a = "cico";
b = "cicoria";
if (a.CompareNoCase(&b))
printf("iquali\n");
else
printf("difers\n");
a = "123456789";
a.Left(6);
a = "123456789";
a.Left(0);
a = "123456789";
a.Left(-1);
a = "123456789";
a.Left(15);
a = "123456789";
a.Right(6);
a = "123456789";
a.Right(0);
a = "123456789";
a.Right(-1);
a = "123456789";
a.Right(15);
return 0;
}
int Aux2()
{
char a[50];
strcpy(a, " 123 ");
itxString_RTrim(a);
printf(">%s<\n", a);
itxString istr(" 123 ");
istr.LTrim();
istr = " 123 ";
istr.RTrim();
istr = " 123 ";
istr.Trim();
return 0;
}
int Aux3()
{
itxString a = "aite";
itxString b = "csa";
a += b;
a += " la benemerita";
printf(">%s<\n", a.GetBuffer());
a = "";
char z[10];
memset(z, 'A', 10);
a.Strncpy(z, 5);
return 0;
}
int Aux4()
{
itxString a = "aaa";
itxString b = "aa";
printf("%d\n", a.Compare(&b));
a.Space(10, 0);
printf("<%s>\n", a.GetBuffer());
a.Space(10);
printf("<%s>\n", a.GetBuffer());
itxString uno;
uno = "aaaaaaa";
printf("%s\n", uno.GetBuffer());
uno.SetEmpty();
printf("%s\n", uno.GetBuffer());
char c = 'Y';
a += c;
printf("%s\n", a.GetBuffer());
a = "";
int s = 1234567899;
a.SetInt(s);
printf("<%s>\n", a.GetBuffer());
return 0;
}
void Aux5()
{
itxString a;
char* p = "abc";
char* aux = p;
aux++;
a += *aux;
}
int Aux6()
{
itxStack stak;
void* appo;
char* a = "aaa\n";
char* b = "bbb\n";
char* c = "ccc\n";
char* d = "ddd\n";
stak.Push(a);
stak.Push(b);
stak.Push(c);
stak.Push(d);
printf("---------------------------------------------------------------\n");
stak.SetCursorBottom();
printf("Bottom is %s\n", (char*)stak.Bottom());
while ((appo = stak.NextUp()) != NULL)
printf("Current is %s\n", (char*)appo);
printf("---------------------------------------------------------------\n");
stak.SetCursorTop();
printf("Top is %s\n", (char*)stak.Top());
while ((appo = stak.NextDown()) != NULL)
printf("Current is %s\n", (char*)appo);
printf("---------------------------------------------------------------\n");
printf("Top is %s\n", (char*)stak.Top());
char* out;
stak.Pop((void**)&out);
printf("%s", out);
stak.Pop((void**)&out);
printf("%s", out);
stak.Pop((void**)&out);
printf("%s", out);
stak.Pop((void**)&out);
printf("%s", out);
return 0;
}
void Aux7()
{
DWORD start, stop;
int G = 5000;
int l = 0;
itxString istr(G);
itxString appo((char*)NULL);
itxString appo2("");
for (int j=10000; j<= 50000; j+=10000)
{
istr.SetEmpty();
start = timeGetTime();
for (int i=0; i<=j; i++)
istr += "a";
stop = timeGetTime();
float f = (stop - start) / (float)1000;
printf("Elapsed time to reach %d size : %f seconds.\n", j, f);
}
// printf("%s", istr.GetBuffer());
printf("JOB DONE\n");
}
void Aux8()
{
itxString a;
a = "I nostri ragazzi imparano a uccidere...";
int x = a.FindSubString(" I nostri");
char* s = "3477";
char d[20];
a.HexToAscii(s, d, 4);
a.SetInt(5);
printf("SetInt test: %s\n", a.GetBuffer());
a.SetInt(1234567890);
printf("SetInt test: %s\n", a.GetBuffer());
}
void Aux9()
{
itxString a;
a = "123456789";
a = "1234567890";
a.Space(20);
a = "123456789\n0123456789";
printf("BEFORE PurgeSubString: %s\n", a.GetBuffer());
char c = 0xA;
a.PurgeSubString(&c);
printf("AFTER PurgeSubString test: %s\n", a.GetBuffer());
}
void Aux10()
{
itxListPtr list;
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i = 0;
int* px;
for (i=0; i<10; i++)
list.Append(&a[i]);
printf("------- HEAD - TAIL ---------------------\n");
px = (int*)list.GetHead();
while(px)
{
printf("~~~~~~~~~~~ %d\n", *px);
px = (int*)list.GetNext();
}
printf("------- TAIL - HEAD ---------------------\n");
px = (int*)list.GetTail();
while(px)
{
printf("~~~~~~~~~~~ %d\n", *px);
px = (int*)list.GetPrev();
}
printf("-----------------------------------------\n");
for (i=0; i<list.GetCount(); i++)
{
px = (int*)list.GetElement(i);
printf("valore %d = %d\n", i, *px);
}
printf("---------------------------------\n");
int newint = 20;
list.Insert(&newint, 5);
list.Insert(&newint, 0);
list.Insert(&newint, list.GetCount());
list.Insert(&newint, 100);
for (i=0; i<list.GetCount(); i++)
{
px = (int*)list.GetElement(i);
printf("valore %d = %d\n", i, *px);
}
printf("---------------------------------\n");
list.Remove(0);
list.Remove(5);
list.Remove(list.GetCount());
list.Remove(100);
for (i=0; i<list.GetCount(); i++)
{
px = (int*)list.GetElement(i);
printf("valore %d = %d\n", i, *px);
}
list.Empty();
itxString boh("rizla");
printf("GetAt ---> %d -> %c\n", boh.GetAt(-1), boh.GetAt(-1));
printf("GetAt ---> %d -> %c\n", boh.GetAt(0) , boh.GetAt(0) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(1) , boh.GetAt(1) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(2) , boh.GetAt(2) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(3) , boh.GetAt(3) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(4) , boh.GetAt(4) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(5) , boh.GetAt(5) );
printf("GetAt ---> %d -> %c\n", boh.GetAt(6) , boh.GetAt(6) );
}
void Aux11()
{
char a[5] = {'a', 'b', 'c', 'd', 'e'};
char b[10] = {'f', 'g', 'h', 'i', 'l', 'm', 'n', 'o', 'p', 'q'};
char c[3] = {'1', '2', '3'};
itxBuffer buf;
buf.Append(a, 5);
buf.Append(b, 10);
itxBuffer buf2;
buf2.SetGranularity(20);
buf2.Append(a, 5);
buf2.Append(b, 10);
itxBuffer buf3;
buf3 = buf2;
int len = buf3.Len();
buf3.SetBuffer(a, 5);
len = buf3.Len();
buf3 += buf;
len = buf3.Len();
bool isemp = buf.IsEmpty();
buf.SetEmpty();
isemp = buf.IsEmpty();
buf3.Space(30, 'T');
buf3.Space(50);
sprintf(buf3.GetBuffer(), "fruzzica o no fruzzica? 3x2=%d", 6);
itxBuffer buf4;
buf4.SetBuffer(b, 10);
buf4.InsAt(c, 3, 5);
itxBuffer buf5;
buf5.Space(10);
buf5.Append("abcd", 4);
char* p = buf5.GetBuffer() + buf5.Len();
strncpy(p, "efg", 3);
buf5.UpdateCursor(buf5.Len() + 3);
}
void Aux12()
{
itxSQLConnection m_Conn;
if (!m_Conn.Create("itxscratch", "sa", ""))
{
printf("create failed\n");
return;
}
if (!m_Conn.Execute("SELECT blob, descr FROM TABLE2"))
{
printf("execute failed\n");
return;
}
itxBuffer out;
m_Conn.Fetch();
m_Conn.GetBinData(1, out);
FILE* f = fopen("outimage.jpg", "wb");
fwrite(out.GetBuffer(), out.Len(), 1, f);
fclose(f);
}
//---------------------- test threads and http ------------
class TT : public itxThread
{
public:
itxString m_URL;
itxString m_DATA;
int m_Idx;
void Set(char* url, char* data, int idx){m_URL = url; m_DATA = data; m_Idx = idx;}
TT(){}
~TT(){}
void Run()
{
try
{
itxHttp http;
http.POST(m_URL.GetBuffer(), m_DATA.GetBuffer(), "text/plain", 4000, true);
printf("\n>%d===%s===\n", m_Idx, http.GetDataReceived());
}
catch(itxException* e)
{
if (e != NULL)
printf("Catched itxException '%s' while requesting %s\n", e->m_procedure, m_URL);
}
catch(...)
{
printf("Catched error while requesting %s\n", m_URL);
}
}
};
#define N 50
void Aux13()
{
TT pT[N];
/*
itxHttp http;
http.POST("www.Services.ort.fr/Bignet/xmledi-1/access", "UNB+UNOA:1+0171+0114+020626:1026+017110262001++TEST'UNH+017110262001+01:001'RQF+MAX:50:01'NAD+BSN+PO460579++DANIELA RIGHI++PRATO+++IT'UNT+4+017110262001'UNZ+1+017110262001'", "text/plain", 4000, true);
printf("===%s===\n", http.GetDataReceived());
return;
//*/
for (int i=0; i<N; i++)
{
pT[i].Set("www.Services.ort.fr/Bignet/xmledi-1/access", "UNB+UNOA:1+0114+0171+020626:1026+017110262001++TEST'UNH+017110262001+01:001'RQF+MAX:50:01'NAD+BSN+PO460579++DANIELA RIGHI++PRATO+++IT'UNT+4+017110262001'UNZ+1+017110262001'", i);
// pT[i].Set("cannonau/cgi-bin/tannit.exe", "", i); //"prm=dbg&tpl=now");
pT[i].Start();
}
printf("Launched %d threads.\n", N);
_getch();
}
//---------------------------------------------------------
//------------------- MAIN --------------------------------
//---------------------------------------------------------
int main()
{
/*
TestMassivo();
Aux1();
Aux2();
Aux3();
Aux4();
Aux5();
Aux6();
Aux7();
Aux8();
Aux9();
Aux10();
Aux11();
Aux12();
*/
Aux13();
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITANNIT_H__
#define __ITANNIT_H__
#include <stdio.h>
#include "tannitds.h"
#ifdef _ITX_APPC
#pragma message("ITannit.lib AS400 support enabled")
#else
#pragma message("ITannit.lib AS400 support disabled")
#endif
#include "itannitdef.h"
extern "C"
{
// General functions
bool ITannit_Create(PTannitQueryResult* qres, int* count);
void ITannit_Destroy();
int ITannit_StoreToken(TannitQueryResult* qres, char* token, int field_num);
int ITannit_StoreValue(PTannitQueryResult qres, char* field, char* value);
TannitQueryResult* ITannit_DBStructure(char* token);
TannitQueryResult* ITannit_NewEntry(char* token, int numfields);
TannitQueryResult* ITannit_FindQuery(char* token);
TannitQueryResult* ITannit_NewTQRFrom(char* source, char* field, char* value, char* destination);
int ITannit_StoreRecord(char* name, ...);
char* ITannit_GetValue(TannitQueryResult* qres, int row, char* field);
void ITannit_SetCurrentRecord(TannitQueryResult* qres, int row);
void ITannit_RemoveCurrentRec(TannitQueryResult* qres);
bool ITannit_CheckCurrentRec(int numfield);
void ITannit_RemoveExcluding(char* firstname, ...);
void ITannit_RemoveQueries(char* firstname, ...);
bool ITannit_Dump(FILE* fp);
bool ITannit_RegisterTP(char* filename);
TannitQueryResult* ITannit_FindRegTP(int tpid);
int ITannit_GetTPFields(char* tpname);
// APPC INTERFACE FUNCTIONS BEGIN
bool ITannit_CreateEnv(PTannitQueryResult* qres, int* count, char* llu, char* rtp);
char* ITannit_TPReceiveFromFile(FILE* fp, PACKET_TYPE msgwaited);
char* ITannit_TPExecute(PACKET_TYPE msgwaited, int maxretray, FILE* log, ...);
char* ITannit_TPExecuteCnv(PACKET_TYPE msgwaited, int maxretray, FILE* log, ...);
char* ITannit_TPExecuteFromFile(FILE* fp, FILE* log, PACKET_TYPE msgwaited, int maxretray);
// APPC Parsing functions
void ITannit_ParsTP(char* tablename, char* tp, int fromrecord, int numrecord, FILE* fp,
char recsep, char fieldsep);
int ITannit_ParsRecord(char* tablename, char* record, FILE* fp, char fieldsep);
void ITannit_ParserLog(FILE* fp, char* des, char* record);
void ITannit_EBCDtoASCII(PTannitQueryResult qres);
// functions that depend by the particular project for which itannit
// has benn developed and should be positioned in other library
bool ITannit_GetP00FromSQL(char* dsn, char* uid, char* pwd, char* connectionID, FILE* log);
bool ITannit_FirstConn(char* dsn, char* uid, char* pwd,
char* user, char* lang, FILE* log);
bool ITannit_ReceiveFileFromAS400(char* filepath, FILE* log);
bool ITannit_SendFileToAS400(char* filepath, FILE* log);
bool ITannit_SendHOK(FILE* log, PACKET_TYPE ptype);
void ITannit_SetUser(char* user);
// APPC INTERFACE FUNCTIONS END
// ODBC INTERFACE FUNCTIONS BEGIN
char* ITannit_AllocateSQLInsertStringWith(char* target, char* table, int row, va_list morefields);
char* ITannit_AllocateSQLUpdateStringWith(char* table, int row, ...);
bool ITannit_ConnectSQL(char* dsn, char* uid, char* pwd);
bool ITannit_DisconnectSQL();
void ITannit_DeleteSQL(char* target, ...);
bool ITannit_ExecuteSQL(char* stm);
bool ITannit_InsertSQL(char* target, char* table, int row, ...);
bool ITannit_BulkInsertSQL(FILE* log, char* target, char* table, ...);
// bool ITannit_SelectFromSQL(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore);
bool ITannit_SelectDirectFromSQL(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore);
int ITannit_ExecuteSQLQuery(char* dsn, char* uid, char* pwd, char* queryname, char* query, int firstRec, int recsToStore);
short int ITannit_GetSQLCols();
bool ITannit_GetSQLColInfo(short int col, char* name, short* type, long int* size);
bool ITannit_FillTQRColsInfoFromSQL(char* dsn, char* uid, char* pwd, char* tqrname, char* table);
int ITannit_ErrorSQL(FILE* log);
bool ITannit_ManualCommitSQL();
bool ITannit_AutoCommitSQL();
bool ITannit_CommitSQL();
bool ITannit_RollbackSQL();
// ODBC INTERFACE FUNCTIONS END
// functions that should not be here but in an string
// manipolation utility library
void ITannit_SubStr(char* source, char* destination, int maxlength, char* tag, char* newtag);
void itxOemToChar(char* source, char* destination);
void itxCharToOem(char* source, char* destination);
void itxEBCDToASCII(char* source);
char* ITannit_Trim(char* source);
char* ITannit_RTrim(char* source);
}
#endif //__ITANNIT_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : parser.h
| TAB : 2 spaces
|
| DESCRIPTION : Parser object declaration.
|
|
*/
#ifndef _PARSER_H_
#define _PARSER_H_
#include "defines.h"
#include "tnt.h"
#include "templatefile.h"
#include "itxlib.h"
/****************
Parser
****************/
typedef enum
{
Preprocrun,
Previewrun,
Forbiddenrun,
Normalrun,
Diagnostic
} RunType_e;
typedef struct TplVarVect
{
int idx;
itxString values[TPL_VARS_NUM];
itxString names[TPL_VARS_NUM];
} TplVarVect_t;
//The command interpreter
class Parser
{
public:
//MEMBERS
AbstractCommand* m_Command[MAX_CMDS];
int m_TotalCount;
int m_BaseCount;
int m_ForceExit;
int m_ForceReturn;
TplVarVect_t m_TplVars;
itxStack m_TplStack;
TemplateFile* m_CurTpl;
char m_StartCommandTag;
bool m_PreprocRun; // becoming obsolete
RunType_e m_RunType; // replacing m_PreprocRun
itxString m_ActualTplDir;
//METHODS
void CreateBaseCommands(void* tannit);
void DestroyBaseCommands();
void UpdateTotalCount();
int PickPar(char* inputStr, int position, itxString* returnStr);
int PickInt(char* inputstr, int position, int* retval);
int PickDouble(char* inputstr, int position, double* retval);
int PickString(char* inputstr, int position, char* retval, int* bufdim);
int PickListString(char* inputstr, itxString** params);
int VerifyCmdSynt(char** tplString, int* cmdOrd, itxString* argStr, char** cmdStart);
int ProcTplData(char* tplString, itxString* outputString);
TemplateFile* LoadTemplate(itxString* tpldir, itxString* pname, char* ext);
void Run(itxString* tpldir, itxString* pname, char* ext = TPL_EXT);
void Run(char* content);
void SetValidBlock(int val);
void SetCycleBlock(int val);
int GetCycleBlock(int offset = 0);
void AddVar(char* varName, char* varValue);
//CONSTRUCTION-DESTRUCTION
Parser();
~Parser();
};
#endif /* _PARSER_H_ */
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.web;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet returns the requested resource file as a stream.
* It works on either a locally or remotely stored resource file, either on a
* resource contained within the jtxlib itself. In the first case only the res_*
* parameters are used while the jtx_* ones are ignored;
* vice-versa, in the second case, only the jtx_* parameters are used.
* <p>
*
* <u>Parameters of the request:</u><br>
* <dl>
* <dt><b>res_path_var</b>:</dt>
* <dd>
* identifies the name of the variable in the application context containing
* the local or remote location of the requested resource (usually configured in <app>.ini).
* </dd>
*
* <dt><b>res_filename</b>:</dt>
* <dd>
* this is the name of the requested resource.
* </dd>
*
* <dt><b>jtx_resname</b>:</dt>
* <dd>
* the requested resource path and filename within the jtxlib. <br>
* For example, if the res.xxx file is in the package jtxlib.web.yyy,
* the value to be passed in this parameter is <i>jtxlib/web/yyy/res.xxx</i>.
* </dd>
*
* <dt><b>mime_type</b>:</dt>
* <dd>
* optional, the mime to be set for the response.
* </dd>
*
* <dt><b>disposition</b>:</dt>
* <dd>
* optional, the content-disposition to be set for the response.
* </dd>
*
* <dt><b>r_tag</b>:</dt>
* <dd>
* optional, a tag to be replaced with <b>r_val</b> at streaming time.
* All the occurrences will be replaced.
* At moment (2009.04.30) this feature is available only for jtxlib resources.
* </dd>
*
* <dt><b>r_val</b>:</dt>
* <dd>
* optional, the value to be used in place of <b>r_tag</b> at streaming time.
* If a null string is passed (i.e. 'r_val=' in query string), the <b>r_tag</b>
* will be removed everywhere.
*
* </dd>
* </dl>
*
* @author gambineri
* @version
*/
public class ResourceStreamer extends HttpServlet
{
private static final long serialVersionUID = 7144360327773089172L;
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException
* @throws IOException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String jtx_resname = request.getParameter("jtx_resname");
String mime_type = request.getParameter("mime_type");
String disposition = request.getParameter("disposition");
if (mime_type != null && mime_type.length() > 0)
response.setContentType(mime_type);
if (disposition != null && disposition.length() > 0)
response.setHeader("Content-disposition", disposition);
if (jtx_resname != null && jtx_resname.length() != 0)
StreamJTXLIBResource(request, response);
else
StreamResource(request, response);
}
//----------------------------------------------------------------------------
private void StreamResource(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String res_path_var = request.getParameter("res_path_var");
String res_filename = request.getParameter("res_filename");
//get real value from the application context
String res_path_val = (String)this.getServletContext().getAttribute(res_path_var);
if (res_path_var == null || res_path_var.length() == 0 ||
res_filename == null || res_filename.length() == 0 ||
res_path_val == null || res_path_val.length() == 0)
return;
// debug(response, res_path_val);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
ServletOutputStream out = response.getOutputStream();
String reqURL = "";
try
{
if (res_path_val.substring(1, 2).equals(":"))
reqURL = "file://localhost/" + res_path_val + res_filename;
else
reqURL = res_path_val + res_filename;
URL url = new URL(reqURL);
// Use Buffered Stream for reading/writing.
bis = new BufferedInputStream(url.openStream());
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while((bytesRead = bis.read(buff, 0, buff.length)) != -1)
bos.write(buff, 0, bytesRead);
}
catch(final MalformedURLException e) {throw e;}
catch(final IOException e) {throw e;}
finally
{
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
//----------------------------------------------------------------------------
private void StreamJTXLIBResource(HttpServletRequest request, HttpServletResponse response)
{
InputStream is = this.getClass().getClassLoader().getResourceAsStream(request.getParameter("jtx_resname"));
String r_tag = (request.getParameter("r_tag") == null ? "" : request.getParameter("r_tag"));
String r_val = (request.getParameter("r_val") == null ? "" : request.getParameter("r_val"));
try
{
ServletOutputStream out = response.getOutputStream();
StringBuffer contentBuf = new StringBuffer();
int b = 0;
while ((b = is.read()) != -1)
contentBuf.append((char)b);
// Do r_tag/r_val replacements
String content = (contentBuf + "");
if (r_tag.length() > 0)
content = content.replaceAll(r_tag, r_val);
//Send resource
out.print(content);
}
catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
//----------------------------------------------------------------------------
private void debug(HttpServletResponse response, String msg) throws IOException
{
PrintWriter out = response.getWriter();
out.println(msg);
out.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
/** Returns a short description of the servlet.
*/
public String getServletInfo()
{
return "Pushes server side resources with the requested content type and disposition.";
}
// </editor-fold>
}
<file_sep>// TestComboDlg.h : header file
//
#include "combination.h"
#include<utility>
#include<map>
#if !defined(AFX_TESTCOMBODLG_H__DE323766_C018_11D7_ACBC_F9366451BC33__INCLUDED_)
#define AFX_TESTCOMBODLG_H__DE323766_C018_11D7_ACBC_F9366451BC33__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CTestComboDlg dialog
class CTestComboDlg : public CDialog
{
// Construction
public:
CTestComboDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CTestComboDlg)
enum { IDD = IDD_TESTCOMBO_DIALOG };
CProgressCtrl c_progressbar;
int m_n_seq;
int m_r_seq;
CString m_complete;
int m_radio;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTestComboDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
std::map<char,int> mc;
private:
__int64 fact(int num);
__int64 NumOfCombo();
void InitialiseMap();
bool CheckMap();
void char_combination(char n[],int n_column,
char r[], int r_size, int r_column, int loop);
public:
void temp(char *begin,char* end);
// Generated message map functions
//{{AFX_MSG(CTestComboDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnStart();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TESTCOMBODLG_H__DE323766_C018_11D7_ACBC_F9366451BC33__INCLUDED_)
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxwin32.h,v $
* $Revision: 1.3 $
* $Author: massimo $
* $Date: 2002-06-26 11:25:18+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 rom<NAME>
* <EMAIL>
*/
#ifndef __ITXWIN32_H__
#define __ITXWIN32_H__
#ifdef WIN32
/* -------------------------------------------------------------
* This file is the main header containing all includes, defines
* and other definitions needed to implement the WIN32 version
* of the itxSystem object.
* -------------------------------------------------------------
*/
#include <windows.h>
#include <sys\timeb.h>
#include <stdio.h> //This for _setmode
#include <mmsystem.h>
#include <fcntl.h> //This for stream modes
#include <io.h> //This for _setmode
#include <strstrea.h>
#ifndef _WINDOWS_
#include <winsock2.h>
#endif
// C calling convention
#define ITXCDECL _cdecl
#define PATH_SEPARATOR "\\"
#define PATH_SEPARATOR_C '\\'
#endif //WIN32
#endif //__ITXWIN32_H__<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxstring.cpp,v $
* $Revision: 1.46 $
* $Author: administrator $
* $Date: 2002-07-23 12:42:01+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "itxstring.h"
/*
* Costruzione/distruzione e funzioni ausiliarie
*/
itxString::itxString(int G)
{
try
{
m_Str = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
*this = '\0';
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::itxString(int G)")
}
itxString::itxString(char* sz, int G)
{
m_Str = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
try
{
if (sz == NULL)
*this = '\0';
else
{
int l = strlen(sz);
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, l + 1);
memcpy(m_Str, sz, l);
m_Cursor = m_Str + l;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::itxString(char* sz, int G)")
}
itxString::itxString(itxString& src, int G)
{
m_Str = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
try
{
if (src.m_Str == NULL)
*this = '\0';
else
{
register unsigned int l = (unsigned)src.m_Cursor - (unsigned)src.m_Str;
if (m_Bufsize <= l)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, l + 1);
memcpy(m_Str, src.m_Str, l);
m_Cursor = m_Str + l;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::itxString(itxString& src, int G)")
}
itxString::~itxString()
{
try
{
ITXFREE(m_Str);
}
//CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::~itxString()")
//patched fabio--->31/05/2001
CATCH_TO_NOTHING
}
int itxString::Space(int len, int c)
{
try
{
if (len <= 0)
return (m_Str == NULL ? 0 : 1);
m_Cursor = m_Str;
if ((int)m_Bufsize < len)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, len);
memset(m_Str, c, len);
*(m_Str + m_Bufsize - 1) = 0;
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::Space(int len, int c)")
return (m_Str == NULL ? 0 : 1);
}
//Use CAREFULLY: only if you write on the internal buffer by anonymous means.
void itxString::UpdateCursor()
{
try
{
m_Cursor = m_Str + strlen(m_Str);
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::UpdateCursor()")
}
/*****************************************************************************
- FUNCTION NAME: GetAt
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
int pos : position 0-based in the buffer string.
-----------------------------------------------------------------------------
- RETURN VALUE:
Returns the integer ascii value of the char at pos position (0-based).
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
int itxString::GetAt(int pos)
{
// if (pos < 0 || (unsigned)pos >= ((unsigned)m_Cursor - (unsigned)m_Str))
// return -1;
return m_Str[pos];
}
void itxString::SetAt(char a, int pos)
{
// if (pos < 0 || (unsigned)pos >= ((unsigned)m_Cursor - (unsigned)m_Str))
// return -1;
m_Str[pos] = a;
}
/*****************************************************************************
- FUNCTION NAME: Left
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
len : len to take.
-----------------------------------------------------------------------------
- RETURN VALUE:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::Left(int len)
{
try
{
if ((unsigned)len < ((unsigned)m_Cursor - (unsigned)m_Str) && len >= 0)
{
m_Cursor = m_Str + len;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::Left(int len)")
return *this;
}
/*****************************************************************************
- FUNCTION NAME: Right
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
len : len to take.
-----------------------------------------------------------------------------
- RETURN VALUE:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::Right(int len)
{
try
{
if ((unsigned)len < ((unsigned)m_Cursor - (unsigned)m_Str) && len >= 0)
{
memmove(m_Str, m_Cursor - len, len + 1);
m_Cursor = m_Str + len;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::Right(int len)")
return *this;
}
/*****************************************************************************
- FUNCTION NAME: Left
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
len : len to take.
-----------------------------------------------------------------------------
- RETURN VALUE:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::Mid(int start, int len)
{
try
{
if ((unsigned)len <= ((unsigned)m_Cursor - (unsigned)m_Str - start) && len >= 0)
{
memmove(m_Str, m_Str + start, len + 1);
m_Cursor = m_Str + len;
*m_Cursor = 0;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::Mid(int start, int len)")
return *this;
}
/*****************************************************************************
- FUNCTION NAME: Strcat
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* add: string to be added.
-----------------------------------------------------------------------------
- RETURN VALUE:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
void itxString::Strcat(char* add)
{
*this += add;
}
/*****************************************************************************
- FUNCTION NAME: Strncpy
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* src : string from which the add is made.
unsigned int nchars : Num of chars to add.
-----------------------------------------------------------------------------
- RETURN VALUE:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
void itxString::Strncpy(char* src, unsigned int nchars)
{
if (nchars == 0 || src == NULL)
return;
try
{
if (strlen(src) <= nchars)
*this = src;
else
{
if (nchars > m_Bufsize)
{
m_Cursor = m_Str;
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, nchars + 1);
/////////
/* int saveG = (int)(m_Granularity);
(m_Granularity) = ((int)(((nchars + 1) - (m_Bufsize)) / (m_Granularity)) + 1) * (m_Granularity);
try
{
char* temp;
if ((temp = (char*)ITXALLOC((m_Bufsize) + (m_Granularity))) != NULL)
{
if ((m_Str) != NULL)
{
memcpy(temp, (m_Str), (m_Bufsize));
(m_Cursor) = temp + ((unsigned)(m_Cursor) - (unsigned)(m_Str));
ITXFREE(m_Str);
}
else
(m_Cursor) = temp;
(m_Str) = temp;
(m_Bufsize) += (m_Granularity);
}
}
catch(...){throw;}
(m_Granularity) = saveG;
*/
/////////
}
memcpy(m_Str, src, nchars);
m_Str[nchars] = 0;
m_Cursor += nchars;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::Strncpy(char* src, unsigned int nchars)")
}
/*****************************************************************************
- FUNCTION NAME: PurgeSubString
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* tobepurged: substring to be purged.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Finds and clears all occurrences of the string pointed to from the parameter.
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
void itxString::PurgeSubString(char* tobepurged)
{
if (tobepurged == NULL)
return;
int len2purge = strlen(tobepurged);
char* cursor = m_Str;
try
{
while((cursor = strstr(cursor, tobepurged)) != NULL)
{
memmove(cursor, cursor + len2purge, (unsigned)m_Cursor - (unsigned)cursor - len2purge + 1);
m_Cursor -= len2purge;
}
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::PurgeSubString(char* tobepurged)")
}
/*****************************************************************************
- FUNCTION NAME: SubstituteSubString
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base: string in which will be made the substitution.
char* what: string to be searched.
char* with: string for replacing.
-----------------------------------------------------------------------------
- OUTPUT PARAMETERS:
char* retstr
-----------------------------------------------------------------------------
- RETURN VALUE:
int: 0 : on success;
-1 : on error;
ret : length of the new string, needed for allocation.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Substitutes all occurrences of the string 'what' in the main string 'base'
with the string 'with'.
*****************************************************************************/
int itxString::SubstituteSubString(char* base, char* what, char* with, char* retstr)
{
char* pNextWhat = NULL;
char* residual = NULL;
int whatlen = 0;
if (base == NULL || what == NULL || with == NULL)
return -1;
if (strlen(base) == 0 || (whatlen = strlen(what)) == 0)
return -1;
if (retstr == NULL)
{
int what_count = 0;
pNextWhat = base;
while ((pNextWhat = strstr(pNextWhat, what)) != NULL)
{
what_count++;
pNextWhat += whatlen;
}
return (strlen(base) + what_count * (strlen(with) - strlen(what)));
}
pNextWhat = base;
residual = base;
retstr[0] = 0;
while ((pNextWhat = strstr(residual, what)) != NULL)
{
strncat(retstr, residual, (unsigned int)pNextWhat - (unsigned int)residual);
strcat(retstr, with);
residual = pNextWhat + whatlen;
}
//Last piece
strcat(retstr, residual);
return 0;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::SubstituteSubString(char* what, char* with)
{
int ret = 0;
try
{
itxString appo(*this);
int newdim = SubstituteSubString(appo.m_Str, what, with, NULL);
if ((int)m_Bufsize <= newdim)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, newdim + 1);
ret = SubstituteSubString(appo.m_Str, what, with, m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::SubstituteSubString(char* what, char* with)")
return ret;
}
/*****************************************************************************
- FUNCTION NAME: FindSubString
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* what : string to be searched.
int start_from : zero-based position of the starting character
(defaults to zero)
-----------------------------------------------------------------------------
- RETURN VALUE:
int: >=0 : on success: the position 0-based of the beginning of 'what';
-1 : on error;
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
int itxString::FindSubString(char* what, int start_from)
{
try
{
if (what != NULL)
{
char* pos = NULL;
if (start_from < (int)((unsigned)m_Cursor - (unsigned)m_Str))
pos = strstr(m_Str + start_from, what);
return (pos == NULL ?
(int)((unsigned)m_Cursor - (unsigned)m_Str) :
(unsigned)pos - (unsigned)m_Str - start_from);
}
else
return -1;
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::FindSubString(char* what)")
}
/*****************************************************************************
- FUNCTION NAME: IndexOf
Slightly different from FindSubString: this function returns the index
0-based of the argument substring or -1 if it cannot be found, in any case.
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* what : sub-string to be searched.
-----------------------------------------------------------------------------
- RETURN VALUE:
int: >=0 : on success: the position 0-based of the beginning of 'what';
-1 : if the string cannot be found;
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
int itxString::IndexOf(char* what)
{
try
{
if (what != NULL && m_Str[0] != 0)
{
char* pos = NULL;
if ((int)((unsigned)m_Cursor - (unsigned)m_Str) > 0)
pos = strstr(m_Str, what);
return (pos == NULL ? -1 : (unsigned)pos - (unsigned)m_Str);
}
else
return -1;
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::IndexOf(char* what)")
}
/*****************************************************************************
- FUNCTION NAME: AdjustStr
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base: string in which will be made the substitution.
-----------------------------------------------------------------------------
- OUTPUT PARAMETERS:
char* retstr
-----------------------------------------------------------------------------
- RETURN VALUE:
int: 0 : on success if retstr != NULL;
ret : on success if retstr == NULL, number of apexes, useful
for pre-allocation.
-1 : on error;
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Doubles the occurrences of the ' character in the string 'base'.
*****************************************************************************/
int itxString::AdjustStr(char* base, char* retstr)
{
char* pAux = NULL;
if (base == NULL || strlen(base) == 0)
return -1;
if (retstr == NULL)
{
int apex_count = 0;
pAux = base;
while (*pAux != 0)
{
if (*pAux == '\'')
apex_count++;
pAux++;
}
return apex_count;
}
pAux = base;
while (*pAux != 0)
{
*retstr++ = *pAux;
if (*pAux == '\'')
*retstr++ = *pAux;
pAux++;
}
*retstr = 0; //zero termination
return 0;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::AdjustStr()
{
int ret = 0;
try
{
itxString appo(*this);
Space(Len() + AdjustStr(appo.m_Str, NULL));
ret = AdjustStr(appo.m_Str, m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::AdjustStr(char* what)")
return ret;
}
/*****************************************************************************
- FUNCTION NAME: RemoveLeadingZeros
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base : string in which will be made the substitution.
int zleft : number of zeros to be left anyway.
-----------------------------------------------------------------------------
- OUTPUT PARAMETERS:
char* retstr
-----------------------------------------------------------------------------
- RETURN VALUE:
int: 0 : on success;
-1 : on error;
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Removes leading zeros in 'base' exeeding 'zleft' zeros.
*****************************************************************************/
int itxString::RemoveLeadingZeros(char* base, int zleft, char* retstr)
{
int zeros = 0;
char* p;
if (base == NULL || retstr == NULL || strlen(base) == 0)
return -1;
p = base;
while (*p++ == '0')
zeros++;
if (p == base || zeros < zleft)
strcpy(retstr, base);
else
strcpy(retstr, base + zeros - zleft);
return 0;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::RemoveLeadingZeros(int zleft)
{
itxString appo(*this);
int ret = RemoveLeadingZeros(appo.m_Str, zleft, m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
return ret;
}
/*****************************************************************************
- FUNCTION NAME: Capitalize
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base : input string.
-----------------------------------------------------------------------------
- OUTPUT PARAMETERS:
char* retstr
-----------------------------------------------------------------------------
- RETURN VALUE:
int: 0 : on success;
-1 : on error;
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
LTrims and capitalizes first non-blank character.
*****************************************************************************/
int itxString::Capitalize(char* base, char* retstr)
{
char* p;
if (base == NULL || retstr == NULL || strlen(base) == 0)
return -1;
p = base;
while (*p == ' ')
p++;
retstr[0] = toupper(p[0]);
strcpy(&retstr[1], &p[1]);
return 0;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::Capitalize()
{
itxString appo(*this);
return Capitalize(appo.m_Str, m_Str);
}
/*****************************************************************************
- FUNCTION NAME: RightInstr
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base : input string
char* search_arg : string to search
int start_from : 1-based position in the 'base' array.
-----------------------------------------------------------------------------
- OUTPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
int: ret : on success the position 1-based of the last occurrence of
'search_arg' in 'base';
0 : 'search_arg' was not found;
-1 : on error;
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Executes an 'Instr' operation from the bottom of a string
*****************************************************************************/
int itxString::RightInstr(char* base, char* search_arg)
{
char* p = NULL;
char* found = NULL;
int blen = 0;
int salen = 0;
if (base == NULL || (blen = strlen(base)) == 0 ||
search_arg == NULL || (salen = strlen(search_arg)) == 0)
return -1;
p = base + strlen(base) - salen;
while ( ((unsigned)p >= (unsigned)(base - 1)) &&
(found = strstr(p, search_arg)) == NULL )
p--;
if (found)
return (unsigned)found - (unsigned)base + 1;
else
return 0;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::RightInstr(char* search_arg)
{
return RightInstr(m_Str, search_arg);
}
/*****************************************************************************
- FUNCTION NAME: MaxTokenLen
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* base : input string
char* sep : separator token
-----------------------------------------------------------------------------
- RETURN VALUE:
int: ret : on success the maximum length of a token;
-1 : on error;
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Computes the maximum length of a token in 'base' using 'sep' as separator.
*****************************************************************************/
int itxString::MaxTokenLen(char* base, char* sep)
{
char* base2 = NULL;
char* token = NULL;
int ret = 0;
int toklen = 0;
if ( base == NULL || strlen(base) == 0 ||
sep == NULL || strlen(sep) == 0 )
return -1;
if ((base2 = strdup(base)) == NULL)
return -1;
token = strtok(base2, sep);
while (token != NULL)
{
toklen = strlen(token);
ret = (ret < toklen ? toklen : ret);
token = strtok(NULL, sep);
}
free(base2);
return ret;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::MaxTokenLen(char* sep)
{
return MaxTokenLen(m_Str, sep);
}
/*****************************************************************************
- FUNCTION NAME: UCase
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* str : string to convert
-----------------------------------------------------------------------------
- RETURN VALUE:
char* : converted string in the input buffer pointed by 'str' arg.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
ToUppers chars in a string.
*****************************************************************************/
char* itxString::UCase(char* str)
{
char* ret = str;
while (*str)
*str++ = toupper(*str);
return ret;
}
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::UCase()
{
UCase(m_Str);
return *this;
}
/*****************************************************************************
- FUNCTION NAME: LCase
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* str : string to convert
-----------------------------------------------------------------------------
- RETURN VALUE:
char* : converted string in the input buffer pointed by 'str' arg.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
ToLowers chars in a string.
*****************************************************************************/
char* itxString::LCase(char* str)
{
char* ret = str;
while (*str)
*str++ = tolower(*str);
return ret;
}
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::LCase()
{
LCase(m_Str);
return *this;
}
/*****************************************************************************
- FUNCTION NAME: EscapeChars
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* source : in
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Genera una nuova stringa sostituendo ai caratteri speciali
i loro codici di escape. La versione statica torna un puntatore
'destination' che DEVE essere disallocato dal chiamante.
*****************************************************************************/
int itxString::EscapeChars(char* source, char** destination)
{
itxString appo(source);
try
{
appo.EscapeChars();
if ((*destination = (char*)malloc(appo.Len() + 1)) == NULL)
return 0;
else
{
strcpy(*destination, appo.GetBuffer());
return 1;
}
}
CATCHALLMSG("Exception in itxString::EscapeChars(char* source, char** destination)")
}
/*--------------- Object Version --------------------------------------------*/
int itxString::EscapeChars()
{
char* s;
char* d;
int srcPos = 0;
int dstPos = 0;
char appo[64];
try
{
memset(appo, '\0', 64);
s = m_Str;
int srclen = strlen(s);
int dstlen = srclen;
if (!s)
return 0;
// count
while (srcPos < srclen)
{
unsigned char ch = s[srcPos];
// se il carattere non e' alfanumerico
if(
(ch < 48) ||
((ch > 57) && (ch < 65)) ||
((ch > 90) && (ch < 97)) ||
(ch > 122)
)
{
dstlen += 2;
}
srcPos++;
}
if ((d = (char*)ITXALLOC(dstlen + 1)) == NULL)
return 0;
// revert
srcPos = 0;
while (srcPos < srclen)
{
unsigned char ch = s[srcPos];
if(
(ch < 48) ||
((ch > 57) && (ch < 65)) ||
((ch > 90) && (ch < 97)) ||
(ch > 122)
)
{
memset(appo, '\0', 64);
sprintf(appo, "%%%X", ch);
memcpy((char*)d + dstPos, appo, 3);
dstPos += 3;
}
else
{
d[dstPos] = ch;
dstPos++;
}
srcPos++;
}
d[dstPos] = '\0';
//Replace old buffer
if ((int)m_Bufsize < dstlen)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, dstlen + 1);
memcpy(m_Str, d, dstPos);
m_Cursor = m_Str + dstPos;
*m_Cursor = 0;
ITXFREE(d);
}
CATCHALLMSG("Exception in itxString::EscapeChars()")
return (m_Str == NULL ? 0 : 1);
}
/*****************************************************************************
- FUNCTION NAME: InBlinder
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char** source : in-out
char blinder : carattere di delimitazione
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Torna la stringa in source epurata dei due delimitatori.
*****************************************************************************/
void itxString::InBlinder(char** source, char blinder)
{
char* s;
int startPos = -1;
int stopPos = -1;
int pos;
try
{
s = *source;
int srclen = strlen(s);
int dstlen = srclen;
if (!s)
return;
// find first blinder occurence
pos = 0;
while (pos < srclen && startPos == -1)
{
int ch = s[pos];
if (ch == blinder)
startPos = pos + 1;
pos++;
}
// find last blinder occurence
pos = srclen - 1;
while (pos >= 0 && stopPos == -1)
{
int ch = s[pos];
if (ch == blinder)
stopPos = pos;
pos--;
}
if (stopPos < startPos)
return;
if (stopPos == -1 && startPos == -1)
return;
s[stopPos] = '\0';
(*source) += startPos;
}
CATCHALLMSG("Exception in itxString::InBlinder(char** source, char blinder)")
return;
}
/*--------------- Object Version --------------------------------------------*/
int itxString::InBlinder(char blinder)
{
try
{
itxString oappo(*this);
char* appo = oappo.m_Str;
InBlinder(&appo, blinder);
*this = appo;
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::InBlinder(char blinder)")
return (m_Str == NULL ? 0 : 1);
}
/*****************************************************************************
- FUNCTION NAME: CompareNoCase
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* s1 : stringa 1
char* s2 : stringa 2
-----------------------------------------------------------------------------
- RETURN VALUE: 1 se sono uguali, 0 altrimenti.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Confronto non case sensitive.
*****************************************************************************/
int itxString::CompareNoCase(char *s1, char *s2)
{
if (s1 == NULL || s2 == NULL)
return 0;
try
{
while(1)
{
if (!(*s1))
{
if (!(*s2))
return 1;
else
return 0;
}
else if (!(*s2))
return 0;
if (isalpha(*s1))
{
if (tolower(*s1) != tolower(*s2))
return 0;
}
else if ((*s1) != (*s2))
return 0;
s1++;
s2++;
}
}
CATCHALLMSG("Exception in itxString::CompareNoCase(char *s1, char *s2)")
}
/*--------------- Object Version --------------------------------------------*/
int itxString::CompareNoCase(itxString* pistr)
{
itxString appo(*this);
return CompareNoCase(appo.m_Str, pistr->m_Str);
}
int itxString::CompareNoCase(char* pistr)
{
itxString appo(*this);
return CompareNoCase(appo.m_Str, pistr);
}
/*****************************************************************************
- FUNCTION NAME: Compare
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
itxString* s1 : stringa da confrontare con this.
-----------------------------------------------------------------------------
- RETURN VALUE: quello di strcmp.
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
Confronto case sensitive.
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
int itxString::Compare(itxString* pistr)
{
try
{
if (this->m_Str == NULL && pistr->m_Str == NULL)
return 0;
if (this->m_Str == NULL || pistr->m_Str == NULL)
return 1;
}
CATCHALLMSG("Exception in itxString::Compare(itxString* pistr)")
return strcmp(this->m_Str, pistr->m_Str);
}
int itxString::Compare(char* pstr)
{
try
{
if (this->m_Str == NULL && pstr == NULL)
return 0;
if (this->m_Str == NULL || pstr == NULL)
return 1;
}
CATCHALLMSG("Exception in itxString::Compare(char* pstr)")
return strcmp(this->m_Str, pstr);
}
/*****************************************************************************
- FUNCTION NAME: LTrim
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* s1 : stringa da L-trimmare
-----------------------------------------------------------------------------
- RETURN VALUE:
stringa L-trimmata
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
char* itxString::LTrim(char* str)
{
try
{
char* p = str;
while(*p == ' ')
p++;
strcpy(str, p);
}
catch(...)
{
return str;
}
return str;
}
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::LTrim()
{
LTrim(m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
return *this;
}
/*****************************************************************************
- FUNCTION NAME: RTrim
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* str : stringa da R-trimmare
-----------------------------------------------------------------------------
- RETURN VALUE:
stringa R-trimmata
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
char* itxString::RTrim(char* str)
{
try
{
char* p = str + strlen(str) - 1;
while(*p == ' ')
p--;
*(++p) = 0;
}
catch(...)
{
return str;
}
return str;
}
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::RTrim()
{
RTrim(m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
return *this;
}
/*****************************************************************************
- FUNCTION NAME: Trim
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char* str : stringa da trimmare
-----------------------------------------------------------------------------
- RETURN VALUE:
stringa trimmata
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
char* itxString::Trim(char* str)
{
try
{
if (str == NULL)
return NULL;
//L
char* p = str;
while(*p == ' ')
p++;
strcpy(str, p);
//R
p = str + strlen(str) - 1;
while(*p == ' ')
p--;
*(++p) = 0;
}
catch(...)
{
return str;
}
return str;
}
/*--------------- Object Version --------------------------------------------*/
itxString& itxString::Trim()
{
Trim(m_Str);
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
return *this;
}
itxString& itxString::RmBlankChars()
{
char* str = m_Str;
try
{
if (str == NULL)
return *this;
//L
char* p = str;
while(*p == ' ' || *p == 0x0A || *p == 0x0D || *p == '\t')
p++;
strcpy(str, p);
//R
p = str + strlen(str) - 1;
while(*p == ' ' || *p == 0x0A || *p == 0x0D || *p == '\t')
p--;
*(++p) = 0;
}
catch(...)
{
return *this;
}
//Set m_Cursor to the proper position
m_Cursor = m_Str + strlen(m_Str);
return *this;
}
/*****************************************************************************
- FUNCTION NAME: SetEmpty
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
stringa contenente il carattere '\0' (stringa vuota).
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
void itxString::SetEmpty()
{
*this = '\0';
m_Cursor = m_Str;
}
/*****************************************************************************
- FUNCTION NAME: SetInt
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
sprintf di un intero sul buffer interno.
*****************************************************************************/
/*--------------- Object Version --------------------------------------------*/
void itxString::SetInt(int val)
{
try
{
m_Cursor = m_Str;
if (m_Bufsize < INT_2_CHAR_LEN)
XALLOC(m_Str, m_Cursor, m_Bufsize, m_Granularity, INT_2_CHAR_LEN);
sprintf(m_Str, "%d", val);
RTrim(m_Str);
m_Cursor = m_Str + strlen(m_Str);
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::SetInt(int val)")
}
/*--------------- Object Version --------------------------------------------*/
char* itxString::CVFromDouble(double value, int mindecimal)
{
char buffer[50];
char newbuffer[50];
int len;
unsigned int prec = 10;
double frac, pint;
char c;
double cvalue = 0.0005;
try
{
if (fabs(value) > 0.0005)
{
sprintf(buffer, "%f", value);
char* dot = strstr(buffer, ".");
// remove tailing zeros
len = strlen(dot);
int ic = 0;
while ((c = dot[len - ic - 1]) == '0')
{
dot[len - ic - 1] = '\0';
ic ++;
}
int sign = 1;
len = strlen(dot);
if (len > 6)
{
frac = fabs(modf(value, &pint));
if (frac < 0) sign = -1;
bool converge = false;
double ceilvalue, floorvalue;
int idec = 1;
double trial;
while(!converge && idec < len + 1)
{
trial = frac * 10 * idec;
ceilvalue = ceil(trial);
floorvalue = floor(trial);
if ((ceilvalue - trial) < cvalue)
{
converge = true;
frac = ceilvalue / (10 * idec);
}
else if ((trial - floorvalue) < cvalue)
{
converge = true;
frac = floorvalue / (10 * idec);
}
idec++;
}
value = pint + sign * frac;
}
sprintf(buffer, "%f", value);
dot = strstr(buffer, ".");
// remove tailing zeros
len = strlen(dot);
ic = 0;
while ((c = dot[len - ic - 1]) == '0')
{
dot[len - ic - 1] = '\0';
ic ++;
}
len = strlen(buffer);
if (buffer[len - 1] == '.')
buffer[len - 1] = '\0';
else
{
sprintf(newbuffer, "%s", buffer);
dot = strstr(newbuffer, ".");
// trunc at contiguous zeros group
bool groupfound = false;
len = strlen(dot);
ic = 0;
int iz = 0;
while (!groupfound)
{
if (dot[ic + 1] == '0')
iz++;
else
iz = 0;
if (iz == 2 || ic == len)
{
groupfound = true;
dot[ic] = '\0';
}
ic++;
}
}
double newvalue = atof(newbuffer);
if (fabs(value - newvalue) < 0.0005)
sprintf(buffer, "%s", newbuffer);
//roundup if necessary
/*
if (len > 6)
{
buf = _ecvt(value, prec, &dec, &sign);
if (dec < 0)
cd = 4 - dec;
else if (dec >= 0 && dec < 3)
cd = 4 - dec;
else if (dec >= 3 && dec < 6)
cd = mindecimal + 1;
else
cd = mindecimal;
sprintf(format, "%%.%df", cd);
sprintf(buffer, format, value);
}
*/
}
else if (fabs(value) > 0.0000005)
{
sprintf(buffer, "%.12f", value);
char* dot = strstr(buffer, ".");
// remove tailing zeros
len = strlen(dot);
int ic = 0;
while ((c = dot[len - ic - 1]) == '0')
{
dot[len - ic - 1] = '\0';
ic ++;
}
}
else
sprintf(buffer, "%s", "0");
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::CVFromDouble(double value, int mindecimal)")
*this = &buffer[0];
return m_Str;
}
/*****************************************************************************
- FUNCTION NAME: GetToken
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
char sep : separatore
int pos : posizione del token
itxString* dest : destinazione
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
la posizione 0, sia nel caso di stringhe inizianti con il separatore che non,
ritorna il primo token
*****************************************************************************/
void itxString::GetToken(char sep, int pos, itxString* dest)
{
if (dest == NULL || pos < 0)
return;
try
{
char* pc = m_Str;
int count = 0;
while (count < pos && *pc != 0)
{
if (*pc == sep)
count++;
pc++;
}
if (count < pos)
return;
*dest = pc;
count = 0;
while (*pc != sep && *pc != 0)
{
count++;
pc++;
}
dest->Left(count);
}
CATCHALL(m_Str, m_Cursor, m_Bufsize, m_Granularity, "itxString::GetToken(char sep, int pos, itxString* dest)")
}
// converts the XXXXXXX.YYYY format string in X.XXX.XXX,YYYY
// converts the X.XXX.XXX,YYYY format string in XXXXXXX.YYYY if invert = -1
void itxString::Currency(int invert)
{
if (invert == -1)
{
InBlinder('"');
SubstituteSubString(".", "");
SubstituteSubString(",", ".");
}
else
{
int len = this->Len();
int dotpos = FindSubString(".");
if (len > dotpos + 3)
{
itxString sfrac;
sfrac = this->GetBuffer();
sfrac.Right(len - dotpos - 1);
sfrac.Left(3);
double dfrac = atof(sfrac.GetBuffer())/10.;
double dceil = ceil(dfrac);
double dfloor = floor(dfrac);
int rfrac;
if (dceil - dfrac > 0.5)
rfrac = (int)dfloor;
else
rfrac = (int)dceil;
Left(dotpos + 1);
if (rfrac < 10.)
*this += "0";
*this += rfrac;
}
SubstituteSubString(".", ",");
int dotins = dotpos - 3;
int stop = (GetAt(0) == '-' ? 1 : 0);
while (dotins > stop)
{
InsAt(".", dotins);
dotins -= 3;
}
if (FindSubString(",") == Len())
Strcat(",00");
if (FindSubString(",") == (Len() - 2))
Strcat("0");
}
}
/*****************************************************************************
- FUNCTION NAME: HexToAscii
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
void itxString::HexToAscii(char* source, char* destination, int src_len)
{
char chex[3];
int i;
if (source == NULL || destination == NULL)
return;
try
{
for (i = 0; i < src_len; i++)
{
memset(chex, 0, 3);
sprintf(chex, "%x", (unsigned char) source[i]);
if (strlen(chex) < 2)
{
chex[1] = chex[0];
chex[0] = '0';
}
memcpy(destination + 2 * i, chex, 2);
}
}
CATCHALLMSG("itxString::HexToAscii(char* source, char* destination, int src_len)")
}
/*****************************************************************************
- FUNCTION NAME: AsciiToHex
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
void itxString::AsciiToHex(char* source, char* destination, int src_len)
{
char chex[3];
char* stop;
int i;
char m;
if (source == NULL || destination == NULL)
return;
try
{
stop = &chex[2];
for (i = 0; i < src_len; i++)
{
memset(chex, 0, 3);
memcpy(chex, &source[i * 2], 2);
m = (char) strtol(chex, &stop, 16);
memcpy(destination + i, &m, 1);
}
}
CATCHALLMSG("itxString::HexToAscii(char* source, char* destination, int src_len)")
}
/*---------------------------------------------------------------------------*
WRAPPER FUNCTIONS
*---------------------------------------------------------------------------*/
int itxString_SubstituteSubString(char* base, char* what, char* with, char* retstr)
{
return itxString::SubstituteSubString(base, what, with, retstr);
}
int itxString_AdjustStr(char* base, char* retstr)
{
return itxString::AdjustStr(base, retstr);
}
int itxString_RemoveLeadingZeros(char* base, int zleft, char* retstr)
{
return itxString::RemoveLeadingZeros(base, zleft, retstr);
}
int itxString_Capitalize(char* base, char* retstr)
{
return itxString::Capitalize(base, retstr);
}
int itxString_RightInstr(char* base, char* search_arg, int start_from)
{
return itxString_RightInstr(base, search_arg, start_from);
}
int itxString_MaxTokenLen(char* base, char* sep)
{
return itxString::MaxTokenLen(base, sep);
}
char* itxString_UCase(char* str)
{
return itxString::UCase(str);
}
char* itxString_LCase(char* str)
{
return itxString::LCase(str);
}
int itxString_EscapeChars(char* source, char** destination)
{
return itxString::EscapeChars(source, destination);
}
void itxString_InBlinder(char **source, char blinder)
{
itxString::InBlinder(source, blinder);
}
int itxString_CompareNoCase(char* s1, char* s2)
{
return itxString::CompareNoCase(s1, s2);
}
char* itxString_LTrim(char* str)
{
return itxString::LTrim(str);
}
char* itxString_RTrim(char* str)
{
return itxString::RTrim(str);
}
char* itxString_Trim(char* str)
{
return itxString::Trim(str);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxlinux.cpp,v $
* $Revision: 1.5 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:31+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifdef LINUX
//This file implements the itxSystem class for Linux systems
#pragma message("=== itxSystem object is implemented for Linux platforms ===\n")
#include "itxsystem.h"
#include "itxstring.h"
//**************************************************************
int itxSystem::BSGetLastError()
{
return errno;
}
//**************************************************************
int itxSystem::PRGetProcessId()
{
return getpid();
}
//**************************************************************
int itxSystem::DLGetLastError()
{
return atoi(dlerror());
}
//**************************************************************
//* Returns current time_t and millisecs fraction.
void itxSystem::TMGetMilliTime(time_t* now, int* milli)
{
struct timeb timebuffer;
ftime(&timebuffer);
if (now != NULL)
*now = timebuffer.time;
if (milli != NULL)
*milli = timebuffer.millitm;
}
//**************************************************************
void itxSystem::FSSetMode(FILE* fp, int mode)
{
//TBD maybe nothing to do :)
}
//**************************************************************
void* itxSystem::DLLoadLibrary(char* fmodule)
{
return dlopen(fmodule, RTLD_LAZY);
}
//**************************************************************
bool itxSystem::DLFreeLibrary(void* pmodule)
{
//TBD: verificare parametro di ritorno
dlclose(pmodule);
return true;
}
//**************************************************************
void* itxSystem::DLGetFunction(void* pmodule, char* pfuncname)
{
return dlsym(pmodule, pfuncname);
}
//**************************************************************
void itxSystem::PRGetModuleName(void* pmodule, char* pfilename, int bufsize)
{
//TBD
}
//**************************************************************
void itxSystem::FSGetCurrentDirectory(char* pfilename, int bufsize)
{
getcwd(pfilename, (size_t)bufsize);
}
//**************************************************************
bool itxSystem::FSFileIsReadOnly(char* pfilename)
{
//TBD
return 0;
}
//**************************************************************
int itxSystem::BSSetenv(char* varname, char* varval)
{
return setenv(varname, varval, 1);
}
//**************************************************************
void itxSystem::FSDirToTokenString(char* dir, char* filter, char token, itxString* retlist)
{
if (dir == NULL || filter == NULL || retlist == NULL)
return;
if (*dir == 0 || *filter == 0)
return;
//TBD
}
//**************************************************************
void* itxSystem::THCreateThread(void* threadproc, void* threadarg, unsigned int* pretid)
{
//TBD
return 0;
}
//**************************************************************
void itxSystem::THPauseThread(void* thread)
{
//TBD
}
//**************************************************************
void itxSystem::THResumeThread(void* thread)
{
//TBD
}
//**************************************************************
void itxSystem::THTerminateThread(void* thread)
{
//TBD
}
//**************************************************************
int itxSystem::SOGetLastError(int socket)
{
int res;
char lasterror[20];
memset(lasterror, '\0', 0);
socklen_t len;
if ((res = getsockopt(socket, SOL_SOCKET, SO_ERROR, lasterror, &len)) == 0)
return -1;
sprintf(lasterror, "%d", res);
return atoi(lasterror);
}
//**************************************************************
bool itxSystem::SOInitLibrary()
{
return true; //nothing to do here!
}
//**************************************************************
bool itxSystem::SOCloseLibrary()
{
return true; //nothing to do here!
}
//**************************************************************
void itxSystem::SOInitDescriptors(void* fdstruct, int socket)
{
if (fdstruct != NULL)
{
FD_ZERO((fd_set*)fdstruct); //initialization
FD_SET(socket, (fd_set*)fdstruct);
}
}
//**************************************************************
void itxSystem::SOClose(int socket)
{
close(socket);
}
#endif //LINUX
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __DEFINES_H__
#define __DEFINES_H__
//Compilation options
//#define MAINT_1 //check if must use dbg
//#define TIMETRACE //check if must print timing stats
#define AITECSA_DISCLAIMER "<!--\r\
This file has been created from the Tannit 4.0 Application owned, produced and distributed\r\
uniquely by AITECSA S.r.l. This copy of Tannit 4.0 is intended to run only on machines owned\r\
by explicitly authorized users, owners of a run time license of Tannit 4.0 product.\r\
Any other use is discouraged and will be persecuted in the terms established by the current laws. \r\
FGPC00013 FMPC00001 MGPC00005 \r\
-->\r"
/*
FMPC00001 - fixed conversion of double data type;
FGPC00013 - Modificata la netgrab e la netprex: il browser agent non pi
"Aitecsa Thunder v 1.45" ma "Thunder v 1.45"
FGPC00012 - Modificata la netgrab: ora torna il numero di bytes scaricati
FGPC00010 - Aggiunto il comando getcast
FGPC00010 - Aggiunta l'opzione refferrer nel comando traceu
FGPC00009 - Impostata la variabile di abiente m_ActualTplDir del Parser ed attivato
l'allineamento della directory del *prex in caso di preprocessing con chiave
FGPC00008 - Modificata pesantemente la Tannit::OnStart aggiungendo le funzioni
Tannit::ManageContext e Tannit::ManageOutput.
Il preprocessing ora condizionabile da chiavi all'interno del file
dei parametri
FGPC00007 - Invertito l'ordine tra la lettura del file tannit.conf e l'acquisizione
dei parametri d'ambiente; questo evita che il programma si blocchi qualora
non trovi tannit.conf cadendo nel trappolone per il modo command line
FGPC00006 - Risolta diversamente la MGPC00001: non viene pi impostata la directory
di esecuzione del programma ma vengono definite le directory ausiliarie
dove cercare i file tannit.conf e prm nel caso non vengano trovati in quella
corrente.
FGPC00005 - Modificato netgrab aggiunto il parametro dei secondo di timeout
FGPC00004 - modificata la *proc: ora se nel prm e' presente il parametro ForceProcCmdTag
non usa la PickPar ma processa direttamente il buffer;
FGPC00003 - modificata la newconn: ritorna un valore con il 5 parametro;
FGPC00002 - *netgrab(url,maxbytes,tofilename) command added;
FGPC00001 - test version of the *copyf(fromfile,tofile) command added;
MGPC00005 - aggiunto il comando mail
MGPC00004 - comando tqrstat: aggiunte info sui campi; macro facilities in tnt.h
correzzione bug: le variabili in prm e con ora sono trimmate a sx e dx.
MGPC00003 - modifica funzionalita` di inquiry, tplservice, response mime type.
MGPC00002 - WIN32: aggiunta funzionalita` di inquiry.
MGPC00001 - WIN32: modifica alla directory in cui vengono prelevati i file conf e prm:
ora sempre dalla dir in cui risiede Tannit.
*/
// Messaggi per la comunicazione con il client download/upload "Aleph"
#define FILE_UPLOADED 1
#define FILE_DOWNLOADED 2
#define DND_CONFIRMED 3
#define NO_FILE_AVAIL 4
#define LOGIN_SUCCESS 5
#define UNABLE_TO_UPLOAD 1002
#define SERVER_ERROR 1003
#define USER_NOT_ENABLED 1004
#define FATAL_ERROR 1999
#define ALEPH_START_COM "ITX_START_OF_TRASMISSIONS_GOOD_LUCK"
#define ALEPH_END_COM "ITX_END_OF_TRASMISSIONS_RETURNING_CODE"
// chiavi per l'invio e la ricezione di file
#define EXCNG_FILE_TAG "excng"
#define SEND_FILE_GRANT "92"
#define RECEIVE_APPC_FILE_GRANT "93"
#define DND_CONFIRM_GRANT "94"
#define RECEIVE_FILE_GRANT "95"
// Chiavi per la comunicazione con Baal: TntRequestTypes
#define RT_BROWSE 0
#define RT_PREPROC 1
#define RT_PREPROC_ALL 2
#define RT_PREVIEW 3
#define TPL_UPD_COMM_RECV "<html><body bgcolor=#44AAFF><font color=Blue><b>Tpl:"
#define TPL_UPD_COMM_SUCC "<br><Font size=1 color=red>E' il direttore che vi parla: sbaraccate ed andatevene in vacanza</Font></b></BODY></HTML>"
// Errori di interrogazione del database
#define ERR_MSG_LEN 256
#define ERRORS_EDGE 0 // limite superiore per i return che definiscono errori
#define DATA_VALUE_ON_ERROR "itxdbdatadefval"
#define ERR_COL_NOT_FOUND "Error: field not found."
#define ERR_QUERY_NOT_FOUND "Error: query not found."
#define ERR_VOID_QUERY_NAME "Error: unable to read query name."
#define LOGIN_ERROR "Error: login failed."
#define ERR_PARAM_NEEDED "Error: parameter needed."
// Errori di sintassi GASP
#define ERR_REM_BLINDCH "Error: double quotes expected."
#define ERR_OPEN_INI_FILE "Error: conf or prm file(s) not found: remember to put them in the same Tannit directory.\n"
#define ERR_OPEN_TPL_FILE "Error: template not found or empty.\n"
#define PARAMETER_NOT_FOUND "notfound"
#define FIELD_NAME_NOT_FOUND "Error: field name not found in get string"
#define INVALID_LOGIN_FILE "loginerror"
#define PARAM_NOT_FOUND_MSG "Error: parameter not found"
#define PAR_NOT_FOUND "paramfileNotFound"
// Errori generici
#define CRYPTING_ERROR "Crypting Error"
#define MEMERR 23
#define MEMORY_ERROR_MSG "Memory allocation Error"
//Messaggi durante il preprocessing
#define PP_STARTED "Now preprocessing...<br>"
#define PP_FINISHED "Preprocess operation completed.<br>"
#define PP_CANT_WRITEOUTPUT "Error while attempting to write on the output file.<br>"
#define PP_IN_OUT_DIRS_EQ "Can't generate output file: preprocess and template directories are the same.<br>"
#define PP_NOT_ALLOWED "Preprocessing not allowed"
#define WWW_PP_STARTED "<html><head><title>PREPROCESSING</title><STYLE>body {border-width: 1px; border-color: #226622; border-style: solid; margin: 0px 0px 0px 0px; background-color: #55aa55; font-family: tahoma; font-size: 8pt;}</STYLE></head><body>"
#define WWW_PP_FINISHED "completed</body></html>"
#define WWW_PP_CANT_WRITEOUTPUT "<table width=100% bgcolor=#aa6666><tr><td>Error while attempting to write on the output file.</td></tr></table>"
#define WWW_PP_IN_OUT_DIRS_EQ "<table width=100% bgcolor=#bb7777><tr><td>Can't generate output file: preprocess and template directories are the same.</td></tr></table>"
#define WWW_PP_NOT_ALLOWED "<table width=100% bgcolor=#cc8888><tr><td>Preprocessing not allowed</td></tr></table>"
// Etichette
#define TANNIT_CONFIG_FILE "tannit.conf"
#define BROWSER_OPERA "Opera"
#define BROWSER_MSIE "MS Internet Explorer"
#define BROWSER_NETSCAPE "Netscape Comunicator"
#define ITX_MISINTER "itxmisi"
#define ISEXPLORER "explorer"
#define ISNETSCAPE "netscape"
#define LOGIN_TAG "login"
#define CPWD_TAG "cpwd"
#define TPLDIR "tpldir"
#define ADDON "addon"
#define BLINDER '"'
#define CONC_LAN_ID_TAG "lid"
#define DEF_PAR_FILE "tannit"
#define DEF_PAR_FILE_EXT "prm"
#define PAR_FILE_TAG "prm"
#define DEFAULT_TPL "tannit"
#define TGT_TAG "tgt"
#define TPL_TAG "tpl"
#define TPL_SERVICE_TAG "tplservice"
#define MIME_TAG "mime"
#define PREPROC_TPL_TAG "preproc"
#define PREPROC_DIR_PRM_NAME "preprocdir"
#define DEBUG_2_VIDEO_TAG "forcedebug"
#define INQUIRY_TAG "diagnostic"
#define TPL_EXT ".htm"
#define TEG_EXT ".teg"
#define DEFAULT_MIME_TYPE "text/html"
#define START_COMMAND_TAG '*'
#define PREPROC_COMMAND_TAG '#'
#define TEG_COMMAND_TAG '' //Tannit Extension Generator
#define CMD_ARG_OPEN_TAG '('
#define CMD_ARG_CLOSE_TAG ')'
#define PARAM_NOT_FOUND 0
#define PARAM_FOUND 1
#define PARAM_NUMBER 128
#define CND_OP_NUM 6
#define GET_PAR_VAL ""
#define REC_VAL_ZERO ""
#define DND_FILE_DONE "2"
#define DND_FILE_READY "1"
#define ITX_UPLOAD_FILE_TAG "itxFile"
#define CORR_UPLOAD_DIR "./itxCrUp/"
#define ITXCOO_SEP "#"
#define TANNIT_TRUE "true"
#define TANNIT_FALSE "false"
#define TNT_COMMENT "$$"
#define LF 0xA
#define CR 0xD
#define TQR_FOR_PREFIX "tqr_"
// Numerici
#define MAX_DSN 32
#define MAX_CRYPTING_BUFFER 256
#define BUFFER_SIZE 10000
#define LANG_ID_LEN 8
#define ID_FIELD_LEN 255
#define EXTRID_FIELD_LEN 256
#define TPL_VARS_NUM 64
#define CYC_NESTING_DEPTH 64
#define SELECTED_ADD_ON 32
#define LANID_LEN 4 /*lunghezza max dell'identificatore di linguaggio*/
#define INIT_FILE_LINE_LEN 512 /*lunghezza massima di una riga del file di inizializzazione*/
#define PAR_NAME_LEN 64 /*lunghezza massima del nome di un parametro nel file di inizializzazione*/
#define PAR_VALUE_LEN 256 /*lunghezza massima del valore di un parametro nel file di inizializzazione*/
#define INIT_FILE_NAME_LEN 256
#define HOME_DIR_LEN 64
#define IMG_DIR_LEN 64
#define SS_DIR_LEN 64
#define GET_VAR_LEN 128
#define TPL_LEN 250000
#define TPL_ABS_NAME_LEN 1024
#define MAX_TPL_NESTS 24
#define TPL_NAME_LEN 256
#define CMD_LEN 64
#define GET_PAR_VAL_LEN 4096
#define ITXCOO_TIME_DELAY 10000 // in secondi
#define PRM_TUNNEL_TAG "KOAN"
#define MAX_PRM_PARS 1000 //Max num di params in un prm
#define MAX_CMDS 1024
#define MAX_EXT_MODULES 50
// TQR Statistic
#define TOTRECS "TOTRECS"
#define ACTUALROW "ACTUALROW"
#define ACTUALPAGE "ACTUALPAGE"
#define ROWSTOSTORE "ROWSTOSTORE"
#define STARTINGROW "STARTINGROW"
#define MORERECS "MORERECS"
#define SOURCECOUNT "SOURCECOUNT"
#define TOTALPAGES "TOTALPAGES"
#define LASTPAGEROW "LASTPAGEROW"
#define NEXTPAGEROW "NEXTPAGEROW"
#define PREVPAGEROW "PREVPAGEROW"
// TQR cursor movement
#define FIRST "FIRST"
#define LAST "LAST"
#define NEXT "NEXT"
#define TO "TO"
// TQR info
#define COLCOUNT "COLCOUNT"
#define COLNAME "COLNAME"
#define COLTYPE "COLTYPE"
#define COLSIZE "COLSIZE"
// Base Command 'type' definitions
#define DEFAULT_BC_TYPE 0
#define START_CYCLE 1
#define END_CYCLE 2
#define START_CND_BLK 4
#define ELSE_CND_BLK 8
#define END_CND_BLK 16
#define ELSIF_CND_BLK 32
//Blocking - non blocking execution states
#define DONT_EXEC_BLK 0
#define EXEC_BLK 1
#define STOP_EXEC_BLK 2
//Inquiry
#define INQ_TOK_SEP '*'
#define INQ_CONN_OK "OK"
#define INQ_CONN_NOK "NOK"
#ifdef DOWNLOAD
#pragma message("WARNING: you are compiling a time limited version. Disable DOWNLOAD option for no time expiration.")
#endif
#endif /* __DEFINES_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : commands.cpp
| TAB : 2 spaces
|
| DESCRIPTION : main implementation file for all base command objects.
|
|
*/
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include "desx.h"
#include "itxtypes.h"
#include "commands.h"
#include "templatefile.h"
#define CRYPT_KEY "itxsecur";
#define CRYPT_WHT "byFabioM";
#define ITXCOOVERS_EQ "="
#define ITXCOOVERS_SEP ";"
#define ITX_DES_BLOK 8
/*----------------------------------------------------------------------------
BC_StartConditionalBlock
----------------------------------------------------------------------------*/
/*
attivita' :inizio del blocco condizionato; necessita di un comando *endif()/*endblk()
per la terminazione del blocco:
la condizione utilizza gli operatori
== uguale
!= diverso
< minore
> maggiore
<= minore-uguale
=> uguale-maggiore
per il confronto tra i due termini.
Nel caso entrambi i termini del confronto siano convertibili a numeri
interi il confronto avviene tra interi. altrimenti tra stringhe.
Se la condizione � una stringa nulla l'if non ha successo.
Se la condizione non contiene nessun operatore e la stringa non � nulla
l'if ha successo.
Se il confronto ha successo il blocco viene elaborato dal parser ed i
comandi al suo interno non vengono eseguiti.
*/
char* BC_StartConditionalBlock::Execute(char* inputStr)
{
char* operators[] = {"==","!=","<","<=",">=",">"};
char* opPosition;
itxString leftOp;
itxString rightOp;
int opOrd = -1;
int result = 0;
int numops = sizeof(operators)/sizeof(char*);
int lopint = 0;
int ropint = 0;
bool numeric_conv_good = false;
for (opOrd=0; opOrd<numops; opOrd++)
if ((opPosition = strstr(inputStr, operators[opOrd])) != NULL)
break;
if (opOrd == numops)
{
// se non vi � operatore il blocco si considera TRUE se vi e' una qualsiasi stringa
m_pParser->SetValidBlock(((strlen(inputStr) > 0) ? EXEC_BLK : DONT_EXEC_BLK));
return NULL;
}
//extracts operands
leftOp.Strncpy(inputStr, (unsigned)opPosition - (unsigned)inputStr);
rightOp = (char*)((unsigned)opPosition + strlen(operators[opOrd]));
leftOp.Trim();
rightOp.Trim();
// nel caso di operatori convertibili ad interi vengono confrontati i valori interi
if ((lopint = atoi(leftOp.GetBuffer())) && (ropint = atoi(rightOp.GetBuffer())))
{
itxString appo;
appo.SetInt(lopint);
if (appo.Compare(&leftOp) == 0)
{
appo.SetInt(ropint);
if (appo.Compare(&rightOp) == 0)
{
result = lopint - ropint;
numeric_conv_good = true;
}
}
}
if (!numeric_conv_good)
result = leftOp.Compare(&rightOp);
switch (opOrd)
{
case 0:
m_pParser->SetValidBlock(result != 0 ? DONT_EXEC_BLK : EXEC_BLK);
break;
case 1:
m_pParser->SetValidBlock(result != 0 ? EXEC_BLK : DONT_EXEC_BLK);
break;
case 2:
m_pParser->SetValidBlock((result<0) ? EXEC_BLK : DONT_EXEC_BLK);
break;
case 3:
m_pParser->SetValidBlock((result<=0) ? EXEC_BLK : DONT_EXEC_BLK);
break;
case 4:
m_pParser->SetValidBlock((result>=0) ? EXEC_BLK : DONT_EXEC_BLK);
break;
case 5:
m_pParser->SetValidBlock((result>0) ? EXEC_BLK : DONT_EXEC_BLK);
break;
}
return NULL;
}
/*----------------------------------------------------------------------------
BC_GetValue
----------------------------------------------------------------------------*/
/*
attivita' :restituisce il valore del parametro di get indicato
- parametro: nome del parametro di get di cui restituire il valore
- OPZdefault: valore di default ritornato nel caso non si trovi il
parametro.
N.B. se OPZdefault � il carattere '+' il valore
ricavato per il parametro viene modificato sostituendo tutti
i caratteri non alfanumerici con la stringa %xx dove xx �
il valore ascii esadecimale del carattere sostituito.
*/
char* BC_GetValue::Execute(char* istr)
{
itxString defParVal;
itxString getParName;
int useDefault = 0;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &getParName) == PARAM_NOT_FOUND)
{
m_Output = PARAM_NOT_FOUND_MSG;
return m_Output.GetBuffer();
}
if (m_pParser->PickPar(istr, 2, &defParVal) == PARAM_FOUND)
useDefault = 1;
if (m_pCGIRes->cgiFormString(getParName.GetBuffer(), &m_Output, 0) != cgiFormSuccess)
{
if (useDefault) // valore opzionale di default definito dall'utente
m_Output = defParVal;
else // valore di default generico
m_Output = GET_PAR_VAL;
}
if (!defParVal.IsNull() && strcmp(defParVal.GetBuffer(), "+") == 0)
{
if(!m_Output.IsNull() && strcmp(m_Output.GetBuffer(), "+") == 0)
m_Output = "";
m_Output.EscapeChars();
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_GetHide
----------------------------------------------------------------------------*/
/*
attivita' :nasconde i caratteri non alfanumerici del parametro trasformandoli in %xx
dove xx � il valore ascii esadecimale del carattere sostituito.
*/
char* BC_GetHide::Execute(char* istr)
{
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &m_Output) == PARAM_NOT_FOUND)
return NULL;
m_Output.EscapeChars();
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_ProcessExternFile
----------------------------------------------------------------------------*/
/*
attivita' :prosegue il parsing nel file specificato. Una volta concluso quest'ultimo
prosegue per il file di partenza.
*/
char* BC_ProcessExternFile::Execute(char* istr)
{
itxString tplName;
itxString tpldir;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &tplName) == PARAM_NOT_FOUND)
{
m_Output = PARAM_NOT_FOUND_MSG;
return m_Output.GetBuffer();
}
//printf("%s<br>", tplName);
if(m_pParser->m_ActualTplDir.IsEmpty())
m_pCGIRes->m_PRMFile.GetPRMValue(TPLDIR, &tpldir);
else
tpldir = m_pParser->m_ActualTplDir;
m_pParser->Run(&tpldir, &tplName);
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_SetVar
----------------------------------------------------------------------------*/
/*
attivita' : assegna alla variabile varName il valore varValue.
*/
char* BC_SetVar::Execute(char* istr)
{
itxString varName;
itxString varValue;
if (m_pParser->PickPar(istr, 1, &varName) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &varValue) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if (varName.IsNull() || varName.IsEmpty())
{
DebugTrace2(IN_COMMAND | IN_WARNING, "Command setvar invoked with empty variable name.\n");
return NULL;
}
if (varValue.IsNull() || varValue.IsEmpty())
DebugTrace2(IN_COMMAND, "Command setvar invoked with empty variable value.\n");
int i;
for (i=0; i<m_pParser->m_TplVars.idx; i++)
{
if (!m_pParser->m_TplVars.names[i].IsNull())
{
if (strcmp(m_pParser->m_TplVars.names[i].GetBuffer(), varName.GetBuffer()) == 0)
break;
}
}
if (i == m_pParser->m_TplVars.idx)
{
if (i < TPL_VARS_NUM)
{
m_pParser->m_TplVars.names[i] = varName;
m_pParser->m_TplVars.values[i] = varValue;
m_pParser->m_TplVars.idx++;
}
else
return NULL;
}
else
m_pParser->m_TplVars.values[i] = varValue ;
return NULL;
}
/*----------------------------------------------------------------------------
BC_GetVar
----------------------------------------------------------------------------*/
/*
attivita' :restituisce il valore della variabile varName.
*/
char* BC_GetVar::Execute(char* istr)
{
itxString varName;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &varName) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_pParser->PickPar(istr, 2, &m_Output);
if (varName.IsNull() || varName.IsEmpty())
{
DebugTrace2(IN_COMMAND | IN_WARNING, "Command getvar invoked with empty variable name.\n");
return NULL;
}
for (int i=0; i < m_pParser->m_TplVars.idx; i++)
{
if (
!m_pParser->m_TplVars.names[i].IsNull() &&
m_pParser->m_TplVars.names[i].Compare(&varName) == 0
)
{
if (!m_pParser->m_TplVars.values[i].IsEmpty())
m_Output = m_pParser->m_TplVars.values[i];
break;
}
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_GetCookie
----------------------------------------------------------------------------*/
/*
attivita' : torna il cookie specificato
*/
char* BC_GetCookie::Execute(char* istr)
{
itxString cooName;
itxString cooAttr;
char* pcoo = NULL;
char* pcomma = NULL;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &cooName) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
DebugTrace2(IN_COMMAND, "COMMAND getcoo\n");
DebugTrace2(IN_COMMAND, " cgiCookie : %s\n", m_pCGIRes->cgiCookie);
if ((pcoo = strstr(m_pCGIRes->cgiCookie, cooName.GetBuffer())) != NULL)
{
if ((pcoo = strstr(pcoo, ITXCOOVERS_EQ)) != NULL)
{
pcoo++;
if ((pcomma = strstr(pcoo, ITXCOOVERS_SEP)) != NULL)
{
m_Output.Strncpy(pcoo, (size_t) (pcomma - pcoo));
pcoo = pcomma;
}
else
m_Output.Strncpy(pcoo, strlen(pcoo));
}
}
if (m_pParser->PickPar(istr, 2, &cooAttr) != PARAM_NOT_FOUND)
{ // Cookie Name found, let see if is enough
m_Output = "";
if ((pcoo = strstr(pcoo, cooAttr.GetBuffer())) != NULL)
{
if ((pcoo = strstr(pcoo, ITXCOOVERS_EQ)) != NULL)
{
pcoo++;
if ((pcomma = strstr(pcoo, ITXCOOVERS_SEP)) != NULL)
m_Output.Strncpy(pcoo, (size_t)(pcomma - pcoo));
else
m_Output.Strncpy(pcoo, strlen(pcoo));
}
}
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_UTime
----------------------------------------------------------------------------*/
/*
attivit� : trasforma data, mese e anno in universal time (secondi passati dalla
mezzanotte del 1.1.1970)
*/
char* BC_UTime::Execute(char* istr)
{
itxString par; //Collects year, month, day, hour, min, sec in this order
struct tm datar;
time_t datas;
char ret[100];
m_Output.SetEmpty();
datar.tm_hour = 0;
datar.tm_isdst = -1;
datar.tm_mday = 0;
datar.tm_min = 0;
datar.tm_mon = 0;
datar.tm_sec = 0;
datar.tm_wday = 0;
datar.tm_yday = 0;
datar.tm_year = 0;
par.SetEmpty();
if (m_pParser->PickPar(istr, 1, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_year = atoi(par.GetBuffer()) - 1900;
if (m_pParser->PickPar(istr, 2, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_mon = atoi(par.GetBuffer()) - 1;
if (m_pParser->PickPar(istr, 3, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_mday = atoi(par.GetBuffer());
if (m_pParser->PickPar(istr, 4, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_hour = atoi(par.GetBuffer());
if (m_pParser->PickPar(istr, 5, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_min = atoi(par.GetBuffer());
if (m_pParser->PickPar(istr, 6, &par) && !par.IsNull() && !par.IsEmpty())
datar.tm_sec = atoi(par.GetBuffer());
datas = mktime(&datar);
sprintf(ret, "%ld", datas);
m_Output = ret;
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_DMYTime
----------------------------------------------------------------------------*/
/*
attivita' : trasforma una stringa che rappresenta una universal time (secondi
passati dalla mezzanotte del 1.1.1970) in formato normale oppure, se
presente un secondo parametro di valore d,m,y, torna il giorno, o il mese,
o l'anno.
*/
char* BC_DMYTime::Execute(char* istr)
{
char ret[100];
itxString utime;
itxString tag;
struct tm* dt;
time_t timet;
m_Output.SetEmpty();
memset(ret, '\0', 100);
if (m_pParser->PickPar(istr, 1, &utime) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
timet = (time_t)atol(utime.GetBuffer());
dt = localtime(&timet);
//dt->tm_mon--;
if (dt == NULL)
return "";
if (m_pParser->PickPar(istr, 2, &tag) == PARAM_FOUND)
{
if (tag.Compare("d") == 0)
strftime(ret, 100,"%d", dt);
else if (tag.Compare("m") == 0)
strftime(ret, 100,"%m", dt);
else if (tag.Compare("y") == 0)
strftime(ret, 100,"%Y", dt);
}
else
strftime(ret, 100, "%Y-%m-%d %H:%M:%S", dt);
m_Output = ret;
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_Now
----------------------------------------------------------------------------*/
/*
attivita' : restituisce il numero di secondi passati dalla mezzanote del 1.1.1970
(universal time); se � presente il parametro opzionale restituisce, a
seconda del valore di quest'ultimo,
d - il giorno corrente
m - il mese corrente
y - l'anno corrente
*/
char* BC_Now::Execute(char* istr)
{
time_t tm;
struct tm* today;
itxString part;
m_Output.SetEmpty();
time(&tm);
today = localtime(&tm);
m_Output.Space(15);
sprintf(m_Output.GetBuffer(), "%ld", tm);
if(m_pParser->PickPar(istr, 1, &part))
{
if (part.Compare("d") == 0)
strftime(m_Output.GetBuffer(), 15,"%d", today);
else if (part.Compare("m") == 0)
strftime(m_Output.GetBuffer(), 15,"%m", today);
else if (part.Compare("y") == 0)
strftime(m_Output.GetBuffer(), 15,"%Y", today);
}
m_Output.Trim();
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_FormatCurrency
----------------------------------------------------------------------------*/
/*
attivita' : ritorna la valuta source formattata con le interpunzioni tra le migliaia
ed il numero di decimali specificato
*/
char* BC_FormatCurrency::Execute(char* istr)
{
itxString source;
itxString decimaliSt;
int decimali = 0;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &source) == PARAM_NOT_FOUND)
return "";
if(m_pParser->PickPar(istr, 2, &decimaliSt) == PARAM_FOUND)
decimali = atoi(decimaliSt.GetBuffer());
if(decimali < 0)
return "";
char* ret = Format(source.GetBuffer(), decimali, 1);
if (ret)
{
m_Output = ret;
free(ret);
}
return m_Output.GetBuffer();
}
//---------------------------------------------------------------------
char* BC_FormatCurrency::Format(char* num, int mant_len, int want_sep)
{
const char* sep = ".";
char* ret = NULL;
int numlen = strlen(num);
int first_pt = 0;
if (num == NULL || numlen == 0)
return NULL;
if ((ret = (char*)calloc(3 * ((numlen >= mant_len ? numlen : mant_len) + 1), 1)) == NULL)
return NULL;
if (strstr(num, ",") != NULL)
{
strcpy(ret, num);
return ret;
}
if (numlen > mant_len) //Il numero e` > 1 ?
{
if (numlen - mant_len > 3 && want_sep) //Gestione separatore 3 cifre
{
first_pt = (numlen - mant_len) % 3;
if (first_pt > 0)
{
memcpy(ret, num, first_pt);
strcat(ret, sep);
}
int i;
for (i = first_pt; i<numlen - mant_len; i+=3)
{
memcpy(ret + strlen(ret), num + i, 3);
strcat(ret, sep);
}
if ((i = strlen(ret)) > 0)
ret[i - 1] = 0;
//Se c'e` parte decimale, metto la virgola e l'attacco
if (mant_len > 0)
{
strcat(ret, ",");
strcat(ret, num + numlen - mant_len);
}
}
else
{
memcpy(ret, num, numlen - mant_len);
strcat(ret, ",");
strcat(ret, num + numlen - mant_len);
}
}
else
{
strcat(ret, "0,");
memset(ret + 2, '0', mant_len - numlen);
strcat(ret, num);
//remove nonsense final zeros
char* p = &ret[strlen(ret) - 1];
while (*p == '0')
p--;
*(++p) = 0;
}
if (ret[strlen(ret) - 1] == ',')
ret[strlen(ret) - 1] = 0;
return ret;
}
/*----------------------------------------------------------------------------
BC_CheckForbiddenChars
----------------------------------------------------------------------------*/
/*
attivita' :cerca i caratteri contenuti nella stringa ForbiddenChars nella teststring
return :TANNIT_TRUE se trova i caratteri; TANNIT_FALSE se non trova i caratteri;
*/
char* BC_CheckForbiddenChars::Execute(char* istr)
{
itxString str2check;
itxString ForbiddenChars;
if(m_pParser->PickPar(istr, 1, &str2check) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &ForbiddenChars) == PARAM_NOT_FOUND)
return TANNIT_FALSE;
return (char*)(strpbrk(str2check.GetBuffer(), ForbiddenChars.GetBuffer()) == NULL ? TANNIT_FALSE : TANNIT_TRUE);
}
/*----------------------------------------------------------------------------
BC_TraceUser
----------------------------------------------------------------------------*/
/*
attivita' :restituisce informazioni sul client a seconda del parametro feature.
feature=brname->nome del browser
feature=brver ->versione del browser (solo parte intera)
feature=osname->nome del sistema operativo
feature=ipnum ->numero ip
feature=ipname->nome, quando risolvibile, della macchina remota
*/
char* BC_TraceUser::Execute(char* istr)
{
itxString feature;
itxString brname;
itxString brver;
itxString osname;
char* cursor;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &feature) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if ((cursor = strstr(m_pCGIRes->cgiUserAgent, "Mozilla/")) != NULL)
{
if (cursor = strstr(m_pCGIRes->cgiUserAgent, "MSIE"))
{
brname = BROWSER_MSIE;
brver = &cursor[5];
if(strstr(m_pCGIRes->cgiUserAgent, "Windows 98"))
osname = "MS Windows 98";
else if(strstr(m_pCGIRes->cgiUserAgent, "Windows 95"))
osname = "MS Windows 95";
else if(strstr(m_pCGIRes->cgiUserAgent, "Windows NT"))
osname = "MS Windows NT";
else if(strstr(m_pCGIRes->cgiUserAgent, "Windows 3.1"))
osname = "MS Windows 3.1";
else if(strstr(m_pCGIRes->cgiUserAgent, "Mac_"))
osname = "Apple Macintosh";
}
else if (cursor = strstr(m_pCGIRes->cgiUserAgent, "Opera"))
brname = BROWSER_OPERA;
else if (cursor = strstr(m_pCGIRes->cgiUserAgent, "Gecko"))
brname = "Gecko";
else
{
brname = BROWSER_NETSCAPE;
brver = &m_pCGIRes->cgiUserAgent[8];
if(strstr(m_pCGIRes->cgiUserAgent, "Win98"))
osname = "MS Windows 98";
else if(strstr(m_pCGIRes->cgiUserAgent, "Win95"))
osname = "MS Windows 95";
else if(strstr(m_pCGIRes->cgiUserAgent, "WinNT"))
osname = "MS Windows NT";
else if(strstr(m_pCGIRes->cgiUserAgent, "Win16"))
osname = "MS Windows 3.1";
else if(strstr(m_pCGIRes->cgiUserAgent, "Macintosh"))
osname = "Macintosh";
else if(strstr(m_pCGIRes->cgiUserAgent, "Linux"))
osname = "Linux";
else if(strstr(m_pCGIRes->cgiUserAgent, "SunOS"))
osname = "SunOS";
}
}
if (feature.Compare("brname") == 0)
m_Output = brname;
else if (feature.Compare("brver") == 0)
{
m_Output = brver;
int semicol = brver.FindSubString(";");
if (semicol >= 0)
m_Output.Strncpy(brver.GetBuffer(), semicol);
else
m_Output = brver;
}
else if (feature.Compare("osname") == 0)
m_Output = osname;
else if (feature.Compare("ipnum") == 0)
m_Output = m_pCGIRes->cgiRemoteAddr;
else if (feature.Compare("ipname") == 0)
m_Output = m_pCGIRes->cgiRemoteHost;
else if (feature.Compare("referrer") == 0)
m_Output = m_pCGIRes->cgiReferrer;
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_ODBCExecuteQuery
----------------------------------------------------------------------------*/
/*
attivita' :esegue una chiamata sql all'odbc di default specificato nel file di
inizializazione; gli eventuali risultati vengono messi in una struttura
rintracciabile per il nome della query
par 1 :nome della query (costituira' l'etichetta di identificazione dei risultati)
par 2 :query sql compresa tra doppi apici
par 3 opz :primo record del resultset da memorizzare nella struttura (opzionale,
valore di default = STARTING_ROW, tipicamente 1)
par 4 opz :numero di record del resultset da memorizzare nella struttura (opzionale,
valore di default = a ROWS_TO_STORE, tipicamente 512)
*/
char* BC_ODBCExecuteQuery::Execute(char* istr)
{
itxString queryName;
itxString queryString;
itxString firstRecord;
itxString recsToStore;
int firstRecInt = STARTING_ROW;
int recsToStoreInt = ROWS_TO_STORE;
if(m_pParser->PickPar(istr, 1, &queryName) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &queryString) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &firstRecord) == PARAM_FOUND)
firstRecInt = atoi(firstRecord.GetBuffer());
if(m_pParser->PickPar(istr, 4, &recsToStore) == PARAM_FOUND)
recsToStoreInt = atoi(recsToStore.GetBuffer());
queryString.InBlinder('\"');
queryString.SubstituteSubString("\"\"", "\"");
m_pTQRODBCManager->Execute(queryName.GetBuffer(), queryString.GetBuffer(), firstRecInt, recsToStoreInt);
return NULL;
}
/*
char* BC_ODBCExecuteQuery::Execute(char* istr)
{
itxString* queryName = new itxString();
itxString* queryString = new itxString();
itxString* firstRecord = new itxString();
itxString* recsToStore = new itxString();
int firstRecInt = STARTING_ROW;
int recsToStoreInt = ROWS_TO_STORE;
if(m_pParser->PickPar(istr, 1, queryName) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, queryString) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, firstRecord) == PARAM_FOUND)
firstRecInt = atoi(firstRecord->GetBuffer());
if(m_pParser->PickPar(istr, 4, recsToStore) == PARAM_FOUND)
recsToStoreInt = atoi(recsToStore->GetBuffer());
queryString->InBlinder('\"');
queryString->SubstituteSubString("\"\"", "\"");
m_pTQRODBCManager->Execute(queryName->GetBuffer(), queryString->GetBuffer(), firstRecInt, recsToStoreInt);
delete queryName;
delete queryString;
delete firstRecord;
delete recsToStore;
return NULL;
}
*/
/*----------------------------------------------------------------------------
BC_TQRRecordFieldValue
----------------------------------------------------------------------------*/
char* BC_TQRRecordFieldValue::Execute(char* istr)
{
itxString tqrname;
itxString colname;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &colname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output = m_pTQRCollection->GetCurrentRecordField(tqrname.GetBuffer(), colname.GetBuffer());
if( m_Output.IsNull() || m_Output.IsEmpty() )
m_pParser->PickPar(istr, 3, &m_Output);
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_TQRRecordFieldValQuot
----------------------------------------------------------------------------*/
char* BC_TQRRecordFieldValQuot::Execute(char* istr)
{
itxString tqrname;
itxString colname;
itxString appo;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &colname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output = m_pTQRCollection->GetCurrentRecordField(tqrname.GetBuffer(), colname.GetBuffer());
if( m_Output.IsNull() || m_Output.IsEmpty() )
{
m_pParser->PickPar(istr, 3, &m_Output);
}
else
{
m_Output.AdjustStr();
m_Output.SubstituteSubString("\"", "\"\"");
appo = '\'';
appo += m_Output;
appo += '\'';
m_Output = appo;
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_CycleTQR
----------------------------------------------------------------------------*/
/*
attivita' :definisce il punto di partenza di un ciclo che viene effettuato sui record
del TQR specificato. Il comando di fine ciclo, necessario pena un
comportamento imprevedibile del template, � *endcycle(TQRName).
TQRName : nome del tqr;
*/
char* BC_CycleTQR::Execute(char* istr)
{
itxString queryName;
if (m_pParser->GetCycleBlock(-1) == 0)
{
m_pParser->SetCycleBlock(0);
return NULL;
}
if(m_pParser->PickPar(istr, 1, &queryName) == PARAM_NOT_FOUND)
{
DebugTrace2(IN_WARNING, "Parameter not found in cycle command.\n");
return PARAM_NOT_FOUND_MSG;
}
TQR* tqr = (TQR*) m_pParser->GetCycleBlock(0);
if (!ISVALIDPTR(tqr))
{
if ((tqr = m_pTQRCollection->Retrieve(queryName.GetBuffer())) == NULL)
{
DebugTrace2(IN_COMMAND, "Cannot find TQR named '%s'.\n", queryName.GetBuffer());
m_pParser->SetCycleBlock(0);
return NULL;
}
}
if (tqr->GetTotalRows() != 0)
{
if (tqr->GetCurrentRecord() != NULL)
m_pParser->SetCycleBlock((int)tqr);
else
m_pParser->SetCycleBlock(0);
}
else
{
m_pParser->SetCycleBlock(0);
DebugTrace2(IN_COMMAND, "TQR '%s' is empty.\n", tqr->GetName().GetBuffer());
}
return NULL;
}
/*----------------------------------------------------------------------------
BC_EndCycleTQR
----------------------------------------------------------------------------*/
char* BC_EndCycleTQR::Execute(char* istr)
{
TQR* tqr = (TQR*) m_pParser->GetCycleBlock(0);
if (ISVALIDPTR(tqr))
m_pTQRCollection->MoveNext(tqr);
return NULL;
}
/*----------------------------------------------------------------------------
BC_CycleFor
----------------------------------------------------------------------------*/
/*
attivita' : definisce il punto d'entrata di un ciclo for:
la variabile counter, il valore iniziale, il valore finale e lo step
*/
char* BC_CycleFor::Execute(char* istr)
{
itxString counter;
itxString tqrname;
int initialvalue, finalvalue, step;
TQR* tqr;
if(m_pParser->PickPar(istr, 1, &counter) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &initialvalue) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &finalvalue) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 4, &step) == PARAM_NOT_FOUND)
step = 1;
tqrname = TQR_FOR_PREFIX;
tqrname += counter;
tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer());
// se il TQR* associato al counter � NULL, allora devo comunque creare il tqr
if (tqr == NULL)
{
tqr = m_pTQRManager->CreateTQR(tqrname.GetBuffer(), 1);
m_pTQRManager->SetColumnAttributes(tqr, 0, counter.GetBuffer(), 0, 10);
itxString icounter;
if (step > 0)
for (int i = initialvalue; i <= finalvalue; i += step)
{
icounter.SetInt(i);
m_pTQRManager->AddTail(tqr);
m_pTQRManager->SetCurrentRecordField(tqr, counter.GetBuffer(), icounter.GetBuffer());
}
else
for (int i = initialvalue; i >= finalvalue; i += step)
{
icounter.SetInt(i);
m_pTQRManager->AddTail(tqr);
m_pTQRManager->SetCurrentRecordField(tqr, counter.GetBuffer(), icounter.GetBuffer());
}
m_pTQRManager->MoveFirst(tqr);
}
if (m_pParser->GetCycleBlock(-1) == 0)
m_pParser->SetCycleBlock(0);
else
{
if (tqr == NULL)
m_pParser->SetCycleBlock(0);
else if (tqr->GetCurrentRecord() != NULL)
m_pParser->SetCycleBlock(1);
else
m_pParser->SetCycleBlock(0);
}
// riposizionamento ad inizio TQR in caso di esaurimento dei cicli
if (tqr != NULL && m_pParser->GetCycleBlock() == 0)
m_pTQRCollection->Remove(tqrname.GetBuffer());
return NULL;
}
/*----------------------------------------------------------------------------
BC_EndCycleFor
----------------------------------------------------------------------------*/
char* BC_EndCycleFor::Execute(char* istr)
{
itxString counter;
itxString tqrname;
if(m_pParser->PickPar(istr, 1, &counter) == PARAM_NOT_FOUND)
{
DebugTrace2(IN_WARNING, "endfor needs argument.\n");
m_pParser->m_ForceExit = 1;
return PARAM_NOT_FOUND_MSG;
}
tqrname = TQR_FOR_PREFIX;
tqrname += istr;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer())) != NULL)
m_pTQRCollection->MoveNext(tqr);
return NULL;
}
/*----------------------------------------------------------------------------
BC_ForIndex
----------------------------------------------------------------------------*/
char* BC_ForIndex::Execute(char* istr)
{
itxString tqrname;
m_Output.SetEmpty();
tqrname = TQR_FOR_PREFIX;
tqrname += istr;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer())) != NULL)
m_Output = tqr->GetCurrentRecord()->FieldValue(0);
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_ExitOnFile
----------------------------------------------------------------------------*/
/*
attivita' :interrompe il processing e forza Tannit verso l'uscita.
*/
char* BC_Exit::Execute(char* istr)
{
m_pParser->m_ForceExit = 1;
return NULL;
}
/*----------------------------------------------------------------------------
BC_TQRExist
----------------------------------------------------------------------------*/
char* BC_TQRExist::Execute(char* istr)
{
itxString tqrname;
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer())) != NULL)
m_Output = TANNIT_TRUE;
else
m_Output = TANNIT_FALSE;
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_Valid
----------------------------------------------------------------------------*/
/*
attivita' :autorizzazione utenti, fa uso della tabella del database specificata nel
file dei parametri al valore logintable.
- login : identificatore dell'utente candidato alla autenticazione;
viene usato per selezionare il record uguagliandolo al campo
specificato nel file di inizializzazione nel parametro loginfield
- pwd : <PASSWORD>azione;
viene usata per convalidare il record selezionato dal campo login
uguagliandola al valore del campo specificato nel file di
inizializzazione nel parametro pwdfield
- extraField: campo addizionale della tabella;
- extraVal : valore del campo addizionale da verificare se specificato
*/
char* BC_Valid::Execute(char* istr)
{
itxString loginSt;
itxString passwd;
itxString extraField;
itxString extraVal;
itxString retMsg;
int validated = 0;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &loginSt) == PARAM_NOT_FOUND ||
m_pParser->PickPar(istr, 2, &passwd) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &extraField) == PARAM_NOT_FOUND)
extraField = "1";
if(m_pParser->PickPar(istr, 4, &extraVal) == PARAM_NOT_FOUND)
extraVal = "1";
// Controllo che la password nel DB sia la stessa di input
validated = CheckDbPwd(&loginSt, &passwd, &extraField, &extraVal, &retMsg);
DebugTrace2(IN_COMMAND, "%s\n", retMsg.GetBuffer());
if (validated == 0)
{
itxString tpldir;
itxString tplName;
tplName = INVALID_LOGIN_FILE;
m_pCGIRes->m_PRMFile.GetPRMValue(TPLDIR, &tpldir);
//Parser is now redirected on the login error template
//and after that, forced to pop the current (unvalidated) template.
m_pParser->Run(&tpldir, &tplName);
m_pParser->m_ForceReturn = 1;
}
return m_Output.GetBuffer();
}
/*
attivita' :confronta la password nel database con la password di input;
l'utente del comando DEVE sapere se su db la pwd e` criptata
oppure no, e passare al comando un valore criptato, oppure no.
return :il numero di caratteri presi
chiamante :lo stato di validazione
*/
int BC_Valid::CheckDbPwd(itxString* login,
itxString* pwd,
itxString* extraField,
itxString* extraVal,
itxString* retMsg)
{
itxString queryString;
itxString appo;
itxString logintable;
itxString pwdcolname;
char* temp_tqr_name = "validation_tqr";
char* dbPwd;
int ret = 0;
queryString += "SELECT ";
m_pCGIRes->m_PRMFile.GetPRMValue("pwdfield", &appo);
pwdcolname = appo;
queryString += appo;
queryString += " FROM ";
m_pCGIRes->m_PRMFile.GetPRMValue("logintable", &appo);
logintable = appo;
queryString += appo;
queryString += " WHERE ";
m_pCGIRes->m_PRMFile.GetPRMValue("loginfield", &appo);
queryString += appo;
queryString += " = ";
if (login->FindSubString("'") < 0 && LoginWantsQuotes(&logintable, &appo))
{
queryString += "'";
queryString += *login;
queryString += "'";
}
else
queryString += *login;
queryString += " AND ";
queryString += *extraField;
queryString += " = ";
queryString += *extraVal;
DebugTrace2(IN_COMMAND, "%s\n", queryString.GetBuffer());
// Connessione al DB e acquisizione del valore della password
if (m_pTQRODBCManager->Execute(temp_tqr_name, queryString.GetBuffer()) == ITXFAILED)
return 0;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(temp_tqr_name)) != NULL)
{
dbPwd = m_pTQRCollection->GetCurrentRecordField(temp_tqr_name, pwdcolname.GetBuffer());
if(dbPwd == NULL || strcmp(dbPwd, "") == 0)
{
DebugTrace2(IN_COMMAND, "Password field value is null or empty.");
*retMsg = ERR_COL_NOT_FOUND;
}
}
else
{
DebugTrace2(IN_COMMAND | IN_ERROR, "Internal tqr not found.");
*retMsg = ERR_QUERY_NOT_FOUND;
}
if (pwd->Compare(dbPwd) == 0)
{
ret = 1;
DebugTrace2(IN_COMMAND, "Current login has been validated.\n");
}
else
DebugTrace2(IN_COMMAND, "Current login has NOT been validated.\n");
m_pTQRCollection->Remove(temp_tqr_name);
return ret;
}
bool BC_Valid::LoginWantsQuotes(itxString* logintable, itxString* loginfield)
{
char* info_tqr_name = "info_tqr";
itxString inquiry;
bool ret = false;
try
{
inquiry = "SELECT * FROM ";
inquiry += *logintable;
m_pTQRODBCManager->Inquiry(info_tqr_name, inquiry.GetBuffer());
TQR* tqrinfo;
if ((tqrinfo = m_pTQRCollection->Retrieve(info_tqr_name)) != NULL)
{
if (!m_pTQRODBCManager->IsNumeric(tqrinfo, loginfield->GetBuffer()))
ret = true;
m_pTQRCollection->Remove(info_tqr_name);
}
}
catch(...)
{
DebugTrace2(IN_COMMAND | IN_ERROR, "%s\n", "Unhandled exception in BC_Valid::LoginWantsQuotes.");
throw;
}
return ret;
}
/*----------------------------------------------------------------------------
BC_Crypt
----------------------------------------------------------------------------*/
char* BC_Crypt::Execute(char* istr)
{
itxString toBeCrypted;
unsigned char key[64] = CRYPT_KEY;
unsigned char wht[64] = CRYPT_WHT;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &toBeCrypted) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output.Space(10 * toBeCrypted.Len() * sizeof(char), 0);
itxEncrypt(&key[0], &wht[0], (unsigned char*)toBeCrypted.GetBuffer(), (unsigned char*)m_Output.GetBuffer());
return m_Output.GetBuffer();
}
/*
// (in) source string must be null terminated
// (out) the destination string is the hex representation of the ascii values of the
// characters of the crypted string
*/
unsigned short BC_Crypt::itxEncrypt(unsigned char* DESKey, unsigned char* Whitenings,
unsigned char* source, unsigned char* destination)
{
struct DESXKey dxKey;
struct DESXContext dxCon;
unsigned char blok[ITX_DES_BLOK];
unsigned char* sourcepos = source;
unsigned char* destinpos = destination;
int sourcelen = 0;
int iblok, nbloks = 0, residual = 0;
itxString appo;
memcpy(dxKey.DESKey64, DESKey, ITX_DES_BLOK);
memcpy(dxKey.Whitening64, Whitenings, ITX_DES_BLOK);
DESXKeySetup(&dxCon, &dxKey);
sourcelen = strlen((char*) source);
nbloks = sourcelen / ITX_DES_BLOK;
residual = sourcelen % ITX_DES_BLOK;
for (iblok = 0; iblok < nbloks; iblok++)
{
memcpy(blok, source + iblok * ITX_DES_BLOK, ITX_DES_BLOK);
DESXEncryptBlock(&dxCon, blok, blok);
appo.HexToAscii((char*) blok, (char*) (destination + 2 * iblok * ITX_DES_BLOK), ITX_DES_BLOK);
}
if (residual != 0)
{
/* blanks added on tail to obtain well formed DES_BLOK */
memset(blok, ' ', ITX_DES_BLOK);
memcpy(blok, source + iblok * ITX_DES_BLOK, residual);
DESXEncryptBlock(&dxCon, blok, blok);
appo.HexToAscii((char*) blok, (char*) (destination + 2 * iblok * ITX_DES_BLOK), ITX_DES_BLOK);
}
/* make destination null-terminated */
*(destination + 2 * (iblok + 1) * ITX_DES_BLOK) = 0;
return 0;
}
/*----------------------------------------------------------------------------
BC_Decrypt
----------------------------------------------------------------------------*/
char* BC_Decrypt::Execute(char* istr)
{
itxString toBeDecr;
unsigned char key[64] = CRYPT_KEY;
unsigned char wht[64] = CRYPT_WHT;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &toBeDecr) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output.Space(toBeDecr.Len() * sizeof(char), 0);
itxDecrypt(&key[0], &wht[0], (unsigned char*)toBeDecr.GetBuffer(), (unsigned char*)m_Output.GetBuffer());
return m_Output.GetBuffer();
}
/*
// (in) source string must be the hex representation of the ascii values of the
// characters of the crypted string
*/
unsigned short BC_Decrypt::itxDecrypt(unsigned char* DESKey, unsigned char* Whitenings,
unsigned char* source, unsigned char* destination)
{
struct DESXKey dxKey;
struct DESXContext dxCon;
unsigned char blok[ITX_DES_BLOK];
unsigned char* sourcepos = source;
unsigned char* destinpos = destination;
int sourcelen = 0;
int iblok, nbloks = 0, i = 0;
itxString appo;
memcpy(dxKey.DESKey64, DESKey, ITX_DES_BLOK);
memcpy(dxKey.Whitening64, Whitenings, ITX_DES_BLOK);
DESXKeySetup(&dxCon, &dxKey);
sourcelen = strlen((char*) source);
nbloks = sourcelen / (ITX_DES_BLOK * 2);
appo.AsciiToHex((char*) source, (char*) source, sourcelen / 2);
for (iblok = 0; iblok < nbloks; iblok++)
{
memcpy(blok, source + iblok * ITX_DES_BLOK, ITX_DES_BLOK);
DESXDecryptBlock(&dxCon, blok, blok);
memcpy(destination + iblok * ITX_DES_BLOK, blok, ITX_DES_BLOK);
}
*(destination + iblok * ITX_DES_BLOK) = 0;
/* eventually trims the blanks added on tail */
i = 0;
while ((*(destination + iblok * ITX_DES_BLOK + i - 1)) == ' ')
{
*(destination + iblok * ITX_DES_BLOK + i - 1) = 0;
i--;
}
return 0;
}
/*----------------------------------------------------------------------------
BC_RemoveTQR
----------------------------------------------------------------------------*/
char* BC_RemoveTQR::Execute(char* istr)
{
itxString tqrname;
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_pTQRCollection->Remove(tqrname.GetBuffer());
return NULL;
}
/*----------------------------------------------------------------------------
BC_TQRStat
----------------------------------------------------------------------------*/
char* BC_TQRStat::Execute(char* istr)
{
itxString tqrname;
itxString stat;
m_Output.Space(GET_PAR_VAL_LEN, '\0');
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &stat) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
int icol;
if(m_pParser->PickInt(istr, 3, &icol) == PARAM_NOT_FOUND)
icol = -1;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer())) != NULL)
{
if (stat.Compare(TOTRECS) == 0)
m_Output.SetInt(tqr->GetTotalRows());
else if (stat.Compare(ACTUALROW) == 0)
m_Output.SetInt(tqr->GetActualRow());
else if (stat.Compare(ROWSTOSTORE) == 0)
m_Output.SetInt(tqr->GetRowsToStore());
else if (stat.Compare(STARTINGROW) == 0)
m_Output.SetInt(tqr->GetStartingRow());
else if (stat.Compare(MORERECS) == 0)
{
if (tqr->GetMoreDBRows())
return TANNIT_TRUE;
else
return TANNIT_FALSE;
}
else if (stat.Compare(SOURCECOUNT) == 0)
m_Output.SetInt(tqr->GetSourceRecordCount());
else if (stat.Compare(ACTUALPAGE) == 0)
m_Output.SetInt(tqr->GetActualPage());
else if (stat.Compare(TOTALPAGES) == 0)
m_Output.SetInt(tqr->GetTotalPages());
else if (stat.Compare(LASTPAGEROW) == 0)
m_Output.SetInt(tqr->GetLastPageRow());
else if (stat.Compare(NEXTPAGEROW) == 0)
m_Output.SetInt(tqr->GetNextPageRow());
else if (stat.Compare(PREVPAGEROW) == 0)
m_Output.SetInt(tqr->GetPrevPageRow());
else if (stat.Compare(COLCOUNT) == 0) //TQR info: column count
m_Output.SetInt(tqr->GetColsNum());
else if (stat.Compare(COLNAME) == 0) //TQR info: column name
m_Output = tqr->GetColName(icol);
else if (stat.Compare(COLTYPE) == 0) //TQR info: column type
m_Output.SetInt(tqr->GetColType(icol));
else if (stat.Compare(COLSIZE) == 0) //TQR info: column size
m_Output.SetInt(tqr->GetColSize(icol));
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
Return
----------------------------------------------------------------------------*/
char* BC_Return::Execute(char* istr)
{
m_pParser->m_ForceReturn = 1;
return NULL;
}
/*----------------------------------------------------------------------------
Flush
----------------------------------------------------------------------------*/
char* BC_Flush::Execute(char* istr)
{
TemplateFile* ptpl = NULL;
try
{
m_pParser->m_TplStack.SetCursorBottom();
TemplateFile* ptpl = (TemplateFile*)m_pParser->m_TplStack.Bottom();
while(ptpl != NULL)
{
m_pCGIRes->Flush(ptpl->m_Output.GetBuffer());
ptpl->m_Output.SetEmpty();
ptpl = (TemplateFile*)m_pParser->m_TplStack.NextUp();
}
}
catch(...)
{
DebugTrace2(IN_COMMAND | IN_ERROR, "BC_Flush::Execute: ptpl = %p", ptpl);
itxString appo;
ptpl->GetContent(&appo);
DebugTrace2(IN_COMMAND | IN_ERROR, "BC_Flush::Execute:\n%s", appo.GetBuffer());
}
return NULL;
}
/*----------------------------------------------------------------------------
BC_TQRMove
----------------------------------------------------------------------------*/
char* BC_TQRMove::Execute(char* istr)
{
itxString tqrname;
itxString action;
int row;
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &action) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &row) == PARAM_NOT_FOUND)
row = 0;
TQR* tqr;
if ((tqr = m_pTQRCollection->Retrieve(tqrname.GetBuffer())) != NULL)
{
if (action.Compare(FIRST) == 0)
tqr->MoveFirst();
else if (action.Compare(LAST) == 0)
tqr->MoveLast();
else if (action.Compare(NEXT) == 0)
tqr->MoveNext();
else if (action.Compare(TO) == 0)
tqr->MoveTo(row);
}
return NULL;
}
/*----------------------------------------------------------------------------
BC_TQRFilt
----------------------------------------------------------------------------*/
char* BC_TQRFilt::Execute(char* istr)
{
itxString source;
itxString field;
itxString value;
itxString destination;
if(m_pParser->PickPar(istr, 1, &source) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &field) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &value) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 4, &destination) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
TQR* tqr;
tqr = m_pTQRManager->Filter(source.GetBuffer(),
field.GetBuffer(),
value.GetBuffer(),
destination.GetBuffer());
if (tqr == NULL)
DebugTrace2(IN_COMMAND, "Unable to filter tqr %s\n", source.GetBuffer());
return NULL;
}
/*----------------------------------------------------------------------------
BC_TQRSample
----------------------------------------------------------------------------*/
char* BC_TQRSample::Execute(char* istr)
{
itxString source;
itxString destination;
int destMaxRecs, seed;
if(m_pParser->PickPar(istr, 1, &source) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &destination) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &destMaxRecs) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 4, &seed) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
TQR* tqr;
tqr = m_pTQRManager->Sample(source.GetBuffer(),
destination.GetBuffer(),
destMaxRecs,
seed);
if (tqr == NULL)
DebugTrace2(IN_COMMAND, "Unable to sample tqr %s\n", source.GetBuffer());
return NULL;
}
/*----------------------------------------------------------------------------
BC_Recsel
----------------------------------------------------------------------------*/
/*
attivita' :analogo a recVal restituisce il valore del campo specificato per il record
corrente del resultset specificato; aggiunge la stringa " SELECTED" se il
dato e' uguale al dato determinato dalla seconda coppia di parametri
par 1 :nome del resultset da identificare
par 2 :nome del campo
par 3 :nome del resultset da identificare per il confronto; se il nome e' "get"
il dato di confronto viene cercato nella stringa di get
par 4 :nome del campo da utilizzare per il confronto
*/
char* BC_Recsel::Execute(char* istr)
{
itxString queryName;
itxString queryField;
itxString cnfField;
itxString cnfSrc;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &queryName) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &queryField) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 3, &cnfSrc) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 4, &cnfField) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
itxString firstVal;
itxString secVal;
firstVal = m_pTQRCollection->GetCurrentRecordField(queryName.GetBuffer(), queryField.GetBuffer());
if (firstVal.IsEmpty())
return " ";
if (cnfSrc.Compare("get") == 0)
{
if (m_pCGIRes->cgiFormString(cnfField.GetBuffer(), &secVal, 0) != cgiFormSuccess)
secVal = GET_PAR_VAL; //valore di default generico
}
else
secVal = m_pTQRCollection->GetCurrentRecordField(cnfSrc.GetBuffer(), cnfField.GetBuffer());
m_Output = firstVal;
if (firstVal.Compare(&secVal) == 0)
m_Output += " SELECTED";
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_Trans
----------------------------------------------------------------------------*/
/*
attivita' :traduce la phraseTag nella lingua corrente. Fa uso dei parametri
LangTable, LangNameField, LangCodeField del file di inizializzazione per
definire tabella dei linguaggi, campo del nome della lingua, campo del
codice della lingua. Ricava il valore del campo LangNameField per il record
in cui il campo LangCodeField corrisponde al valore del parametro di get
identificato dal valore del parametro LangTagGet del file di inizializzazione.
Il nome del campo della lingua � quello da estrarre dalla tabella delle
traduzioni (definita dal parametro TransTable nell'file di inizializzazione)
in corrispondenza del valore del campo TransTagField (sempre nel file dei
parametri) che uguaglia la stringa di input del comando phraseTag.
OPZforceLang, � un parametro che forza la lingua al valore specificato.
*/
char* BC_Trans::Execute(char* istr)
{
itxString translatedPhrase;
itxString phraseTag;
itxString forceLang;
itxString queryString;
itxString userlang;
itxString langName;
itxString LangTable; //PRM
itxString LangTagGet; //PRM
itxString LangCodeField; //PRM
itxString DefaultLanguageId; //PRM
itxString LangNameField; //PRM
itxString TransTable; //PRM
itxString TransTagField; //PRM
char* temp_tqr_name = "trans_tqr";
TQR* tqr;
m_Output.SetEmpty();
//Parse input string
if(m_pParser->PickPar(istr, 1, &phraseTag) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &forceLang) == PARAM_NOT_FOUND)
forceLang.SetEmpty();
//Push on the stack of this functions needed prm variables.
LangTable.SetEmpty();
LangTagGet.SetEmpty();
LangCodeField.SetEmpty();
DefaultLanguageId.SetEmpty();
LangNameField.SetEmpty();
TransTable.SetEmpty();
TransTagField.SetEmpty();
m_pCGIRes->m_PRMFile.GetPRMValue("LangTable", &LangTable);
m_pCGIRes->m_PRMFile.GetPRMValue("LangTagGet", &LangTagGet);
m_pCGIRes->m_PRMFile.GetPRMValue("LangCodeField", &LangCodeField);
m_pCGIRes->m_PRMFile.GetPRMValue("LangNameField", &LangNameField);
m_pCGIRes->m_PRMFile.GetPRMValue("DefaultLanguageId", &DefaultLanguageId);
m_pCGIRes->m_PRMFile.GetPRMValue("TransTable", &TransTable);
m_pCGIRes->m_PRMFile.GetPRMValue("TransTagField", &TransTagField);
if (LangTable.IsEmpty() || LangTagGet.IsEmpty() || LangCodeField.IsEmpty() ||
DefaultLanguageId.IsEmpty() || LangNameField.IsEmpty() || LangTable.IsEmpty() ||
LangCodeField.IsEmpty() || TransTable.IsEmpty() || TransTagField.IsEmpty())
{
DebugTrace2(IN_COMMAND, "Empty prm variables found.");
return NULL;
}
//Get from http get string the value of the current language
if (!forceLang.IsEmpty())
userlang = forceLang;
else
{
userlang.SetEmpty();
if (m_pCGIRes->cgiFormString(LangTagGet.GetBuffer(), &userlang, 0) != cgiFormSuccess)
userlang = DefaultLanguageId;
}
//Query the name of the language to use as field name in the translator table
queryString = "SELECT ";
queryString += LangNameField;
queryString += " FROM ";
queryString += LangTable;
queryString += " WHERE ";
queryString += LangCodeField;
queryString += " = ";
queryString += userlang;
if (m_pTQRODBCManager->Execute(temp_tqr_name, queryString.GetBuffer()) == ITXFAILED)
return NULL;
if ((tqr = m_pTQRCollection->Retrieve(temp_tqr_name)) != NULL)
{
langName = m_pTQRCollection->GetCurrentRecordField(temp_tqr_name, LangNameField.GetBuffer());
if(langName.IsNull() || langName.IsEmpty())
DebugTrace2(IN_COMMAND, "Language name field value is null or empty.");
//can safely remove the tqr becasue langName is an itxString
m_pTQRCollection->Remove(temp_tqr_name);
}
else
DebugTrace2(IN_COMMAND | IN_ERROR, "Internal tqr not found.");
//Query the value of the translation
queryString = temp_tqr_name;
queryString += ", SELECT ";
queryString += langName;
queryString += " FROM ";
queryString += TransTable;
queryString += " WHERE ";
queryString += TransTagField;
queryString += " = '";
queryString += phraseTag;
queryString += "'";
BC_ODBCExecuteQuery::Execute(queryString.GetBuffer());
if ((tqr = m_pTQRCollection->Retrieve(temp_tqr_name)) != NULL)
{
m_Output = m_pTQRCollection->GetCurrentRecordField(temp_tqr_name, langName.GetBuffer());
if(m_Output.IsNull() || m_Output.IsEmpty())
DebugTrace2(IN_COMMAND, "Language name field value is null or empty.");
m_pTQRCollection->Remove(temp_tqr_name);
}
else
DebugTrace2(IN_COMMAND | IN_ERROR, "Internal tqr not found.");
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
TQRStore
----------------------------------------------------------------------------*/
char* BC_TQRStore::Execute(char* istr)
{
itxString tqrname;
int nfields;
itxString sep;
itxString buffer;
char fieldsep, recsep;
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &nfields) == PARAM_NOT_FOUND)
nfields = 0;
if(m_pParser->PickPar(istr, 3, &sep) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 4, &buffer) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
buffer.InBlinder('\x27');
char* psep = sep.GetBuffer();
fieldsep = psep[0];
recsep = psep[1];
m_pTQRManager->LoadDataBuffer(tqrname.GetBuffer(), nfields, recsep, fieldsep, buffer.GetBuffer());
m_pTQRManager->MoveFirst(m_pTQRManager->Get(tqrname.GetBuffer()));
return 0;
};
/*----------------------------------------------------------------------------
TQRInsert
----------------------------------------------------------------------------*/
char* BC_TQRInsert::Execute(char* istr)
{
itxString tqrname;
itxString tablename;
if(m_pParser->PickPar(istr, 1, &tqrname) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &tablename) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_pTQRODBCManager->BulkInsert(tablename.GetBuffer(), tqrname.GetBuffer(), NULL);
return 0;
};
/*----------------------------------------------------------------------------
Pager
----------------------------------------------------------------------------*/
char* BC_Pager::Execute(char* istr)
{
itxString tqrSrcName;
itxString tqrDstName;
int pagesToShow;
if(m_pParser->PickPar(istr, 1, &tqrSrcName) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &pagesToShow) == PARAM_NOT_FOUND)
pagesToShow = 10;
TQR* tqrSrc;
TQR* tqrDst;
if((tqrSrc = m_pTQRManager->Get(tqrSrcName.GetBuffer())) == NULL)
{
DebugTrace2(IN_COMMAND, "Cannot find TQR named '%s'.\n", tqrSrcName.GetBuffer());
return 0;
}
tqrDstName = tqrSrcName;
tqrDstName += "_pg";
tqrDst = m_pTQRManager->CreateTQR(tqrDstName.GetBuffer(), 2);
tqrDst->SetColumnAttributes(0, "pagenum", 0, 10);
tqrDst->SetColumnAttributes(1, "startrow", 0, 10);
m_pTQRManager->SetRowsParam(tqrDst, 1, pagesToShow, 1, 0);
itxString buff;
int sourceTotPages = tqrSrc->GetTotalPages();
for(int i = 1; i <= pagesToShow && i <= sourceTotPages; i++)
{
buff.SetInt(i);
tqrDst->AddTail();
tqrDst->SetCurrentRecordField(0, buff.GetBuffer());
buff.SetInt((tqrSrc->GetRowsToStore() * (i - 1)) + 1);
tqrDst->SetCurrentRecordField(1, buff.GetBuffer());
}
tqrDst->MoveFirst();
return 0;
}
/*----------------------------------------------------------------------------
Netprex
----------------------------------------------------------------------------*/
char* BC_Netprex::Execute(char* istr)
{
itxString url;
itxString cmd_tag;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &url) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &cmd_tag) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
try
{
itxHttp connection("Thunder v 1.45");
connection.GET(url.GetBuffer());
m_Output = connection.GetDataReceived();
char oldtag = m_pParser->m_StartCommandTag;
m_pParser->m_StartCommandTag = cmd_tag.GetAt(0);
m_pParser->Run(m_Output.GetBuffer());
m_pParser->m_StartCommandTag = oldtag;
}
catch(itxException* e)
{
DebugTrace2(IN_COMMAND, "ITX_EXCEPTION: %d '%s'.\n", e->m_errornumber, e->m_procedure);
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Netprex generic exception\n");
}
return NULL;
}
/*----------------------------------------------------------------------------
NetGrab
----------------------------------------------------------------------------*/
char* BC_Netgrab::Execute(char* istr)
{
itxString url;
int maxbytes;
int maxsecs;
itxString to;
char *myBuffer;
FILE *fdto;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &url) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &maxbytes) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &maxsecs) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
try
{
itxHttp connection("Thunder v 1.45");
myBuffer = (char *) calloc(maxbytes, sizeof(char));
int datalen = connection.GETBin(url.GetBuffer(), &myBuffer, maxbytes, 4096, maxsecs);
if(m_pParser->PickPar(istr, 4, &to) != PARAM_NOT_FOUND)
{
to.InBlinder('"');
fdto = fopen(to.GetBuffer(),"wb");
if (fdto)
fwrite(myBuffer, sizeof(char), datalen, fdto);
fclose(fdto);
}
free(myBuffer);
if (datalen > 0)
sprintf(m_Output.GetBuffer(),"%d", datalen);
}
catch(itxException* e)
{
DebugTrace2(IN_COMMAND, "ITX_EXCEPTION: %d '%s'.\n", e->m_errornumber, e->m_procedure);
}
catch(...)
{
DebugTrace2(IN_COMMAND, "NetGrab generic exception\n");
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
Proc
----------------------------------------------------------------------------*/
char* BC_Proc::Execute(char* istr)
{
itxString buffer;
itxString cmd_tag;
m_Output.SetEmpty();
m_pCGIRes->m_PRMFile.GetPRMValue("ForceProcCmdTag", &cmd_tag);
if (cmd_tag.IsEmpty())
{
if(m_pParser->PickPar(istr, 1, &buffer) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickPar(istr, 2, &cmd_tag) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
buffer.InBlinder('\"');
}
else
{
buffer = istr;
}
try
{
char oldtag = m_pParser->m_StartCommandTag;
m_pParser->m_StartCommandTag = cmd_tag.GetAt(0);
m_pParser->Run(buffer.GetBuffer());
m_pParser->m_StartCommandTag = oldtag;
}
catch(...)
{
DebugTrace2(IN_COMMAND, "Proc generic exception\n");
}
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_GetValueQuote
----------------------------------------------------------------------------*/
/*
attivita' :restituisce il valore del parametro di get indicato e sostituisce
nella stringa risultante i caratteri apice con i doppio apice
- parametro: nome del parametro di get di cui restituire il valore
- OPZdefault: valore di default ritornato nel caso non si trovi il
parametro.
N.B. se OPZdefault � il carattere '+' il valore
ricavato per il parametro viene modificato sostituendo tutti
i caratteri non alfanumerici con la stringa %xx dove xx �
il valore ascii esadecimale del carattere sostituito.
*/
char* BC_GetValueQuote::Execute(char* istr)
{
itxString defParVal;
itxString getParName;
int useDefault = 0;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &getParName) == PARAM_NOT_FOUND)
{
m_Output = PARAM_NOT_FOUND_MSG;
return m_Output.GetBuffer();
}
if (m_pParser->PickPar(istr, 2, &defParVal) == PARAM_FOUND)
useDefault = 1;
if (m_pCGIRes->cgiFormString(getParName.GetBuffer(), &m_Output, 0) != cgiFormSuccess)
{
if (useDefault) // valore opzionale di default definito dall'utente
m_Output = defParVal;
else // valore di default generico
m_Output = GET_PAR_VAL;
}
if (!defParVal.IsNull() && strcmp(defParVal.GetBuffer(), "+") == 0)
{
if(!m_Output.IsNull() && strcmp(m_Output.GetBuffer(), "+") == 0)
m_Output = "";
m_Output.EscapeChars();
}
m_Output.AdjustStr();
m_Output.SubstituteSubString("\"", "\"\"");
return m_Output.GetBuffer();
}
/*----------------------------------------------------------------------------
BC_GetValueCast
----------------------------------------------------------------------------*/
/*
attivita' : restituisce il valore del parametro di get indicato e trasformando
la stringa di input nel formato richiesto
*/
char* BC_GetValueCast::Execute(char* istr)
{
itxString defParVal;
itxString outputFormatIndicator;
itxString getParName;
char *mySource;
char *mySourceCrs;
char *myDestin;
char *myDestinCrs;
int useDefault = 0;
int dotsNumber = 0;
FormResultType_t formReadStatus;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &outputFormatIndicator) == PARAM_NOT_FOUND)
{
m_Output = PARAM_NOT_FOUND_MSG;
return m_Output.GetBuffer();
}
if (m_pParser->PickPar(istr, 2, &getParName) == PARAM_NOT_FOUND)
{
m_Output = PARAM_NOT_FOUND_MSG;
return m_Output.GetBuffer();
}
if (m_pParser->PickPar(istr, 3, &defParVal) == PARAM_FOUND)
useDefault = 1;
formReadStatus = m_pCGIRes->cgiFormString(getParName.GetBuffer(), &m_Output, 0);
if(strcmp(outputFormatIndicator.GetBuffer(), "q") == 0)
{
m_Output.AdjustStr();
m_Output.SubstituteSubString("\"", "\"\"");
}
else if(strcmp(outputFormatIndicator.GetBuffer(), "num") == 0)
{
mySource = (char *) calloc(m_Output.Len(), sizeof(char));
myDestin = (char *) calloc(m_Output.Len()+1, sizeof(char));
strcpy(mySource, m_Output.GetBuffer());
mySourceCrs = mySource;
myDestinCrs = myDestin;
dotsNumber = 0;
while(*mySourceCrs != 0)
{
if(isdigit(*mySourceCrs) == 0)
{
if((*mySourceCrs == ',') || (*mySourceCrs == '.'))
{
if(dotsNumber == 0)
{
*myDestinCrs = '.';
}
else
{
myDestinCrs--;
}
dotsNumber++;
}
else
{
myDestinCrs--;
}
}
else
{
*myDestinCrs = *mySourceCrs;
}
myDestinCrs++;
mySourceCrs++;
}
if (mySource)
free(mySource);
if (myDestin)
{
m_Output = myDestin;
free(myDestin);
}
}
if ((formReadStatus != cgiFormSuccess) || m_Output.IsEmpty())
{
if (useDefault) // valore opzionale di default definito dall'utente
m_Output = defParVal;
else // valore di default generico
m_Output = GET_PAR_VAL;
}
if (!defParVal.IsNull() && strcmp(defParVal.GetBuffer(), "+") == 0)
{
if(!m_Output.IsNull() && strcmp(m_Output.GetBuffer(), "+") == 0)
m_Output = "";
m_Output.EscapeChars();
}
return m_Output.GetBuffer();
}
char* BC_Currency::Execute(char* istr)
{
int invert = 0;
m_Output.SetEmpty();
if (m_pParser->PickPar(istr, 1, &m_Output) == PARAM_NOT_FOUND)
return 0;
if (m_pParser->PickInt(istr, 2, &invert) == PARAM_NOT_FOUND)
m_Output.Currency();
else
m_Output.Currency(-1);
return m_Output.GetBuffer();
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: teg.h,v $
* $Revision: 1.0 $
* $Author: fabio $
* $Date: 2001-01-09 19:11:09+01 $
*
* Tannit Extension Manager Command Definition
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#include "tnt.h"
#include "itxlib.h"
class teg_header : public AbstractCommand
{
public:
itxString m_Name;
itxString m_Output;
teg_header(char* name) { m_Name = name; }
~teg_header() {}
char* Execute(char* inputstr);
char* GetName(){ return m_Name.GetBuffer(); }
void Deallocate(){}
};
class teg_load : public AbstractCommand
{
public:
itxString m_Name;
teg_load(char* name) { m_Name = name; }
~teg_load() {}
char* Execute(char* inputstr);
char* GetName(){ return m_Name.GetBuffer(); }
void Deallocate(){}
};
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.test.testjtx;
import jtxlib.main.datastruct.Vector;
class testVector
{
final int NELEMS = 10000;
final int REMOVE_NELEMS = 1000;
final int REMOVEIDX = 500;
final int TOTREMOVES = 300;
//----------------------------------------------------------------------------
public void showMethods()
{
Vector v = new Vector(10);
for (int i=0; i<10; i++)
v.addElement((char)('a' + i));
System.out.println("showMethods - initial vector:");
System.out.println(v);
v.removeElement(4);
System.out.println("showMethods - removed object at idx 4 - new vector:");
System.out.println(v);
v.removeElement(v.size());
System.out.println("showMethods - removed object at idx size() - new vector:");
System.out.println(v);
v.removeElement(0);
System.out.println("showMethods - removed object at idx 0 - new vector:");
System.out.println(v);
v.removeElement(v.size()-1);
System.out.println("showMethods - removed object at idx 'size()-1' - new vector:");
System.out.println(v);
v.removeTail();
System.out.println("showMethods - removed tail - new vector:");
System.out.println(v);
v.removeAllElements();
System.out.println("showMethods - removed all - new vector:");
System.out.println(v);
}
//----------------------------------------------------------------------------
public void add_JTXVector()
{
String s = "cico";
Vector v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<NELEMS; j++)
{
v = new Vector(NELEMS);
for (int i=0; i<NELEMS; i++)
v.addElement(s);
}
long curmilliend = System.currentTimeMillis();
System.out.println("add_JTXVector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void add_Vector()
{
String s = "cico";
java.util.Vector<String> v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<NELEMS; j++)
{
v = new java.util.Vector<String>(NELEMS);
for (int i=0; i<NELEMS; i++)
v.addElement(s);
}
long curmilliend = System.currentTimeMillis();
System.out.println("add_Vector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void removeTail_JTXVector()
{
String s = "cico";
Vector v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<NELEMS; j++)
{
v = new Vector(NELEMS);
for (int i=0; i<NELEMS; i++)
v.addElement(s);
for (int i=0; i<NELEMS; i++)
v.removeTail();
}
long curmilliend = System.currentTimeMillis();
System.out.println("removeTail_JTXVector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void removeTail_Vector()
{
String s = "cico";
java.util.Vector<String> v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<NELEMS; j++)
{
v = new java.util.Vector<String>(NELEMS);
for (int i=0; i<NELEMS; i++)
v.addElement(s);
for (int i=NELEMS-1; i>=0; i--)
v.remove(i);
}
long curmilliend = System.currentTimeMillis();
System.out.println("removeTail_Vector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void remove_JTXVector()
{
String s = "cico";
Vector v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<REMOVE_NELEMS; j++)
{
v = new Vector(REMOVE_NELEMS);
for (int i=0; i<REMOVE_NELEMS; i++)
v.addElement(s);
for (int i=0; i<TOTREMOVES; i++)
v.removeElement(REMOVEIDX);
}
long curmilliend = System.currentTimeMillis();
System.out.println("remove_JTXVector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void remove_Vector()
{
String s = "cico";
java.util.Vector<String> v = null;
long curmilli = System.currentTimeMillis();
for (int j=0; j<REMOVE_NELEMS; j++)
{
v = new java.util.Vector<String>(REMOVE_NELEMS);
for (int i=0; i<REMOVE_NELEMS; i++)
v.addElement(s);
for (int i=0; i<TOTREMOVES; i++)
v.removeElement(REMOVEIDX);
}
long curmilliend = System.currentTimeMillis();
System.out.println("remove_Vector: " + (curmilliend - curmilli) + " millis.");
}
//----------------------------------------------------------------------------
public void runTest()
{
showMethods();
// add_JTXVector();
// add_Vector();
// removeTail_JTXVector();
// removeTail_Vector();
remove_JTXVector();
remove_Vector();
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __DEFINES_H__
#define __DEFINES_H__
//Compilation options
//#define MAINT_1 //check if must use dbg
//#define TIMETRACE //check if must print timing stats
#define AITECSA_DISCLAIMER "<!--\r\
This file has been created from the Tannit® 4.0 Application owned, produced and distributed\r\
uniquely by AITECSA S.r.l. This copy of Tannit® 4.0 is intended to run only on machines owned\r\
by explicitly authorized users, owners of a run time license of Tannit® 4.0 product.\r\
Any other use is discouraged and will be persecuted in the terms established by the current laws.\r\
-->\r"
#ifdef _ITX_APPC
#define APPC_MSG "<!-- appc enabled -->\n"
#endif
#ifndef _ITX_APPC
#define APPC_MSG "<!-- appc disabled -->\n"
#endif
#ifdef WIN32
#define PATH_SEPARATOR "\\"
#elif LINUX
#define PATH_SEPARATOR "/"
#endif
// Messaggi per la comunicazione con il client download/upload "Aleph"
#define FILE_UPLOADED 1
#define FILE_DOWNLOADED 2
#define DND_CONFIRMED 3
#define NO_FILE_AVAIL 4
#define LOGIN_SUCCESS 5
#define UNABLE_TO_UPLOAD 1002
#define SERVER_ERROR 1003
#define USER_NOT_ENABLED 1004
#define FATAL_ERROR 1999
#define ALEPH_START_COM "ITX_START_OF_TRASMISSIONS_GOOD_LUCK"
#define ALEPH_END_COM "ITX_END_OF_TRASMISSIONS_RETURNING_CODE"
// chiavi per l'invio e la ricezione di file
#define EXCNG_FILE_TAG "excng"
#define SEND_FILE_GRANT "92"
#define RECEIVE_APPC_FILE_GRANT "93"
#define DND_CONFIRM_GRANT "94"
#define RECEIVE_FILE_GRANT "95"
// Chiavi per la comunicazione con Baal: TntRequestTypes
#define RT_BROWSE 0
#define RT_PREPROC 1
#define RT_PREPROC_ALL 2
#define RT_PREVIEW 3
#define TPL_UPD_COMM_RECV "<html><body bgcolor=#44AAFF><font color=Blue><b>Tpl:"
#define TPL_UPD_COMM_SUCC "<br><Font size=1 color=red>E' il direttore che vi parla: sbaraccate ed andatevene in vacanza</Font></b></BODY></HTML>"
// Errori di interrogazione del database
#define ERR_MSG_LEN 256
#define ERRORS_EDGE 0 // limite superiore per i return che definiscono errori
#define DATA_VALUE_ON_ERROR "itxdbdatadefval"
#define ERR_COL_NOT_FOUND "Error: field not found."
#define ERR_QUERY_NOT_FOUND "Error: query not found."
#define ERR_VOID_QUERY_NAME "Error: unable to read query name."
#define LOGIN_ERROR "Error: login failed."
#define ERR_PARAM_NEEDED "Error: parameter needed."
// Errori di sintassi GASP
#define ERR_REM_BLINDCH "Error: double quotes expected."
#define ERR_OPEN_INI_FILE "Error: prm file not found.\n"
#define ERR_OPEN_TPL_FILE "Error: template not found or empty.\n"
#define PARAMETER_NOT_FOUND "notfound"
#define FIELD_NAME_NOT_FOUND "Error: field name not found in get string"
#define INVALID_LOGIN_FILE "loginerror"
#define PARAM_NOT_FOUND_MSG "ERROR; parameter not found"
#define PAR_NOT_FOUND "paramfileNotFOund"
// Errori generici
#define CRYPTING_ERROR "Crypting Error"
#define MEMERR 23
#define MEMORY_ERROR_MSG "Memory allocation ERROR"
//Messaggi durante il preprocessing
#define PP_STARTED "Now preprocessing...<br>"
#define PP_FINISHED "Preprocess operation completed.<br>"
#define PP_CANT_WRITEOUTPUT "Error while attempting to write on the output file.<br>"
#define PP_IN_OUT_DIRS_EQ "Can't generate output file: preprocess and template directories are the same.<br>"
// Etichette
#define TANNIT_CONFIG_FILE "tannit.conf"
#define BROWSER_OPERA "Opera"
#define BROWSER_MSIE "MS Internet Explorer"
#define BROWSER_NETSCAPE "Netscape Comunicator"
#define ITX_MISINTER "itxmisi"
#define ISEXPLORER "explorer"
#define ISNETSCAPE "netscape"
#define LOGIN_TAG "login"
#define CPWD_TAG "cpwd"
#define BLINDER '"'
#define CONC_LAN_ID_TAG "lid"
#define DEF_PAR_FILE "tannit"
#define DEF_PAR_FILE_EXT "prm"
#define PAR_FILE_TAG "prm"
#define DEFAULT_TPL "tannit"
#define TGT_TAG "tgt"
#define TPL_TAG "tpl"
#define PREPROC_TPL_TAG "preproc"
#define DEBUG_2_VIDEO_TAG "forcedebug"
#define TPL_EXT ".htm"
#define TEG_EXT ".teg"
#define START_COMMAND_TAG '*'
#define PREPROC_COMMAND_TAG '#'
#define TEG_COMMAND_TAG '§' //Tannit Extension Generator
#define CMD_ARG_OPEN_TAG '('
#define CMD_ARG_CLOSE_TAG ')'
#define PARAM_NOT_FOUND 0
#define PARAM_FOUND 1
#define PARAM_NUMBER 128
#define CND_OP_NUM 6
#define GET_PAR_VAL ""
#define REC_VAL_ZERO ""
#define DND_FILE_DONE "2"
#define DND_FILE_READY "1"
#define ITX_UPLOAD_FILE_TAG "itxFile"
#define CORR_UPLOAD_DIR "./itxCrUp/"
#define ITXCOO_SEP "#"
#define TANNIT_TRUE "true"
#define TANNIT_FALSE "false"
#define TNT_COMMENT "$$"
#define LF 0xA
#define CR 0xD
#define TQR_FOR_PREFIX "tqr_"
// Numerici
#define MAX_DSN 32
#define MAX_CRYPTING_BUFFER 256
#define BUFFER_SIZE 10000
#define LANG_ID_LEN 8
#define ID_FIELD_LEN 255
#define EXTRID_FIELD_LEN 256
#define TPL_VARS_NUM 64
#define CYC_NESTING_DEPTH 64
#define SELECTED_ADD_ON 32
#define LANID_LEN 4 /*lunghezza max dell'identificatore di linguaggio*/
#define INIT_FILE_LINE_LEN 512 /*lunghezza massima di una riga del file di inizializzazione*/
#define PAR_NAME_LEN 64 /*lunghezza massima del nome di un parametro nel file di inizializzazione*/
#define PAR_VALUE_LEN 256 /*lunghezza massima del valore di un parametro nel file di inizializzazione*/
#define INIT_FILE_NAME_LEN 256
#define HOME_DIR_LEN 64
#define IMG_DIR_LEN 64
#define SS_DIR_LEN 64
#define GET_VAR_LEN 128
#define TPL_LEN 250000
#define TPL_ABS_NAME_LEN 1024
#define MAX_TPL_NESTS 24
#define TPL_NAME_LEN 256
#define CMD_LEN 64
#define GET_PAR_VAL_LEN 4096
#define ITXCOO_TIME_DELAY 10000 // in secondi
#define PRM_TUNNEL_TAG "KOAN"
#define MAX_PRM_PARS 1000 //Max num di params in un prm
#define MAX_CMDS 1024
#define MAX_EXT_MODULES 50
// TQR Statistic
#define TOTRECS "TOTRECS"
#define ACTUALROW "ACTUALROW"
#define ACTUALPAGE "ACTUALPAGE"
#define ROWSTOSTORE "ROWSTOSTORE"
#define STARTINGROW "STARTINGROW"
#define MORERECS "MORERECS"
#define SOURCECOUNT "SOURCECOUNT"
#define TOTALPAGES "TOTALPAGES"
#define LASTPAGEROW "LASTPAGEROW"
#define NEXTPAGEROW "NEXTPAGEROW"
#define PREVPAGEROW "PREVPAGEROW"
// TQR cursor movement
#define FIRST "FIRST"
#define LAST "LAST"
#define NEXT "NEXT"
#define TO "TO"
// Base Command 'type' definitions
#define DEFAULT_BC_TYPE 0
#define START_CYCLE 1
#define END_CYCLE 2
#define START_CND_BLK 4
#define ELSE_CND_BLK 8
#define END_CND_BLK 16
#define ELSIF_CND_BLK 32
//Blocking - non blocking execution states
#define DONT_EXEC_BLK 0
#define EXEC_BLK 1
#define STOP_EXEC_BLK 2
#endif /* __DEFINES_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_ITNCNV_CPP__
#define __ITX_ITNCNV_CPP__
#endif
#include <string.h>
#include "itannitdef.h"
void itxOemToChar(char* source, char* destination)
{
char* p;
p = source;
while ((p = strchr(p, 0xAB)) != NULL)
*p = ITX_APPC_FIELD_SEP;
p = source;
while ((p = strchr(p, 0xAA)) != NULL)
*p = ITX_APPC_RECORD_SEP;
p = source;
while ((p = strchr(p, 0xBA)) != NULL)
*p = ITX_APPC_ENDINFO_SEP;
p = source;
while ((p = strchr(p, 0x85)) != NULL)
// *p = '�';
*p = (char) 0x7B;
p = source;
while ((p = strchr(p, 0x8A)) != NULL)
// *p = '�';
*p = (char) 0x7D;
p = source;
while ((p = strchr(p, 0x8D)) != NULL)
// *p = '�';
*p = (char) 0x7E;
p = source;
while ((p = strchr(p, 0x7C)) != NULL)
// *p = '|';
*p = (char) 0xE3;
p = source;
while ((p = strchr(p, 0x5C)) != NULL)
// *p = '\';
*p = (char) 0xA7;
p = source;
while ((p = strchr(p, 0x40)) != NULL)
// *p = '@';
*p = (char) 0xDD;
p = source;
while ((p = strchr(p, 0x23)) != NULL)
// *p = '#';
*p = (char) 0xD9;
p = source;
while ((p = strchr(p, 0xF5)) != NULL)
// *p = '�';
*p = (char) 0x40;
p = source;
while ((p = strchr(p, 0x5B)) != NULL)
// *p = '[';
*p = (char) 0xCA;
p = source;
while ((p = strchr(p, 0x5D)) != NULL)
// *p = ']';
*p = (char) 0xA9;
p = source;
while ((p = strchr(p, 0x87)) != NULL)
// *p = '�';
*p = (char) 0x5C;
p = source;
while ((p = strchr(p, 0x97)) != NULL)
// *p = '�';
*p = (char) 0x60;
p = source;
while ((p = strchr(p, 0x95)) != NULL)
// *p = '�';
*p = (char) 0x7C;
p = source;
while ((p = strchr(p, 0x82)) != NULL)
// *p = '�';
*p = (char) 0x5D;
p = source;
while ((p = strchr(p, 0x9C)) != NULL)
// *p = '�';
*p = (char) 0x23;
p = source;
while ((p = strchr(p, 0xF8)) != NULL)
// *p = '�';
*p = (char) 0x5B;
}
void itxCharToOem(char* source, char* destination)
{
char* p;
p = source;
while ((p = strchr(p, ITX_APPC_FIELD_SEP)) != NULL)
*p = (char) 0xAB;
p = source;
while ((p = strchr(p, ITX_APPC_RECORD_SEP)) != NULL)
*p = (char) 0xAA;
p = source;
while ((p = strchr(p, ITX_APPC_ENDINFO_SEP)) != NULL)
*p = (char) 0xBA;
p = source;
while ((p = strchr(p, 0x7B)) != NULL)
// *p = '�';
*p = (char) 0x85;
p = source;
while ((p = strchr(p, 0x7C)) != NULL)
// *p = '�';
*p = (char) 0x95;
p = source;
while ((p = strchr(p, 0x40)) != NULL)
// *p = '�';
*p = (char) 0xF5;
p = source;
while ((p = strchr(p, 0x7D)) != NULL)
// *p = '�';
*p = (char) 0x8A;
p = source;
while ((p = strchr(p, 0x5D)) != NULL)
// *p = '�';
*p = (char) 0x82;
p = source;
while ((p = strchr(p, 0x7E)) != NULL)
// *p = '�';
*p = (char) 0x8D;
p = source;
while ((p = strchr(p, 0xE3)) != NULL)
// *p = '|';
*p = (char) 0x7C;
p = source;
while ((p = strchr(p, 0x23)) != NULL)
// *p = '�';
*p = (char) 0x9C;
p = source;
while ((p = strchr(p, 0x5C)) != NULL)
// *p = '�';
*p = (char) 0x87;
p = source;
while ((p = strchr(p, 0x5B)) != NULL)
// *p = '�';
*p = (char) 0xF8;
p = source;
while ((p = strchr(p, 0xD9)) != NULL)
// *p = '#';
*p = (char) 0x23;
p = source;
while ((p = strchr(p, 0x60)) != NULL)
// *p = '�';
*p = (char) 0x97;
p = source;
while ((p = strchr(p, 0xCA)) != NULL)
// *p = '[';
*p = (char) 0x5B;
p = source;
while ((p = strchr(p, 0xA9)) != NULL)
// *p = ']';
*p = (char) 0x5D;
p = source;
while ((p = strchr(p, 0xA7)) != NULL)
// *p = '\';
*p = (char) 0x5C;
p = source;
while ((p = strchr(p, 0xDD)) != NULL)
// *p = '@';
*p = (char) 0x40;
}
// it works for null-terminating string
void itxEBCDToASCII(char* source)
{
char* p;
p = source;
while ((p = strchr(p, ITX_APPC_FIELD_SEP)) != NULL)
*p = (char) 0xAB;
p = source;
while ((p = strchr(p, ITX_APPC_RECORD_SEP)) != NULL)
*p = (char) 0xAA;
p = source;
while ((p = strchr(p, ITX_APPC_ENDINFO_SEP)) != NULL)
*p = (char) 0xBA;
p = source;
while ((p = strchr(p, 0x7B)) != NULL)
*p = '�';
p = source;
while ((p = strchr(p, 0x7C)) != NULL)
*p = '�';
p = source;
while ((p = strchr(p, 0x40)) != NULL)
*p = '�';
p = source;
while ((p = strchr(p, 0x7D)) != NULL)
*p = '�';
p = source;
while ((p = strchr(p, 0x5D)) != NULL)
*p = '�';
p = source;
while ((p = strchr(p, 0x7E)) != NULL)
*p = '�';
}
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.sql;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import jtxlib.main.datastruct.Vector;
/**
* A class representing in a matrix-like style a population of records,
* filled via an ODBC query or a manual construction.
* The first record (row) has index 0 and the last one has index <code>getRecordCount() - 1</code>.
* The first field (column) has index 0 and the last one has index <code>getFieldCount() - 1</code>.
* <P>
* <B>Example</B>
* <P>
* You use this class to get data from an ODBC source in this way:
* <PRE>
* JTXConnection conn = new JTXConnection("dsn_name", "dsn_user", "dsn_password");
* JTXResultSet rs = new JTXResultSet(conn);
*
* rs.select("SELECT * FROM Tab1", 2000);
*
* int record_count = rs.getRecordCount();
* for (int i=0; i < record_count; i++)
* {
* System.out.println(rs.getField(i, 2));
* System.out.println(rs.getField(i, "Xyz"));
* System.out.println(rs.getField(i, 0));
* }
* </PRE>
* or, alternatively:
* <PRE>
* JTXConnection conn = new JTXConnection("dsn_name", "dsn_user", "dsn_password");
* JTXResultSet rs = new JTXResultSet(conn);
*
* rs.select("SELECT * FROM Tab1", 2000);
*
* while(rs.next())
* {
* System.out.println(rs.getField("ID"));
* System.out.println(rs.getField("text1"));
* System.out.println(rs.getField("number1"));
* }
*</PRE>
* <P>
* The examples above execute a SELECT query to retrieve 2000 records,
* then they print out, for each row, the values of the requested fields.
*/
public class RecordSet extends DataManager
{
private int m_RowsToFetch = 100;
private String m_Statement = "";
private ResultSet m_RS = null;
private DBColumns m_Cols = null;
// Size of this vector is the total number of fetched rows
private Vector m_Rows = null;
// Cursor: -1 means BOF. BOF state is possible ONLY before the first fetch!!!
private int m_RowCursor = -1;
//------------------------------------------------------------------------------
/**
* Creates an instance of <code>this</code> object.
* <P>
* @param conn A JTXConnection to an ODBC data source.
*/
public RecordSet(DBConnection conn)
{
super(conn);
}
//------------------------------------------------------------------------------
/**
* Creates an instance of <code>this</code> object.
* <P>
* @param coldata A JTXVector of strings containing the names of the columns to assign
* to the newly created instance.
*/
public RecordSet(Vector coldata)
{
try
{
m_Cols = new DBColumns(coldata);
m_Rows = new Vector(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
/**
* Returns the ResultSet object.
*/
public ResultSet getResultSet()
{
return m_RS;
}
//------------------------------------------------------------------------------
/**
* Executes a SELECT statement and fills <code>this</code> JTXResultSet with the specified
* number of records, if possible.
* <p>
* <b>Note</b>: apart from the required number of rows to be fetched, the cursor position
* on the returned resultset is <b>always BOF</b>. This means that you always have to
* perform a {@link #first first()} or a {@link #next next()} to begin accessing data.
* The only way to skip this approach is to use the "positional" version of
* {@link #getField(int, String) getField(int rowIndex, String fieldName)}: in this case,
* you are explicitly indicating the row you want to access data into, thus bypassing the
* current cursor position.
* @param query the SELECT statement.
* @param nrows the number of rows initially fetched inside the current object.
* @see #select(String query)
*/
public boolean select(String query, int nrows)
{
if (query != null && query.trim().length() > 0)
{
try
{
m_Statement = query;
if ((m_RS = executeStatement(m_Statement, StatementType.SELECT)) == null)
return false;
m_Rows = null;
m_RowCursor = -1;
m_Cols = new DBColumns(m_RS.getMetaData());
if (fetch(nrows) == 0)
m_Rows = null; // query returns an empty resultset
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
/**
* Executes a SELECT statement and fills <code>this</code> JTXResultSet with the default
* number (100) of records, if possible.
* @param query the SELECT statement.
* @see #select(String query, int nrows)
*/
public boolean select(String query)
{
return select(query, m_RowsToFetch);
}
//------------------------------------------------------------------------------
/**
* Fetches the desired number of records (rows) into <code>this</code> JTXResultSet, appending them
* to the end of its internal vector.
* <P>
* <B>Note: </B>This function is equivalent to a <i>nrows</i> cycle calling the <i>next()</i>
* method in the java.sql.ResultSet class, if this is possible.
* @param nrows the number of rows to be fetched.
* @see #fetch()
* @see #fetchAll()
*/
public int fetch(int nrows)
{
if (nrows <= 0)
return 0;
if (m_Rows == null)
m_Rows = new Vector(nrows);
if (m_Cols == null)
return 0;
int colNum = m_Cols.getColumnCount();
int nFetched = 0;
DBRecord appo = null;
try
{
while(m_RS.next())
{
appo = new DBRecord(colNum);
for (int i=0; i<colNum; i++)
appo.addFieldValue(m_RS.getString(i+1));
m_Rows.addElement(appo);
nFetched++;
if (nFetched == nrows)
break;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return nFetched;
}
//------------------------------------------------------------------------------
/**
* Fetches all the records (rows) into <code>this</code> JTXResultSet, appending them
* to the end of its internal vector.
* <P>
* <B>Note: </B>
* This function can be very expensive in terms of memory usage and CPU time:
* use but not abuse...
* <P>
* @see #fetch(int nrows)
* @see #fetch()
*/
public int fetchAll()
{
int ret = (m_Rows == null ? 0 : m_Rows.size());
while (fetch() != 0);
return (m_Rows == null ? 0 : m_Rows.size()) - ret;
}
//------------------------------------------------------------------------------
/**
* Fetches the default number of records (rows) into <code>this</code> JTXResultSet, appending them
* to the end of its internal vector.
* @see #fetch(int nrows)
* @see #fetchAll()
*/
public int fetch()
{
return fetch(m_RowsToFetch);
}
//------------------------------------------------------------------------------
/**
* Sets the cursor to the first record, fetching it if necessary and
* if it exists, returns true.
* If the resultset is empty or if it fails, returns false.
*/
public boolean first()
{
if (m_Rows == null)
{
if (fetch(1) > 0)
{
m_RowCursor = 0;
return true;
}
return false;
}
m_RowCursor = 0;
return true;
}
//------------------------------------------------------------------------------
/**
* Fetches the next record and sets the cursor to the next record, if it exists,
* and returns true.
* If the next record does not exist or the resultset is empty or if it fails,
* returns false.
*/
public boolean next()
{
if (m_Rows == null || m_Rows.size() == (m_RowCursor + 1))
{
if (fetch(1) > 0)
{
m_RowCursor++;
return true;
}
return false;
}
m_RowCursor++;
return true;
}
//------------------------------------------------------------------------------
/**
* Fetches all remaining records and sets the cursor to the last record,
* if it exists, and returns true.
* If the resultset is empty or if it fails, returns false.
*/
public boolean last()
{
fetchAll();
if (m_Rows != null && m_Rows.size() > 0)
m_RowCursor = m_Rows.size() - 1;
return (m_RowCursor >= 0 ? true : false);
}
//------------------------------------------------------------------------------
/**
* Returns the current cursor position (-1 means BOF or EOF).
*/
public int getCursorPos()
{
return m_RowCursor;
}
//------------------------------------------------------------------------------
/**
* Returns the number of records (rows) currently contained in <code>this</code> object.
*/
public int getRecordCount()
{
return (m_Rows == null ? 0 : m_Rows.size());
}
//------------------------------------------------------------------------------
/**
* Returns the number of fields (columns) currently contained int <code>this</code> object.
*/
public int getFieldCount()
{
return (m_Cols == null ? 0 : m_Cols.getColumnCount());
}
//------------------------------------------------------------------------------
/**
* Returns a string containing the value of the requested field.
* <P>
* @param rowIndex the 0-based index of the row from which the field must be retrieved.
* @param fieldIndex the 0-based index of the column from which the field must be retrieved.
*/
public String getField(int rowIndex, int fieldIndex)
{
try
{
String aux = (String)(((DBRecord)m_Rows.elementAt(rowIndex)).m_Row.elementAt(fieldIndex));
return (aux == null ? "" : aux);
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
/**
* Returns a string containing the value of the requested field.
* <P>
* @param rowIndex the 0-based index of the row from which the field must be retrieved.
* @param fieldName the name of the field to be retrieved.
*/
public String getField(int rowIndex, String fieldName)
{
return (m_Cols == null ? "" : getField(rowIndex, m_Cols.getColumnIndex(fieldName)));
}
//------------------------------------------------------------------------------
/**
* Returns a string containing the value of the requested field at the current cursor position.
* <P>
* @param fieldName the name of the field to be retrieved.
*/
public String getField(String fieldName)
{
if (m_RowCursor >= 0 && m_Cols != null)
return getField(m_RowCursor, m_Cols.getColumnIndex(fieldName));
else
return "";
}
//------------------------------------------------------------------------------
/**
* Returns a string containing the name of the requested field.
* <P>
* @param fieldIndex the 0-based index of the column from which the field name must be retrieved.
*/
public String getFieldName(int fieldIndex)
{
try
{
if (m_Cols == null)
return "";
return (String)(((DBColumns)m_Cols).m_Name.elementAt(fieldIndex));
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
/**
* Sets a string value in the requested record-field.
* <P>
* @param rowIndex the 0-based index of the row.
* @param fieldIndex the 0-based index of the column.
* @param fieldVal the value to boolean assigned to the column.
*/
public void setField(int rowIndex, int fieldIndex, String fieldVal)
{
try
{
((DBRecord)m_Rows.elementAt(rowIndex)).setElementAt(fieldVal, fieldIndex);
}
catch (Exception e) {e.printStackTrace();}
}
//------------------------------------------------------------------------------
/**
* Sets a string value in the requested record-field.
* <P>
* @param rowIndex the 0-based index of the row.
* @param fieldName the name of the column to be re-assigned.
* @param fieldVal the value to boolean assigned to the column.
*/
public void setField(int rowIndex, String fieldName, String fieldVal)
{
try
{
((DBRecord)m_Rows.elementAt(rowIndex)).setElementAt(fieldVal, m_Cols.getColumnIndex(fieldName));
}
catch (Exception e) {e.printStackTrace();}
}
//------------------------------------------------------------------------------
/**
* Adds a record to <code>this</code> object.
* <P>
* @param newrow A JTXVector of strings.
*/
public int addRow(Vector newrow)
{
if (newrow == null)
return -1;
m_Rows.addElement(new DBRecord(newrow));
return m_Rows.size();
}
//------------------------------------------------------------------------------
/**
* Removes a record from <code>this</code> object.
* <P>
* @param rowidx The zero-based index of the row to be removed.
* @return void
*/
public void removeRow(int rowidx)
{
if (rowidx >=0 && rowidx < m_Rows.size())
m_Rows.removeElement(rowidx);
}
//------------------------------------------------------------------------------
public String toString()
{
String s = "";
String d = "";
try
{
if (m_Rows != null)
for (int i=0; i<m_Rows.size(); i++)
d += "[RECORD " + i + "] " + m_Rows.elementAt(i) + "\n";
s = m_Cols.toString() +
"---------------------------------- DATA -------------------------------------\n" +
" ";
for(int k=0; k<m_Cols.getColumnCount(); k++)
s += m_Cols.getName(k) + "\t\t";
s += "\n" + d;
}
catch(Exception e) {e.printStackTrace();}
return s;
}
//***********************************************
// DBColumns
//***********************************************
class DBColumns
{
private int m_ColNum = 0;
private Vector m_CatalogName = null;
private Vector m_Name = null;
private Vector m_Label = null;
private Vector m_Table = null;
//------------------------------------------------------------------------------
private DBColumns(Vector coldata)
{
try
{
m_ColNum = coldata.size();
m_Name = coldata;
}
catch (Exception e)
{
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
private DBColumns(ResultSetMetaData rsmd)
{
try
{
m_ColNum = rsmd.getColumnCount();
m_CatalogName = new Vector(m_ColNum);
m_Name = new Vector(m_ColNum);
m_Label = new Vector(m_ColNum);
m_Table = new Vector(m_ColNum);
for (int i=1; i<=m_ColNum; i++)
{
m_CatalogName.addElement(rsmd.getCatalogName(i));
m_Name.addElement(rsmd.getColumnName(i));
m_Label.addElement(rsmd.getColumnLabel(i));
m_Table.addElement(rsmd.getTableName(i));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
private int getColumnIndex(String fieldName)
{
int siz = m_Name.size();
int ret = 0;
while (ret < siz)
{
/* Retrieve the column index if exists:
jtxlib is CASE INSENSITIVE ! */
if (((String)m_Name.elementAt(ret)).equalsIgnoreCase(fieldName))
return ret;
else
ret++;
}
return -1;
}
//------------------------------------------------------------------------------
private int getColumnCount()
{
return m_ColNum;
}
//------------------------------------------------------------------------------
private String getCatalogName(int idx)
{
try
{
return (String)m_CatalogName.elementAt(idx);
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
private String getLabel(int idx)
{
try
{
return (String)m_Label.elementAt(idx);
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
private String getName(int idx)
{
try
{
return (String)m_Name.elementAt(idx);
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
private String getTable(int idx)
{
try
{
return (String)m_Table.elementAt(idx);
}
catch (Exception e)
{
return "";
}
}
//------------------------------------------------------------------------------
public String toString()
{
StringBuffer buf = new StringBuffer();
try
{
buf.append("CATALOG NAME LABEL NAME \n");
buf.append("-----------------------------------------------------------------------------\n");
for (int i=0; i<m_ColNum; i++)
{
StringBuffer app = new StringBuffer();
app.append(" \n");
String tablename = (String)(m_Table == null ? "NO_TABLE" : m_Table.elementAt(i));
if (tablename.length() > 0)
tablename += ".";
app.insert(0, tablename + (String)(m_CatalogName == null || m_CatalogName.elementAt(i).equals("") ?
"NO_CATALOG" : m_CatalogName.elementAt(i)));
app.insert(26, tablename + (String)(m_Label == null || m_Label.elementAt(i).equals("") ?
"NO_LABEL" : m_Label.elementAt(i)));
app.insert(52, tablename + (String)(m_Name == null || m_Name.elementAt(i).equals("") ?
"NO_NAME" : m_Name.elementAt(i)));
buf.append(app);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return buf.toString();
}
} // class DBColumn
//***********************************************
// DBRecord
//***********************************************
class DBRecord
{
private Vector m_Row;
//------------------------------------------------------------------------------
private DBRecord(){}
//------------------------------------------------------------------------------
private DBRecord(Vector newrow)
{
m_Row = newrow;
}
//------------------------------------------------------------------------------
private DBRecord(int colnum)
{
m_Row = new Vector(colnum);
}
//------------------------------------------------------------------------------
private void addFieldValue(String fvalue)
{
m_Row.addElement(fvalue);
}
//------------------------------------------------------------------------------
private void removeField(int idx)
{
m_Row.removeElement(idx);
}
//------------------------------------------------------------------------------
private void setElementAt(Object obj, int index) throws java.lang.ArrayIndexOutOfBoundsException
{
m_Row.setElementAt(obj, index);
}
//------------------------------------------------------------------------------
public String toString()
{
StringBuffer buf = new StringBuffer();
for (int i=0; i<m_Row.size(); i++)
buf.append(m_Row.elementAt(i) + "\t\t");
return buf.toString();
}
} // class DBRecord
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: tqrodbc.h,v $
* $Revision: 1.16 $
* $Author: massimo $
* $Date: 2002-05-28 12:55:01+02 $
*
* Management of TQRs from ODBC source
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __TQRODBC_H__
#define __TQRODBC_H__
#include "itxlib.h"
#include "tqr.h"
#define MAX_QUERYHEADER_NUM 256
class TQRODBCManager : public TQRManager
{
itxSQLConnection* m_iconn;
bool m_connected;
public:
TQRODBCManager() { m_connected = false; m_iconn = NULL;};
TQRODBCManager(TQRCollection* tqrs) : TQRManager(tqrs) { m_connected = false; m_iconn = NULL;}
~TQRODBCManager() {};
// TQRODBCManager Interface
void Connect(char* dsn, char* uid, char* pwd);
void SetConnect(itxSQLConnection* conn);
void Disconnect();
int Execute(char* tqrname, char* query, int firstRec = STARTING_ROW, int recsToStore = ROWS_TO_STORE);
void Inquiry(char* tqrname, char* query);
bool BulkInsert(char* target, char* tqrname, ...);
bool PrepareSQLInsertStringWith(itxString* query, char* target, TQR* qres, TQRRecord* record, va_list morefields);
void SetTQRColumnsAttributesFromTable(TQR* qres, char* tablename);
itxSQLConnection* GetConnection() { return m_iconn; };
// Internals
void SetTQRColumnsAttributes(TQRHANDLE qres);
bool IsNumeric(TQR* qres, char* colname);
bool IsReal(TQR* qres, int colindex);
bool IsAlpha(TQR* qres, char* colname);
bool IsDate(TQR* qres, char* colname);
};
#endif<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
-----------------------------------------------------------------------------
- FILENAME : templatefile.h
- TAB : 2 spaces
-----------------------------------------------------------------------------
- DESCRIPTION :
Template file wrapper object.
*****************************************************************************/
#ifndef _TEMPLATEFILE_H_
#define _TEMPLATEFILE_H_
#include "itxlib.h"
class Parser;
class TemplateFile
{
friend Parser;
private:
//Members
itxString m_Tpl;
itxString m_PathName;
long m_ContentLen; //Comprese le linee di commento gasp
int m_TplFound;
public:
int m_ReadCycle[CYC_NESTING_DEPTH];
char m_ValidBlock[CYC_NESTING_DEPTH];
int m_CndLevel;
int m_CycLevel;
itxStack m_CycleStk;
int m_RecursionZero; //Counts the recursion nestings of Parser::ProcTplData on this template
itxString m_Output;
private:
//Methods
void InitMembers();
int Read(char* ext);
void PurgeComments(char*);
int CheckStartBlock(int type, char* cmdStart);
int CheckEndBlock(int type, char** tplString);
inline int MustExec(){return (m_ValidBlock[m_CndLevel] == EXEC_BLK && m_ReadCycle[m_CycLevel]);}
public:
int GetContent(char* tplstr);
itxString* GetContent(itxString* tplstr);
// Returns the pointer to the internal content buffer
inline char* GetContentBuffer(){return m_Tpl.GetBuffer();}
inline int Exist(){return m_TplFound;}
inline char* GetPathName(){return m_PathName.GetBuffer();}
inline long ContentLen(){return m_ContentLen;}
//Construction-Destruction
TemplateFile(char* tpl_path_name, char* ext = TPL_EXT);
TemplateFile(itxString* tpl_path_name, char* ext = TPL_EXT);
TemplateFile(char* tpl_content, int finto);
~TemplateFile(){};
};
#endif /* _TEMPLATEFILE_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxhttp.cpp,v $
* $Revision: 1.13 $
* $Author: massimo $
* $Date: 2002-05-02 16:28:48+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxhttp.h"
itxHttp::itxHttp(char* useragent)
{
m_socket = NULL;
m_useragent = useragent;
m_querystring.SetEmpty();
m_datareceived.SetEmpty();
m_header.SetEmpty();
m_RecvTimeoutSecs = 300;
}
itxString itxHttp::GetURL()
{
itxString appo = m_querystring;
appo.PurgeSubString("http://");
appo.Right(appo.Len() - appo.FindSubString("/"));
return appo;
}
void itxHttp::GetHttpParameter(itxString* destination, int* port, itxString* url, bool ssl)
{
//from rfc2616 - HTTP/1.1
//http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
itxString appo = m_querystring;
appo.PurgeSubString("http://");
appo.PurgeSubString("https://");
int firstslash = appo.FindSubString("/");
int pos_colon = appo.FindSubString(":");
int len = appo.Len();
//Check if the colon is not the port delimiter, but something else
if (pos_colon > firstslash)
pos_colon = len;
*url = appo;
url->Right(len - firstslash);
*destination = appo;
if (pos_colon == len)
{
destination->Left(firstslash);
*port = (ssl ? ITXH_DEFAULTPORT_SSL : ITXH_DEFAULTPORT);
}
else
{
destination->Left(pos_colon);
appo.Left(firstslash);
appo.Right(appo.Len() - (pos_colon + 1));
*port = atoi(appo.GetBuffer());
}
}
int itxHttp::GET(char* querystring, int packetlen, bool ssl)
{
itxString datatosend;
int bytesreceived;
m_querystring = querystring;
m_querystring.Trim();
itxString destination;
int port;
itxString url;
GetHttpParameter(&destination, &port, &url, ssl);
url.SubstituteSubString(" ", "%20"); //Spaces must be escaped
try
{
m_socket = new itxSocket(destination.GetBuffer(), port, ssl);
m_socket->SetReceiveTimeout(m_RecvTimeoutSecs, 0);
m_socket->SetReceiveCycleTimeout(m_RecvTimeoutSecs, 0);
// HTTP GET Method string preparation
datatosend = "GET ";
datatosend += url;
datatosend += " HTTP/1.0\r\nHost: ";
datatosend += destination;
datatosend += "\r\nUser-Agent: ";
datatosend += m_useragent;
datatosend += "\r\n\r\n";
if (ssl)
{
m_socket->SSLSend(&datatosend);
bytesreceived = m_socket->SSLReceive(&m_datareceived);
}
else
{
m_socket->Send(&datatosend);
bytesreceived = m_socket->Receive(&m_datareceived);
}
m_header = m_datareceived;
int end_header = m_header.FindSubString("\r\n\r\n") + 4;
//Chunked transfer-encoding management (?TO VERIFY?)
// if (m_header.FindSubString("chunked") < m_header.Len())
// end_header += (m_header.FindSubString("\r\n", end_header) + 2);
m_header.Left(end_header);
m_datareceived.Right(bytesreceived - end_header);
}
catch(itxException* e)
{
throw (itxException*) e;
}
return bytesreceived;
}
int itxHttp::GETBin(char* querystring, char** datareceived, int maxbytes, int packetlen, long timeoutsec, long timeoutmilli)
{
itxString datatosend;
int bytesreceived;
m_querystring = querystring;
m_querystring.Trim();
itxString destination;
int port;
itxString url;
GetHttpParameter(&destination, &port, &url);
url.SubstituteSubString(" ", "%20"); //Spaces must be escaped
try
{
m_socket = new itxSocket(destination.GetBuffer(), port);
// HTTP GET Method string preparation
datatosend = "GET ";
datatosend += url;
datatosend += " HTTP/1.0\r\nHost: ";
datatosend += destination;
datatosend += "\r\nUser-Agent: ";
datatosend += m_useragent;
datatosend += "\r\n\r\n";
m_socket->Send(&datatosend);
m_socket->SetReceiveTimeout(timeoutsec, timeoutmilli);
bytesreceived = m_socket->BinReceive(*datareceived, maxbytes, packetlen);
m_header = "" ;
char* rawdata = strstr(*datareceived, "\r\n\r\n");
m_header.Strncpy(*datareceived, (unsigned int) rawdata - (unsigned int) *datareceived);
*datareceived = rawdata + 4;
bytesreceived -= m_header.Len();
}
catch(itxException* e)
{
throw (itxException*) e;
}
return bytesreceived;
}
int itxHttp::POST(char* querystring, char* data, char* contentType, int packetlen, bool ssl)
{
itxString destination;
itxString datatosend;
itxString url;
itxString appo;
int bytesreceived;
int port;
m_querystring = querystring;
m_querystring.Trim();
GetHttpParameter(&destination, &port, &url, ssl);
url.SubstituteSubString(" ", "%20"); //Spaces must be escaped
try
{
m_socket = new itxSocket(destination.GetBuffer(), port, ssl);
m_socket->SetReceiveTimeout(m_RecvTimeoutSecs, 0);
m_socket->SetReceiveCycleTimeout(m_RecvTimeoutSecs, 0);
// HTTP POST Method string preparation
datatosend = "POST ";
datatosend += url;
datatosend += " HTTP/1.0\r\nHost: ";
datatosend += destination;
datatosend += "\r\nUser-Agent: ";
datatosend += m_useragent;
datatosend += "\r\nContent-Type: ";
datatosend += contentType;
datatosend += "\r\n";
datatosend += "Content-Length: ";
datatosend += (int)(data != NULL ? strlen(data) : 0);
datatosend += "\r\n\r\n";
datatosend += data;
if (ssl)
{
m_socket->SSLSend(&datatosend);
bytesreceived = m_socket->SSLReceive(&m_datareceived);
}
else
{
m_socket->Send(&datatosend);
bytesreceived = m_socket->Receive(&m_datareceived);
}
m_header = m_datareceived;
int end_header = m_header.FindSubString("\r\n\r\n") + 4;
m_header.Left(end_header);
m_datareceived.Right(bytesreceived - end_header);
}
catch(itxException* e)
{
throw (itxException*) e;
}
return bytesreceived;
}
<file_sep><HTML>
<HEAD>
<TITLE>Tannit 4.0 Command Reference </TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#ffffff" TOPMARGIN=0>
<LINK REL=STYLESHEET HREF="styles.css" TYPE="text/css">
<span class=CmdTitolo>
*now()
</span>
<BR>
<BR>
<BR>
<!-- TODO BEGIN -->
The command returns a string representing the universal time
(seconds past midnight of 1.1.1970) of the current date-time.
<br>
<!-- TODO END -->
<BR>
<BR>
<BR>
<center>
<A HREF="index.htm">Command Reference Index</A><br>
</center>
<br>
<br>
<br>
</BODY>
</HTML>
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: auxfile.h,v $
* $Revision: 1.24 $
* $Author: massimo $
* $Date: 2002-06-25 18:25:14+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 rom<NAME>
* <EMAIL>
*/
#ifndef __AUXFILE_H__
#define __AUXFILE_H__
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include "defines.h"
#include "itxlib.h"
#define INI_REL_PATH0 "dbgname.par"
#define INI_REL_PATH1 "." PATH_SEPARATOR "cgi-bin" PATH_SEPARATOR INI_REL_PATH0
#define INI_REL_PATH2 "." PATH_SEPARATOR "cgi-itx" PATH_SEPARATOR INI_REL_PATH0
#define DBGPATH "DbgPath"
#define CLOCKS_PER_MILLI CLOCKS_PER_SEC/1000
//Text/Graphical aspect
#define NOTHTML_HSEP "-------------------------------------------------------------------------------\n"
#define FIRST_ERROR_ANCHOR "\"#FIRST_ERROR_ANCHOR\""
//Trace types
#define DEFAULT 0
#define IN_COMMAND 1 //Messages (not errors at all) incoming from commands.
#define IN_WARNING 2 //Errors caused by the user
#define IN_TNTAPI 4 //Errors incoming from a call made by the user to a TNT-api function.
#define IN_ERROR 8 //INSIDE-CORE ERRORS: top severity. Use with care (best is: do not use).
#define TEMPLATE 16 //Template separator for the debug page
/*****************************************************************************
---------------------------- DebugFile object -----------------------------
*****************************************************************************/
class DebugFile
{
public:
//MEMBERS
itxString m_DebugPath;
itxString m_CurrentTemplate;
bool m_UseDebug;
bool m_Errors;
bool m_FirstErrorAnchor;
FILE* m_Debug;
int m_HTML;
int m_ReportLevel;
unsigned int m_StartMilliCount;
unsigned int m_StopMilliCount;
itxSystem m_Sys;
//METHODS
void Trace(int type, char* strarg, va_list args);
void _TimeTrace(char* strarg, va_list args);
void _StartMilliCount();
void _StopMilliCount();
void _TraceMilliDiff(char* msg);
struct tm* _CurrentDateTime();
bool Bufferize(itxString* outDebugBuf);
void Open();
void Close();
private:
bool ReadDbgname(FILE*, itxString*);
void ManageTypeOpen(int type);
void ManageTypeClose(int type);
public:
//CONSTRUCTION-DESTRUCTION
DebugFile();
~DebugFile();
};
//////////////////////////////////////
// EXTERN Section
extern DebugFile g_DebugFile;
#ifdef MAINT_1
extern void DebugTrace(char* strarg, ...);
extern void DebugTrace2(int type, char* strarg, ...);
extern void TimeTrace(char* strarg, ...);
extern void StartMilliCount();
extern void StopMilliCount();
extern void TraceMilliDiff(char* msg);
extern struct tm* CurrentDateTime();
extern char* CurrentDateTimeStr();
extern void SQLTrace(itxSQLConnection* conn);
#else
//toggles off some tedious warnings:
#pragma warning(disable : 4002) //too many actual parameters for macro '....'
#pragma warning(disable : 4390) //';' : empty controlled statement found; is this the intent?
#define DebugTrace()
#define DebugTrace2()
#define TimeTrace()
#define StartMilliCount()
#define StopMilliCount()
#define TraceMilliDiff()
#define CurrentDateTime()
#define CurrentDateTimeStr()
#endif /* MAINT_1 */
#endif /* __AUXFILE_H__ */
<file_sep>Attic
=====
Closed/aborted/unmaintained projects or self-study
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
-----------------------------------------------------------------------------
- FILENAME : templatefile.cpp
- TAB : 2 spaces
-----------------------------------------------------------------------------
- DESCRIPTION :
Template file wrapper object impl.
*****************************************************************************/
#include "defines.h"
#include "auxfile.h"
#include "templatefile.h"
#include "itxlib.h"
//-------------------------------------------------------------------------------
void TemplateFile::InitMembers()
{
for (m_CndLevel=0; m_CndLevel < CYC_NESTING_DEPTH; m_CndLevel++)
{
m_ValidBlock[m_CndLevel] = EXEC_BLK;
m_ReadCycle[m_CndLevel] = 1;
}
m_CndLevel = 0;
m_CycLevel = 0;
m_Tpl.SetEmpty();
m_ContentLen = 0;
m_RecursionZero = 0;
m_Output.SetGranularity(100000);
m_Output.SetEmpty();
}
//-------------------------------------------------------------------------------
TemplateFile::TemplateFile(char* tpl_path_name, char* ext)
{
InitMembers();
m_PathName = tpl_path_name;
m_TplFound = Read(ext);
}
//-------------------------------------------------------------------------------
TemplateFile::TemplateFile(itxString* tpl_path_name, char* ext)
{
InitMembers();
m_PathName = *tpl_path_name;
m_TplFound = Read(ext);
}
//-------------------------------------------------------------------------------
TemplateFile::TemplateFile(char* tpl_content, int finto)
{
InitMembers();
char appo[20];
sprintf(appo, "%p", tpl_content);
m_PathName = appo;
m_ContentLen = strlen(tpl_content);
m_TplFound = 1;
//Purge cpp-style comment lines and sets m_Tpl to the purged buffer
PurgeComments(tpl_content);
}
//-------------------------------------------------------------------------------
/*
attivita' :apre il file individuato, alloca tplString e vi scrive i dati del file;
*/
int TemplateFile::Read(char* ext)
{
long numread = 0;
char* dataBuffer = NULL;
FILE* fTemplate;
if (m_PathName.IsNull() || m_PathName.IsEmpty())
return 0;
//N.B. questa linea di codice lega
//la classe TemplateFile all'estensione 'htm' dei template.
m_PathName += ext;
//Apertura e controllo del template da interpretare
if ((fTemplate = fopen(m_PathName.GetBuffer(),"rb")) == 0)
return 0;
//Valutazione della Content-length
fseek(fTemplate, 0, SEEK_SET);
m_ContentLen = ftell(fTemplate);
fseek(fTemplate, 0, SEEK_END);
m_ContentLen = ftell(fTemplate) - m_ContentLen;
rewind(fTemplate);
if ((dataBuffer = (char*)calloc(m_ContentLen + 1, sizeof(char))) == NULL)
return 0;
//lettura template
if ((numread = fread(dataBuffer, sizeof(char), m_ContentLen, fTemplate)) < m_ContentLen)
return 0;
dataBuffer[m_ContentLen] = 0; // sostituzione del carattere EOF con 0
//Purge cpp-style comment lines and sets m_Tpl to the purged buffer
PurgeComments(dataBuffer);
free(dataBuffer);
fclose(fTemplate);
//Purge LF
// m_Tpl.PurgeSubString("\n");
return 1;
}
//-------------------------------------------------------------------------------
void TemplateFile::PurgeComments(char* cursor)
{
try
{
char* slash1 = cursor;
slash1 = strstr(cursor, TNT_COMMENT);
while(slash1 != NULL)
{
*slash1++ = 0;
m_Tpl += cursor;
cursor = slash1;
if ((cursor = strchr(cursor, CR)) != NULL)
{
slash1 = (++cursor);
slash1 = strstr(cursor, TNT_COMMENT);
}
else
slash1 = NULL;
}
m_Tpl += cursor;
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled Exception in TemplateFile::PurgeComments\n");
}
}
//-------------------------------------------------------------------------------
int TemplateFile::GetContent(char* tplstr)
{
try
{
if (tplstr)
strcpy(tplstr, GetContentBuffer());
}
catch(...)
{
return 0;
}
return 1;
}
//-------------------------------------------------------------------------------
itxString* TemplateFile::GetContent(itxString* tplstr)
{
try
{
if (tplstr)
*tplstr = GetContentBuffer();
}
catch(...)
{
return NULL;
}
return tplstr;
}
//-----------------------------------------------------------------
int TemplateFile::CheckStartBlock(int type, char* cmdStart)
{
int ret = 0;
if (type & START_CND_BLK)
{
m_CndLevel++;
// si ereditano le colpe dei padri
if (m_ValidBlock[m_CndLevel-1] != EXEC_BLK)
m_ValidBlock[m_CndLevel] = m_ValidBlock[m_CndLevel-1];
ret = 1;
}
else if (type & ELSE_CND_BLK)
{
if (m_ValidBlock[m_CndLevel] == DONT_EXEC_BLK)
m_ValidBlock[m_CndLevel] = EXEC_BLK;
else if (m_ValidBlock[m_CndLevel] == EXEC_BLK)
m_ValidBlock[m_CndLevel] = DONT_EXEC_BLK;
// si ereditano le colpe dei padri
if (m_ValidBlock[m_CndLevel-1] != EXEC_BLK)
m_ValidBlock[m_CndLevel] = m_ValidBlock[m_CndLevel-1];
ret = 1;
}
else if (type & ELSIF_CND_BLK)
{
if (m_ValidBlock[m_CndLevel] == DONT_EXEC_BLK)
m_ValidBlock[m_CndLevel] = EXEC_BLK;
else if (m_ValidBlock[m_CndLevel] == EXEC_BLK)
m_ValidBlock[m_CndLevel] = STOP_EXEC_BLK;
// si ereditano le colpe dei padri
if (m_ValidBlock[m_CndLevel-1] != EXEC_BLK)
m_ValidBlock[m_CndLevel] = m_ValidBlock[m_CndLevel-1];
ret = 1;
}
if (m_ValidBlock[m_CndLevel] == EXEC_BLK && (type & START_CYCLE))
{
m_CycLevel++;
m_CycleStk.Push(cmdStart);
ret = 1;
}
return ret;
}
//-----------------------------------------------------------------
int TemplateFile::CheckEndBlock(int type, char** tplString)
{
int ret = 0;
if ((m_ValidBlock[m_CndLevel] == EXEC_BLK) && (type & END_CYCLE))
{
if (m_ReadCycle[m_CycLevel])
m_CycleStk.Pop((void**)tplString);
else
{
m_CycleStk.Pop(NULL);
m_ReadCycle[m_CycLevel] = 1;
}
m_CycLevel--;
ret = 1;
}
if (type & END_CND_BLK)
{
m_ValidBlock[m_CndLevel] = EXEC_BLK;
m_CndLevel--;
ret = 1;
}
return ret;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* include/fcgi_config.h. Generated automatically by configure. */
/* include/fcgi_config.h.in. Generated automatically from configure.in by autoheader. */
/* Define if on AIX 3.
System headers sometimes define this.
We just want to avoid a redefinition error message. */
#ifndef _ALL_SOURCE
/* #undef _ALL_SOURCE */
#endif
/* Define if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define to type of ssize_t, if not on this platform. */
#define ssize_t int
/* Define if you have the <sys/select.h> include file */
/* #undef HAVE_SYS_SELECT_H */
/* Define if you don't have fd_set */
#define NO_FD_SET 1
/* Define if want to compile with ASSERT() statements */
#define WITH_ASSERT 1
/* Define if want to compile with additional debugging code */
#define WITH_DEBUG 1
/* Define if want to compile with hooks for testing */
#define WITH_TEST 1
/* Define if sockaddr_un in <sys/un.h> contains the sun_len component */
/* #undef HAVE_SOCKADDR_UN_SUN_LEN */
/* Define if we have f{set,get}pos functions */
#define HAVE_FPOS 1
/* Define if we need cross-process locking */
/* #undef USE_LOCKING */
/* Define if va_arg(arg, long double) crashes the compiler. */
/* #undef HAVE_VA_ARG_LONG_DOUBLE_BUG */
/* Don't know what this stuff is for */
#define HAVE_MATHLIB 1
/* #undef WITH_DOMESTIC */
/* #undef WITH_EXPORT */
/* #undef WITH_GLOBAL */
/* The number of bytes in a int. */
#define SIZEOF_INT 4
/* The number of bytes in a long. */
#define SIZEOF_LONG 4
/* The number of bytes in a off_t. */
#define SIZEOF_OFF_T 0
/* The number of bytes in a size_t. */
#define SIZEOF_SIZE_T 4
/* The number of bytes in a unsigned int. */
#define SIZEOF_UNSIGNED_INT 4
/* The number of bytes in a unsigned long. */
#define SIZEOF_UNSIGNED_LONG 4
/* The number of bytes in a unsigned short. */
#define SIZEOF_UNSIGNED_SHORT 2
/* Define if you have the <limits.h> header file. */
#define HAVE_LIMITS_H 1
/* Define if you have the <unistd.h> header file. */
/* #undef HAVE_UNISTD_H */
/* Define if you have the <netdb.h> header file. */
/* #undef HAVE_NETDB_H */
/* Define if you have the <netinet/in.h> header file. */
/* #undef HAVE_NETINET_IN_H */
/* Define if you have the <windows.h> header file. */
#define HAVE_WINDOWS_H 1
/* Define if you have the <winsock.h> header file. */
#define HAVE_WINSOCK_H 1
/* Define if you have the <sys/socket.h> header file. */
/* #undef HAVE_SYS_SOCKET_H */
/* Define if you have the <strings.h> header file. */
/* #undef HAVE_STRINGS_H */
/* Define if you have the <sys/time.h> header file. */
/* #undef HAVE_SYS_TIME_H */
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.sql;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.GregorianCalendar;
import jtxlib.main.aux.Debug;
import jtxlib.main.aux.Tools;
/* ----------------------------------------------------- */
/* JTXDataManager */
/* ----------------------------------------------------- */
public class DataManager
{
public interface StatementType
{
public final byte SELECT = 0;
public final byte INSERT = 1;
public final byte UPDATE = 2;
public final byte DELETE = 3;
public final byte OTHER = 4;
}
Debug m_Dbg = new Debug();
StatementType m_StmType;
private Statement m_SelectStatement;
private ResultSet m_Data;
//---------------------------------------------------------------
public DataManager()
{
}
//---------------------------------------------------------------
public DataManager(DBConnection conn)
{
try
{
m_SelectStatement = conn.m_Conn.createStatement();
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager(JTXConnection conn): SQLException: " + sqle.getMessage());
if (conn.m_Conn == null)
Debug.Dbg("conn.m_Conn is null.");
sqle.printStackTrace();
}
}
//---------------------------------------------------------------
public void close()
{
try
{
m_SelectStatement.getConnection().commit();
m_SelectStatement.close();
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager.close: SQLException: " + sqle.getMessage());
}
}
//---------------------------------------------------------------
public ResultSet executeStatement(String selectStatement, byte queryType) throws SQLException
{
if ((queryType == StatementType.INSERT) || (queryType == StatementType.UPDATE) || (queryType == StatementType.DELETE))
{
try
{
m_SelectStatement.executeUpdate(selectStatement);
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager.executeUpdate: SQLException: " + sqle.getMessage() + "\r\nQuery:\r\n" + selectStatement);
throw sqle;
}
}
else if (queryType == StatementType.SELECT)
{
try
{
m_Data = m_SelectStatement.executeQuery(selectStatement);
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager.executeQuery: SQLException: " + sqle.getMessage() + "\r\nQuery:\r\n" + selectStatement);
throw sqle;
}
}
else if (queryType == StatementType.OTHER)
{
try
{
m_SelectStatement.execute(selectStatement);
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager.execute: SQLException: " + sqle.getMessage() + "\r\nQuery:\r\n" + selectStatement);
throw sqle;
}
}
return m_Data;
}
//---------------------------------------------------------------
public String getMaxID(String tableName, String idname) throws SQLException //RESTITUISCE MAXID + 1
{
String ret = "1";
try
{
ResultSet rs = m_SelectStatement.executeQuery("SELECT (MAX(" + idname + ") + 1) AS maxid FROM " + tableName);
if (rs != null)
{
rs.next();
ret = rs.getString("maxid");
}
}
catch(SQLException sqle)
{
Debug.Dbg("JTXDataManager-getMaxID: SQLException: " + sqle.getMessage());
throw sqle;
}
if (ret == null)
ret = "1";
return ret;
}
//---------------------------------------------------------------
public byte adjVal(String fieldName, byte defaultVal) throws Exception
{
//wasNull() method works on the last retrieved field value, so
//it's better to fetch it here and not outside, to prevent side effects
byte retVal = m_Data.getByte(fieldName);
return (m_Data.wasNull() ? defaultVal : retVal);
}
//---------------------------------------------------------------
public String adjVal(String fieldName, String defaultVal) //throws Exception
{
//wasNull() method works on the last retrieved field value, so
//it's better to fetch it here and not outside, to prevent side effects
try
{
String retVal = m_Data.getString(fieldName);
return (m_Data.wasNull() ? defaultVal : retVal);
}
catch(SQLException se)
{
Debug.Dbg("Current field is: " + fieldName + "\n");
// m_Dbg.Dbg("SQLException: " + se.getMessage() + " - error code: " + se.getErrorCode() + " SQLState: " + se.getSQLState());
}
return defaultVal;
}
//---------------------------------------------------------------
public String adjTxt(String fieldName, String defaultVal)// throws Exception
{
//wasNull() method works on the last retrieved field value, so
//it's better to fetch it here and not outside, to prevent side effects
try
{
String retVal = m_Data.getString(fieldName);
return (m_Data.wasNull() ? defaultVal : adjQuotes(retVal));
}
catch(SQLException se)
{
Debug.Dbg("Current field is: " + fieldName + "\n");
// m_Dbg.Dbg("SQLException: " + se.getMessage() + " - error code: " + se.getErrorCode() + " SQLState: " + se.getSQLState());
}
return defaultVal;
}
//---------------------------------------------------------------
public String adjQuotes(String in)
{
return Tools.SQLQuotesEnclose(in);
}
//---------------------------------------------------------------
public String defaultVal()
{
String defaultDate;
java.util.Date today = new java.util.Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(today);
defaultDate="'"+calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+"-"+calendar.get(Calendar.DATE)+"'";
return defaultDate;
}
//---------------------------------------------------------------
public String adjDate(String fieldName, String defaultVal) throws Exception
{
//wasNull() method works on the last retrieved field value, so
//it's better to fetch it here and not outside, to prevent side effects
String retVal = "'"+m_Data.getString(fieldName)+"'";
return (m_Data.wasNull() ? defaultVal : retVal);
}
//---------------------------------------------------------------
public String adjDate(String fieldName) throws Exception
{
//wasNull() method works on the last retrieved field value, so
//it's better to fetch it here and not outside, to prevent side effects
String retVal = "'"+m_Data.getString(fieldName)+"'";
return (m_Data.wasNull() ? "CONVERT(varchar(10), getdate(), 120)" : retVal);
}
} //END OF class JTXDataManager
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include "defines.h"
#include "cgiresolver.h"
#include "parser.h"
#include "tntapiimpl.h"
#include "tqrodbc.h"
#include "itxlib.h"
class Tannit : public CGIResolver
{
//MEMBERS
private:
itxString m_ResponseMIMEtype;
public:
Parser m_Parser;
TQRCollection m_TQRCollection;
TQRManager m_TQRManager;
TQRODBCManager m_TQRODBCManager;
itxSQLConnection m_odbcconnection;
itxSQLConnCollection m_connections;
TNTAPIImpl* m_pTNTAPIImpl;
void* m_ExtModHandle[MAX_EXT_MODULES]; //Addon DLL's handles
int m_NExtModules;
private:
//METHODS
RunType_e ManageContext(itxString* tplName, itxString* tplDir, itxString* preproc_outtpl, itxString* preproc_outdir);
void ManageOutput(itxString preproc_outdir, itxString preproc_outtpl);
public:
void OnStart();
void OnPostRequest();
void CommandLineMode(int argc, char** argv);
void OnCommandLine(char* modulename, char cmdsep, char* inputfile, char*outputfile, char* ext);
void Usage(char* argv);
bool IsWebRequest();
void SendResponseMimeType(char* mimetype = NULL);
void Inquiry();
void InquiryCurWorkingDir(itxString* ret);
bool InquiryDebugFile();
void InquiryConfigFiles(itxString* ret);
void InquiryConnections(itxString prmlist, itxString* ret);
void MakeConfigurationFileList(itxString auxdir, char* filter, itxString* conflist);
bool InitCurrentPRM();
bool Initialize();
bool InitODBC(PRMFile* prmfile);
void LoadModules(PRMFile& paramfile);
void LoadUserCommands(itxString* ext_mod_pathname, TNTAPIImpl* pTNTAPIImpl);
//CONSTRUCTORS-DESTRUCTORS
public:
Tannit();
~Tannit();
};
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "itxtypes.h"
#include "iregtp.h"
extern TPAS400 tpAS400[NUM_TPAS400];
void itxTP::Default()
{
for (int i = 0; i < NUM_TPAS400; i++)
{
m_tpas400[i].id = (unsigned short) tpAS400[i].id;
m_tpas400[i].n_fields = tpAS400[i].n_fields;
memcpy(m_tpas400[i].name, tpAS400[i].name, TPAS400_NAME_LEN);
}
}
bool itxTP::Load(char* filename)
{
FILE* f = NULL;
int itp = 1;
char appo[256];
if ((f = fopen(filename, "r")) == NULL)
{
Default();
return TRUE;
}
while (!feof(f))
{
fscanf(f, "%s", appo);
if (strlen(appo) >= TPAS400_NAME_LEN) return FALSE;
sprintf(m_tpas400[itp].name, "%s", appo);
fscanf(f, "%d", &m_tpas400[itp].n_fields);
if (m_tpas400[itp].n_fields <= 0) return FALSE;
itp++;
if (itp >= MAX_NUM_TPAS400) return FALSE;
}
m_tpnumber = itp;
return TRUE;
}
unsigned short itxTP::GetTPID(char* tpname)
{
unsigned short id = 0;
if (tpname != NULL)
{
while (strcmp(m_tpas400[id].name, tpname) != 0 && id < MAX_NUM_TPAS400)
id++;
}
return id;
}
char* itxTP::GetTPName(unsigned short id)
{
char* name = NULL;
if (id > 0 && id < m_tpnumber)
name = (char*) &(m_tpas400[id].name);
return name;
}
int itxTP::GetTPNFields(char* name)
{
unsigned short id = 0;
if ((id = GetTPID(name)) != 0 && id != MAX_NUM_TPAS400)
return m_tpas400[id].n_fields;
return 0;
}
<file_sep>/* The CGI_C library, by <NAME>, version 1.0. CGI_C is intended
to be a high-quality API to simplify CGI programming tasks. */
/* Make sure this is only included once. */
#ifndef CGI_C
#define CGI_C 1
/* Bring in standard I/O since some of the functions refer to
types defined by it, such as FILE *. */
#include <stdio.h>
/* The various CGI environment variables. Instead of using getenv(),
the programmer should refer to these, which are always
valid null-terminated strings (they may be empty, but they
will never be null). If these variables are used instead
of calling getenv(), then it will be possible to save
and restore CGI environments, which is highly convenient
for debugging. */
extern char *cgiServerSoftware;
extern char *cgiServerName;
extern char *cgiGatewayInterface;
extern char *cgiServerProtocol;
extern char *cgiServerPort;
extern char *cgiRequestMethod;
extern char *cgiPathInfo;
extern char *cgiPathTranslated;
extern char *cgiScriptName;
extern char *cgiQueryString;
extern char *cgiRemoteHost;
extern char *cgiHttpHost;
extern char *cgiRemoteAddr;
extern char *cgiAuthType;
extern char *cgiRemoteUser;
extern char *cgiRemoteIdent;
extern char *cgiContentType;
extern char *cgiAccept;
extern char *cgiUserAgent;
/* The number of bytes of data received.
Note that if the submission is a form submission
the library will read and parse all the information
directly from cgiIn; the programmer need not do so. */
extern int cgiContentLength;
/* Pointer to CGI output. The cgiHeader functions should be used
first to output the mime headers; the output HTML
page, GIF image or other web document should then be written
to cgiOut by the programmer. */
extern FILE *cgiOut;
/* Pointer to CGI input. In 99% of cases, the programmer will NOT
need this. However, in some applications, things other than
forms are posted to the server, in which case this file may
be read from in order to retrieve the contents. */
extern FILE *cgiIn;
/* Possible return codes from the cgiForm family of functions (see below). */
typedef enum
{
cgiFormSuccess,
cgiFormTruncated,
cgiFormBadType,
cgiFormEmpty,
cgiFormNotFound,
cgiFormConstrained,
cgiFormNoSuchChoice,
cgiFormMemory
} cgiFormResultType;
typedef enum
{
cgiParseSuccess,
cgiParseMemory,
cgiParseIO
} cgiParseResultType;
/* These functions are used to retrieve form data.
See cgic.html for documentation. */
extern cgiFormResultType cgiFormString(char *name, char *result, int max);
extern cgiFormResultType cgiFormStringNoNewlines(char *name, char *result, int max);
extern cgiFormResultType cgiFormStringSpaceNeeded(char *name, int *length);
extern cgiFormResultType cgiFormStringMultiple(char *name, char ***ptrToStringArray);
extern cgiFormResultType cgiFormInteger(char *name, int *result, int defaultV);
extern cgiFormResultType cgiFormIntegerBounded(char *name, int *result, int min, int max, int defaultV);
extern cgiFormResultType cgiFormDouble(char *name, double *result, double defaultV);
extern cgiFormResultType cgiFormDoubleBounded(char *name, double *result, double min, double max, double defaultV);
extern cgiFormResultType cgiFormSelectSingle(char *name, char **choicesText, int choicesTotal, int *result, int defaultV);
extern cgiFormResultType cgiFormSelectMultiple(char *name, char **choicesText, int choicesTotal, int *result, int *invalid);
extern cgiFormResultType cgiFormCheckboxSingle(char *name);
extern cgiFormResultType cgiFormCheckboxMultiple(char *name, char **valuesText, int valuesTotal, int *result, int *invalid);
extern cgiFormResultType cgiFormRadio(char *name, char **valuesText, int valuesTotal, int *result, int defaultV);
extern void cgiStringArrayFree(char **stringArray);
extern void cgiHeaderLocation(char *redirectUrl);
extern void cgiHeaderStatus(int status, char *statusMessage);
extern void cgiHeaderContentType(char *mimeType);
#ifndef NO_SYSTEM
extern int cgiSaferSystem(char *command);
#endif /* NO_SYSTEM */
typedef enum
{
cgiEnvironmentIO,
cgiEnvironmentMemory,
cgiEnvironmentSuccess
} cgiEnvironmentResultType;
/* One form entry, consisting of an attribute-value pair. */
typedef struct cgiFormEntryStruct
{
char* attr;
char* value;
struct cgiFormEntryStruct* next;
} cgiFormEntry;
extern cgiEnvironmentResultType cgiWriteEnvironment(char *filename);
extern cgiEnvironmentResultType cgiReadEnvironment(char *filename);
extern int cgiMain();
// AITECSA UTILITIES EXTENSION
void itxEscapeChars(char *source, char **destination);
void itxInBlinder(char **source, char blinder);
#endif /* CGI_C */
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.datastruct.narytree;
import java.sql.SQLException;
import jtxlib.main.aux.Tools;
import jtxlib.main.sql.DBConnection;
import jtxlib.main.sql.DataManager;
import jtxlib.main.sql.RecordSet;
/**
* This class maps an n-ary tree data structure onto a relational database table,
* giving to its clients a safe, unique and numeric node identifier together
* with a name (label) and all the necessary functionalities to navigate the tree
* without having to know the inner design of the table and itself.
* It can be used as a lookup table to easily manage knowledge-tree entities or
* complex classification issues.
*
* The way of working relies upon some basic facts fixed by design:
*
* 1) the class must be initialized through the init method, providing a valid
* database connection and the name of the main table.
*
* 2) the main table must contain (at least) the following fields:
*
* *) n_id : numeric auto-sequence (unique node identifier)
* *) n_label : text (name or description associated with the node)
* *) n_depth : numeric (depth of the node, 1-based, i.e. roots are depth 1)
* *) n_pid : numeric (nodeid of the parent node)
*
* @author gambineri
*/
public class NaryTree
{
private final String FN_NODEID = "n_id";
private final String FN_NODELABEL = "n_label";
private final String FN_NODEDEPTH = "n_depth";
private final String FN_NODEPID = "n_pid";
// Error messages
private final String ERR_NO_CONN = "Cannot access database: no connection available.";
private final String ERR_WRONG_DB_STRUCT = "Main table not found or fixed field names missing/mispelled.";
private DBConnection m_Conn = null;
private String m_Tbl = null;
private RecordSet m_TmpRs = null;
/**
* Creates a new instance of NaryTree
* @param conn A DBConnection to the database.
* @param narytree_table Name of the table in which the tree will be stored.
*/
public NaryTree(DBConnection conn, String narytree_table)
{
m_Conn = conn;
m_Tbl = narytree_table;
checkRDBMS();
}
/**
* Checks if the database structure is consistent with the requirements (see general comment on NaryTree)
* and raises an exception with detailed error messages.
* @return True if successful, false otherwise.
*/
private void checkRDBMS()
{
CheckDBConn();
m_TmpRs = new RecordSet(m_Conn);
if (!m_TmpRs.select("SELECT COUNT(*) FROM " + m_Tbl + " WHERE " +
FN_NODEID + " = 0 AND " + FN_NODELABEL + " = '' AND " +
FN_NODEDEPTH + " = 0 AND " + FN_NODEPID + " = 0", 0))
throw new Error(ERR_WRONG_DB_STRUCT);
}
/**
* Adds a root element to the tree.
* @param rootLabel Label for the root element.
* @return returns the node id of the newly created root.
*/
public int addRoot(String rootLabel)
{
int rootid = 0;
try
{
m_TmpRs.executeStatement("BEGIN;", DataManager.StatementType.OTHER);
m_TmpRs.executeStatement(
"INSERT INTO " + m_Tbl +
" (" + FN_NODEDEPTH + ", " + FN_NODELABEL + ", " + FN_NODEPID + ") VALUES (" +
"1, " + m_TmpRs.adjQuotes(rootLabel) + ", 0)",
DataManager.StatementType.INSERT);
m_TmpRs.select("SELECT MAX(" + FN_NODEID + ") FROM " + m_Tbl);
m_TmpRs.first();
rootid = Tools.stringToInt(m_TmpRs.getField(0, 0));
m_TmpRs.executeStatement("COMMIT;", DataManager.StatementType.OTHER);
}
catch (SQLException ex)
{
try {m_TmpRs.executeStatement("ROLLBACK;", DataManager.StatementType.OTHER);}
catch(SQLException ex2) {ex2.printStackTrace();}
ex.printStackTrace();
}
return rootid;
}
/**
* Adds a child node to the given node.
* @param parentNodeId the id of the node that will be the parent of the newly created node.
* @param nodeLabel the label of the newly created node.
* @return the id of the newly created node.
*/
public int addChild(int parentNodeId, String nodeLabel)
{
int nodeid = 0;
try
{
m_TmpRs.executeStatement("BEGIN;", DataManager.StatementType.OTHER);
m_TmpRs.executeStatement(
"INSERT INTO " + m_Tbl +
"(" + FN_NODEDEPTH + ", " + FN_NODELABEL + ", " + FN_NODEPID + ") VALUES (" +
"(SELECT " + FN_NODEDEPTH + " + 1 FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + parentNodeId + "), " +
m_TmpRs.adjQuotes(nodeLabel) + ", " + parentNodeId + ")",
DataManager.StatementType.INSERT);
m_TmpRs.select("SELECT MAX(" + FN_NODEID + ") FROM " + m_Tbl);
m_TmpRs.first();
nodeid = Tools.stringToInt(m_TmpRs.getField(0, 0));
m_TmpRs.executeStatement("COMMIT;", DataManager.StatementType.OTHER);
}
catch (SQLException ex)
{
try {m_TmpRs.executeStatement("ROLLBACK;", DataManager.StatementType.OTHER);}
catch(SQLException ex2) {ex2.printStackTrace();}
ex.printStackTrace();
}
return nodeid;
}
/**
*
* @param nodeid
* @return
*/
public boolean removeNode(int nodeid)
{
try
{
m_TmpRs.executeStatement("DELETE FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid,
DataManager.StatementType.DELETE);
}
catch (SQLException ex)
{
ex.printStackTrace();
return false;
}
return true;
}
/**
*
* @param node
* @return
*/
public boolean removeNode(Node node)
{
try
{
m_TmpRs.executeStatement("DELETE FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + node.m_Id,
DataManager.StatementType.DELETE);
}
catch (SQLException ex)
{
ex.printStackTrace();
return false;
}
return true;
}
/**
*
* @param nodeid
* @return
*/
public Node getNode(int nodeid)
{
return new Node(nodeid);
}
//----------------------------------------------------------------------------
/**
*
* @param nodeid
* @return
*/
public String getNodeLabel(int nodeid)
{
String ret = "";
try
{
m_TmpRs.select("SELECT " + FN_NODELABEL + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid, 1);
ret = m_TmpRs.getField(0, 0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public int getParentId(int nodeid)
{
int ret = 0;
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid, 1);
ret = Tools.stringToInt(m_TmpRs.getField(0, 0));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param node
* @return
*/
public Node getParentNode(Node node)
{
Node ret = null;
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + node.m_Id, 1);
ret = new Node(Tools.stringToInt(m_TmpRs.getField(0, 0)));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public Node getRootNode(int nodeid)
{
int parentid = 0;
int aux = 0;
aux = nodeid;
while ((aux = getParentId(aux)) != 0)
parentid = aux;
return new Node(parentid);
}
/**
*
* @return
*/
public int getRootsCount()
{
int ret = 0;
try
{
m_TmpRs.select("SELECT COUNT(" + FN_NODEID + ") FROM " + m_Tbl +
" WHERE " + FN_NODEDEPTH + " = 1", 1);
ret = Tools.stringToInt(m_TmpRs.getField(0, 0));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @return
*/
public Node[] getRoots()
{
Node[] ret = new Node[getRootsCount()];
try
{
m_TmpRs.select("SELECT " + FN_NODEID + ", " + FN_NODELABEL +
" FROM " + m_Tbl + " WHERE " + FN_NODEDEPTH + " = 1");
int c = 0;
while (m_TmpRs.next())
{
ret[c] = new Node();
ret[c].m_Id = Tools.stringToInt(m_TmpRs.getField(FN_NODEID));
ret[c].m_Pid = 0;
ret[c].m_Depth = 1;
ret[c].m_Label = m_TmpRs.getField(FN_NODELABEL);
c++;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public int getSiblingsCount(int nodeid)
{
int ret = 0;
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid, 1);
m_TmpRs.select("SELECT COUNT(" + FN_NODEID + ") FROM " + m_Tbl +
" WHERE " + FN_NODEPID + " = " + m_TmpRs.getField(0, 0), 1);
ret = Tools.stringToInt(m_TmpRs.getField(0, 0));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret - 1;
}
/**
*
* @param nodeid
* @return
*/
public int[] getSiblingsId(int nodeid)
{
int[] ret = new int[getSiblingsCount(nodeid)];
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid, 1);
m_TmpRs.select("SELECT " + FN_NODEID + " FROM " + m_Tbl +
" WHERE " + FN_NODEPID + " = " + m_TmpRs.getField(0, 0) + " AND " +
FN_NODEID + " <> " + nodeid);
try
{
int c = 0;
while (m_TmpRs.next())
{
ret[c] = Integer.parseInt(m_TmpRs.getField(c, 0));
c++;
}
}
catch(NumberFormatException ex) {ex.printStackTrace();}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public Node[] getSiblings(int nodeid)
{
Node[] ret = new Node[getSiblingsCount(nodeid)];
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + " FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid, 1);
m_TmpRs.select("SELECT " + FN_NODEID + ", " + FN_NODELABEL + ", " + FN_NODEDEPTH +
" FROM " + m_Tbl +
" WHERE " + FN_NODEPID + " = " + m_TmpRs.getField(0, 0) + " AND " +
FN_NODEID + " <> " + nodeid);
int c = 0;
while (m_TmpRs.next())
{
ret[c] = new Node();
ret[c].m_Id = Tools.stringToInt(m_TmpRs.getField(FN_NODEID));
ret[c].m_Pid = nodeid;
ret[c].m_Depth = Tools.stringToInt(m_TmpRs.getField(FN_NODEDEPTH));
ret[c].m_Label = m_TmpRs.getField(FN_NODELABEL);
c++;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public int getChildsCount(int nodeid)
{
int ret = 0;
try
{
m_TmpRs.select("SELECT COUNT(" + FN_NODEID + ") FROM " + m_Tbl +
" WHERE " + FN_NODEPID + " = " + nodeid, 1);
ret = Tools.stringToInt(m_TmpRs.getField(0, 0));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public int[] getChildsId(int nodeid)
{
int[] ret = new int[getChildsCount(nodeid)];
try
{
m_TmpRs.select("SELECT " + FN_NODEID + " FROM " + m_Tbl + " WHERE " + FN_NODEPID + " = " + nodeid);
try
{
int c = 0;
while (m_TmpRs.next())
{
ret[c] = Integer.parseInt(m_TmpRs.getField(c, 0));
c++;
}
}
catch(NumberFormatException ex) {ex.printStackTrace();}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @return the greates value for a node depth.
*/
public int getMaxDepth()
{
int ret = 0;
try
{
m_TmpRs.select("SELECT MAX(" + FN_NODEDEPTH + ") FROM " + m_Tbl, 1);
ret = Tools.stringToInt(m_TmpRs.getField(0, 0));
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
/**
*
* @param nodeid
* @return
*/
public Node[] getChilds(int nodeid)
{
Node[] ret = new Node[getChildsCount(nodeid)];
try
{
m_TmpRs.select("SELECT " + FN_NODEID + ", " + FN_NODEDEPTH + ", " + FN_NODELABEL +
" FROM " + m_Tbl + " WHERE " + FN_NODEPID + " = " + nodeid);
int c = 0;
while (m_TmpRs.next())
{
ret[c] = new Node();
ret[c].m_Id = Tools.stringToInt(m_TmpRs.getField(FN_NODEID));
ret[c].m_Pid = nodeid;
ret[c].m_Depth = Tools.stringToInt(m_TmpRs.getField(FN_NODEDEPTH));
ret[c].m_Label = m_TmpRs.getField(FN_NODELABEL);
c++;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return ret;
}
public void CheckDBConn()
{
if (!m_Conn.isValid())
throw new Error(ERR_NO_CONN);
}
//GETTER ---------------------------------------------------------------------
public String GetDBTableName() {return m_Tbl;}
public String GetDBConnDSN() {return m_Conn.getDSN();}
//Inner class Node ***********************************************************
/**
* An utility class to wrap the concept of NaryTree node.
* Four members are available to easily get node properties.
*/
public class Node
{
public int m_Id = 0;
public int m_Pid = 0;
public int m_Depth = 0;
public String m_Label = "";
//~~~~~~~~~~~~~~~~~~~~~~~~~~
public Node() {}
//~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
*
* @param nodeid
*/
public Node(int nodeid)
{
try
{
m_TmpRs.select("SELECT " + FN_NODEPID + ", " + FN_NODEDEPTH + ", " + FN_NODELABEL +
" FROM " + m_Tbl + " WHERE " + FN_NODEID + " = " + nodeid);
m_TmpRs.first();
m_Id = nodeid;
m_Pid = Tools.stringToInt(m_TmpRs.getField(FN_NODEPID));
m_Depth = Tools.stringToInt(m_TmpRs.getField(FN_NODEDEPTH));
m_Label = m_TmpRs.getField(FN_NODELABEL);
}
catch (Exception ex) {ex.printStackTrace();}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~
// Getter/Setter
/*
public String getId () {return m_Id;}
public String getPid () {return m_Pid;}
public String getLabel() {return m_Label;}
public String getDepth() {return m_Depth;}
// public int getId () {return m_Id;}
// public int getPid () {return m_Pid;}
// public int getDepth () {return m_Depth;}
public void setId (String id) {m_Id = id;}
public void setPid (String pid) {m_Pid = pid;}
public void setLabel(String label) {m_Label = label;}
public void setDepth(String depth) {m_Depth = depth;}
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
*
* @return
*/
public String toString()
{
String ret = "";
for(int j=0; j<m_Depth; j++)
ret += "-";
return ret + "[" + m_Id + "-" + m_Label + "]\n";
}
}
//End of class Node **********************************************************
/**
*
* @param nodeid
* @return
*/
public String hierarchyToString(int nodeid)
{
String ret = (new Node(nodeid)).toString();
Node[] childs = getChilds(nodeid);
if (childs.length == 0)
return ret;
for(int i=0; i < childs.length; i++)
ret += hierarchyToString(childs[i].m_Id);
return ret;
}
/**
*
* @return
*/
public String toString()
{
String ret = "";
Node[] roots = getRoots();
for(int i=0; i<roots.length; i++)
ret += hierarchyToString(roots[i].m_Id);
return ret;
}
} // End of class NaryTree
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include <stdarg.h>
#include "tannit.h"
#include "tannitds.h"
#ifdef _ITX_APPC
#include "itannitc.h"
#endif // _ITX_APPC
#include "extVars.h"
#ifdef _ITX_APPC
void iZLEADPAD(char* a, int b, char* c)
{
char zcode[256];
memset(zcode, '0', b);
zcode[b+1] = 0;
int l = strlen(a);
memcpy(zcode + b - l, a, l);
sprintf(c, "%s", zcode);
}
#endif // _ITX_APPC
/*************************************************************************************
NOME :sendTransStart
Categoria :upload/download service
attivita' :invia un segnale di sincronizzazione al client aleph;
*************************************************************************************/
void sendTransStart(int download, int fileLen)
{
/**/if(usedbg){fprintf(debug, "sendTransStart STARTIN\n");fflush(debug);}
if(strcmp(UserAgentSpy,"Aleph")==0 )
{
/**/if(usedbg){fprintf(debug, "sendTransStart %d\n", fileLen);fflush(debug);}
if (!download)
cgiHeaderContentType("text/html");
/**/if(usedbg){fprintf(debug, "%s:%d;", ALEPH_START_COM, fileLen);fflush(debug);}
fprintf(cgiOut, "%s:%d;", ALEPH_START_COM, fileLen);
}
}
/*************************************************************************************
NOME :sendBack
Categoria :upload/download service
attivita' :invia un segnale di sincronizzazione al client aleph;
*************************************************************************************/
void sendBack(int flagCode)
{
/**/if(usedbg){fprintf(debug, "sendBack STARTIN\n");fflush(debug);}
if(strcmp(UserAgentSpy,"Aleph")==0 )
{
/**/if(usedbg){fprintf(debug, "sendBack %d\n", flagCode);fflush(debug);}
/**/if(usedbg){fprintf(debug, "%s:%d;\r\n", ALEPH_END_COM, flagCode );fflush(debug);}
fprintf(cgiOut, "%s:%d;\r\n", ALEPH_END_COM, flagCode );
//fflush(cgiOut);
EXIT(0);
}
}
int sendFile() //download to the remote operator
{
char *corrCode;
FILE * fp;
char buffer[4096];
long int byteRead, totalBytesRead=0;
char cpwd[GET_PAR_VAL_LEN], login[GET_PAR_VAL_LEN];
char fileName[GET_PAR_VAL_LEN], queryString[GET_PAR_VAL_LEN];
int errCode;
char *dndStatus;
/**/if(usedbg){fprintf(debug, "sendFile STARTIN'\n");fflush(debug);}
/**/if(usedbg){fprintf(debug, "---------------->Llu=%s; Rtp=%s\n", Llu, Rtp);fflush(debug);}
// Lettura parametri di ingresso
if (cgiFormString( LOGIN_TAG, login, 0) != cgiFormSuccess)
{
sendBack(LOGIN_ERROR);
EXIT(0);
}
if (cgiFormString( CPWD_TAG, cpwd, 0) != cgiFormSuccess)
{
sendBack(LOGIN_ERROR);
EXIT(0);
}
//
// Controllo che la password nel DB sia la stessa di input
//
if ( checkDbPwd(login, cpwd, "1", "1") == NOT_VALIDATED )
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
//
// Il codice del corrispondente relativo al login viene messo sulla stringa corrCode
//
sprintf(queryString,"select %s from %s where %s = '%s'",
CorrCodeField, CorrTable, CorrUserField, login);
dbInterface("corrUpload", queryString, 1, 1);
corrCode = storedData(1, CorrCodeField, "corrUpload", &errCode);
char ccode[7];
memset(ccode, '\0', 7);
#ifdef _ITX_APPC
iZLEADPAD(corrCode, 3, ccode);
ITannit_CreateEnv(QueryResultSet, &QueryCounter, Llu, Rtp);
ITannit_StoreRecord("C00", "C00", login, NULL);
ITannit_StoreRecord("C02", "C02", login, ccode, NULL);
iZLEADPAD(corrCode, 6, ccode);
ITannit_SetUser(ccode);
#endif // _ITX_APPC
sprintf(fileName, ".\\dnddir\\%s.new", login);
// Si chiede all'SQL se e' disponibile un file gia' ricevuto da AS400
sprintf(queryString,"select %s from %s where %s = '%s'",
CorrDndStatus, CorrTable, CorrUserField, login);
dbInterface("getDndStatus", queryString, 1, 1);
dndStatus = storedData(1, CorrDndStatus, "getDndStatus", &errCode);
//se lo stato e' : file non presente su disco lo si chiede all'AS400
/**/if(usedbg){fprintf(debug, "Z-queryString: %s\n", queryString);fflush(debug);}
/**/if(usedbg){fprintf(debug, "Colonna: %s\n", CorrDndStatus);fflush(debug);}
/**/if(usedbg){fprintf(debug, "dndStatus: %s\n", dndStatus);fflush(debug);}
#ifdef _ITX_APPC
if ( strcmp(dndStatus, DND_FILE_READY) != 0 )
{
if (!ITannit_ReceiveFileFromAS400(fileName, debug))
{
char* e00 = NULL;
e00 = storedData(1, "f1", "E00", &errCode);
if (e00 == NULL)
{
//connessione con AS400 fallita o impossibile scrivere file su disco
sendTransStart(0, 0);
sendBack(SERVER_ERROR);
EXIT(0);
}
else
{
//connessione con AS400 fallita o impossibile scrivere file su disco
sendTransStart(0, 0);
sendBack(USER_NOT_ENABLED);
EXIT(0);
}
}
fileAvail = storedData(1, "f4", "C01", &errCode);
if ( strcmp(fileAvail, "Y") != 0 )
{
/**/if(usedbg){ITannit_Dump(debug);}
//file not available on the AS400
sendTransStart(0, 0);
sendBack(NO_FILE_AVAIL);
EXIT(0);
}
//si comunica all'SQL che i dati sono pronti per essere inviati
sprintf(queryString,"update %s set %s = %s where %s = '%s'",
CorrTable, CorrDndStatus, DND_FILE_READY, CorrUserField, login);
dbInterface("dndStatusReady", queryString, 1, 1);
//if(usedbg){fprintf(debug, "Y-queryString: %s\n", queryString);fflush(debug);}
}
/**/if(usedbg){ITannit_Dump(debug);}
#endif // _ITX_APPC
if ( (fp = fopen(fileName,"rb")) == NULL )
{
sendBack(FATAL_ERROR);
EXIT(0);
}
fprintf(cgiOut, "Content-disposition: filename=pcorbak\n");
cgiHeaderContentType("application/itxApplication");
//
// Valutazione del numero di byte del file
//
long int fileLen = 0;
fileLen = ftell(fp);
fseek(fp, 0, SEEK_END);
fileLen = ftell(fp) - fileLen;
rewind(fp);
sendTransStart(1, fileLen);
//fflush(cgiOut);
while (!feof(fp))
{
byteRead = fread(buffer, sizeof(char), 4096, fp);
fwrite(buffer, sizeof(char), byteRead, cgiOut);
fwrite(buffer, sizeof(char), byteRead, debug);
//fflush(cgiOut);
totalBytesRead += byteRead;
}
fclose(fp);
#ifdef _ITX_APPC
/**/if(usedbg){ITannit_Dump(debug);}
ITannit_Destroy();
#endif // _ITX_APPC
sendBack(FILE_DOWNLOADED);
return 1;
}
/*************************************************************************************
NOME :receiveAPPCFile
Categoria :upload/download service
attivita' :upload from the remote operator per i corrispondenti
return :
*************************************************************************************/
int receiveAPPCFile()
{
char *corrCode;
char login[GET_PAR_VAL_LEN];
char cpwd[GET_PAR_VAL_LEN];
char queryString[GET_PAR_VAL_LEN];
int errCode;
char uploadFileName[GET_PAR_VAL_LEN];
/**/if(usedbg){fprintf(debug, "receiveAPPCFile STARTING\n");fflush(debug);}
/**/if(usedbg){fprintf(debug, "---------------->Llu=%s; Rtp=%s\n", Llu, Rtp);fflush(debug);}
sendTransStart(0, 0);
// Lettura parametri di ingresso per il client aleph
if (cgiFormString( LOGIN_TAG, login, 0) != cgiFormSuccess) sendBack(LOGIN_ERROR);
if (cgiFormString( CPWD_TAG, cpwd, 0) != cgiFormSuccess) sendBack(LOGIN_ERROR);
if (cgiFormString( ITX_UPLOAD_FILE_TAG, uploadFileName, 0) != cgiFormSuccess)
sendBack(LOGIN_ERROR);
//
// Controllo che la password nel DB sia la stessa di input
//
if ( checkDbPwd(login, cpwd, "1", "1") == NOT_VALIDATED )
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
//
// Il codice del corrispondente relativo al login viene messo sulla stringa corrCode
//
sprintf(queryString,"select %s from %s where %s = '%s'",
CorrCodeField, CorrTable, CorrUserField, login);
dbInterface("corrUpload", queryString, 1, 1);
corrCode = storedData(1, CorrCodeField, "corrUpload", &errCode);
#ifdef _ITX_APPC
ITannit_CreateEnv(QueryResultSet, &QueryCounter, Llu, Rtp);
char ccode[7];
memset(ccode, '\0', 7);
iZLEADPAD(corrCode, 3, ccode);
ITannit_StoreRecord("C00", "C00", login, NULL);
ITannit_StoreRecord("C03", "C03", login, ccode, NULL);
iZLEADPAD(corrCode, 6, ccode);
ITannit_SetUser(ccode);
if(!ITannit_SendFileToAS400(uploadFileName, debug))
{
char* e00 = NULL;
e00 = storedData(1, "f1", "E00", &errCode);
if (e00 == NULL)
{
//connessione con AS400 fallita o impossibile scrivere file su disco
sendTransStart(0, 0);
sendBack(SERVER_ERROR);
EXIT(0);
}
else
{
//connessione con AS400 fallita o impossibile scrivere file su disco
sendTransStart(0, 0);
sendBack(USER_NOT_ENABLED);
EXIT(0);
}
}
/**/if(usedbg){ITannit_Dump(debug);fflush(debug);}
ITannit_Destroy();
#endif // _ITX_APPC
// svuotamento del file
FILE * fp;
fp = fopen(uploadFileName, "w");
fclose(fp);
/**/if(usedbg){fprintf(debug, "receiveAPPCFile EXITING\n");fflush(debug);}
sendBack(FILE_UPLOADED);
return (1);
}
/*************************************************************************************
Categoria :upload/download service
attivita' :upload from the remote operator [non operativo]
return :
*************************************************************************************/
int receiveFile()
{
return (1);
}
int dndConfirm()
{
char *corrCode;
char login[GET_PAR_VAL_LEN];
char cpwd[GET_PAR_VAL_LEN];
char queryString[GET_PAR_VAL_LEN];
int errCode;
/**/if(usedbg){fprintf(debug, "dndConfirm STARTING\n");fflush(debug);}
/**/if(usedbg){fprintf(debug, "---------------->Llu=%s; Rtp=%s\n", Llu, Rtp);fflush(debug);}
sendTransStart(0, 0);
// Lettura parametri di ingresso
if (cgiFormString( LOGIN_TAG, login, 0) != cgiFormSuccess) sendBack(LOGIN_ERROR);
if (cgiFormString( CPWD_TAG, cpwd, 0) != cgiFormSuccess) sendBack(LOGIN_ERROR);
//
// Controllo che la password nel DB sia la stessa di input
//
if ( checkDbPwd(login, cpwd, "1", "1") == NOT_VALIDATED )
{
sendTransStart(0, 0);
sendBack(LOGIN_ERROR);
EXIT(0);
}
//
// Il codice del corrispondente relativo al login viene messo sulla stringa corrCode
//
sprintf(queryString,"select %s from %s where %s = '%s'",
CorrCodeField, CorrTable, CorrUserField, login);
dbInterface("corrUpload", queryString, 1, 1);
corrCode = storedData(1, CorrCodeField, "corrUpload", &errCode);
#ifdef _ITX_APPC
ITannit_CreateEnv(QueryResultSet, &QueryCounter, Llu, Rtp);
char ccode[7];
memset(ccode, '\0', 7);
ITannit_StoreRecord("C00", "C00", login, NULL);
iZLEADPAD(corrCode, 6, ccode);
ITannit_SetUser(ccode);
ITannit_SendHOK(debug, ITX_APPC_PC_FTX);
/**/if(usedbg){ITannit_Dump(debug);}
ITannit_Destroy();
#endif // _ITX_APPC
//si comunica all'SQL che i dati sono stati inviati
sprintf(queryString,"UPDATE %s SET %s = %s, ultimoUpload=getDate() WHERE %s = '%s'",
CorrTable, CorrDndStatus, DND_FILE_DONE, CorrUserField, login);
dbInterface("dndStatusDone", queryString, 1, 1);
/**/if(usedbg){fprintf(debug, "dndConfirm EXITING\n");fflush(debug);}
sendBack(DND_CONFIRMED);
return (1);
}<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsmtp.cpp,v $
* $Revision: 1.6 $
* $Author: andreal $
* $Date: 2002-05-17 19:24:46+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#include "itxsmtp.h"
itxSmtp::itxSmtp(char* server, char* domain, char* sender)
{
m_socket = NULL;
m_sender = sender;
m_server = server;
m_domain = domain;
m_to = NULL;
m_subject.SetEmpty();
m_body.SetEmpty();
m_attachments[0] = NULL;
m_NumAttach = 0;
m_AttachedData = NULL;
m_AttachedDataLen = 0;
}
itxSmtp::~itxSmtp()
{
if (m_socket != NULL)
delete m_socket;
RemoveAttachments();
}
void itxSmtp::AddRcpt(char* to)
{
Recipient* newrcp = NULL;
Recipient** cursor = &m_to;
try
{
newrcp = (Recipient*) new Recipient(to);
while (*cursor != NULL)
cursor = &((*cursor)->m_next);
*cursor = newrcp;
}
catch(...)
{
throw new itxException(0, "itxSmtp::AddRcpt");
}
}
int itxSmtp::ExchangeMessage(char* cmd, char* arg)
{
itxString datatosend;
itxString datareceived;
datatosend = cmd;
datatosend += " ";
datatosend += arg;
datatosend += "\r\n";
m_socket->Send(&datatosend);
m_socket->Receive(&datareceived);
return atoi(datareceived.GetBuffer());
}
bool itxSmtp::AddAttachment(char* attachment)
{
itxString* pAtt = new itxString;
if (pAtt != NULL)
{
*pAtt = attachment;
m_attachments[m_NumAttach++] = pAtt;
m_attachments[m_NumAttach] = NULL;
return true;
}
return false;
}
bool itxSmtp::RemoveAttachments()
{
for (int i=0; i<m_NumAttach; i++)
{
delete m_attachments[i];
m_attachments[i] = NULL;
}
m_NumAttach = 0;
return true;
}
int itxSmtp::Mail()
{
int retcode = 0;
int bytesreceived;
itxString datareceived;
itxString data;
Recipient** cursor = &m_to;
try
{
m_socket = new itxSocket(m_server.GetBuffer(), ITXM_SMTPPORT);
m_socket->SetReceiveTimeout(20, 0);
m_socket->SetReceiveCycleTimeout(0, 0);
// receive welcome
bytesreceived = m_socket->Receive(&datareceived);
// presentation
EXIT_ON_CRITICAL(ExchangeMessage("HELO", m_domain.GetBuffer()));
// header and message body
EXIT_ON_CRITICAL(ExchangeMessage("MAIL FROM:", m_sender.GetBuffer()));
cursor = &m_to;
while (*cursor != NULL)
{
EXIT_ON_CRITICAL(ExchangeMessage("RCPT TO:", (*cursor)->m_address.GetBuffer()));
cursor = &((*cursor)->m_next);
}
data += "From: ";
data += m_sender;
data += "\n";
data += "To: ";
cursor = &m_to;
while (*cursor != NULL)
{
data += (*cursor)->m_address;
cursor = &((*cursor)->m_next);
if (*cursor != NULL) data += ", ";
}
data += "\n";
data += "Subject: ";
data += m_subject;
data += "\n";
data += MIME_VERSION;
if(m_attachments[0] != NULL)
{
data += "Content-Type: multipart/mixed; boundary=\"";
data += BOUNDARY;
data += "\"\n";
}
data += "\r\n";
// body
EXIT_ON_CRITICAL(ExchangeMessage("DATA", ""));
if(m_attachments[0] != NULL)
{
data += "--";
data += BOUNDARY;
data += '\n';
data += "Content-Type: text/plain";// charset=\"iso-8859-1\"";
data += '\n';
data += "Content-Transfer-Encoding: quoted-printable";
data += '\n';
data += "\r\n";
}
data += m_body;
data += '\n';
data += "\r\n";
m_socket->Send(data.GetBuffer(), data.Len());
//Invio di eventuali attachments
if(m_attachments[0] != NULL)
SendAttachments();
EXIT_ON_CRITICAL(ExchangeMessage("", "\r\n."));
// salutation
EXIT_ON_CRITICAL(ExchangeMessage("QUIT", ""));
}
catch(itxException* e)
{
throw e;
}
return retcode;
}
bool itxSmtp::EncodeBase64(int attidx)
{
FILE* fp;
if( (fp = fopen((*m_attachments[attidx]).GetBuffer(), "rb" )) == NULL )
return false;
fseek(fp, 0, SEEK_SET);
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
if ((m_AttachedData = (unsigned char*)malloc(len*2)) == NULL)
return false;
fseek(fp, 0, SEEK_SET);
EncodeFromFile(fp);
fclose(fp);
return true;
}
/*
** base64 encode a stream adding padding and line breaks as per spec.
*/
//--------------------------------------------------------
void itxSmtp::EncodeBlock(unsigned char in[3], unsigned char out[4], int len)
{
static const char cb64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
out[0] = cb64[ in[0] >> 2 ];
out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
}
//--------------------------------------------------------
void itxSmtp::EncodeFromFile(FILE* infile)
{
unsigned char in[3];
int i, len, blocksout = 0;
m_AttachedDataLen = 0; //paranoic
while (!feof(infile))
{
len = 0;
for (i = 0; i < 3; i++)
{
in[i] = (unsigned char) getc(infile);
if (!feof(infile))
len++;
else
in[i] = 0;
}
if (len)
{
EncodeBlock(in, &m_AttachedData[m_AttachedDataLen], B64_DEF_LINE_SIZE);
m_AttachedDataLen += 4;
blocksout++;
}
if (blocksout >= (B64_DEF_LINE_SIZE/4) || feof(infile))
{
if (blocksout)
{
m_AttachedData[m_AttachedDataLen++] = (unsigned char)'\r';
m_AttachedData[m_AttachedDataLen++] = (unsigned char)'\n';
}
blocksout = 0;
}
}
}
bool itxSmtp::SendAttachments()
{
itxString data;
itxString fname;
int i=0;
while(m_attachments[i] != NULL)
{
if (!EncodeBase64(i))
continue;
fname = *m_attachments[i];
fname.Right(fname.Len() - fname.RightInstr("\\"));
data = "--";
data += BOUNDARY;
data += '\n';
// data += "Content-Type: text/plain"; //Forse bisognera' differenziarli...
data += "Content-Type: ; name=\""; //Forse bisognera' differenziarli...
data += fname;
data += "\"";
data += '\n';
data += "Content-Transfer-Encoding: Base64";
data += '\n';
data += "Content-Disposition: attachment; filename=\"";
data += fname;
data += "\"\r\n\r\n";
m_socket->Send(data.GetBuffer(), data.Len());
m_socket->Send((char*)m_AttachedData, m_AttachedDataLen);
m_socket->Send("\r\n\r\n", 4);
data.SetEmpty();
i++;
if (m_AttachedData != NULL)
{
free(m_AttachedData);
m_AttachedDataLen = 0;
}
}
//Chiusura blocchi multipart
data += "--";
data += BOUNDARY;
data += "--\n\r\n";
m_socket->Send(data.GetBuffer(), data.Len());
return true;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// AITECSA s.r.l. 1999
// filename: itannit.h
// description: tannit data structure AS400/SQL interface library
// internal interface object ITannit definition
// project: ASWEB
#ifndef __ITX_ITANNIT_H__
#define __ITX_ITANNIT_H__
#include <stdio.h>
#include <stdarg.h>
#include "tntsql.h"
#include "itxtypes.h"
#include "iregtp.h"
#include "tannitds.h"
class ITannit
{
private:
PTannitQueryResult* m_qres;
int* m_qcount;
TannitQueryResult* m_current;
char m_user[7];
public:
ITannit() { m_qres = NULL; m_qcount = NULL; m_current = NULL;
memset(m_user, '\0', 7);};
ITannit(PTannitQueryResult* qres, int* count)
{
m_qres = qres;
m_qcount = count;
m_current = NULL;
if (m_qres != NULL)
m_current = qres[0];
memset(m_user, '\0', 7);
}
TannitQueryResult* FindEntry(char* name);
int Store(TannitQueryResult* qres);
TannitQueryResult* AllocateNewEntry(itxTP* tpset, char* name);
TannitQueryResult* AllocateNewEntry(char* queryname, int numfields, ...);
TannitQueryResult* AllocateNewEntry(itxSQLConnection* psqlconn, char* queryname, char* query, int firstRec, int recsToStore);
TannitQueryResult* Duplicate(TannitQueryResult* qsrc, char* destination);
bool AllocateNewRecord(TannitQueryResult* qres);
int StoreField(TannitQueryResult* qres, char* token, int position);
int AllocateFieldSpace(TannitQueryResult* qres, int space, int position);
bool CopyRecord(TannitQueryResult* qsrc, TannitRecord* source, TannitQueryResult* qres);
void DoEmpty();
void RemoveEntry(TannitQueryResult* qres);
void RemoveCurrentRec(TannitQueryResult* qres);
bool CheckCurrentRec(int numfield);
char* GetValue(char* name, int row, int field);
void SetValue(char* name, int row, int field, char* entry);
int GetColPos(TannitQueryResult* qres, char* fieldname);
TannitRecord* GetRecordNumber(char* table, int row);
TannitRecord* GetRecordNumber(TannitQueryResult* qres, int row);
bool Serialize(char* name);
bool SerializeRecord(char* record, int pos);
bool Dump(FILE* fp);
bool DumpTable(FILE* fp, char* name);
int BuildDataToSend(char* packet, va_list tables);
bool BuidHeaderToSend(char* packet, int progr, PACKET_TYPE ptype);
bool BuidCorrHeaderToSend(char* packet, int progr, PACKET_TYPE ptype);
bool BuildPacketToSend(char* packet, int progr, PACKET_TYPE ptype, va_list tables);
bool BuildSinglePacketToSend(char* packet, PACKET_TYPE ptype, char* name);
int BuildSingleData(char* packet, char* tablename);
// SQL SERVER Interface
int ITannit::GetIndex(char* name);
TannitQueryResult* Get() { return m_current; };
TannitQueryResult* Get(int i)
{
return m_qres[i];
}
int GetCount() { return *m_qcount; };
void Init(PTannitQueryResult* qres, int* count)
{
m_qres = qres;
m_qcount = count;
m_current = NULL;
if (m_qres != NULL)
m_current = qres[0];
memset(m_user, '\0', 7);
}
void SetUser(char* user)
{ strcpy(m_user, user); }
void Set(TannitQueryResult* qres)
{
m_current = qres;
}
bool SkipSQLRecords(itxSQLConnection* psqlconn, int start, int end);
bool SelectFromSQL(itxSQLConnection* psqlconn, char* queryname, char* query, int firstRec, int recsToStore);
bool ExecuteSQL(itxSQLConnection* psqlconn, char* stm);
int ExecuteQuery(itxSQLConnection* psqlconn, char* queryname, char* query, int firstRec, int recsToStore);
short int GetSQLCols(itxSQLConnection* psqlconn);
bool GetSQLColInfo(itxSQLConnection* psqlconn, short int col, char* name, short* type, long int* size);
bool MoreResultSQL(itxSQLConnection* psqlconn);
};
#endif //__ITX_ITANNIT_H__
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.test.testjtx;
import jtxlib.main.aux.Debug;
import jtxlib.main.tcp.SocketClient;
import jtxlib.main.tcp.SocketServer;
public class testSocket
{
Debug m_Dbg = new Debug();
SocketServer m_Server;
SocketClient m_Client;
public void runTest(String args[])
{
if (args[0].equals("server"))
{
m_Server = new SocketServer();
m_Server.init(1234);
m_Server.accept();
Debug.Dbg(m_Server.receiveLine());
m_Server.send("damme un sett'ottocentomila lire");
try{Thread.sleep(1000);}catch(InterruptedException ie){}
}
else if (args[0].equals("client"))
{
m_Client = new SocketClient();
m_Client.connect("localhost", 1234);
m_Client.send("che te debbo da`?");
Debug.Dbg(m_Client.receiveLine());
}
else if (args[0].equals("tannit"))
{
m_Client = new SocketClient();
//Tannit connection
m_Client.connect("cannonau.aitecsa.com", 80);
//cosi` arriva pure l'header http
m_Client.send("GET /cgi-bin/tannit.exe?tpl=cico HTTP/1.0\r\nHost: cannonau.aitecsa.com \r\nUser-Agent: testjtx\r\n\r\n");
//cosi` arriva solo il contenuto
// m_Client.send("GET /cgi-bin/tannit.exe?tpl=cico");
// m_Client.send("GET /cgi-bin/tannit.exe?mime=image%2Fgif");
//
// byte rets[] = new byte[5000];
// byte appo[] = new byte[5000];
// int read = 0;
// int curs = 0;
//
// while ((read = m_Client.receiveBytes(appo)) != -1)
// {
// for(int i=0; i<read; i++)
// rets[curs + i] = appo[i];
// curs += read;
// }
//
// byte imma[] = new byte[curs];
// for(int i=0; i<curs; i++)
// imma[i] = rets[i];
//
// m_Dbg.Dbg("->> " + curs);
//
// Debug fd = new Debug("U:\\massimo\\images\\aaa.gif");
// fd.send2file(new String(imma));
}
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_TANNITDS_H__
#define __ITX_TANNITDS_H__
#define COL_NAME_LEN 128
#define QUERY_NAME_LEN 64
#define QUERY_NUMBER 10000
#define STARTING_ROW 1
#define ROWS_TO_STORE 512
typedef struct Record
{
char ** row;
struct Record * next;
} TannitRecord;
typedef struct ColummnHeader
{
char name[COL_NAME_LEN];
short sqlDataType;
long int colummnSize;
} TannitColumnHeader;
typedef struct QueryResult
{
char id[QUERY_NAME_LEN];
int startingRow, rowsToStore;
int actualRow, totalRows;
int colsNumber;
TannitRecord* current_record;
TannitRecord* recPtr;
TannitColumnHeader* queryHeader;
} TannitQueryResult, *PTannitQueryResult;
#endif //__ITX_TANNITDS_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
- PROJECT : itxWeb - Tannit
- FILENAME : initialize.c
- TAB : 2, no spaces
- DESCRIPTION : funzioni di inizializzazione
*****************************************************************************/
#include "tannit.h"
#include "extVars.h"
#define ERR_POS_PAR_FILE "Errore:impossibile posizionare il file di inizializzazione\n"
/*************************************************************************************
NOME :initGlobals
attivita' :inizializzazione delle variabili globali per la gestione dell'array di
puntatori a query, dei cicli, dei blocchi condizionati.
chiamante :cgiMain.
*************************************************************************************/
int initGlobals()
{
QueryCounter = 0;
for (CndLevel = 0; CndLevel < CYC_NESTING_DEPTH; CndLevel++) ValidBlock[CndLevel] = 1;
for (CycLevel = 0; CycLevel < CYC_NESTING_DEPTH; CycLevel++) ReadCycle[CycLevel] = 1;
CndLevel = 0;
CycLevel = 0;
ReadCycle[0] = 1;
LockLoop = 0;
TplVars.idx = 0;
TplNest = 0;
//**/if(usedbg){fprintf(debug, "initGlobals 1;\n");fflush(debug);}
memset( QueryResultSet, 0, sizeof( TannitQueryResult* ) * QUERY_NUMBER);
//**/if(usedbg){fprintf(debug, "initGlobals 2;\n");fflush(debug);}
return 1;
}
/*************************************************************************************
NOME :readPar
attivita' :ricerca nel 'initFile' del valore del parametro 'parId'; 'lanId' identifica
il suffisso eventuale per il linguaggio
chiamante :readIniPars
*************************************************************************************/
char * readPar (const char * parId, const char * lanId, FILE * initFile){
char *token, *retVal = 0;
char fileLine[INIT_FILE_LINE_LEN];
char static parValue[PAR_NAME_LEN];
char langParId[PAR_NAME_LEN];
fpos_t pos;
// ogni volta che viene chiamato readPar viene messo il puntatore al file all'inizio
pos = 0;
if( fsetpos( initFile, &pos ) != 0 )
{
fprintf(cgiOut,"%s\n", ERR_POS_PAR_FILE);//fflush(cgiOut);
EXIT(__LINE__);
}
// se lanId � diverso da "" si devono cercare i nomi dei parametri composti dal
// nome originale concatenato con la stringa _lanId (es. BGMAIN diventa BGMAIN_E oppure BGMAIN_2)
sprintf(langParId, "%s_%s", parId, lanId);
parValue[0] = 0;
// scansione delle linee del file
while ( fgets (fileLine, INIT_FILE_LINE_LEN, initFile) != 0 )
{
// se il primo carattere e' '#' la linea non va letta: e' un commento
if ( fileLine[0] == '#' )
continue;
// il segno di uguale determina la fine del token candidato a id del parametro:
// si confronta il token con il parametro da cercare
token = strtok (fileLine, "=");
if ( ( strcmp( token, parId ) == 0 ) || ( strcmp( token, langParId ) == 0 ) )
{
retVal = strtok ('\0',"\n");
if (retVal != NULL) strcpy (parValue, retVal);
else strcpy (parValue, "");
// nel caso il parametro individuato sia quello con la specificazione della lingua
// si interrompe la ricerca in modo da dare precedenza alla versione con lingua
// rispetto a quella di default (che viene scelta solo se non c'e' la versione con la lingua)
if ( strcmp( token, langParId ) == 0 )
break;
}
}
// se il valore del parametro e' nullo si forza a ""
if (retVal == NULL) return("");
//**/if(usedbg){fprintf(debug, "returning:%s;\n", retVal);fflush(debug);}
return (parValue);
}
/*************************************************************************************
NOME :readIniPars
attivita' :funzione per la lettura dei parametri dal file .ini
chiamante :cgiMain
chiama :readPar
note :assegna valori a molte variabili globali; apre il file all'inizio e lo
chiude alla fine
*************************************************************************************/
int readIniPars()
{
char lanId[LANID_LEN];
char initFileName[INIT_FILE_NAME_LEN]; /*nome del file di inizializazione*/
char initFileN[INIT_FILE_NAME_LEN]; /*nome del file di inizializazione con l'estensione*/
FILE *initFile; /*file di inizializazione*/
// il nome del file di inizializzazione viene ricavato dal valore di get PAR_FILE_TAG se
// PAR_FILE non e' presente nella get si usa il file di default DEF_PAR_FILE
if (cgiFormString(PAR_FILE_TAG, initFileName, GET_VAR_LEN)!=cgiFormSuccess)
sprintf(initFileN,"%s.%s", DEF_PAR_FILE, DEF_PAR_FILE_EXT);
else
sprintf(initFileN,"%s.%s", initFileName, DEF_PAR_FILE_EXT);
initFile = fopen(initFileN, "r");
if(!initFile) return(0);
// estrazione dalla stringa di get del valore del parametro opzionale
// CONC_LAN_ID_TAG (concatenated language id)
memset(lanId, 0, LANID_LEN);
if (cgiFormString(CONC_LAN_ID_TAG, lanId, LANID_LEN - 1) != cgiFormSuccess) strcpy(lanId,"");
strcpy (WebUrl, readPar("WEBURL" ,lanId, initFile) );//riferimento al sito web
strcpy (WebHome, readPar("WEBHOME" ,lanId, initFile) );//riferimento alla root web
strcpy (CgiDir, readPar("CgiDir" ,lanId, initFile) );//nome della directory cgi
strcpy (CgiName, readPar("CgiName" ,lanId, initFile) );//nome dell'eseguibile cgi
strcpy (ImgDir, readPar("IMGDIR" ,lanId, initFile) );//directory delle immagini
strcpy (SSDir, readPar("SSDIR" ,lanId, initFile) );//directory degli style sheet
strcpy (TplDir, readPar("TPLDIR" ,lanId, initFile) );// directory dei template
strcpy (CrudeTplDir, readPar("CrudeTplDir" ,lanId, initFile) );// directory dei template da preprocessare
strcpy (PrepropKey, readPar("PrepropKey" ,lanId, initFile) );// chiave di autorizzazione al preprocessing
strcpy (PreviewKey, readPar("PreviewKey" ,lanId, initFile) );// chiave di autorizzazione al previewing
strcpy (NormviewKey, readPar("NormviewKey" ,lanId, initFile) );// chiave di autorizzazione alla visualizzazione standard
strcpy (PrepKeyTag, readPar("PrepKeyTag" ,lanId, initFile) );// tag della get per la chiave di autorizzazione al preprocessing
strcpy (FileDir, readPar("FILEDIR" ,lanId, initFile) );// directory dei file
strcpy (DbgPath, readPar("DbgPath" ,lanId, initFile) );// path del file di debug
strcpy (CooTimeDelay, readPar("CooTimeDelay" ,lanId, initFile) );
strcpy (CooURLEscape, readPar("CooURLEscape" ,lanId, initFile) );
strcpy (BgMain, readPar("BGMAIN" ,lanId, initFile) );// background principale
strcpy (BgMenu, readPar("BGMENU" ,lanId, initFile) );// background menu
strcpy (BgTop, readPar("BGTOP" ,lanId, initFile) );/*background top*/
strcpy (BgLeft, readPar("BGLEFT" ,lanId, initFile) );/*background left*/
strcpy (BgRight, readPar("BGRIGHT" ,lanId, initFile) );/*background right*/
strcpy (BgBott, readPar("BGBOTT" ,lanId, initFile) );/*background bottom*/
strcpy (Odbcdsn, readPar("ODBCDSN" ,lanId, initFile) );/*odbc dsn*/
strcpy (Odbcuid, readPar("ODBCUID" ,lanId, initFile) );/*odbc uid*/
strcpy (Odbcpwd, readPar("ODBCPWD" ,lanId, initFile) );/*odbc pwd*/
strcpy (LoginTable, readPar("LoginTable" ,lanId, initFile) );/*tabella di verifica del login*/
strcpy (PwdField, readPar("PwdField" ,lanId, initFile) );/*campo password*/
strcpy (LoginField, readPar("LoginField" ,lanId, initFile) );/*campo login*/
strcpy (ExtrTable, readPar("ExtrTable" ,lanId, initFile) );/*tabella di default per l'estrazione dell'id*/
strcpy (IdField, readPar("IdField" ,lanId, initFile) );/*campo id da cui estrarre il valore*/
strcpy (ExtrField, readPar("ExtrField" ,lanId, initFile) );/*campo di default da usare come condizione per l'identificazione del record di cui estrarre l'id*/
strcpy (LangTagGet, readPar("LangTagGet" ,lanId, initFile) );/*etichetta della stringa di get per la lingua*/
strcpy (LangTable, readPar("LangTable" ,lanId, initFile) );/*tabella delle lingue*/
strcpy (LangNameField, readPar("LangNameField" ,lanId, initFile) );/*campo nome della tabella delle lingue*/
strcpy (LangCodeField, readPar("LangCodeField" ,lanId, initFile) );/*campo codice della tabella delle lingue*/
strcpy (TransTable, readPar("TransTable" ,lanId, initFile) );/*tabella per le traduzioni*/
strcpy (TransTagField, readPar("TransTagField" ,lanId, initFile) );/*campo etichetta della tabella per le traduzioni*/
strcpy (DefaultLanguageId, readPar("DefaultLanguageId" ,lanId, initFile) );/*id della lingua di default*/
strcpy (FFace1, readPar("FFace1" ,lanId, initFile) );
strcpy (FFace2, readPar("FFace2" ,lanId, initFile) );
strcpy (FSize, readPar("FSize" ,lanId, initFile) );
strcpy (FStyle, readPar("FStyle" ,lanId, initFile) );
strcpy (FColor, readPar("FColor" ,lanId, initFile) );
strcpy (FDecor, readPar("FDecor" ,lanId, initFile) );
strcpy (Lheight, readPar("Lheight" ,lanId, initFile) );
strcpy (TargetTplField, readPar("TargetTplField" ,lanId, initFile) );
strcpy (TplTable, readPar("TplTable" ,lanId, initFile) );
strcpy (TplTableId, readPar("TplTableId" ,lanId, initFile) );
strcpy (TplTableName, readPar("TplTableName" ,lanId, initFile) );
strcpy (ContextField, readPar("ContextField" ,lanId, initFile) );
strcpy (ContextTag, readPar("ContextTag" ,lanId, initFile) );
strcpy (UploadDir, readPar("UploadDir" ,lanId, initFile) );/*directory di destinazione dei file di upload*/
strcpy (AllowUpload, readPar("AllowUpload" ,lanId, initFile) );
strcpy (CorrTable, readPar("CorrTable" ,lanId, initFile) );/*tabella dei corrispondenti*/
strcpy (CorrUserField, readPar("CorrUserField" ,lanId, initFile) );/*campo user della tabella dei corrispondenti*/
strcpy (CorrDndStatus, readPar("CorrDndStatus" ,lanId, initFile) );/*campo DndStatus della tabella dei corrispondenti*/
strcpy (CorrCodeField, readPar("CorrCodeField" ,lanId, initFile) );/*campo codice della tabella dei corrispondenti*/
strcpy (CorrAppDir, readPar("CrAppDir" ,lanId, initFile) );/*nome della directory del disco locale del corrispondente*/
strcpy (CorrFileName, readPar("CrFileName" ,lanId, initFile) );/*nome del file nel disco locale del corrispondente*/
strcpy (CorrDnDir, readPar("CorrDnDir" ,lanId, initFile) );/*nome della directory sul server relativa alla directory di esecuzione della cgi per il download dei file*/
strcpy (Llu, readPar("Llu" ,lanId, initFile) );/*parametro per la redirezione del link all'as400 tra ambiente di test e di produzione*/
strcpy (Rtp, readPar("Rtp" ,lanId, initFile) );/*parametro per la redirezione del link all'as400 tra ambiente di test e di produzione*/
strcpy (ForbiddenChars, readPar("ForbiddenChars" ,lanId, initFile) );
fclose(initFile);
return(1);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxbuffer.cpp,v $
* $Revision: 1.1 $
* $Author: massimo $
* $Date: 2002-06-11 15:57:58+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* © aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
* developed by mr.blue
*/
#include "itxbuffer.h"
/*
* Costruzione/distruzione e funzioni ausiliarie
*/
itxBuffer::itxBuffer(int G)
{
try
{
m_Buf = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "itxBuffer::itxBuffer(int G)")
}
itxBuffer::itxBuffer(void* buf, int bsize, int G)
{
try
{
m_Buf = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
if (buf != NULL)
{
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, bsize);
memcpy(m_Buf, buf, bsize);
m_Cursor = m_Buf + bsize;
}
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "itxBuffer::itxBuffer(void* buf, int bsize, int G)")
}
itxBuffer::itxBuffer(itxBuffer& src, int G)
{
try
{
m_Buf = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
m_Granularity = G;
if (src.m_Buf != NULL)
{
register unsigned int l = PTR_DISTANCE(src.m_Cursor, src.m_Buf);
if (m_Bufsize <= l)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, l);
memcpy(m_Buf, src.m_Buf, l);
m_Cursor = m_Buf + l;
}
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "itxBuffer::itxBuffer(itxBuffer& src, int G)")
}
itxBuffer::~itxBuffer()
{
try
{
ITXFREE(m_Buf);
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "itxBuffer::itxBuffer(itxBuffer& src, int G)")
// CATCH_TO_NOTHING
}
int itxBuffer::Space(int len, int c)
{
try
{
if (len <= 0)
return (m_Buf == NULL ? 0 : 1);
if ((int)m_Bufsize < len)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, len);
memset(m_Buf, c, len);
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "itxBuffer::Space(int len, int c)")
return (m_Buf == NULL ? 0 : 1);
}
/*****************************************************************************
- FUNCTION NAME: SetEmpty
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
void itxBuffer::SetEmpty()
{
ITXFREE(m_Buf);
m_Buf = NULL;
m_Cursor = NULL;
m_Bufsize = 0;
}
/*****************************************************************************
- FUNCTION NAME: SetBuffer
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
void itxBuffer::SetBuffer(char* psrc, unsigned int bsize)
{
try
{
if (psrc == NULL)
SetEmpty();
else
{
if (m_Bufsize <= bsize)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, bsize);
memcpy(m_Buf, psrc, bsize);
m_Cursor = m_Buf + bsize;
}
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "operator=(char* psrc, int bsize)")
}
/*****************************************************************************
- FUNCTION NAME: AddTail
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
itxBuffer& itxBuffer::Append(char* padd, unsigned int bsize)
{
try
{
if (padd != NULL)
{
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Buf) <= bsize)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + bsize);
memcpy(m_Cursor, padd, bsize);
m_Cursor += bsize;
}
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "operator+=(char* padd, int bsize)")
return *this;
}
/*****************************************************************************
- FUNCTION NAME: InsAt
-----------------------------------------------------------------------------
- INPUT PARAMETERS:
-----------------------------------------------------------------------------
- RETURN VALUE:
-----------------------------------------------------------------------------
- ACTION DESCRIPTION:
*****************************************************************************/
void itxBuffer::InsAt(char* padd, unsigned int bsize, int pos) // pos = 0 means insert at the head
{
try
{
if (padd == NULL)
return;
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Buf) <= bsize)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + bsize);
memmove(m_Buf + pos + bsize, m_Buf + pos, PTR_DISTANCE(m_Cursor, m_Buf) - pos);
memcpy(m_Buf + pos, padd, bsize);
m_Cursor += bsize;
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "operator+=(char* padd, int bsize)")
}
<file_sep>//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by TestCombo.rc
//
#define IDSTART 3
#define IDD_TESTCOMBO_DIALOG 102
#define IDR_MAINFRAME 128
#define IDC_PROGRESS1 1000
#define IDC_N_SEQ 1001
#define IDC_R_SEQ 1002
#define IDC_RADIO1 1003
#define IDC_RADIO2 1004
#define IDC_RADIO3 1005
#define IDC_RADIO4 1006
#define IDC_RADIO5 1007
#define IDC_EDIT3 1008
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 129
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1009
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep><HTML>
<HEAD>
<TITLE>Tannit 4.0 Command Reference </TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#ffffff" TOPMARGIN=0>
<LINK REL=STYLESHEET HREF="styles.css" TYPE="text/css">
<span class=CmdTitolo>
*
<!-- TODO BEGIN -->
gethide
<!-- TODO END -->
(</span>
<BR>
<span class=ParamName>
<!-- TODO BEGIN : Add the following block until TODO END for each parameter -->
str
<!-- TODO END -->
</span>
<BR>
<span class=CmdTitolo>
)</span>
<BR>
<BR>
<BR>
<!-- TODO BEGIN -->
Returns a string which is obtained from the <i>src</i> parameter value
in which every non-alphanumeric ascii character is substitued
with the relative two-digits hex sequence <b>%xx</b>.
<!-- TODO END -->
<BR>
<BR>
<BR>
<span class=CmdTitolo2>Parameters </span>
<BR>
<!-- TODO BEGIN : Add the following block until TODO END for each parameter -->
<span class=ParamName><BR>
src</span>
<DD>Input string.</DD>
<!-- TODO END -->
<BR>
<BR>
<BR>
</span>
<span class=CmdTitolo2>Example </span>
<BR>
<BR>
<span class=Codice>
<pre>
*gethide(abc¶def)
</pre>
<br>
<br>
<br>
</span>
The output of the sample above is :<br>
<pre>
abc%B6def
</pre>
<br>
<br>
<br>
<center>
<A HREF="index.htm">Command Reference Index</A><br>
</center>
<br>
<br>
<br>
</BODY>
</HTML>
<file_sep>xml-path-finder
===============
Search into local XML using XPath and Javascript.
<file_sep>package com.imdp;
/**
* Created by massimo on 4/24/14.
*/
public class ImmutableFinal {
public String a = "pippo";
public final String b = "cico";
public void test() {
System.out.println("a: " + a.hashCode() + " - b: " + b.hashCode());
a = "zzz";
System.out.println("a = " + a + " - a: " + a.hashCode() + " - b: " + b.hashCode());
}
}
<file_sep>Tannit 4.0
==========
A fast-cgi based command interpreter for web-based back-end oriented appplications, bringing the power of Object Oriented Programming in C++ directly at the level of the HTML page.
This command interpreter empowers the high-level web-developer with rapid application development scripting instructions to make CRUD operations directly from the web page or any other textual resource.
Tannit commands always take one or more strings as input parameters and return just a string. They are of the form:
```
*command_name([parameter, ...])
```
At run time, the command interpreter replaces the whole command string in the HTML page with the resulting command output string. The Tannit-enriched web-resources (usually HTML or text files) are called Tannit templates.
Tannit command set can also be easily extended by including the header `tnt.h` and sub-classing a specific C++ class, *AbstractCommand*, which is the parent interface for all command-type objects:
```
class AbstractCommand
{
public:
virtual char* GetName() = 0;
virtual char* Execute(char*) = 0;
virtual void Deallocate() = 0;
}
```
For additional information on the complete list of available Tannit commands please navigate to this repo's [help](https://github.com/gambineri/Tannit/tree/master/help).
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsocket.h,v $
* $Revision: 1.36 $
* $Author: massimo $
* $Date: 2002-06-25 11:50:49+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITX_SOCKET_H__
#define __ITX_SOCKET_H__
#include <memory.h>
#include <exception>
#include <stdio.h>
#include "itxstring.h"
#include "itxexception.h"
#include "itxsystem.h"
#define ITXS_PCKLEN 4096
#define ITXS_TIMEOUTSEC 10
#define ITXS_TIMEOUTMILLISEC 0
class itxSocketException : public itxException
{
public:
itxSocketException(char* procedure, SOCKET socket) : itxException(0, procedure)
{
itxSystem sys;
m_errornumber = sys.SOGetLastError(socket);
}
};
class itxSocket
{
private:
itxString m_destination;
int m_port;
SOCKET m_socket;
itxException m_exception;
itxString m_ipv4;
itxSystem m_Sys;
int m_packetlen;
int m_transferredbytes;
struct timeval m_tm;
struct timeval m_tm_cycle;
//SSL
bool m_SSLActive;
void* m_ctx;
void* m_ssl;
// X509* server_cert = 0;
public:
//CONSTRUCTION-DESTRUCTION
itxSocket();
//Create a server socket listening at the specified port
itxSocket(int port);
//Create a socket connecting to the specified destination
itxSocket(char* destination, int port, bool ssl = false);
~itxSocket();
//METHODS
int Send(itxString* datatosend);
int Send(char* datatosend, int bytes_to_send);
int Receive(itxString* datatoreceive, int packetlen = ITXS_PCKLEN);
int BinReceive(char* datatoreceive, int maxbytes, int packetlen = ITXS_PCKLEN);
int BulkSend(FILE* fp, int packetlen = ITXS_PCKLEN);
int BulkReceive(FILE* fp, int packetlen = ITXS_PCKLEN);
int BlockingReceive(itxString* datatoreceive, int packetlen = ITXS_PCKLEN);
char* GetIpv4() { return m_ipv4.GetBuffer(); }
char* GetAddress() { return m_destination.GetBuffer(); }
int GetPort() { return m_port; }
int GetPacketLen() { return m_packetlen; }
int GetLastTransferredBytes() { return m_transferredbytes;}
bool CreateServerSocket(int port, int maxconn = SOMAXCONN);
bool Accept(itxSocket* pclientsocket);
void SetReceiveTimeout(long sec, long millisec);
void SetReceiveCycleTimeout(long sec, long millisec);
void Close();
int SSLSend(itxString* datatosend);
int SSLSend(char* datatosend, int bytes_to_send);
int SSLReceive(itxString* datatoreceive);
private:
void InitSocketLibrary();
void CreateTCPStreamSocket();
void AssignSocket(SOCKET socket);
bool SSLAllocate();
void SSLFree();
bool SSLConnect();
};
#endif // __ITX_SOCKET_H__<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
/***
* General purpose utilities
***/
//------------------------------------------------------------------------------
function callPrint(frameName)
{
frameName.focus();
window.print();
}
//------------------------------------------------------------------------------
function submitForm(obj, jsp_page, frame_target)
{
obj.action = jsp_page;
obj.target = frame_target;
obj.submit();
}
//------------------------------------------------------------------------------
function submitWithEnter(evt, obj, jsp_page, frame_target)
{
var keyCode = evt.which ? evt.which : evt.keyCode;
if (keyCode == 13)
submitForm(obj, jsp_page, frame_target);
}
//------------------------------------------------------------------------------
function deleteIframe(iframeid)
{
var ifr = document.getElementById(iframeid);
if (ifr)
ifr.parentNode.removeChild(ifr);
}
//------------------------------------------------------------------------------
function createIframe(iframeid)
{
var ifr = document.createElement('<iframe>');
ifr.id = iframeid;
document.body.appendChild(ifr);
return ifr;
}
//------------------------------------------------------------------------------
function runHiddenPage(srcpage)
{
var ifr = document.getElementById('hiddenAction');
if (ifr)
ifr.parentNode.removeChild(ifr);
ifr = createIframe('hiddenAction');
ifr.style.visibility = 'hidden';
ifr.src = srcpage;
}
//------------------------------------------------------------------------------
function checkNum(val)
{
if (isNaN(val))
{
alert('Please enter a valid numeric expression.');
return false;
}
else
return true;
}
//------------------------------------------------------------------------------
function checkNumBlankInput(input_field)
{
input_field.value = input_field.value.trim();
if (!checkNum(input_field.value))
input_field.value = '';
}
//------------------------------------------------------------------------------
function mustBeNumeric(control) //to be used "onblur"
{
if (!checkNum(control.value))
{
control.value = '';
control.focus();
}
}
//------------------------------------------------------------------------------
function getTableInDocument(doc, tableid)
{
return (doc.all ? doc.all[tableid] :
doc.getElementById ? doc.getElementById(tableid) : null);
}
//------------------------------------------------------------------------------
function popup(url, width, height)
{
window.open(url, '_blank', 'toolbar=no, status=no, menubar=no, scrollbars=no, width=' + width + ', height=' + height);
}
//------------------------------------------------------------------------------
function popupModal(url, ref, width, height)
{
return showModalDialog(url, ref, 'dialogWidth: '+ width + 'px; dialogHeight: '+ height +'px; status:no; scroll: 0;');
}
//------------------------------------------------------------------------------
function checklength(str, max)
{
if (str.length >= max)
{
str = str.substring(0,max);
return false;
}
return true;
}
//------------------------------------------------------------------------------
function warnNoPrivileges()
{
alert('You do not have enough privileges.');
}
//------------------------------------------------------------------------------
function strLeft(str, n)
{
var r = '';
var cut = n < str.length ? n : str.length;
for (var i = 0 ; i<cut; i++)
r += str.charAt(i);
return r;
}
//------------------------------------------------------------------------------
function setCaretToEnd(control)
{
if (control.createTextRange)
{
var range = control.createTextRange();
range.collapse(false);
range.select();
}
else if (control.setSelectionRange)
{
control.focus();
var length = control.value.length;
control.setSelectionRange(length, length);
}
}
//------------------------------------------------------------------------------
function setCaretToStart(control)
{
if (control.createTextRange)
{
var range = control.createTextRange();
range.collapse(true);
range.select();
}
else if (control.setSelectionRange)
{
control.focus();
control.setSelectionRange(0, 0);
}
}
//------------------------------------------------------------------------------
function trimString(str)
{
str = (this != window? this : str);
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
String.prototype.trim = trimString;
//------------------------------------------------------------------------------
function toITAdate(yyyymmdd)
{
return (yyyymmdd == "" ? "" : yyyymmdd.substring(6) + "/" +
yyyymmdd.substring(4, 6) + "/" +
yyyymmdd.substring(0, 4));
}
//------------------------------------------------------------------------------
function openNewWinMax(href)
{
var w = window.screen.availWidth;
var h = window.screen.availHeight;
var win = open(href, '_blank', 'resizable=1,status=1,menubar=1,toolbar=1,location=0,scrollbars=1');
win.moveTo(0, 0);
win.resizeTo(window.screen.availWidth, window.screen.availHeight)
}
//------------------------------------------------------------------------------
function getOptionIndexByValue(select_obj, opt_val)
{
for (i=0; i<select_obj.options.length; i++)
if (select_obj.options[i].value == opt_val)
return i;
return -1;
}
//------------------------------------------------------------------------------
function getSelectedOption(select_obj)
{
return select_obj.options[select_obj.selectedIndex].value;
}
//------------------------------------------------------------------------------
function setSelectedOption(selectobj, optvalue)
{
// Set to 'selected' the option in the given select
for (i=0; i < selectobj.length; i++)
if (selectobj.options[i].value == optvalue)
{
selectobj.selectedIndex = i;
break;
}
}
//------------------------------------------------------------------------------
function replaceSelectOptionValue(select_obj, existing_optval, new_val)
{
select_obj.options[getOptionIndexByValue(select_obj, existing_optval)].value = new_val;
}
//------------------------------------------------------------------------------
function replaceSelectOptionText(select_obj, existing_optval, new_val)
{
select_obj.options[getOptionIndexByValue(select_obj, existing_optval)].text = new_val;
}
//------------------------------------------------------------------------------
function formatCurrency(num)
{
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxlib.h,v $
* $Revision: 1.12 $
* $Author: massimo $
* $Date: 2002-06-24 13:38:57+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXLIB_H__
#define __ITXLIB_H__
#define CURRENT_VERSION "1.0"
#include "itxsystem.h"
#include "itxstring.h"
#include "itxhttp.h"
#include "itxsocket.h"
#include "itxsmtp.h"
#include "itxexception.h"
#include "itxcoll.h"
#include "itxsql.h"
#include "itxthread.h"
#include "itxtime.h"
#include "itxfileini.h"
#include "itxbuffer.h"
char* itxlibVer();
#endif /* __ITXLIB_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxbuffer.h,v $
* $Revision: 1.3 $
* $Author: massimo $
* $Date: 2002-06-12 14:37:33+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITXBUFFER_H__
#define __ITXBUFFER_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "itxdefines.h"
// Defines
#define DEFAULT_GRANULARITY 10
// This macro sends generic exception info about the current object status
#define CATCHALLBUF(Buf, Cursor, Bufsize, Granularity, method) catch(...) { \
char appobuf[256]; \
sprintf(appobuf, "itxBuffer crashed: m_Buf = 0x%p; m_Cursor = 0x%p; m_Bufsize = %d; m_Granularity = %d; Method = %s", \
(Buf), (Cursor), (Bufsize), (Granularity), (method)); \
throw appobuf; \
}
//-------------------------------------------------
//---------------- itxBuffer -----------------
//-------------------------------------------------
class itxBuffer
{
private:
//Members
char* m_Buf;
char* m_Cursor; //points to the end of data
unsigned int m_Bufsize; //bytes currently allocated
unsigned int m_Granularity;
public:
void SetEmpty();
int Space(int len, int c = ' ');
void InsAt(char* padd, unsigned int bsize, int pos);
itxBuffer& Append(char* padd, unsigned int bsize);
void SetBuffer(char* psrc, unsigned int bsize);
//Object management
inline char* GetBuffer(){return m_Buf;}
inline int Len(){return PTR_DISTANCE(m_Cursor, m_Buf);}
inline bool IsEmpty(){return (m_Buf == NULL);}
inline void SetGranularity(unsigned int G){m_Granularity = G;}
inline void UpdateCursor(unsigned int relpos){m_Cursor += relpos;}
//Construction/Destruction
itxBuffer(void* buf, int bsize, int G = DEFAULT_GRANULARITY);
itxBuffer(itxBuffer& src, int G = DEFAULT_GRANULARITY);
itxBuffer(int G = DEFAULT_GRANULARITY);
~itxBuffer();
//Operator =
void operator=(itxBuffer& src)
{
try
{
if (src.m_Buf == NULL)
SetEmpty();
else
{
register unsigned int l = PTR_DISTANCE(src.m_Cursor, src.m_Buf);
if (m_Bufsize <= l)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, l);
memcpy(m_Buf, src.m_Buf, l);
m_Cursor = m_Buf + l;
}
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "operator=(itxBuffer& src)")
}
//Operator +=
itxBuffer& operator+=(itxBuffer& add)
{
try
{
register unsigned int l = PTR_DISTANCE(add.m_Cursor, add.m_Buf);
if ((m_Bufsize - (unsigned)m_Cursor + (unsigned)m_Buf) <= l)
XALLOC(m_Buf, m_Cursor, m_Bufsize, m_Granularity, m_Bufsize + l);
memcpy(m_Cursor, add.m_Buf, l);
m_Cursor += l;
}
CATCHALLBUF(m_Buf, m_Cursor, m_Bufsize, m_Granularity, "operator+=(itxBuffer& add)")
return *this;
}
};
#endif // __ITXBUFFER_H__
<file_sep><HTML>
<HEAD>
<TITLE>Tannit 4.0 Command Reference </TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#ffffff" TOPMARGIN=0>
<LINK REL=STYLESHEET HREF="styles.css" TYPE="text/css">
<span class=CmdTitolo>
*
<!-- TODO BEGIN -->
foridx
<!-- TODO END -->
(</span>
<BR>
<span class=ParamName>
<!-- TODO BEGIN : Add the following block until TODO END for each parameter -->
counter
<!-- TODO END -->
</span>
<BR>
<span class=CmdTitolo>
)</span>
<BR>
<BR>
<BR>
<!-- TODO BEGIN -->
This command is used to retrieve the value of a counter in a <A HREF="for.htm">*for</A>
cycle block.<br>
<!-- TODO END -->
<BR>
<BR>
<BR>
<span class=CmdTitolo2>Parameters </span>
<BR>
<!-- TODO BEGIN : Add the following block until TODO END for each parameter -->
<span class=ParamName><BR>
counter</span>
<DD>Name of the counter whose value is to be retrieved.</DD>
<!-- TODO END -->
<BR>
<BR>
<BR>
<span class=CmdTitolo2>Return Values </span>
<BR>
<BR>
<!-- TODO BEGIN -->
A string representing the current value of the counter.<BR>
<!-- TODO END -->
<BR>
<span class=CmdTitolo2>Remarks </span>
<BR>
<BR>
<!-- TODO BEGIN -->
See the <A HREF="for.htm">*for</A> command.<BR>
<!-- TODO END -->
<br>
<br>
<br>
<center>
<A HREF="index.htm">Command Reference Index</A><br>
</center>
<br>
<br>
<br>
</BODY>
</HTML>
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.test.testjtx;
import jtxlib.main.datastruct.Vector;
import jtxlib.main.sql.DBConnection;
import jtxlib.main.sql.RecordSet;
class testResultset
{
public void show1(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT * FROM Tab1", 2000);
long curmilli = System.currentTimeMillis();
for (int j=0; j<100; j++)
{
int rcount = rs.getRecordCount();
for (int i=0; i<rcount; i++)
{
rs.getField(i, 0);
rs.getField(i, 1);
rs.getField(i, 2);
}
}
System.out.println("show1: queries and fetches 2000 records, cycles 100 times and 'gets' all records and fields by using field indexes.");
System.out.println("elapsed: " + (System.currentTimeMillis() - curmilli) + " millis.");
}
//-----------------------------------------------
public void show2(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT * FROM Tab1", 2000);
long curmilli = System.currentTimeMillis();
for (int j=0; j<100; j++)
{
int rcount = rs.getRecordCount();
for (int i=0; i<rcount; i++)
{
rs.getField(i, "ID");
rs.getField(i, "text1");
rs.getField(i, "number1");
}
}
System.out.println("show2: queries and fetches 2000 records, cycles 100 times and 'gets' all records and fields by using field names.");
System.out.println("show2: " + (System.currentTimeMillis() - curmilli) + " millis.");
}
//-----------------------------------------------
public void show3(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT * FROM Tab1", 10);
System.out.println("show3: selects 10 records and prints them out.");
System.out.println(rs);
}
//-----------------------------------------------
public void show4(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT * FROM Tab1", 2000);
long curmilli = System.currentTimeMillis();
while(rs.next())
{
rs.getField("ID");
rs.getField("text1");
rs.getField("number1");
}
System.out.println("show4: queries and fetches 2000 records, 'gets' all records and fields by using field names.");
System.out.println("show4: " + (System.currentTimeMillis() - curmilli) + " millis.");
}
//-----------------------------------------------
public void fetchAll(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT * FROM Tab1", 10);
System.out.println("fetchAll: queries and fetches 10 records.");
System.out.println("rs.fetchAll() returns " + rs.fetchAll());
System.out.println("rs.getRecordCount() returns " + rs.getRecordCount());
}
//-----------------------------------------------
public void manualFill()
{
Vector v = new Vector(10);
v.addElement("campo1");
v.addElement("campo2");
v.addElement("campo3");
v.addElement("campo di carne");
v.addElement("campi flegrei");
v.addElement("campo santo");
RecordSet rs = new RecordSet(v);
System.out.println("Adding four times the same row:");
rs.addRow(v);
rs.addRow(v);
rs.addRow(v);
rs.addRow(v);
System.out.println(rs);
System.out.println("Deleting two times row 2:");
rs.removeRow(2);
rs.removeRow(2);
System.out.println(rs);
// testDataPanel tdp = new testDataPanel();
// tdp.add(rs);
}
//-----------------------------------------------
public void first_next_last(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
rs.select("SELECT number1 FROM Tab1 WHERE number1 <= 10 ORDER BY number1 ASC", 1);
System.out.println("cursor subito dopo select = " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.last();
System.out.println("cursor dopo last " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.first();
System.out.println("cursor dopo first " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
//Requery and re-assign resultset
System.out.println("Requery and re-assign......");
rs.select("SELECT number1 FROM Tab1 WHERE number1 <= 10 ORDER BY number1 ASC", 0);
System.out.println("cursor subito dopo select = " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.last();
System.out.println("cursor dopo last " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.first();
System.out.println("cursor dopo first " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
rs.next();
System.out.println("cursor dopo next " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
}
//-----------------------------------------------
public void empty_resultset(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
boolean ret = false;
rs.select("SELECT number1 FROM Tab1 WHERE number1 < 0");
System.out.println("cursor subito dopo select = " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
ret = rs.first();
System.out.println("first torna " + ret);
ret = rs.next();
System.out.println("next torna " + ret);
System.out.println("cursor subito dopo next = " + rs.getCursorPos() + " number1 = " + rs.getField("number1"));
}
//-----------------------------------------------
/*
public void manuallyAddedColumn(DBConnection conn)
{
RecordSet rs = new RecordSet(conn);
boolean ret = false;
System.out.println("manuallyAddedColumn: shows 3 records from a resultset " +
"before and after adding and removing columns manually.");
rs.select("SELECT * FROM Tab1", 3);
System.out.println(rs);
int manaddcolidx = rs.appendColumn("manualColumn1", "manualValue1");
System.out.println("Manually added a column with colidx = " + manaddcolidx);
System.out.println(rs);
manaddcolidx = rs.appendColumn("manualColumn2", "manualValue2");
System.out.println("Manually added a column with colidx = " + manaddcolidx);
System.out.println(rs);
rs.removeColumn("manualColumn1");
System.out.println("Manually removed column 'manualColumn1'");
System.out.println(rs);
rs.removeColumn("text1");
System.out.println("Manually removed column 'text1'");
System.out.println(rs);
}
*/
//-----------------------------------------------
public void runTest()
{
DBConnection conn = new DBConnection("testjtx", "", "");
show1(conn);
show2(conn);
show3(conn);
show4(conn);
fetchAll(conn);
manualFill();
first_next_last(conn);
empty_resultset(conn);
conn.close();
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: tqr.cpp,v $
* $Revision: 1.44 $
* $Author: massimo $
* $Date: 2002-06-26 11:25:18+02 $
*
* Tannit Query Resultset Object and Manager Implementation
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#include "itxtypes.h"
#include "auxfile.h"
#include "tqr.h"
#define TNT_MAX_RECORD_LENGTH 8192
#define TNT_MAX_FIELD_LENGTH 256
//------------------------------------------------------------------------
//-------------------------- TQRCollection Section --------------------------
//------------------------------------------------------------------------
TQR* TQRCollection::CreateTQR(char* queryname, int numfields)
{
TQR* qres = NULL;
try
{
qres = (TQR*) new TQR(queryname, numfields);
Store(NULL, qres);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::CreateTQR\n");
}
return qres;
}
// ritorna il puntatore al TQR di nome name
TQR* TQRCollection::Retrieve(char* name)
{
TQR* qres = NULL;
int icount = 0, i = 0;
int qcount = m_qcount;
try
{
if (name != NULL && qcount > 0)
{
while (icount < qcount)
{
if (m_qres[i] != NULL)
{
if ((m_qres[i]->GetName()).Compare(name) == 0)
break;
icount++;
}
i++;
}
if (icount < qcount)
qres = m_qres[i];
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::Retrieve\n");
throw;
}
return qres;
}
// ritorna l'indice al TQR di nome name
int TQRCollection::Index(char* name)
{
int icount = 0, i = 0;
int qcount = m_qcount;
try
{
if (name != NULL && qcount > 0)
{
while (icount < qcount)
{
if (m_qres[i] != NULL)
{
if ((m_qres[i]->GetName()).Compare(name) == 0)
break;
icount++;
}
i++;
}
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::Index\n");
throw;
}
if (icount >= qcount)
icount = ITXFAILED;
return icount;
}
// torna TQR_NOT_EXIST oppure il numero di record presenti
int TQRCollection::Exist(char* name)
{
TQR* qres = NULL;
int icount = 0, i = 0;
int qcount = m_qcount;
try
{
if ((qres = Retrieve(name)) != NULL)
return qres->totalRows;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::Exist\n");
throw;
}
return TQR_NOT_EXIST;
}
// memorizza qres nella lista dei TQR gestiti e torna l'indice
int TQRCollection::Store(PTQRMng mng, TQR* qres)
{
int i = 0;
try
{
while (m_qres[i] != NULL && i < QUERY_NUMBER)
i++;
if (m_qres[i] == NULL)
{
m_qres[i] = qres;
m_mng[i] = mng;
m_qcount++;
return i;
}
else
return ITXFAILED;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::Store\n");
return ITXFAILED;
}
}
void TQRCollection::Remove(char* name)
{
int i;
TQR* qres;
try
{
if ((i = Index(name)) != ITXFAILED)
{
m_qcount -= 1;
qres = m_qres[i];
delete qres;
m_qres[i] = NULL;
m_mng[i] = NULL;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::Remove\n");
}
}
char* TQRCollection::GetCurrentRecordField(char* name, char* colname)
{
char* value = "";
TQR* qres;
try
{
qres = Retrieve(name);
value = qres->GetCurrentRecordField(colname);
}
catch(...)
{
value = "";
// if (qres == NULL)
// DebugTrace2(IN_WARNING, "Cannot find a tqr named '%s'.\n", name);
}
return value;
}
void TQRCollection::SetCurrentRecordField(char* name, char* colname, char* colvalue)
{
try
{
TQR* qres = Retrieve(name);
qres->SetCurrentRecordField(colname, colvalue);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRCollection::SetCurrentRecordField\n");
}
}
//------------------------------------------------------------------------
//-------------------------- TQRManager Section --------------------------
//------------------------------------------------------------------------
TQR* TQRManager::CreateTQR(char* queryname)
{
TQR* qres = NULL;
try
{
qres = (TQR*) new TQR(queryname);
Store(qres);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::CreateTQR\n");
}
return qres;
}
TQR* TQRManager::CreateTQR(char* queryname, int numfields)
{
TQR* qres = NULL;
try
{
qres = (TQR*) new TQR(queryname, numfields);
Store(qres);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::CreateTQR\n");
}
return qres;
}
void TQRManager::SetColumnAttributes(char* queryname, int colindex, char* colname, short coltype, long colsize)
{
TQR* qres = NULL;
try
{
qres = Get(queryname);
qres->SetColumnAttributes(colindex, colname, coltype, colsize);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::SetColumnAttributes\n");
}
}
void TQRManager::SetColumnAttributes(TQR* qres, int colindex, char* colname, short coltype, long colsize)
{
try
{
qres->SetColumnAttributes(colindex, colname, coltype, colsize);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::SetColumnAttributes\n");
}
}
void TQRManager::SetName(TQR* qres, char* name)
{
try
{
qres->SetName(name);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::SetName\n");
}
}
TQR* TQRManager::Filter(char* source, char* field, char* value, char* destination)
{
TQR* qres = NULL;
TQR* qsrc = NULL;
itxString filter;
int irow = 0;
try
{
if ((qsrc = Get(source)) == NULL)
return qres;
if ((qres = qsrc->Clone(destination)) != NULL)
{
Store(qres);
qsrc->MoveFirst();
for (int irec = 0; irec < qsrc->totalRows; irec++)
{
filter = qsrc->GetCurrentRecordField(field);
if (filter.Compare(value) == 0)
{
qres->AddTail();
*(qres->current_record) = *(qsrc->current_record);
}
qsrc->MoveNext();
}
qres->MoveFirst();
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::Filter\n");
}
return qres;
}
TQR* TQRManager::Sample(char* source, char* destination, int destMaxRecs, int seed)
{
TQR* qres = NULL;
TQR* qsrc = NULL;
int * myArray;
itxString filter;
int irow = 0;
int extracted = 0;
int ii=0;
int irec = 0;
int buffer = 0;
int qsrcStartingRow;
try
{
if ((qsrc = Get(source)) == NULL)
return qres;
if (qsrc->totalRows <= destMaxRecs)
{
destMaxRecs = qsrc->totalRows;
// *qres = *qsrc;
// qres->SetName(destination);
// return qres;
}
if ((qres = qsrc->Clone(destination)) != NULL)
{
Store(qres);
qsrcStartingRow=qsrc->GetActualRow();
myArray = new int[qsrc->totalRows];
for (int i = 0; i < qsrc->totalRows; i++)
{
myArray[i] = i+1;
}
srand((unsigned)seed);
for (irec = 0; irec < destMaxRecs; irec++)
{
extracted = irec + rand() % (qsrc->totalRows - irec);
DebugTrace2(DEFAULT, "myArray[0]-a----------------:%d\n", myArray[0]);
DebugTrace2(DEFAULT, "myArray[%d]-----------------:%d\n", irec, myArray[irec]);
DebugTrace2(DEFAULT, "extracted-----------------:%d\n", extracted);
DebugTrace2(DEFAULT, "destMaxRecs-----------------:%d\n", destMaxRecs);
buffer = myArray[irec];
myArray[irec] = myArray[extracted];
myArray[extracted] = buffer;
DebugTrace2(DEFAULT, "myArray[0]-b----------------:%d\n", myArray[0]);
ii = irec;
while(ii > 0)
{
if (myArray[ii] < myArray[ii-1]) {
buffer = myArray[ii-1];
myArray[ii-1] = myArray[ii];
myArray[ii] = buffer;
}
else
{
DebugTrace2(DEFAULT, "myArray[0]-c----------------:%d\n<br>", myArray[0]);
break;
}
ii--;
}
DebugTrace2(DEFAULT, "myArray[0]-c1---------------:%d\n<br>", myArray[0]);
}
for (irec = 0; irec < destMaxRecs; irec++)
{
qsrc->MoveTo(myArray[irec]);
qres->AddTail();
*(qres->current_record) = *(qsrc->current_record);
DebugTrace2(DEFAULT, "myArray[0]-----------------:%d\n", myArray[0]);
DebugTrace2(DEFAULT, "______:%d-%s\n", myArray[irec], qres->GetCurrentRecordField("dscr"));
}
// DebugTrace2(DEFAULT, "______:totalrows %d\n", qres->GetTotalRows());
qsrc->MoveTo(qsrcStartingRow);
qres->MoveFirst();
delete [] myArray;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRManager::Sample\n");
}
return qres;
}
void TQRManager::LoadDataBuffer(char* tqrname, int tqrcols, char recsep, char fieldsep, char* buffer)
{
istrstream str_buffer(buffer);
char record[TNT_MAX_RECORD_LENGTH];
TQR* qres = NULL;
if ((qres = Get(tqrname)) == NULL)
qres = CreateTQR(tqrname, tqrcols);
qres->MoveLast();
while(!str_buffer.eof())
{
str_buffer.getline(record, TNT_MAX_RECORD_LENGTH, recsep);
if (!ISNULL(record))
qres->LoadRecordBuffer(record, fieldsep);
}
qres->MoveFirst();
}
//-----------------------------------------------------------------
//-------------------------- TQR Section --------------------------
//-----------------------------------------------------------------
TQR::TQR(char* queryname)
{
try
{
id = queryname;
colsNumber = 0;
actualRow = -1;
startingRow = STARTING_ROW;
rowsToStore = ROWS_TO_STORE;
totalRows = 0;
current_record = NULL;
recordshead = NULL;
recordstail = NULL;
m_MoreDBRows = false;
m_SourceRecordCount = 0;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::TQR\n");
}
}
TQR::TQR(char* queryname, int numfields)
{
int ifields = 0;
char appo[10];
try
{
id = queryname;
colsNumber = numfields;
actualRow = -1;
startingRow = STARTING_ROW;
rowsToStore = ROWS_TO_STORE;
totalRows = 0;
current_record = NULL;
recordshead = NULL;
recordstail = NULL;
m_MoreDBRows = false;
m_SourceRecordCount = 0;
queryHeader = (TQRColumnHeader*) new TQRColumnHeader[numfields]();
ifields = 0;
while (ifields < numfields)
{
sprintf(appo, "f%d\0", ifields + 1);
queryHeader[ifields].name = appo;
ifields++;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::TQR %s\n", queryHeader[ifields].name.GetBuffer());
}
}
TQR::~TQR()
{
TQRRecord* delrecord;
try
{
delete [] queryHeader;
current_record = recordshead;
while (current_record != NULL)
{
delrecord = current_record;
current_record = current_record->m_next;
delete delrecord;
}
}
catch(...)
{
// fabio-->patch 30/05/2001
// DebugTrace2(IN_ERROR, "TQR::~TQR\n");
}
}
void TQR::operator=(TQR* src)
{
try
{
id = src->id;
colsNumber = src->colsNumber;
actualRow = src->actualRow;
startingRow = src->startingRow;
rowsToStore = src->rowsToStore;
totalRows = src->totalRows;
queryHeader = (TQRColumnHeader*) new TQRColumnHeader[colsNumber]();
for (int icol = 0; icol < colsNumber; icol ++)
SetColumnAttributes(icol, src->queryHeader->name.GetBuffer(),
src->queryHeader->sqlDataType, src->queryHeader->colummnSize);
src->MoveFirst();
for (int irec = 0; irec < totalRows; irec++)
{
AddTail();
*(current_record) = *(src->current_record);
src->MoveNext();
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::operator=\n");
}
}
TQR* TQR::Clone(char* clonename)
{
TQR* qres = NULL;
try
{
qres = (TQR*) new TQR(clonename, colsNumber);
qres->queryHeader = (TQRColumnHeader*) new TQRColumnHeader[colsNumber]();
for (int icol = 0; icol < colsNumber; icol ++)
qres->SetColumnAttributes(icol, queryHeader[icol].name.GetBuffer(),
queryHeader[icol].sqlDataType, queryHeader[icol].colummnSize);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::Clone\n");
}
return qres;
}
void TQR::SetColumnAttributes(int colindex, char* colname, short coltype, long colsize)
{
try
{
this->queryHeader[colindex].SetAttributes(colname, coltype, colsize);
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::SetColumnAttributes %s\n", colname);
}
}
// alloca spazio per un nuovo record e lo aggiunge in coda
bool TQR::AddTail()
{
TQRRecord* new_record;
try
{
if (totalRows == 0)
{
new_record = (TQRRecord*) new TQRRecord(colsNumber);
recordshead = new_record;
recordstail = new_record;
actualRow = 1;
}
else
{
new_record = (TQRRecord*) new TQRRecord(recordstail, colsNumber, NULL);
recordstail->m_next = new_record;
recordstail = new_record;
actualRow++;
}
current_record = new_record;
totalRows++;
return true;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::AddTail\n");
return false;
}
}
void TQR::RemoveTail()
{
try
{
if (recordstail == NULL)
{
actualRow = -1;
return;
}
current_record = recordstail->m_previous;
delete recordstail;
recordstail = current_record;
if (recordstail != NULL)
recordstail->m_next = NULL;
else
recordshead = NULL;
actualRow--;
totalRows--;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::RemoveTail\n");
}
}
// determina la posizione di una colonna di nome fieldname in base 0.
// il valore di ritorno ITXFAILED indica che non � stata trovata.
int TQR::GetColPos(char* colname)
{
int icol = 0;
try
{
while (icol < colsNumber)
{
if (queryHeader[icol].name.Compare(colname) == 0)
break;
icol++;
}
if (icol == colsNumber)
{
icol = ITXFAILED;
DebugTrace2(IN_WARNING, "Cannot find a field named '%s'\n", colname);
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::GetColPos\n");
}
return icol;
}
void TQR::MoveTo(int rowindex)
{
if (rowindex < 0)
return;
try
{
int irow = 1;
MoveFirst();
while (irow < rowindex && current_record != NULL)
{
MoveNext();
irow++;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::MoveTo\n");
}
}
void TQR::LoadRecordBuffer(char* record, char fieldsep)
{
istrstream str_REC(record);
char stoken[TNT_MAX_FIELD_LENGTH];
itxString token;
bool record_head = TRUE;
int field_count = 0;
try
{
if (record != NULL)
AddTail();
// stores values presented in buffer
while(!str_REC.eof())
{
str_REC.getline(stoken, TNT_MAX_FIELD_LENGTH, fieldsep);
token = stoken;
token.Trim();
if (field_count < colsNumber)
{
SetCurrentRecordField(field_count, token.GetBuffer());
field_count++;
}
}
// stores values not presented in buffer
while (field_count < colsNumber)
{
{
SetCurrentRecordField(field_count, token.GetBuffer());
field_count++;
}
}
if (field_count != colsNumber)
{
RemoveTail();
DebugTrace2(DEFAULT, "TQR::LoadRecordBuffer %s\n", record);
return;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQR::LoadRecordBuffer\n");
}
}
//-----------------------------------------------------------------------------
//-------------------------- TQRColumnHeader Section --------------------------
//-----------------------------------------------------------------------------
// inizializza i valori della colonna
void TQRColumnHeader::SetAttributes(char* colname, short coltype, long colsize)
{
try
{
name = colname;
sqlDataType = coltype;
this->colummnSize = colsize;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRColumnHeader::SetAttributes\n");
}
}
//-----------------------------------------------------------------------------
//-------------------------- TQRRecord Section --------------------------
//-----------------------------------------------------------------------------
TQRRecord::TQRRecord(int colnum)
{
try
{
m_previous = NULL;
m_row = (itxString*) new itxString[colnum]();
for (int i = 0; i < colnum; i++)
m_row[i].SetEmpty();
colsNumber = colnum;
m_next = NULL;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRRecord::TQRRecord\n");
}
}
TQRRecord::TQRRecord(TQRRecord* previous, int colnum, TQRRecord* next)
{
try
{
m_previous = previous;
m_row = (itxString*) new itxString[colnum]();
for (int i = 0; i < colnum; i++)
m_row[i].SetEmpty();
colsNumber = colnum;
m_next = next;
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRRecord::TQRRecord\n");
}
}
TQRRecord::~TQRRecord()
{
try
{
delete [] m_row;
}
catch(char* e)
{
char* now_e_is_referenced = e;
// fabio-->patch 30/05/2001
// DebugTrace2(IN_ERROR, "%s\n", e);
}
catch(...)
{
// fabio-->patch 30/05/2001
// DebugTrace2(IN_ERROR, "TQRRecord::~TQRRecord\n");
}
}
void TQRRecord::operator=(TQRRecord& src)
{
try
{
for (int icol = 0; icol < colsNumber; icol++)
m_row[icol] = (src.m_row[icol]).GetBuffer();
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRRecord::operator=\n");
}
}
// predispone lo spazio size per il campo in posizione colindex
void TQRRecord::ExpandCol(int colindex, int size)
{
try
{
m_row[colindex].Space(size, '\0');
}
catch(...)
{
DebugTrace2(IN_ERROR, "TQRRecord::ExpandCol\n");
}
}<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxthread.h,v $
* $Revision: 1.6 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:30+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef _ITX_THREAD_H_
#define _ITX_THREAD_H_
#include "itxsystem.h"
class _Thread
{
itxSystem m_Sys;
protected:
unsigned int m_TID;
void* m_THandle;
unsigned long m_StackSize;
unsigned short m_Started :1;
unsigned short m_Suspended :1;
unsigned short :(sizeof(unsigned short) - 2);
void SetThreadID(unsigned int t){m_TID = t;}
public:
_Thread(unsigned long StackS = 4096)
{
m_StackSize = StackS;
m_Started = 0;
m_Suspended = 0;
}
unsigned int GetThreadID(){return m_TID;}
void ChangeStackSize(unsigned long S);
void Start(void* thisThread);
void Suspend();
void Kill();
void Resume();
virtual void Run() = 0; //The overridable function
friend void ThreadStarter(void* a)
{
((_Thread*)a)->Run();
}
};
class itxThread : public _Thread
{
public:
itxThread(){}
~itxThread(){}
inline void Start(){ _Thread::Start(this); }
};
#endif /* _ITX_THREAD_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: teg.cpp,v $
* $Revision: 1.0 $
* $Author: fabio $
* $Date: 2001-01-09 19:11:08+01 $
*
* Tannit Extension Manager Command Implementation
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#include <windows.h>
#include <stdio.h>
#include "teg.h"
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;
}
//[[BEGIN_GENERATED_CODE]]
teg_header cmd1("teg_header");
teg_load cmd2("teg_load");
TNTAPI* g_pTNTAPI; //tnt hook object pointer
void __declspec(dllexport) TannitHandshake(AbstractCommand** ppCommands, TNTAPI* pTNTAPI)
{
ppCommands[0] = (AbstractCommand*)&cmd1;
ppCommands[1] = (AbstractCommand*)&cmd2;
g_pTNTAPI = pTNTAPI;
}
//[[END_GENERATED_CODE]]
char* teg_header::Execute(char* inputstr)
{
char* modulename = NULL;
int bufdim;
if (TNTPickString(inputstr, 1, NULL, &bufdim))
{
modulename = (char*)calloc(bufdim, 1);
TNTPickString(inputstr, 1, modulename, &bufdim);
}
m_Output.SetEmpty();
m_Output = "// Tannit Extension Manager 1.0\r\n";
m_Output += "// \r\n";
m_Output += "// aitecsa\r\n";
m_Output += "// ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.\r\n";
m_Output += "// � aitecsa s.r.l. via baglivi 3 00161 roma italy\r\n";
m_Output += "// <EMAIL>\r\n";
m_Output += "// all rights reserved\r\n";
m_Output += "// \r\n";
m_Output += "// \r\n";
m_Output += "// This software is automatically generated using TEG 1.0\r\n";
m_Output += "// \r\n";
m_Output += "// Module Extension: ";
m_Output += modulename;
m_Output += "\r\n";
m_Output += "// \r\n";
free(modulename);
return m_Output.GetBuffer();
}
char* teg_load::Execute(char* inputstr)
{
char* modulename = NULL;
char* commandlist = NULL;
FILE* fp = NULL;
int bufdim;
if (TNTPickString(inputstr, 1, NULL, &bufdim))
{
modulename = (char*)calloc(bufdim, 1);
TNTPickString(inputstr, 1, modulename, &bufdim);
}
if (TNTPickString(inputstr, 2, NULL, &bufdim))
{
commandlist = (char*)calloc(bufdim, 1);
TNTPickString(inputstr, 2, commandlist, &bufdim);
}
if (!TNT_TQRExist(commandlist))
{
itxString cmdstring;
cmdstring.SetEmpty();
int icmd = 1;
char cmdname[64];
if ((fp = fopen(modulename, "r")) != NULL)
{
while (fscanf(fp, "%s", &cmdname[0]) != EOF)
{
cmdstring += cmdname;
cmdstring += '#';
icmd++;
}
TNTLoadDataBuffer(commandlist, 2, '#', '$', cmdstring.GetBuffer());
fclose(fp);
}
}
else
TNTRewind(commandlist);
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_TYPES_H__
#define __ITX_TYPES_H__
#ifndef NULL
#define NULL 0
#endif
/*
typedef unsigned long DWORD;
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef float FLOAT;
*/
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#define ITXFAILED -1
#define ISEQUAL(a,b) (strcmp(a,b) == 0)
#define ISNULL(a) (ISEQUAL(a, ""))
#define FREE(a) { free(a); a = NULL; }
#define ISVALIDPTR(a) ( (a) != (void*)0 && (a) != (void*)1 )
#endif //__ITX_TYPES_H__<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsmtp.h,v $
* $Revision: 1.6 $
* $Author: andreal $
* $Date: 2002-05-17 19:24:46+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 rom<NAME>
* <EMAIL>
*/
#ifndef __ITX_SMTP_H__
#define __ITX_SMTP_H__
#include "itxsocket.h"
#define ITXM_MAXATTACHMENTS 16
#define ITXM_CRITICAL_ERROR 400
#define ITXM_SMTPPORT 25
#define EXIT_ON_CRITICAL(a) { if(a >= ITXM_CRITICAL_ERROR) return a; }
#define MIME_VERSION "MIME-Version: 1.0\r\n"
#define BOUNDARY "==80SW223H3ACKAC232731CAC0473000328A1=="
#define B64_DEF_LINE_SIZE 72
class Recipient
{
public:
itxString m_address;
Recipient* m_next;
Recipient(char* to) { m_address = to; m_next = NULL; }
};
class itxSmtp
{
private:
itxSocket* m_socket;
itxString m_sender;
itxString m_server;
itxString m_domain;
itxString m_subject;
Recipient* m_to;
itxString m_body;
itxString* m_attachments[ITXM_MAXATTACHMENTS];
int m_NumAttach;
unsigned char* m_AttachedData;
int m_AttachedDataLen;
public:
itxSmtp(char* server, char* domain, char* m_sender);
~itxSmtp();
int Mail();
void AddRcpt(char* to);
void SetSubject(char* subject) { m_subject = subject; };
void SetBody(char* body) { m_body = body; };
char* GetIpv4() { return m_socket ? m_socket->GetIpv4() : NULL; }
char* GetAddress() { return m_socket ? m_socket->GetAddress() : NULL; }
int GetPort() { return m_socket ? m_socket->GetPort() : -1; }
itxString GetSender() { return m_sender; }
bool AddAttachment(char* attachment);
bool RemoveAttachments();
private:
int ExchangeMessage(char* cmd, char* arg);
bool SendAttachments();
bool EncodeBase64(int attidx);
void EncodeFromFile(FILE* infile);
void EncodeBlock(unsigned char in[3], unsigned char out[4], int len);
};
#endif
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
- PROJECT : itxWeb - Tannit
- FILENAME : procTpl.c
- TAB : 2, no spaces
- DESCRIPTION : gestione del parsing dei template
*****************************************************************************/
#include "tannit.h"
#include "extVars.h"
#define START_CYCLE 1
#define END_CYCLE 2
#define START_CND_BLK 3
#define ELSE_CND_BLK 4
#define END_CND_BLK 5
#define PREPROC_IT 6
#define NEVER_PREPROC_IT 7
typedef struct
{
char *cmdName;
// int cmdFunction;
void * (* cmdFunction)( int, char *, char * );
int cmdType;
} CommandStructure;
CommandStructure CmdStruct[] = {
{"exeQ", execQuery, 0},
{"_exeQ", execQuery, PREPROC_IT},
{"exeIQ", execInsQuery, 0},
{"remQ", remQuery, 0},
{"totRecs", writeTotalRecords, 0},
{"actRec", writeActualRec, 0},
{"maxRecs", writeMaxRecords, 0},
{"firstRec", writeFirstRecord, 0},
{"moreRecs", moreRecsMsg, 0},
{"recVal", recVal, 0},
{"_recVal", recVal, PREPROC_IT},
{"recCnd", recValCnd, 0},
{"_recCnd", recValCnd, PREPROC_IT},
{"recSEL", recValConf, 0},
{"recLookS", recValLookAsStr, 0},
{"cycleQ", cycleQuery, START_CYCLE},
{"endCQ", endCycleQuery, END_CYCLE},
{"setRec", setActualRow, 0},
{"if", startCndBlk, START_CND_BLK},
{"ifblk", startCndBlk, START_CND_BLK},
{"^ifblk", startCndBlk, START_CND_BLK},
{"else", elseCndBlk, ELSE_CND_BLK},
{"elseblk", elseCndBlk, ELSE_CND_BLK},
{"^elseblk", elseCndBlk, ELSE_CND_BLK},
{"endif", endCndBlk, END_CND_BLK},
{"endblk", endCndBlk, END_CND_BLK},
{"^endblk", endCndBlk, END_CND_BLK},
{"WEBURL", writeWebUrl, PREPROC_IT},
{"WEBROOT", writeHomeDir, PREPROC_IT},
{"cgipath", writeCgiPath, PREPROC_IT},
{"IMGDIR", writeImgDir, PREPROC_IT},
{"SSDIR", writeSSDir, PREPROC_IT},
{"get", getValue, 0},
{"^get", getValue, 0},
{"_get", getValue, PREPROC_IT},
{"getmad", getmad, 0},
{"encr", encrIt, 0},//deprecated
{"auth", authorize, 0},//deprecated
{"crypt", crypt, 0},
{"decr", decrypt, 0},
{"valid", validate, 0},//validazione utenti
{"validAleph", validAleph, 0},//validazione utenti per il client Aleph
{"exof", exitOnFile, 0},
{"chkIt", syntChk, 0},
{"setVar", setVar, 0},
{"getVar", getVar, 0},
{"getId", extrIdG, 0},
{"extId", extrId, 0},
{"trans", translateIt, PREPROC_IT},
{"prex", processExternFile, PREPROC_IT},
{"^prex", processExternFile, 0},
{"setCoo", setCookie, 0},
{"CrAppDir", writeCorrAppDir, 0},
{"CrFileName", writeCorrFileName, 0},
{"inDomain", isInTheDomain, 0},
{"fontSt", fontStyle, PREPROC_IT},
{"revBr", revealBrowser, 0},
{"^revBr", revealBrowser, 0},
{"StoreTQR", StoreTQR, 0},
{"TQRInsert", TQRInsert, 0},
{"getP00", getP00, 0},
{"exeTP", exeTP, 0},
{"fillmsk", fillmsk, 0},
{"span", writeSpan, PREPROC_IT},
{"verCoo", verCookie, 0},
{"now", now, 0},
{"exist", exist, 0},
{"fconn", firstConn, 0},
{"ckcli", ckcli, 0},
{"fddate", formatDimDate, 0},
{"splitREA", splitREA, 0},
{"dimDataMagic", dimDataMagic, 0},
{"sottra", subtractIt, 0},
{"sumf", sumFloat, 0},
{"parval", parval, PREPROC_IT},
{"tgt", switchTplTgt, PREPROC_IT},
{"filtTqr", filterTqr, 0},
{"gethide", putGetHide, 0},
{"tqrval", setTQRValues, 0},
{"pkdate", pkdate, 0},
{"tunnel", prmTunnel, 0},
{"dfcur", dimFormatCurrency, 0},
{"divint", divideInt, 0},
{"fdcap", formatDimCap, 0},
{"fdnace", formatDimNACE, 0},
{"fdvia", formatDimVia, 0},
{"ucase", uppercaseIt, 0},
{"tplname", putTplName, 0},
{"fdnaz", formatDimNaz, 0},
// vers 2.7 specific
{"invoke", invoke, 0},
{"traceU", traceUser, 0},
{"execmd", execmd, 0},
{"getcoo", getcoo, 0},
{"rtrim", rtrim, 0},
{"trim", trim, 0},
{"cfc", cfc, 0},
{"flush", flush, 0},
{"uTime", uTime, 0},
{"uTimeToDMY", uTimeToDMY, 0},
{"exeQnew", exeQnew, 0},
{"olimpybet", olimpybet, 0},
{"dbgmsg", dbgmsg, 0},
{"quotestr", quotestr, 0},
{NULL, NULL, 0}
};
/*************************************************************************************
NOME :bufferTpl
attivita' :ricava il nome del template dal parametro di get TPL_TAG, lo combina con
l'estensione di default TPL_EXT e lo concatena con il nome della directory
in cui si trova il template individuata dalla funzione fillExtPars;
apre il file individuato, alloca tplString e vi scrive i dati del file;
se � specificato optFile lo usa al posto di quello specificato nella
stringa di get (per ora usa sempre la estensione di default).
tplDir e' la directori dove prndere il template;
*************************************************************************************/
int bufferTpl(char ** tplString, char * optFile, char * tplDir)
{
int tplLen=0;
long int contLen = 0;
char * dataBuffer = NULL;
char tplAbsName[TPL_ABS_NAME_LEN];
char tplName[TPL_NAME_LEN];
FILE *fTemplate;
// se non e' assegnato il file da usare come template si chiede alla url il
// parametro TPL_TAG per la definizione del nome del file; se non si trova
// si assegna il default template
/**/if(usedbg){fprintf(debug, "BUFFERTPL : STARTING\n");fflush(debug);}
if (optFile)
strcpy(tplName, optFile);
else if (cgiFormString(TPL_TAG, tplName, TPL_NAME_LEN) != cgiFormSuccess)
strcpy(tplName, DEFAULT_TPL);
if(strpbrk( tplName, "./\\" ))
EXIT(-1);
memset(CurrentTpl[TplNest],0,TPL_NAME_LEN);
strcpy(CurrentTpl[TplNest], tplName);
// si compone il tpl con il nome della directory di origine
// e con la estensione di default (TPL_EXT)
sprintf(tplAbsName,"%s\\%s%s",tplDir, tplName, TPL_EXT);
// sprintf(tplAbsName,"%s\\%s",tplDir, tplName);
/**/if(usedbg){fprintf(debug, "BUFFERTPL : TEMPLATE %s\n", tplAbsName);fflush(debug);}
// apertura e controllo del template da interpretare
if ( ( fTemplate = fopen(tplAbsName,"r") ) == 0 )
return 0;
//
// Valutazione della Content-length
//
fseek(fTemplate, 0, SEEK_SET);
contLen = ftell(fTemplate);
fseek(fTemplate, 0, SEEK_END);
contLen = ftell(fTemplate) - contLen;
rewind(fTemplate);
dataBuffer = (char*) calloc(contLen + 4096, sizeof(char) );if ((dataBuffer) == 0) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "+ + dataBuffer:%d + + len:%d\n", dataBuffer, contLen + 4096 );fflush(debug);}
// si copiano tutti i caratteri del template su dataBuffer
while ((dataBuffer[tplLen++] = fgetc(fTemplate)) != EOF);
dataBuffer[tplLen-1]=0; // sostituzione del carattere EOF con 0
*tplString = (char*) malloc(tplLen * sizeof(char) );if ((*tplString) == 0) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "+ + *tplString:%d + + len:%d\n", *tplString, tplLen * sizeof(char) );fflush(debug);}
if (dataBuffer == 0) return 0;
strcpy(*tplString, dataBuffer);
/**/if(usedbg){fprintf(debug, "BUFFERTPL : ENDING\n");fflush(debug);}
return 1;
}
/*************************************************************************************
NOME :verifyCmdSynt
stato :NUOVA. da completare con un check congruo per la sintassi dei comandi
attivita' :verifica che i primi caratteri di *tmplString siano quelli di uno dei
comandi e verifica la sintassi. cmdOrd identifica la posizione del comando
nell'array; argStr viene indirizzato su tplString all'inizio dell'argomento;
le stringhe vengono terminate ponendo a zero i caratteri di inizio e fine
argomento; tplString viene spostato alla fine del comando
return :se *tmplString inizia con un comando restituisce 1, se non sono verificate le
condizioni sintattiche torna 0, se non � stato chiuso l'argomento torna -1
chiamante :procTplData
chiama :
note :
*************************************************************************************/
int verifyCmdSynt(char ** tplString, int * cmdOrd, char ** argStr, char ** cmdStart)
{
int insideArg = 0;
int argTagNestingLev=-1;
int canBeCommand=1;
int cmdLen = 0;
int argLen = 0;
int i=0;
int cmdArgNotClosed=0;
char * holdTplString;
char * tmpArgP;
char strToEval[CMD_LEN+1];
// memorizzo la posizione di partenza della stringa e
// copio in un buffer un numero di caratteri della stringa pari al massimo numero
// consentito per il nome di un comando (+ il terminator)
holdTplString = *tplString;
strncpy(strToEval, *tplString+1, CMD_LEN+1);
// prima condizione da soddisfare: devo trovare il carattere di inizio argomento
for (cmdLen=0; cmdLen<=CMD_LEN+1; cmdLen++)
{
// la funzione � scettica: presuppone che la stringa non sia un comando
canBeCommand=0;
// se il carattere cmdLen � quello di inizio argomento..
if (strToEval[cmdLen]==CMD_ARG_OPEN_TAG)
{
// se viene trovato il carattere di inizio argomento altrove che nel primo
// carattere della stringa questa pu� essere un comando (altrimenti no,
// l'argomento deve essere preceduto da un nome)
if (cmdLen)
{
// l'argomento punta alla prima parentesi
tmpArgP = *tplString + cmdLen + 1;
// termino il buffer mettendo a zero il carattere dove ho trovato l'inizio argomento
strToEval[cmdLen]=0;
// sono all'interno dell'argomento
insideArg=1;
// sono entrato nel livello zero di annidamento parentesi
argTagNestingLev=0;
// condizione soddisfatta
canBeCommand=1;
}
break;
}
}
// se le condizioni fin qui richieste sono state soddisfatte
if (canBeCommand)
{
// la funzione continua a essere scettica: il fatto che si sia trovato un carattere
// di apertura argomento non la ha convinta
canBeCommand=0;
// si scorre l'array di CommandStructure
// e si comparano le etichette dei comandi con quella isolata ora
for(*cmdOrd = 0; CmdStruct[*cmdOrd].cmdName; (*cmdOrd)++)
{
if(!strcmp(strToEval, CmdStruct[*cmdOrd].cmdName))
{
// condizione soddisfatta
canBeCommand=1;
break;
}
}
}
// se le condizioni fin qui richieste sono state soddisfatte
if (canBeCommand)
{
// la funzione continua a essere scettica
canBeCommand=0;
// sposto il puntatore all'inizio del presunto argomento
*tplString = tmpArgP;
// procedo fino ad incontrere il carattere di fine stringa o fino a quando non esco dall'argomento
while (tmpArgP && insideArg)
{
// il puntatore si sposta al carattere successivo
(*tplString)++;
// se si tratta di un carattere di apertura argomento
if ( **tplString == CMD_ARG_OPEN_TAG )
{
// aumento il livello di annidamento parentesi
argTagNestingLev++;
}
// se trovo il carattere di chiusura argomento
else if (**tplString==CMD_ARG_CLOSE_TAG)
{
// se ho raggiunto il livello 0 ho esaurito l'argomento
if (argTagNestingLev==0)
insideArg=0;
// diminuisco il livello di annidamento parentesi
argTagNestingLev--;
}
}
// se ho esaurito l'argomento prima di terminare la stringa tutto ok
if (!insideArg)
canBeCommand=1;
else
cmdArgNotClosed=1;
}
// la sintassi di comando e' stata verificata, occorre ancora verificare che non
// ci si trovi in un ambiente di preprocessing nel qual caso solo alcuni comandi
// sono ammessi alla esecuzione
if (canBeCommand)
{
if (TntRequestType == RT_PREPROC)
{
if(CmdStruct[*cmdOrd].cmdType == PREPROC_IT)
canBeCommand = 1;
else
canBeCommand = 0;
}
else if (TntRequestType == RT_PREPROC_ALL)
{
if(strstr(strToEval,"^")!=0)
canBeCommand = 0;
}
}
// se � definitivamente un comando
if (canBeCommand)
{
// si fa puntare l'argomento al carattere successivo, il primo del argomento
(tmpArgP)++;
argLen = (*tplString) - (tmpArgP);
*argStr = (char*) malloc ( argLen * sizeof(char) );if (!(*argStr)) EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - *argStr:%d - - len:%d\n", *argStr, argLen * sizeof(char) );fflush(debug);}
strncpy( *argStr, tmpArgP, argLen + 1 );
(*argStr)[argLen] = 0;
}
else
{
// non � un comando
*cmdOrd = 0;
// niente comando
tmpArgP = NULL;
// niente argomento: rimettiamo la stringa a posto
*tplString = holdTplString;
}
*cmdStart = holdTplString - 1;
// se � un comando torna 1, se non lo � torna 0, se non � stato chiuso l'argomento torna -1
return canBeCommand-cmdArgNotClosed;
}
/*************************************************************************************
NOME :procTplData
stato :nuova; da completare i filtri per le funzioni ciclo e condizionale
attivita' :scandisce i dati letti in tplString e li scrive su outputStream se si trova
alla sommit� dei processi ricorsivi (li spedisce direttramente all'otput del
programma); li scrive su outputString se viene chiamata da se stessa
(restituisce i risultati al livello superiore per mezzo di una stringa)
chiamante :main (poi: cgiMain), procTplData (ricorsiva);
chiama :verifyCmdSynt, procTplData, runCmd;
note :
*************************************************************************************/
int procTplData(char * tplString, FILE * outputStream, char ** outputString)
{
int dataIsChar=1; //flag che indica se il dato da restituire � un semplice carattere
char * commandRetStr = NULL; //puntatore che verr� indirizzato al valore restituito dal comando eseguito (l'allocazione spetta al comando)
char * transfArg; //argomento di una funzione trasformato dalla chiamata ricorsiva
char * cmdStart;
char * argStr; //argomento grezzo del comando
char * outStrCrs; //cursore, si sposta partendo da *outputString
char * deadLine;
int tplLen, i=0;
int cmdOrd = 0;
int retStrLen = 0;
char * stampella;
// se non esiste outputStream sono all'interno di una ricorsione:
// non scriver� su stream di uscita ma su *outputString
if (!outputStream)
{
// lunghezza della stringa ricevuta (� l'argomento grezzo di una funzione)
tplLen=strlen(tplString);
//**/if(usedbg){fprintf(debug, "PARSER- tplLen:%d\n", tplLen);fflush(debug);}
// prima allocazione: viene riservato lo spazio della stringa grezza
// (tale rimarr� se la stringa grezza non contiene comandi e quindi non viene modificata)
*outputString=(char*)malloc( (tplLen)* sizeof(char));if (!(*outputString)) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "- - *outputString:%d - - len:%d\n", *outputString, (tplLen)* sizeof(char) );fflush(debug);}
// inizializzazione del cursore
outStrCrs = *outputString;
}
while (*tplString != 0)
{
//**/if(usedbg){fprintf(debug, "%c", *tplString);fflush(debug);}
// di default non mi aspetto un comando: assumo che il dato sia un carattere da copiare
// in uscita cos� come �
dataIsChar=1;
// se incontro il carattere di segnalazione comando
if (*tplString==START_COMMAND_TAG)
{
// verifico la sintassi del comando e metto i puntatori su tplString
// all'inizio del nome del comando e dell'argomento (termino le stringhe ponendo
// a zero i caratteri di inizio e fine argomento); tplString viene spostato a fine comando
if (verifyCmdSynt(&tplString, &cmdOrd, &argStr, &cmdStart))
{
//
if (CmdStruct[cmdOrd].cmdType == START_CND_BLK)
{
CndLevel++;
// si ereditano le colpe dei padri
if (ValidBlock[CndLevel-1] == 0) ValidBlock[CndLevel] = 0;
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
else if (CmdStruct[cmdOrd].cmdType == ELSE_CND_BLK)
{
if (ValidBlock[CndLevel] == 0)
ValidBlock[CndLevel] = 1;
else if (ValidBlock[CndLevel] == 1)
ValidBlock[CndLevel] = 0;
// si ereditano le colpe dei padri
if (ValidBlock[CndLevel-1] == 0) ValidBlock[CndLevel] = 0;
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
if ( (ValidBlock[CndLevel] !=0) &&
(CmdStruct[cmdOrd].cmdType == START_CYCLE) )
{
CycLevel++;
pushStk(&cycleStk, cmdStart);
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
//**/if(usedbg){fprintf(debug, "\nFound:%s - CycLevel %d=%d;CndLevel %d=%d\n", CmdStruct[cmdOrd].cmdName, CycLevel, ReadCycle[CycLevel], CndLevel,ValidBlock[CndLevel]);fflush(debug);}
// esecuzione comando
if (ValidBlock[CndLevel] && ReadCycle[CycLevel])
{
// chiamata ricorsiva: l'argomento del comando viene interpretato e restituito su
// transfArg; il file pointer (secondo argomento) viene passato NULL per permettere
// il riconoscimento del livello interno di ricorsione
procTplData( argStr, NULL, &transfArg);
/**/if(usedbg){fprintf(debug, "Executing:%s - ", CmdStruct[cmdOrd].cmdName );fflush(debug);}
commandRetStr = (char*) CmdStruct[cmdOrd].cmdFunction( 0, 0, transfArg);
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
if ( (ValidBlock[CndLevel] !=0) &&
(CmdStruct[cmdOrd].cmdType == END_CYCLE) )
{
if ( ReadCycle[CycLevel] )
popStk(&cycleStk, &tplString);
else
{
popStk(&cycleStk, &deadLine);
ReadCycle[CycLevel] = 1;
}
CycLevel--;
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
if (CmdStruct[cmdOrd].cmdType == END_CND_BLK)
{
ValidBlock[CndLevel] = 1;
CndLevel--;
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
}
}
if (ValidBlock[CndLevel] && ReadCycle[CycLevel])
{
// se il carattere letto non � il principio di un comando va scritto in output cos� come �
if(dataIsChar)
{
// se esiste l'output stream (livello zero di ricorsione)
if (outputStream)
{
//**/if(usedbg){fprintf(debug, "%c", *tplString);fflush(debug);}
fputc(*tplString, outputStream);
// fflush(outputStream);
}
// se non esiste lo stream di uscita (livelli successivi di ricorsione)
else
{
*outStrCrs++ = *tplString;
}
}
// il dato non � un singolo carattere ma una stringa
// risultato dell'elaborazione di un comando
else
{
// se esiste l'output stream (livello zero di ricorsione)
if (outputStream)
{
i=0;
// si copia la stringa di ritorno del comando sullo stream di uscita
if (commandRetStr)
{
while ( commandRetStr[i])
{
//**/if(usedbg){fprintf(debug, "%c", commandRetStr[i]);fflush(debug);}
fputc(commandRetStr[i++], outputStream);
}
}
// fflush(outputStream);
}
// se non esiste lo stream di uscita (livelli successivi di ricorsione)
else
{
if (commandRetStr && (retStrLen = strlen(commandRetStr)))
{
// si termina outStrCrs (sulla posizione finale della stringa)
*outStrCrs = 0;
stampella = (char*) malloc( ( tplLen + retStrLen + 1 ) * sizeof(char));if (!(stampella)) EXIT(MEMERR);
tplLen = tplLen + retStrLen + 1;
//**/if(usedbg){fprintf(debug, "\nPARSER- Stampella Len:%d\n", tplLen + retStrLen + 1);fflush(debug);}
if (*outputString)
{
strcpy(stampella, *outputString);
}
//BOH *outputString = (char*)realloc( *outputString , ( tplLen + retStrLen + 1) * sizeof(char));if (!(*outputString)) EXIT(23);/*aggiungo alla dimensione inizialmente prevista per *outputString un numero di byte pari alla lunghezza della stringa restituita dal comando*/
// aggiungo il risultato del comando
strcat(stampella, commandRetStr);
*outputString = stampella;
// si risposta il puntatore alla fine
// (per continuare ad aggiungere dati)
outStrCrs = strchr(*outputString, 0);
}
}
commandRetStr = NULL;
}
}
tplString++;
}
if (!outputStream)
{ // nel caso sia in un livello di ricorsione
// prima di uscire si termina la stringa costruita
*outStrCrs = 0;
}
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* olimpybet.cpp 24/08/2000
*
* utility wrap for the public domain DES implementation by <NAME>
*
* filename: tqrext.cpp
* description: tannitqueryresult manipolation functions from
* client inputs and various tannit template command extensions
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
AITECSA s.r.l. 2000
#ifndef __ITX_OLIMPYBET_CPP__
#define __ITX_OLIMPYBET_CPP__
#endif
#include "stdio.h"
#include "stdlib.h"
#include "memory.h"
#include "string.h"
#include "tannit.h"
#include "itannitc.h"
#include "extVars.h"
#include "itxtypes.h"
#define MATRICE_LEN 12
#define MATRICE_INC 1
#define MATRICE_LST 6
#define MATRICE_SPC (MATRICE_LST - 1)
#define SYMBOL_NUM 26
#define MATRICE_NORM 32356 // max 65535 (4 chars)
#define MAX_SERIAL (MATRICE_NORM * SYMBOL_NUM)
#define MAX_MLPFREQ 10
#define SPECIAL_NULL 1
#define SPECIAL_OLIM 2
#define SPECIAL_WRLD 5
#define OLBT_SUCCESSED 0
#define OLBT_ERR_CONN 1
#define OLBT_ERR_ODBC 2
#define OLBT_EVENT_CLOSED 3
#define OLBT_END_RC_TOKS 4
#define OLBT_END_BT_TOKS 5
#define OLBT_ERR_RECEIPT 6
char appo_matrice[MATRICE_LEN+1];
char errorcode[6];
bool Receipt(char* matrice, int serial)
{
if (serial > MAX_SERIAL) return false;
try
{
memset(matrice, '0', MATRICE_LEN);
memset(appo_matrice, '\0', MATRICE_LEN + 1);
matrice[MATRICE_LEN] = '\0';
int serie = serial / MATRICE_NORM;
matrice[0] = serie + 65; // 65 is ascii value for 'A'
matrice[MATRICE_SPC] = matrice[0];
int residual = serial % MATRICE_NORM;
sprintf(appo_matrice, "%X", residual);
int appolen = strlen(appo_matrice);
memcpy(&matrice[MATRICE_SPC - appolen], appo_matrice, appolen);
matrice[MATRICE_LST] = '\0';
sprintf(appo_matrice, "%s", matrice);
return true;
}
catch(...)
{
memset(appo_matrice, '\0', MATRICE_LEN + 1);
return false;
}
}
int BetTrisInput(char* user, int event, int amount, char* gold, char* silver, char* bronze, int special, FILE* log)
{
int result = OLBT_SUCCESSED;
int seriale, maxscommesse, nsco, nmlpf, mlpbase;
int mlpfreq;
int gpronostico, grecord;
char receipt[MATRICE_LEN+1];
char query[1024];
TannitQueryResult* qres;
if (
(user == NULL) ||
(!(event > 0 && event < 301)) ||
(amount != 1) ||
(gold == NULL) ||
(silver == NULL) ||
(bronze == NULL) ||
(ISNULL(gold)) ||
(ISNULL(silver)) ||
(ISNULL(bronze)) ||
(!(special == 0 || special == 1))
)
return OLBT_ERR_RECEIPT;
memset(query, '\0', 1024);
//**/if(usedbg){fprintf(debug, "Connetction...\n");fflush(debug);}
if (ITannit_ConnectSQL(Odbcdsn, Odbcuid, Odbcpwd))
{
//**/if(usedbg){fprintf(debug, "Manual Commit...\n");fflush(debug);}
if (ITannit_ManualCommitSQL())
{
//**/if(usedbg){fprintf(debug, "Select scalari...\n");fflush(debug);}
// recupero i valori scalari globali
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, "Serial", "SELECT * FROM Scalari WITH (TABLOCKX)", 1, 512) != ITXFAILED)
{
qres= ITannit_FindQuery("Serial");
seriale = atoi(ITannit_GetValue(qres, 1, "Seriale"));
maxscommesse = atoi(ITannit_GetValue(qres, 1, "MaxScommesse"));
// calcolo della ricevuta
//**/if(usedbg){fprintf(debug, "Calculate receipt...\n");fflush(debug);}
if (Receipt(receipt, seriale))
{
// prendo i valori interessanti della finale
//**/if(usedbg){fprintf(debug, "Select Finali...\n");fflush(debug);}
sprintf(query, "SELECT NumeroScommesse, MlpBase, MlpFrequenza, Chiusa FROM Finali WHERE ID = %d", event);
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, "Finale", query, 1, 512) != ITXFAILED)
{
//**/if(usedbg){fprintf(debug, "Finali selected...\n");fflush(debug);}
qres = ITannit_FindQuery("Finale");
//**/if(usedbg){fprintf(debug, "1...%x\n", qres);fflush(debug);}
nsco = atoi(ITannit_GetValue(qres, 1, "NumeroScommesse"));
//**/if(usedbg){fprintf(debug, "2...\n");fflush(debug);}
mlpbase = atoi(ITannit_GetValue(qres, 1, "MlpBase"));
//**/if(usedbg){fprintf(debug, "3...\n");fflush(debug);}
mlpfreq = atoi(ITannit_GetValue(qres, 1, "MlpFrequenza"));
//**/if(usedbg){fprintf(debug, "4...\n");fflush(debug);}
int chiusa = atoi(ITannit_GetValue(qres, 1, "Chiusa"));
//**/if(usedbg){fprintf(debug, "Check on Chiusa...\n");fflush(debug);}
if (chiusa == 0)
{
nsco++;
if (nsco > maxscommesse)
maxscommesse = nsco;
// ricalcolo del moltiplicatore di frequenza
nmlpf = (int)(MAX_MLPFREQ - (int)((float)((float) (nsco * MAX_MLPFREQ)/ (float) maxscommesse)));
// aggiorno la finale con i nuovi valori
sprintf(query, "UPDATE Finali SET NumeroScommesse = %d, MlpFrequenza = %d WHERE ID = %d", nsco, nmlpf, event);
//**/if(usedbg){fprintf(debug, "Update Finali...\n");fflush(debug);}
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, 0, query, 1, 512) != ITXFAILED)
{
// inserisco il pronostico utente
//**/if(usedbg){fprintf(debug, "Insert Pronostico...\n");fflush(debug);}
sprintf(query, "INSERT INTO Pronostici (Utente, Finale, MlpBase, MlpFrequenza, GettoniGiocati, Matrice, Oro, Argento, Bronzo, GiocataRecord) VALUES ('%s', %d, %d, %d, %d, '%s', '%s', '%s', '%s', %d)", user, event, mlpbase, mlpfreq, amount, receipt, gold, silver, bronze, special);
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, 0, query, 1, 512) != ITXFAILED)
{
// aggiorno lo scalare seriale e il massimo numero di scommesse
seriale += MATRICE_INC;
sprintf(query, "UPDATE Scalari SET Seriale = %d, MaxScommesse = %d", seriale, maxscommesse);
//**/if(usedbg){fprintf(debug, "Update Scalari...\n");fflush(debug);}
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, 0, query, 1, 512) != ITXFAILED)
{
// aggiornamento dei gettoni utente
sprintf(query, "SELECT GettoniPronostico, GettoniRecord FROM Partecipanti WHERE Utente = '%s'", user);
//**/if(usedbg){fprintf(debug, "Select Partecipanti...\n");fflush(debug);}
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, "User", query, 1, 512) != ITXFAILED)
{
qres = ITannit_FindQuery("User");
if (qres->totalRows > 0)
{
gpronostico = atoi(ITannit_GetValue(qres, 1, "GettoniPronostico"));
grecord = atoi(ITannit_GetValue(qres, 1, "GettoniRecord"));
if (gpronostico > 0)
{
gpronostico--;
if (!(grecord <= 0 && special != 0))
{
if (special != 0)
grecord--;
sprintf(query, "UPDATE Partecipanti SET GettoniPronostico = %d, GettoniRecord = %d WHERE Utente = '%s'", gpronostico, grecord, user);
//**/if(usedbg){fprintf(debug, "Update Partecipanti...\n");fflush(debug);}
if (ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, 0, query, 1, 512) != ITXFAILED)
ITannit_CommitSQL();
else
result = OLBT_ERR_ODBC; //update partecipanti failed
}
else
result = OLBT_END_RC_TOKS; // wrong parameters (no more record tokens)
}
else
result = OLBT_END_BT_TOKS; // wrong parameters (no more bet-tokens)
}
else
result = OLBT_ERR_RECEIPT; // � arrivato un valore user non presente nel DB
}
else
result = OLBT_ERR_ODBC; // select from partecipanti failed
}
else
result = OLBT_ERR_ODBC; // update scalari failed
}
else
result = OLBT_ERR_ODBC; // insert pronostico failed
}
else
result = OLBT_ERR_ODBC; // update finali
}
else
result = OLBT_EVENT_CLOSED; // finale chiusa
}
else
result = OLBT_ERR_ODBC; // select from finali failed
}
else
result = OLBT_ERR_RECEIPT; // calcolo ricevuta failed
}
else
result = OLBT_ERR_ODBC; // select scalari failed
}
else
result = OLBT_ERR_ODBC; // Manual commit mode failed
}
else
result = OLBT_ERR_CONN; // connection failed
if (result != OLBT_SUCCESSED)
{
//**/if(usedbg){fprintf(debug, "Error Condition...\n");fflush(debug);}
memset(appo_matrice, '\0', MATRICE_LEN + 1);
ITannit_ErrorSQL(log);
ITannit_RollbackSQL();
ITannit_AutoCommitSQL();
}
return result;
}
/*************************************************************************************
NOME : olimpybet
Categoria : Gasp Command: olimpybet
attivita' : inserisce la scommessa per il gioco Olimpy-Bet
valori di ritorno:
se ha successo ritorna una stringa di 6 caratteri alfanumerici
che rappresenta la ricevuta della scommessa
se fallisce ritorna un carattere nel seguente set:
'1' : connessione con il DBMS fallita
'2' : istruzione ODBC fallita
'3' : gara chiusa
'4' : gettoni record insufficienti
'5' : gettoni pronostici insufficienti
'6' : errore nel calcolo della ricevuta
*************************************************************************************/
void* olimpybet(int vuoto1, char *vuoto2, char * inputStr)
{
char* user;
int event;
char* gold;
char* silver;
char* bronze;
int special;
char* c_event;
char* c_special;
int betdone;
if(!pickPar(inputStr, 1, &user)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &c_event)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &gold)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 4, &silver)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 5, &bronze)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 6, &c_special)) return(PARAM_NOT_FOUND_MSG);
event = atoi(c_event);
special = atoi(c_special);
ITannit_Create(QueryResultSet, &QueryCounter);
/**/if(usedbg){fprintf(debug, "Entering BetTrisInput\n");fflush(debug);}
betdone = BetTrisInput(user, event, 1, gold, silver, bronze, special, debug);
/**/if(usedbg){fprintf(debug, "Exiting BetTrisInput return value: %d\n", betdone);fflush(debug);}
ITannit_Destroy();
if (betdone == OLBT_SUCCESSED)
return appo_matrice;
else
{
memset(errorcode, '\0', 6);
sprintf(errorcode, "%d", betdone);
return errorcode;
}
}
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.aux;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
public class Tools
{
private final static String DEFAULT_DATE_FORMAT = "dd/MM/yyyy";
private final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public Tools()
{
}
/*****************************************************************************
Message boxes
****************************************************************************/
//---------------------------------------------------------------------------------------------
public static void msgBox(String msg)
{
JOptionPane.showMessageDialog(null, msg, "JTXTools Message Box", JOptionPane.INFORMATION_MESSAGE);
}
//---------------------------------------------------------------------------------------------
public static void msgBox(String msg, String title)
{
JOptionPane.showMessageDialog(null, msg, title, JOptionPane.INFORMATION_MESSAGE);
}
//---------------------------------------------------------------------------------------------
public static int confirmBox(String msg, String title)
{
return JOptionPane.showConfirmDialog(null, msg, title, JOptionPane.YES_NO_CANCEL_OPTION);
}
//---------------------------------------------------------------------------------------------
public static int confirmBoxY_N(String msg, String title)
{
return JOptionPane.showConfirmDialog(null, msg, title, JOptionPane.YES_NO_OPTION);
}
/*****************************************************************************
Date and time management
****************************************************************************/
//---------------------------------------------------------------------------------------------
public static String timeConvert(GregorianCalendar gcalendar)
{
Integer intcal = new Integer(3600 * gcalendar.get(Calendar.HOUR_OF_DAY) +
60 * gcalendar.get(Calendar.MINUTE) +
gcalendar.get(Calendar.SECOND));
return intcal.toString();
}
//---------------------------------------------------------------------------------------------
public static String timeConvert(Date d)
{
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(d);
return timeConvert(gc);
}
//---------------------------------------------------------------------------------------------
public static String timeConvert(String str)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_TIME_FORMAT);
GregorianCalendar gc = new GregorianCalendar();
sdf.setCalendar(gc);
gc.setLenient(false);
try
{
Date dayDate = sdf.parse(str);
gc.setTime(dayDate);
}
catch(ParseException pe)
{
Debug.Dbg("ParseException in timeConvert: " + pe.getMessage());
}
return timeConvert(gc);
}
//---------------------------------------------------------------------------------------------
public static int minsecConvert(String str)
{
int ret = 0;
int min = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '\'')
{
ret = ret + ((new Integer(str.substring(min, i))).intValue() * 60);
min = i + 1;
}
else if (str.charAt(i) == '\"')
return (ret + (new Integer(str.substring(min, i))).intValue());
}
return ret;
}
//---------------------------------------------------------------------------------------------
public static String dateToString(String begdate, int ndays)
{
String ret = "";
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
GregorianCalendar gc = new GregorianCalendar();
sdf.setCalendar(gc);
gc.setLenient(false);
try
{
if (ndays != 0)
{
java.util.Date auxdate = sdf.parse(begdate);
gc.setTime(auxdate);
ret = dateToString(gc, ndays);
}
else
ret = begdate;
}
catch(ParseException pe)
{
Debug.Dbg("ParseException in dateToString: " + pe.getMessage());
return "";
}
return ret;
}
//--------------------------------------------------------------------
public static String dateToString(GregorianCalendar begdate, int ndays)
{
String ret = "";
GregorianCalendar gc = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
sdf.setCalendar(gc);
gc.setTime(begdate.getTime());
gc.setLenient(false);
if (ndays != 0)
gc.add(Calendar.DATE, ndays);
ret = sdf.format(gc.getTime());
return ret;
}
//--------------------------------------------------------------------
public static String dateToString(Date begdate, int ndays)
{
return dateToString(dateToString(begdate), ndays);
}
//--------------------------------------------------------------------
public static String dateToString(Date d)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
return sdf.format(d);
}
//--------------------------------------------------------------------
public static Date stringToDate(String dateString)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
java.util.Date dt = new Date();
try
{
dt = sdf.parse(dateString);
}
catch(ParseException pe)
{
Debug.Dbg("ParseException in stringToDate: " + pe.getMessage());
return dt;
}
return dt;
}
//--------------------------------------------------------------------
public static int stringToInt(String num)
{
try{return Integer.parseInt(num);}
catch(Exception e){return 0;}
}
//--------------------------------------------------------------------
public static int stringToInt(String num, int default_return)
{
try{return Integer.parseInt(num);}
catch(Exception e){return default_return;}
}
//--------------------------------------------------------------------
public static long stringToLong(String num)
{
try{return Long.parseLong(num);}
catch(Exception e){return 0L;}
}
//--------------------------------------------------------------------
public static double stringToDouble(String num)
{
try{return Double.parseDouble(num);}
catch(Exception e){return 0.0;}
}
//--------------------------------------------------------------------
public static GregorianCalendar stringToCalendar(String dateString)
{
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(stringToDate(dateString));
return gc;
}
//--------------------------------------------------------------------
public static String getWeekdayName(String yyyyMMdd)
{
String ret = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
GregorianCalendar gc = new GregorianCalendar();
try
{
gc.setTime(sdf.parse(yyyyMMdd));
sdf.setCalendar(gc);
ret = sdf.getDateFormatSymbols().getWeekdays()[gc.get(Calendar.DAY_OF_WEEK)];
}
catch (ParseException ex) {ex.printStackTrace();}
return ret;
}
//--------------------------------------------------------------------
public static int compareDay(GregorianCalendar day1, GregorianCalendar day2)
{
int month_1 = day1.get(Calendar.MONTH);
int month_2 = day2.get(Calendar.MONTH);
int day_1 = day1.get(Calendar.DAY_OF_MONTH);
int day_2 = day2.get(Calendar.DAY_OF_MONTH);
int ret = 0;
if ((month_1 - month_2) == 0)
ret = (day_1 - day_2);
else if ((month_1 - month_2) > 0)
ret = 1;
else if ((month_1 - month_2) < 0)
ret = -1;
return ret;
}
/*******************************************************************************
Date manip. routines for database
*******************************************************************************/
//--------------------------------------------------------------------
public static String SQLQuotes(String in)
{
if (in == null)
return "";
int pos = 0;
int oldpos = 0;
String ret = "";
while ((pos = in.indexOf('\'', pos)) != -1)
{
pos++;
ret += in.substring(oldpos, pos) + "'";
oldpos = pos;
}
ret += in.substring(oldpos, in.length());
return ret;
}
//--------------------------------------------------------------------
public static String SQLQuotesEnclose(String in)
{
return "'" + SQLQuotes(in) + "'";
}
//--------------------------------------------------------------------
public static boolean isValidDate(String dateString)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
GregorianCalendar gc = new GregorianCalendar();
sdf.setCalendar(gc);
gc.setLenient(false);
try
{
if ( (dateString.length() != 10) ||
(!(dateString.substring(2, 3)).equals("/")) ||
(!(dateString.substring(5, 6)).equals("/")) )
return false;
gc.setTime(sdf.parse(dateString));
}
catch(Exception e)
{
return false;
}
return true;
}
//--------------------------------------------------------------------
public static boolean isValidTime(String timeString)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_TIME_FORMAT);
GregorianCalendar gc = new GregorianCalendar();
sdf.setCalendar(gc);
gc.setLenient(false);
try
{
if ( (timeString.length() != 8) ||
(!(timeString.substring(2, 3)).equals(":")) ||
(!(timeString.substring(5, 6)).equals(":")) )
return false;
int first = (new Integer(timeString.substring(0, 2))).intValue();
int second = (new Integer(timeString.substring(3, 5))).intValue();
int third = (new Integer(timeString.substring(6, 8))).intValue();
if ( (first > 23) || (second > 59) || (third >59) )
return false;
gc.setTime(sdf.parse(timeString));
}
catch(Exception e)
{
return false;
}
return true;
}
//--------------------------------------------------------------------
public static boolean isNumber(String numberstr)
{
try{Integer.parseInt(numberstr);}
catch(Exception e){return false;}
return true;
}
//--------------------------------------------------------------------
public static boolean isDigit(char v) { return Character.isDigit(v); }
//--------------------------------------------------------------------
public static boolean isAlpha(char v) { return Character.isLetter(v);}
//--------------------------------------------------------------------
public static boolean isAlphaNumeric(char v) { return Character.isLetterOrDigit(v); }
//--------------------------------------------------------------------
public static boolean isAlpha(String str)
{
if (str == null)
return false;
int strlen = str.length();
for(int i=0; i<strlen; i++)
if (Character.isLetter(str.charAt(i)) == false)
return false;
return true;
}
//--------------------------------------------------------------------
// number or digit
public static boolean isAlphaNumeric(String str)
{
if (str == null)
return false;
int strlen = str.length();
for(int i=0; i<strlen; i++)
if (Character.isLetterOrDigit(str.charAt(i)) == false)
return false;
return true;
}
//--------------------------------------------------------------------
public static String date2DB(String date2conv)
{
String ret = "";
if (date2conv.length() == 10) // input format: xx/xx/yyyy
ret = date2conv.substring(6, 10) + date2conv.substring(3, 5) + date2conv.substring(0, 2);
return ret;
}
//--------------------------------------------------------------------
public static String DB2Date(String date2conv)
{
String ret = "";
if (date2conv == null)
return "";
if (date2conv.length() == 8) // input format: yyyyMMdd
ret = date2conv.substring(6, 8) + "/" + date2conv.substring(4, 6) + "/" + date2conv.substring(0, 4);
return ret;
}
//--------------------------------------------------------------------
public static String date2DB(Date date2conv)
{
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
return date2DB(sdf.format(date2conv));
}
//*********************************
// IPC Message manip. routines
//*********************************
//--------------------------------------------------------------------
public static String IPCgetID(String message, String token)
{
return (new StringTokenizer(message, token)).nextToken();
}
//--------------------------------------------------------------------
//index = 0 for the first token
public static String IPCgetToken(String message, int index, String token)
{
String strtoken = "";
StringTokenizer tokenizer = new StringTokenizer(message, token, true);
if (index < 0)
return message;
// if (index == 0)
// {
// strtoken = tokenizer.nextToken();
// return (strtoken.equals(token) ? "" : strtoken);
// }
//Here, index is strictly positive
int count = 0;
while (count < index && tokenizer.hasMoreTokens())
{
strtoken = tokenizer.nextToken();
if (strtoken.equals(token))
count++;
}
if (count < index)
return message;
strtoken = tokenizer.nextToken();
return (strtoken.equals(token) ? "" : strtoken);
}
//*********************************
// Time & duration manip. routines
//*********************************
//---------------------------------------------------------------------
public static String duration2String(int min, int sec)
{
if (min < 0)
return "";
else if(sec < 0 || sec > 59)
return "";
else
return min + "'" + sec + "\"";
}
//---------------------------------------------------------------------
public static String duration2String(int totalSecs)
{
if (totalSecs < 0)
return "";
else
return (totalSecs / 60) + "'" + (totalSecs % 60) + "\"";
}
//---------------------------------------------------------------------
public static int minFromDuration(String duration)
{
int index = duration.indexOf('\'');
return (index < 0 ? 0 : Integer.parseInt(duration.substring(0, index).trim()));
}
//---------------------------------------------------------------------
public static int secFromDuration(String duration)
{
int indexStart = duration.indexOf('\'');
int indexEnd = duration.indexOf('"');
return (indexEnd < 0 ? 0 : Integer.parseInt(duration.substring(indexStart + 1, indexEnd).trim()));
}
//---------------------------------------------------------------------
public static int totalFromDuration(String duration)
{
return (minFromDuration(duration)*60)+ secFromDuration(duration);
}
//---------------------------------------------------------------------
public static boolean isValidDuration(String duration)
{
try
{
int apex = duration.indexOf('\'');
int quote = duration.indexOf('\"');
if (apex < 0 && quote < 0)
return false;
if (apex >= 0)
Integer.parseInt(duration.substring(0, apex).trim());
if (quote >= 0)
Integer.parseInt(duration.substring(apex + 1, quote).trim());
}
catch(NumberFormatException nfe)
{
Debug.Dbg("NumberFormatException Exception in isValidDuration");
return false;
}
catch(Exception e)
{
Debug.Dbg("Exception in isValidDuration");
return false;
}
return true;
}
//---------------------------------------------------------------------------------------------
public static String formatSecsFromMidnight(String strTime, String sum)
{
int timeInt = (new Integer(strTime)).intValue();
int sumInt = (new Integer(sum)).intValue();
return formatSecsFromMidnight(timeInt + sumInt);
}
//---------------------------------------------------------------------
public static String formatSecsFromMidnight(int intTime)
{
String strHours;
String strMins;
String strSecs;
if (intTime >= 86400)
intTime = intTime - 86400;
int mins = intTime / 60;
int hours = mins / 60;
int secs = intTime - mins * 60;
mins = mins - hours * 60;
if ( hours < 10)
strHours = "0" + hours;
else
strHours = "" + hours;
if ( mins < 10)
strMins = "0" + mins;
else
strMins = "" + mins;
if ( secs < 10)
strSecs = "0" + secs;
else
strSecs = "" + secs;
return strHours + ":" + strMins + ":" + strSecs;
}
//---------------------------------------------------------------------
public static String monthNameEN(int month_num)
{
String ret = "";
switch (month_num)
{
case 1: ret = "January"; break;
case 2: ret = "February"; break;
case 3: ret = "March"; break;
case 4: ret = "April"; break;
case 5: ret = "May"; break;
case 6: ret = "June"; break;
case 7: ret = "July"; break;
case 8: ret = "August"; break;
case 9: ret = "September"; break;
case 10: ret = "October"; break;
case 11: ret = "November"; break;
case 12: ret = "December"; break;
}
return ret;
}
//---------------------------------------------------------------------
public static String monthNameEN(String month_num)
{
int monthnum = 0;
try{monthnum = Integer.parseInt(month_num);}
catch(NumberFormatException nfe){nfe.printStackTrace();}
return monthNameEN(monthnum);
}
//*********************************
// Path manip. routines
//*********************************
public static String prefixRelativePath(String root_part, String relative_part)
{
String sep = System.getProperty("file.separator");
if (root_part.endsWith(sep))
{
if (relative_part.startsWith(sep))
relative_part = relative_part.substring(1, relative_part.length());
}
else
{
if (!relative_part.startsWith(sep))
relative_part = sep + relative_part;
}
return relative_part;
}
//---------------------------------------------------------------------------------------------
public static String addEndSlash(String path)
{
String sep = System.getProperty("file.separator");
if (path.endsWith(sep))
return path;
else
return (path + sep);
}
//---------------------------------------------------------------------------------------------
public static boolean isValidPath(String str)
{
boolean valid = true;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ':' || str.charAt(i) == '*' ||
str.charAt(i) == '?' || str.charAt(i) == '"' ||
str.charAt(i) == '<' || str.charAt(i) == '>' ||
str.charAt(i) == '|')
valid = false;
}
return valid;
}
//*********************************
// IO routines
//*********************************
//---------------------------------------------------------------------------------------------
/**
* Read a file from disk and place the content in a String.
*
* @param fileName The name of the file (should be in the classpath)
* @return a String with the content of the file.
* @throws RuntimeException In case there is an error loading the file.
*/
public static String readFile(String fileName)
{
URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);
if (url == null)
throw new RuntimeException("JTXTools: File '" + fileName + "' not found in classpath.");
return readFile(url);
}
//---------------------------------------------------------------------------------------------
/**
* Read a file from disk and place the content in a String.
*
* @param url The name of the resource (should be in the classpath)
* @return a String with the content of the file or an
* empty string if parameter 'url' is null.
* @throws RuntimeException In case there is an error loading the file.
*/
public static String readFile(URL url)
{
if (url == null)
return "";
BufferedReader in = null;
StringBuffer message = new StringBuffer();
try
{
in = new BufferedReader(new FileReader(url.getFile()));
String line = null;
while ((line = in.readLine()) != null)
message.append(line);
in.close();
}
catch (FileNotFoundException e)
{
throw new RuntimeException("JTXTools: File '" + url.getFile() + "' not found.");
}
catch (IOException e)
{
throw new RuntimeException("JTXTools: Error reading file '" + url.getFile() + "'.");
}
return message.toString();
}
//---------------------------------------------------------------------------------------------
/**
* Create one or more directories.
*
* Either '/' or '\' should be used as a path seperator.<BR>
* <BR>
* Example: foo/test/bar
*
* @param path The name of the path to be created
* @return true in case of success
*/
public static boolean mkdirs(String path)
{
File dir = new File(path);
return dir.mkdirs();
}
//---------------------------------------------------------------------------------------------
/**
* Remove one or more directories
*
* Either '/' or '\' should be used as a path seperator.<BR>
* <BR>
* Example: foo/test/bar
*
* @param path The name of the path to be created
* @return true in case of success
*/
public static boolean removeDirectory(String path)
{
File dir = new File(path);
return dir.delete();
}
//---------------------------------------------------------------------------------------------
/**
* Check if a path exists
*
* Either '/' or '\' should be used as a path seperator.<BR>
* <BR>
* Example: foo/test/bar
*
* @param path The name of the path to be created
* @return true in case of success
*/
public static boolean directoryExists(String path)
{
File dir = new File(path);
return dir.isDirectory() && dir.exists();
}
//---------------------------------------------------------------------------------------------
/**
* Convert a Java package name to a full path name with the given path separator
* or the native file system one if sep == "".
*
* <BR>
* Example: packageName=net.sourceforge.anttestsetgen<BR>
* The result will then be net/sourceforge/anttestsetgen
*
* @param packageName The Java package name
* @param sep The requested path separator (can be null or "")
* @return the full path
*/
public static String convertPackageToPath(String packageName, String sep)
{
if (packageName != null && !packageName.equals(""))
{
if (sep == null || sep.equals(""))
return packageName.replace('.', System.getProperty("file.separator").charAt(0));
else
return packageName.replace('.', sep.charAt(0));
}
else
return "";
}
//---------------------------------------------------------------------------------------------
/**
* Convert a Java package name to a full path name with the given path separator
* or the native file system one if sep == "".
*
* <BR>
* Example: packageName=net.sourceforge.anttestsetgen<BR>
* The result will then be net/sourceforge/anttestsetgen
*
* @param package The Java package object
* @param sep The requested path separator (can be null or "")
* @return the full path
*/
public static String convertPackageToPath(Package _package, String sep)
{
return convertPackageToPath(_package.getName(), sep);
}
//---------------------------------------------------------------------------------------------
/**
* Remove a file from the file system.
*
* No status info is given about the success (or failure) of the operation.
*
* @param fileName The name of the file to be removed.
*/
public static void removeFile(String fileName)
{
File file = new File(fileName);
file.delete();
}
//---------------------------------------------------------------------------------------------
/**
* Check if a file exists in the file system.
*
* @param fileName The name of the file to be removed.
* @return True in case the file exists.
*/
public static boolean fileExists(String fileName)
{
File file = new File(fileName);
return file.exists();
}
} // End class
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#include "tannit.h"
#include "itannitc.h"
#include "extVars.h"
int Ciccio=1;
//
/*************************************************************************************
NOME :isAlphaNum
Categoria :servizio
attivita' :controlla se il carattere in input e' un alfanumerico
return :l'indice del carattere trovato in un ipotetica lista che comprende i dieci
simboli numerici, quindi l'alfabeto minuscolo e quindi l'alfabeto maiuscolo;
zero se il carattere non viene trovato.
*************************************************************************************/
int isAlphaNum(char testCh)
{
int charKind = 0;
if ((testCh > 47) && (testCh < 58)) charKind = testCh - 47;
else if ((testCh > 64) && (testCh < 91)) charKind = testCh - 64 + 10;
else if ((testCh > 96) && (testCh < 123)) charKind = testCh - 96 + 36;
return charKind;
}
/*************************************************************************************
NOME :reAlphaNum
Categoria :servizio
attivita' :inversa della funzione isAlphaNum;
cerca il carattere corrispondente all'intero di input considerando questo
come un indice in un ipotetica lista comprendente i dieci simboli numerici,
quindi l'alfabeto minuscolo e quindi l'alfabeto maiuscolo;
return :il carattere in chiaro; non ho capito cosa fa quando non trova l'indice
si alluppa? boh
*************************************************************************************/
int reAlphaNum(char codedCh)
{
int resCh = 0;
while(1)
{
if ((codedCh > 0) && (codedCh < 11)) {resCh = codedCh + 47; break;}
else if ((codedCh > 10) && (codedCh < 37)) {resCh = codedCh + 64 - 10; break;}
else if ((codedCh > 36) && (codedCh < 63)) {resCh = codedCh + 96 - 36; break;}
else if (codedCh > 62) codedCh = codedCh - 62;
else break;
}
return resCh;
}
/*************************************************************************************
NOME :getHide
stato :NON MODIFICATA (incluso commento)
Categoria :servizio
attivita' :esegue la formattazione per la spedizione via get (cambia i caratteri
speciali con i caratteri flag);
attualmente e' attiva solo la sostituzione del carattere 'spazio';
si prevede che diventi una funzione associata ad un comando.
chiamante :getValue
*************************************************************************************/
void getHide(char * stringa) {
unsigned int i;
for (i=0;i<(strlen(stringa));i++)
{
if (*(stringa+i)==' ') *(stringa+i)='+';
/* else if (*(stringa+i)=='&') *(stringa+i)='@';
else if (*(stringa+i)=='%') *(stringa+i)='^';
else if (*(stringa+i)=='=') *(stringa+i)='�';
*/
}
}
/*************************************************************************************
NOME :remBlindingChar
Categoria :servizio
attivita' :elimina i caratteri di delimitazione di stringa definiti nella define
BLINDER sostituendovi degli spazi; e' necessario alzare la guardia sullo
errore.
chiamante :execQuery, execInsQuery;
*************************************************************************************/
void remBlindingChar(char * queryString)
{
int found = 0;
char * holdQStr;
holdQStr = queryString;
while (*(queryString) != 0)
{
if (*queryString == BLINDER)
{
*queryString = ' ';
found = 1;
break;
}
queryString++;
}
while (*(++queryString)!=0);
while (queryString != holdQStr)
{
if (*queryString == BLINDER)
{
*queryString = ' ';
found = found + 10;
break;
}
queryString--;
}
if (found != 11)
{
fprintf(cgiOut, "%s<br>\n", ERR_REM_BLINDCH);
EXIT(-11);
}
}
/*************************************************************************************
NOME :pickPar
Categoria :servizio
attivita' :invocata dalle funzioni corrispondenti ai comandi per estrarre il parametro
alla 'position'; legge la inputStr, ALLOCA returnStr adeguatamente e vi
scrive il parametro richiesto
return :0 se parametro non trovato, 1 se trovato
*************************************************************************************/
int pickPar(char* inputStr, int position, char ** returnStr)
{
char *strCursor;
int parLen=0, parNum = 0;
int parsOffstArr[PARAM_NUMBER];
int i, searchPars = 1;
// nel caso che non vi sia nessun parametro
if ( inputStr == NULL )
return(PARAM_NOT_FOUND);
if ( strlen(inputStr) == 0 )
return(PARAM_NOT_FOUND);
position = position - 1;
for (i = 0; i < PARAM_NUMBER; i++) parsOffstArr[i] = 0;
// inizializzazione del cursore al primo carattere della stringa di input
strCursor = inputStr;
while (*strCursor)
{
if (*strCursor == BLINDER)
{
if(searchPars) searchPars = 0; else searchPars = 1;
}
if ( (searchPars) && (*strCursor == ',') )
{
parsOffstArr[++parNum] = strCursor - inputStr + 1;
}
strCursor++;
}
if (parNum > position)
{
parLen = parsOffstArr[position + 1] - parsOffstArr[position];
if (NULL==(*returnStr = (char *) malloc( (parLen) * sizeof(char) ))) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "- - *returnStr:%d - - len:%d\n", *returnStr, (parLen) * sizeof(char) );fflush(debug);}
//si copia il parametro sulla stringa di uscita
strncpy(*returnStr, inputStr + parsOffstArr[position], parLen -1);
(*returnStr)[parLen-1]=0;
}
else if (parNum == position)
{
parLen = strlen(inputStr) - parsOffstArr[position];
if (NULL==(*returnStr = (char *) malloc( (parLen + 1) * sizeof(char) ))) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "- - *returnStr:%d - - len:%d\n", *returnStr, (parLen + 1) * sizeof(char) );fflush(debug);}
strcpy(*returnStr, &inputStr[parsOffstArr[position]]);
}
else //parametro non trovato
{
if (NULL==(*returnStr = (char *) malloc( sizeof(char) ))) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "- - *returnStr:%d - - len:%d\n", *returnStr, sizeof(char) );fflush(debug);}
*returnStr[0]=0;
return(PARAM_NOT_FOUND);
}
//**/if(usedbg){fprintf(debug, "PICKPAR RETURNING\n");fflush(debug);}
//**/if(usedbg){fprintf(debug, "*returnStr: %s\n", *returnStr);fflush(debug);}
return(PARAM_FOUND);
}
/*************************************************************************************
NOME :writeWebUrl
Categoria :Gasp Command
attivita' :ritorna l'indirizzo di partenza del sito cosi' come specificato nel file di
inizializzazione (esempio "http://www.aitecsa.com")
*************************************************************************************/
void * writeWebUrl(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[HOME_DIR_LEN];
sprintf(buffer,"%s",WebUrl);
return buffer;
}
/*************************************************************************************
NOME :writeHomeDir
Categoria :Gasp Command
attivita' :ritorna la directory del sito relativa alla home page cosi' come specificato
nel file di inizializzazione (esempio "aspub")
*************************************************************************************/
void * writeHomeDir(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[HOME_DIR_LEN];
sprintf(buffer,"%s",WebHome);
return buffer;
}
/*************************************************************************************
NOME :writeImgDir
Categoria :Gasp Command
attivita' :ritorna la directory delle immagini relativa alla home page cosi' come
specificato nel file di inizializzazione (esempio "/img")
*************************************************************************************/
void * writeImgDir(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[IMG_DIR_LEN];
sprintf(buffer,"%s",ImgDir);
return buffer;
}
/*************************************************************************************
NOME :writeSSDir
Categoria :Gasp Command - *SSDIR()
attivita' :ritorna la directory degli style sheet relativa alla home page cosi' come
specificato nel file di inizializzazione (esempio "/style")
*************************************************************************************/
void * writeSSDir(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[SS_DIR_LEN];
sprintf(buffer,"%s",SSDir);
return buffer;
}
/*************************************************************************************
NOME :writeCgiPath
Categoria :Gasp Command
attivita' :ritorna l'url completo della applicazione cgi cosi' come specificato nel
file di inizializzazione
(es: "http://www.aitecsa.it/cgi-bin/tannit.exe")
*************************************************************************************/
void * writeCgiPath(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[IMG_DIR_LEN];
sprintf(buffer,"%s/%s/%s", WebUrl, CgiDir, CgiName);
return buffer;
}
/*************************************************************************************
NOME :writeCorrAppDir
Categoria :Gasp Command
attivita' :ritorna il parametro CrAppDir specificato nel file di inizializzazione
*************************************************************************************/
void * writeCorrAppDir(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[PAR_VALUE_LEN];
sprintf(buffer,"%s",CorrAppDir);
return buffer;
}
/*************************************************************************************
NOME :writeCorrFileName
Categoria :Gasp Command
attivita' :ritorna il parametro CrFileName specificato nel file di inizializzazione
*************************************************************************************/
void * writeCorrFileName(int vuoto1,char *vuoto2, char * vuoto3)
{
static char buffer[PAR_VALUE_LEN];
sprintf(buffer,"%s",CorrFileName);
return buffer;
}
/*************************************************************************************
NOME :execQuery
Categoria :Gasp Command: exeQ
attivita' :esegue una chiamata sql all'odbc di default specificato nel file di
inizializazione; gli eventuali risultati vengono messi in una struttura
rintracciabile per il nome della query
par 1 :nome della query (costituira' l'etichetta di identificazione dei risultati)
par 2 :query sql compresa tra doppi apici
par 3 opz :primo record del resultset da memorizzare nella struttura (opzionale,
valore di default = STARTING_ROW, tipicamente 1)
par 4 opz :numero di record del resultset da memorizzare nella struttura (opzionale,
valore di default = a ROWS_TO_STORE, tipicamente 512)
*************************************************************************************/
void * execQuery(int vuoto1,char *vuoto2, char * inputStr)
{
itxString refinedQString;
char *queryName, *queryString, *firstRecord, *recsToStore;
int firstRecInt = STARTING_ROW, recsToStoreInt = ROWS_TO_STORE;
/**/if(usedbg){fprintf(debug, "execQuery-inputStr:%s\n", inputStr);fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryString) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 3, &firstRecord) ) firstRecInt = atoi(firstRecord);
if( pickPar(inputStr, 4, &recsToStore) ) recsToStoreInt = atoi(recsToStore);
remBlindingChar(queryString);
refinedQString.Space(strlen(queryString));
refinedQString = queryString;
refinedQString.SubstituteSubString("\"\"", "\"");
/**/if(usedbg){fprintf(debug, "execQuery: sending query;%s\n", refinedQString.GetBuffer());fflush(debug);}
dbInterface(queryName, refinedQString.GetBuffer(), firstRecInt, recsToStoreInt);
/**/if(usedbg){fprintf(debug, "execQuery: dati archiviati;\n");fflush(debug);}
return 0;
}
/*************************************************************************************
NOME :execInsQuery
Categoria :Gasp Command: exeIQ
attivita' :simile ad execQuery aggiunge un recordset di nome 'C' + nome query che
contiene un record con un campo ("conta") che riporta il max(id) di un campo
della tabella in input
par 1 :nome della query (costituira' l'etichetta di identificazione dei risultati)
par 2 :query sql compresa tra doppi apici
par 3 :nome della tabella da investigare alla ricerca del valore massimo di un campo
par 4 opz :nome del campo da investigare (default = 'id')
note :la funzione viene intesa di utilita' quando in seguito ad una query (ad
esempio di inserimento) si vuole avere a disposizione un contatore per
monitorarne lo stato;
*************************************************************************************/
void * execInsQuery(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryString, *targetTable, *idField;
char tableId[ID_FIELD_LEN];
char countName[64];
char countQuery[256];
strcpy(tableId, "id");
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryString) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &targetTable) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 4, &idField ) ) strcpy(tableId, idField);
remBlindingChar(queryString);
dbInterface(queryName, queryString, 1, 1);
sprintf(countName, "C%s", queryName);
sprintf(countQuery, "SELECT max(%s) conta FROM %s", tableId, targetTable);
dbInterface(countName, countQuery, 1, 1);
return 0;
}
/*************************************************************************************
NOME :remQuery
Categoria :Gasp Command: remQ
attivita' :non operativa, in futuro deve rimuovere una query dalla lista dei resultset
o liberando la memoria o rinominando la query
par 1 :nome della query da fare fuori
*************************************************************************************/
void * remQuery(int vuoto1,char *vuoto2, char * inputStr)
{
int qIdx;
char *queryName;
//**/if(usedbg){fprintf(debug, "remQuery: Starting;\n");fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0);
strcpy( (QueryResultSet[qIdx]->id), "ertyu1234565" );
// ITannit_Create(QueryResultSet, &QueryCounter);
///**/if(usedbg){ITannit_Dump(debug);fflush(debug);}
//// ITannit_RemoveQueries(queryName, NULL);
// ITannit_Destroy();
///**/if(usedbg){fprintf(debug, "remQuery: 4;\n");fflush(debug);}
return 0;
}
/*************************************************************************************
NOME :writeTotalRecords
Categoria :Gasp Command: *totRecs(queryName)
attivita' :restituisce numero di record della query;
par 1 :nome del resultset da identificare
*************************************************************************************/
void * writeTotalRecords(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName;
static char retVal[GET_PAR_VAL_LEN];
int qIdx = 0;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
//**/if(usedbg){fprintf(debug, "writeTotalRecords ----------------------------- queryName: %s\n", queryName);fflush(debug);}
qIdx = queryIndex( queryName, 1 );
if ( qIdx == -1)
{
return("0");
}
//if(QQres !=NULL)/**/if(usedbg){fprintf(debug, "writeTotalRecords ----------------------------- totalRows: %d\n", QQres->totalRows);fflush(debug);}
//**/if(usedbg){fprintf(debug, "writeTotalRecords ----------------------------- qIdx: %d\n", qIdx);fflush(debug);}
listTQRnames();
sprintf(retVal, "%d",QueryResultSet[qIdx]->totalRows);
return retVal;
}
/*************************************************************************************
NOME :writeActualRec
Categoria :Gasp Command: *actRec(queryName)
attivita' :restituisce numero di record della query;
par 1 :nome del resultset da identificare
*************************************************************************************/
void * writeActualRec(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName;
static char retVal[GET_PAR_VAL_LEN];
int qIdx = 0;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0);
sprintf(retVal, "%d",QueryResultSet[qIdx]->actualRow);
return retVal;
}
/*************************************************************************************
NOME :writeMaxRecords
Categoria :Gasp Command: *maxRecs(queryName)
attivita' :restituisce numero di record della query;
par 1 :nome del resultset da identificare
*************************************************************************************/
void * writeMaxRecords(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName;
static char retVal[GET_PAR_VAL_LEN];
int qIdx = 0;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0);
sprintf(retVal, "%d",QueryResultSet[qIdx]->rowsToStore);
return retVal;
}
/*************************************************************************************
NOME :writeFirstRecord
Categoria :Gasp Command: *firstRec(queryName)
attivita' :restituisce il record di partenza che verra' memorizzato;
par 1 :nome del resultset da identificare
*************************************************************************************/
void * writeFirstRecord(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName;
static char retVal[GET_PAR_VAL_LEN];
int qIdx = 0;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0 );
sprintf(retVal, "%d",QueryResultSet[qIdx]->startingRow);
return retVal;
}
/*************************************************************************************
NOME :moreRecsMsg
Categoria :Gasp Command: *moreRecs(queryName, msg)
attivita' :se il resulset ha piu' record di quelli memorizzati visualizza il messaggio
par 1 :nome del resultset da identificare
par 2 :messaggio
*************************************************************************************/
void * moreRecsMsg(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *imfoMsg;
int qIdx;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &imfoMsg) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0 );
if ( QueryResultSet[qIdx]->rowsToStore + QueryResultSet[qIdx]->startingRow < QueryResultSet[qIdx]->totalRows )
{
return (imfoMsg);
}
return 0;
}
/*************************************************************************************
NOME :recVal
Categoria :Gasp Command: recVal
attivita' :restituisce il valore del campo specificato per il record corrente del
resultset specificato;
par 1 :nome del resultset da identificare
par 2 :nome del campo
par 3 opz :offset rispetto al record corrente (es: offset = -1 restituisce il record
precedente); default = 0
*************************************************************************************/
void * recVal(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryField, *recOffsetSt;
int recOffset=0, qIdx;
void * tempZ;
int errCode = 0;
//**/if(usedbg){fprintf(debug, "recVal-STARTING\n");fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryField) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 3, &recOffsetSt)) recOffset = atoi(recOffsetSt);
qIdx = queryIndex( queryName, 0 );
tempZ = (void*) storedData(QueryResultSet[qIdx]->actualRow + recOffset, queryField, queryName, &errCode);//record corrente, nome del campo, nome della query
return tempZ;
}
/*************************************************************************************
NOME :recValCnd
Categoria :Gasp Command: *recCnd(queryName, queryField, concatStr)
attivita' :restituisce il valore del campo specificato (per il record corrente e del
resultset specificato) solo se il dato e' diverso da null;
se e' presente la stringa opzionale questa viene aggiunta in testa al campo
(sempre solo se il campo non e' nullo)
par 1 :nome del resultset da identificare
par 2 :nome del campo
par 3 opz :stringa opzionale da concatenare
*************************************************************************************/
void * recValCnd(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryField, *concatStr, *onTailSt;
static char stringaVuota[1] = {'\0'};
int recOffset=0, qIdx;
char * retVal;
char * tempZ;
int errCode = 0, onTail = 0;
if(!pickPar(inputStr, 1, &queryName ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryField) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &concatStr ) ) concatStr = stringaVuota;
if( pickPar(inputStr, 4, &onTailSt ) ) onTail = atoi(onTailSt);
/**/if(usedbg){fprintf(debug, "FUNCTION recValCnd; query:%s; - field:%s; \n", queryName, queryField);fflush(debug);}
qIdx = queryIndex( queryName, 0 );
tempZ = storedData(QueryResultSet[qIdx]->actualRow + recOffset, queryField, queryName, &errCode);
if( tempZ == 0 )
{
retVal = (char*) malloc( 3 * sizeof(char) );if (!retVal) EXIT(MEMERR);
sprintf(retVal, " ");
return (retVal);
}
if( ( strcmp(tempZ, DATA_VALUE_ON_ERROR) == 0 ) || ( strcmp(tempZ, "") == 0 ) )
{
retVal = (char*) malloc( 3 * sizeof(char) );if (!retVal) EXIT(MEMERR);
sprintf(retVal, " ");
return (retVal);
}
retVal = (char*) malloc( (strlen(concatStr) + strlen(tempZ) + 2 )* sizeof(char) );if (!retVal) EXIT(MEMERR);
/**/if(alloctrc){fprintf(debug, "- - retVal:%d - - len:%d\n", retVal, (strlen(concatStr) + strlen(tempZ) + 2 )* sizeof(char) );fflush(debug);}
if(onTail == 0)
sprintf(retVal, "%s%s", concatStr, tempZ);
else if(onTail == 1)
sprintf(retVal, "%s%s", tempZ, concatStr);
else
sprintf(retVal, "%s%s", concatStr, tempZ);
return (void*) retVal;
}
/*************************************************************************************
NOME :recValConf
Categoria :Gasp Command: recSEL
attivita' :analogo a recVal restituisce il valore del campo specificato per il record
corrente del resultset specificato; aggiunge la stringa " SELECTED" se il
dato e' uguale al dato determinato dalla seconda coppia di parametri
par 1 :nome del resultset da identificare
par 2 :nome del campo
par 3 :nome del resultset da identificare per il confronto; se il nome e' "get"
il dato di confronto viene cercato nella stringa di get
par 4 :nome del campo da utilizzare per il confronto
*************************************************************************************/
void * recValConf(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryField, *cnfField, *cnfSrc;
int qIdx, qIdx2;
char *firstVal, *secVal, *retVal;
int errCode = 0;
//**/if(usedbg){fprintf(debug, "recValConf-STARTED;\n");fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryField) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &cnfSrc) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 4, &cnfField) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0 );
firstVal = storedData(QueryResultSet[qIdx]->actualRow, queryField, queryName, &errCode);
if(!firstVal)
return " ";
if (strcmp(cnfSrc,"get")==0)
{
secVal = (char*) malloc( GET_PAR_VAL_LEN * sizeof(char) );
if (!secVal)
EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - secVal:%d - - len:%d\n", secVal, GET_PAR_VAL_LEN * sizeof(char) );fflush(debug);}
if (cgiFormString( cnfField, secVal, 0) != cgiFormSuccess)
sprintf(secVal, "%s", GET_PAR_VAL); /*valore di default generico*/
//**/if(usedbg){fprintf(debug, "recValConf-secVal: %s;\n", secVal);fflush(debug);}
}
else
{
qIdx2 = queryIndex( cnfSrc, 0 );
secVal = storedData(QueryResultSet[qIdx2]->actualRow, cnfField, cnfSrc, &errCode);//record corrente, nome del campo, nome della query
}
if(!secVal)
return " ";
if (!strcmp(firstVal, secVal))
{
retVal = (char*) malloc( ( strlen(firstVal) + SELECTED_ADD_ON ) * sizeof(char) );
if (!retVal)
EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - retVal:%d - - len:%d\n", retVal, ( strlen(firstVal) + SELECTED_ADD_ON ) * sizeof(char) );fflush(debug);}
sprintf(retVal, "%s SELECTED", firstVal);
}
else
{
retVal = (char*) malloc( ( strlen(firstVal) + 1) * sizeof(char) );
if (!retVal)
EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - retVal:%d - - len:%d\n", retVal, ( strlen(firstVal) + 1 ) * sizeof(char) );fflush(debug);}
strcpy(retVal, firstVal);
}
//**/if(usedbg){fprintf(debug, "recValConf-RETURNING;\n");fflush(debug);}
return retVal;
}
/*************************************************************************************
NOME :recValLookAsStr
Categoria :Gasp Command: *recLookS(TQR, TQR_field, table_2, t2_id, dscr_field)
attivita' :seleziona da TQR il valore del record corrente per il campo TQR_field
quindi esegue una query sulla table_2 con condizione t2_id = TQR_field
ed estrae dscr_field
NOTE: TQR_field e' supposto una STRINGA
*************************************************************************************/
void * recValLookAsStr(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryField, *tableName, *tableField, *dscrField;
int qIdx, qIdx2;
char *tqrVal, *retVal;
char secondQuery[1024];
int errCode = 0;
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryField) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &tableName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 4, &tableField) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 5, &dscrField) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex( queryName, 0 );
tqrVal = storedData(QueryResultSet[qIdx]->actualRow, queryField, queryName, &errCode);
if(!tqrVal) return "";
sprintf(secondQuery, "SELECT %s FROM %s WHERE %s = '%s'", dscrField, tableName, tableField, tqrVal);
newAutoName();
dbInterface(QueryLabel, secondQuery, 1, 1);
qIdx2 = queryIndex( QueryLabel, 0 );
retVal = storedData(QueryResultSet[qIdx2]->actualRow, dscrField, QueryLabel, &errCode);
if(!retVal) return " ";
return retVal;
}
/*************************************************************************************
NOME :cycleQuery
Categoria :Gasp Command: *cycleQ(TQRName, OPZonEmptyListMessage, OPZonEmptyListFile)
attivita' :definisce il punto di partenza di un ciclo che viene effettuato sui record
del TQR specificato. Il comando di fine ciclo, necessario pena un
comportamento imprevedibile del template, � *endCQ(TQRName).
TQRName : nome del tqr;
OPZonEmptyListMessage: opzionale, stringa da ritornare in caso di nessun
record trovato;
OPZonEmptyListFile : file da includere in caso di nessun record trovato;
*************************************************************************************/
void * cycleQuery (int vuoto1, char* vuoto2, char* inputStr)
{
char *queryName, *onEmptyMsg, *onEmptyFileName, *tplStr, *outputStr;
int qIdx;
/**/if(usedbg){fprintf(debug, "cycleQuery - STARTING\n" );fflush(debug);}
if ( ReadCycle[CycLevel-1] == 0)
{
ReadCycle[CycLevel] = 0;
/**/if(usedbg){fprintf(debug, "cycleQuery - abortING\n" );fflush(debug);}
return (0);
}
if(!pickPar(inputStr, 1, &queryName ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &onEmptyMsg ) ) onEmptyMsg = 0;
if(!pickPar(inputStr, 3, &onEmptyFileName ) ) onEmptyFileName = 0;
qIdx = queryIndex(queryName, 0);
if ( QueryResultSet[qIdx]->totalRows == 0 )
{
ReadCycle[CycLevel] = 0;
if (onEmptyFileName)
{
bufferTpl(&tplStr, onEmptyFileName, TplDir);
procTplData(tplStr, cgiOut, &outputStr);
if (tplStr)
{
/**/if(alloctrc){fprintf(debug, "* * tplStr:%d\n", tplStr);fflush(debug);}
free(tplStr);
}
//fflush(cgiOut);
EXIT(1);
}
else if (onEmptyMsg)
{
fprintf(cgiOut, "%s\n", onEmptyMsg);//fflush(cgiOut);
}
}
else if (
( QueryResultSet[qIdx]->actualRow < (QueryResultSet[qIdx]->rowsToStore + 1) ) &&
( (QueryResultSet[qIdx]->actualRow + QueryResultSet[qIdx]->startingRow) < (QueryResultSet[qIdx]->totalRows + 2) )
)
{
/**/if(usedbg){fprintf(debug, "cycleQuery - actualRow - %d\n", QueryResultSet[qIdx]->actualRow );fflush(debug);}
/**/if(usedbg){fprintf(debug, "cycleQuery - rowsToStore- %d\n", QueryResultSet[qIdx]->rowsToStore);fflush(debug);}
/**/if(usedbg){fprintf(debug, "cycleQuery - startingRow- %d\n", QueryResultSet[qIdx]->startingRow);fflush(debug);}
/**/if(usedbg){fprintf(debug, "cycleQuery - totalRows- %d\n", QueryResultSet[qIdx]->totalRows);fflush(debug);}
ReadCycle[CycLevel] = 1;
}
else
{
ReadCycle[CycLevel] = 0;
}
/**/if(usedbg){fprintf(debug, "cycleQuery - endING\n" );fflush(debug);}
return (0);
}
void * endCycleQuery (int vuoto1, char* vuoto2, char* inputStr)
{
char *queryName;
int qIdx;
/**/if(usedbg){fprintf(debug, "endCycleQuery - STARTING\n" );fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex(queryName, 0);
QueryResultSet[qIdx]->actualRow++;
/**/if(usedbg){fprintf(debug, "endCycleQuery - endING\n" );fflush(debug);}
return 0;
}
/*************************************************************************************
NOME :setActualRow
Categoria :Gasp Command: *setRec(queryName,recNum)
attivita' :imposta il record corrente della query;
par 1 :nome del resultset da identificare
par 2 :(opz, se omesso si sottointende il primo record)
valore del record numerico,
oppure stringa "last" per forzare all'ultimo record,
oppure stringa ++ per incrementare il record attuale;
note :se si eccede il massimo numero accettabile per il TQR, il record viene
imostato all'ultimo record; viceversa se si va sotto a STARTING_ROW si
forza a STARTING_ROW.
*************************************************************************************/
void * setActualRow(int vuoto1, char* vuoto2, char* inputStr)
{
char *queryName, *recordNumbSt;
int qIdx, recordNumber = STARTING_ROW;
int lastRow;
if(!pickPar(inputStr, 1, &queryName ) ) return(PARAM_NOT_FOUND_MSG);
qIdx = queryIndex(queryName, 0);
lastRow = QueryResultSet[qIdx]->rowsToStore;
if( pickPar(inputStr, 2, &recordNumbSt ) )
{
if ( strcmp(recordNumbSt, "last") == 0 )
recordNumber = lastRow;
else if(strcmp(recordNumbSt, "++") == 0)
recordNumber = QueryResultSet[qIdx]->actualRow + 1;
else
recordNumber = atoi(recordNumbSt);
}
if (recordNumber > lastRow)
recordNumber = lastRow;
else if (recordNumber < STARTING_ROW)
recordNumber = STARTING_ROW;
QueryResultSet[qIdx]->actualRow = recordNumber;
return (0);
}
/*************************************************************************************
NOME :startCndBlk
Categoria :Gasp Command: *if(condizione)/*ifblk(condizione)
attivita' :inizio del blocco condizionato; necessita di un comando *endif()/*endblk()
per la terminazione del blocco:
la condizione utilizza gli operatori
== uguale
!= diverso
< minore
> maggiore
<= minore-uguale
=> uguale-maggiore
per il confronto tra i due termini.
Nel caso entrambi i termini del confronto siano convertibili a numeri
interi il confronto avviene tra interi. altrimenti tra stringhe.
Se la condizione � una stringa nulla l'if non ha successo.
Se la condizione non contiene nessun opetratore e la stringa non � nulla
l'if ha successo.
Se il confronto ha successo il blocco viene elaborato dal parser ed i
comandi al suo interno non vengono eseguiti.
*************************************************************************************/
void * startCndBlk (int vuoto1, char* vuoto2, char* inputStr)
{
char *operators[] = {"==","!=","<","<=","=>",">"};
char *opPosition[CND_OP_NUM];
const int opNum = CND_OP_NUM;
int i, opOrd, lOpLen, rOpLen, result;
char *leftOp, *rightOp;
//**/if(usedbg){fprintf(debug, "START CND\n");fflush(debug);}
//**/if(usedbg){fprintf(debug, "inputStr:%s\n", inputStr);fflush(debug);}
// si ereditano le colpe dei padri
// if (ValidBlock[CndLevel-1] == 0)
// {
// ValidBlock[CndLevel] = 0;
// return 0;
// }
opOrd = -1;
for (i = 0; i < opNum; i++)
{
opPosition[i] = strstr(inputStr, operators[i]);
if (opPosition[i])
{
opOrd = i;
break;
}
}
if (opOrd == -1)
{
// se non vi � operatore il blocco si considera TRUE se vi e' una qualsiasi stringa
if(strlen(inputStr) > 0)
ValidBlock[CndLevel] = 1;
else
ValidBlock[CndLevel] = 0;
return 0;
}
lOpLen = opPosition[opOrd] - inputStr;
leftOp = (char*) malloc((lOpLen + 1) * sizeof(char));if (!leftOp) EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - leftOp:%d - - len:%d\n", leftOp, (lOpLen + 1) * sizeof(char) );fflush(debug);}
strncpy(leftOp, inputStr, lOpLen);
leftOp[lOpLen] = 0;
rOpLen = strlen(inputStr) - strlen(operators[opOrd]) - lOpLen;
rightOp = (char*) malloc((rOpLen + 1)* sizeof(char));if (!rightOp) EXIT(23);
/**/if(alloctrc){fprintf(debug, "- - rightOp:%d - - len:%d\n", rightOp, (rOpLen + 1) * sizeof(char) );fflush(debug);}
strcpy( rightOp, &inputStr[ lOpLen + strlen(operators[opOrd]) ] );
rightOp[rOpLen]=0;
//trimIt(leftOp);
//trimIt(rightOp);
result = strcmp(leftOp,rightOp);
// nel caso di operatori convertibili ad interi vendono confrontati i valori interi
if ( atoi(leftOp) && atoi(rightOp) ) result= atoi(leftOp) - atoi(rightOp);
switch (opOrd) {
case 0:
if (result) ValidBlock[CndLevel] = 0; else ValidBlock[CndLevel] = 1; break;
case 1:
if (result) ValidBlock[CndLevel] = 1; else ValidBlock[CndLevel] = 0; break;
case 2:
if (result<0) ValidBlock[CndLevel] = 1; else ValidBlock[CndLevel] = 0; break;
case 3:
if (result<=0) ValidBlock[CndLevel] = 1; else ValidBlock[CndLevel] = 0; break;
case 4:
if (result>=0) ValidBlock[CndLevel] = 1; else ValidBlock[CndLevel] = 0; break;
case 5:
if (result>0) ValidBlock[CndLevel] = 1; else ValidBlock[CndLevel] = 0; break;
}
//**/if(usedbg){fprintf(debug, "END CND\n");fflush(debug);}
return 0;
}
/*************************************************************************************
NOME :elseCndBlk
Categoria :Gasp Command: *else(condizione)/*elseblk(condizione)
attivita' :else del blocco condizionato
*************************************************************************************/
void * elseCndBlk (int vuoto1, char* vuoto2, char* inputStr)
{
// si ereditano le colpe dei padri
// if (ValidBlock[CndLevel-1] == 0)
// {
// ValidBlock[CndLevel] = 0;
// return 0;
// }
return 0;
}
/*************************************************************************************
NOME :endCndBlk
Categoria :Gasp Command: *endif(condizione)/*endblk(condizione)
attivita' :fine del blocco condizionato.
*************************************************************************************/
void * endCndBlk (int vuoto1, char* vuoto2, char* inputStr)
{
//**/if(usedbg){fprintf(debug, "ENDIF\n");fflush(debug);}
return 0;
}
/*************************************************************************************
NOME :getValue
Categoria :Gasp Command: *get(parametro,OPZdefault)
attivita' :restituisce il valore del parametro di get indicato
- parametro: nome del paremetro di get di cui restituire il valore
- OPZdefault: valore di default ritornato nel caso non si trovi il
parametro.
N.B. se OPZdefault � il carattere '+' il valore
ricavato per il parametro viene modificato sostituendo tutti
i caratteri non alfanumerici con la stringa %xx dove xx �
il valore ascii esadecimale del carattere sostituito.
*************************************************************************************/
void * getValue(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
char *defParVal, *getParName;
int useDefault = 0;
itxString istr;
if(!pickPar(inputStr, 1, &getParName) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 2, &defParVal)) useDefault = 1;
//**/if(usedbg){fprintf(debug, "getParName:%s\n",getParName);fflush(debug);}
if (cgiFormString( getParName, returnValue, 0) != cgiFormSuccess)
{
if (useDefault)
{
// valore opzionale di default definito dall'utente
strcpy(returnValue,defParVal);
}
else
{
// valore di default generico
sprintf(returnValue, "%s", GET_PAR_VAL);
}
}
if (strcmp(defParVal,"+")==0)
{
char * modRetVal;
if(strcmp(returnValue,"+")==0)
returnValue[0] = '\0';
istr.EscapeChars(returnValue, &modRetVal);
return((void *)modRetVal);
}
return((void *)returnValue);
}
/*************************************************************************************
NOME :getmad
Categoria :Gasp Command: *getmad(parametro,OPZdefault)
attivita' :come la getValue ma raddopia gli apici se presenti ed il valore opzionale +
si limita ad indicare che si devono sostituire gli spazi con caratteri +
*************************************************************************************/
void * getmad(int vuoto1, char *vuoto2, char * inputStr)
{
itxString buffer;
char *retVal;
int retValLen=0;
char *defParVal, *getParName;
int useDefault = 0;
/**/if(usedbg){fprintf(debug, "getmad START with:%s\n", inputStr);fflush(debug);}
if(!pickPar(inputStr, 1, &getParName) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 2, &defParVal)) useDefault = 1;
if (cgiFormStringSpaceNeeded( getParName, &retValLen) != cgiFormSuccess)
retValLen = 0;
buffer.Space(retValLen+1);
if (cgiFormString( getParName, buffer.GetBuffer(), 0) != cgiFormSuccess)
{
if (useDefault)
buffer = defParVal;
else
buffer = GET_PAR_VAL;
if (strcmp(defParVal,"+")==0)
getHide(buffer.GetBuffer());
}
buffer.AdjustStr();
buffer.SubstituteSubString("\"", "\"\"");
retVal = (char*) calloc(buffer.Len() + 1, sizeof(char));
strcpy(retVal, buffer.GetBuffer());
return((void *)retVal);
}
void * quotestr(int vuoto1, char *vuoto2, char * inputStr)
{
itxString buffer;
char* pstring;
static char string[256];
memset(string, '\0', 256);
/**/if(usedbg){fprintf(debug, "quotestr START with:%s\n", inputStr);fflush(debug);}
if(!pickPar(inputStr, 1, &pstring)) return(PARAM_NOT_FOUND_MSG);
buffer = pstring;
buffer.SubstituteSubString("'", "\\'");
strcpy(string, buffer.GetBuffer());
return ((void*)string);
}
/*************************************************************************************
NOME :putGetHide
Categoria :Gasp Command: *gethide(parametro)
attivita' :nasconde i caratteri non alfanumerici del parametro trasformandoli in %xx
dove xx � il valore ascii esadecimale del carattere sostituito.
*************************************************************************************/
void * putGetHide(int vuoto1, char *vuoto2, char * inputStr)
{
char *string = NULL;
char *retVal = NULL;
itxString istr;
if(!pickPar(inputStr, 1, &string) ) return "";
//getHide(string);
istr.EscapeChars(string,&retVal);
return retVal;
}
/*************************************************************************************
NOME :encrIt
Categoria :servizio
attivita' :Criptaggio distruttivo di sicurezza molto blando accoppiato alla vecrIt.
Usato dalla Authorize.
*************************************************************************************/
void * encrIt(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
char *seedStr;
struct _timeb timebuffer;
char appo[4];
char milsec[4];
int crs, i;
int keyIdx = 0;
if(!pickPar(inputStr, 1, &seedStr) ) return(PARAM_NOT_FOUND_MSG);
_ftime( &timebuffer );
sprintf( milsec, "%d", timebuffer.millitm );
if (strlen(milsec) == 1) sprintf( appo, "00%s", milsec );
else if (strlen(milsec) == 2) sprintf( appo, "0%s", milsec );
else sprintf( appo, "%s", milsec );
for(i=0;seedStr[i];i++)
{
if (crs = isAlphaNum(seedStr[i]))
{
keyIdx = i % 3;
seedStr[i] = crs + appo[keyIdx];
if (seedStr[i] = reAlphaNum(seedStr[i])); else EXIT(__LINE__);
}
else EXIT(__LINE__);
}
sprintf( returnValue, "%s%s", appo, seedStr);
return((void *)returnValue);
}
/*************************************************************************************
NOME :encrIt
Categoria :servizio
attivita' :verifica del crittaggio usato dalla encrIt. Usato dalla Authorize
*************************************************************************************/
int vecrIt(char *encrStr, char * candidate)
{
static char returnValue[GET_PAR_VAL_LEN];
int crs, i;
int keyIdx = 0;
if (candidate)
{
for(i=0;candidate[i];i++)
{
if (crs = isAlphaNum(candidate[i]))
{
keyIdx = i % 3;
candidate[i] = crs + encrStr[keyIdx];
if (candidate[i] = reAlphaNum(candidate[i])); else return 0;
}
else return 0;
}
if (strcmp(candidate, &(encrStr[3]) ) == 0) return 1;
else return 0;
}
else return 0;
}
/*************************************************************************************
NOME :authorize
Categoria :Gasp Command: *auth(login,cpwd,OPZextraField,OPZextraVal) - Uso Deprecato
attivita' :autorizzazione utenti, fa uso della tabella del database specificata nel
file dei parametri al valore LoginTable.
- login : identificatore dell'utente candidato alla autenticazione;
viene usato per selezionare il record uguagliandolo al campo
specificato nel file di inizializzazione nel parametro LoginField
- pwd : password dell utente c<PASSWORD> alla autenticazione;
viene usata per convalidare il record selezionato dal campo login
uguagliandola al valore del campo specificato nel file di
inizializzazione nel parametro PwdField
- OPZextraField: campo addizionale della tabella;
- OPZextraVal :valore del campo addizionale da verificare se specificato
Note :usa le encrIt e vecrIt -> PROTEZIONE BLANDA.
*************************************************************************************/
void * authorize(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
static char queryString[GET_PAR_VAL_LEN];
char *encrStr, *candidate, *loginSt;
char *extraField, *extraVal;
char * errStr, *outputStr;
int errCode = 0;
char defExtra[]={'1',0};
if(!pickPar(inputStr, 1, &loginSt ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &encrStr ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &extraField) ) extraField = defExtra;
if(!pickPar(inputStr, 4, &extraVal ) ) extraVal = defExtra;
sprintf(queryString, "select %s from %s where %s = '%s' AND %s=%s ",
PwdField, LoginTable, LoginField, loginSt, extraField, extraVal);
dbInterface("qtst", queryString, 1, 1);
candidate = storedData(1, PwdField, "qtst", &errCode);
// Se si verifica un errore di sintassi si manda su schermo un messaggio di informazione
if ( errCode == ERR_COL_NOT_FOUND || errCode == ERR_QUERY_NOT_FOUND|| errCode == ERR_VOID_QUERY_NAME )
{
fprintf(cgiOut, "%s\n", candidate);//fflush(cgiOut);
}
if ( vecrIt(encrStr, candidate) != 0)
{
sprintf( returnValue, "OK");
}
else
{
if( bufferTpl(&errStr, INVALID_LOGIN_FILE, TplDir) != 0)
{
procTplData(errStr, cgiOut, &outputStr);
if (errStr)
{
/**/if(alloctrc){fprintf(debug, "* * errStr:%d\n", errStr);fflush(debug);}
free(errStr);
}
}
else
{
fprintf(cgiOut, "%s\n", retMsg(LOGIN_ERROR));
}
//fflush(cgiOut);
EXIT(1);
}
return (0);
}
/*************************************************************************************
NOME :validate
Categoria :Gasp Command: *valid(login,cpwd,OPZextraField,OPZextraVal)
attivita' :autorizzazione utenti, fa uso della tabella del database specificata nel
file dei parametri al valore LoginTable.
- login : identificatore dell'utente candidato alla autenticazione;
viene usato per selezionare il record uguagliandolo al campo
specificato nel file di inizializzazione nel parametro LoginField
- pwd : <PASSWORD> alla autenticazione;
viene usata per convalidare il record selezionato dal campo login
uguagliandola al valore del campo specificato nel file di
inizializzazione nel parametro PwdField
- OPZextraField: campo addizionale della tabella;
- OPZextraVal :valore del campo addizionale da verificare se specificato
Note :funzioni di criptaggio per una -> PROTEZIONE FORTE.
*************************************************************************************/
void * validate(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
static char queryString[GET_PAR_VAL_LEN];
char *passwd, *loginSt;
char *extraField, *extraVal;
char * errStr, *outputStr;
int errCode = 0;
char defExtra[]={'1',0};
int validated =1;
if(!pickPar(inputStr, 1, &loginSt ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &passwd ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &extraField) ) extraField = defExtra;
if(!pickPar(inputStr, 4, &extraVal ) ) extraVal = defExtra;
//
// Controllo che la password nel DB sia la stessa di input
//
validated = checkDbPwd(loginSt, passwd, extraField, extraVal );
/**/if(usedbg){fprintf(debug, "----------VALIDATED? - %d\n",retMsg(validated));fflush(debug);}
if ( validated == ERR_COL_NOT_FOUND ||
validated == ERR_QUERY_NOT_FOUND ||
validated == ERR_VOID_QUERY_NAME )
{
fprintf(cgiOut, "%s\n", retMsg(validated));//fflush(cgiOut);
}
if ( validated == NOT_VALIDATED)
{
//apre il template, alloca tplString, e vi copia i dati
if( bufferTpl(&errStr, INVALID_LOGIN_FILE, TplDir) != 0)
{
//interpretazione dei dati e scrittura su outputStream
procTplData(errStr, cgiOut, &outputStr);
if (errStr)
{
/**/if(alloctrc){fprintf(debug, "* * errStr:%d\n", errStr);fflush(debug);}
free(errStr);
}
}
else
{
fprintf(cgiOut, "%s\n", retMsg(LOGIN_ERROR));
}
//fflush(cgiOut);
exit(1);
}
return (0);
}
/*************************************************************************************
NOME :validAleph
Categoria :ALEPH servizio
attivita' :autorizzazione utenti per il client Aleph a partire dai dati loginSt e
passwd e dalle variabili globali del file di inizializzazione che
specificano tabella, campo di login e campo di pwd.
Note :Usa funzioni di criptaggio per una -> PROTEZIONE FORTE.
*************************************************************************************/
void * validAleph(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
static char queryString[GET_PAR_VAL_LEN];
char *passwd, *loginSt;
int errCode = 0;
int validated =1;
if(!pickPar(inputStr, 1, &loginSt ) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &passwd ) ) return(PARAM_NOT_FOUND_MSG);
/**/if(usedbg){fprintf(debug, "sto entrando nella validateAleph\n");fflush(debug);}
//
// Controllo che la password nel DB sia la stessa di input
//
validated = checkDbPwd(loginSt, passwd, "1", "1" );
if ( validated == ERR_COL_NOT_FOUND ||
validated == ERR_QUERY_NOT_FOUND ||
validated == ERR_VOID_QUERY_NAME )
{
fprintf(cgiOut, "%s:0;\n", ALEPH_START_COM);
fprintf(cgiOut, "%s:%d;\r\n", ALEPH_END_COM, FATAL_ERROR);
EXIT(0);
}
if ( validated == NOT_VALIDATED)
{
fprintf(cgiOut, "%s:0;\n", ALEPH_START_COM);
fprintf(cgiOut, "%s:%d;\r\n", ALEPH_END_COM, LOGIN_ERROR);
EXIT(0);
}
sprintf(returnValue, "%s:0;%s:%d;", ALEPH_START_COM, ALEPH_END_COM, LOGIN_SUCCESS);
/**/if(usedbg){fprintf(debug, "validateAleph return value = %s\n", returnValue);fflush(debug);}
return (returnValue);
}
/*************************************************************************************
NOME :exitOnFile
Categoria :Gasp Command: *exof(OPZexitType,OPZexitMessage,OPZexitFile)
attivita' :interrompe il processing del template ed esce dopo aver, a seconda del
parametro exitType, mostrato un messaggio o effettuato il parsing di un file;
- exitType :pu� assumere i seguenti valori validi m (message) f (file)
b (both)
- exitMessage :messaggio da visualizzare prima di uscire
- exitFile :file da processare prima di uscire
*************************************************************************************/
void * exitOnFile(int vuoto1, char *vuoto2, char * inputStr)
{
char *exType, *exMsg, *addFile;
char * tplStr, *outputStr;
if(!pickPar(inputStr, 1, &exType ) ) exType = 0;
if(!pickPar(inputStr, 2, &exMsg ) ) exMsg = 0;
if(!pickPar(inputStr, 3, &addFile ) ) addFile = 0;
if (exType)
{
// scrive il messaggio (par 2) prima di uscire
if (*exType=='m')
{
if (exMsg)
{
fprintf(cgiOut, "%s\n", exMsg);//fflush(cgiOut);
}
EXIT(1);
}
// fa il pars del file (par 3) prima di uscire
else if (*exType=='f')
{
if (exMsg)
{
if (strlen(exMsg))
{
bufferTpl(&tplStr, exMsg, TplDir);
procTplData(tplStr, cgiOut, &outputStr);
// fflush(cgiOut);
}
}
EXIT(1);
}
// scrive il messaggio (par 2) prima di uscire e
// fa il pars del file (par 3) prima di uscire
else if (*exType=='b')
{
if (exMsg && addFile)
{
fprintf(cgiOut, "%s\n", exMsg);//fflush(cgiOut);
if (strlen(addFile))
{
bufferTpl(&tplStr, addFile, TplDir);
procTplData(tplStr, cgiOut, &outputStr);
// fflush(cgiOut);
}
}
EXIT(1);
}
}
return (0);
}
/*************************************************************************************
NOME :syntChk
Categoria :Gasp Command: *chkIt(stringToTest,flag,............
DA DOCUMENTARE
DA DOCUMENTARE
DA DOCUMENTARE
DA DOCUMENTARE
*************************************************************************************/
void * syntChk(int vuoto1, char *vuoto2, char * inputStr)
{
static char returnValue[GET_PAR_VAL_LEN];
char *strToTest, *typeFlag, *minLenS, *maxLenS;
int i, minLen, maxLen, numStr;
if( !pickPar( inputStr, 1, &strToTest ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &typeFlag ) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar( inputStr, 3, &minLenS ) ) minLen = atoi(minLenS);
if( pickPar( inputStr, 4, &maxLenS ) ) maxLen = atoi(maxLenS);
numStr = (int)strlen( strToTest );
if ( !strcmp(typeFlag, "a") )
{
for ( i = 0; strToTest[i]; i++)
{
if ( !isAlphaNum( strToTest[i] ) ) return ("FALSE");
}
}
else if ( !strcmp(typeFlag, "n") )
{
numStr = atoi( strToTest );
}
if ( ( numStr < minLen ) || ( numStr > maxLen ) ) return ("FALSE");
return ("TRUE");
}
/*************************************************************************************
NOME :setVar
Categoria :Gasp Command: *setVar(varName,varValue)
attivita' :assegna alla variabile varName il valore varValue.
*************************************************************************************/
void * setVar(int vuoto1, char *vuoto2, char * inputStr)
{
char *varName, *varValue;
int i;
if( !pickPar( inputStr, 1, &varName ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &varValue) ) return(PARAM_NOT_FOUND_MSG);
for ( i = 0; i < TplVars.idx; i++)
{
if ( ( TplVars.names[i] != 0 ) && ( varName != 0 ) )
{
if ( strcmp(TplVars.names[i] , varName ) == 0 )
break;
}
}
if (i == TplVars.idx)
{
if ( ( TplVars.idx < TPL_VARS_NUM ) && (varValue != 0) )
{
TplVars.names[TplVars.idx] = varName ;
TplVars.values[TplVars.idx] = varValue ;
TplVars.idx++;
}
else
return(UNABLE_TO_WRITE_VAR);
}
else
TplVars.values[i] = varValue ;
return (0);
}
/*************************************************************************************
NOME :getVar
Categoria :Gasp Command: *getVar(varName)
attivita' :restituisce il valore della variabile varName.
*************************************************************************************/
void * getVar(int vuoto1, char *vuoto2, char * inputStr)
{
char *varName, *varDefValue;
int i;
if( !pickPar( inputStr, 1, &varName ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &varDefValue ) ) varDefValue = 0;
for ( i = 0; i < TplVars.idx; i++)
{
//**/if(usedbg){fprintf(debug, "i:%d\t\t%s\n", i, TplVars.names[i]);fflush(debug);}
//**/if(usedbg){fprintf(debug, "name\t\t%s\n", varName);fflush(debug);}
if ( ( TplVars.names[i] != 0 ) && ( varName != 0 ) )
{
if ( strcmp(TplVars.names[i] , varName ) == 0 ) return (TplVars.values[i]);
}
}
if ( varDefValue != 0 ) return(varDefValue);
else return("");
}
/*************************************************************************************
NOME :extrIdG
Categoria :Gasp Command: *getId(getVarName,OPZtableIdField,OPZtableName)
attivita' :restituisce il valore del campo indice il cui valore � la variabile di get
getVarName.
getVarName -nome della variabile di get di cui trovare l'indice
OPZtableIdField -nome, opzionale, del campo di esplorazione il default �
ExtrField
OPZtableName -nome, opzionale, della tabella di lavoro il default �
ExtrTable
*************************************************************************************/
void * extrIdG(int vuoto1, char *vuoto2, char * inputStr)
{
char *tableName, *tableField, *idValue, *fieldValSource;
char fieldValue[EXTRID_FIELD_LEN];
char queryString[GET_PAR_VAL_LEN];
int errCode;
if( !pickPar( inputStr, 1, &fieldValSource ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &tableField ) ) tableField = ExtrField;
if( !pickPar( inputStr, 3, &tableName ) ) tableName = ExtrTable;
//**/fprintf(cgiOut, "<br>flagGet:%d<br>\n", flagGet);fflush(cgiOut);
if ( cgiFormString( fieldValSource, fieldValue, 0) != cgiFormSuccess )
{
return (FIELD_NAME_NOT_FOUND);
}
sprintf(queryString, "select %s from %s where %s = '%s'"
, IdField, tableName, tableField, fieldValue);
//**/fprintf(cgiOut, "<br>queryString:%s<br>\n", queryString);fflush(cgiOut);
dbInterface("idExtr", queryString, 1, 1);
idValue = storedData(1, IdField, "idExtr", &errCode);
return (idValue);
}
/*************************************************************************************
NOME :extrId
Categoria :Gasp Command: *extId(fieldVal,OPZtableIdField,OPZtableName)
attivita' :restituisce il valore del campo indice il cui valore fieldVal.
fieldVal -valore di cui trovare l'indice
OPZtableIdField -nome, opzionale, del campo di esplorazione il default �
ExtrField
OPZtableName -nome, opzionale, della tabella di lavoro il default �
ExtrTable
*************************************************************************************/
void * extrId(int vuoto1, char *vuoto2, char * inputStr)
{
char *tableName, *tableField, *idValue, *fieldValSource;
char *fieldValue;
char queryString[GET_PAR_VAL_LEN];
int errCode;
if( !pickPar( inputStr, 1, &fieldValSource ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &tableField ) ) tableField = ExtrField;
if( !pickPar( inputStr, 3, &tableName ) ) tableName = ExtrTable;
fieldValue = fieldValSource;
sprintf(queryString, "select %s from %s where %s = '%s'", IdField, tableName, tableField, fieldValue);
//**/fprintf(cgiOut, "<br>queryString:%s<br>\n", queryString);fflush(cgiOut);
dbInterface("idExtr", queryString, 1, 1);
idValue = storedData(1, IdField, "idExtr", &errCode);
return (idValue);
}
/*************************************************************************************
NOME :translateIt
Categoria :Gasp Command: *trans(phraseTag,OPZforceLang)
attivita' :traduce la phraseTag nella lingua corrente. Fa uso dei parametri
LangTable, LangNameField, LangCodeField del file di inizializzazione per
definire tabella dei linguaggi, campo del nome della lingua, campo del
codice della lingua. Ricava il valore del campo LangNameField per il record
in cui il campo LangCodeField corrisponde al valore del parametro di get
identificato dal valore del parametro LangTagGet del file di inizializzazione.
Il nome del campo della lingua � quello da estrarre dalla tabella delle
traduzioni (definita dal parametro TransTable nell'file di inizializzazione)
in corrispondenza del valore del campo TransTagField (sempre nel file dei
parametri) che uguaglia la stringa di input del comando phraseTag.
OPZforceLang, � un parametro che forza la lingua al valore specificato.
*************************************************************************************/
void * translateIt(int vuoto1, char *vuoto2, char * inputStr)
{
char *translatedPhrase, *phraseTag, *langName, *forceLang;
char getLangCode[LANG_ID_LEN];
char queryString[GET_PAR_VAL_LEN];
char appo[GET_PAR_VAL_LEN];
char getContext[GET_PAR_VAL_LEN];
int errCode = 0;
if( !pickPar( inputStr, 1, &phraseTag ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &forceLang ) ) forceLang = 0;
if (cgiFormString( LangTagGet, getLangCode, 0) != cgiFormSuccess)
sprintf(getLangCode, "%s", DefaultLanguageId); /*identificativo della lingua di default*/
if ( forceLang != 0 )
sprintf(getLangCode, "%s", forceLang); /*valore dell'id della lingua forzato a forceLang*/
sprintf(queryString,"select %s from %s where %s = %s",
LangNameField, LangTable, LangCodeField, getLangCode);
newAutoName();
dbInterface(QueryLabel, queryString, 1, 1);
langName = storedData(1, LangNameField, QueryLabel, &errCode);
sprintf(queryString, "select %s from %s where %s = '%s'",
langName, TransTable, TransTagField, phraseTag);
if ((TargetTplField != 0) && (TplTable != 0) &&
(TplTableId != 0) && (TplTableName != 0))
{
if ((strcmp(TargetTplField,"")!=0) &&
(strcmp(TplTable,"")!=0) &&
(strcmp(TplTableId,"")!=0) &&
(strcmp(TplTableName ,"")!=0))
{
if (strcmp(CurrentTpl[TplNest],"")!=0)
{
sprintf(queryString,
"SELECT f.%s "
"FROM %s f, %s t "
"WHERE f.%s = '%s' "
"AND f.%s = t.%s "
"AND t.%s = '%s' ",
langName,
TransTable, TplTable,
TransTagField, phraseTag,
TargetTplField, TplTableId,
TplTableName, CurrentTpl[TplNest]);
if (cgiFormString( ContextTag, getContext, 0) == cgiFormSuccess)
{
sprintf(appo," AND t.%s = %s ", ContextField, getContext);
strcat(queryString, appo);
}
}
}
}
newAutoName();
dbInterface(QueryLabel, queryString, 1, 1);
translatedPhrase = storedData(1, langName, QueryLabel, &errCode);
/**/if(usedbg){fprintf(debug, "translateIt-translatedPhrase:%s\n", translatedPhrase);fflush(debug);}
return (translatedPhrase);
}
/*************************************************************************************
NOME :crypt
Categoria :Gasp Command: *crypt(toBeCrypted)
attivita' :cripta il parametro
*************************************************************************************/
void *crypt(int vuoto1, char *vuoto2, char * inputStr)
{
char *toBeCrypted;
char * crypted;
if( !pickPar( inputStr, 1, &toBeCrypted ) ) return(PARAM_NOT_FOUND_MSG);
crypted = (char*) malloc (10 * strlen(toBeCrypted) * sizeof(char) );
/**/if(alloctrc){fprintf(debug, "- - crypted:%d - - len:%d\n", crypted, 10 * strlen(toBeCrypted) * sizeof(char) );fflush(debug);}
tannitEncrypt(toBeCrypted, crypted);
return (crypted);
}
/*************************************************************************************
NOME :decrypt
Categoria :Gasp Command: *decr(toBeDecrypted)
attivita' :decripta il parametro
*************************************************************************************/
void *decrypt(int vuoto1, char *vuoto2, char * inputStr)
{
char *toBeDecr;
char * clear;
if( !pickPar( inputStr, 1, &toBeDecr ) ) return(PARAM_NOT_FOUND_MSG);
/**/if(usedbg){fprintf(debug, "toBeDecr:::::::::%s\n", toBeDecr);fflush(debug);}
clear = (char*) malloc (strlen(toBeDecr) * sizeof(char) );
/**/if(alloctrc){fprintf(debug, "- - clear:%d - - len:%d\n", clear, strlen(toBeDecr) * sizeof(char) );fflush(debug);}
tannitDecrypt(toBeDecr, clear);
/**/if(usedbg){fprintf(debug, "toBeDecr:::::::::%s\n", toBeDecr);fflush(debug);}
/**/if(usedbg){fprintf(debug, "clear::::::::::::%s\n", clear);fflush(debug);}
return (clear);
}
/*************************************************************************************
NOME :crypt2
Categoria :Funzione inutile che non funziona (chissa', un giorno...)
attivita' :nessuna
*************************************************************************************/
void *crypt2(int vuoto1, char *vuoto2, char * inputStr)
{
char *toBeCrypted;
unsigned char* crypted;
if( !pickPar( inputStr, 1, &toBeCrypted ) ) return(PARAM_NOT_FOUND_MSG);
crypted = (unsigned char*) calloc(sizeof(char), MAX_CRYPTING_BUFFER);
// Sta roba non ha mai funzionato va sostituito ma non si sa
// if ((result = itxCodeString(toBeCrypted, crypted, MAX_CRYPTING_BUFFER) == 0))
// return (CRYPTING_ERROR);
//**/if(usedbg){fprintf(debug, "result: %d;\n", result);fflush(debug);}
// crypted[result] = '\0';
//**/if(usedbg){fprintf(debug, "crypted: %s;\n", crypted);fflush(debug);}
//**/if(usedbg){fprintf(debug, "toBeCrypted: %s;\n", toBeCrypted);fflush(debug);}
return (crypted);
}
/*************************************************************************************
NOME :processExternFile
Categoria :Gasp Command: *prex(fileToInclude)
attivita' :prosegue il parsing nel file specificato. Una volta concluso quest'ultimo
prosegue per il file di partenza.
*************************************************************************************/
void * processExternFile(int vuoto1, char *vuoto2, char * inputStr)
{
char * fileName;
char * externData;
char * outputString = 0;
if(!pickPar(inputStr, 1, &fileName ) ) return(PARAM_NOT_FOUND_MSG);
// apre il template, alloca tplString, e vi copia i dati
TplNest++;
if( bufferTpl(&externData, fileName, TplDir) == 0)
{
fprintf(cgiOut,"%s\n", ERR_OPEN_TPL_FILE);//fflush(cgiOut);
EXIT(__LINE__);
}
// interpretazione dei dati e scrittura su cgiOut
procTplData(externData, cgiOut, &outputString);
TplNest--;
return (0);
}
/*************************************************************************************
NOME :setCookie
Categoria :Gasp Command: *setCoo(name,value)
attivita' :imposta all'utente il cookie "nome=valore".
*************************************************************************************/
void * setCookie(int vuoto1, char *vuoto2, char * inputStr)
{
char * name, *value, *expires;
int retvalue = 0;
if( !pickPar( inputStr, 1, &name ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &value ) ) return(PARAM_NOT_FOUND_MSG);
retvalue = pickPar( inputStr, 3, &expires );
/* in later version, do checks for valid variables */
printf("Set-Cookie: %s=%s;",name,value);
if (retvalue != PARAM_NOT_FOUND)
printf(" EXPIRES=%s;",expires);
printf(" PATH='/';");
printf("\n");
return 0;
}
/*************************************************************************************
NOME :isInTheDomain
Categoria :Gasp Command: *inDomain()
attivita' :sgama se l'utente remoto � nel dominio tale...
DA DOCUMENTARE
DA DOCUMENTARE
DA DOCUMENTARE
DA DOCUMENTARE
DA DOCUMENTARE
*************************************************************************************/
void* isInTheDomain(int vuoto1, char *vuoto2, char * inputStr)
{
static char localHost[HOME_DIR_LEN];
static char remotHost[HOME_DIR_LEN];
char * cursor = NULL;
char * cLevel = NULL;
int ipLen = 0;
if( !pickPar( inputStr, 1, &cLevel ) ) return("false");
// Acquisizione della stringa del dominio del client e dell'host
sprintf(localHost,"%s",cgiRemoteHost);
sprintf(remotHost,"%s",cgiHttpHost);
// Troncamento dei livelli A e B dell'ip dell'Host
if ( (ipLen = strlen(localHost) ) > 15 )
return ("false");
cursor = strpbrk(localHost, ".");
if ( (cursor == NULL) || (cursor - localHost > 4) )
return ("false");
cursor++;
if ( (cursor - localHost > ipLen ) || (cursor - localHost < 0) )
return ("false");
cursor = strpbrk(cursor, ".");
if ( (cursor == NULL) )
return ("false");
ipLen = cursor - localHost;
if ( ( ipLen > ipLen ) || ( ipLen < 0) )
return ("false");
cursor[0] = 0;
cursor++;
if ( strncmp( remotHost, localHost, ipLen) != 0)
return ("false");
char * appo = NULL;
if ( (appo = strstr(cursor, cLevel) ) == NULL )
return ("false");
if ( (cursor - appo ) != 0 )
return ("false");
if( cursor[strlen(cLevel)+1] != '.')
return ("false");
return ("true");
}
/*************************************************************************************
NOME :fontStyle
Categoria :Gasp Command: *fontSt(phraseTag)
attivita' :ritorna una stringa di definizione di font.
La sintassi � CSS, i valori sono ricavati dalla tabella TransTable
(specificata nel file prm) ed il record � individuato dal valore phraseTag
nel campo TransTagField.
I campi della tabella che definiscono i valori CSS sono specificati nel
file dei parametri e sono FFace1, FFace2, FSize, FStyle, FColor, FDecor,
Lheight.
*************************************************************************************/
void * fontStyle(int vuoto1, char *vuoto2, char * inputStr)
{
char *phraseTag;
char *retString;
char queryString[GET_PAR_VAL_LEN];
int errCode = 0;
char *fFace1buf, *fFace2buf, *fSizebuf, *fStylebuf, *fColorbuf, *fDecBuf, *lHeigBuf;
char fontFamily[512], fontSize[512], objColor[512], fontStyle[512], fDecoration[512], lHeight[512];
char getContext[GET_PAR_VAL_LEN];
char appo[GET_PAR_VAL_LEN];
if( !pickPar( inputStr, 1, &phraseTag ) ) return(PARAM_NOT_FOUND_MSG);
if( strlen(FFace1) == 0 || strlen(FFace2) == 0 || strlen(FSize) == 0 ||
strlen(FStyle) == 0 || strlen(FColor) == 0 || strlen(FDecor) == 0 ||
strlen(TransTable) == 0 || strlen(TransTagField) == 0
)
{
fprintf(cgiOut, "%s\n", retMsg(ERR_PARAM_NEEDED) );
EXIT(1);
}
sprintf(queryString, "SELECT %s, %s, %s, %s, %s, %s, %s FROM %s WHERE %s = '%s'",
FFace1, FFace2, FSize, FStyle, FColor, FDecor, Lheight, TransTable, TransTagField, phraseTag);
if ((TargetTplField != 0) && (TplTable != 0) &&
(TplTableId != 0) && (TplTableName != 0))
{
if ((strcmp(TargetTplField,"")!=0) &&
(strcmp(TplTable,"")!=0) &&
(strcmp(TplTableId,"")!=0) &&
(strcmp(TplTableName ,"")!=0))
{
if (strcmp(CurrentTpl[TplNest],"")!=0)
{
sprintf(queryString,
"SELECT f.%s, f.%s, f.%s, f.%s, f.%s, f.%s, f.%s "
"FROM %s f, %s t "
"WHERE f.%s = '%s' "
"AND f.%s = t.%s "
"AND t.%s = '%s' ",
FFace1, FFace2, FSize, FStyle, FColor, FDecor, Lheight,
TransTable, TplTable,
TransTagField, phraseTag,
TargetTplField, TplTableId,
TplTableName, CurrentTpl[TplNest]);
if (cgiFormString( ContextTag, getContext, 0) == cgiFormSuccess)
{
sprintf(appo," AND t.%s = %s ", ContextField, getContext);
strcat(queryString, appo);
}
}
}
}
newAutoName();
/**/if(usedbg){fprintf(debug, "fontStyle - FFace1 at %d: %s\n", FFace1, FFace1);fflush(debug);}
/**/if(usedbg){fprintf(debug, "fontStyle - queryString: %s\n", queryString);fflush(debug);}
dbInterface(QueryLabel, queryString, 1, 1);
fFace1buf = storedData(1, FFace1, QueryLabel, &errCode);
fFace2buf = storedData(1, FFace2, QueryLabel, &errCode);
fSizebuf = storedData(1, FSize, QueryLabel, &errCode);
fStylebuf = storedData(1, FStyle, QueryLabel, &errCode);
fColorbuf = storedData(1, FColor, QueryLabel, &errCode);
fDecBuf = storedData(1, FDecor, QueryLabel, &errCode);
lHeigBuf = storedData(1, Lheight,QueryLabel, &errCode);
sprintf(fontFamily, " ");
sprintf(fontSize, " ");
sprintf(fontStyle, " ");
sprintf(objColor, " ");
sprintf(fDecoration, " ");
sprintf(lHeight, " ");
if( (strlen(fFace1buf) > 0 ) )
{
sprintf(fontFamily, " font-family: '%s'", fFace1buf);
if( strlen(fFace2buf) > 0 )
{
strcat(fontFamily, ", '");
strcat(fontFamily, fFace2buf);
strcat(fontFamily, "'");
}
strcat(fontFamily, ";");
}
if( (strlen(fSizebuf) > 0 ) )
{
sprintf(fontSize, " font-size: %spt;", fSizebuf);
}
if( (strlen(fStylebuf) > 0 ) )
{
sprintf(fontStyle, " font-style: %s;", fStylebuf);
}
if ( strlen(fColorbuf) > 0 )
{
sprintf(objColor, " color: #%s; ", fColorbuf);
}
if ( strlen(fDecBuf) > 0 )
{
sprintf(fDecoration, "text-decoration: %s; ", fDecBuf);
}
if ( strlen(lHeigBuf) > 0 )
{
sprintf(lHeight, "line-height: %spt; ", lHeigBuf);
}
retString = (char *)calloc (
strlen(fontFamily) + strlen(fontSize) + strlen(fontStyle) +
strlen(objColor) + strlen(fDecoration) + strlen(lHeight) + 64,
sizeof(char)
);
sprintf(retString, " style=\"%s %s %s %s %s %s\"",
fontFamily, fontSize, fontStyle, objColor, fDecoration, lHeight);
return (retString);
}
/*************************************************************************************
NOME :revealBrowser
Categoria :Gasp Command: *revBr()
attivita' :scrive 'explorer' se il browser si identifica come MSIE altrimenti netscape
*************************************************************************************/
void * revealBrowser(int vuoto1, char *vuoto2, char * inputStr)
{
if (strstr(cgiUserAgent, "MSIE") )
return ISEXPLORER;
else
return ISNETSCAPE;
}
/*************************************************************************************
NOME :writeSpan
Categoria :Gasp Command: *span(phraseTag)
attivita' :� equivalente a
<SPAN *fontST(phraseTag)>*trans(phraseTag)</SPAN>
*************************************************************************************/
void * writeSpan(int vuoto1, char *vuoto2, char * inputStr)
{
char *phraseTag, *fontSt, *transPh, *retString;
//**/if(usedbg){fprintf(debug, "writeSpan: STARTING\n");fflush(debug);}
if( !pickPar( inputStr, 1, &phraseTag ) ) return(PARAM_NOT_FOUND_MSG);
fontSt = (char*) fontStyle(0, 0, phraseTag);
/**/if(usedbg){fprintf(debug, "TargetTplField B- %s\n", TargetTplField);fflush(debug);}
transPh = (char*) translateIt(0, 0, phraseTag);
/**/if(usedbg){fprintf(debug, "TargetTplField C- %s\n", TargetTplField);fflush(debug);}
retString = (char*) calloc(strlen(fontSt) + strlen(transPh) + 64, sizeof(char) );
sprintf(retString, " <SPAN %s>%s</SPAN>", fontSt, transPh);
return (retString);
}
/*************************************************************************************
NOME :traceUser
Categoria :Gasp Command: *traceU(feature)
attivita' :restituisce informazioni sul client a seconda del parametro feature.
feature=brname->nome del browser
feature=brver ->versione del browser (solo parte intera)
feature=osname->nome del sistema operativo
feature=ipnum ->numero ip
feature=ipname->nome, quando risolvibile, della macchina remota
*************************************************************************************/
void * traceUser(int vuoto1, char *vuoto2, char * inputStr)
{
char *feature;
char *cursor;
static char brname[128], brver[128], osname[128];
/**/if(usedbg){fprintf(debug, "traceUser: STARTING\n");fflush(debug);}
memset(brname, '\0', 128);
memset(brver, '\0', 128);
memset(osname, '\0', 128);
/**/if(usedbg){fprintf(debug, "traceUser: 1\n");fflush(debug);}
if( !pickPar( inputStr, 1, &feature ) ) return(PARAM_NOT_FOUND_MSG);
cursor = strstr(cgiUserAgent, "Mozilla/");
/**/if(usedbg){fprintf(debug, "traceUser: 2\n");fflush(debug);}
if (cursor)
{
/**/if(usedbg){fprintf(debug, "traceUser: 3\n");fflush(debug);}
if (cursor=strstr(cgiUserAgent, "MSIE"))
{
/**/if(usedbg){fprintf(debug, "traceUser: 4\n");fflush(debug);}
strcpy(brname, BROWSER_MSIE);
brver[0] = cursor[5];
if(strstr(cgiUserAgent, "Windows 98"))
strcpy(osname, "MS Windows 98");
else if(strstr(cgiUserAgent, "Windows 95"))
strcpy(osname, "MS Windows 95");
else if(strstr(cgiUserAgent, "Windows NT"))
strcpy(osname, "MS Windows NT");
else if(strstr(cgiUserAgent, "Windows 3.1"))
strcpy(osname, "MS Windows 3.1");
else if(strstr(cgiUserAgent, "Mac_"))
strcpy(osname, "Apple Macintosh");
}
else if (cursor=strstr(cgiUserAgent, "Opera"))
{
/**/if(usedbg){fprintf(debug, "traceUser: 5\n");fflush(debug);}
strcpy(brname, BROWSER_OPERA);
}
else
{
/**/if(usedbg){fprintf(debug, "traceUser: 6\n");fflush(debug);}
strcpy(brname, BROWSER_NETSCAPE);
/**/if(usedbg){fprintf(debug, "traceUser: 7\n");fflush(debug);}
brver[0] = cgiUserAgent[8];
/**/if(usedbg){fprintf(debug, "traceUser: 8\n");fflush(debug);}
if(strstr(cgiUserAgent, "Win98"))
strcpy(osname, "MS Windows 98");
else if(strstr(cgiUserAgent, "Win95"))
strcpy(osname, "MS Windows 95");
else if(strstr(cgiUserAgent, "WinNT"))
strcpy(osname, "MS Windows NT");
else if(strstr(cgiUserAgent, "Win16"))
strcpy(osname, "MS Windows 3.1");
else if(strstr(cgiUserAgent, "Macintosh"))
strcpy(osname, "Macintosh");
else if(strstr(cgiUserAgent, "Linux"))
strcpy(osname, "Linux");
else if(strstr(cgiUserAgent, "SunOS"))
strcpy(osname, "SunOS");
/**/if(usedbg){fprintf(debug, "traceUser: 9\n");fflush(debug);}
}
}
/**/if(usedbg){fprintf(debug, "traceUser: RETURNING\n");fflush(debug);}
if (strcmp(feature,"brname")==0)
return brname;
else if (strcmp(feature,"brver")==0)
return brver;
else if (strcmp(feature,"osname")==0)
return osname;
else if (strcmp(feature,"ipnum")==0)
return cgiRemoteAddr;
else if (strcmp(feature,"ipname")==0)
return cgiRemoteHost;
return 0;
}
/*************************************************************************************
NOME :exeQnew
*************************************************************************************/
void* exeQnew(int vuoto1,char *vuoto2, char * inputStr)
{
char *queryName, *queryString, *firstRecord, *recsToStore;
int firstRecInt = STARTING_ROW, recsToStoreInt = ROWS_TO_STORE;
//**/if(usedbg){fprintf(debug, "execQuery-inputStr:%s\n", inputStr);fflush(debug);}
if(!pickPar(inputStr, 1, &queryName) ) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &queryString) ) return(PARAM_NOT_FOUND_MSG);
if( pickPar(inputStr, 3, &firstRecord) ) firstRecInt = atoi(firstRecord);
if( pickPar(inputStr, 4, &recsToStore) ) recsToStoreInt = atoi(recsToStore);
remBlindingChar(queryString);
ITannit_Create(QueryResultSet, &QueryCounter);
ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, queryName, queryString, firstRecInt, recsToStoreInt);
//if (ITannit_MoreResultSQL())
ITannit_Dump(debug);
/**/if(usedbg) ITannit_ErrorSQL(debug);
/**/if(usedbg){fprintf(debug, "execQuery: dati archiviati;\n");fflush(debug);}
return 0;
}
void* dbgmsg(int vuoto1,char *vuoto2, char * inputStr)
{
/**/if(usedbg){fprintf(debug, "Debug Message:%s\n", inputStr);fflush(debug);}
return 0;
}
<file_sep>/* desx.h
* Graven Imagery, 1994
*
* "DESX" is a trademark of RSA Data Security, Inc.
*
* THIS SOFTWARE PLACED IN THE PUBLIC DOMAIN BY THE AUTHOR.
*
* (c) 1994 by <NAME> (CI$ : [71755,204])
*/
struct DESXKey {
unsigned char DESKey64[8];
unsigned char Whitening64[8];
};
struct DESContext {
unsigned long dxkenc[32];
unsigned long dxkdec[32];
};
struct DESXContext {
struct DESContext Context;
unsigned long PreWhitening64[2];
unsigned long PostWhitening64[2];
};
void DESXKeySetup(
struct DESXContext *output,
struct DESXKey *input );
void DESXEncryptBlock(
struct DESXContext* _using,
unsigned char* OutData64,
unsigned char* InData64 );
void DESXDecryptBlock(
struct DESXContext* _using,
unsigned char* OutData64,
unsigned char* InData64 );
/* desx.h V1.00 rwo 94/03/02 00:04:23 EST Graven Imagery
********************************************************************/
<file_sep><HTML>
<HEAD>
<TITLE>Tannit 4.0 Command Reference </TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#ffffff" TOPMARGIN=0>
<LINK REL=STYLESHEET HREF="styles.css" TYPE="text/css">
<span class=CmdTitolo>
*lcase(</span>
<span class=ParamName>
<!-- TODO BEGIN : Add the following block until TODO END for each parameter -->
string
<!-- TODO END -->
</span>
<span class=CmdTitolo>
)</span>
<BR>
<BR>
<!-- TODO BEGIN -->
<DD>Lower cases the input string.</DD>
<!-- TODO END -->
<BR>
<BR>
<BR>
<span class=CmdTitolo>
*ucase(
</span>
<span class=ParamName>
string
</span>
<span class=CmdTitolo>
)</span>
<BR>
<BR>
<BR>
<!-- TODO BEGIN -->
<dd>Upper cases the input string.</dd>
<!-- TODO END -->
<BR>
<BR>
<span class=CmdTitolo>
*left(
</span>
<span class=ParamName>
str,len
<!-- TODO END -->
</span>
<span class=CmdTitolo>
)
</span>
<BR>
<BR>
<!-- TODO BEGIN -->
<dd>Returns the first <i>len</i> characters of <i>str</i>.</dd>
<!-- TODO END -->
<br>
<br>
<span class=CmdTitolo>
*right(
</span>
<span class=ParamName>
str,len
<!-- TODO END -->
</span>
<span class=CmdTitolo>
)
</span>
<BR>
<BR>
<!-- TODO BEGIN -->
<dd>Returns the last <i>len</i> characters of <i>str</i>.</dd>
<!-- TODO END -->
<br>
<br>
<span class=CmdTitolo>
*
trim(
</span>
<span class=ParamName>
string
</span>
<span class=CmdTitolo>
)
</span>
<BR>
<BR>
<!-- TODO BEGIN -->
<dd>Left and right trims the input string.</dd>
<!-- TODO END -->
<BR>
<BR>
<center>
<A HREF="index.htm">Command Reference Index</A><br>
</center>
<br>
<br>
<br>
</BODY>
</HTML>
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxdefines.h,v $
* $Revision: 1.5 $
* $Author: massimo $
* $Date: 2002-06-24 13:38:56+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 rom<NAME>
* <EMAIL>
*/
#ifndef __ITXDEFINES_H__
#define __ITXDEFINES_H__
#define GENERIC_CATCHALL catch(...) \
{ \
throw; \
}
#define CATCH_TO_NOTHING catch(...){}
// This macro sends generic exception message
#define CATCHALLMSG(msg) catch(...) {throw (msg);}
// This macro returns the signed distance between
// the absolute value of two pointers
#define PTR_DISTANCE(p2, p1) ((unsigned)(p2) - (unsigned)(p1))
//Memory
#define ITXALLOC(nbytes) malloc((nbytes))
#define ITXFREE(ptr) free((ptr))
// This macro expands the internal buffer of one G. NO CHECKS PERFORMED!!!!
#define MALLOC(buf, endbuf, bufsize, G) { \
try \
{ \
char* temp; \
if ((temp = (char*)ITXALLOC((bufsize) + (G))) != NULL) \
{ \
if ((buf) != NULL) \
{ \
memcpy(temp, (buf), (bufsize)); \
(endbuf) = temp + ((unsigned)(endbuf) - (unsigned)(buf)); \
ITXFREE(buf); \
} \
else \
(endbuf) = temp; \
(buf) = temp; \
(bufsize) += (G); \
} \
} \
catch(...){throw;}}
/*
The user of this macro MUST compare current m_Bufsize with needed new
dimension before calling this. The algorithm computes the number of
G packs needed (at least) to extend the actual buffer.
XALLOC(buf, endbuf, bufsize, G, size)
{
saveG = G;
G = ((size - bufsize) / G) + 1) * (G);
MALLOC(buf, endbuf, bufsize, G);
G = saveG;
}
*/
#define XALLOC(buf, endbuf, bufsize, G, size) \
{ \
int saveG = (int)(G); \
(G) = ((int)(((size) - (bufsize)) / (G)) + 1) * (G); \
MALLOC((buf), (endbuf), (bufsize), (G)); \
(G) = saveG; \
}
#endif /* __ITXDEFINES_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxsql.h,v $
* $Revision: 1.4 $
* $Author: massimo $
* $Date: 2002-06-24 13:38:58+02 $
*
* Definition of the itxSQLConnection object (ODBC connection wrapper)
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __TNTSQL_H__
#define __TNTSQL_H__
#include "itxsystem.h"
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
#include "itxbuffer.h"
#include "itxlib.h"
// SQL INTERFACE CONSTANTS
#define ITX_QRS_MAX_NAME_LEN 63
#define ITX_QRS_MAX_FIELD_LEN 32767
#define ITX_QRS_MAX_QUERY_LEN 32767
//
#define ITX_SQL_DSN_LENGTH 32
#define ITX_SQL_UID_LENGTH 16
#define ITX_SQL_PWD_LENGTH 16
#define ITX_SQL_MAX_ERRMSG 512
#define ITX_SQL_STATUS_LEN 6
#define ITX_SQL_MAX_CONN 10
#define ITX_SQL_NAME_CONN_LEN 32
class itxSQLConnection
{
public:
itxString m_name;
itxString m_dsn;
itxString m_usr;
itxString m_pwd;
HENV m_henv;
HDBC m_hdbc;
SQLHANDLE m_hstmt;
char m_statement[ITX_QRS_MAX_QUERY_LEN];
SQLINTEGER m_ind;
short int m_cols;
short int m_rows;
public:
// Error parameters
SQLCHAR m_sqlstate[ITX_SQL_STATUS_LEN];
SQLINTEGER m_nativerr;
SQLCHAR m_message[ITX_SQL_MAX_ERRMSG];
SQLSMALLINT m_msglength;
public:
itxSQLConnection();
~itxSQLConnection() { Destroy(); };
bool IsConnected() { return (m_henv ? true : false ); };
bool Create(char* dsn, char* uid, char* pwd);
bool Create(char* name, char* dsn, char* uid, char* pwd);
bool Create();
bool SetAttributes(int attr, void* value, int valuelen);
bool Destroy();
bool Execute(char* statement);
bool Prepare(char* statement);
bool GetColInfo(short int col, char* name, short* type, long int* size);
bool SkipRecords(int start, int end);
bool BindCol(int col, char* value, int size, SQLSMALLINT target_type = SQL_C_CHAR);
bool BindCol(int col, float* value, int size);
bool Fetch();
bool GetBinData(int col, itxBuffer& outbuf);
bool FreeStmt(unsigned short flag);
bool MoreResults();
void Trace();
bool GetColsNumber();
bool ManualCommit();
bool AutoCommit();
bool Commit();
bool Rollback();
};
class itxSQLConnCollection
{
private:
itxSQLConnection* m_connections[ITX_SQL_MAX_CONN];
public:
itxSQLConnCollection();
~itxSQLConnCollection() {};
itxSQLConnection* Get(char* name);
void Put(itxSQLConnection* sqlconn);
bool CloseAll();
};
#endif //__TNTSQL_H__
<file_sep># Microsoft Developer Studio Generated NMAKE File, Based on ocore.dsp
!IF "$(CFG)" == ""
CFG=ocore - Win32 Debug
!MESSAGE No configuration specified. Defaulting to ocore - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "ocore - Win32 Release" && "$(CFG)" != "ocore - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "ocore.mak" CFG="ocore - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "ocore - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "ocore - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "ocore - Win32 Release"
OUTDIR=.\..\..\bin
INTDIR=.\Release
ALL : ".\otannit.exe"
CLEAN :
-@erase "$(INTDIR)\auxfile.obj"
-@erase "$(INTDIR)\cgiresolver.obj"
-@erase "$(INTDIR)\commands.obj"
-@erase "$(INTDIR)\desx.obj"
-@erase "$(INTDIR)\parser.obj"
-@erase "$(INTDIR)\tannitobj.obj"
-@erase "$(INTDIR)\templatefile.obj"
-@erase "$(INTDIR)\tntapiimpl.obj"
-@erase "$(INTDIR)\tntsql.obj"
-@erase "$(INTDIR)\tqr.obj"
-@erase "$(INTDIR)\tqrodbc.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase ".\otannit.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
"$(INTDIR)" :
if not exist "$(INTDIR)/$(NULL)" mkdir "$(INTDIR)"
CPP_PROJ=/nologo /ML /W3 /GX /O2 /I "..\..\include" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "MAINT_1" /D "FCGITANNIT" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ocore.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib advapi32.lib odbc32.lib winmm.lib libci.lib libc.lib oldnames.lib itxlib.lib libfcgi.lib /nologo /subsystem:console /incremental:no /pdb:"$(OUTDIR)\otannit.pdb" /machine:I386 /nodefaultlib /out:"otannit.exe" /libpath:"..\..\lib"
LINK32_OBJS= \
"$(INTDIR)\tannitobj.obj" \
"$(INTDIR)\auxfile.obj" \
"$(INTDIR)\cgiresolver.obj" \
"$(INTDIR)\commands.obj" \
"$(INTDIR)\desx.obj" \
"$(INTDIR)\parser.obj" \
"$(INTDIR)\templatefile.obj" \
"$(INTDIR)\tntapiimpl.obj" \
"$(INTDIR)\tntsql.obj" \
"$(INTDIR)\tqr.obj" \
"$(INTDIR)\tqrodbc.obj"
".\otannit.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
SOURCE="$(InputPath)"
DS_POSTBUILD_DEP=$(INTDIR)\postbld.dep
ALL : $(DS_POSTBUILD_DEP)
$(DS_POSTBUILD_DEP) : ".\otannit.exe"
copy otannit.exe "E:\Programmi\Apache Group\Apache\cgi-bin\otannit.exe"
copy otannit.exe "W:\wwwroot\cometest\cgi-bin\temp_tannit.exe"
echo Helper for Post-build step > "$(DS_POSTBUILD_DEP)"
!ELSEIF "$(CFG)" == "ocore - Win32 Debug"
OUTDIR=.\..\..\bin
INTDIR=.\Debug
ALL : ".\otannit.exe"
CLEAN :
-@erase "$(INTDIR)\auxfile.obj"
-@erase "$(INTDIR)\cgiresolver.obj"
-@erase "$(INTDIR)\commands.obj"
-@erase "$(INTDIR)\desx.obj"
-@erase "$(INTDIR)\parser.obj"
-@erase "$(INTDIR)\tannitobj.obj"
-@erase "$(INTDIR)\templatefile.obj"
-@erase "$(INTDIR)\tntapiimpl.obj"
-@erase "$(INTDIR)\tntsql.obj"
-@erase "$(INTDIR)\tqr.obj"
-@erase "$(INTDIR)\tqrodbc.obj"
-@erase "$(INTDIR)\vc60.idb"
-@erase "$(INTDIR)\vc60.pdb"
-@erase "$(OUTDIR)\otannit.pdb"
-@erase ".\otannit.exe"
-@erase ".\otannit.ilk"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
"$(INTDIR)" :
if not exist "$(INTDIR)/$(NULL)" mkdir "$(INTDIR)"
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /ZI /Od /I "..\..\include" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "MAINT_1" /D "FCGITANNIT" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /GZ /c
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ocore.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib advapi32.lib odbc32.lib winmm.lib libc.lib libci.lib oldnames.lib itxlib.lib libfcgi.lib /nologo /subsystem:console /incremental:yes /pdb:"$(OUTDIR)\otannit.pdb" /debug /machine:I386 /out:"otannit.exe" /pdbtype:sept /libpath:"..\..\lib"
LINK32_OBJS= \
"$(INTDIR)\tannitobj.obj" \
"$(INTDIR)\auxfile.obj" \
"$(INTDIR)\cgiresolver.obj" \
"$(INTDIR)\commands.obj" \
"$(INTDIR)\desx.obj" \
"$(INTDIR)\parser.obj" \
"$(INTDIR)\templatefile.obj" \
"$(INTDIR)\tntapiimpl.obj" \
"$(INTDIR)\tntsql.obj" \
"$(INTDIR)\tqr.obj" \
"$(INTDIR)\tqrodbc.obj"
".\otannit.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
SOURCE="$(InputPath)"
DS_POSTBUILD_DEP=$(INTDIR)\postbld.dep
ALL : $(DS_POSTBUILD_DEP)
$(DS_POSTBUILD_DEP) : ".\otannit.exe"
copy otannit.exe "E:\Programmi\Apache Group\Apache\cgi-bin\otannit.exe"
echo Helper for Post-build step > "$(DS_POSTBUILD_DEP)"
!ENDIF
.c{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(INTDIR)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
!IF "$(NO_EXTERNAL_DEPS)" != "1"
!IF EXISTS("ocore.dep")
!INCLUDE "ocore.dep"
!ELSE
!MESSAGE Warning: cannot find "ocore.dep"
!ENDIF
!ENDIF
!IF "$(CFG)" == "ocore - Win32 Release" || "$(CFG)" == "ocore - Win32 Debug"
SOURCE=.\auxfile.cpp
"$(INTDIR)\auxfile.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\cgiresolver.cpp
"$(INTDIR)\cgiresolver.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\commands.cpp
"$(INTDIR)\commands.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\desx.cpp
"$(INTDIR)\desx.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\parser.cpp
"$(INTDIR)\parser.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\tannitobj.cpp
"$(INTDIR)\tannitobj.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\templatefile.cpp
"$(INTDIR)\templatefile.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\tntapiimpl.cpp
"$(INTDIR)\tntapiimpl.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\tntsql.cpp
"$(INTDIR)\tntsql.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\tqr.cpp
"$(INTDIR)\tqr.obj" : $(SOURCE) "$(INTDIR)"
SOURCE=.\tqrodbc.cpp
"$(INTDIR)\tqrodbc.obj" : $(SOURCE) "$(INTDIR)"
!ENDIF
<file_sep>package com.imdp;
/**
* Created by massimo on 4/21/14.
*/
public class StaticMeth {
int a = 5;
// StaticMeth(){}
String getA(){return "SaticMeth " + a;}
static String buf = new String("Who's creating this object?");
StaticMeth(){
System.out.println(this.toString() + " - " + this.hashCode());
}
public static String theStaticMethod() {
return buf;
}
}
class B extends StaticMeth {
@Override
String getA(){a = 7; return "B " + a;}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// AITECSA s.r.l. 1999
// filename: tpparser.cpp
// description: itannit AS400 interface library
// AS400 transaction program packet parsing
// project: ASWEB
#ifndef __ITX_TP_PARSER_CPP__
#define __ITX_TP_PARSER_CPP__
#endif
#include <strstrea.h>
#include <string.h>
#include <time.h>
#include "itxtypes.h"
#include "itannitc.h"
void ITannit_SubStr(char* source, char* destination, int maxlength, char* tag, char* newtag)
{
char* src = source;
char* src_cursor = source;
char* dst = destination;
unsigned long chunk = 0;
unsigned long taglen = strlen(tag);
unsigned long ntglen = strlen(newtag);
memset(destination, '\0', maxlength);
while ((src_cursor = strstr(src, tag)) != NULL)
{
chunk = (unsigned long) src_cursor - (unsigned long) src;
strncpy(dst, src, chunk);
dst += chunk;
src += chunk;
strncpy(dst, newtag, ntglen);
dst += ntglen;
src += taglen;
}
strcpy(dst, src);
}
char* ITannit_LTrim(char* source)
{
int i = 0;
char* p = source;
while (p[i] == ' ') i++;
return p+i;
}
char* ITannit_RTrim(char* source)
{
int i = strlen(source);
char* p = source;
while (p[i-1] == ' ')
{
p[i-1] = '\0';
i--;
}
return source;
}
char* ITannit_Trim(char* source)
{
ITannit_RTrim(source);
return ITannit_LTrim(source);
}
void ITannit_EBCDtoASCII(PTannitQueryResult qres)
{
int i;
TannitRecord* rec = qres->recPtr;
while (rec != NULL)
{
for (i = 0; i < qres->colsNumber; i++);
// itxEBCDToASCII(rec->row[i]);
rec = rec->next;
}
}
// Si intende che la stringa puntata da tp sia gi� stata assemblata e
// ripulita della parte intestazione e del ITX_APPC_ENDINFO_SEP.
// Gli argomenti fromrecord e numrecord non vengono utilizzati per il momento.
void ITannit_ParsTP(char* tablename, char* tp, int fromrecord, int numrecord, FILE* fp,
char recsep, char fieldsep)
{
istrstream str_TP(tp);
char record[ITX_APPC_MAX_RECORD_LENGTH];
while(!str_TP.eof())
{
str_TP.getline(record, ITX_APPC_MAX_RECORD_LENGTH, recsep);
if (!ISNULL(record))
if (ITannit_ParsRecord(tablename, record, fp, fieldsep) == ITXFAILED)
ITannit_ParserLog(fp, "RECORD", record);
}
}
int ITannit_ParsRecord(char* tablename, char* record, FILE* fp, char fieldsep)
{
istrstream str_REC(record);
char stoken[ITX_APPC_MAX_FIELD_LENGTH];
char* token;
bool record_head = TRUE;
TannitQueryResult* qres = NULL;
int field_count = 0;
while(!str_REC.eof())
{
str_REC.getline(stoken, ITX_APPC_MAX_FIELD_LENGTH, fieldsep);
token = ITannit_Trim(stoken);
if (record_head)
{
if (tablename == NULL)
tablename = token;
if ((qres = ITannit_DBStructure(tablename)) == NULL)
return ITXFAILED;
record_head = FALSE;
}
if (field_count < qres->colsNumber)
{
if ((field_count = ITannit_StoreToken(qres, token, field_count)) == ITXFAILED)
{
ITannit_RemoveCurrentRec(qres);
ITannit_ParserLog(fp, "FIELD", token);
return ITXFAILED;
}
}
}
while (field_count < qres->colsNumber)
{
if ((field_count = ITannit_StoreToken(qres, "", field_count)) == ITXFAILED)
{
ITannit_RemoveCurrentRec(qres);
ITannit_ParserLog(fp, "FIELD", token);
return ITXFAILED;
}
}
if (!ITannit_CheckCurrentRec(field_count))
{
ITannit_RemoveCurrentRec(qres);
return ITXFAILED;
}
qres->totalRows++;
qres->rowsToStore++;
qres->startingRow = STARTING_ROW;
return field_count;
}
void ITannit_ParserLog(FILE* fp, char* des, char* token)
{
time_t tm;
if (fp == NULL) return;
time(&tm);
fprintf(fp, "\n");
fprintf(fp, " %s", ctime(&tm));
fprintf(fp, " ERROR IN PARSING %s :\n", des);
fprintf(fp, " ----> %s\n", token);
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxtime.h,v $
* $Revision: 1.3 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:30+02 $
*
* Definition of the itxTime object (time_t format object)
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __ITXTIME_H__
#define __ITXTIME_H__
#include <time.h>
#include "itxstring.h"
#include "itxsystem.h"
class itxTime
{
public:
itxString m_YyyyMmDd;
unsigned int m_SecsFromMid;
itxString m_outputfmt;
itxString m_output;
time_t m_t;
struct tm m_tm;
itxTime() { m_YyyyMmDd = ""; m_SecsFromMid = 0; m_outputfmt = ""; };
itxTime(char* yyyymmdd, unsigned int secs, char* outputfmt = "yyymmdd")
{
m_YyyyMmDd = yyyymmdd;
m_SecsFromMid = secs;
TimeConversion();
Format(outputfmt);
};
itxTime(int d, int m, int y, unsigned int secs, char* outputfmt = "yyymmdd")
{
SetFrom(d, m, y);
m_SecsFromMid = secs;
TimeConversion();
Format(outputfmt);
};
itxTime(time_t t, char* outputfmt = "yyymmdd") { SetFrom(t); TimeConversion(); Format(outputfmt); };
~itxTime() {};
void SetFrom(time_t t);
void SetFrom(int d, int m, int y);
void Tomorrow();
void Next(unsigned int hourinsecs);
void Now();
int SecFromMid(itxString* hour);
void Format(char* outputfmt);
private:
time_t TimeConversion();
};
#endif //__ITXTIME_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_TPTYPES_H__
#define __ITX_TPTYPES_H__
#define TPAS400_NAME_LEN 4
#define MAX_NUM_TPAS400 512
typedef enum
{
TPAS400_UNDEFINED,
A01,
A02,
A03,
A04,
A05,
A06,
A07,
A08,
A09,
A10,
A11,
A12,
A20,
A23,
A24,
A25,
A26,
A27,
A30,
A31,
A32,
A33,
A34,
A35,
A36,
A37,
A38,
A40,
A50,
A52,
A53,
A54,
A60,
A70,
A75,
A80,
A82,
A90,
A94,
A95,
A96,
A97,
C00,
C01,
C02,
C03,
E00,
E11,
H00,
H01,
H04,
H06,
H08,
H14,
H15,
H16,
H20,
H23,
H25,
H27,
H33,
H61,
H62,
H63,
H70,
H71,
H72,
H7L,
H82,
HAI,
HBA,
HBB,
HCD,
HCM,
HCN,
HG0,
HG1,
HG2,
HG3,
HG4,
HG5,
HG6,
HG7,
HG8,
HG9,
HL4,
HLA,
HLB,
HOK,
HPI,
HPO,
HPT,
HR4,
HR6,
HR7,
HR8,
HRA,
HRF,
HRI,
HSC,
HSH,
HVA,
HVO,
P00,
P03,
P04,
P06,
P07,
P11,
P12,
P14,
P15,
P16,
P20,
P21,
P25,
P27,
P30,
P60,
P70,
PR4,
NUM_TPAS400
}
TPAS400_ID;
typedef struct TPAS400
{
TPAS400_ID id;
char name[TPAS400_NAME_LEN];
short n_fields;
} TPAS400;
TPAS400_ID GetTPID(char* name);
#endif //__ITX_TPTYPES_H__<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.web.widgets.ntrenderer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jtxlib.main.datastruct.narytree.NaryTree;
import jtxlib.main.sql.DBConnection;
/**
* This servlet returns the html needed to dynamically add (child) nodes
* to the narytree html table: it is used in conjunction with the JTXNaryTreeRenderer
* mechanism of dynamic rendering, alternative to the 'toTABLE' method, which
* loads the whole tree structure at once (not that efficient if the tree is *very* big).<br>
* Basically, it returns all the javascript code needed to render the new nodes.<br>
* <p>
* Parameters of the request:<br>
* -------------------------<br>
* <dl>
* <dt>nodeid :<dd>the id of the node for which the child nodes are requested.
* <dt>noderow :<dd>the row index of the html table.
* <dt>dsn :<dd>the ODBC dsn used for the connection to the database
* <dt>nt_table :<dd>the narytree table name (see {@link jtxlib.datastruct.narytree.NaryTree})
* <dt>renderer :<dd>the name of the JTXNaryTreeRenderer instance at session scope to properly script table rows.
* <dl>
* @author gambineri
* @version
*/
public class ChildNodesStreamer extends HttpServlet
{
private static final long serialVersionUID = 8248471741770886684L;
private final String CRLF = "\r\n";
/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String nodeid = request.getParameter("nodeid");
String noderow = request.getParameter("noderow");
String dsn = request.getParameter("dsn");
String nt_table = request.getParameter("nt_table");
String renderer = request.getParameter("renderer");
if (nodeid == null || nodeid.length() == 0 ||
noderow == null || noderow.length() == 0 ||
dsn == null || dsn.length() == 0 ||
nt_table == null || nt_table.length() == 0 ||
renderer == null || renderer.length() == 0)
return;
NaryTreeRenderer ntr = (NaryTreeRenderer)request.getSession().getAttribute(renderer);
DBConnection conn = null;
conn = new DBConnection(dsn, "", "");
NaryTree nt = new NaryTree(conn, nt_table);
ntr.setNaryTree(nt);
PrintWriter out = response.getWriter();
response.setContentType("text/html; charset=UTF-8");
out.println(scriptFirstGeneration(ntr, nodeid, noderow));
out.close();
conn.close();
}
private String scriptFirstGeneration(NaryTreeRenderer ntr, String nodeid, String noderow)
{
String ret = "<html><head><script>" + CRLF + CRLF;
// Node[] childs = ntr.getNaryTree().getChilds(Tools.stringToInt(nodeid));
// int noderowstart = Tools.stringToInt(noderow);
ntr.setLoadMethod(NaryTreeRenderer.LoadMethod.LM_INCREMENTAL);
ret += ntr.dynCreateChildsToHiddenFrame(nodeid, noderow);
ret += "</script></head></html>";
return ret;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
/** Returns a short description of the servlet.
*/
public String getServletInfo()
{
return "Short description";
}
// </editor-fold>
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef _T_N_T_H_
#define _T_N_T_H_
/////////////////////////// AbstractCommand
class AbstractCommand
{
public:
virtual char* GetName() = 0;
virtual char* Execute(char*) = 0;
virtual void Deallocate() = 0;
AbstractCommand(){};
~AbstractCommand(){};
};
/////////////////////////// TNTAPI
class TNTAPI
{
public:
// CGIResolver
virtual int _GetPRMValue(char* param_name, char* param_value, int* bufdim) = 0;
virtual int _GetQueryStringVal(char* var_name, char* var_value, int* bufdim) = 0;
// Parser
virtual int _PickInt(char* inputstr, int par_pos, int* retval) = 0;
virtual int _PickDouble(char* inputstr, int par_pos, double* retval) = 0;
virtual int _PickString(char* inputstr, int position, char* retval, int* bufdim) = 0;
virtual int _PICKSTRING(char* inputstr, int par_pos, void* retstr) = 0;
// TQRManager
virtual void* _TQRCreate(char* queryname, int numfields) = 0;
virtual void _TQRLoadDataBuffer(char* tqrname, int tqrcols, char recsep, char fieldsep, char* buffer) = 0;
virtual bool _TQRExist(char* tqrname) = 0;
virtual void _TQRRewind(char* tqrname) = 0;
virtual void _TQRMoveFirst(char* tqrname) = 0;
virtual void _TQRMoveNext(char* tqrname) = 0;
virtual void _TQRMoveLast(char* tqrname) = 0;
virtual void _TQRMoveTo(char* tqrname, int irow) = 0;
virtual char* _TQRGetField(char* tqrname, char* colname) = 0;
virtual void _TQRDelete(char* tqrname) = 0;
virtual void _TQRFilter(char* source, char* field, char* value, char* destination) = 0;
virtual int _TQRRecordCount(char* source) = 0;
// TQRODBCManager
virtual void _ODBCConnect(char* dsn, char* uid, char* pwd) = 0;
virtual int _ODBCExecute(char* tqrname, char* query, int firstRec, int recsToStore) = 0;
virtual void* _ODBCGetCurrentConnection() = 0;
TNTAPI(){};
~TNTAPI(){};
};
extern TNTAPI* g_pTNTAPI; // Tannit hook
//------------------------------------------------------------------
//------------ Tannit Extension Module Facilities ------------------
//------------------------------------------------------------------
#ifdef WIN32
#define TNTEXPORT __declspec(dllexport)
#endif
// ******************************
// **** BEGIN_TANNIT_COMMAND_LIST
// ******************************
#define BEGIN_TANNIT_COMMAND_LIST \
TNTAPI* g_pTNTAPI; \
void TNTEXPORT TannitHandshake(AbstractCommand** ppCommands, TNTAPI* pTNTAPI) \
{int i = 0;
// ******************************
// **** END_TANNIT_COMMAND_LIST
// ******************************
#define END_TANNIT_COMMAND_LIST g_pTNTAPI = pTNTAPI;}
// ******************************
// **** TANNIT_COMMAND
// ******************************
#define TANNIT_COMMAND(cmd) ppCommands[i++] = (AbstractCommand*)&(cmd);
//------------------------------------------------------------------
//------------ Tannit Application Programming Interfaces -----------
//------------------------------------------------------------------
#define TNTPickInt(inputstr, par_pos, pint) \
g_pTNTAPI->_PickInt((inputstr), (par_pos), (pint))
#define TNTPickDouble(inputstr, par_pos, pdouble) \
g_pTNTAPI->_PickDouble((inputstr), (par_pos), (pdouble))
#define TNTPickString(inputstr, par_pos, retstr, bufdim) \
g_pTNTAPI->_PickString((inputstr), (par_pos), (retstr), (bufdim))
#define TNTPRMValue(param_name, param_value, bufdim) \
g_pTNTAPI->_GetPRMValue((param_name), (param_value), (bufdim))
#define TNTCreateTQR(queryname, numfields) \
g_pTNTAPI->_TQRCreate((queryname), (numfields))
#define TNTLoadDataBuffer(tqrname, tqrcols, recsep, fieldsep, buffer) \
g_pTNTAPI->_TQRLoadDataBuffer(tqrname, tqrcols, recsep, fieldsep, buffer)
#define TNT_TQRExist(tqrname) \
g_pTNTAPI->_TQRExist(tqrname)
#define TNTRewind(tqrname) \
g_pTNTAPI->_TQRRewind(tqrname)
#define TNTMoveFirst(tqrname) \
g_pTNTAPI->_TQRMoveFirst(tqrname)
#define TNTMoveNext(tqrname) \
g_pTNTAPI->_TQRMoveNext(tqrname)
#define TNTMoveLast(tqrname) \
g_pTNTAPI->_TQRMoveLast(tqrname)
#define TNTMoveTo(tqrname, irow) \
g_pTNTAPI->_TQRMoveTo(tqrname, irow)
#define TNTGetField(tqrname, colname) \
g_pTNTAPI->_TQRGetField(tqrname, colname)
#define TNTDelete(tqrname) \
g_pTNTAPI->_TQRDelete(tqrname)
#define TNTFilter(source, field, value, destination) \
g_pTNTAPI->_TQRFilter(source, field, value, destination)
#define TNTCount(tqrname) \
g_pTNTAPI->_TQRRecordCount(tqrname)
#define TNTConnectODBC(dsn, uid, pwd) \
g_pTNTAPI->_ODBCConnect((dsn), (uid), (pwd))
#define TNTExecuteODBC(tqrname, query, firstRec, recsToStore) \
g_pTNTAPI->_ODBCExecute((tqrname), (query), (firstRec), (recsToStore))
#define TNTGetCurrentConnection() \
g_pTNTAPI->_ODBCGetCurrentConnection()
#define TNTGetQueryStringVal(var_name, var_value, bufdim) \
g_pTNTAPI->_GetQueryStringVal((var_name), (var_value), (bufdim))
#define TNTPICKSTRING(inpustr, par_pos, retstr) \
g_pTNTAPI->_PICKSTRING((inpustr), (par_pos), (void*)(&retstr))
#endif /* _T_N_T_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxtime.cpp,v $
* $Revision: 1.6 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:31+02 $
*
* Implementation of the itxTime object (time_t format object)
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 roma italy
* <EMAIL>
*/
#ifndef __ITXTIME_CPP__
#define __ITXTIME_CPP__
#endif
#include <time.h>
#include <memory.h>
#include "itxtime.h"
//conversion from ("yyyymmdd", secs from midnight) to time_t
time_t itxTime::TimeConversion()
{
char buffer[10];
char* dateref = m_YyyyMmDd.GetBuffer();
int secs = m_SecsFromMid;
m_tm.tm_hour = secs / 3600;
m_tm.tm_min = (secs - m_tm.tm_hour * 3600) / 60;
m_tm.tm_sec = secs - m_tm.tm_hour * 3600 - m_tm.tm_min * 60;
memcpy(buffer, &dateref[0], 4);
buffer[4] = '\0';
m_tm.tm_year = atoi(buffer) - 1900;
memcpy(buffer, &dateref[4], 2);
buffer[2] = '\0';
m_tm.tm_mon = atoi(buffer) - 1;
memcpy(buffer, &dateref[6], 2);
buffer[2] = '\0';
m_tm.tm_mday = atoi(buffer);
m_tm.tm_wday = 0;
m_tm.tm_yday = 0;
m_tm.tm_isdst = -1;
m_t = mktime(&m_tm);
return m_t;
}
//conversion from time_t to ("yyyymmdd", secs from midnight)
void itxTime::SetFrom(time_t t)
{
char buffer[10];
m_tm = *localtime(&t);
m_t = t;
m_SecsFromMid = m_tm.tm_hour * 3600;
m_SecsFromMid += m_tm.tm_min * 60;
m_SecsFromMid += m_tm.tm_sec;
sprintf(buffer, "%d", 1900 + m_tm.tm_year);
m_YyyyMmDd = buffer;
sprintf(buffer, "%02d", 1 + m_tm.tm_mon);
m_YyyyMmDd += buffer;
sprintf(buffer, "%02d", m_tm.tm_mday);
m_YyyyMmDd += buffer;
}
void itxTime::SetFrom(int d, int m, int y)
{
char buffer[10];
sprintf(buffer, "%d", y);
m_YyyyMmDd = buffer;
sprintf(buffer, "%02d", m);
m_YyyyMmDd += buffer;
sprintf(buffer, "%02d", d);
m_YyyyMmDd += buffer;
}
int itxTime::SecFromMid(itxString* hour)
{
hour->Trim();
itxString l(*hour);
itxString r(*hour);
l.Left(2);
r.Right(2);
return atoi(l.GetBuffer()) * 3600 + atoi(r.GetBuffer()) * 60;
}
void itxTime::Tomorrow()
{
char buffer[10];
m_tm.tm_mday++;
m_t = mktime(&m_tm);
m_SecsFromMid = m_tm.tm_hour * 3600;
m_SecsFromMid += m_tm.tm_min * 60;
m_SecsFromMid += m_tm.tm_sec;
sprintf(buffer, "%d", 1900 + m_tm.tm_year);
m_YyyyMmDd = buffer;
sprintf(buffer, "%02d", 1 + m_tm.tm_mon);
m_YyyyMmDd += buffer;
sprintf(buffer, "%02d", m_tm.tm_mday);
m_YyyyMmDd += buffer;
}
void itxTime::Next(unsigned int hourinsecs)
{
if (hourinsecs <= m_SecsFromMid)
Tomorrow();
m_SecsFromMid = hourinsecs;
TimeConversion();
}
void itxTime::Now()
{
time(&m_t);
SetFrom(m_t);
}
void itxTime::Format(char* outputfmt)
{
m_outputfmt = outputfmt;
m_output.SetEmpty();
if (m_outputfmt.Compare("yyyymmdd") == 0)
m_output = m_YyyyMmDd;
if (m_outputfmt.Compare("dd/mm/yyyy") == 0)
{
char buffer[12];
sprintf(buffer, "%02d/", m_tm.tm_mday);
m_output += buffer;
sprintf(buffer, "%02d/", 1 + m_tm.tm_mon);
m_output += buffer;
sprintf(buffer, "%d", 1900 + m_tm.tm_year);
m_output += buffer;
}
if (m_outputfmt.Compare("mm/dd/yyyy") == 0)
{
char buffer[12];
sprintf(buffer, "%02d/", 1 + m_tm.tm_mon);
m_output += buffer;
sprintf(buffer, "%02d/", m_tm.tm_mday);
m_output += buffer;
sprintf(buffer, "%d", 1900 + m_tm.tm_year);
m_output += buffer;
}
if (m_outputfmt.Compare("dd/mm/yy") == 0)
{
char buffer[12];
sprintf(buffer, "%02d/", m_tm.tm_mday);
m_output += buffer;
sprintf(buffer, "%02d/", 1 + m_tm.tm_mon);
m_output += buffer;
sprintf(buffer, "%02d", (m_tm.tm_year < 100 ? m_tm.tm_year : m_tm.tm_year - 100));
m_output += buffer;
}
if (m_outputfmt.Compare("Dd/mm/yy") == 0)
{
char buffer[12];
switch (m_tm.tm_wday)
{
case 0: sprintf(buffer, "%s", "Dom"); break;
case 1: sprintf(buffer, "%s", "Lun"); break;
case 2: sprintf(buffer, "%s", "Mar"); break;
case 3: sprintf(buffer, "%s", "Mer"); break;
case 4: sprintf(buffer, "%s", "Gio"); break;
case 5: sprintf(buffer, "%s", "Ven"); break;
case 6: sprintf(buffer, "%s", "Sab"); break;
}
m_output += buffer;
sprintf(buffer, " %02d/", m_tm.tm_mday);
m_output += buffer;
sprintf(buffer, "%02d/", 1 + m_tm.tm_mon);
m_output += buffer;
sprintf(buffer, "%02d", (m_tm.tm_year < 100 ? m_tm.tm_year : m_tm.tm_year - 100));
m_output += buffer;
}
if (m_outputfmt.Compare("yymmdd:hhmm") == 0)
{
char buffer[12];
sprintf(buffer, "%02d", (m_tm.tm_year < 100 ? m_tm.tm_year : m_tm.tm_year - 100));
m_output += buffer;
sprintf(buffer, "%02d", 1 + m_tm.tm_mon);
m_output += buffer;
sprintf(buffer, "%02d", m_tm.tm_mday);
m_output += buffer;
sprintf(buffer, ":%02d", m_tm.tm_hour);
m_output += buffer;
sprintf(buffer, "%02d", m_tm.tm_min);
m_output += buffer;
}
}
<file_sep># Makefile for itxlib
# Copyright (C) 2000 aitecsa s.r.l.
CC=g++
CFLAGS=-O
CPPFLAGS=-DLINUX
LDFLAGS=-L. -lz
LDSHARED=$(CC)
VER=1.0
LIBS=libitx.a
SHAREDLIB=libitx.so
AR=ar rc
RANLIB=ranlib
TAR=tar
SHELL=/bin/bash
prefix = $HOME
exec_prefix = ${prefix}
libdir = ${exec_prefix}/lib
includedir = ${prefix}/include
OBJS = itxstring.o itxcoll.o itxsocket.o itxsmtp.o itxhttp.o itxbuffer.o \
itxfileini.o itxthread.o itxtime.o itxwin32.o itxlinux.o itxsql.o itxlib.o
TEST_OBJS = test.o
#all: test
#test: all
# @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
# if ./test; then \
# echo ' *** itxlib test OK ***'; \
# else \
# echo ' *** itxlib test FAILED ***'; \
# fi
libitx.a: $(OBJS)
$(AR) $@ $(OBJS)
-@ ($(RANLIB) $@ || true) >/dev/null 2>&1
$(SHAREDLIB).$(VER): $(OBJS)
$(LDSHARED) -o $@ $(OBJS)
rm -f $(SHAREDLIB) $(SHAREDLIB).1
ln -s $@ $(SHAREDLIB)
ln -s $@ $(SHAREDLIB).1
test: test.o $(LIBS)
$(CC) $(CFLAGS) -o $@ test.o $(LDFLAGS)
install: $(LIBS)
-@if [ ! -d $(includedir) ]; then mkdir $(includedir); fi
-@if [ ! -d $(libdir) ]; then mkdir $(libdir); fi
cp itxstring.h itxcoll.h itxlib.h $(includedir)
chmod 644 $(includedir)/itxlib.h $(includedir)/itxstring.h \
$(includedir)/itxcoll.h
cp $(LIBS) $(libdir)
cd $(libdir); chmod 755 $(LIBS)
-@(cd $(libdir); $(RANLIB) libitx.a || true) >/dev/null 2>&1
cd $(libdir); if test -f $(SHAREDLIB).$(VER); then \
rm -f $(SHAREDLIB) $(SHAREDLIB).1; \
ln -s $(SHAREDLIB).$(VER) $(SHAREDLIB); \
ln -s $(SHAREDLIB).$(VER) $(SHAREDLIB).1; \
(ldconfig || true) >/dev/null 2>&1; \
fi
# The ranlib in install is needed on NeXTSTEP which checks file times
# ldconfig is for Linux
uninstall:
cd $(includedir); \
v=$(VER); \
if test -f itxlib.h; then \
v=`sed -n '/VERSION "/s/.*"\(.*\)".*/\1/p' < itxlib.h`; \
rm -f itxlib.h itxcoll.h itxstring.h; \
fi; \
cd $(libdir); rm -f libitx.a; \
if test -f $(SHAREDLIB).$$v; then \
rm -f $(SHAREDLIB).$$v $(SHAREDLIB) $(SHAREDLIB).1; \
fi
clean:
rm -f *.o *~ test libitx.a libitx.so*
distclean: clean
depend:
makedepend -- $(CFLAGS) -- *.[ch]
# DO NOT DELETE THIS LINE -- make depend depends on it.
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxexception.h,v $
* $Revision: 1.2 $
* $Author: massimo $
* $Date: 2001-04-20 19:03:11+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef __ITX_EXCEPTION_H__
#define __ITX_EXCEPTION_H__
#include "itxstring.h"
#define ITXE_ERRLEN 20
#define ITXE_PROCLEN 128
class itxException : public exception
{
public:
int m_errornumber;
itxString m_procedure;
itxException(){m_procedure.SetEmpty();}
itxException(int errornumber, char* procedure)
{
m_errornumber = errornumber;
m_procedure = procedure;
}
};
#endif // __ITX_EXCEPTION_H__<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __IREGTP_H__
#define __IREGTP_H__
#include <memory.h>
#include "tptypes.h"
typedef struct NewTPAS400
{
unsigned short id;
char name[TPAS400_NAME_LEN];
short n_fields;
} NewTPAS400;
class itxTP
{
public:
NewTPAS400 m_tpas400[MAX_NUM_TPAS400];
int m_tpnumber;
itxTP()
{
memset(m_tpas400, '\0', MAX_NUM_TPAS400 * sizeof(NewTPAS400));
m_tpnumber = 0;
}
void Default();
bool Load(char* filename);
unsigned short GetTPID(char* name);
char* GetTPName(unsigned short id);
int GetTPNFields(char* name);
};
#endif //__IREGTP_H__<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __DEFINES_H__
#define __DEFINES_H__
//General purpose
#define MAINT_1 //check if must use dbg
#define TIMETRACE //check if must print timing stats
#define AITECSA_DISCLAIMER "<!--\n\
This file has been created from the Tannit� 4.0 Application owned, produced and distributed\n\
uniquely by AITECSA S.r.l. This copy of Tannit� 4.0 is intended to run only on machines owned\n\
by explicitly authorized users, owners of a run time license of Tannit� 4.0 product.\n\
Any other use is discouraged and will be persecuted in the terms established by the current laws.\n\
-->\n"
#ifdef _ITX_APPC
#define APPC_MSG "<!-- appc enabled -->\n"
#endif
#ifndef _ITX_APPC
#define APPC_MSG "<!-- appc disabled -->\n"
#endif
// Messaggi per la comunicazione con il client download/upload "Aleph"
#define FILE_UPLOADED 1
#define FILE_DOWNLOADED 2
#define DND_CONFIRMED 3
#define NO_FILE_AVAIL 4
#define LOGIN_SUCCESS 5
#define UNABLE_TO_UPLOAD 1002
#define SERVER_ERROR 1003
#define USER_NOT_ENABLED 1004
#define FATAL_ERROR 1999
#define ALEPH_START_COM "ITX_START_OF_TRASMISSIONS_GOOD_LUCK"
#define ALEPH_END_COM "ITX_END_OF_TRASMISSIONS_RETURNING_CODE"
// chiavi per l'invio e la ricezione di file
#define EXCNG_FILE_TAG "excng"
#define SEND_FILE_GRANT "92"
#define RECEIVE_APPC_FILE_GRANT "93"
#define DND_CONFIRM_GRANT "94"
#define RECEIVE_FILE_GRANT "95"
// Chiavi per la comunicazione con Baal: TntRequestTypes
#define RT_BROWSE 0
#define RT_PREPROC 1
#define RT_PREPROC_ALL 2
#define RT_PREVIEW 3
#define TPL_UPD_COMM_RECV "<html><body bgcolor=#44AAFF><font color=Blue><b>Tpl:"
#define TPL_UPD_COMM_SUCC "<br><Font size=1 color=red>E' il direttore che vi parla: sbaraccate ed andatevene in vacanza</Font></b></BODY></HTML>"
// Errori di interrogazione del database
#define ERR_MSG_LEN 256
#define NOT_VALIDATED 0
#define VALIDATED 1
#define ERRORS_EDGE 0 // limite superiore per i return che definiscono errori
#define DATA_VALUE_ON_ERROR "itxdbdatadefval"
// Identificatori di errori della struttura Message
#define ERR_COL_NOT_FOUND -68
#define ERR_QUERY_NOT_FOUND -67
#define ERR_VOID_QUERY_NAME -66
#define ERR_PARAM_NEEDED -51
#define LOGIN_ERROR 1001
// Errori di sintassi GASP
#define ERR_REM_BLINDCH "Errore:doppi apici mancanti"
#define ERR_OPEN_INI_FILE "Errore:file di inizializazione non trovato\n"
#define ERR_OPEN_TPL_FILE "Errore:template non trovato o template vuoto\n"
#define PARAMETER_NOT_FOUND "notfound"
#define FIELD_NAME_NOT_FOUND "Error: field name not found in get string"
#define UNABLE_TO_WRITE_VAR "<!-- unable to set var-->"
#define UNABLE_TO_READ_VAR "<!-- unable to get var-->"
#define INVALID_LOGIN_FILE "errlogin"
#define PARAM_NOT_FOUND_MSG "ERROR; parameter not found"
#define PAR_NOT_FOUND "paramfileNotFOund"
// Errori generici
#define CRYPTING_ERROR "Crypting Error"
#define MEMERR 23
#define MEMORY_ERROR_MSG "Memory allocation ERROR"
// Etichette
#define BROWSER_OPERA "Opera"
#define BROWSER_MSIE "MS Internet Explorer"
#define BROWSER_NETSCAPE "Netscape Comunicator"
#define ITX_MISINTER "itxmisi"
#define ISEXPLORER "explorer"
#define ISNETSCAPE "netscape"
#define LOGIN_TAG "login"
#define CPWD_TAG "cpwd"
#define BLINDER '"'
#define CONC_LAN_ID_TAG "lid"
#define DEF_PAR_FILE "tannit"
#define DEF_PAR_FILE_EXT "prm"
#define PAR_FILE_TAG "prm"
#define DEFAULT_TPL "tannit"
#define TGT_TAG "tgt"
#define TPL_TAG "tpl"
#define TPL_EXT ".htm"
#define START_COMMAND_TAG '*'
#define CMD_ARG_OPEN_TAG '('
#define CMD_ARG_CLOSE_TAG ')'
#define PARAM_NOT_FOUND 0
#define PARAM_FOUND 1
#define PARAM_NUMBER 128
#define CND_OP_NUM 6
#define GET_PAR_VAL ""
#define REC_VAL_ZERO ""
#define DND_FILE_DONE "2"
#define DND_FILE_READY "1"
#define ITX_UPLOAD_FILE_TAG "itxFile"
#define CORR_UPLOAD_DIR "./itxCrUp/"
#define ITXCOO_SEP "#"
#define TANNIT_TRUE "true"
#define TANNIT_FALSE "false"
#define TANNIT_COMMENT "//"
#define LINE_FEED 0xA
#define TQR_FOR_PREFIX "tqr_"
// Numerici
#define MAX_DSN 32
#define MAX_CRYPTING_BUFFER 256
#define BUFFER_SIZE 10000
#define LANG_ID_LEN 8
#define ID_FIELD_LEN 255
#define EXTRID_FIELD_LEN 256
#define TPL_VARS_NUM 64
#define CYC_NESTING_DEPTH 64
#define SELECTED_ADD_ON 32
#define LANID_LEN 4 /*lunghezza max dell'identificatore di linguaggio*/
#define INIT_FILE_LINE_LEN 512 /*lunghezza massima di una riga del file di inizializzazione*/
#define PAR_NAME_LEN 64 /*lunghezza massima del nome di un parametro nel file di inizializzazione*/
#define PAR_VALUE_LEN 256 /*lunghezza massima del valore di un parametro nel file di inizializzazione*/
#define INIT_FILE_NAME_LEN 256
#define HOME_DIR_LEN 64
#define IMG_DIR_LEN 64
#define SS_DIR_LEN 64
#define GET_VAR_LEN 128
#define TPL_LEN 250000
#define TPL_ABS_NAME_LEN 1024
#define MAX_TPL_NESTS 24
#define TPL_NAME_LEN 256
#define CMD_LEN 64
#define GET_PAR_VAL_LEN 4096
#define ITXCOO_TIME_DELAY 10000 // in secondi
#define PRM_TUNNEL_TAG "KOAN"
#define MAX_PRM_PARS 1000 //Max num di params in un prm
#define MAX_CMDS 1024
#define MAX_EXT_MODULES 50
// TQR Statistic
#define TOTRECS "TOTRECS"
#define ACTUALROW "ACTUALROW"
#define ROWSTOSTORE "ROWSTOSTORE"
#define STARTINGROW "STARTINGROW"
#define MORERECS "MORERECS"
#endif /* __DEFINES_H__ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : tntapiimpl.cpp
| TAB : 2 spaces
|
| DESCRIPTION : External modules interface: implementation file.
|
|
|
*/
#include "tannitobj.h"
#include "tntapiimpl.h"
#include "auxfile.h"
/////////////////////////// CONSTRUCTION - DESTRUCTION
TNTAPIImpl::TNTAPIImpl(void* tannit)
{
Tannit* ptannit = (Tannit*)tannit;
m_pParser = &ptannit->m_Parser;
m_pTQRManager = &ptannit->m_TQRManager;
m_pTQRODBCManager = &ptannit->m_TQRODBCManager;
m_pCGIResolver = (CGIResolver*)ptannit;
}
TNTAPIImpl::TNTAPIImpl()
{
}
TNTAPIImpl::~TNTAPIImpl()
{
}
//*************************** EXPORT METHODS ***************************
/////////////////////////// TNTPickInt
int TNTAPIImpl::_PickInt(char* inputstr, int par_pos, int* retval)
{
int ret = 0;
try
{
ret = m_pParser->PickInt(inputstr, par_pos, retval);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTPickInt(%p, %d, %p);'\n", inputstr, par_pos, retval);
}
return ret;
}
/////////////////////////// TNTPickDouble
int TNTAPIImpl::_PickDouble(char* inputstr, int par_pos, double* retval)
{
int ret = 0;
try
{
ret = m_pParser->PickDouble(inputstr, par_pos, retval);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTPickInt(%p, %d, %p);'\n", inputstr, par_pos, retval);
}
return ret;
}
/////////////////////////// TNTPickString
int TNTAPIImpl::_PickString(char* inputstr, int position, char* retval, int* bufdim)
{
int ret = 0;
try
{
ret = m_pParser->PickString(inputstr, position, retval, bufdim);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTPickString(%p, %d, %p, %p);'\n", inputstr, position, retval, bufdim);
}
return ret;
}
int TNTAPIImpl::_PICKSTRING(char* inputstr, int par_pos, void* retstr)
{
itxString* a = (itxString*) retstr;
if (m_pParser->PickPar(inputstr, par_pos, a) == PARAM_NOT_FOUND)
{
a->SetEmpty();
return 0;
}
return 1;
}
/////////////////////////// TNTPRMValue
int TNTAPIImpl::_GetPRMValue(char* param_name, char* param_value, int* bufdim)
{
int ret = 0;
try
{
if (m_pCGIResolver->m_PRMFile.GetPRMValue(param_name, param_value, bufdim))
ret = 1;
else
{
DebugTrace2(IN_WARNING, "TNTPRMValue failed: can't find '%s' variable.\n", param_name);
}
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTPRMValue(%s, %p, %p);'\n", param_name, param_value, bufdim);
}
return ret;
}
/////////////////////////// TNTCreateTQR
void* TNTAPIImpl::_TQRCreate(char* queryname, int numfields)
{
void* ret = 0;
try
{
ret = (void*) m_pTQRManager->CreateTQR(queryname, numfields);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTCreateTQR(%s, %d);'\n", queryname, numfields);
}
if (ret == NULL)
DebugTrace2(IN_WARNING, "TNTCreateTQR(%s, %d) failed.\n", queryname, numfields);
return ret;
}
/////////////////////////// TNTLoaddataBuffer
void TNTAPIImpl::_TQRLoadDataBuffer(char* tqrname, int tqrcols, char recsep, char fieldsep, char* buffer)
{
try
{
m_pTQRManager->LoadDataBuffer(tqrname, tqrcols, recsep, fieldsep, buffer);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTLoadDataBuffer(%s, %d, %c, %c, %s);'\n",
tqrname, tqrcols, recsep, fieldsep, buffer);
}
return;
}
/////////////////////////// TNTTQRExist
bool TNTAPIImpl::_TQRExist(char* tqrname)
{
int result = 0;
try
{
result = m_pTQRManager->Exist(tqrname);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNT_TQRExist(%s);'\n",
tqrname);
}
return result == TQR_NOT_EXIST ? false : true;
}
/////////////////////////// TNTRewind
void TNTAPIImpl::_TQRRewind(char* tqrname)
{
try
{
m_pTQRManager->MoveFirst(m_pTQRManager->Get(tqrname));
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTRewind(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTMoveFirst
void TNTAPIImpl::_TQRMoveFirst(char* tqrname)
{
try
{
m_pTQRManager->MoveFirst(m_pTQRManager->Get(tqrname));
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTMoveFirst(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTMoveNext
void TNTAPIImpl::_TQRMoveNext(char* tqrname)
{
try
{
m_pTQRManager->MoveNext(m_pTQRManager->Get(tqrname));
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTMoveNext(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTMoveLast
void TNTAPIImpl::_TQRMoveLast(char* tqrname)
{
try
{
m_pTQRManager->MoveLast(m_pTQRManager->Get(tqrname));
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTMoveLast(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTMoveTo
void TNTAPIImpl::_TQRMoveTo(char* tqrname, int irow)
{
try
{
m_pTQRManager->MoveTo(m_pTQRManager->Get(tqrname), irow);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTMoveTo(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTGetField
char* TNTAPIImpl::_TQRGetField(char* tqrname, char* colname)
{
char* field = NULL;
try
{
field = m_pTQRManager->GetCurrentRecordField(m_pTQRManager->Get(tqrname), colname);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTMoveTo(%s);'\n",
tqrname);
}
return field;
}
/////////////////////////// TNTDelete
void TNTAPIImpl::_TQRDelete(char* tqrname)
{
try
{
m_pTQRManager->Remove(tqrname);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTDelete(%s);'\n",
tqrname);
}
}
/////////////////////////// TNTFilter
void TNTAPIImpl::_TQRFilter(char* source, char* field, char* value, char* destination)
{
try
{
TQR* qres = m_pTQRManager->Filter(source, field, value, destination);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTFilter(%s, %s, %s, %s);'\n",
source, field, value, destination);
}
}
/////////////////////////// TNTCount
int TNTAPIImpl::_TQRRecordCount(char* tqrname)
{
try
{
return m_pTQRManager->GetRecordNumber(tqrname);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTCount(%s);'\n",
tqrname);
}
return -1;
}
/////////////////////////// TNTConnectODBC
void TNTAPIImpl::_ODBCConnect(char* dsn, char* uid, char* pwd)
{
try
{
m_pTQRODBCManager->Connect(dsn, uid, pwd);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTConnectODBC(%s, %s, %s);'\n", dsn, uid, pwd);
}
}
/////////////////////////// TNTExecuteODBC
int TNTAPIImpl::_ODBCExecute(char* tqrname, char* query, int firstRec, int recsToStore)
{
int ret = 0;
try
{
ret = m_pTQRODBCManager->Execute(tqrname, query, firstRec, recsToStore);
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTExecuteODBC(%s, %s, %d, %d);'\n", tqrname, query, firstRec, recsToStore);
}
return ret;
}
/////////////////////////// TNTGetCurrentConnection
void* TNTAPIImpl::_ODBCGetCurrentConnection()
{
try
{
return (void*)m_pTQRODBCManager->GetConnection();
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTGetCurrentConnection();'\n");
}
return NULL;
}
/////////////////////////// TNTGetQueryStringVal
int TNTAPIImpl::_GetQueryStringVal(char* var_name, char* var_value, int* bufdim)
{
int ret = 0;
int needed;
try
{
if (m_pCGIResolver->cgiFormStringSpaceNeeded(var_name, &needed) == cgiFormSuccess)
{
if (var_value == NULL)
{
ret = 1;
*bufdim = needed;
}
else if (*bufdim >= needed)
{
if (m_pCGIResolver->cgiFormString(var_name, var_value, 0) == cgiFormSuccess)
ret = 1;
else
DebugTrace2(IN_WARNING, "TNTGetQueryStringVal failed: supplied buffer too small.\n");
}
}
else
DebugTrace2(IN_WARNING, "TNTGetQueryStringVal failed: can't find requested variable.\n");
}
catch(...)
{
DebugTrace2(IN_TNTAPI, "TNTAPI EXCEPTION - actual call is 'TNTGetQueryStringVal(%s, %p, %p);'\n", var_name, var_value, bufdim);
}
return ret;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __TNTSQL_H__
#define __TNTSQL_H__
#include <stdio.h>
#ifndef WIN32
typedef void* HWND;
#else
#include <windows.h>
#endif
#include <sqltypes.h>
// SQL INTERFACE CONSTANTS
#define ITX_QRS_MAX_NAME_LEN 63
#define ITX_QRS_MAX_FIELD_LEN 8191
#define ITX_QRS_MAX_QUERY_LEN 32767
//
#define ITX_SQL_DSN_LENGTH 32
#define ITX_SQL_UID_LENGTH 16
#define ITX_SQL_PWD_LENGTH 16
#define ITX_SQL_MAX_ERRMSG 512
#define ITX_SQL_STATUS_LEN 6
class itxSQLConnection
{
public:
HENV m_henv;
HDBC m_hdbc;
SQLHANDLE m_hstmt;
char m_dsn[ITX_SQL_DSN_LENGTH];
char m_uid[ITX_SQL_UID_LENGTH];
char* m_statement;
SQLINTEGER m_ind;
short int m_cols;
short int m_rows;
private:
char m_pwd[ITX_SQL_PWD_LENGTH];
public:
// Error parameters
SQLCHAR m_sqlstate[ITX_SQL_STATUS_LEN];
SQLINTEGER m_nativerr;
SQLCHAR m_message[ITX_SQL_MAX_ERRMSG];
SQLSMALLINT m_msglength;
public:
itxSQLConnection();
~itxSQLConnection() { };
bool IsConnected() { return m_henv == NULL ? FALSE : TRUE; };
bool Create(char* dsn, char* uid, char* pwd);
bool SetAttributes(int attr, void* value, int valuelen);
bool Destroy();
bool Execute(char* statement);
bool GetColInfo(short int col, char* name, short* type, long int* size);
bool SkipRecords(int start, int end);
bool BindCol(int col, char* value, int size);
bool Fetch();
bool FreeStmt();
bool MoreResults();
void Error(FILE* log);
bool GetColsNumber();
bool ManualCommit();
bool AutoCommit();
bool Commit();
bool Rollback();
};
#endif //__TNTSQL_H__
<file_sep>/*
* Simulation for approx curve of Mu_p in the case of site percolation
* in two dimension (finite percolation on a disk).
*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
#define MAX_DIST 10 // max disk radius
#define OCCUPIED '+' // site is occupied
#define VACANT '-' // site is vacant
#define SEEN '*' // site has been visited
#define UNUSED '.' // site has not been initialized (used)
#define CLOCKS_PER_MILLI CLOCKS_PER_SEC/1000
char m_Status[MAX_DIST*2 + 1][MAX_DIST*2 + 1];
char m_Dist[MAX_DIST*2 + 1][MAX_DIST*2 + 1];
double m_P = 0.0;
int m_CurDist = 5; // radius of disk (defaults to 5)
//-----------------------------------------------------------
void create_config(double p)
{
memset(m_Status, UNUSED, sizeof(m_Status));
for (int i=0; i<(MAX_DIST*2 + 1); i++)
for (int j=0; j<(MAX_DIST*2 + 1); j++)
if (m_Dist[i][j] <= m_CurDist)
m_Status[i][j] = (((double)rand()/(RAND_MAX + 1)) < p) ? OCCUPIED : VACANT;
}
//-----------------------------------------------------------
void print_config()
{
for (int i=0; i<(MAX_DIST*2 + 1); i++) {
for (int j=0; j<(MAX_DIST*2 + 1); j++)
if (m_Dist[i][j] <= m_CurDist)
printf("%2c", m_Status[i][j]);
else
printf("%2c", ' ');
printf("\n");
}
printf("\n");
}
//-----------------------------------------------------------
int config_level()
{
int ret = 0;
for (int i=0; i<(MAX_DIST*2 + 1); i++)
for (int j=0; j<(MAX_DIST*2 + 1); j++)
if (m_Dist[i][j] <= m_CurDist && m_Status[i][j] == OCCUPIED)
ret++;
return ret;
}
//-----------------------------------------------------------
void assign_distances()
{
int i, j;
for (i=0; i<MAX_DIST; i++) {
for (j=0; j<MAX_DIST; j++)
m_Dist[i][j] = MAX_DIST*2 - i - j;
for (j=MAX_DIST; j<=MAX_DIST*2; j++)
m_Dist[i][j] = j - i;
}
for (i=MAX_DIST; i<=MAX_DIST*2; i++) {
for (j=0; j<MAX_DIST; j++)
m_Dist[i][j] = i - j;
for (j=MAX_DIST; j<=MAX_DIST*2; j++)
m_Dist[i][j] = i - MAX_DIST*2 + j;
}
}
//-----------------------------------------------------------
void print_distance_schema()
{
for (int i=0; i<(MAX_DIST*2 + 1); i++) {
for (int j=0; j<(MAX_DIST*2 + 1); j++)
if (m_Dist[i][j] <= MAX_DIST)
printf("%2d", m_Dist[i][j]);
else
printf("%2c", ' ');
printf("\n");
}
printf("\n");
}
//-----------------------------------------------------------
char percolation_with_auto_build_path(int x, int y)
{
if (m_Status[x][y] == UNUSED)
m_Status[x][y] = (((double)rand()/(RAND_MAX + 1)) < m_P) ? OCCUPIED : VACANT;
if (m_Status[x][y] == OCCUPIED) {
if (m_Dist[x][y] == m_CurDist) {
// m_Status[x][y] = SEEN; //only for 'visual' debug
return 1;
}
m_Status[x][y] = SEEN;
if (percolation_with_auto_build_path(x + 1, y )) return 1;
if (percolation_with_auto_build_path(x - 1, y )) return 1;
if (percolation_with_auto_build_path(x , y - 1)) return 1;
if (percolation_with_auto_build_path(x , y + 1)) return 1;
}
return 0;
}
//-----------------------------------------------------------
char percolation_on_existing_config(int x, int y)
{
if (m_Status[x][y] == OCCUPIED) {
if (m_Dist[x][y] == m_CurDist)
return 1;
m_Status[x][y] = SEEN;
if (percolation_on_existing_config(x + 1, y )) return 1;
if (percolation_on_existing_config(x - 1, y )) return 1;
if (percolation_on_existing_config(x , y - 1)) return 1;
if (percolation_on_existing_config(x , y + 1)) return 1;
}
return 0;
}
//-----------------------------------------------------------
// Approx curve for mu-p probability of percolation on Z2 disk
//-----------------------------------------------------------
void mup_on_disk(int from_dist, int to_dist, int x_points, int confs_per_point)
{
long beg;
long end;
long success = 0;
double inc = 1/(double)x_points;
FILE* fp = NULL;
char fname[256];
if (from_dist <= 0 || to_dist > MAX_DIST) {
printf("Bad range parameters in mup_on_disk\n");
return;
}
srand(time(NULL));
assign_distances();
beg = clock()*CLOCKS_PER_MILLI;
for (m_CurDist = from_dist; m_CurDist<=to_dist; m_CurDist++) {
sprintf(fname, "disk_z2_dist%03d.dat", m_CurDist);
if ((fp = fopen(fname, "wt")) == NULL)
{
printf("Unable to open output file\n");
return;
}
printf("Examinating disk %d\n", m_CurDist);
fprintf(fp, "# Percolation on a finite disk in Z2 of radius %d\n", m_CurDist);
m_P = 0.0;
for (int points = 0; points<x_points; points++) {
m_P += inc;
success = 0;
for (int i=0; i<confs_per_point; i++) {
memset(m_Status, UNUSED, sizeof(m_Status));
success += percolation_with_auto_build_path(MAX_DIST, MAX_DIST);
}
fprintf(fp, "%f %f\n", m_P, success/(double)confs_per_point);
printf("p = %f percolation frequency = %f\n", m_P, success/(double)confs_per_point);
}
fprintf(fp, "\n\n");
fclose(fp);
}
end = clock()*CLOCKS_PER_MILLI;
printf("Done in %d seconds\n", (end - beg)/1000);
}
//-----------------------------------------------------------
// Approx curve for the number of pivotal sites
//-----------------------------------------------------------
void pivotal_sites(int from_dist, int to_dist, int x_points, int confs_per_point)
{
int beg;
int end;
int success = 0;
int pivotals = 0;
int level = 0;
double pivotals_fraction = 0.0;
double inc = 1/(double)x_points;
FILE* fp = NULL;
char fname[256];
char config[MAX_DIST*2 + 1][MAX_DIST*2 + 1];
if (from_dist <= 0 || to_dist > MAX_DIST) {
printf("Bad range parameters in mup_on_disk\n");
return;
}
srand(time(NULL));
assign_distances();
beg = clock()*CLOCKS_PER_MILLI;
for (m_CurDist = from_dist; m_CurDist<=to_dist; m_CurDist++) {
sprintf(fname, "disk_z2_pivot_dist%03d.dat", m_CurDist);
if ((fp = fopen(fname, "wt")) == NULL) {
printf("Unable to open output file\n");
return;
}
printf("Examinating pivotal sites %d\n", m_CurDist);
fprintf(fp, "# Pivotal sites on a finite disk in Z2 of radius %d\n", m_CurDist);
m_P = 0.0;
for (int points = 0; points<x_points; points++) {
m_P += inc;
success = 0;
pivotals_fraction = 0.0;
for (int conf=0; conf<confs_per_point; conf++) {
create_config(m_P);
memcpy(config, m_Status, sizeof(m_Status));
//Is there percolation?
if (percolation_on_existing_config(MAX_DIST, MAX_DIST) == 1) {
pivotals = 0;
memcpy(m_Status, config, sizeof(m_Status));
level = config_level();
//Count pivotal sites by checking on config one by one
for (int i=0; i<(MAX_DIST*2 + 1); i++)
for (int j=0; j<(MAX_DIST*2 + 1); j++)
if (m_Dist[i][j] <= m_CurDist && m_Status[i][j] == OCCUPIED) {
m_Status[i][j] = VACANT;
if (percolation_on_existing_config(MAX_DIST, MAX_DIST) == 0)
pivotals++;
memcpy(m_Status, config, sizeof(m_Status));
}
pivotals_fraction += pivotals / (double)level;
}
}
if (pivotals_fraction > 0)
fprintf(fp, "%f %f\n", m_P, pivotals_fraction/confs_per_point);
printf("%f %f\n", m_P, pivotals_fraction/confs_per_point);
}
fprintf(fp, "\n\n");
fclose(fp);
}
end = clock()*CLOCKS_PER_MILLI;
printf("Done in %d seconds\n", (end - beg)/1000);
}
int main(int argc, char* argv[])
{
// mup_on_disk(100, 100, 100, 300000);
pivotal_sites(10, 10, 100, 10000);
return 0;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxwin32.cpp,v $
* $Revision: 1.4 $
* $Author: administrator $
* $Date: 2002-07-23 16:05:31+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifdef WIN32
//This file implements the itxSystem class for (maybe) all WIN32 subsystems
#pragma message("=== itxSystem object is implemented for WIN32 platforms ===\n")
#include "itxsystem.h"
#include "itxstring.h"
//**************************************************************
int itxSystem::BSGetLastError()
{
return ::GetLastError();
}
//**************************************************************
int itxSystem::PRGetProcessId()
{
return ::GetCurrentProcessId();
}
//**************************************************************
int itxSystem::DLGetLastError()
{
return ::GetLastError();
}
//**************************************************************
//* Returns current time_t and millisecs fraction.
void itxSystem::TMGetMilliTime(time_t* now, int* milli)
{
struct _timeb timebuffer;
_ftime(&timebuffer);
if (now != NULL)
*now = timebuffer.time;
if (milli != NULL)
*milli = timebuffer.millitm;
}
//**************************************************************
void itxSystem::FSSetMode(FILE* fp, int mode)
{
_setmode(_fileno(fp), mode);
}
//**************************************************************
void* itxSystem::DLLoadLibrary(char* fmodule)
{
return (fmodule!= NULL ? ::LoadLibrary(fmodule) : NULL);
}
//**************************************************************
bool itxSystem::DLFreeLibrary(void* pmodule)
{
return (::FreeLibrary((HINSTANCE)pmodule) ? true : false);
}
//**************************************************************
void* itxSystem::DLGetFunction(void* pmodule, char* pfuncname)
{
return ::GetProcAddress((HINSTANCE)pmodule, (LPCSTR)pfuncname);
}
//**************************************************************
void itxSystem::PRGetModuleName(void* pmodule, char* pfilename, int bufsize)
{
::GetModuleFileName((HINSTANCE)pmodule, pfilename, bufsize);
}
//**************************************************************
void itxSystem::FSGetCurrentDirectory(char* pfilename, int bufsize)
{
::GetCurrentDirectory(bufsize, pfilename);
}
//**************************************************************
bool itxSystem::FSFileIsReadOnly(char* pfilename)
{
return ((::GetFileAttributes(pfilename) & FILE_ATTRIBUTE_READONLY) ? true : false);
}
//**************************************************************
int itxSystem::BSSetenv(char* varname, char* varval)
{
itxString appo;
appo = varname;
appo += "=";
appo += varval;
return _putenv(appo.GetBuffer());
}
//**************************************************************
void itxSystem::FSDirToTokenString(char* dir, char* filter, char token, itxString* retlist)
{
if (dir == NULL || filter == NULL || retlist == NULL)
return;
if (*dir == 0 || *filter == 0)
return;
itxString auxpath;
itxString pattern;
WIN32_FIND_DATA ffdata;
HANDLE hff;
bool goon;
auxpath = dir;
if (dir[strlen(dir) - 1] != PATH_SEPARATOR_C)
auxpath += PATH_SEPARATOR_C;
pattern = auxpath;
pattern += filter;
hff = ::FindFirstFile(pattern.GetBuffer(), &ffdata);
if (hff != INVALID_HANDLE_VALUE)
{
goon = true;
while (goon)
{
if (strcmp(ffdata.cFileName, ".") != 0 && strcmp(ffdata.cFileName, "..") != 0)
{
*retlist += auxpath;
*retlist += ffdata.cFileName;
*retlist += token;
}
goon = (::FindNextFile(hff, &ffdata) != 0);
}
}
}
//**************************************************************
void* itxSystem::THCreateThread(void* threadproc, void* threadarg, unsigned int* pretid)
{
DWORD retid = 0;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
void* rethandle = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadproc, threadarg, 0, &retid);
if (rethandle != NULL && pretid != NULL)
*pretid = retid;
else
pretid = NULL;
return rethandle;
}
//**************************************************************
void itxSystem::THPauseThread(void* thread)
{
::SuspendThread(thread);
}
//**************************************************************
void itxSystem::THResumeThread(void* thread)
{
::ResumeThread(thread);
}
//**************************************************************
void itxSystem::THTerminateThread(void* thread)
{
::TerminateThread(thread, -1);
}
//**************************************************************
int itxSystem::SOGetLastError(int socket)
{
//socket param unused under win32
return ::WSAGetLastError();
}
//**************************************************************
bool itxSystem::SOInitLibrary()
{
WORD wVersionRequested = MAKEWORD(1,1);
WSADATA wsaData;
if (::WSAStartup(wVersionRequested, &wsaData) == SOCKET_ERROR)
{
::WSACleanup();
return false;
}
return true;
}
//**************************************************************
bool itxSystem::SOCloseLibrary()
{
::WSACleanup();
return true;
}
//**************************************************************
void itxSystem::SOInitDescriptors(void* fdstruct, int socket)
{
if (fdstruct != NULL)
{
((fd_set*)fdstruct)->fd_array[0] = socket;
((fd_set*)fdstruct)->fd_count = 1;
}
}
//**************************************************************
void itxSystem::SOClose(int socket)
{
closesocket(socket);
}
#endif //WIN32
<file_sep>/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : tannitobj.cpp
| TAB : 2 spaces
|
| DESCRIPTION : main implementation file.
|
|
*/
#include <time.h>
#include <stdlib.h>
#include "tannitobj.h"
#include "templatefile.h"
#include "commands.h"
#include "itxtypes.h"
#include "itxlib.h"
#ifdef FCGITANNIT
#include "fcgi_config.h"
#include "fcgi_stdio.h"
#else
#pragma message("=== Fast CGI support disabled ===")
#pragma message("Link the C run-time as (Debug) Multithreaded DLL and the following libraries:\n"\
" odbc32.lib itxlib.lib winmm.lib ws2_32.lib.\nGood luck.") //Release message
#include <stdio.h>
#endif //FCGITANNIT
// This typedef is needed to call the one and only one
// function exported by user which connects any
// external module to this instance of Tannit.
typedef int (ITXCDECL* TANNIT_HANDSHAKE)(AbstractCommand**, TNTAPI*);
Tannit::Tannit()
{
m_ResponseMIMEtype.SetEmpty();
m_pTNTAPIImpl = NULL;
m_NExtModules = 0;
for (int i=0; i<MAX_EXT_MODULES; i++)
m_ExtModHandle[i] = NULL;
m_TQRManager.SetTQRCollection(&m_TQRCollection);
m_TQRODBCManager.SetTQRCollection(&m_TQRCollection);
}
//-----------------------------------------------------------------
Tannit::~Tannit()
{
for (int i=0; i<MAX_EXT_MODULES; i++)
if (m_ExtModHandle[i] != NULL)
m_Sys.DLFreeLibrary(m_ExtModHandle[i]);
delete m_pTNTAPIImpl;
}
//-----------------------------------------------------------------
bool Tannit::InitCurrentPRM()
{
itxString initFileName; //nome del file di inizializzazione
itxString initFileExt; //nome del file di inizializzazione con l'estensione
itxString lanId;
try
{
if (m_PRMConf.Clone(&m_PRMFile) == false)
return false;
// il nome del file di inizializzazione viene ricavato dal valore di get PAR_FILE_TAG
if (cgiFormString(PAR_FILE_TAG, &initFileExt, GET_VAR_LEN) == cgiFormSuccess)
{
initFileExt += ".";
initFileExt += DEF_PAR_FILE_EXT;
m_PRMFile.MergePRM(&initFileExt);
}
// Estrazione dalla stringa di get del valore del parametro opzionale
// CONC_LAN_ID_TAG (concatenated language id)
lanId.SetEmpty();
cgiFormString(CONC_LAN_ID_TAG, &lanId, LANID_LEN);
m_PRMFile.SetLanguageId(lanId.GetBuffer());
m_PRMFile.SetPRMFileName(initFileExt.GetBuffer());
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception in Tannit::InitCurrentPRM.");
return false;
}
return true;
}
//-----------------------------------------------------------------
bool Tannit::Initialize()
{
// Set prm and conf files auxiliary directory to the one containing
// the Tannit executable. For a IIS WebServer it allows the user to
// place the inizialization files in the cgi-bin directory.
// The auxiliary directory is the place where to search for the
// prm and conf file when not found in the default tannit working
// directory.
char buf[1024];
m_Sys.PRGetModuleName(NULL, buf, 1024);
char* pLastSlash = strrchr(buf, PATH_SEPARATOR_C);
if (pLastSlash)
{
*pLastSlash = 0;
m_PRMConf.SetAuxiliaryDirectory(buf);
m_PRMFile.SetAuxiliaryDirectory(buf);
}
//Reads the web server variables from the environment table
GetEnvironment(false);
// read configuration file: Tannit.conf
if (!m_PRMConf.ReadPRM())
{
DebugTrace2(IN_WARNING, "Tannit configuration file not found.");
return false;
}
// if required here we start the ODBC connection and hook the
// TQRODBCManager to it
//InitODBC(&m_PRMConf); OBSOLETE
// load external and core commands
m_Parser.CreateBaseCommands(this);
LoadModules(m_PRMConf);
return true;
}
//-----------------------------------------------------------------
bool Tannit::InitODBC(PRMFile* prmfile)
{
bool retval = false;
if (m_odbcconnection.IsConnected())
return true;
prmfile->GetPRMValue("odbcdsn", &(m_odbcconnection.m_dsn));
if (!m_odbcconnection.m_dsn.IsEmpty())
{
prmfile->GetPRMValue("odbcuid", &(m_odbcconnection.m_usr));
prmfile->GetPRMValue("odbcpwd", &(m_odbcconnection.m_pwd));
if (m_odbcconnection.Create())
{
m_connections.Put(&m_odbcconnection);
DebugTrace2(DEFAULT, "Connection successfully created.");
m_TQRODBCManager.SetConnect(&m_odbcconnection);
retval = true;
}
else
SQLTrace(&m_odbcconnection);
}
return retval;
}
//-----------------------------------------------------------------
void Tannit::InquiryCurWorkingDir(itxString* ret)
{
if (ret == NULL)
return;
char buf[1024];
m_Sys.FSGetCurrentDirectory(buf, 1024);
*ret = buf;
}
//-----------------------------------------------------------------
bool Tannit::InquiryDebugFile()
{
if (g_DebugFile.m_DebugPath.Len() == 0)
return false;
FILE* fp;
if ((fp = fopen(g_DebugFile.m_DebugPath.GetBuffer(), "w")) == NULL)
return false;
else
{
fclose(fp);
remove(g_DebugFile.m_DebugPath.GetBuffer());
}
return true;
}
//-----------------------------------------------------------------
void Tannit::InquiryConfigFiles(itxString* ret)
{
if (ret == NULL)
return;
// MakeConfigurationFileList("", "*.conf", ret);
// MakeConfigurationFileList("", "*.prm", ret);
MakeConfigurationFileList(m_PRMConf.GetAuxiliaryDirectory(), "*.conf", ret);
MakeConfigurationFileList(m_PRMFile.GetAuxiliaryDirectory(), "*.prm", ret);
}
//-----------------------------------------------------------------
void Tannit::InquiryConnections(itxString prmlist, itxString* ret)
{
if (ret == NULL)
return;
int i = 0;
PRMFile prmf;
itxString prmfile;
itxString appo;
prmlist.GetToken(INQ_TOK_SEP, i++, &prmfile);
while (prmfile.Len() > 0)
{
prmf.SetPRMFileName(prmfile.GetBuffer());
prmf.ClearNamesAndValues();
prmf.ReadPRM();
prmf.GetPRMValue("odbcdsn", &(m_odbcconnection.m_dsn));
if (!m_odbcconnection.m_dsn.IsEmpty())
{
*ret += m_odbcconnection.m_dsn;
*ret += INQ_TOK_SEP;
prmf.GetPRMFileName(&appo);
*ret += appo;
*ret += INQ_TOK_SEP;
prmf.GetPRMValue("odbcuid", &(m_odbcconnection.m_usr));
prmf.GetPRMValue("odbcpwd", &(m_odbcconnection.m_pwd));
if (m_odbcconnection.Create())
{
*ret += INQ_CONN_OK;
m_odbcconnection.Destroy();
}
else
*ret += INQ_CONN_NOK;
*ret += INQ_TOK_SEP;
}
prmlist.GetToken(INQ_TOK_SEP, i++, &prmfile);
}
}
//-----------------------------------------------------------------
void Tannit::MakeConfigurationFileList(itxString auxdir, char* filter, itxString* conflist)
{
itxString auxpath;
if (filter == NULL || conflist == NULL)
return;
m_Sys.FSDirToTokenString(auxdir.GetBuffer(), filter, INQ_TOK_SEP, conflist);
}
//-----------------------------------------------------------------
void Tannit::Inquiry()
{
fprintf(cgiOut, "<HTML><HEAD>\n"
"<TITLE>Tannit� diagnostic information panel</TITLE>\n");
fprintf(cgiOut, "<style> \n"
".item_name \n"
"{ \n"
" color: black; \n"
" background: #AABBCC; \n"
" font-family : Verdana; \n"
" font-size: 15px; \n"
"} \n"
".item_val \n"
"{ \n"
" color: black; \n"
" background: #ABCABC; \n"
" font-family : Verdana; \n"
" font-size: 13px; \n"
"} \n"
".odbc_header \n"
"{ \n"
" color: black; \n"
" background: #FFFFFF; \n"
" font-family : Verdana; \n"
" font-size: 11px; \n"
"} \n"
".odbc_dsn \n"
"{ \n"
" color: black; \n"
" font-family : Verdana; \n"
" font-size: 13px; \n"
"} \n");
fprintf(cgiOut, ".odbc_test_ok \n"
"{ \n"
" color: green; \n"
" font-family : Verdana; \n"
" font-size: 13px; \n"
"} \n"
".odbc_test_nok \n"
"{ \n"
" color: red; \n"
" font-family : Verdana; \n"
" font-size: 13px; \n"
"} \n"
"A \n"
"{ \n"
" text-decoration: none; \n"
" font-family: verdana; \n"
" font-size: 13pt \n"
"} \n"
"</style> \n");
fprintf(cgiOut, "</HEAD>\n"
"<BODY bgcolor=#FFFFFF>\n");
//If tannit executable is a read-only file, no inquiry is possible
char buf[1024];
m_Sys.PRGetModuleName(NULL, buf, 1024);
if (m_Sys.FSFileIsReadOnly(buf))
{
fprintf(cgiOut, "<CENTER><FONT FACE=Verdana SIZE = 10>Tannit is alive and kicking.</FONT></CENTER>\n"
"<CENTER><A HREF=http://www.aitecsa.it><FONT FACE=Verdana SIZE = 3>www.aitecsa.it</FONT></A></CENTER>\n");
}
else
{
fprintf(cgiOut, "<CENTER><FONT FACE=Arial SIZE = 5>Tannit� diagnostic information panel</FONT></CENTER><P></P>\n"
"<FONT FACE=Verdana SIZE=3>\n"
"<TABLE bgcolor=#999999 width=100%% cellspacing=3 cellpadding=5>\n");
char* tablerow = "<TR>\n"
" <TD class=item_name>%s</TD>\n"
" <TD class=item_val>%s</TD>\n"
"</TR>\n";
//Inquiry on current working directory
itxString curdir;
InquiryCurWorkingDir(&curdir);
curdir.Trim();
fprintf(cgiOut, tablerow, "current working directory", curdir.GetBuffer());
//Inquiry on debug file //TBD aggiungere tentativo scrittura file di debug
if (InquiryDebugFile() == false)
fprintf(cgiOut, tablerow, "Debug file",
"NOT GENERATED<BR>"
"Possible causes:<BR>"
".) the file 'dbgname.par' was not found in the current working directory;<BR>"
".) the parameter inside this file has not been assigned;<BR>"
".) the parameter inside this file has been assigned with an incorrect value;<BR>"
".) for some reason, it's not allowed to write in the specified directory.");
else
{
itxString appo;
appo = curdir;
if (curdir.Right(1).Compare(PATH_SEPARATOR) != 0)
appo += PATH_SEPARATOR;
appo += g_DebugFile.m_DebugPath.GetBuffer();
fprintf(cgiOut, tablerow, "Debug file", appo.GetBuffer());
}
//Inquiry on configuration files
itxString prmlist;
itxString out;
InquiryConfigFiles(&prmlist);
out = prmlist;
char sep[2] = {INQ_TOK_SEP, 0};
out.SubstituteSubString(sep, "<BR>");
fprintf(cgiOut, tablerow, "Configuration files", out.GetBuffer());
//Inquiry on database connections
itxString conntest;
InquiryConnections(prmlist, &conntest);
out.SetEmpty();
out = "<table width=100%>\n"
"<tr>\n"
" <td class=odbc_header>DSN</td>\n"
" <td class=odbc_header>found on</td>\n"
" <td class=odbc_header>test</td>\n"
"</tr>\n";
int i = 0;
itxString tok;
conntest.GetToken(INQ_TOK_SEP, i++, &tok); //take dsn
while (tok.Len() > 0)
{
out += "<tr>\n"
" <td class=odbc_dsn>\n";
out += tok; //dsn name
out += "\n"
"</td>\n"
"<td class=item_val>\n";
tok.SetEmpty();
conntest.GetToken(INQ_TOK_SEP, i++, &tok); //take prm
out += tok; //prm/conf file
out += "\n"
"</td>\n";
tok.SetEmpty();
conntest.GetToken(INQ_TOK_SEP, i++, &tok); //take test
if (tok.Compare(INQ_CONN_OK) == 0)
out += "<td class=odbc_test_ok>\n"
" OK\n";
else
out += "<td class=odbc_test_nok>\n"
" NOT OK\n";
out += " </td>\n"
"</tr>\n";
tok.SetEmpty();
conntest.GetToken(INQ_TOK_SEP, i++, &tok); //take next dsn
}
out += "</table>\n";
fprintf(cgiOut, tablerow, "ODBC connections", out.GetBuffer());
//Inquiry Extension Module DLLs successfully loaded
out.SetEmpty();
char modulefile[1024];
for (int dll=0; dll<m_NExtModules; dll++)
{
m_Sys.PRGetModuleName(m_ExtModHandle[dll], modulefile, 1024);
out += modulefile;
out += "<br>";
}
fprintf(cgiOut, tablerow, "Extension modules<br>successfully loaded", out.GetBuffer());
//Close table
fprintf(cgiOut, "</TABLE>\n");
fprintf(cgiOut, "</FONT>\n");
}
fprintf(cgiOut, "</BODY></HTML>\n");
}
//-----------------------------------------------------------------
void Tannit::SendResponseMimeType(char* mimetype)
{
if (mimetype == NULL)
{
// Check if the client requests a specific MIME Content Type and send it
if (!m_PRMFile.GetPRMValue(MIME_TAG, &m_ResponseMIMEtype))
{
if (cgiFormString(MIME_TAG, &m_ResponseMIMEtype, TPL_NAME_LEN) != cgiFormSuccess)
m_ResponseMIMEtype= DEFAULT_MIME_TYPE;
}
}
else
m_ResponseMIMEtype = mimetype;
fprintf(cgiOut, "Content-type: %s\r\n\r\n", m_ResponseMIMEtype.GetBuffer());
}
//-----------------------------------------------------------------
RunType_e Tannit::ManageContext(itxString* tplName, itxString* tpldir, itxString* preproc_outtpl, itxString* preproc_outdir)
{
itxString prmPPkey;
itxString prmPVkey;
itxString getPPkey;
itxString inquiryTag;
bool keyfound = false;
RunType_e runtype = Normalrun;
//Send appropriate response MIME type
SendResponseMimeType();
//If the case, put the disclaimer before anything...
if(m_ResponseMIMEtype.CompareNoCase(DEFAULT_MIME_TYPE))
fprintf(cgiOut, "%s", AITECSA_DISCLAIMER);
//Diagnostic run?
if (cgiFormString(INQUIRY_TAG, &inquiryTag, TPL_NAME_LEN) == cgiFormSuccess)
return Diagnostic;
tplName->SetEmpty();
keyfound = m_PRMFile.GetPRMValue("ppkey", &prmPPkey);
keyfound = (m_PRMFile.GetPRMValue("pvkey", &prmPVkey) || keyfound);
//Gets preprocessing key from param file
if(keyfound)
{
// preprocessing key found in get string
if (cgiFormString("ppkey", &getPPkey, TPL_NAME_LEN) == cgiFormSuccess)
{
// set source template name and directory
m_PRMFile.GetPRMValue(TPLDIR, tpldir);
if (cgiFormString(PREPROC_TPL_TAG, tplName, TPL_NAME_LEN) != cgiFormSuccess)
return Forbiddenrun;
if(getPPkey.Compare(prmPPkey.GetBuffer()) == 0)
{
// set output file name
if (cgiFormString(TPL_TAG, preproc_outtpl, TPL_NAME_LEN) != cgiFormSuccess)
return Forbiddenrun;
Flush(WWW_PP_STARTED);
Flush(tplName->GetBuffer());
// set output file directory
// if input and output directory are the same the execution is blocked
runtype = Preprocrun;
m_PRMFile.GetPRMValue(PREPROC_DIR_PRM_NAME, preproc_outdir);
m_Parser.m_StartCommandTag = PREPROC_COMMAND_TAG;
}
else if(getPPkey.Compare(prmPVkey.GetBuffer()) == 0)
{
runtype = Previewrun;
m_Parser.m_StartCommandTag = PREPROC_COMMAND_TAG;
}
else
runtype = Forbiddenrun; // the key is not valid
}
else // preprocessing key not found in get string
{
m_PRMFile.GetPRMValue(PREPROC_DIR_PRM_NAME, tpldir);
runtype = Normalrun;
if (cgiFormString(TPL_TAG, tplName, TPL_NAME_LEN) != cgiFormSuccess)
return Forbiddenrun;
}
}
else
{
//Gets template directory from param file
m_PRMFile.GetPRMValue(TPLDIR, tpldir);
//Dedicated template (servicetpl): gets the template file name from param file
if (!m_PRMFile.GetPRMValue(TPL_SERVICE_TAG, tplName))
{
if (cgiFormString(PREPROC_TPL_TAG, tplName, TPL_NAME_LEN) != cgiFormSuccess)
{
if (cgiFormString(TPL_TAG, tplName, TPL_NAME_LEN) != cgiFormSuccess)
return Forbiddenrun;
}
else
{
Flush(PP_STARTED);
runtype = Preprocrun;
m_Parser.m_StartCommandTag = PREPROC_COMMAND_TAG;
m_PRMFile.GetPRMValue(PREPROC_DIR_PRM_NAME, preproc_outdir);
if (cgiFormString(TGT_TAG, preproc_outtpl, TPL_NAME_LEN) != cgiFormSuccess)
preproc_outtpl = tplName;
}
}
}
if(runtype == Preprocrun)
{
if ((*preproc_outdir).CompareNoCase(tpldir))
{
runtype = Forbiddenrun;
Flush(PP_IN_OUT_DIRS_EQ);
Flush(PP_FINISHED);
}
}
return runtype;
}
void Tannit::ManageOutput(itxString preproc_outdir, itxString preproc_outtpl)
{
//Output management
if (m_Parser.m_RunType == Preprocrun)
{
if (m_Parser.m_CurTpl != NULL)
{
if (!FlushOnFile(preproc_outdir.GetBuffer(),
preproc_outtpl.GetBuffer(),
m_Parser.m_CurTpl->m_Output.GetBuffer()))
Flush(WWW_PP_CANT_WRITEOUTPUT);
}
Flush(WWW_PP_FINISHED);
}
else if (m_Parser.m_RunType == Previewrun)
{
if (!g_DebugFile.m_Errors)
{
if (m_Parser.m_CurTpl != NULL)
{
m_Parser.m_RunType = Normalrun;
m_Parser.m_StartCommandTag = START_COMMAND_TAG;
m_Parser.Run((m_Parser.m_CurTpl->m_Output).GetBuffer());
}
else
Flush(ERR_OPEN_TPL_FILE);
}
}
if (m_Parser.m_RunType == Normalrun)
{
if (!g_DebugFile.m_Errors)
{
if (m_Parser.m_CurTpl != NULL)
Flush(m_Parser.m_CurTpl->m_Output.GetBuffer());
else
Flush(ERR_OPEN_TPL_FILE);
}
}
}
//-----------------------------------------------------------------
void Tannit::OnStart()
{
itxString preproc_outdir;
itxString preproc_enableext;
itxString preproc_outtpl;
itxString tpldir;
itxString tplName;
itxString forcedebug;
bool goon = true;
TimeTrace("Tannit Program Starting");
StartMilliCount();
//Reads the web server variables from the environment table
GetEnvironment(true);
ManageRequestMethod();
//Looks for the tag indicating that the output must be the debug file,
//also if the request will complete successfully.
if (cgiFormString(DEBUG_2_VIDEO_TAG, &forcedebug, TPL_NAME_LEN) == cgiFormSuccess)
{
g_DebugFile.m_ReportLevel = atoi(forcedebug.GetBuffer());
g_DebugFile.m_Errors = true;
}
//Reads the prm file from the get string, if anyone
if (InitCurrentPRM() == false)
{
Flush(ERR_OPEN_INI_FILE);
DebugTrace2(IN_ERROR, "%s\n", ERR_OPEN_INI_FILE);
return;
}
LoadModules(m_PRMFile);
// if required here we start the ODBC connection and hook the
// TQRODBCManager to it
InitODBC(&m_PRMFile);
// define the running enviroment (normalrun, preprocrun, previewrun, forbiddenrun)
// and set the correct input/output values
m_Parser.m_RunType = ManageContext(&tplName, &tpldir, &preproc_outtpl, &preproc_outdir);
m_Parser.m_ActualTplDir = tpldir;
if (m_Parser.m_RunType != Forbiddenrun && m_Parser.m_RunType != Diagnostic)
{
m_PRMFile.GetPRMValue("enableext", &preproc_enableext);
//~~~~~~~~~~~~~~~~~~~~~ BEGIN CORE JOB
if (preproc_enableext.IsEmpty() || preproc_enableext.IsNull())
m_Parser.Run(&tpldir, &tplName);
else
m_Parser.Run(&tpldir, &tplName, "");
//~~~~~~~~~~~~~~~~~~~~~ END CORE JOB
ManageOutput(preproc_outdir, preproc_outtpl);
}
else if (m_Parser.m_RunType == Diagnostic)
Inquiry();
StopMilliCount();
TraceMilliDiff("OnStart execution time:");
DebugTrace2(DEFAULT, "At %s OnStart ends.", CurrentDateTimeStr());
/* TEST MASSIMO NON TOCCARE PLEASE
itxString img;
if (cgiFormString("img", &img, TPL_NAME_LEN) == cgiFormSuccess)
{
FILE* fp = fopen(img.GetBuffer(), "rb");
char img[300000];
int read = fread(img, 1, 300000, fp);
fclose(fp);
int written = fwrite(img, 1, read, cgiOut);
}
//*/
}
//-----------------------------------------------------------------
bool Tannit::IsWebRequest()
{
return !(cgiServerSoftware == NULL || *cgiServerSoftware == 0);
}
//-----------------------------------------------------------------
void Tannit::LoadModules(PRMFile& paramfile)
{
itxString addon;
itxString addonLval;
char c[10];
addonLval = ADDON;
for (int i = m_NExtModules; i < MAX_EXT_MODULES; i++)
{
sprintf(c, "%d", i + 1);
addonLval += c;
addon = "";
// m_PRMFile.GetPRMValue(&addonLval, &addon);
paramfile.GetPRMValue(&addonLval, &addon);
if (addon.IsNull() || addon.IsEmpty())
return; //no more external modules
if (m_pTNTAPIImpl == NULL)
m_pTNTAPIImpl = new TNTAPIImpl(this);
LoadUserCommands(&addon, m_pTNTAPIImpl);
addonLval = ADDON;
}
}
//-----------------------------------------------------------------
void Tannit::LoadUserCommands(itxString* ext_mod_pathname, TNTAPIImpl* pTNTAPIImpl)
{
try // Try to make the connection with the extern module
{
if ((m_ExtModHandle[m_NExtModules] = m_Sys.DLLoadLibrary(ext_mod_pathname->GetBuffer())) == NULL)
{
DebugTrace("Extern module '%s': LoadLibrary failed. last error: %d\n",
ext_mod_pathname->GetBuffer(), m_Sys.DLGetLastError());
return;
}
TANNIT_HANDSHAKE pf;
// The way to call an export function is quite different between platforms:
// we try every method and fall in error only if no one applies.
if ((pf = (TANNIT_HANDSHAKE)m_Sys.DLGetFunction(m_ExtModHandle[m_NExtModules], (char*)1)) == NULL) //win32
if ((pf = (TANNIT_HANDSHAKE)m_Sys.DLGetFunction(m_ExtModHandle[m_NExtModules], "TannitHandshake")) == NULL) //linux
{
DebugTrace("Extern module '%s': Unable to get TannitHandshake.", ext_mod_pathname->GetBuffer());
return;
}
// Now make the hanshake.
(*pf)((AbstractCommand**)&m_Parser.m_Command[m_Parser.m_TotalCount], (TNTAPI*)pTNTAPIImpl);
}
catch(...)
{
DebugTrace("Extern module '%s': Handshake failed.", ext_mod_pathname->GetBuffer());
return;
}
DebugTrace2(DEFAULT, "Extern module '%s' successfully loaded.", ext_mod_pathname->GetBuffer());
m_NExtModules++;
m_Parser.UpdateTotalCount();
}
void Tannit::Usage(char* name)
{
fprintf(stdout, "usage:\n");
fprintf(stdout, " %s [option ... [option]]\n\n", name);
fprintf(stdout, "option:\n");
fprintf(stdout, " -h: this help\n");
fprintf(stdout, " -t<modulename>: TEG module's command description file\n");
fprintf(stdout, " -s<cmdsep>: processor command separator (i.e.: $, * or #)\n");
fprintf(stdout, " -i<filename>: input file for processing\n");
fprintf(stdout, " -o<filename>: output file\n");
fprintf(stdout, " -p<filename>: tannit parameter file\n");
fprintf(stdout, " -e<filename>: output file extension (i.e.: .htm)\n");
fprintf(stdout, " -g<query_string>: GET input string\n");
fprintf(stdout, "\n");
}
void Tannit::OnCommandLine(char* modulename, char cmdsep, char* inputfile, char* outputfile, char* ext)
{
itxString preproc_outdir;
itxString preproc_outtpl;
itxString tpldir;
itxString tplName;
itxString module;
itxString extension;
TimeTrace("Tannit Program Starting");
StartMilliCount();
// if required here we start the ODBC connection and hook the
// TQRODBCManager to it
InitODBC(&m_PRMFile);
//Gets template directory from param file
m_PRMFile.GetPRMValue(TPLDIR, &tpldir);
m_PRMFile.GetPRMValue(PREPROC_DIR_PRM_NAME, &preproc_outdir);
Flush(PP_STARTED);
m_Parser.m_PreprocRun = true;
m_Parser.m_StartCommandTag = cmdsep;
module = modulename;
if (module.IsEmpty())
{
tplName = inputfile;
preproc_outtpl = outputfile;
m_Parser.Run(&tpldir, &tplName);
//Output management
if (m_Parser.m_CurTpl != NULL)
{
if (!FlushOnFile(preproc_outdir.GetBuffer(), preproc_outtpl.GetBuffer(), m_Parser.m_CurTpl->m_Output.GetBuffer(), ext))
Flush(PP_CANT_WRITEOUTPUT);
}
Flush(PP_FINISHED);
}
else
{
m_Parser.AddVar("TEG_module_name", modulename);
preproc_outtpl = modulename;
tplName = "teg_def";
m_Parser.Run(&tpldir, &tplName, TEG_EXT);
//Output management
extension = ".h";
if (m_Parser.m_CurTpl != NULL)
{
if (!FlushOnFile(preproc_outdir.GetBuffer(), preproc_outtpl.GetBuffer(), m_Parser.m_CurTpl->m_Output.GetBuffer(), extension.GetBuffer()))
Flush(PP_CANT_WRITEOUTPUT);
}
Flush(PP_FINISHED);
tplName = "teg_imp";
m_Parser.Run(&tpldir, &tplName, TEG_EXT);
//Output management
extension = ".cpp";
if (m_Parser.m_CurTpl != NULL)
{
if (!FlushOnFile(preproc_outdir.GetBuffer(), preproc_outtpl.GetBuffer(), m_Parser.m_CurTpl->m_Output.GetBuffer(), extension.GetBuffer()))
Flush(PP_CANT_WRITEOUTPUT);
}
Flush(PP_FINISHED);
}
StopMilliCount();
TraceMilliDiff("OnStart execution time:");
DebugTrace2(DEFAULT, "At %s OnStart ends.", CurrentDateTimeStr());
}
void Tannit::CommandLineMode(int argc, char* argv[])
{
char cmdsep;
itxString inputfile;
itxString outputfile;
itxString extension;
itxString modulename;
fprintf(stdout, "\nTannit� 4.0 (copyright 2001)\n");
fprintf(stdout, "aitecsa\n");
fprintf(stdout, "._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.\n");
fprintf(stdout, " �aitecsa s.r.l. via baglivi 3 00161 roma italy\n");
fprintf(stdout, " aitecsa@aitecsa.it\n");
fprintf(stdout, " all rights reserved\n\n");
if (argc <= 1 || ISEQUAL(argv[1], "-h"))
{
Usage(argv[0]);
return;
}
cmdsep = '*';
inputfile = "tannitin";
outputfile = "tannitout";
extension = TPL_EXT;
modulename.SetEmpty();
bool prmfile = m_PRMConf.Clone(&m_PRMFile);
int i = 1;
while(argv[i] != NULL)
{
char optflag = argv[i][0];
char option = argv[i][1];
char* optvalue = &argv[i][2];
if (optflag != '-')
{
Usage(argv[0]);
return;
}
switch(option)
{
case 't':
modulename = optvalue;
break;
case 's':
cmdsep = optvalue[0];
break;
case 'i':
inputfile = optvalue;
break;
case 'o':
outputfile = optvalue;
break;
case 'g':
{
if (m_Sys.BSSetenv("QUERY_STRING", optvalue) != 0)
{
fprintf(stdout, "ERROR: unable set QUERY_STRING\n");
return;
}
GetEnvironment(true);
cgiContentLength = strlen(cgiQueryString);
if (cgiParseGetFormInput() != cgiParseSuccess)
{
fprintf(stdout, "ERROR: unable to parse get input\n");
return;
}
}
break;
case 'p':
try
{
itxString initFileExt;
initFileExt = optvalue;
if (prmfile != false)
{
m_PRMFile.MergePRM(&initFileExt);
m_PRMFile.SetPRMFileName(optvalue);
fprintf(stdout, "parameter file %s read...\n", optvalue);
}
}
catch(...)
{
fprintf(stdout, "ERROR: unable to read %s paramenter file\n", optvalue);
return;
}
break;
case 'e':
extension = optvalue;
break;
default:
Usage(argv[0]);
return;
}
i++;
}
OnCommandLine(modulename.GetBuffer(), cmdsep, inputfile.GetBuffer(), outputfile.GetBuffer(), extension.GetBuffer());
}
//-----------------------------------------------------------------
//-----------------------------------------------------------------
// MAIN APPLICATION ENTRY POINT
//-----------------------------------------------------------------
//-----------------------------------------------------------------
int main(int argc, char* argv[])
{
#ifdef DOWNLOAD
time_t tm;
struct tm* today;
time(&tm);
today = localtime(&tm);
if ((today->tm_year + 1900) != 2002)
return 0;
#endif
Tannit t; // THE object
// DEBUG FACILITY - BEGIN
#ifdef _DEBUG
//*
int p=1;
while (p)
Sleep(1);
//*/
#endif
// DEBUG FACILITY - END
bool result;
g_DebugFile.Open();
result = t.Initialize();
//test if tannit is invoked from command line
if (!t.IsWebRequest())
{
t.CommandLineMode(argc, argv);
g_DebugFile.Close();
return 0;
}
//tannit was invoked by the WebServer
//TBD gestione debug tracing prima dell'inizio del ciclo
if (result)
{
#ifdef FCGITANNIT
while (FCGI_Accept() >= 0)
{
//Close initialization instance of debug file
//and re-open it for current request
g_DebugFile.Close();
g_DebugFile.Open();
#endif
try
{
t.OnStart(); //User code
}
catch(...)
{
DebugTrace("%s\n", "Exception during OnStart (overridden by user)");
}
if (g_DebugFile.m_Errors)
{
if (!result) // we must send the header
t.SendResponseMimeType(DEFAULT_MIME_TYPE);
itxString appodbg;
if (g_DebugFile.Bufferize(&appodbg))
t.Flush(appodbg.GetBuffer());
}
g_DebugFile.Close();
#ifdef FCGITANNIT
} //FCGI loop
#endif
}
else
{
if (!result) // we must send the header
t.SendResponseMimeType(DEFAULT_MIME_TYPE);
itxString appodbg;
if (g_DebugFile.Bufferize(&appodbg))
t.Flush(appodbg.GetBuffer());
}
g_DebugFile.Close();
return 0;
}
<file_sep>/*
* Copyright (c) 2013 <NAME>
* See the file LICENSE for copying permission.
* */
package jtxlib.main.tcp;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NoRouteToHostException;
import java.net.Socket;
import jtxlib.main.aux.Debug;
public class SocketClient
{
Debug m_Dbg = new Debug();
private Socket connection;
private DataOutputStream outputStream;
private BufferedReader inputStream;
private DataInputStream dataInputStream;
private int m_ConnectionTimeout = 0;
public SocketClient()
{
}
//----------------------------------------------------------
/**
* Creates a new connection.
* <P>
*/
public boolean connect(String connAddress, int connPort)
{
boolean connavail = false;
try
{
connection = new Socket(connAddress, connPort);
outputStream = new DataOutputStream(connection.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
dataInputStream = new DataInputStream(connection.getInputStream());
connavail = true;
}
catch(NoRouteToHostException ex)
{
Debug.Dbg("JTXSocket.connect: " + ex);
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.connect: " + ex);
}
return connavail;
}
//----------------------------------------------------------
public boolean send(String message)
{
try
{
outputStream.writeBytes(message);
outputStream.write(13);
outputStream.write(10);
outputStream.flush();
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.send: " + ex);
return false;
}
return true;
}
//----------------------------------------------------------
public boolean sendNoCRLF(String message)
{
try
{
Debug.Dbg("sendNoCRLF: " + message);
outputStream.write(message.getBytes(), 0, message.length());
outputStream.flush();
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.sendNoCRLF: " + ex);
return false;
}
return true;
}
//----------------------------------------------------------
public boolean sendBytes(byte[] message, int len)
{
try
{
outputStream.write(message, 0, len);
outputStream.flush();
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.sendBytes: " + ex);
return false;
}
return true;
}
//----------------------------------------------------------
public String receiveLine()
{
String received = "";
try
{
received = inputStream.readLine();
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.receive: " + ex);
received = "";
}
return received;
}
//----------------------------------------------------------
public String receive()
{
String received = "";
String appo = "";
try
{
while ((appo = inputStream.readLine()) != null)
received += appo;
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.receive: " + ex);
received = "";
}
return received;
}
//----------------------------------------------------------
public int receiveBytes(byte[] message)
{
int readBytes = 0;
try
{
readBytes = dataInputStream.read(message);
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.receiveBytes: " + ex);
}
return readBytes;
}
//----------------------------------------------------------
/**
*Server closes connection
* <P>
*/
public void close()
{
try
{
connection.close();
connection = null;
inputStream.close();
inputStream = null;
outputStream.close();
outputStream = null;
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.close: " + ex);
}
}
//----------------------------------------------------------
public int getConnectionTimeout()
{
return m_ConnectionTimeout;
}
//----------------------------------------------------------
public void setConnectionTimeout(int timeout)
{
try
{
connection.setSoTimeout(timeout);
m_ConnectionTimeout = timeout;
}
catch(IOException ex)
{
Debug.Dbg("JTXSocket.setConnectionTimeout: " + ex);
}
}
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
//#include "dbInterface.h"
#include "tannitds.h"
#include "tannit.h"
#include "itannitc.h"
#include "itxtypes.h"
#include "extVars.h"
/*************************************************************************************
NOME :storedData
Categoria :interfaccia TQR
attivita' :restituisce il puntatore alla stringa della query identificata da queryName
alla colonna colName alla riga rowNum; errCode accetta in output un
eventuale codice di errore;
*************************************************************************************/
char* storedData(int rowNum, char* colName, char* queryName, int* errCode)
{
int i, colNum = ERR_COL_NOT_FOUND;
int totalCols = ERR_QUERY_NOT_FOUND;
struct Record * probingRec;
struct ColummnHeader * probingCol;
//**/if(usedbg){fprintf(debug, "FUNCTION storedData; STARTED requesting:%s.%s[%d];\n",queryName, colName, rowNum);fflush(debug);}
//**/if(usedbg){fprintf(debug, "queryName:%s\n", queryName);fflush(debug);}
//**/if(usedbg){fprintf(debug, "colName:%s\n", colName);fflush(debug);}
//**/if(usedbg){fprintf(debug, "rowNum:%d\n", rowNum);fflush(debug);}
//**/if(usedbg){fprintf(debug, "QueryCounter:%d\n", QueryCounter);fflush(debug);}
// ricerca della query corrispondente al nome in input
for (i = 0; i < QueryCounter; i++)
{
// nome non
if ( QueryResultSet[i]->id == 0)
{
*errCode = ERR_VOID_QUERY_NAME;
return (DATA_VALUE_ON_ERROR);
}
if (strcmp(QueryResultSet[i]->id, queryName) == 0)
{
probingRec = QueryResultSet[i]->recPtr;
probingCol = QueryResultSet[i]->queryHeader;
totalCols = QueryResultSet[i]->colsNumber;
}
}
if ( totalCols == ERR_QUERY_NOT_FOUND )
{
*errCode = ERR_QUERY_NOT_FOUND;
return (DATA_VALUE_ON_ERROR);
}
for (i = 0; i < totalCols; i++)
{
if (strcmp(probingCol[i].name, colName)==0)
{
colNum=i;
}
}
if (colNum == ERR_COL_NOT_FOUND)
{
*errCode = ERR_COL_NOT_FOUND;
return (DATA_VALUE_ON_ERROR);
}
if (!(probingRec->row))
return(0);
for ( i = 1; i < rowNum; i++)
{
if (!(probingRec = probingRec->next)) return(0);
}
if (rowNum == 0) return(REC_VAL_ZERO);
//**/if(usedbg){fprintf(debug, "FUNCTION storedData; returning:%s;\n\n", probingRec->row[colNum]);fflush(debug);}
return (probingRec->row[colNum]);
}
int dbInterface(char* queryName, char* query, int firstRec, int recsToStore)
{
int result = 0;
ITannit_Create(QueryResultSet, &QueryCounter);
result = ITannit_ExecuteSQLQuery(Odbcdsn, Odbcuid, Odbcpwd, queryName, query, firstRec, recsToStore);
ITannit_Destroy();
if (result == ITXFAILED)
{
/**/if (usedbg) ITannit_ErrorSQL(debug);
/**/if (usedbg) ITannit_ErrorSQL(cgiOut);
}
return result;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITX_TNTSQL_CPP__
#define __ITX_TNTSQL_CPP__
#endif
#include <time.h>
#include "tntsql.h"
#include <sql.h>
#include <sqlext.h>
#define SQBOOL(a) (SQL_SUCCEEDED(a)? TRUE : FALSE)
itxSQLConnection::itxSQLConnection()
{
memset(m_dsn, 0, ITX_SQL_DSN_LENGTH);
memset(m_uid, 0, ITX_SQL_UID_LENGTH);
memset(m_pwd, 0, ITX_SQL_PWD_LENGTH);
m_henv = 0;
m_hdbc = 0;
m_hstmt = 0;
m_statement = 0;
m_cols = 0;
m_rows = 0;
}
bool itxSQLConnection::Create(char* dsn, char* uid, char* pwd)
{
if (IsConnected())
return TRUE;
SQLRETURN retcode;
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_henv); /*Allocate environment handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLSetEnvAttr(m_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); /* Set the ODBC version environment attribute */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &m_hdbc); /* Allocate connection handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLConnect(m_hdbc, (SQLCHAR*) dsn, SQL_NTS, /* Connect to data source */
(SQLCHAR*) uid, SQL_NTS,(SQLCHAR*) pwd, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmt); /* Allocate statement handle */
}
}
}
return SQBOOL(retcode);
}
bool itxSQLConnection::SetAttributes(int attr, void* value, int valuelen)
{
SQLRETURN retcode;
retcode = SQLSetConnectAttr(m_hdbc, (SQLINTEGER) attr, (SQLPOINTER) value, (SQLINTEGER) valuelen);
return SQBOOL(retcode);
}
bool itxSQLConnection::ManualCommit()
{
return SetAttributes(SQL_ATTR_AUTOCOMMIT, (void*) SQL_AUTOCOMMIT_OFF, 0);
}
bool itxSQLConnection::AutoCommit()
{
return SetAttributes(SQL_ATTR_AUTOCOMMIT, (void*) SQL_AUTOCOMMIT_ON, 0);
}
bool itxSQLConnection::Commit()
{
SQLRETURN retcode;
retcode = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_COMMIT);
return SQBOOL(retcode);
}
bool itxSQLConnection::Rollback()
{
SQLRETURN retcode;
retcode = SQLEndTran(SQL_HANDLE_DBC, m_hdbc, SQL_ROLLBACK);
return SQBOOL(retcode);
}
#if 0
// Versione per i DSN su file: bisogna valorizzare il parametro ODBCDSN nel prm
// con la stringa 'FILEDSN=nome_file_dsn;'
bool itxSQLConnection::Create(char* dsn, char* uid = "", char* pwd = "")
{
char OutStr[1024];
SQLRETURN retcode;
SQLSMALLINT outstrlen;
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &m_henv); /*Allocate environment handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLSetEnvAttr(m_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); /* Set the ODBC version environment attribute */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLAllocHandle(SQL_HANDLE_DBC, m_henv, &m_hdbc); /* Allocate connection handle */
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLDriverConnect(m_hdbc, NULL, (SQLCHAR*)dsn, SQL_NTS, (SQLCHAR*)OutStr, 1024, &outstrlen, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(retcode))
retcode = SQLAllocHandle(SQL_HANDLE_STMT, m_hdbc, &m_hstmt); /* Allocate statement handle */
else
{
char sqlstate[10];
SQLINTEGER nativerr;
char msg[1024];
SQLSMALLINT msglength;
SQLGetDiagRec(SQL_HANDLE_DBC, m_hdbc, 1, (SQLCHAR*)sqlstate, &nativerr, (SQLCHAR*)msg, 1024, &msglength);
}
}
}
}
return SQBOOL(retcode);
}
#endif
bool itxSQLConnection::BindCol(int col, char* value, int size)
{
SQLRETURN retcode;
retcode = SQLBindCol(m_hstmt, (unsigned short)(col+1), SQL_C_CHAR, (SQLPOINTER) value, size, &m_ind);
return SQBOOL(retcode);
}
// statement must be a null-terminated string
bool itxSQLConnection::Execute(char* statement)
{
SQLRETURN retcode;
if (m_hstmt == 0)
return FALSE;
m_statement = statement;
m_cols = 0;
retcode = SQLExecDirect(m_hstmt, (unsigned char *) statement, SQL_NTS);
if (SQL_SUCCEEDED(retcode))
retcode = SQLNumResultCols(m_hstmt, &m_cols);
else
if (retcode == SQL_NO_DATA)
retcode = SQL_SUCCESS;
return SQBOOL(retcode);
}
bool itxSQLConnection::GetColInfo(short int col, char* name, short* type, long int* size)
{
SQLRETURN retcode;
short int realColNameLen, decimalDigits;
unsigned long int colSize;
SQLSMALLINT nullable;
retcode = SQLDescribeCol(m_hstmt, (short int)(col + 1), (unsigned char*) name, ITX_QRS_MAX_NAME_LEN, &realColNameLen, type, &colSize, &decimalDigits, &nullable);
if (SQL_SUCCEEDED(retcode))
{
colSize = (colSize > ITX_QRS_MAX_FIELD_LEN) ? ITX_QRS_MAX_FIELD_LEN : colSize;
*size = colSize;
}
return SQBOOL(retcode);
}
// start deve essere <= end
bool itxSQLConnection::SkipRecords(int start, int end)
{
SQLRETURN retcode;
int counter = start;
retcode = SQLFetch(m_hstmt);
while (counter < end && SQL_SUCCEEDED(retcode))
{
retcode = SQLFetch(m_hstmt);
counter++;
}
return SQBOOL(retcode);
}
bool itxSQLConnection::Fetch()
{
SQLRETURN retcode;
retcode = SQLFetch(m_hstmt);
return SQBOOL(retcode);
}
bool itxSQLConnection::FreeStmt()
{
SQLRETURN retcode;
retcode = SQLFreeStmt(m_hstmt, SQL_CLOSE);
return SQBOOL(retcode);
}
bool itxSQLConnection::MoreResults()
{
SQLRETURN retcode;
retcode = SQLMoreResults(m_hstmt);
if (SQBOOL(retcode))
retcode = SQLNumResultCols(m_hstmt, &m_cols);
return SQBOOL(retcode);
}
bool itxSQLConnection::GetColsNumber()
{
SQLRETURN retcode;
retcode = SQLNumResultCols(m_hstmt, &m_cols);
return SQBOOL(retcode);
}
bool itxSQLConnection::Destroy()
{
SQLRETURN retcode;
if (!IsConnected())
return TRUE;
retcode = SQLFreeHandle(SQL_HANDLE_STMT, m_hstmt);
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLDisconnect(m_hdbc);
if (SQL_SUCCEEDED(retcode))
{
retcode = SQLFreeHandle(SQL_HANDLE_DBC, m_hdbc);
if (SQL_SUCCEEDED(retcode))
SQLFreeHandle(SQL_HANDLE_ENV, m_henv);
}
}
m_henv = 0;
m_hdbc = 0;
m_hstmt = 0;
return SQBOOL(retcode);
}
void itxSQLConnection::Error(FILE* log)
{
time_t tm;
if (log == NULL) return;
time(&tm);
fprintf(log, "\n------------------------------------------------------------\n");
fprintf(log, " �AITECSA s.r.l.\n");
fprintf(log, "SQL INTERFACE MODULE ERROR REPORT\n");
fprintf(log, " %s", ctime(&tm));
fprintf(log, "------------------------------------------------------------\n");
fprintf(log, "\n");
fprintf(log, "Last Executed Query:\n");
fprintf(log, "%s\n", m_statement);
memset(m_sqlstate, '\0', ITX_SQL_STATUS_LEN);
memset(m_message, '\0', ITX_SQL_MAX_ERRMSG);
fprintf(log, "\nODBC ERROR REPORT:\n");
SQLGetDiagRec(SQL_HANDLE_ENV, m_henv, 1, m_sqlstate, &m_nativerr, m_message,
ITX_SQL_MAX_ERRMSG - 1, &m_msglength);
fprintf(log, " SQL_HANDLE_ENV : %s\n", m_sqlstate);
fprintf(log, " %s\n", m_message);
SQLGetDiagRec(SQL_HANDLE_DBC, m_hdbc, 1, m_sqlstate, &m_nativerr, m_message,
ITX_SQL_MAX_ERRMSG - 1, &m_msglength);
fprintf(log, " SQL_HANDLE_DBC : %s\n", m_sqlstate);
fprintf(log, " %s\n", m_message);
SQLGetDiagRec(SQL_HANDLE_STMT, m_hstmt, 1, m_sqlstate, &m_nativerr, m_message,
ITX_SQL_MAX_ERRMSG - 1, &m_msglength);
fprintf(log, " SQL_HANDLE_STMT: %s\n", m_sqlstate);
fprintf(log, " %s\n", m_message);
fprintf(log, "\n\n");
}<file_sep>jtxlib
======
Web-oriented Java library
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __TNT_CRYPT_H__
#define __TNT_CRYPT_H__
int BuildCryptUserLabel(unsigned char* usercode, unsigned char* userlabel);
long VerifyCryptUserLabel(unsigned char* usercode, unsigned char* userlabel);
void tannitEncrypt(char* source, char* destination);
void tannitDecrypt(char* source, char* destination);
#endif //__TNT_CRYPT_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
#ifndef __ITANNITDEF_H__
#define __ITANNITDEF_H__
#define ITX_APPC_ANY_MSG '*'
#define ITX_APPC_PC_REQ 'P'
#define ITX_APPC_HS_RPY 'H'
#define ITX_APPC_PC_FTX 'C'
#define ITX_APPC_HS_FTX 'T'
#define ITX_APPC_HS_RST 'I'
#define ITX_APPC_HS_PRT 'S'
#define ITX_APPC_ERROR 'E'
#define ITXOPLC_TEST_ENV 1
#define ITXOPLC_PROD_ENV 2
#define ITXUSER_TEST_ENV 3
#define ITXUSER_PROD_ENV 4
// SQL INTERFACE CONSTANTS
#define ITX_QRS_MAX_NAME_LEN 63
#define ITX_QRS_MAX_FIELD_LEN 8191
#define ITX_QRS_MAX_QUERY_LEN 32767
//
// DIMENSIONE APPC COMMUNICATION CONSTANTS
#define ITX_APPC_MAX_INFO_LENGTH 1920
#define ITX_APPC_HEADER_LENGTH 44
#define ITX_APPC_DATA_LEN ITX_APPC_MAX_INFO_LENGTH - ITX_APPC_HEADER_LENGTH
#define ITX_APPC_MAX_NUM_OF_PACKETS 512
#define ITX_APPC_PN_LEN 5
#define ITX_APPC_PN_LOCATOR 19
#define ITX_APPC_MSG_TYPE_LOCATOR 1
#define ITX_APPC_LAST_PACKET 99999
#define ITX_APPC_PC_FILLER '-'
#define ITX_APPC_AS400_TX_END "FINE\0"
#define ITX_APPC_AS400_TX_END_LEN 4
//
// DIMENSIONE PARSING CONSTANTS
#define ITX_APPC_ENDINFO_SEP '�' //'\xAB'
#define ITX_APPC_RECORD_SEP '�' //'\xBA'
#define ITX_APPC_FIELD_SEP '�' //'\xAB'
#define ITX_ASCII_ENDINFO_SEP '\xAB'
#define ITX_ASCII_RECORD_SEP '\xBA'
#define ITX_ASCII_FIELD_SEP '\xAB'
#define ITX_APPC_MAX_RECORD_LENGTH 8192
#define ITX_APPC_MAX_FIELD_LENGTH 256
//
typedef char PACKET_TYPE;
#endif //__ITANNITDEF_H__
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : commands.h
| TAB : 2 spaces
|
| DESCRIPTION : Base commands declarations.
|
|
*/
#ifndef _COMMANDS_H_
#define _COMMANDS_H_
#include "tnt.h"
#include "defines.h"
#include "cgiresolver.h"
#include "parser.h"
#include "tqrodbc.h"
#include "itxlib.h"
/******************
COMMAND NAMES
******************/
#define ARRAY "array"
#define ARRAYGET "arrayget"
#define ARRAYSET "arrayset"
#define CHECKFORBIDDENCHARS "cfc"
#define CGIPATH "cgipath"
#define CONSOLE "console"
#define COPYFILE "copyf"
#define CRYPT "crypt"
#define CURRENCY "currency"
#define CYCLETQR "cycle"
#define DECRYPT "decrypt"
#define DMYTIME "dmytime"
#define ALTERNATE_CONDITIONAL_BLOCK "else"
#define ELSIF_CONDITIONAL_BLOCK "elsif"
#define MAIL "email"
#define ENDCYCLETQR "endcycle"
#define ENDCYCLEFOR "endfor"
#define END_CONDITIONAL_BLOCK "endif"
#define ODBC_EXECUTE_QUERY "exeq"
#define TQREXIST "exist"
#define EXIT "exit"
#define FLUSH "flush"
#define FORMATCURRENCY "fmtcur"
#define CYCLEFOR "for"
#define FORINDEX "foridx"
#define GETVALUE "get"
#define GETCOOKIE "getcoo"
#define GETENV "getenv"
#define GETHIDE "gethide"
#define GETVALUECAST "getcast"
#define GETVALUEQUOTE "getq"
#define GETVAR "getvar"
#define START_CONDITIONAL_BLOCK "if"
#define LCASE "lcase"
#define LEFT "left"
#define MAKEOP "makeop"
#define MID "mid"
#define NEWCONNECTION "newconn"
#define NOW "now"
#define NETPREX "netprex"
#define NETGRAB "netgrab"
#define NUMERICAL_COMPARISON "numcmp"
#define PAGER "pager"
#define GETPOSTBODY "postbody"
#define PROCESS_EXTERN_FILE "prex"
#define PRMVALUE "prmval"
#define PROCESS_MEMORY_BUFFER "proc"
#define QUOTES "quotes"
#define RAND "rand"
#define REMOVECHAR "rchar"
#define RECSEL "recsel"
#define TQRRECFIELDVALUE "recval"
#define TQRRECFIELDVALQUOT "recvaq"
#define TQRREMOVE "remq"
#define RESETCONNECTION "resetconn"
#define RETURN "return"
#define RIGHT "right"
#define SETCONNECTION "setconn"
#define SETVAR "setvar"
#define STRLEN "strlen"
#define TQRFILT "tqrfilt"
#define TQRINSERT "tqrinsert"
#define TQRMOVE "tqrmove"
#define TQRSAMPLE "tqrsample"
#define TQRSTAT "tqrstat"
#define TQRSTORE "tqrstore"
#define TRACEUSER "traceu"
#define TRANS "trans"
#define TRIM "trim"
#define UCASE "ucase"
#define UTIME "utime"
#define VERINST "verinst"
#define VALID "valid"
/******************
SUPPORT CLASSES
******************/
/*----------------------------------------------------------------------------
BaseCommand
Main specialization class for base (tannit internal) commands.
----------------------------------------------------------------------------*/
class BaseCommand : public AbstractCommand
{
public:
//MEMBERS
itxString m_Name;
itxString m_Output;
int m_Type;
//METHODS
inline char* GetName(){return m_Name.GetBuffer();}
void Deallocate(){}
//CONSTRUCTION-DESTRUCTION
BaseCommand(){m_Type = DEFAULT_BC_TYPE;};
~BaseCommand(){}
};
/******************
BASE COMMANDS
******************/
/*----------------------------------------------------------------------------
StartConditionalBlock
----------------------------------------------------------------------------*/
class BC_StartConditionalBlock : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_StartConditionalBlock(char* name, Parser* pParser, int type)
{
m_Name = name;
m_pParser = pParser;
m_Type = type;
}
~BC_StartConditionalBlock(){}
};
/*----------------------------------------------------------------------------
EndConditionalBlock
----------------------------------------------------------------------------*/
class BC_EndConditionalBlock : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr){return NULL;};
//CONSTRUCTION-DESTRUCTION
BC_EndConditionalBlock(){m_Name = END_CONDITIONAL_BLOCK; m_Type = END_CND_BLK;}
~BC_EndConditionalBlock(){};
};
/*----------------------------------------------------------------------------
AlternateConditionalBlock
----------------------------------------------------------------------------*/
class BC_AlternateConditionalBlock : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr){return NULL;};
//CONSTRUCTION-DESTRUCTION
BC_AlternateConditionalBlock(){m_Name = ALTERNATE_CONDITIONAL_BLOCK; m_Type = ELSE_CND_BLK;}
~BC_AlternateConditionalBlock(){};
};
/*----------------------------------------------------------------------------
PRMValue
----------------------------------------------------------------------------*/
class BC_PRMValue : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr)
{
m_Output.SetEmpty();
if (istr != NULL && strlen(istr) > 0)
{
if (m_pCGIRes->m_PRMFile.GetPRMValue(istr, &m_Output) == false)
DebugTrace2(IN_COMMAND | IN_WARNING, "Cannot find '%s' prm variable.", istr);
}
else
DebugTrace2(IN_COMMAND | IN_WARNING, "Empty argument found.");
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_PRMValue(char* name, CGIResolver* pcgires)
{
m_Name = name;
m_pCGIRes = pcgires;
}
~BC_PRMValue(){};
};
/*----------------------------------------------------------------------------
Cgipath
----------------------------------------------------------------------------*/
class BC_Cgipath : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr)
{
itxString cgidir, cginame;
m_Output.SetEmpty();
m_pCGIRes->m_PRMFile.GetPRMValue("webroot", &m_Output);
m_pCGIRes->m_PRMFile.GetPRMValue("cgidir", &cgidir);
m_pCGIRes->m_PRMFile.GetPRMValue("cginame", &cginame);
m_Output += "/";
m_Output += cgidir;
m_Output += "/";
m_Output += cginame;
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Cgipath(char* name, CGIResolver* pcgires)
{
m_Name = name;
m_pCGIRes = pcgires;
}
~BC_Cgipath(){};
};
/*----------------------------------------------------------------------------
GetValue
----------------------------------------------------------------------------*/
class BC_GetValue : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetValue(Parser* pParser, CGIResolver* pcgires)
{
m_Name = GETVALUE;
m_pCGIRes = pcgires;
m_pParser = pParser;
}
~BC_GetValue(){};
};
/*----------------------------------------------------------------------------
GetHide
----------------------------------------------------------------------------*/
class BC_GetHide : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetHide(Parser* pParser)
{
m_Name = GETHIDE;
m_pParser = pParser;
}
~BC_GetHide(){};
};
/*----------------------------------------------------------------------------
AdjustQuotes
----------------------------------------------------------------------------*/
class BC_AdjustQuotes : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr)
{
m_Output = istr;
m_Output.AdjustStr();
m_Output.SubstituteSubString("\"", "\"\"");
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_AdjustQuotes(Parser* pParser)
{
m_Name = QUOTES;
}
~BC_AdjustQuotes(){};
};
/*----------------------------------------------------------------------------
ProcessExternFile
----------------------------------------------------------------------------*/
class BC_ProcessExternFile : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ProcessExternFile(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = PROCESS_EXTERN_FILE;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
}
~BC_ProcessExternFile(){};
};
/*----------------------------------------------------------------------------
UCase
----------------------------------------------------------------------------*/
class BC_UCase : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr)
{
m_Output = istr;
m_Output.UCase();
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_UCase(){m_Name = UCASE;}
~BC_UCase(){};
};
/*----------------------------------------------------------------------------
LCase
----------------------------------------------------------------------------*/
class BC_LCase : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr)
{
m_Output = istr;
m_Output.LCase();
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_LCase(){m_Name = LCASE;}
~BC_LCase(){};
};
/*----------------------------------------------------------------------------
Left
----------------------------------------------------------------------------*/
class BC_Left : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr)
{
int len;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &m_Output) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &len) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output.Left(len);
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Left(Parser* pParser){m_Name = LEFT; m_pParser = pParser;}
~BC_Left(){};
};
/*----------------------------------------------------------------------------
Right
----------------------------------------------------------------------------*/
class BC_Right : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr)
{
int len;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &m_Output) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &len) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output.Right(len);
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Right(Parser* pParser){m_Name = RIGHT; m_pParser = pParser;}
~BC_Right(){};
};
/*----------------------------------------------------------------------------
Strlen
----------------------------------------------------------------------------*/
class BC_Strlen : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr)
{
m_Output = istr;
m_Output.Trim();
int l = m_Output.Len();
m_Output.SetInt(l);
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Strlen(){m_Name = STRLEN;}
~BC_Strlen(){};
};
/*----------------------------------------------------------------------------
Trim
----------------------------------------------------------------------------*/
class BC_Trim : public BaseCommand
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr)
{
m_Output = istr;
m_Output.Trim();
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Trim(){m_Name = TRIM;}
~BC_Trim(){};
};
/*----------------------------------------------------------------------------
SetVar
----------------------------------------------------------------------------*/
class BC_SetVar : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_SetVar(Parser* pParser){m_Name = SETVAR; m_pParser = pParser;}
~BC_SetVar(){};
};
/*----------------------------------------------------------------------------
GetVar
----------------------------------------------------------------------------*/
class BC_GetVar : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetVar(Parser* pParser){m_Name = GETVAR; m_pParser = pParser;}
~BC_GetVar(){};
};
/*----------------------------------------------------------------------------
GetCookie
----------------------------------------------------------------------------*/
class BC_GetCookie : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetCookie(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = GETCOOKIE;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
}
~BC_GetCookie(){};
};
/*----------------------------------------------------------------------------
UTime
----------------------------------------------------------------------------*/
class BC_UTime : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_UTime(Parser* pParser)
{
m_Name = UTIME;
m_pParser = pParser;
}
~BC_UTime(){};
};
/*----------------------------------------------------------------------------
DMYTime
----------------------------------------------------------------------------*/
class BC_DMYTime : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_DMYTime(Parser* pParser)
{
m_Name = DMYTIME;
m_pParser = pParser;
}
~BC_DMYTime(){};
};
/*----------------------------------------------------------------------------
Now
----------------------------------------------------------------------------*/
class BC_Now : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Now(Parser* pParser)
{
m_Name = NOW;
m_pParser = pParser;
}
~BC_Now(){};
};
/*----------------------------------------------------------------------------
FormatCurrency
----------------------------------------------------------------------------*/
class BC_FormatCurrency : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
private:
char* Format(char* num, int mant_len, int want_sep);
public:
//CONSTRUCTION-DESTRUCTION
BC_FormatCurrency(Parser* pParser)
{
m_Name = FORMATCURRENCY;
m_pParser = pParser;
}
~BC_FormatCurrency(){};
};
/*----------------------------------------------------------------------------
CheckForbiddenChars
----------------------------------------------------------------------------*/
class BC_CheckForbiddenChars : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_CheckForbiddenChars(Parser* pParser)
{
m_pParser = pParser;
m_Name = CHECKFORBIDDENCHARS;
}
~BC_CheckForbiddenChars(){};
};
/*----------------------------------------------------------------------------
TraceUser
----------------------------------------------------------------------------*/
class BC_TraceUser : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TraceUser(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = TRACEUSER;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
}
~BC_TraceUser(){};
};
/*----------------------------------------------------------------------------
ODBCExecuteQuery
----------------------------------------------------------------------------*/
class BC_ODBCExecuteQuery : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
TQRODBCManager* m_pTQRODBCManager;
itxString m_ODBCdsn;
itxString m_ODBCpwd;
itxString m_ODBCuid;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ODBCExecuteQuery(Parser* pParser, CGIResolver* pCGIRes, TQRODBCManager* pTQRODBCManager)
{
m_Name = ODBC_EXECUTE_QUERY;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
m_pTQRODBCManager = pTQRODBCManager;
}
~BC_ODBCExecuteQuery(){};
};
/*----------------------------------------------------------------------------
TQRRecordFieldValue
----------------------------------------------------------------------------*/
class BC_TQRRecordFieldValue : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRRecordFieldValue(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQRRECFIELDVALUE;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_TQRRecordFieldValue(){};
};
/*----------------------------------------------------------------------------
TQRRecordFieldValQuot
----------------------------------------------------------------------------*/
class BC_TQRRecordFieldValQuot : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRRecordFieldValQuot(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQRRECFIELDVALQUOT;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_TQRRecordFieldValQuot(){};
};
/*----------------------------------------------------------------------------
CycleTQR
----------------------------------------------------------------------------*/
class BC_CycleTQR : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_CycleTQR(Parser* pParser, CGIResolver* pCGIRes, TQRCollection* pTQRCollection)
{
m_Name = CYCLETQR;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
m_pTQRCollection = pTQRCollection;
m_Type = START_CYCLE;
}
~BC_CycleTQR(){};
};
/*----------------------------------------------------------------------------
EndCycleTQR
----------------------------------------------------------------------------*/
class BC_EndCycleTQR : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_EndCycleTQR(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = ENDCYCLETQR;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
m_Type = END_CYCLE;
}
~BC_EndCycleTQR(){};
};
/*----------------------------------------------------------------------------
CycleFor
----------------------------------------------------------------------------*/
class BC_CycleFor : public BaseCommand
{
public:
//MEMBERS
TQRManager* m_pTQRManager;
Parser* m_pParser;
CGIResolver* m_pCGIRes;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_CycleFor(Parser* pParser, CGIResolver* pCGIRes, TQRCollection* pTQRCollection,
TQRManager* pTQRManager)
{
m_Name = CYCLEFOR;
m_pTQRManager = pTQRManager;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
m_pTQRCollection = pTQRCollection;
m_Type = START_CYCLE;
}
~BC_CycleFor(){};
};
/*----------------------------------------------------------------------------
EndCycleFor
----------------------------------------------------------------------------*/
class BC_EndCycleFor : public BC_EndCycleTQR
{
public:
//MEMBERS
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_EndCycleFor(Parser* pParser, TQRCollection* pTQRCollection) :
BC_EndCycleTQR(pParser, pTQRCollection)
{
m_Name = ENDCYCLEFOR;
}
~BC_EndCycleFor(){};
};
/*----------------------------------------------------------------------------
EndCycleFor
----------------------------------------------------------------------------*/
class BC_ForIndex : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ForIndex(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = FORINDEX;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_ForIndex(){};
};
/*----------------------------------------------------------------------------
Exit
----------------------------------------------------------------------------*/
class BC_Exit : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Exit(Parser* pParser)
{
m_Name = EXIT;
m_pParser = pParser;
}
~BC_Exit(){};
};
/*----------------------------------------------------------------------------
TQRExist
----------------------------------------------------------------------------*/
class BC_TQRExist : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRExist(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQREXIST;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_TQRExist(){};
};
/*----------------------------------------------------------------------------
Crypt
----------------------------------------------------------------------------*/
class BC_Crypt : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
private:
unsigned short itxEncrypt(unsigned char* DESKey, unsigned char* Whitenings,
unsigned char* source, unsigned char* destination);
public:
//CONSTRUCTION-DESTRUCTION
BC_Crypt(Parser* pParser)
{
m_Name = CRYPT;
m_pParser = pParser;
}
~BC_Crypt(){};
};
/*----------------------------------------------------------------------------
Decrypt
----------------------------------------------------------------------------*/
class BC_Decrypt : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
private:
unsigned short itxDecrypt(unsigned char* DESKey, unsigned char* Whitenings,
unsigned char* source, unsigned char* destination);
public:
//CONSTRUCTION-DESTRUCTION
BC_Decrypt(Parser* pParser)
{
m_Name = DECRYPT;
m_pParser = pParser;
}
~BC_Decrypt(){}
};
/*----------------------------------------------------------------------------
Valid
----------------------------------------------------------------------------*/
class BC_Valid : public BC_ODBCExecuteQuery
{
public:
//MEMBERS
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
int CheckDbPwd(itxString* login, itxString* pwd,
itxString* extraField, itxString* extraVal,
itxString* retMsg);
bool LoginWantsQuotes(itxString* logintable, itxString* loginfield);
//CONSTRUCTION-DESTRUCTION
BC_Valid(Parser* pParser, CGIResolver* pCGIRes, TQRODBCManager* pTQRODBCManager, TQRCollection* pTQRCollection) :
BC_ODBCExecuteQuery(pParser, pCGIRes, pTQRODBCManager)
{
m_Name = VALID;
m_pTQRCollection = pTQRCollection;
}
~BC_Valid(){};
};
/*----------------------------------------------------------------------------
RemoveTQR
----------------------------------------------------------------------------*/
class BC_RemoveTQR : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_RemoveTQR(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQRREMOVE;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_RemoveTQR(){};
};
/*----------------------------------------------------------------------------
TQRStat
----------------------------------------------------------------------------*/
class BC_TQRStat : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRStat(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQRSTAT;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_TQRStat(){};
};
/*----------------------------------------------------------------------------
Return
----------------------------------------------------------------------------*/
class BC_Return : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Return(Parser* pParser)
{
m_Name = RETURN;
m_pParser = pParser;
}
~BC_Return(){};
};
/*----------------------------------------------------------------------------
Flush
----------------------------------------------------------------------------*/
class BC_Flush : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Flush(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = FLUSH;
m_pCGIRes = pCGIRes;
m_pParser = pParser;
}
~BC_Flush(){};
};
/*----------------------------------------------------------------------------
TQRMove
----------------------------------------------------------------------------*/
class BC_TQRMove : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRMove(Parser* pParser, TQRCollection* pTQRCollection)
{
m_Name = TQRMOVE;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
}
~BC_TQRMove(){};
};
/*----------------------------------------------------------------------------
TQRFilt
----------------------------------------------------------------------------*/
class BC_TQRFilt : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRFilt(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = TQRFILT;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_TQRFilt(){};
};
/*----------------------------------------------------------------------------
TQRSample
----------------------------------------------------------------------------*/
class BC_TQRSample : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRSample(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = TQRSAMPLE;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_TQRSample(){};
};
/*----------------------------------------------------------------------------
Recsel
----------------------------------------------------------------------------*/
class BC_Recsel : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRCollection* m_pTQRCollection;
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Recsel(Parser* pParser, TQRCollection* pTQRCollection, CGIResolver* pCGIRes)
{
m_Name = RECSEL;
m_pParser = pParser;
m_pTQRCollection = pTQRCollection;
m_pCGIRes = pCGIRes;
}
~BC_Recsel(){};
};
/*----------------------------------------------------------------------------
Trans
----------------------------------------------------------------------------*/
class BC_Trans : public BC_ODBCExecuteQuery
{
public:
//MEMBERS
TQRCollection* m_pTQRCollection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Trans(Parser* pParser, CGIResolver* pCGIRes, TQRODBCManager* pTQRODBCManager, TQRCollection* pTQRCollection) :
BC_ODBCExecuteQuery(pParser, pCGIRes, pTQRODBCManager)
{
m_Name = TRANS;
m_pTQRCollection = pTQRCollection;
}
~BC_Trans(){};
};
/*----------------------------------------------------------------------------
TQRStore
----------------------------------------------------------------------------*/
class BC_TQRStore : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRStore(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = TQRSTORE;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_TQRStore(){};
};
/*----------------------------------------------------------------------------
TQRInsert
----------------------------------------------------------------------------*/
class BC_TQRInsert : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRODBCManager* m_pTQRODBCManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_TQRInsert(Parser* pParser, TQRODBCManager* pTQRODBCManager)
{
m_Name = TQRINSERT;
m_pParser = pParser;
m_pTQRODBCManager = pTQRODBCManager;
}
~BC_TQRInsert(){};
};
/*----------------------------------------------------------------------------
Pager
----------------------------------------------------------------------------*/
class BC_Pager : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Pager(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = PAGER;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_Pager(){};
};
/*----------------------------------------------------------------------------
Netprex
----------------------------------------------------------------------------*/
class BC_Netprex : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Netprex(Parser* pParser)
{
m_Name = NETPREX;
m_pParser = pParser;
}
~BC_Netprex(){};
};
/*----------------------------------------------------------------------------
Netgrab
----------------------------------------------------------------------------*/
class BC_Netgrab : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Netgrab(Parser* pParser)
{
m_Name = NETGRAB;
m_pParser = pParser;
}
~BC_Netgrab(){};
};
/*----------------------------------------------------------------------------
Proc
----------------------------------------------------------------------------*/
class BC_Proc : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Proc(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = PROCESS_MEMORY_BUFFER;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
}
~BC_Proc(){};
};
/*----------------------------------------------------------------------------
Rand
----------------------------------------------------------------------------*/
class BC_Rand : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Rand(Parser* pParser)
{
m_Name = RAND;
m_pParser = pParser;
}
~BC_Rand(){};
};
/*----------------------------------------------------------------------------
MakeOp
----------------------------------------------------------------------------*/
class BC_MakeOp : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
bool MakeMulDivs(itxListPtr* ops, itxListPtr* terms, char op);
//CONSTRUCTION-DESTRUCTION
BC_MakeOp(Parser* pParser)
{
m_Name = MAKEOP;
m_pParser = pParser;
}
~BC_MakeOp(){};
};
/*----------------------------------------------------------------------------
GetValueQuote
----------------------------------------------------------------------------*/
class BC_GetValueQuote : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetValueQuote(Parser* pParser, CGIResolver* pcgires)
{
m_Name = GETVALUEQUOTE;
m_pCGIRes = pcgires;
m_pParser = pParser;
}
~BC_GetValueQuote(){};
};
/*----------------------------------------------------------------------------
BC_GetValueCast
----------------------------------------------------------------------------*/
class BC_GetValueCast : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetValueCast(Parser* pParser, CGIResolver* pcgires)
{
m_Name = GETVALUECAST;
m_pCGIRes = pcgires;
m_pParser = pParser;
}
~BC_GetValueCast(){};
};
/*----------------------------------------------------------------------------
NewConnection
----------------------------------------------------------------------------*/
class BC_NewConnection : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
itxSQLConnCollection* m_pconnections;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_NewConnection(Parser* pParser, itxSQLConnCollection* pconnections)
{
m_Name = NEWCONNECTION;
m_pParser = pParser;
m_pconnections = pconnections;
}
~BC_NewConnection(){};
};
/*----------------------------------------------------------------------------
SetConnection
----------------------------------------------------------------------------*/
class BC_SetConnection : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRODBCManager* m_pTQRODBCManager;
itxSQLConnCollection* m_pconnections;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_SetConnection(Parser* pParser, TQRODBCManager* ptqrodbcmng, itxSQLConnCollection* pconnections)
{
m_Name = SETCONNECTION;
m_pTQRODBCManager = ptqrodbcmng;
m_pParser = pParser;
m_pconnections = pconnections;
}
~BC_SetConnection(){};
};
/*----------------------------------------------------------------------------
ResetConnection
----------------------------------------------------------------------------*/
class BC_ResetConnection : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRODBCManager* m_pTQRODBCManager;
itxSQLConnection* m_podbcconnection;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ResetConnection(Parser* pParser, TQRODBCManager* ptqrodbcmng, itxSQLConnection* podbcconnection)
{
m_Name = RESETCONNECTION;
m_pParser = pParser;
m_pTQRODBCManager = ptqrodbcmng;
m_podbcconnection = podbcconnection;
}
~BC_ResetConnection(){};
};
/*----------------------------------------------------------------------------
Array
----------------------------------------------------------------------------*/
class BC_Array : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Array(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = ARRAY;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_Array(){};
};
/*----------------------------------------------------------------------------
ArraySet
----------------------------------------------------------------------------*/
class BC_ArraySet : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ArraySet(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = ARRAYSET;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_ArraySet(){};
};
/*----------------------------------------------------------------------------
ArrayGet
----------------------------------------------------------------------------*/
class BC_ArrayGet : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
TQRManager* m_pTQRManager;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_ArrayGet(Parser* pParser, TQRManager* pTQRManager)
{
m_Name = ARRAYGET;
m_pParser = pParser;
m_pTQRManager = pTQRManager;
}
~BC_ArrayGet(){};
};
/*----------------------------------------------------------------------------
RemoveChar
----------------------------------------------------------------------------*/
class BC_RemoveChar : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_RemoveChar(Parser* pParser)
{
m_Name = REMOVECHAR;
m_pParser = pParser;
}
~BC_RemoveChar(){};
};
/*----------------------------------------------------------------------------
Mid
----------------------------------------------------------------------------*/
class BC_Mid : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr)
{
int len;
int start;
m_Output.SetEmpty();
if(m_pParser->PickPar(istr, 1, &m_Output) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 2, &start) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickInt(istr, 3, &len) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
m_Output.Mid(start, len);
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Mid(Parser* pParser){m_Name = MID; m_pParser = pParser;}
~BC_Mid(){};
};
/*----------------------------------------------------------------------------
NumericalCmp
----------------------------------------------------------------------------*/
class BC_NumericalCmp : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr)
{
double a, b;
m_Output.SetEmpty();
if(m_pParser->PickDouble(istr, 1, &a) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if(m_pParser->PickDouble(istr, 2, &b) == PARAM_NOT_FOUND)
return PARAM_NOT_FOUND_MSG;
if (a == b)
m_Output = "0";
else if (a < b)
m_Output = "-1";
else if (a > b)
m_Output = "1";
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_NumericalCmp(Parser* pParser){m_Name = NUMERICAL_COMPARISON; m_pParser = pParser;}
~BC_NumericalCmp(){};
};
/*----------------------------------------------------------------------------
Verinst
----------------------------------------------------------------------------*/
class BC_Verinst : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
public:
//CONSTRUCTION-DESTRUCTION
BC_Verinst(Parser* pParser)
{
m_Name = VERINST;
m_pParser = pParser;
}
~BC_Verinst(){}
};
/*----------------------------------------------------------------------------
CopyFile
----------------------------------------------------------------------------*/
class BC_CopyFile : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_CopyFile(Parser* pParser)
{
m_Name = COPYFILE;
m_pParser = pParser;
}
~BC_CopyFile(){}
};
/*----------------------------------------------------------------------------
Currency
----------------------------------------------------------------------------*/
class BC_Currency : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Currency(Parser* pParser)
{
m_Name = CURRENCY;
m_pParser = pParser;
}
~BC_Currency(){}
};
/*----------------------------------------------------------------------------
Console
----------------------------------------------------------------------------*/
class BC_Console : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Console(Parser* pParser, CGIResolver* pCGIRes)
{
m_Name = CONSOLE;
m_pParser = pParser;
m_pCGIRes = pCGIRes;
}
~BC_Console(){}
};
/*----------------------------------------------------------------------------
GetPOSTbody
----------------------------------------------------------------------------*/
class BC_GetPOSTbody : public BaseCommand
{
public:
//MEMBERS
CGIResolver* m_pCGIRes;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_GetPOSTbody(CGIResolver* pCGIRes)
{
m_Name = GETPOSTBODY;
m_pCGIRes = pCGIRes;
}
~BC_GetPOSTbody(){}
};
/*----------------------------------------------------------------------------
Mail
----------------------------------------------------------------------------*/
class BC_Mail : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr);
//CONSTRUCTION-DESTRUCTION
BC_Mail(Parser* pParser)
{
m_Name = MAIL;
m_pParser = pParser;
}
~BC_Mail(){}
};
/*----------------------------------------------------------------------------
Getenv
----------------------------------------------------------------------------*/
class BC_Getenv : public BaseCommand
{
public:
//MEMBERS
Parser* m_pParser;
//METHODS
char* Execute(char* istr)
{
itxString varname;
if (m_pParser->PickPar(istr, 1, &varname) == PARAM_FOUND)
m_Output = getenv(varname.GetBuffer());
return m_Output.GetBuffer();
}
//CONSTRUCTION-DESTRUCTION
BC_Getenv(Parser* pParser)
{
m_Name = GETENV;
m_pParser = pParser;
}
~BC_Getenv(){}
};
#endif /* _COMMANDS_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/*****************************************************************************
AITECSA S.R.L.
- PROJECT : itxWeb - Tannit
- FILENAME : tannit.h
- TAB : 2, no spaces
- DESCRIPTION : header principale
*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include "cgic.h"
#include "tannitds.h"
//#include "dbinterface.h"
#include "tntcrypt.h"
#include "itxlib.h"
#include "tannitdefines.h"
//Identity
#define INFO_ID 0
#define INFO_TAG "wrinfo"
#define VERSION 1
#define VERSION_MSG "<!-- Tannit: V 3.017 08.09.2000 -->\n"
#define OWNER 2
#define OWNER_MSG "<!-- Code owned by : A I T E C S A S.R.L. -->\n"
#define AUTHOR 3
#define AUTHOR_MSG "<!-- Like Sweetie Pie By The Stone - Alliance Everbody Knows I'm Known For Dropping Science -->\n"
#define APPC_MSG_ID 4
/*
versione 3.017 - eliminate alcune operazioni valide solo per AsWeb e corretta la EXIT.
versione 3.016 - Aggiunta quotestr
versione 3.015 - Aggiunta stampa del pid nel nome del file di debug
versione 3.014 - pecciata la exof: eliminato fflush
versione 3.013 - Aggiunta stampa del pid nella prima printf su dbg (requires windows.h...)
versione 3.012 - Patchone exit
versione 3.011 - Aggiunta la funzione dbgmsg
versione 3.010 - Introdotta la funzione EXIT!
versione 3.009 - Divieto a Go!Zilla
versione 3.008 - Baco sulla TQR User in olimpybet eliminato
versione 3.007 - Multidebug con utime
versione 3.006b - aggiunta la *trim(a)
versione 3.005b - aggiunta la *sumf(a,b,dec)
versione 3.004b - aggiunto il comando *olimpybet() nell'ambito del progetto Olimpy-Bet per Wind
versione 3.003b - aggiunto il comando *SSDIR()
versione 3.002b - modificate getmad ed exeQ: la getmad raddoppia anche i doppi apici, la exeQ
li rimette a posto ( "" -> " )
versione 3.001b - corretto il GRAVISSIMO baco del parser per la pseudo-riallocazione del buffer
di uscita
versione 2.712b - rinominata la funzione di upload receiveFile in receiveAPPCFile; creata la
receive file, per ora inoperativa.
versione 2.711b - la storeTQR elimina eventuali apici dal parametro buffer.
versione 2.710b - aggiunta la funzione cfc (check for chars);
aggiunta la funzione flush (per lo svuotamento del buffer di output);
aggiunta la funzione uTime (universal time).
versione 2.702b - aggiunta la funzione execmd, modificata la setCookie e aggiunti i comandi:
getcoo, rtrim
versione 2.701b - aggiunta la funzione traceUser
versione 2.70b - versione con alcune estensioni per il supporto esteso di Store Procedure SQL Server
e del controllo dell'eventuale errore ODBC
versione 2.60b - sviluppo a dimensione per asweb;
versione 2.50b - Creata la pazzesca funzionalita' del preprocessing;
introdotte le funzioni *_nomeFunz: sempre preprocessabili ma equivalenti
alle preesistenti.
versione 2.01b - l'ereditarieta' dei blocchi condizionati viene attivata a livello di parser
e non piu' al livello delle singole funzioni ifblk ed elseblk
versione 2.004b - Corrette tutte le chiamate a storedData(0,..) con storedData(1,..).
Eliminato il Dump da una funzione.
Corretta la fillmsk (ITannit_CreateEnv al posto di ITannit_CreateEnv).
versione 2.003b - Aggiunta la funzione *recValLookAsStr ed aggiunto alla recValCnd il parametro
per la concatenazione in coda.
La recVal del record 0 (quello pirima del primo) viene forzata a "".
versione 2.002b - Aggiornati: *ifblk - da true senza operatore e con una stringa diversa da null
*fddate- previsto il caso gmmaaaa
versione 2.001b - Aggiunto l'else;
aggiunta la funzione setRec (nota: la cycleQ non resetta pi� il TQR
alla sua uscita);
cambiata la setVar in modo che possa modificare le variabili
gi� dichiarate
versione 2.0b - Completamente rivisti gli if e cycle (rimossi, tra l'altro, PANIC e DAMAGE!)
versione 1.266b - aggiunto il comando GASP *fconn per la prima connessione con AS400 (dimensione),
aggiunto il messaggio "appc enabled" al messaggio di info
versione 1.265b - aggiunti i comandi GASP *getP00, *fillmsk, *exeTP, *exist nel file tqrext.cpp ed
introdotta la funzione itxEscapeChars nel file cgic.cpp;
versione 1.264b - cambiate le malloc di dbInterface in CALLOC per inizializzare le righe;
versione 1.263b - supermegapatch su endCQ per contrastare i casini del patch PANIC;
(patch id: DAMAGE)
versione 1.262b - aggiunte le funzioni: *totRecs(dati), *actRec(dati), *maxRecs(dati),
*firstRec(dati), *moreRecs(dati,msg)
versione 1.261b - !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
pecchate le cycleQ e endCQ!!!
Monitorare la sitazione (patch id: PANIC)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
versione 1.260b - introdotto il nuovo comando *recCnd per concatenare in testa alla recVal una stringa;
versione 1.259b - introdotto il nuovo comando *getmad per raddoppiare gli apici in una stringa;
versione 1.258b - attivato il comando *remQ(nome_query) (funzione remQuery) nella funzionalita' di
renaming del TQR (Tannit Query Resultset);
versione 1.257b - aggiunte le due funzioni StoreTQR e TQRInsert. per l'implementazione delle due funzioni
� stato aggiunto il file tqrext.cpp.
versione 1.256b - patched version (senza le free critiche)
versione 1.255b - aggiunto il comando *cgipath() con la funzione writeCgiPath che scrive l'intero path
di arrivo alla cgi; aggiunto il parametro CgiName; aggiunto messaggio di errore al
fallimento di remBlindingChar (funzione per la cancellazione dei caratteri di inizio
e fine stringa della query)
versione 1.254b - realizzata la funzione di servizio dumpAround per la visualizzazione della memoria
attivalta la funzionalita' per il tracing opzionale dell'allocazione dei puntatori
(se il nome specificato per il file di debug contiene la stringa 'alloctrc' vengono
tracciati tutti gli indirizzi di tutte le malloc effettuate ed il numero di bytes
assegnati)
versione 1.253b - attivato l'uso del file di debug da file aggiuntivo (dbgname.par) di inizializzazione
definita la funzione remQ per la cancellazione delle strutture di dati da query
(non ancora attiva)
versione 1.252b - aggiunta la funzione revealBrowser (*revBr())
versione 1.251b - predisposto il bool usedbg per inibire da file par l'uso del debug (si devono
vaferizzare tutte le fprintf a debug)
versione 1.25b - Realizzati i commenti #ifdef _ITX_APPC nel file appccmp.cpp per isolare la versione
indipendente dallo SNA Server
versione 1.24b - nome del file di debug parametrizzato e proveniente dal parametro DbgPath nell par file
versione 1.23b - Situazione al 17 gennaio 2000 - AS400
versione 1.0b - Rilascio (beta) per dimensione con comunicazione SNASrever - AS400
versione 0.9b - versione stravolta da commentare ancora
versione 0.73b - funzione/comando translateIt per la gestione delle lingue
versione 0.72b - funzione/comando execInsQuery per le query di inserimento con campo identity:
la funzione esegue una query extra per conoscere il valore del massimo del
campo label e lo rende disponibile nella tabella "C" + "nome query"
versione 0.7b - compilata in C++ e collegata alla lib itannit (modulo per la comunicazione AS400)
versione 0.58b - comandi getId e extId
versione 0.58b - comandi setVar e getVar
versione 0.56b - messi nel file di inizializzazione il nome della tabella di
login ed i campi login e password per la funzione authorize
versione 0.55b - funzionalit� internazionali per il file di inizializzazione
*/
typedef struct StrStack_t
{
char *item;
struct StrStack_t *next;
} StrStack;
typedef struct TplVars
{
int idx;
char * values[TPL_VARS_NUM];
char * names[TPL_VARS_NUM];
} TplVarsStrct;
typedef struct MessagesStruct
{
int msgId;
char msg[ERR_MSG_LEN];
} MessagesSt;
/*command functions*/
void* writeWebUrl ( int, char*, char* );
void* writeHomeDir ( int, char*, char* );
void* writeCgiPath ( int, char*, char* );
void* writeImgDir ( int, char*, char* );
void* writeSSDir ( int, char*, char* );
void* execQuery ( int, char*, char* );
void* execInsQuery ( int, char*, char* );
void* remQuery ( int, char*, char* );
void* writeTotalRecords ( int, char*, char* );
void* writeActualRec ( int, char*, char* );
void* writeMaxRecords ( int, char*, char* );
void* writeFirstRecord ( int, char*, char* );
void* moreRecsMsg ( int, char*, char* );
void* recVal ( int, char*, char* );
void* recValCnd ( int, char*, char* );
void* recValConf ( int, char*, char* );
void* recValLookAsStr ( int, char*, char* );
void* cycleQuery ( int, char*, char* );
void* endCycleQuery ( int, char*, char* );
void* setActualRow ( int, char*, char* );
void* startCndBlk ( int, char*, char* );
void* elseCndBlk ( int, char*, char* );
void* endCndBlk ( int, char*, char* );
void* getValue ( int, char*, char* );
void* getmad ( int, char*, char* );
void* encrIt ( int, char*, char* );
void* crypt ( int, char*, char* );
void* decrypt ( int, char*, char* );
void* authorize ( int, char*, char* );
void* validate ( int, char*, char* );
void* exitOnFile ( int, char*, char* );
void* syntChk ( int, char*, char* );
void* setVar ( int, char*, char* );
void* getVar ( int, char*, char* );
void* extrIdG ( int, char*, char* );
void* extrId ( int, char*, char* );
void* translateIt ( int, char*, char* );
void* processExternFile ( int, char*, char* );
void* setCookie ( int, char*, char* );
void* writeCorrAppDir ( int, char*, char* );
void* writeCorrFileName ( int, char*, char* );
void* isInTheDomain ( int, char*, char* );
void* validAleph ( int, char*, char* );
void* fontStyle ( int, char*, char* );
void* revealBrowser ( int, char*, char* );
void* StoreTQR ( int, char*, char* );
void* TQRInsert ( int, char*, char* );
void* getP00 ( int, char*, char* );
void* exeTP ( int, char*, char* );
void* fillmsk ( int, char*, char* );
void* writeSpan ( int, char*, char* );
void* verCookie ( int, char*, char* );
void* now ( int, char*, char* );
void* exist ( int, char*, char* );
void* firstConn ( int, char*, char* );
void* ckcli ( int, char*, char* );
void* formatDimDate ( int, char*, char* );
void* splitREA ( int, char*, char* );
void* dimDataMagic ( int, char*, char* );
void* subtractIt ( int, char*, char* );
void* sumFloat ( int, char*, char* );
void* parval ( int, char*, char* );
void* switchTplTgt ( int, char*, char* );
void* filterTqr ( int, char*, char* );
void* putGetHide ( int, char*, char* );
void* setTQRValues ( int, char*, char* );
void* pkdate ( int, char*, char* );
void* prmTunnel ( int, char*, char* );
void* dimFormatCurrency ( int, char*, char* );
void* divideInt ( int, char*, char* );
void* formatDimCap ( int, char*, char* );
void* formatDimNACE ( int, char*, char* );
void* formatDimVia ( int, char*, char* );
void* uppercaseIt ( int, char*, char* );
void* putTplName ( int, char*, char* );
void* formatDimNaz ( int, char*, char* );
void* traceUser ( int, char*, char* );
//version 2.7 specific
void* invoke ( int, char*, char* );
void* execmd ( int, char*, char* );
void* getcoo ( int, char*, char* );
void* rtrim ( int, char*, char* );
void* trim ( int, char*, char* );
void* cfc ( int, char*, char* );
void* flush ( int, char*, char* );
void* uTime ( int, char*, char* );
void* uTimeToDMY ( int, char*, char* );
void* olimpybet ( int, char*, char* );
void* dbgmsg ( int, char*, char* );
void* quotestr ( int, char*, char* );
void* exeQnew(int vuoto1,char *vuoto2, char * inputStr);
/*command support function*/
int pickPar(char* inputStr, int position, char ** returnStr);
/*program functions*/
int cgiMain ();
int queryIndex (char * queryId, int noexit);
int pushStk (StrStack** ,char*);
int popStk (StrStack** ,char** );
int bufferTpl ( char **, char*, char * );
int procTplData ( char*, FILE*, char**);
char* readPar ( const char *,const char * , FILE * );
int readIniPars ();
void trimIt (char * );
int verVersion ();
int initGlobals ();
int popStk (StrStack** stack, char **strg );
int pushStk (StrStack** stack, char *strg );
int getline (char s[], int lim);
int sendFile ();
int dndConfirm ();
int receiveFile ();
int receiveAPPCFile ();
void sendBack (int flagCode);
void sendTransStart (int download, int fileLen);
int checkDbPwd (char* login, char* cpwd, char*, char*);
char* retMsg (int msgId);
void newAutoName ();
void dumpAround (char * refPtr, int strtChr, int chrnum);
void redirectExit (char* filename);
void listTQRnames ();
int capturePreproc (char ** tplString, FILE ** refinedTplFp);
char* storedData (int , char * , char * , int *);
int dbInterface (char * , char * , int , int );
void EXIT (int retval);
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
// AITECSA s.r.l. 2000
// filename: tqrext.cpp
// description: tannitqueryresult manipolation functions from
// client inputs and various tannit template command extensions
// project: tannit
#ifndef __ITX_TQREXT_CPP__
#define __ITX_TQRTEXT_CPP__
#endif
#include "tannit.h"
#include "itannitc.h"
#include "extVars.h"
#include "itxtypes.h"
#define ECHO_KEYWORD "echo"
#define TRAK_KEYWORD "trak"
#define TQR_TABLE_SEP "__"
#define TQR_FIELD_SEP "_"
extern cgiFormEntry *cgiFormEntryFirst;
void redirectExit(char* filename)
{
char * tplStr, *outputStr;
if (filename != NULL)
{
bufferTpl(&tplStr, filename, TplDir);
procTplData(tplStr, cgiOut, &outputStr);
//fflush(cgiOut);
}
EXIT(1);
}
/*************************************************************************************
NOME : StoreTQR
Categoria : Gasp Command: StoreTQR(nomeTQR,numCols,separatori,valBuffer)
attivita' : permette di creare (se necessario) una nuova TQR ed inserirvi i valori
contenuti nel buffer.
- nomeTQR : nome del TQR da inserire
- numCols : numero delle colonne
- separatori: separatori di campo e di record
- valBuffer : buffer dei valori con separatori
*************************************************************************************/
void* StoreTQR(int vuoto1, char *vuoto2, char * inputStr)
{
char* tqrname;
char* sep;
char* buffer;
char* nfields;
char fieldsep, recsep;
itxString istr;
if(!pickPar(inputStr, 1, &tqrname )) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &nfields )) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 3, &sep )) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 4, &buffer )) return(PARAM_NOT_FOUND_MSG);
/**/if(usedbg){fprintf(debug, "StoreTQR buffer: %s\n", buffer);fflush(debug);}
istr.InBlinder(&buffer, '\x27');
/**/if(usedbg){fprintf(debug, "StoreTQR buffer: %s\n", buffer);fflush(debug);}
fieldsep = *(sep);
recsep = *((char*)(sep+1));
ITannit_Create(QueryResultSet, &QueryCounter);
ITannit_NewEntry(tqrname, atoi(nfields));
ITannit_ParsTP(tqrname, buffer, 0, 0, debug, recsep, fieldsep);
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: TQRInsert
attivita' : trasferisce il TQR indicato nel database.
par 1 : nome del TQR da inserire
par 2 : nome della tabella target
*************************************************************************************/
void* TQRInsert(int vuoto1, char *vuoto2, char * inputStr)
{
char* tqrname;
char* tablename;
if(!pickPar(inputStr, 1, &tqrname)) return(PARAM_NOT_FOUND_MSG);
if(!pickPar(inputStr, 2, &tablename)) return(PARAM_NOT_FOUND_MSG);
ITannit_Create(QueryResultSet, &QueryCounter);
ITannit_FillTQRColsInfoFromSQL(Odbcdsn, Odbcuid, Odbcpwd, tqrname, tablename);
ITannit_ConnectSQL(Odbcdsn, Odbcuid, Odbcpwd);
ITannit_BulkInsertSQL(debug, tablename, tqrname, NULL);
ITannit_DisconnectSQL();
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: getP00 (ASWEB Specific)
attivita' : recupera i dati di connessione utente dal database.
par 1 : identificativo dell'utente
*************************************************************************************/
void *getP00(int vuoto1, char *vuoto2, char * inputStr)
{
char* username;
if(!pickPar(inputStr, 1, &username)) return(PARAM_NOT_FOUND_MSG);
ITannit_Create(QueryResultSet, &QueryCounter);
// ITannit_GetP00FromSQL(Odbcdsn, Odbcuid, Odbcpwd, username, debug);
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: fillmsk
attivita' : scandisce i parametri di Form alla ricerca della maschera del tipo
TQR_TABLE_SEPtable_nameTQR_FIELD_SEPfield_name
ha tre modalit� di lavoro a seconda dei parametri passati:
NessunParametro : inserisce nel TQR omonimo il valore associato al field
trak : come sopra ma ritorna la lista separata da virgole dei TQR modificati
echo : riinvia sul cgiOut gli stessi parametri ripristinando i caratteri escape
par 1 : null, trak o echo
*************************************************************************************/
void *fillmsk(int vuoto1, char *vuoto2, char * inputStr)
{
cgiFormEntry *e;
char table[32];
char field[32];
static char trak[1024];
char* value;
char* ptable;
char* pfield;
TannitQueryResult* qres = NULL;
int fieldnum = 0;
char* echoflag = NULL;
int retval = 0;
itxString istr;
/**/if(usedbg){fprintf(debug, "fillmsk---START\n");fflush(debug);}
retval = pickPar(inputStr, 1, &echoflag);
/**/if(usedbg){if (echoflag != NULL){fprintf(debug, "esamining echoflag: %s\n", echoflag);fflush(debug);}}
if(retval == PARAM_NOT_FOUND)
{
ITannit_Create(QueryResultSet, &QueryCounter);
e = cgiFormEntryFirst;
while (e != NULL)
{
memset(table, '\0', 32);
memset(field, '\0', 32);
/**/if(usedbg){fprintf(debug, "esamining cgiFormEntry: %s\n", e->attr);fflush(debug);}
if ((ptable = strstr(e->attr, TQR_TABLE_SEP)) == e->attr)
{
/**/if(usedbg){fprintf(debug, "processing cgiFormEntry: %s\n", e->attr);fflush(debug);}
value = e->value;
if ((pfield = (char*)((strstr((char*)(ptable + 2), TQR_FIELD_SEP)) + 1)) != 0)
{
strcpy(field, pfield);
memcpy(table, (char*)(ptable + 2), (size_t)((size_t)pfield - (size_t)ptable - 3));
/**/if(usedbg){fprintf(debug, " table: %s\n", table);fflush(debug);}
/**/if(usedbg){fprintf(debug, " field: %s\n", field);fflush(debug);}
fieldnum = 0;
if ((fieldnum = ITannit_GetTPFields(table)) != 0)
{
if ((qres = ITannit_NewEntry(table, fieldnum)) != NULL)
{
_strupr(value);
ITannit_StoreValue(qres, field, value);
}
}
}
}
e = e->next;
}
//**/if(usedbg){ ITannit_Dump(debug);}
ITannit_Destroy();
return 0;
}
/**/if(usedbg){if (echoflag != NULL){fprintf(debug, "esamining echoflag: %s\n", echoflag);fflush(debug);}}
if (ISEQUAL(ECHO_KEYWORD, echoflag))
{
e = cgiFormEntryFirst;
while (e != NULL)
{
memset(table, '\0', 32);
memset(field, '\0', 32);
/**/if(usedbg){fprintf(debug, "esamining cgiFormEntry: %s\n", e->attr);fflush(debug);}
if ((ptable = strstr(e->attr, TQR_TABLE_SEP)) == e->attr)
{
/**/if(usedbg){fprintf(debug, "processing cgiFormEntry: %s\n", e->attr);fflush(debug);}
value = e->value;
if ((pfield = (char*)((strstr((char*)(ptable + 2), TQR_FIELD_SEP)) + 1)) != 0)
{
strcpy(field, pfield);
memcpy(table, (char*)(ptable + 2), (size_t)((size_t)pfield - (size_t)ptable - 3));
/**/if(usedbg){fprintf(debug, " table: %s\n", table);fflush(debug);}
/**/if(usedbg){fprintf(debug, " field: %s\n", field);fflush(debug);}
char* rvalue;
istr.EscapeChars(value, &rvalue);
fprintf(cgiOut, "&%s%s%s%s=%s", TQR_TABLE_SEP, table, TQR_FIELD_SEP, field, rvalue);
}
}
e = e->next;
}
return 0;
}
if (ISEQUAL(TRAK_KEYWORD, echoflag))
{
memset(trak, '\0', 1024);
ITannit_Create(QueryResultSet, &QueryCounter);
e = cgiFormEntryFirst;
while (e != NULL)
{
memset(table, '\0', 32);
memset(field, '\0', 32);
/**/if(usedbg){fprintf(debug, "esamining cgiFormEntry: %s\n", e->attr);fflush(debug);}
if ((ptable = strstr(e->attr, TQR_TABLE_SEP)) == e->attr)
{
/**/if(usedbg){fprintf(debug, "processing cgiFormEntry: %s\n", e->attr);fflush(debug);}
value = e->value;
if ((pfield = (char*)((strstr((char*)(ptable + 2), TQR_FIELD_SEP)) + 1)) != 0)
{
strcpy(field, pfield);
memcpy(table, (char*)(ptable + 2), (size_t)((size_t)pfield - (size_t)ptable - 3));
/**/if(usedbg){fprintf(debug, " table: %s\n", table);fflush(debug);}
/**/if(usedbg){fprintf(debug, " field: %s\n", field);fflush(debug);}
if (strstr(trak, table) == 0)
{
strcat(trak, table);
strcat(trak, ",");
}
fieldnum = 0;
if ((fieldnum = ITannit_GetTPFields(table)) != 0)
{
if ((qres = ITannit_NewEntry(table, fieldnum)) != NULL)
{
_strupr(value);
ITannit_StoreValue(qres, field, value);
}
}
}
}
e = e->next;
}
trak[strlen(trak) - 1] = 0;
//**/if(usedbg){ ITannit_Dump(debug);}
ITannit_Destroy();
return trak;
}
return UNABLE_TO_WRITE_VAR;
}
/*************************************************************************************
Categoria : Gasp Command: *tunnel
attivita' : scandisce i parametri di Form alla ricerca della maschera del tipo
PRM_TUNNEL_TAGparameter_name
e rinvia sul cgiOut gli stessi parametri in formato di url
&prm1_name=prm_value&prm2_name=prm_value&prm3_name=prm_value&...
*************************************************************************************/
void *prmTunnel(int vuoto1, char *vuoto2, char * inputStr)
{
char *separator;
cgiFormEntry *e;
static char appo[256];
char * retval;
char * maskedPar[512];
itxString istr;
/**/if(usedbg){fprintf(debug, "TUNNEL: START\n");fflush(debug);}
if ((retval = (char*)calloc(4096, sizeof(char))) == NULL)
return NULL;
if(pickPar(inputStr, 1, &separator))
{
istr.InBlinder(&separator, BLINDER);
e = cgiFormEntryFirst;
while (e != NULL)
{
if ( strstr(e->attr, PRM_TUNNEL_TAG) != 0)
{
sprintf(appo, "%s%s", e->attr, separator);
strcat(retval, appo);
}
e = e->next;
}
}
else
{
int k = 0;
e = cgiFormEntryFirst;
while (e != NULL)
{
if ( strstr(e->attr, PRM_TUNNEL_TAG) != 0)
{
istr.EscapeChars(e->value,&(maskedPar[k]));
sprintf(appo, "&%s=%s", e->attr, maskedPar[k]);
strcat(retval, appo);
}
k++;
e = e->next;
}
}
/**/if(usedbg){fprintf(debug, "TUNNEL: END\n");fflush(debug);}
return retval;
}
/*************************************************************************************
Categoria : Gasp Command: exeTP (ASWEB Specific)
attivita' : scandisce la inputStr per recuperare tutti i TQR con cui costruire il buffer
da inviare ad AS400. Supporta un massimo di 20 TP.
par vars : a parametri variabili. Nomi di altrettanti TQR.
*************************************************************************************/
void *exeTP(int vuoto1, char *vuoto2, char * inputStr)
{
int retval = 0;
int param = 1;
char* tp[20];
char* returned_buffer = NULL;
TannitQueryResult* qres = NULL;
TannitQueryResult* p00 = NULL;
TannitQueryResult* h00 = NULL;
char * sempreY;
sempreY = (char*)calloc(2, sizeof(char));
sempreY[0]='Y';
sempreY[1]='\0';
memset(tp, 0, 20 * sizeof(char*));
/**/if(usedbg){fprintf(debug, "exeTP---START\n");fflush(debug);}
#ifdef _ITX_APPC
ITannit_CreateEnv(QueryResultSet, &QueryCounter, Llu, Rtp);
while ((retval = pickPar(inputStr, param, &(tp[param-1]))) != PARAM_NOT_FOUND)
{
/**/if(usedbg){fprintf(debug, "%s\n", tp[param-1]);fflush(debug);}
// original patch (it works only if H00 has benn loaded in memory)
if (ISEQUAL(tp[param-1], "HBB") || ISEQUAL(tp[param-1], "HBA"))
{
p00 = ITannit_FindQuery("P00");
h00 = ITannit_FindQuery("H00");
p00->recPtr->row[17] = sempreY;
// p00->recPtr->row[17] = h00->recPtr->row[36];
}
param++;
}
if ((returned_buffer = ITannit_TPExecute(ITX_APPC_PC_REQ, 1, debug,
tp[0], tp[1], tp[2], tp[3], tp[4], tp[5],
tp[6], tp[7], tp[8], tp[9], tp[10], tp[11],
tp[12], tp[13], tp[14], tp[15], tp[16], tp[17],
tp[18], tp[19], NULL)) == NULL)
{
if ((qres = ITannit_NewEntry("ConnectErr", 3)) != NULL)
ITannit_StoreValue(qres, "f1", "AS400");
}
ITannit_Destroy();
#endif
return 0;
}
/*************************************************************************************
Nome : setTQRValues
Categoria : Gasp Command: tqrval (TQRname,recordToMod,field1Name,field1Val,...)
attivita' : scandisce la inputStr per recuperare tutti i valori da inserire nel TQR
- TQRname : nome del TQR
- recordToMod : posizione in base 1 del record da modificare
- field1Name,field1Val,...:
numero variabile di coppie di valori 'nome campo', 'valore'
*************************************************************************************/
void *setTQRValues(int vuoto1, char *vuoto2, char * inputStr)
{
char* tqrname = NULL;
char* trownumber = NULL;
char* fieldname = NULL;
char* fieldvalue = NULL;
itxString istr;
TannitQueryResult* qres = NULL;
int rownumber;
int numpar;
/**/if(usedbg){fprintf(debug, "tqrval Started\n%s\n", inputStr);fflush(debug);}
if(!pickPar(inputStr, 1, &tqrname )) return(PARAM_NOT_FOUND_MSG);
//**/if(usedbg){fprintf(debug, "FOUND %s\n", tqrname);fflush(debug);}
if(!pickPar(inputStr, 2, &trownumber)) return(PARAM_NOT_FOUND_MSG);
//**/if(usedbg){fprintf(debug, "%s\n", trownumber);fflush(debug);}
if(!pickPar(inputStr, 3, &fieldname)) return(PARAM_NOT_FOUND_MSG);
//**/if(usedbg){fprintf(debug, "%s\n", fieldname);fflush(debug);}
if(!pickPar(inputStr, 4, &fieldvalue)) return(PARAM_NOT_FOUND_MSG);
istr.InBlinder(&fieldvalue, BLINDER);
/**/if(usedbg){fprintf(debug, "%s\n", fieldvalue);fflush(debug);}
rownumber = atoi(trownumber);
/**/if(usedbg){fprintf(debug, "%d\n", rownumber);fflush(debug);}
ITannit_Create(QueryResultSet, &QueryCounter);
if ((qres = ITannit_FindQuery(tqrname)) == NULL)
return 0;
ITannit_SetCurrentRecord(qres, rownumber);
ITannit_StoreValue(qres, fieldname, fieldvalue);
numpar = 5;
while ((pickPar(inputStr, numpar, &fieldname) == PARAM_FOUND) &&
(pickPar(inputStr, numpar + 1, &fieldvalue) == PARAM_FOUND))
{
istr.InBlinder(&fieldvalue, BLINDER);
//**/if(usedbg){fprintf(debug, "%s\n", fieldname);fflush(debug);}
//**/if(usedbg){fprintf(debug, "%s\n", fieldvalue);fflush(debug);}
ITannit_StoreValue(qres, fieldname, fieldvalue);
numpar += 2;
}
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: *verCoo(OPZdeltaT)
attivita' : verifica che il Cookie di tipo ITXCOO del client sia valido: ovvero non sia stato
creato o aggiornato pi� di deltat secondi prima del momento del check.
OPZdeltaT : opzionale: se presente � il deltat da utilizzare, se non presente si prende il
deltat del file di parametri e se non si trova si utilizza il deltat definito
come ITXCOO_TIME_DELAY (10.000 secondi).
*************************************************************************************/
void *verCookie(int vuoto1, char *vuoto2, char * inputStr)
{
int retval = 0;
char* login = NULL;
char* efile = NULL;
char* strdeltat = NULL;
char* cooName = NULL;
char* ptime = NULL;
char* plogin = NULL;
char* pcoo = NULL;
char* pcomma = NULL;
char decoo[256];
time_t deltat = 0;
time_t now;
time_t before;
time(&now);
memset(decoo, '\0', 256);
/**/if(usedbg){fprintf(debug, "verCookie---START\n");fflush(debug);}
if( !pickPar( inputStr, 1, &cooName ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 2, &login ) ) return(PARAM_NOT_FOUND_MSG);
if( !pickPar( inputStr, 3, &efile ) ) return(PARAM_NOT_FOUND_MSG);
retval = pickPar(inputStr, 4, &strdeltat);
deltat = ITXCOO_TIME_DELAY;
if(retval == PARAM_NOT_FOUND)
{
if (!ISNULL(CooTimeDelay))
deltat = atoi(CooTimeDelay);
}
else
deltat = atoi(strdeltat);
plogin = decoo;
/**/if(usedbg){fprintf(debug, "verCookie---cgiCookie:%s\n",cgiCookie);fflush(debug);}
if ((pcoo = strstr(cgiCookie,cooName)) != 0)
{
pcoo = pcoo + strlen(cooName);
pcomma = strstr(pcoo, ";");
if (pcomma != 0)
{
*pcomma = '\0';
}
}
/**/if(usedbg){fprintf(debug, "verCookie---pcoo:%s\n",pcoo);fflush(debug);}
tannitDecrypt(pcoo, decoo);
/**/if(usedbg){fprintf(debug, "verCookie---decoo:%s\n",decoo);fflush(debug);}
if ((ptime = strstr(decoo,ITXCOO_SEP)) == 0)
{
redirectExit(efile);
}
/**/if(usedbg){fprintf(debug, "verCookie---decoo:%s\n",decoo);fflush(debug);}
*ptime = '\0';
/**/if(usedbg){fprintf(debug, "verCookie---decoo:%s\n",decoo);fflush(debug);}
ptime++;
/**/if(usedbg){fprintf(debug, "verCookie---decoo:%s\n",decoo);fflush(debug);}
if (!ISEQUAL(login, plogin))
{
redirectExit(efile);
}
before = atoi(ptime);
if (deltat < (now - before))
{
redirectExit(efile);
}
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: *now(OPZflag)
attivita' : restituisce il numero di secondi passati dalla mezzanote del 1.1.1970
(universal time); se � presente il parametro opzionale restituisce, a
seconda del valore di quest'ultimo,
d - il giorno corrente
m - il mese corrente
y - l'anno corrente
*************************************************************************************/
void *now(int vuoto1, char *vuoto2, char * inputStr)
{
static char rsec[256];
time_t tm;
struct tm *today;
char* part;
time(&tm);
today = localtime(&tm);
memset(rsec, '\0', 256);
sprintf(rsec, "%ld", tm);
if(pickPar(inputStr, 1, &part))
{
/**/if(usedbg){fprintf(debug, "NOW-part %s\n",part);fflush(debug);}
if (ISEQUAL(part, "d"))
strftime(rsec, 256,"%d", today);
else if (ISEQUAL(part, "m"))
strftime(rsec, 256,"%m", today);
else if (ISEQUAL(part, "y"))
strftime(rsec, 256,"%Y", today);
}
return rsec;
}
/*************************************************************************************
Categoria : Gasp Command: *pkdate(sdate)
attivita' : torna la data senza caratteri '/' es:
11/12/1999 diventa 11121999
*************************************************************************************/
void *pkdate(int vuoto1, char *vuoto2, char * inputStr)
{
static char rsec[256];
char dd[3];
char mm[3];
char yy[5];
char* sdate;
char* pos;
int l;
if(!pickPar(inputStr, 1, &sdate)) return(PARAM_NOT_FOUND_MSG);
memset(rsec, '\0', 256);
memset(dd, '\0', 3);
memset(mm, '\0', 3);
memset(yy, '\0', 5);
memset(dd, '0', 2);
memset(mm, '0', 2);
//locate day
if ((pos = strtok(sdate, "/")) == NULL) return rsec;
if ((l = strlen(pos)) > 2) return rsec;
memcpy(dd, pos + 2 - l, l);
//locate month
if ((pos = strtok(NULL, "/")) == NULL) return rsec;
if ((l = strlen(pos)) > 2) return rsec;
memcpy(mm, pos + 2 - l, l);
//locate year
if ((pos = strtok(NULL, "/")) == NULL) return rsec;
if ((l = strlen(pos)) != 4) return rsec;
memcpy(yy, pos, l);
sprintf(rsec, "%s%s%s", dd, mm, yy);
return rsec;
}
/*************************************************************************************
Categoria : Gasp Command: exist
attivita' : ritorna la true o false a seconda se esiste il TQR richiesto
*************************************************************************************/
void *exist(int vuoto1, char *vuoto2, char * inputStr)
{
char* tqrname;
TannitQueryResult* qres;
if(!pickPar(inputStr, 1, &tqrname)) return(PARAM_NOT_FOUND_MSG);
ITannit_Create(QueryResultSet, &QueryCounter);
qres = ITannit_FindQuery(tqrname);
ITannit_Destroy();
if (qres == NULL)
return TANNIT_FALSE;
else
return TANNIT_TRUE;
}
/*************************************************************************************
Categoria : Gasp Command: *fconn(escapeFile,login,lid)
attivita' : prima connessione all'AS400 e caricamento dell'H00 su SQLServer;
i TQR H00, P00 e listini vengono anche caricati in memoria.
Effettua inoltre il controllo dell'accesso dell'utente: in caso di accesso
non autorizzato si esce su escapeFile
*************************************************************************************/
void *firstConn(int vuoto1, char *vuoto2, char * inputStr)
{
char *login, *lid, *escapeFile;
TannitQueryResult *qerr =NULL;
if(!pickPar(inputStr, 1, &escapeFile ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &login ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 3, &lid ) ) redirectExit(ITX_MISINTER);
#ifdef _ITX_APPC
ITannit_CreateEnv(QueryResultSet, &QueryCounter, Llu, Rtp);
if (!ITannit_FirstConn(Odbcdsn, Odbcuid, Odbcpwd, login, lid, debug))
{
/**/if(usedbg){fprintf(debug, "firstConn; ITannit_FirstConn could not establish a valid connection\n");fflush(debug);}
redirectExit(escapeFile);
return 0;
}
#endif
/**/if(usedbg){ITannit_Dump(debug);fflush(debug);}
// controllo se FirstConn abbia generato un errore lato server
qerr = ITannit_FindQuery("E00");
if (qerr != 0)
{
/**/if(usedbg){fprintf(debug, "firstConn; malicious error: exiting\n");fflush(debug);}
redirectExit(escapeFile);
}
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: *ckcli(escapeFile,codice_cliente,codice_contratto)
attivita' : convalida l'utente, in caso di errore ridireziona su escapeFile
*************************************************************************************/
void *ckcli(int vuoto1, char *vuoto2, char * inputStr)
{
char *codCliente, *codContratto, *escapeFile;
int errCode;
char *ccli, *ccon;
if(!pickPar(inputStr, 1, &escapeFile ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &codCliente ) ) redirectExit(escapeFile);
if(!pickPar(inputStr, 3, &codContratto ) ) redirectExit(escapeFile);
ccli = storedData(1, "f4", "P00", &errCode);
if ( errCode == ERR_COL_NOT_FOUND || errCode == ERR_QUERY_NOT_FOUND || errCode == ERR_VOID_QUERY_NAME )
{
/**/if(usedbg){fprintf(debug, "firstConn; login error 1: exiting\n");fflush(debug);}
redirectExit(escapeFile);
}
ccon = storedData(1, "f5", "H00", &errCode);
if ( errCode == ERR_COL_NOT_FOUND || errCode == ERR_QUERY_NOT_FOUND || errCode == ERR_VOID_QUERY_NAME )
{
/**/if(usedbg){fprintf(debug, "firstConn; login error 2: exiting\n");fflush(debug);}
redirectExit(escapeFile);
}
if (!(ISEQUAL(ccli, codCliente) && ISEQUAL(ccon, codContratto)))
{
/**/if(usedbg){fprintf(debug, "firstConn; login error 3: exiting\n");fflush(debug);}
redirectExit(escapeFile);
}
// se tutti i controlli sono andati a buon fine si va avanti felici
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: *fddate(31122009)
attivita' : riformatta la data di esempio in: 31/12/2009
*************************************************************************************/
void *formatDimDate(int vuoto1, char *vuoto2, char * inputStr)
{
char *dataGrezza;
static char dataRaffinata[12];
memset(dataRaffinata, 0, 12);
pickPar(inputStr, 1, &dataGrezza);
if (strlen(dataGrezza) == 8)
sprintf(dataRaffinata, "%c%c/%c%c/%c%c%c%c",
dataGrezza[0],
dataGrezza[1],
dataGrezza[2],
dataGrezza[3],
dataGrezza[4],
dataGrezza[5],
dataGrezza[6],
dataGrezza[7]
);
else if (strlen(dataGrezza) == 7)
sprintf(dataRaffinata, "%c/%c%c/%c%c%c%c",
dataGrezza[0],
dataGrezza[1],
dataGrezza[2],
dataGrezza[3],
dataGrezza[4],
dataGrezza[5],
dataGrezza[6]
);
else if (strlen(dataGrezza) == 6)
sprintf(dataRaffinata, "%c%c/%c%c%c%c",
dataGrezza[0],
dataGrezza[1],
dataGrezza[2],
dataGrezza[3],
dataGrezza[4],
dataGrezza[5]
);
else if (strlen(dataGrezza) == 5)
sprintf(dataRaffinata, "%c/%c%c%c%c",
dataGrezza[0],
dataGrezza[1],
dataGrezza[2],
dataGrezza[3],
dataGrezza[4]
);
return dataRaffinata;
}
/*************************************************************************************
Categoria : Gasp Command: *fdcap(100)
attivita' : riformatta il cap di esempio in: 00100
*************************************************************************************/
void *formatDimCap(int vuoto1, char *vuoto2, char * inputStr)
{
char *capGrezzo;
static char capRaffinato[6];
memset(capRaffinato, 0, 6);
pickPar(inputStr, 1, &capGrezzo);
if (strlen(capGrezzo) == 0)
sprintf(capRaffinato, "");
else if (strlen(capGrezzo) == 1)
sprintf(capRaffinato, "0000%c",
capGrezzo[0]
);
else if (strlen(capGrezzo) == 2)
sprintf(capRaffinato, "000%c%c",
capGrezzo[0],
capGrezzo[1]
);
else if (strlen(capGrezzo) == 3)
sprintf(capRaffinato, "00%c%c%c",
capGrezzo[0],
capGrezzo[1],
capGrezzo[2]
);
else if (strlen(capGrezzo) == 4)
sprintf(capRaffinato, "0%c%c%c%c",
capGrezzo[0],
capGrezzo[1],
capGrezzo[2],
capGrezzo[3]
);
else if (strlen(capGrezzo) == 5)
sprintf(capRaffinato, "%s", capGrezzo );
return capRaffinato;
}
/*************************************************************************************
Categoria : Gasp Command: *fdnace(123) ->123
*fdnace(1234) ->123.4
*fdnace(12345) ->123.45
*fdnace(123456) ->123.45.6
*fdnace(1234567)->123.45.67
attivit� : riformatta i codici NACE come negli esempi
*************************************************************************************/
void *formatDimNACE(int vuoto1, char *vuoto2, char * inputStr)
{
char *naceGrezzo;
static char naceRaffinato[11];
memset(naceRaffinato, 0, 11);
pickPar(inputStr, 1, &naceGrezzo);
if (strlen(naceGrezzo) == 0)
sprintf(naceRaffinato, "");
else if (strlen(naceGrezzo) == 1)
sprintf(naceRaffinato, "%c",
naceGrezzo[0]
);
else if (strlen(naceGrezzo) == 2)
sprintf(naceRaffinato, "%c%c",
naceGrezzo[0],
naceGrezzo[1]
);
else if (strlen(naceGrezzo) == 3)
sprintf(naceRaffinato, "%c%c%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2]
);
else if (strlen(naceGrezzo) == 4)
sprintf(naceRaffinato, "%c%c%c.%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2],
naceGrezzo[3]
);
else if (strlen(naceGrezzo) == 5)
sprintf(naceRaffinato, "%c%c%c.%c%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2],
naceGrezzo[3],
naceGrezzo[4]
);
else if (strlen(naceGrezzo) == 6)
sprintf(naceRaffinato, "%c%c%c.%c%c.%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2],
naceGrezzo[3],
naceGrezzo[4],
naceGrezzo[5]
);
else if (strlen(naceGrezzo) == 7)
sprintf(naceRaffinato, "%c%c%c.%c%c.%c%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2],
naceGrezzo[3],
naceGrezzo[4],
naceGrezzo[5],
naceGrezzo[6]
);
else if (strlen(naceGrezzo) == 8)
sprintf(naceRaffinato, "%c%c%c.%c%c.%c%c%c",
naceGrezzo[0],
naceGrezzo[1],
naceGrezzo[2],
naceGrezzo[3],
naceGrezzo[4],
naceGrezzo[5],
naceGrezzo[6],
naceGrezzo[7]
);
return naceRaffinato;
}
/*************************************************************************************
Categoria : Gasp Command: *splitREA(RE175873,1) oppure *splitREA(RE175873,2)
attivita' : ritorna RE oppure 175873
*************************************************************************************/
void *splitREA(int vuoto1, char *vuoto2, char * inputStr)
{
char *reaGrezzo, *trimTypeSt;
static char reaRaffinato[16];
int trimType = 0;
memset(reaRaffinato, 0, 16);
if(!pickPar(inputStr, 1, &reaGrezzo ) ) redirectExit(ITX_MISINTER);
if( pickPar(inputStr, 2, &trimTypeSt ) ) trimType = atoi(trimTypeSt);
if (trimType == 0)
sprintf(reaRaffinato, "%s", reaGrezzo);
else if (trimType == 1)
sprintf(reaRaffinato, "%c%c", reaGrezzo[0], reaGrezzo[1]);
else if (trimType == 2)
sprintf(reaRaffinato, "%s", &(reaGrezzo[2]) );
else
sprintf(reaRaffinato, "REA_FLAG_ERROR");
return reaRaffinato;
}
/*************************************************************************************
Categoria : Gasp Command: *dimDataMagic(dataGrezza,tqrName)
attivita' : crea un TQR di nome tqrName con due campi: il primo con la data in formato
grezzo (11121999) ed il secondo in formato classico (11/12/1999)
se sono presenti pi� date concatenate aggiunge record al TQR
*************************************************************************************/
void *dimDataMagic(int vuoto1, char *vuoto2, char * inputStr)
{
char *dataGrezza, *tqrName, *p;
char pezzoDiData[9];
char cData[11];
unsigned int i = 0, len = 0;
if(!pickPar(inputStr, 1, &dataGrezza ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &tqrName ) ) redirectExit(ITX_MISINTER);
trimIt(dataGrezza);
p = dataGrezza;
len = strlen(dataGrezza);
if (len == 0 || (len % 8) != 0)
return 0;
ITannit_Create(QueryResultSet, &QueryCounter);
QQres = ITannit_NewEntry(tqrName, 2);
i = 0;
while (i < len)
{
memset(pezzoDiData, 0, 9);
memset(cData, 0, 11);
memcpy(pezzoDiData, p, 8);
memcpy(cData, (char*)formatDimDate(0,0,pezzoDiData), 10);
ITannit_StoreRecord(tqrName, cData, pezzoDiData, NULL);
p += 8;
i += 8;
}
ITannit_Destroy();
return 0;
}
/*************************************************************************************
Categoria : Gasp Command: *sottra(sottraendo, sottrattore)
*************************************************************************************/
void *subtractIt(int vuoto1, char *vuoto2, char * inputStr)
{
char *sottraendoSt, *sottrattoreSt;
long int risultato, sottraendo = 0, sottrattore = 0;
static char result[64];
if(!pickPar(inputStr, 1, &sottraendoSt ) ) redirectExit(ITX_MISINTER);
if( pickPar(inputStr, 2, &sottrattoreSt ) ) sottrattore = atoi(sottrattoreSt);
sottraendo = atoi(sottraendoSt);
risultato = sottraendo - sottrattore;
sprintf(result, "%d", risultato);
return result;
}
/*************************************************************************************
Categoria : Gasp Command: *sumf(addendo, addendo, OPZdecimali)
*************************************************************************************/
void *sumFloat(int vuoto1, char *vuoto2, char * inputStr)
{
char *add1St, *add2St, *decimaliSt;
int decimali=0;
double risultato = 0.0, add1 = 0.0, add2 = 0.0;
static char result[128];
static char formato[16];
sprintf(formato,"%%f");
if(!pickPar(inputStr, 1, &add1St ) ) redirectExit(ITX_MISINTER);
if( pickPar(inputStr, 2, &add2St ) ) add2 = atof(add2St);
if( pickPar(inputStr, 3, &decimaliSt) ) sprintf(formato,"%%.%sf",decimaliSt);
add1 = atof(add1St);
risultato = add1 + add2;
sprintf(result, formato, risultato);
return result;
}
/*************************************************************************************
Categoria : Gasp Command: *divint(dividendo, divisore)
Note : ritorna un intero approssimato.
*************************************************************************************/
void *divideInt(int vuoto1, char *vuoto2, char * inputStr)
{
char *dividendoSt, *divisoreSt;
long int risultato = 0;
double risultatoFl, dividendo = 0.0, divisore = 1.0;
static char result[128];
if(!pickPar(inputStr, 1, ÷ndoSt ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &divisoreSt ) ) redirectExit(ITX_MISINTER);
if (strcmp(dividendoSt, "") == 0)
return "";
divisore = atof(divisoreSt);
dividendo = atof(dividendoSt);
if (divisore == 0.0)
return "";
risultatoFl = dividendo / divisore;
risultato = (long int)(risultatoFl + 0.5);
if (risultato == 0)
return "";
sprintf(result, "%d", risultato);
return result;
}
/*************************************************************************************
Categoria : Gasp Command: *parval(nomeParametro)
attivita' : restituisce il valore del parametro nel file dei parametri con il
nomeParametro (n.b.: solo i parametri previsti)
*************************************************************************************/
void *parval(int vuoto1, char *vuoto2, char * inputStr)
{
char *nomeParametro;
if(!pickPar(inputStr, 1, &nomeParametro ) ) redirectExit(ITX_MISINTER);
if (strcmp(nomeParametro, "PrepKeyTag") == 0)
return PrepKeyTag;
else if (strcmp(nomeParametro, "IMGDIR") == 0)
return ImgDir;
return "";
}
/*************************************************************************************
Categoria : Gasp Command: *tgt(shapeTpl,targetTpl)
attivita' : controlla il livello di elaborazione corrente (visualizzazione,
pre-visializzazione, pre-processing) e restituisce delle stringe adatte
ad un inserimento in url.
nei tre casi:
visualizzazione - "tpl=targetTpl"
pre-visializzazione - "tpl=shapeTpl&tgt=targetTpl"
pre-processing - "tpl=targetTpl"
*************************************************************************************/
void *switchTplTgt(int vuoto1, char *vuoto2, char * inputStr)
{
char *shapeTpl, *targetTpl;
char userPKey[TPL_NAME_LEN];
static char retString[512];
itxString istr;
memset(retString, 0, 512);
if(!pickPar(inputStr, 1, &shapeTpl ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &targetTpl ) ) redirectExit(ITX_MISINTER);
istr.InBlinder(&shapeTpl, BLINDER);
istr.InBlinder(&targetTpl, BLINDER);
if (cgiFormString(PrepKeyTag, userPKey, TPL_NAME_LEN) == cgiFormSuccess)
{
// se e' un preprocessing il template destinazione e' il target
if (strcmp(userPKey, PrepropKey) == 0 )
{
sprintf(retString, "%s=%s", TPL_TAG, targetTpl);
}
// se e' un preview il template destinazione e' quello dinamico
// con associato il target
else if (strcmp(userPKey, PreviewKey) == 0 )
{
sprintf(retString, "%s=%s&%s=%s", TPL_TAG, shapeTpl, TGT_TAG, targetTpl);
}
// se e' una visualizzazione utente non dovrei essere qui
// tuttavia invece di dare errore torno targetTpl
else if (strcmp(userPKey, NormviewKey) == 0 )
{
sprintf(retString, "%s=%s", TPL_TAG, targetTpl);
}
else EXIT(0);
}
return(retString);
}
/*************************************************************************************
Categoria : Gasp Command: filtTqr(source,field,value,destination)
attivita' : filra i record del TQR source e li mette nel TQR destination. Il criterio
di selezione � quello che rende uguale il campo field al valore value
*************************************************************************************/
void *filterTqr(int vuoto1, char *vuoto2, char * inputStr)
{
char *source, *field, *value, *destination;
if(!pickPar(inputStr, 1, &source ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &field ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 3, &value ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 4, &destination ) ) redirectExit(ITX_MISINTER);
ITannit_Create(QueryResultSet, &QueryCounter);
ITannit_NewTQRFrom(source, field, value, destination);
ITannit_Destroy();
return(0);
}
/*************************************************************************************
Categoria : servizio
*************************************************************************************/
char* formatCurrency(char* num, int mant_len, int want_sep)
{
const char* sep = ".";
char* ret = NULL;
int numlen = strlen(num);
int first_pt = 0;
if (num == NULL || numlen == 0)
return NULL;
if ((ret = (char*)calloc(3 * ((numlen >= mant_len ? numlen : mant_len) + 1), 1)) == NULL)
return NULL;
if (strstr(num, ",") != NULL)
{
strcpy(ret, num);
return ret;
}
if (numlen > mant_len) //Il numero e` > 1 ?
{
if (numlen - mant_len > 3 && want_sep) //Gestione separatore 3 cifre
{
first_pt = (numlen - mant_len) % 3;
if (first_pt > 0)
{
memcpy(ret, num, first_pt);
strcat(ret, sep);
}
for (int i = first_pt; i<numlen - mant_len; i+=3)
{
memcpy(ret + strlen(ret), num + i, 3);
strcat(ret, sep);
}
if ((i = strlen(ret)) > 0)
ret[i - 1] = 0;
//Se c'e` parte decimale, metto la virgola e l'attacco
if (mant_len > 0)
{
strcat(ret, ",");
strcat(ret, num + numlen - mant_len);
}
}
else
{
memcpy(ret, num, numlen - mant_len);
strcat(ret, ",");
strcat(ret, num + numlen - mant_len);
}
}
else
{
strcat(ret, "0,");
memset(ret + 2, '0', mant_len - numlen);
strcat(ret, num);
}
if (ret[strlen(ret) - 1] == ',')
ret[strlen(ret) - 1] = 0;
return ret;
}
/*************************************************************************************
Categoria : Gasp Command: *dfcur(source,decimali)
attivita' : ritorna la valuta source formattata con le interpunzioni tra le migliaia
ed il numero di decimali specificato
*************************************************************************************/
void *dimFormatCurrency(int vuoto1, char *vuoto2, char * inputStr)
{
char *source, *decimaliSt;
int decimali = 0;
if(!pickPar(inputStr, 1, &source ) ) return "";
if( pickPar(inputStr, 2, &decimaliSt) ) decimali = atoi(decimaliSt);
if(decimali < 0)
return "";
return(formatCurrency(source,decimali,1));
}
/*************************************************************************************
Categoria : Gasp Command: *fdvia(FRZ) -> Frazione
attivit� : estrae dalla tabella accessoria Vie il valore relativo all'etichetta di
input e lo ritorna come nell'esempio
*************************************************************************************/
void * formatDimVia(int vuoto1, char *vuoto2, char * inputStr)
{
char *codiceVia, *titoloVia;
char queryString[GET_PAR_VAL_LEN];
int errCode;
if( !pickPar( inputStr, 1, &codiceVia ) ) return ("");
sprintf(queryString,"select DesIT from Vie where Codice = '%s'",codiceVia);
newAutoName();
dbInterface(QueryLabel, queryString, 1, 1);
titoloVia = storedData(1, "DesIT", QueryLabel, &errCode);
if (titoloVia == 0)
return (codiceVia);
if (strcmp(titoloVia, "") == 0)
return (codiceVia);
return (titoloVia);
}
/*************************************************************************************
Categoria : Gasp Command: *fdnaz(I) -> Nazione
attivit� : estrae dalla tabella accessoria Nazioni il valore relativo all'etichetta di
input e lo ritorna come nell'esempio
*************************************************************************************/
void * formatDimNaz(int vuoto1, char *vuoto2, char * inputStr)
{
char *codiceNaz, *titoloNaz;
char queryString[GET_PAR_VAL_LEN];
int errCode;
if( !pickPar( inputStr, 1, &codiceNaz ) ) return ("");
sprintf(queryString,"select DesIT from Nazioni where Codice = '%s'",codiceNaz);
newAutoName();
dbInterface(QueryLabel, queryString, 1, 1);
titoloNaz = storedData(1, "DesIT", QueryLabel, &errCode);
if (titoloNaz == 0)
return (codiceNaz);
if (strcmp(titoloNaz, "") == 0)
return (codiceNaz);
return (titoloNaz);
}
/*************************************************************************************
Categoria : Gasp Command: *ucase(Pallino) -> PALLINO
attivit� : trasforma in uppercase
*************************************************************************************/
void * uppercaseIt(int vuoto1, char *vuoto2, char * inputStr)
{
char *inputSt, *cursor;
if( !pickPar( inputStr, 1, &inputSt) ) return("");
cursor = inputSt;
while (*cursor)
{
if ((*cursor)>96 && (*cursor)<123)
*cursor = (*cursor) - 32;
cursor++;
}
return (inputSt);
}
/*************************************************************************************
Categoria : Gasp Command: *tplname(-1) -> CurrentTpl[TplNest-1]
attivit� : ritorna il nome del template corrente se il parametro � zero, altrimenti
usa il parametro come offset per individuare il template relativo nella
pila dei template
*************************************************************************************/
void *putTplName(int vuoto1, char *vuoto2, char * inputStr)
{
char *inputSt;
int shift = 0;
int index;
if( pickPar( inputStr, 1, &inputSt) ) shift = atoi(inputSt);
index = TplNest + shift;
if (!(index >= 0 && index < MAX_TPL_NESTS)) index = TplNest;
return (CurrentTpl[index]);
}
/*************************************************************************************
Categoria : Gasp Command: *utime(dd,mm,yyyy) -> universaltime
attivit� : trasforma data, mese e anno in universal time (secondi passati dalla
mezzanotte del 1.1.1970)
*************************************************************************************/
void *uTime(int vuoto1, char *vuoto2, char * inputStr)
{
char *giorno = 0, *mese = 0, *anno = 0;
struct tm datar;
time_t datas;
char * retVal = 0;
if(!pickPar(inputStr, 1, &giorno ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 2, &mese ) ) redirectExit(ITX_MISINTER);
if(!pickPar(inputStr, 3, &anno ) ) redirectExit(ITX_MISINTER);
datar.tm_mday = atoi(giorno);
datar.tm_mon = atoi(mese);
datar.tm_year = atoi(anno) - 1900;
datas = mktime(&datar);
if ((retVal = (char*)calloc(4096, sizeof(char))) == NULL)
return NULL;
sprintf(retVal, "%ld", datas);
return retVal;
}
/*************************************************************************************
Categoria : Gasp Command: *fdate(utime) = gg/mm/yyyy oppure *fdate(utime,d) = giorno
attivita' : trasforma una stringa che rappresenta una universal time (secondi
passati dalla mezzanotte del 1.1.1970) in formato normale oppure, se
presente un secondo parametro di valore d,m,y, torna il giorno, o il mese,
o l'anno; come da esempio
*************************************************************************************/
void *uTimeToDMY(int vuoto1, char *vuoto2, char * inputStr)
{
static char retVal[256];
time_t tm;
struct tm *dt;
char* universaltime = 0 , *tag = 0;
memset(retVal, '\0', 256);
if(!pickPar(inputStr, 1, &universaltime ) ) redirectExit(ITX_MISINTER);
tm = (time_t) atol(universaltime);
dt = localtime(&tm);
if( pickPar(inputStr, 2, &tag ) )
{
if (ISEQUAL(tag, "d"))
strftime(retVal, 256,"%d", dt);
else if (ISEQUAL(tag, "m"))
strftime(retVal, 256,"%m", dt);
else if (ISEQUAL(tag, "y"))
strftime(retVal, 256,"%Y", dt);
}
else
strftime(retVal, 256, "%d/%m/%Y", dt);
return retVal;
}
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: itxfileini.h,v $
* $Revision: 1.4 $
* $Author: massimo $
* $Date: 2002-06-07 11:05:03+02 $
*
* aitecsa
* ._..-_..-._-._..- ..-._-._- ._..-_..-._-._..- ..-._-._- ..-._-.
* � aitecsa s.r.l. via baglivi 3 00161 <NAME>
* <EMAIL>
*/
#ifndef _ITXFILEINI_H_
#define _ITXFILEINI_H_
#include "itxstring.h"
//defines
#define MAX_PARS 1000 //Max num of params in a ini file
#define INI_LINE_LEN 512 //Max len of ini file line
class itxFileINI
{
public:
//MEMBERS
itxString m_Names[MAX_PARS];
itxString m_Values[MAX_PARS];
private:
itxString m_FileName; //Nome del file di inizializzazione con l'estensione.
int m_NumParams;
public:
//METHODS
bool Read(char* inifile);
bool GetINIValue(char* param_name, itxString* param_value);
int GetCount(){ return m_NumParams;}
public:
//CONSTRUCTION-DESTRUCTION
itxFileINI()
{
m_FileName = "";
m_NumParams = 0;
};
~itxFileINI(){}
};
#endif /* _ITXFILEINI_H_ */
<file_sep>/*
* Copyright (c) AITECSA S.r.l.
* See the file LICENSE for copying permission.
* */
/* $RCSfile: parser.cpp,v $
* $Revision: 1.98 $
* $Author: massimo $
* $Date: 2002-06-25 18:25:15+02 $
| _-.-..-._-_-._--_-._.-._ AITECSA S.r.l. 2000
|
|
| FILENAME : parser.cpp
| TAB : 2 spaces
|
| DESCRIPTION : Parser implementations.
|
|
*/
#include "parser.h"
#include "cgiresolver.h"
#include "commands.h"
#include "tannitobj.h"
/****************
Parser
****************/
//-----------------------------------------------------------------
Parser::Parser()
{
for (int i=0; i < MAX_CMDS; i++)
m_Command[i] = NULL;
m_TotalCount = 0;
m_BaseCount = 0;
m_ForceExit = 0;
m_ForceReturn = 0;
m_TplVars.idx = 0;
m_StartCommandTag = START_COMMAND_TAG;
m_PreprocRun = false; // becoming obsolete
m_RunType = Normalrun;
m_CurTpl = NULL;
m_ActualTplDir = "";
}
//-----------------------------------------------------------------
Parser::~Parser()
{
DestroyBaseCommands();
if (m_CurTpl != NULL)
delete m_CurTpl;
}
//-----------------------------------------------------------------
void Parser::CreateBaseCommands(void* tannit)
{
Tannit* ptannit = (Tannit*)tannit;
CGIResolver* pcgires = (CGIResolver*)tannit;
TQRManager* ptqr_manager = &ptannit->m_TQRManager;
TQRODBCManager* ptqrodbc_manager = &ptannit->m_TQRODBCManager;
TQRCollection* ptqrcollection = &ptannit->m_TQRCollection;
itxSQLConnCollection* pconnections = &ptannit->m_connections;
itxSQLConnection* podbcconnection = &ptannit->m_odbcconnection;
int i = 0;
//BEGIN CREATION BASE COMMANDS
m_Command[i++] = (AbstractCommand*)new BC_StartConditionalBlock(START_CONDITIONAL_BLOCK, this, START_CND_BLK);
m_Command[i++] = (AbstractCommand*)new BC_EndConditionalBlock();
m_Command[i++] = (AbstractCommand*)new BC_AlternateConditionalBlock();
m_Command[i++] = (AbstractCommand*)new BC_StartConditionalBlock(ELSIF_CONDITIONAL_BLOCK, this, ELSIF_CND_BLK);
m_Command[i++] = (AbstractCommand*)new BC_PRMValue(PRMVALUE, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_Cgipath(CGIPATH, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_GetValue(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_AdjustQuotes(this);
m_Command[i++] = (AbstractCommand*)new BC_ProcessExternFile(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_UCase();
m_Command[i++] = (AbstractCommand*)new BC_LCase();
m_Command[i++] = (AbstractCommand*)new BC_Trim();
m_Command[i++] = (AbstractCommand*)new BC_SetVar(this);
m_Command[i++] = (AbstractCommand*)new BC_GetVar(this);
m_Command[i++] = (AbstractCommand*)new BC_GetCookie(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_UTime(this);
m_Command[i++] = (AbstractCommand*)new BC_DMYTime(this);
m_Command[i++] = (AbstractCommand*)new BC_Now(this);
m_Command[i++] = (AbstractCommand*)new BC_FormatCurrency(this);
m_Command[i++] = (AbstractCommand*)new BC_CheckForbiddenChars(this);
m_Command[i++] = (AbstractCommand*)new BC_TraceUser(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_ODBCExecuteQuery(this, pcgires, ptqrodbc_manager);
m_Command[i++] = (AbstractCommand*)new BC_TQRRecordFieldValue(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_TQRRecordFieldValQuot(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_CycleTQR(this, pcgires, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_EndCycleTQR(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_CycleFor(this, pcgires, ptqrcollection, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_EndCycleFor(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_ForIndex(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_Exit(this);
m_Command[i++] = (AbstractCommand*)new BC_TQRExist(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_GetHide(this);
m_Command[i++] = (AbstractCommand*)new BC_Crypt(this);
m_Command[i++] = (AbstractCommand*)new BC_Decrypt(this);
m_Command[i++] = (AbstractCommand*)new BC_RemoveTQR(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_TQRStat(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_Valid(this, pcgires, ptqrodbc_manager, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_Return(this);
m_Command[i++] = (AbstractCommand*)new BC_Flush(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_TQRFilt(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_Recsel(this, ptqrcollection, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_TQRMove(this, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_Trans(this, pcgires, ptqrodbc_manager, ptqrcollection);
m_Command[i++] = (AbstractCommand*)new BC_Left(this);
m_Command[i++] = (AbstractCommand*)new BC_Right(this);
m_Command[i++] = (AbstractCommand*)new BC_Strlen();
m_Command[i++] = (AbstractCommand*)new BC_TQRStore(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_TQRInsert(this, ptqrodbc_manager);
m_Command[i++] = (AbstractCommand*)new BC_Pager(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_Netprex(this);
m_Command[i++] = (AbstractCommand*)new BC_Netgrab(this);
m_Command[i++] = (AbstractCommand*)new BC_Rand(this);
m_Command[i++] = (AbstractCommand*)new BC_MakeOp(this);
m_Command[i++] = (AbstractCommand*)new BC_GetValueQuote(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_TQRSample(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_NewConnection(this, pconnections);
m_Command[i++] = (AbstractCommand*)new BC_SetConnection(this, ptqrodbc_manager, pconnections);
m_Command[i++] = (AbstractCommand*)new BC_ResetConnection(this, ptqrodbc_manager, podbcconnection);
m_Command[i++] = (AbstractCommand*)new BC_Array(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_ArraySet(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_ArrayGet(this, ptqr_manager);
m_Command[i++] = (AbstractCommand*)new BC_RemoveChar(this);
m_Command[i++] = (AbstractCommand*)new BC_Mid(this);
m_Command[i++] = (AbstractCommand*)new BC_NumericalCmp(this);
m_Command[i++] = (AbstractCommand*)new BC_Proc(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_Verinst(this);
m_Command[i++] = (AbstractCommand*)new BC_CopyFile(this);
m_Command[i++] = (AbstractCommand*)new BC_Currency(this);
m_Command[i++] = (AbstractCommand*)new BC_Console(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_GetValueCast(this, pcgires);
m_Command[i++] = (AbstractCommand*)new BC_GetPOSTbody(pcgires);
m_Command[i++] = (AbstractCommand*)new BC_Mail(this);
m_Command[i++] = (AbstractCommand*)new BC_Getenv(this);
//END CREATION BASE COMMANDS
UpdateTotalCount();
m_BaseCount = m_TotalCount;
}
//-----------------------------------------------------------------
void Parser::DestroyBaseCommands()
{
for (int i=0; i < m_BaseCount; i++)
{
delete m_Command[i];
m_Command[i] = NULL;
}
}
//-----------------------------------------------------------------
void Parser::UpdateTotalCount()
{
m_TotalCount = 0;
for (int i=0; i < MAX_CMDS; i++)
{
if (m_Command[i] != NULL)
m_TotalCount++;
}
}
//-----------------------------------------------------------------
int Parser::PickPar(char* inputStr, int position, itxString* returnStr)
{
char* strCursor;
int parLen = 0;
int parNum = 0;
int parsOffstArr[PARAM_NUMBER] = {0};
int i = 0;
int searchPars = 1;
// nel caso che non vi sia nessun parametro
if (inputStr == NULL || strlen(inputStr) == 0)
return PARAM_NOT_FOUND;
// inizializzazione del cursore al primo carattere della stringa di input
strCursor = inputStr;
position--;
while (*strCursor)
{
if (*strCursor == BLINDER)
searchPars = (searchPars ? 0 : 1);
if (searchPars && *strCursor == ',')
{
//gestione del carattere 'virgola' con il backslash (alla C)
if ((unsigned)strCursor <= (unsigned)inputStr || *(strCursor - 1) != '\\')
parsOffstArr[++parNum] = (unsigned int)strCursor - (unsigned int)inputStr + 1;
}
strCursor++;
}
//si copia il parametro sulla stringa di uscita
if (parNum > position)
{
parLen = parsOffstArr[position + 1] - parsOffstArr[position];
returnStr->Strncpy(inputStr + parsOffstArr[position], parLen - 1);
}
else if (parNum == position)
*returnStr = &inputStr[parsOffstArr[position]];
else
return PARAM_NOT_FOUND;
returnStr->Trim(); //toggle tedious blanks off...
returnStr->SubstituteSubString("\\,", ","); //eliminazione del backslash per la virgola
return PARAM_FOUND;
}
//-----------------------------------------------------------------
int Parser::PickInt(char* inputstr, int position, int* retval)
{
if (position <= 0 || retval == NULL)
return 0;
itxString retstr;
retstr = "";
if (PickPar(inputstr, position, &retstr) == PARAM_NOT_FOUND)
return 0;
*retval = atoi(retstr.GetBuffer());
return 1;
}
//-----------------------------------------------------------------
int Parser::PickDouble(char* inputstr, int position, double* retval)
{
if (position <= 0 || retval == NULL)
return 0;
itxString retstr;
retstr = "";
if (PickPar(inputstr, position, &retstr) == PARAM_NOT_FOUND)
return 0;
*retval = atof(retstr.GetBuffer());
return 1;
}
//-----------------------------------------------------------------
int Parser::PickString(char* inputstr, int position, char* retval, int* bufdim)
{
if (position <= 0 || bufdim == NULL)
return 0;
itxString retstr;
retstr = "";
if (PickPar(inputstr, position, &retstr) == PARAM_NOT_FOUND)
return 0;
if (retval == NULL)
{
*bufdim = retstr.Len() + 1;
return 1;
}
strcpy(retval, retstr.GetBuffer());
return 1;
}
//-----------------------------------------------------------------
int Parser::PickListString(char* inputstr, itxString** params)
{
int position = 0;
while (PickPar(inputstr, position + 1, params[position]) != PARAM_NOT_FOUND)
position++;
return position;
}
/*-----------------------------------------------------------------
attivita' :
scandisce i dati letti in tplString e li scrive su outputString.
*/
int Parser::ProcTplData(char* tplString, itxString* outputString)
{
BaseCommand* basecmd = NULL;
itxString commandRetStr; //stringa restituita dal comando eseguito (l'allocazione spetta al comando)
itxString transfArg; //argomento di una funzione trasformato dalla chiamata ricorsiva
itxString argStr; //argomento grezzo del comando
char* cmdStart;
char* paux;
int dataIsChar = 1; //flag che indica se il dato da restituire � un semplice carattere
int i = 0;
int cmdOrd = 0;
int retStrLen = 0;
if (tplString == NULL)
return 0;
transfArg.SetGranularity(1024);
try
{
while (*tplString != 0 && m_ForceExit == 0 && m_ForceReturn == 0)
{
dataIsChar=1; // Di default non mi aspetto un comando: assumo che il dato
// sia un carattere da copiare in uscita cos� come �
if (m_CurTpl->m_RecursionZero == 0)
{
paux = tplString;
tplString = strchr(paux, m_StartCommandTag);
if (m_CurTpl->MustExec())
{
if(tplString == NULL)
{
*outputString += paux;
return 0; //Reached the end of template
}
else
{
*tplString = '\0';
*outputString += paux;
*tplString = m_StartCommandTag;
}
}
}
// se incontro il carattere di segnalazione comando
if (*tplString == m_StartCommandTag)
{
// verifico la sintassi del comando e metto i puntatori su tplString
// all'inizio del nome del comando e dell'argomento (termino le stringhe ponendo
// a zero i caratteri di inizio e fine argomento); tplString viene spostato a fine comando
if (VerifyCmdSynt(&tplString, &cmdOrd, &argStr, &cmdStart) == 1)
{
if (cmdOrd < m_BaseCount)
{
if (m_CurTpl->CheckStartBlock(((BaseCommand*)m_Command[cmdOrd])->m_Type, cmdStart))
dataIsChar = 0; // si disattiva il flag che segnala la presenza di un singolo carattere
}
// esecuzione comando
if (m_CurTpl->MustExec())
{
// chiamata ricorsiva: l'argomento del comando viene interpretato e restituito su
// transfArg; il file pointer (secondo argomento) viene passato NULL per permettere
// il riconoscimento del livello interno di ricorsione
transfArg = "";
m_CurTpl->m_RecursionZero++;
ProcTplData(argStr.GetBuffer(), &transfArg);
m_CurTpl->m_RecursionZero--;
try //Esecuzione
{
TimeTrace("PRIMA DEL COMANDO");
DebugTrace2(DEFAULT, "Executing: %s(%s)\n", m_Command[cmdOrd]->GetName(), transfArg.GetBuffer());
commandRetStr = m_Command[cmdOrd]->Execute(transfArg.GetBuffer());
TimeTrace("DOPO IL COMANDO");
m_Command[cmdOrd]->Deallocate();
}
catch(char* msg)
{
DebugTrace2(IN_ERROR, "Propagated message: '%s'\n", msg);
throw;
}
catch(...)
{
itxSystem sys;
DebugTrace2((cmdOrd < m_BaseCount ? IN_ERROR : IN_WARNING),
"Parser::ProcTplData: Unhandled Exception during '%s - %d' COMMAND\n",
m_Command[cmdOrd]->GetName(), sys.BSGetLastError());
throw;
}
// si disattiva il flag che segnala la presenza di un singolo carattere
dataIsChar = 0;
}
if (cmdOrd < m_BaseCount)
{
if (m_CurTpl->CheckEndBlock(((BaseCommand*)m_Command[cmdOrd])->m_Type, &tplString))
dataIsChar = 0; // si disattiva il flag che segnala la presenza di un singolo carattere
}
}
}
if (m_CurTpl->MustExec())
{
// se il carattere letto non � il principio di un comando va scritto in output cos� come �
if (dataIsChar) //&& *tplString != '\x0A')
*outputString += (char) *tplString;
// il dato non � un singolo carattere ma una stringa
// risultato dell'elaborazione di un comando
else
{
// si copia la stringa di ritorno del comando sullo stream di uscita
if (!commandRetStr.IsNull() && !commandRetStr.IsEmpty())
*outputString += commandRetStr;
commandRetStr = "";
}
}
tplString++;
} // while (*tplString != 0)
}
catch (...)
{
DebugTrace2(IN_ERROR, "Parser::ProcTplData: recursion level %d.\n", m_CurTpl->m_RecursionZero);
DebugTrace2(IN_ERROR, "Parser::ProcTplData: transfArg = '%s'\n", transfArg.GetBuffer());
DebugTrace2(IN_ERROR, "Parser::ProcTplData: commandRetStr = '%s'\n", commandRetStr.GetBuffer());
m_ForceExit = 1;
throw;
}
return 0;
}
/*-----------------------------------------------------------------
NOME :VerifyCmdSynt
attivita' :verifica che i primi caratteri di *tplString siano quelli di uno dei
comandi e verifica la sintassi. cmdOrd identifica la posizione del comando
nell'array; argStr viene indirizzato su tplString all'inizio dell'argomento;
le stringhe vengono terminate ponendo a zero i caratteri di inizio e fine
argomento; tplString viene spostato alla fine del comando
return :se *tplString inizia con un comando restituisce 1, se non sono verificate le
condizioni sintattiche torna 0, se non � stato chiuso l'argomento torna -1
*/
int Parser::VerifyCmdSynt(char** tplString, int* cmdOrd, itxString* argStr, char** cmdStart)
{
int insideArg = 0;
int argTagNestingLev = -1;
int blinderCount = 0;
int canBeCommand = 1;
int cmdLen = 0;
int argLen = 0;
int i = 0;
int cmdArgNotClosed = 0;
char* holdTplString = NULL;
char* tmpArgP = NULL;
itxString strToEval;
strToEval.Space(CMD_LEN+1);
// memorizzo la posizione di partenza della stringa e
// copio in un buffer un numero di caratteri della stringa pari al massimo numero
// consentito per il nome di un comando (+ il terminator)
holdTplString = *tplString;
strToEval.Strncpy(*tplString + 1, CMD_LEN + 1);
// prima condizione da soddisfare: devo trovare il carattere di inizio argomento '('
char opentag[2] = {CMD_ARG_OPEN_TAG, '\0'};
strToEval.Left(strToEval.FindSubString(opentag));
cmdLen = strToEval.Len();
tmpArgP = *tplString + cmdLen + 1; // l'argomento punta alla prima parentesi
insideArg=1; // sono all'interno dell'argomento
argTagNestingLev=0; // sono entrato nel livello zero di annidamento parentesi
strToEval.RTrim();
// se le condizioni fin qui richieste sono state soddisfatte
if (canBeCommand)
{
// la funzione continua a essere scettica: il fatto che si sia trovato un carattere
// di apertura argomento non la ha convinta
canBeCommand = 0;
// si scorre l'array di CommandStructure
// e si comparano le etichette dei comandi con quella isolata ora
for(*cmdOrd = 0; *cmdOrd < m_TotalCount; (*cmdOrd)++)
{
if(!strToEval.Compare(m_Command[*cmdOrd]->GetName()))
{
canBeCommand = 1; // condizione soddisfatta
break;
}
}
}
// se le condizioni fin qui richieste sono state soddisfatte
if (canBeCommand)
{
canBeCommand=0; // la funzione continua a essere scettica
// sposto il puntatore all'inizio del presunto argomento
*tplString = tmpArgP;
// procedo fino ad incontrare il carattere di fine stringa o fino a quando non esco dall'argomento
// while (tmpArgP && insideArg)
while (**tplString != '\0' && insideArg)
{
// il puntatore si sposta al carattere successivo
(*tplString)++;
if (**tplString == BLINDER)
{
blinderCount++;
continue;
}
// se si tratta di un carattere di apertura argomento
if (**tplString == CMD_ARG_OPEN_TAG && !(blinderCount % 2))
argTagNestingLev++; // aumento il livello di annidamento parentesi
else if (**tplString==CMD_ARG_CLOSE_TAG && !(blinderCount % 2)) // se trovo il carattere di chiusura argomento
{
// se ho raggiunto il livello 0 ho esaurito l'argomento
if (argTagNestingLev==0)
insideArg=0;
// diminuisco il livello di annidamento parentesi
argTagNestingLev--;
}
}
// se ho esaurito l'argomento prima di terminare la stringa tutto ok
if (!insideArg)
canBeCommand=1;
else
cmdArgNotClosed=1;
}
// se � definitivamente un comando
if (canBeCommand)
{
tmpArgP++; // si fa puntare l'argomento al carattere successivo, il primo del argomento
argLen = (unsigned)*tplString - (unsigned)tmpArgP;
if (argLen == 0)
argStr->SetEmpty();
else
argStr->Strncpy(tmpArgP, argLen);
//Se il comando e` seguito immediatamente da un CR, da un LF o da una coppia CRLF, lo skippo
if (*(*tplString + 1) == '\r')
(*tplString)++;
if (*(*tplString + 1) == '\n')
(*tplString)++;
}
else
{
*cmdOrd = 0; // non � un comando
tmpArgP = NULL; // niente comando
*tplString = holdTplString; // niente argomento: rimettiamo la stringa a posto
}
*cmdStart = holdTplString - 1;
// se � un comando torna 1, se non lo � torna 0, se non � stato chiuso l'argomento torna -1
return (canBeCommand - cmdArgNotClosed);
}
TemplateFile* Parser::LoadTemplate(itxString* tpldir, itxString* pname, char* ext)
{
if (pname->IsEmpty() || pname->IsNull())
return NULL;
TemplateFile* tpl = NULL;
itxString templ = *tpldir;
try
{
if (templ.RightInstr(PATH_SEPARATOR) != templ.Len())
templ += PATH_SEPARATOR;
templ += *pname;
tpl = new TemplateFile(templ.GetBuffer(), ext);
if (tpl->Exist() == 0)
{
DebugTrace2(IN_WARNING, "Template %s not found.\n", templ.GetBuffer());
delete tpl;
tpl = NULL;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception in Parser::LoadTemplate while opening %s.\n", templ.GetBuffer());
throw;
}
return tpl;
}
//-----------------------------------------------------------------
void Parser::Run(itxString* tpldir, itxString* pname, char* ext)
{
TemplateFile* new_tpl = NULL;
TemplateFile* popped_tpl = NULL;
// interpretazione dei dati
try
{
if ((new_tpl = LoadTemplate(tpldir, pname, ext)) != NULL)
{
m_TplStack.Push(new_tpl);
m_CurTpl = new_tpl;
g_DebugFile.m_CurrentTemplate = m_CurTpl->m_PathName;
DebugTrace2(TEMPLATE, "Parser::Run: template is: %s\n", m_CurTpl->m_PathName.GetBuffer());
try
{
ProcTplData(m_CurTpl->GetContentBuffer(), &(m_CurTpl->m_Output));
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception during ProcTplData: now context is Run(itxString*, itxString*, char*), going on...\n");
}
//Return from template was forced, reset dedicated variable
if(m_ForceReturn != 0)
m_ForceReturn = 0;
//Finish with this template
m_TplStack.Pop((void**)&popped_tpl);
if (popped_tpl != new_tpl)
DebugTrace2(DEFAULT, "Template mismatch in Parser::Run : expected %s, found %s\n",
new_tpl->m_PathName.GetBuffer(), popped_tpl->m_PathName.GetBuffer());
//Reassign the currente template with the topmost of the stack
if ((m_CurTpl = (TemplateFile*) m_TplStack.Top()) != NULL)
{
m_CurTpl->m_Output += new_tpl->m_Output;
DebugTrace2(TEMPLATE, "Parser::Run: template is: %s\n", m_CurTpl->m_PathName.GetBuffer());
delete new_tpl;
}
else
m_CurTpl = new_tpl;
g_DebugFile.m_CurrentTemplate = m_CurTpl->m_PathName;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception in Parser::Run. Current template is '%s'\n", pname->GetBuffer());
throw;
}
}
//-----------------------------------------------------------------
void Parser::Run(char* content)
{
TemplateFile* new_tpl = NULL;
TemplateFile* popped_tpl = NULL;
if (content == NULL)
return;
// interpretazione dei dati
try
{
if ((new_tpl = new TemplateFile(content, 0)) != NULL)
{
m_TplStack.Push(new_tpl);
m_CurTpl = new_tpl;
g_DebugFile.m_CurrentTemplate = m_CurTpl->m_PathName;
DebugTrace2(TEMPLATE, "Parser::Run: current template is coming from a memory buffer: %s\n",
m_CurTpl->m_PathName.GetBuffer());
try
{
ProcTplData(m_CurTpl->GetContentBuffer(), &(m_CurTpl->m_Output));
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception during ProcTplData: now context is Run(char*), going on...\n");
}
//Return from template was forced, reset dedicated variable
if(m_ForceReturn != 0)
m_ForceReturn = 0;
//Finish with this template
m_TplStack.Pop((void**)&popped_tpl);
if (popped_tpl != new_tpl)
DebugTrace2(DEFAULT, "Template mismatch in Parser::Run : expected %s, found %s\n",
new_tpl->m_PathName.GetBuffer(), popped_tpl->m_PathName.GetBuffer());
//Reassign the currente template with the topmost of the stack
if ((m_CurTpl = (TemplateFile*) m_TplStack.Top()) != NULL)
{
m_CurTpl->m_Output += new_tpl->m_Output;
DebugTrace2(TEMPLATE, "Parser::Run: template is: %s\n", m_CurTpl->m_PathName.GetBuffer());
delete new_tpl;
}
else
m_CurTpl = new_tpl;
g_DebugFile.m_CurrentTemplate = m_CurTpl->m_PathName;
}
}
catch(...)
{
DebugTrace2(IN_ERROR, "Unhandled exception in Parser::Run. Current template is '%p'\n", content);
throw;
}
}
//-----------------------------------------------------------------
void Parser::SetValidBlock(int val)
{
m_CurTpl->m_ValidBlock[m_CurTpl->m_CndLevel] = val;
}
//-----------------------------------------------------------------
void Parser::SetCycleBlock(int val)
{
m_CurTpl->m_ReadCycle[m_CurTpl->m_CycLevel] = val;
}
//-----------------------------------------------------------------
int Parser::GetCycleBlock(int offset)
{
return m_CurTpl->m_ReadCycle[m_CurTpl->m_CycLevel + offset];
}
//-----------------------------------------------------------------
void Parser::AddVar(char* varName, char* varValue)
{
int i;
for (i=0; i < m_TplVars.idx; i++)
{
if (!m_TplVars.names[i].IsNull())
{
if (strcmp(m_TplVars.names[i].GetBuffer(), varName) == 0)
break;
}
}
if (i == m_TplVars.idx)
{
if (i < TPL_VARS_NUM)
{
m_TplVars.names[i] = varName;
m_TplVars.values[i] = varValue;
m_TplVars.idx++;
}
else
return;
}
else
m_TplVars.values[i] = varValue ;
}
| ec7341df6f50ef5fdb82ba32cac25dbd6edadd80 | [
"HTML",
"Markdown",
"JavaScript",
"Makefile",
"Java",
"C",
"C++"
] | 123 | C++ | gambineri/Attic | deef78a0283b05b3786bf63a25555c1b9701ed5f | 41bba501adab33521238012d6c2941585f5150c4 |
refs/heads/master | <repo_name>anjarupnik/codaisseurup<file_sep>/README.md
# Codaisseurup
Down-sized version of Meetup
Built with: Ruby on Rails

## Getting Started
```bash
git clone <EMAIL>:anjarupnik/codaisseurup.git
cd codaisseurup
rails db:create db:migrate db:seed
rails server
```
<file_sep>/spec/models/profile_spec.rb
require 'rails_helper'
RSpec.describe Profile, type: :model do
describe ".by_initial" do
subject { Profile.by_initial("S") }
let(:sander) { create :profile, first_name: "Sander" }
let(:stefan) { create :profile, first_name: "Stefan" }
let(:wouter) { create :profile, first_name: "Wouter" }
it "returns the profiles that match the initial" do
expect(subject).to match_array([stefan, sander])
end
it "is sorted on first_name" do
expect(subject).to eq([sander, stefan])
end
end
end
<file_sep>/app/models/registration.rb
class Registration < ApplicationRecord
belongs_to :user, optional: true
belongs_to :event
before_save :set_status, :set_total_price
def set_status
self.status = "pending" if event.price > 0
self.status = "confirmed"
end
def set_total_price
self.price = event.price * guests_count
end
end
<file_sep>/spec/models/event_spec.rb
require 'rails_helper'
RSpec.describe Event, type: :model do
describe "validations" do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_length_of(:description).is_at_most(500) }
it { is_expected.to validate_presence_of(:location) }
end
describe "#bargain?" do
let(:bargain_event) { create :event, price: 20 }
let(:non_bargain_event) { create :event, price: 200 }
it "returns true if the price is smaller than 30 EUR" do
expect(bargain_event.bargain?).to eq(true)
expect(non_bargain_event.bargain?).to eq(false)
end
end
it { is_expected.to belong_to :user}
describe "association with category" do
let(:event) { create :event }
let(:category1) { create :category, name: "Bright", events: [event] }
let(:category2) { create :category, name: "Clean lines", events: [event] }
let(:category3) { create :category, name: "A Man's Touch", events: [event] }
it { is_expected.to have_and_belong_to_many :categories }
end
describe "association with registration" do
let(:guest_user) { create :user, email: "<EMAIL>" }
let(:host_user) { create :user, email: "<EMAIL>" }
let!(:event) { create :event, user: host_user }
let!(:registration) { create :registration, event: event, user: guest_user }
it "has guests" do
expect(event.guests).to include(guest_user)
end
end
describe ".order_by_name" do
subject { Event.order_by_name }
let(:event1) { create :event, name: "Anja" }
let(:event2) { create :event, name: "Zoo" }
it "is sorted on name in ascending order" do
expect(subject).to eq([event1, event2])
end
end
describe ".published" do
subject { Event.published }
let(:event) { create :event, active: true }
it "has active event" do
expect(subject).to include(event)
end
end
end
<file_sep>/app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def destroy
photo = Photo.find(params[:id])
@event = photo.event
if @event.user.id == current_user.id
photo.destroy
redirect_to edit_event_path(@event), notice: "Photo successfully removed"
else
redirect_to @event, notice: "Cannot delete that photo"
end
end
end
<file_sep>/app/controllers/api/categories_controller.rb
class Api::CategoriesController < ApplicationController
def index
render status: 200, json: {
categories: Category.all
}.to_json
end
def show
category = Category.find(params[:id])
render status: 200, json: {
category: category
}.to_json
end
end
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe "association with event" do
let(:user) { create :user }
let!(:event) { create :event, user: user }
it "has many events" do
event1 = user.event.new(name: "Wonderful")
event2 = user.event.new(name: "Extraordinary")
expect(user.event).to include(event1)
expect(user.event).to include(event2)
end
it "deletes associated events" do
expect { user.destroy }.to change(Event, :count).by(-1)
end
end
describe "association with profile" do
let!(:user) { create :profile }
it { should have_one(:profile) }
end
end
describe "association with registration" do
let(:guest_user) { create :user, email: "<EMAIL>" }
let(:host_user) { create :user, email: "<EMAIL>" }
let!(:event) { create :event, user: host_user }
let!(:registration) { create :registration, event: event, user: guest_user }
it "has registrations" do
expect(guest_user.registrated_events).to include(event)
end
end
<file_sep>/app/controllers/registrations_controller.rb
class RegistrationsController < ApplicationController
def create
@registration = current_user.registrations.create(registration_params.merge(event_id: params[:event_id]))
@registration.save
redirect_to @registration.event, notice: "Thank you for registering!"
end
private
def registration_params
params.require(:registration).permit(:guests_count)
end
end
<file_sep>/app/models/event.rb
class Event < ApplicationRecord
belongs_to :user, optional: true
has_and_belongs_to_many :categories
has_many :photos
has_many :registrations, dependent: :destroy
has_many :guests, through: :registrations, source: :user
validates :name, presence: true
validates :description, presence: true, length: { maximum: 500 }
validates :location, presence: true
def bargain?
price < 30
end
def self.order_by_price
order :price
end
def self.order_by_name
order(name: :asc)
end
scope :published, -> { where(active: true) }
scope :starts_before_ends_after, ->(starts_at, ends_at) {
where('starts_at < ? AND ends_at > ?', starts_at, ends_at)
}
scope :starts_on_date, ->(starts_at){
where('starts_at == ? ', starts_at)
}
scope :ends_on_date, ->(ends_at){
where('ends_at == ? ', ends_at)
}
end
<file_sep>/app/serializers/event_serializer.rb
class EventSerializer < ActiveModel::Serializer
attributes :name, :description, :location, :price, :capacity, :includes_food,
:includes_drinks, :starts_at, :ends_at, :active
has_many :registrations
end
<file_sep>/app/controllers/api/registrations_controller.rb
class Api::RegistrationsController < Api::BaseController
skip_before_action :verify_authenticity_token
before_action :set_event
def create
registration = @event.registrations.create(registration_params)
if registration.save
render status: 200, json: {
message: "Registration successfully created",
event: @event,
registration: registration
}.to_json
else
render status: 422, json: {
message: "registration could not be created",
errors: registration.errors
}.to_json
end
end
def update
registration = @event.registrations.find(params[:id])
if registration.update(registration_params)
render status: 200, json: {
message: "Registration successfully updated",
event: @event,
registration: registration
}.to_json
else
render status: 422, json: {
message: "Registration could not be updated",
errors: registration.errors
}.to_json
end
end
def destroy
registration = @event.registrations.find(params[:id])
registration.destroy
render status: 200, json: {
message: "Registration successfully deleted",
event: @event,
registration: registration
}.to_json
end
private
def set_event
@event = Event.find(params[:event_id])
end
def registration_params
params.require(:registration).permit(:guests_count)
end
end
<file_sep>/spec/features/show_event_spec.rb
require 'rails_helper'
describe "Viewing an individual event" do
let(:event) { create :event }
it "shows the event's details" do
visit event_url(event)
expect(page).to have_text(event.name)
expect(page).to have_text(event.location)
expect(page).to have_text(event.description)
expect(page).to have_text(event.price)
expect(page).to have_text(event.capacity)
end
describe ".order_by_price" do
let!(:event1) { create :event, price: 100 }
let!(:event2) { create :event, price: 200 }
let!(:event3) { create :event, price: 50 }
it "returns a sorted array of events by prices" do
expect(Event.order_by_price).to eq([event3, event1, event2])
end
end
end
<file_sep>/db/seeds.rb
Registration.destroy_all
Profile.destroy_all
Photo.destroy_all
User.destroy_all
Event.destroy_all
Category.destroy_all
anja = User.create!(email: "<EMAIL>", password: "<PASSWORD>")
lara = User.create!(email: "<EMAIL>", password: "<PASSWORD>")
nika = User.create!(email: "<EMAIL>", password: "<PASSWORD>")
party = Category.create!(name: "Party")
educational = Category.create!(name: "Educational")
art = Category.create!(name: "Art")
music = Category.create!(name:"Music")
event1 = Event.create!(name: "Dreamcatcher", description:"Pozivamo vas na dvodnevni event Dreamcatcher u organizaciji udruge Inkubator u prostoru dnevnog boravka u Rojcu.",
location:"Rojc, dnevni boravak, Gajeva 3, Pula", price:5, capacity: 20, includes_food:false, includes_drinks:true,
starts_at: 10.days.from_now,ends_at: 12.day.from_now, active:true, user: anja, categories: [art, educational])
event2 =Event.create!(name: "<NAME>", description:"Iedere vrijdag Fesa bij Waterkant met <NAME>, onze liefde voor muziek. Iedere week een ander thema en altijd gratis entree. Koude Parbo Bier djogo's en hete tunes op vrijdag vanaf 23 uur.",
location:"Marnixstraat 246, 1016 TL Amsterdam, Netherlands", price:0, capacity: 100, includes_food:true, includes_drinks:true,
starts_at: 20.days.from_now ,ends_at: 30.days.from_now, active:true, user: lara, categories: [party, music])
photo1 = Photo.create!(remote_image_url: "http://res.cloudinary.com/mdfchucknorris/image/upload/v1507801220/968361_jtpgdw.jpg", event: event1)
photo2 = Photo.create!(remote_image_url: "http://res.cloudinary.com/mdfchucknorris/image/upload/v1507801226/images_pubmln.png", event: event2)
Registration.create!(user: anja, event: event1, price: event1.price, guests_count: 1)
Registration.create!(user: lara, event: event2, price: event2.price, guests_count: 2)
| de19cccd7b97810989b0678a363c00ce7e08c2e1 | [
"Markdown",
"Ruby"
] | 13 | Markdown | anjarupnik/codaisseurup | c630ff8e979607bb770e1ad5ca045f9d450b6bf1 | fa3077c5f9bfca75a50c7c6e2585ddc7c720f102 |
refs/heads/master | <repo_name>edward65/tada-server<file_sep>/app/views/orders/index.json.jbuilder
json.array!(@orders) do |order|
json.extract! order, :id, :store_id, :store_name, :user_id, :status, :reject_reason, :content, :accepted_at, :finished_at, :order_fee, :delivery_fee, :items_fee, :tip
json.url order_url(order, format: :json)
end
<file_sep>/db/migrate/20150119063822_modify_order.rb
class ModifyOrder < ActiveRecord::Migration
def change
add_column :orders, :reject_title, :string
add_column :orders, :receive_place, :string
add_column :orders, :receive_address, :string
add_column :orders, :receive_phone, :string
add_column :orders, :receive_note, :string
end
end
<file_sep>/app/controllers/api/v1/api_orders_controller.rb
class Api::V1::ApiOrdersController < ApplicationController
skip_before_filter :authenticate, :only => [:create]
skip_before_filter :verify_authenticity_token
def index_ok
puts "Edward ===v1==index====okoko"
@orders = Order.all
render :json => @orders
end
# POST /add_order:
#傳入:
#user_id: 使用者ID
#store_name: 商店名稱
#items: 購買品項
#回傳:
#成功:> { "success": true, "order_id": "122" }
#失敗:> { }
def create_order
result = false
user_id = params[:user_id]
store_name = params[:store_name]
items = params[:items]
receive_place = params[:receive_place]
receive_address = params[:receive_address]
receive_phone = params[:receive_phone]
receive_note = params[:receive_note]
if user_id.present? and store_name.present? and items.present?
order = Order.create(
:user_id => user_id,
:store_name => store_name,
:content => items,
:receive_place => receive_place,
:receive_address => receive_address,
:receive_phone => receive_phone,
:receive_note => receive_note,
:status => 0 #0:新單、1:接受、2:拒絕、4:完成、5:失效
)
result = true
end
render :json => result ? {"success" => true ,"order_id" =>order.id} : {}
end
def update_ok
puts "Edward ===33==update_ok====okoko"
result = false
from_content = params[:from_content]
to_content = params[:to_content]
if from_content and to_content
# check if this user had answered
order = Order.find_by(content: from_content)
order.content = to_content
order.save
result = true
end
render :json => result ? {"success" => true } : {}
end
end<file_sep>/app/views/users/index.json.jbuilder
json.array!(@users) do |user|
json.extract! user, :id, :first_name, :last_name, :location, :tele, :verify_code, :fb_token, :notification_token, :invite_code, :email, :status
json.url user_url(user, format: :json)
end
<file_sep>/app/controllers/api/v1/api_users_controller.rb
class Api::V1::ApiUsersController < ApplicationController
skip_before_filter :authenticate, :only => [:create]
skip_before_filter :verify_authenticity_token
require 'rubygems' # not necessary with ruby 1.9 but included for completeness
require 'twilio-ruby'
def index_ok
puts "Edward ===v1==index====okoko"
@orders = Order.all
render :json => @orders
end
#edward Test obly
def test_api
puts "Edward ===v1==send_sms====okoko"
verify_code = 9988
twilio_body1 = 'tada 驗證簡訊:[#{verify_code}]'
puts twilio_body1
twilio_body2 = 'tada 驗證簡訊:#{verify_code}'
puts twilio_body2
twilio_body3 = 'tada 驗證簡訊:'+verify_code.to_s
puts twilio_body3
result = true
if business = User.find_by_tele_and_status("+886987198663",1)
puts "Edward ===YESSS member"
else
puts "Edward ===NOOO member"
end
render :json => result ? {"success" => true } : {"nono" =>message.status}
end
#功能: 使用者註冊
#POST /user_register:
#傳入:
#user_name: 使用者名稱
#location: 所在行政區
#phone_number: 使用者電話號碼
#invite_code: 邀請碼
#回傳:
#成功:> { "success": true , "user_id": "122" }
#失敗:> {"error": "0" } # error code: 0-unknow error、1-已經是會員、2-邀請碼無效
def create_user
# put your own credentials here
account_sid = '<KEY> <PASSWORD>'
auth_token = '<PASSWORD>'
result = false
user_name = params[:user_name]
location = params[:location]
phone_number = params[:phone_number]
invite_code = params[:invite_code]
error_code = 0
#確認資料
if user_name.present? and location.present? and phone_number.present?
#確認邀請碼是否有效 EdwardToDo
#確認是否已經是會員
if User.find_by_tele_and_status(phone_number,1)
error_code = 1
else
#不是會員,建立會員
verify_code = SecureRandom.random_number(10000)
user = User.create(
:last_name => user_name,
:location => location,
:tele => phone_number,
:verify_code => verify_code,
:status => 0
)
#傳送簡訊
# set up a client to talk to the Twilio REST API
@client = Twilio::REST::Client.new account_sid, auth_token
@client.account.messages.create({
:from => '+15082983591',
:to => phone_number,
:body => 'tada 驗證簡訊:'+verify_code.to_s,
})
result = true
end
end
render :json => result ? {"success" => true ,"user_id" =>user.id} : {"error" => error_code}
end
#功能: 使用者確認驗證碼
#POST /verify_code:
#傳入:
#user_id: 使用者ID
#verify_code: 驗證碼
#回傳:
#成功:> { "success": true }
#失敗:> { "error": "0" } # error code: 0-unknow error、1-資料不足、2-查無ID、3-驗證碼錯誤
def verify_code
result = false
user_id = params[:user_id]
verify_code = params[:verify_code]
error_code = 0
#確認資料
if user_id.present? and verify_code.present?
#確認是否已經是會員
if user = User.find_by_id(user_id)
#比對驗證碼
if user.verify_code == verify_code then
if user.status == 0
user.status = 1
user.save
end
result = true
else
#驗證碼錯誤
error_code = 3
end
else
#查無ID
error_code = 2
end
else
#資料不足
error_code = 1
end
render :json => result ? {"success" => true } : {"error" => error_code}
end
def update_ok
puts "Edward ===33==update_ok====okoko"
result = false
from_content = params[:from_content]
to_content = params[:to_content]
if from_content and to_content
# check if this user had answered
order = Order.find_by(content: from_content)
order.content = to_content
order.save
result = true
end
render :json => result ? {"success" => true } : {}
end
end<file_sep>/app/controllers/general_controller.rb
# encoding: utf-8
class GeneralController < ApplicationController
# API: 提示需加上.json才能call到API。在routes.rb內把未加.json的導過來
def append_json
render :json => {"error" => "To Call APIs. Please append '.json' in the end of URL"}
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :users
root to: redirect('/orders')
resources :orders
MISSING_JSON_PATH = "general#append_json"
def api_get(params)
uri, path = params.first
get "#{uri}.json" => path, :format => "json"
get uri => MISSING_JSON_PATH
end
def api_post(params)
uri, path = params.first
post "#{uri}.json" => path, :format => "json"
post uri => MISSING_JSON_PATH
end
def api_delete(params)
uri, path = params.first
delete "#{uri}.json" => path, :format => "json"
delete uri => MISSING_JSON_PATH
end
def api_put(params)
uri, path = params.first
put "#{uri}.json" => path, :format => "json"
put uri => MISSING_JSON_PATH
end
#訂單
api_post "api/v1/add_order" => "api/v1/api_orders#create_order"
api_get "api/v1/getorder" => "api/v1/api_orders#index_ok"
api_put "api/v1/putorder" => "api/v1/api_orders#update_ok"
#user
api_post "api/v1/user_register" => "api/v1/api_users#create_user"
api_post "api/v1/verify_code" => "api/v1/api_users#verify_code"
api_get "api/v1/test_api" => "api/v1/api_users#test_api"
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
<file_sep>/db/migrate/20150115062324_create_orders.rb
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.integer :store_id
t.string :store_name
t.integer :user_id
t.integer :status
t.string :reject_reason
t.string :content
t.datetime :accepted_at
t.datetime :finished_at
t.integer :order_fee
t.integer :delivery_fee
t.integer :items_fee
t.integer :tip
t.timestamps null: false
end
end
end
| a119fe9500341bf0ffe71db06e99060878845570 | [
"Ruby"
] | 8 | Ruby | edward65/tada-server | 9b5ec68d93422c9d99d734bed0ea5e689cb71ae8 | 90a14e4dd8eeeab2538779e682bc1b28a50d3bb1 |
refs/heads/master | <repo_name>Muslik/wix-style-react<file_sep>/src/common/EllipsisHOC/EllipsedTooltip.js
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import shallowEqual from 'shallowequal';
import debounce from 'lodash/debounce';
import Tooltip from '../../Tooltip';
import { getDisplayName } from '../hocUtils';
import styles from './EllipsedTooltip.st.css';
class StateFullComponentWrap extends React.Component {
render() {
const { children, ...props } = this.props;
return React.cloneElement(children, props);
}
}
class EllipsedTooltip extends React.Component {
static defaultProps = { showTooltip: true };
state = { isEllipsisActive: false };
componentDidMount() {
window.addEventListener('resize', this._debouncedUpdate);
this._updateEllipsisState();
}
componentWillUnmount() {
this._debouncedUpdate.cancel();
window.removeEventListener('resize', this._debouncedUpdate);
}
componentDidUpdate(prevProps) {
// if props changed, then we want to re-check node for ellipsis state
// and we can not do such check in render, because we want to check already rendered node
if (!shallowEqual(prevProps, this.props)) {
this._updateEllipsisState();
}
}
_updateEllipsisState = () => {
const isEllipsisActive =
this.props.showTooltip &&
this.textNode &&
this.textNode.offsetWidth < this.textNode.scrollWidth;
if (isEllipsisActive !== this.state.isEllipsisActive) {
this.setState({
isEllipsisActive,
});
}
};
_debouncedUpdate = debounce(this._updateEllipsisState, 100);
_renderText = () => {
const { component, style } = this.props;
return (
<StateFullComponentWrap
{...styles('text', {}, component.props)}
style={{
...style,
whiteSpace: 'nowrap',
}}
ref={n => (this.textNode = ReactDOM.findDOMNode(n))}
>
{component}
</StateFullComponentWrap>
);
};
render() {
const { showTooltip, tooltipProps } = this.props;
const { isEllipsisActive } = this.state;
if (isEllipsisActive && showTooltip) {
return (
<Tooltip
appendTo="scrollParent"
{...tooltipProps}
{...styles('root', {}, tooltipProps || this.props)}
content={
<div className={styles.content}>{this.textNode.textContent}</div>
}
showArrow
>
{this._renderText()}
</Tooltip>
);
}
return this._renderText();
}
}
export const withEllipsedTooltip = ({
showTooltip,
shouldLoadAsync,
tooltipProps,
} = {}) => Comp => {
const WrapperComponent = props => (
<EllipsedTooltip
{...props}
component={React.createElement(Comp, props)}
shouldLoadAsync={shouldLoadAsync}
showTooltip={showTooltip}
data-hook="ellipsed-tooltip-wrapper"
tooltipProps={tooltipProps}
/>
);
WrapperComponent.displayName = getDisplayName(Comp);
return WrapperComponent;
};
<file_sep>/src/RadioGroup/RadioButton/RadioButton.private.uni.driver.js
import { radioButtonUniDriverFactory as publicDriverFactory } from './RadioButton.uni.driver';
export const radioButtonPrivateDriverFactory = (base, body) => {
return {
...publicDriverFactory(base, body),
};
};
| 753b1a9bbeebd004086d9baa34ec5cdbfe5ccbf1 | [
"JavaScript"
] | 2 | JavaScript | Muslik/wix-style-react | 6725c8d23ac1974ec572c6d781dab42a9e273050 | c0f176a1409148a65d6a2c6485ccee6470597f94 |
refs/heads/master | <repo_name>IlRomanenko/Deque<file_sep>/Deque/test_main.cpp
#include <vld.h>
#include <gtest/gtest.h>
#include <random>
#include <chrono>
#include "base.h"
#include "deque.h"
class DequeTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
}
virtual void TearDown()
{
deque_int.clear();
}
Deque<int> deque_int;
public:
uniform_int_distribution<int> random;
default_random_engine engine;
void AddElements(int size)
{
fori(i, size)
deque_int.push_back(random(engine));
}
};
TEST_F(DequeTest, VectorInit)
{
for (int i = 0; i < 100; i++)
deque_int.push_back(2 * i + 1);
vector<int> v(deque_int.begin(), deque_int.end());
sort(v.rbegin(), v.rend());
for (int i = 0; i < 300; i++)
deque_int.push_back(2 * i + 1);
cout << v[0] << endl;
}
TEST_F(DequeTest, EmptyInitializer)
{
EXPECT_EQ(0, deque_int.size());
for_each(deque_int.begin(), deque_int.end(),
[](int elem)
{
EXPECT_EQ(0, elem);
});
}
TEST_F(DequeTest, ExtendCapacity)
{
fori(i, 7)
deque_int.push_back(i);
deque_int.push_back(42);
EXPECT_EQ(8, deque_int.size());
}
TEST_F(DequeTest, Can_PushBack_1e3)
{
const int maxn = 1000;
fori(i, maxn)
{
deque_int.push_back(random(engine));
EXPECT_EQ(i + 1, deque_int.size());
}
EXPECT_EQ(1000, deque_int.size());
}
TEST_F(DequeTest, Can_PopBack_1e3)
{
const int maxn = 1000;
AddElements(maxn);
fori(i, maxn)
{
deque_int.pop_back();
EXPECT_EQ(maxn - i - 1, deque_int.size());
}
}
TEST_F(DequeTest, Correct_PushBack_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_back(elem);
}
fori(i, maxn)
{
EXPECT_EQ(v[i], deque_int[i]);
}
}
TEST_F(DequeTest, Correct_PushFront_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_front(elem);
}
fori(i, maxn)
{
EXPECT_EQ(v[maxn - i - 1], deque_int[i]);
}
}
TEST_F(DequeTest, Correct_iterator_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_back(elem);
}
EXPECT_EQ(v.size(), deque_int.size());
int pos = 0;
for (auto it = deque_int.begin(); it != deque_int.end(); it++, pos++)
EXPECT_EQ(v[pos], *it);
pos = 0;
for (auto it = deque_int.cbegin(); it != deque_int.cend(); it++, pos++)
EXPECT_EQ(v[pos], *it);
}
TEST_F(DequeTest, Correct_reverse_iterator_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_back(elem);
}
EXPECT_EQ(v.size(), deque_int.size());
int pos = (int)v.size() - 1;
for (auto it = deque_int.rbegin(); it != deque_int.rend(); it++, pos--)
EXPECT_EQ(v[pos], *it);
pos = (int)v.size() - 1;
for (auto it = deque_int.crbegin(); it != deque_int.crend(); it++, pos--)
EXPECT_EQ(v[pos], *it);
}
TEST_F(DequeTest, Correct_PopBack_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_back(elem);
}
fori(i, maxn)
{
EXPECT_EQ(deque_int.back(), v.back());
deque_int.pop_back();
v.pop_back();
}
}
TEST_F(DequeTest, Correct_PopFront_1e3)
{
vector<int> v;
const int maxn = 1000;
int elem;
fori(i, maxn)
{
elem = random(engine);
v.push_back(elem);
deque_int.push_back(elem);
}
fori(i, maxn)
{
EXPECT_EQ(deque_int.front(), v[i]);
deque_int.pop_front();
}
}
TEST_F(DequeTest, Correct_clear)
{
const int maxn = 1000;
AddElements(maxn);
deque_int.clear();
EXPECT_EQ(0, deque_int.size());
}
TEST_F(DequeTest, Correct_size)
{
const int maxn = 1000;
AddElements(maxn);
int count = 0;
while (!deque_int.empty())
{
EXPECT_EQ(maxn - count, deque_int.size());
deque_int.pop_back();
count++;
}
EXPECT_EQ(maxn, count);
}
TEST_F(DequeTest, LinearTime_1e6)
{
chrono::steady_clock clock;
int maxn = 1000 * 1000;
vector<int> vector_int;
for (int size = 10; size <= maxn; size *= 10)
{
auto before_deque_push = clock.now();
fori(i, size)
deque_int.push_back(random(engine));
while (!deque_int.empty())
deque_int.pop_back();
auto deque_after_pop_back = clock.now();
auto before_vector_push = clock.now();
fori(i, size)
vector_int.push_back(random(engine));
while (!deque_int.empty())
vector_int.pop_back();
auto vector_after_pop_back = clock.now();
auto deque_duration = deque_after_pop_back - before_deque_push;
auto vector_duration = vector_after_pop_back - before_vector_push;
cerr << endl;
cerr << "Size = " << to_string(size) << endl;
cerr << "deque_duration / vector_duration = " << deque_duration.count() / (double)vector_duration.count() << endl;
cerr << "deque_time = " << deque_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << "vector_time = " << vector_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << "relative_time = " << deque_duration.count() / (double)size / (1000 * 1000.0) << " ms" << endl;
cerr << endl;
}
cerr << endl;
}
TEST_F(DequeTest, ReverseDeque_small)
{
deque_int.push_back(10);
deque_int.push_back(20);
deque_int.push_front(30);
//30, 10, 20
reverse(deque_int.begin(), deque_int.end());
//20, 10, 30
const int maxn = 200;
fori(i, maxn)
deque_int.push_back(i * 2 + 1);
//20, 10, 30, 1, 3, 5, 7, 9, ...
reverse(deque_int.begin(), deque_int.end());
// ..., 9, 7, 5, 3, 1, 30, 10, 20
fori(i, maxn)
{
EXPECT_EQ(i * 2 + 1, deque_int[maxn - i - 1]);
}
}
TEST_F(DequeTest, SortDeque)
{
const int maxn = 1000 * 1000;
for (int size = 10; size < maxn; size *= 10)
{
int elem;
vector<int> temp_v;
fori(i, size)
{
elem = random(engine);
deque_int.push_back(elem);
temp_v.push_back(elem);
}
EXPECT_EQ(temp_v.size(), deque_int.size());
chrono::steady_clock clock;
auto before_vector_sort = clock.now();
sort(temp_v.begin(), temp_v.end());
auto after_vector_sort = clock.now();
auto before_deque_sort = clock.now();
sort(deque_int.begin(), deque_int.end());
auto after_deque_sort = clock.now();
auto deque_duration = after_deque_sort - before_deque_sort;
auto vector_duration = after_vector_sort - before_vector_sort;
cerr << endl;
cerr << "Size = " << to_string(size) << endl;
cerr << "deque_duration / vector_duration = " << deque_duration.count() / (double)vector_duration.count() << endl;
cerr << "deque_time = " << deque_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << "vector_time = " << vector_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << endl;
EXPECT_EQ(temp_v.size(), deque_int.size());
while (!temp_v.empty() && !deque_int.empty())
{
EXPECT_EQ(temp_v.back(), deque_int.back());
temp_v.pop_back();
deque_int.pop_back();
}
EXPECT_EQ(temp_v.size(), deque_int.size());
}
cerr << endl;
}
TEST_F(DequeTest, SortDeque_ReverseOrder)
{
const int maxn = 1000 * 1000;
for (int size = 10; size < maxn; size *= 10)
{
int elem;
vector<int> temp_v;
fori(i, size)
{
elem = random(engine);
deque_int.push_back(elem);
temp_v.push_back(elem);
}
EXPECT_EQ(temp_v.size(), deque_int.size());
chrono::steady_clock clock;
auto before_vector_sort = clock.now();
sort(temp_v.rbegin(), temp_v.rend());
auto after_vector_sort = clock.now();
auto before_deque_sort = clock.now();
sort(deque_int.rbegin(), deque_int.rend());
auto after_deque_sort = clock.now();
auto deque_duration = after_deque_sort - before_deque_sort;
auto vector_duration = after_vector_sort - before_vector_sort;
cerr << endl;
cerr << "Size = " << to_string(size) << endl;
cerr << "deque_duration / vector_duration = " << deque_duration.count() / (double)vector_duration.count() << endl;
cerr << "deque_time = " << deque_duration.count() / (1000*1000.0) << " ms" << endl;
cerr << "vector_time = " << vector_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << endl;
EXPECT_EQ(temp_v.size(), deque_int.size());
while (!temp_v.empty() && !deque_int.empty())
{
EXPECT_EQ(temp_v.back(), deque_int.back());
temp_v.pop_back();
deque_int.pop_back();
}
EXPECT_EQ(temp_v.size(), deque_int.size());
}
cerr << endl;
}
TEST_F(DequeTest, LinearTime_1e6_clear_inside)
{
chrono::steady_clock clock;
int maxn = 1000 * 1000;
vector<int> vector_int;
for (int size = 10; size <= maxn; size *= 10)
{
auto before_deque_push = clock.now();
fori(i, size)
deque_int.push_back(random(engine));
deque_int.clear();
auto deque_after_pop_back = clock.now();
auto before_vector_push = clock.now();
fori(i, size)
vector_int.push_back(random(engine));
vector_int.clear();
auto vector_after_pop_back = clock.now();
auto deque_duration = deque_after_pop_back - before_deque_push;
auto vector_duration = vector_after_pop_back - before_vector_push;
cerr << endl;
cerr << "Size = " << to_string(size) << endl;
cerr << "deque_duration / vector_duration = " << deque_duration.count() / (double)vector_duration.count() << endl;
cerr << "deque_time = " << deque_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << "vector_time = " << vector_duration.count() / (1000 * 1000.0) << " ms" << endl;
cerr << "relative_time = " << deque_duration.count() / (double)size / (1000 * 1000.0) << " ms" << endl;
cerr << endl;
}
cerr << endl;
}
int main(int argc, char **argv)
{
cerr.setf(cerr.fixed);
cerr.precision(9);
testing::InitGoogleTest(&argc, argv);
RUN_ALL_TESTS();
system("pause");
return 0;
}<file_sep>/Deque/main.cpp
#include "deque.h"
Deque<int> something()
{
Deque<int> d;
fori(i, 20)
{
d.push_back(2 * i + 1);
}
fori(i, 10)
d.push_front(2 * (-i) + 1);
return d;
}
int main(int argc, char **argv)
{
Deque<int> d;
d = something();
fori (i, 30)
{
cout << d[i] << ' ';
}
cout << endl << endl;
cout << "for (auto it = d.begin(); it != d.end(); it++)" << endl;
for (auto it = d.begin(); it != d.end(); ++it)
cout << *it << ' ';
cout << endl;
cout << "for (auto it = d.cbegin(); it != d.cend(); it++)" << endl;
for (auto it = d.cbegin(); it != d.cend(); it++)
cout << *it << ' ';
cout << endl;
cout << "for (auto it = d.rbegin(); it != d.rend(); it++)" << endl;
for (auto it = d.rbegin(); it != d.rend(); it++)
cout << *it << ' ';
cout << endl;
cout << "for (auto it = d.crbegin(); it != d.crend(); it++)" << endl;
for (auto it = d.crbegin(); it != d.crend(); it++)
cout << *it << ' ';
cout << endl;
cout << "fori(i, 30) { cout << d.begin()[i] << ' '; }" << endl;
fori(i, 30)
{
cout << d.begin()[i] << ' ';
}
cout << endl;
cout << endl << endl;
fori (i, 30)
{
cout << d.back() << ' ';
d.pop_back();
}
system("pause");
return 0;
}<file_sep>/Deque/deque.h
#pragma once
#include "base.h"
#include <vector>
#include <iterator>
#include <algorithm>
const uint base_capacity = 8;
template <typename T> class Deque;
template <typename IteratorType> class container_iterator :
public iterator<random_access_iterator_tag, IteratorType>
{
private:
IteratorType* ptr;
int cur, size, pos;
void move_this(int tsize)
{
tsize -= (tsize / size) * size;
ptr += tsize;
cur += tsize;
pos += tsize;
while (cur >= size)
{
cur -= size;
ptr -= size;
}
while (cur < 0)
{
cur += size;
ptr += size;
}
}
public:
container_iterator(IteratorType* n_ptr, uint pos_in_array, uint capacity, uint pos_in_container)
: ptr(n_ptr), cur(pos_in_array), size(capacity), pos(pos_in_container)
{
}
container_iterator(const container_iterator &it)
{
ptr = it.ptr;
cur = it.cur;
size = it.size;
pos = it.pos;
}
container_iterator(const container_iterator && it)
{
ptr = it.ptr;
cur = it.cur;
size = it.size;
pos = it.pos;
}
container_iterator& operator = (const container_iterator& it)
{
cur = it.cur;
size = it.size;
ptr = it.ptr;
pos = it.pos;
return *this;
}
IteratorType& operator *()
{
return *ptr;
}
const IteratorType& operator *() const
{
return *ptr;
}
container_iterator operator++(int)
{
container_iterator new_it(*this);
move_this(1);
return new_it;
}
container_iterator& operator++()
{
move_this(1);
return *this;
}
container_iterator& operator -- ()
{
move_this(-1);
return *this;
}
container_iterator operator -- (int)
{
container_iterator new_it(*this);
move_this(-1);
return new_it;
}
container_iterator operator + (int f) const
{
container_iterator new_it(*this);
new_it.move_this(f);
return new_it;
}
container_iterator operator - (int f) const
{
container_iterator new_it(*this);
new_it.move_this(-f);
return new_it;
}
int operator - (const container_iterator& it)
{
return pos - it.pos;
}
container_iterator& operator += (int f)
{
move_this(f);
return *this;
}
container_iterator& operator -= (int f)
{
move_this(-f);
return *this;
}
IteratorType& operator [] (int f)
{
container_iterator new_q(*this);
new_q += f;
return *new_q;
}
bool operator != (const container_iterator &it) const
{
return ptr != it.ptr;
}
bool operator == (const container_iterator &it) const
{
return ptr == it.ptr;
}
bool operator < (const container_iterator &it) const
{
return pos < it.pos;
}
bool operator > (const container_iterator &it) const
{
return pos > it.pos;
}
bool operator >= (const container_iterator &it) const
{
return (*this > it || *this == it);
}
bool operator <= (const container_iterator &it) const
{
return (*this < it || *this == it);
}
~container_iterator()
{
}
};
template <typename T> class Deque
{
unique_ptr<T[]> buf;
uint capacity, tail, head;
inline uint nextHead() const
{
return (head - 1 + capacity) % capacity;
}
inline uint nextTail() const
{
return (tail + 1) % capacity;
}
inline uint prevHead() const
{
return (head + 1) % capacity;
}
inline uint prevTail() const
{
return (tail - 1 + capacity) % capacity;
}
T& getAt(int index)
{
return buf[(head + index) % capacity];
}
void extendCapacity()
{
uint new_capacity = capacity << 1;
unique_ptr<T[]> tmp = unique_ptr<T[]>(new T[new_capacity]);
for (uint i = 0; i < capacity; i++)
tmp[i] = getAt(i);
buf.swap(tmp);
head = 0;
tail = capacity;
capacity = new_capacity;
}
void compressCapacity()
{
uint new_capacity = capacity >> 1;
unique_ptr<T[]> tmp = unique_ptr<T[]>(new T[new_capacity]);
uint cur_size = size();
for (uint i = 0; i < cur_size; i++)
tmp[i] = getAt(i);
buf.swap(tmp);
head = 0;
tail = cur_size;
capacity = new_capacity;
}
public:
typedef container_iterator<T> iterator;
typedef container_iterator<const T> const_iterator;
typedef reverse_iterator<const_iterator> const_reverse_iterator;
typedef reverse_iterator<iterator> reverse_iterator;
Deque()
: capacity(base_capacity), head(0), tail(0)
{
buf.reset();
buf = unique_ptr<T[]>(new T[capacity]);
}
Deque(uint user_capacity)
: head(0), tail(0)
{
buf.reset();
capacity = base_capacity;
while (capacity < user_capacity)
capacity <<= 1;
buf = unique_ptr<T[]>(new T[capacity]);
}
Deque(const Deque & obj)
: capacity(obj.capacity), head(obj.head), tail(obj.tail)
{
buf.reset();
buf = new T[capacity];
for (uint i = 0; i < capacity; i++)
buf[i] = obj.buf[i];
}
Deque(Deque && obj)
{
buf.reset();
buf.swap(obj.buf);
capacity = obj.capacity;
head = obj.head;
tail = obj.tail;
}
Deque& operator = (const Deque & obj)
{
capacity = obj.capacity;
head = obj.head;
tail = obj.tail;
buf.reset();
buf = unique_ptr<T[]>(new T[capacity]);
for (uint i = 0; i < capacity; i++)
buf[i] = obj.buf[i];
return *this;
}
bool empty() const
{
return (tail == head);
}
int size() const
{
if (tail >= head)
return tail - head;
return (tail - head + capacity);
}
void clear()
{
unique_ptr<T[]> tmp = unique_ptr<T[]>(new T[base_capacity]);
buf.swap(tmp);
head = tail = 0;
capacity = base_capacity;
}
void push_back(T obj)
{
buf[tail] = obj;
tail = nextTail();
if (tail == head)
extendCapacity();
}
void push_front(T obj)
{
head = nextHead();
buf[head] = obj;
if (head == tail)
extendCapacity();
}
void pop_back()
{
tail = prevTail();
if (size() == capacity / 4 && capacity != base_capacity)
compressCapacity();
}
void pop_front()
{
head = prevHead();
if (size() == capacity / 4 && capacity != base_capacity)
compressCapacity();
}
const T back()
{
return operator[](size() - 1);
}
const T back() const
{
return operator[](size() - 1);
}
const T front()
{
return operator[](0);
}
const T front() const
{
return operator[](0);
}
T& operator[] (int index)
{
if (index < 0 || index > size())
throw new exception();
return getAt(index);
}
const T& operator[] (int index) const
{
if (index < 0 || index > size())
throw new exception();
return getAt(index);
}
iterator begin()
{
return iterator(buf.get() + head, head, capacity, 0);
}
const_iterator begin() const
{
return const_iterator(buf.get() + head, head, capacity, 0);
}
iterator end()
{
return iterator(buf.get() + tail, tail, capacity, tail);
}
const_iterator end() const
{
return const_iterator(buf.get() + tail, tail, capacity, tail);
}
const_iterator cbegin()
{
return const_iterator(buf.get() + head, head, capacity, 0);
}
const_iterator cbegin() const
{
return const_iterator(buf.get() + head, head, capacity, 0);
}
const_iterator cend()
{
return const_iterator(buf.get() + tail, tail, capacity, tail);
}
const_iterator cend() const
{
return const_iterator(buf.get() + tail, tail, capacity, tail);
}
reverse_iterator rbegin()
{
return reverse_iterator(iterator(buf.get() + tail, tail, capacity, tail));
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(iterator(buf.get() + tail, tail, capacity, tail));
}
reverse_iterator rend()
{
return reverse_iterator(iterator(buf.get() + head, head, capacity, 0));
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(iterator(buf.get() + head, head, capacity, 0));
}
const_reverse_iterator crbegin()
{
return const_reverse_iterator(const_iterator(buf.get() + tail, tail, capacity, tail));
}
const_reverse_iterator crbegin() const
{
return const_reverse_iterator(const_iterator(buf.get() + tail, tail, capacity, tail));
}
const_reverse_iterator crend()
{
return const_reverse_iterator(const_iterator(buf.get() + head, head, capacity, 0));
}
const_reverse_iterator crend() const
{
return const_reverse_iterator(const_iterator(buf.get() + head, head, capacity, 0));
}
~Deque()
{
}
};<file_sep>/Deque/base.h
#pragma once
#define _VARIADIC_MAX 10
#include <iostream>
#include <fstream>
#include <memory>
using namespace std;
typedef unsigned int uint;
#define dbg(x) cerr << #x << ' ' << (x) << ' ' << __LINE__ << endl;
#define fori(i, n) for (int i = 0; i < (int)(n); i++)
| 6c7a63adc6459423db9bd072432d0f85a84cba4c | [
"C++"
] | 4 | C++ | IlRomanenko/Deque | 65b66e9e538d196db26c606d36b5308cbf91772d | cc13ae2c54a12e6120726ce5c1acf5746e93c658 |
refs/heads/main | <repo_name>mohammadeslim22/jshw<file_sep>/index.js
const hw = [
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.78,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.26,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
let sumPpu = 0
let ids = []
let topping = []
let batter = []
hw.map(record => {
record.batters.batter.map(bat => {
batter.push(bat);
ids.push(bat.id)
})
record.topping.map(top => {
topping.push(top);
ids.push(top.id)
})
sumPpu += record.ppu
})
console.log(topping)
console.log(batter)
console.log(sumPpu / hw.length)
console.log(sumPpu)
console.log(ids)
| c71b5386d04df338a895c2276821a1ff3dbb5265 | [
"JavaScript"
] | 1 | JavaScript | mohammadeslim22/jshw | 07213bd3e1ebd14995663b54d9784eb5319d0d6e | 8c5be90a6ababd0f3cd34e34402c0bdd1f01883f |
refs/heads/master | <repo_name>tacticalDevC/YubiKey-Guide<file_sep>/scripts/keygen.py
#!/usr/bin/env python3
import os
import sys
import argparse
from subprocess import Popen, PIPE, getoutput
from apt.cache import Cache
from getpass import getpass
from gpg import Context
from pycurl import Curl
import certifi
_PACKAGES_LIST = {
"wget": False,
"gnupg2": False,
"gnupg-agent": False,
"dirmngr": False,
"cryptsetup": False,
"scdaemon": False,
"pcscd": False,
"secure-delete": False,
"hopenpgp-tools": False,
"yubikey-personalization": False
}
_SERVICES_TO_SHUTDOWN = {
"network-manager",
"NetworkManager",
"avahi-daemon"
}
# ===== START OF CORE FUNCTIONS =====
def out_success(text):
print("[+] " + text)
def out_error(text):
print("[!] ERROR: " + text)
def out_info(text):
print("[i] " + text)
def out_question_yes_no(text):
print(text)
resp = input("Please choose (Y/y/N/n): ")
if resp.lower() == "y":
return 1
else:
return 0
def out_question_arbitrary(text):
return input(text)
# ===== END OF CORE FUNCTIONS =====
# ===== START OF FUNCTIONS =====
def verify_yk():
return out_question_yes_no("Did you verify your YubiKey?")
def verify_live():
live = os.system(_CMD_WHOAMI + " | grep \"user\"") # Rewrite that. Detect live system not username
# Maybe detect the device root is mounted on? /dev/sdx
if live is 0:
return True
return False
def kill_network():
cmdchain = ""
for service in _SERVICES_TO_SHUTDOWN:
cmdchain += "sudo "+_SUDO_ARGS+_CMD_SERVICE+" "+service+" stop;"
for interface in os.listdir("/sys/class/net"):
if not interface == "lo":
cmdchain += "sudo "+_SUDO_ARGS+_CMD_IFCONFIG+" "+interface+" down;"
proc = Popen(cmdchain, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, text=True)
if not _USE_ASKPASS: passwd = getpass(); proc.communicate(passwd + "\n")
proc.wait()
def check_dependencies():
cache = Cache()
ret = True
for package in _PACKAGES_LIST:
if cache[package].is_installed:
_PACKAGES_LIST[package] = True
else:
ret = False
return ret
def install_dependencies():
cache = Cache()
if _SUDO_V19:
pass
# Do sudo v1.9 stuff here
#cache.update()
#cache.open()
# for package in packages_list:
# if packages_list[package] is False:
# cache[package].mark_install()
# cache.commit()
# Remember to drop sudo privs here
else:
missing_packages = ""
for package in _PACKAGES_LIST:
if _PACKAGES_LIST[package] is False:
missing_packages += package+" "
proc = Popen(
"sudo "+_SUDO_ARGS+"apt update;"
"sudo "+_SUDO_ARGS+"apt install -y "+missing_packages,
shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, text=True)
if not _USE_ASKPASS: passwd = getpass(); proc.communicate(passwd+"\n")
proc.wait()
passwd = None
def download_conf():
with open(_WORKDIR+"/gpg.conf", 'wb') as f:
c = Curl()
c.setopt(c.URL, "https://raw.githubusercontent.com/drduh/config/master/gpg.conf")
c.setopt(c.WRITEDATA, f)
c.setopt(c.CAINFO, certifi.where())
c.perform()
c.close()
out_success("Configuration downloaded!")
# ===== START KEY GENERATION =====
def keygen():
c = Context(True, home_dir=_WORKDIR)
uid = out_question_arbitrary("Your name: ")+" <"+out_question_arbitrary("Your E-Mail: ")+">"
passwd = getoutput("gpg --gen-random --armor 0 24")
print("This is your passphrase. Write it down somewhere safe!\n"+passwd)
# Create master key
masterkey = c.create_key(uid, "rsa4096", expires=False, certify=True, passphrase=<PASSWORD>)
master_fpr = masterkey.fpr
seckey = c.get_key(master_fpr, True)
# create subkeys
sign_key = c.create_subkey(seckey, "rsa4096", 31536000, sign=True)
encrypt_key = c.create_subkey(seckey, "rsa4096", 31536000, encrypt=True)
auth_key = c.create_subkey(seckey, "rsa4096", 31536000, authenticate=True)
# Export master key
with open(_WORKDIR+"/master.sec.asc", "wb") as f:
f.write(c.key_export_secret(master_fpr))
f.flush()
f.close()
with open(_WORKDIR+"/sub.sec.asc", "wb") as f:
f.write(c.key_export_secret(sign_key.fpr))
f.write(c.key_export_secret(encrypt_key.fpr))
f.write(c.key_export_secret(auth_key.fpr))
f.flush()
f.close()
out_success("Keys generated!")
# ===== END KEY GENERATION =====
# ===== END OF FUNCTIONS =====
# ===== START OF MAIN =====
parser = argparse.ArgumentParser(
description="This script tries to accomplish what @drdruh describes in the README\n"
"WARNING: This script only works on Debian and Ubuntu"
)
parser.add_argument("--verified-yk",
action="store_true",
help="Skip the YubiKey verification check (!DANGEROUS! If your YK is compromised your keys are too!)")
parser.add_argument("--skip-live",
action="store_true",
help="Skip the live system check (!DANGEROUS! Data could be saved on your hard disk)")
parser.add_argument("-d1", "--sec-backup-device",
nargs=1,
type=str,
help="Device to send the secret keys backup to")
parser.add_argument("-d2", "--public-backup-device",
nargs=1,
type=str,
help="Device to send the public key backup to")
parser.add_argument("--create-backup-usb",
nargs=1,
type=str,
help="Path to device to create a encrypted backup")
parser.add_argument("--no-hardened",
action="store_false",
help="Don't use the hardened configuration (WARNING: you could generate weak keys!)")
args = parser.parse_args()
# ===== CONSTANTS =====
_YK_VERIFIED = args.verified_yk
_LIVE_VERIFIED = args.skip_live
_USE_HARDENED_CONF = args.no_hardened
_SUDO_V19 = False
_SUDO_ARGS = "-S"
_USE_ASKPASS = False
_CMD_SERVICE = getoutput("which service")
_CMD_IFCONFIG = getoutput("which ifconfig")
_CMD_WHOAMI = getoutput("which whoami")
_BACKUP_SEC_DEVICE = args.sec_backup_device
_BACKUP_PUB_DEVICE = args.public_backup_device
_BACKUP_DEVICE = args.create_backup_usb
_WORKDIR = getoutput("mktemp -d")
# ===== CONSTANTS =====
# ===== PRE-CHECKS =====
try:
import sudo
_SUDO_V19 = True # Not used yet tho. Don't know the sudo plugin API.
except ModuleNotFoundError:
pass
if os.environ.get("SUDO_ASKPASS") is not None:
_USE_ASKPASS = True
_SUDO_ARGS += ("A " if _USE_ASKPASS else " ")
if _BACKUP_SEC_DEVICE is not None and _BACKUP_PUB_DEVICE is not None:
if _BACKUP_DEVICE is not None:
out_error("Please use either \"--sec-backup-device\" with \"--public-backup-device\" or \"--create-backup-usb\"")
exit(1)
else:
if _BACKUP_DEVICE is None:
out_error("Please use either \"--sec-backup-device\" with \"--public-backup-device\" or \"--create-backup-usb\"")
exit(1)
# ===== END PRE-CHECKS =====
if not _YK_VERIFIED and verify_yk() is not 1:
os.system("/bin/bash -c \"x-www-browser 'https://www.yubico.com/genuine/'\"")
out_error("Please verify before proceeding!")
exit(1)
if _LIVE_VERIFIED or verify_live():
out_success("Great! You seem to be on a live system!")
else:
out_error("You are not on a live system! Please boot into one or pass the \"--skip-live\" flag!")
exit(1)
if check_dependencies():
out_success("Great! All packages are installed!")
else:
if out_question_yes_no("Some packages are missing. Would you like me to install them?"):
out_info("Installing packages...")
install_dependencies()
out_success("Everything set up!")
else:
out_error("Sorry can't run without them.")
exit(1)
if _USE_HARDENED_CONF:
download_conf()
out_info("Shutting down all interfaces...")
kill_network()
out_success("Seems like we are ready to go. YAY! Let's generate keys!")
# TODO:Setup backup device here
keygen()
# ===== END MAIN ===== | ae9fc853aa7dfa6b149ad8eac442ed94545004c1 | [
"Python"
] | 1 | Python | tacticalDevC/YubiKey-Guide | 93975ea5081d860ec69668c1256eef57661c3a44 | 5e6b89b59ebd1ddb6965307c5283b48f4cd2deeb |
refs/heads/master | <file_sep>Pod::Spec.new do |s|
s.name = "DXYTCWeiboSDK"
s.version = "2.0"
s.summary = "腾讯微博 SDK,支持 arm64."
s.requires_arc = true
s.homepage = "http://dev.t.qq.com"
s.license = { :type => 'LGPL', :text => <<-LICENSE
® 1998 - 2014 Tencent All Rights Reserved.
LICENSE
}
s.author = "tencent.com"
s.platform = :ios
s.source = { :git => "https://github.com/dxy-developer/DXYTCWeiboSDK.git", :tag => "v#{s.version.to_s}" }
s.source_files = 'TCWeiboSDK/*.{h,m}'
s.vendored_libraries = 'TCWeiboSDK/libTCWeiboSDK.a'
s.frameworks = 'Social','Accounts'
end<file_sep>DXYTCWeiboSDK
=============
DXYTCWeiboSDK
| 17ba008c0df5efd960fcefd2f01389c0a0fe13fd | [
"Markdown",
"Ruby"
] | 2 | Ruby | dxy-developer/DXYTCWeiboSDK | af2515fa59e1eb1383e8720dd593ae6133a809da | 9fca0f8a9975637927cd8a6c73bdc2590bf2d918 |
refs/heads/master | <file_sep>#ifndef __VIDEO_H__
#define __VIDEO_H__
#ifdef __cplusplus
extern "C" {
#endif
enum video_format_t {
VIDEO_FORMAT_ARGB = 0,
VIDEO_FORMAT_YUYV = 1,
VIDEO_FORMAT_NV12 = 2,
VIDEO_FORMAT_NV21 = 3,
VIDEO_FORMAT_YU12 = 4,
VIDEO_FORMAT_YV12 = 5,
VIDEO_FORMAT_MJPG = 6,
};
struct video_frame_t {
enum video_format_t fmt;
int width;
int height;
int buflen;
void * buf;
};
void video_frame_to_argb(struct video_frame_t * frame, void * pixels);
#ifdef __cplusplus
}
#endif
#endif /* __VIDEO_H__ */
| de80da445501daedd473fda0cd8d08d598b13c68 | [
"C"
] | 1 | C | lichee-pi-nano/xboot | ed5bdeae123fd721c83dc6c8204fc2507dea3da3 | e895e87c98f9faf0d8afcec86e8870799c5806d9 |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Mar 21, 2021 at 03:33 AM
-- Server version: 5.7.24
-- PHP Version: 7.2.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `language`
--
-- --------------------------------------------------------
--
-- Table structure for table `failed_jobs`
--
CREATE TABLE `failed_jobs` (
`id` bigint(20) UNSIGNED NOT NULL,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `languages`
--
CREATE TABLE `languages` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`countryImage` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `languages`
--
INSERT INTO `languages` (`id`, `name`, `countryImage`, `created_at`, `updated_at`) VALUES
(1, 'English', 'assets/flag/English.png', NULL, NULL),
(2, 'Spanish', 'assets/flag/Spanish.png', NULL, NULL),
(3, 'French', 'assets/flag/French.png', NULL, NULL),
(4, 'Japan', 'assets/flag/Japan.png', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `language_keys`
--
CREATE TABLE `language_keys` (
`id` bigint(20) UNSIGNED NOT NULL,
`key` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `language_keys`
--
INSERT INTO `language_keys` (`id`, `key`, `created_at`, `updated_at`) VALUES
(1, 'Enter Full Name', NULL, NULL),
(2, 'Enter Father\'s name', NULL, NULL),
(3, 'Enter Mother\'s name', NULL, NULL),
(4, 'Enter Your address', NULL, NULL),
(5, 'Enter your Password', NULL, NULL),
(6, 'Forget your password?', NULL, NULL),
(7, 'Choose your image', NULL, NULL),
(8, 'Enter Present address', NULL, NULL),
(9, 'Re-enter password', NULL, NULL),
(10, 'How are you?', NULL, NULL),
(11, 'who are you ?', NULL, NULL),
(12, 'Hellow, how are you?', NULL, NULL),
(13, 'welcome back', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2019_08_19_000000_create_failed_jobs_table', 1),
(5, '2021_03_13_102612_create_languages_table', 2),
(6, '2021_03_13_105223_create_language_keys_table', 3),
(7, '2021_03_13_172851_create_subtitles_table', 4);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `subtitles`
--
CREATE TABLE `subtitles` (
`id` bigint(20) UNSIGNED NOT NULL,
`languageKey_id` int(11) NOT NULL,
`language_id` int(11) NOT NULL,
`subtitle` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `subtitles`
--
INSERT INTO `subtitles` (`id`, `languageKey_id`, `language_id`, `subtitle`, `created_at`, `updated_at`) VALUES
(1, 12, 4, 'こんにちは、元気ですか?', NULL, NULL),
(2, 2, 1, 'Enter Father\'s name', NULL, NULL),
(3, 13, 1, 'welcome back', NULL, NULL),
(4, 1, 4, 'フルネームを入力してください', NULL, NULL),
(5, 1, 3, 'Entrez le nom complet', NULL, NULL),
(6, 1, 2, 'Ingrese su nombre completo', NULL, NULL),
(7, 2, 2, 'Ingrese el nombre del padre', NULL, NULL),
(8, 2, 3, 'Entrez le nom du père', NULL, NULL),
(9, 2, 4, '父の名前を入力してください', NULL, NULL),
(10, 10, 1, 'How are you?', NULL, NULL),
(11, 11, 1, 'who are you', NULL, NULL),
(12, 12, 1, 'Hellow, how are you?', NULL, NULL),
(13, 3, 1, 'Enter Mother\'s name', NULL, NULL),
(14, 4, 1, 'Enter Your address', NULL, NULL),
(15, 5, 1, 'Enter your Password', NULL, NULL),
(16, 6, 1, 'Forget your password?', NULL, NULL),
(17, 7, 1, 'Choose your image', NULL, NULL),
(18, 8, 1, 'Enter Present address', NULL, NULL),
(19, 9, 1, 'Re-enter password', NULL, NULL),
(20, 3, 3, 'Entrez le nom de la mère', NULL, NULL),
(21, 3, 4, '母の名前を入力してください', NULL, NULL),
(22, 3, 2, 'Ingrese el nombre de la madre', NULL, NULL),
(23, 4, 2, 'Ingrese su dirección', NULL, NULL),
(24, 4, 3, 'Entrez votre adresse', NULL, NULL),
(25, 4, 4, 'あなたの住所を入力してください', NULL, NULL),
(26, 5, 4, 'パスワードを入力してください', NULL, NULL),
(27, 5, 3, 'Tapez votre mot de passe', NULL, NULL),
(28, 5, 2, 'Ingresa tu contraseña', NULL, NULL),
(29, 6, 2, '¿Olvidaste tu contraseña?', NULL, NULL),
(30, 6, 3, 'Mot de passe oublié?', NULL, NULL),
(31, 6, 4, 'パスワードを忘れましたか?', NULL, NULL),
(32, 8, 4, '現在の住所を入力してください', NULL, NULL),
(33, 8, 2, 'Ingrese la dirección actual', NULL, NULL),
(34, 8, 3, 'Entrez l\'adresse actuelle', NULL, NULL),
(35, 11, 3, 'qui es-tu', NULL, NULL),
(36, 11, 4, 'あなたは誰', NULL, NULL),
(37, 11, 2, '¿Quién es usted?', NULL, NULL),
(38, 12, 2, '¿Hola como estas?', NULL, NULL),
(39, 12, 3, 'Bonjour comment vas-tu?', NULL, NULL),
(40, 1, 1, 'Enter Full Name', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `failed_jobs`
--
ALTER TABLE `failed_jobs`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `languages`
--
ALTER TABLE `languages`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `language_keys`
--
ALTER TABLE `language_keys`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `subtitles`
--
ALTER TABLE `subtitles`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `failed_jobs`
--
ALTER TABLE `failed_jobs`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `languages`
--
ALTER TABLE `languages`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `language_keys`
--
ALTER TABLE `language_keys`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `subtitles`
--
ALTER TABLE `subtitles`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=41;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
use Illuminate\Support\Facades\Route;
Route::get('lang/{locale}/{langId}', 'HomeController@lang');
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::post('addLanguage', 'HomeController@addLanguage')->name('addLanguage');
Route::post('addKey', 'HomeController@addKey')->name('addKey');
Route::get('subtitle', 'HomeController@subtitle')->name('subtitle');
Route::post('addSubtitle', 'HomeController@addSubtitle')->name('addSubtitle');
Route::post('editSubtitle', 'HomeController@editSubtitle')->name('editSubtitle');
Route::get('next', 'HomeController@home')->name('home');
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subtitle extends Model{
protected $fillable = ['languageKey_id', 'language_id', 'subtitle'];
public function languageKey(){
return $this->belongsTo('App\LanguageKey','languageKey_id', 'id');
}
public function language(){
return $this->belongsTo('App\Language','language_id', 'id');
}
}
<file_sep><?php
//Language Default [English] which id no == 1
$languageId = 1;
$lange = App\Subtitle::where('language_id', $languageId)->select('languageKey_id', 'subtitle')->get();
$output = array();
foreach ($lange as $lang) {
$output[$lang->languageKey->key]= $lang->subtitle;
}
return $output;<file_sep><?php
$languageId = session()->get('languageId');
$lange = App\Subtitle::where('language_id', $languageId)->select('languageKey_id', 'subtitle')->get();
$output = array();
foreach ($lange as $lang) {
$output[$lang->languageKey->key]= $lang->subtitle;
}
return $output;<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App;
use App\Language;
use App\LanguageKey;
use App\Subtitle;
class HomeController extends Controller{
public function lang($locale, $languageId){
App::setLocale($locale);
session()->put('locale', $locale);
session()->put('languageId', $languageId);
return redirect()->back();
}
public function home(){
return view('home');
}
// addLanguage
public function addLanguage(Request $request){
$validator = $request->validate([
'name'=>'required|unique:languages,name',
'flag'=>'required'
]);
if ($request->hasFile('flag')){
if($files=$request->file('flag')){
$countryName = $request->name;
$countryImage = $request->flag;
$fullName=$countryName.".".$countryImage->getClientOriginalExtension();
$files->move('assets/flag/', $fullName);
$imageLink = "assets/flag/". $fullName;
Language::insert([
'name'=>$request->name,
'countryImage'=>$imageLink
]);
}
return back()->with('success','Language add Successfully');
}else{
return back()->with('fail','Sorry! Language add Fail. Try new language.');
}
}
// addKey
public function addKey(Request $request){
$validator = $request->validate([
'key'=>'required|unique:language_keys,key'
]);
$languageKey_id = LanguageKey::insertGetId([
'key'=>$request->key
]);
Subtitle::insert([
'languageKey_id'=>$languageKey_id,
'language_id'=>1,
'subtitle'=>$request->key
]);
return back()->with('success','Language key add Successfully');
}
//Subtitle
public function subtitle(){
return view('subtitle');
}
public function addSubtitle(Request $request){
Subtitle::insert([
'languageKey_id'=>$request->languageKey_id,
'language_id'=>$request->language_id,
'subtitle'=>$request->subtitle
]);
return back()->with('success','Subtitle add Successfully');
}
public function editSubtitle(Request $request){
Subtitle::find($request->id)->update([
'subtitle'=>$request->subtitle
]);
return back();
}
}
<file_sep>### Laravel Localization
<a href="https://localization.aslambd.com/" target="_blank">
<img src="storage/images/click_me.png" width="auto" height="260">
</a>
### Documentation
<details>
<summary>1) Make Three(3) Model [Language, LanguageKey, Subtitle]</summary>
i) php artisan make:model Language -m
app/database/migrations/language
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('countryImage');
$table->timestamps();
});
ii) php artisan make:model LanguageKey -m
app/database/migrations/language_keys
Schema::create('language_keys', function (Blueprint $table) {
$table->id();
$table->string('key');
$table->timestamps();
});
iii) php artisan make:model Subtitle -m
App/database/migrations/subtitles
Schema::create('subtitles', function (Blueprint $table) {
$table->id();
$table->integer('languageKey_id');
$table->integer('language_id');
$table->text('subtitle');
$table->timestamps();
});
iv) php artisan migrate
</details>
<details>
<summary>2) Model edit</summary>
i) app/Language.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Language extends Model {
protected $fillable = ['name', 'countryImage'];
public function subtitle(){
return $this->hasOne(Subtitle::class);
}
}
ii) app/Subtitle.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subtitle extends Model{
protected $fillable = ['languageKey_id', 'language_id', 'subtitle'];
public function languageKey(){
return $this->belongsTo('App\LanguageKey','languageKey_id', 'id');
}
public function language(){
return $this->belongsTo('App\Language','language_id', 'id');
}
}
</details>
<details>
<summary>3) Middleware command</summary>
php artisan make:middleware Localization
app/Http/Middleware/Localization.php
<?php
// Localization.php
namespace App\Http\Middleware;
use Closure;
use App;
class Localization {
public function handle($request, Closure $next) {
if (session()->has('locale')) {
App::setLocale(session()->get('locale'));
}
return $next($request);
}
}
</details>
<details>
<summary>4) Localization MiddlewareKernel.php</summary>
App\Http\Kernel's $middlewareGroup's array
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Localization::class, /*Insert this line only*/
],
'api' => [
'throttle:60,1',
'bindings',
],
];
</details>
<details>
<summary>5) HomeController.php</summary>
app/http/controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App;
use App\Language;
use App\LanguageKey;
use App\Subtitle;
class HomeController extends Controller{
public function lang($locale, $languageId){
App::setLocale($locale);
session()->put('locale', $locale);
session()->put('languageId', $languageId);
return redirect()->back();
}
public function home(){
return view('home');
}
// addLanguage
public function addLanguage(Request $request){
$validator = $request->validate([
'name'=>'required|unique:languages,name',
'flag'=>'required'
]);
if ($request->hasFile('flag')){
if($files=$request->file('flag')){
$countryName = $request->name;
$countryImage = $request->flag;
$fullName=$countryName.".".$countryImage->getClientOriginalExtension();
$files->move('assets/flag/', $fullName);
$imageLink = "assets/flag/". $fullName;
Language::insert([
'name'=>$request->name,
'countryImage'=>$imageLink
]);
}
return back()->with('success','Language add Successfully');
}else{
return back()->with('fail','Sorry! Language add Fail. Try new language.');
}
}
// addKey
public function addKey(Request $request){
$validator = $request->validate([
'key'=>'required|unique:language_keys,key'
]);
$languageKey_id = LanguageKey::insertGetId([
'key'=>$request->key
]);
Subtitle::insert([
'languageKey_id'=>$languageKey_id,
'language_id'=>1,
'subtitle'=>$request->key
]);
return back()->with('success','Language key add Successfully');
}
//Subtitle
public function subtitle(){
return view('subtitle');
}
public function addSubtitle(Request $request){
Subtitle::insert([
'languageKey_id'=>$request->languageKey_id,
'language_id'=>$request->language_id,
'subtitle'=>$request->subtitle
]);
return back()->with('success','Subtitle add Successfully');
}
public function editSubtitle(Request $request){
Subtitle::find($request->id)->update([
'subtitle'=>$request->subtitle
]);
return back();
}
}
</details>
<details>
<summary>6) lang</summary>
i) resources/lang/en/language.php
Make file: language.php
<?php
//Language Default [English] which id no == 1
$languageId = 1;
$lange = App\Subtitle::where('language_id', $languageId)->select('languageKey_id', 'subtitle')->get();
$output = array();
foreach ($lange as $lang) {
$output[$lang->languageKey->key]= $lang->subtitle;
}
return $output;
ii) Make folder: All_Language
resources/lang/All_Language/language.php</p>
<?php
$languageId = session()->get('languageId');
$lange = App\Subtitle::where('language_id', $languageId)->select('languageKey_id', 'subtitle')->get();
$output = array();
foreach ($lange as $lang) {
$output[$lang->languageKey->key]= $lang->subtitle;
}
return $output;
</details>
<details>
<summary>7) Blade page</summary>
i) app.blade.php
resources/views/layouts/app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
@include('includes.head')
</head>
<body>
@include('includes.header')
@yield('content')
@include('includes.modal')
@include('includes.footer')
</body>
</html>
ii) head.blade.php
resources/views/includes/head.blade.php
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{-- <meta http-equiv="refresh" content="2" /> --}}
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
<link href="{{ asset('assets/style.css') }}" rel="stylesheet">
iii) header.blade.php
resources/views/includes/header.blade.php
<nav class="navbar navbar-expand-md navbar-light navbar-laravel" style="background-color: cyan;">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Localization') }}
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav m-auto">
<li class="nav-item">
<a class="nav-link btn btn-sm btn-primary text-light" data-toggle="modal" data-original-title="test" data-target="#addLanguage">Add Language</a>
</li>
<li class="nav-item mx-2">
<a class="nav-link btn btn-sm btn-success text-light" data-toggle="modal" data-original-title="test" data-target="#addKey">Add Key</a>
</li>
<li class="nav-item">
<a class="nav-link btn btn-sm btn-secondary text-light" href="{{url('subtitle')}}">Add Subtitle</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{-- Language <span class="caret"></span> --}}
<i class="fas fa-globe"></i>
@php
if(session()->get('languageId')){
$languageId = session()->get('languageId');
$id=$languageId;
$Language = App\Language::find($id);
}else{
$languageId = 1;
$id=$languageId;
$Language = App\Language::find($id);
}
@endphp
@switch($languageId)
@case($id)
{{$Language->name}}
@break
@default
English
@endswitch
</a>
{{-- Top side --}}
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
@php
$Languages = App\Language::all();
@endphp
@foreach($Languages as $Language)
<a class="dropdown-item" href="{{url('lang', ['All_Language', $Language->id])}}">
<img src="{{asset($Language->countryImage)}}" width="30px" height="20x"> {{$Language->name}}
</a>
@endforeach
</div>
</li>
</ul>
</div>
</div>
</nav>
iv) modal.blade.php
resources/views/includes/modal.blade.php
{{-- Add Language --}}
<div class="modal fade" id="addLanguage" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title f-w-600" id="exampleModalLabel">Add Language</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form action="{{ url('addLanguage') }}" method="post" enctype="multipart/form-data" class="needs-validation" >
@csrf
<div class="form">
<div class="form-group">
<label for="name" class="mb-1">Language Full Name:</label>
<input name="name" class="form-control" id="name" type="text" value="{{ old('name')}}" placeholder="Ex: Bangladesh, Japan, India" required>
</div>
<div class="form-group">
<label for="codeTitle" class="mb-1">Country Image/Logo:</label>
<input type="file" class="form-control" name="flag" required>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">Add Now</button>
<button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Add Key --}}
<div class="modal fade" id="addKey" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title f-w-600" id="exampleModalLabel">Add Key</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form action="{{ url('addKey') }}" method="post" enctype="multipart/form-data" class="needs-validation" >
@csrf
<div class="form">
<div class="form-group">
<label for="key" class="mb-1">Key Name:</label>
<input name="key" class="form-control" id="key" type="text" value="{{ old('key')}}" placeholder="Ex: Home_Page, Profile_page" required>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">Add Now</button>
<button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Edit Subtitle --}}
<div class="modal fade" id="editSubtitle" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title f-w-600" id="exampleModalLabel">Edit code</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form action="{{ url('editSubtitle') }}" method="post" enctype="multipart/form-data" class="needs-validation" >
@csrf
<div class="form">
<div class="form-group">
<label for="language_key" class="mb-2">Key Id :</label>
<input name="id" class="form-control" id="id" readonly>
</div>
<div class="form-group">
<label for="language_key" class="mb-2">Language key :</label>
<input name="language_key" class="form-control" id="language_key" type="text" readonly>
</div>
<div class="form-group">
<label for="subtitle" class="mb-2">Subtitle Code :</label>
<textarea name="subtitle" class="form-control" id="subtitle" type="text" rows="5"></textarea>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="submit">Change Code</button>
<button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
v) footer.blade.php
resources/views/includes/footer.blade.php
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
{{-- Edit subtitle --}}
<script type="text/javascript">
$('#editSubtitle').on('show.bs.modal', function (event) {
console.log('Model Opened')
var button = $(event.relatedTarget)
var id = button.data('id')
// var codeTitle = button.data('codeTitle') [Camel case not allow. So don't use it]
var language_key = button.data('language_key')
var subtitle = button.data('subtitle')
var modal = $(this)
modal.find('.modal-body #id').val(id);
modal.find('.modal-body #language_key').val(language_key);
modal.find('.modal-body #subtitle').val(subtitle);
})
</script>
<script type="text/javascript">
$(document).ready( function () {
$('.table').DataTable();
} );
</script>
<script type="text/javascript">
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);
</script>
vi) home.blade.php
resources/views/home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
@if (session('success'))
<div class="alert alert-success" role="alert">
{{ session('success') }}
</div>
@endif
@if (session('fail'))
<div class="alert alert-danger" role="alert">
{{ session('fail') }}
</div>
@endif
<div class="col-md-8">
<div class="card">
<div class="card-header bg-success mb-2">Example Subtitle</div>
<div class="card-body">
<p> {{ trans('language.Hellow, how are you?')}}</p>
<p> @lang('language.Hellow,how are you?') </p>
<p>{{ __('language.Enter your Password')}}</p>
{{-- Space allow on laravel --}}
</div>
</div>
<br>
<a class="btn btn-info" href="{{url('/')}}">Back page</a>
</div>
</div>
</div>
@endsection
vii) subtitle.blade.php
resources/views/subtitle.blade.php
@extends('layouts.app')
@section('content')
<div class="container my-4">
@if (session('success'))
<div class="alert alert-success" role="alert">
{{ session('success') }}
</div>
@endif
@if (session('fail'))
<div class="alert alert-danger" role="alert">
{{ session('fail') }}
</div>
@endif
<div class="d-flex align-items-start row mt-4">
<div class="nav flex-column col-auto nav-pills bg-light border p-1" id="v-pills-tab" role="tablist" aria-orientation="vertical">
@php
$Languages = App\Language::all();
$total_languageKey = App\LanguageKey::all()->count();
@endphp
@foreach($Languages as $Language)
<button class="nav-link btn btn-sm btn-outline-primary p-1 m-1 @if($loop->index==0) active @endif" data-bs-toggle="pill" data-bs-target="#v-pills-{{$Language->id}}">
{{$Language->name}}
</button>
@endforeach
</div>
<div class="tab-content col" id="v-pills-tabContent">
@foreach($Languages as $Language)
@php $total_complete_subtitle = App\Subtitle::where('language_id', $Language->id)->get()->count();
$total_incomplete_subtitle = $total_languageKey - $total_complete_subtitle;
@endphp
<div class="tab-pane fade show @if($loop->index==0) active @endif" id="v-pills-{{$Language->id}}">
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<button class="nav-link btn-sm bg-danger text-light @if($loop->index==0) active @endif" data-bs-toggle="tab" data-bs-target="#nav-{{$Language->id}}_code">Incomplete Subtitle[{{$total_incomplete_subtitle}}/{{$total_languageKey}}]</button>
<button class="nav-link btn-sm bg-success text-light" data-bs-toggle="tab" data-bs-target="#nav-{{$Language->id}}_output">Complete Subtitle[{{$total_complete_subtitle}}/{{$total_languageKey}}]</button>
</div>
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active resp-tab-content" id="nav-{{$Language->id}}_code" role="tabpanel" aria-labelledby="nav-{{$Language->id}}_code-tab">
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<div class="card-header bg-danger mb-2">{{$Language->name}}</div>
<table class="table table-striped table-bordered">
<thead class="text-center">
<tr>
<th>KeyId</th>
<th>Key value</th>
<th>Enter Subtitle</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@php
$subtitleKeys =
App\LanguageKey::join('subtitles', 'subtitles.languageKey_id', '=', 'language_keys.id')
->join('languages', 'languages.id', '=', 'subtitles.language_id')
->where('subtitles.language_id', '=', $Language->id)
->select('subtitles.languagekey_id')->get();
$subtitleKeys = collect($subtitleKeys)->pluck('languagekey_id');
$keys = App\LanguageKey::all();
$allKeys = collect($keys)->pluck('id');
$unSubtitles = $allKeys->diff($subtitleKeys);
@endphp
@foreach($unSubtitles as $id)
@php
$LanguageKey = App\LanguageKey::find($id);
@endphp
<tr>
<form action="{{ url('addSubtitle') }}" method="post">
@csrf
<td>
<input type="hidden" name="languageKey_id" value="{{$LanguageKey->id}}"> {{$LanguageKey->id}}
</td>
<td>
<input type="hidden" name="language_id" value="{{$Language->id}}"> {{ $LanguageKey->key}}
</td>
<td >
<input type="" class="subtitle_input" name="subtitle" required>
</td>
<td>
<button class="btn btn-sm btn-danger text-light">Add Subtitle</button>
</td>
</form>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="nav-{{$Language->id}}_output" role="tabpanel" aria-labelledby="nav-{{$Language->id}}_output-tab">
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<div class="card-header bg-success mb-2">{{$Language->name}}</div>
<table class="table table-striped table-bordered">
<thead class="text-center">
<tr>
<th>KeyId</th>
<th>Key value</th>
<th>Subtitle</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@php
$subtitleKeys =
App\LanguageKey::join('subtitles', 'subtitles.languageKey_id', '=', 'language_keys.id')
->join('languages', 'languages.id', '=', 'subtitles.language_id')
->where('subtitles.language_id', '=', $Language->id)
->select('subtitles.id','subtitles.languagekey_id', 'subtitles.subtitle')->get();
@endphp
@foreach($subtitleKeys as $subtitleKey)
@php
$LanguageKeys = App\LanguageKey::where('id', '=', $subtitleKey->languagekey_id)->get();
@endphp
@foreach($LanguageKeys as $LanguageKey)
<tr>
<td>{{ $LanguageKey->id}}</td>
<td>{{ $LanguageKey->key}}</td>
<td>{{ $subtitleKey->subtitle}}</td>
<td
<a class="btn btn-sm btn-success text-light" data-toggle="modal" data-target="#editSubtitle" data-id="{{$subtitleKey->id}}" data-language_key="{{$LanguageKey->key}}" data-subtitle="{{$subtitleKey->subtitle}}">Edit</a>
</td>
</tr>
@endforeach
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
@endsection
viii) welcome.blade.php
resources/views/welcome.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header bg-success mb-2">Example Subtitle</div>
<div class="card-body p-2">
<p> {{ trans('language.Hellow, how are you?')}} </p>
<p> {{ __('language.Enter Father\'s name')}} </p>
<p> @lang('language.Forget your password?') </p
{{-- Space allow on laravel --}}
</div>
</div> <br>
<a class="btn btn-info" href="{{url('next')}}">Next page</a>
</div>
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<div class="card-header bg-success mb-2">All Subtitle</div>
<table class="table table-bordered">
<thead class="text-center">
<tr>
<th>Id</th>
<th>Key</th>
<th>Language </th>
<th>Subtitle</th>
</tr>
</thead>
<tbody>
@php
$subtitles = App\Subtitle::all();
@endphp
@foreach($subtitles as $subtitle)
<tr>
<td>{{ $subtitle->id}}</td>
<td>{{ $subtitle->languageKey->key}}</td>
<td>{{ $subtitle->language->name}}</td>
<td>{{ $subtitle->subtitle}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
</details>
<details>
<summary>8) Routes</summary>
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('lang/{locale}/{langId}', 'HomeController@lang');
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::post('addLanguage', 'HomeController@addLanguage')->name('addLanguage');
Route::post('addKey', 'HomeController@addKey')->name('addKey');
Route::get('subtitle', 'HomeController@subtitle')->name('subtitle');
Route::post('addSubtitle', 'HomeController@addSubtitle')->name('addSubtitle');
Route::post('editSubtitle', 'HomeController@editSubtitle')->name('editSubtitle');
</details>
<details>
<summary>9) public folder structure</summary>
public
assets
css/
js/
flag/
->English.png
->French.png
->Japan.png
->Spanish.
N:B: Image will be upload by system when language will be added.
Image size should be 80*50 for better position.[Not mandatory]
Link:
Laravel Dynamic Localization
1) https://appdividend.com/2019/04/01/how-to-create-multilingual-website-using-laravel-localization/
2) See only this time (3:30 - 3:40)
-> For create database table
-> Call Table from database and convert array[]
https://www.youtube.com/watch?v=cmmJ-upACd8&ab_channel=ProgrammerSayed
</details>
| 8eee66a6a614271d8b1fc501606c3f3d6051a74a | [
"Markdown",
"SQL",
"PHP"
] | 7 | SQL | aslamcsebd/localization | fa3f6e7edd5e0ded9af3c1c599c6ab513234a5aa | 0b9974887eb889f694127d18d6d6eff16acb8a67 |
refs/heads/master | <file_sep>package wangyijieholding.agendaapplication.calendar;
import java.io.Serializable;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.ArrayList;
import wangyijieholding.agendaapplication.events.EData;
import wangyijieholding.agendaapplication.events.EDataWithTime;
public class CalendarDay implements Serializable {
int arrayPosition;
private Calendar date;
ArrayList<EDataWithTime> events;
public CalendarDay (){
date = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
}
public CalendarDay (int setYear, int setMonth, int setDate){
date = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
date.set(setYear, setMonth, setDate);
date.set(Calendar.AM_PM,Calendar.AM);
date.set(Calendar.HOUR,0);
date.set(Calendar.MINUTE,0);
date.set(Calendar.SECOND,0);
date.set(Calendar.MILLISECOND,0);
events = new ArrayList<EDataWithTime>(25);
}
public CalendarDay (int setYear, int setMonth, int setDate, int position){
arrayPosition = position;
date = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
date.set(setYear, setMonth, setDate);
date.set(Calendar.AM_PM,Calendar.AM);
date.set(Calendar.HOUR,0);
date.set(Calendar.MINUTE,0);
date.set(Calendar.SECOND,0);
date.set(Calendar.MILLISECOND,0);
events = new ArrayList<EDataWithTime>(25);
}
public void addEvent(EDataWithTime event){
events.add(event);
}
public boolean removeEvent(EData event){
return events.remove(event);
}
public Calendar getDate(){
return date;
}
public String getDateString (String[] month, String[] dayOfWeek){
String result;
result = dayOfWeek[date.get(Calendar.DAY_OF_WEEK) - 1] + ", " + month[date.get(Calendar.MONTH)] + " " + Integer.toString(date.get(Calendar.DAY_OF_MONTH)) + ", " + Integer.toString(date.get(Calendar.YEAR));
return result;
}
}<file_sep>package wangyijieholding.agendaapplication.calendar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import wangyijieholding.agendaapplication.R;
import wangyijieholding.agendaapplication.database.CalendarDatabaseHelper;
import wangyijieholding.agendaapplication.events.EDataWithTime;
/*
* This is the activity for displaying the events in detail and handling user inputs
* A custom adapter class, DayDetailListItemAdapter is used for the items in this view
* This activity displays the list_item_with_edit_button custom view
* The adapter class is responsible for maintaining the list and populating it
* The adapter is also responsible for calling the edit event method when the edit button is pressed
*/
public class DayDetailActivity extends AppCompatActivity implements EditModeChoiceDialogFragment.EditModeDialogListener {
CalendarDay displayedDate;
DayDetailListItemAdapter eventAdapter;
Snackbar editModeHelp;
boolean editMode;
int onHoldEvent;
CalendarDatabaseHelper dbHelper;
final String CALENDARDAY_EXTRA = "CalendarDayExtra";
static final String EVENT_DIALOG_TAG = "edit_mode_choice";
static final int EDIT_EVENT_REQUEST = 701;
static final String REFRESH_DATE_EXTRA = "REFRESH_DATE";
static final int NEW_EVENT_REQUEST = 702;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createEvent(view);
}
});
Intent intent = this.getIntent();
displayedDate = (CalendarDay)intent.getSerializableExtra("selectedDate");
Resources res = getResources();
String[] monthNameArray = res.getStringArray(R.array.month_full_name_array);
String[] weekdayNameArray = res.getStringArray(R.array.weekday_name_array);
String title = displayedDate.getDateString(monthNameArray,weekdayNameArray);
//Change the title to today's date
getSupportActionBar().setTitle(title);
//Set edit mode to false initially
editMode = false;
//Populate the list view based on the event title and desc pairings
updateEventList();
dbHelper = new CalendarDatabaseHelper(this);
}
@Override
protected void onResume(){
super.onResume();
updateEventList();
}
public void updateEventList(){
ListView eventList = (ListView) findViewById(R.id.event_day_list);
eventAdapter = new DayDetailListItemAdapter(this,displayedDate.events);
eventList.setAdapter(eventAdapter);
}
public void showDialog(){
EditModeChoiceDialogFragment dialog = new EditModeChoiceDialogFragment();
dialog.show(getSupportFragmentManager(), EVENT_DIALOG_TAG);
}
public void createEvent (View view){
Intent intent = new Intent(this,NewEventActivity.class);
intent.putExtra(CALENDARDAY_EXTRA,displayedDate);
startActivityForResult(intent,NEW_EVENT_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check if the request is edit event request
if (requestCode == EDIT_EVENT_REQUEST){
if (resultCode == RESULT_OK){
Intent refresh = new Intent();
//DisplayedDate ArrayPosition is the position for the date on the array, so the code
//jumps back to the DayDetailActivity as if nothing happened
refresh.putExtra(REFRESH_DATE_EXTRA,displayedDate.arrayPosition);
setResult(Activity.RESULT_OK,refresh);
finish();
}
} if (requestCode == NEW_EVENT_REQUEST){
if(resultCode == RESULT_OK){
Intent refresh = new Intent();
//DisplayedDate ArrayPosition is the position for the date on the array, so the code
//jumps back to the DayDetailActivity as if nothing happened
refresh.putExtra(REFRESH_DATE_EXTRA,displayedDate.arrayPosition);
setResult(Activity.RESULT_OK,refresh);
finish();
}
}
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
Intent editIntent = new Intent(this,EditEventActivity.class);
editIntent.putExtra("EditEventData",displayedDate.events.get(onHoldEvent));
startActivityForResult(editIntent,EDIT_EVENT_REQUEST);
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
EDataWithTime deleteEvent = displayedDate.events.get(onHoldEvent);
deleteEvent.removeFromCalendar();
dbHelper.deleteByID((deleteEvent.getSQLId()));
updateEventList();
}
@Override
public void onDialogNeutralClick(DialogFragment dialog){
System.out.println("Cancel");
}
}
<file_sep>package wangyijieholding.agendaapplication.calendar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import wangyijieholding.agendaapplication.R;
/**
* Created by wangyijie6646 on 8/29/16.
*/
public class EditModeChoiceDialogFragment extends DialogFragment {
EditModeDialogListener cListener;
int SelectedEventIndex;
//Interface for activities using this dialog
public interface EditModeDialogListener{
void onDialogPositiveClick(DialogFragment dialog);
void onDialogNegativeClick(DialogFragment dialog);
void onDialogNeutralClick(DialogFragment dialog);
}
@Override
public void onAttach(Context context){
super.onAttach(context);
//Verify if the listener is implemented by the context
try {
cListener = (EditModeDialogListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString() + "must implement EditModeDialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle saveInstanceState){
//Builder is used to construct this dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_edit_mode).setPositiveButton(R.string.dialog_edit,new DialogInterface.OnClickListener(){
public void onClick (DialogInterface dialog,int id){
cListener.onDialogPositiveClick(EditModeChoiceDialogFragment.this);
}
}).setNegativeButton(R.string.dialog_delete,new DialogInterface.OnClickListener(){
public void onClick (DialogInterface dialog,int id){
cListener.onDialogNegativeClick(EditModeChoiceDialogFragment.this);
}
}).setNeutralButton(R.string.dialog_cancel,new DialogInterface.OnClickListener(){
public void onClick (DialogInterface dialog,int id){
cListener.onDialogNeutralClick(EditModeChoiceDialogFragment.this);
}
});
return builder.create();
}
}<file_sep>package wangyijieholding.agendaapplication.calendar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import java.util.Calendar;
import wangyijieholding.agendaapplication.R;
/**
* Created by wangyijie6646 on 8/6/16.
*/
public class DateView extends View {
CalendarDay displayedDate;
int currentMonth;
Paint CurrentPaint;
Paint EventPaint;
Paint BGPaint;
String dateOfMonth;
boolean sameMonth;
String wordEvent;
String wordEvents;
//Constructors
public DateView(Context context) {
super(context);
init();
}
public DateView (Context c, AttributeSet attrs){
super(c,attrs);
init();
}
//If the date belongs to a month other than the current month, mark sameMonth as false, which
//will cause the date to be set as a different colour;
@SuppressWarnings("WrongConstant")
public DateView (Context c, CalendarDay d, int cm) {
super(c);
displayedDate = d;
init();
currentMonth = cm;
if (currentMonth != displayedDate.getDate().get(Calendar.MONTH) ){
sameMonth = false;
}
}
//Initialise the graphic of the view
public void init (){
CurrentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
CurrentPaint.setColor(Color.BLACK);
CurrentPaint.setTextSize(26);
EventPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
EventPaint.setColor(Color.BLACK);
EventPaint.setTextSize(20);
CurrentPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
BGPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
BGPaint.setColor(Color.GRAY);
this.setWillNotDraw(false);
Integer dayOfMonthInt = displayedDate.getDate().get(Calendar.DAY_OF_MONTH);
dateOfMonth = dayOfMonthInt.toString();
sameMonth = true;
wordEvent = this.getContext().getString(R.string.word_event);
wordEvents = this.getContext().getString(R.string.word_events);
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh){
super.onSizeChanged(w,h,oldw,oldh);
}
//Draw the date when called
@Override
protected void onDraw (Canvas canvas){
super.onDraw(canvas);
if (!sameMonth){
canvas.drawPaint(BGPaint);
}
canvas.drawText(dateOfMonth,10,30,CurrentPaint);
/*if (displayedDate.events.size() > 2) {
for (int i = 0; i < 2; i++) {
canvas.drawText(displayedDate.events.get(i).EventTitle, 10, 100 + 50 * i, CurrentPaint);
}
canvas.drawText("...", 10, 50 * 4, CurrentPaint);
} else {
for (int i = 0; i < displayedDate.events.size(); i++) {
canvas.drawText(displayedDate.events.get(i).EventTitle, 10, 100 + 50 * i, CurrentPaint);
}
}
*/
if (displayedDate.events.size() > 1){
canvas.drawText(Integer.toString(displayedDate.events.size()) + " " + wordEvents ,10, 60, EventPaint);
} else if (displayedDate.events.size() > 0){
canvas.drawText(Integer.toString(displayedDate.events.size()) + " " + wordEvents, 10, 60, EventPaint);
}
}
}
<file_sep>package wangyijieholding.agendaapplication.calendar;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TimePicker;
import wangyijieholding.agendaapplication.R;
/**
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!! Currently Unused !!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
/**
*Simple fragment for the simple task of selecting time from a timepicker
*/
public class SelectTimeFragment extends Fragment {
private static final String ARG_ORIGINAL_TIME_HOUR = "original_time_hour";
private static final String ARG_ORIGINAL_TIME_MINUTE = "original_time_minute";
// TODO: Rename and change types of parameters
private int displayedHour;
private int displayedMinute;
private TimeFragmentListener mListener;
public SelectTimeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SelectTimeFragment.
*/
// TODO: Rename and change types and number of parameters
public static SelectTimeFragment newInstance(int param1, int param2) {
SelectTimeFragment fragment = new SelectTimeFragment();
Bundle args = new Bundle();
args.putInt(ARG_ORIGINAL_TIME_HOUR, param1);
args.putInt(ARG_ORIGINAL_TIME_MINUTE, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
displayedHour = getArguments().getInt(ARG_ORIGINAL_TIME_HOUR);
displayedMinute = getArguments().getInt(ARG_ORIGINAL_TIME_MINUTE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View fragmentView = inflater.inflate(R.layout.fragment_select_time, container, false);
TimePicker timePicker = (TimePicker) fragmentView.findViewById(R.id.select_time_fragment_time_picker);
//Change the time on the time picker to match that of the given parameters
//Check the api version as setHour method and setMinute method are only available after Marshmallow
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
timePicker.setHour(displayedHour);
timePicker.setMinute(displayedMinute);
} else {
timePicker.setCurrentHour(displayedHour);
timePicker.setCurrentMinute(displayedMinute);
}
return fragmentView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof TimeFragmentListener) {
mListener = (TimeFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement TimeFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
//Make activities implement this interface
public interface TimeFragmentListener {
void onFragmentInteraction(Uri uri);
}
}
| f860bc68dbd858f68468413c65eda04fadeda60a | [
"Java"
] | 5 | Java | PieRate/HiCalendar | 45dd8a1a0671b787f3ece30d3264abfdbff87246 | fde9f596debf51a1ba9676d26ebb81ed2552bd13 |
refs/heads/master | <repo_name>chamook/SuccincT<file_sep>/SuccincT/PartialApplications/TailActionApplications.cs
using System;
namespace SuccincT.PartialApplications
{
/// <summary>
/// Action{T1, T2} equivalant delegate for when T2 is an optional parameter
/// </summary>
[Obsolete("The ActionWithOptionalParameter delegates are depreciated. The Action<> and Lambda<> methods should be " +
"used instead. As of v2.1 of Succinc<T>, they will be removed completely.")]
public delegate void ActionWithOptionalParameter<in T1, in T2>(T1 a, T2 b = default(T2));
/// <summary>
/// Action{T1, T2, T3} equivalant delegate for when T3 is an optional parameter
/// </summary>
[Obsolete("The ActionWithOptionalParameter delegates are depreciated. The Action<> and Lambda<> methods should be " +
"used instead. As of v2.1 of Succinc<T>, they will be removed completely.")]
public delegate void ActionWithOptionalParameter<in T1, in T2, in T3>(T1 a, T2 b, T3 c = default(T3));
/// <summary>
/// Action{T1, T2, T3, T4} equivalant delegate for when T4 is an optional parameter
/// </summary>
[Obsolete("The ActionWithOptionalParameter delegates are depreciated. The Action<> and Lambda<> methods should be " +
"used instead. As of v2.1 of Succinc<T>, they will be removed completely.")]
public delegate void ActionWithOptionalParameter<in T1, in T2, in T3, in T4>(T1 a, T2 b, T3 c, T4 d = default(T4));
/// <summary>
/// Action{T1, T2, T3, T4, T5} equivalant delegate for when T5 is an optional parameter
/// </summary>
[Obsolete("The ActionWithOptionalParameter delegates are depreciated. The Action<> and Lambda<> methods should be " +
"used instead. As of v2.1 of Succinc<T>, they will be removed completely.")]
public delegate void ActionWithOptionalParameter<in T1, in T2, in T3, in T4, in T5>
(T1 a, T2 b, T3 c, T4 d, T5 e = default(T5));
/// <summary>
/// Extension methods for tail-applying C# actions (void methods)
/// </summary>
// ReSharper disable UnusedMember.Global - Obsolete
public static class TailActionApplications
{
/// <summary>
/// Partially applies a(p1,p2), via a.TailApply(v2), into a'(p1)
/// </summary>
[Obsolete("The TailApply methods have moved to the SuccincT.Functional namespace. As of v2.1 of Succinc<T>, " +
"they will be deleted from the SuccincT.PartialApplications namespace completely.")]
public static Action<T1> TailApply<T1, T2>(this Action<T1, T2> actionToApply, T2 p2) =>
p1 => actionToApply(p1, p2);
/// <summary>
/// Partially applies a(p1,p2,p3), via a.TailApply(v3), into a'(p1,p2)
/// </summary>
[Obsolete("The TailApply methods have moved to the SuccincT.Functional namespace. As of v2.1 of Succinc<T>, " +
"they will be deleted from the SuccincT.PartialApplications namespace completely.")]
public static Action<T1, T2> TailApply<T1, T2, T3>(this Action<T1, T2, T3> actionToApply, T3 p3) =>
(p1, p2) => actionToApply(p1, p2, p3);
/// <summary>
/// Partially applies a(p1,p2,p3,p4), via a.TailApply(v4), into a'(p1,p2,p3)
/// </summary>
[Obsolete("The TailApply methods have moved to the SuccincT.Functional namespace. As of v2.1 of Succinc<T>, " +
"they will be deleted from the SuccincT.PartialApplications namespace completely.")]
public static Action<T1, T2, T3> TailApply<T1, T2, T3, T4>(this Action<T1, T2, T3, T4> actionToApply, T4 p4) =>
(p1, p2, p3) => actionToApply(p1, p2, p3, p4);
/// <summary>
/// Partially applies a(p1,p2,p3,p4), via a.TailApply(v4), into a'(p1,p2,p3)
/// </summary>
[Obsolete("The TailApply methods have moved to the SuccincT.Functional namespace. As of v2.1 of Succinc<T>, " +
"they will be deleted from the SuccincT.PartialApplications namespace completely.")]
public static Action<T1, T2, T3, T4>
TailApply<T1, T2, T3, T4, T5>(this Action<T1, T2, T3, T4, T5> actionToApply, T5 p5) =>
(p1, p2, p3, p4) => actionToApply(p1, p2, p3, p4, p5);
/// <summary>
/// Partially applies a(p1,p2=default), via a.TailApply(v2), into a'(p1)
/// </summary>
[Obsolete("The TailApply methods that take an ActionWithOptionalParameter delegate are depreciated. The " +
"Action<> and Lambda<> methods should be used instead to convert the method with an optional tail" +
"parameter into an Action<> delegate and the TailApply methods for thosed used. As of v2.1 of " +
"Succinc<T>, these methods will be removed completely.")]
public static Action<T1> TailApply<T1, T2>(this ActionWithOptionalParameter<T1, T2> actionToApply, T2 p2) =>
p1 => actionToApply(p1, p2);
/// <summary>
/// Partially applies a(p1,p2,p3=default), via a.TailApply(v3), into a'(p1,p2)
/// </summary>
[Obsolete("The TailApply methods that take an ActionWithOptionalParameter delegate are depreciated. The " +
"Action<> and Lambda<> methods should be used instead to convert the method with an optional tail" +
"parameter into an Action<> delegate and the TailApply methods for thosed used. As of v2.1 of " +
"Succinc<T>, these methods will be removed completely.")]
public static Action<T1, T2>
TailApply<T1, T2, T3>(this ActionWithOptionalParameter<T1, T2, T3> actionToApply, T3 p3) =>
(p1, p2) => actionToApply(p1, p2, p3);
/// <summary>
/// Partially applies a(p1,p2,p3,p4=default), via a.TailApply(v4), into a'(p1,p2,p3)
/// </summary>
[Obsolete("The TailApply methods that take an ActionWithOptionalParameter delegate are depreciated. The " +
"Action<> and Lambda<> methods should be used instead to convert the method with an optional tail" +
"parameter into an Action<> delegate and the TailApply methods for thosed used. As of v2.1 of " +
"Succinc<T>, these methods will be removed completely.")]
public static Action<T1, T2, T3>
TailApply<T1, T2, T3, T4>(this ActionWithOptionalParameter<T1, T2, T3, T4> actionToApply, T4 p4) =>
(p1, p2, p3) => actionToApply(p1, p2, p3, p4);
/// <summary>
/// Partially applies a(p1,p2,p3,p4,p5=default), via a.TailApply(v5), into a'(p1,p2,p3,p4)
/// </summary>
[Obsolete("The TailApply methods that take an ActionWithOptionalParameter delegate are depreciated. The " +
"Action<> and Lambda<> methods should be used instead to convert the method with an optional tail" +
"parameter into an Action<> delegate and the TailApply methods for thosed used. As of v2.1 of " +
"Succinc<T>, these methods will be removed completely.")]
public static Action<T1, T2, T3, T4>
TailApply<T1, T2, T3, T4, T5>(this ActionWithOptionalParameter<T1, T2, T3, T4, T5> actionToApply, T5 p5) =>
(p1, p2, p3, p4) => actionToApply(p1, p2, p3, p4, p5);
}
}<file_sep>/SuccincT/Parsers/BooleanParser.cs
using System;
using SuccincT.Options;
namespace SuccincT.Parsers
{
/// <summary>
/// Defines a string extension method for parsing boolean
/// values in an elegant fashion (avoiding exception throwing and out parameters).
/// </summary>
public static class BooleanParser
{
/// <summary>
/// Parses the current string for a true/false value and returns an Option{bool} of the result.
/// </summary>
public static Option<bool> TryParseBoolean(this string source) => ReflectionBasedParser.Parse<bool>(source);
/// <summary>
/// Parses the current string for a true/false value and returns an Option{bool} of the result.
/// </summary>
[Obsolete("ParseBoolean has been replaced with TryParseBoolean and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<bool> ParseBoolean(this string source) => ReflectionBasedParser.Parse<bool>(source);
}
}<file_sep>/SuccincT/PatternMatchers/MatchFunctionSelectorData.cs
using System;
using System.Collections.Generic;
namespace SuccincT.PatternMatchers
{
internal sealed class MatchFunctionSelectorData<T, TR>
{
public MatchFunctionSelectorData(Func<T, IList<T>, bool> withTestFunc,
Func<T, bool> whereTestFunc,
IList<T> withList,
Func<T, TR> actionFunc)
{
WithTestFunc = withTestFunc;
WhereTestFunc = whereTestFunc;
WithList = withList;
ActionFunc = actionFunc;
}
internal Func<T, IList<T>, bool> WithTestFunc { get; }
internal IList<T> WithList { get; }
internal Func<T, bool> WhereTestFunc { get; }
internal Func<T, TR> ActionFunc { get; }
}
}<file_sep>/SuccincT/PatternMatchers/MatchFunctionSelector{T,TR}.cs
using System;
using System.Collections.Generic;
using SuccincT.Options;
namespace SuccincT.PatternMatchers
{
internal sealed class MatchFunctionSelector<T, TResult>
{
private readonly Func<T, TResult> _defaultFunction;
private readonly List<MatchFunctionSelectorData<T, TResult>> _testsAndFunctions =
new List<MatchFunctionSelectorData<T, TResult>>();
public MatchFunctionSelector(Func<T, TResult> defaultFunction)
{
_defaultFunction = defaultFunction;
}
public void AddTestAndAction(Func<T, IList<T>, bool> withFunc,
IList<T> withData,
Func<T, bool> whereFunc,
Func<T, TResult> action)
{
_testsAndFunctions.Add(new MatchFunctionSelectorData<T, TResult>(withFunc, whereFunc, withData, action));
}
public TResult DetermineResultUsingDefaultIfRequired(T value)
{
foreach (var data in _testsAndFunctions)
{
if (InvokeCorrectTestMethod(data, value))
{
return data.ActionFunc(value);
}
}
return _defaultFunction(value);
}
public Option<TResult> DetermineResult(T value)
{
foreach (var data in _testsAndFunctions)
{
if (InvokeCorrectTestMethod(data, value))
{
return Option<TResult>.Some(data.ActionFunc(value));
}
}
return Option<TResult>.None();
}
private static bool InvokeCorrectTestMethod(MatchFunctionSelectorData<T, TResult> data, T value) =>
data.WithTestFunc?.Invoke(value, data.WithList) ?? data.WhereTestFunc(value);
}
}<file_sep>/SuccincT/Parsers/IntParsers.cs
using System;
using SuccincT.Options;
namespace SuccincT.Parsers
{
/// <summary>
/// Defines a set of string extension methods for parsing byte, short, int and long
/// values in an elegant fashion (avoiding exception throwing and out parameters).
/// </summary>
[CLSCompliant(false)]
public static class IntParsers
{
/// <summary>
/// Parses the current string for an 8 bit signed integer and returns an Option{sbyte} with None or the value.
/// </summary>
public static Option<sbyte> TryParseSignedByte(this string source) => ReflectionBasedParser.Parse<sbyte>(source);
/// <summary>
/// Parses the current string for an 8 bit unsigned integer and returns an Option{byte} with None or the value.
/// </summary>
public static Option<byte> TryParseUnsignedByte(this string source) => ReflectionBasedParser.Parse<byte>(source);
/// <summary>
/// Parses the current string for a 16 bit signed integer and returns an Option{short} with None or the value.
/// </summary>
public static Option<short> TryParseShort(this string source) => ReflectionBasedParser.Parse<short>(source);
/// <summary>
/// Parses the current string for a 16 bit unsigned integer and returns an Option{ushort} with None or the value.
/// </summary>
public static Option<ushort> TryParseUnsignedShort(this string source) =>
ReflectionBasedParser.Parse<ushort>(source);
/// <summary>
/// Parses the current string for a 32 bit signed integer and returns an Option{int} with None or the value.
/// </summary>
public static Option<int> TryParseInt(this string source) => ReflectionBasedParser.Parse<int>(source);
/// <summary>
/// Parses the current string for a 32 bit unsigned integer and returns an Option{uint} with None or the value.
/// </summary>
public static Option<uint> TryParseUnsignedInt(this string source) => ReflectionBasedParser.Parse<uint>(source);
/// <summary>
/// Parses the current string for a 64 bit signed integer and returns an Option{long} with None or the value.
/// </summary>
public static Option<long> TryParseLong(this string source) => ReflectionBasedParser.Parse<long>(source);
/// <summary>
/// Parses the current string for a 64 bit unsigned integer and returns an Option{ulong} with None or the value.
/// </summary>
public static Option<ulong> TryParseUnsignedLong(this string source) => ReflectionBasedParser.Parse<ulong>(source);
/// <summary>
/// Parses the current string for an 8 bit signed integer and returns an Option{sbyte} with None or the value.
/// </summary>
[Obsolete("ParseSignedByte has been replaced with TryParseSignedByte and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<sbyte> ParseSignedByte(this string source) => ReflectionBasedParser.Parse<sbyte>(source);
/// <summary>
/// Parses the current string for an 8 bit unsigned integer and returns an Option{byte} with None or the value.
/// </summary>
[Obsolete("ParseUnsignedByte has been replaced with TryParseUnsignedByte and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<byte> ParseUnsignedByte(this string source) => ReflectionBasedParser.Parse<byte>(source);
/// <summary>
/// Parses the current string for a 16 bit signed integer and returns an Option{short} with None or the value.
/// </summary>
[Obsolete("ParseShort has been replaced with TryParseShort and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<short> ParseShort(this string source) => ReflectionBasedParser.Parse<short>(source);
/// <summary>
/// Parses the current string for a 16 bit unsigned integer and returns an Option{ushort} with None or the value.
/// </summary>
[Obsolete("ParseUnsignedShort has been replaced with TryParseUnsignedShort and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<ushort> ParseUnsignedShort(this string source) =>
ReflectionBasedParser.Parse<ushort>(source);
/// <summary>
/// Parses the current string for a 32 bit signed integer and returns an Option{int} with None or the value.
/// </summary>
// ReSharper disable once UnusedMember.Global - Obsolete
[Obsolete("ParseInt has been replaced with TryParseInt and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<int> ParseInt(this string source) => ReflectionBasedParser.Parse<int>(source);
/// <summary>
/// Parses the current string for a 32 bit unsigned integer and returns an Option{uint} with None or the value.
/// </summary>
// ReSharper disable once UnusedMember.Global - Obsolete
[Obsolete("ParseUnsignedInt has been replaced with TryParseUnsignedInt and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<uint> ParseUnsignedInt(this string source) => ReflectionBasedParser.Parse<uint>(source);
/// <summary>
/// Parses the current string for a 64 bit signed integer and returns an Option{long} with None or the value.
/// </summary>
// ReSharper disable once UnusedMember.Global - Obsolete
[Obsolete("ParseLong has been replaced with TryParseLong and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<long> ParseLong(this string source) => ReflectionBasedParser.Parse<long>(source);
/// <summary>
/// Parses the current string for a 64 bit unsigned integer and returns an Option{ulong} with None or the value.
/// </summary>
// ReSharper disable once UnusedMember.Global - Obsolete
[Obsolete("ParseUnsignedLong has been replaced with TryParseUnsignedLong and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<ulong> ParseUnsignedLong(this string source) => ReflectionBasedParser.Parse<ulong>(source);
}
}<file_sep>/SuccincT/Parsers/FloatParsers.cs
using System;
using SuccincT.Options;
namespace SuccincT.Parsers
{
/// <summary>
/// Defines a set of string extension methods for parsing float, double and decimal
/// values in an elegant fashion (avoiding exception throwing and out parameters).
/// </summary>
public static class FloatParsers
{
/// <summary>
/// Parses the current string for a 32 bit float value and returns an Option{float} with None or the value.
/// </summary>
public static Option<float> TryParseFloat(this string source) => ReflectionBasedParser.Parse<float>(source);
/// <summary>
/// Parses the current string for a 64 bit float value and returns an Option{double} with None or the value.
/// </summary>
public static Option<double> TryParseDouble(this string source) => ReflectionBasedParser.Parse<double>(source);
/// <summary>
/// Parses the current string for a 128 bit float value and returns an Option{decimal} with None or the value.
/// </summary>
public static Option<decimal> TryParseDecimal(this string source) => ReflectionBasedParser.Parse<decimal>(source);
/// <summary>
/// Parses the current string for a 32 bit float value and returns an Option{float} with None or the value.
/// </summary>
[Obsolete("ParseFloat has been replaced with TryParseFloat and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<float> ParseFloat(this string source) => ReflectionBasedParser.Parse<float>(source);
/// <summary>
/// Parses the current string for a 64 bit float value and returns an Option{double} with None or the value.
/// </summary>
[Obsolete("ParseDouble has been replaced with TryParseDouble and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<double> ParseDouble(this string source) => ReflectionBasedParser.Parse<double>(source);
/// <summary>
/// Parses the current string for a 128 bit float value and returns an Option{decimal} with None or the value.
/// </summary>
[Obsolete("ParseDecimal has been replaced with TryParseDecimal and will be removed in v2.1.")]
// ReSharper disable once UnusedMember.Global - Obsolete
public static Option<decimal> ParseDecimal(this string source) => ReflectionBasedParser.Parse<decimal>(source);
}
}<file_sep>/SuccincTTests/SuccincT/Options/OptionEqualityTests.cs
using NUnit.Framework;
using SuccincT.Options;
using static NUnit.Framework.Assert;
namespace SuccincTTests.SuccincT.Options
{
[TestFixture]
public class OptionEqualityTests
{
[Test]
public void SameSomeValue_AreEqualAndHaveSameHashCode()
{
var a = Option<string>.Some("1234");
var b = Option<string>.Some("1234");
IsTrue(a.Equals(b));
IsTrue(a == b);
AreEqual(a.GetHashCode(), b.GetHashCode());
}
[Test]
public void TwoNones_AreEqualAndHaveSameHashCode()
{
var a = Option<string>.None();
var b = Option<string>.None();
IsTrue(a.Equals(b));
IsTrue(a == b);
AreEqual(a.GetHashCode(), b.GetHashCode());
}
[Test]
public void SomeValueAndNone_AreNotEqual()
{
var a = Option<string>.Some("1234");
var b = Option<string>.None();
IsFalse(a.Equals(b));
IsTrue(a != b);
}
[Test]
public void DifferentSomeValues_AreNotEqualAndHaveDifferentHashCodes()
{
var a = Option<string>.Some("1234");
var b = Option<string>.Some("12345");
IsFalse(a.Equals(b));
IsTrue(a != b);
AreNotEqual(a.GetHashCode(), b.GetHashCode());
}
[Test]
public void ComparingSomeValueWithNull_ResultsInNotEqual()
{
var a = Option<string>.Some("1234");
IsFalse(a.Equals(null));
IsTrue(a != null);
IsTrue(null != a);
}
[Test]
public void ComparingNoneWithNull_ResultsInNotEqual()
{
var a = Option<string>.None();
IsFalse(a.Equals(null));
IsTrue(a != null);
IsTrue(null != a);
}
}
}<file_sep>/README.md
## Succinc\<T\> ##
#### Discriminated unions, pattern matching and partial applications for C# ####
[](https://ci.appveyor.com/project/DavidArno/succinct) [](http://www.nuget.org/packages/SuccincT)
----------
### Introduction ###
Succinc\<T\> is a small .NET framework that started out as a means of providing an elegant solution to the problem of functions that need return a success state and value, or a failure state. Initially, it consisted of a few `Parse` methods that returned an `ISuccess<T>` result. Then I started learning F#...
Now Succinc\<T\> has grown into a library that provides discriminated unions, pattern matching and partial applications for C#, in addition to providing a set of value parsers that do away with the need for `out` parameters and exceptions, and instead return return an `Option<T>`.
### Current Release ###
The current release of Succinc\<T\> is 2.0.0, which is [available as a nuget package](https://www.nuget.org/packages/SuccincT/).
Please be warned that this release [includes a number of breaking changes. Please consult the documentation before installing](https://github.com/DavidArno/SuccincT/issues/6).
This release includes:
* A completely rewritten implementation of pattern matching (keeping the same semantics, so this shouldn't break and existing uses),
* A new `Unit` type and associated methods for converting `Action<T..>` delegates to `Func<T...,Unit>` ones,
* New `Lambda`, `Transform`, `Func` and `Action` methods to simplify the declaration and typing of lambdas.
* A new `Maybe` type, which is a `struct` version of `Option`. This type is largely interchangable with `Option` and is provided for those that (a) prefer the semantics associated with "maybe" versus "option" and (b) those that prefer the idea of such a type being a `struct` (and those not able to be `null`.
### Features ###
#### Discriminated Unions ####
Succinc\<T\> provides a set of union types ([`Union<T1, T2>`](UnionT1T2), [`Union<T1, T2, T3>`](UnionT1T2T3) and [`Union<T1, T2, T3, T4>`](UnionT1T2T3T4)) where an instance will hold exactly one value of one of the specified types. In addition, it provides the likes of [`Option<T>`](Option_T_) and [`Maybe<T>`](Maybe_T_) that can have the value `Some<T>` or [`None`](None).
Succinc\<T\> uses [`Option<T>`](Option_T_) to provide replacements for the .NET basic types' `TryParse()` methods and `Enum.Parse()`. In all cases, these are extension methods to `string` and they return `Some<T>` on a successful parse and [`None`](None) when the string is not a valid value for that type. No more `out` parameters! See the [Option Parsers guide](OptionParsers) for more details.
Further Succinc\<T\> uses [`Option<T>`](Option_T_) to [provide replacements for the XxxxOrDefault LINQ extension methods on `IEnumerable<T>`](IEnumerableExtensions). In all cases, these new extension methods, eg `TryFirst<T>()` return an option with a value if a match occurred, or `None` if not.
#### Pattern Matching ####
Succinc\<T\> can pattern match values, tuples, unions etc in a way similar to F#'s pattern matching features. It uses a fluent (method chaining) syntax to achieve this. Some examples of its abilities:
```csharp
public static void PrintColorName(Color color)
{
color.Match()
.With(Color.Red).Do(x => Console.WriteLine("Red"))
.With(Color.Green).Do(x => Console.WriteLine("Green"))
.With(Color.Blue).Do(x => Console.WriteLine("Blue"))
.Exec();
}
public static string SinglePositiveOddDigitReporter(Option<int> data)
{
return data.Match<string>()
.Some().Of(0).Do(x => "0 isn't positive or negative")
.Some().Where(x => x == 1 || x == 3 || x == 5 || x == 7 || x == 9).Do(x => x.ToString())
.Some().Where(x => x > 9).Do(x => string.Format("{0} isn't 1 digit", x))
.Some().Where(x => x < 0).Do(i => string.Format("{0} isn't positive", i))
.Some().Do(x => string.Format("{0} isn't odd", x))
.None().Do(() => string.Format("There was no value"))
.Result();
}
```
See the [Succinc\<T\> pattern matching guide](PatternMatching) for more details.
#### Partial Applications ####
Succinc\<T\> supports partial function applications. A parameter can be supplied to a multi-parameter method and a new function will be returned that takes the remaining parameters. For example:
```csharp
var times = Lambda<double>((p1, p2) => p1 * p2);
var times8 = times.Apply(8);
var result = times8(9); // <- result == 72
```
See the [Succinc\<T\> partial applications guide](PartialFunctionApplications) for more details.
#### "Implicitly" Typed Lambdas ####
C# doesn't support implicitly typed lambdas, meaning it's not possible to declare something like:
```csharp
var times = (p1, p2) => p1 * p2;
```
Normally, `times` would have to explicitly typed:
```csharp
Func<double, double, double> times = (p1, p2) => p1 * p2;
```
Succinc\<T\> offers an alternative approach, taking advantage of the fact that `var` can be used if the result of a method is assigned to the variable. Using the `Func`, `Action`, `Transform` and `Lambda` set of methods, the above can be expressed more simply as:
```csharp
var times = Lambda<double>((p1, p2) => p1 * p2);
```
For functions, the `Lambda` methods can be used when the parameters and return type all have the same value, as above. This means the type parameter need only be specified once. `Transform` can be used when all the parameters are of one type and the return value, another. The `Func` methods are used when the parameters and/or return type are of different values. For actions, `Lambda` can also be used when only one type is involved and the `Action` methods do a similar job to the `Func` methods.
This is explained in detail in the [Succinc\<T\> typed lambdas guide](TypedLambdas).
#### `Action`/`Func` conversions ####
The `ToUnitFunc` methods supplied by Succinc\<T\> can be used to cast an `Action` lambdas or method (from 0 to 4 parameters) to a `Func` delegate that returns [`unit`](Unit), allowing `void` methods to be treated as functions and thus eg used in ternary oprators. In addition, Succinc\<T\> provides an `Ignore` method that can be used to explicitly ignore the result of any expression, effectively turning that expression into a `void`
These methods are explained in detail in the [Succinc\<T\> `Action`/`Func` conversions guide](ActionFuncConversions).
| c66e480315931ecada24ac36716f6b7dc9d3311e | [
"Markdown",
"C#"
] | 8 | C# | chamook/SuccincT | b06dfb409805afa6bd6a2d5073a8189fae5a0d11 | fb8223cfb19b2122cf85fa77b886590a388139b9 |
refs/heads/master | <file_sep>UPDATE playlists
SET description = $1
WHERE playlist_id = $2;<file_sep>import axios from 'axios';
/****** INITIAL STATE ******/
const initialState = {
songs: [],
playlists: [],
editedPlaylist: {},
isLoading: false,
error: '',
accessToken: '',
refreshToken: '',
country: '',
email: '',
username: ''
}
/****** ACTION TYPES ******/
const GET_ACCESS_TOKEN = 'GET_ACCESS_TOKEN';
const GET_REFRESH_TOKEN = 'GET_REFRESH_TOKEN';
const STORE_COUNTRY = 'STORE_COUNTRY';
const STORE_EMAIL = 'STORE_EMAIL';
const STORE_USERNAME = 'STORE_USERNAME';
const GET_SONGS = 'GET_SONGS';
const ADD_SONG = 'ADD_SONG';
const REMOVE_SONG = 'REMOVE_SONG';
const GET_PLAYLISTS = 'GET_PLAYLISTS';
const CREATE_PLAYLIST = 'CREATE_PLAYLIST';
const DELETE_PLAYLIST = 'DELETE_PLAYLIST';
const EDIT_PLAYLIST = 'EDIT_PLAYLIST';
/****** ACTION CREATORS ******/
// retrieves access token and stores it in reducer
export function getAccessToken(accessToken) {
return {
type: GET_ACCESS_TOKEN,
payload: accessToken
}
}
// retrieves refresh token and stores it in reducer
export function getRefreshToken(refreshToken) {
return {
type: GET_REFRESH_TOKEN,
payload: refreshToken
}
}
// stores country associated with user's spotify account in reducer
export function storeCountry(country) {
return {
type: STORE_COUNTRY,
payload: country
}
}
// stores user's email in reducer
export function storeEmail(email) {
return {
type: STORE_EMAIL,
payload: email
}
}
// stores user's username in reducer
export function storeUsername(username) {
return {
type: STORE_USERNAME,
payload: username
}
}
// gets list of songs from server
export function getSongs(id) {
return {
type: GET_SONGS,
payload: axios.get(`/api/songs/${ id }`)
};
}
// adds a song to a playlist in database
export function addSong(obj) {
alert('Song added to playlist!');
return {
type: ADD_SONG,
payload: axios.post('/api/songs', obj)
}
}
// removes a song's association to a playist in database
export function removeSong(id) {
alert('Song removed from playlist!');
return {
type: REMOVE_SONG,
payload: axios.delete(`/api/songs/${ id }`)
}
}
// gets list of playlists from server
export function getPlaylists(username) {
return {
type: GET_PLAYLISTS,
payload: axios.get(`/api/playlists/${ username }`)
};
}
// adds a new playlist to server/database
export function createPlaylist(obj) {
return {
type: CREATE_PLAYLIST,
payload: axios.post('/api/playlists', obj)
}
}
// deletes a playlist entry within the server/database
export function deletePlaylist(id) {
return {
type: DELETE_PLAYLIST,
payload: axios.delete(`/api/playlists/${ id }`)
}
}
// edits a current playlist's description
export function editPlaylist(id, obj) {
return {
type: EDIT_PLAYLIST,
payload: axios.put(`/api/playlists/${ id }`, obj)
}
}
/****** REDUCER ******/
export default function songReducer(state = initialState, action) {
switch(action.type) {
// GET ACCESS TOKEN
case 'GET_ACCESS_TOKEN':
return {
...state,
accessToken: action.payload
};
// GET REFRESH TOKEN
case 'GET_REFRESH_TOKEN':
return {
...state,
refreshToken: action.payload
};
// GET USER'S COUNTRY
case 'STORE_COUNTRY':
return {
...state,
country: action.payload
};
// GET USER'S EMAIL
case 'STORE_EMAIL':
return {
...state,
email: action.payload
};
// GET USER'S USERNAME
case 'STORE_USERNAME':
return {
...state,
username: action.payload
};
// GET SONGS
case 'GET_SONGS_PENDING':
return {
...state,
isLoading: true
};
case 'GET_SONGS_FULFILLED':
return {
...state,
isLoading: false,
songs: action.payload.data
};
case 'GET_SONGS_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// ADD SONG
case 'ADD_SONG_PENDING':
return {
...state,
isLoading: true
};
case 'ADD_SONG_FULFILLED':
return {
...state,
isLoading: false,
songs: [...state.songs, action.payload.data]
};
case 'ADD_SONG_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// REMOVE SONG
case 'REMOVE_SONG_PENDING':
return {
...state,
isLoading: true
};
case 'REMOVE_SONG_FULFILLED':
return {
...state,
isLoading: false,
songs: [...state.songs]
};
case 'REMOVE_SONG_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// GET PLAYLISTS
case 'GET_PLAYLISTS_PENDING':
return {
...state,
isLoading: true,
};
case 'GET_PLAYLISTS_FULFILLED':
return {
...state,
isLoading: false,
playlists: action.payload.data
};
case 'GET_PLAYLISTS_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// CREATE/ADD PLAYLIST
case 'CREATE_PLAYLIST_PENDING':
return {
...state,
isLoading: true
};
case 'CREATE_PLAYLIST_FULFILLED':
return {
...state,
isLoading: false,
playlists: [...state.playlists, action.payload.data]
};
case 'CREATE_PLAYLIST_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// DELETE PLAYLIST
case 'DELETE_PLAYLIST_PENDING':
return {
...state,
isLoading: true
};
case 'DELETE_PLAYLIST_FULFILLED':
return {
...state,
isLoading: false,
playlists: [...state.playlists]
};
case 'DELETE_PLAYLIST_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// EDIT PLAYLIST
case 'EDIT_PLAYLIST_PENDING':
return {
...state,
isLoading: true
};
case 'EDIT_PLAYLIST_FULFILLED':
return {
...state,
isLoading: false,
editedPlaylist: action.payload.data[0]
};
case 'EDIT_PLAYLIST_REJECTED':
return {
...state,
isLoading: true,
error: action.payload
};
// DEFAULT
default:
return state;
}
}<file_sep>SELECT * FROM playlists
WHERE username = $1;<file_sep>import React, { Component } from 'react';
import './Home.css';
/*
* This component acts more like a welcome page
* Users are prompted with a 'LOGIN WITH SPOTIFY' button
* Login button routes users to Spotify to login
* User will be returned back to web app upon logging in with Spotify
*/
class Home extends Component {
render() {
return (
<div>
<div className="home-container">
<h1 className="welcome">Welcome</h1>
<h3>Get started by logging in with Spotify below!</h3>
<button className="login-button"><a id="link" href={process.env.REACT_APP_LOGIN}>LOGIN WITH SPOTIFY</a></button>
</div>
</div>
);
}
}
export default Home;<file_sep>import React, { Component } from 'react';
import { HashRouter, Link } from 'react-router-dom';
import { Provider } from 'react-redux';
import { Collapse } from 'react-bootstrap';
import routes from './routes';
import store from './redux/store';
import Navbar from './components/Navbar/Navbar';
import menu from './round_menu_white_24dp.png';
import headset from './headset_white_24dp.png';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
open: false
}
}
render() {
return (
<Provider store={ store }>
<HashRouter>
<div className="App">
<div className="menu-bar">
<Link className="inside-bar" id="link" to="/search"> {/*****************************************************/}
<div className="logo"> {/* */}
<h3>Sound<img src={ headset } />Skwerl</h3> {/* Logo - Navigates back to search page when clicked */}
</div> {/* */}
</Link> {/*****************************************************/}
{/* Menu button - opens drop-down menu when clicked */}
<img className="inside-bar" id="menu-button" src={ menu } alt="menu" onClick={ () => this.setState({
open: !this.state.open
}) } />
</div>
{/* Brings in a collapsable drop-down menu */}
<Collapse in={ this.state.open }>
<div>
<Navbar />
</div>
</Collapse>
{ routes }
</div>
</HashRouter>
</Provider>
);
}
}
export default App;
<file_sep>import { createStore, applyMiddleware } from 'redux';
import promiseMiddleWare from 'redux-promise-middleware';
import songReducer from './ducks/songReducer';
/*
* This component sets up the store
* This is where the reducer will live
* The store is responsible for containing important data that will be used by multiple components
*/
const middleware = applyMiddleware(promiseMiddleWare());
const store = createStore(songReducer, middleware);
export default store;<file_sep>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './components/Home/Home';
import Search from './components/Search/Search';
import User from './components/User/User';
import Searched from './components/Searched/Searched';
import Playlists from './components/Playlists/Playlists';
import Playlist from './components/Playlists/Playlist/Playlist';
import Playground from './components/Playground/Playground';
/*
* This component sets up all of the routes within this web application
* Each route will take the user to that specified path
*/
export default (
<Switch>
<Route exact path="/" component={ Home } />
<Route path="/search" component={ Search } />
{/* <Route path="/searched" component={ Searched } /> */}
<Route exact path="/playlists" component={ Playlists } />
<Route path="/playlists/playlist/:id" component={ Playlist } />
<Route path="/user" component={ User } />
<Route path="/playground" component={ Playground } />
</Switch>
);<file_sep>INSERT INTO songs (spotify_uri, song_name, artist, album, album_art, playlist_id)
VALUES ($1, $2, $3, $4, $5, $6);<file_sep># Sound Skwerl
Welcome to Sound Skwerl, the latest, but not so greatest playlist web app! The purpose of this project was to create a simple, full-stack web application that allows users to search for songs and add them to custom-made playlists.
## Before Getting Started
This application is currently designed for mobile view ONLY. In order to view this web application properly, kindly open up the developer tools tab and change the responsive view to "Pixel 2".
Updates to make the web application fully responsive for ALL views are coming soon. Please be patient and I deeply apologize for any inconveniences this may bring.
## Getting Started
Before you start using this web app, you'll have to have a valid Spotify account nad login with it. The spotify account can be the free version, or the premium version.
## Application Walkthrough
### Searching And Adding Songs
Once logged in, you should be taken to the search page where you can search for any song within Spotify's music library. Go ahead and sample as many songs as you like!
When you have found a song you would like to add to a playlist, simply select which playlist you would like to add it to by clicking the dropdown button under each song. Clicking this button should show all of your current playlists and will update when playlists are created/deleted. Once you have selected the playlist you would like to add the song to, click the "ADD" button to add it.
### Playlist Management
Before you can add a song to a playlist, you'll have to create a playlist. Click the menu button in the top right of the screen and click "PLAYLISTS". All of your playlists should appear on this page. To create a playlist, simply input a name and a description for your new playlist and click the "ADD PLAYLIST" button to create it.
At this point, you should see your playlist's name, description, and two buttons at the bottom of your playlist card. The "EDIT" button allows you to edit the description of the playlist, while the "DELETE" button deletes the playlist entirely.
### Selecting An Individual Playlist
When a specific playlist is clicked, you'll be shown all of the songs that you have added to it. Here you can listen to these specific songs and even remove songs from the playlist by clicking the red "X" button to the right of the song.
### User Page
The user page contains your Spotify account info, such as your username, profile avatar, email, and the country associated with your Spotify account.<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
/* Customizable Material-UI Button */
const styles = {
default: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
borderRadius: 3,
border: 0,
color: 'white',
height: 48,
padding: '0 30px',
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
fontSize: '14px'
},
button: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
borderRadius: 3,
border: 0,
color: 'white',
height: 35,
padding: '0 10px',
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
fontSize: '12px'
},
blue: {
background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
borderRadius: 3,
border: 0,
color: 'white',
height: 35,
padding: '0 10px',
boxShadow: '0 3px 5px 2px rgba(33, 203, 243, .3)',
fontSize: '12px'
}
};
function MatButton(props) {
return (
<Button
className={ props.classes[props.classNames] }
type="submit"
size={ props.size }
onClick={ props.clickButton }
>
{ props.children ? props.children : 'idk' }
</Button>
);
}
MatButton.propTypes = {
children: PropTypes.node,
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(MatButton);<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getSongs } from '../../redux/ducks/songReducer';
class Searched extends Component {
constructor(props) {
super(props)
console.log('props: ', this.props);
}
componentDidMount = () => {
const { getSongs } = this.props
getSongs();
}
render() {
const { songs } = this.props;
console.log('this.props.songs: ', songs);
const displaySongs = songs.map((song, i) => {
return (
<div key={ i } >
<p>{ song.song_name }</p>
</div>
);
});
return (
<div>
<h1>Searched</h1>
{ displaySongs }
</div>
);
}
}
const mapStateToProps = state => {
return state;
};
export default connect(mapStateToProps, { getSongs })(Searched);<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './Navbar.css';
/* Contains links to all routes within the applicaiton */
class Navbar extends Component {
render() {
return (
<div className="nav">
<Link to="/"><button className="nav-button">HOME</button></Link>
<Link to="/search"><button className="nav-button">SEARCH</button></Link>
<Link to="/playlists"><button className="nav-button">PLAYLISTS</button></Link>
<Link to="/user"><button className="nav-button">USER</button></Link>
<Link to="/playground"><button className="nav-button">PLAYGROUND</button></Link>
</div>
);
}
}
export default Navbar;<file_sep>DELETE FROM songs
WHERE song_id = $1;<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
// Methods brought in from redux store
import {
getPlaylists,
createPlaylist
} from '../../redux/ducks/songReducer';
import MatButton from '../minor_components/MatButton/MatButton';
import MatInput from '../minor_components/MatInput/MatInput';
import PlayCard from './PlayCard/PlayCard';
import './Playlists.css';
/*
* Playlists component is responsible for displaying all of the user's current playlists
* New playlists can be created with a desired description
* Each playlist will be presented as a card
*/
class Playlists extends Component {
constructor(props) {
super(props);
// Local state - stores name and description for new playlist to be created
this.state = {
name: '',
description: ''
}
}
// Retrieves playlists associated with the user
componentDidMount() {
// Pulled from redux
const { getPlaylists, username } = this.props;
getPlaylists(username);
}
onChangeHandler = (event) => {
// sets the the appropriate state depending on which input is being utilized
this.setState({
[event.target.name]: event.target.value
});
}
// Creates a playlist
onSubmitHandler = (event) => {
event.preventDefault();
alert('Playlist created!');
const { name, description } = this.state;
const { createPlaylist, getPlaylists, username } = this.props;
if (name && description) {
createPlaylist({
playlist_name: name,
description: description,
username: username
})
.then(() => getPlaylists(username))
.then(this.setState({
name: '',
description: ''
}));
}
}
render() {
// Pulled from redux
const { playlists } = this.props;
// maps through playlists array and renders the playlist name, description, an edit button, and delete button for every object in the array
const displayPlaylists = playlists.map((playlist, i) => {
return (
<PlayCard
uniqueKey={ i }
playlist={ playlist }
i={ i }
/>
);
});
return (
<div>
<h1 className="clear">Playlists</h1>
<br />
<form onSubmit={ this.onSubmitHandler }>
<MatInput
name="name"
value={ this.state.name }
placeholder="Playlist Name"
onChange={ this.onChangeHandler }
/>
<MatInput
name="description"
value={ this.state.description }
placeholder="Description"
onChange={ this.onChangeHandler }
/>
<br />
<MatButton classNames="button">Add Playlist</MatButton>
</form>
<br />
<br />
<div className="list">
{ displayPlaylists }
</div>
</div>
);
}
}
// Brings in redux state through props
const mapStateToProps = (state) => {
return state
}
// Connects Playlists component to redux store
export default connect(mapStateToProps, {
getPlaylists,
createPlaylist
})(Playlists);<file_sep>INSERT INTO users (username, email, country)
VALUES ($1, $2, $3);<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button } from 'react-bootstrap';
import { getSongs, removeSong } from '../../../redux/ducks/songReducer';
import './Playlist.css';
import close from '../../../baseline-close-24px.svg';
/*
* Playlist component is responsible for displaying all songs saved to a specific playlist
* Each playlist ONLY displays the songs associated to it
* Users can remove songs from each playlist
*/
class Playlist extends Component {
constructor(props) {
super(props);
}
// Retrieves songs saved in redux
componentDidMount = () => {
// Pulled from redux
const { getSongs } = this.props;
// Retrieves songs based on the playlist id passed through params when a playlist is clicked on
getSongs(this.props.match.params.id);
}
render() {
// Pulled form redux
const { songs, removeSong, getSongs } = this.props;
// Base uri used in addition to a song's Spotify uri in order to play it through an embedded player
const baseUri = 'https://open.spotify.com/embed?uri=';
// Displays the playable songs associated with that specific playlist
const displaySongs = songs.map((song, i) => {
return (
<div key={ i } className="playlist-song-card">
<iframe src={ baseUri + song.spotify_uri } width="260" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>
<br />
{/* Removes a song from the playlist */}
<Button bsStyle="danger" onClick={ () => removeSong(song.song_id).then(() => getSongs(this.props.match.params.id)) }><img src={ close } /></Button>
<br />
<br />
</div>
);
});
return (
<div>
<br />
<br />
{/* Displays the playlist name */}
{ songs[0] &&
<h1 className="clear">{ songs[0].playlist_name }</h1> }
<br />
<div className="display-songs">
{ displaySongs }
</div>
</div>
);
}
}
// Brings in redux state through props
const mapStateToProps = state => {
return state;
}
// Connects Playlist component to redux store
export default connect(mapStateToProps, { getSongs, removeSong })(Playlist);<file_sep>SELECT * FROM songs s
JOIN playlists p
ON p.playlist_id = s.playlist_id
WHERE p.playlist_id = $1;<file_sep>/* Playlist_cntrl contains all methods that deal with the playlists within the application */
// Gets list of playlists associated with the user's Spotify username
const getPlaylists = (req, res, next) => {
const { username } = req.params;
const db = req.app.get('db');
db.get_playlists([username])
.then(playlists => res.status(200).send(playlists))
.catch(err => res.status(500).send({ getPlaylistsError: err }));
}
// Creates a playlist entry in database
const createPlaylist = (req, res, next) => {
const { playlist_name, description, username } = req.body;
const db = req.app.get('db');
db.create_playlist([playlist_name, description, username])
.then(playlist => res.status(200).send(playlist))
.catch(err => res.status(500).send({ createPlaylistError: err }));
}
// Deletes a playlist within the database
const deletePlaylist = (req, res, next) => {
const { id } = req.params;
const db = req.app.get('db');
db.delete_playlist(id)
.then(playlist => res.status(200).send(playlist))
.catch(err => res.status(500).send({ deletePlaylistError: err }));
}
// Edits a current playlist's description
const editPlaylistDescription = (req, res, next) => {
const { id } = req.params;
const { description } = req.body;
const db = req.app.get('db');
db.edit_playlist_description([description, id])
.then(playlist => res.status(200).send(playlist))
.catch(err => res.status(500).send({ editPlaylistDescriptionError: err }));
}
module.exports = {
getPlaylists,
createPlaylist,
deletePlaylist,
editPlaylistDescription
}<file_sep>INSERT INTO playlists (playlist_name, description, username)
VALUES ($1, $2, $3);<file_sep>DELETE FROM playlists
WHERE playlist_id = $1;<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import SpotifyWebApi from 'spotify-web-api-js';
import {
Button,
Collapse,
Well,
DropdownButton,
MenuItem
} from 'react-bootstrap';
import MatButton from '../minor_components/MatButton/MatButton';
import MatInput from '../minor_components/MatInput/MatInput';
import './Playground.css';
/*
* Playground component serves no real purpose towards the application
* All testing of new features were originally brought here to test the functionality before being implemented into other components
*/
const spotifyApi = new SpotifyWebApi();
class Playground extends Component {
constructor(props) {
super(props);
this.state = {
nowPlaying: {
name: 'Not Checked',
albumArt: '',
spotifyUri: '',
open: false
}
}
}
getNowPlaying = () => {
spotifyApi.getMyCurrentPlaybackState()
.then((response) => {
// console.log('response: ', response);
this.setState({
nowPlaying: {
name: response.item.name,
albumArt: response.item.album.images[1].url,
spotifyUri: response.item.uri
}
});
});
// .then(console.log(this.state));
}
render() {
const { country, email, username } = this.props;
if (country && email && username) {
console.log('props: ', this.props);
};
let baseUri = 'https://open.spotify.com/embed?uri=';
let embedUri = baseUri + this.state.nowPlaying.spotifyUri;
return (
<div className="text">
<h1 className="clear">Playground</h1>
<div>
<img className="album-art" src={ this.state.nowPlaying.albumArt }/>
</div>
<div>
<h3>Now Playing: { this.state.nowPlaying.name }</h3>
</div>
<div>
<iframe src={ embedUri } width="300" height="80" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>
</div>
<div>
<MatButton
classNames="button"
clickButton={ () => this.getNowPlaying() }>
Check Now Playing
</MatButton>
</div>
<br />
<br />
<MatInput />
<Button onClick={ () => this.setState({ open: !this.state.open }) }>Dropdown</Button>
<Collapse in={this.state.open}>
<div>
<Well className="well ">
Anim pariatur cliche reprehenderit, enim eiusmod high life
accusamus terry richardson ad squid. Nihil anim keffiyeh
helvetica, craft beer labore wes anderson cred nesciunt sapiente
ea proident.
</Well>
</div>
</Collapse>
<br />
<DropdownButton>
<MenuItem>Test</MenuItem>
</DropdownButton>
<br />
<div className="ui action input">
<input type="text" placeholder="Search..." />
<button className="ui icon button">
<i className="search icon"></i>
</button>
</div>
<br />
<div class="ui icon input">
<input type="text" placeholder="Search..." />
<i class="circular search link icon"></i>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
accessToken: state.accessToken,
refreshToken: state.refreshToken,
country: state.country,
email: state.email,
username: state.username
}
}
export default connect(mapStateToProps)(Playground); | cd49298459a5fa6b5d170683dce0b1168564e573 | [
"JavaScript",
"SQL",
"Markdown"
] | 21 | SQL | gv4383/project-playlist | aa4fdbb556f2c0417f88e5dfee6c379f80d403b8 | 67cd47663a806a3831b91a17acf41761aea918ea |
refs/heads/master | <repo_name>trose618/cm_backend<file_sep>/db/migrate/20190205202318_change_level_column_in_lessons.rb
class ChangeLevelColumnInLessons < ActiveRecord::Migration[5.2]
def change
change_column :lessons, :client_level, :float
end
end
<file_sep>/developer-notes.md
# Developer Notes for Coach Me API
### Goal:
To supply a journal that describes updates to the code base, reasons behinds decisions, and explain the architecture of the api.<file_sep>/db/migrate/20190205202026_remove_age_range_column_in_lessons.rb
class RemoveAgeRangeColumnInLessons < ActiveRecord::Migration[5.2]
def change
remove_column :lessons, :age_range
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'lessons/index'
get 'lessons/create'
get 'lessons/update'
get 'lessons/delete'
namespace :api do
namespace :v1 do
resources :conversations, only: [:index, :create]
resources :messages, only: [:create, :index]
resources :users, only: [:index, :create, :update, :destroy]
resources :lessons, only: [:index, :create, :update, :destroy]
get '/coaches', :to => 'users#coaches'
get '/current_user', :to => "auth#show"
post '/login', :to => 'auth#create'
get '/reload', :to => 'users#reload'
get '/coach_lessons', :to => 'lessons#coach_lessons'
get '/user_convos', :to => 'conversations#users_convos'
get '/confirmed_lessons', :to => 'lessons#confirmed_lessons'
mount ActionCable.server => '/cable'
end
end
end
<file_sep>/app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
has_many :lessons
has_many :jobs
attributes :id, :username, :client, :image_url, :bio
end
<file_sep>/db/migrate/20190401190007_change_user_bio_column.rb
class ChangeUserBioColumn < ActiveRecord::Migration[5.2]
def up
change_column_default :users, :bio, "No bio set."
end
def down
end
end
<file_sep>/app/serializers/lesson_serializer.rb
class LessonSerializer < ActiveModel::Serializer
attributes :id, :client_level, :client_name, :lesson_focus, :client_email, :coach_id, :client_id, :lesson_date, :client_age, :accepted, :checked, :coach_name
end<file_sep>/app/models/user.rb
class User < ApplicationRecord
has_many :jobs, class_name: :Lesson, foreign_key: :coach_id, dependent: :delete_all
has_many :lessons, class_name: :Lesson, foreign_key: :client_id, dependent: :delete_all
has_and_belongs_to_many :conversations, dependent: :destroy
has_secure_password
validates :username, presence: true
validates :password, presence: true, unless: :skip_password_validation
validates :username, uniqueness: { case_sensitive: false }
attr_accessor :skip_password_validation
end
<file_sep>/app/controllers/api/v1/messages_controller.rb
class Api::V1::MessagesController < ApplicationController
skip_before_action :authorized
def index
messages = Message.all
render json: messages
end
def create
message = Message.new(message_params)
if message.save
render json: {message: message }
else
render json: {error: "unable to create message", issues: message.erros}
end
end
private
def message_params
params.require(:message).permit(:text, :conversation_id, :user_id)
end
end
<file_sep>/app/serializers/conversation_serializer.rb
class ConversationSerializer < ActiveModel::Serializer
attributes :id, :title, :user_one_id, :user_two_id
has_many :messages
end
<file_sep>/app/jobs/message_broadcast_job.rb
class MessageBroadcastJob < ApplicationJob
queue_as :default
def perform(message)
payload = {
message_id: message.id,
room_id: message.conversation.id,
content: message.text,
sender: message.user_id,
created_at: message.created_at,
participants: [message.conversation.user_one_id, message.conversation.user_two_id]
}
ActionCable.server.broadcast(build_room_id(message.conversation.id), payload)
end
def build_room_id(id)
"ChatRoom-#{id}"
end
end<file_sep>/app/controllers/api/v1/conversations_controller.rb
class Api::V1::ConversationsController < ApplicationController
skip_before_action :authorized, only: [:index, :create]
def index
conversations = Conversation.all
render json: conversations
end
def users_convos
id = decode_token["user_id"]
conversations = Conversation.all.select{|convo| convo.user_one_id == id || convo.user_two_id == id}
render json: conversations
end
def create
@conversation = Conversation.new(conversation_params)
if @conversation.save
render json: {conversation: @conversation}
else
render json: { error: 'Failed to create convo, already exists' }
end
end
private
def conversation_params
params.require(:conversation).permit(:title, :user_one_id, :user_two_id)
end
end
<file_sep>/app/controllers/api/v1/lessons_controller.rb
class Api::V1::LessonsController < ApplicationController
skip_before_action :authorized
before_action :find_lesson, only: [:update, :destroy]
def index
@lessons = Lesson.all
render json: @lessons
end
def coach_lessons
id = decode_token["user_id"]
@lessons = Lesson.all.select{|lesson| lesson.coach_id == id || lesson.client_id == id}
render json: @lessons
#get this route to work!
end
def confirmed_lessons
id = decode_token["user_id"]
@lessons = Lesson.all.select{|lesson| (lesson.coach_id == id || lesson.client_id == id) && lesson.checked==true}
render json: @lessons
end
def create
@lesson = Lesson.create(lesson_params)
if @lesson.valid?
render json: {lesson: @lesson}
else
render json: {error: "Failed to create lesson"}
end
end
def update
if @lesson.valid?
@lesson.update(lesson_params)
render json: {lesson: @lesson}
else
render json: {error: "Failed to update lesson"}
end
end
def destroy
@lesson.destroy
render json: {message: "lesson deleted"}
end
private
def lesson_params
params.require(:lesson).permit(:client_level, :client_name, :lesson_focus, :client_email, :coach_id, :client_id, :lesson_date, :client_age, :accepted, :checked, :coach_name)
end
def find_lesson
@lesson = Lesson.find(params[:id])
end
end
<file_sep>/app/models/message.rb
class Message < ApplicationRecord
belongs_to :conversation
belongs_to :user
after_create_commit { MessageBroadcastJob.perform_later(self) }
# after_commit { MessageBroadcastJob.perform_later(self) } on: [:create]
end
<file_sep>/db/migrate/20190130212023_create_lessons.rb
class CreateLessons < ActiveRecord::Migration[5.2]
def change
create_table :lessons do |t|
t.datetime :startTime
t.datetime :endTime
t.bigint :client_level
t.string :client_name
t.string :age_range
t.string :lesson_focus
t.string :client_email
t.string :location
t.bigint :coach_id, references: :User
t.bigint :client_id, references: :User
t.timestamps
end
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::API
before_action :authorized
def issue_token(payload)
JWT.encode(payload, 'AINTNOTHING')
end
def decode_token
JWT.decode(get_token, 'AINTNOTHING')[0]
end
def get_token
request.authorization
end
def current_user?
if request.authorization
User.find(decode_token["user_id"])
end
end
def logged_in?
!!current_user?
end
def authorized
if !logged_in?
render json: { message: 'Please log in' }, status: :unauthorized unless logged_in?
end
end
end
<file_sep>/app/models/lesson.rb
class Lesson < ApplicationRecord
belongs_to :coach, class_name: :User
belongs_to :client, class_name: :User
end
<file_sep>/db/migrate/20190205201819_change_start_time_column_in_lessons.rb
class ChangeStartTimeColumnInLessons < ActiveRecord::Migration[5.2]
def change
change_column :lessons, :startTime, :time
end
end
<file_sep>/app/controllers/api/v1/users_controller.rb
class Api::V1::UsersController < ApplicationController
skip_before_action :authorized #, only: [:create, :coaches]
def index
@users = User.all
render json: @users
end
def coaches
@users = User.all.select{|user| user.client == false}
render json: @users
end
def create
@user = User.new(user_params)
if @user.save
token = JWT.encode({user_id: @user.id}, 'AINTNOTHING')
render json: {user: @user, jwt: token}
else
render json: { error: @user.errors.full_messages }, status: 422
end
end
def reload
@user = User.find(decode_token["user_id"])
if @user
render json: {user: @user}
else
#byebug
render json: { error: 'Bad Key' }
end
end
def update
@user = User.find(params[:id])
@user.skip_password_validation = true
if @user.valid?
@user.update(update_user_params)
render json: {user: @user}
else
render json: {error: "Failed to update user"}
end
end
def destroy
@user = User.find(params[:id])
User.all.delete(@user)
render json: {message: "account deleted"}
end
private
def user_params
params.require(:user).permit(:username, :client, :password, :image_url, :bio)
end
def update_user_params
params.require(:user).permit(:username, :bio, :image_url)
end
def find_user
@user = User.find(params[:id])
end
end
<file_sep>/db/migrate/20190207232550_set_default_bio.rb
class SetDefaultBio < ActiveRecord::Migration[5.2]
def up
change_column_default :users, :bio, "Quisque purus tellus, eleifend elementum tortor congue, accumsan
vehicula metus. Praesent non sapien ut arcu aliquet varius at ac
nisi. Aliquam ut posuere metus, ac fringilla lectus. Interdum et
malesuada fames ac ante ipsum primis in faucibus. Integer
ullamcorper non lacus maximus viverra. Sed et faucibus orci. In
efficitur ante ac sapien lobortis, posuere tempor orci gravida."
end
def down
end
end
<file_sep>/db/migrate/20190205200715_remove_end_time_form_lesson.rb
class RemoveEndTimeFormLesson < ActiveRecord::Migration[5.2]
def change
remove_column :lessons, :endTime
end
end
<file_sep>/db/migrate/20190207232008_drop_calendar.rb
class DropCalendar < ActiveRecord::Migration[5.2]
def change
remove_column :users, :calendar
end
end
<file_sep>/app/models/conversation.rb
class Conversation < ApplicationRecord
has_many :messages, dependent: :destroy
has_and_belongs_to_many :users
validates :title, uniqueness: { case_sensitive: false }
end
<file_sep>/db/migrate/20190206024606_remove_lesson_date_and_time_columns_from_lessons.rb
class RemoveLessonDateAndTimeColumnsFromLessons < ActiveRecord::Migration[5.2]
def change
remove_column :lessons, :startTime
change_column :lessons, :lesson_date, :datetime
end
end
<file_sep>/db/migrate/20190209202733_add_users_to_conversation.rb
class AddUsersToConversation < ActiveRecord::Migration[5.2]
def change
add_column :conversations, :user_one_id, :bigint
add_column :conversations, :user_two_id, :bigint
end
end
<file_sep>/db/migrate/20190205202131_add_age_column_in_lessons.rb
class AddAgeColumnInLessons < ActiveRecord::Migration[5.2]
def change
add_column :lessons, :client_age, :bigint
end
end
<file_sep>/db/migrate/20190207162441_add_default_img_to_users.rb
class AddDefaultImgToUsers < ActiveRecord::Migration[5.2]
def up
change_column_default :users, :image_url, "https://moonvillageassociation.org/wp-content/uploads/2018/06/default-profile-picture1-744x744.jpg"
end
def down
end
end
<file_sep>/app/controllers/api/v1/auth_controller.rb
class Api::V1::AuthController < ApplicationController
skip_before_action :authorized, only: [:create]
def create
user = User.find_by(username: login_user_params[:username])
if user && user.authenticate(login_user_params[:password])
token = JWT.encode({user_id: user.id}, 'AINTNOTHING')
render json: {user: user, jwt: token}
else
render json: {error: "Invalid username or password"}, status: 400
end
end
def show
if current_user
render json: {user: current_user}
else
render json: {error: "some error"}, status: 422
end
end
private
def login_user_params
params.require(:user).permit(:username, :password)
end
end | 6fb32b52da1a3a7c46a94c6faa91a0bda872b74b | [
"Markdown",
"Ruby"
] | 28 | Ruby | trose618/cm_backend | 099ff38506596389f3bccb77db24ed0d006592d1 | b4832c8a3298371ecec4046d9e269507356d40d9 |
refs/heads/master | <file_sep>package com.example.agrihelper;
import android.location.Location;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
interface UserLocationService {
@GET("locations/v1/cities/search?")
Call<ArrayList<UserLocationResponse>> getUserLocationId(@Query("apikey") String apiKey, @Query("q") String cityName);
}
class UserLocationResponse {
@SerializedName("Key")
public String locationId;
}
public class CurrentUserLocationId {
public static String BaseUrl = "http://dataservice.accuweather.com/";
public static Call<ArrayList<UserLocationResponse>> getLocationId(String cityName) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
UserLocationService service = retrofit.create(UserLocationService.class);
Call<ArrayList<UserLocationResponse>> call = service.getUserLocationId("xETxc89QjxNIzmMmNONisEjsVmHDKjGG",cityName);
return call;
}
}
<file_sep>package com.example.agrihelper;
import android.location.Location;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
interface AccuweatherService {
@GET("currentconditions/v1/{cityId}?")
Call<ArrayList<AccuweatherResponse>> getWeatherData(@Path("cityId") String cityId, @Query("apikey") String apiKey, @Query("details") boolean details);
}
class AccuweatherResponse {
@SerializedName("Temperature")
public Temperature temperature;
@SerializedName("WeatherText")
public String weatherText;
@SerializedName("Wind")
public AccuWind wind;
@SerializedName("RelativeHumidity")
public String humidity;
}
class Temperature {
@SerializedName("Metric")
public Metric metric;
}
class Metric {
@SerializedName("Value")
public float value;
@SerializedName("Unit")
public String unit;
}
class AccuWind {
@SerializedName("Speed")
public Speed speed;
}
class Speed {
@SerializedName("Metric")
public WindMetric windMetric;
}
class WindMetric {
@SerializedName("Value")
public float value;
@SerializedName("Unit")
public String unitType;
}
public class AccuWeather {
public static String BaseUrl = "http://dataservice.accuweather.com/";
public static Call<ArrayList<AccuweatherResponse>> getCurrentWeather(String cityId) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
AccuweatherService service = retrofit.create(AccuweatherService.class);
Call<ArrayList<AccuweatherResponse>> call = service.getWeatherData(cityId,"xETxc89QjxNIzmMmNONisEjsVmHDKjGG",true);
return call;
}
}
<file_sep>from keras.preprocessing import image
from tensorflow import keras
import numpy as np
import flask
from flask import request
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/get_land_type', methods=['POST'])
def home():
print('Request ', request.files)
imagefile = request.files['image']
new_model = keras.models.load_model('area_identification.h5')
size = 64
test_image = image.load_img(imagefile, target_size=(size, size))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
test_image.reshape(size, size, 3)
result = new_model.predict(test_image, batch_size=1)
index = np.argmax(result[0])
print(index, type(index))
labels = ['AnnualCrop', 'Forest', 'Highway', 'Industrial', 'Residential', 'SeaLake']
return labels[int(index)]
app.run()
<file_sep>package com.example.agrihelper.Model;
public class ForecastWeatherData {
private String date;
private float minRainfall;
private float maxRainfall;
private int colorCode;
public ForecastWeatherData() {
}
public ForecastWeatherData(String date, float minRainfall, float maxRainfall, int colorCode) {
this.date = date;
this.minRainfall = minRainfall;
this.maxRainfall = maxRainfall;
this.colorCode = colorCode;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public float getMinRainfall() {
return minRainfall;
}
public void setMinRainfall(float minRainfall) {
this.minRainfall = minRainfall;
}
public float getMaxRainfall() {
return maxRainfall;
}
public void setMaxRainfall(float maxRainfall) {
this.maxRainfall = maxRainfall;
}
public int getColorCode() {
return colorCode;
}
public void setColorCode(int colorCode) {
this.colorCode = colorCode;
}
}
<file_sep>package com.example.agrihelper;
import android.location.Location;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
interface AccuweatherForecastService {
@GET("forecasts/v1/daily/5day/2801585?")
Call<AccuweatherForecastResponse> getWeatherData(@Query("apikey") String apiKey, @Query("details") boolean details);
}
class AccuweatherForecastResponse {
@SerializedName("DailyForecasts")
public ArrayList<Data> data = new ArrayList<>();
}
class Data {
@SerializedName("Date")
public String date;
@SerializedName("Temperature")
public TemperatureData temperature;
}
class TemperatureData {
@SerializedName("Minimum")
public Metric minimum;
@SerializedName("Maximum")
public Metric maximum;
}
public class AccuWeatherForecast {
public static String BaseUrl = "http://dataservice.accuweather.com/";
public static Call<AccuweatherForecastResponse> getForecastData(Location location) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
AccuweatherForecastService service = retrofit.create(AccuweatherForecastService.class);
return service.getWeatherData("xETxc89QjxNIzmMmNONisEjsVmHDKjGG",true);
}
}
<file_sep>package com.example.agrihelper;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.agrihelper.service.UserAdressService;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private TextView currentLocationText, humidityText, windText, temperatureText;
private View view, detailsView;
private ResultReceiver resultReceiver;
private ProgressBar progressBar;
private String UserLocationId;
private Button moreBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initViews();
resultReceiver = new UserAddressReceiver(new Handler());
}
private void initViews() {
currentLocationText = findViewById(R.id.current_location);
humidityText = findViewById(R.id.humidity_text);
temperatureText = findViewById(R.id.temperature_text);
progressBar = findViewById(R.id.progressBar);
view = findViewById(R.id.card_view);
detailsView = findViewById(R.id.details);
moreBtn = findViewById(R.id.moreBtn);
moreBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap bitmap) {
// mapPreview.setImageBitmap(bitmap);
Intent intent = new Intent(MapsActivity.this, DetailsActivity.class);
saveImage(bitmap);
// intent.putExtra("BITMAP", bitmap);
startActivity(intent);
}
});
}
});
}
public void saveImage(Bitmap bitmap) {
String fileName = "myImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng currentLocation = new LatLng(25.0961, 85.3131);
final Marker[] marker = {mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Bihar"))};
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
Location location = new Location("providerNA");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
LatLng latLng1 = new LatLng(location.getLatitude(), location.getLongitude());
marker[0].remove();
marker[0] = mMap.addMarker(new MarkerOptions().position(latLng1));
view.setVisibility(View.VISIBLE);
fetchUserAddress(location);
Toast.makeText(MapsActivity.this,
"Lat: "+String.valueOf(latLng.latitude)+"\n Lon: "+String.valueOf(latLng.longitude), Toast.LENGTH_SHORT).show();
Log.e("LAT LON", String.valueOf(latLng.latitude)+" "+String.valueOf(latLng.longitude));
}
});
}
private void fetchUserAddress(Location location) {
progressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent(this, UserAdressService.class);
intent.putExtra("RECEIVER", resultReceiver);
intent.putExtra("LOCATION_DATA", location);
startService(intent);
}
private class UserAddressReceiver extends ResultReceiver {
public UserAddressReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == 1) {
currentLocationText.setText(resultData.getString("ADDRESS"));
progressBar.setVisibility(View.INVISIBLE);
// getUserLocationId(resultData.getString("ADDRESS"));
Log.e("Location", resultData.getString("ADDRESS") + " ");
} else {
Toast.makeText(MapsActivity.this, "ADDRESS", Toast.LENGTH_SHORT).show();
}
}
private void getUserLocationId(String city) {
Call<ArrayList<UserLocationResponse>> call = CurrentUserLocationId.getLocationId(city);
call.enqueue(new Callback<ArrayList<UserLocationResponse>>() {
@Override
public void onResponse(@NonNull Call<ArrayList<UserLocationResponse>> call, @NonNull Response<ArrayList<UserLocationResponse>> response) {
if (response.code() == 200) {
ArrayList<UserLocationResponse> accuweatherResponse = response.body();
assert accuweatherResponse != null;
if (accuweatherResponse.size() > 0) {
UserLocationId = accuweatherResponse.get(0).locationId;
getWeatherData(UserLocationId);
Log.e("Location Res", accuweatherResponse.get(0).locationId + " ");
}
}
}
@Override
public void onFailure(@NonNull Call<ArrayList<UserLocationResponse>> call, @NonNull Throwable t) {
Log.e("Weather Data error", t.toString());
}
});
}
private void getWeatherData(String CityId) {
Call<ArrayList<AccuweatherResponse>> call = AccuWeather.getCurrentWeather(CityId);
call.enqueue(new Callback<ArrayList<AccuweatherResponse>>() {
@Override
public void onResponse(@NonNull Call<ArrayList<AccuweatherResponse>> call, @NonNull Response<ArrayList<AccuweatherResponse>> response) {
if (response.code() == 200) {
ArrayList<AccuweatherResponse> accuweatherResponse = response.body();
assert accuweatherResponse != null;
setData(accuweatherResponse);
}
}
@Override
public void onFailure(@NonNull Call<ArrayList<AccuweatherResponse>> call, @NonNull Throwable t) {
Log.e("Weather Data error", t.toString());
}
});
}
private void setData(ArrayList<AccuweatherResponse> response) {
temperatureText.setText(String.valueOf(response.get(0).temperature.metric.value)+ " C");
humidityText.setText(String.valueOf(response.get(0).humidity));
detailsView.setVisibility(View.VISIBLE);
}
}
}<file_sep>package com.example.agrihelper;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.agrihelper.Model.ForecastWeatherData;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class ForecastWeatherAdapter extends RecyclerView.Adapter<ForecastWeatherAdapter.ForecastViewHolder> {
private Context context;
private ArrayList<ForecastWeatherData> weatherData;
public ForecastWeatherAdapter(ArrayList<ForecastWeatherData> weatherData, Context context) {
this.weatherData = weatherData;
this.context = context;
}
@NonNull
@Override
public ForecastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_day_item, parent,false);
return new ForecastViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final ForecastViewHolder holder, int position) {
holder.maxTemp.setText(String.valueOf(weatherData.get(position).getMaxRainfall()));
holder.minTemp.setText(String.valueOf(weatherData.get(position).getMinRainfall()));
holder.tempText.setText(String.valueOf(weatherData.get(position).getMaxRainfall()));
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date date = format.parse(weatherData.get(position).getDate());
holder.date.setText(date.toString());
} catch (ParseException e) {
e.printStackTrace();
}
holder.bg.setBackgroundColor(weatherData.get(position).getColorCode());
}
@Override
public int getItemCount() {
return 4;
}
public class ForecastViewHolder extends RecyclerView.ViewHolder
{
TextView maxTemp, minTemp, tempText, date;
View bg;
public ForecastViewHolder(View view) {
super(view);
maxTemp = view.findViewById(R.id.max_temp_text_view);
minTemp = view.findViewById(R.id.min_temp_text_view);
tempText = view.findViewById(R.id.temp_text_view);
date = view.findViewById(R.id.day_name_text_view);
bg = view.findViewById(R.id.card_view);
}
}
}
<file_sep>from six.moves import urllib
import os
import cv2
import numpy as np
from PIL import Image
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
BATCH_SIZE = 32
image_size = 64
train_image_generator = ImageDataGenerator()
test_image_generator = ImageDataGenerator()
base_dir = 'Images'
train_dir = os.path.join(base_dir, 'Train')
validation_dir = os.path.join(base_dir, 'Validation')
train_data = train_image_generator.flow_from_directory(batch_size = BATCH_SIZE,
directory = train_dir,
shuffle = True,
target_size = (image_size, image_size),
class_mode = 'sparse')
validation_data = test_image_generator.flow_from_directory(batch_size = BATCH_SIZE,
directory = validation_dir,
shuffle = False,
target_size = (image_size, image_size),
class_mode = 'sparse')
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(64, 64, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(64, 64, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu', input_shape=(64, 64, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu', input_shape=(64, 64, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(6, activation='softmax')
])
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
EPOCHS = 50
history = model.fit_generator(
train_data,
steps_per_epoch = int(np.ceil(15300/BATCH_SIZE)),
epochs = EPOCHS,
validation_data = validation_data,
validation_steps = int(np.ceil(1700/BATCH_SIZE))
)
print(history)
#Save the Model
model.save('area_identification.h5')
model.save(filepath='saved_model/')
from keras.preprocessing import image
from tensorflow import keras
import numpy as np
new_model = keras.models.load_model('area_identification.h5')
size=64
test_image = image.load_img('test2.png', target_size=(size, size))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
test_image.reshape(size, size, 3)
result = new_model.predict(test_image, batch_size=1)
index_min = np.argmax(result[0])
print(index_min)
#0 - AnnualCrop
#1 - Forest
#2 - Highway
#3 - Industrial
#4 - Residential
#5 - SeaLake
| 7e3747939c505ac707d936fe11aef2c798d850e8 | [
"Java",
"Python"
] | 8 | Java | scientifictemper/NS275_itempirer_agrihelper | 00c7248e70605301380129e870fe55cd0ff18a7f | c141c9db7fd2e554bb26b58f01d2365a5b375021 |
refs/heads/master | <repo_name>xiaozhizhong/ZhiHuDaily<file_sep>/README.md
# ZhiHuDaily
知乎日报测试App,仅供学习使用.可从官方服务器获取文章、评论数据.
注:使用izzyleung获取的知乎Api.
# Feature
获取首页日报及其他主题日报、查看文章内容及评论、本地收藏、文章分享
# Special
Banner自动轮播、夜间主题切换、消息推送、非wifi网络不加载图片
#screenShots
 
 


# Version
1.1
-修复数据加载错误导致的主页FC的bug
-修复某些日报由于服务器数据无body导致的某些内容空白(使用shareUrl载入网页)
-加入文章收藏功能
-UI调整
1.2
-加入非wifi网络不加载图片的开关
-加入消息推送功能(使用信鸽服务)
1.3
-加入应用打开时的图片显示
-加入页面载入时的loading效果
-加入应用程序图标
<file_sep>/settings.gradle
include ':app', ':xinge'
<file_sep>/app/src/main/java/com/xiao/zhihudaily/app/PushHelper.java
package com.xiao.zhihudaily.app;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
/**
* @describe <></>
* Created by xiaozz on 2016/6/1 0001.
*/
public class PushHelper {
public static void registerPush(Context context) {
SharedPreferences manager = PreferenceManager.getDefaultSharedPreferences(context);
boolean isPushEnable = manager.getBoolean("push", true);
if(isPushEnable){
XGPushManager.registerPush(context, new XGIOperateCallback() {
@Override
public void onSuccess(Object data, int flag) {
Log.e("TPush", "注册成功,设备token为:" + data);
}
@Override
public void onFail(Object data, int errCode, String msg) {
Log.e("TPush", "注册失败,错误码:" + errCode + ",错误信息:" + msg);
}
});
}}
public static void unRegisterPush(Context context) {
XGPushManager.unregisterPush(context);
}
}
<file_sep>/app/src/main/java/com/xiao/zhihudaily/entity/NewsList.java
package com.xiao.zhihudaily.entity;
/**
* @describe <></>
* Created by xiaozz on 2016/5/19 0019.
* 实体类
*/
public class NewsList {
//定义Type为两种类型,一种为单文本日期,一种为标题不带图片
private static final int TYPE_DATE = 1;
private static final int TYPE_TITLE_NO_PIC = 2;
private boolean typeUnclickable = false;
private String title;
private String imageURL = null;
private int id;
private int type;
//otherNews用
private String description;
private String backgroundUrl;
private String name;
public void markUnclickable(){
typeUnclickable = true;
}
public boolean isUnclickable(){
return typeUnclickable;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBackgroundUrl() {
return backgroundUrl;
}
public void setBackgroundUrl(String backgroundUrl) {
this.backgroundUrl = backgroundUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//供外部设置Type类型
public void markDate() {
this.type = TYPE_DATE;
}
public void markTitleNoPic() {
this.type = TYPE_TITLE_NO_PIC;
}
//供外部判断Type类型
public boolean isDate() {
return type == TYPE_DATE;
}
public boolean isTitleNoPic() {
return type == TYPE_TITLE_NO_PIC;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
<file_sep>/app/src/main/java/com/xiao/zhihudaily/activity/ShortCommentActivity.java
package com.xiao.zhihudaily.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.xiao.zhihudaily.R;
import com.xiao.zhihudaily.api.DateUtils;
import com.xiao.zhihudaily.api.HttpDownloader;
import com.xiao.zhihudaily.entity.NewsComment;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xiaoz on 2016/5/27.
*/
public class ShortCommentActivity extends BaseActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shortcomment);
initView();
loadData();
}
CommentRecyclerAdapter commentRecyclerAdapter;
ImageView avatar;
TextView name;
TextView like;
TextView comment;
TextView date;
private void initView(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_shortcomment);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
commentRecyclerAdapter = new CommentRecyclerAdapter();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview_shortcomment);
recyclerView.setLayoutManager(new LinearLayoutManager(toolbar.getContext()));
recyclerView.setAdapter(commentRecyclerAdapter);
avatar = (ImageView) findViewById(R.id.avatar_shortcomment);
name = (TextView) findViewById(R.id.name_shortcomment);
like = (TextView) findViewById(R.id.like_num_comment);
comment = (TextView) findViewById(R.id.content_comment);
date = (TextView) findViewById(R.id.time_comment);
}
private void loadData() {
int id = getIntent().getExtras().getInt("id");
//http://news-at.zhihu.com/api/4/story/#{id}/short-comments 替换id
String commentUrl = "http://news-at.zhihu.com/api/4/story/" + id + "/short-comments";
HttpDownloader.sendRequestWithHttpconnection(commentUrl, new HttpDownloader.HttpCallBackListener() {
@Override
public void onFinish(JSONObject jsonObject) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("comments");
for(int i = 0 ; i<jsonArray.length() ; i++){
NewsComment newsComment = new NewsComment();
JSONObject obj = jsonArray.getJSONObject(i);
newsComment.setName(obj.getString("author"));
newsComment.setTxtComment(obj.getString("content"));
newsComment.setLikeNum(obj.getString("likes"));
String date = DateUtils.getTime(Integer.valueOf(obj.getString("time")));
newsComment.setDate(date);
newsComment.setAvantarUrl(obj.getString("avatar"));
commentRecyclerAdapter.addComment(newsComment);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
commentRecyclerAdapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(Exception e) {
Snackbar.make(getWindow().getDecorView(),"sorry啊,加载粗错了哦~~~~",Snackbar.LENGTH_SHORT).show();
}
});
}
public static class CommentRecyclerAdapter extends RecyclerView.Adapter<CommentRecyclerAdapter.CommentViewHolder>{
List<NewsComment> commentList = new ArrayList<NewsComment>();
private void addComment(NewsComment newsComment){
commentList.add(newsComment);
}
LayoutInflater layoutInflater;
@Override
public CommentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(layoutInflater == null)
layoutInflater = LayoutInflater.from(parent.getContext());
CommentViewHolder commentViewHolder = new CommentViewHolder(layoutInflater.inflate(R.layout.item_shortcomment,parent,false));
return commentViewHolder;
}
@Override
public void onBindViewHolder(CommentViewHolder holder, int position) {
holder.UpadteUi(getItem(position));
}
public NewsComment getItem(int position){
if(commentList!=null)
return commentList.get(position);
return null;
}
@Override
public int getItemCount() {
if(commentList != null)
return commentList.size();
return 0;
}
public static class CommentViewHolder extends RecyclerView.ViewHolder{
private ImageView avatarIv;
private TextView nameTv;
private TextView likeTv;
private TextView contentTv;
private TextView dateTv;
public CommentViewHolder(View itemView) {
super(itemView);
avatarIv = (ImageView) itemView.findViewById(R.id.avatar_shortcomment);
nameTv = (TextView) itemView.findViewById(R.id.name_shortcomment);
likeTv = (TextView) itemView.findViewById(R.id.like_num_comment);
contentTv = (TextView) itemView.findViewById(R.id.content_comment);
dateTv = (TextView) itemView.findViewById(R.id.time_comment);
}
private void UpadteUi(NewsComment newsComment){
Glide.with(avatarIv.getContext()).load(newsComment.getAvantarUrl()).into(avatarIv);
nameTv.setText(newsComment.getName());
likeTv.setText(newsComment.getLikeNum());
contentTv.setText(newsComment.getTxtComment());
dateTv.setText(newsComment.getDate());
}
}
}
}
<file_sep>/app/src/main/java/com/xiao/zhihudaily/entity/NewsPush.java
package com.xiao.zhihudaily.entity;
import io.realm.RealmObject;
/**
* @describe <></>
* Created by xiaozz on 2016/6/2 0002.
*/
public class NewsPush extends RealmObject implements INews{
private int articleId;
private String title;
private String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
}
<file_sep>/app/src/main/java/com/xiao/zhihudaily/activity/NotificationActivity.java
package com.xiao.zhihudaily.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.xiao.zhihudaily.MainActivity;
import com.xiao.zhihudaily.R;
import com.xiao.zhihudaily.adapter.INewsAdapter;
import com.xiao.zhihudaily.entity.NewsPush;
import java.util.List;
import io.realm.Realm;
public class NotificationActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
initView();
loadData();
}
DrawerLayout drawer;
private void initView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_noti);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Nothing to show ^6^", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void loadData() {
Realm realm = Realm.getDefaultInstance();
List<NewsPush> list = realm.where(NewsPush.class).findAll();
if (!list.isEmpty()) {
View notificationContent = findViewById(R.id.notification_content);
ViewGroup.LayoutParams layoutParams = notificationContent.getLayoutParams();
ViewGroup parent = (ViewGroup) notificationContent.getParent();
int position = parent.indexOfChild(notificationContent);
parent.removeView(notificationContent);
RecyclerView recycleView = new RecyclerView(this);
parent.addView(recycleView, position, layoutParams);
INewsAdapter adapter = new INewsAdapter();
adapter.setData(list);
recycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recycleView.setAdapter(adapter);
}
}
static final int TYPE_HOME = 0;
static final int TYPE_STAR = 2;
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.home_draw:
openThisActivity(this, TYPE_HOME);
break;
case R.id.star_draw:
openThisActivity(this, TYPE_STAR);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static void openThisActivity(Context context, int type) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("type", type);
context.startActivity(intent);
}
}<file_sep>/app/src/main/java/com/xiao/zhihudaily/activity/LoadingActivity.java
package com.xiao.zhihudaily.activity;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.xiao.zhihudaily.MainActivity;
import com.xiao.zhihudaily.R;
public class LoadingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window. FEATURE_NO_TITLE );//隐藏标题栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
setContentView(R.layout.activity_loading);
ImageView img = (ImageView) findViewById(R.id.loading_img);
TextView txt = (TextView) findViewById(R.id.loading_txt);
String imageUrl = "http://p2.zhimg.com/10/7b/107bb4894b46d75a892da6fa80ef504a.jpg";
String title = "© Fido Dido";
SharedPreferences sp = getSharedPreferences("loadingImg",MODE_PRIVATE);
String todayImg = sp.getString("todayImg",imageUrl);
String todayTitle = sp.getString("todayTitle",title);
Glide.with(this).load(todayImg).into(img);
txt.setText(todayTitle);
AlphaAnimation animation = new AlphaAnimation(0.35f,1);
animation.setDuration(3000);
txt.setAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
animation.start();
}
}
| 79996623f10efca137708f62bdd85b637eb31c0b | [
"Markdown",
"Java",
"Gradle"
] | 8 | Markdown | xiaozhizhong/ZhiHuDaily | 28918026103fdcf6610e8c3e730c0baa31109a49 | 0a37151725967aed5c4a5ad3c92f37d13202e673 |
refs/heads/master | <file_sep>class Admin::TicketsController < ApplicationController
layout 'admin'
before_action :set_ticket, only: [:show]
def index
# @tickets = Ticket.includes(:client).all
@q = Ticket.ransack(params[:q])
@tickets = @q.result.includes(:client, :user, :comments).page(params[:page])
respond_to do |f|
f.js { render 'index.js.erb' }
f.html
end
end
def show; end
def new
@ticket = Ticket.new
end
def create
@ticket = Ticket.create(ticket_params)
if @ticket.save
redirect_to admin_ticket_path(@ticket)
else
render :new
end
end
def edit; end
def update
if @ticket.update(ticket_params)
redirect_to admin_ticket_path(@ticket)
else
render :edit
end
end
def destroy
@ticket.destroy
redirect_to admin_client_path(@ticket.client)
end
private
def ticket_params
params.require(:ticket).permit(:ticket_number, :request_summary, :request_detail, :outcome_summary, :outcome_detail, :due, :resolved, :last_response, :severity, :status, :client_id, :user_id)
end
def set_ticket
@ticket = Ticket.find(params[:id])
end
end
<file_sep>class Client < ApplicationRecord
#Defaults
enum status: [ :active, :inactive, :potential ]
enum service_type: [ :contract, :billable, :pending]
enum payment_method: [ :credit_card, :cash, :check, :undefined]
paginates_per 10
#Relationships
has_many :tickets
has_many :users
has_one :primary_contact, -> { where(is_primary: true) }, class_name: "User"
#Validations
validates :name, presence: true, length: { in: 3..60 }
validates :status, presence: true
validates :service_type, presence: true
validates :payment_method, presence: true
validates :street, presence: true, length: { in: 6.. 40 }
validates :city, presence: true, length: { in: 3..25 }
validates :state, presence: true, length: { is: 2 }
validates :zipcode, presence: true, numericality: true
#Methods
def active_ticket_count
tickets.active.count
end
end
<file_sep>class Admin::ClientsController < ApplicationController
layout 'admin'
def index
@q = Client.ransack(params[:q])
@clients = @q.result.includes(:primary_contact).page(params[:page])
@tickets = Ticket.active.limit(3).load
respond_to do |f|
f.js { render 'index.js.erb' }
f.html
end
end
def show
@client = Client.includes([tickets: :user], :primary_contact).find(params[:id])
end
def new
@client = Client.new
end
def create
@client = Client.new(client_params)
if @client.save
redirect_to @client
else
render :new
end
end
def edit
@client = Client.find(params[:id])
end
def update
@client = Client.find(params[:id])
if @client.udpate(client_params)
redirect_to @client
else
render :edit
end
end
def destroy
@client = Client.find(params[:id])
@client.delete
redirect_to admin_clients_path
end
private
def client_params
params.require(:client).permit(:name, :status, :service_type, :payment_method, :onboard_date, :offboard_date, :recent_request_date, :account_current, :street, :city, :state, :zipcode)
end
end<file_sep>class CreateTickets < ActiveRecord::Migration[5.2]
def change
create_table :tickets do |t|
t.string :ticket_number
t.string :request_summary
t.text :request_detail
t.string :outcome_summary
t.text :outcome_detail
t.datetime :due
t.datetime :date_resolved
t.datetime :last_response
t.integer :severity
t.integer :status
t.references :client, foreign_key: true
t.references :user, foreign_key: true
t.timestamps
end
end
end
<file_sep>require 'test_helper'
class Admin::UserscontrollerControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get admin_userscontroller_index_url
assert_response :success
end
test "should get show" do
get admin_userscontroller_show_url
assert_response :success
end
test "should get new" do
get admin_userscontroller_new_url
assert_response :success
end
test "should get create" do
get admin_userscontroller_create_url
assert_response :success
end
test "should get edit" do
get admin_userscontroller_edit_url
assert_response :success
end
test "should get update" do
get admin_userscontroller_update_url
assert_response :success
end
test "should get destroy" do
get admin_userscontroller_destroy_url
assert_response :success
end
end
<file_sep>class Admin::PagesController < ApplicationController
layout 'admin'
def dashboard
@tickets = Ticket.active
end
end<file_sep>class Ticket < ApplicationRecord
#defaults
enum status: [ :pending_review, :in_progress, :on_hold, :resolved ]
enum severity: [ :P1, :P2, :P3, :P4]
paginates_per 10
#Relationships
belongs_to :client
belongs_to :user
has_many :comments, as: :commentable
#validations
validates :ticket_number, presence: true, allow_nil: true
validates :request_detail, presence: true
validates :request_summary, presence: true
validates :severity, presence: true
validates :status, presence: true
#Scopes
scope :active, -> { where(status: "active") }
#Methods
def assign_ticket_number
self.update_column(:ticket_number, "Ticket-#{self.id}")
end
def days_pending
return "1"
end
#Callbacks
after_save :assign_ticket_number
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'faker'
index = 1
user_index = 1
10.times do
Client.create(name: Faker::Company.name, street: Faker::Address.street_address, city: Faker::Address.city, state: Faker::Address.state_abbr, zipcode: "66215", status: 0, service_type: 0, payment_method: 0, ein: Faker::Company.ein, industry: Faker::Company.industry, logo: Faker::Company.logo)
10.times do
if user_index == 1
User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, primary_phone: Faker::PhoneNumber.phone_number, client: Client.find(index), is_primary: true)
else
User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, primary_phone: Faker::PhoneNumber.phone_number, client: Client.find(index), is_primary: false)
end
end
user_index = 1
index += 1
end
100.times do
client_record = Client.find(rand(1..10))
user_record = client_record.users[rand(1..10)]
Ticket.create(request_summary: Faker::Kpop.iii_groups, request_detail: Faker::Lorem.sentence(30, true), severity: rand(0..3), status: rand(0..2), client: client_record, user: user_record)
end
Ticket.all.each do |t|
t.comments.create(body: Faker::Lorem.sentence(45, true), user: User.find(rand(1..100)), commentable: Ticket.find(rand(1..10)))
end<file_sep>Rails.application.routes.draw do
namespace :admin do
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get '/admin', to: redirect('/admin/dashboard')
namespace :admin do
get 'dashboard', to: 'pages#dashboard'
resources :clients
resources :tickets do
resources :comments, only: [:new, :create, :edit, :update]
end
resources :users
resources :comments, only: [:destroy]
end
resources :clients, only: [:show]
end
<file_sep>class CreateClients < ActiveRecord::Migration[5.2]
def change
create_table :clients do |t|
t.string :name
t.string :industry
t.string :logo
t.string :street
t.string :ein
t.string :city
t.string :state
t.string :zipcode
t.integer :status
t.integer :service_type
t.integer :payment_method
t.datetime :onboard_date
t.datetime :offboard_date
t.datetime :recent_request_date
t.boolean :account_current, default: true
t.references :user, foreign_key: true
t.timestamps
end
end
end
<file_sep>class Comment < ApplicationRecord
default_scope { order(created_at: :desc) }
belongs_to :commentable, polymorphic: true
belongs_to :user
validates :body, presence: true, length: :within [15..500]
after_save :touch_commentable
def touch_commentable
self.commentable.touch(:last_response)
end
end
<file_sep>module Admin::TicketsHelper
def status_styler(status)
case status
when "pending_review"
("<span class='tag is-white is-pulled-right'>Pending Review</span>").html_safe
when "in_progress"
("<span class='tag is-primary is-pulled-right'>In Progress</span>").html_safe
when "on_hold"
("<span class='tag is-danger is-pulled-right'>On hold</span>").html_safe
when "resolved"
("<sspan class='tag is-success is-pulled-right'>Resolved</span>").html_safe
else
("<span class='tag is-light is-pulled-right'>#{status}</span>").html_safe
end
end
end
<file_sep>class Admin::CommentsController < ApplicationController
def create
@content = get_commentable
@comment = @content.comments.create(comment_params)
respond_to do |format|
if(@comment.save)
format.html { redirect_to [:admin, @content] }
format.json
else
format.html { render :new }
format.js { @messages }
end
end
end
def edit
end
def update
end
def destroy
end
private
def comment_params
params.require(:comment).permit(:body, :user_id, :commentable)
end
def get_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
<file_sep>class User < ApplicationRecord
belongs_to :client
has_many :tickets
def full_name
"#{first_name} #{last_name}"
end
end
| 014a535002f9ec84eb5de2e96d6732247b84933c | [
"Ruby"
] | 14 | Ruby | richardmaycode/Bifrost | 7844e9a58b4b56bcfc7bc68db0bd54e133482920 | 4909858c7b53d0b58985d5b58eadd6f16ff844ea |
refs/heads/main | <file_sep>// EmailServer.cpp : This file contains the 'main' function. Program execution begins and ends there.
// Create an EmailServer
/*
Should handle multiple emails per username
Ability to handle multiple user requests at the same time (i.e. 10 users request their emails on a certain date)
Just store emails locally in a map or other data structure.
*/
#include <iostream>
#include <thread>
#include <vector>
#include <string.h>
#include <map>
#include <chrono>
struct Email
{
std::string subject;
std::string body;
std::string recipient;
Email() {};
Email(std::string _s, std::string _b, std::string _r) : subject(_s), body(_s), recipient(_r) {};
};
class EmailServer
{
private:
std::vector<Email> EmailList;
public:
EmailServer() {};
// Helper function to break a string into a list of substrings based on a denotation
std::vector<std::string> BreakIntoSubstrings(std::string s, char mark)
{
std::vector<std::string> result;
for (int i = 0; i < (int)s.size(); i++)
{
if (s[i] == mark)
{
result.push_back(s.substr(0, i));
s.erase(0, i+1);
}
}
result.push_back(s);
return result;
}
// Populate database with emails based on the input - Single thread
void AddEmails(std::vector<std::string> newemails)
{
for (std::string emailstring : newemails)
{
AddEmailSingle(emailstring);
}
}
// Create numThreads to handle emails list for adding to data store
void AddEmailsMultipleThreads(int numThreads, std::vector<std::string> emails)
{
AddEmails(emails);
// TODO: How to launch numThreads to handle X emails in list?
}
int GetEmailListSize()
{
return EmailList.size();
}
void ResetServer()
{
EmailList.clear();
}
// Creates a new thread of execution - readonly - that performs the requires steps in the input arg, each arg is seperated by a comma
/*
input format = "USERNAME,DATE" (i.e. "Chris,2020") -> Should print out all emails with username chris and date = 2020
*/
void FetchEmails(std::vector<std::string> inputargs)
{
}
private:
// Used when attempting to add emails with multiple threads
void AddEmailSingle(std::string data)
{
// Parse emailstring recipient, subject and date
std::vector<std::string> brokenup = BreakIntoSubstrings(data, ',');
if (brokenup.size() == 3)
{
std::string recipient = brokenup[0];
std::string subject = brokenup[1];
int date = (int)stoi(brokenup[2]);
EmailList.push_back(Email(subject, "body", recipient));
}
}
};
int main()
{
std::cout << "EmailServer Started" << std::endl;
// -- Adding work
std::vector<std::string> SampleInput =
{
"Chris,To whom is concerned,2020",
"Chris,Hello email world!,2020",
"Chris,new hire checklist,2021",
"Bill,engineering meeting today,2020",
"Bill,todays checklist,2021",
"Mike,lunch at in-n-out,2020",
"Mike,coffee break at 3pm,2020",
"Mike,Friday bring your pet to work day,2021"
};
EmailServer MyServer = EmailServer();
// Add emails with a single thread
auto starta = std::chrono::high_resolution_clock::now();
MyServer.AddEmails(SampleInput);
auto enda = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(enda - starta);
std::cout << "Single Threaded email add took = " << duration.count() << " ms" <<std::endl;
MyServer.ResetServer(); // clear all added emails
// Add emails with multiple threads
auto startb = std::chrono::high_resolution_clock::now();
int numThreads = 2;
MyServer.AddEmailsMultipleThreads(numThreads, SampleInput);
auto endb = std::chrono::high_resolution_clock::now();
auto durationb = std::chrono::duration_cast<std::chrono::microseconds>(enda - starta);
std::cout << numThreads << " Threaded email add func took = " << durationb.count() << " ms" << std::endl;
// -- Fetching work
std::vector<std::string> SampleFetch =
{
"Chris,2020",
"Bill,2020",
"Mike,2021"
};
MyServer.FetchEmails(SampleFetch);
// Should print out all emails for Chris in 2020, Bill in 2020, and Mike in 2021!
}
<file_sep>#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <map>
using namespace std;
class EmailServer
{
private:
map<string, vector<string>> UserNameToListOfEmails;
bool ServerOn = false;
public:
EmailServer() {
ServerOn = true;
};
// returns a list of all emails for the specified username
vector<string> GetEmailsForUser(string username)
{
vector<string> result;
if (UserNameToListOfEmails.count(username) > 0)
{
result = UserNameToListOfEmails[username];
}
return result;
}
// adds the email and registers it for the username in the mapping
void AddUserEmail(string username, string email)
{
if (UserNameToListOfEmails.count(username) > 0)
{
UserNameToListOfEmails[username].push_back(email);
}
else
{
vector<string> newemaillist;
newemaillist.push_back(email);
UserNameToListOfEmails[username] = newemaillist;
}
}
// returns the number of emails for the specified username
int GetMailCount(string username)
{
if (UserNameToListOfEmails.count(username) > 0)
{
return UserNameToListOfEmails[username].size();
}
return 0;
}
bool IsServerOn()
{
return ServerOn;
}
// Create a thread for each Username to fetch the counts of their respective emails
void FetchMailCountsAndPrint()
{
thread t_chris = thread(&EmailServer::GetMailCount, "Chris");
thread t_bill = thread(&EmailServer::GetMailCount, "Bill");
thread t_mike = thread(&EmailServer::GetMailCount, "Mike");
t_chris.join();
t_bill.join();
t_mike.join();
}
};
int main()
{
cout << "Mail Server Starting..." << endl;
EmailServer* server = new EmailServer();
server->AddUserEmail("Chris", "All Hands Meeting Today at 4PM!");
server->AddUserEmail("Chris", "engineering project 5, needs more work!");
server->AddUserEmail("Bill", "hardware instructions are incomplete.");
server->AddUserEmail("Mike", "threading is so cool, but not as much as robots");
// Create a thread for each Username to fetch the counts of their respective emails
server->FetchMailCountsAndPrint();
return 0;
}<file_sep>#include <iostream>
#include <string.h>
#include <thread>
#include <vector>
using namespace std;
void print(int n, const std::string &str)
{
cout << "Printing interger: " << n << endl;
cout << "Printing string: " << str << endl;
}
int main()
{
cout << "Starting execution..." << endl;
vector<string> s = {
"Example1",
"Example2",
"Threadripper"
};
vector<thread> threads;
for (string val : s)
{
threads.push_back(thread(print, 1, val));
}
for (auto &th : threads)
{
th.join();
}
// Single Thread of execution
thread t1(print, 10, "SingleThreaded"); // initialize thread t1 with print function, then add print arguments at the end
t1.join(); // stop main thread to execute t1 thread, then continue with main thread
return 0;
}<file_sep># Email Server
Built an email server that handles requests concurrently.
| 66e306ea4cc60f2e81502dc15560a03dc708d6b3 | [
"Markdown",
"C++"
] | 4 | C++ | mpro34/Concurrency | 95c5d9c185738b4066f8f0d92fc6b59dd2ac8539 | 028d2b039d6666413840a2d361b49739d70af84b |
refs/heads/master | <repo_name>Dimildizio/inventory_pyg_old<file_sep>/README.md
# inventory_pyg_old
Requires pygame
old inventory menu for an rpg-like game in python.
<file_sep>/inventory_containers.py
#'hi'
import pygame as pg
import sys
from random import randint, choice
WIDTH = 840
HEIGHT = 480
WHITE = (255,255,255)
INV_TILE = 32
all_item_sprites = pg.sprite.LayeredUpdates()
LOGSIZE =13
GAP = 2
def IMAGE1():
return pg.image.load('knife.png').convert_alpha()
def IMAGE2():
return pg.image.load('Health potion.png').convert_alpha()
IMAGE = [IMAGE1, IMAGE2]
class ItemSprite(pg.sprite.DirtySprite):
def __init__(self, pos):
pg.sprite.DirtySprite.__init__(self, all_item_sprites)
self.image = choice(IMAGE)()
class Obj:
def __init__(self, pos, owner):
self.name = 'I am object'
self.sprite = ItemSprite(pos)
self.gold = randint(1,3)
self.weight = 3
self.owner = owner
owner.weight += self.weight
def __repr__(self):
return str(f'repr')
class ObjInv:
def __init__(self, game = False):
self.game = game
self.size = 12
self.weight_limit = 20
self.weight = 1
self.gold = randint(2,6)
self.inside = {}
for x in range(7):
for y in range(self.size//6):
self.inside[(x,y)] = False
for x in range(5):
for y in range(2):
#should be item.weight+self.weight < self.weight_limit
if randint(1,100) > 50 and self.weight < self.weight_limit:
self.inside[(x,y)] = Obj((x,y), self)
self.inv_pic = Inventory(game = game, inv = self)
def take_item_out(self):
a = self.inv_pic.mouse_in_inv()
if a in self.inside:
item, self.inside[a] = self.inside[a], False
if item:
self.weight -= item.weight
return item
def trade_items(self, item):
if self.game.mode == 'trade' and item.owner != self:
if self.gold >= item.gold:
item.owner.gold += item.gold
self.gold -= item.gold
return self.put_item_in(item)
return item
else:
return self.put_item_in(item)
def put_item_in(self, item):
pos = self.inv_pic.mouse_in_inv()
item.owner = self
self.weight += item.weight
if self.inside[pos]:
out = self.inside[pos]
self.weight -= out.weight
self.inside[pos] = item
return out
self.inside[pos] = item
def get_size(self):
a = [x for x in self.inside.values() if x]
return len(a)
class Inventory:
def __init__(self, game = False, pos = (WIDTH//3, HEIGHT//3), inv = False):
self.game = game
self.size = 12
self.width = 6*INV_TILE
self.height = self.size//6*INV_TILE
self.hover_timer = False
self.pos = pos
self.surf = pg.Surface((self.width+1, self.height+(LOGSIZE+GAP)*3))
self.surf.fill((100,100,100))
self.rect = self.surf.get_rect()
for x in range(0, self.width+1, INV_TILE):
pg.draw.line(self.surf, WHITE, (x, 0), (x, self.height))
for y in range(0, self.height+1, INV_TILE):
pg.draw.line(self.surf, WHITE, (0, y), (self.width, y))
self.surface = self.surf.copy()
self.inv_obj = inv
def draw_items_inv(self):
for key, value in self.inv_obj.inside.items():
if value:
xm,ym = key
position = xm*INV_TILE, ym*INV_TILE
#value.sprite.pos = position[0]+self.pos[0], position[1]+self.pos[1]
self.surface.blit(value.sprite.image, position)
self.draw_inv_info()
self.draw_item_info()
def draw_item_info(self):
if self.in_inv_zone():
key = self.mouse_in_inv()
item = self.inv_obj.inside[key]
if item:
ttext = ['name: item', f'weight: {item.weight}', f'price: {item.gold}']
for x in range(len(ttext)):
itext = self.game.log_font.render(ttext[x], False, (40,40,40))
self.surface.blit(itext, (GAP, self.height+GAP+x*LOGSIZE))
if self.hover_timer and self.hover_timer[1] == key:
if (pg.time.get_ticks() - self.hover_timer[0]) / 1000 > 1:
text = self.game.log_font.render(item.name, False, (40,40,40))
tsize = text.get_rect()
h = key[1]*INV_TILE
w = key[0]*INV_TILE + 16 - tsize.w//2
if w + tsize.w > self.width: w = self.width - tsize.w
elif w - 16 < 0: w = 0
layer = pg.Surface((tsize.w+2, tsize.h))
layer.fill((150,150,150))
layer.blit(text, (1,0))
self.surface.blit(layer, (w,h))
return text
else:
self.hover_timer = (pg.time.get_ticks(), key)
else: self.hover_timer = False
def draw_inv_info(self):
ttext = [f'capacity: {self.inv_obj.weight}/{self.inv_obj.weight_limit}',
f'size: {self.inv_obj.get_size()}/{self.size}', f'gold: {self.inv_obj.gold} gp']
for x in range(len(ttext)):
itext = self.game.log_font.render(ttext[x], False, (40,40,40))
t = itext.get_rect()
#print(t.h)
self.surface.blit(itext, (self.width//2,self.height+GAP+x*LOGSIZE))
def mouse_in_inv(self):
mx,my = pg.mouse.get_pos()
ix,iy = self.pos
return (mx-ix)//INV_TILE, (my-iy)//INV_TILE
def in_inv_zone(self):
mx,my = pg.mouse.get_pos()
ix,iy = self.pos
return (ix < mx < ix+self.width and iy < my < iy+self.height)
class Game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
self.clock = pg.time.Clock()
self.inventories = [ObjInv(self)]
self.log_font = pg.font.SysFont('Times New Roman', 13)
self.Rclick = False
self.Lclick = False
self.curinv = False
self.mode = 'inv'
def draw_inv(self, inv):
inv.surface = inv.surf.copy()
hover = inv.draw_items_inv()
self.screen.blit(inv.surface, inv.pos)
def get_inv(self):
i = self.inventories
if len(i) > 1:
i1,i2 = i[0].inv_pic, i[1].inv_pic
i1.pos = WIDTH//1.5-i1.width//2, HEIGHT//2-i1.height
i2.pos = WIDTH//4-i2.width//2, HEIGHT//2 - i2.height
else:
i1 = i[0].inv_pic
i1.pos = WIDTH//2 - i1.width//2, HEIGHT//2 - i1.height
def quit(self):
pg.quit()
sys.exit()
def draw(self):
self.screen.fill((0,0,0))
for x in self.inventories:
self.draw_inv(x.inv_pic)
if self.Rclick:
self.screen.blit(self.Rclick.sprite.image, pg.mouse.get_pos())
pg.display.flip()
def run(self):
# game loop - set self.playing = False to end the game
self.playing = True
while self.playing:
self.dt = self.clock.tick(30) / 1000
self.events()
self.draw()
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_l:
if len(self.inventories) > 1:
self.inventories.pop()
else:
self.inventories.append(ObjInv(self))
self.get_inv()
if event.type == pg.MOUSEBUTTONUP:
if event.button == 1:
self.curinv = self.inventories[1] if len(
self.inventories) > 1 and pg.mouse.get_pos()[0] < WIDTH//2 else self.inventories[0]
if self.curinv.inv_pic.in_inv_zone():
if self.Rclick:
self.Rclick = self.curinv.trade_items(self.Rclick)
else:
self.Rclick = self.curinv.take_item_out()
if event.button == 2:
pass
if event.button == 3:
self.mode = 'trade' if self.mode == 'inv' else 'inv'
#pos = self.curinv.inv_pic.mouse_in_inv()
#a = self.curinv.objinside(pos)
#if a:
#print(a)
if __name__ == '__main__':
g = Game()
while True:
g.run()
| 183542812b1ce58d2c8be2a681dfe2f927afe040 | [
"Markdown",
"Python"
] | 2 | Markdown | Dimildizio/inventory_pyg_old | dfdf3c98ad31a78788e20364780084794888a1af | b43c3d765d0c51fd4a3003bfe00ee378f7b36db4 |
refs/heads/master | <file_sep>import pandas as pd
import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
import shapely
from libpysal.weights import Queen
import pointpats
import pointpats.centrography
from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset
set_default_credentials('ebook-sds')
## The Meuse dataset from R gstat package
class GetMeuse():
def __init__(self):
self.data = gpd.GeoDataFrame(Dataset('meuse').download(decode_geom=True))
self.data['log_zinc'] = np.log(self.data['zinc'])
self.data.crs = {'init': 'epsg:4326'}
self.data = self.data.to_crs({'init': 'epsg:28992'})
self.data_lonlat = self.data.to_crs({'init': 'epsg:4326'})
self.data_grid = gpd.GeoDataFrame(Dataset('meuse_grid').download(decode_geom=True))
self.data_grid.crs = {'init': 'epsg:4326'}
self.data_grid = self.data_grid.to_crs({'init': 'epsg:28992'})
self.data_grid_lonlat = self.data_grid.to_crs({'init': 'epsg:4326'})
def loadpred_krg(self):
self.data_krg = pd.read_csv('/tmp/meuse_krg.csv')
self.data_krg = gpd.GeoDataFrame(self.data_krg, geometry=gpd.points_from_xy(self.data_krg.x, self.data_krg.y))
self.data_krg.crs = {'init': 'epsg:28992'}
self.data_krg_lonlat = self.data_krg.to_crs({'init': 'epsg:4326'})
self.data_grid_krg = pd.read_csv('/tmp/meuse.grid_krg.csv')
self.data_grid_krg = gpd.GeoDataFrame(self.data_grid_krg, geometry=gpd.points_from_xy(self.data_grid_krg.x, self.data_grid_krg.y))
self.data_grid_krg.crs = {'init': 'epsg:28992'}
self.data_grid_krg_lonlat = self.data_grid_krg.to_crs({'init': 'epsg:4326'})
def loadpred_INLAspde(self):
self.data_INLAspde = pd.read_csv('/tmp/meuse_INLAspde.csv')
self.data_INLAspde = gpd.GeoDataFrame(self.data_INLAspde, geometry=gpd.points_from_xy(self.data_INLAspde.x, self.data_INLAspde.y))
self.data_INLAspde.crs = {'init': 'epsg:28992'}
self.data_INLAspde_lonlat = self.data_INLAspde.to_crs({'init': 'epsg:4326'})
self.data_grid_INLAspde = pd.read_csv('/tmp/meuse.grid_INLAspde.csv')
self.data_grid_INLAspde = gpd.GeoDataFrame(self.data_grid_INLAspde, geometry=gpd.points_from_xy(self.data_grid_INLAspde.x, self.data_grid_INLAspde.y))
self.data_grid_INLAspde.crs = {'init': 'epsg:28992'}
self.data_grid_INLAspde_lonlat = self.data_grid_INLAspde.to_crs({'init': 'epsg:4326'})
## The Boston dataset from R spData package
class GetBostonHousing():
def __init__(self):
self.data = gpd.GeoDataFrame(Dataset('boston_housing').download(decode_geom=True))# gpd.read_file(self.filename)
self.data.crs = {'init': 'epsg:4326'}
self.w = Queen.from_dataframe(self.data)
def loadpred(self):
self.data_preds = gpd.read_file('/tmp/boston_housing_predictions.shp')
self.data_preds.crs = {'init': 'epsg:4326'}
## The Crime dataset from UK Police data
class GetCrimeLondon():
def __init__(self, var, var_value):
self.filename = '/tmp/UK_Police_street_crimes_2019_04.csv'
self.data = gpd.GeoDataFrame(Dataset('uk_police_street_crimes_2019_04').download(decode_geom=True))
self.data.crs = {'init': 'epsg:4326'}
self.data = self.data[self.data[var] == var_value]
self.data_lonlat = self.data
self.data_lonlat = Dataset('''
SELECT c.*
FROM uk_police_street_crimes_2019_04 as c
JOIN london_borough_excluding_mhw as g
ON ST_Intersects(c.the_geom, g.the_geom)
''').download(decode_geom=True)
self.data_lonlat = gpd.GeoDataFrame(self.data_lonlat)
self.data = self.data.to_crs({'init': 'epsg:32630'})
def pp(self):
self.pointpattern = pointpats.PointPattern(
pd.concat([self.data.geometry.x,self.data.geometry.y], axis=1)
)
self.pp_lonlat = pointpats.PointPattern(
pd.concat([self.data_lonlat.geometry.x,self.data_lonlat.geometry.y], axis=1)
)<file_sep>import geopandas as gpd
from cartoframes.auth import set_default_credentials
from cartoframes.data import Dataset
set_default_credentials("ebook-sds")
def get_table(tablename):
"""Retrieve tablename as a GeoDataFrame ordered by database id
Returns:
geopandas.GeoDataFrame: GeoDataFrame representation of table
"""
base_query = ("SELECT * FROM {tablename} ORDER BY cartodb_id ASC").format(
tablename=tablename
)
data = gpd.GeoDataFrame(Dataset(base_query).download(decode_geom=True))
data.crs = {"init": "epsg:4326"}
return data
def get_nyc_census_tracts():
"""Retrieve dataset on NYC Census Tracts
Returns:
geopandas.GeoDataFrame: GeoDataFrame representation of table
"""
return get_table("census_tracts_cleaned")
def get_safegraph_visits():
"""Retrieve Safegraph visit data for Panama City Beach in July 2019
as a GeoDataFrame ordered by database id
Returns:
geopandas.GeoDataFrame: GeoDataFrame representation of table
"""
return get_table("safegraph_pcb_visits")
| 40444e212f80427876b8e3db168249d0b201a0e7 | [
"Python"
] | 2 | Python | Juliopdata/data-science-book | 9459273de3bb7b440b137c4add29a9ff2d5c57ee | d290ec187b758bcc8b80f692da3f4c3592e29352 |
refs/heads/main | <file_sep>'use strict';
//notes constructor function
// 1.New {} is created
// 2.function is called , this = {}
// 3.{} is linked to a prototype - ( creates .__proto__ property and sets its value to the prototype property of the constructor function that is being called )
// 4. function automatically returns the {}
const Person = function (firstname, birthyear) {
console.log(this);
this.firstname = firstname;
this.birthyear = birthyear;
//could name the created property anything but by convention use the same name as the parameter
// this.a = firstname;
// this.b = birthyear;
//don't add a method inside the function becasue each instance will have to carry this arounf and is bad for performance
// this.calcAge = function () {};÷\
};
// a new object is created
const mary = new Person('Mary', 1991);
console.log(mary);
//can create as many new objects as you want
const monty = new Person('monty', 2020);
const lucy = new Person('lucy', 1254);
const betty = new Person('Betty', 1978);
console.log(monty);
console.log(lucy);
console.log(betty);
// to check if the obj is an instance of the constructor function in question
console.log(mary instanceof Person); //true
//prototypes
Person.prototype.calcAge = function () {
console.log(2037 - this.birthyear);
};
//so, monty,lucy,betty's prototype is the same as Person.prototype
console.log(Person.prototype);
console.log(monty.__proto__);
console.log(monty.__proto__ === Person.prototype);
console.log(Person.prototype.isPrototypeOf(monty));
//but prototype.person is not the prototype of person!!
// the confusion comes from bad naming of this property , it's more like "propertyOfLinkedObject" as a more clear description
console.log(Person.prototype.isPrototypeOf(Person));
// you can check if the object has it's own property or if the property is a prototype
//set a new prototype property
Person.prototype.species = 'Homo Sapiens';
console.log(monty.hasOwnProperty('firstname')); //true
console.log(monty.hasOwnProperty('Homo Sapiens')); //false is is a prototype not a property that was put on the object,
//you can check in dev tools, it will be in __proto__, under the objects set properties
lucy.calcAge();
console.dir(Person.prototype.constructor);
//arrays
const arr = [223,223,35,55,55,55,55,2,2,2,2,2,23];
console.log(arr.__proto__);
console.log(arr.__proto__ === Array.prototype); //true
console.log(arr.__proto__.__proto__);
//you could add a new property(make your own) to the Array.prototype and use this custom property in your workflow
//just for an experiment but shouldn't do this,could cause lots of confusion on a team etc ...
Array.prototype.unique = function(){
return [... new Set(this)];
}
console.log(arr.unique());
console.dir(x => x + 1);
// coding challenge
const Car = function(make,speed){
this.make = make;
this.speed = speed;
}
Car.prototype.accelerate = function() {
this.speed += 10;
console.log(`The ${this.make} is traveling ${this.speed}`);
}
Car.prototype.accelerate = function() {
this.speed -= 5;
console.log(`The ${this.make} is traveling ${this.speed}`);
}
const BMW = new Car('BMW', 120);
const Mercedes = new Car('Mercedes', 95);
// console.log(BMW);
// console.log(Mercedes);
BMW.accelerate();
Mercedes.accelerate();
// static methods
//Object.create
//connects the created object prototype to the object
const protoPerson = {
calcAge() {
console.log(2037 - this.birthyear);
},
//this looks like a constructor but it just a plain function,not using new but is a way of
//this will point to the sarah object because we explicitly called init
//just a manual way to intialize the object
//doesn't have to be named init - could be anything
init(firstname,birthyear){
this.firstname = firstname;
this.birthyear = birthyear;
}
};
const steven = Object.create(protoPerson);
steven.name = 'Steven';
steven.birthyear = 1432;
steven.calcAge()
console.log(steven);
console.log(steven.__proto__ === protoPerson); //true
//code challenge 2
//remember you use the class declaration
// const Cars = class {}
class Cars {
constructor(make,speed){
this.make = make;
this.speed = speed;
}
get speedUS(){
return this.speed / 1.6;
};
//set always takes 1 argument
set speedUS(speed){
return this.speed = speed * 1.6;
}
accelerate() {
this.speed += 10;
console.log(`The ${this.make} is traveling ${this.speed}`);
}
decelerate() {
this.speed -= 5;
console.log(`The ${this.make} is traveling ${this.speed}`);
}
}
const BMW2 = new Cars('BMW',120);
const mercedes = new Cars('mercedes',50);
const ford = new Cars('ford',120);
console.log(BMW2.speed);
BMW2.accelerate();
BMW2.accelerate();
BMW2.decelerate();
console.log(mercedes.speed);
mercedes.accelerate();
mercedes.accelerate();
mercedes.decelerate();
console.log(ford.speed);
ford.accelerate();
ford.accelerate();
ford.decelerate();
ford.speedUS = 50;
console.log(ford); | ba89182361fea8f39f0bb81e9f9cf9af3da9e57b | [
"JavaScript"
] | 1 | JavaScript | life-code-joy/oop-js-practice-jonus | 9a8bc17cbd7909d1af6ec4f992b5f7b4da3c5cae | b1e5a1f64d3ee1843cfed067257308abf9923a7f |
refs/heads/master | <file_sep>var regent = {
util: require('./util'),
generator: require('./generator'),
regexp: require('./regexp')
};
module.exports = regent;<file_sep>var regent = require('../');
var $ = regent.generator;
// equal ^[a-zA-Z]{5}$
var wordGen = $.times($.one($.range('a', 'z'), $.range('A', 'Z')), 4);
var words = wordGen.map(function (gen) {
return gen();
});
words.forEach(function (word) {
console.log(word);
});<file_sep>var util = module.exports;
util.random = function (min, max) {
var a = min;
var b = max - min + 1;
return a + Math.floor(Math.random() * b);
};
util.combine = function (list, func) {
var first = list.shift();
var second = list.shift();
if (second === undefined) {
return first;
}
var combination = first.map(function (val1) {
return second.map(function (val2) {
return func(val1, val2);
});
}).reduce(function (val1, val2) {
return val1.concat(val2);
});
if (list.length === 0) {
return combination;
} else {
return util.combine([combination].concat(list), func);
}
};<file_sep>var util = require('./util');
var generator = module.exports;
generator.many1 = function (gen) {
var result = [];
for (var i = 1; i <= 512; i ++) {
(function (i) {
result.push(function () {
var result = [];
for (var j = 1; j <= i; j ++) {
result.push(gen[util.random(0, gen.length - 1)]());
}
return result.join('');
});
})(i);
}
return result;
};
generator.many = function (gen) {
return generator.many1(gen).concat(generator.pure(''));
};
generator.times = function (gen, count) {
var genList = [];
for (var i = 0; i < count; i ++) {
genList.push(gen);
}
return util.combine(genList, function (a, b) {
return function () {
return a() + b();
};
});
};
generator.one = function () {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (prev, curr) {
return prev.concat(curr);
});
};
generator.pure = function (str) {
return [function () {
return str;
}];
};
generator.range = function (beginChar, endChar) {
if (beginChar.length !== 1 || endChar.length !== 1) {
throw Error('Argument type is miss match.');
}
var minCode = beginChar.charCodeAt(0);
var maxCode = endChar.charCodeAt(0);
return [function () {
var charCode = util.random(minCode, maxCode);
return String.fromCharCode(charCode);
}];
};
<file_sep>var regent = require('../');
var $ = regent.generator;
// equal ^[01]{5}$
var binaryGen = $.times($.one($.pure('0'), $.pure('1')), 4);
var binaries = binaryGen.map(function (gen) {
return gen();
});
binaries.forEach(function (binary) {
console.log(binary);
});<file_sep>Regent
=====================
Regular Expression based string GENeraTor
Makes test case string from regex pattern.
Sorry, I have not written documents yet. See the example(example/) and test codes(test/). | 710945db6dc1129bde0004bbd6abe7f7e1face1e | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | KOBA789/regent | e6725ab6385d31a3de62a090f231c2f2555524d3 | f80da7628ce0ec6ec8e9d3e1618bd95d224491de |
refs/heads/master | <file_sep>/*
* This code encrypts input data using the Rijndael (AES) cipher. The
* key length is hard-coded to 128 key bits; this number may be changed
* by redefining a constant near the start of the file.
*
* This program uses CTR mode encryption.
*
* Usage: encrypt <key1> <key2> <file name>
*
* Author: <NAME> (<EMAIL>)
* Based on code from <NAME> (<EMAIL>)
*
*/
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "rijndael.h"
#include <sys/stat.h>
static char rcsid[] = "$Id: encrypt.c,v 1.2 2003/04/15 01:05:36 elm Exp elm $";
#define KEYBITS 128
/*hexvalue takes a character input and returns its hex equivalent along with validation if the character was a hex value originally*/
int hexvalue (char c)
{
if (c >= '0' && c <= '9') {
return (c - '0');
} else if (c >= 'a' && c <= 'f') {
return (10 + c - 'a');
} else if (c >= 'A' && c <= 'F') {
return (10 + c - 'A');
} else {
fprintf (stderr, "ERROR: key digit %c isn't a hex digit!\n", c);
exit (-1);
}
}
int main (int argc, char **argv){
unsigned long rk[RKLENGTH(KEYBITS)]; /* round key */
unsigned char key[KEYLENGTH(KEYBITS)];/* cipher key */
char buf[100];
int i, nbytes, nwritten , ctr;
int totalbytes;
int k0, k1;
int fileId = 0x1234; /* fake (in this example) */
int nrounds; /* # of Rijndael rounds */
char *password; /* supplied (ASCII) password */
int fd;
char *filename;
unsigned char filedata[16];
unsigned char ciphertext[16];
unsigned char ctrvalue[16];
char *inputkey;
int z,keysize,counter ;
if (argc < 4)
{
fprintf (stderr, "Usage: %s <-e -d > <key> <file>\n", argv[0]);
return 1;
}
if(argc==4){
// printf("%s /n" , argv[2]);
filename = argv[3];
/*Getting file info*/
struct stat fileInfo;
stat (filename, &fileInfo);
uid_t fileOwner = fileInfo.st_uid;
/*get key from the input*/
inputkey=argv[2];
keysize=strlen(inputkey); /*get input keys size to divied them*/
// printf("%d\n", keysize);
/*vaildate the input key is hexa decimal then divide it into k0 and k1*/
for (z=0 ;inputkey[z];z++){
hexvalue(inputkey[z]);
// printf("%c", inputkey[z]);
}
/*
Checking if the user option was encryption. It validates first if the file was encrypted or not. If not, it does.
*/
if (!strcmp(argv[1], "-e")) {
if (fileInfo.st_mode & S_ISVTX) {
fprintf (stderr, "Error: %s is already encrypted.\n", filename);
return 1;
} else {
fileId = fileInfo.st_ino;
if (chmod(filename, S_ISVTX)) {
perror("protectfile");
exit (-1);
}
}
}
/*
Checking if the user option was decryption. It validates first if the file was decrypted or not. If not, it does.
*/
else if (!strcmp(argv[1], "-d")) {
if (!(fileInfo.st_mode & S_ISVTX)) {
fprintf (stderr, "Error: %s is already decrpyted.\n", filename);
return 1;
} else {
fileId = fileInfo.st_ino;
if (chmod(filename, S_ISVTX)) {
perror("protectfile");
exit (-1);
}
}
}
}
else{
printf(stderr, "Usage for first time users: %s <-e/-d option> <key>\n", argv[0]);
return 1;
}
nrounds = rijndaelSetupEncrypt(rk, key, KEYBITS);
fd = open(filename, O_RDWR);
if (fd < 0)
{
fprintf(stderr, "Error opening file %s\n", argv[3]);
return 1;
}
bcopy (&fileId, &(ctrvalue[8]), sizeof (fileId));
/* This loop reads 16 bytes from the file, XOR*/
for (ctr = 0, totalbytes = 0; ; ctr++)
{
/* Read 16 bytes (128 bits, the blocksize) from the file */
nbytes = read (fd, filedata, sizeof (filedata));
if (nbytes <= 0) {
break;
}
if (lseek (fd, totalbytes, SEEK_SET) < 0)
{
perror ("Unable to seek back over buffer");
exit (-1);
}
bcopy (&ctr, &(ctrvalue[0]), sizeof (ctr));
/* Call the encryption routine to encrypt the CTR value */
rijndaelEncrypt(rk, nrounds, ctrvalue, ciphertext);
for (i = 0; i < nbytes; i++) {
filedata[i] ^= ciphertext[i];
}
/* Write the result back to the file */
nwritten = write(fd, filedata, nbytes);
if (nwritten != nbytes)
{
fprintf (stderr,
"%s: error writing the file (expected %d, got %d at ctr %d\n)",
argv[0], nbytes, nwritten, ctr);
break;
}
/* Increment the total bytes written */
totalbytes += nbytes;
}
close(fd);
return 0;
}
<file_sep>#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/sysproto.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <sys/types.h>
#include <sys/ucred.h>
#include <sys/param.h>
int
main (int argc, char **argv)
{
int arg2 = (argc == 2);
if (!arg2) {
printf("usage: setkey <key>\n");
return 1;
}
unsigned long k = strtol(argv[1], NULL, 0);
unsigned long keyOne = k & 0xffffffff;
unsigned long keyTwo = k >> 32;
syscall(548, keyOne, keyTwo);
// struct thread *td;
//struct ucred *cred;
// cred = td->td_proc->p_ucred;
// unsigned int k0 = cred->keyOne;
// unsigned int k1 = cred->keyTwo;
// printf("%u\n", k0);
// printf("%u\n", k1);
}
<file_sep>#include <sys/sysproto.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/systm.h>
#include <sys/module.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/sysent.h>
#include <sys/vnode.h>
#include <sys/syslog.h>
#define KEYBITS 128
#define KEYLENGTH(keybits) ((keybits)/8)
#ifndef _SYS_SYSPROTO_H_
struct setkey_args{
unsigned int keyOne;
unsigned int keyTwo;
};
#endif
int
sys_setkey(struct thread *td, struct setkey_args *args)
{
unsigned int keyOne = args->keyOne;
unsigned int keyTwo = args->keyTwo;
struct ucred *cred = td->td_proc->p_ucred;
uid_t id = cred->cr_uid;
unsigned char key[KEYLENGTH(KEYBITS)];
bzero(key,sizeof(key));
bcopy (&keyOne, &(key[0]), sizeof (keyOne));
bcopy (&keyTwo, &(key[sizeof(keyOne)]), sizeof (keyTwo));
/*Disable setting key if both keys provided were zeros*/
if (keyOne == 0 && keyTwo == 0) {
cred->keyOne = 0;
cred->keyTwo = 0;
return 0;
}
else {
cred->keyOne = keyOne;
cred->keyTwo = keyTwo;
printf("Added\n");
log(-1,"Added");
}
static struct ucred userList[16];
int userExistFlag = 0;
for (int i = 0; i< 16;i++){
printf("User: %lu\n",(unsigned long int)userList[i].cr_uid);
printf("K0: %u\n", userList[i].keyOne);
printf("K1: %u\n", userList[i].keyTwo);
}
for(int i = 0; i<16;i++){
if (id == userList[i].cr_uid){
userExistFlag = 1;
if (keyOne == 0 && keyTwo == 0){
userList[i].keyOne = keyOne;
userList[i].keyTwo = keyTwo;
for (int i = 0; i< 16;i++){
printf("User: %lu\n",(unsigned long int)userList[i].cr_uid);
printf("K0: %u\n", userList[i].keyOne);
printf("K1: %u\n", userList[i].keyTwo);
}
return 0;
}
else if (userList[i].keyOne == 0 && userList[i].keyTwo == 0){
userList[i].keyOne = keyOne;
userList[i].keyTwo = keyTwo;
return 0;
}
}
if (!userExistFlag){
for(int i = 0; i<16;i++){
if(userList[i].cr_uid==0){
userList[i].keyOne = keyOne;
userList[i].keyTwo = keyTwo;
userList[i].cr_uid = id;
for (int i = 0; i< 16;i++){
printf("User: %lu\n",(unsigned long int)userList[i].cr_uid);
printf("K0: %u\n", userList[i].keyOne);
printf("K1: %u\n", userList[i].keyTwo);
}
printf("Key Added\n");
log(-1,"KEY ADDED");
return 0;
}
}
printf("List is Full\n");
return 0;
}
for (int i = 0; i< 16;i++){
printf("User: %lu\n",(unsigned long int)userList[i].cr_uid);
printf("K0: %u\n", userList[i].keyOne);
printf("K1: %u\n", userList[i].keyTwo);
}
return 0;
}
return 0;
}
<file_sep>setKey: setkey.c
cc -o setKeyTest setkey.c
| dd99ab5fafae278d447ee44a4f45aca8872a1ad7 | [
"C",
"Makefile"
] | 4 | C | omargaber/Crypto-File-System | e3aff64a82c4b5b5f1ed7608297e026d558f6644 | c561c2971f821068c75d0d16f4e5b8b4cc9cf919 |
refs/heads/master | <file_sep>package com.varun.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.varun.model.Feedback;
import com.varun.service.FeedBackService;
@Controller
public class HomeController {
@Autowired
FeedBackService feedBackService;
@RequestMapping("/home")
public String homePage() {
return "home";
}
@RequestMapping("/feedback")
public ModelAndView feedbackForm() {
return new ModelAndView("feedback","command",new Feedback());
}
@RequestMapping("/addFeedback")
public String addFeedBack(@ModelAttribute Feedback fb) {
System.out.println("In add feedback");
feedBackService.addFeedBack(fb);
return "redirect:/feedback";
}
}
<file_sep>package com.varun.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Feedback {
private String name;
private String gender;
@Id
private String email;
private String website;
private int code;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| c13e7bdae260c9714cebe6f7a2b7c4303bda667a | [
"Java"
] | 2 | Java | varunbelekar/SpringMvcMaven | 493728e8cf344de8d4ce5fb20d2d7711d2f3ba55 | e057f5e818952ff2d4cbf3ba94b9424736ac06df |
refs/heads/main | <repo_name>aj686/Raspberry-Pi-4-with-servo-motor<file_sep>/servo.py
#import libs
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(40,GPIO.OUT)
#Initiakize PWM
servo = GPIO.PWM(40,50)
servo.start(0)
while True:
print("0")
servo.ChangeDutyCycle(2.5)
time.sleep(1)
print("180")
servo.ChangeDutyCycle(12.5)
time.sleep(1)
servo.stop()
GPIO.cleanup()
break
<file_sep>/README.md
# Raspberry-Pi-4-with-servo-motor
Mini project
| 55568498778716cd2d2d9481745d2fadcee0802d | [
"Markdown",
"Python"
] | 2 | Python | aj686/Raspberry-Pi-4-with-servo-motor | b5aae0660b4aa9f6d9588ac28c786a191a0cd37b | ce195c015df3117a4c79a2ca0c9859b9b094a1d8 |
refs/heads/master | <repo_name>plus2dot/signoxemedia<file_sep>/notification_manager/apps.py
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class NotificationManagerConfig(AppConfig):
name = 'notification_manager'
<file_sep>/client_manager/migrations/0005_client_app_build_channel.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-16 13:23
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0006_auto_20170116_1853'),
('client_manager', '0004_auto_20170114_1732'),
]
operations = [
migrations.AddField(
model_name='client',
name='app_build_channel',
field=models.ForeignKey(blank=True,
help_text='All devices owned by this client will recieve updates published to this channel.',
null=True, on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.AppBuildChannel'),
),
]
<file_sep>/notification_manager/views.py
# -*- coding: utf-8 -*-
# Create your views here.
from django.db.models import Q
from django.utils import timezone
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response
from notification_manager.models import Post, UserPostStatus
from notification_manager.serializers import PostSerializer
class PostViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
def get_queryset(self):
user = self.request.user
if user.is_anonymous:
raise PermissionDenied
one_month_ago = timezone.now() - timezone.timedelta(days=31)
# Return posts that are either from the past one month, or are unread by the
# current user.
return self.queryset.filter(
Q(posted_on__gte=one_month_ago) |
Q(userpoststatus__user=user, userpoststatus__read_on=None)).distinct()
# noinspection PyUnusedLocal
@detail_route(methods=['POST'])
def mark_read(self, request, pk=None):
user = request.user
post = self.get_object()
post.userpoststatus_set.filter(user=user).update(read_on=timezone.now())
serializer = self.serializer_class(post, context=self.get_serializer_context())
return Response(serializer.data)
@list_route(methods=['POST'])
def mark_all_read(self, request):
user = request.user
unread_post_statuses = UserPostStatus.objects.filter(user=user, read_on=None)
unread_post_statuses.update(read_on=timezone.now())
serializer = self.serializer_class(self.get_queryset(),
many=True,
context=self.get_serializer_context())
return Response(serializer.data)
<file_sep>/feedmanager/migrations/0005_feed_publish_to.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-12 21:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0001_initial'),
('feedmanager', '0004_auto_20160909_2257'),
]
operations = [
migrations.AddField(
model_name='feed',
name='publish_to',
field=models.ManyToManyField(to='client_manager.Client'),
),
]
<file_sep>/feedmanager/migrations/0005_auto_20160918_0306.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-17 21:36
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
import utils.files
class Migration(migrations.Migration):
dependencies = [
('feedmanager', '0004_auto_20160909_2257'),
]
operations = [
migrations.AlterField(
model_name='category',
name='name',
field=models.CharField(
help_text='Enter a helpful name for this feed category. '
'Example: <em>"Word of the Day"</em>',
max_length=100),
),
migrations.AlterField(
model_name='category',
name='type',
field=models.CharField(choices=[('RANDOM', 'Random'), ('DATED', 'Dated')],
help_text='Select whether this option is time-sensitive or '
'not.For a time-sensitive category (e.g. "This '
'day in history"), only content relevant to the '
'current date will be fetched.',
max_length=10),
),
migrations.AlterField(
model_name='feed',
name='category',
field=models.ForeignKey(
help_text='The feed category decides what snippets appear in this feed.',
on_delete=django.db.models.deletion.CASCADE, to='feedmanager.Category'),
),
migrations.AlterField(
model_name='feed',
name='name',
field=models.CharField(
help_text='This is a friendly name to identify this feed, it is not '
'visible to end-users. ',
max_length=100),
),
migrations.AlterField(
model_name='feed',
name='published',
field=models.BooleanField(default=False,
help_text='A feed that is published will appear in '
"users' asset lists. For a feed to be "
'published it needs to have a valid snippet.'),
),
migrations.AlterField(
model_name='feed',
name='slug',
field=models.SlugField(
help_text='This field should be filled in automatically based on the '
'name. It is a simplified representation of the name such that '
'it can be part of a URL.'),
),
migrations.AlterField(
model_name='imagesnippet',
name='media',
field=models.FileField(
help_text='This is the media file that will be served in the feed '
'directly.',
storage=utils.files.DedupedMediaStorage(),
upload_to=utils.files.md5_file_name),
),
migrations.AlterField(
model_name='snippet',
name='category',
field=models.ForeignKey(
help_text='Select which category should display this snippet.',
on_delete=django.db.models.deletion.CASCADE,
to='feedmanager.Category'),
),
migrations.AlterField(
model_name='snippet',
name='date',
field=models.DateField(blank=True,
help_text='Enter a date here if this snippet is '
'date-sensitive. This will only have an effect '
'if the snippet category itself is '
'date-sensitive.',
null=True),
),
migrations.AlterField(
model_name='snippet',
name='title',
field=models.CharField(blank=True,
help_text='Pick a good topic or title for the snippet. In '
'some cases this might be visible to end-users. ',
max_length=255, null=True),
),
migrations.AlterField(
model_name='template',
name='name',
field=models.CharField(
help_text='This is just a friendly name to help you recognise the purpose '
'of the template. It is not visible to users.',
max_length=100),
),
migrations.AlterField(
model_name='template',
name='template_data',
field=models.TextField(
help_text='This is the actual content of the template. The title and '
'content snippets will be filled in here to render the final '
'page that will be pushed to devices.'),
),
migrations.AlterField(
model_name='videosnippet',
name='media',
field=models.FileField(
help_text='This is the media file that will be served in the feed '
'directly.',
storage=utils.files.DedupedMediaStorage(),
upload_to=utils.files.md5_file_name),
),
migrations.AlterField(
model_name='webfeed',
name='template',
field=models.ForeignKey(
help_text='Web feeds fill in the data from web snippets into this template '
'to produce the final page that will be seen by on devices.',
on_delete=django.db.models.deletion.CASCADE, to='feedmanager.Template'),
),
migrations.AlterField(
model_name='websnippet',
name='content',
field=models.TextField(
help_text='This is the actual content of the web snippet. How and '
'where it appears depends on the template used to render '
'it. Some templates strip HTML content.'),
),
]
<file_sep>/devicemanager/migrations/0013_prioritymessage.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-13 07:46
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mediamanager', '0010_auto_20170407_1939'),
('devicemanager', '0012_auto_20170604_1731'),
]
operations = [
migrations.CreateModel(
name='PriorityMessage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('activated_on', models.DateTimeField(blank=True, null=True)),
('duration', models.IntegerField(blank=True,
choices=[(0, 'Indefinite'), (15, '15 Minutes'),
(30, '30 Minutes'),
(45, '45 Minutes'),
(60, '60 Minutes')], null=True)),
('device_group',
models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.DeviceGroup')),
('message', models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.Asset')),
],
),
]
<file_sep>/client_manager/migrations/0006_auto_20170305_0251.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-04 21:21
from __future__ import unicode_literals
import storages.backends.s3boto
from django.db import migrations, models
import client_manager.models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0005_client_app_build_channel'),
]
operations = [
migrations.AlterField(
model_name='client',
name='device_logo',
field=models.ImageField(blank=True,
help_text='A logo of the client for use on the device. If no device logo is provided, the main logo will be used.',
null=True, storage=storages.backends.s3boto.S3BotoStorage(),
upload_to=client_manager.models.upload_location_device_logo),
),
migrations.AlterField(
model_name='client',
name='logo',
field=models.ImageField(help_text='A logo of the client for use in the frontend.',
storage=storages.backends.s3boto.S3BotoStorage(),
upload_to=client_manager.models.upload_location_logo),
),
]
<file_sep>/client_manager/models.py
# -*- coding: utf-8 -*-
""" Models for the client manager app. """
from datetime import datetime, timedelta
from pathlib import PurePath
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.text import slugify
from rest_framework.authtoken.models import Token
from utils.files import calculate_checksum
from utils.storage import NormalStorage
def build_upload_location(instance, filename, upload_name):
client_dir = slugify(instance.name)
return 'clients/{client_dir}/{upload_name}{extension}'.format(
client_dir=client_dir,
upload_name=upload_name,
extension=PurePath(filename).suffix)
def upload_location_logo(instance, filename):
return build_upload_location(instance, filename, 'logo')
def upload_location_device_logo(instance, filename):
return build_upload_location(instance, filename, 'device_logo')
class Client(models.Model):
"""
This model represents a client, or a customer of this app. It can be used to isolate content of
different clients such that they cannot see each others' content or edit / manage it.
"""
name = models.CharField(
max_length=100,
help_text='Name of client')
logo = models.ImageField(
upload_to=upload_location_logo,
storage=NormalStorage(),
help_text='A logo of the client for use in the frontend.')
logo_checksum = models.CharField(
max_length=120,
editable=False,
null=True,
blank=True)
update_interval = models.DurationField(
default=timedelta(minutes=2),
help_text='How often should devices check for updates')
device_logo = models.ImageField(
upload_to=upload_location_device_logo,
storage=NormalStorage(),
null=True,
blank=True,
help_text='A logo of the client for use on the device. '
'If no device logo is provided, the main logo will be used.')
device_logo_checksum = models.CharField(
max_length=120,
editable=False,
null=True,
blank=True)
display_device_logo = models.BooleanField(
default=True,
help_text='Whether a logo should be shown on the device or not.', )
app_build_channel = models.ForeignKey(
'devicemanager.AppBuildChannel',
null=True,
blank=True,
help_text='All devices owned by this client will '
'receive updates published to this channel.')
organisation_name = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Name of the organisation')
organisation_address = models.CharField(
max_length=255,
null=True,
blank=True,
help_text='Primary address of the organisation')
primary_contact_name = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Name of primary contact.')
primary_contact_email = models.EmailField(
null=True,
blank=True,
help_text='E-Mail address of primary contact.')
primary_contact_phone = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Phone number of primary contact.')
technical_contact_name = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Name of technical contact.')
technical_contact_email = models.EmailField(
null=True,
blank=True,
help_text='E-Mail address of technical contact.')
technical_contact_phone = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Phone number of technical contact.')
financial_contact_name = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Name of financial contact.')
financial_contact_email = models.EmailField(
max_length=100,
null=True,
blank=True,
help_text='E-Mail address of financial contact.')
financial_contact_phone = models.CharField(
max_length=100,
null=True,
blank=True,
help_text='Phone number of financial contact.')
def get_logo_data(self):
""" Returns the URL of the logo for this client. """
if self.device_logo:
if self.device_logo_checksum is None:
self.save()
return self.device_logo.url, self.device_logo_checksum
else:
if self.logo_checksum is None:
self.save()
return self.logo.url, self.logo_checksum
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
self.logo_checksum = calculate_checksum(self.logo)
if self.device_logo:
self.device_logo_checksum = calculate_checksum(self.device_logo)
super().save(force_insert, force_update, using, update_fields)
def __str__(self):
return self.name
class ClientSubscriptionData(models.Model):
activation_date = models.DateField(default=datetime.now)
renewal_date = models.DateField(default=datetime.now)
client = models.OneToOneField(Client, related_name='subscription')
@property
def next_renewal_date(self):
return self.renewal_date + relativedelta(months=1)
def __str__(self):
return 'Subscription(Started: {}, Last Renewed: {})'.format(
self.activation_date,
self.renewal_date)
class Meta:
verbose_name_plural = 'Client Subscription Data'
verbose_name = 'Client Subscription Data'
class ClientUserProfile(models.Model):
"""
This model connects the user model to the client model allowing users to be associated with a
client and limits the data they can interact with to that associated with the client.
"""
user = models.OneToOneField(User, related_name='profile')
client = models.ForeignKey(Client)
def __str__(self):
return '"{user}" of "{client}"'.format(user=self.user, client=self.client)
class ClientSettings(models.Model):
client = models.OneToOneField(Client, related_name='settings')
idle_detection_enabled = models.BooleanField(
default=False,
help_text='Should the app auto-launch during idle periods.')
idle_detection_threshold = models.PositiveSmallIntegerField(
default=15,
help_text='How long (in minutes) should the device be idle before '
'the app is launched.')
def __str__(self):
return 'Settings for {}'.format(self.client)
class Features(models.Model):
client = models.OneToOneField(Client, related_name='features')
screenshots = models.BooleanField(
default=False,
help_text='Enables or disable the screenshot feature for the client.')
smart_notice_board = models.BooleanField(
default=False,
help_text='Enabled or disables smart notice board support. '
'This includes support for the Windows client with idle '
'detection, scheduled launching, and push messaging.')
def __str__(self):
return 'Feature set for {}'.format(self.client)
# noinspection PyUnusedLocal
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
""" Automatically creates a new token for a user when a new user is added. """
if created:
Token.objects.create(user=instance)
<file_sep>/tests/test_admin_login.py
# -*- coding: utf-8 -*-
from pytest_bdd import scenarios, then
scenarios('features/admin_login.feature')
@then('Login should succeed')
def successful_login(client):
response = client.get('/admin/')
assert response.status_code == 200
@then('Login should not succeed')
def failed_login(client):
response = client.get('/admin/')
assert response.status_code != 200
<file_sep>/tests/conftest.py
# -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from pytest_bdd import given
from pytest_bdd.parsers import parse
@given(parse("I'm a {user_type} user"))
def user_object(user_type, transactional_db):
UserModel = get_user_model()
user = UserModel.objects.create_user('{}_user'.format(user_type),
password='<PASSWORD>')
if user_type == 'super':
user.is_staff = True
user.is_superuser = True
elif user_type == 'staff':
user.is_staff = True
user.save()
return user
@given('I log in')
def logged_in_client(user_object, client):
assert client.login(username=user_object.username, password='<PASSWORD>')
return client
<file_sep>/schedule_manager/migrations/0003_scheduledcontent_bring_to_front.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-16 07:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule_manager', '0002_auto_20170305_0251'),
]
operations = [
migrations.AddField(
model_name='scheduledcontent',
name='bring_to_front',
field=models.BooleanField(default=False),
),
]
<file_sep>/mediamanager/urls.py
# -*- coding: utf-8 -*-
""" URL routing configuration for media manager app """
from django.conf.urls import url
from mediamanager.views import asset_view, cal_asset_view, web_asset_view
urlpatterns = [
url(r'^preview/(?P<asset_id>\d+)/', asset_view, name='asset-view'),
url(r'^web/(?P<asset_id>\d+)/', web_asset_view, name='webasset-view'),
url(r'^cal/(?P<asset_id>\d+)/', cal_asset_view, name='calasset-view'),
]
<file_sep>/signoxe_server/hosts.py
# -*- coding: utf-8 -*-
from django_hosts import host, patterns
host_patterns = patterns(
'',
host(r'admin', 'signoxe_server.urls.admin', name='admin'),
host(r'api', 'signoxe_server.urls.api', name='api'),
host(r'content', 'signoxe_server.urls.content', name='content'),
host(r'devices', 'signoxe_server.urls.devices', name='devices'),
host(r'(\w+)', 'signoxe_server.urls', name='wildcard'),
)
<file_sep>/feedmanager/migrations/0009_auto_20171023_1951.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-23 14:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feedmanager', '0008_auto_20170315_1917'),
]
operations = [
migrations.AlterField(
model_name='category',
name='type',
field=models.CharField(choices=[('RANDOM', 'Random'), ('DATED', 'Dated')],
help_text='Select whether this option is time-sensitive or not.For a time-sensitive category (e.g. "This day in history"), only content relevant to the current date will be fetched.',
max_length=10),
),
]
<file_sep>/pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = signoxe_server.settings_test
python_files = test*.py
<file_sep>/devicemanager/migrations/0011_devicescreenshot_thumbnail.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 18:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0010_auto_20170511_1549'),
]
operations = [
migrations.AddField(
model_name='devicescreenshot',
name='thumbnail',
field=models.CharField(blank=True, editable=False, max_length=255, null=True),
),
]
<file_sep>/feedmanager/urls.py
# -*- coding: utf-8 -*-
""" URL routing configuration for feed manager app. """
from django.conf.urls import url
from feedmanager.views import image_feed_view, video_feed_view, web_feed_view
urlpatterns = [
url(r'web/(?P<slug>[-\w]+)/', web_feed_view, name='web-feed-view'),
url(r'image/(?P<slug>[-\w]+)/', image_feed_view, name='image-feed-view'),
url(r'video/(?P<slug>[-\w]+)/', video_feed_view, name='video-feed-view'),
]
<file_sep>/notification_manager/admin.py
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.db import models
from mediamanager.widgets import AceEditorWidget
from notification_manager.models import Post, PostTopic
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'topic', 'posted_on')
list_filter = ('topic', 'posted_on')
formfield_overrides = {
models.TextField: {'widget': AceEditorWidget}
}
admin.site.register(PostTopic)
<file_sep>/feedmanager/migrations/0002_auto_20160821_1855.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-21 13:25
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feedmanager', '0001_squashed_0006_feed_type'),
]
operations = [
migrations.RemoveField(
model_name='imagefeed',
name='category',
),
migrations.RemoveField(
model_name='template',
name='category',
),
migrations.RemoveField(
model_name='videofeed',
name='category',
),
migrations.AddField(
model_name='feed',
name='category',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE,
to='feedmanager.Category'),
preserve_default=False,
),
]
<file_sep>/signoxe_server/settings_test.py
# -*- coding: utf-8 -*-
""" Setting for use while testing """
# noinspection PyUnresolvedReferences
from .settings import *
# Reset staticfile storage so we don't get manifest errors
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
<file_sep>/devicemanager/migrations/0004_auto_20160919_0037.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-18 19:07
from __future__ import unicode_literals
from django.db import migrations, models
import devicemanager.models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0003_device_build_version'),
]
operations = [
migrations.CreateModel(
name='AppBuild',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('version_code', models.PositiveIntegerField(
help_text='The version of code of the Android application. This value '
'should always increase. The app build with the highest '
'version will be pused to the devices.')),
('app_build', models.FileField(
help_text='The app APK file.',
upload_to=devicemanager.models.build_upload_location)),
('checksum', models.CharField(editable=False, max_length=120)),
],
),
migrations.AlterField(
model_name='device',
name='build_version',
field=models.PositiveIntegerField(blank=True, editable=False, null=True),
),
]
<file_sep>/client_manager/apps.py
# -*- coding: utf-8 -*-
""" Client manager app config. """
from django.apps import AppConfig
class ClientManagerConfig(AppConfig):
""" Client manager app config class. """
name = 'client_manager'
verbose_name = 'Client Manager'
<file_sep>/Dockerfile
FROM python:3.6
ENV PYTHONUNBUFFERED 1
ENV DEBUG True
EXPOSE 4000
RUN mkdir /app
WORKDIR /app
ADD requirements.pip /app/
RUN pip install -r requirements.pip
ADD . /app/
RUN python manage.py migrate
ENTRYPOINT ["python", "manage.py", "runserver", "0:4000"]
<file_sep>/client_manager/migrations/0003_auto_20170114_1730.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-14 12:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0002_client_display_device_logo'),
]
operations = [
migrations.AddField(
model_name='client',
name='device_logo',
field=models.ImageField(blank=True,
help_text='A logo of the client for use on the device.',
null=True, upload_to=''),
),
migrations.AlterField(
model_name='client',
name='display_device_logo',
field=models.BooleanField(default=True,
help_text='Whether a logo should be shown on the device or '
'not. '),
),
migrations.AlterField(
model_name='client',
name='logo',
field=models.ImageField(help_text='A logo of the client for use in the frontend.',
upload_to=''),
),
migrations.AlterField(
model_name='client',
name='name',
field=models.CharField(help_text='Name of client', max_length=100),
),
]
<file_sep>/notification_manager/serializers.py
# -*- coding: utf-8 -*-
from rest_framework import serializers
from notification_manager.models import Post, UserPostStatus
class PostSerializer(serializers.ModelSerializer):
topic = serializers.CharField(source='topic.name')
icon = serializers.FileField(source='topic.image')
is_read = serializers.SerializerMethodField()
def get_is_read(self, obj):
user = self.context['request'].user
return UserPostStatus.objects.get(user=user,
post=obj).read_on is not None
class Meta:
model = Post
fields = ('id', 'title', 'topic', 'icon', 'content', 'posted_on', 'is_read')
<file_sep>/feedmanager/admin.py
# -*- coding: utf-8 -*-
""" Admin setup for feed manager app. """
from django.contrib import admin
from django.db import models
from feedmanager.models import (Category, ImageFeed, ImageSnippet, Template, VideoFeed,
VideoSnippet, WebFeed, WebSnippet)
from mediamanager.widgets import AceEditorWidget
@admin.register(WebFeed)
class WebFeedAdmin(admin.ModelAdmin):
""" Admin panel setup class for web feeds. """
list_display = ('name', 'category', 'template', 'published',)
list_filter = ('category', 'published',)
filter_horizontal = ('publish_to',)
prepopulated_fields = {'slug': ('name',)}
@admin.register(ImageFeed)
@admin.register(VideoFeed)
class ImageVideoFeedAdmin(admin.ModelAdmin):
""" Admin panel setup class for file-based feeds. """
list_display = ('name', 'category', 'published',)
list_filter = ('category', 'published',)
filter_horizontal = ('publish_to',)
prepopulated_fields = {'slug': ('name',)}
@admin.register(WebSnippet)
@admin.register(ImageSnippet)
@admin.register(VideoSnippet)
class SnippetAdmin(admin.ModelAdmin):
""" Admin panel setup class for snippets. """
list_display = ('title', 'category', 'date')
list_filter = ('category',)
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
""" Admin panel setup class for categories. """
list_display = ('name', 'type',)
list_filter = ('type',)
@admin.register(Template)
class TemplateAdmin(admin.ModelAdmin):
""" Admin panel setup class for templates. """
list_display = ('name', 'duration')
formfield_overrides = {
models.TextField: {'widget': AceEditorWidget}
}
<file_sep>/schedule_manager/tests/test_valid_schedules.py
# -*- coding: utf-8 -*-
import datetime
import pytest
from django.core.exceptions import ValidationError
from schedule_manager.models import ScheduledContent, WeekDays
@pytest.mark.django_db
def test_disallow_start_time_after_end_time(device_group_1, content_feed_1):
scheduled_content = ScheduledContent(
day=WeekDays.FRIDAY,
default=False,
start_time=datetime.time(11, 5, 0),
end_time=datetime.time(10, 2, 3),
content=content_feed_1,
device_group=device_group_1
)
with pytest.raises(ValidationError):
scheduled_content.save()
@pytest.mark.django_db
@pytest.mark.parametrize('group_1,group_2,day_1,day_2', (
('device_group_1', 'device_group_1', WeekDays.MONDAY, WeekDays.TUESDAY),
('device_group_1', 'device_group_2', WeekDays.MONDAY, WeekDays.MONDAY),
('device_group_1', 'device_group_2', WeekDays.MONDAY, WeekDays.TUESDAY),
))
@pytest.mark.parametrize('start_time_1,end_time_1,start_time_2,end_time_2', (
# Second slice contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(11, 11, 3), datetime.time(11, 55, 50),),
# First slice contained in second slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(10, 11, 3), datetime.time(13, 55, 50),),
# Second start contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(11, 11, 3), datetime.time(13, 55, 50),),
# Second end contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(10, 11, 3), datetime.time(11, 55, 50),),
))
def test_allow_intersection_across_days_and_groups(group_1, group_2,
day_1, day_2,
start_time_1, end_time_1,
start_time_2, end_time_2,
content_feed_1,
request):
group_1 = request.getfuncargvalue(group_1)
group_2 = request.getfuncargvalue(group_2)
ScheduledContent.objects.create(
day=day_1,
default=False,
start_time=start_time_1,
end_time=end_time_1,
content=content_feed_1,
device_group=group_1
)
scheduled_content = ScheduledContent(
day=day_2,
default=False,
start_time=start_time_2,
end_time=end_time_2,
content=content_feed_1,
device_group=group_2
)
assert scheduled_content.save() is None
@pytest.mark.django_db
@pytest.mark.parametrize('start_time_1,end_time_1,start_time_2,end_time_2', (
# Second slice contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(11, 11, 3), datetime.time(11, 55, 50),),
# First slice contained in second slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(10, 11, 3), datetime.time(13, 55, 50),),
# Second start contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(11, 11, 3), datetime.time(13, 55, 50),),
# Second end contained in first slice
(datetime.time(11, 5, 0), datetime.time(12, 0, 5),
datetime.time(10, 11, 3), datetime.time(11, 55, 50),),
))
def test_disallow_intersection_for_same_day_and_group(device_group_1,
start_time_1, end_time_1,
start_time_2, end_time_2,
content_feed_1):
ScheduledContent.objects.create(
day=WeekDays.FRIDAY,
default=False,
start_time=start_time_1,
end_time=end_time_1,
content=content_feed_1,
device_group=device_group_1
)
scheduled_content = ScheduledContent(
day=WeekDays.FRIDAY,
default=False,
start_time=start_time_2,
end_time=end_time_2,
content=content_feed_1,
device_group=device_group_1
)
with pytest.raises(ValidationError):
scheduled_content.save()
@pytest.mark.django_db
def test_allow_editing_range_for_existing_schedule(device_group_1, content_feed_1):
scheduled_content = ScheduledContent(
day=WeekDays.FRIDAY,
default=False,
start_time=datetime.time(9, 5, 0),
end_time=datetime.time(10, 2, 3),
content=content_feed_1,
device_group=device_group_1
)
scheduled_content.save()
scheduled_content.start_time = datetime.time(9, 10, 0)
scheduled_content.save()
@pytest.mark.django_db
@pytest.mark.parametrize('start_time,end_time', (
(datetime.time(11, 5, 0), datetime.time(12, 0, 5)),
(datetime.time(11, 5, 0), None,),
(None, datetime.time(12, 0, 5),),
))
def test_ensure_no_start_end_time_for_default(start_time,
end_time,
content_feed_1,
device_group_1):
scheduled_content = ScheduledContent(
day=WeekDays.WEDNESDAY,
default=True,
start_time=start_time,
end_time=end_time,
content=content_feed_1,
device_group=device_group_1
)
with pytest.raises(ValidationError):
scheduled_content.save()
@pytest.mark.django_db
@pytest.mark.parametrize('start_time,end_time', (
(datetime.time(11, 5, 0), None,),
(None, datetime.time(12, 0, 5),),
(None, None),
))
def test_ensure_start_end_time_for_non_default(start_time, end_time, content_feed_1,
device_group_1):
scheduled_content = ScheduledContent(
day=WeekDays.THURSDAY,
default=False,
start_time=start_time,
end_time=end_time,
content=content_feed_1,
device_group=device_group_1
)
with pytest.raises(ValidationError):
scheduled_content.save()
<file_sep>/devicemanager/migrations/0009_auto_20170509_1529.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-09 09:59
from __future__ import unicode_literals
import django.db.models.deletion
import storages.backends.s3boto
from django.db import migrations, models
import devicemanager.models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0008_auto_20170419_1218'),
]
operations = [
migrations.CreateModel(
name='DeviceScreenShot',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('image', models.ImageField(
storage=storages.backends.s3boto.S3BotoStorage(),
upload_to=devicemanager.models.screenshot_upload_location)),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
migrations.AlterField(
model_name='device',
name='command',
field=models.CharField(blank=True, choices=[('reboot', 'Reboot Device'),
('free-space', 'Delete Unused Media'), (
'clear-media',
'Clear All Device Media'),
('reset-device', 'Reset Device'), (
'change-realm:dev',
'Device Realm: development'), (
'change-realm:stage',
'Device Realm: staging'), (
'change-realm:live',
'Device Realm: live')],
max_length=20,
null=True),
),
migrations.AddField(
model_name='devicescreenshot',
name='device',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.Device'),
),
]
<file_sep>/signoxe_server/settings.py
# -*- coding: utf-8 -*-
"""
Django settings for signoxe_server project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import raven
from everett.manager import (ConfigDictEnv, ConfigEnvFileEnv, ConfigIniEnv, ConfigManager,
ConfigOSEnv, ListOf, )
config = ConfigManager([
ConfigOSEnv(),
ConfigIniEnv(['config.ini',
'/etc/signoxe/server.ini']),
ConfigDictEnv({
'SECRET_KEY': '<KEY>
'DEBUG': 'false',
})
])
# Core config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ADMINS = (
('<NAME>', '<EMAIL>'),
)
DEBUG = config('DEBUG', parser=bool)
SECRET_KEY = config('SECRET_KEY')
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='', parser=ListOf(str))
# Cors config
CORS_ORIGIN_ALLOW_ALL = config('ORIGIN_ALLOW_ALL', namespace='cors', default=str(DEBUG),
parser=bool)
CORS_ORIGIN_WHITELIST = config('ORIGIN_WHITELIST', namespace='cors',
default='', parser=ListOf(str))
# Database config
DATABASES = {
'default': {
'ENGINE': config('ENGINE', namespace='database', default='django.db.backends.sqlite3'),
'NAME': config('NAME', namespace='database', default='db.sqlite3'),
'USER': config('USER', namespace='database', default=''),
'PASSWORD': config('PASSWORD', namespace='database', default=''),
'HOST': config('HOST', namespace='database', default=''),
'PORT': config('PORT', namespace='database', default=''),
}
}
# Apps config
INSTALLED_APPS = [
# Django core apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Signoxe server apps
'devicemanager',
'mediamanager',
'feedmanager',
'client_manager',
'schedule_manager',
'notification_manager',
# Django REST Framework
'rest_framework',
'rest_framework.authtoken',
'djoser',
# Sets CORS headers to permit / deny API requests from other apps
'corsheaders',
# Sentry app to report errors to Sentry
'raven.contrib.django.raven_compat',
# Django-storages to save files to s3
'storages',
# Django hosts to allow splitting app across sub-domains
'django_hosts',
# Django channels to support background tasks and async web apps like
# websockets
'channels',
# Support for tagging items
'taggit',
]
# DRF config
DRF_RENDERER_CLASSES = ('rest_framework.renderers.JSONRenderer',)
if DEBUG:
DRF_RENDERER_CLASSES += ('rest_framework.renderers.BrowsableAPIRenderer',)
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_RENDERER_CLASSES': DRF_RENDERER_CLASSES,
}
MIDDLEWARE_CLASSES = (
'django_hosts.middleware.HostsRequestMiddleware',
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_hosts.middleware.HostsResponseMiddleware',
)
ROOT_URLCONF = 'signoxe_server.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['signoxe_server/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'signoxe_server.wsgi.application'
if not DEBUG:
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Sentry config
SENTRY_KEY = config('KEY', namespace='sentry', default='')
SENTRY_SECRET = config('SECRET', namespace='sentry', default='')
SENTRY_PROJECT = config('PROJECT', namespace='sentry', default='')
if (not DEBUG
and SENTRY_KEY != ''
and SENTRY_PROJECT != ''
and SENTRY_SECRET != ''):
DSN = 'https://{key}:{secret}@app.getsentry.com/{project}'.format(
key=SENTRY_KEY,
secret=SENTRY_SECRET,
project=SENTRY_PROJECT,
)
RAVEN_CONFIG = {
'dsn': DSN,
'release': raven.fetch_git_sha(BASE_DIR),
'ignore_exceptions': ('Http404', 'django.exceptions.http.Http404',),
'environment': 'development' if DEBUG else 'production',
}
# AWS Config
AWS_HEADERS = {
'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',
'Cache-Control': 'max-age=94608000',
}
USE_S3_STORAGE = config('USE_S3_STORAGE', namespace='AWS', default='false', parser=bool)
if USE_S3_STORAGE:
AWS_STORAGE_BUCKET_NAME = config('STORAGE_BUCKET_NAME', namespace='aws')
AWS_ACCESS_KEY_ID = config('ACCESS_KEY_ID', namespace='aws')
AWS_SECRET_ACCESS_KEY = config('SECRET_ACCESS_KEY', namespace='aws')
AWS_S3_HOST = config('S3_HOST', namespace='aws')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
DEFAULT_FILE_STORAGE = 'utils.files.DedupedS3MediaStorage'
MEDIA_URL = 'https://%s/' % AWS_S3_CUSTOM_DOMAIN
else:
DEFAULT_FILE_STORAGE = 'utils.files.DedupedMediaStorage'
MEDIA_URL = config('MEDIA_URL', default='')
# Signoxe app config
SIGNOXE_THUMBNAIL_WIDTH = 320
SIGNOXE_THUMBNAIL_HEIGHT = 180
# Django hosts config
ROOT_HOSTCONF = 'signoxe_server.hosts'
DEFAULT_HOST = 'wildcard'
PARENT_HOST = config('PARENT_HOST', namespace='host', default='')
HOST_PORT = config('PORT', namespace='host', default='')
HOST_SCHEME = config('SCHEME', namespace='host', default='http' if DEBUG else 'https')
# Paths config
SERVER_ROOT = config('SERVER_ROOT', default='/srv/www/signoxe_server/')
STATIC_URL = config('STATIC_URL', default='/static/')
STATIC_ROOT = config('STATIC_ROOT', default=os.path.join(SERVER_ROOT, 'staticfiles'))
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = config('MEDIA_ROOT', default=os.path.join(SERVER_ROOT, 'media'))
# Djoser config
DJOSER = {
'DOMAIN': config('FRONTEND_DOMAIN', default='localhost:3000'),
'SITE_NAME': 'Signoxe DNB',
'PASSWORD_RESET_CONFIRM_URL': 'forgot-password/confirm/{uid}/{token}',
'SERIALIZERS': {
'user': 'client_manager.serializers.UserClientSerializer'
}
}
# Email config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
SERVER_EMAIL = config('SERVER_EMAIL', namespace='email', default='<EMAIL>')
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', namespace='email', default='<EMAIL>')
NOTIFICATION_FROM_EMAIL = config('NOTIFICATION_FROM_EMAIL', namespace='email',
default='<EMAIL>')
EMAIL_HOST = config('HOST', namespace='email', default='email-smtp.us-east-1.amazonaws.com')
EMAIL_HOST_USER = config('HOST_USER', namespace='email', default='')
EMAIL_HOST_PASSWORD = config('HOST_PASSWORD', namespace='email', default='')
EMAIL_USE_TLS = True
# Cookie config
SESSION_COOKIE_DOMAIN = config('COOKIE_DOMAIN', namespace='session', default='')
SESSION_COOKIE_SECURE = config('COOKIE_SECURE', namespace='session', parser=bool, default='false')
SESSION_COOKIE_NAME = config('COOKIE_NAME', namespace='session', default='sessionid')
# Django Channels Config
REDIS_HOST = config('HOST', namespace='redis', default='localhost')
REDIS_PORT = config('PORT', namespace='redis', default='6379', parser=int)
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgi_redis.RedisChannelLayer',
'CONFIG': {
'hosts': [(REDIS_HOST, REDIS_PORT)],
},
'ROUTING': 'signoxe_server.routing.channel_routing'
}
}
TAGGIT_CASE_INSENSITIVE = True
# Cache config
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': f'redis://{REDIS_HOST}:{REDIS_PORT}/1',
'TIMEOUT': 30 if DEBUG else 60 * 5,
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
<file_sep>/mediamanager/migrations/0005_auto_20160918_0306.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-17 21:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mediamanager', '0004_webassettemplate'),
]
operations = [
migrations.AlterModelOptions(
name='webassettemplate',
options={'verbose_name': 'Web Asset Template'},
),
migrations.AlterField(
model_name='webassettemplate',
name='variables',
field=models.CharField(
help_text='The variables present in the template that will need to be '
'filled in by the user in the frontend.',
max_length=200),
),
]
<file_sep>/schedule_manager/views.py
# -*- coding: utf-8 -*-
from django.db import transaction
from rest_framework import mixins, viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from schedule_manager.models import ScheduledContent, SpecialContent
from schedule_manager.serializers import ScheduledContentSerializer, SpecialContentSerializer
class ScheduledContentViewSet(mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
""" API ViewSet class for Scheduled Content. """
queryset = ScheduledContent.objects.all()
serializer_class = ScheduledContentSerializer
@list_route(methods=['post'])
def bulk_update(self, request):
""" Provides an API to modify multiple schedules at once. """
schedules = []
with transaction.atomic():
for entry in request.data:
schedule = ScheduledContent.objects.get(pk=entry['id'])
schedules.append(schedule)
schedule.start_time = entry['start_time']
schedule.end_time = entry['end_time']
schedule.save(validate=False)
for schedule in schedules:
schedule.clean()
serializer = self.serializer_class(schedules, many=True)
return Response(serializer.data)
class SpecialContentViewSet(mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
""" API ViewSet class for Scheduled Content. """
queryset = SpecialContent.objects.all()
serializer_class = SpecialContentSerializer
<file_sep>/devicemanager/__init__.py
# -*- coding: utf-8 -*-
default_app_config = 'devicemanager.apps.DeviceManagerConfig'
<file_sep>/mediamanager/views.py
# -*- coding: utf-8 -*-
"""
View for media manager app.
"""
from channels import Channel
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.views.decorators.clickjacking import xframe_options_exempt
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from mediamanager.models import (Asset, CalendarAsset, ContentFeed, FeedAsset, ImageAsset,
Playlist, PlaylistItem, Ticker, TickerSeries, VideoAsset,
WebAsset, WebAssetTemplate, )
from mediamanager.serializers import (AssetSerializer, CalendarSerializer, ContentFeedSerializer,
FeedSerializer, ImageSerializer, PlaylistItemSerializer,
PlaylistSerializer, TickerSerializer,
TickerSeriesSerializer, VideoSerializer,
WebAssetTemplateSerializer, WebSerializer, )
from utils.errors import NoContentAssetError
from utils.files import verify_mime
from utils.mixins import FilterByOwnerMixin, get_owner_from_request
# noinspection PyUnusedLocal
class TickerSeriesViewSet(FilterByOwnerMixin, viewsets.ModelViewSet):
""" API ViewSet class for ticker series. """
queryset = TickerSeries.objects.all()
serializer_class = TickerSeriesSerializer
@detail_route(methods=['POST'])
def clone(self, request, pk=None):
""" Creates a copy of the ticker series along with all tickers. """
ticker_series = self.get_object() # type: TickerSeries
tickers = ticker_series.ticker_set.all()
ticker_series.pk = None
ticker_series.save()
ticker_series.name = '{} ({})'.format(ticker_series.name, ticker_series.id)
ticker_series.save()
for ticker in tickers:
ticker.pk = None
ticker.ticker_series = ticker_series
ticker.save()
serializer = self.serializer_class(ticker_series)
return Response(serializer.data)
class TickerViewSet(viewsets.ModelViewSet):
""" API ViewSet class for tickers. """
queryset = Ticker.objects.all()
serializer_class = TickerSerializer
class PlaylistViewSet(FilterByOwnerMixin, viewsets.ModelViewSet):
""" API ViewSet class for playlists. """
queryset = Playlist.objects.all()
serializer_class = PlaylistSerializer
@detail_route(methods=['POST'])
def clone(self, request, pk=None):
""" Creates a copy of the ticker series along with all tickers. """
playlist = self.get_object() # type: Playlist
playlist_items = playlist.playlistitem_set.all()
# Saving original value and setting auto add feeds to false to avoid
# feeds being duplicated.
auto_add_feeds = playlist.auto_add_feeds
playlist.auto_add_feeds = False
playlist.pk = None
playlist.save()
playlist.auto_add_feeds = auto_add_feeds
playlist.name = '{} ({})'.format(playlist.name, playlist.id)
for item in playlist_items:
item.pk = None
item.playlist = playlist
item.save()
playlist.save()
serializer = self.serializer_class(playlist)
return Response(serializer.data)
class PlaylistItemViewSet(viewsets.ModelViewSet):
""" API ViewSet class for playlist items. """
queryset = PlaylistItem.objects.all()
serializer_class = PlaylistItemSerializer
class ValidateMimesOnCreateMixin:
""" A mixin to validate the mime-type of uploaded files. """
def create(self, request, *args, **kwargs):
""" While uploading a file, check if the mime type is valid, and if not, raise error. """
if not verify_mime(request.FILES[self.file_field],
supported_types=self.supported_mimes):
raise ValidationError('Invalid file type')
return super().create(request, *args, **kwargs)
class AssetViewSet(FilterByOwnerMixin, viewsets.ModelViewSet):
""" API ViewSet class for assets. """
queryset = Asset.objects.order_by('-created')
serializer_class = AssetSerializer
@detail_route(methods=['GET', 'POST', 'PUT', 'DELETE'])
def tags(self, request, pk=None):
asset = self.get_object()
if request.method == 'DELETE':
tags = request.data
if not tags:
asset.tags.clear()
elif isinstance(tags, list):
asset.tags.remove(*tags)
else:
raise ValidationError
return Response(status=status.HTTP_204_NO_CONTENT)
if request.method == 'PUT':
tags = request.data
if isinstance(tags, list):
asset.tags.set(*tags)
else:
raise ValidationError
if request.method == 'POST':
tags = request.data
if isinstance(tags, list):
asset.tags.add(*tags)
else:
raise ValidationError
return Response(asset.get_tags_list())
class ImageViewSet(FilterByOwnerMixin, ValidateMimesOnCreateMixin, viewsets.ModelViewSet):
""" API ViewSet class for image assets. """
queryset = ImageAsset.objects.all()
serializer_class = ImageSerializer
supported_mimes = ['image/png', 'image/jpeg', 'image/pjpeg']
file_field = 'media_file'
class VideoViewSet(FilterByOwnerMixin, ValidateMimesOnCreateMixin, viewsets.ModelViewSet):
""" API ViewSet class for video assets. """
queryset = VideoAsset.objects.all()
serializer_class = VideoSerializer
supported_mimes = ['video/mp4', 'video/webm']
file_field = 'media_file'
class FeedViewSet(viewsets.ModelViewSet):
""" API ViewSet class for feed assets. """
queryset = FeedAsset.objects.all()
serializer_class = FeedSerializer
def get_queryset(self):
"""
Filters the Feed assets to only list feed assets that have a feed that's published to
the currently logged in user's client.
"""
owner = get_owner_from_request(self.request)
return self.queryset.filter(feed__publish_to__in=[owner])
class WebViewSet(FilterByOwnerMixin, viewsets.ModelViewSet):
""" API ViewSet class for web assets. """
queryset = WebAsset.objects.all()
serializer_class = WebSerializer
class CalendarViewSet(FilterByOwnerMixin, viewsets.ModelViewSet):
""" API ViewSet class for calendar assets. """
queryset = CalendarAsset.objects.all()
serializer_class = CalendarSerializer
@detail_route(methods=['POST'])
def refresh(self, request, pk=None):
cal_asset_id = self.get_object().id # type: CalendarAsset
Channel('update-calendar-assets').send({'ids': [cal_asset_id]})
return Response({})
class ContentFeedViewSet(mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
""" API ViewSet class for content feeds. """
queryset = ContentFeed.objects.all()
serializer_class = ContentFeedSerializer
class WebAssetTemplateViewSet(viewsets.ReadOnlyModelViewSet):
""" API ViewSet class for web asset templates. """
queryset = WebAssetTemplate.objects.all()
serializer_class = WebAssetTemplateSerializer
def filter_by_owner(queryset, owner):
""" Helper function to filter a queryset by owner. """
if owner is not None:
return queryset.filter(owner=owner)
else:
return queryset
def asset_view(request, asset_id):
""" This view redirects to the assets's media location or web page. """
owner = get_owner_from_request(request)
try:
asset = filter_by_owner(Asset.objects, owner).get(pk=asset_id)
except Asset.DoesNotExist:
return HttpResponseNotFound()
return HttpResponseRedirect(asset.get_asset_url())
@xframe_options_exempt
def web_asset_view(request, asset_id):
""" This view renders a web asset's content page. """
# TODO: Add authentication for client devices
# owner = get_owner_from_request(request)
try:
# webasset = filter_by_owner(WebAsset.objects, owner).get(pk=asset_id)
webasset = WebAsset.objects.get(pk=asset_id)
except WebAsset.DoesNotExist:
return HttpResponseNotFound()
return HttpResponse(webasset.content)
@xframe_options_exempt
def cal_asset_view(request, asset_id):
""" This view renders a calendar asset's content page. """
# TODO: Add authentication for client devices
# owner = get_owner_from_request(request)
try:
calasset = CalendarAsset.objects.get(pk=asset_id)
except CalendarAsset.DoesNotExist:
return HttpResponseNotFound()
try:
content = calasset.rendered_content
return HttpResponse(content)
except NoContentAssetError:
return HttpResponse(status=204)
<file_sep>/devicemanager/migrations/0012_auto_20170604_1731.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-04 12:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0011_devicescreenshot_thumbnail'),
]
operations = [
migrations.AlterField(
model_name='appbuild',
name='version_code',
field=models.PositiveIntegerField(
help_text='The version of code of the Android application. This value should '
'always increase. The app build with the highest version will be '
'pushed to the devices.'),
),
]
<file_sep>/devicemanager/migrations/0003_auto_20160713_0227.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-12 20:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0002_auto_20160702_1120'),
]
operations = [
migrations.AlterField(
model_name='device',
name='enabled',
field=models.BooleanField(default=True),
),
]
<file_sep>/mediamanager/migrations/0001_squashed_0011_auto_20160807_1608.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-16 21:51
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
import utils.files
class Migration(migrations.Migration):
replaces = [('mediamanager', '0001_initial'), ('mediamanager', '0002_asset_asset_url'),
('mediamanager', '0003_asset_created'), ('mediamanager', '0004_auto_20160728_2311'),
('mediamanager', '0005_auto_20160801_0452'),
('mediamanager', '0006_auto_20160803_0344'),
('mediamanager', '0007_contentfeed_auto_created'),
('mediamanager', '0008_playlistitem_auto_add_feeds'),
('mediamanager', '0009_feedasset'), ('mediamanager', '0010_auto_20160807_0409'),
('mediamanager', '0011_auto_20160807_1608')]
initial = True
dependencies = [
('feedmanager', '0006_feed_type'),
]
operations = [
migrations.CreateModel(
name='Asset',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('name', models.CharField(max_length=255)),
('type', models.CharField(max_length=25)),
],
),
migrations.CreateModel(
name='ContentFeed',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('title', models.CharField(max_length=100)),
('image_duration', models.IntegerField(default=4500)),
('web_duration', models.IntegerField(default=4500)),
('overlay_ticker', models.BooleanField(default=True)),
],
options={
'verbose_name': 'Content Feed',
'verbose_name_plural': 'Content Feeds',
},
),
migrations.CreateModel(
name='Playlist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='PlaylistItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('position', models.PositiveIntegerField()),
('duration', models.PositiveIntegerField(blank=True, null=True)),
],
),
migrations.CreateModel(
name='Ticker',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('text', models.TextField()),
('speed', models.IntegerField(
choices=[(100, 'FASTEST'), (200, 'FASTER'), (300, 'FAST'), (400, 'NORMAL'),
(500, 'SLOW'), (600, 'SLOWER'), (700, 'SLOWEST')], default=400)),
('font_family', models.CharField(blank=True, max_length=100, null=True)),
('font_size',
models.DecimalField(blank=True, decimal_places=1, max_digits=4, null=True)),
('colour', models.CharField(blank=True, max_length=10, null=True)),
('outline', models.CharField(blank=True, max_length=10, null=True)),
('background', models.CharField(blank=True, max_length=10, null=True)),
('position', models.PositiveIntegerField()),
],
),
migrations.CreateModel(
name='TickerSeries',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('name', models.CharField(max_length=255)),
],
options={
'verbose_name': 'Ticker Series',
'verbose_name_plural': 'Ticker Series',
},
),
migrations.CreateModel(
name='ImageAsset',
fields=[
('asset_ptr', models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False, to='mediamanager.Asset')),
('media_file', models.FileField(storage=utils.files.DedupedMediaStorage(),
upload_to=utils.files.md5_file_name)),
('checksum', models.CharField(editable=False, max_length=120)),
],
options={
'abstract': False,
},
bases=('mediamanager.asset',),
),
migrations.CreateModel(
name='VideoAsset',
fields=[
('asset_ptr', models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False, to='mediamanager.Asset')),
('media_file', models.FileField(storage=utils.files.DedupedMediaStorage(),
upload_to=utils.files.md5_file_name)),
('checksum', models.CharField(editable=False, max_length=120)),
],
options={
'abstract': False,
},
bases=('mediamanager.asset',),
),
migrations.CreateModel(
name='WebAsset',
fields=[
('asset_ptr', models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False, to='mediamanager.Asset')),
('content', models.TextField(blank=True, null=True)),
('url', models.CharField(blank=True, max_length=255, null=True)),
],
options={
'verbose_name': 'Web Asset',
'verbose_name_plural': 'Web Asset',
},
bases=('mediamanager.asset',),
),
migrations.AddField(
model_name='ticker',
name='ticker_series',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.TickerSeries'),
),
migrations.AddField(
model_name='playlistitem',
name='item',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.Asset'),
),
migrations.AddField(
model_name='playlistitem',
name='playlist',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.Playlist'),
),
migrations.AddField(
model_name='playlist',
name='items',
field=models.ManyToManyField(through='mediamanager.PlaylistItem',
to='mediamanager.Asset'),
),
migrations.AddField(
model_name='contentfeed',
name='media_playlist',
field=models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.Playlist'),
),
migrations.AddField(
model_name='contentfeed',
name='ticker_series',
field=models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.TickerSeries'),
),
migrations.AddField(
model_name='asset',
name='asset_url',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='asset',
name='created',
field=models.DateTimeField(auto_now_add=True,
default=datetime.datetime(2016, 7, 21, 11, 59, 3, 477151,
tzinfo=utc)),
preserve_default=False,
),
migrations.AlterModelOptions(
name='playlistitem',
options={'ordering': ('position',)},
),
migrations.AlterField(
model_name='ticker',
name='background',
field=models.CharField(blank=True, default='#FFFFFF', max_length=10, null=True),
),
migrations.AlterField(
model_name='ticker',
name='colour',
field=models.CharField(blank=True, default='#000000', max_length=10, null=True),
),
migrations.AlterField(
model_name='ticker',
name='font_family',
field=models.CharField(blank=True, default='sans', max_length=100, null=True),
),
migrations.AlterField(
model_name='ticker',
name='font_size',
field=models.DecimalField(blank=True, decimal_places=1, default=22, max_digits=4,
null=True),
),
migrations.AlterField(
model_name='ticker',
name='outline',
field=models.CharField(blank=True, default='', max_length=10, null=True),
),
migrations.AlterModelOptions(
name='ticker',
options={'ordering': ('position',)},
),
migrations.AddField(
model_name='contentfeed',
name='auto_created',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='FeedAsset',
fields=[
('asset_ptr', models.OneToOneField(auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True, primary_key=True,
serialize=False, to='mediamanager.Asset')),
('feed', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
to='feedmanager.Feed')),
],
bases=('mediamanager.asset',),
),
migrations.AddField(
model_name='playlist',
name='auto_add_feeds',
field=models.BooleanField(default=True),
),
]
<file_sep>/README.rst
====================
Signoxe Server Setup
====================
This guide assumes that the system on which the sever is to be installed is of
the SUSE family, so either openSUSE Leap or openSUSE Tumbleweed.
Step 1: Installing required software
------------------------------------
Since this is a Python 3 project we need to install Python 3 on our system. The
``zypper`` command can be used to install packages on openSUSE systems.
.. code-block:: bash
sudo zypper install python3 python3-pip python3-virtualenv python3-devel
The following command will install basic developer tools such GCC on our system
so that we can compile software.
.. code-block:: bash
sudo zypper install -tpattern devel_basis
While not necessary, it is also nice to install PostgreSQL server so we have
the same database server as the live server installed locally for testing.
.. code-block:: bash
sudo zypper install postgresql95-server postgresql95-devel
The following a development packages that are required by some of the packages
we use.
.. code-block:: bash
sudo zypper install libffi-devel libopenssl-devel
Step 2: Downloading the project code
------------------------------------
In order to download the project code and push changes to it you need to use
git. The ``git clone`` command can be used to make a local copy of the code.
However since this is a private project you will need to authenticate yourself
each time you update the code or push changes.
There are two ways to authenticate. The first is to use your username and
password, which is easy to set up the first time, but is annoying on a long run
since you will have to enter it each time you make any remote operation on git.
The other option is to use SSH authentication, which is harder to set up
initially but once set up it doesn't need you to supply a username and password
each time.
You can find instructions for setting up SSH access in the `Bitbucket
Documentation`_. Once you have followed those instructions you can clone this
repository with the following command:
.. code-block:: bash
git clone <EMAIL>:signoxe/signoxe-server.git
Step 3: Creating a virtual environment for our project
------------------------------------------------------
Generally while working on Python projects we should use a virtual Python
environment called a virtualenv. Using a virtualenv allows us to install
whatever packages our project requires without installing them globally and
interfering with the main system.
To manage virtualenvs we will install a Python package called ``pew``. Python
packages are installed using the ``pip`` command. If both Python 2 and Python 3
are installed -- which is usually the case -- you should use ``pip2`` to
install packages for Python 2 and ``pip3`` to install packages for Python 3.
Now let's install pew.
.. code-block:: bash
pip3 install --user --upgrade pew
We used ``--user`` to install the package just for the current user, not the
whole system, and we used ``--upgrade`` to upgrade the package if it's already
installed.
Now we'll create a new virtual environment for our project using pew. Enter the
directory where you have cloned the project and run the following command. Change
Working directory to that of signoxe-server ``cd signoxe-server``:
.. code-block:: bash
pew new -r requirements-dev.pip -a . signoxe-server
In the above command ``pew new`` creates a new virtualenv; the
``-r requirements-dev.pip`` tell it that it should install all the software listed
in the requirements-dev.pip file; the ``-a .`` tells pew that we want to use the
current directory as the project directory; and finally ``signoxe-server`` is the
name we are giving this virtualenv.
To install some of the dependencies like jpeg library (if the above command shows
an error) , install them using
.. code-block:: bash
sudo zypper install libjpeg8-devel
Now whenever you want to work on the project you can just type
``pew workon signoxe-server`` and it will go to your project directory and set up
its virtual environment.
Step 4: Running the project
---------------------------
Django projects can be run using the ``manage.py runserver`` command. After
activating the project's virtual environment using pew, you can start the
project server as follows:
.. code-block:: bash
python manage.py runserver 0:4000
The ``0:4000`` here will tell the server to listen on all addresses and on port
4000. This way you can access the server on any computer on the same network.
If you leave out ``0:4000`` the default port will be 8000 and the server will
only be available at ``localhost:4000``. A simpler way to run the command is to
issue ``make run`` in the project directory, that has the same effect. You can
now access the site at http://localhost:4000 or http://127.0.0.1:4000 etc.
As you modify the project code, this development server will automatically pick
up the changes and restart.
.. _Bitbucket Documentation: https://confluence.atlassian.com/bitbucket/set-up-ssh-for-git-728138079.html
<file_sep>/devicemanager/admin.py
# -*- coding: utf-8 -*-
""" Admin setup for device manager app. """
from django.contrib import admin
from devicemanager.models import (AppBuild, AppBuildChannel, Device, DeviceGroup, DeviceScreenShot,
MirrorServer, )
@admin.register(Device)
class DeviceAdmin(admin.ModelAdmin):
""" The device admin panel setup class. """
list_display = ('name', 'device_id', 'last_ping', 'group', 'debug_mode', 'enabled', 'owner',
'build_version',)
list_filter = ('last_ping', 'group', 'debug_mode', 'enabled', 'owner', 'build_version',)
list_editable = ('debug_mode', 'enabled',)
fields = (
'device_id', 'name', 'group', 'last_ping',
('debug_mode', 'enabled',),
'command',
'owner', 'build_version'
)
readonly_fields = ('device_id', 'last_ping', 'build_version')
@admin.register(DeviceGroup)
class DeviceGroupAdmin(admin.ModelAdmin):
""" The device group admin panel setup class. """
list_display = ('name', 'owner', 'display_date_time', 'mirror', 'orientation')
list_filter = ('owner', 'orientation')
@admin.register(AppBuild)
class AppBuildAdmin(admin.ModelAdmin):
""" The AppBuild admin panel setup class. """
list_display = ('__str__', 'version_code', 'release_channel')
@admin.register(MirrorServer)
class MirrorServerAdmin(admin.ModelAdmin):
list_display = ('name', 'mirror_id', 'address', 'last_ping', 'owner',)
list_filter = ('owner',)
readonly_fields = ('mirror_id', 'last_ping',)
@admin.register(DeviceScreenShot)
class DeviceScreenShotAdmin(admin.ModelAdmin):
list_display = ('__str__', 'device', 'timestamp')
list_filter = ('device', 'timestamp', 'device__owner')
readonly_fields = ('timestamp',)
admin.site.register(AppBuildChannel)
<file_sep>/feedmanager/migrations/0004_auto_20160909_2257.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-09 17:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feedmanager', '0003_template_duration'),
]
operations = [
migrations.AlterField(
model_name='template',
name='duration',
field=models.PositiveIntegerField(
default=10000,
help_text='How long should a slide using this template be visible on '
'screen. <br/>If a template has an animation this time should '
'ensure that the animation has enough time to complete. '),
),
]
<file_sep>/signoxe_server/urls/admin.py
# -*- coding: utf-8 -*-
""" URL routing configuration for the admin domain. """
from django.conf.urls import include, url
from django.contrib import admin
import client_manager.urls
import feedmanager.admin_urls
from signoxe_server.system_info import system_info
admin.site.site_header = 'Signoxe Administration'
admin.site.site_title = 'Signoxe admin panel'
urlpatterns = [
url(r'^', admin.site.urls),
url(r'^sys-info/', system_info),
url(r'^', include(client_manager.urls)),
url(r'^', include(feedmanager.admin_urls)),
]
<file_sep>/feedmanager/migrations/0007_auto_20170110_0200.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-09 20:30
from __future__ import unicode_literals
from django.db import migrations, models
import utils.files
class Migration(migrations.Migration):
dependencies = [
('feedmanager', '0006_merge_20160929_1831'),
]
operations = [
migrations.AlterField(
model_name='imagesnippet',
name='media',
field=models.FileField(
help_text='This is the media file that will be served in the feed directly.',
upload_to=utils.files.md5_file_name),
),
migrations.AlterField(
model_name='videosnippet',
name='media',
field=models.FileField(
help_text='This is the media file that will be served in the feed directly.',
upload_to=utils.files.md5_file_name),
),
]
<file_sep>/mediamanager/admin.py
# -*- coding: utf-8 -*-
""" Admin setup for media manager app. """
from django.contrib import admin
from django.db import models
from mediamanager.models import (CalendarAsset, ContentFeed, ImageAsset, Playlist, PlaylistItem,
Ticker, TickerSeries, VideoAsset, WebAsset, WebAssetTemplate, )
from mediamanager.widgets import AceEditorWidget
from utils.mixins import AutoAddOwnerAdminMixin
@admin.register(ImageAsset)
@admin.register(VideoAsset)
class FileAssetAdmin(AutoAddOwnerAdminMixin, admin.ModelAdmin):
""" Admin panel setup class for file-based assets. """
fields = ('name', 'media_file', 'owner',)
list_display = ('name', 'created', 'owner',)
list_filter = ('created', 'owner',)
@admin.register(WebAsset)
class WebAssetAdmin(AutoAddOwnerAdminMixin, admin.ModelAdmin):
""" Admin panel setup class for web assets. """
fields = ('name', 'url', 'content', 'owner',)
list_display = ('name', 'created', 'owner',)
list_filter = ('created', 'owner',)
formfield_overrides = {
models.TextField: {'widget': AceEditorWidget}
}
class TickerInlineAdmin(admin.StackedInline):
""" Inline admin config class for tickers. """
model = Ticker
@admin.register(TickerSeries)
class TickerSeriesAdmin(AutoAddOwnerAdminMixin, admin.ModelAdmin):
""" Admin panel setup class for ticker series. """
inlines = (TickerInlineAdmin,)
list_display = ('name', 'owner', 'ticker_count')
list_filter = ('owner',)
@staticmethod
def ticker_count(obj):
""" Returns the number of tickers in the ticker set, for display in the admin panel """
return obj.ticker_set.count()
class PlaylistItemInlineAdmin(admin.StackedInline):
""" Inline admin config class for playlist itens. """
model = PlaylistItem
@admin.register(Playlist)
class PlaylistAdmin(AutoAddOwnerAdminMixin, admin.ModelAdmin):
""" Admin panel setup class for playlists. """
inlines = (PlaylistItemInlineAdmin,)
list_display = ('name', 'auto_add_feeds', 'owner',)
list_filter = ('owner',)
@admin.register(WebAssetTemplate)
class WebAssetTemplateAdmin(admin.ModelAdmin):
"""
Admin panel setup class for web asset templates.
This class simply overrides the widget used by the template to use out AceEditorWidget
"""
list_display = ('name', 'calendar_support', 'data_support')
list_filter = ('calendar_support', 'data_support')
formfield_overrides = {
models.TextField: {'widget': AceEditorWidget}
}
admin.site.register(ContentFeed)
admin.site.register(CalendarAsset)
<file_sep>/tests/test_api_access.py
# -*- coding: utf-8 -*-
from pytest_bdd import given, scenarios, then
from rest_framework.test import APIClient
scenarios('features/api_access.feature')
@given('I request an auth token')
def api_client(user_object):
client = APIClient()
response = client.post('/api/auth/token/create/', {'username': user_object.username,
'password': '<PASSWORD>'})
assert response.status_code == 200, 'Login Failed'
token = response.json()['auth_token']
assert len(token) == 40, 'Invalid token'
client.credentials(HTTP_AUTHORIZATION='Token {}'.format(token))
return client
@then('I should be able to access my profile API')
def access_profile_page(api_client):
response = api_client.get('/api/auth/me/')
assert response.status_code == 200, 'Failed to access profile page'
@then('I should be able to access the API <api>')
def access_api(api_client, api):
response = api_client.get('/api/{}/'.format(api))
assert response.status_code == 200, 'Failed to access api {}'.format(api)
<file_sep>/mediamanager/serializers.py
# -*- coding: utf-8 -*-
""" Serializers for the media manager app. """
from django.db.models import F
from rest_framework import serializers
from mediamanager.models import (Asset, CalendarAsset, ContentFeed, ImageAsset, Playlist,
PlaylistItem, Ticker, TickerSeries, VideoAsset, WebAsset,
WebAssetTemplate, )
from utils.mixins import AutoAddOwnerOnCreateMixin
class TickerSerializer(serializers.ModelSerializer):
""" Serializer for tickers. """
position = serializers.IntegerField(required=False)
class Meta:
""" Meta class for :class:TickerSerializer """
model = Ticker
fields = (
'id', 'position', 'text', 'colour', 'ticker_series',
'font_size', 'font_family', 'outline', 'background',
'speed',
)
class TickerSeriesSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for ticker series. """
tickers = TickerSerializer(many=True, source='ticker_set', required=False)
owner = serializers.Field(required=False, write_only=True)
class Meta:
""" Meta class for :class:TickerSeriesSerializer """
model = TickerSeries
fields = ('id', 'name', 'tickers', 'owner',)
depth = 1
class ImageSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for image assets. """
owner = serializers.Field(required=False, write_only=True)
metadata = serializers.ReadOnlyField(source='get_metadata_as_dict')
full_metadata = serializers.ReadOnlyField(source='get_raw_metadata_as_dict')
class Meta:
""" Meta class for :class:ImageSerializer """
model = ImageAsset
fields = ('id', 'name', 'type', 'asset_url', 'media_file', 'thumbnail',
'owner', 'metadata', 'full_metadata')
read_only_fields = ('asset_url', 'thumbnail', 'type', 'metadata', 'full_metadata')
class VideoSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for video assets. """
owner = serializers.Field(required=False, write_only=True)
metadata = serializers.ReadOnlyField(source='get_metadata_as_dict')
full_metadata = serializers.ReadOnlyField(source='get_raw_metadata_as_dict')
class Meta:
""" Meta class for :class:VideoSerializer """
model = VideoAsset
fields = ('id', 'name', 'type', 'asset_url', 'media_file', 'thumbnail',
'owner', 'metadata', 'full_metadata')
read_only_fields = ('asset_url', 'thumbnail', 'type', 'metadata', 'full_metadata')
class WebSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for web assets. """
owner = serializers.Field(required=False, write_only=True)
class Meta:
""" Meta class for :class:WebSerializer """
model = WebAsset
fields = ('id', 'name', 'asset_url', 'content', 'url', 'owner',)
read_only_fields = ('asset_url',)
class CalendarSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for calendar assets. """
owner = serializers.Field(required=False, write_only=True)
class Meta:
""" Meta class for :class:CalendarSerializer """
model = CalendarAsset
fields = ('id', 'name', 'asset_url', 'url', 'template', 'owner',)
read_only_fields = ('asset_url',)
class AssetSerializer(serializers.ModelSerializer):
""" Serializer for assets. """
metadata = serializers.ReadOnlyField(source='get_metadata_as_dict')
full_metadata = serializers.ReadOnlyField(source='get_raw_metadata_as_dict')
tags = serializers.ReadOnlyField(source='get_tags_list')
class Meta:
""" Meta class for :class:AssetSerializer """
model = Asset
fields = (
'id', 'name', 'type', 'thumbnail', 'asset_url', 'metadata', 'full_metadata', 'tags')
read_only_fields = (
'asset_url', 'type', 'thumbnail', 'metadata', 'full_metadata', 'tags')
class FeedSerializer(serializers.ModelSerializer):
""" Serializer for feed assets. """
class Meta:
""" Meta class for :class:FeedSerializer """
model = Asset
fields = ('id', 'name', 'type', 'asset_url',)
read_only_fields = ('asset_url', 'type')
class PlaylistItemSerializer(serializers.ModelSerializer):
""" Serializer for playlist items. """
position = serializers.IntegerField(required=False)
def create(self, validated_data):
"""
Handles the special case where a new playlist item is to be added to beginning, which
requires shifting all other items.
"""
position = validated_data.get('position', None)
playlist = validated_data.get('playlist')
if position is not None and position == -1:
PlaylistItem.objects.filter(playlist=playlist).update(position=F('position') + 1)
validated_data['position'] = 0
return super().create(validated_data)
class Meta:
""" Meta class for :class:PlaylistItemSerializer """
model = PlaylistItem
fields = ('id', 'position', 'item', 'duration', 'playlist', 'expire_on', 'enabled')
class PlaylistItemSerializerForPlaylist(serializers.ModelSerializer):
""" Serializer for playlist items inside a playlist. """
id = serializers.IntegerField()
playlist = serializers.IntegerField(source='playlist_id', read_only=True)
item = AssetSerializer()
class Meta:
""" Meta class for :class:PlaylistItemSerializerForPlaylist """
model = PlaylistItem
fields = ('id', 'position', 'item', 'duration', 'playlist', 'expire_on', 'enabled')
class PlaylistSerializer(AutoAddOwnerOnCreateMixin, serializers.ModelSerializer):
""" Serializer for playlists. """
#: Need a custom serializer for items here, to avoid issues while performing updates.
items = PlaylistItemSerializerForPlaylist(source='playlistitem_set',
many=True,
read_only=False,
required=False)
owner = serializers.Field(required=False, write_only=True)
def update(self, instance, validated_data: dict):
""" Handles updates for playlist API. """
playlist_items = validated_data.pop('playlistitem_set', [])
for item in playlist_items:
# Update the position of items in the playlist. Since this the playlist endpoint, this
# is the only kind of update we will allow, not updates to other fields.
PlaylistItem.objects.filter(id=item.get('id')).update(position=item.get('position'))
if 'name' in validated_data:
instance.name = validated_data.get('name')
instance.save()
if 'auto_add_feeds' in validated_data:
instance.auto_add_feeds = validated_data.get('auto_add_feeds')
instance.save()
return instance
class Meta:
""" Meta class for :class:PlaylistSerializer """
model = Playlist
fields = ('id', 'name', 'items', 'owner', 'auto_add_feeds',)
class ContentFeedSerializer(serializers.ModelSerializer):
""" Serializer for content feed """
class Meta:
""" Meta class for :class:ConteFeedSerializer """
model = ContentFeed
fields = ('id', 'title', 'media_playlist', 'ticker_series',
'image_duration', 'web_duration', 'overlay_ticker',)
class WebAssetTemplateSerializer(serializers.ModelSerializer):
""" Serializer for web asset templates. """
class Meta:
""" Meta class for :class:WebAssetTemplateSerializer """
model = WebAssetTemplate
fields = ('id', 'name', 'template', 'variables', 'calendar_support', 'data_support',
'help_html')
<file_sep>/utils/errors.py
# -*- coding: utf-8 -*-
"""Contains common errors for the application"""
class SignoxeBaseError(Exception):
"""Base error class for our application"""
pass
class AssetError(SignoxeBaseError):
"""Base class for all asset-related errors"""
pass
class InvalidAssetError(AssetError):
"""
Error for cases when an asset is invalid. For instance a calendar asset that has no calendar
data.
"""
pass
class NoContentAssetError(AssetError):
"""
Error for cases when an asset has no content currently. For instance a feed asset that has
no snippet for today, or a calendar asset with with data for the current time.
"""
pass
<file_sep>/feedmanager/apps.py
# -*- coding: utf-8 -*-
""" Feed manager app config. """
from django.apps import AppConfig
class FeedManagerConfig(AppConfig):
""" Feed manager app config class. """
name = 'feedmanager'
verbose_name = 'Feed Manager'
<file_sep>/devicemanager/apps.py
# -*- coding: utf-8 -*-
""" Device manager app config. """
from django.apps import AppConfig
class DeviceManagerConfig(AppConfig):
""" Device manager app config class. """
name = 'devicemanager'
verbose_name = 'Device Manager'
<file_sep>/client_manager/migrations/0013_features.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-18 20:21
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0012_auto_20170618_1816'),
]
operations = [
migrations.CreateModel(
name='Features',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('screenshots', models.BooleanField(default=False,
help_text='Enables or disable the screenshot feature for the client.')),
('smart_notice_board', models.BooleanField(default=False,
help_text='Enabled or disables smart notice board support. This includes support for the Windows client with idle detection, scheduled launching, and push messaging.')),
('client', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
related_name='features',
to='client_manager.Client')),
],
),
]
<file_sep>/client_manager/admin.py
# -*- coding: utf-8 -*-
""" Admin configuration for client manager app. """
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.html import format_html
from django_hosts import reverse
from client_manager.models import (Client, ClientSettings, ClientSubscriptionData,
ClientUserProfile, Features, )
class ClientUserProfileAdminInline(admin.StackedInline):
"""
This inline admin config allow a user to associate a client with a user from the backend panel
"""
model = ClientUserProfile
can_delete = False
def user_login_link(obj):
link = reverse('login-as-view', args=[str(obj.pk)], host='admin')
return format_html('<a href="{link}" target="_blank">'
'View frontend as {username}'
'</a>'.format(link=link, username=obj.username))
class AppUserAdmin(UserAdmin):
"""
This admin class extends the user admin setup to include the client user profile as a
configurable option.
"""
inlines = (ClientUserProfileAdminInline,)
list_display = ('username', user_login_link, 'email', 'first_name', 'last_name', 'is_staff')
class ClientSubscriptionDataAdminInline(admin.StackedInline):
"""Inline admin config for Client Subscription data."""
model = ClientSubscriptionData
can_delete = False
class ClientSettingsAdminInline(admin.StackedInline):
"""Inline admin config for Client Settings."""
model = ClientSettings
can_delete = False
class FeaturesAdminInline(admin.StackedInline):
"""Inline admin config for Client Features."""
model = Features
can_delete = False
@admin.register(Client)
class ClientAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('name', 'app_build_channel'),
}),
('Logo', {
'fields': (('logo',), ('display_device_logo', 'device_logo',), ('update_interval',))
}),
('Profile', {
'fields': (
('organisation_name', 'organisation_address',),
('primary_contact_name', 'primary_contact_email', 'primary_contact_phone',),
('technical_contact_name', 'technical_contact_email', 'technical_contact_phone',),
('financial_contact_name', 'financial_contact_email', 'financial_contact_phone',),
),
})
)
inlines = (ClientSubscriptionDataAdminInline, ClientSettingsAdminInline, FeaturesAdminInline)
# The user model is already registered, we need to un-register it before we can register our own
# custom user admin class
admin.site.unregister(User)
admin.site.register(User, AppUserAdmin)
<file_sep>/devicemanager/migrations/0010_auto_20170511_1549.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-11 10:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0009_auto_20170509_1529'),
]
operations = [
migrations.AlterField(
model_name='device',
name='command',
field=models.CharField(blank=True, choices=[('reboot', 'Reboot Device'),
('free-space', 'Delete Unused Media'),
('clear-media',
'Clear All Device Media'),
('reset-device', 'Reset Device'),
('change-realm:dev',
'Device Realm: development'),
('change-realm:stage',
'Device Realm: staging'),
('change-realm:live',
'Device Realm: live'),
('screenshot', 'Take screenshot'),
('screenshot:burst',
'Take screenshot burst')],
max_length=20, null=True),
),
]
<file_sep>/signoxe_server/system_info.py
# -*- coding: utf-8 -*-
"""
Contains a view function to display basic system information.
"""
import subprocess
import sys
import django
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
git_hash = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])
formatted_settings = '\n'.join(
'{} = {}'.format(setting, getattr(settings, setting))
for setting in filter(lambda s: s[0].isupper(), dir(settings))
)
@staff_member_required
def system_info(request):
"""
This view displays a simple HTML page that displays system information such as the Python
version, the Django version, the version of the server, and whether the app is running in
production mode.
"""
message = """<html>
<head><title>Server Information</title></head>
<table>
<tr><td>Python version:</td><td>{python_version}</td></tr>
<tr><td>Django version:</td><td>{django_version}</td></tr>
<tr>
<td>Signoxe version:</td>
<td>
<a href='https://bitbucket.org/signoxe/signoxe-server/commits/{signoxe_version}'>
{signoxe_version}
</a>
</td>
</tr>
<tr><td>Production mode:</td><td>{is_production}</td></tr>
</table>
<p>Settings:</p>
<pre>{settings}</pre>
</html>
""".format(
python_version=sys.version,
django_version=django.get_version(),
signoxe_version=git_hash.decode(),
is_production=not settings.DEBUG,
settings=formatted_settings
)
return HttpResponse(message)
<file_sep>/client_manager/migrations/0004_auto_20170114_1732.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-14 12:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0003_auto_20170114_1730'),
]
operations = [
migrations.AlterField(
model_name='client',
name='device_logo',
field=models.ImageField(blank=True,
help_text='A logo of the client for use on the device. If no device logo is provided, the main logo will be used.',
null=True, upload_to=''),
),
migrations.AlterField(
model_name='client',
name='display_device_logo',
field=models.BooleanField(default=True,
help_text='Whether a logo should be shown on the device or not.'),
),
]
<file_sep>/devicemanager/migrations/0005_auto_20170110_0200.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-09 20:30
from __future__ import unicode_literals
import storages.backends.s3boto
from django.db import migrations, models
import devicemanager.models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0004_auto_20160919_0037'),
]
operations = [
migrations.AddField(
model_name='devicegroup',
name='display_date_time',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='appbuild',
name='app_build',
field=models.FileField(help_text='The app APK file.',
storage=storages.backends.s3boto.S3BotoStorage(),
upload_to=devicemanager.models.build_upload_location),
),
]
<file_sep>/schedule_manager/migrations/0002_auto_20170305_0251.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-04 21:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedule_manager', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='scheduledcontent',
options={'ordering': ('-default', 'start_time'),
'verbose_name': 'Scheduled Content',
'verbose_name_plural': 'Scheduled Content'},
),
migrations.AlterModelOptions(
name='specialcontent',
options={'ordering': ('date',), 'verbose_name_plural': 'Special Content'},
),
migrations.AlterField(
model_name='scheduledcontent',
name='default',
field=models.BooleanField(default=False),
),
]
<file_sep>/mediamanager/models.py
# -*- coding: utf-8 -*-
""" Models for the media manager app. """
import datetime
import json
from pathlib import Path
from subprocess import CalledProcessError
from uuid import uuid4
import hashlib
import os
import re
import requests
from channels import Channel
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.db.models.signals import post_save
from django.template import Context, Template
from django.utils import timezone
from django.utils.text import Truncator
from django_hosts.resolvers import reverse
from icalendar import Calendar
from mistune import markdown
from raven.contrib.django.raven_compat.models import client
from taggit.managers import TaggableManager
from client_manager.models import Client
from mediamanager.types import AssetTypes
from utils.errors import InvalidAssetError, NoContentAssetError
from utils.files import (clean_image_metadata, clean_video_metadata, generate_image_thumbnail,
generate_video_thumbnail, generate_web_thumbnail, md5_file_name)
from utils.storage import NormalStorage
THUMBNAIL_STORAGE = NormalStorage()
class TickerSpeeds:
""" This class consolidates the data about ticker speed choices into a single class. """
FASTEST = 100
FASTER = 200
FAST = 300
NORMAL = 400
SLOW = 500
SLOWER = 600
SLOWEST = 700
#: Choices that a Django field can use.
CHOICES = (
(FASTEST, 'FASTEST'),
(FASTER, 'FASTER'),
(FAST, 'FAST'),
(NORMAL, 'NORMAL'),
(SLOW, 'SLOW'),
(SLOWER, 'SLOWER'),
(SLOWEST, 'SLOWEST'),
)
class TickerSeries(models.Model):
"""
This model represents a ticker series. A ticker series is a collection of tickers ordered by
position.
"""
name = models.CharField(max_length=255)
owner = models.ForeignKey(Client, null=True, blank=True, on_delete=models.SET_NULL)
def __str__(self):
return self.name
def as_list(self):
"""
Returns this tickers in this ticker series as a pure python list ordered by their
position.
"""
return [ticker.as_dict() for ticker in self.ticker_set.order_by('position')]
class Meta:
verbose_name = 'Ticker Series'
verbose_name_plural = 'Ticker Series'
class Ticker(models.Model):
"""
Represents a single ticker in a ticker series.
"""
text = models.TextField()
speed = models.IntegerField(
choices=TickerSpeeds.CHOICES,
default=TickerSpeeds.NORMAL)
font_family = models.CharField(
default='sans',
max_length=100,
null=True,
blank=True)
font_size = models.DecimalField(
default=22,
max_digits=4,
decimal_places=1,
null=True,
blank=True)
colour = models.CharField(
default='#000000',
max_length=10,
null=True,
blank=True)
outline = models.CharField(
default='',
max_length=10,
null=True,
blank=True)
background = models.CharField(
default='#FFFFFF',
max_length=10,
null=True,
blank=True)
position = models.PositiveIntegerField()
ticker_series = models.ForeignKey(TickerSeries)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
""" Adds extra logic to add a position for a ticker when it is newly added. """
if self.position is None:
# Get the ticker with the largest position value. This works
# because tickers are already ordered by position.
last_ticker = self.ticker_series.ticker_set.last()
if last_ticker is None:
self.position = 0 # No tickers in the series yet, set position to 0.
else:
self.position = last_ticker.position + 1
super().save(force_insert, force_update, using, update_fields)
def __str__(self):
return Truncator(self.text).words(10)
def as_dict(self):
"""
Returns a dictionary representation of this ticker so it can be included as-in in a feed.
"""
return {
'text': self.text,
'speed': self.speed,
'fontfamily': self.font_family,
'fontsize': self.font_size,
'color': self.colour,
'outline': self.outline,
'background': self.background,
}
class Meta:
ordering = ('position',)
class Asset(models.Model):
"""
This models servers as a base for all kinds of assets and includes data common to all assets. s
"""
name = models.CharField(max_length=255)
type = models.CharField(max_length=25, editable=False)
raw_metadata = models.TextField(editable=False, blank=True)
metadata = models.TextField(editable=False, blank=True)
asset_url = models.CharField(max_length=255, editable=False)
thumbnail = models.CharField(max_length=255, null=True, blank=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(Client, null=True, blank=True, on_delete=models.SET_NULL)
tags = TaggableManager()
def get_tags_list(self):
return self.tags.names()
def build_clean_metadata(self):
if self.type == AssetTypes.VIDEO:
self.metadata = clean_video_metadata(self.get_raw_metadata_as_dict())
elif self.type == AssetTypes.IMAGE:
self.metadata = clean_image_metadata(self.get_raw_metadata_as_dict())
def get_metadata_as_dict(self):
if self.metadata is None or self.metadata == '':
return None
return json.loads(self.metadata)
def get_raw_metadata_as_dict(self):
if self.raw_metadata is None or self.raw_metadata == '':
return None
return json.loads(self.raw_metadata)
def get_subtype(self):
"""
Uses the stored type to figure out the type of the asset and accordingly returns the
associated child class.
"""
if self.type == AssetTypes.VIDEO:
return self.videoasset
elif self.type == AssetTypes.IMAGE:
return self.imageasset
elif self.type == AssetTypes.WEB:
return self.webasset
elif self.type == AssetTypes.FEED:
return self.feedasset
elif self.type == AssetTypes.CALENDAR:
return self.calendarasset
else:
raise ValueError
def get_absolute_url(self):
""" Returns a friendly url for this asset. """
return reverse('asset-view', args=[str(self.pk)], host='content')
def get_asset_url(self):
"""
Returns a direct url for this asset. It also caches the url into a field in the model.
"""
self._save_asset_url()
return self.asset_url
def as_dict(self):
return self.get_subtype().as_dict()
def _save_asset_url(self, force=False):
"""
Save the asset url to the field in the model so it doesn't need to be calculated each time.
"""
if force or not self.asset_url:
self.asset_url = self.get_subtype().get_asset_url()
self.save()
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
""" Adds logic to save the asset URL while saving if one is not already present. """
super().save(force_insert, force_update, using, update_fields)
self._save_asset_url()
def __str__(self):
return self.name
def add_thumbnail(self, force):
if self.thumbnail is None or force:
try:
self._get_or_generate_thumbnail(force=force)
self.save()
except CalledProcessError:
client.captureException()
def _get_or_generate_thumbnail(self, force=False):
storage = THUMBNAIL_STORAGE
if self.thumbnail is None:
thumbnail_path = self._get_thumbnail_path()
else:
thumbnail_path = str(Path(self.thumbnail).relative_to(storage.url('/')))
if force or not storage.exists(thumbnail_path): # Thumbnail doesn't exist, generate it.
thumbnail = self.generate_thumbnail()
storage.save(thumbnail_path, thumbnail)
self.thumbnail = storage.url(thumbnail_path)
return storage.url(thumbnail_path)
def _get_thumbnail_path(self):
raise NotImplementedError()
def generate_thumbnail(self):
""" Thumbnails can only be generated for specific types of assets """
raise NotImplementedError
class FileAsset(Asset):
"""
This model serves as a base for all file-based assets such as a images and videos. It is an
abstract includes data common to file-based assets.
"""
media_file = models.FileField(upload_to=md5_file_name, )
checksum = models.CharField(max_length=120, editable=False)
def _get_thumbnail_path(self):
# This gets the filename and path within the media folder.
_, filename_with_ext = os.path.split(self.media_file.name)
filename, ext = os.path.splitext(filename_with_ext)
# The thumbnail name is simply tn_ prepended to the hashed file name.
thumbnail_name = '{}.jpeg'.format(filename)
# The thumbnail is stored it the same path.
thumbnail_path = os.path.join('thumbnails', self.type.lower(), thumbnail_name)
return thumbnail_path
def generate_thumbnail(self):
""" Generates the correct thumbnail for asset type and returns thumbnail image data. """
return self.get_subtype().generate_thumbnail()
def save(self, *args, **kwargs):
"""
Adds logic to save the type of the model for the field so no unnecessary lookups are
required while accessing a child model from the Asset model.
"""
if hasattr(self, 'TYPE'):
self.type = self.TYPE
if not self.pk:
# If this is a newly-created asset, here we calculate the md5 hash for the file and
# store it in the checksum field
md5 = hashlib.md5()
for chunk in self.media_file.chunks():
md5.update(chunk)
self.checksum = md5.hexdigest()
super().save(*args, **kwargs)
def get_asset_url(self):
""" Returns the direct URL for the file associated with this asset. """
return self.media_file.url
class Meta:
abstract = True
class VideoAsset(FileAsset):
""" This model represents a Video Asset. """
TYPE = AssetTypes.VIDEO
def generate_thumbnail(self):
""" Generates thumbnail for video asset and returns thumbnail image data. """
return generate_video_thumbnail(source=self.media_file.url,
width=settings.SIGNOXE_THUMBNAIL_WIDTH,
height=settings.SIGNOXE_THUMBNAIL_HEIGHT)
def as_dict(self):
""" Returns a dictionary representation of this video asset. """
return {
'url': self.media_file.url,
'checksum': self.checksum,
'type': 'video',
}
class ImageAsset(FileAsset):
""" This model represents an Image Asset. """
TYPE = AssetTypes.IMAGE
def generate_thumbnail(self):
""" Generates thumbnail for image asset and returns thumbnail image data. """
return generate_image_thumbnail(source=self.media_file,
width=settings.SIGNOXE_THUMBNAIL_WIDTH,
height=settings.SIGNOXE_THUMBNAIL_HEIGHT)
def as_dict(self):
""" Returns a dictionary representation of this image asset. """
return {
'url': self.media_file.url,
'checksum': self.checksum,
'type': 'image',
}
class WebAsset(Asset):
""" This model represents a Web Asset. """
TYPE = AssetTypes.WEB
content = models.TextField(null=True, blank=True)
url = models.CharField(max_length=255, null=True, blank=True)
def _get_thumbnail_path(self):
return 'thumbnails/web/tn_wa{}-{}.jpeg'.format(self.id, uuid4().hex)
def generate_thumbnail(self):
""" Generates thumbnail for web asset and returns thumbnail image data. """
return generate_web_thumbnail(source=self.get_asset_url(),
width=settings.SIGNOXE_THUMBNAIL_WIDTH,
height=settings.SIGNOXE_THUMBNAIL_HEIGHT)
def clean(self):
"""
Validates that a web asset includes at least one, and only one of the fields between url
and content.
"""
if not self.url and not self.content:
raise ValidationError('Web Asset must include at least one of "url" and "content"')
def save(self, *args, **kwargs):
""" Adds the extra logic of setting the type while saving the model. """
if hasattr(self, 'TYPE'):
self.type = self.TYPE
super().save(*args, **kwargs)
def get_asset_url(self):
""" Returns the asset's url field or the content rendered in the page. """
if self.url:
return self.url
else:
return reverse('webasset-view', args=[self.pk], host='content')
@property
def checksum(self):
"""Calculates checksum for Web asset based on content."""
md5 = hashlib.md5()
md5.update(self.content.encode('utf-8'))
return md5.hexdigest()
def as_dict(self):
""" Returns a dictionary representation of this web asset. """
return {
'url': self.get_asset_url(),
'checksum': self.checksum,
'type': 'web',
}
class Meta:
verbose_name = 'Web Asset'
verbose_name_plural = 'Web Asset'
class FeedAsset(Asset):
"""
This model represents a Feed Asset.
A FeedAsset behaves like a regular asset while being linked to a feed model which provides its
content.
"""
TYPE = AssetTypes.FEED
feed = models.OneToOneField('feedmanager.Feed')
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
"""
Adds the type while saving. Also sets owner to None since FeedAssets
are managed by the main site.
"""
if hasattr(self, 'TYPE'):
self.type = self.TYPE
self.owner = None
super().save(force_insert, force_update, using, update_fields)
def get_asset_url(self):
""" Returns the url to the asset linked to this feed. """
return self.feed.get_absolute_url()
def as_dict(self):
""" Returns a dictionary representation of this asset. """
return self.feed.as_dict()
class PlaylistItem(models.Model):
"""
This model represents a Playlist Item.
A PlaylistItem adds playlist-related metadata to an asset, such as the duration (unless the
asset has an explicit duration, like a video), and a position in the playlist.
"""
position = models.PositiveIntegerField()
playlist = models.ForeignKey('Playlist')
item = models.ForeignKey(Asset)
duration = models.PositiveIntegerField(null=True, blank=True)
expire_on = models.DateTimeField(null=True, blank=True)
@property
def enabled(self):
return self.expire_on is None or timezone.now() < self.expire_on
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
""" Adds logic to add a position to the playlistitem, unless one is already provided. """
if self.position is None:
# For new playlists there won't be an existing position, in that case set the position
# to 0 if it's the only item in the playlist, or set one more than the largest position
# value.
last_item = self.playlist.playlistitem_set.last()
if last_item is None:
self.position = 0
else:
self.position = last_item.position + 1
super().save(force_insert, force_update, using, update_fields)
def __str__(self):
return '({position}) {item} in {playlist}'.format(position=self.position,
item=self.item,
playlist=self.playlist)
class Meta:
ordering = ('position',)
class Playlist(models.Model):
"""
This model represents a Playlist.
"""
name = models.CharField(max_length=255)
items = models.ManyToManyField(Asset, through=PlaylistItem)
auto_add_feeds = models.BooleanField(default=True)
owner = models.ForeignKey(Client, null=True, blank=True, on_delete=models.SET_NULL)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
"""
Adds logic to automatically add all existing feeds to this playlist if it's new and allows
automatically adding feeds.
"""
is_new = self.pk is None # No primary key assigned, this Playlist is new.
super().save(force_insert, force_update, using, update_fields)
from feedmanager.models import Feed
if is_new and self.auto_add_feeds:
Feed.add_feeds_to_playlist(self)
def __str__(self):
return self.name
def as_list(self):
"""
Returns a list with the dictionary representation of all the items in this playlist.
"""
playlist = []
playlist_items = self.playlistitem_set.exclude(expire_on__lt=timezone.now())
playlist_items = playlist_items.order_by('position')
for pl_item in playlist_items:
try:
media_item = pl_item.item.get_subtype().as_dict()
except (NoContentAssetError, InvalidAssetError, ObjectDoesNotExist):
# If a feed doesn't have snippets for today (or at all), or a Calendar asset has no
# events for right now, or has no data, it will be skipped.
continue
else:
if 'duration' not in media_item:
media_item['duration'] = pl_item.duration
playlist.append(media_item)
return playlist
def get_absolute_url(self):
""" Returns the preview url for this playlist. """
return reverse('playlist-view', args=[str(self.pk)], host='content')
class ContentFeed(models.Model):
"""
This model represents a Content Feed.
A content feed is a collection of media content, a playlist, a ticker series and other
configuration parameters that are needed for a device to show something. It is linked to a
device group.
"""
title = models.CharField(max_length=100)
media_playlist = models.ForeignKey(Playlist,
null=True, blank=True,
on_delete=models.SET_NULL)
ticker_series = models.ForeignKey(TickerSeries,
null=True, blank=True,
on_delete=models.SET_NULL)
image_duration = models.IntegerField(default=4500)
web_duration = models.IntegerField(default=4500)
overlay_ticker = models.BooleanField(default=True)
auto_created = models.BooleanField(default=False)
def __str__(self):
return self.title
def settings(self):
""" Returns all the device settings for this feed. """
return {
'imageDuration': self.image_duration,
'webDuration': self.web_duration,
'overlayTicker': self.overlay_ticker,
'displayTicker': self.ticker_series is not None
}
def as_dict(self):
"""
Returns a dictionary representation of this content feed.
Can raise an error if the media_playlist is missing.
"""
if self.media_playlist is None:
raise ContentFeed.PlaylistNotSetError('No playlist configured for device group.')
feed_dict = {
'playlist': self.media_playlist.as_list(),
'tickers': self.ticker_series.as_list() if self.ticker_series else [],
'settings': self.settings(),
}
return feed_dict
class PlaylistNotSetError(AttributeError):
"""
Custom error to throw when a playlist has not been set for this content feed. A playlist is
essential to render a content feed.
"""
pass
class Meta:
verbose_name = 'Content Feed'
verbose_name_plural = 'Content Feeds'
class WebAssetTemplate(models.Model):
"""Web Asset Templates to make it easier for users to create web assets."""
name = models.CharField(
max_length=100,
help_text='The template name is what users select on the frontend so '
'it should be descriptive.')
template = models.TextField(
help_text='This is the HTML template that will be rendered by the '
'client and sent as a web asset.')
variables = models.CharField(
max_length=200,
help_text='The variables present in the template that will need '
'to be filled in by the user in the frontend.')
help_text = models.TextField(
help_text='Some helpful text to describe how to use this '
'template and it\'s variables.')
calendar_support = models.BooleanField(default=False)
data_support = models.BooleanField(default=False)
@property
def help_html(self):
return markdown(self.help_text)
def clean(self):
"""Validates variable names and calendar and data support."""
if self.calendar_support and self.data_support:
raise ValidationError('Calendar and data support cannot be enabled '
'in the same template.', code='invalid')
self.variables = self.variables.replace(' ', '')
if re.fullmatch(r'([a-zA-Z_]*,?)*', self.variables) is None:
raise ValidationError({
'variables': 'You need to enter one or more variable names separated by commas',
}, code='invalid')
def render(self, context):
return Template(self.template).render(Context(context))
def __str__(self):
return self.name
class Meta:
verbose_name = 'Web Asset Template'
class CalendarAsset(Asset):
""" This model represents a Calendar Asset. """
TYPE = AssetTypes.CALENDAR
template = models.ForeignKey(WebAssetTemplate, limit_choices_to={'calendar_support': True},
on_delete=models.CASCADE)
url = models.CharField(max_length=255)
data = models.TextField(editable=False, null=True, blank=True)
last_update = models.DateTimeField(editable=False, null=True, blank=True)
def save(self, *args, **kwargs):
""" Adds the extra logic of setting the type while saving the model. """
self.type = self.TYPE
super().save(*args, **kwargs)
def get_asset_url(self):
""" Returns the asset's url field or the content rendered in the page. """
return reverse('calasset-view', args=[self.pk], host='content')
def update_calendar_data(self):
""" Fetches latest ics data from the url and caches it. """
self.data = requests.get(self.url).text
self.last_update = timezone.now()
self.save()
def validate(self):
if self.data is None:
raise InvalidAssetError
def get_current_event(self):
self.validate()
try:
cal = Calendar.from_ical(self.data)
for event in cal.subcomponents:
start = event.decoded('DTSTART')
end = event.decoded('DTEND')
if isinstance(start, datetime.datetime):
now = timezone.now()
else:
now = timezone.now().date()
if start <= now <= end:
return {
'title': event.decoded('SUMMARY').decode('utf-8'),
'content': event.decoded('DESCRIPTION').decode('utf-8'),
}
except (ValueError, KeyError):
# The calendar has returned invalid data, this asset is invalid.
raise InvalidAssetError
@property
def rendered_content(self):
cal_data = self.get_current_event()
if cal_data is None:
raise NoContentAssetError
else:
return self.template.render(cal_data)
@property
def checksum(self):
""" Calculates checksum for calendar asset based on content. """
md5 = hashlib.md5()
md5.update(self.rendered_content.encode('utf-8'))
return md5.hexdigest()
def as_dict(self):
""" Returns a dictionary representation of this web asset. """
return {
'url': self.get_asset_url(),
'checksum': self.checksum,
'type': 'web',
}
# noinspection PyUnusedLocal
def build_metadata_and_thumbnails(sender, instance=None, created=False, **kwargs):
if isinstance(instance, VideoAsset):
Channel('update-video-metadata').send({'ids': [instance.id]})
elif isinstance(instance, ImageAsset):
Channel('update-image-metadata').send({'ids': [instance.id]})
if created:
Channel('create-thumbnail').send({'ids': [instance.id]})
post_save.connect(build_metadata_and_thumbnails, sender=VideoAsset)
post_save.connect(build_metadata_and_thumbnails, sender=ImageAsset)
post_save.connect(build_metadata_and_thumbnails, sender=WebAsset)
<file_sep>/utils/mixins.py
# -*- coding: utf-8 -*-
""" Mixing utilities. """
from rest_framework.exceptions import PermissionDenied
from client_manager.models import ClientUserProfile
def get_owner_from_request(request):
"""
Returns the owner associated with the user currently logged in.
If no user is logged in, it raises a permission error.
"""
if request.user.is_anonymous:
raise PermissionDenied
return get_owner_from_user(request.user)
def get_owner_from_user(user):
try:
userprofile = user.profile # type: ClientUserProfile
except ClientUserProfile.DoesNotExist:
return None
return userprofile.client
class AutoAddOwnerOnCreateMixin:
"""
This mixin automatically fills in the owner when creating an object.
It is intended to be mixed in with a Serializer class.
"""
def create(self, validated_data: dict):
"""
Automatically add the owner to the model based on the owner associated with the user
currently logged in.
"""
request = self.context.get('request')
validated_data['owner'] = get_owner_from_request(request)
return super().create(validated_data)
class FilterByOwnerMixin:
"""
Filters a viewset's queryset based on the owner associated with the currently-logged-in user.
"""
def get_queryset(self):
""" Returns the queryset filtered by owner based on the user from the request. """
return self.queryset.filter(owner=get_owner_from_request(self.request))
class AutoAddOwnerAdminMixin:
"""
This mixin automatically adds an owner while saving an object without an owner in the admin
panel.
"""
def save_model(self, request, obj, form, change):
""" Add owner if none is provided while saving the model via the admin panel. """
if getattr(obj, 'owner', None) is None:
obj.owner = get_owner_from_request(request)
super().save_model(request, obj, form, change)
<file_sep>/mediamanager/migrations/0010_auto_20170407_1939.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-07 14:09from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mediamanager', '0009_auto_20170323_1804'),
]
operations = [
migrations.AlterField(
model_name='asset',
name='asset_url',
field=models.CharField(editable=False, max_length=255),
),
migrations.AlterField(
model_name='asset',
name='thumbnail',
field=models.CharField(blank=True, editable=False, max_length=255, null=True),
),
migrations.AlterField(
model_name='asset',
name='type',
field=models.CharField(editable=False, max_length=25),
),
]
<file_sep>/tests/test_admin_pages.py
# -*- coding: utf-8 -*-
from pytest_bdd import scenarios, then
scenarios('features/admin_pages.feature')
@then('I should be able to access <page> of <app>')
def access_admin_page(client, app, page):
response = client.get('/admin/{app}/{page}/'.format(app=app, page=page))
assert response.status_code == 200
@then('Access the add page')
def access_admin_page(client, app, page):
response = client.get('/admin/{app}/{page}/add/'.format(app=app, page=page))
assert response.status_code == 200
<file_sep>/client_manager/migrations/0012_auto_20170618_1816.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-18 12:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('client_manager', '0011_clientsettings'),
]
operations = [
migrations.AlterField(
model_name='clientsettings',
name='idle_detection_enabled',
field=models.BooleanField(default=False,
help_text='Should the app auto-launch during idle periods.'),
),
migrations.AlterField(
model_name='clientsettings',
name='idle_detection_threshold',
field=models.PositiveSmallIntegerField(default=15,
help_text='How long (in minutes) should the device be idle before the app is launched.'),
),
]
<file_sep>/devicemanager/migrations/0002_auto_20160826_0327_squashed_0003_auto_20160828_1825.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-31 10:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('devicemanager', '0002_auto_20160826_0327'),
('devicemanager', '0003_auto_20160828_1825')]
dependencies = [
('client_manager', '0001_initial'),
('devicemanager', '0001_squashed_0007_auto_20160809_0409'),
]
operations = [
migrations.AddField(
model_name='device',
name='owner',
field=models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.SET_NULL,
to='client_manager.Client'),
),
migrations.AddField(
model_name='devicegroup',
name='owner',
field=models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.SET_NULL,
to='client_manager.Client'),
),
]
<file_sep>/mediamanager/types.py
# -*- coding: utf-8 -*-
""" This module defines common types that can be used across the app. """
class AssetTypes(object):
""" This class exists simply to contain contants related to the different asset types. """
VIDEO = 'VIDEO'
IMAGE = 'IMAGE'
WEB = 'WEB'
FEED = 'FEED'
CALENDAR = 'CALENDAR'
<file_sep>/notification_manager/migrations/0001_squashed_0004_auto_20171103_2045.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-03 20:21
from __future__ import unicode_literals
import django.db.models.deletion
import storages.backends.s3boto
from django.conf import settings
from django.db import migrations, models
import notification_manager.models
class Migration(migrations.Migration):
replaces = [('notification_manager', '0001_initial'),
('notification_manager', '0002_auto_20171102_0616'),
('notification_manager', '0003_remove_userpoststatus_notified_on'),
('notification_manager', '0004_auto_20171103_2045')]
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('body', models.TextField()),
('posted_on', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='PostTopic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=24)),
('image',
models.ImageField(storage=storages.backends.s3boto.S3BotoStorage(),
upload_to=notification_manager.models.post_topic_icon_location)),
],
),
migrations.CreateModel(
name='UserPostStatus',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True,
serialize=False, verbose_name='ID')),
('read_on', models.DateTimeField(blank=True, null=True)),
('post',
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='notification_manager.Post')),
('user',
models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='post',
name='topic',
field=models.ForeignKey(help_text='Topics let you organise posts.',
on_delete=django.db.models.deletion.CASCADE,
to='notification_manager.PostTopic'),
),
migrations.AlterUniqueTogether(
name='userpoststatus',
unique_together=set([('user', 'post')]),
),
migrations.AlterField(
model_name='post',
name='body',
field=models.TextField(
help_text='The main body of the text in Markdown format. It will be rendered to HTML before being displayed to users.'),
),
migrations.AlterField(
model_name='post',
name='title',
field=models.CharField(
help_text='A title for this post. The title should be short, and to the point.',
max_length=255),
),
]
<file_sep>/mediamanager/management/commands/update_calendar_assets.py
# -*- coding: utf-8 -*-
""" Contains the command for update calendar assets. """
from channels import Channel
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Command to update calendar assets."""
help = 'Updates all calendar assets'
def handle(self, *args, **options):
Channel('update-calendar-assets').send({})
<file_sep>/notification_manager/models.py
# -*- coding: utf-8 -*-
from pathlib import PurePath
import mistune
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from storages.backends.s3boto import S3BotoStorage
User = get_user_model()
markdown = mistune.Markdown()
def post_topic_icon_location(instance, filename):
return 'media/post-topic-icons/{upload_name}{extension}'.format(
upload_name=instance.name,
extension=PurePath(filename).suffix
)
class PostTopic(models.Model):
name = models.CharField(max_length=24)
image = models.ImageField(storage=S3BotoStorage(), upload_to=post_topic_icon_location)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(
max_length=255,
help_text='A title for this post. '
'The title should be short, and to the point.')
topic = models.ForeignKey(
PostTopic,
help_text='Topics let you organise posts.')
body = models.TextField(
help_text='The main body of the text in Markdown format. '
'It will be rendered to HTML before being displayed to users.')
posted_on = models.DateTimeField(auto_now_add=True)
@property
def content(self):
return markdown(self.body)
def __str__(self):
return self.title
class Meta:
ordering = ['-posted_on']
class UserPostStatus(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey(Post)
read_on = models.DateTimeField(null=True, blank=True)
class Meta:
unique_together = ('user', 'post')
# noinspection PyUnusedLocal
@receiver(signal=post_save, sender=Post)
def add_post_user_status_for_post(sender, instance, **kwargs):
for user in User.objects.all():
UserPostStatus.objects.get_or_create(user=user, post=instance)
# noinspection PyUnusedLocal
@receiver(signal=post_save, sender=User)
def add_post_user_status_for_user(sender, instance, **kwargs):
one_month_ago = timezone.now() - timezone.timedelta(days=31)
# Only create a status for posts in the past month
for post in Post.objects.filter(posted_on__gte=one_month_ago):
UserPostStatus.objects.get_or_create(user=instance, post=post)
<file_sep>/schedule_manager/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-24 23:48
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('devicemanager', '0007_device_command'),
('mediamanager', '0007_auto_20170110_0200'),
]
operations = [
migrations.CreateModel(
name='ScheduledContent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('day', models.CharField(
choices=[('mon', 'Monday'), ('tue', 'Tuesday'), ('wed', 'Wednesday'),
('thu', 'Thursday'), ('fri', 'Friday'), ('sat', 'Saturday'),
('sun', 'Sunday')], max_length=4)),
('default', models.BooleanField()),
('start_time', models.TimeField(blank=True, null=True)),
('end_time', models.TimeField(blank=True, null=True)),
('content', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.ContentFeed')),
('device_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.DeviceGroup')),
],
options={
'verbose_name': 'Scheduled Content',
'verbose_name_plural': 'Scheduled Content',
},
),
migrations.CreateModel(
name='SpecialContent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('date', models.DateField()),
('content', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.ContentFeed')),
('device_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.DeviceGroup')),
],
options={
'verbose_name_plural': 'Special Content',
},
),
migrations.AlterUniqueTogether(
name='specialcontent',
unique_together=set([('device_group', 'date')]),
),
]
<file_sep>/devicemanager/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-20 22:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('mediamanager', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Device',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('device_id', models.UUIDField()),
('name', models.CharField(max_length=255)),
('last_ping', models.DateTimeField()),
('debug_mode', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='DeviceGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('name', models.CharField(max_length=255)),
('feed', models.ForeignKey(blank=True, null=True,
on_delete=django.db.models.deletion.CASCADE,
to='mediamanager.ContentFeed')),
],
options={
'verbose_name_plural': 'Device Groups',
'verbose_name': 'Device Group',
},
),
migrations.CreateModel(
name='DeviceLocation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,
verbose_name='ID')),
('location', models.CharField(max_length=255)),
],
options={
'verbose_name_plural': 'Device Locations',
'verbose_name': 'Device Location',
},
),
migrations.AddField(
model_name='device',
name='group',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.DeviceGroup'),
),
migrations.AddField(
model_name='device',
name='location',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
to='devicemanager.DeviceLocation'),
),
]
<file_sep>/devicemanager/migrations/0007_device_command.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-20 10:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devicemanager', '0006_auto_20170116_1853'),
]
operations = [
migrations.AddField(
model_name='device',
name='command',
field=models.CharField(blank=True, choices=[('reboot', 'Reboot Device'),
('free-space', 'Delete Unused Media'),
('clear-media', 'Clear All Device Media'),
('reset-device', 'Reset Device')],
max_length=20, null=True),
),
]
<file_sep>/feedmanager/models.py
# -*- coding: utf-8 -*-
""" Models for the feed manager app. """
from datetime import date
import hashlib
from django import template
from django.core.exceptions import ValidationError
from django.db import models
from django.template import Context
from django.utils import timezone
from django.utils.text import slugify
from django_hosts.resolvers import reverse
from client_manager.models import Client
from mediamanager.models import FeedAsset, Playlist
from mediamanager.types import AssetTypes
from utils.files import md5_file_name
def md5_checksum(content):
"""Calculates md5_checksum text content """
md5 = hashlib.md5()
md5.update(content.encode('utf-8'))
return md5.hexdigest()
class Category(models.Model):
"""
This model represents a category for Feeds.
A category can be date-based or random. In the first case the contents of the category are
sensitive to date, for instance a category like "This day in History" only makes sense if the
content being shown is for the correct date.
A random category is one where the content needs to change each day, but the content itself is
not date sensitive.
"""
RANDOM_TYPE = 'RANDOM'
DATED_TYPE = 'DATED'
TYPES = ((RANDOM_TYPE, 'Random'),
(DATED_TYPE, 'Dated'))
name = models.CharField(max_length=100,
help_text='Enter a helpful name for this feed category. Example: '
'<em>"Word of the Day"</em>')
type = models.CharField(max_length=10,
choices=TYPES,
help_text='Select whether this option is time-sensitive or not.'
'For a time-sensitive category '
'(e.g. "This day in history"), '
'only content relevant to the current date will be fetched.')
def get_snippets(self, snippet_type):
"""
Returns the snippets associated with this category while applying the
date filter if needed.
"""
snippets = snippet_type.objects.filter(category=self)
if self.type == 'DATED':
snippets = snippets.filter(date=timezone.now().date())
return snippets
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'Categories'
class Snippet(models.Model):
"""
This model represents a Snippet.
A snippet is a small piece of content and this class serves as a base for the Image, Video, and
Web snippet classes.
"""
title = models.CharField(max_length=255,
null=True, blank=True,
help_text='Pick a good topic or title for the snippet. In some cases '
'this might be visible to end-users. ')
date = models.DateField(null=True, blank=True,
help_text='Enter a date here if this snippet is date-sensitive. This '
'will only have an effect if the snippet category itself is '
'date-sensitive.')
category = models.ForeignKey(Category,
help_text='Select which category should display this snippet.')
def __str__(self):
return self.title
class WebSnippet(Snippet):
"""
This model represents a web snippet.
A web snippet stores a bunch of text content to render on the device.
"""
content = models.TextField(help_text='This is the actual content of the web snippet. How and '
'where it appears depends on the template used to render '
'it. Some templates strip HTML content.')
class FileSnippet(Snippet):
"""
This model serves as a base for file-based snippets.
It includes data and functionality common for any file-based snippet type.
"""
media = models.FileField(upload_to=md5_file_name,
help_text='This is the media file that will be served in the feed '
'directly.')
checksum = models.CharField(max_length=120, editable=False)
def save(self, *args, **kwargs):
"""
Adds logic to create an MD5 checksum of uploaded file and save it to the checksum field of
the model.
"""
if not self.pk:
md5 = hashlib.md5()
for chunk in self.media.chunks():
md5.update(chunk)
self.checksum = md5.hexdigest()
super().save(*args, **kwargs)
class Meta:
abstract = True
class ImageSnippet(FileSnippet):
""" This model represents an ImageSnippet. """
pass
class VideoSnippet(FileSnippet):
""" This model represents an VideoSnippet. """
pass
class Template(models.Model):
"""
This model represents a Template.
This store a template in the Django template format that can be combined with data in a snippet
to produce a rendered HTML page.
"""
name = models.CharField(max_length=100,
help_text='This is just a friendly name to help you recognise the '
'purpose of the template. It is not visible to users.')
template_data = models.TextField(help_text='This is the actual content of the template. The '
'title and content snippets will be filled in here '
'to render the final page that will be pushed to '
'devices.')
duration = models.PositiveIntegerField(
default=10000, # 10 seconds
help_text='How long should a slide using this template be visible on screen. <br/>'
'If a template has an animation this time should ensure that the animation '
'has enough time to complete. '
)
def render(self, context):
"""
Creates a Django template object using the template data and renders it using the supplied
context.
"""
return template.Template(self.template_data).render(context)
def __str__(self):
return self.name
class Feed(models.Model):
"""
This model represents a Feed.
It serves as a base class for the more specialsed Image, Video and Web Feed classes.
"""
name = models.CharField(max_length=100,
help_text='This is a friendly name to identify this feed, it is not '
'visible to end-users. ')
slug = models.SlugField(help_text='This field should be filled in automatically based on the '
'name. It is a simplified representation of the name such '
'that it can be part of a URL.')
published = models.BooleanField(default=False,
help_text='A feed that is published will appear in users\' '
'asset lists. For a feed to be published it needs '
'to have a valid snippet.')
type = models.CharField(max_length=25, editable=False)
category = models.ForeignKey(Category,
help_text='The feed category decides what snippets appear in '
'this feed.')
publish_to = models.ManyToManyField(Client)
asset_type = None
snippet_type = None
@property
def checksum(self):
"""Returns checksum for today's asset for this feed"""
if type(self) == Feed:
return self.get_subtype().checksum
else:
return self.get_snippet_for_today().checksum
def clean(self):
"""
Disallows saving a feed that has no snippets assigned since that would cause errors in
multiple other places
"""
# Don't check for snippets if clean is called on base Feed object since it might not have
# set up a type yet.
if self.published and type(self) is not Feed and not self.snippets.exists():
raise ValidationError({'published': 'You cannot publish a feed that has no snippets.'})
@classmethod
def add_feeds_to_playlist(cls, playlist: Playlist):
""" This class method will add all published feeds to the supplied playlist. """
for feed in cls.objects.filter(published=True, publish_to__in=[playlist.owner]).distinct():
feed.add_feed_item_to_playlist(playlist)
def add_feed_item_to_playlist(self, playlist: Playlist, feed_asset: FeedAsset = None):
"""
Adds a feed item to a playlist by fetching an existing feed item for the feed or creating a
new one if none is present.
"""
if feed_asset is None:
feed_asset = FeedAsset.objects.get(feed=self)
playlist.playlistitem_set.create(item=feed_asset)
def _create_playlist_items(self, feed_asset):
"""
Creates a playlist item for this feed in every playlist subscribed to feeds.
:param feed_asset: The feed asset associated with this Feed
:type feed_asset: FeedAsset
:rtype: None
"""
if self.published:
for playlist in Playlist.objects.filter(auto_add_feeds=True,
owner__in=self.publish_to.all()):
if not playlist.playlistitem_set.filter(item=feed_asset).exists():
self.add_feed_item_to_playlist(playlist)
def _manage_feed_asset(self):
"""
Automatically cretes a FeedAsset for this feed. If a FeedAsset is alredy present, it
will update the existing feed asset. If the feed is unpublished, it will delete the
associated FeedAsset object.
:return: Newly created or updated FeedAsset or None if assets were deleted
:rtype: Union[FeedAsset, None]
"""
if self.published:
feed_asset, created = FeedAsset.objects.update_or_create(
feed=self,
defaults={
'name': '{name} Feed'.format(name=self.name),
})
return feed_asset
else:
FeedAsset.objects.filter(feed=self).delete()
def get_absolute_url(self):
""" Returns the URL for this feed based on the type. """
if self.type == AssetTypes.WEB:
return reverse('web-feed-view', args=[str(self.slug)], host='content')
elif self.type == AssetTypes.IMAGE:
return reverse('image-feed-view', args=[str(self.slug)], host='content')
elif self.type == AssetTypes.VIDEO:
return reverse('video-feed-view', args=[str(self.slug)], host='content')
else:
raise ValueError
def get_asset_url(self):
""" Returns the URL for this feed based on the type. """
if self.type == AssetTypes.WEB:
return reverse('web-feed-view', args=[str(self.slug)], host='content')
elif self.type == AssetTypes.IMAGE or self.type == AssetTypes.VIDEO:
snippet = self.get_subtype().get_snippet_for_today()
return snippet.media.url
else:
raise ValueError
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
"""
Adds logic to the standard save method.
* Adds the feed type to the Feed.
* Adds a slug based on the name.
* Runs the manage feed asset private method to update, create or delete the associated
feed asset based on whether the feed is updated, published, or unpublished.
* Adds associated feed asset to all subscribed playlists.
"""
if type(self) is not Feed:
self.type = self.asset_type
if not self.slug:
self.slug = slugify(self.name)
super().save(force_insert, force_update, using, update_fields)
if type(self) is not Feed:
# Now that the Feed has been saved, create / update / delete the associated FeedAsset
feed_asset = self._manage_feed_asset()
# If a new FeedAsset was created, also add it to all subscribed playlists.
if feed_asset is not None:
self._create_playlist_items(feed_asset)
def get_subtype(self):
"""Get's the child model for this feed instance."""
if self.type == AssetTypes.WEB:
return self.webfeed
elif self.type == AssetTypes.IMAGE:
return self.imagefeed
elif self.type == AssetTypes.VIDEO:
return self.videofeed
else:
raise ValueError
@property
def snippets(self):
"""Returns the snippets for this feed."""
if isinstance(self, Feed):
snippet_type = self.get_subtype().snippet_type
else:
snippet_type = self.snippet_type
return self.category.get_snippets(snippet_type)
def get_snippet_for_today(self):
""" Retuns the snippet for the day. """
snippets = self.snippets
snippet_count = snippets.count()
if snippet_count == 0: # If there are no snippets this feed is invalid.
raise self.snippet_type.DoesNotExist
# index = hash(date.today()) % snippet_count
# date.today().timetuple().tm_yday returns the day of the year for today.
index = date.today().timetuple().tm_yday % snippet_count
return snippets[index]
def __str__(self):
return self.name
def as_dict(self):
"""Returns a dictionary representation of this feed"""
if self.type == AssetTypes.WEB:
return self.webfeed.as_dict()
return {
'url': self.get_asset_url(),
'checksum': self.checksum,
'type': self.type.lower(),
}
class WebFeed(Feed):
"""
This model represents a WebFeed.
"""
template = models.ForeignKey(Template,
help_text='Web feeds fill in the data from web snippets into '
'this template to produce the final page that will '
'be seen by on devices.')
asset_type = AssetTypes.WEB
snippet_type = WebSnippet
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._rendered_content = None
self._checksum = None
def get_absolute_url(self):
""" Returns the URL for this web feed. """
return reverse('web-feed-view', args=[str(self.slug)], host='content')
def get_asset_url(self):
""" Returns a URL for this web feed. """
return self.get_absolute_url()
def rendered_content(self):
""" Renders this current snippet to HTML using the associated template. """
if self._rendered_content is None:
snippet = self.get_snippet_for_today()
self._rendered_content = self.template.render(Context({
'title': snippet.title,
'content': snippet.content
}))
return self._rendered_content
@property
def checksum(self):
"""Returns md5_checksum for today's asset for this feed"""
if self._checksum is None:
self._checksum = md5_checksum(self.rendered_content())
return self._checksum
def as_dict(self):
"""Returns a dictionary representation of this feed"""
return {
'url': self.get_asset_url(),
'checksum': self.checksum,
'type': self.type.lower(),
'duration': self.template.duration,
}
class ImageFeed(Feed):
"""
This model represents an Image Feed.
"""
asset_type = AssetTypes.IMAGE
snippet_type = ImageSnippet
def get_absolute_url(self):
""" Returns a URL for this feed. """
return reverse('image-feed-view', args=[str(self.slug)], host='content')
def get_asset_url(self):
""" Returns a URL for this feed. """
return self.get_absolute_url()
class VideoFeed(Feed):
""" This model represents a Video Feed. """
asset_type = AssetTypes.VIDEO
snippet_type = VideoSnippet
def get_absolute_url(self):
""" Returns a URL for this feed. """
return reverse('video-feed-view', args=[str(self.slug)], host='content')
def get_asset_url(self):
""" Returns a URL for this feed. """
return self.get_absolute_url()
| 32a80583a9cc6104f3d55a8b817ee9caad973bc6 | [
"Python",
"Dockerfile",
"reStructuredText",
"INI"
] | 68 | Python | plus2dot/signoxemedia | 7821a680f3d81898f3e1751359c18e826c132fe5 | c5f5b14b8035192b7095f8f11b36c3cfb2c591cc |
refs/heads/master | <file_sep>#!/usr/bin/python3
# coding: utf-8
import websocket
import threading
import traceback
from time import sleep
import json
import logging
class BitflyerJSON_RPC:
MAX_LIMIT_LEN = 1000
'''
#
# symbolに購読する通貨セットを指定してください
# 'BTC_JPY','FX_BTC_JPY','ETH_BTC', or futures
# recconect: エラー発生時に再接続するか否か
# target_channels: 購読対象を指定できます。デフォルトは全てのチャンネルを受信です。
# default) ("board_snapshot", "tickers", "executions")
#
'''
def __init__(self,
symbol,
reconnect=False,
target_channels=("board_snapshot", "tickers", "executions")
):
# ロガー生成
self.logger = logging.getLogger(__name__)
self.logger.debug("Initializing WebSocket.")
self.endpoint = "wss://ws.lightstream.bitflyer.com/json-rpc"
self.symbol = symbol
self.reconnect = reconnect # 再接続フラグ
self.target_channels = target_channels
# 購読するsubscriptionsを設定
self.channel_board_snapshot = "lightning_board_snapshot" + '_' + self.symbol
self.channel_board = "lightning_board" + '_' + self.symbol
self.channel_ticker = "lightning_ticker" + '_' + self.symbol
self.channel_executions = "lightning_executions" + '_' + self.symbol
self.channels = []
if "board_snapshot" in self.target_channels:
self.channels.append(self.channel_board_snapshot)
self.channels.append(self.channel_board)
if "tickers" in self.target_channels:
self.channels.append(self.channel_ticker)
if "executions" in self.target_channels:
self.channels.append(self.channel_executions)
# データを格納する変数を宣言
self.data = {}
self.exited = False
# findItemByKeys高速化のため、インデックスを作成・格納するための変数を作っておく
self.itemIdxs = {}
# スナップショットの値を格納する辞書
self.board_snapshot = {}
self.board_snapshot_bids_dict = {}
self.board_snapshot_asks_dict = {}
# Ticker情報を格納する配列
self.tickers = []
# 成約情報を格納する配列と辞書
self.executions = []
self.executions_sell_dict = {}
self.executions_buy_dict = {}
wsURL = self.endpoint
self.logger.info("Connecting to %s" % wsURL)
self.__connect(wsURL, symbol)
self.logger.info('Connected to WS.')
self.__wait_for_first_data()
def exit(self):
'''WebSocketクローズ時に呼ばれます'''
self.exited = True
self.ws.close()
def get_board_snapshot(self):
'''板情報のスナップショットを取得します'''
if 'board_snapshot' not in self.target_channels:
raise Exception("board_snapshot is not subscribe target.")
return self.data['board_snapshot']
def get_ticker(self):
'''最新のTicker情報を取得します'''
if 'tickers' not in self.target_channels:
raise Exception("tickers is not subscribe target.")
return self.data['tickers'][-1]
def get_execution(self, order_acceptance_id=''):
'''指定されたorder_acceptance_idに関連する約定情報の配列を返却します
指定されなかった場合、直近MAX_LIMIT_LEN分の約定情報を返却します'''
if 'executions' not in self.target_channels:
raise Exception("executions is not subscribe target.")
if order_acceptance_id == '':
return self.data['executions']
elif order_acceptance_id in self.executions_buy_dict.keys():
return self.executions_buy_dict[order_acceptance_id]
elif order_acceptance_id in self.executions_sell_dict.keys():
return self.executions_sell_dict[order_acceptance_id]
else:
return []
#
# End Public Methods
#
def __connect(self, wsURL, symbol):
'''Connect to the websocket in a thread.'''
self.logger.debug("Starting thread")
self.ws = websocket.WebSocketApp(wsURL,
on_message=self.__on_message,
on_close=self.__on_close,
on_open=self.__on_open,
on_error=self.__on_error,
header=None)
self.wst = threading.Thread(target=lambda: self.ws.run_forever())
self.wst.daemon = True
self.wst.start()
self.logger.debug("Started thread")
# Wait for connect before continuing
conn_timeout = 5
while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
sleep(1)
conn_timeout -= 1
if not conn_timeout:
self.logger.error("Couldn't connect to WS! Exiting.")
self.exit()
raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')
def __on_open(self, ws):
'''コネクションオープン時の処理'''
self.logger.debug("Websocket Opened.")
# 指定されている通貨セットの全てのチャンネルを購読します
for channel in self.channels:
output_json = json.dumps(
{'method' : 'subscribe',
'params' : {'channel' : channel}
}
)
ws.send(output_json)
def __wait_for_first_data(self):
# 全ての購読の最初のデータが揃うまで待ちます
while not set(self.target_channels) <= set(self.data):
sleep(0.1)
def __on_close(self, ws):
'''WebSocketクローズ時の処理'''
self.logger.info('Websocket Closed')
def __on_error(self, ws, error):
'''WebSocketでエラーが発生したときの処理'''
if not self.exited:
self.logger.error("Error : %s" % error)
if self.reconnect:
# 再接続フラグが有効であれば再接続
self.exit()
self.__connect(self.endpoint, self.symbol)
else:
raise websocket.WebSocketException(error)
def __on_message(self, ws, message):
'''WebSocketがメッセージを取得したときの処理'''
message = json.loads(message)['params']
self.logger.debug(json.dumps(message))
try:
recept_channel = message['channel']
recept_data = message['message']
if recept_channel == self.channel_board_snapshot:
# 板スナップショット
self.data["board_snapshot"] = recept_data
self.board_snapshot_bids_dict.clear()
self.board_snapshot_asks_dict.clear()
for bid in self.data["board_snapshot"]["bids"]:
self.board_snapshot_bids_dict[bid["price"]] = bid
for ask in self.data["board_snapshot"]["asks"]:
self.board_snapshot_asks_dict[ask["price"]] = ask
elif recept_channel == self.channel_board:
# 板更新情報
#取得したデータでスナップショットを更新する
if "board_snapshot" not in self.data.keys() :
return
#mid_price
self.data["board_snapshot"]["mid_price"] = recept_data["mid_price"]
# bids
if len(recept_data["bids"]) > 0 :
for re_bid in recept_data["bids"]:
if re_bid["price"] in self.board_snapshot_bids_dict.keys():
if re_bid["size"] == 0:
del self.board_snapshot_bids_dict[re_bid["price"]]
else:
self.board_snapshot_bids_dict[re_bid["price"]] = re_bid
else:
self.board_snapshot_bids_dict[re_bid["price"]] = re_bid
# asks
if len(recept_data["asks"]) > 0 :
for re_ask in recept_data["asks"]:
if re_ask["price"] in self.board_snapshot_asks_dict.keys():
if re_ask["size"] == 0:
del self.board_snapshot_asks_dict[re_ask["price"]]
else:
self.board_snapshot_asks_dict[re_ask["price"]] = re_ask
else:
self.board_snapshot_asks_dict[re_ask["price"]] = re_ask
# 更新したデータを組み立てて、dataテーブルに組み込む
self.data["board_snapshot"]["bids"] = [i[1] for i in sorted(self.board_snapshot_bids_dict.items(), key=lambda bid: bid[1]["price"],reverse=True)]
self.data["board_snapshot"]["asks"] = [i[1] for i in sorted(self.board_snapshot_asks_dict.items(), key=lambda ask: ask[1]["price"],reverse=False)]
elif recept_channel == self.channel_ticker:
# Ticker情報
self.tickers.append(recept_data)
if len(self.tickers) > BitflyerJSON_RPC.MAX_LIMIT_LEN :
self.tickers = self.tickers[len(self.tickers)-BitflyerJSON_RPC.MAX_LIMIT_LEN:]
self.data["tickers"] = self.tickers
elif recept_channel == self.channel_executions:
# 約定情報
# 取得したデータをスタックに入れ込む
# sell側とbuy側のchild_order_idとの辞書を登録する
for execution in recept_data:
self.executions.append(execution)
if execution["sell_child_order_acceptance_id"] in self.executions_sell_dict:
self.executions_sell_dict[execution["sell_child_order_acceptance_id"]].append(execution)
else:
self.executions_sell_dict[execution["sell_child_order_acceptance_id"]] = [execution]
if execution["buy_child_order_acceptance_id"] in self.executions_buy_dict:
self.executions_buy_dict[execution["buy_child_order_acceptance_id"]].append(execution)
else:
self.executions_buy_dict[execution["buy_child_order_acceptance_id"]] = [execution]
if len(self.executions) > BitflyerJSON_RPC.MAX_LIMIT_LEN:
del_index = len(self.executions) - BitflyerJSON_RPC.MAX_LIMIT_LEN
del_target = self.executions[0:del_index-1]
self.executions = self.executions[del_index:]
for del_ex in del_target:
if del_ex["sell_child_order_acceptance_id"] in self.executions_sell_dict :
del self.executions_sell_dict[del_ex["sell_child_order_acceptance_id"]]
if del_ex["buy_child_order_acceptance_id"] in self.executions_buy_dict :
del self.executions_buy_dict[del_ex["buy_child_order_acceptance_id"]]
self.data["executions"] = self.executions
else:
raise Exception("Unknown channel: %s" % recept_channel)
except:
self.logger.error(traceback.format_exc())
if __name__ == '__main__':
ex = BitflyerJSON_RPC(symbol='BTC_JPY')
print("board_snapshot:{0}".format(ex.get_board_snapshot()['mid_price']))
print("tiker:{0}".format(ex.get_ticker()))
print("execution:{0}".format(ex.get_execution()))
<file_sep>from .py_bitflyer_jsonrpc import BitflyerJSON_RPC<file_sep>.. -*- mode: rst -*-
py_bitflyer_jsonrpc
==========
''py_bitflyer_jsonrpc'' は、仮想通貨取引所 Bitflyer のJSON-RPCプロトコルを使用して情報を取得するライブラリです。
Install
-------
Using pip
.. code::
$ pip install git+https://github.com/mottio-cancer/py_bitflyer_jsonrpc.git
Usage
-----
.. code:: python
import py_bitflyer_jsonrpc
api = py_bitflyer_jsonrpc.BitflyerJSON_RPC(symbol=product_code)
"""
or you can select the information you want to enable, as shown below.
The default for target_channels is this.
api = py_bitflyer_jsonrpc.BitflyerJSON_RPC(symbol=product_code,
target_channels=("board_snapshot", "tickers", "executions"))
But "board_snapshot" is somewhat large, you may want to not subscribing for resource savings.
write that.
api = py_bitflyer_jsonrpc.BitflyerJSON_RPC(symbol=product_code,
target_channels=("tickers", "executions"))
"""
Example
-------
Order Book Infomaition
~~~~~~~~~~
.. code:: python
# 現在のオーダー情報のスナップショットを取得します
# スナップショットは、JSON-RPCを通して配信される更新情報を購読し、常に最新の状態に更新しています
snapshot = api.get_board_snapshot()
Ticker
~~~~~~
.. code:: python
# 最新のTicker情報を取得します
ticker = api.get_ticker()
Execution Order
~~~~~~~~~~~~~~~~
.. code:: python
# 直近最大1000件の約定情報を取得します
executions = api.get_excution()
# 指定した''order_acceptance_id''に対応した約定情報が存在すれば、その配列を返します
executions = api.get_execution(order_acceptance_id=ORDER_ACCEPTANCE_ID)
# ''order_acceptance_id''に対応する約定が配信されていない場合は空の配列を返却するので、
# 下記のように注文の約定を待つことに使用できます
while not api.get_execution(order_acceptance_id=ORDER_ACCEPTANCE_ID):
time.sleep(0.1)
More detail
~~~~~~~~~~~
JSON-RPCの仕様について詳しく知りたければ、下記を参照してください。
: https://lightning.bitflyer.jp/docs#json-rpc-2.0-over-websocket
Author
------
@mottio-cancer (<<EMAIL>>)
| 1de789c1cef7aa8a1780f56483feb185b6e79ae2 | [
"Python",
"reStructuredText"
] | 3 | Python | satogiwa/py_bitflyer_jsonrpc | c1dfe36a887c97cc9c5779e81a7039d9b723a53c | cdcaecba19f5a03aff16fb12aef040583a621643 |
refs/heads/master | <repo_name>adin234/kumusta<file_sep>/sa.sh
#!/usr/bin/env bash
php -f send_alerts.php
| a47c7a0f363498df2d87be1079ed8a1f285547c6 | [
"Shell"
] | 1 | Shell | adin234/kumusta | 703f9e93a9899a6a274b723b35019cdb0ccf438d | 7297c72d7141203bc719e0644b9ad6c72ceb3fa7 |
refs/heads/main | <file_sep>import React from 'react';
import {useFormik} from "formik";
import classes from './FormMessage.module.scss'
import classNames from 'classnames'
import FormInput from "./FormInput/FormInput";
import {stringCutter} from "../../../utils/stringCutter";
import UploadComponent from "./UploadComponent/UploadComponent";
import {validationSchema} from "./ValidationFormMessage";
import {useDispatch} from "react-redux";
import {addNewMessage} from "../../../redux/sendForm-reducer";
const FormMessage = () => {
const dispatch = useDispatch()
const formik = useFormik({
initialValues: {
firstNameFrom: '',
firstNameTo: '',
emailFrom: '',
emailTo: '',
emailTopic: '',
message: '',
files: [],
},
validationSchema: validationSchema,
onSubmit: values => {
dispatch(addNewMessage(values))
},
});
const onDeleteFile = (path) => {
const filteredFilesWithoutDelete = formik.values.files.filter(file => {
return file.path !== path
})
formik.setFieldValue('files', filteredFilesWithoutDelete)
}
return (
<div>
<h2>Messages Sender</h2>
<form onSubmit={formik.handleSubmit} className={classes.formMessage}>
От кого
<div className={classNames(classes.fromToInputs)}>
<FormInput
name="firstNameFrom"
placeholder={'Имя'}
formik={formik}
/>
<FormInput
name="emailFrom"
placeholder={'Email'}
formik={formik}
/>
</div>
Кому
<div className={classes.fromToInputs}>
<FormInput
name="firstNameTo"
placeholder={'Имя'}
formik={formik}
/>
<FormInput
name="emailTo"
placeholder={'Email'}
formik={formik}
/>
</div>
Тема письма
<div className={classes.formLetterTheme}>
<FormInput
name="emailTopic"
placeholder={'Тема письма'}
formik={formik}
/>
</div>
Сообщение
<div className={classes.textAreaBlock}>
<textarea
id="message"
name="message"
type="text"
onChange={formik.handleChange}
value={formik.values.message}
/>
</div>
<div className={classes.fileList}>
{formik.values.files
&&
formik.values.files.map((file, index) => {
return <FileBlock file={file} key={index} onDelete={() => onDeleteFile(file.path)}/>
})
}
</div>
<UploadComponent setFieldValue={formik.setFieldValue}/>
<button
type="submit"
className={classes.submitButton}
>Отправить
</button>
</form>
</div>
);
};
export default FormMessage;
const FileBlock = (props) => {
return (
<div className={classes.fileBlock}>
<div>
<i className="fas fa-paperclip"></i>
</div>
<div>
{stringCutter(props.file.name, 15)}
</div>
<div className={classes.deleteButton} onClick={props.onDelete}>
<i className="fas fa-trash"></i> Удалить
</div>
</div>
)
}<file_sep>
export const getIsLoading = (state) => {
return state.sendFormReducer.loading
}
export const getMessages = (state) => {
return state.sendFormReducer.messages
}
<file_sep>import React from 'react';
import classes from './Header.module.scss'
const Header = () => {
return (
<div className={classes.header}>
<div className={classes.geometricFigures}>
<div className={classes.circle}></div>
<div className={classes.rectangle}></div>
<div className={classes.circle}></div>
<div className={classes.parallelogram}></div>
</div>
</div>
);
};
export default Header;<file_sep>
// MESSAGE SCHEME
// emailFrom: ""
// emailTo: ""
// emailTopic: ""
// files: [File]
// firstNameFrom: ""
// firstNameTo: ""
// message: ""
// status
// id
const TOGGLE_LOADING = 'interview-sender/sendForm/TOGGLE_LOADING'
const SET_MESSAGE = 'interview-sender/sendForm/SET_MESSAGE'
const MESSAGE_SUCCESSFUL_SENT = 'interview-sender/sendForm/MESSAGE_SUCCESSFUL_SENT'
const initialState = {
loading: false,
messages: []
}
export const sendFormReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_LOADING: {
return {
...state,
loading: action.loading
}
}
case SET_MESSAGE:
return {
...state,
messages: [...state.messages, action.message]
}
case MESSAGE_SUCCESSFUL_SENT:
return {
...state,
messages: state.messages.map(message => {
if (message.id === action.id) {
return {...message, status: 'completed'}
}
return message
})
}
default:
return state
}
}
const actions = {
toggleLoading(loading) {
return {
type: TOGGLE_LOADING,
loading: loading
}
},
setMessage(message) {
return {
type: SET_MESSAGE,
message: message
}
},
messageSuccessfulSent(id) {
return {
type: MESSAGE_SUCCESSFUL_SENT,
id: id
}
}
}
export const addNewMessage = (messageObj) => async (dispatch) => {
messageObj.status = 'pending'
messageObj.id = Date.now()
messageObj.date = new Date().toString().slice(4, 15)
dispatch(actions.setMessage(messageObj))
dispatch(actions.toggleLoading(true))
setTimeout(() => {
dispatch(actions.messageSuccessfulSent(messageObj.id))
dispatch(actions.toggleLoading(false))
}, 3000)
}<file_sep>import {useDropzone} from "react-dropzone";
import classes from "./UploadComponent.module.scss";
import React, {useEffect, useState} from "react";
const UploadComponent = props => {
const [isOnDrag, setIsOnDrag] = useState(false)
const onDrag = () => {
setIsOnDrag(true)
}
useEffect(() => {
const dropZone = document.getElementById('dropzone')
dropZone.addEventListener('dragenter', onDrag)
return () => {
dropZone.removeEventListener('dragenter', onDrag)
}
})
const {setFieldValue} = props;
const {getRootProps, getInputProps, isDragActive,} = useDropzone({
accept: "image/*",
onDrop: acceptedFiles => {
setFieldValue("files", acceptedFiles);
setIsOnDrag(false)
},
onDragLeave: () => {
setIsOnDrag(false)
}
});
let classesForFileInput = classes.blockFileInput
if (isOnDrag) {
classesForFileInput = classes.dropzone
}
return (
<div>
<div {...getRootProps({className: classesForFileInput})}>
<input {...getInputProps()} />
{isDragActive || isOnDrag ? (
<React.Fragment>
<div className={classes.dragAndDrop}>
<h2>Бросайте файлы сюда, я ловлю</h2>
<span>Мы принимаем картинки (jpg, png, gif), офисные файлы (doc, xls, pdf) и zip-архивы</span>
</div>
<div className={classes.fileInput}>
<i className="fas fa-paperclip"></i>
Прикрепить файлы
</div>
</React.Fragment>
) : (
<div className={classes.fileInput}>
<i className="fas fa-paperclip"></i>
Прикрепить файлы
</div>
)}
</div>
</div>
);
};
export default UploadComponent<file_sep>import React, {useRef} from "react";
import classes from "../FormMessage.module.scss";
const FormInput = ({name, placeholder, formik}) => {
const refDiv = useRef()
if (formik.errors[name] && formik.touched[name]) {
refDiv.current?.parentNode.classList.add(classes.errorContainer)
} else if (!formik.errors[name]) {
refDiv.current?.parentNode.classList.remove(classes.errorContainer)
}
return (
<React.Fragment>
<div ref={refDiv}>
<input
id={name}
name={name}
type="text"
placeholder={placeholder}
onChange={formik.handleChange}
value={formik.values[name]}
onBlur={formik.handleBlur}
/>
{formik.touched[name]
&&
formik.errors[name]
&&
<span className={classes.error}>{formik.errors[name]}</span>
}
</div>
</React.Fragment>
)
}
export default FormInput<file_sep>export function stringCutter (str, sizeStr) {
const size = sizeStr
if (str.length > size) {
return str.slice(0, size) + '...'
}
return str
}<file_sep>import Table from "./components/Table/Table";
import classes from './App.module.scss'
import FormBlock from "./components/FormBlock/FormBlock";
import Header from "./Header/Header";
function App() {
return (
<div className={classes.container}>
<Header />
<FormBlock />
<Table />
</div>
);
}
export default App;
<file_sep>import React from 'react';
import classes from './FormBlock.module.scss'
import FormMessage from "./FormMessage/FormMessage";
import {useSelector} from "react-redux";
import {getIsLoading} from "../../redux/sendForm-selector";
import LoadingScreen from "./LoadingScreen/LoadingScreen";
const FormBlock = () => {
const isLoading = useSelector(getIsLoading)
if (isLoading) {
return (
<LoadingScreen />
)
}
return (
<div id={'dropzone'} className={classes.formBlock}>
<FormMessage />
</div>
);
};
export default FormBlock; | 37cc8f239b0378155d43cea2debc304436a023f7 | [
"JavaScript"
] | 9 | JavaScript | Algoritm211/message-sender | 0a6c9fd669211eb133f819ae21cf9f9462e2cdff | 2ed1e215f846555260ee10713dfecfba6004ddb6 |
refs/heads/master | <repo_name>ppaushya/Suman-Rav-159819<file_sep>/Day5/AnotherClass.java
package org.balance;
import balance.Account;
public class AnotherClass {
public static void main(String[] args) {
Account a= new Account();
a.displayBalance();
}
}
<file_sep>/Day4/CaptalizeString.java
import java.util.Scanner;
public class CaptalizeString {
char [] str1;
String strg;
String strg1;
String strg2;
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter the string: ");
String s1=scan.nextLine();
System.out.println("This is the longest word in the sentence is:");
CaptalizeString obj=new CaptalizeString();
//obj.getCaps();
//obj.getNext();
obj.longestWord(s1);
System.out.println(obj.longestWord(s1));
}
public void getCaps() {
int length;
Scanner st=new Scanner(System.in);
strg=new String();
strg=st.nextLine();
str1= strg.toCharArray();
str1[0]=(char)(str1[0]-32);
for(int i=1;i<str1.length;i++)
{
if(str1[i-1]==' ') {
str1[i]=(char)(str1[i]-32);
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]);
}
}
public void getNext() {
int e;
Scanner st=new Scanner(System.in);
System.out.println("Enter input string");
strg=new String();
strg=st.nextLine();
str1= strg.toCharArray();
for(int i=0;i<str1.length;i++)
{
e=str1[i];
if(e>96 && e<122)
str1[i]=(char)(str1[i]+1);
else if(e=='z')
str1[i]='a';
if(str1[i]=='a'||str1[i]=='e'||str1[i]=='i'||str1[i]=='o'||str1[i]=='u')
str1[i]=(char)(str1[i]-32);
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]);
}
}
public String longestWord(String str)
{
String s="",maxWord="";
int maxlen=0,p=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)!=' ')
{
s=s+str.charAt(i);
}
else
{
p=s.length();
if((int) p>maxlen)
{
maxlen=p;
maxWord=s;
}
s="";
}
}
return maxWord;
}
}
<file_sep>/Day2/StringClass.java
import java.util.Scanner;
public class StringClass {
public static void main(String[] args) {
String str;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the value of string:");
str=scanner.next();
for (int i=0;i<5;i++) {
for(int j=0;j<=i;j++) {
System.out.print(str.charAt(j));
System.out.print("\t");
}
System.out.println();
}
}}<file_sep>/Day5/Student.java
package org.capgemini.com;
public interface Student {
void displayGrade();
void attendance();
}
<file_sep>/Day5/TestClass.java
package org.capgemini.com;
public class TestClass {
public static void main(String[] args) {
Pg_Student pg=new Pg_Student();
pg.displayGrade();
pg.attendance();
if(pg.grade=='A' && pg.att_score==10)
{
System.out.println("Docterate");
}else
System.out.println("Better Luck next time:)");
Ug_Student ug=new Ug_Student();
ug.displayGrade();
ug.attendance();
if(ug.grade=='A' && ug.att_score==10)
{
System.out.println("Finally ur Engineering done");
}
else
System.out.println("Better Luck next time:)");
}
}
<file_sep>/Day5/Pg_Student.java
package org.capgemini.com;
import java.util.Scanner;
public class Pg_Student implements Student {
int marks;
int days_attended;
int att_score;
char grade;
Scanner scan =new Scanner(System.in);
@Override
public void displayGrade() {
System.out.println("Enter marks of Pg student ");
marks=scan.nextInt();
if(marks>=90)
{
grade='A' ;
}
else if(marks>=80&&marks<90)
{
grade='B' ;
}
else if(marks>=70&&marks<80)
{
grade='C' ;
}
else if(marks>=60&&marks<70)
{
grade='D' ;
}
else
System.out.println("Thesis should be repeated");
}
@Override
public void attendance() {
// TODO Auto-generated method stub
System.out.println("Enter attendance in days for Pg student ");
days_attended=scan.nextInt();
if (days_attended==30)
{
System.out.println("Full attendence");
att_score=10;
}
else if(days_attended>15 && days_attended<30)
{
att_score=7;
}
else
att_score=4;
}
}
<file_sep>/README.md
# Suman-Rav-159819
<file_sep>/Day3/SortArray1.java
public class SortArray1 {
int arr[][]= {{1,2,3},{-1,1,5},{5,6,0}};
public static void main(String[] args) {
int rum[]= {1,3,4};
SortArray1 obj =new SortArray1();
obj.getSortArray(rum);
}
public void getSortArray(int[] rum) {
int row=0;
int column=0;
for(int i=0;i<row;i++) {
for(int j=0;j<column;j++) {
if(rum[i]==(rum[i]+1)) {
System.out.println("No missing element");
}
else
System.out.print((rum[i]+1));
}
}
}
}
<file_sep>/Day2/Que8.java
package org.capgemini.com;
import java.util.Scanner;
public class Que8 {
String str1="",str2="";
char[] arr1=new char[str1.length()];
char[] arr2=new char[str2.length()];
public void anagram(String str1,String str2)
{
str1=str1.toLowerCase();
str2=str2.toLowerCase();
arr1=str1.toCharArray();
arr2=str2.toCharArray();
for(int i=0;i<str1.length();i++)
{
for(int j=0;j<str2.length();j++)
{
if(arr1[i]==arr2[j]||arr1[i]==arr2[j]+32)
{
arr2[j]=' ';
arr1[i]=' ';
}
}
}
for(int i=0;i<str1.length();i++)
{
if(arr1[i]==arr2[i])
{
System.out.println("Anagram");
break;
}
else
{
System.out.println("Non Anagram");
break;
}
}
}
public static void main(String[] args) {
Que8 q=new Que8();
Scanner s= new Scanner(System.in);
System.out.println("enter string1");
q.str1=s.nextLine();
System.out.println("enter string2");
q.str2=s.nextLine();
q.anagram(q.str1,q.str2);
s.close();
}
}
<file_sep>/Day5/Interface1.java
package org.capgemini.com;
import java.util.Scanner;
public interface Interface1 {
int num=200;
default int getElement()
{
Scanner scan=new Scanner(System.in);
// num=scan.nextInt();
System.out.println("Enetr two numbers");
int anum=scan.nextInt();
int bnum=scan.nextInt();
return anum+bnum;
}
default void printElement()
{
//int res=getElement();
System.out.println("Final variable num value is costatnt"+num);
}
}
<file_sep>/Day4/Anagram.java
import java.util.Scanner;
public class Anagram {
public void anagram1(String str1,String str2) {
char[] arr1=new char[str1.length()];
char[] arr2=new char[str2.length()];
for(int i=0;i<str1.length();i++)
{
arr1[i]=str1.charAt(i);
}
for(int i=0;i<str2.length();i++)
{
arr2[i]=str2.charAt(i);
}
if(str1.length()!=str2.length())
System.out.println("not an anagram");
char temp;
for(int i=0;i<str1.length();i++)
{
for(int j=i+1;j<arr1.length;j++)
{
if(arr1[i]>arr1[j])
{
temp=arr1[i];
arr1[i]=arr1[j];
arr1[j]=temp;
}
}
}
for(int i=0;i<str2.length();i++)
{
for(int j=i+1;j<arr2.length;j++)
{
if(arr2[i]>arr2[j])
{
temp=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp;
}
}
}
for(int i=0;i<str2.length();i++)
{
if(arr1[i]!=arr2[i])
{System.out.println("not an anagram");
break;
}
else
{System.out.println("anagram");
break;}
}
}
public static void main(String[] args) {
Anagram obj=new Anagram();
Scanner s=new Scanner(System.in);
String str1,str2;
System.out.println("Enter a string");
str1=s.nextLine();
System.out.println("Enter another string");
str2=s.nextLine();
obj.anagram1(str1,str2);
s.close();
}
} | db9ac43154173025aa84237a137d8b716b531f4e | [
"Markdown",
"Java"
] | 11 | Java | ppaushya/Suman-Rav-159819 | 3ea78bbe885097499d107fdc5ad4c3b901324ea3 | 26819b0fb2ddc8ab56eabadda5161b066088ca07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.