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
/**
* Select category for upcoming events
*/
class TlThemeEventsWidget extends WP_Widget {
/**
* Constructor
*/
public function __construct() {
$widget_ops = array('classname' => 'widget-news-events',
'description' => __( 'Mazzareli - News and Events', 'tl_theme_admin'));
parent::__construct(
'tl_theme_upcoming_events',
__('Mazzareli - News and Events Widget','tl_theme_admin'),
$widget_ops
);
}
/**
* Outputs the options form on admin
* @see WP_Widget::form()
* @param $instance current settings
*/
public function form( $instance ) {
//Get Posts from first category (current one)
$default = array(
'title' => 'News and Events',
'current_cat' => null
);
$instance = wp_parse_args((array) $instance, $default);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'tl_theme_admin'); ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" value="<?php echo esc_attr($instance['title']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('current_cat'); ?>"><?php _e('Category of posts', 'tl_theme_admin'); ?></label><br />
<?php
wp_dropdown_categories(array('selected'=>$instance['current_cat'],
'name'=> $this->get_field_name('current_cat'),
'id'=> $this->get_field_id('current_cat'),
'class'=>'widefat',
'show_count'=>true,
'hide_empty'=>false,
'orderby'=>'name'));
?>
</p>
<?php
}
/**
* processes widget options to be saved
* @see WP_Widget::update()
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
if(empty($old_instance)){
$old_instance = $new_instance;
}
foreach ($old_instance as $k => $value) {
$instance[$k] = trim(strip_tags($new_instance[$k]));
}
return $instance;
}
/**
* Front-end display of widget.
* @see WP_Widget::widget()
* @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
* @param array $instance The settings for the particular instance of the widget
*/
public function widget( $args, $instance ) {
extract( $args );
//Get two leatest posts from upcoming Events Category
$args = array(
'numberposts' => 2,
'category' => $instance['current_cat'],
'orderby' => 'post_date',
'order' => 'DESC',
'suppress_filters' => false);
global $post;
$tmp_post = $post;
$posts = get_posts( $args );
$title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
echo $before_widget;
?>
<?php if($title): echo $before_title . $title . $after_title; endif; ?>
<ul>
<?php foreach ($posts as $post): ?>
<li>
<p class="meta"><?php echo get_the_date('j F | Y'); ?></p>
<h3 class="title">
<a title="<?php echo $post->post_title; ?>" href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a>
</h3>
<?php $text = apply_filters('widget_text', $post->post_content); ?>
<div class="excerpt"><p><?php echo mls_abstract($text, 12); ?></p></div>
</li>
<?php endforeach; $post = $tmp_post; ?>
</ul>
<?php
echo $after_widget;
}
} //Class End
register_widget('TlThemeEventsWidget');<file_sep><?php
abstract class ThemeSlider
{
/**
* Slider Type
* @var unknown_type
*/
public $type = '';
/**
* Slider name
* @var unknown_type
*/
public $name = '';
/**
* All settings related to slider, loaded form DB
* @var unknown_type
*/
protected $settings = '';
/**
* Array of slides
* @var unknown_type
*/
protected $slides = array();
/**
* Category id of scroller from the right
* @var unknown_type
*/
public $category_id = null;
/**
* Array of posts related to a scroller from the right
* @var unknown_type
*/
protected $posts = array();
/**
* Rendered output for scroller
* @var unknown_type
*/
public $post_output = '';
/**
* Renedered output for slider witout scroller
* Enter description here ...
* @var unknown_type
*/
public $slider_output = '';
/**
* Handle related to a JS file for slider
* Enter description here ...
* @var unknown_type
*/
protected $js_handle = '';
/**
* Name of the CSS class related to layout. If scroller turn on => "c-8" otherwise "c-12"
* Enter description here ...
* @var unknown_type
*/
protected $slider_container_class = 'c-12'; // 2/3 width
/**
* Render SLider
* @param boolean $echo
*/
abstract public function _renderSlider ();
/**
* Enqueue all scripts and CSS related to a slider and scroller. Override it in sub class.
* @throws Exception
*/
abstract public function enqueueScripts();
/**
*
* Enter description here ...
* @param int $category_id post category
* @param array $posts array of post objects
* @param array $settings slider settings
* @param array $slides slide settings
* @param boolean $force_reload force post reloading
*/
public function __construct ($settings, $slides)
{
$this->settings = $settings;
$this->slides = $slides;
$this->slider_container_class = 'c-12'; //Full width
}
/**
* Render shole thing
*/
public function render(){
$output = '';
$output = $this->_renderSlider();
return '<div id="slider" class="'.$this->type.'">' . $output . '</div>';
}
protected function _renderCategoryScroller ()
{
$per_page = Data()->getMain('mi_home.scroller_items_num');
$o = '';
if ($this->_hasPosts()) {
$n = (int) ceil(count($this->posts) / $per_page);
for ($i = 0; $i < $n; $i ++) { //"Goes by pages - Paginations"
$o .= '<ul>';
for ($k = $i * $per_page; $k < $i * $per_page + $per_page; $k ++) {
if(!isset($this->posts[$k])) break;
if(strlen($this->posts[$k]->post_title) > 40)$this->posts[$k]->post_title = substr($this->posts[$k]->post_title, 0, 38) . '...';
$o .= '<li><h3><a href="' . get_permalink($this->posts[$k]->ID) .
'" title="' . $this->posts[$k]->post_title . '">' .
$this->posts[$k]->post_title . '</a></h3>
'.the_subtitle($this->posts[$k]->ID) .'
</li>'."\n";
}
$o .= '</ul>'."\n";
}
}
$this->post_output = '<div class="c-4">
<div id="cat-slider">
<h2>' . Data()->getMain('mi_home.scroller_title') . '</h2>
<span class="devider"></span>
<div id="scroller">
' . $o . '
</div><!-- END scroller -->
<span class="up-arrow" title="Next"></span>
<span class="down-arrow" title="Previous"></span>
</div> <!-- end cat-slider -->
</div>';
return $this->post_output;
}
/**
* Does scroller exists
*/
protected function _hasCatScroller ()
{
return ($this->scroller_source === null) ? false : true;
}
/**
* Do we have posts loaded?
*/
protected function _hasPosts ()
{
return count($this->posts) > 0;
}
/**
* Loads post from specified category. Posts realted to a scroller.
*/
protected function _loadPosts ()
{
$posts = get_posts(array('numberposts' => 999, 'category' => $this->scroller_source));
$this->posts = $posts;
return $posts;
}
/*Load Specifiend pages */
protected function _loadPages(){
$pages = get_pages(array('include'=>$this->scroller_source, 'hierarchical'=>0,'sort_order' => 'ASC', 'sort_column' => 'menu_order','post_status'=>'publish'));
$this->posts = $pages;
return $pages;
}
} // End of class<file_sep><?php get_header(); ?>
<div id="intro">
<div class="wrap">
<div class="error-404">
<h1><?php echo Data()->getMain('mi_misc.mi_404'); ?></h1>
</div><!-- end error-404 -->
</div><!-- end wrap -->
</div><!-- end intro -->
<div id="content">
<div class="error-404 wrap">
<p>
<?php echo Data()->getMain('mi_misc.mi_404_text'); ?>
</p>
<h3><?php _e('Try one of the following', 'tl_theme'); ?>:</h3>
<ul class="bullets">
<li><?php _e('Go to', 'tl_theme'); ?> <a href="<?php echo home_url('/'); ?>"><?php _e('homepage', 'tl_theme'); ?></a></li>
<li><?php _e('Contact us via ', 'tl_theme'); ?> <a href="mailto:<?php echo Data()->getMain('mi_contact.email'); ?>"><?php echo Data()->getMain('mi_contact.email'); ?></a></li>
</ul>
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div><!-- end error-404 -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
*
* Theme Shortcodes
* @author milos
*
*/
class ThemeShortCodes {
public static $_instance = null;
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
if (null === self::$_instance)
{
self::$_instance = new ThemeShortCodes();
}
return self::$_instance;
}
public function init(){
//Remove default WP gallery shortcode
//remove_shortcode('[gallery]');
add_shortcode('raw' , array(&$this, 'themeRaw'));
add_shortcode('mls_mark' , array(&$this, 'themeMarkText'));
add_shortcode('mls_dropcap' , array(&$this, 'themeDropCap'));
add_shortcode('mls_btn' , array(&$this, 'themeBtn'));
add_shortcode('mls_blockquote' , array(&$this, 'themeBlockQuote'));
add_shortcode('mls_quoteleft' , array(&$this, 'themeQuoteLeft'));
add_shortcode('mls_quoteright' , array(&$this, 'themeQuoteRight'));
add_shortcode('mls_iframe', array(&$this, 'themeIframe'));
add_shortcode('mls_yt', array(&$this, 'themeYoutube'));
add_shortcode('mls_vimeo', array(&$this, 'themeVimeo'));
add_shortcode('mls_msg' , array(&$this, 'ThemeMessageShortcode'));
add_shortcode('mls_h1' , array(&$this, 'themeH1'));
add_shortcode('mls_h2' , array(&$this, 'themeH2'));
add_shortcode('mls_h3' , array(&$this, 'themeH3'));
add_shortcode('mls_h4' , array(&$this, 'themeH4'));
add_shortcode('mls_h5' , array(&$this, 'themeH5'));
/* Todo */
//add_shortcode('mls_center', array(&$this, 'themeAlignCenter'));
//add_shortcode('mls_tabele', array(&$this, 'themeTable'));
add_shortcode('mls_bullet_list', array(&$this, 'themeList1'));
add_shortcode('mls_star_list' , array(&$this, 'themeList2'));
add_shortcode('mls_arrow_list' , array(&$this, 'themeList3'));
add_shortcode('mls_ok_list' , array(&$this, 'themeList4'));
add_shortcode('mls_o_list' , array(&$this, 'themeOrdered1'));
add_shortcode('mls_gallery' , array(&$this, 'themeGallery'));
/* Layout shortcodes */
add_shortcode('mls_onethird' , array(&$this, 'themeOneThird'));
add_shortcode('mls_onehalf' , array(&$this, 'themeOneHalf'));
add_shortcode('mls_twothird' , array(&$this, 'themeTwoThird'));
add_shortcode('mls_oneforth' , array(&$this, 'themeOneForth'));
add_shortcode('mls_threeforth' , array(&$this, 'themeThreeForth'));
add_shortcode('mls_devider', array($this, 'themeDevider'));
add_shortcode('mls_sitemap', array($this, 'themeSiteMap'));
//move wpautop filter to AFTER shortcode is processed
//add_filter('the_content', array(&$this, 'themeFormaterShortcode'), 100);
//remove_filter('the_content', 'do_shortcode', 11);
add_filter('the_content', 'tl_do_shortcode');
//add_filter('the_content', 'do_shortcode', 11);
return $this;
}
protected function shortcodeHead(){
?>
<html>
<head>
<script type="text/javascript" src="<?php echo site_url() . '/wp-includes/js/jquery/jquery.js' ?>"></script>
<script type="text/javascript" src="<?php echo TL_THEME_ADMIN_URI . '/js/shortcodefunctions.js' ?>"></script>
<script type="text/javascript" src="<?php echo TL_THEME_ADMIN_URI . '/bootstrap/js/bootstrap.js' ?>"></script>
<link rel="stylesheet" type="text/css" href="<?php echo TL_THEME_ADMIN_URI . '/css/admin-style.css' ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap.css' ?>" />
<link rel="stylesheet" type="text/css" href="<?php echo TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap-responsive.css' ?>" />
</head>
<body>
<?php
}
protected function shortcodeFooter(){
echo '</body></html>';
}
/**
* Generate UI options for Shortcodes
*/
public function ajaxShortcode(){
AdminSetup::getInstance()->enforce_restricted_access();
$shortcode = sanitize_text_field(trim($_GET['sc']));
$selectedContent = isset($_GET['selectedContent'])? trim($_GET['selectedContent']) : '';
$this->shortcodeHead();
/* On button click Call JS shortcode logic to format and insert staff in to the psot */
$response = '';
$response .= '<div id="theme-panel-wrapper" style="background-image:none;">';
$response .= '<form method="post" class="form-horizontal">';
$response .= '<div class="control-group theme-section well-no-shadow">';
$response .= '<label class="control-label">%s<br></label>';
$response .= '</div>';
$response .= '<script type="text/javascript">
jQuery("body").on("click", "a.mls_send_to_editor",{"selectedContent":"'.$selectedContent.'"}, '.$shortcode.');
var win = window.dialogArguments || opener || parent || top;
</script>';
$o = ShortcodeButton::getInstance();
$fields = $o->getConf($shortcode);
$response = sprintf($response, __('Shortcode Options', 'tl_theme'));
$ta = ThemeAdmin::getInstance()->init();
foreach ($fields as $f) {
$response .= $ta->parseField($f);
}
$response .= ' <div class="control-group dinamic-field"><a class="btn mls_send_to_editor" href="#">'.__('Insert','tl_theme').'</a></div>';
$response .= '</form></div>';
echo $response;
$this->shortcodeFooter();
exit;
}
/* Simple Shortcodes */
public function themeH1($atts, $content){
return '<h1>' . tl_do_shortcode($content) .'</h1>';
}
public function themeH2($atts, $content){
return '<h2>' . tl_do_shortcode($content) .'</h2>';
}
public function themeH3($atts, $content){
return '<h3>' . tl_do_shortcode($content) .'</h3>';
}
public function themeH4($atts, $content){
return '<h4>' . tl_do_shortcode($content) .'</h4>';
}
public function themeH5($atts, $content){
return '<h5>' . tl_do_shortcode($content) .'</h5>';
}
public function themeAlignCenter($atts, $content){
return $content;
}
public function themeDevider($atts, $content){
return '<div class="example"></div>';
}
/* Layout Shortcodes */
public function themeOneHalf($atts, $content){
extract(shortcode_atts(array(
'first' => 'no',
), $atts));
if($first == 'no'){
return '<div class="cs-6">'.tl_do_shortcode($content).'</div>';
}
else{
return '<div class="cs-6 first">'.tl_do_shortcode($content).'</div>';
}
}
public function themeOneThird($atts, $content){
extract(shortcode_atts(array(
'first' => 'no',
), $atts));
if($first == 'no'){
return '<div class="cs-4">'.tl_do_shortcode($content).'</div>';
}
else{
return '<div class="cs-4 first">'.tl_do_shortcode($content).'</div>';
}
}
public function themeTwoThird($atts, $content){
extract(shortcode_atts(array(
'first' => 'no',
), $atts));
if($first == 'no'){
return '<div class="cs-8">'.tl_do_shortcode($content).'</div>';
}
else{
return '<div class="cs-8 first">'.tl_do_shortcode($content).'</div>';
}
}
public function themeOneForth($atts, $content){
extract(shortcode_atts(array(
'first' => 'no',
), $atts));
if($first == 'no'){
return '<div class="cs-3">'.tl_do_shortcode($content).'</div>';
}
else{
return '<div class="cs-3 first">'.tl_do_shortcode($content).'</div>';
}
}
public function themeThreeForth($atts, $content){
extract(shortcode_atts(array(
'first' => 'no',
), $atts));
if($first == 'no'){
return '<div class="cs-9">'.tl_do_shortcode($content).'</div>';
}
else{
return '<div class="cs-9 first">'.tl_do_shortcode($content).'</div>';
}
}
/* Lists */
public function themeList1( $atts, $content = null ) {
return '<ul class="bullets">' . tl_do_shortcode($content) . '</ul>';
}
public function themeList2( $atts, $content = null ) {
return '<ul class="stars">' . tl_do_shortcode($content) . '</ul>';
}
public function themeList3( $atts, $content = null ) {
return '<ul class="arrows">' . tl_do_shortcode($content) . '</ul>';
}
public function themeList4( $atts, $content = null ) {
return '<ul class="checklist">' . tl_do_shortcode($content) . '</ul>';
}
public function themeOrdered1( $atts, $content = null ) {
return '<ol class="list">' . tl_do_shortcode($content) . '</ol>';
}
/* Tables */
public function themeTable($atts, $content){
return $content;
}
public function themeBlockQuote($atts, $content){
return '<blockquote>' . tl_do_shortcode($content) . '</blockquote>';
}
public function themeQuoteLeft($atts, $content){
$content = '<span class="pullquote left">' . tl_do_shortcode($content) . '</span>';
return $content;
}
public function themeQuoteRight($atts, $content){
$content = '<span class="pullquote right">' . tl_do_shortcode($content) . '</span>';
return $content;
}
/*
* @todo Add color classes in styles file
*/
public function themeMarkText($atts, $content){
return '<span class="mark">' . $content . '</span>';
}
public function themeDropCap($atts, $content){
return '<span class="dropcap">'.$content.'</span>';
}
public function themeBtn($atts, $content){
extract(shortcode_atts(array(
'color' => 'red',
'target' => '_self',
'link' => '#'
), $atts));
return '<p><a target="'.$target.'" href="'.$link.'" class="button '.$color.'"><span>'.$content.'</span></a></p>';
}
public function themeIframe($atts) {
extract(shortcode_atts(array(
'url' => 'http://',
'scrolling' => 'auto',
'width' => '100%',
'height' => '500',
'frameborder' => '0',
'marginheight' => '0'
), $atts));
return '<iframe src="'.$url.'" scrolling="'.$scrolling.'" width="'.$width.'" height="'.$height.'" frameborder="'.$frameborder.'" marginheight="'.$marginheight.'"></iframe>';
}
public function ThemeMessageShortcode($atts, $content){
extract( shortcode_atts( array(
'type' => 'info',
), $atts ) );
switch ($type){
case 'success' :
$content = '<p class="message success">' . tl_do_shortcode($content) . '</p>';
break;
case 'info' :
$content = '<p class="message info">' . tl_do_shortcode($content) . '</p>';
break;
case 'warning' :
$content = '<p class="message warning">' . tl_do_shortcode($content) . '</p>';
break;
case 'error' :
$content = '<p class="message error">' . tl_do_shortcode($content) . '</p>';
break;
}
return $content;
}
public function themeRaw($atts, $content){
return str_replace(array('[', ']'), array('[',']'), $content);
}
/* In case we envelope content into a [raw] tag, no filters applied*/
/*public function themeFormaterShortcode($content){
// $content = trim( do_shortcode( shortcode_unautop( $content ) ) );
$content = trim(do_shortcode(shortcode_unautop($content)));
if ( substr( $content, 0, 4 ) == '' )
$content = substr( $content, 4 );
if ( substr( $content, -3, 3 ) == '' )
$content = substr( $content, 0, -3 );
$content = str_replace( array( '<p></p>' ), '', $content );
$content = str_replace( array( '<p> </p>' ), '', $content );
return $content;
}*/
/* Insert Youtube Video Clip */
public function themeYoutube($atts){
extract( shortcode_atts( array(
'yt_width' => 480,
'yt_height' => 320,
'yt_url' => ''
), $atts ) );
preg_match('/\/([^\/]+)$/i', $yt_url, $m);
return '<iframe width="'.$yt_width.'" height="'.$yt_height.'" src="http://www.youtube.com/embed/'.$m[1].'" frameborder="0" allowfullscreen></iframe>';
}
/* Insert Vimeo Video Clip */
public function themeVimeo($atts){
extract( shortcode_atts( array(
'vm_width' => 480,
'vm_height' => 320,
'loop' => '0',
'autoplay' => '0',
'frameborder' => '0',
'allowFullScreen' => 1
), $atts ) );
if($allowFullScreen == 1){
$allowFullScreen = 'webkitAllowFullScreen mozallowfullscreen allowFullScreen';
}else{
$allowFullScreen = '';
}
return '<iframe src="http://player.vimeo.com/video/'. $id .'?autoplay='.$autoplay.'&loop='.$loop.'" width="'.$width.'" height="'.$height.'" frameborder="'.$frameborder.'" '.$allowFullScreen.' ></iframe>';
}
/* Advanced Shortcodes */
/**
* Render Gallery
* @param array $atts
*
* [mls_gallery id=1 title='on' pic_title='off']
*/
public function themeGallery($atts)
{
global $post;
$content = '';
extract( shortcode_atts( array(
'id' => null,
'cols' => 'small-thumbs',
'g_title' => 'on', //Whole gallery title
'title' => 'on', //Picture title
'subtitle' => 'on', // Picture Subtitle
'desc' => 'off' //Picture description
), $atts ) );
/**
* In case we are dealing with 3 or more cols title, subtitle and desc are for whole page.
* In case of 1 or two cols, every particular pic has it
*/
if($id){
$gal_post = get_posts( array(
'p' => $id,
'post_type' => 'mlsgallery',
'post_status' => 'publish' ));
if(!empty($gal_post)) {
$gal_post = $gal_post[0];
$pic_desc = '';
if($g_title == 'on'){
$content .= '<h2 class="portfolio-title">'.esc_attr($gal_post->post_title).'</h2>';
}
$images = get_post_meta($id, 'mls_gallery_image_ids', true);
if(!empty($images)){
$content .= '<ul class="gallery portfolio-menu">';
foreach ($images as $i => $image) {
$li_class = ' ' . $cols;
if($cols == 'wide-thumbs'){
$thumb_src = wp_get_attachment_image_src( $image['id'], 'blog-middle');
$mask_class = 'gallery-2col-mask';
$headers = '<h3 class="title"><a>'.(($title == 'on') ? $image['title']:'').'</a></h3>';
$headers .= ' <h4>'.(($subtitle == 'on') ? $image['subtitle']:'').'</h4>';
$li_class .=' c-6';
if($desc == 'on'){
$pic_desc = (isset($image['text']) && $image['text'] != '') ? '<div class="excerpt"><p>'.$image['text'].'</p></div>' : '';
}else {
$pic_desc = '';
}
}
elseif($cols == 'large-thumbs'){
$thumb_src = wp_get_attachment_image_src( $image['id'], 'blog-big');
$mask_class = 'gallery-2col-mask';
$headers = '<h3 class="title"><a>'.(($title == 'on') ? $image['title']:'').'</a></h3>';
$headers .= ' <h4>'.(($subtitle == 'on') ? $image['subtitle']:'').'</h4>';
if($desc == 'on'){
$pic_desc = (isset($image['text']) && $image['text'] != '') ? '<div class="excerpt"><p>'.$image['text'].'</p></div>' : '';
}else {
$pic_desc = '';
}
}elseif($cols == 'middle-thumbs'){
$thumb_src = wp_get_attachment_image_src( $image['id'], 'thumbnail');
$mask_class = 'gallery-3col-mask';
$headers = '';
}else{
$thumb_src = wp_get_attachment_image_src( $image['id'], 'small-thumb');
$mask_class = 'gallery-4col-mask';
$headers = '';
}
$width = $thumb_src[1];
$height = $thumb_src[2];
$image['text'] = ($desc == 'on' && isset($image['text']) && $image['text'] != '') ? $image['text'] : '';
$image['title'] = ($title == 'on' && isset($image['title']) && $image['title'] != '') ? $image['title'] : '';
$thumb_src_preview = wp_get_attachment_image_src( $image['id'], 'theme-gallery-photo');
$content .= '<li class="'.$li_class.'">';
$content .= $headers;
$content .= '<p class="image">';
$content .= '<a rel="gallery-'.$id.'" href="'.$thumb_src_preview[0].'" class="lightbox" title="'.$image['title'].'" data-desc="'.$image['text'].'">';
$content .= '<span class="'.$mask_class.'"></span>';
$content .= '<img title="'.$image['title'].'" height="'.$height.'" width="'.$width.'" alt="'.$image['title'].'" src="'.$thumb_src[0].'" rel="'.$thumb_src_preview[0].'" />';
$content .= '</a>';
$content .= '</p>';
$content .= $pic_desc;
$content .= ' </li>';
}
$content .= '</ul><div class="clearfix"></div>';
}
}//Gallery exists
}//id
return $content;
}
} // End of class
ThemeShortCodes::getInstance()->init();<file_sep><?php
/**
* Template Name: Product Page Template - no sidebar
* Description: Product Page Template
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
$show_meta = Data()->isOn('mi_product.mi_product_meta_switch');
?>
<?php get_header() ?>
<?php get_template_part( 'template', 'part-ribbon' ); ?>
<div id="content" class="product-no-sidebar">
<div class="wrap">
<div class="c-12 divider">
<div class="post-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<div class="post post-<?php the_ID(); ?>">
<?php if(has_post_thumbnail()): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'theme-gallery-photo'); ?>
<p class="image">
<a class="lightbox-standard" title="<?php the_title_attribute()?>" href="<?php echo $large_image_url[0];?>">
<?php the_post_thumbnail('blog-big'); ?>
</a>
</p>
<?php endif; ?>
<div class="product-desc">
<h2 class="title"><a href="<?php the_permalink()?>"><?php the_title(); ?></a></h2>
<?php if($show_meta): ?>
<p class="meta">
<span class="categories"><?php _e('Category','tl_theme'); ?>: <?php the_terms($post->ID,'food_type'); ?></span>
</p>
<?php endif; ?>
<?php the_content(); ?>
<p class="meta dashed">
<?php the_tags('<span class="tags">'.__('Tags', 'tl_theme').': ', ', ','</span>'); ?>
</p>
</div>
</div><!-- end post -->
<?php endwhile; ?>
<?php endif; ?>
</div><!-- end post-list -->
</div>
</div>
</div>
<?php get_footer(); ?><file_sep><?php
/**
* Gallery Custom Post Type
* @author <NAME>
* @desc
*
*/
class GalleryCustomPostType {
/**
* Post type id
* @var string
*/
protected $post_type = 'mlsgallery';
protected $meta_db_key = 'mls_gallery_image_ids';
/**
* Options for meta box
* @var array
*/
protected $options = array();
/**
* Entry point.
*/
public function init(){
// $this->registerPostType()
$this->doHooks();
return $this;
}
/**
* Register Gallery Post Type
*/
public function registerPostType(){
$labels = array(
'name' => __('Galleries', 'Galleries', 'tl_theme_admin'),
'singular_name' => __('Gallery Item', 'Gallery', 'tl_theme_admin'),
'add_new' => __('Add New', 'Add New Gallery Name', 'tl_theme_admin'),
'add_new_item' => __('Add New Gallery', 'tl_theme_admin'),
'edit_item' => __('Edit Gallery', 'tl_theme_admin'),
'new_item' => __('New Gallery', 'tl_theme_admin'),
'view_item' => __('View Gallery', 'tl_theme_admin'),
'search_items' => __('Search Gallery', 'tl_theme_admin'),
'not_found' => __('Nothing found', 'tl_theme_admin'),
'not_found_in_trash' => __('Nothing found in Trash', 'tl_theme_admin'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 5,
'supports' => array('title','author','thumbnail','excerpt')
);
register_post_type($this->post_type, $args);
flush_rewrite_rules();
return $this;
}
/**
* Create Meta box for gallery custom type
*/
public function doGalleryOptions(){
add_meta_box('gallery_post_type_option',
__('Gallery Options', 'tl_theme' ),
array(&$this, 'renderOptions'), //fja koja daje renderuje opcije
$this->post_type, //post type id
'normal',
'high');
return $this;
}
public function renderOptions(){
global $post_id;
// Use nonce for verification
wp_nonce_field( plugin_basename(__FILE__), ThemeSetup::HOOK . '_gallery_noncename' );
echo '<div class="custom-admin-theme-css">';
echo '<div class="inside">';
$this->getMediaImage();
echo '</div>';
echo '</div>';
}
/**
* Ajax Handler for loading an images in Metabox.
*/
protected function doHooks(){
add_action('init', array(&$this, 'registerPostType'));
add_action('add_meta_boxes', array(&$this, 'doGalleryOptions'));
add_action('wp_ajax_get_media_image', array(&$this, 'getMediaImage'));
add_action('save_post', array(&$this, 'doGSaveData'));
return $this;
}
public function getMediaImage(){
global $post_id;
$image_width = 110;
$paged = (isset($_POST['page']))? $_POST['page'] : 1;
if($paged == ''){ $paged = 1; }
$paged = (int) $paged;
$statement = array('post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' =>10,
'nopaging ' => false,
'paged' => $paged);
//Get all images from WP media center
$media_query = new WP_Query($statement);
$data = get_post_meta($post_id, $this->meta_db_key, true);
$selected_imgs = '';
// Do selected images
if(is_array($data) && !empty($data)){
foreach ($data as $i_key=>$item) {
$thumb_src = wp_get_attachment_image_src( $item['id'], 'thumbnail');
$thumb_src_preview = wp_get_attachment_image_src( $item['id'], 'medium');
$selected_imgs .= '<li>
<img width="'.$image_width.'" src="'.$thumb_src[0].'" rel="'.$thumb_src_preview[0].'" />
<input type="hidden" name="gallery_image_id['.$i_key.'][id]" value="'.$item['id'].'">
<input type="hidden" name="gallery_image_id['.$i_key.'][title]" value="'.$item['title'].'">
<input type="hidden" name="gallery_image_id['.$i_key.'][subtitle]" value="'.$item['subtitle'].'">
<input type="hidden" name="gallery_image_id['.$i_key.'][text]" value="'.$item['text'].'">
<a data-id="'.$item['id'].'" data-toggle="modal" data-target="#tmp_form" href="#tmp_form" class="edit-pic"><img src="'.TL_THEME_ADMIN_URI.'/images/pencil-add-icon.png"></a>
<a href="#" class="delete-pic"><img src="'.TL_THEME_ADMIN_URI.'/images/pencil-delete-icon.png"></a>
</li>';
}
}
?>
<?php if(!isset($_POST['page']) || $_POST['page'] == '') : ?>
<div id="selected-images"><ul><?php echo $selected_imgs; ?></ul></div>
<div id="media-wrapper">
<div class="media-title">
<label><?php _e('SELECT PHOTOS','tl_theme_admin'); ?></label>
</div>
<?php endif; ?>
<?php
echo '<!-- Container for selected images --><div id="image-selector"><div class="media-gallery-nav" id="media-gallery-nav">';
echo '<!-- pagination --> <ul>';
echo '<li class="nav-first" rel="1" ><a href="#">«</a></li>';
for( $i=1 ; $i<=$media_query->max_num_pages; $i++){
if($i == $paged){
echo '<li class="current" rel="' . $i . '">' . $i . '</li>';
}else if( ($i <= $paged+2 && $i >= $paged-2) || $i%10 == 0){
echo '<li rel="' . $i . '"><a href="#">' . $i . '</a></li>';
}
}
echo '<li class="nav-last" rel="' . $media_query->max_num_pages . '"><a href="#">»</a></li>';
echo '</ul><!-- pagination end -->';
echo '</div><br class="clear">';
echo "<div class='loading' style='display:none;height: 90px; width:100%; text-align:center; position:absolute; bottom:0px;'>Loading...</div>";
echo '<ul class="thumbs">';
foreach( $media_query->posts as $image ){
$thumb_src = wp_get_attachment_image_src( $image->ID, 'thumbnail');
$thumb_src_preview = wp_get_attachment_image_src( $image->ID, 'medium');
echo '<li>
<img width="70" src="' . $thumb_src[0] .'" attid="' . $image->ID . '" rel="' . $thumb_src_preview[0] . '"/>
</li>';
}
echo '</ul><br class="clear"></div>';
//This is hidden
echo '<div id="tmp_form" style="display:none;" class="modal hide fade">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 style="background:none; border: none;">' . __("Photo Data","tl_theme_admin") . '</h3>
</div>
<div class="modal-body">
<label>'.__("Image Title","tl_theme_admin").'<br /><input style="width:300px" type="text" name="tmp_title" /></label><br />
<label>'.__("Image Subtitle","tl_theme_admin").'<br /><input style="width:300px" type="text" name="tmp_subtitle" /></label><br />
<label>'.__("Image Description","tl_theme_admin").'<br /><textarea style="width:525px; height: 220px" name="tmp_text" /></textarea></label><br />
<input type="button" name="commit" value="'.__("Add", "tl_theme_admin").'" />
</div>
<div class="modal-footer">
<p>Theme Laboratory</p>
</div>
</div>';
?>
<?php if(!isset($_POST['page']) || $_POST['page'] == '') : ?>
</div><!-- #media-wrapper -->
<?php endif; ?>
<?php
if(isset($_POST['page'])){ die(''); }
}
/**
* Save All data realated to this metabox
* Enter description here ...
* @param unknown_type $post_id
*/
public function doGSaveData($post_id){
if(empty($_POST) || !isset($_POST['gallery_image_id']) || !isset($post_id)) return $post_id;
$post_data = get_post($post_id);
if($post_data->post_type != 'mlsgallery') return ;
if(!isset($_POST[ThemeSetup::HOOK . '_gallery_noncename'])) return $post_id;
$nonce = check_ajax_referer(plugin_basename(__FILE__), ThemeSetup::HOOK . '_gallery_noncename', false);
if ($nonce === false){
die("IM DIEYING");
}
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
if ( !current_user_can( 'edit_page', $post_id ) ){
return $post_id;
}
else {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
$data = array();
//Collect Input and add/update post meta
foreach($_POST['gallery_image_id'] as $id => $img){
$img['id'] = (int) $img['id'];
$img['title'] = strip_tags(trim($img['title']));
$img['subtitle'] = strip_tags(trim($img['subtitle']));
$img['text'] = esc_textarea(trim($img['text']));
if($img['id'] > 0){
$data[] = $img;
}
}
$old_data = get_post_meta($post_id, $this->meta_db_key, true);
if($old_data =='') $old_data = array();
//save_meta_data($post_id, $data, $old_data, $this->meta_db_key);
if($data == $old_data){
add_post_meta($post_id, $this->meta_db_key, $data, true);
}else if(!$data){
delete_post_meta($post_id, $this->meta_db_key, $old_data);
}else if($data != $old_data){
update_post_meta($post_id, $this->meta_db_key, $data, $old_data);
}
}
} // Class End
$gallery_type = new GalleryCustomPostType();
$gallery_type->init(); <file_sep><?php
/**/
class FrameworkException extends Exception{
public function __construct(){
parent::__construct();
}
}<file_sep><?php
// $show_meta = Data()->isOn('mi_event.mi_event_meta_switch');
$hide_cats = Data()->getMain('mi_blog.hide_cats');
get_header(); ?>
<?php get_template_part( 'template', 'part-ribbon' ); ?>
<div id="content">
<div class="wrap">
<div class="c-8 divider">
<div class="post-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<?php $meta_values = eventsMetaData($post->ID); ?>
<div class="post events dashed post-<?php the_ID(); ?>">
<h2 class="title"><a href="<?php the_permalink()?>"><?php the_title(); ?></a></h2>
<ul class="events-calendar">
<li class="day"><?php echo $meta_values['day'] ?></li>
<li><?php echo $meta_values['month'] ?></li>
</ul>
<p class="meta">
<span><?php _e('Date', 'tl_theme'); ?>: <a class="time" href="#"><?php echo $meta_values['month'].' '.$meta_values['day'] .' '.$meta_values['year'].', ' . $meta_values['hours']; ?></a></span>
<span><?php _e('Place', 'tl_theme'); ?>: <a class="author" href="#"><?php echo $meta_values['place'] ?> </a></span>
<span><?php _e('No. participants', 'tl_theme'); ?>: <a class="author" href="#"><?php echo $meta_values['no_participants'] ?> </a></span>
</p>
<?php // endif; ?>
<?php if(has_post_thumbnail()): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'theme-gallery-photo'); ?>
<p class="image">
<a class="lightbox-standard" title="<?php the_title_attribute()?>" href="<?php echo $large_image_url[0];?>">
<?php the_post_thumbnail('blog-big'); ?>
</a>
</p>
<?php endif; ?>
<?php the_content(); ?>
</div><!-- end post -->
<?php endwhile; ?>
<?php endif; ?>
</div><!-- end post-list -->
</div>
<?php get_sidebar('eventtype'); ?>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php if(Data()->isOn('mi_footer.mi_footer2_switch')): ?>
<div id="footer">
<div class="wrap">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("home_sidebar2") ) : ?><?php endif; ?>
</div><!-- end wrap -->
</div><!-- end footer -->
<?php endif; ?>
<div id="subfooter">
<div class="wrap">
<div class="c-6">
<?php if(Data()->isOn('mi_footer.mi_copyright_switch')):?>
<p id="copyright">©<?php echo Data()->getMain('mi_footer.mi_copyright'); ?></p>
<?php else: ?>
<p></p>
<?php endif; ?>
</div>
<div class="c-6">
<ul class="subfooter-menu">
<?php if(Data()->isOn('mi_footer.mi_terms_switch')): ?>
<li><a href="<?php echo Data()->getMain('mi_footer.mi_terms'); ?>" title="<?php __('Terms and Conditions', 'tl_theme'); ?>"><?php ?>Terms & Conditions</a></li>
<?php endif; ?>
<?php if(Data()->isOn('mi_footer.mi_terms_switch')): ?>
<li><a href="<?php echo Data()->getMain('mi_footer.mi_copyright_link'); ?>" title="<?php __('Copyrights', 'tl_theme'); ?>">Copyrights</a></li>
<?php endif; ?>
<?php if(Data()->isOn('mi_footer.mi_sitemap_switch')): ?>
<li><a href="<?php echo Data()->getMain('mi_footer.mi_sitemap_link'); ?>" title="<?php __('Site Map', 'tl_theme'); ?>">Site Map</a></li>
<?php endif; ?>
</ul>
</div>
</div><!-- end wrap -->
</div><!-- end subfooter -->
<?php
$custom_js = Data()->getMain('mi_misc.mi_custom_js');
$custom_js = stripslashes($custom_js);
?>
<!-- Custom JS -->
<script type="text/javascript">
<!--//--><![CDATA[//><!--
<?php echo $custom_js; ?>
//--><!]]>
</script>
<?php wp_footer(); ?>
</body>
</html><file_sep><?php
/**
* Template Name: Testimonials Template without sidebar
* Description: List of testimonials without sidebar
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php get_header(); ?>
<?php get_template_part( 'template', 'part-ribbon' ); ?>
<div id="content">
<div class="wrap">
<div class="c-12 divider">
<?php if(Data()->isOn('mi_testimonial.switch_title') || Data()->isOn('mi_testimonial.show_intro_text')): ?>
<div class="post-list">
<?php if(Data()->isOn('mi_testimonial.switch_title')): ?>
<h2><?php the_title(); ?></h2>
<?php endif; ?>
<?php if(Data()->isOn('mi_testimonial.show_intro_text')): ?>
<?php the_content(); ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php
global $wp_query;
$args = array( 'post_type' => 'testimonial',
'order'=>'ASC',
'orderby' => 'menu_order', 'hierarchical'=>0,
'paged' => get_query_var('paged')
);
query_posts( $args );
?>
<div class="review-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<?php $meta_values = testimonialsMetaData($post->ID); ?>
<div class="review dashed post-<?php the_ID(); ?>">
<?php the_content(); ?>
<?php if($meta_values['author']): ?>
<p class="author"><span><?php echo $meta_values['author']; ?></span> <br />
<?php echo $meta_values['additional_info']; ?>
</p>
<?php endif; ?>
</div><!-- end post -->
<?php endwhile; endif; ?>
<?php wp_pagenavi(array('class'=>'pagination',
'options'=> array('pages_text'=>' ',
'first_text' => '',
'last_text' => '',
'always_show' => false,
'use_pagenavi_css'=>false,
'prev_text' => __('Previous', 'tl_theme'),
'next_text' => __('Next', 'tl_theme'),
))
); ?>
</div><!-- end .review-list -->
</div>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?>
<file_sep><?php
/**
* Common function used in frontend and backend
*/
/**
* Handels all Ajax request from the Front. Contacts forms etc...
* Enter description here ...
*/
function mls_ajax_handler(){
$response = array('status'=>'success');
check_ajax_referer(ThemeSetup::HOOK . '-ajax-nonce-xxx', ThemeSetup::HOOK . '_ajax_nonce');
$action = '';
$sub_action = strip_tags(trim($_POST['subaction']));
switch ($sub_action){
case 'book':{
$fields = array('size'=>'*|v_text',
'date'=>'*|v_text',
'name'=>'-|v_text',
'email'=>'-|v_mail',
'phone'=>'*|v_text',
'notes'=>'-|v_text'
);
if(defined('MLS_SHOWCASE') && !MLS_SHOWCASE){
$tm = new ThemeMailer($fields, 'book');
$resp = $tm->doMagic();
$response = $tm->getJsonResponse();
}else{
$response['data']['msg'] = __('Sending E-mails not allowed.', 'tl_theme');
}
break;
}
case 'contact':{
//Validation map. Fields with "*" are obligatory!
$fields = array('name' => '*|v_text',
'email' => '*|v_mail',
'subject' => '-|v_text',
'message' => '*|v_text',
'website' => '-|v_url');
if(defined('MLS_SHOWCASE') && !MLS_SHOWCASE){
$tm = new ThemeMailer($fields);
$resp = $tm->doMagic();
$response = $tm->getJsonResponse();
}else{
$response['data']['msg'] = __('Sending E-mails not allowed.', 'tl_theme');
}
break;
}
default :{
$response = array('status' => 'error', 'data'=> array('msg'=>__('Unknown request', 'tl_theme')) );
}
}
die(json_encode($response));
}
function mls_get_navigation_menu(){
$menu = '';
if(has_nav_menu('header-menu')){
$menu = wp_nav_menu( array(
'theme_location' => 'header-menu',
'container_id' => 'main-navigation',
'menu_class' => 'dd-menu',
'echo' => false
));
}
else{
$menu = wp_list_pages( array(
'depth' => 2,
'show_date' => '',
'date_format' => get_option('date_format'),
'child_of' => 0,
'number' => 5,
'title_li' => '',
'echo' => 0,
'sort_column' => 'menu_order, post_title',
'link_before' => '',
'link_after' => '',
'walker' => '' ) );
$menu = '<div id="main-navigation"><ul class="dd-menu">'.$menu.'</ul></div>';
}
return $menu;
}
/**
* List of categories
* @param array $params
*/
function mls_get_categories($params = array()){
$params = wp_parse_args($params, array('type' => 'post',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'number' => 999,
'taxonomy' => 'category'));
$data = array();
$cats = get_categories($params);
foreach ($cats as $cat) {
$data[$cat->cat_ID] = $cat->name;
}
return $data;
}
function mls_get_galleries($params = array()){
get_posts(array('post_type' => 'mlsgallery', 'post_status' => 'publish'));
$params = wp_parse_args($params, array( 'post_status' => 'publish',
'number' => 999,
'post_type' => 'mlsgallery'
));
$data = array();
$gals = get_posts($params);
foreach ($gals as $g) {
$data[$g->ID] = $g->post_title;
}
return $data;
}
/**
* Enter description here ...
* @param unknown_type $options
*/
function mls_get_pages($options = array()){
$data = array();
$default = array('sort_order' => 'ASC', 'sort_column' => 'menu_order');
$options = wp_parse_args((array)$options, $default);
$pages = get_pages($options);
foreach ($pages as $page) {
$data[$page->ID] = $page->post_title;
}
wp_reset_query();
return $data;
}
function mls_get_posts($cat_id = '', $limit=-1){
$data = array();
$args = array( 'orderby' => 'post_date', 'order' => 'DESC', 'post_status'=>'publish', 'posts_per_page'=>$limit);
if($cat_id != ''){
$args['category'] = $cat_id;
}
$posts = new WP_Query($args);
if(!empty($posts->posts)){
foreach ($posts->posts as $p){
$data[$p->ID] = $p->post_title;
}
}
wp_reset_query();
wp_reset_postdata();
return $data;
}
/* Not in use */
function mls_get_products($cat_id = '', $limit=-1){
$data = array();
$args = array( 'post_type'=>'product', 'order' => 'ASC', 'orderby' => 'title', 'post_status'=>'publish', 'posts_per_page'=>$limit);
if($cat_id != ''){
$args['category'] = $cat_id;
}
$posts = new WP_Query($args);
if(!empty($posts->posts)){
foreach ($posts->posts as $p){
$data[$p->ID] = $p->post_title;
}
}
wp_reset_query();
wp_reset_postdata();
return $data;
}
function mls_get_homepage_content($content_type, $options = array()){
$data = array();
switch($content_type){
case 'post':
$id = Data()->getMain('mi_home.featured_section_post');
if($id)
$data = get_post($id);
break;
case 'page':
$id = Data()->getMain('mi_home.featured_section_page');
if($id)
$data = get_page($id);
break;
case 'posts':
$default = array( 'orderby' => 'post_date', 'order' => 'DESC', 'post_status'=>'publish', 'posts_per_page'=>-1);
$options = wp_parse_args((array)$options, $default);
$options['cat'] = (int) $options['cat'];
$posts = new WP_Query($options);
$data = $posts->posts;
wp_reset_query();
wp_reset_postdata();
break;
case 'pages':
unset($options['category']);
$ids = Data()->GetMain('mi_home.featured_section_pages');
$default = array('sort_order' => 'ASC', 'sort_column' => 'menu_order', 'hierarchical'=>0, 'include'=>$ids);
$options = wp_parse_args((array)$options, $default);
$data = get_pages($options);
wp_reset_query();
break;
case 'products':
$ids = Data()->getMain('mi_home.featured_section_products');
foreach ($ids as $k => $id) {
$ids[$k] = (int) $id;
}
$default = array('post_type' => 'product', 'order' => 'ASC', 'orderby' => 'menu_order', 'post__in'=>$ids);
unset($options['cat']);
$options = wp_parse_args((array)$options, $default);
$posts = new WP_Query($options);
$data = $posts->posts;
wp_reset_query();
wp_reset_postdata();
break;
}
return $data;
}
function getPagesByTemplate($limit=1, $template = 'default'){
$args = array(
'meta_key' => '_wp_page_template',
'meta_value' => $template,
'number' => $limit,
'post_status'=>'publish'
);
$pages = get_pages( $args );
return $pages;
}
function get_menu_data(){
global $wpdb;
/* Get top categories that are not empty (has at least one item) */
$sql = 'SELECT '.$wpdb->terms.'.*
FROM ' . $wpdb->term_taxonomy . ' INNER JOIN '.$wpdb->termmeta.' ON ('.$wpdb->term_taxonomy.'.term_id='.$wpdb->termmeta.'.term_id)
INNER JOIN '.$wpdb->terms.' ON ('.$wpdb->terms.'.term_id='.$wpdb->term_taxonomy.'.term_id)
WHERE '.$wpdb->term_taxonomy.'.taxonomy =\'food_type\' AND '.$wpdb->term_taxonomy.'.parent=0 ';
$sql .= 'ORDER BY '.$wpdb->termmeta.'.meta_value ASC';
$top_level_cats = $wpdb->get_results($sql);
$menu = array();
foreach ($top_level_cats as $cat){
$menu[$cat->slug] = array('top_term' => $cat);
/* Get items grouped by sub terms */
/* $sql = 'SELECT '.$wpdb->terms.'.*, '.$wpdb->posts .'.* FROM '. $wpdb->term_taxonomy .'
INNER JOIN '. $wpdb->terms .' ON ('. $wpdb->term_taxonomy .'.term_id='. $wpdb->terms .'.term_id)
INNER JOIN '. $wpdb->termmeta .' ON ('. $wpdb->terms .'.term_id='.$wpdb->termmeta.'.term_id)
INNER JOIN '. $wpdb->term_relationships .' ON('. $wpdb->term_taxonomy .'.term_taxonomy_id='. $wpdb->term_relationships .'.term_taxonomy_id)
INNER JOIN '. $wpdb->posts .' ON('. $wpdb->term_relationships .'.object_id='. $wpdb->posts .'.ID AND '. $wpdb->posts .'.post_status=\'publish\')
WHERE '. $wpdb->term_taxonomy .'.taxonomy=\'food_type\' AND '. $wpdb->term_taxonomy .'.parent='.$cat->term_id.' AND
'. $wpdb->term_taxonomy .'.count > 0
ORDER BY '.$wpdb->termmeta.'.meta_value ASC, '. $wpdb->posts .'.menu_order ASC';*/
$sql = '(SELECT '.$wpdb->terms.'.*, '.$wpdb->posts .'.* FROM '. $wpdb->term_taxonomy .'
INNER JOIN '. $wpdb->terms .' ON ('. $wpdb->term_taxonomy .'.term_id='. $wpdb->terms .'.term_id)
INNER JOIN '. $wpdb->termmeta .' ON ('. $wpdb->terms .'.term_id='.$wpdb->termmeta.'.term_id)
INNER JOIN '. $wpdb->term_relationships .' ON('. $wpdb->term_taxonomy .'.term_taxonomy_id='. $wpdb->term_relationships .'.term_taxonomy_id)
INNER JOIN '. $wpdb->posts .' ON('. $wpdb->term_relationships .'.object_id='. $wpdb->posts .'.ID AND '. $wpdb->posts .'.post_status=\'publish\')
WHERE '. $wpdb->term_taxonomy .'.taxonomy=\'food_type\' AND '. $wpdb->term_taxonomy .'.term_id='.$cat->term_id.'
AND '. $wpdb->term_taxonomy .'.count > 0
ORDER BY '. $wpdb->posts .'.menu_order ASC)
UNION
(SELECT '.$wpdb->terms.'.*, '.$wpdb->posts .'.* FROM '. $wpdb->term_taxonomy .'
INNER JOIN '. $wpdb->terms .' ON ('. $wpdb->term_taxonomy .'.term_id='. $wpdb->terms .'.term_id)
INNER JOIN '. $wpdb->termmeta .' ON ('. $wpdb->terms .'.term_id='.$wpdb->termmeta.'.term_id)
INNER JOIN '. $wpdb->term_relationships .' ON('. $wpdb->term_taxonomy .'.term_taxonomy_id='. $wpdb->term_relationships .'.term_taxonomy_id)
INNER JOIN '. $wpdb->posts .' ON('. $wpdb->term_relationships .'.object_id='. $wpdb->posts .'.ID AND '. $wpdb->posts .'.post_status=\'publish\')
WHERE '. $wpdb->term_taxonomy .'.taxonomy=\'food_type\' AND '. $wpdb->term_taxonomy .'.parent='.$cat->term_id.' AND
'. $wpdb->term_taxonomy .'.count > 0
ORDER BY '.$wpdb->termmeta.'.meta_value ASC, '. $wpdb->posts .'.menu_order ASC)';
$data = $wpdb->get_results($sql);
$response = array();
$current_cat = '';
foreach ($data as $d){
if($current_cat != $d->slug){
$current_cat = $d->slug;
}
$response[$d->slug][] = $d;
}
$menu[$cat->slug]['items'] = $response;
}
return $menu;
}
/**
* Get all prices ordered by food categories
*/
function get_prices($items_per_cat=2){
global $wpdb;
$data = array('cats'=>array(), 'items'=>array());
/* Get all food categories */
$sql = 'SELECT '. $wpdb->terms .'.*, '. $wpdb->posts .'.* FROM '. $wpdb->term_taxonomy .'
INNER JOIN '. $wpdb->terms .' ON ('. $wpdb->term_taxonomy .'.term_id='. $wpdb->terms .'.term_id)
INNER JOIN '. $wpdb->termmeta .' ON ('. $wpdb->terms .'.term_id='.$wpdb->termmeta.'.term_id)
INNER JOIN '. $wpdb->term_relationships .' ON('. $wpdb->term_taxonomy .'.term_taxonomy_id='. $wpdb->term_relationships .'.term_taxonomy_id)
INNER JOIN '. $wpdb->posts .' ON('. $wpdb->term_relationships .'.object_id='. $wpdb->posts .'.ID AND '. $wpdb->posts .'.post_status=\'publish\')
WHERE '. $wpdb->term_taxonomy .'.taxonomy=\'food_type\' AND
'. $wpdb->term_taxonomy .'.count > 0
ORDER BY '.$wpdb->termmeta.'.meta_value ASC, '. $wpdb->posts .'.menu_order ASC';
$data = $wpdb->get_results($sql);
$response = array();
$current_cat = '';
$cc = 0;
foreach ($data as $d){
if($current_cat != $d->slug){
$current_cat = $d->slug;
$cc = 0;
}
if($cc < $items_per_cat){
$cc++;
$response[$d->slug][] = $d;
}else{
continue;
}
}
return $response;
}
function getPricesByCategories($items_per_cat=2){
$prices = get_prices($items_per_cat);
if($prices){
$response = array();
foreach ($prices as $d){
$response[$d->slug][] = $d;
}
return $response;
}else{
return array();
}
}
function mls_get_food_types($cat_id = ''){
global $wpdb;
$data = array();
$sql = 'SELECT '. $wpdb->posts .'.* FROM '. $wpdb->posts .'
INNER JOIN '. $wpdb->term_relationships .' ON (' . $wpdb->posts .'.ID='.$wpdb->term_relationships.'.object_id)
INNER JOIN '. $wpdb->term_taxonomy .' ON ('.$wpdb->term_taxonomy.'.term_taxonomy_id='.$wpdb->term_relationships.'.term_taxonomy_id)
WHERE '.$wpdb->posts.'.post_type=\'product\' AND '. $wpdb->term_taxonomy .'.taxonomy=\'food_type\' AND '.$wpdb->posts.'.post_status=\'publish\' AND
'. $wpdb->term_taxonomy .'.count > 0';
if($cat_id){
$sql .= ' AND '.$wpdb->term_taxonomy .'.term_id = '.$cat_id;
}
$sql .= ' ORDER BY '. $wpdb->posts .'.post_title ASC';
$posts = $wpdb->get_results($sql);
if(!empty($posts)){
foreach ($posts as $p){
$data[$p->ID] = $p->post_title;
}
}
return $data;
}
function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version= "";
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
}
elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
}
elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
{
$bname = 'Internet Explorer';
$ub = "MSIE";
}
elseif(preg_match('/Firefox/i',$u_agent))
{
$bname = 'Mozilla Firefox';
$ub = "Firefox";
}
elseif(preg_match('/Chrome/i',$u_agent))
{
$bname = 'Google Chrome';
$ub = "Chrome";
}
elseif(preg_match('/Safari/i',$u_agent))
{
$bname = 'Apple Safari';
$ub = "Safari";
}
elseif(preg_match('/Opera/i',$u_agent))
{
$bname = 'Opera';
$ub = "Opera";
}
elseif(preg_match('/Netscape/i',$u_agent))
{
$bname = 'Netscape';
$ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
$version= $matches['version'][0];
}
else {
$version= $matches['version'][1];
}
}
else {
$version= $matches['version'][0];
}
// check if we have a number
if ($version==null || $version=="") {$version="?";}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT ADMIN
function removeUpdateNotifications(){
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
/*
@todo PRoveriti sta sve ovo znaci.
*/
function RemoveJunkFromHeader ()
{
// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);
}
function mls_get_excerpt_rss() {
$output = get_the_excerpt();
return strip_shortcodes(apply_filters('the_excerpt_rss', $output));
}
/* Meta description of a site */
function dynamic_meta_description() {
$rawcontent = null;
if(is_single() || is_page()) {
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$rawcontent = mls_get_excerpt_rss();
}
}
}
if(empty($rawcontent)) {
$rawcontent = htmlentities(bloginfo('description'));
} else {
// $rawcontent = strip_tags($rawcontent);
$rawcontent = preg_replace('/\[.+\]/','', $rawcontent);
$chars = array("", "\n", "\r", "chr(13)", "\t", "\0", "\x0B");
$rawcontent = htmlentities(str_replace($chars, " ", $rawcontent));
}
if (mb_strlen($rawcontent) < 170) {
} else {
$rawcontent = mb_substr($rawcontent,0,170);
}
return $rawcontent;
}
function csv_tags() {
global $post;
$csv_tags = '';
if(isset($post) && is_object($post)){
$posttags = get_the_tags($post->ID);
if(isset($posttags) && $posttags){
foreach((array)$posttags as $tag) {
$csv_tags .= $tag->name . ',';
}
$csv_tags = substr($csv_tags,0,-1);
}
}
return $csv_tags;
}
/*
Automatically enable threaded comments
Threaded comments aren’t on by default. This can be fixed with the following.
*/
function enable_threaded_comments ()
{
if (! is_admin()) {
if (is_singular() && comments_open() && (get_option('thread_comments') == 1))
wp_enqueue_script('comment-reply');
}
}
add_action('get_header', 'enable_threaded_comments');
function tl_theme_comments($comment, $args, $depth){
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
?>
<li <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent'); ?> id="comment-<?php comment_ID() ?>">
<?php if($comment->comment_approved == '0'): ?>
<p class="aligncenter strong message info"><?php _e('Comment need to be approved by administrator in order to be visible by others.', 'tl_theme') ?></p>
<?php endif; ?>
<ul class="comment-avatar">
<li><?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['avatar_size'] ); ?></li>
<li><?php echo get_comment_author_link(); ?></li>
<li><span><?php echo get_comment_date(); ?> </span></li>
</ul>
<ul class="comment-content">
<li class="comment-content-top"></li>
<li class="comment-content-middle"><?php comment_text() ?></li>
<li class="replay"><?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?></li>
<li class="arrow"></li>
<li class="comment-content-bottom"></li>
</ul>
<?php
}
function mls_custom_dynamic_sidebar($post_id, $theme_sidebar_id=null){
$has_builtin = dynamic_sidebar($theme_sidebar_id);
$has_customs = false;
$data = false;
/* Get custom sidebars for this page/post */
if($post_id){
$data = get_post_meta($post_id, 'tl_theme_sidebar_ids');
}
if(!empty($data) && $data){
$data = $data[0];
foreach ($data as $sidebar_id){
$has_customs = $has_customs || dynamic_sidebar('tl_theme_' . $sidebar_id);
}
}
return $has_builtin || $has_customs;
}
/* Events */
function eventsMetaData($post_id){
$data = get_post_custom($post_id);
$data = unserialize($data['event_meta_data'][0]);
$month = $day = $hours = $year = '';
if($data['date']){
$t = strtotime($data['date']);
$month = date('M', $t);
$day = date('d', $t);
$hours = date('H:i', $t);
$year = date('Y', $t);
}
return array('month'=>$month, 'day'=>$day, 'hours'=>$hours, 'year'=>$year, 'place'=>$data['place'], 'no_participants'=>$data['no_participants']);
}
function testimonialsMetaData($post_id){
$data = get_post_custom($post_id);
$data = unserialize($data['testimonial_meta_data'][0]);
if($data['name']){
$author = $data['name'];
}
$author = (isset($data['name']) && $data['name']) ? $data['name']: '';
$add_info = (isset($data['additional_info']) && $data['additional_info']) ? $data['additional_info']: '';
return array('author'=>$author, 'additional_info'=>$add_info);
}
/*
Customize the admin section footer
*/
function custom_admin_footer ()
{
echo 'Theme Laboratory.';
}
add_filter('admin_footer_text', 'custom_admin_footer');<file_sep><?php
/**
* As name implies this class manage all thing related to a Theme Setup.
*
* 1. Loading all configs from config files
* 2. Setting up all required filters and actions
* 3. Set up Theme support (Thumbs/// etc)
* 4. Trigger activate method only once(When theme is installing)
* 5. ...
*/
if(!defined('RUN_FOREST_RUN')) exit('No Direct Access');
/*
Setup all aspects of the theme
*/
class ThemeSetup{
/*Theme version*/
const THEME_VERSION = '1.0.0';
/**
* The lookup key used to locate the options record in the wp_options table
*/
const OPTIONS_KEY = 'tl_theme_options';
/**
* The hook to be used in all variable actions and filters
*/
const HOOK = 'tl_theme';
/* Minimal WP Version */
public $require_wp = '3.1.1';
protected $init_flag = false;
protected $installed_flag = false;
/* Instance of this class*/
private static $_instance = null;
/* Reference to a ThemeOptions instance */
protected $theme_options = null;
/**
* List of all Errors / Messages
*/
protected $errors = array();
/**
* There can be only one :)
*/
private function __construct(){}
private function __clone(){}
/**
* Returns instance of this class. Singleton
*/
public static function getInstance()
{
if (null === self::$_instance)
{
self::$_instance = new ThemeSetup();
}
return self::$_instance;
}
/**
* Theme Initialization.
*
* Setup all aspects of a theme
*/
public function init(){
if($this->init_flag == false){
self::$_instance->setupPaths();
try{
// Activation
if (is_admin() && isset($_GET['activated']) && isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] == 'themes.php'){
self::$_instance->activate();
}
$this->installed_flag = true;
self::$_instance->setupSupport()
->setupFunctions()
->setupThemeDataObjHandler()
->setupThemeOptionHandler()
->setupHead()
->setupCustomMenus()
->setupHooks()
->setupCustomTypes()
->setupSideBars()
->setupWidgets()
->setupShortCodes()
->setupPlugins()
->setupAjax()
->setupLanguages()
->setupWpCustomizations();
$this->init_flag = true;
}catch(FrameworkException $e){
echo $e->getMessage();
}
}
return $this;
}
/**
* Performs installation action if necessary
*
* @return void
*/
protected function setupPaths(){
//Theme URI
define('TL_THEME_URI' , get_template_directory_uri());
//CSS URI
define('TL_THEME_CSS_URI' , TL_THEME_URI . '/css');
//JS URI
define('TL_THEME_JS_URI' , TL_THEME_URI . '/js');
//JS FONTS URI
define('TL_THEME_FONTS_URI' , TL_THEME_URI . '/fonts');
//INCLUDES URI
define('TL_THEME_INCLUDES_URI' , TL_THEME_URI . '/inc');
//CACHE URI
define('TL_THEME_CACHE_URI' , TL_THEME_URI . '/cache');
//IMAGES URI
define('TL_THEME_IMAGES_URI' , TL_THEME_URI . '/images');
//ADMIN URI
define('TL_THEME_PLUGIN_URI' , TL_THEME_URI . '/framework/plugins');
define('TL_THEME_ADMIN_URI' , TL_THEME_URI . '/framework/admin');
//ADMIN CSS URI
define('TL_THEME_ADMIN_CSS_URI' , TL_THEME_ADMIN_URI . '/css');
//ADMIN JS URI
define('TL_THEME_ADMIN_JS_URI' , TL_THEME_ADMIN_URI . '/js');
/* --- PATHS --- */
//DIRECTORY PATH
define('TL_THEME_DIR' , get_template_directory());
//DIRECTORY PATH
define('TL_THEME_WP_DIR' , '/../../' . dirname(__FILE__));
//CACHE DIR
define('TL_THEME_CACHE_DIR' , TL_THEME_DIR . '/cache');
//FRAMEWORK PATH
define('TL_THEME_FRAMEWORK_DIR' , TL_THEME_DIR . '/framework');
define('TL_THEME_CONFIG_DIR' , TL_THEME_FRAMEWORK_DIR . '/config');
//FUNCTIONS PATH
define('TL_THEME_FUNCTIONS_DIR' , TL_THEME_FRAMEWORK_DIR . '/functions');
//WIDGETS PATH
define('TL_THEME_PATH_WIDGETS_DIR' , TL_THEME_FRAMEWORK_DIR . '/widgets');
//XML PATH
define('TL_THEME_XML_DIR' , TL_THEME_FRAMEWORK_DIR . '/xml');
//ADMIN PATH
define('TL_THEME_ADMIN_DIR' , TL_THEME_FRAMEWORK_DIR . '/admin');
define('TL_THEME_ADMIN_VIEW_DIR' , TL_THEME_ADMIN_DIR . '/view');
//ADMIN FUNCTIONS
define('TL_THEME_ADMIN_FUNCTIONS_DIR' , TL_THEME_ADMIN_DIR . '/functions');
//LIBRARY PATH
define('TL_THEME_LIB_DIR' , TL_THEME_FRAMEWORK_DIR . '/library');
return $this;
}
/**
* @todo Check does this environtment supports our theme.
*/
protected function activate()
{
$this->setupFunctions();
if (!$this->isInstalled())
{
$this->install();
}
/* Set posts as default for home page */
update_option('show_on_front', 'posts');
}
protected function isInstalled(){
$installedVersion = $this->getThemeDataObj()->getOption('meta.version');
return (isset($installedVersion) && ($installedVersion !== null)) ? true:false;
}
/**
* Performs installation when theme is activated for the first time.
*
* @return void
*/
protected function install()
{
$this->getThemeDataObj()->setOptionsDefaults()->save();
$this->installed_flag = true;
}
/**
* Should we implement this method. It should delete all data related to our theme.
*/
protected function uninstall(){ }
protected function setupSupport(){
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'post-thumbnails' );
}
if ( function_exists( 'add_image_size' ) )
{
//Default slider
add_image_size('default-slider', 511, 341, true);
//Full width
add_image_size('full-slider', 9999, 430); //How to do this?
//Wide centered
add_image_size('wide-slider', 966, 430, true);
/* Blog images & gallery images */
add_image_size('blog-middle', 454, 154, true); //middle wide 2 cols
add_image_size('blog-small290', 290, 114, true); //small 3 cols
//add_image_size('blog-small195', 195, 114, true); //small 4 cols
add_image_size('blog-small195', 205, 114, true); //small 4 cols
add_image_size('blog-big', 582, 262, true); //one cols
add_image_size('blog-middle-resp', 450, 263, true); //one cols
add_image_size('portrait-middle', 250, 350, true); //one cols
add_image_size( 'theme-gallery-photo', 800, 9999); // Gallery photo*/
/* Price table & comments*/
add_image_size( 'small-thumb', 82, 82, true); // post list with sidebar
}
return $this;
}
protected function setupHooks(){
add_filter('dynamic_sidebar_params', array($this, 'envelopeWidget'));
add_filter('get_calendar', 'tl_calendar_filter');
/* Custom actions/Filters */
function tl_the_excertp($lenght){
do_action('tl_the_excertp', $lenght);
}
function tl_calendar_filter($str){
$output = '';
$output = preg_replace('/(<td>)<a (.+?)<\/a><\/td>/i', '<td class="cell-full"><a $2</a>', $str);
$output = str_replace(array('«', '»'), array('', ''), $output);
return $output;
}
return $this;
}
public function envelopeWidget($params){
$tmp = $params[0];
if(in_array($tmp['id'], array('home_sidebar1', 'home_sidebar2'))){
$tmp['before_widget'] = '<div class="c-4">' . $tmp['before_widget'];
$tmp['after_widget'] = $tmp['after_widget'] . '</div>';
$params[0] = $tmp;
}
return $params;
}
/**
* Register new POST type
*/
public function setupCustomTypes(){
require_once TL_THEME_ADMIN_DIR . '/lib/GalleryPostType.php';
require_once TL_THEME_ADMIN_DIR . '/lib/ProductPostType.php';
require_once TL_THEME_ADMIN_DIR . '/lib/EventPostType.php';
require_once TL_THEME_ADMIN_DIR . '/lib/TestimonialsPostType.php';
return $this;
}
protected function setupHead(){
require_once (TL_THEME_FUNCTIONS_DIR . '/head.php');
return $this;
}
protected function setupFunctions(){
require_once (TL_THEME_FUNCTIONS_DIR . '/common.php');
require_once (TL_THEME_FUNCTIONS_DIR . '/helper.php');
return $this;
}
protected function setupCustomMenus(){
if ( function_exists( 'register_nav_menus' ) ) {
register_nav_menus(array(
'header-menu' => __('Header Menu', self::HOOK . '_theme' )
));
}
return $this;
}
/**
* Front Ajax Handler. All Ajax Requests goes through this script.
*/
protected function setupAjax(){
add_action( 'wp_ajax_mls_ajax_handler', 'mls_ajax_handler' );
add_action( 'wp_ajax_nopriv_mls_ajax_handler', 'mls_ajax_handler' );
return $this;
}
protected function setupWpCustomizations(){
add_filter('excerpt_more', array(&$this, '_new_excerpt_more'));
function removeHeadLinks() {
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
}
add_action('init', 'removeHeadLinks');
remove_action('wp_head', 'wp_generator');
function tl_fix_shortcodes($content){
$array = array (
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']'
);
$content = strtr($content, $array);
return $content;
}
add_filter('the_content', 'tl_fix_shortcodes', 11);
/* Lenght of excerpt is 20 words at homepage, in other cases standard */
function custom_excerpt_length( $length ) {
//This does not work as expected. Fix it.
if(is_front_page()){
return 20;
}else{
return $length;
}
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
add_filter('the_excerpt', 'myremove_shortcode');
function myremove_shortcode($content) {
$content = strip_shortcodes( $content );
return $content;
}
add_filter('widget_text', 'myremove_shortcode');
add_filter('the_content', 'add_clearfix');
function add_clearfix($content){
if(is_single()){
return $content . '<div class="clearfix"></div>';
}else{
return $content;
}
}
return $this;
}
protected function setupThemeDataObjHandler(){
if($this->theme_options == null){
$this->theme_options = new ThemeOptions(self::OPTIONS_KEY);
}
return $this;
}
protected function setupThemeOptionHandler(){
function Data(){
return ThemeSetup::getInstance()->getThemeDataObj();
}
return $this;
}
public function &getThemeDataObj(){
if($this->theme_options == null){
$this->theme_options = new ThemeOptions(self::OPTIONS_KEY);
}
return $this->theme_options;
}
public function _new_excerpt_more($more) {
global $post;
if(is_search()){
return '... <a href="'. get_permalink($post->ID) . '">'.__('Read More', 'tl_theme' ).'</a>';
}
return __('...', 'tl_theme' );
}
protected function setupLanguages(){
add_action('after_setup_theme', 'setup_languages');
function setup_languages(){
if(is_admin()){
load_theme_textdomain('tl_theme_admin', get_template_directory() . '/framework/language');
}else{
load_theme_textdomain('tl_theme', get_template_directory() . '/framework/language');
}
}
return $this;
}
protected function setupSideBars(){
if ( function_exists('register_sidebar') ){
register_sidebar(array(
'name' => __('Home Page Sidebar 1', 'tl_theme' ),
'description' => __('SideBar shown at home page template. First row.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'home_sidebar1'
));
register_sidebar(array(
'name' => __('Home Page Sidebar 2', 'tl_theme' ),
'description' => __('SideBar shown at home page template. Second row.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'home_sidebar2'
));
register_sidebar(array(
'name' => __('Blog Sidebar', 'tl_theme' ),
'description' => __('Blog Sidebar Widget Area', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'blog_sidebar'
));
register_sidebar(array(
'name' => __('Search Page Sidebar', 'tl_theme' ),
'description' => __('SideBar shown at search page template.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'search_sidebar'
));
register_sidebar(array(
'name' => __('Contact Page Sidebar', 'tl_theme' ),
'description' => __('SideBar shown at contact page template.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'contact_sidebar'
));
register_sidebar(array(
'name' => __('Food Page Sidebar', 'tl_theme' ),
'description' => __('SideBar shown at food page template.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'foodtype_sidebar'
));
register_sidebar(array(
'name' => __('Event Page Sidebar', 'tl_theme' ),
'description' => __('SideBar shown at event page template.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
'id'=>'eventtype_sidebar'
));
//Check if there are User created sidebars?
$sidebars = Data()->getMain('mi_custom_sidebars.csidebar_list');
if(isset($sidebars) && $sidebars != '' && !is_array($sidebars)) $sidebars = array($sidebars);
if(isset($sidebars) && $sidebars!='' && count($sidebars) > 0){
foreach ($sidebars as $s){
$tmp = str_replace(' ', '_', strtolower($s));
register_sidebar(array(
'name' => __('User Defined', 'tl_theme').' - '. $s,
'description' => __('This sidebar was created in the Theme\'s Administration Panel.', 'tl_theme' ),
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
'id'=> 'tl_theme_' . $tmp
));
}
}
}
return $this;
}
protected function setupWidgets(){
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeEventsWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeRecentPostsWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeWorkingHoursWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeContactFormWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeSpecialWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeChefWidget.php';
require_once TL_THEME_PATH_WIDGETS_DIR . '/TlThemeMenuHighlightsWidget.php';
return $this;
}
protected function setupShortCodes(){
require_once (TL_THEME_LIB_DIR . '/ThemeShortcodes.php');
return $this;
}
protected function setupPlugins(){
require_once (TL_THEME_FRAMEWORK_DIR . '/plugins/breadcrumbs-plus/breadcrumbs-plus.php');
require_once (TL_THEME_FRAMEWORK_DIR . '/plugins/wp-pagenavi/wp-pagenavi.php');
require_once (TL_THEME_FRAMEWORK_DIR . '/plugins/CustomPostTypePageTemplate/CustomPostTypePageTemplate.php');
require_once (TL_THEME_FRAMEWORK_DIR . '/plugins/custom-taxonomy-sort/custom-taxonomy-sort.php');
return $this;
}
protected function getRequiredWpVersion(){
return $this->require_wp;
}
public function wpVersionCheck(){
global $wp_version;
if (version_compare($wp_version, $this->getRequiredWpVersion(), "<")){
return false;
}else{
return true;
}
}
public function getInitFlag(){
return $this->init_flag;
}
/**
* Return theme version
*/
public function getVersion(){
return THEME_VERSION;
}
public function hasErrors(){
return count($this->errors) > 0 ? true : false;
}
}<file_sep><div id="sidebar" class="c-4 sidebar">
<?php global $post;
if(isset($post)){
if ( !function_exists('dynamic_sidebar') || !mls_custom_dynamic_sidebar($post->ID, "blog_sidebar") ){}
}else{
mls_custom_dynamic_sidebar(null, "blog_sidebar");
}
?>
</div><file_sep><?php
/**
* Implements meta boxes at post page
*/
class PostOptions {
/**
*
* Enter description here ...
* @var array
*/
protected $options = array();
//protected $meta_db_key = 'mls_post_meta_data';
protected $metabox_ids = array('mls_custom_post_meta', 'mls_gallery_post_options');
/**
*
* Enter description here ...
* @var unknown_type
*/
protected $errors = array();
public function __construct($options = array()){
$this->options = $options;
}
public function init(){
if(empty($this->options)){
$this->_setOptionsDefaults();
}
$this->doHooks();
}
protected function doHooks(){
add_action('add_meta_boxes', array(&$this, 'setupMetaBoxes'));
add_action('save_post', array(&$this, 'doSaveData'));
return $this;
}
public function setupMetaBoxes(){
add_meta_box($this->metabox_ids[0],
__('Post Event Options', 'tl_theme' ),
array(&$this, 'renderEventOptions'), //fja koja daje renderuje opcije
'post', //post type id
'normal',
'high');
return $this;
}
public function renderEventOptions(){
global $post_id;
// Use nonce for verification
wp_nonce_field( plugin_basename(__FILE__), ThemeSetup::HOOK . '_postmeta_noncename' );
echo '<div class="custom-admin-theme-css">';
//Lista slika
echo '<div class="inside">';
foreach ($this->options['mls_custom_post_meta'] as $key => $setting){ // By Fields
if($setting['type'] != 'start_section'){
$data = get_post_meta($post_id, $setting['id'], true);
}
$setting['value'] = (isset($data)) ? $data : '';
echo ThemeAdmin()->parseFieldForMetaBox($setting, ThemeSetup::HOOK);
}
echo '</div>';
echo '</div>';
}
protected function getOptions($meta_box_id = ''){
if($meta_box_id!=''){
if(isset($this->options[$meta_box_id]) && is_array($this->options[$meta_box_id])){
return $this->options[$meta_box_id];
}else{
return array();
}
}else{
throw new Exception('MetaBox not specified', 1003);
}
}
/* This real mistery!!?! Why wordpress call this method event if I do not press SAVE!?! grrrrr */
public function doSaveData($post_id){
$post = get_post($post_id);
if($post->post_type == 'mlsgallery') return $post_id;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}
if(!isset($_POST[ThemeSetup::HOOK . '_postmeta_noncename'])) return $post_id;
$nonce = check_ajax_referer(plugin_basename(__FILE__), ThemeSetup::HOOK . '_postmeta_noncename', false);
if ($nonce === false){
return $post_id;
die();
}
if ( !current_user_can( 'edit_page', $post_id ) ){
return $post_id;
}
if ( !current_user_can( 'edit_post', $post_id ) ){
return $post_id;
}
$data = array();
//Save Events
//Collect Input and add/update post meta
foreach($this->options['mls_custom_post_meta'] as $setting){
if(!is_array($setting) || $setting['type'] == 'start_section'){
continue;
}
$value = $setting['default']===true? 'true' : $setting['default']===false ? 'false' : $setting['default'];
$retrieve = isset($_POST[ThemeSetup::HOOK.$setting['id']]) ? $_POST[ThemeSetup::HOOK.$setting['id']] : false;
if($retrieve){
$value = $retrieve;
}
update_post_meta($post_id, $setting['id'], $value);
$value = '';
}
}
private function _setOptionsDefaults(){
$this->options['mls_custom_post_meta'] = array(
array(
'id'=>'',
'name' => __('Upcoming Events Settings', 'tl_theme_admin' ),
'desc' => __('This settings are related to an Upcoming Events only.', 'tl_theme_admin' ),
'type' => 'start_section',
),
array(
'id' => '_post_month',
'name' => __('Add Month for Upcoming Event', 'tl_theme_admin' ),
'desc' => __('Enter the name of a month in form of a three letters. (ex. APR)', 'tl_theme_admin' ),
'type' => 'text',
'default' => ''
),
array(
'id' => '_post_day',
'name' => __('Add Day for Upcoming Event', 'tl_theme_admin' ),
'desc' => __('Enter two digits. (ex. 12 if an event is scheduled on 12th)', 'tl_theme_admin' ),
'type' => 'text',
'default' => ''
),
array(
'id' => '_post_hours',
'name' => __('Time', 'tl_theme_admin' ),
'desc' => __('Enter something like "Bookstore, 10:00-12:00"', 'tl_theme_admin' ),
'type' => 'text',
'default' => ''
));
}
}
$postO = new PostOptions();
$postO->init(); <file_sep><?php
class ShortcodeButton {
public static $_instance = null;
protected $options = array();
private function __construct($options = array()){}
public function getInstance(){
if (null === self::$_instance)
{
self::$_instance = new ShortcodeButton();
}
return self::$_instance;
}
public function init($options = array()){
$this->options = $options;
$this->initConfig();
add_action('init', array(&$this, 'addButton'));
}
public function addButton(){
if (current_user_can('edit_posts') && current_user_can('edit_pages'))
{
add_filter('mce_external_plugins', array(&$this, 'addPlugin'));
// add_filter('mce_buttons', array(&$this, 'registerButton'));
add_filter('mce_buttons_3', array(&$this, 'registerButton'));
}
}
public function registerButton($buttons){ // 'mls_gallery', 'mls_video', 'mls_mark', 'mls_quoteleft', 'mls_quoteright'
array_push($buttons,'mls_lists','|','mls_headings','|','mls_mark','mls_dropcap','mls_btn','mls_devider','|','|','mls_halfx2','mls_thirdx3','mls_onethird_twothird','mls_twothird_onethird','mls_oneforth_threeforth','mls_forthx4','mls_363','|','|','mls_blockquote','mls_quoteleft','mls_quoteright','|','mls_msg','|','mls_yt','mls_iframe','mls_gallery','|','|');
return $buttons;
}
public function addPlugin($plugin_array) {
global $typenow;
/* Do not need shortcodes for Testimonials Post Type */
if($typenow != 'testimonial'){
$plugin_array['shortcodes'] = TL_THEME_ADMIN_JS_URI . '/tinyMCEshortcodes.js';
$plugin_array['shortcodeslist'] = TL_THEME_ADMIN_JS_URI . '/mls_mce_list_plugin.js';
}
return $plugin_array;
}
public function getConf($key){
return $this->options[$key];
}
public function initConfig(){
/* Gallery options */
$galleries = mls_get_galleries();
$this->options['mls_gallery'] = array(
array('id' =>'mls_sc_gallery_id',
'type' =>'select',
'name' =>__('Select a Gallery', 'tl_theme_admin'),
'desc' => '',
'values' => $galleries,
'default' => null,
'value' => null),
array('id' =>'mls_sc_cols_num',
'type' =>'select',
'name' =>__('Thumb size', 'tl_theme_admin'),
'desc' => '',
'values' =>array('small-thumbs'=>'Small Thumbs','middle-thumbs'=>'Middle Thumbs','wide-thumbs'=>'Wide Thumbs','large-thumbs'=>'Large Thumbs'),
'default' => 'small-thumbs',
'value' =>null),
array('id' =>'mls_sc_gtitle_switch',
'type' =>'checkbox',
'name' =>__('Show Title', 'tl_theme_admin'),
'desc' => __('Main Gallery Title', 'tl_theme_admin'),
'default' =>'off',
'value' =>null),
array('id' =>'mls_sc_title_switch',
'type' =>'checkbox',
'name' =>__('Show title', 'tl_theme_admin'),
'desc' => __('Display picture title', 'tl_theme_admin'),
'default' => 'on',
'value' => null),
array('id' =>'mls_sc_subtitle_switch',
'type' =>'checkbox',
'name' =>__('Show subtitle', 'tl_theme_admin'),
'desc' =>__('Image Subtitle. This data is visible only with 2 column option', 'tl_theme_admin'),
'default' => 'on',
'value' => null),
array('id' =>'mls_sc_desc_switch',
'type' =>'checkbox',
'name' =>__('Show picture description', 'tl_theme_admin'),
'desc' =>__('Available only with 2 column option', 'tl_theme_admin'),
'default' => 'on',
'value' => null)
);
$this->options['mls_yt'] = array(
array('id' =>'yt_url',
'type' =>'text',
'name' => __('Youtube URL', 'tl_theme_admin'),
'desc' => __('Full URL to youtube movie clip.', 'tl_theme_admin'),
'default' => '',
'value' =>null),
array('id' =>'yt_width',
'type' =>'text',
'name' => __('Youtube Movie Width', 'tl_theme_admin'),
'desc' => __('Width in pixels or percents.', 'tl_theme_admin'),
'default' => 480,
'value' =>null),
array('id' =>'yt_height',
'type' =>'text',
'name' => __('Youtube Movie Height', 'tl_theme_admin'),
'desc' => __('Height in pixels.', 'tl_theme_admin'),
'default' => 320,
'value' =>null)
);
/* iFrame */
$this->options['mls_iframe'] = array(
array('id' =>'mls_sc_iframe_url',
'type' =>'text',
'name' => __('Url', 'tl_theme_admin'),
'desc' => __('Enter Full Url (ex. http://www.example.com)', 'tl_theme_admin'),
'default' => 'http://',
'value' => null),
array('id' =>'mls_sc_scrolling',
'type' =>'checkbox',
'name' =>__('Scrolling', 'tl_theme_admin'),
'desc' => __('Enable scrollbars', 'tl_theme_admin'),
'default' =>'on',
'value' =>null),
array('id' =>'mls_sc_width',
'type' =>'text',
'name' => __('Iframe Width', 'tl_theme_admin'),
'desc' => __('Width in pixels or percents.', 'tl_theme_admin'),
'default' => '100%',
'value' =>null),
array('id' =>'mls_sc_height',
'type' =>'text',
'name' => __('Iframe Height', 'tl_theme_admin'),
'desc' => __('Height in pixels.', 'tl_theme_admin'),
'default' => 500,
'value' =>null),
array('id' =>'mls_sc_frameborder',
'type' =>'text',
'name' =>__('Border Width', 'tl_theme_admin'),
'desc' =>__('To disable border set Thickness to 0.', 'tl_theme_admin'),
'default' => 0,
'value' => null),
array('id' =>'mls_sc_marginheight',
'type' =>'text',
'name' => __('Margin Height', 'tl_theme_admin'),
'desc' => __('Set margin for bottom of an Iframe.(Ex. 33px)', 'tl_theme_admin'),
'default' => '40px',
'value' => null),
);
/* Message */
$this->options['mls_msg'] = array(
array('id' =>'mls_sc_msg',
'type' =>'select',
'name' =>__('Message type', 'tl_theme_admin'),
'desc' => ' ',
'default' => 'info',
'values' => array('success'=>'Success', 'info'=>'Info', 'warning'=>'Warning', 'error'=>'Error'),
'value' => null)
);
/* Buttons */
$this->options['mls_btn'] = array(
array('id' => 'mls_btn_color',
'type' => 'select',
'name' => __('Button Color', 'tl_theme_admin'),
'desc' => ' ',
'default' => 'red',
'values' => array('red'=>__('Red', 'tl_theme_admin'), 'dark'=>__('Dark','tl_theme_admin')),
'value' => null),
array('id' => 'mls_btn_target',
'type' => 'select',
'name' => __('Link Target', 'tl_theme_admin'),
'desc' => ' ',
'default' => '_self',
'values' => array('_self'=>'Self', '_blank'=>__('New tab in browser','tl_theme_admin')),
'value' => null),
array('id' => 'mls_btn_link',
'type' => 'text',
'name' => __('Link', 'tl_theme_admin'),
'desc' => ' ',
'default' => '#',
'value' => null),
);
}
} // Class End
$obj = ShortcodeButton::getInstance()->init();<file_sep><?php
/**
* Template Name: Book a Table Template Page [Default]
* Description: Book a Table Page
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
get_header();
get_template_part('template-part-ribbon');
?>
<div id="content">
<div class="wrap">
<div class="c-8 divider">
<div class="entry">
<div class="post-list">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div>
<div class="contact-modal-box"></div>
<form enctype="multipart/form-data" method="post" id="reservationform">
<div class="send-form">
<p>
<label><span>*</span><?php _e('Party Size','tl_theme')?>:</label>
<select name="size">
<option value="0"><?php _e('Number of guests', 'tl_theme')?></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6-10">6-10</option>
<option value="10-15">10-15</option>
<option value="15+"><?php _e('Over', 'tl_theme')?>15</option>
</select>
</p>
<p>
<label><span>*</span><?php _e('Date','tl_theme')?>:</label>
<input class="u-2" name="date" id="datepicker" />
</p>
<p>
<label><?php _e('Name','tl_theme')?>:</label>
<input class="u-4" name="name" id="name1" />
</p>
<p>
<label><?php _e('Email','tl_theme')?>:</label>
<input class="u-4" name="email" id="email1" />
</p>
<p>
<label><span>*</span><?php _e('Phone','tl_theme')?>:</label>
<input class="u-4" name="phone" id="phone1" />
</p>
<p>
<label><?php _e('Additional Info','tl_theme')?>:</label>
<textarea class="u-6" name="notes" id="notes1" cols="80" rows="5"></textarea>
<br/>
</p>
<p>
<a href="#" id="send-book-button" class="button dark"><span><?php _e('Book a table','tl_theme')?></span></a>
<a href="#" id="cancel-book-button" class="button red"><span><?php _e('Reset','tl_theme')?></span></a>
</p>
</div><!-- end book-table-form -->
</form>
</div><!-- end entry -->
</div>
<?php get_sidebar(); ?>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
* Template part: Ribbon at all inner pages
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
$content_type = Data()->getMain('mi_home.featured_section_source_switch');
// $show_read_more = Data()->isOn('mi_home.featured_section_readmore_switch');
$display_type = Data()->getMain('mi_home.featured_section_display_type'); //carousel OR static list
/* Middle content content */
$content = array();
?>
<div id="intro">
<div class="wrap">
<?php $teaser_text = Data()->isOn('mi_header.teaser_switch'); ?>
<?php
if($teaser_text){
$ribbon_teaser = '';
if(is_category()){
$ribbon_teaser = single_cat_title('', false);
}elseif (is_tag()){
$ribbon_teaser = single_tag_title('', false);
$ribbon_teaser = __('Tag', 'tl_theme') .': '. $ribbon_teaser;
}elseif (is_day()){
$ribbon_teaser = __('Archives for', 'tl_theme') . get_the_time('F jS, Y');
}elseif (is_month()){
$ribbon_teaser = single_month_title('', false);
}elseif (is_year()){
$ribbon_teaser = __('Archives for', 'tl_theme') . get_the_time('F, Y');
}elseif (is_author()){
$ribbon_teaser = __('Author', 'tl_theme');
}elseif (isset($_GET['paged']) && !empty($_GET['paged'])){
$ribbon_teaser = __('Blog', 'tl_theme');
}elseif(is_404()){
$ribbon_teaser = __('404 - Sorry', 'tl_theme');
}elseif (is_search()){
$ribbon_teaser = __('Search Result', 'tl_theme');
}elseif(is_home()){
$ribbon_teaser = __('Blog', 'tl_theme');
}
else{
$post = $posts[0]; // Hack. Set $post so that the_date() works.
if($post->post_type == 'product'){
$terms = wp_get_post_terms( $post->ID, 'food_type', array("fields" => "names"));
if(!empty($terms)){
$ribbon_teaser = $terms[count($terms)-1];
}
}elseif ($post->post_type == 'event'){
$ribbon_teaser = __('Events', 'tl_theme');
}elseif ($post->post_type == 'testimonial'){
$ribbon_teaser = __('Testimonials', 'tl_theme');
}elseif(is_page()){
if(mb_strlen($post->post_title) > 17){
$ribbon_teaser = '...';
}
$ribbon_teaser = mb_substr($post->post_title, 0, 17) . $ribbon_teaser;
}else{
$category = get_the_category($post->ID);
if(!empty($category)){
$ribbon_teaser = $category[0]->cat_name;
}
}
}
}
?>
<div class="c8" style="float: left;">
<?php if($teaser_text) :?> <h1><?php echo $ribbon_teaser; ?></h1><?php else: echo ' ' ?><?php endif; ?>
<?php $hide_breadcrumbs_text = Data()->isOn('mi_header.bread_crumbs_text_switch');
if($hide_breadcrumbs_text) {
$mls_breadcrumbs_opts= array('title'=>'');
}
if($post){
$type = ($post->post_type == 'product') ? 'food_type':'category';
$mls_breadcrumbs_opts['singular_post_taxonomy'] = $type;
}
?>
<?php if(Data()->isOn('mi_header.breadcrumbs_switch')) : breadcrumbs_plus($mls_breadcrumbs_opts); endif; ?>
</div>
</div><!-- end wrap -->
</div><!-- end intro --><file_sep><?php
if(!WP_DEBUG){
error_reporting(0);
ini_set('display_errors', false);
}else{
error_reporting(E_ALL);
ini_set('display_errors', true);
}
/* No direct Access */
define('RUN_FOREST_RUN', true);
/* Should we show/include Color Sheme Switcher. Is this showcase or for sale? */
define('MLS_SHOWCASE', false);
/* Class auto loading function */
function mazzThemeAutoload($class) {
$include_paths = array('/framework/','/framework/library/','/framework/widgets/','/framework/admin/');
$path = dirname(__FILE__);
foreach ($include_paths as $inc_path) {
if(file_exists($path . $inc_path . $class . '.php')){
include($path . $inc_path . $class . '.php');
}
}
}
spl_autoload_register('mazzThemeAutoload');
add_post_type_support('page', 'excerpt');
//Get Theme Instance
$theme = ThemeSetup::getInstance()->init();
//Are we in the administration area?
if(is_admin()){
$admin_theme = AdminSetup::getInstance()->init();
}
if ( ! isset( $content_width ) ) $content_width = 954;
if(WP_DEBUG){
if($theme->hasErrors()){
echo '<pre>';
echo "ERRORS ::: ThemeSetup->";
var_dump( $theme->errors);
echo "ERRORS ::: ThemeADmin->";
var_dump(ThemeAdmin()->errors);
echo "ERRORS ::: ThemeOptions->";
var_dump($theme->getThemeDataObj()->errors);
echo '</pre>';
}
}
function tl_do_shortcode($content){
$content = trim(do_shortcode(shortcode_unautop(trim($content))));
/* Remove '' from the start of the string. */
if ( substr( $content, 0, 4 ) == '' )
$content = substr( $content, 4 );
/* Remove '' from the end of the string. */
if ( substr( $content, -3, 3 ) == '' )
$content = substr( $content, 0, -3 );
/* Remove any instances of ''. */
$content = str_replace( array( '<p></p>' ), '', $content );
$content = str_replace( array( '<p> </p>' ), '', $content );
$content = str_replace( array( '<p><div' ), '<div', $content );
$content = str_replace( array( '</div></p>' ), '</div>', $content );
return $content;
}
/*function print_filters_for( $hook = '' ) {
global $wp_filter;
if( empty( $hook ) || !isset( $wp_filter[$hook] ) )
return;
print '<pre>';
print_r( $wp_filter[$hook] );
print '</pre>';
}
print_filters_for('the_content');*/<file_sep><?php
class EventPostType extends CustomPostTypeHelper{
public function __construct($name){
parent::__construct($name, array(
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'map_meta_cap'=> true,
'hierarchical' => false,
'menu_position' => 5,
'supports' => array('title', 'editor', 'thumbnail', 'page-attributes')
),
array(
'name' => _x( 'Events', 'Event', 'tl_theme' ),
'singular_name' => _x( 'Event', 'Event', 'tl_theme' ),
'add_new' => _x( 'Add New', 'event', 'tl_theme' ),
'add_new_item' => __( 'Add New Event' , 'tl_theme'),
'edit_item' => __( 'Edit Event' , 'tl_theme'),
'new_item' => __( 'New Event' , 'tl_theme' ),
'all_items' => __( 'All Events', 'tl_theme' ),
'view_item' => __( 'View Event', 'tl_theme' ),
'search_items' => __( 'Search Events', 'tl_theme' ),
'not_found' => __( 'No events found', 'tl_theme'),
'not_found_in_trash' => __( 'No events found in Trash', 'tl_theme'),
'parent_item_colon' => '',
'menu_name' => 'Events'
)
);
}
}
$meta_fields = array(
array('id'=>'date','label'=>__('Date', 'tl_theme_admin'),'type'=>'datetimepicker','value'=>'', 'default'=>''),
array('id'=>'place','label'=>__('Place', 'tl_theme_admin'),'type'=>'text','value'=>'', 'default'=>''),
array('id'=>'no_participants','label'=>__('Number of participants', 'tl_theme_admin'),'type'=>'text','value'=>'', 'default'=>'')
);
$meta_box1 = array('id' => 'event_attributes',
'title' => __('Event Attributes', 'tl_theme_admin'),
'callback' => null,
'context' => 'side',
'priority' => 'high',
'callback_args' => $meta_fields);
$taxonomi_args = array();
$eventPostTypeObj = new EventPostType('Event');
$eventPostTypeObj->addMetaBox($meta_box1);<file_sep><?php
/**
* Template Name: Blog big list template
* Description: Blog big list template without sidebar
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
$show_meta = Data()->isOn('mi_blog.mi_blog_meta_switch');
$hide_cats = Data()->getMain('mi_blog.hide_cats');
$readmore = Data()->getMain('mi_blog.readmore');
$hide_cats_tmp = array();
if($hide_cats){
foreach ($hide_cats as $value) {
$hide_cats_tmp[] = (string)($value * (-1));
}
}
?>
<?php
get_header();
get_template_part('template-part-ribbon');
global $wp_query;
$args = array( 'post_type' => 'post', 'order'=>'DESC', 'orderby'=>'date',
'paged' => get_query_var('paged'),
'cat' => implode(',', $hide_cats_tmp)
);
query_posts( $args );
?>
<div id="content">
<div class="wrap">
<div class="c-12">
<ul class="portfolio-menu">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<li class="c-12 big-list clearfix post-<?php the_ID();?>">
<?php if(has_post_thumbnail()): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'theme-gallery-photo'); ?>
<p class="image">
<a class="lightbox-standard" href="<?php echo $large_image_url[0]; ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('blog-big'); ?>
</a>
</p>
<?php endif; ?>
<?php if($show_meta): ?>
<p class="meta"><?php the_category(', ') ?></p>
<?php endif; ?>
<h3 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<div class="excerpt">
<p><?php the_excerpt(); ?></p>
</div>
<p class="actions"><a title="" href="" class="read-more-red"><?php _e('Read More','tl_theme'); ?></a></p>
</li>
<?php endwhile; endif; ?>
</ul>
<?php wp_pagenavi(array('class'=>'pagination',
'options'=> array('pages_text'=>' ',
'first_text' => '',
'last_text' => '',
'always_show' => false,
'use_pagenavi_css'=>false,
'prev_text' => __('Previous', 'tl_theme'),
'next_text' => __('Next', 'tl_theme'),
))
); ?>
</div><!-- .c-12 -->
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
* Set up all staff required by theme administration panel.
*/
if(!defined('RUN_FOREST_RUN')) exit('No Direct Access');
/**
* For Mazzareli Theme administration
*/
class AdminSetup {
/* An Instance of Settings Object */
private $settings = null;
private static $_instance = null;
public $admin_panel_hook_name = '';
private function __construct(){}
public function __clone(){}
/**
* Returns instance of this class. Singleton
*/
public static function getInstance()
{
if (null === self::$_instance)
{
self::$_instance = new self();
}
return self::$_instance;
}
public function init(){
$this->setupAdminPlugins();
$this->addWpMenu();
$this->setupFunctions();
$this->setupAdminClasses();
$this->setupShortCodeBtns();
$this->setupAjaxCallback();
$this->setupAdminWpCustomizations();
return $this;
}
protected function setupFunctions(){}
/**
* Proveriti kakav SCOPE ima objekat ako je kreiran u funkciji a van funkcije vec postoji takav
*/
protected function setupAdminClasses(){
function ThemeData(){
return ThemeSetup::getInstance()->getThemeDataObj();
}
function ThemeAdmin(){
return ThemeAdmin::getInstance()->init();
}
}
/**
* Insert Menu item in Main administration menu
*/
protected function addWpMenu(){
add_action('admin_menu', array( $this, 'optionsAdminMenu'));
}
/**
* Add theme options to the main admin menu
* @return void
*/
public function optionsAdminMenu(){
$this->admin_panel_hook_name = add_object_page( 'Mazzareli Theme',
'Mazzareli Theme',
'edit_theme_options',
'tl_theme',
array( ThemeAdmin(), 'displayAdminSettings'));
$this->onAdminPageAdded();
}
protected function onAdminPageAdded(){
require_once (TL_THEME_ADMIN_FUNCTIONS_DIR . '/head.php');
$this->setupMetaBoxes();
}
/**
* Hook a Ajax Theme Handler
*/
protected function setupAjaxCallback(){
add_action('wp_ajax_ajaxCallBack', array( $this, 'ajaxCallBack' ));
add_action('wp_ajax_ajaxShortcode', array( ThemeShortCodes::getInstance(), 'ajaxShortcode' ));
return $this;
}
/**
* Ajax handler Call
*/
public function ajaxCallBack(){
$this->enforce_restricted_access();
ThemeAdmin()->adminAjax();
}
public function setupAdminPlugins(){
require_once (TL_THEME_FRAMEWORK_DIR . '/plugins/regenerate-thumbnails/regenerate-thumbnails.php');
return $this;
}
/**
* Security Check. Used when we have an Ajax Call.
*/
public function enforce_restricted_access(){
//if (!current_user_can('manage_options')) {
if (!current_user_can('edit_pages') || !current_user_can('edit_posts')) {
wp_die( __('You do not have permission to edit the theme settings', 'tl_theme_admin' ) );
}
}
protected function setupMetaBoxes(){
global $typenow;
require_once TL_THEME_ADMIN_DIR . '/lib/MetaBoxAbstract.php';
return $this;
}
/**
* Integrates Buttons in TinyMCE Editor
*/
protected function setupShortCodeBtns(){
global $typenow;
/* Do not load shortcode buttons when administer testimonials. */
if($typenow != 'testimonial'){
require_once (TL_THEME_ADMIN_DIR . '/lib/ShortcodeButton.php');
}
return $this;
}
/* Update with initial data. This action should be triggered only once. After theme instalation / first update */
public function importDemoData(){
$url = get_template_directory_uri();
$data = '';
}
public function mlsGalleryRowAction($actions, $post){
if ($post->post_type == 'mlsgallery'){
unset($actions['view']);
unset($actions['inline hide-if-no-js']);
}
return $actions;
}
/**
* WP admin panel customs
*/
protected function setupAdminWpCustomizations(){
add_filter('post_row_actions',array(&$this, 'mlsGalleryRowAction'), 10, 2);
return $this;
}
public function templateTypeMap(){
$arr = array(
'product' => array('template-product1.php'),
'event' => array('template-events-without-sidebar.php',
'template-events.php',
'template-single-event.php'),
'testimonial' => array('template-testimonials.php',
'template-testimonials-no-sidebar.php'),
'default' => array('template-blog-2cols-archive.php',
'template-blog-3cols-archive.php',
'template-blog-4cols-archive.php',
'template-blog-big-list.php',
'template-blog-medium-list.php',
'template-blog-small-list.php',
'template-book-table.php',
'template-chef.php',
'template-contact.php',
'template-copyrights.php',
'template-home-one.php',
'template-menu1.php',
'template-page-rsidebar.php',
'template-prices.php',
'template-sitemap.php',
'template-terms.php'
)
);
if(MLS_SHOWCASE){
$arr['default'][] = 'template-page-showcase-full-slider-home-one.php';
$arr['default'][] = 'template-page-showcase-standard-slider-home-one.php';
}
}
}<file_sep><?php
/**
* Template Name: Menu Card Template
* Description: Menu Card Template.
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
get_header();
get_template_part('template-part-ribbon');
$menu_of_day = Data()->getMain('mi_product.menu_of_day');
?>
<div id="content">
<div class="wrap">
<div class="c-6">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<h2 class="title"><?php the_title(); ?></h2>
<?php the_content() ?>
<?php endwhile; endif; ?>
</div>
<?php $args = array('include'=>$menu_of_day, 'post_type'=>'product','numberposts'=>4);
$x = get_posts($args);
?>
<div class="c-6">
<div class="menu-off-the-day hidden">
<h3 class="title"><?php _e('Menu Of The Day', 'tl_theme') ?></h3>
<ul>
<?php foreach ($x as $y): ?>
<?php
$meta = get_post_meta($y->ID);
$meta = unserialize($meta['product_meta_data'][0]);
?>
<li><h2 class="title"><a href="<?php echo get_permalink($y->ID) ?>"><?php echo apply_filters('the_title', $y->post_title) ?></a><span><?php echo $meta['price']; ?></span></h2></li>
<?php endforeach; ?>
</ul>
</div>
</div>
<div class="clearfix"></div>
<?php
// $items = get_prices(999);
$counter = 0;
$menu = get_menu_data();
?>
<div class="menu-container">
<div class="menu-slider">
<div class="menu-slider-inner">
<?php $class_page = ''; //var_dump($menu);?>
<?php foreach ($menu as $data): // category ?>
<?php if($class_page != 'left-page'): ?>
<div class="menu-page">
<?php endif; ?>
<?php $class_page = ($class_page == 'left-page') ? 'right-page':'left-page'; ?>
<div class="<?php echo $class_page ?> c-6">
<h2><?php echo $data['top_term']->name; ?></h2>
<?php foreach ($data['items'] as $key=>$subcategories): //by subcategories ?>
<h3 class="price-category-heading"><?php echo (($subcategories[0]->slug != $data['top_term']->slug) ? $subcategories[0]->name : ' '); ?></h3>
<ul class="price-items">
<?php foreach ($subcategories as $menu_item): //by menu_items ?>
<?php
$meta = get_post_meta($menu_item->ID);
$meta = unserialize($meta['product_meta_data'][0]);
?>
<li>
<?php if(has_post_thumbnail($menu_item->ID)): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($menu_item->ID), 'theme-gallery-photo'); ?>
<div class="item-image">
<p class="image">
<a rel="fancy_zoom" href="<?php echo $large_image_url[0]; ?>" title="<?php echo apply_filters('the_title', $menu_item->post_title) .' '.($meta['price']?$meta['price']:''); ?>" data-desc="<?php echo mls_the_excerpt_max_charlength(get_the_excerpt(), 150); ?>">
<?php echo get_the_post_thumbnail($menu_item->ID, 'small-thumb', array('title' => apply_filters('the_title', $menu_item->post_title),
'alt' => apply_filters('the_title', $menu_item->post_title) .' '.($meta['price']?$meta['price']:''))); ?>
</a>
</p>
<?php if($meta['special_switch'] == 'on'):?>
<a title="<?php echo apply_filters('the_title', $menu_item->post_title) .' '.($meta['price']?$meta['price']:''); ?>" class="specialty lightbox" href="<?php echo $large_image_url[0]; ?>"><?php _e('Specialty', 'tl_theme'); ?></a>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="price-heading">
<h4>
<a href="<?php echo get_permalink($menu_item->ID)?>"><?php echo apply_filters('the_title', $menu_item->post_title); ?></a>
<?php if(isset($meta['price'])): ?><span><?php echo $meta['price']; ?></span><?php endif; ?>
</h4>
</div>
<p><?php echo mls_abstract(strip_shortcodes($menu_item->post_content)); ?></p>
</li>
<?php endforeach; //menu items ?>
</ul>
<?php endforeach; // subcategory ?>
</div><!-- .left/right-page -->
<?php if($class_page != 'left-page'): ?>
</div><!-- .menu-page -->
<?php endif; ?>
<?php endforeach; ?>
<?php if($class_page == 'left-page'): ?>
</div><!-- .menu-page -->
<?php endif; ?>
</div>
</div> <!-- .menu-slider -->
<div class="prev-page"></div>
<div class="next-page"></div>
</div>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
* Rendering anything slider
*
*
*/
class AnythingSlider extends ThemeSlider{
protected $theme = 'Default';
protected $run_settings_index = array('theme', 'mode', 'expand', 'resizeContents', 'showMultiple', 'easing', 'buildArrows',
'toggleArrows', 'changeBy', 'autoPlay', 'autoPlayLocked', 'autoPlayDelayed', 'pauseOnHover', 'stopAtEnd', 'playRtl',
'delay', 'resumeDelay', 'animationTime', 'delayBeforeAnimate', 'allowRapidChange');
public function __construct($settings, $slides){
$this->type = 'anything_slider';
$this->js_handle = ThemeSetup::HOOK . '_jquery_anything_all_js';
$this->theme = $settings['theme'];
parent::__construct($settings, $slides);
}
public function enqueueScripts(){}
public function _renderSlider(){
$output = '';
$method_name = '_render' . $this->theme . 'Slider';
if(method_exists($this, $method_name)){
$output = $this->$method_name();
}
return $output;
}
/**
*
* Enter description here ...
*/
protected function _renderFullSlider(){
$output = '';
foreach ($this->slides as $s){
$attachment_id = 0;
if($s['slide_type'] == 'image'){
$slide_url = $s['slide_url'];
preg_match("/attachment_id=([0-9]+)/i", $s['slide_url'], $m);
if(!empty($m)){
$attachment_id = (int) $m[1];
}else{
preg_match("/(.+\.(jpg|jpeg|png|gif))/i", $slide_url, $m);
$attachment_id = mls_attachment_url_to_id($m[1]);
$attachment_id = (int) $attachment_id;
}
$img = wp_get_attachment_image_src($attachment_id, 'full-slider');
$s['slide_url'] = $img[0];
$pos = strpos( $s['slide_url'], 'wp-content');
$path = substr($s['slide_url'], $pos );
$path = ABSPATH . $path;
if(!file_exists($path)){
$s['slide_url'] = $slide_url;
}
$slide_content = '<img title="'.esc_attr($s['slide_heading']).'" alt="image" src="'.$s['slide_url'].'" />';
}elseif($s['slide_type'] == 'youtube'){
if(isset($s['slide_video']) && $s['slide_video'] != '')
{
$slide_content = '<object width="100%" height="100%">
<param name="movie" value="http://www.youtube.com/v/'.$s['slide_video'].'?version=3&autohide=1&controls=0&rel=0&showinfo=0"></param>
<param name="allowFullScreen" value="false"></param>
<param name="allowscriptaccess" value="always"></param>
<param name="wmode" value="opaque">
<embed src="http://www.youtube.com/v/'.$s['slide_video'].'?version=3&autohide=1&controls=0&rel=0&showinfo=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque"></embed>
</object>';
}
}elseif($s['slide_type'] == 'vimeo'){
if(isset($s['slide_video']) && $s['slide_video'] != '')
{
$slide_content = '<object width="100%" height="100%">
<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='.$s['slide_video'].'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&fullscreen=1&autoplay=0&loop=0"></param>
<param name="allowFullScreen" value="false"></param>
<param name="allowscriptaccess" value="always"></param>
<param name="wmode" value="opaque">
<embed src="http://vimeo.com/moogaloop.swf?clip_id='.$s['slide_video'].'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" width="100%" height="100%" allowscriptaccess="always" allowfullscreen="true" wmode="opaque">
</embed>
</object>';
}
}
$output .= '<li>';
if($s['slide_showslideextra'] == 'on'){
$box_w = $s['slide_extrawidth'] == '0' ? '' : 'width:'.$s['slide_extrawidth'].'px;';
$box_h = $s['slide_extraheight'] == '0' ? '' : 'height:'.$s['slide_extraheight'].'px;';
$output .= '<div style="opacity:0;'.$box_w.' '.$box_h.'" class="extra-info '.$s['slide_extraposition'].'"><div class="extra-info-inner">';
$output .= ($s['slide_showslidesubheading'] == 'off') ? '' : '<h4>'.esc_attr(stripslashes($s['slide_subheading'])).'</h4>';
$output .= ($s['slide_showslideheading'] == 'off') ? '' : '<h2>'.esc_attr(stripslashes($s['slide_heading'])).'</h2>';
$output .= ($s['slide_showslidedesc'] == 'off') ? '' :'<p>'.(stripslashes($s['slide_desc'])).'</p>';
$output .= ($s['slide_showbutton'] == 'off') ? '' :'<a class="btn" href="'.$s['slide_link'].'"><span>'.__('Read More', 'tl_theme').'</span></a>';
$output .= ' </div></div>';
//<a href="#" class="btn" style="position: relative; left: 0px;"><span>Read More</span></a>
}
$output .= $slide_content;
$output .= '<div class="clearfix"></div>';
$output .= '</li>';
}
$output = '<div><ul id="sliderul">
'.$output.'
</ul></div>';
return $output;
}
/**
*
* Enter description here ...
*/
protected function _renderStandardSlider(){
$output = '';
foreach ($this->slides as $s){
$attachment_id = 0;
if($s['slide_type'] == 'image'){
$slide_url = $s['slide_url'];
preg_match("/attachment_id=([0-9]+)/i", $s['slide_url'], $m);
if(!empty($m)){
$attachment_id = (int) $m[1];
}else{
preg_match("/(.+\.(jpg|jpeg|png|gif))/i", $slide_url, $m);
$attachment_id = mls_attachment_url_to_id($m[1]);
$attachment_id = (int) $attachment_id;
}
$img = wp_get_attachment_image_src($attachment_id, 'wide-slider');
$s['slide_url'] = $img[0];
$pos = strpos( $s['slide_url'], 'wp-content');
$path = substr($s['slide_url'], $pos );
$path = ABSPATH . $path;
if(!file_exists($path)){
$s['slide_url'] = $slide_url;
}
$slide_content = '<img title="'.esc_attr($s['slide_heading']).'" alt="image" src="'.$s['slide_url'].'" />';
}elseif($s['slide_type'] == 'youtube'){
if(isset($s['slide_video']) && $s['slide_video'] != '')
{
$h = $w = '100%';
$float = $s['slide_videofloat'];
if($s['slide_imagewidth'] > 0 ) $w = $s['slide_imagewidth'];
if($s['slide_imageheight'] > 0 ) $h = $s['slide_imageheight'];
$slide_content = '<object width="'.$w.'" height="'.$h.'" style="margin: 0 auto; display:block; float:'.$float.';">
<param name="movie" value="http://www.youtube.com/v/'.$s['slide_video'].'?version=3&fs=1&autohide=1&controls=0&rel=0&showinfo=0"></param>
<param name="allowFullScreen" value="false"></param>
<param name="allowscriptaccess" value="always"></param>
<param name="wmode" value="opaque">
<embed src="http://www.youtube.com/v/'.$s['slide_video'].'?version=3&autohide=1&controls=0&fs=1&rel=0&showinfo=0" type="application/x-shockwave-flash" width="'.$w.'" height="'.$h.'" allowscriptaccess="always" allowfullscreen="true" wmode="opaque">
</embed>
</object>';
}
}elseif($s['slide_type'] == 'vimeo'){
if(isset($s['slide_video']) && $s['slide_video'] != '')
{
$h = $w = '100%';
if($s['slide_imagewidth'] > 0 ) $w = $s['slide_imagewidth'];
if($s['slide_imageheight'] > 0 ) $h = $s['slide_imageheight'];
$slide_content = '<object width="'.$w.'" height="'.$h.'">
<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id='.$s['slide_video'].'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&fullscreen=1&autoplay=0&loop=0"></param>
<param name="allowFullScreen" value="false"></param>
<param name="allowscriptaccess" value="always"></param>
<param name="wmode" value="opaque">
<embed src="http://vimeo.com/moogaloop.swf?clip_id='.$s['slide_video'].'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" width="'.$w.'" height="'.$h.'" allowscriptaccess="always" allowfullscreen="true" wmode="opaque">
</embed>
</object>';
}
}
$output .= '<li>';
if($s['slide_showslideextra'] == 'on' ){
$box_w = $s['slide_extrawidth'] == '0' ? '' : 'width:'.$s['slide_extrawidth'].'px;';
$box_h = $s['slide_extraheight'] == '0' ? '' : 'height:'.$s['slide_extraheight'].'px;';
$output .=' <div style="opacity:0;'.$box_w.' '.$box_h.'" class="extra-info '.$s['slide_extraposition'].'"><div class="extra-info-inner">';
$output .= ($s['slide_showslidesubheading'] == 'off') ? '' : '<h4>'.esc_attr(stripslashes($s['slide_subheading'])).'</h4>';
$output .= ($s['slide_showslideheading'] == 'off') ? '' : '<h2>'.esc_attr(stripslashes($s['slide_heading'])).'</h2>';
$output .= ($s['slide_showslidedesc'] == 'off') ? '' :'<p>'.(stripslashes($s['slide_desc'])).'</p>';
$output .= ($s['slide_showbutton'] == 'off') ? '' :'<a class="btn" href="'.$s['slide_link'].'"><span>'.__('Read More', 'tl_theme').'<span></a>';
$output .= ' </div></div>';
}
$output .= $slide_content;
$output .= '<div class="clearfix"></div>';
$output .= '</li>';
}
$output = '<div class="wrap"><ul id="sliderul">
'.$output.'
</ul></div>';
return $output;
}
/**
* This is the one with mask
*/
protected function _renderDefaultSlider(){
$output = '';
foreach ($this->slides as $s){
$slide_content = '';
$attachment_id = 0;
if($s['slide_type'] == 'image'){
$slide_url = $s['slide_url'];
preg_match("/attachment_id=([0-9]+)/i", $slide_url, $m);
if(!empty($m)){
$attachment_id = (int) $m[1];
}else{
preg_match("/(.+\.(jpg|jpeg|png|gif))/i", $slide_url, $m);
$attachment_id = mls_attachment_url_to_id($m[1]);
$attachment_id = (int) $attachment_id;
}
$img = wp_get_attachment_image_src($attachment_id, 'default-slider');
$s['slide_url'] = $img[0];
$pos = strpos( $s['slide_url'], 'wp-content');
$path = substr($s['slide_url'], $pos );
$path = ABSPATH . $path;
if(!file_exists($path)){
$s['slide_url'] = $slide_url;
}
$slide_content = '<img title="'.esc_attr($s['slide_heading']).'" alt="image" src="'.$s['slide_url'].'" />';
}else{
continue;
}
$box_w = $s['slide_extrawidth'] == '0' ? '' : 'width:'.$s['slide_extrawidth'].'px;';
$box_h = $s['slide_extraheight'] == '0' ? '' : 'height:'.$s['slide_extraheight'].'px;';
$output .= '<li>
<div class="small-slider text-abstract" style="'.$box_w.' '.$box_h.'">';
if($s['slide_showslideextra'] == 'on')
{
$output .= ($s['slide_showslidesubheading'] == 'off') ? '' : '<h4 style="opacity:0;">'.esc_attr($s['slide_subheading']).'</h4>';
$output .= ($s['slide_showslideheading'] == 'off') ? '' : '<h2 style="opacity:0;">'.esc_attr($s['slide_heading']).'</h3>';
$output .= ($s['slide_showslidedesc'] == 'off') ? '' :'<p>'.($s['slide_desc']).'</p>';
$output .= ($s['slide_showbutton'] == 'off') ? '' :'<a href="'.$s['slide_link'].'" class="btn"><span>'. __('Read More', 'tl_theme') .'</span></a>';
}
$output .='</div>
<div class="big-slider">
'.$slide_content.'
</div>
<div class="clearfix"></div>
</li>';
}//foreach
//<img src="'.TL_THEME_CSS_URI.'/color-shemes/'. Data()->getMain('mi_look_feel.color_sheme') .'/home-slider-mask.png" />
$output = '<div class="wrap">
<div class="mask"></div>
<ul id="sliderul">
'.$output.'
</ul>
</div>';
return $output;
}
protected function _prepareSliderOptionsJs(){
return array();
}
/**
* According to a slides content inject make a list of required anything slider extensions
*/
protected function _hasVideo(){
foreach ($this->slides as $v){
if($v['slide_type'] == 'youtube' || $v['slide_type'] == 'vimeo'){
return true;
break;
}
}
return false;
}
}<file_sep><?php
if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
die ('Please do not load this page directly. Thanks!');
if ( post_password_required() ) { ?>
<?php _e('This post is password protected. Enter the password to view comments.','tl_theme');?>
<?php
return;
}
if ( have_comments() ) : ?>
<div id="comments">
<h2><?php comments_number('0', '1', '%'); ?> <?php _e('Comments', 'tl_theme'); ?>: "<?php the_title(); ?>"</h2>
<?php $args = array(
'walker' => null,
'style' => 'ol',
'callback' => 'tl_theme_comments',
'type' => 'all',
'avatar_size' => 70,
'reverse_top_level' => null );
?>
<ol>
<?php wp_list_comments($args); ?>
</ol>
</div> <!-- #comments -->
<?php else : // this is displayed if there are no comments so far ?>
<?php if ( comments_open() ) : ?>
<!-- If comments are open, but there are no comments. -->
<?php else : // comments are closed ?>
<p><?php _e('Comments are closed.', 'tl_theme'); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php comment_form(array('title_reply' => __( 'Leave a Reply', 'tl_theme' ),
'title_reply_to' => __( 'Leave a Reply to %s', 'tl_theme' ),
'cancel_reply_link' => __( 'Cancel reply', 'tl_theme' ),
'label_submit' => __( 'Post Comment' ,'tl_theme' )));
?><file_sep><?php
/*
Plugin Name: Custom Post Type Page Template
Plugin URI: http://wpgogo.com/development/custom-post-type-page-template.html
Description: This plugin enables custom post types directly to add page templates of the page type.
Author: <NAME>
Version: 1.0
Author URI: http://wpgogo.com/
*/
/* Copyright 2012 <NAME>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
class CustomPostTypePageTemplate {
public function __construct() {
//add_action( 'init', array(&$this, 'custom_post_type_page_template_init') );
add_action( 'admin_init', array(&$this, 'custom_post_type_page_template_admin_init') );
//add_action( 'admin_menu', array(&$this, 'custom_post_type_page_template_admin_menu') );
add_action( 'save_post', array(&$this, 'custom_post_type_page_template_save_post') );
add_filter( 'template_include', array(&$this, 'custom_post_type_page_template_template_include') );
add_action( 'template_redirect', array(&$this, 'custom_post_type_page_template_template_redirect') );
add_filter( 'body_class', array(&$this, 'custom_post_type_page_template_body_classes') );
}
public function custom_post_type_page_template_init() {
if ( function_exists('load_plugin_textdomain') ) {
if ( !defined('WP_PLUGIN_DIR') ) {
load_plugin_textdomain( 'custom-post-type-page-template', str_replace( ABSPATH, '', dirname(__FILE__) ) );
} else {
load_plugin_textdomain( 'custom-post-type-page-template', false, dirname( plugin_basename(__FILE__) ) );
}
}
}
public function custom_post_type_page_template_admin_init() {
$options['post_types'] = array('product');//get_option('custom_post_type_page_template');
if ( !empty($options['post_types']) && is_array($options['post_types']) ) :
foreach( $options['post_types'] as $post_type ) :
add_meta_box( 'pagetemplatediv', __('Page Template', 'custom-post-type-page-template'), array(&$this, 'custom_post_type_page_template_meta_box'), $post_type, 'side', 'core');
endforeach;
endif;
}
public function custom_post_type_page_template_admin_menu() {
add_options_page( __('Custom Post Type Page Template', 'custom-post-type-page-template'), __('Custom Post Type Page Template', 'custom-post-type-page-template'), 'manage_options', basename(__FILE__), array(&$this, 'custom_post_type_page_template_options_page') );
}
public function custom_post_type_page_template_meta_box($post) {
$template = get_post_meta($post->ID, '_wp_page_template', true);
?>
<label class="screen-reader-text" for="page_template"><?php _e('Page Template', 'custom-post-type-page-template') ?></label><select name="page_template" id="page_template">
<option value='default'><?php _e('Default Template', 'custom-post-type-page-template'); ?></option>
<?php page_template_dropdown($template); ?>
</select>
<?php
}
public function custom_post_type_page_template_save_post( $post_id ) {
if ( !empty($_POST['page_template']) ) :
if ( $_POST['page_template'] != 'default' ) :
update_post_meta($post_id, '_wp_page_template', $_POST['page_template']);
else :
delete_post_meta($post_id, '_wp_page_template');
endif;
endif;
}
public function custom_post_type_page_template_template_include($template) {
global $wp_query, $post;
if ( is_singular() && !is_page() ) :
$id = get_queried_object_id();
$new_template = get_post_meta( $id, '_wp_page_template', true );
if ( $new_template && file_exists(get_query_template( 'page', $new_template )) ) :
$wp_query->is_page = 1;
$templates[] = $new_template;
return get_query_template( 'page', $templates );
endif;
endif;
return $template;
}
public function custom_post_type_page_template_template_redirect() {
$options = get_option('custom_post_type_page_template');
if ( empty($options['enforcement_mode']) ) return;
global $wp_query;
if ( is_singular() && !is_page() ) :
wp_cache_delete($wp_query->post->ID, 'posts');
$GLOBALS['post']->post_type = 'page';
wp_cache_add($wp_query->post->ID, $GLOBALS['post'], 'posts');
endif;
}
public function custom_post_type_page_template_body_classes( $classes ) {
if ( is_singular() && is_page_template() ) :
$classes[] = 'page-template';
$classes[] = 'page-template-' . sanitize_html_class( str_replace( '.', '-', get_page_template_slug( get_queried_object_id() ) ) );
endif;
return $classes;
}
public function custom_post_type_page_template_options_page() {
$options = get_option('custom_post_type_page_template');
if ( !empty($_POST) ) :
if ( !empty($_POST['enforcement_mode']) ) $options['enforcement_mode'] = 1;
else unset($options['enforcement_mode']);
if ( empty($_POST['post_types']) ) :
delete_option('custom_post_type_page_template', $options);
unset($options['post_types']);
else :
$options['post_types'] = $_POST['post_types'];
update_option('custom_post_type_page_template', $options);
endif;
endif;
?>
<div class="wrap">
<div id="icon-plugins" class="icon32"><br/></div>
<h2><?php _e('Custom Post Type Page Template', 'custom-post-type-page-template'); ?></h2>
<?php
if ( !empty($_GET['settings-updated']) ) :
?>
<div id="message" class="updated"><p><strong><?php _e( 'Settings saved.', 'custom-post-type-page-template' ); ?></strong></p></div>
<?php
endif;
?>
<form action="?page=custom-post-type-page-template.php&settings-updated=true" method="post">
<table class="form-table">
<tbody>
<tr>
<th><label for="post_types"><?php _e('Custom Post Types', 'custom-post-type-page-template'); ?></label></th>
<td>
<?php
$post_types = get_post_types(array('public'=>true));
foreach( $post_types as $key => $val ) :
if ( $key == 'attachment' || $key == 'page' ) continue;
?>
<label><input type="checkbox" name="post_types[]" value="<?php echo $key; ?>"<?php if ( is_array($options['post_types']) && in_array($key, $options['post_types'])) echo ' checked="checked"'; ?> /> <?php echo $key; ?></label><br />
<?php
endforeach;
?>
</p>
</td>
</tr>
<tr>
<th><label for="enforcement_mode"><?php _e('Enforcement Mode', 'custom-post-type-page-template'); ?></label></th>
<td><label><input type="checkbox" name="enforcement_mode" id="enforcement_mode" value="1" <?php if ( !empty($options['enforcement_mode']) ) echo ' checked="checked"'; ?> /> <?php _e('Check this in case of using themes like Twenty Eleven, Twenty Twelve, etc.', 'custom-post-type-page-template'); ?></label></td>
</tr>
</tbody>
</table>
<p class="submit"><input type="submit" value="<?php _e('Save Changes', 'custom-post-type-page-template'); ?>" class="button-primary" id="submit" name="submit"></p>
</form>
<?php
}
}
global $custom_post_type_page_template;
$custom_post_type_page_template = new CustomPostTypePageTemplate();
?><file_sep><?php
/**
* Template Name: Home Page [Default]
* Description: Home Page with default.
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php get_header();
$hide_slider = Data()->isOn('mi_home.slider_hide_switch');
$show_featured = Data()->isOn('mi_home.featured_section_switch');
$slider = Data()->getSldr();
$slider_type = isset($slider['current_slider']) ? $slider['current_slider'] : '';
if($slider_type){
$slider_theme = $slider['data'][$slider_type]['settings']['theme'];
}else{
$slider_theme = '';
}
?>
<div id="content" class="home">
<div class="wrap"><h1><?php the_title(); ?></h1></div>
<div id="menu-categories" class="background home-page">
<div class="wrap">
<div id="homeLeft"><?php the_content(); ?></div>
<div id="slide"><?php echo do_shortcode("[metaslider id=121]"); ?></div>
</div>
</div>
<?php if(Data()->isOn('mi_footer.mi_footer2_switch')): ?>
<div id="sub-content">
<div class="wrap">
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("home_sidebar1") ) : ?><?php endif; ?>
</div><!-- end wrap -->
</div> <!-- end sub-content -->
<?php endif; ?>
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/*
All staff related to a header of the page
*/
/* Administration panel does NOT need this. Skip it. */
if(is_admin()){
return;
}
add_action('wp_print_scripts', 'add_scripts');
add_action('wp_print_styles', 'add_styles');
/* This script should be loaded always */
function add_scripts(){
//Fancybox
wp_enqueue_script(ThemeSetup::HOOK.'fancybox-js', TL_THEME_JS_URI . '/fancybox/jquery.fancybox-1.3.4.pack.js', array('jquery'), '1.3.4');
// Image Preloader
wp_enqueue_script(ThemeSetup::HOOK.'-preloaderjs', TL_THEME_JS_URI.'/preloader/jquery.preloader.js', array('jquery'));
// wp_enqueue_script(ThemeSetup::HOOK.'-tools', TL_THEME_JS_URI.'/jquery.tools.min.js', array('jquery'));
wp_enqueue_script(ThemeSetup::HOOK.'-loadingimages', TL_THEME_JS_URI.'/jquery.waitforimages.min.js', array('jquery'));
wp_enqueue_script('swfobject');
//Main Js File
wp_enqueue_script(ThemeSetup::HOOK.'-mainjs', TL_THEME_JS_URI.'/main.js', array('jquery', ThemeSetup::HOOK.'fancybox-js', ThemeSetup::HOOK.'-preloaderjs'));
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( ThemeSetup::HOOK.'-mainjs', ThemeSetup::HOOK . 'Ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce(ThemeSetup::HOOK . '-ajax-nonce-xxx')
));
if(defined('MLS_SHOWCASE') && MLS_SHOWCASE){
wp_enqueue_script(ThemeSetup::HOOK.'-cookie', TL_THEME_JS_URI.'/jquery.cookie.js', array('jquery'));
wp_enqueue_script(ThemeSetup::HOOK.'-color-switcher', TL_THEME_JS_URI.'/color-switcher.js', array('jquery', ThemeSetup::HOOK.'-cookie'));
}
if(is_page_template('template-page-book-table.php')){
wp_enqueue_script(ThemeSetup::HOOK . '-ui-uniform', TL_THEME_JS_URI . '/jquery.uniform/jquery.uniform.min.js', array('jquery'));
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_script('jquery-ui-widget');
wp_enqueue_script('jquery-ui-slider');
wp_enqueue_script(ThemeSetup::HOOK.'-timepicker-script', TL_THEME_JS_URI.'/jquery-ui-timepicker-addon.js', array('jquery', 'jquery-ui-datepicker'));//
wp_enqueue_script(ThemeSetup::HOOK.'-booktable-script', TL_THEME_JS_URI.'/book-table.js', array('jquery',ThemeSetup::HOOK . '-ui-uniform', 'jquery-ui-datepicker', ThemeSetup::HOOK.'-timepicker-script'));
}
if(is_page_template('template-page-contact.php')){ // Contact page specific js
/* Google Maps Staff */
$theme = ThemeSetup::getInstance()->getThemeDataObj();
if($theme->isOn('mi_gmaps.mi_gmaps_switch')){
wp_enqueue_script(ThemeSetup::HOOK . '-google-maps-api-js', 'http://maps.google.com/maps/api/js?sensor=false');
wp_enqueue_script(ThemeSetup::HOOK . '-googlemap-js', TL_THEME_JS_URI .'/googlemap.js', array('jquery', ThemeSetup::HOOK . '-google-maps-api-js'));
wp_localize_script(ThemeSetup::HOOK . '-googlemap-js', ThemeSetup::HOOK . 'Google', array('lat'=>$theme->getMain('mi_gmaps.mi_gmaps_lat'),
'long'=>$theme->getMain('mi_gmaps.mi_gmaps_long'),
'zoom'=>$theme->getMain('mi_gmaps.mi_gmaps_zoom')));
}
}
if(is_page_template('template-page-menu1.php')){
wp_enqueue_script(ThemeSetup::HOOK . 'jquery-easing-js', TL_THEME_JS_URI . '/jquery.easing.1.3.js', array('jquery'), '1.3.0');
wp_enqueue_script(ThemeSetup::HOOK .'jquery-bxslider', TL_THEME_JS_URI . '/jquery.bxslider/jquery.bxslider.min.js', array('jquery', ThemeSetup::HOOK . 'jquery-easing-js'));
}
/* This could be a place to put JS related to a sliders */
if(is_page_template('template-page-home-one.php') || is_page_template('template-page-showcase-full-slider-home-one.php') || is_page_template('template-page-showcase-standard-slider-home-one.php')){
//Get Slider type
if($slider_type = Data()->getCurrentSlider()){
switch ($slider_type){
case 'anything_slider':{
/* Get anything slider settings */
$tmp = Data()->getSldr('data.anything_slider.settings');
$carousel_data['display_type'] = Data()->getMain('mi_home.featured_section_display_type');
$carousel_data['items_per_row'] = Data()->getMain('mi_home.featured_section_items_per_row');
$carousel_data['portrait'] = Data()->getMain('mi_home.featured_section_items_portrait');
$carousel_data['featured_section_changeby'] = Data()->getMain('mi_home.featured_section_changeby');
$slider_settings = array(
'slider_type'=>'anything_slider',
'buildNavigation'=> 'off',
'buildStartStop' => 'off',
'buildArrows' => $tmp['buildArrows'],
'toggleArrows' => $tmp['toggleArrows'],
'hashTags' => false,
'autoPlay' => $tmp['autoPlay'],//
'mode' => $tmp['mode'],
'delay' => (int) $tmp['delay'],
'delayBeforeAnimate'=> (int) $tmp['delayBeforeAnimate'],
'easing' => $tmp['easing'],
'animationTime'=> (int)$tmp['animationTime'],
'theme' => $tmp['theme'],
'autoPlayLocked'=>$tmp['autoPlayLocked'],//
'autoPlayDelayed'=>$tmp['autoPlayDelayed'],//
'pauseOnHover'=>$tmp['pauseOnHover'],//
'stopAtEnd'=>$tmp['stopAtEnd'],//
'playRtl'=>$tmp['playRtl'],//
'resumeDelay'=>(int) $tmp['resumeDelay'],
'delayBeforeAnimate'=> (int)$tmp['delayBeforeAnimate'],
'allowRapidChange'=>$tmp['allowRapidChange']
);
if(is_page_template('template-page-showcase-full-slider-home-one.php') ){
$slider_settings['theme'] = 'Full';
}
if(is_page_template('template-page-showcase-standard-slider-home-one.php') ){
$slider_settings['theme'] = 'Standard';
}
$settings['slider'] = $slider_settings;
$settings['carousel'] = $carousel_data;
wp_enqueue_script(ThemeSetup::HOOK . '_'.$slider_type, TL_THEME_JS_URI . '/jquery.anythingslider.js', array('jquery'));
wp_enqueue_script(ThemeSetup::HOOK . 'jquery-easing-js', TL_THEME_JS_URI . '/jquery.easing.1.3.js', array('jquery'), '1.3.0');
//is there a video slide
wp_enqueue_script(ThemeSetup::HOOK . 'video', TL_THEME_JS_URI . '/jquery.anythingslider.video.js', array('jquery', ThemeSetup::HOOK . '_'.$slider_type));
wp_enqueue_script(ThemeSetup::HOOK . 'fx', TL_THEME_JS_URI . '/jquery.anythingslider.fx.js', array('jquery', ThemeSetup::HOOK . '_'.$slider_type));
wp_enqueue_script(ThemeSetup::HOOK . '_sliders', TL_THEME_JS_URI . '/sliders.js', array('jquery', ThemeSetup::HOOK . '_'.$slider_type));
wp_localize_script(ThemeSetup::HOOK . '_sliders', ThemeSetup::HOOK.'Sliders', $settings);
break;
}
}
}
}
}
/* Add Common styling */
function add_styles(){
$hook = 'tl_theme';
global $wp_styles;
//Get Main Css File
wp_register_style($hook . 'style', TL_THEME_URI . '/style.css');
wp_register_style($hook . 'style', get_bloginfo('stylesheet_url'));
wp_enqueue_style($hook . 'style');
//IE Fixes
wp_register_style( $hook . '-ie7-fix', TL_THEME_CSS_URI . '/ie7.css' );
$wp_styles->add_data( $hook . '-ie7-fix', 'conditional', 'IE 7' );
wp_enqueue_style($hook . '-ie7-fix');
wp_register_style( $hook . '-ie8-fix', TL_THEME_CSS_URI . '/ie8.css' );
$wp_styles->add_data( $hook . '-ie8-fix', 'conditional', 'IE 8' );
wp_enqueue_style($hook . '-ie8-fix');
/* Slider */
//if(is_front_page()){
if(is_page_template('template-page-home-one.php') || is_page_template('template-page-showcase-full-slider-home-one.php') || is_page_template('template-page-showcase-standard-slider-home-one.php')){
$slider_type = Data()->getCurrentSlider();
if($slider_type == 'anything_slider')
wp_enqueue_style($hook . '-anythingslider-css', TL_THEME_CSS_URI . '/anythingslider.css');
}
//Get Color Sheme
wp_register_style($hook . 'color-sheme',
TL_THEME_CSS_URI . '/color-shemes/'.Data()->getMain('mi_look_feel.color_sheme').'/'.Data()->getMain('mi_look_feel.color_sheme').'.css');
wp_enqueue_style($hook . 'color-sheme');
//Fancy Box CSS
wp_enqueue_style($hook.'fancybox-css', TL_THEME_JS_URI . '/fancybox/jquery.fancybox-1.3.4.css',array(), '1.3.4');
if(is_page_template('template-page-book-table.php')){
wp_enqueue_style($hook . '-ui-uniform-css', TL_THEME_JS_URI . '/jquery.uniform/uniform.default.css');
//wp_enqueue_style($hook . '-ui-datepicker-css', TL_THEME_JS_URI . '/jquery-ui-1.8.2.datepicker/smoothness/jquery-ui-1.8.2.custom.css');
wp_enqueue_style($hook . '-ui-datepicker-css', TL_THEME_JS_URI . '/jquery-ui-1.8.2.datepicker/smoothness/jquery-ui.css');
}
if(defined('MLS_SHOWCASE') && MLS_SHOWCASE){
wp_enqueue_style($hook.'color-switcher-css', TL_THEME_CSS_URI . '/select_color.css');
}
}<file_sep><?php
/**
* Template part: Home page middle section
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
$content_type = Data()->getMain('mi_home.featured_section_source_switch');
$show_read_more = Data()->isOn('mi_home.featured_section_readmore_switch');
$image_height = Data()->getMain('mi_home.featured_section_items_portrait');
/* Middle content content */
$content = array();
?>
<div id="menu-categories" class="background featured-<?php echo $content_type; ?> ">
<div class="wrap spacer">
<h1><?php echo the_title();?></h1>
<?php echo the_content();?>
</div>
<div class="wrap">
<?php if($content_type == 'post' || $content_type == 'page'): ?>
<?php
$item = call_user_func('mls_get_homepage_content', $content_type, array());
?>
<div class="c-12">
<div class="post-list">
<div class="post <?php echo $content_type; ?>-<?php echo $item->ID ?>">
<?php echo apply_filters('the_content', $item->post_content); ?>
</div><!-- .post -->
</div><!-- .post-list -->
</div><!-- .c-12 -->
<?php elseif($content_type == 'posts' || $content_type == 'pages' || $content_type == 'products'): //featured_section_pages ?>
<?php
$contents = call_user_func('mls_get_homepage_content', $content_type, array('cat'=>Data()->getMain('mi_home.featured_section_category')));
$category_name = get_the_category_by_ID(Data()->getMain('mi_home.featured_section_category'));
?>
<div id="menu-slider">
<ul>
<?php foreach ($contents as $post): setup_postdata($post);?>
<?php $p_meta = get_post_meta($post->ID);
if(isset($p_meta['product_meta_data'])){
$p_meta = unserialize($p_meta['product_meta_data'][0]);
$is_specialty = (isset($p_meta['special_switch']) && $p_meta['special_switch'] == 'on') ? true : false;
$price = (isset($p_meta['price']) && $p_meta['price']!='') ? $p_meta['price'] : '';
}else{
$is_specialty = false;
$price = '';
}
?>
<li>
<div>
<div>
<?php if($content_type == 'posts'): ?>
<p class="meta"><a href="#" title="<?php the_title(); ?>" class="category"><?php echo $category_name; ?></a></p>
<?php endif; ?>
<h3 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php if(has_post_thumbnail($post->ID)): ?>
<p class="image <?php echo ($price ? 'dish':''); ?>">
<a href="<?php the_permalink(); ?>">
<?php if($image_height == 'landscape') :
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'blog-middle-resp' );
else :
$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'portrait-middle' );
endif;
?>
<img title="<?php the_title(); ?>" src="<?php echo $thumbnail['0']; ?>" />
</a>
<?php if($price):?>
<span class="price"><?php echo $price ?></span>
<?php endif; ?>
</p>
<?php if(isset($is_specialty) && $is_specialty): ?>
<a title="<?php the_title() ?>" class="specialty" href="<?php the_permalink(); ?>"><?php _e('Specialty', 'tl_theme') ?></a>
<?php endif; ?>
<?php endif; ?>
<div class="excerpt">
<p><?php echo the_excerpt();?></p>
</div>
<?php if($show_read_more) :?>
<p class="actions"><a class="read-more-red" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php _e('Read More', 'tl_theme')?></a></p>
<?php endif; ?>
</div>
</div>
</li>
<?php endforeach; ?>
</ul>
<div class="prev-menu-slider"></div>
<div class="next-menu-slider"></div>
</div><!-- #menu-slider -->
<?php else: ?>
<?php endif; ?>
</div><!-- end wrap -->
</div><!-- end menu-categories --> <file_sep><?php
class ProductPostType extends CustomPostTypeHelper{
public function __construct($name){
parent::__construct($name, array(
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'map_meta_cap'=> true,
'hierarchical' => false,
'menu_position' => 5,
'supports' => array('title', 'editor', 'thumbnail', 'excerpt','page-attributes'),
'taxonomies' => array('food_type', 'page', 'post_tag')
),
array(
'name' => _x( 'Products', 'Product', 'tl_theme' ),
'singular_name' => _x( 'Product', 'Product', 'tl_theme' ),
'add_new' => _x( 'Add Product', 'product', 'tl_theme' ),
'add_new_item' => __( 'Add New Product' , 'tl_theme'),
'edit_item' => __( 'Edit Product' , 'tl_theme'),
'new_item' => __( 'New Product' , 'tl_theme' ),
'all_items' => __( 'All Products', 'tl_theme' ),
'view_item' => __( 'View Product', 'tl_theme' ),
'search_items' => __( 'Search Products', 'tl_theme' ),
'not_found' => __( 'No products found', 'tl_theme'),
'not_found_in_trash' => __( 'No products found in Trash', 'tl_theme'),
'parent_item_colon' => '',
'menu_name' => 'Products'
)
);
$tax_labels = array(
'name' => _x( 'Food Categories', 'taxonomy general name' , 'tl_theme_admin'),
'singular_name' => _x( 'Food Category', 'taxonomy singular name' , 'tl_theme_admin'),
'search_items' => __( 'Search Food Categories' , 'tl_theme_admin'),
'all_items' => __( 'All Food Categories' , 'tl_theme_admin'),
'parent_item' => __( 'Parent Category' , 'tl_theme_admin'),
'parent_item_colon' => __( 'Parent Category :', 'tl_theme_admin' ),
'edit_item' => __( 'Edit Food Category', 'tl_theme_admin'),
'update_item' => __( 'Update Food Category', 'tl_theme_admin' ),
'add_new_item' => __( 'Add New Food Category', 'tl_theme_admin' ),
'new_item_name' => __( 'New Food Category Name' , 'tl_theme_admin'),
'menu_name' => 'Food Categories',
);
$this->add_taxonomy('Food Category','food_type', $tax_labels, array('hierarchical'=>true, 'rewrite'=>array('slug'=>'food')));
}
}
$meta_fields = array(
array('id'=>'price','label'=>__('Price','tl_theme_admin'),'type'=>'text','value'=>'', 'default'=>''),
array('id'=>'special_switch','label'=>__('Is Specialty','tl_theme_admin'),'type'=>'checkbox','value'=>'', 'default'=>'')
);
$meta_box1 = array('id' => 'product_attributes',
'title' => __('Product Attributes', 'tl_theme_admin'),
'callback' => null,
'context' => 'advanced',
'priority' => 'high',
'callback_args' => $meta_fields);
$taxonomi_args = array();
$productPostTypeObj = new ProductPostType('Product', array(), array());
$productPostTypeObj->addMetaBox($meta_box1);<file_sep><?php
/**
* Template Name: Events Template without sidebar
* Description: List of events without sidebar
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php get_header(); ?>
<?php get_template_part( 'template', 'part-ribbon' ); ?>
<?php
global $wp_query;
$args = array( 'post_type' => 'event', 'order'=>'ASC', 'orderby' => 'menu_order',
'paged' => get_query_var('paged')
);
query_posts( $args );
?>
<div id="content">
<div class="wrap">
<div class="c-12 divider">
<div class="post-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<?php $meta_values = eventsMetaData($post->ID); ?>
<div class="post events dashed">
<h2 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<ul class="events-calendar">
<li class="day"><?php echo $meta_values['day'] ?></li>
<li><?php echo $meta_values['month'] ?></li>
</ul>
<p class="meta">
<span><?php _e('Date', 'tl_theme'); ?>: <a class="time" title="" href="#"><?php echo $meta_values['month'].' '.$meta_values['day'] .' '.$meta_values['year'].', ' . $meta_values['hours']; ?></a></span>
<span><?php _e('Place', 'tl_theme'); ?>: <a class="author" title="" href="#"><?php echo $meta_values['place'] ?> </a></span>
<span><?php _e('No. participants', 'tl_theme'); ?>: <a class="author" title="" href="#"><?php echo $meta_values['no_participants'] ?> </a></span>
</p>
<div class="excerpt">
<p><?php the_excerpt(); ?></p>
</div>
<p class="actions"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" class="read-more-red"><?php _e('Read More', 'tl_theme'); ?></a></p>
</div><!-- end post -->
<?php endwhile; endif; ?>
<?php wp_pagenavi(array('class'=>'pagination',
'options'=> array('pages_text'=>' ',
'first_text' => '',
'last_text' => '',
'always_show' => false,
'use_pagenavi_css'=>false,
'prev_text' => __('Previous', 'tl_theme'),
'next_text' => __('Next', 'tl_theme'),
))
); ?>
</div><!-- end post-list -->
</div>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?>
<file_sep><?php
class TlThemeWorkingHoursWidget extends WP_Widget {
/**
* Constructor
*/
public function __construct() {
$widget_ops = array('classname' => 'widget-restaurant-hours',
'description' => __( 'Working Hours Box', 'tl_theme_admin'));
parent::__construct(
'working_hours',
__('Mazzareli Working Hours Widget','tl_theme_admin'),
$widget_ops
);
}
/**
* Outputs the options form on admin
* @see WP_Widget::form()
* @param $instance current settings
*/
public function form( $instance ) {
$default = array( 'title' => __('Working Hours Box Title', 'tl_theme_admin'),
'subtitle1' => 'Breakfast',
'days1' => 'Monday - Friday',
'hours1' => '07:00 am - 10:30 pm',
'days11' => 'Saturday - Sunday',
'hours11' => '08:00 am - 10:30 pm',
'subtitle2' => 'Lunch',
'days2' => 'Monday - Friday',
'hours2' => '12:00 am - 3:30 pm',
'days21' => 'Saturday - Sunday',
'hours21' => '12:00 am - 3:30 pm');
$instance = wp_parse_args((array) $instance, $default);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Box Title', 'tl_theme_admin'); ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" value="<?php echo esc_attr($instance['title']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('subtitle1'); ?>"><?php _e('Subtitle 1','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('subtitle1'); ?>" id="<?php echo $this->get_field_id('subtitle1'); ?>" value="<?php echo esc_attr($instance['subtitle1']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('days1'); ?>"><?php _e('Days','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('days1'); ?>" id="<?php echo $this->get_field_id('days1'); ?>" value="<?php echo esc_attr($instance['days1']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('hours1'); ?>"><?php _e('Working Hours','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('hours1'); ?>" id="<?php echo $this->get_field_id('hours1'); ?>" value="<?php echo esc_attr($instance['hours1']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('days11'); ?>"><?php _e('Days','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('days11'); ?>" id="<?php echo $this->get_field_id('days11'); ?>" value="<?php echo esc_attr($instance['days11']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('hours11'); ?>"><?php _e('Working Hours','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('hours11'); ?>" id="<?php echo $this->get_field_id('hours11'); ?>" value="<?php echo esc_attr($instance['hours11']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('subtitle2'); ?>"><?php _e('Subtitle 2','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('subtitle2'); ?>" id="<?php echo $this->get_field_id('subtitle2'); ?>" value="<?php echo esc_attr($instance['subtitle2']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('days2'); ?>"><?php _e('Days','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('days2'); ?>" id="<?php echo $this->get_field_id('days2'); ?>" value="<?php echo esc_attr($instance['days2']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('hours2'); ?>"><?php _e('Working Hours','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('hours2'); ?>" id="<?php echo $this->get_field_id('hours2'); ?>" value="<?php echo esc_attr($instance['hours2']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('days21'); ?>"><?php _e('Days','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('days21'); ?>" id="<?php echo $this->get_field_id('days21'); ?>" value="<?php echo esc_attr($instance['days21']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('hours21'); ?>"><?php _e('Working Hours','tl_theme_admin') ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('hours21'); ?>" id="<?php echo $this->get_field_id('hours21'); ?>" value="<?php echo esc_attr($instance['hours21']); ?>" />
</p>
<?php
}
/**
* processes widget options to be saved
* @see WP_Widget::update()
*/
public function update( $new_instance, $old_instance ) {
if(empty($old_instance)){
$old_instance = $new_instance;
}
$instance = $old_instance;
foreach ($instance as $k => $value) {
$instance[$k] = trim(strip_tags($new_instance[$k]));
}
return $instance;
}
/**
* Front-end display of widget.
* @see WP_Widget::widget()
* @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
* @param array $instance The settings for the particular instance of the widget
*
* address, phone, fax, email
*/
public function widget( $args, $instance ) {
extract( $args );
$title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
$subtitle1 = empty($instance['subtitle1']) ? '' : apply_filters('widget_title', $instance['subtitle1']);
$days1 = empty($instance['days1']) ? '' : apply_filters('widget_title', $instance['days1']);
$hours1 = empty($instance['hours1']) ? '' : apply_filters('widget_title', $instance['hours1']);
$days11 = empty($instance['days11']) ? '' : apply_filters('widget_title', $instance['days11']);
$hours11 = empty($instance['hours11']) ? '' : apply_filters('widget_title', $instance['hours11']);
$subtitle2 = empty($instance['subtitle2']) ? '' : apply_filters('widget_title', $instance['subtitle2']);
$days2 = empty($instance['days2']) ? '' : apply_filters('widget_title', $instance['days2']);
$hours2 = empty($instance['hours2']) ? '' : apply_filters('widget_title', $instance['hours2']);
$days21 = empty($instance['days21']) ? '' : apply_filters('widget_title', $instance['days21']);
$hours21 = empty($instance['hours21']) ? '' : apply_filters('widget_title', $instance['hours21']);
echo $before_widget;
?>
<?php if($title): echo $before_title . $title . $after_title; endif; ?>
<?php if($subtitle1): ?>
<ul class="restaurant-hours">
<li><p class="meta"><?php echo $subtitle1; ?></p></li>
<?php if($days1):?><li><label><?php echo $days1 ?></label><span><?php echo $hours1 ?></span></li><?php endif; ?>
<?php if($days11):?><li><label><?php echo $days11 ?></label><span><?php echo $hours11 ?></span></li><?php endif; ?>
</ul>
<?php endif; ?>
<?php if($subtitle2): ?>
<ul class="restaurant-hours">
<li><p class="meta"><?php echo $subtitle2; ?></p></li>
<?php if($days2):?><li><label><?php echo $days2 ?></label><span><?php echo $hours2 ?></span></li><?php endif; ?>
<?php if($days21):?><li><label><?php echo $days21 ?></label><span><?php echo $hours21 ?></span></li><?php endif; ?>
</ul>
<?php endif; ?>
<?php
echo $after_widget;
}
} //Class End
register_widget('TlThemeWorkingHoursWidget');<file_sep><?php
/**
* Options Management Class
*
* Manage all bussiness logic related to insert, update, delete data from DB.
*
*
* 1. Instalacija Prilikom instalacije upisujem samo meta podatke u bazu. Datum instalacije i verziju!
* 2. Inace
*
* Ucitam konf. iz fajlova.
* Ucitam podatke iz DB.
* Populisem settings niz.
*
* U prikazu sve vrednosti se prikazuju preko fje koje proverava ako je "value" NULL onda ide default vrednost.
* Dakle DEFAULT vrednost se prikazuje sve do onog trenutka dok korisnik eksplicitno ne izabere neku opciju! Tj. do prvog
* pritiska na dugme SAVE!
*
*/
/*
Standalone Class used by ThemeSetup and ThemeAdmin classes.
Saves, Deletes, Updates Theme Options.
Restores options to their default states.
*/
class ThemeOptions {
/* All options form DB for option key $option_key */
protected $options = array();
/* Under this key we are saving option in DB. */
protected $option_key = null;
/* Defaults loaded from files */
public $conf_files = array();
/**
* Flag
*/
protected $conf_files_loaded = false;
/**
* Array indexes related to a form data. This is
*/
public $data_index = array('mi_look_feel','mi_blog','mi_social','mi_contact','mi_google_analitics','mi_header','mi_footer','mi_misc','mi_gmaps','mi_custom_sidebars');
/**
* Default settings loaded form config files [$conf_files]. This array could be considered as template
*/
public $settings_tpl = array();
/**
* Settings loaded from config file, but also populated with data form DB
*/
public $settings = array();
/* All errors */
public $errors = array();
/**
* Constructor
*/
public function __construct($option_key){
$this->option_key = $option_key;
$this->options = get_option($this->option_key,
array('meta' => array(),
'main_settings' => array(),
'collections' => array('sliders'=>array()))
);
$this->loadConfFiles();
if($this->optionsLoaded()){
$this->setValuesFromDB();
}
}
protected function loadConfFiles(){
if($this->conf_files_loaded === true) return ;
try{
$this->loadSettings(TL_THEME_CONFIG_DIR . '/' . 'default_theme_options.php');
$this->loadSettings(TL_THEME_CONFIG_DIR . '/' . 'default_slider_options.php');
//Set tpl structure to real struture. Real structure will be updateded with data from DB. In case there is no sliders. Those data
//will be unset from settings arr
$inc = $this->settings_tpl['sliders_tpl']['data']['sliders']['incommon'];
$this->settings_tpl['sliders_tpl']['data']['sliders']['current_slider'] = '';
$this->settings_tpl['sliders_tpl']['data']['sliders']['piece_slider']['incommon'] = $inc;
//$this->settings_tpl['sliders_tpl']['data']['sliders']['cycle_slider']['incommon'] = $inc;
$this->settings_tpl['sliders_tpl']['data']['sliders']['anything_slider']['incommon'] = $inc;
//exit;
unset($this->settings_tpl['sliders_tpl']['data']['sliders']['incommon']);
$this->settings = $this->settings_tpl;
// unset($this->settings['sliders_tpl']['data']['sliders']['cycle_slider']['item_data']);
unset($this->settings['sliders_tpl']['data']['sliders']['piece_slider']['item_data']);
unset($this->settings['sliders_tpl']['data']['sliders']['anything_slider']['item_data']);
$this->conf_files_loaded = true;
}catch (FrameworkException $e){
$this->errors[] = 'Unable to load settings. : ' . $e->getMessage();
}
}
/**
* Inject data in to $this->settings arrays.
* Apply all settings from DB to Settings array
*
* Rebuild Main Settings
* Rebuil Created Sliders
*/
protected function setValuesFromDB(){
$types_to_replace = array('text', 'select', 'file', 'checkbox', 'radio', 'textarea', 'date', 'multiselect', 'number', 'hidden', 'list', 'map');
/* !IMPORTANT! Variable $main is POINTER to a one part od settings array!!! */
$main = &$this->getSetting('main_settings.data.items'); // returns main settings data from conf file!
foreach ($main as $key => $section) {
foreach ($section as $kk => $value){
if(isset($value['type']) && in_array($value['type'], $types_to_replace)){
$main[$key][$kk]['value'] = $this->getOption('main_settings.'.$key.'.'.$value['id']);
}
}
}
//Get sliders from DB
$sliders = $this->getOption('collections.sliders');
//Get sliders configurations
//$sliders_conf = $this->getSlidersTpls(); //sliders conf from file!
if(!empty($sliders))
{
/* Id of active slider */
$current_slider_type = $sliders['current_slider'];
foreach ($sliders['data'] as $slider_key => $slider){
//Set Settings related to a slider
$settings =& $this->settings['sliders_tpl']['data']['sliders'][$slider_key]['settings'];
$transition =& $this->settings['sliders_tpl']['data']['sliders'][$slider_key]['transition'];
$incommon =& $this->settings['sliders_tpl']['data']['sliders'][$slider_key]['incommon'];
foreach ($incommon as $k => $field) {
//Da li je ova vrednost definisana u bazi
if(isset($slider['incommon'][$k])){
$incommon[$k]['value'] = $slider['incommon'][$k];
}
}
foreach ($settings as $k => $field) {
//Da li je ova vrednost definisana u bazi
if(isset($slider['settings'][$field['id']]) && $field['type']!='start_sub_section'){
$settings[$k]['value'] = $slider['settings'][$field['id']];
}
}
if(is_array($transition) && !empty($transition)){
foreach ($transition as $k => $field) {
if(isset($slider['transition'][$field['id']])){
$transition[$k]['value'] = $slider['transition'][$field['id']];
}
}
}
$this->settings['sliders_tpl']['data']['sliders'][$slider_key]['item_data'] = array();
if(isset($slider['item_data']) && is_array($slider['item_data']) && count($slider['item_data']) > 0){
foreach ($slider['item_data'] as $key => $value) {//idem po slajdovima
$slide_tpl = $this->settings_tpl['sliders_tpl']['data']['sliders'][$slider_key]['item_data'];
foreach ($slide_tpl as $k => $tpl) {
if($tpl['type'] != 'start_sub_section')
$slide_tpl[$k]['value'] = $value[$tpl['id']];
}
$this->settings['sliders_tpl']['data']['sliders'][$slider_key]['item_data'][] = $slide_tpl; //Push new slide
}
}
}//foreach
unset($this->settings['sliders_tpl']['data']['sliders']['incommon']);
//Do we have at least one slide created
$this->settings['sliders_tpl']['data']['sliders']['current_slider'] = $current_slider_type;
}else{
//Remove template for a slide form array related to builting slider form, because we do not have one!.
unset($this->settings['sliders_tpl']);
}
}
/**
* Prepare / Format $this->options from $this->settings array.
* Rebuilt options array for SAVE / EDIT ... purpose!!!
*/
public function filterSettingsForDb($filterMain=true, $filterSliders = true){
$types_to_replace = array('text', 'select', 'file', 'checkbox', 'textarea', 'date', 'multiselect', 'number', 'hidden', 'list');
if($filterMain == true){
$main = $this->getSetting('main_settings.data.items');
$tmp = null;
foreach ($main as $key => $section) {
foreach ($section as $kk=>$value){
if(isset($value['type']) && in_array($value['type'], $types_to_replace)){
$tmp = ($value['value']!== null && $value['value']!== '') ? $value['value'] : $value['default'];
$this->setOption('main_settings.'.$key.'.'.$value['id'], $tmp);
$tmp = null;
}
}
}
}
/**
* In case there is no sliders. Do nothing. Sliders do not require any initializations.
*/
if($filterSliders == true){
$sliders = &$this->getSetting('sliders_tpl');
}
}
/**
* Loads Default setting from conf files.
* @param string $file
* @param boolean $overwrite
*/
protected function loadSettings($file, $overwrite = true){
if(file_exists($file) && is_readable($file)){
require_once $file;
if(isset($meta_data) && is_array($meta_data) && $meta_data['name']!=''){
if($overwrite){
$this->settings_tpl[$meta_data['name']] = array('meta' => $meta_data, 'data' => $options);
}
}
else{
$this->errors[$file] = __('Config file corrupted!', 'tl_theme');
}
}
else{
$this->errors[$file] = __('Unable to read file','tl_theme') .$file.'. '. __('Or file missing!','tl_theme');
}
}
/**
* [$path description]
* @var [type]
*/
public function &getSetting($path = null) {
reset($this->settings);
$null = null;
if($path === null) {
return $this->settings;
}
$segs = explode('.', $path);
$target =& $this->settings;
for($i = 0; $i < count($segs)-1; $i++) {
if(isset($target[$segs[$i]]) && is_array($target[$segs[$i]])) {
$target =& $target[$segs[$i]];
} else {
return $null; //Stupid fix to suppress Notice Error
}
}
if(isset($target[$segs[count($segs)-1]])) {
return $target[$segs[count($segs)-1]];
} else {
return $null; //Stupid fix to suppress Notice Error
}
}
public function &getSettingTpl($path = null) {
reset($this->settings_tpl);
if($path === null) {
return $this->settings_tpl;
exit;
}
$segs = explode('.', $path);
$target =& $this->settings_tpl;
for($i = 0; $i < count($segs)-1; $i++) {
if(isset($target[$segs[$i]]) && is_array($target[$segs[$i]])) {
$target =& $target[$segs[$i]];
} else {
return null;
}
}
if(isset($target[$segs[count($segs)-1]])) {
return $target[$segs[count($segs)-1]];
} else {
return null;
}
}
/**
*
* Enter description here ...
* @param unknown_type $key
*/
protected function &getMenuItems(){
return $this->settings['main_settings']['data']['menu_items'];
}
protected function &getTabItems(){
return $this->settings['main_settings']['data']['tabs'];
}
protected function &getMainSettingsFormElements(){
return $this->settings['main_settings']['data']['items'];
}
protected function getSlidersTpls(){
return $this->settings_tpl['sliders_tpl'];
}
/**
* Cemu ovo sluzi i da li se negde koristi?
* @param unknown_type $key
*/
/*public function defsLoaded($key){
return isset($this->settings[$key]);
}*/
public function file_ok($file){
return file_exists($file) && is_readable($file);
}
//DB realted staff
public function optionsLoaded(){
return (is_array($this->options['main_settings']) && count($this->options['main_settings']) > 0);
}
/**
* This methid is called only once. When theme is installing. Load def . vals. Set data to structure proledjuje na snimanje
*/
public function setOptionsDefaults()
{
$this->setOption('meta.version', ThemeSetup::THEME_VERSION);
if(!$this->hasErrors()){
$this->filterSettingsForDb(true, false);
}
return $this;
}
/**
* Saves ALL the internal options data to the wp_options table using the stored $option_key value as the key
*
* @return boolean
*/
public function save()
{
//Delete old data set new data
return update_option($this->option_key, $this->options);
}
/**
* Deletes the internal options data from the wp_options table.
* This method is intended to be used as part of the uninstall process.
*
* @return boolean
*/
public function delete()
{
return delete_option($this->option_key);
}
/**
* Alias for __set
* @param mixed $path (string or array)
* @param mixed $value
*/
public function setOption($path, $value){
return $this->__set($path, $value);
}
public function __set($path, $value = null) {
if(is_array($path)) {
foreach($path as $p => $v) {
$this->__set($p, $v);
}
} else {
$segs = explode('.', $path);
$target =& $this->options;
for($i = 0; $i < count($segs)-1; $i++) {
if(!isset($target[$segs[$i]])) {
$target[$segs[$i]] = array();
}
$target =& $target[$segs[$i]];
}
$target[$segs[count($segs)-1]] = $value;
}
return $this;
}
/**
* Alias for __get
* @param string $param
*/
public function getOption($param=null){
return $this->__get($param);
}
/* These Two ,ethods sholuld be used on View ALWAYS */
public function getMain($opt = null){
$opt = isset($opt) ? 'main_settings.' . $opt : 'main_settings';
return $this->__get( $opt);
}
public function echoMain($opt = null){
$opt = isset($opt) ? 'main_settings.' . $opt : 'main_settings';
echo stripslashes($this->__get( $opt));
}
public function isOn($opt){
if($this->getMain($opt) == 'on'){
return true;
}else{
return false;
}
}
public function getSliderOpts(){
return $this->options['collections']['sliders'];
}
public function getSldr($path=''){
if($path) $path = '.' . $path;
return $this->__get('collections.sliders' . $path);
}
public function getCurrentSlider(){
return $this->__get('collections.sliders.current_slider');
}
/**
* Gets the value at the specified path.
*/
public function __get($path = null) {
if($path === null) {
return $this->options;
exit;
}
$segs = explode('.', $path);
$target =& $this->options;
for($i = 0; $i < count($segs)-1; $i++) {
if(isset($target[$segs[$i]]) && is_array($target[$segs[$i]])) {
$target =& $target[$segs[$i]];
} else {
return null;
}
}
if(isset($target[$segs[count($segs)-1]])) {
return $target[$segs[count($segs)-1]];
} else {
return null;
}
}
/**
* Returns a flattened version of the data (one-dimensional array
* with dot-separated paths as its keys).
*/
public function flatten($path = null) {
$data = $this->__get($path);
if($path === null) {
$path = '';
} else {
$path .= '.';
}
$flat = array();
foreach($data as $key => $value) {
if(is_array($value)) {
$flat += $this->flatten($path.$key);
} else {
$flat[$path.$key] = $value;
}
}
return $flat;
}
/**
* Expands a flattened array to an n-dimensional matrix.
*/
public static function expand($flat) {
$matrix = new self();
foreach($flat as $key => $value) {
$matrix->__set($key, $value);
}
return $matrix;
}
public function getAllOptions()
{
return $this->__get();
}
public function hasErrors(){
return !empty($this->errors);
}
public function getErrors(){
return $this->errors;
}
public function setError($msg){
$this->errors[] = $msg;
}
/**
* @todo Implement it :)
*/
public function _toString(){}
}<file_sep><?php
/**
* NOT IN USE.... AT MOMENT
* @todo decide what to do with this widget
*/
class TlThemeContactInfoWidget extends WP_Widget {
/**
* Constructor
*/
public function __construct() {
$widget_ops = array('classname' => 'widget-address',
'description' => __( 'Contact Info', 'tl_theme_admin'));
parent::__construct(
'contact_info',
__( 'Mazzareli Contact Info Widget','tl_theme_admin'),
$widget_ops
);
}
/**
* Outputs the options form on admin
* @see WP_Widget::form()
* @param $instance current settings
*/
public function form( $instance ) {
$fields_of_intereset = array('address', 'tel', 'fax', 'email');
$themeObj = ThemeSetup::getInstance();
$data = array();
if(isset($themeObj)){ //Data Obj Present
$data = $themeObj->getThemeDataObj()->getSetting('main_settings.data.items.mi_contact');
$datax = array();
foreach ($data as $v){ // By Fields
if(in_array($v['id'], $fields_of_intereset)){
$datax[$v['id']] = array('value'=>$v['value'], 'title'=> $v['name']);
if(!empty($instance))
$instance[$v['id']] = array('value'=>$instance[$v['id']], 'title'=> $v['name']);
}
}
if(isset($instance['title']))
$instance['title'] = array('value'=>$instance['title'], 'title'=> __('Address Box Title', 'tl_theme'));
}
$default = array( 'title' => array('title' => __('Address Box Title', 'tl_theme'), 'value'=>__('Address', 'tl_theme')),
'address' => $datax['address'],
'fax' => $datax['fax'],
'tel' => $datax['tel'],
'email' => $datax['email']);
$instance = wp_parse_args((array) $instance, $default);
?>
<?php foreach ($instance as $k=>$v) : ?>
<p>
<label for="<?php echo $this->get_field_id($k); ?>"><?php echo $instance[$k]['title'] ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name($k); ?>" id="<?php echo $this->get_field_id($k); ?>" value="<?php echo esc_attr($instance[$k]['value']); ?>" />
</p>
<?php endforeach; ?>
<?php
}
/**
* processes widget options to be saved
* @see WP_Widget::update()
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
if(empty($old_instance)){
$old_instance = $new_instance;
}
foreach ($old_instance as $k => $value) {
$instance[$k] = trim(strip_tags($new_instance[$k]));
}
return $instance;
}
/**
* Front-end display of widget.
* @see WP_Widget::widget()
* @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
* @param array $instance The settings for the particular instance of the widget
*
* address, phone, fax, email
*/
public function widget( $args, $instance ) {
extract( $args );
$title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
$address = empty($instance['address']) ? '' : apply_filters('widget_title', $instance['address']);
$fax = empty($instance['fax']) ? '' : apply_filters('widget_title', $instance['fax']);
$tel = empty($instance['tel']) ? '' : apply_filters('widget_title', $instance['tel']);
$email = empty($instance['email']) ? '' : apply_filters('widget_title', $instance['email']);
echo $before_widget;
?>
<?php if($title): echo $before_title . $title . $after_title; endif; ?>
<ul>
<?php if($address !='') :?>
<li>
<p class="meta"><?php _e('Main office', "tl_theme_admin"); ?>: </p>
<p><?php echo esc_attr($address);?></p>
</li>
<?php endif; ?>
<?php if($tel !='') :?>
<li>
<p class="meta"><?php _e('Phone', "tl_theme_admin"); ?>: </p>
<p><?php echo esc_attr($tel);?></p>
</li>
<?php endif; ?>
<?php if($fax !='') :?>
<li>
<p class="meta"><?php _e('Fax', "tl_theme_admin"); ?>: </p>
<p><?php echo esc_attr($fax);?></p>
</li>
<?php endif; ?>
<?php if($email !='') :?>
<li>
<p class="meta"><?php _e('E-mail', "tl_theme_admin"); ?>: </p>
<p><a href="mailto:<?php echo esc_attr($email);?>"><?php echo esc_attr($email);?></a></p>
</li>
<?php endif; ?>
</ul>
<?php
echo $after_widget;
}
} //Class End
register_widget('KidsContactInfoWidget');
<file_sep><?php
class TestimonialsPostType extends CustomPostTypeHelper{
public function __construct($name){
parent::__construct($name, array(
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'map_meta_cap'=> true,
'hierarchical' => false,
'has_archive'=> true,
'menu_position' => 5,
'supports' => array('editor','title', 'page-attributes')
),
array(
'name' => _x( 'Testimonials', 'Testimonial', 'tl_theme' ),
'singular_name' => _x( 'Testimonial', 'Testimonial', 'tl_theme' ),
'add_new' => _x( 'Add New', 'testimonial', 'tl_theme' ),
'add_new_item' => __( 'Add New Testimonial' , 'tl_theme'),
'edit_item' => __( 'Edit Testimonial' , 'tl_theme'),
'new_item' => __( 'New Testimonial' , 'tl_theme' ),
'all_items' => __( 'All Testimonial', 'tl_theme' ),
'view_item' => __( 'View Testimonial', 'tl_theme' ),
'search_items' => __( 'Search Testimonials', 'tl_theme' ),
'not_found' => __( 'No testimonials found', 'tl_theme'),
'not_found_in_trash' => __( 'No testimonials found in Trash', 'tl_theme'),
'parent_item_colon' => '',
'menu_name' => 'Testimonials'
)
);
}
}
$meta_fields = array(
array('id'=>'name','label'=>__('Name', 'tl_theme_admin'),'type'=>'text','value'=>'', 'default'=>''),
array('id'=>'additional_info','label'=>__('Addition info', 'tl_theme_admin'),'type'=>'text','value'=>'', 'default'=>'')
);
$meta_box1 = array('id' => 'testimonials_attributes',
'title' => __('Testimonials Attributes', 'tl_theme_admin'),
'callback' => null,
'context' => 'side',
'priority' => 'high',
'callback_args' => $meta_fields);
$testimonialsPostTypeObj = new TestimonialsPostType('Testimonial');
$testimonialsPostTypeObj->addMetaBox($meta_box1);<file_sep><?php
require 'class.phpmailer-lite.php';
class ThemeMailer extends PHPMailerLite
{
/**
* Fields Map
* @var unknown_type
*/
protected $fields = array();
/* Submited data */
protected $data = array();
/**
* List of Errors
* Enter description here ...
* @var unknown_type
*/
public $errors = array();
/**
* Request sent by Ajax request
* @var unknown_type
*/
/**
* JSON response
* @var unknown_type
*/
public $response = null;
/**
Output flag
*/
protected $echo = false;
protected $rawData = array();
/* Contact form or book a table*/
protected $type = '';
protected $ajax_flag = false;
public function __construct ($fields = array(), $type = "contact")
{
parent::__construct();
if (empty($fields)) {
throw new Exception('List of fields is required.', '1000');
}
if (! empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$this->ajax_flag = true;
}
$this->fields = $fields;
$this->type = $type;
$this->rawData = $_POST['form_data'];
}
public function sanitarize ()
{
foreach ($this->fields as $f_name => $value) {
if(isset($this->rawData[$f_name])){
$this->data[$f_name] = strip_tags( $this->rawData[$f_name]);
$this->data[$f_name] = trim( $this->data[$f_name]);
}
else{
$this->data[$f_name] = '';
}
}
}
public function validate ()
{
foreach ($this->fields as $f_name => $value) {
$validators = explode('|', $value);
if (isset($validators[0]) && $validators[0] == '*' && $this->data[$f_name] == '') { // Required
$this->errors[$f_name] = __('Required','tl_theme');
} else {
if( $this->data[$f_name] != ''){
if (isset($validators[1]) && method_exists($this, $validators[1])) {
$valid = $this->{$validators[1]}( $this->data[$f_name]);
if (! $valid) {
$this->errors[$f_name] = __('Invalid Data', 'tl_theme');
}
}
}
}
}
return !$this->hasErrors();
}
public function doMagic ()
{
$this->sanitarize();
if ($this->validate()) { // success
//Get Data from DB
$wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$opts = get_option('tl_theme_options');
if($this->type == 'contact'){
if(!empty($opts)){
/* Data for Auto response */
$sender = $receiver = $opts['main_settings']['mi_contact']['email_contact_form'];
$sender_name = $opts['main_settings']['mi_contact']['email_sender_name'];
$auto_response_flag = $opts['main_settings']['mi_contact']['switch_auto_reply'];
//Send mail to a site owner
try {
/* Message for owner */
$mail_body = $this->buildMsgBody();
$this->IsMail();
$this->IsHTML(true);
$this->CharSet = 'utf-8';
$this->SetFrom($sender, $sender_name);
$this->AddAddress($sender, 'Contact Form');
$this->Subject = __('Message sent via contact form.', 'tl_theme');
$this->AltBody = __('To view the message, please use an HTML compatible email viewer!', 'tl_theme'); // optional - MsgHTML will create an alternate automatically
$this->Body = $this->buildMsgBody();
if(!$this->Send()){
$this->errors['msg'] = __('Unable to send an e-mail message. Please contact an administrator.', 'tl_theme');
}
} catch (phpmailerException $e) {
$this->errors['msg'] = $e->errorMessage();
} catch (Exception $e) {
$this->errors['msg'] = $e->errorMessage();
}
$this->ClearAddresses();
if(!$this->hasErrors() && $auto_response_flag == 'on' && $this->data['email']!=''){
$subject = $opts['main_settings']['mi_contact']['email_subject']; //For user who filled in a contact form
$auto_response = $opts['main_settings']['mi_contact']['auto_msg'];
$auto_response = nl2br($auto_response);
/* Message to visitor */
try {
$this->IsMail();
$this->IsHTML(false);
$this->CharSet = 'utf-8';
$this->SetFrom($sender, $sender_name);
$this->AddAddress($this->data['email'], $this->data['name']);
$this->Subject = $subject;
$this->AltBody = $auto_response;
$this->Body = $auto_response;
if(!$this->Send()){
$this->errors['msg'] = __('Unable to send an e-mail message. Please contact an administrator.', 'tl_theme');
}
} catch (phpmailerException $e) {
$this->errors['msg'] = $e->errorMessage();
} catch (Exception $e) {
$this->errors['msg'] = $e->errorMessage();
}
}
} else{
$this->errors['msg'] = __('Unable to Sent an email message. Please try again.', 'tl_theme');
}
}elseif ($this->type == 'book'){
if(!empty($opts)){
/* Data for Auto response */
$sender = $receiver = $opts['main_settings']['mi_contact']['book_email'];
$sender_name = $opts['main_settings']['mi_contact']['email_sender_name'];
$auto_response_flag = $opts['main_settings']['mi_contact']['switch_book_auto_reply'];
/* This is subject for receipient! */
$subject = $opts['main_settings']['mi_contact']['book_email_subject'];
$auto_response = $opts['main_settings']['mi_contact']['book_auto_msg'];
$auto_response = nl2br($auto_response);
//Send mail to a site owner
try {
/* Message for owner */
//$mail_body = $this->buildMsgBody();
$this->IsMail();
$this->IsHTML(true);
$this->CharSet = 'utf-8';
$this->SetFrom($sender, $sender_name);
$this->AddAddress($sender, 'Book a Table Form');
$this->Subject = __('Message sent via Book a Table form.', 'tl_theme');
$this->AltBody = __('To view the message, please use an HTML compatible email viewer!', 'tl_theme');
$this->Body = $this->buildBookMsgBody();
if(!$this->Send()){
$this->errors['msg'] = __('Unable to send an e-mail message. Please contact an administrator.', 'tl_theme');
}
} catch (phpmailerException $e) {
$this->errors['msg'] = $e->errorMessage();
} catch (Exception $e) {
$this->errors['msg'] = $e->errorMessage();
}
$this->ClearAddresses();
if(!$this->hasErrors() && $auto_response_flag == 'on' && $this->data['email']!=''){
/* Message to visitor */
try {
$this->IsMail();
$this->IsHTML(false);
$this->CharSet = 'utf-8';
$this->SetFrom($sender, $sender_name);
$this->AddAddress($this->data['email'], $this->data['name']);
$this->Subject = $subject;
$this->AltBody = $auto_response;
$this->Body = $auto_response;
if(!$this->Send()){
$this->errors['msg'] = __('Unable to send an e-mail message. Please contact an administrator.', 'tl_theme');
}
} catch (phpmailerException $e) {
$this->errors['msg'] = $e->errorMessage();
} catch (Exception $e) {
$this->errors['msg'] = $e->errorMessage();
}
}
} else{
$this->errors['msg'] = __('Unable to Sent an email message. Please try again.', 'tl_theme');
}
}
} else{
$this->errors['msg'] = __('Fields marked with an Asterisk (*) are required.', 'tl_theme');
}
if($this->hasErrors()){
$response = array('status' => 'error', 'data' => $this->errors);
} else{
$response = array('status' => 'success', 'data'=> array('msg' => __('Mail Sent. Thank You!', 'tl_theme')));
}
$this->response = $response;
if ($this->ajax_flag === true && $this->echo) {
die(json_encode($response));
} else {
//Do something smart!
}
}
public function buildBookMsgBody(){
$body = '<p>'.__("Mail sent via Book a Table form.","tl_theme").'</p>';
$body .= '<ul>';
$body .= '<li>'.__("Number of guests:","tl_theme").' '.$this->data['size'].'</li>';
$body .= '<li>'.__("Date:","tl_theme").' '.$this->data['date'].'</li>';
$body .= '<li>'.__("Mail:","tl_theme").' '.$this->data['email'].'</li>';
$body .= '<li>'.__("Phone:","tl_theme").' '.$this->data['phone'].'</li>';
$body .= '<li>'.__("Additional info:","tl_theme").' '.$this->data['notes'].'</li>';
$body .= '</ul>';
return $body;
}
public function buildMsgBody(){
$body = '<p>'.__("Mail sent via contact form.","tl_theme").'</p>';
$body .= '<ul>';
$body .= '<li>'.__("Name:","tl_theme").' '.$this->data['name'].'</li>';
$body .= '<li>'.__("Subject:","tl_theme").' '.$this->data['subject'].'</li>';
$body .= '<li>'.__("Mail:","tl_theme").' '.$this->data['email'].'</li>';
$body .= '<li>'.__("Web Address:","tl_theme").' '.$this->data['website'].'</li>';
$body .= '<li>'.__("Message:","tl_theme").' '.$this->data['message'].'</li>';
$body .= '</ul>';
return $body;
}
public function hasErrors ()
{
return !empty($this->errors);
}
protected function v_plain ($txt)
{
return true;
}
protected function v_text($subject)
{
//return preg_match("/[ a-zA-Z0-9\.,\-'\\\"]/u", $subject);
return preg_match("/[\p{L}\p{M}\p{Z}\p{S}\p{N}]+/", $subject); //unicode version
}
protected function v_mail($address)
{
if (function_exists('filter_var')) { //Introduced in PHP 5.2
if (filter_var($address, FILTER_VALIDATE_EMAIL) == false) {
return false;
} else {
return true;
}
} else {
return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/',
$address);
}
}
protected function v_url($url)
{ //Introduced in PHP 5.2
/* if (function_exists('filter_var')) { //Introduced in PHP 5.2
if (filter_var($url, FILTER_VALIDATE_URL) == false) {
return false;
} else {
return true;
}
}else{*/
$regex = "/^((http|https):\/\/){0,1}([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
return preg_match($regex, $url);
// }
}
public function getJsonResponse(){
return $this->response;
}
}<file_sep><div id="sidebar" class="c-4 sidebar">
<?php global $post; if ( !function_exists('dynamic_sidebar') || !mls_custom_dynamic_sidebar($post->ID, "contact_sidebar") ) : ?>
<?php endif; ?>
</div><file_sep><?php
/**
* Helper functions
*/
/**
*
* Enter description here ...
* @param unknown_type $data
* @param unknown_type $echo
*/
function mls_renderSlider($data = array(), $echo = true){
$output = '';
if(!empty($data)){
$slider_type = $data['current_slider'];
$settings = $data['data'][$slider_type]['settings'];
$slides = $data['data'][$slider_type]['item_data'];
switch ($slider_type){
case 'anything_slider':{
$slider = new AnythingSlider($settings, $slides);
break;
}
}
if(isset($slider)){
$output = $slider->render();
}
}
if($echo){
echo $output;
}
}
function mls_attachment_url_to_id( $file_url ){
global $wpdb;
/* Get upload folder */
$upload_dir = wp_upload_dir();
$filename = str_replace( $upload_dir['baseurl'] . '/', '', $file_url);
$rows = $wpdb->get_results( $wpdb->prepare("
SELECT ".$wpdb->posts.".ID, ".$wpdb->postmeta.".meta_value
FROM ".$wpdb->posts."
INNER JOIN ".$wpdb->postmeta." ON ".$wpdb->posts.".ID = ".$wpdb->postmeta.".post_id
AND ".$wpdb->postmeta.".meta_key = '_wp_attached_file'
AND ".$wpdb->postmeta.".meta_value LIKE %s LIMIT 1", like_escape($filename)));
$rows = isset($rows[0]) ? $rows[0]->ID : 0;
return $rows;
}
/**
*
* Enter description here ...
* @param unknown_type $str
* @param unknown_type $wordsreturned
*/
function mls_abstract($str = '', $wordsreturned = 20, $echo=false, $not_strip = array('<p>')){
//Strip all tags
$str = strip_tags($str, implode('', $not_strip));
$retval = $str;
$array = explode(' ', $str);
if (count($array) <= $wordsreturned) {
$retval = $str;
}
else {
array_splice($array, $wordsreturned);
$retval = implode(' ', $array).'...';
}
if($echo){
echo $retval;
}else{
return $retval;
}
}
function mls_the_excerpt_max_charlength($excerpt, $charlength) {
$charlength++;
$retval ='';
if ( mb_strlen( $excerpt ) > $charlength ) {
$subex = mb_substr( $excerpt, 0, $charlength - 5 );
$exwords = mb_split( ' ', $subex );
$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
$retval .= $subex;
$retval .= '...';
} else {
$retval .= $excerpt;
}
return $retval;
}
/**
*
* Enter description here ...
* @param unknown_type $options
* @param unknown_type $selected
* @param unknown_type $attribs
* @param unknown_type $echo
*/
function mls_RenderSelectBox($options, $current=null, $attribs = array('class'=>'', 'id'=>'', 'name'=>'', 'multi'=>false), $echo = false){
$output = '';
$options_str = '';
foreach ($options as $k=>$v){
if(is_array($selected)){
$selected = (in_array($k, $current)) ? 'selected' : '';
}
else{ // echo $k . '==' . $current."\n\n";
$selected = ($k == $current) ? 'selected' : '';
}
$options_str .= '<option value="'.esc_attr($k).'" '.$selected.' >'.esc_attr($v).'</option>';
}
$output = '<select ' .
($attribs['name'] ? 'name="'.$attribs['name'].'"' : 'name="select_box"') .'"' .
($attribs['id'] ? 'id="'.$attribs['id'].'"' : 'id="select_box_id"') .
($attribs['multi'] ? 'multiply="multiply"' : '') .
($attribs['class'] ? 'class="'.$attribs['class'].'"' : '') .
' >'
. $options_str .
'</select>';
if($echo){
echo $output;
}else{
return $output;
}
}<file_sep><?php
$readmore = Data()->getMain('mi_blog.readmore');
$hide_cats = Data()->getMain('mi_blog.hide_cats');
$hide_cats_tmp = array();
if($hide_cats){
foreach ($hide_cats as $value) {
$hide_cats_tmp[] = (string)($value * (-1));
}
}
?>
<?php get_header();?>
<?php get_template_part('template-part-ribbon'); ?>
<?php
// global $query_string;
// var_dump($query_string);
// query_posts( $query_string . '&order=DESC&orderby=date&paged='.get_query_var('paged').'&cat='.implode(',', $hide_cats_tmp) );
?>
<div id="content">
<div class="wrap">
<div class="c-12 divider">
<div class="post-list blog-posts">
<?php if(have_posts()): ?>
<?php
$queryq = strip_tags(trim($_GET['s']));
$queryq = apply_filters( 'get_search_query', $queryq );
$queryq = esc_attr( $queryq );
?>
<h2><?php printf( __( 'Search Results for: %s', 'tl_theme' ), '<span>' . $queryq. '</span>' ); ?></h2>
<?php while (have_posts()) : the_post(); ?>
<div class="devider post post-<?php the_ID(); ?>">
<?php if(has_post_thumbnail()): ?>
<div class="item-image">
<p class="image"><a href="<?php the_permalink(); ?>" class="image">
<span class="post-image-mask"></span>
<?php the_post_thumbnail('small-thumb'); ?>
</a></p></div>
<?php endif; ?>
<h2 class="title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<div class="excerpt">
<p><?php the_excerpt(); ?></p>
</div>
<div class="clearfix"></div>
</div><!-- end post -->
<?php endwhile; ?>
<?php else : ?>
<h2><?php _e('Nothing Found', 'tl_theme') ?></h2>
<?php endif; ?>
<?php wp_pagenavi(array('class'=>'pagination','options'=> array('pages_text'=>' ',
'first_text' => '',
'last_text' => '',
'always_show' => false,
'use_pagenavi_css'=>false,
'prev_text' => '<span class="circle-arrow-left"></span>'. __('Previous', 'kids_theme'),
'next_text' => '<span class="circle-arrow"></span>'. __('Next', 'kids_theme'),
))
); ?>
</div><!-- end post-list -->
</div>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer();?><file_sep><?php
/**
* Template Name: Contact Template Page Mazzareli
* Description: Contact Page
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php get_header(); ?>
<?php get_template_part( 'template', 'part-ribbon' ); ?>
<div id="content">
<div class="wrap">
<div class="c-8 divider">
<div class="page contact-page">
<p>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</p>
<?php if(Data()->isOn('mi_contact.form_switch')): ?>
<div class="contact-modal-box"></div>
<form enctype="multipart/form-data" method="post" id="reservationform">
<div class="send-form">
<p>
<label>*<?php _e('Your Name','tl_theme')?>:</label>
<input class="u-4" name="name" id="name1" />
</p>
<p>
<label>*<?php _e('Your E-mail','tl_theme')?>:</label>
<input class="u-4" name="email" id="email1" />
</p>
<p>
<label><?php _e('Your Website','tl_theme')?>:</label>
<input class="u-4" name="website" id="website1" />
</p>
<p>
<label><?php _e('Subject','tl_theme')?>:</label>
<input class="u-4" name="subject" id="subject1" />
</p>
<p>
<label><?php _e('Your Message','tl_theme')?>:</label>
<textarea class="u-6" name="message" id="message1" cols="80" rows="5"></textarea>
<br/>
</p>
<p>
<a id="send-btn" class="contact-button button dark"><span><?php _e('Contact Us','tl_theme')?></span></a>
<a id="reset-btn" class="button-reset button red"><span><?php _e('Clear form','tl_theme')?></span></a>
</p>
</div><!-- end book-table-form -->
</form>
<?php endif; ?>
<?php if(Data()->isOn('mi_gmaps.mi_gmaps_switch')): ?>
<div class="google-map">
<h3><?php _e('Find us on Google Maps','tl_theme')?></h3>
<div class="google-map-background">
<div id="google-map-location"></div>
</div>
</div><!--end google-map-->
<?php endif; ?>
</div><!-- end entry -->
</div>
<?php get_sidebar('contact'); ?>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer();?><file_sep><?php
class Validator{
public static $instance = null;
public $errors = array();
public $map = array();
//This filter is applied to all data
public $filters = array('trim'=>'trim');
public $apply_filters_flag = true;
/* Reference to input data fubmited from a form */
public $data = null;
public function __construct($map, &$data){
$this->map =& $map;
$this->data =& $data;
}
public function __clone(){}
/**
* Niz polja u kojima su definisali validatori i filteri
*
* Podaci iz POST-a
*
* Kako odratiti strukturi
*
* @param unknown_type $map
* @param unknown_type $data
*/
public function getInstance($map, &$data){
if(self::$instance === null){
$obj = new Validator();
}else {
$obj =& self::$instance;
}
$obj->map =& $map;
$obj->data =& $data;
return $obj;
}
public function resetMap(){
$this->map = null;
}
public function prepareMap($settings){
$map = array();
/**
* field_id => array('validators'=> array(), 'filters'=>array())
*/
$types_to_replace = array('text', 'select', 'file', 'checkbox','radio', 'textarea', 'date', 'multiselect', 'number', 'hidden', 'list');
foreach ($settings as $section => $setting){
foreach ($setting as $value) {
if(isset($value['type']) && in_array($value['type'], $types_to_replace)){ //ako je polje za validaciju
$this->map[$section][$value['id']] = array();
$this->map[$section][$value['id']]['type'] = $value['type'];
if(!isset($this->data[$section][$value['id']])){
//1. Checkbox not checked
//2. Multiselect not checked
//3. Radio Button noting selected
$this->data[$section][$value['id']] = '';
}
if($value['type'] == 'multiselect' && !is_array($this->data[$section][$value['id']])){
if(isset($this->data[$section][$value['id']])){
$this->data[$section][$value['id']] = array($this->data[$section][$value['id']]);
}else{
$this->data[$section][$value['id']] = array('empty');
}
}
if(isset($value['required']) && $value['required']){
$this->map[$section][$value['id']]['required'] = $value['required'];
}
if(isset($value['validators'])){
$this->map[$section][$value['id']]['validators'] = $value['validators'];
}
if(isset($value['filters'])){
$this->map[$section][$value['id']]['filters'] = $value['filters'];
}
}
}
}
}
/**
* This function is used when user trigger SAVE SLIDER action. We are maping this so we can validate and apply filters on input data
*
* @todo We could format config arrays that way so we do NOT need this mapping at all!> Now is too late :)
* @param array $settings settings from template for sliders
* @param string $slider_type slider type
* @return void [nothing]
*
*/
public function prepareMapSliders($settings, $slider_type){
$map = array();
/**
* field_id => array('validators'=> array(), 'filters'=>array())
*/
$types_to_replace = array('text', 'select', 'file', 'checkbox','radio', 'textarea', 'date', 'multiselect', 'number', 'hidden', 'list');
$incommon_settings = $settings[$slider_type]['incommon'];
$sl_settings = $settings[$slider_type]['settings'];
$slides = $settings[$slider_type]['item_data'];
$transitions = isset($settings[$slider_type]['transition']) ? $settings[$slider_type]['transition'] : array();
if($slider_type){
/* Incommon staff */
foreach ($incommon_settings as $key => $setting) { // By fields
if(isset($setting['type']) && in_array($setting['type'], $types_to_replace)){
if($setting['type'] == 'multiselect' && !is_array($this->data['incommon'][$setting['id']])){
if(isset($this->data['incommon'][$setting['id']])){
$this->data['incommon'][$setting['id']] = array($this->data['incommon'][$setting['id']]);
}else{
$this->data['incommon'][$setting['id']] = array('empty');
}
}
if(!isset($this->data['incommon'][$setting['id']])){
$this->data['incommon'][$setting['id']] = $setting['default'];
}
$this->map['incommon'][$setting['id']]['id'] = $setting['id']; // this is VERY ODD.
$this->map['incommon'][$setting['id']]['id']['type'] = $setting['type'];
if(isset($setting['required']) && $setting['required']){
$this->map['incommon'][$setting['id']]['required'] = $setting['required'];
}
if(isset($setting['validators'])){
$this->map['incommon'][$setting['id']]['validators'] = $setting['validators'];
}
if(isset($setting['filters'])){
$this->map['incommon'][$setting['id']]['filters'] = $setting['filters'];
}
}
}
/* Slider Options */
foreach ($sl_settings as $key => $setting){
if(isset($setting['type']) && in_array($setting['type'], $types_to_replace)){
$this->map['settings'][$setting['id']]['id'] = $setting['id'];
if($setting['type'] == 'multiselect' && !is_array($this->data['settings'][$setting['id']])){
if(isset($this->data['settings'][$setting['id']])){
$this->data['settings'][$setting['id']] = array($this->data['settings'][$setting['id']]);
}else{
$this->data['settings'][$setting['id']] = array('empty');
}
}
if(!isset($this->data['settings'][$setting['id']])){
$this->data['settings'][$setting['id']] = $setting['default'];
}
if(isset($setting['required']) && $setting['required']){
$this->map['settings'][$setting['id']]['required'] = $setting['required'];
}
if(isset($setting['validators'])){
$this->map['settings'][$setting['id']]['validators'] = $setting['validators'];
}
if(isset($setting['filters'])){
$this->map['settings'][$setting['id']]['filters'] = $setting['filters'];
}
}
}
/* Slider's Slides */
foreach ($slides as $key => $setting){
if(isset($setting['type']) && in_array($setting['type'], $types_to_replace) && isset($this->data['item_data']) && count($this->data['item_data']) > 0){
if(isset($setting['required']) && $setting['required']){
$this->map['item_data'][$setting['id']]['required'] = $setting['required'];
}
$this->map['item_data'][$setting['id']]['id'] = $setting['id'];
if(isset($setting['validators'])){
$this->map['item_data'][$setting['id']]['validators'] = $setting['validators'];
}
/* Apply default filters */
if(isset($setting['filters'])){
$this->map['item_data'][$setting['id']]['filters'] = $setting['filters'];
}
}elseif (!isset($this->data['item_data']) || count($this->data['item_data']) == 0){
$this->setError('item_data', 'Slider must have at least one slide.');
}
}
foreach ($transitions as $setting) {
if(isset($setting['type']) && in_array($setting['type'], $types_to_replace)){
$this->map['transition'][$setting['id']]['id'] = $setting['id'];
if($setting['type'] == 'multiselect' && !is_array($this->data['transition'][$setting['id']])){
if(isset($this->data['transition'][$setting['id']])){
$this->data['transition'][$setting['id']] = array($this->data['transition'][$setting['id']]);
}else{
$this->data['transition'][$setting['id']] = array('empty');
}
}
if(!isset($this->data['transition'][$setting['id']])){
$this->data['transition'][$setting['id']] = $setting['default'];
}
if(isset($setting['required']) && $setting['required']){
$this->map['transition'][$setting['id']]['required'] = $setting['required'];
}
if(isset($setting['validators'])){
$this->map['transition'][$setting['id']]['validators'] = $setting['validators'];
}
if(isset($setting['filters'])){
$this->map['transition'][$setting['id']]['filters'] = $setting['filters'];
}
}
}
}
}
/**
* Validation of an input data
* @return [type]
*/
public function validate(){
if(isset($this->data['incommon'])){ // we are dealing with sliders
if(isset($this->data['item_data'])){
foreach($this->data['item_data'] as $i => $slide){ // By slides
foreach ($this->map['item_data'] as $id => $value) { //by fields
if(isset($value['required']) && $value['required'] ===true){
if(!isset($this->data['item_data'][$i][$id]) || $this->data['item_data'][$i][$id]=='' || empty($this->data['item_data'][$i][$id])){
$this->setError($id, 'Required data.');
}
}
if(!$this->fieldHasErrors($id)){
//Proceede with validation
if(isset($this->data['item_data'][$i][$id]) && $this->data['item_data'][$i][$id]!=''){ //!empty($this->data['item_data'][$i][$id])
if (isset($value['validators']) && is_array($value['validators'])){
foreach ($value['validators'] as $validator){
if(!$this->{$validator}($this->data['item_data'][$i][$id])){
$this->setError($id, 'NOT VALID');
}
}
}
}else{
/* Checkbox, multiselect etc... */
if($value['type'] == 'multiselect' && !is_array($this->data['item_data'][$i][$value['id']])){
if(isset($this->data['item_data'][$i][$value['id']])){
$this->data['item_data'][$i][$value['id']] = array($this->data['item_data'][$i][$value['id']]);
}else{
$this->data['item_data'][$i][$value['id']] = array('empty');
}
}
if(!isset($this->data['item_data'][$i][$value['id']])){
$this->data['item_data'][$i][$value['id']] = $value['default'];
}
}
}
}// by fields
} //end foreach for slides
}
foreach ($this->map as $sec_key=>$section) // by sections Slider validation
{
if($sec_key == 'item_data') continue;
foreach ($section as $id => $value) { //by fields
if(isset($value['required']) && $value['required'] ===true){
if(!isset($this->data[$sec_key][$id]) || $this->data[$sec_key][$id]=='' || empty($this->data[$sec_key][$id])){
$this->setError($id, 'Required data.');
}
}
if(!$this->fieldHasErrors($id)){
//Proceede with validation
if(isset($this->data[$sec_key][$id]) && $this->data[$sec_key][$id]!='' && !empty($this->data[$sec_key][$id])){
if (isset($value['validators']) && is_array($value['validators'])){
foreach ($value['validators'] as $validator){
if(!$this->{$validator}($this->data[$sec_key][$id])){
$this->setError($id, 'NOT VALID');
}
}
}
}
}
}// by fields
} //foreach
}
else{ //Validation of Main Settings
foreach ($this->map as $sec_key=>$section) // by sections
{
foreach ($section as $id => $value) { //by fields
if(isset($value['required']) && $value['required'] ===true){
if(!isset($this->data[$sec_key][$id]) || $this->data[$sec_key][$id]=='' || empty($this->data[$sec_key][$id])){
$this->setError($id, 'Required data.');
}
}
if(!$this->fieldHasErrors($id)){
//Proceede with validation
if(isset($this->data[$sec_key][$id]) && $this->data[$sec_key][$id]!='' && !empty($this->data[$sec_key][$id])){
if (isset($value['validators']) && is_array($value['validators'])){
foreach ($value['validators'] as $validator){
if(!$this->{$validator}($this->data[$sec_key][$id])){
$this->setError($id, 'NOT VALID');
}
}
}
}
}
}// by fields
} //foreach
}
if($this->hasErrors()){
return false;
}
else{
return true;
}
}
/**
* Enter description here ...
* @param unknown_type $filters
* @param unknown_type $data
*/
public function applyFilters(){
foreach ($this->map as $sec_key => $section) // by sections
{
if($sec_key == 'item_data') continue; // slides are handeled separatedly
foreach ($section as $id => $value) {
//Proccede with validation
if(isset($this->data[$sec_key][$id]) && $this->data[$sec_key][$id]!='' && !empty($this->data[$sec_key][$id])){
//data set
if(!isset($value['filters'])) $value['filters'] = array();
$filters_extra = array_merge($value['filters'], $this->filters);
//if (isset($value['filters']) && is_array($value['filters'])){ //filter set
if (isset($filters_extra) && is_array($filters_extra)){ //filter set
foreach ($filters_extra as $filter){
/* echo $id . "->";
var_dump($this->data[$sec_key][$id]);*/
$this->_applyFilter($this->data[$sec_key][$id], $filter);
}
}
}
} //foreach
}
/* if(isset($this->data['item_data']) && is_array($this->data['item_data'])){
foreach ($this->data['item_data'] as $key => $slide) {
foreach ($this->map['item_data'] as $id => $slide_map) {
if(!isset($slide_map['filters'])) $slide_map['filters'] = array();
$filters_extra = array_merge($slide_map['filters'], $this->filters);
foreach ($filters_extra as $filter){
$this->_applyFilter($this->data['item_data'][$key][$id], $filter);
}
}
}
}
var_dump($this->data['item_data']);
exit;*/
// $filters_extra
}
/**
* Enter description here ...
* @param mixed $el
* @param string $filter
*/
public function _applyFilter(&$el, $filter=null)
{
if(method_exists($this, $filter)){
if(is_array($el) && !empty($el)){
foreach ($el as $k => $v){
//$el[$k] = $this->_applyFilter($v, $filter);
$el[$k] = $this->{$filter}($v);
}
}else {
$el = $this->{$filter}($el);
}
}else{
throw new Exception("Filter does not exists", 1);
}
}
public function trim($param){
return trim($param);
}
public function stripslashes($param){
return stripslashes($param);
}
/**
* This filters are applied to all data
* @param unknown_type $fil
*/
public function addFilter($fil){
$this->filters[$fil] = $fil;
}
/**
* * This filters are applied to all data
* Enter description here ...
* @param unknown_type $fil
*/
public function removeFilter($fil){
if(isset($this->filters[$fil])){
unset($this->filetes[$fil]);
}
}
/**
* Return an error message for particulat fieldn if any
* @param string $id
*/
public function fieldHasErrors($id){
return (isset($this->errors[$id])) ? $this->errors[$id] : false;
}
public function hasErrors(){
return !empty($this->errors);
}
public function toString(){
$html = '';
if($this->hasErrors()){
foreach ($this->errors as $key => $value) {
$html += "<li>$value</li>";
}
$html = '<ul>'.$html.'</ul>';
}
else{
$html = '<p>'.__('No Errors', 'tl_theme_admin').'</p>';
}
return $html;
}
protected function setError($id, $error){
$this->errors[$id] = $error;
}
/*
* Vraca ID polja u kom je doslo do greske
*/
public function getErrors(){
return $this->errors;
}
/* From this point validators */
protected function _email($email){
return is_email($email);
}
protected function _alfa($param){ return true; }
protected function _alfaNumeric($param){
return true;
}
protected function _int($param){
return is_int($param);
}
protected function _numeric($param){
return is_numeric($param);
}
protected function _float($param){
return is_float($param);
}
protected function _noNull($param){
return (isset($param) && $param != '') ? true : false;
}
protected function _url($param){
$regex = '/(http|ftp|https):\/\/[\w\-_]+((\.[\w\-_]+)+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/';
return (preg_match($regex, $param) > 0) ? true : false;
}
protected function _phone($param){
return true;
}
/* Sanitarizers */
protected function strip_tags($param){
return strip_tags($param);
}
protected function intVal($param){
return (int) $param;
}
}<file_sep><?php
$custom_css = Data()->getMain('mi_misc.mi_custom_css');
$logo_defined = (Data()->getMain('mi_look_feel.mi_logo') != '' && Data()->getMain('mi_look_feel.mi_logo') != null) ? Data()->getMain('mi_look_feel.mi_logo') : false;
$logo_h = (Data()->getMain('mi_look_feel.logo_height') !='' && Data()->getMain('mi_look_feel.logo_height') != null) ? Data()->getMain('mi_look_feel.logo_height') : false;
$logo_w = (Data()->getMain('mi_look_feel.logo_width') !='' && Data()->getMain('mi_look_feel.logo_width') != null) ? Data()->getMain('mi_look_feel.logo_width') : false;
$book_table_switch = Data()->isOn('mi_header.book_table_switch');
$book_table_id = getPagesByTemplate(1, 'template-page-book-table.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title><?php
if (function_exists('is_tag') && is_tag()) {
single_tag_title("Tag Archive for ""); echo '" - '; }
elseif (is_archive()) {
wp_title('');
echo ' ';
_e('Archive', 'tl_theme');
echo ' - ';}
elseif (is_search()) {
_e('Search for','tl_theme');
echo ' "'.esc_html($s).'" - '; }
elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(' ');
echo ' ';
}
elseif (is_404()) {
_e('Not Found', 'tl_theme'); echo ' - ';
}
if (is_home() || is_front_page()) {
bloginfo('name');
echo ' - ';
bloginfo('description'); }
else {
bloginfo('name'); }
if ($paged>1) {
echo ' ' . __('- page','tl_theme').' '. $paged; }
?></title>
<!-- Site Description -->
<meta name="description" content="<?php echo dynamic_meta_description(); ?>" />
<!-- WP Tags goes here -->
<meta name="keywords" content="<?php echo csv_tags(); ?>" />
<meta name="Robots" content="index, follow" />
<!-- Favicon -->
<link rel="shortcut icon" href="<?php echo Data()->getMain('mi_look_feel.mi_favicon'); ?>" type="image/x-icon" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); //This Code should be elsewhere... ?>
<!-- Custom CSS and style related to a logo -->
<style type="text/css">
<?php echo $custom_css; ?>
<?php if($logo_defined) {// User defined logo ?>
h1 a { background: none !important; }
<?php } ?>
</style>
<script type="text/javascript">
// <![CDATA[
var settings = {'themeurl':'<?php echo get_template_directory_uri(); ?>'};
// ]]>
</script>
<?php
if(Data()->isOn('mi_google_analitics.google_analitics_switch')):
Data()->echoMain('mi_google_analitics.google_analitics');
endif;
?>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="header">
<?php if(defined('MLS_SHOWCASE') && MLS_SHOWCASE) :?>
<ul id="nav">
<li><a class="black" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/black/black.css" href="#"></a></li>
<li><a class="grey" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/grey/grey.css" href="#"></a></li>
<li><a class="coffee" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/coffee/coffee.css" href="#"></a></li>
<li><a class="deep-blue" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/deep-blue/deep-blue.css" href="#"></a></li>
<li><a class="blue" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/blue/blue.css" href="#"></a></li>
<li><a class="turquoise" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/turquoise/turquoise.css" href="#"></a></li>
<li><a class="green" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/green/green.css" href="#"></a></li>
<li><a class="lime" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/lime/lime.css" href="#"></a></li>
<li><a class="purple" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/purple/purple.css" href="#"></a></li>
<li><a class="pink" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/pink/pink.css" href="#"></a></li>
<li><a class="yellow" rel="<?php echo TL_THEME_CSS_URI; ?>/color-shemes/yellow/yellow.css" href="#"></a></li>
</ul>
<?php endif; ?>
<div class="wrap">
<h1 class="logo">
<a href="<?php echo home_url(); ?>/"><?php if($logo_defined): ?>
<img <?php echo ($logo_h ? 'height="'.$logo_h.'"' : '' ); ?> <?php echo ($logo_h ? 'width="'.$logo_w.'"' : '' ); ?> src="<?php echo Data()->getMain('mi_look_feel.mi_logo'); ?>" title="<?php bloginfo('name'); ?>"/><?php endif; ?>
</a>
</h1>
<?php if(Data()->isOn('mi_social.switch')): ?>
<div class="c4" style="float: right;">
<ul class="social-bookmarking">
<li><a class="rss" title="News Feed" href="<?php echo home_url(); ?>/news/"></a></li>
<!--<li><a target="_blank" class="fb" title="Facebook Profile" href="https://www.facebook.com/LaPetiteAcademy"></a></li>-->
<?php if(Data()->getMain('mi_social.twitter')): ?><li><a target="_blank" class="tw" title="Twitter Profile" href="http://twitter.com/<?php Data()->echoMain('mi_social.twitter'); ?>"></a></li><?php endif;?>
<?php if(Data()->getMain('mi_social.facebook')): ?><li><a target="_blank" class="fb" title="Facebook" href="<?php Data()->echoMain('mi_social.facebook'); ?>"></a></li><?php endif;?>
<?php if(Data()->getMain('mi_social.linkedin')): ?><li><a target="_blank" class="in" title="LinkedIn Profile " href="<?php Data()->echoMain('mi_social.linkedin'); ?>"></a></li><?php endif;?>
<?php if(Data()->getMain('mi_social.pinterest')): ?><li><a target="_blank" class="pin" title="Pintrest Profile " href="<?php Data()->echoMain('mi_social.pinterest'); ?>"></a></li><?php endif;?>
<?php if(Data()->getMain('mi_social.youtube')): ?><li><a target="_blank" class="youtube" title="Youtube channel" href="<?php Data()->echoMain('mi_social.youtube'); ?>"></a></li><?php endif;?>
<?php if(Data()->getMain('mi_social.googleplus')): ?><li><a target="_blank" class="google" title="Google Plus" href="<?php Data()->echoMain('mi_social.googleplus'); ?>"></a></li><?php endif;?>
</ul>
</div>
<?php endif; ?>
<?php if($book_table_switch): ?>
<a href="<?php echo home_url(); ?>/enrollment/" title="<?php _e('Book Table', 'tl_theme'); ?>" class="book-a-table"><?php _e('Enrollment', 'tl_theme'); ?></a>
<?php endif; ?>
<!-- Start main-navigation-->
<?php echo mls_get_navigation_menu(); ?>
<!-- end main-navigation-->
</div><!-- end wrap -->
</div><!-- end header --><file_sep><?php
/*Default Configuration for Theme Options*/
$meta_data = array('name'=>'main_settings', 'version'=>'1.0.0');
/* Main Tabs */
/**
* Option "content" represents name of a METHOD in ThemeAdmin Class OR file name where content is placed
*/
$options['tabs'][] = array('name'=>__('Main Settings', 'tl_theme_admin'), 'id'=>'main_settings_tab', 'type'=>'tab', 'content'=> TL_THEME_ADMIN_VIEW_DIR . '/main-settings.phtml');
$options['tabs'][] = array('name'=>__('Sliders', 'tl_theme_admin'), 'id'=>'sliders_tab', 'type'=>'tab', 'content'=> TL_THEME_ADMIN_VIEW_DIR . '/sliders.phtml');
$options['tabs'][] = array('name'=>__('Help', 'tl_theme_admin'), 'id'=>'help_tab', 'type'=>'tab', 'content'=> TL_THEME_ADMIN_VIEW_DIR . '/help.phtml');
/**
* Menu Items in Main settings TAB
*/
$options['menu_items'][] = array('name'=> __('Look & Feel', 'tl_theme_admin'), 'id' => 'mi_look_feel', 'type'=> 'menu_item', 'class'=>'icon-picture');
$options['menu_items'][] = array('name'=> __('Blog', 'tl_theme_admin'), 'id' => 'mi_blog', 'type'=> 'menu_item', 'class'=>'icon-pencil');
$options['menu_items'][] = array('name'=> __('Products', 'tl_theme_admin'), 'id' => 'mi_product', 'type'=> 'menu_item', 'class'=>'icon-pencil');
$options['menu_items'][] = array('name'=> __('Testimonials', 'tl_theme_admin'), 'id' => 'mi_testimonial', 'type'=> 'menu_item', 'class'=>'icon-pencil');
$options['menu_items'][] = array('name'=> __('Header', 'tl_theme_admin'), 'id' => 'mi_header', 'type'=> 'menu_item', 'class'=>'icon-arrow-up');
$options['menu_items'][] = array('name'=> __('Footer', 'tl_theme_admin'), 'id' => 'mi_footer', 'type'=> 'menu_item', 'class'=>'icon-arrow-down');
$options['menu_items'][] = array('name'=> __('Home Page', 'tl_theme_admin'), 'id' => 'mi_home', 'type'=> 'menu_item', 'class'=>'icon-home');
$options['menu_items'][] = array('name'=> __('Google Maps', 'tl_theme_admin'), 'id' => 'mi_gmaps', 'type'=> 'menu_item', 'class'=>'icon-road');
$options['menu_items'][] = array('name'=> __('Contact', 'tl_theme_admin'), 'id' => 'mi_contact', 'type'=> 'menu_item', 'class'=>'icon-book');
$options['menu_items'][] = array('name'=> __('Social', 'tl_theme_admin'), 'id' => 'mi_social', 'type'=> 'menu_item', 'class'=>'icon-user');
$options['menu_items'][] = array('name'=> __('Google Analitics', 'tl_theme_admin'),'id' => 'mi_google_analitics', 'type'=> 'menu_item', 'class'=>'icon-map-marker');
$options['menu_items'][] = array('name'=> __('Sidebars', 'tl_theme_admin'),'id' => 'mi_custom_sidebars', 'type'=> 'menu_item', 'class'=>'icon-list-alt');
$options['menu_items'][] = array('name'=> __('Misc', 'tl_theme_admin'), 'id' => 'mi_misc', 'type'=> 'menu_item', 'class'=>'icon-cog');
/* LOOK & FEEL */
$options['items']['mi_look_feel'][] = array('name'=>__('Colors & Images','tl_theme_admin'),
'id'=>'look_feel_section',
'desc'=>__('common color settings', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_look_feel'][] = array('name'=>__('Color Shemes','tl_theme_admin'),
'id'=>'look_feel_section',
'type'=>'start_sub_section');
$options['items']['mi_look_feel'][] = array('id'=>'color_sheme',
'name'=>__('Color Shemes','tl_theme_admin'),
'desc'=>__('Select Color Sheme','tl_theme_admin'),
'type'=>'select',
'required'=> true,
'default'=>'turquoise',
'values' => array('turquoise' => 'Turquoise',
'black' => 'Black',
'blue' => 'Blue',
'coffee' => 'Coffee',
'deep-blue' => 'Deep Blue',
'green' => 'Green',
'grey' => 'Grey',
'lime' => 'Lime',
'pink' => 'Pink',
'purple' => 'Purple',
'yellow' => 'Yellow'),
'value' => null);
$options['items']['mi_look_feel'][] = array('name'=>__('Images','tl_theme_admin'),
'id'=>'img_section',
'type'=>'start_sub_section');
$options['items']['mi_look_feel'][] = array('id'=>'mi_logo',
'name'=>__('Logo', 'tl_theme_admin'),
'desc'=>__('Customize your logo. Logo height should not be greater than 100px.', 'tl_theme_admin'),
'type'=>'file',
'default'=>TL_THEME_CSS_URI . '/color-shemes/turquoise/logo.png',
'value' => null);
$options['items']['mi_look_feel'][] = array('id'=>'logo_width',
'name'=>__('Logo width','tl_theme_admin'),
'desc'=>__('Logo width in px. Leave this field blank for default value. Enter only a number.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=> null);
$options['items']['mi_look_feel'][] = array('id'=>'logo_height',
'name'=>__('Logo Height','tl_theme_admin'),
'desc'=>__('Logo height in px. Leave this field blank for default value. Enter only a number.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>null);
$options['items']['mi_look_feel'][] = array('id'=>'mi_favicon',
'name'=>__('Favicon image','tl_theme_admin'),
'desc'=>__('Favicon image. 16x16 pixels.','tl_theme_admin'),
'type'=>'file',
'value' => null,
'default'=>TL_THEME_IMAGES_URI . '/favicon.png');
/* PRODUCTS */
$options['items']['mi_product'][] = array('name'=>__('Product Settings','tl_theme_admin'),
'id'=>'product_section',
'desc'=>__('general settings related to food and beaverages', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_product'][] = array('id'=>'mi_product_meta_switch',
'name'=>__('Enable Meta Data','tl_theme_admin'),
'desc'=>__('Disable this option to hide product\'s meta data.[date, author, categories]','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
$options['items']['mi_product'][] = array('id'=>'menu_of_day',
'name'=>__('Menu of a day ','tl_theme_admin'),
'desc'=>__('Selected items will apear at price page.','tl_theme_admin'),
'type'=>'multiselect',
'filters'=> array('intVal'),
'values' =>mls_get_food_types(),
'value' => null,
'default'=>0//array('empty')
);
/* TESTIMONIALS */
$options['items']['mi_testimonial'][] = array('name'=>__('Testimonial\'s Settings','tl_theme_admin'),
'id'=>'testimonial_section',
'desc'=>__('general settings related to testimonials page', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_testimonial'][] = array('id'=>'switch_title',
'name'=>__('Show Page Title','tl_theme_admin'),
'desc'=>__('Show page title above testimonials','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
$options['items']['mi_testimonial'][] = array('id'=>'show_intro_text',
'name'=>__('Show Page Intro Text','tl_theme_admin'),
'desc'=>__('Show page content above a list of testimonials','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
/* BLOG */
$options['items']['mi_blog'][] = array('name'=>__('Blog Settings','tl_theme_admin'),
'id'=>'blog_section',
'desc'=>__('all about blog', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_blog'][] = array('id'=>'mi_blog_meta_switch',
'name'=>__('Enable Meta Data','tl_theme_admin'),
'desc'=>__('Disable this option to hide blog post meta data.[date, author, categories]','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_blog'][] = array('id'=>'hide_cats',
'name'=>__('Hide Categories ','tl_theme_admin'),
'desc'=>__('Select categories you do not want to appear on your blog page. This option is related to a Kids Category widget.','tl_theme_admin'),
'type'=>'multiselect',
'filters'=> array('intVal'),
'values' =>mls_get_categories(),
'value' => null,
'default'=>0//array('empty')
);
$options['items']['mi_blog'][] = array('id'=>'readmore',
'name'=>__('Read More Text Button','tl_theme_admin'),
'desc'=>__('Replace "Read More" with this text','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>__('Read More', 'tl_theme_admin'));
$options['items']['mi_blog'][] = array('id'=>'comments_switch',
'name'=>__('Show comments','tl_theme_admin'),
'desc'=>__('Press Enabled button to allow users to make a comments','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
$options['items']['mi_blog'][] = array('id'=>'archive_sidebar_switch',
'name'=>__('Hide sidebar','tl_theme_admin'),
'desc'=>__('Enable this option in case you do not need a sidebar in Category/Archive pages.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
/* SOCIAL PROFILES / ACCOUNTS */
$options['items']['mi_social'][] = array('name'=>__('Be Social','tl_theme_admin'),
'id'=> 'social_section',
'desc'=>__('socialize it', 'tl_theme_admin'),
'type'=>'start_section' );
$options['items']['mi_social'][] = array('id'=>'switch',
'name'=>__('Enable Social Icons','tl_theme_admin'),
'desc'=>__('Press disable to remove social icons in header section.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'children'=>true,
'default'=>'on');
/*$options['items']['mi_social'][] = array('id'=>'title',
'name'=>__('Title','tl_theme_admin'),
'desc'=>__('Title will be shown near social icons. From the left.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>__('Enter Your Title','tl_theme_admin')); */
$options['items']['mi_social'][] = array('id'=>'facebook',
'name'=>__('Facebook','tl_theme_admin'),
'desc'=>__('Link to your Facebook Profile/Page. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'twitter',
'name'=>__('Twitter','tl_theme_admin'),
'desc'=>__('Link to your Twitter profile. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'googleplus',
'name'=>__('Google+','tl_theme_admin'),
'desc'=>__('Link to your Google+ profile. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'pinterest',
'name'=>__('Pin it','tl_theme_admin'),
'desc'=>__('Link to your Pinterest profile. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'youtube',
'name'=>__('Youtube Channel','tl_theme_admin'),
'desc'=>__('Link to your Youtube profile. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'linkedin',
'name'=>__('LinkedIn','tl_theme_admin'),
'desc'=>__('Link to your LinkedIn profile. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
$options['items']['mi_social'][] = array('id'=>'rss',
'name'=>__('RSS Channel','tl_theme_admin'),
'desc'=>__('Full URL to your newsfeeds. (Do not forget do add "http://" as prefix)','tl_theme_admin'),
'type'=>'text',
'value' => null,
'parent_id'=>'switch',
'depend_id'=>'on',
'default'=>'');
/* CONTACT INFO */
$options['items']['mi_contact'][] = array('name'=>__('Contact Info / Settings','tl_theme_admin'),
'id'=>'contact_section',
'desc'=>__('contact info', 'tl_theme_admin'),
'type'=>'start_section');
//@todo Wordpress Settings Email
$options['items']['mi_contact'][] = array('id'=>'email',
'name'=>__('E-mail Address','tl_theme_admin'),
'desc'=>__('E-mail address displayed at contact page and 404 page.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'required' => true,
'filters' => array('strip_tags'),
'validators' => array('_email'),
'default'=>'<EMAIL>');
$options['items']['mi_contact'][] = array('id'=>'tel',
'name'=>__('Phone','tl_theme_admin'),
'desc'=>__('Phone number displayed at Contact page.','tl_theme_admin'),
'type'=>'text',
'validators'=>array('_phone'),
'value' => null,
'default'=>'+381 63 1234 567');
$options['items']['mi_contact'][] = array('id'=>'fax',
'name'=>__('Fax','tl_theme_admin'),
'desc'=>__('Fax number diplayed at Contact page.','tl_theme_admin'),
'type'=>'text',
'filters'=>array('strip_tags'),
'validators'=>array('_phone'),
'value'=> null,
'default'=>'+381 63 1234 567');
$options['items']['mi_contact'][] = array('id'=>'address',
'name'=>__('Full Address','tl_theme_admin'),
'desc'=>__('Address displayed at Contact page.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>'900 John Street New York, NY 21000');
$options['items']['mi_contact'][] = array('name'=>__('Book A Table Form','tl_theme_admin'),
'id'=>'mi_contact_sub_section',
'type'=>'start_sub_section');
$options['items']['mi_contact'][] = array('id'=>'book_email',
'name'=>__('E-mail Address','tl_theme_admin'),
'desc'=>__('E-mail address where all reservation will be send.','tl_theme_admin'),
'type'=>'text',
'validators'=>array('_email'),
'value' => null,
'default'=>'');
$options['items']['mi_contact'][] = array('id'=>'switch_book_auto_reply',
'name'=>__('Auto Reply','tl_theme_admin'),
'desc'=>__('If you enable this option, visitors who send you an email message will receive a confirmation e-mail message.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
$options['items']['mi_contact'][] = array('id'=>'book_email_subject',
'name'=>__('E-mail Subject','tl_theme_admin'),
'desc'=>__('Enter an e-mail subject of automated e-mail message.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>'');
$options['items']['mi_contact'][] = array('id'=>'book_auto_msg',
'name'=>__('Response Message','tl_theme_admin'),
'desc'=>__('Text of an Autoreply e-mail message.','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>"Dear Sir or Madam,\n\nWe have received your message. This is an automated reply e-mail message. Please do not reply."
);
$options['items']['mi_contact'][] = array('name'=>__('Contact Form','tl_theme_admin'),
'id'=>'mi_contact_sub_section',
'type'=>'start_sub_section');
$options['items']['mi_contact'][] = array('id'=>'form_switch',
'name'=>__('Show Contact Form','tl_theme_admin'),
'desc'=>__('To hide contact form disable this option', 'tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_contact'][] = array('id'=>'switch_auto_reply',
'name'=>__('Auto Reply','tl_theme_admin'),
'desc'=>__('If you enable this option, visitors who send you an email message will receive a confirmation e-mail message.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'off');
$options['items']['mi_contact'][] = array('id'=>'email_subject',
'name'=>__('E-mail Subject','tl_theme_admin'),
'desc'=>__('Enter an e-mail subject of automated e-mail message.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>'');
$options['items']['mi_contact'][] = array('id'=>'email_sender_name',
'name'=>__('Your name','tl_theme_admin'),
'desc'=>__('"From" field in an automated e-mail message.','tl_theme_admin'),
'type'=>'text',
'value' => null,
'default'=>'');
//@todo Wordpress Settings Email
$options['items']['mi_contact'][] = array('id'=>'email_contact_form',
'name'=>__('E-mail address','tl_theme_admin'),
'desc'=>__('Email address where you will receiving messages from contact form. This e-mail address will be included in a "From" field of an Automated e-mail message','tl_theme_admin'),
'type'=>'text',
'validators'=>array('_email'),
'value' => null,
'default'=>'<EMAIL>');
$options['items']['mi_contact'][] = array('id'=>'auto_msg',
'name'=>__('Response Message','tl_theme_admin'),
'desc'=>__('Text of an Autoreply e-mail message.','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>"Dear Sir or Madam,\n\nWe have received your message. This is an automated reply e-mail message. Please do not reply."
);
/* GOOLGE ANALITICS */
$options['items']['mi_google_analitics'][] = array('name'=>__('Google Analitics','tl_theme_admin'),
'id'=>'google_analitics_section',
'desc'=>__('google', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_google_analitics'][] = array('id'=>'google_analitics_switch',
'name'=>__('Enable Google Analitics','tl_theme_admin'),
'desc'=>__('By default Google Analitics are disabled. Click Enabled to activate it.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'children'=>true,
'default'=>'off'
);
$options['items']['mi_google_analitics'][] = array('id'=>'google_analitics',
'name'=>__('Google Analitics','tl_theme_admin'),
'desc'=>__('If you have a google analytics account setup, you can paste your code in the text area to the side. Make sure to include the opening and closing script tags. Your tracking code will be copied to the footer of each page on your site.
','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'parent_id'=>'google_analitics_switch',
'depend_id'=>'on',
'default'=>''
);
/* HEADER */
$options['items']['mi_header'][] = array('name'=>__('Header settings','tl_theme_admin'),
'id'=>'header_section',
'desc'=>__('setup your header', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_header'][] = array('id'=>'teaser_switch',
'name'=>__('Teaser text','tl_theme_admin'),
'desc'=>__('Disable this option to hide Teaser','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_header'][] = array('id'=>'breadcrumbs_switch',
'name'=>__('Breadcrumbs','tl_theme_admin'),
'desc'=>__('Disable this option to hide breadcrumbs','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_header'][] = array('id'=>'bread_crumbs_text_switch',
'name'=>__('Hide breadcrumbs text','tl_theme_admin'),
'desc'=>__('Enable this option to hide text "You are here:"','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_header'][] = array('id'=>'book_table_switch',
'name'=>__('Show Book Table Link','tl_theme_admin'),
'desc'=>__('Enable this option to show Book a Table Link in heater section.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
/* FOOTER */
$options['items']['mi_footer'][] = array('name'=>__('Footer settings','tl_theme_admin'),
'id'=>'footer_section',
'desc'=>__('setup your footer', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_footer'][] = array('id'=>'mi_footer1_switch',
'name'=>__('Show footer section','tl_theme_admin'),
'desc'=>__('Show or Hide footer section.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_footer'][] = array('id'=>'mi_footer2_switch',
'name'=>__('Show subfooter section','tl_theme_admin'),
'desc'=>__('Show or Hide subfooter section.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'default'=>'on');
$options['items']['mi_footer'][] = array('id'=>'mi_copyright_switch',
'name'=>__('Copyright Text','tl_theme_admin'),
'desc'=>__('Show or Hide Copyright in footer section. Thick checkbox to show.','tl_theme_admin'),
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'on');
$options['items']['mi_footer'][] = array('id'=>'mi_copyright',
'name'=>__('Copyright','tl_theme_admin'),
'desc'=>__('Copyright text in footer section','tl_theme_admin'),
'type'=>'text',
'parent_id'=>'mi_copyright_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'Copyright © 2011-2012 Your Company Name. All Rights Reserved.');
$options['items']['mi_footer'][] = array('id'=>'mi_terms_switch',
'name'=>__('Show Terms of Use Link','tl_theme_admin'),
'desc'=>'',
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'on');
$options['items']['mi_footer'][] = array('id'=>'mi_terms',
'name'=>__('Terms of Use Link','tl_theme_admin'),
'desc'=>__('Link to the page "Term of Use"','tl_theme_admin'),
'type'=>'text',
'parent_id'=>'mi_terms_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'');
$options['items']['mi_footer'][] = array('id'=>'mi_copyright_link_switch',
'name'=>__('Show Copyright Link','tl_theme_admin'),
'desc'=> '',
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'on');
$options['items']['mi_footer'][] = array('id'=>'mi_copyright_link',
'name'=>__('Copyright Link','tl_theme_admin'),
'desc'=>__('Link to the Copyrights','tl_theme_admin'),
'type'=>'text',
'parent_id'=>'mi_copyright_link_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'');
/*$options['items']['mi_footer'][] = array('id'=>'mi_sitemap_switch',
'name'=>__('Show Sitemap Link','tl_theme_admin'),
'desc'=>'',
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'off');
$options['items']['mi_footer'][] = array('id'=>'mi_sitemap_link',
'name'=>__('Sitemap Link','tl_theme_admin'),
'desc'=>__('Full Url to a Sitemap page','tl_theme_admin'),
'type'=>'text',
'parent_id'=>'mi_sitemap_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'');
*/
/* HOME PAGE */
$options['items']['mi_home'][] = array( 'name'=>__('Home Page settings','tl_theme_admin'),
'id'=>'home_section',
'desc'=>'',
'type'=>'start_section');
$options['items']['mi_home'][] = array('name'=>__('Slider section','tl_theme_admin'),
'id'=>'mi_home_slider_sub_section',
'type'=>'start_sub_section'
);
$options['items']['mi_home'][] = array('id'=>'slider_hide_switch',
'name'=>__('Hide Slider','tl_theme_admin'),
'desc'=>__('Enable this option to hide the Slider section at home page.','tl_theme_admin'),
'type'=>'checkbox',
'value' => null,
'children'=>true,
'default'=>'off');
$options['items']['mi_home'][] = array('name'=>__('Featured section','tl_theme_admin'),
'id'=>'mi_home_featured_sub_section',
'type'=>'start_sub_section'
);
$options['items']['mi_home'][] = array('id'=>'featured_section_switch',
'name'=>__('Show Featured section','tl_theme_admin'),
'desc'=>__('To hide featured section disable this option', 'tl_theme_admin'),
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'on');
$options['items']['mi_home'][] = array('id'=>'featured_section_source_switch',
'name'=>__('Data Source for Featured section','tl_theme_admin'),
'desc'=>__('Choose between posts or pages.', 'tl_theme_admin'),
'type'=>'radio',
'children'=>true,
'parent_id' => 'featured_section_switch',
'depend_id' =>'on',
'values' => array('post'=>__('SINGLE POST', 'tl_theme_admin'),
'page'=>__('SINGLE PAGE', 'tl_theme_admin'),
'posts'=>__('POST CATEGORY', 'tl_theme_admin'),
'pages'=>__('PAGES', 'tl_theme_admin'),
'products'=> __('MENU ITEMS', 'tl_theme_admin')
),
'value' => null,
'default'=>'post');
$options['items']['mi_home'][] = array('id'=>'featured_section_category',
'name'=>__('Post Category','tl_theme_admin'),
'desc'=>__('Posts from this category will be shown at home page.', 'tl_theme_admin'),
'type'=>'select',
'value' => null,
'default'=>null,
'parent_id' => 'featured_section_source_switch',
'depend_id' => 'posts',
'values'=> mls_get_categories(array( 'type' => 'post',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1,
'taxonomy' => 'category'))
);
$options['items']['mi_home'][] = array('id' => 'featured_section_pages',
'name' => __('List of Pages','tl_theme_admin'),
'desc' => __('Selected pages will be displayed in featured section.', 'tl_theme_admin'),
'type' => 'multiselect',
'value' => null,
'default' => array(),
'parent_id' => 'featured_section_source_switch',
'depend_id' => 'pages',
'values' => mls_get_pages(array('sort_column'=>'post_title'))
);
$options['items']['mi_home'][] = array('id' => 'featured_section_products',
'name' => __('List of Menu Items','tl_theme_admin'),
'desc' => __('Selected menu items will be displayed in featured section.', 'tl_theme_admin'),
'type' => 'multiselect',
'value' => null,
'default' => array(),
'parent_id' => 'featured_section_source_switch',
'depend_id' => 'products',
'values' => mls_get_products()
);
$options['items']['mi_home'][] = array(
'id' => 'featured_section_items_per_row',
'name' => __('Items per row', 'tl_theme_admin' ),
'desc' => __('Number of items per row.', 'tl_theme_admin' ),
'type' => 'number',
'min'=>'2',
'max' => '6',
'step' => '1',
'default' => '4',
'value' => null,
'parent_id' => 'featured_section_source_switch',
'depend_id' =>'posts pages products',
'filters'=>array('intVal')
);
$options['items']['mi_home'][] = array(
'id' => 'featured_section_changeby',
'name' => __('Items per slide', 'tl_theme_admin' ),
'desc' => __('Number of items to slide at once.', 'tl_theme_admin' ),
'type' => 'number',
'min'=>'1',
'max' => '6',
'step' => '1',
'default' => '1',
'value' => null,
'parent_id' => 'featured_section_source_switch',
'depend_id' =>'posts pages products',
'filters'=>array('intVal')
);
$options['items']['mi_home'][] = array('id'=>'featured_section_items_portrait',
'name'=>__('Image Height','tl_theme_admin'),
'desc'=>__('Select image orientation.', 'tl_theme_admin'),
'type'=>'radio',
'parent_id' => 'featured_section_switch',
'depend_id' =>'posts pages products',
'value' => null,
'values' => array('landscape'=>'DEFAULT', 'portrait'=>'TALLER'),
'default'=>'landscape');
$options['items']['mi_home'][] = array('id'=>'featured_section_post',
'name'=>__('Featured Post','tl_theme_admin'),
'desc'=>__('Select a post shown at featured area.', 'tl_theme_admin'),
'type'=>'select',
'parent_id' => 'featured_section_source_switch',
'depend_id'=>'post',
'value' => null,
'default'=>null,
'values'=> mls_get_posts());
$options['items']['mi_home'][] = array('id'=>'featured_section_page',
'name'=>__('Featured Page','tl_theme_admin'),
'desc'=>__('Select a page shown at featured area.', 'tl_theme_admin'),
'type'=>'select',
'depend_id'=>'page',
'parent_id'=>'featured_section_source_switch',
'value' => null,
'default'=>null,
'values'=> mls_get_pages(array('sort_column'=>'post_title')));
$options['items']['mi_home'][] = array('id'=>'featured_section_full',
'name'=>__('Show entire post/page content','tl_theme_admin'),
'desc'=>__('By default it shows an excerpt without formatting. Change this option to show entire content of the post/page.', 'tl_theme_admin'),
'type'=>'checkbox',
'parent_id'=>'featured_section_source_switch',
'depend_id'=>'post page',
'value' => null,
'default'=>'off');
$options['items']['mi_home'][] = array('id'=>'featured_section_readmore_switch',
'name'=>__('Show Read more link','tl_theme_admin'),
'desc'=>__('To hide Read more link in featured section disable this option', 'tl_theme_admin'),
'type'=>'checkbox',
'parent_id'=>'featured_section_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'on');
/*$options['items']['mi_home'][] = array('name'=>__('Middle section (3 posts)','tl_theme_admin'),
'id'=>'home_section',
'type'=>'start_sub_section');
$options['items']['mi_home'][] = array('id' =>'middle_switch',
'name' =>__('Show Middle Page area','tl_theme_admin'),
'desc' =>__('To hide middle section disable this option', 'tl_theme_admin'),
'type' =>'checkbox',
'children' => true,
'value' => null,
'default' =>'on');
$options['items']['mi_home'][] = array('id'=>'content_section_source_switch',
'name'=>__('Data Source for Middle section','tl_theme_admin'),
'desc'=>__('Choose between posts or pages.', 'tl_theme_admin'),
'type'=>'radio',
'children'=>true,
'parent_id' => 'middle_switch',
'depend_id' =>'on',
'values' => array('mpost'=>__('POSTS'), 'mpage'=>__('PAGES', 'tl_theme_admin')),
'value' => null,
'default'=>'mpost');*/
/* GOOGLE MAPS */
$options['items']['mi_gmaps'][] = array('name'=>__('Google Maps Settings','tl_theme_admin'),
'id'=>'gmaps_section',
'desc'=>__('google maps', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_gmaps'][] = array('id'=>'mi_gmaps_switch',
'name'=>__('Google Maps','tl_theme_admin'),
'desc'=>__('Turn this option on if you want to enable google maps.','tl_theme_admin'),
'type'=>'checkbox',
'children'=>true,
'value' => null,
'default'=>'off');
$options['items']['mi_gmaps'][] = array('id'=>'mi_gmaps_zoom',
'name'=>__('Google Maps Zoom','tl_theme_admin'),
'desc'=>__('Zoom parameter. Valid values are from 1 to 20.','tl_theme_admin'),
'type'=>'text',
'parent_id'=>'mi_gmaps_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'16');
$options['items']['mi_gmaps'][] = array('id'=>'mi_gmaps_lat',
'name'=>__('Latitude','tl_theme_admin'),
'desc'=>__('Enter first coordinate.','tl_theme_admin'),
'type'=>'hidden',
'value' => null,
'default'=>'37.973787');
$options['items']['mi_gmaps'][] = array('id'=>'mi_gmaps_long',
'name'=>__('Longitude','tl_theme_admin'),
'desc'=>__('Enter second coordinate.','tl_theme_admin'),
'type'=>'hidden',
'value' => null,
'default'=>'23.722426');
$options['items']['mi_gmaps'][] = array('id'=>'mi_gmaps_map',
'name'=>__('Select your position','tl_theme_admin'),
'desc'=>__('Drag and drop marker.','tl_theme_admin'),
'type'=>'map',
'parent_id'=>'mi_gmaps_switch',
'depend_id'=>'on',
'value' => null,
'default'=>'');
/* CUSTOM SIDEBARS */
$options['items']['mi_custom_sidebars'][] = array('name'=>__('Custom Sidebars','tl_theme_admin'),
'id'=>'csidebars_section',
'desc'=>__('Create your sidebars', 'tl_theme_admin'),
'type'=>'start_section');
$options['items']['mi_custom_sidebars'][] = array('id' => 'csidebar_list',
'name' => __('Sidebar Name', 'tl_theme_admin'),
'desc' => __('Letters and numbers allowed.', 'tl_theme_admin'),
'type' => 'list',
'value' => null,
'default' => null,
'values' => array()
);
/* MISC */
$options['items']['mi_misc'][] = array('name'=>__('Misc settings','tl_theme_admin'),
'id'=>'misc_section',
'desc'=>'',
'type'=>'start_section');
$options['items']['mi_misc'][] = array('name'=>__('Customs','tl_theme_admin'),
'id'=>'mi_custom_section',
'type'=>'start_sub_section'
);
$options['items']['mi_misc'][] = array('id'=>'mi_custom_css',
'name'=>__('Custom CSS','tl_theme_admin'),
'desc'=>__('Enter Your custom CSS code.','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>''
);
$options['items']['mi_misc'][] = array('id'=>'mi_custom_js',
'name'=>__('Custom Javascript','tl_theme_admin'),
'desc'=>__('Enter Your custom JS code.','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>''
);
$options['items']['mi_misc'][] = array('id'=>'mi_404',
'name'=>__('404 title','tl_theme_admin'),
'desc'=>__('This message is shown when requested page can not be found','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>'This page can not be found.'
);
$options['items']['mi_misc'][] = array('id'=>'mi_404_text',
'name'=>__('404 text','tl_theme_admin'),
'desc'=>__('This message is shown when requested page can not be found','tl_theme_admin'),
'type'=>'textarea',
'value' => null,
'default'=>'Ooops. Something went wrong. Requested page does not exists. Make sure you entered correct URL.'
);
<file_sep><?php
/**
*
*/
class CustomPostTypeHelper
{
public $post_type_name;
public $post_type_args;
public $post_type_labels;
public $taxonomy_name;
public $taxonomy_type_args;
public $taxonomy_type_labels;
public $meta_boxes = array();
/* Class constructor */
public function __construct( $name, $args = array(), $labels = array(), $meta_boxes = array())
{
// Set some important variables
$this->post_type_name = strtolower( str_replace( ' ', '_', $name ) );
$this->post_type_args = $args;
$this->post_type_labels = $labels;
$this->meta_boxes = $meta_boxes;
// Add action to register the post type, if the post type doesnt exist
if( ! post_type_exists( $this->post_type_name ) )
{
add_action( 'init', array( &$this, 'register_post_type' ) );
}
//if(!empty($meta_boxes)){
add_action('add_meta_boxes', array(&$this, '_addCustomMetaBoxes'));
//}
add_action('save_post', array(&$this, '_save' ));
}
/* Method which registers the post type */
public function register_post_type()
{
//Capitilize the words and make it plural
$name = ucwords( str_replace( '_', ' ', $this->post_type_name ) );
$plural = $name . 's';
// Same principle as the labels. We set some default and overwite them with the given arguments.
$args = array_merge(
// Default
array(
'label' => $plural,
'labels' => $this->post_type_labels,
'public' => true,
'show_ui' => true,
'supports' => array( 'title', 'editor' ),
'show_in_nav_menus' => true
),
// Given args
$this->post_type_args
);
// Register the post type
register_post_type( $this->post_type_name, $args );
flush_rewrite_rules();
}
/* Method to attach the taxonomy to the post type */
public function add_taxonomy( $name, $post_type_slug, $taxonomy_labels = array(),$taxonomy_args = array() )
{
if( ! empty( $name ) )
{
// We need to know the post type name, so the new taxonomy can be attached to it.
// $post_type_name = $this->post_type_name;
// Taxonomy properties
$this->taxonomy_name = $post_type_slug;
if( ! taxonomy_exists( $this->taxonomy_name ) )
{
//Capitilize the words and make it plural
$name = ucwords( str_replace( '_', ' ', $name ) );
$plural = $name . 's';
$this->taxonomy_type_labels = $taxonomy_labels;
// Default arguments, overwitten with the given arguments
$this->taxonomy_type_args = array_merge(
// Default
array(
'label' => $plural,
'labels' => $this->taxonomy_type_labels,
'public' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'rewrite' => true
),
// Given
$taxonomy_args
);
// Add the taxonomy to the post type
add_action( 'init', array(&$this, '_registerTaxonomy'));
}
else
{
add_action( 'init', array(&$this, '_registerExistingTaxonomy'));
}
}
}
public function _registerTaxonomy(){
register_taxonomy( $this->taxonomy_name, $this->post_type_name, $this->taxonomy_type_args );
flush_rewrite_rules();
}
public function _registerExistingTaxonomy(){
register_taxonomy_for_object_type( $this->taxonomy_name, $this->post_type_name );
}
public function hasMetaBoxes(){
return !empty($this->meta_boxes);
}
public function getMetaBoxFields($id){
return $this->meta_boxes[$id];
}
/* Ova fja moze biti pozvama akko su metaboxovi vec setovani!!! */
public function _addCustomMetaBoxes(){
foreach ($this->meta_boxes as $value) {
add_meta_box($value['id'],
$value['title'],
array(&$this, '_renderMetaBox'),
$this->post_type_name,
$value['context'],
$value['priority'],
$value['callback_args']);
}
}
/*
* Attaches meta boxes to the post type
* add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );
*/
public function addMetaBox( $meta_box )
{
$this->meta_boxes[$meta_box['id']] = $meta_box;
}
public function _renderMetaBox($post, $args){
wp_nonce_field( plugin_basename(__FILE__), $this->post_type_name . '_box_nonce' );
$data = get_post_meta($post->ID, $this->post_type_name . '_meta_data', true);
foreach ($args['args'] as $f) {
$f['value'] = isset($data[$f['id']]) ? $data[$f['id']] : $f['default'];
echo $this->renderField($f);
}
}
/* Save data from custom meta boxes */
public function _save($post_id)
{
// Deny the wordpress autosave function
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
//if ( ! wp_verify_nonce( $_POST['custom_post_type'], plugin_basename(__FILE__) ) ) return;
if( !isset( $_POST[$this->post_type_name . '_box_nonce'] ) || !wp_verify_nonce( $_POST[$this->post_type_name . '_box_nonce'], plugin_basename(__FILE__) ) ) return;
if( !current_user_can( 'edit_post' ) ) return;
if ( !current_user_can( 'edit_page' ) ) return;
global $post;
if( isset( $_POST ) && isset( $post->ID ) && get_post_type( $post->ID ) == $this->post_type_name )
{
//$data = array($this->post_type_name . '_meta_data'=>'');
$data = array();
// Loop through each meta box
foreach( $this->meta_boxes as $id => $box )
{
// Loop through all fields
foreach( $box['callback_args'] as $field )
{
$data[$field['id']] = isset($_POST[$this->post_type_name][$field['id']]) ? trim($_POST[$this->post_type_name][$field['id']]) : '';
}
}
update_post_meta( $post->ID, $this->post_type_name . '_meta_data', $data );
}
}
/**
*
* Enter description here ...
* @param unknown_type $field
*/
public function renderField($field){
$output = '';
$value = (!isset($field['value'])) ? '' : esc_attr($field['value']);
switch ($field['type']){
case 'text':{
$output .= '<p><label>'.$field['label'].'<br />
<input type="text" name="'.$this->post_type_name.'['.$field['id'].']" value="'.$value.'" /><br />
</label>
</p>';
break;
}
case 'select': {
$options = '';
$output .= '<p><label>'.$field['label'].'</label>';
foreach ($field['values'] as $k => $v) {
if($v == $value)
$options .= '<option value="'.$k.'" selected="selected">'.$v.'</option>';
else
$options .= '<option value="'.$k.'">'.$v.'</option>';
}
$output .= '<select name="'.$this->post_type_name.'['.$field['id'].']">'.$options.'</select>';
$output .= '</p>';
break;
}
case 'multiselect':{
$options = '';
$output .= '<p><label>'.$field['label'].'</label>';
foreach ($field['values'] as $k => $v) {
if($v == $value)
$options .= '<option value="'.$k.'" selected="selected">'.$v.'</option>';
else
$options .= '<option value="'.$k.'">'.$v.'</option>';
}
$output .= '<select multiselect="multiselect" name="'.$this->post_type_name.'['.$field['id'].']">'.$options.'</select>';
$output .= '</p>';
break;
}
case 'textarea':{
$output .= '<p><label>'.$field['label'].'</label>
<textarea name="'.$this->post_type_name.'['.$field['id'].']">'.$value.'</textarea>
</p>';
break;
}
case 'radio':{
$output .= '<p><label>'.$field['label'].'</label>
<input type="radio" name="'.$this->post_type_name.'['.$field['id'].']" '.cb_checked($value).' />
</p>';
break;
}
case 'checkbox':{
$output .= '<p><label>'.$field['label'].'
<input type="checkbox" name="'.$this->post_type_name.'['.$field['id'].']" '.cb_checked($value).' /></label>
</p>';
break;
}
case 'hidden':{
$output .= '<input type="hidden" name="'.$this->post_type_name.'['.$field['id'].']" value="'.$value.'" />';
break;
}
case 'datetimepicker':{
$output .= '<p><label>'.$field['label'].'<br />
<input class="datetimepicker" type="text" name="'.$this->post_type_name.'['.$field['id'].']" value="'.$value.'" /><br />
</label>
</p>';
break;
}
}
echo $output;
}
} // Class end
function cb_checked($param){
return (isset($param) && $param != '') ? 'checked="checked"' : '';
}<file_sep><?php
/**
* Managing theme administration panel
*/
if(!defined('RUN_FOREST_RUN')) exit('No Direct Access');
/**
* Main Administration class
* Some sort of controller
*/
class ThemeAdmin {
/* Self */
private static $_instance = null;
/* Instance of ThemeOptions Class */
protected $data_obj = null;
/* Flag */
protected $is_initialized = false;
/* All nofication in admin panel */
protected $notifications = array();
protected $nonce = '';
private function __construct(){}
private function __clone(){}
public static function getInstance(){
if (null === self::$_instance)
{
self::$_instance = new self();
}
return self::$_instance;
}
/**
* @todo If there is NO $data_obj load IT!
*/
public function init(){
if(!$this->is_initialized){
$obj = self::getInstance();
$obj->data_obj =& ThemeData();
$obj->nonce = rand(1,99999);
$this->is_initialized = true;
}
return $this;
}
/**
* Retrieves loaded data from DB
*/
public function getDataDb(){
return $this->data_obj->getAllOptions();
}
/**
* Retrive specific option.
* @param string $key
*/
public function getOneDb($key){
return $this->data_obj->getOption($key);
}
protected function getMenuItems(){
return $this->data_obj->getMenuItems();
}
protected function getTabItems(){
return $this->data_obj->getTabItems();
}
/*public function defsLoaded($key){
$r = $this->data_obj->defsLoaded($key);
return isset($r) ? true : false;
}*/
protected function file_ok($file){
$r = $this->data_obj->file_ok($file);
return $r;
}
public function setNotification($msg, $type){
$this->notifications[] = array($msg, $type);
}
public function resetNotifications(){
$this->notifications = array();
}
/**
* Niz Settings je niz n osnovu kog se iscrtava interface kada su u pitanju MAIN SETTINGS
* Za slidere sluzi samo kao data container.
*
* Ovi nizovi su ovde prepopulisani sa podacima.
*/
public function displayAdminSettings()
{
/* MAIN SETTINGS TAB */
$ms_view['tab_items'] = $this->data_obj->getSetting('main_settings.data.tabs');
$ms_view['main_settings_menu'] = $this->data_obj->getSetting('main_settings.data.menu_items');
$tabs_content = array();
foreach ($ms_view['main_settings_menu'] as $t){
$ms_view['tabs_content'][$t['id']] = $this->data_obj->getSetting('main_settings.data.items.'.$t['id']);
}
/* SLIDERS SETTINGS TAB */
/* Ovo mi treba bez obzira da li imamo neki slider u bazi ili ne */
if($this->data_obj->getSetting('sliders_tpl') == null){
$slider_data = $this->data_obj->getSettingTpl('sliders_tpl.data.sliders');
$sl_view_sliders = $slider_data;
$sl_view_current_slider_type = 'anything_slider';
}else{
$slider_data = $this->data_obj->getSetting('sliders_tpl.data.sliders');
$sl_view_sliders = $slider_data;
$sl_view_current_slider_type = $slider_data['current_slider'];
}
$sl_view_current_slider_name = $slider_data[$sl_view_current_slider_type]['incommon']['slider_name']['value'];
if(file_exists(TL_THEME_ADMIN_VIEW_DIR . '/admin-panel.phtml') && is_readable(TL_THEME_ADMIN_VIEW_DIR . '/admin-panel.phtml')){
include_once TL_THEME_ADMIN_VIEW_DIR . '/admin-panel.phtml';
}
}
/**
* Alias for renderAdminPanelContent
* Enter description here ...
*/
public function panelMachine(){
$this->renderAdminPanelContent();
}
public function parseField($field = array(), $section=''){
$output='';
if(!isset($field['default'])){ $field['default'] = null;}
$value = (isset($field['value'])) ? $field['value'] : $field['default'];
if ((isset($field['children']) && $field['children'] == true)) $has_children = 'data-haschildren="1"'; else $has_children = 'data-haschildren="0"';
$depend = isset($field['depend']) ? $field['depend'] : '';
$depend_id = isset($field['depend_id']) ? $field['depend_id'] : '';
$parent_id = isset($field['parent_id']) ? 'data-parentid="'.$field['parent_id'].'"' : '';
if(is_array($value)){
$value = array_map('stripslashes', $value);
}
else{
$value = stripslashes($value);
}
if($section){ $section = $section . '__';}
switch ($field['type']){
case 'start_section':{
$output .= '<h2>'. $field['name']. ' <small>'. $field['desc']. '</small></h2>';
break;
}
case 'start_sub_section':{
$output .= '<div class="control-group theme-section well-no-shadow">
<label class="control-label">'.$field['name'].'<br/></label>
</div>';
break;
}
case 'text':{
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input id="'.$field['id'].'" type="text" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" class="span6" />
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'list':{
$options = ($field['value']!='' && !is_array($field['value'])) ? array($field['value']) : $field['value'];
$options_li = '';
$options_str = '';
if(isset($options) && is_array($options)){
foreach ($options as $v){
$options_str .= '<option value="'.esc_attr($v).'" selected="selected">'.esc_attr($v).'</option>';
$options_li .= '<li class="accordion-heading" data-sidebarid="'.esc_attr($v).'"> '.esc_attr($v).'<span><a href="#">×</a></span></li>';
}
}
$output_s = '<select style="display:none;" id="'.$section.$field['id'].'" name="'.$section.$field['id'].'" multiple="multiple">
'.$options_str.'
</select>';
$output .= '<div class="control-group dinamic-field custom_multi_list '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
'.$output_s.'
<input id="_'.$field['id'].'" type="text" name="_'. $field['id'].'" class="span6" />
<a id="add_'.$field['id'].'" class="btn" href="#">Add</a>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
$output .= '<ul id="list_'.$field['id'].'" class="admin-list">'.$options_li.'</ul>';
break;
}
case 'hidden':{
$output .= '<input class="dinamic-field" type="hidden" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" />';
break;
}
case 'textarea':{
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'</label>
<div class="controls">
<textarea id="'.$section.$field['id'].'" rows="4" name="'.$section . $field['id'].'" class="span8">'.esc_textarea($value).'</textarea>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'colorpicker':
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input id="'.$field['id'].'" type="text" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" class="mls_colorpicker" />
<span class="add-on"><i></i></span>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
case 'number' : {
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
<div class="number span6" data-step="'.$field['step'].'" data-min="'.$field['min'].'" data-max="'.$field['max'].'"></div>
<input readonly="readonly" id="'.$field['id'].'" type="text" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" class="span2" />
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'checkbox':{
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class=" control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input name="'.$section . $field['id'].'" type="hidden" value="'.esc_attr($value).'" id="'.$field['id'].'" />
<div data-toggle="buttons-radio" class="btn-group">
<a href="#" data-state="on" class="btn '.(($value == 'on') ? 'active' : '').'">ENABLED</a>
<a href="#" data-state="off" class="btn '.(($value == 'off') ? 'active' : '').'">DISABLED</a>
</div>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'radio': {
$options = $field['values'];
$options_str = '';
foreach ($options as $k=>$v){
$selected = ($k == $value) ? 'active' : '';
$options_str .= '<a href="#" data-state="'.$k.'" class="btn '.$selected.'" >'.esc_attr($v).'</a>';
}
$output .='<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class=" control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input name="'.$section . $field['id'].'" type="hidden" value="'.esc_attr($value).'" id="'.$field['id'].'" />
<div data-toggle="buttons-radio" class="btn-group">
'.$options_str.'
</div>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'file':{
if($value == '') $value = $field['default'];
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input type="hidden" id="'.$field['id'].'" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" />
<div class="btn-group uploader">
<a href="#" name="f_'.$field['id'].'" class="btn active filename span8">'.esc_attr($value).'</a>
<a href="#" class="btn action">Upload File</a>
</div>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'select':{
$options = $field['values'];
$options_str = '';
foreach ($options as $k=>$v){
$selected = ($k == $value) ? 'selected' : '';
$options_str .= '<option value="'.esc_attr($k).'" '.$selected.' >'.esc_attr($v).'</option>';
}
$output .='<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'</label>
<div class="controls">
<select id="'.$field['id'].'" name="'.$section . $field['id'].'">
'.$options_str.'
</select>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'map':{
$output .='<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label class="control-label">'.$field['name'].'</label>
<div class="controls">
<div id="canvas" style="width:640px; height: 360px;"></div>
</div>
</div>';
break;
}
case 'multiselect':{
if(!is_array($value)){ $value = array($value);}
$options = $field['values'];
$options_str = '';
foreach ($options as $k=>$v){
if(in_array($k, $value)){
$options_str .= '<option value="'.esc_attr($k).'" selected>'.esc_attr($v).'</option>';
}
else{
$options_str .= '<option value="'.esc_attr($k).'">'.esc_attr($v).'</option>';
}
}
$output .= '<div class="control-group dinamic-field '.$depend_id.'" '.$has_children.' '.$parent_id.'>
<label for="multiSelect" class="control-label">'.$field['name'].'</label>
<div class="controls">
<select name="'.$section . $field['id'].'" id="'.$field['id'].'" multiple="multiple">
'.$options_str.'
</select>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
}//Switch End
return $output;
}
public function parseFieldForMetaBox($field = array(), $section=''){
$output='';
$value = (isset($field['value'])) ? $field['value'] : $field['default'];
if(is_array($value)){
$value = array_map('stripslashes', $value);
}
else{
$value = stripslashes($value);
}
switch ($field['type']){
case 'start_section':{
$output .= '<h4>'. $field['name']. ' - <small>'. $field['desc']. '</small></h4>';
break;
}
case 'text':{
$output .= '<p class="inside"><label>'.$field['name'].'</label>
<input id="'.$section.$field['id'].'" type="text" name="'.$section . $field['id'].'" value="'.trim(esc_attr($value)).'" style="margin-right:10px; width:50%" />
<span class="howto">'.$field['desc'].'</span></p>';
break;
}
case 'hidden':{
$output .= '<input class="dinamic-field" type="hidden" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" />';
break;
}
case 'textarea':{
$output .= '<div class="control-group dinamic-field">
<label class="control-label">'.$field['name'].'</label>
<div class="controls">
<textarea id="'.$section.$field['id'].'" rows="4" name="'.$section . $field['id'].'" class="span8">'.trim(esc_textarea($value)).'</textarea>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'checkbox':{
$output .= '<div class="control-group dinamic-field">
<label class=" control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input name="'.$section . $field['id'].'" type="hidden" value="'.esc_attr($value).'" id="'.$field['id'].'" />
<div data-toggle="buttons-radio" class="btn-group">
<a href="#" data-state="on" class="btn '.(($value == 'on') ? 'active' : '').'">ENABLED</a>
<a href="#" data-state="off" class="btn '.(($value == 'off') ? 'active' : '').'">DISABLED</a>
</div>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'file':{
if($value == '') $value = $field['default'];
$output .= '<div class="control-group dinamic-field">
<label class="control-label">'.$field['name'].'<br/></label>
<div class="controls">
<input type="hidden" id="'.$field['id'].'" name="'.$section . $field['id'].'" value="'.esc_attr($value).'" />
<div class="btn-group uploader">
<a href="#" name="f_'.$field['id'].'" class="btn active filename span8">'.esc_attr($value).'</a>
<a href="#" class="btn action">Upload File</a>
</div>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'select':{
$options = $field['values'];
$options_str = '';
foreach ($options as $k=>$v){
$selected = ($k == $value) ? 'selected' : '';
$options_str .= '<option value="'.esc_attr($k).'" '.$selected.' >'.esc_attr($v).'</option>';
}
$output .='<div class="control-group dinamic-field">
<label class="control-label">'.$field['name'].'</label>
<div class="controls">
<select id="'.$field['id'].'" name="'.$section . $field['id'].'">
'.$options_str.'
</select>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
case 'multiselect':{
if(!is_array($value)){ $value = array($value);}
$options = $field['values'];
$options_str = '';
foreach ($options as $k=>$v){
if(in_array($k, $value)){
$options_str .= '<option value="'.esc_attr($k).'" selected>'.esc_attr($v).'</option>';
}
else{
$options_str .= '<option value="'.esc_attr($k).'">'.esc_attr($v).'</option>';
}
}
$output .= '<div class="control-group dinamic-field">
<label for="multiSelect" class="control-label">'.$field['name'].'</label>
<div class="controls">
<select name="'.$section . $field['id'].'[]" multiple="multiple">
'.$options_str.'
</select>
<p class="help-block">'.$field['desc'].'</p>
</div>
</div>';
break;
}
}//Switch End
return $output;
}
public function renderTabButtons(){
$tpl = '<li><a data-toggle="tab" href="#%s">%s</a></li>';
$output = '';
$ttt = $this->data_obj->getSetting('main_settings.data.tabs');
foreach ($ttt as $tab) {
$output .= sprintf($tpl, $tab['id'], $tab['name']);
}
return '<ul id="main_navigation" class="nav nav-pills">' . $output .'</ul><!-- main_navigation -->';
}
public function getSetting($path = null) {
return $this->data_obj->getSetting($path);
}
/**
* This is main Ajax Handler. All ajax request fired in theme administration should be handled by
* this method.
*
* PReko posta dobije niz sledeci
*
* main_settings=>arraY(name => '', value= ''), array(name => '', value= '') ..... array(name => '', value= '')
* sliders => ....
*
*/
public function adminAjax()
{
$action = sanitize_text_field($_POST['sec_action']);
// check to see if the submitted nonce matches with the
// generated nonce we created earlier
$nonce = check_ajax_referer(ThemeSetup::HOOK . '-admin-ajax-nonce', ThemeSetup::HOOK . '_admin_ajax_nonce', false);
if ($nonce === false){
die();
}
$resp = $_POST;
switch ($action){
case 'save': {// in case of saving data old data will be overwritten and/or new data will be created.
$validator_main = new Validator(null, $resp['main_settings']);
if(is_array($resp['main_settings'])){
//Prepare Validation array related to a main settings.
$validator_main->prepareMap($this->data_obj->getSettingTpl('main_settings.data.items'));
if($validator_main->validate()){
$validator_main->applyFilters();
}
}
//Sections of interest
if(!$validator_main->hasErrors()){
$this->data_obj->setOption('main_settings', $validator_main->data);
$response = $this->data_obj->save();
}
else{
$response = false;
}
if($response == true){
$response = array('status'=>'success', 'msg'=>__('Success. Data saved!', 'tl_theme_admin'));
}
else{
$response = array('status'=>'fail', 'msg'=>__('Options was not changed.','tl_theme_admin').' '.$validator_main->toString());
}
break;
}
case 'save_slider' : {
$validator_sliders = new Validator(null, $resp['sliders']);
if(is_array($resp['sliders'])){
$type = $resp['sliders']['incommon']['slider_type'];
if(isset($type) && $type != ''){
$validator_sliders->prepareMapSliders($this->data_obj->getSettingTpl('sliders_tpl.data.sliders'), $type);
if($validator_sliders->validate()){
$validator_sliders->applyFilters();
}
// exit;
if(!$validator_sliders->hasErrors()){
$this->data_obj->setOption('collections.sliders.current_slider', $type);
$this->data_obj->setOption('collections.sliders.data.'.$type, $validator_sliders->data);
// exit;
$response = $this->data_obj->save();
}else{
$response = false;
}
}
else{
$response = false;
}
}
if($response == true){
$response = array('status'=>'success', 'msg'=>__('Success. Data saved!','tl_theme_admin'));
}
else{
if($validator_sliders->hasErrors()){
$response = array('status'=>'fail', 'msg'=>current($validator_sliders->errors));
}else{
$response = array('status'=>'fail', 'msg'=>__('Options was not changed. Slider data is not saved.','tl_theme_admin'));
}
}
break;
}
case 'load_sliders':{
$response = $this->data_obj->getSetting('sliders_tpl.data.sliders');
if(is_array($response)){
array_walk_recursive($response, 'my_stripslashes');
}
$response['tpls'] = $this->data_obj->getSettingTpl('sliders_tpl.data.sliders');
break;
}
}
$response = json_encode($response);
header("Content-Type: application/json");
die($response);
}
}
function my_stripslashes(&$p){
$p = stripslashes($p);
}<file_sep><?php
/**
* This week/ Today special widget
*
* Use custom post type product
*/
class TlThemeMenuHighlightsWidget extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'widget-menu-highlights', 'description' => __('Mazzareli - Menu Highlights','tl_theme_admin'));
$control_ops = array('width' => 300, 'height' => 350);
parent::__construct('tl_theme_menuhighlights', __('Mazzareli - Menu Highlights','tl_theme_admin'), $widget_ops, $control_ops);
}
function widget( $args, $instance ) {
extract($args);
$title = apply_filters( 'widget_title', !isset($instance['title']) ? 'Menu Highlights' : $instance['title'], $instance, $this->id_base);
$post_id = $instance['post_id'];
$readmore_switch = $instance['readmore_switch'];
$sidebar = $args['id'];
$tl_posts = get_posts(array('post_type'=>'product', 'include'=> $post_id));
echo $before_widget;
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; }
?>
<ul>
<?php foreach ($tl_posts as $tl_post) :?>
<li>
<?php if(has_post_thumbnail($tl_post->ID)):?>
<p class="image"><?php echo get_the_post_thumbnail($tl_post->ID, 'small-thumb'); ?> </p>
<?php endif; ?>
<h2 class="title"><a href="<?php echo get_permalink($tl_post->ID);?>" title=""><?php echo $tl_post->post_title; ?></a></h2>
<div class="excerpt">
<p><?php mls_abstract($tl_post->post_content, 12, true); ?></p>
</div>
</li>
<?php endforeach; ?>
<?php
//Do we have menu page
$menu_page = getPagesByTemplate(1, 'template-page-menu1.php');
?>
<?php if ($readmore_switch && !empty($menu_page)): ?>
<li>
<p class="actions">
<a class="read-more-<?php echo ($sidebar == 'home_sidebar1') ? 'red':'white';?>" href="<?php echo get_permalink($menu_page[0]);?>" title="<?php echo $tl_post->post_title; ?>"><?php _e('Look for more', 'tl_theme'); ?></a>
</p>
</li>
<?php endif; ?>
</ul>
<div class="clearfix"></div>
<?php echo $after_widget;
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['post_id'] = (array) $new_instance['post_id'];
$instance['readmore_switch'] = isset($new_instance['readmore_switch']);
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => 'Menu Highlights','post_id' => '', 'readmore_switch' => '') );
$title = strip_tags($instance['title']);
$post_id = $instance['post_id']; // this is an array
$read_more_switch = strip_tags($instance['readmore_switch']);
$post_id = (array) $post_id;
$products = get_posts(array('post_type'=>'product', 'number_post'=>999));
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','tl_theme_admin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
<p>
<label for="<?php echo $this->get_field_id('post_id'); ?>"><?php _e('Select Menu Highlights:','tl_theme_admin'); ?></label><br />
<select multiple="multiple" name="<?php echo $this->get_field_name('post_id'); ?>[]" id="<?php echo $this->get_field_id('post_id'); ?>">
<?php foreach ($products as $p):?>
<option value="<?php echo $p->ID; ?>" <?php echo (in_array($p->ID, $post_id)) ? ' selected="selected" ':''; ?>><?php echo $p->post_title; ?></option>
<?php endforeach;?>
</select>
</p>
<p><input id="<?php echo $this->get_field_id('readmore_switch'); ?>" name="<?php echo $this->get_field_name('readmore_switch'); ?>" type="checkbox" <?php checked(isset($instance['readmore_switch']) ? $instance['readmore_switch'] : 0); ?> />
<label for="<?php echo $this->get_field_id('readmore_switch'); ?>"><?php _e('Show read more link', 'tl_theme_admin'); ?></label></p>
<?php
}
}
register_widget('TlThemeMenuHighlightsWidget');<file_sep><?php
/**
* Template Name: Page with right sidebar
* Description: Page with right sidebar .
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php get_header(); ?>
<?php get_template_part('template-part-ribbon'); ?>
<div id="content">
<div class="wrap">
<div class="c-8 divider">
<div class="page">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<p class="left"><?php if ( has_post_thumbnail() ): the_post_thumbnail('medium', array('')); endif; ?></p>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div> <!-- .page -->
</div><!-- .c-8 -->
<?php get_sidebar(); ?>
<!-- <div class="c-4 sidebar"></div> --><!-- .c-4 -->
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
* Contact form widget
*/
class TlThemeContactFormWidget extends WP_Widget {
/**
* Constructor
*/
public function __construct() {
$widget_ops = array('classname' => ' widget-contact-us',
'description' => __( 'Mazzareli - Contact Form', 'tl_theme_admin'));
parent::__construct(
'tl_theme_contact_form',
__('Mazzareli - Contact Form Widget','tl_theme_admin'),
$widget_ops
);
}
/**
* Outputs the options form on admin
* @see WP_Widget::form()
* @param $instance current settings
*/
public function form( $instance ) {
//Get Posts from first category (current one)
$default = array(
'title' => __('Contact Us', 'tl_theme_admin'),
);
$instance = wp_parse_args((array) $instance, $default);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget Title', 'tl_theme_admin'); ?></label><br />
<input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" value="<?php echo esc_attr($instance['title']); ?>" />
</p>
<?php
}
/**
* processes widget options to be saved
* @see WP_Widget::update()
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
if(empty($old_instance)){
$old_instance = $new_instance;
}
if($new_instance['num'] > 8) $new_instance['num'] = 8;
foreach ($old_instance as $k => $value) {
$instance[$k] = trim(strip_tags($new_instance[$k]));
}
return $instance;
}
/**
* Front-end display of widget.
* @see WP_Widget::widget()
* @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
* @param array $instance The settings for the particular instance of the widget
*
* address, phone, fax, email
*/
public function widget( $args, $instance ) {
global $wpdb;
extract( $args );
$title = empty($instance['title']) ? '' : apply_filters('widget_title', $instance['title']);
echo $before_widget;
?>
<?php if($title): echo $before_title . $title . $after_title; endif; ?>
<?php
echo $this->renderForm($args, $instance);
echo $after_widget;
}
protected function renderForm($args, $instance){
?>
<div class="contact-modal-box"></div>
<form enctype="multipart/form-data" method="post" id="contact-form-footer">
<div class="send-form">
<p>
<label>*<?php _e('Your name', 'tl_theme') ?>:</label>
<input class="u-3" name="name" id="name1" />
</p>
<p>
<label>*<?php _e('Your E-mail', 'tl_theme') ?>:</label>
<input class="u-3" name="email" id="email1" />
</p>
<p>
<label>*<?php _e('Your Message', 'tl_theme') ?>:</label>
<textarea class="u-3" name="message" id="message1" cols="80" rows="3"></textarea>
</p>
<p>
<input type="hidden" name="from_widget" value="1" />
<a class="button-submit contact-button button dark"><span><?php _e('Contact Us', 'tl_theme') ?></span></a>
</p>
</div>
</form>
<?php
}
} //Class End
register_widget('TlThemeContactFormWidget');<file_sep><?php
$show_meta = Data()->isOn('mi_blog.mi_blog_meta_switch');
?>
<?php
get_header();
get_template_part('template-part-ribbon');
?>
<div id="content">
<div class="wrap">
<ul id="price-category" class="menu-page">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<li>
<?php
$meta = get_post_meta($post->ID);
$meta = unserialize($meta['product_meta_data'][0]);
?>
<?php if(has_post_thumbnail()): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'theme-gallery-photo'); ?>
<div class="item-image">
<p class="image">
<a class="lightbox-standard" href="<?php echo $large_image_url[0]; ?>" title="<?php the_title() ?>">
<?php echo get_the_post_thumbnail($post->ID, 'small-thumb'); ?>
</a>
</p>
<?php if($meta['special_switch'] == 'on'):?>
<a class="specialty lightbox" href="<?php echo $large_image_url[0]; ?>"><?php _e('Specialty', 'tl_theme'); ?></a>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="price-heading">
<h3>
<a href="<?php echo the_permalink()?>"><?php the_title(); ?></a>
<?php if(isset($meta['price'])): ?><span><?php echo $meta['price']; ?></span><?php endif; ?>
</h3>
</div>
<p><?php the_excerpt(); ?></p>
<div class="clearfix"></div>
</li>
<?php endwhile; endif; ?>
</ul>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/* Head function in administration panel*/
if(is_admin()){
//Theme Admin hooks
add_action('admin_print_scripts-'. $this->admin_panel_hook_name, 'add_admin_scripts');
add_action('admin_print_styles-' . $this->admin_panel_hook_name, 'add_admin_style');
//Post and page hooks
add_action('admin_print_scripts-post-new.php', 'add_custom_post_js');
add_action('admin_print_scripts-post.php' , 'add_custom_post_js');
add_action('admin_print_scripts-post-new.php', 'add_custom_post_css');
add_action('admin_print_scripts-post.php' , 'add_custom_post_css');
}
function add_custom_post_css(){
global $typenow;
if($typenow == 'event'){
wp_enqueue_style(ThemeSetup::HOOK . '-ui-uniform-css', TL_THEME_JS_URI . '/jquery.uniform/uniform.default.css');
wp_enqueue_style(ThemeSetup::HOOK . '-ui-datepicker-css', TL_THEME_JS_URI . '/jquery-ui-1.8.2.datepicker/smoothness/jquery-ui.css');
}
if($typenow == 'mlsgallery' || $typenow == 'testimonial'){
wp_enqueue_style('mlsgallery-css', TL_THEME_ADMIN_URI . '/css/admin_custom_post_type.css');
}elseif (in_array($typenow, array('post', 'page', 'event', 'product'))){
wp_enqueue_style('tiny-mce-shortcode-buttons-css', TL_THEME_ADMIN_URI . '/css/tiny-mce.css');
}
wp_enqueue_style('bootstrap-css', TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap.css');
wp_enqueue_style('bootstrap-responsive-css', TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap-responsive.css');
wp_enqueue_style('admin-style-css', TL_THEME_ADMIN_CSS_URI . '/admin-style.css');
}
function add_custom_post_js(){
global $typenow;
if(isset($typenow) && $typenow){
wp_enqueue_script('mlsgallery-js', TL_THEME_ADMIN_URI . '/js/admin_custom_post_type.js', array('jquery','jquery-ui-sortable'));
wp_localize_script('mlsgallery-js', 'tl_gallery', array( 'theme_admin_url' => TL_THEME_ADMIN_URI));
}
if($typenow == 'event'){
wp_enqueue_script(ThemeSetup::HOOK . '-ui-uniform', TL_THEME_JS_URI . '/jquery.uniform/jquery.uniform.min.js', array('jquery'));
wp_enqueue_script(ThemeSetup::HOOK.'-timepicker-script', TL_THEME_JS_URI.'/jquery-ui-timepicker-addon.js', array('jquery','jquery-ui-slider','jquery-ui-widget', 'jquery-ui-datepicker'));
//wp_enqueue_script('mlsgallery-js', TL_THEME_ADMIN_URI . '/js/admin_custom_post_type.js', array('jquery'));
}
if($typenow == 'mlsgallery'){
wp_enqueue_script( 'bootstrap', TL_THEME_ADMIN_URI . '/bootstrap/js/bootstrap.js', array('jquery'));
}
}
function add_admin_style() {
wp_enqueue_style('bootstrap-css', TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap.css');
wp_enqueue_style('bootstrap-responsive-css', TL_THEME_ADMIN_URI . '/bootstrap/css/bootstrap-responsive.css');
wp_enqueue_style('admin-style-css', TL_THEME_ADMIN_CSS_URI . '/admin-style.css');
wp_enqueue_style('admin-style-cssui', TL_THEME_ADMIN_CSS_URI . '/jquery-ui-1.8.16.custom.css');
wp_enqueue_style( 'mls_color-picker-css', TL_THEME_ADMIN_URI . '/js/colorpicker/css/colorpicker.css');
wp_enqueue_style( 'mls_color-picker-css', TL_THEME_ADMIN_URI . '/js/colorpicker/css/layout.css');
wp_enqueue_style('thickbox');
}
function add_admin_scripts() {
global $wp_styles;
wp_deregister_script('autosave');
wp_enqueue_script('jquery');
$kids_ua = getBrowser();
$ua['version'] = floatval($kids_ua['version']);
if($kids_ua['name'] == 'Internet Explorer' && $kids_ua['version'] < 9.0 ){
wp_register_script('html5-js', 'http://html5shim.googlecode.com/svn/trunk/html5.js', array("jquery"));
wp_enqueue_script( 'html5-js');
}
wp_enqueue_style('ie8-style', TL_THEME_ADMIN_URI . '/css/ie8.css');
$wp_styles->add_data('ie8-style', 'conditional', 'IE 8');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-mouse');
wp_enqueue_script('jquery-ui-widget');
wp_enqueue_script('jquery-ui-slider');
/*
Bug Fix. Jquery UI and Thickbox does not work well together. Check this URL:
http://wordpress.org/support/topic/wp-32-thickbox-jquery-ui-tabs-conflict
*/
wp_register_script( 'custom_tb', TL_THEME_ADMIN_JS_URI . '/custom_tb.js', array('jquery','media-upload', 'thickbox') );
wp_enqueue_script( 'custom_tb');
wp_enqueue_script( 'mls_color_picker', TL_THEME_ADMIN_URI . '/js/colorpicker/js/colorpicker.js', array('jquery'));
wp_enqueue_script( 'mls_color_picker_eye', TL_THEME_ADMIN_URI . '/js/colorpicker/js/eye.js', array('jquery'));
wp_enqueue_script( 'mls_color_picker_layout', TL_THEME_ADMIN_URI . '/js/colorpicker/js/layout.js', array('jquery'));
/* all admin Plugins */
wp_enqueue_script( 'bootstrap', TL_THEME_ADMIN_URI . '/bootstrap/js/bootstrap.js', array('jquery'));
/*Google Maps API */
wp_enqueue_script(ThemeSetup::HOOK . '-google-maps-api-js', 'http://maps.google.com/maps/api/js?sensor=false');
wp_enqueue_script('admin-number-slider-js', TL_THEME_ADMIN_JS_URI . '/jquery.mls_slider.js', array('jquery','jquery-ui-slider', ThemeSetup::HOOK . '-google-maps-api-js'));
wp_enqueue_script('admin-script-js2', TL_THEME_ADMIN_JS_URI . '/admin-main.js', array('jquery','media-upload', 'thickbox', 'bootstrap'));
$theme = ThemeSetup::getInstance()->getThemeDataObj();
wp_localize_script('admin-script-js2', ThemeSetup::HOOK . '_admin_main',array('lat' => $theme->getMain('mi_gmaps.mi_gmaps_lat'),
'long' => $theme->getMain('mi_gmaps.mi_gmaps_long'),
'zoom' => $theme->getMain('mi_gmaps.mi_gmaps_zoom')));
/* Ajax in administration panel */
wp_enqueue_script('admin-ajax-script', TL_THEME_ADMIN_JS_URI . '/admin-ajax.js', array( 'jquery', 'media-upload', 'thickbox','bootstrap'));
wp_localize_script('admin-ajax-script', ThemeSetup::HOOK . '_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
'theme_url' => get_template_directory_uri(),
ThemeSetup::HOOK . '_admin_ajax_nonce' => wp_create_nonce(ThemeSetup::HOOK . '-admin-ajax-nonce')));
}<file_sep><?php
if(!defined("RUN_FOREST_RUN")) die("Forest Gump");
abstract class MetaBoxAbstract {
const LANG = 'some_textdomain';
/**
* Metabox id
* @var string. Required.
*/
protected $id = '';
/**
* Metabox title
* @var string. Required.
*/
public $title = '';
/**
* Function that prints out the HTML for the edit screen section. Pass function name as a string. Within a class, you can instead pass an array to call one of the class's methods. See the second example under Example below.
* @var string. Required.
*/
public $callback = 'show';
/**
* Arguments to pass into your callback function. The callback will receive the $post object and whatever parameters are passed through this variable.
* @var array. Optional.
*/
public $callback_args = array();
/**
* Current Post Type ('post', 'page', 'link', or 'custom_post_type' where custom_post_type is the custom post type slug)
*/
public $post_type = '';
/**
* The part of the page where the edit screen section should be shown ('normal', 'advanced', or 'side').
* @var string. Required.
*/
public $context = 'normal';
/**
* The priority within the context where the boxes should show ('high', 'core', 'default' or 'low')
* @var string. Optional.
*/
public $priority = 'default';
/**
* Fields on the form
* @var array
*/
protected $fields = array();
/**
* All Errors
* @var array
*/
protected $errors = array();
/* Implement in subclass */
abstract public function formFieldsConf();
/**
* The type of Write screen on which to show the edit screen section
* ('post', 'page', 'link', or 'custom_post_type' where custom_post_type
* is the custom post type slug)
* Default: None
*
* @var array
*/
var $_object_types = array();
public function __construct($id, $title, $callback, $callback_args, $context, $priority, $object_types = null){
$this->id = $id;
$this->title = $title;
$this->callback = ($callback !='') ? $callback : $this->callback;
$this->callback_args = is_array($callback_args) && count($callback_args) > 0 ? $callback_args : $this;
$this->priority = $priority !='' ? $priority : $this->priority;
$this->context = $context !='' ? $context : $this->context;
$this->_object_types = !empty($object_types) ? $object_types : array('post', 'page');
// if the user has not already set the type of this metabox,
// then we need to do that now
if(!isset($this->metaboxType) || !$this->metaboxType ) $this->setMetaboxType();
add_action( 'add_meta_boxes', array(&$this, 'addMetaBox' ));
add_action( 'save_post' , array(&$this, 'saveMetaBox'));
// add_filter( 'wp_redirect', array(&$this, '_redirectIntervention'), 40, 1 );
/* Populate fields with default values */
if(empty($this->fields)) $this->formFieldsConf();
add_filter('metabox-requests-'.$this->id, array(&$this, '_filterRequest'));
}
/*
* The Idea behind this method is to be implemented in subclass. If it is not implemented there is no
* additional filtering :)
*/
public function _filterRequest($param){
return $param;
}
/**
* $id, $title, $callback, $post_type, $context, $priority, $callback_args
* Enter description here ...
*/
public function addMetaBox(){
//post or page
$this->post_type = $this->getCurrentPostType();
// this metabox is to be displayed for a certain object type only
if ( !in_array($this->post_type, $this->_object_types) )
return;
add_meta_box(
$this->id
,$this->title
,array( &$this, $this->callback )
,$this->post_type
,$this->context
,$this->priority
,$this->callback_args
);
}
/**
* Save Metabox
* Enter description here ...
* @param unknown_type $post_id
*/
public function saveMetaBox($post_id){
//initializing
$post = get_post($post_id);
$this->post_type = $this->getCurrentPostType();
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !isset($_REQUEST[ get_class().$this->id ]) )
return;
if ( !wp_verify_nonce( $_REQUEST[ get_class().$this->id ], plugin_basename( __FILE__ ) ) )
return;
// this metabox is to be displayed for a certain object type only
if ( !in_array($post->post_type, $this->_object_types) )
return;
// Check permissions
if ( 'page' == $post->post_type )
{
if ( !current_user_can( 'edit_page', $post->ID ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
}
/* Save Meta Data Logic */
do_action('metabox-save-'.$this->id, $this->_getRequestedPostMetas(), $post->ID, $this );
return true;
}
/**
* Display Metabox
*/
public function show(){
wp_nonce_field( plugin_basename( __FILE__ ), get_class().$this->id );
do_action('metabox-show-'.$this->id, $this->fields);
}
/**
* Save data to DB
* @param array $source
* @param int $post_id
*/
public function _saveAsPostMeta($source, $post_id){
foreach ($source as $key=>$s){
update_post_meta($post_id, $key, $s);
}
return true;
}
/**
* Validate / sanitarize and return data before save
*/
protected function _getRequestedPostMetas(){
$ignores = array('post_title', 'post_name', 'post_content', 'post_excerpt', 'post',
'post_status', 'post_type', 'post_author', 'ping_status', 'post_parent', 'message',
'post_category', 'comment_status', 'menu_order', 'to_ping', 'pinged', 'post_password',
'guid', 'post_content_filtered', 'import_id', 'post_date', 'post_date_gmt', 'tags_input',
'action');
$fields = array();
foreach ((array)$this->fields as $field) {
if (!isset($field['id'])) continue;
$fields[] = $field['id'];
}
$requests = $_REQUEST;
foreach ((array)$requests as $k => $request)
{
if (($fields && !in_array($k, $fields)) || (in_array($k, $ignores) || strpos($k, 'nounce')!==false))
{
unset($requests[$k]);
}
}
return apply_filters('metabox-requests-'.$this->id, $requests);
}
/**
* At the moment supports only pages and posts
* @param string $type
*/
protected function setMetaboxType($type='default'){
$this->metaboxType = $type;
switch($this->metaboxType){
case 'default':
add_action('metabox-show-'.$this->id, array(&$this, '_renderMetaBoxContent'), 20, 1 );
add_action('metabox-save-'.$this->id, array(&$this, '_saveAsPostMeta'), 10, 2);
break;
}
}
/**
* Method is designed to return the currently visible post type
*/
function getCurrentPostType()
{ global $typenow;
return $typenow;
}
/**
* Render inner content of metabox
*/
public function _renderMetaBoxContent(){
global $post;
$out = '';
/* Get Meta for this item */
$post_meta = get_post_custom($post->ID);
foreach ($this->fields as $k => $f) {
if(!isset($f['id']) || !isset($f['type'])) {
continue;
} else{
if(array_key_exists($f['id'], $post_meta)){
if(is_array($post_meta[$f['id']])){
$post_meta_data = unserialize($post_meta[$f['id']][0]);
}else
{
$post_meta_data = $post_meta[$f['id']];
}
$this->fields[$k]['value'] = $post_meta_data;
}
}
$out .= $this->_renderField($this->fields[$k]);
}
echo '<div class="custom-admin-theme-css">'.$out.'</div>';
}
/**
* Render Form Fields in Metabox
*/
protected function _renderField($field){
$output = '';
$value = isset($field['value']) ? $field['value'] : '';
switch ($field['type']){
case 'subsection_start':
$output .= '<p class="inside"><h4>'.$field['name'].'</h4>'.$field['desc'].'</p>';
break;
case 'text':
$output .= '<p class="inside"><input type="text" name="'.$field['id'].'" value="'.$value.'" /></p>';
break;
case 'select':
$options = '';
foreach ($field['values'] as $k => $v) {
if($v == $value)
$options .= '<option value="'.$k.'" selected="selected">'.$v.'</option>';
else
$options .= '<option value="'.$k.'">'.$v.'</option>';
}
$output .= '<select name="'.$field['id'].'">'.$options.'</select>';
break;
case 'multiselect':
$value = isset($value) && $value !='' ? $value : 'no_sidebars';
if(!is_array($value)){
$value = array($value);
}
$options = '';
foreach ($field['values'] as $k => $v) {
if(in_array($k, $value))
$options .= '<option value="'.$k.'" selected="selected">'.$v.'</option>';
else
$options .= '<option value="'.$k.'">'.$v.'</option>';
}
$output .= '<div class="inside"><h4>'.$field['name'].' - <small>'.$field['desc'].'</small></h4><select style="width:50%" name="'.$field['id'].'[]" multiple="multiple">'.$options.'</select><br /></div>';
break;
case 'radio':
break;
case 'checkbox':
break;
case 'textarea':
break;
case 'hidden':
break;
case 'image':
break;
}
return $output;
}
public function getErrors(){
return $this->errors;
}
public function hasErrors(){
return !empty($this->errors);
}
}//End of class
class MlsSidebarMetaBox extends MetaBoxAbstract{
public function __construct($id, $title, $callback='', $callback_args, $context, $priority, $custom_post_types=array()){
parent::__construct($id, $title, $callback, $callback_args, $context, $priority, $custom_post_types);
}
public function _filterRequest($param){
$tmp = $param;
foreach ($param as $k=>$p){
if($p == 'no_sidebars'){
unset($tmp[$k]);
}
}
return $tmp;
}
public function formFieldsConf(){
$sidebars = Data()->getMain('mi_custom_sidebars.csidebar_list');
$tmp = array();
if(!is_array($sidebars)) $sidebars = array($sidebars);
$tmp['no_sidebars'] = '-- '.__('No Sidebar', 'tl_theme_admin').' --';
foreach ($sidebars as $value) {
$tmp[str_replace(' ', '_', strtolower($value))] = $value;
}
$this->fields = array(
array(
'id' => 'tl_theme_sidebar_ids',
'name' => __('Select Sidebars', 'tl_theme_admin' ),
'desc' => __('Selected sidebars will be shown at this page/post', 'tl_theme_admin' ),
'type' => 'multiselect',
'values' => $tmp,
'value' => null,
'default' => ''
)
);//Ebd of fields
return $this->fields;
}
} // End MlsSidebarMetaBox
$sidebarMetabox = new MlsSidebarMetaBox('mls_sidebar', 'Sidebars', '', array(), "", "", array('post', 'page', 'product', 'event', 'testimonial'));
<file_sep><?php
/**
* Template Name: Blog 1 Column template with sidebar
* Description: Blog 1 Column template with sidebar
*
* @package Theme Laboratory
* @subpackage Mazzareli
*/
?>
<?php
$show_meta = Data()->isOn('mi_blog.mi_blog_meta_switch');
$hide_cats = Data()->getMain('mi_blog.hide_cats');
$readmore = Data()->getMain('mi_blog.readmore');
$hide_cats_tmp = array();
if($hide_cats){
foreach ($hide_cats as $value) {
$hide_cats_tmp[] = (string)($value * (-1));
}
}
?>
<?php
get_header();
get_template_part('template-part-ribbon');
global $wp_query;
$args = array( 'post_type' => 'post', 'order'=>'DESC', 'orderby'=>'date',
'paged' => get_query_var('paged'),
'cat' => implode(',', $hide_cats_tmp)
);
query_posts( $args );
?>
<div id="content">
<div class="wrap">
<div class="c-8 divider">
<div class="post-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<div id="post-<?php the_ID()?>" <?php post_class() ?>>
<h2 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php if($show_meta): ?>
<p class="meta">
<span><?php _e('Date','tl_theme'); ?>: <a class="date" title="<?php the_time('d D Y'); ?>" href="#"><?php the_time('d D Y'); ?></a></span>
<span><?php _e('Author','tl_theme'); ?>: <a class="author" title="<?php the_author(); ?>" href="#"><?php the_author(); ?></a></span>
<span class="categories"><?php _e('Categories','tl_theme'); ?>: <?php the_category(', ') ?></span>
<?php if(Data()->isOn('mi_blog.comments_switch')) : ?>
<span class="comments"><a href="<?php echo the_permalink().'#comments'; ?>" title="<?php _e('All comments for', 'tl_theme'); the_title(' '); ?>" href="#"><?php comments_number('0', '1', '%'); ?></a></span>
<?php endif; ?>
</p>
<?php endif; ?>
<?php if(has_post_thumbnail()): ?>
<?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'theme-gallery-photo'); ?>
<p class="image"><a href="<?php echo $large_image_url[0]; ?>"><?php the_post_thumbnail('blog-big'); ?></a></p>
<?php endif; ?>
<div class="excerpt">
<p><strong><?php the_excerpt(); ?></strong></p>
</div>
<p class="actions"><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" class="read-more-red"><?php _e('Read More','tl_theme'); ?></a></p>
<p class="meta dashed">
<?php the_tags('<span class="tags">'.__('Tags', 'tl_theme').': ', ', ','</span>'); ?>
</p>
</div><!-- end post -->
<?php endwhile; endif; ?>
<?php wp_pagenavi(array('class'=>'pagination',
'options'=> array('pages_text'=>' ',
'first_text' => '',
'last_text' => '',
'always_show' => false,
'use_pagenavi_css'=>false,
'prev_text' => __('Previous', 'tl_theme'),
'next_text' => __('Next', 'tl_theme'),
))
); ?>
</div><!-- end post-list -->
</div>
<?php get_sidebar('blog'); ?>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
get_header();
get_template_part('template-part-ribbon');
?>
<div id="content">
<div class="wrap">
<div class="c-12 divider">
<div class="review-list">
<?php if(have_posts()): while (have_posts()) : the_post(); ?>
<?php $meta_values = testimonialsMetaData($post->ID); ?>
<div class="review dashed post-<?php the_ID(); ?>">
<?php the_content(); ?>
<?php if($meta_values['author']): ?>
<p class="author"><span><?php echo $meta_values['author']; ?></span> <br />
<?php echo $meta_values['additional_info']; ?>
</p>
<?php endif; ?>
</div><!-- end post -->
<?php endwhile; endif; ?>
</div><!-- end review-list -->
</div>
</div><!-- end wrap -->
</div><!-- end content -->
<?php get_footer(); ?><file_sep><?php
/**
* Chef widget
*/
class TlThemeChefWidget extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'widget-about', 'description' => __('Mazzareli - Chef','tl_theme_admin'));
$control_ops = array('width' => 300, 'height' => 350);
parent::__construct('tl_theme_chef', __('Mazzareli - Chef','tl_theme_admin'), $widget_ops, $control_ops);
}
function widget( $args, $instance ) {
extract($args);
$title = apply_filters( 'widget_title', !isset($instance['title']) ? 'Chef Mazzareli' : $instance['title'], $instance, $this->id_base);
$post_id = esc_attr($instance['post_id']);
$readmore_switch = $instance['readmore_switch'];
$sidebar = $args['id'];
$tl_post = get_page($post_id);
echo $before_widget;
if ( !empty( $title ) ) { echo $before_title . $title . $after_title; }
?>
<?php if(has_post_thumbnail($tl_post->ID)):?>
<p class="image"><?php echo get_the_post_thumbnail($tl_post->ID, 'small-thumb'); ?> </p>
<?php endif; ?>
<div class="excerpt">
<p><?php mls_abstract($tl_post->post_content, 40, true); ?></p>
</div>
<?php if ($readmore_switch):?>
<p class="actions">
<a class="read-more-<?php echo ($sidebar == 'home_sidebar1') ? 'red':'white';?>" href="<?php echo get_permalink($tl_post->ID);?>" title="<?php echo $tl_post->post_title; ?>"><?php _e('Read More', 'tl_theme'); ?></a>
</p>
<?php endif; ?>
<div class="clearfix"></div>
<?php echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['post_id'] = strip_tags($new_instance['post_id']);
$instance['readmore_switch'] = isset($new_instance['readmore_switch']);
return $instance;
}
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'title' => 'Chef Mazzareli','post_id' => '', 'readmore_switch' => '') );
$title = strip_tags($instance['title']);
$post_id = (int) $instance['post_id'];
$read_more_switch = strip_tags($instance['readmore_switch']);
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => 'template-page-chef.php'
));
if(empty($pages)){
echo '<p>'.__('In order to use this widget you need to create Chef\'s page.','tl_theme_admin') . '</p>';
}
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','tl_theme_admin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
<p>
<label for="<?php echo $this->get_field_id('post_id'); ?>"><?php _e('Select a Chef\'s page:', 'tl_theme_admin'); ?></label><br />
<select name="<?php echo $this->get_field_name('post_id'); ?>" id="<?php echo $this->get_field_id('post_id'); ?>">
<?php foreach ($pages as $p):?>
<option value="<?php echo $p->ID; ?>" <?php selected($post_id, $p->ID, true); ?>><?php echo $p->post_title; ?></option>
<?php endforeach;?>
</select>
</p>
<p><input id="<?php echo $this->get_field_id('readmore_switch'); ?>" name="<?php echo $this->get_field_name('readmore_switch'); ?>" type="checkbox" <?php checked(isset($instance['readmore_switch']) ? $instance['readmore_switch'] : 0); ?> />
<label for="<?php echo $this->get_field_id('readmore_switch'); ?>"><?php _e('Show read more link', 'tl_theme_admin'); ?></label></p>
<?php
}
}
register_widget('TlThemeChefWidget'); | 21570a4ee0267f25b4d5ad6d8c729ff23c68bbe9 | [
"PHP"
] | 53 | PHP | themcstaplez/lapetite | 69e65fbe8ddce18c608cb2fea7cf914d9d39b3c4 | d3b51608da7eb4a307295df286920639b90df697 |
refs/heads/master | <repo_name>consulgo/Consulgo.Tests<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/FocusChangeMessage.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation
{
/// <summary>
/// Focus changes stream message
/// </summary>
public class FocusChangeMessage : AutomationMessage
{
public AutomationFocusChangedEventArgs Args { get; set; }
public FocusChangeMessage(AutomationElement sourceElement, AutomationFocusChangedEventArgs args)
: base(sourceElement)
{
Args = args;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/IModel.cs
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Interface to be used to describe the model of the System Under Test
/// </summary>
public interface IModel
{
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/AutomationControlDescription.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Simple description for automation control
/// </summary>
public class AutomationControlDescription
{
/// <summary>
/// Factory method to construct description based on <see cref="AutomationElement.NativeWindowHandleProperty"/>
/// </summary>
/// <param name="handle">Native handle of automation element</param>
/// <returns></returns>
public static AutomationControlDescription ByNativeWindowHandle(int handle)
{
return new AutomationControlDescription(AutomationElement.NativeWindowHandleProperty, handle);
}
/// <summary>
/// Factory method to construct description based on <see cref="AutomationElement.NameProperty"/>
/// </summary>
/// <param name="name">Name of automation element</param>
/// <returns></returns>
public static AutomationControlDescription ByName(string name)
{
name.ThrowIfNullOrEmptyArg("name");
return new AutomationControlDescription(AutomationElement.NameProperty, name);
}
/// <summary>
/// Factory method to construct description based on <see cref="AutomationElement.AutomationIdProperty"/>
/// </summary>
/// <param name="automationId">Automation Identifier of automation element</param>
/// <returns></returns>
public static AutomationControlDescription ById(string automationId)
{
automationId.ThrowIfNullOrEmptyArg("automationId");
return new AutomationControlDescription(AutomationElement.AutomationIdProperty, automationId);
}
protected readonly PropertyCondition _propertyCondition;
public AutomationControl ParentControl { get; set; }
public TreeScope Scope { get; set; }
protected AutomationControlDescription(PropertyCondition propertyCondition)
{
propertyCondition.ThrowIfNullArg("propertyCondition");
_propertyCondition = propertyCondition;
}
protected AutomationControlDescription(AutomationProperty property, string value)
: this(new PropertyCondition(property, value))
{
}
protected AutomationControlDescription(AutomationProperty property, int value)
: this(new PropertyCondition(property, value))
{
}
public PropertyCondition PropertyCondition
{
get
{
_propertyCondition.ThrowIfNull("PropertyCondition must be set first");
return _propertyCondition;
}
}
}
}
<file_sep>/README.md
BDD + UI Automation = Conslugo.Tests.ReactiveBdd + Conslugo.Tests.ReactiveAutomation
====================================================================================
# What is it?
Consulgo.Tests is an experiment in using Reactive Extensions to produce reactive tests that are readable and hide boiler plate. This is Proof-Of-Concept, that it's possible to implement reactive approach for both BDD and Windows Automation instead of the ugly repeatable code.
# Why?
SpecFlow is very good tool. This is not a goal to replace it, but rather to evaluate different approach.
SpecFlow is using synchronous approach, and this combined with Windows Automation often gives smelly code (e.g. Thread.Sleep). Such code is difficult to understand, and many times it is needed to construct own framework (e.g. based on White) to reduce number of places with boilerplate code. I evaluated many times different approaches to the same problem, and this is another attempt for Reactive BDD and Reactive Windows Automation.
Both Reactive BDD and Reactive Windows Automation are shipped in same solution (with sample test apps using both), but can be used separately.
# How does it work?
## Reactive BDD
* System under tests is encapsulated in a model
* All steps are commands
* State of the model is passed as parameter
* Result of each command is an observable
* Commands can have pre- and post- requisites
## Reactive Automation
* All controls have their own classes
* All controls have same base class
* All changes (structure, properties) to the controls are exposed on observables
# Future work
This is only PoC, so implement more features and unit tests.
# Samples
There is a little more advanced Hello World application (called Ugly Yet Another Application), where tests are evaluated from second executable (Consulgo.Test.ReactiveAutomation.SampleRunner). Sample application is started, tested and killed.
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/DesktopWindowControl.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Desktop Window Automation Control
/// </summary>
public class DesktopWindowControl : WindowControl
{
public DesktopWindowControl()
{
var c = AutomationElement.RootElement;
AutomationElement = c;
Description = AutomationControlDescription.ByNativeWindowHandle(c.Current.NativeWindowHandle).ChildOf(this);
}
public static DesktopWindowControl NewInstance
{
get
{
return new DesktopWindowControl();
}
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/ProcessHelper.cs
using System.Diagnostics;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner
{
public class ProcessHelper
{
public static Process StartUglyApplication()
{
var fi = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
var path = System.IO.Path.Combine(
@"..\..\..\Ugly.Yaua",
fi.Directory.Parent.Name,
fi.Directory.Name,
@"Ugly.Yaua.exe");
var p = new Process();
p.StartInfo = new ProcessStartInfo(path
//, "--TryError"
);
p.Start();
return p;
}
public static bool TryToKill(Process p)
{
try
{
p.Kill();
return true;
}
catch
{
return false;
}
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/PaneControl.cs
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Pane automation control
/// </summary>
public class PaneControl : AutomationControl
{
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/FeatureTests.cs
using Consulgo.Test.ReactiveBdd;
using System;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation
{
public class FeatureTests : BaseFeatureTest
{
private StepsImpl _s = new StepsImpl();
public void SmokeTest()
{
UglyApplicationModel model = null;
Given<UglyApplicationModel>(_s.NewUglyApplication)
.And(_s.HelloWorldModeOpen)
.When(_s.EnterName)
.And(_s.AcceptMyChoice)
.Then(_s.GreetingsIsShown)
.Start()
.Subscribe(
m =>
{
Console.WriteLine("Test progress recieved");
model = m;
},
er => Console.WriteLine("Test error: " + er),
() =>
{
Console.WriteLine("Test completed successfully");
if (model != null && model.ApplicationProcess != null)
{
ProcessHelper.TryToKill(model.ApplicationProcess);
}
});
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua/ViewModels/MainViewModel.cs
namespace Ugly.Yaua.ViewModels
{
public class MainViewModel : BaseViewModel
{
public HelloWorldViewModel HelloWorld { get; set; }
public MainViewModel()
{
HelloWorld = new HelloWorldViewModel();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/TextControl.cs
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Text Automation Control
/// </summary>
public class TextControl : AutomationControl
{
public string Value
{
get { return InternalValue; }
set { InternalValue = value; }
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/AutomationMessage.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation
{
/// <summary>
/// Base Automation Message
/// </summary>
public class AutomationMessage
{
public AutomationElement SourceElement { get; set; }
public AutomationMessage()
{
}
public AutomationMessage(AutomationElement sourceElement)
{
SourceElement = sourceElement;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/AutomationControlRxExtensions.cs
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.Controls
{
public static class AutomationControlRxExtensions
{
/// <summary>
/// Streams updates of existance of the control
/// </summary>
/// <param name="control">Control to wait for existance</param>
/// <param name="closeAfter">Should stream be closed after</param>
/// <returns>Event updates stream</returns>
public static IObservable<Unit> WaitForIt(this AutomationControl control, bool closeAfter = true)
{
if (control.AutomationElement != null)
{
return Observable.Create<Unit>(o =>
{
o.OnNext(Unit.Default);
if (closeAfter)
{
o.OnCompleted();
}
return Disposable.Empty;
});
}
return Chain<Unit>(
control.Description.ParentControl.WaitForIt(true),
() => control
.Description
.ParentControl
.AutomationElement
.WaitForFirstElement(
control.Description.PropertyCondition,
control.Description.Scope,
closeAfter)
.Select(PersistAutomationElement(control))
);
}
private static Func<AutomationElement, Unit> PersistAutomationElement(AutomationControl control)
{
return element =>
{
control.AutomationElement = element;
return Unit.Default;
};
}
private static IObservable<T> Chain<T>(this IObservable<T> previous, Func<IObservable<T>> nextProducer)
{
return previous.IsEmpty().SelectMany(Observable.Defer(nextProducer));
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/GeneralHelper.cs
using System;
namespace Consulgo.Test.ReactiveAutomation
{
internal static class GeneralHelper
{
public static void ThrowIfEmpty(this Array array, string paramName, string message = null)
{
if(array.Length == 0)
{
ArgumentOutOfRangeException arex = null;
if (string.IsNullOrEmpty(paramName))
{
arex = new ArgumentOutOfRangeException();
}
else
{
if(string.IsNullOrEmpty(message))
{
arex = new ArgumentOutOfRangeException(paramName);
}
else
{
arex = new ArgumentOutOfRangeException(paramName, message);
}
}
throw arex;
}
}
public static void ThrowIfNullArg(this object @object, string paramName, string message = null)
{
if (@object == null)
{
ArgumentNullException anex = null;
if (string.IsNullOrEmpty(paramName))
{
anex = new ArgumentNullException();
}
else
{
if (string.IsNullOrEmpty(message))
{
anex = new ArgumentNullException(paramName);
}
else
{
anex = new ArgumentNullException(paramName, message);
}
}
throw anex;
}
}
public static void ThrowIfNull(this object @object, string message = null)
{
if (@object == null)
{
NullReferenceException nrex = null;
if (string.IsNullOrEmpty(message))
{
nrex = new NullReferenceException();
}
else
{
nrex = new NullReferenceException(message);
}
throw nrex;
}
}
public static void ThrowIfNullOrEmpty(this string @object, string message = null)
{
if (string.IsNullOrEmpty(@object))
{
NullReferenceException nrex = null;
if (string.IsNullOrEmpty(message))
{
nrex = new NullReferenceException();
}
else
{
nrex = new NullReferenceException(message);
}
throw nrex;
}
}
public static void ThrowIfNullOrEmptyArg(this string @object, string paramName, string message = null)
{
if (string.IsNullOrEmpty(@object))
{
ArgumentNullException anex = null;
if (string.IsNullOrEmpty(paramName))
{
anex = new ArgumentNullException();
}
else
{
if (string.IsNullOrEmpty(message))
{
anex = new ArgumentNullException(paramName);
}
else
{
anex = new ArgumentNullException(paramName, message);
}
}
throw anex;
}
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/StructureChangeMessage.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation
{
/// <summary>
/// Strcuture change stream message
/// </summary>
public class StructureChangeMessage : AutomationMessage
{
public StructureChangedEventArgs Args { get; set; }
public StructureChangeMessage(AutomationElement sourceElement, StructureChangedEventArgs args)
: base(sourceElement)
{
Args = args;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Models/HelloWorldTabModel.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Ugly.Yaua.AutomationIds;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Models
{
public class HelloWorldTabModel : TabItemControl
{
public HelloWorldModel HelloWorld { get; set; }
public HelloWorldTabModel()
{
HelloWorld = AutomationControlDescription.ById(MainWindowIds.HelloWorldPane)
.ChildOf(this)
.As<HelloWorldModel>();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/ApplicationState.cs
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Application state holder
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public class ApplicationState<TModel>
where TModel : IModel
{
/// <summary>
/// Gets or sets reference to model of system under test
/// </summary>
public TModel Model { get; set; }
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Resolvers/BaseAutomationResolver.cs
using Consulgo.Test.ReactiveBdd;
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Resolvers
{
/// <summary>
/// Base automation resolver. Used only for validation of parameters
/// </summary>
public abstract class BaseAutomationResolver : IPropertyResolver<UglyApplicationModel>
{
public IObservable<ApplicationState<UglyApplicationModel>> Resolve<T>(ApplicationState<UglyApplicationModel> state, System.Linq.Expressions.Expression<Func<UglyApplicationModel, T>> propertyExpression)
{
ValidateExpression<T>(propertyExpression);
return ResolveImpl(state, propertyExpression);
}
protected abstract IObservable<ApplicationState<UglyApplicationModel>> ResolveImpl<T>(ApplicationState<UglyApplicationModel> state, System.Linq.Expressions.Expression<Func<UglyApplicationModel, T>> propertyExpression);
private static void ValidateExpression<T>(System.Linq.Expressions.Expression<Func<UglyApplicationModel, T>> propertyExpression)
{
if (propertyExpression.NodeType != ExpressionType.Lambda)
{
throw new NotSupportedException("Use only simple lambdas");
}
if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess)
{
throw new NotSupportedException("Use only members");
}
var me = propertyExpression.Body as MemberExpression;
if (me == null)
{
throw new NotSupportedException("Use only member expressions");
}
var pi = me.Member as PropertyInfo;
if (pi == null)
{
throw new NotSupportedException("Use only public properties as members");
}
var act = typeof(ReactiveAutomation.Controls.AutomationControl);
if (!act.IsAssignableFrom(pi.PropertyType))
{
throw new NotSupportedException("Use only types assignable from AutomationControl");
}
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/Require.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Evaluates given conditions
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public class Require<TModel>
where TModel : IModel
{
private readonly List<Func<IObservable<ApplicationState<TModel>>>> _listOfRequireBeforeFuncs
= new List<Func<IObservable<ApplicationState<TModel>>>>();
private readonly List<Func<IObservable<ApplicationState<TModel>>>> _listOfRequireAfterFuncs
= new List<Func<IObservable<ApplicationState<TModel>>>>();
private readonly ApplicationState<TModel> _state;
/// <summary>
/// Constructs the Require evaluator
/// </summary>
/// <param name="applicationModel">Initial application state</param>
public Require(ApplicationState<TModel> applicationModel)
{
_state = applicationModel;
}
/// <summary>
/// Adds property to evaluation as Pre-Condition
/// </summary>
/// <typeparam name="T">Type of statement</typeparam>
/// <param name="propertyExpression">Expression to get the property</param>
/// <param name="resolver">Resolver implmentation</param>
/// <returns>Constructed object</returns>
public Require<TModel> Before<T>(
Expression<Func<TModel, T>> propertyExpression,
IPropertyResolver<TModel> resolver)
{
RegisterRequire<T>(_listOfRequireBeforeFuncs, propertyExpression, resolver);
return this;
}
/// <summary>
/// Adds property to evaluation as Post-Condition
/// </summary>
/// <typeparam name="T">Type of statement</typeparam>
/// <param name="propertyExpression">Expression to get the property</param>
/// <param name="resolver">Resolver implmentation</param>
/// <returns>Constructed object</returns>
public Require<TModel> After<T>(
Expression<Func<TModel, T>> propertyExpression,
IPropertyResolver<TModel> resolver)
{
RegisterRequire<T>(_listOfRequireAfterFuncs, propertyExpression, resolver);
return this;
}
/// <summary>
/// Evaluates all registered Require Before statements
/// </summary>
/// <returns>Result stream</returns>
public IObservable<ApplicationState<TModel>> EvaluateOnce()
{
return Evaluate(_listOfRequireBeforeFuncs);
}
/// <summary>
/// Evaluates all registered Require After statements
/// </summary>
/// <returns>Result stream</returns>
public IObservable<ApplicationState<TModel>> EvaluateAfter()
{
return Evaluate(_listOfRequireAfterFuncs);
}
private void RegisterRequire<T>(
List<Func<IObservable<ApplicationState<TModel>>>> list,
Expression<Func<TModel, T>> propertyExpression,
IPropertyResolver<TModel> resolver)
{
Func<IObservable<ApplicationState<TModel>>> f = () => resolver.Resolve<T>(_state, propertyExpression);
list.Add(f);
}
private IObservable<ApplicationState<TModel>> Evaluate(List<Func<IObservable<ApplicationState<TModel>>>> list)
{
if (!list.Any())
{
return Observable.Return(_state);
}
return list.ChainAll();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/Program.cs
using Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation;
using System;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner
{
class Program
{
static void Main(string[] args)
{
var f = new FeatureTests();
f.SmokeTest();
Console.WriteLine("Waiting for enter");
Console.ReadLine();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/ICommand.cs
using System;
using System.Reactive;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Command that implements a step in test
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public interface ICommand<TModel> where TModel : IModel
{
/// <summary>
/// Executed when control is passed to the component.
/// Output stream to be closed after execution
/// </summary>
/// <param name="model">Application model</param>
/// <returns>Observable of changed state</returns>
IObservable<Unit> Execute(ApplicationState<TModel> model);
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/BddTestExtensions.cs
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Extensions to the control state to support basic operations on the model
/// TODO tests & implementation & documentation
/// </summary>
public static class BddTestExtensions
{
public static ControlState<TModel> And<TModel>(
this ControlState<TModel> controlState,
System.Func<ApplicationState<TModel>, ICommand<TModel>> command)
where TModel : IModel
{
return controlState.RegisterCommand(state => command(state), CommandType.And);
}
public static ControlState<TModel> Then<TModel>(
this ControlState<TModel> controlState,
System.Func<ApplicationState<TModel>, ICommand<TModel>> command)
where TModel : IModel
{
return controlState.RegisterCommand(state => command(state), CommandType.Eval);
}
public static ControlState<TModel> When<TModel>(
this ControlState<TModel> controlState,
System.Func<ApplicationState<TModel>, ICommand<TModel>> command)
where TModel : IModel
{
return controlState.RegisterCommand(state => command(state), CommandType.Eval);
}
public static ControlState<TModel> Or<TModel>(
this ControlState<TModel> controlState,
System.Func<ApplicationState<TModel>, ICommand<TModel>> command)
where TModel : IModel
{
return controlState.RegisterCommand(state => command(state), CommandType.Or);
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua/ViewModels/BaseViewModel.cs
using System.ComponentModel;
namespace Ugly.Yaua.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void RaiseProperty(string propertyName)
{
var prop = PropertyChanged;
if (prop != null)
{
prop(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua/ViewModels/HelloWorldViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Ugly.Yaua.ViewModels
{
public class HelloWorldViewModel : BaseViewModel
{
public ICommand SayHello { get; private set; }
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaiseProperty("Name");
}
}
private string _result;
public string Result
{
get { return _result; }
set
{
_result = value;
RaiseProperty("Result");
}
}
public HelloWorldViewModel()
{
SayHello = new SimpleCommand(() => Result = string.Format("Hello {0}!", Name));
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/WindowControl.cs
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Window Automation Control
/// TODO implement Window pattern
/// </summary>
public class WindowControl : AutomationControl
{
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/AutomationControl.cs
using System;
using System.Reactive;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.Controls
{
public class AutomationControl
{
private AutomationElement _automationElement;
private AutomationControlDescription _desc;
public AutomationControlDescription Description
{
get
{
_desc.ThrowIfNull("Description must be set before use");
return _desc;
}
set { _desc = value; }
}
public AutomationElement AutomationElement
{
get { return _automationElement; }
set { _automationElement = value; }
}
protected AutomationElement InternalAutomationElement
{
get
{
_desc.ThrowIfNull("AutomationElement must be set before use");
return _automationElement;
}
}
public IObservable<Unit> WaitForElement(bool closeAfter = true)
{
return this.WaitForIt(closeAfter);
}
public string Name
{
get
{
return InternalAutomationElement.Current.Name;
}
}
protected string InternalValue
{
get
{
return ValuePattern.Current.Value;
}
set
{
ValuePattern.SetValue(value);
}
}
protected void InternalInvoke()
{
InvokePattern.Invoke();
}
protected void InternalSelectItem()
{
SelectionItemPattern.Select();
}
protected ValuePattern ValuePattern
{
get
{
return GetPattern<ValuePattern>(ValuePattern.Pattern);
}
}
protected InvokePattern InvokePattern
{
get
{
return GetPattern<InvokePattern>(InvokePattern.Pattern);
}
}
protected SelectionItemPattern SelectionItemPattern
{
get
{
return GetPattern<SelectionItemPattern>(SelectionItemPattern.Pattern);
}
}
protected SelectionPattern SelectionPattern
{
get
{
return GetPattern<SelectionPattern>(SelectionPattern.Pattern);
}
}
protected TPattern GetPattern<TPattern>(AutomationPattern pattern)
where TPattern : BasePattern
{
return InternalAutomationElement.GetCurrentPattern(pattern) as TPattern;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/TabItemControl.cs
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// TabItem Automation Control
/// </summary>
public class TabItemControl : AutomationControl
{
public void Select()
{
InternalSelectItem();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Resolvers/AutomationPropertyChangedResolver.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Consulgo.Test.ReactiveBdd;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Resolvers
{
/// <summary>
/// Resolves element that is to be shown on the screen and its properties setup
/// </summary>
public class AutomationPropertyChangedResolver : BaseAutomationResolver
{
private readonly AutomationProperty[] _properties;
/// <summary>
/// Constructor for resolver
/// </summary>
/// <param name="properties">Properties to be setup on the component</param>
public AutomationPropertyChangedResolver(params AutomationProperty[] properties)
{
_properties = properties;
}
protected override IObservable<ApplicationState<UglyApplicationModel>> ResolveImpl<T>(ReactiveBdd.ApplicationState<UglyApplicationModel> state, System.Linq.Expressions.Expression<Func<UglyApplicationModel, T>> propertyExpression)
{
var elementResolver = new AutomationPropertyResolver();
return elementResolver.Resolve(state, propertyExpression)
.Chain(() =>
Observable.Create<ApplicationState<UglyApplicationModel>>(o =>
{
AutomationControl tc = null;
try
{
var fun = propertyExpression.Compile();
tc = fun(state.Model) as AutomationControl;
return tc
.AutomationElement
.WaitForChange(_properties, TreeScope.Element, true)
.Subscribe(_ =>
{
o.OnNext(state);
},
o.OnError,
o.OnCompleted);
}
catch (Exception ex)
{
o.OnError(ex);
return Disposable.Empty;
}
})
);
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/CommandType.cs
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Type of command
/// </summary>
public enum CommandType
{
/// <summary>
/// Logical conjuction operator [reserved]
/// </summary>
And,
/// <summary>
/// Logical sum operator [reserved]
/// </summary>
Or,
/// <summary>
/// Evaluation of the command operator
/// </summary>
Eval
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Models/HelloWorldModel.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Ugly.Yaua.AutomationIds;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Models
{
public class HelloWorldModel : PaneControl
{
public TextControl EnteredName { get; set; }
public ButtonControl AcceptButton { get; set; }
public TextControl Result { get; set; }
public HelloWorldModel()
{
EnteredName = AutomationControlDescription.ById(MainWindowIds.HelloWorldName)
.ChildOf(this)
.As<TextControl>();
AcceptButton = AutomationControlDescription.ById(MainWindowIds.HelloWorldButton)
.ChildOf(this)
.As<ButtonControl>();
Result = AutomationControlDescription.ById(MainWindowIds.HelloWorldResult)
.ChildOf(this)
.As<TextControl>();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/StepsImpl.cs
using Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Resolvers;
using Consulgo.Test.ReactiveBdd;
using System.Diagnostics;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation
{
public class StepsImpl
{
private const string Name = "Mr. Ugly";
private readonly string GreetingsForName = string.Format("Hello {0}!", Name);
private readonly IPropertyResolver<UglyApplicationModel> _automationResolver;
private readonly IPropertyResolver<UglyApplicationModel> _automationPropertyResolver;
public StepsImpl()
{
_automationResolver = new AutomationPropertyResolver();
_automationPropertyResolver = new AutomationPropertyChangedResolver(ValuePattern.ValueProperty);
}
public ICommand<UglyApplicationModel> GreetingsIsShown(ApplicationState<UglyApplicationModel> state)
{
return new RequireCommand<UglyApplicationModel>(
(require) => require.Before(s => s.MainWindow.HelloWorldTab.HelloWorld, _automationResolver)
.Before(s => s.MainWindow.HelloWorldTab.HelloWorld.Result, _automationResolver),
() => Debug.Assert(string.Equals(state.Model.MainWindow.HelloWorldTab.HelloWorld.Result.Value, GreetingsForName, System.StringComparison.InvariantCulture)));
}
public ICommand<UglyApplicationModel> AcceptMyChoice(ApplicationState<UglyApplicationModel> state)
{
return new RequireCommand<UglyApplicationModel>(
(require) => require.Before(s => s.MainWindow.HelloWorldTab.HelloWorld.AcceptButton, _automationResolver)
.After(s => s.MainWindow.HelloWorldTab.HelloWorld.Result, _automationPropertyResolver),
() => state.Model.MainWindow.HelloWorldTab.HelloWorld.AcceptButton.Invoke());
}
public ICommand<UglyApplicationModel> EnterName(ApplicationState<UglyApplicationModel> state)
{
return new RequireCommand<UglyApplicationModel>(
(require) => require.Before(s => s.MainWindow.HelloWorldTab.HelloWorld, _automationResolver)
.Before(s => s.MainWindow.HelloWorldTab.HelloWorld.EnteredName, _automationResolver),
() => state.Model.MainWindow.HelloWorldTab.HelloWorld.EnteredName.Value = Name);
}
public ICommand<UglyApplicationModel> HelloWorldModeOpen(ApplicationState<UglyApplicationModel> state)
{
return new RequireCommand<UglyApplicationModel>(
(require) => require.Before(s => s.MainWindow.HelloWorldTab, _automationResolver),
() => state.Model.MainWindow.HelloWorldTab.Select());
}
public ICommand<UglyApplicationModel> NewUglyApplication(ApplicationState<UglyApplicationModel> state)
{
return new SimpleCommand<UglyApplicationModel>(
() =>
{
state.Model = new UglyApplicationModel();
state.Model.ApplicationProcess = ProcessHelper.StartUglyApplication();
});
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/RxExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Helper reactive operators.
/// Imporant assumption: Stream completes
/// </summary>
public static class RxExtensions
{
/// <summary>
/// Chains two observables from their producers
/// </summary>
/// <typeparam name="T">Type of message in observables</typeparam>
/// <param name="previousProducer">Froducer of first observable</param>
/// <param name="nextProducer">Producer of second observable</param>
/// <returns>Chained execution observable</returns>
public static Func<IObservable<T>> ChainFuns<T>(Func<IObservable<T>> previousProducer, Func<IObservable<T>> nextProducer)
{
return () => Observable.Defer(previousProducer).IsEmpty().SelectMany(Observable.Defer(nextProducer));
}
/// <summary>
/// Chains two observables where second is producent
/// </summary>
/// <typeparam name="T">Type of message in observables</typeparam>
/// <param name="previous">First observable</param>
/// <param name="nextProducer">Producer of next observable</param>
/// <returns>Chained execution observable</returns>
public static IObservable<T> Chain<T>(this IObservable<T> previous, Func<IObservable<T>> nextProducer)
{
return previous.IsEmpty().SelectMany(Observable.Defer(nextProducer));
}
/// <summary>
/// Chains given collection of observables
/// </summary>
/// <typeparam name="T">Type of message in observables</typeparam>
/// <param name="observableProducers">Observables to chain</param>
/// <returns>Chained execution observable</returns>
public static IObservable<T> ChainAll<T>(this IEnumerable<IObservable<T>> observables)
{
return observables.Aggregate((currentChain, next) =>
Chain(currentChain, () => next));
}
/// <summary>
/// Chains given collection of observables
/// </summary>
/// <typeparam name="T">Type of message in observables</typeparam>
/// <param name="observableProducers">Factories for observables to chain</param>
/// <returns>Chained execution observable</returns>
public static IObservable<T> ChainAll<T>(this IEnumerable<Func<IObservable<T>>> observableProducers)
{
return observableProducers.Aggregate((currentChain, next) =>
ChainFuns(currentChain, next))();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/AutomationToRxExtensions.cs
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation
{
public static class AutomationToRxExtensions
{
/// <summary>
/// Observable for changes of element properties
/// </summary>
/// <param name="element">Element to observe</param>
/// <param name="properties">Properties to observe</param>
/// <param name="scope">Scope of changes</param>
/// <returns></returns>
public static IObservable<Unit> CreatePropertyChangeStream(this AutomationElement element, AutomationProperty[] properties, TreeScope scope = TreeScope.Element)
{
return Observable.Create<Unit>(
o =>
{
var handler = new AutomationPropertyChangedEventHandler((sender, args) =>
{
o.OnNext(Unit.Default);
});
try
{
Automation.AddAutomationPropertyChangedEventHandler(element, scope, handler, properties);
}
catch (Exception ex)
{
o.OnError(ex);
}
return Disposable.Create(() => Automation.RemoveAutomationPropertyChangedEventHandler(element, handler));
});
}
/// <summary>
/// Observable for changes of element structure
/// </summary>
/// <param name="element">Element to observe</param>
/// <param name="scope">Scope of changes</param>
/// <returns></returns>
public static IObservable<StructureChangeMessage> CreateStructureChangeStream(this AutomationElement element, TreeScope scope = TreeScope.Descendants)
{
return Observable.Create<StructureChangeMessage>(
o =>
{
var handler = new StructureChangedEventHandler((sender, args) =>
o.OnNext(new StructureChangeMessage(sender as AutomationElement, args)));
try
{
Automation.AddStructureChangedEventHandler(element, scope, handler);
}
catch (Exception ex)
{
o.OnError(ex);
}
return Disposable.Create(() => Automation.RemoveStructureChangedEventHandler(element, handler));
});
}
/// <summary>
/// Observable for changes of focus
/// </summary>
/// <returns></returns>
public static IObservable<FocusChangeMessage> CreateFocusChangeStream()
{
return Observable.Create<FocusChangeMessage>(
o =>
{
var handler = new AutomationFocusChangedEventHandler((sender, args) => o.OnNext(new FocusChangeMessage(sender as AutomationElement, args)));
try
{
Automation.AddAutomationFocusChangedEventHandler(handler);
}
catch (Exception ex)
{
o.OnError(ex);
}
return Disposable.Create(() => Automation.RemoveAutomationFocusChangedEventHandler(handler));
});
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/UglyApplicationModel.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Models;
using Consulgo.Test.ReactiveBdd;
using System.Diagnostics;
using Ugly.Yaua.AutomationIds;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation
{
public class UglyApplicationModel : IModel
{
public Process ApplicationProcess { get; set; }
public MainWindowModel MainWindow { get; set; }
public UglyApplicationModel()
{
MainWindow = AutomationControlDescription
.ById(MainWindowIds.MainWindow)
.ChildOf(DesktopWindowControl.NewInstance)
.As<MainWindowModel>();
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/ControlState.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Holds control state of requirements evaluation
/// </summary>
/// <typeparam name="TModel"></typeparam>
public class ControlState<TModel> where TModel : IModel
{
private class CommandsToEvaluate
{
public CommandsToEvaluate(
Func<ApplicationState<TModel>, ICommand<TModel>> command,
CommandType type)
{
Command = command;
CommandType = type;
}
public Func<ApplicationState<TModel>, ICommand<TModel>> Command { get; set; }
public CommandType CommandType { get; set; }
}
private ApplicationState<TModel> _state;
private List<CommandsToEvaluate> commandList = new List<CommandsToEvaluate>();
/// <summary>
/// Constructs the control state
/// </summary>
/// <param name="state">Initial state of the system under test</param>
public ControlState(ApplicationState<TModel> state)
{
_state = state;
}
/// <summary>
/// Comments registration for future processing
/// </summary>
/// <param name="command">Command to be regiesterd for future processing</param>
/// <param name="type">Type of command</param>
/// <returns>this</returns>
public ControlState<TModel> RegisterCommand(Func<ApplicationState<TModel>, ICommand<TModel>> command, CommandType type)
{
commandList.Add(new CommandsToEvaluate(command, type));
return this;
}
/// <summary>
/// Main evaluation of all registered commands
/// TODO test and processes
/// </summary>
/// <returns>Final result of the model</returns>
public IObservable<TModel> Start()
{
return (commandList
.Select(cmdTe => cmdTe.Command)
.Select(cmdFun => cmdFun(_state))
.Select(cmd => cmd.Execute(_state)))
.ChainAll()
.Select(s => _state.Model)
.LastAsync();
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua/SplashScreen.xaml.cs
using System;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;
using System.Windows;
namespace Ugly.Yaua
{
/// <summary>
/// Interaction logic for SplashScreen.xaml
/// </summary>
public partial class SplashScreen : Window
{
private IDisposable _disposable;
private CancellationDisposable _cancellationDisposable;
public SplashScreen()
{
InitializeComponent();
Application.Current.Exit += Current_Exit;
}
private void Current_Exit(object sender, ExitEventArgs e)
{
if (_cancellationDisposable != null)
{
_cancellationDisposable.Dispose();
}
if (_disposable != null)
{
_disposable.Dispose();
}
}
/// <summary>
/// Some code to have random start
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_disposable = NewThreadScheduler.Default.Schedule(() =>
{
_cancellationDisposable = new CancellationDisposable();
var r = new Random(DateTime.Now.Millisecond);
var seconds = r.Next(20);
Dispatcher.BeginInvoke((Action)delegate
{
Counter.Content = string.Format("{0} second(s)", seconds);
});
for (int i = 0; i < seconds; i++)
{
if (!_cancellationDisposable.Token.IsCancellationRequested)
{
Thread.Sleep(1000);
}
}
Dispatcher.BeginInvoke((Action)delegate
{
var mainWindow = new MainWindow();
Close();
mainWindow.Show();
});
});
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/SimpleCommand.cs
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Simple evaluation of the statement
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public class SimpleCommand<TModel> : ICommand<TModel> where TModel : IModel
{
public Action<ApplicationState<TModel>> _action;
/// <summary>
/// Constructs the object
/// </summary>
/// <param name="applicationModel">Application state used in evaluaion</param>
/// <param name="action">Action to be evaluated as a result</param>
public SimpleCommand(Action action)
{
_action = (args) => action();
}
/// <summary>
/// Constructs the object
/// </summary>
/// <param name="applicationModel">Application state used in evaluaion</param>
/// <param name="action">Action to be evaluated as a result</param>
public SimpleCommand(Action<ApplicationState<TModel>> action)
{
_action = action;
}
/// <summary>
/// Does the evaluation of the given action
/// </summary>
/// <param name="args">Reserved</param>
/// <returns>Result stream</returns>
public virtual IObservable<Unit> Execute(ApplicationState<TModel> model)
{
return Observable.Create<Unit>(o =>
{
try
{
_action(model);
o.OnNext(Unit.Default);
o.OnCompleted();
}
catch (Exception ex)
{
o.OnError(ex);
}
return Disposable.Empty;
});
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/ButtonControl.cs
namespace Consulgo.Test.ReactiveAutomation.Controls
{
/// <summary>
/// Button Automation Control
/// </summary>
public class ButtonControl : AutomationControl
{
public void Invoke()
{
InternalInvoke();
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua/App.xaml.cs
using System.Windows;
namespace Ugly.Yaua
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
}
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.Args.Length > 0 && e.Args[0].Equals("--TryError", System.StringComparison.InvariantCulture))
{
MessageBox.Show("This is test error message. Application will abort",
"Error during start", MessageBoxButton.OK, MessageBoxImage.Error);
Shutdown(2);
}
else
{
SplashScreen s = new SplashScreen();
s.Show();
}
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/BaseFeatureTest.cs
using System;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Base class for feature tests
/// </summary>
public class BaseFeatureTest
{
/// <summary>
/// Entry point for every acceptance criteria
/// TODO tests
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
/// <param name="command">Command to be evaluated in given step</param>
/// <returns>Control state of evaluation</returns>
protected ControlState<TModel> Given<TModel>(Func<ApplicationState<TModel>, ICommand<TModel>> command)
where TModel : IModel
{
var newappState = new ApplicationState<TModel>();
var newControlState = new ControlState<TModel>(newappState);
newControlState.RegisterCommand(state => command(state), CommandType.Eval);
return newControlState;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Models/MainWindowModel.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Ugly.Yaua.AutomationIds;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Models
{
public class MainWindowModel : WindowControl
{
public HelloWorldTabModel HelloWorldTab { get; set; }
public MainWindowModel()
{
HelloWorldTab = AutomationControlDescription.ByName(MainWindowIds.HelloWorldTabHeader)
.AsDescendantOf<HelloWorldTabModel>(this);
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/CombinedRxExtensions.cs
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation
{
public static class CombinedRxExtensions
{
/// <summary>
/// Observable for changes of properties in given element
/// </summary>
/// <param name="element">Element to observe changes</param>
/// <param name="properties">Properties to observe</param>
/// <param name="scope">Scope of changes</param>
/// <param name="closeAfter">Flag determines if output stream will be completed after change</param>
/// <returns></returns>
public static IObservable<Unit> WaitForChange(
this AutomationElement element,
AutomationProperty[] properties,
TreeScope scope = TreeScope.Element,
bool closeAfter = true)
{
element.ThrowIfNullArg("element", "Element cannot be null");
properties.ThrowIfNullArg("properties", "Properties cannot be null");
properties.ThrowIfEmpty("properties", "Properties cannot be empty");
return Observable.Create<Unit>(o =>
{
var propertyDisposable = element.CreatePropertyChangeStream(properties, scope)
.Subscribe(u =>
{
o.OnNext(u);
if(closeAfter)
{
o.OnCompleted();
}
},
o.OnError,
o.OnCompleted);
return Disposable.Create(propertyDisposable.Dispose);
});
}
/// <summary>
/// Observable for changes of structre in given element
/// </summary>
/// <param name="parent">Parent element to observe structure</param>
/// <param name="condition">Condition used to limit observed changes</param>
/// <param name="scope">Scope of changes</param>
/// <param name="closeAfter">Flag determines if output stream will be completed after change</param>
/// <returns>Stream of observed new Controls</returns>
public static IObservable<AutomationElement> WaitForFirstElement(
this AutomationElement parent,
Condition condition,
TreeScope scope = TreeScope.Descendants,
bool closeAfter = true)
{
parent.ThrowIfNullArg("parent", "Parent element cannot be null");
condition.ThrowIfNullArg("condition", "Condition cannot be null");
return Observable.Create<AutomationElement>(o =>
{
var structureDisposable = parent.CreateStructureChangeStream(scope)
.Where(msg => VerifyChangesInStructure(msg))
.Subscribe(_ => FindElementAndPush(parent, condition, scope, o, closeAfter));
FindElementAndPush(parent, condition, scope, o, closeAfter);
return Disposable.Create(structureDisposable.Dispose);
});
}
private static bool VerifyChangesInStructure(StructureChangeMessage msg)
{
return (msg.Args.StructureChangeType == StructureChangeType.ChildAdded
|| msg.Args.StructureChangeType == StructureChangeType.ChildrenBulkAdded
|| msg.Args.StructureChangeType == StructureChangeType.ChildrenInvalidated);
}
private static bool FindElementAndPush(AutomationElement parent, Condition condition, TreeScope scope, IObserver<AutomationElement> result, bool completeAfter)
{
var element = parent.FindFirst(scope, condition);
if (element != null)
{
result.OnNext(element);
if (completeAfter)
{
result.OnCompleted();
}
return true;
}
return false;
}
}
}
<file_sep>/Consulgo.Tests/Ugly.Yaua.AutomationIds/MainWindowIds.cs
namespace Ugly.Yaua.AutomationIds
{
/// <summary>
/// Shared Automation Identifiers
/// </summary>
public static class MainWindowIds
{
public static readonly string MainWindow = "UglyMainWindow";
public static readonly string HelloWorldTab = "HelloWorldTab";
public static readonly string HelloWorldTabHeader = "Hello World";
public static readonly string HelloWorldPane = "HelloWorldPane";
public static readonly string HelloWorldName = "HelloWorldName";
public static readonly string HelloWorldButton = "HelloWorldButton";
public static readonly string HelloWorldResult = "HelloWorldResult";
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation/Controls/AutomationControlExtensions.cs
using System.Windows.Automation;
namespace Consulgo.Test.ReactiveAutomation.Controls
{
public static class AutomationControlExtensions
{
/// <summary>
/// Sets given control as child of parent control
/// </summary>
/// <param name="desc">Input description</param>
/// <param name="parentControl">Parent control reference</param>
/// <returns>Input description</returns>
public static AutomationControlDescription ChildOf(this AutomationControlDescription desc, AutomationControl parentControl)
{
SetupValues(desc, parentControl, TreeScope.Children);
return desc;
}
/// <summary>
/// Sets given control as descendant of parent control
/// </summary>
/// <param name="desc">Input description</param>
/// <param name="parentControl">Parent control reference</param>
/// <returns>Input description</returns>
public static AutomationControlDescription AsDescendant(this AutomationControlDescription desc, AutomationControl parentControl)
{
SetupValues(desc, parentControl, TreeScope.Descendants);
return desc;
}
/// <summary>
/// Sets given control as descendant of parent control and creates an instance
/// </summary>
/// <typeparam name="T">Type of control</typeparam>
/// <param name="desc">Input description</param>
/// <param name="parentControl">Parent control reference</param>
/// <returns>Input description</returns>
public static T AsChildOf<T>(this AutomationControlDescription desc, AutomationControl parentControl)
where T : AutomationControl, new()
{
SetupValues(desc, parentControl, TreeScope.Children);
var t = new T();
t.Description = desc;
return t;
}
/// <summary>
/// Sets given control as child of parent control and creates an instance
/// </summary>
/// <typeparam name="T">Type of control</typeparam>
/// <param name="desc">Input description</param>
/// <param name="parentControl">Parent control reference</param>
/// <returns>Input description</returns>
public static T AsDescendantOf<T>(this AutomationControlDescription desc, AutomationControl parentControl)
where T : AutomationControl, new()
{
SetupValues(desc, parentControl, TreeScope.Descendants);
var t = new T();
t.Description = desc;
return t;
}
/// <summary>
/// creates new instance of control based on given description
/// </summary>
/// <typeparam name="T">Type of control</typeparam>
/// <param name="desc">Control description</param>
/// <returns>Control instance</returns>
public static T As<T>(this AutomationControlDescription desc)
where T : AutomationControl, new()
{
var t = new T();
t.Description = desc;
return t;
}
private static void SetupValues(AutomationControlDescription desc, AutomationControl parentControl, TreeScope scope)
{
desc.ParentControl = parentControl;
desc.Scope = scope;
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/IPropertyResolver.cs
using System;
using System.Linq.Expressions;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Evaluates expression with given application state
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public interface IPropertyResolver<TModel>
where TModel : IModel
{
/// <summary>
/// Resolves expression in <see cref="propertyExpression"/>
/// on given <see cref="state"/>
/// </summary>
/// <typeparam name="T">Model of the System Under Test</typeparam>
/// <param name="state">Actual state of model</param>
/// <param name="propertyExpression">Expression to be evaluated</param>
/// <returns>Result stream</returns>
IObservable<ApplicationState<TModel>> Resolve<T>(
ApplicationState<TModel> state,
Expression<Func<TModel, T>> propertyExpression);
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveBdd/RequireCommand.cs
using System;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveBdd
{
/// <summary>
/// Command describing action and pre- and post-requisites
/// </summary>
/// <typeparam name="TModel">Model of the system under test</typeparam>
public class RequireCommand<TModel> : SimpleCommand<TModel> where TModel : IModel
{
private readonly Func<Require<TModel>, Require<TModel>> _requireFunction;
/// <summary>
/// Construct the object
/// </summary>
/// <param name="applicationModel">Application state used in evaluaion</param>
/// <param name="require">Producer of require function</param>
/// <param name="action">Action to be evaluated as a result</param>
public RequireCommand(
Func<Require<TModel>, Require<TModel>> require,
Action action)
: base(action)
{
_requireFunction = require;
}
/// <summary>
/// Constructs the object
/// </summary>
/// <param name="applicationModel">Application state used in evaluaion</param>
/// <param name="require">Producer of require function</param>
/// <param name="action">Action to be evaluated as a result</param>
public RequireCommand(
Func<Require<TModel>, Require<TModel>> require,
Action<ApplicationState<TModel>> action)
: base(action)
{
_requireFunction = require;
}
/// <summary>
/// Evaluates require statements and final command
/// </summary>
/// <param name="args">Model used in evaluation</param>
/// <returns>Result stream</returns>
public override IObservable<Unit> Execute(ApplicationState<TModel> model)
{
var rf =_requireFunction(new Require<TModel>(model));
return rf
.EvaluateOnce()
.Select(_ => Unit.Default)
.Chain(() =>
Observable.When(
rf
.EvaluateAfter()
.Select(_ => Unit.Default)
.And(base.Execute(model))
.Then((u1, u2) => Unit.Default))
);
}
}
}
<file_sep>/Consulgo.Tests/Consulgo.Test.ReactiveAutomation.SampleRunner/UiAutomation/Resolvers/AutomationPropertyResolver.cs
using Consulgo.Test.ReactiveAutomation.Controls;
using Consulgo.Test.ReactiveBdd;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace Consulgo.Test.ReactiveAutomation.SampleRunner.UiAutomation.Resolvers
{
/// <summary>
/// Resolves element that is to be shown on the screen
/// </summary>
public class AutomationPropertyResolver : BaseAutomationResolver
{
protected override IObservable<ApplicationState<UglyApplicationModel>> ResolveImpl<T>(ApplicationState<UglyApplicationModel> state, System.Linq.Expressions.Expression<Func<UglyApplicationModel, T>> propertyExpression)
{
return Observable.Create<ApplicationState<UglyApplicationModel>>(
o =>
{
AutomationControl tc = null;
try
{
var fun = propertyExpression.Compile();
tc = fun(state.Model) as AutomationControl;
return tc.WaitForIt(true).Subscribe(_ =>
{
o.OnNext(state);
}, o.OnError, o.OnCompleted);
}
catch(Exception ex)
{
o.OnError(ex);
return Disposable.Empty;
}
});
}
}
}
| 01ad8f55b4ddf3452d67c987cc2d9cc84bfdbb2a | [
"Markdown",
"C#"
] | 46 | C# | consulgo/Consulgo.Tests | 97fe05e25c424f1e1ce0765226c2ed9e99bd528d | a63334dcf35c3b662b113bacd198d405eb93747c |
refs/heads/master | <file_sep>#define _CRT_NONSTDC_NO_WARNINGS
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;
char key1, key2;
double accurate[1001] = { -1, };
int main(void) {
int turn = 1;
cout << "Hello. This is Stream Test Practice" << "\n";
cout << "You Should checking two key for checking." << "\n";
cout << "First Key : ";
key1 = getch();
cout << key1 <<"\n";
cout << "Second Key : ";
key2 = getch();
cout << key2 << "\n";
while (turn) {
clock_t time1=0, time2=0, start=0, endtime=0;
int count = 0, FirstKey = 1, accurateKey = 0;
double Accaverage = 0;
cout << "Input Key press Num.(20~1000) : ";
cin >> count;
for (int I = 0; I < count; I++) {
accurate[I] = -1;
}
int KeyPressNum = count;
cout << "\n" << "Okey. Setting is ready. if you press key, Timer is start." << "\n";
while (count) {
char c = getch();
if ((c == key1 || c == key2) && FirstKey == 0) {
time2 = clock();
accurate[accurateKey] = time2 - time1;
time1 = time2;
count--;
continue;
}
else if ((c == key1 || c == key2) && FirstKey == 1) {
time1 = clock();
start = time1;
count--;
FirstKey--;
continue;
}
}
endtime = clock();
clock_t result = endtime - start;
double SpendClock = (double)result / (double)CLOCKS_PER_SEC;
double SecondPress = KeyPressNum / SpendClock;
for (int I = 0; I < KeyPressNum; I++) {
Accaverage += accurate[I];
}
Accaverage = Accaverage / KeyPressNum;
cout << "\n\n";
cout << "You spend " << SpendClock << " second" << "\n";
cout << "You press " << SecondPress << " times a second and You can stream beat " << SecondPress*15 <<" bpm!\n";
cout << "Your Press AverageAcc is " << Accaverage << ". (Zero is best)\n";
cout << "Do you want repeat?" << "\n";
cout << "Yes = 1, No = 0 " << "\n";
cin >> turn;
}
return 0;
} | 651c9949c454039f3d1b881fc8b35e29819fe3f2 | [
"C++"
] | 1 | C++ | HyangRim/MyHobby | 9ef5ca12433b2ad8d74392df3be751d20695116b | d9c9858476850062a013219440da65e6d61bdb9e |
refs/heads/master | <file_sep>alias ls="ls --color=auto"
alias lsla="ls -lah --color=auto --group-directories-first"
alias grep="grep --color=auto"
alias mkdir="mkdir -pv"
alias vi="echo Use nvim instead of vi"
alias vim="echo Use nvim instead of vim"
alias dirsize="sudo du -sh"
alias sxiv="sxiv -a"
alias groff="groff -Tpdf -kpms"
alias weather="curl -sf wttr.in | tee ~/.local/share/weatherreport; kill -39 $(pidof dwmblocks)"
alias fullclean="make clean && rm -f config.h && git reset --hard origin/master"
alias screenshot="maim -s | xclip -selection clipboard -t image/png"
alias gitlog="git log --graph --pretty=format:'%Cred%h%Creset %Cgreen(%cd) %C(bold blue)<%an>%Creset %s-%C(yellow)%d%Creset'"
alias iiens="ssh <EMAIL>"
alias reboot="sudo systemctl reboot"
alias poweroff="sudo systemctl poweroff"
alias halt="sudo systemctl halt"
alias lock="pamixer -m; slock; pamixer -u"
function torrentselect(){
webtorrent download "$1" -s -o ~/Downloads
}
function torrentwatch(){
webtorrent download "$1" --mpv -s "${2:-'0'}" -o ~/Downloads
}
alias ts="torrentselect"
alias tw="torrentwatch"
function spleet(){
echo "Entering Conda Spleeter";
conda activate spleeter;
spleeter separate -i "$1" -p "spleeter:${2:-2}stems" -o ~/Documents/spleeter; echo "Leaving Conda Spleeter";
conda deactivate;
}
function jsonlint() {
cat "$1" | python -m json.tool > "$2"
}
function unzd() {
if [[ $# != 1 ]]; then echo I need a single argument, the name of the archive to extract; return 1; fi
target="${1%.zip}"
unzip "$1" -d "${target##*/}"
}
alias matrixpack="matrixpack '' 'matrix-client.matrix.org'"
<file_sep>bindkey "^[[H" beginning-of-line # start of line key
# bindkey "^[[F" end-of-line # end of line key
bindkey '\e[4~' end-of-line
bindkey "^[[1;5D" backward-word # ctrl+left
bindkey "^[[1;5C" forward-word # ctrl+right
bindkey "^[[P" delete-char # del
bindkey "^H" backward-kill-word # ctrl+backspace
bindkey "^[[M" kill-word # ctrl+del
autoload -U history-search-end
zle -N history-beginning-search-backward-end history-search-end
zle -N history-beginning-search-forward-end history-search-end
bindkey "^[[A" history-beginning-search-backward-end # up
bindkey "^[[B" history-beginning-search-forward-end # down
# édite la commande actuelle dans l'éditeur
autoload -z edit-command-line
zle -N edit-command-line
bindkey "^E" edit-command-line # ctrl+e
<file_sep>module.exports = (config, Ferdi) => {
setTimeout( () => {
console.log("Expanding groups...")
document.querySelectorAll(".mx_CustomRoomTagPanel_scroller > .mx_AccessibleButton").forEach( el => el.click() );
}, 10000);
}
<file_sep># Riot for Franz
This is a Franz recipe/plugin for Riot 5
## Installation
1. Download or clone this repo on your computer
2. Open the Franz Plugins folder on your machine:
* Mac: `~/Library/Application Support/Franz/recipes/dev/`
* Windows: `%appdata%/Franz/recipes/dev/`
3. Copy the `recipe-riot` folder into the `dev` directory (if the directory does not exist, create it)
4. Reload Franz
5. Open `Settings` tab and enable Riot in the `development` tab of `Available services`
<file_sep># Localization
export LANG="en_US.UTF-8"
# XDG
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_CACHE_HOME="$HOME/.cache"
export XDG_DATA_HOME="$HOME/.local/share"
# Default programs
export EDITOR="nvim"
export TERMINAL="st"
export READER="zathura"
# Clean-up
export ZDOTDIR="$XDG_CONFIG_HOME/zsh"
# Start DWM
if systemctl -q is-active graphical.target && [[ ! $DISPLAY && $XDG_VTNR -eq 1 ]]; then
exec startx
fi
<file_sep># Adding personal scripts
export PATH="$PATH:/home/user/.local/bin"
# Environment variables
source "$ZDOTDIR/env.zsh"
# Plugins
ZSH_PLUGINS_DIR="$ZDOTDIR/plugins"
source "$ZSH_PLUGINS_DIR/sudo.zsh"
# Key bindings
source "$ZDOTDIR/bindings.zsh"
# Aliases
source "$ZDOTDIR/aliases.zsh"
# Enable colors
autoload -U colors && colors
# Disable ctrl-s ctrl-q for pausing and resuming terminal
stty -ixon
# Theme
source "$ZDOTDIR/themes/main.zsh"
# History
HISTSIZE=10000
SAVEHIST=10000
HISTFILE="$XDG_CACHE_HOME/zsh/history"
# Autocompletion
autoload -U compinit
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ":completion:*" menu select
zmodload zsh/complist
compinit
_comp_options+=(globdots) # include hidden files
# http://zsh.sourceforge.net/Doc/Release/Options.html
setopt auto_list
setopt menu_complete
alias zrefresh="source \"$ZDOTDIR/.zshrc\""
source "/usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
# miniconda
[ -f /opt/miniconda3/etc/profile.d/conda.sh ] && source /opt/miniconda3/etc/profile.d/conda.sh
<file_sep># Prompt style
local arrow="%{%(?:%F{green}:%F{red})%}"
PS1="%{%F{green}%}%B%n@%M%B: %{%F{blue}%}%~
${arrow} %{%F{reset}%}"
<file_sep>#!/bin/bash
# Usage
# matrixpack token homeserver directory...
#
# Pack name is the directory name
# Sticker name is the file name
# /!\ Token is a sensitive information
# Slugify function
slugify () {
echo "$1" | iconv -c -t ascii//TRANSLIT | sed -E 's/[~^]+//g' | sed -E 's/[^a-zA-Z0-9]+/-/g' | sed -E 's/^-+|-+$//g' | tr A-Z a-z
}
# Checking params
if test $# -lt 3 ; then
echo 1>&2 "$0:FATAL: $# invalid argument number (expected 3)"
exit 1
fi
# Checking if ImageMagick is installed
if ! command -v convert &> /dev/null && ! command -v montage &> /dev/null; then
echo "$0:ERROR: magick could not be found"
echo "Usage : ./matrixpack.sh token homerserver directory"
exit
fi
for i in "$@"
do
if [ -d "$i" ]; then
# Changing directory to work directly in it
cd "$i"
# Setting variables
dir=$(pwd)
token=$1
packname=${dir##*/}
slug=$(slugify "$packname")
homeserver=$2
# Printing informations
echo -e "Creating sticker pack \033[94;1m$packname\033[0m\nhomeserver=\033[94m$homeserver\033[0m\noutput=\033[94m$slug\033[0m"
# Making result folder
if ! [ -d $slug ]; then mkdir $slug; fi
if ! [ -d "$slug/tmp" ]; then mkdir "$slug/tmp"; fi
echo -n "{\"title\":\"$packname\",\"id\":\"$slug\",\"stickers\":[" > "$slug/$slug.json"
first=""
for f in *
do
# Ignore folders
if [ -f "$f" ]; then
# Resizing large images
width=$(identify -format "%w" "$f"[0])> /dev/null
height=$(identify -format "%h" "$f"[0])> /dev/null
if [ $width -gt 256 ]; then
width="256";
fi
if [ $height -gt 256 ]; then
height="256";
fi
echo -n "$f : "
type="png"
opts="-type TrueColor PNG32:"
# Gif
if [[ "$f" == *.gif ]]; then
type="gif"
opts=""
fi
# Trim, resize and remove indexed palette from image
echo -n "trimming and resizing"
convert "$f" -bordercolor none -border 1 "$slug/tmp/$f.$type"
echo -n "."
convert "$slug/tmp/$f.$type" -trim +repage "$slug/tmp/$f.$type"
echo -n "."
convert -background none -gravity center "$slug/tmp/$f.$type" -resize "${width}x$height" $opts"$slug/tmp/$f.$type"
echo -ne ". \033[92mdone\033[0m! "
# First item in array
echo -n "$first" >> "$slug/$slug.json"
# Uploading image
echo -n "uploading."
mxc=$(curl -s -X POST -H "Content-Type: image/$type" --data-binary "@$slug/tmp/$f.$type" "https://$homeserver/_matrix/media/r0/upload?access_token=$token" | python3 -c "import sys, json; print(json.load(sys.stdin)['content_uri'])")
echo -n "."
# Calculating 128x128> format
convert "$slug/tmp/$f.$type" -resize "128x128" "$slug/tmp/size"
width=$(identify -format "%w" "$slug/tmp/size"[0])> /dev/null
height=$(identify -format "%h" "$slug/tmp/size"[0])> /dev/null
# Appending to json
echo -n "{\"body\":\"$f\",\"info\":{\"mimetype\":\"image/$type\",\"h\":$height,\"w\":$width,\"thumbnail_url\":\"$mxc\"},\"msgtype\":\"m.sticker\",\"url\":\"$mxc\",\"id\":\"$packname-$f\"}" >> "$slug/$slug.json"
first=","
echo -e ". \033[92msuccess\033[0m!"
fi
done
rm "$slug/tmp/size"
montage "$slug/tmp/*"[0] -background none "$slug/preview.png"
rm -r "$slug/tmp"
echo -ne "# $packname \n" > "$slug/README.md"
echo -n "]}" >> "$slug/$slug.json"
cd - > /dev/null
echo -e "\033[92;1mPack successfully created!\n\033[0mCheck \033[94;1m$dir/$slug \033[0mfor output"
fi
done
<file_sep>#!/bin/bash
output=$(dbus-send --reply-timeout=1000 --print-reply --dest=org.mpris.MediaPlayer2.spotifyd /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:"org.mpris.MediaPlayer2.Player" string:'Metadata' \
| grep -Ev "^method" \
| grep -Eo '("(.*)")|(\b[0-9][a-zA-Z0-9.]*\b)' \
| sed -E '2~2 a|' \
| tr -d '\n' \
| sed -E 's/\|/\n/g' \
| sed -E 's/(xesam:)|(mpris:)//' \
| sed -E 's/^"//' \
| sed -E 's/"$//' \
| sed -E 's/"+/|/' \
| sed -E 's/ +/ /g' \
| grep --color=never -E "(title)|(albumArtist)|(length)" \
| sed 's/albumArtist/1/;s/title/2/;s/length/3/' \
| sort \
| sed 's/[0-9]|//')
if ! [ -z "$output" ]; then
duration=$(date -d@$(bc -l <<< "scale=2;$(echo "$output" | sed 3'!d')/1000000") -u +%M:%S)
artist=$(echo "$output" | sed 1'!d')
track=$(echo "$output" | sed 2'!d')
trim="$artist - $track"
if [ $(echo "$trim" | wc -c) -gt 32 ]; then
trim="$(echo "$trim" | cut -c 1-32)…"
fi
echo "$trim $duration"
else echo "Failed" 1>&2
fi
<file_sep>export LESSHISTFILE=-
export FREETYPE_PROPERTIES="truetype:interpreter-version=40" # for fonts
| 1fb2e27f8995f9f4576ead970331fe419875f79c | [
"JavaScript",
"Markdown",
"Shell"
] | 10 | Shell | Tigriz/dotfiles | 1674123bdf15342f57a957843c2629419625af34 | 055437fdaaaf3850f6c083821fb67ca75e62e326 |
refs/heads/master | <file_sep>struct node *reverse (struct node *head, int k)
{
node*curr=head,*prev=NULL,*nextNode=NULL;
int count=k;
while(curr && count--)
{
nextNode=curr->next;
curr->next=prev;
prev=curr;
curr=nextNode;
}
if(curr)
{
head->next=reverse(curr,k);
}
return prev;
}
<file_sep>Node* rev(Node**head)
{
Node*curr=*head,*prev=NULL,*nextNode=NULL;
while(curr)
{
nextNode=curr->next;
curr->next=prev;
prev=curr;
curr=nextNode;
}
return prev;
}
bool compare(Node*head1,Node*head2)
{
Node*temp1=head1,*temp2=head2;
while(temp1&& temp2)
{
if(temp1->data!=temp2->data)
{
return false;
}
temp1=temp1->next;
temp2=temp2->next;
}
return true;
}
bool isPalindrome(Node *head)
{
if(head && head->next)
{
Node*slow=head,*fast=head;
Node*head2=NULL;
Node*slow_prev=NULL;
while(fast && fast->next)
{
slow_prev=slow;
slow=slow->next;
fast=fast->next->next;
}
if(fast!=NULL)
{
slow=slow->next;
}
head2=rev(&slow);
return compare(head,head2);
}
return true;
}
<file_sep>Node *removeDuplicates(Node *root)
{
Node*curr=root;
while(curr && curr->next)
{
if(curr->data==curr->next->data)
{
Node*temp=curr->next;
curr->next=temp->next;
free(temp);
}
else
{
curr=curr->next;
}
}
return root;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
void selectionSort(int arr[], int n)
{
int min_index;
for(int i=0;i<n-1;i++)
{
min_index=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
{
min_index= j;
}
}
swap(&arr[i],&arr[min_index]);
}
}
void print(int arr[], int n)
{
for (int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
int arr[n];
for (int i=0;i<n;i++)
{
cin>>arr[i];
}
// print(arr, n);
selectionSort(arr, n);
print(arr, n);
}
<file_sep>struct Node* reverseList(struct Node *head)
{
Node * curr=head,*nextnode=NULL,*prev=NULL;
while(curr)
{
nextnode=curr->next;
curr->next=prev;
prev=curr;
curr=nextnode;
}
return prev;
}
<file_sep>Node * removeDuplicates( Node *head)
{
Node*temp=head;
set<int>s;
s.insert(temp->data);
while(temp->next)
{
if(s.find(temp->next->data)!=s.end())
{
temp->next=temp->next->next;
}
else
{
temp=temp->next;
s.insert(temp->data);
}
}
return head;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int binarySearch(int arr[],int l,int r,int ele)
{
while(l<=r)
{
int mid=(l+r)/2;
if(arr[mid]==ele)
{
return 1;
}
else if(arr[mid]>ele)
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return 0;
}
int main()
{
int n;
cout<<"enter the size of the array:";
cin>>n;
int arr[n];
cout<<"enter array ele:";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int ele;
cout<<"enter ele you want to find:";
cin>>ele;
if(binarySearch(arr,0,n-1,ele))
{
cout<<"ele found";
}
else
{
cout<<"ele not found";
}
}
<file_sep>int length(Node*slow)
{
Node*temp=slow;
int len=1;
while(temp->next!=slow){
len++;
temp=temp->next;
}
return len;
}
int countNodesinLoop(struct Node *head)
{
Node*slow=head,*fast=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
return length(slow);
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node*next;
};
node *insert(node**head,int x)
{
node*newNode=(struct node*)malloc(sizeof(node));
newNode->data=x;
newNode->next=NULL;
if(*head==NULL)
{
*head=newNode;
return *head;
}
else
{
node*temp=*head;
while(temp->next)
{
temp=temp->next;
}
temp->next=newNode;
}
return *head;
}
void printList(node**head)
{
node*temp=*head;
while(temp)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n];
node*even=NULL,*odd=NULL;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
if(x%2==0)
{
even=insert(&even,x);
}
else
{
odd=insert(&odd,x);
}
}
if(even==NULL)
{
printList(&odd);
}
else
{
node*temp=even;
while(temp->next)
{
temp=temp->next;
}
temp->next=odd;
printList(&even);
}
}
}<file_sep>#include<bits/stdc++.h>
using namespace std;
bool linearSearch(int arr[],int n,int ele){
for(int i=0;i<n;i++)
{
if(arr[i]==ele)
{
return true;
}
}
return false;
}
int main()
{
int arr[5];
cout<<"enter array elements:";
for(int i=0;i<5;i++)
{
cin>>arr[i];
}
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"enter element to found:";
int ele;
cin>>ele;
if(linearSearch(arr,n,ele))
{
cout<<"Element found";
}
else
{
cout<<"element not found";
}
}
<file_sep>Node*insert(Node**head,int x)
{
Node*newnode=(Node*)malloc(sizeof(Node));
Node*temp=*head;
newnode->data=x;
newnode->next=NULL;
if(*head==NULL)
{
*head=newnode;
return *head;
}
else
{
while(temp->next)
{
temp=temp->next;
}
temp->next=newnode;
}
return *head;
}
Node* findIntersection(Node* head1, Node* head2)
{
Node*temp1=head1,*temp2=head2;
Node*head3=NULL;
while(temp1 && temp2)
{
if(temp1->data==temp2->data)
{
head3=insert(&head3,temp1->data);
temp1=temp1->next;
temp2=temp2->next;
}
else if(temp1->data>temp2->data)
{
temp2=temp2->next;
}
else
{
temp1=temp1->next;
}
}
return head3;
}<file_sep>int intersectPoint(Node* head1, Node* head2)
{
unordered_set<Node*>s;
Node*temp=head1;
while(temp)
{
s.insert(temp);
temp=temp->next;
}
temp=head2;
while(temp)
{
if(s.find(temp)!=s.end())
{
return temp->data;
}
temp=temp->next;
}
return -1;
}
| e8c8102bf41c8e36c75d4e06203883487701ee80 | [
"C++"
] | 12 | C++ | ranarupesh123/Data-Structures | 2dbadc13cbddb951c7a7227abc1ed025f0963dcc | fabbc535bc504b1f88a71c830fff3d1456e47f1a |
refs/heads/master | <file_sep>package com.albertsons.app.ps01.domain.enums;
public enum CorpEnum {
DEFAULT_CORP("001");
private String corpId;
private CorpEnum (final String corpId) {
this.corpId = corpId;
}
public String getCorpId() {
return this.corpId;
}
}<file_sep>package com.albertsons.app.ps01.security.userdetails;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import lombok.Data;
import lombok.NonNull;
@Data
public class User implements Authentication {
private static final String EMAIL_DOMAIN = "@safeway.com";
/**
*
*/
private static final long serialVersionUID = 7358339418644588868L;
public User() {
}
public User(String username, String division, String group) {
this.username = username;
this.email = username + EMAIL_DOMAIN;
this.division = division;
if (username == null || "".equals(username) || division == null || "".equals(division)) {
this.role = RoleType.USER_ANONYMOUS;
} else {
this.role = RoleType.getRoleType(group);
}
}
@NonNull
private String username;
@NonNull
private String email;
@NonNull
private String division;
@NonNull
private RoleType role;
@Override
public String getName() {
return username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return RoleType.getGrantedAuthorities(Arrays.asList(role));
}
/**
* @return {@link User}
*/
@Override
public Object getCredentials() {
return this;
}
/**
* @return the user's email address
*/
@Override
public Object getDetails() {
return this.email;
}
/**
* @return {@link User}
*/
@Override
public Object getPrincipal() {
return this;
}
@Override
public boolean isAuthenticated() {
return isUserValid();
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
public Boolean isUserValid() {
if (username == null || "".equals(username) || division == null || "".equals(division)
|| RoleType.USER_ANONYMOUS == role) {
return false;
}
return true;
}
}<file_sep><?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.albertsons.app</groupId>
<artifactId>ps01-web-sprboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>PS01</name>
<description>Host POS Temporary Cycle Change Automation</description>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>9.0.27</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<archive>
<manifest>
<addDefaultImplementationEntries>false</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
<!-- <resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources> -->
</build>
<profiles>
<profile>
<id>local</id>
<properties>
<activatedProperties>local</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>qa</id>
<properties>
<activatedProperties>qa</activatedProperties>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<activatedProperties>prod</activatedProperties>
</properties>
</profile>
</profiles>
</project><file_sep>package com.albertsons.app.ps01.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.albertsons.app.ps01.controller.resource.CycleChangeRequestDTO;
import com.albertsons.app.ps01.repository.CycleChangeRequestRepository;
public class CycleChangeRequestValidator
implements ConstraintValidator<CycleChangeRequestConstraint, CycleChangeRequestDTO> {
private CycleChangeRequestRepository repository;
public CycleChangeRequestValidator(CycleChangeRequestRepository repository) {
this.repository = repository;
}
@Override
public void initialize(CycleChangeRequestConstraint constraintAnnotation) {
}
@Override
public boolean isValid(final CycleChangeRequestDTO cycleChangeDTO, ConstraintValidatorContext context) {
try {
Validator offsiteValidator = new CycleChangeOffsiteValidator(repository);
Validator sequenceValidator = new CycleChangeRunSequenceValidator(repository, offsiteValidator);
Validator effDateValidator = new CycleChangeEffectiveDateValidator(repository, sequenceValidator);
Validator runDateValidator = new CycleChangeRunDateValidator(repository, effDateValidator);
return runDateValidator.isValid(cycleChangeDTO);
} catch (Exception e) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
return false;
}
}
}<file_sep>package com.albertsons.app.ps01.security.userdetails;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
public enum RoleType {
USER_ANONYMOUS("Anonymous user.", "ROLE_ANONYMOUS"), USER_RIM("ps01.user.rim", "ROLE_RIM"),
USER_ADMIN("ps01.user.admin", "ROLE_ADMIN");
private String memberOf;
private String role;
private RoleType(String memberOf, String role) {
this.memberOf = memberOf;
this.role = role;
}
public String getMemberOf() {
return this.memberOf;
}
public void setMemberOf(String memberOf) {
this.memberOf = memberOf;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public static RoleType getDefaultRoleType() {
return RoleType.USER_ANONYMOUS;
}
public static RoleType getRoleType(String memberOf) {
RoleType roleType = getDefaultRoleType();
for (RoleType role : RoleType.values()) {
if (role.getMemberOf().equals(memberOf)) {
roleType = role;
}
}
return roleType;
}
public static List<SimpleGrantedAuthority> getGrantedAuthorities() {
return Arrays.asList(new SimpleGrantedAuthority(RoleType.USER_ADMIN.getRole()),
new SimpleGrantedAuthority(RoleType.USER_RIM.getRole()));
// new SimpleGrantedAuthority(RoleType.USER_ANONYMOUS.getRole()));
}
public static List<SimpleGrantedAuthority> getGrantedAuthorities(String... groups) {
return Arrays.asList(groups).stream().map(group -> {
return new SimpleGrantedAuthority(RoleType.getRoleType(group).getRole());
}).collect(Collectors.toList());
}
public static List<SimpleGrantedAuthority> getGrantedAuthorities(List<RoleType> groups) {
return groups.stream().map(group -> {
return new SimpleGrantedAuthority(group.getRole());
}).collect(Collectors.toList());
}
}<file_sep>package com.albertsons.app.ps01.domain;
import java.sql.Date;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import com.albertsons.app.ps01.validation.ChronologicalOrderDateConstraint;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
/**
*
*/
@Data
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
@ChronologicalOrderDateConstraint.List({
@ChronologicalOrderDateConstraint(startDate = "runDate", endDate = "effectiveDate", message = "Effective date should be later than run date.") })
@Entity
@Table(name = "PSCYCREQ_TABLE")
public class CycleChangeRequest {
@NonNull
@Id
@GeneratedValue
@Column(name = "CYC_REQ_CHG_SK")
private Long id;
@NonNull
@Column(name = "CORP_ID")
private String corpId;
@NonNull
@NotNull(message = "Division ID is required.")
@NotBlank(message = "Division ID is required.")
@Column(name = "DIV_ID")
private String divId;
@NonNull
@Column(name = "RUN_DT")
private Date runDate;
@NonNull
@Column(name = "EFF_DT")
private Date effectiveDate;
@NonNull
@Column(name = "CRT_TS")
@CreatedDate
private Timestamp createTimestamp;
@NonNull
@Column(name = "RUN_NBR")
private Integer runNumber;
@NonNull
@Column(name = "RUN_DY")
private String runDayName;
@NonNull
@Column(name = "EFF_DY")
private String effectiveDayName;
@NonNull
@Column(name = "CYC_CHG_REQ_TYP_NM")
private String cycleChangeRequestType;
@NonNull
@NotBlank(message = "Offsite indicator is required. Accepted values are 0 and 1 only.")
@NotNull(message = "Offsite indicator is required. Accepted values are 0 and 1 only.")
@Column(name = "OFFSITE_IND")
private String offsiteIndicator;
@NonNull
@Column(name = "CHG_STAT_NM")
private String changeStatusName;
@NonNull
@Column(name = "CHG_TS")
private Timestamp changeTimestamp;
@NonNull
@Column(name = "CMMT_TXT")
private String comment;
@NonNull
@Column(name = "CRT_USR_ID")
@CreatedBy
private String createUserId;
@NonNull
@Column(name = "LST_UPD_USR_ID")
@LastModifiedBy
private String lastUpdatedUserId;
@NonNull
@Column(name = "LST_UPD_TS")
@LastModifiedDate
private Timestamp lastUpdateTs;
@NonNull
@Column(name = "EXPIRY_TS")
private Timestamp expiryTimestamp;
} | e6f96253ec5aceffdee2ac90f84ab5f4f776005b | [
"Java",
"Maven POM"
] | 6 | Java | rsapl00/ps01 | 3e971628903043f237e733af3970c50eca20e225 | 4471168f60f6b7153cefc31605fe55ea8b3dfd92 |
refs/heads/master | <repo_name>tpodkowski/BD2-Projekt-Klient<file_sep>/src/components/EditModal.js
import React from 'react';
import Modal from 'react-modal';
const EditModal = ({
reference,
clientList,
isOpen,
onSubmit,
onClose,
}) => console.log({ clientList }) || (
<Modal
isOpen={isOpen}
contentLabel="Minimal Modal Example"
className="add-modal shadow"
>
<h2>Edytuj element</h2>
<form ref={reference} onSubmit={onSubmit}>
{ clientList && Object.entries(clientList).map(([list, value], index) => index > 0 ? (
<div className="form-group" key={index}>
<label htmlFor={`${list}-input`}>{list}</label>
<input
type="text"
className="form-control"
name={list}
id={`${list}-input`}
placeholder={value}
/>
</div>
) : null)}
<div className="row">
<button
type="button"
className="btn btn-link"
onClick={onClose}
>Anuluj</button>
<button
type="submit"
className="btn btn-primary"
>Edytuj</button>
</div>
</form>
</Modal>
);
export default EditModal;<file_sep>/src/components/Table.js
import React from 'react';
const Table = ({
list = [],
handleDelete = () => {},
handleEdit = () => {},
}) => list.length > 0 ? (
<table className="table table-bordered table-striped">
<thead>
<tr>
{Object.keys(list[0]).map((key, index) => (
<th key={index} style={!index ? { width: '50px' } : {}}>
{ key }
</th>
))}
<th style={{ width: '150px' }}>Actions</th>
</tr>
</thead>
<tbody>
{list.map(row => (
<tr key={row.id}>
{Object.values(row).map((cell, index) => (
<td key={index}>
{ cell }
</td>
))}
<td className="d-flex justify-content-between">
<button
className="btn btn-sm btn-danger"
onClick={() => handleDelete(row.id)}>Delete</button>
<button
className="btn btn-sm btn-secondary"
onClick={() => handleEdit(row.id)}>Edit</button>
</td>
</tr>
))}
</tbody>
</table>
) : (
<div className="d-flex justify-content-center">
<div className="card text-center text-white bg-danger mb-3">
<div class="card-body">
<h3>Brak rekordów</h3>
</div>
</div>
</div>
);
export default Table;
<file_sep>/src/const/Tables.js
export default {
CATEGORIES: 'kategorie',
CLIENTS: 'klienci',
STORE: 'magazyn',
PRODUCTS: 'produkty',
ORDERS: 'zamowienia',
ORDER_DETAILS: 'szczegolyzamowienia',
}<file_sep>/src/App.js
import React, { Component, Fragment } from 'react';
import axios from 'axios';
import Modal from 'react-modal';
import serialize from 'form-serialize';
import Navbar from './components/Navbar';
import Table from './components/Table';
import EditModal from './components/EditModal';
import TABLES from './const/Tables';
import './App.css';
const BASE_URL = 'http://localhost:3000/api/';
class App extends Component {
constructor(props) {
super(props);
this.state = {
clientList: [],
activeTable: TABLES.CATEGORIES,
isAddModalOpen: false,
isEditModalOpen: false,
editedId: null,
}
this.addElementFormRef = React.createRef();
this.editElementFormRef = React.createRef();
this.handleDelete = this.handleDelete.bind(this);
this.handleTableChange = this.handleTableChange.bind(this);
this.openAddModal = this.openAddModal.bind(this);
this.closeModals = this.closeModals.bind(this);
this.handleElementAdd = this.handleElementAdd.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleElementEdit = this.handleElementEdit.bind(this);
}
componentDidMount() {
this.fetchClients();
}
fetchClients() {
const { activeTable } = this.state;
axios.get(`${BASE_URL}${activeTable}`)
.then(({ data }) => this.setState({ clientList: data }))
}
handleDelete(clientId) {
const { activeTable } = this.state;
axios.delete(`${BASE_URL}${activeTable}/${clientId}`)
.then(({ data }) => this.setState({ clientList: data}));
}
handleEdit(id) {
this.setState({
editedId: id,
isEditModalOpen: true,
});
}
handleTableChange({ target }) {
const activeTable = target.value;
this.setState({ activeTable }, this.fetchClients);
}
closeModals() {
this.setState({
isAddModalOpen: false,
isEditModalOpen: false,
});
}
openAddModal() {
this.setState({ isAddModalOpen: true });
}
handleElementAdd(event) {
event.preventDefault();
const { activeTable } = this.state;
const formData = serialize(this.addElementFormRef.current, { hash: true });
axios.post(`${BASE_URL}${activeTable}`, formData)
.then(({ data }) => this.setState({ clientList: data}, this.closeModals()));
}
handleElementEdit(event) {
event.preventDefault();
const { activeTable, editedId } = this.state;
const formData = serialize(this.editElementFormRef.current, { hash: true });
axios.patch(`${BASE_URL}${activeTable}/${editedId}`, formData)
.then(({ data }) => this.setState({
clientList: data,
editedId: null,
}, this.closeModals()));
}
render() {
const {
clientList
} = this.state;
return (
<Fragment>
<Navbar
handleAdd={this.openAddModal}
activeTable={this.state.activeTable}
handleTableChange={this.handleTableChange}
/>
<div style={{ paddingTop: '54px' }}>
<Table
list={clientList}
handleDelete={this.handleDelete}
handleEdit={this.handleEdit}
/>
<Modal
isOpen={this.state.isAddModalOpen}
contentLabel="Minimal Modal Example"
className="add-modal shadow"
>
<h2>Dodaj element</h2>
<form ref={this.addElementFormRef} onSubmit={this.handleElementAdd}>
{ clientList[0] && Object.keys(clientList[0]).map((list, index) => index > 0 ? (
<div className="form-group" key={index}>
<label htmlFor={`${list}-input`}>{list}</label>
<input
type="text"
className="form-control"
name={list}
id={`${list}-input`}
/>
</div>
) : null)}
<div className="row">
<button
type="button"
className="btn btn-link"
onClick={this.closeModals}
>Anuluj</button>
<button
type="submit"
className="btn btn-primary"
>Dodaj</button>
</div>
</form>
</Modal>
<EditModal
clientList={clientList.find(({ id }) => id === this.state.editedId)}
isOpen={this.state.isEditModalOpen}
onClose={this.closeModals}
onSubmit={this.handleElementEdit}
reference={this.editElementFormRef}
/>
</div>
</Fragment>
);
}
}
export default App;
| 541693fc12404694a2c3bcaf5bd640cc74c98602 | [
"JavaScript"
] | 4 | JavaScript | tpodkowski/BD2-Projekt-Klient | 16da68e527e693daf7cf02bfc5251061a9b3e23b | 944b7b030e4b974f39e50e4a673427f9928a54b4 |
refs/heads/master | <file_sep>import { useFetchGif } from "../../hooks/useFetchGif"
import { renderHook } from '@testing-library/react-hooks'
describe('Test on hook useFetchGifs', () => {
const category = 'One Punch'
test('should return the initial state', async () => {
const { result, waitForNextUpdate } = renderHook(() => useFetchGif(category));
const { data, loading } = result.current
await waitForNextUpdate();
expect(data).toEqual([])
expect(loading).toBe(true)
})
test('should return an images array and loading false', async () => {
const { result, waitForNextUpdate } = renderHook(() => useFetchGif(category));
await waitForNextUpdate();
const { data, loading } = result.current
expect(data.length).toBe(10)
expect(loading).toBe(false)
})
})
| 1cb6b657082185fbfade0c2bdadf1531ed1a2502 | [
"JavaScript"
] | 1 | JavaScript | santiagopegels/gif-example-app | f607cfef94b1ef05dcbd85de194d17cae447085b | b3ec55b5f614592afbb6d5724dd7a22cd13df079 |
refs/heads/master | <repo_name>DOKVADZETAKO/js-practices<file_sep>/02-Control-Flow-Loops/task-12.js
let arr = [2, 5, 9, 15, 0, 4];
let i;
for(i of arr){
if (i > 3 && i < 10){
console.log(i);
i++
}
}
<file_sep>/05-Arrays/task-10.js
const reverse = function(arr){
if(!(Array.isArray(arr))){
throw new Error ('First parameter required and has to be only array');
}
if(!arr.length){
throw new Error ('empty array');
}
let eachValue = [];
arr.forEach(function(item){
eachValue.unshift(item)
})
return eachValue;
}
const arr = [3,2,1];
const check = reverse(arr);
console.log(check);<file_sep>/05-Arrays/task-3.js
const every = function(arr, cb){
if(!(Array.isArray(arr))){
throw new Error ('First parameter required and has to be only array');
}
if(!(typeof cb === 'function')){
throw new Error ('Second parameter required and has to be only function');
}
let eachValue = false;
for(let count = 0; count < arr.length; count++){
eachValue = cb(arr[count], count , arr);
if(!eachValue){
break;
}
}
return eachValue;
}
const arr = [1,2,3];
const check = every(arr, function(item, i, arr) {
return item > 1;
});
console.log(check);
<file_sep>/03-Functions-Part-1/task-6.js
let a = 3;
console.log(isEven (a));
function isEven (a){
if(typeof a != 'number'){
throw new Error('parameter type is not a Number');
}
return a % 2 == 0;
}
<file_sep>/07-Getting-in-touch-with-strings/task-1.js
let str = 'pitter';
function upperCaseFirst(str) {
if (typeof str != 'string') {
throw new Error('parameter isn\'t string')
} else {
let fitstlatter = str.charAt(0);
fitstlatter = fitstlatter.toUpperCase();
let other = str.substring(1);
let result = fitstlatter + other;
return result;
}
}
console.log(upperCaseFirst('pitter'));
<file_sep>/08-Getting-in-touch-with-objects/task-1.js
const person = {
salary: 1000
}
Object.defineProperty(person, 'salary', {
get(){
let today = new Date();
let month = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
if (today.getDate() < (month - 20)) {
return 'Good salary';
} else {
return 'Bad salary';
}
},
});
console.log(person.salary)
<file_sep>/03-Functions-Part-1/task-4.js
function f(a){
if(typeof a == 'number'){
if (a == 1){
return 'Sunday'
} else if (a == 2){
return 'Monday'
}
else if (a == 3){
return 'Tuesday'
}
else if (a == 4){
return 'Wednesday'
}
else if (a == 5){
return 'Thursday'
}
else if (a == 6){
return 'Friday'
}
else if (a == 7){
return 'Saturday'
}else {
throw new Error('parameter should be in the range of 1 to 7');
}
}else {
throw new Error('all parameters type should be a Number');
}
}
console.log(f(1));<file_sep>/02-Control-Flow-Loops/task-2.js
let login = "";
const res = (login == 'Pitter') ? 'Hi' : (login == 'Owner') ? 'Hello' : (login == '') ? 'unknown' : '';
console.log(res);<file_sep>/08-Getting-in-touch-with-objects/task-2.js
const person = {
salary: null,
rate: null,
}
Object.defineProperties(person, {
rate: {
value: 0,
writable: true,
configurable: false,
enumerable: false,
},
salary: {
get(){
const date = new Date();
const day = date.getDate();
return day * this.rate;
},
set(){
throw new Error('can\'t use')
}
}
});
person.rate = 30
console.log(person.salary);<file_sep>/02-Control-Flow-Loops/task-11.js
let arr = [6, 5, 8, 11, 10];
let j;
for (num of arr){
for( j = 0; j < arr.length; j++){
if(arr[j] > arr [j+1]){
temp = arr[j]
arr[j] = arr [j+1];
arr[j+1] = temp;
}
}
}
console.log(arr);
<file_sep>/03-Functions-Part-1/task-2.js
function f(){
let asd = 0;
for(each of arguments){
if(typeof each == 'number'){
asd = asd + each;
}else{
throw new Error('all parameters type should be a Number');
}
}
return asd
}
console.log(f(1,2,3));
<file_sep>/02-Control-Flow-Loops/task-7.js
let arr = [1,2,3,4];
let a = 0;
for (i of arr){
if(i % 2 == 0){
a = a + i
}
}
console.log(a);
<file_sep>/05-Arrays/task-5.js
const reduce = function(arr, cb, acc){
if(!(Array.isArray(arr))){
throw new Error ('First parameter required and has to be only array');
}
if(!(typeof cb === 'function')){
throw new Error ('Second parameter required and has to be only function');
}
if(!(typeof acc === 'number' || typeof acc === 'string' )){
throw new Error ('Third parameter required and has to be only string or number');
}
let eachValue = acc;
for(let count = 0; count < arr.length; count++){
eachValue = cb(eachValue, arr[count], count , arr);
}
return eachValue;
}
const arr = [1,2,3];
const acc = 0;
const check = reduce(arr, function(acc, item, i, arr) {
return item + acc;
}, acc);
console.log(check);<file_sep>/07-Getting-in-touch-with-strings/task-2.js
const checkSpam = function(source, example) {
if (typeof source != 'string' && typeof example != 'string' ) {
throw new Error('parameter isn\'t string')
} else{
let lowercaseOne = source.toLowerCase();
let lowercaseTwo = example.toLowerCase();
let result = lowercaseOne.indexOf(lowercaseTwo);
if(result == 1){
return true;
}else{
return false;
}
}
}
console.log(checkSpam('asdadasd', 'asdasd'))
<file_sep>/12-Introducing-JavaScript-Classes/task-4.js
class MyString {
constructor() {
}
reverse(reverseStr) {
let nStr = "";
for (var i = reverseStr.length - 1; i >= 0; i--) {
nStr += reverseStr[i];
}
return nStr;
}
ucFirst(capStr) {
let without = capStr.substring(1);
let first = capStr.charAt(0).toUpperCase();
return first + without;
}
ucWords(words){
let word = words.split(" ")
for(let i = 0; i < word.length; i++){
word[i] = this.ucFirst(word[i])
}
return word.join(" ")
}
}
const str = new MyString();
console.log(str.reverse('abcde')); // print 'edcba'
console.log(str.ucFirst('abcde')); // print 'Abcde'
console.log(str.ucWords('abCde abcde abcde')); // print 'Abcde Abcde Abcde'<file_sep>/05-Arrays/task-6.js
const reduceRight = function(arr, cb, acc){
if(!(Array.isArray(arr))){
throw new Error ('First parameter required and has to be only array');
}
if(!(typeof cb === 'function')){
throw new Error ('Second parameter required and has to be only function');
}
if(!(typeof acc === 'number' || typeof acc === 'string' )){
throw new Error ('Third parameter required and has to be only string or number');
}
let eachValue = acc;
for (let i = arr.length - 1; i >= 0; i--){
eachValue = cb(eachValue, arr[i], i , arr);
}
return eachValue;
}
const arr = [1,2,3];
const acc = 0;
const check = reduceRight(arr, function(acc, item, i, arr) {
return item + acc;
}, acc);
console.log(check);
<file_sep>/02-Control-Flow-Loops/task-13.js
let arr = [3, 5, -8, 5, -10];
let a = 0;
for (i of arr){
if(i > 0){
a = a + i
}
i++
}
console.log(a)
<file_sep>/02-Control-Flow-Loops/task-15.js
let n = 1000;
let num = 0;
while( n / 2 > 50 ){
n = n/2;
num=num+1;
}
console.log(num);
<file_sep>/05-Arrays/task-9.js
const arrayFill = function(afs, cb){
if(!((typeof afs === 'number') || (typeof afs === 'string') ||(typeof afs === 'array'))){
throw new Error ('First parameter required and has to be only number, string, object array');
}
if(!(typeof cb === 'number')){
throw new Error ('Second parameter required and has to be only number');
}
let eachValue = [];
for(let count = 0; count < cb; count++){
eachValue.push(afs);
}
return eachValue;
}
const check = arrayFill('x',5);
console.log(check);
<file_sep>/07-Getting-in-touch-with-strings/task-3.js
const truncate = function (string, maxlength) {
if (typeof string == 'string' && typeof maxlength == 'number') {
let a = string.length
if (a > maxlength) {
let n = a - maxlength
let another = string.substring(0, maxlength-3) + "...";
return another
}
} else {
throw new Error("parameter isn'\t string")
}
}
console.log(truncate("I wanna to say next thing about this topic", 22))
<file_sep>/02-Control-Flow-Loops/task-1.js
const a = 5;
const b = 6;
const result = (a + b < 4) ? true : false;
console.log(result);
<file_sep>/05-Arrays/task-2.js
const filter = function(arr, cb){
if(!(Array.isArray(arr))){
throw new Error ('First parameter required and has to be only array');
}
if(!(typeof cb === 'function')){
throw new Error ('Second parameter required and has to be only function');
}
let filtered = [];
for(let count = 0; count < arr.length; count++){
const old = arr[count];
const xd = cb(old, count , arr);
if(xd){
filtered.push(old);
}
}
return filtered;
}
const arr = [1,2,3];
const filtered = filter(arr, function(item, i, arr) {
return item > 1;
});
console.log(filtered); | 3d4907628ae2626bd9f5b7fee97f68902c0fe318 | [
"JavaScript"
] | 22 | JavaScript | DOKVADZETAKO/js-practices | 77e0a9769a08244175315ed587ed470b5d966825 | 460001acc535db55b65fe8813ceb86d710bb0d5f |
refs/heads/main | <file_sep>import React, { useState } from 'react';
import { validateEmail } from '../utils/validateEmail'
const titleStyle = {
backgroundColor: 'red',
padding: '20px'
}
const linkStyle = {
color: 'red',
}
const padding = {
padding: '10px'
}
const errorStyle = {
backgroundColor: 'black',
color: 'red'
}
function Contact() {
const [formState, setFormState] = useState({ name: '', email: '', message: '' })
const [errorMessage, setErrorMessage] = useState('')
const { name, email, message } = formState;
function handleChange(e) {
if (e.target.name === 'email') {
const validate = validateEmail(e.target.value);
if (!validate) {
setErrorMessage('Please enter a valid email.');
} else {
setErrorMessage('')
}
} else if (!e.target.value.length) {
setErrorMessage(`${e.target.name} is required.`)
} else setErrorMessage();
if (!errorMessage) {
setFormState({ ...formState, [e.target.name]: e.target.value })
}
}
function handleSubmit(e) {
e.preventDefault();
}
return(
<div class="contact" style={padding}>
<h1 style={titleStyle}>Contact Me</h1>
<form>
<div class="form-group" style={padding}>
<label htmlFor="name">Your name:</label>
<input type="text" class="form-control" id="name" placeholder="Leave your name here..." defaultValue={name} onBlur={handleChange}/>
</div>
<div class="form-group" style={padding}>
<label htmlFor="email">Your email:</label>
<textarea name="email" id="email" placeholder="Enter your email here..." class="form-control" defaultValue={email} onBlur={handleChange}></textarea>
</div>
<div class="form-group" style={padding}>
<label htmlFor="message">Your message:</label>
<textarea name="message" id="message" placeholder="Enter your message here..." class="form-control" defaultValue={message} onBlur={handleChange}></textarea>
</div>
{errorMessage && (
<div style={errorStyle}>
<h3>Form Errors:</h3>
<p class="error">{errorMessage}</p>
</div>
)}
<button class="btn btn-dark" style={linkStyle} onSubmit={handleSubmit}>Submit Message</button>
</form>
<p style={padding}>Alternatively, please feel free to contact me directly thru either of the avenues below. </p>
<h5>
Call me at <a href="tel:610.608.0403" style={linkStyle}>610-608-0403</a>
</h5>
<h5>
Email me at <a href="mailto:<EMAIL>" style={linkStyle}><EMAIL></a>
</h5>
</div>
)
}
export default Contact;<file_sep>[](https://opensource.org/licenses/MIT)
# REACT Portfolio
Link to application repository =>
https://github.com/aungy5/react-portfolio
Link to deployed app => https://aungy5.github.io/react-portfolio/
## Table of Contents
- [Description](#description)
- [Installation](#installation)
- [Usage](#usage)
- [Contributors](#contributors)
- [Testing](#testing)
- [License](#license)
- [Questions](#questions)
## Description
In this assignment, we were asked to create a REACT Portfolio to showcase the different apps we have made throughout the course to potential employers. Using REACT allows us to create a much more dynamic portfolio, but also requires us to break up the components of our site into different files. I think this assignment was a great way to learn REACT, and now I have a site that shows I know how to use it. Looking forward to building more with REACT in the future as I learn more about it.
## Installation
The user needs to clone this reporsitory and then run npm install from the root of the directory.
## Usage
To use this app, the user simply needs to access the link at the top of this repository.
## Contributors
No additional contributors on this project.
## Testing
No tests were required for this assignment.
## License
Click the license badge at the top of the ReadME to learn more about the license for this project.
## Questions
Please contact me with any questions using either of the avenues below.
Github URL: https://github.com/aungy5
Email: <EMAIL>
<file_sep>import React from 'react';
import {NavLink} from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css'
const navStyle = {
color: 'red'
}
const activeLink = {
fontWeight: 'bold'
}
const barStyle = {
width: '100%'
}
function Navigation(props) {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-dark" style={barStyle}>
<a class="navbar-brand" style={navStyle} href="#"><NAME></a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<NavLink to="/about"><a class="nav-link" style={navStyle}>About Me</a></NavLink>
<NavLink to="/portfolio"><a class="nav-link" style={navStyle}>Portfolio</a></NavLink>
{/* <a class="nav-link" href="https://github.com/aungy5?tab=repositories">GitHub</a>
<a class="nav-link" href="https://www.linkedin.com/in/aungy/">LinkedIn</a> */}
<NavLink to="/resume"><a class="nav-link" style={navStyle}>Resume</a></NavLink>
<NavLink to="/contact"><a class="nav-link" style={navStyle}>Contact</a></NavLink>
</div>
</div>
</nav>
);
}
export default Navigation;<file_sep>import React from 'react';
const imgStyle = {
width: '75px',
height: '75px',
padding: '10px'
}
const copyStyle = {
padding: '10px',
fontWeight: 'bold'
}
function Footer() {
return(
<div class="footer" id="footer">
<a href="https://www.linkedin.com/in/aungy/"><img src="https://github.com/aungy5/react-portfolio/raw/main/public/images/linkedin.png" alt="LinkedIn" style={imgStyle}></img></a>
<p style={copyStyle}>© <NAME>ARY 2021</p>
<a href="https://github.com/aungy5?tab=repositories"><img src="https://github.com/aungy5/react-portfolio/raw/main/public/images/github.jpg" alt="Github" style={imgStyle}></img></a>
</div>
)
}
export default Footer;<file_sep>import React from 'react';
import portfolio from '../components/portfolio.json'
import ProjectCards from './projects';
// const titleStyle = {
// backgroundColor: '#595959',
// padding: '20px',
// color: '#ff1a1a'
// }
const padding = {
padding: '10px'
}
const titleStyle = {
backgroundColor: 'red',
padding: '20px'
}
function Wrapper(props) {
return <div className="wrapper" style={padding}>{props.children}</div>
}
function Portfolio () {
return(
<section>
<Wrapper id="project-data">
{portfolio.map((project) => (
<ProjectCards key={project.id} image={project.image} name={project.name} github={project.github} deploy={project.deploy} technologies={project.technologies}/>
))}
</Wrapper>
</section>
)
}
export default Portfolio; | ecce6d4c8ee10bb4e8191058b82f87c399ecac81 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | aungy5/react-portfolio | b5f0caca3137ac985d6f2634dc28873eab55a2dc | 4bee009e608fd61c13e2e7d6a9cb3b9251fc222d |
refs/heads/master | <repo_name>salx3mall/Doc2Assist<file_sep>/FileManipulators.h
#include <fstream>
#include <string>
#include <iostream>
#include <cctype>
#include <Windows.h>
#include <clocale>
#include "StringProcessingFunctions.h"
using namespace std;
wstring getNewFileName() {
setlocale(LC_ALL, "Russian");
static bool firstFile = true;
static WIN32_FIND_DATA findData;
static HANDLE handle = INVALID_HANDLE_VALUE;
if (firstFile) {
handle = FindFirstFile(L"./tests/*.txt", &findData);
if (handle == INVALID_HANDLE_VALUE) {
cout << " Не найдено файлов с расширением '.txt'. Обработка завершена." << endl;
return L"";
}
firstFile = false;
}
else {
FindNextFile(handle, &findData);
if (GetLastError() == ERROR_NO_MORE_FILES) {
cout << " Больше нет файлов с нужным расширением. Обработка завершена." << endl;
return L"";
}
}
return findData.cFileName;
}
void processSingleFile(wstring fileName) {
setlocale(LC_ALL, "Russian");
static wifstream tests;
static wofstream result;
if (tests.is_open())
tests.close();
if (result.is_open())
result.close();
tests.open(L"./tests/" + fileName);
if (tests.is_open()) {
wstring resultFileName = L"./results/" + transformFileExtension(fileName);
result.open(resultFileName);
if (!result.is_open()) {
wcout << L" Не удалось создать или открыть файл " << transformFileExtension(fileName) << "\n" <<
L"в папке results. Если он открыт в редакторе, закройте файл и повторите попытку." << "\n" <<
L"Результаты преобразования соответствующего блока тестов не сохранены, увы." << endl;
return;
}
wstring currentString;
getline(tests, currentString);
if (iswdigit(currentString[0])) {
currentString.erase(currentString.find_last_not_of(L" \n\r\t") + 1);
currentString.erase(0, currentString.find_first_not_of(L" \n\r\t"));
result << handleString(currentString);
}
while (!tests.eof()) {
getline(tests, currentString);
if (!currentString.empty()) {
currentString.erase(currentString.find_last_not_of(L" \n\r\t") + 1);
currentString.erase(0, currentString.find_first_not_of(L" \n\r\t"));
if (iswdigit(currentString[0]))
result << endl;
if (iswdigit(currentString[0]) ||
(currentString[0] == L'A' || currentString[0] == L'А' ||
currentString[0] == L'B' || currentString[0] == L'В' ||
currentString[0] == L'C' || currentString[0] == L'С' ||
currentString[0] == L'D' ||
currentString[0] == L'E' || currentString[0] == L'Е')) {
result << endl;
currentString = handleString(currentString);
}
result << currentString;
}
}
result << endl;
tests.close();
result.close();
wcout << L" Файл " << fileName << L" считан. Результат записан в файл " <<
resultFileName.substr(resultFileName.find_last_of(L"/") + 1) <<
L" в директории results." << endl;
}
else
wcout << L" Не удалось открыть файл " << fileName << L" на чтение." << endl;
}
<file_sep>/Doc2Assist.cpp
/*Doc2Assist is the application for changing the format of tests representation from numeric list like
____________________________________________________________________________________
1. Text of qeustion #1
A. Correct answer
B. Incorrect answer...
____________________________________________________________________________________
In the format that is understood to the testing application Assistant, developed for medical students of Sumy State University
____________________________________________________________________________________
?
Text of quesstion #1
+ Correct answer
- Incorrect answer...
____________________________________________________________________________________
All the output information is written in russian since this application is intended for the russian-speaking users.
This project made me understand, what the unicode is and how and why to work with the wide character instead of ordinary ones.
*/
#include <clocale>
#include "FileManipulators.h"
using namespace std;
void greetUser();
int main() {
greetUser();
wstring fileName;
while (true) {
fileName = getNewFileName();
if (fileName.empty())
break;
processSingleFile(fileName);
}
cout << " Спасибо, что воспользовались нашим продуктом!" << endl;
system("pause");
return 0;
}
void greetUser() {
setlocale(LC_ALL, "Russian");
cout << " Привет, пользователь!" << endl;
cout << " Программа Doc2Assist предназначена для преобразования нумерованного списка те" << "\n" <<
"стов в формат, понятный программе Assist от мед. института СумГУ." << endl;
cout << " Входной формат следующий: \"[номер]. [текст][перенос строки]\" или \"[номер]." << "\n" <<
"[табуляция][текст][перенос строки]\". Посмотреть примеры формата можно в файле" << "\n" <<
"example.txt, находящемся в каталоге tests." << endl;
cout << " Прежде чем продолжить работу, посетите этот каталог и поместите в него нужное" << "\n" <<
"количество файлов, содержащих необходимые Вам тематические блоки тестов - один" << "\n" <<
"файл на один блок тестов. Лучше всего сразу дать файлам осмысленные имена." << endl;
cout << " Каждый файл обязательно должен иметь расширение .txt, иначе программа просто" << "\n" <<
"не найдет файлы. Можно размножить файл example.txt, переименовывая файлы и вста" << "\n" <<
"вляя в них нужный текст. После того, как это будет выполнено, нажмите клавишу" << "\n" <<
"Enter, чтобы запустить процесс обработки." << endl;
cout << " Результаты будут помещены в папку results (во избежание проблем, пожалуйста," << "\n" <<
"не удаляйте её). Выходные файлы имеют то же название, что и входные, но другое" << "\n" <<
"расширение - .qst. При создании выходного файла в папке results, файл с тем же" << "\n" <<
"именем будет перезаписан." << endl;
cout << " Важно: верным вариантом ответа обязательно должен быть вариант А! При этом уд" << "\n" <<
"аляется звездочка в конце строки." << endl;
system("pause");
}
<file_sep>/StringProcessingFunctions.h
#include <cctype>
using namespace std;
wstring handleString(const wstring& value) {
if (iswdigit(value[0])) {
unsigned i = 0;
while (iswdigit(value[i])) {
i++;
}
if (value[i] == L' ' || value[i] == L'\t')
i++;
else if (value[i] == L'.' && (value[i + 1] == L' ' || value[i + 1] == L'\t'))
i += 2;
return L"?\n" + value.substr(i);
}
else if (value[0] == L'A' || value[0] == L'А') { //both russian and english letters should be accepted
wstring buffer = L"+ " + value.substr(value.substr(1).find_first_not_of(L" .\t") + 1);
if (buffer[buffer.length() - 1] == L'*')
buffer.erase(buffer.length() - 1);
return buffer;
}
else if (value[0] == L'B' || value[0] == L'В' ||
value[0] == L'C' || value[0] == L'С' ||
value[0] == L'D' ||
value[0] == L'E' || value[0] == L'Е') {
return L"- " + value.substr(value.substr(1).find_first_not_of(L" .\t") + 1);
}
return value;
}
wstring transformFileExtension(const wstring& value) {
return value.substr(0, value.find_last_of(L".")) + L".qst";
}
| 414b27997dad932b1c344c9ce1ad565dadc5b9cc | [
"C++"
] | 3 | C++ | salx3mall/Doc2Assist | 425c37a4729cd2897e35a2d166c064ad631135b4 | e71332ff0f973a77aaad14f6447e68e2950ab9c0 |
refs/heads/master | <file_sep>package com.jposni.elevator;
public class Floor {
int floorNo;
boolean upButton;
public void setFloorNo(int floorNo) {
this.floorNo = floorNo;
}
public void setUpButton(boolean upButton) {
this.upButton = upButton;
}
public void setDownButton(boolean downButton) {
this.downButton = downButton;
}
public int getFloorNo() {
return floorNo;
}
public boolean isUpButton() {
return upButton;
}
public boolean isDownButton() {
return downButton;
}
boolean downButton;
public Floor(int floorNo){
this.floorNo = floorNo;
upButton = false;
downButton = false;
}
}
<file_sep>package com.jposni.elevator;
public class Elevator {
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
private int id;
private State state;
private int currentFloorNo;
public State getState() {
return state;
}
public int getCurrentFloorNo() {
return currentFloorNo;
}
public Elevator(int id, State state, int defaultLocation){
this.setId(id);
this.state = state;
this.currentFloorNo = defaultLocation;
}
public void move(int endLocation) throws InterruptedException {
Thread currentThread = Thread.currentThread();
System.out.println("Calling elevator no: " + currentThread.getName());
if(currentFloorNo < endLocation){
this.state = State.RUNNING_UP;
for(int i = currentFloorNo; i <= endLocation; i++){
System.out.print(i + " ===>>> ");
Thread.sleep(500);
}
}else if (currentFloorNo > endLocation){
this.state= State.RUNNING_DOWN;
for(int i = currentFloorNo; i >= endLocation; i--){
System.out.print(i + " ===>>> ");
Thread.sleep(500);
}
}else{
System.out.println("Already situated at " + endLocation + " floor" );
}
this.state = State.IDLE;
this.currentFloorNo = endLocation;
System.out.println("STOP");
}
}
<file_sep>package com.jposni.elevator;
public enum State{
IDLE, RUNNING_UP, RUNNING_DOWN
} | baaa14375fc11d25efa7841a58aed9668dcbbc2b | [
"Java"
] | 3 | Java | jagadeeshposni/elevator | 10579ca72d8882c163ee93072a4905ff61480d87 | 1f9c687e9ae5829b13e084383a5989fe740d6ded |
refs/heads/master | <repo_name>rodeo-studio/ATL<file_sep>/static-assets/js/controller/DefApp.js
var app = app || {};
var SLIDE_TIMER = 8000;
define([
'underscore',
'backbone',
'bootstrap',
'modernizr',
'imageScale',
'views/WeatherView',
'views/HeroSlideView',
'moment',
'visible',
'parallax',
'macy',
'slick',
'sticky',
'cookie',
'views/ProductsView',
'views/ProductView',
'views/ProductsExploreView',
'views/CartView',
], function(_, Backbone, bootstrap, modernizr, imageScale, WeatherView, HeroSlideView, moment, visible, parallax, Macy, slick, sticky, cookie, ProductsView, ProductView, ProductsExploreView, CartView){
app.dispatcher = _.clone(Backbone.Events);
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
var initialize = function() {
var self = this;
var arrHeroSlides = new Array;
var nCurrSlide = 0;
var bFirstResize = true;
var nHeroHeight = 0;
var productsView = null, productView = null, productsExploreView = null;
app.dispatcher.on("WeatherView:loaded", onWeatherLoaded);
app.dispatcher.on("HeroSlideView:ready", onHeroSlideViewReady);
app.dispatcher.on("ProductsView:loaded", onProductsLoaded);
app.dispatcher.on("ProductView:loaded", onProductLoaded);
app.dispatcher.on("ProductView:addToCart", onProductAddToCart);
app.dispatcher.on("ProductsExploreView:loaded", onProductsExploreLoaded);
app.dispatcher.on("ProductsExploreView:addToCart", onProductAddToCart);
app.dispatcher.on("CartView:created", onCartCreated);
app.dispatcher.on("CartView:loaded", onCartLoaded);
app.dispatcher.on("CartView:added", onCartItemAddedLoaded);
app.dispatcher.on("CartView:updatedQty", onCartItemUpdatedQtyLoaded);
app.dispatcher.on("CartView:updatedRemove", onCartItemUpdatedRemoveLoaded);
app.dispatcher.on("CartView:updateCartItemQty", onUpdateCartItemQty);
app.dispatcher.on("CartView:removeCartItem", onRemoveCartItem);
function isBreakpoint( alias ) {
return $('.device-' + alias).is(':visible');
}
function validateForm(elForm){
var bValid = true;
$('.form-group', elForm).removeClass('has-error');
$('.help-block', elForm).hide();
// manage errs
$('.required', elForm).each(function(){
if ($(this).val() == '') {
bValid = false;
var elParent = $(this).parent();
elParent.addClass('has-error');
$('.help-block', elParent).show();
// highlight that there is at least 1 error
var elFormErr = $('.form-error', elForm);
if (elFormErr.length) {
elFormErr.addClass('has-error');
$('.help-block', elFormErr).show();
}
}
});
return bValid;
}
function changeSlide() {
arrHeroSlides[nCurrSlide].hide();
if (nCurrSlide+1 < arrHeroSlides.length) {
nCurrSlide++;
}
else {
nCurrSlide = 0;
}
arrHeroSlides[nCurrSlide].show();
}
function initHeroSlides() {
$('.hero-item').each(function(index){
arrHeroSlides.push(new HeroSlideView({ el: $(this) }));
});
arrHeroSlides[nCurrSlide].show();
setInterval(function(){
changeSlide();
}, SLIDE_TIMER);
}
function checkInView() {
var bVisible = false;
$('.journal-view .journal-post').each(function(index){
bVisible = $(this).visible(true);
if (bVisible) {
$(this).css('opacity', 1);
$('.post-container', $(this)).css('top', 0);
}
});
}
function handleResize() {
var nWindowHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
if (bFirstResize) {
bFirstResize = false;
nHeroHeight = nWindowHeight;
$('.hero').css('height', nHeroHeight);
$('.hero .strap').css('height', nHeroHeight);
}
if ($('#menu-overlay').hasClass('open')) {
// defined height + enough space to see some content underneath
var nMenusHeight = 400 + 100;
if (nWindowHeight < nMenusHeight) {
nMenusHeight = nWindowHeight;
}
$('#menu-overlay').css('height', nMenusHeight);
}
else {
$('#menu-overlay').css('height', 0);
}
checkInView();
if (productView) {
// are we mobile size)
if( isBreakpoint('xs') ) {
productView.removeSticky();
}
else {
productView.addSticky();
}
}
}
function onWeatherLoaded() {
weatherView.render();
}
function onHeroSlideViewReady(elHeroSlide) {
}
function onProductsLoaded() {
productsView.render();
// for the parallax
jQuery(window).trigger('resize').trigger('scroll');
}
function onProductAddToCart(productID, nQty) {
var cartCookie = getCartCookie();
if (cartCookie != undefined) {
cartView.add(cartCookie, productID, nQty);
}
}
function onProductLoaded() {
productView.render();
}
function onProductsExploreLoaded() {
productsExploreView.render();
}
function onCartCreated(cartID) {
setCartCookie(cartID);
}
function onCartLoaded(jsonCart) {
if ($('#cart-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsAdd, $('#cart-view'), $('#cartViewTemplate'));
}
if ($('#cart-detail-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsAdd, $('#cart-detail-view'), $('#cartDetailViewTemplate'));
}
// for the parallax
jQuery(window).trigger('resize').trigger('scroll');
}
function onCartItemAddedLoaded(jsonCart) {
if ($('#cart-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsAdd, $('#cart-view'), $('#cartViewTemplate'));
}
if ($('#cart-detail-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsAdd, $('#cart-detail-view'), $('#cartDetailViewTemplate'));
}
}
function onCartItemUpdatedQtyLoaded(jsonCart) {
if ($('#cart-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsUpdate, $('#cart-view'), $('#cartViewTemplate'));
}
if ($('#cart-detail-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsUpdate, $('#cart-detail-view'), $('#cartDetailViewTemplate'));
}
}
function onCartItemUpdatedRemoveLoaded(jsonCart) {
if ($('#cart-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsRemove, $('#cart-view'), $('#cartViewTemplate'));
}
if ($('#cart-detail-view').length) {
cartView.render(jsonCart.data.checkoutLineItemsRemove, $('#cart-detail-view'), $('#cartDetailViewTemplate'));
}
}
function onUpdateCartItemQty(cartID, productID, nQty) {
cartView.update(cartID, productID, nQty);
}
function onRemoveCartItem(cartID, productID) {
cartView.remove(cartID, productID);
}
// do we want to update header colour on scroll?
if ($('body.header-colour-toggle').length) {
$(window).scroll(function() {
$('.top-logo .white').show();
$('.top-logo .black').hide();
$('.cart-menu').removeClass('dark');
$('.main-menu').removeClass('dark');
if ($(document).scrollTop() > (nHeroHeight - 50)) {
$('.top-logo .black').show();
$('.top-logo .white').hide();
$('.cart-menu').addClass('dark');
$('.main-menu').addClass('dark');
}
handleResize();
});
}
$(window).resize(function() {
handleResize();
});
if ($('#products-view').length) {
function selectType(elType) {
$('.products-intro-view .link').removeClass('active');
elType.addClass('active');
productsView.load(elType.attr('data-id'));
}
productsView = new ProductsView({ el: '#products-view' });
$('.products-intro-view .link').click(function(evt){
selectType($(this));
});
// select All
selectType($('.products-intro-view .link[data-id="All"]'));
}
if ($('#product-detail-view').length) {
productView = new ProductView({ el: '#product-detail-view' });
productView.load(PRODUCT_ID);
}
if ($('#products-explore-view').length) {
productsExploreView = new ProductsExploreView({ el: '#products-explore-view', strCurrProductHandle: PRODUCT_ID });
productsExploreView.load();
}
if ($('#macy-container').length) {
var macyInstance = Macy({
container: '#macy-container',
columns: 1,
waitForImages: true,
mobileFirst: true,
breakAt: {
768: {
columns: 2
}
}
});
macyInstance.on(macyInstance.constants.EVENT_IMAGE_COMPLETE, function (ctx) {
checkInView();
$(window).scroll(function() {
checkInView();
});
});
}
var weatherView = new WeatherView({ el: '#weather-view', lat: -33.833570, lon: 138.610000 });
weatherView.load();
var cartView = new CartView();
var cartCookie = getCartCookie();
if (cartCookie != undefined) {
// we have a cart
cartView.load(cartCookie);
}
else {
// no cart
cartView.create();
}
$('.content').show();
$('img.scale').imageScale({'rescaleOnResize': true});
handleResize();
if ($('body').attr('data-block') != undefined) {
var new_position = $('#'+$('body').attr('data-block')).offset();
if (new_position != undefined) {
window.scrollTo(new_position.left,new_position.top);
}
}
$('.moment').each(function(){
var strFormat = 'do MMMM YYYY';
if ($(this).hasClass('day_month')) {
strFormat = 'do MMMM'
}
if ($(this).hasClass('year')) {
strFormat = 'YYYY'
}
$(this).html(moment($(this).html()).format(strFormat));
$(this).show();
});
if ($('.hero-container').length) {
$('.hero-container').show();
initHeroSlides();
}
$('img.scale').imageScale({
'rescaleOnResize': true
});
$('.down').click(function(evt){
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 1000);
});
$('.top').click(function(evt){
$('html, body').animate({
scrollTop: $("#top").offset().top
}, 1000);
});
$('#menu-btn').click(function(){
$(this).toggleClass('open');
$('#menu-overlay').toggleClass('open');
handleResize();
});
$('.container-fluid').click(function(evt){
$('#menu-btn').removeClass('open');
$('#menu-overlay').removeClass('open');
handleResize();
});
$('#signup').submit(function(evt){
evt.preventDefault();
$.post("server/mailerproxy.php", $('#signup').serialize()).success(function(data) {
console.log(data);
});
$('#signup .thanks').hide();
if (validateForm($('#signup'))) {
$('#signup .thanks').show();
}
});
// for the parallax
jQuery(window).trigger('resize').trigger('scroll');
};
return {
initialize: initialize
};
});
<file_sep>/mysite/code/AboutPage.php
<?php
class AboutPage extends Page {
private static $db = array(
'BaseImageParallax' => 'Boolean',
'BaseImageCaption' => 'Text'
);
private static $has_many = array(
'AboutElements' => 'AboutElement'
);
private static $has_one = array(
'HeroImage' => 'Image',
'BaseImage' => 'Image',
'PageExtraLink1' => 'SiteTree',
'PageExtraLinkImage1' => 'Image',
'PageExtraLink2' => 'SiteTree',
'PageExtraLinkImage2' => 'Image'
);
function getCMSFields() {
$fields = parent::getCMSFields();
// remove fields
$fields->removeFieldFromTab('Root.Main', 'Content');
// Hero Image
$fields->addFieldToTab('Root.Main', new LiteralField('literalfield', '<strong>Hero Image</strong>'));
$uploadHeroField = new UploadField($name = 'HeroImage', $title = 'Image');
$uploadHeroField->setCanUpload(false);
$fields->addFieldToTab('Root.Main', $uploadHeroField);
// Elements
$config = GridFieldConfig_RelationEditor::create();
$config->removeComponentsByType('GridFieldPaginator');
$config->removeComponentsByType('GridFieldPageCount');
$config->addComponent(new GridFieldSortableRows('SortID'));
$aboutElementField = new GridField(
'AboutElements', // Field name
'About Element', // Field title
$this->AboutElements(),
$config
);
$fields->addFieldToTab('Root.Main', $aboutElementField);
// Base Image
$fields->addFieldToTab('Root.Main', new LiteralField('literalfield', '<strong>Base Image</strong>'));
$uploadField1 = new UploadField($name = 'BaseImage', $title = 'Image');
$uploadField1->setCanUpload(false);
$fields->addFieldToTab('Root.Main', $uploadField1);
$fields->addFieldToTab("Root.Main", new CheckboxField ('BaseImageParallax', 'Enable Parallax'));
$fields->addFieldToTab('Root.Main', new TextField('BaseImageCaption', 'Caption'));
// Page extra links
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Extra Link 1</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageExtraLink1ID', 'Page', 'Page'));
$uploadPageExtraLinkField1 = new UploadField($name = 'PageExtraLinkImage1', $title = 'Image');
$uploadPageExtraLinkField1->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageExtraLinkField1);
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Extra Link 2</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageExtraLink2ID', 'Page', 'Page'));
$uploadPageExtraLinkField2 = new UploadField($name = 'PageExtraLinkImage2', $title = 'Image');
$uploadPageExtraLinkField2->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageExtraLinkField2);
return $fields;
}
}
class AboutPage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
}
}
<file_sep>/mysite/code/JournalPage.php
<?php
class JournalPage extends Page {
private static $db = array(
'JournalDate' => 'Date',
'Synopsis' => 'Text'
);
private static $has_many = array(
);
private static $has_one = array(
'HeroImage' => 'Image'
);
function getCMSFields() {
$fields = parent::getCMSFields();
$dateField = new DateField('JournalDate', 'Date');
$dateField->setConfig('showcalendar', true);
$fields->addFieldToTab('Root.Main', $dateField, 'Content');
$uploadField1 = new UploadField($name = 'HeroImage', $title = 'Image');
$uploadField1->setCanUpload(false);
$fields->addFieldToTab('Root.Main', $uploadField1, 'Content');
$fields->addFieldToTab('Root.Main', new TextField('Synopsis', 'Synopsis'), 'Content');
return $fields;
}
}
class JournalPage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
// get journal page links
$this->JournalHolderPage = DataObject::get_one("JournalHolderPage");
}
public function FirstLastPage($Mode = 'first') {
if($Mode == 'first'){
$Where = "ParentID = ($this->ParentID)";
$Sort = "Sort ASC";
}
elseif($Mode == 'last'){
$Where = "ParentID = ($this->ParentID)";
$Sort = "Sort DESC";
}
else {
return false;
}
return DataObject::get("SiteTree", $Where, $Sort, null, 1);
}
public function PrevNextPage($Mode = 'next') {
if($Mode == 'next'){
$Where = "ParentID = ($this->ParentID) AND Sort > ($this->Sort)";
$Sort = "Sort ASC";
}
elseif($Mode == 'prev'){
$Where = "ParentID = ($this->ParentID) AND Sort < ($this->Sort)";
$Sort = "Sort DESC";
}
else{
return false;
}
return DataObject::get("SiteTree", $Where, $Sort, null, 1);
}
}
<file_sep>/mysite/code/FAQElement.php
<?php
class FAQElement extends DataObject {
private static $db = array(
'SortID'=>'Int',
'Title' => 'Text',
'Content' => 'HTMLText'
);
private static $has_one = array(
);
public function FormatContent() {
return $this->Title;
}
public static $summary_fields = array(
'FormatContent' => 'Content'
);
private static $default_sort = "SortID ASC";
function getCMSFields() {
$fields = new FieldList (
new TextField('Title', 'Title'),
new HtmlEditorField('Content', 'Content')
);
return $fields;
}
}
<file_sep>/static-assets/js/views/CartView.js
var DEFAULT_SHOPIFY_VARIANT_TITLE = 'Default Title';
var MINIMUM_ITEM_QTY = 6;
define([
'underscore',
'backbone'
], function(_, Backbone){
var CartView = Backbone.View.extend({
initialize: function(options){
this.options = options;
this.bUpdated = false;
},
create: function(){
var self = this;
var strQuery = "mutation { checkoutCreate(input: {}) { checkout { id subtotalPrice webUrl lineItems(first: 100) { edges { node { title quantity variant { title price } } } } } } }";
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
// fire event
app.dispatcher.trigger("CartView:created", response.data.checkoutCreate.checkout.id);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
load: function(cartID){
var self = this;
var strQuery = 'mutation { checkoutLineItemsAdd(lineItems: [], checkoutId: "' + cartID + '" ) { checkout { id subtotalPrice webUrl lineItems(first: 100) { edges { node { id title quantity variant { title price } } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
// fire event
app.dispatcher.trigger("CartView:loaded", response);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
add: function(cartID, productID, nQty){
this.bUpdated = true;
var strQuery = 'mutation { checkoutLineItemsAdd(lineItems: [{ variantId: "' + productID + '", quantity: ' + nQty + ' }], checkoutId: "' + cartID + '" ) { checkout { id subtotalPrice webUrl lineItems(first: 100) { edges { node { id title quantity variant { title price } } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
// fire event
app.dispatcher.trigger("CartView:added", response);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
update: function(cartID, productID, nQty){
this.bUpdated = true;
var strQuery = 'mutation { checkoutLineItemsUpdate(lineItems: [{ id: "' + productID + '", quantity: ' + nQty + ' }], checkoutId: "' + cartID + '" ) { checkout { id subtotalPrice webUrl lineItems(first: 100) { edges { node { id title quantity variant { title price } } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
// fire event
app.dispatcher.trigger("CartView:updatedQty", response);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
remove: function(cartID, productID){
this.bUpdated = true;
var strQuery = 'mutation { checkoutLineItemsRemove(lineItemIds: ["' + productID + '"], checkoutId: "' + cartID + '" ) { checkout { id subtotalPrice webUrl lineItems(first: 100) { edges { node { id title quantity variant { title price } } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
// fire event
app.dispatcher.trigger("CartView:updatedRemove", response);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
render: function(jsonCart, elContainer, elTemplate){
var template = _.template(elTemplate.text());
var self = this;
// store total qty and check cart is valid
var bCartValid = true, nQty = 0;
$.each(jsonCart.checkout.lineItems.edges, function(key, item){
item.valid = true;
nQty += item.node.quantity;
// is this item valid?
if (item.node.variant.title == DEFAULT_SHOPIFY_VARIANT_TITLE && item.node.quantity < MINIMUM_ITEM_QTY) {
bCartValid = false;
item.valid = false;
}
});
// only show if we have something in the cart
if (nQty) {
elContainer.show();
}
else {
bCartValid = false;
}
elContainer.html(template({ cart: jsonCart, cartQty: nQty, cartValid: bCartValid }));
$('.item .btn-increment-cart-item-qty', elContainer).click(function(evt){
// get cart
var elCart = $(this).closest('.cart');
// get qty
var elQtySelector = $(this).closest('.qty-selector');
var nQty = Number($('.qty', elQtySelector).html()) + 1;
// fire event
app.dispatcher.trigger("CartView:updateCartItemQty", elCart.attr('data-id'), $(this).attr('data-id'), nQty);
});
$('.item .btn-decrement-cart-item-qty', elContainer).click(function(evt){
// get cart
var elCart = $(this).closest('.cart');
// get qty
var elQtySelector = $(this).closest('.qty-selector');
var nQty = Number($('.qty', elQtySelector).html()) - 1;
if (nQty >= 1) {
// fire event
app.dispatcher.trigger("CartView:updateCartItemQty", elCart.attr('data-id'), $(this).attr('data-id'), nQty);
}
});
$('.item .btn-update-cart-item-qty', $(this).el).click(function(evt){
// get cart
var elCart = $(this).closest('.cart');
// fire event
app.dispatcher.trigger("CartView:updateCartItemQty", elCart.attr('data-id'), $(this).attr('data-id'), 5);
});
$('.item .btn-remove-cart-item', $(this).el).click(function(evt){
// get cart
var elCart = $(this).closest('.cart');
// fire event
app.dispatcher.trigger("CartView:removeCartItem", elCart.attr('data-id'), $(this).attr('data-id'));
});
$('.checkout-btn').click(function(evt){
console.log('c');
$('#termsModal').modal();
});
// show that the cart was updated
if (this.bUpdated) {
$('.cart-menu .cart', elContainer).addClass('update-colour');
$('.cart-menu .items', elContainer).addClass('update-colour');
setTimeout(function(){
$('.cart-menu .cart', elContainer).removeClass('update-colour');
$('.cart-menu .items', elContainer).removeClass('update-colour');
}, 1000);
}
this.bUpdated = false;
return this;
}
});
return CartView;
});
<file_sep>/mysite/code/FAQPage.php
<?php
class FAQPage extends Page {
private static $db = array(
'FAQGeneralTitle' => 'Text',
'FAQShippingTitle' => 'Text',
'FAQTermsConditionsTitle' => 'Text',
'FAQPrivacyTitle' => 'Text'
);
private static $has_many = array(
'FAQGeneralElements' => 'FAQGeneralElement',
'FAQShippingElements' => 'FAQShippingElement',
'FAQTermsElements' => 'FAQTermsElement',
'FAQPrivacyElements' => 'FAQPrivacyElement'
);
private static $has_one = array(
);
function getCMSFields() {
$fields = parent::getCMSFields();
// remove fields
$fields->removeFieldFromTab('Root.Main', 'Content');
// FAQ Elements
$config = GridFieldConfig_RelationEditor::create();
$config->removeComponentsByType('GridFieldPaginator');
$config->removeComponentsByType('GridFieldPageCount');
$config->addComponent(new GridFieldSortableRows('SortID'));
$faqGeneralElementField = new GridField(
'FAQGeneralElement', // Field name
'FAQ General Element', // Field title
$this->FAQGeneralElements(),
$config
);
$fields->addFieldToTab('Root.Main', new LiteralField ('literalfield', '<strong>FAQ General</strong>'));
$fields->addFieldToTab('Root.Main', new TextField('FAQGeneralTitle', 'Title'));
$fields->addFieldToTab('Root.Main', $faqGeneralElementField);
$config2 = GridFieldConfig_RelationEditor::create();
$config2->removeComponentsByType('GridFieldPaginator');
$config2->removeComponentsByType('GridFieldPageCount');
$config2->addComponent(new GridFieldSortableRows('SortID'));
$faqShippingElementField = new GridField(
'FAQShippingElement', // Field name
'FAQ Shipping Element', // Field title
$this->FAQShippingElements(),
$config2
);
$fields->addFieldToTab('Root.Main', new LiteralField ('literalfield', '<strong>FAQ Shipping</strong>'));
$fields->addFieldToTab('Root.Main', new TextField('FAQShippingTitle', 'Title'));
$fields->addFieldToTab('Root.Main', $faqShippingElementField);
$config3 = GridFieldConfig_RelationEditor::create();
$config3->removeComponentsByType('GridFieldPaginator');
$config3->removeComponentsByType('GridFieldPageCount');
$config3->addComponent(new GridFieldSortableRows('SortID'));
$faqTermsElementField = new GridField(
'FAQTermsElement', // Field name
'FAQ Terms Element', // Field title
$this->FAQTermsElements(),
$config3
);
$fields->addFieldToTab('Root.Main', new LiteralField ('literalfield', '<strong>FAQ Terms & Conditions</strong>'));
$fields->addFieldToTab('Root.Main', new TextField('FAQTermsConditionsTitle', 'Title'));
$fields->addFieldToTab('Root.Main', $faqTermsElementField);
$config4 = GridFieldConfig_RelationEditor::create();
$config4->removeComponentsByType('GridFieldPaginator');
$config4->removeComponentsByType('GridFieldPageCount');
$config4->addComponent(new GridFieldSortableRows('SortID'));
$faqPrivacyElementField = new GridField(
'FAQPrivacyElement', // Field name
'FAQ Privacy Element', // Field title
$this->FAQPrivacyElements(),
$config4
);
$fields->addFieldToTab('Root.Main', new LiteralField ('literalfield', '<strong>FAQ Privacy Policy</strong>'));
$fields->addFieldToTab('Root.Main', new TextField('FAQPrivacyTitle', 'Title'));
$fields->addFieldToTab('Root.Main', $faqPrivacyElementField);
return $fields;
}
}
class FAQPage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
if ($this->getRequest()->param('FAQBlock')) {
$this->FAQBlockAnchor = $this->getRequest()->param('FAQBlock');
}
$this->FAQPage = DataObject::get_one("FAQPage");
$this->Title = $this->FAQPage->Title;
}
public function index($request) {
return $this->renderWith('FAQPage');
}
}
<file_sep>/static-assets/js/views/ProductsExploreView.js
define([
'underscore',
'backbone'
], function(_, Backbone){
var ProductsExploreView = Backbone.View.extend({
initialize: function(options){
this.template = _.template($('#productsExploreViewTemplate').text());
this.options = options;
},
load: function(){
var self = this;
var strQuery = '{ shop { products(first: 100) { edges { node { id handle title variants(first: 100) { edges { node { id title price availableForSale } } } images(first: 1) { edges { node { id src } } } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
self.products = response.data.shop.products;
// fire event
app.dispatcher.trigger("ProductsExploreView:loaded", self);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
render: function(){
var self = this;
self.products.currProductHandle = this.options.strCurrProductHandle;
$(this.el).html(this.template({ products: self.products }));
$('.next-arrow', $(this.el)).click(function(evt){
$('.products', $(self.el)).slick('slickNext');
});
$('.prev-arrow', $(this.el)).click(function(evt){
$('.products', $(self.el)).slick('slickPrev');
});
$('.btn-add-to-cart', $(this.el)).click(function(evt){
// fire event
app.dispatcher.trigger("ProductsExploreView:addToCart", $(this).attr('data-id'), 1);
});
$('.products', $(this.el)).slick({
arrows: false,
dots: false,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 1,
responsive: [
{
breakpoint: 768,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
]
});
return this;
}
});
return ProductsExploreView;
});
<file_sep>/static-assets/js/views/ProductsView.js
define([
'underscore',
'backbone'
], function(_, Backbone){
var ProductsView = Backbone.View.extend({
initialize: function(options){
this.template = _.template($('#productsViewTemplate').text());
this.options = options;
},
load: function(strQueryType){
var self = this;
var strQuery = '{ shop { products(sortKey:PRODUCT_TYPE, first: 100) { edges { node { id handle title variants(first: 100) { edges { node { id title price availableForSale } } } images(first: 1) { edges { node { id src } } } } } } } }';
if (strQueryType != 'All') {
strQuery = '{ shop { products(first: 100, query:"product_type:' + strQueryType + '") { edges { node { id handle title variants(first: 100) { edges { node { id title price availableForSale } } } images(first: 1) { edges { node { id src } } } } } } } }';
}
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
self.products = response.data.shop.products;
// fire event
app.dispatcher.trigger("ProductsView:loaded", self);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
render: function(){
var self = this;
$(this.el).html(this.template({ products: self.products }));
return this;
}
});
return ProductsView;
});
<file_sep>/mysite/code/FAQPrivacyElement.php
<?php
class FAQPrivacyElement extends FAQElement {
private static $db = array(
);
private static $has_one = array(
'FAQPrivacy' => 'FAQPage'
);
}
<file_sep>/mysite/code/AboutElement.php
<?php
class AboutElement extends DataObject {
private static $db = array(
'SortID'=>'Int',
'Type'=>'Int',
'BackgroundColour'=>'Int',
'Content' => 'HTMLText',
'Quote' => 'Text',
'QuoteCredit' => 'Text',
'ImageCredit' => 'Text'
);
private static $has_one = array(
'About' => 'AboutPage',
'HeroImage' => 'Image'
);
public function FormatType() {
$source = array("Text", "Quote", "Image", "Image (Wide)");
return $source[$this->Type];
}
public function FormatBackground() {
$source = array("Light", "Dark");
return $source[$this->BackgroundColour];
}
public static $summary_fields = array(
'FormatType' => 'Type',
'FormatBackground' => 'BackgroundColour'
);
private static $default_sort = "SortID ASC";
function getCMSFields() {
$typeField = new OptionsetField(
$name = "Type",
$title = "Type",
$source = array("Text", "Quote", "Image", "Image (Wide)"),
$value = 0
);
$backgroundField = new OptionsetField(
$name = "BackgroundColour",
$title = "Background Colour",
$source = array("Light", "Dark"),
$value = 0
);
$uploadImageField = new UploadField($name = 'HeroImage', $title = 'Image');
$uploadImageField->setCanUpload(false);
$fields = new FieldList (
$typeField,
$backgroundField,
new LiteralField ('literalfield', '<strong>Text</strong>'),
new HtmlEditorField('Content', 'Content'),
new LiteralField ('literalfield', '<strong>Quote Text</strong>'),
new TextField('Quote', 'Quote'),
new TextField('QuoteCredit', 'Credit'),
new LiteralField ('literalfield', '<strong>Element Image</strong>'),
$uploadImageField,
new TextField('ImageCredit', 'Caption')
);
return $fields;
}
}
<file_sep>/static-assets/js/views/ProductView.js
define([
'underscore',
'backbone'
], function(_, Backbone){
var ProductView = Backbone.View.extend({
initialize: function(options){
this.template = _.template($('#productViewTemplate').text());
this.options = options;
},
load: function(strProductHandle){
var self = this;
var strQuery = '{ shop { productByHandle(handle: "' + strProductHandle + '") { id handle title descriptionHtml variants(first: 10) { edges { node { id title price availableForSale } } } images(first: 1) { edges { node { id src } } } } } }';
$.ajax({
url: SHOPIFY_GRAPHQL_API,
type: 'POST',
datatype: 'json',
data: strQuery,
success: function(response) {
self.product = response.data.shop.productByHandle;
// fire event
app.dispatcher.trigger("ProductView:loaded", self);
},
error: function(response) {
console.log('ERR');
console.log(response);
},
beforeSend: setShopifyHeader
});
},
addSticky: function(){
$("#sticky_item").stick_in_parent({parent: '#product-detail-view', offset_top: 20});
},
removeSticky: function(){
$("#sticky_item").trigger("sticky_kit:detach");
},
render: function(){
var self = this;
$(this.el).html(this.template(self.product));
var elQty = $('.qty', $(this).el);
var nMinQty = Number(elQty.attr('data-min-qty'));
var nQtyInc = Number(elQty.attr('data-qty-inc'));
$('.back-link', $(this).el).click(function(evt){
window.history.back();
});
$('.btn-add-to-cart', $(this).el).click(function(evt){
var nQty = Number(elQty.attr('data-qty'));
// fire event
app.dispatcher.trigger("ProductView:addToCart", $(this).attr('data-id'), nQty);
});
$('.btn-qty.btn-less', $(this).el).click(function(evt){
var nQty = Number(elQty.attr('data-qty'));
if (nQty > nMinQty) {
nQty -= nQtyInc;
elQty.attr('data-qty', nQty);
elQty.html(nQty);
}
});
$('.btn-qty.btn-more', $(this).el).click(function(evt){
var nQty = Number(elQty.attr('data-qty'));
nQty += nQtyInc;
elQty.attr('data-qty', nQty);
elQty.html(nQty);
});
return this;
}
});
return ProductView;
});
<file_sep>/mysite/code/ProductPage.php
<?php
class ProductPage extends Page {
private static $db = array(
);
private static $has_many = array(
);
private static $has_one = array(
);
function getCMSFields() {
$fields = parent::getCMSFields();
// remove fields
$fields->removeFieldFromTab('Root.Main', 'Content');
return $fields;
}
}
class ProductPage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
if ($this->getRequest()->param('ProductID')) {
$this->ProductID = $this->getRequest()->param('ProductID');
}
$this->ProductPage = DataObject::get_one("ProductPage");
$this->Title = $this->ProductPage->Title;
}
public function index($request) {
return $this->renderWith('ProductPage');
}
}
<file_sep>/mysite/code/FAQGeneralElement.php
<?php
class FAQGeneralElement extends FAQElement {
private static $db = array(
);
private static $has_one = array(
'FAQGeneral' => 'FAQPage'
);
}
<file_sep>/mysite/code/FAQTermsElement.php
<?php
class FAQTermsElement extends FAQElement {
private static $db = array(
);
private static $has_one = array(
'FAQTerms' => 'FAQPage'
);
}
<file_sep>/mysite/code/VineyardElement.php
<?php
class VineyardElement extends DataObject {
private static $db = array(
'SortID'=>'Int',
'Anchor' => 'Text',
'Title' => 'Text',
'Grower' => 'Text',
'Location' => 'Text',
'Content' => 'HTMLText'
);
private static $has_one = array(
'Vineyards' => 'VineyardsPage',
'HeroImage' => 'Image'
);
public function FormatContent() {
return $this->Title;
}
public static $summary_fields = array(
'FormatContent' => 'Title'
);
private static $default_sort = "SortID ASC";
function getCMSFields() {
$uploadImageField = new UploadField($name = 'HeroImage', $title = 'Image');
$uploadImageField->setCanUpload(false);
$fields = new FieldList (
new TextField('Anchor', 'Page Anchor'),
new TextField('Title', 'Title'),
new TextField('Grower', 'Grower'),
new TextField('Location', 'Location'),
new HtmlEditorField('Content', 'Content'),
$uploadImageField
);
return $fields;
}
}
<file_sep>/mysite/code/HomePage.php
<?php
class HomePage extends Page {
private static $db = array(
'SocialFacebook' => 'Text',
'SocialInstagram' => 'Text',
'SocialEmail' => 'Text',
'Quote' => 'Text',
'BaseImageParallax' => 'Boolean',
'BaseImageCaption' => 'Text',
'PageLink1Synopsis' => 'Text',
'PageLink2Synopsis' => 'Text'
);
private static $has_many = array(
);
private static $has_one = array(
'HeroImage' => 'Image',
'BaseImage' => 'Image',
'PageLink1' => 'SiteTree',
'PageLinkImage1' => 'Image',
'PageLink2' => 'SiteTree',
'PageLinkImage2' => 'Image',
'PageExtraLink1' => 'SiteTree',
'PageExtraLinkImage1' => 'Image',
'PageExtraLink2' => 'SiteTree',
'PageExtraLinkImage2' => 'Image'
);
function getCMSFields() {
$fields = parent::getCMSFields();
// remove fields
$fields->removeFieldFromTab('Root.Main', 'Content');
$fields->addFieldToTab('Root.Social', new TextField('SocialFacebook', 'Facebook URL'));
$fields->addFieldToTab('Root.Social', new TextField('SocialInstagram', 'Instagram URL'));
$fields->addFieldToTab('Root.Social', new TextField('SocialEmail', 'Email address'));
// Hero Image
$fields->addFieldToTab('Root.Main', new LiteralField('literalfield', '<strong>Hero Image</strong>'));
$uploadHeroField = new UploadField($name = 'HeroImage', $title = 'Image');
$uploadHeroField->setCanUpload(false);
$fields->addFieldToTab('Root.Main', $uploadHeroField);
$fields->addFieldToTab('Root.Main', new TextField('Quote', 'Quote'));
// Base Image
$fields->addFieldToTab('Root.Main', new LiteralField('literalfield', '<strong>Base Image</strong>'));
$uploadField1 = new UploadField($name = 'BaseImage', $title = 'Image');
$uploadField1->setCanUpload(false);
$fields->addFieldToTab('Root.Main', $uploadField1);
$fields->addFieldToTab("Root.Main", new CheckboxField ('BaseImageParallax', 'Enable Parallax'));
$fields->addFieldToTab('Root.Main', new TextField('BaseImageCaption', 'Caption'));
// Page links
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Link 1</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageLink1ID', 'Page', 'Page'));
$fields->addFieldToTab('Root.PageLinks', new TextField('PageLink1Synopsis', 'Synopsis'));
$uploadPageLinkField1 = new UploadField($name = 'PageLinkImage1', $title = 'Image');
$uploadPageLinkField1->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageLinkField1);
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Link 2</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageLink2ID', 'Page', 'Page'));
$fields->addFieldToTab('Root.PageLinks', new TextField('PageLink2Synopsis', 'Synopsis'));
$uploadPageLinkField2 = new UploadField($name = 'PageLinkImage2', $title = 'Image');
$uploadPageLinkField2->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageLinkField2);
// Page extra links
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Extra Link 1</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageExtraLink1ID', 'Page', 'Page'));
$uploadPageExtraLinkField1 = new UploadField($name = 'PageExtraLinkImage1', $title = 'Image');
$uploadPageExtraLinkField1->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageExtraLinkField1);
$fields->addFieldToTab('Root.PageLinks', new LiteralField('literalfield', '<strong>Page Extra Link 2</strong>'));
$fields->addFieldToTab('Root.PageLinks', new TreeDropdownField('PageExtraLink2ID', 'Page', 'Page'));
$uploadPageExtraLinkField2 = new UploadField($name = 'PageExtraLinkImage2', $title = 'Image');
$uploadPageExtraLinkField2->setCanUpload(false);
$fields->addFieldToTab('Root.PageLinks', $uploadPageExtraLinkField2);
return $fields;
}
}
class HomePage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
}
}
| 877007800a7342f6a243e2967e19abc5bccc1e37 | [
"JavaScript",
"PHP"
] | 16 | JavaScript | rodeo-studio/ATL | 435e104e3b49fe037b4719dec2a0eac56151ae00 | b8197d5e64918fd9d9f1efd63894fd13ddcf74da |
refs/heads/master | <repo_name>juxiezuo-cyh/es6-lessons<file_sep>/src/js/login/event.js
import { $ } from '../common/utils';// 重名名用as
import { fetchPost } from '../common/fetch';
export default (opts = {}) => {
const $loginForm = $('login-from');
const $loginBtn = $('login-btn');
const $remember = $('login-remember');
const $clearAccount = $('clear-account');
const $clearPassword = $('clear-password');
const $account = $('login-account');
const $password = $('login-password');
const $error = $('login-error');
$loginForm.onsubmit = async () => {
// 点击登录
let remember = '0';
if($remember.getAttribute('checked')) {
remember = '1';
}
const data = await fetchPost('/login',{
account : $account.value,
password: $<PASSWORD>,
remember: remember
});
}
$account.oninput = () => {
}
$password.oninput = () => {
}
$clearAccount.onclick = () => {
}
}<file_sep>/src/js/login/render.js
import { getId } from '../common/utils'
const template = (opts = {}) => {
const autocompleteTpl = `
<div id="no-autocomplete">
<input type="text">
<input type="password">
</div>
`
const autocompleteAdaper = opts.autocomplete ? '' : autocompleteTpl;
const autocompleteValue = opts.autocomplete ? 'on' : 'off';
const tpl = `
<div id="login-wrapper">
<form id="login-form" onsubmit="return false">
${autocompleteAdaper}
<label class="login-account-wrapper">
<span class="account-label">${opts.accountLabel}</span>
<input id="login-account"
name="account" type="text"
autocomplete="${autocompleteValue}"
placeholder="${opts.accountPlaceholder}">
<span id="clear-account" class="del"></span>
</label>
<label class="login-account-wrapper">
<span class="account-label">${opts.passwordLabel}</span>
<input id="login-password"
name="password" type="<PASSWORD>"
autocomplete="${autocompleteValue}"
placeholder="${opts.passwordPlaceholder}">
</label>
<input id="login-btn" class="login-btn"
type="submit" value="${opts.loginBtnText}">
</form>
</div>
`
return tpl
}
export default (conf = {}) => {
// document.getElementById('login-wrapper');
conf.container.innerHTML = template(conf);
const $noAutocomplete = getId('no-autocomplete');
if ($noAutocomplete) {
$noAutocomplete.style.height = '0';
$noAutocomplete.style.opacity = '0';
}
} | bb97b0cf377dc6045197f842810ac2d769d7645b | [
"JavaScript"
] | 2 | JavaScript | juxiezuo-cyh/es6-lessons | 34f436451b12b07a8548237b71b8dea3277ba431 | 0608d8ca08d2aa1e480dd08f9d4b13c4cf2d469e |
refs/heads/master | <file_sep>
DATASET_PATH <- 'UCI HAR Dataset'
require(reshape2)
# Reads the feature definitions and returns a vector with the indices
# of the features of interest to us in the raw dataset. The names of the
# elements in the vector correspond to the actual names of the features
# from the raw dataset.
read.features <- function() {
# Read in all the feature names
raw <- read.table(file.path(DATASET_PATH, 'features.txt'))
# The features that interest us are all the means and standard deviations
rows <- union(grep('std', raw$V2), grep('mean', raw$V2))
features <- raw[rows,'V1']
names(features) <- raw[rows, 'V2']
features
}
# Reads the activity types and and returns them as a numerical vector whose
# names correspond to the labels assigned in the raw data.
read.activity.types <- function() {
raw <- read.table(file.path(DATASET_PATH, 'activity_labels.txt'), stringsAsFactors=F)
activity.types <- raw$V1
names(activity.types) <- raw$V2
activity.types
}
# This function reads the dataset with the variables of interest to us.
# Args:
# - type: A single-element character string vector of either of the values
# 'train' or 'test', each value causes the function to return the
# corresponding dataset.
# - features: A numerical vector whose values are the indices of the and
# names are the corresponding names of the variables in the output
# dataset.
# - activity.types: A numerical vector whose values are the qualitative types
# of activitites used in the raw data, and names correspond to the assigned
# activity labels.
#
read.dataset <- function(type, features, activity.types) {
if (!type %in% c('train', 'test')) {
stop("The type must be provided and be one of the values {'train', 'test'}")
} else if (missing(features)) {
stop("The features must be provided")
} else if (missing(activity.types)) {
stop("The activity.types must be provided")
}
# Read the record subjects
subject <- read.table(file.path(DATASET_PATH, type, paste('subject_', type, '.txt', sep='')))$V1
# Read the record measurement features
measurements <- read.table(file.path(DATASET_PATH, type, paste('X_', type, '.txt', sep='')))
measurements <- measurements[,features]
names(measurements) <- names(features)
# Read the record activities
activities <- read.table(file.path(DATASET_PATH, type, paste('y_', type, '.txt', sep='')))$V1
activities <- sapply(activities, function(activity) names(activity.types)[activity])
activities <- factor(activities)
# Combine them all
dataset <- data.frame(Subject=subject, Activity=activities)
dataset <- cbind(dataset, measurements)
}
# Creates a new dataset containing the average (mean) of each measurement from
# the original dataset for each subject and activity.
create.averaged.dataset <- function(original.dataset) {
melted <- melt(dataset, id.vars=c('Subject', 'Activity'))
melted$variable <- sapply(melted$variable, function(v) paste('mean(', v, ')', sep=''))
unmelted <- dcast(melted, Subject + Activity ~ variable, fun.aggregate=mean)
unmelted
}
# Read in the feature definitions
features <- read.features()
# Read in the activity types
activity.types <- read.activity.types()
# Read in the test and training datasets
test.dataset <- read.dataset('test', features, activity.types)
train.dataset <- read.dataset('train', features, activity.types)
# Combine the test and training datasets
dataset <- rbind(test.dataset, train.dataset)
dataset.averaged <- create.averaged.dataset(dataset)
# Write out the tidy datasets to 'tidy_data.csv' and 'tidy_data-averaged.csv'
write.csv(dataset, 'tidy_data.csv', row.names=F)
write.csv(dataset.averaged, 'tidy_data-averaged.csv', row.names=F)
<file_sep>Getting and Cleaning Data -- Course Project
================
This repository contains the processing code for producing tidy datasets from the raw dataset at http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
In order to produce the tidy datasets, I do the following:
1. Read the measurement features from the file `features.txt`, recognizing the ordered index and name of each measurement
2. Subset the recognized measurements to those whose names contain either the text `mean` or the text `std` which signify that they are either an arithmetic mean or standard deviation of the corresponding series.
3. Read the descriptive textual activity labels from the file `activity_labels.txt`
4. For the `test` dataset, read in the subject column data for all the test observations from the file `subject_*.txt`
5. From the `test` dataset, read in the measurement feautres from the file `X_*.txt`. The measurement values should correspond to the features read in step 2 before the subsetting. The measurement values are then projected onto only the features left after the subsetting in step 2.
6. The activities associated with all the records are read in from the file `y_*.txt` for the `test` dataset, and the numerical activity qualitative values are replaced with the textual labels acquired from step 3.
7. The columns from steps 4, 5, and 6 are then combined into one table where the rows are the observations and the columns are the variables.
8. The steps 4:7 are repeated for the `train` dataset.
9. The outcome datasets from steps 7 and 8 are combined vertically (the rows from the latter are appended to rows from the former) and this is our final tidy dataset: `tidy_data.csv`
10. The separate dataset `tidy_data-averaged.csv` is produced by further modifying the dataset from step 9 by computing the arithmetic mean of each measurement variable across all observations, while grouping by the subject and activity.
<file_sep>Human Activity Recognition Using Smartphones Datasteoh
=========
The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals `tAcc-XYZ` and `tGyro-XYZ`. These time domain signals (prefix `t` to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (`tBodyAcc-XYZ` and `tGravityAcc-XYZ`) using another low pass Butterworth filter with a corner frequency of 0.3 Hz.
Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (`tBodyAccJerk-XYZ` and `tBodyGyroJerk-XYZ`). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (`tBodyAccMag`, `tGravityAccMag`, `tBodyAccJerkMag`, `tBodyGyroMag`, `tBodyGyroJerkMag`).
Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing `fBodyAcc-XYZ`, `fBodyAccJerk-XYZ`, `fBodyGyro-XYZ`, `fBodyAccJerkMag`, `fBodyGyroMag`, `fBodyGyroJerkMag`. (Note the `f` to indicate frequency domian signals).
These signals were used to estimate variables of the feature vector for each pattern:
`-XYZ` is used to denote 3-axial signals in the X, Y and Z directions.
- `tBodyAcc-XYZ`
- `tGravityAcc-XYZ`
- `tBodyAccJerk-XYZ`
- `tBodyGyro-XYZ`
- `tBodyGyroJerk-XYZ`
- `tBodyAccMag`
- `tGravityAccMag`
- `tBodyAccJerkMag`
- `tBodyGyroMag`
- `tBodyGyroJerkMag`
- `fBodyAcc-XYZ`
- `fBodyAccJerk-XYZ`
- `fBodyGyro-XYZ`
- `fBodyAccMag`
- `fBodyAccJerkMag`
- `fBodyGyroMag`
- `fBodyGyroJerkMag`
The set of variables that were estimated from these signals are:
- `mean()`: Mean value
- `std()`: Standard deviation
Also available as record variables:
- `Subject`: An identifier of the human whose responsible for this measurement
- `Activity`: The type of activity the human was taking part in which resulted in the record's measurements
| 5a7b4c697ddc49bbf4a7f8cff84bfd8a877ec0bd | [
"Markdown",
"R"
] | 3 | R | mcanabalb/coursera-getdata | 2e4298da7709accadd0d1542a99af487fd419c1c | 92cdf74f53f88434eaea77a78933cddacc27f388 |
refs/heads/master | <repo_name>reglementsdecomptes/reglementsdecomptes.github.io<file_sep>/_posts/2015-12-11-banditisme-famille.markdown
---
layout: post
title: En famille
categories: articles
published: true
cover_image: Cover_linge_en_famille.jpg
related:
- Vieille école
- La loi du silence
author: <NAME>
---
Le tunnel du Prado est un point de passage obligé pour nombre de Marseillais. Dans la nuit du lundi 9 au mardi 10 novembre, il est le théâtre d'une scène de guerre d’une rare violence, immortalisée par les caméras de surveillance.
Kalachnikov, grosses voitures, douilles par dizaines : tous les ingrédients d'un bon film d'action. Pour ajouter au drame, deux frères occupent le centre de la scène. Ils illustrent une caractéristique fréquente des règlements de compte : le choc entre liens de sang et criminalité.
La police identifie rapidement les victime de l'embuscade : <NAME>. succombe de la suite de ses blessures, et surtout : <NAME>. alias « Babouin », tué sur le coup. Deux autres occupants réussissent à s’échapper, dont Omar, l’un des cousins de Mohamed.
Ce dernier faisait figure de « caïd » dans les quartiers nord de la cité phocéenne. Déjà condamné pour homicide volontaire, il avait aussi été interpellé en possession d’armes, de 87.000 euros en liquide et de 52 Kg de cannabis.
« Babouin » n'en était pas à sa première affaire. Il venait d’être libéré en août après 2 ans et demi de détention provisoire. Les enquêteurs envisagent rapidement un lien avec une précédente fusillade : celle de la cité des Lauriers, 15 jours plus tôt.
Causant la mort de trois jeunes hommes, cette expédition punitive aurait été montée par « Babouin » pour venger la mort de son frère Nasseri, retrouvé avec 9 balles dans le corps en 2012.
La dimension familiale du litige saute aux yeux, avec trois individus d’une même fratrie impliqués dans une série de vengeances sanguinaires. Un seul est encore vivant.
Les frères Hornec dans les années 1990, les frères Jourdain en 1997 : les exemples passés à la postérité criminelle ne manquent pas. Et, avec ses règlements de compte, Marseille ne déroge pas à la règle : à l’image du cas emblématique des frères Nicolas et <NAME>. : réputés impitoyables. Originaires de la cité des Cèdres, ils sont soupçonnés d'assassinats, rapts et trafics.


Travailler en famille constitue, dans le milieu, un réel avantage. La trahison y fait figure d’exception. Un journaliste marseillais, qui préfère conserver l'anonymat, explique que la confiance figure au centre de tout système criminel : or elle _« est plus grande dans une même famille. Pas besoin de s’entretuer entre frères pour les gains, il n’y a qu’à partager, et effectivement c’est plus facile d’être en confiance avec des gens qu’on connait aussi bien que ceux de sa propre famille »._
Un avis partagé <NAME>, criminologue. Selon lui, les associés de ce type d'affaires sont souvent issus de la même famille ou encore amis d’enfance. Il voit dans cette proximité l'origine d'une surenchère dans la violence : _« cette double dimension est dangereuse : les affaires et les liens de sang. Lorsqu’on cherche à venger l’honneur de la famille, les deux dimensions se percutent »._ D’ou la difficulté, évidente, pour la police d’approcher ces cercles très fermés.
Les implications familiales pourraient ainsi expliquer en partie les engrenages de violence qui secouent la ville depuis des années, à l’image de « Babouin », tué en représailles à la vengeance présumée de son frère. Les rivalités entre bandes deviennent claniques. Dès lors qu'un ennemi est identifié, son entourage, sa famille deviennent une cible.
La famille peut-elle devenir un outil pour lutter contre la criminalité ? Ou mieux la comprendre. <NAME>, criminologue américain de l’université d'Etat de l'Arizona, s’est penché sur les logiques d’incitation familiale. Il en déduit que 80% des jeunes délinquants étudiés n’ont jamais eu de parent dans les gangs. En revanche, près de la moitié d’entre eux ont un grand frère déjà impliqué dans la criminalité.
L’influence de ces « guides informels » (<NAME>, _La formation des bandes_, PUF) est réelle et doit être mieux comprise, sinon les fratries continueront de peupler, coude-à-coude, les bancs des tribunaux comme Adbelatif et Mohamed, deux frères accusés avec un troisième homme d'un triple homicide au soir de Noël 2011.


<file_sep>/_posts/2015-12-11-quinze-lauriers.markdown
---
layout: post
published: true
categorie: articles
title: "Avoir 15 ans, cité des Lauriers"
cover_image: Cover_Avoir_15_ans.jpg
related:
- La loi du silence
- A Hungarian man in Marseille
author: <NAME>
---
Il est 2h40, dans la nuit du 24 au 25 octobre, lorsque une arme automatique de calibre 9mm, rafale, en pleine vacances de la Toussaint, trois adolescents au pied d’un immeuble de la Cité des Lauriers (13e ardt).
Parmi les victimes, deux sont âgées de 15 ans et déjà connues des services de police pour des faits de petite délinquance. Avant de tirer, les auteurs présumés ont questionné les victimes sur un individu, relié au trafic de drogue, incitant les enquêteurs à envisager l'hypothèse d’un règlement de comptes. Le hall D de ce bâtiment est connu pour être un point de vente, précise une source policière.
Victimes innocentes ou victimes impliquées : comment de jeunes mineurs ont-il pu être mêlés à pareil drame dans une cité où un cinquième de la population est âgé de moins de 15 ans, selon l'Insee (2012).
# Au mauvais endroit, au mauvais moment
Si, dans les Bouches-du-Rhône, seulement 16 % des individus impliqués dans des faits liés à la grande criminalité sont mineurs, selon la préfecture de police, les faits de petite et moyenne délinquance (violences légères, vols, dégradations, rackets) peuvent parfois conduire des jeunes à être concernés par un règlement de comptes. De nombreux mineurs ont effet déjà _« un palmarès bien étoffé »_, indiquent à la fois une source policière et un habitant du 13ème arrondissement. _« On voit des choufs [guetteur, NDLR] à partir de 12 ans»_, souligne un élu responsable de la sécurité dans les quartiers Nord.

{: .fullwidth}
Pour le criminologue <NAME>, le nombre de mineurs impliqués dans des faits de délinquance est lié au mauvais exemple donné par les guetteurs -- qui gagnent 50 euros par jour dans une cité où le taux de chômage est élevé -- et plus encore aux caïds, qui roulent en voiture haut de gamme et s'offrent régulièrement des vacances.
_« Ça crée des envieux. Le temps de l’adolescence, les jeunes vont faire le guetteur et le dealer. Ensuite, deux options, ils quittent le quartier le temps de fonder une famille ou de décrocher un contrat à durée déterminée ou alors se lancent dans une carrière criminelle. »_, souligne l'expert en criminologie.
_« A 15 ans, peu de gamins sont des caïds"_, poursuit <NAME>. Mais la modestie de leur rang ne protège pas pour autant les mineurs : _"soit on vise symboliquement le réseau par les petits dealers, soit on tire arbitrairement en ne visant pas forcément les bonnes cibles »._
# L’école et les loisirs comme issues de secours
<NAME>., 15 ans, une des victimes du triple homicide des Lauriers, ne semblait pas être la cible originelle des assaillants, selon la police. Elève en CAP béton armé au Lycée Poly<NAME> (13e ardt), il préparait son bac professionnel et était le meilleur élève de sa classe, d'après l'avocat de la famille, <NAME>.
<NAME>., l’autre victime âgée de 15 ans, était scolarisé dans un collège en zone de sécurité prioritaire du quartier Blosne, à Rennes.

{: .fullwidth}
Les taux de scolarisation calculés, par tranche d'âge, dans le 13ème arrondissement ne sont pas si éloignés de la moyenne nationale (98.7%). Ils s’inscrivent dans une baisse générale du décrochage scolaire qui concernait 110.000 élèves sur tout le territoire en 2015, contre 136.000 en 2014.
_“Les résultats sont encourageants, même si la communauté éducative doit maintenir ses efforts sur les plus jeunes, deux tiers des élèves décrochant à 15 ans, dès la fin du collège”_, a prévenu la ministre de l’Éducation Nationale, <NAME>, à l'occasion du premier anniversaire du plan national d'actions, "Tous mobilisés contre le décrochage scolaire", le 1er décembre 2015.
Puisque le décrochage recule, c'est sur leur temps libre que les mineurs rejoignent les réseaux de trafic. Aussi est-il crucial d'empêcher les jeunes de tuer le temps au pied des immeubles, explique <NAME>, dirigeant du club de football <NAME>, que fréquentait l'une des victimes.
_« Parmi nos 40 jeunes licenciés des cités avoisinantes, le football constitue une passion et un vecteur d’échange. En bref, un moyen de changer d’environnement"_, poursuit-il.
Depuis son inscription en 2014, <NAME>. venait d’ailleurs souvent aux entraînements. _« Il avait des relations saines et amicales avec ses camarades »._ Après sa mort, il a fallu beaucoup discuter au sein du club, pour les réconforter, conclut <NAME>.
# Rester prudent sur les mots
Pour empêcher que les drames se répètent, il faut également choisir ses mots avec précaution, explique un journaliste marseillais, qui a préféré conserver l'anonymat. _“Ce n’est pas parce qu’ils ne sont pas enfants de chœur qu’on doit en parler avec tant de violence verbale »_ explique-t-il : à force d'entendre résonner à leurs oreilles les mots apparemment ludiques de « matchs retours » ou « barbecue », certains peuvent minimiser la portée des crimes qu'ils recouvrent.
LIRE AUSSI : ["Mourir à 18 ans dans les quartiers Nord de Marseille"](https://reglementsdecomptes.github.io/2015/12/11/PLANDAOU.html)
{: .relance}
<iframe src="{{site.baseurl}}/dataviz/homicides/index.html" frameborder="0" width="100%" height="2500px"></iframe>
Depuis 1996, 37 jeunes de moins de 15 ans ont été victimes d’homicides dans le département des Bouches-du-Rhône avec une variabilité de 0 à 2, selon les années. Avec l’affaire des Lauriers le 25 octobre dernier, l’année 2015 en comptera deux. Deux de trop.
<file_sep>/_posts/2015-12-11-bad-company.md
---
layout: post
title: Bad (Criminal) Company
categories: articles
published: true
cover_image: Cover_On_Keeping_Bad.jpg
related:
- A Hungarian man in Marseille
- "Le centre-ville, zone de sécurité non prioritaire ?"
author: <NAME>
---
It’s almost summer in Marseille. A courier from the town hall’s sport offices arrives at work near the Velodrome, the renowned soccer stadium in a city famous for its team as well as its passionate supporters—but also for its high-rate of homicides and a century-long history of organized crime. It’s around 8.30 a.m., on May 20th of 2015 and <NAME>., the town employee, who turned 50 one week ago, arrives carrying a bag full of fresh pastries. Just as he goes to open the door, a man wearing a motorcycle helmet opens fire on him with a .357 Magnum revolver. The man walks back toward his accomplice and they flee on a motorcycle, leaving <NAME>. bleeding on the ground. Nearby parents walking their children to school in this relatively quiet, well-off neighborhood, hear the shots ring out.

{: .fullwidth .image}
<NAME>.
{: .credit}
A police source says they are just starting the investigation regarding <NAME>.’s murder, which will take months. The not-apparent but pivotal detail here is that <NAME>. hailed from the Panier, an iconic corner of the old Marseille near the harbor, now loved by tourists but historically linked to the Corsica-Marseille organized-crime ring known in part for running the heroin labs of the French Connection. In the last decade or so, their activity has been pushed to the background as police, politicians, and media have turned to Marseille’s ghettos and their own large-scale, powerful and deadly drug traffics. But the old Panier-Corsica heads are starting to [cooperate](http://www.laprovence.com/article/actualites/3490484/marseille-linquietante-alliance-du-milieu-et-des-bandits-des-cites.html) and work with this neo-criminal rings. And <NAME>.'s life is proof that France's mediteranean blend of "traditional" organized-crime is still very much active.
The judiciary police knew <NAME>. as a man connected with the Corsica-Marseille traditional organized-crime scene. Cited in a _La Provence_ [article](http://www.laprovence.com/article/actualites/3412605/marseille-execution-sur-le-chemin-de-lecole.html), they hint at battles between clans regarding [control](http://www.leparisien.fr/espace-premium/actu/abattu-pres-du-stade-velodrome-20-05-2015-4785717.php) of the Panier as the reason for <NAME>.’s death. But a journalist specialized in Marseille’s criminal scene doubts it. <NAME>. wasn’t important enough to warrant this fate: just a minor rogue who dabbled with the big guys and did footwork for them.

{: .fullwidth .image}
Marseille
{: .credit}
But his past tells a slightly different story, that he was indeed very close to famous heads of the Corsica-Marseille scene. According to another journalist who followed the case closely but wishes to remain anonymous to protect his work, he was the main underling of <NAME>., an historical figure of Marseille’s criminal scene who was killed in 2011. Murdering <NAME>. meant killing the last remaining member of this group. According to this same journalist, among others, <NAME>. was also the subordinate of Jean-Pierre A., another figure of traditional criminality in Marseille for whom <NAME>. was said to collect slot machine money—gambling being one of the main sources of revenue for these “traditional” crime rings. Jean-<NAME>. was also known to be the lieutenant of Ange-Toussaint F., supposed head of the Bergers Braqueurs (the “Shepherd-Robbers”), a criminal clan from Northern Corsica and one of the most, if not the most, dangerous of the island.
However according to his lawyer and friend for 17 years, <NAME>, <NAME>. was no criminal. He was _“a real Marseille man, who loved his wife, motorcycles, card games, and was all heart, always ready to help out his friends.”_ His only connection to criminals like <NAME>. and <NAME>. was that they were childhood friends with whom he grew up in the Panier. They still remained close and even went out to restaurants together. And it was only through these men, by chance, that <NAME>. met even bigger Corsican criminals like Ange-Toussaint F.

{: .fullwidth .image}
<NAME>.
{: .credit}
Yet it was also, even if indirectly, under these men’s orders that <NAME>. took part in the [“Calisson” case](http://www.lexpress.fr/actualite/societe/aix-en-provence-la-rancon-de-la-pegre_1225322.html), named after the famous almond pastry from Aix en Provence. From 2005 to 2012, <NAME>. had been, from jail, at the head of a large racketing scheme previously ran by iconic criminals like Gaëtan Zampa and <NAME>. The “Shepherds” extracted thousands of euros from about ten nightclubs in Aix. <NAME>. was [said](http://www.laprovence.com/article/actualites/3412392/execution-sur-le-chemin-de-lecole-a-marseille.html) to have helped by carrying cash envelopes in between victims and racketeers, but his exact role remains unclear. For this, he was accused of extortion committed by an organized group, conspiracy, and unexplained income. He was acquitted for all accusations but the latter, for which he received a two-year sentence, a 14,000 euros fine, confiscation of assets, and was prohibited from public office.
Still he was out of jail by January, after spending little more than 5 months there. According to his lawyer, a government agency (DNVSF) had afterwards declared that his finances were in order and his sentence was to be re-evaluated. However the "Calisson" case wasn’t the only criminal affairs that brought police suspicion to <NAME>.—although he was rarely charged—and the Corsicans weren’t the only unsavory individuals he associated with. Most notably, he was [arrested in Andorra](http://www.lamarseillaise.fr/marseille/faits-divers-justice/38939-petit-ber-bandit-coursier-de-la-mairie-a-ete-abattu) with a member of the Marseille town council trying to cash 1.3 million euros in checks stolen from a notary’s office. But <NAME>. still worked for the town hall when he was killed, a job often described as a cover-up for more lucrative activities. He showed that a minor player in the traditional scene could remain employed in the town hall for almost thirty years.
As of now Ange <NAME>. stays in jail but the « traditional » Corsica organized-crime clans remain very much active. Marseille is no Chicago, and the Shepherds Robbers no Cosa Nostra but, under the mediteranean sun, organized crime doesn’t seem ready to end.

{: .fullwidth .image}
Panier Street
{: .credit}
<file_sep>/_posts/2015-12-16-article-claire.markdown
---
published: true
title: "Tranquille le jour, ombrageux la nuit"
categorie: articles
layout: post
cover_image: opera.png
related:
- La loi du silence
- Quitter les quartiers Nord
author: <NAME>
---
**Le 13 septembre 2015, à proximité de l’Opéra, Laszlo T., un videur hongrois du O’Stop Bar tombe sous les balles d’une kalashnikov . Un choc dans ce quartier hétéroclite du centre de Marseille, tranquille le jour, ombrageux la nuit.**
_«Le O’Stop c’est le bar dans lequel on va le midi manger un oeuf mayo’ ou un sandwich boulettes le soir»,_ raconte une commerçante du quartier de l’Opéra qui a souhaité garder l’anonymat. _«C’est tombé sur ce café là comme ça aurait pu tomber sur un autre»,_ ajoute-t-elle.
Le restaurant est connu pour être l’un des rares établissements de la ville à être ouvert sans interruption. _«24h/24H»_ lit-on en lettres dorées sur l’auvent bordeaux du restaurant situé face au parvis de l'Opéra.

{: .fullwidth .image}
O’Stop bar - source Google Street View
{: .credit}
Les fêtards s’y retrouvent après une soirée dans les discothèques des alentours à l’image d’Hervé qui a fréquenté le lieu de nombreuses années : _«C’est un endroit où se rejoignent ceux qui appartiennent au monde de la nuit parce que c’est l’un des rares lieux où on peut manger chaud vers 5h ou 6h du matin. Le restaurant est un peu moins cher que le Mas_ [autre restaurant marseillais ouvert la nuit], _alors la clientèle y est plus diverse : il y a des personnes aisées, d’autres qui ont des situations précaires, des amateurs d’Opéra qui veulent grignoter un morceau après une représentation et des jeunes qui souhaitent manger quelque chose après une soirée en discothèque»._

{: .fullwidth .image}
L'Opéra de Marseille - source Google Street View
{: .credit}
On peut même y retrouver des hommes politiques. <NAME>, adjoint à la mairie du 1er arrondissement chargé de la sécurité dit s'y rendre de temps en temps. L’élu connaît bien le bar mais aussi le quartier fréquenté par des personnes aux niveaux de vie variés.
_«Le quartier n’est pas particulièrement sujet à la délinquance, selon lui. Il l’est moins que certains quartiers du nord de la ville ou que le quartier de Noailles, situé à proximité»._
La mairie a tout de même renforcé les patrouilles et contrôles de police pour répondre à l’inquiétude des habitants qui ont déjà été confronté à un événement semblable deux ans plus tôt.
En 2013, le quartier avait été le théâtre d’une autre fusillade : trois hommes avaient été blessés suite à un différend. Hervé lui-même a été agressé dans ce quartier il y a une quinzaine d’année. Pourtant, il ne considère pas le quartier comme sensible ou dangereux.
> Il ne faut pas confondre beauté et aseptisation, ce quartier est beau avec ses imperfections et sa diversité, c’est comme un tableau qui regorge de détails
Un habitant du quartier de l'Opéra
{: .credit}
Bastien y habite et le décrit lui comme un _«quartier branché et vivant où se mêlent boutiques de luxe, petits commerces, lieux culturels et où vivent des personnes aisées et d’autre, plus modestes»._ Marseillais, il apprécie son quartier à l'esthétique singulière : _«il ne faut pas confondre beauté et aseptisation, ce quartier est beau avec ses imperfections et sa diversité, c’est comme un tableau qui regorge de détails, de loin ça paraît peut-être un peu flou mais c’est ça qui fait sa beauté»._
Le quartier a été construit au XVIIe siècle lors de l’agrandissement de la ville, explique <NAME>, maître de Conférences en histoire contemporaine à l’Université d’Aix-Marseille. Il a d’abord été habité par des bourgeois puis est devenu plus populaire.
Sa réputation festive s’est forgée au fil des siècles. _«Des bars et des maisons de jeu ouvrent dès la moitié du XIXe. C’est aussi là que les membres de réseaux criminels venaient récupérer l’argent du jeu et de la drogue, aujourd’hui c’est un endroit où les personnes aisées comme les plus populaires habitent»,_ précise <NAME>.
_«C’est aussi un quartier qui se situe près de l’hôtel de ville, autour duquel la prostitution s’est développée. Elle a été encadrée en 1863, n’a pas cessée mais est devenue clandestine»,_ ajoute-t-elle. Encore aujourd’hui le quartier est concerné : neuf bars à hôtesses ont été fermés en fin d’année pour des faits de proxénétisme, rapporte _La Provence._
<file_sep>/dataviz/homicides/js/bar-chart-f87118b2b891a09c218ea5e535f32b01.min.js
/*
* datawrapper / vis / bar-chart v1.7.8
* generated on 2016-01-15T11:32:32+01:00
*/
/*! datawrapper - v1.10.0 */
(function() {
function getDelimiterPatterns(a, b) {
return new RegExp("(\\" + a + "|\\r?\\n|\\r|^)(?:" + b + "([^" + b + "]*(?:" + b + '"[^' + b + "]*)*)" + b + "|([^" + b + "\\" + a + "\\r\\n]*))", "gi")
}
var root = this,
dw = {};
"undefined" != typeof exports ? ("undefined" != typeof module && module.exports && (exports = module.exports = dw), exports.dw = dw) : window.dw = dw, dw.dataset = function(a, b) {
function c(a) {
for (var b = a.name(), c = b, e = 1; d.hasOwnProperty(c);) c = b + "." + e++;
c != b && a.name(c)
}
var d = {},
e = a.slice(0);
_.each(a, function(a) {
c(a), d[a.name()] = a
}), b = _.extend(b, {});
var f = {
columns: function() {
return a
},
column: function(b) {
if (_.isString(b)) {
if (void 0 !== d[b]) return d[b];
throw 'No column found with that name: "' + b + '"'
}
if (!(0 > b)) {
if (void 0 !== a[b]) return a[b];
throw "No column found with that index: " + b
}
},
numColumns: function() {
return a.length
},
numRows: function() {
return a[0].length
},
eachColumn: function(b) {
_.each(a, b)
},
hasColumn: function(b) {
return void 0 !== (_.isString(b) ? d[b] : a[b])
},
indexOf: function(b) {
return f.hasColumn(b) ? _.indexOf(a, d[b]) : -1
},
list: function() {
return _.range(a[0].length).map(function(b) {
var c = {};
return _.each(a, function(a) {
c[a.name()] = a.val(b)
}), c
})
},
toCSV: function() {
var b = "",
c = ",",
d = '"';
return _.each(a, function(a, e) {
var f = a.title();
f.indexOf(d) > -1 && f.replace(d, "\\" + d), f.indexOf(c) > -1 && (f = d + f + d), b += (e > 0 ? c : "") + f
}), _.each(_.range(f.numRows()), function(e) {
b += "\n", _.each(a, function(a, f) {
var g = "" + ("date" == a.type() ? a.raw(e) : a.val(e));
g.indexOf(d) > -1 && g.replace(d, "\\" + d), g.indexOf(c) > -1 && (g = d + g + d), b += (f > 0 ? c : "") + g
})
}), b
},
filterColumns: function(b) {
return a = _.filter(a, function(a) {
return !b[a.name()]
}), _.each(b, function(a, b) {
a && d[b] && delete d[b]
}), f
},
eachRow: function(a) {
var b;
for (b = 0; b < f.numRows(); b++) a(b);
return f
},
add: function(b) {
return c(b), a.push(b), d[b.name()] = b, e.push(b), f
},
reset: function() {
return a = e.slice(0), d = {}, _.each(a, function(a) {
d[a.name()] = a
}), f
}
};
return f
}, dw.column = function(a, b, c) {
function d(a) {
if (_.every(b, _.isNumber)) return dw.column.types.number();
if (_.every(b, _.isDate)) return dw.column.types.date();
var c, d = [dw.column.types.date(a), dw.column.types.number(a), dw.column.types.text()],
e = b.length,
f = .1;
return _.each(b, function(a) {
_.each(d, function(b) {
b.parse(a)
})
}), _.every(d, function(a) {
return a.errors() / e < f && (c = a), !c
}), c
}
var e = _.map(_.shuffle(_.range(b.length)).slice(0, 200), function(a) {
return b[a]
});
c = c ? dw.column.types[c](e) : d(e);
var f, g, h, i = b.slice(0),
j = {
name: function() {
return arguments.length ? (a = arguments[0], j) : dw.utils.purifyHtml(a)
},
title: function() {
return arguments.length ? (h = arguments[0], j) : dw.utils.purifyHtml(h || a)
},
length: b.length,
val: function(a, d) {
if (!arguments.length) return void 0;
var e = d ? i : b;
return 0 > a && (a += e.length), c.parse(dw.utils.purifyHtml(e[a]))
},
values: function(a) {
var d = a ? i : b;
return d = _.map(d, dw.utils.purifyHtml), _.map(d, c.parse)
},
each: function(a) {
for (var c = 0; c < b.length; c++) a(j.val(c), c)
},
raw: function(a, c) {
return arguments.length ? 2 == arguments.length ? (b[a] = c, j) : dw.utils.purifyHtml(b[a]) : b
},
type: function(a) {
if (a === !0) return c;
if (_.isString(a)) {
if (dw.column.types[a]) return c = dw.column.types[a](e), j;
throw "unknown column type: " + a
}
return c.name()
},
range: function() {
return c.toNum ? (f || (f = [Number.MAX_VALUE, -Number.MAX_VALUE], j.each(function(a) {
a = c.toNum(a), _.isNumber(a) && !_.isNaN(a) && (a < f[0] && (f[0] = a), a > f[1] && (f[1] = a))
}), f[0] = c.fromNum(f[0]), f[1] = c.fromNum(f[1])), f) : !1
},
total: function() {
return c.toNum ? (g || (g = 0, j.each(function(a) {
g += c.toNum(a)
}), g = c.fromNum(g)), g) : !1
},
filterRows: function(a) {
return b = [], arguments.length ? _.each(a, function(a) {
b.push(i[a])
}) : b = i.slice(0), j.length = b.length, f = g = !1, j
},
toString: function() {
return a + " (" + c.name() + ")"
},
indexOf: function(a) {
return _.find(_.range(b.length), function(b) {
return j.val(b) == a
})
}
};
return j
}, dw.column.types = {}, dw.column.types.text = function() {
return {
parse: _.identity,
errors: function() {
return 0
},
name: function() {
return "text"
},
formatter: function() {
return _.identity
},
isValid: function() {
return !0
},
format: function() {}
}
}, dw.column.types.number = function(a) {
function b(a, b) {
return 0 === a ? 0 : Math.round(b - Math.ceil(Math.log(Math.abs(a)) / Math.LN10))
}
var c, d = 0,
e = {
"-.": /^ *[-–—]?[0-9]*(\.[0-9]+)?(e[\+\-][0-9]+)?%? *$/,
"-,": /^ *[-–—]?[0-9]*(,[0-9]+)?%? *$/,
",.": /^ *[-–—]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?%? *$/,
".,": /^ *[-–—]?[0-9]{1,3}(\.[0-9]{3})*(,[0-9]+)?%? *$/,
" .": /^ *[-–—]?[0-9]{1,3}( [0-9]{3})*(\.[0-9]+)?%? *$/,
" ,": /^ *[-–—]?[0-9]{1,3}( [0-9]{3})*(,[0-9]+)?%? *$/,
" .": /^ *[-–—]?[0-9]{1,3}( [0-9]{3})*(\.[0-9]+)?%? *$/,
" ,": /^ *[-–—]?[0-9]{1,3}( [0-9]{3})*(,[0-9]+)?%? *$/
},
f = {
"-.": "1234.56",
"-,": "1234,56",
",.": "1,234.56",
".,": "1.234,56",
" .": "1 234.56",
" ,": "1 234,56",
" .": "1 234.56",
" ,": "1 234,56"
},
g = {
na: 1,
"n/a": 1,
"-": 1,
":": 1
},
h = {},
i = ["-.", 0];
a = a || [], _.each(a, function(a) {
_.each(e, function(b, c) {
void 0 === h[c] && (h[c] = 0), b.test(a) && (h[c] += 1, h[c] > i[1] && (i[0] = c, i[1] = h[c]))
})
}), c = i[0];
var j = {
parse: function(a) {
if (_.isNumber(a) || _.isUndefined(a) || _.isNull(a)) return a;
var b = a.replace("%", "").replace("–", "-").replace("—", "-");
return "-" != c[0] && (b = b.replace(c[0], "")), "." != c[1] && (b = b.replace(c[1], ".")), isNaN(b) || "" === b ? (g[b.toLowerCase()] || "" === b || d++, a) : Number(b)
},
toNum: function(a) {
return a
},
fromNum: function(a) {
return a
},
errors: function() {
return d
},
name: function() {
return "number"
},
formatter: function(a) {
var c = a["number-format"] || "-",
d = Number(a["number-divisor"] || 0),
e = (a["number-append"] || "").replace(/ /g, " "),
f = (a["number-prepend"] || "").replace(/ /g, " ");
return function(a, g, h) {
if (isNaN(a)) return a;
var i = c;
if (0 !== d && "-" == i && (i = "n1"), 0 !== d && (a = Number(a) / Math.pow(10, d)), "s" == i.substr(0, 1)) {
var j = +i.substr(1);
i = "n" + Math.max(0, b(a, j))
}
return h && (i = "n0"), "-" == i && (i = a == Math.round(a) ? "n0" : a == .1 * Math.round(10 * a) ? "n1" : "n2"), a = Globalize.format(a, "-" != i ? i : null), g ? f + a + e : a
}
},
isValid: function(a) {
return "" === a || g[String(a).toLowerCase()] || _.isNumber(j.parse(a))
},
ambiguousFormats: function() {
var a = [];
return _.each(h, function(b, c) {
b == i[1] && a.push([c, f[c]])
}), a
},
format: function(a) {
return arguments.length ? (c = a, j) : c
}
};
return j
}, dw.column.types.date = function(a) {
function b(a, b) {
var c = j[b];
return _.isRegExp(c.test) ? c.test.test(a) : c.test(a, b)
}
function c(a, b) {
var c = j[b];
return _.isRegExp(c.parse) ? a.match(c.parse) : c.parse(a, b)
}
function d(a, b, c) {
var d = new Date(Date.UTC(a, 0, 3));
return d.setUTCDate(3 - d.getUTCDay() + 7 * (b - 1) + parseInt(c, 10)), d
}
function e(a) {
var b = a.getUTCDay(),
c = new Date(a.valueOf());
c.setDate(c.getDate() - (b + 6) % 7 + 3);
var d = c.getUTCFullYear(),
e = Math.floor((c.getTime() - new Date(d, 0, 1, -6)) / 864e5);
return [d, 1 + Math.floor(e / 7), b > 0 ? b : 7]
}
var f, g = 0,
h = {},
i = ["", 0],
j = {
YYYY: {
test: /^ *(?:1[7-9]|20)\d{2} *$/,
parse: /^ *(\d{4}) *$/,
precision: "year"
},
"YYYY-H": {
test: /^ *[12]\d{3}[ \-\/]?[hH][12] *$/,
parse: /^ *(\d{4})[ \-\/]?[hH]([12]) *$/,
precision: "half"
},
"H-YYYY": {
test: /^ *[hH][12][ \-\/][12]\d{3} *$/,
parse: /^ *[hH]([12])[ \-\/](\d{4}) *$/,
precision: "half"
},
"YYYY-Q": {
test: /^ *[12]\d{3}[ \-\/]?[qQ][1234] *$/,
parse: /^ *(\d{4})[ \-\/]?[qQ]([1234]) *$/,
precision: "quarter"
},
"Q-YYYY": {
test: /^ *[qQ]([1234])[ \-\/][12]\d{3} *$/,
parse: /^ *[qQ]([1234])[ \-\/](\d{4}) *$/,
precision: "quarter"
},
"YYYY-M": {
test: /^ *([12]\d{3}) ?[ \-\/\.mM](0?[1-9]|1[0-2]) *$/,
parse: /^ *(\d{4}) ?[ \-\/\.mM](0?[1-9]|1[0-2]) *$/,
precision: "month"
},
"M-YYYY": {
test: /^ *(0?[1-9]|1[0-2]) ?[ \-\/\.][12]\d{3} *$/,
parse: /^ *(0?[1-9]|1[0-2]) ?[ \-\/\.](\d{4}) *$/,
precision: "month"
},
"YYYY-WW": {
test: /^ *[12]\d{3}[ -]?[wW](0?[1-9]|[1-4]\d|5[0-3]) *$/,
parse: /^ *(\d{4})[ -]?[wW](0?[1-9]|[1-4]\d|5[0-3]) *$/,
precision: "week"
},
"MM/DD/YYYY": {
test: /^ *(0?[1-9]|1[0-2])([\-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2([12]\d{3})$/,
parse: /^ *(0?[1-9]|1[0-2])([\-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2(\d{4})$/,
precision: "day"
},
"DD/MM/YYYY": {
test: /^ *(0?[1-9]|[1-2]\d|3[01])([\-\.\/ ?])(0?[1-9]|1[0-2])\2([12]\d{3})$/,
parse: /^ *(0?[1-9]|[1-2]\d|3[01])([\-\.\/ ?])(0?[1-9]|1[0-2])\2(\d{4})$/,
precision: "day"
},
"YYYY-MM-DD": {
test: /^ *([12]\d{3})([\-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01])$/,
parse: /^ *(\d{4})([\-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01])$/,
precision: "day"
},
"YYYY-WW-d": {
test: /^ *[12]\d{3}[ \-]?[wW](0?[1-9]|[1-4]\d|5[0-3])(?:[ \-]?[1-7]) *$/,
parse: /^ *(\d{4})[ \-]?[wW](0?[1-9]|[1-4]\d|5[0-3])(?:[ \-]?([1-7])) *$/,
precision: "day"
},
"MM/DD/YYYY HH:MM": {
test: /^ *(0?[1-9]|1[0-2])([-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2([12]\d{3}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
parse: /^ *(0?[1-9]|1[0-2])([-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2(\d{4}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
precision: "day-minutes"
},
"DD.MM.YYYY HH:MM": {
test: /^ *(0?[1-9]|[1-2]\d|3[01])([-\.\/ ?])(0?[1-9]|1[0-2])\2([12]\d{3}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
parse: /^ *(0?[1-9]|[1-2]\d|3[01])([-\.\/ ?])(0?[1-9]|1[0-2])\2(\d{4}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
precision: "day-minutes"
},
"YYYY-MM-DD HH:MM": {
test: /^ *([12]\d{3})([-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01]) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
parse: /^ *(\d{4})([-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01]) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d) *$/,
precision: "day-minutes"
},
"MM/DD/YYYY HH:MM:SS": {
test: /^ *(0?[1-9]|1[0-2])([-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2([12]\d{3}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
parse: /^ *(0?[1-9]|1[0-2])([-\/] ?)(0?[1-9]|[1-2]\d|3[01])\2(\d{4}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
precision: "day-seconds"
},
"DD.MM.YYYY HH:MM:SS": {
test: /^ *(0?[1-9]|[1-2]\d|3[01])([-\.\/ ?])(0?[1-9]|1[0-2])\2([12]\d{3}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
parse: /^ *(0?[1-9]|[1-2]\d|3[01])([-\.\/ ?])(0?[1-9]|1[0-2])\2(\d{4}) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
precision: "day-seconds"
},
"YYYY-MM-DD HH:MM:SS": {
test: /^ *([12]\d{3})([-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01]) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
parse: /^ *(\d{4})([-\/\. ?])(0?[1-9]|1[0-2])\2(0?[1-9]|[1-2]\d|3[01]) *[ \-\|] *(0?\d|1\d|2[0-3]):([0-5]\d)(?::([0-5]\d))? *$/,
precision: "day-seconds"
}
};
a = a || [], _.each(j, function(c, d) {
_.each(a, function(a) {
void 0 === h[d] && (h[d] = 0), b(a, d) && (h[d] += 1, h[d] > i[1] && (i[0] = d, i[1] = h[d]))
})
}), f = i[0];
var k = {
parse: function(a) {
if (_.isDate(a) || _.isUndefined(a)) return a;
if (!f || !_.isString(a)) return g++, a;
var e = c(a, f);
if (!e) return g++, a;
switch (b(a, f) || g++, f) {
case "YYYY":
return new Date(e[1], 0, 1);
case "YYYY-H":
return new Date(e[1], 6 * (e[2] - 1), 1);
case "H-YYYY":
return new Date(e[2], 6 * (e[1] - 1), 1);
case "YYYY-Q":
return new Date(e[1], 3 * (e[2] - 1), 1);
case "Q-YYYY":
return new Date(e[2], 3 * (e[1] - 1), 1);
case "YYYY-M":
return new Date(e[1], e[2] - 1, 1);
case "M-YYYY":
return new Date(e[2], e[1] - 1, 1);
case "YYYY-WW":
return d(e[1], e[2], 1);
case "YYYY-WW-d":
return d(e[1], e[2], e[3]);
case "YYYY-MM-DD":
return new Date(e[1], e[3] - 1, e[4]);
case "DD/MM/YYYY":
return new Date(e[4], e[3] - 1, e[1]);
case "MM/DD/YYYY":
return new Date(e[4], e[1] - 1, e[3]);
case "YYYY-MM-DD HH:MM":
return new Date(e[1], e[3] - 1, e[4], e[5] || 0, e[6] || 0, 0);
case "DD.MM.YYYY HH:MM":
return new Date(e[4], e[3] - 1, e[1], e[5] || 0, e[6] || 0, 0);
case "MM/DD/YYYY HH:MM":
return new Date(e[4], e[1] - 1, e[3], e[5] || 0, e[6] || 0, 0);
case "YYYY-MM-DD HH:MM:SS":
return new Date(e[1], e[3] - 1, e[4], e[5] || 0, e[6] || 0, e[7] || 0);
case "DD.MM.YYYY HH:MM:SS":
return new Date(e[4], e[3] - 1, e[1], e[5] || 0, e[6] || 0, e[7] || 0);
case "MM/DD/YYYY HH:MM:SS":
return new Date(e[4], e[1] - 1, e[3], e[5] || 0, e[6] || 0, e[7] || 0)
}
return g++, a
},
toNum: function(a) {
return a.getTime()
},
fromNum: function(a) {
return new Date(a)
},
errors: function() {
return g
},
name: function() {
return "date"
},
format: function(a) {
return arguments.length ? (f = a, k) : f
},
precision: function() {
return j[f].precision
},
formatter: function(a) {
if (!f) return _.identity;
var b = Globalize.culture().calendar.patterns.M.replace("MMMM", "MMM");
switch (j[f].precision) {
case "year":
return function(a) {
return _.isDate(a) ? a.getFullYear() : a
};
case "half":
return function(a) {
return _.isDate(a) ? a.getFullYear() + " H" + (a.getMonth() / 6 + 1) : a
};
case "quarter":
return function(a) {
return _.isDate(a) ? a.getFullYear() + " Q" + (a.getMonth() / 3 + 1) : a
};
case "month":
return function(a) {
return _.isDate(a) ? Globalize.format(a, "MMM yy") : a
};
case "week":
return function(a) {
return _.isDate(a) ? e(a).slice(0, 2).join(" W") : a
};
case "day":
return function(a, b) {
return _.isDate(a) ? Globalize.format(a, b ? "D" : "d") : a
};
case "day-minutes":
return function(a) {
return _.isDate(a) ? Globalize.format(a, b).replace(" ", " ") + " - " + Globalize.format(a, "t").replace(" ", " ") : a
};
case "day-seconds":
return function(a) {
return _.isDate(a) ? Globalize.format(a, "T").replace(" ", " ") : a
}
}
},
isValid: function(a) {
return _.isDate(k.parse(a))
},
ambiguousFormats: function() {
var a = [];
return _.each(h, function(b, c) {
b == i[1] && a.push([c, c])
}), a
}
};
return k
}, dw.datasource = {}, dw.datasource.delimited = function(a) {
function b() {
if (a.url) return $.ajax({
url: a.url,
method: "GET",
dataType: "text"
}).then(function(b) {
return new DelimitedParser(a).parse(b)
});
if (a.csv) {
var b = $.Deferred(),
c = b.then(function(b) {
return new DelimitedParser(a).parse(b)
});
return b.resolve(a.csv), c
}
throw "you need to provide either an URL or CSV data."
}
var c = {
dataset: b
};
return c
};
var DelimitedParser = function(a) {
a = _.extend({
delimiter: "auto",
quoteChar: '"',
skipRows: 0,
emptyValue: null,
transpose: !1,
firstRowIsHeader: !0
}, a), this.__delimiterPatterns = getDelimiterPatterns(a.delimiter, a.quoteChar), this.opts = a
};
_.extend(DelimitedParser.prototype, {
parse: function(a) {
function b(a, b, c) {
c = c || ",";
for (var d, e = [
[]
], f = null; f = a.exec(b);) {
var g = f[1];
g.length && g != c && e.push([]), d = f[2] ? f[2].replace(new RegExp('""', "g"), '"') : f[3], e[e.length - 1].push(d)
}
e[0][0].substr(0, 1) == h && (e[0][0] = e[0][0].substr(1));
var i = e.length - 1,
j = e[i].length - 1,
k = e[i][j].length - 1;
return e[i][j].substr(k) == h && (e[i][j] = e[i][j].substr(0, k)), e
}
function c(a) {
var b = a,
c = b.length ? b.length : 0,
d = b[0] instanceof Array ? b[0].length : 0;
if (0 === d || 0 === c) return [];
var e, f, g = [];
for (e = 0; d > e; e++)
for (g[e] = [], f = 0; c > f; f++) g[e][f] = b[f][e];
return g
}
function d(a) {
var b = [],
c = {},
d = a.length,
e = a[0].length,
g = f.skipRows,
h = [];
f.firstRowIsHeader && (h = a[g], g++);
for (var i = 0; e > i; i++) {
var j = _.isString(h[i]) ? h[i].replace(/^\s+|\s+$/g, "") : "",
k = "" !== j ? "" : 1;
for (j = "" !== j ? j : "X."; void 0 !== c[j + k];) k = "" === k ? 1 : k + 1;
b.push({
name: j + k,
data: []
}), c[j + k] = !0
}
return _.each(_.range(g, d), function(c) {
_.each(b, function(b, d) {
b.data.push("" !== a[c][d] ? a[c][d] : f.emptyValue)
})
}), b = _.map(b, function(a) {
return dw.column(a.name, a.data)
}), dw.dataset(b)
}
var e = this,
f = this.opts;
e.__rawData = a, "auto" == f.delimiter && (f.delimiter = e.guessDelimiter(a, f.skipRows), e.__delimiterPatterns = getDelimiterPatterns(f.delimiter, f.quoteChar));
var g, h = "|" != f.delimiter ? "|" : "#";
return a = h + a.replace(/\s+$/g, "") + h, g = b(this.__delimiterPatterns, a, f.delimiter), f.transpose && (g = c(g)), d(g)
},
guessDelimiter: function(a) {
var b = 0,
c = -1,
d = this,
e = [" ", ";", "|", ","];
return _.each(e, function(e, f) {
var g = getDelimiterPatterns(e, d.quoteChar),
h = a.match(g).length;
h > b && (b = h, c = f)
}), e[c]
}
}), dw.utils = {
minMax: function(a) {
var b = [Number.MAX_VALUE, -Number.MAX_VALUE];
return _.each(a, function(a) {
b[0] = Math.min(b[0], a.range()[0]), b[1] = Math.max(b[1], a.range()[1])
}), b
},
dateFormat: function(a) {
function b(a) {
return function(b) {
d = !e || b.getMonth() != e.getMonth(), e = b;
for (var c = a.length - 1, f = a[c]; !f[1](b);) f = a[--c];
return f[0](b)
}
}
function c(a) {
var b = function(b) {
var c = Globalize.format(b, a);
return "htt" != a ? c : c.toLowerCase()
};
return b
}
var d = !0,
e = !1,
f = function(a) {
return {
date: "de" == a ? "dd." : "dd",
hour: "en" != a ? "H:00" : "htt",
minute: "de" == a ? "H:mm" : "h:mm",
mm: "de" == a ? "d.M." : "MM/dd",
mmm: "de" == a ? "d.MMM" : "MMM dd",
mmmm: "de" == a ? "d. MMMM" : "MMMM dd"
}
}(Globalize.culture().language);
return b([
[c("yyyy"), function() {
return !0
}],
[c("MMM"), function(a) {
return 0 !== a.getMonth()
}],
[c(f.date), function(a) {
return 1 != a.getDate()
}],
[c(7 > a ? f.mm : a > 70 ? f.mmm : f.mmm), function(a) {
return 1 != a.getDate() && d
}],
[c(f.hour), function(a) {
return a.getHours()
}],
[c(f.minute), function(a) {
return a.getMinutes()
}],
[c(":ss"), function(a) {
return a.getSeconds()
}],
[c(".fff"), function(a) {
return a.getMilliseconds()
}]
])
},
longDateFormat: function(a) {
return function(b) {
if ("date" != a.type()) return b;
switch (a.type(!0).precision()) {
case "year":
return b.getFullYear();
case "quarter":
return b.getFullYear() + " Q" + (b.getMonth() / 3 + 1);
case "month":
return Globalize.format(b, "MMM yy");
case "day":
return Globalize.format(b, "MMM d");
case "minute":
return Globalize.format(b, "t");
case "second":
return Globalize.format(b, "T")
}
}
},
columnNameColumn: function(a) {
var b = _.map(a, function(a) {
return a.title()
});
return dw.column("", b)
},
name: function(a) {
return _.isFunction(a.name) ? a.name() : _.isString(a.name) ? a.name : a
},
getMaxChartHeight: function(a) {
function b(a, b) {
return "auto" == $(a).css("margin-" + b) ? 0 : +$(a).css("margin-" + b).replace("px", "")
}
var c = 0,
d = 0;
$("body > *").each(function(a, e) {
var f = e.tagName.toLowerCase();
"script" == f || "style" == f || "chart" == e.id || $(e).hasClass("tooltip") || $(e).hasClass("qtip") || $(e).hasClass("container") || $(e).hasClass("noscript") || (c += $(e).outerHeight(!1)), c += Math.max(b(e, "top"), d), d = b(e, "bottom")
}), c += d;
var e = ($("#chart").css("margin-top").replace("px", ""), $("#chart").css("margin-bottom").replace("px", ""), $(window).height() - c - 8);
return $.support.leadingWhitespace || (e -= 15), e -= $("body").css("padding-top").replace("px", ""), e -= $("body").css("padding-bottom").replace("px", "")
},
purifyHtml: function(a, b) {
function c(a, b) {
return !_.isString(a) || a.indexOf("<") < 0 ? a : (void 0 === b && (b = f), g[b] || (g[b] = (((b || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join("")), a.replace(e, "").replace(d, function(a, c) {
return g[b].indexOf("<" + c.toLowerCase() + ">") > -1 ? a : ""
}))
}
var d = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
e = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi,
f = "<b><br><br/><i><strong><sup><sub><strike><u><em><tt>",
g = {};
return void 0 === b && (b = f), g[b] = (((b || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(""), dw.utils.purifyHtml = c, c(a, b)
},
significantDimension: function(a) {
function b(a) {
return dw.utils.round(a, f)
}
var c, d, e = [],
f = 0,
g = _.uniq(a);
if (1 == g.length) return -1 * Math.floor(Math.log(g[0]) / Math.LN10);
_.uniq(_.map(g, b)).length == g.length ? (c = function() {
return _.uniq(e).length == g.length
}, d = -1) : (c = function() {
return _.uniq(e).length < g.length
}, d = 1);
var h = 100;
do e = _.map(g, b), f += d; while (c() && h-- > 0);
return 10 > h && console.warn("maximum iteration reached", a, e, f), 0 > d ? f += 2 : f--, f
},
round: function(a, b) {
var c = Math.pow(10, b);
return Math.round(a * c) / c
},
smartRound: function(a, b) {
var c = dw.utils.significantDimension(a);
return c += b || 0, _.map(a, function(a) {
return dw.utils.round(a, c)
})
},
nearest: function(a, b) {
var c, d = Number.MAX_VALUE;
return _.each(a, function(a) {
var e = Math.abs(a - b);
d > e && (d = e, c = a)
}), c
},
metricSuffix: function(a) {
switch (a.substr(0, 2).toLowerCase()) {
case "de":
return {
3: " Tsd.",
6: " Mio.",
9: " Mrd.",
12: " Bio."
};
case "fr":
return {
3: " mil",
6: " Mio",
9: " Mrd"
};
case "es":
return {
3: " Mil",
6: " millón"
};
default:
return {
3: "k",
6: "M",
9: " bil"
}
}
},
magnitudeRange: function(a) {
var b = Math.round(Math.log(a[0]) / Math.LN10),
c = Math.round(Math.log(a[1]) / Math.LN10);
return c - b
},
logTicks: function(a, b) {
var c = Math.round(Math.log(a) / Math.LN10),
d = Math.round(Math.log(b) / Math.LN10);
return _.map(_.range(c, d), function(a) {
return Math.pow(10, a)
})
},
clone: function(a) {
return JSON.parse(JSON.stringify(a))
}
}, dw.utils.filter = function(a, b, c, d) {
function e(b) {
_.each(g, function(c) {
_.isFunction(c) && c(a.val(b), b)
})
}
function f(c) {
var g;
return "auto" == c && (c = "date" == a.type() ? "timescale" : a.length < 6 ? "buttons" : "select"), a.length < 2 ? function() {
return !1
} : ("select" == c && (g = function(b) {
var c = $("<select />");
return a.each(function(a, b) {
var e = d(a);
e && c.append('<option value="' + b + '">' + (_.isString(e) ? $.trim(e) : e) + "</option>")
}), c.change(function(a) {
var b = c.val();
e(b)
}), c.addClass("filter-ui filter-select"), c
}), "buttons" == c && (g = function(c) {
var g = $("<div />");
g.addClass("filter-ui filter-links"), a.each(function(a, c) {
var e = d(a);
if (e) {
var f = $('<a href="#' + c + '"' + (c == b ? ' class="active" ' : "") + ">" + (_.isString(e) ? $.trim(e) : e) + "</a>").data("row", c);
g.append(f)
}
}), $("a", g).click(function(a) {
var b = $(a.target);
a.preventDefault(), b.hasClass("active") || ($("a", g).removeClass("active"), b.addClass("active"), e(b.data("row")))
}), g.appendTo("body");
var h = $("a:first", g).offset().top,
i = $("a:last", g).offset().top;
return h != i ? (g.remove(), f("select")(c)) : g
}), "timescale" == c && (g = function(c) {
function d(b) {
var c = g.invert(b),
d = Number.MAX_VALUE,
e = 0;
return a.each(function(a, b) {
var f = Math.abs(a.getTime() - c.getTime());
d > f && (d = f, e = b)
}), e
}
var f = Math.min(c.__w - 30, Math.max(300, .7 * c.__w)),
g = d3.time.scale().domain([a.val(0), a.val(-1)]).range([0, f]),
h = $("<div></div>").css({
position: "relative",
height: 45,
"margin-left": 3
}).addClass("filter-ui"),
i = f / 80,
j = g.ticks(i),
k = Math.round((a.val(-1).getTime() - a.val(0).getTime()) / 864e5),
l = dw.utils.dateFormat(k),
m = a.type(!0).formatter(),
n = g.ticks(f / 8),
o = function(b) {
return Math.max(-18, g(a.val(b)) - 40)
};
_.each(j, function(a) {
var b = $("<span>" + l(a) + "</span>"),
d = g(a) - 40,
e = c.labelWidth(l(a));
0 > 40 - .5 * e + d && (d = -40 + .5 * e), b.css({
position: "absolute",
top: 0,
width: 80,
left: d,
"text-align": "center",
opacity: .55
}), h.append(b)
}), _.each(n, function(b) {
if (!(b.getTime() < a.val(0).getTime() || b.getTime() > a.val(-1).getTime())) {
var c = $('<span class="dot"></span>');
c.css({
position: "absolute",
bottom: 19,
width: 1,
height: "1ex",
"border-left": "1px solid #000",
"vertical-align": "bottom",
left: Math.round(g(b)) + .5
}), _.find(j, function(a) {
return b.getTime() == a.getTime()
}) || c.css({
height: "0.6ex",
opacity: .5
}), h.append(c)
}
});
var p = $("<div>▲</div>").css({
position: "absolute",
width: 20,
bottom: 2,
left: g(a.val(b)) - 9,
"text-align": "center"
});
h.append(p);
var q = $("<div><span></span></div>").css({
position: "absolute",
width: 80,
top: 0,
left: o(b),
"text-align": "center"
}).data("last-txt", m(a.val(b))).data("last-left", o(b));
$("span", q).css({
background: c.theme().colors.background,
"font-weight": "bold",
padding: "0 1ex"
}).html(m(a.val(b))), h.append(q), $("<div />").css({
position: "absolute",
width: f + 1,
bottom: 15,
height: 2,
"border-bottom": "1px solid #000"
}).appendTo(h);
var r = $("<div />").css({
position: "absolute",
left: 0,
width: f,
height: 40
});
h.append(r);
var s;
return r.click(function(a) {
var b = a.clientX - r.offset().left,
c = d(b);
e(c), h.data("update-func")(c), clearTimeout(s)
}), r.mousemove(function(b) {
var c = b.clientX - r.offset().left,
f = d(c);
$("span", q).html(m(a.val(f))), q.css({
left: o(f)
}), p.css({
left: g(a.val(f)) - 10
}), clearTimeout(s), s = setTimeout(function() {
e(f), q.data("last-left", o(f)), q.data("last-txt", q.text())
}, 500)
}), r.mouseleave(function() {
q.css({
left: q.data("last-left")
}), p.css({
left: q.data("last-left") + 30
}), $("span", q).html(q.data("last-txt")), clearTimeout(s)
}), h.data("update-func", function(b) {
p.stop().animate({
left: g(a.val(b)) - 10
}, 500, "expoInOut");
var c = o(b),
d = m(a.val(b));
$("span", q).html(d), q.css({
left: c
}), q.data("last-left", c), q.data("last-txt", d)
}), h
}), g)
}
var g = [];
c = c || "auto", d = d || _.identity, "auto" == c && ("date" == a.type() ? c = "timescale" : "text" == a.type() && (c = a.length < 6 ? "buttons" : "select"));
var h = {
ui: f(c),
change: function(a) {
g.push(a)
}
};
return h
}, dw.chart = function(attributes) {
function applyChanges(a) {
var b = chart.get("metadata.data.changes", []),
c = chart.get("metadata.data.transpose", !1);
_.each(b, function(b) {
var d = "row",
e = "column";
c && (d = "column", e = "row"), a.hasColumn(b[e]) && (0 === b[d] ? a.column(b[e]).title(b.value) : a.column(b[e]).raw(b[d] - 1, b.value))
});
var d = chart.get("metadata.data.column-format", {});
return _.each(d, function(b, c) {
b.type && a.hasColumn(c) && a.column(c).type(b.type), b["input-format"] && a.hasColumn(c) && a.column(c).type(!0).format(b["input-format"])
}), a
}
function addComputedColumns(dataset) {
function d3_min(a) {
var b, c, d = -1,
e = a.length;
if (1 === arguments.length) {
for (; ++d < e;)
if (null != (c = a[d]) && c >= c) {
b = c;
break
}
for (; ++d < e;) null != (c = a[d]) && b > c && (b = c)
}
return b
}
function d3_max(a) {
var b, c, d = -1,
e = a.length;
if (1 === arguments.length) {
for (; ++d < e;)
if (null != (c = a[d]) && c >= c) {
b = c;
break
}
for (; ++d < e;) null != (c = a[d]) && c > b && (b = c)
}
return b
}
function d3_sum(a) {
var b, c = 0,
d = a.length,
e = -1;
if (1 === arguments.length)
for (; ++e < d;) d3_numeric(b = +a[e]) && (c += b);
return c
}
function d3_mean(a) {
for (var b, c = 0, d = a.length, e = -1, f = d; ++e < d;) d3_numeric(b = d3_number(a[e])) ? c += b : --f;
return f ? c / f : void 0
}
function d3_median(a) {
var b, c = [],
d = a.length,
e = -1;
if (1 === arguments.length)
for (; ++e < d;) d3_numeric(b = d3_number(a[e])) && c.push(b);
return c.length ? d3_quantile(c.sort(d3_ascending), .5) : void 0
}
function d3_quantile(a, b) {
var c = (a.length - 1) * b + 1,
d = Math.floor(c),
e = +a[d - 1],
f = c - d;
return f ? e + f * (a[d] - e) : e
}
function d3_number(a) {
return null === a ? NaN : +a
}
function d3_numeric(a) {
return !isNaN(a)
}
function d3_ascending(a, b) {
return b > a ? -1 : a > b ? 1 : a >= b ? 0 : NaN
}
function add_computed_column(formula, name) {
var datefmt = d3.time.format("%Y-%m-%d"),
values = data.map(function(row, row_i) {
var context = [];
return context.push("var __row = " + row_i + ";"), _.each(row, function(a, b) {
columnNameToVar[b] && (context.push("var " + columnNameToVar[b] + " = " + JSON.stringify(a) + ";"), "number" == dataset.column(b).type() && (context.push("var " + columnNameToVar[b] + "__sum = " + col_aggregates[b].sum + ";"), context.push("var " + columnNameToVar[b] + "__min = " + col_aggregates[b].min + ";"), context.push("var " + columnNameToVar[b] + "__max = " + col_aggregates[b].max + ";"), context.push("var " + columnNameToVar[b] + "__mean = " + col_aggregates[b].mean + ";"), context.push("var " + columnNameToVar[b] + "__median = " + col_aggregates[b].median + ";")))
}), context.push("var round = d3.round, mean = d3.mean, median = d3.median,sum = d3.sum, max = Math.max, min = Math.min;"),
function() {
try {
return eval(this.context.join("\n") + "\n" + formula)
} catch (e) {
return "n/a"
}
}.call({
context: context
})
}).map(function(a) {
return _.isBoolean(a) ? a ? "yes" : "no" : _.isDate(a) ? datefmt(a) : _.isNumber(a) ? "" + a : String(a)
}),
v_col = dw.column(name, values);
v_col.isComputed = !0, dataset.add(v_col)
}
function column_name_to_var(a) {
return a.toString().toLowerCase().replace(/\s+/g, "_").replace(/[^\w\-]+/g, "").replace(/-/g, "_").replace(/\_\_+/g, "_").replace(/^_+/, "").replace(/_+$/, "").replace(/^(\d)/, "_$1")
}
var v_columns = chart.get("metadata.describe.computed-columns", {}),
data = dataset.list(),
columnNameToVar = {},
col_aggregates = {};
return dataset.eachColumn(function(a) {
a.isComputed || (columnNameToVar[a.name()] = column_name_to_var(a.name()), "number" == a.type() && (col_aggregates[a.name()] = {
min: d3_min(a.values()),
max: d3_max(a.values()),
sum: d3_sum(a.values()),
mean: d3_mean(a.values()),
median: d3_median(a.values())
}))
}), _.each(v_columns, add_computed_column), dataset
}
var dataset, theme, visualization, metric_prefix, change_callbacks = $.Callbacks(),
locale, chart = {
get: function(a, b) {
var c = a.split("."),
d = attributes;
return _.some(c, function(a) {
return _.isUndefined(d) || _.isNull(d) ? !0 : (d = d[a], !1)
}), _.isUndefined(d) || _.isNull(d) ? b : d
},
set: function(a, b) {
var c = a.split("."),
d = c.pop(),
e = attributes;
return _.each(c, function(a) {
(_.isUndefined(e[a]) || _.isNull(e[a])) && (e[a] = {}), e = e[a]
}), _.isEqual(e[d], b) || (e[d] = b, change_callbacks.fire(chart, a, b)), this
},
load: function(a) {
var b, c = {
firstRowIsHeader: chart.get("metadata.data.horizontal-header", !0),
transpose: chart.get("metadata.data.transpose", !1)
};
return a ? c.csv = a : c.url = "data.csv", b = dw.datasource.delimited(c), b.dataset().pipe(function(a) {
return chart.dataset(a), a
})
},
dataset: function(a) {
return arguments.length ? (dataset = applyChanges(addComputedColumns(a)), chart) : dataset
},
theme: function(a) {
return arguments.length ? (theme = a, chart) : theme || {}
},
vis: function(a) {
return arguments.length ? (visualization = a, visualization.chart(chart), chart) : visualization
},
hasHighlight: function() {
var a = chart.get("metadata.visualize.highlighted-series");
return _.isArray(a) && a.length > 0
},
isHighlighted: function(a) {
if (void 0 === _.isUndefined(a)) return !1;
var b = this.get("metadata.visualize.highlighted-series"),
c = dw.utils.name(a);
return !_.isArray(b) || 0 === b.length || _.indexOf(b, c) >= 0
},
locale: function(a, b) {
return arguments.length ? (locale = a.replace("_", "-"), Globalize.cultures.hasOwnProperty(locale) ? (Globalize.culture(locale), "function" == typeof b && b()) : $.getScript("/static/vendor/globalize/cultures/globalize.culture." + locale + ".js", function() {
chart.locale(locale), "function" == typeof b && b()
}), chart) : locale
},
metricPrefix: function(a) {
return arguments.length ? (metric_prefix = a, chart) : metric_prefix
},
formatValue: function(a, b, c) {
var d = chart.get("metadata.describe.number-format"),
e = Number(chart.get("metadata.describe.number-divisor")),
f = chart.get("metadata.describe.number-append", "").replace(" ", " "),
g = chart.get("metadata.describe.number-prepend", "").replace(" ", " ");
return 0 !== e && (a = Number(a) / Math.pow(10, e)), "-" != d ? ((c || a == Math.round(a)) && (d = d.substr(0, 1) + "0"), a = Globalize.format(a, d)) : 0 !== e && (a = a.toFixed(1)), b ? g + a + f : a
},
render: function(a) {
if (!visualization || !theme || !dataset) throw "cannot render the chart!";
visualization.chart(chart), visualization.__init();
var b = $(a);
b.parent().addClass("vis-" + visualization.id).addClass("theme-" + theme.id), visualization.render(b)
},
attributes: function(a) {
return arguments.length ? (attributes = a, chart) : attributes
},
onChange: change_callbacks.add,
columnFormatter: function(a) {
var b = chart.get("metadata.data.column-format", {});
if (b = b[a.name()] || {}, "number" == a.type() && "auto" == b) {
var c = dw.utils.metricSuffix(chart.locale()),
d = a.values(),
e = dw.utils.significantDimension(d),
f = -2 > e ? 3 * Math.round(-1 * e / 3) : e > 2 ? -1 * e : 0,
g = dw.utils.significantDimension(_.map(d, function(a) {
return a / Math.pow(10, f)
}));
b = {
"number-divisor": f,
"number-append": f ? c[f] || " × 10<sup>" + f + "</sup>" : "",
"number-format": "n" + Math.max(0, g)
}
}
return a.type(!0).formatter(b)
},
dataCellChanged: function(a, b) {
var c = chart.get("metadata.data.changes", []),
d = chart.get("metadata.data.transpose", !1),
e = !1;
return _.each(c, function(c) {
var f = "row",
g = "column";
d && (f = "column", g = "row"), a == c[g] && c[f] == b && (e = !0)
}), e
}
};
return chart
}, dw.visualization = function() {
var a = {},
b = function(b) {
return new a[b]
};
return b.register = function(b) {
var c = 3 == arguments.length ? a[arguments[1]].prototype : dw.visualization.base,
d = arguments[arguments.length - 1],
e = a[b] = function() {};
_.extend(e.prototype, c, {
id: b
}, d)
}, b
}(), dw.visualization.base = function() {}.prototype, _.extend(dw.visualization.base, {
__init: function() {
return this.__renderedDfd = $.Deferred(), window.parent && window.parent.postMessage && window.parent.postMessage("datawrapper:vis:init", "*"), this
},
render: function(a) {
$(a).html("implement me!")
},
theme: function(a) {
if (!arguments.length) return this.__theme;
this.__theme = a;
var b = ["horizontalGrid", "verticalGrid", "yAxis", "xAxis"];
return _.each(b, function(b) {
if (a.hasOwnProperty(b))
for (var c in a[b]) {
var d = c.replace(/([A-Z])/g, "-$1").toLowerCase();
a[b].hasOwnProperty(d) || (a[b][d] = a[b][c])
}
}), this
},
size: function(a, b) {
var c = this;
return arguments.length ? (c.__w = a, c.__h = b, c) : [c.__w, c.__h]
},
get: function(a, b) {
return this.chart().get("metadata.visualize." + a, b)
},
notify: function(a) {
return dw.backend && _.isFunction(dw.backend.notify) ? dw.backend.notify(a) : void(window.parent && window.parent.postMessage ? window.parent.postMessage("notify:" + a, "*") : window.console && console.log(a))
},
signature: function() {},
translate: function(a) {
var b = this.meta.locale,
c = this.lang;
return b[a] ? b[a][c] || b[a] : a
},
checkBrowserCompatibility: function() {
return !0
},
chart: function(a) {
var b = this;
if (!arguments.length) return b.__chart;
b.dataset = a.dataset(), b.theme(a.theme()), b.__chart = a;
var c = a.get("metadata.data.column-format", {}),
d = {};
return _.each(c, function(a, b) {
d[b] = !!a.ignore
}), b.dataset.filterColumns(d), b
},
axes: function(a, b) {
function c(a) {
_.isArray(a) || (a = [a]);
for (var b = 0; b < a.length; b++)
if (!f.hasColumn(a[b])) return !1;
return !0
}
var d = this;
if (!b && d.__axisCache) return d.__axisCache[a ? "axesAsColumns" : "axes"];
var e, f = d.dataset,
g = {},
h = {},
i = {},
j = [];
return e = d.chart().get("metadata.axes", {}), _.each(d.meta.axes, function(a, b) {
if (e[b]) {
var d = e[b];
c(d) && (h[b] = d, _.isArray(d) || (d = [d]), _.each(d, function(a) {
g[a] = !0
}))
}
}), _.each(d.meta.axes, function(a, b) {
function c(b) {
return !g[b.name()] && _.indexOf(a.accepts, b.type()) >= 0
}
function e() {
var c = dw.backend ? dw.backend.messages.insufficientData : "The visualization needs at least one column of the type %type to populate axis %key";
j.push(c.replace("%type", a.accepts).replace("%key", b))
}
if (!h[b])
if (a.optional) h[b] = !1;
else if (a.multiple) h[b] = [], f.eachColumn(function(a) {
c(a) && (g[a.name()] = !0, h[b].push(a.name()))
}), h[b].length || e();
else {
var i, k = _.filter(f.columns(), c);
if (a.preferred) {
var l = new RegExp(a.preferred, "i");
i = _.find(k, function(a) {
return l.test(a.name()) || a.title() != a.name() && l.test(a.title())
})
}
if (i || (i = k[0]), i) g[i.name()] = !0, h[b] = i.name();
else if (_.indexOf(a.accepts, "text") >= 0) {
var m = dw.column(b, _.map(_.range(f.numRows()), function(a) {
return (a > 25 ? String.fromCharCode(64 + a / 26) : "") + String.fromCharCode(65 + a % 26)
}), "text");
f.add(m), d.chart().dataset(f), g[m.name()] = !0, h[b] = m.name()
} else e()
}
}), j.length && d.notify(j.join("<br />")),
_.each(h, function(a, b) {
_.isArray(a) ? (i[b] = [], _.each(a, function(a, c) {
i[b][c] = a !== !1 ? d.dataset.column(a) : null
})) : i[b] = a !== !1 ? d.dataset.column(a) : null
}), d.__axisCache = {
axes: h,
axesAsColumns: i
}, d.axes(a)
},
keys: function() {
var a = this,
b = a.axes();
if (b.labels) {
var c = a.dataset.column(b.labels),
d = a.chart().columnFormatter(c),
e = [];
return c.each(function(a) {
e.push(String(d(a)))
}), e
}
return []
},
keyLabel: function(a) {
return a
},
reset: function() {
this.clear(), $("#chart").html("").off("click").off("mousemove").off("mouseenter").off("mouseover"), $(".chart .filter-ui").remove(), $(".chart .legend").remove()
},
clear: function() {},
renderingComplete: function() {
window.parent && window.parent.postMessage && setTimeout(function() {
window.parent.postMessage("datawrapper:vis:rendered", "*")
}, 200), this.__renderedDfd.resolve()
},
rendered: function() {
return this.__renderedDfd.promise()
},
supportsSmartRendering: function() {
return !1
},
_svgCanvas: function() {
return !1
}
}), dw.theme = function() {
function a() {
var c, d, e, f, g, h = arguments[0] || {},
i = 1,
j = arguments.length;
for ("object" == typeof h || _.isFunction(h) || (h = {}); j > i; i++)
if (null != (c = arguments[i]))
for (d in c) e = h[d], f = c[d], h !== f && (f && b(f) ? (g = e && b(e) ? e : {}, h[d] = a(g, f)) : void 0 !== f && (h[d] = f));
return h
}
function b(a) {
return _.isObject(a) && !_.isArray(a) && !_.isFunction(a)
}
var c = {},
d = function(a) {
return c[a]
};
return d.register = function(b) {
var d = 3 == arguments.length ? c[arguments[1]] : dw.theme.base,
e = arguments[arguments.length - 1];
c[b] = a({}, d, {
id: b
}, e)
}, d
}(), dw.theme.base = {
colors: {
palette: ["#6E7DA1", "#64A4C4", "#53CCDD", "#4EF4E8"],
secondary: ["#000000", "#777777", "#cccccc", "#ffd500", "#6FAA12"],
positive: "#85B4D4",
negative: "#E31A1C",
background: "#ffffff",
text: "#000000",
gradients: [
["#fefaca", "#008b15"],
["#f0f9e8", "#ccebc5", "#a8ddb5", "#7bccc4", "#43a2ca", "#0868ac"],
["#feebe2", "#fcc5c0", "#fa9fb5", "#f768a1", "#c51b8a", "#7a0177"],
["#ffffcc", "#c7e9b4", "#7fcdbb", "#41b6c4", "#2c7fb8", "#253494"],
["#8c510a", "#d8b365", "#f6e8c3", "#f5f7ea", "#c7eae5", "#5ab4ac", "#01665e"],
["#c51b7d", "#e9a3c9", "#fde0ef", "#faf6ea", "#e6f5d0", "#a1d76a", "#4d9221"],
["#b2182b", "#ef8a62", "#fddbc7", "#f8f6e9", "#d1e5f0", "#67a9cf", "#2166ac"]
],
categories: [
["#7fc97f", "#beaed4", "#fdc086", "#ffff99", "#386cb0", "#f0027f", "#bf5b17", "#666666"],
["#fbb4ae", "#b3cde3", "#ccebc5", "#decbe4", "#fed9a6", "#ffffcc", "#e5d8bd", "#fddaec", "#f2f2f2"],
["#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a", "#ffff99", "#b15928"]
]
},
annotation: {
background: "#000",
opacity: .08
},
padding: {
left: 0,
right: 20,
bottom: 30,
top: 10
},
lineChart: {
strokeWidth: 3,
maxLabelWidth: 80,
fillOpacity: .2,
xLabelOffset: 20
},
columnChart: {
cutGridLines: !1,
barAttrs: {
"stroke-width": 1
},
darkenStroke: 18
},
barChart: {
barAttrs: {
"stroke-width": 1
}
},
xAxis: {
stroke: "#333"
},
yAxis: {
strokeWidth: 1
},
horizontalGrid: {
stroke: "#d9d9d9"
},
verticalGrid: !1,
frame: !1,
frameStrokeOnTop: !1,
yTicks: !1,
hover: !0,
tooltip: !0,
hpadding: 0,
vpadding: 10,
minWidth: 100,
locale: "de_DE",
duration: 1e3,
easing: "expoInOut"
}
}).call(this);
(function() {
dw.visualization.register('raphael-chart', {
init: function() {
this.__elements = {};
this.__labels = {};
},
update: function(row) {
console.warn('vis.update(): override me!', row);
},
setRoot: function(el) {
var me = this;
me.__root = el;
el.css({
position: 'relative'
});
el.addClass(me.chart().get('type'));
},
getSize: function() {
return [this.__w, this.__h];
},
initCanvas: function(canvas, w_sub, h_sub) {
var me = this,
el = me.__root,
size = me.size(),
theme = me.theme();
canvas = _.extend({
w: size[0] - (w_sub || 0),
h: size[1] - (h_sub || 0),
rpad: theme.padding.right,
lpad: theme.padding.left,
bpad: theme.padding.bottom,
tpad: theme.padding.top
}, canvas);
if (size[0] <= 100) {
canvas.bpad = canvas.tpad = canvas.lpad = canvas.rpad = 5;
canvas.bpad = canvas.tpad = 15;
}
canvas.root = el;
canvas.paper = Raphael(el[0], canvas.w, canvas.h + 2);
el.height(canvas.h);
$('.tooltip').hide();
me.__canvas = canvas;
Raphael.easing_formulas.expoInOut = function(n, time, beg, diff, dur) {
dur = 1000;
time = n * 1000;
beg = 0;
diff = 1;
if (time === 0) return beg;
if (time == dur) return beg + diff;
if ((time /= dur / 2) < 1) return diff / 2 * Math.pow(2, 10 * (time - 1)) + beg;
return diff / 2 * (-Math.pow(2, -10 * --time) + 2) + beg;
};
$.extend(jQuery.easing, {
expoIn: function(x, t, b, c, d) {
return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
},
expoOut: function(x, t, b, c, d) {
return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
},
expoInOut: function(x, t, b, c, d) {
if (t == 0) return b;
if (t == d) return b + c;
if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
}
});
return canvas;
},
onMouseMove: function(e) {
var me = this,
x = e.pageX,
y = e.pageY,
hovered_key = this.getKeyByPoint(x, y, e),
row = this.getDataRowByPoint(x, y),
theme = me.theme(),
hoveredNode = hovered_key !== null;
if (!hovered_key) hovered_key = me.getKeyByLabel();
if (!hovered_key) {
clearTimeout(me.__mouseOverTimer);
me.__mouseOutTimer = setTimeout(function() {
clearTimeout(me.__mouseOverTimer);
clearTimeout(me.__mouseOutTimer);
if (theme.hover) me.hover();
if (theme.tooltip) me.hideTooltip();
}, 200);
} else {
if (me.__mouseOutTimer) clearTimeout(me.__mouseOutTimer);
me.__mouseOverTimer = setTimeout(function() {
clearTimeout(me.__mouseOverTimer);
clearTimeout(me.__mouseOutTimer);
if (theme.hover) me.hover(hovered_key);
}, 100);
}
},
registerElement: function(el, key, row) {
el.data('key', key);
if (_.isNumber(row)) el.data('row', row);
if (!this.__elements[key]) {
this.__elements[key] = [];
}
this.__elements[key].push(el);
return el;
},
registerLabel: function(lbl, key, column, row) {
var me = this;
lbl.data('key', key);
if (column && !_.isUndefined(row)) {
lbl.el.attr('data-column', column);
lbl.el.attr('data-row', row);
}
if (!me.__labels[key]) {
me.__labels[key] = [];
}
me.__labels[key].push(lbl);
lbl.on('mouseenter', function(e) {
me.__hoveredLabel = e.target;
clearTimeout(me.__mouseLeaveTimer);
});
lbl.on('mouseleave', function() {
me.__mouseLeaveTimer = setTimeout(function() {
me.__hoveredLabel = null;
}, 100);
});
return lbl;
},
getLabels: function(key) {
return this.__labels[key] || [];
},
hover: function(hover_key) {
var keyElements = this.__elements;
_.each(keyElements, function(elements, key) {
var h = !hover_key || key == hover_key;
_.each(elements, function(el) {
el.animate({
opacity: h ? 1 : 0.5
}, 80);
});
});
var keyLabels = this.__labels;
_.each(keyLabels, function(labels, key) {
var h = !hover_key || key == hover_key;
_.each(labels, function(lbl) {
if (key == hover_key) lbl.addClass('highlighted');
else lbl.removeClass('highlighted');
});
});
},
path: function(pathdata, className) {
var p = this.__canvas.paper.path(pathdata);
if (className && Raphael.svg) {
$(p.node).attr('class', className);
}
return p;
},
label: function(x, y, txt, _attrs) {
var me = this,
lbl, attrs = {
root: this.__canvas.root,
align: 'left',
valign: 'middle',
cl: '',
rotate: 0,
css: {
position: 'absolute',
width: _attrs.w ? _attrs.w : 'auto'
},
x: x,
y: y,
txt: txt
};
$.extend(true, attrs, _attrs || {});
lbl = $('<div class="label' + (attrs.cl ? ' ' + attrs.cl : '') + '"><span>' + txt + '</span></div>');
lbl.css(attrs.css);
lbl.css({
'text-align': attrs.align
});
attrs.root.append(lbl);
function position() {
var w = attrs.w || me.labelWidth(attrs.txt, attrs.cl, attrs.size),
h = attrs.h || lbl.height(),
x = attrs.x,
y = attrs.y,
rot_w = 100;
var css = attrs.rotate == -90 ? {
left: x - rot_w * 0.5,
top: attrs.valign == 'top' ? y + rot_w * 0.5 : y - rot_w * 0.5,
width: rot_w,
height: 20,
'text-align': attrs.valign == 'top' ? 'right' : 'left'
} : {
left: attrs.align == 'left' ? x : attrs.align == 'center' ? x - w * 0.5 : x - w,
top: y - h * (attrs.valign == 'top' ? 0 : attrs.valign == 'middle' ? 0.5 : 1),
width: w,
height: h
};
if (attrs.size) {
css['font-size'] = attrs.size;
}
return css;
}
lbl.css($.extend({}, attrs.css, position()));
if (attrs.rotate == -90) {
lbl.css({
'-moz-transform': 'rotate(-90deg)',
'-webkit-transform': 'rotate(-90deg)',
'-ms-transform': 'rotate(-90deg)',
'-o-transform': 'rotate(-90deg)',
'filter': 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)'
});
}
var label = {
el: lbl
};
label.text = function(txt) {
if (arguments.length) {
$('span', lbl).html(txt);
return label;
}
return $('span', lbl).html();
};
label.animate = function(_attrs, duration, easing) {
if (_attrs.align != attrs.align) {
setTimeout(function() {
lbl.css({
'text-align': _attrs.align
});
}, duration ? duration * 0.5 : 10);
}
if (attrs.rotate && _attrs.valign != attrs.valign) {
setTimeout(function() {
lbl.css({
'text-align': _attrs.valign == 'top' ? 'right' : 'left'
});
}, duration ? duration * 0.5 : 10);
}
if (_attrs.txt != attrs.txt) label.text(_attrs.txt);
$.extend(attrs, _attrs);
var _css = $.extend({}, attrs.css, position());
return duration ? lbl.stop().animate(_css, duration, easing) : lbl.css(_css);
};
label.attr = label.animate;
label.data = function() {
return lbl.data.apply(lbl, arguments);
};
label.hide = function() {
return lbl.hide.apply(lbl, arguments);
};
label.show = function() {
return lbl.show.apply(lbl, arguments);
};
label.width = function() {
return lbl.width.apply(lbl, arguments);
};
label.height = function() {
return lbl.height.apply(lbl, arguments);
};
label.left = function() {
return lbl.offset().left;
};
label.top = function() {
return lbl.offset().top;
};
label.on = function() {
return lbl.on.apply(lbl, arguments);
};
label.hasClass = function() {
return lbl.hasClass.apply(lbl, arguments);
};
label.addClass = function() {
return lbl.addClass.apply(lbl, arguments);
};
label.removeClass = function() {
return lbl.removeClass.apply(lbl, arguments);
};
label.remove = function() {
return lbl.remove.apply(lbl, arguments);
};
lbl.data('label', label);
return label;
},
labelWidth: function(txt, className, fontSize) {
var lbl, span, $span, ow, root = this.__root.get(0);
lbl = document.createElement('div');
lbl.style.position = 'absolute';
lbl.style.left = '-10000px';
span = document.createElement('span');
lbl.appendChild(span);
$span = $(span);
root.appendChild(lbl);
ow = !_.isUndefined(span.offsetWidth) ? function() {
return span.offsetWidth;
} : function() {
return $span.outerWidth();
};
function labelWidth(txt, className, fontSize) {
lbl.setAttribute('class', 'label ' + (className ? ' ' + className : ''));
span.style.fontSize = fontSize ? fontSize : null;
span.innerHTML = txt;
return ow();
}
this.labelWidth = labelWidth;
return labelWidth(txt, className, fontSize);
},
labelHeight: function(txt, className, width, fontSize) {
var lbl, span, $span, oh, root = this.__root.get(0);
lbl = document.createElement('div');
lbl.style.position = 'absolute';
lbl.style.left = '-10000px';
span = document.createElement('span');
lbl.appendChild(span);
$span = $(span);
root.appendChild(lbl);
oh = !_.isUndefined(span.offsetHeight) ? function() {
return span.offsetHeight;
} : function() {
return $span.height();
};
function labelHeight(txt, className, width, fontSize) {
lbl.setAttribute('class', 'label ' + (className ? ' ' + className : ''));
lbl.style.width = width + 'px';
span.style.fontSize = fontSize ? fontSize : null;
span.innerHTML = txt;
return oh();
}
this.labelHeight = labelHeight;
return labelHeight(txt, className, width, fontSize);
},
orderSeriesElements: function() {
var me = this;
_.each(me.dataset.columns(), function(column) {
if (me.chart().isHighlighted(column)) {
_.each(me.__elements[column.name()], function(el) {
el.toFront();
});
}
});
},
getKeyByPoint: function(x, y, evt) {
var me = this,
el = me.__canvas.paper.getElementByPoint(x, y);
if (!el) {
el = $(evt.target);
if (!el.hasClass('label')) el = el.parents('.label');
}
if (el && el.data('key')) return el.data('key');
return null;
},
getKeyByLabel: function() {
var me = this;
if (me.__hoveredLabel) {
lbl = $(me.__hoveredLabel);
if (me.__hoveredLabel.nodeName.toLowerCase() == 'span') lbl = lbl.parent();
if (lbl.data('key')) return lbl.data('key');
}
return null;
},
getDataRowByPoint: function(x, y) {
throw 'getDataRowByPoint() needs to be implemented by each visualization';
},
_baseColor: function() {
var me = this,
base = me.get('base-color', 0),
palette = me.theme().colors.palette,
fromPalette = !_.isString(base);
return fromPalette ? palette[base] : base;
},
_getColor: function(series, row, opts) {
var me = this,
key = opts.key;
if (!key && series) {
key = series.name();
}
if (key) {
var customColors = me.get('custom-colors', {});
if (customColors[key]) return customColors[key];
}
if (opts.byValue && series) {
return opts.byValue(series.val(row));
}
if (series && me.__colors && me.__colors[key]) {
return me.__colors[key];
}
var palette = me.theme().colors.palette,
baseColor = me._baseColor();
if (opts.usePalette) {
return palette[(Math.max(0, palette.indexOf(baseColor)) + row) % palette.length];
}
if (opts.varyLightness) {
var lab = chroma.color(baseColor).lab(),
minL = Math.min(lab[0], 50),
maxL = 91,
f = row / (me.dataset.numRows() - 1);
return chroma.lab(minL + f * (maxL - minL), lab[1], lab[2]).hex();
}
return baseColor;
},
getColor: function(series, row, opts) {
var me = this,
chart = me.chart(),
color = me._getColor(series, row, opts);
if (series && chart.hasHighlight() && !chart.isHighlighted(series)) {
return chroma.interpolate(color, me.theme().colors.background, 0.65, 'rgb').hex();
}
return color;
},
getKeyColor: function(_key, _value, _useNegativeColor, _colorful) {
var me = this,
palette = me.theme().colors.palette,
colorByRow = me.meta['color-by'] == 'row',
colorCache = {};
function keyColor(key, value, useNegativeColor, colorful) {
var color;
key = String(key);
var userCustomColors = me.get('custom-colors', {});
if (userCustomColors[key]) {
color = userCustomColors[key];
} else if (value && useNegativeColor) {
color = me.theme().colors[value < 0 ? 'negative' : 'positive'];
} else {
if (key && me.__customColors && me.__customColors[key])
color = me.__customColors[key];
else color = me._baseColor();
}
var key_color = chroma.hex(color),
bg_color = chroma.hex(me.theme().colors.background),
bg_lch = bg_color.lch();
if (key && !me.chart().isHighlighted(key)) {
if (!colorCache[color + '-hl']) {
colorCache[color + '-hl'] = chroma.interpolate(key_color, bg_color, bg_lch[0] < 60 ? 0.7 : 0.63);
}
return colorCache[color + '-hl'];
}
return color;
}
me.getKeyColor = keyColor;
return keyColor(_key, _value, _useNegativeColor, _colorful);
},
setKeyColor: function(key, color) {
var me = this;
if (!me.__customColors) me.__customColors = {};
me.__customColors[key] = color;
},
getYTicks: function(yscale, h, noDomain, useLogScale) {
var me = this,
domain = yscale.domain(),
ticks = useLogScale ? dw.utils.logTicks(domain[0], domain[1]) : yscale.ticks(h / 80),
bt = yscale(ticks[0]),
tt = yscale(ticks[ticks.length - 1]);
if (!noDomain) {
if (Math.abs(yscale(domain[0]) - bt) < 30) ticks.shift();
if (Math.abs(tt - yscale(domain[1])) < 30) ticks.pop();
ticks.unshift(domain[0]);
ticks.push(domain[1]);
}
return ticks;
},
invertLabel: function(col) {
var c = chroma.color(col),
bg = chroma.color(this.theme().colors.background);
return bg.lab()[0] > 60 ? c.lab()[0] < 80 : c.lab()[0] > 60;
},
signature: function() {
var me = this,
sig = {
type: 'raphael-chart',
el: {}
};
$.each(me.__elements, function(key, elements) {
sig.el[key] = elements.length;
});
return sig;
},
addLegend: function(items, container) {
var me = this,
l = $('<div class="legend"></div>'),
xo = me.__canvas.lpad;
_.each(items, function(item) {
div = $('<div></div>');
div.css({
background: item.color,
width: 12,
height: 12,
position: 'absolute',
left: xo,
top: 1
});
l.append(div);
lbl = me.label(xo + 15, 0, item.label, {
valign: 'left',
root: l
});
xo += me.labelWidth(item.label) + 30;
});
l.css({
position: 'relative'
});
container.append(l);
},
optimizeLabelPositions: function(labels, pad, valign) {
if (!labels.length) return;
var i = 1,
c = valign == 'top' ? 0 : valign == 'middle' ? 0.5 : 1,
min_y = labels[0].el.parent().offset().top,
max_y = min_y + labels[0].el.parent().height();
labels = _.filter(labels, function(lbl) {
return lbl.el.is(":visible");
});
if (!labels.length) return;
_.each(labels, function(lbl) {
lbl.__noverlap = {
otop: lbl.top(),
top: lbl.top(),
dy: 0
};
lbl.height('auto');
});
(function loop() {
var overlap = false;
_.each(labels, function(lbl0, p) {
_.each(labels, function(lbl1, q) {
if (q > p) {
var l0 = lbl0.left(),
l1 = lbl1.left(),
r0 = l0 + lbl0.width(),
r1 = l1 + lbl1.width(),
t0 = lbl0.__noverlap.top - pad,
t1 = lbl1.__noverlap.top - pad,
b0 = t0 + lbl0.height() + pad * 2,
b1 = t1 + lbl1.height() + pad * 2,
dy, l0up;
if (!(l1 > r0 || r1 < l0 || t1 > b0 || b1 < t0)) {
overlap = true;
dy = Math.min(b0, b1) - Math.max(t0, t1);
l0up = t0 + (b0 - t0) * c < t1 + (b1 - t1) * c;
lbl0.__noverlap.dy += dy * 0.5 * (l0up ? -1 : 1);
lbl1.__noverlap.dy += dy * 0.5 * (l0up ? 1 : -1);
}
}
});
});
if (overlap) {
_.each(labels, function(lbl) {
lbl.__noverlap.top = Math.max(min_y, lbl.__noverlap.top + lbl.__noverlap.dy);
lbl.__noverlap.dy = 0;
});
}
if (overlap && ++i < 10) loop();
})();
_.each(labels, function(lbl) {
lbl.el.css({
top: lbl.__noverlap.top - lbl.el.parent().offset().top
});
});
},
checkBrowserCompatibility: function() {
return window['Raphael'] && Raphael.type;
},
clear: function() {
var me = this;
_.each(me.__elements, function(elements) {
_.each(elements, function(el) {
el.remove();
});
});
_.each(me.__labels, function(elements) {
_.each(elements, function(el) {
el.remove();
});
});
me.__elements = {};
me.__labels = {};
},
_svgCanvas: function() {
return this.__canvas.paper.canvas;
}
});
}).call(this);
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
(function() {
var MAX_LABEL_WIDTH = 160;
dw.visualization.register('bar-chart', 'raphael-chart', {
render: function(el) {
this.setRoot(el);
var me = this,
row = 0,
dataset = me.dataset,
sortBars = me.get('sort-values', false),
reverse = me.get('reverse-order');
me.axesDef = me.axes();
if (!me.axesDef) return;
if (!_.isUndefined(me.get('selected-row'))) {
row = me.get('selected-row', 0);
row = row > me.axesDef.bars.length ? 0 : row;
}
me.__lastRow = row;
if (!me.getBarColumn()) return;
var sliceColumns = _.map(me.axesDef.bars, function(i) {
return dataset.column(i);
}),
filter = dw.utils.filter(dw.utils.columnNameColumn(sliceColumns), row),
filterUI = filter.ui(me);
if (filterUI) {
$('#header').append(filterUI);
filter.change(function(val, i) {
me.__lastRow = i;
me.update(i);
});
}
var frameHeight = dw.utils.getMaxChartHeight(el) - 5,
chartHeight = 18 * 1.35 * me.getMaxNumberOfBars() + 5;
c = me.initCanvas({
h: Math.max(frameHeight, chartHeight)
});
$('body.chart').css('overflow-y', frameHeight > chartHeight ? 'hidden' : 'visible');
var barvalues = me.getBarValues(sortBars, reverse);
me.init();
me.initDimensions();
$('.tooltip').hide();
c.lastBarY = 0;
var barGroups = _.groupBy(barvalues, function(bar, i) {
bar.__i = i;
return Math.floor(i / 10);
});
var render = me.renderBar(row);
_.each(barGroups, function(bars) {
_.defer(function() {
_.each(bars, function(bar, i) {
render(bar, bar.__i);
});
complete();
});
});
function complete() {
if (me.__domain[0] < 0) {
var x = c.lpad + c.zero;
me.__yaxis = me.path('M' + [x, c.tpad] + 'V' + c.lastBarY, 'axis').attr(me.theme().yAxis);
}
el.mousemove(_.bind(me.onMouseMove, me));
me.renderingComplete();
}
},
renderBar: function(row) {
var me = this,
c = me.__canvas,
formatValue = me.chart().columnFormatter(me.getBarColumn());
return function(barv, s) {
var d = me.barDimensions(barv, s, row),
lpos = me.labelPosition(barv, s, row),
fill = me.getKeyColor(barv.name, barv.value, me.get('negative-color', false)),
stroke = chroma.color(fill).darken(14).hex();
var bar = me.registerElement(c.paper.rect(d.x, d.y, d.width, d.height).attr({
'stroke': stroke,
'fill': fill
}).data('strokeCol', stroke), barv.name);
if (me.theme().barChart.barAttrs) {
bar.attr(me.theme().barChart.barAttrs);
}
if (lpos.show_val) {
me.registerLabel(me.label(lpos.val_x, lpos.top, formatValue(barv.value, true), {
align: lpos.val_align,
cl: 'value' + lpos.lblClass
}), barv.name);
}
if (lpos.show_lbl) {
me.registerLabel(me.label(lpos.lbl_x, lpos.top, barv.name, {
w: Math.min(me.labelWidth(barv.name, 'series') + 20, MAX_LABEL_WIDTH),
align: lpos.lbl_align,
valign: 'middle',
cl: 'series' + lpos.lblClass
}), barv.name, me.axes().labels, barv.row);
}
c.lastBarY = Math.max(c.lastBarY, d.y + d.height);
};
},
getBarValues: function(sortBars, reverse, forceAll) {
var me = this,
values = [],
filter = me.__lastRow,
labels = me.axes(true).labels,
column = me.getBarColumn(filter),
filterMissing = !forceAll && me.get('filter-missing-values', true),
fmt = me.chart().columnFormatter(labels);
column.each(function(val, i) {
if (filterMissing && typeof val != 'number') return;
values.push({
name: fmt(labels.val(i)),
value: val,
row: i
});
});
if (sortBars) values.sort(function(a, b) {
return (isNaN(b.value) ? 0 : b.value) - (isNaN(a.value) ? 0 : a.value);
});
if (reverse) values.reverse();
return values;
},
getBarColumn: function() {
var me = this,
filter = me.__lastRow;
if (_.isUndefined(filter)) throw 'filter must not be undefined';
return me.axes(true).bars[filter];
},
getMaxNumberOfBars: function() {
var me = this,
filterMissing = me.get('filter-missing-values', true),
bars = me.axes(true).bars,
maxNum = 0;
if (!filterMissing) maxNum = bars[0].length;
else {
_.each(bars, function(bar) {
var notNaN = 0;
bar.each(function(val) {
if (typeof val == 'number') notNaN++;
});
maxNum = Math.max(maxNum, notNaN);
});
}
return maxNum;
},
update: function(row) {
var me = this,
formatValue = me.chart().columnFormatter(me.getBarColumn());
me.initDimensions();
_.each(me.__elements, function(elements) {
elements.__hide = true;
});
var render = me.renderBar(row);
_.each(me.getBarValues(me.get('sort-values', false), me.get('reverse-order')), function(bar, s) {
if (me.__elements[bar.name]) me.__elements[bar.name].__hide = false;
if (!me.__elements[bar.name]) {
render(bar, s);
}
_.each(me.__elements[bar.name], function(rect) {
var dim = me.barDimensions(bar, s, row);
dim.fill = me.getKeyColor(bar.name, bar.value, me.get('negative-color', false));
dim.stroke = chroma.color(dim.fill).darken(14).hex();
rect.animate(dim, me.theme().duration, me.theme().easing);
});
_.each(me.__labels[bar.name], function(lbl) {
var pos = me.labelPosition(bar, s, row),
lpos;
if (lbl.hasClass('value')) {
lbl.text(formatValue(bar.value, true));
lpos = {
halign: pos.val_align,
left: pos.val_x,
top: pos.top
};
} else if (lbl.hasClass('series')) {
lpos = {
halign: pos.lbl_align,
left: pos.lbl_x,
top: pos.top
};
}
if (lpos) {
lbl.animate({
align: lpos.halign,
x: lpos.left,
y: lpos.top
}, me.theme().duration, me.theme().easing);
}
});
});
if (me.__domain[0] < 0) {
var c = me.__canvas,
x = c.lpad + c.zero,
p = 'M' + [x, c.tpad] + 'V' + c.lastBarY;
if (me.__yaxis) {
me.__yaxis.animate({
path: p,
opacity: 1
}, me.theme().duration, me.theme().easing);
} else {
me.__yaxis = me.path(p, 'axis').attr(me.theme().yAxis);
}
} else if (me.__yaxis) {
me.__yaxis.animate({
opacity: 0
}, me.theme().duration * 0.5, me.theme().easing);
}
_.each(me.__elements, function(elements, k) {
if (elements.__hide) {
_.each(elements, function(el) {
if (el && el.hide) el.hide();
});
_.each(me.__labels[k], function(el) {
if (el && el.hide) el.hide();
});
} else {
_.each(elements, function(el) {
if (el && el.show) el.show();
});
_.each(me.__labels[k], function(el) {
if (el && el.show) el.show();
});
}
});
},
initDimensions: function() {
var me = this,
c = me.__canvas,
w = c.w - c.lpad - c.rpad - 30,
column = me.getBarColumn(),
bars = me.getBarValues(false, false, true),
formatValue = me.chart().columnFormatter(column),
domain = me.get('absolute-scale', false) ? dw.utils.minMax(_.map(me.axesDef.bars, function(c) {
return me.dataset.column(c);
})) : column.range();
if (domain[0] > 0) domain[0] = 0;
if (domain[1] < 0) domain[1] = 0;
me.__domain = domain;
me.__scales = {
y: d3.scale.linear().domain(domain)
};
var maxw = [0, 0, 0, 0],
ratio, largestVal = [0, 0],
lw;
_.each(bars, function(bar) {
if (isNaN(bar.value)) return;
var neg = bar.value < 0;
largestVal[neg ? 1 : 0] = Math.max(largestVal[neg ? 1 : 0], Math.abs(bar.value));
});
me.__longLabels = false;
_.each(_.first(bars, 50), function(bar) {
if (isNaN(bar.value)) return;
var neg = bar.value < 0,
t = neg ? 2 : 0,
bw;
bw = Math.abs(bar.value) / (largestVal[0] + largestVal[1]) * w;
lw = me.labelWidth(bar.name, 'series');
if (lw > MAX_LABEL_WIDTH) me.__longLabels = true;
maxw[t] = Math.max(maxw[t], Math.min(lw, MAX_LABEL_WIDTH) + 20);
maxw[t + 1] = Math.max(maxw[t + 1], me.labelWidth(me.chart().formatValue(bar.value, true), 'value') + 20 + bw);
});
c.left = 0;
c.right = 0;
c.zero = largestVal[1] / (largestVal[0] + largestVal[1]) * w;
var maxNegBar = c.zero;
c.left = Math.max(maxw[0], maxw[3]) - c.zero;
c.right = Math.max(maxw[1], maxw[2]) - (w - c.zero);
w -= c.left + c.right;
c.zero = c.left + largestVal[1] / (largestVal[0] + largestVal[1]) * w;
c.maxSeriesLabelWidth = [maxw[0], maxw[2]];
c.maxValueLabelWidth = [maxw[1], maxw[3]];
me.__scales.y.rangeRound([c.lpad, w]);
},
barDimensions: function(bar, s, r) {
var me = this,
w, h, x, y, i, cw, n = me.getMaxNumberOfBars(),
sc = me.__scales,
c = me.__canvas,
bw, pad = 0.35,
vspace = 0.1,
val = bar.value;
if (isNaN(val)) val = 0;
cw = c.h - c.bpad - c.tpad;
bw = 18;
w = sc.y(val) - sc.y(0);
h = bw;
if (w > 0) {
x = c.lpad + c.zero;
} else {
x = c.lpad + c.zero + w;
w *= -1;
}
if (val !== 0) w = Math.max(1, w);
y = Math.round(c.tpad + s * (bw + bw * pad));
return {
width: w,
height: h,
x: x,
y: y
};
},
labelPosition: function(bar, s, r) {
var me = this,
d = me.barDimensions(bar, s, r),
formatValue = me.chart().columnFormatter(me.getBarColumn()),
c = me.__canvas,
val = bar.value,
lbl_left = val >= 0 || isNaN(val),
lbl_x = lbl_left ? c.zero - 10 : c.zero + 10,
lbl_align = lbl_left ? 'right' : 'left',
val_x = lbl_left ? d.x + d.width + 10 : d.x - 10,
val_align = lbl_left ? 'left' : 'right',
show_lbl = true,
show_val = true,
lblClass = me.chart().hasHighlight() && me.chart().isHighlighted(bar) ? ' highlighted' : '';
if (me.__longLabels && me.__domain[0] >= 0) {
lbl_align = lbl_left ? 'left' : 'right';
lbl_x = c.lpad;
}
return {
lblClass: lblClass,
val_align: val_align,
show_lbl: show_lbl,
show_val: show_val,
lbl_align: lbl_align,
lbl_x: lbl_x,
val_x: val_x,
top: d.y + d.height * 0.5
};
},
getDataRowByPoint: function(x, y) {
return 0;
},
showTooltip: function() {},
hideTooltip: function() {},
hover: function(hover_key) {
var me = this,
barvalues = me.getBarValues(),
l = barvalues.length;
_.each(barvalues, function(bar) {
_.each(me.__labels[bar.name], function(lbl) {
if (hover_key !== undefined && bar.name == hover_key) {
lbl.addClass('hover');
} else {
lbl.removeClass('hover');
}
});
if (l > 50) return;
_.each(me.__elements[bar.name], function(el) {
var fill = me.getKeyColor(bar.name, bar.value, me.get('negative-color', false)),
stroke;
if (hover_key !== undefined && bar.name == hover_key) fill = chroma.color(fill).darken(14).hex();
stroke = chroma.color(fill).darken(14).hex();
if (el.attrs.fill != fill || el.attrs.stroke != stroke)
el.animate({
fill: fill,
stroke: stroke
}, 50);
});
});
},
unhoverSeries: function() {
this.hoverSeries();
}
});
}).call(this);
! function(glob) {
var version = "0.4.2",
has = "hasOwnProperty",
separator = /[\.\/]/,
wildcard = "*",
fun = function() {},
numsort = function(a, b) {
return a - b
},
current_event, stop, events = {
n: {}
},
eve = function(name, scope) {
name = String(name);
var e = events,
oldstop = stop,
args = Array.prototype.slice.call(arguments, 2),
listeners = eve.listeners(name),
z = 0,
f = false,
l, indexed = [],
queue = {},
out = [],
ce = current_event,
errors = [];
current_event = name;
stop = 0;
for (var i = 0, ii = listeners.length; i < ii; i++)
if ("zIndex" in listeners[i]) {
indexed.push(listeners[i].zIndex);
if (listeners[i].zIndex < 0) {
queue[listeners[i].zIndex] = listeners[i]
}
}
indexed.sort(numsort);
while (indexed[z] < 0) {
l = queue[indexed[z++]];
out.push(l.apply(scope, args));
if (stop) {
stop = oldstop;
return out
}
}
for (i = 0; i < ii; i++) {
l = listeners[i];
if ("zIndex" in l) {
if (l.zIndex == indexed[z]) {
out.push(l.apply(scope, args));
if (stop) {
break
}
do {
z++;
l = queue[indexed[z]];
l && out.push(l.apply(scope, args));
if (stop) {
break
}
} while (l)
} else {
queue[l.zIndex] = l
}
} else {
out.push(l.apply(scope, args));
if (stop) {
break
}
}
}
stop = oldstop;
current_event = ce;
return out.length ? out : null
};
eve._events = events;
eve.listeners = function(name) {
var names = name.split(separator),
e = events,
item, items, k, i, ii, j, jj, nes, es = [e],
out = [];
for (i = 0, ii = names.length; i < ii; i++) {
nes = [];
for (j = 0, jj = es.length; j < jj; j++) {
e = es[j].n;
items = [e[names[i]], e[wildcard]];
k = 2;
while (k--) {
item = items[k];
if (item) {
nes.push(item);
out = out.concat(item.f || [])
}
}
}
es = nes
}
return out
};
eve.on = function(name, f) {
name = String(name);
if (typeof f != "function") {
return function() {}
}
var names = name.split(separator),
e = events;
for (var i = 0, ii = names.length; i < ii; i++) {
e = e.n;
e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {
n: {}
})
}
e.f = e.f || [];
for (i = 0, ii = e.f.length; i < ii; i++)
if (e.f[i] == f) {
return fun
}
e.f.push(f);
return function(zIndex) {
if (+zIndex == +zIndex) {
f.zIndex = +zIndex
}
}
};
eve.f = function(event) {
var attrs = [].slice.call(arguments, 1);
return function() {
eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0)))
}
};
eve.stop = function() {
stop = 1
};
eve.nt = function(subname) {
if (subname) {
return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event)
}
return current_event
};
eve.nts = function() {
return current_event.split(separator)
};
eve.off = eve.unbind = function(name, f) {
if (!name) {
eve._events = events = {
n: {}
};
return
}
var names = name.split(separator),
e, key, splice, i, ii, j, jj, cur = [events];
for (i = 0, ii = names.length; i < ii; i++) {
for (j = 0; j < cur.length; j += splice.length - 2) {
splice = [j, 1];
e = cur[j].n;
if (names[i] != wildcard) {
if (e[names[i]]) {
splice.push(e[names[i]])
}
} else {
for (key in e)
if (e[has](key)) {
splice.push(e[key])
}
}
cur.splice.apply(cur, splice)
}
}
for (i = 0, ii = cur.length; i < ii; i++) {
e = cur[i];
while (e.n) {
if (f) {
if (e.f) {
for (j = 0, jj = e.f.length; j < jj; j++)
if (e.f[j] == f) {
e.f.splice(j, 1);
break
}!e.f.length && delete e.f
}
for (key in e.n)
if (e.n[has](key) && e.n[key].f) {
var funcs = e.n[key].f;
for (j = 0, jj = funcs.length; j < jj; j++)
if (funcs[j] == f) {
funcs.splice(j, 1);
break
}!funcs.length && delete e.n[key].f
}
} else {
delete e.f;
for (key in e.n)
if (e.n[has](key) && e.n[key].f) {
delete e.n[key].f
}
}
e = e.n
}
}
};
eve.once = function(name, f) {
var f2 = function() {
eve.unbind(name, f2);
return f.apply(this, arguments)
};
return eve.on(name, f2)
};
eve.version = version;
eve.toString = function() {
return "You are running Eve " + version
};
typeof module != "undefined" && module.exports ? module.exports = eve : typeof define != "undefined" ? define("eve", [], function() {
return eve
}) : glob.eve = eve
}(this);
! function(glob, factory) {
if (typeof define === "function" && define.amd) {
define(["eve"], function(eve) {
return factory(glob, eve)
})
} else {
factory(glob, glob.eve)
}
}(this, function(window, eve) {
function R(first) {
if (R.is(first, "function")) {
return loaded ? first() : eve.on("raphael.DOMload", first)
} else if (R.is(first, array)) {
return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first)
} else {
var args = Array.prototype.slice.call(arguments, 0);
if (R.is(args[args.length - 1], "function")) {
var f = args.pop();
return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function() {
f.call(R._engine.create[apply](R, args))
})
} else {
return R._engine.create[apply](R, arguments)
}
}
}
R.version = "2.1.2";
R.eve = eve;
var loaded, separator = /[, ]+/,
elements = {
circle: 1,
rect: 1,
path: 1,
ellipse: 1,
text: 1,
image: 1
},
formatrg = /\{(\d+)\}/g,
proto = "prototype",
has = "hasOwnProperty",
g = {
doc: document,
win: window
},
oldRaphael = {
was: Object.prototype[has].call(g.win, "Raphael"),
is: g.win.Raphael
},
Paper = function() {
this.ca = this.customAttributes = {}
},
paperproto, appendChild = "appendChild",
apply = "apply",
concat = "concat",
supportsTouch = "ontouchstart" in g.win || g.win.DocumentTouch && g.doc instanceof DocumentTouch,
E = "",
S = " ",
Str = String,
split = "split",
events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel" [split](S),
touchMap = {
mousedown: "touchstart",
mousemove: "touchmove",
mouseup: "touchend"
},
lowerCase = Str.prototype.toLowerCase,
math = Math,
mmax = math.max,
mmin = math.min,
abs = math.abs,
pow = math.pow,
PI = math.PI,
nu = "number",
string = "string",
array = "array",
toString = "toString",
fillString = "fill",
objectToString = Object.prototype.toString,
paper = {},
push = "push",
ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i,
colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,
isnan = {
NaN: 1,
Infinity: 1,
"-Infinity": 1
},
bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,
round = math.round,
setAttribute = "setAttribute",
toFloat = parseFloat,
toInt = parseInt,
upperCase = Str.prototype.toUpperCase,
availableAttrs = R._availableAttrs = {
"arrow-end": "none",
"arrow-start": "none",
blur: 0,
"clip-rect": "0 0 1e9 1e9",
cursor: "default",
cx: 0,
cy: 0,
fill: "#fff",
"fill-opacity": 1,
font: '10px "Arial"',
"font-family": '"Arial"',
"font-size": "10",
"font-style": "normal",
"font-weight": 400,
gradient: 0,
height: 0,
href: "http://raphaeljs.com/",
"letter-spacing": 0,
opacity: 1,
path: "M0,0",
r: 0,
rx: 0,
ry: 0,
src: "",
stroke: "#000",
"stroke-dasharray": "",
"stroke-linecap": "butt",
"stroke-linejoin": "butt",
"stroke-miterlimit": 0,
"stroke-opacity": 1,
"stroke-width": 1,
target: "_blank",
"text-anchor": "middle",
title: "Raphael",
transform: "",
width: 0,
x: 0,
y: 0
},
availableAnimAttrs = R._availableAnimAttrs = {
blur: nu,
"clip-rect": "csv",
cx: nu,
cy: nu,
fill: "colour",
"fill-opacity": nu,
"font-size": nu,
height: nu,
opacity: nu,
path: "path",
r: nu,
rx: nu,
ry: nu,
stroke: "colour",
"stroke-opacity": nu,
"stroke-width": nu,
transform: "transform",
width: nu,
x: nu,
y: nu
},
whitespace = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g,
commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,
hsrg = {
hs: 1,
rg: 1
},
p2s = /,?([achlmqrstvxz]),?/gi,
pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,
tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,
pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/gi,
radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,
eldata = {},
sortByKey = function(a, b) {
return a.key - b.key
},
sortByNumber = function(a, b) {
return toFloat(a) - toFloat(b)
},
fun = function() {},
pipe = function(x) {
return x
},
rectPath = R._rectPath = function(x, y, w, h, r) {
if (r) {
return [
["M", x + r, y],
["l", w - r * 2, 0],
["a", r, r, 0, 0, 1, r, r],
["l", 0, h - r * 2],
["a", r, r, 0, 0, 1, -r, r],
["l", r * 2 - w, 0],
["a", r, r, 0, 0, 1, -r, -r],
["l", 0, r * 2 - h],
["a", r, r, 0, 0, 1, r, -r],
["z"]
]
}
return [
["M", x, y],
["l", w, 0],
["l", 0, h],
["l", -w, 0],
["z"]
]
},
ellipsePath = function(x, y, rx, ry) {
if (ry == null) {
ry = rx
}
return [
["M", x, y],
["m", 0, -ry],
["a", rx, ry, 0, 1, 1, 0, 2 * ry],
["a", rx, ry, 0, 1, 1, 0, -2 * ry],
["z"]
]
},
getPath = R._getPath = {
path: function(el) {
return el.attr("path")
},
circle: function(el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.r)
},
ellipse: function(el) {
var a = el.attrs;
return ellipsePath(a.cx, a.cy, a.rx, a.ry)
},
rect: function(el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height, a.r)
},
image: function(el) {
var a = el.attrs;
return rectPath(a.x, a.y, a.width, a.height)
},
text: function(el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height)
},
set: function(el) {
var bbox = el._getBBox();
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height)
}
},
mapPath = R.mapPath = function(path, matrix) {
if (!matrix) {
return path
}
var x, y, i, j, ii, jj, pathi;
path = path2curve(path);
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i];
for (j = 1, jj = pathi.length; j < jj; j += 2) {
x = matrix.x(pathi[j], pathi[j + 1]);
y = matrix.y(pathi[j], pathi[j + 1]);
pathi[j] = x;
pathi[j + 1] = y
}
}
return path
};
R._g = g;
R.type = g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML";
if (R.type == "VML") {
var d = g.doc.createElement("div"),
b;
d.innerHTML = '<v:shape adj="1"/>';
b = d.firstChild;
b.style.behavior = "url(#default#VML)";
if (!(b && typeof b.adj == "object")) {
return R.type = E
}
d = null
}
R.svg = !(R.vml = R.type == "VML");
R._Paper = Paper;
R.fn = paperproto = Paper.prototype = R.prototype;
R._id = 0;
R._oid = 0;
R.is = function(o, type) {
type = lowerCase.call(type);
if (type == "finite") {
return !isnan[has](+o)
}
if (type == "array") {
return o instanceof Array
}
return type == "null" && o === null || type == typeof o && o !== null || type == "object" && o === Object(o) || type == "array" && Array.isArray && Array.isArray(o) || objectToString.call(o).slice(8, -1).toLowerCase() == type
};
function clone(obj) {
if (typeof obj == "function" || Object(obj) !== obj) {
return obj
}
var res = new obj.constructor;
for (var key in obj)
if (obj[has](key)) {
res[key] = clone(obj[key])
}
return res
}
R.angle = function(x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
var x = x1 - x2,
y = y1 - y2;
if (!x && !y) {
return 0
}
return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360
} else {
return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3)
}
};
R.rad = function(deg) {
return deg % 360 * PI / 180
};
R.deg = function(rad) {
return rad * 180 / PI % 360
};
R.snapTo = function(values, value, tolerance) {
tolerance = R.is(tolerance, "finite") ? tolerance : 10;
if (R.is(values, array)) {
var i = values.length;
while (i--)
if (abs(values[i] - value) <= tolerance) {
return values[i]
}
} else {
values = +values;
var rem = value % values;
if (rem < tolerance) {
return value - rem
}
if (rem > values - tolerance) {
return value - rem + values
}
}
return value
};
var createUUID = R.createUUID = function(uuidRegEx, uuidReplacer) {
return function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase()
}
}(/[xy]/g, function(c) {
var r = math.random() * 16 | 0,
v = c == "x" ? r : r & 3 | 8;
return v.toString(16)
});
R.setWindow = function(newwin) {
eve("raphael.setWindow", R, g.win, newwin);
g.win = newwin;
g.doc = g.win.document;
if (R._engine.initWin) {
R._engine.initWin(g.win)
}
};
var toHex = function(color) {
if (R.vml) {
var trim = /^\s+|\s+$/g;
var bod;
try {
var docum = new ActiveXObject("htmlfile");
docum.write("<body>");
docum.close();
bod = docum.body
} catch (e) {
bod = createPopup().document.body
}
var range = bod.createTextRange();
toHex = cacher(function(color) {
try {
bod.style.color = Str(color).replace(trim, E);
var value = range.queryCommandValue("ForeColor");
value = (value & 255) << 16 | value & 65280 | (value & 16711680) >>> 16;
return "#" + ("000000" + value.toString(16)).slice(-6)
} catch (e) {
return "none"
}
})
} else {
var i = g.doc.createElement("i");
i.title = "Raphaël Colour Picker";
i.style.display = "none";
g.doc.body.appendChild(i);
toHex = cacher(function(color) {
i.style.color = color;
return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color")
})
}
return toHex(color)
},
hsbtoString = function() {
return "hsb(" + [this.h, this.s, this.b] + ")"
},
hsltoString = function() {
return "hsl(" + [this.h, this.s, this.l] + ")"
},
rgbtoString = function() {
return this.hex
},
prepareRGB = function(r, g, b) {
if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) {
b = r.b;
g = r.g;
r = r.r
}
if (g == null && R.is(r, string)) {
var clr = R.getRGB(r);
r = clr.r;
g = clr.g;
b = clr.b
}
if (r > 1 || g > 1 || b > 1) {
r /= 255;
g /= 255;
b /= 255
}
return [r, g, b]
},
packageRGB = function(r, g, b, o) {
r *= 255;
g *= 255;
b *= 255;
var rgb = {
r: r,
g: g,
b: b,
hex: R.rgb(r, g, b),
toString: rgbtoString
};
R.is(o, "finite") && (rgb.opacity = o);
return rgb
};
R.color = function(clr) {
var rgb;
if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) {
rgb = R.hsb2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex
} else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) {
rgb = R.hsl2rgb(clr);
clr.r = rgb.r;
clr.g = rgb.g;
clr.b = rgb.b;
clr.hex = rgb.hex
} else {
if (R.is(clr, "string")) {
clr = R.getRGB(clr)
}
if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) {
rgb = R.rgb2hsl(clr);
clr.h = rgb.h;
clr.s = rgb.s;
clr.l = rgb.l;
rgb = R.rgb2hsb(clr);
clr.v = rgb.b
} else {
clr = {
hex: "none"
};
clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1
}
}
clr.toString = rgbtoString;
return clr
};
R.hsb2rgb = function(h, s, v, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) {
v = h.b;
s = h.s;
h = h.h;
o = h.o
}
h *= 360;
var R, G, B, X, C;
h = h % 360 / 60;
C = v * s;
X = C * (1 - abs(h % 2 - 1));
R = G = B = v - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o)
};
R.hsl2rgb = function(h, s, l, o) {
if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) {
l = h.l;
s = h.s;
h = h.h
}
if (h > 1 || s > 1 || l > 1) {
h /= 360;
s /= 100;
l /= 100
}
h *= 360;
var R, G, B, X, C;
h = h % 360 / 60;
C = 2 * s * (l < .5 ? l : 1 - l);
X = C * (1 - abs(h % 2 - 1));
R = G = B = l - C / 2;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return packageRGB(R, G, B, o)
};
R.rgb2hsb = function(r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, V, C;
V = mmax(r, g, b);
C = V - mmin(r, g, b);
H = C == 0 ? null : V == r ? (g - b) / C : V == g ? (b - r) / C + 2 : (r - g) / C + 4;
H = (H + 360) % 6 * 60 / 360;
S = C == 0 ? 0 : C / V;
return {
h: H,
s: S,
b: V,
toString: hsbtoString
}
};
R.rgb2hsl = function(r, g, b) {
b = prepareRGB(r, g, b);
r = b[0];
g = b[1];
b = b[2];
var H, S, L, M, m, C;
M = mmax(r, g, b);
m = mmin(r, g, b);
C = M - m;
H = C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : (r - g) / C + 4;
H = (H + 360) % 6 * 60 / 360;
L = (M + m) / 2;
S = C == 0 ? 0 : L < .5 ? C / (2 * L) : C / (2 - 2 * L);
return {
h: H,
s: S,
l: L,
toString: hsltoString
}
};
R._path2string = function() {
return this.join(",").replace(p2s, "$1")
};
function repush(array, item) {
for (var i = 0, ii = array.length; i < ii; i++)
if (array[i] === item) {
return array.push(array.splice(i, 1)[0])
}
}
function cacher(f, scope, postprocessor) {
function newf() {
var arg = Array.prototype.slice.call(arguments, 0),
args = arg.join("␀"),
cache = newf.cache = newf.cache || {},
count = newf.count = newf.count || [];
if (cache[has](args)) {
repush(count, args);
return postprocessor ? postprocessor(cache[args]) : cache[args]
}
count.length >= 1e3 && delete cache[count.shift()];
count.push(args);
cache[args] = f[apply](scope, arg);
return postprocessor ? postprocessor(cache[args]) : cache[args]
}
return newf
}
var preload = R._preload = function(src, f) {
var img = g.doc.createElement("img");
img.style.cssText = "position:absolute;left:-9999em;top:-9999em";
img.onload = function() {
f.call(this);
this.onload = null;
g.doc.body.removeChild(this)
};
img.onerror = function() {
g.doc.body.removeChild(this)
};
g.doc.body.appendChild(img);
img.src = src
};
function clrToString() {
return this.hex
}
R.getRGB = cacher(function(colour) {
if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) {
return {
r: -1,
g: -1,
b: -1,
hex: "none",
error: 1,
toString: clrToString
}
}
if (colour == "none") {
return {
r: -1,
g: -1,
b: -1,
hex: "none",
toString: clrToString
}
}!(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour));
var res, red, green, blue, opacity, t, values, rgb = colour.match(colourRegExp);
if (rgb) {
if (rgb[2]) {
blue = toInt(rgb[2].substring(5), 16);
green = toInt(rgb[2].substring(3, 5), 16);
red = toInt(rgb[2].substring(1, 3), 16)
}
if (rgb[3]) {
blue = toInt((t = rgb[3].charAt(3)) + t, 16);
green = toInt((t = rgb[3].charAt(2)) + t, 16);
red = toInt((t = rgb[3].charAt(1)) + t, 16)
}
if (rgb[4]) {
values = rgb[4][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100)
}
if (rgb[5]) {
values = rgb[5][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "°") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsb2rgb(red, green, blue, opacity)
}
if (rgb[6]) {
values = rgb[6][split](commaSpaces);
red = toFloat(values[0]);
values[0].slice(-1) == "%" && (red *= 2.55);
green = toFloat(values[1]);
values[1].slice(-1) == "%" && (green *= 2.55);
blue = toFloat(values[2]);
values[2].slice(-1) == "%" && (blue *= 2.55);
(values[0].slice(-3) == "deg" || values[0].slice(-1) == "°") && (red /= 360);
rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3]));
values[3] && values[3].slice(-1) == "%" && (opacity /= 100);
return R.hsl2rgb(red, green, blue, opacity)
}
rgb = {
r: red,
g: green,
b: blue,
toString: clrToString
};
rgb.hex = "#" + (16777216 | blue | green << 8 | red << 16).toString(16).slice(1);
R.is(opacity, "finite") && (rgb.opacity = opacity);
return rgb
}
return {
r: -1,
g: -1,
b: -1,
hex: "none",
error: 1,
toString: clrToString
}
}, R);
R.hsb = cacher(function(h, s, b) {
return R.hsb2rgb(h, s, b).hex
});
R.hsl = cacher(function(h, s, l) {
return R.hsl2rgb(h, s, l).hex
});
R.rgb = cacher(function(r, g, b) {
return "#" + (16777216 | b | g << 8 | r << 16).toString(16).slice(1)
});
R.getColor = function(value) {
var start = this.getColor.start = this.getColor.start || {
h: 0,
s: 1,
b: value || .75
},
rgb = this.hsb2rgb(start.h, start.s, start.b);
start.h += .075;
if (start.h > 1) {
start.h = 0;
start.s -= .2;
start.s <= 0 && (this.getColor.start = {
h: 0,
s: 1,
b: start.b
})
}
return rgb.hex
};
R.getColor.reset = function() {
delete this.start
};
function catmullRom2bezier(crp, z) {
var d = [];
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [{
x: +crp[i - 2],
y: +crp[i - 1]
}, {
x: +crp[i],
y: +crp[i + 1]
}, {
x: +crp[i + 2],
y: +crp[i + 3]
}, {
x: +crp[i + 4],
y: +crp[i + 5]
}];
if (z) {
if (!i) {
p[0] = {
x: +crp[iLen - 2],
y: +crp[iLen - 1]
}
} else if (iLen - 4 == i) {
p[3] = {
x: +crp[0],
y: +crp[1]
}
} else if (iLen - 2 == i) {
p[2] = {
x: +crp[0],
y: +crp[1]
};
p[3] = {
x: +crp[2],
y: +crp[3]
}
}
} else {
if (iLen - 4 == i) {
p[3] = p[2]
} else if (!i) {
p[0] = {
x: +crp[i],
y: +crp[i + 1]
}
}
}
d.push(["C", (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y])
}
return d
}
R.parsePathString = function(pathString) {
if (!pathString) {
return null
}
var pth = paths(pathString);
if (pth.arr) {
return pathClone(pth.arr)
}
var paramCounts = {
a: 7,
c: 6,
h: 1,
l: 2,
m: 2,
r: 4,
q: 4,
s: 4,
t: 2,
v: 1,
z: 0
},
data = [];
if (R.is(pathString, array) && R.is(pathString[0], array)) {
data = pathClone(pathString)
}
if (!data.length) {
Str(pathString).replace(pathCommand, function(a, b, c) {
var params = [],
name = b.toLowerCase();
c.replace(pathValues, function(a, b) {
b && params.push(+b)
});
if (name == "m" && params.length > 2) {
data.push([b][concat](params.splice(0, 2)));
name = "l";
b = b == "m" ? "l" : "L"
}
if (name == "r") {
data.push([b][concat](params))
} else
while (params.length >= paramCounts[name]) {
data.push([b][concat](params.splice(0, paramCounts[name])));
if (!paramCounts[name]) {
break
}
}
})
}
data.toString = R._path2string;
pth.arr = pathClone(data);
return data
};
R.parseTransformString = cacher(function(TString) {
if (!TString) {
return null
}
var paramCounts = {
r: 3,
s: 4,
t: 2,
m: 6
},
data = [];
if (R.is(TString, array) && R.is(TString[0], array)) {
data = pathClone(TString)
}
if (!data.length) {
Str(TString).replace(tCommand, function(a, b, c) {
var params = [],
name = lowerCase.call(b);
c.replace(pathValues, function(a, b) {
b && params.push(+b)
});
data.push([b][concat](params))
})
}
data.toString = R._path2string;
return data
});
var paths = function(ps) {
var p = paths.ps = paths.ps || {};
if (p[ps]) {
p[ps].sleep = 100
} else {
p[ps] = {
sleep: 100
}
}
setTimeout(function() {
for (var key in p)
if (p[has](key) && key != ps) {
p[key].sleep--;
!p[key].sleep && delete p[key]
}
});
return p[ps]
};
R.findDotsAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t,
t13 = pow(t1, 3),
t12 = pow(t1, 2),
t2 = t * t,
t3 = t2 * t,
x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x,
y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y,
mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x),
my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y),
nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x),
ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y),
ax = t1 * p1x + t * c1x,
ay = t1 * p1y + t * c1y,
cx = t1 * c2x + t * p2x,
cy = t1 * c2y + t * p2y,
alpha = 90 - math.atan2(mx - nx, my - ny) * 180 / PI;
(mx > nx || my < ny) && (alpha += 180);
return {
x: x,
y: y,
m: {
x: mx,
y: my
},
n: {
x: nx,
y: ny
},
start: {
x: ax,
y: ay
},
end: {
x: cx,
y: cy
},
alpha: alpha
}
};
R.bezierBBox = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
if (!R.is(p1x, "array")) {
p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]
}
var bbox = curveDim.apply(null, p1x);
return {
x: bbox.min.x,
y: bbox.min.y,
x2: bbox.max.x,
y2: bbox.max.y,
width: bbox.max.x - bbox.min.x,
height: bbox.max.y - bbox.min.y
}
};
R.isPointInsideBBox = function(bbox, x, y) {
return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2
};
R.isBBoxIntersect = function(bbox1, bbox2) {
var i = R.isPointInsideBBox;
return i(bbox2, bbox1.x, bbox1.y) || i(bbox2, bbox1.x2, bbox1.y) || i(bbox2, bbox1.x, bbox1.y2) || i(bbox2, bbox1.x2, bbox1.y2) || i(bbox1, bbox2.x, bbox2.y) || i(bbox1, bbox2.x2, bbox2.y) || i(bbox1, bbox2.x, bbox2.y2) || i(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y)
};
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3;
return t * t2 - 3 * p1 + 3 * p2
}
function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) {
if (z == null) {
z = 1
}
z = z > 1 ? 1 : z < 0 ? 0 : z;
var z2 = z / 2,
n = 12,
Tvalues = [-.1252, .1252, -.3678, .3678, -.5873, .5873, -.7699, .7699, -.9041, .9041, -.9816, .9816],
Cvalues = [.2491, .2491, .2335, .2335, .2032, .2032, .1601, .1601, .1069, .1069, .0472, .0472],
sum = 0;
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase;
sum += Cvalues[i] * math.sqrt(comb)
}
return z2 * sum
}
function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return
}
var t = 1,
step = t / 2,
t2 = t - step,
l, e = .01;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2);
while (abs(l - ll) > e) {
step /= 2;
t2 += (l < ll ? 1 : -1) * step;
l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2)
}
return t2
}
function intersect(x1, y1, x2, y2, x3, y3, x4, y4) {
if (mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || mmax(y1, y2) < mmin(y3, y4) || mmin(y1, y2) > mmax(y3, y4)) {
return
}
var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (!denominator) {
return
}
var px = nx / denominator,
py = ny / denominator,
px2 = +px.toFixed(2),
py2 = +py.toFixed(2);
if (px2 < +mmin(x1, x2).toFixed(2) || px2 > +mmax(x1, x2).toFixed(2) || px2 < +mmin(x3, x4).toFixed(2) || px2 > +mmax(x3, x4).toFixed(2) || py2 < +mmin(y1, y2).toFixed(2) || py2 > +mmax(y1, y2).toFixed(2) || py2 < +mmin(y3, y4).toFixed(2) || py2 > +mmax(y3, y4).toFixed(2)) {
return
}
return {
x: px,
y: py
}
}
function inter(bez1, bez2) {
return interHelper(bez1, bez2)
}
function interCount(bez1, bez2) {
return interHelper(bez1, bez2, 1)
}
function interHelper(bez1, bez2, justCount) {
var bbox1 = R.bezierBBox(bez1),
bbox2 = R.bezierBBox(bez2);
if (!R.isBBoxIntersect(bbox1, bbox2)) {
return justCount ? 0 : []
}
var l1 = bezlen.apply(0, bez1),
l2 = bezlen.apply(0, bez2),
n1 = mmax(~~(l1 / 5), 1),
n2 = mmax(~~(l2 / 5), 1),
dots1 = [],
dots2 = [],
xy = {},
res = justCount ? 0 : [];
for (var i = 0; i < n1 + 1; i++) {
var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1));
dots1.push({
x: p.x,
y: p.y,
t: i / n1
})
}
for (i = 0; i < n2 + 1; i++) {
p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2));
dots2.push({
x: p.x,
y: p.y,
t: i / n2
})
}
for (i = 0; i < n1; i++) {
for (var j = 0; j < n2; j++) {
var di = dots1[i],
di1 = dots1[i + 1],
dj = dots2[j],
dj1 = dots2[j + 1],
ci = abs(di1.x - di.x) < .001 ? "y" : "x",
cj = abs(dj1.x - dj.x) < .001 ? "y" : "x",
is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y);
if (is) {
if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) {
continue
}
xy[is.x.toFixed(4)] = is.y.toFixed(4);
var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t);
if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) {
if (justCount) {
res++
} else {
res.push({
x: is.x,
y: is.y,
t1: mmin(t1, 1),
t2: mmin(t2, 1)
})
}
}
}
}
}
return res
}
R.pathIntersection = function(path1, path2) {
return interPathHelper(path1, path2)
};
R.pathIntersectionNumber = function(path1, path2) {
return interPathHelper(path1, path2, 1)
};
function interPathHelper(path1, path2, justCount) {
path1 = R._path2curve(path1);
path2 = R._path2curve(path2);
var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, res = justCount ? 0 : [];
for (var i = 0, ii = path1.length; i < ii; i++) {
var pi = path1[i];
if (pi[0] == "M") {
x1 = x1m = pi[1];
y1 = y1m = pi[2]
} else {
if (pi[0] == "C") {
bez1 = [x1, y1].concat(pi.slice(1));
x1 = bez1[6];
y1 = bez1[7]
} else {
bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m];
x1 = x1m;
y1 = y1m
}
for (var j = 0, jj = path2.length; j < jj; j++) {
var pj = path2[j];
if (pj[0] == "M") {
x2 = x2m = pj[1];
y2 = y2m = pj[2]
} else {
if (pj[0] == "C") {
bez2 = [x2, y2].concat(pj.slice(1));
x2 = bez2[6];
y2 = bez2[7]
} else {
bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m];
x2 = x2m;
y2 = y2m
}
var intr = interHelper(bez1, bez2, justCount);
if (justCount) {
res += intr
} else {
for (var k = 0, kk = intr.length; k < kk; k++) {
intr[k].segment1 = i;
intr[k].segment2 = j;
intr[k].bez1 = bez1;
intr[k].bez2 = bez2
}
res = res.concat(intr)
}
}
}
}
}
return res
}
R.isPointInsidePath = function(path, x, y) {
var bbox = R.pathBBox(path);
return R.isPointInsideBBox(bbox, x, y) && interPathHelper(path, [
["M", x, y],
["H", bbox.x2 + 10]
], 1) % 2 == 1
};
R._removedFactory = function(methodname) {
return function() {
eve("raphael.log", null, "Raphaël: you are calling to method “" + methodname + "” of removed object", methodname)
}
};
var pathDimensions = R.pathBBox = function(path) {
var pth = paths(path);
if (pth.bbox) {
return clone(pth.bbox)
}
if (!path) {
return {
x: 0,
y: 0,
width: 0,
height: 0,
x2: 0,
y2: 0
}
}
path = path2curve(path);
var x = 0,
y = 0,
X = [],
Y = [],
p;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = p[1];
y = p[2];
X.push(x);
Y.push(y)
} else {
var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
X = X[concat](dim.min.x, dim.max.x);
Y = Y[concat](dim.min.y, dim.max.y);
x = p[5];
y = p[6]
}
}
var xmin = mmin[apply](0, X),
ymin = mmin[apply](0, Y),
xmax = mmax[apply](0, X),
ymax = mmax[apply](0, Y),
width = xmax - xmin,
height = ymax - ymin,
bb = {
x: xmin,
y: ymin,
x2: xmax,
y2: ymax,
width: width,
height: height,
cx: xmin + width / 2,
cy: ymin + height / 2
};
pth.bbox = clone(bb);
return bb
},
pathClone = function(pathArray) {
var res = clone(pathArray);
res.toString = R._path2string;
return res
},
pathToRelative = R._pathToRelative = function(pathArray) {
var pth = paths(pathArray);
if (pth.rel) {
return pathClone(pth.rel)
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) {
pathArray = R.parsePathString(pathArray)
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = pathArray[0][1];
y = pathArray[0][2];
mx = x;
my = y;
start++;
res.push(["M", x, y])
}
for (var i = start, ii = pathArray.length; i < ii; i++) {
var r = res[i] = [],
pa = pathArray[i];
if (pa[0] != lowerCase.call(pa[0])) {
r[0] = lowerCase.call(pa[0]);
switch (r[0]) {
case "a":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] - x).toFixed(3);
r[7] = +(pa[7] - y).toFixed(3);
break;
case "v":
r[1] = +(pa[1] - y).toFixed(3);
break;
case "m":
mx = pa[1];
my = pa[2];
default:
for (var j = 1, jj = pa.length; j < jj; j++) {
r[j] = +(pa[j] - (j % 2 ? x : y)).toFixed(3)
}
}
} else {
r = res[i] = [];
if (pa[0] == "m") {
mx = pa[1] + x;
my = pa[2] + y
}
for (var k = 0, kk = pa.length; k < kk; k++) {
res[i][k] = pa[k]
}
}
var len = res[i].length;
switch (res[i][0]) {
case "z":
x = mx;
y = my;
break;
case "h":
x += +res[i][len - 1];
break;
case "v":
y += +res[i][len - 1];
break;
default:
x += +res[i][len - 2];
y += +res[i][len - 1]
}
}
res.toString = R._path2string;
pth.rel = pathClone(res);
return res
},
pathToAbsolute = R._pathToAbsolute = function(pathArray) {
var pth = paths(pathArray);
if (pth.abs) {
return pathClone(pth.abs)
}
if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) {
pathArray = R.parsePathString(pathArray)
}
if (!pathArray || !pathArray.length) {
return [
["M", 0, 0]
]
}
var res = [],
x = 0,
y = 0,
mx = 0,
my = 0,
start = 0;
if (pathArray[0][0] == "M") {
x = +pathArray[0][1];
y = +pathArray[0][2];
mx = x;
my = y;
start++;
res[0] = ["M", x, y]
}
var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z";
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push(r = []);
pa = pathArray[i];
if (pa[0] != upperCase.call(pa[0])) {
r[0] = upperCase.call(pa[0]);
switch (r[0]) {
case "A":
r[1] = pa[1];
r[2] = pa[2];
r[3] = pa[3];
r[4] = pa[4];
r[5] = pa[5];
r[6] = +(pa[6] + x);
r[7] = +(pa[7] + y);
break;
case "V":
r[1] = +pa[1] + y;
break;
case "H":
r[1] = +pa[1] + x;
break;
case "R":
var dots = [x, y][concat](pa.slice(1));
for (var j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x;
dots[++j] = +dots[j] + y
}
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
break;
case "M":
mx = +pa[1] + x;
my = +pa[2] + y;
default:
for (j = 1, jj = pa.length; j < jj; j++) {
r[j] = +pa[j] + (j % 2 ? x : y)
}
}
} else if (pa[0] == "R") {
dots = [x, y][concat](pa.slice(1));
res.pop();
res = res[concat](catmullRom2bezier(dots, crz));
r = ["R"][concat](pa.slice(-2))
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k]
}
}
switch (r[0]) {
case "Z":
x = mx;
y = my;
break;
case "H":
x = r[1];
break;
case "V":
y = r[1];
break;
case "M":
mx = r[r.length - 2];
my = r[r.length - 1];
default:
x = r[r.length - 2];
y = r[r.length - 1]
}
}
res.toString = R._path2string;
pth.abs = pathClone(res);
return res
},
l2c = function(x1, y1, x2, y2) {
return [x1, y1, x2, y2, x2, y2]
},
q2c = function(x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
_23 = 2 / 3;
return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2]
},
a2c = function(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) {
var _120 = PI * 120 / 180,
rad = PI / 180 * (+angle || 0),
res = [],
xy, rotate = cacher(function(x, y, rad) {
var X = x * math.cos(rad) - y * math.sin(rad),
Y = x * math.sin(rad) + y * math.cos(rad);
return {
x: X,
y: Y
}
});
if (!recursive) {
xy = rotate(x1, y1, -rad);
x1 = xy.x;
y1 = xy.y;
xy = rotate(x2, y2, -rad);
x2 = xy.x;
y2 = xy.y;
var cos = math.cos(PI / 180 * angle),
sin = math.sin(PI / 180 * angle),
x = (x1 - x2) / 2,
y = (y1 - y2) / 2;
var h = x * x / (rx * rx) + y * y / (ry * ry);
if (h > 1) {
h = math.sqrt(h);
rx = h * rx;
ry = h * ry
}
var rx2 = rx * rx,
ry2 = ry * ry,
k = (large_arc_flag == sweep_flag ? -1 : 1) * math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))),
cx = k * rx * y / ry + (x1 + x2) / 2,
cy = k * -ry * x / rx + (y1 + y2) / 2,
f1 = math.asin(((y1 - cy) / ry).toFixed(9)),
f2 = math.asin(((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? PI - f1 : f1;
f2 = x2 < cx ? PI - f2 : f2;
f1 < 0 && (f1 = PI * 2 + f1);
f2 < 0 && (f2 = PI * 2 + f2);
if (sweep_flag && f1 > f2) {
f1 = f1 - PI * 2
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - PI * 2
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3]
}
var df = f2 - f1;
if (abs(df) > _120) {
var f2old = f2,
x2old = x2,
y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * math.cos(f2);
y2 = cy + ry * math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy])
}
df = f2 - f1;
var c1 = math.cos(f1),
s1 = math.sin(f1),
c2 = math.cos(f2),
s2 = math.sin(f2),
t = math.tan(df / 4),
hx = 4 / 3 * rx * t,
hy = 4 / 3 * ry * t,
m1 = [x1, y1],
m2 = [x1 + hx * s1, y1 - hy * c1],
m3 = [x2 + hx * s2, y2 - hy * c2],
m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (recursive) {
return [m2, m3, m4][concat](res)
} else {
res = [m2, m3, m4][concat](res).join()[split](",");
var newres = [];
for (var i = 0, ii = res.length; i < ii; i++) {
newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x
}
return newres
}
},
findDotAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t;
return {
x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x,
y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y
}
},
curveDim = cacher(function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
var a = c2x - 2 * c1x + p1x - (p2x - 2 * c2x + c1x),
b = 2 * (c1x - p1x) - 2 * (c2x - c1x),
c = p1x - c1x,
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a,
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a,
y = [p1y, p2y],
x = [p1x, p2x],
dot;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y)
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y)
}
a = c2y - 2 * c1y + p1y - (p2y - 2 * c2y + c1y);
b = 2 * (c1y - p1y) - 2 * (c2y - c1y);
c = p1y - c1y;
t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a;
t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a;
abs(t1) > "1e12" && (t1 = .5);
abs(t2) > "1e12" && (t2 = .5);
if (t1 > 0 && t1 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1);
x.push(dot.x);
y.push(dot.y)
}
if (t2 > 0 && t2 < 1) {
dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2);
x.push(dot.x);
y.push(dot.y)
}
return {
min: {
x: mmin[apply](0, x),
y: mmin[apply](0, y)
},
max: {
x: mmax[apply](0, x),
y: mmax[apply](0, y)
}
}
}),
path2curve = R._path2curve = cacher(function(path, path2) {
var pth = !path2 && paths(path);
if (!path2 && pth.curve) {
return pathClone(pth.curve)
}
var p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2),
attrs = {
x: 0,
y: 0,
bx: 0,
by: 0,
X: 0,
Y: 0,
qx: null,
qy: null
},
attrs2 = {
x: 0,
y: 0,
bx: 0,
by: 0,
X: 0,
Y: 0,
qx: null,
qy: null
},
processPath = function(path, d, pcom) {
var nx, ny;
if (!path) {
return ["C", d.x, d.y, d.x, d.y, d.x, d.y]
}!(path[0] in {
T: 1,
Q: 1
}) && (d.qx = d.qy = null);
switch (path[0]) {
case "M":
d.X = path[1];
d.Y = path[2];
break;
case "A":
path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1))));
break;
case "S":
if (pcom == "C" || pcom == "S") {
nx = d.x * 2 - d.bx;
ny = d.y * 2 - d.by
} else {
nx = d.x;
ny = d.y
}
path = ["C", nx, ny][concat](path.slice(1));
break;
case "T":
if (pcom == "Q" || pcom == "T") {
d.qx = d.x * 2 - d.qx;
d.qy = d.y * 2 - d.qy
} else {
d.qx = d.x;
d.qy = d.y
}
path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2]));
break;
case "Q":
d.qx = path[1];
d.qy = path[2];
path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4]));
break;
case "L":
path = ["C"][concat](l2c(d.x, d.y, path[1], path[2]));
break;
case "H":
path = ["C"][concat](l2c(d.x, d.y, path[1], d.y));
break;
case "V":
path = ["C"][concat](l2c(d.x, d.y, d.x, path[1]));
break;
case "Z":
path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y));
break
}
return path
},
fixArc = function(pp, i) {
if (pp[i].length > 7) {
pp[i].shift();
var pi = pp[i];
while (pi.length) {
pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6)))
}
pp.splice(i, 1);
ii = mmax(p.length, p2 && p2.length || 0)
}
},
fixM = function(path1, path2, a1, a2, i) {
if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") {
path2.splice(i, 0, ["M", a2.x, a2.y]);
a1.bx = 0;
a1.by = 0;
a1.x = path1[i][1];
a1.y = path1[i][2];
ii = mmax(p.length, p2 && p2.length || 0)
}
};
for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) {
p[i] = processPath(p[i], attrs);
fixArc(p, i);
p2 && (p2[i] = processPath(p2[i], attrs2));
p2 && fixArc(p2, i);
fixM(p, p2, attrs, attrs2, i);
fixM(p2, p, attrs2, attrs, i);
var seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length;
attrs.x = seg[seglen - 2];
attrs.y = seg[seglen - 1];
attrs.bx = toFloat(seg[seglen - 4]) || attrs.x;
attrs.by = toFloat(seg[seglen - 3]) || attrs.y;
attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x);
attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y);
attrs2.x = p2 && seg2[seg2len - 2];
attrs2.y = p2 && seg2[seg2len - 1]
}
if (!p2) {
pth.curve = pathClone(p)
}
return p2 ? [p, p2] : p
}, null, pathClone),
parseDots = R._parseDots = cacher(function(gradient) {
var dots = [];
for (var i = 0, ii = gradient.length; i < ii; i++) {
var dot = {},
par = gradient[i].match(/^([^:]*):?([\d\.]*)/);
dot.color = R.getRGB(par[1]);
if (dot.color.error) {
return null
}
dot.color = dot.color.hex;
par[2] && (dot.offset = par[2] + "%");
dots.push(dot)
}
for (i = 1, ii = dots.length - 1; i < ii; i++) {
if (!dots[i].offset) {
var start = toFloat(dots[i - 1].offset || 0),
end = 0;
for (var j = i + 1; j < ii; j++) {
if (dots[j].offset) {
end = dots[j].offset;
break
}
}
if (!end) {
end = 100;
j = ii
}
end = toFloat(end);
var d = (end - start) / (j - i + 1);
for (; i < j; i++) {
start += d;
dots[i].offset = start + "%"
}
}
}
return dots
}),
tear = R._tear = function(el, paper) {
el == paper.top && (paper.top = el.prev);
el == paper.bottom && (paper.bottom = el.next);
el.next && (el.next.prev = el.prev);
el.prev && (el.prev.next = el.next)
},
tofront = R._tofront = function(el, paper) {
if (paper.top === el) {
return
}
tear(el, paper);
el.next = null;
el.prev = paper.top;
paper.top.next = el;
paper.top = el
},
toback = R._toback = function(el, paper) {
if (paper.bottom === el) {
return
}
tear(el, paper);
el.next = paper.bottom;
el.prev = null;
paper.bottom.prev = el;
paper.bottom = el
},
insertafter = R._insertafter = function(el, el2, paper) {
tear(el, paper);
el2 == paper.top && (paper.top = el);
el2.next && (el2.next.prev = el);
el.next = el2.next;
el.prev = el2;
el2.next = el
},
insertbefore = R._insertbefore = function(el, el2, paper) {
tear(el, paper);
el2 == paper.bottom && (paper.bottom = el);
el2.prev && (el2.prev.next = el);
el.prev = el2.prev;
el2.prev = el;
el.next = el2
},
toMatrix = R.toMatrix = function(path, transform) {
var bb = pathDimensions(path),
el = {
_: {
transform: E
},
getBBox: function() {
return bb
}
};
extractTransform(el, transform);
return el.matrix
},
transformPath = R.transformPath = function(path, transform) {
return mapPath(path, toMatrix(path, transform))
},
extractTransform = R._extractTransform = function(el, tstr) {
if (tstr == null) {
return el._.transform
}
tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E);
var tdata = R.parseTransformString(tstr),
deg = 0,
dx = 0,
dy = 0,
sx = 1,
sy = 1,
_ = el._,
m = new Matrix;
_.transform = tdata || [];
if (tdata) {
for (var i = 0, ii = tdata.length; i < ii; i++) {
var t = tdata[i],
tlen = t.length,
command = Str(t[0]).toLowerCase(),
absolute = t[0] != command,
inver = absolute ? m.invert() : 0,
x1, y1, x2, y2, bb;
if (command == "t" && tlen == 3) {
if (absolute) {
x1 = inver.x(0, 0);
y1 = inver.y(0, 0);
x2 = inver.x(t[1], t[2]);
y2 = inver.y(t[1], t[2]);
m.translate(x2 - x1, y2 - y1)
} else {
m.translate(t[1], t[2])
}
} else if (command == "r") {
if (tlen == 2) {
bb = bb || el.getBBox(1);
m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2);
deg += t[1]
} else if (tlen == 4) {
if (absolute) {
x2 = inver.x(t[2], t[3]);
y2 = inver.y(t[2], t[3]);
m.rotate(t[1], x2, y2)
} else {
m.rotate(t[1], t[2], t[3])
}
deg += t[1]
}
} else if (command == "s") {
if (tlen == 2 || tlen == 3) {
bb = bb || el.getBBox(1);
m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2);
sx *= t[1];
sy *= t[tlen - 1]
} else if (tlen == 5) {
if (absolute) {
x2 = inver.x(t[3], t[4]);
y2 = inver.y(t[3], t[4]);
m.scale(t[1], t[2], x2, y2)
} else {
m.scale(t[1], t[2], t[3], t[4])
}
sx *= t[1];
sy *= t[2]
}
} else if (command == "m" && tlen == 7) {
m.add(t[1], t[2], t[3], t[4], t[5], t[6])
}
_.dirtyT = 1;
el.matrix = m
}
}
el.matrix = m;
_.sx = sx;
_.sy = sy;
_.deg = deg;
_.dx = dx = m.e;
_.dy = dy = m.f;
if (sx == 1 && sy == 1 && !deg && _.bbox) {
_.bbox.x += +dx;
_.bbox.y += +dy
} else {
_.dirtyT = 1
}
},
getEmpty = function(item) {
var l = item[0];
switch (l.toLowerCase()) {
case "t":
return [l, 0, 0];
case "m":
return [l, 1, 0, 0, 1, 0, 0];
case "r":
if (item.length == 4) {
return [l, 0, item[2], item[3]]
} else {
return [l, 0]
}
case "s":
if (item.length == 5) {
return [l, 1, 1, item[3], item[4]]
} else if (item.length == 3) {
return [l, 1, 1]
} else {
return [l, 1]
}
}
},
equaliseTransform = R._equaliseTransform = function(t1, t2) {
t2 = Str(t2).replace(/\.{3}|\u2026/g, t1);
t1 = R.parseTransformString(t1) || [];
t2 = R.parseTransformString(t2) || [];
var maxlength = mmax(t1.length, t2.length),
from = [],
to = [],
i = 0,
j, jj, tt1, tt2;
for (; i < maxlength; i++) {
tt1 = t1[i] || getEmpty(t2[i]);
tt2 = t2[i] || getEmpty(tt1);
if (tt1[0] != tt2[0] || tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3]) || tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4])) {
return
}
from[i] = [];
to[i] = [];
for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) {
j in tt1 && (from[i][j] = tt1[j]);
j in tt2 && (to[i][j] = tt2[j])
}
}
return {
from: from,
to: to
}
};
R._getContainer = function(x, y, w, h) {
var container;
container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x;
if (container == null) {
return
}
if (container.tagName) {
if (y == null) {
return {
container: container,
width: container.style.pixelWidth || container.offsetWidth,
height: container.style.pixelHeight || container.offsetHeight
}
} else {
return {
container: container,
width: y,
height: w
}
}
}
return {
container: 1,
x: x,
y: y,
width: w,
height: h
}
};
R.pathToRelative = pathToRelative;
R._engine = {};
R.path2curve = path2curve;
R.matrix = function(a, b, c, d, e, f) {
return new Matrix(a, b, c, d, e, f)
};
function Matrix(a, b, c, d, e, f) {
if (a != null) {
this.a = +a;
this.b = +b;
this.c = +c;
this.d = +d;
this.e = +e;
this.f = +f
} else {
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0
}
}! function(matrixproto) {
matrixproto.add = function(a, b, c, d, e, f) {
var out = [
[],
[],
[]
],
m = [
[this.a, this.c, this.e],
[this.b, this.d, this.f],
[0, 0, 1]
],
matrix = [
[a, c, e],
[b, d, f],
[0, 0, 1]
],
x, y, z, res;
if (a && a instanceof Matrix) {
matrix = [
[a.a, a.c, a.e],
[a.b, a.d, a.f],
[0, 0, 1]
]
}
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++) {
res = 0;
for (z = 0; z < 3; z++) {
res += m[x][z] * matrix[z][y]
}
out[x][y] = res
}
}
this.a = out[0][0];
this.b = out[1][0];
this.c = out[0][1];
this.d = out[1][1];
this.e = out[0][2];
this.f = out[1][2]
};
matrixproto.invert = function() {
var me = this,
x = me.a * me.d - me.b * me.c;
return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x)
};
matrixproto.clone = function() {
return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f)
};
matrixproto.translate = function(x, y) {
this.add(1, 0, 0, 1, x, y)
};
matrixproto.scale = function(x, y, cx, cy) {
y == null && (y = x);
(cx || cy) && this.add(1, 0, 0, 1, cx, cy);
this.add(x, 0, 0, y, 0, 0);
(cx || cy) && this.add(1, 0, 0, 1, -cx, -cy)
};
matrixproto.rotate = function(a, x, y) {
a = R.rad(a);
x = x || 0;
y = y || 0;
var cos = +math.cos(a).toFixed(9),
sin = +math.sin(a).toFixed(9);
this.add(cos, sin, -sin, cos, x, y);
this.add(1, 0, 0, 1, -x, -y)
};
matrixproto.x = function(x, y) {
return x * this.a + y * this.c + this.e
};
matrixproto.y = function(x, y) {
return x * this.b + y * this.d + this.f
};
matrixproto.get = function(i) {
return +this[Str.fromCharCode(97 + i)].toFixed(4)
};
matrixproto.toString = function() {
return R.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join()
};
matrixproto.toFilter = function() {
return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')"
};
matrixproto.offset = function() {
return [this.e.toFixed(4), this.f.toFixed(4)]
};
function norm(a) {
return a[0] * a[0] + a[1] * a[1]
}
function normalize(a) {
var mag = math.sqrt(norm(a));
a[0] && (a[0] /= mag);
a[1] && (a[1] /= mag)
}
matrixproto.split = function() {
var out = {};
out.dx = this.e;
out.dy = this.f;
var row = [
[this.a, this.c],
[this.b, this.d]
];
out.scalex = math.sqrt(norm(row[0]));
normalize(row[0]);
out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1];
row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear];
out.scaley = math.sqrt(norm(row[1]));
normalize(row[1]);
out.shear /= out.scaley;
var sin = -row[0][1],
cos = row[1][1];
if (cos < 0) {
out.rotate = R.deg(math.acos(cos));
if (sin < 0) {
out.rotate = 360 - out.rotate
}
} else {
out.rotate = R.deg(math.asin(sin))
}
out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate);
out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate;
out.noRotation = !+out.shear.toFixed(9) && !out.rotate;
return out
};
matrixproto.toTransformString = function(shorter) {
var s = shorter || this[split]();
if (s.isSimple) {
s.scalex = +s.scalex.toFixed(4);
s.scaley = +s.scaley.toFixed(4);
s.rotate = +s.rotate.toFixed(4);
return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E)
} else {
return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]
}
}
}(Matrix.prototype);
var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/);
if (navigator.vendor == "Apple Computer, Inc." && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") || navigator.vendor == "Google Inc." && version && version[1] < 8) {
paperproto.safari = function() {
var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({
stroke: "none"
});
setTimeout(function() {
rect.remove()
})
}
} else {
paperproto.safari = fun
}
var preventDefault = function() {
this.returnValue = false
},
preventTouch = function() {
return this.originalEvent.preventDefault()
},
stopPropagation = function() {
this.cancelBubble = true
},
stopTouch = function() {
return this.originalEvent.stopPropagation()
},
getEventPosition = function(e) {
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
return {
x: e.clientX + scrollX,
y: e.clientY + scrollY
}
},
addEvent = function() {
if (g.doc.addEventListener) {
return function(obj, type, fn, element) {
var f = function(e) {
var pos = getEventPosition(e);
return fn.call(element, e, pos.x, pos.y)
};
obj.addEventListener(type, f, false);
if (supportsTouch && touchMap[type]) {
var _f = function(e) {
var pos = getEventPosition(e),
olde = e;
for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) {
if (e.targetTouches[i].target == obj) {
e = e.targetTouches[i];
e.originalEvent = olde;
e.preventDefault = preventTouch;
e.stopPropagation = stopTouch;
break
}
}
return fn.call(element, e, pos.x, pos.y)
};
obj.addEventListener(touchMap[type], _f, false)
}
return function() {
obj.removeEventListener(type, f, false);
if (supportsTouch && touchMap[type]) obj.removeEventListener(touchMap[type], f, false);
return true
}
}
} else if (g.doc.attachEvent) {
return function(obj, type, fn, element) {
var f = function(e) {
e = e || g.win.event;
var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
x = e.clientX + scrollX,
y = e.clientY + scrollY;
e.preventDefault = e.preventDefault || preventDefault;
e.stopPropagation = e.stopPropagation || stopPropagation;
return fn.call(element, e, x, y)
};
obj.attachEvent("on" + type, f);
var detacher = function() {
obj.detachEvent("on" + type, f);
return true
};
return detacher
}
}
}(),
drag = [],
dragMove = function(e) {
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft,
dragi, j = drag.length;
while (j--) {
dragi = drag[j];
if (supportsTouch && e.touches) {
var i = e.touches.length,
touch;
while (i--) {
touch = e.touches[i];
if (touch.identifier == dragi.el._drag.id) {
x = touch.clientX;
y = touch.clientY;
(e.originalEvent ? e.originalEvent : e).preventDefault();
break
}
}
} else {
e.preventDefault()
}
var node = dragi.el.node,
o, next = node.nextSibling,
parent = node.parentNode,
display = node.style.display;
g.win.opera && parent.removeChild(node);
node.style.display = "none";
o = dragi.el.paper.getElementByPoint(x, y);
node.style.display = display;
g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
o && eve("raphael.drag.over." + dragi.el.id, dragi.el, o);
x += scrollX;
y += scrollY;
eve("raphael.drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e)
}
},
dragUp = function(e) {
R.unmousemove(dragMove).unmouseup(dragUp);
var i = drag.length,
dragi;
while (i--) {
dragi = drag[i];
dragi.el._drag = {};
eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e)
}
drag = []
},
elproto = R.el = {};
for (var i = events.length; i--;) {
! function(eventName) {
R[eventName] = elproto[eventName] = function(fn, scope) {
if (R.is(fn, "function")) {
this.events = this.events || [];
this.events.push({
name: eventName,
f: fn,
unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)
})
}
return this
};
R["un" + eventName] = elproto["un" + eventName] = function(fn) {
var events = this.events || [],
l = events.length;
while (l--) {
if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) {
events[l].unbind();
events.splice(l, 1);
!events.length && delete this.events
}
}
return this
}
}(events[i])
}
elproto.data = function(key, value) {
var data = eldata[this.id] = eldata[this.id] || {};
if (arguments.length == 0) {
return data
}
if (arguments.length == 1) {
if (R.is(key, "object")) {
for (var i in key)
if (key[has](i)) {
this.data(i, key[i])
}
return this
}
eve("raphael.data.get." + this.id, this, data[key], key);
return data[key]
}
data[key] = value;
eve("raphael.data.set." + this.id, this, value, key);
return this
};
elproto.removeData = function(key) {
if (key == null) {
eldata[this.id] = {}
} else {
eldata[this.id] && delete eldata[this.id][key]
}
return this
};
elproto.getData = function() {
return clone(eldata[this.id] || {})
};
elproto.hover = function(f_in, f_out, scope_in, scope_out) {
return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in)
};
elproto.unhover = function(f_in, f_out) {
return this.unmouseover(f_in).unmouseout(f_out)
};
var draggable = [];
elproto.drag = function(onmove, onstart, onend, move_scope, start_scope, end_scope) {
function start(e) {
(e.originalEvent || e).preventDefault();
var x = e.clientX,
y = e.clientY,
scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop,
scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft;
this._drag.id = e.identifier;
if (supportsTouch && e.touches) {
var i = e.touches.length,
touch;
while (i--) {
touch = e.touches[i];
this._drag.id = touch.identifier;
if (touch.identifier == this._drag.id) {
x = touch.clientX;
y = touch.clientY;
break
}
}
}
this._drag.x = x + scrollX;
this._drag.y = y + scrollY;
!drag.length && R.mousemove(dragMove).mouseup(dragUp);
drag.push({
el: this,
move_scope: move_scope,
start_scope: start_scope,
end_scope: end_scope
});
onstart && eve.on("raphael.drag.start." + this.id, onstart);
onmove && eve.on("raphael.drag.move." + this.id, onmove);
onend && eve.on("raphael.drag.end." + this.id, onend);
eve("raphael.drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e)
}
this._drag = {};
draggable.push({
el: this,
start: start
});
this.mousedown(start);
return this
};
elproto.onDragOver = function(f) {
f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id)
};
elproto.undrag = function() {
var i = draggable.length;
while (i--)
if (draggable[i].el == this) {
this.unmousedown(draggable[i].start);
draggable.splice(i, 1);
eve.unbind("raphael.drag.*." + this.id)
}!draggable.length && R.unmousemove(dragMove).unmouseup(dragUp);
drag = []
};
paperproto.circle = function(x, y, r) {
var out = R._engine.circle(this, x || 0, y || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out
};
paperproto.rect = function(x, y, w, h, r) {
var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0);
this.__set__ && this.__set__.push(out);
return out
};
paperproto.ellipse = function(x, y, rx, ry) {
var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0);
this.__set__ && this.__set__.push(out);
return out
};
paperproto.path = function(pathString) {
pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E);
var out = R._engine.path(R.format[apply](R, arguments), this);
this.__set__ && this.__set__.push(out);
return out
};
paperproto.image = function(src, x, y, w, h) {
var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0);
this.__set__ && this.__set__.push(out);
return out
};
paperproto.text = function(x, y, text) {
var out = R._engine.text(this, x || 0, y || 0, Str(text));
this.__set__ && this.__set__.push(out);
return out
};
paperproto.set = function(itemsArray) {
!R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length));
var out = new Set(itemsArray);
this.__set__ && this.__set__.push(out);
out["paper"] = this;
out["type"] = "set";
return out
};
paperproto.setStart = function(set) {
this.__set__ = set || this.set()
};
paperproto.setFinish = function(set) {
var out = this.__set__;
delete this.__set__;
return out
};
paperproto.setSize = function(width, height) {
return R._engine.setSize.call(this, width, height)
};
paperproto.setViewBox = function(x, y, w, h, fit) {
return R._engine.setViewBox.call(this, x, y, w, h, fit)
};
paperproto.top = paperproto.bottom = null;
paperproto.raphael = R;
var getOffset = function(elem) {
var box = elem.getBoundingClientRect(),
doc = elem.ownerDocument,
body = doc.body,
docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop) - clientTop,
left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft;
return {
y: top,
x: left
}
};
paperproto.getElementByPoint = function(x, y) {
var paper = this,
svg = paper.canvas,
target = g.doc.elementFromPoint(x, y);
if (g.win.opera && target.tagName == "svg") {
var so = getOffset(svg),
sr = svg.createSVGRect();
sr.x = x - so.x;
sr.y = y - so.y;
sr.width = sr.height = 1;
var hits = svg.getIntersectionList(sr, null);
if (hits.length) {
target = hits[hits.length - 1]
}
}
if (!target) {
return null
}
while (target.parentNode && target != svg.parentNode && !target.raphael) {
target = target.parentNode
}
target == paper.canvas.parentNode && (target = svg);
target = target && target.raphael ? paper.getById(target.raphaelid) : null;
return target
};
paperproto.getElementsByBBox = function(bbox) {
var set = this.set();
this.forEach(function(el) {
if (R.isBBoxIntersect(el.getBBox(), bbox)) {
set.push(el)
}
});
return set
};
paperproto.getById = function(id) {
var bot = this.bottom;
while (bot) {
if (bot.id == id) {
return bot
}
bot = bot.next
}
return null
};
paperproto.forEach = function(callback, thisArg) {
var bot = this.bottom;
while (bot) {
if (callback.call(thisArg, bot) === false) {
return this
}
bot = bot.next
}
return this
};
paperproto.getElementsByPoint = function(x, y) {
var set = this.set();
this.forEach(function(el) {
if (el.isPointInside(x, y)) {
set.push(el)
}
});
return set
};
function x_y() {
return this.x + S + this.y
}
function x_y_w_h() {
return this.x + S + this.y + S + this.width + " × " + this.height
}
elproto.isPointInside = function(x, y) {
var rp = this.realPath = getPath[this.type](this);
if (this.attr("transform") && this.attr("transform").length) {
rp = R.transformPath(rp, this.attr("transform"))
}
return R.isPointInsidePath(rp, x, y)
};
elproto.getBBox = function(isWithoutTransform) {
if (this.removed) {
return {}
}
var _ = this._;
if (isWithoutTransform) {
if (_.dirty || !_.bboxwt) {
this.realPath = getPath[this.type](this);
_.bboxwt = pathDimensions(this.realPath);
_.bboxwt.toString = x_y_w_h;
_.dirty = 0
}
return _.bboxwt
}
if (_.dirty || _.dirtyT || !_.bbox) {
if (_.dirty || !this.realPath) {
_.bboxwt = 0;
this.realPath = getPath[this.type](this)
}
_.bbox = pathDimensions(mapPath(this.realPath, this.matrix));
_.bbox.toString = x_y_w_h;
_.dirty = _.dirtyT = 0
}
return _.bbox
};
elproto.clone = function() {
if (this.removed) {
return null
}
var out = this.paper[this.type]().attr(this.attr());
this.__set__ && this.__set__.push(out);
return out
};
elproto.glow = function(glow) {
if (this.type == "text") {
return null
}
glow = glow || {};
var s = {
width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
fill: glow.fill || false,
opacity: glow.opacity || .5,
offsetx: glow.offsetx || 0,
offsety: glow.offsety || 0,
color: glow.color || "#000"
},
c = s.width / 2,
r = this.paper,
out = r.set(),
path = this.realPath || getPath[this.type](this);
path = this.matrix ? mapPath(path, this.matrix) : path;
for (var i = 1; i < c + 1; i++) {
out.push(r.path(path).attr({
stroke: s.color,
fill: s.fill ? s.color : "none",
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": +(s.width / c * i).toFixed(3),
opacity: +(s.opacity / c).toFixed(3)
}))
}
return out.insertBefore(this).translate(s.offsetx, s.offsety)
};
var curveslengths = {},
getPointAtSegmentLength = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) {
if (length == null) {
return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y)
} else {
return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length))
}
},
getLengthFactory = function(istotal, subpath) {
return function(path, length, onlystart) {
path = path2curve(path);
var x, y, p, l, sp = "",
subpaths = {},
point, len = 0;
for (var i = 0, ii = path.length; i < ii; i++) {
p = path[i];
if (p[0] == "M") {
x = +p[1];
y = +p[2]
} else {
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]);
if (len + l > length) {
if (subpath && !subpaths.start) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y];
if (onlystart) {
return sp
}
subpaths.start = sp;
sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join();
len += l;
x = +p[5];
y = +p[6];
continue
}
if (!istotal && !subpath) {
point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len);
return {
x: point.x,
y: point.y,
alpha: point.alpha
}
}
}
len += l;
x = +p[5];
y = +p[6]
}
sp += p.shift() + p
}
subpaths.end = sp;
point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1);
point.alpha && (point = {
x: point.x,
y: point.y,
alpha: point.alpha
});
return point
}
};
var getTotalLength = getLengthFactory(1),
getPointAtLength = getLengthFactory(),
getSubpathsAtLength = getLengthFactory(0, 1);
R.getTotalLength = getTotalLength;
R.getPointAtLength = getPointAtLength;
R.getSubpath = function(path, from, to) {
if (this.getTotalLength(path) - to < 1e-6) {
return getSubpathsAtLength(path, from).end
}
var a = getSubpathsAtLength(path, to, 1);
return from ? getSubpathsAtLength(a, from).end : a
};
elproto.getTotalLength = function() {
var path = this.getPath();
if (!path) {
return
}
if (this.node.getTotalLength) {
return this.node.getTotalLength()
}
return getTotalLength(path)
};
elproto.getPointAtLength = function(length) {
var path = this.getPath();
if (!path) {
return
}
return getPointAtLength(path, length)
};
elproto.getPath = function() {
var path, getPath = R._getPath[this.type];
if (this.type == "text" || this.type == "set") {
return
}
if (getPath) {
path = getPath(this)
}
return path
};
elproto.getSubpath = function(from, to) {
var path = this.getPath();
if (!path) {
return
}
return R.getSubpath(path, from, to)
};
var ef = R.easing_formulas = {
linear: function(n) {
return n
},
"<": function(n) {
return pow(n, 1.7)
},
">": function(n) {
return pow(n, .48)
},
"<>": function(n) {
var q = .48 - n / 1.04,
Q = math.sqrt(.1734 + q * q),
x = Q - q,
X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
t = X + Y + .5;
return (1 - t) * 3 * t * t + t * t * t
},
backIn: function(n) {
var s = 1.70158;
return n * n * ((s + 1) * n - s)
},
backOut: function(n) {
n = n - 1;
var s = 1.70158;
return n * n * ((s + 1) * n + s) + 1
},
elastic: function(n) {
if (n == !!n) {
return n
}
return pow(2, -10 * n) * math.sin((n - .075) * 2 * PI / .3) + 1
},
bounce: function(n) {
var s = 7.5625,
p = 2.75,
l;
if (n < 1 / p) {
l = s * n * n
} else {
if (n < 2 / p) {
n -= 1.5 / p;
l = s * n * n + .75
} else {
if (n < 2.5 / p) {
n -= 2.25 / p;
l = s * n * n + .9375
} else {
n -= 2.625 / p;
l = s * n * n + .984375
}
}
}
return l
}
};
ef.easeIn = ef["ease-in"] = ef["<"];
ef.easeOut = ef["ease-out"] = ef[">"];
ef.easeInOut = ef["ease-in-out"] = ef["<>"];
ef["back-in"] = ef.backIn;
ef["back-out"] = ef.backOut;
var animationElements = [],
requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
setTimeout(callback, 16)
},
animation = function() {
var Now = +new Date,
l = 0;
for (; l < animationElements.length; l++) {
var e = animationElements[l];
if (e.el.removed || e.paused) {
continue
}
var time = Now - e.start,
ms = e.ms,
easing = e.easing,
from = e.from,
diff = e.diff,
to = e.to,
t = e.t,
that = e.el,
set = {},
now, init = {},
key;
if (e.initstatus) {
time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms;
e.status = e.initstatus;
delete e.initstatus;
e.stop && animationElements.splice(l--, 1)
} else {
e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top
}
if (time < 0) {
continue
}
if (time < ms) {
var pos = easing(time / ms);
for (var attr in from)
if (from[has](attr)) {
switch (availableAnimAttrs[attr]) {
case nu:
now = +from[attr] + pos * ms * diff[attr];
break;
case "colour":
now = "rgb(" + [upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b))].join(",") + ")";
break;
case "path":
now = [];
for (var i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]
}
now[i] = now[i].join(S)
}
now = now.join(S);
break;
case "transform":
if (diff[attr].real) {
now = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
now[i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]
}
}
} else {
var get = function(i) {
return +from[attr][i] + pos * ms * diff[attr][i]
};
now = [
["m", get(0), get(1), get(2), get(3), get(4), get(5)]
]
}
break;
case "csv":
if (attr == "clip-rect") {
now = [];
i = 4;
while (i--) {
now[i] = +from[attr][i] + pos * ms * diff[attr][i]
}
}
break;
default:
var from2 = [][concat](from[attr]);
now = [];
i = that.paper.customAttributes[attr].length;
while (i--) {
now[i] = +from2[i] + pos * ms * diff[attr][i]
}
break
}
set[attr] = now
}
that.attr(set);
! function(id, that, anim) {
setTimeout(function() {
eve("raphael.anim.frame." + id, that, anim)
})
}(that.id, that, e.anim)
} else {
! function(f, el, a) {
setTimeout(function() {
eve("raphael.anim.frame." + el.id, el, a);
eve("raphael.anim.finish." + el.id, el, a);
R.is(f, "function") && f.call(el)
})
}(e.callback, that, e.anim);
that.attr(to);
animationElements.splice(l--, 1);
if (e.repeat > 1 && !e.next) {
for (key in to)
if (to[has](key)) {
init[key] = e.totalOrigin[key]
}
e.el.attr(init);
runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1)
}
if (e.next && !e.stop) {
runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat)
}
}
}
R.svg && that && that.paper && that.paper.safari();
animationElements.length && requestAnimFrame(animation)
},
upto255 = function(color) {
return color > 255 ? 255 : color < 0 ? 0 : color
};
elproto.animateWith = function(el, anim, params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element
}
var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback),
x, y;
runAnimation(a, element, a.percents[0], null, element.attr());
for (var i = 0, ii = animationElements.length; i < ii; i++) {
if (animationElements[i].anim == anim && animationElements[i].el == el) {
animationElements[ii - 1].start = animationElements[i].start;
break
}
}
return element
};
function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) {
var cx = 3 * p1x,
bx = 3 * (p2x - p1x) - cx,
ax = 1 - cx - bx,
cy = 3 * p1y,
by = 3 * (p2y - p1y) - cy,
ay = 1 - cy - by;
function sampleCurveX(t) {
return ((ax * t + bx) * t + cx) * t
}
function solve(x, epsilon) {
var t = solveCurveX(x, epsilon);
return ((ay * t + by) * t + cy) * t
}
function solveCurveX(x, epsilon) {
var t0, t1, t2, x2, d2, i;
for (t2 = x, i = 0; i < 8; i++) {
x2 = sampleCurveX(t2) - x;
if (abs(x2) < epsilon) {
return t2
}
d2 = (3 * ax * t2 + 2 * bx) * t2 + cx;
if (abs(d2) < 1e-6) {
break
}
t2 = t2 - x2 / d2
}
t0 = 0;
t1 = 1;
t2 = x;
if (t2 < t0) {
return t0
}
if (t2 > t1) {
return t1
}
while (t0 < t1) {
x2 = sampleCurveX(t2);
if (abs(x2 - x) < epsilon) {
return t2
}
if (x > x2) {
t0 = t2
} else {
t1 = t2
}
t2 = (t1 - t0) / 2 + t0
}
return t2
}
return solve(t, 1 / (200 * duration))
}
elproto.onAnimation = function(f) {
f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id);
return this
};
function Animation(anim, ms) {
var percents = [],
newAnim = {};
this.ms = ms;
this.times = 1;
if (anim) {
for (var attr in anim)
if (anim[has](attr)) {
newAnim[toFloat(attr)] = anim[attr];
percents.push(toFloat(attr))
}
percents.sort(sortByNumber)
}
this.anim = newAnim;
this.top = percents[percents.length - 1];
this.percents = percents
}
Animation.prototype.delay = function(delay) {
var a = new Animation(this.anim, this.ms);
a.times = this.times;
a.del = +delay || 0;
return a
};
Animation.prototype.repeat = function(times) {
var a = new Animation(this.anim, this.ms);
a.del = this.del;
a.times = math.floor(mmax(times, 0)) || 1;
return a
};
function runAnimation(anim, element, percent, status, totalOrigin, times) {
percent = toFloat(percent);
var params, isInAnim, isInAnimSet, percents = [],
next, prev, timestamp, ms = anim.ms,
from = {},
to = {},
diff = {};
if (status) {
for (i = 0, ii = animationElements.length; i < ii; i++) {
var e = animationElements[i];
if (e.el.id == element.id && e.anim == anim) {
if (e.percent != percent) {
animationElements.splice(i, 1);
isInAnimSet = 1
} else {
isInAnim = e
}
element.attr(e.totalOrigin);
break
}
}
} else {
status = +to
}
for (var i = 0, ii = anim.percents.length; i < ii; i++) {
if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) {
percent = anim.percents[i];
prev = anim.percents[i - 1] || 0;
ms = ms / anim.top * (percent - prev);
next = anim.percents[i + 1];
params = anim.anim[percent];
break
} else if (status) {
element.attr(anim.anim[anim.percents[i]])
}
}
if (!params) {
return
}
if (!isInAnim) {
for (var attr in params)
if (params[has](attr)) {
if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) {
from[attr] = element.attr(attr);
from[attr] == null && (from[attr] = availableAttrs[attr]);
to[attr] = params[attr];
switch (availableAnimAttrs[attr]) {
case nu:
diff[attr] = (to[attr] - from[attr]) / ms;
break;
case "colour":
from[attr] = R.getRGB(from[attr]);
var toColour = R.getRGB(to[attr]);
diff[attr] = {
r: (toColour.r - from[attr].r) / ms,
g: (toColour.g - from[attr].g) / ms,
b: (toColour.b - from[attr].b) / ms
};
break;
case "path":
var pathes = path2curve(from[attr], to[attr]),
toPath = pathes[1];
from[attr] = pathes[0];
diff[attr] = [];
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [0];
for (var j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms
}
}
break;
case "transform":
var _ = element._,
eq = equaliseTransform(_[attr], to[attr]);
if (eq) {
from[attr] = eq.from;
to[attr] = eq.to;
diff[attr] = [];
diff[attr].real = true;
for (i = 0, ii = from[attr].length; i < ii; i++) {
diff[attr][i] = [from[attr][i][0]];
for (j = 1, jj = from[attr][i].length; j < jj; j++) {
diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms
}
}
} else {
var m = element.matrix || new Matrix,
to2 = {
_: {
transform: _.transform
},
getBBox: function() {
return element.getBBox(1)
}
};
from[attr] = [m.a, m.b, m.c, m.d, m.e, m.f];
extractTransform(to2, to[attr]);
to[attr] = to2._.transform;
diff[attr] = [(to2.matrix.a - m.a) / ms, (to2.matrix.b - m.b) / ms, (to2.matrix.c - m.c) / ms, (to2.matrix.d - m.d) / ms, (to2.matrix.e - m.e) / ms, (to2.matrix.f - m.f) / ms]
}
break;
case "csv":
var values = Str(params[attr])[split](separator),
from2 = Str(from[attr])[split](separator);
if (attr == "clip-rect") {
from[attr] = from2;
diff[attr] = [];
i = from2.length;
while (i--) {
diff[attr][i] = (values[i] - from[attr][i]) / ms
}
}
to[attr] = values;
break;
default:
values = [][concat](params[attr]);
from2 = [][concat](from[attr]);
diff[attr] = [];
i = element.paper.customAttributes[attr].length;
while (i--) {
diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms
}
break
}
}
}
var easing = params.easing,
easyeasy = R.easing_formulas[easing];
if (!easyeasy) {
easyeasy = Str(easing).match(bezierrg);
if (easyeasy && easyeasy.length == 5) {
var curve = easyeasy;
easyeasy = function(t) {
return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms)
}
} else {
easyeasy = pipe
}
}
timestamp = params.start || anim.start || +new Date;
e = {
anim: anim,
percent: percent,
timestamp: timestamp,
start: timestamp + (anim.del || 0),
status: 0,
initstatus: status || 0,
stop: false,
ms: ms,
easing: easyeasy,
from: from,
diff: diff,
to: to,
el: element,
callback: params.callback,
prev: prev,
next: next,
repeat: times || anim.times,
origin: element.attr(),
totalOrigin: totalOrigin
};
animationElements.push(e);
if (status && !isInAnim && !isInAnimSet) {
e.stop = true;
e.start = new Date - ms * status;
if (animationElements.length == 1) {
return animation()
}
}
if (isInAnimSet) {
e.start = new Date - e.ms * status
}
animationElements.length == 1 && requestAnimFrame(animation)
} else {
isInAnim.initstatus = status;
isInAnim.start = new Date - isInAnim.ms * status
}
eve("raphael.anim.start." + element.id, element, anim)
}
R.animation = function(params, ms, easing, callback) {
if (params instanceof Animation) {
return params
}
if (R.is(easing, "function") || !easing) {
callback = callback || easing || null;
easing = null
}
params = Object(params);
ms = +ms || 0;
var p = {},
json, attr;
for (attr in params)
if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) {
json = true;
p[attr] = params[attr]
}
if (!json) {
return new Animation(params, ms)
} else {
easing && (p.easing = easing);
callback && (p.callback = callback);
return new Animation({
100: p
}, ms)
}
};
elproto.animate = function(params, ms, easing, callback) {
var element = this;
if (element.removed) {
callback && callback.call(element);
return element
}
var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback);
runAnimation(anim, element, anim.percents[0], null, element.attr());
return element
};
elproto.setTime = function(anim, value) {
if (anim && value != null) {
this.status(anim, mmin(value, anim.ms) / anim.ms)
}
return this
};
elproto.status = function(anim, value) {
var out = [],
i = 0,
len, e;
if (value != null) {
runAnimation(anim, this, -1, mmin(value, 1));
return this
} else {
len = animationElements.length;
for (; i < len; i++) {
e = animationElements[i];
if (e.el.id == this.id && (!anim || e.anim == anim)) {
if (anim) {
return e.status
}
out.push({
anim: e.anim,
status: e.status
})
}
}
if (anim) {
return 0
}
return out
}
};
elproto.pause = function(anim) {
for (var i = 0; i < animationElements.length; i++)
if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) {
animationElements[i].paused = true
}
}
return this
};
elproto.resume = function(anim) {
for (var i = 0; i < animationElements.length; i++)
if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
var e = animationElements[i];
if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) {
delete e.paused;
this.status(e.anim, e.status)
}
}
return this
};
elproto.stop = function(anim) {
for (var i = 0; i < animationElements.length; i++)
if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) {
animationElements.splice(i--, 1)
}
}
return this
};
function stopAnimation(paper) {
for (var i = 0; i < animationElements.length; i++)
if (animationElements[i].el.paper == paper) {
animationElements.splice(i--, 1)
}
}
eve.on("raphael.remove", stopAnimation);
eve.on("raphael.clear", stopAnimation);
elproto.toString = function() {
return "Raphaël’s object"
};
var Set = function(items) {
this.items = [];
this.length = 0;
this.type = "set";
if (items) {
for (var i = 0, ii = items.length; i < ii; i++) {
if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) {
this[this.items.length] = this.items[this.items.length] = items[i];
this.length++
}
}
}
},
setproto = Set.prototype;
setproto.push = function() {
var item, len;
for (var i = 0, ii = arguments.length; i < ii; i++) {
item = arguments[i];
if (item && (item.constructor == elproto.constructor || item.constructor == Set)) {
len = this.items.length;
this[len] = this.items[len] = item;
this.length++
}
}
return this
};
setproto.pop = function() {
this.length && delete this[this.length--];
return this.items.pop()
};
setproto.forEach = function(callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this
}
}
return this
};
for (var method in elproto)
if (elproto[has](method)) {
setproto[method] = function(methodname) {
return function() {
var arg = arguments;
return this.forEach(function(el) {
el[methodname][apply](el, arg)
})
}
}(method)
}
setproto.attr = function(name, value) {
if (name && R.is(name, array) && R.is(name[0], "object")) {
for (var j = 0, jj = name.length; j < jj; j++) {
this.items[j].attr(name[j])
}
} else {
for (var i = 0, ii = this.items.length; i < ii; i++) {
this.items[i].attr(name, value)
}
}
return this
};
setproto.clear = function() {
while (this.length) {
this.pop()
}
};
setproto.splice = function(index, count, insertion) {
index = index < 0 ? mmax(this.length + index, 0) : index;
count = mmax(0, mmin(this.length - index, count));
var tail = [],
todel = [],
args = [],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i])
}
for (i = 0; i < count; i++) {
todel.push(this[index + i])
}
for (; i < this.length - index; i++) {
tail.push(this[index + i])
}
var arglen = args.length;
for (i = 0; i < arglen + tail.length; i++) {
this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen]
}
i = this.items.length = this.length -= count - arglen;
while (this[i]) {
delete this[i++]
}
return new Set(todel)
};
setproto.exclude = function(el) {
for (var i = 0, ii = this.length; i < ii; i++)
if (this[i] == el) {
this.splice(i, 1);
return true
}
};
setproto.animate = function(params, ms, easing, callback) {
(R.is(easing, "function") || !easing) && (callback = easing || null);
var len = this.items.length,
i = len,
item, set = this,
collector;
if (!len) {
return this
}
callback && (collector = function() {
!--len && callback.call(set)
});
easing = R.is(easing, string) ? easing : collector;
var anim = R.animation(params, ms, easing, collector);
item = this.items[--i].animate(anim);
while (i--) {
this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim, anim);
this.items[i] && !this.items[i].removed || len--
}
return this
};
setproto.insertAfter = function(el) {
var i = this.items.length;
while (i--) {
this.items[i].insertAfter(el)
}
return this
};
setproto.getBBox = function() {
var x = [],
y = [],
x2 = [],
y2 = [];
for (var i = this.items.length; i--;)
if (!this.items[i].removed) {
var box = this.items[i].getBBox();
x.push(box.x);
y.push(box.y);
x2.push(box.x + box.width);
y2.push(box.y + box.height)
}
x = mmin[apply](0, x);
y = mmin[apply](0, y);
x2 = mmax[apply](0, x2);
y2 = mmax[apply](0, y2);
return {
x: x,
y: y,
x2: x2,
y2: y2,
width: x2 - x,
height: y2 - y
}
};
setproto.clone = function(s) {
s = this.paper.set();
for (var i = 0, ii = this.items.length; i < ii; i++) {
s.push(this.items[i].clone())
}
return s
};
setproto.toString = function() {
return "Raphaël‘s set"
};
setproto.glow = function(glowConfig) {
var ret = this.paper.set();
this.forEach(function(shape, index) {
var g = shape.glow(glowConfig);
if (g != null) {
g.forEach(function(shape2, index2) {
ret.push(shape2)
})
}
});
return ret
};
setproto.isPointInside = function(x, y) {
var isPointInside = false;
this.forEach(function(el) {
if (el.isPointInside(x, y)) {
console.log("runned");
isPointInside = true;
return false
}
});
return isPointInside
};
R.registerFont = function(font) {
if (!font.face) {
return font
}
this.fonts = this.fonts || {};
var fontcopy = {
w: font.w,
face: {},
glyphs: {}
},
family = font.face["font-family"];
for (var prop in font.face)
if (font.face[has](prop)) {
fontcopy.face[prop] = font.face[prop]
}
if (this.fonts[family]) {
this.fonts[family].push(fontcopy)
} else {
this.fonts[family] = [fontcopy]
}
if (!font.svg) {
fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10);
for (var glyph in font.glyphs)
if (font.glyphs[has](glyph)) {
var path = font.glyphs[glyph];
fontcopy.glyphs[glyph] = {
w: path.w,
k: {},
d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function(command) {
return {
l: "L",
c: "C",
x: "z",
t: "m",
r: "l",
v: "c"
}[command] || "M"
}) + "z"
};
if (path.k) {
for (var k in path.k)
if (path[has](k)) {
fontcopy.glyphs[glyph].k[k] = path.k[k]
}
}
}
}
return font
};
paperproto.getFont = function(family, weight, style, stretch) {
stretch = stretch || "normal";
style = style || "normal";
weight = +weight || {
normal: 400,
bold: 700,
lighter: 300,
bolder: 800
}[weight] || 400;
if (!R.fonts) {
return
}
var font = R.fonts[family];
if (!font) {
var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i");
for (var fontName in R.fonts)
if (R.fonts[has](fontName)) {
if (name.test(fontName)) {
font = R.fonts[fontName];
break
}
}
}
var thefont;
if (font) {
for (var i = 0, ii = font.length; i < ii; i++) {
thefont = font[i];
if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) {
break
}
}
}
return thefont
};
paperproto.print = function(x, y, string, font, size, origin, letter_spacing, line_spacing) {
origin = origin || "middle";
letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1);
line_spacing = mmax(mmin(line_spacing || 1, 3), 1);
var letters = Str(string)[split](E),
shift = 0,
notfirst = 0,
path = E,
scale;
R.is(font, "string") && (font = this.getFont(font));
if (font) {
scale = (size || 16) / font.face["units-per-em"];
var bb = font.face.bbox[split](separator),
top = +bb[0],
lineHeight = bb[3] - bb[1],
shifty = 0,
height = +bb[1] + (origin == "baseline" ? lineHeight + +font.face.descent : lineHeight / 2);
for (var i = 0, ii = letters.length; i < ii; i++) {
if (letters[i] == "\n") {
shift = 0;
curr = 0;
notfirst = 0;
shifty += lineHeight * line_spacing
} else {
var prev = notfirst && font.glyphs[letters[i - 1]] || {},
curr = font.glyphs[letters[i]];
shift += notfirst ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + font.w * letter_spacing : 0;
notfirst = 1
}
if (curr && curr.d) {
path += R.transformPath(curr.d, ["t", shift * scale, shifty * scale, "s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale])
}
}
}
return this.path(path).attr({
fill: "#000",
stroke: "none"
})
};
paperproto.add = function(json) {
if (R.is(json, "array")) {
var res = this.set(),
i = 0,
ii = json.length,
j;
for (; i < ii; i++) {
j = json[i] || {};
elements[has](j.type) && res.push(this[j.type]().attr(j))
}
}
return res
};
R.format = function(token, params) {
var args = R.is(params, array) ? [0][concat](params) : arguments;
token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function(str, i) {
return args[++i] == null ? E : args[i]
}));
return token || E
};
R.fullfill = function() {
var tokenRegex = /\{([^\}]+)\}/g,
objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,
replacer = function(all, key, obj) {
var res = obj;
key.replace(objNotationRegex, function(all, name, quote, quotedName, isFunc) {
name = name || quotedName;
if (res) {
if (name in res) {
res = res[name]
}
typeof res == "function" && isFunc && (res = res())
}
});
res = (res == null || res == obj ? all : res) + "";
return res
};
return function(str, obj) {
return String(str).replace(tokenRegex, function(all, key) {
return replacer(all, key, obj)
})
}
}();
R.ninja = function() {
oldRaphael.was ? g.win.Raphael = oldRaphael.is : delete Raphael;
return R
};
R.st = setproto;
! function(doc, loaded, f) {
if (doc.readyState == null && doc.addEventListener) {
doc.addEventListener(loaded, f = function() {
doc.removeEventListener(loaded, f, false);
doc.readyState = "complete"
}, false);
doc.readyState = "loading"
}
function isLoaded() {
/in/.test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload")
}
isLoaded()
}(document, "DOMContentLoaded");
eve.on("raphael.DOMload", function() {
loaded = true
});
! function() {
if (!R.svg) {
return
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
toInt = parseInt,
math = Math,
mmax = math.max,
abs = math.abs,
pow = math.pow,
separator = /[, ]+/,
eve = R.eve,
E = "",
S = " ";
var xlink = "http://www.w3.org/1999/xlink",
markers = {
block: "M5,0 0,2.5 5,5z",
classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z",
diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z",
open: "M6,1 1,3.5 6,6",
oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"
},
markerCounter = {};
R.toString = function() {
return "Your browser supports SVG.\nYou are running Raphaël " + this.version
};
var $ = function(el, attr) {
if (attr) {
if (typeof el == "string") {
el = $(el)
}
for (var key in attr)
if (attr[has](key)) {
if (key.substring(0, 6) == "xlink:") {
el.setAttributeNS(xlink, key.substring(6), Str(attr[key]))
} else {
el.setAttribute(key, Str(attr[key]))
}
}
} else {
el = R._g.doc.createElementNS("http://www.w3.org/2000/svg", el);
el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)")
}
return el
},
addGradientFill = function(element, gradient) {
var type = "linear",
id = element.id + gradient,
fx = .5,
fy = .5,
o = element.node,
SVG = element.paper,
s = o.style,
el = R._g.doc.getElementById(id);
if (!el) {
gradient = Str(gradient).replace(R._radial_gradient, function(all, _fx, _fy) {
type = "radial";
if (_fx && _fy) {
fx = toFloat(_fx);
fy = toFloat(_fy);
var dir = (fy > .5) * 2 - 1;
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) && fy != .5 && (fy = fy.toFixed(5) - 1e-5 * dir)
}
return E
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null
}
var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))],
max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1);
vector[2] *= max;
vector[3] *= max;
if (vector[2] < 0) {
vector[0] = -vector[2];
vector[2] = 0
}
if (vector[3] < 0) {
vector[1] = -vector[3];
vector[3] = 0
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null
}
id = id.replace(/[\(\)\s,\xb0#]/g, "_");
if (element.gradient && id != element.gradient.id) {
SVG.defs.removeChild(element.gradient);
delete element.gradient
}
if (!element.gradient) {
el = $(type + "Gradient", {
id: id
});
element.gradient = el;
$(el, type == "radial" ? {
fx: fx,
fy: fy
} : {
x1: vector[0],
y1: vector[1],
x2: vector[2],
y2: vector[3],
gradientTransform: element.matrix.invert()
});
SVG.defs.appendChild(el);
for (var i = 0, ii = dots.length; i < ii; i++) {
el.appendChild($("stop", {
offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%",
"stop-color": dots[i].color || "#fff"
}))
}
}
}
$(o, {
fill: "url(#" + id + ")",
opacity: 1,
"fill-opacity": 1
});
s.fill = E;
s.opacity = 1;
s.fillOpacity = 1;
return 1
},
updatePosition = function(o) {
var bbox = o.getBBox(1);
$(o.pattern, {
patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"
})
},
addArrow = function(o, value, isEnd) {
if (o.type == "path") {
var values = Str(value).toLowerCase().split("-"),
p = o.paper,
se = isEnd ? "end" : "start",
node = o.node,
attrs = o.attrs,
stroke = attrs["stroke-width"],
i = values.length,
type = "classic",
from, to, dx, refX, attr, w = 3,
h = 3,
t = 5;
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide":
h = 5;
break;
case "narrow":
h = 2;
break;
case "long":
w = 5;
break;
case "short":
w = 2;
break
}
}
if (type == "open") {
w += 2;
h += 2;
t += 2;
dx = 1;
refX = isEnd ? 4 : 1;
attr = {
fill: "none",
stroke: attrs.stroke
}
} else {
refX = dx = w / 2;
attr = {
fill: attrs.stroke,
stroke: "none"
}
}
if (o._.arrows) {
if (isEnd) {
o._.arrows.endPath && markerCounter[o._.arrows.endPath]--;
o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--
} else {
o._.arrows.startPath && markerCounter[o._.arrows.startPath]--;
o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--
}
} else {
o._.arrows = {}
}
if (type != "none") {
var pathId = "raphael-marker-" + type,
markerId = "raphael-marker-" + se + type + w + h;
if (!R._g.doc.getElementById(pathId)) {
p.defs.appendChild($($("path"), {
"stroke-linecap": "round",
d: markers[type],
id: pathId
}));
markerCounter[pathId] = 1
} else {
markerCounter[pathId]++
}
var marker = R._g.doc.getElementById(markerId),
use;
if (!marker) {
marker = $($("marker"), {
id: markerId,
markerHeight: h,
markerWidth: w,
orient: "auto",
refX: refX,
refY: h / 2
});
use = $($("use"), {
"xlink:href": "#" + pathId,
transform: (isEnd ? "rotate(180 " + w / 2 + " " + h / 2 + ") " : E) + "scale(" + w / t + "," + h / t + ")",
"stroke-width": (1 / ((w / t + h / t) / 2)).toFixed(4)
});
marker.appendChild(use);
p.defs.appendChild(marker);
markerCounter[markerId] = 1
} else {
markerCounter[markerId]++;
use = marker.getElementsByTagName("use")[0]
}
$(use, attr);
var delta = dx * (type != "diamond" && type != "oval");
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - delta * stroke
} else {
from = delta * stroke;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0)
}
attr = {};
attr["marker-" + se] = "url(#" + markerId + ")";
if (to || from) {
attr.d = R.getSubpath(attrs.path, from, to)
}
$(node, attr);
o._.arrows[se + "Path"] = pathId;
o._.arrows[se + "Marker"] = markerId;
o._.arrows[se + "dx"] = delta;
o._.arrows[se + "Type"] = type;
o._.arrows[se + "String"] = value
} else {
if (isEnd) {
from = o._.arrows.startdx * stroke || 0;
to = R.getTotalLength(attrs.path) - from
} else {
from = 0;
to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0)
}
o._.arrows[se + "Path"] && $(node, {
d: R.getSubpath(attrs.path, from, to)
});
delete o._.arrows[se + "Path"];
delete o._.arrows[se + "Marker"];
delete o._.arrows[se + "dx"];
delete o._.arrows[se + "Type"];
delete o._.arrows[se + "String"]
}
for (attr in markerCounter)
if (markerCounter[has](attr) && !markerCounter[attr]) {
var item = R._g.doc.getElementById(attr);
item && item.parentNode.removeChild(item)
}
}
},
dasharray = {
"": [0],
none: [0],
"-": [3, 1],
".": [1, 1],
"-.": [3, 1, 1, 1],
"-..": [3, 1, 1, 1, 1, 1],
". ": [1, 3],
"- ": [4, 3],
"--": [8, 3],
"- .": [4, 3, 1, 3],
"--.": [8, 3, 1, 3],
"--..": [8, 3, 1, 3, 1, 3]
},
addDashes = function(o, value, params) {
value = dasharray[Str(value).toLowerCase()];
if (value) {
var width = o.attrs["stroke-width"] || "1",
butt = {
round: width,
square: width,
butt: 0
}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0,
dashes = [],
i = value.length;
while (i--) {
dashes[i] = value[i] * width + (i % 2 ? 1 : -1) * butt
}
$(o.node, {
"stroke-dasharray": dashes.join(",")
})
}
},
setFillAndStroke = function(o, params) {
var node = o.node,
attrs = o.attrs,
vis = node.style.visibility;
node.style.visibility = "hidden";
for (var att in params) {
if (params[has](att)) {
if (!R._availableAttrs[has](att)) {
continue
}
var value = params[att];
attrs[att] = value;
switch (att) {
case "blur":
o.blur(value);
break;
case "href":
case "title":
var hl = $("title");
var val = R._g.doc.createTextNode(value);
hl.appendChild(val);
node.appendChild(hl);
break;
case "target":
var pn = node.parentNode;
if (pn.tagName.toLowerCase() != "a") {
var hl = $("a");
pn.insertBefore(hl, node);
hl.appendChild(node);
pn = hl
}
if (att == "target") {
pn.setAttributeNS(xlink, "show", value == "blank" ? "new" : value)
} else {
pn.setAttributeNS(xlink, att, value)
}
break;
case "cursor":
node.style.cursor = value;
break;
case "transform":
o.transform(value);
break;
case "arrow-start":
addArrow(o, value);
break;
case "arrow-end":
addArrow(o, value, 1);
break;
case "clip-rect":
var rect = Str(value).split(separator);
if (rect.length == 4) {
o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode);
var el = $("clipPath"),
rc = $("rect");
el.id = R.createUUID();
$(rc, {
x: rect[0],
y: rect[1],
width: rect[2],
height: rect[3]
});
el.appendChild(rc);
o.paper.defs.appendChild(el);
$(node, {
"clip-path": "url(#" + el.id + ")"
});
o.clip = rc
}
if (!value) {
var path = node.getAttribute("clip-path");
if (path) {
var clip = R._g.doc.getElementById(path.replace(/(^url\(#|\)$)/g, E));
clip && clip.parentNode.removeChild(clip);
$(node, {
"clip-path": E
});
delete o.clip
}
}
break;
case "path":
if (o.type == "path") {
$(node, {
d: value ? attrs.path = R._pathToAbsolute(value) : "M0,0"
});
o._.dirty = 1;
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1)
}
}
break;
case "width":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fx) {
att = "x";
value = attrs.x
} else {
break
}
case "x":
if (attrs.fx) {
value = -attrs.x - (attrs.width || 0)
}
case "rx":
if (att == "rx" && o.type == "rect") {
break
}
case "cx":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "height":
node.setAttribute(att, value);
o._.dirty = 1;
if (attrs.fy) {
att = "y";
value = attrs.y
} else {
break
}
case "y":
if (attrs.fy) {
value = -attrs.y - (attrs.height || 0)
}
case "ry":
if (att == "ry" && o.type == "rect") {
break
}
case "cy":
node.setAttribute(att, value);
o.pattern && updatePosition(o);
o._.dirty = 1;
break;
case "r":
if (o.type == "rect") {
$(node, {
rx: value,
ry: value
})
} else {
node.setAttribute(att, value)
}
o._.dirty = 1;
break;
case "src":
if (o.type == "image") {
node.setAttributeNS(xlink, "href", value)
}
break;
case "stroke-width":
if (o._.sx != 1 || o._.sy != 1) {
value /= mmax(abs(o._.sx), abs(o._.sy)) || 1
}
if (o.paper._vbSize) {
value *= o.paper._vbSize
}
node.setAttribute(att, value);
if (attrs["stroke-dasharray"]) {
addDashes(o, attrs["stroke-dasharray"], params)
}
if (o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1)
}
break;
case "stroke-dasharray":
addDashes(o, value, params);
break;
case "fill":
var isURL = Str(value).match(R._ISURL);
if (isURL) {
var existingImages = o.paper.defs.getElementsByTagName("image");
for (var i = 0; i < existingImages.length; i++) {
if (existingImages[i].href.baseVal === isURL[1]) {
el = existingImages[i].parentNode
}
}
if (!el) {
el = $("pattern");
var ig = $("image");
el.id = R.createUUID();
$(el, {
x: 0,
y: 0,
patternUnits: "userSpaceOnUse",
height: 1,
width: 1
});
$(ig, {
x: 0,
y: 0,
"xlink:href": isURL[1]
});
el.appendChild(ig);
! function(el) {
R._preload(isURL[1], function() {
var w = this.offsetWidth,
h = this.offsetHeight;
$(el, {
width: w,
height: h
});
$(ig, {
width: w,
height: h
});
o.paper.safari()
})
}(el);
o.paper.defs.appendChild(el)
}
$(node, {
fill: "url(#" + el.id + ")"
});
o.pattern = el;
o.pattern && updatePosition(o);
break
}
var clr = R.getRGB(value);
if (!clr.error) {
delete params.gradient;
delete attrs.gradient;
!R.is(attrs.opacity, "undefined") && R.is(params.opacity, "undefined") && $(node, {
opacity: attrs.opacity
});
!R.is(attrs["fill-opacity"], "undefined") && R.is(params["fill-opacity"], "undefined") && $(node, {
"fill-opacity": attrs["fill-opacity"]
})
} else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) {
if ("opacity" in attrs || "fill-opacity" in attrs) {
var gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
var stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {
"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)
})
}
}
attrs.gradient = value;
attrs.fill = "none";
break
}
clr[has]("opacity") && $(node, {
"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity
});
case "stroke":
clr = R.getRGB(value);
node.setAttribute(att, clr.hex);
att == "stroke" && clr[has]("opacity") && $(node, {
"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity
});
if (att == "stroke" && o._.arrows) {
"startString" in o._.arrows && addArrow(o, o._.arrows.startString);
"endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1)
}
break;
case "gradient":
(o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value);
break;
case "opacity":
if (attrs.gradient && !attrs[has]("stroke-opacity")) {
$(node, {
"stroke-opacity": value > 1 ? value / 100 : value
})
}
case "fill-opacity":
if (attrs.gradient) {
gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E));
if (gradient) {
stops = gradient.getElementsByTagName("stop");
$(stops[stops.length - 1], {
"stop-opacity": value
})
}
break
}
default:
att == "font-size" && (value = toInt(value, 10) + "px");
var cssrule = att.replace(/(\-.)/g, function(w) {
return w.substring(1).toUpperCase()
});
node.style[cssrule] = value;
o._.dirty = 1;
node.setAttribute(att, value);
break
}
}
}
tuneText(o, params);
node.style.visibility = vis
},
leading = 1.2,
tuneText = function(el, params) {
if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) {
return
}
var a = el.attrs,
node = el.node,
fontSize = node.firstChild ? toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10;
if (params[has]("text")) {
a.text = params.text;
while (node.firstChild) {
node.removeChild(node.firstChild)
}
var texts = Str(params.text).split("\n"),
tspans = [],
tspan;
for (var i = 0, ii = texts.length; i < ii; i++) {
tspan = $("tspan");
i && $(tspan, {
dy: fontSize * leading,
x: a.x
});
tspan.appendChild(R._g.doc.createTextNode(texts[i]));
node.appendChild(tspan);
tspans[i] = tspan
}
} else {
tspans = node.getElementsByTagName("tspan");
for (i = 0, ii = tspans.length; i < ii; i++)
if (i) {
$(tspans[i], {
dy: fontSize * leading,
x: a.x
})
} else {
$(tspans[0], {
dy: 0
})
}
}
$(node, {
x: a.x,
y: a.y
});
el._.dirty = 1;
var bb = el._getBBox(),
dif = a.y - (bb.y + bb.height / 2);
dif && R.is(dif, "finite") && $(tspans[0], {
dy: dif
})
},
Element = function(node, svg) {
var X = 0,
Y = 0;
this[0] = this.node = node;
node.raphael = true;
this.id = R._oid++;
node.raphaelid = this.id;
this.matrix = R.matrix();
this.realPath = null;
this.paper = svg;
this.attrs = this.attrs || {};
this._ = {
transform: [],
sx: 1,
sy: 1,
deg: 0,
dx: 0,
dy: 0,
dirty: 1
};
!svg.bottom && (svg.bottom = this);
this.prev = svg.top;
svg.top && (svg.top.next = this);
svg.top = this;
this.next = null
},
elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
R._engine.path = function(pathString, SVG) {
var el = $("path");
SVG.canvas && SVG.canvas.appendChild(el);
var p = new Element(el, SVG);
p.type = "path";
setFillAndStroke(p, {
fill: "none",
stroke: "#000",
path: pathString
});
return p
};
elproto.rotate = function(deg, cx, cy) {
if (this.removed) {
return this
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2])
}
deg = toFloat(deg[0]);
cy == null && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2
}
this.transform(this._.transform.concat([
["r", deg, cx, cy]
]));
return this
};
elproto.scale = function(sx, sy, cx, cy) {
if (this.removed) {
return this
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3])
}
sx = toFloat(sx[0]);
sy == null && (sy = sx);
cy == null && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1)
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([
["s", sx, sy, cx, cy]
]));
return this
};
elproto.translate = function(dx, dy) {
if (this.removed) {
return this
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1])
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
this.transform(this._.transform.concat([
["t", dx, dy]
]));
return this
};
elproto.transform = function(tstr) {
var _ = this._;
if (tstr == null) {
return _.transform
}
R._extractTransform(this, tstr);
this.clip && $(this.clip, {
transform: this.matrix.invert()
});
this.pattern && updatePosition(this);
this.node && $(this.node, {
transform: this.matrix
});
if (_.sx != 1 || _.sy != 1) {
var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1;
this.attr({
"stroke-width": sw
})
}
return this
};
elproto.hide = function() {
!this.removed && this.paper.safari(this.node.style.display = "none");
return this
};
elproto.show = function() {
!this.removed && this.paper.safari(this.node.style.display = "");
return this
};
elproto.remove = function() {
if (this.removed || !this.node.parentNode) {
return
}
var paper = this.paper;
paper.__set__ && paper.__set__.exclude(this);
eve.unbind("raphael.*.*." + this.id);
if (this.gradient) {
paper.defs.removeChild(this.gradient)
}
R._tear(this, paper);
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.removeChild(this.node.parentNode)
} else {
this.node.parentNode.removeChild(this.node)
}
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null
}
this.removed = true
};
elproto._getBBox = function() {
if (this.node.style.display == "none") {
this.show();
var hide = true
}
var bbox = {};
try {
bbox = this.node.getBBox()
} catch (e) {} finally {
bbox = bbox || {}
}
hide && this.hide();
return bbox
};
elproto.attr = function(name, value) {
if (this.removed) {
return this
}
if (name == null) {
var res = {};
for (var a in this.attrs)
if (this.attrs[has](a)) {
res[a] = this.attrs[a]
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res
}
if (value == null && R.is(name, "string")) {
if (name == "fill" && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient
}
if (name == "transform") {
return this._.transform
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name]
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def
} else {
out[name] = R._availableAttrs[name]
}
}
return ii - 1 ? out : out[names[0]]
}
if (value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i])
}
return out
}
if (value != null) {
var params = {};
params[name] = value
} else if (name != null && R.is(name, "object")) {
params = name
}
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key])
}
for (key in this.paper.customAttributes)
if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par)
if (par[has](subkey)) {
params[subkey] = par[subkey]
}
}
setFillAndStroke(this, params);
return this
};
elproto.toFront = function() {
if (this.removed) {
return this
}
if (this.node.parentNode.tagName.toLowerCase() == "a") {
this.node.parentNode.parentNode.appendChild(this.node.parentNode)
} else {
this.node.parentNode.appendChild(this.node)
}
var svg = this.paper;
svg.top != this && R._tofront(this, svg);
return this
};
elproto.toBack = function() {
if (this.removed) {
return this
}
var parent = this.node.parentNode;
if (parent.tagName.toLowerCase() == "a") {
parent.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild)
} else if (parent.firstChild != this.node) {
parent.insertBefore(this.node, this.node.parentNode.firstChild)
}
R._toback(this, this.paper);
var svg = this.paper;
return this
};
elproto.insertAfter = function(element) {
if (this.removed) {
return this
}
var node = element.node || element[element.length - 1].node;
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling)
} else {
node.parentNode.appendChild(this.node)
}
R._insertafter(this, element, this.paper);
return this
};
elproto.insertBefore = function(element) {
if (this.removed) {
return this
}
var node = element.node || element[0].node;
node.parentNode.insertBefore(this.node, node);
R._insertbefore(this, element, this.paper);
return this
};
elproto.blur = function(size) {
var t = this;
if (+size !== 0) {
var fltr = $("filter"),
blur = $("feGaussianBlur");
t.attrs.blur = size;
fltr.id = R.createUUID();
$(blur, {
stdDeviation: +size || 1.5
});
fltr.appendChild(blur);
t.paper.defs.appendChild(fltr);
t._blur = fltr;
$(t.node, {
filter: "url(#" + fltr.id + ")"
})
} else {
if (t._blur) {
t._blur.parentNode.removeChild(t._blur);
delete t._blur;
delete t.attrs.blur
}
t.node.removeAttribute("filter")
}
return t
};
R._engine.circle = function(svg, x, y, r) {
var el = $("circle");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
cx: x,
cy: y,
r: r,
fill: "none",
stroke: "#000"
};
res.type = "circle";
$(el, res.attrs);
return res
};
R._engine.rect = function(svg, x, y, w, h, r) {
var el = $("rect");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
x: x,
y: y,
width: w,
height: h,
r: r || 0,
rx: r || 0,
ry: r || 0,
fill: "none",
stroke: "#000"
};
res.type = "rect";
$(el, res.attrs);
return res
};
R._engine.ellipse = function(svg, x, y, rx, ry) {
var el = $("ellipse");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
cx: x,
cy: y,
rx: rx,
ry: ry,
fill: "none",
stroke: "#000"
};
res.type = "ellipse";
$(el, res.attrs);
return res
};
R._engine.image = function(svg, src, x, y, w, h) {
var el = $("image");
$(el, {
x: x,
y: y,
width: w,
height: h,
preserveAspectRatio: "none"
});
el.setAttributeNS(xlink, "href", src);
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
x: x,
y: y,
width: w,
height: h,
src: src
};
res.type = "image";
return res
};
R._engine.text = function(svg, x, y, text) {
var el = $("text");
svg.canvas && svg.canvas.appendChild(el);
var res = new Element(el, svg);
res.attrs = {
x: x,
y: y,
"text-anchor": "middle",
text: text,
font: R._availableAttrs.font,
stroke: "none",
fill: "#000"
};
res.type = "text";
setFillAndStroke(res, res.attrs);
return res
};
R._engine.setSize = function(width, height) {
this.width = width || this.width;
this.height = height || this.height;
this.canvas.setAttribute("width", this.width);
this.canvas.setAttribute("height", this.height);
if (this._viewBox) {
this.setViewBox.apply(this, this._viewBox)
}
return this
};
R._engine.create = function() {
var con = R._getContainer.apply(0, arguments),
container = con && con.container,
x = con.x,
y = con.y,
width = con.width,
height = con.height;
if (!container) {
throw new Error("SVG container not found.")
}
var cnvs = $("svg"),
css = "overflow:hidden;",
isFloating;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
$(cnvs, {
height: height,
version: 1.1,
width: width,
xmlns: "http://www.w3.org/2000/svg"
});
if (container == 1) {
cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px";
R._g.doc.body.appendChild(cnvs);
isFloating = 1
} else {
cnvs.style.cssText = css + "position:relative";
if (container.firstChild) {
container.insertBefore(cnvs, container.firstChild)
} else {
container.appendChild(cnvs)
}
}
container = new R._Paper;
container.width = width;
container.height = height;
container.canvas = cnvs;
container.clear();
container._left = container._top = 0;
isFloating && (container.renderfix = function() {});
container.renderfix();
return container
};
R._engine.setViewBox = function(x, y, w, h, fit) {
eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var size = mmax(w / this.width, h / this.height),
top = this.top,
aspectRatio = fit ? "meet" : "xMinYMin",
vb, sw;
if (x == null) {
if (this._vbSize) {
size = 1
}
delete this._vbSize;
vb = "0 0 " + this.width + S + this.height
} else {
this._vbSize = size;
vb = x + S + y + S + w + S + h
}
$(this.canvas, {
viewBox: vb,
preserveAspectRatio: aspectRatio
});
while (size && top) {
sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1;
top.attr({
"stroke-width": sw
});
top._.dirty = 1;
top._.dirtyT = 1;
top = top.prev
}
this._viewBox = [x, y, w, h, !!fit];
return this
};
R.prototype.renderfix = function() {
var cnvs = this.canvas,
s = cnvs.style,
pos;
try {
pos = cnvs.getScreenCTM() || cnvs.createSVGMatrix()
} catch (e) {
pos = cnvs.createSVGMatrix()
}
var left = -pos.e % 1,
top = -pos.f % 1;
if (left || top) {
if (left) {
this._left = (this._left + left) % 1;
s.left = this._left + "px"
}
if (top) {
this._top = (this._top + top) % 1;
s.top = this._top + "px"
}
}
};
R.prototype.clear = function() {
R.eve("raphael.clear", this);
var c = this.canvas;
while (c.firstChild) {
c.removeChild(c.firstChild)
}
this.bottom = this.top = null;
(this.desc = $("desc")).appendChild(R._g.doc.createTextNode("Created with Raphaël " + R.version));
c.appendChild(this.desc);
c.appendChild(this.defs = $("defs"))
};
R.prototype.remove = function() {
eve("raphael.remove", this);
this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null
}
};
var setproto = R.st;
for (var method in elproto)
if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = function(methodname) {
return function() {
var arg = arguments;
return this.forEach(function(el) {
el[methodname].apply(el, arg)
})
}
}(method)
}
}();
! function() {
if (!R.vml) {
return
}
var has = "hasOwnProperty",
Str = String,
toFloat = parseFloat,
math = Math,
round = math.round,
mmax = math.max,
mmin = math.min,
abs = math.abs,
fillString = "fill",
separator = /[, ]+/,
eve = R.eve,
ms = " progid:DXImageTransform.Microsoft",
S = " ",
E = "",
map = {
M: "m",
L: "l",
C: "c",
Z: "x",
m: "t",
l: "r",
c: "v",
z: "x"
},
bites = /([clmz]),?([^clmz]*)/gi,
blurregexp = / progid:\S+Blur\([^\)]+\)/g,
val = /-?[^,\s-]+/g,
cssDot = "position:absolute;left:0;top:0;width:1px;height:1px",
zoom = 21600,
pathTypes = {
path: 1,
rect: 1,
image: 1
},
ovalTypes = {
circle: 1,
ellipse: 1
},
path2vml = function(path) {
var total = /[ahqstv]/gi,
command = R._pathToAbsolute;
Str(path).match(total) && (command = R._path2curve);
total = /[clmz]/g;
if (command == R._pathToAbsolute && !Str(path).match(total)) {
var res = Str(path).replace(bites, function(all, command, args) {
var vals = [],
isMove = command.toLowerCase() == "m",
res = map[command];
args.replace(val, function(value) {
if (isMove && vals.length == 2) {
res += vals + map[command == "m" ? "l" : "L"];
vals = []
}
vals.push(round(value * zoom))
});
return res + vals
});
return res
}
var pa = command(path),
p, r;
res = [];
for (var i = 0, ii = pa.length; i < ii; i++) {
p = pa[i];
r = pa[i][0].toLowerCase();
r == "z" && (r = "x");
for (var j = 1, jj = p.length; j < jj; j++) {
r += round(p[j] * zoom) + (j != jj - 1 ? "," : E)
}
res.push(r)
}
return res.join(S)
},
compensation = function(deg, dx, dy) {
var m = R.matrix();
m.rotate(-deg, .5, .5);
return {
dx: m.x(dx, dy),
dy: m.y(dx, dy)
}
},
setCoords = function(p, sx, sy, dx, dy, deg) {
var _ = p._,
m = p.matrix,
fillpos = _.fillpos,
o = p.node,
s = o.style,
y = 1,
flip = "",
dxdy, kx = zoom / sx,
ky = zoom / sy;
s.visibility = "hidden";
if (!sx || !sy) {
return
}
o.coordsize = abs(kx) + S + abs(ky);
s.rotation = deg * (sx * sy < 0 ? -1 : 1);
if (deg) {
var c = compensation(deg, dx, dy);
dx = c.dx;
dy = c.dy
}
sx < 0 && (flip += "x");
sy < 0 && (flip += " y") && (y = -1);
s.flip = flip;
o.coordorigin = dx * -kx + S + dy * -ky;
if (fillpos || _.fillsize) {
var fill = o.getElementsByTagName(fillString);
fill = fill && fill[0];
o.removeChild(fill);
if (fillpos) {
c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1]));
fill.position = c.dx * y + S + c.dy * y
}
if (_.fillsize) {
fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy)
}
o.appendChild(fill)
}
s.visibility = "visible"
};
R.toString = function() {
return "Your browser doesn’t support SVG. Falling down to VML.\nYou are running Raphaël " + this.version
};
var addArrow = function(o, value, isEnd) {
var values = Str(value).toLowerCase().split("-"),
se = isEnd ? "end" : "start",
i = values.length,
type = "classic",
w = "medium",
h = "medium";
while (i--) {
switch (values[i]) {
case "block":
case "classic":
case "oval":
case "diamond":
case "open":
case "none":
type = values[i];
break;
case "wide":
case "narrow":
h = values[i];
break;
case "long":
case "short":
w = values[i];
break
}
}
var stroke = o.node.getElementsByTagName("stroke")[0];
stroke[se + "arrow"] = type;
stroke[se + "arrowlength"] = w;
stroke[se + "arrowwidth"] = h
},
setFillAndStroke = function(o, params) {
o.attrs = o.attrs || {};
var node = o.node,
a = o.attrs,
s = node.style,
xy, newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r),
isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry),
res = o;
for (var par in params)
if (params[has](par)) {
a[par] = params[par]
}
if (newpath) {
a.path = R._getPath[o.type](o);
o._.dirty = 1
}
params.href && (node.href = params.href);
params.title && (node.title = params.title);
params.target && (node.target = params.target);
params.cursor && (s.cursor = params.cursor);
"blur" in params && o.blur(params.blur);
if (params.path && o.type == "path" || newpath) {
node.path = path2vml(~Str(a.path).toLowerCase().indexOf("r") ? R._pathToAbsolute(a.path) : a.path);
if (o.type == "image") {
o._.fillpos = [a.x, a.y];
o._.fillsize = [a.width, a.height];
setCoords(o, 1, 1, 0, 0, 0)
}
}
"transform" in params && o.transform(params.transform);
if (isOval) {
var cx = +a.cx,
cy = +a.cy,
rx = +a.rx || +a.r || 0,
ry = +a.ry || +a.r || 0;
node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom));
o._.dirty = 1
}
if ("clip-rect" in params) {
var rect = Str(params["clip-rect"]).split(separator);
if (rect.length == 4) {
rect[2] = +rect[2] + +rect[0];
rect[3] = +rect[3] + +rect[1];
var div = node.clipRect || R._g.doc.createElement("div"),
dstyle = div.style;
dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect);
if (!node.clipRect) {
dstyle.position = "absolute";
dstyle.top = 0;
dstyle.left = 0;
dstyle.width = o.paper.width + "px";
dstyle.height = o.paper.height + "px";
node.parentNode.insertBefore(div, node);
div.appendChild(node);
node.clipRect = div
}
}
if (!params["clip-rect"]) {
node.clipRect && (node.clipRect.style.clip = "auto")
}
}
if (o.textpath) {
var textpathStyle = o.textpath.style;
params.font && (textpathStyle.font = params.font);
params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"');
params["font-size"] && (textpathStyle.fontSize = params["font-size"]);
params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]);
params["font-style"] && (textpathStyle.fontStyle = params["font-style"])
}
if ("arrow-start" in params) {
addArrow(res, params["arrow-start"])
}
if ("arrow-end" in params) {
addArrow(res, params["arrow-end"], 1)
}
if (params.opacity != null || params["stroke-width"] != null || params.fill != null || params.src != null || params.stroke != null || params["stroke-width"] != null || params["stroke-opacity"] != null || params["fill-opacity"] != null || params["stroke-dasharray"] != null || params["stroke-miterlimit"] != null || params["stroke-linejoin"] != null || params["stroke-linecap"] != null) {
var fill = node.getElementsByTagName(fillString),
newfill = false;
fill = fill && fill[0];
!fill && (newfill = fill = createNode(fillString));
if (o.type == "image" && params.src) {
fill.src = params.src
}
params.fill && (fill.on = true);
if (fill.on == null || params.fill == "none" || params.fill === null) {
fill.on = false
}
if (fill.on && params.fill) {
var isURL = Str(params.fill).match(R._ISURL);
if (isURL) {
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = isURL[1];
fill.type = "tile";
var bbox = o.getBBox(1);
fill.position = bbox.x + S + bbox.y;
o._.fillpos = [bbox.x, bbox.y];
R._preload(isURL[1], function() {
o._.fillsize = [this.offsetWidth, this.offsetHeight]
})
} else {
fill.color = R.getRGB(params.fill).hex;
fill.src = E;
fill.type = "solid";
if (R.getRGB(params.fill).error && (res.type in {
circle: 1,
ellipse: 1
} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) {
a.fill = "none";
a.gradient = params.fill;
fill.rotate = false
}
}
}
if ("fill-opacity" in params || "opacity" in params) {
var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1);
opacity = mmin(mmax(opacity, 0), 1);
fill.opacity = opacity;
if (fill.src) {
fill.color = "none"
}
}
node.appendChild(fill);
var stroke = node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0],
newstroke = false;
!stroke && (newstroke = stroke = createNode("stroke"));
if (params.stroke && params.stroke != "none" || params["stroke-width"] || params["stroke-opacity"] != null || params["stroke-dasharray"] || params["stroke-miterlimit"] || params["stroke-linejoin"] || params["stroke-linecap"]) {
stroke.on = true
}(params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false);
var strokeColor = R.getRGB(params.stroke);
stroke.on && params.stroke && (stroke.color = strokeColor.hex);
opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1);
var width = (toFloat(params["stroke-width"]) || 1) * .75;
opacity = mmin(mmax(opacity, 0), 1);
params["stroke-width"] == null && (width = a["stroke-width"]);
params["stroke-width"] && (stroke.weight = width);
width && width < 1 && (opacity *= width) && (stroke.weight = 1);
stroke.opacity = opacity;
params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter");
stroke.miterlimit = params["stroke-miterlimit"] || 8;
params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round");
if (params["stroke-dasharray"]) {
var dasharray = {
"-": "shortdash",
".": "shortdot",
"-.": "shortdashdot",
"-..": "shortdashdotdot",
". ": "dot",
"- ": "dash",
"--": "longdash",
"- .": "dashdot",
"--.": "longdashdot",
"--..": "longdashdotdot"
};
stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E
}
newstroke && node.appendChild(stroke)
}
if (res.type == "text") {
res.paper.canvas.style.display = E;
var span = res.paper.span,
m = 100,
fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/);
s = span.style;
a.font && (s.font = a.font);
a["font-family"] && (s.fontFamily = a["font-family"]);
a["font-weight"] && (s.fontWeight = a["font-weight"]);
a["font-style"] && (s.fontStyle = a["font-style"]);
fontSize = toFloat(a["font-size"] || fontSize && fontSize[0]) || 10;
s.fontSize = fontSize * m + "px";
res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "<").replace(/&/g, "&").replace(/\n/g, "<br>"));
var brect = span.getBoundingClientRect();
res.W = a.w = (brect.right - brect.left) / m;
res.H = a.h = (brect.bottom - brect.top) / m;
res.X = a.x;
res.Y = a.y + res.H / 2;
("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1));
var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"];
for (var d = 0, dd = dirtyattrs.length; d < dd; d++)
if (dirtyattrs[d] in params) {
res._.dirty = 1;
break
}
switch (a["text-anchor"]) {
case "start":
res.textpath.style["v-text-align"] = "left";
res.bbx = res.W / 2;
break;
case "end":
res.textpath.style["v-text-align"] = "right";
res.bbx = -res.W / 2;
break;
default:
res.textpath.style["v-text-align"] = "center";
res.bbx = 0;
break
}
res.textpath.style["v-text-kern"] = true
}
},
addGradientFill = function(o, gradient, fill) {
o.attrs = o.attrs || {};
var attrs = o.attrs,
pow = Math.pow,
opacity, oindex, type = "linear",
fxfy = ".5 .5";
o.attrs.gradient = gradient;
gradient = Str(gradient).replace(R._radial_gradient, function(all, fx, fy) {
type = "radial";
if (fx && fy) {
fx = toFloat(fx);
fy = toFloat(fy);
pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5);
fxfy = fx + S + fy
}
return E
});
gradient = gradient.split(/\s*\-\s*/);
if (type == "linear") {
var angle = gradient.shift();
angle = -toFloat(angle);
if (isNaN(angle)) {
return null
}
}
var dots = R._parseDots(gradient);
if (!dots) {
return null
}
o = o.shape || o.node;
if (dots.length) {
o.removeChild(fill);
fill.on = true;
fill.method = "none";
fill.color = dots[0].color;
fill.color2 = dots[dots.length - 1].color;
var clrs = [];
for (var i = 0, ii = dots.length; i < ii; i++) {
dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color)
}
fill.colors = clrs.length ? clrs.join() : "0% " + fill.color;
if (type == "radial") {
fill.type = "gradientTitle";
fill.focus = "100%";
fill.focussize = "0 0";
fill.focusposition = fxfy;
fill.angle = 0
} else {
fill.type = "gradient";
fill.angle = (270 - angle) % 360
}
o.appendChild(fill)
}
return 1
},
Element = function(node, vml) {
this[0] = this.node = node;
node.raphael = true;
this.id = R._oid++;
node.raphaelid = this.id;
this.X = 0;
this.Y = 0;
this.attrs = {};
this.paper = vml;
this.matrix = R.matrix();
this._ = {
transform: [],
sx: 1,
sy: 1,
dx: 0,
dy: 0,
deg: 0,
dirty: 1,
dirtyT: 1
};
!vml.bottom && (vml.bottom = this);
this.prev = vml.top;
vml.top && (vml.top.next = this);
vml.top = this;
this.next = null
};
var elproto = R.el;
Element.prototype = elproto;
elproto.constructor = Element;
elproto.transform = function(tstr) {
if (tstr == null) {
return this._.transform
}
var vbs = this.paper._viewBoxShift,
vbt = vbs ? "s" + [vbs.scale, vbs.scale] + "-1-1t" + [vbs.dx, vbs.dy] : E,
oldt;
if (vbs) {
oldt = tstr = Str(tstr).replace(/\.{3}|\u2026/g, this._.transform || E)
}
R._extractTransform(this, vbt + tstr);
var matrix = this.matrix.clone(),
skew = this.skew,
o = this.node,
split, isGrad = ~Str(this.attrs.fill).indexOf("-"),
isPatt = !Str(this.attrs.fill).indexOf("url(");
matrix.translate(1, 1);
if (isPatt || isGrad || this.type == "image") {
skew.matrix = "1 0 0 1";
skew.offset = "0 0";
split = matrix.split();
if (isGrad && split.noRotation || !split.isSimple) {
o.style.filter = matrix.toFilter();
var bb = this.getBBox(),
bbt = this.getBBox(1),
dx = bb.x - bbt.x,
dy = bb.y - bbt.y;
o.coordorigin = dx * -zoom + S + dy * -zoom;
setCoords(this, 1, 1, dx, dy, 0)
} else {
o.style.filter = E;
setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate)
}
} else {
o.style.filter = E;
skew.matrix = Str(matrix);
skew.offset = matrix.offset()
}
oldt && (this._.transform = oldt);
return this
};
elproto.rotate = function(deg, cx, cy) {
if (this.removed) {
return this
}
if (deg == null) {
return
}
deg = Str(deg).split(separator);
if (deg.length - 1) {
cx = toFloat(deg[1]);
cy = toFloat(deg[2])
}
deg = toFloat(deg[0]);
cy == null && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1);
cx = bbox.x + bbox.width / 2;
cy = bbox.y + bbox.height / 2
}
this._.dirtyT = 1;
this.transform(this._.transform.concat([
["r", deg, cx, cy]
]));
return this
};
elproto.translate = function(dx, dy) {
if (this.removed) {
return this
}
dx = Str(dx).split(separator);
if (dx.length - 1) {
dy = toFloat(dx[1])
}
dx = toFloat(dx[0]) || 0;
dy = +dy || 0;
if (this._.bbox) {
this._.bbox.x += dx;
this._.bbox.y += dy
}
this.transform(this._.transform.concat([
["t", dx, dy]
]));
return this
};
elproto.scale = function(sx, sy, cx, cy) {
if (this.removed) {
return this
}
sx = Str(sx).split(separator);
if (sx.length - 1) {
sy = toFloat(sx[1]);
cx = toFloat(sx[2]);
cy = toFloat(sx[3]);
isNaN(cx) && (cx = null);
isNaN(cy) && (cy = null)
}
sx = toFloat(sx[0]);
sy == null && (sy = sx);
cy == null && (cx = cy);
if (cx == null || cy == null) {
var bbox = this.getBBox(1)
}
cx = cx == null ? bbox.x + bbox.width / 2 : cx;
cy = cy == null ? bbox.y + bbox.height / 2 : cy;
this.transform(this._.transform.concat([
["s", sx, sy, cx, cy]
]));
this._.dirtyT = 1;
return this
};
elproto.hide = function() {
!this.removed && (this.node.style.display = "none");
return this
};
elproto.show = function() {
!this.removed && (this.node.style.display = E);
return this
};
elproto._getBBox = function() {
if (this.removed) {
return {}
}
return {
x: this.X + (this.bbx || 0) - this.W / 2,
y: this.Y - this.H,
width: this.W,
height: this.H
}
};
elproto.remove = function() {
if (this.removed || !this.node.parentNode) {
return
}
this.paper.__set__ && this.paper.__set__.exclude(this);
R.eve.unbind("raphael.*.*." + this.id);
R._tear(this, this.paper);
this.node.parentNode.removeChild(this.node);
this.shape && this.shape.parentNode.removeChild(this.shape);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null
}
this.removed = true
};
elproto.attr = function(name, value) {
if (this.removed) {
return this
}
if (name == null) {
var res = {};
for (var a in this.attrs)
if (this.attrs[has](a)) {
res[a] = this.attrs[a]
}
res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient;
res.transform = this._.transform;
return res
}
if (value == null && R.is(name, "string")) {
if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) {
return this.attrs.gradient
}
var names = name.split(separator),
out = {};
for (var i = 0, ii = names.length; i < ii; i++) {
name = names[i];
if (name in this.attrs) {
out[name] = this.attrs[name]
} else if (R.is(this.paper.customAttributes[name], "function")) {
out[name] = this.paper.customAttributes[name].def
} else {
out[name] = R._availableAttrs[name]
}
}
return ii - 1 ? out : out[names[0]]
}
if (this.attrs && value == null && R.is(name, "array")) {
out = {};
for (i = 0, ii = name.length; i < ii; i++) {
out[name[i]] = this.attr(name[i])
}
return out
}
var params;
if (value != null) {
params = {};
params[name] = value
}
value == null && R.is(name, "object") && (params = name);
for (var key in params) {
eve("raphael.attr." + key + "." + this.id, this, params[key])
}
if (params) {
for (key in this.paper.customAttributes)
if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) {
var par = this.paper.customAttributes[key].apply(this, [].concat(params[key]));
this.attrs[key] = params[key];
for (var subkey in par)
if (par[has](subkey)) {
params[subkey] = par[subkey]
}
}
if (params.text && this.type == "text") {
this.textpath.string = params.text
}
setFillAndStroke(this, params)
}
return this
};
elproto.toFront = function() {
!this.removed && this.node.parentNode.appendChild(this.node);
this.paper && this.paper.top != this && R._tofront(this, this.paper);
return this
};
elproto.toBack = function() {
if (this.removed) {
return this
}
if (this.node.parentNode.firstChild != this.node) {
this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild);
R._toback(this, this.paper)
}
return this
};
elproto.insertAfter = function(element) {
if (this.removed) {
return this
}
if (element.constructor == R.st.constructor) {
element = element[element.length - 1]
}
if (element.node.nextSibling) {
element.node.parentNode.insertBefore(this.node, element.node.nextSibling)
} else {
element.node.parentNode.appendChild(this.node)
}
R._insertafter(this, element, this.paper);
return this
};
elproto.insertBefore = function(element) {
if (this.removed) {
return this
}
if (element.constructor == R.st.constructor) {
element = element[0]
}
element.node.parentNode.insertBefore(this.node, element.node);
R._insertbefore(this, element, this.paper);
return this
};
elproto.blur = function(size) {
var s = this.node.runtimeStyle,
f = s.filter;
f = f.replace(blurregexp, E);
if (+size !== 0) {
this.attrs.blur = size;
s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")";
s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5))
} else {
s.filter = f;
s.margin = 0;
delete this.attrs.blur
}
return this
};
R._engine.path = function(pathString, vml) {
var el = createNode("shape");
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = vml.coordorigin;
var p = new Element(el, vml),
attr = {
fill: "none",
stroke: "#000"
};
pathString && (attr.path = pathString);
p.type = "path";
p.path = [];
p.Path = E;
setFillAndStroke(p, attr);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p
};
R._engine.rect = function(vml, x, y, w, h, r) {
var path = R._rectPath(x, y, w, h, r),
res = vml.path(path),
a = res.attrs;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.r = r;
a.path = path;
res.type = "rect";
return res
};
R._engine.ellipse = function(vml, x, y, rx, ry) {
var res = vml.path(),
a = res.attrs;
res.X = x - rx;
res.Y = y - ry;
res.W = rx * 2;
res.H = ry * 2;
res.type = "ellipse";
setFillAndStroke(res, {
cx: x,
cy: y,
rx: rx,
ry: ry
});
return res
};
R._engine.circle = function(vml, x, y, r) {
var res = vml.path(),
a = res.attrs;
res.X = x - r;
res.Y = y - r;
res.W = res.H = r * 2;
res.type = "circle";
setFillAndStroke(res, {
cx: x,
cy: y,
r: r
});
return res
};
R._engine.image = function(vml, src, x, y, w, h) {
var path = R._rectPath(x, y, w, h),
res = vml.path(path).attr({
stroke: "none"
}),
a = res.attrs,
node = res.node,
fill = node.getElementsByTagName(fillString)[0];
a.src = src;
res.X = a.x = x;
res.Y = a.y = y;
res.W = a.width = w;
res.H = a.height = h;
a.path = path;
res.type = "image";
fill.parentNode == node && node.removeChild(fill);
fill.rotate = true;
fill.src = src;
fill.type = "tile";
res._.fillpos = [x, y];
res._.fillsize = [w, h];
node.appendChild(fill);
setCoords(res, 1, 1, 0, 0, 0);
return res
};
R._engine.text = function(vml, x, y, text) {
var el = createNode("shape"),
path = createNode("path"),
o = createNode("textpath");
x = x || 0;
y = y || 0;
text = text || "";
path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1);
path.textpathok = true;
o.string = Str(text);
o.on = true;
el.style.cssText = cssDot;
el.coordsize = zoom + S + zoom;
el.coordorigin = "0 0";
var p = new Element(el, vml),
attr = {
fill: "#000",
stroke: "none",
font: R._availableAttrs.font,
text: text
};
p.shape = el;
p.path = path;
p.textpath = o;
p.type = "text";
p.attrs.text = Str(text);
p.attrs.x = x;
p.attrs.y = y;
p.attrs.w = 1;
p.attrs.h = 1;
setFillAndStroke(p, attr);
el.appendChild(o);
el.appendChild(path);
vml.canvas.appendChild(el);
var skew = createNode("skew");
skew.on = true;
el.appendChild(skew);
p.skew = skew;
p.transform(E);
return p
};
R._engine.setSize = function(width, height) {
var cs = this.canvas.style;
this.width = width;
this.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
cs.width = width;
cs.height = height;
cs.clip = "rect(0 " + width + " " + height + " 0)";
if (this._viewBox) {
R._engine.setViewBox.apply(this, this._viewBox)
}
return this
};
R._engine.setViewBox = function(x, y, w, h, fit) {
R.eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]);
var width = this.width,
height = this.height,
size = 1 / mmax(w / width, h / height),
H, W;
if (fit) {
H = height / h;
W = width / w;
if (w * H < width) {
x -= (width - w * H) / 2 / H
}
if (h * W < height) {
y -= (height - h * W) / 2 / W
}
}
this._viewBox = [x, y, w, h, !!fit];
this._viewBoxShift = {
dx: -x,
dy: -y,
scale: size
};
this.forEach(function(el) {
el.transform("...")
});
return this
};
var createNode;
R._engine.initWin = function(win) {
var doc = win.document;
doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
try {
!doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
createNode = function(tagName) {
return doc.createElement("<rvml:" + tagName + ' class="rvml">')
}
} catch (e) {
createNode = function(tagName) {
return doc.createElement("<" + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')
}
}
};
R._engine.initWin(R._g.win);
R._engine.create = function() {
var con = R._getContainer.apply(0, arguments),
container = con.container,
height = con.height,
s, width = con.width,
x = con.x,
y = con.y;
if (!container) {
throw new Error("VML container not found.")
}
var res = new R._Paper,
c = res.canvas = R._g.doc.createElement("div"),
cs = c.style;
x = x || 0;
y = y || 0;
width = width || 512;
height = height || 342;
res.width = width;
res.height = height;
width == +width && (width += "px");
height == +height && (height += "px");
res.coordsize = zoom * 1e3 + S + zoom * 1e3;
res.coordorigin = "0 0";
res.span = R._g.doc.createElement("span");
res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";
c.appendChild(res.span);
cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height);
if (container == 1) {
R._g.doc.body.appendChild(c);
cs.left = x + "px";
cs.top = y + "px";
cs.position = "absolute"
} else {
if (container.firstChild) {
container.insertBefore(c, container.firstChild)
} else {
container.appendChild(c)
}
}
res.renderfix = function() {};
return res
};
R.prototype.clear = function() {
R.eve("raphael.clear", this);
this.canvas.innerHTML = E;
this.span = R._g.doc.createElement("span");
this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";
this.canvas.appendChild(this.span);
this.bottom = this.top = null
};
R.prototype.remove = function() {
R.eve("raphael.remove", this);
this.canvas.parentNode.removeChild(this.canvas);
for (var i in this) {
this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null
}
return true
};
var setproto = R.st;
for (var method in elproto)
if (elproto[has](method) && !setproto[has](method)) {
setproto[method] = function(methodname) {
return function() {
var arg = arguments;
return this.forEach(function(el) {
el[methodname].apply(el, arg)
})
}
}(method)
}
}();
oldRaphael.was ? g.win.Raphael = R : Raphael = R;
return R
});
! function() {
var Color, K, PITHIRD, TWOPI, X, Y, Z, bezier, brewer, chroma, clip_rgb, colors, cos, css2rgb, hex2rgb, hsi2rgb, hsl2rgb, hsv2rgb, lab2lch, lab2rgb, lab_xyz, lch2lab, lch2rgb, limit, luminance, luminance_x, rgb2hex, rgb2hsi, rgb2hsl, rgb2hsv, rgb2lab, rgb2lch, rgb_xyz, root, type, unpack, xyz_lab, xyz_rgb, _ref;
root = typeof exports !== "undefined" && exports !== null ? exports : this;
chroma = root.chroma = function(x, y, z, m) {
return new Color(x, y, z, m)
};
if (typeof module !== "undefined" && module !== null) {
module.exports = chroma
}
chroma.color = function(x, y, z, m) {
return new Color(x, y, z, m)
};
chroma.hsl = function(h, s, l, a) {
return new Color(h, s, l, a, "hsl")
};
chroma.hsv = function(h, s, v, a) {
return new Color(h, s, v, a, "hsv")
};
chroma.rgb = function(r, g, b, a) {
return new Color(r, g, b, a, "rgb")
};
chroma.hex = function(x) {
return new Color(x)
};
chroma.css = function(x) {
return new Color(x)
};
chroma.lab = function(l, a, b) {
return new Color(l, a, b, "lab")
};
chroma.lch = function(l, c, h) {
return new Color(l, c, h, "lch")
};
chroma.hsi = function(h, s, i) {
return new Color(h, s, i, "hsi")
};
chroma.interpolate = function(a, b, f, m) {
if (a == null || b == null) {
return "#000"
}
if (type(a) === "string") {
a = new Color(a)
}
if (type(b) === "string") {
b = new Color(b)
}
return a.interpolate(f, b, m)
};
chroma.mix = chroma.interpolate;
chroma.contrast = function(a, b) {
var l1, l2;
if (type(a) === "string") {
a = new Color(a)
}
if (type(b) === "string") {
b = new Color(b)
}
l1 = a.luminance();
l2 = b.luminance();
if (l1 > l2) {
return (l1 + .05) / (l2 + .05)
} else {
return (l2 + .05) / (l1 + .05)
}
};
chroma.luminance = function(color) {
return chroma(color).luminance()
};
chroma._Color = Color;
Color = function() {
function Color() {
var a, arg, args, m, me, me_rgb, x, y, z, _i, _len, _ref, _ref1, _ref2, _ref3;
me = this;
args = [];
for (_i = 0, _len = arguments.length; _i < _len; _i++) {
arg = arguments[_i];
if (arg != null) {
args.push(arg)
}
}
if (args.length === 0) {
_ref = [255, 0, 255, 1, "rgb"], x = _ref[0], y = _ref[1], z = _ref[2], a = _ref[3], m = _ref[4]
} else if (type(args[0]) === "array") {
if (args[0].length === 3) {
_ref1 = args[0], x = _ref1[0], y = _ref1[1], z = _ref1[2];
a = 1
} else if (args[0].length === 4) {
_ref2 = args[0], x = _ref2[0], y = _ref2[1], z = _ref2[2], a = _ref2[3]
} else {
throw "unknown input argument"
}
m = args[1]
} else if (type(args[0]) === "string") {
x = args[0];
m = "hex"
} else if (type(args[0]) === "object") {
_ref3 = args[0]._rgb, x = _ref3[0], y = _ref3[1], z = _ref3[2], a = _ref3[3];
m = "rgb"
} else if (args.length >= 3) {
x = args[0];
y = args[1];
z = args[2]
}
if (args.length === 3) {
m = "rgb";
a = 1
} else if (args.length === 4) {
if (type(args[3]) === "string") {
m = args[3];
a = 1
} else if (type(args[3]) === "number") {
m = "rgb";
a = args[3]
}
} else if (args.length === 5) {
a = args[3];
m = args[4]
}
if (a == null) {
a = 1
}
if (m === "rgb") {
me._rgb = [x, y, z, a]
} else if (m === "hsl") {
me._rgb = hsl2rgb(x, y, z);
me._rgb[3] = a
} else if (m === "hsv") {
me._rgb = hsv2rgb(x, y, z);
me._rgb[3] = a
} else if (m === "hex") {
me._rgb = hex2rgb(x)
} else if (m === "lab") {
me._rgb = lab2rgb(x, y, z);
me._rgb[3] = a
} else if (m === "lch") {
me._rgb = lch2rgb(x, y, z);
me._rgb[3] = a
} else if (m === "hsi") {
me._rgb = hsi2rgb(x, y, z);
me._rgb[3] = a
}
me_rgb = clip_rgb(me._rgb)
}
Color.prototype.rgb = function() {
return this._rgb.slice(0, 3)
};
Color.prototype.rgba = function() {
return this._rgb
};
Color.prototype.hex = function() {
return rgb2hex(this._rgb)
};
Color.prototype.toString = function() {
return this.hex()
};
Color.prototype.hsl = function() {
return rgb2hsl(this._rgb)
};
Color.prototype.hsv = function() {
return rgb2hsv(this._rgb)
};
Color.prototype.lab = function() {
return rgb2lab(this._rgb)
};
Color.prototype.lch = function() {
return rgb2lch(this._rgb)
};
Color.prototype.hsi = function() {
return rgb2hsi(this._rgb)
};
Color.prototype.luminance = function() {
return luminance(this._rgb)
};
Color.prototype.name = function() {
var h, k;
h = this.hex();
for (k in chroma.colors) {
if (h === chroma.colors[k]) {
return k
}
}
return h
};
Color.prototype.alpha = function(alpha) {
if (arguments.length) {
this._rgb[3] = alpha;
return this
}
return this._rgb[3]
};
Color.prototype.css = function() {
if (this._rgb[3] < 1) {
return "rgba(" + this._rgb.join(",") + ")"
} else {
return "rgb(" + this._rgb.slice(0, 3).join(",") + ")"
}
};
Color.prototype.interpolate = function(f, col, m) {
var dh, hue, hue0, hue1, lbv, lbv0, lbv1, me, res, sat, sat0, sat1, xyz0, xyz1;
me = this;
if (m == null) {
m = "rgb"
}
if (type(col) === "string") {
col = new Color(col)
}
if (m === "hsl" || m === "hsv" || m === "lch" || m === "hsi") {
if (m === "hsl") {
xyz0 = me.hsl();
xyz1 = col.hsl()
} else if (m === "hsv") {
xyz0 = me.hsv();
xyz1 = col.hsv()
} else if (m === "hsi") {
xyz0 = me.hsi();
xyz1 = col.hsi()
} else if (m === "lch") {
xyz0 = me.lch();
xyz1 = col.lch()
}
if (m.substr(0, 1) === "h") {
hue0 = xyz0[0], sat0 = xyz0[1], lbv0 = xyz0[2];
hue1 = xyz1[0], sat1 = xyz1[1], lbv1 = xyz1[2]
} else {
lbv0 = xyz0[0], sat0 = xyz0[1], hue0 = xyz0[2];
lbv1 = xyz1[0], sat1 = xyz1[1], hue1 = xyz1[2]
}
if (!isNaN(hue0) && !isNaN(hue1)) {
if (hue1 > hue0 && hue1 - hue0 > 180) {
dh = hue1 - (hue0 + 360)
} else if (hue1 < hue0 && hue0 - hue1 > 180) {
dh = hue1 + 360 - hue0
} else {
dh = hue1 - hue0
}
hue = hue0 + f * dh
} else if (!isNaN(hue0)) {
hue = hue0;
if (lbv1 === 1 || lbv1 === 0) {
sat = sat0
}
} else if (!isNaN(hue1)) {
hue = hue1;
if (lbv0 === 1 || lbv0 === 0) {
sat = sat1
}
} else {
hue = Number.NaN
}
if (sat == null) {
sat = sat0 + f * (sat1 - sat0)
}
lbv = lbv0 + f * (lbv1 - lbv0);
if (m.substr(0, 1) === "h") {
res = new Color(hue, sat, lbv, m)
} else {
res = new Color(lbv, sat, hue, m)
}
} else if (m === "rgb") {
xyz0 = me._rgb;
xyz1 = col._rgb;
res = new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m)
} else if (m === "lab") {
xyz0 = me.lab();
xyz1 = col.lab();
res = new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m)
} else {
throw "color mode " + m + " is not supported"
}
res.alpha(me.alpha() + f * (col.alpha() - me.alpha()));
return res
};
Color.prototype.darken = function(amount) {
var lch, me;
if (amount == null) {
amount = 20
}
me = this;
lch = me.lch();
lch[0] -= amount;
return chroma.lch(lch).alpha(me.alpha())
};
Color.prototype.darker = function(amount) {
return this.darken(amount)
};
Color.prototype.brighten = function(amount) {
if (amount == null) {
amount = 20
}
return this.darken(-amount)
};
Color.prototype.brighter = function(amount) {
return this.brighten(amount)
};
Color.prototype.saturate = function(amount) {
var lch, me;
if (amount == null) {
amount = 20
}
me = this;
lch = me.lch();
lch[1] += amount;
return chroma.lch(lch).alpha(me.alpha())
};
Color.prototype.desaturate = function(amount) {
if (amount == null) {
amount = 20
}
return this.saturate(-amount)
};
return Color
}();
clip_rgb = function(rgb) {
var i;
for (i in rgb) {
if (i < 3) {
if (rgb[i] < 0) {
rgb[i] = 0
}
if (rgb[i] > 255) {
rgb[i] = 255
}
} else if (i === 3) {
if (rgb[i] < 0) {
rgb[i] = 0
}
if (rgb[i] > 1) {
rgb[i] = 1
}
}
}
return rgb
};
css2rgb = function(css) {
var hsl, i, m, rgb, _i, _j, _k, _l;
if (chroma.colors != null && chroma.colors[css]) {
return hex2rgb(chroma.colors[css])
}
if (m = css.match(/rgb\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)/)) {
rgb = m.slice(1, 4);
for (i = _i = 0; _i <= 2; i = ++_i) {
rgb[i] = +rgb[i]
}
rgb[3] = 1
} else if (m = css.match(/rgba\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*,\s*([01]|[01]?\.\d+)\)/)) {
rgb = m.slice(1, 5);
for (i = _j = 0; _j <= 3; i = ++_j) {
rgb[i] = +rgb[i]
}
} else if (m = css.match(/rgb\(\s*(\-?\d+)%,\s*(\-?\d+)%\s*,\s*(\-?\d+)%\s*\)/)) {
rgb = m.slice(1, 4);
for (i = _k = 0; _k <= 2; i = ++_k) {
rgb[i] = Math.round(rgb[i] * 2.55)
}
rgb[3] = 1
} else if (m = css.match(/rgba\(\s*(\-?\d+)%,\s*(\-?\d+)%\s*,\s*(\-?\d+)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
rgb = m.slice(1, 5);
for (i = _l = 0; _l <= 2; i = ++_l) {
rgb[i] = Math.round(rgb[i] * 2.55)
}
rgb[3] = +rgb[3]
} else if (m = css.match(/hsl\(\s*(\-?\d+),\s*(\-?\d+)%\s*,\s*(\-?\d+)%\s*\)/)) {
hsl = m.slice(1, 4);
hsl[1] *= .01;
hsl[2] *= .01;
rgb = hsl2rgb(hsl);
rgb[3] = 1
} else if (m = css.match(/hsla\(\s*(\-?\d+),\s*(\-?\d+)%\s*,\s*(\-?\d+)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
hsl = m.slice(1, 4);
hsl[1] *= .01;
hsl[2] *= .01;
rgb = hsl2rgb(hsl);
rgb[3] = +m[4]
}
return rgb
};
hex2rgb = function(hex) {
var a, b, g, r, rgb, u;
if (hex.match(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)) {
if (hex.length === 4 || hex.length === 7) {
hex = hex.substr(1)
}
if (hex.length === 3) {
hex = hex.split("");
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
}
u = parseInt(hex, 16);
r = u >> 16;
g = u >> 8 & 255;
b = u & 255;
return [r, g, b, 1]
}
if (hex.match(/^#?([A-Fa-f0-9]{8})$/)) {
if (hex.length === 9) {
hex = hex.substr(1)
}
u = parseInt(hex, 16);
r = u >> 24 & 255;
g = u >> 16 & 255;
b = u >> 8 & 255;
a = u & 255;
return [r, g, b, a]
}
if (rgb = css2rgb(hex)) {
return rgb
}
throw "unknown color: " + hex
};
hsi2rgb = function(h, s, i) {
var b, g, r, _ref;
_ref = unpack(arguments), h = _ref[0], s = _ref[1], i = _ref[2];
h /= 360;
if (h < 1 / 3) {
b = (1 - s) / 3;
r = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
g = 1 - (b + r)
} else if (h < 2 / 3) {
h -= 1 / 3;
r = (1 - s) / 3;
g = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
b = 1 - (r + g)
} else {
h -= 2 / 3;
g = (1 - s) / 3;
b = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
r = 1 - (g + b)
}
r = limit(i * r * 3);
g = limit(i * g * 3);
b = limit(i * b * 3);
return [r * 255, g * 255, b * 255]
};
hsl2rgb = function() {
var b, c, g, h, i, l, r, s, t1, t2, t3, _i, _ref, _ref1;
_ref = unpack(arguments), h = _ref[0], s = _ref[1], l = _ref[2];
if (s === 0) {
r = g = b = l * 255
} else {
t3 = [0, 0, 0];
c = [0, 0, 0];
t2 = l < .5 ? l * (1 + s) : l + s - l * s;
t1 = 2 * l - t2;
h /= 360;
t3[0] = h + 1 / 3;
t3[1] = h;
t3[2] = h - 1 / 3;
for (i = _i = 0; _i <= 2; i = ++_i) {
if (t3[i] < 0) {
t3[i] += 1
}
if (t3[i] > 1) {
t3[i] -= 1
}
if (6 * t3[i] < 1) {
c[i] = t1 + (t2 - t1) * 6 * t3[i]
} else if (2 * t3[i] < 1) {
c[i] = t2
} else if (3 * t3[i] < 2) {
c[i] = t1 + (t2 - t1) * (2 / 3 - t3[i]) * 6
} else {
c[i] = t1
}
}
_ref1 = [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)], r = _ref1[0], g = _ref1[1], b = _ref1[2]
}
return [r, g, b]
};
hsv2rgb = function() {
var b, f, g, h, i, p, q, r, s, t, v, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
_ref = unpack(arguments), h = _ref[0], s = _ref[1], v = _ref[2];
v *= 255;
if (s === 0) {
r = g = b = v
} else {
if (h === 360) {
h = 0
}
if (h > 360) {
h -= 360
}
if (h < 0) {
h += 360
}
h /= 60;
i = Math.floor(h);
f = h - i;
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch (i) {
case 0:
_ref1 = [v, t, p], r = _ref1[0], g = _ref1[1], b = _ref1[2];
break;
case 1:
_ref2 = [q, v, p], r = _ref2[0], g = _ref2[1], b = _ref2[2];
break;
case 2:
_ref3 = [p, v, t], r = _ref3[0], g = _ref3[1], b = _ref3[2];
break;
case 3:
_ref4 = [p, q, v], r = _ref4[0], g = _ref4[1], b = _ref4[2];
break;
case 4:
_ref5 = [t, p, v], r = _ref5[0], g = _ref5[1], b = _ref5[2];
break;
case 5:
_ref6 = [v, p, q], r = _ref6[0], g = _ref6[1], b = _ref6[2]
}
}
r = Math.round(r);
g = Math.round(g);
b = Math.round(b);
return [r, g, b]
};
K = 18;
X = .95047;
Y = 1;
Z = 1.08883;
lab2lch = function() {
var a, b, c, h, l, _ref;
_ref = unpack(arguments), l = _ref[0], a = _ref[1], b = _ref[2];
c = Math.sqrt(a * a + b * b);
h = Math.atan2(b, a) / Math.PI * 180;
return [l, c, h]
};
lab2rgb = function(l, a, b) {
var g, r, x, y, z, _ref, _ref1;
if (l !== void 0 && l.length === 3) {
_ref = l, l = _ref[0], a = _ref[1], b = _ref[2]
}
if (l !== void 0 && l.length === 3) {
_ref1 = l, l = _ref1[0], a = _ref1[1], b = _ref1[2]
}
y = (l + 16) / 116;
x = y + a / 500;
z = y - b / 200;
x = lab_xyz(x) * X;
y = lab_xyz(y) * Y;
z = lab_xyz(z) * Z;
r = xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z);
g = xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z);
b = xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z);
return [limit(r, 0, 255), limit(g, 0, 255), limit(b, 0, 255), 1]
};
lab_xyz = function(x) {
if (x > .206893034) {
return x * x * x
} else {
return (x - 4 / 29) / 7.787037
}
};
xyz_rgb = function(r) {
return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055))
};
lch2lab = function() {
var c, h, l, _ref;
_ref = unpack(arguments), l = _ref[0], c = _ref[1], h = _ref[2];
h = h * Math.PI / 180;
return [l, Math.cos(h) * c, Math.sin(h) * c]
};
lch2rgb = function(l, c, h) {
var L, a, b, g, r, _ref, _ref1;
_ref = lch2lab(l, c, h), L = _ref[0], a = _ref[1], b = _ref[2];
_ref1 = lab2rgb(L, a, b), r = _ref1[0], g = _ref1[1], b = _ref1[2];
return [limit(r, 0, 255), limit(g, 0, 255), limit(b, 0, 255)]
};
luminance = function(r, g, b) {
var _ref;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
r = luminance_x(r);
g = luminance_x(g);
b = luminance_x(b);
return .2126 * r + .7152 * g + .0722 * b
};
luminance_x = function(x) {
x /= 255;
if (x <= .03928) {
return x / 12.92
} else {
return Math.pow((x + .055) / 1.055, 2.4)
}
};
rgb2hex = function() {
var b, g, r, str, u, _ref;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
u = r << 16 | g << 8 | b;
str = "000000" + u.toString(16);
return "#" + str.substr(str.length - 6)
};
rgb2hsi = function() {
var TWOPI, b, g, h, i, min, r, s, _ref;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
TWOPI = Math.PI * 2;
r /= 255;
g /= 255;
b /= 255;
min = Math.min(r, g, b);
i = (r + g + b) / 3;
s = 1 - min / i;
if (s === 0) {
h = 0
} else {
h = (r - g + (r - b)) / 2;
h /= Math.sqrt((r - g) * (r - g) + (r - b) * (g - b));
h = Math.acos(h);
if (b > g) {
h = TWOPI - h
}
h /= TWOPI
}
return [h * 360, s, i]
};
rgb2hsl = function(r, g, b) {
var h, l, max, min, s, _ref;
if (r !== void 0 && r.length >= 3) {
_ref = r, r = _ref[0], g = _ref[1], b = _ref[2]
}
r /= 255;
g /= 255;
b /= 255;
min = Math.min(r, g, b);
max = Math.max(r, g, b);
l = (max + min) / 2;
if (max === min) {
s = 0;
h = Number.NaN
} else {
s = l < .5 ? (max - min) / (max + min) : (max - min) / (2 - max - min)
}
if (r === max) {
h = (g - b) / (max - min)
} else if (g === max) {
h = 2 + (b - r) / (max - min)
} else if (b === max) {
h = 4 + (r - g) / (max - min)
}
h *= 60;
if (h < 0) {
h += 360
}
return [h, s, l]
};
rgb2hsv = function() {
var b, delta, g, h, max, min, r, s, v, _ref;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
min = Math.min(r, g, b);
max = Math.max(r, g, b);
delta = max - min;
v = max / 255;
if (max === 0) {
h = Number.NaN;
s = 0
} else {
s = delta / max;
if (r === max) {
h = (g - b) / delta
}
if (g === max) {
h = 2 + (b - r) / delta
}
if (b === max) {
h = 4 + (r - g) / delta
}
h *= 60;
if (h < 0) {
h += 360
}
}
return [h, s, v]
};
rgb2lab = function() {
var b, g, r, x, y, z, _ref;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
r = rgb_xyz(r);
g = rgb_xyz(g);
b = rgb_xyz(b);
x = xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / X);
y = xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / Y);
z = xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / Z);
return [116 * y - 16, 500 * (x - y), 200 * (y - z)]
};
rgb_xyz = function(r) {
if ((r /= 255) <= .04045) {
return r / 12.92
} else {
return Math.pow((r + .055) / 1.055, 2.4)
}
};
xyz_lab = function(x) {
if (x > .008856) {
return Math.pow(x, 1 / 3)
} else {
return 7.787037 * x + 4 / 29
}
};
rgb2lch = function() {
var a, b, g, l, r, _ref, _ref1;
_ref = unpack(arguments), r = _ref[0], g = _ref[1], b = _ref[2];
_ref1 = rgb2lab(r, g, b), l = _ref1[0], a = _ref1[1], b = _ref1[2];
return lab2lch(l, a, b)
};
chroma.scale = function(colors, positions) {
var classifyValue, f, getClass, getColor, resetCache, setColors, setDomain, tmap, _colorCache, _colors, _correctLightness, _domain, _fixed, _max, _min, _mode, _nacol, _numClasses, _out, _pos, _spread;
_mode = "rgb";
_nacol = chroma("#ccc");
_spread = 0;
_fixed = false;
_domain = [0, 1];
_colors = [];
_out = false;
_pos = [];
_min = 0;
_max = 1;
_correctLightness = false;
_numClasses = 0;
_colorCache = {};
setColors = function(colors, positions) {
var c, col, _i, _j, _ref, _ref1, _ref2;
if (colors == null) {
colors = ["#ddd", "#222"]
}
if (colors != null && type(colors) === "string" && ((_ref = chroma.brewer) != null ? _ref[colors] : void 0) != null) {
colors = chroma.brewer[colors]
}
if (type(colors) === "array") {
colors = colors.slice(0);
for (c = _i = 0, _ref1 = colors.length - 1; 0 <= _ref1 ? _i <= _ref1 : _i >= _ref1; c = 0 <= _ref1 ? ++_i : --_i) {
col = colors[c];
if (type(col) === "string") {
colors[c] = chroma(col)
}
}
if (positions != null) {
_pos = positions
} else {
_pos = [];
for (c = _j = 0, _ref2 = colors.length - 1; 0 <= _ref2 ? _j <= _ref2 : _j >= _ref2; c = 0 <= _ref2 ? ++_j : --_j) {
_pos.push(c / (colors.length - 1))
}
}
}
resetCache();
return _colors = colors
};
setDomain = function(domain) {
if (domain == null) {
domain = []
}
_domain = domain;
_min = domain[0];
_max = domain[domain.length - 1];
resetCache();
if (domain.length === 2) {
return _numClasses = 0
} else {
return _numClasses = domain.length - 1
}
};
getClass = function(value) {
var i, n;
if (_domain != null) {
n = _domain.length - 1;
i = 0;
while (i < n && value >= _domain[i]) {
i++
}
return i - 1
}
return 0
};
tmap = function(t) {
return t
};
classifyValue = function(value) {
var i, maxc, minc, n, val;
val = value;
if (_domain.length > 2) {
n = _domain.length - 1;
i = getClass(value);
minc = _domain[0] + (_domain[1] - _domain[0]) * (0 + _spread * .5);
maxc = _domain[n - 1] + (_domain[n] - _domain[n - 1]) * (1 - _spread * .5);
val = _min + (_domain[i] + (_domain[i + 1] - _domain[i]) * .5 - minc) / (maxc - minc) * (_max - _min)
}
return val
};
getColor = function(val, bypassMap) {
var c, col, f0, i, k, p, t, _i, _ref;
if (bypassMap == null) {
bypassMap = false
}
if (isNaN(val)) {
return _nacol
}
if (!bypassMap) {
if (_domain.length > 2) {
c = getClass(val);
t = c / (_numClasses - 1)
} else {
t = f0 = (val - _min) / (_max - _min);
t = Math.min(1, Math.max(0, t))
}
} else {
t = val
}
if (!bypassMap) {
t = tmap(t)
}
k = Math.floor(t * 1e4);
if (_colorCache[k]) {
col = _colorCache[k]
} else {
if (type(_colors) === "array") {
for (i = _i = 0, _ref = _pos.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
p = _pos[i];
if (t <= p) {
col = _colors[i];
break
}
if (t >= p && i === _pos.length - 1) {
col = _colors[i];
break
}
if (t > p && t < _pos[i + 1]) {
t = (t - p) / (_pos[i + 1] - p);
col = chroma.interpolate(_colors[i], _colors[i + 1], t, _mode);
break
}
}
} else if (type(_colors) === "function") {
col = _colors(t)
}
_colorCache[k] = col
}
return col
};
resetCache = function() {
return _colorCache = {}
};
setColors(colors, positions);
f = function(v) {
var c;
c = getColor(v);
if (_out && c[_out]) {
return c[_out]()
} else {
return c
}
};
f.domain = function(domain, classes, mode, key) {
var d;
if (mode == null) {
mode = "e"
}
if (!arguments.length) {
return _domain
}
if (classes != null) {
d = chroma.analyze(domain, key);
if (classes === 0) {
domain = [d.min, d.max]
} else {
domain = chroma.limits(d, mode, classes)
}
}
setDomain(domain);
return f
};
f.mode = function(_m) {
if (!arguments.length) {
return _mode
}
_mode = _m;
resetCache();
return f
};
f.range = function(colors, _pos) {
setColors(colors, _pos);
return f
};
f.out = function(_o) {
_out = _o;
return f
};
f.spread = function(val) {
if (!arguments.length) {
return _spread
}
_spread = val;
return f
};
f.correctLightness = function(v) {
if (!arguments.length) {
return _correctLightness
}
_correctLightness = v;
resetCache();
if (_correctLightness) {
tmap = function(t) {
var L0, L1, L_actual, L_diff, L_ideal, max_iter, pol, t0, t1;
L0 = getColor(0, true).lab()[0];
L1 = getColor(1, true).lab()[0];
pol = L0 > L1;
L_actual = getColor(t, true).lab()[0];
L_ideal = L0 + (L1 - L0) * t;
L_diff = L_actual - L_ideal;
t0 = 0;
t1 = 1;
max_iter = 20;
while (Math.abs(L_diff) > .01 && max_iter-- > 0) {
! function() {
if (pol) {
L_diff *= -1
}
if (L_diff < 0) {
t0 = t;
t += (t1 - t) * .5
} else {
t1 = t;
t += (t0 - t) * .5
}
L_actual = getColor(t, true).lab()[0];
return L_diff = L_actual - L_ideal
}()
}
return t
}
} else {
tmap = function(t) {
return t
}
}
return f
};
return f
};
if ((_ref = chroma.scales) == null) {
chroma.scales = {}
}
chroma.scales.cool = function() {
return chroma.scale([chroma.hsl(180, 1, .9), chroma.hsl(250, .7, .4)])
};
chroma.scales.hot = function() {
return chroma.scale(["#000", "#f00", "#ff0", "#fff"], [0, .25, .75, 1]).mode("rgb")
};
chroma.analyze = function(data, key, filter) {
var add, k, r, val, visit, _i, _len;
r = {
min: Number.MAX_VALUE,
max: Number.MAX_VALUE * -1,
sum: 0,
values: [],
count: 0
};
if (filter == null) {
filter = function() {
return true
}
}
add = function(val) {
if (val != null && !isNaN(val)) {
r.values.push(val);
r.sum += val;
if (val < r.min) {
r.min = val
}
if (val > r.max) {
r.max = val
}
r.count += 1
}
};
visit = function(val, k) {
if (filter(val, k)) {
if (key != null && type(key) === "function") {
return add(key(val))
} else if (key != null && type(key) === "string" || type(key) === "number") {
return add(val[key])
} else {
return add(val)
}
}
};
if (type(data) === "array") {
for (_i = 0, _len = data.length; _i < _len; _i++) {
val = data[_i];
visit(val)
}
} else {
for (k in data) {
val = data[k];
visit(val, k)
}
}
r.domain = [r.min, r.max];
r.limits = function(mode, num) {
return chroma.limits(r, mode, num)
};
return r
};
chroma.limits = function(data, mode, num) {
var assignments, best, centroids, cluster, clusterSizes, dist, i, j, kClusters, limits, max, max_log, min, min_log, mindist, n, nb_iters, newCentroids, p, pb, pr, repeat, sum, tmpKMeansBreaks, value, values, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _ref1, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _s, _t, _u, _v, _w;
if (mode == null) {
mode = "equal"
}
if (num == null) {
num = 7
}
if (data.values == null) {
data = chroma.analyze(data)
}
min = data.min;
max = data.max;
sum = data.sum;
values = data.values.sort(function(a, b) {
return a - b
});
limits = [];
if (mode.substr(0, 1) === "c") {
limits.push(min);
limits.push(max)
}
if (mode.substr(0, 1) === "e") {
limits.push(min);
for (i = _i = 1, _ref1 = num - 1; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 1 <= _ref1 ? ++_i : --_i) {
limits.push(min + i / num * (max - min))
}
limits.push(max)
} else if (mode.substr(0, 1) === "l") {
if (min <= 0) {
throw "Logarithmic scales are only possible for values > 0"
}
min_log = Math.LOG10E * Math.log(min);
max_log = Math.LOG10E * Math.log(max);
limits.push(min);
for (i = _j = 1, _ref2 = num - 1; 1 <= _ref2 ? _j <= _ref2 : _j >= _ref2; i = 1 <= _ref2 ? ++_j : --_j) {
limits.push(Math.pow(10, min_log + i / num * (max_log - min_log)))
}
limits.push(max)
} else if (mode.substr(0, 1) === "q") {
limits.push(min);
for (i = _k = 1, _ref3 = num - 1; 1 <= _ref3 ? _k <= _ref3 : _k >= _ref3; i = 1 <= _ref3 ? ++_k : --_k) {
p = values.length * i / num;
pb = Math.floor(p);
if (pb === p) {
limits.push(values[pb])
} else {
pr = p - pb;
limits.push(values[pb] * pr + values[pb + 1] * (1 - pr))
}
}
limits.push(max)
} else if (mode.substr(0, 1) === "k") {
n = values.length;
assignments = new Array(n);
clusterSizes = new Array(num);
repeat = true;
nb_iters = 0;
centroids = null;
centroids = [];
centroids.push(min);
for (i = _l = 1, _ref4 = num - 1; 1 <= _ref4 ? _l <= _ref4 : _l >= _ref4; i = 1 <= _ref4 ? ++_l : --_l) {
centroids.push(min + i / num * (max - min))
}
centroids.push(max);
while (repeat) {
for (j = _m = 0, _ref5 = num - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; j = 0 <= _ref5 ? ++_m : --_m) {
clusterSizes[j] = 0
}
for (i = _n = 0, _ref6 = n - 1; 0 <= _ref6 ? _n <= _ref6 : _n >= _ref6; i = 0 <= _ref6 ? ++_n : --_n) {
value = values[i];
mindist = Number.MAX_VALUE;
for (j = _o = 0, _ref7 = num - 1; 0 <= _ref7 ? _o <= _ref7 : _o >= _ref7; j = 0 <= _ref7 ? ++_o : --_o) {
dist = Math.abs(centroids[j] - value);
if (dist < mindist) {
mindist = dist;
best = j
}
}
clusterSizes[best]++;
assignments[i] = best
}
newCentroids = new Array(num);
for (j = _p = 0, _ref8 = num - 1; 0 <= _ref8 ? _p <= _ref8 : _p >= _ref8; j = 0 <= _ref8 ? ++_p : --_p) {
newCentroids[j] = null
}
for (i = _q = 0, _ref9 = n - 1; 0 <= _ref9 ? _q <= _ref9 : _q >= _ref9; i = 0 <= _ref9 ? ++_q : --_q) {
cluster = assignments[i];
if (newCentroids[cluster] === null) {
newCentroids[cluster] = values[i]
} else {
newCentroids[cluster] += values[i]
}
}
for (j = _r = 0, _ref10 = num - 1; 0 <= _ref10 ? _r <= _ref10 : _r >= _ref10; j = 0 <= _ref10 ? ++_r : --_r) {
newCentroids[j] *= 1 / clusterSizes[j]
}
repeat = false;
for (j = _s = 0, _ref11 = num - 1; 0 <= _ref11 ? _s <= _ref11 : _s >= _ref11; j = 0 <= _ref11 ? ++_s : --_s) {
if (newCentroids[j] !== centroids[i]) {
repeat = true;
break
}
}
centroids = newCentroids;
nb_iters++;
if (nb_iters > 200) {
repeat = false
}
}
kClusters = {};
for (j = _t = 0, _ref12 = num - 1; 0 <= _ref12 ? _t <= _ref12 : _t >= _ref12; j = 0 <= _ref12 ? ++_t : --_t) {
kClusters[j] = []
}
for (i = _u = 0, _ref13 = n - 1; 0 <= _ref13 ? _u <= _ref13 : _u >= _ref13; i = 0 <= _ref13 ? ++_u : --_u) {
cluster = assignments[i];
kClusters[cluster].push(values[i])
}
tmpKMeansBreaks = [];
for (j = _v = 0, _ref14 = num - 1; 0 <= _ref14 ? _v <= _ref14 : _v >= _ref14; j = 0 <= _ref14 ? ++_v : --_v) {
tmpKMeansBreaks.push(kClusters[j][0]);
tmpKMeansBreaks.push(kClusters[j][kClusters[j].length - 1])
}
tmpKMeansBreaks = tmpKMeansBreaks.sort(function(a, b) {
return a - b
});
limits.push(tmpKMeansBreaks[0]);
for (i = _w = 1, _ref15 = tmpKMeansBreaks.length - 1; _w <= _ref15; i = _w += 2) {
if (!isNaN(tmpKMeansBreaks[i])) {
limits.push(tmpKMeansBreaks[i])
}
}
}
return limits
};
root = typeof exports !== "undefined" && exports !== null ? exports : this;
chroma.brewer = brewer = {
OrRd: ["#fff7ec", "#fee8c8", "#fdd49e", "#fdbb84", "#fc8d59", "#ef6548", "#d7301f", "#b30000", "#7f0000"],
PuBu: ["#fff7fb", "#ece7f2", "#d0d1e6", "#a6bddb", "#74a9cf", "#3690c0", "#0570b0", "#045a8d", "#023858"],
BuPu: ["#f7fcfd", "#e0ecf4", "#bfd3e6", "#9ebcda", "#8c96c6", "#8c6bb1", "#88419d", "#810f7c", "#4d004b"],
Oranges: ["#fff5eb", "#fee6ce", "#fdd0a2", "#fdae6b", "#fd8d3c", "#f16913", "#d94801", "#a63603", "#7f2704"],
BuGn: ["#f7fcfd", "#e5f5f9", "#ccece6", "#99d8c9", "#66c2a4", "#41ae76", "#238b45", "#006d2c", "#00441b"],
YlOrBr: ["#ffffe5", "#fff7bc", "#fee391", "#fec44f", "#fe9929", "#ec7014", "#cc4c02", "#993404", "#662506"],
YlGn: ["#ffffe5", "#f7fcb9", "#d9f0a3", "#addd8e", "#78c679", "#41ab5d", "#238443", "#006837", "#004529"],
Reds: ["#fff5f0", "#fee0d2", "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#a50f15", "#67000d"],
RdPu: ["#fff7f3", "#fde0dd", "#fcc5c0", "#fa9fb5", "#f768a1", "#dd3497", "#ae017e", "#7a0177", "#49006a"],
Greens: ["#f7fcf5", "#e5f5e0", "#c7e9c0", "#a1d99b", "#74c476", "#41ab5d", "#238b45", "#006d2c", "#00441b"],
YlGnBu: ["#ffffd9", "#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#1d91c0", "#225ea8", "#253494", "#081d58"],
Purples: ["#fcfbfd", "#efedf5", "#dadaeb", "#bcbddc", "#9e9ac8", "#807dba", "#6a51a3", "#54278f", "#3f007d"],
GnBu: ["#f7fcf0", "#e0f3db", "#ccebc5", "#a8ddb5", "#7bccc4", "#4eb3d3", "#2b8cbe", "#0868ac", "#084081"],
Greys: ["#ffffff", "#f0f0f0", "#d9d9d9", "#bdbdbd", "#969696", "#737373", "#525252", "#252525", "#000000"],
YlOrRd: ["#ffffcc", "#ffeda0", "#fed976", "#feb24c", "#fd8d3c", "#fc4e2a", "#e31a1c", "#bd0026", "#800026"],
PuRd: ["#f7f4f9", "#e7e1ef", "#d4b9da", "#c994c7", "#df65b0", "#e7298a", "#ce1256", "#980043", "#67001f"],
Blues: ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6", "#4292c6", "#2171b5", "#08519c", "#08306b"],
PuBuGn: ["#fff7fb", "#ece2f0", "#d0d1e6", "#a6bddb", "#67a9cf", "#3690c0", "#02818a", "#016c59", "#014636"],
Spectral: ["#9e0142", "#d53e4f", "#f46d43", "#fdae61", "#fee08b", "#ffffbf", "#e6f598", "#abdda4", "#66c2a5", "#3288bd", "#5e4fa2"],
RdYlGn: ["#a50026", "#d73027", "#f46d43", "#fdae61", "#fee08b", "#ffffbf", "#d9ef8b", "#a6d96a", "#66bd63", "#1a9850", "#006837"],
RdBu: ["#67001f", "#b2182b", "#d6604d", "#f4a582", "#fddbc7", "#f7f7f7", "#d1e5f0", "#92c5de", "#4393c3", "#2166ac", "#053061"],
PiYG: ["#8e0152", "#c51b7d", "#de77ae", "#f1b6da", "#fde0ef", "#f7f7f7", "#e6f5d0", "#b8e186", "#7fbc41", "#4d9221", "#276419"],
PRGn: ["#40004b", "#762a83", "#9970ab", "#c2a5cf", "#e7d4e8", "#f7f7f7", "#d9f0d3", "#a6dba0", "#5aae61", "#1b7837", "#00441b"],
RdYlBu: ["#a50026", "#d73027", "#f46d43", "#fdae61", "#fee090", "#ffffbf", "#e0f3f8", "#abd9e9", "#74add1", "#4575b4", "#313695"],
BrBG: ["#543005", "#8c510a", "#bf812d", "#dfc27d", "#f6e8c3", "#f5f5f5", "#c7eae5", "#80cdc1", "#35978f", "#01665e", "#003c30"],
RdGy: ["#67001f", "#b2182b", "#d6604d", "#f4a582", "#fddbc7", "#ffffff", "#e0e0e0", "#bababa", "#878787", "#4d4d4d", "#1a1a1a"],
PuOr: ["#7f3b08", "#b35806", "#e08214", "#fdb863", "#fee0b6", "#f7f7f7", "#d8daeb", "#b2abd2", "#8073ac", "#542788", "#2d004b"],
Set2: ["#66c2a5", "#fc8d62", "#8da0cb", "#e78ac3", "#a6d854", "#ffd92f", "#e5c494", "#b3b3b3"],
Accent: ["#7fc97f", "#beaed4", "#fdc086", "#ffff99", "#386cb0", "#f0027f", "#bf5b17", "#666666"],
Set1: ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#ffff33", "#a65628", "#f781bf", "#999999"],
Set3: ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3", "#fdb462", "#b3de69", "#fccde5", "#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f"],
Dark2: ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e", "#e6ab02", "#a6761d", "#666666"],
Paired: ["#a6cee3", "#1f78b4", "#b2df8a", "#33a02c", "#fb9a99", "#e31a1c", "#fdbf6f", "#ff7f00", "#cab2d6", "#6a3d9a", "#ffff99", "#b15928"],
Pastel2: ["#b3e2cd", "#fdcdac", "#cbd5e8", "#f4cae4", "#e6f5c9", "#fff2ae", "#f1e2cc", "#cccccc"],
Pastel1: ["#fbb4ae", "#b3cde3", "#ccebc5", "#decbe4", "#fed9a6", "#ffffcc", "#e5d8bd", "#fddaec", "#f2f2f2"]
};
root = typeof exports !== "undefined" && exports !== null ? exports : this;
chroma.colors = colors = {
indigo: "#4b0082",
gold: "#ffd700",
hotpink: "#ff69b4",
firebrick: "#b22222",
indianred: "#cd5c5c",
yellow: "#ffff00",
mistyrose: "#ffe4e1",
darkolivegreen: "#556b2f",
olive: "#808000",
darkseagreen: "#8fbc8f",
pink: "#ffc0cb",
tomato: "#ff6347",
lightcoral: "#f08080",
orangered: "#ff4500",
navajowhite: "#ffdead",
lime: "#00ff00",
palegreen: "#98fb98",
darkslategrey: "#2f4f4f",
greenyellow: "#adff2f",
burlywood: "#deb887",
seashell: "#fff5ee",
mediumspringgreen: "#00fa9a",
fuchsia: "#ff00ff",
papayawhip: "#ffefd5",
blanchedalmond: "#ffebcd",
chartreuse: "#7fff00",
dimgray: "#696969",
black: "#000000",
peachpuff: "#ffdab9",
springgreen: "#00ff7f",
aquamarine: "#7fffd4",
white: "#ffffff",
orange: "#ffa500",
lightsalmon: "#ffa07a",
darkslategray: "#2f4f4f",
brown: "#a52a2a",
ivory: "#fffff0",
dodgerblue: "#1e90ff",
peru: "#cd853f",
lawngreen: "#7cfc00",
chocolate: "#d2691e",
crimson: "#dc143c",
forestgreen: "#228b22",
darkgrey: "#a9a9a9",
lightseagreen: "#20b2aa",
cyan: "#00ffff",
mintcream: "#f5fffa",
silver: "#c0c0c0",
antiquewhite: "#faebd7",
mediumorchid: "#ba55d3",
skyblue: "#87ceeb",
gray: "#808080",
darkturquoise: "#00ced1",
goldenrod: "#daa520",
darkgreen: "#006400",
floralwhite: "#fffaf0",
darkviolet: "#9400d3",
darkgray: "#a9a9a9",
moccasin: "#ffe4b5",
saddlebrown: "#8b4513",
grey: "#808080",
darkslateblue: "#483d8b",
lightskyblue: "#87cefa",
lightpink: "#ffb6c1",
mediumvioletred: "#c71585",
slategrey: "#708090",
red: "#ff0000",
deeppink: "#ff1493",
limegreen: "#32cd32",
darkmagenta: "#8b008b",
palegoldenrod: "#eee8aa",
plum: "#dda0dd",
turquoise: "#40e0d0",
lightgrey: "#d3d3d3",
lightgoldenrodyellow: "#fafad2",
darkgoldenrod: "#b8860b",
lavender: "#e6e6fa",
maroon: "#800000",
yellowgreen: "#9acd32",
sandybrown: "#f4a460",
thistle: "#d8bfd8",
violet: "#ee82ee",
navy: "#000080",
magenta: "#ff00ff",
dimgrey: "#696969",
tan: "#d2b48c",
rosybrown: "#bc8f8f",
olivedrab: "#6b8e23",
blue: "#0000ff",
lightblue: "#add8e6",
ghostwhite: "#f8f8ff",
honeydew: "#f0fff0",
cornflowerblue: "#6495ed",
slateblue: "#6a5acd",
linen: "#faf0e6",
darkblue: "#00008b",
powderblue: "#b0e0e6",
seagreen: "#2e8b57",
darkkhaki: "#bdb76b",
snow: "#fffafa",
sienna: "#a0522d",
mediumblue: "#0000cd",
royalblue: "#4169e1",
lightcyan: "#e0ffff",
green: "#008000",
mediumpurple: "#9370db",
midnightblue: "#191970",
cornsilk: "#fff8dc",
paleturquoise: "#afeeee",
bisque: "#ffe4c4",
slategray: "#708090",
darkcyan: "#008b8b",
khaki: "#f0e68c",
wheat: "#f5deb3",
teal: "#008080",
darkorchid: "#9932cc",
deepskyblue: "#00bfff",
salmon: "#fa8072",
darkred: "#8b0000",
steelblue: "#4682b4",
palevioletred: "#db7093",
lightslategray: "#778899",
aliceblue: "#f0f8ff",
lightslategrey: "#778899",
lightgreen: "#90ee90",
orchid: "#da70d6",
gainsboro: "#dcdcdc",
mediumseagreen: "#3cb371",
lightgray: "#d3d3d3",
mediumturquoise: "#48d1cc",
lemonchiffon: "#fffacd",
cadetblue: "#5f9ea0",
lightyellow: "#ffffe0",
lavenderblush: "#fff0f5",
coral: "#ff7f50",
purple: "#800080",
aqua: "#00ffff",
whitesmoke: "#f5f5f5",
mediumslateblue: "#7b68ee",
darkorange: "#ff8c00",
mediumaquamarine: "#66cdaa",
darksalmon: "#e9967a",
beige: "#f5f5dc",
blueviolet: "#8a2be2",
azure: "#f0ffff",
lightsteelblue: "#b0c4de",
oldlace: "#fdf5e6"
};
type = function() {
var classToType, name, _i, _len, _ref1;
classToType = {};
_ref1 = "Boolean Number String Function Array Date RegExp Undefined Null".split(" ");
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
name = _ref1[_i];
classToType["[object " + name + "]"] = name.toLowerCase()
}
return function(obj) {
var strType;
strType = Object.prototype.toString.call(obj);
return classToType[strType] || "object"
}
}();
limit = function(x, min, max) {
if (min == null) {
min = 0
}
if (max == null) {
max = 1
}
if (x < min) {
x = min
}
if (x > max) {
x = max
}
return x
};
unpack = function(args) {
if (args.length >= 3) {
return args
} else {
return args[0]
}
};
TWOPI = Math.PI * 2;
PITHIRD = Math.PI / 3;
cos = Math.cos;
bezier = function(colors) {
var I, I0, I1, c, lab0, lab1, lab2, lab3, _ref1, _ref2, _ref3;
colors = function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = colors.length; _i < _len; _i++) {
c = colors[_i];
_results.push(chroma(c))
}
return _results
}();
if (colors.length === 2) {
_ref1 = function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = colors.length; _i < _len; _i++) {
c = colors[_i];
_results.push(c.lab())
}
return _results
}(), lab0 = _ref1[0], lab1 = _ref1[1];
I = function(t) {
var i, lab;
lab = function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
_results.push(lab0[i] + t * (lab1[i] - lab0[i]))
}
return _results
}();
return chroma.lab.apply(chroma, lab)
}
} else if (colors.length === 3) {
_ref2 = function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = colors.length; _i < _len; _i++) {
c = colors[_i];
_results.push(c.lab())
}
return _results
}(), lab0 = _ref2[0], lab1 = _ref2[1], lab2 = _ref2[2];
I = function(t) {
var i, lab;
lab = function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
_results.push((1 - t) * (1 - t) * lab0[i] + 2 * (1 - t) * t * lab1[i] + t * t * lab2[i])
}
return _results
}();
return chroma.lab.apply(chroma, lab)
}
} else if (colors.length === 4) {
_ref3 = function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = colors.length; _i < _len; _i++) {
c = colors[_i];
_results.push(c.lab())
}
return _results
}(), lab0 = _ref3[0], lab1 = _ref3[1], lab2 = _ref3[2], lab3 = _ref3[3];
I = function(t) {
var i, lab;
lab = function() {
var _i, _results;
_results = [];
for (i = _i = 0; _i <= 2; i = ++_i) {
_results.push((1 - t) * (1 - t) * (1 - t) * lab0[i] + 3 * (1 - t) * (1 - t) * t * lab1[i] + 3 * (1 - t) * t * t * lab2[i] + t * t * t * lab3[i])
}
return _results
}();
return chroma.lab.apply(chroma, lab)
}
} else if (colors.length === 5) {
I0 = bezier(colors.slice(0, 3));
I1 = bezier(colors.slice(2, 5));
I = function(t) {
if (t < .5) {
return I0(t * 2)
} else {
return I1((t - .5) * 2)
}
}
}
return I
};
chroma.interpolate.bezier = bezier
}.call(this);
[].map || (Array.prototype.map = function(t, n) {
for (var e = this, r = e.length, u = [], i = 0; r > i;) i in e && (u[i] = t.call(n, e[i], i++, e));
return u.lengh = r, u
}), [].filter || (Array.prototype.filter = function(t, n, e, r, u) {
e = this, r = [];
for (u in e) ~~u + "" == u && u >= 0 && t.call(n, e[u], +u, e) && r.push(e[u]);
return r
}), [].forEach || (Array.prototype.forEach = function(t, n) {
for (var e = 0, r = this.length; r > e; ++e) t.call(n, this[e], e, this)
}), d3 = function() {
function t(t) {
for (var n = 1; t * n % 1;) n *= 10;
return n
}
function n(t, n, e) {
return function() {
var r = e.apply(n, arguments);
return r === n ? t : r
}
}
function e(t) {
var n = [t.a, t.b],
e = [t.c, t.d],
o = u(n),
a = r(n, e),
c = u(i(e, n, -a)) || 0;
n[0] * e[1] < e[0] * n[1] && (n[0] *= -1, n[1] *= -1, o *= -1, a *= -1), this.rotate = (o ? Math.atan2(n[1], n[0]) : Math.atan2(-e[0], e[1])) * d3_degrees, this.translate = [t.e, t.f], this.scale = [o, c], this.skew = c ? Math.atan2(a, c) * d3_degrees : 0
}
function r(t, n) {
return t[0] * n[0] + t[1] * n[1]
}
function u(t) {
var n = Math.sqrt(r(t, t));
return n && (t[0] /= n, t[1] /= n), n
}
function i(t, n, e) {
return t[0] += e * n[0], t[1] += e * n[1], t
}
function o(t, n) {
return n -= t = +t,
function(e) {
return t + n * e
}
}
function a(t, n) {
var e, r = [],
u = [],
i = xn.transform(t),
a = xn.transform(n),
c = i.translate,
f = a.translate,
s = i.rotate,
l = a.rotate,
h = i.skew,
g = a.skew,
m = i.scale,
p = a.scale;
return c[0] != f[0] || c[1] != f[1] ? (r.push("translate(", null, ",", null, ")"), u.push({
i: 1,
x: o(c[0], f[0])
}, {
i: 3,
x: o(c[1], f[1])
})) : f[0] || f[1] ? r.push("translate(" + f + ")") : r.push(""), s != l ? (s - l > 180 ? l += 360 : l - s > 180 && (s += 360), u.push({
i: r.push(r.pop() + "rotate(", null, ")") - 2,
x: o(s, l)
})) : l && r.push(r.pop() + "rotate(" + l + ")"), h != g ? u.push({
i: r.push(r.pop() + "skewX(", null, ")") - 2,
x: o(h, g)
}) : g && r.push(r.pop() + "skewX(" + g + ")"), m[0] != p[0] || m[1] != p[1] ? (e = r.push(r.pop() + "scale(", null, ",", null, ")"), u.push({
i: e - 4,
x: o(m[0], p[0])
}, {
i: e - 2,
x: o(m[1], p[1])
})) : (1 != p[0] || 1 != p[1]) && r.push(r.pop() + "scale(" + p + ")"), e = u.length,
function(t) {
for (var n, i = -1; ++i < e;) r[(n = u[i]).i] = n.x(t);
return r.join("")
}
}
function c(t, n) {
var e, r = {},
u = {};
for (e in t) e in n ? r[e] = h(e)(t[e], n[e]) : u[e] = t[e];
for (e in n) e in t || (u[e] = n[e]);
return function(t) {
for (e in r) u[e] = r[e](t);
return u
}
}
function f(t, n) {
var e, r = [],
u = [],
i = t.length,
o = n.length,
a = Math.min(t.length, n.length);
for (e = 0; a > e; ++e) r.push(l(t[e], n[e]));
for (; i > e; ++e) u[e] = t[e];
for (; o > e; ++e) u[e] = n[e];
return function(t) {
for (e = 0; a > e; ++e) u[e] = r[e](t);
return u
}
}
function s(t, n) {
var e, r, u, i, a, c = 0,
f = 0,
s = [],
l = [];
for (t += "", n += "", Tn.lastIndex = 0, r = 0; e = Tn.exec(n); ++r) e.index && s.push(n.substring(c, f = e.index)), l.push({
i: s.length,
x: e[0]
}), s.push(null), c = Tn.lastIndex;
for (c < n.length && s.push(n.substring(c)), r = 0, i = l.length;
(e = Tn.exec(t)) && i > r; ++r)
if (a = l[r], a.x == e[0]) {
if (a.i)
if (null == s[a.i + 1])
for (s[a.i - 1] += a.x, s.splice(a.i, 1), u = r + 1; i > u; ++u) l[u].i--;
else
for (s[a.i - 1] += a.x + s[a.i + 1], s.splice(a.i, 2), u = r + 1; i > u; ++u) l[u].i -= 2;
else if (null == s[a.i + 1]) s[a.i] = a.x;
else
for (s[a.i] = a.x + s[a.i + 1], s.splice(a.i + 1, 1), u = r + 1; i > u; ++u) l[u].i--;
l.splice(r, 1), i--, r--
} else a.x = o(parseFloat(e[0]), parseFloat(a.x));
for (; i > r;) a = l.pop(), null == s[a.i + 1] ? s[a.i] = a.x : (s[a.i] = a.x + s[a.i + 1], s.splice(a.i + 1, 1)), i--;
return 1 === s.length ? null == s[0] ? (a = l[0].x, function(t) {
return a(t) + ""
}) : function() {
return n
} : function(t) {
for (r = 0; i > r; ++r) s[(a = l[r]).i] = a.x(t);
return s.join("")
}
}
function l(t, n) {
for (var e, r = xn.interpolators.length; --r >= 0 && !(e = xn.interpolators[r](t, n)););
return e
}
function h(t) {
return "transform" == t ? a : l
}
function g(t, n) {
return n -= t,
function(e) {
return Math.round(t + n * e)
}
}
function m(t, n) {
return n = n - (t = +t) ? 1 / (n - t) : 0,
function(e) {
return (e - t) * n
}
}
function p(t, n) {
return n = n - (t = +t) ? 1 / (n - t) : 0,
function(e) {
return Math.max(0, Math.min(1, (e - t) * n))
}
}
function d(t, n) {
try {
for (var e in n) Object.defineProperty(t.prototype, e, {
value: n[e],
enumerable: !1
})
} catch (r) {
t.prototype = n
}
}
function v() {}
function M(t) {
return t
}
function y(t, n) {
var e = Math.pow(10, 3 * Math.abs(8 - n));
return {
scale: n > 8 ? function(t) {
return t / e
} : function(t) {
return t * e
},
symbol: t
}
}
function x(t, n) {
return n - (t ? Math.ceil(Math.log(t) / Math.LN10) : 1)
}
function w(t) {
return t + ""
}
function b(t, n, e, r) {
var u = e(t[0], t[1]),
i = r(n[0], n[1]);
return function(t) {
return i(u(t))
}
}
function D(t, n) {
var e, r = 0,
u = t.length - 1,
i = t[r],
o = t[u];
return i > o && (e = r, r = u, u = e, e = i, i = o, o = e), (n = n(o - i)) && (t[r] = n.floor(i), t[u] = n.ceil(o)), t
}
function T(t, n, e, r) {
var u = [],
i = [],
o = 0,
a = Math.min(t.length, n.length) - 1;
for (t[a] < t[0] && (t = t.slice().reverse(), n = n.slice().reverse()); ++o <= a;) u.push(e(t[o - 1], t[o])), i.push(r(n[o - 1], n[o]));
return function(n) {
var e = xn.bisect(t, n, 1, a) - 1;
return i[e](u[e](n))
}
}
function C(t) {
var n = t[0],
e = t[t.length - 1];
return e > n ? [n, e] : [e, n]
}
function _(t, n, e, r) {
function u() {
var u = Math.min(t.length, n.length) > 2 ? T : b,
c = r ? p : m;
return o = u(t, n, c, e), a = u(n, t, c, l), i
}
function i(t) {
return o(t)
}
var o, a;
return i.invert = function(t) {
return a(t)
}, i.domain = function(n) {
return arguments.length ? (t = n.map(Number), u()) : t
}, i.range = function(t) {
return arguments.length ? (n = t, u()) : n
}, i.rangeRound = function(t) {
return i.range(t).interpolate(g)
}, i.clamp = function(t) {
return arguments.length ? (r = t, u()) : r
}, i.interpolate = function(t) {
return arguments.length ? (e = t, u()) : e
}, i.ticks = function(n) {
return F(t, n)
}, i.tickFormat = function(n, e) {
return L(t, n, e)
}, i.nice = function() {
return D(t, Y), u()
}, i.copy = function() {
return _(t, n, e, r)
}, u()
}
function k(t, n) {
return xn.rebind(t, n, "range", "rangeRound", "interpolate", "clamp")
}
function Y(t) {
return t = Math.pow(10, Math.round(Math.log(t) / Math.LN10) - 1), t && {
floor: function(n) {
return Math.floor(n / t) * t
},
ceil: function(n) {
return Math.ceil(n / t) * t
}
}
}
function S(t, n) {
var e = C(t),
r = e[1] - e[0],
u = Math.pow(10, Math.floor(Math.log(r / n) / Math.LN10)),
i = n / r * u;
return .15 >= i ? u *= 10 : .35 >= i ? u *= 5 : .75 >= i && (u *= 2), e[0] = Math.ceil(e[0] / u) * u, e[1] = Math.floor(e[1] / u) * u + .5 * u, e[2] = u, e
}
function F(t, n) {
return xn.range.apply(xn, S(t, n))
}
function L(t, n, e) {
var r = -Math.floor(Math.log(S(t, n)[2]) / Math.LN10 + .01);
return xn.format(e ? e.replace(Ln, function(t, n, e, u, i, o, a, c, f, s) {
return [n, e, u, i, o, a, c, f || "." + (r - 2 * ("%" === s)), s].join("")
}) : ",." + r + "f")
}
function A(t, n, e) {
function r(n) {
return t(u(n))
}
var u = O(n),
i = O(1 / n);
return r.invert = function(n) {
return i(t.invert(n))
}, r.domain = function(n) {
return arguments.length ? (t.domain((e = n.map(Number)).map(u)), r) : e
}, r.ticks = function(t) {
return F(e, t)
}, r.tickFormat = function(t, n) {
return L(e, t, n)
}, r.nice = function() {
return r.domain(D(e, Y))
}, r.exponent = function(o) {
return arguments.length ? (u = O(n = o), i = O(1 / n), t.domain(e.map(u)), r) : n
}, r.copy = function() {
return A(t.copy(), n, e)
}, k(r, t)
}
function O(t) {
return function(n) {
return 0 > n ? -Math.pow(-n, t) : Math.pow(n, t)
}
}
function I(t, n, e, r, u) {
function i(n) {
return t(e(n))
}
function o() {
return e === U ? {
floor: a,
ceil: c
} : {
floor: function(t) {
return -c(-t)
},
ceil: function(t) {
return -a(-t)
}
}
}
function a(t) {
return Math.pow(n, Math.floor(Math.log(t) / Math.log(n)))
}
function c(t) {
return Math.pow(n, Math.ceil(Math.log(t) / Math.log(n)))
}
return i.invert = function(n) {
return r(t.invert(n))
}, i.domain = function(n) {
return arguments.length ? (n[0] < 0 ? (e = N, r = E) : (e = U, r = H), t.domain((u = n.map(Number)).map(e)), i) : u
}, i.base = function(t) {
return arguments.length ? (n = +t, i) : n
}, i.nice = function() {
return t.domain(D(u, o).map(e)), i
}, i.ticks = function() {
var u = C(t.domain()),
i = [];
if (u.every(isFinite)) {
var o = Math.log(n),
a = Math.floor(u[0] / o),
c = Math.ceil(u[1] / o),
f = r(u[0]),
s = r(u[1]),
l = n % 1 ? 2 : n;
if (e === N)
for (i.push(-Math.pow(n, -a)); a++ < c;)
for (var h = l - 1; h > 0; h--) i.push(-Math.pow(n, -a) * h);
else {
for (; c > a; a++)
for (var h = 1; l > h; h++) i.push(Math.pow(n, a) * h);
i.push(Math.pow(n, a))
}
for (a = 0; i[a] < f; a++);
for (c = i.length; i[c - 1] > s; c--);
i = i.slice(a, c)
}
return i
}, i.tickFormat = function(t, u) {
if (arguments.length < 2 && (u = Hn), !arguments.length) return u;
var o, a = Math.log(n),
c = Math.max(.1, t / i.ticks().length),
f = e === N ? (o = -1e-12, Math.floor) : (o = 1e-12, Math.ceil);
return function(t) {
return t / r(a * f(e(t) / a + o)) <= c ? u(t) : ""
}
}, i.copy = function() {
return I(t.copy(), n, e, r, u)
}, k(i, t)
}
function U(t) {
return Math.log(0 > t ? 0 : t)
}
function H(t) {
return Math.exp(t)
}
function N(t) {
return -Math.log(t > 0 ? 0 : -t)
}
function E(t) {
return -Math.exp(-t)
}
function j() {
return !0
}
function z() {
this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0])
}
function X(t, n, e) {
function r(n) {
var e = t(n),
r = i(e, 1);
return r - n > n - e ? e : r
}
function u(e) {
return n(e = t(new Nn(e - 1)), 1), e
}
function i(t, e) {
return n(t = new Nn(+t), e), t
}
function o(t, r, i) {
var o = u(t),
a = [];
if (i > 1)
for (; r > o;) e(o) % i || a.push(new Date(+o)), n(o, 1);
else
for (; r > o;) a.push(new Date(+o)), n(o, 1);
return a
}
function a(t, n, e) {
try {
Nn = z;
var r = new z;
return r._ = t, o(r, n, e)
} finally {
Nn = Date
}
}
t.floor = t, t.round = r, t.ceil = u, t.offset = i, t.range = o;
var c = t.utc = q(t);
return c.floor = c, c.round = q(r), c.ceil = q(u), c.offset = q(i), c.range = a, t
}
function q(t) {
return function(n, e) {
try {
Nn = z;
var r = new z;
return r._ = n, t(r, e)._
} finally {
Nn = Date
}
}
}
function P(t, n, e, r) {
for (var u, i, o = 0, a = n.length, c = e.length; a > o;) {
if (r >= c) return -1;
if (u = n.charCodeAt(o++), 37 === u) {
if (i = re[n.charAt(o++)], !i || (r = i(t, e, r)) < 0) return -1
} else if (u != e.charCodeAt(r++)) return -1
}
return r
}
function G(t) {
return new RegExp("^(?:" + t.map(xn.requote).join("|") + ")", "i")
}
function R(t) {
for (var n = new v, e = -1, r = t.length; ++e < r;) n.set(t[e].toLowerCase(), e);
return n
}
function B(t, n, e) {
t += "";
var r = t.length;
return e > r ? new Array(e - r + 1).join(n) + t : t
}
function W(t, n, e) {
Vn.lastIndex = 0;
var r = Vn.exec(n.substring(e));
return r ? e += r[0].length : -1
}
function Z(t, n, e) {
$n.lastIndex = 0;
var r = $n.exec(n.substring(e));
return r ? e += r[0].length : -1
}
function $(t, n, e) {
Qn.lastIndex = 0;
var r = Qn.exec(n.substring(e));
return r ? (t.m = te.get(r[0].toLowerCase()), e += r[0].length) : -1
}
function V(t, n, e) {
Jn.lastIndex = 0;
var r = Jn.exec(n.substring(e));
return r ? (t.m = Kn.get(r[0].toLowerCase()), e += r[0].length) : -1
}
function J(t, n, e) {
return P(t, ee.c.toString(), n, e)
}
function K(t, n, e) {
return P(t, ee.x.toString(), n, e)
}
function Q(t, n, e) {
return P(t, ee.X.toString(), n, e)
}
function tn(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 4));
return r ? (t.y = +r[0], e += r[0].length) : -1
}
function nn(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.y = en(+r[0]), e += r[0].length) : -1
}
function en(t) {
return t + (t > 68 ? 1900 : 2e3)
}
function rn(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.m = r[0] - 1, e += r[0].length) : -1
}
function un(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.d = +r[0], e += r[0].length) : -1
}
function on(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.H = +r[0], e += r[0].length) : -1
}
function an(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.M = +r[0], e += r[0].length) : -1
}
function cn(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 2));
return r ? (t.S = +r[0], e += r[0].length) : -1
}
function fn(t, n, e) {
ue.lastIndex = 0;
var r = ue.exec(n.substring(e, e + 3));
return r ? (t.L = +r[0], e += r[0].length) : -1
}
function sn(t, n, e) {
var r = ie.get(n.substring(e, e += 2).toLowerCase());
return null == r ? -1 : (t.p = r, e)
}
function ln(t) {
var n = t.getTimezoneOffset(),
e = n > 0 ? "-" : "+",
r = ~~(Math.abs(n) / 60),
u = Math.abs(n) % 60;
return e + B(r, "0", 2) + B(u, "0", 2)
}
function hn(t, n, e) {
function r(n) {
return t(n)
}
return r.invert = function(n) {
return gn(t.invert(n))
}, r.domain = function(n) {
return arguments.length ? (t.domain(n), r) : t.domain().map(gn)
}, r.nice = function(t) {
return r.domain(D(r.domain(), function() {
return t
}))
}, r.ticks = function(e, u) {
var i = C(r.domain());
if ("function" != typeof e) {
var o = i[1] - i[0],
a = o / e,
c = xn.bisect(oe, a);
if (c == oe.length) return n.year(i, e);
if (!c) return t.ticks(e).map(gn);
Math.log(a / oe[c - 1]) < Math.log(oe[c] / a) && --c, e = n[c], u = e[1], e = e[0].range
}
return e(i[0], new Date(+i[1] + 1), u)
}, r.tickFormat = function() {
return e
}, r.copy = function() {
return hn(t.copy(), n, e)
}, k(r, t)
}
function gn(t) {
return new Date(t)
}
function mn(t) {
return function(n) {
for (var e = t.length - 1, r = t[e]; !r[1](n);) r = t[--e];
return r[0](n)
}
}
function pn(t) {
var n = new Date(t, 0, 1);
return n.setFullYear(t), n
}
function dn(t) {
var n = t.getFullYear(),
e = pn(n),
r = pn(n + 1);
return n + (t - e) / (r - e)
}
function vn(t) {
return null != t && !isNaN(t)
}
function Mn(t, n, e) {
return (e[0] - n[0]) * (t[1] - n[1]) < (e[1] - n[1]) * (t[0] - n[0])
}
function yn(t, n, e, r) {
var u = t[0],
i = e[0],
o = n[0] - u,
a = r[0] - i,
c = t[1],
f = e[1],
s = n[1] - c,
l = r[1] - f,
h = (a * (c - f) - l * (u - i)) / (l * o - a * s);
return [u + h * o, c + h * s]
}
var xn = {
version: "3.1.7"
};
xn.range = function(n, e, r) {
if (arguments.length < 3 && (r = 1, arguments.length < 2 && (e = n, n = 0)), 1 / 0 === (e - n) / r) throw new Error("infinite range");
var u, i = [],
o = t(Math.abs(r)),
a = -1;
if (n *= o, e *= o, r *= o, 0 > r)
for (;
(u = n + r * ++a) > e;) i.push(u / o);
else
for (;
(u = n + r * ++a) < e;) i.push(u / o);
return i
}, xn.rebind = function(t, e) {
for (var r, u = 1, i = arguments.length; ++u < i;) t[r = arguments[u]] = n(t, e, e[r]);
return t
};
var wn = document,
bn = {
svg: "http://www.w3.org/2000/svg",
xhtml: "http://www.w3.org/1999/xhtml",
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
xn.ns = {
prefix: bn,
qualify: function(t) {
var n = t.indexOf(":"),
e = t;
return n >= 0 && (e = t.substring(0, n), t = t.substring(n + 1)), bn.hasOwnProperty(e) ? {
space: bn[e],
local: t
} : t
}
}, xn.transform = function(t) {
var n = wn.createElementNS(xn.ns.prefix.svg, "g");
return (xn.transform = function(t) {
if (null != t) {
n.setAttribute("transform", t);
var r = n.transform.baseVal.consolidate()
}
return new e(r ? r.matrix : Dn)
})(t)
}, e.prototype.toString = function() {
return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"
};
var Dn = {
a: 1,
b: 0,
c: 0,
d: 1,
e: 0,
f: 0
};
xn.interpolateNumber = o, xn.interpolateTransform = a, xn.interpolateObject = c, xn.interpolateArray = f, xn.interpolateString = s;
var Tn = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
xn.interpolate = l, xn.interpolators = [function(t, n) {
var e = typeof n;
return ("string" === e ? s : "object" === e ? Array.isArray(n) ? f : c : o)(t, n)
}], xn.interpolateRound = g, xn.map = function(t) {
var n = new v;
for (var e in t) n.set(e, t[e]);
return n
}, d(v, {
has: function(t) {
return Cn + t in this
},
get: function(t) {
return this[Cn + t]
},
set: function(t, n) {
return this[Cn + t] = n
},
remove: function(t) {
return t = Cn + t, t in this && delete this[t]
},
keys: function() {
var t = [];
return this.forEach(function(n) {
t.push(n)
}), t
},
values: function() {
var t = [];
return this.forEach(function(n, e) {
t.push(e)
}), t
},
entries: function() {
var t = [];
return this.forEach(function(n, e) {
t.push({
key: n,
value: e
})
}), t
},
forEach: function(t) {
for (var n in this) n.charCodeAt(0) === _n && t.call(this, n.substring(1), this[n])
}
});
var Cn = "\0",
_n = Cn.charCodeAt(0),
kn = ".",
Yn = ",",
Sn = [3, 3],
Fn = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"].map(y);
xn.formatPrefix = function(t, n) {
var e = 0;
return t && (0 > t && (t *= -1), n && (t = xn.round(t, x(t, n))), e = 1 + Math.floor(1e-12 + Math.log(t) / Math.LN10), e = Math.max(-24, Math.min(24, 3 * Math.floor((0 >= e ? e + 1 : e - 1) / 3)))), Fn[8 + e / 3]
}, xn.round = function(t, n) {
return n ? Math.round(t * (n = Math.pow(10, n))) / n : Math.round(t)
}, xn.format = function(t) {
var n = Ln.exec(t),
e = n[1] || " ",
r = n[2] || ">",
u = n[3] || "",
i = n[4] || "",
o = n[5],
a = +n[6],
c = n[7],
f = n[8],
s = n[9],
l = 1,
h = "",
g = !1;
switch (f && (f = +f.substring(1)), (o || "0" === e && "=" === r) && (o = e = "0", r = "=", c && (a -= Math.floor((a - 1) / 4))), s) {
case "n":
c = !0, s = "g";
break;
case "%":
l = 100, h = "%", s = "f";
break;
case "p":
l = 100, h = "%", s = "r";
break;
case "b":
case "o":
case "x":
case "X":
i && (i = "0" + s.toLowerCase());
case "c":
case "d":
g = !0, f = 0;
break;
case "s":
l = -1, s = "r"
}
"#" === i && (i = ""), "r" != s || f || (s = "g"), null != f && ("g" == s ? f = Math.max(1, Math.min(21, f)) : ("e" == s || "f" == s) && (f = Math.max(0, Math.min(20, f)))), s = An.get(s) || w;
var m = o && c;
return function(t) {
if (g && t % 1) return "";
var n = 0 > t || 0 === t && 0 > 1 / t ? (t = -t, "-") : u;
if (0 > l) {
var p = xn.formatPrefix(t, f);
t = p.scale(t), h = p.symbol
} else t *= l;
t = s(t, f), !o && c && (t = On(t));
var d = i.length + t.length + (m ? 0 : n.length),
v = a > d ? new Array(d = a - d + 1).join(e) : "";
return m && (t = On(v + t)), kn && t.replace(".", kn), n += i, ("<" === r ? n + t + v : ">" === r ? v + n + t : "^" === r ? v.substring(0, d >>= 1) + n + t + v.substring(d) : n + (m ? t : v + t)) + h
}
};
var Ln = /(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,
An = xn.map({
b: function(t) {
return t.toString(2)
},
c: function(t) {
return String.fromCharCode(t)
},
o: function(t) {
return t.toString(8)
},
x: function(t) {
return t.toString(16)
},
X: function(t) {
return t.toString(16).toUpperCase()
},
g: function(t, n) {
return t.toPrecision(n)
},
e: function(t, n) {
return t.toExponential(n)
},
f: function(t, n) {
return t.toFixed(n)
},
r: function(t, n) {
return (t = xn.round(t, x(t, n))).toFixed(Math.max(0, Math.min(20, x(t * (1 + 1e-15), n))))
}
}),
On = M;
if (Sn) {
var In = Sn.length;
On = function(t) {
for (var n = t.lastIndexOf("."), e = n >= 0 ? "." + t.substring(n + 1) : (n = t.length, ""), r = [], u = 0, i = Sn[0]; n > 0 && i > 0;) r.push(t.substring(n -= i, n + i)), i = Sn[u = (u + 1) % In];
return r.reverse().join(Yn || "") + e
}
}
xn.bisector = function(t) {
return {
left: function(n, e, r, u) {
for (arguments.length < 3 && (r = 0), arguments.length < 4 && (u = n.length); u > r;) {
var i = r + u >>> 1;
t.call(n, n[i], i) < e ? r = i + 1 : u = i
}
return r
},
right: function(n, e, r, u) {
for (arguments.length < 3 && (r = 0), arguments.length < 4 && (u = n.length); u > r;) {
var i = r + u >>> 1;
e < t.call(n, n[i], i) ? u = i : r = i + 1
}
return r
}
}
};
var Un = xn.bisector(function(t) {
return t
});
xn.bisectLeft = Un.left, xn.bisect = xn.bisectRight = Un.right, xn.scale = {}, xn.scale.linear = function() {
return _([0, 1], [0, 1], l, !1)
}, xn.scale.pow = function() {
return A(xn.scale.linear(), 1, [0, 1])
}, xn.scale.sqrt = function() {
return xn.scale.pow().exponent(.5)
}, xn.scale.log = function() {
return I(xn.scale.linear().domain([0, Math.LN10]), 10, U, H, [1, 10])
};
var Hn = xn.format(".0e");
xn.time = {};
var Nn = Date,
En = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
z.prototype = {
getDate: function() {
return this._.getUTCDate()
},
getDay: function() {
return this._.getUTCDay()
},
getFullYear: function() {
return this._.getUTCFullYear()
},
getHours: function() {
return this._.getUTCHours()
},
getMilliseconds: function() {
return this._.getUTCMilliseconds()
},
getMinutes: function() {
return this._.getUTCMinutes()
},
getMonth: function() {
return this._.getUTCMonth()
},
getSeconds: function() {
return this._.getUTCSeconds()
},
getTime: function() {
return this._.getTime()
},
getTimezoneOffset: function() {
return 0
},
valueOf: function() {
return this._.valueOf()
},
setDate: function() {
jn.setUTCDate.apply(this._, arguments)
},
setDay: function() {
jn.setUTCDay.apply(this._, arguments)
},
setFullYear: function() {
jn.setUTCFullYear.apply(this._, arguments)
},
setHours: function() {
jn.setUTCHours.apply(this._, arguments)
},
setMilliseconds: function() {
jn.setUTCMilliseconds.apply(this._, arguments)
},
setMinutes: function() {
jn.setUTCMinutes.apply(this._, arguments)
},
setMonth: function() {
jn.setUTCMonth.apply(this._, arguments)
},
setSeconds: function() {
jn.setUTCSeconds.apply(this._, arguments)
},
setTime: function() {
jn.setTime.apply(this._, arguments)
}
};
var jn = Date.prototype;
xn.time.year = X(function(t) {
return t = xn.time.day(t), t.setMonth(0, 1), t
}, function(t, n) {
t.setFullYear(t.getFullYear() + n)
}, function(t) {
return t.getFullYear()
}), xn.time.years = xn.time.year.range, xn.time.years.utc = xn.time.year.utc.range, xn.time.day = X(function(t) {
var n = new Nn(1970, 0);
return n.setFullYear(t.getFullYear(), t.getMonth(), t.getDate()), n
}, function(t, n) {
t.setDate(t.getDate() + n)
}, function(t) {
return t.getDate() - 1
}), xn.time.days = xn.time.day.range, xn.time.days.utc = xn.time.day.utc.range, xn.time.dayOfYear = function(t) {
var n = xn.time.year(t);
return Math.floor((t - n - 6e4 * (t.getTimezoneOffset() - n.getTimezoneOffset())) / 864e5)
}, xn.requote = function(t) {
return t.replace(zn, "\\$&")
};
var zn = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,
Xn = "%a %e %b %X %Y",
qn = "%d.%m.%Y",
Pn = "%H:%M:%S",
Gn = Globalize.culture(__locale).calendar.days.names,
Rn = Globalize.culture(__locale).calendar.days.namesAbbr,
Bn = Globalize.culture(__locale).calendar.months.names,
Wn = Globalize.culture(__locale).calendar.months.namesAbbr,
Zn = Globalize.culture().calendar.firstDay;
En.forEach(function(t, n) {
t = t.toLowerCase(), n = 7 - n;
var e = xn.time[t] = X(function(t) {
return (t = xn.time.day(t)).setDate(t.getDate() - (t.getDay() + n) % 7), t
}, function(t, n) {
t.setDate(t.getDate() + 7 * Math.floor(n))
}, function(t) {
var e = xn.time.year(t).getDay();
return Math.floor((xn.time.dayOfYear(t) + (e + n) % 7) / 7) - (e !== n)
});
xn.time[t + "s"] = e.range, xn.time[t + "s"].utc = e.utc.range, xn.time[t + "OfYear"] = function(t) {
var e = xn.time.year(t).getDay();
return Math.floor((xn.time.dayOfYear(t) + (e + n) % 7) / 7)
}
}), xn.time.week = xn.time[En[Zn].toLowerCase()], xn.time.weeks = xn.time[En[Zn].toLowerCase()].range, xn.time.weeks.utc = xn.time[En[Zn].toLowerCase()].utc.range, xn.time.weekOfYear = xn.time.sundayOfYear, xn.time.format = function(t) {
function n(n) {
for (var r, u, i, o = [], a = -1, c = 0; ++a < e;) 37 === t.charCodeAt(a) && (o.push(t.substring(c, a)), null != (u = ne[r = t.charAt(++a)]) && (r = t.charAt(++a)), (i = ee[r]) && (r = i(n, null == u ? "e" === r ? " " : "0" : u)), o.push(r), c = a + 1);
return o.push(t.substring(c, a)), o.join("")
}
var e = t.length;
return n.parse = function(n) {
var e = {
y: 1900,
m: 0,
d: 1,
H: 0,
M: 0,
S: 0,
L: 0
},
r = P(e, t, n, 0);
if (r != n.length) return null;
"p" in e && (e.H = e.H % 12 + 12 * e.p);
var u = new Nn;
return u.setFullYear(e.y, e.m, e.d), u.setHours(e.H, e.M, e.S, e.L), u
}, n.toString = function() {
return t
}, n
};
var $n = G(Gn),
Vn = G(Rn),
Jn = G(Bn),
Kn = R(Bn),
Qn = G(Wn),
te = R(Wn),
ne = {
"-": "",
_: " ",
0: "0"
},
ee = {
a: function(t) {
return Rn[t.getDay()]
},
A: function(t) {
return Gn[t.getDay()]
},
b: function(t) {
return Wn[t.getMonth()]
},
B: function(t) {
return Bn[t.getMonth()]
},
c: xn.time.format(Xn),
d: function(t, n) {
return B(t.getDate(), n, 2)
},
e: function(t, n) {
return B(t.getDate(), n, 2)
},
H: function(t, n) {
return B(t.getHours(), n, 2)
},
I: function(t, n) {
return B(t.getHours() % 12 || 12, n, 2)
},
j: function(t, n) {
return B(1 + xn.time.dayOfYear(t), n, 3)
},
L: function(t, n) {
return B(t.getMilliseconds(), n, 3)
},
m: function(t, n) {
return B(t.getMonth() + 1, n, 2)
},
M: function(t, n) {
return B(t.getMinutes(), n, 2)
},
p: function(t) {
return t.getHours() >= 12 ? "PM" : "AM"
},
S: function(t, n) {
return B(t.getSeconds(), n, 2)
},
U: function(t, n) {
return B(xn.time.sundayOfYear(t), n, 2)
},
w: function(t) {
return t.getDay()
},
W: function(t, n) {
return B(xn.time.mondayOfYear(t), n, 2)
},
x: xn.time.format(qn),
X: xn.time.format(Pn),
y: function(t, n) {
return B(t.getFullYear() % 100, n, 2)
},
Y: function(t, n) {
return B(t.getFullYear() % 1e4, n, 4)
},
Z: ln,
"%": function() {
return "%"
}
},
re = {
a: W,
A: Z,
b: $,
B: V,
c: J,
d: un,
e: un,
H: on,
I: on,
L: fn,
m: rn,
M: an,
p: sn,
S: cn,
x: K,
X: Q,
y: nn,
Y: tn
},
ue = /^\s*\d+/,
ie = xn.map({
am: 0,
pm: 1
});
xn.time.hour = X(function(t) {
var n = t.getTimezoneOffset() / 60;
return new Nn(36e5 * (Math.floor(t / 36e5 - n) + n))
}, function(t, n) {
t.setTime(t.getTime() + 36e5 * Math.floor(n))
}, function(t) {
return t.getHours()
}), xn.time.hours = xn.time.hour.range, xn.time.hours.utc = xn.time.hour.utc.range, xn.time.minute = X(function(t) {
return new Nn(6e4 * Math.floor(t / 6e4))
}, function(t, n) {
t.setTime(t.getTime() + 6e4 * Math.floor(n))
}, function(t) {
return t.getMinutes()
}), xn.time.minutes = xn.time.minute.range, xn.time.minutes.utc = xn.time.minute.utc.range, xn.time.month = X(function(t) {
return t = xn.time.day(t), t.setDate(1), t
}, function(t, n) {
t.setMonth(t.getMonth() + n)
}, function(t) {
return t.getMonth()
}), xn.time.months = xn.time.month.range, xn.time.months.utc = xn.time.month.utc.range, xn.time.second = X(function(t) {
return new Nn(1e3 * Math.floor(t / 1e3))
}, function(t, n) {
t.setTime(t.getTime() + 1e3 * Math.floor(n))
}, function(t) {
return t.getSeconds()
}), xn.time.seconds = xn.time.second.range, xn.time.seconds.utc = xn.time.second.utc.range;
var oe = [1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6],
ae = [
[xn.time.second, 1],
[xn.time.second, 5],
[xn.time.second, 15],
[xn.time.second, 30],
[xn.time.minute, 1],
[xn.time.minute, 5],
[xn.time.minute, 15],
[xn.time.minute, 30],
[xn.time.hour, 1],
[xn.time.hour, 3],
[xn.time.hour, 6],
[xn.time.hour, 12],
[xn.time.day, 1],
[xn.time.day, 2],
[xn.time.week, 1],
[xn.time.month, 1],
[xn.time.month, 3],
[xn.time.year, 1]
],
ce = [
[xn.time.format("%Y"), j],
[xn.time.format("%B"), function(t) {
return t.getMonth()
}],
[xn.time.format("%b %d"), function(t) {
return 1 != t.getDate()
}],
[xn.time.format("%a %d"), function(t) {
return t.getDay() != Zn && 1 != t.getDate()
}],
[xn.time.format("%I %p"), function(t) {
return t.getHours()
}],
[xn.time.format("%I:%M"), function(t) {
return t.getMinutes()
}],
[xn.time.format(":%S"), function(t) {
return t.getSeconds()
}],
[xn.time.format(".%L"), function(t) {
return t.getMilliseconds()
}]
],
fe = xn.scale.linear(),
se = mn(ce);
return ae.year = function(t, n) {
return fe.domain(t.map(dn)).ticks(n).map(pn)
}, xn.time.scale = function() {
return hn(xn.scale.linear(), ae, se)
}, xn.ascending = function(t, n) {
return n > t ? -1 : t > n ? 1 : t >= n ? 0 : 0 / 0
}, xn.quantile = function(t, n) {
var e = (t.length - 1) * n + 1,
r = Math.floor(e),
u = +t[r - 1],
i = e - r;
return i ? u + i * (t[r] - u) : u
}, xn.median = function(t, n) {
return arguments.length > 1 && (t = t.map(n)), t = t.filter(vn), t.length ? xn.quantile(t.sort(xn.ascending), .5) : void 0
}, xn.extent = function(t, n) {
var e, r, u, i = -1,
o = t.length;
if (1 === arguments.length) {
for (; ++i < o && (null == (e = u = t[i]) || e != e);) e = u = void 0;
for (; ++i < o;) null != (r = t[i]) && (e > r && (e = r), r > u && (u = r))
} else {
for (; ++i < o && (null == (e = u = n.call(t, t[i], i)) || e != e);) e = void 0;
for (; ++i < o;) null != (r = n.call(t, t[i], i)) && (e > r && (e = r), r > u && (u = r))
}
return [e, u]
}, xn.min = function(t, n) {
var e, r, u = -1,
i = t.length;
if (1 === arguments.length) {
for (; ++u < i && (null == (e = t[u]) || e != e);) e = void 0;
for (; ++u < i;) null != (r = t[u]) && e > r && (e = r)
} else {
for (; ++u < i && (null == (e = n.call(t, t[u], u)) || e != e);) e = void 0;
for (; ++u < i;) null != (r = n.call(t, t[u], u)) && e > r && (e = r)
}
return e
}, xn.max = function(t, n) {
var e, r, u = -1,
i = t.length;
if (1 === arguments.length) {
for (; ++u < i && (null == (e = t[u]) || e != e);) e = void 0;
for (; ++u < i;) null != (r = t[u]) && r > e && (e = r)
} else {
for (; ++u < i && (null == (e = n.call(t, t[u], u)) || e != e);) e = void 0;
for (; ++u < i;) null != (r = n.call(t, t[u], u)) && r > e && (e = r)
}
return e
}, xn.sum = function(t, n) {
var e, r = 0,
u = t.length,
i = -1;
if (1 === arguments.length)
for (; ++i < u;) isNaN(e = +t[i]) || (r += e);
else
for (; ++i < u;) isNaN(e = +n.call(t, t[i], i)) || (r += e);
return r
}, xn.geom = {}, xn.geom.polygon = function(t) {
return t.area = function() {
for (var n = 0, e = t.length, r = t[e - 1][1] * t[0][0] - t[e - 1][0] * t[0][1]; ++n < e;) r += t[n - 1][1] * t[n][0] - t[n - 1][0] * t[n][1];
return .5 * r
}, t.centroid = function(n) {
var e, r, u = -1,
i = t.length,
o = 0,
a = 0,
c = t[i - 1];
for (arguments.length || (n = -1 / (6 * t.area())); ++u < i;) e = c, c = t[u], r = e[0] * c[1] - c[0] * e[1], o += (e[0] + c[0]) * r, a += (e[1] + c[1]) * r;
return [o * n, a * n]
}, t.clip = function(n) {
for (var e, r, u, i, o, a, c = -1, f = t.length, s = t[f - 1]; ++c < f;) {
for (e = n.slice(), n.length = 0, i = t[c], o = e[(u = e.length) - 1], r = -1; ++r < u;) a = e[r], Mn(a, s, i) ? (Mn(o, s, i) || n.push(yn(o, a, s, i)), n.push(a)) : Mn(o, s, i) && n.push(yn(o, a, s, i)), o = a;
s = i
}
return n
}, t
}, xn
}();
<file_sep>/_posts/2015-12-11-Marseille-violence-hits-up-Hungary.md
---
layout: post
published: true
title: A Hungarian man in Marseille
categorie: articles
cover_image: Cover_Hungary.jpg
related:
- Bad (Criminal) Company
- Du fait divers à la querelle politique
author: <NAME>
---
On September 13th, Hungary was brought violently into the tumultuous crime scene of France’s southern city Marseille. A Hungarian man, <NAME>. was shot to death in front of a bar, supposedly by gang members.
The victim was targeted by several men armed with heavy weapons that fired in bursts the terrace of the bar where he was working. Among the other casualties, six persons were harmed, three of them being severely hurt. They were all taking shelter from the rain on the terrace of the O’Stop bar.
The alleged target, <NAME>., was a 29 years old Hungarian man who had been living in France for two years. He was working as a guard and the head of his own security services company, Lima Protection. Witnesses said he took part in a quarrel earlier that evening with customers of the bar. The murder would have been a potential revenge from those men that came back later with machine guns. His death is the first of a foreign national in the long history of shoot-outs in France’s troubled southern city. Usually, violent acts are linked to the everlasting gang war and settling of accounts that oppose youth of the suburbs.
Violent killings of Hungarian nationals in France are uncommon, according to the Hungarian Consulate in Paris. Hence the media fury it triggered in the country, prompt to drawing quick conclusions. Newspapers with a wide audience mentioned a dispute with _“Arabs”._ In a political context of rising nationalism in Europe and especially in Hungary, it is not surprising that the media are fueling the argument of a clash opposing ethnic communities. The French police has not yet revealed the identity of the suspects.
> During the tragic night, a group of Arab immigrants refused to pay their order and caused a conflict.
**Blikk** — national daily tabloid
{: .credit}
Using words such as _“immigrants”,_ the Hungarian media assume that the culprits were arms dealers. Dismissing the thesis of a settlement of accounts, Hungarian journalists assure that Laszlo T. was truly a victim since he had no police records. French investigators have yet to speak out on the case.

{: .fullwidth}
Locals of Bekes county in Hungary, from which Laszlo T. was a native, expressed their utter surprise and emotional support to the family. As indicated by the local newspaper Beol, Laszlo’s mother was extremely affected by his loss and under sedatives. His step-dad handled the funerals and launched a crowdfunding campaign for the ceremony that was held on October 16th. Friends from his childhood boxing club also held a vigil in his honor.
In France, Laszlo’s friends also showed their support on social media. Marseille’s Royal Boxing Club released a tribute video to the young man on its Youtube account. Renaud, one of his boxer companions recalls _“a brave, strong and a good man”_ with a taste for thai boxing.
Almost three months after the incident, very few information leaked from the investigation. French officers refuse to reveal any details on their probe and the owners of the O’Stop bar are reluctant to answer any inquiries.
<file_sep>/_posts/2015-12-11-barbecue.markdown
---
layout: post
title: « Barbecue »
categories: articles
published: true
cover_image: Cover_Barbecue.jpg
related:
- Identifier des cendres
- Quitter les quartiers Nord
author: <NAME>
---
Le 30 novembre, une nuit calme, dans ce petit quartier de la Batarelle, au nord du 13ème arrondissement de Marseille, des riverains donnent l’alerte: une voiture incendiée se consume rue de la Gardiette, juste devant la barrière du chemin d’accès au Pic de l’Etoile. Les marins-pompiers sont dépêchés sur place et font la macabre découverte d’un corps étranglé, pieds et poings liés.
Très vite, on suppose un règlement de compte, à cause de l'emploi de cette technique caractéristique du « barbecue ». Pour la police, elle est synonyme de trafic de stupéfiants : la victime, tuée par balle, est ensuite brûlée dans l’incendie d’un véhicule. Mais l’enquête en cours n’entérine pas encore cette théorie: _« il n’a pas été tué par balle mais étranglé »,_ précise-t-on à la police judiciaire.
Depuis le début de la décennie, la police observe une recrudescence de ce type d’homicides qui font écho une autre série survenue dans les années 2000, dans le sillage d'un criminel baptisé "le rotisseur". A-t-il un successeur ? Une deuxième vague de meurtres est-elle lancée ?

{: .fullwidth .image}
6 corps calcinés entre 2014 et 2015.<br />
2 considérés comme des règlements de compte par la police
{: .punchline}
Du fait-divers, les "barbecues" gagnent la chronique judiciaire. Le 9 décembre, la cour d'assises d'Aix-en-Provence ont entrepris de juger le triple meurtre de <NAME>., <NAME>. et <NAME>., trois hommes dont les corps criblés de balles avaient été découverts le 25 décembre 2011, dans une Audi A3 noire en flammes. Sur le banc des accusés, un commanditaire, <NAME>. et deux exécutants <NAME>. et <NAME>.. Malgré les difficultés à mettre en évidence des preuves tangibles de leur culpabilité, et un _"dossier de rumeurs"_ d'après les avocats de la défense, la cour d'Aix a requis la perpétuité assortie de 22 ans de sûreté à l'encontre des trois accusés, rapporte le journal _La Provence_ le 17 décembre dernier.
Cette affaire, qui a pour toile de fond le contrôle du trafic de drogue dans la cité des Micocouliers, est la dernière à suivre le schéma classique établi dans les années 2000 impliquant des rivalités de bandes organisées sur fond de trafic de stupéfiants et de luttes territoriales, et l'assassinat suivi de la combustion du cadavre dans une voiture en guise de représailles. Depuis, les cas s'écartent de plus en plus de la définition "traditionnelle".
Sur les six derniers cas recensé au 10 décembre 2015, la police considère que 2 seulement sont de "vrais" barbecues, contre 20 règlements de compte recensés cette année par la préfecture de police des Bouches-du-Rhône.
Le 30 novembre, à la Batarelle, riverains et sauveteurs ont immédiatement reconnu le procédé, qui résonne dans l’imaginaire collectif de la cité phocéenne. Dans un article de _La Provence_, un marin-pompier témoigne : _«à chaque feu de ce genre, on se demande si l'on va faire une découverte macabre »._
Mais la police est partagée, car le mode opératoire n'est pas nominal : la victime n’a pas été criblée de balle, l’autopsie -- rendue difficile par la combustion -- n’a pas encore déterminé les causes exactes de la mort et les poings liés ne sont pas communs dans les « barbecues ».
Selon une source policière, la victime, née en 1992, est connue des services pour des faits de petites délinquance mais n’est pas impliquée dans le trafic de stupéfiants: ce profil renvoie à un différend qui ne serait pas lié à une activité criminelle, et ne correspond donc pas à un règlement de comptes. Un article du _Parisien_ paru le 15 décembre 2015, citant un enquêteur, affirme toutefois que "L'exécution d'Anthony L. (nom de la victime révélé à la suite de l'enquête policière NDLR.) pourrait être le match retour au meurtre du fameux "Babouin" au tunnel du Prado, vengé par ses complices"
Pour <NAME>, docteur en droit et spécialiste du banditisme dans la région de Marseille, cette technique _« est certainement moins utilisée que ce que l’on pense même si ces dernières années, elle a été beaucoup pratiquée, notamment dans les cités »._
>Il joue sur le match retour car il crée une haine supplémentaire
**<NAME>** - docteur en droit et spécialiste du banditisme local dans la région de Marseille
{: .credit}
L'universitaire ajoute que _« la pratique est liée aux règlements de comptes; dans le Midi, elle a d’abord été utilisée par le grand banditisme corso-varois, puis par le néo-banditisme marseillais »._ Selon <NAME>, spécialiste de la criminalité et du trafic de drogue, le « barbecue », par le côté spectaculaire et l’humiliation qu’il provoque, envoie un message : _« il joue sur le match retour car il crée une haine supplémentaire »._

{: .fullwidth .image}
* **7** cadavres calcinés dans des voitures entre 1998-2006
* **2005** - relaxé pour une association de malfaiteurs autour de machines à sous
* **2006** Il meurt fusllé à la brasserie marseillaise Les Marronniers (13E)
{: .note}
Dans les années 2000, <NAME>., jeune malfaiteur marseillais surnommé le « Rôtisseur », popularise la pratique. Le « barbecue » devient une signature des luttes territoriales et d’influence des grands gangs, autour de l'affaire dite des machines à sous, qui cristallisait les rivalités pour le contrôle de cet argent autour de l'étang de Berre, zone d'influence de <NAME>. Faute de preuves, ce dernier n'est pas condamné pour ces possibles assassinats.
On comptabilise sept cas dans les années 2000. Tous répondent au même schéma: les victimes sont connues des services de police, et ont déjà été condamnées. Originaires des quartiers nord de Marseille, elles sont souvent considérées comme des grands chefs des bandes des cités.

{: .fullwidth}

{: .fullwidth}
Loin des caïds des années 2000, les "rotisseurs" d'aujourd'hui semblent réutiliser les codes de leurs aînés en les étendant à d’autres sphères que les traditionnelles guerres de bandes rivales. Les derniers cas ne sont pas la résurgence des années 2000, mais plutôt l’effet d’une vulgarisation de la pratique - une analyse sur le néo-banditisme que développent <NAME> et <NAME>, respectivement commissaire et capitaine de police, auteurs de Bandes, Dérive criminelle & terrorisme - employée maintenant par les tout petits délinquants, pas assez « gradés » pour être considérés comme cibles de règlement de compte.
<file_sep>/_posts/2015-12-11-Le-centre-ville-de-Marseille-,-une-zone-de-sécurité-non-prioritaire.md
---
layout: post
published: true
title: "Zone de sécurité non prioritaire ?"
categorie: articles
cover_image: Cover_zone_non_prioritaire.jpg
related:
- "L'argent ou l'honneur ?"
- "Avoir 15 ans, cité des Lauriers"
author: <NAME>
twitter: "https://twitter.com/JustineBarraud"
---
Dimanche 13 septembre, une [fusillade](http://www.lemonde.fr/police-justice/article/2015/09/13/une-fusillade-en-plein-c-ur-de-marseille-fait-un-mort-et-six-blesses_4755203_1653578.html) a éclaté à 6H00 du matin, suite à un différend survenu un peu plus tôt dans la nuit devant un bar du centre de Marseille, en face de l'Opéra. Un homme est mort et cinq autres ont été blessés.
Selon l'AFP, ce n’est pas un cas isolé dans ce quartier situé à deux pas du Vieux-Port : deux ans auparavant, trois hommes avaient été blessés par des tirs de kalachnikov. A l'époque, l'enquête avait également révélé que tout était parti d'un différend entre deux groupes.
## Quartier de l’Opéra, un quartier à risque
> Le quartier de l’Opéra, c’est un quartier de nuit, situé à l’hyper centre de Marseille. Il y a beaucoup de monde qui fréquente les commerces et les boites de nuit, donc c’est un quartier à risque.
<NAME>, adjoint délégué à la sécurité de la mairie du 1er arrondissement de Marseille
{: .credit}
Depuis cette dernière fusillade, _<< un sentiment d’insécurité, de tristesse et de peur s’est installé parmi les commerçants >>,_ témoigne <NAME>, adjoint délégué à la sécurité. _<< On essaie de les tranquilliser avec les mesures prises pour sécuriser le secteur. Le nombre de policiers n’a cependant pas été augmenté. Il y a beaucoup de patrouilles à pied, des brigades VTT, mais finalement comme ailleurs. >>_
Même son de cloche pour le président du Comité inter-quartier (CIQ) des habitants de l’Opéra, <NAME> : _<< Le quartier de l’Opéra, c’est le jour et la nuit. La journée, l’Opéra vit tranquillement autour de ses restaurants et brasseries. Avec les boites de nuit, ce sont souvent des bandes d’autres quartiers qui viennent faire la fête >>,_ explique-t-il. Entre les débordements dû à l’alcool et les cas plus extrême, comme la fusillade du 13 septembre, le CIQ Bourse/Opéra a demandé l’augmentation des patrouilles de nuit.
## La division Centre: un secteur restreint
Selon <NAME>, le besoin en sécurité a été comblé. Les habitants du quartier de l'opéra devraient être rassurés. Et pourtant ils évitent de sortir la nuit. En effet, l'Opéra est un quartier de fête. Mais malgré les risques de violence que peut causer un quartier où la nuit vit, l’hypercentre de Marseille n’est pas une zone prioritaire de sécurité.
En règle générale, la répartition des effectifs de police se fait en fonction du nombre d’habitants, de la taille du secteur et des besoins, selon la DDSP des Bouches-du-Rhône. Marseille est répartie en trois divisions : division Nord, Centre et Sud et selon la configuration des secteurs, la présence policière n’est pas la même.
La division Centre, dont fait parti le quartier de l’Opéra, ne concentre que quatre arrondissements: le 1er, le 2e, le 6e et le 7e. En comparaison, les divisions nord et sud regroupe 12 autres arrondissements dont 10 sont considérées comme des zones de sécurité prioritaire (ZSP).

{: .fullwidth}
La répartition des policiers se base sur des études sur la criminalité à moyen-long terme. _<< Une fusillade c’est un cas anecdotique par rapport au problème global de la délinquance. Elle ne symbolise pas forcément une hausse de la délinquance >>,_ explique <NAME>, porte-parole de la DDSP des Bouches du Rhône.
Ces cas là ne change néanmoins pas l’affectation première des policiers à certains secteurs. Les ressources en personnel sont, certes, utilisées en fonction de l’évolution de la délinquance mais afin de ne pas déstabiliser l’organisation quotidienne de la sécurité, il y a des effectifs qui sont fixes dans certains secteurs de Marseille.
## Etat d’urgence et centre-ville
Le 19 novembre, les députés ont voté la prolongation de l’état d’urgence pour trois mois. Dans ce cadre exceptionnel, le préfet de Police des Bouches du Rhône, <NAME>, a annoncé davantage de patrouilles dans le centre ville. Mais pour <NAME>, la priorité en matière de sécurité se situe vers les cités et quartiers sensibles de Marseille.
> Il ne faut pas délaisser le centre ville car c’est un point important. Néanmoins, on constate une baisse des faits criminels dans ce secteur.”
<NAME>, préfet de Police des Bouches-du-Rhône
{: .credit}
<file_sep>/_posts/2015-12-11-Sortir-des-quartiers-nord.markdown
---
layout: post
published: true
categorie: articles
title: Quitter les quartiers Nord
cover_image: Cover_Sortir_des_quartiers.jpg
related:
- "Le centre-ville, zone de sécurité non prioritaire ?"
- Mourir à 18 ans
author: <NAME>
---
Assassiné dans la nuit du 24 au 25 octobre 2015 au pied d'un immeuble de la cité des Lauriers (13e ardt), <NAME>., 15 ans, avait pourtant déménagé quatre ans plus tôt à Rennes pour échapper à la violence des quartiers Nord.
C’est à 2h40 que <NAME>. est retrouvé mort, dans le hall d’entrée D du bâtiment B des Lauriers. Son corps gît à côté de ceux de <NAME>. (15 ans) et <NAME>. (24 ans). Selon [La Provence](http://www.laprovence.com/article/actualites/3641977/marseille-ils-ont-ete-lachement-assassines-procureur.html), les trois jeunes hommes ont été les victimes d’une fusillade dont ils n’étaient pas les cibles initiales. Ce soir-là, les assaillants cherchaient une personne dont on ignore jusqu’à présent l’identité. Les auteurs présumés sont montés dans l’immeuble pour trouver leur cible, sans succès d’après l’AFP. Et c’est en redescendant qu’ils ont ouvert le feu sur les trois jeunes hommes désarmés.
Au mauvais endroit, au mauvais moment ? La question n’est pas encore élucidée pas les enquêteurs. Pour rendre hommage aux trois victimes, une marche blanche a été organisée le 7 novembre. Elle a rassemblé 700 personnes selon les organisateurs, comme le rapporte [_Le Figaro_](http://www.lefigaro.fr/flash-actu/2015/11/07/97001-20151107FILWWW00109-marche-blanche-apres-une-fusillade-a-marseille.php#xtor=AL-155-[Facebook]). Le quartier des Lauriers, endeuillé, a pu y exprimer son ras-le-bol des meurtres et du trafic de drogue. Mais également sa volonté de faire changer les choses.

{: .fullwidth .image}
Répartition des logements sociaux du 13e arrondissement
{: .credit}
LIRE AUSSI : ["En première ligne : mourir à 18 ans dans les quartiers nord de Marseille, de <NAME>"](https://)
{: .relance}
# Pour éviter l’engrenage des trafics, quitter les quartiers nord
<NAME>, élu Front national des 13e et 14e arrondissements délégué au logement, explique que les familles expriment régulièrement à la police, aux élus et à leurs bailleurs sociaux leur souhait de quitter le quartiers. Mais les procédures sont longues, et parfois vaine.
Un journaliste marseillais spécialiste de ce type d'affaires, insiste sur ces problèmes de logement : _« ce n’est pas une envie c’est une nécessité. De nombreuses familles veulent partir mais elles ne peuvent pas. Il y a ceux qui sont victimes de règlements de compte et qui ne veulent plus rester et il y a ceux qui parlent à la police et qui après sont visés par les trafiquants qui doivent partir »_.
Selon le rapport rédigé en mars 2015 par l’Observatoire régional de la Délinquance et des Contextes sociaux ([ORDCS](http://ordcs.mmsh.univ-aix.fr/publications/Documents/Rapport%20final_Clos-Sauvagere.pdf)), 52% des personnes interrogées à Clos la Rose (13e arrondissement) et 45,5% à la Sauvagère (10e arrondissement) souhaitent quitter leur logement pour des raisons d’insécurité.
C’est le cas de la famille de <NAME>., originaire d’un village au centre de Mayotte et installée dans la cité phocéenne depuis 1994. En 2011, la mère décide de quitter Marseille pour le quartier de Blosnes, à Rennes afin d’éloigner son fils Mohamed des _« mauvaises fréquentations »_. En septembre 2015, il est impliqué dans une affaire de voiture volée et finit par fuguer à Marseille, succombant à la fin tragique qu’on lui connaît, le 25 octobre 2015, comme l’indique la chaîne ultra-marine _[1ère](http://www.la1ere.fr/2015/10/26/un-mahorais-de-15-ans-parmi-les-victimes-d-un-reglement-de-compte-marseille-299309.html)_.

{: .fullwidth .image}
**La Cité des grands Lauriers, 400 logements sociaux dans un immeuble** - Les logements sociaux de ce grand-ensemble sont répliqués à l’identique
{: .credit}
# Le manque de sécurité remis en cause
Depuis son arrivée à la mairie, en mars 2014, <NAME>, a reçu de nombreux riverains souhaitant quitter leur quartier : _« Tout le monde veut partir des Lauriers mais personne ne veut y venir. La mairie des 13e et 14e arrondissements possède 6% du parc HLM, elle a des logements dans la Cite des lauriers et quand il y en a un qui se libère, personne ne veut venir. Le problème c’est que le 13e et 14e sont constitués de beaucoup de cités sensibles, quand survient une demande de relogement c’est pour se reloger dans un endroit pareil. Et si c’est pour quitter les Lauriers pour aller à <NAME>, beaucoup renoncent à déménager. Ce n’est pas tellement la qualité des logements qui prime dans cette décision que le niveau de sécurité des Cités »_.
Car les logements sociaux en France répondent schématiquement à la même architecture, celle des grands ensembles. Ces quartiers qui se ressemblent et qui ont parfois les mêmes bailleurs (Habitat 13 ou Habitat Marseille Provence), connaissent les mêmes problèmes d’insécurité. Contactés, les bailleurs sociaux du 13e arrondissement n’ont pas donné suite à nos sollicitations.
# Quand sortir des Cités n’est pas possible, trouver d’autres moyens de vivre dans la Cité
Certains trouvent toutefois le moyen de s'accomoder des difficultés liées à leur environnement. C’était le cas de <NAME>. qui faisait partie du club de foot <NAME> (FCM) depuis 2014. Selon <NAME>, dirigeant du club, _« le foot véhicule les valeurs de dépassement de soi et l’esprit de solidarité »_, et c’est par le foot que les jeunes enfants de Malpassé (quartier dans lequel se trouve la cité des Lauriers) réussissent à ne pas mettre un pied dans le trafic de drogue, tout en restant dans leur cité.
LIRE AUSSI : ["Avoir 15 ans à la Cité des Lauriers », de Delphine Allaire"](https://)
{: .relance}
<file_sep>/_posts/2015-12-11-police-scientifique.markdown
---
layout: post
published: true
categorie: articles
title: Identifier des cendres
cover_image: Cover_police_scientifique.jpg
related:
- « Matchs retour » en cascade
- « Barbecue »
author: <NAME>
---
Parmi les modes opératoires prisés dans les règlements de compte marseillais, figure celui de l’incendie. Popularisé sous le terme de « barbecue », il vise à faire disparaître un maximum de traces sur les lieux du crime. Un défi pour la police scientifique en charge de l’identification des victimes calcinées.
_« C’est toujours pareil, un véhicule incendié est abandonné en rase campagne pour que l’incendie s’éteigne de lui-même et que les cadavres soient complètement dégradés»_, explique Bruno Sera, directeur adjoint du laboratoire de police scientifique de Marseille. Mode opératoire classique à Marseille, utilisé dans plusieurs crimes, à commencer par les règlements de compte. Plus le corps est carbonisé, plus l’identification de la victime s’annonce compliquée.
C’est d’ailleurs l’objectif recherché par les auteurs : contrecarrer le travail de la police scientifique. <NAME> criminologue explique : _« Il y a deux techniques qui sont apparues avec le développement de la police scientifique. L’extincteur qui effacerait les traces ADN et le barbecue qui est la technique la plus directe. Elle élimine un maximum de traces qu’on a laissé sur la victime et permet de retarder l’identification"._
Samedi 29 novembre: une Ford Fiesta incendiée dans le quartier de la Batarelle (13e ardt). Au fond du coffre, un jeune homme brûlé, pieds et poings liés. L’arrivée des pompiers est déterminante pour la suite de l’enquête. Ce soir-là l’alerte est donnée assez tôt, le corps n’est pas entièrement dégradé, comme dans la plupart des règlements de compte. Sur les 20 crimes de cette catégorie recensés par la police judiciaire de Marseille, 2 relèvent du « barbecue ».
Sur les lieux du crime, les Officiers de police judiciaire (OPJ) interviennent pour réaliser les prélèvements aux côtés d’un médecin légiste. L’autopsie est également réalisée dans les 24 à 48h après la découverte du corps. Elle permet d’en apprendre plus sur les causes de la mort.
Les traces digitales restées intactes, les poils ainsi que chaque objet du véhicule ou de la victime qui n'a pas été touché par les flammes, sont relevés, placés sous scellées et envoyés au laboratoire de police de Marseille. La division de l’identification se charge de l’analyse des prélèvements. _« On est une dizaine d’experts en biologie génétique à travailler sur un cas, analyser les empreintes digitales quand elles sont disponible et les traces ADN »,_ explique Bruno Sera.

{: .fullwidth}

{: .fullwidth}
Problème : les corps calcinés rendent difficile l’analyse des empreintes digitales. _« Les mains et le corps sont les premiers membres à être impactés par le feu et sont donc rarement exploitables»_, confirme Bruno Sera. Quand le corps est trop calciné, il est impossible d’extraire de l’ADN cellulaire. Les experts tentent alors l’extraction d’ADN mitochondrial qui nécessite des techniques plus complexes.
# Fichage et coordination

{: .fullwidth}
L’identification peut alors durer longtemps. _«Dans les cas d’urgence, néanmoins, on peut parvenir avec du sang ou un peu de muscle à une empreinte digitale en 48h »,_ explique Bruno Sera. Elles sont alors transmises au Ficher Automatisé des empruntes digitales (FAED).
C'est le procureur qui se charge ensuite de saisir ce fichier pour comparer les analyses du laboratoire de police avec les empreintes déjà enregistrées.
Lorsque la personne n’est pas connue des services de police, le laboratoire peut procéder à des comparaisons sur les prélèvements génétiques d’antécédents, des proches potentiels de la victime. _«Pour cela, il faut avoir des informations sur l’environnement de la victime, regarder du côté des déclarations de personnes disparues»,_ explique Bruno Sera.
Dans les cas extrêmes, où le degré de calcination du corps est trop élevé pour réaliser une identification, on procède à une analyse dentaire. Dans les cas de règlements de compte, néanmoins, cette méthode est très rarement utilisée. L’identification est toujours réalisée, même si elle est retardée. Un délai dont l’impact psychologique sur les victimes et leurs proches profite aux criminels.
<file_sep>/_posts/2015-12-11-PLANDAOU.markdown
---
layout: post
published: true
categorie: articles
title: "Mourir à 18 ans "
cover_image: Cover_Mourir_a_18_ans.jpg
related:
- "Avoir 15 ans, cité des Lauriers"
- Quitter les quartiers Nord
author: <NAME>
twitter: "https://twitter.com/mahauldbecker"
---
Il avait 18 ans. Il est mort par balles le 12 octobre dernier au bas d’une cité sensible du plan d’Aou, dans le 15ème arrondissement de Marseille.
Il n’a eu droit ni à une marche, ni à un hommage. “Il”, c’est d'ailleurs le seul moyen de désigner ce petit trafiquant, au parcours rendu “anonyme” par l'affaire judiciaire que sa mort a déclenchée.
Son identité n’a pas été dévoilée au grand public et les habitants se refusent à en parler. Cet enfant des quartiers Nord est pourtant emblématique d’une génération marginale, éloignée des parcours scolaires classiques et cible d'aînés déjà impliqués dans le trafic de drogue.
<iframe src="{{site.baseurl}}/dataviz/plandaou/index.html" frameborder="0" width="100%" height="2500px"></iframe>
<NAME>, qui s'est rendue surles lieux après les faits, raconte sur France Bleu Provence : _“ce qui m'a le plus surpris : le corps de la victime n'a pas eu le temps de refroidir et les jeunes étaient déjà revenus sur place pour continuer leur trafic.”_ La sénatrice et maire du 15ème et 16ème arrondissements ajoute : _“c'est comme si cette tragédie ne les atteignait pas.”_
Mourir jeune et dans l’indifférence, c’est ce qui guette ces trafiquants de première ligne, prêts à prendre tous les risques pour survivre, se faire un nom, sans mesurer les risques encourus.
>Le corps de la victime n'a pas eu le temps de refroidir et les jeunes étaient déjà revenus sur place pour continuer leur trafic.
<NAME>
{: .credit}
# Parcours d’un chaos
Dans le 15ème arrondissement de Marseille, les collèges publics ne dépassent pas les [75% de réussite au brevet](http://www.lemonde.fr/brevet-college/article/2015/07/13/brevet-des-colleges-le-taux-de-reussite-progresse-a-86-3_4681536_4401482.html), quand la moyenne nationale est de plus de 86%. <NAME>, du Collectif des quartiers populaires explique [au micro d’Europe 1](http://www.europe1.fr/mediacenter/emissions/l-interview-verite-thomas-sotto/sons/salim-grabsi-notre-environnement-se-deteriore-depuis-quinze-ans-2373347) que les jeunes des quartiers Nord de Marseille représentent 50% des collégiens de la ville mais “plus que 25% des lycéens”.
Ces chiffres en disent long sur les difficultés de ces quartiers, et plus généralement, du département. Le redécoupage de cette zone en grande métropole, qui deviendra effective en janvier 2016 n’est pas de bonne augure [selon les derniers chiffres de l’Insee](http://www.lesechos.fr/politique-societe/regions/021363170267-la-future-metropole-aix-marseille-provence-cumule-les-handicaps-selon-linsee-1160384.php). Fortement touchée par le chômage (12,5% au premier trimestre 2015 pour Marseille-Aubagne), les difficultés socio-économiques de la région expliquent en partie le développement de la violence dans ces “quartiers”. Ainsi, le passage à la métropole pourrait agraver la situation dans ces contextes.
<script id="infogram_0_marseille__les_jeunes_quittent_tot_le_cadre_scolaire" title="Marseille : les jeunes quittent tôt le cadre scolaire" src="//e.infogr.am/js/embed.js?Cg4" type="text/javascript"></script><div style="width:100%;padding:8px 0;font-family:Arial;font-size:13px;line-height:15px;text-align:center;"><a target="_blank" href="https://infogr.am/marseille__les_jeunes_quittent_tot_le_cadre_scolaire" style="color:#989898;text-decoration:none;">Marseille : les jeunes quittent tôt le cadre scolaire</a><br><a style="color:#989898;text-decoration:none;" href="http://charts.infogr.am/bar-chart?utm_source=embed_bottom&utm_medium=seo&utm_campaign=bar_chart" target="_blank">Create bar charts</a></div>
{: .fullwidth}
_“Mon fils, il est sage, mais trouvez-lui du travail”,_ résume une habitante du plan d’Aou, interrogée par téléphone. L’échec scolaire, la difficulté à trouver un emploi et le sentiment d’exclusion sont les facteurs qui incitent souvent ces jeunes à chercher de la reconnaissance ailleurs. C’est à ce stade qu’ils sont _“récupérés”_ par leurs aînés, toujours à la recherche de petites mains pour mieux tenir les cités explique <NAME> dans _Libération_ [Guetteur au départ](http://www.liberation.fr/france/2015/09/21/trafic-de-drogue-les-guetteurs-auxiliaires-indispensables_1387538) et puis très vite petit revendeur, l’appât du gain comme de la renommée sont les tickets d’entrée dans ce cercle vicieux de la délinquance.
Passer ses journées à attendre à l’entrée d’une cité pour parfois des sommes modiques (entre 40 et 100 euros pour 8 à 10 heures de travail, [selon Libération](http://www.liberation.fr/france/2015/09/21/trafic-de-drogue-les-guetteurs-auxiliaires-indispensables_1387538)) n’est pas le rêve de tous les adolescents. Mais, <NAME>, spécialiste des phénomènes de bande et de la ségrégation urbaine explique dans un ouvrage sur la question que [les motivations de ces jeunes sont nombreuses](https://www.cairn.info/revue-cultures-et-conflits-2014-1-page-35.htm) : _“attachement au quartier et allégeance à son pôle déviant, proximité avec les acteurs de la délinquance, rejet intense de la police et de l’ordre social qu’elle représente”._
Deux semaines après le décès de ce jeune homme, deux autres adolescents, de 15 ans cette fois, ont trouvé la mort au cours d’une fusillade dans la région marseillaise où les règlements de compte ont déjà fait, en 2015, au moins un mort [de plus qu’en 2014](http://www.laprovence.com/actu/faits-divers-en-direct/3662499/reglements-de-comptes-plus-de-tues-quen-2014.html).
<file_sep>/_posts/2015-12-11-methode-globale.md
---
layout: post
published: true
title: Plus de police ≠ moins de crimes
categorie: articles
cover_image: Cover_approche_globale.jpg
related:
- "En plein jour, en pleine ville"
- Un effet pervers du démantèlement des trafics
author: <NAME>
---
Malgré des interventions policières régulières et la mise en place de nouvelles actions, les règlements de compte connaissent peu de trève à Marseille. Aussi des questions émergent-elles sur _«l’approche globale»_ mise en oeuvre par la police pour lutter contre le néo-banditisme de cité.
Plus de vingt interpellations, 30 kilos de résine de cannabis et des centaines de milliers d'euros saisis. Le 18 mai dernier, près de 300 policiers, notamment des hommes du Raid et des CRS, investissaient la cité des Lauriers, dans le 13e arrondissement de Marseille. Préparée depuis _«près d'un an»,_ selon le ministre de l'Intérieur, <NAME>, cette vaste opération s'inscrit dans une logique plus large : faire revenir les forces de l'ordre dans les cités marseillaises pour lutter contre les trafics qui s'y déroulent. Pourtant, quelques mois après, un nouveau règlement de compte sanglant, vraisemblablement sur fond de trafic de drogue, met une nouvelle fois les Lauriers à la une de l'actualité. Trois jeunes, dont deux mineurs sont abattus le 25 octobre. La nouvelle méthode prônée par le ministère de l'Intérieur, baptisée « approche globale » semble battue en brèche.
# Une nouvelle méthode _«saluée par tous»_
Sur le fond, le préfet de police des Bouches-du-Rhône, <NAME> met en avant une logique de _«coordination»_ entre les différents services de police, notamment _«pour échanger du renseignement»_, lors d’un entretien exclusif. Sur le terrain, cette méthode globale se traduit par _«le déploiement de CRS dans les quartiers, pour sécuriser l'intervention des autres acteurs»_.
La particularité de l’approche globale réside dans la durée et la récurrence de la présence policière, qui peut durer _«15 jours, trois semaines, voire un mois»,_ rappelle-t-il, estimant qu'elle est _«saluée par tous»._
Les habitants, concernés au plan premier, semblent plus ou moins satisfaits du déroulement de ces opérations : selon un rapport réalisé à la demande de la préfecture de police portant sur l’évaluation de la méthode globale, 76% des personnes interrogées dans la cité de La Sauvagère estiment que la présence policière a rendu _«la vie plus agréable»_. Au cour de la même période, près de 50% des personnes interrogées à la cité du Clos des Roses considèrent en revanche que cette présence n’a eu _"aucun effet"_. Malgré ces perceptions contrastées, le déploiement policier a permis d’entamer des travaux de rénovation urbaines dans des cités au sein desquelles _«les dealers s’étaient appropriés les territoires à tel point qu’il y avait des contrôles à l’entrée des cités»_, précise une source policière.
L'objectif de cette nouvelle approche est ambitieux. Il s'agit, pour <NAME>, chercheuse en sociologie au CNRS et co-auteure d'un rapport sur l'évaluation de la méthode globale, de _«dépasser les méthodes coup de poing qui ne s'inscrivent pas dans la durée»_, en assurant une présence régulière des forces de l'ordre dans les quartiers les plus sensibles. _«On fait en sorte que la population voit du bleu»_ explique un syndicaliste policier : _«l'enjeu était de replacer des policiers en uniforme dans les cités»_. Mais ce volet répressif est doublé d'un volet social. _«L'Etat participe à l'amélioration du cadre de vie des habitants, notamment via la mise en place d'un préfet à l'égalité des chances»_, pointe <NAME>aria. Cette intervention vient répondre à un sentiment d’abandon de la part de l’Etat que l'on observe dans les quartiers sensibles depuis _«vingt, voire trente ans»._ <NAME>, ancien conseiller du préfet de police des Bouches-du-Rhône a participé à la mise en place de l’approche globale. _«On s’est rendu compte que toutes les administrations, la police, faisaient en fonction de leur propre logique. On était dans une perspective de saupoudrage»,_ précise-t-il. Ici, l’objectif était _«de mener des opérations policières, tout en permettant aux services publics de se redéployer dans les quartiers sensibles»,_ à l'image de la rénovation urbaine.
LIRE AUSSI : ["Sortir des quartiers Nord de Marseille, une nécessité bien difficile : le cas de <NAME>."](https://)
{: .relance}
L'infographie ci-dessous, décrit les différentes phases de présence des CRS dans la cité de La Sauvagère entre mars 2013 et septembre 2014.
Durant la première phase, correspondant au mois de mars 2013, la présence des CRS était quasiment continue, avec des effectifs compris entre 30 et 60 hommes. Cette démonstration de force a permis une _«asphyxie temporaire du trafic»_, selon un rapport publié a posteriori.

{: .fullwidth}
La seconde phase, plus étalée dans le temps, a consisté en des retours ponctuels entre juin 2013 et juillet 2014. Ces interventions, d'une trentaine d'hommes, plus courtes et moins régulières ont permis d'assurer une présence et une visibilité aux forces de l'ordre.

{: .fullwidth}
Enfin, la dernière phase, à partir de juillet 2014, a donné lieu à une absence des CRS durant trois mois, jusqu'en septembre 2014. Les forces de police ont toutefois fait leur retour dès l'automne 2014, avec des effectifs quasiment équivalents à ceux du début de l'intervention à la Sauvagère.

{: .fullwidth}
La préfecture de police indique que cette présence s'accompagne d'interpellations régulières, réalisée tant durant des opérations qu'à l'occasion de contrôles.
Source : <NAME>., <NAME>., <NAME>.O., Evaluation de la "méthode globale" (Zones de sécurité prioritaires), Les Rapports de Recherche de l'ORDCS, n°6.
{: .credit}
# Un trafic enraciné
_«Il y a une opération policière par jour dans les 13e et 14e arrondissement»_ constate un élu responsable de la sécurité dans les quartiers Nord pour qui _«les opérations de police sont efficaces »._ Et de poursuivre : _«Quand une opération est menée dans une cité, au bout d'une demi-heure, les dealers sont ailleurs. Ils ont des plans B, voire C»_. Le déplacement des trafics, c'est précisément ce contre quoi le préfet de Police essaie de lutter. _«Les CRS essaient de rayonner sur plusieurs cités»_. Mais cela n'empêche pas les bandes rivales de se livrer à des règlements de compte, sur fond de guerre entre les territoires. Pour l'année 2015, la préfecture de police des Bouches-du-Rhône en dénombre 12. Paradoxalement, ce n'est pas forcément le signe que l’approche globale ne fonctionne pas.
LIRE AUSSI : ["Quand le démantèlement des réseaux de trafiquants tue"](https://)
{: .relance}
_«Quand on fait tomber des réseaux on les affaiblit»_, explique <NAME>, qui estime que son action peut, à court terme _«favoriser les règlements de compte»_. En clair, il faudra donc attendre encore un peu avant de pouvoir constater les effets tangibles de la méthode globale sur ces crimes.
<file_sep>/_posts/2015-12-11-demantelement-des-reseaux.markdown
---
published: true
layout: post
title: Un effet pervers du démantèlement des trafics
categories: articles
cover_image: Cover_demantelement_reseaux.jpg
related:
- Plus de police ≠ moins de crimes
- Le choix des mots
author: <NAME>
---
<NAME>. a été assassiné le 19 juin, au pied d'un immeuble des quartiers Nord. Sa mort intervient un mois après le démantèlement d'un trafic de stupéfiants dans une cité voisine qui a entraîné une guerre de territoires dont il a pu être la victime, selon une source policière.

{: .fullwidth .image}
Avenue Saint-Paul, Cité des Bleuets, Marseille (Google)
{: .credit}
Sous un porche de la cité des Bleuets (13ème ardt), <NAME>. reçoit une première balle. Il est environ 23H00. Mais en ce 19 juin, deuxième jour de ramadan, des enfants jouent encore dans le petit square, au bas des tours.
D’après _La Provence_, le tireur est seul et cagoulé. Abdallah, blessé, reçoit deux autres balles avant d’atteindre la porte d’un appartement. Il se réfugie chez un voisin, qui l'emmène à l’hôpital militaire Alphonse Laveran. Mais il ne survit pas à ses blessures. Il meurt à 1H00 du matin.
A 28 ans, Abdallah était connu des services de police pour des affaires de stupéfiants, sans être un _“gros profil”_ d’après l’AFP. "L'enquête est en cours", indique simplement une source policière contactée par téléphone. Une autre source policière, citée par _Le Figaro_ avance une hypothèse : _“il y a de fortes probabilités mais pas de certitude sur le mobile. Un gros réseau de trafic de stupéfiants avait été démantelé dans ce secteur il y a un mois”._
Le 18 mai, en effet, près de 300 policiers avait opéré un vaste coup de filet permettant d’interpeller plus d'une vingtaine de personnes dans la cité des Lauriers, située à 900 mètres de la cité des Bleuets.

{: .fullwidth}
Si la mort d’<NAME>. a un lien avec ce démantèlement, ce ne serait pas une première. L’opération policière a également précédé un règlement de compte survenu le 25 octobre dans la cité des Lauriers. <NAME>, préfet de police des Bouches-du-Rhône, expliquait alors au micro de RTL que le quartier, déstabilisé, était la cible d’une guerre de territoire entre réseaux adverses. _"Il y avait des tentatives de reprises et on peut penser que le règlement de compte [du 25 octobre] est sans doute lié à cette tentative."_
Selon lui, la mort de <NAME>. 15 ans, <NAME>. 15 ans et <NAME>. 23 ans peut être la conséquence du démantèlement du trafic de la cité des Lauriers.
Même scénario, en juillet dernier, après le démantèlement du réseau du plan d’Aou, qui, [d’après 20Minutes](http://www.20minutes.fr/marseille/1647795-20150707-marseille-nouvelle-approche-lutter-contre-trafics-stups), avait permis de saisir 30 kilos de cannabis et d’interpeller quatre trafiquants. Un règlement de compte est survenu trois mois plus tard, le 12 octobre 2015, dans la même cité.
> Quand un réseau est frappé par un démantèlement, il est affaibli.
**<NAME>** - spécialiste de la criminalité et du trafic de drogue.
{: .credit}
D'après <NAME>, le démantèlement des trafics de drogues déstabilise l’organisation du trafic. Le réseau a alors deux manières de se reconstruire. _"Il se réorganise soit en interne, avec les anciens lieutenants qui sont en liberté et qui vont reprendre la main sur le territoire démantelé. Soit ce sont des réseaux concurrents qui vont vouloir mettre la main sur tel ou tel point de deal, car ça représente une grande valeur économique”._ Et pour s’emparer de ce qui reste du réseau, la concurrence est prête à tout. _“Si le réseau est suffisamment affaibli pour faire allégeance à un autre réseau, la concurrence a forcément recours à la violence. Il va y avoir une pression physique, une démonstration de force d’un réseau sur un autre. Et donc les règlements de compte, ça peut arriver.”_
Et les forces de police ont conscience de ces effets de bord.
> Malheureusement oui, l’action qu’on mène favorise les règlements de compte, à court terme.
**<NAME>** - préfet de police des Bouches-du-Rhône
{: .credit}
Les règlements de compte surviennent en fait souvent quelques semaines ou quelques mois après le démantèlement du réseau. Un court délai qui permet de les identifier comme une conséquence du démantèlement.
Mais la déconstruction des réseaux a d’autres conséquences, moins visibles, à plus long terme. Quand les trafiquants incarcérés sont remis en liberté, une nouvelle guerre de territoire survient.
_“Quand ils sortent de prison, soit ils sont intégrés au réseau qui a survécu, soit ils vont vouloir récupérer leur place d’antan. Et ça peut aller au carton. Une nouvelle fois, il peut y avoir des règlements de compte”,_ confirme <NAME>.
Les exemples sont nombreux. En avril 2014, deux hommes à peine sortis de la prison de Lyunes, <NAME>. et <NAME>., sont abattus dans leur voiture, sur l’autoroute. En mars 2013 déjà, un détenu est exécuté cinq minutes après avoir été libéré de la prison des Baumettes.

{: .fullwidth}
Si cette chronologie n’est pas exhaustive, elle permet de mettre en évidence l’apparition de règlements de compte après les démantèlements. Pour le cas d’<NAME>., l’enquête doit encore confirmer que son assassinat a bien un lien avec le démantèlement du réseau des Lauriers, un mois plus tôt.
Face aux conséquences mortelles des démantèlements, la police a une responsabilité, selon <NAME>. _“Le problème c’est qu’en France la police est réactive. Elle commence une enquête sur les faits, après un flingage.”_ Pour le spécialiste, il faudrait une police pro-active, c’est-à-dire capable d’identifier les acteurs avant qu’il n’y ait de règlements de compte.
_“Mais ça commence à changer.”_
LIRE AUSSI : ["Marseille, l'approche globale à l'épreuve des faits"](https://)
{: .relance}
<file_sep>/img/2015-12-11-Carte-ZSP-Marseille.md
<file_sep>/_posts/2015-12-11-reglement-de-comte-en-plein-quartier-beaumont.md
---
layout: post
published: true
categorie: articles
title: "En plein jour, en pleine ville"
cover_image: Cover_quartier_beaumont.jpg
related:
- Vieille école
- Le choix des mots
author: <NAME>
---
Au beau milieu de l'été, un crime aux allures de règlement de comptes a été commis à Beaumont, un quartier calme du 12ème arrondissement de Marseille. Habitants et élus sont partagés entre confiance et résignation.
Les clients font la queue devant la boulangerie. La petite terrasse aux murs jaunis du « Rotonde Bar » est à moitié remplie et le soleil est déjà haut dans le ciel sans nuages de Marseille, raconte Sylvie, qui a assisté à la scène et accepté de la raconter par téléphone, sous couvert de l'anonymat.
Ce devait être une journée splendide. Vers 9 heures, jeudi 6 août 2015, deux hommes à moto s’arrêtent près du bar, avenue du 24 avril 1915, une zone pavillonnaire de l'est marseillais. L’un attend reste sur sa moto, l’autre descend. Il porte une perruque et fait des allers et retours entre le bar et la terrasse.

{: .fullwidth .image}
Google
{: .credit}
Un jeune homme qui le voit passer à cinq reprises le salue deux fois. Aucune réponse, rapporte la [Provence](http://www.laprovence.com/article/actualites/3525845/marseille-un-homme-abattu-en-pleinerue-dans-un-guet-apens.html). Entre-temps, arrive un homme d’une cinquantaine d’années portant une chemise bleu-gris et un jean clair, selon des photos de la scène de crime. Lui aussi est à moto. Il entre dans le bar sans même retirer son casque noir.
C’est <NAME>., fiché au grand banditisme. Il est connu depuis 30 ans pour des vols de voiture, un vol aggravé et pour avoir participé au fameux [braquage d’un fourgon blindé Brink’s à Gentilly](http://www.leparisien.fr/faits-divers/deux-fourgons-de-la-brink-s-attaques-a-l-explosif-27-12-2000-2001852979.php) le 26 décembre 2000 avec une dizaine de malfaiteurs.

{: .fullwidth .image}
Le « Rotonde Bar », avenue du 24 avril 1915 à Marseille. Google Street View
{: .credit}
Il est également soupçonné d’avoir fait partie du commando qui a permis l'évasion d'<NAME> -- une figure du grand banditisme condamné pour braquage et meurtre, suspecté de trafic de drogue -- de la prison de Fresnes en 2003. <NAME>. est en liberté depuis 2012.
Il est presque 9 h 40, lorsque l'homme, toujours casqué, ressort du bar et se dirige vers la petite boulangerie située juste en face. À peine commence-t-il à traverser que l’homme à la perruque sort un calibre 9 mm. Les habitants croient à un gros pétard. Il vient pourtant d’abattre à bout portant <NAME>. d’une balle dans le dos. Calmement, l'assassin s’approche de sa victime qui vient de s’effondrer sur la route.
Nathalie, gérante d’un magasin voisin, raconte à l’AFP : _“D'un coup, j'ai réalisé que la personne était en train de se faire tuer”_. L’homme à la perruque a tiré huit balles, dont cinq dans la tête. Il s'enfuit ensuite avec son complice à moto. On ignore encore l’identité des suspects, indique une source policière. Mais comment les habitants réagissent-ils à ce crime commis en plein jour, en pleine ville ?
>D'un coup, j'ai réalisé que la personne était en train de se faire tuer.
**Nathalie** - responsable d’un magasin voisin
{: .credit}
Une cellule psychologique a été mise en place après le meurtre pour venir en aide aux témoins de la scène. Mais les riverains que nous avons contactés ne semblent pas inquiets pour leur sécurité. _« C’est un quartier très calme, il n’y a que deux morts par ans »_, explique Valérie, une habitante de l’avenue adjacente de la Figone.

{: .fullwidth .image}
Au premier plan le « Rotonde Bar » et la boulangerie à l’arrière plan. / Google Street View
{: .credit}
Didier, qui habite un immeuble tout proche de la scène du crime, paraît résigné : _« Ce sont des actes isolés. Vous savez, depuis que je suis en âge de raison, il y a toujours eu une vingtaine de morts par arme à feu dans la région »_. Pour <NAME>, adjoint délégué au 12ème arrondissement et chargé de la sécurité, il n’y pas de mesure particulière à prendre après de tels événements : _« Je ne vois pas pourquoi on demanderait un périmètre de sécurité quand des voyous se tuent entre eux »_.
>C’est un quartier très calme, il n’y a que deux morts par an.
**Valérie** - habitante à côté du lieu du crime
{: .credit}
Les riverains ne semblent pas craindre que les règlements de compte s’exportent des quartiers Nord vers des zones rarement concernées par ce genre d’affaires. La délinquance à Marseille est en baisse, comme le souligne le directeur départemental de la sécurité publique, Pierre-<NAME>l. Contacté par téléphone, il fait savoir que les moyens de surveillance sont revus régulièrement en proportion de la criminalité constatée.
<NAME> confie que de nombreux habitants l'ont questionné sur la sécurité dans le quartier, dit-il. Impossible de faire des miracles, leur a-t-il répondu : _« Il peut toujours y avoir des dommages collatéraux, et ça m’interpelle. Mais on est impuissants par rapport à cela »_.
<file_sep>/_posts/2015-12-11-Ne-pas-parler-trop-vite-de-règlement-de-compte.md
---
published: true
title: Le choix des mots
layout: post
categorie: articles
cover_image: Cover_Ne_pas_parler_trop_vite.jpg
related:
- "Avoir 15 ans, cité des Lauriers"
- En famille
author: "<NAME> & <NAME>"
---
Les véhicules de gendarmerie entourent une voiture stationnée près du rond point du Canet, en périphérie de Meyreuil, à une trentaine de kilomètres de Marseille. Dimanche 1er novembre, vers 18h, Jean-<NAME>. a été la cible d’un ou plusieurs coups de feu. L’homme _“âgé d’une trentaine d’années”_ a été retrouvé sur le siège conducteur, le _“visage en partie défiguré”,_ a déclaré à [La Provence](http://www.laprovence.com/article/actualites/3651539/meyreuil-assassine-sur-fond-de-vendetta.html) <NAME>, Procureur d’Aix.
> “On est à côté de Gardane, on est pas loin de Marseille, des cadavres dans des voitures on en a trouvé...C’est tombé là comme ça aurait pu tomber ailleurs ”
<NAME>, adjoint à la mairie de Meyreuil, chargé de la sécurité.
{: .credit}
_“Assassinat sur fond de vendetta”, “match retour”,_ la presse locale évoque, dès le surlendemain, l’hypothèse d’un règlement de comptes. Mais est-ce aussi évident ? Comme dans bien des cas d’homicides constatés dans la région marseillaise, et particulièrement à la campagne, les premières suppositions ne résistent pas à l’épreuve des investigations.
D’après _La Provence_, la victime était recherchée dans l’enquête sur la mort de <NAME>. Le corps de cet homme de 54 ans avait été retrouvé, le 23 septembre 2015, sur le siège passager d’une voiture calcinée à Pertuis, dans le département du Vaucluse, à 35 kilomètres de Meyreuil.
# Un règlement de comptes ?
_“Une mort plus qu’étrange”,_ commente <NAME>, avocat de la famille et conseiller d’opposition (PS) de la ville de Pertuis. <NAME>., _“le jeune maçon”_ et le _“leader de la communauté gitane”,_ installée le long de la Durance, _“étaient amis. Ils étaient proches et travaillaient ensemble”._ _“On peut imaginer que ceux qui ont tué <NAME>. étaient impliqués dans le meurtre de <NAME>.”,_ avance l'avocat. Pour l’heure, le lien entre les deux homicides n’a pas été confirmé : <NAME>, procureur d’Avignon, ne s’est pas dessaisi du dossier <NAME>. au profit du parquet d’Aix-en-Provence, chargée de l’enquête sur la mort de Rougier.
Les modes opératoires portent également à confusion. D’un côté, ce qui a tout l’air, dans le jargon marseillais, d’un “barbecue”. De l’autre, l’arme utilisée - un revolver ou un fusil de chasse - ne correspond pas au scénario classique du règlement de compte. <NAME>, spécialiste de la criminalité, rejette a priori la possibilité que des tensions communautaires aient pu jouer : _“Il y a des rivalités, mais plutôt entre clans et réseaux criminels qu’entre communautés.”_ A ce stade, les circonstances de leur mort restent troubles, et les gendarmes de la section de recherches de Marseille, responsable de toute affaire criminelle au niveau régional, refusent de communiquer sur l'enquête.

{: .fullwidth .image}
Homicides et règlements en dehors de Marseille et sa périphérie, de janvier 2014 à novembre 2015
{: .note}
# Meyreuil : pas un cas isolé
Cet empressement à voir un règlement de comptes derrière chaque homicide survenu en dehors de la périphérie de Marseille, a pu déjà être constaté dans de précédentes affaires. En juillet 2014, dans le centre ville de Tarascon, une ville réputée calme, située à une centaine de kilomètres de la citée phocéenne, [<NAME>. est abattu en pleine rue au fusil de chasse](https://reglementsdecomptes.wordpress.com/2015/04/30/abdelkarim-k-et-si-le-reglement-de-comptes-netait-quune-affaire-privee/). En pleine ‘série noire’ - 4 règlements de compte en un mois - la presse locale pense qu’il s’agit d’un épisode supplémentaire. En fait pour la soeur de la victime, il s’agit plutôt d’une affaire privée, une dispute qui a dégénérée.
<NAME> : [“Quand le trafic dépasse les frontières de Marseille”](https://reglementsdecomptes.wordpress.com/2015/05/12/quand-le-trafic-depasse-les-frontieres-de-marseille/)
{: .relance}
La criminalité particulièrement forte de la région, qui ne se limite pas à Marseille et les “quartiers nord”, tisse une toile fond favorable à ce genre d’interprétation hâtive. En 2015, il y a eu 20 règlements de compte dans le département des Bouches-du-Rhône, dont 12 à Marseille, a indiqué la préfecture de police. La Ciotat, Port de Bouc, Aubagne, Gignac-la-Nerthe, etc. sur les 32 cas de règlements de comptes que nous avons répertoriés entre le 1er janvier 2014 et le 30 novembre 2015, huit ont eu lieu dans un périmètre situé au delà d’une vingtaine de kilomètres de la cité phocéenne (Voir Carte).
<file_sep>/_drafts/2015-12-11-vendetta-appat-gain.markdown
---
layout: post
published: true
categorie: articles
title: "L'argent ou l'honneur ?"
cover_image: Cover_Vendetta.jpg
related:
- La loi du silence
- Quitter les quartiers Nord
author: "<NAME>"
---
<NAME>., 27 ans, <NAME>., 29 ans, morts par balles à bord de leur voiture à Saint Jérôme (13 ardt) en 2012. <NAME>., 15 ans, <NAME>., 23 ans, et <NAME>., 15 ans, tués au pistolet automatique devant leur domicile, dans la cité voisine des Lauriers (13 ardt), en octobre 2015. <NAME>., 31 ans et <NAME>., 34 ans, abattus dans une embuscade sous le tunnel du Prado-Carénage, en novembre 2015.
Trois affaires apparemment isolées les unes des autres. Et pourtant, liées par les lieux, les acteurs et les véhicules employés. Les victimes se connaissaient également. Et dans le cas de Nasseri et <NAME>., elles étaient membres d'une même même famille.
Selon une source policière, _« des éléments rapprochent [Mohamed] M. à la cité des Lauriers. »_ Les deux faits-divers pourraient ainsi être liés par une vengeance : celle d'un homme, <NAME>., pour la mort de son frère <NAME>. tombé à Saint-Jérôme. Selon cette hypothèse, <NAME>. se serait rendu aux Lauriers, cité des meurtriers présumés de son frère, le jour de la fusillade qui a provoqué la mort de trois jeunes hommes, puis aurait été abattu, en représailles à ses crimes présumés, à la sortie du tunnel du tunnel <NAME>.
Si les règlements de comptes ont d'abord pour mobile l'appartenance à un réseau de trafic de drogues -- et les luttes d'influence qu'il génère dans les quartiers Nord de Marseille -- les liens familiaux et le code de l’honneur qui s'y applique, sont également déterminants. _"Il y a une double dimension business et sang",_ résume <NAME>, criminologue : _"les deux se percutent quand il s’agit de venger l’honneur de la famille"._
Dans un environnement où les affaires se règlent souvent en famille, le code de l'honneur complexifie les relations interpersonnelles en superposant aux questions strictement financières une dimension affective, plus irrationnelle.
# Le rap comme vecteur de la notion d’honneur
Dans la culture populaire, cette idée que la famille prime sur tout, qu'il faut protéger les siens et les venger, résonne avec les paroles des chanteurs de rap et notamment Lacrim, un artiste basé à Marseille: _“Hein mon gros, mon gros, mais pourquoi tu fais du biff [de l’argent]? Pour ta famille ou pour tes salopes?”_

{: .fullwidth}
Dans les quartiers Nord, la famille peut aussi s’entendre au sens large et désigner, par extension, les partenaires de réseaux. Un code de l'honneur similaire s'applique alors. _“On est dans des équipes constituées avec des liens forts créés à l'occasion des trafics, des séjours en prison. Quand vous avez un membre de l'équipe qui se fait tuer, on a envie de le venger”,_ explique une source policière.
Selon cette même source cependant, il ne faut pas avoir une conception trop chevaleresque de ces règles de fonctionnement : _“Oui il y a un code de l'honneur qui, dans le banditisme, peut exister, c'est assez noble. Mais dans les narco-trafic, les types n'ont aucune noblesse. Il y a un degré de violence et une disproportion entre les choses reprochées et ce qui arrive aux victimes qui n'a rien d'un code de l'honneur.”_

{: .fullwidth .image}
Mos Def - Black on Both Sides (1999)
{: .credit}
À l’honneur de la famille s’ajoute l’honneur personnel, indispensable dans une économie où chaque preuve de faiblesses pousse à la violence des adversaires toujours avides d'une plus grande part du trafic. Cette perpétuelle quête de légitimité, et d'autorité, le sociologue <NAME> l’appelle le capital guerrier, tandis ce que les anglo-saxons parlent de _"street credibility"._
La culture hip-hop anglo-saxonne regorge elle aussi de références à ce code de l’honneur. L’album Black on Both Sides de Mos Def (1999), en est un exemple. _“Je suis le code de l’honneur comme le ferait n’importe quel vrai homme. Je ne manque jamais de respect aux femme car j’aime ma mère”,_ rappe l’Américain de Boston dans la chanson “Know That”.
Le français Rhoff avait lui aussi largement traité le thème de l’honneur dans son album Le code de l’horreur (2008). Plus pessimiste, il regrette l’absence d’honneur de certains caïds de la région parisienne: _“où sont les hommes d’honneur, à la Jack Mess? Plus de parole, ni loyauté, les balances tiennent le business“._

{: .fullwidth .image}
Rhoff - Le code de l'horreur (2008)
{: .credit}
Pour les rappeurs, qui ont largement encouragé la diffusion d'une conception romanesque voire romantique, du code de l'honneur, celui-ci reste donc une valeur. Mais sur le terrain, c’est la quête plus prosaïque du gain matériel qui fait la loi. Et le réel moteur des règlements de comptes.
<file_sep>/README.md
# Projet Règlements de comptes
[](https://travis-ci.org/reglementsdecomptes/reglementsdecomptes.github.io)
<file_sep>/_posts/2015-12-11-match-retour-en-cascade-dans-les-quartiers-nord-de-marseille.markdown
---
layout: post
published: true
title: "\"Matchs retour\""
categorie: articles
cover_image: Cover_Matchs_retour.jpg
related:
- Mourir à 18 ans
- Plus de police ≠ moins de crimes
author: "<NAME>"
---
Il est 16 heures le 14 avril 2014 lorsque <NAME>. se rend chez son avocat. Le jeune homme de 27 ans conduit une voiture de location quand des hommes cagoulés arrivent à sa hauteur, sur l’autoroute A7, quelques mètres avant la sortie Plombières. Ils tirent sur le véhicule de la victime qui s'arrête en pleine voie. <NAME>. -- membre d'un réseau de trafic de drogues basé dans la cité des Flammants (14e ardt) -- tente de s’enfuir à pied mais il est tué de plusieurs balles de kalachnikov.
Le 18 juillet 2014, alors qu’il circule sur son scooter aux abords du rond-point de Sainte Marthe (14e ardt), <NAME>. est renversé par une voiture. Il tombe de son véhicule, tente de prendre la fuite à pied mais n’a pas le temps d’aller très loin. Le jeune homme de 24 ans -- membre d'un réseau de trafic de drogues basé dans la cité Font-Vert (14e ardt, également) -- est tué par une quarantaine de balles de kalachnikov.
Le règlement de compte visant <NAME>. fait écho au meurtre de <NAME>. trois mois plus tôt : même mode opératoire, même arme utilisée et même violence. Rien d’anormal : l’homicide du 18 juillet semble être le “match retour” du règlement de compte du 14 avril.
Autre cas le 13 mars 2013 : <NAME>. et <NAME>., deux jeunes de 18 et 25 ans, sont tués par balles en plein jour, au pied des immeubles de la cité des Bleuets (13e ardt).
Le quartier, pourtant réputé calme, est le théâtre d'un nouveau règlement de compte le 20 juin 2015, lorsque <NAME>., 28 ans, est tué par trois tirs d’une arme de poing de calibre 9mm. Connu des services de police pour des trafics de stupéfiants sans pour autant être un “gros profil”, <NAME>. serait-il lui aussi la victime d’un match retour ? Les enquêteurs, qui ne connaissent pas encore le mobile du crime, ne l'exclut pas, selon une source policière.
# Un guet-apens planifié
L’expression de “match retour” qualifie des homicides qui prennent la forme d'une vengeance destinée à répondre, plus ou moins directement, à un meurtre ayant eu lieu précédemment.
Dans le cas de <NAME>. le “match retour” a eu lieu trois mois après les faits. Mais il s’écoule parfois plus de temps avant que la vengeance ne se manifeste. R<NAME>, reporter Police et Justice au quotidien _La Provence_ rappelle que certains règlements de comptes et les “match retour” qui les suivent s’échelonnent parfois sur plusieurs années.
.jpeg)
{: .fullwidth}
Si un “match retour” est une réponse à un règlement de comptes antérieurs, le mode opératoire n’est pas toujours le même. Un autre journaliste marseillais, bon connaisseur de ces dossiers, qui a souhaité conserver l'anonymat, explique qu'il varie du simple coup de couteau dans la rue à des formes beaucoup plus élaborées et spectaculaires.
Une seule caractéristique les relie : ce sont des guet-apens préparés. Un règlement de compte n’est jamais le fruit du hasard et la victime est toujours placée dans une situation dont elle ne peut pas s’échapper. Sur son scooter puis à pied, <NAME>. n’a aucun moyen d’éviter les tirs de ses agresseurs. De même <NAME>., ciblé sous un porche, sans aucun moyen de locomotion.
Les armes utilisées ne sont pas forcément les mêmes. Ce sont souvent des kalachnikovs car elles sont des armes faciles à manier et demandent très peu d’entretien. Mais les agresseurs peuvent aussi utiliser des armes de poing, comme un calibre 9mm dans le cas de l’homicide d’Abdallah A.
<NAME>, expert en criminologie explique, ajoute dans un entretien téléphonique, que ces “match retour” sont souvent délicats à relier à des affaires précédentes, notamment à cause de la diversité des modes opératoire :
> Tout est bon dans le “match retour”. Il peut adopter une autre forme que l’on appelle le “drive by shooting”: on tire sur un groupe de personnes alors que le véhicule est en déplacement.
**<NAME>** - expert en criminologie
{: .credit}
Dans le cas du “drive by shooting” (qui consiste à tirer sur un groupe de personnes alors que le véhicule est en déplacement) le lien est encore plus difficile à établir car les personnes ne sont pas visées en tant qu’individus mais parce qu’elles représentent le clan rival ou parce qu’elles sont sur le territoire de ce clan, sans lien obligatoire avec celui-ci.
# Un long travail de recherche pour la police
D'après <NAME>, lorsqu’un homicide est commis dans le milieu criminel les policiers essaient d'évaluer rapidement quelles sont les forces en présence et ce qui les relient, afin d’anticiper d'où viendra le coup d’après. Mais les rivalités s’entremêlent, ce qui complique le travail des enquêteurs.
_“C’est un vrai travail de renseignement criminel qui est parfois méprisé. Parfois les équipes des clans changent, parfois des hypothèses sont tirées un peu rapidement car on ne connaît pas les spécificités actuelles du clan”,_ explique <NAME>.
Pour éviter les "matchs retour", la police emploie depuis 2012 une méthode pro-active : les enquêteurs essaient de placer en détention certaines personnes dont ils savent, grâce à leurs indics ou aux écoutes téléphoniques, qu’ils vont commettre un assassinat ou qu’ils pourraient en être très prochainement victime.
> On cible tous les futurs auteurs ou victimes de règlements de compte, on ouvre des enquêtes tous azimuts sur eux, sur tous les sujets
**Source policière**
{: .credit}
Mais ces cibles ou agresseurs finissent un jour par sortir de priso. Et l’échéance du règlement de compte n’en est que repoussée. Car comme le rappelle <NAME> : _“dans ce milieu on a de la mémoire”_
# La portée symbolique des “match retour”
Plus que la philosophie du “tuer pour tuer”, ces “match retour” -- qui tiennent de la vendetta -- ont également une portée symbolique. Il est essentiel pour un clan de réagir lorsqu'un de ses membres est visé car l’absence de réponse serait perçu comme un acte de faiblesse, explique <NAME>.
> L'absence de réponse peut attiser la convoitise d’autres réseaux qui diraient alors qu’ils “n’ont pas les couilles de réagir”.
**<NAME>** - expert en criminologie
{: .credit}
Les modes opératoires sont également un langage. Le “drive by shooting” vise avant tout à fragiliser le clan par le nombre de victimes. Mais il a également pour objectif de marquer les esprits par une attaque perpétrée sur son propre territoire.
La technique du “barbecue” a également une forte portée symbolique. En brûlant le corps de la victime, les auteurs retardent à la fois l’identification et le deuil de la famille, ce qui humilie le clan, particulièrement lorsque celui-ci repose sur les liens de sang. D’après une source policière, c’est _“la technique d’intimidation la plus efficace car elle permet à ses auteurs de dire ‘attention ne jouez pas avec nous sinon vous verrez ce qui va vous arriver’.”_
Les “matchs retour” constituent donc un rapport de force permanent entre clans rivaux, qui leur permet d’imposer leur autorité et d’impressionner. Si le mobile premier est la vengeance, les bandes cherchent avant tout à imposer leur puissance de feu par le nombre de crimes auxquels elles sont en mesure de répondre et le mode opératoire qu’elles choisissent.
<file_sep>/_posts/2015-12-11-Braquages-mecanique-et-petits-santons-plongee-dans-la-vie-du-gangster-Robert-B.md
---
layout: post
title: Vieille école
categories: articles
published: true
cover_image: Cover_Braquages_mecaniques.jpg
related:
- En famille
- Matchs retour en cascade dans les quartiers nords de Marseille
author: <NAME>
---
Le 6 août 2015, [<NAME> est tué par balles](https://reglementsdecomptes.github.io/2015/12/11/reglement-de-comte-en-plein-quartier-beaumont.html) dans une avenue commerçante du 12e arrondissement de Marseille. Ce quinquagénaire n’était pas un inconnu des forces de police. Braqueur notoire, il était sorti de prison en 2012 et semblait préparer son prochain coup. Portrait d’une forte tête de la pègre marseillaise.

{: .fullwidth}
Ses amis le surnommaient le “Petit Robert”. Il n’a pourtant rien d’un enfant de coeur. Fiché pour grand banditisme et surveillé par la police, il faisait partie des grands noms d’un réseau de braqueurs « à l’ancienne », fort d’une carrière de 30 ans dans la délinquance. Un parcours qui s’est achevé un matin du mois d’août dans une artère commerçante du quartier de Beaumont, quand deux individus ont tiré sur lui à huit reprises au calibre 9mm.
Le meurtre a tout d’un règlement de compte. <NAME> évoluait en effet dans le « Milieu » marseillais, parmi ces truands qui sont les héritiers de l’âge d’or du banditisme de la French Connexion. Cette ancienne génération de bandits [se distingue des jeunes trafiquants de drogue des cités du Nord](https://reglementsdecomptes.wordpress.com/2015/05/12/deux-generations-de-trafiquants-dos-a-dos/) de la ville, comme l’explique le criminologue <NAME>, contacté par téléphone : _« Les bandits à l’ancienne avaient plus de temps, une meilleure formation criminelle. Ils étaient moins pressés et moins désireux de gagner du fric rapidement. (…) La société change donc le milieu change aussi. »_
Si les règlements de compte existent aussi chez ces vieux truands, ils sont souvent plus discrets :_« Avant, on flinguait moins spectaculairement car aujourd’hui on utilise plus la kalachnikov que le 9mm, on arrosait pas comme on peut faire avec la kalach »,_ ajoute le spécialiste. A Marseille, ce sont surtout les jeunes qui sont les principales victimes des règlements de compte (voir infographie). Le cas de <NAME> est donc singulier.

{: .fullwidth}
Le quinquagénaire était notamment lié à la “Dream Team”, ce gang de braqueurs qui sévit entre la France et l’Espagne. Il a également un lien trouble avec <NAME>, un bandit célèbre pour s’être évadé de prison à deux reprises. Les enquêteurs soupçonnent fortement <NAME>. d’avoir aidé “Nino” Ferrara à s’échapper de la prison de Fresnes en 2003, selon [_La Provence_](http://www.laprovence.com/article/actualites/3525845/marseille-un-homme-abattu-en-pleinerue-dans-un-guet-apens.html). Les braqueurs <NAME> et et <NAME> semblent également faire partie de ses relations dans le milieu du grand banditisme marseillais, selon [_la Dépèche_](http://www.ladepeche.fr/article/2009/11/06/709382-proces-antonio-ferrara-attaque-fourgon-blinde.html).
## Profession truand, spécialité braquages
>Je ne peux pas être passé sur Paris le 26 décembre 2000, parce que, chez nous, le 26, c’est les santons. C’est aussi important que le 25.
**<NAME>** - Braqueur
{: .credit}
Comme les choses n’arrivent jamais vraiment par hasard, c’est une enfance difficile qui a mené <NAME> sur cette voie. Selon [un compte-rendu d’un procès tenu en 2009 sur le site de l’_Obs_](http://chroniquesjudiciaires.blogs.nouvelobs.com/archive/2009/12/02/proces-ferrara-et-consorts-episode-8.html), il a été placé à l’âge de cinq ans chez une voisine de son père. Celui-ci ne reprendra sa garde qu’en 1977, le jeune Robert a alors 14 ans. Cette cohabitation ne dure guère. Un an plus tard, il décide de vivre chez son frère. Côté études, la vie de Robert est tout aussi instable. Il finit par les interrompre lorsqu’il est exclu de son lycée professionnel pour vol de voiture.
C’est à l’âge de 26 ans, après le suicide de son frère, que <NAME>. entre dans le grand banditisme. Les simples vols de voiture deviennent des vols à main armée et des vols aggravés. <NAME>. aura passé plus de 20 ans en prison. Entre deux incarcérations, ce passionné de moto est mécanicien au noir. Certains soirs, il monte sur scène pour jouer de la batterie dans un groupe de rock.

{: .fullwidth}
<NAME>. a fait des braquages sa spécialité. En 2000, il participe à l’attaque d’un fourgon de la société de transport de fonds Brink's à Gentilly. Dans cette affaire emblématique, environ 6 millions d’euros ont été dérobés par plusieurs membres de la fine fleur du banditisme marseillais. La police finit par retrouver une partie des membres du gang endormis sur des sacs de billets, les armes à la main. Sur le banc des accusés, on retrouve <NAME>, <NAME> et <NAME>, membres de la fameuse « [Dream Team](http://www.liberation.fr/societe/2013/02/13/la-rechute-des-tontons-braqueurs_881610) ». Le charismatique <NAME> et le corse <NAME> sont également présents, et seront acquittés en appel, fautes de preuves suffisantes. <NAME>. aura moins de chance. Son ADN, retrouvé sur les lieux, le trahit. Il tente de se défendre :_« Je ne peux pas être passé sur Paris le 26 décembre 2000, parce que, chez nous, le 26, c’est les santons. C’est aussi important que le 25. »_ Il dit n'avoir commis _« que des cambriolages de bijouteries et jamais des hold-up »,_ selon des propos rapportés par [_Le Parisien_](http://www.leparisien.fr/val-de-marne/l-adn-au-coeur-du-proces-des-braqueurs-14-12-2006-2007591580.php). <NAME> sera condamné à 9 ans de réclusion criminelle.
## L’impossible réinsertion
>On dit toujours que la délinquance, c'est à cause des parents. Mais quand j'ai décidé de faire une connerie, c'est moi qui l'ai décidé !
**<NAME>** - Braqueur
{: .credit}
En 2009, il se retrouve encore devant la cour d’appel de Paris pour [le braquage manqué d’un fourgon blindé à Toulouse](http://www.ladepeche.fr/article/2001/11/24/286186-un-fourgon-blinde-attaque-a-la-kalachnikov.html). Il est de nouveau aux côté de <NAME>, de <NAME> et de <NAME>. Lors du procès, on lui demande quelle a été la période la plus heureuse de sa vie. Il répond :_« Je ne dirai pas l'enfance, car je n'ai pas eu de parents. On dit toujours que la délinquance, c'est à cause des parents. Mais quand j'ai décidé de faire une connerie, c'est moi qui l'ai décidé ! »,_ selon des propos rapportés par la journaliste <NAME>. Condamné en assises à 11 ans, il est finalement acquitté en appel. Libérable en 2011, il sort de prison en 2012.
Lors du procès en appel, l’avocat général a déclaré que pour permettre à <NAME> de se reconstruire et de trouver un travail, il fallait l'innocenter, toujours selon les chroniques judiciaires de <NAME>. Mais il semble bien que <NAME> n’a jamais abandonné ses affaires dans la pègre marseillaise. Il devait participer à un autre braquage de fourgon, qui a été déjoué par la police au début du mois de septembre par [l’appréhension de neuf personnes](http://www.bfmtv.com/societe/annecy-une-attaque-de-fourgon-dejouee-neuf-suspects-deferes-911006.html), selon une informations révélée par _Midi Libre_ et confirmée par <NAME>, procureur de la République à Marseille. Leurs repérages sur la route des fourgons blindés en Haute-Savoie a mis la police sur leur piste.
<iframe src="https://kumu.io/embed/df7e010675ca1f7aa7c49135877766a4" width="100%" height="600" frameborder="0"></iframe>
Le gang a été déstabilisé et retardé dans ses projets par la mort de <NAME>. : _« On ne peut absolument pas vous dire si il a été assassiné par des membres de cette équipe ou des concurrents, c'est trop tôt... Ca a surtout stoppé dans l'élan notre équipe qui s'est un peu égayée dans la nature »,_ [a déclaré <NAME> en conférence de presse](http://www.lamarseillaise.fr/marseille/faits-divers-justice/41401-marseille-un-gang-de-neuf-braqueurs-marseillais-demantele). Les obsèques du bandit auraient donné lieu à une occasion pour la police d’identifier <NAME>, selon _Le Parisien._ Ce braqueur de 52 ans était sur le banc des accusés aux côtés de <NAME> en 2009 lors du procès du braquage de Toulouse, pour lequel il a été inculpé et écopé de douze ans de prison.
La mort de <NAME>. est-elle liée à cette nouvelle activité ? Lorsqu’il a été assassiné le 6 août 2015, <NAME>. résidait dans le centre-ville de Marseille. Il était en liberté depuis trois ans. Selon un des proches de l’enquête qui s’est exprimé auprès de _La Provence,_ _“Les tueurs connaissaient son emploi du temps. Et le fait qu'il n'ait pas enlevé son casque peut laisser penser qu'il n'était pas tranquille »._ Le truand, fan de moto, a quitté ce monde un casque vissé sur la tête.
<file_sep>/_posts/2015-12-11-silence-plan-daou.md
---
layout: post
published: true
categorie: articles
title: La loi du silence
cover_image: Cover_Le_silence.jpg
related:
- « Barbecue »
- Un effet pervers du démantèlement des trafics
author: <NAME>
---
Prolixes lorsqu'il est question de drogue, de chômage ou de déscolarisation des jeunes, les habitants des quartiers Nord de Marseille -- où l'emprise des trafiquants de drogue est forte -- restent silencieux lorsqu'on les interroge sur des meurtres qui s'apparentent à des règlements de compte.

{: .fullwidth .image}
Suite aux opérations policières dans la cité de la Castellane, les trafics se déplacent dans les grands ensembles de la Bricarde mais également dans le quartier résidentiel du Plan d’Aou. - **Google Maps 10/12/2015**
{: .credit}
Aux alentours de onze heures, le 12 octobre, le calme règne dans la rue Jorgi Reboul, dans la cité du plan d’Aou dans le 15e arrondissement. Soudain des balles résonnent : un [jeune homme de dix-huit ans](http://reglementsdecomptes.github.io/2015/12/11/PLANDAOU.html) est abattu.
L'un des projectiles vient se loger dans la nuque. L'autre dans le bras. Puis le silence revient. Nul témoin. Nul hommage. Dans les quartiers Nord, règne une omerta inquiète et solidaire qui freine l'enquête policière, expliquent élus et sociologues.
Sur la chaussée, des traces de sang témoignent pourtant d’un dernier appel au secours. Agonisant, le jeune homme a péniblement atteint la porte la plus proche, celle de l’immeuble au crépi orange, à quelques mètres de là. Un homme a ouvert et appelé les sauveteurs. En vain : marins-pompiers et médecins du Samu ont tenté de ranimer le jeune majeur mais il a succombé à ses blessures, en route vers l’hôpital Nord de Marseille.
Son cri de détresse, comme le rentissement des balles, s’est perdu dans les mémoires. _“Je n’étais pas là quand c’est arrivé”,_ élude une mère de famille qui habite le même immeuble. _"Tout le monde se connaît dans le quartier",_ ajoute un voisin. Mais _"lui, le mort, non jamais entendu parler”._

{: .fullwidth .image}
Le 12 octobre, un jeune homme de 18 ans reçoit une ou deux balles dans la rue Jorgi Reboul et trouve refuge dans l’immeuble voisin. **(Google Maps 10/12/2015)**
{: .credit}
Pour la police, l’affaire -- très localisée -- a tout d'un règlement de comptes. Le jeune homme, né en 1996, avait déjà un casier judiciaire important : vols avec effraction, violences volontaires et affaires de stupéfiants. Un profil tristement banal dans un quartier mis en coupe réglée par les traficants de drogue. Selon une source policière, les enquêteurs seraient sur le point d'apréhender l'auteur du crime dont deux complices présumés ont déjà été interpellés.
A la maison des jeunes, à quelques mètre de la scène du crime, on affirme n’avoir rien entendu. _“Ce n’était pas moi qui assurait la permanence”,_ explique un animateur, sur un ton expéditif. _"D’ailleurs, à partir de 17 ou 18 ans, les jeunes ne viennent plus au centre : ils ont pris leur indépendance”._
Ce silence émeut <NAME> sénatrice et maire PS des 15e et 16e arrondissements de Marseille. _"C'est quand même la mort violente d'un enfant de 18 ans, mais aucun sentiment ne transparaît. Ces jeunes ne sont même pas rentrés chez eux pour se faire oublier. Normalement, il y a de l'émotion ! Mais là, rien.”_ s’indigne-t-elle, au micro de France Bleu Provence.
La loi du silence a progressivement imposé qu'un crime ne produise ni réaction, ni témoignage. Les victimes meurent dans une apprente indifférence. Pour <NAME>, sociologue, chargé de recherche au CNRS (Centre Maurice Halbwachs) que nous avons joint par téléphone, cette omerta date des années 2000, lorsque les caïds du néo-banditisme de cité ont renforcé leur emprise sur les quartiers nord en s’associant à ceux que les policiers désignent comme le “milieu traditionnel”. Selon lui, le principal ressort du silence, c'est la peur : des représailles, de l’escalade de la violence, des “matchs retour” (vengeances) et ... des descentes de police.
Pour <NAME>, chercheur à l’observatoire régional de la délinquance et des contextes sociaux, cette analyse mérite d'être nuancée. Car les enquêtes de police progressent grâce aux témoignages, rares et très discrets, mais non négligeables, souligne-t-il.
Selon <NAME>, dans les quartiers Nord, le silence est également élevé au rang de vertu morale. C'est un comportement relevant à la fois de la fidélité et l’humilité. Dans une stratégie collective de prévention des “flag”, la solidarité s’illustre dans les alertes familiales et le soutien aux proches, expique-t-il. Se crée ainsi un “nous” qui repose davantage sur la ressemblance sociale, la proximité urbaine, les référents symboliques communs, que sur un réseau institutionnalisé, comme pouvait l’être celui des mafias corses et italiennes, ajoute-t-il.
Mais, pour le sociologue, la clé de compréhension du silence est également à chercher dans la structure socio-économique du quartier. Les analyses sociologiques de la pauvreté soulignent l’importance de la résistance présumée des populations qui se considèrent comme dominées par rapport aux forces de police, représentant elle l’ordre social établi. L’insécurité sociale, c’est-à-dire _“l’absence de revenus suffisants à la maîtrise de sa propre existence”,_ encourage une forme de soutien implicite aux délinquants locaux, explique Marwan Mohammed.
Pour <NAME>, l’emprise des trafiquants finit par être acceptée des habitants: ils rendent service, rémunèrent et protègent parfois. Dans un climat de défiance vis-à-vis des institutions centrales -- forces de l’ordre, justice pénale, médias -- et l'intimidation générale, la mort se donne ainsi en silence.
<file_sep>/_posts/2015-12-11-fait-divers-querelle-politique.markdown
---
layout: post
published: true
title: Du fait divers à la querelle politique
categorie: articles
cover_image: Cover_querelle_politique.jpg
related:
- Bad (Criminal) Company
- "L'argent ou l'honneur ?"
author: <NAME>
---
C’est presque en homme ordinaire que <NAME>. se rend, mardi 19 mai, un peu avant 8h30, au service des Sports de la ville de Marseille. Il y travaille comme coursier depuis près de trente ans.

{: .fullwidth .image}
Capture d'écran - vidéo AFP
{: .credit}
Arrivé devant le bâtiment, ses viennoiseries à la main, un homme casqué lui tire plusieurs balles dans la tête et le thorax, avant de s'enfuir à moto avec un complice. Les balles proviennent d’un revolver de calibre .357 Magnum, précise une source policière.
Cette affaire aurait pu en rester à la rubrique “Faits divers”. Mais rapidement les élus d'opposition au conseil municipal pointent la situation professionnelle ambigüe de Bernard F., à la fois employé de la fonction publique et proche du grand banditisme. En quelques heures, les critiques virent à la controverse.
<iframe src='//cdn.knightlab.com/libs/timeline3/latest/embed/index.html?source=1Mr7AF3dgapAmR4p1IXXCQAnSB1xJeaQqcRBQak5Oabo&font=OpenSans-GentiumBook&lang=fr&timenav_position=top&initial_zoom=2&height=500' width='100%' height='500' frameborder='0'></iframe>
Le jour même de l’assassinat, le président du groupe PS de la ville de Marseille, <NAME>, tweete : _«L'homme abattu ce matin faisait partie du grand banditisme et était employé municipal à la mairie de #Marseille : comment est-ce possible ?»_. Revenant aujourd’hui sur cette période, il explique qu'il a été étonné que _«la mairie de Marseille et son entourage aient été très choqués par ses mots»._ Selon lui, son seul souhait alors était d’interroger la population sur cette ambiguïté professionnelle.
<NAME> insiste sur le fait qu’il ne prétend pas détenir la clef du mystère et qu’il _“n’accuse personne en particulier"_. D’ailleurs certains élus socialistes ont eux-même déjà pratiqué une forme de clientélisme, estiment-il. Néanmoins plusieurs éléments le troublent, dans cette affaire : outre ses antécédents judiciaires, celui qui se faisait appeler «Petit Ber» était a priori très peu présent au service des sports de la ville.
<blockquote class="twitter-tweet" lang="fr"><p lang="fr" dir="ltr">L'homme abattu ce matin faisait partie du grand banditisme et était employé municipal à la mairie de <a href="https://twitter.com/hashtag/Marseille?src=hash">#Marseille</a> : comment est ce possible ?</p>— <NAME> (@stephanemari) <a href="https://twitter.com/stephanemari/status/600778867926765568">19 Mai 2015</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
Le 14 septembre dernier, la mairie de Marseille a répété sa ligne de défense s'agissant des différentes procédures judiciaires dans lesquelles <NAME>. était impliqué. Répondant à une question orale de Me <NAME>, président du groupe Front National de la ville de Marseille, <NAME> a expliqué que _"la ville et son employeur n’ont pas eu d’attitude laxiste à son égard",_ lui imposant des exclusions temporaires à chacune de ses condamnations passées.
Le maire de Marseille a ajouté que la ville avait même envisagé une révocation complète, la _«sanction la plus sévère et définitive»._ Néanmoins le pourvoi en cassation de <NAME>. a eu un «effet suspensif« sur ses sanctions, obligeant la municipalité à demeurer _«dans l’attente de son jugement imminent par la dernière instance pénale»._ _«L’affaire est en cours"_, confirme <NAME>, déléguée à la sécurité publique et prévention de la délinquance dans une interview téléphonique : _"Il faut laisser la justice faire son travail"._
> La ville et son employeur n’ont pas eu d’attitude laxiste à son égard.
**<NAME>** - Maire de la ville de Marseille (Conseil Municipal du 14 septembre 2015)
{: .credit}
Le maire en vient pourtant à la politique. Au conseil municipal de septembre, <NAME> a répondu aux critiques de ses opposants en leur renvoyant la balle : _«Je n’étais pas maire de Marseille à l’époque»._ Le recrutement de <NAME>. au service des sports date il est vrai de mai 1987, époque à laquelle le parti socialiste était aux commandes de la ville. _«Il y a 11.500 employés municipaux, il se peut qu’il y ait toujours quelqu’un qui ne se comporte pas bien»_, a ajouté <NAME>.
<NAME>, l'élu Front Nationam qui a questionné le maire en conseil municipal, considère aujourd’hui que ce dernier a _«botté en touche»_ et raille qu'il soit _«compliqué de mettre en mouvement une action disciplinaire contre un fonctionnaire»._ Invoquant le statut de fonctionnaire public, qui impose un casier judiciaire quasi vide (la plupart des condamnations pour crimes et délits sont interdites), il estime que les condamnations antérieures à l'affaire “Calisson”, toujours en cours, suffisaient à justifier sa révocation.
> Je constate qu'il est compliqué de mettre en mouvement une action disciplinaire contre un fonctionnaire
**<NAME>** - Président du groupe FN de la ville de Marseille (Interview 10 décembre 2015)
{: .credit}
Selon <NAME>, le seul fait que <NAME>. ait tenté d’encaisser un chèque volé d’un montant de plus de 1,3 millions d’euros en 2003 aurait dû l’empêcher de travailler au service des sports de la mairie.
<file_sep>/dataviz/homicides/js/default-5baee189e1a2f0bf680f4910cc958098.min.js
/*
* datawrapper / theme / default v1.5.2
* generated on 2016-01-15T11:32:32+01:00
*/
(function() {
dw.theme.register('default', {
colors: {
palette: ["#7A7873", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"],
secondary: ["#000000", '#777777', '#cccccc', '#ffd500', '#6FAA12'],
context: '#aaa',
axis: '#000000',
positive: '#1f77b4',
negative: '#d62728',
background: '#ffffff'
},
lineChart: {
fillOpacity: 0.2
},
vpadding: 10,
frame: false,
verticalGrid: false,
columnChart: {
darkenStroke: 5
}
});
}).call(this);
| 8884089b9ca6a860e808fc804a02a5f1f11d8269 | [
"Markdown",
"JavaScript"
] | 23 | Markdown | reglementsdecomptes/reglementsdecomptes.github.io | 513be6f872d3c6c5ad13333573bc28853b8ca84e | 2cde1eb4dfab1fc4b62e7bbc553a47e76389d91e |
refs/heads/master | <file_sep>from django.db import models
class Reservation(models.Model):
start_date = models.DateField()
finish_date = models.DateField()
parking_space_number = models.CharField(max_length=4)
phone_number = models.CharField(max_length=16)
name = models.CharField(max_length=35)
surname = models.CharField(max_length=35)
<file_sep>Simple app with a form to book a parking space.
Built using:
Django 2.0
Python 3.5.2
SQLite<file_sep># Generated by Django 2.0 on 2018-02-23 11:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reservation', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='reservation',
name='start_date',
field=models.DateField(),
),
]
<file_sep>import datetime
from django.forms import ModelForm, DateInput, TextInput, ValidationError
from .models import Reservation
class ReservationForm(ModelForm):
class Meta:
model = Reservation
fields = '__all__'
# Validating form fields using widgets
widgets = {
'start_date': DateInput(attrs={'type': 'date'}),
'finish_date': DateInput(attrs={'type': 'date'}),
'parking_space_number': TextInput(attrs={'pattern': '[1-9]+', 'title': 'Enter a valid parking space number'}),
'phone_number': TextInput(attrs={'pattern': '[0-9]+', 'title': 'Enter digits only '}),
'name': TextInput(attrs={'pattern': '[A-Za-z ]+', 'title': 'Enter characters only '}),
'surname': TextInput(attrs={'pattern': '[A-Za-z ]+', 'title': 'Enter characters only '})
}
# Additional custom validator for start_date / finish_date fields
def clean(self):
data = self.cleaned_data
start_date = data['start_date']
finish_date = data['finish_date']
if start_date > finish_date:
raise ValidationError('Wrong start and finish dates.')
if start_date < datetime.date.today():
raise ValidationError('Start date in the past.')
return data
class ParkingSpaceForm(ModelForm):
class Meta:
model = Reservation
fields = ['parking_space_number']
widgets = {
'parking_space_number': TextInput(attrs={'pattern': '[1-9]+', 'title': 'Enter a valid parking space number'})
}
<file_sep>from django.shortcuts import render
from django.views import View
from reservation.models import Reservation
from django.db.models import Q
from .forms import ReservationForm, ParkingSpaceForm
class ReservationView(View):
def get(self, request):
reservation = ReservationForm()
return render(request, 'reservation/index.html', {'form': reservation})
def post(self, request):
reservation_form = ReservationForm(data=request.POST)
if reservation_form.is_valid():
start_date = reservation_form.cleaned_data['start_date']
finish_date = reservation_form.cleaned_data['finish_date']
parking_space_number = reservation_form.cleaned_data['parking_space_number']
if Reservation.objects.filter(Q(parking_space_number=parking_space_number,
start_date__range=[start_date, finish_date]) |
Q(parking_space_number=parking_space_number,
finish_date__range=[start_date, finish_date])).exists():
msg = 'Dates overlaps. Try other dates and / or parking space.'
else:
msg = 'Reservation taken.'
reservation_form.save()
reservation_form = ReservationForm()
return render(request, 'reservation/index.html', {'message': msg,
'form': reservation_form})
return render(request, 'reservation/index.html', {'form': reservation_form})
class ReservationsListView(View):
def get(self, request):
parking_space_number = ParkingSpaceForm()
return render(request, 'reservation/reservations_search.html', {'form': parking_space_number})
def post(self, request):
parking_space_number_form = ParkingSpaceForm(data=request.POST)
if parking_space_number_form.is_valid():
space_number = parking_space_number_form.cleaned_data['parking_space_number']
reservations_list = Reservation.objects.filter(parking_space_number=space_number)
return render(request, 'reservation/reservations_list.html', {'form': ParkingSpaceForm(),
'reservations': reservations_list,
'space_number': space_number})
return render(request, 'reservation/reservations_search.html', {'form': parking_space_number_form})
| ab04b75d3e99aba2fc4a775938e08eaba3163bd1 | [
"Markdown",
"Python"
] | 5 | Python | elpromyko/parking-reservation | dc3b86bfbe11c0afe824d95b5aeb046e344f3b2f | 72bf7e4e244502aee7852fb45b31ec5fe12aed4d |
refs/heads/main | <file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController,AlertController } from '@ionic/angular';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
import { TaskService } from '../services/task.service';
import { Task,SetPartnerCategory } from '../interfaces/task';
import { ConfirmedValidator } from '../confirmed.validator';
import {Md5} from 'ts-md5/dist/md5';
@Component({
selector: 'app-crearperfil',
templateUrl: './crearperfil.page.html',
styleUrls: ['./crearperfil.page.scss'],
})
export class CrearperfilPage implements OnInit {
nombre:string;
myValue:any;
ionicForm: FormGroup;
isSubmitted = false;
className: string = 'quitar';
tasks: Task[] = [];
setPartnerCategorys: SetPartnerCategory[] = [];
paises:any;
usrMail:any;
contra:any;
constructor(private router: Router,private navController: NavController,
public formBuilder: FormBuilder,private taskService: TaskService,
public alertController: AlertController,
public navCtrl: NavController) {
this.ionicForm = this.formBuilder.group({
nombre: ['', [Validators.required]],
apellido: ['', [Validators.required]],
apellidomaterno: ['', [Validators.required]],
// telefono:['', [Validators.pattern('^[0-9]+$'),Validators.maxLength(10),Validators.minLength(10)]],
celular:['', [Validators.pattern('^[0-9]+$'),Validators.required,Validators.pattern('^[0-9]+$'),Validators.maxLength(10),Validators.minLength(10)]],
correo:['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
contrasena: ['', [Validators.required]],
confirmarcontrasena: ['', [Validators.required]],
pais: ['156', [Validators.required]],
terminos: [false, [Validators.requiredTrue]],
// tipo_empresa: ['1',],
// rfc: ['BUFP910825DE3', [Validators.required, Validators.pattern('^([A-ZÑ\x26]{3,4}([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])([A-Z]|[0-9]){2}([A]|[0-9]){1})?$')]],
// uso_cfdi: ['', [Validators.required]],
// password:['', [Validators.required,Validators.minLength(8)]],
// myBoolean: ['false',[]],
}, {
validator: ConfirmedValidator('contrasena', 'confirmarcontrasena')
})
}
res_users_id:any;
ngOnInit() {
this.taskService.getMailActivityTeam(2)
.subscribe((data) => {
this.res_users_id = data[0].res_users_id;
}, (err) => {
console.log(err)
});
this.taskService.getPaises()
.subscribe(paises => {
this.paises = paises;
console.log(paises)
});
}
atras(){
this.navController.back();
}
get errorControl() {
return this.ionicForm.controls;
}
async presentAlert() {
const alert = await this.alertController.create({
cssClass: 'class_alert',
header: 'Mensaje de XPERIENCE',
//subHeader: 'Subtitle',
message: 'Usuario existente captura otro usuario',
buttons: ['OK']
});
await alert.present();
}
submitForm() {
this.isSubmitted = true;
console.log(this.ionicForm.valid)
if (!this.ionicForm.valid){
console.log('Please provide all the required values!')
return false;
}else{
console.log('Formulario completo' + this.ionicForm.value);
this.usrMail = this.ionicForm.value.correo;
this.contra = this.ionicForm.value.contrasena = Md5.hashStr(this.ionicForm.value.contrasena)
let fecha = new Date().toISOString()
const task = {
name:this.ionicForm.value.nombre + " " + this.ionicForm.value.apellido + " " +this.ionicForm.value.apellidomaterno,
display_name:this.ionicForm.value.nombre + " " + this.ionicForm.value.apellido + " " + this.ionicForm.value.apellidomaterno,
lang:"es_MX",
type:"contact",
active:true,
email:this.ionicForm.value.correo,
phone:this.ionicForm.value.celular,
is_company:false,
color:0,
partner_share:true,
email_normalized:this.ionicForm.value.correo,
message_bounce:0,
parent_id:null,
//partner_gid:0,
invoice_warn:"no-message",
supplier_rank:0,
customer_rank:1,
picking_warn:"no-message",
purchase_warn:"no-message",
sale_warn:"no-message",
is_published:false,
warning_stage:0,
blocking_stage:0,
active_limit:false,
partner_name:this.ionicForm.value.nombre,
first_name:this.ionicForm.value.apellido,
second_name:this.ionicForm.value.apellidomaterno,
create_uid:2,
write_uid:2,
write_date:fecha,
create_date:fecha,
x_password:<PASSWORD>,
country_id:this.ionicForm.value.pais
};
this.taskService.getUsuario(this.ionicForm.value.correo)
.subscribe((data) => {
if(data[0]!=null){
this.presentAlert()
}else{
this.taskService.createTask(task)
.subscribe((newTask) => {
alert("Tus datos han sido guardados correctamente");
setTimeout(() => {
console.log("usuario" + this.usrMail)
console.log("contra" + this.contra)
this.taskService.getLogin2(this.ionicForm.value.correo,this.ionicForm.value.contrasena)
.subscribe((data) => {
if(data[0]!=null){
const setPartnerCategorys = {
category_id:1,
partner_id:data[0].id
}
this.taskService.setPartnerCategory(setPartnerCategorys)
.subscribe((reply: any) => {
this.ionicForm.value.nombre ="";
this.ionicForm.value.apellido ="";
this.ionicForm.value.correo ="";
this.ionicForm.value.celular ="";
this.ionicForm.value.terminos = false;
this.ionicForm.value.contrasena="";
this.navCtrl.navigateRoot(['/registro']);
}, (err) => {
console.log(err)
});
}
});
}, 1000);
}, (err) => {
console.log(err)
});
}
}, (err) => {
console.log(err)
});
}
}
aceptar(){
this.myValue=true
if(this.className == 'quitar'){
this.className = 'mostrar';
}else{
this.className = 'quitar';
}
return false;
}
cancelar(){
this.myValue=false
if(this.className == 'quitar'){
this.className = 'mostrar';
}else{
this.className = 'quitar';
}
return false;
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { MenuquickfitPage } from './menuquickfit.page';
describe('MenuquickfitPage', () => {
let component: MenuquickfitPage;
let fixture: ComponentFixture<MenuquickfitPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MenuquickfitPage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(MenuquickfitPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, NavController } from '@ionic/angular';
@Component({
selector: 'app-servicios',
templateUrl: './servicios.page.html',
styleUrls: ['./servicios.page.scss'],
})
export class ServiciosPage implements OnInit {
constructor(public alertController: AlertController,private router: Router,private navController: NavController) { }
items = [
{img:"../../assets/images/cama.png",name:'Toallas Extra',subtitle: "", active:false},
{img:"../../assets/images/flor.png",name:'Limpieza',subtitle: "", active:false},
{img:"../../assets/images/bata.png",name:'Amenidades',subtitle: "", active:false},
{img:"../../assets/images/pool.png",name:'Botellas de agua',subtitle: "", active:false},
];
items2 = [
{img:"../../assets/images/cel.png",name:'Llaves',subtitle: "Elevador de alta gama", active:false},
{img:"../../assets/images/aire.png",name:'Aire acondicionado',subtitle: "", active:false},
{img:"../../assets/images/bata.png",name:'Baño',subtitle: "", active:false},
{img:"../../assets/images/tv.png",name:'SmartTV',subtitle: 'PantallaDigital 50"', active:false},
];
ngOnInit() {
}
status: boolean = false;
clickEvent(){
this.status = !this.status;
}
toggleClass(item){
item.active = !item.active;
}
atras(){
this.navController.back();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {NavController} from '@ionic/angular';
@Component({
selector: 'app-avisoprivacidad',
templateUrl: './avisoprivacidad.page.html',
styleUrls: ['./avisoprivacidad.page.scss'],
})
export class AvisoprivacidadPage implements OnInit {
constructor(private navCtrl: NavController) { }
ngOnInit() {
}
atras(){
this.navCtrl.back();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Task,Paises,GetUsuario,getValetParking,GetResUsers,GetResPartnerPhone,
SetValetParking,SetPartnerCategory,Login,GetMailActivityTeam,SetServicio } from './../interfaces/task';
@Injectable({
providedIn: 'root'
})
export class TaskService {
//private api = 'https://jsonplaceholder.typicode.com';
//private api = 'http://webservicearca.000webhostapp.com';
private api = 'http://unchx.ddns.net:3001';
private api2 = 'http://portal.thexperiencehotel.com:3001';
private api3004 = 'http://portal.thexperiencehotel.com:3004';
constructor(
private http: HttpClient
) {}
createTask(task: Task) {
// const path = `${this.api}/todos`;
const path = `${this.api}/res_partner`;
return this.http.post(path, task);
}
setPartnerCategory(setPartnerCategory: SetPartnerCategory) {
// const path = `${this.api}/todos`;
const path = `${this.api}/res_partner_res_partner_category_rel`;
return this.http.post(path, setPartnerCategory);
}
getPaises() {
//const path = `${this.api}/todos`;
const path = `${this.api}/res_country?select=id,name&order=name`;
return this.http.get<Paises[]>(path);
}
getMailActivityTeam(mail_activity_team_id: any) {
//const path = `${this.api}/todos`;
const path = `${this.api}/mail_activity_team_users_rel?mail_activity_team_id=eq.${mail_activity_team_id}`;
return this.http.get<GetMailActivityTeam[]>(path);
}
getResUsers(res_users_id:any){
const path = `${this.api}/res_users?id=eq.${res_users_id}`;
return this.http.get<GetResUsers[]>(path);
}
getResPartnerPhone(res_users_id:any){
const path = `${this.api}/res_partner?id=eq.${res_users_id}`;
return this.http.get<GetResPartnerPhone[]>(path);
}
getLogin2(mail: any,contrasena:any) {
//const path = `${this.api}/todos/${id}`;
const path = `${this.api}/res_partner?email=eq.${mail}&x_password=eq.${contrasena}&active=eq.true`;
//alert(path)
return this.http.get<Login>(path);
}
getLogin(mail: any,contrasena:any) {
//const path = `${this.api}/todos/${id}`;
const path = `${this.api}/res_partner?email=eq.${mail}&x_password=eq.${contrasena}&active=eq.true`;
//alert(path)
return this.http.get<Task>(path);
}
getUsuario(mail: any){
//const path = `${this.api}/todos/${id}`;
const path = `${this.api}/res_partner?email=eq.${mail}`;
//alert(path)
return this.http.get<GetUsuario>(path);
}
getValetParking(user_id: any){
//const path = `${this.api}/todos/${id}`;
const path = `${this.api}/mail_activity?res_id=eq.${user_id}&activity_type_id=eq.15`;
//alert(path)
return this.http.get<getValetParking>(path);
}
getServicio(user_id: any,activity_type_id:any){
//const path = `${this.api}/todos/${id}`;
const path = `${this.api}/mail_activity?res_id=eq.${user_id}&activity_type_id=eq.${activity_type_id}`;
//alert(path)
return this.http.get<any>(path);
}
setValetParking(setValetParking: SetValetParking) {
// const path = `${this.api}/todos`;
const path = `${this.api}/mail_activity`;
return this.http.post(path, setValetParking);
}
setServicio(setServicio: SetServicio) {
// const path = `${this.api}/todos`;
const path = `${this.api}/mail_activity`;
return this.http.post(path, setServicio);
}
deleteServicio(user_id:any,activity_type_id:any) {
const path = `${this.api}/mail_activity?res_id=eq.${user_id}&activity_type_id=eq.${activity_type_id}`
return this.http.delete(path);
}
getHabitaciones(checkin:any,checkout:any,cantidadpersonas:any){
const path = `${this.api2}/rpc/disponibilidad_unica?d_checkin=${checkin}&d_checkout=${checkout}&capacity=gte.${cantidadpersonas}`
return this.http.get<any>(path);
}
postCrearReserva(data:any){
const path = `${this.api3004}/crear_reserva`
return this.http.post(path,data);
}
getDisponibilidad(checkIn:any,checkOut:any,idCategoria:any){
const path = `${this.api2}/rpc/disponibilidad?d_checkin=${checkIn}&d_checkout=${checkOut}&categoria_id=${idCategoria}`
return this.http.get<any>(path);
}
}
<file_sep>import {
Component,
OnInit
} from '@angular/core';
import {
FormGroup,
FormBuilder,
Validators,
FormControl
} from "@angular/forms";
import {
ActivatedRoute,
Router
} from '@angular/router';
import {
NavController
} from '@ionic/angular';
import {
TaskService
} from '../services/task.service';
import {
NativeStorage
} from '@ionic-native/native-storage/ngx';
@Component({
selector: 'app-datosreservacion',
templateUrl: './datosreservacion.page.html',
styleUrls: ['./datosreservacion.page.scss'],
})
export class DatosreservacionPage implements OnInit {
ionicForm: FormGroup;
isSubmitted = false;
orderObj: any;
constructor(
private navCtrl: NavController,
public formBuilder: FormBuilder,
private router: Router,
private apiRest: TaskService, private route: ActivatedRoute,
private nativeStorage: NativeStorage) {
this.ionicForm = this.formBuilder.group({
nombre: ['', [Validators.required]],
apellido: ['', [Validators.required]],
celular: ['', [Validators.required]],
correo: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
password: ['', [Validators.required]]
})
}
get errorControl() {
return this.ionicForm.controls;
}
ngOnInit() {
this.route.queryParams.subscribe((queryParams) => {
this.orderObj = {
categoria_id: queryParams.categoria_id,
fechacheckin: queryParams.fechacheckin,
fechacheckout: queryParams.fechacheckout,
ninos: queryParams.ninos,
adultos: queryParams.adultos
};
});
this.route.queryParams.subscribe(queryParams =>
console.log("VALOR ID: " + queryParams.categoria_id + " VALOR FECHA CHECKIN: " + queryParams.fechacheckin + " VALOR FECHA CECKOUT: " + queryParams.fechacheckout + " VALOR ninos: " + queryParams.ninos + " VALOR adultos: " + queryParams.adultos)
);
}
politicascancelacion() {
this.router.navigate(['politicascancelacion'])
}
submitForm() {
console.log("categoria id: " + this.orderObj.categoria_id)
console.log("fechacheckin: " + this.orderObj.fechacheckin)
console.log("fechacheckout: " + this.orderObj.fechacheckout)
console.log("adultos: " + this.orderObj.adultos)
console.log("ninos" + this.orderObj.ninos)
this.nativeStorage.getItem('app')
.then(
app => {
let id=app.user_id;
let checkIn = this.orderObj.fechacheckin + " 18:00:00";
let checkOut = this.orderObj.fechacheckout + " 16:00:00";
let idCategoria = this.orderObj.categoria_id;
this.apiRest.getDisponibilidad(checkIn,checkOut,idCategoria).subscribe(
dataHabitacion =>{
console.log("DATA HABITACION");
console.log(dataHabitacion);
dataHabitacion=dataHabitacion[0];
let id_room = dataHabitacion.room_id;
let habitacion = dataHabitacion.habitacion + dataHabitacion.categoria
let datosReserva = {
id,
f_checkin: checkIn,
f_checkout: checkOut,
adultos: this.orderObj.adultos,
ninos: this.orderObj.ninos,
id_room,
habitacion,
}
this.apiRest.postCrearReserva(datosReserva).subscribe(reservacion =>{
console.log(reservacion);
console.log(Number.isInteger(reservacion));
if(Number.isInteger(reservacion[0])){
alert("Reservación generada de manera exitosa.");
this.router.navigate(['/inicio']);
}else alert(reservacion);
});
}
);
},
error => {
//Datos del usuario
}
);
//Obtener idRoom, habitacion + categoria
// this.apiRest.getDisponibilidad(checkIn,checkOut,idCategoria).subscribe(
// dataHabitacion =>{
// console.log("DATA HABITACION");
// console.log(dataHabitacion);
// dataHabitacion=dataHabitacion[0];
// let id_room = dataHabitacion.room_id;
// let habitacion = "Habitación " + id_room + " " +dataHabitacion.habitacion + dataHabitacion.categoria
// let datosReserva = {
// id: idCategoria,
// f_checkin: checkIn,
// f_checkout: checkOut,
// adultos: this.orderObj.adultos,
// ninos: this.orderObj.ninos,
// id_room,
// habitacion,
// }
// this.apiRest.postCrearReserva(datosReserva).subscribe(reservacion =>{
// console.log(reservacion);
// alert("Reservación generada de manera exitosa.")
// });
// }
// );
// console.log("categoria id: " + this.orderObj.categoria_id)
// console.log("fechacheckin: " + this.orderObj.fechacheckin)
// console.log("fechacheckout: " + this.orderObj.fechacheckout)
// console.log("adultos: " + this.orderObj.adultos)
// console.log("ninos" + this.orderObj.ninos)
// let datosReserva = {
// id: idCategoria,
// f_checkin: checkIn,
// f_checkout: checkOut,
// adultos: this.orderObj.adultos,
// ninos: this.orderObj.ninos,
// id_room: 771,
// habitacion: "Habitacion 111 - Petite secret room - Single room", //Habitacion + categoria
// }
// let data = this.apiRest.postCrearReserva(datosReserva);
// console.log(data);
// this.isSubmitted = true;
// if (!this.ionicForm.valid) {
// console.log('Please provide all the required values!')
// return false;
// } else {
// console.log("Campos correctos en login (LOGUEADO)" + this.ionicForm.valid)
// this.nativeStorage.getItem('app')
// .then(
// app => {
// //Datos del cliente
// let datosReserva = {
// id: "",
// f_checkin: "",
// f_checkout: "",
// adultos: 2,
// ninos: 0,
// id_room: 771,
// habitacion: "Habitacion 111 - Petite secret room - Single room", //Habitacion + categoria
// }
// this.generarReserva(this.generarReserva(datosReserva));
// },
// error => {
// //Datos del usuario
// let datosReserva = {
// id: "",
// f_checkin: "",
// f_checkout: "",
// adultos: 2,
// ninos: 0,
// id_room: 771,
// habitacion: "Habitacion 111 - Petite secret room - Single room", //Habitacion + categoria
// }
// this.generarReserva(this.generarReserva(datosReserva));
// }
// );
// }
}
generarReserva(datosReserva) {
//this.apiRest.postCrearReserva(datosReserva);
}
atras() {
this.navCtrl.back();
}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute,Router } from '@angular/router';
import { AlertController, NavController } from '@ionic/angular';
import { TaskService } from '../services/task.service';
import { SetServicio } from '../interfaces/task';
@Component({
selector: 'app-nomolestar',
templateUrl: './nomolestar.page.html',
styleUrls: ['./nomolestar.page.scss'],
})
export class NomolestarPage implements OnInit {
constructor(private taskService: TaskService,public alertController: AlertController,
private router: Router,private navController: NavController,
private route: ActivatedRoute) {
}
activo:boolean;
user_id:any;
name:any;
email:any;
x_descauto:any;
x_placas:any;
res_users_id:any;
setServicio: SetServicio[] = [];
texto:any = "Desactivado";
ngOnInit() {
this.taskService.getMailActivityTeam(4)
.subscribe((data) => {
this.res_users_id = data[0].res_users_id;
console.log(this.res_users_id)
}, (err) => {
console.log(err)
});
this.route.queryParams.subscribe(params => {
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
console.log(this.user_id + " " + this.name + " " +this.email)
this.taskService.getServicio(this.user_id,23)
.subscribe((data) => {
console.log(data);
console.log(data[0]);
if(typeof(data[0]) !== "undefined" || data[0]!=null){
console.log("No molestar activado: " + data);
this.activo=false;
}else{
console.log("Me molestar desactivado: " + data);
this.activo=true;
}
}, (err) => {
console.log(err)
});
}
ngOnwillEnter(){
this.taskService.getMailActivityTeam(4)
.subscribe((data) => {
this.res_users_id = data[0].res_users_id;
console.log(this.res_users_id)
}, (err) => {
console.log(err)
});
this.route.queryParams.subscribe(params => {
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
console.log(this.user_id + " " + this.name + " " +this.email)
this.taskService.getServicio(this.user_id,23)
.subscribe((data) => {
console.log(data);
console.log(data[0]);
if(typeof(data[0]) !== "undefined" || data[0]!=null){
console.log("No molestar activado: " + data);
this.activo=false;
}else{
console.log("Me molestar desactivado: " + data);
this.activo=true;
}
}, (err) => {
console.log(err)
});
}
atras(){
this.navController.back();
}
// status: boolean = false;
clickEvent(){
let fecha_hora = new Date().toISOString()
let fecha = new Date("YYYY-MM-DD");
//fecha.setDate(fecha.getDate() + 1)
//console.log(fecha)
const setServicio = {
res_model_id:78,
res_model:"res.partner",
res_id:this.user_id,
res_name:this.name,
activity_type_id:23,
summary:"NO MOLESTAR",
note:"<p><br></p><table class=\"table table-bordered\"><tbody><tr><td style=\"text-align:center\"><h2><b><h2><font><h2>Tarea</h2></font></h2></b></h2></td><td style=\"text-align:center\"><h2><b><font>Habitación</font></b></h2></td></tr><tr><td>NO MOLESTAR</td><td>ACTIVO <br></br>HORA DE SOLICTUD: "+fecha_hora+"</br></td></tr></tbody></table>",
date_deadline:"2021-02-11",
automated:"True",
user_id:this.res_users_id,
recommended_activity_type_id:null,
previous_activity_type_id:null,
create_uid:this.res_users_id,
create_date:fecha_hora,
write_uid:this.res_users_id,
write_date:fecha_hora,
calendar_event_id:null,
team_id:4
// this.status = !this.status;
// if(this.status){
// this.texto="Activado"
// }else{
// this.texto="Desactivado"
// }
}
this.taskService.setServicio(setServicio)
.subscribe((newTask) => {
this.activo=false;
}, (err) => {
console.log(err)
});
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { IniciologueadoPage } from './iniciologueado.page';
const routes: Routes = [
{
path: '',
component: IniciologueadoPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class IniciologueadoPageRoutingModule {}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MenusereiaPage } from './menusereia.page';
const routes: Routes = [
{
path: '',
component: MenusereiaPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class MenusereiaPageRoutingModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LandingsereiaPageRoutingModule } from './landingsereia-routing.module';
import { LandingsereiaPage } from './landingsereia.page';
import { DatePickerModule } from 'ionic4-date-picker';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,DatePickerModule,
LandingsereiaPageRoutingModule
],
declarations: [LandingsereiaPage]
})
export class LandingsereiaPageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-perfil',
templateUrl: './perfil.page.html',
styleUrls: ['./perfil.page.scss'],
})
export class PerfilPage implements OnInit {
constructor(private router: Router,private navController: NavController) { }
inis: string = 'inis';
inic: string = 'inic';
inivp: string = 'inivp';
circuloxperience: string = '';
circulocontacto: string = '';
circuloperfil: string = '';
ngOnInit() {
this.inivp = '';
}
inicio(){
this.router.navigate(['/inicio']);
this.inis = 'inis';
this.inic = 'inic';
this.inivp = '';
this.circuloxperience = 'circulo3'
this.circulocontacto = 'circulo2'
this.circuloperfil = 'circulo'
}
iniciarsesion(){
this.router.navigate(['/registro']);
}
registro(){
this.router.navigate(['/crearperfil']);
}
menu(){
this.router.navigate(['/menu']);
this.inis = 'inis';
this.inic = 'inic';
this.inivp = '';
this.circuloxperience = 'circulo3'
this.circulocontacto = 'circulo2'
this.circuloperfil = 'circulo'
}
activar(val){
if(val == 1){
this.inis = '';
this.inic = 'inic';
this.inivp = 'inivp';
this.circuloxperience = 'circulo'
this.circulocontacto = 'circulo2'
this.circuloperfil = 'circulo3'
}else if(val == 2){
this.inic = '';
this.inis = 'inis';
this.inivp = 'inivp';
this.circuloxperience = 'circulo3'
this.circulocontacto = 'circulo'
this.circuloperfil = 'circulo3'
}else if(val == 3){
this.inis = 'inis';
this.inic = 'inic';
this.inivp = '';
this.circuloxperience = 'circulo3'
this.circulocontacto = 'circulo2'
this.circuloperfil = 'circulo'
}
return false;
}
}
<file_sep>export interface Task {
name:string,
display_name:string,
lang:string,
type:string,
active:boolean,
email:string,
is_company:boolean,
color:number,
partner_share:boolean,
email_normalized:string,
message_bounce:number,
parent_id:number,
//partner_gid:number,
invoice_warn:string,
supplier_rank:number,
customer_rank:number,
picking_warn:string,
purchase_warn:string,
sale_warn:string,
is_published:boolean,
warning_stage:number,
blocking_stage:number,
active_limit:boolean,
partner_name:string,
first_name:string,
second_name:string,
create_uid:number,
write_uid:number,
write_date:string,
create_date:string,
x_password:string,
country_id:number
}
export interface Paises {
id:number,
name:string,
}
export interface Login {
id:number,
name:string,
email:string,
x_descauto:string,
x_placas:string,
x_passowrd:string,
}
export interface GetUsuario {
email:string
}
export interface getValetParking {
user_id:string;
}
export interface SetValetParking{
res_model_id:number,
res_model:string,
res_id:number,
res_name:string,
activity_type_id:number,
summary:string,
note:string,
date_deadline:string,
automated:string,
user_id:number,
recommended_activity_type_id:number,
previous_activity_type_id:number,
create_uid:number,
create_date:string,
write_uid:number,
write_date:string,
calendar_event_id:number,
team_id:number
}
export interface SetServicio{
res_model_id:number,
res_model:string,
res_id:number,
res_name:string,
activity_type_id:number,
summary:string,
note:string,
date_deadline:string,
automated:string,
user_id:number,
recommended_activity_type_id:number,
previous_activity_type_id:number,
create_uid:number,
create_date:string,
write_uid:number,
write_date:string,
calendar_event_id:number,
team_id:number
}
export interface SetPartnerCategory{
category_id:number,
partner_id:number
}
export interface GetMailActivityTeam{
mail_activity_team_id:number;
res_users_id:number;
}
export interface GetResUsers{
partner_id:number;
}
export interface GetResPartnerPhone{
mobile:number;
}<file_sep>import { Component, OnInit, Renderer2 } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-iniciologueado',
templateUrl: './iniciologueado.page.html',
styleUrls: ['./iniciologueado.page.scss'],
})
export class IniciologueadoPage implements OnInit {
public items = ["../assets/images/sliderinicio1.jpg",
"../assets/images/sliderinicio1.jpg"
];
public sliderOptions = {
initialSlide: 0,
slidesPerView: 1,
autoplay:false,
//allowTouchMove: false,
//Si quito el pagination muestra los bullets pero no deja dar click
// pagination: {
// clickable: true,
// }
//Con el pagination asi los muestra y deja dar click
pagination: {
el: ".swiper-pagination",
type: "bullets",
clickable: true
}
};
constructor(public navCtrl: NavController,private route: ActivatedRoute,
private router: Router,private renderer: Renderer2){ }
user_id:any;
name:any;
email:any;
x_descauto:any;
x_placas:any;
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
}
menuconcierge(){
//this.navCtrl.navigateRoot("menuconcierge")
this.router.navigate(['/menuconcierge'], {
queryParams: {
user_id: this.user_id,
name:this.name,
email:this.email,
x_descauto:this.x_descauto,
x_placas:this.x_placas
}
});
}
menusereia(){
//this.navCtrl.navigateRoot("menusereia")
this.router.navigate(['/landingsereia']);
}
menuquickfit(){
//this.navCtrl.navigateRoot("menuquickfit")
this.router.navigate(['/landingquickfit']);
}
menu(){
this.navCtrl.navigateRoot("menulogueado")
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-menuquickfit',
templateUrl: './menuquickfit.page.html',
styleUrls: ['./menuquickfit.page.scss'],
})
export class MenuquickfitPage implements OnInit {
constructor(private router: Router,
private navCtrl: NavController,
private navController: NavController) { }
inis: string = 'inis';
inic: string = 'inic';
inivp: string = 'inivp';
circuloxperience: string = '';
circulocontacto: string = '';
circuloperfil: string = '';
ngOnInit() {
this.inivp = '';
}
iniciologueado(){
//this.navCtrl.navigateRoot("")
this.router.navigate(['/iniciologueado']);
}
terminos(){
//this.navCtrl.navigateRoot("terminos")
this.router.navigate(['/terminos']);
}
menuconcierge(){
//this.navCtrl.navigateRoot("menuconcierge")
this.router.navigate(['/menuconcierge']);
}
menusereia(){
this.router.navigate(['/landingsereia']);
}
menu(){
this.router.navigate(['/menulogueado']);
}
cerrarsesion(){
this.navCtrl.navigateRoot("registro")
}
registro(){
this.router.navigate(['/crearperfil']);
}
}
<file_sep>import { Component, OnInit, Renderer2 } from '@angular/core';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-inicio',
templateUrl: './inicio.page.html',
styleUrls: ['./inicio.page.scss'],
})
export class InicioPage implements OnInit {
public items = ["../assets/images/sliderinicio1.jpg",
"../assets/images/sliderinicio1.jpg"
];
public sliderOptions = {
initialSlide: 0,
slidesPerView: 1,
autoplay:false,
//allowTouchMove: false,
//Si quito el pagination muestra los bullets pero no deja dar click
// pagination: {
// clickable: true,
// }
//Con el pagination asi los muestra y deja dar click
pagination: {
el: ".swiper-pagination",
type: "bullets",
clickable: true
}
};
constructor(public navCtrl: NavController,private renderer: Renderer2){ }
ngOnInit() {
}
xperience(){
this.navCtrl.navigateRoot("xperience")
}
contacto(){
this.navCtrl.navigateRoot("contacto")
}
perfil(){
this.navCtrl.navigateRoot("perfil")
}
menu(){
this.navCtrl.navigateRoot("menu")
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { XperiencePageRoutingModule } from './xperience-routing.module';
import { XperiencePage } from './xperience.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
XperiencePageRoutingModule
],
declarations: [XperiencePage]
})
export class XperiencePageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-menulogueado',
templateUrl: './menulogueado.page.html',
styleUrls: ['./menulogueado.page.scss'],
})
export class MenulogueadoPage implements OnInit {
constructor(private router: Router,
private navCtrl: NavController) { }
ngOnInit() {
}
reservacion(){
this.router.navigate(["/reservacion"])
}
atras(){
this.navCtrl.back();
}
iniciologueado(){
//this.navCtrl.navigateRoot("")
this.router.navigate(['/iniciologueado']);
}
avisoprivacidad(){
this.router.navigate(['/avisoprivacidad']);
}
terminos(){
//this.navCtrl.navigateRoot("terminos")
this.router.navigate(['/terminostxt']);
}
menuconcierge(){
//this.navCtrl.navigateRoot("menuconcierge")
this.router.navigate(['/menuconcierge']);
}
menusereia(){
//this.navCtrl.navigateRoot("menusereia")
this.router.navigate(['/landingsereia']);
}
menuquickfit(){
//this.navCtrl.navigateRoot("menuquickfit")
this.router.navigate(['/landingquickfit']);
}
cerrarsesion(){
this.navCtrl.navigateRoot("registro")
}
registro(){
this.router.navigate(['/crearperfil']);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LandingquickfitPageRoutingModule } from './landingquickfit-routing.module';
import { LandingquickfitPage } from './landingquickfit.page';
import { DatePickerModule } from 'ionic4-date-picker';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
DatePickerModule,
LandingquickfitPageRoutingModule
],
declarations: [LandingquickfitPage]
})
export class LandingquickfitPageModule {}
<file_sep>import {
Component,
OnInit
} from '@angular/core';
import {
ActivatedRoute,
Router
} from '@angular/router';
import {
NavController
} from '@ionic/angular';
import {
TaskService
} from '../services/task.service';
import {
NativeStorage
} from '@ionic-native/native-storage/ngx';
@Component({
selector: 'app-menuconcierge',
templateUrl: './menuconcierge.page.html',
styleUrls: ['./menuconcierge.page.scss'],
})
export class MenuconciergePage implements OnInit {
constructor(private router: Router, private navCtrl: NavController,
private route: ActivatedRoute, private rest: TaskService, private nativeStorage: NativeStorage) {}
user_id: any;
name: any;
email: any;
x_descauto: any;
x_placas: any;
switchToallas:any=false;
switchLimpieza:any=false;
switchAmenidades:any=false;
switchAgua:any=false;
switchTv:any=false;
switchAire:any=false;
switchBanio:any=false;
switchMantenimiento:any=false;
switchValet:any=false;
switchNoMolestar:any=false;
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
console.log(this.user_id + " " + this.name + " " + this.email)
}
ionViewWillEnter() {
this.nativeStorage.getItem('app')
.then(
app => {
console.log(app)
this.user_id = app.user_id;
this.getMailActivityTeam(23,"switchNoMolestar");//NO molestar
this.getMailActivityTeam(15,"switchValet");//Valet
this.getMailActivityTeam(14,"switchToallas");//Toallas
this.getMailActivityTeam(16,"switchLimpieza");//Limpieza
this.getMailActivityTeam(17,"switchAmenidades");//Amenidades
this.getMailActivityTeam(18,"switchAgua");//Agua
this.getMailActivityTeam(26,"switchMantenimiento");//Mantenimiento
this.getMailActivityTeam(22,"switchTv");//Smart Tv
this.getMailActivityTeam(20,"switchAire");//Aire acondicionado
this.getMailActivityTeam(21,"switchBanio");//Baño
},
error => console.error("NO HAY USER_ID")
);
}
atras(){
this.navCtrl.back();
}
mensajegerente() {
this.router.navigate(['/mensajegerente']);
}
mensajerecepcion() {
this.router.navigate(['/mensajerecepcion']);
}
iniciologueado() {
this.navCtrl.navigateRoot("iniciologueado")
}
servicios() {
this.router.navigate(['/servicios']);
}
terminos() {
this.navCtrl.navigateRoot("terminostxt")
}
cerrarsesion() {
this.navCtrl.navigateRoot("registro")
}
menuconcierge() {
//this.navCtrl.navigateRoot("menuconcierge")
this.router.navigate(['/menuconcierge']);
}
menusereia() {
//this.navCtrl.navigateRoot("menusereia")
this.router.navigate(['/landingsereia']);
}
menuquickfit() {
//this.navCtrl.navigateRoot("menuquickfit")
this.router.navigate(['/landingquickfit']);
}
menu() {
this.navCtrl.navigateRoot("menulogueado")
}
noMolestar(event) {
console.log("====NO MOLESTAR====");
console.log(event.detail);
let idType=23;
if(event.detail.checked==true){
this.setMailActivity(4,idType,"No molestar",this.switchNoMolestar);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
valet(event) {
console.log("====VALET====");
console.log(event.detail);
let idType=15;
if(event.detail.checked==true){
this.setMailActivity(2,idType,"Valet Parking",this.switchValet);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
toallas(event) {
console.log("====TOALLAS====");
console.log(event.detail);
let idType=14;
if(event.detail.checked==true){
this.setMailActivity(1,idType,"Toallas Extra",this.switchToallas);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
limpieza(event) {
console.log("====limpieza====");
console.log(event.detail);
let idType=16;
if(event.detail.checked==true){
this.setMailActivity(1,idType,"Limpieza",this.switchToallas);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
amenidades(event) {
console.log("====amenidades====");
console.log(event.detail);
let idType=17;
if(event.detail.checked==true){
this.setMailActivity(1,idType,"Amenidades",this.switchToallas);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
agua(event) {
console.log("====TOALLAS====");
console.log(event.detail);
let idType=18;
if(event.detail.checked==true){
this.setMailActivity(1,idType,"Botellas de agua",this.switchAgua);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
mantenimiento(event) {
console.log("====mantenimiento====");
console.log(event.detail);
let idType=26;
if(event.detail.checked==true){
this.setMailActivity(3,idType,"Mantenimiento",this.switchTv);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
tv(event) {
console.log("====TV====");
console.log(event.detail);
let idType=22;
if(event.detail.checked==true){
this.setMailActivity(3,idType,"Smart TV",this.switchTv);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
aire(event) {
console.log("====AIRE====");
console.log(event.detail);
let idType=20;
if(event.detail.checked==true){
this.setMailActivity(3,idType,"Aire acondicionado",this.switchAire);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
banio(event) {
console.log("====BANO====");
console.log(event.detail);
let idType=21;
if(event.detail.checked==true){
this.setMailActivity(1,idType,"Baño",this.switchBanio);
}else{
this.rest.deleteServicio(this.user_id,idType).subscribe(()=>{
this.switchToallas=false;
});
}
}
getMailActivityTeam(typeId:any,switchOption:any) {
this.rest.getServicio(this.user_id, typeId)
.subscribe((data) => {
console.log("=====Get mailActivity: "+typeId+"=====");
console.log(data);
console.log(((data.length==0)?false:true));
//switchOption=((data.length==0)?false:true);
this[switchOption]=((data.length==0)?false:true);
}, (err) => {
console.log(err)
});
}
setMailActivity(team: any, typeId:any,summary:any,switchOption:any) {
console.log("RES_USER ID PEDRO: "+this.user_id)
this.rest.getServicio(this.user_id,typeId).subscribe(servicio=>{
if(servicio.length==0){
this.rest.getMailActivityTeam(team)
.subscribe((data) => {
let res_users_id = data[0].res_users_id;
let fecha_hora = new Date().toISOString()
var manana = new Date()
manana.setDate(manana.getDate() + 1)
let fManana=manana.toISOString();
const setServicio = {
res_model_id: 78,
res_model: "res.partner",
res_id: this.user_id,
res_name: this.name,
activity_type_id: typeId,
summary: summary,
note: "<p><br></p><table class=\"table table-bordered\"><tbody><tr><td style=\"text-align:center\"><h2><b><h2><font><h2>Valet Parking </h2></font></h2></b></h2></td><td style=\"text-align:center\"><h2><b><font>Habitación</font></b></h2></td></tr><tr><td>Descripción del Auto: "+this.x_descauto+" Placas : "+this.x_placas+"</td><td>ACTIVO <br></br>HORA DE SOLICTUD: " + fecha_hora + "</br></td></tr></tbody></table>",
date_deadline: fManana,
automated: "True",
user_id: res_users_id,
recommended_activity_type_id: null,
previous_activity_type_id: null,
create_uid: res_users_id,
create_date: fecha_hora,
write_uid: res_users_id,
write_date: fecha_hora,
calendar_event_id: null,
team_id: team
}
this.rest.setServicio(setServicio)
.subscribe((newTask) => {
console.log(setServicio)
console.log("GUARDA!")
switchOption=true;
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});
}else console.log("Ya existe un registro de "+summary);
});
}
}<file_sep><ion-content>
<div class="bg_registro" [class]="className">
<div class="content_llamanos">
<!-- <h1>TERMINOS Y CONDICIONES</h1> -->
<img src="../../assets/images/logoTerminos.png" alt="logo" class="logo">
<div class="title1">Terminos y condiciones</div>
<p class="parrafo1">
Para hacer uso de Xperience en este
dispositivo es necesario que aceptes los
Terminos y Condiciones.
</p>
<div class="leerterminos" (click)="terminostxt()">
<div class="txt2">leer términos</div>
<img src="../../assets/images/flecha-derechanegra.png" alt="arrow">
</div>
<ion-grid class="content_btns">
<ion-button color="transparent" class="btn2" (click)="cancelar()">cancelar</ion-button>
<ion-button color="transparent" class="btn1" (click)="cancelar()">Acepto</ion-button>
</ion-grid>
</div>
</div>
</ion-content>
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
@Component({
selector: 'app-menusereia',
templateUrl: './menusereia.page.html',
styleUrls: ['./menusereia.page.scss'],
})
export class MenusereiaPage implements OnInit {
constructor(private navCtrl: NavController,private router: Router
,private nativeStorage:NativeStorage) { }
ngOnInit() {
}
iniciologueado(){
//this.navCtrl.navigateRoot("iniciologueado")
this.router.navigate(['/iniciologueado']);
}
landingsereia(){
this.router.navigate(['/landingsereia']);
}
menuconcierge(){
//this.navCtrl.navigateRoot("menuconcierge")
this.router.navigate(['/menuconcierge']);
}
menuquickfit(){
//this.navCtrl.navigateRoot("menuquickfit")
this.router.navigate(['/menuquickfit']);
}
menu(){
this.navCtrl.navigateRoot("menulogueado")
}
terminos(){
//this.navCtrl.navigateRoot("terminos")
this.router.navigate(['/terminos']);
}
cerrarsesion(){
this.nativeStorage.clear();
this.navCtrl.navigateRoot("registro");
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { IniciarsesioncodigoPage } from './iniciarsesioncodigo.page';
describe('IniciarsesioncodigoPage', () => {
let component: IniciarsesioncodigoPage;
let fixture: ComponentFixture<IniciarsesioncodigoPage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ IniciarsesioncodigoPage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(IniciarsesioncodigoPage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { IniciologueadoPageRoutingModule } from './iniciologueado-routing.module';
import { IniciologueadoPage } from './iniciologueado.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
IniciologueadoPageRoutingModule
],
declarations: [IniciologueadoPage]
})
export class IniciologueadoPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { DatosreservacionPageRoutingModule } from './datosreservacion-routing.module';
import { DatosreservacionPage } from './datosreservacion.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
DatosreservacionPageRoutingModule
],
declarations: [DatosreservacionPage]
})
export class DatosreservacionPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { ItinerarioPageRoutingModule } from './itinerario-routing.module';
import { ItinerarioPage } from './itinerario.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ItinerarioPageRoutingModule
],
declarations: [ItinerarioPage]
})
export class ItinerarioPageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { DatePickerModule } from 'ionic4-date-picker';
@Component({
selector: 'app-landingquickfit',
templateUrl: './landingquickfit.page.html',
styleUrls: ['./landingquickfit.page.scss'],
})
export class LandingquickfitPage implements OnInit {
constructor(private router: Router,private navCtrl: NavController) { }
fecha:any;
numeroCantidad:any=1;
cantidad:any=this.numeroCantidad + " Persona";
mostrarCalendario:any="hide";
ocultarTexto:any="";
className: string = 'quitar';
hora:any="12:00"
ngOnInit() {
this.fecha = new Date().toISOString();
console.log(this.fecha)
}
calendario(){
if(this.ocultarTexto==""){
this.mostrarCalendario = ""
this.ocultarTexto="hide"
}
}
mas(){
this.numeroCantidad+=1
if(this.numeroCantidad>1){
this.cantidad=this.numeroCantidad +" Personas";
}else{
this.cantidad=this.numeroCantidad +" Persona";
}
}
menos(){
if(this.numeroCantidad>1){
this.numeroCantidad-=1
if(this.numeroCantidad>=2){
this.cantidad=this.numeroCantidad +" Personas";
}else{
this.cantidad=this.numeroCantidad +" Persona";
}
}
}
aceptar(){
if(this.className == 'quitar'){
this.className = 'mostrar';
}else{
this.className = 'quitar';
}
return false;
}
cancelar(){
if(this.className == 'quitar'){
this.className = 'mostrar';
}else{
this.className = 'quitar';
}
return false;
}
dateSelected($event){
console.log($event.toLocaleString())
}
atras(){
this.navCtrl.back();
}
}
<file_sep>import { Component, ElementRef, OnInit, ViewChild, Renderer2, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
@Component({
selector: 'app-iniciarsesioncodigo',
templateUrl: './iniciarsesioncodigo.page.html',
styleUrls: ['./iniciarsesioncodigo.page.scss'],
})
export class IniciarsesioncodigoPage implements OnInit {
@ViewChild('numero3') child: HTMLElement;
//@ViewChild("numero3") nameField : ElementRef;
@ViewChild("numero4") numero4 : ElementRef;
@ViewChild("numero5") numero5 : ElementRef;
@ViewChild("numero6") numero6 : ElementRef;
@ViewChild('numero2', {static: false}) numero2:ElementRef;
@ViewChild('myInput') myInput: ElementRef;
correo:string;
myValue:any;
ionicForm: FormGroup;
isSubmitted = false;
className: string = 'quitar';
elemento: any;
constructor(private router: Router,
private navController: NavController,
public formBuilder: FormBuilder,
private elmRef: ElementRef,
private renderer: Renderer2) {
this.ionicForm = this.formBuilder.group({
correo:['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
})
}
ngOnInit() {
//document.getElementById('numero2').focus();
}
edit(){
//this.myInput.nativeElement.focus();
this.router.navigate(['/iniciarsesionreservacion']);
}
moveFocus(event,numero) {
//console.log(event.srcElement)
if(numero==1){
this.edit();
}else if(numero==2){
setTimeout(()=>{
//this.numero3.nativeElement.focus()
})
}
}
eventHandler(event){
console.log("EVENT: "+event);
console.log("EVENT KEYCODE: "+event.keyCode);
console.log("EVENT KEYIDENTIFIER: "+ event.keyIdentifier);
}
atras(){
this.navController.back();
}
siguiente(){
this.router.navigate(['/iniciarsesionreservacion']);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MenulogueadoPageRoutingModule } from './menulogueado-routing.module';
import { MenulogueadoPage } from './menulogueado.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
MenulogueadoPageRoutingModule
],
declarations: [MenulogueadoPage]
})
export class MenulogueadoPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MensajerecepcionPageRoutingModule } from './mensajerecepcion-routing.module';
import { MensajerecepcionPage } from './mensajerecepcion.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule,
MensajerecepcionPageRoutingModule
],
declarations: [MensajerecepcionPage]
})
export class MensajerecepcionPageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertController, NavController } from '@ionic/angular';
import { TaskService } from '../services/task.service';
import { SetValetParking } from '../interfaces/task';
@Component({
selector: 'app-valetparking',
templateUrl: './valetparking.page.html',
styleUrls: ['./valetparking.page.scss'],
})
export class ValetparkingPage implements OnInit {
constructor(
private taskService: TaskService,public alertController: AlertController,
private router: Router,private navCtrl: NavController,private route: ActivatedRoute) { }
activo:boolean;
setValetParking: SetValetParking[] = [];
//texto:any = "<NAME>";
user_id:any;
name:any;
email:any;
x_descauto:any;
x_placas:any;
res_users_id:any;
ngOnwillEnter(){
this.route.queryParams.subscribe(params => {
console.log("PARAMETROS: "+params.user_id)
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
console.log(this.user_id + " " + this.name + " " +this.email)
this.taskService.getMailActivityTeam(2)
.subscribe((data) => {
this.res_users_id = data[0].res_users_id;
}, (err) => {
console.log(err)
});
// var fecha = new Date("YYYY-MM-DD").getDate()+1;
this.taskService.getValetParking(this.user_id)
.subscribe((data) => {
if(data[0]!=null){
console.log("Esta esperando su carro ya lo pidio: " + data);
this.activo=true;
}else{
console.log("No esta esperando su carro puedes pedirlo: " + data);
this.activo=false;
}
}, (err) => {
console.log(err)
});
}
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log("PARAMETROS: "+params.user_id)
this.user_id = params.user_id
this.name = params.name,
this.email = params.email,
this.x_descauto = params.x_descauto,
this.x_placas = params.x_placas
});
console.log(this.user_id + " " + this.name + " " +this.email)
this.taskService.getMailActivityTeam(2)
.subscribe((data) => {
this.res_users_id = data[0].res_users_id;
}, (err) => {
console.log(err)
});
// var fecha = new Date("YYYY-MM-DD").getDate()+1;
this.taskService.getValetParking(this.user_id)
.subscribe((data) => {
if(typeof(data[0]) !== "undefined" || data[0]!=null){
console.log("Esta esperando su carro ya lo pidio: " + data);
console.log(data);
this.activo=true;
}else{
console.log("No esta esperando su carro puedes pedirlo: " + data);
this.activo=false;
}
}, (err) => {
// do alerty stuff
console.log(err)
});
}
atras(){
this.navCtrl.back();
}
status: boolean = false;
clickEvent(){
let fecha_hora = new Date().toISOString()
let fecha = new Date("YYYY-MM-DD");
//fecha.setDate(fecha.getDate() + 1)
const setValetParking = {
res_model_id:78,
res_model:"res.partner",
res_id:this.user_id,
res_name:this.name,
activity_type_id:15,
summary:"VALET PARKING",
note:"<p><br></p><table class=\"table table-bordered\"><tbody><tr><td style=\"text-align:center\"><h2><b><h2><font><h2>Tarea</h2></font></h2></b></h2></td><td style=\"text-align:center\"><h2><b><font>Habitación</font></b></h2></td></tr><tr><td>TRAER AUTO</td><td>AUTO:"+this.x_descauto+" <br></br>PLACAS:"+this.x_placas+"<br> HORA DE SOLICTUD:"+ fecha_hora +"</br></td></tr></tbody></table>",
date_deadline:"2021-02-11",
automated:"True",
user_id:this.res_users_id,
recommended_activity_type_id:null,
previous_activity_type_id:null,
create_uid:this.res_users_id,
create_date:fecha_hora,
write_uid:this.res_users_id,
write_date:fecha_hora,
calendar_event_id:null,
team_id:2
};
this.taskService.setValetParking(setValetParking)
.subscribe((newTask) => {
console.log("Haz solicitado pedir tu vehiculo");
this.activo=true;
}, (err) => {
console.log(err)
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavController } from '@ionic/angular';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
@Component({
selector: 'app-iniciarsesionencontrarreservacion',
templateUrl: './iniciarsesionencontrarreservacion.page.html',
styleUrls: ['./iniciarsesionencontrarreservacion.page.scss'],
})
export class IniciarsesionencontrarreservacionPage implements OnInit {
apellido:string;
myValue:any;
ionicForm: FormGroup;
isSubmitted = false;
className: string = 'quitar';
constructor(private router: Router,private navController: NavController,public formBuilder: FormBuilder,) {
this.ionicForm = this.formBuilder.group({
apellido:['', [Validators.required],],
numero:['', [Validators.required],]
})
}
//className: string = 'quitar';
ngOnInit() {
}
get errorControl() {
return this.ionicForm.controls;
}
submitForm() {
this.isSubmitted = true;
console.log(this.ionicForm.valid)
if (!this.ionicForm.valid){
console.log('Please provide all the required values!')
return false;
}else{
//alert('Form Completed' + this.ionicForm.value);
this.router.navigate(['/iniciarsesioncodigo']);
//this.router.navigate(['/principal']);
// const task = {
// nombre: this.ionicForm.value.nombre,
// nombre_2: this.ionicForm.value.nombre2,
// telefono: this.ionicForm.value.telefono,
// celular: this.ionicForm.value.celular,
// mail: this.ionicForm.value.mail,
// persona_contacto: this.ionicForm.value.personaContacto,
// sucursal: this.ionicForm.value.sucursal,
// tipo_empresa: this.ionicForm.value.tipoEmpresa,
// rfc: this.ionicForm.value.rfc,
// persona_fisica: this.ionicForm.value.persona_fisica,
// password: <PASSWORD>,
// status: "0",
// uso_cfdi: this.ionicForm.value.uso_cfdi,
//};
// this.taskService.createTask(task)
// .subscribe((newTask) => {
// // do happy stuff
// alert("Tus datos han sido guardados correctamente")
// }, (err) => {
// // do alerty stuff
// alert(err)
// });
// }
}
}
atras(){
this.navController.back();
}
cancelar(){
if(this.className == 'quitar'){
this.className = 'mostrar';
}else{
this.className = 'quitar';
}
return false;
}
siguiente(){
this.router.navigate(['/crearperfil']);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'xperience',
loadChildren: () => import('./xperience/xperience.module').then( m => m.XperiencePageModule)
},
{
path: 'registro',
loadChildren: () => import('./registro/registro.module').then( m => m.RegistroPageModule)
},
{
path: 'iniciarsesioncodigo',
loadChildren: () => import('./iniciarsesioncodigo/iniciarsesioncodigo.module').then( m => m.IniciarsesioncodigoPageModule)
},
{
path: 'iniciarsesionreservacion',
loadChildren: () => import('./iniciarsesionreservacion/iniciarsesionreservacion.module').then( m => m.IniciarsesionreservacionPageModule)
},
{
path: 'iniciarsesionencontrarreservacion',
loadChildren: () => import('./iniciarsesionencontrarreservacion/iniciarsesionencontrarreservacion.module').then( m => m.IniciarsesionencontrarreservacionPageModule)
},
{
path: 'crearperfil',
loadChildren: () => import('./crearperfil/crearperfil.module').then( m => m.CrearperfilPageModule)
},
{
path: 'inicio',
loadChildren: () => import('./inicio/inicio.module').then( m => m.InicioPageModule)
},
{
path: 'contacto',
loadChildren: () => import('./contacto/contacto.module').then( m => m.ContactoPageModule)
},
{
path: 'perfil',
loadChildren: () => import('./perfil/perfil.module').then( m => m.PerfilPageModule)
},
{
path: 'menu',
loadChildren: () => import('./menu/menu.module').then( m => m.MenuPageModule)
},
{
path: 'terminos',
loadChildren: () => import('./terminos/terminos.module').then( m => m.TerminosPageModule)
},
{
path: 'habitaciones',
loadChildren: () => import('./habitaciones/habitaciones.module').then( m => m.HabitacionesPageModule)
},
{
path: 'calendario',
loadChildren: () => import('./calendario/calendario.module').then( m => m.CalendarioPageModule)
},
{
path: 'parking',
loadChildren: () => import('./parking/parking.module').then( m => m.ParkingPageModule)
},
{
path: 'listadoroomservice',
loadChildren: () => import('./listadoroomservice/listadoroomservice.module').then( m => m.ListadoroomservicePageModule)
},
{
path: 'menuconcierge',
loadChildren: () => import('./menuconcierge/menuconcierge.module').then( m => m.MenuconciergePageModule)
},
{
path: 'menusereia',
loadChildren: () => import('./menusereia/menusereia.module').then( m => m.MenusereiaPageModule)
},
{
path: 'menuquickfit',
loadChildren: () => import('./menuquickfit/menuquickfit.module').then( m => m.MenuquickfitPageModule)
},
{
path: 'iniciologueado',
loadChildren: () => import('./iniciologueado/iniciologueado.module').then( m => m.IniciologueadoPageModule)
},
{
path: 'menulogueado',
loadChildren: () => import('./menulogueado/menulogueado.module').then( m => m.MenulogueadoPageModule)
},
{
path: 'valetparking',
loadChildren: () => import('./valetparking/valetparking.module').then( m => m.ValetparkingPageModule)
},
{
path: 'terminostxt',
loadChildren: () => import('./terminostxt/terminostxt.module').then( m => m.TerminostxtPageModule)
},
{
path: 'mensajegerente',
loadChildren: () => import('./mensajegerente/mensajegerente.module').then( m => m.MensajegerentePageModule)
},
{
path: 'servicios',
loadChildren: () => import('./servicios/servicios.module').then( m => m.ServiciosPageModule)
},
{
path: 'nomolestar',
loadChildren: () => import('./nomolestar/nomolestar.module').then( m => m.NomolestarPageModule)
},
{
path: 'mensajerecepcion',
loadChildren: () => import('./mensajerecepcion/mensajerecepcion.module').then( m => m.MensajerecepcionPageModule)
},
{
path: 'landingsereia',
loadChildren: () => import('./landingsereia/landingsereia.module').then( m => m.LandingsereiaPageModule)
},
{
path: 'landingquickfit',
loadChildren: () => import('./landingquickfit/landingquickfit.module').then( m => m.LandingquickfitPageModule)
},
{
path: 'avisoprivacidad',
loadChildren: () => import('./avisoprivacidad/avisoprivacidad.module').then( m => m.AvisoprivacidadPageModule)
},
{
path: 'reservacion',
loadChildren: () => import('./reservacion/reservacion.module').then( m => m.ReservacionPageModule)
},
{
path: 'datosreservacion',
loadChildren: () => import('./datosreservacion/datosreservacion.module').then( m => m.DatosreservacionPageModule)
},
{
path: 'itinerario',
loadChildren: () => import('./itinerario/itinerario.module').then( m => m.ItinerarioPageModule)
},
{
path: 'politicascancelacion',
loadChildren: () => import('./politicascancelacion/politicascancelacion.module').then( m => m.PoliticascancelacionPageModule)
},
{
path: 'historialviajes',
loadChildren: () => import('./historialviajes/historialviajes.module').then( m => m.HistorialviajesPageModule)
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-historialviajes',
templateUrl: './historialviajes.page.html',
styleUrls: ['./historialviajes.page.scss'],
})
export class HistorialviajesPage implements OnInit {
constructor() { }
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MensajegerentePageRoutingModule } from './mensajegerente-routing.module';
import { MensajegerentePage } from './mensajegerente.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
MensajegerentePageRoutingModule
],
declarations: [MensajegerentePage]
})
export class MensajegerentePageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { HistorialviajesPageRoutingModule } from './historialviajes-routing.module';
import { HistorialviajesPage } from './historialviajes.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HistorialviajesPageRoutingModule
],
declarations: [HistorialviajesPage]
})
export class HistorialviajesPageModule {}
<file_sep>import {
Component,
OnInit
} from '@angular/core';
import {
Router
} from '@angular/router';
import { NavController,AlertController } from '@ionic/angular';
import {
TaskService
} from '../services/task.service';
import {
NativeStorage
} from '@ionic-native/native-storage/ngx';
import {
DatePickerModule
} from 'ionic4-date-picker';
@Component({
selector: 'app-reservacion',
templateUrl: './reservacion.page.html',
styleUrls: ['./reservacion.page.scss'],
})
export class ReservacionPage implements OnInit {
constructor(
private navCtrl: NavController,
private router: Router,
public alertController: AlertController,
private taskService: TaskService,
private nativeStorage:NativeStorage) {}
numeroCantidad: any = 1;
cantidad: any = this.numeroCantidad + " Adulto";
numeroCantidadMenores: any = 0;
cantidadMenores: any = this.numeroCantidadMenores + " Menor";
showbusqueda: any = "";
showcalendariocheckin: any = "";
showcalendariocheckout: any = "";
mostrarencontrar: any = "";
diacheckin: any;
mescheckin: any;
aniocheckin: any;
diacheckout: any;
mescheckout: any;
aniocheckout: any;
monthNames: any = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
"Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
];
fechachekincompleta: any;
fechachekoutcompleta: any;
dateObj: any = new Date();
currentmonth: any = this.dateObj.getUTCMonth(); //months from 1-12
currentday: any = this.dateObj.getUTCDate();
currentyear: any = this.dateObj.getUTCFullYear();
diffInDays: any;
diffInMs: any;
fechaIn: any;
fechaOut: any;
habitaciones: any;
noches:any;
diacheckoutSinver:any;
mescheckoutSinver:any;
aniocheckoutSinver:any;
ngOnInit() {
this.diacheckin = this.currentday;
this.mescheckin = this.monthNames[this.currentmonth];
this.aniocheckin = this.currentyear;
this.diacheckout = this.dateObj.getUTCDate() + 1;
this.mescheckout = this.monthNames[this.currentmonth];
this.aniocheckout = this.currentyear;
this.fechachekincompleta = this.aniocheckin+"-"+(("0" + (this.dateObj.getUTCMonth()+1)).slice(-2))+"-"+this.diacheckin
this.fechachekoutcompleta= this.aniocheckout+"-"+(("0" + (this.dateObj.getUTCMonth()+1)).slice(-2))+"-"+this.diacheckout
// this.fechaIn = this.aniocheckin.toString()+"-"+this.mescheckin.toString()+"-"+this.diacheckin.toString()
// this.fechaOut = this.aniocheckout.toString()+"-"+this.mescheckout.toString()+"-"+this.diacheckout.toString()
// this.diffInMs = new Date(parseDate(this.fechaOut)) - new Date(parseDate(fechaIn))
// this.diffInDays = this.diffInMs / (1000 * 60 * 60 * 24);
// console.log(this.diffInDays)
}
datosreservacion(categoria_id){
this.nativeStorage.getItem('app')
.then(
app => {
console.log("APP NS");
console.log(app);
this.router.navigate(['/datosreservacion'], {
queryParams: {
categoria_id: categoria_id,
fechacheckin:this.fechachekincompleta,
fechacheckout:this.fechachekoutcompleta,
cantidadpersonas: (this.numeroCantidad + this.numeroCantidadMenores),
ninos:this.numeroCantidadMenores,
adultos: this.numeroCantidad
}
});
},
error => {
alert("Es necesario estar registrado para poder realizar una reservación.")
}
);
}
fechaCheckin($event) {
this.mostrarencontrar="hide"
this.showbusqueda=""
var month = $event.getUTCMonth(); //months from 1-12
var day = $event.getUTCDate();
var daycheckout = $event.getUTCDate() + 1;
var year = $event.getUTCFullYear();
this.diacheckin = day;
this.mescheckin = this.monthNames[month];
this.aniocheckin = year
// this.diacheckout = daycheckout;
// this.mescheckout = this.monthNames[month];
// this.aniocheckout = year
this.diacheckoutSinver = day;
this.mescheckoutSinver = this.monthNames[month];
this.aniocheckoutSinver = year
this.fechachekincompleta = this.aniocheckin + "-" + (("0" + ($event.getUTCMonth()+1)).slice(-2)) + "-" + this.diacheckin;
this.fechachekoutcompleta = this.aniocheckoutSinver + "-" + (("0" + ($event.getUTCMonth()+1)).slice(-2)) + "-" + this.diacheckoutSinver
console.log("CHECKIN en fecha checkin" + this.fechachekincompleta)
console.log("CHECKOUT en fecha checkin" + this.fechachekoutcompleta);
var date1 = new Date(this.fechachekincompleta);
var date2 = new Date(this.fechachekoutcompleta);
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
Difference_In_Days = Math.trunc(Difference_In_Days)
this.noches = ", "+Difference_In_Days + " Noche(s)";
//To display the final no. of days (result)
// alert("Total numero de dias entre fechas <br>"
// + date1 + "<br> y <br>"
// + date2 + " is: <br> "
// + Difference_In_Days);
var date3 = new Date(this.fechachekincompleta);
var date4 = new Date();
// To calculate the time difference of two dates
var Difference_In_Time2 = date3.getTime() - date4.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time2 / (1000 * 3600 * 24);
// To calculate the time difference of two dates
Difference_In_Days = Math.trunc(Difference_In_Days)
if(Difference_In_Days <0){
this.alertCheckin();
this.mostrarencontrar="hide"
//this.showbusqueda=""
}else{
//this.mostrarencontrar=""
}
}
async alertCheckin() {
const alert = await this.alertController.create({
cssClass: 'class_alert',
header: 'Mensaje de XPERIENCE',
//subHeader: 'Subtitle',
message: 'Fecha del CHECKIN debe ser igual o mayor a la fecha de hoy.',
buttons: ['OK']
});
await alert.present();
}
async alertCheckout() {
const alert = await this.alertController.create({
cssClass: 'class_alert',
header: 'Mensaje de XPERIENCE',
//subHeader: 'Subtitle',
message: 'Fecha del CHECKOUT debe ser mayor a la fecha del CHECKIN y Fecha CHECKIN Mayor al dia de hoy.',
buttons: ['OK']
});
await alert.present();
}
fechaCheckout($event) {
var month = $event.getUTCMonth(); //months from 1-12
var day = $event.getUTCDate();
var year = $event.getUTCFullYear();
this.diacheckout = day;
this.mescheckout = this.monthNames[month];
this.aniocheckout = year
this.fechachekoutcompleta = this.aniocheckout + "-" + (("0" + ($event.getUTCMonth()+1)).slice(-2)) + "-" + this.diacheckout
console.log("CHECKIN en fecha checkout" + this.fechachekincompleta)
console.log("CHECKOUT en fecha checkin" + this.fechachekoutcompleta);
var date1 = new Date(this.fechachekincompleta);
var date2 = new Date(this.fechachekoutcompleta);
// To calculate the time difference of two dates
var Difference_In_Time = date1.getTime() - date2.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
Difference_In_Days = Math.trunc(Difference_In_Days)
this.noches = ", "+Difference_In_Days + " Noche(s)";
console.log(Difference_In_Days+"FECHA 1")
var date3 = new Date();//dia actual
var Difference_In_Time2 = date2.getTime() - date3.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days2 = Difference_In_Time2 / (1000 * 3600 * 24);
Difference_In_Days2 = Math.trunc(Difference_In_Days2)
console.log(Difference_In_Days2+" FECHA 2")
if(Difference_In_Days2<0){
console.log(Difference_In_Days2+" FECHA 2 2")
}
if(Difference_In_Days >0 || Difference_In_Days2<=0){
this.alertCheckout();
this.mostrarencontrar="hide"
this.showbusqueda=""
}else{
this.mostrarencontrar=""
}
}
mostrarCheckin() {
if (this.showcalendariocheckin == "") {
this.showcalendariocheckin = "showCal"
this.showcalendariocheckout = ""
} else {
this.showcalendariocheckin = ""
}
}
mostrarCheckout() {
if (this.showcalendariocheckout == "") {
this.showcalendariocheckout = "showCal"
this.showcalendariocheckin = ""
} else {
this.showcalendariocheckout = ""
}
}
busqueda() {
// if (this.showbusqueda == "") {
this.taskService.getHabitaciones(this.fechachekincompleta, this.fechachekoutcompleta,(this.numeroCantidad + this.numeroCantidadMenores))
.subscribe(habitaciones => {
this.habitaciones = habitaciones
var date1 = new Date(this.fechachekincompleta);
var date2 = new Date(this.fechachekoutcompleta);
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
Difference_In_Days = Math.trunc(Difference_In_Days)
this.noches = ", "+Difference_In_Days + " Noche(s)";
//To display the final no. of days (result)
// alert("Total numero de dias entre fechas <br>"
// + date1 + "<br> y <br>"
// + date2 + " is: <br> "
// + Difference_In_Days);
this.showbusqueda = "show";
//$('#divHabitaciones').scrollTop(); //TODO activar jquery para hacer el scroll
setTimeout(function(){
document.getElementById("divHabitaciones").scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 500);
});
// } else {
// //this.showbusqueda="";
// }
}
atras() {
this.navCtrl.back();
}
mas() {
if((this.numeroCantidad + this.numeroCantidadMenores) <=3 ){
this.numeroCantidad += 1
if (this.numeroCantidad > 1) {
this.cantidad = this.numeroCantidad + " Adultos";
} else {
this.cantidad = this.numeroCantidad + " Adulto";
}
}
}
menos() {
if((this.numeroCantidad + this.numeroCantidadMenores) <=4 ){
if (this.numeroCantidad > 1) {
this.numeroCantidad -= 1
if (this.numeroCantidad >= 2) {
this.cantidad = this.numeroCantidad + " Adultos";
} else {
this.cantidad = this.numeroCantidad + " Adulto";
}
}
}
}
masMenores() {
if((this.numeroCantidad + this.numeroCantidadMenores) <=3 ){
this.numeroCantidadMenores += 1
if (this.numeroCantidadMenores > 1) {
this.cantidadMenores = this.numeroCantidadMenores + " Menores";
} else {
this.cantidadMenores = this.numeroCantidadMenores + " Menor";
}
}
}
menosMenores() {
if (this.numeroCantidadMenores > 0) {
if((this.numeroCantidad + this.numeroCantidadMenores) <=4 ){
this.numeroCantidadMenores -= 1
if (this.numeroCantidadMenores >= 2) {
this.cantidadMenores = this.numeroCantidadMenores + " Menores";
} else {
this.cantidadMenores = this.numeroCantidadMenores + " Menor";
}
}
}
}
}<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { ValetparkingPageRoutingModule } from './valetparking-routing.module';
import { ValetparkingPage } from './valetparking.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ValetparkingPageRoutingModule
],
declarations: [ValetparkingPage]
})
export class ValetparkingPageModule {}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { ListadoroomservicePage } from './listadoroomservice.page';
describe('ListadoroomservicePage', () => {
let component: ListadoroomservicePage;
let fixture: ComponentFixture<ListadoroomservicePage>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ListadoroomservicePage ],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(ListadoroomservicePage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, ElementRef, OnInit, ViewChild,Renderer2} from '@angular/core';
import { NavController,Platform } from '@ionic/angular';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
interface Marker {
position: {
lat: number,
lng: number,
};
title: string;
}
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public items = ["../assets/images/introimg1.jpg",
// "../assets/images/introimg2.jpg",
"../assets/images/introimg3.jpg",
// "../assets/images/introimg4.jpg",
// "../assets/images/introimg5.jpg",
"../assets/images/introimg6.jpg",
//"../assets/images/introimg7.jpg"
];
public items2 = [
{
titulo:"¡Bienvenido!",
subtitulo:"Tu Xperiencia en un solo lugar",
saltar:"SALTAR",
siguiente:"SIGUIENTE"
},
// {
// titulo:"",
// subtitulo:"Una sección para cada viaje. Podrás también descubrir nuestras actividades y tipos de alojamientos.",
// saltar:"SALTAR",
// siguiente:"SIGUIENTE"
// },
{
titulo:"",
subtitulo:"Tus Xperiencias viven aqui, siempre en un solo toque.",
saltar:"SALTAR",
siguiente:"SIGUIENTE"
},
// {
// titulo:"",
// subtitulo:"Consulta tus viajes y agrega actividades, reservaciones en restaurantes o entrenamientos.",
// saltar:"SALTAR",
// siguiente:"SIGUIENTE"
// },
// {
// titulo:"",
// subtitulo:"Chatea con nosotros en cualquier momento, en cualquier idioma, para informes o una requisición especial.",
// saltar:"SALTAR",
// siguiente:"SIGUIENTE"
// },
{
titulo:"",
subtitulo:"Nuestro exclusivo concierge digital es toda una Xperiencia.",
saltar:"SALTAR",
siguiente:"SIGUIENTE"
},
// {
// titulo:"",
// subtitulo:"Tu perfil y preferencias siempre a la mano para que hagas de tu estadía la mejor Xperiencia.",
// saltar:"SALTAR",
// siguiente:"SIGUIENTE"
// },
];
public sliderOptions = {
initialSlide: 0,
slidesPerView: 1,
autoplay:false,
mousewheel: true,
cssMode: false,
allowTouchMove: false,
//Con el pagination asi no los muestra
pagination: {
clickable: true,
}
};
public sliderOptions2 = {
initialSlide: 0,
slidesPerView: 1,
autoplay:false,
allowTouchMove: false
//Si quito el pagination muestra los bullets pero no deja dar click
// pagination: {
// clickable: true,
// }
//Con el pagination asi los muestra y deja dar click
// pagination: {
// el: ".swiper-pagination",
// type: "bullets",
// clickable: true
// }
};
constructor(public navCtrl: NavController,private renderer: Renderer2,
private nativeStorage:NativeStorage,public platform:Platform) {
this.platform.ready().then(() => {
this.nativeStorage.getItem('saltarIntro')
.then(
saltarIntro => {
this.navCtrl.navigateRoot("inicio");
},
error =>{
this.nativeStorage.setItem('saltarIntro', {
status:true
}).then(
() => {},
);
}
);
});
}
@ViewChild('slides') slides;
@ViewChild('slides2') slides2;
@ViewChild("content_atras") content_atras: ElementRef;
bandera: boolean;
ngOnInit() {
this.bandera=false;
}
nextSlide() {
this.slides.slideNext();
this.slides2.slideNext();
}
prevSlide() {
this.slides.slidePrev();
this.slides2.slidePrev();
}
slideChanged(){
this.slides.getActiveIndex().then(index => {
// console.log(index);
// console.log('currentIndex:', index);
this.slides2.slideTo(index);
//console.log(this.slides.length)
if(index==2){
this.addMyClass();
this.bandera=true;
}
// OR this.slides.slideTo(index + 1);
});
}
slideChanged2(){
this.slides2.getActiveIndex().then(index => {
// console.log(index);
// console.log('currentIndex2:', index);
this.slides.slideTo(index);
// OR this.slides.slideTo(index + 1);
});
}
addMyClass(){
//this.myButton.nativeElement.classList.add("my-class"); //BAD PRACTICE
this.renderer.addClass(this.content_atras.nativeElement, "quitSaltar");
}
xperience(){
this.navCtrl.navigateRoot("xperience")
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { AvisoprivacidadPageRoutingModule } from './avisoprivacidad-routing.module';
import { AvisoprivacidadPage } from './avisoprivacidad.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
AvisoprivacidadPageRoutingModule
],
declarations: [AvisoprivacidadPage]
})
export class AvisoprivacidadPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MenusereiaPageRoutingModule } from './menusereia-routing.module';
import { MenusereiaPage } from './menusereia.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
MenusereiaPageRoutingModule
],
declarations: [MenusereiaPage]
})
export class MenusereiaPageModule {}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { IniciarsesioncodigoPageRoutingModule } from './iniciarsesioncodigo-routing.module';
import { IniciarsesioncodigoPage } from './iniciarsesioncodigo.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
ReactiveFormsModule,
IniciarsesioncodigoPageRoutingModule
],
declarations: [IniciarsesioncodigoPage]
})
export class IniciarsesioncodigoPageModule {}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
import { Router } from '@angular/router';
import { AlertController, NavController } from '@ionic/angular';
import { SMS } from '@ionic-native/sms/ngx';
import { TaskService } from '../services/task.service';
@Component({
selector: 'app-mensajegerente',
templateUrl: './mensajegerente.page.html',
styleUrls: ['./mensajegerente.page.scss'],
})
export class MensajegerentePage implements OnInit {
ionicForm: FormGroup;
isSubmitted = false;
celularGerente:any;
constructor(public alertController: AlertController,private router: Router,private taskService: TaskService,
private navController: NavController,public formBuilder: FormBuilder,private sms: SMS) {
this.ionicForm = this.formBuilder.group({
mensaje: ['', [Validators.required]]
});
}
ngOnInit() {
this.taskService.getMailActivityTeam(5)
.subscribe((data) => {
console.log("ngOnInit getMailActivityTeam: "+data[0].res_users_id);
this.taskService.getResUsers(data[0].res_users_id)
.subscribe((data) => {
console.log("ngOnInit getResUsers: "+data[0].partner_id);
this.taskService.getResPartnerPhone(data[0].partner_id)
.subscribe((data) => {
console.log("ngOnwillEnter getResPartnerPhone: "+data[0].mobile);
this.celularGerente = data[0].mobile
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});
}
ngOnwillEnter(){
this.taskService.getMailActivityTeam(5)
.subscribe((data) => {
console.log("ngOnInit getMailActivityTeam: "+data[0].res_users_id);
this.taskService.getResUsers(data[0].res_users_id)
.subscribe((data) => {
console.log("ngOnInit getResUsers: "+data[0].partner_id);
this.taskService.getResPartnerPhone(data[0].partner_id)
.subscribe((data) => {
console.log("ngOnwillEnter getResPartnerPhone: "+data[0].mobile);
this.celularGerente = data[0].mobile
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});
}
get errorControl() {
return this.ionicForm.controls;
}
submitForm() {
this.isSubmitted = true;
console.log(this.ionicForm.valid)
if (!this.ionicForm.valid){
console.log('Captura los valores requeridos');
return false;
}else{
this.celularGerente = this.celularGerente
let celular2 = "6692124207";
this.sms.send([celular2,this.celularGerente],this.ionicForm.value.mensaje).then(val => {
this.presentAlertConfirm();
});
}
}
async presentAlertConfirm() {
const alert = await this.alertController.create({
cssClass: 'my-custom-class',
header: 'Mensaje',
message: 'Mensaje enviado',
buttons: [
{
text: 'Aceptar',
handler: () => {
console.log('Confirm Okay');
this.router.navigate(['/menuconcierge']);
}
}
]
});
await alert.present();
}
atras(){
this.navController.back();
}
}
<file_sep>import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, NavController,Platform } from '@ionic/angular';
import { FormGroup, FormBuilder, Validators, FormControl } from "@angular/forms";
import { TaskService } from '../services/task.service';
import { Login } from '../interfaces/task';
import {Md5} from 'ts-md5/dist/md5';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
@Component({
selector: 'app-registro',
templateUrl: './registro.page.html',
styleUrls: ['./registro.page.scss'],
})
export class RegistroPage implements OnInit {
condition:boolean = true;
condition2:boolean;
correo:string;
password:string;
myValue:any;
ionicForm: FormGroup;
isSubmitted = false;
className: string = 'quitar';
login: Login[] = [];
@ViewChild('borra') private draggableElement: ElementRef;
constructor(private router: Router,private navCtrl: NavController,
public formBuilder: FormBuilder,private taskService: TaskService,
public alertController: AlertController,private nativeStorage:NativeStorage,
public platform:Platform) {
this.platform.ready().then(() => {
this.nativeStorage.getItem('user_id')
.then(
user_id => {
console.log("INI user_id")
console.log(user_id)
},
error => console.error("NO HAY USER_ID")
);
this.nativeStorage.setItem("user_id",55).then(()=>{console.log("Se guardo user_id")},error=>console.log("No se guardo el user_ud"));
this.nativeStorage.getItem("user_id").
then(
user_id=>{
console.log("user_id");
console.log(user_id)
},
error=>console.error("No hay user_id")
);
});
this.ionicForm = this.formBuilder.group({
correo:['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')]],
password:['', [Validators.required]]
})
}
ngOnInit() {
}
registro(){
this.router.navigate(['crearperfil'])
}
correof(){
this.condition=true;
this.condition2=false;
//this.celular = "000000000"
}
celularf(){
this.condition = false;
this.condition2 = true;
this.correo = "<EMAIL>"
}
atras(){
this.router.navigate(['xperience'])
}
get errorControl() {
return this.ionicForm.controls;
}
async presentAlert() {
const alert = await this.alertController.create({
cssClass: 'class_alert',
//header: 'Alert',
//subHeader: 'Subtitle',
message: 'Usuario y/o contraseña incorrecta',
buttons: ['OK']
});
await alert.present();
}
submitForm() {
this.isSubmitted = true;
console.log("Campos correctos en login (LOGUEADO)"+this.ionicForm.valid)
if (!this.ionicForm.valid){
console.log('Please provide all the required values!')
return false;
}else{
console.log("No Existe: "+this.ionicForm.value.password +" "+ Md5.hashStr("<PASSWORD>"));
this.ionicForm.value.password = <PASSWORD>(this.ionicForm.value.password)
this.taskService.getLogin(this.ionicForm.value.correo,this.ionicForm.value.password)
.subscribe((data) => {
if(data[0]!=null){
this.nativeStorage.setItem('app', {
user_id:data[0].id,
name:data[0].name,
email:data[0].email,
x_descauto:data[0].x_descauto,
x_placas:data[0].x_plac
}).then(
() => {
console.log('Se actualizo la informacion APP')
this.navCtrl.navigateRoot(['/iniciologueado'], {
queryParams: {
user_id: data[0].id,
name:data[0].name,
email:data[0].email,
x_descauto:data[0].x_descauto,
x_placas:data[0].x_placas
}
});
},
error => console.error('Error al actualizar la informacion APP', error)
);
}else{
this.presentAlert();
}
}, (err) => {
alert(err)
});
}
}
siguiente(){
}
} | 09ee60d3524997a5889ce95eb71c4d43859cc56c | [
"TypeScript",
"HTML"
] | 44 | TypeScript | pedrobuelna/xperiencelimpio | 51165d35be861361f833b264e38e87dfeb56118d | c05b5a24419846cf70fecfd74924e382e6b47cd2 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>roomeeting</artifactId>
<groupId>fr.exanpe.roomeeting</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>roomeeting-site</artifactId>
<packaging>pom</packaging>
<name>roomeeting-site</name>
<description>Project RooMeeting</description>
<properties>
<github.global.server>github</github.global.server>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>2.0.1</version>
<configuration>
<generateReports>false</generateReports>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>maven-dependency-plugin</id>
<phase>generate-sources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifact>${project.groupId}:roomeeting-web:${project.version}:war</artifact>
<transitive>false</transitive>
<outputDirectory>${project.build.directory}/tmp</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<id>maven-antrun-plugin</id>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
<configuration>
<target>
<echo>Copying bin...</echo>
<copy file="${basedir}/src/site/base/roomeeting-bin.zip" tofile="${project.build.directory}/to_upload/bin/roomeeting-bin.zip"/>
<echo>Enriching zip...</echo>
<zip destfile="${project.build.directory}/to_upload/bin/roomeeting-bin.zip" update="true">
<zipfileset file="${project.build.directory}/tmp/roomeeting-web-${project.version}.war" fullpath="roomeeting/webapps/roomeeting.war"/>
<zipfileset dir="${basedir}/../roomeeting-classpath/src/main/resources/" prefix="roomeeting/roomeeting-conf/"/>
</zip>
<echo>Complete</echo>
</target>
</configuration>
</plugin>
<plugin>
<groupId>com.github.github</groupId>
<artifactId>site-maven-plugin</artifactId>
<version>0.8</version>
<configuration>
<message>Creating site for ${project.version}</message>
</configuration>
<executions>
<execution>
<phase>site</phase>
<goals>
<goal>site</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<!--
TODO : activer apres avoir builder la configuration de reporting
<extensions>
<extension>
<groupId>${project.groupId}</groupId>
<artifactId>roomeeting-conf-reporting</artifactId>
<version>1.0.0</version>
</extension>
</extensions>
-->
</build>
</project><file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import fr.exanpe.roomeeting.common.enums.ParameterEnum;
import fr.exanpe.roomeeting.common.exception.BusinessException;
import fr.exanpe.roomeeting.common.exception.HackException;
import fr.exanpe.roomeeting.common.exception.TechnicalException;
import fr.exanpe.roomeeting.common.utils.RoomDateUtils;
import fr.exanpe.roomeeting.domain.business.BookingManager;
import fr.exanpe.roomeeting.domain.business.ParameterManager;
import fr.exanpe.roomeeting.domain.business.consts.ErrorMessages;
import fr.exanpe.roomeeting.domain.business.dao.BookingDAO;
import fr.exanpe.roomeeting.domain.business.dto.DateAvailabilityDTO;
import fr.exanpe.roomeeting.domain.business.dto.RoomAvailabilityDTOBuilder;
import fr.exanpe.roomeeting.domain.business.dto.TimeSlot;
import fr.exanpe.roomeeting.domain.business.filters.RoomFilter;
import fr.exanpe.roomeeting.domain.core.business.impl.DefaultManagerImpl;
import fr.exanpe.roomeeting.domain.core.dao.CrudDAO;
import fr.exanpe.roomeeting.domain.core.dao.QueryParameters;
import fr.exanpe.roomeeting.domain.model.Booking;
import fr.exanpe.roomeeting.domain.model.Gap;
import fr.exanpe.roomeeting.domain.model.Room;
import fr.exanpe.roomeeting.domain.model.User;
@Service
public class BookingManagerImpl extends DefaultManagerImpl<Booking, Long> implements BookingManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(BookingManagerImpl.class);
@Autowired
private BookingDAO bookingDAO;
@PersistenceContext
protected EntityManager entityManager;
@Autowired
private ParameterManager parameterManager;
@Autowired
private CrudDAO crudDAO;
@Override
public void delete(Long id)
{
throw new NotImplementedException("Use deleteBooking to ensure database coherency");
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<DateAvailabilityDTO> searchRoomAvailable(RoomFilter filter)
{
int days = 0;
int daysSearch = filter.getExtendDays();
List<Room> rooms = null;
Date dateSearch = filter.getDate();
while (CollectionUtils.isEmpty(rooms) && days <= daysSearch)
{
if (days > 0)
{
if (filter.isExtendWorkingOnly())
{
dateSearch = RoomDateUtils.nextWorkingDay(filter.getDate());
}
else
{
dateSearch = RoomDateUtils.nextWorkingDay(filter.getDate());
}
}
// anterior date
Date toDate = RoomDateUtils.setHourMinutes(dateSearch, filter.getRestrictTo().getHours(), filter.getRestrictTo().getMinutes());
if (toDate.before(new Date()))
{
days++;
continue;
}
// TODO ajouter restrict from et to
// TODO do not check previous dates...
rooms = bookingDAO.searchRoomAvailable(filter, dateSearch);
days++;
}
if (CollectionUtils.isEmpty(rooms)) { return new ArrayList<DateAvailabilityDTO>(); }
List<Gap> gaps = crudDAO.findWithNamedQuery(
Room.FIND_GAPS_FOR_DATE,
QueryParameters.with("date", dateSearch).and("rooms", rooms).and("startTime", toTime(dateSearch, filter.getRestrictFrom()))
.and("endTime", toTime(dateSearch, filter.getRestrictTo())).parameters());
return consolidateRoomAndGaps(rooms, gaps, dateSearch);
}
private List<DateAvailabilityDTO> consolidateRoomAndGaps(List<Room> rooms, List<Gap> gaps, Date dateSearch)
{
RoomAvailabilityDTOBuilder builder = RoomAvailabilityDTOBuilder.create();
for (Room room : rooms)
{
builder.organise(room, dateSearch);
}
for (Gap gap : gaps)
{
builder.organise(gap, dateSearch);
}
return builder.getResult();
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Gap findGap(Long gapId)
{
return crudDAO.find(Gap.class, gapId);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Booking findWithRoomUser(Long id, User user)
{
Booking booking = findSecured(id, user);
if (booking == null) { return null; }
booking.getUser();
booking.getRoom();
return booking;
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Booking> listUserFuturesBookings(User u)
{
return crudDAO.findWithNamedQuery(Booking.LIST_USER_FUTURES_BOOKINGS, QueryParameters.with("user", u).parameters());
}
@Override
public List<Booking> listUserPastsBookings(User user)
{
// TODO max as parameter
return crudDAO.findMaxResultsWithNamedQuery(Booking.LIST_USER_PASTS_BOOKINGS, QueryParameters.with("user", user).parameters(), 5);
}
// TODO trash TimeSlot ?
@Override
public Booking processBooking(User user, Gap bookGap, TimeSlot from, TimeSlot to) throws BusinessException
{
List<Gap> gaps = crudDAO.findWithNamedQuery(Gap.FIND_GAP_AROUND_TIMESLOT, QueryParameters.with("date", bookGap.getDate())
.and("room", bookGap.getRoom()).and("startTime", toTime(bookGap.getDate(), from)).and("endTime", toTime(bookGap.getDate(), from)).parameters());
// no gap around... check for a booking
if (CollectionUtils.isEmpty(gaps))
{
if (CollectionUtils.isNotEmpty(crudDAO.findWithNamedQuery(
Booking.FIND_BOOKING_FOR_DATE,
QueryParameters.with("date", bookGap.getDate()).and("room", bookGap.getRoom()).parameters()))) { throw new TechnicalException(
ErrorMessages.INCONSISTENT_DATABASE); }
return bookEmptyDay(user, bookGap, from, to);
}
if (gaps.size() > 1) { throw new TechnicalException(ErrorMessages.INCONSISTENT_DATABASE); }
return bookOnGap(gaps.get(0), user, bookGap, from, to);
}
private Booking bookOnGap(Gap gap, User user, Gap bookGap, TimeSlot from, TimeSlot to)
{
boolean onGapBound = false;
boolean perfectMatch = false;
// booking start on last booking end
if (from.getHours() == gap.getStartHour() && from.getMinutes() == gap.getStartMinute())
{
// alter gap
gap.setStartHour(to.getHours());
gap.setStartMinute(to.getMinutes());
onGapBound = true;
}
// booking end on next booking start
if (to.getHours() == gap.getEndHour() && to.getMinutes() == gap.getEndMinute())
{
// alter gap
gap.setEndHour(from.getHours());
gap.setEndMinute(from.getMinutes());
perfectMatch = onGapBound;
onGapBound = true;
}
if (onGapBound)
{
if (perfectMatch)
{
crudDAO.delete(Gap.class, gap.getId());
}
else
{
crudDAO.update(gap);
}
}
else
{
Gap gapEnd = new Gap();
gapEnd.setDate(bookGap.getDate());
gapEnd.setStartHour(to.getHours());
gapEnd.setStartMinute(to.getMinutes());
gapEnd.setEndHour(gap.getEndHour());
gapEnd.setEndMinute(gap.getEndMinute());
gapEnd.setRoom(bookGap.getRoom());
crudDAO.create(gapEnd);
// booking in the middle of a gap
gap.setEndHour(from.getHours());
gap.setEndMinute(from.getMinutes());
crudDAO.update(gap);
}
Booking booking = new Booking();
booking.setDate(bookGap.getDate());
booking.setStartHour(from.getHours());
booking.setStartMinute(from.getMinutes());
booking.setEndHour(to.getHours());
booking.setEndMinute(to.getMinutes());
booking.setRoom(bookGap.getRoom());
booking.setUser(user);
booking = crudDAO.create(booking);
return booking;
}
public Booking findSecured(Long id, User u)
{
try
{
return crudDAO.findUniqueWithNamedQuery(Booking.FIND_WITH_USER, QueryParameters.with("id", id).and("user", u).parameters());
}
catch (EmptyResultDataAccessException e)
{
throw new HackException(e);
}
}
public void deletePastBooking(Long id)
{
super.delete(id);
}
@Override
public void deleteBooking(Long id, User u)
{
Booking booking = findSecured(id, u);
Gap replacementGap = null;
// before is never deleted
if (!isFirstHour(booking.getStartHour(), booking.getStartMinute()))
{
List<Gap> gaps = crudDAO.findWithNamedQuery(Gap.FIND_GAP_FOR_TIME, QueryParameters.with("room", booking.getRoom()).and("date", booking.getDate())
.and("time", RoomDateUtils.setHourMinutes(new Date(), booking.getStartHour(), booking.getStartMinute())).parameters());
if (CollectionUtils.isNotEmpty(gaps))
{
if (gaps.size() > 1) { throw new TechnicalException(ErrorMessages.INCONSISTENT_DATABASE); }
replacementGap = gaps.get(0);
// detach for buffer manipulation
entityManager.detach(replacementGap);
replacementGap.setEndHour(booking.getEndHour());
replacementGap.setEndMinute(booking.getEndMinute());
}
}
// got something after
if (!isLastHour(booking.getEndHour(), booking.getEndMinute()))
{
List<Gap> gaps = crudDAO.findWithNamedQuery(Gap.FIND_GAP_FOR_TIME, QueryParameters.with("room", booking.getRoom()).and("date", booking.getDate())
.and("time", RoomDateUtils.setHourMinutes(new Date(), booking.getEndHour(), booking.getEndMinute())).parameters());
if (CollectionUtils.isNotEmpty(gaps))
{
if (gaps.size() > 1) { throw new TechnicalException(ErrorMessages.INCONSISTENT_DATABASE); }
Gap afterGap = gaps.get(0);
if (replacementGap != null)
{
replacementGap.setEndHour(afterGap.getEndHour());
replacementGap.setEndMinute(afterGap.getEndMinute());
entityManager.remove(afterGap);
}
else
{
replacementGap = afterGap;
replacementGap.setStartHour(booking.getStartHour());
replacementGap.setStartMinute(booking.getStartMinute());
}
}
}
// booking between 2 bookings
if (replacementGap == null)
{
replacementGap = new Gap();
replacementGap.setDate(booking.getDate());
replacementGap.setRoom(booking.getRoom());
replacementGap.setStartHour(booking.getStartHour());
replacementGap.setStartMinute(booking.getStartMinute());
replacementGap.setEndHour(booking.getEndHour());
replacementGap.setEndMinute(booking.getEndMinute());
crudDAO.create(replacementGap);
}
else
{
crudDAO.update(replacementGap);
}
entityManager.remove(booking);
}
public int purgeGaps()
{
return entityManager.createNamedQuery(Gap.PURGE).executeUpdate();
}
private Booking bookEmptyDay(User user, Gap bookGap, TimeSlot from, TimeSlot to)
{
// booking
Booking booking = new Booking();
booking.setDate(bookGap.getDate());
booking.setStartHour(from.getHours());
booking.setStartMinute(from.getMinutes());
booking.setEndHour(to.getHours());
booking.setEndMinute(to.getMinutes());
booking.setRoom(bookGap.getRoom());
booking.setUser(user);
booking = crudDAO.create(booking);
if (!isFirstHour(from))
{
// before
Gap before = new Gap();
before.setDate(bookGap.getDate());
before.setStartHour(parameterManager.findInteger(ParameterEnum.HOUR_DAY_START));
before.setStartMinute(0);
before.setEndHour(from.getHours());
before.setEndMinute(from.getMinutes());
before.setRoom(bookGap.getRoom());
crudDAO.create(before);
}
if (!isLastHour(to))
{
// after
Gap after = new Gap();
after.setDate(bookGap.getDate());
after.setStartHour(to.getHours());
after.setStartMinute(to.getMinutes());
after.setEndHour(parameterManager.findInteger(ParameterEnum.HOUR_DAY_END));
after.setEndMinute(0);
after.setRoom(bookGap.getRoom());
crudDAO.create(after);
}
return booking;
}
private boolean isFirstHour(int hour, int minute)
{
return hour == parameterManager.findInteger(ParameterEnum.HOUR_DAY_START) && minute == 0;
}
private boolean isFirstHour(TimeSlot ts)
{
return isFirstHour(ts.getHours(), ts.getMinutes());
}
private boolean isLastHour(int hour, int minute)
{
return hour == parameterManager.findInteger(ParameterEnum.HOUR_DAY_END) && minute == 0;
}
private boolean isLastHour(TimeSlot ts)
{
return isLastHour(ts.getHours(), ts.getMinutes());
}
private Date toTime(Date d, TimeSlot ts)
{
return RoomDateUtils.setHourMinutes(d, ts.getHours(), ts.getMinutes());
}
}
<file_sep>package fr.exanpe.roomeeting.web.pages.book;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.internal.SelectModelImpl;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.common.enums.ParameterEnum;
import fr.exanpe.roomeeting.common.utils.RoomDateUtils;
import fr.exanpe.roomeeting.domain.business.BookingManager;
import fr.exanpe.roomeeting.domain.business.ParameterManager;
import fr.exanpe.roomeeting.domain.business.SiteManager;
import fr.exanpe.roomeeting.domain.business.UserManager;
import fr.exanpe.roomeeting.domain.business.dto.DateAvailabilityDTO;
import fr.exanpe.roomeeting.domain.business.dto.SearchAvailabilityDTO;
import fr.exanpe.roomeeting.domain.business.dto.TimeSlot;
import fr.exanpe.roomeeting.domain.business.filters.RoomFilter;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
import fr.exanpe.roomeeting.web.services.SelectTimeSlotService;
import fr.exanpe.t5.lib.annotation.ContextPageReset;
public class Search
{
private static final String KEY_NO_RESULT = "no-result";
private static final String KEY_DATE_BEFORE_AFTER = "date-before-after";
@Inject
private UserManager userManager;
@Inject
private SiteManager siteManager;
@Inject
private BookingManager bookingManager;
@Inject
private ParameterManager parameterManager;
@Inject
private SelectTimeSlotService selectHoursService;
@Inject
private RooMeetingSecurityContext securityContext;
@SessionAttribute
private SearchAvailabilityDTO search;
@Persist
@Property
private RoomFilter filter;
@Property
@Persist
private SelectModel sitesSelectModel;
@Property
@Persist
private SelectModel hoursModel;
@Property
@Persist(PersistenceConstants.FLASH)
private boolean noResult;
void onActivate()
{
if (filter == null)
{
filter = new RoomFilter();
filter.setSite(userManager.findDefaultSite(securityContext.getUser()));
}
if (sitesSelectModel == null)
{
List<Site> sites = siteManager.list();
if (CollectionUtils.isNotEmpty(sites))
{
OptionModel[] oms = new OptionModel[sites.size()];
for (int i = 0; i < sites.size(); i++)
{
oms[i] = new OptionModelImpl(sites.get(i).getName(), sites.get(i).getId());
}
sitesSelectModel = new SelectModelImpl(oms);
}
}
if (hoursModel == null)
{
hoursModel = selectHoursService.create(false);
int start = parameterManager.find(ParameterEnum.HOUR_DAY_START.getCode()).getIntegerValue();
int end = parameterManager.find(ParameterEnum.HOUR_DAY_END.getCode()).getIntegerValue();
filter.setRestrictFrom(new TimeSlot(start, 0));
filter.setRestrictTo(new TimeSlot(end, 0));
}
}
@ContextPageReset
void reset()
{
filter = null;
sitesSelectModel = null;
hoursModel = null;
search = null;
}
@BeginRender
void begin()
{
// date already passed... change day
if (RoomDateUtils.setHourMinutes(filter.getDate(), filter.getRestrictTo().getHours(), filter.getRestrictTo().getMinutes()).before(new Date()))
{
filter.setDate(RoomDateUtils.nextWorkingDay(new Date()));
}
// date from is passed, adjust it
if (RoomDateUtils.setHourMinutes(filter.getDate(), filter.getRestrictFrom().getHours(), filter.getRestrictTo().getMinutes()).before(new Date()))
{
filter.setRestrictFrom(new TimeSlot(Calendar.getInstance().get(Calendar.HOUR_OF_DAY), 0));
}
}
@InjectComponent
private Form searchForm;
@OnEvent(value = EventConstants.VALIDATE, component = "searchForm")
void validateSearch() throws ValidationException
{
if (!filter.getRestrictFrom().before(filter.getRestrictTo()))
{
searchForm.recordError(messages.get("search-error-before-after"));
}
if (RoomDateUtils.setHourMinutes(filter.getDate(), filter.getRestrictFrom().getHours(), filter.getRestrictFrom().getMinutes()).before(new Date()))
{
searchForm.recordError(messages.get("search-error-past"));
}
if (filter.getCapacity() < 0)
{
searchForm.recordError(messages.get("search-error-capacity"));
}
}
@OnEvent(value = EventConstants.SUCCESS)
public Object search()
{
List<DateAvailabilityDTO> list = bookingManager.searchRoomAvailable(filter);
if (CollectionUtils.isEmpty(list))
{
noResult = true;
return this;
}
search = new SearchAvailabilityDTO(list, filter);
return Choose.class;
}
@Inject
private Messages messages;
public String toStringDate(Date d)
{
return FastDateFormat.getInstance(messages.get("date-format")).format(d);
}
public Date getToday()
{
// last hour allowed
Calendar lastHour = Calendar.getInstance();
lastHour.set(Calendar.HOUR_OF_DAY, parameterManager.find(ParameterEnum.HOUR_DAY_END.getCode()).getIntegerValue() - 1);
if (Calendar.getInstance().after(lastHour)) { return RoomDateUtils.nextWorkingDay(new Date()); }
return new Date();
}
}
<file_sep>package fr.exanpe.roomeeting.web.services;
import java.util.Calendar;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.internal.OptionModelImpl;
import org.apache.tapestry5.internal.SelectModelImpl;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.common.enums.ParameterEnum;
import fr.exanpe.roomeeting.domain.business.ParameterManager;
import fr.exanpe.roomeeting.domain.business.dto.TimeSlot;
public class SelectTimeSlotService
{
@Inject
private ParameterManager parameterManager;
@Inject
private Messages messages;
public SelectModel create(boolean todayRestrict)
{
int startHour = parameterManager.find(ParameterEnum.HOUR_DAY_START.getCode()).getIntegerValue();
int endHour = parameterManager.find(ParameterEnum.HOUR_DAY_END.getCode()).getIntegerValue();
if (todayRestrict)
{
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) > startHour)
{
startHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
}
return create(new TimeSlot(startHour, 0), new TimeSlot(endHour, 0), 30);
}
public SelectModel create(TimeSlot start, TimeSlot end, int minutes)
{
String separator = messages.get("hour-separator");
int perHour = 60 / minutes;
// int numberElements = (end.getHours() - start.getHours() - 1) * perHour + 1;
int numberElements = (end.getMinutes() - start.getMinutes()) / minutes;
OptionModel[] oms = new OptionModel[(end.getHours() - start.getHours()) * perHour + 1 + numberElements];
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, start.getHours());
c.set(Calendar.MINUTE, start.getMinutes());
for (int i = 0; i < oms.length; i++)
{
String time = FastDateFormat.getInstance("HH" + separator + "mm").format(c);
oms[i] = new OptionModelImpl(time, new TimeSlot(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)));
c.add(Calendar.MINUTE, minutes);
}
SelectModel hoursModel = new SelectModelImpl(oms);
return hoursModel;
}
}
<file_sep>package fr.exanpe.roomeeting.mail.service;
import java.util.Map;
import javax.mail.MessagingException;
import org.springframework.core.io.Resource;
public interface RooMeetingMailService
{
/**
* Envoyer un email simple a un destinataire
*
* @param from Expediteur
* @param to Destinataire
* @param subject Sujet
* @param texte Corps du mail
*/
void sendEmail(String from, String to, String subject, String text);
/**
* Envoyer un email au format MIME a partir d'un modele
*
* @param from Expediteur
* @param to Destinataire
* @param subject Sujet
* @param template Le template du mail a envoyer
* @param model Le modele utilise pour alimenter le template
* @throws MessagingException en cas de pb lors de la construction du message
*/
void sendTemplatedEmail(String from, String to, String subject, String template, Map<String, String> model) throws MessagingException;
/**
* Envoyer un email au format MIME a partir d'un template et d'un modele
*
* @param to Destinataire
* @param subject Sujet
* @param template Le template du mail a envoyer
* @param model Le modele utilise pour alimenter le template
* @throws MessagingException en cas de pb lors de la construction du message
*/
void sendTemplatedEmail(String to, String subject, String template, Map<String, String> model) throws MessagingException;
/**
* Envoyer un email au format MIME a partir d'un template et d'un modele, plus une piece jointe
*
* @param from Expediteur
* @param to Destinataire
* @param subject Sujet
* @param template Le template du mail a envoyer
* @param model Le modele utilise pour alimenter le template
* @param attachment La piece jointe
* @throws MessagingException en cas de pb lors de la construction du message
*/
void sendTemplatedEmailWithAttachment(String from, String to, String subject, String template, Map<String, String> model, Resource attachment)
throws MessagingException;
}
<file_sep>title=My profile
name-label=Name
firstname-label=Firstname
email-label=Mail
pass1-label=<PASSWORD>
pass2-label=<PASSWORD> (again)
update-label=Update
external-account=Your account is externally managed. These information can't be modified from RooMeeting.
error-passes=Passwords don't match
success=Update successful<file_sep>package fr.exanpe.roomeeting.web.base;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.Grid;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;
import fr.exanpe.roomeeting.domain.core.business.DefaultManager;
public abstract class AbstractRefPage<T>
{
@Persist
private List<T> list;
private T current;
@Persist
private T editing;
@InjectComponent("editZone")
private Zone editZone;
@InjectComponent(value = "grid")
private Grid grid;
@Inject
private Logger logger;
private Class<T> clazz;
void onActivate()
{
list = getManager().list();
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if (clazz == null)
{
logger.error("Could not get parametered class by reflection");
throw new RuntimeException("Could not get parametered class by reflection");
}
}
public abstract DefaultManager<T, Long> getManager();
public abstract boolean save(T t);
@OnEvent(value = EventConstants.ACTION, component = "setupEdit")
Object setupEdit(Long id)
{
editing = getManager().find(id);
return editZone.getBody();
}
@OnEvent(value = EventConstants.ACTION, component = "setupAdd")
Object setupAdd()
{
try
{
editing = clazz.newInstance();
}
catch (Exception e)
{
logger.error("Instanciation failed for " + clazz.getName(), e);
}
return editZone.getBody();
}
@OnEvent(value = EventConstants.ACTION, component = "cancel")
void cancel()
{
editing = null;
}
@OnEvent(value = "validateSave")
void validateSave()
{
if (save(editing))
{
list = getManager().list();
editing = null;
}
}
@OnEvent(value = EventConstants.ACTION, component = "delete")
public void delete(Long id)
{
// security check
getManager().delete(id);
}
public boolean hasElements()
{
return CollectionUtils.isNotEmpty(list);
}
/**
* @return the list
*/
public List<T> getList()
{
return list;
}
/**
* @param list the list to set
*/
public void setList(List<T> list)
{
this.list = list;
}
/**
* @return the current
*/
public T getCurrent()
{
return current;
}
/**
* @param current the current to set
*/
public void setCurrent(T current)
{
this.current = current;
}
/**
* @return the editing
*/
public T getEditing()
{
return editing;
}
/**
* @param editing the editing to set
*/
public void setEditing(T editing)
{
this.editing = editing;
}
/**
* @return the editZone
*/
public Zone getEditZone()
{
return editZone;
}
/**
* @param editZone the editZone to set
*/
public void setEditZone(Zone editZone)
{
this.editZone = editZone;
}
/**
* @return the grid
*/
public Grid getGrid()
{
return grid;
}
/**
* @param grid the grid to set
*/
public void setGrid(Grid grid)
{
this.grid = grid;
}
}
<file_sep>package fr.exanpe.roomeeting.web.services.coercers;
import org.apache.tapestry5.ioc.services.Coercion;
import fr.exanpe.roomeeting.domain.model.Site;
public class SiteStringCoercer implements Coercion<Site, String>
{
@Override
public String coerce(Site input)
{
if (input == null) { return null; }
return input.getId() + "";
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.mail.service.impl;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
import fr.exanpe.roomeeting.mail.service.RooMeetingMailService;
/**
* Implementation du service de mail pour RooMeeting
*
* @author lguerin
*/
@Component("roomeetingMailService")
public class RooMeetingMailServiceImpl implements RooMeetingMailService
{
@Autowired
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
@Value("${mail.from}")
private String from;
/*
* (non-Javadoc)
* @see
* fr.exanpe.roomeeting.mail.service.RooMeetingMailService#sendEmail(java.lang.String)
*/
@Override
public void sendEmail(String from, String to, String subject, String text)
{
this.sendSimpleEmail(from, to, subject, text);
}
@Override
public void sendTemplatedEmail(String from, String to, String subject, String template, Map<String, String> model) throws MessagingException
{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
helper.setText(emailText, true);
mailSender.send(message);
}
private void sendSimpleEmail(String from, String to, String subject, String text)
{
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
@Override
public void sendTemplatedEmail(String to, String subject, String template, Map<String, String> model) throws MessagingException
{
this.sendTemplatedEmail(this.from, to, subject, template, model);
}
@Override
public void sendTemplatedEmailWithAttachment(String from, String to, String subject, String template, Map<String, String> model, Resource attachment)
throws MessagingException
{
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, model);
helper.setText(emailText, true);
helper.addAttachment(attachment.getFilename(), attachment);
mailSender.send(message);
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.security;
import fr.exanpe.roomeeting.domain.model.User;
/**
* Contexte de sécurité de l'application RooMeeting.
*
* @author lguerin
*/
public interface RooMeetingSecurityContext
{
/**
* Authentifie un utilisateur.
*
* @param user Utilisateur à authentifier.
*/
void login(User user);
/**
* Teste si un utilisateur est authentifié ou non.
*
* @return true si authentifié
*/
boolean isLoggedIn();
/**
* Retourne l'utilisateur {@link User} authentifié.
*
* @return utilisateur courant authentifié.
*/
User getUser();
/**
* Deconnecte l'utilisateur courant
*/
void logout();
}
<file_sep>-- Role admin
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 1);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 2);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 3);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 4);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 5);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 10);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 11);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 20);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 40);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (1, 41);
-- Role supervisor
INSERT INTO Role_Authority (roles_id, authorities_id)
values (2, 10);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (2, 20);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (2, 40);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (2, 41);
-- Role User
INSERT INTO Role_Authority (roles_id, authorities_id)
values (3, 11);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (3, 20);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (3, 40);
INSERT INTO Role_Authority (roles_id, authorities_id)
values (3, 41); <file_sep>package fr.exanpe.roomeeting.web.services.coercers;
import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.ioc.services.Coercion;
import fr.exanpe.roomeeting.domain.business.dto.TimeSlot;
public class StringTimeSlotCoercer implements Coercion<String, TimeSlot>
{
@Override
public TimeSlot coerce(String input)
{
if (StringUtils.isEmpty(input)) { return null; }
String[] hm = input.split("_");
return new TimeSlot(Integer.parseInt(hm[0]), Integer.parseInt(hm[1]));
}
}
<file_sep>package fr.exanpe.roomeeting.mail.service;
import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.unitils.UnitilsTestNG;
import org.unitils.spring.annotation.SpringApplicationContext;
import org.unitils.spring.annotation.SpringBean;
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;
/**
* @author lguerin
*/
@SpringApplicationContext("applicationContext-mail.xml")
public class RooMeetingMailServiceTest extends UnitilsTestNG
{
private static final String MAIL_TEST_FROM = "<EMAIL>";
private static final String MAIL_TEST_SUBJECT = "Test";
private static final String MAIL_TEST_TO = "<EMAIL>";
/**
* Logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(RooMeetingMailServiceTest.class);
/**
* Service de gestion des utilisateurs a tester
*/
@SpringBean("roomeetingMailService")
private RooMeetingMailService mailService;
/**
* Port de Test
*/
private static final int TEST_SMTP_PORT = 1025;
/**
* Server SMTP de Test
*/
private SimpleSmtpServer smtpServer;
@BeforeMethod
public void startSmtpServer()
{
smtpServer = SimpleSmtpServer.start(TEST_SMTP_PORT);
}
@AfterMethod
public void stopSmtpServer()
{
smtpServer.stop();
}
/**
* Test method for
* {@link fr.exanpe.roomeeting.mail.service.RooMeetingMailService#sendEmail(java.lang.String, java.lang.String, java.lang.String, java.lang.String)}
* .
*/
@Test
public void testSendEmail()
{
Assert.assertEquals(0, smtpServer.getReceivedEmailSize());
mailService.sendEmail(MAIL_TEST_FROM, MAIL_TEST_TO, MAIL_TEST_SUBJECT, "Message de test");
Assert.assertEquals(1, smtpServer.getReceivedEmailSize());
SmtpMessage email = (SmtpMessage) smtpServer.getReceivedEmail().next();
Assert.assertEquals(MAIL_TEST_SUBJECT, email.getHeaderValue("Subject"));
Assert.assertEquals(MAIL_TEST_FROM, email.getHeaderValue("From"));
Assert.assertEquals(MAIL_TEST_TO, email.getHeaderValue("To"));
Assert.assertEquals("Message de test", email.getBody());
}
@Test
public void testSendTemplatedEmail()
{
Map<String, String> model = this.getTemplateModel();
Assert.assertEquals(0, smtpServer.getReceivedEmailSize());
try
{
mailService.sendTemplatedEmail(MAIL_TEST_FROM, MAIL_TEST_TO, MAIL_TEST_SUBJECT, "emailTemplateTest.vm", model);
}
catch (MessagingException e)
{
LOGGER.error("Pb lors du préparation ou de l'envoi du mail: " + e);
throw new RuntimeException(e);
}
Assert.assertEquals(1, smtpServer.getReceivedEmailSize());
SmtpMessage email = (SmtpMessage) smtpServer.getReceivedEmail().next();
Assert.assertEquals(MAIL_TEST_SUBJECT, email.getHeaderValue("Subject"));
Assert.assertEquals(MAIL_TEST_FROM, email.getHeaderValue("From"));
Assert.assertEquals(MAIL_TEST_TO, email.getHeaderValue("To"));
Assert.assertTrue(email.getHeaderValue("Content-Type").contains("multipart/mixed"));
Assert.assertTrue(email.getBody().contains(model.get("name")));
Assert.assertTrue(email.getBody().contains(model.get("text")));
}
@Test
public void testSendTemplatedEmailWithoutFrom()
{
Map<String, String> model = this.getTemplateModel();
Assert.assertEquals(0, smtpServer.getReceivedEmailSize());
try
{
mailService.sendTemplatedEmail(MAIL_TEST_TO, MAIL_TEST_SUBJECT, "emailTemplateTest.vm", model);
}
catch (MessagingException e)
{
LOGGER.error("Pb lors du préparation ou de l'envoi du mail: " + e);
throw new RuntimeException(e);
}
Assert.assertEquals(1, smtpServer.getReceivedEmailSize());
SmtpMessage email = (SmtpMessage) smtpServer.getReceivedEmail().next();
Assert.assertEquals(MAIL_TEST_FROM, email.getHeaderValue("From"));
}
@Test
public void testSendTemplatedEmailWithAttachment()
{
Map<String, String> model = this.getTemplateModel();
Assert.assertEquals(0, smtpServer.getReceivedEmailSize());
Resource resource = new ClassPathResource("tapestry.png");
try
{
mailService.sendTemplatedEmailWithAttachment(MAIL_TEST_FROM, MAIL_TEST_TO, MAIL_TEST_SUBJECT, "emailTemplateTest.vm", model, resource);
}
catch (MessagingException e)
{
LOGGER.error("Pb lors du préparation ou de l'envoi du mail: " + e);
throw new RuntimeException(e);
}
Assert.assertEquals(1, smtpServer.getReceivedEmailSize());
}
private Map<String, String> getTemplateModel()
{
Map<String, String> model = new HashMap<String, String>();
String name = "roomeeting";
String text = "Mail de l'application RooMeeting";
model.put("name", name);
model.put("text", text);
return model;
}
}
<file_sep>title=Bienvenue
futures-bookings-text=Réservations à venir
pasts-bookings-text=Réservations passées
no-futures-booking-text=Aucune réservation en cours ou à venir
room-label=Salle
start-label=Début
end-label=Fin
date-label=Date
no-pasts-booking-text=Aucune réservation passée
feedback-label=Remarque
delete-text=Attention, cette action est irréversible<file_sep>package fr.exanpe.roomeeting.domain.database;
import java.util.Comparator;
public class DatabaseVersionComparator implements Comparator<DatabaseVersion>
{
@Override
public int compare(DatabaseVersion dv1, DatabaseVersion dv2)
{
String[] v1 = dv1.getVersion().split("\\.");
String[] v2 = dv2.getVersion().split("\\.");
for (int i = 0; i < v1.length; i++)
{
// dv1 is after dv2
if (i >= v2.length)
{
// so return greater than
return 1;
}
if (Integer.parseInt(v1[i]) != Integer.parseInt(v2[i])) { return Integer.parseInt(v1[i]) - Integer.parseInt(v2[i]); }
}
// 1.0 vs 1.0.1, v1 is lesser
if (v2.length > v1.length) { return -1; }
return 0;
}
}
<file_sep>INSERT INTO Authority (id, authority) values (1, 'AUTH_ADM_USERS');
INSERT INTO Authority (id, authority) values (2, 'AUTH_ADM_SITES');
INSERT INTO Authority (id, authority) values (3, 'AUTH_ADM_ROOM');
INSERT INTO Authority (id, authority) values (4, 'AUTH_ADM_FEATURES');
INSERT INTO Authority (id, authority) values (5, 'AUTH_ADM_PARAMS');
INSERT INTO Authority (id, authority) values (10, 'AUTH_READ_FEEDBACK');
INSERT INTO Authority (id, authority) values (11, 'AUTH_POST_FEEDBACK');
INSERT INTO Authority (id, authority) values (20, 'AUTH_BOOK');
INSERT INTO Authority (id, authority) values (40, 'AUTH_ROOM_CARD');
INSERT INTO Authority (id, authority) values (41, 'AUTH_SITE_CARD');<file_sep>informations-alt-title=Information about iCalendar format
informations-title=Information<file_sep>package fr.exanpe.roomeeting.web.components;
import java.util.List;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import fr.exanpe.roomeeting.domain.model.ref.RoomFeature;
public class DisplayRoomFeatures
{
@Parameter
@Property
private List<RoomFeature> features;
@Property
private RoomFeature currentFeature;
}
<file_sep>connection=Connection
id-label=Username
password-label=<PASSWORD>
password-lost=<PASSWORD> ?
login-error=The username or password is incorrect
login-button=Connect<file_sep>book-label=Book
home-label=Home
feedback-label=Feedbacks
disconnect-label=Log out
profile-label=Profile
admin-label=Administration
sites-label=Sites
users-label=Users
ref-label=Referential
roomfeatures-label=Room features
params-label=Parameters
roomeeting-description=Your meeting room booking portal<file_sep>package fr.exanpe.roomeeting.domain.business.dto;
import java.util.ArrayList;
import java.util.List;
import fr.exanpe.roomeeting.domain.model.Gap;
import fr.exanpe.roomeeting.domain.model.Room;
public class RoomAvailabilityDTO
{
private Room room;
private List<Gap> gaps = new ArrayList<Gap>();
public RoomAvailabilityDTO(Room room)
{
super();
this.room = room;
}
/**
* @return the room
*/
public Room getRoom()
{
return room;
}
/**
* @return the gaps
*/
public List<Gap> getGaps()
{
return gaps;
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
public class SumUpContext
{
}
<file_sep>title=Available rooms
return-search=Back to search
fully-available=Free
from=From
to=to
hour-short=:
room-label=Room
capacity-label=Capacity
availabilitie-s-label=Availabilitie(s)<file_sep>site-word=Site
unknown-word=unknown
site-not-found=Site not found
name-label=Name
address-label=Address
roomNumber-label=Room number
map-label=Map
map-alt-prefix=Access map<file_sep>room-word=Room
unknown-word=unknown
room-not-found=Room not found (unknown or deleted)
name-label=Name
site-label=Site
floor-label=Floor
capacity-label=Capacity
phoneNumber-label=Phone number
features-label=Features
map-label=Map
map-alt-prefix=Room access map <file_sep>title=Confirmation de réservation
confirm-head-phrase=Nous vous confirmons la réservation de la salle suivante :
exportICal=Exporter au format iCalendar
end=Terminer
booking-flushed=Réservation déjà confirmée. Export impossible.
export-error=Une erreur a eu lieu durant l'export.
informations-iCalendar=Le format iCalendar permet d'importer automatiquement votre réservation dans les outils de planification tels que Microsoft Outlook, Google Calendar, IBM Lotus Notes...<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import fr.exanpe.roomeeting.domain.model.Room;
public class RoomDescription
{
@Property
@Parameter(defaultPrefix = BindingConstants.PROP)
private Room room;
}
<file_sep>package fr.exanpe.roomeeting.domain.business.dto;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.MultiKeyMap;
import fr.exanpe.roomeeting.domain.model.Gap;
import fr.exanpe.roomeeting.domain.model.Room;
public class RoomAvailabilityDTOBuilder
{
public static RoomAvailabilityDTOBuilder create()
{
return new RoomAvailabilityDTOBuilder();
}
private List<DateAvailabilityDTO> dateAvailabilityDTOs = new ArrayList<DateAvailabilityDTO>();
private MultiKeyMap mkmap = new MultiKeyMap();
public RoomAvailabilityDTOBuilder organise(Room room, Date date)
{
if (CollectionUtils.isEmpty(dateAvailabilityDTOs) || !date.equals(dateAvailabilityDTOs.get(dateAvailabilityDTOs.size() - 1).getDate()))
{
dateAvailabilityDTOs.add(new DateAvailabilityDTO(date));
}
DateAvailabilityDTO dateDTO = dateAvailabilityDTOs.get(dateAvailabilityDTOs.size() - 1);
if (CollectionUtils.isEmpty(dateDTO.getSiteAvailabilityDTOs())
|| !room.getSite().equals(dateDTO.getSiteAvailabilityDTOs().get(dateDTO.getSiteAvailabilityDTOs().size() - 1).getSite()))
{
dateDTO.getSiteAvailabilityDTOs().add(new SiteAvailabilityDTO(room.getSite()));
}
SiteAvailabilityDTO siteDTO = dateDTO.getSiteAvailabilityDTOs().get(dateDTO.getSiteAvailabilityDTOs().size() - 1);
RoomAvailabilityDTO roomavailibity = new RoomAvailabilityDTO(room);
siteDTO.getRoomAvailabilityDTOs().add(roomavailibity);
mkmap.put(date, room, roomavailibity);
return this;
}
public RoomAvailabilityDTOBuilder organise(Gap gap, Date dateSearch)
{
RoomAvailabilityDTO roomavailibity = (RoomAvailabilityDTO) mkmap.get(dateSearch, gap.getRoom());
roomavailibity.getGaps().add(gap);
return this;
}
public List<DateAvailabilityDTO> getResult()
{
return dateAvailabilityDTOs;
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
import java.util.List;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import fr.exanpe.t5.lib.model.gmap.GMapMarkerModel;
public class SiteMapModal
{
@Parameter(defaultPrefix = BindingConstants.PROP)
@Property
private List<GMapMarkerModel> markers;
@Property
private GMapMarkerModel currentMarker;
}
<file_sep>application-log-level=ERROR
log-home=./
hibernate.use_cache=false<file_sep>package fr.exanpe.roomeeting.web.pages.card;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.domain.business.SiteManager;
import fr.exanpe.roomeeting.domain.model.Room;
public class RoomCard
{
@Inject
private SiteManager siteManager;
@Property
@Persist(PersistenceConstants.FLASH)
private Room room;
void onActivate(long id)
{
room = siteManager.findRoom(id);
}
public boolean hasMap()
{
return room.getMap() != null && room.getMap().length > 0;
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business;
import fr.exanpe.roomeeting.domain.core.business.DefaultManager;
import fr.exanpe.roomeeting.domain.model.ref.RoomFeature;
public interface RoomFeatureManager extends DefaultManager<RoomFeature, Long>
{
void create(String name, String classpathIcon);
}
<file_sep>package fr.exanpe.roomeeting.web.pages.feedback;
import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.common.annotations.RoomeetingSecured;
import fr.exanpe.roomeeting.domain.business.BookingManager;
import fr.exanpe.roomeeting.domain.business.FeedbackManager;
import fr.exanpe.roomeeting.domain.model.Booking;
import fr.exanpe.roomeeting.domain.model.Feedback;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
import fr.exanpe.roomeeting.web.pages.Home;
import fr.exanpe.t5.lib.annotation.Authorize;
@Authorize(all = "AUTH_POST_FEEDBACK")
public class PostFeedback
{
@Persist
@Property
private Feedback feedback;
@Inject
private FeedbackManager feedbackManager;
@Inject
private BookingManager bookingManager;
@Inject
private RooMeetingSecurityContext securityContext;
@Inject
private Messages messages;
@RoomeetingSecured
Object onActivate(Long id)
{
if (id == null) { return Home.class; }
Booking booking = bookingManager.findWithRoomUser(id, securityContext.getUser());
if (booking == null) { return Home.class; }
feedback = new Feedback();
feedback.setBooking(booking);
return null;
}
@OnEvent(value = "post")
public Object post()
{
// security check
feedbackManager.create(feedback);
return Home.class;
}
public String toStringDate(Date d)
{
return FastDateFormat.getInstance(messages.get("date-format")).format(d);
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import fr.exanpe.roomeeting.common.enums.AuthorityEnum;
import fr.exanpe.roomeeting.common.exception.BusinessException;
import fr.exanpe.roomeeting.common.exception.TechnicalException;
import fr.exanpe.roomeeting.domain.business.BookingManager;
import fr.exanpe.roomeeting.domain.business.UserManager;
import fr.exanpe.roomeeting.domain.business.filters.UserFilter;
import fr.exanpe.roomeeting.domain.core.business.impl.DefaultManagerImpl;
import fr.exanpe.roomeeting.domain.core.dao.CrudDAO;
import fr.exanpe.roomeeting.domain.core.dao.QueryParameters;
import fr.exanpe.roomeeting.domain.model.Authority;
import fr.exanpe.roomeeting.domain.model.Booking;
import fr.exanpe.roomeeting.domain.model.Role;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.model.User;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
import fr.exanpe.roomeeting.domain.util.MessagesResolver;
import fr.exanpe.roomeeting.mail.service.RooMeetingMailService;
/**
* @author lguerin
*/
@Transactional(propagation = Propagation.REQUIRED)
@Service("userManager")
public class UserManagerImpl extends DefaultManagerImpl<User, Long> implements UserManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(UserManagerImpl.class);
@Autowired
private CrudDAO crudDAO;
@Autowired
private RooMeetingSecurityContext securityContext;
@Autowired
private PasswordEncoder passwordEncoder;
@PersistenceContext
protected EntityManager entityManager;
@Autowired
private BookingManager bookingManager;
@Autowired
private RooMeetingMailService mailService;
@Autowired
private MessagesResolver messagesResolver;
@Value("${mail.from}")
private String from;
@Override
public void delete(Long id)
{
User u = find(id);
List<Booking> futuresBookings = bookingManager.listUserFuturesBookings(u);
if (CollectionUtils.isNotEmpty(futuresBookings))
{
for (Booking b : futuresBookings)
{
bookingManager.deleteBooking(b.getId(), u);
}
}
List<Booking> pastBookings = bookingManager.listUserPastsBookings(u);
if (CollectionUtils.isNotEmpty(pastBookings))
{
for (Booking b : pastBookings)
{
bookingManager.deletePastBooking(b.getId());
}
}
entityManager.createNamedQuery(Role.DELETE_FOR_USER).setParameter("userId", u.getId()).executeUpdate();
super.delete(u.getId());
}
/*
* (non-Javadoc)
* @see fr.exanpe.roomeeting.domain.business.UserManager#findByUsername(java.lang.String)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public User findByUsername(String username)
{
Assert.hasText(username, String.format("Le parametre username ne peut pas etre null ou vide"));
User result;
try
{
result = crudDAO.findUniqueWithNamedQuery(User.FIND_BY_USERNAME, QueryParameters.with("username", username).parameters());
}
catch (NoResultException e)
{
LOGGER.info("L'utilisateur identifié par: " + username + " n'existe pas.");
result = null;
}
catch (EmptyResultDataAccessException e)
{
LOGGER.info("User identified by username: " + username + " n'existe pas.");
result = null;
}
return result;
}
@Override
public void resetPassword(String username, Locale locale) throws BusinessException
{
User user = findByUsername(username);
if (user == null) { throw new BusinessException("business-error-invalid-username"); }
String passwordClear = RandomStringUtils.randomAlphanumeric(8);
String passwordEncrypted = encodePassword(passwordClear);
try
{
// TODO could be outsourced to a dedicated mail service, but not the core one...
mailService.sendEmail(
from,
user.getEmail(),
messagesResolver.getMessage("reset-mail-subject", null, locale),
messagesResolver.getMessage("reset-mail-body", new Object[]
{ passwordClear }, locale));
}
catch (Exception e)
{
throw new TechnicalException("System could not send the mail", e);
}
user.setPassword(passwordEncrypted);
update(user);
}
@Override
@Transactional(readOnly = false, rollbackFor = BusinessException.class)
public void createUser(User user, List<Role> roles) throws BusinessException
{
if (!isAvailableUsername(user.getUsername())) { throw new BusinessException("L'utilisateur: " + user.getUsername() + " existe déjà."); }
String pass = encodePassword(user.getPassword());
user.setPassword(pass);
for (Role role : roles)
{
Role realRole = crudDAO.findUniqueWithNamedQuery(Role.FIND_BY_ROLE_NAME, QueryParameters.with("name", role.getName()).parameters());
if (realRole == null) { throw new BusinessException("Le role: " + role.getName() + " n'existe pas !"); }
user.addRole(realRole);
}
crudDAO.create(user);
}
@Override
public String encodePassword(String password)
{
return this.passwordEncoder.encode(password);
}
/*
* (non-Javadoc)
* @see fr.exanpe.roomeeting.domain.business.UserManager#isAvailableName(java.lang.String)
*/
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public boolean isAvailableUsername(String username)
{
return findByUsername(username) == null;
}
@Override
public void cleanRoles(User user)
{
user.getRoles().clear();
crudDAO.update(user);
}
public RooMeetingSecurityContext getSecurityContext()
{
return securityContext;
}
public void setSecurityContext(RooMeetingSecurityContext securityContext)
{
this.securityContext = securityContext;
}
@Override
public void createRole(Role r)
{
crudDAO.create(r);
}
@Override
public List<Role> listRoles()
{
return crudDAO.findWithNamedQuery(Role.FIND_ALL);
}
@Override
public void createAuthority(Authority a)
{
crudDAO.create(a);
}
@Override
public Authority findAuthority(AuthorityEnum a)
{
return crudDAO.find(Authority.class, a.getCode());
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<User> searchUsers(UserFilter filter)
{
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> objectUser = q.from(User.class);
q.select(objectUser);
List<Predicate> predicates = new ArrayList<Predicate>();
if (StringUtils.isNotEmpty(filter.getName()))
{
predicates.add(builder.like(builder.upper(objectUser.<String> get("name")), StringUtils.upperCase(filter.getName()) + "%"));
}
if (StringUtils.isNotEmpty(filter.getUsername()))
{
predicates.add(builder.like(builder.upper(objectUser.<String> get("username")), StringUtils.upperCase(filter.getUsername()) + "%"));
}
if (StringUtils.isNotEmpty(filter.getFirstname()))
{
predicates.add(builder.like(builder.upper(objectUser.<String> get("firstname")), StringUtils.upperCase(filter.getFirstname()) + "%"));
}
if (filter.getRole() != null)
{
predicates.add(builder.isMember(filter.getRole(), objectUser.<Collection<Role>> get("roles")));
}
q.where(predicates.toArray(new Predicate[predicates.size()]));
return crudDAO.findCriteriaQuery(q, 100);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Site findDefaultSite(User user)
{
return find(user.getId()).getDefaultSite();
}
@Override
public void onConnected(User user)
{
user.setLastConnection(new Date());
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Role findRole(long id)
{
return crudDAO.find(Role.class, id);
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.common.exception;
/**
* Class <code>HackException</code> represents a hack resulting exception
*
* @author jmaupoux
*/
public class HackException extends RuntimeException
{
/**
* serialUid
*/
private static final long serialVersionUID = -8229837820658777788L;
/**
* Build a <code>HackException</code>.
*/
public HackException()
{
super();
}
/**
* Build a <code>HackException</code>.
*
* @param message msg
* @param cause cause
*/
public HackException(String message, Throwable cause)
{
super(message, cause);
}
/**
* Build a <code>HackException</code>.
*
* @param message msg
*/
public HackException(String message)
{
super(message);
}
/**
* Build a <code>HackException</code>.
*
* @param cause cause
*/
public HackException(Throwable cause)
{
super(cause);
}
}
<file_sep>title=Welcome
futures-bookings-text=Bookings to come
pasts-bookings-text=Bookings pasts
no-futures-booking-text=No bookings ongoing or to come
room-label=Room
start-label=Start
end-label=End
date-label=Date
no-pasts-booking-text=No pasts bookings
feedback-label=Feedback
delete-text=Warning, this action can be undone.<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
public class DisplayValue
{
@Parameter(defaultPrefix = BindingConstants.MESSAGE)
@Property
private String label;
@Parameter(defaultPrefix = BindingConstants.LITERAL)
@Property
private boolean last;
}
<file_sep>RooMeeting
==========
RooMeeting is an Open Source J2EE web application that aim to help companies managing meeting rooms.
This management rely on some principles :
* Some sites hosts somes rooms
* Rooms offer some features, like the ability to do some video-conference, to access wi-fi... anything you wish to declare.
* A user is linked to a profile that give him access only to a specific part of the application.
Features
--------
Among all its features, RooMeeting offers the following :
* A restricted administration area to manage your company data (users, sites, rooms...)
* A rich search engine, which target automatically the room that best fit a meeting request
* A facility to locate rooms, relying on GoogleMaps and plans
* An integration with almost all calendar products (Microsoft Outlook, Google Agenda, IBM Lotus Notes...) with the iCalendar export feature.
*Coming Soon* :
* An integration with externals user datasource, as Microsoft Exchange
* Incidents reporting to room managers
More
----
http://attonnnn.github.io/roomeeting<file_sep>package fr.exanpe.roomeeting.web.components;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SupportsInformalParameters;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.domain.business.RoomFeatureManager;
import fr.exanpe.roomeeting.domain.business.SiteManager;
import fr.exanpe.roomeeting.web.services.InputStreamResponse;
/**
* Component rendering an <img> from an InputStream.
* Do not create any physical file.<br/>
* The binary image will be copied in session before rendered to the user. The inputStream parameter
* will be automatically closed by the component once in session.<br/>
* Once consumed by the browser, the image is automatically cleared.
* A clear() method allow you to clear the inputstream data if not consumed by the browser (you can
* also discard persistent fields on your page).<br/>
* <br/>
* If an error occurs with the stream parameter, an error is logged and the image of parameter
* "errorImage" is displayed.
*
* @author jmaupoux
* @since 1.3
*/
@SupportsInformalParameters
public class RestImage<T>
{
/**
* Render event
*/
private static final String EVENT = "roomFeatureIcon";
/**
* Content type of the image. Default to image/jpeg
*/
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL, value = "image/jpeg")
private String contentType;
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String imageType;
@Parameter
private T context;
@Inject
private RoomFeatureManager roomFeatureManager;
@Inject
private SiteManager siteManager;
/**
* resources
*/
@Inject
private ComponentResources resources;
@BeginRender
void init(MarkupWriter writer) throws IOException
{
String src = resources.createEventLink(imageType, context).toURI();
writer.element("img", "src", src);
resources.renderInformalParameters(writer);
writer.end();
}
/**
* Event rendering the image
*
* @return the stream response containing the image
*/
@OnEvent(value = "roomFeatureIcon")
StreamResponse render(Long id)
{
StreamResponse response = new InputStreamResponse(new ByteArrayInputStream(roomFeatureManager.find(id).getIcon()), contentType);
return response;
}
/**
* Event rendering the image
*
* @return the stream response containing the image
*/
@OnEvent(value = "roomMap")
StreamResponse renderRoomMap(Long id)
{
StreamResponse response = new InputStreamResponse(new ByteArrayInputStream(siteManager.findRoom(id).getMap()), contentType);
return response;
}
}
<file_sep>title=Mon profil
name-label=Nom
firstname-label=Prénom
email-label=Email
pass1-label=<PASSWORD> de passe
pass2-label=<PASSWORD> de passe (contrôle)
update-label=Mettre à jour
external-account=Votre compte est administré de manière externe et ne peut être modifié dans cette RooMeeting.
error-passes=Les mots de passe diffèrent
success=Modifications effectuées<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Index;
import fr.exanpe.roomeeting.common.utils.RoomDateUtils;
@Entity
@NamedQueries(
{
@NamedQuery(name = Gap.FIND_GAP_AROUND_TIMESLOT, query = "From Gap gap where gap.date = :date and gap.room = :room and gap.startTime <= :startTime and gap.endTime >= :endTime"),
@NamedQuery(name = Gap.FIND_GAP_FOR_TIME, query = "From Gap gap where gap.date = :date and gap.room = :room and (gap.startTime = :time or gap.endTime = :time)") })
@NamedNativeQuery(name = Gap.PURGE, query = "DELETE FROM Gap where date < CURRENT_DATE", resultClass = Gap.class)
public class Gap implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -243347798060345357L;
public static final String FIND_GAP_AROUND_TIMESLOT = "Gap.findGapAroundTimeslot";
public static final String FIND_GAP_FOR_TIME = "Gap.findGapForTime";
public static final String PURGE = "Gap.purge";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@Index(name = "idx_gap_date_room", columnNames =
{ "date", "room" })
private Room room;
@Temporal(TemporalType.DATE)
private Date date;
private Integer startHour;
private Integer startMinute;
private Integer endHour;
private Integer endMinute;
@Temporal(TemporalType.TIME)
private Date startTime;
@Temporal(TemporalType.TIME)
private Date endTime;
@PreUpdate
@PrePersist
void compute()
{
startTime = RoomDateUtils.setHourMinutes(date, startHour, startMinute);
endTime = RoomDateUtils.setHourMinutes(date, endHour, endMinute);
}
/**
* @return the id
*/
public Long getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id)
{
this.id = id;
}
/**
* @return the room
*/
public Room getRoom()
{
return room;
}
/**
* @param room the room to set
*/
public void setRoom(Room room)
{
this.room = room;
}
/**
* @return the date
*/
public Date getDate()
{
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date)
{
this.date = date;
}
/**
* @return the startHour
*/
public Integer getStartHour()
{
return startHour;
}
/**
* @param startHour the startHour to set
*/
public void setStartHour(Integer startHour)
{
this.startHour = startHour;
}
/**
* @return the startMinutes
*/
public Integer getStartMinute()
{
return startMinute;
}
/**
* @param startMinutes the startMinutes to set
*/
public void setStartMinute(Integer startMinutes)
{
this.startMinute = startMinutes;
}
/**
* @return the endHour
*/
public Integer getEndHour()
{
return endHour;
}
/**
* @param endHour the endHour to set
*/
public void setEndHour(Integer endHour)
{
this.endHour = endHour;
}
/**
* @return the endMinutes
*/
public Integer getEndMinute()
{
return endMinute;
}
/**
* @param endMinutes the endMinutes to set
*/
public void setEndMinute(Integer endMinutes)
{
this.endMinute = endMinutes;
}
/**
* @return the startTime
*/
public Date getStartTime()
{
return startTime;
}
/**
* @param startTime the startTime to set
*/
public void setStartTime(Date startTime)
{
this.startTime = startTime;
}
/**
* @param endTime the endTime to set
*/
public void setEndTime(Date endTime)
{
this.endTime = endTime;
}
/**
* @return the endTime
*/
public Date getEndTime()
{
return endTime;
}
}
<file_sep>reset-mail-subject=Roomeeting password reset
reset-mail-body=Your password has been reset to : {0}<file_sep>title=Comportement invalide
message=Un comportement invalide a été détecté. Veuillez contacter l'administrateur pour plus d'informations<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OrderBy;
import fr.exanpe.roomeeting.domain.model.ref.RoomFeature;
@Entity
@NamedQueries(
{ @NamedQuery(name = Room.FIND_GAPS_FOR_DATE, query = "SELECT g FROM Gap g join fetch g.room WHERE g.room in (:rooms) AND g.date = :date and ((g.startTime between :startTime and :endTime) or (g.endTime between :startTime and :endTime)) order by g.room.id, g.date, g.startTime") })
public class Room implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -243387796260345357L;
public static final String FIND_GAPS_FOR_DATE = "Room.findGapsForDate";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private int capacity;
private Integer floor;
private String phoneNumber;
@ManyToOne
private Site site;
@OrderBy("id")
@ManyToMany(fetch = FetchType.EAGER)
private List<RoomFeature> features = new ArrayList<RoomFeature>();
@Lob
private byte[] map;
/**
* @return the id
*/
public Long getId()
{
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id)
{
this.id = id;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the capacity
*/
public int getCapacity()
{
return capacity;
}
/**
* @param capacity the capacity to set
*/
public void setCapacity(int capacity)
{
this.capacity = capacity;
}
/**
* @return the site
*/
public Site getSite()
{
return site;
}
/**
* @param site the site to set
*/
public void setSite(Site site)
{
this.site = site;
}
/**
* @return the floor
*/
public Integer getFloor()
{
return floor;
}
/**
* @param floor the floor to set
*/
public void setFloor(Integer floor)
{
this.floor = floor;
}
/**
* @return the phoneNumber
*/
public String getPhoneNumber()
{
return phoneNumber;
}
/**
* @param phoneNumber the phoneNumber to set
*/
public void setPhoneNumber(String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
/**
* @return the roomFeatures
*/
public List<RoomFeature> getFeatures()
{
return features;
}
/**
* @param roomFeatures the roomFeatures to set
*/
public void setFeatures(List<RoomFeature> roomFeatures)
{
this.features = roomFeatures;
}
/**
* @return the icon
*/
public byte[] getMap()
{
return map;
}
/**
* @param icon the icon to set
*/
public void setMap(byte[] icon)
{
this.map = icon;
}
@Override
public boolean equals(Object obj)
{
if (obj == null || !(obj instanceof Room)) { return false; }
return id != null && id.equals(((Room) obj).getId());
}
@Override
public int hashCode()
{
return id.intValue();
}
}
<file_sep>INSERT INTO Role (id, priority, name) values (1, 1, 'roles-key-admin');
INSERT INTO Role (id, priority, name) values (2, 2, 'roles-key-supervisor');
INSERT INTO Role (id, priority, name) values (3, 3, 'roles-key-user');<file_sep>spring.profiles.active=${configuration.active}<file_sep>room-word=Salle
unknown-word=inconnue
room-not-found=La salle n'a pas été trouvée (inconnue ou supprimée)
name-label=Nom
site-label=Site
floor-label=Etage
capacity-label=Capacité
phoneNumber-label=Numéro de téléphone
features-label=Caractéristiques
map-label=Plan
map-alt-prefix=Plan de la salle <file_sep>inconsistent-database=Database inconsistent. Booking aborted.<file_sep>package fr.exanpe.roomeeting.web.components;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.web.util.GMapUtils;
import fr.exanpe.t5.lib.model.gmap.GMapMarkerModel;
public class SiteDescription
{
@Property
@Parameter(defaultPrefix = BindingConstants.PROP)
private Site site;
public boolean hasMap()
{
return StringUtils.isNotEmpty(site.getLatitude()) && StringUtils.isNotEmpty(site.getLongitude());
}
public List<GMapMarkerModel> getMarkers()
{
List<GMapMarkerModel> l = new ArrayList<GMapMarkerModel>();
l.add(GMapUtils.toMarker(site));
return l;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>fr.exanpe.roomeeting</groupId>
<artifactId>roomeeting</artifactId>
<packaging>pom</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>roomeeting</name>
<description>Projet RooMeeting</description>
<scm>
<connection>scm:git:git@gitproxy:attonnnn/roomeeting.git</connection>
<developerConnection>scm:git:<EMAIL>:attonnnn/roomeeting.git</developerConnection>
<url>https://github.com/attonnnn/roomeeting</url>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<slf4j-version>1.6.4</slf4j-version>
<tapestry-release-version>5.3.2</tapestry-release-version>
<hibernate-version>4.1.0.Final</hibernate-version>
<ehcache-version>2.3.1</ehcache-version>
<spring-version>3.1.1.RELEASE</spring-version>
<spring-security-version>3.1.4.RELEASE</spring-security-version>
<h2-version>1.3.171</h2-version>
<unitils-version>3.1</unitils-version>
<compile-source>1.6</compile-source>
</properties>
<!-- Dependances communes a l'ensemble des modules -->
<dependencies>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.5</version>
</dependency>
<!-- A dependency on either JUnit or TestNG is required, or the surefire
plugin (which runs the tests) will fail, preventing Maven from packaging
the WAR. Tapestry includes a large number of testing facilities designed
for use with TestNG (http://testng.org/), so it's recommended. -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>5.8</version>
<classifier>jdk15</classifier>
<scope>test</scope>
</dependency>
<!-- Traces -->
<!-- slf4j API -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
</dependency>
<!-- route from log4j call to slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${slf4j-version}</version>
</dependency>
<!-- logback dependency -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.30</version>
</dependency>
<!-- used by logback to process conditions and expressions -->
<dependency>
<groupId>janino</groupId>
<artifactId>janino</artifactId>
<version>2.5.10</version>
</dependency>
</dependencies>
<!-- Fixing dependencies differencies between
Spring version and Spring security dependencies -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- BD embarquee pour les tests -->
<!-- H2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2-version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${compile-source}</source>
<target>${compile-source}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<optimize>false</optimize>
</configuration>
</plugin>
</plugins>
<!--
TODO : activer apres avoir builder la configuration de reporting
<extensions>
<extension>
<groupId>${project.groupId}</groupId>
<artifactId>roomeeting-conf-reporting</artifactId>
<version>1.0.0</version>
</extension>
</extensions>
-->
</build>
<modules>
<module>roomeeting-db</module>
<module>roomeeting-classpath</module>
<module>roomeeting-common</module>
<module>roomeeting-mail</module>
<module>roomeeting-domain-core</module>
<module>roomeeting-domain</module>
<module>roomeeting-web</module>
</modules>
</project><file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
public class LayoutMenu
{
/** The page title, for the <title> element and the element. */
@Property
@Parameter(required = false, defaultPrefix = BindingConstants.MESSAGE)
private String title;
@Inject
private ComponentResources componentResources;
@SetupRender
void init()
{
if (title == null)
{
title = componentResources.getContainerMessages().get("title");
}
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.security.impl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import fr.exanpe.roomeeting.domain.model.User;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
/**
* Implementation du SecurityContext propre à roomeeting
*
* @author lguerin
*/
@Component("roomeetingSecurityContext")
public class RooMeetingSecurityContextImpl implements RooMeetingSecurityContext
{
/*
* (non-Javadoc)
* @see
* fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext#login(fr.exanpe.roomeeting.domain.model
* .User)
*/
@Override
public void login(User user)
{
Assert.notNull(user, "user");
UsernamePasswordAuthenticationToken logged = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(logged);
}
/*
* (non-Javadoc)
* @see fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext#isLoggedIn()
*/
@Override
public boolean isLoggedIn()
{
if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null
&& SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null)
{
if ("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getName())) { return false; }
return SecurityContextHolder.getContext().getAuthentication().isAuthenticated();
}
return false;
}
/*
* (non-Javadoc)
* @see fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext#getUser()
*/
@Override
public User getUser()
{
User user = null;
if (isLoggedIn())
{
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User)
{
user = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
}
return user;
}
/*
* (non-Javadoc)
* @see fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext#logout()
*/
@Override
public void logout()
{
SecurityContextHolder.getContext().setAuthentication(null);
SecurityContextHolder.clearContext();
}
}
<file_sep>package fr.exanpe.roomeeting.web.services.coercers;
import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.ioc.services.Coercion;
import fr.exanpe.roomeeting.domain.business.UserManager;
import fr.exanpe.roomeeting.domain.model.Role;
public class StringRoleCoercer implements Coercion<String, Role>
{
private UserManager userManager;
public StringRoleCoercer(UserManager userManager)
{
this.userManager = userManager;
}
@Override
public Role coerce(String input)
{
if (StringUtils.isEmpty(input)) { return null; }
return userManager.findRole(Long.parseLong(input));
}
}
<file_sep>package fr.exanpe.roomeeting.common.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Marker for secured method
*
* @author jmaupoux
*/
@Target(
{ ElementType.METHOD, ElementType.TYPE })
public @interface RoomeetingSecured
{
}
<file_sep>package fr.exanpe.roomeeting.web.pages.admin;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import fr.exanpe.roomeeting.domain.business.SiteManager;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.web.util.GMapUtils;
import fr.exanpe.t5.lib.model.gmap.GMapMarkerModel;
/**
* Welcome page
*/
public class ManageSites
{
@Persist
@Property
private List<Site> sites;
@Property
private Site currentSite;
@Property
private Site currentMarkerSite;
@Inject
private SiteManager siteManager;
void onActivate()
{
sites = siteManager.list();
}
@OnEvent(value = EventConstants.ACTION, component = "delete")
void delete(long id)
{
siteManager.delete(id);
}
public boolean hasMap(Site s)
{
return StringUtils.isNotEmpty(s.getLatitude()) && StringUtils.isNotEmpty(s.getLongitude());
}
public List<GMapMarkerModel> getMarkers()
{
List<GMapMarkerModel> markers = new ArrayList<GMapMarkerModel>();
for (Site s : sites)
{
if (hasMap(s))
{
markers.add(GMapUtils.toMarker(s));
}
}
return markers;
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
public class SiteMapButton
{
@Parameter(allowNull = false, required = true)
@Property
private String latitude;
@Parameter(allowNull = false, required = true)
@Property
private String longitude;
}
<file_sep>package fr.exanpe.roomeeting.web.pages;
public class Hack
{
public static final String PAGE_NAME = "Hack";
}
<file_sep>package fr.exanpe.roomeeting.domain.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
/**
* Rôles attribués aux utilisateurs de l'application.
*/
@NamedQueries(
{ @NamedQuery(name = Role.FIND_BY_ROLE_NAME, query = "FROM Role WHERE name = :name"), @NamedQuery(name = Role.FIND_ALL, query = "FROM Role ORDER BY priority") })
@Entity
@NamedNativeQuery(name = Role.DELETE_FOR_USER, query = "DELETE FROM Uzer_Role WHERE users_id = :userId", resultClass = Role.class)
public class Role implements Serializable
{
/**
* serialUID
*/
private static final long serialVersionUID = 2186257499592013844L;
/**
* Identifiants des requetes NamedQuery
*/
public static final String FIND_BY_ROLE_NAME = "Role.findByRoleName";
public static final String DELETE_FOR_USER = "Role.deleteForUser";
/**
* Identifiants des requetes NamedQuery
*/
public static final String FIND_ALL = "Role.findAll";
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Integer priority;
@Column(nullable = false)
private String name;
/**
* Fetch.EAGER because User needs all the authorities
* all the time
*/
@ManyToMany(fetch = FetchType.EAGER)
private List<Authority> authorities;
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
private List<User> users;
public Role()
{
super();
}
public long getId()
{
return id;
}
public List<Authority> getAuthorities()
{
return authorities;
}
public void setAuthorities(List<Authority> authorities)
{
this.authorities = authorities;
}
public List<User> getUsers()
{
return users;
}
public void setUsers(List<User> users)
{
this.users = users;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
/**
* @return the order
*/
public Integer getPriority()
{
return priority;
}
/**
* @param order the order to set
*/
public void setPriority(Integer order)
{
this.priority = order;
}
}
<file_sep>package fr.exanpe.roomeeting.web.services.coercers;
import org.apache.tapestry5.ioc.services.Coercion;
import fr.exanpe.roomeeting.domain.model.Role;
public class RoleStringCoercer implements Coercion<Role, String>
{
@Override
public String coerce(Role input)
{
if (input == null) { return null; }
return input.getId() + "";
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;
/**
* Layout component for pages of application roomeeting-web.
*/
@Import(stylesheet =
{ "context:css/bootstrap-roomeeting.css", "context:css/roomeeting.css", "${exanpe.asset-base}/css/exanpe-t5-lib-skin.css",
"context:bootstrap/datepicker/datepicker.css" })
public class Layout
{
/** The page title, for the <title> element and the <h1>element. */
@Property
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
private String title;
/** The page title, for the <title> element and the <h1>element. */
@Property
@Parameter(required = true, defaultPrefix = BindingConstants.LITERAL, value = "true")
private String bar;
@Inject
private RequestGlobals requestGlobals;
public String getContextRoot()
{
return requestGlobals.getHTTPServletRequest().getContextPath();
}
}
<file_sep>package fr.exanpe.roomeeting.common.enums;
public enum ParameterEnum
{
HOUR_DAY_START(1L), HOUR_DAY_END(2L), DB_VERSION(99L);
private long code;
private ParameterEnum(long code)
{
this.code = code;
}
public long getCode()
{
return code;
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business;
import fr.exanpe.roomeeting.common.enums.ParameterEnum;
import fr.exanpe.roomeeting.domain.core.business.DefaultManager;
import fr.exanpe.roomeeting.domain.model.ref.Parameter;
public interface ParameterManager extends DefaultManager<Parameter, Long>
{
Parameter find(ParameterEnum e);
Integer findInteger(ParameterEnum e);
String findString(ParameterEnum e);
}
<file_sep>title=Booking confirmation
confirm-head-phrase=Booking has been executed for room:
exportICal=Export as iCalendar format
end=End
booking-flushed=Booking already confirmed. Export unavailable.
export-error=An error occurred while exporting.
informations-iCalendar=iCalendar format allow to automatically import this booking in agenda like software as Microsoft Outlook, Google Calendar, IBM Lotus Notes...<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>roomeeting</artifactId>
<groupId>fr.exanpe.roomeeting</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>roomeeting-domain</artifactId>
<name>roomeeting-domain</name>
<dependencies>
<dependency>
<artifactId>roomeeting-domain-core</artifactId>
<groupId>${project.groupId}</groupId>
<version>${project.version}</version>
</dependency>
<dependency>
<artifactId>roomeeting-mail</artifactId>
<groupId>${project.groupId}</groupId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.mnode.ical4j</groupId>
<artifactId>ical4j</artifactId>
<version>1.0.4</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${spring-security-version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Dependances pour Unitils -->
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-dbunit</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-testng</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-orm</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-easymock</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-mock</artifactId>
<version>${unitils-version}</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-spring</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-inject</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-core</artifactId>
<version>${unitils-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business;
import java.util.List;
import java.util.Locale;
import fr.exanpe.roomeeting.common.enums.AuthorityEnum;
import fr.exanpe.roomeeting.common.exception.BusinessException;
import fr.exanpe.roomeeting.domain.business.filters.UserFilter;
import fr.exanpe.roomeeting.domain.core.business.DefaultManager;
import fr.exanpe.roomeeting.domain.model.Authority;
import fr.exanpe.roomeeting.domain.model.Role;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.model.User;
/**
* Le service <code>UserManager</code> permet de gérer les utilisateurs {@link User} qui se
* connectent à
* l'application.
*
* @author lguerin
*/
public interface UserManager extends DefaultManager<User, Long>
{
/**
* Recherche un objet {@link User} à partir de son <code>username</code>.
*
* @param username l'identifiant (login) de l'utilisateur
* @return l'objet <code>User</code>, ou <code>null</code>
*/
User findByUsername(String username);
/**
* Créé un nouvel utilisateur
*
* @param user l'utilisateur à créer
* @param roles les rôles de l'utilisateur
* @throws BusinessException en cas de probleme lors de la creation de l'utilisateur
*/
void createUser(User user, List<Role> roles) throws BusinessException;
String encodePassword(String password);
/**
* Retourne true si l'utilisateur <code>username</code> n'existe pas déjà.
*
* @param username Le nom de l'utilisateur à créer
* @return true if available
*/
boolean isAvailableUsername(String username);
/**
* Supprime les roles de l'utilisateur
*
* @param user l'utilisateur à nettoyer
*/
void cleanRoles(User user);
List<User> searchUsers(UserFilter username);
void createRole(Role r);
void createAuthority(Authority a);
List<Role> listRoles();
Authority findAuthority(AuthorityEnum a);
void onConnected(User user);
Site findDefaultSite(User user);
Role findRole(long id);
void resetPassword(String username, Locale locale) throws BusinessException;
}
<file_sep>package fr.exanpe.roomeeting.domain.business.dto;
import java.util.ArrayList;
import java.util.List;
import fr.exanpe.roomeeting.domain.model.Site;
public class SiteAvailabilityDTO
{
private Site site;
private List<RoomAvailabilityDTO> roomAvailabilityDTOs = new ArrayList<RoomAvailabilityDTO>();
public SiteAvailabilityDTO(Site site)
{
super();
this.site = site;
}
/**
* @return the site
*/
public Site getSite()
{
return site;
}
/**
* @return the roomAvailabilityDTOs
*/
public List<RoomAvailabilityDTO> getRoomAvailabilityDTOs()
{
return roomAvailabilityDTOs;
}
}
<file_sep>-- *****************************************************************************
-- * Nom du script : 01_ddl_V_DOSSIER_ADMINISTRATIF.sql
-- *****************************************************************************
spool ../logs/01_ddl_V_DOSSIER_ADMINISTRATIF.log
whenever OSERROR exit SQL.OSCODE;
prompt debut 01_ddl_V_DOSSIER_ADMINISTRATIF.sql
--===================================
-- PARTIE REENTRANTE
--===================================
prompt partie reentrante
-- Pas de partie reentrante car le create or replace, ne genere pas pas d'erreur lors de multiple execution
prompt fin partie reentrante
--===================================
-- Partie non réentrante
--===================================
WHENEVER SQLERROR EXIT SQL.SQLCODE;
CREATE OR REPLACE FORCE VIEW "V_DOSSIER_ADMINISTRATIF" ("ID", "ID_DOSSIER", "ID_EMPLOI", "ACTIF", "NOM", "PRENOM", "NOM_MARITAL", "DATE_DE_NAISSANCE", "SEXE", "MATRICULE_ARMEE", "IDENTIFIANT_DEFENSE", "SMU_AFFECTATION", "MESSAGE", "DATE_DEB_ACTIVITE", "DATE_FIN_ACTIVITE", "COMPAGNIE_AFFECTATION", "DATE_DEBUT_AFFECTATION_CIE", "DATE_FIN_AFFECTAION_CIE", "SMU_DETACHEMENT", "COMPAGNIE_DETACHEMENT", "DATE_DEBUT_DETACHEMENT_CIE", "DATE_FIN_DETACHEMENT_CIE", "TELEPHONE_AFFECTATION", "TELEPHONE_DETACHEMENT", "TELEPHONE_PORTABLE", "TELEPHONE_FIXE", "GRADE", "SPECIALITE", "UNITE_AFFECTATION", "UNITE_DETACHEMENT", "VERROUS", "ID_USER_VERROUS", "DATE_VERROUS", "DOS_INDIC_SAISI_GRP", "SOUS_UNITE_AFFECTATION", "SOUS_UNITE_DETACHEMENT", "DOS_DAT_CREATION", "SMU_ASSOCIE", "DOS_SMU_EXCLUS", "DOM_VAL_LIB_R_SERIE_AFF", "DOM_VAL_LIB_RSERIEDET")
AS
SELECT
/*+ RULE */
dd.dos_id,
dd.dos_id,
e.emp_id,
dd.dos_statut,
dd.dos_nom,
dd.dos_prenom,
dd.dos_nom_mari,
dd.dos_dat_naissance,
dd.dom_val_rsex,
dd.dos_matri_armee,
dd.dos_ident_defense,
e.dom_val_lib_ruf_aff, --e.dom_val_lib_rcss_aff,
'O' MESSAGE,
e.emp_dat_deb_activite,
e.emp_dat_fin_activite,
e.dom_val_lib_rcss_aff,
e.emp_dat_deb_aff,
e.emp_dat_fin_aff,
e.dom_val_lib_ruf_det, --e.dom_val_lib_rcss_det,
e.dom_val_lib_rcss_det,
e.emp_dat_deb_det,
e.emp_dat_fin_det,
e.emp_tel_travail_aff,
e.emp_tel_travail_det,
dd.dos_tel_portable tel_portable,
dd.dos_tel_domicile tel_fixe,
e.dom_val_lib_rgr,
e.emp_nom_specialite,
e.dom_val_lib_ruf_aff,
e.dom_val_lib_ruf_det,
dd.dos_ind_verrou,
dd.uti_id_verrou,
dd.dos_dat_verrou,
dd.dos_indic_saisi_grp,
e.dom_val_lib_rusf_aff,
e.dom_val_lib_rusf_det,
dd.dos_dat_creation,
(SELECT r.r_str_nom
FROM dossier_smu_associe dsa,
r_structure r
WHERE r.r_str_id = dsa.r_str_id
AND dsa.dos_id(+) = dd.dos_id
AND ROWNUM = 1
) structure_associee,
dd.dos_smu_exclus,
e.dom_val_lib_rserieaff,
e.dom_val_lib_rseriedet
FROM dossier dd,
r_structure rs,
t_emploi e
WHERE dd.dos_id = e.dos_id(+)
AND rs.r_str_id(+) = e.r_str_id_aff
AND e.for_ind_histo(+) = 'N';
-- Code ne devant pas échouer
prompt fin 01_ddl_V_DOSSIER_ADMINISTRATIF.sql
spool off
exit
<file_sep>persons=personnes
number-floor=ème étage
room-label=Salle
capacity-label=Capacité
features-label=Caractéristiques<file_sep>reset-mail-subject=Réinitialisation de mot de passe RooMeeting
reset-mail-body=Votre mot de passe a été réinitialisé en : {0}<file_sep>INSERT INTO Parameter (id, name, description, integerValue)
values (1, 'parameters-key-start-hour-name', 'parameters-key-start-hour-desc', 8);
INSERT INTO Parameter (id, name, description, integerValue)
values (2, 'parameters-key-end-hour-name', 'parameters-key-end-hour-desc', 20);<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business;
import java.util.List;
import fr.exanpe.roomeeting.domain.core.business.DefaultManager;
import fr.exanpe.roomeeting.domain.model.Room;
import fr.exanpe.roomeeting.domain.model.Site;
public interface SiteManager extends DefaultManager<Site, Long>
{
public void addRoom(Site s, Room r);
public List<Site> list();
public Site findWithRooms(Long siteId);
public Room findRoom(Long id);
public void updateRoom(Room editRoom);
public void removeRoom(Site site, Long roomId);
}
<file_sep>connection=Connexion
id-label=Identifiant
password-label=<PASSWORD>
password-lost=<PASSWORD> ?
login-error=Mauvais couple utilisateur ou mot de passe
login-button=Se connecter<file_sep>package fr.exanpe.roomeeting.web.services.coercers;
import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.tapestry5.ioc.services.Coercion;
public class StringDateCoercer implements Coercion<Date, String>
{
@Override
public String coerce(Date input)
{
if (input == null) { return null; }
return FastDateFormat.getInstance("yyyyMMdd").format(input);
}
}
<file_sep>logo-alt=Back to home
<file_sep>generic-error-message=Une erreur est survenue<file_sep>/** Global item repository for RooMeeting js lib */
if(!RooMeeting)
{
var RooMeeting = {};
}
jQuery(document).ready(function () {
jQuery('.datepicker-input').datepicker({
autoclose : true,
format:"dd/mm/yyyy",
weekStart:"1",
language:'fr'
});
jQuery(".tooltiped").tooltip();
});
<file_sep>#!/bin/ksh
#-------------------------------------------------------------------------------
# Objet: Execution des patchs de base de données version 2.10.2
#-------------------------------------------------------------------------------
echo "Execution des patchs de base de données version 2.10.2"
if [ $# -eq 3 ]; then
cd scripts
for script in `ls *.ksh `
do
echo "Execution script : "${script}
./${script} $1 $2 $3
done
else
echo " Le nombre de parametres en entree n'est pas correct"
echo 1.- nom utilisateur de la base de connexion
echo 2.- mot de passe de la base de connexion
echo 3.- oracle sid de la base de connexion
exit 1
fi
RET=$?
echo "Code Retour du traitement: $RET"
if [ $RET -ne 0 ]
then
echo "==> FIN ANORMALE patchDB"
else
echo "==> FIN NORMALE patchDB"
fi
exit $RET<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
public class DisplayParameter
{
@Parameter
@Property
private fr.exanpe.roomeeting.domain.model.ref.Parameter parameter;
public boolean testIsNull(Object o)
{
return o == null;
}
}
<file_sep>package fr.exanpe.roomeeting.domain.business.filters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import fr.exanpe.roomeeting.domain.business.dto.TimeSlot;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.model.ref.RoomFeature;
public class RoomFilter
{
private Site site;
private int capacity = 0;
private String name;
private Date date = new Date();
private List<RoomFeature> features = new ArrayList<RoomFeature>();
private int extendDays = 0;
private boolean extendWorkingOnly = true;
private TimeSlot restrictFrom;
private TimeSlot restrictTo;
/**
* @return the site
*/
public Site getSite()
{
return site;
}
/**
* @param site the site to set
*/
public void setSite(Site site)
{
this.site = site;
}
/**
* @return the capacity
*/
public int getCapacity()
{
return capacity;
}
/**
* @param capacity the capacity to set
*/
public void setCapacity(int capacity)
{
this.capacity = capacity;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the date
*/
public Date getDate()
{
return date;
}
/**
* @param date the date to set
*/
public void setDate(Date date)
{
this.date = date;
}
/**
* @return the extendDays
*/
public int getExtendDays()
{
return extendDays;
}
/**
* @param extendDays the extendDays to set
*/
public void setExtendDays(int extendDays)
{
this.extendDays = extendDays;
}
/**
* @return the extendWorking
*/
public boolean isExtendWorkingOnly()
{
return extendWorkingOnly;
}
/**
* @param extendWorking the extendWorking to set
*/
public void setExtendWorkingOnly(boolean extendWorking)
{
this.extendWorkingOnly = extendWorking;
}
/**
* @return the restrictFrom
*/
public TimeSlot getRestrictFrom()
{
return restrictFrom;
}
/**
* @param restrictFrom the restrictFrom to set
*/
public void setRestrictFrom(TimeSlot restrictFrom)
{
this.restrictFrom = restrictFrom;
}
/**
* @return the restrictTo
*/
public TimeSlot getRestrictTo()
{
return restrictTo;
}
/**
* @param restrictTo the restrictTo to set
*/
public void setRestrictTo(TimeSlot restrictTo)
{
this.restrictTo = restrictTo;
}
/**
* @return the features
*/
public List<RoomFeature> getFeatures()
{
return features;
}
/**
* @param features the features to set
*/
public void setFeatures(List<RoomFeature> features)
{
this.features = features;
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
public class DisplayValueContainer
{
}
<file_sep>site-word=Site
unknown-word=inconnu
site-not-found=Le site n'a pas été trouvé (inconnu ou supprimé)
name-label=Nom
address-label=Adresse
roomNumber-label=Nombre de salles
map-label=Plan
map-alt-prefix=Plan d'accès<file_sep>package fr.exanpe.roomeeting.web.pages.book;
import org.apache.commons.io.IOUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;
import fr.exanpe.roomeeting.common.exception.BusinessException;
import fr.exanpe.roomeeting.domain.business.ICalManager;
import fr.exanpe.roomeeting.domain.model.Booking;
import fr.exanpe.roomeeting.web.pages.Home;
import fr.exanpe.roomeeting.web.services.FileStreamResponse;
public class ConfirmBooking
{
@SessionAttribute
@Property
private Booking booking;
@Inject
private ICalManager iCalManager;
@Inject
private Messages messages;
@Inject
private RequestGlobals requestGlobals;
@Property
@Persist(PersistenceConstants.FLASH)
private String exportMessage;
Object onActivate()
{
if (booking == null) { return Search.class; }
return null;
}
@OnEvent(value = EventConstants.ACTION, component = "exportICal")
StreamResponse exportOutlook() throws BusinessException
{
if (booking == null)
{
exportMessage = messages.get("booking-flushed");
return null;
}
String export = iCalManager.generateICal(booking);
if (export == null)
{
exportMessage = messages.get("export-error");
return null;
}
return new FileStreamResponse(IOUtils.toInputStream(export), "text/calendar", iCalManager.generateICalName(booking));
}
@OnEvent(value = EventConstants.ACTION, component = "end")
Object end()
{
booking = null;
return Home.class;
}
}
<file_sep>informations-alt-title=Informations sur le format iCalendar
informations-title=Informations<file_sep>book-label=Réserver
home-label=Accueil
feedback-label=Remarques
disconnect-label=Se déconnecter
profile-label=Profil
admin-label=Administration
sites-label=Sites
users-label=Utilisateurs
ref-label=Référentiel
roomfeatures-label=Caractéristiques des salles
params-label=Paramètres
roomeeting-description=Votre portail de réservation de salle de réunion<file_sep>title=Invalid behavior detected
message=An invalid behavior has been detected. Please contact your administrator for further explanations<file_sep>package fr.exanpe.roomeeting.domain.security.ad;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.InetOrgPerson;
import org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.stereotype.Component;
import fr.exanpe.roomeeting.common.enums.RoleEnum;
import fr.exanpe.roomeeting.domain.business.UserManager;
import fr.exanpe.roomeeting.domain.model.User;
@Component
public class LdapUserDetailsMapper implements UserDetailsContextMapper
{
private InetOrgPersonContextMapper ldapUserDetailsMapper = new InetOrgPersonContextMapper();
@Autowired
private UserManager userManager;
@Override
public UserDetails mapUserFromContext(DirContextOperations arg0, String arg1, Collection<? extends GrantedAuthority> arg2)
{
InetOrgPerson userLdap = (InetOrgPerson) ldapUserDetailsMapper.mapUserFromContext(arg0, arg1, arg2);
User u = userManager.findByUsername(userLdap.getUsername());
if (u == null)
{
u = new User();
u.addRole(userManager.findRole(RoleEnum.ADMIN.getCode()));
}
u.setExternal(true);
u.setEmail(userLdap.getMail());
u.setName(userLdap.getSn());
u.setUsername(userLdap.getUsername());
userManager.update(u);
return u;
}
@Override
public void mapUserToContext(UserDetails arg0, DirContextAdapter arg1)
{
ldapUserDetailsMapper.mapUserToContext(arg0, arg1);
}
}
<file_sep>package fr.exanpe.roomeeting.web.services;
import org.apache.tapestry5.ioc.Messages;
/**
* Return a message, or the key itself
*
* @author jmaupoux
*/
public class OptionalMessageService
{
public String getOptionalMessage(Messages messages, String key)
{
if (messages.contains(key)) { return messages.get(key); }
return key;
}
}
<file_sep>logo-alt=Retour à l'accueil
<file_sep>#!/bin/ksh
#------------------------------------------------------------------------
# Objet: Rajout du mapping dans V_DOSSIER_ADMINISTRATIF, la colonne DOM_VAL_LIB_R_SERIE_AFF a ete rajouté
#------------------------------------------------------------------------
if [ $# -eq 3 ]; then
sqlplus -s $1\/$2@$3 @01_ddl_TABLE.sql
else
echo " Le nombre de parametres en entree n'est pas correct"
echo 1.- nom utilisateur de la base de connexion
echo 2.- mot de passe de la base de connexion
echo 3.- oracle sid de la base de connexion
exit 1
fi
RET=$?
echo "Code Retour du traitement: $RET"
if [ $RET -ne 0 ]
then
echo "==> FIN ANORMALE 01_ddl_TABLE"
else
echo "==> FIN NORMALE 01_ddl_TABLE"
fi
exit $RET<file_sep>package fr.exanpe.roomeeting.domain.business.dto;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DateAvailabilityDTO
{
private Date date;
private List<SiteAvailabilityDTO> siteAvailabilityDTOs = new ArrayList<SiteAvailabilityDTO>();
public DateAvailabilityDTO(Date d)
{
super();
this.date = d;
}
/**
* @return the d
*/
public Date getDate()
{
return date;
}
/**
* @return the siteAvailabilityDTOs
*/
public List<SiteAvailabilityDTO> getSiteAvailabilityDTOs()
{
return siteAvailabilityDTOs;
}
}
<file_sep>package fr.exanpe.roomeeting.web.components;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;
import fr.exanpe.roomeeting.domain.business.FeedbackManager;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
public class Menu
{
@Inject
private FeedbackManager feedbackManager;
@Inject
private RooMeetingSecurityContext securityContext;
@Inject
private RequestGlobals requestGlobals;
public String getUsername()
{
// TODO : a modifier après avoir mis en place le filtre Spring Security
// return securityContext.getUser().getUsername();
return securityContext.getUser().getUsername();
}
public boolean isAuthenticated()
{
return securityContext.isLoggedIn();
}
public String getContextRoot()
{
return requestGlobals.getHTTPServletRequest().getContextPath();
}
public int getFeedbackCount()
{
return feedbackManager.count(securityContext.getUser());
}
}
<file_sep>generic-error-message=An unexpected error occurred.<file_sep>persons=persons
number-floor=th floor
room-label=Room
capacity-label=Capacity
features-label=Features<file_sep>title=Salles disponibles
return-search=Retour à la recherche
fully-available=Libre
from=De
to=à
hour-short=h
room-label=Salle
capacity-label=Capacité
availabilitie-s-label=Disponibilité(s)<file_sep>title=Remise à zéro du mot de passe
reset-message=Votre mot de passe a été réinitialisé et envoyé par email.
reset-password=<PASSWORD> de <PASSWORD>
username-label=Nom d'utilisateur
reset-button=Réinitialiser
error-mail-send=Erreur lors de l'envoi de l'email<file_sep>package fr.exanpe.roomeeting.common.utils;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
public final class RoomDateUtils
{
private RoomDateUtils()
{
}
/**
* Return the next working date, excluding {@link Calendar#SATURDAY} and {@link Calendar#SUNDAY}
*/
public static Date nextWorkingDay(Date date)
{
Calendar c = Calendar.getInstance();
c.setTime(date);
do
{
c.add(Calendar.DATE, 1);
}
while (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY);
return c.getTime();
}
/**
* Return the next working date, excluding {@link Calendar#SATURDAY} and {@link Calendar#SUNDAY}
*/
public static Date nextDay(Date date)
{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, 1);
return c.getTime();
}
public static Date setHourMinutes(Date date, int hour, int minutes)
{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minutes);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c = DateUtils.truncate(c, Calendar.MINUTE);
return c.getTime();
}
}
<file_sep>/**
*
*/
package fr.exanpe.roomeeting.domain.business.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import fr.exanpe.roomeeting.domain.business.FeedbackManager;
import fr.exanpe.roomeeting.domain.business.UserManager;
import fr.exanpe.roomeeting.domain.core.business.impl.DefaultManagerImpl;
import fr.exanpe.roomeeting.domain.core.dao.CrudDAO;
import fr.exanpe.roomeeting.domain.core.dao.QueryParameters;
import fr.exanpe.roomeeting.domain.model.Feedback;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.model.User;
@Service("feedbackManager")
public class FeedbackManagerImpl extends DefaultManagerImpl<Feedback, Long> implements FeedbackManager
{
private static final Logger LOGGER = LoggerFactory.getLogger(FeedbackManagerImpl.class);
// TODO parameter
private static final int MAX_RESULTS = 100;
@Autowired
private UserManager userManager;
@Autowired
private CrudDAO crudDAO;
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Feedback> list(User user)
{
Site site = userManager.findDefaultSite(user);
if (site == null) { return list(MAX_RESULTS); }
return crudDAO.findMaxResultsWithNamedQuery(Feedback.LIST_BY_SITE, QueryParameters.with("site", site).parameters(), MAX_RESULTS);
}
@Override
public int count(User user)
{
Site site = userManager.findDefaultSite(user);
if (site == null) { return (int) count(); }
return (int) crudDAO.count(Feedback.COUNT_BY_SITE, QueryParameters.with("site", site).parameters());
}
}
<file_sep>package fr.exanpe.roomeeting.web.pages.feedback;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import fr.exanpe.roomeeting.common.annotations.RoomeetingSecured;
import fr.exanpe.roomeeting.common.exception.HackException;
import fr.exanpe.roomeeting.domain.business.FeedbackManager;
import fr.exanpe.roomeeting.domain.model.Feedback;
import fr.exanpe.roomeeting.domain.security.RooMeetingSecurityContext;
import fr.exanpe.t5.lib.annotation.Authorize;
@Authorize(all = "AUTH_READ_FEEDBACK")
public class ListFeedbacks
{
@Persist
@Property
private List<Feedback> list;
@Property
private Feedback current;
@Inject
private FeedbackManager feedbackManager;
@Inject
private RooMeetingSecurityContext securityContext;
@RoomeetingSecured
void onActivate()
{
list = feedbackManager.list(securityContext.getUser());
}
@RoomeetingSecured
@OnEvent(value = EventConstants.ACTION, component = "delete")
public void delete(Long id)
{
for (Feedback f : list)
{
if (id.equals(f.getId()))
{
// security check
feedbackManager.delete(id);
return;
}
}
throw new HackException();
}
public boolean hasElements()
{
return CollectionUtils.isNotEmpty(list);
}
}
<file_sep>inconsistent-database=La base de données est incohérente. Impossibilité de réserver sur ce créneau.<file_sep>title=Reset password
reset-message=Your password has been reset and sent by email.
reset-password=<PASSWORD>
username-label=Username
reset-button=Reset
error-mail-send=Email sending failed<file_sep>package fr.exanpe.roomeeting.web.pages.admin;
import java.io.IOException;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.IOUtils;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Grid;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.springframework.security.access.AccessDeniedException;
import fr.exanpe.roomeeting.domain.business.RoomFeatureManager;
import fr.exanpe.roomeeting.domain.business.SiteManager;
import fr.exanpe.roomeeting.domain.model.Room;
import fr.exanpe.roomeeting.domain.model.Site;
import fr.exanpe.roomeeting.domain.model.ref.RoomFeature;
import fr.exanpe.t5.lib.annotation.ContextPageReset;
/**
* Welcome page
*/
public class ManageSite
{
@Property
@Persist
private Site site;
@Inject
private SiteManager siteManager;
@Inject
private RoomFeatureManager roomFeatureManager;
@Property
private Room currentRoom;
@Property
@Persist
private Room editRoom;
@Property
private UploadedFile roomMap;
@Property
@Persist(PersistenceConstants.FLASH)
private String errorUpload;
@InjectComponent("roomZone")
private Zone roomZone;
@InjectComponent(value = "gridRooms")
private Grid gridRooms;
@Inject
private Messages messages;
void onActivate()
{
if (site == null)
{
site = new Site();
editRoom = null;
}
}
boolean onActivate(Long siteId)
{
// TODO security
site = siteManager.findWithRooms(siteId);
editRoom = null;
return true;
}
@ContextPageReset
private void reset()
{
site = new Site();
editRoom = null;
}
Object onUploadException(FileUploadException ex)
{
errorUpload = messages.get("file-error");
return this;
}
@SetupRender
void init()
{
// TODO bug
if (CollectionUtils.isNotEmpty(site.getRooms()))
{
gridRooms.getDataModel().get("phoneNumber").sortable(false);
}
}
@OnEvent(value = "validateSite")
void validateSite()
{
site = siteManager.update(site);
editRoom = null;
}
@OnEvent(value = EventConstants.ACTION, component = "setupEditRoom")
Object setupEditRoom(Long id)
{
editRoom = null;
for (Room r : site.getRooms())
{
if (id.equals(r.getId()))
{
editRoom = r;
break;
}
}
if (editRoom == null) { throw new AccessDeniedException("Not authorized"); }
return roomZone.getBody();
}
@OnEvent(value = EventConstants.ACTION, component = "setupAddRoom")
Object setupAddRoom()
{
editRoom = new Room();
return roomZone.getBody();
}
@OnEvent(value = EventConstants.ACTION, component = "cancelRoom")
void cancelRoom()
{
editRoom = null;
}
@OnEvent(value = "validateRoom")
void validateRoom()
{
// Map
if (roomMap != null)
{
if (!(roomMap.getFileName().endsWith(".png") || roomMap.getFileName().endsWith(".jpg") || roomMap.getFileName().endsWith(".jpeg")))
{
errorUpload = messages.get("file-format");
return;
}
byte[] b;
try
{
b = IOUtils.toByteArray(roomMap.getStream());
}
catch (IOException e)
{
throw new RuntimeException(e);
}
editRoom.setMap(b);
}
if (editRoom.getId() == null)
{
siteManager.addRoom(site, editRoom);
}
else
{
siteManager.updateRoom(editRoom);
}
site = siteManager.findWithRooms(site.getId());
editRoom = null;
}
@OnEvent(value = EventConstants.ACTION, component = "deleteRoom")
void deleteRoom(Long id)
{
// security check
siteManager.removeRoom(site, id);
}
public boolean hasRooms()
{
return CollectionUtils.isNotEmpty(site.getRooms());
}
public boolean isSiteExists()
{
return site.getId() != null;
}
public boolean hasRoomMap()
{
return currentRoom.getMap() != null && currentRoom.getMap().length != 0;
}
public List<RoomFeature> listFeatures()
{
return roomFeatureManager.list();
}
}
| cf31e579770b8635a71502e153335469ec455f1f | [
"SQL",
"Markdown",
"JavaScript",
"Maven POM",
"INI",
"Java",
"Shell"
] | 101 | Maven POM | jmaupoux/roomeeting | 9286cd705b14aac89a45295fc17e0a82ef6ed879 | 7bdfa9e3c8e2bea08bb18dfb672059f5c5b1bfa0 |
refs/heads/master | <repo_name>SuhEunyeong/2020-2-ComputerVision<file_sep>/Find_Hidden_Object-master/src/hw_2018315051_main.py
import cv2
import os
import hw02_2018315051_template_matching
import imutils
import numpy as np
import math
def main():
os.chdir(os.path.dirname(os.path.abspath(__file__)))
img_template = cv2.imread('../img/fish.png')
img_reference = cv2.imread('../img/test_background.png')
x, y, angle, scale = hw02_2018315051_template_matching.template_matching(img_template, img_reference)
rotated = imutils.rotate_bound(img_template, angle)
h = rotated.shape[0] * scale
w = rotated.shape[1] * scale
if(angle < 90 or (angle > 180 and angle < 270)):
pts = np.array([[x + abs(math.sin(math.pi/(18/(angle/10))) * (37 * scale)), y], [x + w, y + abs(math.sin(math.pi/(18/(angle/10))) * (85 * scale))],
[x + abs(math.cos(math.pi/(18/(angle/10))) * (85 * ((i+1)/2))), y + h], [x,y + abs(math.cos(math.pi/(18/(angle/10))) * (37 * ((i+1)/2)))]], np.int32)
cv2.polylines (img_reference, [pts], True , (0,0,255), 2)
elif(angle > 270 or (angle > 90 and angle < 180)):
angle_test = angle - 180
pts = np.array([[x + abs(math.cos(math.pi/(18/(angle_test/10))) * (85 * scale)), y], [x + w, y + abs(math.cos(math.pi/(18/(angle_test/10))) * (37 * scale))],
[x + abs(math.sin(math.pi/(18/(angle_test/10))) * (37 * scale)), y + h], [x,y + abs(math.sin(math.pi/(18/(angle_test/10))) * (85 * scale))]], np.int32)
cv2.polylines (img_reference, [pts], True , (0,0,255), 2)
cv2.rectangle(img_reference, (x, y), (x + int(w), y + int(h)), (0,0,255), 2)
cv2.imshow("A", img_reference)
cv2.waitKey(0)
main() | 157d084ce535573dbbbcb78212e706f5ec71e0f7 | [
"Python"
] | 1 | Python | SuhEunyeong/2020-2-ComputerVision | 7b67e09b7d00d84a87d5cb63fed10e5177585149 | 4740f03b33eb9c816b6255296b1345f3a8722180 |
refs/heads/master | <repo_name>MAUAK/ExExemploHeranca<file_sep>/ExExemploHerança/Program.cs
using System;
namespace ExExemploHerança
{
class Program
{
static void Main(string[] args)
{
//Criando uma nova conta juridica e passando os valores de cada variável
ContaJuridica conta = new ContaJuridica(8010, "LARA", 100.0, 500.0);
//Imprimindo o saldo da conta cadastrada
Console.WriteLine(conta.Saldo);
}
}
}
<file_sep>/ExExemploHerança/ContaJuridica.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ExExemploHerança
{
//Criando uma subclasse Conta Juridica
class ContaJuridica : Conta
{
//Declarando a variável e usando o encapsulamento
public double EmprestimoLimite { get; set; }
//Criando o contrutor padrão
public ContaJuridica() { }
//Criando o construtor com parâmetros
public ContaJuridica(int numero, string titular, double saldo, double emprestimoLimite) : base(numero, titular, saldo)
{
EmprestimoLimite = emprestimoLimite;
}
//Criando o método Emprestimo
public void Emprestimo(double saldoTotal)
{
if (saldoTotal <= EmprestimoLimite)
{
Saldo += saldoTotal;
}
}
}
}
| 6b3ccb605dfad012e044b804c02fef30356de1bf | [
"C#"
] | 2 | C# | MAUAK/ExExemploHeranca | 192b88db743431fe238a016db9aeda511169a6ea | c091f17828bc68904a1077f9a49d6a9605f8262d |
refs/heads/master | <file_sep>#!/usr/bin/python
from Stream import Stream
import time
import threading
class StreamManager(object):
""" This class manages all streams """
STREAM = "stream"
SECS_BETWEEN_STATUS_CHECKS = 10
def __init__(self,streamDAO):
""" Load all streams and create maps that
facilitates later request handling """
self._streamDAO = streamDAO
self._streams = {stream.name : stream for
stream in streamDAO.getStreams()}
serverStreamTpls = [ (svr,stream) for stream in self.streams \
for svr in stream.servers ]
self._streamsByServer = {}
for key, val in serverStreamTpls:
self._streamsByServer.setdefault(key, []).append(val)
# Create thread status update Thread
self._t = threading.Thread(target=self.__updateStreamStatus)
self._t.daemon = True
self._t.start()
@property
def streamDAO(self): return self._streamDAO
@property
def streams(self):
return self._streams.values()
@property
def activeStreams(self):
""" Get list of all streams that are currently being served"""
s = {}
for server,streams in self._streamsByServer.items():
if (server.state == server.STATE.UP):
for stream in streams:
if (stream.getStreamState(server) == stream.STATE.UP):
s[stream] = ''
return s.keys()
def __updateStreamStatus(self):
""" Since different servers host different streams we
should request the status of all streams from each
server once and subsequently update the stream
objects. The server returns a dict with a all active
streams and their address."""
while(True):
for server,streams in self._streamsByServer.items():
activeStreams = server.getActiveStreams()
# Update each streams state
for stream in streams:
stream.lock.acquire()
stream.setStreamState(server,Stream.STATE.DOWN)
if (stream.name in activeStreams):
stream.setStreamState(server,Stream.STATE.UP)
stream.setStreamAddress(server,activeStreams[stream.name])
stream.lock.release()
time.sleep(StreamManager.SECS_BETWEEN_STATUS_CHECKS)
def getStream(self,name):
""" Get stream object by name """
if (name in self._streams):
return self._streams[name]
return None
def configureStream(self,name,cfg):
stream = self.getStream(name)
if (stream == None):
return
# Apply config
stream.applyConfig(cfg)
# Save config
self.streamDAO.persist(stream)
def requestStream(self,name):
""" Check if the requested stream can be provided by any server """
stream = self.getStream(name)
if (stream == None):
return Stream.STATE.DOWN
streamState = Stream.STATE.DOWN
for server in stream.servers:
address = stream.getStreamAddress(server)
if (not address == ''):
streamState = Stream.STATE.BUSY
if (server.curUpload + stream.dataRate < server.maxUpload):
return address
return streamState
<file_sep>#!/usr/bin/python
import abc
import md5
class UserMgmtDAO(object):
""" This is an abstract class for user management """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def getUserPwd(self,username):
""" Get user password """
pass
@abc.abstractmethod
def getUserGroups(self,username):
""" Get all group names that user is a member of """
pass
@staticmethod
def hashPwd(password):
""" Our standard way of hashing passwords """
return md5.new(password).hexdigest()
def isLoginValid(self,username,password):
""" Encrypt the password and check whether it is matching our db """
return self.hashPwd(password) in [self.getUserPwd(username)]
def isMemberOfGroup(self,username,group):
""" Check if user is member of a particular group """
return group in self.getUserGroups(username)
<file_sep>#!/usr/bin/python
# Some channels
channels=dict();
channels["ARD"] = "frequency=11836000:polarization=H:srate=27500000 --program=28106";
channels["ZDF"] = "frequency=11953500:polarization=H:srate=27500000 --program=28006";
channels["WDR"] = "frequency=12421500:polarization=H:srate=27500000 --program=28327";
channels["RTL"] = "frequency=12187000:polarization=H:srate=27500000 --program=12003";
channels["SAT1"] = "frequency=12544000:polarization=H:srate=22000000 --program=17500";
channels["PRO7"] = "frequency=12544000:polarization=H:srate=22000000 --program=17501";
channels["KABEL1"] = "frequency=12544000:polarization=H:srate=22000000 --program=17502";
channels["VOX"] = "frequency=12187500:polarization=H:srate=22000000 --program=12060";
channels["SPORT1"] = "frequency=12480000:polarization=V:srate=27500000 --program=900";
channels["EUROSPORT"] = "frequency=12226000:polarization=H:srate=27500000 --program=31200";
channels["EINSFESTIVAL"] = "frequency=10743800:polarization=H:srate=22000000 --program=28722";
channels["EINSPLUS"] = "frequency=10743800:polarization=H:srate=22000000 --program=28723";
channels["ZDFNEO"] = "frequency=11953500:polarization=H:srate=27500000 --program=28014";
channels["ZDFKULTUR"] = "frequency=11953500:polarization=H:srate=27500000 --program=28016";
channels["ZDFINFO"] = "frequency=11953500:polarization=H:srate=27500000 --program=28011";
channels["HR"] = "frequency=11836500:polarization=H:srate=27500000 --program=28108";
channels["BRALPHA"] = "frequency=12265500:polarization=H:srate=27500000 --program=28487";
channels["MDR"] = "frequency=12109500:polarization=H:srate=27500000 --program=28230";
channels["NDR"] = "frequency=12109500:polarization=H:srate=27500000 --program=28227";
channels["SR"] = "frequency=12265500:polarization=H:srate=27500000 --program=28486";
channels["SWR"] = "frequency=11836500:polarization=H:srate=27500000 --program=28113";
channels["KIKA"] = "frequency=11953500:polarization=H:srate=27500000 --program=28008";
channels["ARTE"] = "frequency=10743800:polarization=H:srate=22000000 --program=28724";
channels["N24"] = "frequency=12544800:polarization=H:srate=22000000 --program=17503";
channels["PHOENIX"] = "frequency=10743800:polarization=H:srate=22000000 --program=28725";
channels["DMAX"] = "frequency=12480000:polarization=V:srate=27500000 --program=63";
channels["BBC1"] = "frequency=10773000:polarization=H:srate=22000000 --program=6301 --dvb-satno=2";
channels["BBC2"] = "frequency=10773000:polarization=H:srate=22000000 --program=6302 --dvb-satno=2";
channels["ITV1"] = "frequency=10758000:polarization=V:srate=22000000 --program=10060 --dvb-satno=2";
channels["ITV1+1"] = "frequency=10891000:polarization=H:srate=22000000 --program=10145 --dvb-satno=2";
channels["ITV2"] = "frequency=10758000:polarization=V:srate=22000000 --program=10070 --dvb-satno=2";
channels["ITV2+1"] = "frequency=10891000:polarization=H:srate=22000000 --program=10165 --dvb-satno=2";
channels["ITV3"] = "frequency=10906000:polarization=V:srate=22000000 --program=10260 --dvb-satno=2";
channels["ITV3+1"] = "frequency=10906000:polarization=V:srate=22000000 --program=10261 --dvb-satno=2";
channels["ITV4"] = "frequency=10758000:polarization=V:srate=22000000 --program=10072 --dvb-satno=2";
channels["ITV4"] = "frequency=10832000:polarization=H:srate=22000000 --program=10015 --dvb-satno=2";
channels["E4"] = "frequency=10729000:polarization=V:srate=22000000 --program=8305 --dvb-satno=2";
channels["E4+1"] = "frequency=10729000:polarization=V:srate=22000000 --program=8300 --dvb-satno=2";
channels["MORE4"] = "frequency=10729000:polarization=V:srate=22000000 --program=8340 --dvb-satno=2";
channels["MORE4+1"] = "frequency=10714000:polarization=H:srate=22000000 --program=9230 --dvb-satno=2";
channels["FILM4"] = "frequency=10714000:polarization=H:srate=22000000 --program=9220 --dvb-satno=2";
channels["FILM4+1"] = "frequency=10714000:polarization=H:srate=22000000 --program=9225 --dvb-satno=2";<file_sep>#!/usr/bin/python
from Stream import Stream
import xml.etree.ElementTree as ET
from StreamDAO import StreamDAO
class XMLStreamDAO(StreamDAO):
""" This is an stream factory that gets its data from XML files """
def __init__(self,svrMgr,folder):
super(XMLStreamDAO,self).__init__(svrMgr)
self.streamXML = folder+'/stream.xml'
self.folder = folder+'/'
# Constants
STREAM = "stream"
def __getFromQuery(self,root,query):
''' Use simple query language to
dynamically parse the XML. Query format
elem1/elem2/.../elemn:attr1,attr2,... returns
a list of tuples of the following form
[(path.text,{attr1: val, attr2: val, ...}),...] or
[path.text,...] or [{attr1: val,...},...] either
path of attr are not required'''
qsplit = query.split(':')
attrs = []
if (len(qsplit) == 2):
attrs = qsplit[1].split(',')
data = []
for path in root.findall(qsplit[0]):
# Get element text if there is any
text = path.text
if (text == None):
text = ''
text = text.strip()
# Get element attributes
d = dict()
for attr in attrs:
d[attr] = path.get(attr)
if (len(d) > 0 and not text == ''):
data.append((text,d))
elif (not text == ''):
data.append(text)
elif (len(d) > 0):
data.append(d)
return data
def getStreams(self):
''' Load the stream configuration from XML files '''
xmlStreamRoot = ET.parse(self.streamXML).getroot()
streams = []
for stream in xmlStreamRoot.iter(XMLStreamDAO.STREAM):
# Generic stream information
name = self.__getFromQuery(stream,Stream.STREAM_NAME)[0]
servers = self.getServers(
self.__getFromQuery(stream,Stream.STREAM_SERVERS))
# Let's dynamically load the stream class definition
streamClassName = self.__getFromQuery(stream,Stream.STREAM_CLASS)[0]
streamClass = self.getStreamClass(streamClassName)
# Load current stream config
cfgFile = self.__getFromQuery(stream,Stream.STREAM_CFG)[0]
xmlCfgRoot = ET.parse(self.folder+cfgFile).getroot()
cfgCur = dict()
for c in Stream.STREAM_CFG_CUR:
cfgCur[c] = [self.__getFromQuery(xmlCfgRoot,c)[0]['cur']]
for c in streamClass.STREAM_CFG_CUR:
cfgCur[c] = [self.__getFromQuery(xmlCfgRoot,c)[0]['cur']]
# Get available config options
cfgOpts = []
for c in Stream.STREAM_CFG_OPTS:
cfgOpts.append(self.__getFromQuery(xmlCfgRoot,c))
clsCfgOpts = []
for c in streamClass.STREAM_CFG_OPTS:
clsCfgOpts.append(self.__getFromQuery(xmlCfgRoot,c))
# Create the new stream
streams.append(streamClass(name,servers,cfgCur,cfgOpts,cfgFile,
*clsCfgOpts))
return streams
def __setFromQuery(self,root,query,value):
''' Replace the current attribute pointed to
by the query with value query must have the
form path:attr'''
qsplit = query.split(':')
if (not len(qsplit) == 2):
return
for path in root.findall(qsplit[0]):
path.set(qsplit[1],value)
def persist(self,stream):
''' Save the configutation of the stream to XML '''
xmlCfgTree = ET.parse(self.folder+stream.cfgFile)
xmlCfgRoot = xmlCfgTree.getroot()
for k,v in stream.getCfg().items():
self.__setFromQuery(xmlCfgRoot,k,v)
xmlCfgTree.write(self.folder+stream.cfgFile)
<file_sep>#!/bin/sh
# /etc/init.d/tvonline
### BEGIN INIT INFO
# Provides: tvonline
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start the TVOnlineWeb server
# Description: TVOnline is a program that serves video streams
### END INIT INFO
cd /home/pi/tvonline
case "$1" in
start)
echo "Starting tvOnline"
nohup python tvOnlineWeb.py > log.txt 2>&1 &
PID=$!
GPID=`ps x -o "%p %r" | grep ${PID} | sed -e 's/^ \w*\ *//'`
echo ${GPID} > gpid.txt
;;
stop)
echo "Stopping tvOnline"
GPID=`cat gpid.txt`
kill -9 -${GPID}
;;
*)
echo "Usage: /etc/init.d/tvonline {start|stop}"
exit 1
;;
esac
exit 0
<file_sep>#!/usr/bin/python
from Config import Config
import abc
class ConfigDAO(object):
""" This is an abstract class for config data access objects """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def loadConfig(self):
""" Load current configuration.
@return Config object """
pass
@abc.abstractmethod
def saveConfig(self, cfg):
""" Save configuration.
@return True iff stored successfully """
pass
def persistConfig(self, audioCodec,
audioRate, videoCodec,
videoRate, videoSize,
streamEncryption):
""" This function checks and prepares the configuration
values posted by the user and saves them.
@return (Success(T/F),Msg)"""
# Check the new configuration values
cfg = self.loadConfig()
if (not audioCodec in cfg.audioCodecs or
not int(audioRate) in cfg.audioRates or
not videoCodec in cfg.videoCodecs or
not int(videoRate) in cfg.videoRates or
not int(videoSize) in cfg.videoSizes or
not streamEncryption in cfg.streamEncryptions):
return (False,'Chosen configuration is not supported. '+
'Configuration was not saved')
# Store the configuration
cfg = Config()
cfg.curAudioCodec = audioCodec
cfg.curAudioRate = audioRate
cfg.curVideoCodec = videoCodec
cfg.curVideoRate = videoRate
cfg.curVideoSize = videoSize
cfg.curStreamEncryption = streamEncryption
cfg.curEncryptionKey = 'NewKey'
status = (True,'Successfully saved new configuration.')
try:
if(not self.saveConfig(cfg)):
status = (False,'Failed to save the new configuration.')
except:
status = (False,'An error occurred while saving the '+
'configuration.')
return status
<file_sep>#!/usr/bin/python
from Config import Config
from ConfigDAO import ConfigDAO
import xml.etree.ElementTree as ET
class XMLConfigDAO(ConfigDAO):
""" This is a implementation of the ConfigDAO abstract class which
uses an XML file to store the data. """
def __init__(self,folder):
self.folder = folder
def loadConfig(self):
cfg = Config()
xmlRoot = ET.parse(self.folder+'/config.xml').getroot()
# Load audio config
cfg.audioCodecs = [str(codec.text) for codec
in xmlRoot.find('audiocodecs').iter('audiocodec')]
cfg.curAudioCodec = str(xmlRoot.find('audiocodecs').get('cur'))
cfg.audioRates = [int(rate.text) for rate
in xmlRoot.find('audiorates').iter('audiorate')]
cfg.curAudioRate = str(xmlRoot.find('audiorates').get('cur'))
# Load video config
cfg.videoCodecs = [str(codec.text) for codec
in xmlRoot.find('videocodecs').iter('videocodec')]
cfg.curVideoCodec = str(xmlRoot.find('videocodecs').get('cur'))
cfg.videoRates = [int(rate.text) for rate
in xmlRoot.find('videorates').iter('videorate')]
cfg.curVideoRate = int(xmlRoot.find('videorates').get('cur'))
cfg.videoSizes = [int(size.text) for size
in xmlRoot.find('videosizes').iter('videosize')]
cfg.curVideoSize = int(xmlRoot.find('videosizes').get('cur'))
# Load stream Config
cfg.streamEncryptions = [str(enc.text) for enc
in xmlRoot.find('streamencryptions')
.iter('streamencryption')]
cfg.curStreamEncryption = str(xmlRoot.find('streamencryptions')
.get('cur'))
cfg.curEncryptionKey = str(xmlRoot.find('streamencryptions')
.get('key'))
return cfg
def saveConfig(self, cfg):
# Load current config
xml = ET.parse(self.folder+'/config.xml')
xmlRoot = xml.getroot()
# Update config
xmlRoot.find('audiocodecs').set('cur',cfg.curAudioCodec)
xmlRoot.find('audiorates').set('cur',cfg.curAudioRate)
xmlRoot.find('videocodecs').set('cur',cfg.curVideoCodec)
xmlRoot.find('videorates').set('cur',cfg.curVideoRate)
xmlRoot.find('videosizes').set('cur',cfg.curVideoSize)
xmlRoot.find('streamencryptions').set('cur',cfg.curStreamEncryption)
xmlRoot.find('streamencryptions').set('key',cfg.curEncryptionKey)
# Save config
xml.write(self.folder+'config.xml')
return True
<file_sep>import time
import threading
from functools import wraps
from LinuxCommands import LinuxCommands as Commands
SERVER_SECRET = "MyBigFatSecret"
STREAM_ADDRESS = "machr666.no-ip.org"
def checkAuth(f):
@wraps(f)
def wrapper(self,*args,**kwds):
# Ensure that only servers who know this server's
# secret can execute functions on this stream server
if (not str(args[0]) == SERVER_SECRET):
print (str(args[0]) + ' is an invalid secret')
return [False,"Server secret is wrong"]
return f(self,*args[1:],**kwds)
return wrapper
class TVOnlineService(object):
""" Provides functions that the TV-Online website expects
Stream servers to have """
UPLOAD_RATE_CALC_INTVL = 5
UPLOAD_DEVICES = ['wlan0']
def __init__(self):
self.__curUploadRate = 0
self.__lastTtlUpload = 0
self.__lock = threading.Lock()
self.__cmds = Commands()
self.__streams = {}
self.__t = threading.Thread(target=self.__monitorUploadRate)
self.__t.daemon = True
self.__t.start()
#----------------------------------------------------
# Monitor and control stream server
#----------------------------------------------------
def __monitorUploadRate(self):
""" Continually update the current upload rate in bit/s """
while(True):
ttl = self.__cmds.getTtlUploadRate(TVOnlineService.UPLOAD_DEVICES)
rate = (ttl-self.__lastTtlUpload)/TVOnlineService.UPLOAD_RATE_CALC_INTVL
self.__lastTtlUpload = ttl
self.__lock.acquire()
self.__curUploadRate = rate
self.__lock.release()
time.sleep(TVOnlineService.UPLOAD_RATE_CALC_INTVL)
@checkAuth
def shutdown(self):
""" Shut down the server """
print('Shutting down TVOnline stream server.')
if (self.__cmds.shutdown()):
return [True, 'Success: Process launched']
return [False, 'Error: Failed to launch process']
@checkAuth
def curUploadRate(self):
""" Determine current upload rate in bits """
self.__lock.acquire()
rate = self.__curUploadRate
self.__lock.release()
return [True, rate]
#----------------------------------------------------
# Monitor stream processes
#----------------------------------------------------
@checkAuth
def activeStreams(self):
""" Return addresses of all active streams """
inactive = []
for name,(proc,address) in self.__streams.items():
if (not proc.isAlive()): inactive.append(name)
for name in inactive:
print ("Stream: "+name+" has stopped")
del self.__streams[name]
running = {name : address for name,(proc,address)
in self.__streams.items()}
print("Currently running streams: "+str(running))
return [True, running]
#----------------------------------------------------
# Starting and stopping streams
#----------------------------------------------------
def __stopOldStream(self,cfg):
name = self.__cmds.streamName(cfg)
if (name in self.__streams):
return self.__streams[name][0].kill()
return True
@checkAuth
def startStream(self,cfg):
""" Start a new stream """
if (not self.__stopOldStream(cfg)):
return [False, 'Error: Failed to terminate current '+
'instance of the stream: '+str(cfg)]
(name, proc, protocol, port, sFile) = self.__cmds.startStream(cfg)
self.__streams[name] = (proc,str(protocol+'://'+str(STREAM_ADDRESS)+
':'+str(port)+"/"+str(sFile)))
return [True, {name : self.__streams[name][1]}]
@checkAuth
def stopStream(self, cfg):
if (self.__stopOldStream(cfg)):
return [True, 'Success: Stopped stream: '+str(cfg)]
return [False, 'Error: Could not stop stream: '+str(cfg)]
<file_sep>import xmlrpclib
server = xmlrpclib.Server('https://localhost:1443')
server2 = xmlrpclib.Server('https://localhost:1443')
print server.shutdown("TVOnlineRules")
print server2.curUploadRate("TVOnlineRules")
<file_sep>#!/usr/bin/python
from util.util import *
from Server import Server
import time
import xmlrpclib
import threading
class BaseServer(Server):
""" This class represents a generic stream server """
SERVER_ARGS = []
MAX_PING_TRIAL = 3
MAX_BOOT_TIME_SECS = 60
SECS_BETWEEN_STATE_CHECKS = 5
def __init__(self,name,address,maxStreams,uplink,tvOnlinePort,
tvOnlineSecret,maxUpload):
super(BaseServer,self).__init__(name,address,maxStreams,uplink,
tvOnlinePort,tvOnlineSecret,maxUpload)
# Let's create background process that regularly checks if
# the server status
self._lock = threading.Lock()
self.__t = threading.Thread(target=self.__checkState)
self.__t.daemon = True
self.__t.start()
@property
def server(self): return xmlrpclib.Server('https://'+self.address+":"+
str(self.tvOnlinePort))
@property
def lock(self): return self._lock
def __checkState(self):
""" Check current server state """
while(True):
# Has the maximum boot time been exceeded?
if (self.state == Server.STATE.BOOT and
getTStamp() - self.stateTStamp >=
BaseServer.MAX_BOOT_TIME_SECS):
self.lock.acquire()
self.state = Server.STATE.DOWN
self.lock.release()
# Server up and running?
if (self.__getCurUploadRate()):
self.lock.acquire()
self.state = Server.STATE.UP
self.pingTrials = 0
self.lock.release()
# Ping failure
else:
self.lock.acquire()
self.pingTrials += 1
if (not self.state == Server.STATE.BOOT and
self.pingTrials == BaseServer.MAX_PING_TRIAL):
self.state = Server.STATE.DOWN
self.lock.release()
# Let's wait a while
time.sleep(BaseServer.SECS_BETWEEN_STATE_CHECKS)
def __getCurUploadRate(self):
resp = [False,0]
try:
# Returns [True,rate]
resp = self.server.curUploadRate(self.tvOnlineSecret)
if (resp[0]):
uploadRate = resp[1]
except:
uploadRate = 0
self.lock.acquire()
self.curUpload = uploadRate/1024
self.lock.release()
return resp[0]
def startServer(self):
pass
def __shutdown(self):
retVal = False
try:
resp = self.server.shutdown(self.tvOnlineSecret)
retVal = resp[0]
if (not retVal):
print(resp[1])
except Exception, e:
print(e)
return retVal
def stopServer(self):
# Let spawn a process that executes the remote shutdown
t = threading.Thread(target=self.__shutdown)
t.daemon = True
t.start()
def getActiveStreams(self):
retVal = {}
try:
# Response is [T/F,{name : address,...}]
resp = self.server.activeStreams(self.tvOnlineSecret)
if (resp[0]):
retVal = resp[1]
else:
print (resp[1])
except Exception, e:
print(e)
return retVal
def __startStream(self,cfg):
print("Starting stream with args "+str(cfg))
retVal = False
try:
resp = self.server.startStream(self.tvOnlineSecret,cfg)
retVal = resp[0]
if (not retVal):
print (resp[1])
except Exception, e:
print(e)
return retVal
def startStream(self,cfg):
t = threading.Thread(target=self.__startStream,args=(cfg,))
t.daemon = True
t.start()
def __stopStream(self,cfg):
print("Stopping stream with args "+str(cfg))
retVal = False
try:
resp = self.server.stopStream(self.tvOnlineSecret,cfg)
retVal = resp[0]
if (not retVal):
print (resp[1])
except Exception, e:
print(e)
return retVal
def stopStream(self,cfg):
t = threading.Thread(target=self.__stopStream,args=(cfg,))
t.daemon = True
t.start()
<file_sep>#!/usr/bin/python
from util.util import *
import abc
class ServerDAO(object):
""" This is an abstract class for a server factory """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def getServers(self):
pass
def getServerClass(self,name):
return getClass(name)
<file_sep>#!/usr/bin/python
from UserMgmtDAO import UserMgmtDAO
import xml.etree.ElementTree as ET
class XMLUserMgmtDAO(UserMgmtDAO):
""" This is a XML implementation of UserMgmtDAO """
def __init__(self,folder):
xmlUserRoot = ET.parse(folder+"/user.xml").getroot()
self.__userDB = {}
self.__groupDB = {}
for user in xmlUserRoot.iter('user'):
name = user.get('name')
self.__userDB[name] = user.get('pwd')
self.__groupDB[name] = []
for group in user.findall('groups/group'):
self.__groupDB[name].append(group.get('name'))
def getUserPwd(self,username):
if (username in self.__userDB):
return self.__userDB[username]
return []
def getUserGroups(self,username):
if (username in self.__groupDB):
return self.__groupDB[username]
return []
<file_sep>import base64
import uuid
f = open('cookiesecret.txt','w+')
f.write(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))
f.close
<file_sep>import os.path
import socket
import tornado.web
import tornado.httpserver
import tornado.options
import tornado.ioloop
# User authentication and rights management
from usermgmt.XMLUserMgmtDAO import XMLUserMgmtDAO
userDAO = XMLUserMgmtDAO('data')
# Server configuration
from stream.server.XMLServerDAO import XMLServerDAO
from stream.server.ServerManager import ServerManager
serverMgr = ServerManager(XMLServerDAO('data'))
# Stream configuration
from stream.Stream import Stream
from stream.XMLStreamDAO import XMLStreamDAO
from stream.StreamManager import StreamManager
streamMgr = StreamManager(XMLStreamDAO(serverMgr,'data'))
from tornado.options import define, options
class TVServer(tornado.web.Application):
''' Configure server '''
def __init__(self):
handlers = [
(r"/", ReqHandler),
(r"/login", LoginHandler),
(r"/logout", LogoutHandler),
(r"/tv", TVHandler),
(r"/stream", StreamHandler),
(r"/server", ServerManagerHandler),
(r"/(\w+)", ReqHandler),
]
mainDir = os.path.dirname(__file__)
f = open('cookiesecret.txt','r')
cookie_secret = f.read()
f.close()
settings = dict(
xsrf_cookies = True,
cookie_secret = cookie_secret,
login_url = "/login",
template_path = os.path.join(mainDir, "templates/myStyle"),
static_path = os.path.join(mainDir, "templates/myStyle/static")
)
tornado.web.Application.__init__(self, handlers, **settings)
#---------------------------------------------------------------
# Utility classes and functions
#---------------------------------------------------------------
class PersonalisedRequestHandler(tornado.web.RequestHandler):
''' This class specifies how we store the user identity '''
def get_current_user(self):
return self.get_secure_cookie("user")
def delete_session_cookie(self):
self.clear_cookie("user");
# Decorator that checks both whether user is authenticated and
# if they are authorised
def requireAuth(groups=[]):
def _decorator(f):
@tornado.web.authenticated
def wrappedF(self,*args):
if (groups == [] or
[userDAO.isMemberOfGroup(self.current_user,group)
for group in groups].count(True) > 0):
f(self,*args)
return
self.render("../noauth.html")
return wrappedF
return _decorator
#---------------------------------------------------------------
# Request Handlers
#---------------------------------------------------------------
class LoginHandler(PersonalisedRequestHandler):
''' Show the login page and handle authentication process '''
def get(self):
if not self.current_user:
self.render("../login.html", failure=False)
return
self.redirect("/")
def post(self):
# Login failure
if (not userDAO.isLoginValid(self.get_argument("username"),
self.get_argument("password"))):
self.render("../login.html", failure=True)
return
# Login success
self.set_secure_cookie("user", self.get_argument("username"))
self.redirect("/")
class LogoutHandler(PersonalisedRequestHandler):
''' End the user's current session '''
def get(self):
self.delete_session_cookie()
self.redirect("/")
class TVHandler(PersonalisedRequestHandler):
''' Handle get/post requests for the tv video page '''
@requireAuth()
def get(self):
self.render("../tv.html",
streams=streamMgr.activeStreams,
curStream='',
curStreamAddress='/static/images/chooseStream.jpg')
@requireAuth()
def post(self):
streamName = self.get_argument(streamMgr.STREAM,'')
addr = streamMgr.requestStream(streamName)
if (addr == Stream.STATE.BUSY):
addr = '/static/images/busyStream.jpg'
elif (addr == Stream.STATE.DOWN):
addr = '/static/images/chooseStream.jpg'
self.render("../tv.html",
streams=streamMgr.activeStreams,
curStream=streamName,
curStreamAddress=addr)
class ServerManagerHandler(PersonalisedRequestHandler):
''' Handle get/post requests for the server configuration page '''
@requireAuth(["admin"])
def get(self):
self.render("../server.html",
SERVER=serverMgr.SERVER,
STATE=serverMgr.STATE,
infrastructure=serverMgr.infrastructure)
@requireAuth(["admin"])
def post(self):
serverMgr.changeServerState(self.get_argument(serverMgr.SERVER),
self.get_argument(serverMgr.STATE))
self.render("../server.html",
SERVER=serverMgr.SERVER,
STATE=serverMgr.STATE,
infrastructure=serverMgr.infrastructure)
class StreamHandler(PersonalisedRequestHandler):
''' Handle get/post requests for the stream configuration page '''
@requireAuth(["admin"])
def get(self):
self.render("../stream.html", streams=streamMgr.streams)
@requireAuth(["admin"])
def post(self):
streamMgr.configureStream(self.get_argument(streamMgr.STREAM),
self.request.arguments)
self.render("../stream.html", streams=streamMgr.streams)
class ReqHandler(PersonalisedRequestHandler):
''' Handle get/post requests for the TVOnline website '''
@requireAuth()
def get(self, page="home"):
self.render("../" + page + ".html")
def get_error_html(self, status_code, **kwargs):
self.render("../error.html")
#---------------------------------------------------------------
# Launch the server
#---------------------------------------------------------------
define("port", default=8001, help="Server port", type=int)
mainDir = os.path.dirname(__file__)
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(TVServer(),
ssl_options = {"certfile": os.path.join(mainDir, "certs/tvonline.crt"),
"keyfile": os.path.join(mainDir, "certs/tvonline.key")})
#http_server.listen(options.port)
http_server.bind(options.port,family=socket.AF_INET)
http_server.start(1) # TODO: Currently start(0) doesn't work because of
# threading issues (objects aren't updated properly)
tornado.ioloop.IOLoop.instance().start()
<file_sep>#!/usr/bin/python
from util.util import *
import abc
class Server(object):
""" This abstract class represents a generic stream server """
__metaclass__ = abc.ABCMeta
SERVER_CLASS = 'svrclass'
SERVER_UPLINK = 'uplink'
SERVER_UPLINK_NAME = 'name'
# Generic constructor arguments
SERVER_ARGS = ['name','address','maxStreams','uplink','tvOnlinePort',
'tvOnlineSecret']
UPLINK_ARGS = ['maxUpload']
STATE = enum(UP='Online', DOWN='Offline', BOOT='Booting')
def __init__(self,name,address,maxStreams,uplink,tvOnlinePort,
tvOnlineSecret,maxUpload):
self._name = name
self._address = address
self._maxStreams = int(maxStreams)
self._uplink = uplink
self._tvOnlinePort = int(tvOnlinePort)
self._tvOnlineSecret = tvOnlineSecret
self._maxUpload = int(maxUpload)
self._curUpload = 0
self._state = Server.STATE.DOWN
self.updateStateChangeTStamp()
self._pingTrials = 0
def __eq__(self,other):
if other == None:
return False
return cmp(self,other)
def __cmp__(self,other):
return cmp(self.name, other.name)
def __str__(self):
return str(self.name + " Type: " + self.serverType +
" Addr: " + self.address +
" Uplink: " + self.uplink +
" UploadMax: " + str(self.maxUpload) +
" CurUpload: " + str(self.curUpload))
@property
def serverType(self): return self.__class__.__name__
@property
def name(self): return self._name
@property
def address(self): return self._address
@property
def maxStreams(self): return self._maxStreams
@property
def uplink(self): return self._uplink
@property
def tvOnlinePort(self): return self._tvOnlinePort
@property
def tvOnlineSecret(self): return self._tvOnlineSecret
@property
def maxUpload(self): return self._maxUpload
@property
def curUpload(self): return self._curUpload
@curUpload.setter
def curUpload(self,value): self._curUpload = value
@property
def state(self): return self._state
@state.setter
def state(self,value): self._state = value
@property
def stateTStamp(self): return self._stateTStamp
@stateTStamp.setter
def stateTStamp(self,value): self._stateTStamp = value
@property
def pingTrials(self): return self._pingTrials
@pingTrials.setter
def pingTrials(self,value): self._pingTrials = value
def updateStateChangeTStamp(self):
self.stateTStamp = getTStamp()
def changeState(self,state):
""" Set server state """
print(state)
if (state == Server.STATE.UP):
print("Booting up " + self.name)
self.startServer()
self.lock.acquire()
self.state = Server.STATE.BOOT
self.updateStateChangeTStamp()
self.lock.release()
elif (state == Server.STATE.DOWN):
print("Shutting down " + self.name)
self.stopServer()
# Boot the remote server
@abc.abstractmethod
def startServer(self):
pass
# Shutdown the remote server
@abc.abstractmethod
def stopServer(self):
pass
# Get the status of all streams running on the
# server. Returns a list with the name of all
# streams that are currently running
@abc.abstractmethod
def getActiveStreams(self):
pass
# Start a new stream
@abc.abstractmethod
def startStream(self,cfg):
pass
# Stop a stream
@abc.abstractmethod
def stopStream(self,cfg):
pass
<file_sep>#!/usr/bin/python
import sys
from MockUserMgmtDAO import MockUserMgmtDAO
m = MockUserMgmtDAO()
print(m.hashPwd(sys.argv[1]))
<file_sep>tvonline
========
TVOnline consists of a backend and a frontend application that allows different
video and audio streams to be consumed over the internet through the browser or
external video players.
Front-End:
An Python-Tornado web app that keeps track of the status of registered stream
servers and streams hosted on them. General users can choose to watch any of the
running streams. Administrators can further remotely turn on/off stream servers
and reconfigure streams.
Back-End:
The python back-end is currently only running on Linux servers that have VLC
installed. It is a simple secure XML-RPC service that start/stops streams upon
requests from Administrators. Moreover, each server also manages its upload and
further accepts shutdown requests from Administrators. Currently there is only
support for dvb-s tv streams, but DVD, file, or other stream types could easily
be added.
<file_sep>"""
SecureXMLRPCServer.py - simple XML RPC server supporting SSL.
Based on this article: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549
For windows users: http://webcleaner.sourceforge.net/pyOpenSSL-0.6.win32-py2.4.exe
Also special thanks to http://rzemieniecki.wordpress.com/2012/08/10/quick-solution-to-ssl-in-simplexmlrpcserver-python-2-6-and-2-7/
"""
# Configure below
LISTEN_HOST='127.0.0.1' # You should not use '' here, unless you have a real FQDN.
LISTEN_PORT=1443
KEYFILE = 'certs/tvonline.key'
CERTFILE = 'certs/tvonline.crt'
# Configure above
import SocketServer
import BaseHTTPServer
import SimpleXMLRPCServer
import fcntl, ssl, socket, os, sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"/../.."
sys.path.insert(0,parentdir)
from TVOnlineService import TVOnlineService
class SecureXMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
"""
Secure XML-RPC server.
It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
"""
def __init__(self, server_address, HandlerClass, logRequests=True):
self.logRequests = logRequests
SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
self.socket = ssl.wrap_socket(socket.socket(), server_side=True,
certfile=CERTFILE,keyfile=KEYFILE,
ssl_version=ssl.PROTOCOL_SSLv23)
self.server_bind()
self.server_activate()
# [Bug #1222790] If possible, set close-on-exec flag; if a
# method spawns a subprocess, the subprocess shouldn't have
# the listening socket open.
if hasattr(fcntl, 'FD_CLOEXEC'):
flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
"""
Secure XML-RPC request handler class.
It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
"""
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def do_POST(self):
try:
# Unmarshal request an execute it
data = self.rfile.read(int(self.headers["content-length"]))
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
except: # This should only happen if the module is buggy
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
else:
# got a valid XML RPC response
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
# shut down the connection
self.connection.shutdown(socket.SHUT_RDWR)
self.connection.close()
def server(HandlerClass=SecureXMLRpcRequestHandler,
ServerClass=SecureXMLRPCServer,
instance=TVOnlineService()):
server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port)
server = ServerClass(server_address, HandlerClass)
server.register_instance(instance)
sa = server.socket.getsockname()
print "Serving HTTPS on", sa[0], "port", sa[1]
server.serve_forever()
if __name__ == '__main__':
server()
<file_sep>#!/usr/bin/python
class Config(object):
""" This class stores the choices made by users on the config page """
def __str__(self):
return str("Audio Codec:"+str(self.curAudioCodec)+
" Rate:"+str(self.curAudioRate)+"kbit/s\n"+
"Video Codec:"+str(self.curVideoRate)+
" Rate:"+str(self.curVideoRate)+"kbit/s"+
" Size:"+str(self.curVideoSize)+"%\n"+
"Stream encryption:"+str(self.curStreamEncryption)+
" Key:"+str(self.curEncryptionKey))
# Audio config
@property
def audioCodecs(self): return self._audioCodecs
@audioCodecs.setter
def audioCodecs(self, value): self._audioCodecs = value
@property
def curAudioCodec(self): return self._curAudioCodec
@curAudioCodec.setter
def curAudioCodec(self, value): self._curAudioCodec = value
@property
def audioRates(self): return self._audioRates
@audioRates.setter
def audioRates(self, value): self._audioRates = value
@property
def curAudioRate(self): return self._curAudioRate
@curAudioRate.setter
def curAudioRate(self, value): self._curAudioRate = value
# Video config
@property
def videoCodecs(self): return self._videoCodecs
@videoCodecs.setter
def videoCodecs(self, value): self._videoCodecs = value
@property
def curVideoCodec(self): return self._curVideoCodec
@curVideoCodec.setter
def curVideoCodec(self, value): self._curVideoCodec = value
@property
def videoRates(self): return self._videoRates
@videoRates.setter
def videoRates(self, value): self._videoRates = value
@property
def curVideoRate(self): return self._curVideoRate
@curVideoRate.setter
def curVideoRate(self, value): self._curVideoRate = value
@property
def videoSizes(self): return self._videoSizes
@videoSizes.setter
def videoSizes(self, value): self._videoSizes = value
@property
def curVideoSize(self): return self._curVideoSize
@curVideoSize.setter
def curVideoSize(self, value): self._curVideoSize = value
# Stream config
@property
def streamEncryptions(self): return self._streamEncryptions
@streamEncryptions.setter
def streamEncryptions(self, value): self._streamEncryptions = value
@property
def curStreamEncryption(self): return self._curStreamEncryption
@curStreamEncryption.setter
def curStreamEncryption(self, value): self._curStreamEncryption = value
<file_sep>#!/usr/bin/python
class StreamConfigControl(object):
""" This class controls the stream configuration """
def __init__(self,streamsCfgDAO):
self.streamsCfgDAO = streamsCfgDAO
@property
def streams(self): return self.streamsCfgDAO.streams
def loadStreamCfg(self, streamName):
""" Get the configuration for a stream by name """
return self.streamsCfgDAO.getCfg(streamName)
def saveStreamCfg(self, streamCfg):
""" Update the configuration for a stream """
return self.streamsCfgDAO.setCfg(streamCfg)
<file_sep>$(document).ready(function() {
// Elements in document
var $content = $("#content"),
$nav = $("#nav"),
$load = $("#load");
// This function changes the content
var updatePage = function(state) {
$content.slideUp('fast', function() {
$load.fadeIn('fast');
$.get(state, function (data) {
var tempHTML=data.replace(/<script/g, "<dynscript").replace(/<\/script/g, "</dynscript");
cnt=$(tempHTML).find("#content").html().replace(/dynscript/g, "script");
$content.html(cnt);
$load.fadeOut('normal');
$content.slideDown('normal');
});
});
}
// This will make the backward/forward buttons work
$.History.bind(function(state) {
updatePage(state);
});
});
<file_sep>#!/usr/bin/python
from UserMgmtDAO import UserMgmtDAO
class MockUserMgmtDAO(UserMgmtDAO):
""" This is a Mock implementation of MockUserMgmtDAO """
def __init__(self):
self.userDB = { 'machr666' : self.hashPwd('secret'),
'bob' : self.hashPwd('<PASSWORD>')}
self.groupDB = { 'machr666' : ['user','admin'],
'bob' : ['user'] }
def getUserPwd(self,username):
if (username in self.userDB):
return self.userDB[username]
return []
def getUserGroups(self,username):
if (username in self.groupDB):
return self.groupDB[username]
return []
<file_sep>#!/usr/bin/python
import time
def enum(**enums):
return type('Enum', (), enums)
def getClass(name):
pkgMod = '.'.join(name.split('.')[0:-1])
clsName = name.split('.')[-1]
mod = __import__(pkgMod, fromlist=[clsName])
return getattr(mod, clsName)
def getTStamp():
return time.time()
<file_sep>#!/usr/bin/python
from Stream import Stream
class DVBSStream(Stream):
""" This class represents a DVB-S stream """
STREAM_CFG_CUR = ['channels:cur']
STREAM_CFG_OPTS = ['channels/channel:name,id,cat',
'categories/category:name,id']
def __init__(self,name,servers,cfgCur,cfgOpts,cfgFile,
channels,categories):
super(DVBSStream,self).__init__(name,servers,cfgCur,cfgOpts,cfgFile)
self._channels = {}
self._catChannels = {}
for cat in categories:
l = []
for chan in channels:
if (chan['cat'] == cat['id']):
l.append(chan['id'])
self._channels[chan['id']] = [chan['name']]
self._catChannels[cat['name']] = l
# Store current config in object
self.applyConfig(cfgCur)
def __str__(self):
retVal = super(DVBSStream,self).__str__()
for cat, channels in self.catChannels.items():
retVal += 'Channels in Category: '+cat+'\n'
for chan in channels:
retVal+='\t'+chan+'\n'
return retVal
@property
def displayName(self): return self.name + ": " +\
self.channelName(self.curChannel)
@property
def curChannel(self): return self._curChannel
@curChannel.setter
def curChannel(self,value): self._curChannel = value
@property
def channels(self): return self._channels
@property
def catChannels(self): return self._catChannels
def channelName(self,channel): return self.channels[channel][0]
def applyConfig(self,cfg):
self.lock.acquire()
if (cfg[DVBSStream.STREAM_CFG_CUR[0]][0] in self.channels):
self.curChannel = cfg[DVBSStream.STREAM_CFG_CUR[0]][0]
self.lock.release()
# Update remaining attributes and notify stream servers of changes
# if necessary
super(DVBSStream,self).applyConfig(cfg)
def getCfg(self):
cfg = super(DVBSStream,self).getCfg()
self.lock.acquire()
cfg[DVBSStream.STREAM_CFG_CUR[0]] = self.curChannel
self.lock.release()
return cfg
<file_sep>#!/usr/bin/python
from util.util import *
import abc
import threading
class Stream(object):
""" This abstract class represents a generic stream """
__metaclass__ = abc.ABCMeta
STREAM_NAME = 'name'
STREAM_CLASS = 'streamClass'
STREAM_SERVERS = 'servers/server'
STREAM_CFG = 'streamConfig'
STREAM_CFG_CUR = ['audioCodecs:cur', 'audioRates:cur',
'videoCodecs:cur','videoRates:cur',
'videoSizes:cur',
'streamEncryptions:cur']
STREAM_CFG_OPTS = ['audioCodecs/audioCodec','audioRates/audioRate',
'videoCodecs/videoCodec','videoRates/videoRate',
'videoSizes/videoSize',
'streamEncryptions/streamEncryption']
STATE = enum(UP='Up', DOWN='Down', BUSY='Busy')
def __init__(self,name,servers,cfgCur,cfgOpts,cfgFile):
self._name = name
self._displayName = name
self._servers = servers
self._audioCodecs = cfgOpts[0]
self._audioRates = cfgOpts[1]
self._videoCodecs = cfgOpts[2]
self._videoRates = cfgOpts[3]
self._videoSizes = cfgOpts[4]
self._streamEncryptions = cfgOpts[5]
self._addresses = {}
self._cfgFile = cfgFile
# Other
self._state = {server : Stream.STATE.DOWN for server in servers}
self._lock = threading.Lock()
def __eq__(self,other):
if other == None:
return False
return cmp(self,other)
def __cmp__(self,other):
return cmp(self.name, other.name)
def __str__(self):
retStr = 'Stream: '+ self.name + ' Type: ' +\
self.type + '\nServers:\n'
for svr in self.servers:
retStr += '\t'+str(svr)+'\t Stream-State: '+self.state[svr]+'\n'
retStr += 'Config: \n'
retStr += 'AudioCodec: '+ self.curAudioCodec + '\n'
retStr += 'AudioRate: '+ self.curAudioRate + ' kbit/s\n'
retStr += 'VideoCodec: '+ self.curVideoCodec + '\n'
retStr += 'VideoRate: '+ self.curVideoRate + ' kbit/s\n'
retStr += 'VideoSize: '+ self.curVideoSize + '%\n'
retStr += 'StreamEncryption: '+ self.curStreamEncryption + '\n'
return retStr
@property
def type(self): return self.__class__.__name__
@property
def name(self): return self._name
@property
def displayName(self): return self._displayName
@displayName.setter
def displayName(self,value): self._displayName = value
@property
def servers(self): return self._servers
# Config
@property
def curAudioCodec(self): return self._curAudioCodec
@curAudioCodec.setter
def curAudioCodec(self, value): self_curAudioCodec = value
@property
def audioCodecs(self): return self._audioCodecs
@property
def curAudioRate(self): return self._curAudioRate
@curAudioRate.setter
def curAudioRate(self, value): self_curAudioRate = int(value)
@property
def audioRates(self): return self._audioRates
@property
def curVideoCodec(self): return self._curVideoCodec
@curVideoCodec.setter
def curVideoCodec(self, value): self_curVideoCodec = value
@property
def videoCodecs(self): return self._videoCodecs
@property
def curVideoRate(self): return self._curVideoRate
@curVideoRate.setter
def curVideoRate(self, value): self_curVideoRate = int(value)
@property
def videoRates(self): return self._videoRates
@property
def curVideoSize(self): return self._curVideoSize
@curVideoSize.setter
def curVideoSize(self, value): self_curVideoSize = int(value)
@property
def videoSizes(self): return self._videoSizes
@property
def curStreamEncryption(self): return self._curStreamEncryption
@curStreamEncryption.setter
def curStreamEncryption(self, value): self_curStreamEncryption = value
@property
def streamEncryptions(self): return self._streamEncryptions
@property
def dataRate(self): return (int(self.curVideoRate) +\
int(self.curAudioRate) )*110/100
@property
def addresses(self): return self._addresses
@property
def cfgFile(self): return self._cfgFile
@property
def state(self): return self._state
@property
def lock(self): return self._lock
def setStreamState(self,server,state):
self.state[server] = state
if (state == Stream.STATE.DOWN and
server in self.addresses):
del self.addresses[server]
def getStreamState(self,server):
if (not server in self.state):
self.state[server] = Stream.STATE.DOWN
return self.state[server]
def setStreamAddress(self,server,address):
self.addresses[server] = address
def getStreamAddress(self,server):
self.lock.acquire()
address = ''
if (server in self.addresses):
address = self.addresses[server]
self.lock.release()
return address
@abc.abstractmethod
def applyConfig(self,cfg):
# The generic stream configuration
self.lock.acquire()
if (cfg[Stream.STREAM_CFG_CUR[0]][0] in self.audioCodecs):
self._curAudioCodec = cfg[Stream.STREAM_CFG_CUR[0]][0]
if (cfg[Stream.STREAM_CFG_CUR[1]][0] in self.audioRates):
self._curAudioRate = cfg[Stream.STREAM_CFG_CUR[1]][0]
if (cfg[Stream.STREAM_CFG_CUR[2]][0] in self.videoCodecs):
self._curVideoCodec = cfg[Stream.STREAM_CFG_CUR[2]][0]
if (cfg[Stream.STREAM_CFG_CUR[3]][0] in self.videoRates):
self._curVideoRate = cfg[Stream.STREAM_CFG_CUR[3]][0]
if (cfg[Stream.STREAM_CFG_CUR[4]][0] in self.videoSizes):
self._curVideoSize = cfg[Stream.STREAM_CFG_CUR[4]][0]
if (cfg[Stream.STREAM_CFG_CUR[5]][0] in self.streamEncryptions):
self._curStreamEncryption = cfg[Stream.STREAM_CFG_CUR[5]][0]
self.lock.release()
# Apply stream state
streamCfg = self.getCfg()
for server in self.servers:
if server.name in cfg:
state = cfg[server.name][0]
self.lock.acquire()
if (not self.getStreamState(server) == state):
self.setStreamState(server,state)
if (state == Stream.STATE.UP):
server.startStream(streamCfg)
else:
server.stopStream(streamCfg)
self.lock.release()
@abc.abstractmethod
def getCfg(self):
self.lock.acquire()
cfg = { Stream.STREAM_NAME : self.name,
Stream.STREAM_CLASS : self.type,
Stream.STREAM_CFG_CUR[0] : self.curAudioCodec,
Stream.STREAM_CFG_CUR[1] : self.curAudioRate,
Stream.STREAM_CFG_CUR[2] : self.curVideoCodec,
Stream.STREAM_CFG_CUR[3] : self.curVideoRate,
Stream.STREAM_CFG_CUR[4] : self.curVideoSize,
Stream.STREAM_CFG_CUR[5] : self.curStreamEncryption }
self.lock.release()
return cfg
<file_sep>#!/usr/bin/python
from Config import Config
from ConfigDAO import ConfigDAO
class MockConfigDAO(ConfigDAO):
""" This is a mock implementation of the ConfigDAO abstract class """
def loadConfig(self):
cfg = Config()
cfg.audioCodecs = ['MP3','WAV','OGG']
cfg.curAudioCodec = 'WAV'
cfg.audioRates = [56,96,128,196,256,312]
cfg.curAudioRate = 128
cfg.videoCodecs = ['MPEG-I', 'MPEG-II', 'DIVx', 'XVid', 'MP4', 'VOB']
cfg.curVideoCodec = 'MP4'
cfg.videoRates = [576,648,720,850,1024]
cfg.curVideoRate = 648
cfg.videoSizes = [33,50,66,75,100]
cfg.curVideoSize = 66
cfg.streamEncryptions = ['None', 'AES', 'Blowfish', 'CSMA']
cfg.curStreamEncryption = 'AES'
cfg.curEncryptionKey = ''
return cfg
def saveConfig(self, cfg):
print('New config')
print(cfg)
return True
<file_sep>#!/usr/bin/python
from util.util import *
import abc
class StreamDAO(object):
""" This is an abstract class for a stream factory """
__metaclass__ = abc.ABCMeta
def __init__(self,svrMgr):
self._svrMgr = svrMgr
@abc.abstractmethod
def getStreams(self):
pass
def getStreamClass(self,name):
return getClass(name)
def getServers(self,servers):
return [self._svrMgr.getServer(svr) for svr in servers]
<file_sep>import os
import signal
import subprocess
import time
class SysProcess(object):
MAX_NUM_KILL_TRIES = 3
def __init__(self):
self.p = None
@property
def pid(self):
if (self.p == None):
return 0
return self.p.pid
def execute(self,cmd):
if (self.p != None):
print('Cannot make multiple calls from SysProcess object')
return False
print('Starting '+str(cmd))
self.p = subprocess.Popen(cmd, shell=False,
preexec_fn=os.setsid)
return True
def isAlive(self):
if (self.p == None):
return False
return self.p.poll() == None
@staticmethod
def findAllPids(progName):
pids = subprocess.Popen(["pidof", progName], stdout=subprocess.PIPE).communicate()[0]
return [int(pid) for pid in pids.split()]
@staticmethod
def killAll(pids):
for pid in pids:
SysProcess.killGroup(pid)
@staticmethod
def killGroup(pid):
print("Killing process group with pid: "+str(pid))
os.kill(pid, signal.SIGKILL)
os.killpg(pid, signal.SIGKILL)
def kill(self):
if (self.p == None):
return True
SysProcess.killGroup(self.p.pid)
tries = SysProcess.MAX_NUM_KILL_TRIES
while (self.isAlive() and tries>1):
SysProcess.killGroup(self.p.pid)
time.sleep(1)
tries -= 1
return not self.isAlive()
<file_sep>from SysProcess import SysProcess
from channels import channels
from stream.Stream import Stream
from stream.DVBSStream import DVBSStream
class LinuxCommands(object):
def __init__(self):
# Shut any vlc instances
pids = SysProcess.findAllPids("vlc")
SysProcess.killAll(pids)
def shutdown(self):
p = SysProcess()
return p.execute(['shutdown','-h','1'])
def getTtlUploadRate(self,devices):
curTtlUploadBits = 0
for dev in devices:
txBitFile = open('/sys/class/net/'+dev+'/statistics/tx_bytes','r')
curTtlUploadBits += int(txBitFile.read())*8 # bytes to bits
txBitFile.close()
return curTtlUploadBits
def streamName(self,cfg):
return cfg[Stream.STREAM_NAME]
def startStream(self,cfg):
name = self.streamName(cfg)
streamClass = cfg[Stream.STREAM_CLASS]
audioCodec = cfg[Stream.STREAM_CFG_CUR[0]]
audioRate = cfg[Stream.STREAM_CFG_CUR[1]]
videoCodec = cfg[Stream.STREAM_CFG_CUR[2]]
videoRate = cfg[Stream.STREAM_CFG_CUR[3]]
videoSize = cfg[Stream.STREAM_CFG_CUR[4]]
streamEncryption = cfg[Stream.STREAM_CFG_CUR[5]]
vlcParams = ''
port = '0'
protocol = ''
sFile = ''
if (streamClass == 'DVBSStream'):
print('Start DVB-s stream')
channel = cfg[DVBSStream.STREAM_CFG_CUR[0]]
vlcParams += 'dvb-s://'+str(channels[channel])
port = 4000
protocol = 'http'
sFile = 'tv.mp4'
vlcParams += ' --sout=#transcode{acodec='+str(audioCodec)+',ab='+\
str(audioRate)+',channels=2,samplerate=44100,hq'
vlcParams += ',vcodec='+str(videoCodec)+',vb='+str(videoRate)+\
',fps=25,scale=0.'+str(videoSize)+'}'
vlcParams += ':std{access='+str(protocol)+',mux=ts,dst=0.0.0.0:'+\
str(port)+'/'+sFile+'}'
p = SysProcess()
p.execute(str("cvlc "+vlcParams).split())
return(name,p,protocol,port,sFile)
<file_sep>#!/usr/bin/python
class ServerManager(object):
""" This class manages the server infrastructure """
SERVER = "server"
STATE = "state"
def __init__(self,serverDAO):
""" Load all servers and create maps that
facilitate later request handling """
self.__servers = {server.name : server for
server in serverDAO.getServers()}
uplinkServerTpls = [(server.uplink, server) for
server in self.__servers.values()]
self.__serversByUplink = {}
for key, val in uplinkServerTpls:
self.__serversByUplink.setdefault(key, []).append(val)
@property
def infrastructure(self):
""" Get up-to-date information about all servers """
return self.__serversByUplink
def getServer(self,name):
""" Get server object by name """
if name in self.__servers:
return self.__servers[name]
return None
def changeServerState(self,name,state):
""" Start/Stop servers """
server = self.getServer(name)
if server == None:
return
server.changeState(state)
def getServerUploadCapacity(self,name,update=False):
""" Check the remaining upload capacity of a given server """
server = self.getServer(name)
if server == None:
return 0
ttlUplinkUpload = 0
for uplink in self.__serversByUplink:
if (uplink == server.uplink):
ttlUplinkUpload += server.curUpload
return server.uploadMax - ttlUplinkUpload
<file_sep>#!/usr/bin/python
from Server import Server
import xml.etree.ElementTree as ET
from ServerDAO import ServerDAO
class XMLServerDAO(ServerDAO):
""" This is an server factory that gets its data from XML files """
def __init__(self,folder):
self.serverXML = folder+'/server.xml'
self.uplinkXML = folder+'/uplink.xml'
# Constants
SERVER = "server"
UPLINK = "uplink"
def getServers(self):
xmlSvrRoot = ET.parse(self.serverXML).getroot()
xmlUplRoot = ET.parse(self.uplinkXML).getroot()
servers = []
for svr in xmlSvrRoot.iter(XMLServerDAO.SERVER):
# Let's dynamically load the class definition
svrClassName = svr.find(Server.SERVER_CLASS).text
svrClass = self.getServerClass(svrClassName)
# Retrieve the server information
args = []
for attr in Server.SERVER_ARGS:
args.append(svr.find(attr).text)
# Retrieve the uplink information
uplink = svr.find(Server.SERVER_UPLINK).text
for upl in xmlUplRoot.iter(Server.SERVER_UPLINK):
if (upl.find(Server.SERVER_UPLINK_NAME).text == uplink):
for attr in Server.UPLINK_ARGS:
args.append(upl.find(attr).text)
break
# Retrieve extra information related to the server class type
for attr in svrClass.SERVER_ARGS:
args.append(svr.find(attr).text)
# Add the server to the list of servers
servers.append(svrClass(*args))
return servers
<file_sep>{% extends "main.html" %}
{% block content %}
<h2>Welcome to TVOnline!</h2>
<p>On this website you can watch live TV streamed from a desktop computer.
This is ideal if you want to share your local satellite signal with a
group of friends, who live abroad or in order to get access to your TV
when you are abroad.</p>
<p>The site offers username/password authentication and further allows
selected users to configure the quality of the stream. At the moment we
assume that there is only one TV card available, so program changes will
affect all the users that are watching TV on the website. This is, however,
deliberate as we do expect more than 1-2 people using this website to watch
TV on demand.</p>
<p>As for the setup we recommend to run this website on a Raspberry Pi which
will use Wake-On-LAN (WOL) to wake up a desktop computer whenever video
transcoding is required.</p>
{% end %}
<file_sep>#!/usr/bin/python
import subprocess
from BaseServer import BaseServer
class WOLServer(BaseServer):
""" This class represents a stream server that supports Wake-On-LAN.
Make sure etherwake can be run by the server process. e.g. by
executing `sudo chmod u+s /usr/sbin/etherwake` """
# WOLServer specific constructor arguments
SERVER_ARGS = ['wolAddr','wolMACAddr']
def __init__(self,name,address,maxStreams,uplink,tvOnlinePort,
tvOnlineSecret,maxUpload,wolAddr,wolMACAddr):
self._wolAddr = wolAddr
self._wolMACAddr = wolMACAddr
super(WOLServer,self).__init__(name,address,maxStreams,uplink,
tvOnlinePort,tvOnlineSecret,maxUpload)
def startServer(self):
subprocess.call(['etherwake', self._wolMACAddr],
stdout=subprocess.PIPE)
| 95bd06c260ba09d7e53069552adc347d9f70c8a6 | [
"HTML",
"Markdown",
"JavaScript",
"Python",
"Shell"
] | 33 | Python | machr666/tvonline | b002bcec6f08de1172c7d247a23e2a7d78827d4b | 6103917c253ec946c46081832cf4471af0266c7f |
refs/heads/master | <repo_name>iketari/preoccupyjs<file_sep>/README.md
# PreoccupyJS
<p align="center">
<img src="https://github.com/iketari/preoccupyjs/raw/master/test-spa/src/assets/occupy_logo.png" alt="PrepoccupyJS's custom image"/>
</p>
[](https://github.com/prettier/prettier)
[](https://travis-ci.org/iketari/preoccupyjs)
[](https://coveralls.io/github/iketari/preoccupyjs)
[](https://david-dm.org/iketari/preoccupyjs?type=dev)
An emulator of user behavioural actions for SPAs. Could be used as a part of Remote Control functionality.
### Demo
1. Open https://artsiom.mezin.eu/preoccupyjs/demo.
2. Click **Activate remote control**.
3. Click **Control** to open a new tab, it's going to open a new tab.
4. In the new tab click **Connect**. You will see a system dialog to choose the window to broadcast the screen media. Please, select the third tab with the title "Chrome Tab". From the options list select the tab with the title "PreoccupyJS. Test Application".
5. Enjoy!
### Docs
https://artsiom.mezin.eu/preoccupyjs/docs
### Architecture
The main idea of the PreoccupyJS package is to emulate users actions within a remote-controlled SPA and to change the SPA's DOM accordingly.
Under the hood PreoccupyJS consists of the next main parts:
1. [Host](http://artsiom.mezin.eu/preoccupyjs/docs/classes/host.html) - A controller for the host tab (machine), it's responsible for the collecting of Actions (user events) and transmitting it to the client tab using Transport.
2. [Client](http://artsiom.mezin.eu/preoccupyjs/docs/classes/client.html) - A controller for the client tab (machine), it's responsible for the Actions interpreting and performing on the client page.
3. [Actions](http://artsiom.mezin.eu/preoccupyjs/docs/classes/baseaction.html) - A quantum of information which is collected from the Host side. It describes a single user action (like click, mousemove, scroll, etc...). Each action is transmitted to the Client tab (machine) by the Transport and performed over there by the Client.
4. [Transport](http://artsiom.mezin.eu/preoccupyjs/docs/interfaces/abstracttransport.html) - An abstract class. A Transport implementation allows Actions to be transmitted from the host tab to the client one.
**PreoccupyJS doesn't provide any functionality to grab, broadcast, or present Screen Media streams. You have to take care about this part of fuctionality separetly.**
### Basic Usage
Install from NPM
```bash
npm install --save-dev preoccupyjs
```
On the Host side:
1. Import the Host and required Transport constructors
```javascript
import { Host, RxjsTransport } from 'preoccupyjs';
```
2. Preapre a focusable DOM element, which is going to play a role of "touch screen" for the remote controller.
```javascript
const hostEl = document.createElement('div'); // fill free to style and modify this element as you wish, but don't delete it!
hostEl.tabIndex = 0; // make it focusable
```
3. Set up the transport
```javascript
const transport = new RxjsTransport(options as {
subject: Subject<object>; // an AnonymousSubject, e.g. WebSocketSubject
wrapFn?: (data: Message) => object; // wraps a preoccupyJS message to make it fits for your Subject type
});
```
4. Set up and run the host
```javascript
const host = new Host(transport, hostEl);
host.start(); // run the communication whenever your app is ready!
```
On the client side:
1. Import the Client, DomController, and required Transport constructors
```javascript
import { Host, RxjsTransport } from 'preoccupyjs';
```
2. Set up the transport
```javascript
const transport = new RxjsTransport(options as {
subject: Subject<object>; // an AnonymousSubject, e.g. WebSocketSubject
filterFn?: (rawMsg: object) => boolean; // filter all messages in subject to avoid non-preoccupyjs related
});
```
3. Set up and run the client
```javascript
const client = new Client(transport, new DomController(document.body)); // you can specify the controlled scope of the page by passing any other DOM element
client.start(); // run the communication whenever your app is ready!
```
### Features
- Preoccupyjs has a modular structure. You can reuse existing Actions or replace/extend it by your own.
- Preoccupyjs is totally transport agnostic. It's up to you how to transmit the actions between host and client browser tab.
### Importing library
You can import the generated bundle to use the whole library generated by this starter:
```javascript
import { createHost, createClient } from 'preoccupyjs';
```
Additionally, you can import the transpiled modules (transports, actions) from `dist/lib`:
```javascript
import { DblClickToAction } from 'preoccupyjs/lib/actions/DblClickToAction';
```
### NPM scripts
- `npm t`: Run test suite
- `npm start`: Run `npm run build` in watch mode
- `npm run test:watch`: Run test suite in [interactive watch mode](http://facebook.github.io/jest/docs/cli.html#watch)
- `npm run test:prod`: Run linting and generate coverage
- `npm run build`: Generate bundles and typings, create docs
- `npm run lint`: Lints code
- `npm run commit`: Commit using conventional commit style ([husky](https://github.com/typicode/husky) will tell you to use it if you haven't :wink:)
### Excluding peerDependencies
On library development, one might want to set some peer dependencies, and thus remove those from the final bundle. You can see in [Rollup docs](https://rollupjs.org/#peer-dependencies) how to do that.
Good news: the setup is here for you, you must only include the dependency name in `external` property within `rollup.config.js`. For example, if you want to exclude `lodash`, just write there `external: ['lodash']`.
### Automatic releases
_**Prerequisites**: you need to create/login accounts and add your project to:_
- [npm](https://www.npmjs.com/)
- [Travis CI](https://travis-ci.org)
- [Coveralls](https://coveralls.io)
_**Prerequisite for Windows**: Semantic-release uses
**[node-gyp](https://github.com/nodejs/node-gyp)** so you will need to
install
[Microsoft's windows-build-tools](https://github.com/felixrieseberg/windows-build-tools)
using this command:_
```bash
npm install --global --production windows-build-tools
```
#### Setup steps
Follow the console instructions to install semantic release and run it (answer NO to "Do you want a `.travis.yml` file with semantic-release setup?").
_Note: make sure you've setup `repository.url` in your `package.json` file_
```bash
npm install -g semantic-release-cli
semantic-release-cli setup
# IMPORTANT!! Answer NO to "Do you want a `.travis.yml` file with semantic-release setup?" question. It is already prepared for you :P
```
From now on, you'll need to use `npm run commit`, which is a convenient way to create conventional commits.
Automatic releases are possible thanks to [semantic release](https://github.com/semantic-release/semantic-release), which publishes your code automatically on [github](https://github.com/) and [npm](https://www.npmjs.com/), plus generates automatically a changelog. This setup is highly influenced by [Kent C. Dodds course on egghead.io](https://egghead.io/courses/how-to-write-an-open-source-javascript-library)
### Git Hooks
There is already set a `precommit` hook for formatting your code with Prettier :nail_care:
By default, there are two disabled git hooks. They're set up when you run the `npm run semantic-release-prepare` script. They make sure:
- You follow a [conventional commit message](https://github.com/conventional-changelog/conventional-changelog)
- Your build is not going to fail in [Travis](https://travis-ci.org) (or your CI server), since it's runned locally before `git push`
This makes more sense in combination with [automatic releases](#automatic-releases)
### FAQ
#### `Array.prototype.from`, `Promise`, `Map`... is undefined?
TypeScript or Babel only provides down-emits on syntactical features (`class`, `let`, `async/await`...), but not on functional features (`Array.prototype.find`, `Set`, `Promise`...), . For that, you need Polyfills, such as [`core-js`](https://github.com/zloirock/core-js) or [`babel-polyfill`](https://babeljs.io/docs/usage/polyfill/) (which extends `core-js`).
For a library, `core-js` plays very nicely, since you can import just the polyfills you need:
```javascript
import "core-js/fn/array/find"
import "core-js/fn/string/includes"
import "core-js/fn/promise"
...
```
Contributions of any kind are welcome!<file_sep>/test-spa/src/app/ace/ace.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ace',
templateUrl: './ace.component.html',
styleUrls: ['./ace.component.css']
})
export class AceComponent implements OnInit {
text: string = 'SELECT * FROM users;';
constructor() { }
ngOnInit() {
}
}
// beh-select<file_sep>/src/actions/KeypressAction.ts
import { PreoccupyAction, ActionsName, BaseAction } from './base';
import { DomController } from '../dom';
import { Host } from '../host';
export class KeypressAction extends BaseAction implements PreoccupyAction {
static type: string = ActionsName.KEYPRESS;
static eventName: string = 'keypress';
constructor(public payload: Partial<KeyboardEvent>) {
super();
this.type = KeypressAction.type;
}
performEvent(dom: DomController, stack: PreoccupyAction[]) {
dom.keypress(this.payload);
}
static handleEvent(host: Host, event: KeyboardEvent): PreoccupyAction {
return new KeypressAction({
key: event.key,
code: event.code,
keyCode: event.keyCode
});
}
}
<file_sep>/src/actions/KeydownAction.ts
import { PreoccupyAction, ActionsName, BaseAction } from './base';
import { DomController } from '../dom';
import { Host } from '../host';
import { pick } from '../utils';
export class KeydownAction extends BaseAction implements PreoccupyAction {
static type: string = ActionsName.KEYDOWN;
static eventName: string = 'keydown';
constructor(public payload: Partial<KeyboardEvent>) {
super();
this.type = KeydownAction.type;
}
performEvent(dom: DomController, stack: PreoccupyAction[]) {
dom.keydown(this.payload);
}
static handleEvent(host: Host, event: KeyboardEvent): PreoccupyAction {
const eventData = pick<KeyboardEvent>(event, [
'which',
'key',
'code',
'ctrlKey',
'keyCode',
'metaKey',
'shiftKey',
'type'
]);
return new KeydownAction(eventData);
}
}
<file_sep>/src/utils.spec.ts
import { pick, css } from './utils';
describe('Utils', () => {
describe('pick', () => {
it('should return an object', () => {
const obj = {
foo: true,
bar: true,
baz: true
};
const actualt = pick(obj, ['foo', 'baz']);
expect(actualt).toEqual({ foo: true, baz: true });
});
});
describe('css', () => {
it('should setup css props', () => {
const el = document.createElement('div');
css(el, { display: 'flex', 'font-size': '13px' });
expect(el.style).toMatchInlineSnapshot(`
CSSStyleDeclaration {
"0": "display",
"1": "font-size",
"_importants": Object {
"display": undefined,
"font-size": undefined,
},
"_length": 2,
"_onChange": [Function],
"_values": Object {
"display": "flex",
"font-size": "13px",
},
}
`);
});
});
});
<file_sep>/src/preoccupyjs.spec.ts
import { createClient, createHost } from './preoccupyjs';
import { Client } from './client';
import { Host } from './host';
describe('main', () => {
describe('createClient', () => {
it('should create a client instance', () => {
const actual = createClient(document.createElement('div'));
expect(actual).toBeInstanceOf(Client);
});
});
describe('createHost', () => {
it('should create a host instance', () => {
const actual = createHost(document.createElement('div'));
expect(actual).toBeInstanceOf(Host);
});
});
});
<file_sep>/test/preoccupyjs.test.ts
import { Host, Client } from '../src/preoccupyjs';
/**
* Dummy test
*/
describe('Dummy test', () => {
it('Client is truthy', () => {
expect(Client).toBeTruthy();
});
});
<file_sep>/src/transports/abstract.ts
import { PreoccupyAction } from './../actions/base';
export enum TransportEvents {
connect,
disconnect,
action
}
export type Listener = (event: TransportEvent) => void;
export interface TransportEvent {
type: TransportEvents;
detail: any;
}
export interface AbstractTransport {
on(type: TransportEvents, callback: Listener): void;
publish(action: PreoccupyAction): void;
handshake(): void;
disconnect(): void;
}
<file_sep>/CHANGELOG.md
# Semantic Versioning Changelog
## [1.1.11](https://github.com/iketari/preoccupyjs/compare/v1.1.10...v1.1.11) (2019-06-17)
### Bug Fixes
* **src/dom.ts:** Improve scroll action behaviour ([2192ce7](https://github.com/iketari/preoccupyjs/commit/2192ce7))
## [1.1.10](https://github.com/iketari/preoccupyjs/compare/v1.1.9...v1.1.10) (2019-06-12)
### Bug Fixes
* **dom.ts:** Fix bug with finding body element ([2bd3903](https://github.com/iketari/preoccupyjs/commit/2bd3903))
## [1.1.9](https://github.com/iketari/preoccupyjs/compare/v1.1.8...v1.1.9) (2019-06-11)
### Bug Fixes
* **src/*:** Export all neccessary classes to implement a Transport outside the library ([a1b6c35](https://github.com/iketari/preoccupyjs/commit/a1b6c35))
## [1.1.8](https://github.com/iketari/preoccupyjs/compare/v1.1.7...v1.1.8) (2019-04-16)
### Bug Fixes
* **package.json:** Rebuild ([057ba1d](https://github.com/iketari/preoccupyjs/commit/057ba1d))
* **RightClickToAction.ts:** Fix tslint ([952ab6e](https://github.com/iketari/preoccupyjs/commit/952ab6e))
* **RightClickToAction.ts:** Pass button field as a part of payload for a contextmenu event ([ca628cb](https://github.com/iketari/preoccupyjs/commit/ca628cb))
## [1.1.7](https://github.com/iketari/preoccupyjs/compare/v1.1.6...v1.1.7) (2019-02-05)
### Bug Fixes
* **transports/rxjs.ts:** Set up a universal interface to communicate with the server ([32fe7d6](https://github.com/iketari/preoccupyjs/commit/32fe7d6))
## [1.1.6](https://github.com/iketari/preoccupyjs/compare/v1.1.5...v1.1.6) (2019-01-28)
### Bug Fixes
* **package.json:** CI setting up ([cf5dd45](https://github.com/iketari/preoccupyjs/commit/cf5dd45))
<file_sep>/src/host.ts
import { actionMap } from './actions';
import { AbstractTransport, TransportEvents } from './transports';
import { PreoccupyAction } from './actions/base';
export interface Coordinates {
x: number;
y: number;
}
export class Host {
private actions: Map<string, any> = actionMap;
private eventCallbacks: WeakMap<
PreoccupyAction,
EventListenerOrEventListenerObject
> = new WeakMap();
constructor(private transport: AbstractTransport, private el: HTMLElement) {}
public start() {
this.initEvents();
this.transport.handshake();
}
public stop() {
this.transport.disconnect();
this.disableEvents();
}
private initEvents() {
this.actions.forEach(Action => {
this.eventCallbacks.set(Action, (event: Event) => {
const action = Action.handleEvent(this, event);
this.transport.publish(action);
});
this.el.addEventListener(Action.eventName, this.eventCallbacks.get(Action));
});
}
private disableEvents() {
this.actions.forEach(Action =>
this.el.removeEventListener(Action.eventName, this.eventCallbacks.get(Action))
);
}
public getRelativeCoordinate(event: MouseEvent): Coordinates {
const { offsetX, offsetY } = event;
const { clientHeight, clientWidth } = event.target as HTMLDivElement;
return {
x: offsetX / clientWidth,
y: offsetY / clientHeight
};
}
}
<file_sep>/src/actions/RightClickToAction.ts
import { PreoccupyAction, ActionsName, BaseAction } from './base';
import { DomController } from '../dom';
import { Host } from '../host';
export class RightClickToAction extends BaseAction implements PreoccupyAction {
static type: string = ActionsName.RIGHT_CLICK_TO;
static eventName: string = 'contextmenu';
constructor(
public payload: {
x: number;
y: number;
button: number;
}
) {
super();
this.type = RightClickToAction.type;
}
performEvent(dom: DomController, stack: PreoccupyAction[]) {
dom.rightClickTo(this.payload);
}
static handleEvent(host: Host, event: Event): PreoccupyAction {
let e = event as MouseEvent;
event.preventDefault();
const payload = {
...host.getRelativeCoordinate(e),
button: e.button
};
return new RightClickToAction(payload);
}
}
<file_sep>/test-spa/src/app/control/control.component.ts
import { Component, OnInit, HostListener, ViewChild, ElementRef } from '@angular/core';
import { createHost } from 'preoccupyjs';
import { fromEvent } from 'rxjs';
import { throttleTime } from 'rxjs/operators';
@Component({
selector: 'app-control',
templateUrl: './control.component.html',
styleUrls: ['./control.component.css']
})
export class ControlComponent implements OnInit {
host: any;
@ViewChild('pad') padView: ElementRef;
constructor() { }
ngOnInit() {}
public onConnectClick() {
this.host = createHost(this.padView.nativeElement);
this.host.start();
}
}
<file_sep>/src/host.spec.ts
import { Host } from './host';
import { AbstractTransport } from './transports';
import { PreoccupyAction, BaseAction } from './actions/base';
const MOCK_ACTION_TYPE = 'superevent';
describe('Host', () => {
let host: Host;
let padEl: HTMLElement;
let transportMock: AbstractTransport;
let Action: typeof BaseAction;
let performEventSpy: jest.SpyInstance;
let handshakeSpy: jest.SpyInstance;
let disconnectSpy: jest.SpyInstance;
beforeEach(() => {
padEl = document.createElement('div');
handshakeSpy = jest.fn();
disconnectSpy = jest.fn();
transportMock = {
on() {},
publish() {},
disconnect: disconnectSpy as any,
handshake: handshakeSpy as any
};
host = new Host(transportMock, padEl);
performEventSpy = jest.fn();
Action = class implements PreoccupyAction {
static type: string = MOCK_ACTION_TYPE;
public type: string = MOCK_ACTION_TYPE;
static eventName: string = MOCK_ACTION_TYPE;
constructor(public payload: object) {}
performEvent = performEventSpy as any;
static handleEvent = jest.fn();
};
((host as any).actions as Map<string, any>).set('abstract', Action);
});
afterEach(() => {
padEl.remove();
});
describe('start', () => {
it('should handshake the transport', () => {
host.start();
expect(handshakeSpy).toBeCalled();
});
it('should set up listeneres for Actions', () => {
host.start();
const event = new Event(MOCK_ACTION_TYPE);
padEl.dispatchEvent(event);
expect(Action.handleEvent).toHaveBeenCalledWith(host, event);
});
});
describe('stop', () => {
it('should disconnect the transport', () => {
host.stop();
expect(disconnectSpy).toBeCalled();
});
});
describe('getRelativeCoordinate', () => {
it('should translate coordinates', () => {
const event = new MouseEvent('mousemove');
['clientWidth', 'clientHeight'].forEach(prop => {
// DOM object modidifcation
Object.defineProperty(padEl, prop, {
get() {
return 100;
}
});
});
['offsetX', 'offsetY'].forEach(prop => {
// Event object modificatiob
Object.defineProperty(event, prop, {
get() {
return 4200;
}
});
});
padEl.dispatchEvent(event);
const actual = host.getRelativeCoordinate(event);
expect(actual).toMatchInlineSnapshot(`
Object {
"x": 42,
"y": 42,
}
`);
});
});
});
<file_sep>/test-spa/src/app/scroll/scroll.component.ts
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
const SCROLL_OFFSET = 20;
@Component({
selector: 'app-scroll',
templateUrl: './scroll.component.html',
styleUrls: ['./scroll.component.css']
})
export class ScrollComponent implements OnInit {
@ViewChild('scrollable') scrollableElRef: ElementRef = null;
dates: Date[] = [];
constructor() { }
ngOnInit() {
this.dates = this.generate(10);
}
onScroll(event: MouseEvent) {
console.log(event)
const {scrollHeight, scrollTop, clientHeight} = <HTMLDivElement>event.target;
if (clientHeight + scrollTop + SCROLL_OFFSET >= scrollHeight) {
this.dates.push(...this.generate(10));
}
}
generate(n: number) {
return Array.from(Array(n).keys()).map(i => new Date());
}
}
<file_sep>/test-spa/src/app/app.component.ts
import { Component } from '@angular/core';
import { createClient } from 'preoccupyjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'test-spa';
activated = false;
onActivate() {
const client = createClient(document.documentElement);
client.start();
this.activated = true;
}
}
<file_sep>/src/dom.spec.ts
import { DomController } from './dom';
describe('DomController', () => {
let dom: DomController;
let domEl: HTMLElement;
let elementUnderCursor: HTMLElement = null;
beforeEach(() => {
domEl = document.createElement('div');
domEl.style.position = 'relative';
dom = new DomController(domEl);
document.elementFromPoint = () => elementUnderCursor;
});
afterEach(() => {});
describe('init', () => {
it('should init cursor', () => {
(dom as any).cursor.moveTo = jest.fn();
dom.init();
expect((dom as any).cursor.moveTo).toHaveBeenCalled();
});
});
describe('destroy', () => {
it('shoud get rid of cursor element', () => {
(dom as any).cursor.destroy = jest.fn();
dom.destroy();
expect((dom as any).cursor.destroy).toHaveBeenCalled();
});
});
describe('moveCursorTo', () => {
it('shoud move the cursor', () => {
(dom as any).cursor.moveTo = jest.fn();
elementUnderCursor = document.createElement('div');
dom.moveCursorTo({ x: 100, y: 100 });
expect((dom as any).cursor.moveTo).toHaveBeenCalled();
});
it('shoud not move the cursor if there is no element under it', () => {
(dom as any).cursor.moveTo = jest.fn();
elementUnderCursor = null;
dom.moveCursorTo({ x: 100, y: 100 });
expect((dom as any).cursor.moveTo).not.toHaveBeenCalled();
});
});
describe('all public methods', () => {
it('should not throw exceptions if there is no element', () => {
elementUnderCursor = null;
Object.defineProperty(document, 'activeElement', {
get() {
return null;
}
});
dom.clickTo({ x: 0, y: 0 });
dom.mouseDownTo({ x: 0, y: 0 });
dom.mouseUpTo({ x: 0, y: 0 });
dom.rightClickTo({ x: 0, y: 0, button: 1 });
dom.dblClickTo({ x: 0, y: 0 });
dom.keydown({});
dom.keyup({});
dom.keypress({});
dom.scroll({ x: 0, y: 0, deltaX: 10, deltaY: 10 });
});
});
});
<file_sep>/src/preoccupyjs.ts
import { Client } from './client';
import { DomController } from './dom';
import { Host } from './host';
import { AbstractTransport, LocalTransport } from './transports';
import { DEBUG_FLAG } from './utils';
export * from './client';
export * from './host';
export * from './transports';
export * from './actions';
export { DEBUG_FLAG } from './utils';
const localTransport = new LocalTransport();
export function createClient(
el: HTMLElement,
transport: AbstractTransport = localTransport
): Client {
return new Client(transport, new DomController(el));
}
export function createHost(el: HTMLElement, transport: AbstractTransport = localTransport): Host {
return new Host(transport, el);
}
<file_sep>/src/client.spec.ts
import { Client } from "./client";
import { AbstractTransport } from "./transports";
import { DomController } from "./dom";
import { PreoccupyAction } from "./actions/base";
describe('Client', () => {
let client: Client;
let transportMock: AbstractTransport;
let domMock: DomController;
let Action;
let performEventSpy: jest.SpyInstance;
let handshakeSpy: jest.SpyInstance;
let disconnectSpy: jest.SpyInstance;
beforeEach(() => {
handshakeSpy = jest.fn();
disconnectSpy = jest.fn();
transportMock = {
on: () => null,
publish: () => null,
disconnect: disconnectSpy as any,
handshake: handshakeSpy as any
};
domMock = {
clickTo: jest.fn() as any,
destroy: jest.fn() as any
} as DomController;
client = new Client(transportMock, domMock);
performEventSpy = jest.fn();
Action = class implements PreoccupyAction {
constructor(payload: object) {}
performEvent = performEventSpy as any;
};
((client as any).actions as Map<string, any>).set('abstract', Action);
});
describe('start', () => {
it('should handshake the transport', () => {
client.start();
expect(handshakeSpy).toBeCalled();
});
});
describe('stop', () => {
it('should disconnect the transport', () => {
client.stop();
expect(disconnectSpy).toBeCalled();
});
it('should destroy the DOM Controller', () => {
client.stop();
expect(domMock.destroy).toBeCalled();
});
});
describe('perform', () => {
it('should call action methods', () => {
client.perform({type: 'abstract', payload: {} });
expect(performEventSpy).toBeCalled();
});
it('should not call action methods of unregistred actions', () => {
client.perform({type: 'foobarbaz', payload: {} });
expect(performEventSpy).not.toBeCalled();
});
});
});
<file_sep>/src/transports/Message.ts
export class Message {
public hash: string;
constructor(public type: string, public data: object, hash?: string) {
this.hash = hash || Math.random() * 10e6 + '';
}
public serialize(): string {
return JSON.stringify(this.data);
}
static parse(src: string): Message {
const [_prefix, type, hash, dataSrc] = src.split('|');
return new Message(type, JSON.parse(dataSrc), hash);
}
}
<file_sep>/test-spa/src/app/form/form.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
formResult: string = '';
onFormSubmit(event) {
event.preventDefault();
const formData: any = new FormData(event.target);
this.formResult = Array.from(formData.entries())
.reduce<string>((acc, pair) => acc += `name: ${pair[0]} value: ${pair[1]}\n`, '');
console.log(this.formResult, formData.entries())
}
onContextMenu(event) {
window['contextmenuField'].value = `Event.button: ${event.button}`;
event.preventDefault();
}
}
<file_sep>/src/utils.ts
export function css(el: HTMLElement, styles: { [key: string]: string }) {
for (const [prop, value] of Object.entries(styles)) {
el.style.setProperty(prop, value);
}
}
export function pick<T>(src: any, fields: string[] = []): Partial<T> {
return fields.reduce(
(result: any, field: string) => {
result[field] = src[field];
return result;
},
{} as Partial<T>
);
}
export const DEBUG_FLAG = 'preoccupydebug';
<file_sep>/src/transports/local.ts
import { PreoccupyAction } from './../actions/base';
import { AbstractTransport, TransportEvents } from './abstract';
import { EventEmitter } from './EventEmitter';
import { Message } from './Message';
export class LocalTransport extends EventEmitter implements AbstractTransport {
private connected: boolean = false;
private publishedMessages: Message[] = [];
private storage: Storage = localStorage;
constructor(private preifx: string = 'prefix', private stackSize: number = 10) {
super();
}
public handshake() {
if (this.connected) {
this.trigger(TransportEvents.connect);
} else {
this.connect();
}
}
public disconnect() {
this.cleanUp();
window.removeEventListener('storage', this);
this.off();
this.connected = false;
}
public publish(action: PreoccupyAction): void {
const message = new Message('action', action);
this.publishedMessages.push(message);
this.storage.setItem(`${this.preifx}|${message.type}|${message.hash}`, message.serialize());
if (this.publishedMessages.length > this.stackSize) {
const messageToDelete = this.publishedMessages.shift();
if (messageToDelete) {
this.storage.removeItem(`${this.preifx}|${messageToDelete.type}|${messageToDelete.hash}`);
}
}
}
public handleEvent(event: Event) {
switch (event.type) {
case 'storage':
this.onStorageMessage(event as StorageEvent);
break;
default:
break;
}
}
private connect() {
window.addEventListener('storage', this);
this.connected = true;
this.trigger(TransportEvents.connect);
}
private cleanUp() {
Object.keys(localStorage).forEach(key => {
if (key.startsWith(this.preifx)) {
localStorage.removeItem(key);
}
});
}
private onStorageMessage({ key, newValue }: StorageEvent) {
if (key && newValue && key.startsWith(this.preifx)) {
const message = Message.parse(key + '|' + newValue);
if (this.isExternalMessage(message)) {
this.trigger(TransportEvents.action, message);
}
}
}
private isExternalMessage(message: Message): boolean {
return !this.publishedMessages.find(ownMessage => ownMessage.hash === message.hash);
}
}
<file_sep>/src/actions/base.ts
import { DomController } from '../dom';
import { Host } from '../host';
export enum ActionsName {
BASE = '[Action] Base',
MOVE_TO = '[Action] Move To',
MOUSE_DOWN_TO = '[Action] MouseDown To',
MOUSE_UP_TO = '[Action] MouseUp To',
CLICK_TO = '[Action] Click To',
RIGHT_CLICK_TO = '[Action] Right Click To',
DBL_CLICK_TO = '[Action] Double Click To',
KEYPRESS = '[Action] Keypress',
KEYDOWN = '[Action] Keydown',
KEYUP = '[Action] Keyup',
SCROLL_BY = '[Action] Scroll By'
}
export interface RawPreoccupyAction {
type: string;
payload?: object;
}
export interface PreoccupyAction {
payload?: object;
performEvent(dom: DomController, stack: PreoccupyAction[]): void;
}
export abstract class BaseAction implements PreoccupyAction {
public type: string;
static type: string = ActionsName.BASE;
abstract performEvent(dom: DomController, stack: PreoccupyAction[]): void;
static handleEvent(host: Host, event: Event): PreoccupyAction {
console.warn(`You have to implement a static method handleEvent for ${this.type} action`);
return {} as PreoccupyAction;
}
constructor(public payload: object = {}) {
this.type = BaseAction.type;
}
}
<file_sep>/src/transports/index.ts
export * from './abstract';
export * from './local';
export * from './rxjs';
export * from './Message';
export * from './EventEmitter';
<file_sep>/src/transports/rxjs.ts
import { Subscription } from 'rxjs/internal/Subscription';
import { filter } from 'rxjs/operators';
import { PreoccupyAction } from '../actions/base';
import { AbstractTransport, TransportEvents } from './abstract';
import { EventEmitter } from './EventEmitter';
import { Message } from './Message';
import { Subject } from 'rxjs';
export interface RxjsTransportOptions {
subject: Subject<object>;
filterFn?: (rawMsg: object) => boolean;
wrapFn?: (data: Message) => object;
}
export class RxjsTransport extends EventEmitter implements AbstractTransport {
private subscription: Subscription = null;
private connected: boolean = false;
private subject: Subject<object>;
private filterFn: (rawMsg: object) => boolean;
private wrapFn: (message: Message) => object;
constructor(options: RxjsTransportOptions) {
super();
this.subject = options.subject;
this.filterFn = options.filterFn === undefined ? rawData => Boolean(rawData) : options.filterFn;
this.wrapFn =
options.wrapFn === undefined ? message => ({ data: message.serialize() }) : options.wrapFn;
}
public disconnect() {
this.off();
this.subscription && this.subscription.unsubscribe();
this.connected = false;
}
public publish(action: PreoccupyAction): void {
const message = new Message('action', action);
this.subject.next(this.wrapFn(message));
}
public handshake() {
if (this.connected) {
this.trigger(TransportEvents.connect);
} else {
this.connect();
}
}
public connect() {
this.subscription = this.subject
.pipe(filter(rawData => this.filterFn(rawData)))
.subscribe((data: any) => {
const message = Message.parse('|||' + data.data);
this.trigger(TransportEvents.action, message);
});
this.trigger(TransportEvents.connect, null);
}
}
<file_sep>/src/dom.ts
import { Coordinates } from './host';
import { Cursor } from './cursor';
import { DEBUG_FLAG } from './utils';
const CURSOR = 1;
export class DomController {
private cursor: Cursor = new Cursor();
constructor(private el: Element) {}
public init() {
this.cursor.moveTo({ x: 0, y: 0 });
const bodyEl = document.body;
if (getComputedStyle(this.el).position !== 'static') {
this.el.appendChild(this.cursor.getEl());
} else {
bodyEl.appendChild(this.cursor.getEl());
}
}
public destroy() {
this.cursor.destroy();
}
public moveCursorTo(coordinates: Coordinates) {
const absCoordinates = this.getAbsoluteCoordinates(coordinates);
const payload = this.getMouseEventPayload(coordinates);
if (payload === null) {
return;
}
this.fireEvent('mousemove', ...payload);
this.cursor.moveTo(absCoordinates);
}
public mouseDownTo(coordinates: Coordinates) {
const payload = this.getMouseEventPayload(coordinates);
if (payload === null) {
return;
}
this.fireEvent('mousedown', ...payload);
}
public mouseUpTo(coordinates: Coordinates) {
const payload = this.getMouseEventPayload(coordinates);
if (payload === null) {
return;
}
this.fireEvent('mouseup', ...payload);
}
public clickTo(coordinates: Coordinates) {
const payload = this.getMouseEventPayload(coordinates);
if (payload === null) {
return;
}
const [el, options] = payload;
if (document.activeElement !== null) {
this.fireEvent('blur', document.activeElement as HTMLElement);
}
this.setFocus(el);
this.fireEvent('focus', el);
this.fireEvent('click', el, options);
}
public rightClickTo(event: Partial<MouseEvent>) {
const { x, y, button } = event;
const payload = this.getMouseEventPayload({ x, y });
if (payload === null) {
return;
}
let [el, options] = payload;
options = {
...options,
button
};
this.fireEvent('contextmenu', el, options);
}
public dblClickTo(coordinates: Coordinates) {
const el = this.getElementFromPoint(this.getAbsoluteCoordinates(coordinates)) as HTMLElement;
if (!el) {
return;
}
switch (el.tagName.toLowerCase()) {
case 'textarea':
case 'input':
(el as HTMLInputElement).select();
break;
default:
break;
}
this.fireEvent('dblclick', el);
}
public keydown(payload: Partial<KeyboardEvent>): any {
const el = document.activeElement;
if (!el) {
return;
}
if (payload.code === 'Backspace') {
switch (el.tagName.toLowerCase()) {
case 'textarea':
case 'input':
const inputEl = el as HTMLInputElement;
if (['checkbox', 'radio'].includes(inputEl.type) || !inputEl.value) {
break;
}
inputEl.value = (el as HTMLTextAreaElement).value.slice(0, -1);
break;
default:
if ((el as HTMLElement).isContentEditable) {
el.innerHTML = el.innerHTML.slice(0, -1);
}
break;
}
}
this.fireEvent('keydown', el as HTMLElement, payload);
}
public keyup(payload: object): any {
const el = document.activeElement;
if (!el) {
return;
}
this.fireEvent('keyup', el as HTMLElement, payload);
}
public keypress(event: Partial<KeyboardEvent>) {
const el = document.activeElement as HTMLElement;
if (!el || event.keyCode === undefined) {
return;
}
this.fireEvent('keypress', el, event);
switch (el.tagName.toLowerCase()) {
case 'textarea':
case 'input':
(el as HTMLTextAreaElement).value += String.fromCharCode(event.keyCode);
break;
default:
el.innerHTML += String.fromCharCode(event.keyCode);
break;
}
this.fireEvent('input', el, event);
}
public scroll({
x,
y,
deltaX,
deltaY
}: {
x: number;
y: number;
deltaX: number;
deltaY: number;
}) {
let initialEl = this.getElementFromPoint(this.getAbsoluteCoordinates({ x, y })) as HTMLElement;
let scrollableEl: HTMLElement | undefined;
let el = initialEl;
let isVerticalScrollAction = deltaY !== 0;
if (!el) {
return;
}
while (el && el.parentElement) {
if (isVerticalScrollAction && this.isScrollableY(el)) {
scrollableEl = el;
break;
}
if (!isVerticalScrollAction && this.isScrollableX(el)) {
scrollableEl = el;
break;
}
el = el.parentElement;
}
if (!scrollableEl) {
scrollableEl = this.getScrollingElement();
}
if (isVerticalScrollAction) {
scrollableEl.scrollBy({ top: deltaY });
} else {
scrollableEl.scrollBy({ top: deltaX });
}
this.fireEvent('wheel', el);
this.fireEvent('scroll', el);
}
private getMouseEventPayload(
coordinates: Coordinates
): [HTMLElement, Partial<MouseEvent>] | null {
const absCoordinates = this.getAbsoluteCoordinates(coordinates);
const el = this.getElementFromPoint(absCoordinates) as HTMLElement;
if (!el) {
return null;
}
const options = {
clientX: absCoordinates.x,
clientY: absCoordinates.y,
view: window
};
return [el, options];
}
private getAbsoluteCoordinates({ x, y }: Coordinates): Coordinates {
const { innerHeight, innerWidth } = window;
return {
x: x * innerWidth,
y: y * innerHeight
};
}
private getElementFromPoint({ x, y }: Coordinates) {
return document.elementFromPoint(x - CURSOR, y - CURSOR);
}
private setFocus(el: HTMLElement) {
if (el.focus) {
el.focus();
}
}
private fireEvent(type: string, el: HTMLElement, options: object = {}): boolean {
let event: Event;
const defaultOptions = {
bubbles: true,
cancelable: true
};
switch (type) {
case 'click':
case 'dblclick':
case 'mousedown':
case 'mouseup':
case 'contextmenu':
case 'mousemove':
event = new MouseEvent(type, {
...defaultOptions,
...options
});
break;
case 'keypress':
case 'keydown':
case 'keyup':
event = new KeyboardEvent(type, {
...defaultOptions,
...options
});
break;
default:
event = new Event(type, {
...defaultOptions,
...options
});
break;
}
if ((window as any)[DEBUG_FLAG]) {
console.log('fired', event);
}
return el.dispatchEvent(event);
}
private isScrollable(el: HTMLElement) {
return this.isScrollableY(el) || this.isScrollableX(el);
}
private isScrollableX(el: HTMLElement) {
const style = getComputedStyle(el);
return ['auto', 'scroll'].includes(style.overflowX) && el.scrollWidth > el.clientWidth;
}
private isScrollableY(el: HTMLElement) {
const style = getComputedStyle(el);
return ['auto', 'scroll'].includes(style.overflowY) && el.scrollHeight > el.clientHeight;
}
private getScrollingElement(): HTMLElement {
return (document.scrollingElement || document.documentElement) as HTMLElement;
}
}
<file_sep>/src/cursor.ts
import { Coordinates, Host } from './host';
import { css } from './utils';
export class Cursor {
private el: HTMLElement;
constructor() {
this.el = this.createCursorEl();
}
public moveTo({ x, y }: Coordinates) {
this.el.style.transform = `translateX(${x}px) translateY(${y}px)`;
}
public getEl(): HTMLElement {
return this.el;
}
public destroy() {
this.el && this.el.remove();
}
private createCursorEl() {
const el = document.createElement('div');
css(el, {
'z-index': '100500',
position: 'fixed',
top: '0',
left: '0',
width: '30px',
height: '30px',
display: 'inline-block',
background: `url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAHPklEQVRIS61Xe0xTeRb+bmmLlecFYUEKRXkJiqIYdyGz3QZkfcRGJ0bGie4fuhsdKQurENE16ibsGONO4kaNswiaXUfJiKKxkQlhBR8JiKMxtKwVrMpj2aUpfdBLb1/ctpvf3XbSYdDBXU9y/2hz+/t+33fO+c4phe8HBUAAwB/yzHjlw3wkQCSoqKioeKVSWdja2jpE07TIYDD8GwALwPNhoH7IEAqFIlMmk1UbDAalTqfTZGdnezo7O78CoAFgAOD+0OCEMbVv3z75s2fPGm02W1Ztba3v7NmzHo1G0wbgMoBvAUwA8IaAB1NCviKpIQ8J8g55SKreGeSA8PLy8t8kJibWV1VV0RkZGbh48SIqKyvNHo+HsL4G4EVAdnKgUCaTxZnN5liBQMCt<KEY>')`
});
return el;
}
}
<file_sep>/src/transports/EventEmitter.ts
import { TransportEvents, Listener } from "./abstract";
export class EventEmitter {
listeners: { [prop: string]: Listener[] } = {};
off(type?: string) {
if (type === undefined) {
this.listeners = {};
return;
}
this.listeners[type] = [];
}
on(type: TransportEvents, callback: Listener): void {
if (!this.listeners[type]) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
}
trigger(type: TransportEvents, detail?: any) {
if (Array.isArray(this.listeners[type])) {
this.listeners[type].forEach(callback =>
callback({
type,
detail
})
);
}
}
}<file_sep>/tools/gh-pages-publish.ts
const { cd, exec, echo, touch, mkdir, cp, rm } = require('shelljs');
const { readFileSync } = require('fs');
const url = require('url');
let repoUrl;
let pkg = JSON.parse(readFileSync('package.json') as any);
if (typeof pkg.repository === 'object') {
if (!pkg.repository.hasOwnProperty('url')) {
throw new Error('URL does not exist in repository section');
}
repoUrl = pkg.repository.url;
} else {
repoUrl = pkg.repository;
}
let parsedUrl = url.parse(repoUrl);
let repository = (parsedUrl.host || '') + (parsedUrl.path || '');
let ghToken = process.env.GH_TOKEN;
rm('-rf', 'temp')
mkdir('temp');
echo('Copying demo SPA...');
cp('-r', 'test-spa/dist/*', 'temp/demo');
echo('Copying docs...');
cp('-r', 'docs', 'temp');
echo('Copying coverage...');
cp('-r', 'coverage', 'temp');
cd('temp');
echo('Initiasing git repo...');
exec('git init');
exec('git add .');
exec('git config user.name "<NAME>"');
exec('git config user.email "<EMAIL>"');
exec('git commit -m "docs(docs): update gh-pages"');
echo('Deploying...');
exec(`git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages`);
echo('All deployed!');
<file_sep>/src/actions/index.ts
import { MoveToAction } from './MoveToAction';
import { ClickToAction } from './ClickToAction';
import { KeypressAction } from './KeypressAction';
import { ScrollByAction } from './ScrollByAction';
import { DblClickToAction } from './DblClickToAction';
import { KeydownAction } from './KeydownAction';
import { KeyupAction } from './KeyupAction';
import { RightClickToAction } from './RightClickToAction';
import { MouseDownToAction } from './MouseDownToAction';
import { MouseUpToAction } from './MouseUpToAction';
export * from './base';
export { MoveToAction } from './MoveToAction';
export { ClickToAction } from './ClickToAction';
export { KeypressAction } from './KeypressAction';
export { ScrollByAction } from './ScrollByAction';
export { DblClickToAction } from './DblClickToAction';
export { KeydownAction } from './KeydownAction';
export { KeyupAction } from './KeyupAction';
export { RightClickToAction } from './RightClickToAction';
export { MouseDownToAction } from './MouseDownToAction';
export { MouseUpToAction } from './MouseUpToAction';
export const actionMap = new Map<string, any>(
[
MoveToAction,
ClickToAction,
KeydownAction,
KeypressAction,
KeyupAction,
MoveToAction,
ScrollByAction,
DblClickToAction,
RightClickToAction,
MouseDownToAction,
MouseUpToAction
].map<[string, any]>(Action => [Action.type, Action])
);
<file_sep>/src/client.ts
import { actionMap } from './actions';
import { PreoccupyAction, RawPreoccupyAction } from './actions/base';
import { DomController } from './dom';
import { AbstractTransport, Message, TransportEvents } from './transports';
const STACK_LENGTH = 30;
export class Client {
private actionStack: PreoccupyAction[] = [];
private actions: Map<string, any> = actionMap;
constructor(private transport: AbstractTransport, private dom: DomController) {}
public perform(rawAction: RawPreoccupyAction) {
if (this.actions.has(rawAction.type)) {
const Action = this.actions.get(rawAction.type);
const action = new Action(rawAction.payload) as PreoccupyAction;
action.performEvent(this.dom, this.actionStack);
this.actionStack.push(action);
while (this.actionStack.length > STACK_LENGTH) {
this.actionStack.shift();
}
}
}
public start() {
this.transport.on(TransportEvents.connect, event => {
this.dom.init();
});
this.transport.on(TransportEvents.action, event => {
const message: Message = event.detail;
this.perform(message.data as RawPreoccupyAction);
});
this.transport.handshake();
}
public stop() {
this.transport.disconnect();
this.dom.destroy();
}
}
| 127dc24b71bbe0b50bda349d4226df2984dced2f | [
"Markdown",
"TypeScript"
] | 31 | Markdown | iketari/preoccupyjs | 41340eaffa85ecb482490bbc61af9c346adf684e | 7661870ce2ca7ff445653f02714d56ba17e98f64 |
refs/heads/main | <repo_name>arqowl/concessionariaIGTI<file_sep>/src/entidades/Pessoa.java
package entidades;
public abstract class Pessoa {
// Atributos
protected String nome;
protected String cpf;
//Construtores
//Métodos
//Getters and Setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
}
<file_sep>/README.md
# concessionariaIGTI
Esse programa em Java é responsável por criar um sistema de vendas de carros em memória de uma concessionária.
1) Ele é responsável por cadastrar um funcionário
2) Ele consegue cadastrar um carro
3) Ele consegue cadastrar um cliente
4) E, finalmente, consegue vender um carro a um cliente através de um funcionário
<file_sep>/src/entidades/Carro.java
package entidades;
public class Carro extends Veiculo{
//Atributos
//Construtores
public Carro() {
}
public Carro(String modelo, String marca, Integer ano, Double valor, Vendedor vendedorResponsavel, Cliente clienteComprador) {
this.modelo = modelo;
this.marca = marca;
this.ano = ano;
this.valor = valor;
this.vendedorResponsavel = vendedorResponsavel;
this.clienteComprador = clienteComprador;
}
//Métodos
//Getters and Setters
}
<file_sep>/src/entidades/Vendedor.java
package entidades;
public class Vendedor extends Pessoa {
//Atributos
protected Integer matricula;
//Construtores
public Vendedor() {
}
public Vendedor(String nome, String cpf, Integer matricula) {
this.nome = nome;
this.cpf = cpf;
this.matricula = matricula;
}
//Métodos
//Getters and Setters
public Integer getMatricula() {
return matricula;
}
public void setMatricula(Integer matricula) {
this.matricula = matricula;
}
}
<file_sep>/src/entidades/Veiculo.java
package entidades;
import java.util.*;
public abstract class Veiculo {
//Atributos
protected String modelo;
protected String marca;
protected Integer ano;
protected Double valor;
protected Vendedor vendedorResponsavel;
protected Cliente clienteComprador;
//Construtores
//Métodos
public void consultarVeiculo() {
}
//Getters and Setters
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public Integer getAno() {
return ano;
}
public void setAno(Integer ano) {
this.ano = ano;
}
public Double getValor() {
return valor;
}
public void setValor(Double valor) {
this.valor = valor;
}
public Vendedor getVendedorResponsavel() {
return vendedorResponsavel;
}
public void setVendedorResponsavel(Vendedor vendedorResponsavel) {
this.vendedorResponsavel = vendedorResponsavel;
}
public Cliente getClienteComprador() {
return clienteComprador;
}
public void setClienteComprador(Cliente clienteComprador) {
this.clienteComprador = clienteComprador;
}
}
| 94f5816e99530d48c41806c883b6f5661ec1ad7f | [
"Markdown",
"Java"
] | 5 | Java | arqowl/concessionariaIGTI | c51afda371a10697c8131a76c093c15b54c105a3 | cf98ce832fd6b1fe430fe3514ad778068b5e08a2 |
refs/heads/master | <file_sep>package com.learncamel.file;
import javax.xml.transform.Source;
import java.io.*;
public class CopyFilesWithoutCamel {
public static void main(String[] args) throws IOException {
File inputDirectory = new File("data/input");
File outputDirectory = new File("data/output");
File[] files = inputDirectory.listFiles();
for(File source : files) {
if(source.isFile()) {
File dest = new File(outputDirectory.getPath()+File.separator+source.getName());
OutputStream outputStream = new FileOutputStream(dest);
byte[] buffer = new byte[(int)source.length()];
FileInputStream inputStream = new FileInputStream(source);
inputStream.read(buffer);
try {
outputStream.write(buffer);
} finally {
outputStream.close();
inputStream.close();
}
}
}
}
}
<file_sep># sreeswaroop
Its my sample code base to keep my practice projects
| 293b0b0db9377bf9568a7e070ea6a80b686e3c1a | [
"Markdown",
"Java"
] | 2 | Java | sreeswaroop/sreeswaroop | 7a2c78120b4b2f39ece17ec115c16121a5267fa6 | 5623151c6fe256be05921f657320e36b5768ffcc |
refs/heads/master | <repo_name>mitchfriedman/Airship<file_sep>/src/com/mitch/flyship/Enemy/Components/MineNode.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Assets;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.flyship.objects.Enemy;
import com.mitch.flyship.objects.Ship;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.containers.Vector2d;
public class MineNode extends EnemyComponent {
private static final float LOWER_DROP_BOUNDS_PERCENT = 0.2f;
private static final float UPPER_DROP_BOUNDS_PERCENT = 0.8f;
private double xDropPos;
private boolean directionLeft = false;
private boolean hasDropped = false;
private boolean lastHasDropped = false;
private Image mine;
Vector2d minePosition;
public MineNode() {}
public MineNode(final XmlResourceParser parser) {
this();
String imageID = parser.getAttributeValue(null, "mine");
double x = Double.parseDouble(parser.getAttributeValue(null, "x"));
double y = Double.parseDouble(parser.getAttributeValue(null, "y"));
minePosition = new Vector2d(x,y);
mine = Assets.getImage(imageID);
}
@Override
public void onObjectCreationCompletion() {
super.onObjectCreationCompletion();
directionLeft = enemy.getComponent(HorizontalEnemy.class).directionLeft;
if (!directionLeft) {
minePosition = new Vector2d(enemy.getSize().x - minePosition.x - mine.getWidth(), minePosition.y);
}
float screenWidth = enemy.getLevel().getAirshipGame().getGraphics().getWidth();
float minXPos = screenWidth * LOWER_DROP_BOUNDS_PERCENT;
float maxXPos = screenWidth * UPPER_DROP_BOUNDS_PERCENT;
xDropPos = Math.random() * (maxXPos - minXPos) + minXPos;
}
@Override
public void onUpdate(final double deltaTime) {
super.onUpdate(deltaTime);
//handle updating the ship image after it has been dropped off
boolean readyToDrop = enemy.getVelocity().x < 0 && enemy.getPos().x < xDropPos ||
enemy.getVelocity().x > 0 && enemy.getPos().x > xDropPos;
lastHasDropped = hasDropped;
if(!hasDropped && readyToDrop) {
dropMine();
}
}
private void dropMine()
{
if (!hasDropped) {
hasDropped = true;
Enemy mine = new Enemy(enemy.getLevel(), "MINE");
mine.setDamage(1);
mine.setDepth(enemy.getDepth());
mine.addComponent(new StaticImage("Enemy/mine", false, false));
mine.addComponent(new ExplosionAnimation());
for (EnemyComponent comp : mine.getComponents()) {
comp.onObjectCreationCompletion();
}
mine.setPos(enemy.getPos().add(minePosition));
enemy.getLevel().getBodyManager().addBodyDuringUpdate(mine);
}
}
@Override
public void onHit(Ship ship) {
super.onHit(ship);
dropMine();
}
@Override
public void onPaint(float deltaTime) {
super.onPaint(deltaTime);
if (!lastHasDropped) {
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
g.drawImage(mine, enemy.getPos().add(minePosition));
}
}
@Override
public EnemyComponent clone() {
MineNode enemy = new MineNode();
enemy.mine = mine;
enemy.minePosition = minePosition;
return enemy;
}
}
<file_sep>/src/com/mitch/flyship/SliderMoveListener.java
package com.mitch.flyship;
public abstract class SliderMoveListener {
public void onDown() {}
public void onUp() {}
public void onPositionChanged(float position) {}
}
<file_sep>/src/com/mitch/flyship/Popup.java
package com.mitch.flyship;
import java.util.ArrayList;
import android.graphics.Rect;
import com.mitch.flyship.objects.Button;
import com.mitch.flyship.objects.Slider;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.Input;
import com.mitch.framework.containers.Align;
import com.mitch.framework.containers.Vector2d;
public class Popup {
public static Popup settings;
public float marginTop = 0;
private boolean screenLastTouched = false;
private boolean lastTouchedOutside = false;
private Vector2d position;
private AirshipGame game;
private Graphics g;
private boolean enabled;
boolean disableOnClick = true;
private double currentY = 0;
private int popupHeight = 0;
public Image topBorder, center;
//private HashMap<Image, Vector2d> images;
private ArrayList<Image> images;
private ArrayList<Vector2d> imagePositions;
private ArrayList<Button> buttons;
private ArrayList<Slider> sliders;
public Popup(AirshipGame game) {
/* At the time of writing this code, I am the only one who knows what I am doing.
* By the time I read this again, nobody will know what I have done. What was I thinking?
* Sometimes you just need to sit back and smoke a joint, let it come to you later on. */
this.game = game;
g = game.getGraphics();
topBorder = Assets.getImage("GUI/menu border");
center = Assets.getImage("GUI/menu center");
images = new ArrayList<Image>();
imagePositions = new ArrayList<Vector2d>();
buttons = new ArrayList<Button>();
sliders = new ArrayList<Slider>();
position = new Vector2d(0,0);
}
public void build()
{
popupHeight = (int) currentY;
position = new Vector2d( g.getWidth()/2 - topBorder.getWidth()/2,
g.getHeight()/2 - popupHeight / 2 + marginTop);
for (Vector2d imagePos : imagePositions) {
imagePos.y += position.y - marginTop;
}
for (Button button : buttons) {
button.setPos(button.getPos().add(new Vector2d(0, position.y - marginTop)));
}
for (Slider slider : sliders) {
slider.setPos(slider.getPos().add(new Vector2d(0, position.y - marginTop)));
}
}
public int getHeight()
{
return (int) (popupHeight + marginTop);
}
public void setDisableOnClick(boolean disable)
{
disableOnClick = disable;
}
public void update(double deltaTime) {
Input input = game.getInput();
for(Button button : buttons) {
button.onUpdate(deltaTime);
}
for(Slider slider : sliders) {
slider.onUpdate(deltaTime);
}
if (disableOnClick && !input.isTouchDown(0) && screenLastTouched && lastTouchedOutside) {
setEnabled(false);
}
if (input.isTouchDown(0)) {
screenLastTouched = true;
lastTouchedOutside = touchedOutside(input);
}
else {
screenLastTouched = false;
lastTouchedOutside = false;
}
}
private boolean touchedOutside(Input input) {
Rect bounds = getBounds();
Vector2d touch = new Vector2d(input.getTouchX(0), input.getTouchY(0));
return touch.y < bounds.top || touch.y > bounds.bottom || touch.x < bounds.left || touch.x > bounds.right;
}
public Rect getBounds() {
Rect bounds = new Rect(0,0,0,0);
bounds.top = (int)position.y;
bounds.left = (int)position.x;
bounds.right = bounds.left + topBorder.getWidth();
bounds.bottom = bounds.top + popupHeight;
return bounds;
}
public void paint(float deltaTime)
{
if(enabled) {
g.drawARGB(190, 100, 59, 15);
g.drawImage(topBorder, position);
for(int i = 0; i < popupHeight - marginTop - topBorder.getHeight(); i++) {
int yPos = (int) (position.y + topBorder.getHeight() + i);
g.drawImage(center, new Vector2d(position.x, yPos));
}
g.drawImage(topBorder, new Vector2d(position.x, position.y + popupHeight-marginTop), false, true);
for (int i = 0; i < images.size(); i++) {
Image image = images.get(i);
Vector2d pos = imagePositions.get(i);
g.drawImage(image, pos);
}
for(Button button : buttons) {
button.onPaint(deltaTime);
}
for(Slider slider : sliders) {
slider.onPaint(deltaTime);
}
}
}
public void addHeightMargin(int margin) {
currentY += margin;
}
public void addTimerImage(final double timeInSeconds, final String FONT)
{
String strMinutes = String.valueOf( (int) (timeInSeconds / 60) );
String strSeconds = String.valueOf( (int) (timeInSeconds % 60) );
if (strMinutes.length() == 1) {
strMinutes = "0" + strMinutes;
}
if (strSeconds.length() == 1) {
strSeconds = "0" + strSeconds;
}
String strTime = strMinutes + ":" + strSeconds;
final int WIDTH = Assets.getImage(FONT + "0").getWidth() * (2 + strMinutes.length()) +
Assets.getImage(FONT + ":").getWidth();
final int HEIGHT = Assets.getImage(FONT + "0").getHeight();;
final int CHARACTER_SPACING = 0;
int currentX = 0;
Vector2d timerPos = new Vector2d( g.getWidth()/2 - WIDTH/2, 0 );
for (int c = 0; c < strTime.length(); c++) {
Image charImage = Assets.getImage(FONT + strTime.charAt(c));
Vector2d charPos = timerPos.add(new Vector2d(currentX, currentY + HEIGHT/2 - charImage.getHeight()/2));
images.add(charImage);
imagePositions.add(charPos);
currentX += charImage.getWidth() + CHARACTER_SPACING;
}
currentY += HEIGHT;
}
public void addNumericImage(int value)
{
final String FONT = "FONT/TIMER/";
final int FONT_WIDTH = Assets.getImage(FONT + "0").getWidth();
final int FONT_HEIGHT = Assets.getImage(FONT + "0").getHeight();
String strValue = String.valueOf(value);
Vector2d numericImagePos = new Vector2d(g.getWidth() / 2 -
FONT_WIDTH * strValue.length() / 2, currentY);
for (int n = 0; n < strValue.length(); n++) {
images.add(Assets.getImage(FONT + strValue.charAt(n)));
imagePositions.add( numericImagePos.add( new Vector2d(FONT_WIDTH * n + n, 0) ) );
}
currentY += FONT_HEIGHT;
}
public void addImage(String name, Align.Horizontal horizontal) {
Image image = Assets.getImage(name);
Vector2d pos = new Vector2d(0, currentY);
switch(horizontal) {
case LEFT:
pos.x = g.getWidth() / 2 - center.getWidth() / 2 + topBorder.getHeight();
break;
case CENTER:
pos.x = g.getWidth() / 2 - image.getWidth() / 2;
break;
case RIGHT:
pos.x = g.getWidth() / 2 + center.getWidth() / 2 - topBorder.getHeight();
break;
}
images.add(image);
imagePositions.add(pos);
currentY += image.getHeight();
}
public void addSlider(float defaultValue, SliderMoveListener listener) {
Vector2d pos = new Vector2d(0,0);
Slider slider = new Slider(game, "GUI/Slider bar", pos, defaultValue, listener);
pos = new Vector2d(g.getWidth()/2 - slider.getWidth()/2, currentY);
slider.setPos(pos);
sliders.add(slider);
currentY += slider.getHeight();
}
public void addButton(ButtonClickListener listener, String name) {
Vector2d pos = new Vector2d(0,0);
Button button = new Button(game, name, new Align(Align.Vertical.TOP, Align.Horizontal.LEFT), pos, listener);
pos = new Vector2d((g.getWidth() - Assets.getImage(name+"-active").getWidth())/2, currentY);
button.setPos(pos);
buttons.add(button);
currentY += button.getImage().getHeight();
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean getEnabled() {
return this.enabled;
}
public boolean isEnabled() {
return enabled;
}
public static Popup buildSettingsPopup(final AirshipGame game)
{
if (settings != null) {
return settings;
}
SliderMoveListener sensitivityListener = new SliderMoveListener() {
@Override
public void onPositionChanged(float position) {
game.setSensitivity(position);
}
};
ButtonClickListener calibrateListener = new ButtonClickListener() {
@Override
public void onUp()
{
game.centerOrientation();
game.getAchievementManager().onCalibrate();
}
};
settings = new Popup(game);
settings.addHeightMargin(settings.topBorder.getHeight() + 4);
settings.addImage("GUI/tilt sensitivity", Align.Horizontal.CENTER);
settings.addHeightMargin(3);
settings.addSlider((float) game.getSensitivity(), sensitivityListener);
settings.addHeightMargin(10);
settings.addImage("GUI/tilt calibration", Align.Horizontal.CENTER);
settings.addHeightMargin(3);
settings.addButton(calibrateListener, "GUI/Calibrate");
settings.addHeightMargin(4);
settings.build();
return settings;
}
}
<file_sep>/src/com/mitch/flyship/Enemy/Components/CoinStealer.java
package com.mitch.flyship.Enemy.Components;
import java.util.ArrayList;
import java.util.List;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Assets;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.flyship.objects.Coin;
import com.mitch.flyship.objects.Ship;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.containers.Vector2d;
/**
* A blank Enemy Component.
*/
public class CoinStealer extends EnemyComponent {
private final static String FONT = "FONT/COIN/";
private final static int N_DIGITS = 3;
private final static List<Image> fontImages = new ArrayList<Image>();
private final static double ATTRACTION_RANGE = 105;
private final static double COLLECITON_RANGE = 4;
private final static double COIN_STEALING_INTERVAL = 0.1;
private double attractionSpeed = 0;
private Vector2d counterOffset = new Vector2d(0,0);
private boolean enabled = true;
private int fontWidth;
private Vector2d[] numberPositions = new Vector2d[N_DIGITS];
private Image[] numberImages = new Image[N_DIGITS];
private int nCoins = 0;
private double timeSinceLastSteal = 0;
public CoinStealer() {}
// DEBUGGING: Did you remember to clone the elements?
public CoinStealer(XmlResourceParser parser) //xml stuff here
{
this();
counterOffset.x = parser.getAttributeFloatValue(null, "offsetX", 0);
counterOffset.y = parser.getAttributeFloatValue(null, "offsetY", 0);
}
@Override
public void onComponentAdded() {
super.onComponentAdded();
if (fontImages.size() == 0) {
for (int i = 0; i < 10; i++) {
fontImages.add(Assets.getImage(FONT + i));
}
}
fontWidth = fontImages.get(0).getWidth();
for( int i = 0; i < N_DIGITS; i++ ) {
numberPositions[i] = counterOffset
.add(new Vector2d(fontWidth*i,0))
.add(new Vector2d(i*1,0));
}
attractionSpeed = enemy.getLevel().getBodyManager().getShip().coinAttractionSpeed;
}
@Override
public void onObjectCreationCompletion() {
super.onObjectCreationCompletion();
updateCoinCounter();
}
@Override
public void onHit(Ship ship) {
super.onHit(ship);
enabled = false;
}
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
updateCoinCounter();
timeSinceLastSteal += deltaTime;
if (canStealCoins() && enabled) {
stealCoin();
timeSinceLastSteal = 0;
}
if (enabled) {
attractCoins();
}
}
private boolean canStealCoins()
{
Ship ship = enemy.getLevel().getBodyManager().getShip();
Vector2d shipCenter = ship.getPos().add( ship.getSize().divide(2) );
Vector2d enemyCenter = enemy.getPos().add( enemy.getSize().divide(2) );
boolean withinRange = shipCenter.getDistance(enemyCenter) < ATTRACTION_RANGE;
boolean durationElapsed = timeSinceLastSteal > COIN_STEALING_INTERVAL;
return withinRange && durationElapsed;
}
private void stealCoin()
{
Ship ship = enemy.getLevel().getBodyManager().getShip();
ship.dropCoin(Coin.CoinType.ONE);
}
private void attractCoins()
{
List<Coin> bodies = enemy.getLevel().getBodyManager().getBodiesByClass(Coin.class);
for (Coin coin : bodies) {
Vector2d center = enemy.getPos().add( enemy.getSize().divide(2) );
double distance = coin.getPos().getDistance(center);
if ( distance < COLLECITON_RANGE ) {
nCoins += coin.value;
enemy.getLevel().getBodyManager().removeBody(coin);
}
else if (distance < ATTRACTION_RANGE) {
Vector2d direction = center.subtract(coin.getPos());
double distanceDivisor = direction.getLength() / ATTRACTION_RANGE;
double length = attractionSpeed - distanceDivisor * attractionSpeed;
Vector2d coinPos = coin.getPos().add(direction.normalize().scale(length));
coin.setPos(coinPos);
}
}
}
private void updateCoinCounter()
{
for (int i = 0; i < N_DIGITS; i++) {
int place = (int) Math.pow(10, N_DIGITS-i);
int numberAtPosition = (int) Math.floor(nCoins % place / (place / 10));
numberImages[i] = fontImages.get(numberAtPosition);
}
}
@Override
public void onPaint(float deltaTime) {
super.onPaint(deltaTime);
if (enabled) {
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
for (int i = 0; i < N_DIGITS; i++) {
g.drawImage(numberImages[i], enemy.getPos().add(numberPositions[i]));
}
}
}
@Override
public EnemyComponent clone() {
CoinStealer component = new CoinStealer();
component.counterOffset = counterOffset;
return component;
}
}
<file_sep>/src/com/mitch/flyship/Enemy/Components/HorizontalEnemy.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.framework.Graphics;
import com.mitch.framework.containers.Vector2d;
/**
* Created by KleptoKat on 7/20/2014.
*/
public class HorizontalEnemy extends EnemyComponent {
double speed;
boolean directionLeft = true;
boolean randomDirection = false;
double topOffset = 0;
boolean topOffsetIsPercent = false;
double bottomOffset = 0;
boolean bottomOffsetIsPercent = false;
public HorizontalEnemy() {}
public HorizontalEnemy(double speed, boolean directionLeft)
{
this.speed = speed;
this.directionLeft = directionLeft;
}
public HorizontalEnemy(XmlResourceParser xrp) //xml stuff here
{
speed = Double.valueOf(xrp.getAttributeValue(null, "speed"));
directionLeft = xrp.getAttributeBooleanValue(null, "directionLeft", false);
randomDirection = xrp.getAttributeBooleanValue(null, "randomDirection", false);
String sps = xrp.getAttributeValue(null, "topOffset");
if (sps != null && sps.substring(sps.length()-1).equals("%")) {
topOffsetIsPercent = true;
topOffset = Float.valueOf(sps.substring(0, sps.length()-1)) / 100f;
} else if (sps != null) {
topOffset = Float.valueOf(sps);
}
String spe = xrp.getAttributeValue(null, "bottomOffset");
if (spe != null && spe.substring(spe.length()-1).equals("%")) {
bottomOffsetIsPercent = true;
bottomOffset = Float.valueOf(spe.substring(0, spe.length()-1)) / 100f;
} else if (spe != null) {
bottomOffset = Float.valueOf(spe);
}
}
@Override
public void onComponentAdded() {
super.onComponentAdded();
directionLeft = randomDirection ? Math.floor(Math.random() * 2) == 1 : directionLeft;
speed = Math.abs(speed);
enemy.setVelocity( new Vector2d(directionLeft ? -speed : speed, 0) );
}
@Override
public void onObjectCreationCompletion() {
super.onObjectCreationCompletion();
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
double yStartOffset = topOffset * (double) (topOffsetIsPercent ? g.getHeight() : 1.0);
double yEndOffset = bottomOffset * (double) (bottomOffsetIsPercent ? g.getHeight() : 1.0);
double yStart = yStartOffset;
double yEnd = g.getHeight() + yEndOffset;
double y = Math.random() * (yEnd - yStart) + yStart;
double x = directionLeft ? g.getWidth() : -enemy.getSize().x;
enemy.setPos(new Vector2d(x, y));
if (!directionLeft && randomDirection) {
StaticImage staticImage = enemy.getComponent(StaticImage.class);
staticImage.invertHorizontal = !staticImage.invertHorizontal;
}
}
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
if ( (enemy.getPos().x > g.getWidth() && !directionLeft) ||
(enemy.getPos().x < -enemy.getSize().x && directionLeft) ) {
enemy.getLevel().getBodyManager().removeBody(enemy);
}
}
@Override
public EnemyComponent clone() {
HorizontalEnemy enemy = new HorizontalEnemy();
enemy.directionLeft = directionLeft;
enemy.randomDirection = randomDirection;
enemy.speed = speed;
enemy.topOffset = topOffset;
enemy.bottomOffset = bottomOffset;
enemy.topOffsetIsPercent = topOffsetIsPercent;
enemy.bottomOffsetIsPercent = bottomOffsetIsPercent;
return enemy;
}
}
<file_sep>/src/com/mitch/flyship/LoadAssetsTask.java
package com.mitch.flyship;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import com.mitch.framework.Audio;
import com.mitch.framework.Graphics;
import com.mitch.framework.implementation.AndroidGame;
public class LoadAssetsTask extends AsyncTask<AndroidGame, Void, Void> {
@Override
protected Void doInBackground(AndroidGame... args) {
AndroidGame game = args[0];
XmlResourceParser xrp;
//Loads assets
xrp = game.getResources().getXml(R.xml.asset_list);
Graphics g = game.getGraphics();
Audio a = game.getAudio();
Assets.loadFromXML(xrp, g, a);
xrp.close();
//Loads levels
xrp = game.getResources().getXml(R.xml.level_list);
LevelProperties.loadLevels(xrp);
xrp.close();
return null;
}
}
<file_sep>/src/com/mitch/flyship/screens/Level.java
package com.mitch.flyship.screens;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import com.mitch.flyship.AirshipGame;
import com.mitch.flyship.Assets;
import com.mitch.flyship.BodySpawner;
import com.mitch.flyship.ButtonClickListener;
import com.mitch.flyship.GameBody;
import com.mitch.flyship.LevelProperties;
import com.mitch.flyship.Player;
import com.mitch.flyship.Popup;
import com.mitch.flyship.ShipParams;
import com.mitch.flyship.Enemy.EnemyProperties;
import com.mitch.flyship.levelmanagers.LevelBodyManager;
import com.mitch.flyship.levelmanagers.LevelSpawnerManager;
import com.mitch.flyship.objects.Button;
import com.mitch.flyship.objects.Cloud;
import com.mitch.flyship.objects.Coin;
import com.mitch.flyship.objects.Enemy;
import com.mitch.flyship.objects.Ship;
import com.mitch.flyship.objects.Water;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.Music;
import com.mitch.framework.Screen;
import com.mitch.framework.containers.Align;
import com.mitch.framework.containers.Align.Horizontal;
import com.mitch.framework.containers.Vector2d;
public class Level extends Screen {
enum GameState {
OVER,
PAUSED,
RUNNING
}
public enum DeathReason {
CRASH,
LACK_OF_WATER
}
public List<EnemyProperties> getEnemyTypes()
{
return enemyTypes;
}
public LevelBodyManager getBodyManager()
{
return bm;
}
private LevelProperties properties;
private Music music;
private Image backgroundImage;
private int backgroundHeight = 0;
private double backgroundPos = 0;
private double speed = 0;
private List<Button> buttons = new ArrayList<Button>();
private List<Button> pauseButtons = new ArrayList<Button>();
private ButtonClickListener pauseListener, hangarListener,
settingsListener, resumeListener, muteListener,
leaderboardsListener, restartListener;
private LevelBodyManager bm;
private LevelSpawnerManager sm;
private GameState state = GameState.RUNNING;
private double lastUpdate = 0;
private double elapsedTime = 0;
private boolean isSpawning = true;
private double acceleration;
private double startSpeed;
private boolean includeCloudAtEnd = true;
private Popup options;
private Popup endPopup;
List<EnemyProperties> enemyTypes;
public Level(AirshipGame game)
{
this(game, new LevelProperties());
}
public Level(AirshipGame game, LevelProperties properties)
{
super(game);
this.properties = properties;
generateListeners();
generateButtons();
generate(properties);
}
private void generate(LevelProperties properties)
{
if (AirshipGame.DEBUG) {
Log.d("Level", "Generating level " + properties.getName());
}
game.getAchievementManager().resetRun();
bm = new LevelBodyManager();
sm = new LevelSpawnerManager(this, true);
this.startSpeed = properties.getStartSpeed();
this.speed = startSpeed;
this.acceleration = properties.getAcceleration();
this.enemyTypes = properties.getEnemyTemplates();
setBackgroundImage(properties.getBackground());
setMusic(properties.getMusic());
//Enemy.generateDictionary(this);
generateShip(properties.getShip());
generateSpawners(properties);
generatePauseState();
lastUpdate = System.nanoTime();
}
private void generateButtons()
{
Graphics g = game.getGraphics();
Align alignment;
Vector2d position;
alignment = new Align(Align.Vertical.TOP, Align.Horizontal.RIGHT);
position = new Vector2d(g.getWidth()-8, 8);
buttons.add(new Button(game, "GUI/Gear", alignment, position, pauseListener));
alignment = new Align(Align.Vertical.TOP, Align.Horizontal.LEFT);
position = new Vector2d(g.getWidth()-50, 8);
Button button = new Button(game, "GUI/mute", alignment, position, muteListener);
//button.setToggled(AirshipGame.muted);
pauseButtons.add(button);
}
private void generatePauseState()
{
// This whole thing could be done with an XML file but fuck you.
Graphics g = game.getGraphics();
Align alignment;
Vector2d position;
alignment = new Align(Align.Vertical.TOP, Align.Horizontal.RIGHT);
position = new Vector2d(0,0);
Button settingsButton = new Button(game, "GUI/Settings Button", alignment, position, settingsListener);
settingsButton.setPos(new Vector2d(g.getWidth(), settingsButton.getImage().getHeight()));
pauseButtons.add(settingsButton);
alignment = new Align(Align.Vertical.TOP, Align.Horizontal.RIGHT);
position = new Vector2d(g.getWidth(), settingsButton.getImage().getHeight()*2 + 15);
pauseButtons.add(new Button(game, "GUI/Hangar Button", alignment, position, hangarListener));
alignment = new Align(Align.Vertical.TOP, Align.Horizontal.RIGHT);
position = new Vector2d(g.getWidth(), settingsButton.getImage().getHeight()*3 + 30);
pauseButtons.add(new Button(game, "GUI/Resume Button", alignment, position, resumeListener));
options = Popup.buildSettingsPopup(game);
}
private void generateShip(String shipID)
{
ShipParams params = game.loadMerchantShipParams();
Player player = new Player(this);
Vector2d centerScreen = game.getGraphics().getSize().scale(0.5);
Ship ship = new Ship(this, player, params, centerScreen);
bm.setShip(ship);
}
private void generateSpawners(LevelProperties props)
{
sm.addSpawner( new BodySpawner(Coin.class, "COIN",
timeToDistance(0.275, startSpeed),
timeToDistance(1.250, startSpeed)) );
sm.addSpawner( new BodySpawner(Water.class, "WATER",
timeToDistance(35, startSpeed),
timeToDistance(40, startSpeed)) );
sm.addSpawner( new BodySpawner(Cloud.class, "CLOUD",
timeToDistance(0.250, startSpeed),
timeToDistance(2.500, startSpeed)) );
for (EnemyProperties property : enemyTypes) {
List<Integer> spawnRange = new ArrayList<Integer>();
for (int i = 0; i < 3; i++) {
spawnRange.add(timeToDistance(property.getSpawnRange().get(i), startSpeed));
}
sm.addSpawner(new BodySpawner(Enemy.class, property.getName(), spawnRange));
}
// This method IS SO COOL AND ADDICTED TO METH!!!
// because method sounds like meth head get it??
}
/**
* Calculates the distance that will be travelled
* over a certain amount of time based on level speed.
* @param time The time in milliseconds
* @return distance travelled after a certain amount of time.
*/
public static int timeToDistance(double time, double speed)
{
if (speed == 0) {
return Integer.MAX_VALUE;
}
return (int) Math.round(time * speed);
}
public static double calculateDistanceTravelled(double deltaSeconds, double speed)
{
return deltaSeconds * speed;
}
public double getElapsedTime()
{
return elapsedTime;
}
public String getLeaderboardID()
{
return properties.getLeaderboardID();
}
public double getLevelSpeed()
{
return speed;
}
public void onLevelPause()
{
}
public void onLevelResume()
{
bm.getShip().getPlayer().resetSensitivity();
}
@Override
public void dispose() { music.stop(); }
public void restart()
{
generate(properties);
}
@Override
public void pause()
{
music.pause();
if (state != GameState.OVER) {
setPaused(true);
}
}
@Override
public void resume()
{
if (AirshipGame.muted) {
music.pause();
} else {
music.play();
}
}
@Override
public void backButton()
{
// im a shit joke maker.
// What did the guy with diarrhea say to the guy without a home?
// "Hey man, at least you have a good, solid stool."
if (state == GameState.RUNNING) {
setPaused(true);
} else if (state == GameState.PAUSED && options.isEnabled()) {
options.setEnabled(false);
} else if (state == GameState.PAUSED) {
setPaused(false);
} else if (state == GameState.OVER) {
game.setScreen(new Menu(game));
}
}
private void buildEndPopup(int score, DeathReason deathReason)
{
endPopup = new Popup(game);
endPopup.addImage("END/ENDING", Horizontal.CENTER);
endPopup.marginTop = Assets.getImage("END/ENDING").getHeight() + endPopup.topBorder.getHeight();
endPopup.addHeightMargin(endPopup.topBorder.getHeight() * 2 + 2);
String deathMessageImage = "END/CRASHED";
/*switch (deathReason) {
case CRASH:
deathMessageImage = "END/CRASHED";
break;
case LACK_OF_WATER:
deathMessageImage = "END/WATER";
break;
}*/
endPopup.addImage(deathMessageImage, Horizontal.CENTER);
endPopup.addHeightMargin(5);
endPopup.addNumericImage(score);
endPopup.addHeightMargin(10);
endPopup.addButton(leaderboardsListener, "END/LEADERBOARDS");
endPopup.addHeightMargin(3);
endPopup.addButton(restartListener, "END/RETRY");
endPopup.addHeightMargin(3);
endPopup.addButton(hangarListener, "END/HANGAR");
endPopup.addHeightMargin(3);
endPopup.setDisableOnClick(false);
endPopup.build();
Graphics g = game.getGraphics();
if (includeCloudAtEnd && endPopup.getHeight() > g.getHeight()) {
includeCloudAtEnd = false;
buildEndPopup(score, deathReason);
}
}
public void setBackgroundImage(String image)
{
//Log.d("Level", image);
backgroundImage = Assets.getImage(image);
backgroundHeight = backgroundImage.getHeight();
}
public void pauseMusic()
{
if (music != null) {
music.pause();
}
}
public void restartMusic()
{
if (music != null) {
music.seekBegin();
music.play();
}
}
public void setMusic(String musicName)
{
Music newMusic = Assets.getMusic(musicName);
if (newMusic == this.music)
return;
if (this.music == null || (this.music != newMusic && !this.music.isPlaying())) {
this.music = newMusic;
this.music.setLooping(true);
this.music.seekBegin();
}
if (this.music != null && this.music.isPlaying()) {
this.music.pause();
}
if (AirshipGame.muted) {
this.music.pause();
} else if (!this.music.isPlaying()) {
this.music.play();
}
}
public void end(DeathReason deathReason)
{
buildEndPopup(bm.getShip().getPlayer().getCurrency(), deathReason);
state = GameState.OVER;
endPopup.setEnabled(true);
game.getAchievementManager().onDeath();
}
public void setPaused(boolean intentToPause)
{
boolean paused = state == GameState.PAUSED;
if (intentToPause && !paused) {
state = GameState.PAUSED;
onLevelPause();
} else if (!intentToPause && paused) {
state = GameState.RUNNING;
onLevelResume();
}
}
public void toggleLevelPauseState()
{
if (state == GameState.PAUSED) {
setPaused(false);
}
else if (state == GameState.RUNNING) {
setPaused(true);
}
}
private void updateSpawners(double deltaSeconds)
{
for (BodySpawner spawner : sm.getSpawners()) {
spawner.updateDistance(calculateDistanceTravelled(deltaSeconds, getLevelSpeed()));
if (spawner.canSpawn() && isSpawning) {
List<GameBody> bodyList = spawner.trySpawnObjects(this);
if (bodyList == null && AirshipGame.DEBUG) {
Log.d("CRITICAL SPAWNING ERROR:", "INVOKE METHOD FAILED");
}
for (GameBody body : bodyList) {
getBodyManager().addBody(body);
}
spawner.reset();
}
}
}
@Override
public void paint(float deltaTime)
{
switch(state) {
case RUNNING:
paintRunning(deltaTime);
break;
case PAUSED:
paintRunning(deltaTime);
paintPaused(deltaTime);
break;
case OVER:
paintRunning(deltaTime);
paintOver(deltaTime);
break;
}
}
private void paintOver(float deltaTime)
{
endPopup.paint(deltaTime);
}
private void paintPaused(float deltaTime)
{
for(Button button: pauseButtons) {
button.onPaint(deltaTime);
}
options.paint(deltaTime);
}
private void paintRunning(float deltaTime)
{
Graphics g = game.getGraphics();
g.drawARGB( 255, 0, 0, 0);
if (backgroundPos < g.getHeight()) {
g.drawImage(backgroundImage, 0, backgroundPos);
}
g.drawImage(backgroundImage, 0, backgroundPos-backgroundHeight);
//paints all bodies in body manager (ship, enemies, items)
bm.onPaint(deltaTime);
for(Button button: buttons) {
button.onPaint(deltaTime);
}
bm.getShip().getPlayer().onPaint(deltaTime);
}
@Override
public void update(float deltaTime)
{
// Level handles this as it needs to be precise.
// It takes too long for the time to get from AndroidFastRenderView
// to this method. This causes jerky movements and overall a crappy game.
long now = System.nanoTime();
double deltaSeconds = (now - lastUpdate)/1000000000.0;
lastUpdate = now;
switch(state) {
case RUNNING:
updateRunning((double)deltaSeconds);
break;
case PAUSED:
updatePaused((double)deltaTime);
break;
case OVER:
updateOver((double)deltaTime);
break;
}
}
public void updateOver(double deltaTime)
{
endPopup.update(deltaTime);
if (!endPopup.isEnabled()) {
state = GameState.PAUSED;
}
}
private void updatePaused(double deltaTime)
{
options.update(deltaTime);
if (!options.isEnabled()) {
for (Button button : pauseButtons) {
button.onUpdate(deltaTime);
}
for (Button button : buttons) {
button.onUpdate(deltaTime);
}
}
}
private void updateRunning(double deltaSeconds)
{
elapsedTime += deltaSeconds;
speed += acceleration * deltaSeconds / 60;
//updates all bodies in body manager (ship, enemies, items)
bm.onUpdate(deltaSeconds);
bm.offsetBodies(new Vector2d( 0, deltaSeconds * getLevelSpeed() ));
// Updates menu buttons (options gear)
for (Button button : buttons) {
button.onUpdate(deltaSeconds);
}
// Updates background position
backgroundPos += deltaSeconds * getLevelSpeed();
backgroundPos = backgroundPos > backgroundHeight ? 0 : backgroundPos;
updateSpawners(deltaSeconds);
game.getAchievementManager().setElapsedTime(elapsedTime);
game.getAchievementManager().setWaterPercent(bm.getShip().getPlayer().getWaterPercent());
}
private void generateListeners()
{
resumeListener = new ButtonClickListener() {
@Override
public void onUp() {
setPaused(false);
}
};
settingsListener = new ButtonClickListener() {
@Override
public void onUp() {
options.setEnabled(true);
}
};
pauseListener = new ButtonClickListener() {
@Override
public void onUp() {
toggleLevelPauseState();
}
};
hangarListener = new ButtonClickListener() {
@Override
public void onUp() {
if (state == GameState.OVER) {
game.setScreen(new Menu(game, null));
} else {
game.setScreen(new Menu(game, (Level)game.getCurrentScreen()));
}
}
};
muteListener = new ButtonClickListener() {
@Override
public void onUp() {
if (music.isPlaying()) {
AirshipGame.muted = true;
music.pause();
} else {
AirshipGame.muted = false;
music.play();
}
}
};
leaderboardsListener = new ButtonClickListener() {
@Override
public void onUp() {
game.loadBoard(getLeaderboardID());
}
};
restartListener = new ButtonClickListener() {
@Override
public void onUp() {
generate(properties);
state = GameState.RUNNING;
}
};
}
}
<file_sep>/src/com/mitch/flyship/screens/Loading.java
package com.mitch.flyship.screens;
import com.mitch.flyship.AirshipGame;
import com.mitch.flyship.Assets;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.Screen;
public class Loading extends Screen {
private final static double SPLASH_FADE_OUT_TIME = 1500; //180 works best
private final static double SPLASH_FADE_OUT_AT = 1800;
double elapsedTime = 0;
double opacity = 0;
Image splash;
public Loading(AirshipGame game)
{
super(game);
Graphics g = game.getGraphics();
Assets.loadImage("WIG_Splash", "WIG_splash1.png", null, g);
splash = Assets.getImage("WIG_Splash");
}
@Override
public void update(float deltaTime)
{
elapsedTime += deltaTime;
if (elapsedTime > SPLASH_FADE_OUT_AT) {
double percentage = (elapsedTime-SPLASH_FADE_OUT_AT) / SPLASH_FADE_OUT_TIME;
percentage = percentage > 1 ? 1 : percentage;
opacity = 255 * percentage;
}
if (Assets.isLoaded() && elapsedTime > SPLASH_FADE_OUT_AT + SPLASH_FADE_OUT_TIME) {
game.setScreen(new Menu(game));
//game.setScreen(new Level(game));
}
}
@Override
public void paint(float deltaTime)
{
Graphics g = game.getGraphics();
// draws image at center.
g.drawARGB( 255, 0, 0, 0);
g.drawImage(splash, g.getWidth()/2-splash.getWidth()/2, g.getHeight()/2-splash.getHeight()/2);
g.drawARGB( (int) opacity, 0, 0, 0);
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void dispose() {}
@Override
public void backButton() {}
}
<file_sep>/src/com/mitch/flyship/ShipParams.java
package com.mitch.flyship;
import java.util.ArrayList;
import java.util.List;
import com.mitch.framework.Image;
import com.mitch.framework.containers.Frame;
import com.mitch.framework.containers.Rect;
import com.mitch.framework.containers.Vector2d;
public class ShipParams {
final public Image tilt0;
final public Image tilt1;
final public Image tilt2;
final public float animation_fps;
final public Vector2d propellerPos;
final public List<Frame> animationRects;
final public int coinCollectionRange;
final public int coinAttractionRange;
final public int coinAttractionSpeed;
final public int waterCollectionRange;
final public int waterAttractionRange;
final public double waterAttractionSpeed;
final public Rect collisionOffset;
public ShipParams(String type)
{
this.tilt0 = Assets.getImage("ship/" + type + "-normal");
this.tilt1 = Assets.getImage("ship/" + type + "-tilt1");
this.tilt2 = Assets.getImage("ship/" + type + "-tilt2");
this.animation_fps = 16;
this.propellerPos = new Vector2d(9, 61);
this.animationRects = new ArrayList<Frame>();
this.animationRects.add(new Frame(Assets.getImage("ship/Interceptor-prop1"), false, false ));
this.animationRects.add(new Frame(Assets.getImage("ship/Interceptor-prop2"), false, false ));
this.animationRects.add(new Frame(Assets.getImage("ship/Interceptor-prop1"), true, false ));
this.animationRects.add(new Frame(Assets.getImage("ship/Interceptor-prop2"), true, false ));
this.coinCollectionRange = 3;
this.coinAttractionRange = 30;
this.coinAttractionSpeed = 6;
this.waterCollectionRange = 3;
this.waterAttractionRange = 15;
this.waterAttractionSpeed = 4;
// 8 from left, ten from top, 8 from right, 3 from bottom
this.collisionOffset = new Rect(8,10,-8,-3);
}
}<file_sep>/src/com/mitch/flyship/Enemy/Components/PositionLogger.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.mitch.flyship.Enemy.EnemyComponent;
/**
* A blank Enemy Component.
*/
public class PositionLogger extends EnemyComponent {
public PositionLogger() {}
// DEBUGGING: Did you remember to clone the elements?
public PositionLogger(XmlResourceParser parser) //xml stuff here
{ this(); }
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
Log.d("POSITION OF " + enemy.getName(), enemy.getPos().x + ", " + enemy.getPos().y);
}
@Override
public EnemyComponent clone() {
PositionLogger component = new PositionLogger();
return component;
}
}
<file_sep>/src/com/mitch/framework/implementation/AndroidFastRenderView.java
package com.mitch.framework.implementation;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
@SuppressLint("ViewConstructor")
public class AndroidFastRenderView extends SurfaceView implements Runnable {
public AndroidGame game;
public Bitmap framebuffer;
public Thread renderThread = null;
public SurfaceHolder holder;
volatile boolean running = false;
public static final float FPS = 35.0f;
public static final float UPS = 60.0f;
final double TIME_BETWEEN_UPDATES = 1000000000/UPS;
final double TIME_BETWEEN_RENDERS = 1000000000/FPS;
final double MAX_UPDATES_BEFORE_RENDER = 5;
public long startTime;
public long lastUpdate;
public long lastRender;
long now;
public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer) {
super(game);
this.game = game;
this.framebuffer = framebuffer;
this.holder = getHolder();
}
public void resume() {
running = true;
renderThread = new Thread(this);
renderThread.start();
}
@SuppressWarnings("unused")
public void run() {
now = System.nanoTime();
startTime = now;
lastUpdate = startTime;
lastRender = startTime;
int updateCount = 0;
int frameCount = 0;
long lastTime = now;
long time = 0;
int fps = 0;
int ups = 0;
short updates = 0;
while(running) {
if(!holder.getSurface().isValid())
continue;
now = System.nanoTime();
time += now-lastTime;
lastTime = now;
if (time > 1000000000) {
time -= 1000000000;
fps = frameCount;
ups = updateCount;
updateCount = 0;
frameCount = 0;
//Log.d("FPS:UPS", fps + ":"+ups);
}
now = System.nanoTime();
updates = 0;
while (now - lastUpdate > TIME_BETWEEN_UPDATES && updates < MAX_UPDATES_BEFORE_RENDER) {
game.getCurrentScreen().update((now - lastUpdate)/1000000);
updates++;
lastUpdate += TIME_BETWEEN_UPDATES;
updateCount++; // for FPS
}
if ( now - lastUpdate > TIME_BETWEEN_UPDATES)
{
lastUpdate = (long) (now - TIME_BETWEEN_UPDATES);
Log.d("Fast Render View", "Updating took too long. Catching up.");
}
drawGame();
lastRender = now;
frameCount++;
while (now - lastRender < TIME_BETWEEN_RENDERS && now - lastUpdate < TIME_BETWEEN_RENDERS) {
//Thread.yield();
// This stops the app from consuming lots of CPU. Might cause stuttering.
//try {Thread.sleep(1);} catch(Exception e) {}
now = System.nanoTime();
}
}
}
public void pause() {
running = false;
while(true) {
try {
renderThread.join();
break;
} catch (InterruptedException e) {
// retry
}
}
}
void drawGame()
{
game.getCurrentScreen().paint((now - lastRender)/1000000);
Canvas canvas = holder.lockCanvas();
canvas.drawBitmap(framebuffer, null, canvas.getClipBounds(), null);
holder.unlockCanvasAndPost(canvas);
}
}<file_sep>/src/com/mitch/flyship/BodySpawner.java
package com.mitch.flyship;
import java.lang.reflect.Method;
import java.util.List;
import com.mitch.flyship.screens.Level;
import com.mitch.framework.containers.MathHelper;
public class BodySpawner {
public enum Special {
NONE,
RESTART_WITH_HEIGHT
};
public String getName() {
return name;
}
public Special special = Special.NONE;
private String[] specialSpawnInfo = new String[1]; // We use an array so we can pass the value by reference
private String name;
private Method spawnObjectsMethod;
private int startDistance;
private int spawnRange_Start;
private int spawnRange_End;
private boolean spawned = false;
private double distanceSinceLastSpawn = 0;
private double randomSpawnDistance = 0;
public BodySpawner(Class<? extends GameBody> cls, String name, int spawnRange_Start, int spawnRange_End)
{
this(cls, name, 0, spawnRange_Start, spawnRange_End);
}
public BodySpawner(Class<? extends GameBody> cls, String name, List<Integer> spawnInfo)
{
this(cls, name, spawnInfo.get(0), spawnInfo.get(1), spawnInfo.get(2));
}
public BodySpawner(Class<? extends GameBody> cls, String name,
int startDistance, int spawnRange_Start, int spawnRange_End)
{
this.name = name;
this.startDistance = startDistance;
this.spawnRange_Start = spawnRange_Start;
this.spawnRange_End = spawnRange_End;
try {
// The default special for any object is Special.NONE. Objects that
// override the method getSpecial can change this. If an object is special
// we can also ask for another parameter. If that object doesn't have the
// capabilities of that special it will result in an error.
// Since an array can be passed by reference and we can still maintain
// the values, we can use it as an "out" parameter. Currently the
// capacity of this out parameter is the size of the array as
// declared above. This can be changed to whatever is desired.
Method getSpecialMethod = cls.getMethod("getSpecial", (Class[]) null);
special = (Special) getSpecialMethod.invoke(null, (Object[]) null);
if (special == Special.RESTART_WITH_HEIGHT) {
this.spawnObjectsMethod = cls.getMethod("spawnObjects", Level.class, String.class, String[].class);
} else {
this.spawnObjectsMethod = cls.getMethod("spawnObjects", Level.class, String.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateDistance(double distance)
{
distanceSinceLastSpawn += distance;
}
public boolean canSpawn()
{
return distanceSinceLastSpawn > spawnRange_Start + randomSpawnDistance +
(!spawned ? startDistance : 0);
}
@SuppressWarnings("unchecked")
public List<GameBody> trySpawnObjects(Level level)
{
if (spawnObjectsMethod == null) {
return null;
}
try {
if (special == Special.RESTART_WITH_HEIGHT) {
return (List<GameBody>) spawnObjectsMethod.invoke(null, level, name, specialSpawnInfo);
} else {
return (List<GameBody>) spawnObjectsMethod.invoke(null, level, name);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void reset() {
distanceSinceLastSpawn = 0;
randomSpawnDistance = Math.random() * (spawnRange_End - spawnRange_Start);
if (special.equals(Special.RESTART_WITH_HEIGHT) && specialSpawnInfo[0].length() > 0) {
spawned = false;
startDistance = Integer.valueOf(specialSpawnInfo[0]);
} else {
spawned = true;
}
}
/***
* Generates a random number from an array of weights. This
* function is used locally for selecting a coin configuration.
* @param weights An ArrayList of numbers. These numbers are the
* probability of its index being returned
* @return Random number in the range of 0 to weights.size()-1
* (inclusive). This number is based on the weights given. -1 on error
* @deprecated Use {@link MathHelper#generateRandomValueFromWeights(List<Float>)} instead
*/
public static int generateRandomValueFromWeights(List<Float> weights)
{
return MathHelper.generateRandomValueFromWeights(weights);
}
}
<file_sep>/src/com/mitch/flyship/ButtonClickListener.java
package com.mitch.flyship;
public abstract class ButtonClickListener {
public void onDown() {}
public void onUp() {}
public void onCancel() {}
}
<file_sep>/src/com/mitch/flyship/Enemy/Components/CrateDestroyable.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Assets;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.flyship.objects.Ship;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.containers.Vector2d;
/**
* A blank Enemy Component.
*/
public class CrateDestroyable extends EnemyComponent {
private static final double START_SPEED = 4.0;
private static final double END_SPEED = 1.5;
private static final double DURATION = 0.4;
private static final int SIZE = 12;
private static final String[] imageLocations =
{ "crate-TL", "crate-TR",
"crate-BL", "crate-BR" };
private Image[] images;
private double distance = 0;
private Vector2d[] positions = new Vector2d[4];
private boolean activated = false;
private double timeElapsed = 0.0;
public CrateDestroyable() {}
// DEBUGGING: Did you remember to clone the elements?
public CrateDestroyable(XmlResourceParser parser) //xml stuff here
{ this(); }
@Override
public void onComponentAdded() {
super.onComponentAdded();
enemy.setDestroyingOnHit(false);
}
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
if (enemy.isTouched(new Vector2d(0,0)) && !activated) {
onTouch();
}
if (activated && timeElapsed < DURATION) {
timeElapsed += deltaTime;
double speed = Math.abs((END_SPEED - START_SPEED))
* (DURATION / timeElapsed)
+ START_SPEED;
distance += speed * deltaTime;
calculateDistance();
} else if (timeElapsed >= DURATION) {
enemy.getLevel().getBodyManager().removeBody(enemy);
}
}
@Override
public void onPaint(float deltaTime) {
super.onPaint(deltaTime);
if (activated) {
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
for (int i = 0; i < 4; i++) {
g.drawImage(images[i], positions[i]);
}
}
}
@Override
public void onHit(Ship ship) {
super.onHit(ship);
activate();
}
public void onTouch()
{
activate();
}
public void activate()
{
enemy.getLevel().getAirshipGame().getAchievementManager().onCrateBreak();
if (!activated) {
images = new Image[] {
Assets.getImage(imageLocations[0]),
Assets.getImage(imageLocations[1]),
Assets.getImage(imageLocations[2]),
Assets.getImage(imageLocations[3]),
};
enemy.removeComponent(StaticImage.class);
enemy.setVelocity(new Vector2d(0,0));
calculateDistance();
activated = true;
}
}
public void calculateDistance()
{
double x,y;
x = enemy.getPos().x - distance;
y = enemy.getPos().y - distance;
positions[0] = new Vector2d(x,y);
x = enemy.getPos().x + enemy.getSize().x - SIZE + distance;
y = enemy.getPos().y - distance;
positions[1] = new Vector2d(x,y);
x = enemy.getPos().x - distance;
y = enemy.getPos().y + enemy.getSize().y - SIZE + distance;
positions[2] = new Vector2d(x,y);
x = enemy.getPos().x + enemy.getSize().x - SIZE + distance;
y = enemy.getPos().y + enemy.getSize().y - SIZE + distance;
positions[3] = new Vector2d(x,y);
}
@Override
public EnemyComponent clone() {
CrateDestroyable component = new CrateDestroyable();
return component;
}
}
<file_sep>/src/com/mitch/flyship/objects/Cloud.java
package com.mitch.flyship.objects;
import java.util.ArrayList;
import java.util.List;
import com.mitch.flyship.AirshipGame;
import com.mitch.flyship.Assets;
import com.mitch.flyship.GameBody;
import com.mitch.flyship.screens.Level;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.containers.MathHelper;
import com.mitch.framework.containers.Vector2d;
public class Cloud extends GameBody {
static final int N_CLOUDS = 8;
static final Float[] cloudWeights = new Float[] {
4f, //0
4f, //1
6f, //2
0.75f, //3
3f, //4
6f, //5
6f, //6
4f //7
};
Level level;
Image image;
int cloudType;
public Cloud(AirshipGame game, Vector2d vel, int cloudType)
{
super(game, "CLOUD");
this.cloudType = cloudType;
image = Assets.getImage("Clouds/cloud " + cloudType);
setVelocity(vel);
setSize(image.getSize());
}
public Cloud(AirshipGame game, Vector2d vel)
{
this(game, vel, (int) (Math.random() * N_CLOUDS));
}
public Cloud(Level level, Vector2d vel)
{
this(level.getAirshipGame(), vel);
this.level = level;
}
public Cloud(Level level, Vector2d vel, int cloudType)
{
this(level.getAirshipGame(), vel, cloudType);
this.level = level;
}
@Override
public void onUpdate(double deltaSeconds) {;
setPos(getPos().add(velocity.scale(deltaSeconds)));
Graphics g = game.getGraphics();
if ( (level != null) && (getPos().x > g.getWidth() || getPos().y > g.getHeight()) ) {
level.getBodyManager().removeBody(this);
}
}
@Override
public void onPaint(float deltaTime) {
Graphics g = game.getGraphics();
g.drawImage(image, getPos());
}
@Override
public void onPause() {
}
@Override
public void onResume() {
}
public static List<GameBody> spawnObjects(Level level, String type)
{
List<Float> weights = new ArrayList<Float>(N_CLOUDS);
for (int i = 0; i < cloudWeights.length; i++) {
weights.add(cloudWeights[0]);
}
int cloudType = MathHelper.generateRandomValueFromWeights(weights);
Cloud cloud = new Cloud(level, new Vector2d(0,8), cloudType);
cloud.setDepth( 149 + (int) (Math.random()*2) );
Graphics g = level.getAirshipGame().getGraphics();
Vector2d cloudSize = cloud.getSize();
cloud.setPos(new Vector2d(Math.random() * (g.getWidth()+cloudSize.x*2) - cloudSize.x, -cloudSize.y));
List<GameBody> clouds = new ArrayList<GameBody>();
clouds.add(cloud);
return clouds;
}
}
<file_sep>/src/com/mitch/flyship/objects/Slider.java
package com.mitch.flyship.objects;
import com.mitch.flyship.AirshipGame;
import com.mitch.flyship.Assets;
import com.mitch.flyship.GameBody;
import com.mitch.flyship.SliderMoveListener;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.Input;
import com.mitch.framework.containers.Rect;
import com.mitch.framework.containers.Vector2d;
public class Slider extends GameBody {
boolean lastTouchedOnScreen = false;
boolean lastTouched = false;
SliderMoveListener listener;
float sliderPosition;
int minX, maxX;
Image low, high, slider, notch;
public Slider(AirshipGame game, String name, Vector2d pos, float defaultValue, SliderMoveListener listener) {
super(game, name);
slider = Assets.getImage("GUI/Slider bar");
low = Assets.getImage("GUI/low");
high = Assets.getImage("GUI/high");
notch = Assets.getImage("GUI/Slider notch");
setPos(pos);
this.listener = listener;
sliderPosition = defaultValue;
}
@Override
protected void onSetPos() {
minX = (int) (getPos().x + 7 + low.getWidth());
maxX = (int) (minX + slider.getWidth() - notch.getWidth());
}
@Override
public void onUpdate(double deltaTime) {
//TODO: touching slider bar should put notch under finger
if (!lastTouchedOnScreen && !lastTouched && isSliderTouched()) {
lastTouched = true;
listener.onDown();
}
else if (lastTouched && game.getInput().isTouchDown(0)) {
sliderPosition = ((float) (game.getInput().getTouchX(0) - minX)) / (float)(maxX-minX);
sliderPosition = sliderPosition < 0 ? 0 : sliderPosition;
sliderPosition = sliderPosition > 1 ? 1 : sliderPosition;
listener.onPositionChanged(sliderPosition);
}
else if (lastTouched && !game.getInput().isTouchDown(0)) {
lastTouched = false;
listener.onUp();
}
if (!lastTouchedOnScreen && game.getInput().isTouchDown(0)) {
lastTouchedOnScreen = true;
}
else if (lastTouchedOnScreen && !game.getInput().isTouchDown(0)) {
lastTouchedOnScreen = false;
}
}
public boolean isSliderTouched()
{
Input input = game.getInput();
if (!input.isTouchDown(0)) {
return false;
}
Vector2d touchPos = new Vector2d(input.getTouchX(0), input.getTouchY(0));
return Rect.vectorWithinRect(touchPos, getTouchBounds());
}
Rect getTouchBounds()
{
return new Rect(
getPos().x,
getPos().y,
11 + low.getWidth() + slider.getWidth() + high.getWidth(),
notch.getHeight());
}
public float getHeight() {
return notch.getHeight();
}
public float getWidth() {
return low.getWidth() + high.getWidth() + slider.getWidth() + 15;
}
@Override
public void onPaint(float deltaTime) {
// TODO Auto-generated method stub
Graphics g = game.getGraphics();
g.drawImage(low, getPos().add(new Vector2d(3,notch.getHeight()/2 - low.getHeight()/2)));
g.drawImage(slider, new Vector2d(getPos().x + 7 + low.getWidth(), getPos().y + notch.getHeight()/2 - slider.getHeight()/2));
g.drawImage(high, new Vector2d(getPos().x + 11 + low.getWidth() + slider.getWidth(), getPos().y + notch.getHeight()/2 - high.getHeight()/2));
g.drawImage(notch, new Vector2d(getPos().x + 7 + low.getWidth() + sliderPosition*(maxX-minX), getPos().y));
}
@Override
public void onPause() {
// TODO Auto-generated method stub
}
@Override
public void onResume() {
// TODO Auto-generated method stub
}
}
<file_sep>/src/com/mitch/flyship/Enemy/EnemyComponent.java
package com.mitch.flyship.Enemy;
import com.mitch.flyship.objects.Enemy;
import com.mitch.flyship.objects.Ship;
/**
* Created by KleptoKat on 7/20/2014.
*/
public abstract class EnemyComponent {
protected Enemy enemy;
public boolean mustBeUnique = true;
public EnemyComponent() {}
public void setEnemy(Enemy enemy)
{
this.enemy = enemy;
}
public abstract EnemyComponent clone();
public void onComponentAdded() {}
public void onObjectCreationCompletion() {}
public void onPaint(float deltaTime) {}
public void onUpdate(double deltaTime) {}
public void onHit(Ship ship) {}
public void onTouch() {}
}<file_sep>/src/com/mitch/flyship/Enemy/Components/ExplosionAnimation.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.AnimationImage;
import com.mitch.flyship.Assets;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.flyship.objects.Ship;
import com.mitch.framework.Graphics;
import com.mitch.framework.containers.Frame;
import com.mitch.framework.containers.Vector2d;
/**
* A blank Enemy Component.
*/
class ExplosionAnimation extends EnemyComponent {
static final int N_EXPLOSIONS = 7;
private AnimationImage explosion;
private Vector2d offset = new Vector2d(0,0);
private Vector2d explosionPos = new Vector2d(0,0);
public ExplosionAnimation() {}
// DEBUGGING: Did you remember to clone the elements?
public ExplosionAnimation(XmlResourceParser parser) //xml stuff here
{
this();
offset.x = parser.getAttributeFloatValue(null, "x", 0);
offset.y = parser.getAttributeFloatValue(null, "y", 0);
}
@Override
public void onComponentAdded() {
super.onComponentAdded();
enemy.setDestroyingOnHit(false);
explosion = new AnimationImage(11);
for (int i = 1; i <= N_EXPLOSIONS; i++) {
explosion.addFrame(new Frame(Assets.getImage("Explosion/original/" + i)));
}
explosion.pause();
}
private void beginAnimation()
{
explosion.resume();
}
@Override
public void onHit(Ship ship) {
super.onHit(ship);
beginAnimation();
enemy.setDepth(500);
enemy.setColliding(false);
StaticImage comp = enemy.getComponent(StaticImage.class);
comp.setDrawing(false);
}
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
if (!explosion.isPaused()) {
explosion.updateTime(deltaTime);
enemy.setVelocity(enemy.getVelocity().scale(0.7));
explosionPos = enemy.getPos()
.add(enemy.getSize().divide(2)
.subtract(explosion.getFrame().image.getSize().divide(2)))
.add(offset);
}
if (explosion.getCurrentFrameIndex() == explosion.getAnimationSize()-1) {
enemy.getLevel().getBodyManager().removeBody(enemy);
}
}
@Override
public void onPaint(float deltaTime) {
super.onPaint(deltaTime);
if (!explosion.isPaused()) {
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
g.drawImage(explosion.getFrame().image, explosionPos);
}
}
@Override
public EnemyComponent clone() {
ExplosionAnimation component = new ExplosionAnimation();
component.offset = offset;
return component;
}
}
<file_sep>/src/com/mitch/flyship/Enemy/Components/Animation.java
package com.mitch.flyship.Enemy.Components;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.mitch.flyship.AnimationImage;
import com.mitch.flyship.Assets;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.flyship.objects.Ship;
import com.mitch.framework.Graphics;
import com.mitch.framework.containers.Frame;
import com.mitch.framework.containers.Vector2d;
public class Animation extends EnemyComponent {
private final static String FRAME = "Frame";
private List<String> images;
private List<Boolean> reverseX;
private List<Boolean> reverseY;
private int fps;
private AnimateOn animateOn;
private AnimationImage animation;
private Vector2d animationPosition;
/* my little animation children, i grant you life
* and later on, i shall taketh it away.
* I am the god of animation. */
private enum AnimateOn {
BIRTH,
DEATH
}
public Animation() {
fps = 0;
images = new ArrayList<String>();
reverseX = new ArrayList<Boolean>();
reverseY = new ArrayList<Boolean>();
}
public Animation(final XmlResourceParser parser) {
this();
fps = Integer.parseInt(parser.getAttributeValue(null, "fps"));
animateOn = AnimateOn.valueOf(parser.getAttributeValue(null, "animateOn"));
//adding somethign to be parsed that is a part of the Animation XML node
//must be put above this function call to parseImages, as it alters the xml
parseImages(parser);
animation = new AnimationImage(fps);
for(int i=0;i<images.size();i++) {
animation.addFrame(new Frame(Assets.getImage(images.get(i)), reverseX.get(i), reverseY.get(i)));
}
}
@Override
public void onComponentAdded() {
super.onComponentAdded();
enemy.setSize(animation.getFrame(0).image.getSize());
if(animateOn.equals(AnimateOn.DEATH)) {
enemy.setDestroyingOnHit(false);
}
}
@Override
public void onObjectCreationCompletion() {
super.onObjectCreationCompletion();
if(animateOn.equals(AnimateOn.BIRTH)) {
setAnimationPosition();
animation.resume();
}
}
@Override
public void onUpdate(final double deltaTime) {
super.onUpdate(deltaTime);
if(!animation.isPaused()) {
animation.updateTime(deltaTime);
setAnimationPosition();
}
if(animateOn.equals(AnimateOn.DEATH) && animation.getCurrentFrameIndex() == animation.getAnimationSize() -1) {
enemy.getLevel().getBodyManager().removeBody(enemy);
}
}
@Override
public void onPaint(final float deltaTime) {
super.onPaint(deltaTime);
if(!animation.isPaused()) {
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
g.drawImage(animation.getFrame().image, animationPosition);
}
}
@Override
public void onHit(final Ship ship) {
super.onHit(ship);
/* not working right now, this can only be used for BIRTH animations */
/*if(animateOn.equals(AnimateOn.DEATH) && animation.isPaused()) {
animation.resetAnimation();
setAnimationPosition();
enemy.setColliding(false);
StaticImage component = enemy.getComponent(StaticImage.class);
component.setDrawing(false);
}*/
}
@Override
public EnemyComponent clone() {
Animation enemy = new Animation();
enemy.fps = fps;
enemy.animation = animation;
enemy.animateOn = animateOn;
enemy.animationPosition = animationPosition;
return enemy;
}
private void parseImages(final XmlResourceParser parser) {
while(true) {
try {
int eventType = parser.next();
if (eventType == XmlResourceParser.END_TAG && parser.getName().equals("Animation")) {
break;
}
if (eventType != XmlResourceParser.START_TAG) {
continue;
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.d("XmlPullParserException", e.getLocalizedMessage());
continue;
} catch (IOException e) {
e.printStackTrace();
Log.d("IOException", e.getLocalizedMessage());
continue;
}
String tagName = parser.getName();
if(tagName.equals(FRAME)) {
String image = parser.getAttributeValue(null, "image");
images.add(image);
reverseX.add(Boolean.parseBoolean(parser.getAttributeValue(null, "reverseX")));
reverseY.add(Boolean.parseBoolean(parser.getAttributeValue(null, "reverseY")));
}
}
}
private void setAnimationPosition() {
animationPosition = enemy.getPos()
.add(enemy.getSize().divide(2))
.subtract(animation.getFrame().image.getSize().divide(2));
}
}
<file_sep>/src/com/mitch/flyship/objects/Water.java
package com.mitch.flyship.objects;
import java.util.ArrayList;
import java.util.List;
import com.mitch.flyship.Assets;
import com.mitch.flyship.GameBody;
import com.mitch.flyship.screens.Level;
import com.mitch.framework.Graphics;
import com.mitch.framework.Image;
import com.mitch.framework.containers.Vector2d;
public class Water extends GameBody {
Level level;
final Image image;
public Water(Level level)
{
super(level.getAirshipGame(), "WATER");
this.level = level;
this.image = Assets.getImage("water");
super.offset = image.getSize().divide(2);
}
@Override
public void onUpdate(double deltaTime) {
if (getPos().y > game.getGraphics().getHeight()) {
level.getBodyManager().removeBody(this);
}
}
@Override
public void onPaint(float deltaTime) {
Graphics g = game.getGraphics();
g.drawImage(image, getPos().subtract(offset));
}
@Override
public void onPause() {}
@Override
public void onResume() {}
public static List<GameBody> spawnObjects(Level level, String type)
{
Graphics g = level.getAirshipGame().getGraphics();
double xPos = Math.random()*( g.getWidth() - Assets.getImage("water").getWidth() );
double yPos = -Assets.getImage("water").getHeight();
Water water = new Water(level);
water.setPos(new Vector2d(xPos, yPos));
List<GameBody> bodies = new ArrayList<GameBody>();
bodies.add(water);
return bodies;
}
}<file_sep>/src/com/mitch/flyship/GoogleAPIManager.java
package com.mitch.flyship;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.games.Games;
import com.mitch.framework.implementation.AndroidGame;
public class GoogleAPIManager implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final int CONNECTION_RESOLUTION_REQUEST_CODE = 511010;
public static final int REQUEST_LEADERBOARD = 500;
List<LeaderboardScore> leaderboardScores;
GoogleApiClient client;
AndroidGame game;
public GoogleAPIManager(AndroidGame game)
{
this.game = game;
client = buildClient(game);
leaderboardScores = new ArrayList<LeaderboardScore>();
}
public GoogleApiClient buildClient(AndroidGame androidGame) {
return new GoogleApiClient.Builder(androidGame)
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
public void suspendConnection()
{
client.disconnect();
}
public void connect()
{
if (!client.isConnected() && !client.isConnecting()) {
client.connect();
}
}
public boolean isConnected()
{
return client.isConnected();
}
void tryPushScores()
{
if (client.isConnected()) {
Log.d("Google Api Manager", "Pushing Scores");
for (LeaderboardScore score : leaderboardScores) {
Games.Leaderboards.submitScore(client, score.getLeaderboard(), score.getScore());
/*game.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(client,
score.getLeaderboard()), REQUEST_LEADERBOARD);*/
}
leaderboardScores.clear();
} else if (!client.isConnecting()) {
connect();
}
}
public void pushLeaderboardScore(String leaderboardID, long score)
{
leaderboardScores.add(new LeaderboardScore(leaderboardID, score));
tryPushScores();
}
public void loadBoards()
{
if (client.isConnected()) {
game.startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(client), REQUEST_LEADERBOARD);
} else {
client.connect();
}
}
public void loadBoard(String leaderboard)
{
if (client.isConnected()) {
game.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(client,
leaderboard), REQUEST_LEADERBOARD);
} else {
client.connect();
}
}
public void unlockAchievement(String id)
{
Games.Achievements.unlock(client, id);
}
public void incrementAchievement(String id, int value)
{
Games.Achievements.increment(client, id, value);
}
public void unlockAchievement(int id)
{
Games.Achievements.unlock(client, game.getString(id));
}
public void incrementAchievement(int id, int value)
{
if (isConnected()) {
/*Games.Achievements.incrementImmediate(client, game.getString(id), value).setResultCallback(new ResultCallback<Achievements.UpdateAchievementResult>() {
@Override
public void onResult(UpdateAchievementResult arg0) {
Log.d(arg0.getAchievementId(), arg0.getStatus().toString());
}
});*/
Games.Achievements.increment(client, game.getString(id), value);
}
/*Games.Achievements.increment(client, game.getString(id), value);
Log.d("ACHIEVEMENT INCREMENTED!", value + ", bam");*/
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(game, CONNECTION_RESOLUTION_REQUEST_CODE);
} catch(Exception e) {
connect();
}
} else {
Log.d("Google Api Manager", "No resolution for failed connection.");
}
}
@Override
public void onConnected(Bundle bundle) {
Log.d("Google Api Manager", "Connected to Google Play.");
tryPushScores();
}
@Override
public void onConnectionSuspended(int cause) {
if (cause == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
connect();
}
}
public class LeaderboardScore
{
String leaderboard;
long score;
public LeaderboardScore(String leaderboard, long score)
{
this.leaderboard = leaderboard;
this.score = score;
}
public String getLeaderboard() {
return leaderboard;
}
public long getScore() {
return score;
}
}
}
<file_sep>/src/com/mitch/framework/implementation/AndroidGame.java
package com.mitch.framework.implementation;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import com.mitch.flyship.GoogleAPIManager;
import com.mitch.framework.Audio;
import com.mitch.framework.FileIO;
import com.mitch.framework.Game;
import com.mitch.framework.Graphics;
import com.mitch.framework.Input;
import com.mitch.framework.Screen;
import com.mitch.framework.containers.Vector2d;
public abstract class AndroidGame extends Activity implements Game {
//public GoogleApiClientBuilder clientBuilder;
public static float SCALE;
public static final float SCREEN_WIDTH = 201; // assets made for this dont change!!
public AndroidFastRenderView renderView;
protected GoogleAPIManager apiManager;
Graphics graphics;
Audio audio;
Input input;
FileIO fileIO;
Screen screen;
WakeLock wakeLock;
Vector2d screenSize;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Display display = getWindowManager().getDefaultDisplay();
screenSize = new Vector2d(display.getWidth(), display.getHeight());
/**
* Scaling the game size increases smoothness. Scale of 1 is jittery.
* screenSize.x / SCREEN_WIDTH is the maximum scale size. (note for preferences.)
*/
AndroidGame.SCALE = (int) (screenSize.x / SCREEN_WIDTH * 0.7);
AndroidGame.SCALE = AndroidGame.SCALE < 1 ? 1 : AndroidGame.SCALE;
Log.d("SCALE", ""+AndroidGame.SCALE);
createFrameBuffer();
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
screen = getInitScreen();
setContentView(renderView);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Airship! At the Helm!");
apiManager = new GoogleAPIManager(this);
apiManager.connect();
}
/*public int validateGooglePlayServices() {
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}*/
/*public void pushHighScore(int score) {
if(!clientBuilder.connected) {
try {
clientBuilder.connect();
} finally {
clientBuilder.pushToLeaderBoards(score);
}
}
}*/
public void createFrameBuffer()
{
int frameBufferX = (int) (SCREEN_WIDTH*SCALE);
int frameBufferY = (int) ((screenSize.y/screenSize.x)*frameBufferX);
float scaleX = (float)(frameBufferX/screenSize.x);
float scaleY = (float) (frameBufferY/screenSize.y);
Bitmap frameBuffer = Bitmap.createBitmap( (int) frameBufferX,
(int) frameBufferY, Config.RGB_565);
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
input = new AndroidInput(this, renderView, scaleX/SCALE, scaleY/SCALE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GoogleAPIManager.CONNECTION_RESOLUTION_REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
apiManager.connect();
} else {
}
}
@Override
public void onResume() {
super.onResume();
wakeLock.acquire();
screen.resume();
renderView.resume();
input.onResume();
/*validateGooglePlayServices();
if(!clientBuilder.connected) {
clientBuilder.connect();
}*/
}
@Override
public void onPause() {
super.onPause();
wakeLock.release();
renderView.pause();
screen.pause();
input.onPause();
if (isFinishing())
screen.dispose();
}
@Override
public Input getInput() {
return input;
}
public void Vibrate(int time) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(time);
}
@Override
public FileIO getFileIO() {
return fileIO;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public Audio getAudio() {
return audio;
}
@Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
public Screen getCurrentScreen() {
return screen;
}
public GoogleAPIManager getGoogleAPIManager()
{
return apiManager;
}
// keep these methods for reference
/*@SuppressWarnings("rawtypes")
public ArrayList GetHighScores() {
if(highScores.size()==0) {
String Score1 = prefs.getString("score1",null);
if(Score1 == null) {
SetHighScoresZero();
Score1 = prefs.getString("score1",null);
}
String Score2 = prefs.getString("score2",null);
String Score3 = prefs.getString("score3",null);
String Score4 = prefs.getString("score4",null);
String Score5 = prefs.getString("score5",null);
highScores.add(Score1);
highScores.add(Score2);
highScores.add(Score3);
highScores.add(Score4);
highScores.add(Score5);
}
return highScores;
}
@SuppressWarnings("rawtypes")
public ArrayList GetGearHighScores() {
ArrayList<Integer> gearHighScores = new ArrayList<Integer>();
ArrayList<String> highScore = GetHighScores();
for(int i=0;i<highScore.size();i++) {
String score = highScore.get(i);
for(int j=0;j<5;j++) {
if(score.charAt(j) == '_') {
gearHighScores.add(Integer.parseInt(score.substring(0,j)));
break;
}
}
}
return gearHighScores;
}
public ArrayList GetTimeHighScores() {
ArrayList<String> timeHighScores = new ArrayList<String>();
ArrayList<String> highScore = GetHighScores();
for(int i=0;i<highScore.size();i++) {
String score = highScore.get(i);
for(int j=0;j<5;j++) {
if(score.charAt(j) == '_') {
timeHighScores.add(score.substring(j+1,score.length()));
break;
}
}
}
return timeHighScores;
}
public void SaveHighScore(int gearScore, String timeScore) {
ArrayList<Integer> gearScores = GetGearHighScores();
ArrayList<String> timeScores = GetTimeHighScores();
if(gearScores.get(0) == null) {
SetHighScoresZero();
gearScores = GetGearHighScores();
timeScores = GetTimeHighScores();
}
Collections.sort(gearScores, Collections.reverseOrder());
Collections.sort(timeScores, Collections.reverseOrder());
for(int i=0;i<5;i++) {
if(gearScore == gearScores.get(i)) {
int index = timeScores.get(i).indexOf(':');
int oldMins = Integer.parseInt(timeScores.get(i).substring(0,index));
int oldSecs = Integer.parseInt(timeScores.get(i).substring(index+1,timeScores.get(i).length()));
int indexOfColon2 = timeScore.indexOf(':');
int newMins = Integer.parseInt(timeScore.substring(0,indexOfColon2));
int newSecs = Integer.parseInt(timeScore.substring(indexOfColon2+1,timeScore.length()));
if(newMins == oldMins) {
if(newSecs > oldSecs) {
gearScores.add(i,gearScore);
timeScores.add(i,timeScore);
break;
}
}
else if(newMins > oldMins) {
gearScores.add(i, gearScore);
timeScores.add(i, timeScore);
}
}
else if(gearScore > gearScores.get(i)) {
gearScores.add(i, gearScore);
timeScores.add(i, timeScore);
break;
}
}
SaveTop5(gearScores, timeScores);
}
public void SaveTop5(ArrayList<Integer> gearScores, ArrayList<String> times) {
//Log.w("LOG","gears:"+gearScores+" time:"+times);
String score1 = Integer.toString(gearScores.get(0)) + "_" + times.get(0);
String score2 = Integer.toString(gearScores.get(1)) + "_" + times.get(1);
String score3 = Integer.toString(gearScores.get(2)) + "_" + times.get(2);
String score4 = Integer.toString(gearScores.get(3)) + "_" + times.get(3);
String score5 = Integer.toString(gearScores.get(4)) + "_" + times.get(4);
editor.putString("score1", score1);
editor.putString("score2", score2);
editor.putString("score3", score3);
editor.putString("score4", score4);
editor.putString("score5", score5);
editor.commit();
}
public void SetHighScoresZero() {
editor.putString("score1","0_00:00");
editor.putString("score2","0_00:00");
editor.putString("score3","0_00:00");
editor.putString("score4","0_00:00");
editor.putString("score5","0_00:00");
editor.commit();
}*/
}<file_sep>/src/com/mitch/flyship/Enemy/Components/BlankComponent.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Enemy.EnemyComponent;
/**
* A blank Enemy Component.
*/
public class BlankComponent extends EnemyComponent {
public BlankComponent() {}
// DEBUGGING: Did you remember to clone the elements?
public BlankComponent(XmlResourceParser parser) //xml stuff here
{ this(); }
@Override
public EnemyComponent clone() {
BlankComponent component = new BlankComponent();
return component;
}
}
<file_sep>/src/com/mitch/flyship/Enemy/Components/VerticalEnemy.java
package com.mitch.flyship.Enemy.Components;
import android.content.res.XmlResourceParser;
import com.mitch.flyship.Enemy.EnemyComponent;
import com.mitch.framework.Graphics;
import com.mitch.framework.containers.Vector2d;
/**
* Created by KleptoKat on 7/20/2014.
*/
public class VerticalEnemy extends EnemyComponent {
double speed;
boolean directionDown = true;
public VerticalEnemy() {}
public VerticalEnemy(double speed, boolean directionDown)
{
this.speed = speed;
this.directionDown = directionDown;
}
public VerticalEnemy(XmlResourceParser xrp) //xml stuff here
{
this();
speed = Double.valueOf(xrp.getAttributeValue(null, "speed"));
directionDown = xrp.getAttributeBooleanValue(null, "directionDown", true);
}
@Override
public void onComponentAdded() {
super.onComponentAdded();
enemy.setVelocity(new Vector2d(0, directionDown ? speed : -speed));
}
@Override
public void onObjectCreationCompletion() {
super.onObjectCreationCompletion();
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
double x = Math.random() * (g.getWidth() - enemy.getSize().x);
double y = directionDown ? -enemy.getSize().y : g.getHeight();
enemy.setPos(new Vector2d(x, y));
}
@Override
public void onUpdate(double deltaTime) {
super.onUpdate(deltaTime);
Graphics g = enemy.getLevel().getAirshipGame().getGraphics();
if ( (enemy.getPos().y > g.getHeight() && directionDown) ||
(enemy.getPos().y < 0 && !directionDown) ) {
enemy.getLevel().getBodyManager().removeBody(enemy);
}
}
@Override
public EnemyComponent clone() {
VerticalEnemy enemy = new VerticalEnemy();
enemy.directionDown = directionDown;
enemy.speed = speed;
return enemy;
}
}
| 4610af049191a327d4e33526dc80cc92989f9986 | [
"Java"
] | 24 | Java | mitchfriedman/Airship | e440fa2134e1fdfc3051fc606db881c1a53dbff1 | 9e6abdef9f136d21aabb1b469e42be602fae0246 |
refs/heads/master | <repo_name>1thorarinn/composerPrufa<file_sep>/archive-posts.php
<?php
/*
Template Name: Blog
*/
?>
<?php get_header(); ?>
<div class="section lightgrey" id="blog-overview">
<?php if ( have_posts() ) : ?>
<?php while (have_posts()) : the_post(); ?>
<div class="container">
<div class="row">
<div class="col s12">
<h1 class="center header text_h2"><?php the_title(); ?></h1>
</div>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<div id="primary" class="content-area container">
<main id="main" class="site-main" role="main">
<!-- Posts -->
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; ?>
<?php query_posts('showposts=6&post_type=post&paged=' . $paged); // First post Featured ?>
<?php get_template_part('template-parts/loop', 'archive'); ?>
<?php rewind_posts(); ?>
<!-- /Posts -->
<?php //the_posts_navigation(); // http://wordpress.stackexchange.com/questions/174907/how-to-use-the-posts-navigation-for-wp-query-and-get-posts ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- c/lass="section lightgrey" id="blog-overview" -->
<?php
get_sidebar();
get_footer();
| 9b570088873d772f687641d6ccbe258eec3a8988 | [
"PHP"
] | 1 | PHP | 1thorarinn/composerPrufa | 49ebd0f244e7f59300f0316f776b3eded71d5985 | 6437a8c7222a10322d6a41bd774d2708f4a1b8c6 |
refs/heads/master | <file_sep>import Vue from 'vue';
const defaultParameters = {
c: `thumb`,
f: `auto`,
g: `center`,
q: `auto`,
};
const imageHost = `https://res.cloudinary.com/maoberlehner/image/upload`;
export default {
install() {
Vue.prototype.$img = function $img(
id = ``,
width = 0,
height = 0,
parameters = {},
) {
const activeParameters = { ...defaultParameters, ...parameters };
if (width > 0) activeParameters.w = width;
if (height > 0) activeParameters.h = height;
const parameterString = Object.keys(activeParameters)
.map(x => `${x}_${activeParameters[x]}`)
.join(`,`);
return `${imageHost}/${parameterString}/${id}`;
};
},
};
<file_sep>import api from '../utils/api';
export default {
data() {
return {
content: null,
};
},
created() {
this.fetchData();
},
methods: {
async fetchData() {
const { data } = await api.get(`cdn/stories/${this.slug}`);
this.content = data.story.content;
},
},
};
| fb4b361f493eaf336e5eb7df11d20021a4125b3e | [
"JavaScript"
] | 2 | JavaScript | maoberlehner/using-cloudinary-and-storyblok-to-handle-assets-for-a-vue-application | 8d9c8b2a809d2a808beeb4b337a54a10bdb8546c | 18d8befbc2f0a2a20522dd5e4b4967d815d93be1 |
refs/heads/master | <file_sep>const path = require('path');
const webpack = require('webpack');
const ROOT_PATH = path.resolve(__dirname);
const SRC_PATH = path.resolve(ROOT_PATH, 'src');
const BUILD_PATH = path.resolve(ROOT_PATH, 'dist');
module.exports = {
entry: {
index: path.resolve(SRC_PATH, 'index.jsx')
},
output: {
path: BUILD_PATH,
filename: 'js/[name].[hash:5].js'
},
module: {
// 配置preLoaders, 将eslint添加进去
loaders: [
{
test: /\.jsx?$/,
loaders: ['eslint-loader'],
include: SRC_PATH,
enforce: 'pre'
}, {
test: /\.jsx?$/,
loaders: ['babel-loader'],
include: SRC_PATH,
exclude: path.resolve(ROOT_PATH, 'node_modules')
}
]
},
plugins: [
new webpack.DllReferencePlugin({
manifest: require(path.resolve(ROOT_PATH, 'lib', 'manifest.json')),
context: ROOT_PATH,
})
]
};<file_sep># react-webpack
基于webpack手工搭建react环境
## 启动 ##
npm run start
## 搭建过程中遇到的问题 ##
error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
#出现原因:eslint配置了换行必须使用LF,Windows下的编辑器里需要设置使用LF换行
eslint配置文件中关闭掉这个错误就行了, "linebreak-style":[0]
```javascript
module.exports = {
extends: 'google',
quotes: [2, 'single'],
globals: {
SwaggerEditor: false
},
env: {
browser: true
},
rules:{
"linebreak-style": 0
}
}
```
# 搭建步骤简述 #
1. npm init 项目初始化,生成一个package.json
2. 安装webpack
```javascript
npm install webpack webpack-dev-server --save-dev
```
3. 安装Babel
```javascript
npm install babel-core babel-preset-es2015 babel-preset-react --save-dev
```
4. 配置Babel 见工程下的.babelrc
```javascript
{
"presets": ["es2015", "react"]
}
```
5.安装ESLint
```javascript
npm install eslint@3.19.0 install eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y --save-dev
```
6. 配置ESLint 详细见工程的.eslintrc.js
7. 安装webpack loader
```javascript
npm install eslint-loader install babel-loader style-loader css-loader less-loader sass-loader file-loader url-loader --save-dev
```
8. 安装webpack plugin
```javascript
npm install html-webpack-plugin uglifyjs-webpack-plugin --save-dev
```
9. 配置webpack 详细看文件夹webpack.config.js
10. 安装核心功能包
```javascript
npm install react react-dom redux redux-actions react-redux react-router react-router-redux redux-devtools --save
```
11. 创建项目入口模块 根目录下创建src目录-->新建/src/index.jsx:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
function Index() {
return (
<div className="container">
<h1>Hello React!</h1>
</div>
);
}
ReactDOM.render(<Index />, document.getElementById('root'));
export default Index;
```
12. 创建渲染页面 在src下的templates文件中创建index.html-->/scr/templates/index.html
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
| 0dbc1bc0bf0c4ebbfb289fe1e7de0f108d52d05f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | zhaoFangyi/react-webpack | 53cee7a490f1451c132a8dfd6a367d49837688c8 | 95b4f37805c3d9b63f0bf98306cab0341753428e |
refs/heads/master | <repo_name>zakharenkodmytro/gwtptest<file_sep>/src/main/java/com/dima/dima/client/application/ThirdPresenter.java
package com.dima.dima.client.application;
import com.dima.dima.client.place.NameTokens;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
//import com.gwtplatform.mvp.client.presenter.slots.NestedSlot;
import com.gwtplatform.mvp.client.annotations.UseGatekeeper;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
public class ThirdPresenter extends Presenter<ThirdPresenter.MyView, ThirdPresenter.MyProxy> {
interface MyView extends View {
}
@NameToken(NameTokens.third)
@ProxyCodeSplit
//@UseGatekeeper(TestGateKeeper.class)
interface MyProxy extends ProxyPlace<ThirdPresenter> {
}
public static final Object SLOT_rate = new Object();
@Inject
ThirdPresenter(
EventBus eventBus,
MyView view,
MyProxy proxy) {
super(eventBus, view, proxy, HeaderPresenter.SLOT_content);
}
@Inject
RatePagePresenter ratePagePresenter;
@Override
protected void onReset() {
super.onReset();
setInSlot(ThirdPresenter.SLOT_rate, ratePagePresenter);
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/SecondPresenterView.java
package com.dima.dima.client.application;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import com.gwtplatform.mvp.client.ViewImpl;
import javax.inject.Inject;
public class SecondPresenterView extends ViewImpl implements SecondPresenterPresenter.MyView {
interface Binder extends UiBinder<Widget, SecondPresenterView> {
}
@UiField
Label secondLabel;
@UiField
HTMLPanel listPanel;
public Label getSecondLabel() {
return secondLabel;
}
@Inject
SecondPresenterView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
@Override
public void setInSlot(Object slot, IsWidget content) {
if (slot == SecondPresenterPresenter.SLOT_list) {
listPanel.clear();
if (content != null) {
listPanel.add(content);
}
} else {
super.setInSlot(slot, content);
}
}
@Override
public void addToSlot(Object slot, IsWidget content) {
if (slot == SecondPresenterPresenter.SLOT_list) {
if (content != null) {
listPanel.add(content);
}
} else {
super.addToSlot(slot, content);
}
}
}
<file_sep>/src/main/java/com/dima/dima/server/DispatchHandlersModule.java
package com.dima.dima.server;
import com.dima.dima.client.application.GetData;
import com.dima.dima.client.application.GetFirst;
import com.gwtplatform.dispatch.rpc.server.guice.HandlerModule;
public class DispatchHandlersModule extends HandlerModule {
@Override
protected void configureHandlers() {
bindHandler(GetFirst.class, GetFirstActionHandler.class);
bindHandler(GetData.class, GetDataActionHandler.class);
System.out.println("I;m in DispatchHandlersModule");
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/ApplicationModule.java
package com.dima.dima.client.application;
import com.dima.dima.client.application.home.HomeModule;
import com.dima.dima.client.application.home.HomePresenter;
import com.dima.dima.client.application.home.HomeView;
import com.gwtplatform.mvp.client.gin.AbstractPresenterModule;
public class ApplicationModule extends AbstractPresenterModule {
@Override
protected void configure() {
install(new HomeModule());
bindPresenter(ApplicationPresenter.class, ApplicationPresenter.MyView.class, ApplicationView.class,
ApplicationPresenter.MyProxy.class);
bindPresenter(FirstPresenterPresenter.class, FirstPresenterPresenter.MyView.class, FirstPresenterView.class,
FirstPresenterPresenter.MyProxy.class);
bindPresenter(SecondPresenterPresenter.class, SecondPresenterPresenter.MyView.class, SecondPresenterView.class,
SecondPresenterPresenter.MyProxy.class);
bindPresenter(ThirdPresenter.class, ThirdPresenter.MyView.class, ThirdView.class,
ThirdPresenter.MyProxy.class);
bindPresenter(HeaderPresenter.class, HeaderPresenter.MyView.class, HeaderView.class,
HeaderPresenter.MyProxy.class);
bindPresenter(ErrorPresenter.class, ErrorPresenter.MyView.class, ErrorView.class,
ErrorPresenter.MyProxy.class);
bindPresenterWidget(RatePagePresenter.class, RatePagePresenter.MyView.class, RatePageView.class);
bindPresenterWidget(WhyNotPresenter.class, WhyNotPresenter.MyView.class, WhyNotView.class);
}
}<file_sep>/src/main/java/com/dima/dima/client/application/HeaderPresenter.java
package com.dima.dima.client.application;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.user.client.ui.Label;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
//import com.gwtplatform.mvp.client.presenter.slots.NestedSlot;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
public class HeaderPresenter extends Presenter<HeaderPresenter.MyView, HeaderPresenter.MyProxy> {
private UserNotHappyEventHandler notHappyEventHandler = new UserNotHappyEventHandler() {
@Override
public void onUserNotHappy(UserNotHappyEvent event) {
getView().getHappyLabel().setText("");
}
};
interface MyView extends View {
public Label getHappyLabel();
}
@ProxyStandard
interface MyProxy extends Proxy<HeaderPresenter> {
}
@ContentSlot
public static final GwtEvent.Type<RevealContentHandler<?>> SLOT_content = new GwtEvent.Type<>();
@Inject
HeaderPresenter(
EventBus eventBus,
MyView view,
MyProxy proxy) {
super(eventBus, view, proxy, RevealType.Root);
}
@Override
protected void onBind() {
super.onBind();
registerHandler(getEventBus().addHandler(UserNotHappyEvent.TYPE, notHappyEventHandler));
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/ThirdView.java
package com.dima.dima.client.application;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;
import javax.inject.Inject;
public class ThirdView extends ViewImpl implements ThirdPresenter.MyView {
interface Binder extends UiBinder<Widget, ThirdView> {
}
@UiField
HTMLPanel ratePanel;
@Inject
ThirdView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
@Override
public void setInSlot(Object slot, IsWidget content) {
if (slot == ThirdPresenter.SLOT_rate) {
ratePanel.clear();
if (content != null) {
ratePanel.add(content);
}
} else {
super.setInSlot(slot, content);
}
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/GetFirst.java
package com.dima.dima.client.application;
import com.gwtplatform.dispatch.rpc.shared.ActionImpl;
import com.gwtplatform.dispatch.rpc.shared.UnsecuredActionImpl;
/**
* Created by Olga on 19.10.2015.
*/
public class GetFirst extends UnsecuredActionImpl<GetFirstResult> {
private String text;
@Override
public boolean isSecured() {
return super.isSecured();
}
private GetFirst() {
}
public GetFirst(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/WhyNotView.java
package com.dima.dima.client.application;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.PopupViewImpl;
public class WhyNotView extends PopupViewImpl implements WhyNotPresenter.MyView {
interface Binder extends UiBinder<PopupPanel, WhyNotView> {
}
@UiField
Button okButton;
public Button getOkButton() {
return okButton;
}
@Inject
WhyNotView(Binder uiBinder, EventBus eventBus) {
super(eventBus);
initWidget(uiBinder.createAndBindUi(this));
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/ErrorPresenter.java
package com.dima.dima.client.application;
import com.dima.dima.client.place.NameTokens;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
public class ErrorPresenter extends Presenter<ErrorPresenter.MyView, ErrorPresenter.MyProxy> {
interface MyView extends View {
}
@NameToken(NameTokens.error)
@ProxyCodeSplit
interface MyProxy extends ProxyPlace<ErrorPresenter> {
}
// public static final NestedSlot SLOT_ERROR = new NestedSlot();
@Inject
ErrorPresenter(
EventBus eventBus,
MyView view,
MyProxy proxy) {
super(eventBus, view, proxy, HeaderPresenter.SLOT_content);
}
}
<file_sep>/src/main/java/com/dima/dima/client/application/GetDataResult.java
package com.dima.dima.client.application;
import com.gwtplatform.dispatch.rpc.shared.Result;
/**
* Created by Olga on 21.10.2015.
*/
public class GetDataResult implements Result {
private String result;
public GetDataResult() {}
public GetDataResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
}<file_sep>/src/main/java/com/dima/dima/server/guice/ServerModule.java
package com.dima.dima.server.guice;
import com.dima.dima.server.DispatchHandlersModule;
import com.gwtplatform.dispatch.rpc.server.guice.HandlerModule;
public class ServerModule extends HandlerModule {
@Override
protected void configureHandlers() {
install(new DispatchHandlersModule());
}
}
| 6034a22037ea9acba2f2b9b3b7979345e69056f2 | [
"Java"
] | 11 | Java | zakharenkodmytro/gwtptest | e34513cc213442e6922c0fa2d434c8262b2696ec | b66978cee12bc9eef3f879efdd0329f5f4041485 |
refs/heads/main | <file_sep>import { useState } from "react";
import 'semantic-ui-css/semantic.min.css';
import { Button, Form} from 'semantic-ui-react';
import "./App.css";
import Exceldata from './exceldata';
import Footer from "./Footer";
function App () {
const [data, setData] = useState({
Nombre: "",
Especialidad: "",
Contacto1: "",
Contacto2: "",
Portafolio: "",
Web: "",
});
const handleChange = (e) =>
setData({ ...data, [e.target.name]: e.target.value });
const handleSubmit = async (e) => {
e.preventDefault();
try {
await fetch(
"https://sheet.best/api/sheets/952adab9-c60d-4d56-945f-4d550147cfbd",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}
);
} catch (error) {
console.log(error);
}
window.location.reload();
};
return (
<div className="container">
<div className="title">
<h1>Directorio de especialistas en CM Freelance Perú</h1>
</div>
<div className="formcontainer">
<Form className="form" onSubmit={handleSubmit}>
<Form.Field>
<label>Nombre</label>
<input placeholder='Ingresa tu nombre completo' type="text" name = "Nombre" value = {data.Nombre} onChange={handleChange}/>
</Form.Field>
<Form.Field>
<label>Especialidad</label>
<input placeholder='Ingresa tus especialidades' type="text" name = "Especialidad" value = {data.Especialidad} onChange={handleChange}/>
</Form.Field>
<Form.Field>
<label>Contacto1</label>
<input placeholder='Ingresa tu Celular sin espacios o +' type="text" name = "Contacto1" value = {data.Contacto1} onChange={handleChange}/>
</Form.Field>
<Form.Field>
<label>Contacto2</label>
<input placeholder='¿Hay alguna otra forma de contactarte?' type="text" name = "Contacto2" value = {data.Contacto2} onChange={handleChange}/>
</Form.Field>
<Form.Field>
<label>Portafolio</label>
<input placeholder='Ingresa tu portafolio' type="text" name = "Portafolio" value = {data.Portafolio} onChange={handleChange}/>
</Form.Field>
<Form.Field>
<label>Web</label>
<input placeholder='Ingresa tu web' type="text" name = "Web" value = {data.Web} onChange={handleChange}/>
</Form.Field>
<Button color="blue" type='submit'>Enviar</Button>
</Form>
</div>
<div>
<Exceldata />
</div>
<div>
<Footer />
</div>
</div>
);
};
export default App;<file_sep>import React, { useEffect, useState } from "react";
import 'semantic-ui-css/semantic.min.css';
import './exceldata.css';
function ExcelData() {
const [data,setData] =useState();
const getData=async() =>{
try {
const res= await fetch("https://sheet.best/api/sheets/952adab9-c60d-4d56-945f-4d550147cfbd");
const data= await res.json();
setData(data);
} catch(error){
console.log(error);
}
};
useEffect(()=>{
getData();
},[]);
return (
<div className="containerdata">
<div className="mapdata">
{data?.map((item,i)=>(
<div class="ui cards" key={i}>
<div class="ui centered card">
<div class="content">
<div class="header">
{item.Nombre}
</div>
<div class="meta">
{item.Especialidad}
</div>
<div class="description">
{item.Contacto1}
</div>
<div class="description">
<a href={item.Portafolio} target="_blank" rel="noreferrer">
{item.Portafolio}
</a>
</div>
<div class="description">
<a href={item.Web} target="_blank" rel="noreferrer">
{item.Web}
</a>
</div>
</div>
</div>
</div>
))}
</div>
</div>
);
}
export default ExcelData;
<file_sep>import React from 'react';
import './Footer.css';
function Footer() {
return (
<div className='footer-container'>
<div className="containerfooter">
<div className="col">
<a href="https://portfolio-cm-2021.netlify.app/" target="_blank" rel="noreferrer">
2021 © <NAME>
</a>
</div>
</div>
</div>
);
}
export default Footer; | f3209d59fde87310b3241e0e0863f76ab332615d | [
"JavaScript"
] | 3 | JavaScript | CarlosMurilloGH/FormToGoogleSheet | 9f93a8cd940947e0d11b08e73cd53a38f79b44c8 | 8ab5d1781346214b93b4b2f7f46b5fdc41ae9834 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace puntaje_de_tenis
{
public partial class Form1 : Form
{
public string[] s_Puntaje = new string[5]; //points puede tener 5 diferentes puntajes
public int A = 0, B = 0; // Contadores
public struct Save { // Guardo del retroceso
public string save1, save2, save3, save4, save5, save6;
public bool jugador;
}
public Save save;//onjetos del guardado
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
s_Puntaje[0] = "00"; // valores del contador points
s_Puntaje[1] = "15";
s_Puntaje[2] = "30";
s_Puntaje[3] = "40";
s_Puntaje[4] = "Ad";
button3.Enabled = false; // inahabilitamos botn de retroceso
}
private void button2_Click(object sender, EventArgs e)
{
save.save1 = label1.Text; save.save2 = label2.Text; save.save3 = label3.Text; //Hacemos el save del puntaje actual
save.save4 = label4.Text; save.save5 = label5.Text; save.save6 = label6.Text;
save.jugador = false;
B++;
if (A == 4 && B == 4) //si amabos llegan a estar en ventaja "Ad" los regresa a 40
{
A--;
B--;
label3.Text = s_Puntaje[3];
label6.Text = s_Puntaje[3];
}
if (B == 5) { // si un jugador mete 5 equivale es un game
label5.Text = '0' + Convert.ToString(Convert.ToInt32(label5.Text) + 1);
B = 0;//regresamos poins a 00
A = 0;
if (Convert.ToInt32(label5.Text) == 6) { // si un jugador mete 5 equivale a un set
label4.Text = '0' + Convert.ToString(Convert.ToInt32(label4.Text) + 1);
label5.Text = s_Puntaje[0];//regresamos game a 00
label2.Text = s_Puntaje[0];
if (Convert.ToInt32(label4.Text) == 2) { // con 2 sets gana
label6.Text = s_Puntaje[B]; //cambia el la informacion de la tabla antes del messegebox
label4.Text = s_Puntaje[0];
MessageBox.Show("EL jugador A a ganado", "Ganador");//mensaje de victoria
}
}
}
label6.Text = s_Puntaje[B]; //un jugador puede modificar al otro
label3.Text = s_Puntaje[A];
button3.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
save.save1 = label1.Text; save.save2 = label2.Text; save.save3 = label3.Text;
save.save4 = label4.Text; save.save5 = label5.Text; save.save6 = label6.Text;
save.jugador = true;
A++;
if (A == 4 && B == 4){
A--;
B--;
label3.Text = s_Puntaje[3];
label6.Text = s_Puntaje[3];
}
if (A == 5) {
label2.Text = '0' + Convert.ToString(Convert.ToInt32(label2.Text) + 1);
A = 0;
B = 0;
if (Convert.ToInt32(label2.Text) == 6) {
label1.Text = '0' + Convert.ToString(Convert.ToInt32(label1.Text) + 1);
label2.Text = s_Puntaje[0];
label5.Text = s_Puntaje[0];
if (Convert.ToInt32(label1.Text) == 2){
label3.Text = s_Puntaje[B];
MessageBox.Show("EL jugador A a ganado", "Ganador");
label1.Text = s_Puntaje[0];
button3.Enabled = false;
}
}
}
label3.Text = s_Puntaje[A];
label6.Text = s_Puntaje[B];
button3.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
label1.Text = save.save1; label2.Text = save.save2; label3.Text = save.save3;
label4.Text = save.save4; label5.Text = save.save5; label6.Text = save.save6;
if (A == 0 || B == 0)
{
if (A == 0)
{
if (save.jugador == true)
{
A = 4;
}
}
else
{
if (save.jugador == false)
{
B = 4;
}
}
if (save.jugador == true) { A--; } //jugador "A" metio el ultimo punto
else { B--; } //jugador "A" metio el ultimo punto
}
button3.Enabled = false;
}
}
}
| 584db6fd615fed4fa841a4cd5eaca997733e0ffe | [
"C#"
] | 1 | C# | jalilraziel/Marcador_de_tenis | 0ac34cdd76b245867d2abdeed05f3ca3cfe43669 | a2a164e3a588b4eb2a1f724a9988a717199897f3 |
refs/heads/master | <repo_name>cews7/javascript-roman-numerals<file_sep>/test/roman-numerals-test.js
const assert = require('chai').assert
const romanNumeralConverter = require('../lib/roman-numerals')
describe("romanNumeralConverter function", function() {
it('converts arabic number to roman numeral', function() {
assert.equal(romanNumeralConverter(10), "X")
assert.equal(romanNumeralConverter(1000), "M")
assert.equal(romanNumeralConverter(2017), "MMXVII")
});
});
| a424f595930e21c7997137745a44d97cca8ce699 | [
"JavaScript"
] | 1 | JavaScript | cews7/javascript-roman-numerals | 9eaa9f4d8f78619ccd0858389626f4ef42eaad81 | 7de15347ff2f4ed967f4500edd9d7569281ddb98 |
refs/heads/master | <repo_name>silva1999/m150-autovermietung_frontend<file_sep>/WebContent/js/script.js
/**
* @author <NAME>
* @date 21.01.2019
* @version 1.0
* Inspiration for ajax call: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call
*
* External javascript functions
*/
/*
* -------------- General functions --------------------------
*/
/* Open login dialog, or logout and redirect to start */
function openLogin(){
/* logout */
if($("#userId").val() != ""){
$("#userId").val("");
$("#usernameId").val("");
$("#loginname").text("Anmelden");
if($("#pageId").val() != "overview"){
goToOverview();
}
}
/* Open login dialog*/
else{
document.getElementById("logindlg").style.display = "block";
document.getElementById("username").value = "";
document.getElementById("pw").value = "";
}
}
/* close login dialog */
function closeLogin(){
document.getElementById("logindlg").style.display = "none";
document.getElementById("username").value = "";
document.getElementById("pw").value = "";
document.getElementById("errorLogin").innerHTML = "";
if($("#bookCar").val() == "yes" && $("#userId").val() != ""){
$("#bookCar").val("");
goToForm();
}
}
/* Store credentials in page */
function storeIds(carId, userId, username, page){
$("#userId").val(userId);
$("#carId").val(carId);
$("#usernameId").val(username);
$("#loginname").text(username);
$("#pageId").val(page);
}
/* call login endpoint */
function login(){
var username = $("#username").val();
var pw = $("#pw").val();
$.ajax({
type: "GET",
url: "http://localhost:8080/user/login?username=" + username + "&password=" + pw,
timeout: 600000,
success: function (data) {
$("#errorLogin").text("");
$("#loginname").text(data.username);
$("#usernameId").val(data.username);
$("#userId").val(data.userId);
console.log("SUCCESS : ", data);
closeLogin();
},
error: function (e) {
$("#errorLogin").text("Benutzername oder Passwort ist nicht korrekt.");
$("#loginname").text("Anmelden");
$("#usernameId").val("");
$("#userId").val("");
console.log("ERROR : ", e);
}
});
}
/* Redirect to form page */
function goToForm(){
$("#bookCar").val("yes");
var userId = $("#userId").val();
var carId = $("#carId").val();
var username = $("#usernameId").val();
if(userId == "" || username == ""){
openLogin();
}else{
redirectToOtherPage(username,userId,carId,"form")
}
}
/* Redirect to overview page */
function goToOverview(){
var userId = $("#userId").val();
var carId = $("#carId").val();
var username = $("#usernameId").val();
redirectToOtherPage(username,userId,carId,"overview");
}
/* Redirect function */
function redirectToOtherPage(username,userId,carId,page){
var url = 'http://localhost:9080/Autovermietung_frontend/jsp/content.jsp';
if(userId == "" || username == ""){
window.location = url;
}else{
window.location = url
+ '?username=' + username
+ '&token=' + userId
+ '&carId=' + carId
+ '&page=' + page;
}
}
/*
* -------------- Overview functions --------------------------
*/
/* Open detail dialog */
function showDetails(apiResponse) {
var data = apiResponse;
var focusedCarId = "item" + data.id;
document.getElementById("detailWindow").style.display = "block";
document.getElementById("list").style.width = "75%";
document.getElementById("detailName").innerHTML = "" + data.name;
document.getElementById("detailSpecification").innerHTML = "" + data.specification;
document.getElementById("detailPlace").innerHTML = "" + data.place;
document.getElementById("detailPrice").innerHTML = "" + data.price + " CHF";
document.getElementById("carId").value = data.id;
var elements = document.getElementsByClassName('item');
for (var i = 0; i < elements.length; i++) {
elements[i].style["margin-left"] = "70px";
elements[i].style["margin-right"] = "50px";
elements[i].style["background-color"] = "#58bef5";
}
$("#focusedCar").val(focusedCarId);
document.getElementById(focusedCarId).style.background = "#58feff";
}
/* Close detail dialog */
function closeDetails() {
document.getElementById("item1").style.display = "none";
document.getElementById("list").style.width = "100%";
var elements = document.getElementsByClassName('item');
for (var i = 0; i < elements.length; i++) {
elements[i].style["margin-left"] = "220px";
elements[i].style["margin-right"] = "150px";
}
}
/* Call endpoint and get car list */
function getCars(callback){
$.ajax({
type: "GET",
url: "http://localhost:8080/cars",
timeout: 600000,
success: callback,
error: function (e) {
console.log("ERROR : ", e);
}
});
}
/* Call endpoint and get car by id */
function getCarByIdWithCallback(id, callback){
$.ajax({
type: "GET",
url: "http://localhost:8080/cars/" + id,
timeout: 600000,
success: callback,
error: function (e) {
console.log("ERROR : ", e);
}
});
}
/* create car list page with proper data */
function createCarList(apiresponse){
var data = apiresponse;
var carlist = document.getElementById("list");
for(var i = 0; i < data.length; i++){
var divitem = document.createElement("div");
divitem.className = "item";
var carId = data[i].id;
divitem.id = "item" + carId;
//https://stackoverflow.com/questions/30476721/passing-parameter-onclick-in-a-loop
divitem.onclick = (function (carId, showDetails) {
return function(){
getCarByIdWithCallback(carId, showDetails);
}
})(carId, showDetails);
var carimg = document.createElement("img");
carimg.src = "../images/img_" + data[i].id + ".jpg";
carimg.className = "carimg";
var carinfo = document.createElement("div");
carinfo.className = "carinfo";
carinfo.innerHTML = "" + data[i].name + " " + data[i].specification;
divitem.appendChild(carimg);
divitem.appendChild(carinfo);
carlist.appendChild(divitem);
}
}
/*
* -------------- Rent car functions --------------------------
*/
/* Load page and prepare form */
function initializeForm(apiResponse){
var data = apiResponse;
document.getElementById("detailName").innerHTML = "" + data.name;
document.getElementById("detailSpecification").innerHTML = "" + data.specification;
document.getElementById("detailPlace").innerHTML = "" + data.place;
document.getElementById("detailPrice").innerHTML = "" + data.price + " CHF";
document.getElementById("carId").value = "" + data.id;
var carimg = document.createElement("img");
carimg.src = "../images/img_" + data.id + ".jpg";
carimg.className = "bigcarimg";
var picture = document.getElementById("picture");
picture.appendChild(carimg);
}
/* Show success dialog */
function openSuccessMsg(){
document.getElementById("successmsg").style.display = "block";
}
/* Call endpoint and get car by id */
function getCarById(callback){
var id = $("#carId").val();
$.ajax({
type: "GET",
url: "http://localhost:8080/cars/" + id,
timeout: 600000,
success: callback,
error: function (e) {
console.log("ERROR : ", e);
}
});
}
/* Call endpoint and book car */
function rentCar(){
var carId = $("#carId").val();
var userId= $("#userId").val();
var startdate= $("#startDate").val();
var enddate= $("#endDate").val();
$.ajax({
type: "POST",
url: "http://localhost:8080/rent/"+ carId +
"?userId=" + userId + "&startdate=" + startdate +
"&enddate=" + enddate,
timeout: 600000,
success: function (data) {
document.getElementById("formerror").style.display = "none";
$("#formerror").text("");
console.log("SUCCESS : ", data);
openSuccessMsg();
},
error: function (e) {
console.log("ERROR : ", e);
console.log("Status : ", e.status);
if(e.status == "404"){
document.getElementById("formerror").style.display = "none";
console.log("ERREICHT : ", e.status);
goToOverview();
}
if(e.status == "405"){
console.log("ERREICHT : ", e.status);
$("#formerror").text("Bitte geben Sie korrekte Daten ein.");
document.getElementById("formerror").style.display = "block";
}
if(e.status == "406"){
console.log("ERREICHT : ", e.status);
$("#formerror").text("Das Auto ist an diesem Zeitpunkt bereits reserviert.");
document.getElementById("formerror").style.display = "block";
}
if(e.status == "0"){
console.log("ERREICHT : ", e.status);
$("#formerror").text("Ihr Guthaben reicht nicht aus. Kontaktieren Sie ihre Bank.");
document.getElementById("formerror").style.display = "block";
}
if(e.status == "500"){
console.log("ERREICHT : ", e.status);
$("#formerror").text("Ein Fehler ist aufgetreten. Bitte versuchen Sie es nochmal.");
document.getElementById("formerror").style.display = "block";
}
}
});
}<file_sep>/WebContent/js/servicecaller.js
function login(){
var username = $("#username").val();
var pw = $("#pw").val();
$.ajax({
type: "GET",
url: "http://localhost:8080/user/login?username=" + username + "&password=" + pw,
timeout: 600000,
success: function (data) {
$("#logindlg").text(data);
console.log("SUCCESS : ", data);
},
error: function (e) {
$("#logindlg").text(e.responseText);
console.log("ERROR : ", e);
}
});
}
function submit(){
var data = clientPost {
firstname: $("#input1").val(),
lastname: $("#input2").val()
};
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/test/url/post",
data: data,
// http://api.jquery.com/jQuery.ajax/
// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
processData: false, // prevent jQuery from automatically transforming
// the data into a query string
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
}
});
} | 1463614b3571fecb1cf55b7868af495120e95c63 | [
"JavaScript"
] | 2 | JavaScript | silva1999/m150-autovermietung_frontend | 0bf9bdbcc1e16c0ed9cc72273057b303a213cf47 | a1652902a2ee0646a8413d963bb00f81acc31d33 |
refs/heads/master | <repo_name>kronmess/Quiz-Part-2<file_sep>/Quiz part 2 no 2.py
import re
with open('staffdata.txt','r') as f:
data = f.read()
datas = f.readlines()
split_data = re.findall(r'\w+', data)
sorted_names = sorted(split_data[1::4])
def start():
print(data)
start = input("1. New Staff\n2. Delete Staff\n3. View Summary Data\n4.Save and Exit\nInput Choice:").lower()
while True:
if start == "1":
newstaff()
newstaffname()
newstaffposition()
if start == "2":
pass
if start == "3":
pass
if start == "4":
pass
elif start == "exit":
exit()
def newstaff():
text = str(input("Please input Staff ID:"))
split_data.append(text)
if text =="stop":
start()
if len(text) != 5:
return False
if input == input:
return False
if text(0) != "S":
return False
if text(1) != int:
return False
else:
start()
def newstaffname():
nameinput=(input("Please input a name:"))
split_data.append(nameinput)
if nameinput =="stop":
start()
if len(nameinput) <= 20:
return False
def newstaffposition():
posinput=(input("Please choose a position:"))
if posinput == "Staff":
return True
if posinput == "Manager":
return True
if posinput == "Officer":
return True
else:
return False
class Employee:
def __init__(self,id,name,position,salary):
self.__id = id
self.__name = name
self.__position = position
self.__salary = salary
start() | 60cfcffc5d662f2c8354846fd8635adcbcfcb952 | [
"Python"
] | 1 | Python | kronmess/Quiz-Part-2 | 6980c119a0ec8219db7619346c192ee9f90855d9 | c7f30558f28be62966cde2ff0c6cf042e0d51a21 |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
var mongoose = require('mongoose');
var mongodburl = 'mongodb://id:<EMAIL>:11788/restaurant';
var restSchema = require('./models/restaurant');
var bodyParser = require('body-parser');
app.set('view engine','ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/public'));
app.get('/',function(req,res){
res.sendFile(__dirname + '/public/index.html');
});
| 30dcf351f9cf09b02d5a427f04533d765987da57 | [
"JavaScript"
] | 1 | JavaScript | tkcjonny/project | cbdfa0ead2e78d0f51d7b7346d837863aa9ed98a | 04b4435df6106ee37b3606259a4a79b7a7ec9ebd |
refs/heads/master | <repo_name>DianeDii/gitTest<file_sep>/node_httpService1.js
var http = require('http')
var server = http.createServer();
server.on('request',function(request,response){
console.log('收到请求,来自'+request.url)
console.log('请求我的端口号来自于'+request.socket.remotePort)
console.log('请求我的IP来自于'+request.socket.remoteAddress)
var url = request.url
if (url === '/products'){
var products = [
{
name:'apple',
price: 3
},
{
name:'banana',
price: 5
},
{
name:'小傻瓜',
price: 0
}
]
//JSON转字符串JSON.parse(),JSON.stringify()
response.end(JSON.stringify(products))
} else if(url === '/login'){
response.end('hi! admin.')
}
})
server.listen(3003,function(){
console.log('server start,welcome!')
})<file_sep>/node_sendHtmlPage.js
var http = require('http')
var fs = require('fs')
var server = http.createServer()
server.on('request',function (request,response) {
var url = request.url
if (url ==='/') {
//这里我们引入fs
fs.readFile('./div-control.html',function (error,data) {
if (error) {
response.setHeader('Content-Type','text/html; charset=utf-8')
response.end('文件读取失败,请稍后重试!')
} else {
//data默认为二进制数据,可以通过。toString()转化为字符串
response.end(data)
}
})
} else {
}
})
server.listen(3000,function () {
console.log('server is running ...');
})<file_sep>/README.md
# gitTest
<<<<<<< HEAD
#设立该库的目的是熟悉Git & Gitkraken & js小模块练手
#练习项目来自http://www.fgm.cc/learn/
#本人新手,欢迎指正讨论
=======
js基础练习。
>>>>>>> 014239a756ac88468c85454e66a90b8e6d45eabf
| 4b265b6bc17a5e936ffecf6e1c13490f44e6ef81 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | DianeDii/gitTest | f30d45362ec55fba76d24116c6f1cad8d0a4d199 | a4033136eec22cfde99c38de45518d4227cccac5 |
refs/heads/master | <file_sep>import React, {
useContext,
useState,
useRef,
useEffect,
useCallback,
} from "react";
import classNames from "classnames";
import { AppContext } from "../../misc";
import { getRandomAmount } from "../../../common/utils";
import EyeContext from "./Eye.context";
import styles from "./Eye.module.scss";
import EyeLids from "./components/EyeLids";
import {
eyeLidsWidthSimple,
eyeLidsHeight,
eyeBlinkTime,
cursorFollowingTime,
} from "./Eye.utils";
const { isEyeStalled: stalledEyeClassName } = styles;
const Eye = () => {
const [isFollowingCursorMovement, setCursorFollowingMode] = useState(true);
const refCursorFollower = useRef();
const {
themeClassName,
isEyeHovered,
isEyeTripping,
setEyeHoverState,
setLastDropTriggerTime,
} = useContext(AppContext);
const eyeDimensions = {
width: `${eyeLidsWidthSimple}px`,
height: `${eyeLidsHeight}px`,
};
const setEyeBallPosition = useCallback(function (event = {}) {
const { innerWidth, innerHeight } = window;
const { clientX = innerWidth / 2, clientY = innerHeight / 2 } = event;
const { current: cursorFollowerElement } = refCursorFollower;
const percentPositionX = (clientX * 100) / innerWidth;
const percentPositionY = (clientY * 100) / innerHeight;
cursorFollowerElement.style.top = `${percentPositionY}%`;
cursorFollowerElement.style.left = `${percentPositionX}%`;
});
useEffect(() => {
if (!isEyeTripping) {
const { min, max } = cursorFollowingTime[
isFollowingCursorMovement ? "active" : "passive"
];
const { current: cursorFollowerElement } = refCursorFollower;
setTimeout(() => {
setCursorFollowingMode(!isFollowingCursorMovement);
cursorFollowerElement.classList[
isFollowingCursorMovement ? "add" : "remove"
](stalledEyeClassName);
}, getRandomAmount(min, max));
} else {
setCursorFollowingMode(false);
setEyeBallPosition();
}
}, [isFollowingCursorMovement, isEyeTripping]);
useEffect(() => {
setCursorFollowingMode(!isEyeTripping);
}, [isEyeTripping]);
useEffect(() => {
const eventName = "mousemove";
const removeCursorTrackerEvent = () =>
document.removeEventListener(eventName, setEyeBallPosition);
if (isFollowingCursorMovement) {
document.addEventListener(eventName, setEyeBallPosition);
} else {
removeCursorTrackerEvent();
setEyeBallPosition();
}
return () => removeCursorTrackerEvent();
}, [isFollowingCursorMovement]);
return (
<EyeContext.Provider
value={{
eyeLidsClass: styles.eyeLids,
crossShapedClass: styles.eyeLidsCross,
simpleShapedClass: styles.eyeLidsSimple,
}}
>
<button
className={classNames(
styles.eyeWrap,
styles[themeClassName],
isEyeTripping && styles.isEyeTripping,
isEyeHovered && styles.isEyeHovered
)}
onMouseOver={() => setEyeHoverState(true)}
onMouseLeave={() => setEyeHoverState(false)}
onClick={() => setLastDropTriggerTime(new Date())}
>
<div
className={styles.eyeClip}
style={{ width: `${eyeLidsWidthSimple}px` }}
>
<div className={styles.eye} style={eyeDimensions}>
<div className={styles.eyeBallClip}>
<div className={styles.eyeBallBoundary}>
{/* The main eye ball */}
<div
ref={refCursorFollower}
className={classNames(
styles.eyeBall,
styles.eyeBallCursorFollower
)}
>
{/* The outermost layer of the trippy eyes */}
<div className={classNames(styles.eye, styles.eyeInner)}>
{/* The middle eye ball */}
<div className={styles.eyeBall}>
<div className={styles.eye} style={eyeDimensions}>
{/* The innermost eye ball */}
<div
className={classNames(
styles.eyeBall,
styles.eyeBallInnermost
)}
></div>
{/* The innermost eye's blinking lids */}
<EyeLids shouldBlinkAutomatically />
</div>
{/* The inner part of the middle inner eye's blinking horizontal lids */}
<EyeLids animationDelay={eyeBlinkTime} />
</div>
{/* The middle inner eye's non-blinking vertical lids */}
<EyeLids shouldNotBlinkAtAll />
{/* The outer part of the middle inner eye's blinking */}
{/* horizontal lids with a cut for the vertical eye */}
<EyeLids isCrossShape animationDelay={eyeBlinkTime} />
</div>
</div>
</div>
</div>
{/* The main eye's blinking lids */}
<EyeLids
shouldBlinkOnClick
shouldBlinkAutomatically={!isEyeTripping}
shouldClose={isEyeHovered}
/>
</div>
</div>
</button>
</EyeContext.Provider>
);
};
export default Eye;
<file_sep>import React, { useContext } from "react";
import classNames from "classnames";
import { AppContext } from "../../misc";
import { CloudLeft, CloudRight, TearDrop, Star, Eye } from "../../shapes";
import styles from "./Main.module.scss";
const Main = () => {
const { themeClassName, isEyeTripping } = useContext(AppContext);
return (
<main className={styles.main}>
<div
className={classNames(
styles.canvas,
styles[themeClassName],
isEyeTripping && styles.isEyeTripping
)}
>
<CloudLeft />
<CloudRight />
<TearDrop />
<div className={styles.layerPattern} />
<Star />
<Eye />
</div>
</main>
);
};
export default Main;
<file_sep>import React, { useContext } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faStar } from "@fortawesome/free-solid-svg-icons";
import { AppContext } from "../../misc";
import styles from "./LinkUrl.module.scss";
const LinkUrl = ({ className, label, href, isEnhanced }) => {
const { themeClassName } = useContext(AppContext);
return (
<a
className={classNames(styles.linkUrl, styles[themeClassName], className)}
target="_blank"
href={href}
rel="noreferrer"
>
{label}
{isEnhanced && (
<FontAwesomeIcon icon={faStar} className={styles.linkEnhancerStar} />
)}
</a>
);
};
LinkUrl.propTypes = {
className: PropTypes.string,
label: PropTypes.string.isRequired,
href: PropTypes.string.isRequired,
isEnhanced: PropTypes.bool,
};
export default LinkUrl;
<file_sep>import React, { useContext } from "react";
import classNames from "classnames";
import { AppContext } from "../../misc";
import Shape from "./BandLogo.shape.svg";
import styles from "./BandLogo.module.scss";
const BandLogo = () => {
const { switchTheme, themeClassName } = useContext(AppContext);
return (
<button
className={classNames(styles.bandLogo, styles[themeClassName])}
onClick={switchTheme}
>
<Shape />
</button>
);
};
export default BandLogo;
<file_sep>export const eyeLidsWidthSimple = 493;
export const eyeLidsWidthCross = 899;
export const eyeLidsHeight = 671;
export const eyeBlinkTime = 250;
export const cursorFollowingTime = {
active: {
min: 4500,
max: 11500,
},
passive: {
min: 1000,
max: 3000,
},
};
export const coordinatesSimpleOpen = [
"M0,0V671H493V0ZM433.08,385C318.54,493.51,178.49,490.22,60,385l-58-50",
"58.05-50c110.63-105.1,251.6-108.39,373.08,0l58.05,50Z",
].join(",");
export const coordinatesSimpleClosed = [
"M0,0V671H493V0ZM466,328c-122-24-287-25-425-3L1.91,335.5,60,335.31c110.63-.41",
"251.6-.42,373.08,0l58,.19Z",
].join(",");
export const coordinatesCrossOpen = [
"M0,0V671H899V0ZM636,385.48c-26.15,24.84-54,44-82.87,57.33-13.11",
"27.1-31,53.67-53.74,79.23l-49.95,58.05-50-58.05C374.74,496,355.63",
"468.2,342.3,439.4c-27-13-53.61-31-79.34-53.92l-58-50,58-50c26.38-25",
"54.12-44,82.64-57.27,13-27,31-53.61,53.92-79.34l50-58.05L499.43,149c25.05",
"26.45,44.13,54.27,57.38,82.87,27.1,13.11,53.67,31,79.23,53.74l58.05,50Z",
].join(",");
export const coordinatesCrossClosed = [
"M0,0V671H899V0ZM643,336c-24-3-36,0-64,0-1,90-56.88,160.48-79.57,186l-49.95",
"58.05-50-58.05C374.74,496,320,434,319,338c0-6-15-11-56-2l-58.09-.47L263",
"336c44,0,56,11,56-1,3-97,57.56-160.31,80.52-186l50-58.05L499.43,149C524.48",
"175.41,581,243,579,336c15-1,53,3.43,59,3l56.09-3.47Z",
].join(",");
<file_sep>import React, { useState, useEffect, useCallback, useContext } from "react";
import classNames from "classnames";
import PropTypes from "prop-types";
import { AppContext } from "../../../misc";
import { getRandomAmount } from "../../../../common/utils";
import { eyeBlinkTime } from "../Eye.utils";
import EyeContext from "../Eye.context";
import {
eyeLidsWidthSimple,
eyeLidsWidthCross,
eyeLidsHeight,
coordinatesSimpleOpen,
coordinatesSimpleClosed,
coordinatesCrossOpen,
coordinatesCrossClosed,
} from "../Eye.utils";
import {
SvgWrapper,
SvgPathAnimation,
SvgAnimationKeyframe,
} from "../../../misc";
const clickEventName = "click";
const blinkTriggers = {
none: "none",
click: clickEventName,
auto: "auto",
};
const LidsShape = (props) => {
const {
className,
isCrossShape,
shouldClose = false,
shouldBlinkAutomatically = false,
shouldBlinkOnClick = false,
shouldNotBlinkAtAll = false,
minWaitingBeforeBlinking = eyeBlinkTime,
maxWaitingBeforeBlinking = 9000,
animationDelay,
animationRepeatCount = "0",
animationFillMode = "freeze",
keyframes = [
new SvgAnimationKeyframe("start", 0),
new SvgAnimationKeyframe("end", 1),
],
} = props;
const [isOpen, setOpenState] = useState(true);
const [isAutoBlinkingAllowed, setAutoBlinkingPermission] = useState(
shouldBlinkAutomatically && !shouldClose
);
const [blinkingTriggeredBy, setBlinkingTriggeredBy] = useState(
blinkTriggers.none
);
const [lastBlinkingWaitTime, setLastBlinkingWaitTime] = useState(0);
const [timerIds, setTimerIds] = useState([]);
const { isEyeTripping } = useContext(AppContext);
const triggerBlinking = (triggeredBy) => setBlinkingTriggeredBy(triggeredBy);
const clearAllTimers = () =>
timerIds.forEach((timerId) => clearTimeout(timerId));
const handleDocumentClick = useCallback(() =>
triggerBlinking(blinkTriggers.click)
);
const shapeWidth = isCrossShape ? eyeLidsWidthCross : eyeLidsWidthSimple;
const coordinatesClosed = isCrossShape
? coordinatesCrossClosed
: coordinatesSimpleClosed;
const coordinatesOpen = isCrossShape
? coordinatesCrossOpen
: coordinatesSimpleOpen;
const coordinatesStart = isOpen ? coordinatesClosed : coordinatesOpen;
const coordinatesEnd = isOpen ? coordinatesOpen : coordinatesClosed;
const blink = function () {
if (!shouldNotBlinkAtAll) {
setOpenState(false);
clearAllTimers();
setTimerIds([
...timerIds,
setTimeout(() => {
setOpenState(!shouldClose);
setBlinkingTriggeredBy(blinkTriggers.none);
}, eyeBlinkTime),
]);
}
};
// Make the eye blink automatically:
useEffect(() => {
if (
isOpen &&
isAutoBlinkingAllowed &&
blinkingTriggeredBy !== blinkTriggers.click
) {
const randomBlinkWaitingTime = getRandomAmount(
minWaitingBeforeBlinking,
maxWaitingBeforeBlinking
);
const blinkSpeedDice = [
minWaitingBeforeBlinking,
randomBlinkWaitingTime,
randomBlinkWaitingTime,
randomBlinkWaitingTime,
];
const {
[Math.round(
getRandomAmount(0, blinkSpeedDice.length - 1)
)]: waitingTimeBeforeBlinking,
} = blinkSpeedDice.filter(
(diceValue) => diceValue !== lastBlinkingWaitTime
);
setTimerIds([
...timerIds,
setTimeout(
() => triggerBlinking(blinkTriggers.auto),
waitingTimeBeforeBlinking
),
]);
setLastBlinkingWaitTime(randomBlinkWaitingTime);
}
}, [isOpen, isAutoBlinkingAllowed]);
// Update blinking permission:
useEffect(() => {
setAutoBlinkingPermission(shouldBlinkAutomatically && !shouldClose);
setOpenState(!shouldClose);
}, [shouldBlinkAutomatically, shouldClose]);
// Check for triggered blinking:
useEffect(() => {
if (
blinkingTriggeredBy !== blinkTriggers.none &&
isAutoBlinkingAllowed &&
!shouldClose
) {
blink();
}
if (shouldClose) {
clearAllTimers();
setOpenState(false);
}
}, [blinkingTriggeredBy, isAutoBlinkingAllowed, shouldClose]);
// Handle tripping eye state change:
useEffect(() => {
blink();
}, [isEyeTripping]);
// Set document click handler:
useEffect(() => {
const removeDocumentClickHandler = () =>
document.removeEventListener(clickEventName, handleDocumentClick);
if (shouldBlinkOnClick && blinkingTriggeredBy === blinkTriggers.none) {
document.addEventListener(clickEventName, handleDocumentClick);
} else {
removeDocumentClickHandler();
}
return () => removeDocumentClickHandler();
}, [shouldBlinkOnClick, blinkingTriggeredBy]);
return (
<EyeContext.Consumer>
{({ eyeLidsClass, simpleShapedClass, crossShapedClass }) => (
<SvgWrapper
key={isOpen}
className={classNames(
className,
eyeLidsClass,
isCrossShape ? crossShapedClass : simpleShapedClass
)}
width={shapeWidth}
height={eyeLidsHeight}
viewBox={`0 0 ${shapeWidth} ${eyeLidsHeight}`}
>
<path d={coordinatesStart}>
<SvgPathAnimation
duration={eyeBlinkTime}
delay={animationDelay}
coordinatesStart={coordinatesStart}
coordinatesEnd={coordinatesEnd}
keyframes={keyframes}
repeatCount={animationRepeatCount}
fillMode={animationFillMode}
/>
</path>
</SvgWrapper>
)}
</EyeContext.Consumer>
);
};
LidsShape.propTypes = {
className: PropTypes.string,
isCrossShape: PropTypes.bool,
shouldClose: PropTypes.bool,
shouldBlinkAutomatically: PropTypes.bool,
shouldBlinkOnClick: PropTypes.bool,
shouldNotBlinkAtAll: PropTypes.bool,
animationRepeatCount: PropTypes.number,
animationDelay: PropTypes.number,
animationFillMode: PropTypes.string,
minWaitingBeforeBlinking: PropTypes.number,
maxWaitingBeforeBlinking: PropTypes.number,
handleTrippingEyeStateChange: PropTypes.func,
keyframes: PropTypes.arrayOf(PropTypes.instanceOf(SvgAnimationKeyframe)),
};
export default LidsShape;
<file_sep>import React, { useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { AppContext } from "../../misc";
import styles from "./Dropdown.module.scss";
import { clickEvents } from "../../../common/globalVariables";
const closerEvents = [...clickEvents, "keyup"];
const Dropdown = ({ openerButtonText, children }) => {
const [dropdownOpenState, setDropdownOpenState] = useState(false);
const { setEyeTrippingState, themeClassName } = useContext(AppContext);
const handleDropdownClosing = ({ key, type, target }) => {
const isEscapeButtonKeyup = type === "keyup" && key === "Escape";
if (clickEvents.includes(type) || isEscapeButtonKeyup) {
setDropdownOpenState(false);
closerEvents.forEach((eventName) =>
document.removeEventListener(eventName, handleDropdownClosing)
);
if (
!target.classList.contains(styles.dropdownContainer) ||
isEscapeButtonKeyup
) {
setEyeTrippingState(false);
}
}
};
useEffect(() => {
if (dropdownOpenState) {
closerEvents.forEach((eventName) =>
document.addEventListener(eventName, handleDropdownClosing)
);
setEyeTrippingState(true);
}
return function cleanUp() {
closerEvents.forEach((eventName) =>
document.removeEventListener(eventName, handleDropdownClosing)
);
};
}, [dropdownOpenState]);
return (
<div
className={classNames(
styles.dropdownContainer,
styles[themeClassName],
dropdownOpenState && styles.dropdownStateOpen
)}
>
<button
className={styles.dropdownOpener}
onClick={() => setDropdownOpenState(!dropdownOpenState)}
>
{openerButtonText}
</button>
<div className={styles.dropdown}>{children}</div>
</div>
);
};
Dropdown.propTypes = {
openerButtonText: PropTypes.string.isRequired,
children: PropTypes.element,
};
export default Dropdown;
<file_sep>export const clickEvents = ["click", "touchstart"];
<file_sep>import React, { useContext } from "react";
import classNames from "classnames";
import { AppContext } from "../../misc";
import { LinkUrl, Dropdown, SiteLogo } from "../../elements";
import styles from "./Header.module.scss";
import { navMenuItems } from "./Header.utils";
const Header = () => {
const { themeClassName } = useContext(AppContext);
return (
<header className={classNames(styles.Header, styles[themeClassName])}>
<SiteLogo />
<nav>
<ul className={styles.navList}>
{Object.entries(navMenuItems).map(
({ 0: menuItemGroup, 1: menuDropdownContent }) => (
<li key={menuItemGroup}>
<Dropdown openerButtonText={menuItemGroup}>
{Array.isArray(menuDropdownContent) ? (
<ul>
{menuDropdownContent.map((dropdownLinkData) => {
const { label } = dropdownLinkData;
return (
<li key={label}>
<LinkUrl
{...dropdownLinkData}
className={styles.linkUrl}
/>
</li>
);
})}
</ul>
) : (
<dl>
{Object.entries(menuDropdownContent).map(
({ 0: dropdownLinkTerm, 1: dropdownLink }) => (
<React.Fragment key={dropdownLinkTerm}>
<dt>{dropdownLinkTerm}</dt>
<dd>{dropdownLink}</dd>
</React.Fragment>
)
)}
</dl>
)}
</Dropdown>
</li>
)
)}
</ul>
</nav>
</header>
);
};
export default Header;
<file_sep>import React from "react";
import styles from "./Footer.module.scss";
import { LinkUrl } from "../../elements";
const Footer = () => (
<footer className={styles.Footer}>
<small>
<p>
A website made by{" "}
<LinkUrl
label="this guy"
href="https://dk.linkedin.com/in/norbert-biro"
/>{" "}
based on <LinkUrl label="Saba Anwar" href="https://www.sabaanwar.fr" />
's Gazsiafter animation theme design
</p>
<p>
Copyright © <span className="current-year"></span> Paperdeer. All
Rights Reserved
</p>
</small>
</footer>
);
export default Footer;
<file_sep>export const getRandomAmount = function (min, max) {
return Math.random() * (max - min) + min;
};
export const getShuffledArray = function (inputArray) {
// https://stackoverflow.com/a/2450976/5125537
const outputArray = [...inputArray];
let { length: counter } = outputArray;
let temp;
let index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter -= 1;
temp = outputArray[counter];
outputArray[counter] = outputArray[index];
outputArray[index] = temp;
}
return outputArray;
};
<file_sep>import React from "react";
const EyeContext = React.createContext();
export default EyeContext;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import AnimationKeyframe from "./_SvgAnimationKeyframe";
// IMPORTANT! This component should ONLY be used as a child of an <path> element in an SVG wrapper
const SvgPathAnimation = (props) => {
const {
fillMode,
duration,
delay = 0,
coordinatesStart,
coordinatesEnd,
repeatCount = "indefinite",
isEaseInOut = true,
restart = "whenNotActive",
keyframes = [
new AnimationKeyframe("start", 0),
new AnimationKeyframe("end", 0.5),
new AnimationKeyframe("start", 1),
],
} = props;
const keyframeCoordinates = {
start: coordinatesStart,
end: coordinatesEnd,
};
const finalKeyframeOrder = keyframes.map(
({ keyframeName }) => keyframeCoordinates[keyframeName]
);
const attributes = {
attributeName: "d",
dur: `${duration}ms`,
repeatCount,
restart,
from: coordinatesStart,
to: coordinatesEnd,
begin: `${delay}ms`,
values: finalKeyframeOrder.join(";"),
keyTimes: keyframes.map(({ keyframeTime }) => keyframeTime).join("; "),
fill: fillMode,
};
if (isEaseInOut) {
const cubicBezierValues = "0.25, 0.1, 0.25, 1";
attributes.calcMode = "spline";
attributes.keySplines = new Array(finalKeyframeOrder.length - 1)
.fill(cubicBezierValues)
.join(";");
}
return <animate {...attributes} />;
};
SvgPathAnimation.propTypes = {
duration: PropTypes.number.isRequired,
delay: PropTypes.number,
coordinatesStart: PropTypes.string.isRequired,
coordinatesEnd: PropTypes.string.isRequired,
keyframes: PropTypes.arrayOf(PropTypes.instanceOf(AnimationKeyframe)),
repeatCount: PropTypes.string,
restart: PropTypes.oneOf(["always", "whenNotActive", "never"]),
fillMode: PropTypes.oneOf(["freeze", "remove"]),
isEaseInOut: PropTypes.bool,
};
export default SvgPathAnimation;
<file_sep>import React from "react";
import PropTypes from "prop-types";
const SvgWrapper = ({ width, height, className, children }) => (
<svg
className={className}
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
width={width}
height={height}
viewBox={`0 0 ${width} ${height}`}
>
{children}
</svg>
);
SvgWrapper.propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
className: PropTypes.string,
children: PropTypes.element,
};
export default SvgWrapper;
<file_sep>export { default as LinkUrl } from "./LinkUrl/LinkUrl";
export { default as LinkEmail } from "./LinkEmail/LinkEmail";
export { default as Dropdown } from "./Dropdown/Dropdown";
export { default as SiteLogo } from "./BandLogo/BandLogo";
<file_sep>import React from "react";
import Home from "./Home";
const Pages = () => <Home />;
export default Pages;
<file_sep>import React, { useContext } from "react";
import classNames from "classnames";
import { SvgPathAnimation, SvgWrapper, AppContext } from "../../misc";
import {
width,
height,
coordinatesStart,
coordinatesEnd,
} from "./CloudLeft.utils";
import styles from "./CloudLeft.module.scss";
const CloudLeft = () => {
const { themeClassName, isEyeTripping } = useContext(AppContext);
return (
<div
className={classNames(
styles.cloudLeft,
styles[themeClassName],
isEyeTripping && styles.isEyeTripping
)}
style={{ width: `${width}px`, height: `${height}px` }}
>
<SvgWrapper
width={width}
height={height}
className={styles.cloudLeftShape}
>
<path d={coordinatesStart}>
<SvgPathAnimation
duration={7000}
coordinatesStart={coordinatesStart}
coordinatesEnd={coordinatesEnd}
/>
</path>
</SvgWrapper>
</div>
);
};
export default CloudLeft;
<file_sep>import React, { useContext } from "react";
import classNames from "classnames";
import { SvgPathAnimation, SvgWrapper, AppContext } from "../../misc";
import {
width,
height,
coordinatesStart,
coordinatesEnd,
} from "./CloudRight.utils";
import styles from "./CloudRight.module.scss";
const CloudRight = () => {
const { themeClassName, isEyeTripping } = useContext(AppContext);
return (
<div
className={classNames(
styles.cloudRight,
styles[themeClassName],
isEyeTripping && styles.isEyeTripping
)}
style={{ width: `${width}px`, height: `${height}px` }}
>
<SvgWrapper
width={width}
height={height}
className={styles.cloudRightShape}
>
<path d={coordinatesStart}>
<SvgPathAnimation
duration={3500}
coordinatesStart={coordinatesStart}
coordinatesEnd={coordinatesEnd}
/>
</path>
</SvgWrapper>
</div>
);
};
export default CloudRight;
| 0712bc137008e94d0ebaadac1abd707b05de9885 | [
"JavaScript"
] | 18 | JavaScript | norbertgogibiro/public-demo | 824009b75bf80c80e2116bdc103ba1c1fb97b53f | cab760f8292e4dd72d77514bfabb67b96ec1bd41 |
refs/heads/master | <file_sep>/* README
* - Use Arduino Uno to view Serial messages for debugging
* - Use the board manager to ad adafruit if they don't exist
* - If Adafruit not available in Board Manager, add URL to preferences on additional board locations
* - Arduino is C++. Easier to search for C++ solutions
* Trinket:
* Board - Trinket 5V/16Hz (USB)
* Programmer - USBTinyISP
*
* Links:
* https://github.com/FastLED/FastLED/wiki/Pixel-reference
*/
#include <FastLED.h>
#include "StudioLightingPattern.h"
#include <IRremote.h>
#define PIN_LEDS 10
#define PIN_REMOTE 6
#define LEDS 65
CRGB leds[LEDS];
StudioLightingPattern lighting = StudioLightingPattern(LEDS, leds);
IRrecv irrecv(PIN_REMOTE);
decode_results results;
bool LightsActive = true;
void setup() {
Serial.begin(9600);
Serial.println("SETUP");
irrecv.enableIRIn(); // Start the receiver
FastLED.addLeds<NEOPIXEL, PIN_LEDS>(leds, LEDS);
FastLED.show();
lighting.Init(NORMAL, 255);
test();
}
void loop() {
if (irrecv.decode(&results))
{
Serial.println(results.value, HEX);
remoteCommand();
irrecv.resume(); // Receive the next value
}
if (LightsActive) {
lighting.Update();
}
}
void remoteCommand() {
if (results.value == 0xC || results.value == 0x80C) { // -PWR-
Serial.println("Power");
LightsActive = !LightsActive;
if(!LightsActive) { lighting.ClearLights(); }
if (LightsActive) { Serial.println("ON"); } else { Serial.println("OFF"); }
}
else if (results.value == 0xD || results.value == 0x80D) { // -Mute/Unmute- (only unlocks because choosing a pattern will lock it)
Serial.println("Rotate Pattern");
lighting.UnlockPattern();
}
else if (results.value == 0x20 || results.value == 0x820) { // -CH+-
Serial.println("NextPattern");
lighting.NextPattern();
}
else if (results.value == 0x21 || results.value == 0x821) { // -CH--
Serial.println("PreviousPattern");
lighting.PreviousPattern();
}
else if (results.value == 0x1 || results.value == 0x801) { // -1-
Serial.println("Rainbow");
lighting.LockPattern();
lighting.SetRainbow();
}
else if (results.value == 0x2 || results.value == 0x802) { // -2-
Serial.println("Color Wipe");
lighting.LockPattern();
lighting.SetColorWipe();
}
else if (results.value == 0x3 || results.value == 0x803) { // -3-
Serial.println("Theater Chase");
lighting.LockPattern();
lighting.SetTheaterChase();
}
else if (results.value == 0x4 || results.value == 0x804) { // -4-
Serial.println("Slow Fade");
lighting.LockPattern();
lighting.SetSlowFade();
}
else if (results.value == 0x5 || results.value == 0x805) { // -5-
Serial.println("Wave");
lighting.LockPattern();
lighting.SetWave();
}
else if (results.value == 0x6 || results.value == 0x806) { // -6-
// Serial.println("Clap");
lighting.LockPattern();
// lighting.SetClap();
}
else if (results.value == 0x7 || results.value == 0x807) { // -7-
Serial.println("Party");
lighting.LockPattern();
lighting.SetParty();
}
}
void test() {
// Serial.println("Entering test mode");
// Test Patterns
lighting.LockPattern();
// Test methods
// lighting.SetRainbow();
// lighting.SetColorWipe();
// lighting.SetTheaterChase();
// lighting.SetWave();
// lighting.SetParty();
lighting.SetSlowFade();
}
<file_sep>#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
enum Themes { NORMAL, HALLOWEEN, CHRISTMAS };
#define COLUMNS 5
#define CHASE_SECTION_SIZE 5
#define COLOR_INTERVAL 40
#define LAG_OFFSET 2
#define PATTERN_COUNT 7
#define WAVE_FADE_SIZE 15 // Size of the fade trailWaveEnabled
const TProgmemPalette16 themePalette_p PROGMEM;
class StudioLightingPattern
{
public:
// Constructor - calls base-class constructor to initialize strip
StudioLightingPattern(uint16_t pixels, CRGB* ledAlloc)
{
TotalSteps = pixels;
TotalLeds = pixels;
leds = ledAlloc;
}
void Init(Themes theme, int brightness = 255){
Serial.println("INIT");
CalculateIntervals();
InitTheme(theme);
delay(500);
ActivePattern = Patterns[iPattern];
ActiveBrightness = brightness;
FastLED.setBrightness(ActiveBrightness);
currentPalette = themePalette;
delay(500);
changed_time = millis();
colored_time = millis();
lastUpdate = millis();
delay(500);
SetColorWipe(); // Starting pattern
Update();
}
// Update the pattern
void Update(){
if (!PatternLocked) { ChangePattern(false); }
if((millis() - lastUpdate) > UpdateInterval){ // time to update
lastUpdate = millis();
if (ActivePattern == "RAINBOW_CYCLE") {
RainbowCycleUpdate();
} else if (ActivePattern == "COLOR_WIPE") {
ColorWipeUpdate();
} else if (ActivePattern == "WAVE") {
WaveUpdate();
} else if (ActivePattern == "THEATER_CHASE") {
TheaterChaseUpdate();
} else if (ActivePattern == "PARTY") {
PartyUpdate();
} else if (ActivePattern == "SLOW_FADE") {
SlowFadeUpdate();
} else {
// do nothing
}
}
}
void ClearLights() {
for (int i=0; i<TotalLeds; i++) {
SetPixel(i, 0);
}
FastLED.show();
}
void NextPattern() {
ChangePattern(true);
}
void PreviousPattern() {
GoBackPattern = true;
ChangePattern(true);
GoBackPattern = false;
}
void SetBPM(int tempo) {
BPM = tempo;
CalculateIntervals();
}
//**************TEST METHODS****************//
void LockPattern() {
PatternLocked = true;
}
void UnlockPattern() {
PatternLocked = false;
}
void SetRainbow() {
Serial.println("Set Rainbow");
ActivePattern = "RAINBOW_CYCLE";
iPattern = 0;
RainbowCycle();
}
void SetColorWipe() {
Serial.println("Set Colorwipe");
ActivePattern = "COLOR_WIPE";
iPattern = 1;
ColorWipe();
}
void SetTheaterChase() {
Serial.println("Set Theater Chase");
ActivePattern = "THEATER_CHASE";
iPattern = 2;
TheaterChase();
}
void SetWave() {
Serial.println("Set Wave");
ActivePattern = "WAVE";
iPattern = 3;
Wave();
}
void SetParty() {
Serial.println("Set Party");
ActivePattern = "PARTY";
iPattern = 4;
Party();
}
void SetSlowFade() {
Serial.println("Set Slow Fade");
ActivePattern = "SLOW_FADE";
iPattern = 5;
SlowFade();
}
private:
//***************VARIABLES***************//
// Settings
String Patterns[PATTERN_COUNT] = { "RAINBOW_CYCLE", "COLOR_WIPE", "THEATER_CHASE", "WAVE", "PARTY", "SLOW_FADE" };
String ActivePattern;
Themes ActiveTheme;
CRGB *leds;
uint16_t ActiveBrightness;
uint16_t TotalSteps = 0; // total number of steps in the pattern
uint16_t TotalLeds = 0;
uint8_t TotalRotations = 1;
// FastLED settings
CRGBPalette16 currentPalette;
CRGBPalette16 themePalette;
TBlendType currentBlending;
// Bool rules
bool PatternLocked = false;
bool GoingForward = true;
bool GoBackPattern = false;
// Active Patterns
bool TheaterChaseEnabled = true;
bool RainbowCycleEnabled = true;
bool ColorWipeEnabled = true;
bool WaveEnabled = true;
bool PartyEnabled = true;
bool SlowFadeEnabled = true;
// Indices
uint16_t Index = 0;
int iPattern = 0;
int iColor = 0; // Index for the current cycle color
int iRotation = 0; // Index for the current rotation of the complete cycle
// Pattern Intervals
// These are overridden when the BPM is changed
double RainbowInterval = 5;
double WipeInterval = 50;
double ChaseInterval = 50;
double WaveInterval = 50;
double PartyInterval = 50;
double SlowFadeInterval = 50;
// Timing
int BPM = 128;
int UpdateInterval = 5; // milliseconds between updates
int PatternInterval = 30; // Seconds before changing the pattern
unsigned long lastUpdate; // last update of position
unsigned long this_time = millis();
unsigned long changed_time = this_time - (PatternInterval * 1000); // Set to init right away
unsigned long colored_time = this_time;
//***************UTILITY METHODS***************//
// Increment the Index and reset at the end
void Increment(){
// Serial.println("Increment: " + (String) Index);
if (GoingForward){
Index++;
if (Index == TotalSteps){
Index = TotalSteps - 1;
PatternComplete(); // call the comlpetion callback
}
}
else { // reverse
Index--;
if (Index == 0){
PatternComplete(); // call the comlpetion callback
}
}
}
void PatternComplete()
{
if (iRotation + 1 < TotalRotations){
iRotation++;
if (GoingForward) { Index = 0; } else { Index = TotalSteps; }
} else {
iRotation = 0;
// Serial.println("PatternComplete");
if (ActivePattern == "COLOR_WIPE") {
Reverse();
NextColor();
} else if (ActivePattern == "THEATER_CHASE"
|| ActivePattern == "WAVE") {
NextColor();
Index = 0;
} else {
Index = 0; // Start Over
}
}
}
// Reverse direction of the pattern
void Reverse(){
// Serial.println("Reversing");
GoingForward = !GoingForward;
}
// set intervals based on BPM
void CalculateIntervals() {
Serial.println("Calculating Intervals");
RainbowInterval = (((BPM * 60) / TotalLeds) / 4) - LAG_OFFSET;
WipeInterval = (((BPM * 60) / TotalLeds) / 4) - LAG_OFFSET; //(4 beats)
ChaseInterval = ((BPM * 60) / TotalLeds) - LAG_OFFSET;
WaveInterval = (((BPM * 60) / TotalLeds) / 4) - LAG_OFFSET; //(4 beats)
PartyInterval = ((BPM * 60) / TotalLeds) - LAG_OFFSET;
SlowFadeInterval = ((BPM * 60) / TotalLeds) - LAG_OFFSET;
}
//***************COLOR METHODS***************//
void SetPixel(int pixel) {
leds[pixel] = ColorFromPalette(currentPalette, iColor, ActiveBrightness, currentBlending);
}
void SetPixel(int pixel, int brightness) {
leds[pixel] = ColorFromPalette(currentPalette, iColor, brightness, currentBlending);
}
void NextColor() {
iColor += COLOR_INTERVAL;
}
void NextColor(int interval) {
iColor += interval;
}
//***************THEME UTILITY METHODS***************//
// Set the properties and colors based on the theme
void InitTheme(Themes theme){
ActiveTheme = theme;
if (ActiveTheme == NORMAL){
PatternInterval = 30;
themePalette = PartyColors_p;
}
if (ActiveTheme == HALLOWEEN) {
PatternInterval = 30;
const TProgmemPalette16 themePalette_p PROGMEM =
{
CRGB::Purple,
CRGB::Orange,
CRGB::Red,
CRGB::White,
CRGB::Purple,
CRGB::Green
};
themePalette = themePalette_p;
// deactivate undesired modes
RainbowCycleEnabled = false;
}
if (ActiveTheme == CHRISTMAS) {
PatternInterval = 30;
const TProgmemPalette16 themePalette_p PROGMEM =
{
CRGB::Red,
CRGB::Green,
CRGB::White,
CRGB::Gold,
CRGB::Red,
CRGB::Green
};
themePalette = themePalette_p;
// deactivate undesired modes
RainbowCycleEnabled = false;
}
}
//***************PATTERN UTILITY METHODS***************//
void ChangePattern(bool force) {
this_time = millis();
if((this_time - changed_time) > (PatternInterval * 1000) || force) {
GoingForward = true;
currentPalette = themePalette;
changed_time = millis();
SetNextPatternIndex();
ActivePattern = Patterns[iPattern];
Serial.println(ActivePattern);
if (ActivePattern == "RAINBOW_CYCLE") {
RainbowCycle();
} else if (ActivePattern == "COLOR_WIPE") {
ColorWipe();
} else if (ActivePattern == "WAVE") {
Wave();
} else if (ActivePattern == "THEATER_CHASE") {
TheaterChase();
} else if (ActivePattern == "PARTY") {
Party();
} else if (ActivePattern == "SLOW_FADE") {
SlowFade();
} else {
ActivePattern = "RAINBOW_CYCLE";
iPattern = 0;
RainbowCycle();
}
}
}
void SetNextPatternIndex() {
Serial.println(PATTERN_COUNT);
if (GoBackPattern) {
if (iPattern == 0) {
iPattern = (PATTERN_COUNT - 1);
}
else {
iPattern--;
}
}
else {
if (iPattern == (PATTERN_COUNT - 1)) {
iPattern = (int) 0;
}
else { iPattern = iPattern + 1; }
}
Serial.println((String)iPattern);
if (!IsEnabledPattern(Patterns[iPattern])){
SetNextPatternIndex();
}
}
bool IsEnabledPattern(String pattern) {
if (pattern == "RAINBOW_CYCLE") {
return RainbowCycleEnabled;
} else if (pattern == "COLOR_WIPE") {
return ColorWipeEnabled;
} else if (pattern == "WAVE") {
return WaveEnabled;
} else if (pattern == "THEATER_CHASE") {
return TheaterChaseEnabled;
} else if (pattern == "PARTY") {
return PartyEnabled;
} else if (pattern == "SLOW_FADE") {
return SlowFadeEnabled;
} else {
return true;
}
}
//***************PATTERN METHODS***************//
void RainbowCycle(){
Serial.println("Begin RAINBOW_CYCLE");
currentPalette = RainbowColors_p;
currentBlending = LINEARBLEND;
UpdateInterval = RainbowInterval;
TotalRotations = 1;
TotalSteps = 255;
Index = 0;
}
// Update the Rainbow Cycle Pattern
void RainbowCycleUpdate(){
static int rainbowIndex = 1;
static int rainbowColorInterval = 255 / TotalLeds;
for(int i=0; i<TotalLeds; i++){
leds[i] = ColorFromPalette(currentPalette, rainbowIndex, ActiveBrightness, currentBlending);
rainbowIndex += rainbowColorInterval;
}
FastLED.show();
}
// Initialize for a ColorWipe
void ColorWipe(){
Serial.println("Begin COLOR_WIPE");
currentPalette = themePalette;
currentBlending = NOBLEND;
UpdateInterval = WipeInterval;
TotalRotations = 1;
TotalSteps = TotalLeds;
Index = 0;
}
// Update the Color Wipe Pattern
void ColorWipeUpdate(){
SetPixel(Index);
FastLED.show();
Increment();
}
// Initialize for a Theater Chase
void TheaterChase(){
Serial.println("Begin THEATER_CHASE");
currentBlending = NOBLEND;
currentPalette = themePalette;
UpdateInterval = ChaseInterval;
TotalRotations = 1;
TotalSteps = TotalLeds;
Index = 0;
}
// Update the Theater Chase Pattern
void TheaterChaseUpdate(){
for(int i=0; i<TotalLeds; i++){
if ((i + Index) % CHASE_SECTION_SIZE == 0){
leds[i] = ColorFromPalette(currentPalette, iColor, ActiveBrightness, currentBlending);
}
else{
leds[i] = ColorFromPalette(currentPalette, iColor + 40, ActiveBrightness, currentBlending);
}
}
FastLED.show();
Increment();
}
void Wave()
{
Serial.println("Begin WAVE");
UpdateInterval = WaveInterval;
TotalRotations = 4;
TotalSteps = TotalLeds;
Index = 0;
}
// Update the Wave Pattern
void WaveUpdate()
{
ClearLights();
SetPixel(Index);
for (int i=0; i<WAVE_FADE_SIZE; i++){
int brightness = (255 / (float)WAVE_FADE_SIZE) * (WAVE_FADE_SIZE-i);
// Back
int pointBack = Index - i;
if (pointBack < 0) { pointBack = TotalSteps + pointBack; }
SetPixel(pointBack, brightness);
// Front
int pointFront = Index + i;
if (pointFront > TotalSteps) { pointFront = pointFront - TotalSteps; }
SetPixel(pointFront, brightness);
}
FastLED.show();
Increment();
}
// Initialize for a Theater Chase
void Party(){
Serial.println("Begin PARTY");
currentPalette = RainbowColors_p;
UpdateInterval = PartyInterval;
TotalRotations = 1;
TotalSteps = 1;
Index = 0;
}
// Update the Theater Chase Pattern
void PartyUpdate(){
for(int i=0; i<TotalLeds; i++){
SetPixel(i);
NextColor(30);
}
FastLED.show();
Increment();
}
// Initialize for a ColorWipe
void SlowFade(){
Serial.println("Begin COLOR_WIPE");
currentPalette = RainbowColors_p;
currentBlending = LINEARBLEND;
UpdateInterval = SlowFadeInterval;
TotalRotations = 1;
TotalSteps = 255;
Index = 0;
}
// Update the Color Wipe Pattern
void SlowFadeUpdate(){
for(int i=0; i<TotalLeds; i++){
leds[i] = ColorFromPalette(currentPalette, iColor, ActiveBrightness, currentBlending);
}
NextColor(1);
FastLED.show();
Increment();
}
};
| b260421f2333aa83aa70c48b984810f104f5b642 | [
"C++"
] | 2 | C++ | Andy--Rose/StudioLighting | f8e4ded13653abb5dd7e81a27bee1309d354096d | 24c1d36ddd4093603144d7592a758494d1d55471 |
refs/heads/master | <file_sep>
var User = require('../models/users');
exports.user_create = function(req, res, next) {
if (req.body) {
let items = req.body
User.create(items, function(err, newUsers){
if(err) return res.json({ error: err });
var usuario = newUsers;
//res.json(newUsers);
res.render('validar', { nombreUsuario: usuario.name });
});
} else {
res.json({status: 'ERROR', message: 'Debe completar todos loscampos'}); //opcional mandar un mensaje de error
}
}
exports.lista_usuarios = function (req, res, next) {
User.find({}, function (err, usuarios) {
if (err) return handleError(err);
usuarios = usuarios.sort();
usuarios = reemplazar_nombres(usuarios);
res.render('registro', {usuarios: usuarios});
});
}
function reemplazar_nombres(arreglo) {
arreglo.map(function (arreglo) {
if (arreglo.name.includes('\u00f1')) {
let nombre = arreglo.name;
arreglo.name = nombre.replace(new RegExp("\u00f1", 'gi'), "nn");
}
if (arreglo.lastname.includes('\u00f1')) {
let apellido = arreglo.lastname;
arreglo.lastname = apellido.replace(new RegExp("\u00f1", 'gi'), "nn");
}
});
return arreglo;
}
| 54f6c8de3a2654c29be5556667d184c03d06c997 | [
"JavaScript"
] | 1 | JavaScript | Gabyblackroses/MVC2 | 455d621d3c303dc6072dd2af5804c3d6c53e69a9 | 7cb50892754b5d9b00b502b88ba814441623444d |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import {Observable} from "rxjs";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Problem} from "../model/problem";
@Injectable({
providedIn: 'root'
})
export class ProblemService {
constructor(private http: HttpClient) {}
getRandomProblem(): Observable<Problem> {
return this.http.get<Problem>("http://localhost:8080/problem");
}
saveProblem(problem: Problem) {
return this.http.post<Problem>("http://localhost:8080/problem", problem);
}
getAllProblems(): Observable<Array<Problem>> {
return this.http.get<Array<Problem>>("http://localhost:8080/problem/all");
}
deleteProblem(i: number) {
return this.http.delete("http://localhost:8080/problem/" + i);
}
}
<file_sep>import {Coordinate} from "./coordinate";
export class Problem {
public blackCoordinates: Coordinate[];
public whiteCoordinates: Coordinate[];
public solution: Coordinate;
}
<file_sep>import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ProblemService} from "../service/problem.service";
import {Problem} from "../model/problem";
import {Coordinate} from "../model/coordinate";
import {GobanUtil} from "../util/goban-util";
@Component({
selector: 'app-problemsolver',
templateUrl: './problemsolver.component.html',
styleUrls: ['./problemsolver.component.css']
})
export class ProblemsolverComponent implements OnInit {
@ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>;
private solution: Coordinate;
private ctx: CanvasRenderingContext2D;
constructor(private problemService: ProblemService) { }
ngOnInit() {
this.problemService.getRandomProblem().subscribe((problem: Problem) => {
this.solution = problem.solution;
this.ctx.fillStyle = "black";
problem.blackCoordinates.forEach((coordinate: Coordinate) => {
GobanUtil.drawStone(this.ctx, "black", coordinate);
});
problem.whiteCoordinates.forEach((coordinate: Coordinate) => {
GobanUtil.drawStone(this.ctx,"white", coordinate);
});
});
this.ctx = this.canvas.nativeElement.getContext('2d');
this.canvas.nativeElement.addEventListener('click', (e) => {
const mousePointer = {
x: e.layerX,
y: e.layerY
};
if (this.isIntersect(mousePointer, this.solution)) {
alert("correct");
} else {
alert("wrong");
}
});
GobanUtil.drawGoban(this.ctx);
}
private isIntersect(mousePointer, coordinate: Coordinate): boolean {
return Math.sqrt((mousePointer.x-coordinate.x*50) ** 2 + (mousePointer.y - coordinate.y*50) ** 2) < 25;
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProblemsolverComponent } from './problemsolver/problemsolver.component';
import { NavigationComponent } from './navigation/navigation.component';
import {HttpClientModule} from "@angular/common/http";
import { ProblemcreatorComponent } from './problemcreator/problemcreator.component';
import { ProblemlistComponent } from './problemlist/problemlist.component';
import { EmptyComponent } from './empty/empty.component';
@NgModule({
declarations: [
AppComponent,
ProblemsolverComponent,
NavigationComponent,
ProblemcreatorComponent,
ProblemlistComponent,
EmptyComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import {Component, OnInit} from '@angular/core';
import {ProblemService} from "../service/problem.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-problemlist',
templateUrl: './problemlist.component.html',
styleUrls: ['./problemlist.component.css']
})
export class ProblemlistComponent implements OnInit {
thumbnails: string[];
constructor(private problemService: ProblemService,
private router: Router) { }
ngOnInit() {
this.thumbnails = [];
this.problemService.getAllProblems().subscribe(problems => {
problems.forEach(problem => {
this.generateAscii(problem);
});
});
}
deleteProblem(i: number) {
this.problemService.deleteProblem(i).subscribe((success) => {
this.router.navigate(["empty"]);
setTimeout(() => {
this.router.navigate(["problemlist"]);
}, 1);
});
}
private generateAscii(problem) {
let thumbnail: string = "";
for (let y = 1; y < 9; y++) {
for (let x = 1; x < 10; x++) {
let found = false;
problem.blackCoordinates.forEach(coordinate => {
if (coordinate.x == x && coordinate.y == y) {
thumbnail = thumbnail + "●";
found = true;
}
});
if (!found) {
problem.whiteCoordinates.forEach(coordinate => {
if (coordinate.x == x && coordinate.y == y) {
thumbnail = thumbnail + "○";
found = true;
}
});
}
if (!found) {
if (x == 1) {
if (y == 1) {
thumbnail = thumbnail + "┌";
} else {
thumbnail = thumbnail + "├";
}
} else {
if (y == 1) {
thumbnail = thumbnail + "┬";
} else {
thumbnail = thumbnail + "┼";
}
}
}
if (x == 9) {
thumbnail = thumbnail + "<br/>";
}
}
}
this.thumbnails.push(thumbnail);
}
}
<file_sep>package com.site.tsumego.repository;
import com.site.tsumego.exception.ProblemException;
import com.site.tsumego.model.Coordinate;
import com.site.tsumego.model.Problem;
import org.springframework.stereotype.Repository;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
@Repository
public class ProblemRepository {
private final Random randomGenerator;
private ArrayList<Problem> problems = new ArrayList<>();
public ProblemRepository() {
try {
FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\jorisr\\Desktop\\tsumego"));
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
problems = (ArrayList<Problem>)object;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
randomGenerator = new Random();
}
public Problem getRandomProblem() throws ProblemException {
if(!problems.isEmpty()) {
return problems.get(randomGenerator.nextInt(problems.size()));
} else {
return Problem.create(Collections.emptyList(), Collections.emptyList(), Coordinate.create(0,0));
}
}
public void createNewProblem(Problem problem) {
problems.add(problem);
saveProblemsToFile();
}
public List<Problem> getAllProblems() {
return problems;
}
public void deleteProblem(int id) {
problems.remove(id);
saveProblemsToFile();
}
private void saveProblemsToFile() {
try {
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\jorisr\\Desktop\\tsumego");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(problems);
objectOut.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>package com.site.tsumego.service;
import com.site.tsumego.exception.ProblemException;
import com.site.tsumego.model.Coordinate;
import com.site.tsumego.model.Problem;
import com.site.tsumego.model.dto.CoordinateDto;
import com.site.tsumego.model.dto.ProblemDto;
import com.site.tsumego.repository.ProblemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class ProblemService {
private ProblemRepository problemRepository;
private Function<Coordinate, CoordinateDto> convertCoordinate = coordinate -> {
CoordinateDto coordinateDto = new CoordinateDto();
coordinateDto.setX(coordinate.getX());
coordinateDto.setY(coordinate.getY());
return coordinateDto;
};
private Function<CoordinateDto, Coordinate> convertCoordinateDto = coordinateDto -> Coordinate.create(coordinateDto.getX(), coordinateDto.getY());
@Autowired
public ProblemService(ProblemRepository problemRepository) {
this.problemRepository = problemRepository;
}
public ProblemDto getRandomProblem() throws ProblemException {
return convert(problemRepository.getRandomProblem());
}
public void createNewProblem(ProblemDto problemDto) throws ProblemException {
problemRepository.createNewProblem(convert(problemDto));
}
public void deleteProblem(int id) {
problemRepository.deleteProblem(id);
}
// Helpers
private ProblemDto convert(Problem problem) {
ProblemDto problemDto = new ProblemDto();
problemDto.setBlackCoordinates(problem.getBlackCoordinates().stream()
.map(convertCoordinate)
.collect(Collectors.toList()));
problemDto.setWhiteCoordinates(problem.getWhiteCoordinates().stream()
.map(convertCoordinate)
.collect(Collectors.toList()));
problemDto.setSolution(convertCoordinate.apply(problem.getSolution()));
return problemDto;
}
private Problem convert(ProblemDto problemDto) throws ProblemException {
return Problem.create(
problemDto.getBlackCoordinates().stream().map(convertCoordinateDto).collect(Collectors.toList()),
problemDto.getWhiteCoordinates().stream().map(convertCoordinateDto).collect(Collectors.toList()),
convertCoordinateDto.apply(problemDto.getSolution())
);
}
public List<ProblemDto> getAllProblems() {
return problemRepository.getAllProblems().stream().map(this::convert).collect(Collectors.toList());
}
}
<file_sep>package com.site.tsumego.repository;
import com.site.tsumego.model.Problem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestProblemRepository {
@Autowired
private ProblemRepository problemRepository;
@Test
public void getRandomProblem() throws Exception {
Problem problem = problemRepository.getRandomProblem();
assertThat(problem).isNotNull();
}
}
<file_sep>import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {NavigationComponent} from "./navigation/navigation.component";
import {ProblemsolverComponent} from "./problemsolver/problemsolver.component";
import {ProblemcreatorComponent} from "./problemcreator/problemcreator.component";
import {ProblemlistComponent} from "./problemlist/problemlist.component";
import {EmptyComponent} from "./empty/empty.component";
const routes: Routes = [
{ path: '', component: NavigationComponent },
{ path: 'problemsolver', component: ProblemsolverComponent },
{ path: 'problemcreator', component: ProblemcreatorComponent },
{ path: 'problemlist', component: ProblemlistComponent },
{ path: 'empty', component: EmptyComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<file_sep>package com.site.tsumego.model.dto;
import java.util.List;
public class ProblemDto {
private List<CoordinateDto> blackCoordinates;
private List<CoordinateDto> whiteCoordinates;
private CoordinateDto solution;
public List<CoordinateDto> getBlackCoordinates() {
return blackCoordinates;
}
public void setBlackCoordinates(List<CoordinateDto> blackCoordinates) {
this.blackCoordinates = blackCoordinates;
}
public List<CoordinateDto> getWhiteCoordinates() {
return whiteCoordinates;
}
public void setWhiteCoordinates(List<CoordinateDto> whiteCoordinates) {
this.whiteCoordinates = whiteCoordinates;
}
public CoordinateDto getSolution() {
return solution;
}
public void setSolution(CoordinateDto solution) {
this.solution = solution;
}
}
<file_sep>package com.site.tsumego.model;
import java.io.Serializable;
public class Coordinate implements Serializable {
private int x;
private int y;
private Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public static boolean isEqual(Coordinate c1, Coordinate c2) {
return c1.x == c2.x && c1.y == c2.y;
}
public static Coordinate create(int x, int y) {
return new Coordinate(x, y);
}
@Override
public String toString() {
return "[" + x + ", " + y + " ]";
}
}
<file_sep>package com.site.tsumego.model;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TestCoordinate {
@Test
public void createCoordinate() {
Coordinate coordinate = Coordinate.create(0, 0);
assertThat(coordinate).isNotNull();
assertThat(coordinate.getX()).isEqualTo(0);
assertThat(coordinate.getY()).isEqualTo(0);
}
}
<file_sep>import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {GobanUtil} from "../util/goban-util";
import {Coordinate} from "../model/coordinate";
import {Problem} from "../model/problem";
import {ProblemService} from "../service/problem.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-problemcreator',
templateUrl: './problemcreator.component.html',
styleUrls: ['./problemcreator.component.css']
})
export class ProblemcreatorComponent implements OnInit {
@ViewChild('canvas', { static: true }) canvas: ElementRef<HTMLCanvasElement>;
private ctx: CanvasRenderingContext2D;
private stoneColor: string;
private problem: Problem;
constructor(private problemService: ProblemService,
private router: Router) { }
ngOnInit() {
this.problem = new Problem();
this.problem.solution = new Coordinate();
this.problem.blackCoordinates = [];
this.problem.whiteCoordinates = [];
this.stoneColor = 'black';
this.ctx = this.canvas.nativeElement.getContext('2d');
GobanUtil.drawGoban(this.ctx);
this.canvas.nativeElement.addEventListener('click', (e) => {
const mousePointer = {
x: e.layerX,
y: e.layerY
};
const coordinate: Coordinate = new Coordinate();
coordinate.x = Math.round(mousePointer.x/50);
coordinate.y = Math.round(mousePointer.y/50);
GobanUtil.drawStone(this.ctx, this.stoneColor, coordinate);
if (this.stoneColor == 'black') {
this.problem.blackCoordinates.push(coordinate);
} else if (this.stoneColor == 'white') {
this.problem.whiteCoordinates.push(coordinate);
} else if (this.stoneColor == 'green') {
this.problem.solution = coordinate;
}
});
}
public setStoneColor(event) {
this.stoneColor = event.target.id;
}
public clearGoban() {
GobanUtil.clearGoban(this.ctx);
this.problem.blackCoordinates = [];
this.problem.whiteCoordinates = [];
this.problem.solution = null;
}
public saveProblem() {
this.problemService.saveProblem(this.problem).subscribe((success) => {
this.router.navigate(["empty"]);
setTimeout(() => {
this.router.navigate(["problemcreator"]);
}, 1);
});
}
}
<file_sep>import {Coordinate} from "../model/coordinate";
export class GobanUtil {
public static drawGoban(ctx): void {
ctx.beginPath();
// Vertical lines
for (let i = 1; i < 10; i++) {
ctx.moveTo(i*50, 50);
ctx.lineTo(i*50, 400);
}
// Horizontal lines
for (let i = 1; i < 10; i++) {
ctx.moveTo(50, i*50);
ctx.lineTo(500, i*50);
}
ctx.closePath();
ctx.stroke();
}
public static drawStone(ctx, color: string, coordinate: Coordinate): void {
ctx.beginPath();
ctx.arc(coordinate.x*50, coordinate.y*50, 25, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
ctx.arc(coordinate.x*50, coordinate.y*50, 25, 0, 2 * Math.PI);
ctx.fillStyle = "black";
ctx.closePath();
ctx.stroke();
};
public static clearGoban(ctx) {
ctx.clearRect(0, 0, 500,400);
this.drawGoban(ctx);
}
}
<file_sep>"# tsumegosite"
| 0cd6d6e6d458f73fc64e8843de3ab4662ab8969a | [
"Markdown",
"Java",
"TypeScript"
] | 15 | TypeScript | Vocht/tsumegosite | e7b58a42bb6411118d96526e790f3b31a696989a | c7015699da8a736d1e22c718a0abeb1e8edce23b |
refs/heads/master | <file_sep>/*
* FIFO Buffer
* Implementation uses arrays to conserve memory
*
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>
* Copyright (c) 2019 <NAME>, <NAME> (addind methods : pushBuffer, popBuffer, peekBuffer)
*
* 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.
*/
#include "FIFO.h"
FIFO::FIFO() {
head = 0;
tail = 0;
numElements = 0;
}
FIFO::~FIFO() {
}
/**
* \fn bool FIFO::push(uint8_t data)
* \brief Allows a user to push one element inside the FIFO.
* \param data : the element to be pushed inside the FIFO.
* \return The function returns true if the element was pushed inside the FIFO, else return false.
*/
bool FIFO::push(uint8_t data) {
if(numElements == FIFO_SIZE) {
return false;
}
else {
//Increment size
numElements++;
//Only move the tail if there is more than one element
if(numElements > 1) {
//Increment tail location
tail++;
//Make sure tail is within the bounds of the array
tail %= FIFO_SIZE;
}
//Store data into array
buffer[tail] = data;
return true;
}
}
/**
* \fn bool FIFO::pushBuffer(const uint8_t* src, int src_size)
* \brief Allows a user to push a buffer of uint8_t of length src_size inside the FIFO.
* \param *src : a pointer to the source buffer.
* \param src_size : the number of elements inside the source buffer.
* \return The function returns true if the elements were pushed inside the fifo, else return false
*/
bool FIFO::pushBuffer(const uint8_t* src, int src_size){
if(numElements + 1 + src_size > FIFO_SIZE){
return false;
}
if (push((uint8_t) src_size)){
for(int i=0; i < src_size; i++){
push(src[i]);
}
return true;
}
return false;
}
/**
* \fn uint8_t FIFO::pop()
* \brief Allows a user to pop a element from the FIFO.
* \return The function returns 0 if the FIFO is empty, else it returns the removed element.
*/
uint8_t FIFO::pop() {
if(isEmpty()) {
return 0;
}
else {
//Decrement size
numElements--;
uint8_t data = buffer[head];
if(numElements >= 1) {
//Move head up one position
head++;
//Make sure head is within the bounds of the array
head %= FIFO_SIZE;
}
return data;
}
}
/**
* \fn int FIFO::popBuffer(uint8_t* dest, int dest_size)
* \brief Allows a user to remove a buffer from the FIFO. The first element removed will be considered as the length of the buffer to remove. The removed buffer will be written inside the destination buffer.
* \param *dest : a pointer to the destination buffer.
* \param dest_size : the number of elements the destination buffer can contain.
* \return The function returns the number of elements written inside the destination buffer.
*/
int FIFO::popBuffer(uint8_t* dest, int dest_size) {
if(isEmpty()) {
return 0;
}
else {
uint8_t str_size = pop();
if(dest_size < str_size)
return -1;
if( str_size > numElements)
return -1;
for(uint8_t i = 0;i < str_size; i++) {
dest[i] = pop();
}
return str_size;
}
}
/**
* \fn uint8_t FIFO::size()
* \brief Returns the number of elements in the FIFO.
* \return The function returns the number of elements the FIFO contains.
*/
int FIFO::size() {
return numElements;
}
/**
* \fn uint8_t FIFO::peek()
* \brief Returns the top element of the FIFO.
* \return The function returns first element inside the FIFO or 0 if the FIFO is empty.
*/
uint8_t FIFO::peek() {
if (numElements == 0) {
return 0;
}
else {
return buffer[head];
}
}
/**
* \fn int FIFO::peekBuffer(uint8_t* dest, int dest_size)
* \brief Allows a user to get the top buffer from the FIFO. The first element will be considered as the length of the buffer to get, then the next elements will be written inside the destination buffer.
* \param *dest : a pointer to the destination buffer.
* \param dest_size : the number of elements the destination buffer can contain.
* \return The function returns the number of elements written inside the destination buffer or if the buffer is empty or if the destination buffer can't contain the number of elements, the function will return -1.
*/
int FIFO::peekBuffer(uint8_t* dest, int dest_size) {
if (isEmpty()) {
return -1;
}
else {
int str_size = buffer[head];
if( dest_size < str_size)
return -1;
if( str_size > numElements)
return -1;
for (int i = 0; i < dest_size; i++) {
dest[i] = buffer[(head + i + 1) % FIFO_SIZE];
}
return str_size;
}
}
bool FIFO::isEmpty() {
return numElements == 0;
}
<file_sep># Arduino-FIFO
Simple FIFO buffer for Arduino or other embedded processors
The default size of the buffer is 32760 bytes.
With the default buffer size this library uses only 32766 bytes of memory.
(32760 byte buffer + 3 * 2 byte integers)
If you wish to change the buffer size then edit the ```#define FIFO_SIZE 32760``` inside of "FIFO.h"
<file_sep>/*
* FIFO Buffer
* Implementation uses arrays to conserve memory
*
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>
* Copyright (c) 2019 <NAME>, <NAME> (addind methods : pushBuffer, popBuffer, peekBuffer)
*
* 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.
*/
#ifndef __FIFO__
#define __FIFO__
#include <stdint.h>
#ifdef FIFO_SIZE
#elif ADAFRUIT_FEATHER_M0
#define FIFO_SIZE 16526
#else
#define FIFO_SIZE 32760
#endif
class FIFO {
private:
int head;
int tail;
int numElements;
uint8_t buffer[FIFO_SIZE];
public:
FIFO();
~FIFO();
bool push(uint8_t data);
bool pushBuffer(const uint8_t* src, int src_size);
uint8_t pop();
int popBuffer(uint8_t* dest, int dest_size);
int size();
uint8_t peek();
int peekBuffer(uint8_t* dest, int dest_size);
bool isEmpty();
};
#endif
<file_sep>#include "FIFO.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int getSize() {
int min = 25;
int max = 50;
return min + std::rand() % ((max + 1) - min);
}
void fillTab(uint8_t* tab, uint8_t fillinDigit, int tabSize) {
for (int i = 0; i < tabSize; i++) {
tab[i] = fillinDigit;
}
}
int test_empty_size(){
FIFO exFIFO;
uint8_t displayBuf[50];
std::cout <<"Test exFIFO with an empty size" << std::endl;
if(exFIFO.pop() != 0
){
std::cout << "Error exFIFO.pop()"<< std::endl;
return -1;
}
if(exFIFO.peek() != 0){
std::cout << "Error exFIFO.peek()" << std::endl;
return -1;
}
if(exFIFO.peekBuffer(displayBuf, 50) != -1){
std::cout << "Error exFIFO.peekBuffer()"<<std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != -1){
std::cout << "Error exFIFO.popBuffer()"<< std::endl;
return -1;
}
if(exFIFO.size() !=0){
std::cout << "Error exFIFO.size()"<< std::endl;
return -1;
}
if(!exFIFO.isEmpty()){
std::cout << "Error exFIFO.isEmpty()"<< std::endl;
return -1;
}
return 0;
}
int test_one_element(){
FIFO exFIFO;
uint8_t displayBuf[50];
exFIFO.push(0);
std::cout <<"Test exFIFO with one element" << std::endl;
if(exFIFO.pop() != 0){
std::cout << "Error exFIFO.pop()"<< std::endl;
return -1;
}
exFIFO.push(0);
if(exFIFO.peek() != 0){
std::cout << "Error exFIFO.peek()"<< std::endl;
return -1;
}
if(exFIFO.peekBuffer(displayBuf, 50) != 0){
std::cout << "Error exFIFO.peekBuffer()"<< std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != 0){
std::cout << "Error exFIFO.popBuffer()"<< std::endl;
return -1;
}
exFIFO.push(0);
if(exFIFO.size() !=1){
std::cout << "Error exFIFO.size()"<< std::endl;
return -1;
}
if(exFIFO.isEmpty()){
std::cout << "Error exFIFO.isEmpty()"<< std::endl;
return -1;
}
exFIFO.pop();
return 0;
}
int test_one_bad_element(){
FIFO exFIFO;
uint8_t displayBuf[50];
exFIFO.push(17);
std::cout <<"Test exFIFO with one element but bad value" << std::endl;
if(exFIFO.peekBuffer(displayBuf, 50) != -1){
std::cout << "Error exFIFO.peekBuffer()"<< std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != -1){
std::cout << "Error exFIFO.popBuffer()"<< std::endl;
return -1;
}
return 0;
}
int test_random_input(){
FIFO exFIFO;
uint8_t displayBuf[50];
int test_size[10];
int total_elem =0;
std::cout <<"Test exFIFO with random values" << std::endl;
for( int i =0; i < 10; i++){
test_size[i] = getSize();
total_elem += 1 + test_size[i];
uint8_t ex1[test_size[i]];
fillTab(ex1, 48+i, sizeof(ex1));
exFIFO.pushBuffer(ex1,test_size[i]);
if(exFIFO.size() != total_elem){
std::cout << "Error exFIFO.size()"<< std::endl;
return -1;
}
}
while(!(exFIFO.isEmpty())) {
uint8_t test = exFIFO.peek();
if(exFIFO.peekBuffer(displayBuf, test) != test){
std::cout << "Error exFIFO.peekBuffer()"<< std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf, test) != test){
std::cout << "Error exFIFO.popBuffer()"<< std::endl;
return -1;
}
}
return 0;
}
int test_toomuch_elements(){
std::cout <<"Test exFIFO out of bounds" << std::endl;
FIFO exFIFO;
uint8_t displayBuf[511];
for(int i=0; i < 255; i++){
displayBuf[i] = i;
}
exFIFO.pushBuffer(displayBuf, 255);
exFIFO.pushBuffer(displayBuf, 255);
if(exFIFO.size() !=512){
std::cout << "Error exFIFO.size()"<<std::endl;
return -1;
}
if(exFIFO.push(23)){
std::cout << "Error exFIFO.push()"<< std::endl;
return -1;
}
if(exFIFO.peekBuffer(displayBuf,511) != 255){
std::cout << "Error exFIFO.peekBuffer()" << std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf,511) != 255){
std::cout << "Error exFIFO.popBuffer()" << std::endl;
return -1;
}
if(exFIFO.peekBuffer(displayBuf,511) != 255){
std::cout << "Error exFIFO.peekBuffer()" << std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf,511) != 255){
std::cout << "Error exFIFO.popBuffer()" << std::endl;
return -1;
}
return 0;
}
int test_max_size() {
FIFO exFIFO;
uint8_t displayBuf[70];
int total_elem = 0;
std::cout <<"Test exFIFO with max size" << std::endl;
for (int i = 0; i < 8; i++) {
uint8_t ex1[63];
total_elem += 64;
fillTab(ex1, 48 + i, 63);
exFIFO.pushBuffer(ex1, 63);
if(exFIFO.size() != total_elem){
std::cout << "Error exFIFO.size() "<<std::endl;
return -1;
}
}
uint8_t test = exFIFO.peek();
exFIFO.popBuffer(displayBuf, test);
uint8_t ex1[63];
fillTab(ex1, 48+8, 63);
exFIFO.peekBuffer(ex1, 63);
while(!(exFIFO.isEmpty())) {
uint8_t test = 63;
if(exFIFO.peekBuffer(displayBuf, 70) != test){
std::cout << "Error exFIFO.peekBuffer()"<< std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf, 70) != test){
std::cout << "Error exFIFO.popBuffer()"<< std::endl;
return -1;
}
}
return 0;
}
int test_max_coverage(){
std::cout <<"Test exFIFO test_max_coverage" << std::endl;
FIFO exFIFO;
uint8_t displayBuf[7];
uint8_t ex1[63];
fillTab(ex1, 48, 63);
exFIFO.pushBuffer(ex1,63);
if(exFIFO.size() !=64){
std::cout << "Error exFIFO.size()"<< std::endl;
return -1;
}
if(exFIFO.isEmpty()){
std::cout << "Error exFIFO.isEmpty()"<< std::endl;
return -1;
}
if(exFIFO.peekBuffer(displayBuf,7) != 63){
std::cout << "Error exFIFO.peekBuffer()" << std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf,7) != 63){
std::cout << "Error exFIFO.popBuffer()" << std::endl;
return -1;
}
if(exFIFO.size() != 0){
std::cout << "Error exFIFO.size()"<< std::endl;
return -1;
}
exFIFO.push(45);
for(int i=0; i < 10; i++){
exFIFO.push(48);
}
if(exFIFO.peekBuffer(displayBuf,7) != -1){
std::cout << "Error exFIFO.peekBuffer()" << std::endl;
return -1;
}
if(exFIFO.popBuffer(displayBuf,7) != -1){
std::cout << "Error exFIFO.popBuffer()" << std::endl;
return -1;
}
return 0;
}
int main() {
if(test_empty_size() !=0)
return -1;
if(test_one_element() != 0)
return -1;
if(test_one_bad_element() != 0)
return -1;
if(test_random_input()!= 0)
return -1;
if(test_toomuch_elements() != 0)
return -1;
if(test_max_size()!= 0)
return -1;
if(test_max_coverage()!= 0)
return -1;
return 0;
}
<file_sep>/*
* FIFO Buffer Test Program
* Pushes then pops items onto FIFO buffer.
*
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>, <NAME>
*
* 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.
*/
#include "FIFO.h"
void setup() {
//Open serial port at 9600 baud
Serial.begin(9600);
//Wait until the serial port has opened
while (!Serial) delay(1);
//Wait a little bit to make sure we don't get any garbage on the serial monitor
delay(100);
randomSeed(analogRead(0));
delay(100);
}
void loop() {
Serial.println("Starting tests...");
if(test_empty_size() !=0)
Serial.println("Error in test");
if(test_one_element() != 0)
Serial.println("Error in test");
if(test_one_bad_element() != 0)
Serial.println("Error in test");
if(test_random_input()!= 0)
Serial.println("Error in test");
if(test_toomuch_elements() != 0)
Serial.println("Error in test");
if(test_max_size()!= 0)
Serial.println("Error in test");
if(test_max_coverage()!= 0)
Serial.println("Error in test");
while (1);
}
int getSize() {
return random(25,50);
}
void fillTab(uint8_t* tab, char fillinDigit, int tabSize) {
for (int i = 0; i < tabSize; i++) {
tab[i] = fillinDigit;
}
}
int test_empty_size(){
FIFO exFIFO;
uint8_t displayBuf[50];
Serial.println("Test exFIFO with an empty size" );
if(exFIFO.pop() != 0
){
Serial.println( "Error exFIFO.pop()");
return -1;
}
if(exFIFO.peek() != 0){
Serial.println( "Error exFIFO.peek()" );
return -1;
}
if(exFIFO.peekBuffer(displayBuf, 50) != -1){
Serial.println( "Error exFIFO.peekBuffer()");
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != -1){
Serial.println( "Error exFIFO.popBuffer()");
return -1;
}
if(exFIFO.size() !=0){
Serial.println( "Error exFIFO.size()");
return -1;
}
if(!exFIFO.isEmpty()){
Serial.println( "Error exFIFO.isEmpty()");
return -1;
}
return 0;
}
int test_one_element(){
FIFO exFIFO;
uint8_t displayBuf[50];
exFIFO.push(0);
Serial.println("Test exFIFO with one element" );
if(exFIFO.pop() != 0){
Serial.println( "Error exFIFO.pop()");
return -1;
}
exFIFO.push(0);
if(exFIFO.peek() != 0){
Serial.println( "Error exFIFO.peek()");
return -1;
}
if(exFIFO.peekBuffer(displayBuf, 50) != 0){
Serial.println( "Error exFIFO.peekBuffer()");
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != 0){
Serial.println( "Error exFIFO.popBuffer()");
return -1;
}
exFIFO.push(0);
if(exFIFO.size() !=1){
Serial.println( "Error exFIFO.size()");
return -1;
}
if(exFIFO.isEmpty()){
Serial.println( "Error exFIFO.isEmpty()");
return -1;
}
exFIFO.pop();
return 0;
}
int test_one_bad_element(){
FIFO exFIFO;
uint8_t displayBuf[50];
exFIFO.push(17);
Serial.println("Test exFIFO with one element but bad value" );
if(exFIFO.peekBuffer(displayBuf, 50) != -1){
Serial.println( "Error exFIFO.peekBuffer()");
return -1;
}
if(exFIFO.popBuffer(displayBuf, 50) != -1){
Serial.println( "Error exFIFO.popBuffer()");
return -1;
}
return 0;
}
int test_random_input(){
FIFO exFIFO;
uint8_t displayBuf[50];
int test_size[10];
int total_elem =0;
Serial.println("Test exFIFO with random values" );
for( int i =0; i < 10; i++){
test_size[i] = getSize();
total_elem += 1 + test_size[i];
uint8_t ex1[test_size[i]];
fillTab(ex1, 48+i, sizeof(ex1));
exFIFO.pushBuffer(ex1,test_size[i]);
if(exFIFO.size() != total_elem){
Serial.println( "Error exFIFO.size()");
return -1;
}
}
while(!(exFIFO.isEmpty())) {
uint8_t test = exFIFO.peek();
if(exFIFO.peekBuffer(displayBuf, test) != test){
Serial.println( "Error exFIFO.peekBuffer()");
return -1;
}
if(exFIFO.popBuffer(displayBuf, test) != test){
Serial.println( "Error exFIFO.popBuffer()");
return -1;
}
}
return 0;
}
int test_toomuch_elements(){
Serial.println("Test exFIFO out of bounds" );
FIFO exFIFO;
uint8_t displayBuf[511];
for(int i=0; i < 255; i++){
displayBuf[i] = i;
}
exFIFO.pushBuffer(displayBuf, 255);
exFIFO.pushBuffer(displayBuf, 255);
if(exFIFO.size() !=512){
Serial.println( "Error exFIFO.size()");
return -1;
}
if(exFIFO.push(23)){
Serial.println( "Error exFIFO.push()");
return -1;
}
if(exFIFO.peekBuffer(displayBuf,511) != 255){
Serial.println( "Error exFIFO.peekBuffer()" );
return -1;
}
if(exFIFO.popBuffer(displayBuf,511) != 255){
Serial.println( "Error exFIFO.popBuffer()" );
return -1;
}
if(exFIFO.peekBuffer(displayBuf,511) != 255){
Serial.println( "Error exFIFO.peekBuffer()" );
return -1;
}
if(exFIFO.popBuffer(displayBuf,511) != 255){
Serial.println( "Error exFIFO.popBuffer()" );
return -1;
}
return 0;
}
int test_max_size() {
FIFO exFIFO;
uint8_t displayBuf[70];
int total_elem = 0;
Serial.println("Test exFIFO with max size" );
for (int i = 0; i < 8; i++) {
uint8_t ex1[63];
total_elem += 64;
fillTab(ex1, 48 + i, 63);
exFIFO.pushBuffer(ex1, 63);
if(exFIFO.size() != total_elem){
Serial.println( "Error exFIFO.size() ");
return -1;
}
}
uint8_t test = exFIFO.peek();
exFIFO.popBuffer(displayBuf, test);
uint8_t ex1[63];
fillTab(ex1, 48+8, 63);
exFIFO.peekBuffer(ex1, 63);
while(!(exFIFO.isEmpty())) {
uint8_t test = 63;
if(exFIFO.peekBuffer(displayBuf, 70) != test){
Serial.println( "Error exFIFO.peekBuffer()");
return -1;
}
if(exFIFO.popBuffer(displayBuf, 70) != test){
Serial.println( "Error exFIFO.popBuffer()");
return -1;
}
}
return 0;
}
int test_max_coverage(){
Serial.println("Test exFIFO test_max_coverage" );
FIFO exFIFO;
uint8_t displayBuf[7];
uint8_t ex1[63];
fillTab(ex1, 48, 63);
exFIFO.pushBuffer(ex1,63);
if(exFIFO.size() !=64){
Serial.println( "Error exFIFO.size()");
return -1;
}
if(exFIFO.isEmpty()){
Serial.println( "Error exFIFO.isEmpty()");
return -1;
}
if(exFIFO.peekBuffer(displayBuf,7) != 63){
Serial.println( "Error exFIFO.peekBuffer()" );
return -1;
}
if(exFIFO.popBuffer(displayBuf,7) != 63){
Serial.println( "Error exFIFO.popBuffer()" );
return -1;
}
if(exFIFO.size() != 0){
Serial.println( "Error exFIFO.size()");
return -1;
}
exFIFO.push(45);
for(int i=0; i < 10; i++){
exFIFO.push(48);
}
if(exFIFO.peekBuffer(displayBuf,7) != -1){
Serial.println( "Error exFIFO.peekBuffer()" );
return -1;
}
if(exFIFO.popBuffer(displayBuf,7) != -1){
Serial.println( "Error exFIFO.popBuffer()" );
return -1;
}
return 0;
}
| d331f709b93e90ac65de4c3bf56ef8b1e8332107 | [
"Markdown",
"C++"
] | 5 | C++ | AKUINO/Arduino-FIFO | eb3eca0f1135b15a70a808ddd682041baf124b27 | 1d71be3ea3cf507172f612c1b45d6f5a47739745 |
refs/heads/master | <file_sep><?php
include 'score.php';
$score = new score();
error_reporting(E_ERROR);
$n = 0;
$testName = $_GET['load'];
$json = file_get_contents(__DIR__ . "/test/$testName");
$decode = json_decode($json, true);
for ($i = 1, $quantity = count($decode[0]); $i <= $quantity; $i++) {
if ($decode[0]['question' . $i] == $_POST['question' . $i]) {
$n += 1;
}
}
$score = $score->Test_Score($n);
if (isset($_POST['OK']) && empty($_POST['name'])) {
echo
"<script>alert('Вы не ввели свое имя! Пожалуйста, введите свое имя.');",
"location.href='" . $_SERVER['REQUEST_URI'], "';",
"</script>";
die();
}
$name = $_POST['name'];
if (isset($_POST['OK'])) {
echo "<h1>Правильных ответов $n из 5</h1>";
echo "<form method=\"post\" action=\"list.php\"><input type=\"submit\" value=\"В главное меню\"></form>";
echo "<h2>$name, Ваша оценка: $score</h2>";
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Тест 1</title>
</head>
<body>
<form method="post">
Введите свое имя: <input name="name" required>* (Обязательное поле)
<p><b><?= $decode[1]['answer'] ?></b><Br>
<input type="radio" name="question1" value="<?= $decode[0]["question1"] ?>"> <?= $decode[0]["question1"] ?><Br>
<input type="radio" name="question1"
value="<?= $decode[2]["possibleAnswer1.1"] ?>"> <?= $decode[2]["possibleAnswer1.1"] ?><Br>
<input type="radio" name="question1"
value="<?= $decode[2]["possibleAnswer1.2"] ?>"> <?= $decode[2]["possibleAnswer1.2"] ?><Br>
</p>
<p><b><?= $decode[1]['answer2'] ?></b><Br>
<input type="radio" name="question2"
value="<?= $decode[2]["possibleAnswer2.1"] ?>"> <?= $decode[2]["possibleAnswer2.1"] ?><Br>
<input type="radio" name="question2" value="<?= $decode[0]["question2"] ?>"> <?= $decode[0]["question2"] ?><Br>
<input type="radio" name="question2"
value="<?= $decode[2]["possibleAnswer2.2"] ?>"> <?= $decode[2]["possibleAnswer2.2"] ?><Br>
</p>
<p><b><?= $decode[1]['answer3'] ?></b><Br>
<input type="radio" name="question3"
value="<?= $decode[2]["possibleAnswer3.1"] ?>"> <?= $decode[2]["possibleAnswer3.1"] ?><Br>
<input type="radio" name="question3"
value="<?= $decode[2]["possibleAnswer3.2"] ?>"> <?= $decode[2]["possibleAnswer3.2"] ?><Br>
<input type="radio" name="question3" value="<?= $decode[0]["question3"] ?>"> <?= $decode[0]["question3"] ?><Br>
</p>
<p><b><?= $decode[1]['answer4'] ?></b><Br>
<input type="radio" name="question4" value="<?= $decode[0]["question4"] ?>"> <?= $decode[0]["question4"] ?><Br>
<input type="radio" name="question4"
value="<?= $decode[2]["possibleAnswer4.1"] ?>"> <?= $decode[2]["possibleAnswer4.1"] ?><Br>
<input type="radio" name="question4"
value="<?= $decode[2]["possibleAnswer4.2"] ?>"> <?= $decode[2]["possibleAnswer4.2"] ?><Br>
</p>
<p><b><?= $decode[1]['answer5'] ?></b><Br>
<input type="radio" name="question5"
value="<?= $decode[2]["possibleAnswer5.1"] ?>"> <?= $decode[2]["possibleAnswer5.1"] ?><Br>
<input type="radio" name="question5" value="<?= $decode[0]["question5"] ?>"> <?= $decode[0]["question5"] ?><Br>
<input type="radio" name="question5"
value="<?= $decode[2]["possibleAnswer5.2"] ?>"> <?= $decode[2]["possibleAnswer5.2"] ?><Br>
</p>
<input type="submit" name="OK" value="Отправить">
</form>
</body>
</html><file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Панеь загрузки тестов</title>
</head>
<body>
<form method="post" action="list.php">
<input type="submit" value="Выйти">
</form>
<form enctype="multipart/form-data" method="post">
<input name="name">
<input type="file" name="uploadFile">
<input type="submit" name="submit" value="Отправить">
</form>
</body>
</html>
<?php
error_reporting(E_ERROR);
if ((is_null($_FILES['uploadFile']) || empty($_POST['name'])) && isset($_POST['submit'])) {
echo 'Вы не загрузили новый тест на сайт или не ввели свое имя, попробуйте снова.';
exit();
}else{
$json = $_FILES['uploadFile'];
$filename = $json['name'];
$nameVar = $_POST['name'];
}
$Name = fopen('nameFile', 'a+'); //открываем файл, в котором будут храниться именя файлов загруженных на сервер
trim(fwrite($Name, $nameVar . " ")); //записываем имена в файл черех пробел и удаляем пробелы на кончах файла
fclose($Name); // закрываем файл
if (isset($_POST['submit'])){
if (move_uploaded_file($json['tmp_name'], __DIR__ . "/test/$filename")) { //проверяем файл на наличие на сервере
echo 'Тест успешно загружен';
} else {
echo 'К сожалению, произошла ошибка, загрузите файл повторно';
}
} | 2002228845bb720e2c7e09f1f3388df6c2549fea | [
"PHP"
] | 2 | PHP | Stuksus/SeventhLesson | b29151c437f98e91c0f70ffc8e354c6ef2f4caa4 | 862558f5ee8d036e50a33cd9500d61fb91eaaa98 |
refs/heads/master | <repo_name>Bincy19/reverse<file_sep>/reverse.py
n=int(input("Enter number: "))
rev=0
while(n>0):
dig=int(n%10)
rev=(rev*10)+dig
n=n//10
print ("reverse of the number :",rev) | a48b8c1b20927ca76b1f2e63c25a5582b330dc83 | [
"Python"
] | 1 | Python | Bincy19/reverse | d414ee7f7419cdb7b640920bf400175f2bd70446 | f6fba11066165f1a397d47182d1b16d02125d90a |
refs/heads/master | <file_sep>/// This file contains Vuex logic for the PomodoroSettings component
const initialState = {
workTime: 25,
breakTime: 5,
longBreakTime: 15,
autoStartBreak: false,
autoStartNextSession: false,
countUpwards: false,
countUpwardsBreak: false
};
const mutations = {
setWorkTime(state, payload) {
state.workTime = payload;
},
setBreakTime(state, payload) {
state.breakTime = payload;
},
setLongBreakTime(state, payload) {
state.longBreakTime = payload;
},
setAutoStartBreak(state, payload) {
state.autoStartBreak = payload;
},
setAutoStartNextSession(state, payload) {
state.autoStartNextSession = payload;
},
setCountUpwards(state, payload) {
state.countUpwards = payload;
},
setCountUpwardsBreak(state, payload) {
state.countUpwardsBreak = payload;
}
};
const actions = {};
const getters = {};
const module = {
state: initialState,
mutations: mutations,
actions: actions,
getters: getters
};
export default module;
<file_sep>/// This file contains Vuex logic for the Pomodoro component
export const constants = {
WORK_STAGE: "WORK_STAGE",
BREAK_STAGE: "BREAK_STAGE",
LONG_BREAK_STAGE: "LONG_BREAK_STAGE"
};
const initialState = { stage: constants.WORK_STAGE, countCycles: 0 };
const mutations = {
changeStage(state, payload) {
state.stage = payload;
},
changeCycles(state, payload) {
state.countCycles = payload;
}
};
const actions = {
workStage(context) {
context.commit("changeStage", constants.WORK_STAGE);
},
breakStage(context) {
context.commit("changeStage", constants.BREAK_STAGE);
},
longBreakStage(context) {
context.commit("changeStage", constants.LONG_BREAK_STAGE);
},
incrementCycles({ commit, state }) {
commit("changeCycles", state.countCycles + 1);
},
resetCycles({ commit }) {
commit("changeCycles", 0);
}
};
const getters = {
isWorkStage: state => state.stage === constants.WORK_STAGE,
isBreakStage: state => state.stage === constants.BREAK_STAGE,
isLongBreakStage: state => state.stage === constants.LONG_BREAK_STAGE
};
const module = {
state: initialState,
mutations: mutations,
actions: actions,
getters: getters
};
export default module;
<file_sep>import Vue from "vue";
import Vuex from "vuex";
import PomodoroSettings from "./modules/PomodoroSettings";
import Pomodoro from "./modules/Pomodoro";
Vue.use(Vuex);
export const appStore = {
modules: {
// All modules should have namespaced: true
PomodoroSettings: { namespaced: true, ...PomodoroSettings },
Pomodoro: { namespaced: true, ...Pomodoro }
}
};
export default new Vuex.Store(appStore);
<file_sep>/// This file contains utility functions for use in tests.
import { appStore } from "@/store";
import { render } from "@testing-library/vue";
/// Sleep for a given timer.
export const sleep = milliseconds => {
return new Promise(resolve => setTimeout(resolve, milliseconds));
};
export const renderComponent = function(component, customState = {}) {
return render(component, {
store: {
...appStore,
modules: { ...appStore.modules, ...customState }
}
});
};
<file_sep>/// This file contains unit tests for the Pomodoro component
import PomodoroComponent from "@/components/Pomodoro.vue";
import { fireEvent, wait } from "@testing-library/vue";
import { expect } from "chai";
import Vue from "vue";
import PomodoroModuleInitial, {
constants
} from "../../src/store/modules/Pomodoro";
import PomodoroSettingsModuleInitial from "../../src/store/modules/PomodoroSettings";
import { renderComponent, sleep } from "../_utils";
describe("Pomodoro", function() {
let createInitialState;
let state;
let renderPomodoroComponent;
beforeEach(() => {
// This is for test isolation.
createInitialState = (pomodoroState = {}, pomodoroSettingsState = {}) => ({
Pomodoro: {
namespaced: true,
...PomodoroModuleInitial,
state: {
...PomodoroModuleInitial.state,
...pomodoroState
}
},
PomodoroSettings: {
namespaced: true,
...PomodoroSettingsModuleInitial,
state: {
...PomodoroSettingsModuleInitial.state,
...pomodoroSettingsState
}
}
});
state = createInitialState(
{ stage: constants.WORK_STAGE },
{ workTime: 30, breakTime: 5, longBreakTime: 15 }
);
renderPomodoroComponent = function(customState = state) {
return renderComponent(PomodoroComponent, {
...customState
});
};
});
it("Advances to break stage after a work stage", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent();
const startButton = getByText(/Start/i).closest("button");
fireEvent.click(startButton);
await Vue.nextTick();
const timerDisplay = getByTestId("timer-display");
const skipButton = getByText(/Skip/i).closest("button");
// Act
fireEvent.click(skipButton);
await Vue.nextTick();
// Assert
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("05:00");
});
it("Advances to work stage after a break stage", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.BREAK_STAGE
},
{ workTime: 30, breakTime: 5, longBreakTime: 15 }
)
);
const startButton = getByText(/Start/i).closest("button");
fireEvent.click(startButton);
await Vue.nextTick();
const timerDisplay = getByTestId("timer-display");
const skipButton = getByText(/Skip/i).closest("button");
// Act
fireEvent.click(skipButton);
await Vue.nextTick();
// Assert
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("30:00");
});
it("Advances to long break stage after 3 work stages", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent();
const timerDisplay = getByTestId("timer-display");
const clickStartAndSkip = async function() {
const startButton = getByText(/Start/i).closest("button");
//..Click start
fireEvent.click(startButton);
await Vue.nextTick();
const skipButton = getByText(/Skip/i).closest("button");
//..Click skip
fireEvent.click(skipButton);
await Vue.nextTick();
};
const skipOneCycle = async function() {
//..Work Stage
await clickStartAndSkip();
//..Break Stage
await clickStartAndSkip();
};
// Act
//..After 3 Work/Break cycles
await skipOneCycle();
await skipOneCycle();
await skipOneCycle();
//..Skip a Work Stage
await clickStartAndSkip();
// Assert
const timerDisplayValue = timerDisplay.innerHTML;
//..Should be long break
expect(timerDisplayValue).to.equal("15:00");
});
// This test is broken
it("Autostarts the next session", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.WORK_STAGE
},
{
workTime: 30,
breakTime: 5,
longBreakTime: 15,
autoStartNextSession: true
}
)
);
const clickStartAndSkip = async function() {
const startButton = getByText(/Start/i).closest("button");
//..Click start
await fireEvent.click(startButton);
await Vue.nextTick();
const skipButton = getByText(/Skip/i).closest("button");
//..Click skip
await fireEvent.click(skipButton);
await Vue.nextTick();
};
const skipOneCycle = async function() {
//..Work Stage
await clickStartAndSkip();
//..Break Stage
await clickStartAndSkip();
};
// Act
await skipOneCycle();
await sleep(1001);
// Assert
const timerDisplay = getByTestId("timer-display");
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("29:59");
});
it("Autostarts the break", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.WORK_STAGE
},
{
workTime: 30,
breakTime: 5,
longBreakTime: 15,
autoStartBreak: true
}
)
);
const clickStartAndSkip = async function() {
const startButton = getByText(/Start/i).closest("button");
//..Click start
await fireEvent.click(startButton);
await Vue.nextTick();
const skipButton = getByText(/Skip/i).closest("button");
//..Click skip
await fireEvent.click(skipButton);
await Vue.nextTick();
};
// Act
//..Work Stage
await clickStartAndSkip();
// Assert
await wait(
() => {
//..Break Stage
const timerDisplay = getByTestId("timer-display");
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("04:59");
},
{ timeout: 1500 }
);
});
it("Counts up", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.WORK_STAGE
},
{
workTime: 30,
breakTime: 5,
longBreakTime: 15,
countUpwards: true
}
)
);
// Act
const startButton = getByText(/Start/i).closest("button");
//..Click start
await fireEvent.click(startButton);
// Assert
const timerDisplay = getByTestId("timer-display");
await wait(
() => {
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("00:01");
},
{ timeout: 1500 }
);
});
it("Counts up on break stage", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.BREAK_STAGE
},
{
workTime: 30,
breakTime: 5,
longBreakTime: 15,
countUpwardsBreak: true
}
)
);
// Act
const startButton = getByText(/Start/i).closest("button");
//..Click start
await fireEvent.click(startButton);
// Assert
const timerDisplay = getByTestId("timer-display");
await wait(
() => {
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("00:01");
},
{ timeout: 1500 }
);
});
it("Counts upon long break stage", async function() {
// Arrange
const { getByTestId, getByText } = renderPomodoroComponent(
createInitialState(
{
stage: constants.LONG_BREAK_STAGE
},
{
workTime: 30,
breakTime: 5,
longBreakTime: 15,
countUpwardsBreak: true
}
)
);
// Act
const startButton = getByText(/Start/i).closest("button");
//..Click start
await fireEvent.click(startButton);
// Assert
const timerDisplay = getByTestId("timer-display");
await wait(
() => {
const timerDisplayValue = timerDisplay.innerHTML;
expect(timerDisplayValue).to.equal("00:01");
},
{ timeout: 1500 }
);
});
});
| fefaad74b1c34d17c28b1a29b0625531bdba03f1 | [
"JavaScript"
] | 5 | JavaScript | KaiPrince/Pomodoro-Timer | 82d73c1182fe5651fb1610b4ba9de3e66bdd3095 | 2631e077e0cc6a5ddfc2caa813f39e1e87cd20f9 |
refs/heads/master | <repo_name>chnzhangrui/iDDS<file_sep>/atlas/lib/idds/atlas/processing/hyperparameteropt_condor_submitter.py
#!/usr/bin/env python
#
# 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.0OA
#
# Authors:
# - <NAME>, <<EMAIL>>, 2020
"""
Class of activelearning condor plubin
"""
import os
import json
import traceback
from idds.common import exceptions
from idds.common.constants import ContentStatus, ProcessingStatus
from idds.common.utils import replace_parameters_with_values
from idds.atlas.processing.condor_submitter import CondorSubmitter
from idds.core import (catalog as core_catalog)
class HyperParameterOptCondorSubmitter(CondorSubmitter):
def __init__(self, workdir, **kwargs):
super(HyperParameterOptCondorSubmitter, self).__init__(workdir, **kwargs)
if not hasattr(self, 'max_unevaluated_points'):
self.max_unevaluated_points = 1
if not hasattr(self, 'min_unevaluated_points'):
self.min_unevaluated_points = 1
def __call__(self, processing, transform, input_collection, output_collection):
try:
contents = core_catalog.get_contents_by_coll_id_status(coll_id=output_collection['coll_id'])
points = []
unevaluated_points = 0
for content in contents:
point = content['content_metadata']['point']
points.append(point)
if not content['status'] == ContentStatus.Available:
unevaluated_points += 1
if unevaluated_points >= self.min_unevaluated_points:
# not submit the job
processing_metadata = processing['processing_metadata']
processing_metadata['unevaluated_points'] = unevaluated_points
ret = {'processing_id': processing['processing_id'],
'status': ProcessingStatus.New,
'processing_metadata': processing_metadata}
return ret
job_dir = self.get_job_dir(processing['processing_id'])
input_json = 'idds_input.json'
with open(os.path.join(job_dir, input_json), 'w') as f:
json.dump(points, f)
sandbox = None
if 'sandbox' in transform['transform_metadata']:
sandbox = transform['transform_metadata']['sandbox']
executable = transform['transform_metadata']['executable']
arguments = transform['transform_metadata']['arguments']
output_json = None
if 'output_json' in transform['transform_metadata']:
output_json = transform['transform_metadata']['output_json']
param_values = {'NUM_POINTS': self.max_unevaluated_points - unevaluated_points,
'IN': 'input_json',
'OUT': output_json}
executable = replace_parameters_with_values(executable, param_values)
arguments = replace_parameters_with_values(arguments, param_values)
input_list = None
job_id, outputs = self.submit_job(processing['processing_id'], sandbox, executable, arguments, input_list, input_json, output_json)
processing_metadata = processing['processing_metadata']
processing_metadata['job_id'] = job_id
processing_metadata['submitter'] = self.name
if not job_id:
processing_metadata['submit_errors'] = outputs
else:
processing_metadata['submit_errors'] = None
ret = {'processing_id': processing['processing_id'],
'status': ProcessingStatus.Submitted,
'processing_metadata': processing_metadata}
return ret
except Exception as ex:
self.logger.error(ex)
self.logger.error(traceback.format_exc())
raise exceptions.AgentPluginError('%s: %s' % (str(ex), traceback.format_exc()))
<file_sep>/main/lib/idds/tests/datacarousel_test.py
#!/usr/bin/env python
#
# 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.0OA
#
# Authors:
# - <NAME>, <<EMAIL>>, 2019
"""
Test client.
"""
from idds.client.client import Client
from idds.common.constants import RequestType, RequestStatus
from idds.common.utils import get_rest_host
# from idds.tests.common import get_example_real_tape_stagein_request
# from idds.tests.common import get_example_prodsys2_tape_stagein_request
def get_req_properties():
req_properties = {
'scope': 'data16_13TeV',
'name': 'data16_13TeV.00298862.physics_Main.daq.RAW',
'requester': 'panda',
'request_type': RequestType.StageIn,
'transform_tag': 'prodsys2',
'status': RequestStatus.New,
'priority': 0,
'lifetime': 30,
'request_metadata': {'workload_id': '20776840', 'src_rse': 'NDGF-T1_DATATAPE', 'rule_id': '236e4bf87e11490291e3259b14724e30'}
}
return req_properties
host = get_rest_host()
props = get_req_properties()
# props = get_example_real_tape_stagein_request()
# props = get_example_prodsys2_tape_stagein_request()
# props = get_example_active_learning_request()
client = Client(host=host)
request_id = client.add_request(**props)
print(request_id)
| 29f5d96081ae0beab7ac9ca15e9e50bd2d7b98da | [
"Python"
] | 2 | Python | chnzhangrui/iDDS | 4eb478e61da09d8d7fcffcd2e3c7a599f755205c | 73ff30aee7a49b88e563f42a9be7e607d8eaaf4d |
refs/heads/master | <repo_name>cjbreaux/park<file_sep>/js/scripts.js
$(document).ready(function() {
var meters = parseFloat(prompt("What is your height in Meters?"));
if (meters >= 1.8) {
$(".big").show();
$(".medium").show();
$(".small").show();
$("img").addClass("border");
}
if (meters < 1.8 && meters >= 1.2) {
$(".medium").show();
$(".small").show();
$(".medium img").addClass("border");
$(".small img").addClass("border");
}
if (meters <1.2) {
$(".small").show();
$(".small img").addClass("border");
}
});
| 1a7eb65ee1c2244280cffac398d950291c03647c | [
"JavaScript"
] | 1 | JavaScript | cjbreaux/park | 0623e0b9e7d84485d01dba09b46f5b04d12b2aa3 | 20b31fa86fb04c5f316485f8a55cc90b3396d17a |
refs/heads/master | <file_sep>class Meal {
constructor(id, categoryId, title, affordability, complexity, imageUrl, duration, ingredients, steps, isGlutenFree, isVegan, isVegetarian, isLactoseFree) {
this.id = id
}
}
export default Meal;
| 6c7292605f655eeb2b0e689ce8742db53cf15b90 | [
"JavaScript"
] | 1 | JavaScript | bart-antczak/ReactNativeMealsApp | 02cf0e9e3bca3f877d95c9b2d48103a5862ddba3 | 2272a9792e51d3bb4cd7e9023a8832db9c3ab923 |
refs/heads/master | <file_sep>#pragma once
#include"Empleado.h"
#include <fstream>
class ListaEmpleados
{
private:
Empleado* primero;
Empleado* ultimo;
public:
ListaEmpleados();
~ListaEmpleados();
//funciones
bool isEmpty();
bool search(int r);
void agregar(int c, string n, float s, bool a);
void imprimirEmpleado();
void actualizarSalario(float s);
void dasctivarEmpleado(int r);
void eliminarEmpleado(int r);
void guardarEmpleados();
};
<file_sep>#pragma once
#include <string>
#include<iostream>
using namespace std;
class Empleado
{
private:
int cod_emp;
string nom_emp;
float salario;
bool activo;
Empleado* siguiente;
Empleado* anterior;
public:
Empleado();
~Empleado();
//setters
void setCodigo(int c);
void setNombre(string n);
void setSalario(float s);
void setActivo(bool a);
void setSiguiente(Empleado* s);
void setAnterior(Empleado* a);
//funciones
void imprimir();
//
int getCodigo();
string getNombre();
float getSalario();
bool getActivo();
Empleado* getSiguiente();
Empleado* getAnterior();
};
<file_sep>#include "Empleado.h"
Empleado::Empleado()
{
cod_emp = 0;
nom_emp = "";
salario = 0;
activo = false;
siguiente = nullptr;
anterior = nullptr;
}
Empleado::~Empleado()
{
}
void Empleado::setCodigo(int c)
{
cod_emp = c;
}
void Empleado::setNombre(string n)
{
nom_emp = n;
}
void Empleado::setSalario(float s)
{
salario = s;
}
void Empleado::setActivo(bool a)
{
activo = a;
}
void Empleado::setSiguiente(Empleado* s)
{
siguiente = s;
}
void Empleado::setAnterior(Empleado* a)
{
anterior = a;
}
void Empleado::imprimir()
{
cout << "Codigo de empleado: " << cod_emp << " Nombre de empleado: " << nom_emp << " Salario: " << salario<<endl;
}
int Empleado::getCodigo()
{
return cod_emp;
}
string Empleado::getNombre()
{
return nom_emp;
}
float Empleado::getSalario()
{
return salario;
}
bool Empleado::getActivo()
{
return activo;
}
Empleado* Empleado::getSiguiente()
{
return siguiente;
}
Empleado* Empleado::getAnterior()
{
return anterior;
}
<file_sep>#include <iostream>
#include"ListaEmpleados.h"
using namespace std;
int main(){
ListaEmpleados* l = new ListaEmpleados();
l->agregar(2, "hollaadsjsadsa", 200, true);
l->agregar(3, "hollaadsjsadsa", 200, true);
l->agregar(4, "hollaadsjsadsa", 200, true);
l->imprimirEmpleado();
l->dasctivarEmpleado(3);
l->imprimirEmpleado();
return 0;
}<file_sep>#include "ListaEmpleados.h"
ListaEmpleados::ListaEmpleados()
{
primero = nullptr;
ultimo = nullptr;
}
ListaEmpleados::~ListaEmpleados()
{
}
bool ListaEmpleados::isEmpty()
{
return primero == nullptr;
}
bool ListaEmpleados::search(int r)
{
if (primero == nullptr)
return false;
Empleado* aux = primero;
while ((aux->getSiguiente() != primero) && (!(aux->getCodigo() == r)))
aux = aux->getSiguiente();
return aux->getCodigo() == r;
}
void ListaEmpleados::agregar(int c, string n, float s, bool a)
{
if (search(c))
return;
//agregar
Empleado* nuevo = new Empleado();
nuevo->setCodigo(c);
nuevo->setNombre(n);
nuevo->setSalario(s);
nuevo->setActivo(a);
if (isEmpty()) {
primero = nuevo;
ultimo = nuevo;
primero->setSiguiente(ultimo);
ultimo->setAnterior(primero);
}
else {
ultimo->setSiguiente(nuevo);
nuevo->setAnterior(ultimo);
ultimo = nuevo;
ultimo->setSiguiente(primero);
primero->setAnterior(ultimo);
}
}
void ListaEmpleados::imprimirEmpleado()
{
if (isEmpty())
{
cout << "Sin elementos" << endl;
}
else {
Empleado* aux = primero;
do
{
if(aux->getActivo())
aux->imprimir();
aux = aux->getSiguiente();
} while (aux != primero);
}
}
void ListaEmpleados::actualizarSalario(float s)
{
if (!(isEmpty())) {
Empleado* aux = primero;
while (aux != primero) {
if (s > 0 && s <= 1) {
float t = aux->getSalario() + s * aux->getSalario();
aux->setSalario(t);
}
else {
cout << "Incremento no valido" << endl;
}
aux = aux->getSiguiente();
}
}
}
void ListaEmpleados::dasctivarEmpleado(int r)
{
if (!(isEmpty())) {
Empleado* aux = primero;
do {
if (aux->getCodigo() == r)
aux->setActivo(false);
aux = aux->getSiguiente();
} while (aux != primero);
}
}
void ListaEmpleados::eliminarEmpleado(int r)
{
if (!(isEmpty())) {
Empleado* aux = primero;
do {
if (!(isEmpty())) {
if (aux->getCodigo() == r) {
if (aux == primero) {
primero = aux->getSiguiente();
primero->setAnterior(ultimo);
ultimo->setSiguiente(primero);
delete aux;
}
else if (aux = ultimo) {
ultimo = aux->getAnterior();
ultimo->setSiguiente(primero);
primero->setAnterior(ultimo);
delete aux;
}
else {
aux->getAnterior()->setSiguiente(aux->getSiguiente());
aux->getSiguiente()->setAnterior(aux->getAnterior());
}
}
aux = aux->getSiguiente();
}
} while (aux != primero);
}
}
void ListaEmpleados::guardarEmpleados()
{
Empleado* aux = primero;
do {
if (aux->getActivo() == true) {
ofstream of("RRHH.dat", ios::out | ios::binary);
if (!of) {
cout << "Error al intentar abrir archivo\n";
return;
}
of.write(reinterpret_cast<const char*>(&aux), sizeof(of));
aux = aux->getSiguiente();
}
else {
aux = aux->getSiguiente();
}
} while (aux != primero);
}
| 91220f890514419f117fb68a6f77923871d79590 | [
"C++"
] | 5 | C++ | marlonavila12/EvamenII_Marlon_Avila | 707e13990d1609dab4fbe8e3b38f502dc5edf104 | c1af83bf0f50b4cd9ac70abddcae0881be9a1440 |
refs/heads/master | <file_sep>package co.nilin.spring.cloud.consulall.Controller;
import co.nilin.spring.cloud.consulall.utils.MyProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@EnableFeignClients
public class DistributedPropertiesController {
@Value("${my.prop}")
String value;
@Autowired
private MyProperties properties;
@GetMapping("/getConfigFromValue")
public String getConfigFromValue(){
return value;
}
@GetMapping("/getConfigFromProperty")
public String getConfigFromProperty(){
return properties.getProp();
}
}
<file_sep>spring.application.name=myApp
spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
debug=true
server.port=8082
logging.level.org.springframework=DEBUG
spring.cloud.consul.config.enabled=true
spring.cloud.consul.discovery.instanceId=${spring.application.name}:${random.value}
spring.cloud.consul.discovery.serviceName=${spring.application.name}
spring.cloud.consul.discovery.healthCheckPath= /my-health-check
spring.cloud.consul.discovery.healthCheckInterval= 20s
| 61b433e08041078999d8ebe4d565d96605ae5087 | [
"Java",
"INI"
] | 2 | Java | MostafaTahery/consul-all | 9e1ae7571b58f6766f1d8b55ae64100a0fc3f0f7 | cd1eefd9304c9906e6dbec6d1b92f1d81cb8088a |
refs/heads/master | <file_sep><?php
error_reporting("E_ALL");
ini_set("display_errors", 1);
if(isset($_POST["intializare"])){
require_once("mysql.php");
$sql_preia = "SELECT description, lat, lng FROM incident_reports";
$res_preia = mysqli_query($con, $sql_preia);
$results="";
while($row_preia = mysqli_fetch_array($res_preia)){
$results = $row_preia[0]."|".$row_preia[1]."|".$row_preia[2]."*".$results;
}
echo $results;
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<title>Incident Reporting System</title>
<?php include "functions.php"; include "mysql.php"; ?>
<?php head(); ?>
</head>
<body>
<?php
meniu();
?>
<div class="row">
<div class="col-md-12">
<?php
$sql = "SELECT * FROM incident_reports";
$res = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($res)){
?>
<div class="row incidente">
<div class="col-md-6">
<div class="type"><h3><?php echo $row["type"] ?></h3></div><br><hr><br>
<div class="description"><?php echo $row["description"] ?></div>
<div class="date_reported"><?php echo $row["date_reported"] ?></div>
</div>
<div class="col-md-6">
<?php if(!empty($row["image_path"])): ?><div class="imagine"><img src="<?php echo BASE_URL.$row["image_path"]; ?>" style="width:100%"></div><?php endif; ?>
</div>
</div>
<?php
}
?>
</div>
</div>
</body>
</html><file_sep><?php
function head(){
define("BASE_URL", "http://localhost/incident_reporting_system/");
?>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="js/jquery-ui-1.11.0.custom/jquery-ui-1.11.0.custom/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery-ui-1.11.0.custom/jquery-ui-1.11.0.custom/jquery-ui.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
<?php
}
function meniu(){
?>
<div class="row">
<div class="col-md-12 preheader">
©By <NAME>
</div>
</div>
<nav class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">
<img alt="incindent-reporting-system" src="">
</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href="list_view.php">List view</a></li>
<li><a href="report_incident.php">Report an Incident</a></li>
</ul>
</div>
</nav>
<?php
}
function footer(){
?>
<div class="row row-footer">
<div class="col-md-12 preheader">
©By <NAME>
</div>
</div>
<?php
}
?><file_sep><?php
include "mysql.php";
//preluam datele de la aplicatia Android in variabilele $_POST si $_FILE
$email = $_POST["email"];
$incidentType = $_POST["incidentType"];
$description = $_POST["description"];
$lat = $_POST["lat"];
$lng = $_POST["lng"];
$date_reported = date("Y-m-d h:i:s");
echo "email = ".$_POST["email"]." description = ".$_POST["description"];
var_dump($_POST);
$ok_fisier = 1;
if($_FILES["imagineIncident"]["error"]===UPLOAD_ERR_OK){
$destination = "IncidentImages/".$_FILES["imagineIncident"]["name"];
if(move_uploaded_file($_FILES["imagineIncident"]["tmp_name"], $destination)) //copiez poza la destinatia dorita
echo "SUCCES!";
else
{
$ok_fisier=0;
echo "Eroare la move_uploaded_file";
}
if($ok_fisier===1){
//introducem datele in baza de date - aici sa fac cu prepared statements (TO_DO)
$sql = "INSERT INTO incident_reports SET user_email = '{$email}', description = '{$description}', type = '{$incidentType}', lat = '{$lat}', lng = '{$lng}',
image_path='{$destination}', date_reported ='{$date_reported}'";
if(mysqli_query($con,$sql)===FALSE){
echo "Eroare la inserare in baza de date ".$sql;
}
}
}
else
echo "Fisierul contine erori ".$_FILES["imagineIncident"]["error"];
?><file_sep><?php
include "mysql.php";
$lat = $_POST["lat"];
$lng = $_POST["lng"];
$lat_lower = $lat - 10;
$lat_upper = $lat + 10;
$lng_lower = $lng - 10;
$lng_upper = $lng + 10;
//var_dump($_POST);
$sql = "SELECT lat, lng, type, description FROM incident_reports WHERE (lat >= $lat_lower AND lat <= $lat_upper) AND (lng >= $lng_lower AND lng <= $lng_upper)";
$res = mysqli_query($con, $sql);
$toSend = array();
while($row = mysqli_fetch_assoc($res)){
array_push($toSend, array("lat"=>$row["lat"], "lng"=>$row["lng"], "type"=>$row["type"], "description"=>$row["description"]));
}
echo json_encode(array("result"=>$toSend));
?><file_sep><!DOCTYPE html>
<html>
<head>
<title>Incident Reporting System</title>
<?php include "functions.php"; include "mysql.php"; ?>
<?php head(); ?>
</head>
<body>
<?php
meniu();
?>
<div class="row report">
<div class="col-md-6 report-incident">
<?php
if(isset($_GET["lat"]) && isset($_GET["lng"])){
echo "<input type='hidden' name='lat' value='".$_GET["lat"]."'>";
echo "<input type='hidden' name='lng' value='".$_GET["lng"]."'>";
}
if(isset($_POST["send"])){
$country = $_POST["country"];
$city = $_POST["city"];
$address = implode("+", explode(" ", $_POST["address"]));
$type= mysqli_real_escape_string($con, $_POST["type"]);
$date_reported = mysqli_real_escape_string($con, $_POST["date"]);
$user_email = mysqli_real_escape_string($con, $_POST["user_email"]);
$description = mysqli_real_escape_string($con, $_POST["description"]);
//toate campurile sunt obligatorii
//verificari
$err_country=0; $err_city=0; $err_address=0; $err_type=0; $err_date_reported=0; $err_user_email=0; $err_description=0;
if(empty($country))
$err_country="Country cannot be empty.";
if(empty($city))
$err_city="City cannot be empty.";
if(empty($_POST["address"]))
$err_address="Address cannot be empty.";
if(empty($type))
$err_type="Type cannot be empty.";
if(empty($date_reported))
$err_date_reported="Date reported cannot be empty.";
if(empty($user_email))
$err_user_email="User email cannot be empty.";
if(empty($description))
$err_description="Description cannot be empty.";
if(!empty($err_country) || !empty($err_city) || !empty($err_address) || !empty($err_date_reported) || !empty($err_user_email) || !empty($err_description)){
?>
<div class="alert alert-danger alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>There are errors!</strong><br>
<?php
if(!empty($err_country)) echo $err_country."<br>";
if(!empty($err_city)) echo $err_city."<br>";
if(!empty($err_address)) echo $err_address."<br>";
if(!empty($err_date_reported)) echo $err_date_reported."<br>";
if(!empty($err_user_email)) echo $err_user_email."<br>";
if(!empty($err_description)) echo $err_description."<br>";
?>
</div>
<?php
}
else{
//trimit url
$final_address = $country."+".$city."+".$address;
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$final_address&key=<KEY>";
//echo $url;
$json = file_get_contents($url);
$response = json_decode($json);
$lat = $response->results[0]->geometry->location->lat;
$lng = $response->results[0]->geometry->location->lng;
//introduc chestiile in baza de date
$sql_insert = "INSERT INTO incident_reports SET lat=".$lat.", lng=".$lng.", type='{$type}', description='{$description}',
user_email='{$user_email}', date_reported='{$date_reported}'";
if(mysqli_query($con, $sql_insert)===FALSE){
?>
<div class="alert alert-danger alert-dismissable">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>There are errors!</strong> Please resend form.
</div>
<?php
}
else
{
//trimit mail la admin
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: Incident Reporting System <<EMAIL>>' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail("<EMAIL>", "A FOST RAPORTAT UN INCIDENT", "Adresa: ".$country." ".$city." ".$address." Tip incident: ".$type." Raportat la data de ".$date_reported." de catre ".$user_email, $headers);
header("Location:".BASE_URL."report_incident.php?lat=".$lat."&lng=".$lng);
}
} //de la else
} //de la if isset POST
?>
<h3>Report an incident</h3><br>
<form name="report-form" class="report-form" method="POST" action="">
<label for="user_email">User Email</label>
<input type="text" name="user_email" id="address" class="form-control"><br>
<label for="country">Country</label><br>
<select name="country" id="country" class="form-control">
<option value="Iceland">Iceland</option>
<option value="France">France</option>
<option value="England">England</option>
<option value="Romania">Romania</option>
</select><br>
<label for="city">City</label>
<input type="text" name="city" id="city" class="form-control">
<br>
<label for="address">Address</label>
<input type="text" name="address" id="address" class="form-control">
<br>
<label for="type">Type</label>
<select name="type" id="type" class="form-control">
<option value="fire">Fire</option>
<option value="pollution">Pollution source</option>
<option value="jam">Traffic jam</option>
</select>
<br>
<label for="description">Description</label>
<input type="text" name="description" id="description" class="form-control">
<br>
<label for="date">Date</label>
<input type="text" name="date" id="date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
<br>
<input type="submit" name="send" id="send" value="Add incident" class="btn btn-default">
</form>
</div>
<div class="col-md-6 report-map" style="height: 600px">
<div class="row row-map" id="map" style="height: 500px; position: absolute!important; width: 95%; top: 50%; transform: translateY(-50%);">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap">
</script>
</div>
</div>
</div>
<?php footer(); ?>
</body>
</html>
<script>
$( function() {
$( "#date" ).datepicker({ dateFormat: 'dd-mm-yy' });
} );
function initMap() {
//verific daca am ceva in inputuri
if($("input[name='lat']").val() && $("input[name='lng']").val()){
var lat_helper = $("input[name='lat']").val();
var lng_helper = $("input[name='lng']").val();
var myLatLng = {lat: lat_helper, lng:lng_helper};
}
else
var myLatLng = {lat: -20, lng: 67};
console.log("myLatLng: "+lat_helper+" "+lng_helper);
$.ajax({
url:"ajaxMap.php",
type:"POST",
data:{intializare:1},
success:function(response){
var responses_helper = response.split('*');
responses_helper = responses_helper.filter(function(n){ return n != "" }); //filtrez valori nule
var responses = new Array();
var k=0;
for(var i=0; i<responses_helper.length; i++){
pieces = responses_helper[i].split('|');
responses[k] = new Array(pieces[0], pieces[1], pieces[2]); //description, latitude, longitude
k++;
}
if($("input[name='lat']").val() && $("input[name='lng']").val()){
var lat_helper = $("input[name='lat']").val();
var lng_helper = $("input[name='lng']").val();
var valoriCentru = new google.maps.LatLng(lat_helper, lng_helper);
}
else
var valoriCentru = new google.maps.LatLng(responses[0][1], responses[0][2]);
console.log(responses[0][1]+" "+responses[0][2]);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: valoriCentru
});
for(var i=0; i<responses.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(responses[i][1], responses[i][2]),
map: map,
title: responses[i][0] //descrierea
});
}
}
});
}
</script>
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Incident Reporting System</title>
<?php include "functions.php"; ?>
<?php head(); ?>
</head>
<body>
<?php
meniu();
?>
<!--imagine_faina-->
<div class="row" style="height: 75%; position: relative;">
<div class="col-md-12 title-inner">
<div class="title">
Information Reporting System<br>
<i>Take action. Build a better world.</i>
</div>
</div>
</div>
<div class="jumbotron">
<h1>Make the world safer. Add a report.</h1>
<p>Add a report to let everybody know if there's a fire or a pollution source. You can also use our <b><i>Android app</i></b> to submit a report whenever you observe something is wrong!</p>
<p><a class="btn btn-primary btn-lg" href="report_incident.php" role="button">Add a Report</a></p>
</div>
<div class="row row-map" id="map">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap">
</script>
</div>
<div class="jumbotron">
<h1>And there's more...</h1>
<p>View all the submited reports in List View or Map View.</p>
<p><a class="btn btn-primary btn-lg" href="list_view" role="button">List view</a></p>
</div>
<?php footer(); ?>
</body>
</html>
<script>
function initMap() {
$.ajax({
url:"ajaxMap.php",
type:"POST",
data:{intializare:1},
success:function(response){
var responses_helper = response.split('*');
responses_helper = responses_helper.filter(function(n){ return n != "" }); //filtrez valori nule
var responses = new Array();
var k=0;
for(var i=0; i<responses_helper.length; i++){
pieces = responses_helper[i].split('|');
responses[k] = new Array(pieces[0], pieces[1], pieces[2]); //description, latitude, longitude
k++;
}
var valoriCentru = new google.maps.LatLng(responses[0][1], responses[0][2]);
console.log(responses[0][1]+" "+responses[0][2]);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: valoriCentru
});
for(var i=0; i<responses.length; i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(responses[i][1], responses[i][2]),
map: map,
title: responses[i][0] //descrierea
});
}
}
});
}
</script> | 3bb956af76793ba122f757e269ba088988a3e501 | [
"PHP"
] | 7 | PHP | IuliaRadulescu/IncidentReportingSystemWeb | 39853c6b076948dd24edf31cc46ac1965d5d818e | d480f9f4bec511aa5713da8197b2dd6956894aa2 |
refs/heads/master | <file_sep># FanSourceVR
A React VR app that shows different angles of a sporting event with video panels
This was all built for the 2018 SXSW Hackathon
## Team Members
- Developer: <NAME>
- Designer <NAME>
- Designer: <NAME>
## See What We Built!
- [Virtual Reality](http://fan-source-vr.surge.sh/)
- [Facebook Live Feed](http://fan-source-live.surge.sh/)
## Screenshots




<file_sep>this is a copy of ../static_assets
for surge to recognize static_assets they need to be in the vr directory
Doing a symlink doesn't work for some reason<file_sep>import React, { Component } from 'react';
class FacebookVideo extends Component {
render() {
return (
<div className="fb-video" data-href={this.props.videoURL} data-width="500" data-show-text="false">
<div className="fb-xfbml-parse-ignore">
<blockquote cite={this.props.videoURL}>
<a href={this.props.videoURL}>How to Share With Just Friends</a>
<p>How to share with just friends.</p>
Posted by <a href="https://www.facebook.com/facebook/">Facebook</a> on Friday, December 5, 2014
</blockquote>
</div>
</div>
);
}
}
export default FacebookVideo;
<file_sep>import React, { Component } from 'react';
import './App.css';
import FacebookVideo from './components/FacebookVideo'
class App extends Component {
constructor(props) {
super(props);
this.state = {videos: []}
}
componentDidMount() {
fetch("https://api.crowdtangle.com/posts/?listIds=554797&types=live_video,live_video_complete,live_video_scheduled&sortBy=date&token=<KEY>", {
headers: {
'content-type': 'application/json',
},
mode: 'cors',
})
.then(response => response.json())
.then(data => {
this.setState({
videos: data.result.posts
})
})
.catch(data => {
console.log('error', data)
});
}
render() {
let videos = [];
for (let i=0; i < this.state.videos.length; i++) {
videos.push(<FacebookVideo key={this.state.videos[i].link} videoURL={this.state.videos[i].link} />)
}
return (
<div className="App">
<h1>Fan Source VR</h1>
<div className="fb-live">
{videos}
</div>
</div>
);
}
}
export default App;
| b50b46e5d53efaf7abd55001081e65818993b003 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | pwgraham91/FanSourceVR | 8361e833fd4400d9b419ef70bc26661e7e844c31 | 6f8faafe13fce2645b97299d19cf002d9b04912d |
refs/heads/master | <repo_name>S1yu/ML<file_sep>/NN/LeNet.py
import torch
import torch.nn as nn
import torchvision
class LeNet(nn.Module):
def __init__(self):
super(LeNet,self).__init__()
self.conv=nn.Sequential(
nn.Conv2d(in_channels=1,out_channels=6,kernel_size=5,padding=2),
nn.Sigmoid(),
nn.MaxPool2d(kernel_size=2,stride=2),
nn.Conv2d(6,out_channels=16,kernel_size=5,),
nn.Sigmoid(),
nn.MaxPool2d(kernel_size=2,stride=2)
)
self.fc=nn.Sequential(
nn.Linear(in_features=16*5*5,out_features=120,),
nn.Sigmoid(),
nn.Linear(120,84),
nn.Sigmoid(),
nn.Linear(84, 10),
)
def forward(self, img):
feature = self.conv(img)
output = self.fc(feature.view(img.shape[0], -1))
return output
def load_data_fashion_mnist(batch_size):
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
mnist_train = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=True, download=False,
transform=transform)
mnist_test = torchvision.datasets.FashionMNIST(root='~/Datasets/FashionMNIST', train=False, download=False,
transform=transform)
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=0)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False, num_workers=0)
return train_iter, test_iter
def evaluate_accuracy(data_iter, net, device=None):
if device is None and isinstance(net, torch.nn.Module):
device = list(net.parameters())[0].device
acc_sum, n = 0.0, 0
with torch.no_grad():
for X, y in data_iter:
if isinstance(net, torch.nn.Module):
# set the model to evaluation mode (disable dropout)
net.eval()
# get the acc of this batch
acc_sum += (net(X.to(device)).argmax(dim=1) == y.to(device)).float().sum().cpu().item()
# change back to train mode
net.train()
n += y.shape[0]
return acc_sum / n
def train(net, train_iter, test_iter, optimizer, num_epochs):
net = net.to(torch.device("cpu"))
loss = nn.CrossEntropyLoss()
batch_count = 0
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, Y in train_iter:
X = X.to(torch.device("cpu"))
Y = Y.to(torch.device("cpu"))
y_hat = net(X)
l = loss(y_hat, Y)
optimizer.zero_grad()
l.backward()
optimizer.step()
train_l_sum += l.cpu().item()
train_acc_sum += (y_hat.argmax(dim=1) == Y).sum().cpu().item()
n += Y.shape[0]
batch_count += 1
test_acc = evaluate_accuracy(test_iter, net)
print(
f'epoch {epoch + 1} : loss {train_l_sum / batch_count:.3f}, train acc {train_acc_sum / n:.3f}, test acc {test_acc:.3f}')
if __name__ == '__main__':
bathc_size = 256
lr, num_epochs = 0.01, 10
net = LeNet()
opt = torch.optim.SGD(net.parameters(), lr=lr)
train_iter, test_iter = load_data_fashion_mnist(batch_size=bathc_size)
# train
train(net, train_iter, test_iter, opt, num_epochs)
<file_sep>/NN/MyDateSet.py
import numpy as np
from torch.utils.data.dataset import Dataset
class MyDataSet(Dataset):
def __init__(self, root, lable):
self.data = root
self.lable = lable
def __getitem__(self, item):
data = self.data[item]
lables = self.lable[item]
return data, lables
def __len__(self):
return len(self.data)
if __name__ == '__main__':
source = np.loadtxt("D:\project\IrisDateset\iris.csv", delimiter=",", usecols=(1, 2, 3, 4), skiprows=1)
print(source.shape)
<file_sep>/Tree/tree.py
import sklearn as sk
import numpy as np
import matplotlib.pyplot as plt
sk.tree.DecisionTreeRegressor(criterion="entropy")
| 2758fb4dd307e5bd810220e431230fb8e3519dd9 | [
"Python"
] | 3 | Python | S1yu/ML | 58b0820b71bb4c3fc3a136f1aeeab2c6e7d7199e | 11fc6180b82a9894a077eac0038d639db3fc793c |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Booking Perpus | Admin</title>
<link href="<?php echo base_url(); ?>assets/css/styles.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>assets/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="<?php echo base_url(); ?>assets/js/all.min.js" crossorigin="anonymous"></script>
<style media="screen">
body{
background-image: url("<?php echo base_url('assets/img/bg-main.png'); ?>");
background-size: cover;
position: relative;
}
</style>
</head>
<body class="sb-nav-fixed">
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<a class="navbar-brand" href="<?php echo base_url(); ?>">Administrator</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button>
<!-- Navbar-->
<ul class="navbar-nav ml-auto"></ul>
</nav>
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">Core</div>
<a class="nav-link active" href="<?php echo base_url(); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-users"></i></div>Pengguna
</a>
<a class="nav-link" href="<?php echo base_url('login/logout'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-sign-out-alt"></i></div>Keluar
</a>
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Logged in as:</div>
<?php echo $_SESSION['fn']; ?>
</div>
</nav>
</div>
<div id="layoutSidenav_content">
<main>
<div class="container-fluid">
<h1 class="mt-4"><i class="fas fa-users"></i> Manajemen Pengguna</h1>
<?php
if ($this->session->flashdata('err')) {
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Gagal!</strong> <?php echo $this->session->flashdata('err')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('warn')) {
?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Perhatian!</strong> <?php echo $this->session->flashdata('warn')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('succ')) {
?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Berhasil!</strong> <?php echo $this->session->flashdata('succ')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
?>
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#modalCreateTeacher"><i class="fas fa-asterisk"></i> Buat Akun Baru </button><br>
<div class="modal fade" id="modalCreateTeacher" tabindex="-1" role="dialog" aria-labelledby="modalCreateTeacherTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="<?php echo base_url('admin/createUserConfirm'); ?>" method="post">
<div class="modal-header">
<h5 class="modal-title" id="modalCreateTeacherTitle"><i class="fas fa-asterisk"></i> Create a new user</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label class="mb-1" for="unId"><i class="fas fa-user"></i> Username</label>
<input class="form-control py-4" id="unId" type="text" name="un" placeholder="Masukan Username User.." required/>
</div>
<div class="form-group">
<label class="mb-1" for="pwdId"><i class="fas fa-user-lock"></i> Password</label>
<input class="form-control py-4" id="pwdId" type="password" name="pwd" placeholder="Masukan Password Pengguna disini.." required/>
</div>
<div class="form-group">
<label class="mb-1" for="idnId"><i class="fas fa-user-lock"></i> Nomor Identifikasi</label>
<input class="form-control py-4" id="idnId" type="number" min="1" name="idn" placeholder="Masukan nomor ID Pengguna disini" required/>
</div>
<div class="form-group">
<label class="mb-1" for="fnId"><i class="fas fa-user"></i> Nama Penuh</label>
<input class="form-control py-4" id="fnId" type="text" name="fn" placeholder="Masukan Nama Penuh Pengguna" required/>
</div>
<div class="form-group">
<label class="mb-1" for="roleId"><i class="fas fa-flag"></i> Peran</label>
<select class="form-control" name="role" required>
<option value="">- Pilih Peran Pengguna.. -</option>
<option value="lo">Staff Perpustakaan</option>
<option value="cs">Mahasiswa</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-user-plus"></i> Create</button>
</div>
</form>
</div>
</div>
</div>
<ul class="nav nav-tabs" id="loTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="lo-tab" data-toggle="tab" href="#lo" role="tab" aria-controls="lo" aria-selected="true"><i class="fas fa-user-tie"></i> Staff Perpustakaan</a>
</li>
<li class="nav-item">
<a class="nav-link" id="cs-tab" data-toggle="tab" href="#cs" role="tab" aria-controls="cs" aria-selected="false"><i class="fas fa-user-graduate"></i> Mahasiswa</a>
</li>
</ul>
<div class="tab-content" id="loTabContent">
<div class="tab-pane fade show active" id="lo" role="tabpanel" aria-labelledby="lo-tab">
<div class="table-responsive mt-2">
<table class="table" id="dataTable" width="100%" cellspacing="0">
<thead class="thead-dark">
<tr>
<th>Username</th>
<th>Nomor Identifikasi</th>
<th>Nama Penuh</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Username</th>
<th>Nomor Identifikasi</th>
<th>Nama Penuh</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($dataUserLO as $row ): ?>
<tr>
<td><a href="#modalOfficerId<?php echo $row->id; ?>" data-toggle="modal" title="Click for details..."><?php echo $row->username; ?></a></td>
<td><?php echo $row->id_number; ?></td>
<td>
<?php echo $row->fullname; ?>
<a class="btn btn-danger btn-sm float-right" href="<?php echo base_url('admin/deleteUserConfirm/lo/').$row->id ?>" onclick="return confirm('Are you sure? This will be delete projects, student groups and phases in this account.')" title="Delete" role="button"><i class="fas fa-trash"></i></a>
</td>
<div class="modal fade" id="modalOfficerId<?php echo $row->id; ?>" tabindex="-1" role="dialog" aria-labelledby="modalOfficerId<?php echo $row->id; ?>Title" aria-hidden="true">
<div class="modal-dialog" role="document">
<form action="<?php echo base_url("admin/editUserConfirm/$row->id"); ?>" method="post">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalOfficerId<?php echo $row->id; ?>Title"><i class="fas fa-user-cog"></i> <?php echo $row->fullname; ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<input type="hidden" name="unOld" value="<?php echo $row->username; ?>" />
<div class="form-group">
<label class="mb-1" for="unId<?php echo $row->id ?>"><i class="fas fa-user"></i> Username</label>
<input class="form-control py-4" id="unId<?php echo $row->id ?>" type="text" name="un" value="<?php echo $row->username; ?>" required/>
</div>
<div class="form-group">
<label class="mb-1" for="pwdId<?php echo $row->id ?>"><i class="fas fa-user-lock"></i> Password</label>
<input type="hidden" name="oldPwd" value="<?php echo $row->password; ?>">
<input class="form-control py-4" id="pwdId<?php echo $row->id ?>" type="password" name="pwd" placeholder="Fill this input for renew password..."/>
</div>
<div class="form-group">
<label class="mb-1" for="idnId<?php echo $row->id ?>"><i class="fas fa-user"></i> Nomor Identifikasi</label>
<input class="form-control py-4" id="idnId<?php echo $row->id ?>" type="text" min="1" name="idn" value="<?php echo $row->id_number; ?>" required/>
</div>
<div class="form-group">
<label class="mb-1" for="fnId<?php echo $row->id ?>"><i class="fas fa-user"></i> Nama Penuh</label>
<input class="form-control py-4" id="fnId<?php echo $row->id ?>" type="text" name="fn" value="<?php echo $row->fullname; ?>" required/>
</div>
</div>
<div class="modal-footer">
<input type="text" name="role" value="lo" readonly hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
</div>
</div>
</form>
</div>
</div>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div class="tab-pane fade" id="cs" role="tabpanel" aria-labelledby="cs-tab">
<div class="table-responsive mt-2">
<table class="table" id="dataTableCS" width="100%" cellspacing="0">
<thead class="thead-dark">
<tr>
<th>Username</th>
<th>Nomor Identifikasi</th>
<th>Nama Penuh</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Username</th>
<th>Nomor Identifikasi</th>
<th>Nama Penuh</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($dataUserCS as $row ): ?>
<tr>
<td><a href="#modalStudentId<?php echo $row->id; ?>" data-toggle="modal" title="Click for details..."><?php echo $row->username; ?></a></td>
<td><?php echo $row->id_number; ?></td>
<td>
<?php echo $row->fullname; ?>
<a class="btn btn-danger btn-sm float-right" href="<?php echo base_url('admin/deleteUserConfirm/cs/').$row->id ?>" onclick="return confirm('Are you sure? This will be delete projects, student groups and phases in this account.')" title="Delete" role="button"><i class="fas fa-trash"></i></a>
</td>
<div class="modal fade" id="modalStudentId<?php echo $row->id; ?>" tabindex="-1" role="dialog" aria-labelledby="modalStudentId<?php echo $row->id; ?>Title" aria-hidden="true">
<div class="modal-dialog" role="document">
<form action="<?php echo base_url("admin/editUserConfirm/$row->id"); ?>" method="post">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalStudentId<?php echo $row->id; ?>Title"><i class="fas fa-user-cog"></i> <?php echo $row->fullname; ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<input type="hidden" name="unOld" value="<?php echo $row->username; ?>" />
<div class="form-group">
<label class="mb-1" for="unId<?php echo $row->id ?>"><i class="fas fa-user"></i> Username</label>
<input class="form-control py-4" id="unId<?php echo $row->id ?>" type="text" name="un" value="<?php echo $row->username; ?>" required/>
</div>
<div class="form-group">
<label class="mb-1" for="pwdId<?php echo $row->id ?>"><i class="fas fa-user-lock"></i> Password</label>
<input type="hidden" name="oldPwd" value="<?php echo $row->password; ?>">
<input class="form-control py-4" id="pwdId<?php echo $row->id ?>" type="password" name="pwd" placeholder="Fill this input for renew password..."/>
</div>
<div class="form-group">
<label class="mb-1" for="idnId<?php echo $row->id ?>"><i class="fas fa-user"></i> Nomor Identifikasi</label>
<input class="form-control py-4" id="idnId<?php echo $row->id ?>" type="text" min="1" name="idn" value="<?php echo $row->id_number; ?>" required/>
</div>
<div class="form-group">
<label class="mb-1" for="fnId<?php echo $row->id ?>"><i class="fas fa-user"></i> Nama Penuh</label>
<input class="form-control py-4" id="fnId<?php echo $row->id ?>" type="text" name="fn" value="<?php echo $row->fullname; ?>" required/>
</div>
</div>
<div class="modal-footer">
<input type="text" name="role" value="cs" readonly hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
</div>
</div>
</form>
</div>
</div>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Our Last Destiny's Corporation 2021</div>
<div>
<a href="#">Privacy Policy</a>
·
<a href="#">Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
</div>
<script src="<?php echo base_url(); ?>assets/js/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/scripts.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap4.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/datatables-demo.js"></script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Booking Perpus | Officer</title>
<link href="<?php echo base_url(); ?>assets/css/styles.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>assets/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="<?php echo base_url(); ?>assets/js/all.min.js" crossorigin="anonymous"></script>
<style media="screen">
body{
background-image: url("<?php echo base_url('assets/img/bg-main.png'); ?>");
background-size: cover;
position: relative;
}
</style>
</head>
<body class="sb-nav-fixed">
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<a class="navbar-brand" href="<?php echo base_url(); ?>">Staff Perpustakaan</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button>
<!-- Navbar-->
<ul class="navbar-nav ml-auto"></ul>
</nav>
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">Core</div>
<a class="nav-link" href="<?php echo base_url(); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-clipboard-check"></i></div>Konfirmasi
</a>
<a class="nav-link active" href="<?php echo base_url('petugas/books'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-book"></i></div>Daftar Buku
</a>
<a class="nav-link" href="<?php echo base_url('login/logout'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-sign-out-alt"></i></div>Keluar
</a>
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Logged in as:</div>
<?php echo $_SESSION['fn']; ?>
</div>
</nav>
</div>
<div id="layoutSidenav_content">
<main>
<div class="container-fluid">
<h1 class="mt-4"><i class="fas fa-book"></i> Book List</h1>
<?php
if ($this->session->flashdata('err')) {
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Gagal!</strong> <?php echo $this->session->flashdata('err')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('warn')) {
?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Perhatian!</strong> <?php echo $this->session->flashdata('warn')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('succ')) {
?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Sukses!</strong> <?php echo $this->session->flashdata('succ')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
?>
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#modalAddBook"><i class="fas fa-asterisk"></i> Add new book</button><br>
<div class="table-responsive">
<table class="table" id="dataTable" width="100%" cellspacing="0">
<thead class="thead-dark">
<tr>
<th>Barcode</th>
<th>Judul</th>
<th>Penulis</th>
<th>Penerbit</th>
<th>Genre</th>
<th>Tahun Terbit</th>
<th>Dipinjam Oleh</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Barcode</th>
<th>Judul</th>
<th>Penulis</th>
<th>Penerbit</th>
<th>Genre</th>
<th>Tahun Terbit</th>
<th>Dipinjam Oleh</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($dataBooks as $row ): ?>
<tr>
<td><?php echo $row->barcode; ?></td>
<td><a href="#modalBookId<?php echo $row->id; ?>" data-toggle="modal" title="Click for details..."><?php echo $row->title; ?></a></td>
<div class="modal fade" id="modalBookId<?php echo $row->id; ?>" tabindex="-1" role="dialog" aria-labelledby="modalBookId<?php echo $row->id; ?>Title" aria-hidden="true">
<div class="modal-dialog" role="document">
<form action="<?php echo base_url("petugas/editBookConfirm/$row->id"); ?>" method="post">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalBookId<?php echo $row->id; ?>Title"><i class="fas fa-book"></i> <?php echo $row->title; ?></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<input type="hidden" name="bcOld" value="<?php echo $row->barcode; ?>" />
<div class="form-group">
<label class="mb-1" for="bc"><i class="fas fa-barcode"></i> Barcode</label>
<input class="form-control py-4" id="bc" type="text" name="barcode" value="<?php echo $row->barcode; ?>" placeholder="Type book barcode here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="title"><i class="fas fa-book"></i> Title</label>
<input class="form-control py-4" id="title" type="text" name="title" value="<?php echo $row->title; ?>" placeholder="Type book title here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="auth"><i class="fas fa-user"></i> Author</label>
<input class="form-control py-4" id="auth" type="text" name="author" value="<?php echo $row->author; ?>" placeholder="Type book author here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="pub"><i class="fas fa-industry"></i> Publisher</label>
<input class="form-control py-4" id="pub" type="text" name="publisher" value="<?php echo $row->publisher; ?>" placeholder="Type book publiser here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="gen"><i class="fas fa-filter"></i> Genre</label>
<input class="form-control py-4" id="gen" type="text" name="genre" value="<?php echo $row->genre; ?>" placeholder="Type book genre here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="y"><i class="fas fa-calendar"></i> Year Released</label>
<select class="form-control" id="y" name="year" required>
<?php for ($i=1900;$i<=2040;$i++) {
if ($i==$row->year_released) {
?><option value="<?php echo $i; ?>" selected><?php echo $i; ?></option> <?php
} else {
?><option value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php
}
} ?>
</select>
</div>
</div>
<div class="modal-footer">
<input type="text" name="role" value="lo" readonly hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
</div>
</div>
</form>
</div>
</div>
<td><?php echo $row->author; ?></td>
<td><?php echo $row->publisher; ?></td>
<td><?php echo $row->genre; ?></td>
<td><?php echo $row->year_released; ?></td>
<td>
<?php echo $row->fullname; ?>
<a class="btn btn-danger btn-sm float-right" href="<?php echo base_url('petugas/removeBookConfirm/').$row->id ?>" onclick="return confirm('Are you sure?')" title="Delete" role="button"><i class="fas fa-trash"></i></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="modal fade" id="modalAddBook" tabindex="-1" role="dialog" aria-labelledby="modalAddBookTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalAddBookTitle"><i class="fas fa-asterisk"></i> Add new book</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<?php echo form_open_multipart('petugas/addBookConfirm') ?>
<div class="form-group">
<label class="mb-1" for="bc"><i class="fas fa-barcode"></i> Barcode</label>
<input class="form-control py-4" id="bc" type="text" name="barcode" placeholder="Type book barcode here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="title"><i class="fas fa-book"></i> Title</label>
<input class="form-control py-4" id="title" type="text" name="title" placeholder="Type book title here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="auth"><i class="fas fa-user"></i> Author</label>
<input class="form-control py-4" id="auth" type="text" name="author" placeholder="Type book author here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="pub"><i class="fas fa-industry"></i> Publisher</label>
<input class="form-control py-4" id="pub" type="text" name="publisher" placeholder="Type book publiser here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="gen"><i class="fas fa-filter"></i> Genre</label>
<input class="form-control py-4" id="gen" type="text" name="genre" placeholder="Type book genre here..." required/>
</div>
<div class="form-group">
<label class="mb-1" for="y"><i class="fas fa-calendar"></i> Year Released</label>
<select class="form-control" id="y" name="year" required>
<?php for ($i=1900;$i<=2040;$i++) {
if ($i==date('Y')) {
?><option value="<?php echo $i; ?>" selected><?php echo $i; ?></option> <?php
} else {
?><option value="<?php echo $i; ?>"><?php echo $i; ?></option> <?php
}
} ?>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-asterisk"></i> Create</button>
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Our Last Destiny's 2021</div>
<div>
<a href="#">Privacy Policy</a>
·
<a href="#">Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
</div>
<script src="<?php echo base_url(); ?>assets/js/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/scripts.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap4.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/datatables-demo.js"></script>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->model('BP_model');
}
public function index(){
if ($this->session->userdata('logged_in') == true){
if($_SESSION['rl']=='administrator'){
redirect('admin');
}elseif ($_SESSION['rl']=='lo') {
redirect('petugas');
}elseif ($_SESSION['rl']=='cs') {
redirect('mahasiswa');
}else {
$this->session->set_flashdata('err','Unknow role, please try again!');
redirect('login/logout');
}
} else {
$this->load->view('v_login');
}
}
public function cek(){
$un = $this->input->post('username');
$pwdAdmin = md5('<PASSWORD>'.$this->input->post('password'));
$pwdLO = md5('<PASSWORD>'.$this->input->post('password'));
$pwdCS = md5('<PASSWORD>'.$this->input->post('password'));
$dataAdmin = $this->BP_model->read('admin', array('username' => $un));
$dataLO = $this->BP_model->read('library_officer', array('username' => $un));
$dataCS = $this->BP_model->read('college_student', array('username' => $un));
$data="";
if($dataAdmin){
$data=$dataAdmin;
$userdata = array(
'id' => $data->id,
'un' => $data->username,
'pwd' => $data->password,
'fn' => $data->fullname,
'rl' => 'administrator',
'logged_in' => TRUE
);
} elseif ($dataLO) {
$data=$dataLO;
$userdata = array(
'id' => $data->id,
'un' => $data->username,
'pwd' => $data->password,
'idn' => $data->id_number,
'fn' => $data->fullname,
'rl' => 'lo',
'logged_in' => TRUE
);
} elseif ($dataCS) {
$data=$dataCS;
$userdata = array(
'id' => $data->id,
'un' => $data->username,
'pwd' => $<PASSWORD>,
'idn' => $data->id_number,
'fn' => $data->fullname,
'rl' => 'cs',
'logged_in' => TRUE
);
}
if($data){
if ($un==$data->username && ($pwdAdmin==$data->password || $pwdLO==$data->password || $pwdCS==$data->password)) {
$this->session->set_userdata($userdata);
} elseif ($un==$data->username && ($pwdAdmin==$data->password || $pwdLO!=$data->password || $pwdCS!=$data->password)) {
$this->session->set_flashdata('err','Username and password didn\'t match, please try again!');
}
} else {
$this->session->set_flashdata('err','Unknow user, please try again!');
}
redirect('login');
}
public function logout(){
session_destroy();
redirect('login');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class BP_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function read($table,$arr,$readMore=0,$getMySQLiResultObject=0){
$query = $this->db->get_where($table, $arr);
if($readMore==1){
if ($getMySQLiResultObject==1) {
return $query;
}else{
return $query->result();
}
}elseif ($readMore==0) {
return $query->row();
}
}
public function create($table,$data){
$this->db->insert($table,$data);
}
public function update($table,$data,$id,$col='id'){
$this->db->where($col, $id);
$this->db->update($table, $data);
}
public function delete($table,$id,$col='id'){
$this->db->delete($table, array($col => $id));
}
public function getLastID(){
$id = $this->db->insert_id();
return $id;
}
public function queryRunning($q,$getMore=1,$getMySQLiResultObject=0){
$query=$this->db->query($q);
if ($getMore==1) {
if ($getMySQLiResultObject==1) {
return $query;
}else{
return $query->result();
}
}else{
return $query->row();
}
}
}
?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->model('BP_model');
$this->updateBookPerDay();
}
public function index(){
if ($this->session->userdata("logged_in") == true){
if($_SESSION['rl']=='administrator'){
$dataLO['dataUserLO'] = $this->BP_model->queryRunning("SELECT * FROM library_officer");
$dataCS['dataUserCS'] = $this->BP_model->queryRunning("SELECT * FROM college_student");
$this->load->view('admin/va_users',$dataLO+$dataCS);
}elseif ($_SESSION['rl']=='lo') {
$this->session->set_flashdata('err','Anda bukan administrator.');
redirect('petugas');
}elseif ($_SESSION['rl']=='cs') {
$this->session->set_flashdata('err','Anda bukan administrator.');
redirect('mahasiswa');
}else {
$this->session->set_flashdata('err','Role tidak diketahui, coba lagi!');
redirect('login/logout');
}
} else {
$this->sessionTimedOut();
}
}
public function sessionTimedOut(){
if ($this->session->userdata("logged_in") == false){
$this->session->set_flashdata('err','Masuk terlebih dahulu!');
redirect('login');
}
}
public function updateBookPerDay(){
date_default_timezone_set('Asia/Jakarta');
$day=date('Y-m-d',strtotime('yesterday'));
$books=$this->BP_model->queryRunning("SELECT * FROM reservation WHERE check_in<='$day' AND status!='OUT'");
foreach ($books as $row) {
$this->BP_model->update('books',array('borrowed_by' => NULL),$row->book_id);
}
$this->BP_model->queryRunning("UPDATE reservation SET status='OUT' WHERE check_in<='$day' AND status!='OUT'",1,1);
}
public function createUserConfirm(){
$this->sessionTimedOut();
if ($this->input->post('role')=='lo') {
$table='library_officer';
$hash_addition='BookingPerpusLibraryOfficer';
}elseif ($this->input->post('role')=='cs') {
$table='college_student';
$hash_addition='BookingPerpusCollegeStudent';
}
$data = array(
'username' => $this->input->post('un'),
'password' => md5($<PASSWORD>.$this->input->post('pwd')),
'id_number' => $this->input->post('idn'),
'fullname' => $this->input->post('fn')
);
if ($this->BP_model->read($table,array('username' => $this->input->post('un')))) {
$this->session->set_flashdata('err','Username sudah dipakai.');
redirect("admin");
}else{
$this->BP_model->create($table,$data);
$this->session->set_flashdata('succ','User telah dibuat.');
redirect("admin");
}
}
public function editUserConfirm($UserId){
$this->sessionTimedOut();
if ($this->input->post('role')=='lo') {
$table='library_officer';
$hash_addition='BookingPerpusLibraryOfficer';
}elseif ($this->input->post('role')=='cs') {
$table='college_student';
$hash_addition='BookingPerpusCollegeStudent';
}
if ($this->input->post('unOld')==$this->input->post('un')) {
$unNew=$this->input->post('unOld');
}else{
$unNew=$this->input->post('un');
$cekUN=$this->BP_model->read($table,array('username' => $this->input->post('un')));
if ($cekUN) {
$this->session->set_flashdata('err','Username sudah dipakai.');
redirect("admin");
}
}
if($this->input->post('pwd')!=NULL){
$pwd=md5($hash_addition.$this->input->post('pwd'));
}else{
$pwd=md5($this->input->post('oldPwd'));
}
$data = array(
'username' => $unNew,
'password' => $pwd,
'id_number' => $this->input->post('idn'),
'fullname' => $this->input->post('fn')
);
$this->BP_model->update($table,$data,$UserId);
$this->session->set_flashdata('succ','User telah disunting.');
redirect("admin");
}
public function deleteUserConfirm($role,$DeleteId){
$this->sessionTimedOut();
if ($role=='lo') { $table='library_officer';}
elseif ($role=='cs') { $table='college_student';}
$this->BP_model->delete($table,$DeleteId);
$this->session->set_flashdata('succ','User telah dihapus.');
redirect("admin");
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Booking Perpus | Student</title>
<link href="<?php echo base_url(); ?>assets/css/styles.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>assets/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="<?php echo base_url(); ?>assets/js/all.min.js" crossorigin="anonymous"></script>
<style media="screen">
body{
background-image: url("<?php echo base_url('assets/img/bg-main.png'); ?>");
background-size: cover;
position: relative;
}
</style>
</head>
<body class="sb-nav-fixed">
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<a class="navbar-brand" href="<?php echo base_url(); ?>">Mahasiswa</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button>
<!-- Navbar-->
<ul class="navbar-nav ml-auto"></ul>
</nav>
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">Core</div>
<a class="nav-link active" href="<?php echo base_url(); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-list"></i></div>Daftar Reservasi
</a>
<a class="nav-link" href="<?php echo base_url('mahasiswa#myReservation'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-list"></i></div>Reservasi Saya
</a>
<a class="nav-link" href="<?php echo base_url('login/logout'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-sign-out-alt"></i></div>Logout
</a>
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Logged in as:</div>
<?php echo $_SESSION['fn']; ?>
</div>
</nav>
</div>
<div id="layoutSidenav_content">
<main>
<div class="container-fluid" id="myReservation">
<h1 class="mt-4">
<i class="fas fa-list"></i> Daftar Reservasi
</h1>
<?php
if ($this->session->flashdata('err')) {
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Gagal!</strong> <?php echo $this->session->flashdata('err')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
if ($this->session->flashdata('warn')) {
?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Perhatian!</strong> <?php echo $this->session->flashdata('warn')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
if ($this->session->flashdata('succ')) {
?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Berhasil!</strong> <?php echo $this->session->flashdata('succ')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
?>
<button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#modalCreateReservation"><i class="fas fa-asterisk"></i> Buat Reservasi Baru</button><br>
<div class="modal fade" id="modalCreateReservation" tabindex="-1" role="dialog" aria-labelledby="modalCreateReservationTitle" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form action="<?php echo base_url('mahasiswa/createReservationConfirm/').$_SESSION['id']; ?>" method="post">
<div class="modal-header">
<h5 class="modal-title" id="modalCreateReservationTitle"><i class="fas fa-asterisk"></i> Buat Reservasi Baru</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label class="mb-1" for="d"><i class="fas fa-calendar"></i> Check In</label>
<input class="form-control py-4" id="d" type="date" name="date" min="<?php date_default_timezone_set("Asia/Jakarta"); echo date('Y-m-d'); ?>" max="<?php echo date('Y-m-d',strtotime("+1 week")); ?>" value="<?php echo date('Y-m-d'); ?>" required/>
</div>
<div class="form-group">
<label class="mb-1" for="b"><i class="fas fa-book"></i> Buku</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><strong>1</strong></span>
</div>
<select class="form-control" id="b" name="book1" required>
<option value="">- Wajib Diisi -</option>
<?php
foreach ($books as $row) {
if (!$row->borrowed_by) {
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->barcode; ?> - <?php echo $row->title; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><strong>2</strong></span>
</div>
<select class="form-control" id="b" name="book2">
<option value="">- Opsional -</option>
<?php
foreach ($books as $row) {
if (!$row->borrowed_by) {
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->barcode; ?> - <?php echo $row->title; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><strong>3</strong></span>
</div>
<select class="form-control" id="b" name="book3">
<option value="">- Opsional -</option>
<?php
foreach ($books as $row) {
if (!$row->borrowed_by) {
?>
<option value="<?php echo $row->id; ?>"><?php echo $row->barcode; ?> - <?php echo $row->title; ?></option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fas fa-asterisk"></i> Create</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="card bg-light mb-3">
<div class="card-header"><h4><center>Your Reservation Code</center></h4></div>
<div class="card-body py-3">
<h4><center><?php
if ($reservation_info) {
echo $reservation_info->reservation_code;
}else{
echo "Belum Tersedia.";
}
?></center></h4>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="card bg-light mb-3">
<div class="card-header"><h4><center>Nama</center></h4></div>
<div class="card-body py-3"><h4><center><?php echo $_SESSION['fn']; ?></center></h4>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="card bg-light mb-3">
<div class="card-header"><h4><center>Daftar Buku</center></h4></div>
<div class="card-body py-3">
<div class="table-responsive">
<table class="table" width="100%">
<tr>
<td>Barcode</td>
<td>Judul</td>
<td>Penulis</td>
<td>Penerbit</td>
<td>Genre</td>
<td>Tahun Release</td>
<td>Check In</td>
</tr>
<?php
if ($reserved_books) {
foreach ($reserved_books as $row) {
?>
<tr>
<td><?php echo $row->barcode; ?></td>
<td><?php echo $row->title; ?></td>
<td><?php echo $row->author; ?></td>
<td><?php echo $row->publisher; ?></td>
<td><?php echo $row->genre; ?></td>
<td><?php echo $row->year_released; ?></td>
<td><?php echo $row->check_in; ?></td>
</tr>
<?php
}
} else {
?><td colspan="7">Belum Tersedia.</td><?php
}
?>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="table-responsive mt-2">
<table class="table" id="dataTable" width="100%" cellspacing="0">
<thead class="thead-dark">
<tr>
<th>Check In</th>
<th>Kode Reservasi</th>
<th>Nama Lengkap</th>
<th>Status</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Check In</th>
<th>Kode Reservasi</th>
<th>Nama Penuh</th>
<th>Status</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($reservation as $row ): ?>
<tr style="background-color: white;">
<td><?php echo $row->check_in; ?></td>
<td><?php echo $row->reservation_code; ?></td>
<td><?php echo $row->fullname; ?></td>
<td><?php echo $row->status; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Our Last Destiny's Project</div>
<div>
<a href="#">Privacy Policy</a>
·
<a href="#">Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
</div>
<script src="<?php echo base_url(); ?>assets/js/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/scripts.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap4.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/datatables-demo.js"></script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mahasiswa extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->model('BP_model');
$this->updateBookPerDay();
}
public function index(){
if ($this->session->userdata("logged_in") == true){
if ($_SESSION['rl']=='administrator') {
$this->session->set_flashdata('err','Anda bukan mahasiswa.');
redirect('admin');
}elseif ($_SESSION['rl']=='lo') {
$this->session->set_flashdata('err','Anda bukan mahasiswa.');
redirect('petugas');
}elseif ($_SESSION['rl']=='cs') {
$data['books']=$this->BP_model->queryRunning("SELECT * FROM books");
$data['reservation']=$this->BP_model->queryRunning("SELECT reservation.*,college_student.fullname FROM (reservation LEFT JOIN college_student ON reservation.cs_id=college_student.id) WHERE status!='OUT' GROUP BY reservation_code");
$data['reservation_info']=$this->BP_model->queryRunning("SELECT reservation.reservation_code,reservation.check_in,college_student.fullname FROM reservation,college_student WHERE reservation.status='PENDING' AND reservation.cs_id=".$_SESSION['id']." GROUP BY reservation.reservation_code ORDER BY reservation.check_in",0);
if ($data['reservation_info']) {
$data['reserved_books']=$this->BP_model->queryRunning("SELECT books.*,reservation.reservation_code,reservation.check_in,reservation.book_id FROM reservation,books WHERE book_id=books.id AND status='PENDING' AND books.borrowed_by=".$_SESSION['id']." AND reservation_code='".$data['reservation_info']->reservation_code."'");
// print_r($data['reserved_books']);
// exit();
}else {
$data['reserved_books']=NULL;
}
$this->load->view('mahasiswa/vm_main',$data);
}else {
$this->session->set_flashdata('err','Role tidak diketahui, coba lagi!');
redirect('login/logout');
}
} else {
$this->session->set_flashdata('err','Masuk terlebih dahulu!');
redirect('login');
}
}
public function sessionTimedOut(){
if ($this->session->userdata("logged_in") == false){
$this->session->set_flashdata('err','Masuk terlebih dahulu!');
redirect('login');
}
}
public function updateBookPerDay(){
date_default_timezone_set('Asia/Jakarta');
$day=date('Y-m-d',strtotime('yesterday'));
$books=$this->BP_model->queryRunning("SELECT * FROM reservation WHERE check_in<='$day' AND status!='OUT'");
foreach ($books as $row) {
$this->BP_model->update('books',array('borrowed_by' => NULL),$row->book_id);
}
$this->BP_model->queryRunning("UPDATE reservation SET status='OUT' WHERE check_in<='$day' AND status!='OUT'",1,1);
}
public function createReservationConfirm($studentId) {
$this->sessionTimedOut();
if ($this->input->post('date')<date('Y-m-d') || $this->input->post('date')>date('Y-m-d',strtotime('+1 week'))) {
$this->session->set_flashdata('err','Diluar batas tanggal yang disediakan!');
redirect('mahasiswa');
}elseif ($this->BP_model->read('reservation',array('check_in' => $this->input->post('date'), 'cs_id' => $_SESSION['id'], 'status' => 'PENDING'))) {
$this->session->set_flashdata('err','Anda sudah melakukan reservasi di hari tersebut.');
redirect('mahasiswa');
}elseif ($this->BP_model->queryRunning("SELECT * FROM reservation WHERE check_in='".$this->input->post('date')."' AND status!='OUT'")->result_id->num_rows>=50) {
$this->session->set_flashdata('err','Reservasi sudah penuh, coba dilain hari!');
redirect('mahasiswa');
}
else{
date_default_timezone_set("Asia/Jakarta");
$data = array(
'reservation_code' => date('DymdHis'),
'check_in' => $this->input->post('date'),
'cs_id' => $studentId,
'book_id' => $this->input->post('book1'),
'timestamp' => date('Y-m-d'),
'status' => 'PENDING'
);
$this->BP_model->create('reservation',$data);
$this->BP_model->update('books',array('borrowed_by' => $_SESSION['id']),$this->input->post('book1'));
if ($this->input->post('book2')) {
$data['book_id']=$this->input->post('book2');
$this->BP_model->create('reservation',$data);
$this->BP_model->update('books',array('borrowed_by' => $_SESSION['id']),$this->input->post('book2'));
}
if ($this->input->post('book3')) {
$data['book_id']=$this->input->post('book3');
$this->BP_model->create('reservation',$data);
$this->BP_model->update('books',array('borrowed_by' => $_SESSION['id']),$this->input->post('book3'));
}
}
$this->session->set_flashdata('succ','Reservasi telah dibuat.');
$this->session->set_flashdata('warn','Jangan lupa untuk datang tepat waktu! Reservasi akan terhapus otomatis jika pada hari itu anda tidak datang.');
redirect('mahasiswa');
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Booking Perpus | Login</title>
<link href="<?php echo base_url('assets/css/styles.css'); ?>" rel="stylesheet" />
<script src="<?php echo base_url('assets/js/all.min.js'); ?>"></script>
<style media="screen">
body{
background-image: url("<?php echo base_url('assets/img/bg-login.png'); ?>");
background-size: cover;
position: relative;
}
</style>
</head>
<body class="bg-primary" style="height:100vh">
<div id="layoutAuthentication">
<div id="layoutAuthentication_content">
<main style="height:100vh">
<div class="container-fluid h-100" style="height:100vh">
<div class="row justify-content-end" style="height:90vh">
<div class="col-md-3">
<div class="card shadow-lg border-0 rounded-lg mt-5 h-100"><img src="assets/img/bg-logo2.png" style="border-radius: 1px;"/>
<div class="card-body mt-3 d-flex flex-column justify-content-center">
<?php echo form_open('login/cek') ?>
<span class="text-danger"><?php echo $this->session->flashdata('err'); ?></span>
<div class="form-group"><label class="mb-3" for="un">Username</label><input class="form-control py-4" id="un" type="text" name="username" placeholder="Your username..." autofocus required/></div>
<div class="form-group">
<label class="mb-3 " for="pwd">Password</label>
<input class="form-control py-4" id="pwd" type="password" name="password" placeholder="<PASSWORD> security password..." required/>
<a href="" class="float-right" data-toggle="tooltip" data-placement="right" title="Contact our administrator (<EMAIL>) or your library officer.">Forget password?</a>
</div>
<div class="form-group d-flex align-items-center mt-4 mb-5" style="float:right">
<button type="submit" class="btn btn-primary"><span class="fas fa-sign-in-alt"></span> Login</button>
<button type="reset" class="btn btn-danger"><span class="fas fa-redo-alt"></span> Reset</button>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<div id="layoutAuthentication_footer">
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Our Last Destiny's Project</div>
</div>
</div>
</footer>
</div>
</div>
<script src="<?php echo base_url('assets/js/jquery-3.4.1.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/scripts.js'); ?>"></script>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</body>
</html>
<file_sep>vp_book<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Petugas extends CI_Controller {
public function __construct() {
parent:: __construct();
$this->load->model('BP_model');
$this->updateBookPerDay();
}
public function index(){
if ($this->session->userdata("logged_in") == true){
if ($_SESSION['rl']=='administrator') {
$this->session->set_flashdata('err','Anda bukan petugas.');
redirect('admin');
}elseif ($_SESSION['rl']=='lo') {
$data['reservation']=$this->BP_model->queryRunning("SELECT reservation.*,college_student.fullname FROM reservation,college_student WHERE status!='OUT' AND cs_id=college_student.id GROUP BY reservation_code");
$this->load->view('petugas/vp_konfirmasi',$data);
}elseif ($_SESSION['rl']=='cs') {
$this->session->set_flashdata('err','Anda bukan petugas.');
redirect('mahasiswa');
}else {
$this->session->set_flashdata('err','Role tidak diketahui, coba lagi!');
redirect('login/logout');
}
} else {
$this->sessionTimedOut();
}
}
public function sessionTimedOut(){
if ($this->session->userdata("logged_in") == false){
$this->session->set_flashdata('err','Masuk terlebih dahulu!');
redirect('login');
}
}
public function updateBookPerDay(){
date_default_timezone_set('Asia/Jakarta');
$day=date('Y-m-d',strtotime('yesterday'));
$books=$this->BP_model->queryRunning("SELECT * FROM reservation WHERE check_in<='$day' AND status!='OUT'");
foreach ($books as $row) {
$this->BP_model->update('books',array('borrowed_by' => NULL),$row->book_id);
}
$this->BP_model->queryRunning("UPDATE reservation SET status='OUT' WHERE check_in<='$day' AND status!='OUT'",1,1);
}
public function konfirmasi($reservationCode,$msg){
$this->sessionTimedOut();
$this->updateBookPerDay();
if ($msg=='in') {
$this->BP_model->update('reservation',array('status' => 'IN'),$reservationCode,'reservation_code');
}elseif ($msg=='out') {
$books=$this->BP_model->read('reservation',array('reservation_code' => $reservationCode),1);
foreach ($books as $row) {
$this->BP_model->update('books',array('borrowed_by' => NULL),$row->book_id);
}
$this->BP_model->update('reservation',array('status' => 'OUT'),$reservationCode,'reservation_code');
}
$this->session->set_flashdata('succ','Reservasi telah dikonfirmasi.');
redirect("petugas");
}
public function books(){
$this->sessionTimedOut();
$data['dataBooks'] = $this->BP_model->queryRunning('SELECT books.*,college_student.fullname FROM books LEFT JOIN college_student ON borrowed_by=college_student.id');
$this->load->view('petugas/vp_book',$data);
}
public function addBookConfirm(){
$this->sessionTimedOut();
$cekBC=$this->BP_model->read('books',array('barcode' => $this->input->post('barcode')));
if ($cekBC) {
$this->session->set_flashdata('err','Barcode sudah dipakai.');
}else{
$data = array(
'barcode' => $this->input->post('barcode'),
'title' => $this->input->post('title'),
'author' => $this->input->post('author'),
'publisher' => $this->input->post('publisher'),
'genre' => $this->input->post('genre'),
'year_released' => $this->input->post('year')
);
$this->BP_model->create('books',$data);
$this->session->set_flashdata('succ','Buku telah ditambahkan.');
}
redirect("petugas/books");
}
public function editBookConfirm($BookId){
$this->sessionTimedOut();
if ($this->input->post('bcOld')==$this->input->post('barcode')) {
$bcNew=$this->input->post('bcOld');
}else{
$bcNew=$this->input->post('barcode');
$cekBC=$this->BP_model->read('books',array('barcode' => $this->input->post('barcode')));
if ($cekBC) {
$this->session->set_flashdata('err','Barcode sudah dipakai.');
redirect("petugas/books");
}
}
$data = array(
'barcode' => $bcNew,
'title' => $this->input->post('title'),
'author' => $this->input->post('author'),
'publisher' => $this->input->post('publisher'),
'genre' => $this->input->post('genre'),
'year_released' => $this->input->post('year')
);
$this->BP_model->update('books',$data,$BookId);
$this->session->set_flashdata('succ','Buku telah disunting.');
redirect("petugas/books");
}
public function removeBookConfirm($DeleteId){
$this->sessionTimedOut();
$this->BP_model->delete('books',$DeleteId);
$this->session->set_flashdata('succ','Buku telah dihapus.');
redirect("petugas/books");
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 02, 2021 at 07:13 PM
-- Server version: 10.4.19-MariaDB
-- PHP Version: 7.4.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: `booking_perpus`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE `admin` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`fullname` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`id`, `username`, `password`, `fullname`) VALUES
(1, 'admin', '<PASSWORD>', 'Administrator');
-- --------------------------------------------------------
--
-- Table structure for table `books`
--
CREATE TABLE `books` (
`id` int(11) NOT NULL,
`barcode` varchar(20) NOT NULL,
`title` varchar(500) NOT NULL,
`author` varchar(255) NOT NULL,
`publisher` varchar(200) NOT NULL,
`genre` varchar(100) NOT NULL,
`year_released` year(4) NOT NULL,
`borrowed_by` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`id`, `barcode`, `title`, `author`, `publisher`, `genre`, `year_released`, `borrowed_by`) VALUES
(3, '1965463176', 'Habis Gelap Terbitlah Terang', 'R. <NAME>', 'Indonesia Raya', 'Education', 1945, NULL),
(4, '6546543213', 'Habis Gelap Terbitlah Terang', 'R. A. Kartini', 'Indonesia Raya', 'Education', 1945, NULL),
(5, '123456', 'Bumi Datar', 'Rangga', 'PT Sunda Empire', 'Education', 2021, 1),
(6, '1654', 'Bumi Datar', 'Rangga', 'PT Sunda Empire', 'Education', 2021, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `college_student`
--
CREATE TABLE `college_student` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`id_number` varchar(50) NOT NULL,
`fullname` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `college_student`
--
INSERT INTO `college_student` (`id`, `username`, `password`, `id_number`, `fullname`) VALUES
(1, 'mhs1', '<PASSWORD>', '<PASSWORD>', 'Mahasiswa Satu'),
(3, 'Indra', '799da4a9eb99ba0a30bdb9bf<PASSWORD>', '12345677777', 'Indra Yuhyen'),
(4, 'rizal', '393b02a32ebe3cf9138230af376d0bc8', '123457794', 'Rizal Maul'),
(6, 'mhs2', '<PASSWORD>', '213123', 'Mahasiswa Dua');
-- --------------------------------------------------------
--
-- Table structure for table `library_officer`
--
CREATE TABLE `library_officer` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`id_number` varchar(50) NOT NULL,
`fullname` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `library_officer`
--
INSERT INTO `library_officer` (`id`, `username`, `password`, `id_number`, `fullname`) VALUES
(1, 'petugas', '<PASSWORD>', '19991346 201006 1 002', 'Indra Athalla Yuhen');
-- --------------------------------------------------------
--
-- Table structure for table `reservation`
--
CREATE TABLE `reservation` (
`id` int(11) NOT NULL,
`reservation_code` varchar(100) NOT NULL,
`check_in` date NOT NULL,
`cs_id` int(11) NOT NULL,
`book_id` int(11) NOT NULL,
`timestamp` date NOT NULL,
`status` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `reservation`
--
INSERT INTO `reservation` (`id`, `reservation_code`, `check_in`, `cs_id`, `book_id`, `timestamp`, `status`) VALUES
(1, 'Fri210528172508', '2021-05-28', 1, 3, '2021-05-28', 'OUT'),
(2, 'Fri210528172508', '2021-05-28', 1, 4, '2021-05-28', 'OUT'),
(3, 'Fri210528172508', '2021-05-28', 1, 5, '2021-05-28', 'OUT'),
(7, 'Fri210528184308', '2021-05-28', 1, 3, '2021-05-28', 'OUT'),
(8, 'Fri210528184308', '2021-05-28', 1, 4, '2021-05-28', 'OUT'),
(9, 'Fri210528184308', '2021-05-28', 1, 5, '2021-05-28', 'OUT'),
(10, 'Fri210528190702', '2021-05-30', 1, 6, '2021-05-28', 'OUT'),
(11, 'Sat210529164222', '2021-05-30', 1, 3, '2021-05-29', 'OUT'),
(12, 'Sat210529164222', '2021-05-30', 1, 5, '2021-05-29', 'OUT'),
(13, 'Sat210529172446', '2021-05-31', 1, 4, '2021-05-29', 'OUT'),
(14, 'Sun210530101834', '2021-05-30', 1, 5, '2021-05-30', 'OUT'),
(15, 'Tue210601000511', '2021-06-01', 4, 3, '2021-06-01', 'OUT'),
(16, 'Wed210602230638', '2021-06-02', 1, 3, '2021-06-02', 'OUT'),
(17, 'Wed210602235444', '2021-06-03', 1, 5, '2021-06-02', 'PENDING');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `books`
--
ALTER TABLE `books`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_cs_book` (`borrowed_by`);
--
-- Indexes for table `college_student`
--
ALTER TABLE `college_student`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `library_officer`
--
ALTER TABLE `library_officer`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `reservation`
--
ALTER TABLE `reservation`
ADD PRIMARY KEY (`id`),
ADD KEY `fk_cs_reservation` (`cs_id`),
ADD KEY `fk_book_reservation` (`book_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admin`
--
ALTER TABLE `admin`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `books`
--
ALTER TABLE `books`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `college_student`
--
ALTER TABLE `college_student`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `library_officer`
--
ALTER TABLE `library_officer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `reservation`
--
ALTER TABLE `reservation`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `books`
--
ALTER TABLE `books`
ADD CONSTRAINT `fk_cs_book` FOREIGN KEY (`borrowed_by`) REFERENCES `college_student` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
--
-- Constraints for table `reservation`
--
ALTER TABLE `reservation`
ADD CONSTRAINT `fk_book_reservation` FOREIGN KEY (`book_id`) REFERENCES `books` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `fk_cs_reservation` FOREIGN KEY (`cs_id`) REFERENCES `college_student` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
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><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>Booking Perpus | Officer</title>
<link href="<?php echo base_url(); ?>assets/css/styles.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>assets/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" />
<script src="<?php echo base_url(); ?>assets/js/all.min.js" crossorigin="anonymous"></script>
<style media="screen">
body{
background-image: url("<?php echo base_url('assets/img/bg-main.png'); ?>");
background-size: cover;
position: relative;
}
</style>
</head>
<body class="sb-nav-fixed">
<nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<a class="navbar-brand" href="<?php echo base_url(); ?>">Staff Perpustakaan</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button>
<!-- Navbar-->
<ul class="navbar-nav ml-auto"></ul>
</nav>
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">Core</div>
<a class="nav-link active" href="<?php echo base_url(); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-clipboard-check"></i></div>Konfirmasi
</a>
<a class="nav-link" href="<?php echo base_url('petugas/books'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-book"></i></div>Daftar Buku
</a>
<a class="nav-link" href="<?php echo base_url('login/logout'); ?>">
<div class="sb-nav-link-icon"><i class="fas fa-sign-out-alt"></i></div>Keluar
</a>
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Logged in as:</div>
<?php echo $_SESSION['fn']; ?>
</div>
</nav>
</div>
<div id="layoutSidenav_content">
<main>
<div class="container-fluid">
<h1 class="mt-4"><i class="fas fa-clipboard-check"></i> Konfirmasi</h1>
<?php
if ($this->session->flashdata('err')) {
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Gagal!</strong> <?php echo $this->session->flashdata('err')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('warn')) {
?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Perhatian!</strong> <?php echo $this->session->flashdata('warn')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}else if ($this->session->flashdata('succ')) {
?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Sukses!</strong> <?php echo $this->session->flashdata('succ')?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<?php
}
?>
<div class="table-responsive mt-2">
<table class="table" id="dataTable" width="100%" cellspacing="0">
<thead class="thead-dark">
<tr>
<th>Check In</th>
<th>Kode Reservasi</th>
<th>Nama Penuh</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Check In</th>
<th>Kode Reservasi</th>
<th>Nama Penuh</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($reservation as $row ): ?>
<tr>
<td><?php echo $row->check_in; ?></td>
<td><?php echo $row->reservation_code; ?></td>
<td>
<?php echo $row->fullname;
if ($row->status=='PENDING') {
?>
<a class="btn btn-success float-right" href="<?php echo base_url('petugas/konfirmasi/'.$row->reservation_code.'/in') ?>" onclick="return confirm('Are you sure?')" title="Confirm" role="button"><i class="fas fa-sign-in-alt"></i> Check In</a>
<?php
}elseif ($row->status=='IN') {
?>
<a class="btn btn-danger float-right" href="<?php echo base_url('petugas/konfirmasi/'.$row->reservation_code.'/out') ?>" onclick="return confirm('Are you sure?')" title="Confirm" role="button"><i class="fas fa-sign-out-alt"></i> Check Out</a>
<?php
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © Our Last Destiny's 2021</div>
<div>
<a href="#">Privacy Policy</a>
·
<a href="#">Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
</div>
<script src="<?php echo base_url(); ?>assets/js/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/scripts.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap4.min.js" crossorigin="anonymous"></script>
<script src="<?php echo base_url(); ?>assets/js/datatables-demo.js"></script>
</body>
</html>
| 91d474c253e41efae5f29926ec0ca6b4de89a399 | [
"SQL",
"PHP"
] | 11 | PHP | rizalmyusuf/booking-perpus | 91d4b6f7dac13925c50634fd5d23396fa48ebba1 | 3ce4b9c833e3f391165c94af44dddedf6a0987cf |
refs/heads/master | <repo_name>joeinnes/mtc<file_sep>/src/World.js
import React from 'react'
import styles from './World.module.css'
const World = () => {
return (
<div className={styles.world}></div>
)
}
export default World<file_sep>/src/App.js
import React from 'react'
import './App.css'
import Header from './Header'
import Meatcoins from './Meatcoins'
import World from './World'
import Actionbar from './Actionbar'
import Clouds from './Clouds'
import Farm from './Farm'
import AboutOverlay from './AboutOverlay'
import { get, set } from 'idb-keyval'
const vh = Math.max(
document.documentElement.clientHeight,
window.innerHeight || 0
)
class App extends React.Component {
state = {
mtc: 0,
displayAboutOverlay: false
}
toggleAbout = () => {
this.setState((prevState, props) => {
return {
displayAboutOverlay: !prevState.displayAboutOverlay
}
})
}
updateMTC = val => {
this.setState((prevState, props) => {
set('mtc', prevState.mtc + val)
return {
mtc: prevState.mtc + val
}
})
}
componentDidMount() {
get('mtc').then(val =>
this.setState({
mtc: val || 0
})
)
}
render() {
return (
<div className="App">
<AboutOverlay
display={this.state.displayAboutOverlay}
clickHandler={() => this.toggleAbout()}
/>
<Header appName="Meat Coin" clickHandler={() => this.toggleAbout()} />
<Meatcoins mtc={this.state.mtc} />
<Clouds count={1.5 * Math.ceil(vh / 100)} />
<Farm animalCount={this.state.mtc} />
<World />
<Actionbar clickHandler={val => this.updateMTC.bind(this, val)} />
</div>
)
}
}
export default App
<file_sep>/src/AboutOverlay.js
import React from 'react'
import PropTypes from 'prop-types'
import styles from './AboutOverlay.module.css'
import { ReactComponent as Cheese } from './assets/cheese.svg'
import { ReactComponent as Meat } from './assets/meat.svg'
import { ReactComponent as Plant } from './assets/plant.svg'
const AboutOverlay = props => {
return (
<div
className={styles.overlay}
style={{ display: props.display ? 'block' : 'none' }}
>
<h1>Meat Coin</h1>
<p>
Meat Coin is a super simple app to help you manage your meat
consumption. Whether you want to reduce your meat intake for health,
animal welfare, or environmental reasons, Meat Coin has you covered.
</p>
<p>
Every time you eat a plant-based meal, hit the plant icon
<Plant className={styles.icon} /> to be credited with a meat coin. If
you eat a meal with meat, tap <Meat className={styles.icon} /> to reduce
your Meat Coin balance by 1 MTC. You can also use the{' '}
<Cheese className={styles.icon} /> button to reduce your MTC balance by
a half, in case you eat a meal containing dairy.
</p>
<p>
Other rules are up to you - do you want to include breakfast? If you
have meat and dairy in a single meal, is that 1.5 MTC or just one? Are
eggs dairy? You decide!
</p>
<p>
No data is ever transmitted to the cloud, all the information is stored
locally on your device. As a result, there's no logging in, no syncing,
and no complexity.
</p>
<p>
All the usual caveats apply - use at your own risk, I'm not a doctor,
and you should check with one before making changes to your diet,
software is provided as-is, and I'm not promising that it works. If for
some reason it blows up your device, that's not my fault either.
</p>
<p>
Let me know if something is broken or if you like it!{' '}
<a href="mailto:<EMAIL>" className={styles.link}>
<EMAIL>
</a>
</p>
<p>
All emojis designed by{' '}
<a href="https://openmoji.org/" className={styles.link}>
OpenMoji
</a>{' '}
– the open-source emoji and icon project. Licence:{' '}
<a
href="https://creativecommons.org/licenses/by-sa/4.0/#"
className={styles.link}
>
CC BY-SA 4.0
</a>
</p>
<button
className={styles.closeoverlay}
onClick={() => props.clickHandler()}
>
Close
</button>
</div>
)
}
AboutOverlay.propTypes = {
clickHandler: PropTypes.func,
display: PropTypes.bool
}
export default AboutOverlay
<file_sep>/src/Chicken.js
import React from 'react'
import styles from './Chicken.module.css'
import PropTypes from 'prop-types'
import { ReactComponent as ChickenImage } from './assets/chicken.svg'
const Chicken = props => {
const duration = Math.random() * 15 + 5
const chickenStyle = {
animationName: Math.random() > 0.5 ? 'wobble' : 'wobbleReverse',
animationTimingFunction: 'ease',
animationDuration: duration + 's',
animationIterationCount: 'infinite',
animationDelay: -1 * duration,
left: Math.random() * 90 + 5 + 'vw',
bottom: Math.random() * 10 + 15 + 'vh',
height: props.height + 'vw'
}
return <ChickenImage className={styles.chicken} style={chickenStyle} />
}
Chicken.propTypes = {
height: PropTypes.number
}
export default Chicken
<file_sep>/src/Cloud.js
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Cloud.module.css'
const Cloud = props => {
const startPoint = -1 * (Math.random() * props.transitionTime)
const cloudStyle = {
animationName: 'animateCloud',
animationDelay: startPoint + 's',
animationDuration: props.transitionTime + 's',
animationTimingFunction: 'linear',
animationIterationCount: 'infinite',
transform: `scale(${props.scale})`,
top: props.fromTop + 'vh'
}
return <div className={styles.cloud} style={cloudStyle} />
}
Cloud.propTypes = {
transitionTime: PropTypes.number,
scale: PropTypes.number,
fromTop: PropTypes.number
}
export default Cloud
<file_sep>/src/Actionbar.js
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Actionbar.module.css'
import { ReactComponent as Cheese } from './assets/cheese.svg'
import { ReactComponent as Meat } from './assets/meat.svg'
import { ReactComponent as Plant } from './assets/plant.svg'
const Actionbar = props => {
return (
<footer className={styles.footer}>
<Meat className={styles.button} onClick={props.clickHandler(-1)} />
<Cheese className={styles.button} onClick={props.clickHandler(-0.5)} />
<Plant className={styles.button} onClick={props.clickHandler(1)} />
</footer>
)
}
Actionbar.propTypes = {
clickHandler: PropTypes.func
}
export default Actionbar
<file_sep>/src/Meatcoins.js
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Meatcoins.module.css'
const Meatcoins = (props) => {
return (
<span className={styles.mtc}>{props.mtc} MTC</span>
)
}
Meatcoins.propTypes = {
mtc: PropTypes.number,
}
export default Meatcoins<file_sep>/src/Farm.js
import React from 'react'
import PropTypes from 'prop-types'
import Cow from './Cow'
import Chicken from './Chicken'
const Farm = props => {
let animalsArray = []
for (let i = 0; i < props.animalCount; i++) {
if (props.animalCount === 1) {
animalsArray.push(<Cow height={300 / props.animalCount} key={i} />)
} else if (i % 3 === 0) {
animalsArray.push(
<Chicken height={300 / props.animalCount} key={i + 'a'} />
)
animalsArray.push(
<Chicken height={300 / props.animalCount} key={i + 'b'} />
)
} else {
animalsArray.push(<Cow height={300 / props.animalCount} key={i} />)
}
}
return animalsArray
}
Farm.propTypes = {
animalCount: PropTypes.number
}
export default Farm
<file_sep>/src/Header.js
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Header.module.css'
import { ReactComponent as CowFace } from './assets/cow-face.svg'
const Header = props => {
return (
<header className={styles.header}>
<h1 className={styles.title}>{props.appName}</h1>
<CowFace onClick={() => props.clickHandler()} className={styles.icon} />
</header>
)
}
Header.propTypes = {
appName: PropTypes.string,
menuIcon: PropTypes.string,
clickHandler: PropTypes.func
}
export default Header
<file_sep>/src/Cow.js
import React from 'react'
import styles from './Cow.module.css'
import PropTypes from 'prop-types'
import { ReactComponent as CowImg } from './assets/cow.svg'
const Cow = props => {
const duration = Math.random() * 15 + 5
const cowStyle = {
animationName: Math.random() > 0.5 ? 'wobble' : 'wobbleReverse',
animationTimingFunction: 'ease',
animationDuration: duration + 's',
animationIterationCount: 'infinite',
animationDelay: -1 * duration,
height: props.height + 'vw',
left: Math.random() * 90 + 5 + 'vw',
bottom: Math.random() * 10 + 10 + 'vh'
}
return (
<div>
<CowImg alt="A cow" className={styles.cow} style={cowStyle} />
</div>
)
}
Cow.propTypes = {
height: PropTypes.number
}
export default Cow
<file_sep>/src/Clouds.js
import React from 'react'
import PropTypes from 'prop-types'
import Cloud from './Cloud'
const Clouds = props => {
let CloudList = []
for (let i = 0; i < props.count; i++) {
CloudList.push(
<Cloud
transitionTime={Math.random() * 30 + 15}
scale={Math.random() * 0.5 + 0.3}
fromTop={Math.random() * 75}
key={i}
/>
)
}
return CloudList
}
Clouds.propTypes = {
count: PropTypes.number
}
export default Clouds
| d534cd525e0587eab917ffe5f7f9950d15b0ec2f | [
"JavaScript"
] | 11 | JavaScript | joeinnes/mtc | 5564487327e956ffad4fcd0afe59129196965c2c | db0333e9751321e1c2d6a3f74183d93104cc6b68 |
refs/heads/master | <repo_name>ozanozbirecikli/Projects<file_sep>/Sorgu.java
package Internship;
import java.sql.*;
public class Sorgu {
private static int count;
private static int totalpopulation;
public static void viewTable(Connection con, String dbName) throws SQLException {
Statement stmt = null;
String query = "SELECT code, name FROM " + dbName + " order BY name";
String query2 = "SELECT id, cityname, countrycode, district, population FROM " + dbName + " order BY population";
try {
stmt = con.createStatement();
ResultSet rs2 = stmt.executeQuery(query);
ResultSet rs = stmt.executeQuery(query2);
while (rs2.next()) {
int code = rs2.getInt("code");
String countryname = rs2.getString("name");
count = 0;
totalpopulation = 0;
while (rs.next()) {
int id = rs.getInt("id");
String cityname = rs.getString("cityname, (district)");
int countrycode = rs.getInt("countrycode");
// String district = rs.getString("district");
int population = rs.getInt("population");
System.out.println(id + "\t" + cityname + "\t" + countrycode + "\t" + population);
count(countrycode, code, population);
}
if (verification() == true) {
System.out.println(countryname + "\t" + code + "\t" + count + "\t" + totalpopulation);
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stmt != null) {
stmt.close();
}
}
}
public static void count(int countrycode, int code, int population) {
if (countrycode == code) {
count++;
}
population++;
}
public static boolean verification() {
if (count >= 15 && totalpopulation >= 3000000) {
return true;
}
return false;
}
}
<file_sep>/FarmBank/Farmer.java
package FarmBank;
import java.util.ArrayList;
public class Farmer extends Account {
private double farmbalance;
private ArrayList<Product> myProducts = new ArrayList<Product>();
public Farmer() {
}
public Farmer(String username, String name, String surname, String password, String password_again, String listoflocations) {
super(username, name, surname, password, password_again, listoflocations);
this.farmbalance = 0;
System.out.println("Farmer has been registered");
}
public double getFarmbalance() {
return farmbalance;
}
public void setFarmbalance(double d){
farmbalance +=d;
}
public String toString() {
return super.toString();
}
public ArrayList getmyProducts() {
return myProducts;
}
public void setMyProductsAmnt(int n, int a){
myProducts.get(n).setAmount(a);
}
public String getInfo2(int n){
return myProducts.get(n).getInfo();
}
public int getAmnt(int n){
return myProducts.get(n).getAmount();
}
public double getMyPrice(int n){
return myProducts.get(n).getPrice();
}
}
<file_sep>/README.md
# Projects
These are the projects that i have done.
<file_sep>/FarmBank/FarmBankAccount.java
package FarmBank;
import javax.swing.*;
import java.awt.*;
public class FarmBankAccount extends FarmBank{
private Account farmbank;
private static double balance = 0;
public FarmBankAccount() {
farmbank = new Account("FarmBank", "FarmBank", "Account", "farmbank", "farmbank", " ");
farmbankview();
}
public void farmbankview() {
JFrame frame = new JFrame("Farm Bank");
frame.setSize(new Dimension(1250, 750));
frame.setLayout(new BorderLayout());
frame.setLocation(170, 75);
JPanel uppanel = new JPanel();
uppanel.setBackground(Color.LIGHT_GRAY);
frame.add(uppanel, BorderLayout.NORTH);
JLabel balance2 = new JLabel("Balance: " + balance);
uppanel.add(balance2);
JLabel username = new JLabel(farmbank.getUsername() + " ");
uppanel.add(username);
JLabel name = new JLabel(farmbank.getName() + " " + farmbank.getSurname() + " ");
uppanel.add(name);
JButton quit = new JButton("Quit");
uppanel.add(quit, BorderLayout.CENTER);
quit.addActionListener(q1 -> {
frame.setVisible(false);
});
JPanel center = new JPanel();
center.setLayout(new GridLayout(1,3));
frame.add(center, BorderLayout.CENTER);
JPanel productPanel = new JPanel();
productPanel.setBounds(50, 100, 300, 500);
JLabel products = new JLabel(" ----PRODUCTS---- ");
productPanel.add(products);
for (Object p : getproductArray()) {
productPanel.add(new JLabel(p.toString()));
}
center.add(productPanel);
JPanel farmerPanel = new JPanel();
farmerPanel.setBounds(380, 100, 300, 500);
JLabel farmers = new JLabel(" ----FARMERS---- ");
farmerPanel.add(farmers);
for (Farmer f : getFarmerList()) {
farmerPanel.add(new JLabel(f.toString()));
}
center.add(farmerPanel);
JPanel cstomerPanel = new JPanel();
cstomerPanel.setBounds(710, 100, 300, 500);
JLabel customers = new JLabel(" ----CUSTOMERS---- ");
cstomerPanel.add(customers);
for (Customer c : getCustomerList()) {
cstomerPanel.add(new JLabel(c.toString()));
}
center.add(cstomerPanel);
frame.setVisible(true);
}
public static void setBalance(double n){
balance += n;
System.out.println(balance);
}
}
<file_sep>/FarmBank/Openingscreen.java
package FarmBank;
import javax.swing.*;
import java.awt.*;
public class Openingscreen {
public static void main(String[] args){
JFrame frame = new JFrame("Farm Bank");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(350,200));
frame.setLocation(550,300);
frame.setLayout(new FlowLayout());
JPanel userpanel = new JPanel();
frame.add(userpanel, BorderLayout.CENTER);
userpanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
JRadioButton login = new JRadioButton("Login");
JRadioButton register = new JRadioButton("Register");
ButtonGroup group1 = new ButtonGroup();
group1.add(login);
group1.add(register);
userpanel.add(login);
userpanel.add(register);
JButton customer = new JButton("Customer");
userpanel.add(customer);
JButton farmer = new JButton("Farmer");
userpanel.add(farmer);
OpeningScreenListener listener = new OpeningScreenListener(register, login, customer, farmer);
customer.addActionListener(listener);
farmer.addActionListener(listener);
frame.setVisible(true);
}
}
<file_sep>/FarmBank/LoginListener.java
package FarmBank;
import Exercises.Farm;
import javax.swing.*;
import java.awt.event.*;
import static FarmBank.RegisterListener.customer;
import static FarmBank.RegisterListener.farmer;
public class LoginListener extends FarmBank implements ActionListener {
private JTextField username;
private JTextField password;
private JFrame frame;
private Account acc;
private Account acc2;
public LoginListener(Account acc, Account acc2, JTextField username, JTextField password, JFrame frame) {
this.acc = acc;
this.username = username;
this.password = <PASSWORD>;
this.frame = frame;
this.acc2 = acc2;
}
public void actionPerformed(ActionEvent e) {
if (acc instanceof Account && (FarmBankchecker(username, password))) {
FarmBankAccount farmbank = new FarmBankAccount();
frame.setVisible(false);
}
if (acc instanceof Farmer) {
if (checker(acc, username, password) == true) {
FarmerView view2 = new FarmerView((Farmer) login(acc, username, password));
frame.setVisible(false);
} else
JOptionPane.showMessageDialog(null, "Wrong Username or Password");
}
if (acc instanceof Customer) {
if (checker(acc, username, password) == true) {
CustomerView view2 = new CustomerView((Customer) login(acc, username, password));
frame.setVisible(false);
} else
JOptionPane.showMessageDialog(null, "Wrong Username or Password");
}
}
}
<file_sep>/FarmBank/FarmerView.java
package FarmBank;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class FarmerView extends FarmBank {
private JFrame frame;
private Farmer farmer;
private JComboBox products;
private JTextField info2;
private JComboBox units;
private JTextField price2;
private JTextField amount2;
private JPanel items;
private int amnt;
private double prc;
public FarmerView(Farmer farmer){
this.farmer = farmer;
farmView();
}
public void farmView(){
frame = new JFrame("Farmer View");
frame.setSize(new Dimension(1250, 750));
frame.setLayout(new BorderLayout());
frame.setLocation(170,75);
JPanel uppanel = new JPanel();
uppanel.setBackground(Color.LIGHT_GRAY);
frame.add(uppanel, BorderLayout.NORTH);
JLabel balance = new JLabel("Balance: " + farmer.getFarmbalance() + " ");
uppanel.add(balance);
JLabel username = new JLabel(farmer.getUsername() + " ");
uppanel.add(username);
JLabel name = new JLabel(farmer.getName() + " " + farmer.getSurname() + " ");
uppanel.add(name);
JButton quit = new JButton("QUIT");
uppanel.add(quit, BorderLayout.EAST);
quit.addActionListener(q2 ->{
frame.setVisible(false);
} );
JPanel mainpanel = new JPanel();
mainpanel.setBackground(Color.WHITE);
mainpanel.setLayout(new BorderLayout());
JPanel mainpanel2 = new JPanel();
mainpanel2.setBackground(Color.GREEN);
mainpanel.add(mainpanel2, BorderLayout.EAST);
JLabel orderlabel = new JLabel("Orders That Have Been Taken");
mainpanel2.add(orderlabel);
JLabel orders = new JLabel();
mainpanel2.add(orders);
JTabbedPane tabbedPane = new JTabbedPane();
frame.add(tabbedPane);
tabbedPane.addTab("ACCOUNT", null, mainpanel, "You can see your Account");
JPanel additem = new JPanel();
additem.setLayout(null);
additem.setBackground(Color.WHITE);
tabbedPane.addTab("CREATE ITEM",null, additem, "You can create items");
JLabel type = new JLabel("Product Type");
type.setBounds(50,30,150,30);
additem.add(type);
String [] productTypes = {"Cheese", "Milk", "Eggs", "Meat", "Chicken", "Butter", "Vegetables", "Fruits"};
products = new JComboBox(productTypes);
products.setBounds(205,30,150,40);
products.setSelectedIndex(0);
additem.add(products);
JLabel info = new JLabel("Description: ");
info.setBounds(50,100,150,30);
additem.add(info);
info2 = new JTextField("");
info2.setBounds(205,100,250,50);
additem.add(info2);
JLabel amount = new JLabel("Amount");
amount.setBounds(50,180,150,30);
additem.add(amount);
amount2 = new JTextField("Enter the Amount");
amount2.setBounds(205,180,100,30);
additem.add(amount2);
String [] unit = {"kg", "piece", "liter"};
units = new JComboBox(unit);
units.setBounds(315,180,75,40);
additem.add(units);
JLabel price = new JLabel("Price:");
price.setBounds(50,250,150,30);
additem.add(price);
price2 = new JTextField("Enter the Price");
price2.setBounds(205,250,100,30);
additem.add(price2);
JButton create = new JButton("Create");
create.setBounds(250,350,100,50);
additem.add(create);
items = new JPanel();
items.setBounds(800,100,450,650);
items.setBackground(Color.YELLOW);
JLabel items2 = new JLabel(" -------- Created Items -------- ");
items2.setBounds(900,120, 200,20);
items.add(items2);
create.addActionListener(new FarmerViewListener());
for(Object pr: farmer.getmyProducts()){
items.add(new JLabel(pr.toString()));
}
additem.add(items);
frame.setVisible(true);
}
class FarmerViewListener extends FarmBank implements ActionListener{
int x = 800;
int y = 150;
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if (source.getText().equals("Create")) {
String item = (String) products.getSelectedItem();
String descriptn = info2.getText();
String unit = (String)units.getSelectedItem();
try {
amnt = Integer.parseInt(amount2.getText());
}catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Please Enter an Integer");
}
try {
prc = Double.parseDouble(price2.getText());
Product product1 = new Product(item, descriptn, amnt, unit, prc);
addProduct(product1);
farmer.getmyProducts().add(product1);
JLabel label = new JLabel(getproductArray().get(getproductArray().size() - 1).toString());
label.setBounds(x, y, 250, 30);
items.add(label);
y += 30;
}catch (NumberFormatException ex2){
JOptionPane.showMessageDialog(null,"Please Enter a Double");
}
}
}
}
}
<file_sep>/FarmBank/RegisterView.java
package FarmBank;
import javax.swing.*;
import java.awt.*;
public class RegisterView extends JFrame {
private JPanel mainpanel;
private Account accountF;
private Account accountC;
public JFrame frame;
public RegisterView(Account acc) {
if (acc instanceof Farmer) {
accountF = new Farmer();
frame = new JFrame("Farmer Register");
FarmerRegister();
frame.setVisible(true);
}
if (acc instanceof Customer) {
accountC = new Customer();
frame = new JFrame("Customer Register");
Customerregister();
frame.setVisible(true);
}
}
public void Customerregister() {
frame.setSize(new Dimension(500, 500));
frame.setLocation(70, 100);
mainpanel = new JPanel();
frame.add(mainpanel);
mainpanel.setLayout(null);
JLabel label1 = new JLabel("Username: ");
label1.setBounds(20, 20, 100, 30);
mainpanel.add(label1);
JLabel label2 = new JLabel("Name: ");
label2.setBounds(20, 60, 100, 30);
mainpanel.add(label2);
JLabel label3 = new JLabel("Surname: ");
label3.setBounds(20, 100, 100, 30);
mainpanel.add(label3);
JLabel label4 = new JLabel("Password: ");
label4.setBounds(20, 140, 100, 30);
mainpanel.add(label4);
JLabel label5 = new JLabel("Confirm Password:");
label5.setBounds(20, 180, 120, 30);
mainpanel.add(label5);
JTextField username = new JTextField("Please Enter Your Username");
username.setBounds(220, 20, 220, 30);
mainpanel.add(username);
JTextField name = new JTextField("Please Enter Your Name");
name.setBounds(220, 60, 220, 30);
mainpanel.add(name);
JTextField surname = new JTextField("Please Enter Your Surname");
surname.setBounds(220, 100, 220, 30);
mainpanel.add(surname);
JTextField password = new JTextField("Please Enter Your Password");
password.setBounds(220, 140, 220, 30);
mainpanel.add(password);
JTextField password_again = new JTextField("Please Enter Your Password again");
password_again.setBounds(220, 180, 220, 30);
mainpanel.add(password_again);
JCheckBox robot = new JCheckBox("I am not a robot");
mainpanel.add(robot);
robot.setBounds(20, 300, 200, 20);
JLabel listofloc = new JLabel("Your Locations:");
mainpanel.add(listofloc);
listofloc.setBounds(20, 220, 100, 30);
JTextField list = new JTextField("Enter Your Location");
mainpanel.add(list);
list.setBounds(220, 220, 220, 30);
JButton enter = new JButton("Enter");
enter.setBounds(200, 350, 100, 50);
mainpanel.add(enter);
enter.addActionListener(new RegisterListener(username, name, surname, password, password_again, list, accountC, frame));
}
public void FarmerRegister() {
frame.setSize(new Dimension(500, 500));
frame.setLocation(70, 100);
mainpanel = new JPanel();
frame.add(mainpanel);
mainpanel.setLayout(null);
JLabel label1 = new JLabel("Username: ");
label1.setBounds(20, 20, 100, 30);
mainpanel.add(label1);
JLabel label2 = new JLabel("Name: ");
label2.setBounds(20, 60, 100, 30);
mainpanel.add(label2);
JLabel label3 = new JLabel("Surname: ");
label3.setBounds(20, 100, 100, 30);
mainpanel.add(label3);
JLabel label4 = new JLabel("Password: ");
label4.setBounds(20, 140, 100, 30);
mainpanel.add(label4);
JLabel label5 = new JLabel("Confirm Password:");
label5.setBounds(20, 180, 120, 30);
mainpanel.add(label5);
JTextField username = new JTextField("Please Enter Your Username");
username.setBounds(220, 20, 220, 30);
mainpanel.add(username);
JTextField name = new JTextField("Please Enter Your Name");
name.setBounds(220, 60, 220, 30);
mainpanel.add(name);
JTextField surname = new JTextField("Please Enter Your Surname");
surname.setBounds(220, 100, 220, 30);
mainpanel.add(surname);
JTextField password = new JTextField("Please Enter Your Password");
password.setBounds(220, 140, 220, 30);
mainpanel.add(password);
JTextField password_again = new JTextField("Please Enter Your Password again");
password_again.setBounds(220, 180, 220, 30);
mainpanel.add(password_again);
JCheckBox robot = new JCheckBox("I am not a robot");
mainpanel.add(robot);
robot.setBounds(20, 300, 200, 20);
JButton enter = new JButton("Enter");
enter.setBounds(200, 350, 100, 50);
mainpanel.add(enter);
JLabel listofloc = new JLabel("List Of Locations:");
mainpanel.add(listofloc);
listofloc.setBounds(20, 220, 100, 30);
JTextField list = new JTextField("Enter The List Of Locations");
mainpanel.add(list);
list.setBounds(220, 220, 220, 30);
enter.addActionListener(new RegisterListener(username, name, surname, password, password_again, list, accountF, frame));
}
}
| a85d500c45362a40c005eeb1a35a910a29de77d7 | [
"Markdown",
"Java"
] | 8 | Java | ozanozbirecikli/Projects | d5368c7172da58ce50bc72bf8b2b91c8ff2d0577 | dc9e6ad126a76843641f0cdb1e35273ff6dcda47 |
refs/heads/master | <repo_name>ufcpp/LazyMixin<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/AccessViaProperty/AccessViaPropertyAnalyzer.cs
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
namespace LazyMixinAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class AccessViaPropertyAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "AccessViaProperty";
internal const string Title = "It is recommended to access a field of LazyMixin<T> via a property.";
internal const string MessageFormat = "The field '{0}' is LazyMixin<T>, which Value can be encapsulated with a property.";
internal const string Category = "Correction";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Info, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeFieldDeclaration, SymbolKind.Field);
}
private void AnalyzeFieldDeclaration(SymbolAnalysisContext context)
{
var f = (IFieldSymbol)context.Symbol;
var containing = f.ContainingType;
foreach (var p in containing.GetMembers().OfType<IPropertySymbol>())
{
if (p.Name.ToLower() == f.Name.TrimStart('_').ToLower())
return;
}
var t = f.Type;
if (t.IsTargetType())
{
var node = f.DeclaringSyntaxReferences.First().GetSyntax();
var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), f.Name);
context.ReportDiagnostic(diagnostic);
}
}
}
}
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/AssemblyAttributes.cs
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("LazyMixinAnalyzer.Test")]
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/TypeExtensions.cs
using Microsoft.CodeAnalysis;
namespace LazyMixinAnalyzer
{
static class TypeExtensions
{
/// <summary>
/// Check <paramref name="t"/> is a target type of this code analyzer/code generator, the Laziness.LazyMixin{T}.
/// This uses only its name, loosely typed.
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static bool IsTargetType(this ITypeSymbol t) => t.ContainingNamespace?.Name == "Laziness" && t.MetadataName == "LazyMixin`1";
}
}
<file_sep>/README.md
# LazyMixin
Simple mixin-like implementation for lazy initialization without thread-safety.
## Installation
You can donwload from NuGet, [LazyMixin](https://www.nuget.org/packages/LazyMixin/).
PM> Install-Package LazyMixin
requires Visual Studio 2015.
## How to use
The `LazyMixin<T>` struct is simple and efficient in memory usage, but has tight restrictions because of the C# struct (.NET value type) charactaristics.
- Do not use for a property. It makes a copied value.
- Do not use for a readonly field. It also makes a copied value.
for instance:
// Do not
public LazyMixin<T> X { get; }
// Do not
private readonly LazyMixin<T> _x;
// Recommended usage
public T X => _x.Value;
private LazyMixin<T> _x;
It is thus highly recommended to use this struct with the LazyMixinAnalyzer analyzer.
This analyzer is included within the LazyMixin Nuget package so that you can automatically use it.
The analyzer provides:
Error on using `LazyMixin<T>` for a property
public LazyMixin<T> X { get; } // error: DoNotUseLazyForProperty
Error on using `LazyMixin<T>` for a read-only field
private readonly LazyMixin<T> _x; // error: DoNotUseLazyForReadonlyField
Code Fix to encapsulate a `LazyMixin<T>` field with a property
private LazyMixin<T> _x; // info: AccessViaProperty
the fix result is:
public T X => _x.Value;
private LazyMixin<T> _x;
## Sample
There are some samples in test codes
- [LazyMixin.Test/UnitTest1.cs](https://github.com/ufcpp/LazyMixin/blob/master/LazyMixin/LazyMixin.Test/UnitTest1.cs)
- [LazyMixinAnalyzer.Test/DoNotUseLazyForPropertyUnitTests.cs](https://github.com/ufcpp/LazyMixin/blob/master/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/DoNotUseLazyForPropertyUnitTests.cs)
- [LazyMixinAnalyzer.Test/DoNotUseLazyForReadonlyFieldUnitTests.cs](https://github.com/ufcpp/LazyMixin/blob/master/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/DoNotUseLazyForReadonlyFieldUnitTests.cs)
- [LazyMixinAnalyzer.Test/AccessViaPropertyUnitTests.cs](https://github.com/ufcpp/LazyMixin/blob/master/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/AccessViaPropertyUnitTests.cs)
## License
under [MIT License](http://opensource.org/licenses/MIT)
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/DataSource/AccessViaPropertyUnitTest/NoNamespace/Source.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Laziness;
class TypeName
{
public StringBuilder X => _x.Value;
private LazyMixin<StringBuilder> _x;
}
class A { }
struct B { }
class C
{
private A _a;
private B _b;
public readonly A[] _c;
public A[,] _d;
protected readonly B[] _e;
protected B[,] _f;
}
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/AccessViaProperty/AccessViaPropertyCodeFixProvider.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace LazyMixinAnalyzer
{
[ExportCodeFixProvider("LazyMixinAnalyzerCodeFixProvider", LanguageNames.CSharp), Shared]
public class AccessViaPropertyCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(AccessViaPropertyAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<FieldDeclarationSyntax>().First();
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create("Encapsulate", c => Encapsulate(context.Document, declaration, c), "EncapsulateLazyMixinField"),
diagnostic);
}
private static readonly SyntaxToken PublicToken = SyntaxFactory.Token(SyntaxKind.PublicKeyword);
private static readonly SyntaxToken ArrowToken = SyntaxFactory.Token(SyntaxKind.EqualsGreaterThanToken);
private static readonly SyntaxToken SemicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken);
private GenericNameSyntax GetType(TypeSyntax t)
{
var gt = t as GenericNameSyntax;
if (gt != null) return gt;
var qt = t as QualifiedNameSyntax;
if (qt != null) return GetType(qt.Right);
//todo: AliasQualifiedNameSyntax
return null;
}
private async Task<Document> Encapsulate(Document document, FieldDeclarationSyntax f, CancellationToken cancellationToken)
{
var fieldType = GetType(f.Declaration.Type);
if (fieldType == null) return document;
var fieldName = f.Declaration.Variables.First().Identifier.ValueText;
var lower = fieldName.TrimStart('_');
var upper = char.ToUpper(lower[0]) + lower.Substring(1, lower.Length - 1);
var elementType = fieldType.TypeArgumentList.Arguments.First();
var oldNode = f.FirstAncestorOrSelf<ClassDeclarationSyntax>();
var p = SyntaxFactory.PropertyDeclaration(elementType, upper)
.WithModifiers(SyntaxTokenList.Create(PublicToken))
.WithExpressionBody(
SyntaxFactory.ArrowExpressionClause(
ArrowToken,
SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName(fieldName),
SyntaxFactory.IdentifierName("Value")
)
)
)
.WithSemicolonToken(SemicolonToken)
.WithAdditionalAnnotations(Formatter.Annotation)
;
var xx = p.ToString();
var xx1 = p.GetText().ToString();
var newNode = oldNode.InsertNodesBefore(f, new[] { p });
// .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(
var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = oldRoot.ReplaceNode(oldNode, newNode);
return document.WithSyntaxRoot(newRoot);
}
}
}<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/AccessViaPropertyUnitTests.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using TestHelper;
using Xunit;
namespace LazyMixinAnalyzer.Test
{
public class AccessViaPropertyUnitTest : ConventionCodeFixVerifier
{
[Fact]
public void NoDiagnositcs() => VerifyCSharpByConvention();
[Fact]
public void NoNamespace() => VerifyCSharpByConvention();
[Fact]
public void AccessViaProperty() => VerifyCSharpByConvention();
[Fact]
public void AccessViaPropertyWithQualifiedName() => VerifyCSharpByConvention();
protected override CodeFixProvider GetCSharpCodeFixProvider() => new AccessViaPropertyCodeFixProvider();
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => new AccessViaPropertyAnalyzer();
protected override IEnumerable<MetadataReference> References
{
get
{
foreach (var x in base.References) yield return x;
yield return MetadataReference.CreateFromFile(typeof(Laziness.LazyMixin<>).Assembly.Location);
}
}
}
}<file_sep>/LazyMixin/LazyMixin.Test/UnitTest1.cs
using Xunit;
namespace Laziness.Test
{
public class UnitTest1
{
[Fact]
public void TestLazyMixinCounter()
{
var sample = new Sample();
Assert.False(sample.IsInitialized);
sample.Counter.Add();
Assert.True(sample.IsInitialized);
sample.Counter.Add();
sample.Counter.Add();
sample.Counter.Add();
Assert.Equal(4, sample.Counter.Count);
sample.Reset();
Assert.False(sample.IsInitialized);
sample.Counter.Add();
Assert.True(sample.IsInitialized);
sample.Counter.Add();
sample.Counter.Add();
sample.Counter.Add();
Assert.Equal(4, sample.Counter.Count);
}
[Fact]
public void TestGetValueOrDefault()
{
var sample = new LazyMixin<Counter>();
Assert.Null(sample.GetValueOrDefault());
var v = sample.Value;
Assert.Equal(v, sample.GetValueOrDefault());
}
}
class Sample
{
public Counter Counter => _counter.Value;
private LazyMixin<Counter> _counter;
public bool IsInitialized => _counter.IsInitialized;
public void Reset() => _counter.Dispose();
}
class Counter
{
public int Count { get; private set; }
public void Add() => Count++;
}
}
<file_sep>/LazyMixin/LazyMixin/LazyMixin.cs
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("LazyMixin.Test")]
namespace Laziness
{
/// <summary>
/// Simple implementation for lazy initialization without thread-safety.
/// </summary>
/// <remarks>
/// This struct is simple and efficient in memory usage, but has many restriction because of the C# struct charactaristics.
/// - Do not use for a property. It makes a copied value.
/// - Do not use for a readonly field. It also makes a copied value.
///
/// It is thus highly recommended to use this struct with the LazyMixinAnalyzer.
/// </remarks>
/// <example><![CDATA[
/// // Do not
/// public Lazy<T> X { get; }
///
/// // Do not
/// public Lazy<T> X => _x.Value;
/// private readonly Lazy<T> _x;
///
/// // Recommended
/// public Lazy<T> X => _x.Value;
/// private Lazy<T> _x;
/// ]]></example>
/// <typeparam name="T"></typeparam>
public struct LazyMixin<T> : IDisposable
where T : class, new()
{
private T _value;
/// <summary>
/// Gets the lazily initialized value.
/// </summary>
public T Value => _value ?? (_value = new T());
/// <summary>
/// Get value, if created.
/// </summary>
public T GetValueOrDefault() => _value;
/// <summary>
/// Invokes value.Dispose if _value != null, then resets value to null.
/// </summary>
/// <remarks>
/// This struct can be resused. If you use the Value after invoking the Dispose, the Value is re-initialized.
/// </remarks>
public void Dispose()
{
if (_value != null)
{
(_value as IDisposable)?.Dispose();
_value = null;
}
}
internal bool IsInitialized => _value != null;
}
}
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/DoNotUseLazyForProperty/DoNotUseLazyForPropertyAnalyzer.cs
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
namespace LazyMixinAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DoNotUseLazyForPropertyAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "DoNotUseLazyForProperty";
internal const string Title = "Do not use LazyMixin<T> for a property.";
internal const string MessageFormat = "The type of the property '{0}' is LazyMixin<T>, which is not allowed.";
internal const string Category = "Correction";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzePropertyDeclaration, SymbolKind.Property);
}
private void AnalyzePropertyDeclaration(SymbolAnalysisContext context)
{
var p = (IPropertySymbol)context.Symbol;
var t = p.Type;
if (t.IsTargetType())
{
var node = p.DeclaringSyntaxReferences.First().GetSyntax();
var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), p.Name);
context.ReportDiagnostic(diagnostic);
}
}
}
}
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/DoNotUseLazyForReadonlyFieldUnitTests.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using TestHelper;
using Xunit;
namespace LazyMixinAnalyzer.Test
{
public class DoNotUseLazyForReadonlyFieldUnitTest : ConventionCodeFixVerifier
{
[Fact]
public void NoDiagnositcs() => VerifyCSharpByConvention();
[Fact]
public void DoNotUseLazyForReadonlyField() => VerifyCSharpByConvention();
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => new DoNotUseLazyForReadonlyFieldAnalyzer();
protected override IEnumerable<MetadataReference> References
{
get
{
foreach (var x in base.References) yield return x;
yield return MetadataReference.CreateFromFile(typeof(Laziness.LazyMixin<>).Assembly.Location);
}
}
}
}<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer/DoNotUseLazyForReadonlyField/DoNotUseLazyForReadonlyFieldAnalyzer.cs
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
namespace LazyMixinAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DoNotUseLazyForReadonlyFieldAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "DoNotUseLazyForReadonlyField";
internal const string Title = "Do not use LazyMixin<T> for a read-only field.";
internal const string MessageFormat = "The type of the readonly field '{0}' is LazyMixin<T>, which is not allowed.";
internal const string Category = "Correction";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(AnalyzeFiedlDeclaration, SymbolKind.Field);
}
private void AnalyzeFiedlDeclaration(SymbolAnalysisContext context)
{
var f = (IFieldSymbol)context.Symbol;
if (!f.IsReadOnly)
return;
var t = f.Type;
if (t.IsTargetType())
{
var node = f.DeclaringSyntaxReferences.First().GetSyntax();
var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), f.Name);
context.ReportDiagnostic(diagnostic);
}
}
}
}
<file_sep>/LazyMixin/LazyMixinAnalyzer/LazyMixinAnalyzer.Test/DataSource/DoNotUseLazyForPropertyUnitTest/DoNotUseLazyForProperty/Source/TypeName.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Laziness;
namespace ConsoleApplication1
{
class TypeName
{
public LazyMixin<StringBuilder> X { get; }
}
}
| 94a964860ec9fe2cfaca96d897c7981c1e2fec73 | [
"Markdown",
"C#"
] | 13 | C# | ufcpp/LazyMixin | 8de2fdf53e5ff83d4c2cd9b7fd0bb4157a65f8f8 | 7997daffd5fe85db7d4a6081fa8d150c01bfd555 |
refs/heads/master | <repo_name>sajinie93/Easy_Order_Mobile<file_sep>/src/providers/menu-item-service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {MenuItem} from "../models/menuItem";
@Injectable()
export class MenuItemService {
private data:any;
private menuItems:MenuItem[];
public selectedItems: MenuItem[];
constructor(public http: Http) {
console.log('Hello MenuItemService Provider');
}
loadMenuItems(){
var body = this.http.get('http://192.168.8.100:3000/menuItems')
.map(res => {
console.log('inside loadMenuItems function');
console.log('rec', res);
return res.json()
});
this.data = body.subscribe(menuItems =>{
// console.log(categories);
this.data=menuItems;
this.menuItems = this.data.menuItems;
});
this.menuItems = this.data.menuItems;
}
fetchData(category: string): MenuItem[]{
this.http.get('http://192.168.8.100:3000/menuItems')
.map(res => {
console.log('inside loadMenuItems function');
console.log('rec', res);
return res.json()
}).subscribe(menuItems =>{
console.log('inside inside loadMenuItems function');
this.data=menuItems;
this.menuItems = this.data.menuItems;
});
return this.menuItems;
}
fetchDataTest(category: string){
return this.http.get('http://192.168.8.100:3000/menuItems')
.map(res => {
console.log('inside loadMenuItems function');
console.log('rec', res);
return res.json()
});
}
}
<file_sep>/src/models/menuItem.ts
export class MenuItem{
constructor(public _id: string, public title: string, public description: string, public unit_price: string, public imagePath: string, public category: string){
}
}
<file_sep>/src/pages/category/category.ts
import {Component} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {CategoryService} from "../../providers/category-service";
import {Category} from "../../models/category";
import { GithubUsers } from '../../providers/github-users';
@Component({
selector: 'page-category',
templateUrl: 'category.html'
})
export class CategoryPage {
data:any;
items: Category[];
// set default category number to 2
select: "Burger";
constructor(public navCtrl: NavController, public navParams: NavParams, private categoryService: CategoryService, private githubUsers: GithubUsers) {
//fetch categories from category service and assign them to the item array
console.log('inside the category constructor');
categoryService.loadCategories().subscribe(categories =>{
console.log(categories);
this.data=categories;
this.items = this.data.categories;
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CategoryPage');
}
}
<file_sep>/src/models/category.ts
export class Category{
constructor(public id: string, public title: string, public isCustomizable: boolean){
}
}
<file_sep>/src/pages/shopping-cart/shopping-cart.ts
import {Component, DoCheck, OnChanges, OnInit, SimpleChanges} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {ShoppingCartService} from "../../providers/shopping-cart-service";
import {MenuItem} from "../../models/menuItem";
@Component({
selector: 'page-shopping-cart',
templateUrl: 'shopping-cart.html'
})
export class ShoppingCartPage implements OnInit, DoCheck, OnChanges{
//initialize shopping list and total price
shoppingList: MenuItem[] =[];
private totalPrize: number=0;
constructor(public navCtrl: NavController, public navParams: NavParams, private shoppingCartService: ShoppingCartService) {}
ionViewDidLoad() {
// console.log('ionViewDidLoad ShoppingCartPage');
}
ngOnInit(): void {
// console.log("wish list is updated in shopping cart");
}
//update the shopping list and the total price in each checking
ngDoCheck(): void {
console.log("docheck in shopping cart");
this.shoppingList = this.shoppingCartService.getWishList();
this.totalPrize = this.shoppingCartService.getPrice();
}
ngOnChanges(changes: SimpleChanges): void {
// console.log("onchanges in shopping cart");
}
//remove the items from wish-list
removeFromWishList(item: MenuItem):void{
this.shoppingCartService.removeFromWishList(item);
console.log('remove from list');
}
//calling the shopping cart service to place the order
placeOrder(){
this.shoppingCartService.placeOrder();
}
}
<file_sep>/src/models/sides.ts
// import {MenuItem} from "./menuItem";
// export class Sides extends MenuItem{
// constructor(public id: string,public title: string, public description: string, public unitPrice: number,public imagePath: string, public category: string){
// super( id, title,description,unitPrice , imagePath, category);
// }
// }
<file_sep>/src/providers/shopping-cart-service.ts
import { Injectable } from '@angular/core';
import {Http, RequestOptions, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import {MenuItem} from "../models/menuItem";
import {Observable} from "rxjs";
@Injectable()
export class ShoppingCartService {
private tableNum:number = 1;
private wishList: MenuItem[] = [];
private orderList: string[] = [];
private totalPrize: number;
restaurantApiUrl = 'http://192.168.8.100:3000';
constructor(public http: Http) {
this.totalPrize = 0;
}
addToWishList(menuItem: MenuItem){
this.wishList.push(menuItem);
this.orderList.push(menuItem._id);
this.totalPrize = this.totalPrize + parseInt(menuItem.unit_price);
}
removeFromWishList(menuItem: MenuItem){
this.totalPrize = this.totalPrize - parseInt(menuItem.unit_price);
this.wishList.splice(this.wishList.indexOf(menuItem), 1);
this.orderList.splice(this.orderList.indexOf(menuItem._id), 1);
}
getWishList(): MenuItem[]{
return this.wishList;
}
getPrice():number{
return this.totalPrize;
}
placeOrder(): Observable<MenuItem[]>{
let obj = {"order":this.orderList, "price": this.totalPrize, "tableNum": this.tableNum};
let body = JSON.stringify(obj);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
console.log(body);
return this.http.post(`${this.restaurantApiUrl}/placeOrder`, body, options)
.catch(this.handleError);
}
handleError(error) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
<file_sep>/src/providers/category-service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from "rxjs";
import {User} from "../models/users";
@Injectable()
export class CategoryService {
restaurantApiUrl = 'http://192.168.8.100:3000';
github = 'http://api.github.com';
constructor(public http: Http) {
}
loadCategories(){
return this.http.get('http://192.168.8.100:3000/categories')
.map(res => {
console.log('inside loadCategories function');
console.log('rec', res);
return res.json()
});
}
loads(): Observable<User[]> {
console.log('inside the load function');
return this.http.get(`${this.github}/users`)
.map(res => {
return <User[]>res.json()
});
}
}
<file_sep>/src/app/app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { TabsPage } from '../pages/tabs/tabs';
import {CategoryPage} from '../pages/category/category';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import {CategoryService} from "../providers/category-service";
import {AboutPage} from "../pages/about/about";
import {MenuItemService} from "../providers/menu-item-service";
import {MenuItemPage} from "../pages/menu-item/menu-item";
import {ShoppingCartService} from "../providers/shopping-cart-service";
import {ShoppingCartPage} from "../pages/shopping-cart/shopping-cart";
import {GithubUsers} from "../providers/github-users";
@NgModule({
declarations: [
MyApp,
TabsPage,
CategoryPage,
AboutPage,
MenuItemPage,
ShoppingCartPage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
TabsPage,
CategoryPage,
AboutPage,
MenuItemPage,
ShoppingCartPage
],
providers: [
StatusBar,
SplashScreen,
CategoryService,
MenuItemService,
ShoppingCartService,
GithubUsers,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
<file_sep>/src/pages/menu-item/menu-item.ts
import {Component, DoCheck, Input, OnChanges, OnInit} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {MenuItemService} from "../../providers/menu-item-service";
import {ShoppingCartService} from "../../providers/shopping-cart-service";
import {MenuItem} from "../../models/menuItem";
import {DomSanitizer } from '@angular/platform-browser';
// import {isUndefined} from "ionic-angular/umd/util/util";
// import {DomSanitizationService} from '@angular/platform-browser/src/security/dom_sanitization_service';
@Component({
selector: 'page-menu-item',
templateUrl: 'menu-item.html'
})
export class MenuItemPage implements OnChanges, OnInit, DoCheck {
// initialize the category
@Input() category :string="Burger";
items: MenuItem[];
data: any;
photo: any;
str: string;
constructor(public navCtrl: NavController, public navParams: NavParams, private menuItemService: MenuItemService, private shoppingCartService: ShoppingCartService, private sanitizer:DomSanitizer) {
// this.items = this.menuItemService.fetchData(this.category);
console.log('constructor of item page');
}
ionViewDidLoad() {
console.log('ionViewDidLoad MenuItemPage');
}
getImage (image) {
this.photo = this.sanitizer.bypassSecurityTrustUrl(`url(${image})`);
this.str = 'sajinie';
return this.sanitizer.bypassSecurityTrustUrl(`url(${image})`);
}
//calls when the category is changed
ngOnChanges(): void {
//fetch the menu items of the particular category soon after it is required
// if (this.category == isUndefined){
// console.log('this.category:',this.category);
// }
// onwaiting(this.category);
console.log('this.category:',this.category);
console.log('before onChanges');
this.menuItemService.fetchDataTest(this.category).subscribe(menuItems =>{
console.log(menuItems);
this.data=menuItems;
this.items = this.data.menuItems;
});
// this.items = this.menuItemService.fetchData(this.category);
console.log('after onChanges');
console.log(this.items);
}
ngDoCheck(): void {
// console.log('doCheck in menu item component');
}
ngOnInit(): void {
// this.items = this.menuItemService.fetchData(this.category);
// console.log('onInit in menu item component');
}
//add the tapped menu item to the wish-list
addToCart(item: MenuItem){
this.shoppingCartService.addToWishList(item);
}
itemTapped(item: MenuItem){
console.log(item + "is tapped");
}
}
| da35ddd89f0edffd22c7b1aad1524083dbfa36e6 | [
"TypeScript"
] | 10 | TypeScript | sajinie93/Easy_Order_Mobile | cb6c4975d0063646f8d4f7a5de785d04df42bd9b | 046bfae9e5904d6417c73c1f233a9b45cd10b037 |
refs/heads/master | <repo_name>AgentK1729/mlprsc<file_sep>/Programs/Fibonacci.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#define INPUTSIZE 46
int64_t start, end;
int64_t timeElapsed;
double i = 0, c;
double Fibonacci(double n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
{
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
}
int64_t printFibonacciTime()
{
struct timespec tms;
if (clock_gettime(CLOCK_MONOTONIC,&tms)) {
return -1;
}
int64_t micros = tms.tv_sec * 1000000;
micros += tms.tv_nsec/1000;
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return micros;
}
double main()
{
nice(1);
printf("Start Fibo ");
start = printFibonacciTime();
for ( c = 1 ; c <= INPUTSIZE ; c++ )
{
Fibonacci(i);
i++;
}
printf("End Fibo ");
end = printFibonacciTime();
timeElapsed = end - start;
printf("Fibo total : %"PRId64" microseconds , %f seconds\n", timeElapsed, (double)timeElapsed/1000000);
return 0;
}<file_sep>/make_exe.py
from sys import argv
def make_exe(filename, path):
"""
Compiles filename and makes executables in path
"""
from subprocess import Popen, PIPE
f = open(filename, "r")
linenum = 0
lines = []
flag = False
for line in f:
if "#define" in line:
flag = True
else:
if flag == False:
linenum += 1
lines.append(line)
for i in range(1, 46):
temp_line = lines[linenum].split(" ")
temp_line[-1] = str(i)+"\n"
lines[linenum] = ' '.join(temp_line)
f1 = open(filename, "w")
f1.write(''.join(lines))
f1.close()
command = "gcc %s -o %s%s%d" % (filename, path, filename.split(".")[0], i)
Popen(command, shell=True, stdout=PIPE).stdout
make_exe(argv[1], argv[2])<file_sep>/Programs/bubble.c
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#define MAX 79903
int64_t start, end;
int64_t timeElapsed;
int list[MAX];
void display() {
int i;
printf("[");
for(i = 0; i < MAX; i++) {
printf("%d ",list[i]);
}
printf("]\n");
}
void bubbleSort() {
int temp;
int i,j;
bool swapped = false;
for(i = 0; i < MAX-1; i++) {
swapped = false;
for(j = 0; j < MAX-1-i; j++) {
if(list[j] > list[j+1]) {
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
swapped = true;
}
}
if(!swapped) {
break;
}
}
}
int64_t printBubbleTime()
{
struct timespec tms;
if (clock_gettime(CLOCK_MONOTONIC,&tms)) {
return -1;
}
int64_t micros = tms.tv_sec * 1000000;
micros += tms.tv_nsec/1000;
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return micros;
}
void main() {
nice(-15);
int i;
printf("Start Bubble ");
start = printBubbleTime();
for (i=0; i<MAX; i++)
{
list[i] = rand() % 100;
}
bubbleSort();
printf("End Bubble ");
end = printBubbleTime();
timeElapsed = end - start;
printf("bubble total : %"PRId64" microseconds , %f seconds\n", timeElapsed, (double)timeElapsed/1000000);
}
<file_sep>/Programs/HeapSort.c
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <inttypes.h>
#define N 2500
int64_t start, end;
int64_t timeElapsed;
long heap[N];
int64_t printHeapTime()
{
struct timespec tms;
if (clock_gettime(CLOCK_MONOTONIC,&tms)) {
return -1;
}
int64_t micros = tms.tv_sec * 1000000;
micros += tms.tv_nsec/1000;
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return micros;
}
void main()
{
long i, j, c, root, temp;
printf("Start Heap ");
start = printHeapTime();
for (i = 0; i < N; i++)
heap[i] = rand()%1000;
for (i = 1; i < N; i++)
{
c = i;
do
{
root = (c - 1) / 2;
if (heap[root] < heap[c])
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
c = root;
} while (c != 0);
}
for (j = N - 1; j >= 0; j--)
{
temp = heap[0];
heap[0] = heap[j];
heap[j] = temp;
root = 0;
do
{
c = 2 * root + 1;
if ((heap[c] < heap[c + 1]) && c < j-1)
c++;
if (heap[root]<heap[c] && c<j)
{
temp = heap[root];
heap[root] = heap[c];
heap[c] = temp;
}
root = c;
} while (c < j);
}
printf("End Bubble ");
end = printHeapTime();
timeElapsed = end - start;
printf("Heap total : %"PRId64" microseconds , %f seconds\n", timeElapsed, (double)timeElapsed/1000000);
}<file_sep>/jsonify.py
from sys import argv
def parse(path):
def jsonify(string):
lines = []
for line in string:
lines.append(line)
count = int(lines[0].split(" ")[2])
attr = {}
required_keys = [".gnu.hash", ".dynamic", ".dynsym", ".dynstr", ".got",
".plt", ".rodata", ".rela.dyn"]
for i in range(1, count):
split_line = lines[4+i].split()
if i <= 9:
if split_line[2] in required_keys:
attr[split_line[2]] = int(split_line[6], 16)
else:
if split_line[1] in required_keys:
attr[split_line[1]] = int(split_line[5], 16)
return attr
from os import listdir
from subprocess import Popen, PIPE
from json import dump
files = listdir(path)
data = {}
digits = [str(i) for i in range(10)]
for filename in files:
command = "readelf -SW %s" % path+filename
print filename
ind = 0
while filename[ind] not in digits:
ind += 1
input_size = int(filename[ind:])
temp_data = jsonify(Popen(command, shell=True, stdout=PIPE).stdout)
command = "size %s" % path+filename
size_data = Popen(command, shell=True, stdout=PIPE).stdout
lines = []
for line in size_data:
lines.append(line)
temp_data["text"] = int(lines[1].split()[0])
temp_data["data"] = int(lines[1].split()[1])
temp_data["bss"] = int(lines[1].split()[2])
temp_data["input_size"] = input_size
data[filename] = temp_data
dump(data, open("data.json", "w"))
parse(argv[1])<file_sep>/Programs/MatrixMultiplicationLong.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <stdint.h>
#include <inttypes.h>
#define INPUTSIZE 1500
long long m, n, p, q, c, d, k, sum = 0;
long long mat1_row, mat1_col, mat2_row, mat2_col = 0;
long long randomNumber = 0;
long long first[INPUTSIZE][INPUTSIZE], second[INPUTSIZE][INPUTSIZE], multiply[INPUTSIZE][INPUTSIZE];
int64_t start, end;
int64_t timeElapsed;
void MatrixMultiplication()
{
mat1_row = mat1_col = mat2_row = mat2_col = INPUTSIZE;
for (c = 0; c < mat1_row; c++) {
for (d = 0; d < mat2_col; d++) {
for (k = 0; k < mat2_row; k++) {
randomNumber = rand() % 1000;
sum = sum + randomNumber * randomNumber;
}
multiply[c][d] = sum;
sum = 0;
}
}
}
int64_t printMatrixTime()
{
struct timespec tms;
if (clock_gettime(CLOCK_MONOTONIC,&tms)) {
return -1;
}
int64_t micros = tms.tv_sec * 1000000;
micros += tms.tv_nsec/1000;
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return micros;
}
double main()
{
nice(-8);
printf("Start Matrix Mul ");
start = printMatrixTime();
MatrixMultiplication();
printf("End Matrix Mul ");
end = printMatrixTime();
timeElapsed = end - start;
printf("Matrix total : %"PRId64" microseconds , %f seconds\n", timeElapsed, (double)timeElapsed/1000000);
return 0;
}<file_sep>/README.md
This readme file contains instructions to run the source code
of project: Applying Machine Learing To Process Scheduling.
In /Program folder there are source code files of the programs we used in our project.
All of the programs are written using C and Python programming languages.
The script "make_exe.py" generates executable files for any C program you pass to it. We used this script to generate several executables of various computation-intensive programs to use for our learning model.
To run this script, type "python make_exe.py program_name path_to_store_executable"
The script "jsonify.py" converts the data we get from readelf and size commands to JSON format, which we use for training our model. To run this script, type
"python jsonify.py path_to_executables"
To execute our code and verify our results, please refer to the following steps:
Each program has exactly one macro named 'INPUTSIZE' define inside it that defines the input size of that programs.
This macro can be editted using any text editor to change the input size of the programs.
Steps to compile the source code
1. Open the directory /Programs.
2. Open the programs with any text editor and edit the input size of programs.
3. Open the Linux terminal window and navigate to the /Programs folder.
4. Using the GCC compiler, compile the programs to generate the executable.
5. Commands to compile the source code
$ gcc MatrixMultiplicationLong.c -o mat1500
$ gcc Fibonacci.c -o fib46
$ gcc bubble.c -o bub79903
6. Above instruction will geberate the executable named 'mat1500', 'fib46', 'bub79903'.
Note: Throughout our project we followed this nomenclature for naming the executables.
The first characters indicate the program name and last digits indicate the input size.
For Example: 'mat1500' is an executable file of Matrix Multipmication program that multiplies
two matrices of 1500 * 1500 dimension.
We have deliberately chosen high input size of the programs such that they take longer duration to finish
their execution.
This helps us to accurately measure the change in turnaround time of any process.
The above generated programs must be run in parallel in order to get the most accurate results
Steps to run the programs in parallel.
1. Open the Linux terminal and navigate to the folder /Programs
2. Run the above executables in parallel by using the setsid command.
3. Syntax is
$ setsid ./fib46 && setsid ./mat1500 && setsid ./bub79903
Steps to compute the total turnaround time of each process.
1. Note which program was executed first.
2. Note the starting time of the program that was executed first.
3. Wait until all programs finish their execution.
4. Compute the total turnaround time of a process by subtracting the start time of first process from its finish time.
5. Repeat the above step for all the processes for calculating their respective turnaround time.
| 9a2f19c08c5eb4a7a53e0cc1f25d73c1cb73de7d | [
"Markdown",
"C",
"Python"
] | 7 | C | AgentK1729/mlprsc | 32493e632f3a5f7b6fc3e3abaab40ef16fe6fd80 | 695445d1bee8f1ea239804b63765db14788078b8 |
refs/heads/master | <repo_name>utfpr/municipalMarketFairControl<file_sep>/backend/routes/celula.js
const express = require('express');
const { body, param, validationResult } = require('express-validator/check');
const { isCpf } = require('./utils');
const router = express.Router();
const celulaController = require('../controllers/celula');
const feiranteController = require('../controllers/feirante');
const authMiddleware = require('../middlewares/auth');
router.get('/', authMiddleware.isSupervisor, async (req, res) => {
const celulas = await celulaController.listCelula();
return res.json(celulas.map(celula => celula));
});
router.get('/:id', authMiddleware.isSupervisor, [param('id').isInt()], async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send({ msg: 'id_nao_existente' });
const { id } = req.params;
const celula = await celulaController.findCelulaById(id);
if (celula === null) return res.status(400).send({ msg: 'id_nao_existente' });
return res.status(200).send(celula);
});
router.put(
'/:id',
authMiddleware.isSupervisor,
[
param('id').isInt(),
body('cpf_feirante')
.custom(isCpf)
.optional(),
body('periodo')
.isInt({ min: 1, max: 3 })
.optional(),
],
async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send();
const cpfFeirante = req.body.cpf_feirante;
const { periodo } = req.body;
const { id } = req.params;
const celula = await celulaController.findCelulaById(id);
if (celula === null) return res.status(400).send({ msg: 'id_nao_existente' });
if (cpfFeirante !== undefined) {
const feirante = await feiranteController.findFeiranteByCpf(cpfFeirante);
if (feirante === null) return res.status(400).send({ msg: 'cpf_nao_existente' });
}
const atualizado = await celulaController.updateCelula(id, {
...(cpfFeirante !== undefined ? { cpf_feirante: cpfFeirante } : {}),
...(periodo !== undefined ? { periodo } : {}),
});
if (atualizado === null) return res.status(400).send({ msg: 'erro' });
return res.status(200).send({ msg: 'ok' });
},
);
module.exports = router;
<file_sep>/docs/api/subcategoria.md
# Subcategoria
## ```POST /subcategoria``` - Adicionar subcategoria
- Headers
```
token: <jwt supervisor>
```
- Body
```javascript
{
"nome": "Bolos",
"categoria_id": "1"
}
```
- Resposta *#1A* - **Code 200** - Subcategoria cadastrada
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#1C* - **Code 200** - ID não existente (categoria)
```javascript
{
"msg": "categoria_nao_existente"
}
```
- Resposta *#2* - **Code 400** - Atributos faltando
- Resposta *#3* - **Code 401** - Token inválido
## ```GET /subcategoria/1``` - Retorna informações de uma subcategoria pelo ID
- Headers:
```
token: <jwt supervisor>
```
- Resposta *#1A* - **Code 200** - Sucesso
```javascript
{
"id": "1",
"nome": "Doces",
"categoria_id": "1"
}
```
- Resposta *#1B* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 401** - Token inválido
## ```PUT /subcategoria/1``` - Atualiza subcategoria
- Headers:
```
token: <jwt supervisor>
```
- Body
```javascript
{
"nome": "Doces"
}
```
- Resposta *#1A* - **Code 200** - Subcategoria atualizada
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#1C* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 400** - Atributo incorreto
- Resposta *#3* - **Code 401** - Token inválido
## ```DELETE /subcategoria/1``` - Remove subcategoria
- Headers:
```
token: <jwt supervisor>
```
- Resposta *#1A* - **Code 200** - Sucesso
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#1C* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 401** - Token inválido
<file_sep>/backend/routes/image.js
const express = require('express');
const multer = require('multer');
const url = require('url');
const fs = require('fs');
const PATH = './uploads';
function checkIfDirectoryExists() {
if (!fs.existsSync(PATH)) {
fs.mkdir(PATH.replace('./', ''));
}
return PATH;
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
checkIfDirectoryExists('./uploads');
cb(null, './uploads');
},
filename: (req, file, cb) => {
const extArray = file.mimetype.split('/');
const extension = extArray[extArray.length - 1];
cb(null, `${Date.now()}.${extension}`);
},
});
const upload = multer({ storage });
// const upload = multer({ dest: 'uploads/' });
const router = express.Router();
router.post('/upload', upload.single('photo'), (req, res) => {
if (req.file) {
res.json(req.file);
}
});
router.get('/:filename', (req, res) => {
const request = url.parse(req.url, true);
const filename = request.pathname;
const filePath = `./uploads${filename}`;
fs.exists(filePath, (exists) => {
if (!exists) {
// 404 missing files
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
return;
}
const img = fs.readFileSync(filePath);
res.writeHead(200, { 'Content-Type': 'image/jpeg' });
res.end(img, 'binary');
});
});
module.exports = router;
<file_sep>/frontend/src/screens/PerfilFeirante/index.js
import React, { PureComponent } from 'react';
import {
Form,
} from 'antd';
import * as feiranteAPI from '../../api/feirante';
import ContentComponent from '../../components/ContentComponent';
import WrappedHorizontalFeirantesForm from '../Feirante/FeirantesForm';
class PerfilFeirante extends PureComponent {
state = {
loading: true,
feirante: {},
};
componentDidMount() {
this._loadValues();
}
_loadValues = async () => {
this.setState({loading: true});
const cpf = localStorage.getItem('userID')
const feirante = await feiranteAPI.getProfile(cpf);
this.setState({ feirante, loading: false });
console.log(feirante);
}
render() {
const {
loading, feirante,
} = this.state;
return (
<ContentComponent
loading={loading}
title="Perfil"
limitedSize
>
<WrappedHorizontalFeirantesForm readOnly feirante={feirante} />
</ContentComponent>
);
}
}
const WrappedHorizontalPerfilFeiranteForm = Form.create({ name: 'feiras_form' })(PerfilFeirante);
export default WrappedHorizontalPerfilFeiranteForm;<file_sep>/frontend/src/screens/Feirante/index.js
import React, { PureComponent, Fragment } from 'react';
import {
Button, Modal,
Tag, Table,
Select,
} from 'antd';
import ContentComponent from '../../components/ContentComponent';
import TabelaComponent from '../../components/TabelaComponent';
import FeirantesForm from './FeirantesForm';
import * as feirantesAPI from '../../api/feirante';
import EmptyComponent from '../../components/EmptyComponent';
const { Column } = Table;
const Option = Select.Option;
export default class FeiranteScreen extends PureComponent {
state = {
feirantes: [],
visible: false,
loading: true,
selectedFeirante: {},
};
componentDidMount() {
this._loadFeirantes();
}
_loadFeirantes = async () => {
this.setState({ loading: true });
const feirantes = await feirantesAPI.get();
this.setState({ feirantes, loading: false });
}
_onDeleteFeirante = async cpf => {
await feirantesAPI.del(cpf)
.then(() => {
this._loadFeirantes();
});
}
showModal = feirante => {
this.setState({
visible: true,
selectedFeirante: feirante,
});
}
handleOk = (e) => {
this.setState({
visible: false,
selectedFeirante: {},
});
}
handleCancel = (e) => {
this.setState({
visible: false,
selectedFeirante: {},
});
}
_renderModal = () => {
const { visible, selectedFeirante} = this.state;
return (
<Modal
title={ selectedFeirante && selectedFeirante.cpf
? `${selectedFeirante.nome} - ${selectedFeirante.nome_fantasia}`
: 'Cadastrar um novo feirante'
}
visible={visible}
onCancel={this.handleCancel}
footer={null}
destroyOnClose
maskClosable={false}
>
<FeirantesForm
feirante={selectedFeirante}
onSuccess={this.handleOk}
refresh={this._loadFeirantes}
/>
{
/* selectedFeirante && selectedFeirante.cpf
? (
<Fragment>
<Divider>
Subcategorias
</Divider>
<Subcategorias categoria={selectedCategoria} />
</Fragment>
) : null
*/
}
</Modal>
);
}
/* atrubutos :
cpf,
cnpj,
nome,
rg,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
*/
// TABELA SÓ COM AS INFORMAÇÕES BÁSICA, CLICAR NUMA MODAL ABRE O RESTO DAS INFORMAÇÕES !
render() {
const { feirantes, loading } = this.state;
return (
<Fragment>
<ContentComponent
buttonProps={{
text: 'Adicionar',
onClick: this.showModal,
type: 'primary',
icon: 'plus',
}}
title="Feirantes"
>
<Table
dataSource={feirantes}
size="small"
loading={loading}
pagination={{
pageSize: 15,
}}
locale={{
emptyText: <EmptyComponent onButtonClick={this.showModal} />
}}
>
<Column
key='nome'
dataIndex='nome'
title='Nome'
/>
<Column
key='nome_fantasia'
dataIndex='nome_fantasia'
title='Nome Fantasia'
/>
<Column
key='cpf'
dataIndex='cpf'
title='CPF'
width={120}
/>
<Column
key='rg'
dataIndex='rg'
title='RG'
width={100}
/>
<Column
key='cnpj'
dataIndex='cnpj'
title='CNPJ'
width={180}
render={(cnpj) => {
return cnpj
? cnpj
: <Tag color='#f50'>Não usa</Tag>
}}
/>
<Column
key='usa_ee'
dataIndex='usa_ee'
title='Voltagem'
width={70}
render={(usa_ee, linha) => {
return usa_ee
? <Tag color={linha.voltagem_ee === 110 ? '#87d068' : '#1abc9c'}>{linha.voltagem_ee}v</Tag>
: <Tag color="#f50">Não</Tag>
}}
/>
<Column
key='acoes'
title='Ações'
width={160}
render={ linha => (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Button
type="primary"
onClick={() => this.showModal(linha)}
>
Detalhes
</Button>
</div>
)}
/>
</Table>
{ this._renderModal() }
</ContentComponent>
</Fragment>
);
}
}
<file_sep>/frontend/src/api/celula.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/celula`;
export async function get() {
const info = await axios
.get(host, {
headers: { token: localStorage.getItem('token') },
})
.catch(() => null);
return info ? info.data : [];
}
<file_sep>/backend/tests/controllers/subcategoria.js
const { assert } = require('chai');
const models = require('../../models');
const categoriaController = require('../../controllers/categoria');
const subcategoriaController = require('../../controllers/subcategoria');
describe('subcategoria.js', () => {
beforeEach(async () => {
await models.categoria.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
});
after(() => {
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
});
describe('findSubcategoriaById', () => {
it('Retorna null caso não encontrar', async () => {
// Recuperando um subcategoria inexistente
const subcategoriaNull = await subcategoriaController.findSubcategoriaById(
9999999999999999999999999999,
);
assert.isNull(subcategoriaNull);
});
it('Retorna um ponteiro no caso de encontrar', async () => {
// Criando uma categoria e uma subcategoria na mão
const categoria = await categoriaController.addCategoria('Categoria_1', false);
const subcategoria = await models.subcategoria.create({
nome: 'Subcategoria_11',
categoria_id: categoria.id,
});
// Recuperando a subcategoria criada
const res = await subcategoriaController.findSubcategoriaById(subcategoria.id);
assert.isNotNull(res);
});
});
describe('addSubcategoria', () => {
it('Retorna um ponteiro para a subcategoria criada.', async () => {
// Criando na mão uma categoria para teste
const categoria = await categoriaController.addCategoria('Categoria_1', false);
assert.isNotNull(categoria);
// Criando uma subcategoria para teste
const subcategoria = await subcategoriaController.addSubcategoria(
'Subcategoria_11',
categoria.id,
);
assert.isNotNull(subcategoria);
// OBS: É possível adicionar 2 subcategoria com o mesmo nome
});
});
describe('updateSubcategoria', () => {
it('Alterando um nome de uma subcategoria', async () => {
// Criando uma categoria e uma subcategoria na mão
const categoria = await categoriaController.addCategoria('Categoria_1', false);
const subcategoria = await models.subcategoria.create({
nome: 'Subcategoria_11',
categoria_id: categoria.id,
});
// Alterando a subcategoria
const res = await subcategoriaController.updateSubcategoria(subcategoria.id, 'SUBCATEGORIA');
assert.strictEqual(res.nome, 'SUBCATEGORIA'); // Não altera...
});
});
describe('deleteSubcategoria', () => {
it('Removendo uma subcategoria', async () => {
// Criando uma categoria e uma subcategoria na mão
const categoria = await categoriaController.addCategoria('Categoria_1', false);
const subcategoria = await models.subcategoria.create({
nome: 'Subcategoria_11',
categoria_id: categoria.id,
});
// Removendo a subcategoria
await subcategoriaController.deleteSubcategoria(subcategoria.id);
const subcategoriaNull = await subcategoriaController.findSubcategoriaById(subcategoria.id);
assert.isNull(subcategoriaNull);
});
});
});
<file_sep>/docs/api/supervisor.md
# Supervisor
## `POST /supervisor` - Adiciona supervisor
- Headers
```
token: <jwt admin>
```
- Body
```javascript
{
"cpf": "111.111.111-11",
"nome": "João",
"senha": "<PASSWORD>",
"is_adm": false
}
```
- Resposta _#1A_ - **Code 200** - Supervisor cadastrado
```javascript
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF existente
```javascript
{
"msg": "cpf_existente"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/faltando
- Resposta _#3_ - **Code 401** - Token inválido
## `GET /supervisor` - Lista supervisores
- Headers:
```
token: <jwt admin>
```
- Resposta _#1_ - **Code 200** - Sucesso
```javascript
[
{
cpf: "111.111.111-11",
nome: "João",
is_adm: false
},
{
cpf: "111.111.222-22",
nome: "José",
is_adm: true
}
];
```
- Resposta _#2_ - **Code 401** - Token inválido
## `GET /supervisor/11111111111` - Retorna informações supervisor pelo CPF
- Headers:
```
token: <jwt admin>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```javascript
{
"cpf": "111.111.111-11",
"nome": "João",
"is_adm": false
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```javascript
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `PUT /supervisor/11111111111` - Atualiza supervisor
- Headers
```
token: <jwt admin>
```
- Body
```javascript
{
"is_adm": true,
"nome": "<NAME>",
"senha": "<PASSWORD>",
}
```
- Resposta _#1A_ - **Code 200** - Supervisor atualizado
```javascript
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```javascript
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `DELETE /supervisor/11111111111` - Remove supervisor (marca como inativo)
- Headers:
```
token: <jwt admin>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```javascript
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```javascript
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#1C_ - **Code 200** - ADM root (não pode ser excluido)
```javascript
{
"msg": "admin_root"
}
```
- Resposta _#2_ - **Code 400** - CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
<file_sep>/backend/tests/models/feirante.js
/* eslint-disable */
const chance = require("chance").Chance();
const { assert } = require("chai");
const models = require("../../models");
after( () => {
models.sequelize.close();
});
describe("Testando Feirante", () => {
beforeEach( () => {
models.feirante.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.celula.destroy({ where: {} });
models.participa.destroy({ where: {} });
});
it("Add Feirante", async () => {
let categoria = await models.categoria.create({
id: 1,
nome: "Alimentos",
need_cnpj: true
});
let subcategoria = await models.subcategoria.create({
id: 1,
nome: "Pasteis",
categoria_id: 1
});
let feirante = await models.feirante.findOne({
where: {
cpf: "111.111.111-11",
cnpj: "222.222.222-22",
usa_ee: false,
nome_ficticio: "<NAME>",
razao_social: "Tio do pastel LTDA",
comprimento_barraca: 2,
largura_barraca: 3,
endereco: "Rua da feira",
voltagem_ee: null,
status: true,
sub_categoria_id: 1,
senha: "<PASSWORD>"
}
});
assert.isNull(feirante);
feirante = await models.feirante.create({
cpf: "111.111.111-11",
cnpj: "222.222.222-22",
usa_ee: false,
nome_ficticio: "<NAME>",
razao_social: "Tio do pastel LTDA",
comprimento_barraca: 2,
largura_barraca: 3,
endereco: "Rua da feira",
voltagem_ee: true,
status: true,
sub_categoria_id: 1,
senha: "<PASSWORD>"
});
feirante = await models.feirante.findOne({
where: {
nome_ficticio: "<NAME>",
razao_social: "Tio do pastel LTDA",
status: true,
senha: "<PASSWORD>"
}
});
assert.isNotNull(feirante);
assert.strictEqual(feirante.cpf, "111.111.111-11");
assert.strictEqual(feirante.senha, "<PASSWORD>678");
});
it("Relações", async () => {
let categoria = await models.categoria.create({
id: 1,
nome: "Alimentos",
need_cnpj: true
});
let subcategoria = await models.subcategoria.create({
id: 1,
nome: "Pasteis",
categoria_id: 1
});
let feirante = await models.feirante.create({
cpf: "111.111.111-11",
cnpj: "222.222.222-22",
usa_ee: false,
nome_ficticio: "<NAME>",
razao_social: "Tio do pastel LTDA",
comprimento_barraca: 2,
largura_barraca: 3,
endereco: "Rua da feira",
voltagem_ee: true,
status: true,
sub_categoria_id: 1,
senha: "<PASSWORD>"
});
let feira = await models.feira.create({ data: "2018-12-31" });
let celula = await models.celula.create({
id: 1,
cpf_feirante: "111.111.111-11",
periodo: 1
});
let participa = await models.participa.create({
cpf_feirante: "111.111.111-11",
data_feira: "2018-12-31",
celula_id: 1,
});
feirante = await models.feirante.findOne({
where: {
cpf: "111.111.111-11"
}
});
feira = await models.feira.findOne({
where: {
data: "2018-12-13"
}
});
participa = await models.participa.findOne({
where: {
//cpf_feirante: "111.111.111-11",
//data_feira: "2018-12-31"
}
});
assert.strictEqual(participa.cpf_feirante, "111.111.111-11");
assert.strictEqual(participa.data_feira, "2018-12-31");
});
})<file_sep>/frontend/src/api/supervisor.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/supervisor`;
const formatCPF = cpf => {
return cpf.replace('.', '').replace('.', '').replace('-', '');
}
export async function get() {
const data = await axios
.get(host, { headers: { token: localStorage.getItem('token') } })
.then(record => {
if (!record.data) return [];
return record.data;
})
.catch(ex => console.warn(ex));
return data.map(record => ({
...record,
cpf: record.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4'),
}));
}
export async function getByCpf(cpf) {
const record = (await axios.get(host + cpf, {
headers: { token: localStorage.getItem('token') },
})).data;
return { ...record, cpf: record.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4') };
}
export async function post(cpf, nome, senha, isAdm) {
await axios.post(
host,
{
cpf,
nome,
senha,
is_adm: isAdm ? 1 : 0,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export async function put(cpf, nome, isAdm, senha) {
const cleanedCPF = formatCPF(cpf);
await axios.put(
`${host}/${cleanedCPF}`,
{
nome,
is_adm: isAdm,
senha,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export function del(cpf) {
const cleanedCPF = formatCPF(cpf);
return axios.delete(`${host}/${cleanedCPF}`, { headers: { token: localStorage.getItem('token') } });
}
<file_sep>/backend/tests/controllers/utils.js
const { assert } = require('chai');
const sinon = require('sinon');
const { amanha, proximaSexta } = require('../../controllers/utils');
describe('utils.js', () => {
describe('amanha', () => {
it('Retorna data amanhã', () => {
let clock = sinon.useFakeTimers(new Date('01-01-2018'));
assert.strictEqual(amanha().toISOString(), new Date('01-02-2018').toISOString());
clock.restore();
clock = sinon.useFakeTimers(new Date('01-31-2018'));
assert.strictEqual(amanha().toISOString(), new Date('02-01-2018').toISOString());
clock.restore();
});
it('Retorna data errada', () => {
let clock = sinon.useFakeTimers(new Date('01-01-2018'));
assert.notStrictEqual(amanha().toISOString(), new Date('01-03-2018').toISOString());
clock.restore();
clock = sinon.useFakeTimers(new Date('01-31-2018'));
assert.notStrictEqual(amanha().toISOString(), new Date('02-02-2018').toISOString());
clock.restore();
});
});
describe('proximaSexta', () => {
let clock = sinon.useFakeTimers(new Date('11-01-2018'));
assert.equal(proximaSexta().getDay(), new Date('11-02-2018').getDay());
clock.restore();
clock = sinon.useFakeTimers(new Date('11-02-2018'));
assert.equal(proximaSexta().getDay(), new Date('11-02-2018').getDay());
clock.restore();
});
});
<file_sep>/frontend/src/screens/Categorias/Subcategorias.js
import React, { PureComponent, Fragment } from 'react';
import {
Popconfirm, Button, Form,
Input, Modal, message,
Table,
} from 'antd';
import EmptyComponent from '../../components/EmptyComponent';
import UpdateSubcategoria from './UpdateSubcategoria';
import * as categoriasAPI from '../../api/categoria';
import * as subcategoriasAPI from '../../api/subcategoria';
const { Column } = Table;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class Subcategorias extends PureComponent {
state = {
subcategorias: [],
loading: true,
editingSubcategoria: {},
};
componentDidMount() {
this._loadSubcategorias();
}
_handleSubmit = (e) => {
const {
form: {resetFields},
categoria,
} = this.props;
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
message.loading('Carregando...', 0);
return subcategoriasAPI.post(values.nome, categoria.id)
.then(() => {
resetFields();
this._loadSubcategorias();
message.success('Subcategoria criada com sucesso!', 2.5);
}).catch(() => {
message.error('Não foi possível adicionar subcategoria!', 2.5);
});
}
});
}
_loadSubcategorias = async () => {
const { categoria } = this.props;
this.setState({loading: true});
const subcategorias = await categoriasAPI.getSub(categoria.id);
this.setState({subcategorias, loading: false});
}
_onDeleteSubCategoria = id => {
message.loading('Carregando...', 0);
return subcategoriasAPI.deleteSub(id)
.then(() => {
this._loadSubcategorias();
message.success('Subcategoria excluída com sucesso!', 2.5);
}).catch(() => {
message.error('Não foi possível excluir subcategoria, tente novamente mais tarde', 2.5);
});
}
_onEditSub = async sub => {
const { form: { setFieldsValue } } = this.props;
this.setState({ editingSubcategoria: sub });
return await setFieldsValue({
novo_nome: sub.nome,
});
}
_renderSubcategorias = () => {
const { subcategorias, loading } = this.state;
return (
<Table
dataSource={subcategorias}
loading={loading}
size="small"
pagination={{
pageSize: 15,
}}
locale={{
emptyText: <EmptyComponent />
}}
>
<Column
key="SubcategoriaId"
dataIndex="id"
title="#"
width={50}
/>
<Column
key="SubcategoriaNome"
dataIndex="nome"
title="Nome"
/>
<Column
key="acoes"
title="Ações"
width={90}
render={linha => {
return (
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<Button shape="circle" icon="edit" onClick={() => this._onEditSub(linha)} />
<Popconfirm
title="Você quer deletar esta subcategoria?"
okText="Sim"
cancelText="Não"
onConfirm={() => this._onDeleteSubCategoria(linha.id)}
>
<Button shape="circle" icon="delete" type="danger" />
</Popconfirm>
</div>
);
}}
/>
</Table>
);
}
handleCancel = () => {
this.setState({ editingSubcategoria: {} });
}
render() {
const { form } = this.props;
const {
getFieldDecorator, getFieldsError, getFieldError,
isFieldTouched, getFieldValue,
} = form;
const { editingSubcategoria } = this.state;
const nomeError = isFieldTouched('nome') && getFieldError('nome');
return (
<Fragment>
<Form layout="inline" onSubmit={this._handleSubmit}>
<Form.Item
validateStatus={nomeError ? 'error' : ''}
help={nomeError || ''}
>
{getFieldDecorator('nome', {rules: [{
required: true,
message: 'O nome da subcategoria é obrigatório!'
}]})(
<Input
placeholder="Nome"
/>
)}
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
disabled={
hasErrors(getFieldsError())
|| !getFieldValue('nome')
}
>
Adicionar
</Button>
</Form.Item>
</Form>
<Modal
title={`${editingSubcategoria.id} - ${editingSubcategoria.nome}`}
visible={Boolean(editingSubcategoria && editingSubcategoria.id)}
onCancel={this.handleCancel}
footer={null}
width={300}
>
{
editingSubcategoria && editingSubcategoria.id
? (
<UpdateSubcategoria
onCancel={this.handleCancel}
refresh={this._loadSubcategorias}
subcategoria={editingSubcategoria}
/>
) : null
}
</Modal>
{ this._renderSubcategorias() }
</Fragment>
);
}
}
const WrappedHorizontalSubcategoriasForm = Form.create({ name: 'categorias_form' })(Subcategorias);
export default WrappedHorizontalSubcategoriasForm;<file_sep>/backend/tests/controllers/login.js
const { assert } = require('chai');
const jwt = require('jsonwebtoken');
const faker = require('faker');
const keys = require('../../config/keys.json');
const feiranteController = require('../../controllers/feirante');
const loginController = require('../../controllers/login');
const supervisorController = require('../../controllers/supervisor');
const models = require('../../models');
describe('login.js', () => {
let feirante1;
let feirante2;
let supervisor1;
let supervisor2;
before(async () => {
await models.categoria.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
const categoria = await models.categoria.create({ nome: 'Categoria', need_cnpj: false });
const subcategoria = await categoria.createSubCategoria({ nome: 'SubCategoria' });
feirante1 = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'4321',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirante2 = await feiranteController.addFeirante(
'72268053083',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
supervisor1 = await supervisorController.addSupervisor('73332119087', 'Nome', '1234', false);
supervisor2 = await supervisorController.addSupervisor('79381775044', 'Nome', '12345', false);
});
after(() => {
models.categoria.destroy({ where: {} });
models.supervisor.destroy({ where: {} });
models.feirante.destroy({ where: {} });
});
it('Faz login corretamente (supervisor)', async () => {
const token = await loginController.login(supervisor1.cpf, '1234');
assert.isNotNull(token);
const decoded = await jwt.verify(token.token, keys.jwt);
assert.strictEqual(decoded, supervisor1.cpf);
assert.strictEqual(token.tag, 'supervisor');
});
it('Não faz login com senha incorreta (supervisor)', async () => {
const token = await loginController.login(supervisor1.cpf, '12345');
assert.isNull(token);
});
it('Não faz login com cpf incorreto (supervisor)', async () => {
const token = await loginController.login(supervisor2.cpf, '1234');
assert.isNull(token);
});
it('Não faz login com cpf inexistente (supervisor)', async () => {
const token = await loginController.login('11111111117', '1234');
assert.isNull(token);
});
it('Faz login corretamente (feirante)', async () => {
const token = await loginController.login(feirante1.cpf, '4321');
assert.isNotNull(token);
const decoded = await jwt.verify(token.token, keys.jwt);
assert.strictEqual(decoded, feirante1.cpf);
assert.strictEqual(token.tag, 'feirante');
});
it('Não faz login com senha incorreta (feirante)', async () => {
const token = await loginController.login(feirante1.cpf, '54321');
assert.isNull(token);
});
it('Não faz login com cpf incorreto (feirante)', async () => {
const token = await loginController.login(feirante2.cpf, '4321');
assert.isNull(token);
});
it('Não faz login com cpf inexistente (feirante)', async () => {
const token = await loginController.login('22222222224', '4321');
assert.isNull(token);
});
});
<file_sep>/frontend/src/screens/FeiranteScreen.js
import React, { Component } from 'react';
import {
Layout, Icon, Menu, Button,
Drawer, Modal,
} from 'antd';
import { withRouter } from 'react-router-dom';
import routes from '../routes';
import styles from './FeiranteScreen.module.scss';
const { Header } = Layout;
const { confirm } = Modal;
class FeiranteScreen extends Component {
state = {
collapsed: false,
selectedKey: [],
visible: false,
};
componentDidMount() {
this._setPath();
}
showDrawer = () => {
this.setState({
visible: true,
});
};
onClose = () => {
this.setState({
visible: false,
});
};
_setPath = () => {
const { pathname } = this.props.location;
const currentRoute = routes.find(route => route.path === pathname);
if (!currentRoute) return null;
this.setState({ selectedKey: [currentRoute.key] });
}
_onChangeRoute = event => {
const { item: { props } } = event;
const { history } = this.props;
this.setState(
{ selectedKey: [props.eventKey] },
history.push({
pathname: props.path,
state: { selectedKey: [props.eventKey] },
}),
);
}
_onLogout = () => {
localStorage.clear();
window.location = '/';
}
_toggle = () => {
const { collapsed } = { ...this.state };
this.setState({
collapsed: !collapsed,
});
}
_onChangeRoute = event => {
const { item: { props } } = event;
const { history } = this.props;
this.setState(
{ selectedKey: [props.eventKey] },
history.push({
pathname: props.path,
state: { selectedKey: [props.eventKey] },
}),
);
}
_renderNavItems = () => {
return routes.map(route => {
if(route.permissions.find(permission => permission === "feirante")) {
return (
<Menu.Item
key={route.key}
path={route.path}
name={route.label}
onClick={this._onChangeRoute}
>
<Icon type={route.icon} />
<span>{route.label}</span>
</Menu.Item>
);
}
return null;
});
}
_onAskToLogout = () => {
confirm({
title: 'Você deseja sair da aplicação ?',
okText: 'Sim',
cancelText: 'Cancelar',
onOk: () => {
this._onLogout();
},
});
}
_renderSairButton = () => {
return (
<Menu.Item
key="sair"
name="sair"
onClick={this._onAskToLogout}
>
<Icon type="logout" />
<span>Sair</span>
</Menu.Item>
)
}
render() {
const { children } = this.props;
const { selectedKey } = this.state;
return (
<Layout className={styles.layout}>
<Header className={styles.header}>
<div className={styles.headerContainer}>
<div className={styles.logo} />
<Menu
theme="dark"
mode="horizontal"
selectedKeys={selectedKey}
className={styles.menuDesktop}
>
{this._renderNavItems()}
{this._renderSairButton()}
</Menu>
<Button
type="primary"
onClick={this.showDrawer}
className={styles.menuButton}
>
Menu
</Button>
</div>
</Header>
{children}
<Drawer
title="Menu"
placement="right"
closable
className={styles.drawer}
onClose={this.onClose}
visible={this.state.visible}
>
<Menu
theme="light"
mode="vertical"
selectedKeys={selectedKey}
>
{this._renderNavItems()}
{this._renderSairButton()}
</Menu>
</Drawer>
</Layout>
);
}
}
export default withRouter(FeiranteScreen);
<file_sep>/README.md
# municipalMarketFairControl
A control software developed for the Campo Mourão municipal administration's market fairs
# Instalação
## Primeiros passos
Vamos começar instalando os softwares necessários
- Instale [Node.js](https://nodejs.org/en/)
- Instale o [Yarn](https://yarnpkg.com/pt-BR/) utilizando o comando `npm install yarn -g`
- Instale o [MariaDB](https://mariadb.org/)
## Backend
Após fazer a instalação dos softwares necessários para começar a desenvolver, precisamos instalar as dependências do projeto.
Para isso, acesse a pasta `/backend` e execute o comando de instalação:
#### `yarn`
Após executar a instalação das dependências do projeto, é necessário é necessário executar o `script.sql` dentro da pasta `database`
Para isso utilize o [MySQL Workbench](https://www.mysql.com/products/workbench/) ou utilize o CLI do MariaDB.
Após a criação do banco de dados e de suas tabelas, é necessário adicionar o primeiro administrador do sistema.
Para isso, ainda na pasta `database` abra o terminal e execute o arquivo `insert_first_admin.js` utilizando o comando:
#### `node insert_first_admin.js`
Ao executar o script, também podemos executar o script para popular o banco de dados. Para isso, utilize o comando:
#### `node insert_fake_data.js`
Desta forma, o nosso banco de dados esta pronto e para executar o backend navegue até a pasta `/backend` e execute o comando:
#### `yarn run serve`
Agora, após executar o comando, o servidor esta disponível através da porta `:3000` do seu localhost.
## Frontend
Para iniciar o front-end devemos primeiramente instalar as dependências do projeto. Para isso acesse a pasta `/frontend` e execute o comando:
#### `yarn`
Feito a instalação das dependências do projeto, basta executar o servidor frontend, para isso, execute o seguinte comando:
#### `yarn start`
Após terminar a execução do comando anterior, o servidor front-end ficará disponível através da porta `:8000` do seu localhost.
# Importante
A instalação das dependências utilizando o comando `yarn` só é necessário durante a primeira execução, ou se for adicionado uma nova dependência.
Então se não for alterado nada dentro do arquivo `package.json`, não é necessário executá-lo novamente.
## Dados do primeiro admin:
- CPF: `56662192007`
- Senha: `<PASSWORD>`
## .env
Dentro da pasta ´frontend´ faça uma cópia do arquivo `.env-default` e de o nome de `.env`. Ele serve para definir as configurações do front-end, como a porta de execução e o endereço backend.
Caso for necessário fazer a alteração do mesmo, pare o servidor frontend, altere a configuração dentro do `.env` e rode novamente o servidor frontend.
# Cuidado
Caso use um banco um usuário diferente de `root` sem senha para o banco de dados, é necessário alterar as informações contidas no arquivo `backend/config/config.json`. Porém, lembre-se de **NÃO FAZER O COMMIT DESTAS ALTERAÇÕES**, pois essas alterações se tornarão publicas e sua senha será exposta, caso for uma senha sensível. Para fazer a alterações, basta substituir o trecho de código contendo as suas informações.
```json
"development": {
"username": "SEU USUARIO AQUI",
"password": "<PASSWORD>",
"database": "feira_municipal",
"host": "127.0.0.1",
"dialect": "mysql",
"logging": false,
"operatorsAliases": false
},
```
<file_sep>/frontend/src/screens/HomeScreen.js
import React, { Component } from 'react';
import {
Layout, Icon, Menu, Popconfirm,
Modal,
} from 'antd';
import { withRouter } from 'react-router-dom';
import routes from '../routes';
import styles from './HomeScreen.module.scss';
const { confirm } = Modal;
const { Header, Sider } = Layout;
class HomeScreen extends Component {
state = {
collapsed: false,
selectedKey: [],
};
componentDidMount() {
this._setPath();
}
_setPath = () => {
const { pathname } = this.props.location;
const currentRoute = routes.find(route => route.path === pathname);
if (!currentRoute) return null;
this.setState({ selectedKey: [currentRoute.key] });
}
_onChangeRoute = event => {
const { item: { props } } = event;
const { history } = this.props;
this.setState(
{ selectedKey: [props.eventKey] },
history.push({
pathname: props.path,
state: { selectedKey: [props.eventKey] },
}),
);
}
_onLogout = () => {
confirm({
title: 'Você deseja realmente sair da aplicação?',
okText: 'Sim',
cancelText: 'Cancelar',
onOk: () => {
localStorage.clear();
window.location = '/';
},
});
}
_toggle = () => {
const { collapsed } = { ...this.state };
this.setState({
collapsed: !collapsed,
});
}
_renderNavItems = () => {
return routes.map(route => {
const loggedUserType = localStorage.getItem('tag');
if (route.hidden) return null;
if(!route.permissions.find(permission => permission === loggedUserType)) return null;
return (
<Menu.Item
key={route.key}
path={route.path}
name={route.label}
>
<Icon type={route.icon} />
<span>{route.label}</span>
</Menu.Item>
);
});
}
render() {
const { children } = this.props;
const { selectedKey } = this.state;
return (
<Layout>
<Sider
trigger={null}
collapsible
collapsed={this.state.collapsed}
>
<div className="logo" />
<Menu
theme="dark"
mode="inline"
onClick={this._onChangeRoute}
selectedKeys={selectedKey}
>
{this._renderNavItems()}
</Menu>
</Sider>
<Layout>
<Header className={styles.header}>
<Icon
className={styles.collapseButton}
type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
onClick={this._toggle}
/>
<h1
style={{
marginBottom: 3,
marginLeft: 8,
fontSize: 20,
flex: 1,
}}
>
Sistema de Controle da Feira Criativa
</h1>
<Icon onClick={this._onLogout} className={styles.logoutButton} type="logout" />
</Header>
{children}
</Layout>
</Layout>
);
}
}
export default withRouter(HomeScreen);
<file_sep>/docs/api/feira.md
# Feira
## `GET /feira/info` - Informações da feira atual (data, cancelado)
- Headers
```
token: <jwt feirante/supervisor>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```javascript
{
"data": "01/01/2018",
"status": 1
}
```
- Resposta _#1B_ - **Code 200** - Sem feira atual (não foi criada no sistema)
```javascript
{
"msg": "feira_invalida"
}
```
- Resposta _#2_ - **Code 401** - Token inválido
## `POST /feira` - Adiciona feira
- Headers
```
token: <jwt supervisor>
```
- Body
```javascript
{
"data": "01/01/2018"
}
```
- Resposta _#1A_ - **Code 200** - Feira cadastrada
```javascript
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - Data não permitida (data anterior)
```javascript
{
"msg": "data_nao_permitida"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/faltando
- Resposta _#3_ - **Code 401** - Token inválido
## `POST /feira/cancelar` - Cancelar feira atual
- Headers
```
token: <jwt supervisor>
```
- Resposta _#1A_ - **Code 200** - Feira cancelada
```javascript
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - Feira não cancelada (feira ja foi cancelada/sem feira atual)
```javascript
{
"msg": "feira_nao_cancelada"
}
```
- Resposta _#2_ - **Code 401** - Token inválido
<file_sep>/backend/models/participa.js
/* jshint indent: 2 */
/* eslint-disable */
module.exports = function(sequelize, DataTypes) {
const Participa = sequelize.define(
"participa",
{
cpf_feirante: {
type: DataTypes.STRING(15),
allowNull: false,
defaultValue: "",
primaryKey: true,
references: {
model: "feirante",
key: "cpf"
}
},
data_feira: {
type: DataTypes.DATEONLY,
allowNull: false,
defaultValue: "0000-00-00",
primaryKey: true,
references: {
model: "feira",
key: "data"
}
},
faturamento: {
type: "DOUBLE",
allowNull: true,
defaultValue: 0
},
periodo: {
type: DataTypes.INTEGER(11),
allowNull: false
},
hora_confirmacao: {
type: DataTypes.DATE,
allowNull: true
},
celula_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
}
},
{
tableName: "participa",
timestamps: false,
createdAt: false
}
);
Participa.associate = models => {
models.feira.belongsToMany(models.feirante, {
through: models.participa,
as: "Feirantes",
foreignKey: "data_feira"
});
models.feirante.belongsToMany(models.feira, {
through: models.participa,
as: "Feiras",
foreignKey: "cpf_feirante"
});
};
return Participa;
};
<file_sep>/frontend/src/components/AvisoComponent.js
import React, {PureComponent} from 'react';
import { Card, Col } from 'antd';
export default class AvisoComponent extends PureComponent {
state = {};
render() {
const { aviso } = this.props;
return (
<Col sm={24} style={{marginBottom: 20 }}>
<Card
title={aviso.assunto}
style={{
backgroundColor: '#fafafa',
}}
bordered
>
<p>{aviso.texto}</p>
</Card>
</Col>
);
}
}<file_sep>/backend/models/endereco.js
/* jshint indent: 2 */
module.exports = (sequelize, DataTypes) => {
const Endereco = sequelize.define(
'endereco',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
logradouro: {
type: DataTypes.STRING(100),
allowNull: false,
},
bairro: {
type: DataTypes.STRING(100),
allowNull: true,
},
numero: {
type: DataTypes.INTEGER(11),
allowNull: true,
},
CEP: {
type: DataTypes.STRING(10),
allowNull: true,
},
cpf_feirante: {
type: DataTypes.STRING(15),
allowNull: false,
references: {
model: 'feirante',
key: 'cpf',
},
},
},
{
tableName: 'endereco',
timestamps: false,
createdAt: false,
},
);
Endereco.associate = (models) => {
models.endereco.belongsTo(models.feirante, {
foreignKey: 'cpf_feirante',
targetKey: 'cpf',
});
};
return Endereco;
};
<file_sep>/docs/api/categoria.md
# Categoria
## ```POST /categoria``` - Adiciona categoria
- Headers
```
token: <jwt supervisor>
```
- Body
```javascript
{
"nome": "Alimentos",
"need_cnpj": "1"
}
```
- Resposta *#1A* - **Code 200** - Categoria cadastrada
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#2* - **Code 400** - Atributos incorretos/faltando
- Resposta *#3* - **Code 401** - Token inválido
## ```GET /categoria``` - Lista categorias
- Headers:
```
token: <jwt supervisor>
```
- Resposta *#1* - **Code 200** - Sucesso
```javascript
[
{
"id": "1",
"nome": "Alimentos",
"need_cnpj": "1"
},
{
"id": "2",
"nome": "Artesanato",
"need_cnpj": "0"
}
]
```
- Resposta *#2* - **Code 401** - Token inválido
## ```GET /categoria/1``` - Retorna informações de uma categoria pelo ID
- Headers:
```
token: <jwt supervisor>
```
- Resposta *#1A* - **Code 200** - Sucesso
```javascript
{
"id": "1",
"nome": "Alimentos",
"need_cnpj": "1"
}
```
- Resposta *#1B* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 401** - Token inválido
## ```GET /categoria/1/subcategorias``` - Lista subcategorias de uma categoria pelo ID
- Headers:
```
token: <jwt supervisor>
```
- Resposta *#1A* - **Code 200** - Sucesso
```javascript
[
{
"id": "1",
"nome": "Bolos"
},
{
"id": "2",
"nome": "Salgados"
},
{
"id": "3",
"nome": "Sorvetes"
}
]
```
- Resposta *#1B* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 401** - Token inválido
## ```PUT /categoria/1``` - Atualiza categoria
- Headers
```
token: <jwt supervisor>
```
- Body
```javascript
{
"nome": "Artesanato",
"need_cnpj": "0"
}
```
- Resposta *#1A* - **Code 200** - Categoria atualizada
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#1C* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 400** - Atributos incorretos
- Resposta *#3* - **Code 401** - Token inválido
## ```DELETE /categoria/1``` - Remove categoria
- Headers
```
token: <jwt supervisor>
```
- Resposta *#1A* - **Code 200** - Sucesso
```javascript
{
"msg": "ok"
}
```
- Resposta *#1B* - **Code 200** - Erro no banco de dados
```javascript
{
"msg": "erro"
}
```
- Resposta *#1C* - **Code 200** - ID não existente
```javascript
{
"msg": "id_nao_existente"
}
```
- Resposta *#2* - **Code 401** - Token inválido
<file_sep>/backend/routes/utils.js
const cpfCheck = require('cpf-check');
const cnpjCheck = require('cnpj');
const isCpf = cpf => cpfCheck.validate(cpfCheck.strip(cpf)).valid;
const isCnpj = cnpj => cnpj === '' || cnpjCheck.validate(cnpj); // CNPJ pode ser vazio
const isEndereco = (endereco) => {
if (
endereco.logradouro === undefined
|| typeof endereco.logradouro !== 'string'
|| (endereco.logradouro.length < 1 || endereco.logradouro.length > 100)
) return false;
// Esses são opcionais
if (
endereco.bairro !== undefined
&& (typeof endereco.bairro !== 'string'
|| (endereco.bairro.length < 1 || endereco.bairro.length > 100))
) return false;
if (endereco.numero !== undefined && typeof endereco.numero !== 'number') return false;
if (
endereco.cep !== undefined
&& (typeof endereco.cep !== 'string' || endereco.cep.length !== 10)
) return false;
return true;
};
module.exports = { isCpf, isCnpj, isEndereco };
<file_sep>/backend/tests/routes/login.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const faker = require('faker');
const app = require('../../app');
const supervisorController = require('../../controllers/supervisor');
const feiranteController = require('../../controllers/feirante');
const categoriaController = require('../../controllers/categoria');
const models = require('../../models');
const { assert } = chai;
chai.use(chaiHttp);
const host = '/api/login/';
describe('Rota Login', () => {
let feirante;
let supervisor;
let admin;
let subcategoria;
let categoria;
before(async () => {
admin = await supervisorController.addSupervisor(
'89569380080',
faker.name.firstName(),
'123456',
true,
);
supervisor = await supervisorController.addSupervisor(
'56919550040',
faker.name.firstName(),
'1234567',
false,
);
categoria = await categoriaController.addCategoria('Alimento', false);
subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'12345678',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
});
after(async () => {
await models.categoria.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
});
describe('POST /login', () => {
it('Login Admin', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: admin.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 200);
assert.isNotNull(res.body.token);
assert.strictEqual(res.body.tag, 'administrador');
});
it('Login Supervisor', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: supervisor.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 200);
assert.isNotNull(res.body.token);
assert.strictEqual(res.body.tag, 'supervisor');
});
it('Login Feirante', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: feirante.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 200);
assert.isNotNull(res.body.token);
assert.strictEqual(res.body.tag, 'feirante');
});
it('Admin senha errada', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: admin.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 401);
assert.isUndefined(res.body.token);
assert.isUndefined(res.body.tag);
});
it('Supervisor senha errada', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: supervisor.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 401);
assert.isUndefined(res.body.token);
assert.isUndefined(res.body.tag);
});
it('Feirante senha errada', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: feirante.cpf,
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 401);
assert.isUndefined(res.body.token);
assert.isUndefined(res.body.tag);
});
it('CPF invalido', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: '1111111111',
senha: '<PASSWORD>',
});
assert.strictEqual(res.statusCode, 400);
});
it('Senha com menos de 6 dígitos', async () => {
const res = await chai
.request(app)
.post(host)
.send({
cpf: '58295846035',
senha: '123',
});
assert.strictEqual(res.statusCode, 400);
});
});
});
<file_sep>/backend/tests/routes/feirante.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const faker = require('faker');
const supervisorController = require('../../controllers/supervisor');
const categoriaController = require('../../controllers/categoria');
const feiranteController = require('../../controllers/feirante');
const loginController = require('../../controllers/login');
const app = require('../../app');
const models = require('../../models');
const { assert } = chai;
chai.use(chaiHttp);
const host = '/api/feirante/';
describe('feirante.js', () => {
let tokenSupervisor;
let feirante;
let tokenAdmin;
let tokenFeirante;
let subcategoria;
before(async () => {
const admin = await supervisorController.addSupervisor(
'89569380080',
faker.name.firstName(),
'1234',
true,
);
const supervisor = await supervisorController.addSupervisor(
'56919550040',
faker.name.firstName(),
'1234',
false,
);
const categoria = await categoriaController.addCategoria('Alimento', false);
subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'1234',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await models.celula.create({
id: 1, periodo: 1, x: 0, y: 0, comprimento: 0, largura: 0,
});
tokenFeirante = (await loginController.login(feirante.cpf, '1234')).token;
tokenAdmin = (await loginController.login(admin.cpf, '1234')).token;
tokenSupervisor = (await loginController.login(supervisor.cpf, '1234')).token;
});
after(async () => {
await models.celula.destroy({ where: {} });
await models.categoria.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
});
describe('POST /feirante', () => {
it('Supervisor pode adicionar feirante', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '07281509057',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
it('Administrador pode adicionar feirante', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenAdmin)
.send({
cpf: '44174625000',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>56',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
it('Feirante não pode adicionar feirante', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenFeirante)
.send({
cpf: '16319981024',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 401);
});
it('Sem token não pode adicionar feirante', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', 'aaaa')
.send({
cpf: '39616904051',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 401);
});
it('Atributos faltando', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '07281509057',
cnpj: '',
/* nome: faker.name.firstName(), */
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 400);
});
it('Atributos faltando #2', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '07281509057',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
/* logradouro: faker.address.streetAddress(), */
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 400);
});
it('Atributos incorretos', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '07281509057',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: '', // faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 400);
});
it('Atributos opcionais', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '03042659003',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
/* CEP: '87.303-065', */
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
it('Subcategoria não existe', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '47668203044',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: 4,
});
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'subcategoria_nao_existe');
});
it('CPF existente', async () => {
const res = await chai
.request(app)
.post(host)
.set('token', tokenSupervisor)
.send({
cpf: '07281509057',
cnpj: '',
nome: faker.name.firstName(),
rg: '509627249',
senha: '<PASSWORD>',
usa_ee: false,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_existente');
});
});
describe('GET /feirante', () => {
it('Lista feirantes', async () => {
const res = await chai
.request(app)
.get(host)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.lengthOf(res.body, 4);
assert.strictEqual(res.body.filter(e => e.cpf === feirante.cpf)[0].rg, feirante.rg);
});
});
describe('GET /feirante/:cpf', () => {
it('CPF inválido', async () => {
const res = await chai
.request(app)
.get(`${host}11111111111`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 400);
});
it('CPF não existente', async () => {
const res = await chai
.request(app)
.get(`${host}93146729059`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_nao_existente');
});
it('Retorna feirante pelo CPF', async () => {
const res = await chai
.request(app)
.get(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.cpf, feirante.cpf);
});
});
describe('PUT /feirante/:cpf', () => {
it('CPF inválido', async () => {
const res = await chai
.request(app)
.put(`${host}11111111111`)
.set('token', tokenSupervisor)
.send({ senha: '<PASSWORD>' });
assert.strictEqual(res.statusCode, 400);
});
it('Atributo incorreto', async () => {
const res = await chai
.request(app)
.put(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor)
.send({ senha: '<PASSWORD>' });
assert.strictEqual(res.statusCode, 400);
});
it('CPF não existe', async () => {
const res = await chai
.request(app)
.put(`${host}91137616091`)
.set('token', tokenSupervisor)
.send({ senha: '<PASSWORD>' });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_nao_existente');
});
it('Atualiza feirante', async () => {
const novoNome = faker.name.firstName();
let res = await chai
.request(app)
.put(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor)
.send({ nome: novoNome });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
res = await chai
.request(app)
.get(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.nome, novoNome);
});
});
describe('DELETE /feirante/:cpf', () => {
it('CPF inválido', async () => {
const res = await chai
.request(app)
.delete(`${host}11111111111`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 400);
});
it('CPF não existe', async () => {
const res = await chai
.request(app)
.delete(`${host}91137616091`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_nao_existente');
});
it('Remove supervisor', async () => {
let res = await chai
.request(app)
.delete(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
res = await chai
.request(app)
.get(`${host}${feirante.cpf}`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_nao_existente');
});
});
});
<file_sep>/docs/api/feirante.md
# Feirante
## `POST /feirante` - Adiciona feirante
- Headers
```
token: <jwt supervisor>
```
- Body
```json
{
"cpf": "54440467091",
"cnpj": "87087101000120",
"nome": "<NAME>",
"rg": "11.111.111-1",
"usa_ee": true,
"nome_fantasia": "<NAME>",
"razao_social": "João LTDA",
"comprimento_barraca": 4,
"largura_barraca": 4,
"endereco": {
"logradouro": "Rua Brasil",
"bairro": "Centro",
"numero": 100,
"cep": "87.303-000"
},
"voltagem_ee": 220,
"sub_categoria_id": 2,
"senha": "<PASSWORD>"
}
```
- Resposta _#1A_ - **Code 200** - Feirante cadastrado
```json
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF existente
```json
{
"msg": "cpf_existente"
}
```
- Resposta _#1C_ - **Code 200** - Subcategoria não existe
```json
{
"msg": "subcategoria_nao_existe"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/faltando
- Resposta _#3_ - **Code 401** - Token inválido
## `GET /feirante` - Lista feirantes
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1_ - **Code 200** - Sucesso
```json
[
{
"cpf": "54440467091",
"cnpj": "87087101000120",
"nome": "<NAME>",
"rg": "378507333",
"usa_ee": true,
"nome_fantasia": "Barraca do Jão",
"razao_social": "João LTDA",
"comprimento_barraca": 4,
"largura_barraca": 4,
"endereco": {
"logradouro": "Rua Brasil",
"bairro": "Centro",
"numero": 100,
"cep": "87.303-000"
},
"voltagem_ee": 220,
"sub_categoria_id": 2
},
{
"cpf": "22822806012",
"cnpj": "87087101000120",
"nome": "<NAME>",
"rg": "378507333",
"usa_ee": true,
"nome_fantasia": "Barraca do Jão 2",
"razao_social": "João LTDA 2",
"comprimento_barraca": 4,
"largura_barraca": 4,
"endereco": {
"logradouro": "Rua Brasil",
"bairro": "Centro",
"numero": 100,
"cep": "87.303-000"
},
"voltagem_ee": 220,
"sub_categoria_id": 2
}
];
```
- Resposta _#2_ - **Code 401** - Token inválido
## `GET /feirante/11111111111` - Retorna informações feirante pelo CPF
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```json
{
"cpf": "54440467091",
"cnpj": "87087101000120",
"nome": "<NAME>",
"rg": "378507333",
"usa_ee": true,
"nome_fantasia": "<NAME>",
"razao_social": "João LTDA",
"comprimento_barraca": 4,
"largura_barraca": 4,
"endereco": {
"logradouro": "Rua Brasil",
"bairro": "Centro",
"numero": 100,
"cep": "87.303-000"
},
"voltagem_ee": 220,
"sub_categoria_id": 2
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```json
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `PUT /feirante/11111111111` - Atualiza feirante
- Headers
```
token: <jwt supervisor>
```
- Body
```json
{
"voltagem_ee": 110
}
```
- Resposta _#1A_ - **Code 200** - Feirante atualizado
```json
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```json
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `DELETE /feirante/11111111111` - Remove feirante (marca como inativo)
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```json
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```json
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `GET /feirante/11111111111/participacoes` - Retorna participações do feirante pelo CPF
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```json
[
{
"data_feira": "01/01/2018",
"faturamento": 10000,
"periodo": 1,
"hora_confirmacao": "15:45 21/12/2017",
"celula_id": 4
},
{
"data_feira": "08/01/2018",
"faturamento": 15000,
"periodo": 1,
"hora_confirmacao": "15:45 02/01/2017",
"celula_id": 4
}
];
```
- Resposta _#1B_ - **Code 200** - CPF não existente
```json
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
## `POST /feirante/confirma` - Confirma presença na feira atual
- Headers
```
token: <jwt feirante>
```
- Body
```json
{
"periodo": 1
}
```
- Resposta _#1A_ - **Code 200** - Feirante confirmado
```json
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - Periodo inválido (diferente de 1,2,3)
```json
{
"msg": "periodo_invalido"
}
```
- Resposta _#1C_ - **Code 200** - Feirante não confirmado (feira não existe/cancelada)
```json
{
"msg": "feirante_nao_confirmado"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/faltando
- Resposta _#3_ - **Code 401** - Token inválido
<file_sep>/backend/models/aviso.js
module.exports = (sequelize, DataTypes) => {
const Aviso = sequelize.define(
'aviso',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
assunto: {
type: DataTypes.STRING(100),
allowNull: true,
},
texto: {
type: DataTypes.STRING(100),
allowNull: true,
},
data_feira: {
type: DataTypes.DATEONLY,
allowNull: false,
defaultValue: '0000-00-00',
primaryKey: true,
references: {
model: 'feira',
key: 'data',
},
},
},
{
tableName: 'aviso',
timestamps: false,
createdAt: false,
},
);
return Aviso;
};
<file_sep>/docs/api/celula.md
# Célula
## `GET /celula` - Lista células
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1_ - **Code 200** - Sucesso
```json
[
{
"cpf_feirante": "58295846035",
"periodo": 1
},
{
"cpf_feirante": "40515695009",
"periodo": 2
}
]
```
- Resposta _#2_ - **Code 401** - Token inválido
## `GET /celula/1` - Retorna informações da célula pelo ID
- Headers:
```
token: <jwt supervisor>
```
- Resposta _#1A_ - **Code 200** - Sucesso
```json
{
"cpf_feirante": "58295846035",
"periodo": 1
}
```
- Resposta _#1B_ - **Code 200** - ID não existente
```json
{
"msg": "id_nao_existente"
}
```
- Resposta _#2_ - **Code 401** - Token inválido
## `PUT /celula/1` - Atualiza célula
- Headers
```
Token: <jwt supervisor>
```
- Body
```json
{
"cpf_feirante": "58295846035",
"periodo": 1
}
```
- Resposta _#1A_ - **Code 200** - Célula atualizada
```json
{
"msg": "ok"
}
```
- Resposta _#1B_ - **Code 200** - Erro no banco de dados
```json
{
"msg": "erro"
}
```
- Resposta _#1C_ - **Code 200** - ID não existente
```json
{
"msg": "id_nao_existente"
}
```
- Resposta _#1D_ - **Code 200** - CPF não existente
```json
{
"msg": "cpf_nao_existente"
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos/CPF inválido
- Resposta _#3_ - **Code 401** - Token inválido
<file_sep>/frontend/src/components/EmptyComponent.js
import React, {PureComponent} from 'react';
import { Empty, Button } from 'antd';
export default class TabelaComponent extends PureComponent {
state = {};
render() {
const { onButtonClick, ...other } = this.props;
return (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
imageStyle={{
height: 60,
}}
description="Nenhum registro"
{...other}
>
{ onButtonClick
? (<Button type="primary" onClick={onButtonClick}>Adicionar</Button>)
: null
}
</Empty>
);
}
}
<file_sep>/backend/controllers/celula.js
const models = require('../models');
const findCelulaById = async (id) => {
const celula = await models.celula.findOne({
where: { id },
});
if (celula === null) return null;
return {
id: celula.id,
cpf_feirante: celula.cpf_feirante,
periodo: celula.periodo,
x: celula.x,
y: celula.y,
comprimento: celula.comprimento,
largura: celula.largura,
};
};
// Retorna celula reservada para um feirante
const findCelulaByFeirante = async (cpfFeirante) => {
const celula = await models.celula.findOne({
where: { cpf_feirante: String(cpfFeirante) },
});
if (celula === null) return null;
return {
id: celula.id,
cpf_feirante: celula.cpf_feirante,
periodo: celula.periodo,
x: celula.x,
y: celula.y,
comprimento: celula.comprimento,
largura: celula.largura,
};
};
const listCelula = async () => {
const celulas = await models.celula.findAll();
return celulas.map(celula => ({
id: celula.id,
cpf_feirante: celula.cpf_feirante,
periodo: celula.periodo,
x: celula.x,
y: celula.y,
comprimento: celula.comprimento,
largura: celula.largura,
}));
};
const updateCelula = async (id, dados) => {
const celula = await models.celula.findOne({ where: { id } });
if (celula === null) return null;
const { periodo } = dados;
if (periodo !== undefined && (periodo < 1 || periodo > 3)) return null;
try {
return await celula.update(dados);
} catch (error) {
return null;
}
};
module.exports = {
findCelulaById,
findCelulaByFeirante,
listCelula,
updateCelula,
};
<file_sep>/frontend/src/api/participa.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/participa`;
export function setPosicao(cpf, celula) {
return axios.post(`${host}/posicao`, {
cpf_feirante: Number(cpf), celula_id: celula, force: 1,
}, {
headers: { token: localStorage.getItem('token') },
});
}
export async function getConfirmados() {
const info = await axios.get(`${host}/confirmados`, {
headers: { token: localStorage.getItem('token') },
});
return info ? info.data : [];
}
export async function setPeriodo(periodo) {
const info = await axios.post(`${host}/confirma`, {
periodo,
}, {
headers: { token: localStorage.getItem('token') },
});
return info ? info.data : {};
}
export async function cancelaParticipacao() {
const info = await axios.post(`${host}/cancela`, {}, {
headers: { token: localStorage.getItem('token') },
});
return info ? info.data : {};
}
export async function getParticipa(data) {
const feirantes = await axios
.get(`${host}/${data}`)
.catch(e => console.log(`Erro ${e}`));
return feirantes;
}
export async function getParticipacaoUltimaFeira() {
const participacao = await axios
.get(`${host}/participacao`, {
headers: { token: localStorage.getItem("token") }
})
.catch(e => console.log(`Erro ${e}`));
return participacao.data;
}
export async function getParticipacaoGeral() {
const participacao = await axios
.get(`${host}/participacoes`, {
headers: { token: localStorage.getItem("token") }
})
.catch(e => console.log(`Erro ${e}`));
return participacao.data;
}<file_sep>/backend/tests/controllers/helper.js
const models = require('../../models');
before(async () => {
await models.categoria.destroy({ where: {} });
await models.celula.destroy({ where: {} });
await models.endereco.destroy({ where: {} });
await models.feira.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.participa.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
});
after(async () => {
await models.categoria.destroy({ where: {} });
await models.celula.destroy({ where: {} });
await models.endereco.destroy({ where: {} });
await models.feira.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.participa.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
models.sequelize.close();
});
<file_sep>/backend/database/insert_fake_data.js
const faker = require('faker');
const moment = require('moment');
const models = require('../models');
const categoriaController = require('../controllers/categoria');
const celulaController = require('../controllers/celula');
const subcategoriaController = require('../controllers/subcategoria');
const feiranteController = require('../controllers/feirante');
const feiraController = require('../controllers/feira');
const participaController = require('../controllers/participa');
const supervisorController = require('../controllers/supervisor');
// const { insert_celulas } = require('./insert_celulas');
const insert_data = async () => {
await models.categoria.destroy({ where: {} });
await models.celula.destroy({ where: {} });
await models.endereco.destroy({ where: {} });
await models.aviso.destroy({ where: {} });
await models.feira.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.participa.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
// insert_celulas();
supervisorController.addSupervisor('56662192007', 'Admin', '123456', true, true).catch(ex => console.error(ex));
const categoria = await categoriaController.addCategoria('Categoria 1', 1).catch(ex => console.error(ex));
const subcategoria = await subcategoriaController.addSubcategoria('Subcategoria 1', categoria.id).catch(ex => console.error(ex));
const feirante1 = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'123456',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
).catch(ex => console.error(ex));
const feirante2 = await feiranteController.addFeirante(
'19181608055',
'469964807',
faker.name.firstName(),
'',
'123456',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
).catch(ex => console.error(ex));
const feirante3 = await feiranteController.addFeirante(
'00192857010',
'469964807',
faker.name.firstName(),
'',
'123456',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
).catch(ex => console.error(ex));
const feirante4 = await feiranteController.addFeirante(
'24029942075',
'469964807',
faker.name.firstName(),
'',
'123456',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
).catch(ex => console.error(ex));
await feiranteController.addFeirante(
'52741277036',
'469964807',
faker.name.firstName(),
'',
'123456',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
).catch(ex => console.error(ex));
await feiraController.addFeira(moment()
.utc()
.startOf('isoWeek')
.add(6, 'day')
.hour(18)).catch(ex => console.error(ex));
await celulaController.updateCelula(1, { cpf_feirante: feirante1.cpf }).catch(ex => console.error(ex));
await celulaController.updateCelula(2, { cpf_feirante: feirante2.cpf }).catch(ex => console.error(ex));
await participaController.confirmaPresencaFeiraAtual(feirante1.cpf, 1).catch(ex => console.error(ex));
await participaController.confirmaPresencaFeiraAtual(feirante2.cpf, 1).catch(ex => console.error(ex));
await participaController.confirmaPresencaFeiraAtual(feirante3.cpf, 1).catch(ex => console.error(ex));
await participaController.confirmaPresencaFeiraAtual(feirante4.cpf, 1).catch(ex => console.error(ex));
process.exit(0);
};
insert_data();
<file_sep>/backend/middlewares/auth.js
const jwt = require('jsonwebtoken');
const feiranteController = require('../controllers/feirante');
const supervisorController = require('../controllers/supervisor');
const keys = require('../config/keys.json');
const isFeirante = async (req, res, next) => {
const { token } = req.headers;
if (token !== '') {
try {
const decoded = jwt.verify(token, keys.jwt);
if (decoded !== null) {
const feirante = await feiranteController.findFeiranteByCpf(decoded);
if (feirante !== null) {
req.cpf = decoded;
return next();
}
return res.status(401).end();
}
return res.status(401).end();
} catch (error) {
return res.status(401).end();
}
}
return res.status(401).end();
};
const isSupervisor = async (req, res, next) => {
const { token } = req.headers;
if (token !== '') {
try {
const decoded = jwt.verify(token, keys.jwt);
if (decoded !== null) {
const supervisor = await supervisorController.findSupervisorByCpf(decoded);
if (supervisor !== null) {
req.cpf = decoded;
return next();
}
return res.status(401).end();
}
return res.status(401).end();
} catch (error) {
return res.status(401).end();
}
}
return res.status(401).end();
};
const isFeiranteOrSupervisor = async (req, res, next) => {
const { token } = req.headers;
if (token !== '') {
try {
const decoded = jwt.verify(token, keys.jwt);
if (decoded !== null) {
const feirante = await feiranteController.findFeiranteByCpf(decoded);
if (feirante !== null) {
req.cpf = decoded;
return next();
}
const supervisor = await supervisorController.findSupervisorByCpf(decoded);
if (supervisor !== null) {
req.cpf = decoded;
return next();
}
return res.status(401).end();
}
return res.status(401).end();
} catch (error) {
return res.status(401).end();
}
}
return res.status(401).end();
};
const isAdmin = async (req, res, next) => {
const { token } = req.headers;
if (token !== '') {
try {
const decoded = jwt.verify(token, keys.jwt);
if (decoded !== null) {
const supervisor = await supervisorController.findSupervisorByCpf(decoded);
if (supervisor !== null && supervisor.is_adm) {
req.cpf = decoded;
return next();
}
return res.status(401).end();
}
return res.status(401).end();
} catch (error) {
return res.status(401).end();
}
}
return res.status(401).end();
};
module.exports = {
isFeirante, isSupervisor, isFeiranteOrSupervisor, isAdmin,
};
<file_sep>/backend/tests/middlewares/auth.js
const jwt = require('jsonwebtoken');
const chai = require('chai');
const chaiHttp = require('chai-http');
const { assert } = require('chai');
const sinon = require('sinon');
const keys = require('../../config/keys.json');
const models = require('../../models');
chai.use(chaiHttp);
const app = require('../../app');
const feiranteController = require('../../controllers/feirante');
const supervisorController = require('../../controllers/supervisor');
after(() => {
models.sequelize.close();
});
describe('Testando middleware validação JWT', () => {
before(() => {
models.feirante.destroy({ where: {} });
models.supervisor.destroy({ where: {} });
});
describe('Testando validação feirante', () => {
it('Não passa jwt nos headers', async () => {
const req = await chai
.request(app)
.post('/testes/token-feirante')
.set('token', '')
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido', async () => {
const req = await chai
.request(app)
.post('/testes/token-feirante')
.set('token', `${jwt.sign('<PASSWORD>', keys.jwt)}x`)
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido 2', async () => {
const req = await chai
.request(app)
.post('/testes/token-feirante')
.set('token', jwt.sign('<PASSWORD>', 'invalid_key'))
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido, porém feirante não existe', async () => {
// Essa função abaixo é utilizada para forçar a função findFeiranteByCpf
// a retornar qualquer valor desejado.
// Dessa forma não precisa ficar criando entidades de teste no banco de dados
// https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/
sinon.stub(feiranteController, 'findFeiranteByCpf').returns(null);
const req = await chai
.request(app)
.post('/testes/token-feirante')
.set('token', jwt.sign('111.111.111-11', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido e feirante existe', async () => {
sinon.stub(feiranteController, 'findFeiranteByCpf').returns({ cpf: '111.111.111-11' });
const req = await chai
.request(app)
.post('/testes/token-feirante')
.set('token', jwt.sign('111.111.111-11', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 200);
assert.strictEqual(req.text, '111.111.111-11');
});
});
describe('Testando validação supervisor', () => {
it('Não passa jwt nos headers', async () => {
const req = await chai
.request(app)
.post('/testes/token-supervisor')
.set('token', '')
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido', async () => {
const req = await chai
.request(app)
.post('/testes/token-supervisor')
.set('token', `${jwt.sign('111.111.111-11', keys.jwt)}x`)
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido 2', async () => {
const req = await chai
.request(app)
.post('/testes/token-supervisor')
.set('token', jwt.sign('111.111.111-11', 'invalid_key'))
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido, porém supervisor não existe', async () => {
// Essa função abaixo é utilizada para forçar a função findFeiranteByCpf
// a retornar qualquer valor desejado.
// Dessa forma não precisa ficar criando entidades de teste no banco de dados
// https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/
sinon.stub(supervisorController, 'findSupervisorByCpf').returns(null);
const req = await chai
.request(app)
.post('/testes/token-supervisor')
.set('token', jwt.sign('<PASSWORD>', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido e supervisor existe', async () => {
sinon.stub(supervisorController, 'findSupervisorByCpf').returns({ cpf: '111.111.111-11' });
const req = await chai
.request(app)
.post('/testes/token-supervisor')
.set('token', jwt.sign('<PASSWORD>', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 200);
assert.strictEqual(req.text, '111.111.111-11');
});
});
describe('Testando validação administrador', () => {
it('Não passa jwt nos headers', async () => {
const req = await chai
.request(app)
.post('/testes/token-admin')
.set('token', '')
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido', async () => {
const req = await chai
.request(app)
.post('/testes/token-admin')
.set('token', `${jwt.sign('111.111.111-11', keys.jwt)}x`)
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt inválido 2', async () => {
const req = await chai
.request(app)
.post('/testes/token-admin')
.set('token', jwt.sign('<PASSWORD>', 'invalid_key'))
.send();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido, porém admininstrador não existe', async () => {
// Essa função abaixo é utilizada para forçar a função findFeiranteByCpf
// a retornar qualquer valor desejado.
// Dessa forma não precisa ficar criando entidades de teste no banco de dados
// https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/
sinon.stub(supervisorController, 'findSupervisorByCpf').returns(null);
const req = await chai
.request(app)
.post('/testes/token-admin')
.set('token', jwt.sign('11<PASSWORD>1.111-11', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 401);
});
it('Passa jwt válido e admin existe', async () => {
sinon.stub(supervisorController, 'findSupervisorByCpf').returns({ cpf: '111.111.111-11' });
const req = await chai
.request(app)
.post('/testes/token-admin')
.set('token', jwt.sign('111.<PASSWORD>1-11', keys.jwt))
.send();
sinon.restore();
assert.strictEqual(req.status, 200);
assert.strictEqual(req.text, '111.111.111-11');
});
});
});
<file_sep>/frontend/src/screens/RelatorioFeirante/index.js
import React, { PureComponent } from "react";
import moment from "moment-timezone";
import { Table, Input, Button, Col, Row } from "antd";
import * as feiraAPI from "../../api/feira";
import * as relatorioAPI from "../../api/relatorio";
import ContentComponent from "../../components/ContentComponent";
import styles from "./RelatorioFeirante.module.scss";
import EmptyComponent from "../../components/EmptyComponent";
import {
getParticipacaoUltimaFeira,
getParticipacaoGeral
} from "../../api/participa";
const { Column } = Table;
export default class RelatorioFeirante extends PureComponent {
state = {
participantes: [],
faturamentos: [],
loading: true,
dataFeira: "",
presencas: []
};
componentDidMount() {
this._loadValues();
this._loadFat();
}
_loadFat = async () => {
this.setState({ loading: true });
try {
// Chamar a rota de relatorios do
await getParticipacaoGeral()
.then(response => {
this.setState({ faturamentos: response });
})
.catch(ex => console.warn(ex));
} catch (ex) {
console.warn(ex);
}
this.setState({ loading: false });
};
_loadValues = async () => {
this.setState({ loading: true });
try {
// Chamar a rota de relatorios do
await getParticipacaoUltimaFeira()
.then(response => {
const { data } = response;
this.setState({ presencas: data });
})
.catch(ex => console.warn(ex));
} catch (ex) {
console.warn(ex);
}
this.setState({ loading: false });
};
_renderPeriodo = periodo => {
if ((periodo = 1)) return "Manhã";
if ((periodo = 2)) return "Tarde";
return "Manhã e Tarde";
};
render() {
const { faturamentos, loading } = this.state;
return (
<ContentComponent loading={loading} title="Relatórios">
<Row gutter={10}>
<Col span={4}>
<div>
<Input
placeholder="Faturamento"
formatter={value =>
`R$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
parser={value => value.replace(/\$\s?|(,*)/g, "")}
/>
<div style={{ marginTop: 5 }}>
<Button onClick={this.toggle} type="primary">
Adicionar
</Button>
</div>
</div>
</Col>
</Row>
<Table
dataSource={faturamentos}
loading={loading}
rowKey={item => item.data_feira}
locale={{
emptyText: <EmptyComponent />
}}
>
<Column
title="Data"
dataIndex="data_feira"
key="data"
render={data => moment(data, "YYYY-MM-DD").format("DD/MM/YYYY")}
width={90}
/>
{/* <Column
title="CPF"
dataIndex="cpf_feirante"
key="CPF"
render={cpf_feirante =>
cpf_feirante.replace(
/(\d{3})(\d{3})(\d{3})(\d{2})/g,
"$1.$2.$3-$4"
)
}
width={90}
/> */}
<Column
title="Periodo"
dataIndex="periodo"
key="periodo"
render={this._renderPeriodo}
width={90}
/>
<Column
title="Faturamento"
dataIndex="faturamento"
key="faturamentoKey"
render={faturamentoteste =>
String(faturamentoteste).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
width={90}
/>
</Table>
</ContentComponent>
);
}
}
<file_sep>/backend/tests/controllers/categoria.js
const { assert } = require('chai');
const categoriaController = require('../../controllers/categoria');
const subCategoriaController = require('../../controllers/subcategoria');
const models = require('../../models');
describe('categoria.js', () => {
beforeEach(() => {
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
});
after(() => {
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
});
it('Cadastrar categorias', async () => {
models.categoria.destroy({ where: {} });
const res = await categoriaController.addCategoria('Salgadinhos', true);
assert.isNotNull(res);
});
it('Achar por id', async () => {
await models.categoria.destroy({ where: {} });
const res = await categoriaController.addCategoria('Pastel', true);
assert.isNotNull(res);
const categoria = await categoriaController.findCategoriaById(res.id);
assert.isNotNull(categoria);
});
it('Remover por Id', async () => {
const categoria = await categoriaController.addCategoria('Verduras', true);
assert.isNotNull(categoria);
let res = await categoriaController.deleteCategoria(categoria.id);
assert.isNotNull(res);
res = await categoriaController.findCategoriaById(categoria.id);
assert.isNull(res);
});
it('Remover por Id (com subcategoria)', async () => {
const categoria = await categoriaController.addCategoria('Verduras', true);
assert.isNotNull(categoria);
let subcategoria = await categoria.createSubCategoria({ nome: 'Alface' });
assert.isNotNull(subcategoria);
subcategoria = await subCategoriaController.findSubcategoriaById(subcategoria.id);
assert.isNotNull(subcategoria);
let res = await categoriaController.deleteCategoria(categoria.id);
assert.isNotNull(res);
res = await categoriaController.findCategoriaById(categoria.id);
assert.isNull(res);
subcategoria = await subCategoriaController.findSubcategoriaById(subcategoria.id);
assert.isNull(subcategoria);
});
it('Atualizar dados', async () => {
const categoria = await categoriaController.addCategoria('Caldo de cana', true);
assert.isNotNull(categoria);
const res = await categoriaController.updateCategoria(categoria.id, {
need_cnpj: false,
});
assert.isNotNull(res);
const res1 = await categoriaController.updateCategoria(categoria.id, {
nome: 'Artesanato',
need_cnpj: false,
});
assert.isNotNull(res1);
assert.strictEqual(res1.nome, 'Artesanato');
});
it('Listar todas Categorias', async () => {
let categoria = await categoriaController.addCategoria('Caldo de cana', true);
assert.isNotNull(categoria);
categoria = await categoriaController.addCategoria('Verduras', true);
assert.isNotNull(categoria);
const res = await categoriaController.addCategoria('Pastel', true);
assert.isNotNull(res);
const categorias = await categoriaController.listCategoria();
assert.lengthOf(categorias, 3);
});
});
<file_sep>/frontend/src/screens/Login/index.js
import React, { PureComponent } from 'react';
import MaskedInput from 'react-text-mask';
import styles from './LoginScreen.module.scss';
import image from '../../assets/brazao.png';
import {
Input, Icon, Button, Form,
message,
} from 'antd';
import { validateCPF } from '../../helpers/validators';
import login from '../../api/login';
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class LoginScreen extends PureComponent {
state = {};
componentDidMount() {
const { history } = this.props;
if (localStorage.getItem('token') !== null) {
if (localStorage.getItem('tag') === 'feirante') {
history.push('/feirante');
}
else {
history.push('/supervisor');
}
}
this.props.form.validateFields();
}
_handleSubmit = (e) => {
const { history } = this.props;
e.preventDefault();
message.loading('Carregando...', 0);
this.props.form.validateFields(async (err, values) => {
if (!err) {
await login(values.cpf.replace(/\D+/g, ''), values.senha)
.then(response => {
message.success('Logado com sucesso', 1.0);
localStorage.setItem('userID', response.data.userID);
localStorage.setItem('token', response.data.token);
localStorage.setItem('tag', response.data.tag);
if (response.data.tag === 'feirante') {
history.push('/feirante');
} else {
history.push('/supervisor');
}
})
.catch(ex => {
console.warn(ex);
message.error('CPF ou senha incorretos', 2.5);
});
}
});
}
render() {
const {
getFieldDecorator, getFieldsError, getFieldError, isFieldTouched,
} = this.props.form;
const cpfError = isFieldTouched('cpf') && getFieldError('cpf');
const senhaError = isFieldTouched('senha') && getFieldError('senha');
return (
<div className={styles.holder}>
<div className={styles.bgImage} />
<div className={styles.container}>
<div className={styles.card}>
<img className={styles.brazao} alt="brazão" src={image} />
<h1>Feira da Economia Criativa de<br />Campo Mourão</h1>
<Form onSubmit={this._handleSubmit}>
<Form.Item
validateStatus={cpfError ? 'error' : ''}
help={cpfError || ''}
>
{getFieldDecorator('cpf', {
rules: [
{
validator: validateCPF,
},
],
})(
<MaskedInput
placeholder="CPF"
mask={[/[0-9]/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '.', /\d/, /\d/, /\d/, '-', /\d/, /\d/]}
render={(ref, props) => (
<input className="ant-input" ref={ref} {...props} />
)}
/>
)}
</Form.Item>
<Form.Item
validateStatus={senhaError ? 'error' : ''}
help={senhaError || ''}
>
{getFieldDecorator('senha', {
rules: [{
required: true,
message: 'Insira sua senha!'
}],
})(
<Input
type="password"
placeholder="Senha"
/>
)}
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
block
disabled={hasErrors(getFieldsError())}
>
Entrar
</Button>
</Form.Item>
</Form>
</div>
</div>
</div>
);
}
}
const WrappedHorizontalLoginForm = Form.create({ name: 'login_form' })(LoginScreen);
export default WrappedHorizontalLoginForm;<file_sep>/backend/routes/testes.js
const express = require('express');
const router = express.Router();
const authMiddleware = require('../middlewares/auth');
// Rota de teste que necessita ter feirante autenticado
router.post('/feirante', authMiddleware.isFeirante, (req, res) => {
res.status(200).send({ cpf: req.cpf });
});
// Rota de teste que necessita ter supervisor autenticado
router.post('/supervisor', authMiddleware.isSupervisor, (req, res) => {
res.status(200).send({ cpf: req.cpf });
});
// Rota de teste que necessita ter administrador autenticado
router.post('/administrador', authMiddleware.isAdmin, (req, res) => {
res.status(200).send({ cpf: req.cpf });
});
module.exports = router;
<file_sep>/frontend/src/screens/Mapeamento/AlocacaoForm.js
import React, { Component, Fragment } from 'react';
import {
Popconfirm, Button, Form,
Select, Table,Checkbox,message,
} from 'antd';
import maskCPF from '../../helpers/masker';
import * as participaAPI from '../../api/participa';
const { Column } = Table;
const { Option } = Select;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class AlocacaoForm extends Component {
state = {
subcategorias: [],
loading: false,
editingSubcategoria: {},
};
// componentDidMount() {
// this._loadCelulas();
// }
// _loadCelulas = () => {
// const { celula } = this.props;
// this.setState({celula});
// }
// componentDidUpdate(prevProps){
// if(prevProps.celula !== this.props.celula){
// this.setState({
// celula: this.props.celula
// });
// }
// }
_handleSubmit = (e) => {
// const { celula } = this.state;
const {
form: {resetFields},
refresh, celula, loadCelulas,onSuccess,
} = this.props;
e.preventDefault();
// this.setState({loading: true});
this.props.form.validateFields((err, values) => {
if (!err) {
return participaAPI.setPosicao(values.nome, celula.id)
.then(response => {
refresh();
loadCelulas();
resetFields();
if (onSuccess) {
onSuccess();
}
message.success('Feirante atualizado com sucesso', 2.5);
}).catch(ex => {
message.error('Não foi possível atualizar, tente novamente mais tarde', 2.5);
console.warn(ex);
});
}
});
}
// _loadSubcategorias = async () => {
// const { categoria } = this.props;
// this.setState({loading: true});
// const subcategorias = await categoriasAPI.getSub(categoria.id);
// this.setState({subcategorias, loading: false});
// }
_onRemoveFeiranteCelula = cpf => {
const { refresh,onSuccess} = this.props;
return participaAPI.setPosicao(cpf, null)
.then(() => {
refresh();
if (onSuccess) {
onSuccess();
}
message.success('Feirante removido com sucesso', 2.5);
}).catch(() => {
message.error('Não foi possível atualizar,tente novamente mais tarde', 2.5);
});
}
// _onEditSub = async sub => {
// const { form: { setFieldsValue } } = this.props;
// this.setState({ editingSubcategoria: sub });
// return await setFieldsValue({
// novo_nome: sub.nome,
// });
// }
_renderPeriodo = (periodo) => {
switch(periodo) {
case 1:
return 'Manhã';
case 2:
return 'Tarde';
case 3:
return 'Manhã e tarde';
default:
return '';
}
}
_renderFeirantesNaCelula = () => {
const { loading } = this.state;
const { celula } = this.props;
if(!celula) return null;
return (
<Table
dataSource={celula.feirantes}
loading={loading}
size="small"
rowKey={celula => celula.feirante.cpf}
pagination={{
pageSize: 15,
}}
>
<Column
key='AlocacaoId'
dataIndex="feirante.cpf"
title="#"
width={120}
render={cpf => maskCPF(cpf)}
/>
<Column
key="AlocacaoNome"
dataIndex="feirante.nome"
title="Nome"
/>
<Column
key="AlocacaoNomeFantasia"
dataIndex="feirante.nomeFantasia"
title="Nome fantasia"
/>
<Column
key="AlocacaoPeriodo"
dataIndex="periodo"
title="Periodo"
render={periodo => this._renderPeriodo(periodo)}
/>
<Column
key="acoes"
title="Ações"
width={90}
render={linha => {
return (
<Popconfirm
title="Você quer relamente deletar esta categoria?"
okText="Sim"
cancelText="Não"
onConfirm={() => this._onRemoveFeiranteCelula(linha.feirante.cpf)}
>
<Button shape="circle" icon="delete" type="danger" />
</Popconfirm>
);
}}
/>
</Table>
);
}
handleCancel = () => {
this.setState({ editingSubcategoria: {} });
}
render() {
const { form, confirmados, celula } = this.props;
// const { celula } = this.state;
const {
getFieldDecorator, getFieldsError, getFieldError,
isFieldTouched, getFieldValue,
} = form;
const nomeError = isFieldTouched('nome') && getFieldError('nome');
const naoAlocados = confirmados.feirantes ? confirmados.feirantes.filter(feirante => feirante.celulaId === null) : [];
return (
<Fragment>
<Form layout="inline" onSubmit={this._handleSubmit}>
<Form.Item
validateStatus={nomeError ? 'error' : ''}
help={nomeError || ''}
>
{getFieldDecorator('nome', {rules: [{
required: true,
message: 'O nome da subcategoria é obrigatório!'
}]})(
<Select
showSearch
style={{ width: 300 }}
disabled={!celula || !celula.feirantes || celula.feirantes.length === 2 || (celula.feirantes[0] && celula.feirantes[0].periodo === 3)}
placeholder="Selecione um feirante..."
optionFilterProp="children"
filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
>
{
naoAlocados.map(confirmado => {
const nome = `${maskCPF(confirmado.feirante.cpf)} - ${confirmado.feirante.nomeFantasia ? confirmado.feirante.nomeFantasia : confirmado.feirante.nome}`;
return (
<Option
key={confirmado.feirante.cpf}
cpf={confirmado.feirante.cpf}
value={confirmado.feirante.cpf}
>
<span style={{fontWeight: "bold"}}>{nome}</span>
<br />
<span style={{fontStyle: "italic"}}>{confirmado.sub_categoria.nome}</span>
</Option>
);
})
}
</Select>
)}
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
disabled={
hasErrors(getFieldsError())
|| !getFieldValue('nome')
}
>
Alocar
</Button>
</Form.Item>
{
celula && celula.feirantes && celula.feirantes.length === 1 && celula.feirantes[0].periodo !== 3
? (
<p>Já existe um feirante alocado nesta célula, aloque outro no periodo da {celula.feirantes[0].periodo === 1 ? 'tarde' : 'manhã'}.</p>
) : null
}
</Form>
{ this._renderFeirantesNaCelula() }
</Fragment>
);
}
}
const WrappedHorizontalAlocacaoForm = Form.create({ name: 'categorias_form' })(AlocacaoForm);
export default WrappedHorizontalAlocacaoForm;<file_sep>/backend/tests/models/exemplo.js
// const chance = require("chance").Chance();
// const { assert } = require("chai");
// const models = require("../../models");
// after(() => {
// models.sequelize.close();
// });
// describe("Teste exemplo", () => {
// // Essa função é executada antes de cada teste
// beforeEach(() => {
// // Limpa o banco
// models.feirante.destroy({ where: {} });
// models.categoria.destroy({ where: {} });
// models.subcategoria.destroy({ where: {} });
// models.feira.destroy({ where: {} });
// models.celula.destroy({ where: {} });
// // Caso precisar adicionar algo no banco antes dos testes colocar aqui
// });
// // Testa adicionar feira
// it("Adiciona feira", async () => {
// // Verifica se a feira não existe
// let feira = await models.feira.findOne({ where: { data: "2018-12-31" } });
// assert.isNull(feira);
// // Cria a feira
// await models.feira.create({ data: "2018-12-31" });
// feira = await models.feira.findOne({ where: { data: "2018-12-31" } });
// // Verifica se a feira existe e se a data está correta
// assert.isNotNull(feira);
// assert.strictEqual(feira.data, "2018-12-31");
// });
// });
<file_sep>/backend/app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const feirante = require('./routes/feirante');
const feira = require('./routes/feira');
const login = require('./routes/login');
const supervisor = require('./routes/supervisor');
const celula = require('./routes/celula');
const categoria = require('./routes/categoria');
const subcategoria = require('./routes/subcategoria');
const participa = require('./routes/participa');
const aviso = require('./routes/aviso');
const date = require('./routes/date');
const image = require('./routes/image');
const auth = require('./routes/testes');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const router = express.Router();
router.use('/feirante', feirante);
router.use('/login', login);
router.use('/supervisor', supervisor);
router.use('/celula', celula);
router.use('/feira', feira);
router.use('/categoria', categoria);
router.use('/subcategoria', subcategoria);
router.use('/participa', participa);
router.use('/aviso', aviso);
router.use('/date', date);
router.use('/image', image);
router.use('/auth', auth);
app.use('/api', router);
module.exports = app;
<file_sep>/backend/tests/controllers/supervisor.js
const { assert } = require('chai');
const faker = require('faker');
const supervisorController = require('../../controllers/supervisor');
const models = require('../../models');
describe('supervisor.js', () => {
beforeEach(async () => {
await models.supervisor.destroy({ where: {} });
});
after(() => {
models.supervisor.destroy({ where: {} });
});
describe('addSupervisor', () => {
it('Cadastra um supervisor', async () => {
const supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
assert.isNotNull(supervisor);
});
it('Não cadastra um supervisor com informação faltando', async () => {
const supervisor = await supervisorController.addSupervisor(
'58295846035',
null,
faker.name.firstName(),
true,
);
assert.isNull(supervisor);
});
it('Não cadastra um supervisor repetido', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
assert.isNotNull(supervisor);
supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
assert.isNull(supervisor);
});
it('Re-ativa um supervisor', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
assert.isNotNull(supervisor);
const res = await supervisorController.deleteSupervisor(supervisor.cpf);
assert.isNotNull(res);
supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
assert.isNotNull(supervisor);
});
});
describe('listSupervisor', () => {
it('Retorna vazio se não existir supervisor', async () => {
const supervisores = await supervisorController.listSupervisor();
assert.lengthOf(supervisores, 0);
});
it('Retorna lista de supervisores', async () => {
let supervisores = await supervisorController.listSupervisor();
assert.lengthOf(supervisores, 0);
const supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisores = await supervisorController.listSupervisor();
assert.lengthOf(supervisores, 1);
assert.strictEqual(supervisores[0].cpf, supervisor.cpf);
});
it('Não lista supervisor inativo', async () => {
let supervisores = await supervisorController.listSupervisor();
assert.lengthOf(supervisores, 0);
const supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
const supervisor2 = await supervisorController.addSupervisor(
'83762032076',
faker.name.firstName(),
faker.name.firstName(),
true,
);
await supervisorController.deleteSupervisor(supervisor2.cpf);
supervisores = await supervisorController.listSupervisor();
assert.lengthOf(supervisores, 1);
assert.strictEqual(supervisores[0].cpf, supervisor.cpf);
});
});
describe('findSupervisorByCpf', () => {
it('Retorna null se supervisor não existe', async () => {
const supervisor = await supervisorController.findSupervisorByCpf('58295846035');
assert.isNull(supervisor);
});
it('Retorna supervisor', async () => {
const supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
const supervisorFind = await supervisorController.findSupervisorByCpf('58295846035');
assert.isNotNull(supervisorFind);
assert.strictEqual(supervisor.cpf, supervisorFind.cpf);
});
it('Retorna null se supervisor for inativo', async () => {
const supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
await supervisorController.deleteSupervisor(supervisor.cpf);
const supervisorFind = await supervisorController.findSupervisorByCpf('58295846035');
assert.isNull(supervisorFind);
});
});
describe('updateSupervisor', () => {
it('Não atualiza supervisor que não existe', async () => {
const supervisor = await supervisorController.updateSupervisor('58295846035', {
nome: faker.name.firstName(),
senha: faker.name.firstName(),
is_adm: true,
});
assert.isNull(supervisor);
});
it('Não atualiza supervisor desativado', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
await supervisorController.deleteSupervisor(supervisor.cpf);
supervisor = await supervisorController.updateSupervisor('58295846035', {
nome: faker.name.firstName(),
senha: faker.name.firstName(),
is_adm: true,
});
assert.isNull(supervisor);
});
it('Não deixa atualizar status', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisor = await supervisorController.updateSupervisor('58295846035', {
status: false,
});
assert.isNull(supervisor);
});
it('Não deixa atualizar root_adm', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisor = await supervisorController.updateSupervisor('58295846035', {
root_adm: true,
});
assert.isNull(supervisor);
});
it('Não deixa atualizar is_adm para o root_adm', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
true,
);
supervisor = await supervisorController.updateSupervisor('58295846035', {
is_adm: false,
});
assert.isNull(supervisor);
});
it('Atualiza is_adm', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisor = await supervisorController.updateSupervisor('58295846035', {
is_adm: false,
});
assert.isNotNull(supervisor);
});
it('Atualiza somente senha', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisor = await supervisorController.updateSupervisor('58295846035', {
senha: faker.name.firstName(),
});
assert.isNotNull(supervisor);
});
it('Atualiza todos os campos exceto senha', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
const novoNome = faker.name.firstName();
supervisor = await supervisorController.updateSupervisor('58295846035', {
nome: novoNome,
is_adm: false,
});
assert.isNotNull(supervisor);
assert.strictEqual(supervisor.nome, novoNome);
});
});
describe('deleteSupervisor', () => {
it('Não deleta supervisor que não existe', async () => {
const supervisor = await supervisorController.deleteSupervisor('58295846035');
assert.isNull(supervisor);
});
it('Não deleta supervisor desativado', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
await supervisorController.deleteSupervisor(supervisor.cpf);
supervisor = await supervisorController.deleteSupervisor(supervisor.cpf);
assert.isNull(supervisor);
});
it('Deleta supervisor', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
);
supervisor = await supervisorController.deleteSupervisor(supervisor.cpf);
assert.isNotNull(supervisor);
supervisor = await supervisorController.findSupervisorByCpf(supervisor.cpf);
assert.isNull(supervisor);
});
it('Não deleta supervisor root', async () => {
let supervisor = await supervisorController.addSupervisor(
'58295846035',
faker.name.firstName(),
faker.name.firstName(),
true,
true,
);
supervisor = await supervisorController.deleteSupervisor(supervisor.cpf);
assert.isNull(supervisor);
});
});
});
<file_sep>/frontend/src/screens/Relatorios/index.js
import React, { PureComponent, Fragment } from 'react';
import {
Table, Tag, Button,
} from 'antd';
import moment from 'moment-timezone';
import ContentComponent from '../../components/ContentComponent';
import EmptyComponent from '../../components/EmptyComponent';
import * as relatorioAPI from '../../api/relatorio';
const { Column } = Table;
export default class RelatoriosScreen extends PureComponent {
state = {
feiras: [],
visible: false,
participantes: {},
loading: true,
};
componentDidMount() {
this._loadRelatorios();
}
_loadRelatorios = async () => {
this.setState({loading: true});
const feiras = await relatorioAPI.getFeiras();
this.setState({ feiras, loading: false });
}
_goToRelatorio = (event, data) => {
event.preventDefault();
const { history } = this.props;
history.push(`/supervisor/relatorios/${moment(data).format('DD-MM-YYYY')}`);
}
_renderAcoes = feira => {
return (
<Button onClick={event => this._goToRelatorio(event, feira.data)} disabled={!feira.status} type="primary">
Relatório
</Button>
);
}
_hideModal = () => {
this.setState({visible: false});
}
render() {
const { feiras, loading } = this.state;
return (
<Fragment>
<ContentComponent
title="Relatórios"
>
<Table
dataSource={feiras}
loading={loading}
rowKey={linha => linha.data}
locale={{
emptyText: <EmptyComponent />
}}
>
<Column
title="Data"
dataIndex="data"
key="data"
render={data => moment(data).format('DD/MM/YYYY')}
width={90}
/>
<Column
title="Data limite"
dataIndex="data_limite"
key="data_limite"
render={data => moment(data).format('DD/MM/YYYY [às] HH:mm')}
/>
<Column
title="Status"
dataIndex="status"
key="status"
render={status => {
return status
? <Tag color="#87d068">Ativo</Tag>
: <Tag color="#f50">Inativo</Tag>
}}
width={70}
/>
<Column
title="Ações"
key="acoes"
render={this._renderAcoes}
width={105}
/>
</Table>
</ContentComponent>
</Fragment>
)
}
}
<file_sep>/backend/controllers/feira.js
const Sequelize = require('sequelize');
const models = require('../models/');
const { proximaSexta } = require('./utils');
const op = Sequelize.Op;
const listFeiras = async () => {
const feiras = await models.feira.findAll({ order: [['data', 'DESC']] });
return feiras;
};
const findFeira = async (dataFeira) => {
const feira = await models.feira.findOne({
where: { data: dataFeira },
});
if (!feira) return null;
return feira;
};
const findFeiraAtual = async () => {
const dataAtual = new Date();
const nextData = new Date();
dataAtual.setDate(dataAtual.getDate() - 1);
nextData.setDate(nextData.getDate() + 7);
// let hoje = dataAtual.getFullYear().toString();
// hoje = hoje.concat('-', dataAtual.getMonth().toString(), '-', dataAtual.getDate().toString());
// let prox = nextData.getFullYear().toString();
// prox = prox.concat('-', nextData.getMonth().toString(), '-', nextData.getDate().toString());
const hoje = dataAtual.toISOString().split('T')[0];
const prox = nextData.toISOString().split('T')[0];
const feira = await models.feira.findOne({
// encontra a feira da semana
where: {
data: {
[op.between]: [hoje, prox],
},
status: true,
},
});
return feira;
};
// Realmente necessário?
const feiraAtualInfo = async () => {
const feira = await findFeiraAtual();
if (feira !== null) {
return {
data: feira.data,
data_limite: feira.data_limite,
status: feira.status,
evento_image_url: feira.evento_image_url,
};
}
return null;
// devolve a {data, status} da feira casa haja
// senao retorna null
};
const setDataLimiteFeiraAtual = async (dataHora) => {
const feira = await findFeiraAtual();
if (feira === null) return null;
const agora = new Date();
if (dataHora < agora) return null;
try {
return await feira.update({ data_limite: dataHora });
} catch (error) {
return null;
}
};
const addFeira = async (dataFeira, eventoImageUrl) => {
// const data = date.slice(6, 10).concat('-', date.slice(3, 5), '-', date.slice(0, 2));
// const feira = await models.feira.findOne({
// where: {
// data,
// },
// });
// console.log('aaaa')
// if (feira != null) {
// return null;
// }
const agora = new Date();
if (dataFeira < agora) return null;
try {
return await models.feira.create({
data: dataFeira.toISOString().split('T')[0],
data_limite: proximaSexta(),
evento_image_url: eventoImageUrl,
status: true,
});
} catch (error) {
console.error(error); // eslint-disable-line
return null;
}
// adiciona uma feira no banco
// se der certo retorna true
// caso algum erro ocorra devolve null
};
const alteraFeiraStatus = async (data) => {
const feira = await findFeira(data);
if (feira) {
return feira.update({ status: !feira.status });
}
return null;
// altera o status de uma feira
// retorna null se der errado
};
const alteraFotoFeira = async (data, photo) => {
const feira = await findFeira(data);
if (feira) {
return feira.update({ evento_image_url: photo });
}
return null;
};
const cancelaFeiraAtual = async () => {
const feira = await findFeiraAtual();
if (feira !== null) {
const disable = await feira.update({ status: false });
return disable;
}
return null;
// cancelar a fiera atual
// desativa
// retorna null se der errado
};
module.exports = {
findFeira,
findFeiraAtual,
feiraAtualInfo,
setDataLimiteFeiraAtual,
addFeira,
alteraFeiraStatus,
alteraFotoFeira,
cancelaFeiraAtual,
listFeiras,
};
<file_sep>/frontend/src/App.js
import React, { Component } from 'react';
import { BrowserRouter, matchPath } from 'react-router-dom';
import { message } from 'antd';
import routes from './routes';
import MainLayout from './layouts/MainLayout';
import './App.css';
import 'antd/dist/antd.css';
import { auth } from './api/auth';
class App extends Component {
state = {};
componentDidMount() {
this._verifyUser();
message.config({
maxCount: 1,
});
}
_mediaProviderUpdate = ref => {
if (ref) {
ref.provider.update();
}
};
_verifyUser = async () => {
try {
const route = routes.find(r => matchPath(window.location.pathname, r));
const loggedUserType = await localStorage.getItem('tag');
const isUserLogged = await auth(loggedUserType);
if (route && !route.public && !loggedUserType) {
localStorage.clear();
window.location = '/';
return null;
}
if (loggedUserType) {
if (route && !route.public && !isUserLogged.data.cpf) {
localStorage.clear();
window.location = '/';
return null;
}
if(!route.permissions.find(permission => permission === loggedUserType) && !route.public) {
window.location = '/';
return null;
};
}
} catch (ex) {
console.warn(ex);
}
}
render() {
return (
<BrowserRouter>
<MainLayout />
</BrowserRouter>
);
}
}
export default App;
<file_sep>/backend/models/feira.js
/* jshint indent: 2 */
module.exports = (sequelize, DataTypes) => {
const Feira = sequelize.define(
'feira',
{
data: {
type: DataTypes.DATEONLY,
allowNull: false,
defaultValue: '0000-00-00',
primaryKey: true,
},
data_limite: {
type: DataTypes.DATE,
allowNull: false,
},
evento_image_url: {
type: DataTypes.STRING(200),
allowNull: true,
},
status: {
type: DataTypes.BOOLEAN(),
allowNull: true,
defaultValue: true,
},
},
{
tableName: 'feira',
timestamps: false,
createdAt: false,
},
);
return Feira;
};
<file_sep>/frontend/src/api/subcategoria.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/subcategoria`;
export async function post(nome, categoria_id) {
await axios.post(
host, {
nome,
categoria_id,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export function put(nome, id) {
return axios.put(
`${host}/${id}`,
{
nome,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export async function getSubById(id) {
const record = (await axios.get(`${host}/${id}`, {
headers: { token: localStorage.getItem('token') },
})).data;
return { ...record };
}
export async function getCatBySub(id) {
return axios.get(`${host}/${id}/categoria`, {
headers: { token: localStorage.getItem('token') },
});
}
export async function deleteSub(id) {
const record = (await axios.delete(`${host}/${id}`, {
headers: { token: localStorage.getItem('token') },
})).data;
return { ...record };
}<file_sep>/frontend/src/layouts/MainLayout.js
import React, { Component } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import routes from '../routes';
import HomeScreen from '../screens/HomeScreen';
import FeiranteScreen from '../screens/FeiranteScreen';
class MainLayout extends Component {
state = {}
_renderRoute = (route, index) => {
return (
<Route key={index} {...route} />
);
}
_renderPrivateRoute = (route, index) => {
const { component: Comp, ...others } = route;
if (route.permissions.find(permission => permission === 'feirante')) {
return (
<Route
key={index}
render={props => {
return (
<FeiranteScreen>
<Comp {...props} />
</FeiranteScreen>
);
}}
{...others}
/>
);
}
return (
<Route
key={index}
render={props => {
return (
<HomeScreen>
<Comp {...props} />
</HomeScreen>
);
}}
{...others}
/>
);
}
_renderContent = () => {
return routes.map((route, index) => (
route.public
? this._renderRoute(route, index)
: this._renderPrivateRoute(route, index)
));
}
render() {
return (
<div>
<Switch>
{this._renderContent()}
</Switch>
</div>
);
}
}
export default withRouter(MainLayout);
<file_sep>/backend/tests/routes/celula.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const faker = require('faker');
const supervisorController = require('../../controllers/supervisor');
const categoriaController = require('../../controllers/categoria');
const feiranteController = require('../../controllers/feirante');
const loginController = require('../../controllers/login');
const app = require('../../app');
const models = require('../../models');
const { assert } = chai;
chai.use(chaiHttp);
const host = '/api/celula/';
describe('celula.js', () => {
let tokenFeirante;
let feirante;
let tokenSupervisor;
before(async () => {
const supervisor = await supervisorController.addSupervisor(
'89569380080',
faker.name.firstName(),
'1234',
true,
);
const categoria = await categoriaController.addCategoria('Alimento', false);
const subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'1234',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
tokenFeirante = (await loginController.login(feirante.cpf, '1234')).token;
tokenSupervisor = (await loginController.login(supervisor.cpf, '1234')).token;
});
after(async () => {
await models.celula.destroy({ where: {} });
await models.categoria.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
// await models.sequelize.close();
});
describe('GET /celula', () => {
it('Feirante não pode listar celulas', async () => {
const res = await chai
.request(app)
.get(host)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 401);
});
it('Supervisor pode listar celulas', async () => {
const res = await chai
.request(app)
.get(host)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.lengthOf(res.body, 1);
assert.strictEqual(res.body[0].periodo, 1);
});
});
describe('GET /celula/:id', () => {
it('Lista celula inexistente', async () => {
const res = await chai
.request(app)
.get(`${host}100`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'id_nao_existente');
});
it('Lista celula', async () => {
const res = await chai
.request(app)
.get(`${host}1`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.periodo, 1);
});
});
describe('PUT /celula/:id', () => {
it('Atributo inválido', async () => {
const res = await chai
.request(app)
.put(`${host}1`)
.set('token', tokenSupervisor)
.send({ periodo: 'string' });
assert.strictEqual(res.statusCode, 400);
});
it('CPF inválido', async () => {
const res = await chai
.request(app)
.put(`${host}1`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: '11111111111' });
assert.strictEqual(res.statusCode, 400);
});
it('CPF não existente', async () => {
const res = await chai
.request(app)
.put(`${host}1`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: '59517816049' });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cpf_nao_existente');
});
it('ID não existente', async () => {
const res = await chai
.request(app)
.put(`${host}100`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'id_nao_existente');
});
it('Atualiza celula', async () => {
const res = await chai
.request(app)
.put(`${host}1`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
});
});
<file_sep>/frontend/src/api/feira.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/feira`;
export async function listFeiras() {
const info = await axios
.get(host, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return info === null ? [] : info.data;
};
export async function feiraAtual() {
const feira = await axios
.get(`${host}/info`, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return feira ? feira.data : {};
};
export async function post(data, photo) {
const feira = await axios
.post(host, { data, photo }, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return Boolean(feira);
};
export async function deletaUltimaFeira() {
const feira = await axios
.delete(host, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return feira;
};
export async function alteraStatusFeira(data) {
const feira = await axios
.put(`${host}/altera-status`, { data }, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return feira;
};
export async function atualizaFoto(data, photo) {
const feira = await axios
.put(`${host}`, { data, photo }, { headers: { token: localStorage.getItem('token') } })
.catch(ex => console.error(ex));
return feira;
};
<file_sep>/backend/tests/routes/utils.js
const { assert } = require('chai');
const utils = require('../../routes/utils');
describe('utils.js', () => {
describe('isCpf', () => {
it('CPF válido', () => {
assert.isTrue(utils.isCpf('11161955003'));
assert.isTrue(utils.isCpf('41889740012'));
assert.isTrue(utils.isCpf('111.619.550-03'));
});
it('CPF inválido', () => {
assert.isFalse(utils.isCpf(''));
assert.isFalse(utils.isCpf('11161955004'));
assert.isFalse(utils.isCpf('111.619.550-04'));
});
});
describe('isCnpj', () => {
it('CNPJ válido', () => {
assert.isTrue(utils.isCnpj('34734698000190'));
assert.isTrue(utils.isCnpj('14538070000102'));
assert.isTrue(utils.isCnpj('73.356.873/0001-05'));
});
it('CNPJ inválido', () => {
assert.isFalse(utils.isCnpj('34734668000191'));
assert.isFalse(utils.isCnpj('73.356.173/0001-07'));
});
});
});
<file_sep>/frontend/src/routes/index.js
import FeiranteScreen from '../screens/Feirante';
import FeiraScreen from '../screens/Feira';
import AvisosScreen from '../screens/Avisos';
import SupervisoresScreen from '../screens/Supervisores';
import RelatoriosScreen from '../screens/Relatorios';
import MapeamentoScreen from '../screens/Mapeamento';
import CategoriasScreen from '../screens/Categorias';
import RelatorioPage from '../screens/Relatorios/RelatorioPage';
import LoginScreen from '../screens/Login';
import ConfirmacaoFeirante from '../screens/ConfirmacaoFeirante';
import RelatorioFeirante from '../screens/RelatorioFeirante';
import PerfilFeirante from '../screens/PerfilFeirante';
const FEIRANTE = 'feirante';
const SUPERVISOR = 'supervisor';
const ADMINISTRADOR = 'administrador';
export default [
{
path: '/',
exact: true,
hidden: true,
public: true,
component: LoginScreen,
key: 'login',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor',
exact: true,
component: FeiraScreen,
icon: 'shop',
key: 'feira',
label: 'Feira',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/supervisores',
exact: true,
component: SupervisoresScreen,
icon: 'user',
key: 'supervisores',
label: 'Supervisores',
permissions: [ADMINISTRADOR],
},
{
path: '/supervisor/feirante',
exact: true,
component: FeiranteScreen,
icon: 'team',
key: 'feirante',
label: 'Feirantes',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/categorias',
exact: true,
component: CategoriasScreen,
icon: 'tags',
key: 'categorias',
label: 'Categorias',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/relatorios',
exact: true,
component: RelatoriosScreen,
icon: 'read',
key: 'relatorios',
label: 'Relatórios',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/relatorios/:data',
exact: true,
hidden: true,
component: RelatorioPage,
icon: 'read',
key: 'relatoriopage',
label: 'Relatórios',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/mapeamento',
exact: true,
component: MapeamentoScreen,
icon: 'table',
key: 'mapeamento',
label: 'Mapeamento',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/supervisor/avisos',
exact: true,
component: AvisosScreen,
icon: 'info-circle',
key: 'avisos',
label: 'Avisos',
permissions: [SUPERVISOR, ADMINISTRADOR],
},
{
path: '/feirante',
exact: true,
component: ConfirmacaoFeirante,
icon: 'check',
key: 'confirmacao',
label: 'Confirmação',
permissions: [FEIRANTE],
},
{
path: '/feirante/relatorio',
exact: true,
component: RelatorioFeirante,
icon: 'table',
key: 'RelatorioFeirante',
label: 'Relatório',
permissions: [FEIRANTE],
},
{
path: '/feirante/perfil',
exact: true,
component: PerfilFeirante,
icon: 'user',
key: 'perfil',
label: 'Perfil',
permissions: [FEIRANTE],
},
];
<file_sep>/backend/routes/feirante.js
const express = require('express');
const { body, param, validationResult } = require('express-validator/check');
const { isCpf, isCnpj, isEndereco } = require('./utils');
const router = express.Router();
const subCategoriaController = require('../controllers/subcategoria');
const feiranteController = require('../controllers/feirante');
const authMiddleware = require('../middlewares/auth');
router.post(
'/',
authMiddleware.isSupervisor,
[
body('cpf').custom(isCpf),
body('cnpj')
.custom(isCnpj)
.optional(),
body('nome')
.isString()
.isLength({ min: 1, max: 100 }),
body('rg')
.isString()
.isLength({ min: 9, max: 9 }),
body('usa_ee').isBoolean(),
body('nome_fantasia')
.optional()
.isString()
.isLength({ min: 0, max: 100 }),
body('razao_social')
.optional()
.isString()
.isLength({ min: 0, max: 100 }),
body('comprimento_barraca').isDecimal(),
body('largura_barraca').isDecimal(),
body('endereco').custom(isEndereco),
body('voltagem_ee')
.optional(),
body('sub_categoria_id').isInt(),
body('senha')
.isString()
.isLength({ min: 6, max: 100 }),
],
async (req, res) => {
if (!req.body) return res.status(400).send();
const {
cpf,
cnpj,
nome,
rg,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
senha,
} = req.body;
const subcategoria = await subCategoriaController.findSubcategoriaById(sub_categoria_id);
if (subcategoria === null) return res.json({ msg: 'subcategoria_nao_existe' });
const feirante = await feiranteController.findFeiranteByCpf(cpf);
if (feirante !== null) return res.json({ msg: 'cpf_existente' });
const ret = await feiranteController.addFeirante(
cpf,
rg,
nome,
cnpj,
senha,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
);
if (ret === null) return res.json({ msg: 'erro' });
return res.json({ msg: 'ok' });
},
);
router.get('/', authMiddleware.isSupervisor, async (req, res) => {
const feirantes = await feiranteController.listFeirante();
return res.json(
feirantes.map(feirante => ({
cpf: feirante.cpf,
cnpj: feirante.cnpj,
nome: feirante.nome,
rg: feirante.rg,
usa_ee: feirante.usaEe,
nome_fantasia: feirante.nomeFantasia,
razao_social: feirante.razaoSocial,
comprimento_barraca: feirante.comprimentoBarraca,
largura_barraca: feirante.larguraBarraca,
endereco: {
logradouro: feirante.endereco.logradouro,
bairro: feirante.endereco.bairro,
numero: feirante.endereco.numero,
cep: feirante.endereco.CEP,
},
voltagem_ee: feirante.voltagemEe,
sub_categoria_id: feirante.subCategoriaId,
})),
);
});
router.get('/profile/:cpf', [param('cpf').custom(isCpf)], authMiddleware.isFeirante, async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send();
const { cpf } = req.params;
if (req.cpf !== cpf) {
res.status(401).send({
msg: 'nao_autorizado',
});
}
const feirante = await feiranteController.findFeiranteByCpf(cpf);
if (feirante === null) return res.json({ msg: 'cpf_nao_existente' });
return res.json({
cpf: feirante.cpf,
cnpj: feirante.cnpj,
nome: feirante.nome,
rg: feirante.rg,
usa_ee: feirante.usaEe,
nome_fantasia: feirante.nomeFantasia,
razao_social: feirante.razaoSocial,
comprimento_barraca: feirante.comprimentoBarraca,
largura_barraca: feirante.larguraBarraca,
endereco: {
logradouro: feirante.endereco.logradouro,
bairro: feirante.endereco.bairro,
numero: feirante.endereco.numero,
cep: feirante.endereco.CEP,
},
voltagem_ee: feirante.voltagemEe,
sub_categoria_id: feirante.subCategoriaId,
});
});
router.get('/:cpf', [param('cpf').custom(isCpf)], authMiddleware.isSupervisor, async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send();
const { cpf } = req.params;
const feirante = await feiranteController.findFeiranteByCpf(cpf);
if (feirante === null) return res.json({ msg: 'cpf_nao_existente' });
return res.json({
cpf: feirante.cpf,
cnpj: feirante.cnpj,
nome: feirante.nome,
rg: feirante.rg,
usa_ee: feirante.usaEe,
nome_fantasia: feirante.nomeFantasia,
razao_social: feirante.razaoSocial,
comprimento_barraca: feirante.comprimentoBarraca,
largura_barraca: feirante.larguraBarraca,
endereco: {
logradouro: feirante.endereco.logradouro,
bairro: feirante.endereco.bairro,
numero: feirante.endereco.numero,
cep: feirante.endereco.CEP,
},
voltagem_ee: feirante.voltagemEe,
sub_categoria_id: feirante.subCategoriaId,
});
});
router.put(
'/:cpf',
authMiddleware.isSupervisor,
[
param('cpf').custom(isCpf),
body('cnpj')
.optional()
.custom(isCnpj),
body('nome')
.optional()
.isString()
.isLength({ min: 1, max: 100 }),
body('rg')
.optional()
.isString()
.isLength({ min: 9, max: 9 }),
body('usa_ee')
.optional()
.isBoolean(),
body('nome_fantasia')
.optional(),
body('razao_social')
.optional(),
body('comprimento_barraca')
.optional()
.isDecimal(),
body('largura_barraca')
.optional()
.isDecimal(),
body('endereco')
.optional()
.custom(isEndereco),
body('voltagem_ee')
.optional(),
body('sub_categoria_id')
.optional()
.isInt(),
body('senha')
.optional()
.isString()
.isLength({ min: 6, max: 100 }),
],
async (req, res) => {
if (!req.body) return res.status(400).send();
const { cpf } = req.params;
const {
cnpj,
nome,
rg,
senha,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
} = req.body;
if (sub_categoria_id !== undefined) {
const subcategoria = await subCategoriaController.findSubcategoriaById(sub_categoria_id);
if (subcategoria === null) return res.json({ msg: 'subcategoria_nao_existe' });
}
const feirante = await feiranteController.findFeiranteByCpf(cpf);
if (feirante === null) return res.json({ msg: 'cpf_nao_existente' });
// Isso permite tornar os atributos opcionais (atualiza somente o que precisar)
const ret = await feiranteController.updateFeirante(cpf, {
...(cnpj !== undefined ? { cnpj } : {}),
...(nome !== undefined ? { nome } : {}),
...(rg !== undefined ? { rg } : {}),
...(senha !== undefined ? { senha } : {}),
...(usa_ee !== undefined ? { usa_ee } : {}),
...(nome_fantasia !== undefined ? { nome_fantasia } : {}),
...(razao_social !== undefined ? { razao_social } : {}),
...(comprimento_barraca !== undefined ? { comprimento_barraca } : {}),
...(largura_barraca !== undefined ? { largura_barraca } : {}),
...(endereco !== undefined ? { endereco } : {}),
...(voltagem_ee !== undefined ? { voltagem_ee } : {}),
...(sub_categoria_id !== undefined ? { sub_categoria_id } : {}),
});
if (ret === null) return res.json({ msg: 'erro' });
return res.json({ msg: 'ok' });
},
);
router.delete(
'/:cpf',
[param('cpf').custom(isCpf)],
authMiddleware.isSupervisor,
async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send();
const { cpf } = req.params;
const feirante = await feiranteController.findFeiranteByCpf(cpf);
if (feirante === null) return res.json({ msg: 'cpf_nao_existente' });
const ret = await feiranteController.deleteFeirante(cpf);
if (ret === null) return res.json({ msg: 'erro' });
return res.json({ msg: 'ok' });
},
);
// router.get('/:cpf/participacoes')
// router.post('/confirma', [body('periodo').isInt({ min: 1, max: 3 })], (req, res) => {});
module.exports = router;
<file_sep>/backend/tests/routes/categoria.js
// var chai = require('chai');
// var chaiHttp = require('chai-http');
// const app = require('../../app');
// const faker = require('faker');
// const supervisorController = require('../../controllers/supervisor');
// const feiranteController = require('../../controllers/feirante');
// const categoriaController = require('../../controllers/categoria');
// const loginController = require('../../controllers/login');
// const models = require('../../models');
// const { assert } = chai;
// chai.use(chaiHttp);
// describe('Rotas Categoria', () => {
// let tokenSupervisor;
// let feirante;
// let tokenAdmin;
// let tokenFeirante;
// let subcategoria;
// let categoria;
// before(async () => {
// const admin = await supervisorController.addSupervisor(
// '89569380080',
// faker.name.firstName(),
// '1234',
// true,
// );
// const supervisor = await supervisorController.addSupervisor(
// '56919550040',
// faker.name.firstName(),
// '1234',
// false,
// );
// categoria = await categoriaController.addCategoria('Alimento', false);
// subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
// feirante = await feiranteController.addFeirante(
// '58295846035',
// '469964807',
// faker.name.firstName(),
// '',
// '1234',
// true,
// faker.name.firstName(),
// faker.name.firstName(),
// 4,
// 4,
// {
// logradouro: faker.address.streetAddress(),
// bairro: faker.address.secondaryAddress(),
// numero: 100,
// CEP: '87.303-065',
// },
// 110,
// subcategoria.id,
// );
// tokenFeirante = (await loginController.login(feirante.cpf, '1234')).token;
// tokenAdmin = (await loginController.login(admin.cpf, '1234')).token;
// tokenSupervisor = (await loginController.login(supervisor.cpf, '1234')).token;
// });
// after(async () => {
// await models.categoria.destroy({ where: {} });
// await models.subcategoria.destroy({ where: {} });
// await models.feirante.destroy({ where: {} });
// await models.supervisor.destroy({ where: {} });
// });
// describe('POST /categoria', () => {
// it('Supervisor pode adicionar categoria', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Alimentos',
// need_cnpj: '1'
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// });
// it('Admin pode adicionar categoria', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', tokenAdmin)
// .send({
// nome: 'Artesanato',
// need_cnpj: '0'
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// });
// it('Feirante não pode adicionar categoria', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', tokenFeirante)
// .send({
// nome: 'Artesanato',
// need_cnpj: '0'
// });
// assert.strictEqual(res.statusCode, 401);
// });
// it('Sem token não pode adicionar categoria', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', 'aaaaa')
// .send({
// nome: 'Artesanato',
// need_cnpj: '0'
// });
// assert.strictEqual(res.statusCode, 401);
// });
// it('Atributos faltando', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', tokenSupervisor)
// .send({
// //nome: '',
// need_cnpj: '1'
// });
// assert.strictEqual(res.statusCode, 400);
// });
// it('Atributos incorretos', async () => {
// const res = await chai
// .request(app)
// .post('/categoria')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Alimentos',
// need_cnpj: '4'
// });
// assert.strictEqual(res.statusCode, 400);
// });
// });
// describe('GET /categoria', () => {
// it('Supervisor pode listar categorias', async () => {
// const res = await chai
// .request(app)
// .get('/categoria')
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// });
// it('Admin pode listar categorias', async () => {
// const res = await chai
// .request(app)
// .get('/categoria')
// .set('token', tokenAdmin);
// assert.strictEqual(res.statusCode, 200);
// });
// it('Feirante não pode listar categorias', async () => {
// const res = await chai
// .request(app)
// .get('/categoria')
// .set('token', tokenFeirante);
// assert.strictEqual(res.statusCode, 401);
// });
// });
// describe('GET /categoria/:id', () => {
// it('id não existe', async () => {
// const res = await chai
// .request(app)
// .get('/categoria/3')
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Retorna categoria pelo ID', async () => {
// const res = await chai
// .request(app)
// .get(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.id, categoria.id);
// });
// });
// describe('GET /categoria/:id/subcategorias', () => {
// it('id não existe', async () => {
// const res = await chai
// .request(app)
// .get('/categoria/3/subcategorias')
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Lista subcategorias com um ID existente', async () => {
// const res = await chai
// .request(app)
// .get(`/categoria/${categoria.id}/subcategorias`)
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.filter(e => e.id === subcategoria.id)[0].nome, subcategoria.nome);
// });
// });
// describe('PUT /categoria/:id', () => {
// it('Atributos faltando', async () => {
// const res = await chai
// .request(app)
// .put(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor)
// .send({
// //nome: '',
// need_cnpj: '1'
// });
// assert.strictEqual(res.statusCode, 400);
// });
// it('Atributos incorretos', async () => {
// const res = await chai
// .request(app)
// .put(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor)
// .send({
// nome: 'Alimentos',
// need_cnpj: '4'
// });
// assert.strictEqual(res.statusCode, 400);
// });
// it('ID não existe', async () => {
// const res = await chai
// .request(app)
// .put('/categoria/3')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Alimentos',
// need_cnpj: '1'
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// let novoNome = faker.name.firstName();
// it('Atualiza categoria', async () => {
// let res = await chai
// .request(app)
// .put(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor)
// .send({
// nome: novoNome,
// need_cnpj: '0'
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// res = await chai
// .request(app)
// .get(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor);
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.nome, novoNome);
// });
// });
// describe('DELETE /categoria/:id', () => {
// it('ID não existe', async () => {
// const res = await chai
// .request(app)
// .delete('/categoria/3')
// .set('token', tokenSupervisor)
// .send();
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Remove categoria', async () => {
// const res = await chai
// .request(app)
// .delete(`/categoria/${categoria.id}`)
// .set('token', tokenSupervisor)
// .send();
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// });
// });
// });<file_sep>/backend/models/celula.js
/* jshint indent: 2 */
module.exports = (sequelize, DataTypes) => {
const Celula = sequelize.define(
'celula',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
defaultValue: '0',
primaryKey: true,
},
cpf_feirante: {
type: DataTypes.STRING(15),
allowNull: true,
references: {
model: 'feirante',
key: 'cpf',
},
},
periodo: {
type: DataTypes.INTEGER(11),
allowNull: false,
},
x: {
type: 'DOUBLE',
allowNull: false,
},
y: {
type: 'DOUBLE',
allowNull: false,
},
comprimento: {
type: 'DOUBLE',
allowNull: false,
},
largura: {
type: 'DOUBLE',
allowNull: false,
},
},
{
tableName: 'celula',
timestamps: false,
createdAt: false,
},
);
Celula.associate = (models) => {
models.celula.hasMany(models.participa, {
foreignKey: 'celula_id',
sourceKey: 'id',
as: 'CelulasParticipa',
});
models.celula.belongsTo(models.feirante, {
foreignKey: 'cpf_feirante',
targetKey: 'cpf',
});
};
return Celula;
};
<file_sep>/frontend/src/screens/ConfirmacaoFeirante/index.js
import React, { PureComponent } from "react";
import { Row, Form, Steps, Modal, Button, Select, Alert } from "antd";
import moment from "moment-timezone";
import * as feiraAPI from "../../api/feira";
import classNames from "classnames";
import ContentComponent from "../../components/ContentComponent";
import * as avisoAPI from "../../api/aviso";
import * as participaAPI from "../../api/participa";
import styles from "./ConfirmacaoFeirante.module.scss";
import AvisoComponent from "../../components/AvisoComponent";
import { SVGMap } from "react-svg-map";
import Map from "../Mapeamento/Mapa";
const { Step } = Steps;
const Option = Select.Option;
class ConfirmacaoFeirante extends PureComponent {
state = {
avisos: [],
feiraAtual: {},
loading: true,
visible: false,
current: 0,
selectedPeriodo: null,
participacao: {},
customMap: {
...Map
}
};
componentDidMount() {
this.props.form.validateFields();
this._loadValues();
}
_loadValues = async () => {
try {
this.setState({ loading: true });
const avisos = await avisoAPI.getAvisosProximaFeira();
const feiraAtual = await feiraAPI.feiraAtual();
this.setState({ avisos, feiraAtual: feiraAtual });
await this._getUltimaFeira();
this.setState({ loading: false });
} catch (ex) {
console.warn(ex);
this.setState({ loading: false });
}
};
_getUltimaFeira = async () => {
const { feiraAtual } = this.state;
const participacao = await participaAPI.getParticipacaoUltimaFeira();
if (participacao.length) {
let current = 0;
const ultimaFeira = participacao[0];
if (moment(feiraAtual.data).isSame(moment(ultimaFeira.data_feira))) {
if (ultimaFeira.periodo && !ultimaFeira.celula_id) {
current = 1;
} else if (ultimaFeira.periodo && ultimaFeira.celula_id) {
current = 2;
}
}
this.setState({ participacao: participacao[0], current });
}
};
_showModal = () => {
this.setState({ visible: true });
};
_onChangePeriodo = value => {
this.setState({ selectedPeriodo: value });
};
_hideModal = () => {
this.setState({ visible: false });
};
_confirmaFeirante = () => {
const { selectedPeriodo } = this.state;
return participaAPI
.setPeriodo(selectedPeriodo)
.then(response => {
this.setState({ current: 1, selectedPeriodo: null });
})
.catch(ex => {
console.error(ex);
});
};
_renderCelulaColor = (celulaDoMapa, index) => {
const { participacao } = this.state;
if (celulaDoMapa.id !== participacao.celula_id) return "celulaMapa livre";
return "celulaMapa diaTodo";
};
_cancelaParticipacao = () => {
return participaAPI
.cancelaParticipacao()
.then(() => {
this.setState({ current: 0 });
})
.catch(ex => {
console.error(ex);
});
};
_loadCelulas = () => {
const { confirmados, customMap, selectedCelula } = this.state;
const newMap = {
...customMap,
locations: customMap.locations.map((location, index) => {
const feirantes = confirmados.feirantes
? confirmados.feirantes.filter(
feirante => feirante.celulaId === index
)
: [];
const newLocation = {
...location,
id: index,
key: index,
name: `Celula ${index}`,
feirantes
};
return newLocation;
})
};
this.setState({ customMap: newMap });
if (selectedCelula) {
this._refreshCelula();
}
};
_findCelula = id => {
const { customMap } = this.state;
return customMap.locations.find(location => location.id === id);
};
_renderCurrentStep = () => {
const { current, feiraAtual = {}, selectedPeriodo, customMap } = this.state;
function onBlur() {
console.log("blur");
}
function onFocus() {
console.log("focus");
}
if (current === 0) {
return (
<>
<h4 className={styles.alignCenter}>
Você tem até o dia{" "}
{moment(feiraAtual.data_limite).format("DD/MM/YYYY [às] HH:mm")}{" "}
para confirmar presença
</h4>
<div className={classNames([styles.alignCenter, styles.presenca])}>
<Select
style={{ width: 200 }}
placeholder="Selecione o Periodo"
optionFilterProp="children"
onChange={this._onChangePeriodo}
onFocus={onFocus}
onBlur={onBlur}
filterOption={(input, option) =>
option.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
<Option value={1}>Manhã </Option>
<Option value={2}>Tarde</Option>
<Option value={3}>Dia Todo</Option>
</Select>
<Button
type="primary"
onClick={this._confirmaFeirante}
disabled={!selectedPeriodo}
>
Confirmar Presença
</Button>
</div>
</>
);
}
if (current === 1) {
return (
<>
<h4 className={styles.alignCenter}>
Aguardando alocação e confirmação.
</h4>
<div className={classNames([styles.alignCenter, styles.presenca])}>
<Button onClick={this._cancelaParticipacao} type="danger">
Cancelar Presença
</Button>
</div>
</>
);
}
if (current === 2) {
return (
<>
<div className={classNames([styles.alignCenter, styles.presenca])}>
<SVGMap
map={customMap}
onLocationClick={this._onClick}
locationClassName={this._renderCelulaColor}
onLocationMouseOver={this.handleLocationMouseOver}
onLocationMouseOut={this.handleLocationMouseOut}
onLocationMouseMove={this.handleLocationMouseMove}
/>
<h4 className={styles.alignCenter}>
Você tem até o dia{" "}
{moment(feiraAtual.data_limite).format("DD/MM/YYYY [às] HH:mm")}{" "}
para cancelar presença
</h4>
<Button onClick={this._cancelaParticipacao} type="danger">
Cancelar Presença
</Button>
</div>
</>
);
}
};
_renderAvisos = () => {
const { avisos } = this.state;
return (
<div className={styles.avisosContainer}>
<h1>Avisos</h1>
{avisos.length ? (
<Row gutter={24}>
{avisos.map(aviso => {
return <AvisoComponent key={aviso.id} aviso={aviso} />;
})}
</Row>
) : (
<p>Sem avisos para a próxima feira</p>
)}
</div>
);
};
_renderFotoEventoFeira = () => {
const { feiraAtual } = this.state;
const feiraEventoImagem = feiraAtual.evento_image_url;
if (!feiraEventoImagem) return null;
return (
<div
className={styles.eventoImage}
onClick={this._showModal}
style={{
backgroundImage: `url(${
process.env.REACT_APP_HOST
}/image/${feiraEventoImagem})`
}}
/>
);
};
_renderSteps = () => {
const {current = 0} = this.state;
return (
<>
<Steps current={current}>
<Step title="Confirmar Presença" />
<Step title="Aguardando confirmação" />
<Step title="Presença Confirmada" />
</Steps>
{this._renderCurrentStep()}
</>
)
}
_renderAlert = () => {
const { history } = this.props;
return (
<ContentComponent>
<Alert
message="Aviso"
description={
<div>
<p>É necessário lançar o faturamento da última feira para prosseguir</p>
<Button
type="primary"
onClick={() => { history.push('../feirante/relatorio')}}
>Lançar</Button>
</div>
}
type="info"
showIcon
/>
</ContentComponent>
);
}
render() {
const { loading, feiraAtual, visible, participacao } = this.state;
if (loading) return null;
if (feiraAtual.data === undefined) {
return (
<ContentComponent>
<Alert
message="Aviso"
description="Não há feiras cadastradas para esta semana"
type="info"
showIcon
/>
</ContentComponent>
);
}
return (
<ContentComponent
loading={loading}
title={`Próxima feira: ${moment(feiraAtual.data).format("DD/MM/YYYY")}`}
limitedSize
>
{this._renderFotoEventoFeira()}
{this._renderAvisos()}
{
!participacao.faturamento && !moment(feiraAtual.data, 'yyyy-mm-dd').isSame(moment(participacao.data_feira))
? this._renderAlert()
: this._renderSteps()
}
<Modal visible={visible} onCancel={this._hideModal} footer={null} width="80%">
<img
src={`${process.env.REACT_APP_HOST}/image/${
feiraAtual.evento_image_url
}`}
alt="evento"
className={styles.imagemEvento}
/>
</Modal>
</ContentComponent>
);
}
}
const WrappedHorizontalConfirmacaoFeiranteForm = Form.create({
name: "feiras_form"
})(ConfirmacaoFeirante);
export default WrappedHorizontalConfirmacaoFeiranteForm;
<file_sep>/backend/tests/models/celula.js
const chance = require("chance").Chance();
const { assert } = require("chai");
const models = require("../../models");
after(() => {
models.sequelize.close();
});
describe.only('Testando Celula', () => {
beforeEach(() => {
models.feirante.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.celula.destroy({ where: {} });
models.participa.destroy({ where: {} });
});
it('Adiciona Celula', async () => {
let categoria = await models.categoria.create({
id: 1,
nome: "Alimentos",
need_cnpj: true
});
let subcategoria = await models.subcategoria.create({
id: 1,
nome: "Pasteis",
categoria_id: 1
});
let feirante = await models.feirante.create({
cpf: "111.555.999",
cnpj: "222.222.222-22",
usa_ee: false,
nome_fantasia: "<NAME>",
razao_social: "Tio do pastel LTDA",
comprimento_barraca: 2,
largura_barraca: 3,
voltagem_ee: null,
status: true,
sub_categoria_id: 1,
senha: "<PASSWORD>"
});
let celula = await models.celula.findOne({
where: {
id: 1,
cpf_feirante: '111.555.999',
periodo: 1
}
});
assert.isNull(celula);
celula = await models.celula.create({
id: 1,
cpf_feirante: '111.555.999',
periodo: 1
});
assert.isNotNull(celula);
assert.strictEqual(celula.cpf_feirante, '111.555.999' );
});
});
<file_sep>/frontend/src/helpers/validators.js
const CPF_BLACKLIST = [
'000.000.000-00',
'111.111.111-11',
'222.222.222-22',
'333.333.333-33',
'444.444.444-44',
'555.555.555-55',
'666.666.666-66',
'777.777.777-77',
'888.888.888-88',
'999.999.999-99',
'123.456.789-09',
];
const verifierDigitCPF = value => {
const numbers = value
.split('')
.map(number => Number(number));
const modulus = numbers.length + 1;
const multiplied = numbers.map((number, index) => number * (modulus - index));
const mod = multiplied.reduce((buffer, number) => buffer + number) % 11;
return (mod < 2 ? 0 : 11 - mod);
};
export const validateCPF = (rule, value, callback) => {
if (value && value.length === 14 && CPF_BLACKLIST.indexOf(value) === -1) {
let numbers = value.substr(0, 11);
numbers = numbers.replace(/\D+/g, '');
numbers += verifierDigitCPF(numbers);
numbers += verifierDigitCPF(numbers);
if (numbers.substr(-2) === value.substr(-2)) {
return callback();
}
}
callback('Digite um CPF válido!');
};
<file_sep>/frontend/src/api/auth.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/auth`;
export function auth(userType) {
if(!userType) return null;
return axios.post(`${host}/${userType}`, undefined, {headers: {token: localStorage.getItem('token')}});
}<file_sep>/frontend/src/api/relatorio.js
import axios from 'axios';
const feira = `${process.env.REACT_APP_HOST}/feira`;
const participa = `${process.env.REACT_APP_HOST}/participa`;
export async function getFeiras() {
const feiras = (await axios.get(
feira,
{ headers: { token: localStorage.getItem('token') } },
)).data;
return feiras;
}
export async function getFaturamentoPeriodo(data) {
const faturamento = await axios.get(`${participa}/faturamento-periodo/${data}`, {
headers: { token: localStorage.getItem('token') },
});
return faturamento.data.faturamentoPorPeriodo;
}
export async function getParticipantes(data) {
const relatorios = await axios.get(
`${participa}/data/${data}`,
{ headers: { token: localStorage.getItem('token') } },
).catch(ex => {
console.warn(ex);
return false;
});
return relatorios && !relatorios.msg ? relatorios.data : false;
}<file_sep>/backend/tests/models/feira.js
const chance = require("chance").Chance();
const { assert } = require("chai");
const models = require("../../models");
after(() => {
models.sequelize.close();
});
describe("Testando Feira", () => {
beforeEach(() => {
models.feirante.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.celula.destroy({ where: {} });
});
it("Add Feira", async () => {
let feira = await models.feira.findOne({ where: { data: "2018-12-15" } });
assert.isNull(feira);
await models.feira.create({ data: "2018-12-15" });
feira = await models.feira.findOne({ where: { data: "2018-12-15" } });
assert.isNotNull(feira);
assert.strictEqual(feira.data, "2018-12-15");
});
it("Del Feira", async () => {
await models.feira.create({ data: "2018-12-15" });
let feira = await models.feira.findOne({ where: { data: "2018-12-15" } });
assert.isNotNull(feira);
feira = await models.feira.destroy({ where: { data: "2018-12-15" } });
assert.strictEqual(feira, 1);
feira = await models.feira.findOne({ where: { data: "2018-12-15" } });
assert.isNull(feira);
});
});<file_sep>/backend/controllers/aviso.js
const models = require('../models');
const feiraController = require('../controllers/feira');
const addAviso = async (assunto, texto, data_feira) => {
try {
const feira = await feiraController.findFeira(data_feira);
if (!feira) return {};
return models.aviso.create({
assunto,
texto,
data_feira,
});
} catch (error) {
return null;
}
};
const removeAviso = async (id) => {
try {
return models.aviso.destroy({ where: { id } });
} catch (error) {
return null;
}
};
const updateAviso = async (id, assunto, texto, data_feira) => {
const feira = await feiraController.findFeira(data_feira);
const aviso = await models.aviso.findOne({
where: {
id,
},
});
if (!feira || !aviso) return null;
try {
return await aviso.update({
assunto,
texto,
data_feira,
});
} catch (error) {
return null;
}
};
const getAvisos = async () => {
const avisos = await models.aviso.findAll({
where: {},
});
return avisos || [];
};
const getAvisosProximaFeira = async () => {
const feiraAtual = await feiraController.findFeiraAtual();
if (!feiraAtual) return [];
const avisos = await models.aviso.findAll({
where: {
data_feira: feiraAtual.data,
},
});
return avisos || [];
};
const getById = async (id) => {
try {
const aviso = await models.aviso.findOne({
where: {
id,
},
});
return aviso;
} catch (error) {
return null;
}
};
module.exports = {
addAviso,
removeAviso,
updateAviso,
getAvisosProximaFeira,
getAvisos,
getById,
};
<file_sep>/backend/tests/routes/supervisor.js
// var chai = require('chai');
// var chaiHttp = require('chai-http');
// const app = require('../../app');
// chai.use(chaiHttp);
// describe('Teste route supervisor', () => {
// it('Teste GET supervisor', () => {
// chai.request(app).get('/supervisor').end((err, res) => {
// chai.expect(res).to.have.status(200);
// });
// });
// it('Teste POST supervisor', () => {
// var send = {
// cpf: "07564266982",
// senha: 'senha123',
// };
// chai.request(app).post(send).then( (res) => {
// chai.expect(res).to.have.status(200);
// chai.expect(req).to.be.json;
// });
// });
// });
<file_sep>/backend/tests/controllers/feira.js
const { assert } = require('chai');
const models = require('../../models');
const feiraController = require('../../controllers/feira');
const { proximaSexta } = require('../../controllers/utils');
const amanha = () => {
const tmp = new Date();
tmp.setDate(tmp.getDate() + 1);
return tmp;
};
describe('feira.js', () => {
beforeEach(async () => {
await models.participa.destroy({ where: {} });
await models.feira.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
});
after(() => {
models.celula.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.participa.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.feirante.destroy({ where: {} });
});
describe('findFeira', () => {
it('Retorna null se feira não existe', async () => {
const feira = await feiraController.findFeira(amanha());
assert.isNull(feira);
});
it('Retorna feira', async () => {
const feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
const feiraTmp = await feiraController.findFeira(new Date(feira.data));
assert.isNotNull(feiraTmp);
assert.strictEqual(feiraTmp.data, feira.data);
});
});
describe('findFeiraAtual', () => {
it('Retorna null se não existe feira na semana', async () => {
const feira = await feiraController.addFeira(new Date('01-01-2020'));
assert.isNotNull(feira);
const feiraAtual = await feiraController.findFeiraAtual();
assert.isNull(feiraAtual);
});
it('Retorna feira da semana', async () => {
const feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
const feiraAtual = await feiraController.findFeiraAtual();
assert.isNotNull(feiraAtual);
assert.strictEqual(feira.data, feiraAtual.data);
assert.strictEqual(feiraAtual.data_limite.toISOString(), proximaSexta().toISOString());
});
});
describe('setDataLimiteFeiraAtual', () => {
it('Retorna null se não existe feira na semana', async () => {
const feira = await feiraController.addFeira(new Date('01-01-2020'));
assert.isNotNull(feira);
const feiraAtual = await feiraController.findFeiraAtual();
assert.isNull(feiraAtual);
});
it('Não deixa setar data anterior a atual', async () => {
const feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
const cincoMinutosAtras = new Date();
cincoMinutosAtras.setMinutes(cincoMinutosAtras.getMinutes() - 5);
const atualizado = await feiraController.setDataLimiteFeiraAtual(cincoMinutosAtras);
assert.isNull(atualizado);
});
it('Atualiza data_limite', async () => {
const feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
const cincoMinutosDepois = new Date();
cincoMinutosDepois.setMinutes(cincoMinutosDepois.getMinutes() + 5);
const atualizado = await feiraController.setDataLimiteFeiraAtual(cincoMinutosDepois);
assert.isNotNull(atualizado);
});
});
describe('addFeira', () => {
it('Adiciona feira', async () => {
const feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
// console.log('data_limite: ', feira.data_limite);
});
it('Não adiciona feira repetida', async () => {
let feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
feira = await feiraController.addFeira(amanha());
assert.isNull(feira);
});
it('Não adiciona feira em data anterior a atual', async () => {
const ontem = new Date();
ontem.setDate(ontem.getDate() - 1);
const feira = await feiraController.addFeira(ontem);
assert.isNull(feira);
});
});
describe('cancelaFeiraAtual', () => {
it('Retorna null se não existe feira na semana', async () => {
const feira = await feiraController.cancelaFeiraAtual();
assert.isNull(feira);
});
it('Cancela feira da semana', async () => {
let feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
feira = await feiraController.cancelaFeiraAtual();
assert.isNotNull(feira);
feira = await feiraController.findFeiraAtual();
assert.isNull(feira);
});
it('Não cancela feira se ja foi cancelada', async () => {
let feira = await feiraController.addFeira(amanha());
assert.isNotNull(feira);
feira = await feiraController.cancelaFeiraAtual();
assert.isNotNull(feira);
feira = await feiraController.cancelaFeiraAtual();
assert.isNull(feira);
});
});
});
<file_sep>/frontend/src/components/ContentComponent.js
import React, { PureComponent, Fragment } from 'react';
import { Layout, Button, Spin } from 'antd';
import styles from './ContentComponent.module.scss';
const { Content } = Layout;
export default class ContentComponent extends PureComponent {
state = {};
_renderHeaderButton = () => {
const { buttonProps } = this.props;
return (
<Button {...buttonProps}>
{buttonProps.text}
</Button>
)
}
_renderContent = () => {
const { buttonProps, title, children} = this.props;
return (
<Fragment>
<div className={styles.header}>
<h1>{title}</h1>
{
buttonProps
? (
this._renderHeaderButton()
) : null
}
</div>
<div className={styles.divider} />
{children}
</Fragment>
)
}
render() {
const { loading, limitedSize } = this.props;
return (
<Content className={limitedSize ? styles.containerMaxWidth : styles.container}>
{
loading
? (
<Spin tip="Carregando...">
{this._renderContent()}
</Spin>
)
: (
<Fragment>
{this._renderContent()}
</Fragment>
)
}
</Content>
);
}
}
<file_sep>/docs/api/login.md
# Login
## `POST /login` - Realiza login feirante/supervisor
- Body
```json
{
"cpf": "11111111111",
"senha": "<PASSWORD>"
}
```
- Resposta _#1_ - **Code 200** - Credenciais corretas
```javascript
{
"token": "<KEY>",
"tag": "feirante" // feirante|supervisor|administrador
}
```
- Resposta _#2_ - **Code 400** - Atributos incorretos
- Resposta _#3_ - **Code 401** - Credenciais incorretas
<file_sep>/backend/controllers/supervisor.js
const bcrypt = require('bcrypt');
const models = require('../models');
const addSupervisor = async (cpf, nome, senha, isAdm, rootAdm = false) => {
const supervisor = await models.supervisor.findOne({
where: { cpf },
});
const hashSenha = await bcrypt.hash(senha, 10);
if (supervisor !== null && !supervisor.status) {
const ret = await supervisor.update({
cpf,
nome,
senha: <PASSWORD>,
is_adm: isAdm,
status: true,
});
return ret;
}
if (supervisor === null) {
try {
const ret = await models.supervisor.create({
cpf,
nome,
senha: <PASSWORD>,
is_adm: isAdm,
root_adm: rootAdm,
status: true,
});
return ret;
} catch (error) {
return null;
}
}
return null;
};
const listSupervisor = async () => {
const supervisores = await models.supervisor.findAll({
where: {
status: true,
},
});
return supervisores.map(el => ({
cpf: el.cpf,
nome: el.nome,
is_adm: el.is_adm,
root_adm: el.root_adm,
}));
};
const findSupervisorByCpf = async (cpf) => {
const supervisor = await models.supervisor.findOne({
where: {
cpf,
status: true,
},
});
if (supervisor === null) return null;
return {
cpf: supervisor.cpf,
nome: supervisor.nome,
is_adm: supervisor.is_adm,
};
};
const updateSupervisor = async (cpf, dados) => {
const supervisor = await models.supervisor.findOne({
where: { cpf, status: true },
});
if (supervisor === null) return null;
if ('status' in dados) return null;
if ('root_adm' in dados) return null;
if (supervisor.root_adm && 'is_adm' in dados) return null;
const { ...obj } = dados;
if ('senha' in obj) {
obj.senha = await bcrypt.hash(obj.senha, 10);
}
try {
return await supervisor.update(obj);
} catch (error) {
return null;
}
};
const deleteSupervisor = async (cpf) => {
const supervisor = await models.supervisor.findOne({
where: { cpf, status: true },
});
if (supervisor === null || supervisor.root_adm) return null;
const ret = await supervisor.update({ status: false });
return ret;
};
module.exports = {
addSupervisor,
listSupervisor,
findSupervisorByCpf,
updateSupervisor,
deleteSupervisor,
};
<file_sep>/backend/tests/models/participa.js
const chance = require('chance').Chance();
const { assert } = require('chai');
const models = require('../../models');
after(() => {
models.sequelize.close();
});
describe('Testando participa', () => {
before(() => {
models.feirante.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.celula.destroy({ where: {} });
models.participa.destroy({ where: {} });
});
it.only('Adiciona feirante na feira', async () => {
const feira = await models.feira.create({ data: '2018-09-28' });
const categoria = await models.categoria.create({
id: 1,
nome: 'Categoria 1',
need_cnpj: false,
});
const subCategoria = await categoria.createSubCategoria({ nome: 'SubCategoria 1' });
const feirante = await models.feirante.create({
cpf: '1',
usa_ee: false,
senha: '<PASSWORD>',
nome_fantasia: chance.name(),
razao_social: chance.name(),
comprimento_barraca: 4,
largura_barraca: 4,
sub_categoria_id: subCategoria.id,
});
// assert.lengthOf(await feira.getFeirantes(), 0);
// await feira.addFeirante(feirante);
// assert.lengthOf(await feira.getFeirantes(), 1);
});
it('Não deixa adicionar feirante repetido na feira', async () => {
await models.feirante
.create({
cpf: '1',
usa_ee: false,
nome_ficticio: chance.name(),
razao_social: chance.name(),
comprimento_barraca: 4,
largura_barraca: 4,
sub_categoria_id: 0,
})
.catch(async (err) => {
const feira = await models.feira.findOne({ where: { data: '2018-09-28' } });
const feirantes = await feira.getFeirantes();
assert.lengthOf(feirantes, 1);
});
});
it('Atualiza o faturamento', async () => {
const feirante = await models.feirante.findOne({ where: { cpf: '1' } });
assert.isNotNull(feirante);
let participacoes = await feirante.getFeiras();
assert.lengthOf(participacoes, 1);
assert.strictEqual(participacoes[0].participa.faturamento, 0);
await participacoes[0].participa.update({ faturamento: 5000 });
participacoes = await feirante.getFeiras();
assert.strictEqual(participacoes[0].participa.faturamento, 5000);
});
it('Define uma celula para um feirante na feira', async () => {
const celula = await models.celula.create({ id: 1, periodo: 1 });
let participa = await models.participa.findOne({
where: { cpf_feirante: '1', data_feira: '2018-09-28' },
});
assert.isNotNull(participa);
assert.isUndefined(participa.celula);
await participa.setCelula(celula);
participa = await models.participa.findOne({
where: { cpf_feirante: '1', data_feira: '2018-09-28' },
});
assert.isNotNull(participa);
assert.strictEqual(participa.celula_id, 1);
});
});
<file_sep>/backend/tests/routes/participa.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const faker = require('faker');
const sinon = require('sinon');
const supervisorController = require('../../controllers/supervisor');
const categoriaController = require('../../controllers/categoria');
const feiranteController = require('../../controllers/feirante');
const feiraController = require('../../controllers/feira');
const celulaController = require('../../controllers/celula');
const loginController = require('../../controllers/login');
const participaController = require('../../controllers/participa');
const app = require('../../app');
const models = require('../../models');
const { proximaSexta } = require('../../controllers/utils');
const { assert } = chai;
chai.use(chaiHttp);
const host = '/api/participa/';
describe('participa.js', () => {
let tokenFeirante;
let feirante;
let feirante2;
let tokenSupervisor;
before(async () => {
const supervisor = await supervisorController.addSupervisor(
'89569380080',
faker.name.firstName(),
'1234',
true,
);
const categoria = await categoriaController.addCategoria('Alimento', false);
const subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
'1234',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirante2 = await feiranteController.addFeirante(
'81176013033',
'469964807',
faker.name.firstName(),
'',
'1234',
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
tokenFeirante = (await loginController.login(feirante.cpf, '1234')).token;
tokenSupervisor = (await loginController.login(supervisor.cpf, '1234')).token;
});
after(async () => {
await models.feira.destroy({ where: {} });
await models.celula.destroy({ where: {} });
await models.participa.destroy({ where: {} });
await models.categoria.destroy({ where: {} });
await models.subcategoria.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
await models.supervisor.destroy({ where: {} });
// await models.sequelize.close();
});
afterEach(async () => {
await models.feira.destroy({ where: {} });
await models.celula.destroy({ where: {} });
await models.participa.destroy({ where: {} });
// await models.sequelize.close();
});
describe('GET /participa/confirmados', () => {
it('Retorna "feira_invalida" se não existe feira atual', async () => {
const res = await chai
.request(app)
.get(`${host}confirmados`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feira_invalida');
});
it('Retorna array vazio se não existem feirantes confirmados', async () => {
await feiraController.addFeira(proximaSexta());
const res = await chai
.request(app)
.get(`${host}confirmados`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.lengthOf(res.body, 0);
});
it('Retorna feirantes confirmados', async () => {
await feiraController.addFeira(proximaSexta());
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const res = await chai
.request(app)
.get(`${host}confirmados`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 200);
assert.lengthOf(res.body, 1);
assert.strictEqual(res.body[0].feirante.cpf, feirante.cpf);
});
it('Somente supervisor pode listar feirantes confirmados', async () => {
await feiraController.addFeira(proximaSexta());
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const res = await chai
.request(app)
.get(`${host}confirmados`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 401);
});
});
describe('POST /participa/confirma', () => {
it('Retorna "feira_invalida" se não existe feira atual', async () => {
const res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feira_invalida');
});
it('Retorna erro 400 se passar periodo inválido/não passar', async () => {
await feiraController.addFeira(proximaSexta());
let res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 5 });
assert.strictEqual(res.statusCode, 400);
res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodoo: 2 });
assert.strictEqual(res.statusCode, 400);
});
it('Retorna "confirmacao_fechada" se fechou o periodo de confirmação', async () => {
const data = proximaSexta();
await feiraController.addFeira(data);
data.setDate(data.getDate() + 1);
const clock = sinon.useFakeTimers(data);
const res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'confirmacao_fechada');
clock.restore();
});
it('Retorna "periodo_invalido" se período não condiz com o da celula reservada', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 2,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await celulaController.updateCelula(1, { cpf_feirante: feirante.cpf });
const res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'periodo_invalido');
});
it('Retorna "ok" se confirmar presença', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 2,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await celulaController.updateCelula(1, { cpf_feirante: feirante.cpf });
const res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 2 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
it('Retorna "ja_confirmado" se feirante já confirmou', async () => {
await feiraController.addFeira(proximaSexta());
let res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenFeirante)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ja_confirmado');
});
it('Somente feirante pode confirmar presença', async () => {
await feiraController.addFeira(proximaSexta());
const res = await chai
.request(app)
.post(`${host}confirma`)
.set('token', tokenSupervisor)
.send({ periodo: 1 });
assert.strictEqual(res.statusCode, 401);
});
});
describe('POST /participa/cancela', () => {
it('Retorna "feira_invalida" se não existe feira atual', async () => {
const res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feira_invalida');
});
it('Retorna "cancelamento_fechado" se fechou o periodo de cancelamento', async () => {
const data = proximaSexta();
await feiraController.addFeira(data);
data.setDate(data.getDate() + 1);
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const clock = sinon.useFakeTimers(data);
const res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'cancelamento_fechado');
clock.restore();
});
it('Retorna "nao_confirmado" se não está confirmado', async () => {
await feiraController.addFeira(proximaSexta());
// await participaController.confirmaPresencaFeiraAtual(feirante.cpf);
const res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'nao_confirmado');
});
it('Retorna "nao_confirmado" se feirante já cancelou', async () => {
await feiraController.addFeira(proximaSexta());
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
let res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'nao_confirmado');
});
it('Retorna "ok" se cancelou', async () => {
await feiraController.addFeira(proximaSexta());
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenFeirante);
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
});
it('Somente feirante pode cancelar presença', async () => {
await feiraController.addFeira(proximaSexta());
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const res = await chai
.request(app)
.post(`${host}cancela`)
.set('token', tokenSupervisor);
assert.strictEqual(res.statusCode, 401);
});
});
describe('POST /participa/posicao', () => {
it('Retorna "feira_invalida" se não existe feira atual', async () => {
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 1, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feira_invalida');
});
it('Retorna "feirante_invalido" se feirante não existe/não está confirmado', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
let res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 1, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feirante_invalido');
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: '61799227057', celula_id: 1, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'feirante_invalido');
});
it('Retorna "celula_invalida" se celula não existe', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 2, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'celula_invalida');
});
it('Retorna "periodo_invalido" se período não condiz com o da celula', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 2);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 1, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'periodo_invalido');
});
it('Retorna "ok" se limpar posição feirante', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
const ret = await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
assert.isNotNull(ret);
let dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
// assert.isNotNull(dadosCelula.cpfFeirante);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: null, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
assert.isNull(dadosCelula.cpfFeirante);
});
it('Retorna "ok" se atualizar posicao (celula livre)', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await models.celula.create({
id: 2,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
const ret = await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
assert.isNotNull(ret);
let dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 2, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
assert.isNull(dadosCelula.cpfFeirante);
dadosCelula = await participaController.getDadosCelulaFeiraAtual(2);
assert.isNotNull(dadosCelula.cpfFeirante);
assert.strictEqual(dadosCelula.cpfFeirante, feirante.cpf);
});
it('Retorna "celula_ocupada" se celula estiver ocupada', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await models.celula.create({
id: 2,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
await participaController.confirmaPresencaFeiraAtual(feirante2.cpf, 1);
await participaController.setPosicaoFeiranteFeiraAtual(feirante.cpf, 1, false);
await participaController.setPosicaoFeiranteFeiraAtual(feirante2.cpf, 2, false);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 2, force: false });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'celula_ocupada');
let dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
assert.isNotNull(dadosCelula.cpfFeirante);
assert.strictEqual(dadosCelula.cpfFeirante, feirante.cpf);
dadosCelula = await participaController.getDadosCelulaFeiraAtual(2);
assert.isNotNull(dadosCelula.cpfFeirante);
assert.strictEqual(dadosCelula.cpfFeirante, feirante2.cpf);
});
it('Retorna "ok" se atualizar posicao com force=true (celula ocupada)', async () => {
await feiraController.addFeira(proximaSexta());
await models.celula.create({
id: 1,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await models.celula.create({
id: 2,
periodo: 1,
x: 0,
y: 0,
comprimento: 0,
largura: 0,
});
await participaController.confirmaPresencaFeiraAtual(feirante.cpf, 1);
await participaController.confirmaPresencaFeiraAtual(feirante2.cpf, 2);
await participaController.setPosicaoFeiranteFeiraAtual(feirante.cpf, 1, false);
await participaController.setPosicaoFeiranteFeiraAtual(feirante2.cpf, 2, false);
const res = await chai
.request(app)
.post(`${host}posicao`)
.set('token', tokenSupervisor)
.send({ cpf_feirante: feirante.cpf, celula_id: 2, force: true });
assert.strictEqual(res.statusCode, 200);
assert.strictEqual(res.body.msg, 'ok');
let dadosCelula = await participaController.getDadosCelulaFeiraAtual(1);
assert.isNull(dadosCelula.cpfFeirante);
dadosCelula = await participaController.getDadosCelulaFeiraAtual(2);
assert.isNotNull(dadosCelula.cpfFeirante);
assert.strictEqual(dadosCelula.cpfFeirante, feirante.cpf);
});
});
});
<file_sep>/backend/routes/aviso.js
const router = require('express').Router();
const authMiddleware = require('../middlewares/auth');
const avisoController = require('../controllers/aviso');
router.get('/', async (req, res) => {
const aviso = await avisoController.getAvisos();
res.status(200).send(aviso);
});
router.get('/proxima', async (req, res) => {
const aviso = await avisoController.getAvisosProximaFeira();
res.status(200).send(aviso);
});
router.post('/', authMiddleware.isSupervisor, async (req, res) => {
const { assunto, texto, data_feira } = req.body;
const add = await avisoController.addAviso(assunto, texto, data_feira);
if (add !== null) {
res.status(200).send({
msg: 'ok',
});
} else {
res.status(400).send({
msg: 'erro',
});
}
});
router.put('/:id', authMiddleware.isSupervisor, async (req, res) => {
const { id } = req.params;
const { assunto, texto, data_feira } = req.body;
const update = await avisoController.updateAviso(id, assunto, texto, data_feira);
if (update !== null) {
res.status(200).send({
msg: 'ok',
});
} else {
res.status(400).send({
msg: 'erro',
});
}
});
router.get('/:id', authMiddleware.isSupervisor, async (req, res) => {
const { id } = req.params;
const byId = await avisoController.getById(id);
if (byId !== null) {
res.status(200).send(byId);
} else {
res.status(400).send({
msg: 'erro',
});
}
});
router.delete('/:id', authMiddleware.isSupervisor, async (req, res) => {
const { id } = req.params;
const remove = await avisoController.removeAviso(id);
if (remove !== null) {
res.status(200).send({
msg: 'ok',
});
} else {
res.status(400).send({
msg: 'erro',
});
}
});
module.exports = router;
<file_sep>/backend/tests/routes/subcategoria.js
// var chai = require('chai');
// var chaiHttp = require('chai-http');
// const app = require('../../app');
// const faker = require('faker');
// const supervisorController = require('../../controllers/supervisor');
// const feiranteController = require('../../controllers/feirante');
// const categoriaController = require('../../controllers/categoria');
// const subCategoriaController = require('../../controllers/subcategoria');
// const loginController = require('../../controllers/login');
// const models = require('../../models');
// const { assert } = chai;
// chai.use(chaiHttp);
// describe('Rotas Subcategoria', () => {
// let tokenSupervisor;
// let feirante;
// let tokenAdmin;
// let tokenFeirante;
// let subcategoria;
// let categoria;
// before(async () => {
// const admin = await supervisorController.addSupervisor(
// '89569380080',
// faker.name.firstName(),
// '1234',
// true,
// );
// const supervisor = await supervisorController.addSupervisor(
// '56919550040',
// faker.name.firstName(),
// '1234',
// false,
// );
// categoria = await categoriaController.addCategoria('Alimento', false);
// subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
// feirante = await feiranteController.addFeirante(
// '58295846035',
// '469964807',
// faker.name.firstName(),
// '',
// '1234',
// true,
// faker.name.firstName(),
// faker.name.firstName(),
// 4,
// 4,
// {
// logradouro: faker.address.streetAddress(),
// bairro: faker.address.secondaryAddress(),
// numero: 100,
// CEP: '87.303-065',
// },
// 110,
// subcategoria.id,
// );
// tokenFeirante = (await loginController.login(feirante.cpf, '1234')).token;
// tokenAdmin = (await loginController.login(admin.cpf, '1234')).token;
// tokenSupervisor = (await loginController.login(supervisor.cpf, '1234')).token;
// });
// after(async () => {
// await models.categoria.destroy({ where: {} });
// await models.subcategoria.destroy({ where: {} });
// await models.feirante.destroy({ where: {} });
// await models.supervisor.destroy({ where: {} });
// });
// describe('POST /subcategoria', () => {
// it('Supervisor pode adicionar subcategoria', async () => {
// const res = await chai
// .request(app)
// .post('/subcategoria')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Salgados',
// categoria_id: `${categoria.id}`,
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// });
// it('Admin pode adicionar subcategoria', async () => {
// const res = await chai
// .request(app)
// .post('/subcategoria')
// .set('token', tokenAdmin)
// .send({
// nome: 'Salgados',
// categoria_id: `${categoria.id}`,
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// });
// it('Feirante não pode adicionar subcategoria', async () => {
// const res = await chai
// .request(app)
// .post('/subcategoria')
// .set('token', tokenFeirante)
// .send({
// nome: 'Salgados',
// categoria_id: `${categoria.id}`,
// });
// assert.strictEqual(res.statusCode, 401);
// });
// it('Atributos faltando', async () => {
// const res = await chai
// .request(app)
// .post('/subcategoria')
// .set('token', tokenSupervisor)
// .send({
// //nome: 'Salgados',
// categoria_id: `${categoria.id}`,
// });
// assert.strictEqual(res.statusCode, 400);
// });
// it('Categoria nao existe', async () => {
// const res = await chai
// .request(app)
// .post('/subcategoria')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Salgados',
// categoria_id: `5`,
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'categoria_nao_existente');
// });
// });
// describe('GET /subcategoria/:id', () => {
// it('ID nao existe', async () => {
// const res = await chai
// .request(app)
// .get('/subcategoria/4')
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Retorna informações pelo ID', async () => {
// const res = await chai
// .request(app)
// .get(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.id, subcategoria.id);
// });
// });
// describe('PUT /subcategoria/:id', () => {
// it('Atributos faltando', async () => {
// const res = await chai
// .request(app)
// .put(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// .send({
// //nome: 'Salgados',
// });
// assert.strictEqual(res.statusCode, 400);
// });
// it('ID não existe', async () => {
// const res = await chai
// .request(app)
// .put('/subcategoria/1')
// .set('token', tokenSupervisor)
// .send({
// nome: 'Salgados',
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Atualiza subcategoria', async () => {
// let novoNome = faker.name.firstName();
// let res = await chai
// .request(app)
// .put(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// .send({
// nome: novoNome,
// });
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// res = await chai
// .request(app)
// .get(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.nome, novoNome);
// });
// });
// describe('DELETE /subcategoria/:id', () => {
// it('ID não existe', async () => {
// const res = await chai
// .request(app)
// .delete('/subcategoria/1')
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// it('Deleta subcategoria', async () => {
// let res = await chai
// .request(app)
// .delete(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'ok');
// res = await chai
// .request(app)
// .get(`/subcategoria/${subcategoria.id}`)
// .set('token', tokenSupervisor)
// assert.strictEqual(res.statusCode, 200);
// assert.strictEqual(res.body.msg, 'id_nao_existente');
// });
// });
// });
<file_sep>/frontend/src/screens/Categorias/UpdateSubcategoria.js
import React, { PureComponent } from 'react';
import {
Button, Form,
Input, message,
} from 'antd';
import * as subcategoriasAPI from '../../api/subcategoria';
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class UpdateSubcategoria extends PureComponent {
state = {
editingSubcategoria: {},
};
componentDidMount() {
this._loadValues();
}
_loadValues = async () => {
const { form: { setFieldsValue }, subcategoria } = this.props;
return setFieldsValue({
nome: subcategoria.nome,
});
}
_updateSubcategoriaSubmit = event => {
const {
form: { resetFields }, subcategoria, refresh,
onCancel,
} = this.props;
event.preventDefault();
this.props.form.validateFields(async (err, values) => {
if (!err) {
message.loading('Carregando...', 0);
return subcategoriasAPI.put(values.nome, subcategoria.id)
.then(() => {
resetFields(['nome']);
this.setState({ subcategoria: {} });
onCancel();
refresh();
message.loading('Subcategoria atualizada com sucesso', 2.5);
}).catch(() => {
message.error('Não foi possível atualizar esta subcategoria,tente novamente mais tarde', 2.5);
});
}
});
}
render() {
const { form } = this.props;
const {
getFieldError, getFieldDecorator,
isFieldTouched, getFieldsError,
getFieldValue,
} = form;
const nomeError = isFieldTouched('nome') && getFieldError('nome');
return (
<Form onSubmit={this._updateSubcategoriaSubmit}>
<Form.Item
validateStatus={nomeError ? 'error' : ''}
help={nomeError || ''}
>
{getFieldDecorator('nome', {
rules: [{
required: true,
message: 'O nome da subcategoria é obrigatório!'
}]
})(
<Input
placeholder="Nome"
/>
)}
</Form.Item>
<Form.Item>
<Button
type="primary"
htmlType="submit"
block
disabled={
hasErrors(getFieldsError())
|| !getFieldValue('nome')
}
>
Atualizar
</Button>
</Form.Item>
</Form>
);
}
}
const WrappedHorizontalUpdateSubcategoriasForm = Form.create({ name: 'subcategorias_form' })(UpdateSubcategoria);
export default WrappedHorizontalUpdateSubcategoriasForm;<file_sep>/frontend/src/api/feirante.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/feirante`;
export async function get() {
const data = await axios
.get(host, { headers: { token: localStorage.getItem('token') } })
.catch(() => null)
.then(record => record.data);
return data.map(record => ({
...record,
cpf: record.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4'),
cnpj: record.cnpj ? record.cnpj.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g, '$1.$2.$3/$4-$5') : null,
rg: record.rg ? record.rg.replace(/(\d{2})(\d{3})(\d{3})(\d{1})/g, '$1.$2.$3-$4') : null,
}));
}
export async function getByCpf(cpf) {
const record = (await axios.get(`${host}/${cpf}`, {
headers: { token: localStorage.getItem('token') },
})).data;
return { ...record,
cpf: record.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4'),
cnpj: record.cnpj ? record.cnpj.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g, '$1.$2.$3/$4-$5') : null,
rg: record.rg ? record.rg.replace(/(\d{2})(\d{3})(\d{3})(\d{1})/g, '$1.$2.$3-$4') : null,
cep: record.endereco.cep.replace(/(\d{5})(\d{3})/g, '$1-$2')};
}
export async function getProfile(cpf) {
const record = (await axios.get(`${host}/profile/${cpf}`, {
headers: { token: localStorage.getItem('token') },
})).data;
return { ...record,
cpf: record.cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4'),
cnpj: record.cnpj ? record.cnpj.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g, '$1.$2.$3/$4-$5') : null,
rg: record.rg ? record.rg.replace(/(\d{2})(\d{3})(\d{3})(\d{1})/g, '$1.$2.$3-$4') : null,
cep: record.endereco.cep.replace(/(\d{5})(\d{3})/g, '$1-$2')};
}
export async function post(
cpf,
cnpj,
nome,
rg,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
senha,
) {
await axios.post(
host, {
cpf: cpf.replace(/\D/g, ''),
cnpj: cnpj.replace(/\D/g, ''),
nome,
rg: rg.replace(/\D/g, ''),
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
senha,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export async function put(
cpf,
cnpj,
nome,
rg,
usa_ee,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
) {
console.log(cpf.replace(/\D/g, ''));
await axios.put(`${host}/${cpf.replace(/\D/g, '')}`, {
cnpj,
nome,
rg,
usa_ee: usa_ee ? 1 : 0,
nome_fantasia,
razao_social,
comprimento_barraca,
largura_barraca,
endereco,
voltagem_ee,
sub_categoria_id,
}, { headers: { token: localStorage.getItem('token') } });
}
export async function del(cpf) {
axios.delete(`${host}/${cpf}`, { headers: { token: localStorage.getItem('token') } });
}
<file_sep>/backend/routes/login.js
const { body, validationResult } = require('express-validator/check');
const express = require('express');
// const bcrypt = require('bcrypt');
const { isCpf } = require('./utils');
const loginController = require('../controllers/login');
const router = express.Router();
router.post(
'/',
[
body('cpf').custom(isCpf),
body('senha')
.isString()
.isLength({ min: 6, max: 100 }),
],
async (req, res) => {
if (!validationResult(req).isEmpty()) return res.status(400).send();
const { cpf, senha } = req.body;
const info = await loginController.login(cpf, senha);
if (info !== null) {
return res.json({ userID: cpf, token: info.token, tag: info.tag });
}
return res.status(401).send();
},
);
module.exports = router;
<file_sep>/backend/routes/date.js
const router = require('express').Router();
router.get('/', async(req, res)=>{
dataServer = new Date();
let c = 5;
res.status(200).json({
serverData: dataServer
});
});
module.exports = router;<file_sep>/backend/routes/supervisor.js
const router = require('express').Router();
const CPF = require('cpf-check');
const authMiddleware = require('../middlewares/auth');
const supervisorController = require('../controllers/supervisor');
// get supervisores
router.get('/', authMiddleware.isAdmin, async (req, res) => {
const supervisores = await supervisorController.listSupervisor();
res.status(200).send(supervisores);
});
// get supervisor
// authMiddleware.isAdmin,
router.get('/:cpf', authMiddleware.isAdmin, async (req, res) => {
const cpfS = req.params.cpf;
const cpfValido = CPF.validate(CPF.strip(cpfS));
if (cpfValido.code === 'INVALID' || cpfValido.code === 'LENGTH') {
// validação cpf
res.status(400).send();
}
const supervisor = await supervisorController.findSupervisorByCpf(cpfS);
if (supervisor != null) {
res.status(200).send(supervisor);
} else {
res.status(400).send({
msg: 'cpf_nao_existe',
});
}
});
// post cadastro supervisor
router.post('/', authMiddleware.isAdmin, async (req, res) => {
const cpfS = req.body.cpf;
const nomeS = req.body.nome;
const senhaS = req.body.senha;
const isAdm = req.body.is_adm;
// console.log(req.body);
const cpfValido = CPF.validate(CPF.strip(cpfS));
if (cpfValido.code === 'INVALID' || cpfValido.code === 'LENGTH' || senhaS.lenght < 6) {
// validação cpf e tamanho da senha
res.status(400);
} else {
// retorna null se cpf não existir
const cpfExist = await supervisorController.findSupervisorByCpf(CPF.strip(cpfS));
if (cpfExist == null) {
// cpf não consta na base de dados, pode ser cadastrado
const cadastro = await supervisorController.addSupervisor(
CPF.strip(cpfS),
nomeS,
senhaS,
isAdm,
);
if (cadastro != null) {
res.status(200).send({
msg: 'ok',
});
}
} else {
res.status(400).send({
msg: 'cpf_existente',
});
}
}
});
// put update supervisor
router.put('/:cpf', authMiddleware.isAdmin, async (req, res) => {
const { nome, senha } = req.body;
const isAdm = req.body.is_adm;
const cpfS = req.params.cpf;
const cpfValido = CPF.validate(CPF.strip(cpfS));
if (cpfValido.code === 'INVALID' || cpfValido.code === 'LENGTH') {
// validação cpf
res.status(400);
}
const supervisorValidate = await supervisorController.findSupervisorByCpf(cpfS);
if (supervisorValidate != null) {
// supervisor encontrado
// const status = true; // WTF?
// const supervisor =
// await supervisorController.updateSupervisor(cpfS, { status, nome, senha });
const supervisor = await supervisorController.updateSupervisor(cpfS, {
...(nome !== undefined ? { nome } : {}),
...(senha !== undefined ? { senha } : {}),
...(isAdm !== undefined ? { is_adm: isAdm } : {}),
});
if (supervisor != null) {
res.status(200).send({
msg: 'ok',
});
}
} else {
// supervisor nao encotrado
res.status(400).send({
msg: 'cpf_nao_existente',
});
}
});
// delete remove supervisor
router.delete('/:cpf', authMiddleware.isAdmin, async (req, res) => {
const cpfS = req.params.cpf;
const cpfValido = CPF.validate(cpfS);
if (cpfValido.code === 'INVALID' || cpfValido.code === 'LENGTH') {
// validação cpf
return res.status(400);
}
const supervisorValidate = await supervisorController.findSupervisorByCpf(cpfS);
if (supervisorValidate !== null) {
// // Possível problema no futuro: E se o ultimo administrador for excluido?
// const admins = (await supervisorController.listSupervisor()).filter(
// supervisor => supervisor.is_adm,
// );
// if (admins.length <= 1) {
// return res.send({
// msg: 'ultimo_admin',
// });
// }
if (supervisorValidate.root_adm) {
return res.json({
msg: 'admin_root',
});
}
// supervisor encontrado
const supervisor = await supervisorController.deleteSupervisor(cpfS);
if (supervisor != null) {
// supervisor "removido"
return res.status(200).send({
msg: 'ok',
});
}
}
// supervisor nao encontrado
return res.status(400).send({
msg: 'cpf_nao_existente',
});
});
module.exports = router;
<file_sep>/backend/database/script.sql
DROP DATABASE IF EXISTS feira_municipal;
CREATE DATABASE IF NOT EXISTS feira_municipal;
USE feira_municipal;
DROP TABLE IF EXISTS feira;
DROP TABLE IF EXISTS feirante;
DROP TABLE IF EXISTS participa;
DROP TABLE IF EXISTS subcategoria;
DROP TABLE IF EXISTS categoria;
DROP TABLE IF EXISTS celula;
DROP TABLE IF EXISTS supervisor;
DROP TABLE IF EXISTS endereco;
DROP TABLE IF EXISTS aviso;
CREATE TABLE categoria (
id INTEGER AUTO_INCREMENT,
nome VARCHAR(200) NOT NULL,
need_cnpj BOOLEAN NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE subcategoria (
id INTEGER AUTO_INCREMENT,
nome VARCHAR(200) NOT NULL,
categoria_id INTEGER NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (categoria_id) REFERENCES categoria (id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE feira (
data DATE,
data_limite DATETIME,
status BOOLEAN DEFAULT false,
evento_image_url VARCHAR(200),
PRIMARY KEY (data)
);
CREATE TABLE aviso (
id INTEGER AUTO_INCREMENT,
assunto VARCHAR(100) NOT NULL,
texto VARCHAR(1000) NOT NULL,
data_feira DATE NULL DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (data_feira) REFERENCES feira (data) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE feirante (
cpf VARCHAR(15),
rg VARCHAR(15) NOT NULL,
nome VARCHAR(100) NOT NULL,
cnpj VARCHAR(15),
usa_ee BOOLEAN NOT NULL,
nome_fantasia VARCHAR(100),
razao_social VARCHAR(100),
comprimento_barraca REAL NOT NULL,
largura_barraca REAL NOT NULL,
voltagem_ee INTEGER,
status BOOLEAN DEFAULT true,
sub_categoria_id INTEGER NOT NULL,
senha VARCHAR(500) NOT NULL,
PRIMARY KEY (cpf),
FOREIGN KEY (sub_categoria_id) REFERENCES subcategoria (id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE endereco (
id INTEGER AUTO_INCREMENT,
logradouro VARCHAR(100) NOT NULL,
bairro VARCHAR (100),
numero INTEGER,
CEP VARCHAR(10),
cpf_feirante VARCHAR(15) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (cpf_feirante) REFERENCES feirante (cpf) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE celula (
id INTEGER,
cpf_feirante VARCHAR(15),
periodo INTEGER NOT NULL,
x REAL NOT NULL,
y REAL NOT NULL,
comprimento REAL NOT NULL,
largura REAL NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (cpf_feirante) REFERENCES feirante (cpf) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE participa (
cpf_feirante VARCHAR(15),
data_feira DATE,
faturamento REAL DEFAULT 0,
periodo INTEGER NOT NULL,
hora_confirmacao DATETIME,
celula_id INTEGER,
PRIMARY KEY (cpf_feirante, data_feira),
FOREIGN KEY (cpf_feirante) REFERENCES feirante (cpf) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (data_feira) REFERENCES feira (data) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE supervisor (
cpf VARCHAR(15),
nome VARCHAR(100) NOT NULL,
senha VARCHAR(500) NOT NULL,
is_adm BOOLEAN DEFAULT false,
root_adm BOOLEAN DEFAULT false,
status BOOLEAN DEFAULT true,
PRIMARY KEY (cpf)
);<file_sep>/frontend/src/api/aviso.js
import axios from 'axios';
const host = `${process.env.REACT_APP_HOST}/aviso`;
export async function get() {
return (await axios.get(host)).data;
}
export async function getAvisosProximaFeira() {
return (await axios.get(`${host}/proxima`)).data;
}
export async function post(assunto, texto, data_feira) {
await axios.post(
host,
{
assunto,
texto,
data_feira,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export async function put(id, assunto, texto, data_feira) {
await axios.put(
`${host}/${id}`,
{
assunto,
texto,
data_feira,
},
{ headers: { token: localStorage.getItem('token') } },
);
}
export async function getById(id) {
const record = (await axios.get(
`${host}/${id}`,
{ headers: { token: localStorage.getItem('token') } },
)).data;
return record;
}
export async function del(id) {
await axios.delete(
`${host}/${id}`,
{ headers: { token: localStorage.getItem('token') } },
);
}
<file_sep>/frontend/src/screens/Relatorios/RelatorioPage.js
import React, { PureComponent } from 'react';
import moment from 'moment-timezone';
import {
Statistic, Row, Col, Card,
Table,
} from 'antd';
import ContentComponent from '../../components/ContentComponent';
import * as relatorioAPI from '../../api/relatorio';
import styles from './Relatorios.module.scss';
const { Column } = Table;
export default class RelatorioPage extends PureComponent {
state = {
participantes: [],
faturamentoPeriodo: [],
loading: true,
dataFeira: '',
};
componentDidMount() {
this._loadValues();
}
_loadValues = async () => {
try {
const { data } = this.props.match.params;
const newDate = data.split('-');
const dataFeira = `${newDate[2]}-${newDate[1]}-${newDate[0]}`;
await this.setState({dataFeira});
await this._getParticipantes();
await this._getFaturamento();
} catch(ex) {
console.warn(ex);
}
}
_getParticipantes = async () => {
this.setState({loading: true});
const { dataFeira } = this.state;
const participantes = await relatorioAPI.getParticipantes(dataFeira);
this.setState({participantes, loading: false});
}
_getFaturamento = async () => {
const { dataFeira } = this.state;
const faturamentoPeriodo = await relatorioAPI.getFaturamentoPeriodo(moment(dataFeira).format('YYYY-MM-DD'));
this.setState({faturamentoPeriodo});
}
_renderFeiraInvalida = () => {
return (
<ContentComponent
title="Relatórios"
>
<div className={styles.errorContainer}>
<h2>Feira não existente!</h2>
<a href="/supervisor/relatorios" alt="voltar">Voltar</a>
</div>
</ContentComponent>
)
}
_getFaturamentoDeUmPeriodo = (periodoDesejado) => {
const { faturamentoPeriodo } = this.state;
if (!faturamentoPeriodo) return 0;
const periodo = faturamentoPeriodo.find(fat => fat.periodo === periodoDesejado);
return periodo ? periodo.faturamento : 0;
}
render() {
const { participantes, dataFeira, loading } = this.state;
if (!participantes) return this._renderFeiraInvalida();
const presentes = participantes.participaram ? participantes.participaram.length : 0;
const ausentes = participantes.naoParticiparam ? participantes.naoParticiparam.length : 0;
return (
<ContentComponent
loading={loading}
title={`Feira do dia ${moment(dataFeira).format('DD/MM/YYYY')}`}
>
<Row gutter={24}>
<Col span={8}>
<Card
style={{
backgroundColor: '#2ecc71',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Faturamento"
value={participantes.faturamento}
precision={2}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
prefix="R$"
/>
</Card>
</Col>
<Col span={8}>
<Card
style={{
backgroundColor: '#3498db',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Presentes"
value={presentes}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
suffix={presentes > 1 ? 'feirantes' : 'feirante'}
/>
</Card>
</Col>
<Col span={8}>
<Card
style={{
backgroundColor: '#e74c3c',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Ausentes"
value={ausentes}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
suffix={ausentes > 1 ? 'feirantes' : 'feirante'}
/>
</Card>
</Col>
</Row>
<h2 className={styles.titulo}>Faturamento por período</h2>
<Row gutter={24}>
<Col span={8}>
<Card
style={{
backgroundColor: '#e67e22',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Manhã"
value={this._getFaturamentoDeUmPeriodo(1)}
precision={2}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
prefix="R$"
/>
</Card>
</Col>
<Col span={8}>
<Card
style={{
backgroundColor: '#34495e',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Tarde"
value={this._getFaturamentoDeUmPeriodo(2)}
precision={2}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
prefix="R$"
/>
</Card>
</Col>
<Col span={8}>
<Card
style={{
backgroundColor: '#9b59b6',
border: 'none',
borderRadius: 4,
}}
>
<Statistic
title="Manhã e Tarde"
value={this._getFaturamentoDeUmPeriodo(3)}
precision={2}
style={{color: '#fff'}}
valueStyle={{ color: '#fff' }}
prefix="R$"
/>
</Card>
</Col>
</Row>
<h2 className={styles.titulo}>Participaram</h2>
<Table
rowKey={linha => linha.cpf}
dataSource={participantes.participaram}
locale={{
emptyText: 'Nenhum registro'
}}
>
<Column
title="CPF"
dataIndex="cpf"
key="cpf"
render={cpf => cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4')}
width={150}
/>
<Column
title="Nome"
dataIndex="nome"
key="nome"
/>
<Column
title="Nome fantasia"
dataIndex="nomeFantasia"
key="nomeFantasia"
/>
<Column
title="Faturamento"
key="faturamento"
dataIndex="faturamento"
render={faturamento => faturamento ? faturamento.toLocaleString('pt-BR', {
minimumFractionDigits: 2,
style: 'currency',
currency: 'BRL',
}) : 'R$ 0,00'}
width={105}
/>
</Table>
<h2 className={styles.titulo}>Não participaram</h2>
<Table
rowKey={linha => linha.cpf}
dataSource={participantes.naoParticiparam}
locale={{
emptyText: 'Nenhum registro'
}}
>
<Column
title="CPF"
dataIndex="cpf"
key="cpf"
render={cpf => cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '$1.$2.$3-$4')}
width={150}
/>
<Column
title="Nome"
dataIndex="nome"
key="nome"
/>
<Column
title="Nome fantasia"
dataIndex="nomeFantasia"
key="nomeFantasia"
/>
</Table>
</ContentComponent>
);
}
}<file_sep>/frontend/src/components/TabelaComponent.js
import React, {PureComponent} from 'react';
import { Table } from 'antd';
export default class TabelaComponent extends PureComponent {
state = {};
render() {
const { colunas, linhas, ...tableProps } = this.props;
const lin = linhas.map(linha => {
return {
key: linha.id,
...linha,
}
});
return (
<Table
dataSource={lin}
columns={colunas}
{...tableProps}
/>
);
}
}<file_sep>/backend/controllers/categoria.js
const models = require('../models');
const addCategoria = async (nome, needCnpj) => {
const categoria = await models.categoria.findOne({
where: { nome },
});
if (categoria != null) {
return null;
}
try {
const res = await models.categoria.create({
nome,
need_cnpj: needCnpj,
});
return res;
} catch (error) {
return null;
}
};
const listCategoria = async () => {
const categorias = await models.categoria.findAll();
return categorias.map(el => ({
id: el.id,
nome: el.nome,
need_cnpj: el.need_cnpj,
}));
};
const findCategoriaById = async (id) => {
const categoria = await models.categoria.findOne({
where: { id },
});
if (categoria == null) {
return null;
}
return { id: categoria.id, nome: categoria.nome, need_cnpj: categoria.need_cnpj };
};
const deleteCategoria = async (id) => {
try {
return await models.categoria.destroy({ where: { id } });
} catch (error) {
return null;
}
};
const updateCategoria = async (id, dados) => {
const categoria = await models.categoria.findOne({
where: { id },
});
if (categoria == null) {
return null;
}
const res = await categoria.update(dados);
return res;
};
module.exports = {
addCategoria,
listCategoria,
findCategoriaById,
deleteCategoria,
updateCategoria,
};
<file_sep>/frontend/src/screens/Supervisores/index.js
import React, { PureComponent, Fragment } from 'react';
import {
Button, Popconfirm, Modal,
Tag, Table, Empty, message,
} from 'antd';
import ContentComponent from '../../components/ContentComponent';
import SupervisorForm from './SupervisorForm';
import * as SupervisorAPI from '../../api/supervisor';
import EmptyComponent from '../../components/EmptyComponent';
const { Column } = Table;
export default class SupervisorScreen extends PureComponent {
state = {
Supervisor: [],
visible: false,
loading: true,
selectedSupervisor: {},
};
componentDidMount() {
this._loadSupervisor();
}
_loadSupervisor = async () => {
this.setState({ loading: true });
const Supervisor = await SupervisorAPI.get();
this.setState({ Supervisor, loading: false });
}
_onDeleteSupervisor = async cpf => {
message.loading('Carregando.', 0);
await SupervisorAPI.del(cpf)
.then(() => {
message.success('Supervisor deletado com sucesso.', 2.5);
this._loadSupervisor();
})
.catch(() => {
message.error('Não foi possível excluir, tente novamente mais tarde!', 2.5);
});
}
showModal = supervisor => {
this.setState({
visible: true,
selectedSupervisor: supervisor,
});
}
handleOk = (e) => {
this.setState({
visible: false,
selectedSupervisor: {},
});
}
handleCancel = (e) => {
this.setState({
visible: false,
selectedSupervisor: {},
});
}
_renderModal = () => {
const { visible, selectedSupervisor} = this.state;
return (
<Modal
title={ selectedSupervisor && selectedSupervisor.cpf
? selectedSupervisor.nome
: 'Cadastrar novo supervisor'
}
visible={visible}
onCancel={this.handleCancel}
footer={null}
destroyOnClose
maskClosable={false}
>
<SupervisorForm
supervisor={selectedSupervisor}
onSuccess={this.handleOk}
refresh={this._loadSupervisor}
/>
</Modal>
);
}
/* atrubutos :
cpf,
nome,
senha,
isAdm
*/
// TABELA SÓ COM AS INFORMAÇÕES BÁSICA, CLICAR NUMA MODAL ABRE O RESTO DAS INFORMAÇÕES !
_renderAcoes = linha => {
return (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Button type="primary" onClick={() => this.showModal(linha)}>
Editar
</Button>
{
linha.root_adm
? (
<Button
shape="circle"
icon="delete"
type="danger"
disabled
/>
)
: (
<Popconfirm
title="Você quer deletar este supervisor?"
okText="Sim"
cancelText="Não"
onConfirm={() => this._onDeleteSupervisor(linha.cpf)}
>
<Button
shape="circle"
icon="delete"
type="danger"
/>
</Popconfirm>
)
}
</div>
)
}
render() {
const { Supervisor, loading } = this.state;
return (
<Fragment>
<ContentComponent
buttonProps={{
text: 'Adicionar',
onClick: this.showModal,
type: 'primary',
icon: 'plus',
}}
title="Supervisores"
>
<Table
dataSource={Supervisor}
size="small"
loading={loading}
rowKey={linha => linha.cpf}
pagination={{
pageSize: 15,
}}
locale={(
<Empty
image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
imageStyle={{
height: 60,
}}
description={
<span>
Customize <a href="#API">Description</a>
</span>
}
>
<Button type="primary">Create Now</Button>
</Empty>
)}
>
<Column
key="cpf"
dataIndex="cpf"
title="CPF"
width={150}
/>
<Column
key="nome"
dataIndex="nome"
title="Nome"
/>
<Column
key="isAdm"
dataIndex="is_adm"
title="Administrador"
width={50}
render={isAdm => {
return isAdm
? <Tag color="#87d068">Sim</Tag>
: <Tag color="#2db7f5">Não</Tag>
}}
/>
<Column
key="acoes"
title="Ações"
render={linha => this._renderAcoes(linha)}
width={130}
/>
</Table>
{ this._renderModal() }
</ContentComponent>
</Fragment>
);
}
}<file_sep>/backend/controllers/feirante.js
const bcrypt = require('bcrypt');
const models = require('../models');
const addFeirante = async (
cpf,
rg,
nome,
cnpj,
senha,
usaEe,
nomeFantasia,
razaoSocial,
comprimentoBarraca,
larguraBarraca,
endereco,
voltagemEe,
subCategoriaId,
) => {
const feirante = await models.feirante.findOne({
where: { cpf },
});
const hashSenha = await bcrypt.hash(senha, 10);
if (feirante !== null && !feirante.status) {
const ret = await feirante.update({
cpf,
rg,
nome,
cnpj,
senha: <PASSWORD>,
usa_ee: usaEe,
nome_fantasia: nomeFantasia,
razao_social: razaoSocial,
comprimento_barraca: comprimentoBarraca,
largura_barraca: larguraBarraca,
voltagem_ee: voltagemEe,
sub_categoria_id: subCategoriaId,
status: true,
});
return ret;
}
// Utilizando transaction pois se ocorrer erro
// no momento de adicionar o endereço é necessário fazer rollback do feirante
let transaction;
if (feirante === null) {
try {
transaction = await models.sequelize.transaction();
const ret = await models.feirante.create({
cpf,
rg,
nome,
cnpj,
senha: <PASSWORD>,
usa_ee: usaEe,
nome_fantasia: nomeFantasia,
razao_social: razaoSocial,
comprimento_barraca: comprimentoBarraca,
largura_barraca: larguraBarraca,
voltagem_ee: voltagemEe,
sub_categoria_id: subCategoriaId,
status: true,
});
await models.endereco.create({
cpf_feirante: cpf,
logradouro: endereco.logradouro,
bairro: endereco.bairro,
numero: endereco.numero,
CEP: endereco.CEP,
});
await transaction.commit();
return ret;
} catch (error) {
await transaction.rollback();
return null;
}
}
return null;
};
const listFeirante = async () => {
const feirantes = await models.feirante.findAll({
where: {
status: true,
},
include: ['endereco', 'sub_categoria'],
});
return feirantes.map(el => ({
cpf: el.cpf,
rg: el.rg,
nome: el.nome,
cnpj: el.cnpj,
usaEe: el.usa_ee,
nomeFantasia: el.nome_fantasia,
razaoSocial: el.razao_social,
comprimentoBarraca: el.comprimento_barraca,
larguraBarraca: el.largura_barraca,
endereco: {
logradouro: el.endereco.logradouro,
bairro: el.endereco.bairro,
numero: el.endereco.numero,
CEP: el.endereco.CEP,
},
voltagemEe: el.voltagem_ee,
subCategoriaId: el.sub_categoria_id,
...el,
}));
};
const findFeiranteByCpf = async (cpf) => {
const feirante = await models.feirante.findOne({
where: {
cpf,
status: true,
},
include: ['endereco'],
});
if (feirante === null) return null;
return {
cpf: feirante.cpf,
rg: feirante.rg,
nome: feirante.nome,
cnpj: feirante.cnpj,
usaEe: feirante.usa_ee,
nomeFantasia: feirante.nome_fantasia,
razaoSocial: feirante.razao_social,
comprimentoBarraca: feirante.comprimento_barraca,
larguraBarraca: feirante.largura_barraca,
endereco: {
logradouro: feirante.endereco.logradouro,
bairro: feirante.endereco.bairro,
numero: feirante.endereco.numero,
CEP: feirante.endereco.CEP,
},
voltagemEe: feirante.voltagem_ee,
subCategoriaId: feirante.sub_categoria_id,
};
};
const updateFeirante = async (cpf, dados) => {
const feirante = await models.feirante.findOne({
where: { cpf, status: true },
});
if (feirante === null) return null;
if ('status' in dados) return null;
const { endereco, ...obj } = dados;
if ('senha' in obj) {
obj.senha = await bcrypt.hash(obj.senha, 10);
}
if (endereco !== undefined) {
const enderecoTmp = await models.endereco.findOne({ where: { cpf_feirante: cpf } });
try {
await enderecoTmp.update(endereco);
if (Object.keys(obj).length === 0) {
const ret = await models.feirante.findOne({
where: { cpf, status: true },
include: ['endereco'],
});
return ret;
}
} catch (error) {
return null;
}
}
if (Object.keys(obj).length !== 0) {
try {
await feirante.update(obj);
const ret = await models.feirante.findOne({
where: { cpf, status: true },
include: ['endereco'],
});
return ret;
} catch (error) {
return null;
}
}
return null;
};
const deleteFeirante = async (cpf) => {
const feirante = await models.feirante.findOne({
where: { cpf, status: true },
});
if (feirante === null) return null;
const ret = await feirante.update({ status: false });
return ret;
};
module.exports = {
addFeirante,
listFeirante,
findFeiranteByCpf,
updateFeirante,
deleteFeirante,
};
<file_sep>/backend/tests/models/subcategoria.js
const chance = require("chance").Chance();
const { assert } = require("chai");
const models = require("../../models");
after(() => {
models.sequelize.close();
});
describe("Testando Subcategoria", () => {
beforeEach(() => {
models.feirante.destroy({ where: {} });
models.categoria.destroy({ where: {} });
models.subcategoria.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.celula.destroy({ where: {} });
// Cria a categoria Alimentos com id 1
models.categoria.create({
id: "1",
nome: "alimentos",
need_cnpj: false
});
});
it("Adicionar Subcategoria", async ()=>{
// Verifica que a subcategoria Pastel já existe
let subcategoria = await models.subcategoria.findOne({
where:{
id: "",
nome: "pastel",
categoria_id: "1"
}
});
assert.isNull(subcategoria);
// Cria uma nova Subcategoria Pastel, relacionada com a categoria Alimentos
subcategoria = await models.subcategoria.create({
id: "",
nome: "pastel",
categoria_id: "1"
});
// Faz uma consulta para encontrar a Subcategoria Pastel
subcategoria = await models.subcategoria.findOne({
where:{
nome: "pastel",
categoria_id: "1"
}
});
assert.isNotNull(subcategoria);
assert.strictEqual(subcategoria.nome, "pastel");
});
});
<file_sep>/backend/tests/controllers/feirante.js
const { assert } = require('chai');
const faker = require('faker');
const participaController = require('../../controllers/participa');
const feiraController = require('../../controllers/feira');
const categoriaController = require('../../controllers/categoria');
const feiranteController = require('../../controllers/feirante');
const models = require('../../models');
describe('feirante.js', () => {
let subcategoria;
before(async () => {
await models.categoria.destroy({ where: {} });
const categoria = await categoriaController.addCategoria('Alimento', false);
subcategoria = await categoria.createSubCategoria({ nome: 'Salgado' });
});
beforeEach(async () => {
await models.participa.destroy({ where: {} });
await models.feira.destroy({ where: {} });
await models.endereco.destroy({ where: {} });
await models.feirante.destroy({ where: {} });
});
after(() => {
models.participa.destroy({ where: {} });
models.feira.destroy({ where: {} });
models.endereco.destroy({ where: {} });
models.feirante.destroy({ where: {} });
});
describe('addFeirante', () => {
it('Não cadastra feirante sem endereço', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{},
110,
subcategoria.id,
);
assert.isNull(feirante);
});
it('Não cadastra um feirante com subcategoria inválida', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
337,
);
assert.isNull(feirante);
});
it('Cadastra um feirante', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNotNull(feirante);
});
it('Não cadastra um feirante com informação faltando', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
null,
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNull(feirante);
});
it('Não cadastra um feirante repetido', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNotNull(feirante);
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNull(feirante);
});
it('Re-ativa um feirante', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNotNull(feirante);
const res = await feiranteController.deleteFeirante(feirante.cpf);
assert.isNotNull(res);
feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
assert.isNotNull(feirante);
});
});
describe('listFeirante', () => {
it('Retorna vazio se não existir feirante', async () => {
const supervisores = await feiranteController.listFeirante();
assert.lengthOf(supervisores, 0);
});
it('Retorna lista de feirantes', async () => {
let feirantes = await feiranteController.listFeirante();
assert.lengthOf(feirantes, 0);
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirantes = await feiranteController.listFeirante();
assert.lengthOf(feirantes, 1);
assert.strictEqual(feirantes[0].cpf, feirante.cpf);
assert.strictEqual(feirantes[0].endereco.numero, 100);
});
it('Não lista feirante inativo', async () => {
let supervisores = await feiranteController.listFeirante();
assert.lengthOf(supervisores, 0);
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
const feirante2 = await feiranteController.addFeirante(
'75191649001',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await feiranteController.deleteFeirante(feirante2.cpf);
supervisores = await feiranteController.listFeirante();
assert.lengthOf(supervisores, 1);
assert.strictEqual(supervisores[0].cpf, feirante.cpf);
});
});
describe('findFeiranteByCpf', () => {
it('Retorna null se feirante não existe', async () => {
const feirante = await feiranteController.findFeiranteByCpf('58295846035');
assert.isNull(feirante);
});
it('Retorna feirante', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
const feiranteFind = await feiranteController.findFeiranteByCpf('58295846035');
assert.isNotNull(feiranteFind);
assert.strictEqual(feirante.cpf, feiranteFind.cpf);
});
it('Retorna null se feirante for inativo', async () => {
const feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await feiranteController.deleteFeirante(feirante.cpf);
const feiranteFind = await feiranteController.findFeiranteByCpf('58295846035');
assert.isNull(feiranteFind);
});
});
describe('updateSupervisor', () => {
it('Não atualiza feirante que não existe', async () => {
const feirante = await feiranteController.updateFeirante('58295846035', {
rg: '469964807',
nome: faker.name.firstName(),
cnpj: '',
usa_ee: true,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.isNull(feirante);
});
it('Não atualiza feirante desativado', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await feiranteController.deleteFeirante(feirante.cpf);
feirante = await feiranteController.updateFeirante('58295846035', {
rg: '469964807',
nome: faker.name.firstName(),
cnpj: '',
usa_ee: true,
nome_fantasia: faker.name.firstName(),
razao_social: faker.name.firstName(),
comprimento_barraca: 4,
largura_barraca: 4,
endereco: {
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
voltagem_ee: 110,
sub_categoria_id: subcategoria.id,
});
assert.isNull(feirante);
});
it('Não deixa atualizar status', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirante = await feiranteController.updateFeirante('58295846035', {
status: false,
});
assert.isNull(feirante);
});
it('Atualiza somente senha', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirante = await feiranteController.updateFeirante('58295846035', {
senha: faker.<PASSWORD>(),
});
assert.isNotNull(feirante);
});
it('Atualiza somente endereço', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
const novoCep = '87.303-000';
feirante = await feiranteController.updateFeirante('58295846035', {
endereco: {
CEP: novoCep,
},
});
assert.isNotNull(feirante);
assert.strictEqual(feirante.endereco.CEP, novoCep);
});
it('Atualiza endereço e mais informações', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
const novoNomeFantasia = faker.name.firstName();
const novoCep = '87.303-000';
const novoNumero = 200;
feirante = await feiranteController.updateFeirante('58295846035', {
nome_fantasia: novoNomeFantasia,
endereco: {
CEP: novoCep,
numero: novoNumero,
},
});
assert.isNotNull(feirante);
assert.strictEqual(feirante.endereco.CEP, novoCep);
assert.strictEqual(feirante.endereco.numero, novoNumero);
assert.strictEqual(feirante.nome_fantasia, novoNomeFantasia);
});
});
describe('deleteFeirante', () => {
it('Não deleta feirante que não existe', async () => {
const feirante = await feiranteController.deleteFeirante('58295846035');
assert.isNull(feirante);
});
it('Não deleta feirante desativado', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
await feiranteController.deleteFeirante(feirante.cpf);
feirante = await feiranteController.deleteFeirante(feirante.cpf);
assert.isNull(feirante);
});
it('Deleta feirante', async () => {
let feirante = await feiranteController.addFeirante(
'58295846035',
'469964807',
faker.name.firstName(),
'',
faker.name.firstName(),
true,
faker.name.firstName(),
faker.name.firstName(),
4,
4,
{
logradouro: faker.address.streetAddress(),
bairro: faker.address.secondaryAddress(),
numero: 100,
CEP: '87.303-065',
},
110,
subcategoria.id,
);
feirante = await feiranteController.deleteFeirante(feirante.cpf);
assert.isNotNull(feirante);
feirante = await feiranteController.findFeiranteByCpf(feirante.cpf);
assert.isNull(feirante);
});
});
});
<file_sep>/backend/controllers/login.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const models = require('../models');
const keys = require('../config/keys.json');
const login = async (cpf, senha) => {
let user = await models.supervisor.findOne({ where: { cpf } });
if (user !== null) {
if (await bcrypt.compare(senha, user.senha)) {
return {
tag: user.is_adm ? 'administrador' : 'supervisor',
token: jwt.sign(cpf, keys.jwt),
};
}
return null;
}
user = await models.feirante.findOne({ where: { cpf } });
if (user !== null) {
if (await bcrypt.compare(senha, user.senha)) {
return {
tag: 'feirante',
token: jwt.sign(cpf, keys.jwt),
};
}
return null;
}
return null;
};
module.exports = { login };
<file_sep>/backend/database/insert_celulas.js
const models = require('../models');
/*
Metro = 0.0147 no comprimento
= 0.0167 na largura
*/
const CBase = 0.0142557;
const LBase = 0.0166666;
const celulas = [
{ // Cell 0
id: 0,
y: 0.065,
x: 0.135,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 1
id: 1,
y: 0.66,
x: 0.77,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 2
id: 2,
y: 0.719,
x: 0.713,
comprimento: CBase * 2,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 3
id: 3,
y: 0.719,
x: 0.67,
comprimento: CBase * 2,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 4
id: 4,
y: 0.75,
x: 0.645,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 5
id: 5,
y: 0.75,
x: 0.625,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 6
id: 6,
y: 0.75,
x: 0.605,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 7
id: 7,
y: 0.75,
x: 0.585,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 8
id: 8,
y: 0.75,
x: 0.565,
comprimento: CBase * 1,
largura: LBase * 1,
periodo: 1,
},
{ // Cell 9
id: 9,
y: 0.715,
x: 0.505,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 10
id: 10,
y: 0.715,
x: 0.455,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 11
id: 11,
y: 0.715,
x: 0.405,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 12
id: 12,
y: 0.715,
x: 0.355,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 13
id: 13,
y: 0.715,
x: 0.305,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 14
id: 14,
y: 0.715,
x: 0.255,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 15
id: 15,
y: 0.72,
x: 0.12,
comprimento: CBase * 2,
largura: LBase * 2,
periodo: 1,
},
{ // Cell 16
id: 16,
y: 0.72,
x: 0.05,
comprimento: CBase * 2,
largura: LBase * 2,
periodo: 1,
},
{ // Cell 17
id: 17,
y: 0.68,
x: 0.12,
comprimento: CBase * 2,
largura: LBase * 2,
periodo: 1,
},
{ // Cell 18
id: 18,
y: 0.625,
x: 0.13,
comprimento: CBase * 2,
largura: LBase * 2,
periodo: 1,
},
{ // Cell 19
id: 19,
y: 0.57,
x: 0.13,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 20
id: 20,
y: 0.53,
x: 0.19,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 70
id: 70,
y: 0.16,
x: 0.135,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 71
id: 71,
y: 0.098,
x: 0.135,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 72
id: 72,
y: 0.48,
x: 0.24,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 73
id: 73,
y: 0.425,
x: 0.24,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 74
id: 74,
y: 0.37,
x: 0.24,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 75
id: 75,
y: 0.315,
x: 0.24,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
{ // Cell 76
id: 76,
y: 0.26,
x: 0.24,
comprimento: CBase * 3,
largura: LBase * 3,
periodo: 1,
},
];
const insert_celulas = async () => {
await celulas.forEach(async (celula) => {
await models.celula.create(celula);
});
};
module.exports = { insert_celulas };
<file_sep>/docs/api/README.md
# Documentação API
## - Autenticação - [`/api/login`](login.md)
## - Supervisor - [`/api/supervisor`](supervisor.md)
## - Feirante - [`/api/feirante`](feirante.md)
## - Feira - [`/api/feira`](feira.md)
## - Célula - [`/api/celula`](celula.md)
## - Categoria - [`/api/categoria`](categoria.md)
## - Subcategoria - [`/api/subcategoria`](subcategoria.md)
| b5f4d366efaedb50b55ae0b894923aba43afdebb | [
"JavaScript",
"SQL",
"Markdown"
] | 88 | JavaScript | utfpr/municipalMarketFairControl | 7145e12f98692fca1e699b01b3a1a4ea6b248e03 | 791eba225730ecf08f71c0706174e417d415623e |
refs/heads/master | <repo_name>christophherr/file-metadata<file_sep>/server.js
let express = require('express'),
path = require('path'),
multer = require('multer'),
upload = multer(),
port = process.env.port || 3000,
app = express();
app.listen(port, () => console.log('listening on port ' + port));
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.post('/file-info', upload.single('file'), (req, res) =>
res.json({
'file name': req.file.originalname,
'file type': req.file.mimetype,
'file size': req.file.size
})
);
| 377822b76b867ff79c5ff95286d006777376a646 | [
"JavaScript"
] | 1 | JavaScript | christophherr/file-metadata | 58b781578fa26c1eb76ba0123a2af10910ae9176 | 3d865d934ccb70ddb21abec0c0927a00530e895b |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { IProduct } from '../model/product';
import { ICategory } from '../model/category';
@Injectable({
providedIn: 'root'
})
export class ProductService {
localStorage: Storage;
aryProducts: IProduct[] = [];
itemCounter:number = 0;
isSaveSuccessful:boolean;
constructor() {
}
getIncrementItemNumber() {
return this.itemCounter++;
}
getLocalStorage() {
return (typeof window !== "undefined") ? window.localStorage : null;
}
addItem(val:IProduct) {
this.localStorage = this.getLocalStorage();
let product:IProduct = val;
this.aryProducts.push(product);
if(this.localStorage) {
this.localStorage.setItem('products', JSON.stringify(this.aryProducts));
this.isSaveSuccessful = true;
return this.isSaveSuccessful;
}
}
getProducts():Array<IProduct> {
this.localStorage = this.getLocalStorage();
if(this.localStorage) {
let products = this.localStorage.getItem('products');
let parseObj = JSON.parse(products);
return parseObj;
}
}
getFilteredProducts(val:ICategory) {
//get category id
//return the object based on the category ID
let catID = val.categoryID;
let aryProducts = this.getProducts();
if(+catID !== 0) {
let aryFilteredProducts:Array<IProduct> = [];
//use standard loop for minimal weight and load compared to foreach/for loops
for(var i = 0; i < aryProducts.length; i++) {
let aryCategories:Array<ICategory> = aryProducts[i].categories;
for(var j = 0; j < aryCategories.length; j++) {
if(aryCategories[j].categoryID === +catID) {
aryFilteredProducts.push(aryProducts[i]);
}
}
}
return aryFilteredProducts;
}else {
return aryProducts;
}
}
getProduct(id: number | string) {
return this.getProducts().find(product => product.id === +id);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ProductService } from './service/product.service';
import { IProduct } from './model/product';
import { ICategory } from './model/category';
import { CATEGORYLIST } from './categorylist';
@Component({
selector: 'app-productlist',
templateUrl: './productlist.component.html',
styleUrls: ['./productlist.component.scss']
})
export class ProductlistComponent implements OnInit {
isProductsEmpty:Boolean;
aryProducts:Array<IProduct>;
aryCategories:Array<ICategory>;
aryCategorySelection:Array<ICategory> = CATEGORYLIST;
selectedCategory:number;
pageHeaderTitle:string = 'Product List';
constructor(private prodService:ProductService) { }
ngOnInit() {
this.aryProducts = this.prodService.getProducts();
this.selectedCategory = 0;
}
categorySelected(val:ICategory) {
this.selectedCategory = val.categoryID;
let filteredProducts = this.prodService.getFilteredProducts(val);
this.aryProducts = filteredProducts;
this.isProductsEmpty = (this.aryProducts.length <= 0 || this.aryProducts == null);
}
}
<file_sep>import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { IProduct } from '../productlist/model/product';
import { ProductService } from '../productlist/service/product.service';
import { ICategory } from '../productlist/model/category';
import { CATEGORYLIST } from '../productlist/categorylist';
@Component({
selector: 'app-addproduct',
templateUrl: './addproduct.component.html',
styleUrls: ['./addproduct.component.scss']
})
export class AddProductComponent implements OnInit {
formGroup: FormGroup;
allCategoryID:number = 0;
isAllCategory:boolean;
pageHeaderTitle:string = 'Add Product Form';
constructor(private fb:FormBuilder, private prodService:ProductService) {
this.createForm();
}
ngOnInit() {}
//sample categories here - should be dynamic and coming from admin - created global shared data as CATEGORYLIST
public aryCategories:Array<ICategory> = CATEGORYLIST;
public aryCategoryValues:any;
createForm() {
this.formGroup = this.fb.group({
title: ['', [Validators.required, Validators.minLength(10)]],
sku: ['', Validators.required],
desc: [''],
aryCategoryValues: ['', Validators.required]
})
}
save(addForm:any) {
let itemSequence = this.prodService.getIncrementItemNumber();
let aryCategoryID:ICategory[] = addForm.value.aryCategoryValues;
let all = aryCategoryID.find(category => category.categoryID === this.allCategoryID);
this.isAllCategory = (all) ? true : false;
let product = {} as IProduct;
product.id = itemSequence;
product.title = addForm.value.title;
product.description = addForm.value.desc;
product.sku = addForm.value.sku + '-' + itemSequence;
if(this.isAllCategory) {
product.categories = CATEGORYLIST;
} else {
product.categories = addForm.value.aryCategoryValues;
}
let isSuccessful = this.prodService.addItem(product);
if(isSuccessful) {
alert('success');
}
}
getProducts() {
let products = this.prodService.getProducts();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { ProductService } from '../productlist/service/product.service';
import { IProduct } from '../productlist/model/product';
@Component({
selector: 'app-productdetail',
templateUrl: './productdetail.component.html',
styleUrls: ['./productdetail.component.scss']
})
export class ProductDetailComponent implements OnInit {
product:IProduct;
pageHeaderTitle:string = 'Product Detail';
constructor(private prodService:ProductService, private route: ActivatedRoute) { }
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.product = this.prodService.getProduct(id);
}
}
<file_sep>import { ICategory } from './model/category';
export const CATEGORYLIST:ICategory[] = [
{
categoryID: 0,
category: 'All Categories'
},
{
categoryID: 1,
category: 'Category 1'
},
{
categoryID: 2,
category: 'Category 2'
},
{
categoryID: 3,
category: 'Category 3'
},
{
categoryID: 4,
category: 'Category 4'
},
{
categoryID: 5,
category: 'Category 5'
}
]<file_sep>import { ICategory } from './category';
export interface IProduct {
id: number,
title: string,
description: string,
sku: string,
categories: Array<ICategory>
} | f3849e939fe1589f4dca441951dee0444b01b210 | [
"TypeScript"
] | 6 | TypeScript | paulalonte/ecommerce-product-app | 457a5bfc7926cd2711ff4a50fe375ce30a37a1c2 | 60a5462d6c0b1e9da6c5701f28cd97462c330abb |
refs/heads/master | <repo_name>ashcherbyna/Automation-Courses-Home-Work<file_sep>/src/Home Work/Homework3/Homework3_3.java
import java.util.Scanner;
import java.util.Random;
public class Homework3_3{
public static void main(String[] args) {
System.out.println("Fill the length of Array:");
Scanner scr = new Scanner(System.in);
int number = scr.nextInt();
int[] anArray = new int[number];
int[] randomList = list(anArray);
display(randomList);
}
private static int[] list(int[] anArray){
for (int i=0; i<anArray.length;i++){
anArray[i]=random();
}
return anArray;
}
private static int random() {
//так с Random не нужно работать. Нужно создать статическое поле и пререиспользовать.
Random random = new Random();
int randomNum = random.nextInt();
return randomNum;
}
private static void display(int[] randomList){
for (int i = 0; i<randomList.length;i++){
if (randomList[i]%3 == 0){
System.out.println("Numbew /3 = "+randomList[i]);
}
}
}
}
<file_sep>/src/Home Work/Homework3/Homework3_4.java
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Homework3_4 {
public static void main(String[] args) {
System.out.println("Fill your FIO:");
Scanner fioScan = new Scanner(System.in);
String fio = fioScan.nextLine();
System.out.println("Fill your Mobile Phone(Example +380123456789):");
Scanner phoneScan = new Scanner(System.in);
String phone = phoneScan.nextLine();
System.out.println("Fill your email:");
Scanner emailScan = new Scanner(System.in);
String email = emailScan.nextLine();
checkFio(fio);
checkPhone(phone);
checkEmail(email);
}
private static void checkFio(String fio) {
Pattern pattern = Pattern.compile("^[\\sa-zA-z-]+$");
Matcher matcher = pattern.matcher(fio);
if (matcher.matches() != true) {
System.out.println("FIO: " + fio + " is not Valid");
}
}
private static void checkPhone(String phone) {
Pattern pattern = Pattern.compile("^((\\+380)([0-9]{2})([0-9]{7}))+$");
Matcher matcher = pattern.matcher(phone);
if (matcher.matches() != true) {
System.out.println("Phone: " + phone + " is not Valid");
}
}
private static void checkEmail(String email) {
Pattern pattern = Pattern.compile("^[a-zA-Z0-9-_].+@[a-z]+\\.(com|ua|ru|org|com.ua)+$");
Matcher matcher = pattern.matcher(email);
if (matcher.matches() != true) {
System.out.println("Email: " + email + " is not Valid");
}
}
}<file_sep>/src/Home Work/Homework5/calculator/Root.java
package calculator;
/**
* Операция корень из числа
* @author ShcherbynaAndrey
*/
public class Root implements BinaryOperation {
@Override
public double resultFor(double left, double right){
return Math.pow(left, 1.0/right);
}
}
<file_sep>/src/Home Work/Homework3/Homework3_1.java
import java.util.Scanner;
public class Homework3_1 {
public static void main(String[] args) {
System.out.println("Fill something");
Scanner scr = new Scanner(System.in);
String stroka = scr.nextLine();
StringBuilder reverseString = new StringBuilder(stroka);
String reverseStringNew = reverseString.reverse().toString();
System.out.println(palindromCheck(stroka,reverseStringNew));
}
private static String palindromCheck(String stroka, String reverseStringNew){
if (stroka.equals(reverseStringNew)){
return ("ItsPalindrom");
}
else{
return ("It is not a Palindrom");
}
}
}
<file_sep>/src/Home Work/Homework5/calculator/Exponentiation.java
package calculator;
/**
* Операция возведения в степень
* @author ShcherbynaAndrey
*/
public class Exponentiation implements BinaryOperation {
@Override
public double resultFor(double left, double right){
return Math.pow(left,right);
}
}
<file_sep>/src/Home Work/Homework2/Homework2_2.java
public class Homework2_2 {
public static void main(String[] args) {
long number = 123456789;
totalSum(number);
}
private static void totalSum(long number) {
int result = 0;
while (number>=1) {
result +=(number%10);
number/=10;
}
System.out.println("Total sum of all numbers = "+result);
}
}
<file_sep>/src/Home Work/_homeWork1/Homework1_1.java
public class Homework1_1 {
public static void main(String[] args) {
int x = 50;
float y = 25.f;
byte z = 5;
double n = 15.6d;
System.out.println(calculationFirst(x,y,z,n));
System.out.println(calculationSecond(x,y,z,n));
System.out.println(calculationThird(x,y,z,n));
System.out.println(calculationFourse(x,y,z,n));
}
private static long calculationFirst(int x, float y, byte z, double n){
return (long) ( x + ( y - 100 ) * z / n );
}
private static int calculationSecond(int x, float y, byte z, double n){
return (int) ( x - ( 50 + y * z ) * n ) + x;
}
private static float calculationThird(int x, float y, byte z, double n){
return (float) ( x * ( y / ( z - 1 ) + 555 ) + n );
}
private static double calculationFourse(int x, float y, byte z, double n){
return (double) ( - x / y + z * ( n + 1 ));
}
}
| d1416c3ea94437277b5e9ac9b73997327132c025 | [
"Java"
] | 7 | Java | ashcherbyna/Automation-Courses-Home-Work | 595de0ed601de49df9299a84a5a5dbff4fab0223 | 22e740a72f348c7ebd931bde4bcf634c4e03d6e5 |
refs/heads/master | <file_sep>
# 实现对近几年国家统计局公布的房价指数进行爬取
# 用法
## cd ScrapyHouseIndex
## scrapy crawl priceWave -o price.csv
<file_sep>#coding:utf8
import scrapy
from houseWave.items import HousewaveItem
from scrapy_splash import SplashRequest
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class ScrapeGovhousePriceSpider(scrapy.Spider):
name = "priceWave"
#减慢爬取速度,防止被ban
download_delay = 2
start_urls = [
#尝试了 必须是page=1
'http://www.stats.gov.cn/was5/web/search?page=1&channelid=288041&was_custom_expr=like%28%E4%BD%8F%E5%AE%85%E9%94%80%E5%94%AE%E4%BB%B7%E6%A0%BC%E6%8C%87%E6%95%B0%29%2Fsen&perpage=10&outlinepage=10',
]
#log the info
# scrapy.log.start(logfile="./log", loglevel=None, logstdout=False)
def start_requests(self):
for url in self.start_urls:
# yield SplashRequest(url, self.parse, args={'wait':1}) #ok
yield scrapy.Request(url, meta={
'splash': {
'args': {
# set rendering arguments here
'html': 1,
'png': 1,
'wait':1,
},
}
})
#2017年4月份70个大中城市住宅销售价格变动情况
# print u"=========入库====="
def parse(self, response):
print u"执行的url",response.url
lists = response.xpath('//li')
# print response.body
urlLists = []
for quote in lists:
#首先找到住宅销售价格变动的所有月份的网页
href = quote.xpath('./span[@class="cont_tit"]/font[@class="cont_tit03"]/a/@href').extract_first()
title = quote.xpath('./span[@class="cont_tit"]/font[@class="cont_tit03"]/a/text()').extract_first()
if href is not None and title is not None:
# print u'标题',title
name = re.findall(ur"\d{4}年\d+月份\d+.*?住宅.*?",title)
if len(name) > 0:
# if href == 'http://www.stats.gov.cn/tjsj/zxfb/201611/t20161118_1430920.html':
yield scrapy.Request(href, callback = self.getIndex,meta={'title':title})
"""
解析下一个网页的所有链接
"""
# print u'执行parse的url',response.url
next_page_url = response.xpath(u'//li/dl/a[@class="next-page"]/@href').extract_first()
urlhead = 'http://www.stats.gov.cn/was5/web/'
# print u"下一个网页",urlhead+next_page_url
if next_page_url is not None:
#此时应该可以配置headers等参数
yield scrapy.Request(urlhead+next_page_url, meta={
'splash': {
'args': {
# set rendering arguments here
'html': 1,
'png': 1,
'wait':2,
},
}
})
#处理得到城市第三个元素即当月的环比指数
def getIndex(self, response):
#找到合适的值
item = HousewaveItem()
lists = response.xpath('//table[@class="MsoNormalTable"]')
title = response.meta['title']
year = re.findall(r"\d+",title)[0]
month = re.findall(r"\d+",title)[1]
# print u'链接地址',response.url
"""
遍历该网页中所有的表格
"""
for i in range(len(lists)):
# 70个大中城市新建住宅价格指数
table_title = lists[i].xpath('.//tbody/tr[1]/td/p/b/span/text()').extract()
# print u'表头',table_title
if len(table_title) > 0:
"""
找到数据的开始行
"""
name = re.findall(ur"大中城市新建商品住宅价格指数|大中城市二手住宅价格指数",table_title[-1])
irow = 1 # 对每个表的行计数
# print u'表头==',name
if len(name)>0:
# print u'name表格标题',name
if ('大中城市新建商品住宅价格指数' in name[0]) == True:
dataType = 'new'
if ('大中城市二手住宅价格指数' in name[0])==True:
dataType = 'old'
# break
# print u'name表格标题',dataType
#找到北京所在的行开始往下找
allrows = lists[i].xpath('.//tbody/tr')
# print u"数据",dataType,allrows
if allrows is not None:
for row in allrows:
row = row.xpath('./td/p/span/text()').extract()
# print u"行数据",row
rowinfo = self.deal_key(row)
if ('北京' in rowinfo or '北' in rowinfo) == True:
break
irow += 1
# print u"北京姑",irow
"""
提取每行的数据
"""
path ='.//tbody/tr[position()>=' + str(irow) + ']'
allrows = lists[i].xpath(path)
# print u"数据",dataType,irow
for erow in allrows:
#'./td/p/span/text()|./td/p/span/font/text()' #兼容2015-5,7,9
path = './td[position()<=4]/p/span/text()|./td[position()<=4]/p/span/font/text()'
rowinfo = erow.xpath(path).extract()
# print 'rowinfo',rowinfo
key,value = self.deal_info(rowinfo[:-3],rowinfo[-3:][0])
# print rowinfo
# print u'城市',key
if '北'==key:
key = '北京'
item['city'] = key
item['index'] = value
item['types'] = dataType
item['year'] = year
item['month'] = month
yield item
path = './td[position()>4]/p/span/text()|./td[position()>4]/p/span/font/text()'
rowinfo = erow.xpath(path).extract()
key,value = self.deal_info(rowinfo[:-3],rowinfo[-3:][0])
item['city'] = key
item['index'] = value
item['types'] = dataType
item['year'] = year
item['month'] = month
yield item
def getItem(key, value, dataType, year, month):
##return every item instance
item = HousewaveItem()
item['city'] = key
item['index'] = value
item['types'] = dataType
item['year'] = year
item['month'] = month
yield item
def deal_key(self, key):
keys = ''
for k in key:
keys += k
# print u'二手房房价',re.findall(ur"<a.*?infodesc .*?>.*?[\u4e00-\u9fa5]+.*?<\/a>",str)
keys = re.findall(ur"[\u4e00-\u9fa5]+",keys)
cz = ''
for k in keys:
cz += k
return cz
def deal_info(self, key, value):
# print key, value
keys = ''
for k in key:
keys += k
# print u'二手房房价',re.findall(ur"<a.*?infodesc .*?>.*?[\u4e00-\u9fa5]+.*?<\/a>",str)
keys = re.findall(ur"[\u4e00-\u9fa5]+",keys)
cz = ''
for k in keys:
cz += k
# print u'键',key
# print u'值',value
# print u'key主键',keys
value = float(value)
return cz, value
#要弄懂scrapy中的 item到底怎么用?
# http://www.runoob.com/xpath/xpath-syntax.html
# http://blog.csdn.net/zcc_0015/article/details/52274996
# http://blog.csdn.net/haipengdai/article/details/48654083
# https://segmentfault.com/q/1010000003814607
# http://izhaoyi.top/about/
#http://www.cnblogs.com/zhonghuasong/p/5976003.html
#http://blog.csdn.net/zistxym/article/details/42918339
#解决docker安装问题
#https://segmentfault.com/q/1010000007206051/a-1020000007219088
# http://jingyan.baidu.com/article/2c8c281db408940008252a02.html
#日志问题
#http://www.stats.gov.cn/tjsj/zxfb/201501/t20150118_670296.html
#上个网页的数据出现第一列竟然找不到北京两个字
#http://www.stats.gov.cn/tjsj/zxfb/201404/t20140418_541217.html
#这个数据有问题 | 3e652f8692ae080128325be8fa00ff16916db2d3 | [
"Markdown",
"Python"
] | 2 | Markdown | tianshanchuan/ScrapyHouseIndex | 5c671538aa71e0a5bcef73174c2b53c578dc5d59 | dc2609034a751c27b56efe724f89e467f9d0937f |
refs/heads/main | <file_sep>const express = require('express');
const Router = express.Router();
const productModule = require('./src/modules/products');
const orderModule = require('./src/modules/orders');
Router.route('/products')
.get((req, res) => {
productModule.getProducts(req)
.then(data => res.json(data));
})
.post((req, res) => {
productModule.postProduct(req.body)
.then(data => res.json(data))
})
Router.route('/orders')
.post((req, res) => {
orderModule.postOrder(req.body)
.then(data => res.json(data))
})
module.exports = Router;<file_sep>const products = [
{"id": '1', "name": 'Cookies', "price": 2.99},
{"id": '2', "name": 'Bread', "price": 2.00},
{"id": '3', "name": 'Orange Juice', "price": 5.00},
]
exports.getProducts = async function() {
const data = products;
return data;
}
exports.postProduct = async function(product) {
const data = products;
try {
data.push({
id: product.id,
name: product.name,
price: product.price
})
return data;
}
catch (error) {
console.log(error);
}
}<file_sep>var assert = require('assert');
var sinon = require('sinon');
const orderModule = require('../src/modules/orders');
describe('postOrder', () => {
it('If post order - should return total order amount', async () => {
sinon.stub(orderModule, 'postOrder').returns(orderPostedMockData);
const result = await orderModule.postOrder(orderMockData);
assert.deepEqual(result.totalAmountOrder, 2);
});
it('If post order with product id does not exists - should return zero to total product amount', async () => {
sinon.stub(orderModule, 'postOrder').returns(orderWithNoProductPostedMockData);
const result = await orderModule.postOrder(orderNoProductMockData);
assert.deepEqual(result.request_order[0].totalAmountProduct, 0);
})
});
const orderMockData = [{"product_id":"id-01",
"quantity": 2
}];
const orderNoProductMockData = [{"product_id":"id-99",
"quantity": 2
}];
const orderWithNoProductPostedMockData = {
"request_order": [{
"product_id": "id-99",
"quantity": 2,
"totalAmountProduct": 0
}],
"totalAmountOrder": 0
}
const orderPostedMockData = {
"request_order": [{
"product_id": "id-01",
"quantity": 2,
"totalAmountProduct": 2
}],
"totalAmountOrder": 2
}
beforeEach(function () {
sinon.restore();
})
<file_sep>There are two projects in the directory:
- app
This contains the web application created in React JS.
URL - http://localhost:3000
Run the following to display the app:
npm install
npm start
- services
This contains the API services created in NodeJS using Node express.
APIs
- GET products -
This service return the list of products
Payload:
GET http://localhost:3001/api/products
- POST products -
This service add to the original list of products and return the new list
Payload:
POST http://localhost:3001/api/products
{
"id": "1",
"name": "description",
"price": 1
}
- POST orders -
This service post the list of orders with total of product per order and the total amount of all the orders
Payload:
POST http://localhost:3001/api/orders
[{"product_id":"1",
"quantity": 1
},
{"product_id": "2",
"quantity": 1
}]
Run the api:
npm install
node index.js
To run the unittest:
npm run test
| 22081cb856e3d7a28859e47ffa270691bb42b256 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | khloe19/fitsybox-exam | 04c106c17ac8f5f809528796b6e05b0d1839c2b2 | 317a1afba56c40e9c2e9a5d367d646a3af9048c9 |
refs/heads/main | <repo_name>felipeferreira1/percentual_titulos_publicos_pp<file_sep>/Percentual - Títulos Públicos em Poder do Público.R
#Rotina para coletar e calcular o percentual de títulos públicos em poder do público
#Feito por: <NAME>
#última atualização: 13/11/2019
#Definindo diretórios a serem utilizados
getwd()
setwd("C:/Users/User/Documents")
#Carregando pacotes que serão utilizados
library(tidyverse)
library(data.table)
library(RQuantLib)
library(zoo)
library(rio)
library(lubridate)
library(ggplot2)
library(scales)
library(ggrepel)
#Definindo argumentos da coleta
abertura = "D" #D (dia) ou M (mês) ou A (ano)
indice = "M" #M para valores em R$ milhões, R para valores em Reais, S para valores US$ milhões ou U para valores em US$
formato = "A" #A (CSV) ou T (tela) ou E (Excel)
data_inicial = "2020-01-01" %>% as.Date()
data_final = as.Date(Sys.time())
#Criando lista com últimos dias úteis do mês
lista_dias <- c(data_inicial, data_final) #Lista com data do início do ano e data de hoje
dias_uteis <- seq(lista_dias[1], lista_dias[2], by="1 day") #Calculando quais são os dias entre essas duas datas
dias_uteis <- data.frame(dates=dias_uteis, bizday=isBusinessDay("Brazil", dias_uteis)) #Marcando quais desses dias são úteis
dias_uteis <- filter(dias_uteis, bizday == "TRUE") #Filtrando só os dias úteis
dias_uteis <- data.table(dias_uteis) #Transformando em data.table
dias_uteis <- dias_uteis %>% mutate(lista_dias = tapply(dias_uteis$dates, as.yearmon(dias_uteis$dates))) #Criando coluna com a lista_dias
#Como a referência de um mês é o último dia útil do mês anterior, vamos pegar todo primeiro dia útel dos meses (para identificar) e o último dia útil do mês anterior(para ser a referência na busca) de cada mês
ultimo_dia_util <- dias_uteis[,tail(.SD,1),by = lista_dias] #Selecionando o último dia útil de cada mês
ultimo_dia_util <- as.array(ultimo_dia_util$dates) #Transformando em vetor
ultimo_dia_util[length(ultimo_dia_util)] <- format(Sys.time()) #Adicionando dia de hoje
ultimo_dia_util <- format(ultimo_dia_util, "%d/%m/%Y") #Formatando como datas "dd/mm/YYYY"
primeiro_dia_util <- dias_uteis[,head(.SD,1),by = lista_dias] #Selecionando o primeiro dia útil de cada mês
primeiro_dia_util <- as.array(primeiro_dia_util$dates) #Transformando em vetor
dia_do_ultimo_dado <- as.Date(Sys.Date()) #Pegamos o dia do último dado, sabendo que a referência sempre será o dia útil imediatamente anterior
while (isBusinessDay("Brazil", dia_do_ultimo_dado) == F)
dia_do_ultimo_dado <- dia_do_ultimo_dado + 1
primeiro_dia_util[length(primeiro_dia_util) + 1 ] <- dia_do_ultimo_dado
primeiro_dia_util <- primeiro_dia_util[-1] #Tirando primeiro dado, já que a referência do 1º mês da da série é calculada tendo como referência o último dia útil do mês anterior
primeiro_dia_util <- format(primeiro_dia_util, "%d/%m/%Y") #Formatando como datas "dd/mm/YYYY"
#Criando lista com nome de arquivos
lista_nome_arquivos <- NULL #Vazia, a ser preenchida
#Coleta de dados
for (i in 1:length(ultimo_dia_util)){
dados <- read.csv(url(paste("http://www4.bcb.gov.br/pom/demab/cronograma/vencdata_csv.asp?data=", ultimo_dia_util[i], "&abertura=", abertura, "&indice=", indice, "&formato=", formato, sep="")),sep=";", skip = 3)
dados <- data.table(dados) #Transformando em data table para facilitar as manipulações
dados <- select(dados, Data = VENCIMENTO, Total = TOTAL, Participação = PART..) #Selecionando as colunas que vamos usar
dados$Data <- as.Date(dados$Data, "%d/%m/%Y") #Transformando a coluna de data em data
dados <- transform(dados, Total = as.numeric(gsub(",",".",Total))) #Transformando o resto das colunas em números
dados <- transform(dados, `Participação` = as.numeric(gsub(",",".",`Participação`))) #Transformando o resto das colunas em números
nome_arquivo <- paste("Ref_", gsub("/", "_", ultimo_dia_util[i]), sep = "") #Nomeia os vários arquivos intermediários que são criados com cada série
assign(nome_arquivo, dados) #Nomeando arquivos
lista_nome_arquivos[i] <- nome_arquivo #Guardando nome dos arquivos
if(i==1)
export(dados, "Percentual - Títulos Públicos em Poder do Público(fonte).xlsx", sheetName = nome_arquivo)
else
export(dados, "Percentual - Títulos Públicos em Poder do Público(fonte).xlsx", which = nome_arquivo)
print(paste(i, length(ultimo_dia_util), sep = '/')) #Printa o progresso da repetição
}
rm(dados)
#Calculando acumulados em 6 e 12 meses
filtros_6_meses <- ymd(as.Date(ultimo_dia_util, format = "%d/%m/%Y") %m+% months(6)) #Calculando 6 meses a frente
filtros_12_meses <- ymd(as.Date(ultimo_dia_util, format = "%d/%m/%Y") %m+% months(12)) #Calculando 12 meses a frente
acumulado_6_meses <- data.table(Data = as.Date(primeiro_dia_util, format = "%d/%m/%Y"), Acumulado = 0) #Criando data.table vazio
acumulado_12_meses <- data.table(Data = as.Date(primeiro_dia_util, format = "%d/%m/%Y"), Acumulado = 0) #Criando data.table vazio
for (i in 1:length(lista_nome_arquivos)){
acumulado <- get(lista_nome_arquivos[i]) #Chamando arquivos
acumulado <- filter(acumulado, Data < filtros_6_meses[i]) #Filtrando para datas < que 6 meses
acumulado <- sum(acumulado$Participação) #Calculando o acumulado pós-filtro
acumulado_6_meses[i,2] <- acumulado #Adicionando ao data.table de acumulados
print(paste(i, length(lista_nome_arquivos), sep = '/')) #Printa o progresso da repetição
}
export(acumulado_6_meses, "Percentual - Títulos Públicos em Poder do Público(fonte).xlsx", which = "Acum_6_meses")
for (i in 1:length(lista_nome_arquivos)){
acumulado <- get(lista_nome_arquivos[i]) #Chamando arquivos
acumulado <- filter(acumulado, Data < filtros_12_meses[i]) #Filtrando para datas < que 12 meses
acumulado <- sum(acumulado$Participação) #Calculando o acumulado pós-filtro
acumulado_12_meses[i,2] <- acumulado #Adicionando ao data.table de acumulados
print(paste(i, length(lista_nome_arquivos), sep = '/')) #Printa o progresso da repetição
}
export(acumulado_12_meses, "Percentual - Títulos Públicos em Poder do Público(fonte).xlsx", which = "Acum_12_meses")
#Gráficos
#Acumulado em 6 meses
graf_acum_6_meses <- ggplot(acumulado_6_meses, aes(x = Data, y = Acumulado)) + geom_bar(stat = "identity", fill = "darkblue") +
geom_label_repel(aes(label = sprintf("%0.2f", round(Acumulado,2))), force = 0.01) +
theme_minimal() + scale_x_date(breaks = date_breaks("1 month"), labels = date_format("%d/%b")) +
theme(axis.text.x=element_text(angle=45, hjust=1)) + xlab("") + ylab("") +
labs(title = "Vencimento de Títulos Federais em Poder do Público", subtitle = "Percentual da Dívida Total vencendo em até 6 meses",
caption = "Fonte: BCB")
ggsave("acumulado_6_meses.png", graf_acum_6_meses)
graf_acum_12_meses <- ggplot(acumulado_12_meses, aes(x = Data, y = Acumulado)) + geom_bar(stat = "identity", fill = "darkblue") +
geom_label_repel(aes(label = sprintf("%0.2f", round(Acumulado,2))), force = 0.01) +
theme_minimal() + scale_x_date(breaks = date_breaks("1 month"), labels = date_format("%d/%b")) +
theme(axis.text.x=element_text(angle=45, hjust=1)) + xlab("") + ylab("") +
labs(title = "Vencimento de Títulos Federais em Poder do Público", subtitle = "Percentual da Dívida Total vencendo em até 12 meses",
caption = "Fonte: BCB")
ggsave("acumulado_12_meses.png", graf_acum_12_meses) | 101a0215a84381a0a463132a334c0eb0daee1931 | [
"R"
] | 1 | R | felipeferreira1/percentual_titulos_publicos_pp | f5f9ecee7e607ec8240428d57ebfbb9d680e22e6 | 5b15acc1d83e3b3eed309b789ca39df48fc6ebaf |
refs/heads/master | <file_sep>
import Vapor
import Authentication
struct UsersController: RouteCollection {
func boot(router: Router) throws {
let usersRoute = router.grouped("api", "users")
usersRoute.get(use: getAllHandler)
usersRoute.get(User.Public.parameter, use: getUserHandler)
usersRoute.post(use: createUserHandler)
usersRoute.delete(User.parameter, use: deleteUserHandler)
usersRoute.get(User.parameter, "acronyms", use: getAcronymsHandler)
usersRoute.put(User.Public.parameter, use: editUserHandler)
let basicAuthMiddleware = User.basicAuthMiddleware(using: BCryptVerifier())
let basicAuthGroup = usersRoute.grouped(basicAuthMiddleware)
basicAuthGroup.post("login", use: loginHandler)
}
func createUserHandler(_ req: Request) throws -> Future<User> {
return try req.content.decode(User.self).flatMap(to: User.self) { user in
let hasher = try req.make(BCryptHasher.self)
user.password = try hasher.make(user.password)
return user.save(on: req)
}
}
func getAllHandler(_ req: Request) throws -> Future<[User.Public]> {
return User.Public.query(on: req).all()
}
func getUserHandler(_ req: Request) throws -> Future<User.Public> {
return try req.parameter(User.Public.self)
}
func deleteUserHandler(_ req: Request) throws ->Future<HTTPStatus> {
return try req.parameter(User.self).flatMap(to: HTTPStatus.self) { (user) in
return user.delete(on: req).transform(to: .noContent)
}
}
func getAcronymsHandler(_ req: Request) throws -> Future<[Acronym]> {
return try req.parameter(User.self).flatMap(to: [Acronym].self) { user in
return try user.acronyms.query(on: req).all()
}
}
func editUserHandler(_ req: Request) throws -> Future<User.Public> {
return try flatMap(to: User.Public.self, req.parameter(User.Public.self), req.content.decode(User.Public.self)) { user, updatedUser in
user.name = updatedUser.name
user.username = updatedUser.username
return user.save(on: req)
}
}
func loginHandler(_ req: Request) throws -> Future<Token> {
let user = try req.requireAuthenticated(User.self)
let token = try Token.generate(for: user)
return token.save(on: req)
}
}
<file_sep>import Vapor
import Leaf
import Authentication
struct WebsiteController: RouteCollection {
func boot(router: Router) throws {
let authSessionRoutes = router.grouped(User.authSessionsMiddleware())
authSessionRoutes.get(use: indexHandler)
authSessionRoutes.get("users", use: allUsersHandler)
authSessionRoutes.get("categories", use: allCategoriesHandler)
authSessionRoutes.get("acronyms", Acronym.parameter, use: acronymHandler)
authSessionRoutes.get("user", User.parameter, use: userHandler)
authSessionRoutes.get("category", Category.parameter, use: categoryHandler)
authSessionRoutes.get("login", use: loginHandler)
authSessionRoutes.post("login", use: loginPostHandler)
authSessionRoutes.get("signup", use: signupHandler)
authSessionRoutes.post("signup", use: signupPostHandler)
let protectedRoutes = authSessionRoutes.grouped(RedirectMiddleware<User>(path: "/login"))
protectedRoutes.get("create-acronym", use: createAcronymHandler)
protectedRoutes.post("create-acronym", use: createAcronymPostHandler)
protectedRoutes.get("acronyms", Acronym.parameter, "edit", use: editAcronymHandler)
protectedRoutes.post("acronyms", Acronym.parameter, "edit", use: editAcronymPostHandler)
protectedRoutes.post("acronyms", Acronym.parameter, "delete", use: delteAcronymHandler)
}
func indexHandler(_ req: Request) throws -> Future<View> {
return Acronym.query(on: req).all().flatMap(to: View.self) { acronyms in
let context = IndexContent(title: "Homepage", acronyms: acronyms.isEmpty ? nil : acronyms)
return try req.leaf().render("index", context)
}
}
func acronymHandler(_ req: Request) throws -> Future<View> {
return try req.parameter(Acronym.self).flatMap(to: View.self) { acronym in
return acronym.creator.get(on: req).flatMap(to: View.self) { creator in
return try acronym.categories.query(on: req).all().flatMap(to: View.self) { categories in
let context = AcronymContext(title: acronym.long, acronym: acronym, creator: creator, categories: categories.isEmpty ? nil : categories)
return try req.leaf().render("acronym", context)
}
}
}
}
func userHandler(_ req: Request) throws -> Future<View> {
return try req.parameter(User.self).flatMap(to: View.self) { user in
return try user.acronyms.query(on: req).all().flatMap(to: View.self) { acronyms in
let context = UserContext(title: user.name, user: user, acronyms: acronyms.isEmpty ? nil : acronyms)
return try req.leaf().render("user", context)
}
}
}
func allUsersHandler(_ req: Request) throws -> Future<View> {
return User.query(on: req).all().flatMap(to: View.self) { users in
let context = UsersContext(title: "All Users", users: users)
return try req.leaf().render("users", context)
}
}
func allCategoriesHandler(_ req: Request) throws -> Future<View> {
return Category.query(on: req).all().flatMap(to: View.self) { categories in
let context = CategoriesContext(title: "All Categories", categories: categories)
return try req.leaf().render("categories", context)
}
}
func categoryHandler(_ req: Request) throws -> Future<View> {
return try req.parameter(Category.self).flatMap(to: View.self) { category in
return try category.acronyms.query(on: req).all().flatMap(to: View.self) { acronyms in
let context = CategoryContext(title: category.name, acronyms: acronyms.isEmpty ? nil : acronyms)
return try req.leaf().render("category", context)
}
}
}
func createAcronymHandler(_ req: Request) throws -> Future<View> {
let context = CreateAcronymContext(title: "Create An Acronym")
return try req.leaf().render("createAcronym", context)
}
func createAcronymPostHandler(_ req: Request) throws -> Future<Response> {
return try req.content.decode(AcronymPostData.self).flatMap(to: Response.self) { data in
let user = try req.requireAuthenticated(User.self)
let acronym = try Acronym(short: data.acronymShort, long: data.acronymLong, creatorID: user.requireID())
return acronym.save(on: req).map(to: Response.self) { acronym in
guard let id = acronym.id else {
return req.redirect(to: "/")
}
return req.redirect(to: "/acronyms/\(id)")
}
}
}
func editAcronymHandler(_ req: Request) throws -> Future<View> {
return try req.parameter(Acronym.self).flatMap(to: View.self) { acronym in
let context = EditAcronymContext(title: "Edit Acronym", acronym: acronym)
return try req.leaf().render("createAcronym", context)
}
}
func editAcronymPostHandler(_ req: Request) throws -> Future<Response> {
return try flatMap(to: Response.self, req.parameter(Acronym.self), req.content.decode(AcronymPostData.self)) { acronym, data in
acronym.short = data.acronymShort
acronym.long = data.acronymLong
acronym.creatorID = try req.requireAuthenticated(User.self).requireID()
return acronym.save(on: req).map(to: Response.self) { acronym in
guard let id = acronym.id else {
return req.redirect(to: "/")
}
return req.redirect(to: "/acronyms/\(id)")
}
}
}
func delteAcronymHandler(_ req: Request) throws -> Future<Response> {
return try req.parameter(Acronym.self).flatMap(to: Response.self) { acronym in
return acronym.delete(on: req).transform(to: req.redirect(to: "/"))
}
}
func loginHandler(_ req: Request) throws -> Future<View> {
let context = LoginContext(title: "Log Innn")
return try req.leaf().render("login", context)
}
func loginPostHandler(_ req: Request) throws -> Future<Response> {
return try req.content.decode(LoginPostData.self).flatMap(to: Response.self) { data in
let verifier = try req.make(BCryptVerifier.self)
return User.authenticate(username: data.username, password: <PASSWORD>, using: verifier, on: req).map(to: Response.self) { user in
guard let user = user else {
return req.redirect(to: "/login")
}
try req.authenticateSession(user)
return req.redirect(to: "/")
}
}
}
func signupHandler(_ req: Request) throws -> Future<View> {
let context = SignupContext(title: "Sign Up")
return try req.leaf().render("signup", context)
}
func signupPostHandler(_ req: Request) throws -> Future<Response> {
return try req.content.decode(SignupPostData.self).flatMap(to: Response.self) { data in
guard data.password != "", data.password == <PASSWORD> else {
return Future<Response>.init(req.redirect(to: "/signup"))
}
let hasher = try req.make(BCryptHasher.self)
let hashedPassword = try hasher.make(data.password)
let user = User(name: data.name, username: data.username, password: hashedPassword)
return user.save(on: req).map(to: Response.self, { user in
try req.authenticateSession(user)
return req.redirect(to: "/")
})
}
}
}
extension Request {
func leaf() throws -> LeafRenderer {
return try self.make(LeafRenderer.self)
}
}
struct SignupPostData: Content {
let name: String
let username: String
let password: String
let password2: String
}
struct SignupContext: Encodable {
let title: String
}
struct LoginContext: Encodable {
let title: String
}
struct LoginPostData: Content {
let username: String
let password: String
}
struct CategoryContext: Encodable {
let title: String
let acronyms: [Acronym]?
}
struct CategoriesContext: Encodable {
let title: String
let categories: [Category]
}
struct UsersContext: Encodable {
let title: String
let users: [User]
}
struct IndexContent: Encodable {
let title: String
let acronyms: [Acronym]?
}
struct AcronymContext: Encodable {
let title: String
let acronym: Acronym
let creator: User
let categories: [Category]?
}
struct UserContext: Encodable {
let title: String
let user: User
let acronyms: [Acronym]?
}
struct CreateAcronymContext: Encodable {
let title: String
}
import Foundation
struct AcronymPostData: Content {
static let defaultMediaType = MediaType.urlEncodedForm
let acronymLong: String
let acronymShort: String
}
struct EditAcronymContext: Encodable {
let title: String
let acronym: Acronym
let editing = true
}
| db5b371ee42ec395ee41d068c9a31ca6b0dc12db | [
"Swift"
] | 2 | Swift | h1m5/TILApp | 855888420c16021ba6b7784ff664baac430f1230 | 3b8b6f058be03124f0ed41efef102503d7316f60 |
refs/heads/master | <file_sep>import { version } from 'react/package.json';
type SemVer = [ number, number, number ];
const semVer: SemVer = version.split('.').map(
(i: string): number => parseInt(i, 10),
) as SemVer;
const [ major, minor ] = semVer;
export const hasContext = (
major > 16 ||
(
major === 16 &&
minor >= 3
)
);
export const hasHooks = (
major > 16 ||
(
major === 16 &&
minor >= 8
)
);
| d64217bf1729ae3304fbfad036644bfbabec5d1a | [
"TypeScript"
] | 1 | TypeScript | umbertoghio/reactn | 694e22d922e83a0f8029f212b6de6bd37d609dba | 9a8b7d1823b9563287eee5ff359b08c2460e6cfb |
refs/heads/master | <repo_name>enilsson18/IncompressibleFluidSimulation<file_sep>/IncompressibleFluidSimulation/Quad.cpp
#include "Quad.h"
void Quad::render()
{
unsigned int VBO;
unsigned int VAO;
float vertices[] = {
// positions // texture Coords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindVertexArray(0);
}
<file_sep>/README.md
# Incompressible Fluid Simulation
## About
This Project was made in C++ through Visual Studios with the help of OpenGL and GLFW. The goal of the project is to implement an incompressible fluid simulator and put a unique spin on it.
### Resources
* https://www.youtube.com/watch?v=alhpH6ECFvQ&ab_channel=TheCodingTrain
* https://www.karlsims.com/fluid-flow.html
* https://www.khanacademy.org/math/multivariable-calculus
This is a learning project and thus heavily used other resources as references for the hard math and algorithms involved in Fluid Simulations.
# Controls
## Sim Window
* Move your mouse around the screen while left clicking to add fluid to the simulation
* Press Space to freeze the simulation (You may use your mouse to add particles to the sim during this freeze time).
* Press C to clear the simulation.
## Console
Here is a complete command list:
* "help" - Displays a list of all the commands.
* "clear" - Clears the sim of all fluid density particles and or tracers.
* "get fps" - Outputs the sim's current fps to the console.
* "get res" - Outputs the resolution of the simulation.
* "get dt" - Outputs the timestep of the simulation.
* "get visc" - Outputs the viscosity of the fluid.
* "get diff" - Outputs the diffusion of the fluid.
* "get iter" - Outputs the number of times a pressure gradient is normalized.
* "set tracers enabled" - Enables the addition of tracers to the sim.
* "set tracers disabled" - Disables the addition of tracers to the sim and removes all existing tracers.
* "set colors enabled" - Enables traditional RGB channels in the fluid sim.
* "set colors disabled" - Turns the simulation to a single color channel which is between white and black.
* "set blur enabled" - Blurs the fluid sim graphics to create a smoother picture.
* "set blur disabled" - Tells the simulation to render graphics normally.
* "freeze velocity" - Stops the velocity map from updating so you can see the density shift alone.
* "unfreeze velocity" - Resumes normal velocity processing.
Set Values for simulation by entering a number in place of #:
* "set res #" - Sets the resolution for the simulation.
* "set dt #.#" - Sets the timestep of the simulation.
* "set visc #.#" - Sets the viscosity of the fluid.
* "set diff #.#" - Sets the diffusion of the fluid.
* "set iter #" - Sets the number of times a pressure gradient is normalized.<file_sep>/IncompressibleFluidSimulation/BlurGL.cpp
#include "BlurGL.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <shader.h>
#include "RenderObject.h"
#include "Quad.h"
BlurGL::BlurGL()
{
shader = Shader("resources/shaders/gausian_blur.vs", "resources/shaders/gausian_blur.fs");
}
BlurGL::BlurGL(int width, int height)
{
shader = Shader("resources/shaders/gausian_blur.vs", "resources/shaders/gausian_blur.fs");
setup(width, height);
}
void BlurGL::setup(int width, int height) {
this->width = width;
this->height = height;
// clear just incase this is a reinitialization
glDeleteFramebuffers(1, &FBOX);
glDeleteFramebuffers(1, &FBOY);
glDeleteTextures(1, &outX);
glDeleteTextures(1, &outY);
//x values
//make the shadow buffer and bind it to quad fbo
glGenFramebuffers(1, &FBOX);
//create an image representing base depth buffer
glGenTextures(1, &outX);
glBindTexture(GL_TEXTURE_2D, outX);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, NULL);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//bind the buffer
glBindFramebuffer(GL_FRAMEBUFFER, FBOX);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, outX, 0);
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//y values
//make the shadow buffer and bind it to quad fbo
glGenFramebuffers(1, &FBOY);
//create an image representing base depth buffer
glGenTextures(1, &outY);
glBindTexture(GL_TEXTURE_2D, outY);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_FLOAT, NULL);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//bind the buffer
glBindFramebuffer(GL_FRAMEBUFFER, FBOY);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, outY, 0);
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
unsigned int &BlurGL::process(int width, int height, unsigned int &inputTex,int blurIterations)
{
// stop if no more
if (blurIterations < 1) { return outY; }
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// check if the window size has changed or this is the first iteration
if (isSizeInvalid(width, height)) {
setup(width, height);
}
//enter the gausian blur buffer phase
//render the current information to a quad and then send that data to the shader
//x axis
glBindFramebuffer(GL_FRAMEBUFFER, FBOX);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
shader.setInt("stage", 0);
shader.setFloat("textureWidth", width);
shader.setFloat("textureHeight", height);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, inputTex);
Quad::render();
//y axis
glBindFramebuffer(GL_FRAMEBUFFER, FBOY);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
shader.setInt("stage", 1);
shader.setFloat("textureWidth", width);
shader.setFloat("textureHeight", height);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, outX);
Quad::render();
// reset buffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// process more iterations if specified (if blurIterations - 1 is 0 or less then it will just return outY)
return process(this->width, this->height, outY, blurIterations - 1);
}
unsigned int &BlurGL::getBlur() {
return outY;
}
bool BlurGL::isSizeInvalid(int width, int height) {
if (this->width != width || this->height != height) {
return true;
}
return false;
}
<file_sep>/IncompressibleFluidSimulation/BlurGL.h
#pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <img/stb_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <shader.h>
#include "RenderObject.h"
class BlurGL {
public:
Shader shader;
unsigned int FBOX;
unsigned int FBOY;
unsigned int outX;
unsigned int outY;
int width;
int height;
float strength;
BlurGL();
BlurGL(int width, int height);
void setup(int width, int height);
unsigned int &process(int width, int height, unsigned int &inputTex, int blurIterations = 1);
unsigned int &getBlur();
bool isSizeInvalid(int width, int height);
};<file_sep>/IncompressibleFluidSimulation/RenderObject.cpp
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "RenderObject.h"
RenderObject::RenderObject() {
data = nullptr;
glGenBuffers(1, &VBO);
glGenVertexArrays(1, &VAO);
}
void RenderObject::allocateMemory(int size) {
if (data != nullptr) {
delete[] data;
}
data = new float[size];
}<file_sep>/IncompressibleFluidSimulation/Quad.h
#pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <img/stb_image.h>
//idk but manually importing fixes the problem
//#include <img/ImageLoader.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <shader.h>
#include <vector>
#include <string>
#include <iostream>
static class Quad {
public:
static void render();
};
<file_sep>/IncompressibleFluidSimulation/FluidBox.h
#pragma once
// basic
#include <iostream>
// vector and math lib
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <vector>
struct DynamicVector {
// (access dim, y, x)
std::vector<std::vector<std::vector<float>>> vector;
DynamicVector(int x_size, int y_size, float default_value = 0) {
vector = std::vector<std::vector<std::vector<float>>>(2, std::vector<std::vector<float>>(y_size, std::vector<float>(x_size, default_value)));
}
std::vector<std::vector<float>> &getXList() {
return vector[0];
}
std::vector<std::vector<float>> &getYList() {
return vector[1];
}
glm::vec2 getVec(int x, int y) {
return glm::vec2(vector[0][y][x], vector[1][y][x]);
}
glm::vec2 getVec(glm::vec2 vec) {
int x = (int) vec.x;
int y = (int) vec.y;
return getVec(x, y);
}
};
struct Tracer {
glm::vec2 pos;
glm::vec3 color;
Tracer(glm::vec2 pos, glm::vec3 color) {
this->pos = pos;
this->color = color;
}
};
class FluidBox {
public:
// settings
int size;
float dt;
float diff;
float visc;
float divIter;
int updateCount = 0;
bool velocityFrozen;
// runtime vars
// density (one is the previous stored value and the other is the current value)
// First dimension refers to rgb
std::vector<std::vector<std::vector<float>>> prevDensity;
std::vector<std::vector<std::vector<float>>> density;
// Color Tracers (Each array contains the rgb float values "0-255")
std::vector<Tracer> tracers;
// velocity
DynamicVector* velocityPrev;
DynamicVector* velocity;
FluidBox(int size, float diffusion, float viscosity, float dt);
void update();
void resetSize(int size);
void enforceBounds(std::vector<std::vector<float>> &v, int dim = 1);
void removeDivergence(std::vector<std::vector<float>> &v, std::vector<std::vector<float>> &vPrev, float a, float c, int b);
void diffuse(std::vector<std::vector<float>> &v, std::vector<std::vector<float>> &vPrev, int b);
void project(std::vector<std::vector<float>> &vx, std::vector<std::vector<float>> &vy, std::vector<std::vector<float>> &p, std::vector<std::vector<float>> &div);
void advect(int b, std::vector<std::vector<float>> &vx, std::vector<std::vector<float>> &vy, std::vector<std::vector<float>> &d, std::vector<std::vector<float>> &d0);
void updateTracers();
void calcUpstreamCoords(float Nfloat, float vx, float vy, float dtx, float dty, int i, int j, float &i0, float &i1, float &j0, float &j1, float &s0, float &s1, float &t0, float &t1);
void fadeDensity(float increment, float min, float max);
void addTracer(glm::vec2 pos, glm::vec3 color);
void addDensity(glm::vec2 pos, float amount, glm::vec3 color = glm::vec3(1.0f));
void addVelocity(glm::vec2 pos, glm::vec2 amount);
void freezeVelocity();
void unfreezeVelocity();
bool getFreezeVelocity();
void clear();
glm::vec3 getColorAtPos(glm::vec2 pos);
std::vector<Tracer>& getTracers();
std::vector<std::vector<Tracer*>> generateTracerMap();
};<file_sep>/LibResources/include/img/ImageLoader.cpp
#define STB_IMAGE_IMPLEMENTATION
#include "ImageLoader.h"
#include "stb_image.h"
#include <glad/glad.h>
#include <GLFW\glfw3.h>
#include <string>
#include <iostream>
class DataLoader {
static bool load(std::string url) {
bool toReturn;
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// set the texture wrapping/filtering options (on the currently bound texture object)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load and generate the texture
int width, height, nrChannels;
unsigned char *data = stbi_load("container.jpg", &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
toReturn = true;
}
else
{
std::cout << "Failed to load texture" << std::endl;
toReturn = false;
}
stbi_image_free(data);
return toReturn;
}
};<file_sep>/LibResources/include/img/ImageLoader.h
#include <iostream>
#include <string>
class ImageLoader {
public:
static bool load(std::string url);
};<file_sep>/IncompressibleFluidSimulation/Main.cpp
#include <iostream>
#include <thread>
// utility
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <shader.h>
#include <tuple>
#include <windows.h>
#include <future>
#include <thread>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include "FluidBox.h"
#include "RenderObject.h"
#include "BlurGL.h"
#include "Quad.h"
using namespace std;
// settings
int resolution = 150;
double fps = 60;
// control settings
bool enableTracers = false;
bool enableColor = true;
bool enableBlur = true;
int blurIterations = 10;
string commandToRead;
std::atomic<bool> enteredCommand;
// status vars
int SCR_HEIGHT;
int SCR_WIDTH;
enum ControlMode { NONE = 0, DIRECTIONAL = 1, MOUSE_SWIPE = 2 };
struct MouseData {
bool pressedL;
bool pressedR;
bool dragging;
bool prevPressedL;
bool prevPressedR;
//glm::vec2 pressPos;
//glm::vec2 releasePos;
glm::vec2 currentPos;
glm::vec2 lastPos;
MouseData() {
pressedL = false;
pressedR = false;
//pressPos = glm::vec2(0);
//releasePos = glm::vec2(0);
currentPos = glm::vec2(0);
lastPos = glm::vec2(0);
}
void update() {
prevPressedR = pressedR;
prevPressedL = pressedL;
}
};
struct FPSCounter {
std::chrono::system_clock::time_point now;
int fpsCount;
int fpsCounter;
int updateInterval = 60;
int storedFPS;
FPSCounter() {
fpsCount = 0;
fpsCounter = 0;
storedFPS = 0;
}
void start() {
now = std::chrono::system_clock::now();
}
void end() {
//end of timer sleep and normalize the clock
std::chrono::system_clock::time_point after = std::chrono::system_clock::now();
std::chrono::microseconds difference(std::chrono::time_point_cast<std::chrono::microseconds>(after) - std::chrono::time_point_cast<std::chrono::microseconds>(now));
int diffCount = difference.count();
if (diffCount == 0) {
diffCount = 1;
}
// apply fps to average
fpsCount += 1;
fpsCounter += 1000000 / diffCount;
if (fpsCount % int(updateInterval) == 0) {
storedFPS = fpsCounter / fpsCount;
fpsCount = 0;
fpsCounter = 0;
}
}
void printFPS(bool sameLine = false) {
if (sameLine) { std::cout << "\r"; }
std::cout << "FPS: " << storedFPS;
if (!sameLine) { std::cout << std::endl; }
}
};
//prototypes
// callbacks
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
// fluid modifiers
void addDirectionalFluid(FluidBox& fluid, int brushSize = 5, float densityInc = 20.0f, float velocityInc = 0.01f, glm::vec2 pos = glm::vec2(100.0f, 100.0f), glm::vec2 dir = glm::vec2(1.0f, 0.0f), glm::vec3 color = glm::vec3(255));
void addMouseSwipeFluid();
void addBlop(glm::vec2 pos, int radius, float densityInc, float velocityInc);
void addMouseClickBlop();
// commands
string enterCommand();
std::vector<string> seperateStringBySpaces(string str);
void printProcessCommandResult(bool result);
bool processCommand(string command);
// methods
tuple<unsigned int, unsigned int> findWindowDims(float relativeScreenSize = 0.85, float aspectRatio = 1);
void setupBlurFBO();
void updateData(FluidBox &fluidBox, float* data);
void updateBuffers(RenderObject* renderObject);
void processControls(GLFWwindow* window, FluidBox& fluid, ControlMode& controlMode);
void updateForces(FluidBox& fluid);
void incrementColorIndex();
glm::vec2 getScalingVec();
glm::vec3 getColorSpect(float n, float m);
void containTracers(FluidBox& fluid, int min, int max);
bool constrain(glm::vec2& vec, float min, float max);
void constrain(float &num, float min, float max);
// Control structs
MouseData mouse;
// global stuff
// main vars
GLFWwindow* window;
FluidBox* fluid;
RenderObject* renderFluid;
Shader renderToQuad;
// fbo to give blur
BlurGL* blur;
unsigned int toBlurFBO;
unsigned int toBlur;
// control vars
ControlMode controlMode;
bool freeze;
FPSCounter timer;
// color stuff
int colorIndex;
int colorInc;
int colorSpectSize;
glm::vec3 defaultColor;
glm::vec3 tracerColor;
int tracerRadius;
// key trackers
bool fPressed;
void setup() {
fluid = new FluidBox(resolution, 0.0f, 0.0000001f, 0.4f);
controlMode = ControlMode::MOUSE_SWIPE;
freeze = false;
colorIndex = 0;
colorInc = 1;
colorSpectSize = 5;
defaultColor = glm::vec3(255);
tracerColor = glm::vec3(defaultColor);
tracerRadius = 0;
mouse = MouseData();
commandToRead = "";
enteredCommand.store(false);
fPressed = false;
// init graphics stuff
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
std::tie(SCR_WIDTH, SCR_HEIGHT) = findWindowDims(0.7f, 1.0f);
//SCR_WIDTH = 300;
//SCR_HEIGHT = 300;
// glfw window creation
window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Fluid Sim", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
}
glfwMakeContextCurrent(window);
// set callbacks
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
// glad: load all OpenGL function pointers
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
}
// main graphics setup
renderToQuad = Shader("resources/shaders/render_quad.vs", "resources/shaders/render_quad.fs");
blur = new BlurGL(SCR_WIDTH, SCR_HEIGHT);
setupBlurFBO();
// setup fluid render stuff
renderFluid = new RenderObject();
renderFluid->shader = Shader("resources/shaders/point_render.vs", "resources/shaders/point_render.fs", "resources/shaders/point_render.gs");
renderFluid->allocateMemory((resolution * resolution) * (2 + 3));
updateData(*fluid, renderFluid->data);
updateBuffers(renderFluid);
}
void setupBlurFBO() {
// clear just incase this is a reinitialization
glDeleteFramebuffers(1, &toBlurFBO);
glDeleteTextures(1, &toBlur);
//x values
//make the shadow buffer and bind it to quad fbo
glGenFramebuffers(1, &toBlurFBO);
//create an image representing base depth buffer
glGenTextures(1, &toBlur);
glBindTexture(GL_TEXTURE_2D, toBlur);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, SCR_WIDTH, SCR_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//bind the buffer
glBindFramebuffer(GL_FRAMEBUFFER, toBlurFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, toBlur, 0);
glEnable(GL_DEPTH_TEST);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void draw() {
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderFluid->shader.use();
renderFluid->shader.setFloat("sizeX", 2.0f / resolution);
renderFluid->shader.setFloat("sizeY", 2.0f / resolution);
glBindVertexArray(renderFluid->VAO);
glDrawArrays(GL_POINTS, 0, resolution * resolution);
}
void drawToBlur() {
// check if fbo needs to be updated based on the un-updated BlurGL parameters
if (blur->isSizeInvalid(SCR_WIDTH, SCR_HEIGHT)) {
setupBlurFBO();
}
// draw original output
glBindFramebuffer(GL_FRAMEBUFFER, toBlurFBO);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
draw();
// blur
unsigned int blurredOutput = blur->process(SCR_WIDTH, SCR_HEIGHT, toBlur, blurIterations);
// render blurred output
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderToQuad.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, blurredOutput);
Quad::render();
}
void updateFrame(FPSCounter& timer) {
timer.start();
processControls(window, *fluid, controlMode);
// update frame
if (!freeze) {
fluid->update();
fluid->fadeDensity(0.05f, 0, 255);
}
updateData(*fluid, renderFluid->data);
updateBuffers(renderFluid);
//draw
if (enableBlur) {
drawToBlur();
}
else {
draw();
}
mouse.update();
// update view
glfwSwapBuffers(window);
glfwPollEvents();
timer.end();
//timer.printFPS(true);
}
// store the command input and then signal the main thread that we are complete and can exit the program
string commandInputThread() {
std::cout << "Enter a command: ";
commandToRead = enterCommand();
enteredCommand.store(true);
return commandToRead;
}
int main() {
setup();
timer = FPSCounter();
//frameLoopThread(timer);
future<string> commandInput = std::async(std::launch::async, commandInputThread);
while (!glfwWindowShouldClose(window)) {
updateFrame(timer);
// if a command is sent then process, reset the command flag, and restart the async operation
if (enteredCommand.load()) {
bool out = processCommand(commandToRead);
printProcessCommandResult(out);
// reset vals
commandToRead = "";
enteredCommand.store(false);
commandInput = std::async(std::launch::async, commandInputThread);
}
}
glfwTerminate();
delete[] renderFluid->data;
return 0;
}
void listAllCommands() {
std::cout << "----- Commands -----" << std::endl;
std::cout <<
"help" << std::endl <<
"clear" << std::endl <<
"get fps" << std::endl <<
"get res" << std::endl <<
"get dt" << std::endl <<
"get visc" << std::endl <<
"get diff" << std::endl <<
"get iter" << std::endl <<
"get blur" << std::endl <<
"set tracers enabled" << std::endl <<
"set tracers disabled" << std::endl <<
"set colors enabled" << std::endl <<
"set colors disabled" << std::endl <<
"set blur enabled" << std::endl <<
"set blur disabled" << std::endl <<
"set res #" << std::endl <<
"set dt #.#" << std::endl <<
"set visc #.#" << std::endl <<
"set diff #.#" << std::endl <<
"set iter #" << std::endl <<
"set blur #" << std::endl <<
"freeze velocity" << std::endl <<
"unfreeze velocity" << std::endl;
std::cout << "--------------------" << std::endl;
}
// control methods
bool processCommand(string command) {
// process and desegment
// follows these steps
// 1. Seperate words based on spaces into a list.
// 2. Iterate down the list into a decision tree.
// 3. Run the proper identified command
std::vector<string> list = seperateStringBySpaces(command);
if (list.size() == 0) {
return false;
}
// command list
if (list[0] == "help") {
listAllCommands();
return true;
}
if (list[0] == "clear") {
(*fluid).clear();
return true;
}
if (list[0] == "set") {
if (list.size() > 1) {
if (list[1] == "tracers") {
if (list.size() > 2) {
if (list[2] == "enabled") {
enableTracers = true;
return true;
}
if (list[2] == "disabled") {
enableTracers = false;
return true;
}
}
}
if (list[1] == "colors") {
if (list.size() > 2) {
if (list[2] == "enabled") {
enableColor = true;
return true;
}
if (list[2] == "disabled") {
enableColor = false;
return true;
}
}
}
if (list[1] == "blur") {
if (list.size() > 2) {
if (list[2] == "enabled") {
enableBlur = true;
return true;
}
if (list[2] == "disabled") {
enableBlur = false;
return true;
}
}
}
if (list[1] == "resolution" || list[1] == "res") {
if (list.size() > 2) {
float num;
try {
num = std::stoi(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
constrain(num, 10, SCR_HEIGHT - 1);
resolution = num;
fluid->resetSize(resolution);
renderFluid->allocateMemory((resolution * resolution) * (2 + 3));
return true;
}
}
if (list[1] == "dt") {
if (list.size() > 2) {
float num;
try {
num = std::stof(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
fluid->dt = num;
return true;
}
}
if (list[1] == "viscosity" || list[1] == "visc") {
if (list.size() > 2) {
float num;
try {
num = std::stof(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
fluid->visc = num;
return true;
}
}
if (list[1] == "diffusion" || list[1] == "diff") {
if (list.size() > 2) {
float num;
try {
num = std::stof(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
fluid->diff = num;
return true;
}
}
if (list[1] == "div_iter" || list[1] == "iter") {
if (list.size() > 2) {
float num;
try {
num = std::stoi(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
fluid->divIter = num;
return true;
}
}
if (list[1] == "blur") {
if (list.size() > 2) {
float num;
try {
num = std::stoi(list[2]);
}
catch (std::invalid_argument err) {
return false;
}
blurIterations = num;
return true;
}
}
}
}
if (list[0] == "get") {
if (list.size() > 1) {
if (list[1] == "fps") {
timer.printFPS();
return true;
}
if (list[1] == "resolution" || list[1] == "res") {
std::cout << "Resolution: " << resolution << std::endl;
return true;
}
if (list[1] == "dt") {
std::cout << "dt: " << fluid->dt << std::endl;
return true;
}
if (list[1] == "viscosity" || list[1] == "visc") {
std::cout << "Viscosity: " << fluid->dt << std::endl;
return true;
}
if (list[1] == "diffusion" || list[1] == "diff") {
std::cout << "Diffusion: " << fluid->diff << std::endl;
return true;
}
if (list[1] == "div_iter" || list[1] == "iter") {
std::cout << "Divergence Iterations: " << fluid->divIter << std::endl;
return true;
}
if (list[1] == "blur") {
std::cout << "Blur Iterations: " << blurIterations << std::endl;
return true;
}
}
}
if (list[0] == "freeze") {
if (list.size() > 1) {
if (list[1] == "velocity") {
fluid->freezeVelocity();
return true;
}
}
}
if (list[0] == "unfreeze") {
if (list.size() > 1) {
if (list[1] == "velocity") {
fluid->unfreezeVelocity();
return true;
}
}
}
return false;
}
void printProcessCommandResult(bool result) {
if (result) {
//std::cout << "Command Executed Sucessfully" << std::endl;
}
else {
std::cout << "Command Executed Unsucessfully (type help for a list of all valid commands)" << std::endl;
}
std::cout << std::endl;
}
void processControls(GLFWwindow* window, FluidBox& fluid, ControlMode& controlMode) {
// process mouse input
if (mouse.pressedL) {
if (controlMode == ControlMode::MOUSE_SWIPE) {
addMouseSwipeFluid();
}
}
else if (mouse.prevPressedL){
incrementColorIndex();
}
// freeze velocity
if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) {
if (fPressed == false) {
if (fluid.getFreezeVelocity()) {
fluid.unfreezeVelocity();
}
else {
fluid.freezeVelocity();
}
}
fPressed = true;
}
else {
fPressed = false;
}
// clear screen controls
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS) {
fluid.clear();
}
// enter commands
if (glfwGetKey(window, GLFW_KEY_SLASH) == GLFW_PRESS) {
//string command = enterCommand();
//printProcessCommandResult(processCommand(command));
}
// process key input
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
// default values
freeze = false;
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) {
switch (controlMode) {
case 0:
break;
case 1:
addDirectionalFluid(fluid);
break;
case 2:
freeze = true;
break;
}
}
}
void addMouseSwipeFluid() {
// An arbitrary number used for scaling the addition of fluid
float densityMultiplier = 0.05f;
float velocityMultiplier = 0.0025f;
glm::vec2 scaling = getScalingVec();
// The distance between the mouse's current pos and its previous pos
float mouseDiff = glm::length((mouse.currentPos - mouse.lastPos) * scaling);
// solve for parameters of directional fluid
int brushSize = 10;
float densityInc = densityMultiplier * mouseDiff;
float velocityInc = velocityMultiplier * mouseDiff;
glm::vec2 position = mouse.currentPos * scaling;
glm::vec2 direction = (mouse.currentPos - mouse.lastPos) * scaling;
glm::vec3 color = getColorSpect(colorIndex, colorSpectSize);
addDirectionalFluid(*fluid, brushSize, densityInc, velocityInc, position, direction, color);
}
void addDirectionalFluid(FluidBox& fluid, int brushSize, float densityInc, float velocityInc, glm::vec2 pos, glm::vec2 dir, glm::vec3 color){
// create limits for the increments to prevent too much velocity being added (can make divergence unsolvable) and also limits the density
constrain(densityInc, 0, 50);
constrain(velocityInc, 0, 0.15f);
dir = glm::normalize(dir);
if (!enableColor) {
color = glm::vec3(defaultColor);
}
for (int y = -brushSize; y < brushSize; y++) {
for (int x = -brushSize; x < brushSize; x++) {
// make a circle for the density and velocity to be added
if (glm::length(glm::vec2(x, y)) <= brushSize) {
glm::vec2 cpos = glm::vec2(pos.x + x, pos.y + y);
// skip if the pos is out of bounds
if (!constrain(cpos, 1, fluid.size - 2)) {
fluid.addDensity(cpos, densityInc * (float(std::rand()) / INT_MAX + 0.5f), color);
if (!fluid.getFreezeVelocity()) {
fluid.addVelocity(cpos, velocityInc * dir);
}
}
}
}
}
if (enableTracers) {
fluid.addTracer(pos, tracerColor);
}
}
void containTracers(FluidBox& fluid, int min, int max) {
for (int y = 0; y < fluid.size; y++) {
for (int x = 0; x < fluid.size; x++) {
for (int i = 0; i < fluid.density.size(); i++) {
if (fluid.density[i][y][x] < min) {
fluid.density[i][y][x] = min;
}
if (fluid.density[i][y][x] > max) {
fluid.density[i][y][x] = max;
}
}
}
}
}
void updateData(FluidBox &fluidBox, float* data) {
int index = 0;
for (int y = 0; y < fluidBox.size; y++) {
for (int x = 0; x < fluidBox.size; x++) {
data[index] = float(x) / fluidBox.size;
data[index + 1] = float(y) / fluidBox.size;
//data[index + 2] = 0;
//data[index + 3] = 0;
//data[index + 4] = 0;
//float color = (fluidBox.density[y][x] / 255.0f);
//data[index + 2] = color;
//data[index + 3] = color;
//data[index + 4] = color;
// get color from the rgb density maps in the fluid sim
glm::vec3 color = fluidBox.getColorAtPos(glm::vec2(x,y));
data[index + 2] = color.x;
data[index + 3] = color.y;
data[index + 4] = color.z;
//float alpha = fluidBox.density[y][x] / 255.0f;
//glm::vec3 color = alpha * fluidBox.getColorAtPos(glm::vec2(x, y));
//data[index + 2] = color.x/255;
//data[index + 3] = color.y/255;
//data[index + 4] = color.z/255;
//data[index + 2] = fluidBox.density[y][x] / 255.0f;
//data[index + 3] = 1000 * abs(fluidBox.velocity->getXList()[y][x]) / 255.0f;
//data[index + 4] = 1000 * abs(fluidBox.velocity->getYList()[y][x]) / 255.0f;
//data[index + 2] = std::fmod(fluidBox.density[y][x] + 50, 200.0f) / 255.0f;
//data[index + 3] = 200 / 255.0f;
//data[index + 4] = fluidBox.density[y][x] / 255.0f;
index += 5;
}
}
// override color if a tracer is there
if (enableTracers) {
std::vector<Tracer> tracers = fluidBox.getTracers();
for (int i = 0; i < tracers.size(); i++) {
int x = tracers[i].pos.x;
int y = tracers[i].pos.y;
for (int iy = -tracerRadius; iy <= tracerRadius; iy++) {
for (int ix = -tracerRadius; ix <= tracerRadius; ix++) {
int newX = x + ix;
int newY = y + iy;
if (newX >= 0 && newX < resolution && newY >= 0 && newY < resolution) {
float length = glm::length(glm::vec2(ix, iy));
if (length <= tracerRadius) {
int index = (newY * (fluidBox.size) + newX) * 5;
float power = length / 2.0f;
if (power == 0) {
power = 1;
}
data[index + 2] = tracers[i].color.x * power;
data[index + 3] = tracers[i].color.y * power;
data[index + 4] = tracers[i].color.z * power;
}
}
}
}
}
}
}
void updateBuffers(RenderObject* renderObject) {
glBindVertexArray(renderObject->VAO);
glBindBuffer(GL_ARRAY_BUFFER, renderObject->VBO);
glBufferData(GL_ARRAY_BUFFER, ((resolution * resolution) * (2 + 3))*sizeof(float), renderObject->data, GL_STATIC_DRAW);
// position
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
// color
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(2 * sizeof(float)));
glBindVertexArray(0);
}
void incrementColorIndex() {
colorIndex = (colorIndex + colorInc) % colorSpectSize;
}
glm::vec2 getScalingVec() {
return glm::vec2(float(resolution) / SCR_WIDTH, float(resolution) / SCR_HEIGHT);
}
// sinusoidal color function
glm::vec3 getColorSpect(float n, float m) {
float PI = 3.14159265358979f;
float a = 5 * PI * n / (3 * m) + PI / 2;
float r = sin(a) * 192 + 128;
r = max(0, min(255, r));
float g = sin(a - 2 * PI / 3) * 192 + 128;
g = max(0, min(255, g));
float b = sin(a - 4 * PI / 3) * 192 + 128;
b = max(0, min(255, b));
return glm::vec3(r, g, b);
}
// command methods
string enterCommand() {
string command = "";
std::getline(std::cin, command);
return command;
}
std::vector<string> seperateStringBySpaces(string str) {
std::vector<string> list = std::vector<string>();
int startIndex = 0;
bool trackingString = false;
for (int i = 0; i < str.length(); i++) {
if (str[i] != ' ') {
if (!trackingString) {
startIndex = i;
trackingString = true;
}
}
else {
if (trackingString) {
list.push_back(str.substr(startIndex, i - startIndex));
trackingString = false;
}
}
}
if (trackingString) {
list.push_back(str.substr(startIndex, str.length() - startIndex));
}
return list;
}
// finds the optimal dimensions for the window
tuple<unsigned int, unsigned int> findWindowDims(float relativeScreenSize, float aspectRatio) {
// set window size to max while also maintaining size ratio
RECT rect;
GetClientRect(GetDesktopWindow(), &rect);
unsigned int SCR_WIDTH = (rect.right - rect.left) * relativeScreenSize;
unsigned int SCR_HEIGHT = (rect.bottom - rect.top) * relativeScreenSize;
return tuple<unsigned int, unsigned int>{SCR_HEIGHT, SCR_HEIGHT};
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// std::cout << "Failed to create GLFW window" << std::endl;
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on some displays
SCR_WIDTH = width;
SCR_HEIGHT = height;
glViewport(0, 0, width, height);
}
// clicking
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
mouse.pressedL = true;
}
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
mouse.pressedL = false;
}
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
mouse.pressedR = true;
}
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_RELEASE) {
mouse.pressedR = false;
}
}
// mouse movement
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
int winxpos, winypos;
glfwGetWindowPos(window, &winxpos, &winypos);
xpos = xpos;
ypos = -ypos + SCR_HEIGHT;
mouse.lastPos = mouse.currentPos;
mouse.currentPos = glm::vec2(xpos, ypos);
}<file_sep>/IncompressibleFluidSimulation/FluidBox.cpp
// basic
#include <iostream>
#include <algorithm>
#include "FluidBox.h"
// vector and math lib
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <vector>
using namespace std;
void constrain(int &num, int min, int max);
void constrain(float &num, float min, float max);
bool constrain(glm::vec2& vec, float min, float max);
FluidBox::FluidBox(int size, float diffusion, float viscosity, float dt) {
//setup(size, diffusion, viscosity, dt);
this->size = size;
this->diff = diffusion;
this->visc = viscosity;
this->dt = dt;
this->divIter = 25;
velocityFrozen = false;
// init 2d arrays
clear();
};
// the main update step
void FluidBox::update() {
vector<vector<float>>& vPrevXList = velocityPrev->getXList();
vector<vector<float>>& vPrevYList = velocityPrev->getYList();
vector<vector<float>>& vXList = velocity->getXList();
vector<vector<float>>& vYList = velocity->getYList();
if (!velocityFrozen) {
diffuse(vPrevXList, vXList, 1);
diffuse(vPrevYList, vYList, 2);
//project(vPrevXList, vPrevYList, vXList, vYList);
advect(1, vPrevXList, vPrevYList, vXList, vPrevXList);
advect(2, vPrevXList, vPrevYList, vYList, vPrevYList);
project(vXList, vYList, vPrevXList, vPrevYList);
}
// applys advection for each color channel
for (int i = 0; i < 3; i++) {
diffuse(prevDensity[i], density[i], 0);
advect(0, vXList, vYList, density[i], prevDensity[i]);
}
updateTracers();
//std::cout << velocity->getXList()[size / 2][size / 2] << std::endl;
//std::cout << simDensity[size / 2][size / 2] << std::endl;
}
void FluidBox::resetSize(int size) {
float scale = size/this->size;
int sizeToFit = min(this->size, size);
int prevSize = this->size;
this->size = size;
vector<vector<vector<float>>> tempPrevDensity = prevDensity;
vector<vector<vector<float>>> tempDensity = density;
vector<Tracer> tempTracers = tracers;
DynamicVector tempVelocityPrev = (*velocityPrev);
DynamicVector tempVelocity = (*velocity);
// reset to size
clear();
// copy data over into new array
// density
for (int i = 0; i < 3; i++) {
for (int y = 0; y < sizeToFit; y++) {
for (int x = 0; x < sizeToFit; x++) {
prevDensity[i][y][x] = tempPrevDensity[i][y][x];
density[i][y][x] = tempDensity[i][y][x];
}
}
}
// velocity
for (int i = 0; i < 2; i++) {
for (int y = 0; y < sizeToFit; y++) {
for (int x = 0; x < sizeToFit; x++) {
velocityPrev->vector[i][y][x] = tempVelocityPrev.vector[i][y][x];
velocity->vector[i][y][x] = tempVelocity.vector[i][y][x];
}
}
}
// tracers
for (int i = 0; i < tempTracers.size(); i++) {
glm::vec2 vec = tempTracers[i].pos;
constrain(tempTracers[i].pos, 0, sizeToFit);
addTracer(vec, tempTracers[i].color);
}
}
void FluidBox::enforceBounds(std::vector<std::vector<float>> &v, int dim) {
float reflectPower = 1.0f;
// x
if (dim == 1) {
for (int y = 1; y < v.size() - 1; y++) {
v[y][0] = -v[y][1] * reflectPower;
v[y][size - 1] = -v[y][size - 2] * reflectPower;
}
}
// y
if (dim == 2) {
for (int i = 1; i < size - 1; i++) {
v[0][i] = -v[1][i] * reflectPower;
v[size - 1][i] = -v[size - 2][i] * reflectPower;
}
}
// top left
v[0][0] = 0.5f * (v[0][1] + v[1][0]);
// top right
v[0][size-1] = 0.5f * (v[0][size-2] + v[1][size-1]);
// bottom right
v[size-1][size-1] = 0.5f * (v[size-1][size-2] + v[size-2][size-1]);
//bottom left
v[size-1][0] = 0.5f * (v[size-2][0] + v[size-1][1]);
}
// Accounts for divergence in the velocity vectors
void FluidBox::removeDivergence(std::vector<std::vector<float>> &v, std::vector<std::vector<float>> &vPrev, float a, float c, int b) {
float cRecip = 1 / c;
for (int i = 0; i < divIter; i++) {
for (int y = 1; y < size - 1; y++) {
for (int x = 1; x < size - 1; x++) {
// remove divergence for each coord
v[y][x] = (vPrev[y][x] +
a * (
v[y + 1][x] +
v[y - 1][x] +
v[y][x + 1] +
v[y][x - 1]
)
) * cRecip;
}
}
enforceBounds(v, b);
}
}
void FluidBox::diffuse(std::vector<std::vector<float>> &v, std::vector<std::vector<float>> &vPrev, int b) {
float a = dt * diff * (size - 2) * (size - 2);
removeDivergence(v, vPrev, a, 1 + 4 * a, b);
}
void FluidBox::project(std::vector<std::vector<float>> &vx, std::vector<std::vector<float>> &vy, std::vector<std::vector<float>> &p, std::vector<std::vector<float>> &div) {
for (int y = 1; y < size - 1; y++) {
for (int x = 1; x < size - 1; x++) {
div[y][x] = -0.5f*(
vx[y][x+1]
- vx[y][x-1]
+ vy[y+1][x]
- vy[y-1][x]
) / size;
p[y][x] = 0;
}
}
enforceBounds(p);
enforceBounds(div);
removeDivergence(p, div, 1, 4, 0);
for (int y = 1; y < size - 1; y++) {
for (int x = 1; x < size - 1; x++) {
vx[y][x] -= 0.5f * (p[y][x+1] - p[y][x-1]) * size;
vy[y][x] -= 0.5f * (p[y+1][x] - p[y-1][x]) * size;
}
}
enforceBounds(vx, 1);
enforceBounds(vy, 2);
}
void FluidBox::advect(int b, std::vector<std::vector<float>> &vx, std::vector<std::vector<float>> &vy, std::vector<std::vector<float>> &d, std::vector<std::vector<float>> &d0) {
float i0, i1, j0, j1;
float dtx = dt * (size - 2);
float dty = dt * (size - 2);
float s0, s1, t0, t1;
float Nfloat = size;
for (int j = 1; j < size - 1; j++) {
for (int i = 1; i < size - 1; i++) {
calcUpstreamCoords(Nfloat, vx[j][i], vy[j][i], dtx, dty, i, j, i0, i1, j0, j1, s0, s1, t0, t1);
int i0i = int(i0);
int i1i = int(i1);
int j0i = int(j0);
int j1i = int(j1);
constrain(i0i, 0, size - 1);
constrain(i1i, 0, size - 1);
constrain(j0i, 0, size - 1);
constrain(j1i, 0, size - 1);
d[j][i] =
s0 * (t0 * d0[j0i][i0i] + t1 * d0[j1i][i0i]) +
s1 * (t0 * d0[j0i][i1i] + t1 * d0[j1i][i1i]);
}
}
enforceBounds(d, b);
}
void FluidBox::updateTracers() {
float i0, i1, j0, j1;
float dtx = dt * (size - 2);
float dty = dt * (size - 2);
float s0, s1, t0, t1;
float Nfloat = size;
for (int i = 0; i < tracers.size(); i++) {
calcUpstreamCoords(Nfloat, velocity->getVec(tracers[i].pos).x, velocity->getVec(tracers[i].pos).y, dtx, dty, tracers[i].pos.x, tracers[i].pos.y, i0, i1, j0, j1, s0, s1, t0, t1);
tracers[i].pos +=
s0 * (t0 * (tracers[i].pos - glm::vec2(i0, j0)) + t1 * (tracers[i].pos - glm::vec2(i0, j1))) +
s1 * (t0 * (tracers[i].pos - glm::vec2(i1, j0)) + t1 * (tracers[i].pos - glm::vec2(i1, j1))) - glm::vec2(0.5f);
constrain(tracers[i].pos, 0, size - 1);
}
}
void FluidBox::calcUpstreamCoords(float Nfloat, float vx, float vy, float dtx, float dty, int i, int j, float &i0, float &i1, float &j0, float &j1, float &s0, float &s1, float &t0, float &t1) {
float tmp1, tmp2, x, y;
tmp1 = dtx * vx;
tmp2 = dty * vy;
x = i - tmp1;
y = j - tmp2;
if (x < 0.5f) x = 0.5f;
if (x > Nfloat + 0.5f) x = Nfloat + 0.5f;
i0 = floor(x);
i1 = i0 + 1.0f;
if (y < 0.5f) y = 0.5f;
if (y > Nfloat + 0.5f) y = Nfloat + 0.5f;
j0 = floor(y);
j1 = j0 + 1.0f;
s1 = x - i0;
s0 = 1.0f - s1;
t1 = y - j0;
t0 = 1.0f - t1;
}
void FluidBox::addTracer(glm::vec2 pos, glm::vec3 color) {
if (constrain(pos, 0, size - 1)) {
return;
}
tracers.push_back(Tracer(pos, color));
}
void FluidBox::addDensity(glm::vec2 pos, float amount, glm::vec3 color) {
if (constrain(pos, 0, size - 1)) {
return;
}
density[0][pos.y][pos.x] += amount * color.x / 255.0f;
density[1][pos.y][pos.x] += amount * color.y / 255.0f;
density[2][pos.y][pos.x] += amount * color.z / 255.0f;
}
void FluidBox::addVelocity(glm::vec2 pos, glm::vec2 amount) {
if (constrain(pos, 1, size - 2)) {
return;
}
velocity->getXList()[pos.y][pos.x] += amount.x;
velocity->getYList()[pos.y][pos.x] += amount.y;
}
void FluidBox::freezeVelocity()
{
velocityFrozen = true;
}
void FluidBox::unfreezeVelocity()
{
velocityFrozen = false;
}
bool FluidBox::getFreezeVelocity()
{
return velocityFrozen;
}
void FluidBox::clear() {
this->prevDensity = vector<vector<vector<float>>>(3, vector<vector<float>>(size, vector<float>(size, 0)));
this->density = vector<vector<vector<float>>>(3, vector<vector<float>>(size, vector<float>(size, 0)));
this->tracers = vector<Tracer>();
this->velocityPrev = new DynamicVector(size, size);
this->velocity = new DynamicVector(size, size);
}
void FluidBox::fadeDensity(float increment, float min, float max) {
int checkInterval = size / 60;
float densityMultiplier = 10.0f / 255.0f;
float avgDensity = 0;
for (int y = 0; y < size; y += checkInterval) {
for (int x = 0; x < size; x += checkInterval) {
for (int i = 0; i < density.size(); i++) {
avgDensity += density[i][y][x];
}
}
}
avgDensity /= 3 * (size / checkInterval)*(size / checkInterval);
float densityIncrement = increment * (avgDensity * densityMultiplier);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
for (int i = 0; i < density.size(); i++) {
density[i][y][x] -= densityIncrement;
constrain(density[i][y][x], min, max);
}
}
}
}
glm::vec3 FluidBox::getColorAtPos(glm::vec2 pos) {
glm::vec3 output = glm::vec3(1);
output.x = density[0][pos.y][pos.x];
output.y = density[1][pos.y][pos.x];
output.z = density[2][pos.y][pos.x];
return output;
}
std::vector<Tracer>& FluidBox::getTracers() {
return tracers;
}
vector<vector<Tracer*>> FluidBox::generateTracerMap() {
vector<vector<Tracer*>> map = vector<vector<Tracer*>>(size, vector<Tracer*>(size, nullptr));
for (int i = 0; i < tracers.size(); i++) {
map[tracers[i].pos.y][tracers[i].pos.x] = &tracers[i];
}
return map;
}
// search for y row and then x if not found then return nullptr
// min is inclusive and max is exclusive
Tracer& binaryTracerSearch(vector<Tracer>& tracers, int min, int max, glm::vec2 targetPos) {
int mid = (max - min) / 2 + min;
int left = min + (mid - min) / 2;
int right = min + 3 * (mid - min) / 2;
// if ys are found then start searching xs
if (tracers[mid].pos.y == targetPos.y) {
if (tracers[left].pos.x == targetPos.x) {
return tracers[left];
}
else if (tracers[left].pos.x < targetPos.x) {
return binaryTracerSearch(tracers, left, mid, targetPos);
}
else {
return binaryTracerSearch(tracers, min, left, targetPos);
}
}
if (tracers[mid].pos.y == targetPos.y) {
if (tracers[left].pos.x == targetPos.x) {
return tracers[right];
}
else if (tracers[right].pos.x < targetPos.x) {
return binaryTracerSearch(tracers, right, max, targetPos);
}
else {
return binaryTracerSearch(tracers, mid, right, targetPos);
}
}
// searching for y value
else if (tracers[mid].pos.y < targetPos.y) {
return binaryTracerSearch(tracers, mid, max, targetPos);
}
else {
return binaryTracerSearch(tracers, min, mid, targetPos);
}
}
void constrain(int &num, int min, int max) {
if (num < min) {
num = min;
}
if (num > max) {
num = max;
}
}
void constrain(float &num, float min, float max) {
if (num < min) {
num = min;
}
if (num > max) {
num = max;
}
}
bool constrain(glm::vec2& vec, float min, float max) {
bool toReturn = false;
if (vec.x < min) {
vec.x = min;
toReturn = true;
}
if (vec.y < min) {
vec.y = min;
toReturn = true;
}
if (vec.x > max) {
vec.x = max;
toReturn = true;
}
if (vec.y > max) {
vec.y = max;
toReturn = true;
}
return toReturn;
}<file_sep>/IncompressibleFluidSimulation/RenderObject.h
#pragma once
#include <shader.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
class RenderObject {
public:
Shader shader;
unsigned int VAO;
unsigned int VBO;
float* data;
RenderObject();
void allocateMemory(int size);
}; | 6e7518692a671a8091e7bf9d0169fb5c032889aa | [
"Markdown",
"C++"
] | 12 | C++ | enilsson18/IncompressibleFluidSimulation | 9fcc297ca58bf4dfdf34f35dda67b9154227ee0a | 23c3c6381d3bbc6c6f2237f58b3385d3a2f9d826 |
refs/heads/master | <file_sep><?PHP
require_once("db-config.php");
if(!isset($_POST['submitted']))
{
return false;
}
$formvars = array();
$formvars['nom_utilis'] = test_input($_POST['nom']);
$formvars['prenom_utilis'] = test_input($_POST['prenom']);
$formvars['ad_mail'] = test_input($_POST['email']);
$formvars['mot_d_passe'] = test_input($_POST['mdp']);
if (isset($_POST['vegetarien']) == true){
$formvars['vegetarien'] = test_input($_POST['vegetarien']);
}
else {
$formvars['vegetarien'] = 0;
}
if (isset($_POST['halal']) == true){
$formvars['halal'] = test_input($_POST['halal']);
}
else {
$formvars['halal'] = 0;
}
if (isset($_POST['vegan']) == true){
$formvars['vegan'] = test_input($_POST['vegan']);
}
else {
$formvars['vegan'] = 0;
}
$allergies = array();
if (isset($_POST['gluten']) == true){
$allergies[] = test_input($_POST['gluten']);
}
if (isset($_POST['crustace']) == true){
$allergies[] = test_input($_POST['crustace']);
}
if (isset($_POST['oeuf']) == true){
$allergies[] = test_input($_POST['oeuf']);
}
if (isset($_POST['poisson']) == true){
$allergies[] = test_input($_POST['poisson']);
}
if (isset($_POST['arachide']) == true){
$allergies[] = test_input($_POST['arachide']);
}
if (isset($_POST['soja']) == true){
$allergies[] = test_input($_POST['soja']);
}
if (isset($_POST['lait']) == true){
$allergies[] = test_input($_POST['lait']);
}
if (isset($_POST['fruit-a-coques']) == true){
$allergies[] = test_input($_POST['fruit-a-coques']);
}
if (isset($_POST['celeri']) == true){
$allergies[] = test_input($_POST['celeri']);
}
if (isset($_POST['moutarde']) == true){
$allergies[] = test_input($_POST['moutarde']);
}
if (isset($_POST['sesame']) == true){
$allergies[] = test_input($_POST['sesame']);
}
if (isset($_POST['mollusque']) == true){
$allergies[] = test_input($_POST['mollusque']);
}
if(estUnique($formvars, 'ad_mail') == false){
header("Location: ../existeDeja.php");
}
else{
insertIntoDB($formvars, $allergies);
//header("Location: ../bienvenue.php");
}
function estUnique($formvars,$fieldname){
$query = "SELECT ".$fieldname." FROM utilisateur WHERE ".$fieldname."='".$formvars[$fieldname]."'";
$reponse = dbLogin()->prepare($query);
$reponse->execute();
// Set the resulting array to associative
$count = $reponse->fetchColumn();
if(!empty ($count)){
return false;
}
return true;
}
function insertIntoDB($formvars, $allergies){
$pdo = dbLogin();
$query = "INSERT INTO utilisateur (
nom_utilis,
prenom_utilis,
mot_d_passe,
vegetarien,
halal,
vegan,
ad_mail)
VALUES
(
:nom_utilis,
:prenom_utilis,
:mot_d_passe,
:vegetarien,
:halal,
:vegan,
:ad_mail
)";
$reponse = $pdo->prepare($query);
$reponse->execute(array(
"nom_utilis" => $formvars['nom_utilis'],
"prenom_utilis" => $formvars['prenom_utilis'],
"mot_d_passe" => $formvars['mot_d_passe'],
"vegetarien" => $formvars['vegetarien'],
"halal" => $formvars['halal'],
"vegan" => $formvars['vegan'],
"ad_mail" => $formvars['ad_mail']));
$lastId = $pdo->lastInsertId();
foreach ($allergies as $element) {
$query2 = "INSERT INTO est_allergique_all_util (
ID_all,
ID_utilis)
VALUES
(
:ID_all,
:ID_utilis
)";
echo $query2;
$reponse2 = dbLogin()->prepare($query2);
$reponse2->execute(array(
"ID_all" => $element,
"ID_utilis" => $lastId));
}
}
?>
<file_sep><?php
require_once("php/db-config.php");
require_once("php/login-check.php");
require_once("php/init-session.php");
?>
<!DOCTYPE HTML>
<!--
Aesthetic by gettemplates.co
Twitter: http://twitter.com/gettemplateco
URL: http://gettemplates.co
-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Ch'Efrei</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:title" content=""/>
<meta property="og:image" content=""/>
<meta property="og:url" content=""/>
<meta property="og:site_name" content=""/>
<meta property="og:description" content=""/>
<meta name="twitter:title" content="" />
<meta name="twitter:image" content="" />
<meta name="twitter:url" content="" />
<meta name="twitter:card" content="" />
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<!-- Animate.css -->
<link rel="stylesheet" href="css/animate.css">
<!-- Icomoon Icon Fonts-->
<link rel="stylesheet" href="css/icomoon.css">
<!-- Themify Icons-->
<link rel="stylesheet" href="css/themify-icons.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="css/magnific-popup.css">
<!-- Bootstrap DateTimePicker -->
<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css">
<!-- Owl Carousel -->
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/style2.css">
<!-- Modernizr JS -->
<script src="js/modernizr-2.6.2.min.js"></script>
<!-- FOR IE9 below -->
<!--[if lt IE 9]>
<script src="js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="gtco-loader"></div>
<div id="page">
<!-- <div class="page-inner"> -->
<?php
include ("include/navbar.php");
?>
<header id="gtco-header" class="gtco-cover gtco-cover-sm" role="banner" style="background-image: url(images/img_bg_2.jpg)" data-stellar-background-ratio="0.5">
<div class="overlay"></div>
<div class="gtco-container">
<div class="row">
<div class="col-md-12 col-md-offset-0 text-left">
<div class="row row-mt-14em">
<div class="col-md-12 mt-text animate-box" data-animate-effect="fadeInUp">
<h1 class="cursive-font text-center primary-color">Ch'Efrei</h1>
<h1 class="cursive-font text-center">Rejoignez la communauté !</h1>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="gtco-section">
<div class="gtco-container">
<div class="col-md-offset-2 col-md-8 animate-box">
<h1 class="primary-color cursive-font">Inscription</h1>
<form id="inscription" action="php/inscription.php" method="post">
<input type="hidden" name="submitted" id="submitted" value="1">
<div class="row form-group">
<div class="col-md-4">
<label class="primary-color">Nom</label>
<input type="text" name="nom" id="nom" class="form-control" placeholder="Votre nom" required>
</div>
<div class="col-md-8">
<label class="primary-color">Prénom</label>
<input type="text" name="prenom" id="prenom" class="form-control" placeholder="Votre prénom" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="primary-color">Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Votre adresse email" required>
<span id="inscription_email_errorloc" class="insciption-erreur"></span>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="primary-color">Mot de passe</label>
<input type="password" name="mdp" id="mdp" class="form-control" placeholder="Votre mot de passe" required>
</div>
</div>
<div class="row form-group">
<div class="col-md-4">
<label class="primary-color">Vos restrictions alimentaires</label>
</div>
<div class="col-md-8">
<label class="checkbox-inline">
<input type="checkbox" name="vegetarien" value="1">Végétarien<br>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="vegan" value="1">Vegan<br>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="halal" value="1">Halal<br>
</label>
</div>
</div>
<div class="row form-group">
<div class="col-md-4">
<label class="primary-color">Vos allergies</label>
</div>
</div>
<div class="row form-group">
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="gluten" value="1">Gluten<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="crustace" value="2">Crustacé<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="oeuf" value="3">Oeuf<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="poisson" value="4">Poisson<br>
</label>
</div>
</div>
<div class="row form-group">
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="arachide" value="5">Arachide<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="soja" value="6">Soja<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="lait" value="7">Lait<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="fruit-a-coques" value="8">Fruit à coques<br>
</label>
</div>
</div>
<div class="row form-group">
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="celeri" value="9">Céleri<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="moutarde" value="10">Moutarde<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="sesame" value="11">Sésame<br>
</label>
</div>
<div class="col-md-3">
<label class="checkbox-inline">
<input type="checkbox" name="mollusque" value="12">Mollusque<br>
</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="S'inscrire" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<?php
include ("include/container-valeurs.php");
?>
<?php
include ("include/footer.php");
?>
<?php
include ("include/modal-login-form.php");
?>
</div>
<div class="gototop js-top">
<a href="#" class="js-gotop"><i class="icon-arrow-up"></i></a>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- jQuery Easing -->
<script src="js/jquery.easing.1.3.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- Waypoints -->
<script src="js/jquery.waypoints.min.js"></script>
<!-- Carousel -->
<script src="js/owl.carousel.min.js"></script>
<!-- countTo -->
<script src="js/jquery.countTo.js"></script>
<!-- Stellar Parallax -->
<script src="js/jquery.stellar.min.js"></script>
<!-- Magnific Popup -->
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/magnific-popup-options.js"></script>
<script src="js/moment.min.js"></script>
<script src="js/bootstrap-datetimepicker.min.js"></script>
<!-- Main -->
<script src="js/main.js"></script>
</body>
</html>
<file_sep><?php
function db_reset($conn, $file)
{
try{
$query = file_get_contents($file);
$sql = $conn->prepare("$query");
$sql->execute();
echo "Database has been reset";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
/**
* Permet la connexion à la DB
**/
function db_connect($servername, $dbname, $username, $password) {
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
// set the PDO error mode to exception
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
function CloseCon($conn)
{
$conn -> close();
}
function affichage_chiffres($conn){
try{
/* Affichage dans l'index pour les meilleures recettes limite à 6 recettes*/
$reponse = $conn->prepare("SELECT (
SELECT COUNT(*)
FROM recette
) AS countRecette,
(SELECT COUNT(*)
FROM ingredient
) AS countIngredient,
(SELECT COUNT(*)
FROM note_util_rc
) AS countNote,
(SELECT COUNT(*)
from utilisateur
) AS countUtilisateur");
$reponse->execute();
// result est un tableau deux dimensions result[, nom]
// echo $result[3]['ID_recette'];
while ($row = $reponse->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInUp">
<div class="feature-center">
<span class="counter js-counter" data-from="0" data-to="<?php echo $row['countRecette']?>" data-speed="5000" data-refresh-interval="50">1</span>
<span class="counter-label">Recettes</span>
</div>
</div>
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInUp">
<div class="feature-center">
<span class="counter js-counter" data-from="0" data-to="<?php echo $row['countIngredient']?>" data-speed="5000" data-refresh-interval="50">1</span>
<span class="counter-label">Ingrédients</span>
</div>
</div>
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInUp">
<div class="feature-center">
<span class="counter js-counter" data-from="0" data-to="<?php echo $row['countUtilisateur']?>" data-speed="5000" data-refresh-interval="50">1</span>
<span class="counter-label">Utilisateurs</span>
</div>
</div>
<div class="col-md-3 col-sm-6 animate-box" data-animate-effect="fadeInUp">
<div class="feature-center">
<span class="counter js-counter" data-from="0" data-to="<?php echo $row['countNote']?>" data-speed="5000" data-refresh-interval="50">1</span>
<span class="counter-label">Avis</span>
</div>
</div>
<?php
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
/**
* Selectionne les 10 meilleures recettes à notre client qui lui ont plû à tout le monde à ces notes
**/
function affichage_meilleures_notes_global($conn){
try{
/* Affichage dans l'index pour les meilleures recettes limite à 6 recettes*/
$reponse = $conn->prepare("SELECT count(*), AVG(n.note), r.temps_min, r.nom_recette, r.ID_recette
FROM note_util_rc n
JOIN recette r ON r.ID_recette = n.ID_recette
GROUP BY nom_recette
HAVING AVG(n.note) > 3
ORDER BY AVG(n.note)
DESC LIMIT 6");
$reponse->execute();
// result est un tableau deux dimensions result[, nom]
// echo $result[3]['ID_recette'];
while ($row = $reponse->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0); $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)'];?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
/**
* Selectionne les 10 meilleures recettes à notre client qui lui ont plû à lui
**/
function affichage_meilleures_notes_utilisateur($conn, $id_util){
try{
/* Affichage dans l'index pour les meilleures recettes de l'utilisateur limite à 10 recettes*/
$reponse = $conn->prepare("SELECT ID_recette, note FROM note_util_rc Where ID_utilis = ".$id_util." ORDER BY note DESC Limit 10");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
$result = $reponse->fetchAll();
echo "<table border=1>";
echo "<tr> <td>ID RECETTE</td> <td>Note</td>";
foreach ($result as $value)
{
echo "<tr>";
foreach( $value as $key => $val)
{
echo ("<td> $val<br> </td>");
}
echo"</tr>";
}
echo "</table>";
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nombre_recette($conn){
try{
if (isset($_GET['recette'])){
$recherche = $_GET['recette'];
/* Affichage des recettes contenant le mot saisie par l'utilisateur dans le titre de la recette */
$reponse = $conn->prepare("SELECT count(DISTINCT ID_recette) FROM recette
Where nom_recette LIKE '%".$recherche."%'
ORDER BY nom_recette");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
return $row['count(DISTINCT ID_recette)'];
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nombre_recette_avec_ingredient($conn){
try{
if (isset($_GET['recherche_ingr'])){
$recherche_ingr = $_GET['recherche_ingr'];
/*
* liste_ingr correspond à la liste de tous les ingrédients présents dans
*/
$liste_ingr = explode(",", $recherche_ingr);
/*
* Creation de la query
*/
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$query = " select count(DISTINCT recette.ID_recette) from recette inner join possede_rc_ing on possede_rc_ing.ID_recette = recette.ID_recette
join ingredient on Ingredient.ID_ingr = possede_rc_ing.ID_ingr ";
else {
$query.= " join possede_rc_ing possede_rc_ing".$i." on possede_rc_ing".$i.".ID_recette = recette.ID_recette
join ingredient ingredient".$i." on ingredient".$i.".ID_ingr = possede_rc_ing".$i.".ID_ingr ";
}
}
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$where_query = "WHERE ingredient.nom_ingr LIKE '%".$liste_ingr[0]."%'";
else {
$where_query .= " AND ";
$where_query .= " Ingredient".$i.".nom_ingr LIKE '%".$liste_ingr[$i]."%' ";
}
}
/* Affichage des recettes contenant les ingrédients de la liste */
$reponse = $conn->prepare($query.$where_query);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
return $row['count(DISTINCT recette.ID_recette)'];
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nom_recette_sans_note($conn){
try{
if (isset($_GET['recette'])){
$recherche = $_GET['recette'];
/* Affichage des recettes contenant le mot saisie par l'utilisateur dans le titre de la recette */
$reponse = $conn->prepare("SELECT r.nom_recette, r.temps_min, r.ID_recette
FROM recette r
LEFT JOIN note_util_rc n ON r.ID_recette = n.ID_recette
Where nom_recette LIKE '%".$recherche."%'
AND n.ID_recette IS NULL
GROUP BY r.nom_recette");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
Aucun avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nom_recette_avec_note($conn){
try{
if (isset($_GET['recette'])){
$recherche = $_GET['recette'];
/* Affichage des recettes contenant le mot saisie par l'utilisateur dans le titre de la recette */
$reponse = $conn->prepare("SELECT count(*), AVG(n.note), r.temps_min, r.nom_recette, r.ID_recette
FROM recette r
JOIN note_util_rc n ON r.ID_recette = n.ID_recette
Where nom_recette LIKE '%".$recherche."%'
GROUP BY r.ID_recette
ORDER BY AVG(n.note) DESC");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0); $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)']?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nom_ingredient_sans_note($conn){
try{
if (isset($_GET['recherche_ingr'])){
$recherche_ingr = $_GET['recherche_ingr'];
/*
* liste_ingr correspond à la liste de tous les ingrédients présents dans
*/
$liste_ingr = explode(",", $recherche_ingr);
/*
* Creation de la query
*/
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$query = " select distinct recette.nom_recette, recette.temps_min, recette.ID_recette from recette inner join possede_rc_ing on possede_rc_ing.ID_recette = recette.ID_recette LEFT JOIN note_util_rc n ON recette.ID_recette = n.ID_recette
join ingredient on Ingredient.ID_ingr = possede_rc_ing.ID_ingr ";
else {
$query.= " join possede_rc_ing possede_rc_ing".$i." on possede_rc_ing".$i.".ID_recette = recette.ID_recette
join ingredient ingredient".$i." on ingredient".$i.".ID_ingr = possede_rc_ing".$i.".ID_ingr ";
}
}
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$where_query = "WHERE ingredient.nom_ingr LIKE '%".$liste_ingr[0]."%' AND n.ID_recette IS NULL";
else {
$where_query .= " AND ";
$where_query .= " Ingredient".$i.".nom_ingr LIKE '%".$liste_ingr[$i]."%' ";
}
}
$qry = " GROUP BY recette.ID_recette";
/* Affichage des recettes contenant les ingrédients de la liste */
$reponse = $conn->prepare($query.$where_query.$qry);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
Aucun avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_nom_ingredient_avec_note($conn){
try{
if (isset($_GET['recherche_ingr'])){
$recherche_ingr = $_GET['recherche_ingr'];
/*
* liste_ingr correspond à la liste de tous les ingrédients présents dans
*/
$liste_ingr = explode(",", $recherche_ingr);
/*
* Creation de la query
*/
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$query = " select distinct count(*), AVG(n.note), recette.nom_recette, recette.temps_min, recette.ID_recette from recette inner join possede_rc_ing on possede_rc_ing.ID_recette = recette.ID_recette JOIN note_util_rc n ON recette.ID_recette = n.ID_recette
join ingredient on Ingredient.ID_ingr = possede_rc_ing.ID_ingr ";
else {
$query.= " join possede_rc_ing possede_rc_ing".$i." on possede_rc_ing".$i.".ID_recette = recette.ID_recette
join ingredient ingredient".$i." on ingredient".$i.".ID_ingr = possede_rc_ing".$i.".ID_ingr ";
}
}
for ($i = 0 ;$i < count($liste_ingr); $i++){
if ($i == 0)$where_query = "WHERE ingredient.nom_ingr LIKE '%".$liste_ingr[0]."%' ";
else {
$where_query .= " AND ";
$where_query .= " Ingredient".$i.".nom_ingr LIKE '%".$liste_ingr[$i]."%' ";
}
}
$qry = " GROUP BY recette.ID_recette
ORDER BY AVG(n.note) DESC";
/* Affichage des recettes contenant les ingrédients de la liste */
$reponse = $conn->prepare($query.$where_query.$qry);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0) ; $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)']?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function information_recette($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare("SELECT count(*), AVG(n.note), r.temps_min, r.nom_recette, r.ID_recette
FROM recette r
LEFT JOIN note_util_rc n ON r.ID_recette = n.ID_recette
Where r.ID_recette LIKE ".$recette."");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="row animate-box" data-animate-effect="fadeInUp">
<div class="col-md-8 col-md-offset-2 text-center gtco-heading">
<h2 class="cursive-font primary-color"><?php echo $row['nom_recette']?> !</h2>
</div>
</div>
<div class="col-md-offset-3 col-md-6 animate-box" data-animate-effect="fadeIn">
<a href="images/recette_<?php echo $row['ID_recette']?>.jpg" class="fh5co-card-item image-popup">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
</div>
</a>
</div>
<div class="row">
<div class="col-md-offset-2 col-md-2 col-sm-12 animate-box" align="center" data-animate-effect="fadeIn">
<h3 class="btn btn-primary btn-sm">
<div class="cursive-font">
<i class="icon-star2"></i>
<?php
if (empty($row['AVG(n.note)'])){
if(isset($_SESSION['nom_utilis'])){
?>
<a href="review.php?recette=<?php echo $_GET['recette']?>" id="review">
Aucun avis
</a>
<?php
}
else{
?>
<a href="#" id="review">
Aucun avis
</a>
<?php
}
}
else {
?>
<a href="recette-review.php?recette=<?php echo $row['ID_recette'];?>" id="review">
<?php
echo round($row['AVG(n.note)'], 1)?>/5 <?php echo $row['count(*)']
?> avis
</a>
<?php
}?>
</div>
</h3>
</div>
<div class="col-md-offset-1 col-md-2 col-sm-12 animate-box" align="center" data-animate-effect="fadeIn">
<h3 class="cursive-font primary-color padding-top-12px">
<i class="icon-clock"></i>
<?php echo $row['temps_min']?> minutes
</h3>
</div>
<div class="col-md-offset-1 col-md-2 col-sm-12 animate-box" align="center" data-animate-effect="fadeIn">
<div class="row">
<h3 class="cursive-font primary-color padding-top-12px">
<i class="ti-user"></i>
1 personne
</h3>
</div>
</div>
</div>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function affichage_ingredient($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare( "SELECT possede_rc_ing.quantite, possede_rc_ing.mesure, ingredient.nom_ingr FROM ingredient join possede_rc_ing on ingredient.ID_ingr = possede_rc_ing.ID_ingr Where ID_recette = ".$recette);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
if ($row['mesure'] == 'NULL'){
echo $row['quantite']." ".$row['nom_ingr'];
}
else{
echo $row['quantite']." ".$row['mesure']." ".$row['nom_ingr'];
}
?>
<hr>
<?php
}
/*$reponse = $conn->prepare( "SELECT instruction FROM recette Where ID_recette = ".$id_rec);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
$result = $reponse->fetchAll();
foreach ($result as $value) {
foreach( $value as $key => $val)
{
$descrip = $val;
}
}
// $liste_etape[0] n'a pas de valeur
// donc si besoin de l'étape 1 => $liste_etape[1] directement.
$liste_etape = explode("/", $descrip);
$nb_etape = count($liste_etape)-1;
echo "nb etape".$nb_etape;*/
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function affichage_preparation($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare( "SELECT instruction FROM recette Where ID_recette = ".$recette);
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
$result = $reponse->fetchAll();
foreach ($result as $value) {
foreach( $value as $key => $val)
{
$descrip = $val;
}
}
$liste_etape = explode("/", $descrip);
$etape = 0;
foreach( $liste_etape as $key => $val)
{
if($etape != 0){
?>
<h3 class="cursive-font primary-color">Etape <?php echo $etape;?></h3>
</h3>
<?php
echo $val;
?>
<hr>
<?php }
$etape++;
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function affichage_note_moyenne($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare("SELECT count(*), AVG(n.note), r.nom_recette, r.ID_recette
FROM recette r
LEFT JOIN note_util_rc n ON r.ID_recette = n.ID_recette
Where r.ID_recette LIKE ".$recette."");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
$nbreAvis = $row['count(*)'];
?>
<h1 class="cursive-font text-center"><?php echo $row['nom_recette']?></h1>
<br>
<div class="row">
<div class="col-sm-6">
<div class="rating-block">
<h2 class="cursive-font primary-color">Note moyenne de notre communauté</h2>
<div class = "row">
<div class="col-sm-2" align="center">
<h2 class="bold padding-bottom-7"><?php echo round($row['AVG(n.note)'], 1)?><small>/ 5</small></h2>
</div>
<div class="col-sm-2" align="center">
<h2 class="bold padding-bottom-7"> <?php echo $row['count(*)'];?> <small>avis</small></h2>
</div>
<div class="col-md-5" align="center">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0); $star++){
?>
<button type="button" class="btn-primary btn-md">
<i class="icon-star2"></i>
</button>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<button type="button" class="btn-primary btn-md sans-etoile">
<i class="icon-star2"></i>
</button>
<?php
}
?>
</div>
</div>
<br>
<div class="row">
<?php
if(isset($_SESSION['nom_utilis'])){
?>
<div class="col-md-4" align="center">
<a href="review.php?recette=<?php echo $_GET['recette']?>">
<button class="btn btn-primary btn-sm">Donnez votre avis</button>
</a>
</div>
<?php
}
?>
</div>
</div>
</div>
<div class="col-md-offset-1 col-sm-5 ">
<h1 class="cursive-font primary-color">Leurs avis</h1>
<div class="col-sm-12">
<?php
$reponse2 = $conn->prepare("SELECT count(*), note
FROM note_util_rc
Where ID_recette LIKE ".$recette."
GROUP BY note
ORDER BY note DESC");
$reponse2->execute();
// Set the resulting array to associative
$reponse2->setFetchMode(PDO::FETCH_ASSOC);
$row = $reponse2->fetch(PDO::FETCH_ASSOC);
for ($star = 5; $star >= 1; $star--){
?>
<div class="row">
<div class="pull-left etoile-barre-avis">
<div class="etoile-barre-avis2">
<?php echo $star; ?><span class="glyphicon glyphicon-star"></span>
</div>
</div>
<div class="pull-left barre-avis">
<div class="progress barre-progression">
<?php
if((int)$row['note'] == $star){
?>
<div class="progress-bar progress-bar-warning" style="width: <?php echo intval($row['count(*)']*100/$nbreAvis,0)?>%" role="progressbar"></div>
</div>
</div>
<?php echo $row['count(*)'];?>
<?php
$row = $reponse2->fetch(PDO::FETCH_ASSOC);
}
else{
?>
<div class="progress-bar progress-bar-warning" style="width: 0%" role="progressbar"></div>
</div>
</div>
<?php
echo '0';
}
?>
<span class="glyphicon glyphicon-user"></span>
</div>
<?php
}
?>
</div>
</div> <?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function affichage_commentaire($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare("SELECT n.note, n.description, n.date_note, u.nom_utilis, u.prenom_utilis
FROM note_util_rc n
JOIN utilisateur u ON u.ID_utilis = n.ID_utilis
Where n.ID_recette LIKE ".$recette."
ORDER BY n.note DESC");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
?>
<div class="row">
<div class="col-sm-3">
<img src="images/logo_chef.png" class="img-rounded image-resize-100px">
<div class="review-block-name"><?php echo ucwords(strtolower($row['prenom_utilis']))." ". ucwords(strtolower($row['nom_utilis']));?></div>
<div class="review-block-date"><?php echo $row['date_note'];?></div>
</div>
<div class="col-sm-9">
<div class="review-block-rate">
<?php
for ($star = 0; $star < $row['note']; $star++){
?>
<button type="button" class="btn-primary btn-xs">
<i class="icon-star2"></i>
</button>
<?php
}
for ($star = $row['note']; $star < 5; $star++){
?>
<button type="button" class="btn-primary btn-xs sans-etoile">
<i class="icon-star2"></i>
</button>
<?php
}
?>
</div>
<br>
<p>
<?php echo $row['description'];
?>
</p>
</div>
</div>
<hr>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function get_recette_nom($conn){
try{
if (isset($_GET['recette'])){
$recette = $_GET['recette'];
$reponse = $conn->prepare("SELECT nom_recette
FROM recette
Where ID_recette LIKE ".$recette."");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC)){
return $row['nom_recette'];
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function nouveaute_recette($conn){
try{
/* Affichage dans l'index pour les meilleures recettes de l'utilisateur limite à 10 recettes*/
$reponse = $conn->prepare("SELECT id_recette, nom_recette, temps_min, datediff(date(NOW()), recette.date) FROM recette Where datediff(date(NOW()), recette.date)<35 Limit 2");
$reponse->execute();
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['id_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['id_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function nouveaute_les_mieux_note($conn){
try{
/* Affichage dans l'index pour les meilleures recettes de l'utilisateur limite à 10 recettes*/
$reponse = $conn->prepare("SELECT distinct count(*), recette.id_recette, recette.temps_min, nom_recette, datediff(date(NOW()), recette.date), AVG(note_util_rc.note)
FROM recette join note_util_rc on recette.id_recette = note_util_rc.id_recette
Where datediff(date(NOW()), recette.date)<35
GROUP BY recette.id_recette
Limit 2");
$reponse->execute();
// Set the resulting array to associative
$reponse->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $reponse->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['id_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['id_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(note_util_rc.note)'], 0); $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(note_util_rc.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)'];?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function recherche_meilleure_recette_ing_fav($conn){
try{
if (isset($_SESSION['ID_utilis'])){
$id_util = $_SESSION['ID_utilis'];
// L'utilisateur est-il vegetarien ou vegan
$rep = $conn->prepare("SELECT vegetarien, vegan from utilisateur WHERE ID_utilis = ".$id_util);
$rep->execute();
// Set the resulting array to associative
$rep->setFetchMode(PDO::FETCH_ASSOC);
$vege_vega = $rep->fetchAll();
/* Recupère tous les ingrédients dans toutes les recettes*/
$reponse = $conn->prepare("SELECT ID_recette,ID_ingr FROM possede_rc_ing
WHERE (ID_recette NOT IN (SELECT DISTINCT p.ID_recette FROM est_allergique_all_util est_all
join compose_ing_all c On c.ID_all = est_all.ID_all
Join possede_rc_ing p on p.ID_ingr = c.ID_ingr
WHERE est_all.ID_utilis = ".$id_util.")
AND ID_recette NOT IN (SELECT DISTINCT id_recette FROM note_util_rc where id_utilis = ".$id_util.") )"
.(($vege_vega[0]['vegan'] == 1)? " AND ID_recette NOT IN (SELECT DISTINCT ID_recette FROM possede_rc_ing, Ingredient
WHERE (Ingredient.ID_ingr = possede_rc_ing.ID_Ingr) AND ((type = 'Viande') OR (type = 'Laitier') OR (type = 'Poisson') OR (type = 'Fromage')))":
(($vege_vega[0]['vegetarien'] == 1)? " AND ID_recette NOT IN (SELECT DISTINCT ID_recette FROM possede_rc_ing, Ingredient
WHERE (Ingredient.ID_ingr = possede_rc_ing.ID_Ingr) AND (type = 'Viande')) ":
""))." ORDER BY ID_recette");
// Set the resulting array to associative
$reponse->execute();
$reponse->setFetchMode(PDO::FETCH_ASSOC);
$table_ingr = $reponse->fetchAll();
/* Recupère tous les ingrédients dans toutes les recettes*/
$reponse2 = $conn->prepare("SELECT DISTINCT ID_ingr FROM ((SELECT ID_recette
FROM note_util_rc
Where ID_utilis = ".$id_util." ORDER BY note DESC Limit 3 )AS BestRecipies, possede_rc_ing)
WHERE BestRecipies.ID_recette = possede_rc_ing.ID_recette ");
$reponse2->execute();
// Set the resulting array to associative
$reponse2->setFetchMode(PDO::FETCH_ASSOC);
$table_util_fav = $reponse2->fetchAll();
if(!empty ($table_util_fav)){
?>
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center gtco-heading">
<h2 class="cursive-font primary-color">Vous allez aimer...</h2>
</div>
</div>
<div class="row">
<?php
//$tab_ID_rec_conseil[] = array('' => , );
$temp_id = 0;
$cpt_similitude = 0;
$array = [];
$indexarray = -1;
foreach ($table_ingr as $value)
{
foreach( $value as $key => $val)
{
if ($key == "ID_recette"){
if ($val != $temp_id){
$temp_id = $val;
$cpt_similitude = 0;
}
}
else {
foreach($table_util_fav as $value2){
foreach( $value2 as $kk => $ingr_fav){
if ($ingr_fav == $val){
if ($cpt_similitude == 0) $indexarray++;
$cpt_similitude++;
// recettes succeptibles de plaire au monsieur 😀
$array[$indexarray] = [];
$array[$indexarray][0] = $temp_id;
$array[$indexarray][1] = $cpt_similitude;
}
}
}
}
}
}
for ($i = 0; $i <= $indexarray; $i++){
if ($i == 0)$where_query = "WHERE r.ID_recette = " .$array[$i][0];
else {
$where_query .= " OR (r.ID_recette = " .$array[$i][0]. ") ";
}
}
$reponse3 = $conn->prepare("SELECT count(*), AVG(n.note), r.temps_min, r.nom_recette, r.ID_recette
FROM note_util_rc n
JOIN recette r ON r.ID_recette = n.ID_recette
". $where_query ."
GROUP BY nom_recette
ORDER BY AVG(n.note)
");
$reponse3->execute();
$reponse3->setFetchMode(PDO::FETCH_ASSOC);
$tabPoids = $reponse3->fetchAll();
//foreach ($tabPoids as $row)
for ($i = 0; $i < count($tabPoids); $i++)
{
$k = 0;
while($tabPoids[$i]['ID_recette'] != $array[$k][0]) $k++;
$tabPoids[$i]['nb_similitude'] = $array[$k][1];
}
$poidsIngCommun = 3;
$poidsNote = 5;
$k = 1;
while ($k < count($tabPoids))
{
if($tabPoids[$k]['nb_similitude']*$poidsIngCommun + $tabPoids[$k]['AVG(n.note)']*$poidsNote > $tabPoids[$k - 1]['nb_similitude']*$poidsIngCommun + $tabPoids[$k - 1]['AVG(n.note)']*$poidsNote)
{
$Temp = $tabPoids[$k];
$tabPoids[$k] = $tabPoids[$k - 1];
$tabPoids[$k - 1] = $Temp;
$k = 0;
}
$k++;
}
// result est un tableau deux dimensions result[, nom]
// echo $result[3]['ID_recette'];
foreach($tabPoids as $row)
{
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0); $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)'];?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
?>
</div>
<br>
<hr>
<br>
<?php
}
else{
?>
<div class="row">
<div class="col-md-12 text-center gtco-heading">
<h2 class="cursive-font primary-color">Donnez des avis pour avoir des recettes à votre image</h2>
<img src="images/logo-chef-triste.png" alt="logo-chef-triste" class="text-center">
<p>Nous sommes désolés, aucune recette n'a été trouvée...</p>
</div>
</div>
<br>
<hr>
<br>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function affichage_recette_notee($conn){
try{
if (isset($_SESSION['ID_utilis'])){
$id_util = $_SESSION['ID_utilis'];
/* Affichage dans l'index pour les meilleures recettes de l'utilisateur limite à 10 recettes*/
$reponse = $conn->prepare("SELECT count(*), AVG(n.note), r.temps_min, r.nom_recette, r.ID_recette
FROM note_util_rc n
JOIN recette r ON r.ID_recette = n.ID_recette
WHERE n.ID_utilis = ".$id_util."
GROUP BY nom_recette
ORDER BY AVG(n.note)");
$reponse->execute();
$reponse->setFetchMode(PDO::FETCH_ASSOC);
if(!empty ($reponse)){
?>
<div class="row">
<div class="col-md-8 col-md-offset-2 text-center gtco-heading">
<h2 class="cursive-font primary-color">Vous avez donné votre avis...</h2>
</div>
</div>
<div class="row">
<?php
while ($row = $reponse->fetch(PDO::FETCH_ASSOC))
{
?>
<div class="col-lg-6 col-md-6 col-sm-6 animate-box" data-animate-effect="fadeIn">
<a href="recette.php?recette=<?php echo $row['ID_recette'];?>" class="fh5co-card-item">
<figure>
<div class="overlay"><i class="ti-plus"></i></div>
<img src="images/recette_<?php echo $row['ID_recette'];?>.jpg" alt="Image" class="img-responsive">
</figure>
<div class="fh5co-text">
<div class="row">
<?php
for($star = 0; $star < round($row['AVG(n.note)'], 0); $star++){
?>
<i class="icon-star2"></i>
<?php
}
for($star = round($row['AVG(n.note)'], 0); $star < 5; $star++){
?>
<i class="icon-star-outlined"></i>
<?php
}
echo $row['count(*)'];?> avis
<div class="row">
<i class="icon-clock"></i>
<?php echo $row['temps_min']; ?> minutes
</div>
<div class="row row-mt-1em">
<h3 class="cursive-font"><?php echo $row['nom_recette'];?></h3>
</div>
</div>
</div>
</a>
</div>
<?php
}
?>
</div>
<br>
<hr>
<br>
<?php
}
else{
?>
<div class="row">
<div class="col-md-12 text-center gtco-heading">
<h2 class="cursive-font primary-color">Vous n'avez toujours pas donné d'avis !</h2>
<img src="images/logo-chef-triste.png" alt="logo-chef-triste" class="text-center">
<p>Nous sommes désolés, aucune recette n'a été trouvée...</p>
</div>
</div>
<br>
<hr>
<br>
<?php
}
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
function retrieve_product_id($conn, $id)
{
try{
// Connect first: $conn is the database instance
$id = -1;
$stmt = $conn->prepare("SELECT id, description, weight, cost, quantity FROM products WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
// Set the resulting array to associative
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
echo "<table border=1>";
foreach ($result as $value)
{
echo "<tr>";
foreach( $value as $key => $val)
{
echo ("<td> $val<br> </td>");
}
echo"</tr>";
}
echo "</table>";
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
?><file_sep># PJ-Transverse
----------------
/!\ CONNEXION A LA DATABASE:
pour se connecter à la database, n'oubliez pas de changer les paramètres dans le fichier php/db-config.php.
----------------
Afin de rentrer dans le sujet de notre projet transverse autour de « L’intelligence artificielle », nous avons réfléchi à différentes stratégies afin de mettre en place le concept afin que notre application ne se limite pas seulement à du traitement de données. Ainsi afin de répondre à la problématique de ce projet, deux objectifs qui incorporent le concept « d’intelligence artificielle » ont été mis en place :
• Elimination de certaines recettes en se basant des avis de l’utilisateur. Un ingrédient qui est récurrent dans les recettes qui n’ont pas plu à l’utilisateur peut être un facteur de son insatisfaction. L’application pourrait ainsi privilégier des recettes ne contenant pas l’ingrédient en question afin de satisfaire l’utilisateur. Pour ce faire, on utilisera simplement des statistiques croisant aliments et recettes avec les notes attribuées.
• L’IA réfléchira et proposera à son utilisateur les recette qui sont le plus susceptible à lui plaire. Des statistiques seront menées afin de connaitre le type de plat préféré de l’utilisateur ou encore ses ingrédients préférés.
| c81615026f2213f7758858452a46581188c19ee3 | [
"Markdown",
"PHP"
] | 4 | PHP | OpOpTeam/PJ-Transverse | 10e50e0af175fb48c5fb81dc9d886bca24408a20 | d0cf25f734b8614b695759ebf57eea7b4bcf99f9 |
refs/heads/master | <repo_name>katlex/reagent-covered<file_sep>/doo.sh
#!/bin/sh
lein doo
<file_sep>/dist.sh
#!/bin/sh
set -e
lein cljsbuild once prod
rm -rf dist
mkdir dist
cp prod.html dist/index.html
mkdir dist/assets
cp prod/main.js dist/assets
mkdir dist/coverage
cp -R coverage/*/* dist/coverage
cp circle.yml dist
<file_sep>/figwheel.sh
#!/bin/sh
lein with-profile dev figwheel
<file_sep>/README.md
# Reagent covered
![Build status][CircleCI-Status]
A bare bones ClojureScript project which has:
1. [Reagent][Reagent] as a UI building tool
1. [Figwheel][Figwheel] for rapid development cycle
1. Tests made with [cljs.test][Cljs-Testing] and run with [doo][Doo]
1. [Instanbul][Instanbul] code coverage reports
## Prerequisites
The project needs [leiningen][Lein] and [npm][Npm] installed. Python or any tool to run ad hoc web server.
## Usage
### Installation
npm i
### Run rebuild/test cycle
./doo.sh
### Run dev tools
python -m SimpleHTTPServer 9898
./figwheel.sh
Open http://localhost:9898 save any file application gets rebuilt incrementally and auto reloaded in the browser without page update.
[Reagent]: https://github.com/reagent-project/reagent
[Figwheel]: https://github.com/bhauman/lein-figwheel
[Doo]: https://github.com/bensu/doo
[Cljs-Testing]: https://github.com/clojure/clojurescript/wiki/Testing
[Instanbul]: https://github.com/gotwarlost/istanbul
[Lein]: https://leiningen.org/
[Npm]: https://www.npmjs.com/
[CircleCI-Status]: https://circleci.com/gh/katlex/reagent-covered.png?style=shield
<file_sep>/publish.sh
#!/bin/sh
set -e
lein github-cdn
| 90a0b17652dd27543a712a120233f0dd0176a947 | [
"Markdown",
"Shell"
] | 5 | Shell | katlex/reagent-covered | 44717c3ffe3b08c4d7ee3dd6f7fa2b6588734b65 | ee2b3be9b446e601e0da3ca4bc13cbe15f9cfe24 |
refs/heads/master | <repo_name>etienne-dldc/swift-state-manager<file_sep>/StateManager.swift
//
// EDStateManager.swift
//
// Created by <NAME> on 09/05/2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
/// EDState
/// This strcy represent your step
/// add as many properties as you want
struct EDState {
// var counter: Int = 0
}
/// State Actions Type
enum EDStateActionType {
case IncrementCounter
}
/// State Action object
struct EDStateAction {
let type: EDStateActionType
let payload: Any?
}
/// Listener wrapper
/// Wrap listener to only maintain a weak ref to the listener
/// This way, listeners are not kept in momory
/// This wrapper also deal with setup and update
class EDStateListenerWrapper {
weak var listener : EDStateListener?
var setUpDone: Bool = false
init (listener: EDStateListener) {
self.listener = listener
self.tryUpdate()
}
func isInMemory() -> Bool {
return self.listener != nil
}
func tryUpdate() {
if let myListener = self.listener {
if setUpDone {
myListener.onStateUpdate()
} else {
myListener.onStateSetup()
setUpDone = true
}
}
}
}
/// Listener portocol
protocol EDStateListener: class {
func onStateUpdate()
func onStateSetup()
}
/// State manager
/// This class is a singleton, use it with EDStateManager.sharedInstance
class EDStateManager {
private var currentState = EDState()
private var previousState = EDState()
static let sharedInstance = EDStateManager()
/// Listeners
private var listeners = [EDStateListenerWrapper]();
/// Private init, because singleton
private init() {
// You can add you own setup here.
}
/// Remove released listeners and exec update
private func triggerUpdate() {
// Clean listeners
for (index, listener) in self.listeners.enumerate() {
if listener.isInMemory() == false {
self.listeners.removeAtIndex(index)
}
}
// Call stateUpdate
for listener in self.listeners {
listener.tryUpdate()
}
}
private func dequeueActions() {
dequeInProgress = true
if actionsQueue.count > 0 {
let action = self.actionsQueue.removeAtIndex(0)
// Copy state
self.previousState = self.currentState
self.currentState = reducer(currentState, action: action)
self.triggerUpdate()
dequeueActions()
}
dequeInProgress = false
}
// Dispatch an EDStateActionType
func dispatchAction(type: EDStateActionType) {
return self.dispatchAction(action, payload: nil)
}
func dispatchAction(type: EDStateActionType, payload: Any?) {
let action = EDStateAction(type: type, payload: payload)
self.actionsQueue.append(action)
if dequeInProgress == false {
dequeueActions()
}
}
/// Add a listener
/// Usualy the object register itself on init : state.addListener(self)
func addListener(listener: EDStateListener) {
let weakListener = EDStateListenerWrapper(listener: listener)
self.listeners.append(weakListener)
}
/// Reducer
/// -> Update the state
/// make changes in state
/// check value of currentState
private func reducer(previousState: EDState, action: EDStateAction) -> EDState {
var state = previousState
print("=> Action : \(action.type)")
let payload = action.payload
switch action.type {
case .SelectTab:
let newSelectedTab = payload as! Int
if currentState.user.hasASeed == false {
// Only map is allow if no seed
state.tab = 1
} else {
state.tab = newSelectedTab
}
case .SetPlantStep:
let newSteps = payload as! Int
state.steps = newSteps
case .SetPlantStatus:
let status = payload as! EDStatePlantStatus
// TODO verif status
// if status == true && self.currentState.plantIsAnimating {
// fatalError("Plant is already animating !")
// }
state.plantStatus = status
case .SetGeoloc:
let newGeoloc = payload as! CLLocationCoordinate2D
state.location = newGeoloc
case .HideCurrentPopup:
// if let popup = self.getCurrentPopup() {
// if popup == "colony" {
// state.displayedOnboarding = "Graine"
// }
// }
let tab = getCurrentTab()
state.popups[tab] = nil
case .SetOnboardingToDisplay:
let onboardingName = payload as! String
state.onboardingToDisplay = onboardingName
case .ShowOnboarding:
let onboardingName = payload as! String
state.displayedOnboarding = onboardingName
state.onboardingToDisplay = nil
case .HideOnboarding:
if currentState.displayedOnboarding == "Intro" {
state.prezStep = "yolo"
state = self.setPopup(state, popupName: "commencer", onTab: 1)
}
if currentState.displayedOnboarding == "Graine" {
self.dispatchAction(EDStateActionType.SetUnreadMessages, payload: true)
}
state.displayedOnboarding = nil
case .SetUserSeed:
state.user.hasASeed = true
case .SelectSeed:
if let seed = payload as? Seed {
state.selectedSeed = seed
} else {
state.selectedSeed = nil
}
state = updateMapPopup(state)
case .DisplayLogin:
state.loginIsDisplay = true
case .UpdatePlant:
let newPlant = payload as! EDPlant
state.plant = newPlant
case .SetPlantProgress:
let newProgress = payload as! Float
state.plantProgress = newProgress
state.nextPlantProgress = nil
case .SetCommentDisplay:
let display = payload as! Bool
state.commentViewIsDisplay = display
case .SetUnreadMessages:
let hasUnread = payload as! Bool
state.unreadMessages = hasUnread
case .SetBackgroundMode:
let back = payload as! Bool
if back == false {
state.notificationSended = false
}
state.appInBackground = back
case .NotificationSended:
state.notificationSended = true
}
state = self.updatePlant(state)
return state
}
// MARK: Sub-reducers
/**
* Sub reducer
* -> Update the state but don't trigger update
**/
func getPlantProgressForSteps(steps: Int) -> Float {
var result = 5 * log10( ( Float(steps) + 10000 ) / 10000 )
result += 0.6 // Pouce size
return result
}
func updatePlant(state: EDState) -> EDState {
var state = state
// Update progress
if currentState.user.hasASeed == false {
// if no seed Do nothing because no plant :)
return state
}
if state.plantStatus == .Generating {
return state
}
let nextProgress = self.getPlantProgressForSteps(currentState.steps)
let diff = abs(nextProgress - currentState.plantProgress)
if diff > 0.1 {
print("Generate Plant !")
state.plantStatus = .Generating
// Save nextProgress
state.nextPlantProgress = nextProgress
// Generate plant for currentState.plantProgress => nextProgress
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
self.dispatchAction(EDStateActionType.SetPlantStatus, payload: EDStatePlantStatus.Generating)
}
let nextPlant = EDPlant(
progresses: [self.previousState.plantProgress, nextProgress],
randomManager: self.randomManager,
bezierManager: self.bezierManager
)
dispatch_async(dispatch_get_main_queue()) {
self.dispatchAction(EDStateActionType.SetPlantProgress, payload: nextProgress)
self.dispatchAction(EDStateActionType.UpdatePlant, payload: nextPlant)
self.dispatchAction(EDStateActionType.SetPlantStatus, payload: EDStatePlantStatus.Generated)
}
}
// let blocksDispatchQueue = dispatch_queue_create("com.domain.blocksArray.sync", DISPATCH_QUEUE_CONCURRENT)
// dispatch_sync(blocksDispatchQueue) {
// self.dispatchAction(EDStateActionType.SetPlantStatus, payload: EDStatePlantStatus.Generating)
// let nextPlant = EDPlant(progresses: [self.previousState.plantProgress, nextProgress])
// self.dispatchAction(EDStateActionType.SetPlantProgress, payload: nextProgress)
// self.dispatchAction(EDStateActionType.UpdatePlant, payload: nextPlant)
// self.dispatchAction(EDStateActionType.SetPlantStatus, payload: EDStatePlantStatus.Generated)
// }
}
return state
}
func setPopup(state: EDState, popupName: String, onTab tabIndex: Int) -> EDState {
var state = state
state.popups[tabIndex] = popupName
return state
}
func updateMapPopup(state: EDState) -> EDState {
var state = state
if state.selectedSeed != nil {
state.popups[1] = "colony"
}
return state
}
// - MARK: Read State
/**
* -> Don't change the state, just read it
**/
func tabHasChanged() -> Bool {
return currentState.tab != previousState.tab
}
func isSelectedTab(index: Int) -> Bool {
return currentState.tab == index
}
func getCurrentTab() -> Int {
return currentState.tab
}
func getPreviousTab() -> Int {
return previousState.tab
}
func isNotifiedTab(index: Int) -> Bool {
return isNotifiedTabForState(currentState, index: index)
}
func previousIsNotifiedTab(index: Int) -> Bool {
return isNotifiedTabForState(previousState, index: index)
}
private func isNotifiedTabForState(state: EDState, index: Int) -> Bool {
if state.tab == index {
return false
}
if index == 2 && state.plantStatus == .Generated {
return true
}
if index == 3 && state.unreadMessages == true { // Chat
return true
}
let popup = state.popups[index]
if popup != nil {
return true
}
return false
}
func tabNotificationHasChanged(index: Int) -> Bool {
return isNotifiedTab(index) != previousIsNotifiedTab(index)
}
func popupHasChanged() -> Bool {
return self.getCurrentPopup() != self.getPrevioustPopup()
}
func tabBarIsDisplayed() -> Bool {
return currentState.user.hasASeed != false
}
func userHasSeed() -> Bool {
return currentState.user.hasASeed
}
func previousTabBarIsDisplayed() -> Bool {
return previousState.user.hasASeed != false
}
func tabBarDisplayHasChanged() -> Bool {
return tabBarIsDisplayed() != previousTabBarIsDisplayed()
}
func getCurrentPopup() -> String? {
return self.currentState.popups[self.currentState.tab]
}
func getPrevioustPopup() -> String? {
if self.previousState.tab >= 0 {
return self.previousState.popups[self.previousState.tab]
} else {
return nil
}
}
func plantIsGenerating() -> Bool {
return currentState.plantStatus == .Generating
}
func getPlantStatus() -> EDStatePlantStatus {
return currentState.plantStatus
}
func plantStatusHasChanged() -> Bool {
return currentState.plantStatus != previousState.plantStatus
}
func getPlant() -> EDPlant? {
return currentState.plant
}
func getCurrentTotalSteps() -> Int {
return currentState.steps
}
func getPreviousTotalSteps() -> Int {
return previousState.steps
}
func locationHasChanged() -> Bool {
return (currentState.location.latitude != previousState.location.latitude ||
currentState.location.longitude != previousState.location.longitude)
}
func getCurrentLocation() -> CLLocationCoordinate2D {
return currentState.location
}
func getProgressBarProgress() -> Float {
let plantProgress = self.getPlantProgressForSteps(currentState.steps)
print(plantProgress)
return (plantProgress % 3) / 3
}
func getOnboardingToDisplay() -> String? {
if currentState.onboardingToDisplay != previousState.onboardingToDisplay && currentState.onboardingToDisplay != nil {
return currentState.onboardingToDisplay!
}
if currentState.displayedOnboarding != nil {
return nil
}
if currentState.prezStep == "start" {
return "Intro"
}
return nil
}
func selectedSeedHasChanged() -> Bool {
if currentState.selectedSeed == nil && previousState.selectedSeed == nil {
return false
}
if currentState.selectedSeed != nil && previousState.selectedSeed == nil {
return true
}
if currentState.selectedSeed == nil && previousState.selectedSeed != nil {
return true
}
// Both not nil
return currentState.selectedSeed!.id != previousState.selectedSeed!.id
}
func distanceToSelectedSeed() -> Double? {
if currentState.selectedSeed == nil {
return nil
}
let from = CLLocation(latitude: currentState.location.latitude, longitude: currentState.location.longitude)
let to = CLLocation(latitude: currentState.selectedSeed!.coordinate.latitude, longitude: currentState.selectedSeed!.coordinate.longitude)
return from.distanceFromLocation(to)
}
func getSelectedSeed() -> Seed? {
return currentState.selectedSeed
}
func commentDisplayHasChanged() -> Bool {
return currentState.commentViewIsDisplay != previousState.commentViewIsDisplay
}
func commentIsDisplay() -> Bool {
return currentState.commentViewIsDisplay
}
func backgroundModeHasChanged() -> Bool {
return currentState.appInBackground != previousState.appInBackground
}
func isInBackgroundMode() -> Bool {
return currentState.appInBackground
}
func userIsAuthenticated() -> Bool {
// TODO join user and state
// let user = UserSingleton.sharedInstance;
// if(user.getUserData()["userId"] == nil){
//
// }
return currentState.user.isAuthenticated
}
func hasNotifToSend() -> Bool {
if currentState.appInBackground == false {
return false
}
if currentState.notificationSended == true {
return false
}
var result = false
for i in 0..<currentState.popups.count {
if currentState.popups[i] != previousState.popups[i] && currentState.popups[i] != nil {
result = true
}
}
if result == false {
if currentState.plantStatus == .Generated {
result = true
}
}
return result
}
func allFunctionnalities() -> Bool {
return currentState.steps > 20000
}
// func allFunctionnalitiesHasChanged() -> Bool{
// return currentState.fonctionnalities != previousState.fonctionnalities
// }
// - MARK: EDLocationManager Delegate
func syLocationManager(manager: EDLocationManager, didUpdateLocations locations: [CLLocation]) {
self.dispatchAction(.SetGeoloc, payload: locations[0].coordinate)
}
func syLocationManagerDidGetAuthorization(manager: EDLocationManager) {
print("Location manager Authorisation ok")
}
// - MARK: EDPedometer Delegate
func syPedometer(didReveiveData data: NSNumber) {
self.dispatchAction(.SetPlantStep, payload: Int(data))
}
}
<file_sep>/StateManagerExample/StateManagerExample/MyStateManager.swift
//
// MyStateManager
// StateManagerExample
//
// Created by <NAME> on 09/06/2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
struct MyState {
var counter: Int = 0
}
enum MyActions {
case CounterIncrement
}
func myReducer (currentState: MyState, action: (type: MyActions, payload: Any?)) -> MyState {
var state = currentState
switch action.type {
case .CounterIncrement:
state.counter += 1
}
return state
}
class MyStateRequester: EDStateRequester<MyState, MyActions> {
}
class MyStateManager {
static let sharedInstance = EDStateManager<MyState, MyActions>(
reducer: myReducer,
initialState: MyState(),
requester: MyStateRequester
)
private init() {}
}<file_sep>/StateManagerExample/StateManagerExample/StateManager.swift
//
// EDStateManager.swift
//
// Created by <NAME> on 09/05/2016.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
/// Listener wrapper
/// Wrap listener to only maintain a weak ref to the listener
/// This way, listeners are not kept in momory
/// This wrapper also deal with setup and update
class EDStateListenerWrapper {
weak var listener : EDStateListener?
var setUpDone: Bool = false
init (listener: EDStateListener) {
self.listener = listener
self.tryUpdate()
}
func isInMemory() -> Bool {
return self.listener != nil
}
func tryUpdate() {
if let myListener = self.listener {
if setUpDone {
myListener.onStateUpdate()
} else {
myListener.onStateSetup()
setUpDone = true
}
}
}
}
class EDStateRequester<stateT, actionT> {
let stateManager: EDStateManager<stateT, actionT>
init(stateManager: EDStateManager<stateT, actionT>) {
self.stateManager = stateManager
}
var currentState: stateT {
get {
return self.stateManager.currentState
}
}
var previouState: stateT {
get {
return self.stateManager.previousState
}
}
}
/// Listener portocol
protocol EDStateListener: class {
func onStateUpdate()
func onStateSetup()
}
/// State manager
/// This class is a singleton, use it with EDStateManager.sharedInstance
class EDStateManager<stateT, actionT> {
typealias EDState = stateT
typealias EDStateActionType = actionT
typealias EDStateAction = (type: EDStateActionType, payload: Any?)
typealias EDReducer = (currentState: EDState, action: EDStateAction) -> EDState
private var currentState: EDState
private var previousState: EDState
private let reducer: EDReducer
private let requester: EDStateRequester<stateT, actionT>
private var actionsQueue: [EDStateAction] = []
private var dequeInProgress: Bool = false
/// Listeners
private var listeners = [EDStateListenerWrapper]();
init(reducer: EDReducer, initialState: EDState, requester: EDStateRequester<stateT, actionT> ) {
self.reducer = reducer
self.requester = requester
currentState = initialState
previousState = initialState
}
/// Remove released listeners and exec update
private func triggerUpdate() {
// Clean listeners
for (index, listener) in self.listeners.enumerate() {
if listener.isInMemory() == false {
self.listeners.removeAtIndex(index)
}
}
// Call stateUpdate
for listener in self.listeners {
listener.tryUpdate()
}
}
private func dequeueActions() {
dequeInProgress = true
if actionsQueue.count > 0 {
let action = self.actionsQueue.removeAtIndex(0)
// Copy state
self.previousState = self.currentState
self.currentState = self.reducer(currentState: currentState, action: action)
self.triggerUpdate()
dequeueActions()
}
dequeInProgress = false
}
// Dispatch an EDStateActionType
func dispatchAction(type: EDStateActionType) {
return self.dispatchAction(type, payload: nil)
}
func dispatchAction(type: EDStateActionType, payload: Any?) {
let action = EDStateAction(type: type, payload: payload)
self.actionsQueue.append(action)
if dequeInProgress == false {
dequeueActions()
}
}
/// Add a listener
/// Usualy the object register itself on init : state.addListener(self)
func addListener(listener: EDStateListener) {
let weakListener = EDStateListenerWrapper(listener: listener)
self.listeners.append(weakListener)
}
}
| 1ed173b09abed8f315971edbeba33717ce04d6ee | [
"Swift"
] | 3 | Swift | etienne-dldc/swift-state-manager | 85f4cfcdde57ba53929f87b811471a6bbff6b121 | 41bf6086cd496fa4990a36cb4a81388c67fa3220 |
refs/heads/master | <file_sep><h1 align="center">Welcome to ktx2png 👋</h1>
> Basic KTX texture decompression tool using PVRTexTool CLI
### 🏠 [Homepage](https://github.com/PhoenixFire6879/ktx2png/blob/master/README.md)
## Prerequisites
- python 3
- you can only run this on Windows or Linux
## Usage
- run ```ktx2png.py``` and wait for the /ktx and /png folders to be created
- put textures files in /ktx folder
- run ```ktx2png.py``` again
## Author
👤 **Phoenix**
* Github: [@PhoenixFire6879](https://github.com/PhoenixFire6879)
* Discord: PhoenixFire#6879
* Twitter: [@PhoenixBSArt](https://twitter.com/PhoenixBSArt)
## 🤝 Contributing
Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/PhoenixFire6879/ktx-tool/issues).
## Show your support
Give a ⭐️ if this project helped you!
<file_sep>import os
import platform
def _(*args):
print('[Tool] ', end='')
for arg in args:
print(arg, end=' ')
print()
if not os.path.isdir('ktx/'):
os.mkdir('ktx')
if not os.path.isdir('png/'):
os.mkdir('png/')
path = './ktx'
system = platform.system()
for file in os.listdir(path):
if file.endswith(".ktx"):
filepath = 'ktx/' + file
no_extension = file.split('\\')[-1].split('.')[0]
opath = 'png/' + no_extension +'.png'
if system == 'Windows':
os.system("PVRTexToolCLI.exe -i " + filepath + " -d " + opath + " -f r8g8b8a8 ")
elif system == 'Linux':
os.system("chmod +x ./PVRTexToolCLI")
os.system("./PVRTexToolCLI -i " + filepath + " -d " + opath + " -f r8g8b8a8")
else:
_("Unsupported OS system")
| 47e0ad93939a6caba2221a40b935f1ec6098cc8c | [
"Markdown",
"Python"
] | 2 | Markdown | PhoenixFire6879/ktx-tool | b0f7fa3a9253dd54422a5de5fc959d70013224f5 | 1ef2723e586ac94eb6e2e842f2a1fcd6f22eca97 |
refs/heads/main | <file_sep>//算法1
var arr = [1, 4, 2, 3, 0, 5];
var target = 11;
function findTarget(arr, target) {
var hashTable = {};
arr.forEach(function (value, index) {
hashTable[value] = index;
//console.log(index);
});
for (var i = 0; i < arr.length; i++) {
if (hashTable[target - arr[i]]) {
//console.log([arr[hashTable[arg - arr[i]]], arr[i]]);
return true;
}
}
return false;
}
console.log(findTarget(arr, target));
//算法2
const mergeInterval=(arr)=>{
arr.sort((a,b)=> a[0] - b[0]);
let result = [];
let current = arr[0];
for(let i = 1; i<=arr.length;i++){
if(arr[i]&¤t[1]>=arr[i][0]){
current[1] = Math.max(current[1],arr[i][1]);
}else{
result.push(current); // [1,6] i =3
current = arr[i]//[7,9] i = 3
}
}
return result;
}
//作业3
function add(a,b){
return a+b;
}
function add(a){
return function (b){
return a+b;
}
}
<file_sep>//算法1
//算法2
var isPalindrome = function(s) {
s = s.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()
for(let i = 0 ; i<Math.floor(s.length/2);i++)
if(s[i]!==s[s.length-1-i])
return false
return true
};
//react1
import React from 'react'
import { useState, useEffect } from 'react';
import axios from 'axios';
const App = () => {
const [list, setList] = useState([]);
const [detail, setDetail] = useState(null);
useEffect(() => {
axios
.get('https://api.github.com/users?per_page=100')
.then(res => { setList(res.data) })
.catch(err => {
console.log(err);
})
}, []);
const handleDetial = (login) => {
axios
.get(`https://api.github.com/users/${login}`)
.then(res => { setDetail(res.data) })
.catch(err => {
console.log(err);
})
}
return (
<div>
<div>
<h2>List</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Image</th>
</tr>
</thead>
<tbody>
{list.map(({ id, login, avatar_url }) => {
return <tr key={id} onClick={() => handleDetial(login)}>
<td>{id}</td>
<td>{login}</td>
<td>
<img
src={avatar_url}
alt={`avatar for ${login}`}
style={{ height: 50, width: 50 }}
/>
</td>
</tr>
})}
</tbody>
</table>
</div>
<div>
<h2>Detail:</h2>
{detail && <div>
name: {detail.login}
location: {detail.location}
following: {detail.following}
followers: {detail.followers}
</div>}
</div>
</div>
)
}
export default App; | c7ec1f71905c55296dac24c8542d14464dea21c2 | [
"JavaScript"
] | 2 | JavaScript | alex4457/homework | b7c40e26a0ac22459798ac36a301e3d7bb678c0c | 06854a401577811f5b999273aa4ba5a9f9f8c077 |
refs/heads/master | <file_sep>import math
class LNode:
def __init__(self,elem,next_=None):
self.elem = elem
self.next = next_
class LinkedListUnderflow(ValueError): #自定义链表抛出异常错误
pass
class LList:
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def prepend(self,elem): #在最前面插入元素
self._head = LNode(elem,self._head)
def pop(self): #弹出最前面的元素
if self._head is None:
raise LinkedListUnderflow('in pop')
e = self._head.elem
self._head = self._head.next
return e
def append(self,elem): #在最后插入元素
if self._head is None:
self._head = LNode(elem)
return
p = self._head
while p.next is not None:
p = p.next
p.next = LNode(elem)
def pop_last(self): #在最后弹出元素
if self._head is None:
raise LinkedListUnderflow('in pop_last')
p = self._head
if p.next is None:
e = p.elem
self._head = None
return e
while p.next.next is not None:
p = p.next
e = p.next.elem
p.next = None
return e
def find(self,pred): #在列表中找到满足给定pred函数条件的第一个值
p = self._head
while p is not None:
if pred(p.elem):
return p.elem
p = p.next
def printall(self):
p = self._head
while p is not None:
print(p.elem, end = '')
if p.next is not None:
print(', ',end = '')
p = p.next
print('')
def elements(self): #用生成器函数实现对象的一个迭代器
p = self._head
while p is not None:
yield p.elem
p = p.next
def filter(self,pred): ##在列表中找到满足给定pred函数条件的所有值 (find的升级功能)
p = self._head
while p is not None:
if pred(p.elem):
yield p.elem
p = p.next
class LList1: #增加尾指针 后端插入提高的效率
def __init__(self):
LList.__init__(self)
self._rear = None
def prepend(self,elem): #在最前面插入元素
if self._head is None:
self._head = LNode(elem,self._head)
self._rear = self._head
else:
self._head = LNode(elem, self._head)
def append(self,elem): #后端插入提高的效率
if self._head is None:
self._head = LNode(elem,self._head)
self._rear = self._head
else:
self._rear.next = LNode(elem)
self._rear = self._rear.next
def pop_last(self):
if self._head is None:
raise LinkedListUnderflow('in pop_last')
p = self._head
if p.next is None:
e = p.elem
self._head = None
return e
while p.next.next is not None:
p = p.next
e = p.next.elem
p.next = None
self._rear = p
return e
def printall(self):
p = self._head
while p is not None:
print(p.elem, end = '')
if p.next is not None:
print(', ',end = '')
p = p.next
print('')
if __name__ == '__main__':
list1 = LList()
# for i in range(10):
# list1.prepend(i)
# for i in range(11,20):
# list1.append(i)
# list1.pop()
# list1.pop_last()
# list1.printall()
#
# for x in list1.elements():
# print(x)
# for i in list([2,4,6,2,2]):
# list1.append(i)
#
# print(list1.find(lambda x: x < 5))
# for i in list1.filter(lambda x:x<5):
# print(i)
list2 = LList1()
for i in range(11,20):
list2.append(i)
list2.printall()
<file_sep># n,m,d = map(int,input().split())
# spec = [int(c) for c in input().split()]
# parent = {}
# child = {}
# tmp = [int(c) for c in input().split()]
# for i,tm in enumerate(tmp):
# parent[i+2] = tm
# child[tm] = i+2
#第三行有n-1个整数,第i个数表示第i+1号结点的父亲结点的编号,同样在1-n之间。
# n,m,d = 6, 2, 3
# spec = [2, 1]
# parent = {2:3, 3:4, 4:5, 5:6, 6:1}
# child = {3:2, 4:3, 5:4, 6:5, 1:6}
# def get_dist(j,s):
# def dfs_l(j,s,count):
# if j == s:
# return True,count
# if j in parent.keys():
# flag,a = dfs_l(parent[j], s, count+1)
# else:
# return False,0
# return flag,a
# def dfs_r(j,s,count):
# if j == s:
# return True,count
# if j in child.keys():
# flag,a = dfs_r(child[j], s, count+1)
# else:
# return False,0
# return flag,a
# if j == s:
# return 0
# else:
# flag,dist =dfs_l(j,s,0)
# if flag == True:
# return dist
# else:
# flag, dist = dfs_r(j, s, 0)
# return dist
#
# res = []
# # 包含特殊点本身
# for j in range(1,n+1):
# count = 0
# for s in spec:
# if get_dist(j,s) <= d:
# count += 1
# continue
# else:
# break
# if count == len(spec):
# res.append(j)
# print(len(res))
# n,m,d = 6, 2, 3
# spec = [2, 1]
# parent = {2:3, 3:4, 4:5, 5:6, 6:1}
# child = {3:2, 4:3, 5:4, 6:5, 1:6}
n,m,d = map(int,input().split())
spec = [int(c) for c in input().split()]
lis = [int(c) for c in input().split()]
# nei为节点邻接表
nei = [[] for _ in range(n+1)]
for i in range(n-1):
nei[i+2].append(lis[i])
nei[lis[i]].append(i+2)
for i in range(1,n+1):
nei[i].append(i)
flag = [0] * (n+1)
for i in range(m):
dis = 1
queue = [spec[i]]
# 存储已经被遍历的节点
see = set()
while queue:
size = len(queue)
while size != 0 :
tmp = queue.pop(0)
for j in range(len(nei[tmp])):
if nei[tmp][j] not in see:
see.add(nei[tmp][j])
flag[nei[tmp][j]] += 1
for i in nei[tmp]:
if i != tmp:
queue.append(i)
size -= 1
dis += 1
if dis > d:
break
#共有多少合适的点
count = 0
for i in range(len(flag)):
if flag[i] == m:
count += 1
print(count)<file_sep>class Solution:
def cutRope(self, number):
'''
贪心解法
'''
num = number
if num == 2:
return 1
elif num == 3:
return 2
mod = num % 3
zhen = num // 3
if mod == 0:
return pow(3, zhen)
elif mod == 1:
return 2 * 2 * pow(3, zhen - 1)
else:
return 2 * pow(3, zhen)
def cutRope1(self, number):
'''
动态规划解法
'''
if number < 2:
return 0
elif number == 2:
return 1
elif number == 3:
return 2
dp = [0 for _ in range(number + 1)]
dp = [0 for _ in range(number + 1)]
dp[1] = 1
dp[2] = 2
dp[3] = 3
for i in range(4,number + 1):
for j in range(1,(number//2)+1):
dp[i] = max(dp[i],dp[j]*dp[i-j])
return dp[number]
test = Solution()
print(test.cutRope1(4))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class solution:
def __init__(self):
self.maxnode = TreeNode(0)
self.minnode = TreeNode(2**32)
def getmaxmin(self,root):
if not root:
return
if not root.left and not root.right:
if root.val > self.maxnode.val:
self.maxnode = root
elif root.val < self.minnode.val:
self.minnode = root
self.getmaxmin(root.left)
self.getmaxmin(root.right)
def getlca(self,root):
if root == None or root.val == self.maxnode.val or root.val == self.minnode.val:
return root
# 递归查找左子树是否存在p或q
left = self.getlca(root.left)
# 递归查找左子树是否存在p或q
right = self.getlca(root.right)
# 父节点的左子树或右子树查找到匹配节点,则将匹配到的节点值往上回送到父节点位置
if left and right:
return root
elif left:
return left
else:
return right
def getdist(self,lca,node):
if not lca:
return None
if lca.val == node.val:
return 0
dist = self.getdist(lca.left,node)
if dist == None:
dist = self.getdist(lca.right,node)
if dist != None:
return dist + 1
return None
def main(self,root):
'''
思路:1、首先在二叉树中找到最大、最小的权值节点
2、求得最大、最小节点的最近公共祖先
3、求得最大、最小的权值节点与最近公共祖先的距离和即为所求
:param root:
:return:
'''
self.getmaxmin(root)
lca = self.getlca(root)
dist1 = self.getdist(lca,self.maxnode)
dist2 = self.getdist(lca, self.minnode)
return dist1 + dist2
if __name__ == '__main__':
l = [5, 4, 8, 11, None, 13, 4, 14, 2, None, None, 5, 1]
tree = operate_tree.Tree()
root = tree.creatTree(l)
sol = solution()
print(sol.main(root))<file_sep>class LNode:
def __init__(self,elem,next_=None):
self.elem = elem
self.next = next_
class LinkedListUnderflow(ValueError): #自定义链表抛出异常错误
pass
class LCList: ##循环链表类
def __init__(self):
self._rear = None
def is_empty(self):
return self._rear is None
def prepend(self,elem): #在最前面插入元素
p = LNode(elem)
if self._rear is None:
p.next = p
self._rear = p
else:
p.next = self._rear.next
self._rear.next = p
def pop(self): #弹出最前面的元素
if self._rear is None:
raise LinkedListUnderflow('in pop')
p = self._rear.next
if self._rear is p:
self._rear = None
else:
self._rear.next = p.next
return p.elem
def append(self,elem): #在最后插入元素
self.prepend(elem)
self._rear = self._rear.next
# def pop_last(self): #在最后弹出元素
# if self._rear is None:
# raise LinkedListUnderflow('in pop')
#
# p = self._rear.next
# if self._rear is p:
# self._rear = None
# else:
# while p.next.next is not self._rear:
# p = p.next
# p = p.next.next
#
# return p.elem
def printall(self):
if self.is_empty():
return
p = self._rear.next
while True:
print(p.elem)
if p is self._rear:
break
p = p.next
if __name__ == '__main__':
list1 = LCList()
for i in range(10):
list1.prepend(i)
for i in range(11,20):
list1.append(i)
list1.pop()
# list1.printall()<file_sep>
def mincostTickets(days, costs):
# 这里+31是为了防止在第一个30天内,i-30的索引为负,做此初始化,则转移方程可节省条件判断语句
# dp = [0] * (days[-1] + 31)
# 1、确定状态 dp[i]表示一年内到当天为止,旅行所需的最低消费
# 3、初始化
dp = [0] * (days[-1] + 1)
# 列表中存在不唯一的数尽量用集合,速度更快
dayset = set(days)
# 4、计算顺序 自左往右
for i in range(1, days[-1]+1):
# 2、转移矩阵
if i not in dayset:
dp[i] = dp[i - 1]
else:
dp[i] = min(dp[i - 1] + costs[0], (dp[i - 30] if i >= 30 else 0) + costs[2],
(dp[i - 7] if i >= 7 else 0) + costs[1])
return dp[days[-1]]
if __name__ == '__main__':
days = [1,4,6,7,8,20]
costs = [2,7,15]
print(mincostTickets(days,costs))<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def oddEvenList(head):
if head == None or head.next == None:
return head
# 节点编号为奇数
odd = head
# 节点编号为偶数
even = head.next
evenhead = even
while even and even.next:
odd.next = even.next
# 跳到下一个奇数编号节点
odd = odd.next
even.next = odd.next
# 跳到下一个偶数编号节点
even = even.next
# 奇数编号子串与偶数编号子串连接
odd.next = evenhead
return head
if __name__ == '__main__':
l = [1,2,3,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
res = oddEvenList(cur.next)
llist.outll(res)<file_sep>def combinationSum1(candidates,target):
'''
回溯法
解题要点:1、candidates数组不含有重复元素
2、res中tmp每一项中可以包含重复元素
3、解集不能包含重复的组合
'''
def backtrack(first, remain, tmp):
# 停止条件
if remain == 0:
res.append(tmp)
return
if remain < candidates[first]:
return
# 回溯递归
for i in range(first, len(candidates)):
# 剪枝
if candidates[i] > remain:
break
# 后续可能还需要用到candidates[i]
backtrack(i, remain - candidates[i], tmp + [candidates[i]])
res = []
candidates.sort()
backtrack(0, target, [])
return res
####################################40###########################################
def combinationSum2(candidates,target):
'''
解题要点:1、candidates数组含有重复元素
2、candidates中的每个数字在每个组合中只能使用一次
3、解集不能包含重复的组合
'''
def backtrack(first, remain, tmp):
# 停止条件
if remain == 0:
res.append(tmp)
return
if not candidates or remain < 0:
return
# 回溯递归
for i in range(first,len(candidates)):
# (剪枝)遇到相同的数跳过
if i > first and candidates[i] == candidates[i - 1]:
continue
# 同上
if candidates[i] > remain:
break
# candidates[i]已经取过,后续不能再使用
backtrack(i + 1, remain - candidates[i], tmp + [candidates[i]])
res = []
candidates.sort()
backtrack(0, target, [])
return res
if __name__ == '__main__':
candidates = [2,3,6,7]
target = 7
candidates2 = [10,1,2,7,6,1,5]
target2 = 8
# print(combinationSum1(candidates,target))
print(combinationSum2(candidates2,target2))
<file_sep>
# n = int(input())
# Qs = input()
# dic = {}
# duiying = {0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M'}
# for i,c in enumerate(input().split()):
# dic[duiying[i]] = int(c)
#
# res = float('-inf')
# for k in dic.keys():
# if k in Qs:
# continue
# if dic[k] > res:
# res = dic[k]
# flag = k
#
# print(flag)
n,m,k = map(int,input().split())
dic = {}
seen = set()
butong_lau = 0
for i in range(k):
u,v = map(int,input().split())
dic[u] = v
if v not in seen:
seen.add(v)
butong_lau += 1
no_lau = 0
for i in range(1,n+1):
if i not in dic.keys():
no_lau += 1
# 所有人都会语言
if no_lau == 0:
print(butong_lau - 1)
# 有一些人会,有一些人不会
else:
res = (no_lau - 1) + butong_lau-1
print(res)
<file_sep>def findLengthOfLCIS( nums):
'''
最长连续递增子序列
不需要动态规划
:param nums:
:return:
'''
if len(nums) < 1:
return 0
res = 1
index = 0
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
res = max(res, i - index + 1)
else:
index = i
return res
<file_sep>def factor(x):
total = 0
for i in range(1,x+1):
if x%i == 0:
total += 1
# x若为奇数个约数,则为最后亮的灯
return 1 if total % 2 == 1 else 0
def totallight(num,n):
count = 0
res = []
for i in range(n):
if factor(num[i]) == 1:
count += 1
res.append(num[i])
return res,count
if __name__ == '__main__':
n = 100
num = [0] * n
for i in range(n):
num[i] = i+1
print(totallight(num,n))<file_sep>def myPow(x, n):
'''
思路:迭代 时间复杂度:O(logn) 空间复杂度O(1)
:param x:
:param n:
:return:
'''
if n < 0:
x = 1 / x
n = -n
pow = 1
# x为当前乘子系数
# pow为最后输出的值
while n:
# 若n为奇数,先将n-1乘上
if n % 2 != 0:
pow *= x
# 此时n-1为偶数,将乘子系数连乘,
x *= x
# 将n//2
n >>= 1
return pow
def myPow1( x, n):
'''
思路:递归 时间复杂度:O(logn) 空间复杂度O(logn)
:param x:
:param n:
:return:
'''
def fastPow(x, n):
if (n == 0):
return 1
half = fastPow(x, n // 2)
if (n % 2 == 0):
return half * half
else:
return half * half * x
if (n < 0):
x = 1 / x
n = -n
return fastPow(x, n)
print(myPow(2,16))
<file_sep>
def addBinary(a, b):
a = int(a, 2)
b = int(b, 2)
binary = lambda n: '' if n == 0 else binary(n // 2) + str(n % 2)
return binary(a + b) if a + b != 0 else '0'
def addBinary2(a, b):
a = int(a, 2)
b = int(b, 2)
# return bin(a+b)[2:]
return "{0:b}".format(a+b) #################二进制与十进制转换
if __name__ == '__main__':
a = "1010"
b = "1011"
print(addBinary2(a,b))
<file_sep>def Add(num1, num2):
while num2:
# & 0xFFFFFFFF的作用是超过32位的越界处理 因为python数据结构会自动增位
temp = (num1 ^ num2) & 0xFFFFFFFF
num2 = ((num1 & num2) << 1) & 0xFFFFFFFF
num1 = temp
# <= 0x7FFFFFFF表示是正数 ~(num1 ^ 0xFFFFFFFF) 表示负数的补码 ~n = -(n+1)
return num1 if num1 <= 0x7FFFFFFF else ~(num1 ^ 0xFFFFFFFF)<file_sep>
# X = [5,13,4]
# Y = [2,7,12]
# Z = ['113221101000101','1016','2222248A']
T = int(input())
def func(x,y,z):
x = int(x)
y = int(y)
for i in range(1,len(z)):
try :
valx = int(z[:i],x)
valy = int(z[i:],y)
except:
continue
if valx == valy:
return valx
for i in range(T):
a = [x for x in input().split()]
X,Y,Z = a[0],a[1],a[2]
print(func(X,Y,Z))
<file_sep>def removeBoxes(nums):
n = len(nums)
dp = [[[0] * n for _ in range(n)] for _ in range(n)]
# dp[i][j][k] 表示在 [i,j]部分能得到的最大得分
# k表示boxes[i]左边有k个与之相等的数可以与它结合(可能原本有多余k个数,但是能和它合并一起消失的,只有k个)
# 如...X DFD X DFDF X SDF [X LSKDFJ X LSJDFLK X DLKFJ...]
# dp[i][j][k]表示只考虑[]部分对分数的贡献,那么第一个X可能跟着前面K个X消失,也可能等着后面的X一起消失
# 1. 跟前面的k个一起消失的话 得分为 (k+1)**2 + helper(i+1,j,0)
# 2.1 跟后面的第二个X一起消失的话,[]中的“LSKDFJ” 部分独立拿分,X成为第二个X开头的子序的前导之一 k->1+k
# 得分为helper(i+1,m-1,0)+helper(m,j,1+k) m此时是第二个X的序号
# 2.2 跟后面的第三个X一起消失的话,[]中的“LSKDFJ X LSJDFLK” 部分独立拿分,X成为第三个X开头的子序的前导之一 k->1+k
# 得分还是helper(i+1,m-1,0)+helper(m,j,1+k) m此时是第三个X的序号
# 2.3 至于“LSKDFJ”与“LSJDFLK”部分分别独立拿分,再合并k+3个X拿分的情况,包含于2.1情况中
# 因为helper(m,j,1+k) 可以递归,下一层的2.1情况就是前K个与第一个X第二个X和第三个X合并
# 所以只用考虑[]中第一个X与第Y个X直接合并,中间部分作为子区间独立拿分的情况
# 几种情况取最高得分,并存入dp[i][j][k]
def helper(i, j, k):
if i > j:
return 0
if dp[i][j][k] != 0:
return dp[i][j][k]
while i < j and nums[i] == nums[i + 1]:
i += 1
k += 1
res = (k + 1) ** 2 + helper(i + 1, j, 0)
for m in range(i + 1, j + 1):
if nums[m] == nums[i]:
res = max(res, helper(i + 1, m - 1, 0) + helper(m, j, 1 + k))
dp[i][j][k] = res
return dp[i][j][k]
return helper(0, n - 1, 0)
<file_sep>from Tree import operate_tree
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
def GetNext(self, pNode):
'''
分三种情况来写代码
:param pNode:
:return:
'''
node = pNode
if not node:
return
# 若当前节点有右子树,下一个结点即为右子树最左下角的节点
if node.right:
res = node.right
while res.left:
res = res.left
return res
# 若没有右子树,且节点是父结点的左节点,那么下一个结点就是当前节点的父结点
# 若节点不是父结点的左节点,那么一直往上找父结点直到找到一个节点是父结点的左节点,返回该父结点
else:
while node.next:
#
if node.next.left == node:
return node.next
node = node.next
return
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def swapPairs(head):
'''
思路:处理链表中的三个节点三个节点:head、head.next、未处理完的链表部分
交换两节点head、head.next
:param head:
:return:
'''
if not head or not head.next:
return head
nex = head.next
# 由于是从左往右递归
# swapPairs(nex.next)处理右边节点后面的未完成的链表部分
head.next = swapPairs(nex.next)
nex.next = head
return nex
def swapPairs1(head):
if not head or not head.next:
return head
res = LNode(0)
res.next = head
pre = res
cur = res.next
while cur and cur.next:
pre.next = cur.next
cur.next = cur.next.next #这一步把cur.next移到pre.next的节点清除
pre.next.next = cur
pre = cur
cur = cur.next
return res.next
if __name__ == '__main__':
l = [1,2,3,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
res = swapPairs1(cur.next)
llist.outll(res)<file_sep># python3
def main():
case = int(input())
for t in range(case):
n = int(input())
golds = [int(c) for c in input().split()]
# dp[i][j]表示在golds[i-1:j]中博弈时,先手方最多能拿到多少价值
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
sum = [0 for _ in range(n + 1)]
#初始化
for i in range(1, n + 1):
sum[i] = sum[i - 1] + golds[i - 1]
dp[i][i] = golds[i - 1]
for j in range(n):
for i in range(1, n):
if i + j <= n:
# i+j为序列右边边界
# min(dp[i + 1][i + j], dp[i][i + j - 1])最小化对手价值
# sum[i + j] - sum[i - 1] 为sum(golds[i-1:i+j])
dp[i][i + j] = sum[i + j] - sum[i - 1] - min(dp[i + 1][i + j], dp[i][i + j - 1])
print ('Case #%d: %d %d'%(t + 1, dp[1][n], sum[n] - dp[1][n]))
if __name__ == '__main__':
main()
<file_sep>def find_root(x,parent):
'''
找到当前节点的父根节点
:param x:
:param parent:
:return:
'''
x_root = x
while parent[x_root] != -1:
x_root = parent[x_root]
return x_root
def union_vertices(x,y,parent,rank):
'''
合并两个集合
:param x:
:param y:
:param parent:
:return:
'''
x_root = find_root(x, parent)
y_root = find_root(y, parent)
# 合并失败,不进行合并
if x_root == y_root:
return 0
# 合并x的父结点与y的父结点
else:
# parent[x_root] = y_root(未压缩路径,可能使长路径接到短路金父结点,增加了路径长度)
# 压缩路径,将短路径的父结点接到长路径的父结点
if rank[x_root] > rank[y_root]:
parent[y_root] = x_root
elif rank[y_root] > rank[x_root]:
parent[x_root] = y_root
else:
parent[x_root] = y_root
rank[y_root] += 1
return 1
def test():
# 顶点数量
num = 6
parent = [-1] * num
# rank记录查找路径的长度
rank = [0] * num
edges = [[0, 1], [1, 2], [1, 3], [2, 4], [3, 4], [2, 5]]
for i in range(len(edges)):
x = edges[i][0]
y = edges[i][1]
if union_vertices(x, y, parent,rank) == 0:
print('检测到环')
exit(0)
print('未检测到环')
if __name__ == '__main__':
test()
<file_sep>class permutation:
'''
题型:带限定条件的排列问题
'''
def __init__(self,arr):
self.nums = arr
self.n = len(self.nums)
self.visited = [None]*self.n
self.graph = [[None]*self.n for _ in range(self.n)]
self.comb = ''
# 这里采用集合来存储答案是因为重复的数会多计算一次相同的组合,采用hash集合进行过滤
self.res = set()
def dfs(self,start):
self.visited[start] = True
self.comb += str(self.nums[start])
if len(self.comb) == self.n:
# 将字符串第3位不为'4'的组合存下
if self.comb.index('4') != 2:
self.res.add(self.comb)
for j in range(self.n):
if self.graph[start][j] == 1 and self.visited[j] == False:
self.dfs(j)
self.comb = self.comb[:-1]
self.visited[start] = False
def getallcomb(self):
# 构建图的关系
for i in range(self.n):
for j in range(self.n):
if i==j:
self.graph[i][j] = 0
else:
self.graph[i][j] = 1
# 组合中3与5不能直接连接
self.graph[3][5] = 0
self.graph[5][3] = 0
# 以每个节点作为开始节点进行深度遍历
for i in range(self.n):
self.dfs(i)
return self.res
if __name__ == '__main__':
arr = [1,2,2,3,4,5]
t = permutation(arr)
print(t.getallcomb())
<file_sep>def FindContinuousSequence(tsum):
'''
low,high双指针 动态滑动窗口
:param tsum:
:return:
'''
res = []
if tsum == 1:
return []
low = 1
high = 2
while low < high:
summ = (low + high)*(high - low + 1) // 2
if summ == tsum:
res.append([x for x in range(low, high + 1)])
low += 1
elif summ < tsum:
high += 1
else:
# 此时左指针定位的元素开始不能使得凑出和为tsum 故左指针右移
low += 1
return res
def FindContinuousSequence1(tsum):
res=[]
for i in range(1,tsum//2+1):
sumRes = i
for j in range(i+1,tsum//2+2):
sumRes += j
if sumRes == tsum:
res.append(list(range(i, j+1)))
break
elif sumRes > tsum:
break
return res
<file_sep># -*- coding: utf-8 -*-
from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def getIntersectionNode(headA, headB): ###本题是要求交集,理解题意,不是求一个公共交点
if headA is None or headB is None:
return None
pa = headA
pb = headB
while pa is not pb: #?本地通不过出不来结果
pa = headB if pa is None else pa.next
pb = headA if pb is None else pb.next
return pa
def getIntersectionNode1(headA, headB): ###???
if (headA is None) | (headB is None):
return None
last = headB
while last.next:
last = last.next
last.next = headB
slow, fast = headA, headA
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
slow = headA
while slow != fast:
slow = slow.next
fast = fast.next
last.next = None
return slow
last.next = None
return None
def getIntersectionNode2( headA, headB): #哈希表法
has = set()
while headA:
has.add(headA)
headA = headA.next
while headB:
if headB in has:
return headB
headB = headB.next
return None
if __name__ == '__main__':
l1 = [4,1,8,4,5]
l2 = [5,0,1,8,4,5]
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
cur2 = llist.initList(l2)
res = getIntersectionNode2(cur1.next,cur2.next)
print('输出')
llist.outll(res)<file_sep>class board:
def __init__(self,L,W):
self.l = L
self.w = W
class dpc:
def __init__(self,l,h):
self.l = l
self.h = h
def main(n,L,W):
boards = []
l = 0
for i in range(n):
boards.append(board(L[i],W[i]))
l += W[i]
# 类对象排序,先按x.w排序,再按x.l排序
# 重量排序的优先级高于长度排序的优先级
# 思路:先选择重量较小的木板作为塔顶,逐次往下找到合适的木板
boards.sort(key=lambda x:(x.w,x.l))
dp = [dpc(0,0) for _ in range(l+5)]
summ = 0
res = 0
for i in range(n):
# boards[i]代表最底部的木板
# dp
for j in range(summ, -1, -1):
# j代表boards[i]上共累积的重量
if boards[i].w * 7 >= j:
# 寻找的boards[i]的长度应使得大于前总重量下木板的最长长度
if dp[j].l < boards[i].l:
#
if dp[j].h+1 > dp[j+boards[i].w].h:
# j+boards[i].w表示选择了boards[i],当前所有木板的重量,
# dp[x].h表示当前总重量下最大的金字塔高度
# dp[x].l表示当前总重量下木板的最长长度
# 思路:由已经选择的木板来选择最底部的木板
dp[j+boards[i].w].h = dp[j].h + 1
dp[j+boards[i].w].l = boards[i].l
# 找到最优高度
res = max(res,dp[j+boards[i].w].h)
summ += boards[i].w
return res
def main2(n,L,W):
boards = []
l = 0
for i in range(n):
boards.append(board(L[i], W[i]))
l += W[i]
boards.sort(key=lambda x: (x.l, x.w))
res = 1
# dp[i][h]记录以第i块积木为底, 高为h的积木塔的最低重量.
dp = [[-1] * (n+1) for _ in range(n)]
dp[0][1] = boards[0].w
for i in range(1,n):
dp[i][1] = boards[i].w
for h in range(2,n+1):
for j in range(i-1,-1,-1):
if dp[j][h-1] != -1 and boards[i].w * 7 >= dp[j][h-1] and (dp[i][h] == -1 or boards[i].w + dp[j][h-1] < dp[i][h]):
res = max(res,h)
dp[i][h] = boards[i].w + dp[j][h-1]
return res
if __name__ == '__main__':
n = 10
L = [1,2,3,4,5,6,7,8,9,10]
W = [1,1,1,1,1,1,1,1,1,10]
print(main(n,L,W))<file_sep>class Solution:
def __init__(self):
self.A = []
self.B = []
def push(self, node):
# write code here
self.A.append(node)
def pop(self):
# return xx
if not self.B:
while self.A:
self.B.append(self.A.pop())
first = self.B.pop()
return first<file_sep>def trailingZeroes(n):
'''
统计数字1...n中,是5的倍数,25的倍数。。。的数量
:param n:
:return:
'''
res = 0
while n >= 5:
n = n // 5
res += n
return res<file_sep>from collections import deque,defaultdict
###方法一:贪心BFS算法(非最短路径)
class Qitem():
def __init__(self,word,lens):
self.word = word
self.lens = lens
def isdiff(str1,str2):
diff = 0
for i in range(len(str1)):
if str1[i] != str2[i]:
diff += 1
if diff > 1:
return False
return True
def shortestchain(D,start,target):
Q = deque()
item = Qitem(start,1)
Q.append(item)
while len(Q) > 0:
curr = Q[0]
Q.pop()
for it in D:
temp = it
if isdiff(curr.word,temp):
item.word = temp
item.lens += 1
Q.append(item)
D.remove(temp)
if temp == target:
return item.lens
return 0
###方法二:BFS
def shortestchain1(wordList,beginWord,endWord):
'''
思路:双向BFS
'''
if not beginWord or not endWord or not wordList or endWord not in wordList:
return 0
n = len(beginWord)
wordList_dict = defaultdict(list)
for word in wordList:
for i in range(n):
wordList_dict[word[:i] + '*' + word[i + 1:]].append(word)
levels_l = [(beginWord, 1)]
levels_2 = [(endWord, 1)]
used_dict1 = {beginWord: 1}
used_dict2 = {endWord: 1}
def visit(n, used_dict1, used_dict2, levels):
word1, level = levels.pop(0)
for i in range(n):
mid_word = word1[:i] + '*' + word1[i + 1:]
for word in wordList_dict[mid_word]:
if word not in used_dict1:
if word in used_dict2:
return level + used_dict2[word]
levels.append((word, level + 1))
used_dict1[word] = level + 1
else:
if word in used_dict2:
return used_dict1[word] + used_dict2[word]
return 0
while levels_l and levels_2:
cn1 = visit(n, used_dict1, used_dict2, levels_l)
if cn1:
return cn1
cn2 = visit(n, used_dict2, used_dict1, levels_2)
if cn2:
return cn2
return 0
def shortestchain2(wordList,beginWord,endWord):
if endWord not in wordList:
return 0
l = len(endWord)
ws = set(wordList)
head = {beginWord}
tail = {endWord}
tmp = list('abcdefghijklmnopqrstuvwxyz')
res = 1
while head:
if len(head) > len(tail):
head, tail = tail, head
q = set()
for cur in head:
for i in range(l):
for j in tmp:
word = cur[:i] + j + cur[i + 1:]
if word in tail:
return res + 1
if word in ws:
q.add(word)
ws.remove(word)
head = q
res += 1
return 0 #对本测试例出现错误 待调试
if __name__ == '__main__':
D = ['pooN','pbcc','zamc','poIc','pbca','pbIc','poIN']
start = 'TooN'
target = 'pbca'
print(shortestchain1(D,start,target))
<file_sep>class sol:
def __init__(self):
self.res = []
def helper(self, s1, s2, t, T, index):
'''
:param s1:
:param s2:
:param t:表示新序列的字符串
:param T:将s1转化为t所需要执行的操作
:param index:操作s1的总次数
:return:
'''
# 停止条件
if index == len(s1):
if (s2 == t) and T not in self.res:
self.res.append(T)
return
self.helper(s1, s2, t, T + "d", index + 1)
self.helper(s1, s2, s1[index] + t, T + "l", index + 1)
self.helper(s1, s2, t + s1[index], T + "r", index + 1)
def main(self):
# 局数
n = int(input())
# 每一局的
while n > 0:
s1 = input()
s2 = input()
# 每一局都需要重新清理结果列表
self.res = []
self.helper(s1, s2, "", "", 0)
# 输出
print("{")
for k in self.res:
print(' '.join(c for c in k))
print("}")
n -= 1
test = sol()
test.main()
<file_sep># T = int(input())
def get_end(st,end,grid):
e0 = end[0]
e1 = end[1]
# 这里题意有点问题,不知道是否需要更改起点grid的状态
def dfs(i,j,grid):
# 遍历到终点,且终点网格位置为'X'
if i == e0 and j == e1 and grid[i][j] == 'X':
return True
# 遍历到终点,且终点网格位置为'.'
if i == e0 and j == e1 and grid[i][j] == '.':
if grid[i+1][j] == '0' and grid[i-1][j] == '0' and grid[i][j+1] == '0' and grid[i][j-1] == '0':
return False
else:
return True
# 遍历到非终点,且终点网格位置为'.'
if 0 <= i < n and 0 <= j < m and grid[i][j] == '.':
grid[i][j] = 'X'
if 0 <= i+1 < n and 0 <= j < m and grid[i + 1][j] != '0':
return dfs(i + 1, j, grid)
if 0 <= i-1 < n and 0 <= j < m and grid[i - 1][j] != '0':
return dfs(i - 1, j, grid)
if 0 <= i < n and 0 <= j-1 < m and grid[i][j - 1] != '0':
return dfs(i, j - 1, grid)
if 0 <= i < n and 0 <= j+1 < m and grid[i][j + 1] != '0':
return dfs(i, j + 1, grid)
# 遍历到非终点,且终点网格位置为'X'
if 0 <= i < n and 0 <= j < m and grid[i][j] == 'X':
grid[i][j] = '0'
if 0 <= i+1 < n and 0 <= j < m and grid[i + 1][j] != '0':
return dfs(i + 1, j, grid)
if 0 <= i-1 < n and 0 <= j < m and grid[i - 1][j] != '0':
return dfs(i - 1, j, grid)
if 0 <= i < n and 0 <= j-1 < m and grid[i][j - 1] != '0':
return dfs(i, j - 1, grid)
if 0 <= i < n and 0 <= j+1 < m and grid[i][j + 1] != '0':
return dfs(i, j + 1, grid)
return False
return dfs(st[0], st[1], grid)
T = 1
for _ in range(T):
# n,m = map(int,input().split())
# grid = []
# for i in range(n):
# grid.append(list(input()))
n,m =9,47
# grid1 = ['X...XX','...XX.','.X..X.','......']
grid1 = ['....X.X.X.X...X..X.....X..X..X..X....X.X...X..X',
'XX..X...X.........X...X...X..X.XX......X...X...',
'..XX...X.......X.....X.....X.XX..X.....X..XX...',
'.X...XX....X...X.......X.X...X......X.X.X......',
'X......X..X.XXX....X...X.X.XX..X.......X....X.X',
'....XX.X...X.XXX.X..XX.XXX...XXX..XX.X.X.XX..XX',
'.........X...X.XXXX...XX.XX....XX..X...X....X..',
'.............X....XXXX....X.X...XX.XX.X.X..X...',
'.X......X.....X......X......X.X.X..X.......XXX.']
grid = [list(x) for x in grid1]
# st = list(input().split())
# end = list(input().split())
st = [1,33]
end=[6,29]
if get_end(st,end,grid):
print('YES')
else:
print('NO')
<file_sep>#思路
# 对于N个数中任意两个数a,b(a!=b)考虑先后顺序 , 有(a,b)及(b,a)两种情况
# 对于其中的(a,b)情况有,将其视为一个整体,插入到剩下的(N-2)个数中,有(N-1)种方法,同时剩下的N-2个数有(N-2)!种组合方式
# 进而推出对N!个序列有(N-1)!种情况。
# 同理对(b,a)也有(N-1)!种情况。
# 一共有C(N,2)对数对,对于(a,b)及(b,a)移动代价相同,所以只需求出C(N,2)对数的代价P
# 最后 P * 2 * ((N-1)!) 即为最终解
# N = int(input())
# X = [int(c) for c in input().split()]
N = 5
X = [0,1,3,5,8]
mod = 10**9+7
def jie(num):
'''
计算(num)!
:param num:
:return:
'''
plus = 1
while num:
plus = (plus*num)%mod
num -= 1
return plus
summ = 0
tmp = 0
'''
for i in range(N):
for j in range(i+1,N):
tmp=(X[j]-X[i])
sum=(sum+tmp)%mod
'''
# 在上面基础优化
for i in range(1,len(X)):
# tmp为当前
tmp = (tmp + X[i-1])%mod
# summ:上一轮的代价 X[i]*i-tmp为加入X[i]后,新增的权重代价
summ = (summ + (X[i]*i-tmp))%mod
# 2 * (N-1)!
count = jie(N-1)*2 % mod
print((summ*count) % mod)<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def addTwoNumbers(l1, l2, carry=0):
'''
:param l1:
:param l2:
:param carry: carry判断两数之和是否有进位
:return:
'''
# l1,l2输入都为空
# 有进位要返回进位
if not l1 and not l2:
return LNode(1) if carry else None
# l1,l2取完,则后续其值赋为0
l1 = l1 or LNode(0)
l2 = l2 or LNode(0)
val = l1.val + l2.val + carry
# 链表l1存储两数之和
l1.val = val % 10
l1.next = addTwoNumbers(l1.next,l2.next,val > 9)
return l1 #
def addTwoNumbers1(l1, l2):
res = LNode(0)
tmp = res
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
summ = x + y + carry
tmp.next = LNode(summ % 10)
carry = summ // 10
tmp = tmp.next
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry > 0:
tmp.next = LNode(1)
return res.next
if __name__ == '__main__':
l1 = [2,4,3]
l2 = [5,6,4]
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
cur2 = llist.initList(l2)
res = addTwoNumbers(cur1.next, cur2.next)
llist.outll(res)<file_sep>
# 1. 三个同样的字母连在一起,一定是拼写错误,去掉一个的就好啦:比如 helllo -> hello
# 2. 两对一样的字母(AABB型)连在一起,一定是拼写错误,去掉第二对的一个字母就好啦:比如 helloo -> hello
# 3. 上面的规则优先“从左到右”匹配,即如果是AABBCC,虽然AABB和BBCC都是错误拼写,应该优先考虑修复AABB,结果为AABCC
n = int(input())
for _ in range(n):
s = input()
# res存储不被删除的数
res = []
for e in s:
if len(res) < 2:
res.append(e)
continue
# 判断AAA型
if len(res) >= 2:
if e == res[-1] and e == res[-2]:
continue
# 判断AABB型
if len(res) >= 3:
if e == res[-1] and res[-2] == res[-3]:
continue
res.append(e)
print("".join(res))
<file_sep>'''
方法一:暴力法
'''
def lengthOfLongestSubstring(s):
n = len(s)
res = 0
for i in range(n):
for j in range(i+1,n+1):
if allunique(s,i,j):
res = max(res,j-i)
return res
def allunique(s,st,end):
uni = []
for i in range(st,end):
if s[i] in uni:
return False
uni.append(s[i])
return True
'''
方法二:滑动窗口法 (类似队列)
'''
def lengthOfLongestSubstring1(s):
n = len(s)
uni = []
res = 0
i,j = 0,0
while i < n and j < n:
if s[j] not in uni:
uni.append(s[j])
j += 1
res = max(res,j-i)
else:
uni.remove(s[i])
i += 1
return res
'''
方法三:优化的滑动窗口法 substr即为窗
'''
def lengthOfLongestSubstring2(s):
'''
substr:即为输出的无重复字符的最长子串
'''
substr = ''
maxlen = 0
for char in s:
if char not in substr:
substr += char
maxlen = max(maxlen, len(substr))
else:
substr = substr[substr.index(char) + 1:] + char
return maxlen
if __name__ == '__main__':
s = 'pwwkew'
print(lengthOfLongestSubstring2(s))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#################################二叉搜索树的最近公共祖先###################### 235
def lowestCommonAncestor(root, p, q): #递归方法 利用二叉搜索树的性质快速求解
if not root or not p or not q:
return
if p.val < root.val and q.val < root.val:
return lowestCommonAncestor(root.left,p,q)
elif p.val > root.val and q.val > root.val:
return lowestCommonAncestor(root.right,p,q)
return root
def lowestCommonAncestor1(root, p, q): #非递归方法
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
########################################二叉树的最近公共祖先############################### 236
def lowestCommonAncestor2(root,p,q):
if root == None or root.val == p.val or root.val == q.val:
return root
# 递归查找左子树是否存在p或q
left = lowestCommonAncestor2(root.left,p,q)
# 递归查找左子树是否存在p或q
right = lowestCommonAncestor2(root.right,p,q)
# 父节点的左子树或右子树查找到匹配节点,则将匹配到的节点值往上回送到父节点位置
if left and right:
return root
elif left:
return left
else:
return right
if __name__ == '__main__':
l = [3,5,1,6,2,0,8,None,None,7,4]
p = 0
q = 8
tree = operate_tree.Tree()
print(lowestCommonAncestor2(tree.creatTree(l),TreeNode(p),TreeNode(q)).val) #输出该节点的值
<file_sep># 思路: 单纯数学规律,从第一个数字开始,每 2m 个数字之和为 m^2,总共有 n/2m 个这样的组合,因此和为 m*n/2
s = input()
n, m = [int(i) for i in s.split(' ')]
print((n*m)//2)
<file_sep>import collections
#空间占用多,速度慢
def leastInterval(tasks, n):
dic = {}
for i in tasks:
if i not in dic.keys():
dic[i] = 1
else:
dic[i] += 1
dic = sorted(dic.items(),key = lambda x:x[1],reverse=True)
max_len = 0
same_count = 0
for i in dic:
if i[1] >= max_len:
max_len = i[1]
same_count += 1
else:
break
return max((max_len - 1) * (n + 1) + same_count, len(tasks))
def leastInterval2(tasks, n):
apt = [tasks.count(x) for x in set(tasks)]
max_len = max(apt)
same_count = apt.count(max_len)
return max((max_len - 1) * (n + 1) + same_count, len(tasks))
def leastInterval3(tasks, n): #优化
cdict = collections.Counter(tasks) #dict_value类型 可迭代
max_len = max(cdict.values())
same_count = list(cdict.values()).count(max_len)
return max((max_len - 1) * (n + 1) + same_count, len(tasks))
if __name__ == '__main__':
tasks = ["A", "A", "A", "B", "B", "B"]
n = 2
print(leastInterval3(tasks, n))<file_sep>def ispopserial(push,pop):
if not push or not pop:
return False
pushlen = len(push)
poplen = len(pop)
if pushlen != poplen:
return False
pushind = 0
popind = 0
stack = []
while pushind < pushlen:
stack.append(push[pushind])
pushind += 1
# 没push一个元素就判断它是否可以被pop
while stack and stack[-1] == pop[popind]:
stack.pop()
popind += 1
return len(stack) == 0 and popind == poplen
if __name__ == '__main__':
push = '12345'
pop = '35412'
print(ispopserial(push,pop))<file_sep>
def getallcomb(nsum,pdata,ndepth):
'''
题意:给定一个正整数n,求解出所有和为n的整数组合,要求组合按照递增方式展示,而且唯一
:param nsum: 给定的整整n
:param pdata: 存储递归时组合的数
:param ndepth: 记录组合总数字的个数
:return:
'''
if nsum < 0:
return
# 已达到要求,输出该整数组合
if nsum == 0:
print([pdata[j] for j in range(ndepth)])
return
# 记录本层节点父节点的取值
start = (1 if ndepth == 0 else pdata[ndepth-1])
# 该子树下,下一个递归节点的可取值(要保证本层节点的取值大于上层节点的取值)
# 如果不要求组合按照递增方式,则上述start取值为1
for i in range(start,nsum+1):
pdata[ndepth] = i
ndepth += 1
getallcomb(nsum-i,pdata,ndepth)
ndepth -= 1
if __name__ == '__main__':
n = 10
result = [None] * n
getallcomb(n,result,0)
<file_sep>n,k = 3,2
class tower:
def __init__(self,id,h):
self.id = id
self.h = h
towers = [tower(i,int(c)) for i,c in enumerate([5,8,5])]
res = []
for i in range(k):
max_ind = towers.index(max(towers, key=lambda x: x.h))
min_ind = towers.index(min(towers, key=lambda x: x.h))
res.append([max_ind+1, min_ind+1])
towers[max_ind].h -= 1
towers[min_ind].h += 1
if max(towers, key=lambda x: x.h).h - min(towers, key=lambda x: x.h).h < 2:
break
print("%d %d" % (max(towers, key=lambda x: x.h).h - min(towers, key=lambda x: x.h).h, len(res)))
for i in range(len(res)):
print("%d %d" % (res[i][0], res[i][1]))
<file_sep>def firstWillWin(n):
'''
两人摸石子问题
动态规划思想
:param n:
:return:
'''
# 石子数还剩为n,是否可赢
dp = [False]*(n+1)
dp[1] = dp[2] = True
for i in range(3,n+1):
#表示本轮先手可取1或
dp[i] = (dp[i - 1] == False | dp[i - 2] == False)
return dp[n]
# 数学归纳法得到:n%3 != 0
if __name__ == '__main__':
n = 5
print(firstWillWin(n))
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildtree(preorder,inorder):
'''
中序列表中每个节点具有划分左右子树的作用
:param preorder:
:param inorder:
:return:
'''
# 由中序遍历判断子节点,由先序遍历构建子树
def build(pre,prestart,preend,instart,inpos):
if prestart > preend:
return
# 先序遍历建子树
root = TreeNode(pre[prestart])
# root节点在中序列表中的位置 为后面划分左右子树做准备
rootidx = inpos[root.val]
# 左子树在preorder所占长度
leftLen = rootidx - instart
### 通过不断迭代缩小prestart-preend的范围缩小了递归的时间
# 递归构建左子树 root占据了prestart的位置 , 故prestart+1
root.left = build(pre, prestart + 1, prestart + leftLen, instart, inpos)
# 递归构建右子树 rootidx + 1是右子树在inoder中第一个输出的节点
root.right = build(pre, prestart + leftLen + 1, preend, rootidx + 1, inpos)
return root
inPos = {val: idx for idx, val in enumerate(inorder)}
return build(preorder, 0, len(preorder)-1, 0, inPos)
def buildtree1(preorder,inorder):
'''
pre.pop(0)缩减代码 , 同时也可以将index在中序数组的下标搜索提前用哈希表保存下来
:param preorder:
:param inorder:
:return:
'''
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
for i in range(len(inorder)):
if preorder[0] == inorder[i]:
root.left = buildtree1(preorder[1:i+1], inorder[:i])
root.right = buildtree1(preorder[i+1:], inorder[i + 1:])
break
return root
if __name__ == '__main__':
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
tree = operate_tree.Tree()
result = buildtree1(preorder, inorder)
print(tree.levelOrder(result))
<file_sep>class Solution:
def LastRemaining_Solution(self, n, m):
if n < 1 or m < 1:
return -1
res = 0
for i in range(2, n):
res = (res + m) % i
return res
def LastRemaining_Solution1(self, n, m):
'''
:param n:
:param m:
:return:
'''
if n < 1 or m < 1:
return -1
nums = list(range(n))
# cur代表当前指针指向环中的某个数
cur = 0
while len(nums) > 1:
for i in range(1,m):
cur += 1
if cur == len(nums):
cur = 0
nums.remove(nums[cur])
if cur == len(nums):
cur = 0
return nums
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isValidBST(root): # 不能简单地认为递归每个节点,左节点小于当前节点,右节点大于当前节点就可以了,还要注意边界问题,
# 即左子树上的节点值(包括左子树上的右子节点)都少于根节点(即上限动态调整) ,
# 右子树上的节点值(包右子树上的左子节点)都大于根节点(即下限动态调整)
def dfs(root, lower, upper):
if not root:
return True
if root.val > lower and root.val < upper:
# 每次递归需要改变边界的上下限 要保证所有递归子树都满足二叉搜索树的条件才成立
return dfs(root.left, lower, root.val) and dfs(root.right, root.val, upper)
else:
return False
return dfs(root, float('-inf'), float('inf'))
if __name__ == '__main__':
l = [9,7,11,5,8,10,12]
tree = operate_tree.Tree()
print(isValidBST(tree.creatTree(l)))<file_sep>
def countPrimes(n):
'''
统计所有小于非负整数 n 的质数的数量
方法
:param n:
:return:
'''
if n < 3:
return 0
res = [1] * n
res[0],res[1]=0,0
# i*i--n--步进位i 【int(n**0.5)】*【int(n**0.5)】
for i in range(2,int(n**0.5)+1):
# 将是output[i]倍数的数都化为0
if res[i] == 1:
res[i**2:n:i] = [0] * len(res[i**2:n:i])
return sum(res)
if __name__ == '__main__':
n = 10
print(countPrimes(n))
<file_sep>
def canCompleteCircuit(gas, cost):
'''
贪心:每次起始出发点选在 其上一加油站gas[i] - cost[i]为负,本加油站gas[i] - cost[i]为正的加油站
:param nums:
:return:
'''
n = len(gas)
# total_tank无论从哪个加油站出发,总的油箱剩油量
total_tank=0
# curr_tank是从st加油站出发,到当前加油站,油箱的剩油量
curr_tank = 0
st = 0
for i in range(n):
total_tank += gas[i] - cost[i]
curr_tank += gas[i] - cost[i]
# 如果从上一次记录的st加油站出发不能通过(i-->i+1),则新的st加油站应该为i+1,同时初始化curr_tank
if curr_tank < 0:
st = i + 1
curr_tank = 0
return st if total_tank >= 0 else -1
if __name__ == '__main__':
gas = [1, 2, 3, 4, 5]
cost = [3, 4, 5, 1, 2]
print(canCompleteCircuit(gas,cost))
#问题1: 为什么应该将起始站点设为k+1?
#因为k->k+1站耗油太大,0->k站剩余油量都是不为负的,每减少一站,就少了一些剩余油量。所以如果从k前面的站点作为起始站,剩余油量不可能冲过k+1站。
#问题2: 为什么如果k+1->end全部可以正常通行,且rest>=0就可以说明车子从k+1站点出发可以开完全程?
#因为,起始点将当前路径分为A、B两部分。其中,必然有(1)A部分剩余油量<0。(2)B部分剩余油量>0。
#所以,无论多少个站,都可以抽象为两个站点(A、B)。(1)从B站加满油出发,(2)开往A站,车加油,(3)再开回B站的过程。
#重点:B剩余的油>=A缺少的总油。必然可以推出,B剩余的油>=A站点的每个子站点缺少的油。<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
############################################################################################## 112
def hasPathSum(root, sum): #路径之和1 问题:是否存在根节点到叶子节点路径总和等于给定目标和的路径
if not root:
return False
while not root.left and not root.right:
return sum == root.val
sum = sum - root.val
return hasPathSum(root.left, sum) or hasPathSum(root.right, sum)
################################################################################################## 113
def hasPathSum1(root, sum): #路径之和2 问题:从根节点到叶子节点路径总和等于给定目标和的 具体的路径
def dfs(root, sum, res, tmp):
if not root:
return []
tmp.append(root.val)
if not root.left and not root.right and root.val == sum:
# 这个地方一定要使用tmp的拷贝, 因为后面tmp.pop()会弹出元素,导致错误
res.append(tmp.copy())
sum = sum - root.val
dfs(root.left, sum, res, tmp)
dfs(root.right, sum, res, tmp)
tmp.pop()
res = []
tmp = []
dfs(root, sum, res, tmp)
res.sort(key = len)
return res
######################################################################################### 437
def hasPathSum2(root, sum) : # 路径之和3 问题:从任意位置到出发经过(路径方向必须是向下)若干连续的二叉树结构满足 路径之和为目标数
def mypathsum(root, sum, tar):
if not root:
return 0
res = 0
for t in tar:
if root.val == t:
res += 1
tar = [x - root.val for x in tar] + [sum]
return res + mypathsum(root.left, sum, tar) + mypathsum(root.right, sum, tar)
return mypathsum(root, sum, [sum])
if __name__ == '__main__':
l = [5,4,8,11,None,13,4,7,2,None,None,5,1]
sum = 22
tree = operate_tree.Tree()
print(hasPathSum1(tree.creatTree(l),sum)) #输出该节点的值<file_sep>######################这种类型的题都有三种解法可以解决
######1.sum
######2.异或等逻辑运算
######3.哈希表存储
def missingNumber(nums):
ml = len(nums)
return int(ml * (ml + 1) / 2 - sum(nums))
def missingNumber2(nums): #采用异或操作, 可防止sum的数很大越界
summ = len(nums)
for i in range(len(nums)):
summ ^= nums[i] #summ的总数 = nums的总数 + 1
summ ^= i
return summ
###############136###############
def singleNumber( nums): #一个二进制位只能表示0或者1。也就是天生可以记录一个数出现了一次还是两次
summ = 0
for i in nums:
summ ^= i
return summ
def singleNumber12( nums):
return 2*sum(set(nums)) - sum(nums)
###############137#################
def singleNumber21(nums): #记录出现3次,需要两个二进制位。那么上面单独的x就不行了。我们需要两个变量,每个变量取一位:
dic = {}
for i in nums:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
return list (dic.keys()) [list (dic.values()).index (1)]
def singleNumber22(nums): #记录出现3次,需要两个二进制位。那么上面单独的x就不行了。我们需要两个变量,每个变量取一位:
a,b = 0,0
for i in nums:
b = (b ^ i) & ~a
a = (a ^ i) & ~b
return b
def singleNumber23(nums):
return (3*sum(set(nums)) - sum(nums))//2
#######################260###################只出现一次的数字III
def FindNumsAppearOnce(array):
'''
思路:
1 在基础题目中,数组中所有数字异或得到单独数字;那么在这个题目中,数组中所有数字异或得到这两个单独数字的异或,比如是x;
2 我们只需要把数组中所有数字分成两组,并且每一组中的仅包含一个单独数字,那么就把这个问题转化为基础问题了,比如:数组:[a,b,c,d,a,b]
转换为[a,a,c],[b,b,d],或者是[a,a,d],[b,b,c],这没区别,就把这个问题转换成了基础问题了,问题在于如何转换
3 x是两个不相同数字的异或,那么x必然不是0,我们只要找到x为1的某一位,比如第n位,或者m位,只要是x在这一位上为1。那么在这一位上,
c,d是不同的,异或运算才得到1,否则就是0了。,这就是区分c,d的关键
4 遍历数组,当第n位为1的时,归位一组,第n位不为1,归为另一组。这样就得到了两个组,将问题成功转换为夹出问题
'''
# 得到的accumulate是两个单独数字的异或
accumulate = 0
nums = array
for n in nums:
accumulate ^= n
# 左移mask,移动到xor为1的那一位,也是单独数字存在差异的一位 mask都是10000...的形式
mask = 1
while (mask & accumulate) == 0:
mask <<= 1
#num1,num2代表数组将数组划分为两部分的 累积异或
acc1, acc2 = 0, 0
for n in nums:
# 按照差异,对数组分组,两个单独数字被分到不同的组 这样划分后,每个不同分组的元素是不平等
if n & mask == 0:
acc1 ^= n
else:
acc2 ^= n
return [acc1, acc2]
if __name__ == '__main__':
nums = [9,6,4,2,3,5,7,0,1]
# print(missingNumber2(nums))
nums2 = [4,1,2,1,2]
# print(singleNumber(nums2))
nums3 = [0,1,0,1,0,1,99]
aaa = [1,2,1,2,3,4]
print(FindNumsAppearOnce(aaa))<file_sep>
def gardenNoAdj(N, paths):
res = [0] * N
graph = [[] for _ in range(N)]
for x, y in paths:
graph[x - 1].append(y - 1)
graph[y - 1].append(x - 1)
for i in range(N):
# seen将节点i的邻接节点的颜色存下
seen = set(res[x] for x in graph[i])
# 将邻接节点的花的种类剔除,随意选择剩下的一种花类型
res[i] = ({1, 2, 3, 4} - seen).pop()
return res
if __name__ == '__main__':
N = 3
paths = [[1, 2], [2, 3], [3, 1]]
print(gardenNoAdj(N,paths))<file_sep># n = 5
#
# grid = []
# for i in range(5):
# grid.append([int(c) for c in input().split()])
#
#
# def dfs(grid, i, j):
# # 遍历过的节点清零
# grid[i][j] = '0'
# # 遍历当前结点的四个方向
# if i > 0 and grid[i - 1][j] == "1":
# dfs(grid, i - 1, j)
# if j > 0 and grid[i][j - 1] == "1":
# dfs(grid, i, j - 1)
# if i < len(grid) - 1 and grid[i + 1][j] == "1":
# dfs(grid, i + 1, j)
# if j < len(grid[0]) - 1 and grid[i][j + 1] == "1":
# dfs(grid, i, j + 1)
class sol:
def __init__(self):
self.visited = 0
self.res = float('inf')
# 计算数字相等的连通域的最大面积
def search(self,arr,i,j,value,arrlist):
if i < 0 or i >= len(arr) or j < 0 or j >= len(arr[0]) or arr[i][j] != value:
return 0
arrlist.append((i,j,arr[i][j]))
arr[i][j] = self.visited
res = 1
res += self.search(arr, i + 1, j, value, arrlist)
res += self.search(arr, i - 1, j, value, arrlist)
res += self.search(arr, i, j - 1, value, arrlist)
res += self.search(arr, i, j + 1, value, arrlist)
return res
# 消去连通区的数字后进行重力下沉
def down(self,arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 0:
continue
else:
if i+1 < 5 and arr[i+1][j] == 0:
arr[i][j], arr[i+1][j] = arr[i+1][j], arr[i][j]
# 消消乐时,尝试所有顺序的消去方法,找到剩余最少的方块
def play(self,arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 0:
continue
import copy
arrback = copy.deepcopy(arr)
# 存储已消去的快
arrlist = []
tmp = self.search(arr,i,j,arr[i][j],arrlist)
if tmp > 3:
self.down(arr)
self.play(arr)
arr = arrback
tmpres = 0
for i in range(5):
for j in range(5):
if arr[i][j] != 0:
tmpres += 1
if tmpres < self.res:
self.res = tmpres
def main(self):
n = 5
grid = []
for i in range(5):
grid.append([int(c) for c in input().split()])
self.play(grid)
return self.res
a = sol()
print(a.main())
<file_sep>n = int(input())
nums = [int(c) for c in input().split()]
# max_bd为可能出现数字最大的骰子
max_bd = max(nums)
min_bd=1
res=0
exp_his=[]
# i为最大骰子数的所有可取数
for i in range(1,max_bd+1):
# cur_expect记录最大数取值为i的概率
cur_expect=1
for num in nums:
# exp_i 代表每个骰子的取值不超过i的概率
exp_i=min(i/num, 1)
# 此时cur_expect记录的是取值不超过i的概率
cur_expect=cur_expect*exp_i
# 去除最大数的取值为1,...,i-1的概率
if exp_his:
for t in exp_his:
cur_expect=cur_expect-t
# exp_his列表里再存下最大数取值为i的概率
exp_his.append(cur_expect)
res+=cur_expect*i
print('%.2f'%res)<file_sep># n = int(input())
# ask = int(input())
#
# from collections import defaultdict
#
# look = defaultdict(list)
#
# for _ in range(ask):
# a,b = map(int,input().split())
# look[a].append(b)
# queue = []
#
# def dfs(look,k,x):
# if x not in look and x not in look[k]:
# return True
# if x in look[k]:
# return False
# for i in look[x]:
# a = dfs(look,k,i)
# if a == False:
# return a
#
# for k in look:
# zhi = dfs(look,k,k)
# if zhi == False:
# print(0)
# exit()
#
#
# for k in look:
# queue.append(look[k])
# for j in look[k]:
# for i in queue:
# if k in i and j in i:
# print(0)
# exit()
#
# print(1)
num_kids = int(input())
num_requests = int(input())
matrix_requests = [[0 for _ in range(num_kids)] for _ in range(num_kids)]
for i in range(num_requests):
a,b = map(int,input().split(' '))
matrix_requests[a - 1][b - 1] = 1
matrix_requests[b - 1][a - 1] = 1
# 记录最大冲突的小孩数
max_sum = 0
# 记录没有任何冲突的小孩数量
count_zero = 0
for i in range(num_kids):
_sum = sum(matrix_requests[i][0: i + 1])
if _sum == 0:
count_zero = count_zero + 1
if _sum > max_sum:
max_sum = _sum
if count_zero >= max_sum:
print(1)
else:
print(0)
<file_sep># mod = 10**9 + 7
#
# # 矩阵快速乘法和幂运算
# def matmul(A,B):
# C = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
# for i in range(len(A)):
# for k in range(len(B)):
# for j in range(len(B[0])):
# C[i][j] = (C[i][j] + A[i][k]*B[k][j]%mod)%mod
# return C
#
# def matpow(A,n):
# B = [[0 for _ in range(len(A))] for _ in range(len(A))]
# for i in range(len(A)):
# B[i][i] += 1
# while n:
# if n & 1:
# B = matmul(B,A)
# A = matmul(A,A)
# n >>= 1
# return B
#
# # n,a,b,c,f0 = 10**18, 5, 5, 5, 100
# a1,a2,a3,a4,n = map(int,input().split())
#
# A = [[1,0,1,1],[1,0,0,0],[0,1,0,0],[0,0,1,0]]
# A = matpow(A,n-4)
#
# res = (a4*A[0][0]+a3*A[0][1]+a2*A[0][2]+a1*A[0][3]) % mod
# print(res)
#
# mod = 10**9 + 7
#
# a1,a2,a3,a4,n = map(int,input().split())
#
# for i in range(5,n+1):
# tmp = a1+a2+a4
# a1,a2,a3,a4 = a2,a3,a4,tmp
# print(a4)
def hasPath(matrix, rows, cols, path):
n = len(path)
def dfs(matrix,i,j,k):
if i < 0 or j < 0 or j >= cols or i > rows:
return
if k == n:
return True
if matrix[i][j] == path[k]:
matrix[i][j] = '1'
return dfs(matrix, i + 1, j, k + 1) or dfs(matrix, i - 1, j, k + 1) or dfs(matrix, i, j + 1, k + 1) or \
dfs(matrix, i, j - 1, k + 1)
dfs(matrix, i + 1, j, k + 1)
dfs(matrix, i - 1, j, k + 1)
dfs(matrix, i, j + 1, k + 1)
dfs(matrix, i, j - 1, k + 1)
return False
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == path[0] and dfs(matrix,i,j,1):
return True
return False
matrix = [['a','b','c','d'],['c','f','c','s'],['j','d','e','h']]
rows = 3
cols = 4
path = 'abfc'
print(hasPath(matrix, rows, cols, path))
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i*cols+j] == path[0]:
if self.find(list(matrix),rows,cols,path[1:],i,j):
return True
return False
def find(self,matrix,rows,cols,path,i,j):
if not path:
return True
matrix[i*cols+j]='0'
if j+1<cols and matrix[i*cols+j+1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j+1)
elif j-1>=0 and matrix[i*cols+j-1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j-1)
elif i+1<rows and matrix[(i+1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i+1,j)
elif i-1>=0 and matrix[(i-1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i-1,j)
else:
return False
<file_sep>from collections import defaultdict, deque
N = int(input())
graph = defaultdict(list)
for _ in range(N-1):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
queue = deque()
# 队列存储当前遍历到的节点,及走过的路径长度
queue.append((1, 0))
visit = set([1])
max_depth = 0
while queue:
node, depth = queue.popleft()
# 从该节点出发找到一条路径可以使得只经过结点一次,并且使得该路径最长
max_depth = max(depth, max_depth)
for child in graph[node]:
if child not in visit:
visit.add(child)
queue.append((child, depth+1))
print(2*(N-1)-max_depth)
<file_sep>def wordBreak(s, wordDict):
####该方法存在问题,若存在复杂子问题时,要想到DP
for i, w in enumerate(wordDict):
while s.find(w) != -1:
s = s[:s.find(w)] + s[s.find(w) + len(w):]
return True if len(s) == 0 else False
def wordBreak1(s, wordDict):
dp = [True]
for i in range(1, len(s) + 1):
# dp[j] s[j:i] + for循环迭代器 判断是否在单词表里
# 用动态,前面已经判断能用单词表组成的字符串在下一次就不需要在判断了(这里any()函数相当于or,具有短路功能,all()相当于and)
dp.append(any(dp[j] and s[j:i] in wordDict for j in range(i)))
return dp[-1]
def wordBreak2(s, words):
dp = [True]
# 优化 使用最长单词的长度做限定 加['']防止给的wordict 为空
max_len = max(map(len,words+['']))
words = set(words)
for i in range(1, len(s)+1):
dp += any(dp[j] and s[j:i] in words for j in range(max(0, i-max_len),i)),
return dp[-1]
def wordBreak3(s, wordDict): ####清晰版
'''
题意:给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
拆分时可以重复使用字典中的单词
你可以假设字典中没有重复的单词
:param s:
:param wordDict:
:return:
'''
# 集合去重
wordDict = set(wordDict)
# 1、确定状态,dp[i]表示字符串s[0:i]是否能由worddict中的单词拆分
# 3、初始化及边界条件
dp = [True] + [False] * (len(s))
max_len = 0
# 求出worddict中最长单词的长度
for word in wordDict:
max_len = max(max_len, len(word))
# 4、计算顺序 自左往右
for i in range(1, len(s) + 1):
# 这里对DP数组递推过程的第二维遍历过程进行优化,
# 每次遍历只是从worddict中找到一个单词使得其到达dp[i]
# 这样第二维的遍历长度降为定值max_len,
for k in range(max(i - max_len, 0), i):
# 2、递推公式 bool型(存在型)递推公式
if dp[k] and s[k:i] in wordDict:
dp[i] = True
return dp[len(s)]
############################引申题5.13##################################
list = ['test','tester','testertest','testing','apple','seattle','banana','batting','ngcat','batti','bat',
'testingtester','testbattingcat']
def findlongestword(nums):
'''
题意:找出list表中的字符串能由数组中其它字符串组成的最长字符串
方法:采用贪心算法,对list列表按长度进行排序,遍历列表直到找到一个字符串满足题意,输出的就是最长的字符串
'''
nums.sort(key=len,reverse=True)
for i in nums:
num_ex = nums.copy()
del num_ex[nums.index(i)]
if wordBreak3(i,num_ex):
return i
if __name__ == '__main__':
s = "leetcode"
wordDict = ["leet","code"]
# print(findlongestword(list))
print(wordBreak3(s,wordDict))<file_sep>def isSubsequence(s, t):
count = 0
if not s:
return True
for i in t:
if s[count] == i:
count += 1
if count == len(s):
return True
return False
def isSubsequence1(s, t):
if not s:
return True
for ss in s: ##遍历短串字符速度稍快
res = t.find(ss)
if res == -1: #find()方法仅能用于字符串
return False
else:
t = t[res+1:]
return True
if __name__ == '__main__':
s = "leeeeetcode"
t = "yyyyylyyyyyyyyyyeyyyyyyyyyyyyyyeyyyyyyyyyyyyeyyyyyyyyyeyyyyyyyyyeyyyyyyyyyytyyyyyyyyyycyyyyyyyyyyyoyyyyyyyyyyyyydyyyyyyyyyyyeyyyyyyyyyyyy"
print(isSubsequence1(s,t))<file_sep># leetcode 892<file_sep>'''
构造一个迷宫是很麻烦的一件事情,因此有人提出了一种迷宫生成方法,与铺砖的方法类似,
首先设计一个n*m的单位迷宫,然后就像铺砖一样,将这个单位迷宫复制拼接起来,如果能够通
过这种方式生成的迷宫可以
从起始位置通向无穷多的位置,那么我们认为这个单位迷宫是合法的
(每个单位不可旋转)。单位迷宫的表示包含三种符号,‘#’,‘.’和‘S’,其中‘#’代表墙,‘.’代表没
有障碍物可以通过的,S则代表的是起始位置,当然迷宫是只有一个起点的,你可以任选一个单位迷宫的
S位置作为起点,其他单位迷宫的S则视为可通行的。
'''
# 思路:将每个base版块复制9份组成一个大的grid,从中间的版块往外面递归遍历,若能找到一条路径到达grid的边界,则合适
T = int(input())
def can_get_border(si, sj, grid):
def dfs(si, sj, grid):
if si < 0 or si >= len(grid) or sj < 0 or sj >= len(grid[0]) :
return
if grid[si][sj] != '0' and grid[si][sj] != '#':
grid[si][sj] = '0'
dfs(si+1, sj, grid)
dfs(si-1, sj, grid)
dfs(si, sj+1, grid)
dfs(si, sj-1, grid)
dfs(si, sj, grid)
for i in range(len(grid)):
if grid[i][0] == '0' or grid[i][len(grid[0]) - 1] == '0':
return True
for j in range(len(grid[0])):
if grid[0][j] == '0' or grid[len(grid) - 1][j] == '0':
return True
for _ in range(T):
n,m = map(int,input().split())
#复制9分
grid = []
for i in range(n):
a = list(input())
grid.append(a+a+a)
ss = grid
for i in range(n):
grid.append(grid[i].copy())
for i in range(n):
grid.append(grid[i].copy())
for i in range(n):
for j in range(m):
if ss[i][j] == 'S':
si = i
sj = j
if can_get_border(si+n,sj+m,grid):
print('Yes')
else:
print('NO')
# 2
# 2 2
# S#
# #.
# 3 3
# ...
# ###
# #S#<file_sep>def comb(n):
count = 0
for m in range(0,n+1,5):
count += (m+2)//2
return count
if __name__ == '__main__':
n = 100
print(comb(n))
<file_sep>class Employee:
def __init__(self, id, importance, subordinates):
self.id = id
self.importance = importance
self.subordinates = subordinates
def getImportance(employees, id):
'''
方法:DFS 前序遍历
每个员工看成是一个节点
其下属看成一个N叉树
'''
emap = {e.id: e for e in employees}
###递归本层级子员工
def dfs(eid):
employee = emap[eid]
return (employee.importance + sum(dfs(eid) for eid in employee.subordinates))
return dfs(id)
def getImportance1(employees, id):
'''
方法:BFS 层序遍历
'''
emap = {e.id: e for e in employees}
res = 0
queue = [id]
while queue:
###本层级员工重要性计算
res += sum(emap[iid].importance for iid in queue)
###下一层级员工id统计
queue = [sub for iid in queue for sub in emap[iid].subordinates]
return res
if __name__ == '__main__':
nums = [[1,2,[2]], [2,3,[]]]
employees = [Employee(x[0],x[1],x[2]) for x in nums]
print(getImportance1(employees, 2))
<file_sep>#
#如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false。
#现在考虑一个环形链表,把慢指针和快指针想象成两个在环形赛道上跑步的运动员(分别称之为慢跑者与快跑者)。而快跑者最终一定会追上慢跑者。这是为什么呢?
#考虑下面这种情况(记作情况 A)- 假如快跑者只落后慢跑者一步,在下一次迭代中,它们就会分别跑了一步或两步并相遇。
#其他情况又会怎样呢?例如,我们没有考虑快跑者在慢跑者之后两步或三步的情况。但其实不难想到,因为在下一次或者下下次迭代后,又会变成上面提到的情况 A。
#
from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def hasCycle(head): #快慢指针法 (有环则两指针必定相遇)
if not head or not head.next:
return None
slow ,fast = head ,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
while slow == fast:
return True
return False
def hasCycle1(head):
'''
方法:哈希表 存放链表节点的地址
思路:将访问过的节点都赋上同一元素值,空间复杂度缩小)
:param head:
:return:
'''
has = set()
while head:
# id()存储head结点的内存地址
if id(head) in has:
return True
has.add(id(head))
head = head.next
return False
if __name__ == '__main__':
l1 = [4,1,8,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l1)
res = hasCycle(cur.next)
print(res)<file_sep>def cal_process_time(t,m,n):
'''
:param t:每个服务器处理的时间
:param m:服务器的数量
:param n:任务个数
:return:每个服务器的处理任务所花的总时间
'''
pro_time = [0]*m
for i in range(n): #遍历每个任务
#选择第一个服务器处理
mintime = pro_time[0] + t[0]
minind = 0
#在后续服务器中找到一个使得所需时间最短的
for j in range(1,m):
if mintime > pro_time[j] + t[j]:
mintime = pro_time[j] + t[j]
minind =j
pro_time[minind] += t[minind]
return pro_time
if __name__ == '__main__':
t = [7,10]
m = 2
n = 10
print(cal_process_time(t,m,n))<file_sep>def IsContinuous(numbers):
if not numbers:
return []
n = len(numbers)
nums = numbers
nums.sort()
countgap = 0
countzero = 1 if nums[0] == 0 else 0
for i in range(1,n):
if nums[i] != 0 and nums[i] == nums[i - 1]:
return False
elif nums[i-1] != 0:
countgap += nums[i] - nums[i-1] - 1
elif nums[i] == 0:
countzero += 1
return False if countgap > countzero else True
nums = [0,3,5,4,6]
print(IsContinuous(nums))<file_sep>
def canPlaceFlowers(flowerbed, n): ####列表两个表头00的情况 表尾00的情况 ####
nums = flowerbed
res = 0
nums.insert(0, 0) ##在其前和后添加10 01
nums.insert(0, 1)
nums.append(0)
nums.append(1)
count = 0
for i in nums:
if i == 1:
res += abs(count - 1)//2
count = 0
else:
count += 1
res += abs(count - 1) // 2
return res >= n
if __name__ == '__main__':
flowerbed = [0,1,1,0,1,0,1,0,0]
n = 1
print(canPlaceFlowers(flowerbed,n))<file_sep>n,k = map(int,input().split())
nums = [int(c) for c in input().split()]
if len(set(nums)):
print(1)
else:
queue = nums[:k]
tmp = res = sum(queue)
minidx = 0
for i in range(k,n):
tmp = tmp - nums[i - k] + nums[i]
if tmp < res:
res = tmp
minidx = i - k + 2
print(minidx)
<file_sep>def insertsort(list):
for i in range(1,len(list)):
key = list[i] #当前要插入的数
j = i - 1 #j为前一个插入的数的索引
while j >= 0: #遍历前面所有已排序好的数 ,找到可插入的位置
if key < list[j]:
list[j + 1] = list[j]
list[j] = key
j -= 1
return list
if __name__ == '__main__':
l = [1, 3, 4, 5, 6, 2, 7, 90, 21, 23, 45]
print(insertsort(l))<file_sep>
s = 'aabccb'
ans = 0
mp = dict()
cur = 0
s = list(map(ord,s))
'''
思路:字典mp每个对应的key存储遍历到目前该字符为止,该字符串中偶数串的个数
'''
for num in s:
# get()方法,第二个参数,若不能找到对应的key,则返回0
mp[cur] = mp.get(cur, 0)+1
a = 1 << num
cur ^= 1<<num
ans += mp.get(cur, 0)
print (ans)
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def constructMaximumBinaryTree(nums): #常规递归思路
if len(nums) == 0:
return None
maxi = max(nums)
root = TreeNode(maxi)
l = nums[:nums.index(maxi)]
r = nums[nums.index(maxi) + 1:]
root.left = constructMaximumBinaryTree(l)
root.right = constructMaximumBinaryTree(r)
return root
def constructMaximumBinaryTree1(nums): #用栈实现,速度更快
stack = [] #用列表存根节点
for n in nums:
node = TreeNode(n)
while stack and stack[-1].val < n:
node.left = stack.pop()
if stack:
stack[-1].right = node
stack.append(node)
return stack[0]
if __name__ == '__main__':
l = [3,2,1,6,0,5]
tree = operate_tree.Tree()
print(tree.levelOrder(constructMaximumBinaryTree1(l)))<file_sep>N = 1
S = ['1','1','0','0']
T = ['1','1','0','0','1','1']
for t in range(N):
new = []
for i in S:
if i == '1':
new.append('0')
else:
new.append('1')
new = ''.join(new).lstrip('0')
S = ''.join(S)
T = ''.join(T)
if S + new == T:
print('YES')
else:
print('NO')
<file_sep>
n = int(input())
m = int(input())
for _ in range(n):
graph = []
for mm in range(m):
a = [int(c) for c in input().split()]
featnum = a[0]
ff = []
for i in range(featnum):
ff.append((a[2*i+1],a[2*i+2]))
graph.append(ff)
cnts = {}
for frame in range(m):
for feat in graph[frame]:
tmp = frame
count = 1
while tmp+1 <= m-1 and feat in graph[tmp+1]:
count += 1
tmp += 1
if feat not in cnts:
cnts[feat] = count
elif count > cnts[feat]:
cnts[feat] = count
res = float('-inf')
for i in cnts:
if cnts[i] > res:
res = cnts[i]
print(res)
<file_sep>n,m = map(int,input().split())
from collections import defaultdict
guys = []
guysdic = defaultdict(int)
for i in range(m):
key = tuple(map(int, input().split()))
guys.append(key)
guysdic[key] = i
guys.sort(key = lambda x:x[0])
res = 0
ans = [0] * m
for i in range(m):
if i == 0:
res += guys[i][1] - guys[i][0] + 1
ans[guysdic[guys[i]]] = res
else:
if guys[i][1] <= guys[i-1][1]:
ans[guysdic[guys[i]]] = res
continue
else:
if guys[i][0] > guys[i-1][1]:
res += guys[i][1] - guys[i][0] + 1
ans[guysdic[guys[i]]] = res
else:
chongdie = guys[i-1][1] - guys[i][0] + 1
res += guys[i][1] - guys[i][0] + 1
res -= chongdie
ans[guysdic[guys[i]]] = res
for r in ans:
print(r)
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def mergeTwoLists(l1, l2):
# 初始化一个空链表
dummy = cur = LNode(None)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next
if __name__ == '__main__':
l1 = [1,2,4]
l2 = [1,3,4]
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
cur2 = llist.initList(l2)
res = mergeTwoLists(cur1.next, cur2.next)
llist.outll(res)<file_sep>class treeNode():
def __init__(self,data=-1,left=None,right=None):
self.val=data
self.left=left
self.right=right
def __str__(self):
return str(self.val)
#####################################112####################################
def PathSum1(root, sum):
if not root:
return []
sum = sum - root.val
if not root.left and not root.right and sum == 0: #遍历到叶子节点
return True
return PathSum1(root.left, sum) or PathSum1(root.right, sum)
###########################################113#######################################
def pathSum2(root, sum):
if not root:
return []
def dfs(root, sum, res, temp):
if not root:
return []
temp.append(root.val)
sum = sum - root.val
if not root.left and not root.right and sum == 0 :
res.append(temp.copy())
dfs(root.left, sum, res, temp)
dfs(root.right, sum, res, temp)
temp.pop()
res = [] #列表存在此,防止每次递归将列表清空
temp = []
dfs(root, sum, res, temp)
return res
###################################################437##################################################
class sol1: #双重递归的方法
result = 0
def mypathsum(self, root, sum): #第二层递归
if not root:
return 0
sum -= root.val
if sum == 0:
self.result += 1
self.mypathsum(root.left, sum)
self.mypathsum(root.right, sum)
def pathSum3(self, root, sum): #第一层递归
if not root:
return 0
self.mypathsum(root, sum)
self.pathSum3(root.left, sum)
self.pathSum3(root.right, sum)
return self.result
class sol2:
def pathSum3(self, root, sum): #一维数组 + 一层递归
return self.mypathsum(root, sum, [sum])
def mypathsum(self, node, origin, targets):
if not node:
return 0
result = 0
for t in targets:
if t == node.val: #targets中存在0的元素即表示找到了该数
result += 1
targets = [t-node.val for t in targets]+[origin] #记录下经过一个节点后的 ,加origin = sum是要看后面有没有直接 等于sum的数字
return result + self.mypathsum(node.left, origin, targets)+self.mypathsum(node.right, origin, targets)
if __name__ == '__main__':
# root = treeNode(5,treeNode(4,treeNode(11,treeNode(7),treeNode(2))),treeNode(8,treeNode(13),treeNode(4,treeNode(5),treeNode(1))))
# sum = 22
# print(PathSum1(root,sum))
# print(pathSum2(root,sum))
root1 = treeNode(10, treeNode(5, treeNode(3, treeNode(3), treeNode(-2)),treeNode(2, None, treeNode(1))),
treeNode(-3, None, treeNode(11)))
sum1 = 8
S = sol2()
print(S.pathSum3(root1,sum1))<file_sep>
def advantageCount1(A, B): #思路将A,B升序排序,并建立由sorteB 到 B的索引映射, 对sortA 大于 sortB的,结果记录在sortb的当前位置记录,否则将其放到sortB的最后位置
n = len(A)
sortA = sorted(A)
res = [0] * n
idx = sorted(range(n), key=lambda x: B[x])
sorteB = [B[x] for x in idx]
bf, af = 0, n - 1
for a in sortA:
if a > sorteB[bf]:
res[idx[bf]] = a #idx[bf] 是现在B中索引bf 对应在 B排序前中索引的位置
bf += 1
else:
res[idx[af]] = a
af -= 1
return res
if __name__ == '__main__':
A = [2,0,4,1,2]
B = [1,3,0,0,2]
print(advantageCount1(A,B))<file_sep>def hammingDistance( x, y):
z = x ^ y
count = 0
while z:
if z&1 == 1:
count += 1
z >>= 1
return count
if __name__ == '__main__':
print(hammingDistance( 1, 4))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def findMode(root):
if not root:
return []
else:
res = [] #中序遍历递归整颗树的节点 并存在列表,用数组的思想来解决
middle_digui(root, res)
from collections import Counter
dic = Counter(res)
max = 0
for k in dic:
if dic[k] > max:
max = dic[k] #找到众数的个数
temp = []
for k in dic:
if dic[k] == max:
temp.append(k) #找到所有众数的值
return temp
def middle_digui(root, res):
if not root:
return
middle_digui(root.left, res)
res.append(root.val)
middle_digui(root.right, res)
if __name__ == '__main__':
l = [1,None,2,2]
tree = operate_tree.Tree()
print(findMode(tree.creatTree(l)))<file_sep>
def containsDuplicate(nums):
num = set(nums)
if len(num) != len(nums):
return True
return False
######################219################
def containsDuplicate2(nums,k):
num_dic = {}
for i in range(len(nums)):
if (nums[i] in num_dic) and (abs(i - num_dic[nums[i]]) <= k):
return True
num_dic[nums[i]] = i
return False
if __name__ == '__main__':
nums = [1,3,4,3,2,4,2]
nums2 = [1,0,1,1]
# print(containsDuplicate(nums))
print(containsDuplicate2(nums2,0))<file_sep>
def maxSubArray(nums): ######DP方法##### nums中存的是在当前下标及其之前的最优子序列的值
for i in range(1, len(nums)): #基本思想就是保证dp[i]前面计算的最优子序列的和要大于等于0 否则舍去前面的子序列
nums[i] = nums[i] + max(nums[i - 1], 0)
return max(nums)
def maxSubArray2(nums): ###耗时少###
ans = nums[0]
current_sum = 0
for i in range(len(nums)):
if current_sum > 0:
current_sum += nums[i]
else:
current_sum = nums[i]
ans = max(ans,current_sum)
return ans
###################################分治法解决问题#########################
def maxSubArrayHelper( nums, l, r): ########待看
if l > r:
return -2147483647
m = (l + r) // 2
leftMax = sumNum = 0
for i in range(m - 1, l - 1, -1):
sumNum += nums[i]
leftMax = max(leftMax, sumNum)
rightMax = sumNum = 0
for i in range(m + 1, r + 1):
sumNum += nums[i]
rightMax = max(rightMax, sumNum)
leftAns = maxSubArrayHelper(nums, l, m - 1)
rightAns = maxSubArrayHelper(nums, m + 1, r)
return max(leftMax + nums[m] + rightMax, max(leftAns, rightAns))
def maxSubArray3(nums):
return maxSubArrayHelper(nums, 0, len(nums) - 1)
if __name__ == '__main__':
nums = [-2,1,-3,4,-1,2,1,-5,4]
print(maxSubArray3(nums))<file_sep>from Linked_list import linkedlist_operate
from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def sortedListToBST(head):
if not head:
return None
if not head.next:
return TreeNode(head.val)
# 这里取得中点要靠前,所以让fast先走一步
slow, fast = head, head.next.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
mid = slow.next
slow.next = None
root = TreeNode(mid.val)
root.left = sortedListToBST(head)
root.right = sortedListToBST(mid.next)
return root
if __name__ == '__main__':
l = [1,2,3,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
res = sortedListToBST(cur.next)
tree = operate_tree.Tree()
print(tree.levelOrder(res))
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def mergeTrees(t1, t2):
if not t1 and not t2:
return
if not t1 and t2:
return t2
if not t2 and t1:
return t1
t1.val += t2.val #递归循环里只考虑本层循环需要做的
t1.left = mergeTrees(t1.left, t2.left)
t1.right = mergeTrees(t1.right, t2.right)
return t1
if __name__ == '__main__':
l = [1,3,2,5,None,None,None]
r = [2,1,3,None,4,7,None]
tree = operate_tree.Tree()
print(tree.levelOrder(mergeTrees(tree.creatTree(l),tree.creatTree(r))))<file_sep>def copyBooks( pages, k):
'''
动态规划
:param pages:
:param k:
:return:
'''
n = len(pages)
if n == 0:
return 0
if k > n:
k = n
# 第k个抄写员抄写前i-1本书最少需要花多久时间
dp = [[float('inf')] * (n + 1) for _ in range(k + 1)]
dp[0][0] = 0
for ki in range(1, k + 1):
dp[ki][0] = 0
for i in range(1, n + 1):
dp[ki][i] = float('inf')
for j in range(i, -1, -1):
dp[ki][i] = min(dp[ki][i], max(dp[ki - 1][j], sum(pages[x] for x in range(j,i))))
return dp[k][n]
def copyBooks1( pages, k):
'''
贪心+二分
:param pages:
:param k:
:return:
'''
def islesstle(pages,k,tmax):
pagesum = 0
peonum = 1
for i in pages:
if pagesum + i <= tmax:
pagesum += i
else:
peonum += 1
pagesum = i
return peonum <= k
l = max(pages)
r = sum(pages)
while l < r:
mid = l + (r - l) // 2
if islesstle(pages,k,mid):
r = mid
else:
l = mid + 1
return l
if __name__ == '__main__':
pages = [3, 2, 4]
k = 2
print(copyBooks1( pages, k))<file_sep># 双hash表 + 贪心法<file_sep>import bisect
def searchMatrix(matrix, target):
for arr in matrix:
ind = bisect.bisect_left(arr, target)
if not ind < len(arr):
continue
if arr[ind] == target:
return True
return False
def searchMatrix2(matrix, target):
'''
先快速选到合适行,在选到合适列
'''
m = len(matrix)
if m == 0:
return False
n = len(matrix[0])
i = m - 1 #行
j = 0 #列
# 从左下角出发 也可选择从右上角 i = 0 , j = n-1
while i >= 0 and j < n:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False
if __name__ == '__main__':
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
print(searchMatrix2(matrix, target))<file_sep>def countDigitOne(n):
'''
思路:
:param n:
:return:
'''
cnt, i = 0, 1
while i <= n: # i 依次个、十、百...位的算,直到大于 n 为止。
cnt += n // (i * 10) * i + min(max(n % (i * 10) - i + 1, 0), i)
i *= 10
return cnt
if __name__ == '__main__':
n = 100
print(countDigitOne(n))
<file_sep>
def radix_sort(nums):
mod = 10
div = 1
mostBit = len(str(max(nums))) # 最大数的位数决定了外循环多少次
buckets = [[] for _ in range(mod)] # 构造 mod 个空桶
while mostBit:
for num in nums: # 将数据放入对应的桶中
buckets[num // div % mod].append(num)
i = 0
for bucket in buckets: # 将数据收集起来
while bucket:
nums[i] = bucket.pop(0) # 依次取出
i += 1
div *= 10 #进位,由地位到高位桶排序
mostBit -= 1
return nums
if __name__ == '__main__':
nums = [13,141,221,28,19,115,12]
print(radix_sort(nums))<file_sep># from collections import defaultdict
# def main(n,m,task_t,depend):
# '''
# BFS方法
# :param n:
# :param m:
# :param task_t:
# :param depend:
# :return:
# '''
#
# task_dict = { i:x for i,x in enumerate(task_t)}
# dic = defaultdict(list)
# for i in range(m):
# dic[depend[i][1]-1].append(depend[i][0]-1)
# res = []
# # 初始化任务完成状态
# remain = list(task_dict.keys())
# while remain:
# level = []
# # 找到所有能够执行的任务
# for i in remain:
# if i not in task_dict or i not in dic:
# level.append(i)
# # 将level中的任务按执行时间降序排列
# level.sort(key = lambda x:task_dict[x])
# for i in level:
# res.append(i)
# remain.remove(i)
# # 删除已完成任务的依赖
# for k in dic.copy():
# if i in dic[k]:
# dic[k].remove(i)
# if len(dic[k]) == 0:
# del dic[k]
#
# for i in res:
# print(i+1,end = ' ')
#
# if __name__ == '__main__':
# n, m = 5,6
# task_t = [1,2,1,1,1]
# depend = [[1,2],[1,3],[1,4],[2,5],[3,5],[4,5]]
# main(n,m,task_t,depend)
# 优先队列法
from collections import defaultdict
import heapq
class Node(object):
def __init__(self, time, l, index):
self.time = time
self.l = l
self.index = index
def __lt__(self, other):
if self.time < other.time:
return True
elif self.time == other.time:
return self.index < other.index
else:
return False
N, M = map(int, input().split())
times = list(map(int, input().split()))
d = defaultdict(set)
l = []
# heapq.heapify(l)
for i in range(M):
tmp = list(map(int, input().split()))
for e in tmp[:-1]:
d[tmp[-1]].add(e)
for i in range(N):
# print(times[i], d[i+1],i+1)
heapq.heappush(l, Node(times[i], d[i + 1], i + 1))
res = []
while len(l) > 0:
tmp = []
node = None
# 找出一个入度为0的结点开始
while len(l) > 0:
node = heapq.heappop(l)
if len(node.l) > 0:
tmp.append(node)
else:
res.append(node.index)
break
for e in tmp:
heapq.heappush(l, e)
# 做完node这个任务,更新后续任务的依赖关系,即更新后续任务node.l的值
if node != None:
for i in range(len(l)):
if node.index in l[i].l:
l[i].l.remove(node.index)
for e in res:
print(e, end=" ")
<file_sep>from collections import Counter,defaultdict
def minWindow(s, t):
'''
:param s:
:param t:
:return:
'''
t = Counter(t)
lookup = defaultdict(int)
# start,end分别表示动态滑窗的起始点
start = 0
end = 0
min_len = float("inf")
res = ""
while end < len(s):
lookup[s[end]] += 1
end += 1
# print(start, end)
while all(map(lambda x: lookup[x] >= t[x], t.keys())):
if end - start < min_len:
res = s[start:end]
min_len = end - start
lookup[s[start]] -= 1
start += 1
return res
def minWindow1(s, t):
# mem为t的字符计数器
mem = defaultdict(int)
for char in t:
mem[char] += 1
t_len = len(t)
minL, minR = 0, float('inf')
l = 0
for r, ch in enumerate(s):
# 经过此步操作后,mem中包含t的key的键值为0,其余的s中遍历过的字符但是不在t中的键值变为负数(这里我们值关系t中对应的值
# 在mem中的计数情况,其它的不需要过多考虑)
if mem[ch] > 0:
t_len -= 1
mem[ch] -= 1
# 当子串满足要求,mem记录的是满足存在子串的滑窗中的字符个数
if t_len == 0:
while mem[s[l]] < 0:
mem[s[l]] += 1
l += 1
# 存下当前动态滑窗在字符串中的索引
if r - l < minR - minL:
minL, minR = l, r
# 调整滑窗的前向索引
mem[s[l]] += 1
t_len += 1
l += 1
return '' if minR == float('inf') else s[minL:minR + 1]
if __name__ == '__main__':
s = "ADOBECODEBANC"
t = "ABC"
print(minWindow1(s, t))<file_sep>from collections import defaultdict,Counter
def longestArithSeqLength(nums):
'''
求最长的等差子序列的长度
:param nums:
:return:
'''
# 1、确定状态 三维dp[(j,i)]表示到达当前位置i,公差为j的等差数列的长度
# 3、初始条件为空
dp = defaultdict(int)
# 4、计算顺序 自左向右
for i in range(1, len(nums)):
# j为nums[i]之前的数
for j in range(i):
# 这里代表i 代表后面数组中出现符合等差数列规律的数
# 2、转移方程
if (nums[i] - nums[j], j) not in dp:
dp[(nums[i] - nums[j], i)] = 2
else:
dp[(nums[i] - nums[j], i)] = dp[(nums[i] - nums[j], j)] + 1
return max(dp.values())
def longestArithSeqLength2(nums):
# nums每个数的下标字典
idx = defaultdict(list)
for i, v in enumerate(nums):
idx[v].append(i)
ans = 0
# 1、确定状态
cnts = Counter()
# 4、计算顺序 自左向右
for k in range(1,len(nums)):
for j in range(k):
# nums[j]为等差数列中间数 nums[k]为等差数列靠后的数
# v为等差数列靠前的数
v = 2 * nums[j] - nums[k]
if v in idx:
# 可能出现nums中有重复数,其下标不同
for i in idx[v]:
if i >= j:
break
# 2、状态转移矩阵
# cnts[j, k]表示到达当前nums[k],以公差为(nums[k]-nums[j]),找到的v(属于数列中的数)的最大数量
# 因此最后结果还要加上nums[j]、nums[k]的长度
cnts[j, k] = max(cnts[j, k], cnts[i, j] + 1)
ans = max(ans, cnts[j, k])
return ans + 2
if __name__ == '__main__':
nums = [3,3,3,6,9,12]
print(longestArithSeqLength2(nums))
<file_sep>#
#内部bisect库实现
#
import bisect
L = [1, 3, 3, 6, 8, 12, 15]
x = 3
# 在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
x_insert_point = bisect.bisect_left(L, x)
print(x_insert_point)
# 在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
x_insert_point = bisect.bisect_right(L, x)
print(x_insert_point)
# 将x插入到列表L中,x存在时插入在左侧
x_insort_left = bisect.insort_left(L, x)
print(L)
# 将x插入到列表L中,x存在时插入在右侧
x_insort_rigth = bisect.insort_right(L, x)
print(L)
#
#二完全有序数组的二叉搜索
#
def binary_search(nums,target):
low, high = 0, len(nums)
# 没在列表中的元素能插在中间
while low < high:
mid = low + (high - low) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
return low #若查找的数不在列表中,则返回一个可插入的索引位置,使得列表依旧按顺序排列
#
#非完全有序数组的二叉搜索 eg.[3,4,5,0,1,2]
#
def binary_search2(nums,target):
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if target == nums[mid]:
return mid
if nums[low] <= nums[mid]: # 二分后前半段是升序
if nums[low] <= target <= nums[mid]: # 目标在前半段
high = mid - 1
else:
low = mid + 1
else: # 二分后前半段不是升序
if nums[mid] <= target <= nums[high]: # 目标在后半段
low = mid + 1
else:
high = mid - 1
return -1
########################二分查找四种#######################
def lower_bound(data,value):
'''
第一个大于等于value的位置
'''
st = 0
en = len(data)-1
mid = st+((en-st)>>1)
while(st<=en):
if data[mid]<value:
st = mid +1
else:
en = mid -1
mid = st+((en-st)>>1)
return st
def lower_bound_en(data,value):
'''
第一个小于value的位置
'''
st = 0
en = len(data)-1
mid = st+((en-st)>>1)
while(st<=en):
if data[mid]<value:
st = mid +1
else:
en = mid -1
mid = st+((en-st)>>1)
return en
def upper_bound(data,value):
'''
第一个大于value的位置
'''
st = 0
en = len(data)-1
mid = st+((en-st)>>1)
while(st<=en):
if data[mid]<=value:
st = mid +1
else:
en = mid -1
mid = st+((en-st)>>1)
return st
def upper_bound_en(data,value):
'''
第一个小于等于value的位置
'''
st = 0
en = len(data)-1
mid = st+((en-st)>>1)
while(st<=en):
if data[mid]<=value:
st = mid +1
else:
en = mid -1
mid = st+((en-st)>>1)
return en
if __name__ == '__main__':
nums = [1,2,5,12,36,44,49,69,75,79,88,98,100]
tar = 23
print(binary_search(nums,tar))<file_sep>class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree:
def preorderTraversal(self,root): #前序遍历
def dfs(root, res):
if root:
res.append(root.val)
dfs(root.left, res)
dfs(root.right, res)
res = []
dfs(root, res)
return res
def inorderTraversal(self,root): #中序遍历
def dfs(root,res):
if root:
if root.left:
dfs(root.left,res)
res.append(root.val)
if root.right:
dfs(root.right,res)
res = []
dfs(root, res)
return res
def postorderTraversal(self,root): #后序遍历
def dfs(root,res):
if root:
if root.left:
dfs(root.left,res)
if root.right:
dfs(root.right,res)
res.append(root.val)
res = []
dfs(root, res)
return res
def levelOrder(self, root):
res, level = [], [root]
while root and level:
res.append([node.val for node in level])
lrpair = [(node.left, node.right) for node in level]
level = [leaf for lr in lrpair for leaf in lr if leaf]
return res
def creatTree(self,nodeList): #数组层序构建二叉树
if nodeList[0] == None:
return None
head = TreeNode(nodeList[0])
Nodes = [head] #在后续存储所有节点
j = 1
for node in Nodes: #Nodes在每轮迭代都会变化,node遍历过的数就不会再遍历了
if node:
node.left = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
Nodes.append(node.left)
j += 1
if j == len(nodeList):
return head
node.right = (TreeNode(nodeList[j]) if nodeList[j] != None else None)
j += 1
Nodes.append(node.right)
if j == len(nodeList):
return head
<file_sep>
# n = int(input())
# works = []
# total = 0
# for _ in range(n):
# a,b = map(int,input().split())
# total += b
# works.append([a,b])
# works.sort(key = lambda x:x[1])
# cur_date = 0
# more_day = 0
#
# for i in range(n):
# cur_date += works[i][1]
# if cur_date > works[i][0]:
# more_day += cur_date - works[i][0]
# print(more_day)
# dp = [float('-inf') for _ in range(total+1)]
# for i in range(0,n):
# if j + works[i][1] > works[i][0]:
# if dp[j + works[i][1]] == float('-inf'):
# dp[j + works[i][1]] = j + works[i][1] - works[i][0]
#
# for j in range(0,total+1-works[i][1]):
# dp[j] = min(dp[j], dp[j+works[i][1]])
# else:
# dp[j] = min(dp[j], dp[j + works[i][1]])
#
# print(dp[total])
# def removeBoxes(nums):
# n = len(nums)
# dp = [[[0] * n for _ in range(n)] for _ in range(n)]
# def helper(i, j, k):
# if i > j:
# return 0
# if dp[i][j][k] != 0:
# return dp[i][j][k]
#
# while i < j and nums[i] == nums[i + 1]:
# i += 1
# k += 1
# res = (k + 1) ** 2 + helper(i + 1, j, 0)
# for m in range(i + 1, j + 1):
# if nums[m] == nums[i]:
# res = max(res, helper(i + 1, m - 1, 0) + helper(m, j, 1 + k))
# dp[i][j][k] = res
# return dp[i][j][k]
# return helper(0, n - 1, 0)
# while True:
# nums = [int(c) for c in input().split()]
# print(removeBoxes(nums))
# s = input()
#
# def isValid(s):
# dic = {')': '(', ']': '[', '}': '{'}
#
# stack = []
# for c in s:
# if c in dic:
# tmp = stack.pop() if stack else '?'
# if tmp != dic[c]:
# return False
# else:
# stack.append(c)
# return True if not stack else False
#
# maxx = 0
# for i in range(len(s)):
# if s[i] == '(':
# for j in range(i,len(s)):
# if s[j] == ')' and isValid(s[i+1:j]):
# maxx = max(j - i + 1,maxx)
#
# if s[i] == '[':
# for j in range(i,len(s)):
# if s[j] == ']' and isValid(s[i+1:j]):
# maxx = max(j - i + 1,maxx)
# print(maxx)
nums = [int(c) for c in input().split()]
if not nums:
print('')
exit(0)
res = nums[0]
pre_max = nums[0]
pre_min = nums[0]
for num in nums[1:]:
cur_max = max(pre_max * num, pre_min * num, num)
cur_min = min(pre_max * num, pre_min * num, num)
res = max(res, cur_max)
pre_max = cur_max
pre_min = cur_min
print(res)
<file_sep>n,s = map(int,input().split())
nums = [int(c) for c in input().split()]
l,r = 0,0
total = 0
minl = float('inf')
count = 0
while l < len(nums) and r < len(nums):
while total < s and r < len(nums):
total += nums[r]
count += 1
r += 1
if count < minl:
minl = count
total -= nums[l]
l += 1
count -= 1
print(minl)<file_sep>def strtoint(ch):
if ch == None:
flag = False
print('不是数字')
return
flag = True
minus = False
res = 0
i = 0
if ch[0] == '-':
minus = True
i += 1
if ch[0] == '+':
i += 1
for i in range(i,len(ch)):
if '0'<=ch[i]<='9':
res = res*10 + int(ch[i])
else:
flag = False
print('不是整数')
return
return -res if minus else res
if __name__ == '__main__':
s = list('d4d5s4')
print(strtoint(s))
<file_sep>class Solution:
def __init__(self):
self.count = 0
def InversePairs(self, data):
def MergeSort(lists):
if len(lists) <= 1:
return lists
mid = int(len(lists)/2)
left = MergeSort(lists[:mid])
right = MergeSort(lists[mid:])
r, l = 0, 0
res = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
res.append(left[l])
l += 1
else:
res.append(right[r])
r += 1
# count记录逆序对的数量
self.count += len(left)-l
res += right[r:]
res += left[l:]
return res
MergeSort(data)
return self.count % 1000000007<file_sep>def match(s,p): #暴力匹配法
i = 0
j = 0
lens = len(s)
lenp = len(p)
if lens < lenp:
return False
while i < lens and j < lenp:
if s[i] == p[j]:
i += 1
j += 1
else:
i = i - j + 1 #回朔
j = 0
if i > lens - lenp:
return False
if j >= lenp:
return i - lenp
return False
#########################################################################
def get_next(p,nexts):
i = 0
j = -1
nexts[0] = -1
while i < len(p):
if j == -1 or p[i] == p[j]:
i += 1
j += 1
nexts[i] = j
else:
j = nexts[j]
return nexts
def match2(s,p):
i = 0
j = 0
lens = len(s)
lenp = len(p)
nexts = [0]*(lenp+1)
nexts = get_next(p,nexts)
if lens < lenp:
return False
while i < lens and j < lenp:
if j == -1 or s[i] == p[j]:
i += 1
j += 1
else:
j = nexts[j]
if j >= lenp:
return i - lenp
return False
if __name__ == '__main__':
s = 'abababaabcbab'
p = 'abaabc'
print(match2(s,p))
<file_sep>from Linked_list import linkedlist_operate #链表题规范化输入输出
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseBetween(head,m,n):
l1 = []
l2 = []
l3 = []
count = 0
while head:
count += 1
if m <= count <= n:
l2.append(head.val)
elif count < m:
l1.append(head.val)
else:
l3.append(head.val)
head = head.next
l1.extend(l2[::-1]).extend(l3)
return l1
def reverseBetween1(head,m,n):
# 迭代版本
'''
思路:每次循环将cur.next和(pre.next--cur这个整体作交换(这一部分随着交换次数的增加,长度会增加))
:param head:
:param m:
:param n:
:return:
'''
dummy = pre = LNode(0)
dummy.next = head
for i in range(m - 1):
pre = pre.next
cur = pre.next
# cur:当前节点 pre:上一个节点 tmp:下一个节点
for i in range(n - m):
# 保存cur.next为后面做交换
tmp = cur.next
# tmp.next后的数接到cur后
# 使得pre.next中去除tmp位置元素
cur.next = tmp.next
# 将cur.next调换到最前面
tmp.next = pre.next
pre.next = tmp
return dummy.next
def reverseBetween2(head,m,n): #递归版本
# 待理解
if not head:
return None
left, right = head, head
stop = False
def recurseAndReverse(right, m, n):
nonlocal left, stop
# base case. Don't proceed any further
if n == 1:
return
# Keep moving the right pointer one step forward until (n == 1)
right = right.next
# Keep moving left pointer to the right until we reach the proper node
# from where the reversal is to start.
if m > 1:
left = left.next
# Recurse with m and n reduced.
recurseAndReverse(right, m - 1, n - 1)
# In case both the pointers cross each other or become equal, we
# stop i.e. don't swap data any further. We are done reversing at this
# point.
if left == right or right.next == left:
stop = True
# Until the boolean stop is false, swap data between the two pointers
if not stop:
left.val, right.val = right.val, left.val
# Move left one step to the right.
# The right pointer moves one step back via backtracking.
left = left.next
recurseAndReverse(right, m, n)
return head
if __name__ == '__main__':
l = [1, 2,3,4,5,6,7,8,9,10]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
print('输入')
llist.outll(cur)
m=2
n=5
res = reverseBetween1(cur.next,m,n)
print('输出')
llist.outll(res)<file_sep>
def longestPalindrome(s):
dic = {}
res = 0
odds = False #记录是否有奇数个的相同字符
for i in s:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
if len(dic) == 1: #字符串都相同
return dic[s[0]]
for j in dic:
if dic[j] % 2 == 0:
res += dic[j]
else:
res += dic[j] - 1
odds = True
if odds: #存在奇数个的字符的情况,要记得加1,因为最后只能保留一个是奇数的字符
res += 1
return res
if __name__ == '__main__':
nums = "tattarrattat"
print(longestPalindrome(nums))<file_sep>n,m = 5,3
nums = [1 ,2 ,3 ,2 ,2]
Q = 3
questions = [[1, 4],[2, 4],[1, 5]]
res = []
# questions.sort(key = lambda x:x[0])
for i in range(Q):
l = questions[i][0]
r = questions[i][1]
nums_test = nums[l-1:r]
see = set(nums_test)
res.append(len(see))
print('\n'.join(str(c) for c in res))
<file_sep>import heapq as hp
import math
#####################################BFS########################################
#层序遍历
def BFS(graph,s):
'''
:param graph:
:param s:表示第一个开始的节点
:return:
'''
res = []
queue = []
queue.append(s)
# 存储访问过哪些节点
seen = set()
seen.add(s)
while queue:
# 弹出队列第一个元素
vertex = queue.pop(0)
# vertex的邻接节点
nodes = graph[vertex]
for w in nodes:
if w not in seen:
queue.append(w)
seen.add(w)
res.append(vertex)
return res
########################################DFS#######################################
#前序遍历
def DFS(graph,s): #s表示第一个开始的节点
res = []
stack = []
stack.append(s)
seen = set() # 存储访问过哪些节点
seen.add(s)
while stack:
vertex = stack.pop() #弹出队列最后一个元素
nodes = graph[vertex] #vertex的临接节点
for w in nodes:
if w not in seen:
stack.append(w)
seen.add(w)
res.append(vertex)
return res
######################################KFS###########################################
def KFS(graph,s): #s表示第一个开始的节点
res = []
queue = []
queue.append(s)
seen = set() # 存储访问过哪些节点
seen.add(s)
parent = {s:None}
while (len(queue) > 0):
vertex = queue.pop(0) #弹出队列第一个元素
nodes = graph[vertex] #vertex的邻接节点
for w in nodes:
if w not in seen:
queue.append(w)
seen.add(w)
parent[w] = vertex
res.append(vertex)
return res,parent
#####################################Dijkstra######################################################
def Dijkstra (graph,start):
'''
方法一:堆排实现
:param graph:网络结构
:param start:路径起点
:return:
'''
res = []
pqueue = []
hp.heappush(pqueue,(0,start))
# 存储访问过哪些节点
seen = set()
parent = {start:None}
# 防止distance字典无初始化 导致后面distance[w]出现索引超界
distance = {x: math.inf for x in graph if x != start}
distance[start] = 0
while pqueue:
# 弹出队列第一个元素 小顶堆
dist,vertex = hp.heappop(pqueue)
# 当点在堆内弹出来的时候才能说是被看到
seen.add(vertex)
# vertex的邻接节点
nodes = graph[vertex]
for w in nodes:
if w not in seen:
if dist + graph[vertex][w] < distance[w]:
hp.heappush(pqueue,(dist+graph[vertex][w],w))
parent[w] = vertex
distance[w] = dist + graph[vertex][w]
res.append(vertex)
return parent,distance
if __name__ == '__main__':
# graph = {'A': ['B', 'C'], 'B': ['A', 'C', 'D'], 'C': ['A', 'B', 'D', 'E'], 'D': ['B', 'C', 'E', 'F'],
# 'E': ['C', 'D'], 'F': ['D']}
# # print(BFS(graph,'E'))
# print(DFS(graph, 'E'))
################################KFS########################################### 不带权重的最短路径
# res,parent = KFS(graph, 'E')
#######给定起始点‘E’,给定终点‘B’,求得最少走的节点数####
# v = 'B'
# Minpath = []
# while v != None:
# Minpath.append(v)
# v = parent[v]
# print(Minpath[::-1])
############################Dijistra######################################## 带权重的最短路径
graph_w = {'A': {'B':5, 'C':1}, 'B': {'A':5, 'C':2, 'D':1}, 'C': {'A':1, 'B':2, 'D':4, 'E':8},
'D': {'B':1, 'C':4, 'E':3, 'F':6},
'E': {'C':8, 'D':3}, 'F': {'D':6}}
parent, distance = Dijkstra(graph_w,'A')
v = 'D'
Minpath = []
while v != None:
Minpath.append(v)
v = parent[v]
print(Minpath[::-1]) #输出从A--D的最短路径
<file_sep>def maxKilledEnemies(grid):
# write your code here
m = len(grid)
if not grid or m == 0 or len(grid[0]) == 0:
return 0
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
res = [[0] * n for _ in range(m)]
# up
for i in range(m):
for j in range(n):
if grid[i][j] == 'W':
dp[i][j] = 0
else:
dp[i][j] = 0
if grid[i][j] == 'E':
dp[i][j] = 1
if i > 0:
dp[i][j] += dp[i - 1][j]
res[i][j] += dp[i][j]
# down
for i in range(m - 1, -1, -1):
for j in range(n):
if grid[i][j] == 'W':
dp[i][j] = 0
else:
dp[i][j] = 0
if grid[i][j] == 'E':
dp[i][j] = 1
if i < m - 1:
dp[i][j] += dp[i + 1][j]
res[i][j] += dp[i][j]
# left
for i in range(m):
for j in range(n):
if grid[i][j] == 'W':
dp[i][j] = 0
else:
dp[i][j] = 0
if grid[i][j] == 'E':
dp[i][j] = 1
if j > 0:
dp[i][j] += dp[i][j - 1]
res[i][j] += dp[i][j]
# right
for i in range(m):
for j in range(n - 1, -1, -1):
if grid[i][j] == 'W':
dp[i][j] = 0
else:
dp[i][j] = 0
if grid[i][j] == 'E':
dp[i][j] = 1
if j < n - 1:
dp[i][j] += dp[i][j + 1]
res[i][j] += dp[i][j]
maxx = 0
for i in range(m) :
for j in range(n):
if grid[i][j] == '0':
if res[i][j] > maxx:
maxx = res[i][j]
return maxx
if __name__ == '__main__':
grid = ["E"]
print(maxKilledEnemies(grid))<file_sep>class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.item = []
def push(self, x):
if not self.item:
self.item.append([x, x])
else:
self.item.append([x, min(self.item[-1][1], x)])
def pop(self):
self.item.pop()
def top(self) :
return self.item[-1][0]
def getMin(self):
return self.item[-1][1]
<file_sep>def spiralOrder(matrix):
u = 0
d = len(matrix) - 1
l = 0
r = len(matrix[0]) - 1
res = []
while True:
for i in range(l,r+1):
res.append(matrix[u][i])
u += 1
if u > d:break
for i in range(u,d+1):
res.append(matrix[i][r])
r -= 1
if r < l:break
for i in range(r,l-1,-1):
res.append(matrix[d][i])
d -= 1
if d < u:break
for i in range(d,u-1,-1):
res.append(matrix[i][l])
l += 1
if l > r:break
return res
matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
print(spiralOrder(matrix))
<file_sep>def rotate(arr):
lens = len(arr)
i = lens - 1
res = []
while i > 0: #打印右上角
row,col = 0,i
tem1 = []
while col < lens:
tem1.append(arr[row][col])
row += 1
col += 1
res.append(tem1)
i -= 1
i = 0
while i < lens: #打印左下角
row,col = i,0
tem2 = []
while row < lens:
tem2.append(arr[row][col])
row += 1
col += 1
res.append(tem2)
i += 1
return res
if __name__ == '__main__':
arr = [[1,2,3],[4,5,6],[7,8,9]]
print(rotate(arr))
<file_sep>from Linked_list import linkedlist_operate #链表题规范化输入输出
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
# def sortList(head):
# l = []
# while head:
# l.append(head.val)
# head = head.next
# l.sort()
# return l
##############################################################
# 链表的归并排序
def sortleft(head):
def merge(left, right):
dum = cur = LNode(0)
while left and right:
#较小的数接在cur后面
if left.val < right.val:
cur.next= left
left = left.next
else:
cur.next= right
right = right.next
cur = cur.next
# 剩下的数接在cur后面
cur.next = left or right
return dum.next
if not head or not head.next:
return head
fast,slow = head,head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
mid = slow.next
slow.next = None
left = sortleft(head)
right = sortleft(mid)
sorted = merge(left, right)
return sorted
if __name__ == '__main__':
l = [1, 8, 3, 4, 5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
print('输入')
llist.outll(cur)
res = sortleft(cur.next)
print('输出')
llist.outll(res)<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def maxsubtree(root,maxsum=float('-inf')):
'''
方法:后序遍历
:param root:
:param maxsum:
:return:
'''
if not root:
return 0
l = maxsubtree(root.left,maxsum)
r = maxsubtree(root.right,maxsum)
sums = root.val + l + r
# 判断左、右子树及以root为节点的数的节点数之和与maxsum的大小
maxsum = max(maxsum,sums,l,r)
return maxsum
class solution:
maximum = float('-inf')
result = None
def findSubtree(self, root):
self.helper(root)
return self.result,self.maximum
def helper(self, root):
if root is None:
return 0
left = self.helper(root.left)
right = self.helper(root.right)
sums = left + right + root.val
if sums > self.maximum:
self.maximum = sums
self.result = root
return sums
if __name__ == '__main__':
nums = [-10, 9, 20, None, None, 15, 7]
# nums = [15,16,17,8,67,7,41,55,None,44,None,None,11,None,None]
tree = operate_tree.Tree()
sol = solution()
print(maxsubtree(tree.creatTree(nums)))
<file_sep>
def minimumTotal(triangle):
'''
方法:二维DP
其实上一行到下一行就两个选择,横坐标不变或加一
:param triangle:
:return:
'''
# 第3、这里无需初始化
n = len(triangle)
# 第3、计算顺序 自下向上 自左往右(自下向上的原因:减少最后dp列表的最优判断)
# 从倒数第二层开始 此时triangle[i+1][j]是倒数第一层
for i in range(n-2,-1,-1):
for j in range(len(triangle[i])):
# 第1、确定状态 triangle[i][j]表示当前三角形位置的最小路径之和
# 第2、转移方程
triangle[i][j] += min(triangle[i+1][j],triangle[i+1][j+1])
#保存了每个位置计算的路径值
return triangle[0][0]
def minimumTotal2(triangle):
'''
方法:一维DP
:param triangle:
:return:
'''
n = len(triangle)
dp = triangle[-1]
# 第4
for i in range(n-2,-1,-1):
for j in range(i+1):
# 第1 第2
dp[j] = triangle[i][j] + min(dp[j],dp[j+1])
#保存了每一层计算的路径做小值
return dp[0]
if __name__ == '__main__':
nums =[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
print(minimumTotal(nums))<file_sep>def multiply(num1,num2):
size1 = len(num1)
size2 = len(num2)
int1 = 0
int2 = 0
s0 = ord('0')
for i in range(size1):
exp = size1 - i - 1
num = ord(num1[i]) - s0
int1 += num * (10 ** exp)
for i in range(size2):
exp = size2 - i - 1
num = ord(num2[i]) - s0
int2 += num * (10 ** exp)
return str(int1*int2)
if __name__ == '__main__':
num1 = "2"
num2 = "3"
print(multiply(num1,num2))<file_sep>import sys
import itertools
def deal(n, l):
res = ''
plan = []
cost = []
for i in range(1, n):
res += str(i)
for i in itertools.permutations(res, 3):
plan.append(i)
for i in plan:
summ = 0
for k,j in enumerate(i):
if k == 0:
summ += l[0][int(i[0])]
summ += l[int(i[0])][int(i[1])]
elif k == len(i)-1:
summ += l[int(i[k])][0]
else:
summ += l[int(i[k])][int(i[k + 1])]
cost.append(summ)
return min(cost)
if __name__ == "__main__":
# 读取第一行的n
n = 4
l = [[0 ,2, 6 ,5],
[2, 0, 4, 4],
[6, 4, 0, 2],
[5, 4, 2, 0]]
print(deal(n, l))
###########################################动态规划问题<file_sep>
###################################198########################################
def rob(nums):
'''
动态规划 , 备忘录法 o(n^2)
:param nums:
:return:
'''
# 1、确定状态 dp[i]为到达当前位置获得的最大金币
dp = [0 for i in range(len(nums))]
dp[0] = nums[0]
dp[1] = nums[1]
for i in range(2,len(nums)):
# 多次使用max()增加时间复杂度
dp[i] = nums[i] + max([dp[x] for x in range(i-1)])
return max(dp)
def rob1(nums):
'''
动态规划 优化时间
时间 o(n)
空间 o(n)
:param nums:
:return:
'''
# 1、确定状态 dp[i]为到达当前位置获得的最大金币
dp = [0 for i in range(len(nums))]
# 3、边界条件
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
# 4、计算顺序 自左向右
for i in range(2,len(nums)):
# 2、转移方程
dp[i] = max(nums[i] + dp[i-2],dp[i-1])
return dp[-1]
def rob2(nums):
'''
动态规划 优化空间
时间 o(n)
空间 o(1)
:param nums:
:return:
'''
# now i指向的点 last i前一个点
last = now = 0
for i in range(len(nums)):
# 等号右边的dp_prev与等号左边的dp_m相差2个下标位置
now, last = max(nums[i] + last, now), now
return last
####################################213##########################################
def rob_circle(nums):
if len(nums) == 1:
return nums[1]
pre1 = rob2(nums[1:])
pre2 = rob2(nums[:-1])
return max(pre1, pre2)
if __name__ == '__main__':
nums = [2,7,9,3,1]
print(rob1(nums))
nums1 = [1]
print(rob_circle(nums))<file_sep>
n,m = map(int,input().split())
# n,m = 5, 2
mod = 10**9 + 7
tmp = 657049
nums = []
for _ in range(n):
if _ == 0:
nums.append(tmp)
else:
tmp = (tmp**2) % mod
nums.append(tmp)
def medianSlidingWindow(nums, k):
import bisect
# window里一直是有序的数组
window = sorted(nums[:k])
res = []
# 如果滑窗长度为偶数
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
for i in range(k, len(nums)):
bisect.insort(window, nums[i])
# 滑窗删除未排序前窗前的第一个数(如果用remove时间复杂度是O(n),这里用二分)
index = bisect.bisect_left(window, nums[i - k])
window.pop(index)
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
return res
if __name__ == '__main__':
k = m
res = medianSlidingWindow(nums, k)
target = sum(res)
if target == int(target):
res = int(target)
print(res)
else:
res = (int(target)+ 0.5)
print('%.1f' %res)
<file_sep>grid = input()
points = input()
A = []
tmp = []
for i in grid:
if i == '0' or i == '1':
tmp.append(int(i))
if len(tmp) == 4:
A.append(tmp)
tmp = []
B = []
tp = []
for i in points:
if i != '[' and i != ']' and i != ',':
tp.append(int(i))
if len(tp) == 2:
B.append(tp)
tp = []
# A = [[0,0,1,1],[1,0,1,0],[0,1,1,0],[0,0,1,0]]
# B = [[2,2],[3,3],[4,4]]
for p in B:
x = p[0] - 1
y = p[1] - 1
if 0 <= x - 1 < 4:
A[x - 1][y] = 1 - A[x - 1][y]
if 0 <= x + 1 < 4:
A[x + 1][y] = 1 - A[x + 1][y]
if 0 <= y - 1 < 4:
A[x][y - 1] = 1 - A[x][y - 1]
if 0 <= y + 1 < 4:
A[x][y + 1] = 1 - A[x][y + 1]
print(A)
<file_sep>def getlargestsub(s):
if s == None:
return None
s = list(s)
n = len(s)
largestsub = [None]*(n+1)
largestsub[0] = s[n-1]
j = 0 #代表上一个存入largestsub数组的数的下标
for i in range(n-2,0,-1):
if s[i] >= largestsub[j]:
j += 1
largestsub[j] = s[i]
largestsub = largestsub[0:j+1]
return ''.join(largestsub[::-1])
if __name__ == '__main__':
s = 'acbdxmng'
result = getlargestsub(s)
print(result)
<file_sep>
def searchInsert(nums,target): #二分查找解决 注意 这种不能解决列表中有重复数的情况 但是能解决没在列表中的元素能插在其后面索引后面
fir, last = 0, len(nums)
while (last - fir >= 1): #注意这个条件
mid = (fir + last) // 2
if nums[mid] < target:
fir = mid + 1
elif nums[mid] > target:
last = mid
else:
return (mid)
return (fir)
if __name__ == '__main__':
nums = [1,2,3,4,5]
val = 6
print(searchInsert(nums,val))<file_sep>def main(N,nums):
MAXI = max(nums)
sumi = sum(nums)
# 如果数量最多的某类数的数量大于总树数量的一半
if ((sumi%2 == 0) and (MAXI > sumi//2)) or ((sumi%2 == 1) and (MAXI > sumi//2 + 1)):
print('-')
else:
result = [0]
# 遍历每棵树
for i in range(sumi):
if MAXI > sumi/2:
maxind = nums.index(MAXI)
result.append(maxind+1)
nums[maxind] = nums[maxind] - 1
else:
# 尝试种植下一棵与res最近种的树品种不同的树,如果与前一棵树相同,则选择另外一种
for j in range(N):
if (nums[j] != 0) and (j+1 != result[-1]) :
result.append(j+1)
nums[j] = nums[j] - 1
break
# 每次迭代要更新nums的值
MAXI = max(nums)
sumi = sum(nums)
result.pop(0)
str1 = ''
for i in result:
str1 = str1 +' ' +str(i)
return str1.lstrip(' ')
# def main(N,nums):
# MAXI = max(nums)
# sumi = sum(nums)
# # guo
# if ((sumi % 2 == 0) and (MAXI > sumi // 2)) or ((sumi % 2 == 1) and (MAXI > sumi // 2 + 1)):
# print('-')
# else:
# result = ['start']
# for i in range(sumi):
# if MAXI > sumi/2:
# Mindex = nums.index(MAXI)
# result = result + [Mindex+1]
# nums[Mindex] = nums[Mindex] - 1
# else:
# for j in range(N):
# if (nums[j] != 0) and (j+1 != result[-1]) :
# result = result + [j+1]
# nums[j] = nums[j] - 1
# break
# MAXI = max(nums)
# sumi = sum(nums)
# del result[0]
# result = str(result).replace('[','')
# result = result.replace(']','')
# result = result.replace(',','')
# return result
if __name__ == '__main__':
# a = int(input())
# nums = [int(c) for c in input().split()]
a = 3
nums =[4,2,1]
print(main(a,nums))<file_sep># n,m = map(int,input().split())
# # n为配料总数 m为钱数
#
# stors = [int(c) for c in input().split()]
# prices = [int(c) for c in input().split()]
#
# raws = []
# for i in range(len(stors)):
# raws.append([stors[i],prices[i]])
#思路:将原料按原料数量及原料价格一起排序,先正序排原料数量,若数量相同再正序排原料价格
# 用一个堆栈来维护,结果输出堆栈里最小的原料数量
import heapq as hq
n,m = 3, 10
raws = [[5,15],[5,20],[5,20]]
# 堆栈排序结构
class tup:
def __init__(self,num,val):
self.num = num
self.val = val
# 改写__lt__方法实现结构体排序
def __lt__(self,other):#operator <
if self.num < other.num:
return True
elif self.num == other.num:
return self.val < other.val
heap = []
for raw in raws:
hq.heappush(heap,tup(raw[0],raw[1]))
# 弹出第一最小原料数量的原料,判断当前钱是否够买
cur = hq.heappop(heap)
while m >= cur.val:
# 更新当前钱数及原料状态
m -= cur.val
tmp = cur.num + 1
hq.heappush(heap,tup(tmp,cur.val))
if m >= cur.val:
cur = hq.heappop(heap)
else:
break
rr = hq.heappop(heap)
print(rr.num)<file_sep>n,m = map(int,input().split())
nums = [int(x) for x in input().split()]
nums.sort()
arr = nums[:2*m]
res = 0
for i in range(m):
res += arr[i]*arr[2*m-1-i]
print(res)<file_sep>def isHappy(n):
dic = set()
m = n
while True:
summ = 0
# 计算整数n各位数字的平方和
while m != 0:
summ += (m%10)**2
m = m//10
if summ == 1:
return True
elif summ in dic:
return False
else:
dic.add(summ)
m = summ
if __name__ == '__main__':
n = 19
print(isHappy(n))<file_sep>'''
辗转相除法(最大公约数)
'''
def main1(a,b):
'''
解题步骤:
1 通过键盘输入两个需要求解的数a,b
2 比较两数的大小,找出较小的数,默认a为较小的数
3 较大数b取余较小数a,如果取余结果等于较小数a,算法终止,当前a或b即为最大的公约数
4 若取余结果不等于较小数a,则转到第二步
'''
def dfs(a,b):
if a > b:
a,b = b,a
if b % a == 0:
return a
else:
return dfs(b % a,b)
res = dfs(a,b)
res2 = a * b // res
return res, res2
print(main1(10,6))
'''
更相减损法(最大公约数)
'''
def main2(a,b):
'''
解题步骤:
1 通过键盘输入两个需要求解的数a,b
2 比较两数的大小,找出较小的数,默认a为较小的数
3 较大数b减去较小数a,如果相减结果等于较小数a,算法终止,当前a或b即为最大的公约数
4 若减结果不等于较小数a,则转到第二步
'''
def dfs(a,b):
if a > b:
a,b = b,a
if b - a == a:
return a
else:
return dfs(b - a,a)
res = dfs(a,b)
res2 = a*b // res
return res, res2
print(main2(10,6))
'''
最小公倍数 两个数的乘积 = 最大公约数 × 最小公倍数
'''
#########3个数的最大公约数与最小公倍数
def dfs(a, b):
if a > b:
a, b = b, a
if b - a == a:
return a
else:
return dfs(b - a, a)
def gcd_3(a,b,c):
return dfs(dfs(a,b),c)
#利用求大公约数求最小公倍数
def maxG(a,b,c):
return a*c*b*gcd_3(a,b,c)//(dfs(a,b)*dfs(a,c)*dfs(b,c))
print(gcd_3(5,10,6))
print(maxG(5,10,6))
<file_sep>T = int(input())
for _ in range(T):
s = int(input())
n,d,x,y = map(int, input().split())
t0,t1,t2 = map(int, input().split())
count0 = 0
count1 = 0
count2 = 0
while s > 0 :
if count0 == 0:
s -= n*d
count0 = t0
if s <= 0:
print('NO')
break
if count1 == 0:
s -= y
count1 = t1
if s <= 0:
print('YES')
break
if count2 == 0:
s -= x
count2 = t2
if s <= 0:
print('YES')
break
count0 -= 1
count1 -= 1
count2 -= 1
<file_sep>def countBits(num):
'''
判断二进制数有多少个1
动态规划
:param num:
:return:
'''
dp = [0] * (num + 1)
for i in range(num + 1):
# dp[i] = dp[i/2] + (i % 2)
dp[i] = dp[i >> 1] + (i % 2)
return dp
def countBits1(num):
'''
判断二进制数有多少个0
动态规划
:param num:
:return:
'''
dp = [0] * (num + 1)
dp[0] = 1
dp[1] = 0
for i in range(2,num + 1):
# dp[i] = dp[i/2] + (i % 2)
dp[i] = dp[i >> 1] + ((i+1) % 2)
return dp
if __name__ == '__main__':
num = 10
print(countBits1(num))<file_sep>######理解题意:两字符串完全相等,则不可能有最长特殊子序列,长度相同,取任意一个即可,长度不同,取长的那个字符串即可####
def findLUSlength1(a, b):
if a == b:
return -1
return max(len(a), len(b))
def findLUSlength2(a, b):
if a == b:
return -1
return max(len(a), len(b))
################################522#############################
def findLUSlength3(strs):
def subseq(w1, w2):
# True iff word1 is a subsequence of word2.
i = 0
for c in w2:
if i < len(w1) and w1[i] == c: #i用于记录w1中的元素是否在w2中全部出现过 这里添加i < len(w1)
i += 1
return i == len(w1) #当i = len(w1) 说明w1中的元素按顺序地在w2中出现 即w1是w2的子序列
A = strs # 采用降序排列,找到此字符串则为最长字符串 速度最快
A.sort(key = len, reverse = True)
for i, word1 in enumerate(A):
if all(not subseq(word1, word2) for j, word2 in enumerate(A) if i != j): #当word1都不是除word1以外的strs元素中的子序列时,输出该word1为最长特殊子序列
return len(word1)
return -1
if __name__ == '__main__':
a,b = "aba", "cdc"
# print(findLUSlength1(a,b))
print(findLUSlength3(["aba", "cdc", "eaedfg"]))<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList1(head):
# 初始化res=None代表反转链表的尾结点
p, res = head, None
while p:
p,res,res.next=p.next,p,res
return res
def isPalindrome(head):
if not head or not head.next:
return True
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 链表长度为奇数时
if fast:
slow = slow.next
p2 = reverseList1(slow)
p1 = head
while p1 and p2:
if p1.val != p2.val:
return False
p1 = p1.next
p2 = p2.next
return True
if __name__ == '__main__':
l = [1,2,2,1]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
print(isPalindrome(cur.next))
<file_sep>def deal(n, m, lmachine, ltask):
# 完成的任务数要最大 获得的收益也要最大
lmachine.sort(key=lambda x: (x.time, x.level), reverse=True)
ltask.sort(key=lambda x: (x.time, x.level), reverse=True)
# 最大能完成的任务数量及收益
profit = 0
count = 0
level = [0] * 105
j = 0
# 对于任务i,找到一个最合适的机器去完成它
for i in range(m):
# 机器j若满足任务i时间要求,level数组存储已遍历机器的机器等级
while j < n and lmachine[j].time >= ltask[i].time:
level[lmachine[j].level] += 1
j += 1
# 遍历找得最小的k来完成任务的机器等级
for k in range(ltask[i].level, 101):
if level[k]:
count += 1
level[k] -= 1
profit += 200 * ltask[i].time + 3 * ltask[i].level
break
return count, profit
class node:
def __init__(self, time, level):
self.time = time
self.level = level
if __name__ == '__main__':
n, m = map(int,input().split())
lmachine = []
ltask = []
for i in range(n):
b = input().split()
machine = node(int(b[0]), int(b[1]))
lmachine.append(machine)
for j in range(m):
c = input().split()
task = node(int(c[0]), int(c[1]))
ltask.append(task)
count, profit = deal(n, m, lmachine, ltask)
print(count, profit)
<file_sep>n = int(input())
nochan = []
for _ in range(n):
a,b,c = map(str,input().split(','))
nochan.append([a,b,c])
m = int(input())
from collections import defaultdict
dic = defaultdict(list)
for _ in range(m):
a,b,c,d = map(str,input().split(','))
dic[(a, b)].append(c)
dic[(a, b)].append(d)
res = []
for passen in nochan:
if (passen[0],passen[1]) in dic:
tmp = dic[(passen[0], passen[1])]
tmp.append(passen[2])
res.append(tmp)
else:
res.append(passen)
seen1 = set()
seen2 = set()
res2 = []
for idxx,i in enumerate(res):
if (i[0],i[1]) not in seen1 and (i[0],i[2]) not in seen2:
seen1.add((i[0],i[1]))
seen2.add((i[0],i[2]))
res2.append(i)
res2.sort(key = lambda x:(x[0],x[1]))
for k in res2:
print(','.join(k))
# 3
# CZ7132,A1,ZHANGSAN
# CZ7132,A2,ZHAOSI
# CZ7156,A2,WANGWU
# 2
# CZ7132,A1,CZ7156,A2
# CZ7156,A2,CZ7156,A3
<file_sep>
class Solution:
def __init__(self,X,start_node):
self.X = X #初始化矩阵D
self.start_node = start_node #开始的节点
self.array = [[0]*(2**len(self.X)) for i in range(len(self.X))]
#记录处于x节点,未经历M个节点时,矩阵储存x的下一步是M中哪个节点
def transfer(self,sets):
su = 0
for s in sets:
su = su + 2**s # 二进制转换
return su
# tsp总接口
def tsp(self):
s = self.start_node
num = len(self.X)
cities = list(range(num)) #形成节点的集合
past_sets = [s] #已遍历节点集合
cities.pop(cities.index(s)) #构建未经历节点的集合
node = s #初始节点
return self.solve(node,cities) #返回最短消耗
def solve(self,node,future_sets):
# 迭代终止条件,表示没有了未遍历节点,直接连接当前节点和起点即可
if len(future_sets) == 0:
return self.X[node][self.start_node]
d = 99999
# node如果经过future_sets中节点,最后回到原点的距离
distance = []
# 遍历未经历的节点
for i in range(len(future_sets)):
s_i = future_sets[i]
copy = future_sets[:] #索引切片是浅拷贝
copy.pop(i) # 删除第i个节点,认为已经完成对其的访问
distance.append(self.X[node][s_i] + self.solve(s_i,copy))
# 动态规划递推方程,利用递归
d = min(distance)
# node需要连接的下一个节点
next_one = future_sets[distance.index(d)]
# 未遍历节点集合
c = self.transfer(future_sets)
# 回溯矩阵,(当前节点,未遍历节点集合)——>下一个节点
self.array[node][c] = next_one
return d
if __name__ == '__main__':
D = [[0,8,2,3],[8,0,1,5],[2,1,0,1],[3,5,1,0]]
S = Solution(D,0)
print (S.tsp())
# 开始回溯
M = S.array
Opt_path = [0]
lists = list(range(len(S.X)))
start = S.start_node
while len(lists) > 0:
lists.pop(lists.index(start))
m = S.transfer(lists)
next_node = S.array[start][m]
Opt_path.append(next_node)
start = next_node
print(Opt_path)
<file_sep># s = '(((0)))'
#
# count1 = 0
#
# for i in s:
# if i == '(':
# count1 += 1
# if i == '0':
# break
#
# count2 = 0
# for j in range(len(s)-1,-1,-1):
# if s[j] == ')':
# count2 += 1
# if s[j] == '0':
# break
# res = min(count1,count2)
# print(res)
# app_list = [[5,1,1000],[2,3,3000],[5,2,15000],[10,4,16000]]
# disk = 15
# mem = 10
# n = len(app_list)
#
# dp = [[0 for _ in range(mem+1)] for _ in range(disk+1)]
# for i in range(0,n):
# for j in range(disk,app_list[i][0]-1,-1):
# for y in range(mem,app_list[i][1]-1,-1):
# dp[j][y] = max(dp[j][y], dp[j-app_list[i][0]][y-app_list[i][1]] + app_list[i][2])
# print(dp[disk][mem])
s = [1, 4, 2, 2, 3, 3, 2, 4, 1]
res = 0
from collections import defaultdict
class test:
def __init__(self):
self.res = 0
def dfs(self,s,score,flag):
if not flag:
if score > self.res:
self.res = score
return
count = 0
keyi = {}
for i in range(len(s)):
if s[i] == s[i-1]:
flag = True
keyi[i] = 2
<file_sep>class MyQueue():
def __init__(self):
"""
Initialize your data structure here.
"""
self.itema = []
self.itemb = []
def push(self, x):
"""
Push element x to the back of queue.
"""
self.itema.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
"""
if not self.itemb:
while self.itema:
self.itemb.append(self.itema.pop())
first = self.itemb.pop()
return first
def peek(self):
"""
Get the front element.
"""
if not self.itemb:
while self.itema:
self.itemb.append(self.itema.pop())
return self.itemb[-1]
def empty(self):
"""
Returns whether the queue is empty.
"""
return len(self.itema) == 0 and len(self.itemb) == 0<file_sep>import itertools
def countAndSay(n): #####这一题关键要读懂题目,后一个序列的输出结果是对前面的序列每个位置的数的描述,存在两个及以上连续的相同的数,则要计数报数
st = '1' ###
count = 1
for i in range(n - 1):
tmp = ''
for j in range(len(st) - 1):
if st[j] == st[j + 1]:
count += 1
else:
tmp += str(count)
tmp += st[j]
count = 1
tmp += str(count)
tmp += st[-1]
count = 1
st = tmp
def countAndSay2(n):
st = '1'
for i in range(n-1):
a = [digit for digit, group in itertools.groupby(st)]
b = [len(list(group)) for digit, group in itertools.groupby(st)] #itertools groupby 将迭代器中相邻的重复元素跳出来放在一起
st = ''.join(str(len(list(group))) + digit for digit,group in itertools.groupby(st))
return st
if __name__ == '__main__':
n = 10
print(countAndSay2(n))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def maxPathSum(root: TreeNode):
'''
思路:后序遍历到最右节点,从下往上递归
:param root:
:return:
'''
def max_path(root):
nonlocal max_num
if not root:
return 0
# 后序遍历到树的最右子节点
left = max_path(root.left)
right = max_path(root.right)
# 记录当前节点最大值 = 左子树节点之和+右子树节点之和+根节点 即后面的后序往上递归的寻路过程都是为了找到有路径的增益大于该节点
# 的左或右子树的节点之和
max_num = max(left + right + root.val, max_num)
# 此节点与左右子树较大值之和,较差的解直接被舍弃,不会再被用到
tmp = max(left, right) + root.val
# 若root的较大分支增益仍为负
# 不会在任何情况选这条路(父节点root中止),因此返回0
return max(0,tmp)
max_num = float('-inf')
max_path(root)
return max_num
if __name__ == '__main__':
nums = [-10, 9, 20, None, None, 15, 7]
tree = operate_tree.Tree()
print(maxPathSum(tree.creatTree(nums)))
<file_sep>import random
def getmaxmoney(n):
'''
:param n:房间的数量
:return:
'''
a = [None] * n
for i in range(n):
a[i] = random.uniform(1,n)
# 前4个房间中最多金币的量
max4 = 0
for i in range(4):
if a[i] > max4:
max4 = a[i]
for i in range(4,n-1):
if a[i] > max4:
return True if a[i] == max(a) else False
# for i in range(4,n-1):
# if a[i] > max4:
# return True
return False
if __name__ == '__main__':
n = 10
test_n = 100000
success = 0
for i in range(test_n):
if getmaxmoney(n):
success += 1
print(success/test_n)
<file_sep>def stoneGame(piles):
n = len(piles)
# dp[i][j]表示在piles[i:j+1]中,先手方相对于对手能够多出的石子数
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = piles[i]
# 计算顺序 由对角线向左,由下往上
for j in range(1,n):
for i in range(j-1,-1,-1):
dp[i][j] = max(piles[i]-dp[i+1][j],piles[j]-dp[i][j-1])
return dp[0][n-1] > 0
if __name__ == '__main__':
piles = [1,100,3]
print(stoneGame(piles))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def countNodes(root):
def get_height(root):
if not root:
return 0
# 这里因为给定完全二叉树,故求树的高度可简化
return 1 + get_height(root.left)
if not root: return 0
h = get_height(root)
if get_height(root.right) == h - 1:
# 说明根节点的左子树是满二叉树 故而 (左子树的节点数+根节点)== 2**(h-1) -1 + 1
return 2 ** (h - 1) + countNodes(root.right)
else:
# 根节点的右子树最后一层没有节点,故右子树的节点数+根节点 == 2**(h-2)-1 + 1
return 2 ** (h - 2) + countNodes(root.left)
if __name__ == '__main__':
l = [1,2,3,4,5,6]
tree = operate_tree.Tree()
print(countNodes(tree.creatTree(l)))
<file_sep>
class job:
def __init__(self,diff,peny):
self.d = diff
self.p = peny
N, M = 3,3
dict = {1:100,10:1000,1000000000:1001}
jobs = [1,10,1000000000]
import bisect
jobs.sort()
guys = [9, 10, 1000000000]
res = []
for ai in guys:
# 二分查找
ind = bisect.bisect_right(jobs, ai)
res.append(dict[jobs[ind-1]])
print(' '.join(str(c) for c in res))
<file_sep>from collections import Counter
n, k = map(int, input().split())
s = input()
# 计算得到每个数字的出现次数
d = Counter(list(map(int, s)))
res = float("inf")
ans = "A"
# i表示需要修改成的相同数字
for i in range(10):
tmp_s = s
# need代表还需要替换的次数
need = k - d[i]
cost = 0
# gap是修改以为数字的代价 由贪心原则 选择较小的gap进行数据搜索
gap = 1
while need > 0:
# i+gap为需要修改的原始数字,
if i + gap <= 9:
if d[i + gap] < need:
tmp_s = tmp_s.replace(str(i + gap), str(i))
cost += d[i + gap] * gap
need -= d[i + gap]
else:
# 因为要使i+gap --> i,从左往右逐次替代能保证字典序最小
# replace原序是从左往右
tmp_s = tmp_s.replace(str(i + gap), str(i), need)
cost += need * gap
break
# i-gap表示要变化的值小于当前值i
if i - gap >= 0:
if d[i - gap] < need:
tmp_s = tmp_s.replace(str(i - gap), str(i))
cost += d[i - gap] * gap
need -= d[i - gap]
else:
# 因为要使i-gap --> i,从右往左逐次替代能保证字典序最小
tmp_s = tmp_s[::-1]
tmp_s = tmp_s.replace(str(i - gap), str(i), need)
# 替换完要还原成原来的顺序
tmp_s = tmp_s[::-1]
cost += need * gap
break
gap += 1
# 遍历10个不同的i,找出修改
if cost < res:
ans = tmp_s
res = cost
# 对于cost相同的,选择字典序最小的号码输出
elif cost == res and tmp_s < ans:
ans = tmp_s
print(res)
print(ans)<file_sep>##########################数组操作#########################
def removeElement(nums,val):
n = len(nums)
for i in range(n-1,-1,-1):
if nums[i] == val:
del nums[i] #删除元素 del 比 pop 快
return len(nums)
def removeElement2(nums,val): #python2 中快
for i in range(nums.count(val)):
nums.remove(val)
return len(nums)
if __name__ == '__main__':
nums = [3,2,2,3]
val = 2
print(removeElement2(nums,val))<file_sep>
def reverseStr(s, k): ##########转换为列表操作###########
l = list(s)
for i in range(0, len(s), 2 * k):
l[i:i + k] = reversed(l[i:i + k])
return ''.join(l)
def reverseStr2(s, k): ###########字符串操作###########
res = ''
for i in range(0, len(s), 2 * k):
res += s[i:i + k][::-1] + s[i + k:i + 2 * k]
return res
if __name__ == '__main__':
s = "abcdefg"
k = 2
print(reverseStr2(s,k))<file_sep>import collections
import heapq as hq
def networkDelayTime(times, N, K):
'''
方法:堆排 + Dijkstra算法
思路:求出源点K到其它每个节点的最短距离,当其中相距最远的节点距离已经接收到信号,则所有节点都收到了信号
:param times:
:param N:
:param K:
:return:
'''
pqueue = [(0, K)]
dist = {}
adj = collections.defaultdict(list)
for u, v, w in times:
adj[u].append((v, w))
while pqueue:
# 将下一节点距离上一节点最短距离的节点先弹出来
time, node = hq.heappop(pqueue)
if node not in dist:
dist[node] = time
for v, w in adj[node]:
if v not in dist:
# 堆排(根据time + w 的值优先进行排序) 将最小值放在堆顶
hq.heappush(pqueue, (time + w, v))
return max(dist.values()) if len(dist) == N else -1
def networkDelayTime1(times, N, K):
'''
方法:Dijkstra算法
思路:求出源点K到其它每个节点的最短距离,当其中相距最远的节点距离已经接收到信号,则所有节点都收到了信号
:param times:
:param N:
:param K:
:return:
'''
graph = collections.defaultdict(list)
for u,v,w in times:
graph[u].append((v,w))
dist = {x: float('inf') for x in range(1,N+1)}
dist[K] = 0
seen = [False] * (N+1)
while True:
can_node = -1
can_dist = float('inf')
for i in range(1,N+1):
if not seen[i] and dist[i] < can_dist:
can_dist = dist[i]
can_node = i
if can_node < 0:break
seen[can_node] = True
for v,w in graph[can_node]:
dist[v] = min(dist[v],dist[can_node] + w)
return max(dist.values()) if max(dist.values()) < float('inf') else -1
if __name__ == '__main__':
times = [[2,3,1],[2,1,1],[3,4,1]]
N = 4
K = 2
print(networkDelayTime1(times, N, K))<file_sep>def nthUglyNumber(n):
'''
思路:因为丑数只能由1,2,3,5组合相乘得到,因此(除1外)每个丑数都是由若干个2,3,5的乘子组成
每次循环找下一丑数都是
:param n:
:return:
'''
res = [1]
p2, p3, p5 = 0,0,0
while n-1 > 0:
# p2代表res对应第p2之前位置已经乘过p2,且res[p2-1]*2在前面的丑数列表中已经出现
tmp = min(res[p2]*2,res[p3]*3,res[p5]*5)
res.append(tmp)
if res[p2]*2 == tmp:
p2 += 1
# 这里注意要用if,不能用elif,
# 因为丑数6,可能由于丑数2乘以res[p3]产生;也可能由于丑数3乘以res[p2]产生,而丑数6已经在res列表中
# 若采用elif,p3不会+1,下一次循环时,tmp又会等于6
if res[p3]*3 == tmp:
p3 += 1
if res[p5]*5 == tmp:
p5 += 1
n -= 1
return res[-1]
if __name__ == '__main__':
n = 10
print(nthUglyNumber(n))<file_sep>def getmaxdupstr(s): #迭代法
maxlen = 0
curmaxlen = 0
prechar = ''
for i in s:
if i != prechar:
maxlen = max(maxlen,curmaxlen)
curmaxlen = 1
prechar = i
else:
curmaxlen += 1
return maxlen
def getmaxdupstr1(s,index,curmaxlen,maxlen): #递归法
if index == len(s) - 1:
return max(maxlen,curmaxlen)
if s[index] == s[index-1]:
curmaxlen += 1
return getmaxdupstr1(s, index + 1, curmaxlen, maxlen)
else:
maxlen = max(maxlen,curmaxlen)
curmaxlen = 1
return getmaxdupstr1(s,index+1,curmaxlen,maxlen)
if __name__ == '__main__':
s = 'abcabcbb'
# print(getmaxdupstr(s))
print(getmaxdupstr1(s,0,1,1))
<file_sep>
class LNode:
def __init__(self, val=None):
self.val = val
self.next = None
class LinkList(object):
def __init__(self):
self.head = None
#链表初始化函数, 方法类似于尾插
def initList(self, val):
#创建头结点
self.head = LNode()
p = self.head
#逐个为 val 内的数据创建结点, 建立链表
for i in val:
node = LNode(i)
p.next = node
p = p.next
return self.head #将列表转化为链表结构后要返回链表的头指针
#链表判空
def isEmpty(self):
if self.head.next == 0:
print ("Empty List!")
return 1
else:
return 0
#取链表长度
def getLength(self):
if self.isEmpty():
exit(0)
p = self.head
len = 0
while p:
len += 1
p = p.next
return len
#输出链表
def outll(self,res):
p = res
while p is not None:
print(p.val, end='')
if p.next is not None:
print(', ', end='')
p = p.next
print('')
#链表插入数据函数
def insertElem(self, key, index):
if self.isEmpty():
exit(0)
if index<0 or index>self.getLength()-1:
print ("\rKey Error! Program Exit.")
exit(0)
p = self.head
i = 0
while i<=index:
pre = p
p = p.next
i += 1
#遍历找到索引值为 index 的结点后, 在其后面插入结点
node = LNode(key)
pre.next = node
node.next = p
#链表删除数据函数
def deleteElem(self, index):
if self.isEmpty():
exit(0)
if index<0 or index>self.getLength()-1:
print ("\rValue Error! Program Exit.")
exit(0)
i = 0
p = self.head
#遍历找到索引值为 index 的结点
while p.next:
pre = p
p = p.next
i += 1
if i==index:
pre.next = p.next
p = None
return 1
#p的下一个结点为空说明到了最后一个结点, 删除之即可
def create_linklist(self):
i = 1
head = LNode()
head.next = None
tmp = None
cur = head
while i < 8:
tmp = LNode()
tmp.val = i
tmp.next = None
cur.next = tmp
cur = tmp
i += 1
if __name__ == '__main__':
# 初始化链表与数据
val = [1, 2, 3, 4, 5]
# l = LinkList()
# l.initList(val)
# l.traveList()
#
# # 插入结点到索引值为3之后, 值为666
# l.insertElem(666, 3)
# l.traveList()
#
# # 删除索引值为4的结点
# l.deleteElem(4)
# l.traveList()
<file_sep>n = int(input())
ques = []
for i in range(n):
p,a,q,b = map(int,input().split())
ques.append([p,a,q,b])
total = 120
dp = [0] * (total+1)
for i in range(n):
for j in range(total,ques[i][0]-1,-1):
if j >= ques[i][2]:
dp[j] = max(dp[j], dp[j - ques[i][0]] + ques[i][1], dp[j - ques[i][2]] + ques[i][3])
elif j >= ques[i][0]:
dp[j] = max(dp[j], dp[j - ques[i][0]] + ques[i][1])
print(dp[total])
<file_sep>
def maxProfit(prices):
# 滚动数组优化空间复杂度
res = float('-inf')
if len(prices) <= 1:
return 0
minpr = prices[0]
for i in range(len(prices)):
diff = prices[i] - minpr
minpr = min(minpr, prices[i])
if diff > res:
res = diff
return res
##############################122##############################
def maxProfit2(prices):
'''
只看相邻两天是否有增长,增长则加上收益
:param prices:
:return:
'''
profit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i] - prices[i-1]
return profit
#############################买卖股票3##################################
def maxProfit3(prices):
'''
思路:5阶段处理法
1 第一次买前
2 持有股票
3 第一次卖之后 第二次卖之前
4 持有股票
5 第二次卖之后
:param prices:
:return:
'''
n = len(prices)
if n == 0 :
return 0
# dp[i][j]表示prices[0]--prices[i-1],在阶段j的最大获利
dp = [[0] * (5 + 1) for _ in range(n + 1)]
dp[0][1] = 0
for i in range(1, n + 1):
# 1,3,5阶段 手中无股票
for j in range(1, 5 + 1, 2):
# dp[i][j] = max{dp[i-1][j], dp[i-1][j-1] + P_i-1 - P_i-2 }
dp[i][j] = dp[i - 1][j]
if j > 1 and i > 1 :
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + prices[i - 1] - prices[i - 2])
# 2,4阶段 手中有股票
for j in range(2, 5 + 1, 2):
# dp[i][j] = max{dp[i-1][j] + P_i-1 – P_i-2 , dp[i-1][j-1], dp[i-1][j-2] + P_i-1 – P_i-2 }
dp[i][j] = dp[i - 1][j - 1]
if i > 1 :
dp[i][j] = max(dp[i][j], dp[i - 1][j] + prices[i - 1] - prices[i - 2])
if i > 1 and j == 4 :
dp[i][j] = max(dp[i][j], dp[i - 1][j - 2] + prices[i - 1] - prices[i - 2])
return max(dp[n][1], dp[n][3], dp[n][5])
def maxProfit31(prices):
h1 = h2 = - max(prices)
s1 = s2 = 0
for price in prices:
s2, h2, s1, h1 = max(s2, price + h2), max(h2, -price + s1), max(s1, price + h1), max(h1, -price)
return s2
#################################买卖股票4#####################################
def maxProfit4(K,prices):
'''
思路:同3
:param prices:
:return:
'''
n = len(prices)
if n == 0 :
return 0
# 增加条件,如果K超过n/2次,说明购买次数没有限制,同解决方法2
if K > n/2:
res = maxProfit2(prices)
return res
dp = [[-1000000] * (2 * K + 2) for _ in range(n + 1)]
dp[0][1] = 0
for i in range(1, n + 1):
# 修改5为2K+1
for j in range(1, 2 * K + 2, 2):
# dp[i][j] = max{dp[i-1][j], dp[i-1][j-1] + P_i-1 - P_i-2 }
dp[i][j] = dp[i - 1][j]
if j > 1 and i > 1 :
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + prices[i - 1] - prices[i - 2])
for j in range(2,2 * K + 2, 2):
# dp[i][j] = max{dp[i-1][j] + P_i-1 – P_i-2 , dp[i-1][j-1], dp[i-1][j-2] + P_i-1 – P_i-2 }
dp[i][j] = dp[i - 1][j - 1]
if i > 1 :
dp[i][j] = max(dp[i][j], dp[i - 1][j] + prices[i - 1] - prices[i - 2])
if i > 1 and j > 2:
dp[i][j] = max(dp[i][j], dp[i - 1][j - 2] + prices[i - 1] - prices[i - 2])
return max(dp[n][_] for _ in range(1,2*K+2,2))
if __name__ == '__main__':
nums = [3,2,6,5,0,3]
K=2
print(maxProfit4(K,nums))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#将先序遍历输出后的列表转化为二叉搜索树
def bstFromPreorder(preorder):
if not preorder:
return None
root = TreeNode(preorder[0])
if len(preorder) == 1:
return root
r = 0
for i in range(1,len(preorder)):
if preorder[i] > preorder[0]:
r = i
break
# 表示数组的值都在root节点的左子树中
if r == 0:
root.left = bstFromPreorder(preorder[1:])
# r表示root节点右子树的最小节点编号
else:
root.left = bstFromPreorder(preorder[1:r])
root.right = bstFromPreorder(preorder[r:])
return root
def bstFromPreorder2(preorder):
if preorder:
root = TreeNode(preorder[0])
l,r = [],[]
for i in range(1, len(preorder)):
if preorder[i] <= preorder[0]:
l.append(preorder[i])
else:
r.append(preorder[i])
root.left = bstFromPreorder2(l)
root.right = bstFromPreorder2(r)
return root
if __name__ == '__main__':
l = [3,9,20,1,2]
tree = operate_tree.Tree()
print(tree.levelOrder(bstFromPreorder([8,5,1,7,10,12])))<file_sep>def PrintMinNumber(numbers):
# write code here
nums = [str(c) for c in numbers]
class st(str):
def __lt__( x, y):
return x + y < y + x
nums.sort(key=st)
res = ''.join(nums)
return int(res)
nums = [3,32,321]
print(PrintMinNumber(nums))<file_sep>
def checkRecord(s):
if s.count('A') > 1:
return False
for i in range(2, len(s)):
if s[i] == 'L' and s[i - 1] == 'L' and s[i - 2] == 'L':
return False
return True
if __name__ == '__main__':
s = "PPALLP"
print(checkRecord(s))<file_sep>def fun(nums):
# 令初始为最大的数
maxsum = nums[0]
for i in range(len(nums)):
maxtmp = 0
for j in range(i,len(nums)):
maxtmp += nums[j]
if maxtmp > maxsum:
maxsum = maxtmp
return maxsum
nums = [int(c) for c in input().split()]
print(fun(nums))<file_sep>
def uniquePaths(m,n):
dp = [[1 for i in range(n)] for j in range(m)]
if m == 0 and n == 0: #增加这两行代码提高了速度
return 0
for i in range(m):
for j in range(n):
if i != 0 and j != 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
def uniquePathsWithObstacles(grid): #63.带障碍物
m,n = len(grid),len(grid[0])
dp = [[0 for i in range(n)] for j in range(m)]
if m == 0 and n == 0: # 增加这两行代码提高了速度
return 0
if grid[0][0] == 1:
return 0
else:
dp[0][0] = 1
for i in range(1,m): #dp第一列赋值
if grid[i][0] != 1:
dp[i][0] = dp[i-1][0]
else:
dp[i][0] = 0
for i in range(1,n): #dp第一行赋值
if grid[0][i] != 1:
dp[0][i] = dp[0][i-1]
else:
dp[0][i] = 0
for i in range(1,m):
for j in range(1,n):
if grid[i][j] != 1:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
else:
dp[i][j] = 0
return dp[-1][-1]
if __name__ == '__main__':
m,n=3,3
print(uniquePaths(m,n))
nums = [[1,0,0],[0,1,0],[0,0,0]]
# print(uniquePathsWithObstacles(nums))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def invertTree(root):
if not root:
return None
root.left, root.right = root.right, root.left #反转左右节点
invertTree(root.left)
invertTree(root.right)
return root
if __name__ == '__main__':
l = [4,2,7,1,3,6,9]
tree = operate_tree.Tree()
print(tree.levelOrder(invertTree(tree.creatTree(l))))<file_sep>from itertools import combinations
def letterCombinations(digits):
dic = {2: ['a','b','c'], 3: ['d','e','f'], 4: ['g','h','i'], 5: ['j','k','l'], 6: ['m','n','o'],
7: ['p','q','r','s'], 8: ['t','u','v'], 9: ['w','x','y','z']}
dic1 = {"2": "abc","3": "def","4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"}
if digits == '':
return []
res = ['']
for i in digits:
tmp = []
for j in dic[int(i)]:
for k in res:
tmp.append( k+j )
res = tmp
return res
def letterCombinations2(digits):
def dfs(res, dic, digits, cur):
if not digits:
res.append(cur)
return
for c in dic[digits[0]]:
dfs(res, dic, digits[1:], cur + c)
if not digits:
return []
dic = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
res = []
cur = ""
dfs(res, dic, digits, cur)
return res
if __name__ == '__main__':
s = "23"
print(letterCombinations2(s))<file_sep>n,m = map(int, input().split())
cols = [int(c) for c in input().split()]
from collections import Counter
dic_col = Counter(cols)
if len(dic_col.keys()) == n:
res = min(dic_col.values())
else:
res = 0
print(res)
<file_sep>import re
while True:
s = input()
ser1 = input()
ser2 = input()
# 正则表达式 通配符
p = '.*' + ser1 + '.*' + ser2 + '.*'
patt = re.compile(p)
if patt.match(s):
if patt.match(s[::-1]):
print('both')
else:
print('forward')
elif patt.match(s[::-1]):
print('backward')
else:
print('invalid')
<file_sep>def maxEnvelopes(envelopes):
'''
动态规划
:param envelopes:
:return:
'''
# w宽度 h高度
def custom_sort(x, y):
if x[0] > y[0]:
return 1
if x[0] < y[0]:
return -1
if x[1] > y[1]:
return 1
if x[1] < y[1]:
return -1
return 0
import functools
# 自定义排序法
envelopes = sorted(envelopes, key = functools.cmp_to_key(custom_sort))
n = len(envelopes)
dp = [1]*len(envelopes)
res = 0
for i in range(n):
for j in range(i):
if envelopes[j][0] < envelopes[i][0] and envelopes[j][1] < envelopes[i][1]:
dp[i] = max(dp[i],dp[j]+1)
res = max(dp[i],res)
return res
def maxEnvelopes1(envelopes):
'''
动态+二分查找
:param envelopes:
:return:
'''
envelopes = sorted(envelopes, key = lambda x:(x[0],-x[1]))
nums = []
for i in envelopes:
nums.append(i[1])
stack = [0] * len(nums)
maxl = 0
for x in nums:
low, high = 0, maxl
while low < high:
mid = low +(high - low) // 2
if stack[mid] < x:
low = mid + 1
else:
high = mid
stack[low] = x
maxl = max(low + 1, maxl)
return maxl
if __name__ == '__main__':
envelopes = [[5,4],[6,4],[6,8],[6,7],[2,3]]
print(maxEnvelopes(envelopes))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isSymmetric(root):
'''
满足镜像的条件:1、它们的两个根结点具有相同的值
2、每个树的右子树都与另一个树的左子树镜像对称
方法:递归
:param root:
:return:
'''
def isqeual(node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
# 递归遍历每一层的相邻的两个结点,判断是否对称
return isqeual(node1.left, node2.right) and isqeual(node1.right, node2.left)
return isqeual(root, root)
def isSymmetric1(root):
'''
方法:迭代
:param root:
:return:
'''
queue = [root, root]
while queue:
node1 = queue.pop()
node2 = queue.pop()
if not node1 and not node2: continue
if not node1 or not node2: return False
if node1.val != node2.val: return False
queue.append(node1.left)
queue.append(node2.right)
queue.append(node1.right)
queue.append(node2.left)
return True
if __name__ == '__main__':
l = [1,2,2,None,3,None,3]
tree = operate_tree.Tree()
print(isSymmetric1(tree.creatTree(l)))<file_sep>import itertools
nums = [_ + 1 for _ in range(5)]
chazhao = (3,1,5,2,4)
A = list(itertools.permutations(nums))
ind = A.index(chazhao)
print(A[len(A)-1-ind])
<file_sep>def twoCitySchedCost(costs): #sorted() 排序的lambda trick
costs = sorted(costs, key=lambda x: x[0] - x[1])
res, N = 0, len(costs) // 2
# for i in range(N):
# res += costs[i][0] + costs[i+N][1]
return sum(costs[i][0] for i in range(N)) + sum(costs[i + N][1] for i in range(N))
if __name__ == '__main__':
cost = [[10,20],[30,200],[400,50],[30,20]]
print(twoCitySchedCost(cost))<file_sep>
def rotate(nums,k): ###insert方法耗时 时间复杂度O(n^2)
for i in range(k):
nums.insert(0,nums[-1-i])
del nums[-k:]
return nums
def rotate2(nums,k): #####
k = k % len(nums) #如果k大于数组长度
nums[:] = nums[-k:] + nums[:-k]
return nums
if __name__ == '__main__':
nums = [1,2,3,4,5,6,7]
k = 3
# print(rotate(nums, k))
print(rotate2(nums, k))<file_sep>def cacu(a,b):
b[0] = 1
N = len(b)
for i in range(1,N):
b[i] = b[i-1] * a[i-1]
b[0] = a[N-1]
for i in range(N-2,0,-1):
b[i] *= b[0]
b[0] *= a[i]
return b
if __name__ == '__main__':
a = [1,2,3,4,5,6,7,8,9,10]
b = [None]*len(a)
print(cacu(a,b))
<file_sep>n = int(input())
res = 0
for i in range(1,n+1):
count = 0
while i >= 5:
i = i // 5
count += i
res += count
print(res)<file_sep>def minDeletionSize( A):
res = 0
for i in range(len(A[0])):
for j in range(1, len(A)):
a = A[j][i]
b = A[j-1][i]
if A[j][i] < A[j - 1][i]:
res += 1
break
return res
def minDeletionSize1( A):
res = 0
for i in zip(*A):
if list(i) != sorted(i):
res += 1
return res
if __name__ == '__main__':
A = ["zyx","wvu","tsr"]
print(minDeletionSize1(A))<file_sep>class Solution:
def minNumberInRotateArray(self, rotateArray):
'''
:param rotateArray:
:return:
'''
nums = rotateArray
low = 0
high = len(nums) - 1
while low < high:
mid = low + ((high - low) >> 1)
# 中间的数大于右边最大的数,说明最小的数应该出现在右半部分
if nums[mid] > nums[high]:
low = mid + 1
# 特殊测试用例 [1,1,1,1,0,1] 此时只能用O(log(n))的算法进行搜索
elif nums[mid] == nums[high]:
high = high - 1
# 或low = low + 1
else:
high = mid
return nums[low]<file_sep>
def wiggleMaxLength(nums):
'''
求摆动子序列
方法:flag法
:param nums:
:return:
'''
if len(nums) < 2:
return len(nums)
l = 1
state = 'begin'
for i in range(1, len(nums)):
if state == 'begin':
if nums[i] - nums[i - 1] > 0:
state = 'up'
l += 1
elif nums[i] - nums[i - 1] < 0:
state = 'down'
l += 1
elif state == 'up':
# 上一个前后差值为正,此次则应该为负
if nums[i] - nums[i - 1]<0:
state = 'down'
l += 1
elif state == 'down':
if nums[i] > nums[i - 1]:
state = 'up'
l += 1
return l
def wiggleMaxLength1(nums):
#空间优化的DP算法
if not nums:
return 0
up,down = 1,1
for i in range(1,len(nums)):
if nums[i] > nums[i-1]:
up = down + 1
elif nums[i] < nums[i-1]:
down = up + 1
return max(up,down)
def wiggleMaxLength2(nums):
if len(nums) < 2:
return len(nums)
count = 1
diff = nums[1] - nums[0]
if diff != 0:
count += 1
prediff = diff
for i in range(2, len(nums)):
diff = nums[i] - nums[i - 1]
# prediff 要包括等于号
if (diff > 0 and prediff <= 0) | (diff < 0 and prediff >= 0):
count += 1
prediff = diff
return count
if __name__ == '__main__':
l = [1,7,4,9,2,5]
print(wiggleMaxLength(l))<file_sep>class Solution:
def __init__(self):
self.head = None
self.end = None
def Convert(self, root):
'''
二叉搜索树转化为双向链表
思路:
:param root:
:return:
'''
# write code here
if not root:
return
self.Convert(root.left)
root.left = self.end
# self.end == None表示双向链表为空时 将root分别赋予给 self.head self.end
if self.end == None:
self.head = root
else:
self.end.right = root
self.end = root
self.Convert(root.right)
return self.head<file_sep>
def MoreThanHalfNum_Solution(numbers):
'''
假设有这个数字,那么它的数量一定比其它所有数字之和还要多,按照这个思路得出num,然后验证
'''
if not numbers:
return 0
num = numbers[0]
count = 1
for i in range(1, len(numbers)):
if numbers[i] == num:
count += 1
else:
count -= 1
if count == 0:
num = numbers[i]
count = 1
count = 0
for i in numbers:
if i == num:
count += 1
return num if count > len(numbers) / 2.0 else 0<file_sep>def shellsort(nums):
ll = len(nums)
gap = 1
while gap < ll//3: # 动态定义间隔序列
gap = gap *3 + 1
while gap > 0:
for i in range(gap,ll):
cur,preind = nums[i],i-gap # cur保存当前待插入的数
while preind >= 0 and cur < nums[preind]: # 插入排序
nums[preind + gap] = nums[preind] # 将比 cur 大的元素向后移动
preind -= gap
nums[preind + gap] = cur
gap //= 3 #移动到下一个动态间隔
return nums
if __name__ == '__main__':
nums = [13, 141, 221, 28, 19, 115, 12]
print(shellsort(nums))<file_sep>def minCost(costs):
# write your code here
n = len(costs)
# dp[i][j]表示粉刷第i个房子为第j中的颜色的最小费用
dp = [[float('inf')] * 3 for _ in range(n + 1)]
dp[0][0] = dp[0][1] = dp[0][2] = 0
for i in range(1, n + 1):
# show this time's the last house's color
for j in range(3):
# the pre house's color
for k in range(3):
if k == j:
continue
dp[i][j] = min(dp[i][j], dp[i - 1][k] + costs[i - 1][j])
res = min(dp[n][0], dp[n][1], dp[n][2])
return res
################################房屋染色2#############################
# 颜色为k种
def minCostII(costs):
# write your code here
if not costs:
return 0
n = len(costs)
k = len(costs[0])
# dp[i][j]表示粉刷第i个房子为第j中的颜色的最小费用
dp = [[float('inf')] * k for _ in range(n + 1)]
for i in range(k):
dp[0][i] = 0
for i in range(1, n + 1):
# 找出dp[i-1][0]....dp[i-1][k-1]中最小的费用和次小的费用 j2 j1记录颜色种类
min1 = min2 = float('inf')
j2 = j1 = float('inf')
for j in range(k):
if dp[i - 1][j] < min1:
min2 = min1
j2 = j1
min1 = dp[i - 1][j]
j1 = j
else:
if dp[i - 1][j] < min2:
min2 = dp[i - 1][j]
j2 = j
# 转移矩阵
for j in range(k):
if j != j1:
dp[i][j] = dp[i - 1][j1] + costs[i - 1][j]
else:
dp[i][j] = dp[i - 1][j2] + costs[i - 1][j]
res = min(dp[n][j] for j in range(k))
return res
if __name__ == '__main__':
costs = [[14,2,11],[11,14,5],[14,3,10]]
print(minCostII(costs))<file_sep>
def bfs(grid, begin, end):
'''
bfs方法能求得最短路径
:param grid:
:param begin:
:param end:
:return:
'''
n= len(grid)
seen = []
dx = [1, 0, -1, 0] # 四个方位
dy = [0, 1, 0, -1]
level = []
level.append(begin)
seen.append(begin)
step = 0
while level:
queue = []
step += 1
for q in level:
for i in range(4):
nx, ny = q[0] + dx[i], q[1] + dy[i]
if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] != '#':
if [nx, ny ] in end:
return step
if [nx, ny] not in queue and [nx, ny] not in seen:
queue.append([nx, ny])
seen.append([nx, ny])
level = queue
print(level)
return -1
if __name__ == '__main__':
n = int(input())
grid = [['' for _ in range(n)] for _ in range(n)]
g3 = []
begin = []
end = []
# 复制9块迷宫 从中间那块迷宫的起点'S'出发,直到到达任意9块迷宫中的'E'
for i in range(n):
s = input()
g3.append(s*3)
grid[i] = list(s)
if 'S' in s:
begin.append(i+n)
begin.append(s.index('S')+n)
if 'E' in s:
for x in range(0,2*n+1,n):
for y in range(0,2*n+1,n):
end.append([i + x,s.index('E') + y])
maze = []
for i in range(3):
for j in range(len(g3)):
maze.append(g3[j])
print(bfs(maze, begin, end))
<file_sep>'''
总结:关键是对数论中的逆元取模(即分数的取模方式)不熟悉
'''
n,p,q = map(int,input().split())
mod = 10**9 + 7
# 逆元模板
def inv(x):
global mod
if(x==1):
return 1
return (mod-mod//x)*inv(mod%x)%mod
# 求两个数的最大公约数
def fun(a,b):
x = a % b
while (x != 0):
a = b
b = x
x = a % b
return b
# n_chan代表所有符合条件的组合数
n_chan = 0
num = 0
i = p
while i <= n-q:
summ = 1
if i == p:
# 求出C(N,P)
summ = 1
for j in range(i, 0, -1):
summ *= (n - (i - j)) / j
cn = summ
# 求期望的分子部分
num += i * cn
else:
# 递推依次求 C(n,p+1),...,C(n,n-q)
cn = cn*(n-(i-1))/i
num += i * cn
#C(n,p)+C(n,p+1)+...+C(n,n-q)
n_chan += cn
i += 1
den = n_chan
gongyue = fun(num,den)
# 约分分子分母
num = num//gongyue
den = den//gongyue
print(int(num//gongyue*inv(den))%mod)
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def detectCycle(head):
if not head or not head.next:
return None
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
# 找到链表中入环的第一个结点
# 这里注意,slow与fast指针第一次相遇的结点不一定是入口节点
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None
def detectCycle1(head): ###哈希##
l = set()
while head:
if head in l:
return head
l.add(head)
head = head.next
return head
if __name__ == '__main__':
l1 = [4,1,8,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l1)
res = detectCycle(cur.next)
print('输出')
print(res)<file_sep>class DP:
def lengthOfLIS(self, nums):
'''
方法: 动态规划o(n^2)
:param nums:
:return:
'''
if len(nums) < 2:
return len(nums)
# 1、确定状态,dp[i]表示nums[:i]这段数组的最长上升子序列
# 2、初始化
dp = [1] * len(nums)
# 4、计算顺序 自左往右
for i in range(1, len(nums)):
# j为遍历i之前的数
for j in range(i):
# 遍历i之前的所有dp,判断前面dp[j]+1 是否有长于dp[i]的
if nums[i] > nums[j]:
# 2、状态转移方程
dp[i] = max(dp[j] + 1, dp[i])
return max(dp)
def lengthOfLIS2(self, nums):
'''
方法: 动态规划 + 二分查找 o(nlogn)
思路:模拟一个stack,每输入一个数x,如果这个数大于栈顶的那个数,把它推入栈中,
如果不是,则用二分查找栈中元素是否有小于该元素的值,如果存在,则将x插入到它的后面
虽然插入后改变了栈中元素的值,最长上升子序列的输出不合理,但是对于求出最长上升子序列的长度不影响
:param nums:
:return:
'''
# stack是一个逐个存储nums的有序栈
stack = [0] * len(nums)
# 1、确定状态 当前迭代的最大长度
maxl = 0
# 4、计算顺序 自左向右
for x in nums:
# 3、初始边界条件
# 当x不符合上升子序列时,maxl的值会减小,从而缩短了二分搜索的范围
low, high = 0, maxl
# 在stack中(二分搜索)找到一个位置插入x
while low < high:
mid = low +(high - low) // 2
if stack[mid] < x:
low = mid + 1
else:
high = mid
# stack[:low]的长度 即为以x为子序列末尾的最大长度
stack[low] = x
# 2、状态转移方程
maxl = max(low + 1, maxl)
return maxl
if __name__ == '__main__':
mal = DP()
nums = [4, 12, 17, 18, 20, 15, 101, 18]
print(mal.lengthOfLIS2(nums))
<file_sep>###################################131####################################
def partition(s: str):
'''
dfs 回朔法
:param s:
:return:
'''
def dfs(s, tmp, res):
if not s:
res.append(tmp)
return 0
for i in range(len(s)):
if s[:i + 1] == s[i::-1]:
dfs(s[i + 1:], tmp + [s[:i + 1]], res)
res = []
tmp = []
dfs(s, tmp, res)
return res
################################132################################
def minCut( s):
'''
动态规划 + 中心拓展
:param s:
:return:
'''
n = len(s)
# 记录字符串s[l:r+1]是否为回文串
ispalin = [[False] * n for _ in range(n)]
for i in range(n):
# odd case, like "aba"
l = r = i
while l >= 0 and r < len(s) and s[l] == s[r]:
ispalin[l][r] = True
l -= 1
r += 1
# even case, like "abba"
l = i
r = i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
ispalin[l][r] = True
l -= 1
r += 1
# 状态dp[i]为 s[0:i-1]子串最少可以划分为多少个回文串
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for j in range(i):
if ispalin[j][i - 1]:
dp[i] = min(dp[i], dp[j] + 1)
return dp[n] - 1
if __name__ == '__main__':
s = 'aab'
print(minCut(s))<file_sep>n,k = 6, 3
inters = [1 ,3 ,5 ,2 ,5 ,4]
T = [1, 1, 0 ,1, 0 ,0]
cur_ep = 0
point = 0
max_ep = 0
for i in range(n):
get_p = inters[i]
if T[i] == 1:
point += get_p
else:
# 当前打瞌睡的总兴趣分
cur_ep += get_p
# 使得cur_ep始终只包括k项打瞌睡的总兴趣分
if i + 1 > k:
de_ep = inters[i-k] if T[i-k] == 0 else 0
cur_ep -= de_ep
#
if cur_ep > max_ep:
max_ep = cur_ep
point += max_ep
print(point)
# max_inters = float('-inf')
# bianli = []
# for i,t in enumerate(T):
# if t == 0:
# bianli.append(i)
#
# for i in bianli:
# if i == 0:
# tt = 0
# if i + 1 + k < len(T):
# r = i + 1 + k
# else:
# r = len(T)
# for j in range(i+1, i+1 + k):
# if T[j] == 0:
# tt += inters[j]
# elif i == len(inters):
# tt = inters[-1]
# else:
# tt = 0
# if i + k < len(T):
# r = i + k
# else:
# r = len(T)
# for j in range(i,r):
# if T[j] == 0:
# tt += inters[j]
#
# if tt > max_inters:
# max_inters = tt
# max_i = i
#
# res = 0
# i = 0
# while i < len(T):
# if i != max_i:
# if T[i] == 1:
# res += inters[i]
# i += 1
# else:
# if i + k < len(T):
# r = i + k
# else:
# r = len(T)
# res += sum(inters[i:r])
# i += k
# print(res)
<file_sep>from queue import PriorityQueue as pque
## 优先队列接口
'''
#向队列中添加元素
PriorityQueue.put(item[, block[, timeout]])
#从队列中获取元素
PriorityQueue.get([block[, timeout]])
#队列判空
PriorityQueue.empty()
#队列大小
PriorityQueue.qsize()
'''
def PriorityQueue_int():
que = pque()
que.put(10)
que.put(1)
que.put(5)
while not que.empty():
print (que.get())
def PriorityQueue_tuple():
que = pque()
que.put((10,'ten'))
que.put((1,'one'))
que.put((10/2,'five'))
while not que.empty():
print (que.get())
class tup(object):
def __init__(self,priority,description):
self.priority = priority
self.description = description
#下面两个方法重写一个就可以了
def __lt__(self,other):#operator <
return self.priority > other.priority
# def __cmp__(self,other):
# #call global(builtin) function cmp for int
# return cmp(self.priority,other.priority)
# def __str__(self):
# return '(' + str(self.priority)+',\'' + self.description + '\')'
def PriorityQueue_class():
que = pque()
skill5 = tup(5,'proficient')
skill6 = tup(6,'proficient6')
que.put(skill6)
que.put(tup(5,'proficient'))
que.put(tup(10,'expert'))
que.put(tup(1,'novice'))
while not que.empty():
print (que.get())
if __name__ == '__main__':
PriorityQueue_class()
<file_sep>class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# 判断a的子结构是否与b相同
def isequal(root1,root2):
if (not root1 and not root2) or (not root2 and root1):
return True
if not root1 and root2:
return False
if root1.val == root2.val:
return isequal(root1.left,root2.left) and isequal(root1.right,root2.right)
else:
return False
result = False
if pRoot1 and pRoot2:
# 如果树a中出现于树b的根节点值相同的结点,则进行子结构的匹配
if pRoot1.val == pRoot2.val:
result = isequal(pRoot1, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.left, pRoot2)
if not result:
result = self.HasSubtree(pRoot1.right, pRoot2)
return result<file_sep>n,m = map(int,input().split())
nums = []
for i in range(m):
nums.append(int(input()))
class sol:
def __init__(self):
self.seen = set()
def dfs(self,nums,n,m,pos,step):
if step == m:
if pos not in self.seen:
self.seen.add(pos)
return
if 1 <= pos + nums[step] <= n:
a = pos + nums[step]
self.dfs(nums,n,m,a,step+1)
if 1 <= pos - nums[step] <= n:
b = pos - nums[step]
self.dfs(nums,n,m,b,step+1)
return
def main(self):
for pos in range(1,n+1):
self.dfs(nums,n,m,pos,0)
print(len(self.seen))
test = sol()
test.main()
s = list(input())
dic = set(s)
maxx = 0
for c in dic:
if s.count(c) > maxx:
maxx = s.count(c)
print(maxx)<file_sep>def canFinish(numCourses, prerequisites):
'''
方法一:DFS
:param numCourses:
:param prerequisites:
:return:
'''
###初始化逆邻接表
graph = [[] for _ in range(numCourses)]
for x,y in prerequisites:
graph[x].append(y)
###visit记录节点的访问状态
### 0表示节点未访问,1表示节点已经访问,-1表示节点正在被访问
visit = [0 for _ in range(numCourses)]
###DFS遍历
def dfs(i):
if visit[i] == -1:
return False
if visit[i] == 1:
return True
###如果节点i正在被访问,则节点i赋值为-1
###DFS遍历邻接点,如果邻接点已经被遍历,则为有环图
visit[i] = -1
for j in graph[i]:
if not dfs(j):
return False
###如果节点i被访问期间其邻接节点且为无环图,则节点i赋值为1
visit[i] = 1
return True
###以图的每个节点为起始点做dfs遍历
for i in range(numCourses):
if not dfs(i):
return False
return True
def canFinish1(numCourses, prerequisites):
'''
方法二:(BFS的拓扑排序) Kahn算法 AVO网 ---这里采用队列进行bfs的拓扑排序 采用栈可进行dfs的拓扑排序
用途:拓扑排序的结果不唯一。拓扑排序还可以用于检测一个有向图是否有环
关键辅助结构:
1、邻接表:通过结点的索引,我们能够得到这个结点的后继结点;
2、入度数组:通过结点的索引,我们能够得到指向这个结点的结点个数。
:param numCourses:
:param prerequisites:
:return:
'''
#课程的长度
clen = len(prerequisites)
if clen == 0:
# 没有课程,当然可以完成课程的学习
return True
# 入度数组,一开始全部为 0
in_degrees = [0 for _ in range(numCourses)]
# 邻接表
adj = [set() for _ in range(numCourses)]
# 想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
# [0,1] 表示1在先,0在后
# 注意:邻接表存放的是后继successor结点的集合
for second, first in prerequisites:
in_degrees[second] += 1
adj[first].add(second)
queue = []
# 首先遍历一遍,把所有入度为 0 的结点加入queue
for i in range(numCourses):
if in_degrees[i] == 0:
queue.append(i)
#counter记录能完成的课程数
counter = 0
while queue:
top = queue.pop(0)
counter += 1
for successor in adj[top]:
in_degrees[successor] -= 1
if in_degrees[successor] == 0:
queue.append(successor)
return counter == numCourses
#############################################210###############################################两种方法同上
def findOrder(numCourses, prerequisites):
'''
方法一:bfs拓扑排序
:param numCourses:
:param prerequisites:
:return:
'''
clen = len(prerequisites)
if clen == 0:
###不同
return [i for i in range(numCourses)]
in_degrees = [0 for _ in range(numCourses)]
adj = [set() for _ in range(numCourses)]
for second, first in prerequisites:
in_degrees[second] += 1
adj[first].add(second)
#增加res
res = []
queue = []
for i in range(numCourses):
if in_degrees[i] == 0:
queue.append(i)
while queue:
top = queue.pop(0)
res.append(top)
for successor in adj[top]:
in_degrees[successor] -= 1
if in_degrees[successor] == 0:
queue.append(successor)
#不同
if len(res) != numCourses:
return []
return res
def findOrder1(numCourses, prerequisites):
'''
方法一:dfs
:param numCourses:
:param prerequisites:
:return:
'''
if len(prerequisites) == 0:
###不同
return [i for i in range(numCourses)]
graph = [set() for _ in range(numCourses)]
for x, y in prerequisites:
graph[x].add(y)
visit = [0 for _ in range(numCourses)]
#保存结果
res = []
def dfs(i):
if visit[i] == -1:
return False
if visit[i] == 1:
return True
visit[i] = -1
for j in graph[i]:
if not dfs(j):
return False
visit[i] = 1
#此处将节点添加入结果列表
res.append(i)
return True
for i in range(numCourses):
if not dfs(i):
return []
return res
if __name__ == '__main__':
numCourses = 4
prerequisites = [[1,0],[2,0],[3,1],[3,2]]
print(findOrder1(numCourses,prerequisites))
<file_sep>def longestDupSubstring(S):
import functools
A = [ord(c) - ord('a') for c in S]
base = 26
mod = 2 ** 63 - 1
n = len(S)
###rabin-Karp 指纹字符串查找算法
def rabinKarp(k):
p = pow(base, k, mod)
cur = functools.reduce(lambda x, y: (x * base + y) % mod, A[: k])
seed = {cur}
for index in range(k, n):
cur = (cur * base + A[index] - A[index - k] * p) % mod
if cur in seed:
return index - k + 1
seed.add(cur)
return -1
###二分查找
low, high = 0, n
res = 0
while low < high:
mid = (low + high + 1) // 2
pos = rabinKarp(mid)
if pos != -1:
low = mid
res = pos
else:
high = mid - 1
return S[res: res + low]
if __name__ == '__main__':
str = "banana"
print(longestDupSubstring(str))<file_sep>L,R = map(int,input().split())
L,R = 1,1
import math
C = 2*math.pi*R
L = L%C
# 逆时针
x1 = round(R*math.sin(L/R),3)
y1 = round(R*math.cos(L/R),3)
# 顺时针
x2 = round(R*math.sin(-L/R),3)
y2 = round(R*math.cos(-L/R),3)
print('%.3f' % y2+ ' ' + '%.3f' % x2)
print('%.3f' % y1+ ' ' + '%.3f' % x1)
<file_sep># n = int(input())
# A = [int(c) for c in input().split()]
# B = [int(c) for c in input().split()]
n = 5
A=[1,2,4,3,5]
B=[5,2,3,4,1]
def seq(nums):
# stack是一个逐个存储nums的有序栈
stack = [0] * len(nums)
# 1、确定状态 当前迭代的最大长度
maxl = 0
# 4、计算顺序 自左向右
for x in nums:
# 3、初始边界条件
# 当x不符合上升子序列时,maxl的值会减小,从而缩短了二分搜索的范围
low, high = 0, maxl
# 在stack中(二分搜索)找到一个位置插入x
while low < high:
mid = low + (high - low) // 2
if stack[mid] < x:
low = mid + 1
else:
high = mid
# stack[:low]的长度 即为以x为子序列末尾的最大长度
stack[low] = x
# 2、状态转移方程
maxl = max(low + 1, maxl)
return maxl
C = [0 for _ in range(n+1)]
D = [0 for _ in range(n)]
#
for i in range(n):
C[A[i]] = i+1
B= B[::-1]
for i in range(n):
# 按B中的顺序,给A赋值
# 1,3,4,2,5
D[i] = C[B[i]]
# 此后相当于对D寻找最长上升子序列
print(seq(D))<file_sep>def main(hp, normalatt, buffatt):
if normalatt > buffatt // 2:
if hp % normalatt == 0:
count = hp // normalatt
else:
count = hp // normalatt + 1
return count
else:
count1 = 2 * (hp // buffatt)
remain = hp - (count1 // 2) * buffatt
if remain > normalatt:
count1 += 2
elif remain == 0:
count1 += 0
else:
count1 += 1
return count1
if __name__ == '__main__':
hp = int(input())
normalatt = int(input())
buffatt = int(input())
print(main(hp, normalatt, buffatt))
<file_sep>def dominantIndex(nums):
num = nums.copy()
nums.sort()
if len(nums) < 1:
return -1
if len(nums) == 1:
return 0
if nums[-1] >= 2 * nums[-2]:
return num.index(nums[-1])
else:
return -1
if __name__ == '__main__':
nums = [0,0,0,1]
print(dominantIndex(nums))<file_sep>import sys
def main(a,nums):
c = a+nums
return c
if __name__ == '__main__':
# 1
a = int(input())
nums = [int(c) for c in input().split()]
print(main(a,nums))
# 2
res = [int(c) for c in input().split()]
n, k = res[0], res[1]
n, k = map(int, input().split())
nums = [int(c) for c in input().split()]
print(main(n, k, nums))<file_sep>def rectCover(number):
'''
斐波那契数列
'''
n = number
if n == 0:
return 0
if n == 1:
return 1
fir = 1
las = 2
for i in range(2, n):
fir, las = las, fir + las
return las<file_sep>'''
题目:
小Q所在的城镇里有一条笔直的公路,在这条公路上分布着n个村子,编号从1到n。有些村庄需要购进水果,有些村庄需要贩出水果。
设第i个村庄对水果的需求为Ai,其中Ai>0,表示该村庄需要购进水果,Ai<0表示该村需要贩出水果,假定sum(Ai)=0,即水果供求平衡。
现在把k个单位的水果从一个村庄到相邻村庄需要k块钱,请问最少需要多少运费可以满足所有村庄的需求。
'''
def myfunc(nums):
ans, j = 0, 1
if len(nums) == 2:
return abs(nums[0]) # 终止条件
if nums[0] > 0:
flag = 1
elif nums[0] < 0:
flag = -1
else:
return myfunc(nums[1:])
if nums[j] * flag > 0:
j += 1
else: # 表示找到首个异号数字
if abs(nums[0]) > abs(nums[j]): # 表示异号的数的绝对值较小
ans += abs(nums[j]) * j # [5,-4,2,-3]-->[1,0,2,-3]
nums[0] = nums[j] + nums[0] # 继续计算[1,0,2,-3]直到第一个数为0
nums[j] = 0
else: # 若异号的数绝对值大于第一个数[3,-4,2,-1]
ans += abs(nums[0]) * j # [3,-4,2,-1]-->[0,-1,2,-1]
nums[j] = nums[j] + nums[0] # [0,-1,2,-1]-->[-1,2,-1]
nums[0] = 0 # [-1,2,-1]-->[0,1,-1]-->[1,-1]-->1
return ans + myfunc(nums[1:]) # 同时注意费用的计算,搬移量*距离
if __name__ == '__main__':
n = int(input())
nums = list(map(int, input().split()))
print(myfunc(nums))
<file_sep>
def findMinHeightTrees(n, edges):
'''
方法:BFS
思想:每次遍历树的所有叶节点,将本轮记录的所有叶节点从graph中删除,同时找到满足下一轮遍历的叶节点,循环反复直至遍历完至少n-1各节点
输出此时记录的叶节点,即为最小高度树的叶节点
:param n:
:param edges:
:return:
'''
if n == 1:return [0]
graph = [[] for _ in range(n)]
for x,y in edges:
graph[x].append(y)
graph[y].append(x)
# 从叶节点往根节点遍历
leaves = [i for i in range(n) if len(graph[i]) == 1]
while n > 2:
n -= len(leaves)
next_leaves = []
# 每次遍历所有的叶节点
for i in leaves:
j = graph[i].pop()
# 将上一层的叶节点从graph中删除
graph[j].remove(i)
if len(graph[j]) == 1:next_leaves.append(j)
leaves = next_leaves
return leaves
if __name__ == '__main__':
n = 4
edges = [[1, 0], [1, 2], [1, 3]]
print(findMinHeightTrees(n, edges))
<file_sep>class Solution:
def VerifySquenceOfBST(self, sequence):
'''
二叉搜索树的后序遍历序列
:param sequence:
:return:
'''
length = len(sequence)
if length == 0:
return False
if length == 1:
return True
# 后序遍历根节点
root = sequence[-1]
# left为右子树的最小结点号
r = 0
while sequence[r] < root:
r += 1
for j in range(r, length-1):
if sequence[j] < root:
return False
return self.VerifySquenceOfBST(sequence[:r]) or self.VerifySquenceOfBST(sequence[r:length-1])<file_sep>def main(nums):
'''
未完成AC原因:对于只有一个字符串的情况'aa',‘acca’也是可以循环的,但是‘ac'就不能循环了
:param nums:
:return:
'''
if len(nums) == 1:
# 更改此行
return 'true' if nums[0][-1] == nums[0][0] else 'false'
head = []
end = []
for i in nums:
head.append(i[0])
end.append(i[-1])
for i in range(len(nums)):
if head[i] == end[i-1]:
continue
else:
return 'false'
return 'true'
if __name__ == '__main__':
nums = ['acca']
print(main(nums))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.head = None
self.end = None
def Convert(self, root):
# write code here
if not root:
return
self.Convert(root.left)
root.left = self.end
if not self.end:
self.head = root
else:
self.end.right = root
# 最后的end指针指向最右边的结点
self.end = root
self.Convert(root.right)
return self.head
class Solution1:
def Convert(self, root):
if not root:
return None
if not root.left and not root.right:
return root
# 1.将左子树构造成双链表,并返回链表头节点
left = self.Convert(root.left)
p = left
# 2.定位至左子树双链表最后一个节点
while p and p.right:
p = p.right
# 3.如果左子树链表不为空的话,将当前root追加到左子树链表
if left:
p.right = root
root.left = p
# 4.将右子树构造成双链表,并返回链表头节点
right = self.Convert(root.right)
# 5.如果右子树链表不为空的话,将该链表追加到root节点之后
if right:
right.left = root
root.right = right
return left if left else root
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def removeElements(head, val): #思路类似链表移除重复的数
dum = LNode(0)
dum.next = head
cur = dum
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dum.next
if __name__ == '__main__':
l = [1,2,3,4,5,4]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
val = 4
res = removeElements(cur.next,val)
print('输出')
llist.outll(res)
<file_sep>def countingSort(nums):
bucket = [0] * (max(nums) + 1) # 桶的个数
for num in nums: # 将元素值作为键值存储在桶中,记录其出现的次数
bucket[num] += 1
i = 0 # nums 的索引
for j in range(len(bucket)):
while bucket[j] > 0:
nums[i] = j
bucket[j] -= 1
i += 1
return nums
if __name__ == '__main__':
nums = [13,141,221,28,19,115,12]
print(countingSort(nums))<file_sep>def main(n,nums):
nums.sort()
mid = len(nums) // 2
num1 = nums[:mid]
num2 = nums[mid:]
for i in range(mid):
num1[i] = num1[i] + num2[-(i+1)]
maximum = max(num1)
minimum = min(num1)
return maximum - minimum
if __name__ == '__main__':
n = int(input())
nums = [int(c) for c in input().split()]
print(main(n,nums))<file_sep>def PredictTheWinner(nums):
n = len(nums)
# 表示从nums[i]到nums[j]先手比另一位玩家多的分数,最后返回dp[0][len(nums)-1]是否大于0即可
dp = [[0 for _ in range(n)] for _ in range(n)]
# 初始化 当i=j时,先手一定赢,比另一位玩家多dp[i][j]
for i in range(n):
dp[i][i] = nums[i]
# 从下往上 从对角线往右
for i in range(n-1,-1,-1):
for j in range(i+1,n):
# 如果先手拿nums[i], 则后手比先手所dp[i+1][j]
# 如果先手拿nums[j], 则另一位玩家比先手多dp[i][j-1],
dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j - 1])
return dp[0][n-1] >= 0
if __name__ == '__main__':
nums = [1,5,2]
print(PredictTheWinner(nums))
<file_sep># 堆数
n = 10
# 第i堆的苹果数
app_heap = [155, 926, 296, 237, 24, 546, 271, 726 ,274,802]
#询问数
m = 7
ques = [1622, 1274, 883, 4224, 4093, 669, 459]
que = sorted(ques)
dic = {}
for i in que:
dic[i] = int()
res = []
summ = 0
i = 0
for ind,heapnum in enumerate(app_heap):
summ += heapnum
while i <= len(que):
if summ >= que[i]:
dic[que[i]] = ind+1
i += 1
if i == len(que):
break
else:
break
for i in ques:
print(dic[i])<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def deleteDuplicates(head):
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
def deleteDuplicates1(head):
dum = cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur = cur.next.next
head = cur
head = head.next
else:
cur = cur.next
return dum
###########################82 II#####
def deleteDuplicates2(head):
dum = pre = LNode(0)
dum.next = head
while head and head.next: #这里将head看成当前值
if head.val == head.next.val:
# 若存在多个重复值,则都跳过
while head and head.next and head.val == head.next.val:
head = head.next
head = head.next
pre.next = head
else:
pre = pre.next #没有重复节点时,pre的位置对应右移一步
head = head.next
return dum.next
#############################如何对无序的链表删除重复项###################### 拓展
def deleteDuplicates3(head):
'''
哈希表最小的时间复杂度
:param head:
:return:
'''
has = set()
dum = head
while head and head.next:
if head.val not in has:
has.add(head.val)
head = head.next
else: #删除单前节点操作
head.val = head.next.val
head.next = head.next.next
if head.val in has:
head.val = None
else:
head = head.next
return dum
if __name__ == '__main__':
l1 = [8,9,7,4,3,2,1,8,4,6,5,4,3,1,10]
l2 = [1,1,2,3,3]
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
cur2 = llist.initList(l2)
res = deleteDuplicates2(cur2.next)
print('输出')
llist.outll(res)<file_sep>def LeftRotateString(s, n):
'''
复制字符串,切片
:param s:
:param n:
:return:
'''
leng = len(s)
if leng == 0:
return ""
n = n % leng
s += s
return s[n:n + leng]
def LeftRotateString1(s, n):
'''
双旋转 YX = (X^T Y^T)^T
:param s:
:param n:
:return:
'''
if len(s) == 0:
return ""
s = s[::-1]
n = n % len(s)
s1 = s[:len(s)-n]
s2 = s[len(s)-n:]
return s1+s2
<file_sep>def findJudge(N, trust):
'''
思路:将每个人看成网络的一个节点 a信任b看成是a到b的有向路径 因此记录节点的入度既能判断某人是否是法官
:param N:
:param trust:
:return:
'''
rec = [0] * (N + 1)
for item in trust:
rec[item[1]] += 1
rec[item[0]] -= 1
for i in range(1, N + 1):
if rec[i] == N - 1:
return i
return -1
if __name__ == '__main__':
N = 4
trust = [[1, 3], [1, 4], [2, 3], [2, 4], [4, 3]]
print(findJudge(N, trust))<file_sep>#########################
# #
#找到数组中的最大值和最小值#
# #
#########################
def getmaxmin(nums): #方法1:蛮力法 O(2n-2)
max = -2**31
min = 2**31
for num in nums:
if num > max:
max = num
if num < min:
min = num
return max,min
def getmaxmin1(nums,l,r): #分治法 O(3n/2-2)
if not nums:
return []
list = []
m = (l+r)//2
if l == r: #若数组为奇数个,就有一个单独的元素需要处理
list.append(nums[l])
list.append(nums[l])
return list
if l+1 == r: #为一对时
if nums[l] >= nums[r]:
max = nums[l]
min = nums[r]
else:
min = nums[l]
max = nums[r]
list.append(min)
list.append(max)
ll = getmaxmin1(nums,l,m)
rl = getmaxmin1(nums,m+1,r)
Max = ll[1] if ll[1] > rl[1] else rl[1]
Min = ll[0] if ll[0] < rl[0] else rl[0]
list.append(Min)
list.append(Max)
return list
if __name__ == '__main__':
nums = [7,3,19,40,4,7,1]
print(getmaxmin1(nums,0,len(nums)-1))<file_sep>def numIslands(grid):
'''
题意:求岛屿的数量
方法:DFS+遍历限定条件优化
:param grid:
:return:
'''
'''
方法:DFS+遍历限定条件优化
:param grid:
:return:
'''
if not grid:
return 0
def dfs(grid, i, j):
# 遍历过的节点清零
grid[i][j] = '0'
# 遍历当前结点的四个方向
if i > 0 and grid[i - 1][j] == "1":
dfs(grid, i - 1, j)
if j > 0 and grid[i][j - 1] == "1":
dfs(grid, i, j - 1)
if i < len(grid) - 1 and grid[i + 1][j] == "1":
dfs(grid, i + 1, j)
if j < len(grid[0]) - 1 and grid[i][j + 1] == "1":
dfs(grid, i, j + 1)
# summ记录岛屿数量
summ = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
# 如果地图位置为1,dfs遍历该点的连通域,遍历完毕,得到一个岛屿计数
if grid[i][j] == '1':
summ += 1
dfs(grid, i, j)
return summ
def numIslands1( grid):
'''
bfs
:param grid:
:return:
'''
def bfs(grid, i, j):
queue = [[i, j]]
while queue:
[i, j] = queue.pop(0)
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == '1':
grid[i][j] = '0'
queue += [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
bfs(grid, i, j)
count += 1
return count
def numIslands2(grid):
'''
并查集
:param grid:
:return:
'''
########用并查集合并相关联顶点
f = {}
def find(x):
f.setdefault(x, x)
if f[x] != x:
f[x] = find(f[x])
return f[x]
def union(x, y):
f[find(x)] = find(y)
########
if not grid: return 0
row = len(grid)
col = len(grid[0])
for i in range(row):
for j in range(col):
if grid[i][j] == "1":
# 由于从左往右从上往下遍历,故只需要判断是否和左边、上边的格子是否有填充为'1'即可
for x, y in [[-1, 0], [0, -1]]:
tmp_i = i + x
tmp_j = j + y
if 0 <= tmp_i < row and 0 <= tmp_j < col and grid[tmp_i][tmp_j] == "1":
# grid[tmp_i][tmp_j]为左或上的点 grid[i][j]为当前点
union(tmp_i * col + tmp_j, i * col + j)
res = set()
for i in range(row):
for j in range(col):
if grid[i][j] == "1":
res.add(find((i * col + j)))
return len(res)
#################################130########################################
def solve(board):
'''
题意:
方法:DFS+限定条件
:param board:
:return:
'''
if not board: return
row = len(board)
col = len(board[0])
if row < 3 or col < 3: return
def dfs(i, j):
# 如果i,j中有一个越界或者遇到了X则不继续扫描
if i < 0 or j < 0 or i >= row or j >= col or board[i][j] != 'O':
return
# 否则把数组中的O变成#,意思是这个O和边缘是连通的
board[i][j] = '#'
# 之后从当前坐标开始上下左右进行递归搜索
dfs(i - 1, j)
dfs(i + 1, j)
dfs(i, j - 1)
dfs(i, j + 1)
###将边缘上的'O'都赋值为'#',同时也将矩阵中与边缘上的'O'连通的的'O'都赋值为'#'
for i in range(row):
dfs(i, 0)
dfs(i, col - 1)
for i in range(col):
dfs(0, i)
dfs(row - 1, i)
# 之后再将所有的#变成O,O变成X就可以了
for i in range(0, row):
for j in range(0, col):
if board[i][j] == 'O':board[i][j] = 'X'
if board[i][j] == '#':board[i][j] = 'O'
return board
#########################################695#####################################
def maxAreaOfIsland(grid):
'''
题意:求岛屿的数量
方法:BFS+遍历限定条件优化
:param grid:
:return:
'''
if not grid:
return 0
def bfs(grid, i, j):
###遍历过的节点一定要清零
grid[i][j] = 0
count = 1
###边界不需要判断
if i > 0 and grid[i - 1][j] == 1:
count += bfs(grid, i - 1, j)
if j > 0 and grid[i][j - 1] == 1:
count += bfs(grid, i, j - 1)
if i < len(grid) - 1 and grid[i + 1][j] == 1:
count += bfs(grid, i + 1, j)
if j < len(grid[0]) - 1 and grid[i][j + 1] == 1:
count += bfs(grid, i, j + 1)
return count
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
res = max(res,bfs(grid, i, j))
return res
if __name__ == '__main__':
# grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
# print(numIslands(grid))
# board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
# print(solve(board))
grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
print(maxAreaOfIsland(grid))<file_sep>def reOrderArray(array):
'''
O(1)的空间复杂度 若在开新数组需要O(n)的时间复杂度
'''
for i in range(len(array)):
key = array[i]
j = i - 1
while j >= 0:
if (array[j + 1] % 2 != 0) and (array[j] % 2 == 0):
array[j + 1] = array[j]
array[j] = key
j -= 1
return array
<file_sep>#####遍历不同的列表产生的算法复杂度和处理方法不同
def findContentChildren(g, s):
count = 0
g.sort()
s.sort()
for gi in g:
for i, si in enumerate(s):
if gi <= si:
del s[i]
count += 1
break
return count
def findContentChildren1(g, s):
count = 0
g.sort()
s.sort()
# 田忌赛马原则,用尺寸尽量少的饼干来先满足胃口小的孩子
for si in s:
if g[count] <= si:
count += 1
if count == len(g):
break
# 如果当前饼干尺寸不能满足当前小孩的胃口,则换用大一点的饼干尺寸来满足当前小孩
return count
if __name__ == '__main__':
g =[1,2]
s =[1,2,3]
print(findContentChildren(g,s))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def rightSideView(root):
'''
方法一:dfs递归
:param root:
:return:
'''
res = []
def dfs(root,res,deep):
if root:
if len(res) < deep:
res.append(root.val)
dfs(root.right, res, deep + 1)
dfs(root.left,res,deep+1)
dfs(root,res,1)
return res
def rightSideView1(root):
'''
方法二:层序遍历(bfs)非递归
:param root:
:return:
'''
res, lev = [], [root]
while root and lev:
res.append(lev[-1].val)
#(n.left, n.right)
lev = [k for n in lev for k in (n.left, n.right) if k]
return res
if __name__ == '__main__':
l = [1,2,3,8,5,9,4]
tree = operate_tree.Tree()
print(rightSideView(tree.creatTree(l)))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def sortedArrayToBST( nums):
if not nums:
return None
mid = len(nums) // 2
T = TreeNode(nums[mid])
T.left = sortedArrayToBST(nums[:mid])
T.right = sortedArrayToBST(nums[mid + 1:])
return T
def printtreemidorder(root):
def dfs(root,res):
if not root:
return
if root.left:
dfs(root.left,res)
res.append(root.val)
if root.right:
dfs(root.right,res)
res = []
dfs(root, res)
return res
if __name__ == '__main__':
l = [1,2,3,4,5]
root = sortedArrayToBST(l)
tree = operate_tree.Tree()
print(tree.levelOrder(root))<file_sep># n,x = map(int, input().split())
# pris = [int(c) for c in input().split()]
#
# # dp[i]满减为i元的情况下,最少的凑单价
# dp = [float('inf')] * (x + 1)
#
# for i in range(n):
# for j in range(x,-1,-1):
# if j > pris[i]:
# dp[j] = min(dp[j],dp[j-pris[i]]+pris[i])
# else:
# dp[j] = min(dp[j],pris[i])
# print(dp[x])
#############贪心##################
#不能全过
N, X = [int(c) for c in input().split()]
costs = [int(c) for c in input().split()]
costs.sort()
# 列表是全局变量
ans = [float('inf')]
maked = set()
index = set()
# 贪心 +DFS + 剪枝
def dfs(cur):
if cur >= X:
ans[0] = min(ans[0], cur)
return
maked.add(cur)
for i in range(N):
if i not in index and costs[i] + cur not in maked:
index.add(i)
dfs(cur + costs[i])
index.remove(i)
dfs(0)
print(ans[0])
<file_sep>n,m,k=map(int,input().split())
def findKthNumber(n, m, k):
'''
方法:二分搜索
思路:在m,n的乘法表中寻找不超过mid的个数,如果个数超过k则需减少右边的最大边界,反之则增大左边的边界
:param n:
:param m:
:param k:
:return:
'''
l = 1
r = n*m+1
while l < r:
mid = l + (r-l)//2
count = 0
# 把每一行不大于mid的数累加
for i in range(1,m+1):
count += min(mid//i, n)
# 二分搜索
if count >= k:
r = mid
else:
l = mid + 1
return l
print(findKthNumber(n, m, n*m-k+1))
<file_sep>n = int(input())
Ex = 0
for i in range(n):
xi,pi = map(int,input().split())
Ex += xi*pi/100
Ex = round(Ex,3)
print('%.3f' %Ex)<file_sep>
def strStr1(haystack, needle):
if not needle in haystack:
return -1
return haystack.index(needle)
def strStr2(haystack, needle):
return haystack.find(needle)
def strStr3(haystack, needle):
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i + len(needle)] == needle:
return i
return -1
if __name__ == '__main__':
a = "aaaaa"
b = "a"
print(strStr1(a,b))<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverse( head):
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev
def reverseKGroup(head, k):
# cur = head
# count = 0
# # cur指针遍历到下一个k个数组的原始头结点
# while cur and count != k:
# cur = cur.next
# count += 1
#
# if count == k:
# # 获取下一组反转后的头结点
# cur = reverseKGroup(cur,k)
# # 对k个链表组内的节点进行反转
# while count:
# tmp = head.next
# # 将下一组反转后的头结点接到该组head结点后
# head.next = cur
# cur = head
# head = tmp
# count -= 1
# head = cur
# return head
if not head or k < 2:
return
count = k
pre = None
cur = head
while count:
if cur:
# 进入一个节点cur
# 即将它放到pre位置(即数组最前面),pre存储的是逆序后的已读入的链表结点
cur.next,pre,cur = pre,cur,cur.next
count -= 1
if count == 0:
# 将下一组k个链表结点 反转 接到‘head’后面,这个head是每次迭代
head.next = reverseKGroup(cur,k)
else:
# 如果结点总数不是 k 的整数倍,最后剩余的节点保持原有顺序
head = reverse(pre)
return head
# pre存储本轮k个结点逆序后的链表输出
return pre
if __name__ == '__main__':
l = [1,2,3,4,5,6,7,8,9,10,11,12,13]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
k = 5
res = reverseKGroup(cur.next,k)
print('输出')
llist.outll(res)
<file_sep># 如果要对数组区间[p, r]的数据进行排序,我们先选择其中任意一个数据作为 pivot(分支点),一般为区间最后一个元素
# 然后遍历数组,将小于pivot的数据放到左边,将大于pivot的数据放到右边。接着,我们再递归对左右两边的数据进行排序,
# 直到区间缩小为1,说明所有的数据都排好了序。
#特点:每递归一次,即有一个元素被排在正确的位置上
def qsort(arr):
'''
递归方法
:param arr:
:return:
'''
if not len(arr):
return []
else:
# 在这里以第一个元素为基准线
pivot = arr[0]
left = qsort([x for x in arr[1:] if x < pivot])
right = qsort([x for x in arr[1:] if x >= pivot])
return left+[pivot]+right
def quicksort(list,left,right):
#
if left < right:
q = partition(list,left,right) #q 为分好区后,pivot的索引位置
quicksort(list,left,q-1)
quicksort(list,q+1,right)
def partition(arr,low,high):
'''
[low,high]为数组索引边界
partition函数作用:选中pivot,使得它左边的值比它小,右边的值比它大,这样,这个pivot就排在了它最后的位置上
:param arr:
:param low:
:param high:
:return:
'''
# 分支点选为数组最左边的点 ,这个可根据实际情况选择
pivot = arr[low]
while low < high:
while low < high and arr[high] >= pivot:
high -= 1
# 将小于pivot的数放到另一分区前面
arr[low] = arr[high]
while low < high and arr[low] <= pivot:
low += 1
# 将大于pivot的数放到另一分区前面
arr[high] = arr[low]
# low=high,此位置存pivot
arr[low] = pivot
return low #返回pivot的下标位置
def quick_sort(arr):
'''''
模拟栈操作实现非递归的快速排序
'''
if len(arr) < 2:
return arr
stack = []
stack.append(len(arr)-1)
stack.append(0)
while stack:
l = stack.pop()
r = stack.pop()
index = partition(arr, l, r)
if l < index - 1:
# 下一次循环调整数组中小于pivot的元素
stack.append(index - 1)
stack.append(l)
if r > index + 1:
# 下一次循环调整数组中大于pivot的元素
stack.append(r)
stack.append(index + 1)
if __name__ == '__main__':
l = [8, 3, 2, 4, 5, 6, 7, 90, 21, 23, 8]
# l=qsort(l)
# quick_sort(l)
quicksort(l,0,len(l)-1)
print(l)
<file_sep>def schedule(R,O,n,m):
def sort_val(R,O):
for i in range(n):
for j in range(i+1,n):
if R[j] - O[j] > R[i] - O[i]:
R[i],R[j] = R[j],R[i]
O[i], O[j] = O[j], O[i]
sort_val(R,O)
remain = m
for i in range(n):
if remain < R[i]:
return False
else:
remain -= O[i]
return True
if __name__ == '__main__':
R = [10,15,23,20,6,9,7,16,50]
O = [2,7,8,4,5,8,6,8,10]
m = 50
n = 9
print(schedule(R,O,n,m))
<file_sep>n,m = map(int,input().split())
nums = [int(c) for c in input().split()]
# n,m = 7,2
# nums = [ 4, 3, 3, 3, 1, 5, 5 ]
from collections import Counter
dic = Counter(nums)
res = []
i = 0
while i < len(nums):
times = nums[i]
if dic[nums[i]] > m:
i += dic[nums[i]]
else:
res += [nums[i]]*dic[nums[i]]
i += dic[nums[i]]
print(' '.join(str(c) for c in res))<file_sep>num = list(input().split(','))
nums1 = num[:-1] + [num[-1].split(';')[0]]
n = int(num[-1].split(';')[1])
nums_ou = []
nums_ji = []
for c in nums1:
if int(c) % 2 == 0:
nums_ou.append(int(c))
else:
nums_ji.append(int(c))
nums_ou.sort(reverse=True)
nums_ji.sort(reverse=True)
res = nums_ou + nums_ji
print(','.join([str(c) for c in res[:n]]))
<file_sep>def isValid(s):
dic = {')': '(', '}': '{', ']': '['}
stack = []
for i in s:
if i in dic:
element = stack.pop() if stack else '#'
if element != dic[i]:
return False
else:
stack.append(i)
return True if not stack else False
################最长的有效括号#################32
def longestValidParentheses( s):
if not s:
return 0
res = 0
stack = [-1]
for i in range(len(s)):
if s[i] == "(":
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
res = max(res, i - stack[-1])
return res
if __name__ == '__main__':
s = ')()())'
print(longestValidParentheses(s))
<file_sep>def Find(target, array):
# write cod
m = len(array)
n = len(array[0])
i = m - 1
j = 0
while i >= 0 and j < n:
if array[i][j] == target:
return True
elif array[i][j] < target:
j += 1
else:
i -= 1
return False
if __name__ == '__main__':
target = 10
mat = [[1,3,5],[6,9,10],[12,15,16]]
print(Find(target,mat))<file_sep>n,m = map(int,input().split())
graph = []
for i in range(n):
graph.append(list(input()))
# visited记录像素格上色次数
visited = [[0] * m for _ in range(n)]
def colorY(i,j,visited,graph):
# 往右下搜索
while i < n and j < m:
if graph[i][j] == 'G' or graph[i][j] == 'Y':
# 当像素格被'\'操作涂过后,对应visited记为1
visited[i][j] += 1
i += 1
j += 1
else:
# 当前这一笔操作结束
break
def colorB(i,j,visited,graph):
# 往左下搜索
while i < n and j >= 0:
if graph[i][j] == 'G' or graph[i][j] == 'B':
# 当像素格被'/'操作涂过后,对应visited记为2
visited[i][j] += 2
i += 1
j -= 1
else:
break
def main():
res = 0
for i in range(n):
for j in range(m):
if graph[i][j] == 'Y' and visited[i][j] == 0:
# colorY代表当前操作的一笔'\'
colorY(i, j, visited, graph)
res += 1
if graph[i][j] == 'B' and visited[i][j] == 0:
# colorB代表当前操作的一笔'/'
colorB(i, j, visited, graph)
res += 1
# 像素格原本为Green时,需要的执行的操作
if graph[i][j] == 'G' and visited[i][j] == 0:
colorY(i, j, visited, graph)
colorB(i, j, visited, graph)
res += 2
if graph[i][j] == 'G' and visited[i][j] == 1:
# 之前已经用colorY操作过
colorB(i, j, visited, graph)
res += 1
if graph[i][j] == 'G' and visited[i][j] == 2:
# 之前已经用colorB操作过
colorY(i, j, visited, graph)
res += 1
print(res)
if __name__ == '__main__':
main()<file_sep>def myAtoi( str):
number = '0123456789'
sign = '+-'
str = str.strip()
if len(str) > 1:
if str[0] not in sign and str[0] not in number:
return 0
try:
integer = int(str)
if integer < -2**31:
return -2**31
if integer > 2**31-1:
return 2**31 - 1
return integer
except ValueError:
string = str[0]
i = 1
while i < len(str):
if str[i] in number:
string += str[i]
i += 1
else:
break
try:
if int(string) < -2**31:
return -2**31
if int(string) > 2**31-1:
return 2**31 - 1
return int(string)
except ValueError:
return 0
elif str == '' or str not in number:
return 0
else:
return int(str)
if __name__ == '__main__':
print(myAtoi(' -42'))
<file_sep>class pair():
def __init__(self,a=None,b=None):
self.a = a
self.b = b
def findpais(arr):
dic = dict()
n = len(arr)
res = []
for i in range(n):
for j in range(i+1,n):
summ = arr[i] + arr[j]
if summ not in dic:
dic[summ] = pair(arr[i],arr[j])
else:
res.append([(dic[summ].a,dic[summ].b),(arr[i],arr[j])])
return res
if __name__ == '__main__':
arr = [3,4,7,10,20,9,8]
print(findpais(arr))<file_sep>s = input()
nums = [int(x) for x in s.split()]
# nums = [1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 7, 7, 9]
dic = {1:4,2:4,3:4,4:4,5:4,6:4,7:4,8:4,9:4}
def isHu(nums):
"""
判断是否可以胡牌
思路:从最小的数字开始尝试,如果把其当成雀头成员,该数字划掉两个,并看余下的数字能否划空
如果是刻子成员,该数字划掉三个,并查看余下数字能否划空
如果是顺子成员,划掉该值 a ,a+1,a+2,并查看余下数字能否划空
如果上述三种尝试都无法划空数组,说明存在数字无法是 雀头、刻子、顺子的成员, 即无法胡牌。
(上述任何一种情况能划空数组,都可以胡牌)
:param nums:
:return:
"""
if not nums:
return True
n = len(nums)
count0 = nums.count(nums[0])
# 这里为什么用n%3来检验的原因是,并不是每次雀头都是最开始尝试的首尾数字,如果雀头出现在数组后面,则需根据数组长度来判断是否有确定雀头
if n % 3 != 0 and count0 >= 2 and isHu(nums[2:]) == True:
return True
if count0 >= 3 and isHu(nums[3:]) == True:
return True
if nums[0] + 1 in nums and nums[0] + 2 in nums:
last_nums = nums.copy()
last_nums.remove(nums[0])
last_nums.remove(nums[0] + 1)
last_nums.remove(nums[0] + 2)
if isHu(last_nums) == True:
return True
# 以上条件都不满足,则不能和牌
return False
def main(nums):
res = []
for i in nums:
dic[i] -= 1
# 遍历尝试加入每种数字,判断是否能和牌
for last in range(1,10):
if dic[last] > 0:
total_pai = nums+[last]
else:
continue
total_pai.sort()
if isHu(total_pai):
res.append(last)
res.sort()
return ' '.join(str(c) for c in res) if res else '0'
if __name__ == '__main__':
print(main(nums))
<file_sep>def t1(nums,l,r):
def partion(nums,l,r):
pivot = nums[l]
while l < r:
while l < r and nums[r] >= pivot:
r -= 1
nums[l] = nums[r]
while l < r and nums[l] <= pivot:
l += 1
nums[r] = nums[l]
nums[l] = pivot
return l
if l < r:
mid = partion(nums,l,r)
t1(nums,l,mid-1)
t1(nums,mid+1,r)
nums = [4,3,25,4]
t1(nums,0,len(nums)-1)
print(nums)
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList1(head):
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev
def reverseList(head):
pre = reverse_head = None
while head:
nextNode = head.next
if not nextNode:reverse_head = head
head.next = pre
pre = head
head = nextNode
return reverse_head
def reorderList(head):
'''
思路:1.找到中点
2.逆转后半部分
3.拼接前半部分和逆转过的后半部分
:param head:
:return:
'''
if not head or not head.next:
return None
fast,slow = head,head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
rev = slow.next # 数组长度为奇数 中间的数一般放最后
slow.next = None # 为了使前半部分 被切分出来
rev = reverseList1(rev) #将数组后半部分反转
first = head #前半部分
second = rev #后半部分 #链表长为奇数,first比second长度大1,偶数则相等
# 里面的节点交换顺序要理清
while first and second:
tmp1 = first.next
tmp2 = second.next
first.next = second
second.next = tmp1
first,second = tmp1,tmp2
return head
if __name__ == '__main__':
l = [1,2,3,4,5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
res = reorderList(cur.next)
print('输出')
llist.outll(res)
<file_sep>
def summ(nums,flag):
res = []
cur = 0
square = 0
if flag:
for i in range(len(nums)):
cur += nums[i]
square += nums[i] * nums[i]
# E[x^2] - E[x]^2
res.append(square/(i+1) - (cur/(i+1))**2)
else:
for i in range(len(nums)-1,-1,-1):
cur += nums[i]
square += nums[i] * nums[i]
# E[x^2] - E[x]^2
res.append(square/(i+1) - (cur/(i+1))**2)
return res
nums = [int(c) for c in input().split()]
# 从左到右做一遍方差,再从右到左求一遍方差,然后就可以求了。
left = summ(nums,True)
right = summ(nums,False)
n = len(nums)
k = 0
minn = float('inf')
for i in range(1,n):
if left[i-1] + right[n - i - 1] < minn:
minn = left[i-1] + right[n - i - 1]
k = i - 1
print(k)<file_sep>def convertToBase7(num: int) -> str:
res = []
# 十进制转k进制处理方法
if num > 0:
while num:
res.append(num % 7)
num //= 7
res = res[::-1]
return ''.join(str(c) for c in res)
elif num < 0:
num = abs(num)
while num :
res.append(num % 7)
num //= 7
res = res[::-1]
return '-' + ''.join(str(c) for c in res)
else:
return '0'
print(convertToBase7(-7))<file_sep>'''
动态规划,由于设定的最优子状态不能保证找到的当前层路径最优后续的路径也是最优的,状态变量设定错误
只AC0.2
(接下来往lintcode 515 Paint House那道题上想,每当该层出现0,要维护两种不同状态的分叉的最优)
'''
# n = int(input())
# grid = []
# for i in range(n):
# grid.append([int(c) for c in input().split()])
n = 6
grid = [[1,2,3],[8,9,10],[5,0,5],[-9,-8,-10],[0,1,2],[5,4,6]]
class node:
def __init__(self,val,flag):
self.val = val
self.flag = flag
dp = [[node(0,1)]*3 for _ in range(n+1)]
# for j in range(3):
# dp[0][j].append([0,1])
for i in range(1,n+1):
zuo = dp[i - 1][0].val + dp[i - 1][0].flag*grid[i-1][0]
you = dp[i - 1][1].val + dp[i - 1][1].flag*grid[i-1][0]
if zuo > you:
val = zuo
if grid[i-1][0] == 0:
flag = -1 * dp[i - 1][0].flag
else:
flag = dp[i - 1][0].flag
dp[i][0] = node(val,flag)
else:
val = you
if grid[i-1][0] == 0:
flag = -1 * dp[i - 1][1].flag
else:
flag = dp[i - 1][1].flag
dp[i][0] = node(val, flag)
zuo = dp[i - 1][0].val + dp[i - 1][0].flag*grid[i-1][1]
zhong = dp[i - 1][1].val + dp[i - 1][1].flag*grid[i-1][1]
you = dp[i - 1][2].val + dp[i - 1][2].flag*grid[i-1][1]
if zuo > zhong and zuo > you:
val = zuo
if grid[i-1][1] == 0:
flag = -1 * dp[i - 1][0].flag
else:
flag = dp[i - 1][0].flag
dp[i][1] = node(val,flag)
elif zhong > zuo and zhong > you:
val = zhong
if grid[i-1][1] == 0:
flag = -1 * dp[i - 1][1].flag
else:
flag = dp[i - 1][1].flag
dp[i][1] = node(val, flag)
else:
val = you
if grid[i-1][1] == 0:
flag = -1 * dp[i - 1][2].flag
else:
flag = dp[i - 1][1].flag
dp[i][1] = node(val, flag)
zuo = dp[i - 1][1].val + dp[i - 1][1].flag * grid[i-1][2]
you = dp[i - 1][2].val + dp[i - 1][2].flag * grid[i-1][2]
if zuo > you:
val = zuo
if grid[i-1][2] == 0:
flag = -1 * dp[i - 1][1].flag
else:
flag = dp[i - 1][1].flag
dp[i][2] = node(val, flag)
else:
val = you
if grid[i-1][2] == 0:
flag = -1 * dp[i - 1][2].flag
else:
flag = dp[i - 1][2].flag
dp[i][2] = node(val, flag)
a = 1
maxx = max(dp[n][0].val,dp[n][1].val,dp[n][2].val)
print(maxx)
# dp[i][2][0] = max(dp[i - 1][1][0], dp[i - 1][2][0]) + grid[i][2]<file_sep>def selectsort(list):
for i in range(len(list)-1):
min = i
for j in range(i+1,len(list)):
if list[j] < list[min]:
min = j
if i != min:
list[i],list[min] = list[min],list[i]
return list
if __name__ == '__main__':
l = [1, 3, 2, 4, 5, 6, 7, 90, 21, 23, 45]
print(selectsort(l))
<file_sep>from Linked_list import linkedlist_operate
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def removeNthFromEnd(head, n):
dum = LNode(None)
# dum初始化技巧
dum.next = head
count = 0
while head:
count += 1
head = head.next
# 这里:新head定位在原head之前,因为一般在(删除点的pre)做操作
first = dum
# 处理删除倒数数,定位尾端边界 不要在循环中处理,易忽略边界问题
m = count - n
while m > 0:
first = first.next
m -= 1
first.next = first.next.next
return dum.next
def removeNthFromEnd1(head, n):
'''
思路:定义两个相同的链表slow、fast,先让快指针先走n步,
随后,slow、fast指针同时向后遍历直到fast指针到达链表尾部
此时slow指向的是倒数第n+1个节点,将其next接到倒数第n-1个节点即可
:param head:
:param n:
:return:
'''
slow,fast = head,head
for i in range(n):
# 若n超出链表的长度,则删除第一个节点
if fast.next == None:
return head.next
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
if __name__ == '__main__':
l1 = [2,4,3,4,5,6]
n = 3
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
res = removeNthFromEnd1(cur1.next, n)
print('输出')
llist.outll(res)<file_sep>
grid = input()
ee = []
tmp = []
count = 0
hang = 0
for i in grid:
if i == '0' or i == '1':
count+= 1
tmp.append(int(i))
if i == ']' and len(tmp) != 0:
ee.append(tmp)
tmp = []
lie = count
count = 0
print(ee)
# ee = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
graph = []
for i in range(len(ee)):
for j in range(len(ee[0])):
if ee[i][j] == 1:
graph.append([i,j])
n = lie
def canFinish(numCourses, prerequisites):
# 课程的长度
clen = len(prerequisites)
if clen == 0:
# 没有课程,当然可以完成课程的学习
return True
# 入度数组,一开始全部为 0
in_degrees = [0 for _ in range(numCourses)]
# 邻接表
adj = [set() for _ in range(numCourses)]
# 想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
# [0,1] 表示1在先,0在后
# 注意:邻接表存放的是后继successor结点的集合
for second, first in prerequisites:
in_degrees[second] += 1
adj[first].add(second)
queue = []
# 首先遍历一遍,把所有入度为 0 的结点加入queue
for i in range(numCourses):
if in_degrees[i] == 0:
queue.append(i)
# counter记录能完成的课程数
counter = 0
while queue:
top = queue.pop(0)
counter += 1
for successor in adj[top]:
in_degrees[successor] -= 1
if in_degrees[successor] == 0:
queue.append(successor)
return counter == numCourses
if canFinish(n, graph):
print('0')
else:
print('1')
# ee = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
# vv = [[0, 0, 0, 1, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0]]
<file_sep>def numDecodings(s):
'''
序列型动态规划
:param s:
:return:
'''
nums = list(s)
n = len(s)
if n == 0:
return 0
# dp[i]表示(s[0:i-1)个字符的解码方法
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
t = ord(nums[i - 1]) - ord('0')
# 判断一位字符串解码方式
if (t >= 1 and t <= 9):
dp[i] += dp[i - 1]
# 判断两位的字符串解码方式
if i >= 2:
t = (ord(nums[i - 2]) - ord('0')) * 10 + (ord(nums[i - 1]) - ord('0'))
if t >= 10 and t <= 26:
dp[i] += dp[i - 2]
return dp[n]
#################################639#######################################
def numDecodings1(s):
'''
序列型动态规划
:param s:
:return:
'''
nums = list(s)
n = len(s)
if n == 0:
return 0
dp = [0] * (n + 1)
dp[0] = 1
mod = 1000000007
for i in range(1, n + 1):
if s[i - 1] == '*':
dp[i] = (dp[i] + 9 * dp[i - 1]) % mod
if i >= 2:
if s[i - 2] == '*':
dp[i] = (dp[i] + 15 * dp[i - 2]) % mod
elif s[i - 2] == '1':
dp[i] = (dp[i] + 9 * dp[i - 2]) % mod
elif s[i - 2] == '2':
dp[i] = (dp[i] + 6 * dp[i - 2]) % mod
else:
if s[i - 1] >= '1' and s[i - 1] <= '9':
dp[i] = (dp[i] + dp[i - 1]) % mod
if i >= 2:
if s[i - 2] == '*':
if s[i - 1] >= '0' and s[i - 1] <= '6':
dp[i] = (dp[i] + 2 * dp[i - 2]) % mod
elif s[i - 1] >= '7' and s[i - 1] <= '9':
dp[i] = (dp[i] + dp[i - 2]) % mod
else:
twoDigits = int(s[i - 2: i])
if twoDigits >= 10 and twoDigits <= 26:
dp[i] = (dp[i] + dp[i - 2]) % mod
return dp[n]
if __name__ == '__main__':
s = "*1*1*0"
print(numDecodings1(s))
<file_sep>#链接:https://leetcode.com/problems/longest-consecutive-sequence/
#连续子序列 3,4,5,6,7,7,8,9 则其连续子序列为 3,4,5,6,7,8,9,
def longestConsecutive(nums): #方法1 O(nlogn) 先排序,
if not nums:
return 0
nums.sort()
longest_streak = 1
current_streak = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
if nums[i] == nums[i - 1] + 1:
current_streak += 1
else: #序列中断
longest_streak = max(longest_streak, current_streak)
current_streak = 1
return max(longest_streak, current_streak)
def longestConsecutive2(nums): #方法2 O(n)
dic = {}
max_length = 0
for num in nums:
if num not in dic: #找其左右邻居已经找到的连续子序列数值
left = dic.get(num - 1, 0) #如果不存在,则返回0
right = dic.get(num + 1, 0)
cur_length = 1 + left + right
if cur_length > max_length:
max_length = cur_length
dic[num] = cur_length
dic[num - left] = cur_length
dic[num + right] = cur_length
return max_length
if __name__ == '__main__':
nums = [9,1,4,7,7,3,-1,0,5,8,-1,6]
print(longestConsecutive2(nums))
<file_sep>
def canConstruct(ransomNote, magazine):
if len(ransomNote) > len(magazine):
return False
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True
if __name__ == '__main__':
ransomNote,magazine= "aa","aab"
print(canConstruct(ransomNote, magazine))<file_sep>def findKthNumber(n, k):
'''
思路:对于10叉树,需要知道n的大小方能确定树的深度,依此来求得k排序
:param n:字典中最大的节点
:param k:
:return:
'''
res = 1
k -= 1
while k > 0:
gap = 0
interval = [res,res+1]
# 计算res与res+1之间的数字个数gap
# 注意:1和2之间隔了多少个数需要根据n的大小确定树的深度来确定,如果n = 99, 那么1与2之间隔了11个数 n=999,1和2之间隔了111
# 个数,
while interval[0] <= n:
gap += (min(n+1,interval[1]) - interval[0])
interval = [10*interval[0],10*interval[1]]
# 如果相隔的距离小于k,那么我们可以将搜索范围【0——k】缩小到【gap——k】,下一轮迭代则是【gap_old+gap_new——k】
if gap <= k:
res += 1
k -= gap
# 如果相隔的距离大于k,那么说明超出了搜索范围,因此仅将范围缩小1,res*=10,相当于在当前res节点上跳到10叉树下一个同位置
# 子节点,排序位置仅变动1,之后,其得到的gap则会小一个数量级,例如之前gap=111,超过了k的范围,往子节点跳了一格后,
# 下一次得到的gap=11
else:
res *= 10
k -= 1
return res
if __name__ == '__main__':
n = 999
k = 100
print(findKthNumber(n, k))
<file_sep>def Sum_Solution(n):
'''
短路原理 & 若第一项为0就不会判断后面一项
:param n:
:return:
'''
# write code here
res = n
res = res & (res + Sum_Solution(n - 1))
return res
print(Sum_Solution(3))<file_sep>
def rotatesame(str1,str2):
def issub(str1,str2):
return str1.find(str2) != -1
len1 = len(str1)
len2 = len(str2)
if len1 != len2:
return False
tmp = [None] * (len1*2)
for i in range(len1):
tmp[i] = str1[i]
tmp[i+len1] = str1[i]
return issub(''.join(tmp),str2)
if __name__ == '__main__':
str1 = 'waterbottle'
str2 = 'erbottlewat'
print(rotatesame(str1,str2))
<file_sep>import time, functools
def display_time(fun):
functools.wraps(fun)
def wrapper(*args, **kw):
startTime = time.time()
tmp = fun(*args, **kw)
endTime = time.time()
print('%s executed : %s s' % (fun.__name__, float(endTime - startTime )))
return tmp
return wrapper
class Trie:
'''
字典树知识:
Trie 树最大优点:利用字符串的公共前缀来减少存储空间与查询时间,从而最大限度地减少无谓的字符串比较
与哈希表的比较:随着哈希表大小增加,会出现大量的冲突,时间复杂度可能增加到 O(n),其中 n 是插入的键的数量。
与哈希表相比,Trie 树在存储多个具有相同前缀的键时可以使用较少的空间。此时 Trie 树只需要 O(m) 的时间复杂度,
其中 m 为键长。而在平衡树中查找键值需要 O(mlogn) 时间复杂度。
'''
# 前缀树初始化
def __init__(self):
# 初始化字典树的根节点为空
self.root={}
self.end_char = '#'
#插入
def insert(self,word):
node = self.root
for char in word:
# 递归建立字典
node= node.setdefault(char,{})
node[self.end_char] = self.end_char
# 搜索
def search(self,word):
node = self.root
for char in word:
if char not in node:
return False
# 转移到其它节点搜索
node = node[char]
return self.end_char in node
# 查找满足前缀为word的字符串
def startsWith(self,prefix):
node = self.root
for char in prefix:
if char not in node:
return False
# 如果当前节点不能满足
node = node[char]
return True
if __name__ == '__main__':
trie = Trie()
trie.insert('apple')
print(trie.search('apple'))
print(trie.search("app"))
print(trie.startsWith("app"))
trie.insert("app")
print(trie.search("app"))
<file_sep>def Capitalorder(ch):
'''
:param ch:
:return:
'''
first = 0
last = len(ch)-1
while first < last:
if 'a' <= ch[first] <= 'z' and first < last:
first += 1
if 'A' <= ch[last] <= 'Z' and first < last:
last -= 1
ch[first],ch[last] = ch[last],ch[first]
a = ch[:first]
b = ch[first:]
a.sort()
b.sort()
a.extend(b)
return a
if __name__ == '__main__':
ch = list('AbcDef')
print(Capitalorder(ch))<file_sep>def hammingWeight(n):
"""
:type n: int
:rtype: int
"""
er = n
count = 0
while er:
if er % 2 == 1:
count += 1
er = er >> 1
return count
if __name__ == '__main__':
n = 0b00000000000000000000000000001011
print(hammingWeight(n))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.flag = -1
def Serialize(self, root):
# write code here
if not root:
return '#,'
return str(root.val) + ',' + self.Serialize(root.left) + self.Serialize(root.right)
def Deserialize(self, s):
# write code here
self.flag += 1
l = s.split(',')
if self.flag >= len(s):
return None
root = None
if l[self.flag] != '#':
root = TreeNode(int(l[self.flag]))
root.left = self.Deserialize(s)
root.right = self.Deserialize(s)
return root
if __name__ == '__main__':
l = [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, 5, 1]
tree = operate_tree.Tree()
root = tree.creatTree(l)
test = Solution()
s = test.Serialize(root)
res = test.Deserialize(s)
a = 1<file_sep>class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
# write code here
res = []
def dfs(root,k,res):
if not root:
return
dfs(root.left,k,res)
# res数组长度小于k说明还没有找满前k个数
if len(res) < k:
res.append(root)
else:
return
dfs(root.right,k,res)
if k == 0:
return None
else:
dfs(pRoot,k,res)
if len(res) < k:
return None
return res[-1]
<file_sep>
def isPalindrome(s):
s = s.lower()
s = list(filter(str.isalnum, s))
return s == s[::-1]
######################680##########################
def isPalindrome2(s): #######该方法超时,当原字符不是回文数时,没必要对遍历对每个字符都执行删除判断是否是回文数
if s == s[::-1]:
return True
for i in range(len(s)):
r = s[:i] + s[i+1:]
if r == r[::-1]:
return True
return False
def isPalindrome3(s):
r = s[::-1]
if s == r:
return True
for i in range(len(s)): ###在字符串中,只要判断第一次出现正逆序不同的字符,删除正序的该位置字符和逆序的该位置字符,若还不相等,说明不止需要删除一个数
if s[i] != r[i]:
m = s[:i] + s[i+1:]
n = r[:i] + r[i+1:]
return m == m[::-1] or n == n[::-1]
if __name__ == '__main__':
s = "0P"
# print(isPalindrome(s))
s = "<KEY>"
print(isPalindrome3(s))<file_sep>
def search(nums, target):
try:
ind = nums.index(target) #内置函数
except:
ind = -1
return ind
def search1(nums, target):
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) >> 1
if target == nums[mid]:
return mid
if nums[low] <= nums[mid]: # 二分后前半段是升序
if nums[low] <= target <= nums[mid]: # 目标在前半段
high = mid - 1
else:
low = mid + 1
else: # 二分后前半段不是升序
if nums[mid] <= target <= nums[high]: # 目标在后半段
low = mid + 1
else:
high = mid - 1
return -1
if __name__ == '__main__':
nums = [4, 5, 6, 7, 0, 1, 2]
target = 0
print(search1(nums, target))<file_sep># 固定左端left(即确定该位置放入特工C(1, 1))),记忆当前左端所能到达最大的右端坐标right,从后续可用数中选两个
# 即组合数为C(right - left, 2)
n,d = 4,3
nums = [1,2,3,4]
mod = 99997867
i = 0
res = 0
pos = 2
while i < len(nums)-2:
if nums[pos] - nums[i] > d:
i += 1
continue
while pos+1 <= len(nums)-1 and nums[pos+1] - nums[i] <= d:
pos += 1
res += (pos - i)*(pos - i -1)//2
i += 1
print(res%mod)
<file_sep>class jumpfl():
def jumpFloor(self,number): #跳台阶问题,一次可以跳1,2中的数
# write code here
dp = [0] * number
if number <= 1:
dp[0] = 1
else:
dp[0] = 1 #斐波那契数列法
dp[1] = 2
for i in range(2, len(dp)):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[len(dp) - 1]
def jumpFloor1(self,number): #跳台阶问题,一次可以跳1,2中的数
# write code here
dp = [0] * number
if number <= 1:
dp[0] = 1
else:
dp[0] = 1 #斐波那契数列法
dp[1] = 2
dp[2] = 4
for i in range(3, len(dp)):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
return dp[number-1]
def jumpFloorII(self,number): #变态跳台阶问题,一次可以跳1,2,...,n中的任意的数
# n = number
# n = 1, f(1) = 1
# n = 2, f(2) = f(2-1) + f(2-2) 第一步跳了一个台阶后面还能有多少种跳法 + 第二步跳了二个台阶后面还能有多少种跳法
# ...
# f(n-1) = f(n-2) + f(n-2) + ... + f(0)
# f(n) = f(n-1) + f(n-2) + ... + f(0) = 2 * f(n-1)
# 数学归纳法的思想推导求得迭代公式 f(n) = 2 * f(n-1)
if number == 1:
return 1
else:
return 2 * self.jumpFloorII(number - 1)
if __name__ == '__main__':
setl = jumpfl()
# print(setl.jumpFloor(569))
# print(setl.jumpFloorII(569))
print(setl.jumpFloor1(16))
<file_sep>import bisect
def searchRange(nums, target):
try:
ind = nums.index(target)
count = nums.count(target)
return [ind,ind+count-1]
except:
return [-1,-1]
def searchRange1(nums, target):
first, last = 0, len(nums)
while first < last:
mid = first + (last - first) // 2
if nums[mid] < target:
first = mid + 1
else:
last = mid
ind = first
if ind >= len(nums):
return [-1, -1]
if nums[ind] != target:
return [-1, -1]
end = ind
for i in range(ind + 1, len(nums)):
if nums[i] == target:
end += 1
else:
break
return [ind,end]
def searchRange2(nums, target):
ind = bisect.bisect_left(nums,target) #返回将x插入到列表a中的索引位置,如果已有x,则返回第一个x的位置
if ind >= len(nums):
return [-1, -1]
if nums[ind] != target:
return [-1, -1]
end = bisect.bisect_right(nums, target) - 1 #返回将x插入到列表a中的索引位置,如果已有x,则返回最后一个x位置的下一个位置
return [ind,end]
if __name__ == '__main__':
nums = [1]
target = 2
print(searchRange2(nums, target))<file_sep>from heapq import *
class Solution:
def __init__(self):
self.low = []
self.high = []
def Insert(self, num):
# write code here
heappush(self.high, -heappushpop(self.low, -num))
if len(self.low) < len(self.high):
heappush(self.low, -heappop(self.high))
def GetMedian(self, n=None):
# write code here
return float(-self.low[0]) if len(self.low) > len(self.high) else (-self.low[0] + self.high[0]) / 2.0<file_sep>class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
'''
dfs bfs 迭代
'''
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return None
dummy = pHead
# 在链表每个结点后复制结点
while dummy:
dummynext = dummy.next
copynode = RandomListNode(dummy.label)
copynode.next = dummynext
dummy.next = copynode
dummy = dummynext
dummy = pHead
# 将复制链表的random指针指向原链表节点random指针指向的下一个节点
# second step, random' to random'
while dummy:
dummyrandom = dummy.random
copynode = dummy.next
if dummyrandom:
copynode.random = dummyrandom.next
dummy = copynode.next
# 分离复制的链表与原链表
# third step, split linked list
dummy = pHead
copyHead = pHead.next
while dummy:
copyNode = dummy.next
dummy.next = copyNode.next
if copyNode.next:
copyNode.next = copyNode.next.next
else:
copyNode.next = None
dummy = dummy.next
return copyHead<file_sep># def main(l,r):
# sub = list(seq[l:r + 1])
# i = 0
# score = 0
# stack = []
# flag = ''
# while 0 <= i < len(sub):
# if flag == "" and sub[i] not in "<>":
# score += int(sub[i])
# sub[i] = str(int(sub[i]) - 1)
# stack.append(int(sub[i]))
# i += 1
# elif flag == "" and sub[i] == "<":
# score += sum(stack)
# return score
# elif flag == '' and sub[i] == ">":
# flag += sub[i]
# idx = i
# i += 1
# stack = []
# elif flag == ">" and sub[i] not in "<>":
# stack.append(int(sub[i]))
# sub[i] = str(int(sub[i]) - 1)
# i += 1
# if i == len(sub):
# score += sum(stack)
# return score
# elif flag == ">" and sub[i] == ">":
# score += sum(stack)
# stack = []
# idx = i
# i += 1
# elif flag == ">" and sub[i] == "<":
# maxx = max(stack)
# for j in stack:
# tmp = ((1 + j) * j) // 2
# score += tmp
# if maxx % 2 == 0:
# sub = sub[:idx + 1] + sub[i + 1:]
# i = idx + 1
# flag = ">"
# else:
# sub = sub[:idx] + sub[i:]
# i = idx - 1
# flag = "<"
# stack = []
# elif flag == "<" and sub[i] not in "<>":
# stack.append(int(sub[i]))
# sub[i] = str(int(sub[i]) - 1)
# i -= 1
# if i == -1:
# score += sum(stack)
# return score
# elif flag == "<" and sub[i] == "<":
# score += sum(stack)
# stack = []
# i -= 1
# elif flag == "<" and sub[i] == ">":
# maxx = max(stack)
# for j in stack:
# tmp = ((1 + j) * j) // 2
# score += tmp
# if maxx % 2 != 0:
# sub = sub[:i + 1] + sub[idx + 1:]
# i += 1
# flag = ">"
# else:
# sub = sub[:i] + sub[idx:]
# i -= 1
# flag = "<"
# stack = []
# return score
# if __name__ == '__main__':
# # n,m,q = map(int,input().split())
# n, m, q = 4,10,6
# # seq = [c for c in input().split()]
# seq = ">22<"
# lr = [[1,4],[1,3],[2,4],[2,3],[1,1],[2,2]]
# for a in lr:
# # a,b = map(int,input().split())
# l = a[0] - 1
# r = a[1] - 1
# if seq[l] == "<":
# print(0)
# elif l == r:
# if seq[l] not in "<>":
# print(seq[l])
# else:
# print(0)
# else:
# print(main(l,r))
def main(l,r):
sub = list(seq[l:r + 1])
i = 0
score = 0
stack = []
flag = ''
while 0 <= i < len(sub):
####### 还未有标志位的处理
if flag == "" and sub[i] not in "<>":
score += int(sub[i])
sub[i] = str(int(sub[i]) - 1)
stack.append(int(sub[i]))
i += 1
elif flag == "" and sub[i] == "<":
score += sum(stack)
return score
elif flag == '' and sub[i] == ">":
flag += sub[i]
idx = i
i += 1
stack = []
########## 标志位为">"
elif flag == ">" and sub[i] not in "<>":
stack.append(int(sub[i]))
sub[i] = str(int(sub[i]) - 1)
i += 1
if i == len(sub):
score += sum(stack)
return score
elif flag == ">" and sub[i] == ">":
score += sum(stack)
stack = []
idx = i
i += 1
elif flag == ">" and sub[i] == "<":
# 根据stack里最大的数值来判断删除">"还是"<"
maxx = max(stack)
for j in stack:
tmp = ((1 + j) * j) // 2
score += tmp
if maxx % 2 == 0:
sub = sub[:idx + 1] + sub[i + 1:]
i = idx + 1
flag = ">"
else:
sub = sub[:idx] + sub[i:]
i = idx - 1
flag = "<"
stack = []
########### 标志位为"<"
elif flag == "<" and sub[i] not in "<>":
stack.append(int(sub[i]))
sub[i] = str(int(sub[i]) - 1)
i -= 1
if i == -1:
score += sum(stack)
return score
elif flag == "<" and sub[i] == "<":
score += sum(stack)
stack = []
i -= 1
elif flag == "<" and sub[i] == ">":
# 根据stack里最大的数值来判断删除">"还是"<"
maxx = max(stack)
for j in stack:
tmp = ((1 + j) * j) // 2
score += tmp
if maxx % 2 != 0:
sub = sub[:i + 1] + sub[idx + 1:]
i += 1
flag = ">"
else:
sub = sub[:i] + sub[idx:]
i -= 1
flag = "<"
stack = []
return score
if __name__ == '__main__':
n,m,q = map(int,input().split())
seq = [c for c in input().split()]
for _ in range(q):
a,b = map(int,input().split())
l = a - 1
r = b - 1
if seq[l] == "<":
print(0)
elif l == r:
if seq[l] not in "<>":
print(seq[l])
else:
print(0)
else:
print(main(l,r))
<file_sep>def minHeightShelves(books, shelf_width):
'''
动态规划
思路:每放入一本书,将其放入新起的一层,随后不断将之前已经摆好的书往新起的一层后移,在保证新起的一层不超过最大宽度的前提下,
递推得到最小的书架整体高度
:param books:
:param shelf_width:
:return:
'''
n = len(books)
# dp[i]表示第i本书放入书架的整体最小高度
dp = [float('inf')] * (n+1)
dp[0] = 0
for i in range(1,n+1):
# tmp_width 当前新层宽度,j为第i本书及其之前已经摆放的书
tmp_width,j,h = 0,i,0
while j > 0 :
tmp_width += books[j-1][0]
if tmp_width > shelf_width:
break
# 本层最大高度的书作为本层高度
h = max(h, books[j-1][1])
dp[i] = min(dp[i],dp[j-1]+h)
j -= 1
return dp[-1]
if __name__ == '__main__':
books = [[1, 1], [2, 3], [2, 3], [1, 1], [1, 1], [1, 1], [1, 2]]
shelf_width = 4
print(minHeightShelves(books,shelf_width))<file_sep>########################45##########################
def Jump(nums):
'''
想象成这一步所能跳跃的范围,若最后终点在范围内则为最佳点 采用贪心算法 最优避免DP规划导致多余计算
思路:fir0,end0中找到使其跳的最远的作为end1,fir1=end0+1,依照此规律知道某段firn,endn中的数超过n-1
:param nums:
:return:
'''
# count计步器
n,fir,end,count=len(nums),0,0,0
# n-1表示从0到len(nums)要完成的最少跳跃步数
while end < n-1:
count = count + 1
maxend = end + 1
for i in range(fir, end+1):
if i + nums[i] >= n - 1:
return count
maxend = max(i + nums[i], maxend)
fir, end = end + 1 , maxend #下一轮的开始为上一轮while循环的结束
return count
def Jump2(nums): #####以上程序碰到列表中有0的数则可能出现问题
last, cur, step = 0, 0, 0
n = len(nums)
for i in range(n):
if i > last:
step += 1
last = cur
cur = max(cur, i + nums[i])
return step
##############################55###############################
def canJump(nums):
maxend = 0
# 前序遍历
for i in range(len(nums)):
if i > maxend:
return False
maxend = max(i+nums[i],maxend)
return True
def canJump2(nums):
n = len(nums) -1
goal = nums[n]
# 后序遍历
for i in range(n,-1,-1):
if i + nums[i] >= goal:
goal = i
return not goal
def canJump3(nums):
'''
动态规划
:param nums:
:return:
'''
n = len(nums)
dp = [False for i in range(n)]
dp[0] = True
for i in range(1, n):
for j in range(i):
if dp[j] and nums[j] + j >= i:
dp[i] = True
break
return dp[n - 1]
if __name__ == '__main__':
nums = [0,2,3]
nums2 = [2,3,1,1,4]
print(canJump3(nums2))<file_sep>q = int(input())
# 将十进制转换为k进制,k进制的每一位,用列表中的一个数表示,注意当k大于10时,k进制中的每一位可能为两位数
def dec2k(dec):
ansk = []
while dec:
ansk.append(dec % k)
dec = dec // k
ansk = ansk[::-1]
return ansk
# 将k进制转换为十进制,k进制的每一位,用列表中的一个数表示,注意当k大于10时,k进制中的每一位可能为两位数
def k2dec(rans):
ansd = 0
tmp = 1
# 由低位加起
for i in range(len(rans) - 1, -1, -1):
ansd += rans[i] * tmp
tmp *= k
return ansd
# k进制表示中,k-1的数量最多的数,且输出最小的,即k进制数每一位均为k-1构成
def get_ans():
if len(lvalue) == 0 or len(rvalue) == 0:
return
# 第一种全为(k-1), l <= and <= r
record, tmp = 0, 0
while tmp <= r:
record = tmp
tmp = tmp * k + (k - 1)
# print("record:", record)
if record >= l:
return record
else:
# 每判断一下都需要进制转换,复杂度太高,超时,由于每次只更新一位,因此,可以直接修改
# for i in range(len(lvalue) - 1, -1, -1):
# t = lvalue[i]
# lvalue[i] = k - 1
# if k2dec(lvalue) > r: # 大于,则还原
# lvalue[i] = t
# return k2dec(lvalue)
dec = k2dec(lvalue)
tmp = 1
for i in range(len(lvalue) - 1, -1, -1):
dec = dec + (k - 1 - lvalue[i]) * tmp
tmp = tmp * k
t = lvalue[i]
lvalue[i] = k - 1
if dec > r: # 大于,则还原
lvalue[i] = t
return k2dec(lvalue)
while q > 0:
k, l, r = map(int, input().strip().split())
lvalue = dec2k(l)
rvalue = dec2k(r)
print(get_ans())
q -= 1
<file_sep>def isChinese(ch):
return True if '\u4e00' <= ch <= '\u9af5' else False
def truncatestr(strs,lens):
if strs == '' or strs== None or lens == 0:
return ''
sb = ''
count = 0
for c in strs:
if count <lens:
if isChinese(c):
if count + 1 <= lens and count + 3 > lens:
return sb
count += 3
sb += c
else:
count += 1
sb += c
else:
break
return sb
if __name__ == '__main__':
strs = '人ABC们DEF'
lens = 6
print(truncatestr(strs,lens))<file_sep>def matrixchainorder(nums,n):
'''
方法:动态规划法
:paragram nums:矩阵维度数组
:paragram n:len(nums)
:return:
'''
# 第1、确定状态dp[i][j],nums[i]--nums[j]之间的最优矩阵链之积
# 初始化其为最大值
dp = [[float('inf')]*n for _ in range(n)]
# 第3、初始条件及边界情况
for i in range(1,n):
# dp[i,i]之间没有分割点
dp[i][i] = 0
for l in range(2,n):
# 第4、计算顺序,自顶向下
for i in range(1,n-l+1):
j = i + l - 1
# dp[i][j] = 2**31
for k in range(i,j):
# 第2、转移方程
# k 为dp[i,j]最优值的分割点
q = dp[i][k] + dp[k+1][j] + nums[i-1]*nums[k]*nums[j]
if q < dp[i][j]:
dp[i][j] = q
return dp[1][n-1]
def matrixchainorder1(nums,i,j):
'''
方法:递归法
思路:在大小为n的矩阵链中,有1,2,3,...,n-1中方式放置第一组括号
:paragram nums:
:paragram i:
:paragram j:
:return:
'''
if i == j:
return 0
mins = 2**31
k = i
while k < j:
# nums[i]--nums[k]在i-k中继续找 nums[k+1]--nums[j]在k+1-j中继续找
# nums[i - 1] * nums[k] * nums[j] 表示i-1至j直接的矩阵链相乘已经计算完毕,要i-1是因为递归初始是从1开始的
count = matrixchainorder1(nums,i,k) + matrixchainorder1(nums,k+1,j) + nums[i-1]*nums[k]*nums[j]
if count < mins:
mins = count
k += 1
return mins
if __name__ == '__main__':
arr = [40,20,30,10,30]
# 40×20,20×30,30×10,10×30
n = len(arr)
print(matrixchainorder(arr,n))
print(matrixchainorder1(arr,1,n-1))
<file_sep>k = int(input().strip())
a, x, b, y = list(map(int, input().split()))
mod = 1000000007
# dp[i]表示总歌单长度为i时,一共有多少组组成歌单的方法
dp = [0] * (k+1)
dp[0] = 1
#在x首长度为A的歌中选,总歌单长度i的歌单组成方法
for i in range(1, x + 1):
for j in range(k, a - 1, -1):
dp[j] = dp[j] + dp[j-a]
#在y首长度为B的歌中选,总歌单长度i的歌单组成方法
for i in range(1, y + 1):
for j in range(k, b - 1, -1):
dp[j] = dp[j] + dp[j - b]
print(dp[k])<file_sep>def medianSlidingWindow(nums, k):
'''
二分法
:param nums:
:param k:
:return:
'''
import bisect
# window里一直是有序的数组
window = sorted(nums[:k])
res = []
# 如果滑窗长度为偶数
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
for i in range(k, len(nums)):
bisect.insort(window, nums[i])
# 滑窗删除未排序前窗前的第一个数(如果用remove时间复杂度是O(n),这里用二分)
index = bisect.bisect_left(window, nums[i - k])
window.pop(index)
if k % 2 == 0:
res.append((window[k // 2] + window[k // 2 - 1]) / 2)
else:
res.append(window[k // 2])
return res
from heapq import *
def medianSlidingWindow1(nums, k):
'''
大小堆维护
:param nums:
:param k:
:return:
'''
# 对滑窗数组维护一个小顶堆和一个大顶堆,小顶堆存滑窗后半部分数,大顶堆存滑窗前半部分数
# 如果k是奇数,则小顶堆中的数量比大顶堆中的数量多一个
# 如果k是偶数,则小顶堆中的数量和大顶堆中的数量相同
max_heap,min_heap,res = [],[],[]
for i,n in enumerate(nums[:k]):
heappush(max_heap, (-n,i))
for i in range(k - k // 2):
heappush(min_heap, (-max_heap[0][0], max_heap[0][1]))
heappop(max_heap)
for i,n in enumerate(nums[k:]):
if k % 2:
res.append(min_heap[0][0]/1.)
else:
res.append((min_heap[0][0] - max_heap[0][0])/2.)
##############
# 如果滑窗后续数大于小顶堆的最小值,则应将其插入滑窗后半部分
if n >= min_heap[0][0]:
heappush(min_heap,(n,i+k))
# nums[i]是上一次滑窗的第一个元素,判断它在小顶堆还是大顶堆中(这里如果nums[i]在大顶堆中)
if nums[i] <= min_heap[0][0]:
heappush(max_heap, (-min_heap[0][0], min_heap[0][1]))
heappop(min_heap)
else:
heappush(max_heap,(-n,i+k))
if nums[i] >= min_heap[0][0]:
heappush(min_heap, (-max_heap[0][0], max_heap[0][1]))
heappop(max_heap)
###
# 删除大小堆中之前滑窗已经遍历过的数
while(max_heap and max_heap[0][1] <= i):
heappop(max_heap)
while(min_heap and min_heap[0][1] <= i):
heappop(min_heap)
if k % 2:
res.append(min_heap[0][0] / 1.)
else:
res.append((min_heap[0][0] - max_heap[0][0]) / 2.)
return res
if __name__ == '__main__':
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print(medianSlidingWindow1(nums, k))<file_sep>ss = list(input())
res = []
char = ['(', ')', '<']
flag = 0
for i in ss:
if i not in char:
if flag == 0:
res.append(i)
if i == '(':
flag += 1
if i == ')':
flag -= 1
if i == '<' and flag==0:
if len(res) > 0:
res.pop()
print(''.join(res))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isBalanced(root):
# 本题可与111 树的最大深度结合看
# (a1,a2)a1代表子树的高度,a2代表当前子树是否是平衡二叉树
def check(root):
if not root:
return (0, True)
# 递归遍历root节点的左、右子树
l = check(root.left)
r = check(root.right)
# 判断左子树 右子树是否为平衡状态
if (not l[1]) | (not r[1]):
return (0, False)
# 判断左右子树的高度差
if abs(l[0] - r[0]) > 1:
return (0, False)
else:
# (获取树的最大深度,平衡状态)
return (max(l[0], r[0]) + 1, True)
return check(root)[1]
if __name__ == '__main__':
l = [3,9,20,None,None,15,7]
tree = operate_tree.Tree()
print(isBalanced(tree.creatTree(l)))<file_sep>
############DP方法#################耗时较大###
def coinChange(coins,amount):
'''
动态规划
:param coins:
:param amount:
:return:
'''
# 1、确定状态 dp[i]表示总金额为i块钱的最小硬币兑换数
# 3、初始化及边界条件
dp = [0] + [float('inf')] * amount
# 4、计算方向 自左往右
for i in range(min(coins),amount+1):
# 2、状态转移方程
dp[i] = min(dp[i - coin] for coin in coins if coin <= i) + 1
return dp[-1] if dp[-1] < float('inf') else -1
#####################################DFS##########################
def coinChange2(coins, amount):
'''
DFS
:param coins:
:param amount:
:return:
'''
# 面值大者排前面(贪心策略)
coins.sort(reverse=True)
res = float('inf')
def dfs(pt, remain, count):
'''
:param pt:从大到小排序的硬币数组的某个下标
:param remain: 剩下的还需要找零的钱
:param count: 已经兑换的零钱数量
:return: None
'''
# res:当前递归产生的最小的零钱兑换次数
nonlocal res
# 递归停止条件
if not remain:
res = min(res, count)
# 先试大面值的硬币,如果不能到达终止条件,剪枝(退回到上一层递归在用较小的面值的硬币)
for i in range(pt, len(coins)):
# 增加coins[i] * (res - count)剪枝,
# 其意义:如果当前剩余需要找零的钱remain全用coin[i]进行兑换,
# 其所需要花费的硬币数量大于等于(res-count),
# 说明后续在该节点展开的子树,其最小的硬币兑换数将超过res
if coins[i] <= remain < coins[i] * (res - count):
dfs(i, remain - coins[i], count + 1)
# 先用大面值递归查找
for i in range(len(coins)):
dfs(i, amount, 0)
return res if res < float('inf') else -1
if __name__ == '__main__':
coins = [2,5,7]
amount = 27
# print(coinChange(coins,amount))
print(coinChange2(coins,amount))<file_sep>from Linked_list import linkedlist_operate
import heapq
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
class tup:
def __init__(self,v,n):
self.v = v
self.n = n
#下面两个方法重写一个就可以了
def __lt__(self,other):#operator <
return self.v < other.v
def mergeKLists(nums):
'''
方法:优先队列法
:param nums:
:return:
'''
dummy = cur = LNode(0)
queue = []
for l in nums:
if l:
# 刚开始初始化一个堆为列表中每个链表的头结点
heapq.heappush(queue,tup(l.val,l))
while queue:
node = heapq.heappop(queue)
cur.next = node.n
cur = cur.next
newnode = node.n.next
if newnode:
heapq.heappush(queue, tup(newnode.val, newnode))
return dummy.next
def mergeKLists1(lists):
'''
方法:分治
这题的出题目的与分治的思想最为接近
:param lists:
:return:
'''
if not lists:
return
n = len(lists)
return merge(lists,0,n-1)
def merge(lists,left,right):
# 递归划分k个链表
if left == right:
return lists[left]
mid = left + (right - left)//2
l1 = merge(lists,left,mid)
l2 = merge(lists,mid + 1,right)
return mergetwolists(l1,l2)
def mergetwolists(l1,l2):
# 两两合并排序后的链表值
if not l1: return l2
if not l2: return l1
if l1.val < l2.val:
# l1的当前值后接(l1.next与l2比较大小之后得到的值)
l1.next = mergetwolists(l1.next,l2)
return l1
else:
l2.next = mergetwolists(l1,l2.next)
return l2
if __name__ == '__main__':
l1 = [1,4,5]
l2 = [1,3,4]
l3 = [2,6]
llist = linkedlist_operate.LinkList()
cur1 = llist.initList(l1)
cur2 = llist.initList(l2)
cur3 = llist.initList(l3)
res = mergeKLists1([cur1.next, cur2.next, cur3.next])
llist.outll(res)<file_sep>def maxInWindows(nums, k):
if k == 0:
return []
if k > len(nums):
return []
import bisect
# window里一直是有序的数组
window = sorted(nums[:k])
res = []
res.append(window[-1])
for i in range(k, len(nums)):
bisect.insort(window, nums[i])
# 滑窗删除未排序前窗前的第一个数(如果用remove时间复杂度是O(n),这里用二分)
index = bisect.bisect_left(window, nums[i - k])
window.pop(index)
res.append(window[-1])
return res
if __name__ == '__main__':
num = [2,3,4,2,6,2,5,1]
size = 3
print(maxInWindows(num, size))<file_sep>def duplicate(numbers, duplication):
'''
思路:
数组的长度为 n 且所有数字都在 0 到 n-1 的范围内,我们可以将每次遇到的数进行"归位",当某个数发现自己的"位置"被相同的数占了,
则出现重复。扫描整个数组,当扫描到下标为 i 的数字时,首先比较该数字(m)是否等于 i,如果是,则接着扫描下一个数字;如果不是,
则拿 m 与第 m 个数比较。如果 m 与第 m 个数相等,则说明出现重复了;如果 m 与第 m 个数不相等,则将 m 与第 m 个数交换,
将 m "归位",再重复比较交换的过程,直到发现重复的数
'''
nums = numbers
if not nums:
return False
for i in range(len(nums)):
while nums[i] != i:
if nums[i] == nums[nums[i]]:
duplication[0] = nums[i]
print(duplication[0])
return True
tmp = nums[i]
nums[i] = nums[tmp]
nums[tmp] = tmp
return False
nums = [2,3,2,4,5,6]
s = [0]
print(duplicate(nums, s))<file_sep>
ss = input()
res = ''
count = 0
for i in range(len(ss)):
if 0<i<len(ss)-1:
if ss[i] == ss[i-1]:
count += 1
else:
if count-1 != 0:
res += str(count-1)
res += ss[i-1]
count = 1
elif i == 0:
count += 1
elif i == len(ss) - 1:
if ss[i] == ss[i-1]:
count += 1
if count - 1 != 0:
res += str(count-1)
res += ss[i]
else:
if count - 1 != 0:
res += str(count-1)
res += ss[i - 1]
res += ss[i]
print(res)
<file_sep>
def Kruskal(graph):
vnum = graph.vertex_num()
reps = [i for i in range(vnum)]
mst,edges = [],[]
for vi in range(vnum):
for v,w in graph.out_edges(vi):
edges.append((w,vi,v))
edges.sort()
for w,vi,vj in edges:
if reps[vi] != reps[vj]:
mst.append((vi,vj),w)
if len(mst) == vnum-1:
break
rep,orep = reps[vi], reps[vj]
for i in range(vnum):
if reps[i] == orep:
reps[i] = rep
return mst
if __name__ == '__main__':
graph_w = {'A': {'B': 5, 'C': 1}, 'B': {'A': 5, 'C': 2, 'D': 1}, 'C': {'A': 1, 'B': 2, 'D': 4, 'E': 8},
'D': {'B': 1, 'C': 4, 'E': 3, 'F': 6},
'E': {'C': 8, 'D': 3}, 'F': {'D': 6}}
res = Kruskal(graph_w)
print(res)<file_sep>def addStrings(num1, num2):
res = ""
i, j, carry = len(num1) - 1, len(num2) - 1, 0
while i >= 0 or j >= 0:
n1 = ord(num1[i]) - ord('0') if i >= 0 else 0
n2 = ord(num2[j]) - ord('0') if j >= 0 else 0
tmp = n1 + n2 + carry
carry = tmp // 10
res = str(tmp % 10) + res
i, j = i - 1, j - 1
if carry: res = "1" + res
return res
if __name__ == '__main__':
nums1 = '9' * 36
nums2 = '2' * 36
print(addStrings(nums1, nums2))
<file_sep>def count(ss, n, s):
length = len(ss)
m = n % length
if m == 0:
if ss *(n//length) == s:
return 1
else:
return 0
for i in range(length, n-m, length):
if s[i-length: i] != ss:
return 0
if s[n-m:] != ss[:m]:
return 0
return 1
n = int(input())
s = input()
m = int(input())
sub = []
for i in range(m):
sub_str = input()
sub.append(sub_str)
res = 0
for ss in sub:
res += count(ss, n, s)
print(res)<file_sep># 动态规划解题步骤:1、问题抽象化
# 2、建立模型
# 3、寻找约束条件
# 4、判断是否满足最优性原理
# 5、找大问题与小问题的递推关系式、填表、寻找解组成
# 动态规划与分治法相同点:都是把大问题拆分成小问题,通过寻找大问题与小问题的递推关系,
# 解决一个个小问题,最终达到解决原问题的效果
#动态规划与分治法不同点:分治法在子问题和子子问题等上被重复计算了很多次,而动态规划则具有记忆性,
# 通过填写表把所有已经解决的子问题答案纪录下来,在新问题里需要用到的子问题可以直接提取,
# 避免了重复计算,从而节约了时间,所以在问题满足最优性原理之后,用动态规划解决问题的核心就在于填表,
# 表填写完毕,最优解也就找到。
#0-1背包问题求解
#Q:有n个物品,它们有各自的体积和价值,现有给定容量的背包,如何让背包里装入的物品具有最大的价值总和?
#n=4,背包容量cap=30
#找到最优的价值总和(最优解求解)
def findoptv(W,V,n,cap):
'''
:param W: 各物品所占空间
:param V: 各物品价值
:param n: 物品数量
:param cap: 背包容量
:return: 背包里装入的物品最大的价值总和
'''
# # 4、计算顺序 自上向下 自左往右
# for i in range(1,n+1):
# for j in range(1,cap+1):
# # 2、转移方程
# # 物品大于背包容量
# if j < W[i]:
# dp[i][j] = dp[i-1][j]
# else:
# # 选择物品i与不选择物品i
# dp[i][j] = max(dp[i-1][j],dp[i-1][j-W[i]]+V[i])
# return dp[-1][-1]
#优化空间复杂度
dp = [0 for _ in range(cap+1)]
for i in range(1,n+1):
for j in range(cap,W[i]-1,-1):
dp[j] = max(dp[j], dp[j-W[i]] + V[i])
return dp[cap],dp
#找到得到最优的价值总和由哪些商品组成(最优解回溯) 由右下往左上回溯
def finditems(i,j):
'''
回溯法 DFS
搜索dp矩阵
:param i:
:param j:
:return:
'''
if (i >= 0):
# 未选择物品i
if(dp[i][j] == dp[i-1][j]):
items[i] = 0
finditems(i-1,j)
# 背包剩余容量大于物品i的重量 且 选择物品i
elif (j - W[i] >= 0) and (dp[i][j] == dp[i - 1][j - W[i]] + V[i]):
items[i] = 1
finditems(i-1,j-W[i])
return items
if __name__ == '__main__':
V = [0, 3,9,8,16,20]
W = [0, 4,3,10,12,5]
n = 5
cap = 20
# 1、确定状态 dp[i][j]表示背包容量为j时,物品种类为前i项时,背包里装入的物品最大的价值总和
# dp = [[0] * (cap + 1) for i in range(n + 1)]
items = [0] * (n + 1)
res,dp = findoptv(W, V, n, cap)
print(res)
# print(finditems(n,cap))
'''
完全背包问题
有N种物品和一个容量为V的背包,每种物品都有(无限件可用)。第i种物品的费用是w[i],
价值是v[i]。求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。
基本思路:
这个问题非常类似于01背包问题,所不同的是每种物品有无限件。也就是从每种物品的角度考虑,与它相关的策略已并非取或不取两种,
而是有取0件、取1件、取2件……等很多种。如果仍然按照解01背包时的思路,令f[i][j]表示前i种物品恰放入一个容量为V的背包的最大权值。
仍然可以按照每种物品不同的策略写出状态转移方程,像这样:
dp[i][j]=max(dp[i−1][j−k∗w[i]]+k∗v[i]) | 0<=k∗w[i]<=j
递推公式:
一维:
for (int i = 1; i <= n; i++)
for (int j = w[i]; j <= cap; j++)
dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
优化后的二维:dp[i][j]=max(dp[i−1][j],dp[i][j−w[i]]+v[i])
'''
'''
多重背包问题
有N种物品和一个容量为V的背包。第i种物品最多有p[i]件可用,每件费用是w[i],价值是v[i]。
求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。
基本思路:
这题目和完全背包问题很类似。基本的方程只需将完全背包问题的方程略微一改即可,因为对于第i种物品有p[i]+1种策略:
取0件,取1件……取p[i]件。令dp[i][j]表示前i种物品恰放入一个容量为j的背包的最大权值,则有状态转移方程:
dp[i][j]=max(dp[i−1][j−k∗w[i]]+k∗v[i]) | 0<=k<=p[i]
复杂度:O(V∗Σp[i])
改进 -->
for (i = 1; i <= n; i++)
int num = min(p[i], V / w[i])
for (int k = 1; num > 0; k <<= 1)
if (k > num) k = num
num -= k
for (int j = V; j >= w[i] * k; j--)
dp[j] = max(dp[j], dp[j - w[i] * k] + v[i] * k);
O(V∗Σlog(p[i]))
'''
<file_sep>from Linked_list import linkedlist_operate #链表题规范化输入输出
class LNode:
def __init__(self, x=None):
self.val = x
self.next = None
def reverseList(head):
l = []
while head:
l.append(head.val)
head = head.next
lt = l[::-1] #列表
llist = linkedlist_operate.LinkList()
cur = llist.initList(lt) #将列表转化为链表输出
return cur.next
def reverseList1(head):
'''
思路:1、p指针初始指向链表头结点
2、res指向链表的尾结点
3、p指针从头结点开始一直遍历链表下一节点,直到结束
4、res指针从尾节点开始,接收p指针指向的链表值
:param head:
:return:
'''
# 初始化res=None代表反转链表的尾结点
p, res = head, None
while p:
p,res,res.next=p.next,p,res
return res
def reverseList2(head):
if head == None or head.next == None:
return
pre,cur,next = None,None,None
cur = head.next
next = cur.next
cur.next = None
pre = cur
cur = next
while cur.next != None:
next = cur.next
cur.next = pre
pre = cur
cur = cur.next
cur = next
cur.next = pre
head.next = cur
if __name__ == '__main__':
l = [1, 8, 3, 4, 5]
llist = linkedlist_operate.LinkList()
cur = llist.initList(l)
print('输入')
llist.outll(cur)
res = reverseList1(cur)
print('输出')
llist.outll(res)
# head = LNode()
# head.next = None
# tmp = None
# cur = head
#
# for i in l:
# tmp = LNode()
# tmp.val = i
# tmp.next = None
# cur.next = tmp
# cur = tmp
# print('输入')
# cur = head
# outll(cur)
#
# print('输出:')
# res = reverseList1(head)
# outll(res)
<file_sep>def numSquares(n):
'''
动态规划 时间复杂度:O(n*sqrt(n))
:param n:
:return:
'''
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1,n + 1):
for j in range(1,int(i**(1/2))+1):
dp[i] = min(dp[i-j**2]+1,dp[i])
return dp[n]
def numSquares1(n):
'''
bfs
:param n:
:return:
'''
can_use = []
for i in range(1,n+1):
if i**2 <= n:
can_use.append(i**2)
else:
break
seen = set()
queue = [(0,0)]
can_use.sort(reverse=True)
while queue:
cur,step = queue.pop(0)
step += 1
# 测试can_use内完全平方数的组合
for num in can_use:
num += cur
if num == n:
return step
if num < n and (num,step) not in seen:
seen.add((num,step))
queue.append((num,step))
if __name__ == '__main__':
n = 12
print(numSquares1(n))
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def minDepth(root):
if not root:
return 0
if not root.left:
return minDepth(root.right) + 1
if not root.right:
return minDepth(root.left) + 1
return min(minDepth(root.left),minDepth(root.right)) + 1
def maxDepth(root):
if not root:
return 0
return 1 + max(maxDepth(root.left),maxDepth(root.right))
if __name__ == '__main__':
l = [3,9,20,1,2]
tree = operate_tree.Tree()
print(maxDepth(tree.creatTree(l)))
<file_sep>def countbit(n):
count = 0
if n < 0:
# 对负数取补码
n = n & 0xffffffff
while n:
count += 1
# 避免负数移位造成最高位的补充位都是1的影响 (对负数移位,最左边的用1填充) --> 这里是将最右边的1变为0
# x = bin(n)
n = (n-1) & n
# y = bin(n)
a = 1
return count
if __name__ == '__main__':
n = -15
print(countbit(n))
# -15的补码为(保持符号位不变,其他位按位取反再+1) 1111 1111 1111 1111 1111 1111 1111 0001<file_sep>def heapsort(list):
# 1、构造大顶堆 2、调整堆将最大值放到最后的节点位置
n = len(list)
# 构造大顶堆
for i in range((n//2),-1,-1):
adjust_head(list,i,n)
# 交换堆顶元素与最后一个元素的位置
for i in range(n-1,-1,-1):
# 先将为调整的数中的排在数组最后一个的元素放到最前面,
list[0],list[i] = list[i],list[0]
# 对nums[0:i]中的数重新建堆
adjust_head(list, 0, i)
def adjust_head(list,i,lenth):
# lchild是索引值 i从0开始 堆的索引i从0开始,与大话数据结构定义的不一样
lchild = 2*i + 1
rchild = 2*i + 2
maxl = i
if i < lenth//2:
if lchild < lenth and list[lchild] > list[maxl]:
maxl = lchild
if rchild < lenth and list[rchild] > list[maxl]:
maxl = rchild
if maxl != i:
# 将当前最大的数移到后面
list[maxl],list[i] = list[i],list[maxl]
# 在去除该最大数后的数组中重新构造堆
adjust_head(list,maxl,lenth)
if __name__ == '__main__':
l = [1, 3, 2, 4, 5, 6, 7, 90, 21, 23]
heapsort(l)
print(l)
<file_sep>import heapq as hq
# 堆接口
'''
#向堆中插入元素,heapq会维护列表heap中的元素保持堆的性质
heapq.heappush(heap, item)
#heapq把列表x转换成堆
heapq.heapify(x)
#从可迭代的迭代器中返回最大的n个数,可以指定比较的key
heapq.nlargest(n, iterable[, key])
#从可迭代的迭代器中返回最小的n个数,可以指定比较的key
heapq.nsmallest(n, iterable[, key])
#从堆中删除元素,返回值是堆中最小或者最大的元素
heapq.heappop(heap)
'''
######################## heappush创建堆
nums = [0,2,1,4,3,9,5,8,6,7]
heap = []
for num in nums:
hq.heappush(heap, num) # 加入堆
hq.heappop(heap)
a = 1
# print(heap[0]) # 如果只是想获取最小值而不是弹出,使用heap[0]
# print([hq.heappop(heap) for _ in range(len(nums)-1)]) # 堆排序结果
# out: [1, 2, 3, 5, 23, 54, 132]
# ######################### heapify创建堆 heappop
# nums = [2, 3, 5, 1, 54, 23, 132]
# hq.heapify(nums)
# hq.heappop(nums)
# # print()
# print([hq.heappop(nums) for _ in range(len(nums)-1)]) # 堆排序结果
# # out: [1, 2, 3, 5, 23, 54, 132]
#
#
# ######################### merge合并堆
#
# num1 = [32, 3, 5, 34, 54, 23, 132]
# num2 = [23, 2, 12, 656, 324, 23, 54]
# num1 = sorted(num1)
# num2 = sorted(num2)
# # 合并两个已经排序好的[iterables]
# res = hq.merge(num1, num2)
# print(list(res))
#
# ######################## nlargest nsmallest
#
# nums = [1, 3, 4, 5, 2]
# print(hq.nlargest(3, nums))
# print(hq.nsmallest(3, nums))
#
#
# '''
# 堆排序自定义比较
# '''
# #heapq使用的内置的小于号,或者类的__lt__比较运算来进行比较
# def heapq_int():
# # 初始化数值
# heap = []
# #以堆的形式插入堆
# hq.heappush(heap,10)
# hq.heappush(heap,1)
# hq.heappush(heap,10/2)
# [hq.heappush(heap,i) for i in range(10)]
# [hq.heappush(heap,10 - i) for i in range(10)]
# print (hq.nlargest(10,heap))
# print ([hq.heappop(heap) for i in range(len(heap))])
#
# def heapq_tuple():
# # 初始化元组
# heap = []
# hq.heappush(heap,(10,'ten'))
# hq.heappush(heap,(1,'one'))
# hq.heappush(heap,(10/2,'five'))
# while heap:
# print (hq.heappop(heap))
#
# class tup:
# def __init__(self,priority,description):
# self.priority = priority
# self.description = description
# # 改写__lt__方法实现结构体排序
# def __lt__(self,other):#operator <
# return self.priority < other.priority
#
# # def __ge__(self,other):#oprator >=
# # return self.priority >= other.priority
# # def __le__(self,other):#oprator <=
# # return self.priority < other.priority
# # 自定义比较函数
# # def __cmp__(self,other):
# # #call global(builtin) function cmp for int
# # return cmp(self.priority,other.priority)
# # def __str__(self):
# # return '(' + str(self.priority)+',\'' + self.description + '\')'
#
# def heapq_class():
# heap = []
# hq.heappush(heap,tup(100,'proficient'))
# hq.heappush(heap,tup(10,'expert'))
# hq.heappush(heap,tup(11,'novice'))
# while heap:
# print (hq.heappop(heap))
# if __name__ == '__main__':
# heapq_class()
<file_sep>def getpath(maze,x,y,slo):
N = len(maze)
if x == N-1 and y == N-1:
slo[x][y] = 1
return True
if x>=0 and x<N and y>=0 and y < N and maze[x][y] == 1:
slo[x][y] = 1
if getpath(maze,x+1,y,slo):
return True
if getpath(maze,x,y+1,slo):
return True
slo[x][y] = 0
return False
return False
if __name__ == '__main__':
maze = [[1,0,0,0],
[1,1,0,1],
[0,1,0,0],
[1,1,1,1]]
slo = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
if getpath(maze,0,0,slo):
print(slo)<file_sep>def squareroot(x):
'''
牛顿法 找到cur^2-x^2 = 0的函数 cur取何值时过零
:param x:
:param e:
:return:
'''
if x <= 1:
return x
cur = x
while cur*cur > x:
cur = (cur + x/cur)//2
return int(cur)
def squareroot1(x):
'''
二分法
:param x:
:param e:
:return:
'''
low, high = 0, x // 2 + 1
while low < high:
mid = (low + high + 1) // 2
if mid * mid > x:
high = mid - 1
else:
low = mid
return low<file_sep>
n,m = map(int,input().split())
xiguas = []
for _ in range(n):
ti,wi = map(int,input().split())
xiguas.append([ti,wi])
xiguas.sort(key = lambda x:x[1],reverse=True)
for _ in range(m):
d = int(input())
res = 0
# 应该二分搜索进行优化
for xigua in xiguas:
if xigua[0] >= d:
res += xigua[1]
break
if res:
print(res)
else:
print(-1)
<file_sep>def intervalIntersection(A, B):
def solve(l1, l2):
maxa = max(l1)
mina = min(l1)
maxb = max(l2)
minb = min(l2)
if mina < minb:
if maxa < minb:
return None,'l1'
elif maxa <= maxb:
return [minb, maxa],'l1'
else:
return [minb, maxb],'l2'
elif minb <= mina <= maxb:
if maxa <= maxb:
return [mina, maxa],'l1'
elif maxa > maxb:
return [mina, maxb],'l2'
else:
return None,'l2'
res = []
i,j=0,0
while i < len(A) and j < len(B):
s = solve(A[i], B[j])
if s[0] != None:
if s[1] == 'l1':
res.append(s[0])
i += 1
else:
res.append(s[0])
j += 1
elif s[0] == None:
if s[1] == 'l1':
i += 1
else:
j += 1
return res
#思路:如果 A[0] 拥有最小的末端点,那么它只可能与 B[0] 相交。然后我们就可以删除区间 A[0] 了,因为它不能与其他任何区间再相交了。
# 相似的,如果 B[0] 拥有最小的末端点,那么它只可能与区间 A[0] 相交,然后我们就可以将 B[0] 删除了,因为它无法再与其他区间相交了。
def intervalIntersection1(A, B):
i, j, res = 0, 0, []
while i < len(A) and j < len(B):
#两集合无交集
if A[i][1] < B[j][0]: #A.max < B.min
i += 1 #移动A
elif B[j][1] < A[i][0]: #B.max < A.min
j += 1 #移动B
# 两集合有交集
else:
res.append([max(A[i][0], B[j][0]), min(A[i][1], B[j][1])])
if A[i][1] > B[j][1]: #A.max > B.max
j += 1 #移动B(移动终端节点小的)
else:
i += 1
return res
if __name__ == '__main__':
A = [[3, 5], [9, 20]]
B = [[4, 5], [7, 10], [11, 12], [14, 15], [16, 20]]
print(intervalIntersection1(A, B))<file_sep>N = int(input())
nums = [int(c) for c in input().split()]
if N < 3:
print(-1)
res = -1
for i in range(3,N):
shape = nums[:i]
max_len = max(shape)
shape.remove(max_len)
if sum(shape) > max_len:
res = i
break
if i == N-1:
print(-1)
<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isSameTree(p, q):
if not p and not q:
return True
if p and q == None:
return False
if q and p == None:
return False
if p.val == q.val:
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
else:
return False
if __name__ == '__main__':
l = [1,2,3]
r = [1,2,3]
tree = operate_tree.Tree()
print(isSameTree(tree.creatTree(l), tree.creatTree(r)))
<file_sep>import collections
def customSortString(S, T):
c = collections.Counter(T) #记录待排序字符串各字符出现次数
res = []
for i in T:
if i not in S:
res.append(i)
for i in S:
res.extend([i] * c[i])
return ''.join(res)
if __name__ == '__main__':
S ='cba'
T = 'abcd'
print(customSortString(S,T))<file_sep>
def minDistance(word1, word2):
'''
题意:给定两个单词word1 = "horse", word2 = "ros",只能使用三种操作:插入、删除、替换,每种操作计数1次,
问需要多少次操作使word1转换为word2
思路:迭代动态规划
1、自顶向下
2、dp[i][j]代表word1(0至i-1)位置上的字符转换为word2(0至j-1)位置上的字符最少的操作数
'''
n1 = len(word1)
n2 = len(word2)
#第1、确定状态 word1(0至i-1)位置上的字符转换为word2(0至j-1)位置上的字符最少的操作数
dp = [[0]*(n2+1) for _ in range(n1+1)]
# 第3、初始化条件
for i in range(n1+1):dp[i][0] += i
for j in range(n2+1):dp[0][j] += j
# 第4、计算顺序 自左往右 自上向下
for i in range(1,n1+1):
for j in range(1,n2+1):
# 第2、状态转移矩阵
# 如果两个单词当前最后位置上的元素相同
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
# [i-1][j]代表删除操作,[i][j-1]代表插入操作,[i-1][j-1]替换操作
dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) + 1
return dp[-1][-1]
def minDistance1(word1, word2):
'''
思路:递归动态规划
速度更快
'''
dp = [{} for _ in range(len(word1) + 1)]
def getDistance(i, j):
# 边界处理
if i == 0: return j
if j == 0: return i
# 优化点,递归时不需要计算所有dp矩阵位置的值,根据条件筛选后,减少了许多计算量
if j in dp[i]: return dp[i][j]
#
if word1[i - 1] == word2[j - 1]:
dp[i][j] = getDistance(i - 1, j - 1)
else:
dp[i][j] = min(getDistance(i - 1, j - 1),getDistance(i - 1, j),getDistance(i, j - 1)) + 1
return dp[i][j]
res = getDistance(len(word1), len(word2))
return res
if __name__ == '__main__':
word1 = 'horse'
word2 = 'ros'
print(minDistance1(word1,word2))<file_sep>
#Q:给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
#输出需要删除的字符个数。
#区分最长公共子序列与最长子串的区别
#最长公共子序列:要求可以不连续
#最长公共子串:公共子串必须在原串中是连续的
#最长回文串:其正序串S与逆序串S'的最长公共子串不一定就是最长回文串;还需要注意当我们找到最长的公共子串
#的候选项时,都需要检查子串的索引是否与反向子串的原始索引相同。如果相同,那么我们尝试更新目前为止找到的最长回文子串;
#如果不是,我们就跳过这个候选项并继续寻找下一个候选。
class DP:
# 最大公共子序列
def maxlcs(self,a,b):
m = len(a)
n = len(b)
dp = [[0 for i in range(n+1)] for j in range(m+1)]
mem = [[None for i in range(n+1)] for j in range(m+1)]
res = []
for i in range(1,m+1):
for j in range(1,n+1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
mem[i][j] = 'ok'
elif dp[i-1][j] >= dp[i][j-1]: #这里注意符号一定是大于等于
dp[i][j] = dp[i-1][j]
mem[i][j] = 'up'
else:
dp[i][j] = dp[i][j - 1]
mem[i][j] = 'left'
p1,p2 = m,n
while dp[p1][p2]:
cc = mem[p1][p2]
if cc == 'ok':
res.append(a[p1-1])
p1-=1
p2-=1
if cc == 'left':
p2-=1
if cc == 'up':
p1 -= 1
res = ''.join(res[::-1])
return res,dp[m][n]
# 最长公共子串
def maxlss(self,a,b):
'''
思路
'''
m = len(a)
n = len(b)
# dp[i][j]表示a的子串a[:i]与b的子串b[:j]的最长公共子串的长度
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
result = 0
# a序列最长子串最后的索引位置
last = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
if dp[i][j] > result:
result = dp[i][j]
last = i
else:
dp[i][j] = 0
return a[last-result:last],result
def longestPalindrome(self, s):
#DP的方法 但是速度较慢 待优化
if not s:
return ''
# 先将任一单个字母作为结果
start = 0
maxlen = 1
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
# 将长度1和长度2(相同字母)情况初始化赋值
for i in range(len(s)):
dp[i][i] = 1
if (i < len(s) - 1) and (s[i] == s[i + 1]): #找到两个字母的回文
dp[i][i + 1] = 1
start = i
maxlen = 2
# 注意:不可横向遍历,否则例如abcba,是无法先将bcb置为1的,进而无法将abcba置为1
for length in range(3, len(s) + 1): #找到length个字母的回文 从3开始 因为初始化时已经找到两个字母的回文
for i in range(len(s) - length + 1):
j = i + length - 1 #i是回文串的tou j是回文串的尾
if (dp[i + 1][j - 1] == 1) and s[i] == s[j]:
dp[i][j] = 1
if length > maxlen:
start = i
maxlen = length
# for line in dp:
# print line
return s[start:start + maxlen]
##############################中心拓展法#########################################
def longestPalindrome2(self, s): #最长回文串 如何用动态规划求解
res = ''
for i in range(len(s)):
# odd case, like "aba"
tmp = self.helper(s, i, i) # i,i即代表找最大回文数是奇数情况的
if len(tmp) > len(res):
res = tmp
# even case, like "abba"
tmp = self.helper(s, i, i + 1) # i,i+1即代表找最大回文数是偶数情况的,
if len(tmp) > len(res):
res = tmp
return res
# get the longest palindrome, l, r are the middle indexes
# from inner to outer
def helper(self, s, l, r):
while 0 <= r < len(s) and s[l] == s[r]: # 从中间开始往两边检测最长回文数
l -= 1
r += 1
return s[l + 1:r]
#动态规划求解
def longestPalindrome3(self, s: str) -> str:
size = len(s)
if size <= 1:
return s
# 二维 dp 问题
# 状态:dp[l,r]: s[l:r] 包括 l,r ,表示的字符串是不是回文串
dp = [[0 for _ in range(size)] for _ in range(size)]
longest_l = 1
res = s[0]
# 因为只有 1 个字符的情况在最开始做了判断
# 左边界一定要比右边界小,因此右边界从 1 开始
for r in range(1, size):
for l in range(r):
# 状态转移方程:如果头尾字符相等并且中间也是回文
# 在头尾字符相等的前提下,l+1<=r-1 如果收缩以后不构成区间(最多只有 1 个元素),直接返回 True 即可
# 否则要继续看收缩以后的区间的回文性
# a1 or a2 满足a1就不会在判断a2
if s[l] == s[r] and (r - l <= 2 or dp[l + 1][r - 1]):
dp[l][r] = True
cur_len = r - l + 1
if cur_len > longest_l:
longest_l = cur_len
res = s[l:r + 1]
return res
if __name__ == '__main__':
mal = DP()
print(mal.maxlcs(['A','B','C','B','D','A','B'],['B','D','C','A','B','A']))
print(mal.maxlss("babad", 'dabab'))
print(mal.longestPalindrome3('google”'))<file_sep>###
# 思路:贪心前一般需要对序列值进行排序,本题的关键是每个序列坐标的end值,根据题意 xstart ≤ x ≤ xend 才能射爆气球,为使得一根箭尽可能
# 多的射爆气球,应该保证交叠区域满足条件 :任何交叠区域的气球的xstarti < xend1,xend1是该交叠区域最小的xend值
#
###
def findMinArrowShots(points):
points.sort(key = lambda x:x[1])
res = 0
end = -float('inf')
for p in points:
if p[0] > end:
res += 1
end = p[1]
return res
if __name__ == '__main__':
point = [[10,16], [2,8], [1,6], [7,12]]
print(findMinArrowShots(point))<file_sep>######
######矩阵第一行和第一列的数要单独进行计算,其它的遵循迭代公式计算即可
######
def minPathSum(grid):
m,n = len(grid),len(grid[0])
#1、确定状态 dp[i][j]为i行,j列矩阵的最小路径之和
dp = [[0 for _ in range(n)] for _ in range(m)]
if m == 0 and n == 0: #增加这两行代码提高了速度
return 0
# 第4、计算顺序 ,自左向右,自上向下
for i in range(m):
for j in range(n):
# 第3、初始条件
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
# 第2、状态转移矩阵
elif i == 0 and j != 0:
dp[i][j] = dp[i][j-1] + grid[i][j]
elif j == 0 and i != 0:
dp[i][j] = dp[i-1][j] + grid[i][j]
else:
dp[i][j] = min(dp[i-1][j] + grid[i][j], dp[i][j-1] + grid[i][j])
return dp[-1][-1]
###滚动数组优化空间复杂度
def minPathSum1(grid):
m,n = len(grid),len(grid[0])
dp = [[0 for _ in range(n)] for _ in range(2)]
if m == 0 and n == 0:
return 0
old = 1
now = 0
# 第4、计算顺序 ,自左向右,自上向下
for i in range(m):
# old为i-1行 now为i行
old = now
now = 1- now
for j in range(0,n):
if i == 0 and j == 0:
dp[now][j] = grid[i][j]
continue
# 第2、状态转移矩阵
dp[now][j] = grid[i][j]
if i > 0:
t1 = dp[old][j]
else:
t1 = float('inf')
if j > 0:
t2 = dp[now][j-1]
else:
t2 = float('inf')
if t1 < t2:
dp[now][j] += t1
else:
dp[now][j] += t2
return dp[now][n-1]
if __name__ == '__main__':
nums = [[1,3,1], [1,5,1], [4,2,1]]
nums1= [[1,4,3],[8,7,5],[2,1,5]]
print(minPathSum1(nums1))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def buildtree(postorder,inorder):
'''
给与注释的三行代码与105题不同
:param preorder:
:param inorder:
:return:
'''
def build(post, poststart, postend, instart, inPos):
if poststart > postend: return None
#
root = TreeNode(post[postend])
rootIdx = inPos[root.val]
leftLen = rootIdx - instart
#后序遍历 0 - poststart + leftLen - 1
root.left = build(post, poststart, poststart + leftLen - 1, instart, inPos)
# root占据了postend的位置 , 故postend-1
root.right = build(post, poststart + leftLen, postend - 1, rootIdx + 1, inPos)
return root
inPos = {val: idx for idx, val in enumerate(inorder)}
return build(postorder, 0, len(postorder)-1, 0, inPos)
def buildTree1(postorder,inorder) :
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
for i in range(len(inorder)):
if postorder[-1] == inorder[i]:
root.left = buildTree1(postorder[:i],inorder[:i])
root.right = buildTree1(postorder[i:-1],inorder[i + 1:])
return root
if __name__ == '__main__':
inorder = [9,3,15,20,7]
preorder = [9,15,7,20,3]
tree = operate_tree.Tree()
result = buildTree1(preorder, inorder)
print(tree.levelOrder(result))
<file_sep>class DLNode:
def __init__(self,elem,prev = None,next_=None):
self.elem = elem
self.next = next_
self.prev = prev #多一个前向指针
class LinkedListUnderflow(ValueError): #自定义链表抛出异常错误
pass
class DLList:
def __init__(self):
self._head = None
self._rear = None
def prepend(self,elem):
p = DLNode(elem, None, self._head) #激活头指针
if self._head is None:
self._rear = p
else:
p.next.prev = p
self._head = p
def append(self,elem):
p = DLNode(elem, self._rear, None)
if self._head is None:
self._head = p
else:
p.prev.next = p
self._rear = p
def pop(self):
if self._head is None:
raise LinkedListUnderflow(' in pop of DLList')
e = self._head.elem
self._head = self._head.next
if self._head is not None:
self._head.prev = None
return e
def pop_last(self):
if self._head is None:
raise LinkedListUnderflow(' in pop_last of DLList')
e = self._head.elem
self._rear = self._rear.prev
if self._rear is None:
self._head = None
else:
self._rear.next = None
return e
def printall(self):
p = self._head
while p is not None:
print(p.elem, end = '')
if p.next is not None:
print(', ',end = '')
p = p.next
print('')
if __name__ == '__main__':
list1 = DLList()
for i in range(11,20):
list1.prepend(i)
list1.pop_last()
list1.printall()<file_sep># Definition for an interval.
class node:
def __init__(self, s, e):
self.start = s
self.end = e
def eraseOverlapIntervals(intervals):
intervals = sorted(intervals, key = lambda x:(x[0]))
res = 0
end = -float('inf')
for x in intervals:
if x[0] < end:
end = min(end, x[1])
res += 1
else:
end = x[1]
return res
def eraseOverlapIntervals1(intervals):
end = float('-inf')
erased = 0
for i in sorted(list(intervals), key=lambda i: i.end):
if i.start >= end:
end = i.end
else:
erased += 1
return erased
if __name__ == '__main__':
l =[[1,2]]
print(eraseOverlapIntervals1(l))<file_sep>n = int(input())
nums = [int(c) for c in input().split()]
def fun(val):
power = val
for i in nums:
if power > i:
power += power - i
elif power < i:
power -= i - power
return power
def main(nums):
low = 0
high = max(nums)
while low < high:
mid = (low + high)//2
res = fun(mid)
if res == 0:
return mid
elif res > 0:
high = mid
else:
low = mid + 1
return low
if __name__ == '__main__':
print(main(nums))<file_sep>def disk_split(d,sp):
dind = 0
for i in range(len(sp)):
while dind < len(d) and d[dind] < sp[i] : #注意这种情况 ,先判断列表索引满足条件,在调用列表索引,避免报错
dind += 1
if dind >= len(d):
return False
d[dind] -= sp[i]
return True
if __name__ == '__main__':
d = [120,120,120]
sp = [60,80,80,20,80]
print(disk_split(d,sp))
<file_sep>class Solution:
def VerifySquenceOfBST(self, sequence):
length = len(sequence)
# 对于递归来说,当sequence为空为终止条件
if length == 0:
return False
# 对于判断BST来说,sequence为空为终止条件
if length == 1:
return True
root = sequence[-1]
left = 0
# 找到squence中root左子树的部分
while sequence[left] < root:
left += 1
# 判断root的右子树是否有小于root的节点
for i in range(left, length - 1):
if sequence[i] < root:
return False
return self.VerifySquenceOfBST(sequence[:left]) or self.VerifySquenceOfBST(sequence[left:-1])<file_sep>def numTrees(n):
'''
动态规划方法
思路:假设n个节点存在二叉排序树的个数是G(n),令f(i)为以i为根的二叉搜索树的个数,则
G(n)=f(1)+f(2)+f(3)+f(4)+...+f(n)
当i为根节点时,其左子树节点个数为i-1个,右子树节点为n-i,则
f(i) = G(i-1)*G(n-i)
从而得
G(n)=G(0)∗G(n−1)+G(1)∗G(n−2)+...+G(n−1)∗G(0) (n从1开始) 当n=0时, G(0) = 1
:param n:
:return:
'''
dp = [0] * (n+1)
dp[0] = 1
dp[1] = 1
for i in range(2,n+1):
for j in range(i):
# dp[i-1-j]代表最后取到的i-1
dp[i] += dp[j] * dp[i-1-j]
return dp[-1]
def numTrees1(n):
'''
思路:由上面公式,根据数学归纳法, 可直接得到, G(0) = 1, G(n+1) = 2*(2*n+1)*G(n)/(n+2) 这样的公式称为卡特兰数
:param n:
:return:
'''
C = 1
for i in range(0,n):
C = 2*(2*i+1)*C//(i+2)
return C
if __name__ == '__main__':
n = 12
print(numTrees(n))<file_sep>def bubblesort(list):
flag = True
for i in range(len(list)):
if flag:
flag = False #初始化为False
for j in range(i+1,len(list)):
if list[j] > list[j+1]:
list[j],list[j+1] = list[j+1],list[j] #如何数组发生了交换,这说明无序,还需遍历后面的i 否则说明已经有序
flag = True
else:
break
return list
if __name__ == '__main__':
l = [1, 3, 2, 4, 5, 6, 7, 90, 21, 23, 45]
print(bubblesort(l))<file_sep>n = int(input())
graph = []
for i in range(n):
graph.append([int(c) for c in input().split()])
n = 4
graph =[[0 ,2 ,6 ,5],[2 ,0 ,4 ,4],[6 ,4 ,0 ,2],[5 ,4 ,2 ,0]]
V = 1 << (n - 1) # 从左至右每一位二进制代表第i个城市是否被访问 如这里1左移3位——>1000代表,第一个城市被访问,而其他城市没有
dp = [[float("inf")] * V for i in range(n)] # dp[i][j]:从节点i只经过集合j所有点再回到0点所需要的最小开销
# 初始化,代表从起始点i出发,其它各城市访问状态为‘0’
for i in range(n):
dp[i][0] = graph[i][0]
# j为二进制数,判断位上对应的节点是否被访问
for j in range(1, V):
# i表示起始点城市的节点编号
for i in range(n):
for k in range(1, n): # 能不能先到k城市
# 可以途径k
if (j >> (k - 1) & 1) == 1:
dp[i][j] = min(dp[i][j], graph[i][k] + dp[k][j ^ (1 << (k - 1))])
# 从0出发,经过所有点,再回到0的费用
print(dp[0][(1 << (n - 1)) - 1])
#################################################################################################
# n = int(input())
# # graph = []
# # for i in range(n):
# # graph.append([int(c) for c in input().split()])
n = 4
graph =[[0 ,2 ,6 ,5],[2 ,0 ,4 ,4],[6 ,4 ,0 ,2],[5 ,4 ,2 ,0]]
# ‘10000’
stateNum = 1 << n
# dp[i][j]表示 以经过的城市状态为二进制数i开始,并且以j结尾的最短路径
dp = [[float('inf')] * n for _ in range(stateNum)]
dp[1][0] = 0
for i in range(1,stateNum):
for j in range(n):
# 如果该状态已经访问过
if dp[i][j] != float('inf'):
for k in range(1,n):
# 如果没有访问过k,且从这里到k的距离小于原来的距离,则更新
if (1 << k) & i == 0:
# i | (1 << k) 表示同时经过城市i和城市k(在后续遍历中若找到值比dp[i | (1 << k)][k]更小,则更新)
dp[i | (1 << k)][k] = min(dp[i | (1 << k)][k],dp[i][j] + graph[j][k])
res = float('inf')
# 因为确定是从北京出发,故而还需要加上graph[j][0],并找出最短的路径
for i in range(1,n):
res = min(res,dp[stateNum-1][i] + graph[i][0])
print(res)<file_sep>def deal(n, l):
return sum(l[0:n:2]) - sum(l[1:n:2])
if __name__ == '__main__':
n = 3
l = [2,7,4]
l.sort()
l = l[::-1]
print(deal(n, l))
<file_sep>import math
def summ(s, n, m):
# 计算以s为第一天的量,吃n天最少需要多少巧克力
summ = 0
for i in range(n):
summ += s
# s为下一天需要吃的数量
s = math.ceil(s / 2)
return summ
def bin_seach(n, m):
'''
题目要求第一天多吃多少巧克力?
思路:第一天可以吃的巧克力数量为1---m块,因此可以尝试第一天取1到m中的数,并判断是否满足父母回来前还有巧克力即可
贪心+二分搜索
:param n: 父母出差n天
:param m: 总的巧克力数量
:return: 第一天最大的可吃的巧克力数量
'''
if n == 1:
return m
# 1--m中二分搜索
low = 1
high = m
while low < high:
# 偶数的话中位数往上取
mid = math.ceil((low + high) / 2)
if summ(mid, n, m) == m:
return mid
elif summ(mid, n, m) < m:
low = mid
else:
high = mid - 1
return high
if __name__ == '__main__':
n, m = map(int,input().split())
res = bin_seach(n, m)
print(res)
<file_sep>from collections import OrderedDict
from Linked_list import linkedlist_operate
class ListNode:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache():
'''
方法:借助python内置有序字典表实现
'''
def __init__(self, capacity):
self.capacity = capacity
self.dict = OrderedDict()
def get(self, key):
if key not in self.dict:
return - 1
self.dict.move_to_end(key)
return self.dict[key]
def put(self, key, value):
if key in self.dict:
del self.dict[key]
self.dict[key] = value
if len(self.dict) > self.capacity:
# 弹出队尾元素
self.dict.popitem(last=False)
class LRUCache1():
'''
方法:借助双向链表、哈希表数据结构进行实现
'''
def __init__(self, capacity):
self.capacity = capacity
self.hashmap = {}
# 新建两个节点 head 和 tail
self.head = ListNode()
self.tail = ListNode()
# 初始化双向链表
self.head.next = self.tail
self.tail.prev = self.head
# 因为get与put操作都可能需要将双向链表中的某个节点移到末尾,所以定义一个方法
def move_node_to_tail(self, key):
# 先将哈希表key指向的节点拎出来,为了简洁起名node
node = self.hashmap[key]
# 将node节点从原链表中删除
node.prev.next = node.next
node.next.prev = node.prev
# 之后将node插入到尾节点前
#(前向链接)
node.prev = self.tail.prev
self.tail.prev = node
# (后向链接)
node.next = self.tail
self.tail.prev.next = node
def get(self, key):
if key in self.hashmap:
# 如果已经在链表中了,就把它移到末尾(变成最新访问的)
self.move_node_to_tail(key)
res = self.hashmap.get(key, -1) #字典的get方法 指定key不存在的返回值为-1
if res == -1:
return res
else:
return res.value
def put(self, key, value):
if key in self.hashmap:
# 如果key本身已经在哈希表中了就不需要在链表中加入新的节点
# 但是需要更新字典该值对应节点的value
self.hashmap[key].value = value
# 之后将该节点移到末尾
self.move_node_to_tail(key)
else:
if len(self.hashmap) == self.capacity:
# 去掉哈希表中对应的最久没有被访问过的点,即头节点之后的节点
self.hashmap.pop(self.head.next.key)
self.head.next = self.head.next.next
self.head.next.prev = self.head
# 如果不在的话就插入到尾节点前
new = ListNode(key, value)
self.hashmap[key] = new
# (前向)
new.prev = self.tail.prev
self.tail.prev = new
# (后向)
new.next = self.tail
self.tail.prev.next = new
<file_sep>from heapq import *
class MedianFinder:
def addNum(self, x):
heappush(self.high, -heappushpop(self.low, -x))
if len(self.low) < len(self.high):
heappush(self.low, -heappop(self.high))
def findMedian(self):
return float(-self.low[0]) if len(self.low) > len(self.high) else (-self.low[0] + self.high[0]) / 2.0
<file_sep>n = int(input())
nums = list(input().split())
for i in range(n):
if nums[i] in ['+','-','*','/']:
j = i
break
for i in range(len(nums)):
if nums[i] in ['+','-','*','/']:
# new存改变顺序后的算术表达式,nums仍为之前未交换的算术表达式,后面判断两者运算结果是否相等
new = nums[:]
# 带条件的插入排序
for j in range(i,0,-2):
if int(new[j+1]) > int(new[j-1]):
break
# 如果后面的数字比前面大
new[j+1],new[j-1] = new[j-1],new[j+1]
# 直接由字符串计算公式 算术结果
if eval(''.join(new)) == eval(''.join(nums)):
nums = new[:]
else:
break
print(' '.join(nums))
<file_sep>n = int(input())
baowu = []
for i in range(n):
baowu.append(list(map(int,input().split())))
def maxEnvelopes1(baowu):
'''
动态+二分查找
思路:同leetcode354 唯一不同的是这里要求只要不小于即可,不需要一定大于前一个选的物品
:param envelopes:
:return:
'''
baowu.sort(key=lambda x: (x[0], -x[1]))
nums = []
for i in baowu:
nums.append(i[1])
stack = [0] * len(nums)
maxl = 0
for x in nums:
low, high = 0, maxl
while low < high:
mid = low +(high - low) // 2
if stack[mid] <= x:
low = mid + 1
else:
high = mid
stack[low] = x
maxl = max(low + 1, maxl)
return maxl
print(maxEnvelopes1(baowu))
<file_sep>'''
一般的思路:Counter记录每个元素出现的次数,维护一个大顶堆,每次将对应的最大的两个数相减一次,知道最后堆中不存在任何数,即为yes
递推出的高级解法:Counter记录每个元素出现的次数,只要那个元素出现次数最多的数不大于总数的一半,总能通过上述一般思路得出yes
'''
from collections import Counter
T = int(input())
for _ in range(T):
n = int(input())
nums = [int(c) for c in input().split()]
dic = Counter(nums)
maxx = float('-inf')
for k in dic:
maxx = max(dic[k],maxx)
if maxx > n/2:
print('NO')
else:
print('YES')
<file_sep>def twoSum(nums, target):
dic = {}
for n,i in enumerate(nums):
if i in dic:
return [dic[i], n]
dic[target - i] = n
if __name__ == '__main__':
nums = [2,7,11,15]
target = 9
print(twoSum(nums,target))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def flatten(root):
def dfs(root):
if not root:
return
dfs(root.left)
dfs(root.right)
# 用后续遍历来调整整个二叉树的结构
# 先将左、右子树调整为链式结构,最后到根节点
tmp = root.right
root.right = root.left
root.left = None
# 将原来的root.right赋给root.right.right
# 相当于root.left-root-root.right------>root-root.left-root.right
while root.right:
root = root.right
root.right = tmp
return root
dfs(root)
return root
if __name__ == '__main__':
l = [1,2,5,3,4,None,6]
tree = operate_tree.Tree()
flatten(tree.creatTree(l))
<file_sep>'''
思路:
排序后除了最大的那个数,其余的数必然满足那个条件啊,因为只是前面的那个数就比它大了,
所以只要给最大的那个数找两侧的数就可以了,两侧最大的数就是第二大第三大的数,如果这两数都不满足条件,
那么必然无法排成,如果满足 那必然能排成圆环
'''
t = 1
for i in range(t):
n = 5
nums = [1,2,2,2,4]
nums.sort()
nums[n-1],nums[n-2] = nums[n-2],nums[n-1]
flag = 0
if nums[n-2] >= nums[n-1] + nums[n-3]:
flag = 1
if flag:
print('NO')
else:
print('YES')
<file_sep>N = int(input())
class pair:
def __init__(self,x,y):
self.x = x
self.y = y
pairs = []
for i in range(N):
a1,a2 = map(int, input().split())
pairs.append(pair(a1,a2))
xmin = float('-inf')
xmax = float('inf')
ymin = float('-inf')
ymax = float('inf')
for pair in pairs:
if pair.x < xmin:
xmin = pair.x
if pair.x > xmax:
xmax = pair.x
if pair.y < ymin:
ymin = pair.y
if pair.y > ymax:
ymax = pair.y
if xmax - xmin > 0 and ymax - ymin == 0:
print((xmax-xmin)**2)
elif ymax - ymin > 0 and xmax - xmin == 0:
print((ymax - ymin) ** 2)
else:
if ymax - ymin < xmax - xmin:
print((ymax - ymin) ** 2)
else:
print((xmax - xmin) ** 2)<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def binaryTreePaths(root): #思路同112的路径之和2
def dfs(root, tmp, res):
if not root:
return []
tmp += str(root.val) + '->'
if not root.left and not root.right:
res.append(tmp[:-2])
dfs(root.left, tmp, res)
dfs(root.right, tmp, res)
res = []
tmp = ''
dfs(root, tmp, res)
return res
if __name__ == '__main__':
l = [1,2,3,None,5,None,None]
tree = operate_tree.Tree()
print(binaryTreePaths(tree.creatTree(l)))<file_sep>ss = list(input().split(','))
class LargerNumKey(str):
def __lt__(x, y):
return x + y > y + x
def fun(nums):
largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey))
return '0' if largest_num[0] == '0' else largest_num
print(fun(ss))<file_sep>def findMin( nums) :
if not nums:
return 0
if len(nums) == 1:
return nums[0]
if nums[0] < nums[-1]:
return nums[0]
low, high = 0, len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] > nums[mid + 1]:
return nums[mid + 1]
if nums[mid - 1] > nums[mid]:
return nums[mid]
if nums[low] < nums[mid]:
low = mid + 1
if nums[high] > nums[mid]:
high = mid - 1
if __name__ == '__main__':
nums =[3,4,5,1,2]
print(findMin(nums))<file_sep>def subsets(nums):
'''
题意:
不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
解集不能包含重复的子集。
回溯法
:param nums:
:return:
'''
def backtrack(first, tmp):
res.append(tmp)
for i in range(first, len(nums)):
backtrack(i + 1, tmp + [nums[i]])
res = []
backtrack(0,[])
return res
def subsets1(nums):
import itertools
res = []
for i in range(len(nums)+1):
# itertools.combinations(nums, i)表示以nums中的i个元素进行组合
for tmp in itertools.combinations(nums, i):
res.append(tmp)
return res
def subsets2(nums):
# 迭代法
if not nums:
return [[]]
res = [[nums[0]]]
for i in range(1, len(nums)):
lens = len(res)
for j in range(lens):
res.append(res[j] + [nums[i]])
res.append([nums[i]])
res.append([])
return res
##################################### 90 ###########################################
def subsetsWithDup(nums):
'''
回溯法
:param nums:
:return:
'''
def backtrack(first, tmp):
res.append(tmp)
for i in range(first, len(nums)):
# 剪枝
if i > first and nums[i] == nums[i - 1]:
continue
backtrack(i + 1, tmp + [nums[i]])
res = []
nums.sort()
backtrack(0, [])
return res
def subsetsWithDup1(nums): #若列表集合存在重复元素
'''
题意:可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
解集不能包含重复的子集。
:param nums:
:return:
'''
nums.sort()
res = [[]]
cur = []
for i in range(len(nums)):
# 当为首元素或该元素在列表没有有相同元素时
if(i==0 or nums[i]!=nums[i-1]):
cur = [tmp + [nums[i]] for tmp in res]
else:
#因为有相同元素的存在,相同元素已经遍历过的无需在遍历
cur = [tmp + [nums[i]] for tmp in cur]
res += cur
return res
if __name__ == '__main__':
# nums = [1,2,3]
# print(subsets1(nums))
nums = [1, 2, 2]
print(subsetsWithDup(nums))
<file_sep>def isUgly(num):
'''
判断是否为丑数
丑数就是只包含质因数 2, 3, 5 的正整数。注意1也是丑数
:param num:
:return:
'''
if num == 0:
return False
while num != 1:
if num % 2 == 0:
num /= 2
elif num % 3 == 0:
num /= 3
elif num % 5 == 0:
num /= 5
else:
return False
return True
if __name__ == '__main__':
n = 14
print(isUgly(n))<file_sep>
def generate(numRows): #自己的方法
if numRows == 0:
return []
if numRows == 1:
return [[1]]
res = [[1], [1, 1]]
for i in range(2, numRows):
col = i + 1
dp = []
for j in range(col):
if (j == 0) | (j == (col - 1)):
dp.append(1)
else:
dp.append(res[i - 1][j - 1] + res[i - 1][j])
res.append(dp)
return res
def generate2(numRows): #标准答案
res = []
for i in range(numRows):
col = i + 1
dp = [None for _ in range(col)]
dp[0] = 1
dp[-1] = 1
for j in range(1,col-1):
dp[j] = res[i - 1][j - 1] + res[i - 1][j]
res.append(dp)
return res
def getRow(rowIndex): ############119###########优化空间复杂度
dp = []
for i in range(rowIndex):
col = i + 1
dp = dp + [None]
dp[0] = 1
dp[-1] = 1
pt = 1
for j in range(1, col - 1):
dp[j], pt = pt + dp[j], dp[j]
return dp
if __name__ == '__main__':
n = 5
print(generate(n))
print(getRow(5))<file_sep>from Tree import operate_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insertIntoBST(root, val):
if val > root.val:
if root.right:
insertIntoBST(root.right, val)
else:
root.right = TreeNode(val)
elif val < root.val:
if root.left:
insertIntoBST(root.left, val)
else:
root.left = TreeNode(val)
return root
if __name__ == '__main__':
l = [18, 2, 22, None, None, None, 63, None, 84, None, None]
val = 79
tree = operate_tree.Tree()
print(tree.preorderTraversal(tree.creatTree(l)))
print(tree.preorderTraversal(insertIntoBST(tree.creatTree(l), val)))<file_sep>def maxcover(nums,L):
i = 0
j = 1
n = len(nums)
count = 2
maxcount = 1
start = i
res = []
while i < n and j < n:
while (j < n) and (nums[j] - nums[i] <= L):
j += 1
count += 1
j -= 1
count -= 1
if count > maxcount:
start = i #记录覆盖点的起点
maxcount = count
i += 1
j += 1
res = [nums[x] for x in range(start,start + maxcount)]
return maxcount,res
if __name__ == '__main__':
nums = [1,3,7,8,10,11,12,13,15,16,17,19,25]
L = 8
print(maxcover(nums,L))
<file_sep>def main(numa, numb):
'''
题意:给定两个列表numa、numb,numa中有一个数字不遵循列表严格单调上升,在
numb中找出一个最大的数,使得列表numa严格单调上升,
未全AC原因:没有注意列表中需要修改的数字出现在列表边缘的情况,
numa = [1 ,3, 7, 8, 6],numb = [2, 1, 5, 8, 9] (不符合条件的数出现在列表头)
numa = [5 ,3, 7, 8, 6],numb = [2, 1, 5, 8, 9] (不符合条件的数出现在列表尾)
没有考虑numa[i]未能找到合适替换数,应该想办法替换numa[i-1]
:param numa:
:param numb:
:return:numa修改后的列表输出,如果没找到则输出NO
'''
# 未能全部通过原因,没有考虑numa边界
numa.append(float('inf'))
numa.insert(0,float('-inf'))
# 先拿较大的数来替换
numb.sort(reverse=True)
for i in range(1,len(numa)):
if numa[i] > numa[i - 1]:
continue
else:
# 先想办法替换numa[i],若未能找到,则再想办法替换numa[i+1],如果都不能找到值,则输出NO
for j in range(len(numb)):
if numa[i-1] < numb[j] < numa[i + 1]:
numa[i] = numb[j]
for j in range(len(numb)):
if numa[i - 2] < numb[j] < numa[i]:
numa[i-1] = numb[j]
numa.pop(0)
numa.pop(-1)
str1 = ''
for i in numa:
str1 = str1 + ' ' + str(i)
return str1.lstrip(' ')
return 'NO'
if __name__ == '__main__':
numa = [1 ,3, 7, 8, 7]
numb = [2, 1, 5, 8, 9]
print(main(numa, numb))<file_sep>'''
思路:
判断数组中是否既有偶数又有奇数,如果都有,则直接升序排列输出即为字典序最小
'''
n = 10
nums = [7,3,5,1]
# for i in range(n):
# minn = float('inf')
# flag = 0
# for j in range(n):
# if i != j and (nums[i] + nums[j]) % 2 != 0 and nums[j] < nums[i]:
# if nums[j] < minn:
# minn = nums[j]
# min_ind = j
# flag = 1
# if flag == 1:
# nums[i],nums[min_ind] = nums[min_ind],nums[i]
# print(nums)
jishu = 0
oushu = 0
for i in nums:
if i % 2 == 0:
oushu += 1
elif i % 2 != 0:
jishu += 1
if jishu!=0 and oushu!=0 :
nums.sort()
print(nums)
else:
print(nums)
<file_sep>#归并排序思想:如果要排序一个数组,我们先把数组从中间递归地分成前后两部分。
#然后分别对前后两部分进行排序,再将排好序的两部分数据合并在一起就可以了
#
def mergesort(nums):
if len(nums) <= 1:
return nums
mid = len(nums)//2
# 递归划分待排序的数组
left = mergesort(nums[:mid])
right = mergesort(nums[mid:])
return merge(left,right)
def merge(left,right):
l,r=0,0
res = []
while l < len(left) and r < len(right):
# 将待合并的数组left、right合并,并进行排序(left、right数组已排序)
if left[l] < right[r]:
res.append(left[l])
l += 1
else:
res.append(right[r])
r += 1
res += left[l:]
res += right[r:]
return res
if __name__ == '__main__':
l = [1, 3, 2, 4, 5, 6, 7, 90, 21, 23, 45]
print(mergesort(l))
<file_sep>#C(m,n)的计算方法
# 递推法 下式算得c[1][1]--c[100][100]的所有组合次数
def way1():
N=100
c = [[0] * (N+1) for _ in range(N+1)]
c[0][0] = 1
for i in range(1,N+1):
c[i][0] = 1
for j in range(1,N+1):
c[i][j] = c[i-1][j-1] + c[i-1][j]
##常规阶数法:
def way2():
N = 100
k = 3
summ = 1
for i in range(k,0,-1):
summ *= (N-(k-i))/i
return int(summ)
way2()
<file_sep>######
# 类快速排序求topk
######
class sol():
def __init__(self):
self.res = []
def partion(self,arr,low,high):
pivot = arr[low]
while low < high:
while low < high and arr[high] >= pivot:
high -= 1
arr[low] = arr[high]
while low < high and arr[low] <= pivot:
low += 1
arr[high] = arr[low]
arr[low] = pivot
return low
def topk(self,nums,k):
'''
找到第k个最小的元素
:param nums:
:return:
'''
if not nums or len(nums) < k or k == 0:
return []
low = 0
high = len(nums) - 1
p = self.partion(nums,low,high)
while p != k - 1:
if p < k-1:
low = p + 1
else:
high = p - 1
p = self.partion(nums,low,high)
res = []
for i in range(p+1):
res.append(nums[i])
return res
def main(self):
nums = [4,5,1,6,2,7,3,8]
k = 6
return self.topk(nums,k)
test = sol()
print(test.main())
<file_sep>m = int(input())
S = input().split()
def numPermsDISequence(S):
mod = 10 ** 9 + 7
n = len(S)
# dp[i][j]代表符合01规则的前i个位置的由j结尾的数组的数目,那么可以求得递推公式:
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
for j in range(i + 1):
# 当S[i - 1]为0时,p[i-1] < p[i]
if S[i - 1] == '1':
# dp[i][j] = dp[i-1][j] + dp[i-1][j+1] + ... + dp[i-1][i-1]
for k in range(j, i):
# here start from j, regard as swap value j with i, then shift all values no larger than j
dp[i][j] += dp[i - 1][k]
dp[i][j] %= mod
else:
# dp[i][j] = dp[i-1][0] + dp[i-1][1] + ... + dp[i-1][j-1]
for k in range(0, j):
dp[i][j] += dp[i - 1][k]
dp[i][j] %= mod
# print(dp)
return sum(dp[n]) % mod
print(numPermsDISequence(S))
<file_sep>##条件语句判断,is与==的区别
#is用于判断两个对象是否相同 ==判断是否相等
#is不要用于数值与字符串等不可变的类型
#
def findDuplicate(nums):
return (sum(nums) - sum(set(nums))) // (len(nums) - len(set(nums)))
#######快慢指针方法#####同环形链表二 环的入口为
def findDuplicate1(nums):
slow, fast = 0, 0
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast: #找到环
slow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
if __name__ == '__main__':
nums = [2,3,1, 1]
print(findDuplicate1(nums))
<file_sep>#############################相似题目46#################### 全排列
def permutation(string):
def backtrack(first):
if first == n:
res.append(string[:])
return
for i in range(first,n):
# 字符串是一种不可变的数据类型,不能直接用数组索引修改其值
string[first], string[i] = string[i], string[first]
backtrack(first+1)
# 递归交换了相邻顺序的字符,结束后要将其交换回原位置
string[first], string[i] = string[i], string[first]
res = []
n = len(string)
backtrack(0)
return res
###########################47############################# 全排列2 排列数组存在相同的值
def permuteUnique(nums):
def backtrack(nums, first):
if first == n:
# 为防止递归时交换数组顺序导致的错误,递归函数的数组都要用拷贝进行传递
res.append(nums.copy())
return
for i in range(first, n):
# 剪枝(注意组合与排列剪枝条件的区别)
if i > first and nums[first] == nums[i]:
continue
nums[first], nums[i] = nums[i], nums[first]
backtrack(nums.copy(), first + 1)
# 这里由于使用数组的拷贝,因此不需要在递归结束后再将交换的字符交换回来
# 先对排列数组进行排序
nums.sort()
res = []
n = len(nums)
backtrack(nums, 0)
return res
if __name__ == '__main__':
# s = 'abc'
# s = list(s)
# print([''.join(x) for x in permutation(s)])
nums = "abc"
nums = list(nums)
print([''.join(x) for x in permutation(nums)])
<file_sep># python3
def main():
case = int(input())
for c in range(case):
n = int(input())
golds = [int(c) for c in input().split()]
dp = [[0 for _ in range(n + 1)] for _ in range(n + 1)]
sum = [0 for _ in range(n + 1)]
for i in range(1, n + 1):
sum[i] = sum[i - 1] + golds[i - 1]
dp[i][i] = golds[i - 1]
#
for j in range(n):
for i in range(1, n):
if i + j <= n:
dp[i][i + j] = sum[i + j] - sum[i - 1] - min(dp[i + 1][i + j], dp[i][i + j - 1])
print ('Case #%d: %d %d'%(c + 1, dp[1][n], sum[n] - dp[1][n]))
if __name__ == '__main__':
main()
# python2的输入
# n = int(raw_input())
# a = [int(i) for i in raw_input().split()]
# dp = [1]
# for i in range(1,n+1):
# d = 0
# col = [0]*10
# for j in range(i):
# col[a[i - j - 1]] += 1
# if(col[a[i - j - 1]] > 1):
# break
# d += dp[i-1-j]
# dp.append(d)
# print dp[-1] % 1000000007
'''
C++输入输出
#include <iostream>
using namespace std;
int main()
{
int N, M;
// 每组第一行是2个整数,N和M,至于为啥用while,因为是多组。
while(cin>> N >> M) {
cout << N << " " << M << endl;
// 循环读取“接下来的M行”
for (int i=0; i<M; i++) {
int a, b, c;
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
}
}
return 0;
}
''' | ceada1c46e6540f9066f7111f6a0387c24722f5c | [
"Python"
] | 314 | Python | w5802021/leet_niuke | 199f2b62101480b963e776c07c275b789c20a413 | 556c966791e6a5e9a1a8eec61f67973aec9e56ca |
refs/heads/master | <file_sep># encoding: utf-8
get '/' do
@cafes = Cafe.all
@cafe_ids= @cafes.pluck(:id).join(",")
puts @cafe_ids
@food_generes = Food_genre.all
erb :index
end
get '/menus/:id' do
@params = params
@cafe = Cafe.find(params[:id])
@cafe_name = @cafe.name
# @cafe_name = @cafe.pluck([:name]).join("")
@menu_items = @cafe.menus
@menu_items_ids = Array.new
@menu_items.each do | item|
@menu_items_ids.push(item.id.to_s)
end
@menu_items_ids = @menu_items_ids.join(",")
erb :menu
end
post '/userlunchbag/new' do
puts "posting"
puts params
status 202
end
get '/pos' do
@userorders = [
{userid:1, student_id:12345, name:"Bill", order_id:1, order_details:"Pizza, Chicken Tenders", pickuptime: "1:00pm", pickupdate:"9/12/2015", pickup:false},
{userid:2, student_id:123456, name:"Jane", order_id:2, order_details:"Turkey Club", pickuptime: "12:00pm", pickupdate:"9/12/2015", pickup:false},
{userid:3, student_id:1234567, name:"Joe", order_id:3, order_details:"Turkey Club, Pizza", pickuptime: "11:10am", pickupdate:"9/12/2015", pickup:true},
{userid:3, student_id:1234568, name:"Jimmy", order_id:4, order_details:"Mac and Cheese", pickuptime: "11:00am", pickupdate:"9/12/2015", pickup:true},
]
erb :pos
end
# get '/projects' do
# @projects = Project.all
# @projects_size = @projects.size
# @projects.to_json(:methods => [:project_size, :skills_str , :role_str] )
# end
# get '/projects/:id' do
# #@project = Project.find(params[:id])
# @project = Project.find_by_slug(params[:id])
# # unless @project[:toolbox_ids].nil?
# # @project.tools = @project[:toolbox_ids].join(", ")
# # end
# # unless @project[:skills].nil?
# # @project.skills_str = @project[:skills].join(", ")
# # end
# # unless @project[:role].nil?
# # @project.role_str = @project[:role].join(", ")
# # end
# unless @project.description.nil?
# @project.description = @project.description.gsub("'", '')
# end
# @project.to_json #(:methods => [:tools, :skills_str , :role_str] )
# end
# get '/projectCategories' do
# @project_categories = ProjectType.all
# @project_categories.to_json
# end
# get '/toolboxCategories' do
# @toolbox_categories = Toolbox.all
# @toolbox_categories.to_json
# end
# end
<file_sep>class Addcafelocation < ActiveRecord::Migration
def up
add_column :cafes, :location, :string
add_column :cafes, :mycafe_id, :integer
add_column :menus, :mycafe_id, :integer
add_column :food_genres, :myfood_genres_id, :integer
add_column :menus, :myfood_genres_id, :integer
add_column :menus, :menu_img, :string
add_column :food_genres, :foodgenre_img, :string
end
def down
remove_column :cafes, :location
remove_column :cafes, :mycafe_id
remove_column :menus, :mycafe_id
remove_column :food_genres, :myfood_genres_id
remove_column :menus, :myfood_genres_id
remove_column :menus, :menu_img
remove_column :food_genres, :foodgenre_img
end
end
<file_sep>class Addmenustable < ActiveRecord::Migration
def up
create_table :menus do |t|
t.string :name
t.decimal :price
t.text :description
t.string :food_genre_id
t.integer :cafe_id
t.timestamps
end
create_table :cafes do |t|
t.string :name
t.string :description
t.string :logo_img
end
create_table :food_genres do |t|
t.string :name
t.text :description
end
create_table :users do |t|
t.string :fn
t.string :ln
t.string :username
t.integer :phone
t.string :email
t.string :role
end
create_table :orders do |t|
t.date :pickup_dt
t.time :pickup_time
t.integer :menu_id
t.integer :cafe_id
t.integer :user_id
t.timestamps
end
end
def down
drop_table :users
drop_table :cafes
drop_table :menus
drop_table :food_genres
drop_table :orders
end
end
<file_sep>class Menu < ActiveRecord::Base
has_many :food_genres
belongs_to :cafes
end
class Cafe < ActiveRecord::Base
has_many :menus
end
class User < ActiveRecord::Base
has_many :orders
has_many :lunchbags
end
class Food_genre < ActiveRecord::Base
end
class Order < ActiveRecord::Base
belongs_to :users
end
class LunchBag < ActiveRecord::Base
belongs_to :users
end
#not going to bother with friendly ids; not enough time
# extend FriendlyId
# # friendly_id :title, use: :slugged
# # # validates_presence_of :slug
# # def to_param
# # slug
# # end
<file_sep> ActiveSupport::Inflector.inflections do |inflect|
inflect.plural "cafe", "cafes"
end
<file_sep># encoding: utf-8
require_relative 'response_format'
MenuApp.helpers ResponseFormat
<file_sep>#Hungry Bear- A Lunch Time Ordering App
##Installation Instructions
Assumes that you have ruby, mysql and bower installed
###Install Gems and Bower packages to get dependencies
bundle install
bower install
###Create and Seed the DB
cd into the app root dir
then:
rake db:setup
rake db:seed
<file_sep># encoding: utf-8
require 'multi_json'
require 'sinatra'
require 'sinatra/activerecord'
require 'mysql2'
require 'pluck_to_hash'
require 'friendly_id'
class MenuApp < Sinatra::Application
enable :sessions
#https://github.com/jsmestad/sinatra_warden
#https://sideprojectsoftware.com/blog/2015/02/22/sinatra-authentication.html
settings = YAML::load(File.open('config/database.yml'))
settings = settings['development']
configure :development do
enable :raise_errors, :sessions, :logging
ActiveRecord::Base.establish_connection(
adapter: 'mysql2',
username: 'myrailsbuddy',
password: '<PASSWORD>',
host: 'localhost',
database: 'menuapp_development')
end
set :root, File.dirname(__FILE__)
set :static, true
set :public_folder, 'public'
end
require_relative 'config/initializers/inflections.rb'
require_relative 'helpers/init'
require_relative 'models/init'
require_relative 'routes/init'
| 96f0754ec6e157be7440af534ae9db8f5b865e8a | [
"Markdown",
"Ruby"
] | 8 | Ruby | j9recurses/hungrybear | b14d1cbb19f57922a77216bc43cc699617c47158 | b52000dfc25dfd727ffabef3827cfb565a934d7e |
refs/heads/main | <file_sep>@@include("slick.min.js");
$(document).ready(function () {
$(".header__burger").click(function (event) {
$(".header__burger,.header__menu,.header__profile").toggleClass("active");
$("body").toggleClass("lock");
});
$(".search__input").focus(function (event) {
$(".header__logo").addClass("hidden");
});
$(".header__menu").click(function (event) {
$(".header__burger,.header__menu,.header__profile").removeClass("active");
$("body").removeClass("lock");
});
$(".search__input").blur(function (event) {
$(".header__logo").removeClass("hidden");
});
$(".slider").slick({
slidesToShow: 3,
slidesToScroll: 1,
arrows: true,
dots: false,
speed: 1000,
autoplay: true,
autoplaySpeed: 1500,
infinite: true,
responsive: [
{
breakpoint: 650,
settings: {
slidesToShow: 2,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
},
},
],
});
});
| 05b2235e997fd8a2d0c039c609b1bf2b48c7862b | [
"JavaScript"
] | 1 | JavaScript | vitalia-kontanistova/Aiogi_1 | d9126943363f5ac0b81b836ebbc956b23fb53d44 | fe7d99f6bbd4149060145044c423623f0f4dee17 |
refs/heads/master | <repo_name>LiteSoul/face-recognition-brain-api<file_sep>/server.js
const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const cors = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(cors());
// DB var for now
const database = {
users: [
{
id: "10",
name: "Johna",
email: "<EMAIL>",
password: "<PASSWORD>",
entries: 0,
joined: new Date()
},
{
id: "11",
name: "Tama",
email: "<EMAIL>",
password: "<PASSWORD>",
entries: 0,
joined: new Date()
},
{
id: "12",
name: "Rose",
email: "<EMAIL>",
password: "<PASSWORD>",
entries: 0,
joined: new Date()
}
]
};
// / get this is working
app.get("/", (req, res) => {
res.send(database.users);
});
// /signin post = success or fail
app.post("/signin", (req, res) => {
checkUserPassword(
req.body.password,
<PASSWORD>$10$OwGL7uACsQwkyg7Up8sA..x.ymMCb3gTxRaYMiJ9aSpDOBPAfKsPO"
);
if (
req.body.email === database.users[0].email &&
req.body.password === database.users[0].password
)
res.json(database.users[0]);
else res.status(400).json("error loggin in");
});
// /register post = user obj
app.post("/register", (req, res) => {
const { id, email, password, name } = req.body;
storeUserPassword(password, 10);
database.users.push({
id: id,
name: name,
email: email,
entries: 0,
joined: new Date()
});
res.json(database.users[database.users.length - 1]);
});
// /profile/:id get = user
app.get("/profile/:id", (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
return res.json(user);
}
});
if (!found) res.status(400).json("user not found");
});
// /image put = user
app.put("/image", (req, res) => {
const { id } = req.body;
let found = false;
database.users.forEach(user => {
if (user.id === id) {
found = true;
user.entries++;
return res.json(user.entries);
}
});
if (!found) res.status(400).json("user not found");
});
const storeUserPassword = (password, salt) => {
bcrypt.hash(password, salt).then(hash => {
// Store hash in your password DB.
console.log(hash);
});
};
const checkUserPassword = (enteredPassword, storedPasswordHash) => {
bcrypt.compare(enteredPassword, storedPasswordHash).then(res => {
// res returns true or false
console.log(res);
});
};
//-----APP LISTEN TO PORT 3000-----
app.listen(3000, () => console.log("Server running ok"));
| 29fd9612a41b0be452d29cd4286e16cd182c1723 | [
"JavaScript"
] | 1 | JavaScript | LiteSoul/face-recognition-brain-api | 0316bdf99dcd4bccc409cc65fbdc633f4e609468 | 1ba17448df44bb86e510584d42849aaa11e227e2 |
refs/heads/main | <file_sep>import { GET_USERS, USER_UPDATED } from '../actions/types';
/**
*
* @type {{users: *[]}}
*/
const initialState = {
users: [],
};
export default function users(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_USERS:
return {
...state,
users: payload,
};
case USER_UPDATED:
return {
...state,
users: state.users.map(user => (user.id === payload.id ? payload : user)),
};
default:
return state;
}
}
<file_sep>import axios from 'axios';
import { setAlert } from './alert';
import { GET_CATEGORIES, CREATE_CATEGORY } from './types';
export const getCategories = () => async dispatch => {
try {
const res = await axios.get('/api/categories');
dispatch({
type: GET_CATEGORIES,
payload: res.data,
});
} catch (e) {
console.log(e.response);
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
export const createCategory = formData => async dispatch => {
// axios
// .post('/api/categories/create', formData)
// .then(res =>
// dispatch({
// type: CREATE_CATEGORY,
// payload: res.data,
// })
// )
// .catch(e => dispatch(setAlert(e.response.data.msg, 'error')));
try {
const res = await axios.post('/api/categories/create', formData);
console.log(res);
dispatch({
type: CREATE_CATEGORY,
payload: res.data,
});
dispatch(setAlert(res.data.msg, 'success'));
} catch (e) {
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
export const updateCategory = formData => async dispatch => {
try {
await axios.patch('/api/categories/update', formData);
dispatch(getCategories());
dispatch(setAlert('categorie a jour !', 'success'));
} catch (e) {
console.log(e);
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
export const destroyCategory = formData => async dispatch => {
try {
await axios.get(`/api/categories/destroy?id=${formData}`);
dispatch(getCategories());
dispatch(setAlert('Bye Bye categorie !', 'success'));
} catch (e) {
console.log(e);
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
<file_sep>import React from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Dimensions,
} from "react-native";
const Home = ({ navigation }) => {
function goShopping() {
navigation.navigate("Shop");
}
function goRegister() {
navigation.navigate("Register");
}
function goLogin() {
navigation.navigate("Login");
}
return (
<View style={styles.container}>
<Text style={styles.text}>React Native Shop !</Text>
<TouchableOpacity style={styles.touchable} onPress={goShopping}>
<Text style={styles.btn}>Voir le shop</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchable} onPress={goRegister}>
<Text style={styles.btn}>Register</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchable} onPress={goLogin}>
<Text style={styles.btn}>Login</Text>
</TouchableOpacity>
</View>
);
};
const screen = Dimensions.get("window");
const btnWidth = screen.width / 2;
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 4,
marginTop: 150,
alignItems: "center",
height: "100%",
},
text: {
fontSize: 24,
padding: 6,
fontWeight: "bold",
marginBottom: 20,
},
btn: {
fontSize: 18,
fontWeight: "bold",
color: "#fff",
textTransform: "uppercase",
},
touchable: {
height: Math.floor(btnWidth / 2 - 15),
width: Math.floor(btnWidth - 15),
alignItems: "center",
justifyContent: "center",
borderRadius: Math.floor(btnWidth),
margin: 7,
backgroundColor: "#000",
padding: 12,
},
});
export default Home;
<file_sep>import React, { Fragment, useEffect } from "react";
import { View, Text, Image, TouchableOpacity, StyleSheet } from "react-native";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getProduct } from "../actions/products";
import { formatPrice } from "../utils/helpers";
const ProductDetail = ({
route,
navigation,
products: { product },
getProduct,
}) => {
useEffect(() => {
const { id } = route.params;
getProduct(id);
console.log(product.image);
}, [route]);
return (
<Fragment>
{product && (
<View style={styles.container}>
<Text style={styles.title}>{product.title}</Text>
<Image source={{ uri: product.image }} style={styles.image} />
<Text style={styles.description}>{product.description}</Text>
<Text style={styles.price}>{formatPrice(product.priceHT)}€</Text>
</View>
)}
<View style={styles.btnContainer}>
<TouchableOpacity
style={styles.btn}
onPress={() => navigation.goBack()}
>
<Text>Go Back</Text>
</TouchableOpacity>
</View>
</Fragment>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: "#dddeee",
padding: 5,
borderRadius: 15,
marginTop: 5,
alignItems: "center",
width: "100%",
},
btnContainer: {
padding: 15,
borderRadius: 15,
marginTop: 5,
alignItems: "center",
width: "100%",
},
btn: {
width: "25%",
backgroundColor: "lightblue",
padding: 15,
borderRadius: 5,
alignItems: "center",
},
title: {
marginBottom: 5,
fontSize: 36,
textTransform: "uppercase",
color: "rgba(150, 100, 250, 0.7)",
padding: 5,
borderBottomWidth: 10,
borderColor: "white",
},
description: {
color: "rgba(50, 100, 250, 0.7)",
fontSize: 16,
marginTop: 15,
marginBottom: 5,
width: "75%",
textAlign: "center",
},
price: {
marginTop: 5,
fontSize: 36,
color: "rgba(50, 200, 150, 0.7)",
},
image: {
width: 300,
height: 200,
},
});
ProductDetail.propTypes = {
getProduct: PropTypes.func.isRequired,
products: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
products: state.products,
});
export default connect(mapStateToProps, { getProduct })(ProductDetail);
// insert into products (category_id, image, title, metaDescription, description, priceHT, createdAt, updatedAt) VALUES (1, 'https://www.fillmurray.com/g/300/200', 'Iphone 1000', 'Un Bon Truc', "Un poisson frais exceptionnel, on a pris ca ce matin par surprise dans l'egout en bas pendant que les pompiers y faisaient des prelevements pour suivre l'epidemie", 2500, now(), now());
<file_sep>import { combineReducers } from 'redux';
import alert from './alert';
import auth from './auth';
import categories from './categories';
import articles from './articles';
import roles from './roles';
import users from './users';
import products from './products';
import cart from './cart';
import employees from './employees';
export default combineReducers({
alert,
auth,
categories,
articles,
roles,
users,
products,
cart,
employees,
});
<file_sep>import { CREATE_ARTICLE, GET_ARTICLES } from '../actions/types';
/**
*
* @type {{articles: *[]}}
*/
const initialState = {
articles: [],
};
export default function articles(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_ARTICLES:
return {
...state,
articles: payload,
};
case CREATE_ARTICLE:
return {
...state,
articles: [...state.articles, payload.article],
};
default:
return state;
}
}
<file_sep>import axios from "axios";
import { setAlert } from "./alert";
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
AUTH_ERROR,
USER_LOADED,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
} from "./types";
import setAuthToken from "../utils/setAuthToken";
import { getData } from "../utils/asyncStorage";
axios.defaults.headers.post["Content-Type"] = "application/json";
/**
* @namespace localStorage
* @returns {function(*): Promise<void>}
*/
export const loadUser = () => async (dispatch) => {
try {
const tok = await getData("token");
await setAuthToken(tok);
const res = await axios.get("https://api.evilweb.fr/api/auth");
dispatch({
type: USER_LOADED,
payload: res.data,
});
} catch (e) {
dispatch({
type: AUTH_ERROR,
});
}
};
export const register = ({ name, email, password, url }) => async (
dispatch
) => {
const data = JSON.stringify({ name, email, password });
try {
const res = await axios.post(`https://api.evilweb.fr${url}`, data);
if (url === "/api/users/register") {
dispatch({
type: REGISTER_SUCCESS,
payload: res.data,
});
return dispatch(loadUser());
}
return dispatch(setAlert("Employé embauché", "success"));
} catch (e) {
const errors = e.message;
console.log(e.message);
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "error")));
}
if (url === "/api/users/register") {
dispatch({
type: REGISTER_FAIL,
});
}
}
};
export const login = (email, password) => async (dispatch) => {
const data = JSON.stringify({ email, password });
try {
const res = await axios.post("https://api.evilweb.fr/api/auth", data);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data,
});
dispatch(loadUser());
} catch (e) {
const errors = e.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "error")));
}
dispatch({
type: LOGIN_FAIL,
});
}
};
export const logout = () => (dispatch) => {
dispatch({ type: LOGOUT });
};
<file_sep>import React, { Fragment, useEffect } from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
const { Navigator, Screen } = createStackNavigator();
import { connect } from "react-redux";
import {
View,
Text,
FlatList,
SafeAreaView,
StyleSheet,
StatusBar,
ScrollView,
TouchableOpacity,
} from "react-native";
import PropTypes from "prop-types";
import { getProducts } from "../actions/products";
import Item from "./subcomponents/Item";
import ProductDetail from "./ProductDetail";
const Shop = ({ navigation, products: { products }, getProducts }) => {
useEffect(() => {
getProducts();
}, []);
function productDetails(id) {
navigation.navigate("productDetail", { id: id });
}
const renderItem = ({ item }) => (
<TouchableOpacity onPress={() => productDetails(item.id)}>
<Item product={item} />
</TouchableOpacity>
);
return (
<SafeAreaView style={styles.container}>
{products && (
<FlatList
style={styles.list}
data={products}
contentContainerStyle={{ alignSelf: "flex-start" }}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
renderItem={renderItem}
keyExtractor={(item, index) => item.title + index}
/>
)}
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
list: {
flex: 1,
},
item: {
backgroundColor: "#f9c2ff",
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
Shop.propTypes = {
products: PropTypes.object.isRequired,
getProducts: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
products: state.products,
});
export default connect(mapStateToProps, { getProducts })(Shop);
<file_sep>import { setAlert } from './alert';
import {
GET_CART,
ADD_TO_CART,
GET_CART_COUNT,
UPDATE_QTY,
REMOVE_ITEM,
} from './types';
export const getCart = () => async dispatch => {
try {
dispatch({
type: GET_CART,
});
} catch (e) {
console.log(e);
}
};
export const getCartCount = () => async dispatch => {
dispatch({
type: GET_CART_COUNT,
});
};
export const addToCart = product => async (dispatch, state) => {
try {
if (!product.qty) {
product.qty = 1;
}
dispatch({
type: ADD_TO_CART,
payload: product,
});
dispatch(setAlert('Produit ajouté au panier', 'success'));
} catch (e) {
console.log(e);
}
};
export const updateQty = formData => async dispatch => {
try {
dispatch({
type: UPDATE_QTY,
payload: formData,
});
dispatch(setAlert('Qty mis à jour !', 'success'));
} catch (e) {
console.log(e);
}
};
export const deleteProduct = id => async dispatch => {
try {
dispatch({
type: REMOVE_ITEM,
payload: id,
});
dispatch(setAlert('Produit retire du panier !', 'success'));
} catch (e) {
console.log(e);
}
};
export const updateCart = formData => async dispatch => {
try {
dispatch(setAlert('Panier mis à jour !', 'success'));
} catch (e) {
console.log(e);
}
};
export const destroyCart = formData => async dispatch => {
try {
dispatch(setAlert('Votre panier est vide !', 'success'));
} catch (e) {
console.log(e);
}
};
<file_sep>import axios from 'axios';
import { setAlert } from './alert';
import { GET_ROLES, CREATE_ROLE } from './types';
// CREATE, READ, UPDATE, DELETE
export const getRoles = () => async dispatch => {
try {
const res = await axios.get('/api/roles');
dispatch({
type: GET_ROLES,
payload: res.data,
});
} catch (e) {
console.log(e.response);
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
export const createRole = formData => dispatch => {
axios
.post('/api/roles/create', formData)
.then(res => {
dispatch({
type: CREATE_ROLE,
payload: res.data,
});
dispatch(setAlert(res.data.msg, 'success'));
})
.catch(e => dispatch(setAlert(e.response.data.msg, 'error')));
};
export const updateRole = formData => async dispatch => {
try {
await axios.patch('/api/roles/update', formData);
dispatch(getRoles());
dispatch(setAlert('rôle a jour !', 'success'));
} catch (e) {
dispatch(setAlert(e.response.data.errors[0].msg, 'error'));
}
};
export const destroyRole = formData => async dispatch => {
try {
await axios.delete(`/api/roles/destroy`, { data: formData });
dispatch(getRoles());
dispatch(setAlert('Bye Bye rôle !', 'success'));
} catch (e) {
dispatch(setAlert(e.response.data.msg, 'error'));
}
};
<file_sep>function convertToEuro(priceHT) {
return priceHT / 100;
}
function addTva(priceHT) {
const TVA = 20 / 100;
const montantTVA = priceHT * TVA;
return priceHT + montantTVA;
}
function formatPrice(priceHT) {
return addTva(convertToEuro(priceHT)).toFixed(2);
}
function ucfirst(word) {
if (word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
}
export { ucfirst, formatPrice, convertToEuro };
<file_sep>import { CREATE_ROLE, GET_ROLES } from '../actions/types';
/**
*
* @type {{roles: *[]}}
*/
const initialState = {
roles: [],
};
export default function categories(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_ROLES:
return {
...state,
roles: payload,
};
case CREATE_ROLE:
return {
...state,
roles: [...state.roles, payload.category],
};
default:
return state;
}
}
<file_sep>import "react-native-gesture-handler";
import React, { useEffect, useState, Fragment } from "react";
import { NavigationContainer } from "@react-navigation/native";
import {
createDrawerNavigator,
DrawerContentScrollView,
DrawerItemList,
} from "@react-navigation/drawer";
import { createStackNavigator } from "@react-navigation/stack";
const { Navigator, Screen } = createStackNavigator();
import { StyleSheet, Text, View, ActivityIndicator } from "react-native";
import Home from "./src/components/Home";
import RegisterForm from "./src/components/RegisterForm";
import LoginForm from "./src/components/LoginForm";
import Shop from "./src/components/Shop";
import store from "./src/store";
import { loadUser } from "./src/actions/auth";
import { Provider } from "react-redux";
import ProductDetail from "./src/components/ProductDetail";
const Drawer = createDrawerNavigator();
export default function App() {
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
store.dispatch(loadUser());
setTimeout(() => {
setIsLoading(false);
}, 500);
}, []);
return (
<Provider store={store}>
{isLoading ? (
<View style={styles.container}>
<ActivityIndicator size={"large"} />
</View>
) : (
<View style={styles.container}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="home">
<Drawer.Screen
name="home"
component={Home}
options={{
title: "Welcome !",
}}
/>
<Drawer.Screen name="Shop" component={Shop} />
<Drawer.Screen name="Register" component={RegisterForm} />
<Drawer.Screen name="Login" component={LoginForm} />
<Drawer.Screen name="productDetail" component={ProductDetail} />
</Drawer.Navigator>
</NavigationContainer>
</View>
)}
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
},
});
| 8a845116243d15bd356b4cbf49a1a983e63e11ba | [
"JavaScript"
] | 13 | JavaScript | Kenshirosan/react-native-shop | 5b1ba84cee2c29c09cf042bebd0f5279d1d2d07f | f81979d065b589ff723b298c5db70932c7156933 |
refs/heads/master | <repo_name>shakshimaheshwari/MostPopularSuperHeroAndDegreeofSeperation<file_sep>/README.md
# MostPopularSuperHeroAndDegreeofSeperation
Examined the Marvel Data-set to find out the most popular superhero in a densely connected Social graph. The idea of Social graph in this data-set is that the two super heroes are friends in this social graph if they co-exist in the same comic-book. The most popular super-hero is defined on the basis of this idea that with how many super-hero characters does it coexist in the comic books. Also programmed the concept of Breadth first Search in order to find out the degree of seperation between the source and the target super-heroes
#Pre-requisities
* Install Apache Spark
* Install Python
* Install pyCharm or any other IDE of your choice
#Procedure
```
$ Import collections
$ Import SparkContext and SparkConf
$ Create an RDD by calling sc.textFile
$ Perform operations on RDD to achieve the objective
$ while executing spark program write **spark-submit <filename.py>** on the command line
```
# Data-set description
* **Marvel-Graph.txt**:- This data-set consists of the super-heroes ids wherein the first id represnt the super-hero id and the rest of the line represents the super-heroes to whom it is friends with
* **Marvel-Names.txt**:- This data-set consist of the names of the super-heroes against their IDs
#Deployment
You can deploy it on Amazon's EMR
<file_sep>/MostPopularSuperHero/mostpopularsuperhero.py
from pyspark import SparkConf, SparkContext
import collections
def parseLine(text):
fields = text.split()
superheroId = int(fields[0])
return (superheroId, len(fields)-1)
def parseNames(text):
fields = text.split('\"')
return (int(fields[0]), fields[1].encode("utf-8"))
conf = SparkConf().setMaster("local").setAppName("SuperHero")
sc = SparkContext(conf = conf)
input = sc.textFile("C:/Sakshi/SparkCourse/MostPopularSuperHero/Marvel-Graph.txt")
superHeroIds = input.map(parseLine)
names = sc.textFile("C:/Sakshi/SparkCourse/MostPopularSuperHero/Marvel-Names.txt")
namesRdd = names.map(parseNames)
totalCount = superHeroIds.reduceByKey(lambda x,y : x+y)
flippedCount = totalCount.map(lambda (x,y) : (y,x))
mostPouplar= flippedCount.max()
mostPopularName = namesRdd.lookup(mostPouplar[1])[0]
print mostPopularName + " is most popular superhero , with" + \
str(mostPouplar[0]) + " co-apperances"
| cb5fc1de657ace1d11bb1207f37887df3cd65421 | [
"Markdown",
"Python"
] | 2 | Markdown | shakshimaheshwari/MostPopularSuperHeroAndDegreeofSeperation | 6397d6638651d576e106aa11d83c18546d964f37 | 40c40cea04d71c66da29cd68eb255a941a5fbf1b |
refs/heads/master | <file_sep>CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_creation_date` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01',
`user_level` int(11) NOT NULL DEFAULT '1',
`user_xp` int(11) NOT NULL DEFAULT '0',
`user_trophies` int(11) NOT NULL DEFAULT '1000',
`user_lastlogin_date` timestamp NULL DEFAULT '1970-01-01 00:00:01',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=152 DEFAULT CHARSET=latin1<file_sep>CREATE TABLE `devices` (
`device_id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT '0',
`device_model` varchar(45) NOT NULL,
`device_os_version` varchar(45) NOT NULL,
`device_platform` varchar(45) NOT NULL,
`device_usage_time` int(11) NOT NULL DEFAULT '0',
`device_core_version` varchar(45) NOT NULL,
`device_app_version` varchar(45) NOT NULL,
`device_first_ip` varchar(45) NOT NULL,
`device_creation_date` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01',
`device_update_date` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01',
`device_blocked` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`device_id`),
UNIQUE KEY `device_id_UNIQUE` (`device_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1<file_sep>package com.mozaicgames.executors;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.CBackendRequestExecutor;
import com.mozaicgames.core.CBackendRequestExecutorParameters;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.utils.CBackendQueryGetUserGameData;
import com.mozaicgames.utils.CBackendQueryGetUserWalletData;
import com.mozaicgames.utils.CSqlBuilderInsert;
import com.mozaicgames.utils.CSqlBuilderUpdate;
public class CRequestExecutorRegisterGameResult extends CBackendRequestExecutor
{
@Override
public boolean isSessionTokenValidationNeeded()
{
return true;
}
@Override
public JSONObject execute(JSONObject jsonData, CBackendRequestExecutorParameters parameters) throws CBackendRequestException
{
Connection sqlConnection = null;
PreparedStatement preparedStatementInsert = null;
PreparedStatement preparedStatementUpdateData = null;
PreparedStatement preparedStatementUpdateWallet = null;
try
{
sqlConnection = parameters.getSqlDataSource().getConnection();
sqlConnection.setAutoCommit(false);
JSONArray jsonGamesDataArray = jsonData.getJSONArray(CRequestKeys.mKeyGameDataVector);
final int jsonGamesDataArrayLength = jsonGamesDataArray.length();
if (jsonGamesDataArrayLength == 0)
{
throw new JSONException("Invalid array data!");
}
final JSONObject jsonCurrentUserData = CBackendQueryGetUserGameData.getUserData(parameters.getUserId(), parameters.getSqlDataSource());
int currentUserLevel = jsonCurrentUserData.getInt(CRequestKeys.mKeyUserDataLevel);
int currentUserXp = jsonCurrentUserData.getInt(CRequestKeys.mKeyUserDataXp);
int currentUserTrophies = jsonCurrentUserData.getInt(CRequestKeys.mKeyUserDataTrophies);
final JSONObject jsonCurrentUserWallet = CBackendQueryGetUserWalletData.getUserGameData(parameters.getUserId(), parameters.getDevicePlatform(), parameters.getSqlDataSource());
int currentWalletTokens = jsonCurrentUserWallet.getInt(CRequestKeys.mKeyUserWalletDataTokensNum);
int currentWalletJokers = jsonCurrentUserWallet.getInt(CRequestKeys.mKeyUserWalletDataJokersNum);
int currentWalletCredits = jsonCurrentUserWallet.getInt(CRequestKeys.mKeyUserWalletDataCreditsNum);
JSONArray gamesRewardsVector = new JSONArray();
for (int i = 0; i < jsonGamesDataArrayLength; i++)
{
JSONObject jsonGameData = jsonGamesDataArray.getJSONObject(i);
final Timestamp creationTime = new Timestamp(System.currentTimeMillis());
final int gameType = jsonGameData.getInt(CRequestKeys.mKeyGameType);
final String gameSeed = jsonGameData.getString(CRequestKeys.mKeyGameSeed);
final int gameSeedSource = jsonGameData.getInt(CRequestKeys.mKeyGameSeedSource);
int playerPlace = jsonGameData.getInt(CRequestKeys.mKeyGamePlayerPlace);
final int playerScore = jsonGameData.getInt(CRequestKeys.mKeyGamePlayerScore);
final int playerStars = jsonGameData.getInt(CRequestKeys.mKeyGamePlayerStars);
final int gameDuration = jsonGameData.getInt(CRequestKeys.mKeyGameDuration);
final int gameReuslt = jsonGameData.getInt(CRequestKeys.mKeyGameFinishResult);
final int numDeckRefreshed = jsonGameData.getInt(CRequestKeys.mKeyGameDeckRefreshNum);
final int numUsedActions = jsonGameData.getInt(CRequestKeys.mKeyGameActionsUsedNum);
final int numUsedHints = jsonGameData.getInt(CRequestKeys.mKeyGameHintsUsedNum);
final int numUsedJockers = jsonGameData.getInt(CRequestKeys.mKeyGameJokersUsedNum);
final int foundationRank1 = jsonGameData.getInt(CRequestKeys.mKeyGameFoundationRank1);
final int foundationRank2 = jsonGameData.getInt(CRequestKeys.mKeyGameFoundationRank2);
final int foundationRank3 = jsonGameData.getInt(CRequestKeys.mKeyGameFoundationRank3);
final int foundationRank4 = jsonGameData.getInt(CRequestKeys.mKeyGameFoundationRank4);
final int gainedXp = 1 + foundationRank1 + foundationRank2 + foundationRank3 + foundationRank4 + Math.min(gameDuration, 360) / 10;
int gainedTrophies = 0;
int gainedTokens = 0;
int gainedJokers = 0;
int gainedCredits = 1;
int gainedLevel = 0;
boolean isFoundation4k = foundationRank1 == 14 && foundationRank2 == 14 && foundationRank3 == 14 && foundationRank4 == 14;
CSqlBuilderInsert sqlBuilderInsert = new CSqlBuilderInsert()
.into(CDatabaseKeys.mKeyTableGameResultsTableName)
.value(CDatabaseKeys.mKeyTableGameResultsSessionToken, parameters.getSessionToken())
.value(CDatabaseKeys.mKeyTableGameResultsUserId, Integer.toString(parameters.getUserId()))
.value(CDatabaseKeys.mKeyTableGameResultsCreationDate, creationTime.toString())
.value(CDatabaseKeys.mKeyTableGameResultsType, Integer.toString(gameType))
.value(CDatabaseKeys.mKeyTableGameResultsSeed, gameSeed)
.value(CDatabaseKeys.mKeyTableGameResultsPlayerPlace, Integer.toString(playerPlace))
.value(CDatabaseKeys.mKeyTableGameResultsPlayerScore, Integer.toString(playerScore))
.value(CDatabaseKeys.mKeyTableGameResultsPlayerStars, Integer.toString(playerStars))
.value(CDatabaseKeys.mKeyTableGameResultsSeedSource, Integer.toString(gameSeedSource))
.value(CDatabaseKeys.mKeyTableGameResultsDuration, Integer.toString(gameDuration))
.value(CDatabaseKeys.mKeyTableGameResultsCompleteResult, Integer.toString(gameReuslt))
.value(CDatabaseKeys.mKeyTableGameResultsDeckRefreshNum, Integer.toString(numDeckRefreshed))
.value(CDatabaseKeys.mKeyTableGameResultsUsedActionsNum, Integer.toString(numUsedActions))
.value(CDatabaseKeys.mKeyTableGameResultsUsedHintsNum, Integer.toString(numUsedHints))
.value(CDatabaseKeys.mKeyTableGameResultsUsedJokersNum, Integer.toString(numUsedJockers))
.value(CDatabaseKeys.mKeyTableGameResultsFoundationRank1, Integer.toString(foundationRank1))
.value(CDatabaseKeys.mKeyTableGameResultsFoundationRank2, Integer.toString(foundationRank2))
.value(CDatabaseKeys.mKeyTableGameResultsFoundationRank3, Integer.toString(foundationRank3))
.value(CDatabaseKeys.mKeyTableGameResultsFoundationRank4, Integer.toString(foundationRank4));
final String strQueryInsert = sqlBuilderInsert.toString();
preparedStatementInsert = sqlConnection.prepareStatement(strQueryInsert, PreparedStatement.RETURN_GENERATED_KEYS);
int affectedRows = preparedStatementInsert.executeUpdate();
if (affectedRows == 0)
{
throw new SQLException("Nothing updated in database!");
}
switch (gameReuslt)
{
default:
case 0: // application closed
case 1: // user quit
gainedTrophies = -12;
playerPlace = 4;
break;
case 2: // user finished out of time
case 3: // user finished freeze
case 4: // user finished freeze then quit
case 5: // user finished foundation complete
if (playerPlace == 1)
{
// user finished first
gainedTrophies = 11;
double randNumber = Math.random();
if (randNumber < 0.4)
{
gainedTokens ++;
if (randNumber < 0.2)
{
gainedCredits ++;
}
}
}
else if (playerPlace == 2)
{
// user finished second
gainedTrophies = 6;
double randNumber = Math.random();
if (randNumber < 0.3)
{
gainedCredits ++;
}
}
else if (playerPlace == 3)
{
// user lost
gainedTrophies = -6;
}
else
{
// user lost
gainedTrophies = -12;
}
if (isFoundation4k)
{
gainedTrophies += 10;
gainedCredits ++;
double randNumber = Math.random();
if (randNumber < 0.5)
{
gainedCredits ++;
if (numUsedJockers > 3)
{
gainedJokers ++;
}
if (randNumber < 0.2)
{
gainedCredits ++;
gainedJokers ++;
if (randNumber < 0.1)
{
gainedJokers ++;
if (randNumber < 0.05)
{
gainedJokers ++;
}
}
}
}
}
break;
}
currentUserTrophies += gainedTrophies;
currentUserXp += gainedXp;
currentWalletTokens += gainedTokens;
currentWalletJokers += gainedJokers;
currentWalletCredits += gainedCredits;
currentUserTrophies = Math.max(currentUserTrophies, 0);
// calculate new user level
int maxXpForThisLevel = (int) (100 * Math.pow(currentUserLevel, 2) - 1);
while (currentUserXp > maxXpForThisLevel)
{
gainedLevel ++;
currentUserXp -= maxXpForThisLevel;
maxXpForThisLevel = (int) (100 * Math.pow(currentUserLevel + gainedLevel, 2) - 1);
}
currentUserLevel += gainedLevel;
// jsonResponse.put(CRequestKeys.mKeyUserDataLevel, currentUserLevel);
JSONObject jsonGameResponse = new JSONObject();
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedXp, gainedXp);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedLevel, gainedLevel);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedLevelMaxXp, maxXpForThisLevel);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedTrophie, gainedTrophies);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedCredits, gainedCredits);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedJokers, gainedJokers);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedTokens, gainedTokens);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedPlace, playerPlace);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedScore, playerScore);
jsonGameResponse.put(CRequestKeys.mKeyGameRewardsGainedStars, playerStars);
gamesRewardsVector.put(jsonGameResponse);
}
CSqlBuilderUpdate sqlBuilderUpdateUserData = new CSqlBuilderUpdate()
.table(CDatabaseKeys.mKeyTableUsersTableName)
.set(CDatabaseKeys.mKeyTableUsersUserLevel, Integer.toString(currentUserLevel))
.set(CDatabaseKeys.mKeyTableUsersUserXp, Integer.toString(currentUserXp))
.set(CDatabaseKeys.mKeyTableUsersUserTrophies, Integer.toString(currentUserTrophies))
.where(CDatabaseKeys.mKeyTableUsersUserId + "=" + parameters.getUserId());
final String strQueryUpdateUsers = sqlBuilderUpdateUserData.toString();
preparedStatementUpdateData = sqlConnection.prepareStatement(strQueryUpdateUsers, PreparedStatement.RETURN_GENERATED_KEYS);
final int affectedRowsUpdateData = preparedStatementUpdateData.executeUpdate();
if (affectedRowsUpdateData == 0)
{
throw new SQLException("Nothing updated in database!");
}
CSqlBuilderUpdate sqlBuilderUpdateUserWallet = new CSqlBuilderUpdate()
.table(CDatabaseKeys.mKeyTableUsersWalletDataTableName)
.set(CDatabaseKeys.mKeyTableUsersWalletDataTokensNum, Integer.toString(currentWalletTokens))
.set(CDatabaseKeys.mKeyTableUsersWalletDataJokersNum, Integer.toString(currentWalletJokers))
.set(CDatabaseKeys.mKeyTableUsersWalletDataCreditsNum, Integer.toString(currentWalletCredits))
.where(CDatabaseKeys.mKeyTableUsersWalletDataUserId + "=" + parameters.getUserId());
final String strQueryUdpdateWallet = sqlBuilderUpdateUserWallet.toString();
preparedStatementUpdateWallet = sqlConnection.prepareStatement(strQueryUdpdateWallet, PreparedStatement.RETURN_GENERATED_KEYS);
final int affectedRowsUpdateWallet = preparedStatementUpdateWallet.executeUpdate();
if (affectedRowsUpdateWallet == 0)
{
throw new SQLException("Nothing updated in database!");
}
JSONObject jsonResponse = new JSONObject();
jsonResponse.put(CRequestKeys.mKeyGameRewardsVector, gamesRewardsVector);
sqlConnection.commit();
return toJSONObject(EBackendResponsStatusCode.STATUS_OK, jsonResponse);
}
catch (JSONException e)
{
throw new CBackendRequestException(EBackendResponsStatusCode.INVALID_DATA, "Invalid data!");
}
catch (SQLException e)
{
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, e.getMessage());
}
finally
{
if (preparedStatementInsert != null)
{
try
{
preparedStatementInsert.close();
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
if (preparedStatementUpdateData != null)
{
try
{
preparedStatementUpdateData.close();
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
if (preparedStatementUpdateWallet != null)
{
try
{
preparedStatementUpdateWallet.close();
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
}
<file_sep>CREATE TABLE `users_wallet` (
`wallet_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`device_platform` varchar(45) NOT NULL,
`wallet_credits_num` int(11),
`wallet_jokers_num` int(11),
`wallet_tokens_num` int(11),
PRIMARY KEY (`wallet_id`),
UNIQUE KEY `wallet_id_UNIQUE` (`wallet_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1<file_sep>CREATE TABLE `users_settings` (
`settings_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`settings_magnet_on` tinyint(4),
`settings_left_handed_on` tinyint(4),
`settings_music_on` tinyint(4),
`settings_sfx_on` tinyint(4),
PRIMARY KEY (`settings_id`),
UNIQUE KEY `settings_id_UNIQUE` (`settings_id`),
UNIQUE KEY `user_id_UNIQUE` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1<file_sep>package com.mozaicgames.utils;
import com.mozaicgames.core.EBackendResponsStatusCode;
public class CBackendQueryResponse {
private final EBackendResponsStatusCode mStatus;
private final String mBody;
public CBackendQueryResponse(EBackendResponsStatusCode status, String body)
{
mStatus = status;
mBody = body;
}
public EBackendResponsStatusCode getCode()
{
return mStatus;
}
public String getBody()
{
return mBody;
}
}
<file_sep>package com.mozaicgames.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.executors.CDatabaseKeys;
import com.mozaicgames.executors.CRequestKeys;
public class CBackendQueryGetUserSettingsData
{
private CBackendQueryGetUserSettingsData()
{
}
static public JSONObject getUserGameData(int userId, DataSource dataSource) throws CBackendRequestException
{
Connection sqlConnection = null;
PreparedStatement preparedStatementSelect = null;
try {
sqlConnection = dataSource.getConnection();
sqlConnection.setAutoCommit(false);
final CSqlBuilderSelect sqlBuilderSelect = new CSqlBuilderSelect()
.from(CDatabaseKeys.mKeyTableUsersSettingsTableName)
.column(CDatabaseKeys.mKeyTableUsersSettingsMagnetOn)
.column(CDatabaseKeys.mKeyTableUsersSettingsLeftHandedOn)
.column(CDatabaseKeys.mKeyTableUsersSettingsMusicOn)
.column(CDatabaseKeys.mKeyTableUsersSettingsSfxOn)
.where(CDatabaseKeys.mKeyTableUsersSettingsUserId + "=" + userId);
// find the session in the database first
final String strQuerySelect = sqlBuilderSelect.toString();
preparedStatementSelect = sqlConnection.prepareStatement(strQuerySelect);
ResultSet response = preparedStatementSelect.executeQuery();
if (response != null && response.next())
{
final short dataMagnetOn = response.getShort(1);
final short dataLeftHandedOn = response.getShort(2);
final short dataMusicOn = response.getShort(3);
final short dataSfxOn = response.getShort(4);
JSONObject responseUserData = new JSONObject();
responseUserData.put(CRequestKeys.mKeyUserSettingsMagnetOn, dataMagnetOn);
responseUserData.put(CRequestKeys.mKeyUserSettingsLeftHandedOn, dataLeftHandedOn);
responseUserData.put(CRequestKeys.mKeyUserSettingsMusicOn, dataMusicOn);
responseUserData.put(CRequestKeys.mKeyUserSettingsSfxOn, dataSfxOn);
return responseUserData;
}
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementSelect != null)
{
try
{
preparedStatementSelect.close();
preparedStatementSelect = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, "Internal error");
}
}
<file_sep>package com.mozaicgames.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.executors.CDatabaseKeys;
import com.mozaicgames.executors.CRequestKeys;
public class CBackendQueryGetUserWalletData
{
private CBackendQueryGetUserWalletData()
{
}
static public JSONObject getUserGameData(int userId, String devicePlatform, DataSource dataSource) throws CBackendRequestException
{
Connection sqlConnection = null;
PreparedStatement preparedStatementSelect = null;
try {
sqlConnection = dataSource.getConnection();
sqlConnection.setAutoCommit(false);
final CSqlBuilderSelect sqlBuilderSelect = new CSqlBuilderSelect()
.from(CDatabaseKeys.mKeyTableUsersWalletDataTableName)
.column(CDatabaseKeys.mKeyTableUsersWalletDataCreditsNum)
.column(CDatabaseKeys.mKeyTableUsersWalletDataJokersNum)
.column(CDatabaseKeys.mKeyTableUsersWalletDataTokensNum)
.where(CDatabaseKeys.mKeyTableUsersWalletDataUserId + "='" + userId + "' and " + CDatabaseKeys.mKeyTableUsersWalletDataDevicePlatform + "='" + devicePlatform + "'");
// find the session in the database first
final String strQuerySelect = sqlBuilderSelect.toString();
preparedStatementSelect = sqlConnection.prepareStatement(strQuerySelect);
ResultSet response = preparedStatementSelect.executeQuery();
if (response != null && response.next())
{
final int dataCreditsNum = response.getInt(1);
final int dataJockersNum = response.getInt(2);
final int dataTokensNum = response.getInt(3);
JSONObject responseUserData = new JSONObject();
responseUserData.put(CRequestKeys.mKeyUserWalletDataCreditsNum, dataCreditsNum);
responseUserData.put(CRequestKeys.mKeyUserWalletDataJokersNum, dataJockersNum);
responseUserData.put(CRequestKeys.mKeyUserWalletDataTokensNum, dataTokensNum);
return responseUserData;
}
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementSelect != null)
{
try
{
preparedStatementSelect.close();
preparedStatementSelect = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, "Internal error");
}
}
<file_sep># mozabackend
A simple backend server I developed for my games.
<file_sep>CREATE TABLE `game_results` (
`result_id` bigint(20) NOT NULL AUTO_INCREMENT,
`session_token` varchar(45) NOT NULL,
`user_id` int(11) NOT NULL,
`creation_date` timestamp NOT NULL,
`type` int(11) DEFAULT '0',
`seed` varchar(45) DEFAULT '0',
`seed_source` int(11) DEFAULT '0',
`duration` int(11) DEFAULT '0',
`complete_result` int(11) DEFAULT '0',
`player_place` int(11) DEFAULT '0',
`player_score` int(11) DEFAULT '0',
`player_stars` int(11) DEFAULT '0',
`deck_refresh_num` int(11) DEFAULT '0',
`used_actions_num` int(11) DEFAULT '0',
`used_hints_num` int(11) DEFAULT '0',
`used_jokers_num` int(11) DEFAULT '0',
`gained_xp` int(11) DEFAULT '0',
`foundation_rank_1` int(11) DEFAULT '0',
`foundation_rank_2` int(11) DEFAULT '0',
`foundation_rank_3` int(11) DEFAULT '0',
`foundation_rank_4` int(11) DEFAULT '0',
PRIMARY KEY (`result_id`),
UNIQUE KEY `result_id_UNIQUE` (`result_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1<file_sep>#!/bin/sh -
#scp scripts/launch.sh root@192.168.127.12:/dev/
scp bin/mozabackendserver.jar root@192.168.127.12:/home/dev/<file_sep>package com.mozaicgames.utils;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class CBackendAdvancedEncryptionStandard
{
private String encryptionKey;
private String encryptionAlgorithm;
public CBackendAdvancedEncryptionStandard(String encryptionKey, String encryptionAlgorithm)
{
this.encryptionKey = encryptionKey;
this.encryptionAlgorithm = encryptionAlgorithm;
}
public String encrypt(String plainText) throws Exception
{
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.encodeBase64String(encryptedBytes);
}
public String decrypt(String encrypted) throws Exception
{
Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
byte[] plainBytes = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(plainBytes);
}
private Cipher getCipher(int cipherMode) throws Exception
{
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), encryptionKey.getBytes(), 64, 128);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), encryptionAlgorithm);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(cipherMode, key);
return cipher;
}
}
<file_sep>#!/bin/sh -
scp bin/mozabackendserver.jar root@172.16.31.10:/home/prod/<file_sep>package com.mozaicgames.utils;
import java.util.List;
public class CSqlBuilder
{
public CSqlBuilder()
{
}
protected void appendList(StringBuilder sql, List<String> list, String init, String sep)
{
boolean first = true;
for (String s : list)
{
if (first)
{
sql.append(init);
}
else
{
sql.append(sep);
}
sql.append(s);
first = false;
}
}
@Override
public String toString()
{
return "CSqlBuilder";
}
}
<file_sep>package com.mozaicgames.executors;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.CBackendRequestExecutor;
import com.mozaicgames.core.CBackendRequestExecutorParameters;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.utils.CBackendAdvancedEncryptionStandard;
import com.mozaicgames.utils.CSqlBuilderInsert;
public class CRequestExecutorRegisterDevice extends CBackendRequestExecutor
{
@Override
public JSONObject execute(JSONObject jsonData, CBackendRequestExecutorParameters parameters) throws CBackendRequestException
{
String deviceModel = null;
String deviceOsVerrsion = null;
String devicePlatform = null;
String deviceClientCoreVersion = null;
String deviceClientAppVersion = null;
try
{
deviceModel = jsonData.getString(CRequestKeys.mKeyDeviceModel);
deviceOsVerrsion= jsonData.getString(CRequestKeys.mKeyDeviceOsVersion);
devicePlatform = jsonData.getString(CRequestKeys.mKeyDevicePlatform);
deviceClientCoreVersion = jsonData.getString(CRequestKeys.mKeyDeviceClientCoreVersion);
deviceClientAppVersion = jsonData.getString(CRequestKeys.mKeyDeviceClientAppVersion);
}
catch (JSONException e)
{
// bad input
// return database connection error - status retry
throw new CBackendRequestException(EBackendResponsStatusCode.INVALID_DATA, "Invalid input data!");
}
Connection sqlConnection = null;
PreparedStatement preparedStatementInsert = null;
//@TODO
// check input parameters
try
{
sqlConnection = parameters.getSqlDataSource().getConnection();
sqlConnection.setAutoCommit(false);
final String remoteAddress = parameters.getRemoteAddress();
final Timestamp creationTime = new Timestamp(System.currentTimeMillis());
final CSqlBuilderInsert sqlBuilderInsert = new CSqlBuilderInsert()
.into(CDatabaseKeys.mKeyTableDevicesTableName)
.value(CDatabaseKeys.mKeyTableDevicesModel, deviceModel)
.value(CDatabaseKeys.mKeyTableDevicesOsVersion, deviceOsVerrsion)
.value(CDatabaseKeys.mKeyTableDevicesPlatform, devicePlatform)
.value(CDatabaseKeys.mKeyTableDevicesClientCoreVersion, deviceClientCoreVersion)
.value(CDatabaseKeys.mKeyTableDevicesClientAppVersion, deviceClientAppVersion)
.value(CDatabaseKeys.mKeyTableDevicesFirstIp, remoteAddress)
.value(CDatabaseKeys.mKeyTableDevicesCreationDate, creationTime.toString())
.value(CDatabaseKeys.mKeyTableDevicesUpdateDate, creationTime.toString());
final String strQueryInsert = sqlBuilderInsert.toString();
preparedStatementInsert = sqlConnection.prepareStatement(strQueryInsert, PreparedStatement.RETURN_GENERATED_KEYS);
int affectedRows = preparedStatementInsert.executeUpdate();
if (affectedRows == 0)
{
throw new Exception("Nothing updated in database!");
}
// get last user id
long newDeviceId = 0;
ResultSet restultLastInsert = preparedStatementInsert.getGeneratedKeys();
if (restultLastInsert.next())
{
newDeviceId = restultLastInsert.getLong(1);
}
final CBackendAdvancedEncryptionStandard encripter = parameters.getEncriptionStandard();
final String newUUID = encripter.encrypt(String.valueOf(newDeviceId));
JSONObject jsonResponse = new JSONObject();
jsonResponse.put(CRequestKeys.mKeyClientDeviceToken, newUUID);
sqlConnection.commit();
return toJSONObject(EBackendResponsStatusCode.STATUS_OK, jsonResponse);
}
catch (Exception e)
{
// error processing statement
// return statement error - status error
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, e.getMessage());
}
finally
{
if (preparedStatementInsert != null)
{
try
{
preparedStatementInsert.close();
preparedStatementInsert = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
}
<file_sep>package com.mozaicgames.utils;
import java.util.ArrayList;
import java.util.List;
public class CSqlBuilderInsert extends CSqlBuilder
{
private final List<String> mColumns = new ArrayList<String>();
private final List<String> mTables = new ArrayList<String>();
private final List<String> mValues = new ArrayList<String>();
public CSqlBuilderInsert into(String name)
{
mTables.add(name);
return this;
}
public CSqlBuilderInsert value(String name, String value)
{
mColumns.add(name);
mValues.add("'" + value + "'");
return this;
}
@Override
public String toString() {
StringBuilder sql = new StringBuilder("insert into ");
appendList(sql, mTables, "", ", ");
appendList(sql, mColumns, " ( ", ", ");
appendList(sql, mValues, " ) values ( ", ", ");
sql.append(");");
return sql.toString();
}
}
<file_sep>#!/bin/sh -
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="8000" -cp mozabackendserver.jar:libs/* Main -p 8081<file_sep>package com.mozaicgames.utils;
import java.util.ArrayList;
import java.util.List;
public class CSqlBuilderUpdate extends CSqlBuilder
{
private final List<String> mColumns = new ArrayList<String>();
private final List<String> mTables = new ArrayList<String>();
private final List<String> mJoins = new ArrayList<String>();
private final List<String> mLeftJoins = new ArrayList<String>();
private final List<String> mWheres = new ArrayList<String>();
private final List<String> mOrderBys = new ArrayList<String>();
private final List<String> mGroupBys = new ArrayList<String>();
private final List<String> mHavings = new ArrayList<String>();
private int mLimit = 0;
private String mOrderByType = "";
public CSqlBuilderUpdate()
{
super();
}
public CSqlBuilderUpdate table(String name)
{
mTables.add(name);
return this;
}
public CSqlBuilderUpdate set(String name, String value)
{
mColumns.add(name + "='" + value + "'");
return this;
}
public CSqlBuilderUpdate update(String name, String value, String sign)
{
mColumns.add(name + "=" + name + sign + "'" + value + "'");
return this;
}
public CSqlBuilderUpdate where(String expr)
{
mWheres.add(expr);
return this;
}
public CSqlBuilderUpdate groupBy(String expr)
{
mGroupBys.add(expr);
return this;
}
public CSqlBuilderUpdate having(String expr)
{
mHavings.add(expr);
return this;
}
public CSqlBuilderUpdate join(String join)
{
mJoins.add(join);
return this;
}
public CSqlBuilderUpdate leftJoin(String join)
{
mLeftJoins.add(join);
return this;
}
public CSqlBuilderUpdate orderBy(String name)
{
mOrderBys.add(name);
return this;
}
public CSqlBuilderUpdate orderType(String exp)
{
mOrderByType = exp;
return this;
}
public CSqlBuilderUpdate limit(int expr)
{
mLimit = expr;
return this;
}
@Override
public String toString() {
StringBuilder sql = new StringBuilder("update ");
appendList(sql, mTables, "", ", ");
appendList(sql, mColumns, " set ", ", ");
appendList(sql, mJoins, " join ", " join ");
appendList(sql, mLeftJoins, " left join ", " left join ");
appendList(sql, mWheres, " where ", " and ");
appendList(sql, mGroupBys, " group by ", ", ");
appendList(sql, mHavings, " having ", " and ");
appendList(sql, mOrderBys, " order by ", ", ");
if (mOrderBys.size() > 0)
{
sql.append(" " + mOrderByType);
}
if (mLimit > 0)
{
sql.append(" limit " + mLimit);
}
sql.append(";");
return sql.toString();
}
}
<file_sep>package com.mozaicgames.core;
public enum EBackendResponsStatusCode
{
BAD_REQUEST (0),
STATUS_OK (2000),
INVALID_REQUEST (4001),
INVALID_DATA (4002),
INVALID_TOKEN_DEVICE (4010),
INVALID_TOKEN_USER (4020),
INVALID_TOKEN_SESSION_KEY (4030),
INTERNAL_ERROR (5000),
RETRY_LATER (8000),
CLIENT_OUT_OF_DATE (9000),
CLIENT_REJECTED (1000);
private final int mValue;
EBackendResponsStatusCode(int val)
{
mValue = val;
}
public int getValue()
{
return mValue;
}
}
<file_sep>CREATE TABLE `sessions` (
`session_id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`device_id` bigint(20) NOT NULL,
`session_token` varchar(45) NOT NULL,
`session_creation_date` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01',
`session_expire_date` timestamp NOT NULL DEFAULT '1970-01-01 00:00:01',
`session_ip` varchar(45) NOT NULL,
`session_platform` varchar(45) NOT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;<file_sep>package com.mozaicgames.executors;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.CBackendRequestExecutor;
import com.mozaicgames.core.CBackendRequestExecutorParameters;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.utils.CSqlBuilderUpdate;
public class CRequestExecutorUpdateUserSettings extends CBackendRequestExecutor
{
@Override
public boolean isSessionTokenValidationNeeded()
{
return true;
}
@Override
public JSONObject execute(JSONObject jsonData, CBackendRequestExecutorParameters parameters) throws CBackendRequestException
{
Connection sqlConnection = null;
PreparedStatement preparedStatementUpdate = null;
try
{
sqlConnection = parameters.getSqlDataSource().getConnection();
sqlConnection.setAutoCommit(false);
CSqlBuilderUpdate sqlBuilderUpdate = new CSqlBuilderUpdate()
.table(CDatabaseKeys.mKeyTableUsersSettingsTableName)
.where(CDatabaseKeys.mKeyTableUsersSettingsUserId + "=" + parameters.getUserId());
if (jsonData.has(CRequestKeys.mKeyUserSettingsMagnetOn))
{
final int deviceMagnetOn = jsonData.getBoolean(CRequestKeys.mKeyUserSettingsMagnetOn) ? 1 : 0;
sqlBuilderUpdate.set(CDatabaseKeys.mKeyTableUsersSettingsMagnetOn, Integer.toString(deviceMagnetOn));
}
if (jsonData.has(CRequestKeys.mKeyUserSettingsLeftHandedOn))
{
final int deviceLeftHandedOn = jsonData.getBoolean(CRequestKeys.mKeyUserSettingsLeftHandedOn) ? 1 : 0;
sqlBuilderUpdate.set(CDatabaseKeys.mKeyTableUsersSettingsLeftHandedOn, Integer.toString(deviceLeftHandedOn));
}
if (jsonData.has(CRequestKeys.mKeyUserSettingsMusicOn))
{
final int deviceMusicOn = jsonData.getBoolean(CRequestKeys.mKeyUserSettingsMusicOn) ? 1 : 0;
sqlBuilderUpdate.set(CDatabaseKeys.mKeyTableUsersSettingsMusicOn, Integer.toString(deviceMusicOn));
}
if (jsonData.has(CRequestKeys.mKeyUserSettingsSfxOn))
{
final int deviceSfxOn = jsonData.getBoolean(CRequestKeys.mKeyUserSettingsSfxOn) ? 1 : 0;
sqlBuilderUpdate.set(CDatabaseKeys.mKeyTableUsersSettingsSfxOn, Integer.toString(deviceSfxOn));
}
final String strQueryUpdate = sqlBuilderUpdate.toString();
preparedStatementUpdate = sqlConnection.prepareStatement(strQueryUpdate, PreparedStatement.RETURN_GENERATED_KEYS);
int affectedRows = preparedStatementUpdate.executeUpdate();
if (affectedRows == 0)
{
throw new Exception("Nothing updated in database!");
}
JSONObject jsonResponse = new JSONObject();
sqlConnection.commit();
return toJSONObject(EBackendResponsStatusCode.STATUS_OK, jsonResponse);
}
catch (Exception e)
{
// error processing statement
// return statement error - status error
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, e.getMessage());
}
finally
{
if (preparedStatementUpdate != null)
{
try
{
preparedStatementUpdate.close();
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
}
<file_sep>package com.mozaicgames.core;
import javax.sql.DataSource;
import com.mozaicgames.utils.CBackendAdvancedEncryptionStandard;
import com.mozaicgames.utils.CBackendSessionManager;
public class CBackendRequestExecutorParameters
{
private final String mRemoteAddress;
private final CBackendAdvancedEncryptionStandard mEncriptionStandard;
private final DataSource mSqlDataSource;
private final CBackendSessionManager mSessionManager;
private final String mClientCoreVersion;
private final String mClientAppVersion;
private final int mUserId;
private final long mDeviceId;
private final long mSessionId;
private final String mSessionToken;
private final String mDevicePlatform;
public CBackendRequestExecutorParameters(final String remoteAddress,
final CBackendAdvancedEncryptionStandard encriptionStandard,
final DataSource sqlDataSource,
final CBackendSessionManager sessionManager,
final String clientCoreVersion,
final String clientAppVersion,
final int userId,
final long deviceId,
final long sessionId,
final String sessionToken,
final String devicePlatform)
{
mRemoteAddress = remoteAddress;
mEncriptionStandard = encriptionStandard;
mSqlDataSource = sqlDataSource;
mSessionManager = sessionManager;
mClientCoreVersion = clientCoreVersion;
mClientAppVersion = clientAppVersion;
mUserId = userId;
mDeviceId = deviceId;
mSessionId = sessionId;
mSessionToken = sessionToken;
mDevicePlatform = devicePlatform;
}
public String getRemoteAddress()
{
return mRemoteAddress;
}
public CBackendAdvancedEncryptionStandard getEncriptionStandard()
{
return mEncriptionStandard;
}
public DataSource getSqlDataSource()
{
return mSqlDataSource;
}
public CBackendSessionManager getSessionManager()
{
return mSessionManager;
}
public String getClientCoreVersion()
{
return mClientCoreVersion;
}
public String getClientAppVersion()
{
return mClientAppVersion;
}
public int getUserId()
{
return mUserId;
}
public long getDeviceId()
{
return mDeviceId;
}
public long getSessionId()
{
return mSessionId;
}
public String getSessionToken()
{
return mSessionToken;
}
public String getDevicePlatform()
{
return mDevicePlatform;
}
}
<file_sep>package com.mozaicgames.executors;
public class CRequestKeys
{
public static final String mKeyClientDeviceToken = "client_device_token";
public static final String mKeyClientUserToken = "client_user_token";
public static final String mKeyClientSessionToken = "client_session_token";
public static final String mKeyClientUserSettingsData = "client_user_settings_data";
public static final String mKeyClientUserWalletData = "client_user_wallet_data";
public static final String mKeyClientUserGameData = "client_user_game_data";
public static final String mKeyUserSettingsMagnetOn = "settings_magnet_on";
public static final String mKeyUserSettingsLeftHandedOn = "settings_lefthanded_on";
public static final String mKeyUserSettingsMusicOn = "settings_music_on";
public static final String mKeyUserSettingsSfxOn = "settings_sfx_on";
public static final String mKeyUserWalletDataCreditsNum = "walletdata_credits_num";
public static final String mKeyUserWalletDataJokersNum = "walletdata_jokers_num";
public static final String mKeyUserWalletDataTokensNum = "walletdata_tokens_num";
public static final String mKeyUserDataLevel = "userdata_level";
public static final String mKeyUserDataXp = "userdata_xp";
public static final String mKeyUserDataLevelMaxXp = "userdata_level_max_xp";
public static final String mKeyUserDataTrophies = "userdata_trophies";
public static final String mKeyDeviceModel = "device_model";
public static final String mKeyDeviceOsVersion = "device_os_version";
public static final String mKeyDevicePlatform = "device_platform";
public static final String mKeyDeviceUsageTime = "device_usage_time";
public static final String mKeyDeviceClientCoreVersion = "client_core_version";
public static final String mKeyDeviceClientAppVersion = "client_app_version";
public static final String mKeyGameDataVector = "games";
public static final String mKeyGameType = "game_game_type";
public static final String mKeyGameSeed = "game_seed";
public static final String mKeyGameSeedSource = "game_seed_source";
public static final String mKeyGameDuration = "game_duration";
public static final String mKeyGamePlayerPlace = "game_player_place";
public static final String mKeyGamePlayerScore = "game_player_score";
public static final String mKeyGamePlayerStars = "game_player_stars";
public static final String mKeyGameFinishResult = "game_complete_result";
public static final String mKeyGameDeckRefreshNum = "game_deck_refresh_num";
public static final String mKeyGameActionsUsedNum = "game_actions_used_num";
public static final String mKeyGameHintsUsedNum = "game_hints_used_num";
public static final String mKeyGameJokersUsedNum = "game_jokers_used_num";
public static final String mKeyGameFoundationRank1 = "game_foundation_rank_1";
public static final String mKeyGameFoundationRank2 = "game_foundation_rank_2";
public static final String mKeyGameFoundationRank3 = "game_foundation_rank_3";
public static final String mKeyGameFoundationRank4 = "game_foundation_rank_4";
public static final String mKeyGameRewardsVector = "game_rewards";
public static final String mKeyGameRewardsGainedXp = "game_rewards_gained_xp";
public static final String mKeyGameRewardsGainedLevel = "game_rewards_gained_level";
public static final String mKeyGameRewardsGainedLevelMaxXp = "game_rewards_gained_level_max_xp";
public static final String mKeyGameRewardsGainedTrophie = "game_rewards_gained_trophies";
public static final String mKeyGameRewardsGainedCredits = "game_rewards_gained_credits";
public static final String mKeyGameRewardsGainedJokers = "game_rewards_gained_jokers";
public static final String mKeyGameRewardsGainedTokens = "game_rewards_gained_tokens";
public static final String mKeyGameRewardsGainedPlace = "game_rewards_gained_place";
public static final String mKeyGameRewardsGainedScore = "game_rewards_gained_score";
public static final String mKeyGameRewardsGainedStars = "game_rewards_gained_stars";
}
<file_sep>#!/bin/sh -
java -cp mozabackendserver.jar:libs/* Main -p 8081<file_sep>package com.mozaicgames.executors;
import org.json.JSONException;
import org.json.JSONObject;
import com.mozaicgames.core.CBackendRequestException;
import com.mozaicgames.core.CBackendRequestExecutor;
import com.mozaicgames.core.CBackendRequestExecutorParameters;
import com.mozaicgames.core.EBackendResponsStatusCode;
import com.mozaicgames.utils.CBackendQueryGetUserGameData;
import com.mozaicgames.utils.CBackendQueryGetUserWalletData;
import com.mozaicgames.utils.CBackendQueryGetUserSettingsData;
import com.mozaicgames.utils.CBackendQueryResponse;
import com.mozaicgames.utils.CBackendQueryValidateDevice;
import com.mozaicgames.utils.CBackendSession;
import com.mozaicgames.utils.CBackendSessionManager;
import com.mozaicgames.utils.CBackendUpdateUserLastLoginDate;
public class CRequestExecutorUpdateSession extends CBackendRequestExecutor
{
@Override
public boolean isSessionTokenValidationNeeded()
{
return false;
}
@Override
public JSONObject execute(JSONObject jsonData, CBackendRequestExecutorParameters parameters) throws CBackendRequestException
{
String deviceToken = null;
try
{
deviceToken = jsonData.getString(CRequestKeys.mKeyClientSessionToken);
}
catch (JSONException e)
{
// bad input
// return database connection error - status retry
throw new CBackendRequestException(EBackendResponsStatusCode.INVALID_DATA, "Invalid input data!");
}
long sessionId = 0;
long deviceId = 0;
int userId = 0;
boolean createNewSession = false;
final CBackendSessionManager sessionManager = parameters.getSessionManager();
final String remoteAddress = parameters.getRemoteAddress();
CBackendSession activeSession = sessionManager.getActiveSessionFor(deviceToken);
if (null == activeSession)
{
CBackendSession lastKnownSession = sessionManager.getLastKnownSessionFor(deviceToken);
if (null == lastKnownSession)
{
throw new CBackendRequestException(EBackendResponsStatusCode.INVALID_TOKEN_SESSION_KEY, "Unknown session token! Register first!");
}
activeSession = lastKnownSession;
createNewSession = sessionManager.isSessionValid(activeSession) == false;
}
if (false == createNewSession)
{
createNewSession = activeSession.getIp().equals(remoteAddress) == false;
}
sessionId = activeSession.getId();
deviceId = activeSession.getDeviceId();
userId = activeSession.getUserId();
final CBackendQueryValidateDevice validatorDevice = new CBackendQueryValidateDevice(parameters.getSqlDataSource(), deviceId);
final CBackendQueryResponse validatorResponse = validatorDevice.execute();
if (validatorResponse.getCode() != EBackendResponsStatusCode.STATUS_OK)
{
throw new CBackendRequestException(validatorResponse.getCode(), validatorResponse.getBody());
}
final String devicePlatform = validatorResponse.getBody();
if (createNewSession)
{
activeSession = sessionManager.updateSession(sessionId, deviceId, userId, activeSession.getKey(), remoteAddress, devicePlatform);
}
// update user last login date
final CBackendUpdateUserLastLoginDate updateLastLoginQuerry = new CBackendUpdateUserLastLoginDate(parameters.getSqlDataSource(), userId);
final CBackendQueryResponse updateLoginDateResponse = updateLastLoginQuerry.execute();
if (updateLoginDateResponse.getCode() != EBackendResponsStatusCode.STATUS_OK)
{
throw new CBackendRequestException(validatorResponse.getCode(), validatorResponse.getBody());
}
if (activeSession != null)
{
try
{
JSONObject jsonResponse = new JSONObject();
jsonResponse.put(CRequestKeys.mKeyClientSessionToken, activeSession.getKey());
jsonResponse.put(CRequestKeys.mKeyClientUserSettingsData, CBackendQueryGetUserSettingsData.getUserGameData(userId, parameters.getSqlDataSource()));
jsonResponse.put(CRequestKeys.mKeyClientUserWalletData, CBackendQueryGetUserWalletData.getUserGameData(userId, devicePlatform, parameters.getSqlDataSource()));
jsonResponse.put(CRequestKeys.mKeyClientUserGameData, CBackendQueryGetUserGameData.getUserData(userId, parameters.getSqlDataSource()));
return toJSONObject(EBackendResponsStatusCode.STATUS_OK, jsonResponse);
}
catch (JSONException e)
{
System.err.println(e.getMessage());
}
}
// error processing statement
// return statement error - status error
throw new CBackendRequestException(EBackendResponsStatusCode.INTERNAL_ERROR, "Unable to retrive active session!");
}
}
<file_sep>CREATE TABLE sessions_history (
`session_history_id` INT NOT NULL AUTO_INCREMENT,
`session_id` INT NOT NULL,
`session_token` VARCHAR(45) NOT NULL,
`session_creation_date` DATETIME NOT NULL,
`session_ip` VARCHAR(45) NOT NULL,
`session_platform` VARCHAR(45) NOT NULL,
PRIMARY KEY (`session_history_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;<file_sep>package com.mozaicgames.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import com.mozaicgames.executors.CDatabaseKeys;
public class CBackendSessionManager
{
private final DataSource mSqlDataSource;
private final ConcurrentMap<String, CBackendSession> mActiveSessions;
private final CBackendAdvancedEncryptionStandard mEncripter;
public CBackendSessionManager(final DataSource sqlDataSource, final CBackendAdvancedEncryptionStandard encripter)
throws Exception
{
mSqlDataSource = sqlDataSource;
mEncripter = encripter;
mActiveSessions = new ConcurrentHashMap<>();
if (mSqlDataSource == null || mEncripter == null)
{
throw new Exception("Invalid argument");
}
}
public static final int TIME_TO_LIVE = 600000;
public synchronized void cleanInvalidSessions()
{
long now = System.currentTimeMillis();
for (CBackendSession session : mActiveSessions.values())
{
if ((now - session.getCreationTime()) > TIME_TO_LIVE || now < session.getExpireTime())
{
mActiveSessions.remove(session.getKey());
}
}
}
public synchronized boolean isSessionValid(CBackendSession session)
{
long now = System.currentTimeMillis();
if (session != null)
{
return now < session.getExpireTime();
}
return false;
}
public synchronized CBackendSession getActiveSessionFor(String sessionKey)
{
CBackendSession session = mActiveSessions.get(sessionKey);
if (session == null)
{
return getLastKnownSessionFor(sessionKey);
}
else
{
if (false == isSessionValid(session))
{
mActiveSessions.remove(session.getKey());
}
return session;
}
}
public synchronized CBackendSession getLastKnownSessionFor(String sessionKey)
{
// find cached session
CBackendSession session = mActiveSessions.get(sessionKey);
if (session != null)
{
if (false == isSessionValid(session))
{
mActiveSessions.remove(sessionKey);
}
return session;
}
Connection sqlConnection = null;
PreparedStatement preparedStatementSelect = null;
try {
sqlConnection = mSqlDataSource.getConnection();
sqlConnection.setAutoCommit(false);
CSqlBuilderSelect sqlBuilderSelect = new CSqlBuilderSelect()
.column(CDatabaseKeys.mKeyTableSessionSessionId)
.column(CDatabaseKeys.mKeyTableSessionUserId)
.column(CDatabaseKeys.mKeyTableSessionDeviceId)
.column(CDatabaseKeys.mKeyTableSessionExpireDate)
.column(CDatabaseKeys.mKeyTableSessionIp)
.column(CDatabaseKeys.mKeyTableSessionPlatform)
.from(CDatabaseKeys.mKeyTableSessionTableName)
.where(CDatabaseKeys.mKeyTableSessionSessionToken + "='" + sessionKey+"'");
// find the session in the database first
final String strQuerySelect = sqlBuilderSelect.toString();
preparedStatementSelect = sqlConnection.prepareStatement(strQuerySelect);
ResultSet response = preparedStatementSelect.executeQuery();
if (response != null && response.next())
{
final long sessionId = response.getLong(1);
final int userId = response.getInt(2);
final long deviceId = response.getLong(3);
final long timestampExpired = response.getTimestamp(4).getTime();
final long timestampNow = System.currentTimeMillis();
final String sessionIp = response.getString(5);
final String sessionPlatform = response.getString(6);
CBackendSession newSession = new CBackendSession(sessionId, userId, deviceId, sessionKey, timestampExpired, timestampNow, sessionIp, sessionPlatform);
if (timestampNow < timestampExpired)
{
mActiveSessions.put(sessionKey, newSession);
}
return newSession;
}
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementSelect != null)
{
try
{
preparedStatementSelect.close();
preparedStatementSelect = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println("Ex: " + e.getMessage());
}
}
return null;
}
public synchronized CBackendSession getLastKnownSessionFor(long deviceId, int userId)
{
// find cached session
for (CBackendSession session : mActiveSessions.values())
{
if (session.getUserId() == userId && session.getDeviceId() == deviceId)
{
if (false == isSessionValid(session))
{
mActiveSessions.remove(session.getKey());
}
return session;
}
}
Connection sqlConnection = null;
PreparedStatement preparedStatementSelect = null;
try
{
sqlConnection = mSqlDataSource.getConnection();
sqlConnection.setAutoCommit(false);
CSqlBuilder sqlBuilderSelect = new CSqlBuilderSelect()
.column(CDatabaseKeys.mKeyTableSessionSessionId)
.column(CDatabaseKeys.mKeyTableSessionSessionToken)
.column(CDatabaseKeys.mKeyTableSessionExpireDate)
.column(CDatabaseKeys.mKeyTableSessionIp)
.column(CDatabaseKeys.mKeyTableSessionPlatform)
.from(CDatabaseKeys.mKeyTableSessionTableName)
.where(CDatabaseKeys.mKeyTableSessionDeviceId + "=" + deviceId)
.where(CDatabaseKeys.mKeyTableSessionUserId + "=" + userId);
// find the session in the database first
final String strQuerySelect = sqlBuilderSelect.toString();
preparedStatementSelect = sqlConnection.prepareStatement(strQuerySelect);
ResultSet response = preparedStatementSelect.executeQuery();
if (response != null && response.next())
{
final long sessionId = response.getLong(1);
final String sessionKey = response.getString(2);
final long timestampNow = System.currentTimeMillis();
final long timestampExpired = response.getTimestamp(3).getTime();
final String sessionIp = response.getString(4);
final String sessionPlatform = response.getString(5);
CBackendSession newSession = new CBackendSession(sessionId, userId, deviceId, sessionKey, timestampExpired, timestampNow, sessionIp, sessionPlatform);
if (timestampNow < timestampExpired)
{
mActiveSessions.put(sessionKey, newSession);
}
return newSession;
}
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementSelect != null)
{
try
{
preparedStatementSelect.close();
preparedStatementSelect = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
return null;
}
public synchronized CBackendSession createSession(long deviceId, int userId, String remoteAddress, String sessionPlatform)
{
Connection sqlConnection = null;
PreparedStatement preparedStatementInsert = null;
PreparedStatement preparedStatementInsertHistory = null;
try
{
sqlConnection = mSqlDataSource.getConnection();
sqlConnection.setAutoCommit(false);
// calculate milliseconds to end of the day.
final String strUserId = Integer.toString(userId);
final String stdDeviceId = Long.toString(deviceId);
final long milisCurrent = System.currentTimeMillis();
final long milisInDay = TimeUnit.DAYS.toMillis(1);
final long numOfDaysSinceEpoch = milisCurrent / milisInDay;
final long milisFirstOfTheDay = numOfDaysSinceEpoch * milisInDay;
final long milisLastOfTheDay = milisFirstOfTheDay + milisInDay - 1000;
final String newSessionKey = mEncripter.encrypt(strUserId + "-" + stdDeviceId + "-" + String.valueOf(milisCurrent));
// there is no session stored in the backend or the session was
// expired
// create new session data
final String strTimeCurrentDate = new Timestamp(milisCurrent).toString();
final String strTimeExpireDate = new Timestamp(milisLastOfTheDay).toString();
// create session key
final CSqlBuilderInsert sqlBuilderInsert = new CSqlBuilderInsert()
.into(CDatabaseKeys.mKeyTableSessionTableName)
.value(CDatabaseKeys.mKeyTableSessionUserId, strUserId)
.value(CDatabaseKeys.mKeyTableSessionDeviceId, stdDeviceId)
.value(CDatabaseKeys.mKeyTableSessionSessionToken, newSessionKey)
.value(CDatabaseKeys.mKeyTableSessionCreationDate, strTimeCurrentDate)
.value(CDatabaseKeys.mKeyTableSessionExpireDate, strTimeExpireDate)
.value(CDatabaseKeys.mKeyTableSessionIp, remoteAddress)
.value(CDatabaseKeys.mKeyTableSessionPlatform, sessionPlatform);
final String strQueryInsert = sqlBuilderInsert.toString();
preparedStatementInsert = sqlConnection.prepareStatement(strQueryInsert, PreparedStatement.RETURN_GENERATED_KEYS);
long sessionId = 0;
int affectedRows = preparedStatementInsert.executeUpdate();
ResultSet restultLastInsert = preparedStatementInsert.getGeneratedKeys();
if (affectedRows >= 1 && restultLastInsert.next())
{
sessionId = restultLastInsert.getLong(1);
}
else
{
return null;
}
CBackendSession newSession = new CBackendSession(sessionId, userId, deviceId, newSessionKey, milisLastOfTheDay, milisCurrent, remoteAddress, sessionPlatform);
mActiveSessions.put(newSessionKey, newSession);
// insert into history
final CSqlBuilderInsert strBuilderInsertHistory = new CSqlBuilderInsert()
.into(CDatabaseKeys.mKeyTableSessionHistoryTableName)
.value(CDatabaseKeys.mKeyTableSessionHistorySessionId, Long.toString(sessionId))
.value(CDatabaseKeys.mKeyTableSessionHistorySessionToken, newSessionKey)
.value(CDatabaseKeys.mKeyTableSessionHistoryCreationDate, strTimeCurrentDate)
.value(CDatabaseKeys.mKeyTableSessionHistoryIp, remoteAddress)
.value(CDatabaseKeys.mKeyTableSessionHistoryPlatform, sessionPlatform);
final String strQueryInsertHistory = strBuilderInsertHistory.toString();
preparedStatementInsertHistory = sqlConnection.prepareStatement(strQueryInsertHistory, PreparedStatement.RETURN_GENERATED_KEYS);
affectedRows = preparedStatementInsertHistory.executeUpdate();
if (affectedRows == 0)
{
return null;
}
sqlConnection.commit();
return newSession;
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementInsert != null)
{
try
{
preparedStatementInsert.close();
preparedStatementInsert = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
if (preparedStatementInsertHistory != null)
{
try
{
preparedStatementInsertHistory.close();
preparedStatementInsertHistory = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
return null;
}
public synchronized CBackendSession updateSession(long sessionId, long deviceId, int userId, String oldSessionKey, String remoteAddress, String sessionPlatform)
{
Connection sqlConnection = null;
PreparedStatement preparedStatementUpdate = null;
PreparedStatement preparedStatementInsertHistory = null;
try
{
sqlConnection = mSqlDataSource.getConnection();
sqlConnection.setAutoCommit(false);
// calculate milliseconds to end of the day.
final String strSessionId = Long.toString(sessionId);
final String strUserId = Integer.toString(userId);
final String stdDeviceId = Long.toString(deviceId);
final long milisCurrent = System.currentTimeMillis();
final long milisInDay = TimeUnit.DAYS.toMillis(1);
final long numOfDaysSinceEpoch = milisCurrent / milisInDay;
final long milisFirstOfTheDay = numOfDaysSinceEpoch * milisInDay;
final long milisLastOfTheDay = milisFirstOfTheDay + milisInDay - 1000;
final String newSessionKey = mEncripter.encrypt(strUserId + "-" + stdDeviceId + "-" + String.valueOf(milisCurrent));
// there is no session stored in the backend or the session was
// expired
// create new session data
final String strTimeCurrentDate = new Timestamp(milisCurrent).toString();
final String strTimeExpireDate = new Timestamp(milisLastOfTheDay).toString();
// create session key
final CSqlBuilderUpdate sqlBuilderUpdate = new CSqlBuilderUpdate()
.table(CDatabaseKeys.mKeyTableSessionTableName)
.set(CDatabaseKeys.mKeyTableSessionSessionToken, newSessionKey)
.set(CDatabaseKeys.mKeyTableSessionCreationDate, strTimeCurrentDate)
.set(CDatabaseKeys.mKeyTableSessionExpireDate, strTimeExpireDate)
.set(CDatabaseKeys.mKeyTableSessionIp, remoteAddress)
.where(CDatabaseKeys.mKeyTableSessionUserId + "=" + strUserId)
.where(CDatabaseKeys.mKeyTableSessionDeviceId + "=" + stdDeviceId)
.where(CDatabaseKeys.mKeyTableSessionPlatform + "='" + sessionPlatform+"'");
final String strQueryUpdate = sqlBuilderUpdate.toString();
preparedStatementUpdate = sqlConnection.prepareStatement(strQueryUpdate, PreparedStatement.RETURN_GENERATED_KEYS);
int affectedRows = preparedStatementUpdate.executeUpdate();
if (affectedRows == 0)
{
return null;
}
// insert into history
final CSqlBuilderInsert strBuilderInsertHistory = new CSqlBuilderInsert()
.into(CDatabaseKeys.mKeyTableSessionHistoryTableName)
.value(CDatabaseKeys.mKeyTableSessionHistorySessionId, strSessionId)
.value(CDatabaseKeys.mKeyTableSessionHistorySessionToken, newSessionKey)
.value(CDatabaseKeys.mKeyTableSessionHistoryCreationDate, strTimeCurrentDate)
.value(CDatabaseKeys.mKeyTableSessionHistoryIp, remoteAddress)
.value(CDatabaseKeys.mKeyTableSessionHistoryPlatform, sessionPlatform);
final String strQueryInsertHistory = strBuilderInsertHistory.toString();
preparedStatementInsertHistory = sqlConnection.prepareStatement(strQueryInsertHistory, PreparedStatement.RETURN_GENERATED_KEYS);
affectedRows = preparedStatementInsertHistory.executeUpdate();
if (affectedRows == 0)
{
return null;
}
sqlConnection.commit();
mActiveSessions.remove(oldSessionKey);
CBackendSession newSession = new CBackendSession(sessionId, userId, deviceId, newSessionKey, milisLastOfTheDay, milisCurrent, remoteAddress, sessionPlatform);
mActiveSessions.put(newSessionKey, newSession);
return newSession;
}
catch (Exception e)
{
// could not get a connection
// return database connection error - status retry
System.err.println("Register handler Null pointer exception: " + e.getMessage());
}
finally
{
if (preparedStatementUpdate != null)
{
try
{
preparedStatementUpdate.close();
preparedStatementUpdate = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
if (preparedStatementInsertHistory != null)
{
try
{
preparedStatementInsertHistory.close();
preparedStatementInsertHistory = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
try
{
sqlConnection.close();
sqlConnection = null;
}
catch (SQLException e)
{
System.err.println(e.getMessage());
}
}
return null;
}
}
| da7382808a24898b4abdc778f3869bd9b4c7ee54 | [
"Java",
"SQL",
"Markdown",
"Shell"
] | 27 | SQL | vladcioaba/mozabackend | d3fbd560f12a52bb1172e8bdd4cc91aeab4943d7 | 31db2afd82083996b7a26cbbc00c76d23f5653c3 |
refs/heads/master | <file_sep>module.exports = function(app) {
var express = require('express');
var jobsRouter = express.Router();
jobsRouter.get('/', function(req, res) {
res.send({
"jobs": [
{ id: 1, title: "Product Manager" },
{ id: 2, title: "Account Manager" },
{ id: 3, title: "Sales Manager" },
{ id: 4, title: "Project Manager" },
{ id: 5, title: "Store Manager" }
]
});
});
jobsRouter.post('/', function(req, res) {
res.status(201).end();
});
jobsRouter.get('/:id', function(req, res) {
res.send({
"jobs": {
"id": req.params.id
}
});
});
jobsRouter.put('/:id', function(req, res) {
res.send({
"jobs": {
"id": req.params.id
}
});
});
jobsRouter.delete('/:id', function(req, res) {
res.status(204).end();
});
app.use('/api/jobs', jobsRouter);
};
| 48a75d5e152853e347ccfdfe7447c279da93dc3f | [
"JavaScript"
] | 1 | JavaScript | johnnyoshika/ember-jobs | 7b6be1c1e7ba4c1cfe86cedaafb60d64f8ef4337 | d906c48a861d3ec67a6edde675fd0364b4093784 |
refs/heads/master | <file_sep>/**
* Decimal to Binary Converter
*/
#include <stdio.h>
#include <string.h>
long double power(long double number, int times){
if(times == 0)
{
return 1;
}
float original = number;
number = (long double) number;
for (long i = 1; i < times; i++)
{
number *= original;
}
return number;
};
int main()
{
long double num, temp, binary = 0.0L;
printf(" Enter Real number in Decimal form : ");
scanf("%Lf", &num);
long int integerPart = (long int) num;
// finding integer binary part of number
temp = integerPart;
for(int i = 120; i >= 0; i--)
{
if(temp - power(2, i) == 0)
{
binary += power(10, i);
break;
}
else if(temp - power(2, i) > 0)
{
binary += power(10, i);
temp -= power(2, i);
}
}
//finding fractional binary part ob number
temp = num - integerPart;
for(int i = 1; i <= 120; i++)
{
if(temp - power(0.5, i) == 0)
{
binary += power(0.1, i);
break;
}
else if(temp - power(0.5, i) > 0)
{
binary += power(0.1, i);
temp -= power(0.5, i);
}
}
printf(" Real number in binary form : ");
printf("%16.8Lf\n", binary);
}
<file_sep># C-Decimal2Binary-Converter
Decimal real number to Binary real number converter in Clang
| ed8fd65aa412c6f7f64966cc33e8526bec580abf | [
"Markdown",
"C"
] | 2 | C | random-jordan/C-Decimal2Binary-Converter | 1888c01cbb01b780b94d27de78f7954d94d21a9d | 701a3abf8fd7f2beef28f46f781672ff1be7c0b7 |
refs/heads/master | <file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('home');
// });
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Auth::routes();
Route::group(['middleware' => ['auth', 'Role:admin']], function(){
Route::get('/admin', [App\Http\Controllers\UserController::class, 'index'])
->name('dashboard.admin');
Route::get('/admin/create-user/', [App\Http\Controllers\UserController::class, 'create'])
->name('create.user');
Route::post('/admin/create-user/', [App\Http\Controllers\UserController::class, 'store'])
->name('store.user');
Route::get('/admin/deleted-users/', [App\Http\Controllers\UserController::class, 'getDeletedUsers'])
->name('getDeletedUsers');
Route::get('/admin/deleted-users/delete-all/',
[App\Http\Controllers\UserController::class, 'deleteAll'])
->name('deleteAll.users');
Route::get('/admin/deleted-users/restore-all/',
[App\Http\Controllers\UserController::class, 'restoreAll'])
->name('restoreAll.users');
Route::get('/admin/show-user/{user}', [App\Http\Controllers\UserController::class, 'show'])
->name('show.user');
Route::get('/admin/edit-user/{user}', [App\Http\Controllers\UserController::class, 'edit'])
->name('edit.user');
Route::put('/admin/edit-user/{user}', [App\Http\Controllers\UserController::class, 'update'])
->name('update.user');
Route::get('/admin/delete-user/{user}', [App\Http\Controllers\UserController::class, 'destroy'])
->name('user.delete');
Route::get('/admin/deleted-users/delete/{id}',
[App\Http\Controllers\UserController::class, 'deletePermanent'])
->name('deletePermanent.user');
Route::get('/admin/deleted-users/restore/{id}',
[App\Http\Controllers\UserController::class, 'restore'])
->name('restore.user');
Route::get('/admin/departments/deleted-departments/',
[App\Http\Controllers\DepartmentController::class, 'getDeletedDepartments'])
->name('getDeletedDepartments');
Route::get('/admin/departments/deleted-departments/delete-all/',
[App\Http\Controllers\DepartmentController::class, 'deleteAll'])
->name('deleteAll.departments');
Route::get('/admin/departments/deleted-departments/restore-all/',
[App\Http\Controllers\DepartmentController::class, 'restoreAll'])
->name('restoreAll.departments');
Route::resource('/admin/departments', App\Http\Controllers\DepartmentController::class);
Route::get('/admin/departments/deleted-departments/delete/{id}',
[App\Http\Controllers\DepartmentController::class, 'deletePermanent'])
->name('deletePermanent.department');
Route::get('/admin/departments/deleted-departments/restore/{id}',
[App\Http\Controllers\DepartmentController::class, 'restore'])
->name('restore.department');
Route::get('/admin/companies/deleted-companies/',
[App\Http\Controllers\CompanyController::class, 'getDeletedCompanies'])
->name('getDeletedCompanies');
Route::get('/admin/companies/deleted-companies/delete-all/',
[App\Http\Controllers\CompanyController::class, 'deleteAll'])
->name('deleteAll.companies');
Route::get('/admin/companies/deleted-companies/restore-all/',
[App\Http\Controllers\CompanyController::class, 'restoreAll'])
->name('restoreAll.companies');
Route::resource('/admin/companies', App\Http\Controllers\CompanyController::class);
Route::get('/admin/companies/deleted-companies/delete/{id}',
[App\Http\Controllers\CompanyController::class, 'deletePermanent'])
->name('deletePermanent.company');
Route::get('/admin/companies/deleted-companies/restore/{id}',
[App\Http\Controllers\CompanyController::class, 'restore'])
->name('restore.company');
});
Route::group(['middleware' => ['auth', 'Role:user']], function(){
Route::get('/user', [App\Http\Controllers\UserController::class, 'index'])
->name('dashboard.user');
});<file_sep><h1 align="center">Middle Project HR</h1>
<br><br>
# How To Use
To use this App is very simple, you must run a simple syntax in terminal or command prompt.
### Clone The Project
```
git clone https://github.com/rizqiwahyudi/middle-project-HR.git
```
### Install The Project With Composer
```
composer install
```
### Copy ".env.example" file to ".env"
```
cp .env.example .env
```
or you can copy the file in your File Manager.
### Generate App_Key
```
php artisan key:generate
```
### Symlink Storage For Store Public Files
```
php artisan storage:link
```
### Initiate The Database Migration
```
php artisan migrate
```
or You can make the seed with the following command <b>(RECOMMENDED)</b> :
```
php artisan migrate --seed
```
> **NOTE : Make sure the web server and database are turned on before migration command**
### And Lastly, Run the server
```
php artisan serve
```
### License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Department;
class DepartmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Department::create([
'name' => 'HRD',
'description' => 'Managing human resources and employees',
]);
Department::create([
'name' => 'Sales & Marketing',
'description' => 'Responsible for sales and marketing of products produced by the company',
]);
Department::factory(10)->create();
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::create([
'username' => 'admin',
'first_name' => 'admin',
'last_name' => 'company',
'email' => '<EMAIL>',
'telepon' => '+62'.random_int(00000000000, 99999999999),
'password' => <PASSWORD>::make('<PASSWORD>'),
'role' => 'admin',
'company_id' => 1,
'department_id' => 1,
'remember_token' => Str::random(10),
]);
User::create([
'username' => 'user',
'first_name' => 'user',
'last_name' => 'company',
'email' => '<EMAIL>',
'telepon' => '+62'.random_int(00000000000, 99999999999),
'password' => <PASSWORD>::<PASSWORD>('<PASSWORD>'),
'company_id' => 1,
'department_id' => 2,
'remember_token' => Str::random(10),
]);
User::factory(10)->create();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
class CompanyController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$companies = Company::all();
return view('admin.company.index', compact('companies'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.company.create-company');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:companies',
'logo' => 'required|image|mimes:jpeg,jpg,png,svg|max:2048|dimensions:min_width=100,min_height=100',
'website_url' => 'required|url|unique:companies,website_url',
]);
$company = $request->all();
if ($request->file('logo')) {
$logo = $request->file('logo');
$logo_name = date('d-m-Y-H-i-s').'_'.$logo->hashName();
$company['logo'] = $logo_name;
$logo->storeAs('public/images', $logo_name);
}
Company::create($company);
return redirect()->route('companies.index')
->with('success', 'Company Berhasil Ditambahkan!');
}
/**
* Display the specified resource.
*
* @param \App\Models\Company $company
* @return \Illuminate\Http\Response
*/
public function show(Company $company)
{
return view('admin.company.show-company', compact('company'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Company $company
* @return \Illuminate\Http\Response
*/
public function edit(Company $company)
{
return view('admin.company.edit-company', compact('company'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Company $company
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Company $company)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|'.Rule::unique('companies')->ignore($company->id),
'logo' => 'image|mimes:jpeg,jpg,png,svg|max:2048|dimensions:min_width=100,min_height=100',
'website_url' => 'required|url|'.Rule::unique('companies')->ignore($company->id),
]);
$data = $request->all();
if ($request->hasFile('logo')) {
Storage::delete('public/images/'.$company->logo);
$logo = $request->file('logo');
$logo_name = date('d-m-Y-H-i-s').'_'.$logo->hashName();
$data['logo'] = $logo_name;
$logo->storeAs('public/images', $logo_name);
}
$company->update($data);
return redirect()->route('companies.index')
->with('success', 'Data Company Berhasil Diupdate!');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Company $company
* @return \Illuminate\Http\Response
*/
public function destroy(Company $company)
{
$company->delete();
if ($company) {
return redirect()->route('companies.index')
->with('success', 'Data Company Berhasil Dihapus Sementara');
} else {
return redirect()->route('companies.index')
->with('error', 'Data Company Gagal Dihapus!');
}
}
public function getDeletedCompanies()
{
$companies = Company::onlyTrashed()->get();
return view('admin.company.deleted-company', compact('companies'));
}
public function restoreAll()
{
$companies = Company::onlyTrashed();
$companies->restore();
if ($companies) {
return redirect()->route('companies.index')
->with('success', 'Data Company Berhasil Direstore');
} else {
return redirect()->route('getDeletedCompanies')
->with('error', 'Data Company Gagal Direstore');
}
}
public function deleteAll()
{
$companies = Company::onlyTrashed()->get();
$logos = $companies->pluck('logo');
foreach ($companies as $company) {
$company->forceDelete();
}
if ($companies) {
foreach ($logos as $logo) {
Storage::delete('public/images/'.$logo);
}
return redirect()->route('getDeletedCompanies')
->with('success', 'Data Company Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedCompanies')
->with('error', 'Data Company Gagal Dihapus!');
}
}
public function deletePermanent($id)
{
$company = Company::onlyTrashed()->firstWhere('id', $id);
$logo = $company->logo;
$company->forceDelete();
if ($company) {
Storage::delete('public/images/'.$logo);
return redirect()->route('getDeletedCompanies')
->with('success', 'Data Company Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedCompanies')
->with('error', 'Data Company Gagal Dihapus!');
}
}
public function restore($id)
{
$company = Company::onlyTrashed()->where('id', $id);
$company->restore();
if ($company) {
return redirect()->route('companies.index')
->with('success', 'Data Company Berhasil Direstore');
} else {
return redirect()->route('getDeletedCompanies')
->with('error', 'Data Company Gagal Direstore');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class DepartmentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$departments = Department::all();
return view('admin.department.index', compact('departments'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.department.create-department');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255|unique:departments,name',
'description' => 'required|string',
]);
Department::create($request->all());
return redirect()->route('departments.index')
->with('success', 'Department Berhasil Ditambahkan!');
}
/**
* Display the specified resource.
*
* @param \App\Models\Department $department
* @return \Illuminate\Http\Response
*/
public function show(Department $department)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Department $department
* @return \Illuminate\Http\Response
*/
public function edit(Department $department)
{
return view('admin.department.edit-department', compact('department'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Department $department
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Department $department)
{
$request->validate([
'name' => 'required|string|max:255|'.Rule::unique('departments')->ignore($department->id),
'description' => 'required|string',
]);
$department->update($request->all());
return redirect()->route('departments.index')
->with('success', 'Data Department Berhasil Diupdate!');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Department $department
* @return \Illuminate\Http\Response
*/
public function destroy(Department $department)
{
$department->delete();
if ($department) {
return redirect()->route('departments.index')
->with('success', 'Data Department Berhasil Dihapus Sementara');
} else {
return redirect()->route('departments.index')
->with('error', 'Data Department Gagal Dihapus!');
}
}
public function getDeletedDepartments()
{
$departments = Department::onlyTrashed()->get();
return view('admin.department.deleted-department', compact('departments'));
}
public function restoreAll()
{
$departments = Department::onlyTrashed();
$departments->restore();
if ($departments) {
return redirect()->route('departments.index')
->with('success', 'Data Department Berhasil Direstore');
} else {
return redirect()->route('getDeletedDepartments')
->with('error', 'Data Department Gagal Direstore');
}
}
public function deleteAll()
{
$departments = Department::onlyTrashed();
$departments->forceDelete();
if ($departments) {
return redirect()->route('getDeletedDepartments')
->with('success', 'Data Department Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedDepartments')
->with('error', 'Data Department Gagal Dihapus!');
}
}
public function deletePermanent($id)
{
$department = Department::onlyTrashed()->where('id', $id);
$department->forceDelete();
if ($department) {
return redirect()->route('getDeletedDepartments')
->with('success', 'Data Department Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedDepartments')
->with('error', 'Data Department Gagal Dihapus!');
}
}
public function restore($id)
{
$department = Department::onlyTrashed()->where('id', $id);
$department->restore();
if ($department) {
return redirect()->route('departments.index')
->with('success', 'Data Department Berhasil Direstore');
} else {
return redirect()->route('getDeletedDepartments')
->with('error', 'Data Department Gagal Direstore');
}
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Company;
use Illuminate\Support\Facades\Storage;
class CompanySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
if (!Storage::exists("public/images")) {
Storage::makeDirectory("public/images");
}
Company::create([
'name' => 'PT. <NAME>',
'email' => '<EMAIL>',
'logo' => 'logo.png',
'website_url' => 'https://site.alt-on.net',
]);
Company::create([
'name' => 'WIMI SEC',
'email' => '<EMAIL>',
'logo' => 'logo.png',
'website_url' => 'https://wimisec.or.id',
]);
Company::factory(10)->create();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Company;
use App\Models\Department;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user = Auth::user();
if ($user->role == 'admin') {
$users = User::all();
$companiesCount = Company::count();
$departmentsCount = Department::count();
$employeesCount = User::count();
return view('admin.index', compact(
'users',
'companiesCount',
'departmentsCount',
'employeesCount',
));
}
return view('user.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$companies = Company::all();
$departments = Department::all();
return view('admin.create-user', compact('companies', 'departments'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => ['required', 'string', 'max:255', 'unique:users'],
'first_name' => ['required', 'string', 'max:100'],
'last_name' => ['required', 'string', 'max:100'],
'telepon' => ['required', 'numeric', 'digits_between:10,13', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['<PASSWORD>', 'string', 'min:8', 'confirmed'],
'company' => ['required', 'not_in:0'],
'department' => ['required', 'not_in:0'],
'role' => ['required', 'not_in:0'],
]);
if ($validator->fails()) {
return redirect()->route('create.user')
->withErrors($validator)
->withInput();
}
User::create([
'username' => $request['username'],
'first_name' => $request['first_name'],
'last_name' => $request['last_name'],
'telepon' => $request['telepon'],
'email' => $request['email'],
'password' => <PASSWORD>($request['password']),
'company_id' => $request['company'],
'department_id' => $request['department'],
'role' => $request['role'],
]);
return redirect()->route('dashboard.admin')
->with('success', 'User Berhasil Ditambahkan!');
}
/**
* Display the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return view('admin.show-user', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
$companies = Company::all();
$departments = Department::all();
return view('admin.edit-user', compact([
'companies',
'departments',
'user',
]));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$request->validate([
'username' => 'required|string|max:255'.Rule::unique('users')->ignore($user->id),
'first_name' => 'required|string|max:100',
'last_name' => 'required|string|max:100',
'telepon' => 'required|numeric|digits_between:10,13'.Rule::unique('users')->ignore($user->id),
'email' => 'required|string|email|max:255'.Rule::unique('users')->ignore($user->id),
'company' => 'required|not_in:0',
'department' => 'required|not_in:0',
'role' => 'required|not_in:0',
]);
$user->company_id = $request->company;
$user->department_id = $request->department;
$user->update($request->all());
return redirect()->route('dashboard.admin')
->with('success', 'Data User Berhasil Diupdate!');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
$user->delete();
if ($user) {
return redirect()->route('dashboard.admin')
->with('success', 'Data User Berhasil Dihapus Sementara');
} else {
return redirect()->route('dashboard.admin')
->with('error', 'Data User Gagal Dihapus!');
}
}
public function getDeletedUsers()
{
$users = User::onlyTrashed()->get();
return view('admin.deleted-user', compact('users'));
}
public function deletePermanent($id)
{
$user = User::onlyTrashed()->where('id', $id);
$user->forceDelete();
if ($user) {
return redirect()->route('getDeletedUsers')
->with('success', 'Data User Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedUsers')
->with('error', 'Data User Gagal Dihapus!');
}
}
public function restore($id)
{
$user = User::onlyTrashed()->where('id', $id);
$user->restore();
if ($user) {
return redirect()->route('dashboard.admin')
->with('success', 'Data User Berhasil Direstore');
} else {
return redirect()->route('getDeletedUsers')
->with('error', 'Data User Gagal Direstore');
}
}
public function restoreAll()
{
$users = User::onlyTrashed();
$users->restore();
if ($users) {
return redirect()->route('dashboard.admin')
->with('success', 'Data User Berhasil Direstore');
} else {
return redirect()->route('getDeletedUsers')
->with('error', 'Data User Gagal Direstore');
}
}
public function deleteAll()
{
$users = User::onlyTrashed();
$users->forceDelete();
if ($users) {
return redirect()->route('getDeletedUsers')
->with('success', 'Data User Berhasil Dihapus Permanen');
} else {
return redirect()->route('getDeletedUsers')
->with('error', 'Data User Gagal Dihapus!');
}
}
}
| 5906f1cb677cc6d148100625f53d7d6d5bb3bd68 | [
"Markdown",
"PHP"
] | 8 | PHP | muhammadlr17/middle-project-HR | a118138a9aab4e1c42a2af7b8866d12bac2749a2 | a13b10c861cc9979ad298d81fcd298ed873b2c72 |
refs/heads/master | <repo_name>petehughes/SpotifyRemote<file_sep>/SpotifyRemote/SpotifyManager.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpotLocalAPI = SpotifyAPI.Local.SpotifyLocalAPI;
namespace SpotifyRemoteNS
{
public class SpotifyManager
{
private SpotifyAPI.Local.SpotifyLocalAPI spotClient;
private SpotifyAPI.Web.SpotifyWebAPI spotWeb;
private bool spotClientConnected = false;
public SpotifyManager()
{
spotClient = null;
spotWeb = null;
spotClientConnected = false;
}
public bool Initialize()
{
Debug.WriteLine("SpotifyManager Initialize.");
ConnectToSpotifyClient();
if(!IsSpotifyProcessRunning())
{
CommandOpenSpotify.Instance.m_currentTextlabel = CommandOpenSpotify.kSpotifyStartString;
}
else
{
CommandOpenSpotify.Instance.m_currentTextlabel = CommandOpenSpotify.kSpotifyOpenString;
}
return true;
}
public void Destroy()
{
DisconnectSpotifyClient();
}
public bool GetSpotifyConnectionStatus()
{
if(spotClient != null && spotClientConnected)
{
if(spotClient.GetStatus() == null)
{
spotClient = null;
spotClientConnected = false;
return false;
}
return true;
}
else
{
return false;
}
}
private bool ConnectToSpotifyClient()
{
Debug.WriteLine("SpotifyManager:: Connect to client.");
if (SpotLocalAPI.IsSpotifyRunning())
{
CommandOpenSpotify.Instance.m_currentTextlabel = CommandOpenSpotify.kSpotifyOpenString;
if (spotClient == null)
{
spotClient = new SpotLocalAPI();
}
bool connected = spotClient.Connect();
#if DEBUG
Debug.WriteLine("Spotify Client Connected: {0}", connected);
Debug.Assert(connected);
#endif
if(connected)
{
RegisterEvents();
}
spotClientConnected = connected;
SettingsManager.GetSettingsManager().ApplyCurrentSettings();
return connected;
}
CommandOpenSpotify.Instance.m_currentTextlabel = CommandOpenSpotify.kSpotifyStartString;
SettingsManager.GetSettingsManager().ApplyCurrentSettings();
spotClientConnected = false;
return false;
}
private void DisconnectSpotifyClient()
{
spotClient.Dispose();
spotClient = null;
spotClientConnected = false;
}
private void RegisterEvents()
{
Debug.WriteLine("SpotifyManager:: RegisterEvents");
spotClient.ListenForEvents = true;
spotClient.OnTrackChange += SpotClient_OnTrackChangeInternal;
spotClient.OnPlayStateChange += SpotClient_OnPlayStateChangeInternal;
}
public void OpenSpotify()
{
Debug.WriteLine("SpotifyManager:: OpenSpotify.");
Process spotifyWindow = null;
if((spotifyWindow = GetSpotifyWindowProcess()) != null)
{
UnsafeNativeMethods.BringProcessToFront(spotifyWindow);
}
else if(!SpotifyAPI.Local.SpotifyLocalAPI.IsSpotifyRunning())
{
Debug.WriteLine("Spotify not running.");
SpotifyAPI.Local.SpotifyLocalAPI.RunSpotify();
System.Threading.Thread.Sleep(300);
ConnectToSpotifyClient();
// update command hidden states.
}
}
public void NextTrack()
{
Debug.WriteLine("SpotifyManager:: NextTrack.");
if(!GetSpotifyConnectionStatus())
{
ConnectToSpotifyClient();
}
if(GetSpotifyConnectionStatus())
{
spotClient.Skip();
}
}
public void PreviousTrack()
{
Debug.WriteLine("SpotifyManager:: PreviousTrack.");
if (!GetSpotifyConnectionStatus())
{
ConnectToSpotifyClient();
}
if (GetSpotifyConnectionStatus())
{
spotClient.Previous();
}
}
public void PlayPause()
{
Debug.WriteLine("SpotifyManager:: Play/Pause.");
if (!GetSpotifyConnectionStatus())
{
ConnectToSpotifyClient();
}
if (GetSpotifyConnectionStatus())
{
if(spotClient.GetStatus().Playing)
{
spotClient.Pause();
}
else
{
spotClient.Play();
}
}
}
private bool IsSpotifyProcessRunning()
{
Process[] retrevedProc = Process.GetProcessesByName("Spotify");
Process spotMain = null;
foreach (Process item in retrevedProc)
{
if (item.MainWindowTitle != "")
{
spotMain = item;
if (spotMain != null)
{
return true;
}
break;
}
}
return false;
}
private Process GetSpotifyWindowProcess()
{
Process[] retrevedProc = Process.GetProcessesByName("Spotify");
Process spotMain = null;
foreach (Process item in retrevedProc)
{
if (item.MainWindowTitle != "")
{
spotMain = item;
break;
}
}
return spotMain;
}
// INTERNAL.
private void SpotClient_OnTrackChangeInternal(object sender, SpotifyAPI.Local.TrackChangeEventArgs e)
{
Debug.WriteLine("SotifyManager:: OnTrackChange");
OnSpotifyTrackChange(this, e);
}
private void SpotClient_OnPlayStateChangeInternal(object sender, SpotifyAPI.Local.PlayStateEventArgs e)
{
Debug.WriteLine("SotifyManager:: OnPlayStateChange");
OnSpotifyPlayStateChange(this, e);
}
// END OF INTERNAL.
public event EventHandler<SpotifyAPI.Local.TrackChangeEventArgs> SpotifyClientTrackChange;
public event EventHandler<SpotifyAPI.Local.PlayStateEventArgs> SpotifyClientPlayStateChange;
void OnSpotifyTrackChange(object sender, SpotifyAPI.Local.TrackChangeEventArgs e)
{
SpotifyClientTrackChange?.Invoke(this, e);
}
void OnSpotifyPlayStateChange(object sender, SpotifyAPI.Local.PlayStateEventArgs e)
{
SpotifyClientPlayStateChange?.Invoke(this, e);
}
}
// Win32 Window Helper.
public static class UnsafeNativeMethods
{
public static void BringProcessToFront(System.Diagnostics.Process process)
{
IntPtr handle = process.MainWindowHandle;
if (IsIconic(handle))
{
ShowWindow(handle, SW_RESTORE);
}
SetForegroundWindow(handle);
}
private const int SW_RESTORE = 9;
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);
}
}
<file_sep>/SpotifyRemote/SettingsManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell;
using System.Diagnostics;
namespace SpotifyRemoteNS
{
public class SettingsManager
{
public enum eToolbarTextMode
{
kAllTextVisible = 0,
kOpenTextVisible = 1,
kHideAllText = 3,
}
public enum eToolbarTrackChangeMode
{
kDisabled = 0,
kEnabledNoAnimation = 1,
kEnabledWithAnimation = 2
}
//settings manager.
static SettingsManager sm_settingsManager;
CommandOpenSpotify m_cmdOpenSpotify;
OleMenuCommand m_tbButtonOpen;
OleMenuCommand m_tbButtonPrevious;
OleMenuCommand m_tbButtonPlayPause;
OleMenuCommand m_tbButtonNext;
TrackChangeAnimator m_trackChangeAnimator;
SpotifyManager m_spotifyManager;
eToolbarTextMode m_textMode;
eToolbarTrackChangeMode m_trackChangeMode;
bool m_hideTextSpotifyInactive;
public static ref SettingsManager GetSettingsManager()
{
return ref sm_settingsManager;
}
public static void ProvideSettingsManager(ref SettingsManager settingsManager)
{
sm_settingsManager = settingsManager;
}
public void SetSpotifyManager(ref SpotifyManager spotifyManager)
{
m_spotifyManager = spotifyManager;
}
///////////////////////////////////////////
// Toolbar Text Mode
public void SetButtonTextMode(eToolbarTextMode textMode)
{
m_textMode = textMode;
}
public eToolbarTextMode GetButtonTextMode()
{
return m_textMode;
}
// Toolbar Text Mode End
///////////////////////////////////////////
public void SetTrackChangeMode(eToolbarTrackChangeMode trackChangeMode)
{
m_trackChangeMode = trackChangeMode;
}
public eToolbarTrackChangeMode GetTrackChangeMode()
{
return m_trackChangeMode;
}
public void SetHideTextSpotifyInactive(bool enabled)
{
m_hideTextSpotifyInactive = enabled;
}
public bool GetHideTextSpotifyInactive()
{
return m_hideTextSpotifyInactive;
}
public void ReadSettingsFromFile()
{
Debug.WriteLine("SettingsManager:: ReadSettingsFromFile");
UserSettings.Default.Reload();
m_textMode = (eToolbarTextMode)UserSettings.Default.TextToolbarVisibleMode;
m_trackChangeMode = (eToolbarTrackChangeMode)UserSettings.Default.TrackInfoOnChangeMode;
m_hideTextSpotifyInactive = UserSettings.Default.TextToolbarHiddenOnInactive;
}
public void SaveSettingsToFile()
{
Debug.WriteLine("SettingsManager:: SaveSettingsToFile");
UserSettings.Default.TextToolbarVisibleMode = (ushort)m_textMode;
UserSettings.Default.TrackInfoOnChangeMode = (ushort)m_trackChangeMode;
UserSettings.Default.TextToolbarHiddenOnInactive = m_hideTextSpotifyInactive;
UserSettings.Default.Save();
}
public void ApplyCurrentSettings()
{
switch (m_textMode)
{
case eToolbarTextMode.kAllTextVisible:
m_tbButtonOpen.Text = m_cmdOpenSpotify.m_currentTextlabel;
m_tbButtonPrevious.Text = CommandPreviousTrack.commandText;
m_tbButtonPlayPause.Text = CommandPlayPause.commandText;
m_tbButtonNext.Text = CommandNextTrack.commandText;
break;
case eToolbarTextMode.kOpenTextVisible:
m_tbButtonOpen.Text = m_cmdOpenSpotify.m_currentTextlabel;
m_tbButtonPrevious.Text = " ";
m_tbButtonPlayPause.Text = " ";
m_tbButtonNext.Text = " ";
break;
case eToolbarTextMode.kHideAllText:
m_tbButtonOpen.Text = " ";
m_tbButtonPrevious.Text = " ";
m_tbButtonPlayPause.Text = " ";
m_tbButtonNext.Text = " ";
break;
default:
m_tbButtonOpen.Text = m_cmdOpenSpotify.m_currentTextlabel;
m_tbButtonPrevious.Text = CommandPreviousTrack.commandText;
m_tbButtonPlayPause.Text = CommandPlayPause.commandText;
m_tbButtonNext.Text = CommandNextTrack.commandText;
Debug.WriteLine("WARNING m_textMode has unrecognized mode.");
break;
}
if (m_hideTextSpotifyInactive)
{
if (!m_spotifyManager.GetSpotifyConnectionStatus())
{
m_tbButtonOpen.Text = " ";
m_tbButtonPrevious.Text = " ";
m_tbButtonPlayPause.Text = " ";
m_tbButtonNext.Text = " ";
}
}
switch (m_trackChangeMode)
{
case eToolbarTrackChangeMode.kDisabled:
m_trackChangeAnimator.SetTrackChange(false);
m_trackChangeAnimator.SetAnimationOnChange(false);
break;
case eToolbarTrackChangeMode.kEnabledNoAnimation:
m_trackChangeAnimator.SetTrackChange(true);
m_trackChangeAnimator.SetAnimationOnChange(false);
break;
case eToolbarTrackChangeMode.kEnabledWithAnimation:
m_trackChangeAnimator.SetTrackChange(true);
m_trackChangeAnimator.SetAnimationOnChange(true);
break;
default:
m_trackChangeAnimator.SetTrackChange(true);
m_trackChangeAnimator.SetAnimationOnChange(true);
Debug.WriteLine("WARNING m_trackChangeMode has unrecognized mode.");
break;
}
}
public void SetCmdOpenSpotify(ref CommandOpenSpotify commandOpenSpotify)
{
m_cmdOpenSpotify = commandOpenSpotify;
}
public void SetTbButtonOpen(ref OleMenuCommand buttonOpen)
{
m_tbButtonOpen = buttonOpen;
}
public void SetTbButtonPrevious(ref OleMenuCommand buttonPrev)
{
m_tbButtonPrevious = buttonPrev;
}
public void SetTbButtonPlayPause(ref OleMenuCommand buttonPausePlay)
{
m_tbButtonPlayPause = buttonPausePlay;
}
public void SetTbButtonNext(ref OleMenuCommand buttonNext)
{
m_tbButtonNext = buttonNext;
}
public void SetTrackChangeAnimation(ref TrackChangeAnimator trChangeAnimator)
{
m_trackChangeAnimator = trChangeAnimator;
}
}
}
<file_sep>/SpotifyRemote/CommandOpenSpotifyPackage.cs
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using EnvDTE80;
using EnvDTE;
namespace SpotifyRemoteNS
{
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(SpotifyRemote.PackageGuidString)]
[ProvideToolWindow(typeof(SpotifyRemoteNS.SpotifyRemoteSettings))]
[ProvideAutoLoad("ADFC4E64-0397-11D1-9F4E-00A0C911004F")]
public sealed class SpotifyRemote : Package
{
/// <summary>
/// CommandOpenSpotifyPackage GUID string.
/// </summary>
public const string PackageGuidString = "c8693e55-5320-47e8-ba93-631dcee86150";
// for exit.
public DTE2 ApplicationObject
{
get
{
if (m_applicationObject == null)
{
// Get an instance of the currently running Visual Studio IDE
DTE dte = (DTE)GetService(typeof(DTE));
m_applicationObject = dte as DTE2;
}
return m_applicationObject;
}
}
private DTE2 m_applicationObject = null;
DTEEvents m_packageDTEEvents = null;
private SpotifyManager m_spotifyManager;
/// <summary>
/// Initializes a new instance of the <see cref="SpotifyRemote"/> class.
/// </summary>
public SpotifyRemote()
{
// Inside this method you can place any initialization code that does not require
// any Visual Studio service because at this point the package object is created but
// not sited yet inside Visual Studio environment. The place to do all the other
// initialization is the Initialize method.
SettingsManager sm = new SettingsManager();
SettingsManager.ProvideSettingsManager(ref sm);
m_spotifyManager = new SpotifyManager();
sm.SetSpotifyManager(ref m_spotifyManager);
}
#region Package Members
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
/// </summary>
protected override void Initialize()
{
base.Initialize();
m_packageDTEEvents = ApplicationObject.Events.DTEEvents;
m_packageDTEEvents.OnBeginShutdown += SpotifyRemoteDTEEventBeginShutdown;
m_packageDTEEvents.OnStartupComplete += SpotifyRemoteDTEEventOnStartupComplete;
SettingsManager sm = SettingsManager.GetSettingsManager();
CommandOpenSpotify.Initialize(this);
CommandNextTrack.Initialize(this);
CommandPlayPause.Initialize(this);
CommandPreviousTrack.Initialize(this);
SpotifyRemoteNS.SpotifyRemoteSettingsCommand.Initialize(this);
SpotifyRemoteNS.CommandOpenSettings.Initialize(this);
sm.ReadSettingsFromFile();
sm.ApplyCurrentSettings();
m_spotifyManager.Initialize();
}
public ref SpotifyManager GetSpotifyManager()
{
return ref m_spotifyManager;
}
private void SpotifyRemoteDTEEventOnStartupComplete()
{
// throw new NotImplementedException();
}
private void SpotifyRemoteDTEEventBeginShutdown()
{
SettingsManager.GetSettingsManager().SaveSettingsToFile();
m_spotifyManager.Destroy();
}
#endregion
}
}
<file_sep>/SpotifyRemote/CommandOpenSpotify.cs
using System;
using System.ComponentModel.Design;
using System.Globalization;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace SpotifyRemoteNS
{
/// <summary>
/// Command handler
/// </summary>
public class CommandOpenSpotify
{
#if DEBUG
public const string kSpotifyOpenString = "Open Spotify(D)";
#else
public const string kSpotifyOpenString = "Open Spotify";
#endif
#if DEBUG
public const string kSpotifyStartString = "Start Spotify(D)";
#else
public const string kSpotifyStartString = "Start Spotify";
#endif
/// <summary>
/// Command ID.
/// </summary>
public const int CommandId = 0x0100;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = new Guid("30159a3f-d07b-4eaa-9337-0aa4c68ae3a3");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
private readonly Package package;
private SpotifyManager m_spotifyManager;
private TrackChangeAnimator m_trackChangeAnimator;
public string m_currentTextlabel = kSpotifyOpenString;
/// <summary>
/// Initializes a new instance of the <see cref="CommandOpenSpotify"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
private CommandOpenSpotify(Package package)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
SpotifyRemote spotifyRemotePackage = package as SpotifyRemote;
m_spotifyManager = spotifyRemotePackage.GetSpotifyManager();
this.package = package;
OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
OleMenuCommand menuItem = null;
if (commandService != null)
{
var menuCommandID = new CommandID(CommandSet, CommandId);
menuItem = new OleMenuCommand(this.MenuItemCallback, menuCommandID);
commandService.AddCommand(menuItem);
}
// Initialize TrackChangeAnimator.
m_trackChangeAnimator = new TrackChangeAnimator();
m_trackChangeAnimator.Initialize(menuItem, m_currentTextlabel);
m_spotifyManager.SpotifyClientTrackChange += SpotifyClientTrackChange;
SettingsManager setManager = SettingsManager.GetSettingsManager();
setManager.SetTbButtonOpen(ref menuItem);
setManager.SetTrackChangeAnimation(ref m_trackChangeAnimator);
}
private void SpotifyClientTrackChange(object sender, SpotifyAPI.Local.TrackChangeEventArgs e)
{
m_trackChangeAnimator.StartTrackChange(e.NewTrack);
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static CommandOpenSpotify Instance;
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
private IServiceProvider ServiceProvider
{
get
{
return this.package;
}
}
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner package, not null.</param>
public static void Initialize(Package package)
{
Instance = new CommandOpenSpotify(package);
SettingsManager setManager = SettingsManager.GetSettingsManager();
setManager.SetCmdOpenSpotify(ref Instance);
}
/// <summary>
/// This function is the callback used to execute the command when the menu item is clicked.
/// See the constructor to see how the menu item is associated with this function using
/// OleMenuCommandService service and MenuCommand class.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event args.</param>
private void MenuItemCallback(object sender, EventArgs e)
{
//string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
//string title = "CommandOpenSpotify";
//// Show a message box to prove we were here
//VsShellUtilities.ShowMessageBox(
// this.ServiceProvider,
// message,
// title,
// OLEMSGICON.OLEMSGICON_INFO,
// OLEMSGBUTTON.OLEMSGBUTTON_OK,
// OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
// execute.
m_spotifyManager.OpenSpotify();
}
}
}
<file_sep>/SpotifyRemote/ThemeHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.PlatformUI;
using MediaColor = System.Windows.Media.Color;
using DrawingColor = System.Drawing.Color;
namespace SpotifyRemoteNS
{
static class ThemeHelper
{
public enum eVSTheme
{
kDark = 1,
kBlue = 2,
kLight = 3,
kUnknown = 0
}
public static eVSTheme GetTheme()
{
System.Drawing.Color c = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
if (c == System.Drawing.Color.FromArgb(255, 37, 37, 38))
{
//Dark..
return eVSTheme.kDark;
}
else if (c == System.Drawing.Color.FromArgb(255, 255, 255, 255))
{
return eVSTheme.kBlue;
}
else if (c == System.Drawing.Color.FromArgb(255, 245, 245, 245))
{
return eVSTheme.kLight;
}
else
{
return eVSTheme.kUnknown;
}
}
//thnx
public static MediaColor ToMediaColor(this DrawingColor color)
{
return MediaColor.FromArgb(color.A, color.R, color.G, color.B);
}
public static DrawingColor ToDrawingColor(this MediaColor color)
{
return DrawingColor.FromArgb(color.A, color.R, color.G, color.B);
}
}
}
<file_sep>/README.md
<img src="https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/297aadc6d2ca8b99afcb631bd2b4c1132a89fc31/VSIXSpotifyRemote/SpotifyRemoteLogo.png" width="200">
# SpotifyRemote
<img src="https://arjankuijpers.gallerycdn.vsassets.io/extensions/arjankuijpers/spotifyremote/2.0/1510793706623/271382/1/2017-07-16_00-24-42.gif">
## For Visual Studio (2015/2017)
License:

Join the conversation on:
[](https://gitter.im/SpotifyRemoteForVisualStudio/Lobby#)
Master: [](https://ci.appveyor.com/project/arjankuijpers/spotifyremote/branch/master)
* [Getting Started & Installation](#getting-started)
* [Tips](#tips)
* [FAQ](#frequent-asked-questions)
* [About](#about-spotifyremote)
* [Bug report & feature request](https://github.com/arjankuijpers/SpotifyRemote/issues)
## Getting started
#### Installation:
1. [Download](https://marketplace.visualstudio.com/items?itemName=ArjanKuijpers.SpotifyRemote) the installer package (VSIX) from the [Visual Studio marketplace](https://marketplace.visualstudio.com/items?itemName=ArjanKuijpers.SpotifyRemote#review-details).
2. Run the Visual Studio extension installer (VSIX).
3. Restart Visual Studio.
4. Go to **view** *>* **Toolbars** and Select **SpotifyRemote**
<img src="https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/081ea5748298841b9385c684de59b0f88dfd9399/SpotifyRemote/docs/enable_tb_from_view.png" width="350">
[Click here](https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/081ea5748298841b9385c684de59b0f88dfd9399/SpotifyRemote/docs/enable_tb_from_view.png) for full sized screenshot
## Tips
**Can it start Spotify from Visual Studio?**
It will, when you click a command and Spotify is not running.
## Frequent Asked Questions
**Does it work on Visual Studio 2017?**
*Yes it does, try it.*
**What can SpotifyRemote do?**
1. Currently you can do the basic commands such as:
* Open Spotify,
* Play
* Pause
* Next
* Previous
2. Showing Track name & Artist when it changes.
*But that's not where it stops, See [Features](#features) to know what is planned.*
You can also make a feature request (at github).
**Can I help with development?**
*Sure you can, please fork and do your developer magic. Afterwards create a [pull request](https://github.com/arjankuijpers/SpotifyRemote/pulls).
And if your changes are stable it will be merged in the release version*
**What version of Windows do I need?**
*At least* Windows 7 *, Visual Studio 2015 is only supported on Windows 7 and later*
**What version of Visual Studio do I need?**
*At least* Visual Studio 2015
## Features
### Supported
- [x] Start Spotify
- [x] Open Spotify
- [x] Play / Pause
- [x] Skip / Previous
- [x] Shows track title upon change
- [ ] Playlist browsing
### Planned
- [x] Create better interface (update icons).
- [x] Hide Text of play control buttons when spotify is not active.
- [x] Settings in tools menu.
- [ ] Multiple themes.
- [ ] Awesome features people request.
Do you miss a feature? Submit a request here: [Github](https://github.com/arjankuijpers/SpotifyRemote/issues)
## Troubleshooting
**SpotifyRemote is not visible in the Visual studio**
Go to **view** *>* **Toolbars** and Select **SpotifyRemote** it should show up at the top of Visual Studio.
The toolbar will be displayed over here.
<img src="https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/081ea5748298841b9385c684de59b0f88dfd9399/SpotifyRemote/docs/Enable_toolbar1.png" >
Go to toolbars and select the SpotifyRemote toolbar.
<img src="https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/081ea5748298841b9385c684de59b0f88dfd9399/SpotifyRemote/docs/Enable_toolbar2.png" width="200">
The toolbar should now be visible. (icons may be different).
<img src="https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/081ea5748298841b9385c684de59b0f88dfd9399/SpotifyRemote/docs/Enable_toolbar3.png">
## About SpotifyRemote
SpotifyRemote is a attempt to recreate the awesome [vscode-spotify](https://marketplace.visualstudio.com/items?itemName=shyykoserhiy.vscode-spotify) plugin from [shyykoserhiy](https://github.com/ShyykoSerhiy/vscode-spotify).
This project is open source and I encourage forks and pull requests.
Please submit bug reports and feature requests at [Github](https://github.com/arjankuijpers/SpotifyRemote/issues).
## License
[SpotifyRemote is released under the MIT License](https://raw.githubusercontent.com/arjankuijpers/SpotifyRemote/master/LICENSE).
<file_sep>/SpotifyRemote/TrackChangeAnimator.cs
using SpotifyAPI.Local.Models;
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace SpotifyRemoteNS
{
public class TrackChangeAnimator
{
OleMenuCommand m_menuCommand;
Track m_currentTrack;
string m_standardCommandText;
bool m_trackChangeEnabled = true;
bool m_animationEnabled = true;
internal System.Timers.Timer m_timer = null;
private const float m_animationTimeWait = 5000; //ms
private const float m_animationFrameTime = 125; //ms
public bool Initialize(OleMenuCommand menuCommand, string menuCommandText)
{
Debug.WriteLine("TrackChangeAnimator:: Initialize.");
m_menuCommand = menuCommand;
m_standardCommandText = menuCommandText;
return true;
}
public void SetTrackChange(bool enabled)
{
m_trackChangeEnabled = enabled;
}
public void SetAnimationOnChange(bool enabled)
{
m_animationEnabled = enabled;
}
public void SetStandardCommandText(string text)
{
m_standardCommandText = text;
}
public void Destroy()
{
}
public void StartTrackChange(Track newTrack)
{
Debug.WriteLine("TrackChangeAnimator:: StartTrackChange.");
if (newTrack == null || newTrack.TrackResource == null ||
newTrack.TrackResource.Name == null || newTrack.AlbumResource.Name == null)
{
Debug.WriteLine("TrackChangeAnimator:: StartTrackChange newTrack contains argument is null.");
return;
}
if(!m_trackChangeEnabled)
{
return;
}
m_currentTrack = newTrack;
StartTrackChangeAnimation();
}
public void StopTrackChange()
{
Debug.WriteLine("TrackChangeAnimator:: Initialize.");
m_menuCommand.Text = m_standardCommandText;
}
//////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
private void StartTrackChangeAnimation()
{
string trackName = m_currentTrack.TrackResource.Name;
string artistName = m_currentTrack.ArtistResource.Name;
Console.WriteLine("Show New track name: " + trackName);
m_menuCommand.Text = String.Format("{0} - {1}", trackName, artistName);
if(m_timer != null)
{
m_timer.Stop();
m_timer.Start();
}
else
{
m_timer = new System.Timers.Timer() { Interval = m_animationTimeWait };
m_timer.Elapsed += TrackChangeAnimTimerTick;
m_timer.Start();
}
}
private void TrackChangeAnimTimerTick(object sender, System.Timers.ElapsedEventArgs e)
{
Debug.WriteLine("TrackChangeAnimator:: TrackChange Wait done.");
m_timer.Stop();
m_timer.Elapsed -= TrackChangeAnimTimerTick;
if(!m_animationEnabled)
{
m_timer = null;
m_menuCommand.Text = m_standardCommandText;
return;
}
// Else Animation is enabled.
m_timer.Elapsed += TimerAnimationTick;
m_timer.Interval = m_animationFrameTime;
m_timer.Start();
}
private void TimerAnimationTick(object sender, System.Timers.ElapsedEventArgs e)
{
if (m_menuCommand.Text.Length <= m_standardCommandText.Length)
{
m_timer.Stop();
m_timer.Elapsed -= TimerAnimationTick;
m_timer = null;
m_menuCommand.Text = m_standardCommandText;
}
else
{
if (m_menuCommand.Text.Length > m_standardCommandText.Length)
{
m_menuCommand.Text = m_menuCommand.Text.Remove(m_menuCommand.Text.Length - 1);
}
else
{
m_menuCommand.Text += " ";
}
}
}
}
}
<file_sep>/SpotifyRemote/SpotifyRemoteSettingsControl.xaml.cs
namespace SpotifyRemoteNS
{
using Microsoft.VisualStudio.PlatformUI;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
/// <summary>
/// Interaction logic for SpotifyRemoteSettingsControl.
/// </summary>
public partial class SpotifyRemoteSettingsControl : UserControl
{
System.Windows.Media.Color foregroundColor = new System.Windows.Media.Color();
System.Windows.Media.Color subOptionsColor = new System.Windows.Media.Color();
System.Windows.Media.Color explainOptColor = new System.Windows.Media.Color();
/// <summary>
/// Initializes a new instance of the <see cref="SpotifyRemoteSettingsControl"/> class.
/// </summary>
public SpotifyRemoteSettingsControl()
{
this.InitializeComponent();
}
private void SpotifyRemoteSettings_Initialized(object sender, System.EventArgs e)
{
Microsoft.VisualStudio.PlatformUI.VSColorTheme.ThemeChanged += VSColorTheme_ThemeChanged;
}
private void SpotifyRemoteSettings_Loaded(object sender, RoutedEventArgs e)
{
LoadSettings();
UpdateUIColors();
}
private void SpotifyRemoteSettings_Unloaded(object sender, RoutedEventArgs e)
{
SaveSettings();
SettingsManager sm = SettingsManager.GetSettingsManager();
sm.ApplyCurrentSettings();
}
private void LoadSettings()
{
SettingsManager sm = SettingsManager.GetSettingsManager();
switch (sm.GetButtonTextMode())
{
case SettingsManager.eToolbarTextMode.kAllTextVisible:
rb_tv0.IsChecked = true;
break;
case SettingsManager.eToolbarTextMode.kOpenTextVisible:
rb_tv1.IsChecked = true;
break;
case SettingsManager.eToolbarTextMode.kHideAllText:
rb_tv2.IsChecked = true;
break;
default:
rb_tv0.IsChecked = true;
break;
}
if (sm.GetHideTextSpotifyInactive())
{
checkBox_hideText.IsChecked = true;
}
else
{
checkBox_hideText.IsChecked = true;
}
switch (sm.GetTrackChangeMode())
{
case SettingsManager.eToolbarTrackChangeMode.kDisabled:
checkBox_ShowTrackArtist.IsChecked = false;
checkBox_enableInteractiveAnimation.IsChecked = false;
break;
case SettingsManager.eToolbarTrackChangeMode.kEnabledNoAnimation:
checkBox_ShowTrackArtist.IsChecked = true;
checkBox_enableInteractiveAnimation.IsChecked = false;
break;
case SettingsManager.eToolbarTrackChangeMode.kEnabledWithAnimation:
checkBox_ShowTrackArtist.IsChecked = true;
checkBox_enableInteractiveAnimation.IsChecked = true;
break;
default:
checkBox_ShowTrackArtist.IsChecked = true;
checkBox_enableInteractiveAnimation.IsChecked = true;
break;
}
}
private void SaveSettings()
{
SettingsManager sm = SettingsManager.GetSettingsManager();
if (rb_tv0.IsChecked == true)
{
sm.SetButtonTextMode(SettingsManager.eToolbarTextMode.kAllTextVisible);
}
else if(rb_tv1.IsChecked == true)
{
sm.SetButtonTextMode(SettingsManager.eToolbarTextMode.kOpenTextVisible);
}
else {
sm.SetButtonTextMode(SettingsManager.eToolbarTextMode.kHideAllText);
}
if(checkBox_hideText.IsChecked == true)
{
sm.SetHideTextSpotifyInactive(true);
}
else
{
sm.SetHideTextSpotifyInactive(false);
}
if(checkBox_ShowTrackArtist.IsChecked == true && checkBox_enableInteractiveAnimation.IsChecked == true)
{
sm.SetTrackChangeMode(SettingsManager.eToolbarTrackChangeMode.kEnabledWithAnimation);
}
else if (checkBox_ShowTrackArtist.IsChecked == true && checkBox_enableInteractiveAnimation.IsChecked == false)
{
sm.SetTrackChangeMode(SettingsManager.eToolbarTrackChangeMode.kEnabledNoAnimation);
}
else
{
sm.SetTrackChangeMode(SettingsManager.eToolbarTrackChangeMode.kDisabled);
}
}
///////////////////////////////////////////////////////////////////
//// Theme
private void VSColorTheme_ThemeChanged(Microsoft.VisualStudio.PlatformUI.ThemeChangedEventArgs e)
{
UpdateUIColors();
}
private void UpdateUIColors()
{
var defaultBackground = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
var defaultForeground = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowTextColorKey);
System.Drawing.Color c = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
SolidColorBrush backgroundCol = new SolidColorBrush(ThemeHelper.ToMediaColor(defaultBackground));
switch (ThemeHelper.GetTheme())
{
case ThemeHelper.eVSTheme.kDark:
foregroundColor = Color.FromRgb(255, 255, 255);
subOptionsColor = Color.FromRgb(130, 203, 247);
explainOptColor = Color.FromRgb(255, 255, 255);
WindowTitle.Foreground = new SolidColorBrush(Color.FromRgb(186, 255, 171));
WindowTitle.Background = new SolidColorBrush(ThemeHelper.ToMediaColor(defaultBackground));
Background = backgroundCol;
//listView.Background = backgroundCol;
break;
case ThemeHelper.eVSTheme.kBlue:
foregroundColor = Color.FromRgb(0, 0, 0);
subOptionsColor = Color.FromRgb(100, 106, 106);
explainOptColor = Color.FromRgb(0, 0, 0);
WindowTitle.Foreground = new SolidColorBrush(Color.FromRgb(83, 114, 76));
WindowTitle.Background = new SolidColorBrush(ThemeHelper.ToMediaColor(defaultBackground));
Background = backgroundCol;
//.Background = backgroundCol;
break;
case ThemeHelper.eVSTheme.kLight:
foregroundColor = Color.FromRgb(0, 0, 0);
subOptionsColor = Color.FromRgb(100, 106, 106);
explainOptColor = Color.FromRgb(0, 0, 0);
WindowTitle.Foreground = new SolidColorBrush(Color.FromRgb(83, 114, 76));
WindowTitle.Background = backgroundCol;
Background = backgroundCol;
//listView.Background = backgroundCol;
break;
case ThemeHelper.eVSTheme.kUnknown:
//break;
default:
byte a = defaultForeground.A;
byte r = defaultForeground.R;
byte g = defaultForeground.G;
byte b = defaultForeground.B;
foregroundColor = Color.FromArgb(a, r, g, b);
subOptionsColor = Color.FromArgb(a, r, g, b);
explainOptColor = Color.FromArgb(a, r, g, b);
WindowTitle.Foreground = new SolidColorBrush(foregroundColor);
WindowTitle.Background = new SolidColorBrush(ThemeHelper.ToMediaColor(defaultBackground));
Dispatcher.BeginInvoke(new System.Action(() => MessageBox.Show("Spotify extension couldn't detect color scheme. \nWould you be so kind to file a bug report?")));
break;
}
//SetListViewColors(foregroundColor);
UpdateSettingsTitles(foregroundColor);
UpdateSettingsSubOptions(subOptionsColor);
UpdateExplainationSettings(explainOptColor);
}
private void UpdateSettingsTitles(Color color)
{
SolidColorBrush scb = new SolidColorBrush(color);
title_textVisibility.Foreground = scb;
title_hideButText.Foreground = scb;
title_showPlayListButton.Foreground = scb;
title_InteractiveInfo.Foreground = scb;
title_devInfoNotAvailable.Foreground = scb;
title_devInfo.Foreground = scb;
}
private void UpdateSettingsSubOptions(Color color)
{
SolidColorBrush scb = new SolidColorBrush(color);
rb_tv0.Foreground = scb;
rb_tv1.Foreground = scb;
rb_tv2.Foreground = scb;
checkBox_hideText.Foreground = scb;
checkBox_ShowTrackArtist.Foreground = scb;
checkBox_enableInteractiveAnimation.Foreground = scb;
}
private void UpdateExplainationSettings(Color color)
{
SolidColorBrush scb = new SolidColorBrush(color);
label_hideText.Foreground = scb;
additionalInfoEnableAnimation.Foreground = scb;
}
}
} | f763e6bff577801160354b76e18014b2fb06a147 | [
"Markdown",
"C#"
] | 8 | C# | petehughes/SpotifyRemote | 3713d4d6ab1d01cd3bbde718258e9ceea04e71ff | 454ba49585b8924debb16ee9e81c9c0ccd191828 |
refs/heads/master | <repo_name>tobpe/verisure-alarm<file_sep>/rf-receiver/verisure_rx.py
#!/usr/bin/env python
#=============================================================
# Securitas-Direct (Verisure) RF sniffer
# By <NAME> (http://funoverip.net / @funoverip)
#=============================================================
#
# Usage: verisure_rx.py [-k KEY]
#
# optional arguments:
# -k,--key <KEY> Optional AES-128 Key (hexadecimal)
#
#=============================================================
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import ctypes
import datetime
import argparse
from aes_cbc import aes_cbc
from grc.verisure_demod import verisure_demod
from threading import Thread
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
from time import sleep
# Colors
def pink(t): return '\033[95m' + t + '\033[0m'
def blue(t): return '\033[94m' + t + '\033[0m'
def yellow(t): return '\033[93m' + t + '\033[0m'
def green(t): return '\033[92m' + t + '\033[0m'
def red(t): return '\033[91m' + t + '\033[0m'
# Thread dedicated to GNU Radio flowgraph
class flowgraph_thread(Thread):
def __init__(self, flowgraph):
Thread.__init__(self)
self.setDaemon(1)
self._flowgraph = flowgraph
def run(self):
self._flowgraph.Run()
#print "FFT Closed/Killed"
# Generate timestamp
def get_time():
current_time = datetime.datetime.now().time()
return current_time.isoformat()
# Print out frames to stdout
def dump_frame(frame, aes):
# Dissecting frame
pkt_len = hexlify(frame[0:1])
unkn1 = hexlify(frame[1:2])
seqnr = hexlify(frame[2:3])
src_id = hexlify(frame[3:7])
dst_id = hexlify(frame[7:11])
data = ""
# Payload is a block of 16b and AES key provided ? Try to decrypt it
if (ord(unhexlify(pkt_len))-2-8) % 16 == 0 and aes!=None:
if unkn1 == '\x04':
# block is 16b without additional padding
data = " ".join(hexlify(n) for n in aes.decrypt(frame[11:], False))
else:
# block is 16b with padding
data = " ".join(hexlify(n) for n in aes.decrypt(frame[11:]))
if len(data) ==0:
data = "<empty> Wrong EAS key ?"
else:
data = " ".join(hexlify(n) for n in frame[11:])
# Print out the frame
print "[%s] %s %s %s %s %s %s" % (get_time(), yellow(pkt_len), blue(unkn1), seqnr, green(src_id), red(dst_id), pink(data))
# Main entry point
if __name__ == '__main__':
# Crypto object
aes = None
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
# Read args
parser = argparse.ArgumentParser()
parser.add_argument("-k", "--key", help="Optional AES-128 Key (hex)", type=str)
args = parser.parse_args()
# Initializing GNU Radio flowgraph
flowgraph = verisure_demod()
if args.key:
print "[%s] AES key provided. Decryption enabled" % get_time()
aes_key = args.key
aes_key = ''.join(aes_key.split())
aes_key = unhexlify(aes_key)
aes_iv = unhexlify("00000000000000000000000000000000")
print "[%s] AES-128 IV : %s" % (get_time(), hexlify(aes_iv))
print "[%s] AES-128 key: %s" % (get_time(), hexlify(aes_key))
aes = aes_cbc(aes_iv, aes_key)
# current frequency
freq = 0
# Some additional output
print "[%s] Starting flowgraph" % get_time()
# Start flowgraph insie a new thread
flowgraph_t = flowgraph_thread(flowgraph)
flowgraph_t.start()
# Until flowgraph thread is running (and we hope 'producing')
while flowgraph_t.isAlive():
# Did we change frequency ?
if freq != flowgraph.get_frequency():
print "[%s] Frequency tuned to: %0.2f KHz" % (get_time(), flowgraph.get_frequency()/1000)
freq = flowgraph.get_frequency()
# Emptying message queue
while True:
if flowgraph.myqueue.count() <= 0:
break;
frame = flowgraph.myqueue.delete_head_nowait().to_string()
dump_frame(frame, aes)
# I can't exit the script because of a blocking call to "myqueue.delete_head()". So for now..
sleep(0.1)
print "[%s] Exiting" % (get_time())
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<file_sep>/rf-receiver/grc/verisure_demod.py
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Verisure (Securitas Direct) - demodulator
# Generated: Sun Nov 16 10:44:20 2014
##################################################
from gnuradio import analog
from gnuradio import blocks
from gnuradio import digital
from gnuradio import eng_notation
from gnuradio import filter
from gnuradio import gr
from gnuradio import wxgui
from gnuradio.eng_option import eng_option
from gnuradio.fft import window
from gnuradio.filter import firdes
from gnuradio.wxgui import fftsink2
from gnuradio.wxgui import forms
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import cc1111
import math
import osmosdr
import wx
class verisure_demod(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Verisure (Securitas Direct) - demodulator")
##################################################
# Variables
##################################################
self.symbole_rate = symbole_rate = 38450
self.samp_rate = samp_rate = 2.0e06
self.rat_interop = rat_interop = 8
self.rat_decim = rat_decim = 5
self.frequency_tune = frequency_tune = 17.22e3
self.frequency_shift = frequency_shift = 0.52e06
self.frequency_center = frequency_center = 868.5e06
self.firdes_transition_width = firdes_transition_width = 15000
self.firdes_decim = firdes_decim = 4
self.firdes_cutoff = firdes_cutoff = 21e3
self.samp_per_sym = samp_per_sym = ((samp_rate/2/firdes_decim)*rat_interop/rat_decim) / symbole_rate
self.rf_gain = rf_gain = 0
self.myqueue = myqueue = gr.msg_queue(200)
self.if_gain = if_gain = 20
self.frequency = frequency = frequency_center + frequency_shift + frequency_tune
self.freq_display = freq_display = frequency_center + frequency_shift + frequency_tune
self.firdes_filter = firdes_filter = firdes.low_pass(1,samp_rate/2, firdes_cutoff, firdes_transition_width)
self.fft_sp = fft_sp = 50000
self.crc_verbose = crc_verbose = False
self.bb_gain = bb_gain = 20
self.access_code = access_code = '11010011100100011101001110010001'
##################################################
# Blocks
##################################################
_rf_gain_sizer = wx.BoxSizer(wx.VERTICAL)
self._rf_gain_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_rf_gain_sizer,
value=self.rf_gain,
callback=self.set_rf_gain,
label="RF Gain",
converter=forms.float_converter(),
proportion=0,
)
self._rf_gain_slider = forms.slider(
parent=self.GetWin(),
sizer=_rf_gain_sizer,
value=self.rf_gain,
callback=self.set_rf_gain,
minimum=0,
maximum=14,
num_steps=15,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_rf_gain_sizer, 0, 0, 1, 1)
_if_gain_sizer = wx.BoxSizer(wx.VERTICAL)
self._if_gain_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_if_gain_sizer,
value=self.if_gain,
callback=self.set_if_gain,
label="IF Gain",
converter=forms.float_converter(),
proportion=0,
)
self._if_gain_slider = forms.slider(
parent=self.GetWin(),
sizer=_if_gain_sizer,
value=self.if_gain,
callback=self.set_if_gain,
minimum=0,
maximum=30,
num_steps=31,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_if_gain_sizer, 0, 1, 1, 1)
_frequency_tune_sizer = wx.BoxSizer(wx.VERTICAL)
self._frequency_tune_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_frequency_tune_sizer,
value=self.frequency_tune,
callback=self.set_frequency_tune,
label="Frequency Tuning",
converter=forms.float_converter(),
proportion=0,
)
self._frequency_tune_slider = forms.slider(
parent=self.GetWin(),
sizer=_frequency_tune_sizer,
value=self.frequency_tune,
callback=self.set_frequency_tune,
minimum=-30e3,
maximum=30e3,
num_steps=1000,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_frequency_tune_sizer, 0, 3, 1, 1)
_bb_gain_sizer = wx.BoxSizer(wx.VERTICAL)
self._bb_gain_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_bb_gain_sizer,
value=self.bb_gain,
callback=self.set_bb_gain,
label="BB Gain",
converter=forms.float_converter(),
proportion=0,
)
self._bb_gain_slider = forms.slider(
parent=self.GetWin(),
sizer=_bb_gain_sizer,
value=self.bb_gain,
callback=self.set_bb_gain,
minimum=0,
maximum=30,
num_steps=31,
style=wx.SL_HORIZONTAL,
cast=float,
proportion=1,
)
self.GridAdd(_bb_gain_sizer, 0, 2, 1, 1)
self.wxgui_fftsink2_0 = fftsink2.fft_sink_c(
self.GetWin(),
baseband_freq=frequency_center + frequency_shift + frequency_tune,
y_per_div=10,
y_divs=10,
ref_level=0,
ref_scale=2.0,
sample_rate=fft_sp,
fft_size=512,
fft_rate=15,
average=False,
avg_alpha=None,
title="FFT",
peak_hold=True,
)
self.GridAdd(self.wxgui_fftsink2_0.win, 2, 0, 1, 4)
self.rational_resampler_xxx_0_0 = filter.rational_resampler_ccc(
interpolation=rat_interop,
decimation=rat_decim,
taps=None,
fractional_bw=None,
)
self.rational_resampler_xxx_0 = filter.rational_resampler_ccc(
interpolation=1,
decimation=int(samp_rate/2/fft_sp),
taps=None,
fractional_bw=None,
)
self.osmosdr_source_0 = osmosdr.source( args="numchan=" + str(1) + " " + "hackrf=0" )
self.osmosdr_source_0.set_sample_rate(samp_rate)
self.osmosdr_source_0.set_center_freq(frequency_center, 0)
self.osmosdr_source_0.set_freq_corr(0, 0)
self.osmosdr_source_0.set_dc_offset_mode(0, 0)
self.osmosdr_source_0.set_iq_balance_mode(0, 0)
self.osmosdr_source_0.set_gain_mode(False, 0)
self.osmosdr_source_0.set_gain(rf_gain, 0)
self.osmosdr_source_0.set_if_gain(if_gain, 0)
self.osmosdr_source_0.set_bb_gain(bb_gain, 0)
self.osmosdr_source_0.set_antenna("", 0)
self.osmosdr_source_0.set_bandwidth(0, 0)
self.freq_xlating_fir_filter_xxx_1 = filter.freq_xlating_fir_filter_ccc(2, (1, ), frequency_shift+frequency_tune, samp_rate)
self.freq_xlating_fir_filter_xxx_0_0 = filter.freq_xlating_fir_filter_ccc(firdes_decim, (firdes_filter), 0, samp_rate/2)
self._freq_display_static_text = forms.static_text(
parent=self.GetWin(),
value=self.freq_display,
callback=self.set_freq_display,
label="Current Frequency",
converter=forms.float_converter(),
)
self.GridAdd(self._freq_display_static_text, 1, 0, 1, 4)
self.digital_correlate_access_code_bb_0_0 = digital.correlate_access_code_bb(access_code, 1)
self.digital_clock_recovery_mm_xx_0_0 = digital.clock_recovery_mm_ff(samp_per_sym*(1+0.0), 0.25*0.175*0.175, 0.5, 0.175, 0.005)
self.digital_binary_slicer_fb_0_0_0 = digital.binary_slicer_fb()
self.cc1111_cc1111_packet_decoder_0 = cc1111.cc1111_packet_decoder(myqueue,True, True, False, False)
self.blocks_null_sink_0_0 = blocks.null_sink(gr.sizeof_char*1)
self.analog_quadrature_demod_cf_0_0 = analog.quadrature_demod_cf(2)
##################################################
# Connections
##################################################
self.connect((self.rational_resampler_xxx_0_0, 0), (self.analog_quadrature_demod_cf_0_0, 0))
self.connect((self.freq_xlating_fir_filter_xxx_0_0, 0), (self.rational_resampler_xxx_0_0, 0))
self.connect((self.digital_binary_slicer_fb_0_0_0, 0), (self.digital_correlate_access_code_bb_0_0, 0))
self.connect((self.digital_clock_recovery_mm_xx_0_0, 0), (self.digital_binary_slicer_fb_0_0_0, 0))
self.connect((self.digital_correlate_access_code_bb_0_0, 0), (self.cc1111_cc1111_packet_decoder_0, 0))
self.connect((self.cc1111_cc1111_packet_decoder_0, 0), (self.blocks_null_sink_0_0, 0))
self.connect((self.analog_quadrature_demod_cf_0_0, 0), (self.digital_clock_recovery_mm_xx_0_0, 0))
self.connect((self.freq_xlating_fir_filter_xxx_1, 0), (self.freq_xlating_fir_filter_xxx_0_0, 0))
self.connect((self.freq_xlating_fir_filter_xxx_1, 0), (self.rational_resampler_xxx_0, 0))
self.connect((self.rational_resampler_xxx_0, 0), (self.wxgui_fftsink2_0, 0))
self.connect((self.osmosdr_source_0, 0), (self.freq_xlating_fir_filter_xxx_1, 0))
def get_symbole_rate(self):
return self.symbole_rate
def set_symbole_rate(self, symbole_rate):
self.symbole_rate = symbole_rate
self.set_samp_per_sym(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate)
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.set_firdes_filter(firdes.low_pass(1,self.samp_rate/2, self.firdes_cutoff, self.firdes_transition_width))
self.set_samp_per_sym(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate)
self.osmosdr_source_0.set_sample_rate(self.samp_rate)
def get_rat_interop(self):
return self.rat_interop
def set_rat_interop(self, rat_interop):
self.rat_interop = rat_interop
self.set_samp_per_sym(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate)
def get_rat_decim(self):
return self.rat_decim
def set_rat_decim(self, rat_decim):
self.rat_decim = rat_decim
self.set_samp_per_sym(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate)
def get_frequency_tune(self):
return self.frequency_tune
def set_frequency_tune(self, frequency_tune):
self.frequency_tune = frequency_tune
self.set_frequency(self.frequency_center + self.frequency_shift + self.frequency_tune)
self._frequency_tune_slider.set_value(self.frequency_tune)
self._frequency_tune_text_box.set_value(self.frequency_tune)
self.set_freq_display(self.frequency_center + self.frequency_shift + self.frequency_tune)
self.freq_xlating_fir_filter_xxx_1.set_center_freq(self.frequency_shift+self.frequency_tune)
self.wxgui_fftsink2_0.set_baseband_freq(self.frequency_center + self.frequency_shift + self.frequency_tune)
def get_frequency_shift(self):
return self.frequency_shift
def set_frequency_shift(self, frequency_shift):
self.frequency_shift = frequency_shift
self.set_frequency(self.frequency_center + self.frequency_shift + self.frequency_tune)
self.set_freq_display(self.frequency_center + self.frequency_shift + self.frequency_tune)
self.freq_xlating_fir_filter_xxx_1.set_center_freq(self.frequency_shift+self.frequency_tune)
self.wxgui_fftsink2_0.set_baseband_freq(self.frequency_center + self.frequency_shift + self.frequency_tune)
def get_frequency_center(self):
return self.frequency_center
def set_frequency_center(self, frequency_center):
self.frequency_center = frequency_center
self.set_frequency(self.frequency_center + self.frequency_shift + self.frequency_tune)
self.set_freq_display(self.frequency_center + self.frequency_shift + self.frequency_tune)
self.osmosdr_source_0.set_center_freq(self.frequency_center, 0)
self.wxgui_fftsink2_0.set_baseband_freq(self.frequency_center + self.frequency_shift + self.frequency_tune)
def get_firdes_transition_width(self):
return self.firdes_transition_width
def set_firdes_transition_width(self, firdes_transition_width):
self.firdes_transition_width = firdes_transition_width
self.set_firdes_filter(firdes.low_pass(1,self.samp_rate/2, self.firdes_cutoff, self.firdes_transition_width))
def get_firdes_decim(self):
return self.firdes_decim
def set_firdes_decim(self, firdes_decim):
self.firdes_decim = firdes_decim
self.set_samp_per_sym(((self.samp_rate/2/self.firdes_decim)*self.rat_interop/self.rat_decim) / self.symbole_rate)
def get_firdes_cutoff(self):
return self.firdes_cutoff
def set_firdes_cutoff(self, firdes_cutoff):
self.firdes_cutoff = firdes_cutoff
self.set_firdes_filter(firdes.low_pass(1,self.samp_rate/2, self.firdes_cutoff, self.firdes_transition_width))
def get_samp_per_sym(self):
return self.samp_per_sym
def set_samp_per_sym(self, samp_per_sym):
self.samp_per_sym = samp_per_sym
self.digital_clock_recovery_mm_xx_0_0.set_omega(self.samp_per_sym*(1+0.0))
def get_rf_gain(self):
return self.rf_gain
def set_rf_gain(self, rf_gain):
self.rf_gain = rf_gain
self._rf_gain_slider.set_value(self.rf_gain)
self._rf_gain_text_box.set_value(self.rf_gain)
self.osmosdr_source_0.set_gain(self.rf_gain, 0)
def get_myqueue(self):
return self.myqueue
def set_myqueue(self, myqueue):
self.myqueue = myqueue
def get_if_gain(self):
return self.if_gain
def set_if_gain(self, if_gain):
self.if_gain = if_gain
self._if_gain_slider.set_value(self.if_gain)
self._if_gain_text_box.set_value(self.if_gain)
self.osmosdr_source_0.set_if_gain(self.if_gain, 0)
def get_frequency(self):
return self.frequency
def set_frequency(self, frequency):
self.frequency = frequency
def get_freq_display(self):
return self.freq_display
def set_freq_display(self, freq_display):
self.freq_display = freq_display
self._freq_display_static_text.set_value(self.freq_display)
def get_firdes_filter(self):
return self.firdes_filter
def set_firdes_filter(self, firdes_filter):
self.firdes_filter = firdes_filter
self.freq_xlating_fir_filter_xxx_0_0.set_taps((self.firdes_filter))
def get_fft_sp(self):
return self.fft_sp
def set_fft_sp(self, fft_sp):
self.fft_sp = fft_sp
self.wxgui_fftsink2_0.set_sample_rate(self.fft_sp)
def get_crc_verbose(self):
return self.crc_verbose
def set_crc_verbose(self, crc_verbose):
self.crc_verbose = crc_verbose
def get_bb_gain(self):
return self.bb_gain
def set_bb_gain(self, bb_gain):
self.bb_gain = bb_gain
self._bb_gain_slider.set_value(self.bb_gain)
self._bb_gain_text_box.set_value(self.bb_gain)
self.osmosdr_source_0.set_bb_gain(self.bb_gain, 0)
def get_access_code(self):
return self.access_code
def set_access_code(self, access_code):
self.access_code = access_code
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
(options, args) = parser.parse_args()
tb = verisure_demod()
tb.Start(True)
tb.Wait()
<file_sep>/utils/vbox-mem-parser.py
#!/usr/bin/env python
#
# Parse Verisure Vbox memory (dumpfile) and search for personal crypt/hash keys
# By <NAME> (http://funoverip.net / @funoverip)
#
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import argparse
from binascii import hexlify, unhexlify
from securitas_name_convert import id2name, name2id, name2id_as_str
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--nodename", help=" Vbox node Name (ex: '262D 3BF9')", type=str , required=False)
parser.add_argument("-i", "--nodeid", help="Vbox node ID (ex: '0100d37c')", type=str , required=False)
parser.add_argument("-f", "--file", help="Memory dump file", type=str , required=True)
args = parser.parse_args()
# Testing node args
vbox_id_as_str=''
vbox_id=0
vbox_name=''
if not (args.nodename or args.nodeid) or (args.nodename and args.nodeid):
print "Error. You must provide the name (-n) OR the id (-i) of your Vbox"
sys.exit(0)
if args.nodeid:
vbox_id_as_str = unhexlify(args.nodeid)
vbox_id_as_str = vbox_id_as_str[3] + vbox_id_as_str[2] + vbox_id_as_str[1] + vbox_id_as_str[0]
vbox_id = long(args.nodeid, 16)
vbox_name = id2name(vbox_id)
if args.nodename:
vbox_name = args.nodename
vbox_id = name2id(vbox_name)
vbox_id_as_str = name2id_as_str(vbox_name)
vbox_id_as_str = vbox_id_as_str[3] + vbox_id_as_str[2] + vbox_id_as_str[1] + vbox_id_as_str[0]
# Testing dumpfile arg
dumpfile = args.file
try:
dumpfile_size = os.path.getsize(dumpfile)
except:
print "ERROR while opening %s" % dumpfile
sys.exit(0)
print "[*] Provided arguments:"
print " Dumpfile : %s" % dumpfile
print " Dumpfile size: %d bytes" % dumpfile_size
print " Vbox name : %s" % vbox_name
print " Vbox id : %08x" % vbox_id
print "[*] Searching memory..."
with open(dumpfile, "rb") as f:
mem = f.read()
i =0
found_device_list = False
while i <= dumpfile_size-4:
# Searching VBOX id
#===================
found_vbox = False
while True:
if i >= dumpfile_size-4:
break
if mem[i:i+4] == vbox_id_as_str:
print " Potential device list was found.. ",
found_vbox = True
break
i+=1
# Found it? Then get keys
#========================
if found_vbox:
device_id = mem[i:i+4]
i+=4
# Do we have 32 null free byte + \x00 or \x02 ?
if not '\x00' in mem[i:i+32] and (mem[i+32] == '\x00' or mem[i+32] == '\x02'):
print "=> Confirmed!"
print "[*] Extracting device list and crypto keys"
found_device_list = True
key_crypt = ' '.join(hexlify(n) for n in mem[i:i+16])
key_hash = ' '.join(hexlify(n) for n in mem[i+16:i+32])
print " Device : %s (VBOX!) " % hexlify(device_id[3] + device_id[2] + device_id[1] + device_id[0])
print " crypt: %s" % key_crypt if len(key_crypt) == 47 else " crypt: %s <INCOMPLETE>" % key_crypt
print " hash : %s" % key_hash if len(key_hash) == 47 else " hash : %s <INCOMPLETE>" % key_hash
i+=32 # keys space
i+=1 # ending byte
# Searching for other device/keys
for j in range(0,63):
if i >= dumpfile_size-4:
break
device_id = mem[i:i+4]
i+=4
key_crypt = ' '.join(hexlify(n) for n in mem[i:i+16])
i+=16
key_hash = ' '.join(hexlify(n) for n in mem[i:i+16])
i+=16
i+=1
if not device_id == '\x00\x00\x00\x00':
print " Device : %s" % hexlify(device_id[3] + device_id[2] + device_id[1] + device_id[0])
print " crypt: %s" % key_crypt if len(key_crypt) == 47 else " crypt: %s <INCOMPLETE>" % key_crypt
print " hash : %s" % key_hash if len(key_hash) == 47 else " hash : %s <INCOMPLETE>" % key_hash
print "[*] Done"
break
# We do NOT have 32 null free byte + (\x00 or \x02)
else:
print "=> False positive"
else:
print "[-] VBox not found in dumpfile"
break
sys.exit(0)
<file_sep>/lib/securitas_name_convert.py
import numpy as np
from struct import pack, unpack
word_8736E = "\x00\x01\x02\x03\x04\x05\x06\x07\xff\xff\xff\xff\xff\xff\xff" + \
"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\xff\x10\x11\x12\x13\x14\xff" + \
"\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
unk_87397 = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
def id2name(id):
global unk_87397
tmp = id >> 24
result = ((id << 8) | (((id >> 16) ^ (id >> 8) ^ id ^ (id >> 24)) & 0xFF)) & 0xffffffff
ret = ''
for i in reversed(range(0,9)):
if i == 4:
ret = ' ' + ret
else:
ret = unk_87397[result & 0x1F] + ret
result = (result >> 5) | (tmp << 27)
tmp >>= 5
return ret
def name2id(name):
global word_8736E
i = np.int32(0)
j = i
result = np.int64(0)
while True:
if i > j + 7:
return np.int32(result >> 8)
c = np.uint8(ord(name[i]))
if c == np.uint8(ord(' ')):
j += 1
else:
tmp = word_8736E[c - 50]
if ord(tmp) == 255:
return 0
v10 = np.uint32(result >> 27)
result_lo = np.uint32(np.uint32(ord(tmp) & 0x1F) | np.int64(32 * np.uint32(result)))
result_hi = v10 | (32 * (result >> 32))
result = np.int64( (result_hi << 32) | result_lo )
i += 1
def name2id_as_str(name):
return pack(">I",name2id(name))
<file_sep>/utils/name2id.py
#!/usr/bin/env python
#
# Convert Verisure node Name to node ID
# By <NAME> (http://funoverip.net / @funoverip)
#
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
from securitas_name_convert import id2name, name2id
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: %s <name>" % sys.argv[0]
print "Ex: %s '262E 9BV7'" % sys.argv[0]
sys.exit(0)
nodename = sys.argv[1]
nodeid = name2id(nodename)
print "Name: %s" % nodename
print "Id : %08x" % nodeid
<file_sep>/lib/aes_cbc.py
#!/usr/bin/en python
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
class aes_cbc:
def __init__(self, iv, key):
self.BS = 16
self.iv = iv
self.key = key
def pad(self, s):
return s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
def unpad(self,s):
return s[0:-ord(s[-1])]
def decrypt(self, ciphertext, padding=True):
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
plaintext = cipher.decrypt(ciphertext)
if padding:
return self.unpad(plaintext)
else:
return plaintext
def encrypt(self, cleartext, padding=True):
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
if padding:
ciphertext = cipher.encrypt(self.pad(cleartext))
else:
ciphertext = cipher.encrypt(cleartext) # really ??????
return ciphertext
<file_sep>/README.md
Introduction
============
Repository containing my Verisure Wireless alarm scripts related to the following blogposts:
- http://funoverip.net/2014/11/reverse-engineer-a-verisure-wireless-alarm-part-1-radio-communications/
- http://funoverip.net/2014/12/reverse-engineer-a-verisure-wireless-alarm-part-2-firmwares-and-crypto-keys/
Author
======
- Name: <NAME>
- E-mail: <EMAIL>
- Web: http://funoverip.net
- Twitter: @funoverip.net
GNU Radio RF Receiver HOWTO
===========================
Some notes
----------
- Dependency: **GNURadio >= 3.7** and **gr-cc1111 blocks** (see https://github.com/funoverip/gr-cc1111)
- An optional AES key can be provided using '-k' switch if you want to decrypt the payloads. Keys are randomly generated by the VBox. The way we recovered the key is explained here: http://funoverip.net/?p=1879
Output sample
-------------
```
$ cd rf-receiver/
$ ./verisure_rx.py -k <KEY>
linux; GNU C++ version 4.8.2; Boost_105400; UHD_003.007.002-0-unknown
Using Volk machine: sse4_2_32_orc
gr-osmosdr v0.1.3-1-g4bb2fa4e (0.1.4git) gnuradio 3.7.5git-214-g94562c93
built-in source types: file fcd rtl rtl_tcp uhd hackrf rfspace
Using HackRF One with firmware 2014.08.1
[13:10:11.803448] AES key provided. Decryption enabled
[13:10:11.803569] AES-128 IV : 00000000000000000000000000000000
[13:10:11.803626] AES-128 key: <KEY>
[13:10:11.803682] Starting flowgraph
[13:10:11.804074] Frequency tuned to: 869037.22 KHz
[13:10:20.175256] 0f 14 14 0100c3a7 ffffffff 81 00 00 00 00
[13:10:20.175462] 0f 14 18 0100c3a7 ffffffff 81 00 0a 00 00
[13:10:20.175559] 0f 14 1c 0100c3a7 ffffffff 81 00 14 00 00
[13:10:20.175693] 0f 14 00 0100c3a7 ffffffff 81 00 1e 00 00
[13:11:00.365623] 1a 08 d8 050232d1 0100c3a7 58 f9 87 00 1e 9e f9 82 62
[13:11:00.365757] 1a 0c c7 0100c3a7 050232d1 01 8d 88 00 00 85 85 70 bb
[13:11:20.115119] 0f 14 08 0100c3a7 ffffffff 81 00 00 00 00
[13:11:20.115237] 0f 14 0c 0100c3a7 ffffffff 81 00 0a 00 00
[13:11:20.222030] 0f 14 10 0100c3a7 ffffffff 81 00 14 00 00
[13:11:20.222251] 0f 14 14 0100c3a7 ffffffff 81 00 1e 00 00
[13:12:20.135730] 0f 14 18 0100c3a7 ffffffff 81 00 00 00 00
[13:12:20.136097] 0f 14 1c 0100c3a7 ffffffff 81 00 0a 00 00
[13:12:20.136260] 0f 14 00 0100c3a7 ffffffff 81 00 14 00 00
[13:12:20.136453] 0f 14 04 0100c3a7 ffffffff 81 00 1e 00 00
[13:12:40.267982] 1a 08 dc 050232db 0100c3a7 0a 68 87 00 1e 32 f4 a9 77
[13:12:40.368316] 1a 0c cb 0100c3a7 050232db 01 bb 88 00 00 0b 3a 0c 8a
[13:13:12.124306] 1a 08 db 0301fa45 0100c3a7 0e cc 87 00 94 3d 0a 7d 87
[13:13:12.224630] 1a 0e cf 0100c3a7 0301fa45 08 10 88 00 00 8e 26 2d 50
```
| 2f128c0f789686b12b36c8f69a4d51b80922996a | [
"Markdown",
"Python"
] | 7 | Python | tobpe/verisure-alarm | 50bd52e55806400c779f39ad4cc3a3238a5a1046 | 2646d9bf9402b91bf73cedcb90074d1727b0dc99 |
refs/heads/master | <file_sep>import React from 'react';
import {Link} from 'react-router-dom';
const Welcome = () => (
<div style={{display:"grid", gridTemplateColumns: "100%", gridTemplateRows:"60vh 40vh"}}>
<div id="main-title" className="tc f-subheadline-l f1-m f3 1h-title fw3" style={{padding:"10vw", paddingTop: "15vh", color: "white"}}>
<span className="text-highlight">Welcome to my super-ordinanry, </span>
<span className="text-highlight">mega-basic, underwhelmingly-simple </span>
<span className="text-highlight">Task Manager App</span>
</div>
<div id="callToAction" className="f2-l f2-m f4" style={{alignSelf:"start", justifySelf:"center"}}>
<Link to="/signin">
<span className="no-underline grow dib v-mid white ba ph3 pv2 mb3" style={{backgroundColor:"#3f6389", border:"none"}}>Sign In</span>
</Link>
<span className="dib v-mid ph3 white-70 mb3">or</span>
<Link to="signup">
<span className="no-underline grow dib v-mid white ba b--white ph3 pv2 mb3">Sign Up</span>
</Link>
</div>
</div>
);
export default Welcome;<file_sep>import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from 'react-router-dom';
import Welcome from './components/welcome';
import Signin from './components/signin';
import Signup from './components/signup';
import Settings from './components/settings';
import Home from './components/home';
import PrivateRoute from './components/privateroute';
import './App.css';
import 'tachyons';
class App extends React.Component {
render () {
return (
<Router>
<Switch>
<Route path='/signin' component={Signin}/>
<Route path='/signup' component={Signup}/>
<PrivateRoute path='/settings' component={Settings}/>
<PrivateRoute path='/home' component={Home}/>
<Route path='/' component={Welcome}/>
</Switch>
</Router>
);
}
}
export default App;
<file_sep>import React from 'react';
const Home = () => (
<div style={{backgroundColor:"white", height:'100vh'}}>
hello
</div>
)
export default Home;<file_sep>import reducer from "./Reduce";
import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from 'redux-thunk';
export const intialState = {
user: {},
authenticated: false,
token: '',
loggedIn: false,
tasks: [],
isFetching: false,
}
export const store = createStore(reducer, intialState, applyMiddleware( thunkMiddleware ));<file_sep>import * as AT from './ActionsTypes';
import {intialState} from './Store';
export default (state, action) => {
if (typeof state === 'undefined') {
return intialState;
}
switch(action.type){
case AT.FETCHING:
return {
...state,
isFetching: true
}
case AT.DONE_FETCHING:
return {
...state,
isFetching: false
}
case AT.SIGNIN:
case AT.SIGNUP:
return {
...state,
authenticated: true,
user: action.user,
token: action.token,
loggedIn: true
}
case AT.SIGNOUT:
return {
...state,
user: '',
token: '',
loggedIn: false
}
default:
return state;
}
}
<file_sep>export const SIGNIN = 'SIGNIN';
export const SIGNUP = 'SIGNUP';
export const AUTHENTICATING = 'AUTHENTICATING';
export const REGISTRATING_USER = 'REGISTRATING USER';
export const SIGNOUT = 'LOGOUT';
export const FAILED_AUTH = 'FAILED AUTH';
export const FAILED_SIGNUP = "FAILED SIGNUP";
export const FETCHING = "FETCHING";
export const DONE_FETCHING = "DONE FETCHING";<file_sep>import * as AT from './ActionsTypes';
import {API_URL} from './Constants';
export const fetching = () => {
return {
type: AT.FETCHING
}
}
export const doneFetching = () => {
return {
type: AT.DONE_FETCHING
}
}
export const signin = (user, token) => {
return {
type: AT.SIGNIN,
user,
token
}
}
export const signup = (user, token) => {
return {
type: AT.SIGNUP,
user,
token
}
}
export const signout = () => {
return {
type: AT.SIGNOUT
}
}
export const authenticateUser = ({email, password}) => {
console.log('authenticating user')
return async (dispatch) => {
dispatch(fetching())
try {
console.log('fetching')
const body = JSON.stringify({email, password});
console.log(body);
const response = await fetch(`${API_URL}/users/login`, {
method: 'post',
headers: {'Content-Type': 'application/json'},
body
});
if (response.status === 200) {
const {user, token} = await response.json();
console.log(user, token)
dispatch(signin(user, token));
} else {
}
dispatch(doneFetching());
} catch(e) {
console.log(e)
dispatch(doneFetching());
}
}
}
export const registerUser = ({email, name, password}) => {
return async (dispatch) => {
dispatch(fetching());
try {
const rawResponse = await fetch(`${API_URL}/users`, {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({email, name, password})
});
const response = await rawResponse.json();
if (response.status === 201) {
const {user, token} = response;
console.log(user, token)
dispatch(signup(user, token));
} else {
}
dispatch(doneFetching());
} catch (e) {
console.log(e);
dispatch(doneFetching());
}
}
}
<file_sep>import React from 'react';
import {registerUser} from '../Redux/Actions'
import Form from './form';
const Signup = () => (
<div>
<Form title = "Sign Up" fields = "name email password" action={registerUser}/>
</div>
)
export default Signup;<file_sep>import React from 'react';
import {authenticateUser} from '../Redux/Actions';
import Form from './form';
class Signin extends React.Component{
render() {
return (
<div>
<Form title = "Sign In" fields="email password" action = {authenticateUser}/>
</div>
)
}
}
export default Signin; | 2d0b755f15f1759cf7013a0f9689819e3497d769 | [
"JavaScript"
] | 9 | JavaScript | yoaveshel/Task-Manager-Frontend | 0cfae7bee96055cd9d8ac490bf17552ae1b45213 | 491064a6614ab02f4d5d957838b159c0157da0c7 |
refs/heads/master | <file_sep>Django==1.11
djangorestframework==3.4.1
<file_sep>from django.contrib.auth.models import User
from django.test import TestCase
from pugorugh.models import Dog, UserDog, UserPref
# 2. Test get all dogs
# 3. Test get single dog
# 4. Test delete single dog
# 5. Test update single dog
# 6. Test create user preferences
# 7. Test get user preferences
# 8. Test update user preferences
# 9. Test update new user prefernces - updates all dogs that match with U
# 10. Test validiators - bad entries
# 11. Test get all liked dogs
# 12. Test get all unliked dogs
# 13. Test get all undecided dogs
# 14. Test iterate through next like or disliked or undecided
# 15. Test new user creation - token creates
# 16. Test the URLS
# create a base modeltest case the models
class BaseTestCase(TestCase):
def setUp(self):
''' setup up dummy data for the Dog model '''
dog_1 = {
'name': 'dog_1',
'image_filename': '1.jpg',
'breed': 'mutt',
'age': 12,
'gender': 'm',
'size': 'm'
}
dog_2 = {
'name': 'dog_2',
'image_filename': '2.jpg',
'breed': 'mutt',
'age': 48,
'gender': 'f',
'size': 'l'
}
self.dog_1 = Dog.objects.create(**dog_1)
self.dog_2 = Dog.objects.create(**dog_2)
def tearDown(self):
pass
class UserModelTestCase(BaseTestCase):
''' test cases for the user model '''
@staticmethod
def create_test_users(count=2):
''' this test creates 2 users in the database
'''
for i in range(count):
User.objects.create(
username='user_{}'.format(i),
email='<EMAIL>'.<EMAIL>(i),
password='<PASSWORD>'
)
def test_create_user(self):
''' test the creation of the user '''
self.create_test_users()
self.assertEqual(User.objects.count(), 2)
self.assertEqual(User.objects.get(id=1).password,'<PASSWORD>')
class DogModelTests(BaseTestCase):
''' testing of the Dog model '''
def test_dog_creation(self):
''' test out the creation of our model '''
balto = Dog.objects.get(name="dog_1")
self.assertEqual(balto, self.dog_1)
alfie = Dog.objects.get(name="dog_2")
self.assertEqual(alfie, self.dog_2)
class UserDogModelTests(BaseTestCase):
''' testing of the UserDog model '''
def create_user_dogs(self):
UserModelTestCase.create_test_users(2)
self.user_1 = User.objects.get(id=1)
self.user_2 = User.objects.get(id=2)
UserDog.objects.create(user=self.user_1, dog=self.dog_1, status='u')
UserDog.objects.create(user=self.user_1, dog=self.dog_2, status='u')
UserDog.objects.create(user=self.user_2, dog=self.dog_1, status='u')
UserDog.objects.create(user=self.user_2, dog=self.dog_2, status='u')
def test_user_dog_creation(self):
''' test the creation of userdogs '''
self.create_user_dogs()
self.assertEqual(UserDog.objects.count(), 4)
self.assertEqual(UserDog.objects.get(id=1).user, self.user_1)
self.assertEqual(UserDog.objects.get(id=1).status, 'u')
class UserPrefModelTests(BaseTestCase):
''' testing of the UserDog model '''
def create_user_prefs(self):
UserModelTestCase.create_test_users(1)
self.user_1 = User.objects.get(id=1)
UserPref.objects.create(user=self.user_1,
age='b,y',
gender='m,f',
size='l,xl'
)
def test_user_dog_creation(self):
''' test the creation of userdogs '''
self.create_user_prefs()
self.assertEqual(UserPref.objects.count(), 1)
self.assertEqual(UserPref.objects.get(id=1).user, self.user_1)
self.assertEqual(UserPref.objects.get(id=1).gender, 'm,f')
<file_sep>
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient, APITestCase
from pugorugh.models import Dog, UserDog, UserPref
class BaseTestCase(APITestCase):
'''SETUP '''
def setUp(self):
self.client = APIClient()
''' create users to be used in our dummy data '''
self.user_1 = User.objects.create(
username='test_user_1',
email='<EMAIL>',
password='<PASSWORD>'
)
self.user1_token = Token.objects.create(user=self.user_1)
self.user_2 = User.objects.create(
username='test_user_2',
email='<EMAIL>',
password='<PASSWORD>'
)
self.user2_token = Token.objects.create(user=self.user_2)
''' setup up dummy data for the Dog model '''
dog_1 = {
'name': 'dog_1',
'image_filename': '1.jpg',
'breed': 'mutt',
'age': 12,
'gender': 'm',
'size': 'm'
}
dog_2 = {
'name': 'dog_2',
'image_filename': '2.jpg',
'breed': 'mutt',
'age': 48,
'gender': 'f',
'size': 'l'
}
self.dog_1 = Dog.objects.create(**dog_1)
self.dog_2 = Dog.objects.create(**dog_2)
''' set up dummy data for UserPerf Model '''
user_pref_1 = {
'user': self.user_1,
'age': 'b,y',
'gender': 'm,f',
'size': 'l, xl'
}
user_pref_2 = {
'user': self.user_2,
'age': 'a,s',
'gender': 'm',
'size': 's, m'
}
self.user_pref_1 = UserPref.objects.create(**user_pref_1)
self.user_pref_2 = UserPref.objects.create(**user_pref_2)
''' setup up dummy data for the UserDog model '''
user_dog_1 = {
'user': self.user_1,
'dog': self.dog_1,
'status': 'd'
}
user_dog_2 = {
'user': self.user_2,
'dog': self.dog_2,
'status': 'l'
}
self.user_dog_1 = UserDog.objects.create(**user_dog_1)
self.user_dog_2 = UserDog.objects.create(**user_dog_2)
# url : /api/user/
class UserViewsTests(BaseTestCase):
def test_register_bad_user(self):
response = self.client.post('/api/user/')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_register_good_user(self):
response = self.client.post('/api/user/',
{'username': 'test',
'password': '<PASSWORD>'})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data['username'], 'test')
self.assertEqual(response.data['is_active'], True)
def test_login_bad_user(self):
response = self.client.post('/api/user/login/')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_login_good_user(self):
response = self.client.post('/api/user/',
{'username': 'test',
'password': '<PASSWORD>'})
self.user_token = Token.objects.get(user__username='test')
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user_token.key
)
response = self.client.post('/api/user/login/',
{'username': 'test',
'password': '<PASSWORD>'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEquals(self.user_token.key, response.data['token'])
# url : /api/user/prefernces/
class UserPrefViewTests(BaseTestCase):
''' test the retreval of the user prefernences '''
def test_get_user_prefernces(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user1_token.key
)
response = self.client.get('/api/user/preferences/')
self.assertEqual(response.data['age'], 'b,y')
def test_put_user_preferences(self):
data = {'size': 's,m,l'}
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user1_token.key
)
response = self.client.put('/api/user/preferences/', data=data)
self.assertEqual(response.data['size'], 's,m,l')
# url : /api/dog/-?<pk>/<ldu_decision>/next?/
class LDUDogViewTests(BaseTestCase):
''' test the retreval of the liked dogs '''
def test_get_liked_dogs(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user2_token.key
)
response = self.client.get('/api/dog/-1/liked/next/')
self.assertEqual(response.data['name'], self.dog_2.name)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_disliked_dogs(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user1_token.key
)
response = self.client.get('/api/dog/-1/disliked/next/')
self.assertEqual(response.data['name'], self.dog_1.name)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_pk_bad(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user1_token.key
)
response = self.client.get('/api/dog/22/disliked/next/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_staus_bad(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user2_token.key
)
response = self.client.get('/api/dog/-1/undecided/next/')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_put_status(self):
self.client.credentials(
HTTP_AUTHORIZATION='Token ' + self.user1_token.key
)
response = self.client.put('/api/dog/1/liked/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
# self.assertEqual(self.dog_1.userdog__status, 'l')
# print(self.user_dog_1.status)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-06-06 04:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pugorugh', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userdog',
name='status',
field=models.CharField(help_text='status; Enter, (l) Liked, (d) Disliked, (u) Undecided', max_length=1),
),
]
<file_sep>from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from pugorugh.serializers import (DogSerializer, UserPrefSerializer)
class DogSerializerTests(APITestCase):
'''SETUP '''
def setUp(self):
''' setup up dummy data for the Dog serializer '''
self.dog_1_data = {
'name': 'dog_1',
'image_filename': '1.jpg',
'breed': 'mutt',
'age': 12,
'gender': 'm',
'size': 'm'
}
def test_get_correct_value(self):
serializer = DogSerializer(data=self.dog_1_data)
self.assertTrue(serializer.is_valid())
self.assertEqual(
serializer.data['name'],
self.dog_1_data['name']
)
class UserPrefSerializerTests(APITestCase):
'''SETUP '''
def setUp(self):
''' create user to be used in our dummy data '''
self.user_1 = User.objects.create(
username='test_user_1',
email='<EMAIL>',
password='<PASSWORD>'
)
''' set up dummy data for UserPerf Serializer '''
self.user_pref_1 = {
'user': self.user_1,
'age': 'b,y',
'gender': 'm,f',
'size': 'l, xl'
}
def test_validate_userpref_bad_age(self):
self.user_pref_1['age'] = 'z'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertFalse(serializer.is_valid())
self.assertEqual(set(serializer.errors.keys()), set(['age']))
def test_validate_userpref_good_age(self):
self.user_pref_1['age'] = 's'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertTrue(serializer.is_valid())
def test_validate_userpref_bad_gender(self):
self.user_pref_1['gender'] = 'z'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertFalse(serializer.is_valid())
self.assertEqual(set(serializer.errors.keys()), set(['gender']))
def test_validate_userpref_good_gender(self):
self.user_pref_1['gender'] = 'm'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertTrue(serializer.is_valid())
def test_validate_userpref_bad_size(self):
self.user_pref_1['size'] = 'z'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertFalse(serializer.is_valid())
self.assertEqual(set(serializer.errors.keys()), set(['size']))
def test_validate_userpref_good_size(self):
self.user_pref_1['gender'] = 'm'
serializer = UserPrefSerializer(data=self.user_pref_1)
self.assertTrue(serializer.is_valid())
<file_sep>
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from rest_framework import generics, status, views
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from . import models
from . import serializers
class UserRegisterView(generics.CreateAPIView):
permission_classes = (AllowAny,)
model = get_user_model()
serializer_class = serializers.UserSerializer
class ListCreateDogView(generics.ListCreateAPIView):
''' lists out all dogs in the Dog model and gives
the user, if authorised, the ability to create
a new Doggie
'''
queryset = models.Dog.objects.all()
serializer_class = serializers.DogSerializer
class RetrieveUpdateDestroyDogView(generics.RetrieveUpdateDestroyAPIView):
''' this class expects a primary key of the Dog in the URL.
Allows the ability to get, update and destroy a single
record in our Dog model
'''
queryset = models.Dog.objects.all()
serializer_class = serializers.DogSerializer
class RetrieveUpdateUserPrefView(generics.RetrieveUpdateAPIView):
''' Retrieve update the logged in user preferences.
'''
queryset = models.UserPref.objects.all()
serializer_class = serializers.UserPrefSerializer
def get_object(self):
''' override the queryset with the logged in users
prefs
'''
return self.get_queryset().get(user=self.request.user)
def put(self, *args, **kwargs):
''' override the put request - the reason being is that
on the first pass we can create all the undecdeid dogs
for the newly registered user to view
'''
# firstly lets get if the current userprefs exist.
try:
userprefs = self.get_queryset().get(user=self.request.user)
for key, value in self.request.data.items():
setattr(userprefs, key, value)
userprefs.save()
except models.UserPref.DoesNotExist:
new_values = self.request.data
userprefs = models.UserPref(**new_values)
userprefs.save()
# secondly take the opportunity to update all dogs that
# match the new userprefs with an undecided status
qs = self.build_queryset(self.request.user)
# get all the dogs that we are going to filter against
all_dogs = models.Dog.objects.filter(qs)
# give each of the dog in the queryset an value of undecided
for dog in all_dogs:
d = models.UserDog.objects.create(
user=self.request.user,
dog=dog, status='u'
)
d.save()
# retrun the updated user preferences
serializer = serializers.UserPrefSerializer(userprefs)
return Response(serializer.data)
def build_queryset(self, user):
''' dynamically create a queryset to use '''
query = Q()
age_filters = {}
age_range = {
'b': (0, 6), 'y': (6, 48), # arbitary ages of dogs
'a': (48, 84), 's': (84, 240)
}
reg_user_prefs = models.UserPref.objects.get(user=user)
# part 1 build the query based on size and gender
g_s_query = (
Q(gender__in=reg_user_prefs.gender) &
Q(size__in=reg_user_prefs.size)
)
# part 2 build the query based on age
ages = reg_user_prefs.age.split(',')
for a in ages:
a = a.strip() # this ugly should do a pre-save on model
if a in age_range.keys():
age_filters.update({a: age_range[a]})
# part 3 combine the 2 queries
for value in age_filters.values():
query |= Q(age__range=value)
query.add(g_s_query, Q.AND)
return query
class RetrieveUpdateLDUDogView(views.APIView):
''' Retrieve doggies liked, disliked or undecided based on
the logged in user preferences.
'''
def get(self, *args, **kwargs):
''' Filter and return a single Doogie base on the incoming url or
incoming argument of liked, disliked, undecided and the asscocitaed
pk - which is the record in the table -1 being the first, 1 being
the second
'''
like_dislike_undecided = self.kwargs.get('ldu_decision')[:1]
status_data = models.Dog.objects.filter(
(Q(userdog__user=self.request.user) &
Q(userdog__status=like_dislike_undecided))
)
if status_data:
if self.kwargs.get('pk') == '-1':
serializer = serializers.DogSerializer(status_data[0])
return Response(serializer.data)
else:
try:
user_dog = status_data.filter(id__gt=int(self.kwargs.get('pk')))[:1].get()
serializer = serializers.DogSerializer(user_dog)
return Response(serializer.data)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
return Response(status=status.HTTP_404_NOT_FOUND)
def put(self, *args, **kwargs):
''' PUT updated statuses for dogs
'''
like_dislike_undecided = self.kwargs.get('ldu_decision')[:1]
pk = int(self.kwargs.get('pk'))
try:
dog = models.Dog.objects.get(id=pk)
except ObjectDoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
associated_dog = models.UserDog.objects.get(
user=self.request.user, dog=dog)
associated_dog.status = like_dislike_undecided
associated_dog.save()
serializer = serializers.DogSerializer(dog)
return Response(serializer.data, status=status.HTTP_200_OK)
<file_sep>from django.contrib.auth import get_user_model
from rest_framework.authtoken.models import Token
from rest_framework import serializers
from . import models
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = get_user_model().objects.create(
username=validated_data['username'],
)
user.set_password(validated_data['password'])
user.save()
# create an initial set of preferences for the
self.create_inital_preferences(user)
# create a new token for the newly registered user
self.create_user_token(user)
return user
def create_inital_preferences(self, user):
''' creates an inital set of preferences
for the newly registered user
'''
inital_prefs = models.UserPref(
user=user,
age='b,y,a,s',
gender='m,f',
size='s,m,l,xl'
)
inital_prefs.save()
def create_user_token(self, user):
''' creates a new token for the newly registered user
'''
new_token = Token(user=user)
new_token.save()
class Meta:
fields = '__all__'
model = get_user_model()
class DogSerializer(serializers.ModelSerializer):
class Meta:
fields = (
'id',
'name',
'image_filename',
'breed',
'age',
'gender',
'size',
)
model = models.Dog
class UserPrefSerializer(serializers.ModelSerializer):
def get_validated_values(self, valid_entries, values, err_msg):
# pdb.set_trace()
values = values.replace(' ', '')
for entry in values.split(','):
if entry not in valid_entries:
raise serializers.ValidationError(err_msg)
return values
def validate_age(self, value):
valid_entries = ['b', 'y', 'a', 's']
err_msg = (
'Age must be (b) Baby, (y) Young, (a) Adult,'
' (s) Senior or a combaination seperated by a comma.'
)
return(self.get_validated_values(valid_entries, value, err_msg))
def validate_gender(self, value):
valid_entries = ['m', 'f']
err_msg = (
'Gender must be (m) Male, (f) Female,'
'or a combaination seperated by a comma.'
)
return(self.get_validated_values(valid_entries, value, err_msg))
def validate_size(self, value):
valid_entries = ['s', 'm', 'l', 'xl']
err_msg = (
'Size must be (s) Small, (m) Medium, (l) Large, '
'(xl) Extra Large or a combination seperated '
'by a comma.'
)
return(self.get_validated_values(valid_entries, value, err_msg))
class Meta:
fields = (
'age',
'gender',
'size',
)
model = models.UserPref
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-06-06 09:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pugorugh', '0002_auto_20180606_0428'),
]
operations = [
migrations.AlterField(
model_name='userpref',
name='age',
field=models.CharField(help_text='age; Enter, (b) Baby, (y) Young, (a) Adult, (s) Senior or a combaination seperated by a comma.', max_length=10),
),
migrations.AlterField(
model_name='userpref',
name='gender',
field=models.CharField(help_text='gender; Enter, (m) Male, (f) Female, (s) Senior or a combaination seperated by a comma.', max_length=10),
),
migrations.AlterField(
model_name='userpref',
name='size',
field=models.CharField(help_text='size; Enter, (s) Small, (m) Medium, (l) Large, (xl) Extra Large or a combination seperated by a comma.', max_length=10),
),
]
<file_sep>from django.contrib.auth.models import User
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=100)
image_filename = models.CharField(max_length=255, blank=True)
breed = models.CharField(max_length=100)
age = models.PositiveIntegerField()
gender = models.CharField(
max_length=1,
help_text='gender; Enetr, (m) Male, (f) Female, (u) Unknown'
)
size = models.CharField(
max_length=2,
help_text=(
'size; Enter, (s) Small, (m) Medium, (l) Large,'
'(xl) Extra Large'
))
def __str__(self):
return self.name
class UserDog(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
dog = models.ForeignKey(Dog, on_delete=models.CASCADE)
status = models.CharField(
max_length=1,
help_text='status; Enter, (l) Liked, (d) Disliked, (u) Undecided'
)
def __str__(self):
return self.user.username + ' ' + self.dog.name
class UserPref(models.Model):
''' this needs to fixed max_lenght is too much, need to strip blanks
use signals pre_save()
'''
user = models.OneToOneField(User,
related_name='preferences',
on_delete=models.CASCADE,
help_text=(
'Can only have one set of'
'prefrences per user'),
null=True
)
age = models.CharField(
max_length=10,
help_text=(
'age; Enter, (b) Baby, (y) Young, (a) Adult,'
' (s) Senior or a combaination seperated by a comma.')
)
gender = models.CharField(
max_length=10,
help_text=(
'gender; Enter, (m) Male, (f) Female,'
' (s) Senior or a combaination seperated by a comma.'
)
)
size = models.CharField(
max_length=10,
help_text=(
'size; Enter, (s) Small, (m) Medium, (l) Large,'
'(xl) Extra Large or a combination seperated by a comma.'
)
)
def __str__(self):
return (self.user.username + ' ages ({0.age}),'
' genders ({0.gender}), sizes ({0.size})'.format(self))
<file_sep># Generated by Django 2.0.6 on 2018-06-04 02:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Dog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('image_filename', models.CharField(blank=True, max_length=255)),
('breed', models.CharField(max_length=100)),
('age', models.PositiveIntegerField()),
('gender', models.CharField(help_text='gender; Enetr, (m) Male, (f) Female, (u) Unknown', max_length=1)),
('size', models.CharField(help_text='size; Enter, (s) Small, (m) Medium, (l) Large, (xl) Extra Large', max_length=2)),
],
),
migrations.CreateModel(
name='UserDog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.CharField(help_text='status; Enter, (l) Liked, (d) Disliked', max_length=1)),
('dog', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pugorugh.Dog')),
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='UserPref',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('age', models.CharField(help_text='age; Enter, (b) Baby, (y) Young, (a) Adult, (s) Senior or a combaination seperated by a comma.', max_length=5)),
('gender', models.CharField(help_text='gender; Enter, (m) Male, (f) Female, (s) Senior or a combaination seperated by a comma.', max_length=4)),
('size', models.CharField(help_text='size; Enter, (s) Small, (m) Medium, (l) Large, (xl) Extra Large or a combination seperated by a comma.', max_length=6)),
('user', models.OneToOneField(help_text='Can only have one set of prefrences per user', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='preferences', to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>from django.conf.urls import url
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from pugorugh.views import (UserRegisterView,
ListCreateDogView,
RetrieveUpdateDestroyDogView,
RetrieveUpdateUserPrefView,
RetrieveUpdateLDUDogView,
)
app_name = 'pugorugh'
# API endpoints
urlpatterns = format_suffix_patterns([
url(r'^api/user/login/$', obtain_auth_token, name='login-user'),
url(r'^api/user/$', UserRegisterView.as_view(), name='register-user'),
# url for the logged in users doggie prferences
url(r'^api/user/preferences/$',
RetrieveUpdateUserPrefView.as_view(),
name='userprefs'),
# list out all doggies created
url(r'^api/alldogs/', ListCreateDogView.as_view(), name='dog-listcreate'),
url(r'^api/alldogs/(?P<pk>\d+)$',
RetrieveUpdateDestroyDogView.as_view(),
name='dog-rud'),
# urls for likes, dislikes, undecided
url(r'^api/dog/(?P<pk>-?\d+)/(?P<ldu_decision>\w+)/(next/)?$',
RetrieveUpdateLDUDogView.as_view(),
name='dog-ldu'),
url(r'^favicon\.ico$',
RedirectView.as_view(
url='/static/icons/favicon.ico',
permanent=True
)),
url(r'^$', TemplateView.as_view(template_name='index.html')),
])
| e267c91f23055397201c3d9c23d7583b269d51b8 | [
"Python",
"Text"
] | 11 | Text | mcintoshsg/pug_or_ugh_v1 | 3e735cd840ffc5a85497eab48518800f0757d9f3 | 8678213b4b4ea09a70f369aa08002ff4a8194a29 |
refs/heads/master | <file_sep>package example02;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class LogDataClass {
public List<LogData> getDataListForFile1(String filePath) {
//찾을 문자열 입력
String textArray[] = {"eclipse.galileo-bean-thread-", "##galileo_bean start.", "ESB_TRAN_ID : ", "Content-Length:", "#galileo call time:", "StopWatch", "##galileo_bean end."};
//data를 collecting하기 위한 map
Map<String, LogData> logDataMap = new LinkedHashMap<String, LogData>();
//collecting이 완료된 data를 넣기 위한 list(return)
List<LogData> logDataList = new ArrayList<LogData>();
//파일열기
File file = new File(filePath);
BufferedReader bufferedReader = null;
//로그파일을 한줄씩 읽을 String
String currentLineText = new String();
try {
bufferedReader = new BufferedReader(new FileReader(file));
//한줄씩 읽기
while((currentLineText = bufferedReader.readLine())!=null) {
//thread명이 존재하지 않으면 continue; (while문 제일 마지막으로);
if(!currentLineText.contains(textArray[0])) {
continue;
}
//(thread명이 존재할 경우만 진행됨) thread명을 threadName에 저장
String threadName = findThreadNumber(currentLineText, textArray[0]);
//line에 "##galileo_bean start."가 존재하는 경우 : 신규 LogData객체 생성 (thread명 setting) 후, Map에 put (key=thread명, value=LogData)
if(currentLineText.contains(textArray[1])) {
LogData newLogData = new LogData(currentLineText.substring(1, 18));
logDataMap.put(threadName, newLogData);
continue;
}
//해당thread명을 key로하는 logData가 Map에 존재하지 않으면 continue; (while문 제일 마지막으로);
if(logDataMap.get(threadName)==null) {
continue;
}
//line에 "ESB_TRAN_ID : " 또는 "Content-Length:" 또는 "#galileo call time:"가 존재하는 경우
//(Map에서 해당 thread를 key값으로 하는 value(LogData)를 찾아 해당값 setting)
if(currentLineText.contains(textArray[2])||currentLineText.contains(textArray[3])||currentLineText.contains(textArray[4])) {
checkCurrentLineText(textArray, currentLineText, logDataMap.get(threadName));
continue;
//line에 "StopWatch"가 존재하는 경우 (그다음 7줄을 더 읽어와서 각 데이터를 추출)
} else if(currentLineText.contains(textArray[5])){
String currentLineStr = new String();
for(int temp2=0; temp2<7; temp2++) {
currentLineStr = bufferedReader.readLine();
checkCurrentLineStr(currentLineStr, logDataMap.get(threadName));
}//for문 끝
continue;
//line에 "##galileo_bean end."가 존재하는 경우 (Map에서 해당 thread를 key값으로 하는 value(LogData)를 찾아 해당값 setting)
} else if(currentLineText.contains(textArray[6])){
logDataMap.get(threadName).setEndTime(currentLineText.substring(1, 18));
//logDataList에 추가하고 logDataMap에서 제거함
logDataList.add(logDataMap.get(threadName));
logDataMap.remove(threadName);
continue;
}
}//한줄씩 읽기 while문 끝
} catch (Exception e) {
e.printStackTrace();
}
finally {
//bufferedReader 닫기
if(bufferedReader!=null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return logDataList;
}
/**
* currentLineText에 원하는 찾는 문자열이 존재하는 경우
* Map에서 해당 threadName을 key값으로 하는 value(LogData)를 찾아 해당값을 setting
* @param textArray
* @param currentLineText
* @param logData
*/
private void checkCurrentLineText(String[] textArray, String currentLineText, LogData logData) {
//line에 "ESB_TRAN_ID : "가 존재하는 경우 (Map에서 해당 thread를 key값으로 하는 value(LogData)를 찾아 해당값 setting)
if(currentLineText.contains(textArray[2])) {
logData.setEsbTranId(findData(currentLineText, textArray[2]));
//line에 "Content-Length:"가 존재하는 경우 (Map에서 해당 thread를 key값으로 하는 value(LogData)를 찾아 해당값 setting)
} else if(currentLineText.contains(textArray[3])) {
logData.setContentLength(findData(currentLineText, textArray[3]));
//line에 "#galileo call time:"가 존재하는 경우 (Map에서 해당 thread를 key값으로 하는 value(LogData)를 찾아 해당값 setting)
} else if(currentLineText.contains(textArray[4])) {
String arr[] = findData(currentLineText, textArray[4]).split("ms");
logData.setGalileoCallTime(arr[0].trim());
}
}
/**
* currentLineStr에 원하는 찾는 문자열이 존재하는 경우
* Map에서 해당 threadName을 key값으로 하는 value(LogData)를 찾아 해당값을 setting
* @param currentLineStr
* @param logData
*/
private void checkCurrentLineStr(String currentLineStr, LogData logData) {
//찾을 문자열 입력
String[] textStr = {"1. Before Marshalling", "2. Marshalling", "3. Invoking galileo", "4. Unmarshalling and Send to CmmMod Server"};
for(int temp=0; temp<textStr.length; temp++) {
if(currentLineStr.contains(textStr[0])) {
logData.setBeforeMarshalling(currentLineStr.substring(0, 5));
} else if(currentLineStr.contains(textStr[1])) {
logData.setMarshalling(currentLineStr.substring(0, 5));
} else if(currentLineStr.contains(textStr[2])) {
logData.setInvokingGalileo(currentLineStr.substring(0, 5));
} else if(currentLineStr.contains(textStr[3])) {
logData.setUnmarshallingAndSendToCmmModServer(currentLineStr.substring(0, 5));
}
}
}
/**
* threadNumber 가져오기
* @param currentText
* @param splitText
* @return threadNumber
*/
private String findThreadNumber(String currentText, String splitText) {
String array[] = currentText.split(splitText);
return array[1].substring(0, 8);
}
/**
* 특정 text 찾아오기
* (CurrentText를 keyword를 기준으로 잘라 그 뒤쪽의 문자열을 가져옴)
* @param CurrentText
* @param keyword
* @return data
*/
private String findData(String CurrentText, String keyword) {
String data = null;
String split[] = CurrentText.split(keyword);
if(split.length!=1) {
data = split[1];
}
return data;
}
/**
* logDataList를 이용하여 file1 작성하기
* @param logDataList
*/
public void makeFile1(String filePath, List<LogData> logDataList) {
//logDataList의 logData중 null값이 있는지 체크하기
checkEntireList(logDataList);
//logDataList를 startTime순서로 정렬하기
Collections.sort(logDataList);
File file = new File(filePath);
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
for(int temp=0; temp<logDataList.size(); temp++) {
//canBeUsed값이 true인것만 작성
if(logDataList.get(temp).getCanBeUsed()==true) {
bufferedWriter.write(logDataList.get(temp).getStartTime());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getEndTime());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getEsbTranId());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getContentLength());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getGalileoCallTime());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getBeforeMarshalling());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getMarshalling());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getInvokingGalileo());
bufferedWriter.write(", ");
bufferedWriter.write(logDataList.get(temp).getUnmarshallingAndSendToCmmModServer());
bufferedWriter.write("\n");
}
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(bufferedWriter!=null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* logDataList에서 LogData의 변수에 null값이 있을 경우
* canBeUsed값을 false로 setting
* @param logDataList
*/
private void checkEntireList(List<LogData> logDataList) {
//모든 logDataList를 체크
for(int temp=0; temp<logDataList.size(); temp++) {
Object obj= logDataList.get(temp);
int cnt = 0;
//각 logDataList의 모든 field를 체크
for(Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
if(field.get(obj)==null) {
break;
}
//value가 null이 아니면 cnt++
cnt++;
} catch (Exception e) {
e.printStackTrace();
}
}//개선된 for문 끝
//모든 field값이 null이 아니면 setCanBeUsed값을 true로 변경
if(cnt==obj.getClass().getDeclaredFields().length) {
logDataList.get(temp).setCanBeUsed(true);
}
}//for문 끝
}
/**
* File2를 작성하기 위한 Map생성
* @param logDataList
* @return
*/
public Map<String, LogDataByMinute> getDataMapForFile2(List<LogData> logDataList){
//canBeUsed가 false인 것은 List에서 제거
for(int temp = 0; temp<logDataList.size(); temp++) {
if(logDataList.get(temp).getCanBeUsed()==false) {
logDataList.remove(temp);
}
}
//return을 위한 logDataByMinuteMap
Map<String, LogDataByMinute> logDataByMinuteMap = new LinkedHashMap<String, LogDataByMinute>();
//logDataList에서 나온 logData객체의 현재값과 기존에 Map에 들어있던 객체의 값을 비교하기 위한 변수
int minutes = 0;
String time = null;
int totalCount = 0;
long totalDuration = 0;
int totalSize = 0;
//logDataList에 각각의 logData객체를 비교 (해당List는 시작시간 순으로 정렬되어있음)
for(LogData logData: logDataList) {
try {
DateFormat dateFormat = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
Date startDate = dateFormat.parse(logData.getStartTime());
Date endDate = dateFormat.parse(logData.getEndTime());
//시작의 '분'이 기존과 다르다면 : LogDataByMinute객체 생성 및 값 setting (아직 값이 한개라 최대/최소 등의 값은 모두 최초 처음값과 동일) -- Map에 저장
if(minutes!=startDate.getMinutes()) {
minutes = startDate.getMinutes();
time = logData.getStartTime().substring(0, 14);
totalCount = 1;
totalDuration = (endDate.getTime() - startDate.getTime());
totalSize = Integer.parseInt(logData.getContentLength());
logDataByMinuteMap.put(time, new LogDataByMinute(time, totalCount, totalDuration/totalCount, totalDuration, totalDuration, totalSize/totalCount, totalSize, totalSize));
//시작의 '분'이 기존과 같다면 : 기존의 LogDataByMinute객체에 값 setting (total값은 기존값과 더하고, min, max는 기존값과 현재값을 다시 비교해서 setting)
} else {
totalCount++;
totalDuration = totalDuration + (endDate.getTime() - startDate.getTime());
totalSize = totalSize + Integer.parseInt(logData.getContentLength());
logDataByMinuteMap.get(time).setTotalCount(totalCount);
logDataByMinuteMap.get(time).setAvgDuration(totalDuration/totalCount);
logDataByMinuteMap.get(time).setMinDuration(Math.min((endDate.getTime() - startDate.getTime()), logDataByMinuteMap.get(time).getMinDuration()));
logDataByMinuteMap.get(time).setMaxDuration(Math.max((endDate.getTime() - startDate.getTime()), logDataByMinuteMap.get(time).getMaxDuration()));
logDataByMinuteMap.get(time).setAvgSize(totalSize/totalCount);
logDataByMinuteMap.get(time).setMinSize(Math.min(Integer.parseInt(logData.getContentLength()), logDataByMinuteMap.get(time).getMinSize()));
logDataByMinuteMap.get(time).setMaxSize(Math.max(Integer.parseInt(logData.getContentLength()), logDataByMinuteMap.get(time).getMaxSize()));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return logDataByMinuteMap;
}
/**
* logDataByMinuteMap를 이용하여 file2 작성하기
* @param filePath
* @param logDataByMinuteMap
*/
public void makeFile2(String filePath, Map<String, LogDataByMinute> logDataByMinuteMap) {
File file = new File(filePath);
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
Set<String> keySet = logDataByMinuteMap.keySet();
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()){
String key = iterator.next();
bufferedWriter.write(logDataByMinuteMap.get(key).getTime());
bufferedWriter.write(", ");
bufferedWriter.write(Integer.toString(logDataByMinuteMap.get(key).getTotalCount()));
bufferedWriter.write(", ");
bufferedWriter.write(Long.toString(logDataByMinuteMap.get(key).getAvgDuration()));
bufferedWriter.write(", ");
bufferedWriter.write(Long.toString(logDataByMinuteMap.get(key).getMinDuration()));
bufferedWriter.write(", ");
bufferedWriter.write(Long.toString(logDataByMinuteMap.get(key).getMaxDuration()));
bufferedWriter.write(", ");
bufferedWriter.write(Integer.toString(logDataByMinuteMap.get(key).getAvgSize()));
bufferedWriter.write(", ");
bufferedWriter.write(Integer.toString(logDataByMinuteMap.get(key).getMinSize()));
bufferedWriter.write(", ");
bufferedWriter.write(Integer.toString(logDataByMinuteMap.get(key).getMaxSize()));
bufferedWriter.write("\n");
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(bufferedWriter!=null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
<file_sep>package example02;
public class LogData implements Comparable<LogData> {
private String startTime;
private String endTime;
private String esbTranId;
private String contentLength;
private String galileoCallTime;
private String beforeMarshalling;
private String marshalling;
private String invokingGalileo;
private String unmarshallingAndSendToCmmModServer;
private Boolean canBeUsed = false;
public LogData() { }
public LogData(String startTime) {
this.startTime = startTime;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getEsbTranId() {
return esbTranId;
}
public void setEsbTranId(String esbTranId) {
this.esbTranId = esbTranId;
}
public String getContentLength() {
return contentLength;
}
public void setContentLength(String contentLength) {
this.contentLength = contentLength;
}
public String getGalileoCallTime() {
return galileoCallTime;
}
public void setGalileoCallTime(String galileoCallTime) {
this.galileoCallTime = galileoCallTime;
}
public String getBeforeMarshalling() {
return beforeMarshalling;
}
public void setBeforeMarshalling(String beforeMarshalling) {
this.beforeMarshalling = beforeMarshalling;
}
public String getMarshalling() {
return marshalling;
}
public void setMarshalling(String marshalling) {
this.marshalling = marshalling;
}
public String getInvokingGalileo() {
return invokingGalileo;
}
public void setInvokingGalileo(String invokingGalileo) {
this.invokingGalileo = invokingGalileo;
}
public String getUnmarshallingAndSendToCmmModServer() {
return unmarshallingAndSendToCmmModServer;
}
public void setUnmarshallingAndSendToCmmModServer(String unmarshallingAndSendToCmmModServer) {
this.unmarshallingAndSendToCmmModServer = unmarshallingAndSendToCmmModServer;
}
public Boolean getCanBeUsed() {
return canBeUsed;
}
public void setCanBeUsed(Boolean canBeUsed) {
this.canBeUsed = canBeUsed;
}
@Override
public int compareTo(LogData logData) {
return startTime.compareTo(logData.getStartTime());
}
}
<file_sep>package example02;
public class LogDataByMinute {
private String time;
private int totalCount;
private long avgDuration;
private long minDuration;
private long maxDuration;
private int avgSize;
private int minSize;
private int maxSize;
public LogDataByMinute() { }
public LogDataByMinute(String time, int totalCount, long avgDuration, long minDuration, long maxDuration,
int avgSize, int minSize, int maxSize) {
this.time = time;
this.totalCount = totalCount;
this.avgDuration = avgDuration;
this.minDuration = minDuration;
this.maxDuration = maxDuration;
this.avgSize = avgSize;
this.minSize = minSize;
this.maxSize = maxSize;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public long getAvgDuration() {
return avgDuration;
}
public void setAvgDuration(long avgDuration) {
this.avgDuration = avgDuration;
}
public long getMinDuration() {
return minDuration;
}
public void setMinDuration(long minDuration) {
this.minDuration = minDuration;
}
public long getMaxDuration() {
return maxDuration;
}
public void setMaxDuration(long maxDuration) {
this.maxDuration = maxDuration;
}
public int getAvgSize() {
return avgSize;
}
public void setAvgSize(int avgSize) {
this.avgSize = avgSize;
}
public int getMinSize() {
return minSize;
}
public void setMinSize(int minSize) {
this.minSize = minSize;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
}
<file_sep>package example01;
public class MainApp {
public static void main(String[] args) {
//시작시간
long startTime = System.currentTimeMillis();
XMLDataClass xmlDataClass = new XMLDataClass();
//파일을 가져와서 tFile만들기
String filePath = "C:\\Users\\meta\\Desktop\\1.XML 파일 분석";
xmlDataClass.createTFile(filePath);
//종료시간
long endTime = System.currentTimeMillis();
//걸린시간
System.out.println("소요시간: " + (endTime-startTime) + "ms");
//메모리 사용량 조회
System.out.println("Used Memory : " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1024 + "Kbyte");
}
}
| 7bc92dce6f20ec975f516839ff9c8549ac51bfd6 | [
"Java"
] | 4 | Java | jihyunpark88/metabuild | eab42be58e32261ce6b553202dfc9d386b35dc1b | 34d3568a8791c1b6d262dd6419260fb86d7b49c9 |
refs/heads/master | <file_sep>import React, { Component } from 'react'
import { withHistory, Link } from 'react-router-dom'
import { createContainer } from 'meteor/react-meteor-data'
import Button from '@material-ui/core/Button';
import Lock from '@material-ui/icons/Lock'
import Email from '@material-ui/icons/Email'
export default class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
error: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let email = document.getElementById('login-email').value;
let password = document.getElementById('login-password').value;
Meteor.loginWithPassword(email, password, (err) => {
if (err) {
this.setState({
error: err.reason
});
} else {
this.props.history.push('/');
}
});
}
render() {
const error = this.state.error;
return (
<div className="body-wrapper">
<section id="login-section">
<div className="login-container">
<div className="login-show text-white text-center login">
<div className="overlay"></div>
<div className="show-body">
<h1>Declaration of Loss Online</h1>
<p className="lead">Thank you for using your login credentials.
If you are not yet a member, please
</p>
<button className="btn btn-outline-light btn-reg login">
<Link to="/signup">Register Here</Link>
</button>
</div>
</div>
<div className="login-form">
<div className="login-header">
<div className="logo">
<img src="images/logo.svg" alt="" />
</div>
<div className="lan-select">
en
</div>
</div>
<div className="login-body login">
{error.length > 0 ?
<div className="alert alert-danger fade in">{error}</div>
: ''}
<form id="login-form" onSubmit={this.handleSubmit}>
<div className="form-group with-icon mb-4">
<input id="login-email" type="text" name="email" className="form-control" />
<label >Email</label>
<Email />
</div>
<div className="form-group with-icon mb-4">
<input id="login-password" type="<PASSWORD>" name="password" className="form-control" />
<label >Password</label>
<Lock />
</div>
<div className="bottom">
<a href="/" className="dslink">Forget Password?</a>
<Button variant="contained" color="primary">
Login
</Button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
);
}
}<file_sep>import React, { Component } from 'react';
import { withHistory, Link } from 'react-router-dom';
import { Accounts } from 'meteor/accounts-base';
import Button from '@material-ui/core/Button';
export default class SignupPage extends Component {
constructor(props) {
super(props);
this.state = {
error: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let name = document.getElementById("signup-name").value;
let email = document.getElementById("signup-email").value;
let password = document.getElementById("signup-password").value;
this.setState({ error: "test" });
Accounts.createUser({ email: email, username: name, password: <PASSWORD> }, (err) => {
if (err) {
this.setState({
error: err.reason
});
} else {
this.props.history.push('/login');
}
});
}
render() {
const error = this.state.error;
return (
<div className="body-wrapper">
<section id="login-section">
<div className="login-container">
<div className="login-show text-white text-center register">
<div className="overlay"></div>
<div className="show-body">
<h1>Declaration of Loss Online</h1>
<p className="lead">
Please use this form to register.If you are a member, please
</p>
<button className="btn btn-outline-light btn-reg register">
<Link to="/login">Login Here</Link>
</button>
</div>
</div>
<div className="login-form">
<div className="login-header">
<div className="logo">
<img src="images/logo.svg" alt="" />
</div>
<div className="lan-select">
en
</div>
</div>
<div className="login-body register">
{error.length > 0 ?
<div className="alert alert-danger fade in">{error}</div>
: ''}
<form onSubmit={this.handleSubmit}>
<div className="form-group with-icon mb-4">
<input id="signup-name" type="text" name="name" className="form-control" />
<label for="">Full Name</label>
<i className="material-icons">
person
</i>
</div>
<div className="form-group with-icon mb-4">
<input id="signup-email" type="text" name="email" className="form-control" />
<label for="">Email</label>
<i className="material-icons">
email
</i>
</div>
<div className="form-group with-icon mb-4">
<input type="<PASSWORD>" id="signup-password" name="password" className="form-control" />
<label for="">Password</label>
<i className="material-icons">
lock
</i>
</div>
<div className="text-right">
<Button variant="contained" color="primary" size='large' type='submit'>
Register
</Button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
);
}
}<file_sep>import React from 'react';
import { Meteor } from 'meteor/meteor';
import ReactDOM from 'react-dom';
import './main.html';
import '../imports/startup/load-fonts.js'
// add render routes function
import { renderRoutes } from '../imports/startup/routes.jsx'
// render routes after DOM has loaded
Meteor.startup(() => {
ReactDOM.render(renderRoutes(), document.querySelector("#target"));
});
| 31d3b9a058cb53fd77da62d69df8ebe214cec1db | [
"JavaScript"
] | 3 | JavaScript | vjhameed/stevedec | 0b9e3442a4af113f2f5a19fc9af1c805ed8aa41b | 02fc294ca5ab42b0159927d8b5b0c11b2f97e20e |
refs/heads/master | <repo_name>sharm173/HTTP-SERVER<file_sep>/http-server.cc
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <signal.h>
const char * usage =
" \n"
"Simple iterative HTTP server \n"
" \n"
"To use it in one window type: \n"
" \n"
" myhttpd [-f|-t|-p] [<port>] \n"
" \n"
"Where 1024 < port < 65536 \n"
" \n"
"-f :Create a new process for each request \n"
" \n"
"-t : Create a new thread for each request \n"
" \n"
"-p: Pool of threads \n";
int QueueLength = 5;
pthread_mutex_t mutex;
// Processes time request
void dispatchHTTP( int socket );
void iterativeServer (int masterSocket);
void forkServer (int masterSocket);
void createThreadForEachRequest (int masterSocket);
void poolOfThreads (int masterSocket);
void *loopthread (int masterSocket);
extern "C" void zomboy( int sig )
{
int pid = wait3(0, 0, NULL);
while(waitpid(-1, NULL, WNOHANG) > 0);
}
bool is_dir(const char* path) {
struct stat buf;
stat(path, &buf);
return S_ISDIR(buf.st_mode);
}
int
main(int argc, char **argv)
{
int port = 0;
if(argc == 2) port = atoi( argv[1] );
else if(argc == 3) port = atoi(argv[2]);
else {
fprintf( stderr, "%s", usage );
exit( -1 );
}
struct sigaction zombie;
zombie.sa_handler = zomboy;
sigemptyset(&zombie.sa_mask);
zombie.sa_flags = SA_RESTART;
int error2 = sigaction(SIGCHLD, &zombie, NULL );
if ( error2 ) {
perror( "sigaction" );
exit( -1 );
}
// Set the IP address and port for this server
struct sockaddr_in serverIPAddress;
memset( &serverIPAddress, 0, sizeof(serverIPAddress) );
serverIPAddress.sin_family = AF_INET;
serverIPAddress.sin_addr.s_addr = INADDR_ANY;
serverIPAddress.sin_port = htons((u_short) port);
// Allocate a socket
int masterSocket = socket(PF_INET, SOCK_STREAM, 0);
if ( masterSocket < 0) {
perror("socket");
exit( -1 );
}
// Set socket options to reuse port. Otherwise we will
// have to wait about 2 minutes before reusing the sae port number
int optval = 1;
int err = setsockopt(masterSocket, SOL_SOCKET, SO_REUSEADDR,
(char *) &optval, sizeof( int ) );
// Bind the socket to the IP address and port
int error = bind( masterSocket,
(struct sockaddr *)&serverIPAddress,
sizeof(serverIPAddress) );
if ( error ) {
perror("bind");
exit( -1 );
}
// Put socket in listening mode and set the
// size of the queue of unprocessed connections
error = listen( masterSocket, QueueLength);
if ( error ) {
perror("listen");
exit( -1 );
}
if(argc == 3 ) {
if(argv[1][1] == 'f') forkServer(masterSocket);
else if (argv[1][1] == 't') createThreadForEachRequest(masterSocket);
else if (argv[1][1] == 'p') poolOfThreads(masterSocket);
else {
}
}
else {
//run iterative server
iterativeServer(masterSocket);
}
}
void iterativeServer( int masterSocket) {
while (1) {
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
printf("before slaveSocket\n");
int slaveSocket =accept(masterSocket,(struct sockaddr*)&clientIPAddress, (socklen_t*)&alen);
printf("after slaveSocket\n");
if(slaveSocket < 0) {
printf("%s",strerror(errno));
}
if (slaveSocket >= 0) {
dispatchHTTP(slaveSocket);
}
//close(slaveSocket);
//shutdown(slaveSocket,0);
//dispatch http closes slave socket
}
}
void forkServer( int masterSocket) {
while (1) {
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
int slaveSocket =accept(masterSocket,(struct sockaddr*)&clientIPAddress, (socklen_t*)&alen);
if (slaveSocket >= 0) {
int ret = fork();
if (ret == 0) {
dispatchHTTP(slaveSocket);
exit(0);
}
close(slaveSocket);
}
}
}
void createThreadForEachRequest(int masterSocket)
{
while (1) {
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
int slaveSocket =accept(masterSocket,(struct sockaddr*)&clientIPAddress, (socklen_t*)&alen);
if (slaveSocket >= 0) {
// When the thread ends resources are recycled
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_create(&thread, &attr, (void * (*)(void *))dispatchHTTP, (void *) slaveSocket);
}
}
}
void poolOfThreads( int masterSocket ) {
pthread_mutex_init(&mutex, NULL);
pthread_t thread[5];
for (int i=0; i<4; i++) {
pthread_create(&thread[i], NULL, (void * (*)(void *))loopthread,(void *)masterSocket);
}
loopthread (masterSocket);
}
void *loopthread (int masterSocket) {
while (1) {
struct sockaddr_in clientIPAddress;
int alen = sizeof( clientIPAddress );
pthread_mutex_lock(&mutex);
int slaveSocket =accept(masterSocket,(struct sockaddr*)&clientIPAddress, (socklen_t*)&alen);
pthread_mutex_unlock(&mutex);
if (slaveSocket >= 0) {
dispatchHTTP(slaveSocket);
}
}
}
void dispatchHTTP( int socket ) {
char curr_string[1025];
int n;
unsigned char newChar;
unsigned char oldChar = 0;
int gotGET = 0;
int length = 0;
char docPath[1025] = {0};
printf("1\n");
while(n = read(socket, &newChar, sizeof(newChar))){
//length++;
if(newChar == ' '){
if(gotGET==0)
gotGET = 1;
else {
curr_string[length]=0;
strcpy(docPath, curr_string);
}
}
else if(newChar == '\n' && oldChar == '\r'){
read(socket, &oldChar, sizeof(oldChar));
read(socket, &newChar, sizeof(newChar));
if(oldChar == '\r' && newChar == '\n') break;
while(1){
while(read(socket, &oldChar, sizeof(oldChar))) {
if(oldChar == '\r') {
read(socket, &newChar, sizeof(newChar));
break;
}
}
read(socket, &oldChar, sizeof(oldChar));
read(socket, &newChar, sizeof(newChar));
if(oldChar == '\r' && newChar == '\n') break;
}
break;
}
else{
oldChar = newChar;
if(gotGET==1){
curr_string[length] = newChar;
length++;
}
}
}
printf("2\n");
char cwd[256] = {0};
getcwd(cwd,sizeof(cwd));
printf("current: %s\n",cwd);
if (strncmp(docPath, "/icons", strlen("/icons")) == 0) {
strcat(cwd, "/http-root-dir/");
strcat(cwd, docPath);
}
else if (strncmp(docPath, "/htdocs", strlen("/htdocs")) == 0) {
strcat(cwd, "/http-root-dir/");
strcat(cwd, docPath);
}
else if (strncmp(docPath, "/cgi-bin", strlen("/cgi-bin")) == 0) {
strcat(cwd, "/http-root-dir/");
strcat(cwd, docPath);
}
else {
if(strcmp(docPath,"/") == 0) {
strcpy(docPath, "/index.html");
strcat(cwd, "/http-root-dir/htdocs/index.html");
}
else {
strcat(cwd, "/http-root-dir/htdocs");
strcat(cwd, docPath);
}
}
if(strstr(docPath,"..") != 0) { //possible bug
char expand[1025] = {0};
char *real = realpath(docPath, expand);
if(real != NULL && strlen(expand) >= strlen(cwd) + strlen("/http-root-dir/htdocs")) {
strcpy(cwd,expand);
}
}
printf("3\n");
char contentType[256] = {0};
if(strstr(docPath, ".html") != NULL || strstr(docPath,".html/") != NULL) {
strcpy(contentType,"text/html");
}
else if(strstr(docPath, ".gif") != NULL || strstr(docPath,".gif/") != NULL) {
strcpy(contentType, "image/gif");
}
else if (strstr(docPath, ".jpg") != NULL || strstr(docPath,".jpg/") != NULL){
strcpy(contentType, "image/jpeg");
}
else if (strstr(docPath, ".xbm") != NULL || strstr(docPath,".xbm/") != NULL){
strcpy(contentType, "image/xbm");
}
else {
strcpy(contentType, "text/plain");
}
printf("4\n");
if(strstr(cwd,"cgi-bin")!= NULL) {
write(socket, "HTTP/1.1 200 Document follows\r\n", 31);
write(1, "HTTP/1.1 200 Document follows\r\n", 31);
write(socket, "Server: CS252 Lab4\r\n", 20);
write(1, "Server: CS252 Lab4\r\n", 20);
// write(socket, "Content-type: ",14);
// write(1, "Content-type: ",14);
// write(socket,contentType, strlen(contentType));
// write(1,contentType, strlen(contentType));
// write(socket, "\r\n",2);
// write(1, "\r\n\r\n",4);
//int tmpout = dup(1);
//int tmpsoc = dup(socket);
//dup2(socket,1);
int ret = fork();
if(ret == 0) {
int tmpout = dup(1);
int tmpsoc = dup(socket);
dup2(socket,1);
//child process
if(strchr(cwd,'?') == NULL) {
char *arr[2];
arr[0] = cwd;
arr[1] = NULL;
execvp(arr[0], arr);
}
else {
char *a = strchr(cwd,'?');
*a='\0';
a++;
write(tmpout,a,strlen(a));
int set =setenv("QUERY_STRING", a, 1);
if(set != 0) perror("setenv");
int set2 = setenv("REQUEST_METHOD","GET", 1);
if(set2 != 0) perror("setenv");
char *arr[3];
arr[0] = cwd;
arr[1] = a;
arr[2] = NULL;
execvp(arr[0], arr);
}
//execvp(arr[0], arr);
dup2(tmpout,1);
close(tmpout);
dup2(tmpsoc,socket);
close(tmpsoc);
_exit(1);
}
//dup2(tmpout,1);
//close(tmpout);
//dup2(tmpsoc,socket);
//close(tmpsoc);
}
else {
if(is_dir(cwd)){
printf("%s\n",cwd);
strcat(cwd,"-html.html");
strcpy(contentType,"text/html");
}
FILE *doc;
//printf("%s",cwd);
if (strstr(contentType, "image") != 0)// || strstr(contentType, "image/jpeg") != 0 ||strstr(contentType, "image/xbm") != 0 )
doc = fopen(cwd, "rb");
else
doc = fopen(cwd, "r");
printf("5\n");
if(doc > 0) {
write(socket, "HTTP/1.1 200 Document follows\r\n", 31);
write(1, "HTTP/1.1 200 Document follows\r\n", 31);
write(socket, "Server: CS252 Lab4\r\n", 20);
write(1, "Server: CS252 Lab4\r\n", 20);
write(socket, "Content-type: ",14);
write(1, "Content-type: ",14);
write(socket,contentType, strlen(contentType));
write(1,contentType, strlen(contentType));
write(socket, "\r\n\r\n",4);
write(1, "\r\n\r\n",4);
long count = 0;
char c;
int fd = fileno(doc);
while((count = (read(fd,&c,1)))){
//write(socket,&c,1);
//write(1,&c,1);
if((write(socket,&c,1)) != count){
perror("write");
}
}
printf("Write\n");
fclose(doc);
printf("close\n");
close(fd);
}
else {
//404 error
const char *notFound = "File not Found";
write(socket, "HTTP/1.1 404 File Not Found\r\n", 29);
write(socket, "Server: CS252 Lab4\r\n", 20);
write(socket, "Content-type: ",14);
write(socket,contentType, strlen(contentType));
write(socket, "\r\n\r\n",4);
write(socket,notFound, strlen(notFound));
}
}
//return;
close(socket);
//shutdown(socket,0);
}
| 6335b09afa110c1189c86379f444b50c6c29d77b | [
"C++"
] | 1 | C++ | sharm173/HTTP-SERVER | 0a5dc5b9182cdd011d767a8df543ae6c25156377 | 49747fc6024bded976dab70a429b8e870df6c304 |
refs/heads/main | <repo_name>jlsuh/badreads<file_sep>/README.md
# Badreads
## Remarks
This project uses `Web Storage API`. For an in-dept explanation of the API please consider visiting [the official documentation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API).<file_sep>/js/main.js
function createBook(title, author, pages, imageLink, alreadyRead) {
return {
title,
author,
pages,
imageLink,
alreadyRead,
toggleRead() {
this.alreadyRead = !this.alreadyRead;
},
info() {
const readValue = this.alreadyRead ? "already read" : "not read yet";
return `${this.title} by ${this.author}, ${this.pages} pages, ${readValue}`;
}
};
}
function createCard(book) {
let imageLink;
let alt;
[imageLink, alt] =
(book.imageLink !== "" && isValidHttpUrl(book.imageLink)) ?
[book.imageLink, `${book.title} book photo`] : ["/img/no-photo.jpg", "No photo provided photo"];
function isValidHttpUrl(str) {
let url;
try {
url = new URL(str);
} catch (_) {
return false;
}
return url.protocol === "http:" || url.protocol === "https:";
}
return {
book,
imageLink,
alt
};
}
let cardCreator = (function(document) {
function createButton(className, textContent, callback) {
const removeButton = document.createElement("button");
removeButton.classList.add(className);
removeButton.textContent = textContent;
removeButton.addEventListener("click", callback);
return removeButton;
}
function setImage(card) {
const img = document.createElement("img");
img.src = card.imageLink;
img.alt = card.alt;
return img;
}
function setBookPhoto(card, div) {
const bookPhoto = document.createElement("div");
const img = setImage(card);
bookPhoto.classList = "book-photo";
bookPhoto.appendChild(img);
div.appendChild(bookPhoto);
return div;
}
function setBookInfo(div, book, bookRemover, readToggler) {
const bookInfo = document.createElement("div");
const info = document.createElement("div");
const buttonContainer = document.createElement("div");
const removeButton = createButton("remove-button", "Remove", bookRemover);
const readToggleButton = createButton("read-toggle", "Toggle Read", readToggler);
bookInfo.classList.add("book-info");
info.classList.add("about-book");
buttonContainer.classList.add("buttons-container");
info.textContent = book.info();
buttonContainer.appendChild(removeButton);
buttonContainer.appendChild(readToggleButton);
bookInfo.appendChild(buttonContainer);
bookInfo.appendChild(info);
div.appendChild(bookInfo);
return div;
}
return {
createDivCard(card, bookRemover, readToggler) {
const alternateBackground = (index) => {
return index % 2 == 0 ? "rgb(220, 220, 220)" : "rgb(235, 235, 235)";
};
const div = document.createElement("div");
setBookPhoto(card, div);
const book = card.book;
setBookInfo(div, book, bookRemover, readToggler);
div.classList.add("card");
const index = book.index;
div.setAttribute("index", index);
div.style.backgroundColor = alternateBackground(index);
return div;
}
};
})(document);
let modalForm = (function(document) {
const modal = document.getElementById("new-book-modal");
const newBookBtn = document.getElementById("new-book");
const closeSpan = document.getElementById("close-modal");
const bookFields = Array.from(document.getElementsByClassName("book-field"));
function hideModal() {
modal.style.display = "none";
document.body.style.overflow = null;
}
function restoreFields() {
bookFields.forEach(bookField => {
if(bookField.type === "text") {
bookField.value = "";
} else if(bookField.type === "checkbox") {
bookField.checked = false;
}
});
}
function restoreDefault() {
restoreFields();
hideModal();
}
return {
init(window) {
newBookBtn.addEventListener("click", () => {
modal.style.display = "flex";
document.body.style.overflow = "hidden";
});
closeSpan.addEventListener("click", () => {
restoreDefault();
});
window.addEventListener("click", function(e) {
if(e.target === modal) {
restoreDefault();
}
});
},
restoreFields
};
})(document);
let libraryApp = (function(window, document, cardCreator) {
let library = [];
let modal = modalForm;
function getBookFromModal() {
const formElements = document.getElementById("form-modal").elements;
const title = formElements.title.value;
const author = formElements.author.value;
const pages = formElements.pages.value;
const imageLink = formElements.imageLink.value;
const alreadyRead = formElements.alreadyRead.checked;
return createBook(title, author, pages, imageLink, alreadyRead);
}
function addBookToLibrary() {
const book = getBookFromModal();
library.unshift(book);
modal.restoreFields();
refreshBooksContainer();
}
function removeBooks() {
document.body.removeChild(document.getElementById("books-container"));
}
function displayBooks() {
const booksContainerDiv = document.createElement("div");
booksContainerDiv.id = "books-container";
let index = 0;
library.forEach(book => {
book.index = index;
const divCard = cardCreator.createDivCard(createCard(book), removeBookFromLibrary, readToggle);
booksContainerDiv.appendChild(divCard);
index += 1;
});
document.body.appendChild(booksContainerDiv);
}
function removeBookFromLibrary(e){
const index = getBookIndex(e);
library.splice(index, 1);
refreshBooksContainer();
}
function readToggle(e) {
const index = getBookIndex(e);
library[index].toggleRead();
refreshBooksContainer();
}
function refreshBooksContainer() {
window.localStorage.setItem("library", JSON.stringify(library));
removeBooks();
displayBooks();
}
function fetchLibraryFromLocalStorage() {
const deserializedLibrary = JSON.parse(window.localStorage.getItem("library") || "[]");
const associatedBooks = [];
deserializedLibrary.forEach(book => {
associatedBooks.push(createBook(book.title, book.author, book.pages, book.imageLink, book.alreadyRead));
});
return associatedBooks;
}
function getBookIndex(e) {
return e.currentTarget.parentNode.parentNode.parentNode.getAttribute("index");
}
return {
init() {
library = fetchLibraryFromLocalStorage();
modalForm.init(window);
if(library !== []) {
displayBooks();
}
document.getElementById("submit-button").addEventListener("click", addBookToLibrary);
}
};
})(window, document, cardCreator);
libraryApp.init();
| 46f00f96e752d7db0e96112ed672bb2f0cf3fbbe | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jlsuh/badreads | 5e2aeef595dce09d334a93ec9e58ac17dda8b882 | 43d3bce8c37fd91cc3769314bd6a8f3b03cff808 |
refs/heads/master | <file_sep>#!/usr/bin/env python
import re
import sys
import csv
import argparse
# without this, we may encounter fields larger than can be read
csv.field_size_limit(sys.maxsize)
parser = argparse.ArgumentParser()
parser.add_argument("files", help="path to CSVs, default stdin", nargs="*")
args = parser.parse_args()
files = args.files
if not files:
files = ["-"]
records = []
max_field_sizes = {}
number_looking_fields = {}
fieldnames = []
for file in files:
if file == "-":
infp = sys.stdin
else:
infp = open(file, "r")
reader = csv.DictReader(infp)
for record in reader:
if not fieldnames:
fieldnames = reader.fieldnames
records.append(record)
for key, value in record.items():
if key not in max_field_sizes:
max_field_sizes[key] = len(value)
if max_field_sizes[key] < len(value):
max_field_sizes[key] = len(value)
if max_field_sizes[key] < len(key):
max_field_sizes[key] = len(key)
if key not in number_looking_fields:
number_looking_fields[key] = True
if not re.search(r'^-?([1-9]+[0-9]*|0)(\.[0-9]+)?$', value):
number_looking_fields[key] = False
if file != "-":
infp.close()
header_fmt_parts = []
record_fmt_parts = []
sep_parts = []
for field in fieldnames:
header_fmt_parts.append(" {:^" + str(max_field_sizes[field]) + "} ")
align = "<"
if number_looking_fields[field]:
align = ">"
record_fmt_parts.append(" {:" + align + str(max_field_sizes[field]) + "} ")
sep_parts.append("-" + ("-" * max_field_sizes[field]) + "-")
header_fmt_str = "|".join(header_fmt_parts)
record_fmt_str = "|".join(record_fmt_parts)
print(header_fmt_str.format(*fieldnames))
print("+".join(sep_parts))
for record in records:
values = [record[f] for f in fieldnames]
print(record_fmt_str.format(*values))
| 0a054dddd3568ba59b75e49a7c5e3a6deb9302d5 | [
"Python"
] | 1 | Python | f0rk/csv2psql | 427bd33ccd1db42e82e8308da698f1441b970d26 | 6fdce048eb341158965dc5ea605f289ddb19a46b |
refs/heads/master | <repo_name>JONGSHIN/executor<file_sep>/src/main/java/org/jongshin/executor/oberservers/IObserverManager.java
package org.jongshin.executor.oberservers;
import org.jongshin.executor.data.TaskResult;
import org.jongshin.executor.task.ITask;
/**
* The interface responsible for managing observers and notifying them of any
* change in dependent task object.
*
* @author Vitalii_Kim
*
*/
public interface IObserverManager {
/**
* Associates the specified observer with the specified task.
*
* @param <K>
* the type of task's key
* @param <V>
* the type of task's computation result
*
* @param task
* the task, with which the specified observer is to be
* associated
* @param observer
* the observer to be associated with the specified task
* @throws NullPointerException
* if
* <li>{@code task} is {@code null}</li>
* <li>{@code observer} is {@code null}</li>
*/
<K, V> void add(ITask<K, V> task, IObserver<V> observer);
/**
* Removes all observers associated with specified task.
*
* @param <K>
* the type of task's key
* @param <V>
* the type of task's computation result
*
* @param task
* the task whose mapping is to be removed from observers
*
* @throws NullPointerException
* if {@code task} is {@code null}
*/
<K, V> void removeAll(ITask<K, V> task);
/**
* Removes specified observer associated with specified task.
*
* @param <K>
* the type of task's key
* @param <V>
* the type of task's computation result
* @param task
* the task whose mapping is to be removed from observers
* @param observer
* the observer to be removed
*
* @throws NullPointerException
* if
* <li>{@code task} is {@code null}</li>
* <li>{@code observer} is {@code null}</li>
*/
<K, V> void remove(ITask<K, V> task, IObserver<V> observer);
/**
* This method is called whenever the {@code ITask} is changed. An
* application calls an Observable object's notifyObservers method to have
* all the object's observers notified of the change.
*
* @param <V>
* the type of task's computation result
* @param taskResult
* The result of task computation
* @throws NullPointerException
* if {@code taskResult} has is {@code null}
*/
<V> void notifyObservers(TaskResult<V> taskResult);
}
<file_sep>/src/main/java/org/jongshin/executor/App.java
package org.jongshin.executor;
import java.util.concurrent.TimeUnit;
import org.jongshin.executor.data.CompositeKey;
import org.jongshin.executor.oberservers.IObserver;
import org.jongshin.executor.service.IProcessorService;
import org.jongshin.executor.service.ProcessorServiceImpl;
import org.jongshin.executor.task.SingleTask;
/**
*
* @author Vitalii_Kim
*
*/
class DfuCreateTask extends SingleTask<CompositeKey<String>, String> {
public DfuCreateTask(CompositeKey<String> key) {
super(key);
}
@Override
public String process() {
return "DFU Created: " + getKey();
}
}
class ActionItemCreateTask extends SingleTask<CompositeKey<String>, String> {
public ActionItemCreateTask(CompositeKey<String> key) {
super(key);
}
@Override
public String process() {
return "Action Item Created: " + getKey();
}
}
class DfuCreateObserver implements IObserver<String> {
@Override
public void notifyCompleted(String data) {
System.out.println(data);
}
@Override
public void notifyCanceled() {
System.out.println("CANCELED");
}
@Override
public void notifyFailed(Throwable cause) {
System.out.println("FAILED");
}
}
class ActionItemCreateObserver implements IObserver<String> {
@Override
public void notifyCompleted(String data) {
System.out.println(data);
}
@Override
public void notifyCanceled() {
System.out.println("CANCELED");
}
@Override
public void notifyFailed(Throwable cause) {
System.out.println("FAILED");
}
}
public class App {
public static void main(String[] args) {
IProcessorService ps = new ProcessorServiceImpl();
DfuCreateTask dfuCreateTask = new DfuCreateTask(new CompositeKey<String>("DfuId"));
ps.schedule(5, 3, TimeUnit.SECONDS, dfuCreateTask, new DfuCreateObserver());
ActionItemCreateTask actionItemCreateTaskRP1 = new ActionItemCreateTask(
new CompositeKey<String>("DfuId", "RP1"));
ps.schedule(5, 3, TimeUnit.SECONDS, actionItemCreateTaskRP1, new ActionItemCreateObserver());
ActionItemCreateTask actionItemCreateTaskRP2 = new ActionItemCreateTask(
new CompositeKey<String>("DfuId", "RP2"));
ps.schedule(5, 3, TimeUnit.SECONDS, actionItemCreateTaskRP2, new ActionItemCreateObserver());
actionItemCreateTaskRP2.cancel();
}
}
<file_sep>/src/main/java/org/jongshin/executor/task/AggregatedTask.java
package org.jongshin.executor.task;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Used for process several task as one and join their results.
*
* @author Vitalii_Kim
*
* @param <K>
* the type of key
* @param <V>
* the type of computation result
*/
public class AggregatedTask<K, V> extends AbstractTask<K, V> {
private Set<SingleTask<K, V>> tasks;
public AggregatedTask(K key) {
super(key);
tasks = new CopyOnWriteArraySet<>();
}
public boolean addTask(SingleTask<K, V> task) {
return tasks.add(task);
}
public boolean removeTask(SingleTask<K, V> task) {
return tasks.remove(task);
}
public Set<SingleTask<K, V>> getTasks() {
return tasks;
}
}
<file_sep>/src/main/java/org/jongshin/executor/data/ScheduledExecution.java
package org.jongshin.executor.data;
import java.util.concurrent.TimeUnit;
/**
* Represents an action that should be acted upon after a given delay.
*
* @author Vitalii_Kim
*
*/
public class ScheduledExecution extends Execution {
private final long initialDelay;
private final long period;
private final TimeUnit timeUnit;
public ScheduledExecution(long initialDelay, long period, TimeUnit timeUnit) {
this.initialDelay = initialDelay;
this.period = period;
this.timeUnit = timeUnit;
}
public long getInitialDelay() {
return initialDelay;
}
public long getPeriod() {
return period;
}
public TimeUnit getTimeUnit() {
return timeUnit;
}
public boolean isRepeatable() {
return period != 0;
}
@Override
public String toString() {
return "ScheduledExecution [initialDelay=" + initialDelay + ", period=" + period + ", timeUnit=" + timeUnit
+ "]";
}
}
<file_sep>/src/main/java/org/jongshin/executor/data/TaskStatus.java
package org.jongshin.executor.data;
/**
* Represents the status of task execution.
*
* @author Vitalii_Kim
*
*/
public enum TaskStatus {
NOT_STARTED, PENDING, STARTED, CANCELED, FAILED, COMPLETED;
}
<file_sep>/src/main/java/org/jongshin/executor/data/Execution.java
package org.jongshin.executor.data;
import java.util.concurrent.Future;
/**
* Represents the result of an asynchronous computation. Methods are provided to
* check if the computation is canceled, get status of task. Cancellation is
* performed by the {@code cancel} method.
*
* @author Vitalii_Kim
*
*/
public class Execution {
private Execution parentExecution;
private TaskStatus taskStatus;
private Future<?> future;
private boolean canceled;
public Execution() {
this.taskStatus = TaskStatus.PENDING;
}
public Execution getParentExecution() {
return parentExecution;
}
public void setParentExecution(Execution parentExecution) {
this.parentExecution = parentExecution;
}
public TaskStatus getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(TaskStatus taskStatus) {
this.taskStatus = taskStatus;
}
public Future<?> getFuture() {
return future;
}
public void setFuture(Future<?> future) {
this.future = future;
}
public boolean isCanceled() {
return canceled;
}
public void cancel() {
this.canceled = true;
}
@Override
public String toString() {
return "Execution [parentExecution=" + parentExecution + ", taskStatus=" + taskStatus + ", future=" + future
+ ", canceled=" + canceled + "]";
}
}
<file_sep>/src/main/java/org/jongshin/executor/oberservers/ObserverManagerImpl.java
package org.jongshin.executor.oberservers;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jongshin.executor.data.Execution;
import org.jongshin.executor.data.ProcessorException;
import org.jongshin.executor.data.ScheduledExecution;
import org.jongshin.executor.data.TaskResult;
import org.jongshin.executor.task.ITask;
import com.google.common.base.Preconditions;
/**
* The implementation of {@link IObserverManager}.
*
* @author Vitalii_Kim
*
*/
public class ObserverManagerImpl implements IObserverManager {
@SuppressWarnings("rawtypes")
private Map<ITask, Collection<IObserver>> observers;
private Lock lock;
public ObserverManagerImpl() {
observers = new ConcurrentHashMap<>();
lock = new ReentrantLock();
}
@Override
public <K, V> void add(ITask<K, V> task, IObserver<V> observer) {
Preconditions.checkNotNull(task, "task is null");
Preconditions.checkNotNull(observer, "observer is null");
@SuppressWarnings("rawtypes")
Collection<IObserver> bindedObservers = observers.get(task);
if (bindedObservers == null) {
lock.lock();
try {
bindedObservers = observers.get(task);
if (bindedObservers == null) {
if (bindedObservers == null) {
bindedObservers = new CopyOnWriteArraySet<>();
observers.put(task, bindedObservers);
}
}
} finally {
lock.unlock();
}
}
bindedObservers.add(observer);
}
@Override
public <K, V> void removeAll(ITask<K, V> task) {
Preconditions.checkNotNull(task);
observers.remove(task);
}
@Override
public <K, V> void remove(ITask<K, V> task, IObserver<V> observer) {
Preconditions.checkNotNull(task, "task is null");
Preconditions.checkNotNull(observer, "observer is null");
@SuppressWarnings("rawtypes")
Collection<IObserver> bindedObservers = observers.get(task);
if (bindedObservers != null) {
bindedObservers.remove(observer);
}
}
@SuppressWarnings("unchecked")
@Override
public <V> void notifyObservers(TaskResult<V> taskResult) {
Preconditions.checkNotNull(taskResult);
@SuppressWarnings("rawtypes")
ITask task = taskResult.getTask();
@SuppressWarnings("rawtypes")
Collection<IObserver> bindedObservers = observers.get(task);
if (bindedObservers == null) {
throw new ProcessorException(String.format("Can't find any observer [task=%s]", task));
}
Execution execution = taskResult.getExecution();
bindedObservers.stream().forEach(observer -> {
switch (execution.getTaskStatus()) {
case CANCELED: {
observer.notifyCanceled();
break;
}
case FAILED: {
observer.notifyFailed((Throwable) taskResult.getData());
break;
}
case COMPLETED: {
observer.notifyCompleted(taskResult.getData());
break;
}
default:
break;
}
});
if (execution.isCanceled()) {
observers.remove(task);
}
Execution parentExecution = execution.getParentExecution();
if (parentExecution instanceof ScheduledExecution) {
if (!((ScheduledExecution) parentExecution).isRepeatable()) {
observers.remove(task);
}
} else {
observers.remove(task);
}
}
}
<file_sep>/src/main/java/org/jongshin/executor/data/CompositeKey.java
package org.jongshin.executor.data;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Preconditions;
/**
* Used for identify the task.
*
* @author Vitalii_Kim
*
* @param <K>
* the type of elements in this key
*/
public final class CompositeKey<K> {
private final K major;
private final List<K> minors;
/**
*
* @param major
* the major part
* @param minors
* the minor part
*
* @throws NullPointerException
* if
* <li>{@code major} is {@code null}</li>
* <li>{@code minors} is {@code null}</li>
*/
public CompositeKey(K major, @SuppressWarnings("unchecked") K... minors) {
Preconditions.checkNotNull(major, "Illegal major");
Preconditions.checkNotNull(minors, "Illegal minors");
this.major = major;
this.minors = Arrays.asList(minors);
}
public K getMajor() {
return major;
}
public List<K> getMinors() {
return Collections.unmodifiableList(minors);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((major == null) ? 0 : major.hashCode());
result = prime * result + ((minors == null) ? 0 : minors.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
@SuppressWarnings("rawtypes")
CompositeKey other = (CompositeKey) obj;
if (major == null) {
if (other.major != null)
return false;
} else if (!major.equals(other.major))
return false;
if (minors == null) {
if (other.minors != null)
return false;
} else if (!minors.equals(other.minors))
return false;
return true;
}
@Override
public String toString() {
return "CompositeKey [major=" + major + ", minors=" + minors + "]";
}
}
| 2fe1ba12ef82b588c6c6522ad180b91b9b67541d | [
"Java"
] | 8 | Java | JONGSHIN/executor | d3e56b780e7f1e8a0c141c131dbc6aaa5816962d | fb1966cae07a995a5684b7d2cc7889eeb2075238 |
refs/heads/master | <repo_name>NotSylver/Zira<file_sep>/src/Utils.js
'use strict';
const Logger = require('disnode-logger');
const fs = require('fs');
class Utils {
constructor(caller) {
this.db = caller.db;
this.bot = caller.bot;
this.caller = caller;
}
async message(channel, content) {
try {
await this.bot.createMessage(channel, content);
} catch (e) {
this.caller.Logger.Warning('Message', ` ${channel} `, e.message.replace(/\n\s/g, ''));
if (e.code === 50013) {
this.bot.createMessage(channel, 'I\'m unable to send the message as I\'m missing the permission `Embed Links` in this channel.').catch(err => this.caller.Logger.Warning('Error Message', ` ${channel} `, err.message.replace(/\n\s/g, '')));
}
}
}
snowflakeDate(resourceID) {
return new Date(parseInt(resourceID) / 4194304 + 1420070400000); // eslint-disable-line
}
randomNumber(min, max) {
const first = Math.ceil(min);
const second = Math.floor(max);
return Math.floor(Math.random() * ((second - first) + 1)) + first;
}
getTime(time) {
const currentTime = new Date();
const elapsed = currentTime - time;
let weeks = 0;
let days = 0;
let hours = 0;
let minutes = 0;
let seconds = parseInt(elapsed / 1000); // eslint-disable-line
while (seconds >= 60) {
minutes++;
seconds -= 60;
if (minutes === 60) {
hours++;
minutes = 0;
}
if (hours === 24) {
days++;
hours = 0;
}
if (days >= 7) {
weeks++;
days = 0;
}
}
let message = '';
if (weeks > 0) {
if (weeks === 1) {
message += '1 week';
} else {
message += `${weeks} weeks`;
}
}
if (days > 0) {
if (weeks > 0) message += ', ';
if (days === 1) {
message += '1 day';
} else {
message += `${days} days`;
}
}
if (hours > 0) {
if (days > 0 || weeks > 0) message += ', ';
if (hours === 1) {
message += '1 hour';
} else {
message += `${hours} hours`;
}
}
if (minutes > 0) {
if (hours > 0 || days > 0 || weeks > 0) message += ', ';
if (minutes === 1) {
message += '1 minute';
} else {
message += `${minutes} minutes`;
}
}
if (seconds > 0) {
if (minutes > 0 || hours > 0 || days > 0 || weeks > 0) message += ', ';
if (seconds === 1) {
message += '1 second';
} else {
message += `${seconds} seconds`;
}
}
if (!message) message = '1 second';
return message;
}
ordinalSuffix(i) {
if ((i % 10) === 1 && (i % 100) !== 11) {
return `${i}st`;
}
if ((i % 10) === 2 && (i % 100) !== 12) {
return `${i}nd`;
}
if ((i % 10) === 3 && (i % 100) !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
combine(First, Second) {
const res = [];
const arr = First.concat(Second);
let I = arr.length;
const Obj = {};
while (I--) {
const item = arr[I];
if (!Obj[item]) {
res.unshift(item);
Obj[item] = true;
}
}
return res;
}
getLang(guild = { // eslint-disable-line
lang: 'en',
}) {
let {
lang,
} = guild;
if (!guild.lang) lang = 'en';
if (!fs.existsSync(`./lang/${lang}.json`)) lang = 'en';
try {
return require(`../lang/${lang}.json`); // eslint-disable-line
} catch (e) {
Logger.Error('Utils', 'getLang', `Error when getting file: ${lang} :: ${e}`);
} finally {
delete require.cache[require.resolve(`../lang/${lang}.json`)];
}
}
parseParams(Params) {
const params = [];
let string = '';
if (typeof Params === 'object') string = Params.join(' ');
if (typeof Params === 'string') string = Params;
string.split(', ').forEach((str) => {
const emoji = str.split(' ', 1)[0];
let role = str.replace(`${emoji} `, '');
if (role.indexOf('<@&') !== -1) role = role.replace(/\D+/g, '');
params.push([emoji, role]);
});
return params;
}
async getGuild(id) {
const self = this;
let guild = await self.db.Find('reaction', {
id,
});
[guild] = guild;
if (!guild) {
guild = {
id,
roles: [],
msgid: [],
chan: '',
};
self.db.Insert('reaction', guild);
}
return guild;
}
async updateGuild(guild) {
const self = this;
const {
id,
} = guild;
await self.db.Update('reaction', {
id,
}, guild);
}
mapObj(map) {
const obj = {};
map.forEach((value, key) => {
obj[key] = value;
});
return obj;
}
postStats(caller) {
process.send({
name: 'stats',
data: {
messages: caller.handler.seen,
commands: caller.handler.commands,
users: caller.bot.users.filter(u => !u.bot).length,
bots: caller.bot.users.filter(u => u.bot).length,
guilds: caller.bot.guilds.map(g => g.id),
memory: (process.memoryUsage().rss / 1024 / 1024).toFixed(2),
uptime: caller.utils.getTime(caller.bot.startTime),
cluster: caller.id,
shards: caller.bot.shards.size,
},
});
}
}
module.exports = Utils;
<file_sep>/commands/reset.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
let guild = GUILD;
const lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.author.id === command.msg.channel.guild.ownerID) {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.yellow,
title: lang.reset.title,
description: lang.reset.question,
},
});
let timer;
const handler = async (message) => {
if (message.author.id !== command.msg.author.id && message.channel.id !== command.msg.id) return;
console.log(message.content);
if (message.content === 'yes') {
guild = {
id: guild.id,
roles: [],
msgid: [],
chan: '',
emoji: '',
user: [],
bot: [],
log: '',
joinChannel: '',
joinMessage: '',
leaveChannel: '',
leaveMessage: '',
suggestionRole: '',
suggestionDM: false,
approveChannel: '',
lang: guild.lang,
};
if (GUILD.premium) {
guild.premium = GUILD.premium;
guild.premiumExpires = GUILD.premiumExpires;
guild.premiumUsers = GUILD.premiumUsers;
}
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.green,
description: lang.reset.yes,
},
});
caller.utils.updateGuild(guild);
caller.bot.off('messageCreate', handler);
clearTimeout(timer);
} else if (message.content === 'no') {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
description: lang.reset.no,
},
});
caller.bot.off('messageCreate', handler);
clearTimeout(timer);
}
};
caller.bot.on('messageCreate', handler);
timer = setTimeout(() => {
caller.bot.off('messageCreate', handler);
}, 120000);
} else {
caller.utils.sendMessage(command, {
embed: {
title: lang.titleError,
description: lang.reset.perm,
color: caller.color.yellow,
},
});
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'misc',
};
};
<file_sep>/commands/translate.js
'use strict';
const translate = require('google-translate-api');
exports.Run = async function Run(caller, command, GUILD) {
const lang = caller.utils.getLang(GUILD.code);
if (!command.params[0] || !command.params[1]) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.title,
color: caller.color.blue,
description: `**${command.prefix}${lang.translate}\n\n${lang.example}${command.prefix}translate es Hi, how are you today?`,
},
});
return;
}
if (command.params.join(' ').indexOf('@everyone') !== -1 || command.params.join(' ').indexOf('@here') !== -1) return;
const code = command.params[0];
const string = command.params.splice(1).join(' ');
translate(string, {
to: code,
}).then((res) => {
caller.utils.message(command.msg.channel.id, `${command.msg.author.username}\n${res.from.language.iso} **->** ${code}\n\n${res.text}`);
}).catch((e) => {
caller.utils.message(command.msg.channel.id, `${e}`).catch(console.error);
});
};
exports.Settings = function Settings() {
return {
show: false,
};
};
<file_sep>/.env.example
PREFIX="your desired prefix here"
TOKEN="your bot token here"
OWNER="your user id here"
DB_USER="mongo username"
DB_PASS="<PASSWORD>"
DB_HOST="mongo host/collection"
WEBHOOK_ID="webhook id for guild logging"
WEBHOOK_TOKEN="webhook token for guild logging"
TRELLO_KEY="trello key"
TRELLO_TOKEN="trello token"
SHARDS=1
CLUSTERS=1<file_sep>/events/reactionAdd.js
'use strict';
exports.Run = async function Run(caller, _message, _emoji, _user) {
const self = caller;
const guild = await self.utils.getGuild(_message.channel.guild.id);
if (guild.msgid.indexOf(_message.id) === -1) return;
if (!guild) return; // no idea why this would be undefined or null but yea
const [role] = guild.roles.filter(r => r.msg === _message.id && (r.emoji === _emoji.name || r.emoji.indexOf(_emoji.id) !== -1));
const emoji = (_emoji.id === null) ? _emoji.name : `${(_emoji.animated) ? '<a:' : '<:'}${_emoji.name}:${_emoji.id}>`;
const message = await self.bot.getMessage(_message.channel.id, _message.id).catch(console.error);
const me = message.channel.guild.members.get(self.bot.user.id);
const user = message.channel.guild.members.get(_user);
const lang = self.utils.getLang(guild);
let claimed = false;
if (role) {
if (!me.permission.has('manageRoles')) return;
let highestRole = 0;
me.roles.forEach((id) => {
const {
position,
} = message.channel.guild.roles.get(id);
if (position > highestRole) highestRole = position;
});
if (role.id) {
const ROLECHECK = message.channel.guild.roles.get(role.id);
if (!ROLECHECK || ROLECHECK.position >= highestRole) return;
} else if (role.ids) {
let higher = false;
role.ids.forEach((id) => {
const ROLECHECK = message.channel.guild.roles.get(id);
if (!ROLECHECK || ROLECHECK.position >= highestRole) higher = true;
});
if (higher) return;
}
if (role.toggle) {
const toggleEmojis = guild.roles.filter(r => r.msg === _message.id && r.toggle === true && r.id !== role.id).map(r => r.emoji);
if (self.userRateLimits[_user] !== undefined) {
const ms = new Date().getTime() - self.userRateLimits[_user];
if (ms < (500 * toggleEmojis.length)) return;
}
self.userRateLimits[_user] = new Date().getTime();
if (me.permission.has('manageMessages')) {
const ReactionKeys = Object.keys(message.reactions);
ReactionKeys.forEach((i, index) => {
if (toggleEmojis.indexOf(i) !== -1 || toggleEmojis.filter(e => e.indexOf(i) !== -1)[0]) {
setTimeout(() => {
message.removeReaction(i, _user).catch(console.error);
}, 100 * index);
}
});
}
}
if (role.once) {
const [claimedUser] = await self.db.Find('once', {
id: _user,
});
if (claimedUser) {
if (claimedUser.claimed.indexOf(role.id) !== -1) {
claimed = true;
} else {
claimedUser.claimed.push(role.id);
await self.db.Update('once', {
id: _user,
}, claimedUser);
}
} else {
await self.db.Insert('once', {
id: _user,
claimed: [role.id],
});
}
if (me.permission.has('manageMessages')) await message.removeReaction(emoji.replace(/(<:)|(<)|(>)/g, ''), _user).catch(console.error);
}
if (role.remove) {
if (user.roles.indexOf(role.id) !== -1) user.roles.splice(user.roles.indexOf(role.id), 1);
if (user.roles.indexOf(role.add) === -1 && role.add) user.roles.push(role.add);
try {
await user.edit({
roles: self.utils.combine(user.roles, role.ids),
}, 'Reaction Role');
} catch (e) {
console.error(e);
return;
}
if (guild.log) {
self.bot.createMessage(guild.log, {
embed: {
footer: {
text: `${user.username}#${user.discriminator}`,
icon_url: user.avatarURL,
},
color: 0x00d62e,
description: `<@${user.id}>${lang.log.give[0]}${role.emoji}${lang.log.remove[1]}<@&${role.id}>${lang.log.give[2]}<@&${role.add}>`,
timestamp: new Date(),
},
}).catch((e) => {
console.error(e);
if (e.code === 50013 || e.code === 50001) {
guild.log = '';
self.utils.updateGuild(guild);
}
});
if (me.permission.has('manageMessages')) await message.removeReaction(emoji.replace(/(<:)|(<)|(>)/g, ''), _user).catch(console.error);
}
return; // eslint-disable-line
}
if (role.multi) {
try {
await user.edit({
roles: self.utils.combine(user.roles, role.ids),
}, 'Reaction Role');
} catch (e) {
console.error(e);
return;
}
let roles = '';
role.ids.forEach((id, index) => {
roles += `<@&${id}>${(index === role.ids.length - 1) ? ' ' : ', '}`;
});
if (guild.log) {
self.bot.createMessage(guild.log, {
embed: {
footer: {
text: `${user.username}#${user.discriminator}`,
icon_url: user.avatarURL,
},
color: 0x00d62e,
description: `<@${user.id}>${lang.log.give[0]}${role.emoji}${lang.log.give[1]}${roles}`,
timestamp: new Date(),
},
}).catch((e) => {
console.error(e);
if (e.code === 50013 || e.code === 50001) {
guild.log = '';
self.utils.updateGuild(guild);
}
});
}
return; // eslint-disable-line
}
if (!claimed) {
try {
if (!me.permission.has('manageRoles')) return;
await message.channel.guild.addMemberRole(_user, role.id, 'Reaction Role');
} catch (e) {
console.error(e);
return;
}
if (guild.log) {
self.bot.createMessage(guild.log, {
embed: {
footer: {
text: `${user.username}#${user.discriminator}`,
icon_url: user.avatarURL,
},
color: 0x00d62e,
description: `<@${user.id}>${lang.log.give[0]}${role.emoji}${lang.log.give[1]}<@&${role.id}>`,
timestamp: new Date(),
},
}).catch((e) => {
console.error(e);
if (e.code === 50013 || e.code === 50001) {
guild.log = '';
self.utils.updateGuild(guild);
}
});
}
return; // eslint-disable-line
}
}
if (me.permission.has('manageMessages')) await message.removeReaction(emoji.replace(/(<:)|(<)|(>)/g, ''), _user).catch(console.error);
};
<file_sep>/commands/prefix.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const guild = GUILD;
const lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.member.permission.has('manageGuild')) {
if (!command.params[0]) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.title,
color: caller.color.blue,
description: `**${command.prefix}${lang.prefix.help}`,
},
});
return;
}
const prefix = command.params.join(' ');
if (prefix.length < 1 || prefix.length > 10) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.prefix.error,
color: caller.color.yellow,
},
});
return;
}
guild.prefix = prefix;
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleComp,
description: lang.prefix.set + guild.prefix,
color: caller.color.green,
},
});
caller.utils.updateGuild(guild);
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.perm.noGuildPerm,
color: caller.color.yellow,
},
});
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'misc',
};
};
<file_sep>/events/guildMemberAdd.js
'use strict';
exports.Run = async function Run(caller, guild, member, GuildDB) {
const Guild = GuildDB;
if (Guild.joinChannel && Guild.joinMessage) {
if (!member.user.bot) {
let msg = Guild.joinMessage;
msg = msg.replace(/\$user/g, member.username);
msg = msg.replace(/\$mention/g, `<@${member.id}>`);
msg = msg.replace(/\$guild/g, guild.name);
msg = msg.replace(/\$membercount/g, guild.memberCount);
caller.utils.message(Guild.joinChannel, msg).catch((err) => {
console.error(err);
if (err.code === 50013 || err.code === 50001) {
Guild.joinChannel = '';
caller.utils.updateGuild(Guild);
}
});
}
}
let fixed = false;
if (typeof Guild.user === 'undefined') {
Guild.user = [];
fixed = true;
}
if (typeof Guild.bot === 'undefined') {
Guild.bot = [];
fixed = true;
}
if (typeof Guild.user === 'string') {
Guild.user = [Guild.user];
fixed = true;
}
if (typeof Guild.bot === 'string') {
Guild.bot = [Guild.bot];
fixed = true;
}
if (fixed) caller.utils.updateGuild(Guild);
switch (member.bot) {
case false:
if (!Guild.user[0]) return;
guild.editMember(member.id, {
roles: Guild.user,
}, 'Autorole on join').catch(console.error);
break;
case true:
if (!Guild.bot[0]) return;
guild.editMember(member.id, {
roles: Guild.bot,
}, 'Autorole on join').catch(console.error);
break;
default:
}
};
<file_sep>/commands/submit.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const guild = GUILD;
const lang = caller.utils.getLang(guild);
if (!command.params[0]) {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: lang.title,
description: `**${command.prefix}${lang.submit.help}`,
},
}).catch(console.error);
return;
}
const channel = command.msg.channel.guild.channels.get(guild.suggestion);
if (channel) {
if (guild.submitChannel) {
if (guild.submitChannel !== command.msg.channel.id) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
color: caller.color.yellow,
description: lang.suggestion.useChannel[0] + guild.submitChannel + lang.suggestion.useChannel[1],
},
}).then((m) => {
setTimeout(() => {
if (command.msg.channel.guild.members.get(caller.bot.user.id).permission.has('manageMessages')) command.msg.delete().catch(console.error);
m.delete().catch(console.error);
}, 5000);
}).catch(console.error);
return;
}
}
let card;
if (guild.trello && guild.trello.enabled) {
card = await caller.trello.addCard(`${command.msg.author.username}#${command.msg.author.discriminator}`, command.params.join(' '), guild.trello.list);
}
if (typeof card === 'string') card = undefined; // cause appearntly the creator of the trello package doesnt believe in rejecting errors
let message;
const id = Math.random().toString(36).substr(2, 5);
try {
const embed = {
author: {
name: `${command.msg.author.username}#${command.msg.author.discriminator}`,
icon_url: command.msg.author.avatarURL,
},
color: caller.color.blue,
fields: [{
name: lang.submit.title,
value: command.params.join(' '),
}],
footer: {
text: `ID: ${id}`,
},
};
if (card) {
embed.title = 'Trello';
embed.url = card.shortUrl;
}
message = await caller.bot.createMessage(guild.suggestion, {
embed,
});
} catch (e) {
caller.Logger.Warning(command.msg.author.username, ` ${command.msg.author.id} ${command.msg.channel.id} `, e.message.replace(/\n\s/g, ''));
guild.suggestion = '';
caller.utils.updateGuild(guild);
return;
}
if (command.msg.channel.guild.members.get(caller.bot.user.id).permission.has('addReactions')) {
await caller.bot.addMessageReaction(guild.suggestion, message.id, '⬆').catch(console.error);
await caller.bot.addMessageReaction(guild.suggestion, message.id, '⬇').catch(console.error);
}
if (!guild.suggestions) guild.suggestions = [];
guild.suggestions.push({
user: command.msg.author.id,
suggestion: command.params.join(' '),
message: message.id,
id,
trello: (card) ? card.shortUrl : null,
channel: guild.suggestion,
});
caller.utils.updateGuild(guild);
if (command.msg.channel.guild.members.get(caller.bot.user.id).permission.has('manageMessages')) caller.bot.deleteMessage(command.msg.channel.id, command.msg.id).catch(console.error);
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'suggestion',
};
};
<file_sep>/commands/edit.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const guild = GUILD;
const lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.member.permission.has('manageRoles')) {
if (!command.params[0] || !command.params[1]) {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: lang.title,
description: `**${command.prefix}${lang.edit.help}\n\n${lang.example}${command.prefix}edit ${command.msg.id} Some new message\n`,
},
}).catch(console.error);
return;
}
try {
await caller.bot.editMessage(guild.chan, command.params[0], command.params.splice(1).join(' '));
} catch (e) {
caller.Logger.Warning(command.msg.author.username, ` ${command.msg.author.id} ${command.msg.channel.id} `, e.message.replace(/\n\s/g, ''));
if (e.code === 50001) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.edit.read[0] + guild.chan + lang.edit.read[1],
color: caller.color.yellow,
},
}).catch(console.error);
} else if (e.code === 10008) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: `${lang.edit.unknownGet}${guild.chan}>`,
color: caller.color.yellow,
},
}).catch(console.error);
} else if (e.code === 50005) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.edit.no,
color: caller.color.yellow,
},
}).catch(console.error);
}
return;
}
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleComp,
description: lang.edit.edited,
color: caller.color.green,
},
}).catch(console.error);
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.perm.noPerm,
color: caller.color.yellow,
},
}).catch(console.error);
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'role',
};
};
<file_sep>/events/guildMemberRemove.js
'use strict';
exports.Run = async function Run(caller, guild, member, GuildDB) {
const Guild = GuildDB;
if (Guild.leaveChannel && Guild.leaveMessage) {
if (!member.user.bot) {
let msg = Guild.leaveMessage;
msg = msg.replace(/\$user/g, member.user.username);
msg = msg.replace(/\$mention/g, `<@${member.id}>`);
msg = msg.replace(/\$guild/g, guild.name);
msg = msg.replace(/\$membercount/g, guild.memberCount);
caller.utils.message(Guild.leaveChannel, msg).catch((err) => {
console.error(err);
if (err.code === 50013 || err.code === 50001) {
Guild.leaveChannel = '';
caller.utils.updateGuild(Guild);
}
});
}
}
};
<file_sep>/commands/list.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const guild = GUILD;
const lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.member.permission.has('manageRoles')) {
let list = lang.list.top;
let list2 = '';
let list3 = '';
const IDS = [];
guild.roles.forEach(async (item) => {
if (IDS.indexOf(item.msg) === -1) {
IDS.push(item.msg);
}
});
let second = false;
let third = false;
IDS.forEach(async (id) => {
const roles = guild.roles.filter(r => r.msg === id);
roles.forEach(async (item) => {
let type = 'Normal';
let role = `<@&${item.id}>`;
if (item.toggle) type = 'Toggled';
if (item.once) type = 'Once';
if (item.multi) {
type = 'Multi';
role = item.name;
}
if (item.remove) type = 'Remove';
if (list.length < 1950) {
list += `${(item.channel) ? `<#${item.channel}>` : `<#${guild.chan}>`} ~~-~~ ${item.msg} ~~-~~ ${type} ~~-~~ ${item.emoji} ~~-~~ ${role}\n`;
} else if (list2.length < 1950) {
second = true;
list2 += `${(item.channel) ? `<#${item.channel}>` : `<#${guild.chan}>`} ~~-~~ ${item.msg} ~~-~~ ${type} ~~-~~ ${item.emoji} ~~-~~ ${role}\n`;
} else {
third = true;
list3 += `${(item.channel) ? `<#${item.channel}>` : `<#${guild.chan}>`} ~~-~~ ${item.msg} ~~-~~ ${type} ~~-~~ ${item.emoji} ~~-~~ ${role}\n`;
}
});
});
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: `${command.msg.channel.guild.name} ${lang.list.title}`,
description: list,
},
}).catch(console.error);
if (second) {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: `${command.msg.channel.guild.name} ${lang.list.cont}`,
description: list2,
},
}).catch(console.error);
}
if (third) {
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: `${command.msg.channel.guild.name} ${lang.list.cont}`,
description: list3,
},
}).catch(console.error);
}
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.perm.noPerm,
color: caller.color.yellow,
},
}).catch(console.error);
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'role',
};
};
<file_sep>/commands/eval.js
'use strict';
exports.Run = async function Run(caller, command, guild) { // eslint-disable-line no-unused-vars
if (command.msg.author.id !== process.env.OWNER) return;
const code = command.params.join(' ');
try {
let evaled = eval(code); // eslint-disable-line
if (typeof evaled !== 'string') evaled = require('util').inspect(evaled); // eslint-disable-line
if (evaled.length > 1960) {
caller.utils.message(command.msg.channel.id, '```Result longer then 2000 characters so it was logged to console.```');
console.log(evaled);
} else if (evaled === undefined) {
caller.utils.message(command.msg.channel.id, `\`\`\`json\n${evaled}\n\`\`\``);
} else {
caller.utils.message(command.msg.channel.id, `\`\`\`json\n${evaled}\n\`\`\``);
}
} catch (e) {
caller.utils.message(command.msg.channel.id, `\`\`\`json\n${e}\n\`\`\``);
}
};
exports.Settings = function Settings() {
return {
show: false,
};
};
<file_sep>/commands/multi.js
'use strict';
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const guild = GUILD;
const lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.member.permission.has('manageRoles')) {
if (!command.params[0] || !command.params[1] || !command.params[2]) {
const ROLES = command.msg.channel.guild.roles.filter(r => r.id !== command.msg.channel.guild.id);
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
title: lang.title,
description: `**${command.prefix}${lang.multi.help}\n\n${lang.example}${command.prefix}multi :information_source: Updates, <@&${ROLES[caller.utils.randomNumber(0, ROLES.length - 1)].id}>\n${command.prefix}multi :information_source: Updates, <@&${ROLES[caller.utils.randomNumber(0, ROLES.length - 1)].id}>, <@&${ROLES[caller.utils.randomNumber(0, ROLES.length - 1)].id}>`,
},
}).catch(console.error);
return;
}
if (!guild.chan) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.noChannel[0] + command.prefix + lang.noChannel[1],
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
if (!guild.emoji || !guild.msgid.length) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.noMessage[0] + command.prefix + lang.noMessage[1],
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
const emoji = command.params[0];
const Params = command.params.splice(1).join(' ').split(', ');
Params.forEach((item, index) => {
if (item.indexOf('<@&') !== -1) Params[index] = item.replace(/\D+/g, '');
});
const roles = [];
for (let i = 0; i < Params.length; i++) {
// eslint-disable-next-line no-loop-func
const [role] = command.msg.channel.guild.roles.filter(r => r.id === Params[i] || r.name.toLowerCase().indexOf(Params[i].toLowerCase()) !== -1);
if (!role) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.unknownRole[0] + caller.utils.ordinalSuffix(i + 1) + lang.unknownRole[1],
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
roles.push(role.id);
}
let emojiFree = true;
for (let r = 0; r < guild.roles.length; r++) {
if (guild.roles[r].msg === guild.emoji) {
if (guild.roles[r].emoji === emoji) emojiFree = false;
}
}
if (!emojiFree) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.add.emoji[0] + emoji + lang.add.emoji[1],
color: caller.color.yellow,
},
}).catch(console.error);
return;
}
try {
await caller.bot.addMessageReaction(guild.chan, guild.emoji, emoji.replace(/(<:)|(<)|(>)/g, ''));
} catch (e) {
caller.Logger.Warning(command.msg.author.username, ` ${command.msg.author.id} ${command.msg.channel.id} `, e.message.replace(/\n\s/g, ''));
if (e.code === 50001) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.add.cannotRead[0] + emoji + lang.add.cannotRead[1] + guild.chan + lang.add.cannotRead[2],
color: caller.color.yellow,
},
}).catch(console.error);
} else if (e.code === 50013) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.add.cannotReact[0] + emoji + lang.add.cannotReact[1] + guild.chan + lang.add.cannotReact[2],
color: caller.color.yellow,
},
}).catch(console.error);
} else if (e.code === 10014) {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.unknownEmoji[0] + caller.utils.ordinalSuffix(1) + lang.unknownEmoji[1],
color: caller.color.yellow,
},
}).catch(console.error);
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: `${lang.add.unknown[0]}${emoji}${lang.add.unknown[1]}${guild.chan}>`,
color: caller.color.yellow,
},
}).catch(console.error);
}
return;
}
let message = '';
roles.forEach((id, index) => {
message += `<@&${id}>${(index === roles.length - 1) ? ' ' : ', '}`;
});
guild.roles.push({
ids: roles,
name: message,
emoji,
msg: guild.emoji,
channel: guild.chan,
multi: true,
});
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleComp,
description: message + lang.multi.set[0] + emoji + lang.multi.set[1],
color: caller.color.green,
},
}).catch(console.error);
caller.utils.updateGuild(guild);
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.perm.noPerm,
color: caller.color.yellow,
},
}).catch(console.error);
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'role',
};
};
<file_sep>/commands/lang.js
'use strict';
const fs = require('fs');
const {
promisify,
} = require('util');
function Sanitize(string) {
let str = string;
while (string.indexOf('../') !== -1) {
str = string.replace('../', '');
}
while (string.indexOf('./') !== -1) {
str = string.replace('./', '');
}
return str;
}
const readdir = promisify(fs.readdir);
exports.Run = async function Run(caller, command, GUILD) {
if (!command.msg.channel.guild) {
caller.utils.message(command.msg.channel.id, {
embed: {
description: ':warning: This command can\'t be used in DM',
color: caller.color.yellow,
},
});
return;
}
const guild = GUILD;
let lang = caller.utils.getLang(guild);
if (command.msg.author.id === process.env.OWNER || command.msg.member.permission.has('manageGuild')) {
const code = (command.params[0]) ? Sanitize(command.params[0]) : 'thisisntalanguage';
if (fs.existsSync(`./lang/${code}.json`)) {
guild.lang = code;
lang = require(`../lang/${code}.json`); // eslint-disable-line
caller.utils.message(command.msg.channel.id, {
embed: {
description: lang.lang.langUpdate,
color: caller.color.green,
},
});
caller.utils.updateGuild(guild);
} else {
const files = await readdir('./lang/');
let description = '';
files.forEach((file) => {
if (file.indexOf('.json') !== -1) {
description += `**${command.prefix}lang ${file.split('.json')[0]}** ~~-~~ ${require(`../lang/${file}`).language}\n`; // eslint-disable-line
}
});
description += lang.lang.translate;
caller.utils.message(command.msg.channel.id, {
embed: {
color: caller.color.blue,
description,
},
});
}
} else {
caller.utils.message(command.msg.channel.id, {
embed: {
title: lang.titleError,
description: lang.perm.noGuildPerm,
color: caller.color.yellow,
},
});
}
};
exports.Settings = function Settings() {
return {
show: true,
category: 'misc',
};
};
| d93c19e6eb532e80ccb24ec337b377e84e7dc2f2 | [
"JavaScript",
"Shell"
] | 14 | JavaScript | NotSylver/Zira | d45351145f2efa530a1d5c41bedbec1d257061d3 | a73a63a9de8d0e63ca0fdd87e9a7670b8f05d425 |
refs/heads/master | <repo_name>DavidTraina/SystemsProgramming<file_sep>/lab6/README.md
3/21/2021 Lab 6
https://q.utoronto.ca/courses/68725/assignments/1 13160 1 / 2
# Lab 6
```
Due Feb 15, 2019 by 6:30pm Points 1
```
# Lab 6: Using the Debugger
```
Due date : Friday 15 February before 6:30pm.
```
# Introduction
```
The main purpose of this lab is to give you some practice using the debugger. Before that, we have one more string function for you to write.
```
# Starting
```
As usual, go to Lab6 on Markus and then pull your repo to trigger the downloading of the starter code.
```
# More Practice with Strings
```
Complete the program copy.c according to the instructions in the starter code.
```
# Using gdb
```
It’s common for programmers to debug using print , at least for simple issues, but debugging with print statements will become increasingly difficult
as we delve into systems programming. Now is the time to learn how to use a common C debugger, gdb. It’ll seem hard at first, but you’ll be
thankful for these skills at the end of this course and in courses like CSC 369.
To demonstrate that you’ve completed the lab, you’ll submit a script record of your interactions on the command line to your git repository. Try it
out by typing script then typing a few unix commands. Perhaps make a directory for your work on this lab or list the files in your current directory or
whatever you wish... Then after you’ve done something, type exit. This will stop recording your actions and save them in a file named typescript.
Check out the man page for script to see that you can give it a filename as an argument to override this default name.
The file overflow.c (in your repo in Lab6) contains a program to explore. You will change the values of SIZE and OVERFLOW to see what happens
when OVERFLOW is bigger than SIZE.
First, read through the program and explain what it is doing aloud to yourself (or to some unsuspecting bystander, if you prefer). Notice that we are
printing the addresses of the variables. The purpose of doing that is to show where the variables are placed in memory.
Next, compile and run the program as shown here:
```
```
$ gcc -Wall -std=gnu99 -g -o overflow overflow.c
$ ./overflow
```
```
Don’t miss the -g flag or gdb won’t work properly. Check the values of before , a , and after – did the program behave as expected?
Now change the value of OVERFLOW to 5. Compile the program and run it again. What changed? (If nothing changed – if everything still seems okay –
then try this code on a lab machine. It depends on how the variables are placed into memory by the compiler, and your compiler may be doing
something we didn’t expect.)
Let’s see why variables other than a were affected. The next step is to run the program in gdb. Here are a list of the 9 need-to-know commands in
gdb:
```
```
gdb executable start gdb on this executable
list [n] list some of the code starting from line n or from the end of last call to list
break [n or fun_name] set a breakpoint either at line n or at the beginning of the function fun_name
run [args] begin execution with these command-line arguments
next execute one line
print variable or expression print the value once
display variable or expression print the value after every gdb command
continue execute up to the next breakpoint
quit bye-bye!
```
```
Try this out on your overflow executable. Start by typing gdb overflow. Set a breakpoint in main by typing break main, and then start the program
running by typing run. You want to watch the values of a few variables, so use display to show the value of some variables. Do this for each
variable you want to watch. Step through the program one line at a time using next (after you enter next once, you can execute another line by
```
3/21/2021 Lab 6
https://q.utoronto.ca/courses/68725/assignments/1 13160 2 / 2
```
just hitting “enter”). Keep a close eye on the first element in after, and notice the final value of a. When the program terminates, type quit to
leave gdb.
Now start gdb again but before you start, use script to record your interaction. (You’ll submit this interaction.) This time make sure you watch the
array after. It is pretty slow to step through every line of your code, so use list to find the line number of the for loop where we start to assign
values to the array. Set a breakpoint on that line number and also set a breakpoint somewhere before that line. Start your program using run and it
should run up to the first breakpoint. Then use continue to jump to the second breakpoint you set which should be the for loop. At any point, you
can use continue to execute up to the next breakpoint. If you tried it again now, it should jump to the second pass through the loop.
Instead, use next to step through one line at a time. Watch the value of after[0] carefully. When it changes, print its address. (Yes, you can do
“print &(after[0])” inside gdb.) Then, print the address of a[4]. Does that help you understand what happened? Exit gdb. (Say ‘y’ when it asks if
you want to Quit anyway.) Then exit your script. Rename the script file you generated to gdb_example.txt and add it to your repository.
The last step is to try to make your program crash. (I had to set OVERFLOW to something like 5000 to get it to crash with a Segmentation fault.) Once
you’ve found a value for OVERFLOW that produces a Segmentation fault, run the program in gdb without setting a breakpoint so that it runs
automatically until the crash. Then use the backtrace command and the print command to investigate the value for i. Try backtrace full for even
more helpful information. You don’t need to record what you’re doing on this step. We just want you to see the backtrace command.
```
# Submitting Your Work
```
Make sure that gdb_example.txt is added to the Lab6 directory. Remember to add, commit and push all changes to copy.c and gdb_example.txt. Do
not commit any executables or any other additional files.
We will be auto-testing your solution to copy.c so you must not change the signature. We will not be auto-grading your scripts but reading them. So
if you have extra steps during your debugging, this is fine and you don’t need to stress about the format of the output. We aren’t expecting that
every student’s gdb_example.txt will be the same.
```
<file_sep>/lab4/README.md
3/21/2021 Lab 4
https://q.utoronto.ca/courses/68725/assignments/1 13158 1 / 2
# Lab 4
```
Due Feb 1, 2019 by 6:30pm Points 1
```
# Lab 4: Strings
```
Due date : Friday 1 February before 6:30pm.
```
# Introduction
```
The purpose of this lab is to give you some practice working with strings in C.
Complete each of the following programs in your lab4 repository folder according to the comments in each file. (Do a pull to download the starter
code to your computer.)
The suggested order for writing these programs is:
compare.c
truncate.c
strip.c
greeting.c
We have provided a Makefile for your convenience. You do not need to change it. If you run the make clean command when you don’t have all the
executables built, it will report an error. That is not a problem.
```
# Submission
```
Remember to commit and push all changes to these files before the deadline. Do not commit any executables or any other files.
```
- 3/21/2021 Lab
- https://q.utoronto.ca/courses/68725/assignments/1 13158 2 /
<file_sep>/a3/helper.c
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include "helper.h"
int get_file_size(char *filename) {
struct stat sbuf;
if ((stat(filename, &sbuf)) == -1) {
perror("stat");
exit(1);
}
return sbuf.st_size;
}
/* A comparison function to use for qsort */
int compare_freq(const void *rec1, const void *rec2) {
struct rec *r1 = (struct rec *) rec1;
struct rec *r2 = (struct rec *) rec2;
if (r1->freq == r2->freq) {
return 0;
} else if (r1->freq > r2->freq) {
return 1;
} else {
return -1;
}
}
<file_sep>/lab1/README.md
# Lab 1
**Due** Jan 11, 2019 by 6:30pm **Points** 1
# Lab 1: Introduction to the Unix Shell and C Programs
**Due date** : Friday 11 January before 6:30pm. Submissions made after the deadline will not be accepted.
# Introduction
The purpose of this lab is to practice using a few different shell commands to navigate through the file system, review git, and compile and run
simple C programs.
**Before starting this lab, we strongly recommend you complete the following sections on the PCRS
(https://pcrs.teach.cs.toronto.edu/csc209-2019-01) :**
```
C Language Basics -> DISCOVER: Types, Variables and Assignment Statements (video 1)
C Language Basics -> DISCOVER: Input, Output and Compiling (all videos)
```
You'll find the other videos in the "C Language Basics" part useful as a reference as you start working with C.
You should also have your computing environment set up (see the Software Setup page on Quercus) before starting this lab.
# 0. MarkUs, git, and git hooks
To start, login to MarkUs and navigate to the lab1 assignment. You'll find your repository URL to clone. _Even if you know your MarkUs repo URL,
it's important to visit the page first!_ This triggers the starter code for this lab to be committed to your repository.
Then, open a terminal on your computer and do a git pull in your CSC 209 MarkUs repository. You should see a new folder called lab1 with some
starter code inside. Make sure to do all your work on this lab in that folder.
You should also see a folder called markus-hooks. This semester, we are using a tool to help you make sure you're using git correctly with MarkUs. A
_git hook_ is a program that runs at a specific time in the git workflow to perform specific checks about the action being run. In this course, you'll be
using a _pre-commit hook_ to perform two checks every time you commit changes:
```
You may not add, delete, or modify top-level files or directories in your repository. Instead, all of your work should be done in assignment-specific
subdirectories, like lab1.
When an assignment has required files, you'll receive a warning message if your repo is missing some of these files. If the assignment restricts
your submission to only those required files, you won't be able to commit any other files inside that assignment's subdirectory.
```
Because these checks are also made by the MarkUs server when you push your code, your submission may not be accepted (the push will fail) if
your changes fail to satisfy the above conditions. **You can set up git hooks on your computer, so that you will be prevented from committing
changes that will violate the checks:**
```
1. OSX and Linux users only : open the file markus-hooks/pre-commit. You'll need to modify the command inside the file to use python3 (or
python3.6, depending on your setup) rather than just plain python, which likely refers to a Python 2 interpreter.
2. In your new cloned repository, copy the file markus-hooks/pre-commit into .git/hooks:
```
```
$ cp markus-hooks/pre-commit .git/hooks
```
```
Note the period at the start of .git; this is a hidden folder , and may or may not show up in a graphical file explorer, depending on your settings.
Running the above command in a terminal is the safest approach.
3. Check your work: run ls .git/hooks. One of the files listed should be pre-commit.
```
# 1. Basic utilities
Your first task is to inspect the contents of the lab1 folder. In the command line, use the ls command to inspect the contents of this folder. Use the
**man page for ls (http://man7.org/linux/man-pages/man1/ls.1.html)** , which we encourage you to explore the different options you can pass to ls
as command-line arguments to vary its behaviour. Note that you can pass multiple command-line arguments to ls.
Play around with these options now, and see if you can do each of the following: (Note that these commands will show you both files and
directories.)
```
1. Use -l to show metadata about each file in the current working directory.
2. Show the same metadata about each file as -l, except do not show the owner or group of the file.
3. Show only the filename and size of each file, one per line.
```
```
4. Show all files in the current working directory including the hidden files, which are files that start with a "."
```
# 2. Compiling and running C programs
You should see a bunch of different C source code files being listed by ls. For each one, do the following:
```
1. Compile it by running the command gcc -Wall -std=gnu99 -g <filename>. The arguments -Wall, -std=gnu99, and -g are the standard compiler
flags we'll be using in this course -- more about these later.
2. Run it according to its usage. Note that some of the executables take no command-line arguments, some require at least one command-line
argument of a certain form, and some will read in keyboard input. Try running each program and read the code to learn what each program
does!
```
# 3. A simple script
Executing commands one at a time in the shell is not scalable: often we have a set of commands we want to execute together repeatedly. We can
do so by writing a _shell script_ , which is a program written in a shell programming language like bash. We'll return to shell programming at the end of
this course, but for now, you'll write the simplest type of shell program: a list of commands.
To do this, create a new file in your lab1 directory called compile_all.sh; you can do this using any text editor you like. The first line of the file should
be the following:
```
#!/usr/bin/env bash
```
This line is called a **shebang (https://en.wikipedia.org/wiki/Shebang_%28Unix%29)** line, and is used to tell the operating system to interpret the
contents of the file as a shell program.
In this file, write one line for each compilation command you ran in Part 2. **If you are on Windows, you need to ensure your text editor is using
Unix-style line endings (aka "LF" or "\n") for this file.**
Then in the command line, run your script just as you would any other executable:
```
$ ./compile_all.sh
```
This should fail! The operating system will not run this program because the file is not executable. On Unix the permission settings of the file
determine whether a file is executable.
To change the permissions we will use the program chmod:
```
$ chmod a+x compile_all.sh
```
You can read the man page (man chmod) to see what arguments chmod accepts. In this case, the 'a' means that we want to change the permissions
for all users, the '+' means that we are adding permissions, and the 'x' means the executable permissions.
Now try running the shell script again.
If you inspect the contents of your folder using ls -l, you should see that the compilation has been successful and an executable has been
produced. Unfortunately, there's a problem: because gcc uses the default executable name a.out for the executable, each compilation command
in your script overwrites the result of the previous step. To fix this problem, modify your script by using the -o <out_name> gcc flag to produce
executables whose names match the C source files, without the extension.
For example, use the command
```
gcc -Wall -std=gnu99 -g -o hello hello.c
```
to compile hello.c into an executable named hello.
Then when you re-run your script, you should be able to see the resulting executables all created.
**Note** : this compilation script is a poor way to automate the compilation of multiple C programs in practice. Later in the term, we'll learn about the
Unix software tool make, which is the industry standard for managing compilation.
# 4. Redirection, pipes, and more Unix utilities
Now that we have some programs, your final task will be to review how input and output redirection work, and review some basic shell utilities.
Create a second shell script called my_commands.sh that contains commands that perform each of the following tasks (each of the following should be
done in just a single line, and be performed in order):
```
1. Run echo_arg with the command-line argument csc 209 and redirect the output to the file echo_out.txt.
2. Run echo_stdin with its standard input redirected from the file echo_stdin.c.
3. Use a combination of count and the Unix utility program wc (https://linux.die.net/man/1/wc) to determine the total number of digits in the
decimal representations of the numbers from 0 to 209, inclusive.
```
```
4. Use a combination of echo_stdin and ls (http://man7.org/linux/man-pages/man1/ls.1.html) to print out the name of the largest file in the current
directory. You can assume the largest file has a name with fewer than 30 characters.
```
# Submission
Use git to submit your final compile_all.sh and my_commands.sh -- make sure they're inside your lab1 folder and named exactly as described in this
handout, as that's where our test scripts will be looking for them.
You do _not_ need to submit anything for Sections 1 or 2.
**IMPORTANT** : make sure to review how to use git to submit your work to the MarkUs server; in particular, you need to run git push, not just git
commit and git add. Watch carefully for error messages, since committing non-required files may cause the push to fail.
<file_sep>/a4/wordsrv.c
// NOTE: View code with indentation settings such that a tab is 4 spaces and an indent is 4 spaces.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
#include "socket.h"
#include "gameplay.h"
#ifndef PORT
#define PORT 54623
#endif
#define MAX_QUEUE 5
int find_network_newline(const char *buf, int n);
void add_player(struct client **top, int fd, struct in_addr addr);
void remove_player(struct client **top, int fd, struct game_state *game);
int safe_write(struct client **top, struct client *p, char *msg, struct game_state *game);
void add_to_game(struct client **new_players_adr, struct client *p, struct game_state *game);
void broadcast(struct game_state *game, char *outbuf);
void announce_turn(struct game_state *game);
void announce_winner(struct game_state *game, struct client *winner);
void advance_turn(struct game_state *game);
/* Send the message in outbuf to all clients */
/* The set of socket descriptors for select to monitor.
* This is a global variable because we need to remove socket descriptors
* from allset when a write to a socket fails.
*/
fd_set allset;
int main(int argc, char **argv) {
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if(sigaction(SIGPIPE, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
int clientfd, maxfd, nready;
struct client *p;
struct sockaddr_in q;
fd_set rset;
if(argc != 2){
fprintf(stderr,"Usage: %s <dictionary filename>\n", argv[0]);
exit(1);
}
// Create and initialize the game state
struct game_state game;
srandom((unsigned int)time(NULL));
// Set up the file pointer outside of init_game because we want to
// just rewind the file when we need to pick a new word.
game.dict.fp = NULL;
game.dict.size = get_file_length(argv[1]);
init_game(&game, argv[1]);
// head and has_next_turn also don't change when a subsequent game is
// started so we initialize them here.
game.head = NULL;
game.has_next_turn = NULL;
/* A list of client who have not yet entered their name. This list is
* kept separate from the list of active players in the game, because
* until the new playrs have entered a name, they should not have a turn
* or receive broadcast messages. In other words, they can't play until
* they have a name.
*/
struct client *new_players = NULL;
struct sockaddr_in *server = init_server_addr(PORT);
int listenfd = set_up_server_socket(server, MAX_QUEUE);
// Initialize allset and add listenfd to the
// set of file descriptors passed into select.
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
// maxfd identifies how far into the set to search
maxfd = listenfd;
while (1) {
// Make a copy of allset before we pass it into select.
rset = allset; // read set
nready = select(maxfd + 1, &rset, NULL, NULL, NULL); // Blocks until a fd in rset has data or is closed
if (nready == -1) {
perror("select");
continue;
}
if (FD_ISSET(listenfd, &rset)){
printf("A new client is connecting\n");
clientfd = accept_connection(listenfd);
FD_SET(clientfd, &allset);
if (clientfd > maxfd) {
maxfd = clientfd;
}
printf("Connection from %s\n", inet_ntoa(q.sin_addr)); // ignore the q (i think)
add_player(&new_players, clientfd, q.sin_addr); // add newly connected client to new_players
char *greeting = WELCOME_MSG;
if (write(clientfd, greeting, strlen(greeting)) == -1) {
fprintf(stderr, "Write to client %s failed\n", inet_ntoa(q.sin_addr));
remove_player(&new_players, clientfd, NULL);
};
}
/* Check which other socket descriptors have something ready to read.
* The reason we iterate over the rset descriptors at the top level and
* search through the two lists of clients each time is that it is
* possible that a client will be removed in the middle of one of the
* operations. This is also why we call break after handling the input.
* If a client has been removed the loop variables may not longer be
* valid.
*/
int cur_fd;
for(cur_fd = 0; cur_fd <= maxfd; cur_fd++) {
if(FD_ISSET(cur_fd, &rset)) { // There are things to read from cur_fd.
// Check if this socket descriptor is an active player.
for(p = game.head; p != NULL; p = p->next) {
if(cur_fd == p->fd) {
// Handle input from an active client.
int num_in_buf = p->in_ptr - p->inbuf;
int room_in_buf = MAX_BUF - 3 - num_in_buf; // -1 for \0 and -2 for \r\n
int num_read; // Number of bytes (and thus characters) read from cur_fd.
if ((num_read = read(cur_fd, p->in_ptr, room_in_buf)) <= 0) {
if (num_read == 0) { // For sockets, read performs like recv w/ no flags. 0 means client dropped out.
printf("[%d] read 0 bytes.\n", cur_fd);
remove_player(&(game.head), cur_fd, &game);
break;
}
perror("read");
exit(1);
}
// Client still connected if we get here.
printf("[%d] read %d bytes.\n", cur_fd, num_read);
// Update values.
p->in_ptr += num_read;
num_in_buf += num_read;
room_in_buf -= num_read;
// Check if partial read.
int where; // The index after the \n in p->inbuf, if it exists.
if ((where = find_network_newline(p->inbuf, num_in_buf)) == -1) { // No \r\n means only partial read.
if (room_in_buf == 0) { // Reached max length and no \r\n yet, so input is invalid.
// (we are supposed to assume this never happens but we'll partially handle it)
char msg[] = "Your input was too long! Weird stuff might happen now.\r\n";
if (safe_write(&(game.head), p, msg, &game) != -1) { // Player still connected, can reference p.
p->in_ptr = p->inbuf;
}
}
break;
}
// We have a full line if we get here.
(p->inbuf)[where-2] = '\0'; // Cut out network newline and null terminate.
printf("[%d] found newline %s.\n", cur_fd, p->inbuf);
// Check if it's this player's turn.
if (p != game.has_next_turn) {
printf("Player %s tried to guess out of turn.\n", p->name);
char msg[] = "It is not your turn to guess.\r\n";
if (safe_write(&(game.head), p, msg, &game) != -1) { // Player still connected, can reference p.
p->in_ptr = p->inbuf;
}
break;
}
// It's this player's turn if we get here.
// Check if the guess is valid
char p_guess = (p->inbuf)[0];
// Check client guessed a single lowercase letter that is not already guessed. Makes use of short circuiting.
if (where != 3 || p_guess < 'a' || p_guess > 'z' || game.letters_guessed[p_guess - 'a'] == 1) {
printf("%s's guess was invalid.\n", p->name);
char msg[] = "Invalid guess. Please guess again.\r\n";
if (safe_write(&(game.head), p, msg, &game) != -1) { // player still connected
p->in_ptr = p->inbuf;
}
break;
}
// Guess is valid if we get here.
// Update letters_guessed, reset in_ptr and save current client name in case they disconnect.
game.letters_guessed[p_guess - 'a'] = 1;
p->in_ptr = p->inbuf;
char p_name[MAX_NAME];
strcpy(p_name, p->name); // strcpy safe since p->name null terminated and p_name big enough.
// Check if guess in word and update game.guess accordingly.
char guess_in_word = 0;
char solved = 1;
char letter;
int j = 0;
while ((letter = (game.word)[j]) != '\0') {
if (letter == p_guess) {
(game.guess)[j] = letter;
guess_in_word = 1;
} else if ((game.guess)[j] == '-') { // Still an unguessed letter so game isn't solved.
solved = 0;
}
j++;
}
// Decide what to do depending on if guess was in the word and if the game is over.
if (guess_in_word) {
if (solved) { // Game solved, start a new game.
announce_winner(&game, p);
init_game(&game, argv[1]);
} else { // We announce the guess iff game doesn't end.
char msg[MAX_MSG];
sprintf(msg, "%s guesses: %c\r\n", p_name, p_guess); // null terminates msg
broadcast(&game, msg);
}
} else { // Guess wasn't in the word, advance the turn.
printf("Letter %c is not in the word.\n", p_guess);
char msg[MAX_MSG];
sprintf(msg, "%c is not in the word\r\n", p_guess);
advance_turn(&game); // Must do before safe_write because safe_write could destroy client pointed to by p.
safe_write(&(game.head), p, msg, &game);
if (game.guesses_left == 0) { // Game over, start a new game.
printf("Game Over\nNew Game\n");
sprintf(msg, "No more guesses. The word was %s.\r\n\r\nLet's start a new game.\r\n", game.word);
broadcast(&game, msg);
init_game(&game, argv[1]);
} else { // We announce the guess iff game doesn't end.
sprintf(msg, "%s guesses: %c\r\n", p_name, p_guess); // null terminates msg
broadcast(&game, msg);
}
}
// Broadcast gurrent game status and announce whos turn it is.
char msg[MAX_MSG];
status_message(msg, &game);
broadcast(&game, msg);
announce_turn(&game);
break;
}
}
// Check if any new players are entering their names
for(p = new_players; p != NULL; p = p->next) {
if(cur_fd == p->fd) {
// Handle input from an new client who has not entered an acceptable name.
// (Piazza says to assume name entered will not exceed MAX_NAME-1 characters)
int num_in_buf = p->in_ptr - p->inbuf; // Number of bytes/characters in inbuf
int room_in_buf = MAX_NAME + 1 - num_in_buf; // Space available in inbuf.
// Name's at most MAX_NAME-1 chars. (-1 for \0).
// We +2 for \r\n (not part of name).
int num_read; // Number of bytes (and characters) read.
if ((num_read = read(cur_fd, p->in_ptr, room_in_buf)) <= 0) {
if (num_read == 0) { // For sockets, read performs like recv w/ no flags. 0 means client dropped out.
printf("[%d] read 0 bytes.\n", cur_fd);
remove_player(&new_players, cur_fd, NULL);
break;
}
perror("read");
exit(1);
}
// Client still connected if we get here.
printf("[%d] read %d bytes.\n", cur_fd, num_read);
// Update values.
p->in_ptr += num_read;
num_in_buf += num_read;
room_in_buf -= num_read;
// Check if partial read.
int where; // index after network newline in p->inbuf
if ((where = find_network_newline(p->inbuf, num_in_buf)) == -1) { // No \r\n means only partial read.
if (room_in_buf == 0) { // Reached max name length and no \r\n yet, so name is invalid.
// (we are supposed to assume this never happens but we'll partially handle it)
char msg[] = "Your name was too long! It might look weird now.\r\n";
if (safe_write(&new_players, p, msg, NULL) != -1) { // Client is still connected.
p->in_ptr = p->inbuf;
}
}
break;
}
// We have a full line if we get here.
(p->inbuf)[where-2] = '\0'; // Cut out network newline and null terminate.
printf("[%d] found newline %s.\n", cur_fd, p->inbuf);
// Check if name empty.
if (where-2 == 0) { // Only \r\n in inbuf, so empty name.
printf("[%d] entered empty name.\n", cur_fd);
char msg[] = "Please enter a valid name.\r\n";
if (safe_write(&new_players, p, msg, NULL) != -1) { // Client still connected.
p->in_ptr = p->inbuf; // Reset pointer to beginning.
}
break;
}
// Check if name already in use by iterating through active players in game.head.
char name_in_use = 0;
for (struct client *player = game.head; player != NULL; player = player->next) {
if (strlen(player->name) == strlen(p->inbuf) && strcmp(player->name, p->inbuf) == 0) {
// strcmp/strlen safe since both null terminated.
printf("[%d] name \"%s\" was already taken.\n", cur_fd, player->name);
char msg[] = "Sorry, that name is taken! Please enter a new name.\r\n";
name_in_use = 1;
p->in_ptr = p->inbuf;
safe_write(&new_players, p, msg, NULL);
break;
}
}
if (name_in_use) {
break;
}
// Name is valid so add client to game.head and remove from new_players.
add_to_game(&new_players, p, &game);
break;
}
}
}
}
}
return 0;
}
/* Move the has_next_turn pointer to the next active client and decrement number of guesses.
* Assume game->has_next_turn not NULL.
*/
void advance_turn(struct game_state *game) {
(game->guesses_left)--;
game->has_next_turn = (game->has_next_turn)->next;
if (game->has_next_turn == NULL) {
game->has_next_turn = game->head;
}
}
/* Add a client to the head of the linked list */
void add_player(struct client **top, int fd, struct in_addr addr) {
// top is the address of a linked list. That address is in the main stackframe.
struct client *p = malloc(sizeof(struct client));
if (!p) {
perror("malloc");
exit(1);
}
printf("Adding client %s\n", inet_ntoa(addr));
p->fd = fd;
p->ipaddr = addr;
p->name[0] = '\0';
p->in_ptr = p->inbuf;
p->inbuf[0] = '\0';
p->next = *top;
*top = p;
}
/* Removes client from the linked list pointed to by top and closes its socket (fd).
* Also removes socket descriptor from allset. If game is provided, will handle case
* where it is the client's turn.
*/
void remove_player(struct client **top, int fd, struct game_state *game) {
struct client **p;
for (p = top; *p && (*p)->fd != fd; p = &(*p)->next);
/* My personal notes for future reference, no need for anyone to read:
-------------------------------------------------------------------
top is the address of a linked list. That address is in the main stackframe.
*top is the address (A) of a struct client (head of linked list), which is a heap
address. Of course, *top is the value at the main stackframe address top.
(*top)->next = ((A)->next) := (B) is the address of another struct client, which
is a heap address. The address of that address &(B) is just
&((A)->next) = &((*(A)).next), which is the address of the .next attribute of a
client *(A). This is just an offset of the address of that client (A), so it's
stored on the heap (since (A) is on the heap and structs are stored contiguously).
KEY: Therefore, p = &(*p)->next is a heap address, and is the address of the
.next attribute of the client *preceeding* the client we are deleting. So, (*p) is
a pointer to the struct we want to delete. At bottom of the if-statement, free(*p)
frees the struct we want to remove. t holds the heap address of the client after the
client we are removing. So, when we do (*p) = t, we are saying "make the value of the
.next attribute of the client preceeding the one we want to remove, equal to the heap
address of the client after the one we want to remove." This cuts out the one want to
remove, as required.
*/
// Now, p points to (1) top, or (2) a pointer to another client
// This avoids a special case for removing the head of the list.
if (*p) {
int has_next_fd; // The file diescriptor of the current player, only used if game != NULL.
char p_name[MAX_NAME];
if (game) {
has_next_fd = (game->has_next_turn)->fd;
strcpy(p_name, (*p)->name); // Safe since p_name big enough and name is null terminated.
}
struct client *t = (*p)->next;
printf("Removing client %d %s\n", fd, inet_ntoa((*p)->ipaddr));
FD_CLR((*p)->fd, &allset);
close((*p)->fd);
free(*p);
*p = t;
if (game) {
if (has_next_fd == fd) { // It was the client we removed's turn.
if (t == NULL) { // The client we removed was at the end of top.
game->has_next_turn = game->head;
} else {
game->has_next_turn = t;
}
}
// Inform other players that client was removed.
char msg[MAX_MSG];
sprintf(msg, "Goodbye %s\r\n", p_name);
broadcast(game, msg);
if (game->has_next_turn != NULL) {
announce_turn(game);
}
}
} else {
fprintf(stderr, "Trying to remove fd %d, but I don't know about it\n", fd);
}
}
// Write msg to client pointed to by p. If client has disconnected remove them from top. game is
// included exclusively for the remove_player call. Assume msg is null-terminated.
int safe_write(struct client **top, struct client *p, char *msg, struct game_state* game) {
int n;
if ((n = write(p->fd, msg, strlen(msg))) != strlen(msg)) { // Piazza says assume socket closed
remove_player(top, p->fd, game);
n = -1;
}
return n;
}
/* Announce to all clients in game.head except has_next_turn whos turn it is.
* Prompt has_next_turn for input. Assumes has_next_turn != NULL.
*/
void announce_turn(struct game_state *game) {
struct client *p = game->head;
char msg[MAX_MSG];
sprintf(msg, "It's %s's turn.\r\n", (game->has_next_turn)->name);
printf("%s", msg);
while (p != NULL) {
struct client *temp = p->next; // Save next client in case safe_write deallocates p.
if (p != game->has_next_turn) {
safe_write(&(game->head), p, msg, game);
}
p = temp;
}
safe_write(&(game->head), game->has_next_turn, "Your guess?\r\n", game);
}
/* Announce the winner to all players in game.head. */
void announce_winner(struct game_state *game, struct client *winner) {
printf("Game over. %s won!\n", winner->name);
char msg[MAX_MSG] ;
sprintf(msg, "The word was %s.\r\nGame Over! %s Won!\r\n\r\nLet's start a new game.\r\n", game->word, winner->name);
struct client *p = game->head;
// Iterate through clients except winner and write msg.
while (p != NULL) {
struct client *temp = p->next; // Do first in case we remove p
if (p != winner) {
safe_write(&(game->head), p, msg, game);
}
p = temp;
}
// Write special message to winner.
sprintf(msg, "The word was %s.\r\nGame Over! You Win!\r\n\r\nLet's start a new game.\r\n", game->word);
safe_write(&(game->head), winner, msg, game);
}
/*
* Search the first n characters of buf for a network newline (\r\n).
* Return one plus the index of the '\n' of the first network newline,
* or -1 if no network newline is found. Don't assume buf is null-terminated.
*/
int find_network_newline(const char *buf, int n) {
for (int i = 0; i < n - 1; i++) {
if (buf[i] == '\r' && buf[i+1] == '\n') {
return i + 2;
}
}
return -1;
}
/* Write outbuf to all clients in game.head. Assume outbuf null is terminated. */
void broadcast(struct game_state *game, char *outbuf) {
struct client *p = game->head;
while (p != NULL) {
struct client *temp = p->next; // Do first in case we remove p
safe_write(&(game->head), p, outbuf, game);
p = temp;
}
}
/* Add client p to game.head and remove it from new_players which is pointed to by new_players_adr. */
void add_to_game(struct client **new_players_adr, struct client *p, struct game_state *game) {
// Add player to game.head
add_player(&(game->head), p->fd, p->ipaddr);
strcpy((game->head)->name, p->inbuf); // inbuf null terminated, has length at most MAX_NAME (with \0), so strcpy safe.
if (game->has_next_turn == NULL) { // First player in game.
game->has_next_turn = game->head;
}
// Remove p from new_players
struct client **player;
for (player = new_players_adr; *player && (*player)->fd != p->fd; player = &(*player)->next);
if (*player) {
struct client *t = (*player)->next;
free(*player);
*player = t;
} else {
fprintf(stderr, "Trying to remove fd %d from new_players, but I don't know about it\n",
p->fd);
}
// Save game->head for comparison later.
struct client *temp = game->head;
// Notify active players of new joiner.
char msg[MAX_MSG];
sprintf(msg, "%s has just joined.\r\n", (game->head)->name); // null terminates msg
broadcast(game, msg);
// If game->head disconnected then broadcast would have changed it. Make sure still the same.
if (temp != game->head) {
return;
}
// Show new player the game state.
char status[MAX_MSG];
status_message(status, game); // Null terminated
if (safe_write(&(game->head), game->head, status, game) == -1) { // Client disconnected.
return;
}
printf("%s has just joined.\n", (game->head)->name);
announce_turn(game);
}
<file_sep>/a3/psort.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "helper.h"
#include <sys/wait.h>
// void read_and_print(FILE* infp) {
// struct rec record;
// rewind(infp);
// while(fread(&record, sizeof(struct rec), 1, infp) > 0) {
// printf("%s-%d\n",record.word, record.freq);
// }
// printf("done\n");
// }
int main(int argc, char *argv[]) {
if (argc != 7) {
fprintf(stderr, "Usage: psort -n <number of processes> -f <inputfile> -o <outputfile>\n");
exit(1);
}
int num_processes;
char *in_file, *out_file;
char ch;
while ((ch = getopt(argc, argv, "n:f:o:")) != -1) {
switch(ch) {
case 'n':
num_processes = atoi(optarg);
break;
case 'f':
in_file = optarg;
break;
case 'o':
out_file = optarg;
break;
default:
fprintf(stderr, "Usage: psort -n <number of processes> -f <inputfile> -o <outputfile>\n");
exit(1);
}
}
// get file size so each child doesn't need to calculate
FILE *infp;
if ((infp = fopen(in_file, "r")) == NULL) {
fprintf(stderr, "Could not open %s\n", in_file);
exit(1);
}
int file_size = get_file_size(in_file);
if (fclose(infp) == EOF) {
perror("fclose in_file in parent");
exit(1);
}
// Exit if file is empty or user entered invalid number of processes
if (file_size == 0 || num_processes < 1) {
return 0;
}
int recs_in_file = file_size / sizeof(struct rec);
// Let M = the number of recs in the file, N = number of processes. We want to divide M into N groups as evenly as possible.
// Then M = floor(M/N)*N + (M%N). So, we make N groups of floor(M/N), then add 1 to (M%N) of them.
int base_sort_amt = recs_in_file / num_processes; // The minimum amount of recs a child will sort (integer division is floor division)
int num_sort_extra = recs_in_file % num_processes; // The number of children that will sort an extra rec.
if (recs_in_file < num_processes) { // no point in making processes that will sort nothing.
num_processes = recs_in_file;
}
int pipe_fd[num_processes][2];
for (int i = 0; i < num_processes; i++) {
// setup pipe
if ((pipe(pipe_fd[i])) == -1) {
perror("pipe");
exit(1);
}
// fork child process
int result = fork();
if (result < 0) {
perror("fork");
exit(1);
} else if (result == 0) { // in child
// close child read end, dont need it
if (close(pipe_fd[i][0]) == -1) {
perror("close reading end from inside child failed");
exit(1);
}
// Before we forked, the parent had open the reading ends to all previously forked children, now close them here.
for (int j = 0; j < i; j++) {
if (close(pipe_fd[j][0]) == -1) {
perror("close parent's leftover reading end of previously forked child failed");
exit(1);
}
}
if ((infp = fopen(in_file, "r")) == NULL) {
fprintf(stderr, "Could not open %s\n", in_file);
exit(1);
}
// calculate number of recs to sort and at which index of file to get them
int num_to_sort = base_sort_amt;
int start_sorting_i = base_sort_amt * i * sizeof(struct rec);
if (i < num_sort_extra) {
num_to_sort++;
start_sorting_i += i * sizeof(struct rec);
} else {
start_sorting_i += num_sort_extra * sizeof(struct rec);
}
fseek(infp, start_sorting_i, SEEK_SET);
struct rec *records = malloc(num_to_sort * sizeof(struct rec)); // stack memory is limited, so we allocate on the heap.
if (records == NULL) {
perror("malloc");
exit(1);
}
//read the recs we need to sort
int num_read;
int num_read_total = 0;
while ((num_read_total += (num_read = fread(records, sizeof(struct rec), num_to_sort, infp))) != num_to_sort) {
if (num_read == 0) {
perror("fread in child");
exit(1);
}
}
if (fclose(infp) == EOF) {
perror("fclose in_file in parent");
exit(1);
}
// sort recs
qsort(records, num_to_sort, sizeof(struct rec), compare_freq);
// write sorted recs to pipe in order
for (int j = 0; j < num_to_sort; j++) {
if (write(pipe_fd[i][1], &(records[j]), sizeof(struct rec)) != sizeof(struct rec)) {
perror("writing to pipe from child");
exit(1);
}
}
// Child done writing to the pipe so close it
if (close(pipe_fd[i][1]) == -1) {
perror("close pipe in child after writing");
exit(1);
}
// exit so child doesn't continue looping and doesn't have its own children
free(records);
exit(0);
} else { // parent
if (close(pipe_fd[i][1]) == -1) { // close write end of pipe in parent or else children will inherit the open fd
perror("close write end of pipe in parent");
exit(1);
}
}
}
// only parent will get here
FILE *outfp;
if ((outfp = fopen(out_file, "w")) == NULL) {
fprintf(stderr, "Could not open %s\n", out_file);
exit(1);
}
// We read from pipe before waiting, no problem because read() will block until child writes or closes its fd for write end of the pipe.
// If a child terminates abnormally, all its file descriptors are automatically closed so no worries about blocking on read forever.
// load 1 rec from each pipe into recs_to_compare
struct rec recs_to_compare[num_processes];
for (int i = 0; i < num_processes; i++) {
if (read(pipe_fd[i][0], &recs_to_compare[i], sizeof(struct rec)) == -1) { // read will not be 0 because every child sorted at least 1 rec
perror("read from pipe");
exit(1);
}
}
// write all recs to output file
// When we write recs_to_compare[k] to output and child has closed write end of pip_fd[k],
// this index is now invalid because there is nothing more to read there.
int smallest_valid_i = 0; // smallest index of recs_to_compare that is valid.
while (smallest_valid_i < num_processes) { // if false, then no valid indexes, so we have written all recs from in_file (or a child terminated abnormally)
int min_i = smallest_valid_i; // the index of the rec with minimum frequency
// find index of minimal rec
for (int i = smallest_valid_i+1; i < num_processes; i++) {
if ((recs_to_compare[i]).freq == -1) { // not valid
continue;
}
if ((recs_to_compare[i]).freq < (recs_to_compare[min_i]).freq) {
min_i = i;
}
}
// write minimal rec to output file
if (fwrite(&(recs_to_compare[min_i]), sizeof(struct rec), 1, outfp) != 1) {
perror("fwrite");
exit(1);
}
// read a new rec from the pipe corresponding to index of minimal rec we just wrote to file
int r = read(pipe_fd[min_i][0], &(recs_to_compare[min_i]), sizeof(struct rec));
if (r != sizeof(struct rec)) {
if (r == 0) { // we've read everything from the pipe, thus, min_i is now an invalid index
// close the pipe, nothing more to read here
if (close(pipe_fd[min_i][0]) == -1) {
perror("close pipe in parent after reading");
exit(1);
}
recs_to_compare[min_i].freq = -1; // legal frequencies are non-negative; this is a sentinal value indicating min_i is invalid.
if (min_i == smallest_valid_i) { // min_i is no longer valid so need to find next smallest valid index.
smallest_valid_i++;
while((smallest_valid_i < num_processes) && ((recs_to_compare[smallest_valid_i]).freq == -1)) { // makes use of short circuiting
smallest_valid_i++;
}
}
} else {
perror("read from pipe in parent");
exit(1);
}
}
}
if (fclose(outfp) == EOF) {
perror("fclose out_file");
exit(1);
}
// collect exit statuses of children
int status;
char abnormal_termination = 0;
for (int i = 0; i < num_processes; i++) {
if (wait(&status) == -1) {
fprintf(stderr, "wait\n");
}
if (!(WIFEXITED(status))) {
fprintf(stderr, "Child terminated abnormally\n");
abnormal_termination = 1;
}
}
if (abnormal_termination) {
exit(1);
}
// FILE *test = fopen(out_file, "r");
// read_and_print(test);
// fclose(test);
return 0;
}
<file_sep>/README.md
Labs and assignments from _Software Tools and Systems Programming_ course taken in Winter 2019
<file_sep>/a3/README.md
# Assignment 3: Processes and Pipes
**Due** Mar 18, 2019 by 4pm **Points** 10
# Introduction
The fork system call is often used to create multiple cooperating processes to solve a single problem. This is especially useful on a multiprocessor
where different processes can truly be run in parallel. In the best case, if we have N processes running in parallel and each process works on a
subset of the problem, then we can solve the problem in 1/N the time it takes to solve the problem using one processor.
If it were always that easy, we would all be writing and running parallel programs. It is rarely possible to divide up a problem into N independent
subsets. Usually, the results of each subset need to be combined in some way. There is also a difficult tradeoff to make between the benefits of
parallelism and the cost of starting up parallel processes and collecting results from different processes.
For this assignment, you will write a parallel sorting program using Unix processes (i.e., fork). We can hope to gain some benefit from using more
than one process even on a uniprocessor since we will be reading data from a file, so we might win by letting the scheduler overlap the computation
of one process with the file I/O of another process. We would hope to see a performance improvement if the program is run on a multiprocessor.
If we genuinely wanted to write a fast parallel sort program on a shared-memory system, we would use a thread package rather than multiple Unix
processes. Linux/Unix processes are costly to create, and the communication mechanisms between processes are also expensive. However, a
large part of the purpose of the assignment is to give you practice creating and using multiple processes, and it is also interesting to measure the
performance of this kind of program.
# Specifications
The data to be sorted is a list of records where a record contains a word and its frequency measure (see struct rec in helper.h). The records are
written to the file in sequence in binary format. This means that you can use fread to read one record at a time or multiple records in one fread
call.
You will write a C program called psort that takes 3 arguments:
```
the number of processes to create,
the name of the input file to sort, and
the name of the file to write the output to.
```
It will be called as shown below. You must use getopt to read in the command-line arguments. The command man 3 getopt will give you the correct
man page, which has a nice example that you can use as a template.
```
psort -n <number of processes> -f <inputfile> -o <outputfile>
```
If the correct number of command-line arguments and the correct options (-n, -f, and -o) are provided, you may assume that the values
corresponding with the options are valid. If the incorrect number of command-line arguments or incorrect options are provided, you must report that
using the following message and exit the program with an exit code of 1 (copy and paste this line of code to your program):
```
fprintf(stderr, "Usage: psort -n <number of processes> -f <inputfile> -o <outputfile>\n");
```
If <number of processes> is N, then your program will create N processes and divide up the file to be sorted into N chunks. Each process will read
1/N of the file and sort its chunk of the file according to frequency (from smallest to largest) in memory using the qsort library function. You should
divide up the words as evenly as possible. So if there are 3 processes and 5 records, the first two processes get 2 records each and the third gets 1
record.
The parent process will also set up a pipe between the parent and each of its children. When a child has finished sorting its chunk, it will write each
record in sorted order to the pipe. The parent will merge the data from each of the children by reading one record at a time from the pipes. The
parent will write the final sorted list to the output file. The output file will be in the same binary format as the input.
The psort program may print to stdout the time it took to run (see below for details). If it runs correctly, this will be the only output to stdout.
The parent must ensure that all of the children have terminated properly and the parent will print out an error message if any of the children have
terminated prematurely.
# Details
The first thing you should do is to write a small program that reads a binary file in the given format and prints its contents to standard output. This
will not only help you test your program, but your psort program will also need to be able to read the binary file, so it gives you the opportunity to
make sure you can do that part correctly. We will not be grading your program that displays a binary file.
The qsort function sorts an array in place. The final argument to qsort is a pointer to a comparison function. The comparison function will be called
by qsort with arguments that are elements of the array to be sorted. The comparison function is given in helper.c. Here is **a tutorial on using
qsort (http://www.anyexample.com/programming/c/qsort__sorting_array_of_strings__integers_and_structs.xml)**. The man page for qsort also has
an example.
Since you can compute that each child will sort a portion of the file from smallest to largest, it would make a lot of sense to write a function to
perform this task. Each child will open the file, use fseek to get to the correct location in the file, and begin reading at that point. The child can read
the data in one system call, use qsort to sort the data, and then will write one record at a time to the pipe connecting the child to the parent.
The parent process will need to implement a merge function that compares the current smallest value read from each child pipe, and writes the
record with the smallest frequency to the output file each time. The following diagram shows how merge might work with 4 child processes.
First, the parent reads one value from each of the child pipes. Since the smallest value is 3, the parent will write 3 to the output file, and will then
read from that child's pipe, loading 4 into the array. Now, 4 is the smallest value, so the parent will write 4 to the output file, and read from that
child's pipe, loading 10 into the array. Now, 5 is the smallest value, so the parent will write 5 to the output file, and read from that child's pipe,
loading 8 into the array. And so on...
The parent must use wait (rather than waitpid). If a child does not terminate normally for any reason, the following error message should be
printed, but this should not cause the program to exit. (Copy and past the line below into your program.)
```
fprintf(stderr, "Child terminated abnormally\n");
```
You must practice good system programming skills. Your program should not crash under any circumstance. This means that the return value from
all system calls must be checked, files and pipes must be closed when not needed, and all dynamically allocated memory must be freed before your
program terminates.
When working on the assignment, you should also be careful to clean up any processes left running. You can get a list of all of the processes you
have on a machine by running:
```
ps aux | grep <user name>
```
**Do not log out without checking for and cleaning up any processes left running.**
The starter code in your repository contains a sample input file: 8-words.b, and the 8-words.txt file used to generate it. We have also given you a
program called mkwords.c that can be used to generate more input files. Read the comments in the code to see how to run it. Note that you will need
to compile it as below to link in the math library:
```
gcc -Wall -g -std=gnu99 -o mkwords mkwords.c -lm
```
You will want to ensure that your program works with a relatively small data set before you begin experimenting with the large ones. You might want
to use parts of the dictionary.txt file from a2 as source of words. Remember to create the input files on teach.cs machines so that you don't need
to worry about line endings and other differences between files on different systems.
The starter code also includes helper.h and helper.c which define the struct rec and include two functions that you will find useful.
# Makefile
Create and submit a Makefile that compiles the program to produced the executable named psort. To build the executable, it may depend on
helper.h, helper.c, and psort.c. You may edit and add to those files, but do not add any additional files or change struct rec.
## Marking
We will use testing scripts to evaluate correctness. As a result, it's very important that your output matches the expected output precisely. Also, it is
not sufficient to produce the correct output -- following the algorithm specified is required.
For this and future assignments, your code may also be evaluated on:
```
Code style and design : At this point in your programming career you should be able to make good choices about code structure, use of helper
functions, variable names, comments, formatting, etc.
Memory management : your programs should not exhibit any memory leaks. This means freeing any memory allocated with malloc and realloc.
This is a very important marking criterion. Use valgrind to check your code.
Error-checking : library and system call functions (even malloc!) can fail. Be sure to check the return values of such functions, and terminate
your program if anything bad happens.
Warnings : your programs should not cause any warnings to be generated by gcc -Wall.
```
## Reminder
Your program must compile on teach.cs using gcc with the -Wall option and should not produce any error messages. Programs that do not
compile, will get 0. You can still get part marks by submitting something that doesn't completely work but does some of the job -- but it **must at least
compile** to get any marks at all. Also check that your output messages are **exactly** as specified in this handout.
# Submission
We will be looking for the following files in the a3 directory of your repository:
```
helper.c
helper.h
psort.c
Makefile
```
Do not commit .o files or executables to your repository.
# Timing Your Program (Optional)
This part is optional and not for any marks, so complete it only to satisfy your curiosity!
**Using gettimeofday** : You should read the man page for gettimeofday, but here is an example of how to use it, and how to compute the time between
two readings of gettimeofday
```
#include <sys/time.h>
struct timeval starttime, endtime;
double timediff;
if ((gettimeofday(&starttime, NULL)) == -1) {
perror("gettimeofday");
exit(1);
}
// code you want to time
if ((gettimeofday(&endtime, NULL)) == -1) {
perror("gettimeofday");
exit(1);
}
timediff = (endtime.tv_sec - starttime.tv_sec) +
(endtime.tv_usec - starttime.tv_usec) / 1000000.0;
fprintf(stdout, "%.4f\n", timediff);
```
The real question is how many processes should we use to get the best performance out of our program? To answer this question, you will need to
find out how long your program takes to run. Use gettimeofday to measure the time from the beginning of the program until the end, and print this
time to standard output. Now try running your program on different numbers of processes on different sized datasets.
Think about what the performance results mean. Would you expect the program to run faster with more than one process? Why or why not? Why
does the speedup eventually decrease below 1? How does the speedup differ between data sets? Why? Did the performance results surprise you?
If so, how?
<file_sep>/lab2/README.md
3/21/2021 Lab 2
https://q.utoronto.ca/courses/68725/assignments/1 13155 1 / 2
# Lab 2
```
Due Jan 18, 2019 by 6:30pm Points 1
```
# Lab 2: Pointers and Input
```
Due date : Friday 18 January before 6:30pm. Submissions made after the deadline will not be accepted.
```
# Introduction
```
The purpose of this lab is to practice writing C programs involving pointers and the scanf function.
To start, log in to MarkUs and navigate to the lab2 assignment. Like the previous lab, this triggers the starter code for this lab to be committed to
your repository. We've described each problem briefly below, but for more detail on the first two problems, read through the starter code. There is no
starter code for the final two problems.
```
# 1. invest.c
```
Your task is to implement a function invest that takes an amount of money and multiplies it by a given rate. It's your job to figure out the exact type
of this function's arguments, given the sample usage in the main function in the starter code.
```
# 2. score_card.c
```
Your task is to implement a function sum_card, which takes an array of pointers to integers, and returns the sum of the integers being pointed to.
```
# 3. phone.c
```
Your task is to write a small C program called phone.c that uses scanf to read two values from standard input. The first is a 10 character string and
the second is an integer. The program takes no command-line arguments.
If the integer is -1, the program prints the full string to stdout. If the integer is between 0 and 9 the program prints only the corresponding digit from
the string to stdout. In both of these cases the program returns 0.
If the integer is less than -1 or greater than 9, the program prints the message "ERROR" to stdout and returns 1.
We haven't learned about strings yet, but you will see that to hold a string of 10 characters, you actually need to allocate space for 11 characters.
The extra space is for a special character that indicates the end of the string. Use this line
```
```
char phone[11];
```
```
to declare the variable to hold the string. Other than this line, there is no starter code for this program.
```
# 4. phone_loop.c
```
Your task is to write a C program called phone_loop.c. This program will again read from standard input using scanf and take no command-line
arguments. Similar to phone.c, this program reads a 10-character string as the first input value but then it repeatedly reads integers until standard
input is closed.
After each integer the output produced is as before:
if the integer is -1, the full string is printed
if the integer is between 0 and 9, the individual character at that position is printed
if the integer is less than -1 or greater than 9, the message "ERROR" is printed (to stdout)
```
```
In each case the printing is followed by a newline character.
When the program finishes running, main returns with a 0 return code if there were no errors and with a 1 return code otherwise.
```
## How do you end standard input?
```
One way to run your program is to redirect the input to come from a file. Then it is clear when the file ends. But how do you close standard input,
when it is coming from the keyboard? You manually indicate the end of standard input from a keyboard by pressing Ctrl-D (on Unix) or Ctrl-Z (on
Windows) and enter.
```
# Submission
3/21/2021 Lab 2
https://q.utoronto.ca/courses/68725/assignments/1 13155 2 / 2
```
Use git to submit your final invest.c, score_card.c, phone.c and phone_loop.c -- make sure they're inside your lab2 folder and named exactly as
described in this handout, as that's where our test scripts will be looking for them. Do NOT add or commit executables to your repository. We will
build executables by compiling your code as part of testing it.
IMPORTANT : make sure to review how to use git to submit your work to the MarkUs server; in particular, you need to run git push, not just git
commit and git add.
```
<file_sep>/a2/CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(a2)
set(CMAKE_CXX_STANDARD 14)
include_directories(.)
add_executable(a2
dictionary.txt
family.c
family.h
Makefile
reading.c
reading.h
wheel.c)
<file_sep>/a4/README.md
# Assignment 4: A multi-player word game
**Due** Apr 4, 2019 by 4pm **Points** 10
# First task: Makefile
We have provided starter code for the Makefile. Completing it is your first task and the starter code will
not compile until you complete these tasks.
To avoid port conflicts when testing your programs on teach.cs, you will use PORT (see below) to specify
a port number. Select that number using the same algorithm we used for lab 10: take the last four digits
of your student number, and add a 5 in front. For example, if your student number is 1008123456, your
port would be 53456. Using this base port, you may add 1 to it as necessary in order to use new ports
(for example, the fictitious student here could also use 53457, 53458, 53459, 53460). Sometimes, when
you shutdown your server (e.g. to compile and run it again), the OS will not release the old port
immediately, so you may have to cycle through ports a bit.
```
In wordsrv.c, replace x with the port number on which the server will expect connections (this is the
port based on your student number):
```
```
#ifndef PORT
#define PORT y
#endif
```
```
Then, in Makefile, replace y with your student number port plus 1:
PORT= x;
```
Now, if you type make PORT=53456 the program will be compiled with PORT defined as 53456. If you type
just make, PORT will be set to y as defined in the makefile. Finally, if you use gcc directly and do not
use -D to supply a port number, it will still have the x value from your source code file. This method of
setting a port value will make it possible for us to test your code by compiling with our desired port
number. (Read the Makefile. It's also useful for you to know how to use -D to define macros at
command line.)
# Word guessing game server
For assignment four, you will write a word guessing game server. The game is similar to the game you
wrote in assignment two, but with some key differences. In particular, the server chooses the word
before the players start guessing and doesn't change the word during a round. The game is played by
one or more players who take turns guessing letters.
Players will connect using nc. When a new player connects, the server will send them "Welcome to our
word game. What is your name?". After they input an acceptable name that is not equal to any existing
player's name and is not the empty string, they are added to the game, and all active players (if any) are
alerted to the addition (e.g., "Karen has just joined.") If they input an unacceptable name, they should be
notified and asked again to enter their name.
With your server, players can join or leave the game at any time. A player leaves the game by
exiting/killing nc.
New players who have not yet entered their names are stored in a linked list, and each new player is
added to the front of the list (see add_player). Players in this list do not get turns, and do not receive any
messages about the status of the game.
When a player has entered their name, they are moved from the new players list to the head of the list of
active players that is stored in the game_state struct.
Adding a player to the active list in the game_state struct must not change whose turn it is, unless this is
the first player to join the game. When someone leaves, if it is their turn, the turn has to pass to the next
player in the list, not to the top of the list. When the last player leaves, the variable that stores the pointer
to the player with the next turn is set to NULL.
For each turn, or to newcomers moved to the active list, you display the game state in a simple text
format. The output should look something like this:
```
***************
Word to guess: --u--s
Guesses remaining: 3
Letters guessed:
u s z
***************
```
Then, prompt the player whose turn it is with the query "Your guess?", and tell everyone else (for
example) "It's Jen's turn."
The player is expected to type a single lowercase letter, followed by the enter (or return) key. Note that
because we are running nc with the -c or -C option it will send the network newline ('\r\n'). If the
user enters anything else, such as multiple characters or a character that is not a lowercase letter
between 'a' and 'z', the guess is invalid. You should tell the player this (the exact format of this
message is up to you) and ask them again for their guess. An invalid guess does not decrement the
number of guesses.
Once the player makes a valid guess, tell everyone what guess that player made. (The exact format of
this message is up to you.)
If the player guesses a letter that has not already been guessed and that letter is in the word, the player
gets to guess again. Prompt the player whose turn it is with the query "Your guess?", and once again tell
everyone else (for example) "It's Jen's turn."
The game ends in two situations. First, it ends when a player guesses the last hidden letter. Announce to
the player, for example, "Game over! You win!" and tell everyone else, for example, "Game over! Karen
won!" Second, the game ends when the players have zero guesses remaining. In that case, tell
everyone "No guesses left. Game over."
Once the game has ended (for either reason), it should restart with a new word to guess. The player
who was supposed to guess next, gets the first turn.
Be prepared for the possibility that the player drops the connection (disconnects) when it is their turn to
guess. Furthermore, you must notice user input or dropped connections even when it isn't that player's
turn. If the player types something other than a blank line when it is not their turn, tell them "It is not your
turn to guess." For a blank line, you can say "It is not your turn to guess" or you can ignore it, whichever
you prefer.
How does the server tell when a client has dropped a connection? When a client terminates, the socket
is closed. This means that when the server tries to write to the socket, the return value of write will
indicate that there was an error, and the socket is closed. Similarly, if the server tries to read from a
closed socket, the return value from the read call will indicate if the client end is closed.
As players connect, disconnect, enter their names, and make moves, the server should send to stdout
a brief statement of each activity. (Again the format of these activity statements is up to you.) Remember
to use the network newline in your network communication throughout, but not in messages printed on
stdout.
You are allowed to assume that the user does not "type ahead" -- if you receive multiple lines in a single
read(), for this assignment you do not need to do what is usually required in working with sockets of
storing the excess data for a future input.
However, you can't assume that you get the entire player name or guess in a single read(). For the
input of the player name or guess, if the data you read does not include a network newline, you must
loop to get the rest of the input.
# Sample Interactions
To help you better understand the game play, we provide three sets of sample interactions. The
messages displayed may vary, but behaviour of your program should be consistent with these
interactions.
Please note that these interactions do not cover all possible scenarios and your program must take other
situations into account. For example, the number of players can vary, and players can connect and
disconnect at any time, including when it is a player's turn.
In these interactions, our server logs show that we always read the word from index 0, since the
dictionary used contained only one word for demonstration purposes. With a larger dictionary, we'd
expect that index number to vary.
```
Interaction 1: game1_client_jen.txt (https://q.utoronto.ca/courses/68725/files/3161153/download?
wrap=1) (https://q.utoronto.ca/courses/68725/files/3161153/download?wrap=1) ,
game1_client_karen.txt (https://q.utoronto.ca/courses/68725/files/3161154/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161154/download?wrap=1) , game1_server.txt
(https://q.utoronto.ca/courses/68725/files/3161155/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161155/download?wrap=1)
player Jen connects, then enters name
player Karen connects, then enters name
players make guesses (some correct, some incorrect, one out of turn) until player Karen wins
a new game starts
player Jen disconnects
player Karen disconnects
server terminated
Interaction 2: game2_client_jared.txt (https://q.utoronto.ca/courses/68725/files/3161157/download?
wrap=1) (https://q.utoronto.ca/courses/68725/files/3161157/download?wrap=1) ,
game2_client_mark.txt (https://q.utoronto.ca/courses/68725/files/3161158/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161158/download?wrap=1) , game2_client_anisha.txt
(https://q.utoronto.ca/courses/68725/files/3161156/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161156/download?wrap=1) , game2_client_stathis.txt
(https://q.utoronto.ca/courses/68725/files/3161159/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161159/download?wrap=1) , game2_server.txt
(https://q.utoronto.ca/courses/68725/files/3161160/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161160/download?wrap=1)
player Jared connects, enters name and guesses
during Jared's turn, player Mark connects and enters name
during Jared's turn, player Anisha connects and enters name
when Jared's turn ends, player Anisha guesses; players Mark and Jared disconnect during
Anisha's turn
the game ends with no winner
a new game starts
player Anisha guesses once
player Anisha disconnects
player Stathis connects and enters name
server terminated
Interaction 3: game3_client_jingyi.txt (https://q.utoronto.ca/courses/68725/files/3161161/download?
wrap=1) (https://q.utoronto.ca/courses/68725/files/3161161/download?wrap=1) ,
game3_client_tudor.txt (https://q.utoronto.ca/courses/68725/files/3161163/download?wrap=1)
```
```
(https://q.utoronto.ca/courses/68725/files/3161163/download?wrap=1) , game3_server.txt
(https://q.utoronto.ca/courses/68725/files/3161164/download?wrap=1)
(https://q.utoronto.ca/courses/68725/files/3161164/download?wrap=1)
player <NAME> connects, but does not enter name yet
player Tudor connects, enters name
player Tudor guesses incorrectly; player Tudor's turn again
during player Tudor's turn, player <NAME> enters name
when player Tudor's turn ends, it becomes player Jing Yi's turn
server terminated
```
# Testing
To use nc, type nc -C hostname yyyyy (use lowercase -c on Mac), where hostname is the full name of the
machine on which your server is running, and yyyyy is the port on which your server is listening. If you
aren't sure which machine your server is running on, you can run hostname -f to find out. If you are sure
that the server and client are both on the same server, you can use localhost in place of the fully
specified host name.
To test if your partial reads work correctly, you can send a partial line (without the network newline) from
nc by typing Ctrl-D.
## Marking
The TAs will be reading the output of your program (rather than using a script to match it against
expected output). This means that your message do not need to exactly match the ones in this handout.
However, your messages will be read by a person, so you want to make your output meaningful and
readable.
Your code may be evaluated on:
```
Code style and design : At this point in your programming career you should be able to make good
choices about code structure, use of helper functions, variable names, comments, formatting, etc.
Memory management : your programs should not exhibit any memory leaks. Use valgrind to check
your code.
Error-checking : library and system call functions (even malloc!) can fail. Be sure to check the return
values of such functions, and terminate your program if anything bad happens.
Warnings : your programs should not cause any warnings to be generated by gcc -Wall.
```
## Reminder
Your program must compile on teach.cs using gcc with the -Wall option and should not produce any
error messages. Programs that do not compile, will get 0. You can still get part marks by submitting
something that doesn't completely work but does some of the job -- but it **must at least compile** to get
any marks at all. Also check that your output messages are **exactly** as specified in this handout.
# Submission
We will be looking for the following files in the a4 directory of your repository:
```
Makefile
wordsrv.c
socket.c
socket.h
gameplay.c
gameplay.h
```
No other files will be accepted. Do not commit .o files or executables to your repository.
<file_sep>/a3/helper.h
#ifndef _HELPER_H
#define _HELPER_H
#define SIZE 44
struct rec {
int freq;
char word[SIZE];
};
int get_file_size(char *filename);
int compare_freq(const void *rec1, const void *rec2);
#endif /* _HELPER_H */
<file_sep>/lab5/README.md
3/21/2021 Lab 5
https://q.utoronto.ca/courses/68725/assignments/1 13159 1 / 2
# Lab 5
```
Due Feb 8, 2019 by 6:30pm Points 1
```
# Lab 5: File I/O and Structs
```
Due date : Friday 8 February before 6:30pm.
```
# Introduction
```
The purpose of this lab is to give you some practice using structs and reading binary data from files. To get started, visit Lab5 in MarkUs to trigger
the creation of a Lab5 subdirectory containing the starter code in your repository.
We’ve provided the Makefile for this lab; you shouldn’t need to change it. Simply run make to compile the program.
```
## Introduction: Bitmap files
```
A 24-bit bitmap file is a simple image file format that consists of two main parts:
1. The file metadata.
2. The pixel array , storing numbers corresponding to the blue, green, and red colour values of each pixel in the image (as a number between 0 and
255 ).
(Note: the actual file format consists of an optional third section after the pixel array, but we’ll ignore that section for the purpose of this lab.)
At fixed locations in the file metadata, there are three important integers (each stored with exactly 4 bytes):
At byte offset 10-13, the offset in the bitmap file where the pixel array starts.
At byte offset 18-21, the width of the image, in pixels.
At byte offset 22-25, the height of the image, in pixels.
Suppose our bitmap image has height m and width n; we’ll always assume in this lab that the width n is a multiple of 4, which simplifies the byte
layout in the file a little. For this image, the pixel array stores exactly 3nm bytes, in the following way:
Each group of 3 bytes represents a single pixel, where the bytes store the blue, green, and red colour values of the pixel, in that order.
Pixels are grouped by row. For example, the first 3n bytes in the pixel array represent the pixels in the top-most row of the image.
That’s all you need for this lab, but if you’re curious about learning more about the bitmap file format, you can start here
(https://en.wikipedia.org/wiki/BMP_file_format).
```
## Task 1: Reading bitmap metadata
```
In the starter code, we have provided a main function in bitmap_printer.c that opens a bitmap file for processing, and a separate file bitmap.c that
implements the required functions for working with bitmaps.
Your first task is to use the description of the bitmap metadata to implement read_bitmap_metadata. Don’t just try to read in the entire bitmap file! Use
fseek to navigate to different byte locations so that you only read in the three required integers.
We’ve provided in the starter code two sample bitmap files you can use to test your work. It’s quite possible for you to go out and find your own
bitmap images, but beware that there are many variations of this file format, and we’re only covering the 24-bit version in this lab, so you might
need to convert new images to this format yourself (and crop to ensure the width is a multiple of 4).
```
## Task 2: Reading in pixels
```
Now, you’ll read in all of the pixels into memory, using a common pattern for storing a two-dimensional array on the heap. Read through the
comments in the starter code carefully to complete this part.
Note that because each pixel colour value (blue, green, or red) is stored in just one byte, the type we use is unsigned char, which is guaranteed to
represent the numbers 0-255.
```
## Task 3: Cleaning up
```
Don’t forget about tidying up the program’s resources! Add some code to the bottom of the main function in bitmap_printer.c to close the bitmap file
and free all of the program’s dynamically-allocated memory.
```
- 3/21/2021 Lab
- https://q.utoronto.ca/courses/68725/assignments/1 13159 2 /
<file_sep>/lab8/checkpasswd.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAXLINE 256
#define MAX_PASSWORD 10
#define SUCCESS "Password verified\n"
#define INVALID "Invalid password\n"
#define NO_USER "No such user\n"
int main(void) {
char user_id[MAXLINE];
char password[MAXLINE];
if(fgets(user_id, MAXLINE, stdin) == NULL) {
perror("fgets");
exit(1);
}
if(fgets(password, MAXLINE, stdin) == NULL) {
perror("fgets");
exit(1);
}
int fd[2];
if (pipe(fd) == -1) {
perror("pipe");
exit(1);
}
if (write(fd[1], user_id, MAX_PASSWORD) < 0) {
perror("write");
exit(1);
}
if (write(fd[1], password, MAX_PASSWORD) < 0) { // Why need MAX_PASSWORD bytes??? just always read and write same number of bytes
perror("write");
exit(1);
}
if (close(fd[1])) {// done writing
perror("close");
exit(1);
}
int n = fork();
if (n < 0) {
perror("fork");
exit(1);
}
if (dup2(fd[0], STDIN_FILENO) == -1) { // after fork so it happens in child too
perror("dup2");
exit(1);
}
if (n == 0) {
if (-1 == execl("./validate", "validate", (char *) NULL)) {
perror("execl");
exit(1);
}
}
// Will only execute in parent b/c exec takes over child process and will not continue here
if (close(fd[0])) { // ***THIS MUST HAPPEN AFTER dup2***
perror("close");
exit(1);
}
int status;
wait(&status);
if (WIFEXITED(status) != 0) { // Terminated normally
switch(WEXITSTATUS(status)) {
case 0:
printf(SUCCESS);
break;
case 2:
printf(INVALID);
break;
case 3:
printf(NO_USER);
break;
}
}
return 0;
}
<file_sep>/lab8/README.md
3/21/2021 Lab 8
https://q.utoronto.ca/courses/68725/assignments/1 13163 1 / 2
# Lab 8
```
Due Mar 8, 2019 by 6:30pm Points 1
```
# Lab 8: pipe, exec, dup
```
Due : Friday 8 March before 6:30pm
```
# Introduction
```
In an application that requires a user to login, the application must be able to read in a user id and password, and validate it to determine whether
the login is successful. One approach to validation is to hand the task off to a separate process.
In this lab, you are given a program that validates user id and passwords, and will apply what you’ve learned about processes and pipes to create a
program that runs this validation program in a child process and reports the result of the validation.
```
# 1. Understanding the validate program
```
You can find the code for the validation program used for this lab in validate.c. The validate program reads the user id and password from stdin,
because if they were given as command-line arguments they would be visible to programs such as ps that inspect the state of the system. You are
also given a sample file containing user ids and password combinations, which is used by validate.
After reading the comments at the top of validate.c, you will want to compile it and try running validate directly first.
How many bytes does validate expect to read in each read call? Does it require the input to be null-terminated? What happens in each case?
Notice that this program doesn’t print any output; the only information it provides comes in the exit code of the program.
Use the shell variable $? to refer to the exit code of the last process run (e.g., by running echo $?).
NOTE: You may not change the validate program.
```
# 2. Create the main program
```
Your task is to complete checkpasswd.c, which reads a user id and password from stdin, creates a new process to run the validate program, sends
it the user id and password, and prints a message to stdout reporting whether the validation is successful.
Your program should use the exit status of the validate program to determine which of the three following messages to print:
“Password verified” if the user id and password match.
“Invalid password” if the user id exists, but the password does not match.
“No such user” if the user id is not recognized
The exact messages are given in the starter code as defined constants.
Note that in the given password file pass.txt, the “killerwhales:swim” has a userid that is too large, and “monkeys:eat<PASSWORD>” has a password that
is too long. The examples are expected to fail, but the other cases should work correctly.
You will find the following system calls useful: fork, exec, pipe, dup2, write, wait (along with WIFEXITED, WEXITSTATUS). You may not use popen or
pclose in your solution.
Important: execl arguments
Week 7 Video 6 “Running Different Programs” demonstrates a version of execl that takes only two arguments. The signature for execl is:
int execl(const char *path, const char *arg0, ... /*, (char *)NULL */);
In the video, the execl call only passed two arguments (execl("./hello", NULL)), but that shortcut doesn’t work on teach.cs. Instead, you need to
pass the middle argument (respresenting argv[0]) explicitly: execl("./hello", "hello", NULL).
Let’s consider two more examples. If you want to call the executable ./giant with the arguments fee fi fo, you would do it like this:
execl("./giant", "giant", "fee", "fi", "fo", NULL); If you want to call ./giant with no arguments you would call it like this: execl("./giant", "giant",
NULL);
```
# Submission
```
Submit your final checkpasswd.c file to MarkUs under the lab8 folder in your repository.
```
- 3/21/2021 Lab
- https://q.utoronto.ca/courses/68725/assignments/1 13163 2 /
<file_sep>/a1/trim.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Reads a trace file produced by valgrind and an address marker file produced
* by the program being traced. Outputs only the memory reference lines in
* between the two markers
*/
int main(int argc, char **argv) {
if(argc != 3) {
fprintf(stderr, "Usage: %s tracefile markerfile\n", argv[0]);
exit(1);
}
FILE *marker_file = fopen(argv[2], "r");
FILE *trace_file = fopen(argv[1], "r");
if (marker_file == NULL || trace_file == NULL) {
printf("There was an error opening the file\n");
return 1;
}
// Addresses should be stored in unsigned long variables
unsigned long start_marker, end_marker;
fscanf(marker_file, "%lx %lx", &start_marker, &end_marker);
fclose(marker_file);
char letter;
unsigned long hex;
char line[50];
char start_printing = 0;
char character;
char letter_found;
int i;
while (fgets(line, 50, trace_file) != NULL) {
i = 0;
letter_found = 0;
while (i < 50) {
character = line[i];
if (character != ' ' && character != '\t') {
if (letter_found == 0) {
letter = line[i];
letter_found = 1;
} else {
hex = strtol(&(line[i]), NULL, 16);
break;
}
}
i++;
}
if (hex == end_marker) {
break;
}
if (start_printing == 0) {
if (hex == start_marker) {
start_printing = 1;
}
} else {
printf("%c,%#lx\n", letter, hex);
}
}
fclose(trace_file);
/* For printing output, use this exact formatting string where the
* first conversion is for the type of memory reference, and the second
* is the address
*/
// printf("%c,%#lx\n", VARIABLES TO PRINT GO HERE);
return 0;
}
<file_sep>/lab2/phone_loop.c
#include <stdio.h>
int main() {
int return_code = 0;
char phone[11]; // need room for 0 terminator
printf("Type in a 10 character string\n");
scanf("%10s", phone);
int input_int;
while (1) {
printf("Type in an integer\n");
if (scanf("%d", &input_int) == EOF) {
break;
}
if (input_int < -1 || input_int > 9) {
printf("ERROR\n");
return_code = 1;
} else if (input_int == -1) {
printf("%s\n", phone);
} else {
printf("%c\n", phone[input_int]);
}
}
return return_code;
}<file_sep>/a2/cmake-build-debug/CMakeFiles/a2.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/a2.dir/family.c.obj"
"CMakeFiles/a2.dir/reading.c.obj"
"CMakeFiles/a2.dir/wheel.c.obj"
"a2.pdb"
"a2.exe"
"a2.exe.manifest"
"liba2.dll.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/a2.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/a1/README.md
# Assignment 1
**Due** Jan 31, 2019 by 4pm **Points** 5
# Assignment A1: Intro C
For this assignment, you will be writing two command-line utilities: a simple game of life and a program that counts member references in other
programs. Both programs will require that you use command-line arguments. The first also requires that you use arrays and the second requires
that you process standard input (using scanf).
Please remember that we are using testing scripts to evaluate your work. As a result, it's very important that (a) all of your files are named correctly
and located in the specified locations in your repository and (b) the output of your programs match the expected output precisely.
# Part 0: Getting Started (0%)
Follow the instructions carefully, so that we receive your work correctly.
Your first step should be to log into **MarkUs (https://markus.cdf.toronto.edu/csc209-2019-01/)** and navigate to the **a1: Intro C** assignment. Like for
the labs, this triggers the starter code for this assignment to be committed to your repository. You will be working alone on this assignment, and the
URL for your Git repository can be found on the right hand side of the page.
Pull your git repository. There should be a new folder named a1. All of your code for this assignment should be located in this folder. Starter code,
including a Makefile that will compile your code and provide a sanity check, has already been placed in this folder. To use the Makefile, type " _make
test_life_ ", " _make test_trim_ ", or " _make test_trcount_ ". That will compile the corresponding program and run our sanity checks. To remove .o files and
the executable, type " _make clean_ ".
Once you have pushed files to your repository, you can use MarkUs to verify that what you intended to submit was actually submitted. The
Submissions tab for the assignment will show you what is in the repository, and will let you know if you named the files correctly.
# Part 1: Game of Life (life.c and life_helpers.c) (2.5%)
You will write a C program called life.c that is implements a 1D variant of the **Game of Life
(https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life)** called **Rule 90 (https://en.wikipedia.org/wiki/Rule_90)**. You'll also write two helper
functions in life_helpers.c.
## Details
Your program reads two command line arguments, the first represents the initial state and the second represents the number of states to print. Your
program will then print the number of states specified, one per line, starting with the initial state. For example, given the initial state
......X.......X.......X...... and 10 states, the program would print:
```
......X.......X.......X......
.....X.X.....X.X.....X.X.....
....X...X...X...X...X...X....
...X.X.X.X.X.X.X.X.X.X.X.X...
..X.......................X..
.X.X.....................X.X.
....X...................X....
...X.X.................X.X...
..X...X...............X...X..
.X.X.X.X.............X.X.X.X.
```
## Requirements
You may assume that, if given, the first argument is an initial state made up of only the characters "." and "X" and, if given, the second argument is
an integer greater than or equal to 1. For this program, the user might still forget command-line arguments altogether. When this happens, your
program shouldn't crash. Instead you should print to standard error the message "USAGE: life initial n" (followed by a single newline \n character),
and return from main with return code 1. The starter code actually implements this behaviour for you already. Following the standard C
conventions, main should return 0 when the program runs successfully.
Along with the main function, you are required to write (and use) two helper functions. (These helper functions are to be implemented in the file
life_helpers.c. The main function is in life.c.) The first helper function is named print_state. It takes a character array and the size of that array as its
arguments, and returns void. This function's job is to print the characters of the given array following by a single newline character.
The second helper function is named update_state and it takes a character array and the size of that array, and returns void. This function should
update the state of the array according to the following rules:
```
the first and last elements in the array never change
an element whose immediate neighbours are either both "." or both "X" will become "."
an element whose immediate neighbours are a combination of one "." and one "X" will become "X"
```
## Command line arguments and return codes
For this program, you may assume that if exactly two command-line arguments are provided, they will have the correct format. If the user calls the
program with too few or too many arguments, the program should not print anything to stdout (only the provided message to stderr), but should
return from main with return code 1. Following the standard C conventions, main should return 0 when the program runs successfully.
# Part 2: Memory Reference Traces (trim.c and trcount.c) (2.5%)
In this part of the assignment, we examine how programs use memory by tracing the memory usage of a program and then counting the number of
accesses to different parts of memory. Before we explain your tasks, we start by explaining how to generate memory traces.
## Generating a memory trace
We use a program called valgrind to print information about every memory access made by a running program. This information includes the type
of access, the address, and the number of bytes accessed. valgrind runs on Linux (and is installed on the teach.cs machines). It does *not* run on
Mac or Windows in a way that is useful for this assignment. The output of valgrind is saved to a file, and your program will read this file. Since
getting exactly the output we want is a little complicated, we have given you a sample input file in your repository, and have included below some
instructions and programs to help you generate some real traces. If you download these to your account on teach.cs, and run make traces, the four
programs will be compiled and use runit to generate a trace for each program.
**trace-programs.zip** contains the following files:
Makefile
runit - a shell program that produces a memory reference trace from a given program. (Read the comments in the file.)
heaploop.c - a program that iterates over data allocated in the heap
matmul.c - a program that muliplies two randomly generated matrices. The size of the matrices is given as a command line argument.
simple.c - a program that assigns values to three variables
stackloop.c - a program that iterates over data allocated on the stack
You can download the zip file using a web browser on teach.cs. If you instead download it on to your own computer, you can use scp to transfer it
to teach.cs (scp trace-programs.zip _username_ @<EMAIL>:). Once you have the zip archive on teach.cs, you can run unzip trace-programs.zip
to expand it.
Note: Do not commit these programs or the traces they generate. Only the traces provided with the starter code should be committed to the repo.
In the output of runit, each line represents one memory access. The first non-blank character will always be one of 'I' (Instruction), 'S' (Store), 'M'
(Modify), or 'L' (Load). Then there will be one or two spaces followed by an address in hexadecimal format, followed by a comma, and a number
that represents the size in bytes of this memory access. In the trace file snippet below, there are two Instruction references, one Load reference and
one Store reference.
```
I 0400baa6,
S 04226ce0,
I 0400baad,
L fff000948,
```
The trace-programs directory also contains several small C programs that exhibit different memory reference behaviours. Let's look at simple.c. The
main thing to notice in this program are the lines that refer to MARKER_START and MARKER_END. They are declared as volatile which prevents the
compiler from re-ordering access to these variables. The addresses of these variables are written to a file called marker-simple in hexadecimal.
We set a value for MARKER_START just before the "interesting" part of the program, set a value for MARKER_END at the end of the "interesting" part of the
program. The addresses for these variables will appear in the tracefile at the point where the variables are assigned a value. This will allow us to
"trim" the trace file to keep only the interesting memory references.
## Task 1: Trimming the trace file (trim.c)
The first task is to write a program, trim.c that reads a file containing the output of runit, and outputs only the memory references between the
marker addresses.
## Details
```
The program trim takes two arguments. The first is the name of (or path to) a trace file produced by runit. The second argument is the name
of a "marker" file: a file containing the start and end address markers that define which part of the trace file we want to keep. The marker
addresses are not kept.
The marker file will contain two hexadecimal numbers on a single line. The first is the starting marker address, and the second is the ending
marker address.
```
```
When using fscanf, the format conversion specification for a hexadecimal address value is %lx. To print a hexadecimal literal use %#lx so the
initial "0x" is printed.
Assume that all input files are formatted correctly and you do not need to do any error checking on the file format.
If the start_marker address does not appear in the trace file, then the output of trim will be empty. If the end_marker does not appear in the trace
file then the remainder of the trace file will be printed.
You must use the output format strings specified in the printf statements in the starter code.
```
Example marker file from running simple on teach.cs.toronto.edu:
```
0xfff00090a 0xfff00090b
```
Example output from simple:
```
I,0x
S,0x
I,0x
S,0x60106c
I,0x40077d
L,0x
I,0x
L,0x60106c
I,0x
I,0x40078b
S,0xfff00090c
I,0x40078e
```
Now that we are only looking at the the memory references for a small part of the program, you can see where we are setting values for the
variables. The first two "S" references are storing values for i and j. The third "S" reference is storing the value for k. You can see that it is a
memory reference on the stack because of the high value of the address. (The f's give it away.)
## Task 2: Counting memory references (trcount.c)
The next step is to complete the program trcount.c that prints out counts of the different types of instructions.
If trcount has one argument then it is the name of a trace file from which to read. If it has no arguments, then it will read from stdin.
For example the output of trcount given using the example trace output above is:
```
Reference Counts by Type:
Instructions: 7
Modifications: 0
Loads: 2
Stores: 3
Data Reference Counts by Location:
Globals: 4
Heap: 0
Stack: 1
```
Note that you must use **exactly** this format in your output. The formatting strings for the printf statements are given to you in the starter code to
make this easy for you.
Values for Instructions, Modifications, Loads, and Stores are determined by counting the number of times each type of reference appears in the
trace.
The starter code contains several constants that define the start and end of different regions of memory. For example, all references to heap
memory occur between address 0x4000000 and 0x8000000. Due to complexities in how programs are laid out in memory, these values were
determined for the set of example programs provided on the teach.cs machines. If you try this out on other machines, these constants might be
different.
These constants are used to determine which of the three regions of memory each reference comes from. Your program will only count **data**
references (Load, Store, Modify) and will not count instruction references.
## Command line arguments and return codes
For the programs in part 2, you may assume that if the correct number of command-line arguments are provided, they will have the correct format. If
the user calls the program with too few or too many arguments, the program should not print anything to stdout (only the provided message to
stderr), but should return from main with return code 1. Following the standard C conventions, main should return 0 when the program runs
successfully.
# Reminder
Your programs must compile on teach.cs using gcc with the -Wall option and should not produce any error messages. Programs that do not
compile, will get 0. You can still get part marks by submitting something that doesn't completely work but does some of the job -- but it **must at least**
**compile** to get any marks at all. Also check that your output messages are **exactly** as specified in this handout.
# Submission
We will be looking for the following files in the a1 directory of your repository:
```
life.c
life_helpers.c
trim.c
trcount.c
```
Do not commit .o files or executables to your repository.
<file_sep>/a2/cmake-build-debug/Makefile
# CMAKE generated file: DO NOT EDIT!
# Generated by "MinGW Makefiles" Generator, CMake Version 3.13
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
SHELL = cmd.exe
# The CMake executable.
CMAKE_COMMAND = C:\Users\David\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\183.5429.37\bin\cmake\win\bin\cmake.exe
# The command to remove a file.
RM = C:\Users\David\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\183.5429.37\bin\cmake\win\bin\cmake.exe -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = C:\CS\CSC209\trainada\a2
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = C:\CS\CSC209\trainada\a2\cmake-build-debug
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
C:\Users\David\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\183.5429.37\bin\cmake\win\bin\cmake.exe -E echo "No interactive CMake dialog available."
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
C:\Users\David\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\183.5429.37\bin\cmake\win\bin\cmake.exe -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start C:\CS\CSC209\trainada\a2\cmake-build-debug\CMakeFiles C:\CS\CSC209\trainada\a2\cmake-build-debug\CMakeFiles\progress.marks
$(MAKE) -f CMakeFiles\Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start C:\CS\CSC209\trainada\a2\cmake-build-debug\CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles\Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles\Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles\Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named a2
# Build rule for target.
a2: cmake_check_build_system
$(MAKE) -f CMakeFiles\Makefile2 a2
.PHONY : a2
# fast build rule for target.
a2/fast:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/build
.PHONY : a2/fast
family.obj: family.c.obj
.PHONY : family.obj
# target to build an object file
family.c.obj:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/family.c.obj
.PHONY : family.c.obj
family.i: family.c.i
.PHONY : family.i
# target to preprocess a source file
family.c.i:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/family.c.i
.PHONY : family.c.i
family.s: family.c.s
.PHONY : family.s
# target to generate assembly for a file
family.c.s:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/family.c.s
.PHONY : family.c.s
reading.obj: reading.c.obj
.PHONY : reading.obj
# target to build an object file
reading.c.obj:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/reading.c.obj
.PHONY : reading.c.obj
reading.i: reading.c.i
.PHONY : reading.i
# target to preprocess a source file
reading.c.i:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/reading.c.i
.PHONY : reading.c.i
reading.s: reading.c.s
.PHONY : reading.s
# target to generate assembly for a file
reading.c.s:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/reading.c.s
.PHONY : reading.c.s
wheel.obj: wheel.c.obj
.PHONY : wheel.obj
# target to build an object file
wheel.c.obj:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/wheel.c.obj
.PHONY : wheel.c.obj
wheel.i: wheel.c.i
.PHONY : wheel.i
# target to preprocess a source file
wheel.c.i:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/wheel.c.i
.PHONY : wheel.c.i
wheel.s: wheel.c.s
.PHONY : wheel.s
# target to generate assembly for a file
wheel.c.s:
$(MAKE) -f CMakeFiles\a2.dir\build.make CMakeFiles/a2.dir/wheel.c.s
.PHONY : wheel.c.s
# Help Target
help:
@echo The following are some of the valid targets for this Makefile:
@echo ... all (the default if no target is provided)
@echo ... clean
@echo ... depend
@echo ... a2
@echo ... edit_cache
@echo ... rebuild_cache
@echo ... family.obj
@echo ... family.i
@echo ... family.s
@echo ... reading.obj
@echo ... reading.i
@echo ... reading.s
@echo ... wheel.obj
@echo ... wheel.i
@echo ... wheel.s
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles\Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep>/a2/README.md
# Assignment 2
**Due** Feb 14, 2019 by 4pm **Points** 10
# Assignment A2: Structs and Dynamic Memory
The goal of this assignment is to practice linked lists, strings, pointers, and dynamic memory allocation in C. You'll be implementing a word guessing
game.
## Wheel of Misfortune
Wheel of Misfortune is a two-player word game that goes like this. Player 1 picks a secret word, and tells player 2 the length. (For example, -----
would mean that the word selected by player 1 has five letters.) Player 2 then begins guessing letters. For each letter guessed by player 2 that
appears in the word, player 1 reveals the positions of that letter. Otherwise, if the letter does not occur at all in the word, player 2 loses a guess.
Player 2 wins the game if they are able to fully uncover the word before exhausting their allowed number of guesses. Player 1 wins if player 2 runs
out of guesses.
## But this isn't an ordinary opponent!
In this assignment, you will be implementing a Wheel of Misfortune game where the computer has the role of player 1, and a human has the role of
player 2. However, rather than choosing a word at the beginning of the game like a good little computer is supposed to do, this nasty computer
opponent is going to cheat and make it very difficult for the human to win. It will actively dodge human efforts to determine the word, as we'll explain
now.
When the game starts, you will tell the computer the length of the word you want to guess. Let's say that you choose a word-length of four letters,
so that you see ---- as the current representation of the word. Rather than playing fair and committing to one particular four-letter word from the
outset, the computer instead compiles a list of every four-letter word in its dictionary. For simplicity, let's assume that it has exactly the following
four-letter words: ally beta cool deal else flew good hope ibex. For your first guess, let's say you choose the letter e. The computer now must tell
you whether there are any e's in the word and, if there is at least one e, it must also show you the word with each e written in its proper position.
But how can the computer do this, since it has **not** chosen a word yet? The trick is for the computer to divide all current words into **word families**
based on where the e's lie in each word. Here is our vocabulary again, with the e's in bold: ally b **e** ta cool d **e** al **e** ls **e** fl **e** w good hop **e** ib **e** x. There are
five word families:
```
----, which contains the words ally, cool, and good
-e--, containing beta and deal
--e-, containing flew and ibex
e--e, containing else
---e, containing hope
```
What the computer will do is choose one of these word families, then uncover the e's that occur in each word of that chosen family. There are
several means by which the computer could choose a family; in this assignment, the computer will always choose the family with the most words. If
there is a tie for the most words, the computer will chose any one of the families tied for the most words.
As evidenced in our running example, the largest word family is of size three (the family ----). The computer will choose this word family, reduce its
candidate word list (now ally, cool, and good), and report to you that there are no e's in the word. Nasty!
It's not necessarily the case that the chosen word family includes no copies of your guess. (Remember, the computer is using the heuristic of
always choosing the largest family. This is not always optimal.) To demonstrate this, let's say that the computer is working with ally, cool, and good,
and your next guess is o. This time, there are two word families:
```
-oo-, containing cool and good
----, containing ally
```
The computer would choose the first word family, reducing its word list to cool and good, and revealing two o's in the word.
Note that if you guess a letter that does not appear anywhere in the computer's current word list, or your letter appears in the same position of every
single word in the current word list, the computer will "divide" the word list into a single family consisting of all words. This really isn't a special case
at all if your code is sufficiently general (as it should be).
There are two ways that the game can end. The first is that you are lucky enough to pare the computer's word list down to a single word, in which
case you win the game. The second (much more common :) ) case is that you exhaust all of your guesses without guessing the computer's word. In
this latter case, the computer can just pick any word at random from its current list, and report this word to you. All words in the current list are
indistinguishable to you, since they are all in the same word family.
## Starter Code
Your first step should be to log into **MarkUs (https://markus.cdf.toronto.edu/csc209-2019-01/)** and navigate to the **a2: Structs and Dynamic
Memory** assignment, which triggers the starter code for this assignment to be committed to your repository. You will be working alone on this
assignment, and the URL for your git repository can be found on the right hand side of the page.
Pull your git repository. There should be a new folder named a2. All of your code for this assignment should be located in this folder. Starter code,
including a Makefile that will compile your code, has been placed in this folder.
Once you have pushed files to your repository, you can use MarkUs to verify that what you intended to submit was actually submitted. The
Submissions tab for the assignment will show you what is in the repository, and will let you know if you named the files correctly.
### Word Families
The concept of a word family is embodied in the Family type defined in family.h. Each family contains a signature giving the pattern of each of the
words in the family, based on a single character guess. For example, the signature could be the string --e--, representing all words in the current
(five-letter) word list whose third letter is an e. The word_ptrs member is what points to the actual words that belong to each family. word_ptrs is an
array, where each element is a pointer to one of the words in the current word list. The last element in word_ptrs should be a NULL pointer.
The num_words member keeps track of the number of words belonging to this family. It begins at 0 for each initialized family, and increases by one
each time a new word is added. max_words gives the maximum number of words that this family can hold. When num_words reaches max_words, we
have no space left in the word_ptrs array in which to place new pointers-to-words, so we must allocate more space to word_ptrs. In this way, we can
begin by creating a family of modest size, and only if it becomes sufficiently large, increase its memory usage by fixed increments.
The next member of Family is a pointer to another Family structure. Through next pointers, we can create linked lists of families, allowing us to
traverse a whole chain of families by beginning at the head of a family list.
A skeleton of the Family implementation is in family.c. You will write much of the code to complete this module.
### Master words list
The starter code comes with a file named dictionary.txt. It is a huge English word list of over 120000 words. The file reading.h declares functions
related to reading this dictionary into memory, and associated implementations are in reading.c. The first thing your program will do is call
read_words to read the entire dictionary into memory. This words list remains in memory throughout the entire program run, and is never modified.
Sub-dictionaries of specific lengths are used in each round, depending on the length of word that you choose. These sub-lists, like word lists
associated with families, are not copies of the master words list's words, but are pointers to these words.
reading.c is a complete module for which you will not write any code. It will be helpful when working on other word-list-related tasks, however, to
understand how this code works.
### Game Code
Finally, the code that plays the actual game is in wheel.c. It uses functions defined in the helper modules family.c and reading.c.
The entry point (the main function) performs two initializations: it reads the dictionary words into memory, and initializes the family module. It then
continues to call play_round until the user decides not to play anymore. Lastly, it deallocates the memory used for the dictionary, and exits.
Some of this module's code has been written, but other code is left for you to write, as explained below.
## Your Tasks
### Programming: family.c
Implement the following functions in family.c:
```
Family *new_family(char *str)
void add_word_to_family(Family *fam, char *word)
Family *find_family(Family *fam_list, char *sig)
Family *find_biggest_family(Family *fam_list)
void deallocate_families(Family *fam_list)
Family *generate_families(char **word_list, char letter)
char *get_family_signature(Family *fam)
char **get_new_word_list(Family *fam)
char *get_random_word_from_family(Family *fam)
```
Details:
```
Read the comments for each function carefully.
Some function comments mention using realloc. Like malloc, realloc is used to allocate memory. Read the man page to find out more about
realloc.
Once the initial word list has been read from the dictionary file, you will not make any copies of the words. Instead you will make lists of pointers
to these words.
Be careful: realloc might not be able to extend word_ptrs in-place, in which case it moves your word_ptrs array and returns the new pointer to
where the new location can be found.
```
```
When you are working on generate_families, remember that we reuse the words in word_list so do not change them.
When working on generate_families, do not explicitly enumerate all the word families: a word of length n has 2^n possible families, but many of
those will be empty. (For example, no English word contains three consecutive u's.)
```
### Programming: wheel.c
Implement the following functions in wheel.c:
```
char **prune_word_list(char **words, int len, int *words_remaining)
char **get_word_list_of_length(char **words, int *len)
```
### Testing (recommended, but not for credit)
You will find that if you try to write all the functions and only then start testing your program, you will have a very hard time debugging. Therefore, we
highly recommend that you write a new program, say test_wheel.c, in which your write several test functions for almost all of the functions you need
to write. (Some of the functions are really too simple for this to be necessary.) That way, you can be more confident that each function operates as
expected.
When testing, you may need to create a few extra helper functions that hard-code the data structure that a function takes as input.
## Data Structure Examples
You're working with some rather subtle data structures in this assignment, so I wanted to run through a short demonstration before letting you loose.
## Step 0
Let's say that our dictionary file contains the following words (almost the same as before, but note the word of length five): ally beta cool deal else
flute good hope ibex. Starting from main in wheel.c, the first thing we do is call read_words. This gives us words set up with pointers to each of the
nine words. (Actually, there is one extra pointer in words: a pointer to NULL, which tells you when you've reached the end of the array.) words is
passed around to many functions, but never changes again after this point.
## Step 1
Assume that the user wants to play with words of length 4. From within get_word_list_of_length, prune_word_list will be called with integer 4 and a
pointer to the location into which it should place the number of words found. The structure returned by prune_word_list (we'll call it pruned) looks like
an array of pointers to those words from words that are the appropriate length. Notice that the original dictionary is still there, unmodified. In the next
game, the user might want to use words of length 5, and we can't have lost those words.
## Step 2
The user's first guess is e. generate_families gets called with the current word_list and the letter e. It generates a linked list of five families; the
pointer to the first is referred to as famhead. Note that the order of the families in this list is immaterial; this is just one possible ordering.
# Marking
We will use testing scripts to evaluate correctness. As a result, it's very important that your output matches the expected output precisely. Unlike A1,
which was marked only for correctness, this assignment will be marked not only for correctness, but also for style and design. At this point in your
programming career you should be able to make good choices about code structure, use of helper functions, variable names, comments,
formatting, etc.
For this and future assignments, your code may be evaluated on:
```
Memory management : your programs should not exhibit any memory leaks. This means freeing any memory allocated with malloc and
realloc. This is a very important marking criterion. Use valgrind to check your code.
Error-checking : library and system call functions (even malloc!) can fail. Be sure to check the return values of such functions, and terminate
your program if anything bad happens.
Warnings : your programs should not cause any warnings to be generated by gcc -Wall.
```
# Submission
Please commit to your repository often. We will look at family.c and wheel.c, so those files must be pushed for us to successfully test your code.
You must _NOT_ change family.h, reading.h, reading.c, or the provided Makefile. We will be testing your code with the original versions of those
files. We will run a series of additional tests on your full program and also on your individual functions (in family.c and wheel.c) so it is important
that they have the required signatures. Do not add executables or test files to your repo.
Remember to also test your code on teach.cs before your final submission. Your program must compile cleanly (without any warning or error
messages) on teach.cs _using our original Makefile_ and may not crash (seg fault, bus error, abort trap, etc.) on our tests. Programs that do not
compile or which crash will be assigned a 0.
<file_sep>/lab9/README.md
3/21/2021 Lab 9
https://q.utoronto.ca/courses/68725/assignments/1 13164 1 / 2
# Lab 9
```
Due Mar 15, 2019 by 6:30pm Points 1
```
# Lab 9: Signals
```
Due : Friday 15 March before 6:30pm
```
# Introduction
```
The purpose of this lab is to practice using signal handlers and alarms and to review operations on binary files. We will use these techniques to
explore how quickly your machine performs read and write operations. The lab provides links to help you find information about the timer and other
functions used, but it useful to have TAs nearby while you are working, so you can ask questions.
```
## Timing Reads: The Overall Task
```
In this lab, you will explore how various operations affect the runtime of a program. In short, you will be doing some profiling. You will write a C
program that takes an integer argument s representing a number of seconds and a string representing the name of an existing binary file f, which
contains 100 integers. The program will repeatedly generate a random integer from 0 to 99 and use that number as an index to read the
corresponding integer from f. The program runs for s seconds and then reports how many reads were completed.
```
# 1. Create a test file
```
Since your program has to read integers from a binary file, you need to create a test file containing 100 integers. Write a small program,
write_test_file.c, to do this task. It should take a single argument representing a filename and create a file with that name that contains 100
integers. The values of the integers themselves don’t matter, so start off by writing the integers 0 through 99 in order.
Because your newly-created test file is binary, you can’t display the integers with cat, and a normal text editor won’t work either. Instead, look at the
contents with the tool od (https://linux.die.net/man/1/od). The -vtu1 flag will display the contents in a format that is easier for you to read. Once
you have convinced yourself that the 100 integers are being correctly written, change your write_test_file to write random integers between 0 and
```
99. To generate random numbers, use the function **random (https://linux.die.net/man/3/random)**.
# 2. Write a program to read random locations in the file
```
The next step is to complete the first draft of the time_reads.c program. The starter code in the Lab9 folder just handles the command-line
arguments.
For now, you will need to write code that goes into the loop body. Your program should seek to a random location in the file, read the integer at that
location, and print it. Change your program to seek and read in the infinite loop.
At the moment, the only way to stop the program is to send it a signal. You can do this from the keyboard directly (with ctrl-C) or from another
terminal window by looking up the process id (https://linux.die.net/man/1/ps) and using the kill (https://linux.die.net/man/1/kill) command).
Try both ways.
```
# 3. Add a signal handler
```
Now, use sigaction (https://linux.die.net/man/2/sigaction) to add a signal handler to your program. Start with something simple that just prints a
message to standard out and exits (with termination code 0 ) when it receives a SIGPROF. Then, to test it, run your program and use kill to send it
a SIGPROF signal from the shell in another terminal window. (Check the man page for kill (https://linux.die.net/man/1/kill) to see how to get a listing
of signals and their numbers.)
```
# 4. Add timing
```
Add code to set up a timer (using setitimer (https://linux.die.net/man/2/setitimer) ) for s seconds (where s is obtained from the command line).
You shouldn’t use real time, since your results will be affected if your system is busy. Instead, use ITIMER_PROF to make the itimer send a SIGPROF.
Here (https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html) is an extra manual page that gives more advice on how to set an
alarm. Part of the learning goals of this lab is practicing using a man page to learn a new system call so we are intentionally not giving you any more
instruction about how to set the alarm.
Change your signal handler to print a message to standard out (use the MESSAGE format in the starter code) that provides both the total number of
reads completed and the time elapsed (s seconds). Run your code a few times to see how it works.
Once you have done this step, you can submit your lab. However, there’s more to do to explore how your computer works ...
```
3/21/2021 Lab 9
https://q.utoronto.ca/courses/68725/assignments/1 13164 2 / 2
# 5. Explore! (Not for lab credit)
```
Try different amounts of time (1 second? 5 seconds? 10 seconds?). Is the number of reads that your program can perform per second fairly
constant? (It’s slower the first second. Why do you think that is?) What happens if you remove the print statement in the loop (not the one in your
signal handler)? Can you explain why the number of read operations per second changes? What does that tell you about the cost of printing?
Try opening the file for reading and writing, and instead of reading a value, write a random value at the offset. Is one operation more expensive than
the other, and if so, can you speculate as to why?
Now, change the size of your data file (and be sure to change the possible offsets generated in your program). Does the number of reads (or writes)
per second change if the file size is much larger? If so, is there a specific file size where the change occurs? Do you have an explanation as to
why?
If you’ve been printing a message for every piece of data being read, you may notice that the alarm often happens while the statement is being
printed, so only part of the output will be delivered. Optionally, use sigprocmask to mask the SIGPROF signal during the print statement so that each
line of output is fully printed before the alarm is delivered and the signal handler executes and finishes the program.
```
# Submission
```
Submit both write_test_file.c and time_reads.c files to MarkUs under the Lab9 folder in your repository.
```
<file_sep>/lab10/README.md
3/21/2021 Lab 10
https://q.utoronto.ca/courses/68725/assignments/1 13165 1 / 2
# Lab 10
```
Due Mar 22, 2019 by 6:30pm Points 1
```
# Lab 10: Sockets
```
Due : Friday, March 22nd before 6:30pm
```
# Introduction
```
The purpose of this exercise is to practice using the socket-related system calls. The buffering part of this exercise will be particularly useful in
assignment 4.
The Unix programming concepts you will be using in this exercise are:
socket
server functions: bind, listen, accept
client functions: connect
```
# Setup: starter code and choosing a port
```
Do a git pull in your repository to download the starter code for Lab 10.
The port on which the server listens is defined on the second line of the Makefile found in the starter code. We have it set to 30001 by default;
before continuing, we’d like you to change this.
To avoid port conflicts, use the following number as the port on which your server will listen: take the last four digits of your student number, and add
a 5 in front. For example, if your student number is 1008123456, your port would be 53456. Using this base port, you may add 1 to it as necessary
in order to use new ports (for example, the fictitious student here could also use 53457, 53458, 53459, 53460). Sometimes, when you shutdown
your server (e.g. to compile and run it again), the OS will not release the old port immediately, so you may have to cycle through ports a bit.
Note that you only need to change the PORT variable value in the Makefile. It uses this variable and the -D flag to tell gcc to define a constant
during compilation that will be accessible to the program during execution.
```
# Introduction: sending and receiving messages
```
Open randclient.c. It is a client program that sends multiple copies of the same message to a server. Each message ends with a network newline
"\r\n".
You might expect that a server using read will receive one complete line of text with each read call. However, this isn’t guaranteed to happen. For
example, in a busy network or with a slow client, one line of text might be split across multiple TCP segments. A server cannot do a single read and
expect to get any sensible unit of communication.
To simulate this, randclient.c artificially splits up its copies of the messages over multiple write calls. This will cause trouble for any server that
expects to read entire messages at a time – readserver.c is one such server.
Run readserver & and then run randclient 127.0.0.1. Notice that the server thinks that every small piece of a message is a complete message,
which of course is incorrect. Your task is to add buffering to your server so that it waits for a complete line (ending with the network newline) before
printing the message.
```
# Task 1: A Buffering Server
```
In bufserver.c, we have given you the skeleton for a buffering server. The Step comments in the code indicate what you should do to complete the
server. The main idea is that you have a buffer (a character array) where you store pieces of a message until you have a network newline (“\r\n”).
Each message piece goes after the data that you’ve already placed in the buffer. When you find a network newline, you know that you have a
complete message, so you can print that message and then shift any remaining bytes to the front of the buffer as the start of the next copy of the
message.
An example of how these buffered reads will work is given in a diagram.
Once you finish the steps, try running bufserver & and then run randclient 127.0.0.1 to connect to the server. The server should have one line of
output per message. If there is extra garbage printed or other errors, carefully go over the steps again – it’s very easy to get off-by-one mistakes
here. Another tip is to be careful to note when you are guaranteed to have a null-terminated string in buf, and when you aren’t.
```
# Task 2: Using the Debugger
3/21/2021 Lab 10
https://q.utoronto.ca/courses/68725/assignments/1 13165 2 / 2
```
For this part, you are asked to run the client and the server in the debugger to help you understand how the socket calls work. To carry out this
exercise, you will need to have two terminal windows open on your machine. One will be used to run the server and the other will be used to run the
client. If you’re working remotely, a simple option is to open two ssh connections (but make sure they are both on the same machine, like wolf).
```
## Debugging Exercise 1
```
In the client window, run script client.1, and in the server window run script server.1. This will cause transcripts of your sessions to be written to
files that you will submit.
In the server window, run gdb bufserver and set a breakpoint at set_up_server_socket (break set_up_server_socket). Step through the code using next
(or n) until you see the bind call. (Remember that gdb shows you the line just before it is to be executed. You want to stop before the bind call
happens.) Try running the client (randclient 127.0.0.1) in the client window and notice that the connection is refused.
In the server window, step once (just before listen), and try running the client again. Still the connection is refused because the socket is not fully
set up on the server.
In the server window, step until you see the accept call, and then step one more time. gdb does not give you the next prompt because the accept
call has not returned yet. The accept call is blocked waiting for a connection from a client.
In the client window, run the client again. Note that the accept call returns in the server. Keep stepping in the server until the read call. This is
where the server starts reading the message from the client. Keep stepping in the server until all of the bytes are received.
In both the client and server windows, type exit to complete the scripts. Commit your script files before you move on.
```
## Debugging Exercise 2
```
In the client window, run script client.2 and in the server window, run script server.2.
Now run gdb bufserver in the server window, and set a breakpoint at the start of main; do the same in the client window, but with randclient. In the
client, type run 127.0.0.1 to run the client in gdb.
Try stepping through the two programs in different orders so that you can see how the messages are transferred. Look at the values of variables
(e.g. buf, inbuf) at different times to see their values.
This is your chance to really think about how the client and server talk to each other, so take advantage of the opportunity to learn a bit more gdb.
Pay attention to how the data is being sent. Reading and writing on a socket has to be done carefully. Time you spend understanding what is
happening with this example code will help you get started on Assignment 4.
After you have tried several variations, exit from gdb and type exit in both windows. Commit your script files.
```
# Submission
```
Submit your final bufserver.c, client.1, client.2, server.1, and server.2 files to MarkUs under the Lab10 folder in your repository. You should not
make changes to any other files.
```
<file_sep>/a1/life_helpers.c
#include <stdio.h>
void print_state(char *state, int size) {
printf("%.*s\n", size, state); // Specify the precision with size.
}
void update_state(char *state, int size) {
int prev_changed = 0; // We need to whole process array simultaneously.
// We don't want to have to copy the array to be able to modify the
// original while keeping a snapshot of what it was, so we use this to
// tell if we should interpret the previous neighbouring cell as it is
// currently (0), or as the inverted version of itself (1).
for (int i = 1; i < size - 1; i++) { // Omit the first/last elements.
char change_to;
if ((state[i-1] == state[i+1]) == prev_changed) { // Opposite values so cell goes to 'X'.
// (a == b) returns 0 if false, 1 if true.
// if neighbours are equal and prev_changed == 1, then LHS=RHS=1 so evaluates true.
// if neighbours are opposite and prev_changed == 0, then LHS=RHS=0, so evaluates true.
change_to = 'X';
} else { // Same value on both sides, cell goes to '.'.
change_to = '.';
}
if (state[i] == change_to) {
prev_changed = 0; // This cell can be interpreted as is when processing next cell.
} else {
state[i] = change_to; // This cell needs to interpreted as the inversion because we changed it.
prev_changed = 1;
}
}
}<file_sep>/lab11/README.md
3/21/2021 Lab 11
https://q.utoronto.ca/courses/68725/assignments/1 13168 1 / 2
# Lab 11
```
Due Mar 29, 2019 by 6:30pm Points 1
```
# Lab 11: Select
```
Due : Friday 29 March before 6:30pm
```
# Introduction
```
The purpose of this lab is to practice using select to read from multiple inputs. This system call is used in assignment 4. Like last week, you are
welcome to reuse code from this lab in the assignment if it would be useful.
```
# Setup
```
Find the starter code in the Lab11 folder in your repository.
Like last week, you should change the port in the Makefile before doing anything else. Take the last four digits of your student number, and add a 5
in front. For example, if your student number is 998123456, your port would be 53456. Using this base port, you may add 1 to it as necessary in
order to use new ports (for example, the fictitious student here could also use 53457, 53458, 53459, 53460). Sometimes, when you shutdown your
server (e.g., to compile and run it again), the OS will not release the old port immediately, so you may have to cycle through ports a bit.
```
# An Echo System
```
Start by carefully reading through the starter code carefully making sure you understand what it already does.
Start with the chat_client.c code. This program creates a connection to a server. Then, it reads input from the user, sends it to the server, and waits
for a response which it displays back to the user on standard out. It strictly alternates these reads (from the keyboard and from the server).
What happens in chat_server.c? It accepts a connection from a client. Then, it waits for input from the user and then echos it (it sends what is
received right back). It keeps information about multiple clients in an array and does this echoing operation independently with each of them. In
other words, input from one particular client is echoed only to that same client - not to all of the others. The server uses select in a loop to process
input from whichever client is talking without waiting for others.
The goal of the lab is to create a functioning chat system where the messages sent by one client are delivered to all the other clients and
participants are not required to talk in some pre-defined artificial turns. To accomplish this, you will need to change both the client and the server.
```
# 1. Identify Yourself
```
Once we start broadcasting messages from the server, it will get confusing if we can’t identify who the message comes from. Your first task is to
modify the client so that the first thing it does is to ask the user for a username, to read the username from stdin, and to write that username to the
socket. The server should be modified so that it reads the username immediately after accepting the connection. The username should be added to
the table of struct socknames it is managing. Then, whenever the server echoes a message, it should prefix the message with Username:, where
“Username” is that connection’s name.
```
# 2. Start Echoing
```
This is a quick task. Change the read_from function so that it broadcasts any message received to all connected clients. Then, test by connecting
more than one client to the server and making sure that every client receives any message that the other clients send. It’ll be a bit awkward since
our clients are reading from stdin before reading from the socket. You’ll have to hit Enter on the client that didn’t send the message to see what
the other client has sent, and that will lead to the other clients receiving “empty” messages.
```
# Task 3: Monitor stdin and the Socket in the Client
```
Take a look at how the server uses select. In particular, look at the fd_set variables it is managing and how it checks which file descriptor is ready
for reading using FD_ISSET. Pay special attention to how the fdset used in the select call is reset for each new call. Make sure you understand
how the chat_server.c starter code works before you try to use select in the client.
Your task is to update the client so it monitors just two file descriptors: the socket with the server and stdin. Whenever a message is received on
either, your program should read it and pass it to the correct output stream.
```
# Submission
```
Submit your final chat_client.c and chat_server.c files to MarkUs under the Lab11 folder in your repository.
```
3/21/2021 Lab 1 1
https://q.utoronto.ca/courses/68725/assignments/1 13168 2 / 2
```
Congratulations! You’ve finished the last lab of the course. Good luck with the last assignment!
```
<file_sep>/lab7/README.md
3/21/2021 Lab 7
https://q.utoronto.ca/courses/68725/assignments/1 13162 1 / 2
# Lab 7
```
Due Mar 1, 2019 by 6:30pm Points 1
```
# Lab 7: fork
```
Due : Friday 1 March before 6:30pm
```
# Introduction
```
The purpose of this exercise is to play with fork, and get a feeling for how it works. It should be a fairly short lab.
```
# 1. Run the simplefork program
```
Open simplefork.c in your favourite editor. Read it through to figure out what it is doing. Compile and run it a few times. Recall from lecture that it is
up to the operating system to decide whether the parent or the child runs first after the fork call, and it may change from run to run.
Question 1: Which lines of output are printed more than once?
Question 2: Write down all the different possible orders for the output. Note that this includes output orders that you may not be able to reproduce.
```
# 2. Fork in a loop
```
The program in forkloop.c takes one command-line argument, which is the number of iterations of the loop that calls fork. Try running the program
first with 1, 2, or 3 iterations. Notice that the shell prompt sometimes appears in the middle of the output. That happens because the parent process
exits before some of the children get a chance to print their output.
Also notice that some of the parent process ids are 1. This happens when the parent process terminates before the child calls getppid. (What do
we call the child and the parent process when it is in thist state?) If you want avoid this situation you can add a sleep(1); just before the return call
in main. Note that this is really just a hack and if we really want to ensure that a parent does not terminate before its child, we need to use wait
correctly.
Question 3: How many processes are created, including the original parent, when forkloop is called with 2, 3, and 4 as arguments? n arguments?
Question 4: If we run forkloop 1, two processes are created, the original parent process and its child. Assuming the process id of the parent is 414
and the process id of the child is 416, we can represent the relationship between these processes using the following ASCII diagram:
```
```
414 -> 416
```
```
Use a similar ASCII diagram to show the processes created and their relationships when you run forkloop 3.
```
# 3. Make the parent create all the new processes
```
Create a copy of forkloop.c called parentcreates.c. In the new file, modify the program so that the new children do not create additional processes,
i.e., so that only the original parent calls fork. Keep the printf call for all processes. The resulting diagram will look something like the following
when parentcreates 3 is run. Note that the child process ids will not necessarily be in sequence.
```
```
414 -> 416
414 -> 417
414 -> 420
```
# 4. Make each child create a new process
```
Create a copy of forkloop.c called childcreates.c. In the new file, modify the program so that each process creates exactly one new process. Keep
the printf call for all processes. The resulting diagram will look something like the following when childcreates 3 is called:
```
```
414 -> 416 -> 417 -> 420
```
# 5. Add wait (optional)
```
The information provided by the getppid system call may not always give you the information you expect. If a process’s parent has terminated, the
process gets “adopted” by the init process, which has a process id of 1, which is returned by getppid.
A process can wait for its children to terminate. If a process wants to wait until all its children have terminated, it needs to call wait once for each
child. Add the appropriate wait calls to both parentcreates and childcreates to ensure that each parent does not terminate before its children.
```
3/21/2021 Lab 7
https://q.utoronto.ca/courses/68725/assignments/1 13162 2 / 2
```
Your programs should delay calling wait as long as possible. In other words, if the process has other work to do like creating more children, it
should create the children first and then call wait.
```
# Submission
```
Submit your final parentcreates.c and childcreates.c files to MarkUs under the lab7 folder in your repository. Remember to use git pull to first get
the starter code.
Because this is a busy week, we have made part 5 optional. You can get full credit for the lab by only submitting the code for parts 3 and 4.
You do not need to submit answers to the questions.
```
| 8edbacfbdd65df3d760826ff4db2534da0f8f4fa | [
"Markdown",
"C",
"CMake",
"Makefile"
] | 26 | Markdown | DavidTraina/SystemsProgramming | e56ad45895548c5bab0c81d182a752778994ec56 | 6cc8c00e6930e1eda599faa2ed0f620b5fc05912 |
refs/heads/dev | <repo_name>huerhai/ccms-components<file_sep>/src/components/menus/MenusNodeCtrl.js
/**
* Created with MenusNodeCtrl.js
* @Description:
* @Author: maxsmu
* @Date: 2016-03-16 9:04 AM
*/
import { Inject } from 'angular-es-utils';
import { dispatchMenuChange } from './MenuService';
@Inject('$state', '$timeout')
export default class MenusNodeCtrl {
$onInit() {
this._$timeout(() => {
// -获取当前选择的菜单项(初始化时)
const menu = this.getMenu(this.list);
if (menu) {
dispatchMenuChange(menu);
}
}, 0);
}
/**
* 点击菜单
* @param node
*/
clickParents(node) {
node.toggleNode = !node.toggleNode;
};
/**
* 单击菜单时
* @param menu
*/
clickMenus(menu) {
// - 路由未发生变化时,阻断事件广播
if (menu.state !== this._$state.current.name) {
dispatchMenuChange(menu);
}
};
/**
* 初始化时默认打开的菜单项
* @param menus
* @returns {*}
*/
getMenu(menus = []) {
return Array.isArray(menus) ? menus.find(item => {
return item.state === this._$state.current.name;
}) : {};
}
}
| 1b24b496ad6be77857cd70e432dbfa5687474a7a | [
"JavaScript"
] | 1 | JavaScript | huerhai/ccms-components | 2ce93fb0cd8430f7b246477f938d77c8a4fe2298 | 062951e42285dea8604e55a46ed361ec98226f52 |
refs/heads/master | <file_sep>// Display articles in the articles pane.
$.getJSON("/articles", function(data) {
// For each one
for (var i = 0; i < data.length; i++) {
// Display the apropos information on the page
$("#article-list").append(`<p data-id=${data[i]._id}><a href="#">${data[i].title}`);
}
});
// Whenever someone clicks a p tag
$(document).on("click", "p", function() {
// Save the id from the p tag
var thisId = $(this).attr("data-id");
// Now make an ajax call for the Article
$.ajax({
method: "GET",
url: "/articles/" + thisId
})
// With that done, add the note information to the page
.then(function(data) {
console.log(data);
// The title of the article
$("#article-display").html(`<h3 data-id=${data._id}><a href=${data.link} target="_blank">${data.title}</a></h3>`);
// create a comment input form
$("#comment-div").html(
`<h4>What do you think?</h4>
<input class="form-control" id="username" name="username" placeholder="User Name">
<textarea class="form-control" id="comment-body" name="comment" placeholder="Comment..."></textarea>
<button class="btn btn-dark btn-sm" id="comment-submit">Submit</button>`
);
// An input to enter a new title
$("#notes").append("<input id='titleinput' name='title' >");
// A textarea to add a new note body
$("#notes").append("<textarea id='bodyinput' name='body'></textarea>");
// A button to submit a new note, with the id of the article saved to it
$("#notes").append("<button data-id='" + data._id + "' id='savenote'>Save Note</button>");
// If there's a note in the article
if (data.note) {
// Place the title of the note in the title input
$("#titleinput").val(data.note.title);
// Place the body of the note in the body textarea
$("#bodyinput").val(data.note.body);
}
});
});
// When you click the submit button
$(document).on("click", "#comment-submit", function() {
// Grab the id associated with the article from the submit button
var thisId = $(this).attr("data-id");
// Run a POST request to change the note, using what's entered in the inputs
$.ajax({
method: "POST",
url: "/articles/" + thisId,
data: {
// Value taken from title input
title: $("#username").val(),
// Value taken from note textarea
body: $("#comment-body").val()
}
})
// With that done
.then(function(data) {
// Log the response
console.log(data);
// Empty the notes section
$("#notes").empty();
});
// Also, remove the values entered in the input and textarea for note entry
$("#titleinput").val("");
$("#bodyinput").val("");
});
// submit multiple comments to the comment-display div
$(document).on("click", "#comment-submit", function() {
// store new comment information
let username = $("#username").val();
let commentBody = $("#comment-body").val();
// send comments to the databas
// refresh the comments collection JSON object
// append all comments to the .comment-display div
$(".comment-display").append(
`<div class="comment"><h5>${username} commented:</h5>
<p>${commentBody}</p></div>`
);
console.log(
`User ${username} posted a new comment:
${commentBody}`
);
console.log("New Comment Submitted");
// Also, remove the values entered in the input and textarea for note entry
$("#username").val("");
$("#comment-body").val("");
});
<file_sep>// server dependencies
var express = require("express");
var logger = require("morgan");
var mongoose = require("mongoose");
// scraping dependencies
var axios = require("axios");
var cheerio = require("cheerio");
// require the models
var db = require("./models");
var PORT = process.env.PORT || 3041;
// initialize express
var app = express();
// log requests with morgan logger
app.use(logger("dev"));
// parse request body as JSON
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// public is a static folder
app.use(express.static("public"));
// connect to mongodb
mongoose.connect(
process.env.MONGODB_URI || "mongodb://localhost/natsNews",
{
useNewUrlParser: true
}
);
// routes
app.get("/", function(req, res) {
console.log("this works");
}) // I can't get a route on the home page to work for some reason
// GET route for scraping federalbaseball.com
app.get("/scrape", function(req, res) {
// get html body
axios.get("https://www.federalbaseball.com/").then(function(response) {
var $ = cheerio.load(response.data);
// get h2 elements
$("h2").each(function(i, element) {
// declare an empty `result` object
var result = {};
// add text and url to the `result` object
result.title = $(this)
.children("a")
.text();
result.link = $(this)
.children("a")
.attr("href");
// create new article using the `result` object
db.Article.create(result)
.then(function(dbArticle) {
// view article in console
console.log(dbArticle);
})
.catch(function(err) {
// if (err) log (err)
console.log(err);
});
});
// Send a message to the dom
res.send("Scrape Complete");
// console.log("Scrape Complete");
});
});
// Route for getting all Articles from the db
app.get("/articles", function(req, res) {
// Grab every document in the Articles collection
db.Article.find({})
.then(function(dbArticle) {
// If we were able to successfully find Articles, send them back to the client
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurred, send it to the client
res.json(err);
});
});
// Route for grabbing a specific Article by id, populate it with it's note
app.get("/articles/:id", function(req, res) {
// Using the id passed in the id parameter, prepare a query that finds the matching one in our db...
db.Article.findOne({ _id: req.params.id })
// ..and populate all of the notes associated with it
.populate("note")
.then(function(dbArticle) {
// If we were able to successfully find an Article with the given id, send it back to the client
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurred, send it to the client
res.json(err);
});
});
// Route for saving/updating an Article's associated Note
app.post("/articles/:id", function(req, res) {
// Create a new note and pass the req.body to the entry
db.Note.create(req.body)
.then(function(dbNote) {
// If a Note was created successfully, find one Article with an `_id` equal to `req.params.id`. Update the Article to be associated with the new Note
// { new: true } tells the query that we want it to return the updated User -- it returns the original by default
// Since our mongoose query returns a promise, we can chain another `.then` which receives the result of the query
return db.Article.findOneAndUpdate(
{ _id: req.params.id },
{ note: dbNote._id },
{ new: true }
);
})
.then(function(dbArticle) {
// If we were able to successfully update an Article, send it back to the client
res.json(dbArticle);
})
.catch(function(err) {
// If an error occurred, send it to the client
res.json(err);
});
});
// start the server
app.listen(PORT, function() {
console.log("App running on port " + PORT + "!");
});
<file_sep># Nats News Scraper
View and Comment on Washington Nationals News
View articles from [Federal Baseball](https://www.federalbaseball.com/). Multiple users can post multiple comments on articles.
Heroku deployment: https://nats-news-2.herokuapp.com/
| 7393d57585fdad98f97ad67f1a056fd83eac90f0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | dbstocker/nats-news-scraper | 4b17abebd7cad0e558f366df0f49846919a22af9 | 3848e35cb96414936b3ecf0fe343143d33946a7c |
refs/heads/master | <repo_name>ny030303/tetris<file_sep>/src/main/java/net/gondr/tetris1/App.java
package net.gondr.tetris1;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import net.gondr.views.MainController;
public class App extends Application
{
public static App app;
public Game game = null;
public MainController controller;
@Override
public void start(Stage primaryStage) throws Exception {
app = this;
System.out.println(this);
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/net/gondr/views/Main.fxml"));
AnchorPane ap = (AnchorPane) loader.load();
Scene scene = new Scene(ap);
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if(game != null) {
game.keyHandler(e);
}
});
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
System.out.println("프로그램 로딩중 오류 발생");
}
}
public static void main(String[] args) {
launch(args);
}
}
<file_sep>/src/main/java/net/gondr/views/MainController.java
package net.gondr.views;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import net.gondr.tetris1.App;
import net.gondr.tetris1.Game;
public class MainController {
@FXML
private Canvas gameCanvas;
@FXML
private Canvas nextBlockCanvas;
@FXML
private Label scoreText;
@FXML
public Button gameBtn;
public boolean isReset = true;
@FXML
public void initialize() {
App.app.controller = this;
System.out.println("메인 레이아웃 초기화 완료");
App.app.game = new Game(gameCanvas, nextBlockCanvas);
// App.app.game.createSideBoard(nextBlockCanvas);
App.app.game.getScore(scoreText);
App.app.game.getButton(gameBtn);
// App.app.game.clearBoard();
}
@FXML
public void clickBtnEvent() {
if(isReset) {
App.app.game.clearBoard();
App.app.game.scoreReset();
scoreText.setText("0점");
// score 리셋
// 속도 리셋
// 버튼 text 바꾸기
} else {
}
}
public void changeReset() {
if(isReset) {
isReset = false;
} else {
isReset = true;
}
}
public void setGameBtnText(String text) {
gameBtn.setText(text);
}
}
| 2e0a5c69285c5102e05d54b6ecfad5cc1ee29fec | [
"Java"
] | 2 | Java | ny030303/tetris | 86428d9b07cabfca90e88ccedcdf84927745922e | d4b48a8bb1917487c104e342e0d887da063bdef0 |
refs/heads/master | <file_sep>import { makeStyles } from '@material-ui/core/styles';
export const useStyles = makeStyles((theme) => ({
root: {
margin: theme.spacing(6, 0, 3),
},
lightBulb: {
verticalAlign: 'middle',
marginRight: theme.spacing(1),
},
mb1: {
marginBottom: theme.spacing(1)
},
ml1: {
marginLeft: theme.spacing(1)
},
mr1: {
marginRight: theme.spacing(1)
},
mt1: {
marginTop: theme.spacing(1)
},
paper: {
[theme.breakpoints.down('xs')]: {
borderRadius: 0,
padding: theme.spacing(0.5)
},
padding: theme.spacing(2),
textAlign: 'center'
},
textRight: {
textAlign: 'right'
},
textRightHideMobile: {
[theme.breakpoints.down('xs')]: {
display: 'none'
},
textAlign: 'right'
},
}));
| e7000de2370f58266e2d29db006e4ffba6b6da74 | [
"JavaScript"
] | 1 | JavaScript | joeplaa/nextjs-mui-out-of-memory | 5cb62d2def7670cee0b782c26af2dfecd29a2574 | 870f6996172acbeea93bd1a250fe30a3c569f46c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.