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
<repo_name>guptarah/swbd_disfluency<file_sep>/scripts/crop_disf_chunks #! /bin/bash # script to crop disfluent part from wav file disf_trans="/media/CARE/switchboard/swb_ms98_transcriptions/disfluent_uttr" audio_location="/media/CARE/switchboard/wav_files/" trimmed_audio_storage="/media/CARE/switchboard/trimmed_files/" while read line do file_id=$(paste -d' ' <(echo "SW0") <(echo $line | cut -c3-6 | tr "a-z" "A-Z") | sed s/\ //g ) file_name=$file_id.wav echo $file_name start_time=$(echo $line | cut -d' ' -f2) start_time_bef=$(echo "$start_time - 1"|bc) end_time=$(echo $line | cut -d' ' -f3) end_time_ext=$(echo "$end_time + 1"|bc) # extending as some features do not get extracted at the end of file time_duration=$(echo "$end_time_ext - $start_time_bef"|bc) echo $time_duration sox $audio_location/$file_name $trimmed_audio_storage/$file_id"_"$start_time_bef"_"$end_time_ext".wav" trim $start_time_bef $time_duration done < "/media/CARE/switchboard/swb_ms98_transcriptions/disfluent_uttr" <file_sep>/scripts/compute_start_end_line_loc.py import numpy import sys time_file = sys.argv[1] start_time = float(sys.argv[2]) end_time = float(sys.argv[3]) time_mat = numpy.genfromtxt(time_file,delimiter=' ',dtype='float') length_file = time_mat.shape[0] vec1 = numpy.tile(start_time,(length_file,1)) vec2 = numpy.tile(end_time,(length_file,1)) vec1_diff = numpy.matrix(time_mat[:,0]).T - vec1 vec2_diff = numpy.matrix(time_mat[:,1]).T - vec2 f1=open('./temp_start_end', 'w+') f1.write(str(numpy.nonzero(numpy.diff(numpy.sign(vec1_diff).T))[1][0,0] + 2)) f1.write('\n') f1.write(str(numpy.nonzero(numpy.diff(numpy.sign(vec2_diff).T))[1][0,0] + 1)) f1.close <file_sep>/scripts/extract_features #! /bin/bash # script to extract features from praat input_dir=$1 # dir containing the wav files output_dir=$2 # dir where to store feature # GIVE full path below transcript_dir=$3 # dir where transcripts are located # example: ./extract_features /media/CARE/switchboard/trimmed_files/ /home/rahul/research/swbd_disfluency/features/ /media/CARE/switchboard/swb_ms98_transcriptions/ cd ../../tools for files in $input_dir/*.wav do cd ../../tools echo $(basename $files) save_dir=$output_dir/$(basename $files) mkdir $save_dir # extract praat features ./praat extract_voice_report.praat $files $save_dir # voice report ./praat extract_intensity.praat $files $save_dir # voice report ./praat extract_pitch.praat $files $save_dir # voice report # extract lables file_id=$(basename $files | cut -c1-7) prime_dir=$(echo $file_id | cut -c4-5) sec_dir=$(echo $file_id | cut -c4-7) trans_loc=$(ls $transcript_dir/$prime_dir/$sec_dir/*$sec_dir"A"*word*) start_time=$(basename $files | cut -d'_' -f2 ) end_time=$(basename $files | cut -d'_' -f3 | cut -d'.' -f1-2) echo $trans_loc $start_time $end_time cd ../swbd_disfluency/scripts/ cut -d' ' -f2-3 $trans_loc > temp_times python compute_start_end_line_loc.py temp_times $start_time $end_time # this will create temp_start_end with start and end line numbers to locate in word transcript file start_line=$(head -n1 temp_start_end) end_line=$(tail -n1 temp_start_end) echo $start_line $end_line sed -n $start_line,"$end_line"p $trans_loc | grep '\-$' | cut -d' ' -f2,3 > time_w_disf python create_lables.py time_w_disf $start_time $end_time cp temp_lables $save_dir/lables rm temp_lables done <file_sep>/README.md Scripts to process switchboard data to create matrices for disfluency detection <file_sep>/scripts/create_lables.py import numpy import sys disf_time_file = sys.argv[1] start_time = float(sys.argv[2]) end_time = float(sys.argv[3]) disf_times = numpy.matrix(numpy.genfromtxt(disf_time_file,delimiter=' ',dtype='float')) num_disf = disf_times.shape[0] num_label_stamps = int(100*(end_time - start_time)) lables = numpy.zeros(num_label_stamps) print disf_times for ind in range(0,num_disf): start_disf = int((disf_times[ind,0] - start_time) *100) end_disf = int((disf_times[ind,1] - start_time)*100) print start_disf lables[start_disf:end_disf] = 1 numpy.savetxt('temp_lables',lables,fmt='%d')
cb5b1c306e988c27e3f2eb24070d3dba91798915
[ "Markdown", "Python", "Shell" ]
5
Shell
guptarah/swbd_disfluency
de771e14e902e59b6d23e574230fef09fb618c0d
10c66769e91a09dc06e08a825f5710f207032ace
refs/heads/master
<repo_name>alx/smsModeration<file_sep>/README.md *smsModeration* is a complete installation to receive and moderate SMS before sending them to a custom display. It could be used during interactive exhibition when you need to check received SMS (for abuse, explicit language, ...) before to send them to public display. It uses a standard Android phone with a standard gsm contract, and a computer hosting the moderation interface. Some command-line knowledge might be required to complete the installation, feel free to contact me if you need some help. # Hardware requirements Current installation of smsModeration is running on a *nix laptop with ruby install, and the sms are coming from an Android phone running SMS Gateway app. ![Network Schema](https://raw.github.com/alx/smsModeration/master/documentation/network.png) # Moderation Interface Install smsModeration uses rvm and bundler to manage ruby version and gem packages. To install necessary ruby gems for this apps, just launch bundler inside smsModeration folder: ``` bundle install ``` To run the moderation interface and be able to receive sms on this interface, you can run the application with: ``` shotgun smssync.rb ``` Now you can use your browser to connect to moderation interface: [http://localhost:9393](http://localhost:9393) If the moderation machine is on the network, you can connect from a browser on a different machine: [http://machine.ip:9393](http://machine.ip:9393) # Android SMS Gateway On the Android phone receiving the SMS, you need to install SMS Gateway app. Configure this app to send all incoming sms to the computer running the moderation interface. In this configuration, the device name need to be set to "gateway". # Using Moderation Interface ![Moderation Interface](https://raw.github.com/alx/smsModeration/master/documentation/moderation_interface.png) Moderation interface is composed by 4 columns. ## Messages received Messages arrive in the column on the left. From there you can choose to keep a message or not. * The number of messages available is display on top of this column * A timer is available on top of the column to let you know when the list will be refreshed * You can refresh the list manually with the blue refresh button * You can trash all items on this list by pressing the red trash button ## Current selection The second column shows the messages of your current selection. A counter is available on top of the column to indicate you how many messages are in the current selection. You can make a new selection by pressing on the blue "New Selection" button. The current selection serial is indicated on this button. On each messages from this column, you can choose to remove a message from the selection or to favorite it. ## Favorites The third column displays your favorite messages. You can remove the favorite status of a message by pressing on the yellow star button. You can add a message to the current selection by pressing on the blue select button. ## All messages The fourth and last column shows all the selected messages. Because the number of selected messages can be huge, you need to press the "Display all" button on top of the column to display them. You can add a message from this list to the current selection by pressing on the blue select button. # Gource ![Gource display](https://raw.github.com/alx/smsModeration/master/documentation/gource.png) It's possible to create a [gource](https://code.google.com/p/gource/) video to display the sms activity by using the script in the ```gource``` folder. ## Examples * [SMS Activity with Users](https://vimeo.com/58178587) * [SMS Activity without Users](https://vimeo.com/58249481) # Know issues * Current limitation to about 1 sms every 3 seconds on a HTC Desire. This could be due to gsm network or SMS Gateway application, more tests need to be done to improve this performance issue * This installation might not be gsm-contract-compliant, you might need to ask your gsm provider before abusing their network and risking getting your access down * Some issues opening the moderation interface on Windows <file_sep>/Gemfile source "http://rubygems.org" gem "sinatra" gem "dm-core" gem "dm-migrations" gem "dm-timestamps" gem "dm-serializer" gem "dm-sqlite-adapter" gem "nokogiri" gem "multi_json", "1.7.8" <file_sep>/export_csv.sh #!/bin/sh # to use: ./export_csv.sh >out.csv sqlite3 ./smssync.db <<! .headers on .mode csv .output out.csv select * from messages; ! <file_sep>/public/scripts/main.js //var root = "http://localhost:4567"; var root = ""; var displayHiddenNumbers = true; var timeout = 60; /****** * Recents *****/ var updateNbRecents = function() { $("#nb-recents").html($('#recents .message').length); } var refreshRecent = function() { $("#recents-timeout").html(timeout); $.getJSON(root + "/recents.json", function(json) { if(!displayHiddenNumbers) { json.filter(function(element) { return !element.is_hidden; }); } // var output = $.map(json, function(element) { // // var elementHtml = "<div id='element-" + element.id + "' class='row-fluid'><div class='row'><div class='span2'>"; // elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; // elementHtml += element.msg + "</div></div><div class='row align-right'>"; // elementHtml += "<span class='badge'>" + element.phone_valid_messages + "/" + element.phone_messages + "</span> "; // elementHtml += "<button class='select btn btn-success' type='button'>Ok</button> "; // elementHtml += "<button class='reject btn btn-danger' type='button'>No</button></div></div>"; // // return elementHtml; // }); // $("#recents").html(output.join("")); // for(i = 0; i < json.length; i++) { var element = json[i]; if($("#recents #element-" + element.id).length == 0) { var elementHtml = "<div id='element-" + element.id + "' class='row-fluid message'><div class='row'><div class='span2'>"; elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; elementHtml += element.msg + "</div></div><div class='row align-right'>"; if(element.phone_valid_messages == 1) { elementHtml += "<span class='badge badge-warning'>"; } else if(element.phone_valid_messages > 1) { elementHtml += "<span class='badge badge-important'>"; } else { elementHtml += "<span class='badge'>"; } elementHtml += element.phone_valid_messages + "/" + element.phone_messages + "</span> "; elementHtml += "<button class='select btn btn-mini btn-success' type='button'><i class='icon-home icon-white'></i></button> "; elementHtml += "<button class='reject btn btn-mini btn-danger' type='button'><i class='icon-trash icon-white'></i></button></div>"; elementHtml += "<div class='row align-right'><span class='badge messageListSelector messageListSelector-1'>1</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-2'>2</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-3'>3</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-4'>4</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-5'>5</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-6'>6</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-7'>7</span></div>"; elementHtml += "</div>"; $("#recents").prepend(elementHtml); } } updateNbRecents(); }); } $("#recents-refresh").live("click", function() { refreshRecent(); }); $("#recents button.select").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $(parent).remove(); $.post(root + "/messages/" + msgId, {action: 'select', list_index: findListIndex()}, function() { refreshSelected(); }); }); $("#recents .messageListSelector").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $(parent).remove(); $.post(root + "/messages/" + msgId, {action: 'select', list_index: $(this).html()}, function() { refreshSelected(); }); }); $("#recents button.reject").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $(parent).remove(); $.post(root + "/messages/" + msgId, {action: 'reject'}, function() { refreshSelected(); }); }); $("#delete-received").live("click", function() { $("#recents .message").remove(); $.post(root + "/delete_received"); updateNbRecents(); }); $("#hidden-numbers").live("click", function() { var button = $(this); if(button.hasClass('btn-inverse')) { displayHiddenNumbers = false; button.removeClass('btn-inverse'); button.find('i').removeClass('icon-ok icon-white').addClass('icon-remove'); } else { displayHiddenNumbers = true; button.addClass('btn-inverse'); button.find('i').removeClass('icon-remove').addClass('icon-white icon-ok'); } refreshRecent(); }); $("#refresh-recents").live("click", function() { refreshRecent(); }); /****** * Selected *****/ var updateListCount = function() { $('#selected_count_all').html($('#selected .message').length); for(i = 1; i <= 7; i++){ var listCount = $('#selected_count_list_' + i); listCount.removeClass('warning over'); listCount.html($('#selected .active.messageListSelector-' + i).length); if(parseInt(listCount.html()) == parseInt($('#quota_list_' + i).val())) { listCount.addClass('warning'); } else if(parseInt(listCount.html()) > parseInt($('#quota_list_' + i).val())) { listCount.addClass('over'); } } } /* * find a possible list where to put a new message. * if no list found, wend this message to list 6 */ var findListIndex = function() { for(i = 1; i <= 6; i++) { if( !$('#selected_count_list_' + i).hasClass('warning') && !$('#selected_count_list_' + i).hasClass('over') ) { return i; } } return 6; } var refreshSelected = function() { $.getJSON(root + "/selected.json", function(json) { // var output = $.map(json.messages, function(element) { // var elementHtml = ""; // if($("#selected #element-" + element.id).length == 0) { // elementHtml = "<div id='element-" + element.id + "' class='row-fluid'><div class='row'><div class='span2'>"; // elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; // elementHtml += element.msg + "</div></div><div class='row align-right'>"; // // if(element.is_favorite) { // elementHtml += "<button class='favorite btn btn-warning' type='button'><i class='icon-white icon-star'></i></button> "; // } else { // elementHtml += "<button class='favorite btn' type='button'><i class='icon-star'></i></button> "; // } // // elementHtml += "<button class='reject btn btn-danger' type='button'>No</button></div></div>"; // } // return elementHtml; // }); // $("#selected").html(output.join("")); for(i = 0; i < json.messages.length; i++) { var element = json.messages[i]; if($("#selected #element-" + element.id).length == 0) { var elementHtml = "<div id='element-" + element.id + "' class='row-fluid message'><div class='row'>"; elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='row'>"; elementHtml += element.msg + "</div><div class='row align-right'>"; if(element.is_favorite) { elementHtml += "<button class='favorite btn btn-warning btn-mini' type='button'><i class='icon-white icon-star'></i></button> "; } else { elementHtml += "<button class='favorite btn btn-mini' type='button'><i class='icon-star'></i></button> "; } elementHtml += "<button class='reject btn btn-danger btn-mini' type='button'><i class='icon-trash icon-white'></i></button></div>"; elementHtml += "<div class='row align-right'><span class='badge messageListSelector messageListSelector-1'>1</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-2'>2</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-3'>3</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-4'>4</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-5'>5</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-6'>6</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-7'>7</span></div>"; elementHtml += "</div>"; $("#selected").prepend(elementHtml); if(element.list_index > 0) { $('#selected #element-' + element.id + ' .messageListSelector-' + element.list_index).addClass('active'); $('#selected_count_list_' + element.list_index).html( parseInt($('#selected_count_list_' + element.list_index).html()) + 1 ); } } } updateListCount(); updateNbRecents(); $("#selected_id").html(json.id); }); } $('#selected .messageListSelector').live('click', function() { var button = $(this); var parent = button.parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'change_list', list_index: button.html()}, function() { parent.find('.messageListSelector').removeClass('active'); button.addClass('active'); updateListCount(); }); }); $("button.favorite").live("click", function() { var button = $(this); var parent = button.parents(".message"); var msgId = parent.attr("id").split("-")[1]; // Message is already favorite if(button.hasClass('btn-warning')) { $.post(root + "/messages/" + msgId, {action: 'unfavorite'}, function() { button.removeClass('btn-warning'); button.find('i').removeClass('icon-white'); refreshFavorites(); }); } else { $.post(root + "/messages/" + msgId, {action: 'favorite'}, function() { button.addClass('btn-warning'); button.find('i').addClass('icon-white'); refreshFavorites(); }); } }); $("#selected button.reject").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $(parent).remove(); $.post(root + "/messages/" + msgId, {action: 'reject'}); updateListCount(); }); $("#new-selection").live("click", function() { $("#selected .message").remove(); $("#selected_id").html(parseInt($("#selected_id").html()) + 1); $.post(root + "/selection"); updateListCount(); }); /****** * Favorites *****/ var refreshFavorites = function() { $("#favorites .message").remove(); $.getJSON(root + "/favorites.json", function(json) { for(i = 0; i < json.length; i++) { var element = json[i]; var elementHtml = "<div id='element-" + element.id + "' class='row-fluid message'><div class='row'><div class='span2'>"; elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; elementHtml += element.msg + "</div></div><div class='row align-right'>"; if(element.is_favorite) { elementHtml += "<button class='favorite btn btn-warning btn-mini' type='button'><i class='icon-white icon-star'></i></button> "; } else { elementHtml += "<button class='favorite btn btn-mini' type='button'><i class='icon-star'></i></button> "; } elementHtml += "<button class='select btn btn-info btn-mini' type='button'>Select</button></div>"; elementHtml += "<div class='row align-right'><span class='badge messageListSelector messageListSelector-1'>1</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-2'>2</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-3'>3</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-4'>4</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-5'>5</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-6'>6</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-7'>7</span></div>"; elementHtml += "</div>"; $("#favorites").prepend(elementHtml); } $("#nb-favorites").html(json.length); }); } $("#favorites button.select").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'duplicate', list_index: findListIndex()}, function() { refreshSelected(); }); }); $("#favorites .messageListSelector").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'duplicate', list_index: $(this).html()}, function() { refreshSelected(); }); }); /****** * All *****/ var refreshAll = function() { $("#all .message").remove(); $.getJSON(root + "/all.json", function(json) { for(i = 0; i < json.length; i++) { var element = json[i]; var elementHtml = "<div id='element-" + element.id + "' class='row-fluid message'><div class='row'><div class='span2'>"; elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; elementHtml += element.msg + "</div></div><div class='row align-right'>"; if(element.is_favorite) { elementHtml += "<button class='favorite btn btn-warning btn-mini' type='button'><i class='icon-white icon-star'></i></button> "; } else { elementHtml += "<button class='favorite btn btn-mini' type='button'><i class='icon-star'></i></button> "; } elementHtml += "<button class='select btn btn-info btn-mini' type='button'>Select</button></div>"; elementHtml += "<div class='row align-right'><span class='badge messageListSelector messageListSelector-1'>1</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-2'>2</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-3'>3</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-4'>4</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-5'>5</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-6'>6</span>"; elementHtml += "<span class='badge messageListSelector messageListSelector-7'>7</span></div>"; elementHtml += "</div>"; $("#all").prepend(elementHtml); } }); } $("#display-all").live("click", function() { refreshAll(); }); $("#all button.select").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'duplicate', list_index: findListIndex()}, function() { refreshSelected(); }); }); $("#all .messageListSelector").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'duplicate', list_index: $(this).html()}, function() { refreshSelected(); }); }); /****** * Latest *****/ var refreshLatest = function() { $("#latest .row-fluid").remove(); $.getJSON(root + "/latest.json", function(json) { for(i = 0; i < json.length; i++) { var element = json[i]; var elementHtml = "<div id='element-" + element.id + "' class='row-fluid message'><div class='row'><div class='span2'>"; elementHtml += "<span class='label label-info'>" + element.hours + "</span></div><div class='span10'>"; elementHtml += element.msg + "</div></div><div class='row align-right'>"; if(element.is_favorite) { elementHtml += "<button class='favorite btn btn-warning' type='button'><i class='icon-white icon-star'></i></button> "; } else { elementHtml += "<button class='favorite btn' type='button'><i class='icon-star'></i></button> "; } elementHtml += "<button class='select btn btn-info' type='button'>Select</button></div></div>"; $("#latest").prepend(elementHtml); } }); } $("#latest button.select").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'select', list_index: findListIndex()}, function() { refreshSelected(); }); }); $("#latest .messageListSelector").live("click", function() { var parent = $(this).parents(".message"); var msgId = parent.attr("id").split("-")[1]; $.post(root + "/messages/" + msgId, {action: 'select', list_index: $(this).html()}, function() { refreshSelected(); }); }); /****** * Stats *****/ var refreshStats = function() { $.getJSON(root + "/stats.json", function(json) { $("#stats-messages").html(json.messages); $("#stats-selected_messages").html(json.selected_messages); $("#stats-selections").html(json.selections); $("#stats-favorites").html(json.favorites); Morris.Line({ element: 'line', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Received', 'Selected'] }); }); } $('.display_list').click(function() { var list = $(this).data('list'); if(list == 'all') { $('#selected .message').show(); } else { $('#selected .message').hide(); $('#selected .active.messageListSelector-' + list).parents('.message').show(); } }); /****** * Main *****/ refreshRecent(); refreshSelected(); refreshFavorites(); refreshLatest(); setInterval(function(){refreshRecent()}, timeout * 1000); setInterval(function(){$("#recents-timeout").html(parseInt($("#recents-timeout").html()) - 1)}, 1000); setInterval(function(){$.getJSON(root + "/fetch_messages");}, timeout / 3 * 1000); var windowHeight = $(window).height(); var offset = 120; $("#recents").css("max-height", windowHeight - offset); $("#selected").css("max-height", windowHeight - offset); $("#favorites").css("max-height", windowHeight - offset); $("#all").css("max-height", windowHeight - offset); <file_sep>/app.rb # encoding: utf-8 require 'rubygems' require 'sinatra' gem 'multi_json', '=1.7.8' require 'json' require 'date' require 'net/http' gem 'dm-core' gem 'dm-timestamps' gem 'dm-migrations' gem 'dm-serializer' require 'dm-core' require 'dm-timestamps' require 'dm-migrations' require 'dm-serializer' require 'nokogiri' require 'yaml' #log = File.new("sinatra.log", "a") #STDOUT.reopen(log) #STDERR.reopen(log) # ============ # Esendex conf # ============ # ====== # Models # ====== DataMapper.setup(:default, "sqlite3:///#{Dir.pwd}/db/smssync.db") class Message include DataMapper::Resource property :id, Serial property :msg, Text property :tel, String property :esendex_id, String property :created_at, DateTime property :validated_at, DateTime property :is_valid, Boolean, :default => false property :is_favorite, Boolean, :default => false property :list_index, Integer, :default => 0 has n, :selections, :through => Resource def to_json(args) output = { :id => self.id, :msg => self.msg, :date => self.created_at, :hours => self.created_at.strftime("%H:%M"), :is_valid => self.is_valid, :is_favorite => self.is_favorite, :is_hidden => self.tel.empty?, :list_index => self.list_index } output[:phone_messages] = Message.all(:tel => self.tel).size output[:phone_valid_messages] = Message.all(:tel => self.tel, :is_valid => true).size output end def to_epoch @created_at.to_time.to_i end end class Selection include DataMapper::Resource property :id, Serial property :created_at, DateTime has n, :messages, :through => Resource end DataMapper.finalize # init database if not already created begin @selection = Selection.first rescue DataMapper.auto_migrate! @selection = Selection.new @selection.save end # ============= # Configuration # ============= configure do set :static, true end # ==== # Main # ==== get '/' do if params['device'] == 'gateway' Message.create :msg => params['text'], :tel => params['phone'] else send_file File.expand_path('public/index.html', '.') end end # ========== # Stats JSON # ========== get '/gource.log' do messages = [] 8.times do |i| date_start = DateTime.new(2012, 12, 15 + i, 17, 30) end_date = DateTime.new(2012, 12, 15 + i, 19, 30) date_epoch = date_start.to_time.to_i Message.all(:is_valid => true, :created_at.gt => date_start, :created_at.lt => end_date).each do |msg| path = "#{date_start.strftime "%d_%m_%Y"}/" if msg.is_valid path += "#{msg.selections.first.id}" else path = "" end path += "/#{msg.msg}" # Let them eat cake # http://www.colourlovers.com/palette/49963/let_them_eat_cake # background: 774F38 colors = ["ECE5CE", "E08E79", "F1D4AF", "C5E0DC"] # (◕_”_◕) # http://www.colourlovers.com/palette/848743/(%E2%97%95_%E2%80%9D_%E2%97%95) # background: 490A3D colors = ["8A9B0F", "BD1550", "F8CA00", "E97F02"] color = colors[0] text = msg.msg if text =~ /aime|amour|<3/i color = colors[1] elsif text =~ /epous|mari|femme/i color = colors[2] elsif text =~ /anniversaire|paix|reve/i color = colors[3] end date = msg.to_epoch - date_epoch messages << [date, msg.tel, "A", path, color].join("|") end end messages.sort! do |a, b| a.split("|")[0].to_i <=> b.split("|")[0].to_i end return messages.join "\n" end get '/stats.json' do stats = { :messages => Message.count, :selected_messages => 0, :selections => Selection.count, :favorites => Message.count(:is_favorite => true), } stats[:words] = {} stats[:words][:aime] = Message.all.reject{|msg| msg.msg.index("aime").nil?}.size + Message.all.reject{|msg| msg.msg.index("amour").nil?}.size + Message.all.reject{|msg| msg.msg.index("<3").nil?}.size stats[:words][:marriage] = Message.all.reject{|msg| msg.msg.index("epou").nil?}.size + Message.all.reject{|msg| msg.msg.index("mari").nil?}.size + Message.all.reject{|msg| msg.msg.index("femme").nil?}.size stats[:words][:anniversaire] = Message.all.reject{|msg| msg.msg.index("anniversaire").nil?}.size stats[:words][:paix] = Message.all.reject{|msg| msg.msg.index("paix").nil?}.size stats[:words][:reve] = Message.all.reject{|msg| msg.msg.index("rêve").nil?}.size first_date = DateTime.new(2012, 12, 15) stats[:by_day] = { :testing => { :messages => Message.all(:created_at.lt => first_date).size, :selections => Selection.all(:created_at.lt => first_date).size }, :days => [] } 9.times do |day| selections = Selection.all(:created_at.gt => first_date, :created_at.lt => first_date + 1) selected = 0 message_count = Message.all(:created_at.gt => first_date, :created_at.lt => first_date + 1).size selections.each do |selection| selected += selection.messages.size end average = 0 ratio = 0 if selected != 0 average = (selected.to_f / selections.size.to_f ).to_i ratio = ((selected.to_f / message_count.to_f ) * 100).to_i end stats[:by_day][:days] << { :messages => message_count, :selected => selected, :selections => selections.size, :average_selection => average, :ratio_selected => ratio } first_date += 1 end stats[:selections_details] = [] Selection.all.each do |selection| messages = selection.messages.size stats[:selected_messages] += messages stats[:selections_details] << { :id => selection.id, :messages => messages, :created_at => selection.created_at } end messages = Message.all stats[:messages_details] = { :first => { :id => messages.first.id, :created_at => messages.first.created_at }, :last => { :id => messages.last.id, :created_at => messages.last.created_at }, :count_5m => [] } current_date = messages.first.created_at last_date = messages.last.created_at current_count = 1 messages.each do |msg| if (msg.created_at.to_time.to_i - current_date.to_time.to_i) < 500 current_count += 1 else stats[:messages_details][:count_5m] << current_count current_count = 1 current_date = msg.created_at end end stats[:morris] = [] today_messages = Message.all(:created_at.gt => Date.today) return stats.to_json end # ============= # Messages JSON # ============= get '/selected.json' do selection = Selection.last return {:id => selection.id, :messages => selection.messages}.to_json end get '/recents.json' do return Message.all(:validated_at => nil, :order => [ :created_at.desc ]).to_json end get '/favorites.json' do return Message.all(:is_favorite => true).to_json end get '/all.json' do return Message.all(:is_valid => true).to_json end get '/latest.json' do return Message.all(:is_valid => true, :limit => 4, :order => [:created_at.desc]).to_json end # ================ # Messages Actions # ================ post '/delete_received' do Message.all(:validated_at => nil).each do |m| m.update(:validated_at => Time.now) end return {:status => "ok"}.to_json end post '/messages/:id' do msg = Message.get(params[:id]) not_found unless msg case params[:action] when "select" msg.update(:is_valid => true, :validated_at => Time.now) if params[:list_index] msg.update(:list_index => params[:list_index]) end selection = Selection.last selection.messages << msg selection.save when "duplicate" new_msg = Message.create( :tel => msg.tel, :msg => msg.msg, :is_valid => true, :validated_at => msg.validated_at ) if params[:list_index] new_msg.update(:list_index => params[:list_index]) end selection = Selection.last selection.messages << new_msg selection.save when "change_list" msg.update(:list_index => params[:list_index]) when "favorite" msg.update(:is_favorite => true) when "unfavorite" msg.update(:is_favorite => false) when "reject" selection = Selection.last selection.messages.delete(msg) selection.save msg.update(:is_valid => false, :validated_at => Time.now) end return {:status => "ok"}.to_json end # ================= # Selection Actions # ================= get '/messages.txt' do selection = Selection.last messages = selection.messages return "&vMessageListe=#{messages.map{|m| m.msg}.join('|').gsub("&", "et")}\n&vTxt_version=#{Selection.last.id}" end get %r{/messages_(\d+).txt} do |list_index| selection = Selection.last messages = selection.messages.all(:list_index => list_index, :order => [ :validated_at.asc ]) return "&vMessageListe=#{messages.map{|m| m.msg}.join('|').gsub("&", "et")}\n&vTxt_version=#{Selection.last.id}&list_index=#{list_index}" end post '/selection' do Selection.create end # ==== # Misc # ==== get '/create_dummies' do Message.create(:msg => "Vu des montage de Kinect (camera usb aussi) sur trépied si ça peut aider, faut contact ML tetalab, sinon je vois pas trop", :tel => "007") Message.create(:tel => "007", :msg => "@tetalab sinon, vous faites un projet pour empreint numérique cette année ?") Message.create(:tel => "007", :msg => "ouep, nickel un court panorama :)") Message.create(:tel => "007", :msg => "#FF les assos présentes au #capitoledulibre le samedi 24/10, notamment @Wikimedia_Fr, @framasoft, @OSM_FR et #tetaneutral avec @lguerby") end # ==== # Esendex # ==== def fetch_messages if File.file? "conf/esendex.yml" esendex_conf = YAML.load_file("conf/esendex.yml") end auth = esendex_conf["auth"] http = Net::HTTP.new('api.esendex.com', 80) begin req = Net::HTTP::Get.new('/v1.0/inbox/messages') req.basic_auth auth["login"], auth["pass"] response = http.request(req) doc = Nokogiri.XML(response.body) count = doc.at('messageheaders').attribute('count').text().to_i if count > 0 doc.css('messageheader').each do |message| begin body_uri = message.at('body').attribute('uri').text.gsub("http://api.esendex.com", "") req = Net::HTTP::Get.new(body_uri) req.basic_auth auth["login"], auth["pass"] response = http.request(req) body = Nokogiri.XML(response.body) esendex_id = message.attribute('id').text if Message.count(:esendex_id => esendex_id) == 0 Message.create( :msg => body.at("bodytext").text, :tel => message.at('from phonenumber').text, :esendex_id => esendex_id ) end begin req = Net::HTTP::Delete.new("/v1.0/inbox/messages/#{esendex_id}") req.basic_auth auth["login"], auth["pass"] response = http.request(req) rescue end rescue end end end rescue end end get '/fetch_messages' do fetch_messages return 200 end get '/send_messages' do Net::HTTP.start('api.esendex.com', 80) {|http| req = Net::HTTP::Post.new('/v1.0/messagedispatcher') req.basic_auth '', '' response = http.request(req) return response.body } end <file_sep>/gource/gource.sh #!/bin/sh rm gource.log wget http://127.0.0.1:9393/gource.log gource --camera-mode overview \ --file-idle-time 0 \ --bloom-multiplier 1.2 \ --bloom-intensity 0.4 \ -e 0.5 \ --background 490A3D \ --font-size 20 \ --font-colour EEEEEE \ --title "Holon - Decembre 2012" \ --hide date,filenames,mouse,progress,usernames,users \ -1280x800 -o gource.ppm gource.log ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i gource.ppm -vcodec libx264 -preset ultrafast -crf 1 -threads 0 -bf 0 gource.mp4 #ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i gource.ppm -vcodec libvpx -b 10000K gource.webm
a35c987e666f1dce2da9b789dc740dd25f78bec8
[ "Markdown", "JavaScript", "Ruby", "Shell" ]
6
Markdown
alx/smsModeration
2187dc21ff1cf031c6f94f9af0cca07180052172
0493d61399a78f43dc0285add9d37bd56116ec9d
refs/heads/master
<repo_name>arunvelsriram/BrightnessControl<file_sep>/backlight.sh #!/usr/bin/env bash PATH_TO_FILE="/sys/class/backlight/intel_backlight/brightness" if [[ $# == 1 && ($1 == "-u" || $1 == "-d") ]]; then if [[ $1 == "-u" ]]; then newb=$(($(<$PATH_TO_FILE) + 250)) else newb=$(($(<$PATH_TO_FILE) - 250)) fi #echo $newb echo $newb > /sys/class/backlight/intel_backlight/brightness else echo -e "USAGE:\n python brightness_control.py option\nOPTIONS:\n -u, Increase brightness\n -d, Decrease brightness" fi<file_sep>/README.md BrightnessControl =========== Shell script to control screen brightness in Ubuntu Linux. ##Usage $ sudo backlight.sh -u | -d -u Increases brightness -d Decrease brightness ##More Fun ###Creating your own command * Move the script backlight.sh to */usr/bin/* `$ sudo mv backlight.sh /usr/bin/backlight` * Now its possible to execute the script from anywhere in the commandline without the .sh extension `$ sudo backlight -u | -d` ###Executing the script without password * As the script requires more privileges, we have to run it with *sudo* and type in the password * To avoid this lets modify the *sudoers file* to allow the current user to execute the command without password * Open the *sudoers file*: `$ sudo visudo ` * Add the following line to the file `username ALL=(ALL) NOPASSWD: /usr/bin/backlight` where username is your username * Press Control + X to save the file and reboot your system * After the reboot you can run the command without entering the password ###Control brightness on keypress * It makes our life easier if we are able to raise/lower brightness using keyboard. It's very easy. * Install *xbindkeys* using the following command: `$ sudo apt-get install xbindkeys` * Next we have to create a configuration file for *xbindkeys* in the home directory `$ xbindkeys --defaults > $HOME/.xbindkeysrc` where $HOME referes to your home directory * Open the configuration file: `$ nano .xbindkeysrc` * Add your configuration which is a pair of key and a command to execute on pressing that key. ``` "sudo backlight -u" Control + Right "sudo backlight -d" Control + Left ``` * Save the file and close it. * Run xbindkeys `$ xbindkeys` * Now pressing *Control + Right* should increase the brightness and *Control + Right* decreases it. * To make *xbindkeys* stop listening to key presses: `$ killall -HUP xbindkeys` ##Devices Checked in Ubuntu 14.04 64-bit Linux on Dell Inspiron N4010. It will work in all Dell Inspirons I guess. About other laptops I don't know SORRY! ###Author [<NAME>](http://github.com/arunvelsriram) ###Contact Email : <EMAIL> [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/arunvelsriram/brightnesscontrol/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
5c75bb569463229f47c2cb7661483d27c6757336
[ "Markdown", "Shell" ]
2
Shell
arunvelsriram/BrightnessControl
14d4d3fbf2a7e1c8158ca018d884a1a0bbacbd04
6c3749b9ad96b0fe22d38258a87a9bfee6b0c073
refs/heads/main
<repo_name>jinie/rclone_mounter<file_sep>/Mounter.py #!/usr/local/bin/python3 import os import subprocess import sys import logging import configparser import psutil import signal # User Configuration user_home = os.environ["HOME"] mount_root = user_home rclone_config = os.path.join(user_home, ".config", "rclone", "rclone.conf") rclone_binary = "/usr/local/bin/rclone" logging_level = logging.INFO log_folder = os.path.join(user_home, "Library", "Logs", "Mounter") rclone_logging_flags = [] # We assume the data will only be changed through this remote, # and not by any other means, including web interface or another rclone instance, # we are going to effectively disable remote refresh uber_important_rclone_options = [ # # to avoid I/O errors when file is considered "harmful" by Google "--drive-acknowledge-abuse", # # Full cache mode for best compatibility "--vfs-cache-mode", "full", # # 1TB max total size cached "--vfs-cache-max-size", "1024G", # # Cache files forever "--vfs-cache-max-age", "1000h", # # Check cache for stale objects every so often. Default is 1m, 5 min is # good enough; we mainly want to remove files from cache once the size # exceeds the max-size above "--vfs-cache-poll-interval", "5m", # # time the kernel caches the attributes for. Reduces roundtrips to kernel, # no risk of corruption since files don't change externally. # Otherwise -- remove it! "--attr-timeout", "60s", # # Cache directories forever. # We can always send "SIGHUP" to force refresh directory caches "--dir-cache-time", "1000h", # # Don't poll for changes on remote "--poll-interval", "0", # # For how long kernel should wait before giving up. Imperative for mount stabilty "--daemon-timeout", "599s", # # Run as a daemon "--daemon", # # Statistics as one-liners "--stats-one-line", # # Adjust stats output to appear without -v "--stats-log-level", "NOTICE", # # Output statistics and progres periodically, until SIGINFO works in --daemon mode "--stats", "1m", # # Use Rclone RC https://rclone.org/rc/ "--rc", # # Use fast-list "--fast-list", # # Use a sane umask "--umask", "077", # # Allow root access for SMB sharing "--allow-root", ] + rclone_logging_flags # Executes the short running command line utility and logs outputs def run_helper(shortname, args): logging.info("Launching {}: {}".format(shortname, " ".join(args))) p = subprocess.run(args, capture_output=True, text=True) if p.stdout: logging.info("{}: {}".format(shortname, p.stdout)) if p.stderr: logging.error("{}: {}".format(shortname, p.stderr)) # Initialize logging if not os.path.exists(log_folder): run_helper("mkdir", ["mkdir", "-p", log_folder]) logging.basicConfig( filename=os.path.join(log_folder, "Mounter.log"), encoding="utf-8", format="%(asctime)s : %(levelname)s : %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p", level=logging_level, ) # Parser for rclone configuration remotes = configparser.ConfigParser() remotes.read(rclone_config) # We parse rclone.conf and look for remote names that don't match the below criteria def is_hidden(key): return ( key.endswith("-raw") or key.endswith("-intermediate") or key.endswith("-hidden") or key == "DEFAULT" ) # we use remote names to come up with user friendly titles like so def make_title(key): return key.replace("-", " ").title() # Mount points are also derived from the remote names def make_path(key): return os.path.join(mount_root, key) # Path for rclone log file def make_rclone_log_path(key): return os.path.join(log_folder, item + ".log") def build_list_of_active_daemons(): active_daemons = dict() # https://rclone.org/commands/rclone_mount/#vfs-directory-cache for p in psutil.process_iter(["name", "pid", "cmdline"]): if not p.name() == "rclone": continue try: cmdline = p.cmdline() except psutil.ZombieProcess: logging.warning("rclone({}) is a zombie process, skipped".format(p.pid)) continue except Exception as e: logging.info( "Exception occured getting a command line for rclone({}): {}".format( p.pid, e ) ) continue if "--daemon" not in cmdline: continue active_daemons[p.pid] = cmdline return active_daemons active_daemons = build_list_of_active_daemons() def flush_directory_caches(path=None): for pid, cmdline in active_daemons.items(): if not path or path in cmdline: logging.info("Flushing directory caches for {}({})".format("rclone", pid)) os.kill(pid, signal.SIGHUP) def refresh_directory_caches(): logging.info("Refreshing directory caches") run_helper("rclone",["rclone","rc","vfs/refresh","recursive=true","_async=true"]) def daemon_exists_for_path(path): for pid, cmdline in active_daemons.items(): if path in cmdline: return True return False # User visible prefixes and captions. Must be unique safe_unmount_caption = "⛔️ Unmount" force_unmount_caption = "❌ Force Unmount" mount_caption = "🎣 Mount" show_folder_caption = "📂 Show Mounted" show_log_caption = "🔍 Show Logs For" flush_directory_caches_for_caption = "🧹 Flush Dir Caches For" show_mounter_log_caption = "🔍 Show Mounter Log" flush_directory_caches_caption = "🧹 Flush All Dir Caches" refresh_directory_caches_caption = "🧹 Refresh All Dir Caches" # Populate the menu if no arguments passed by emitting menu item strings. if len(sys.argv) == 1: logging.info("Populating the menu") for item in remotes: if is_hidden(item): continue path = make_path(item) if os.path.ismount(path): print( "SUBMENU|🟢 {0}|{1} {0}|{2} {0}|{3} {0}|{4} {0}|{5} {0}".format( make_title(item), show_folder_caption, safe_unmount_caption, force_unmount_caption, flush_directory_caches_for_caption, refresh_directory_caches_caption, show_log_caption, ) ) elif daemon_exists_for_path(path): print( "SUBMENU|🟡 {0} [Working...]|{1} {0}".format( make_title(item), show_log_caption ) ) else: print( "SUBMENU|🔴 {0}|{1} {0}|{2} {0}".format( make_title(item), mount_caption, show_log_caption ) ) print("----") print(flush_directory_caches_caption) print(show_mounter_log_caption) else: action = sys.argv[1] target_matched = False logging.info('Action received: "{}"'.format(action)) for item in remotes: if is_hidden(item): continue path = make_path(item) if make_title(item) in action: target_matched = True if mount_caption in action: if not os.path.exists(path): run_helper("mkdir", ["mkdir", "-p", path]) run_helper( "rclone", [ rclone_binary, "--config", rclone_config, "mount", item + ":", path, "--volname", make_title(item), "--log-file", make_rclone_log_path(item), ] + uber_important_rclone_options, ) elif safe_unmount_caption in action: run_helper("unmount", ["/usr/sbin/diskutil", "unmount", path]) run_helper("rmdir", ["/bin/rmdir", path]) elif force_unmount_caption in action: run_helper("ummount", ["/usr/sbin/diskutil", "unmount", "force", path]) run_helper("rmdir", ["/bin/rmdir", path]) elif show_folder_caption in action: run_helper("open", ["open", path]) elif show_log_caption in action: run_helper("open", ["open", make_rclone_log_path(item)]) elif flush_directory_caches_for_caption in action: flush_directory_caches(path) elif refresh_directory_caches_caption in action: refresh_directory_caches() else: logging.error( 'Action "{}" is unrecognized for "{}".'.format( action, make_title(item) ) ) if not target_matched: if show_mounter_log_caption in action: run_helper("open", ["open", os.path.join(log_folder, "Mounter.log")]) elif flush_directory_caches_caption in action: flush_directory_caches() else: logging.error('Action "{}" is unrecognized. Doing nothing.'.format(action)) <file_sep>/README.md ## Platypus script for simple UI to mount and unmount rclone remotes on macOS ### Prerequisites - `rclone` from https://rclone.org, not brew - `macFUSE` from https://osxfuse.github.io - Python3 and pip3 - `platypus` from https://sveinbjorn.org/platypus ### Configuration Name rclone remotes with the expectation that the script: - Derives user-readable title from rclone remote name by replacing `-` with ` ` and converting to title case - Skips remote if its name ends with specific suffixes, such as `-hidden`, `-intermediate`, `-raw`, etc. This is handy when using crypt remote: you would not want to manually mount the underlying raw storage, only mount crypt remote. For example: ``` [google-drive] type = drive ... [encrypted-data-raw] type = drive ... [secret-encrypted-data] type = crypt remote = encrypted-data-raw: ... ``` will result in the main menu containing the following items (one shown as mounted, another unmounted for illustration purposes): 🟢 Google Drive <br> 🔴 Secret Encrypted Data<br> Each item will have a submenu, with the following actions: 📂 Show<br> ⛔️ Unmount<br> ❌ Force<br> 🎣 Mount<br> 🔍 Logs<br> ### Usage Checkout the repository and run the `make run` to create `Mounter.app` wrapper at `~/Applications` and launch it. Look for '🏔' in the menu bar. Run `make` without arguments to list available targets <file_sep>/Makefile LOCAL_TARGET="Mounter.app" TARGET="$(HOME)/Applications/Mounter.app" .PHONY: help help: @echo @echo "Available targets:" @echo @fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//' @echo @echo "Example: " @echo " make run" define check_install_shell @command -v $(1) > /dev/null || (echo "ERROR: $(1) is missing. $(2)"; exit 1) endef define check_install_pip3 @[[ ! -z $$(pip3 list | grep "$(1)" ) ]] || pip3 install $(1) endef .PHONY: check-tools check-tools: ## Check for tools and python modules. Installs python modules as needed @echo "Checking for tools" $(call check_install_shell,platypus,) $(call check_install_shell,python3,) $(call check_install_shell,rclone,Install directly from rclone.org. Homebrew version won't work) $(call check_install_shell,pip3,) $(call check_install_pip3,psutil) .PHONY: patch-rclone-path patch-rclone-path: ## Embed absolute path to rclone on this system to Mounter.py patch-rclone-path: check-tools @echo "Patching the rclone path in Mounter.py" @sed -i "" "s|rclone_binary = .*$$|rclone_binary = \"$$(which rclone)\"|g" Mounter.py define platypusify @echo targeting $(2) @mkdir -p "$(2)" @platypus --overwrite \ --background \ --name "Mounter" \ --interface-type "Status Menu" \ --status-item-kind "Text" --status-item-title '🏔' --status-item-sysfont \ --bundle-identifier "com.arrogantrabbit.mounter" \ "./Mounter.py" \ "$(2)" $(1) endef .PHONY: install install: ## Install the Platypus wrapper to "~/Applications" with default logging install: check-tools patch-rclone-path $(call platypusify,--optimize-nib,$(TARGET)) .PHONY: run run: ## Make and run wrapper. run: install @echo "Launching $(TARGET)" @open "$(TARGET)" .PHONY: check-tools-dev check-tools-dev: ## Checks for tools useful for development check-tools-dev: check-tools @echo "Checking for dev tools" $(call check_install_pip3,black) $(call check_install_pip3,flake8) .PHONY: format format: ## Run Black formatter and Flake8 format: check-tools-dev @python3 -m black --line-length 90 Mounter.py @python3 -m flake8 --max-line-length 90 Mounter.py .PHONY: install-dev install-dev: ## Create wrapper with symlink to script and verbose logging. install-dev: check-tools-dev format patch-rclone-path $(call platypusify,--symlink,$(LOCAL_TARGET)) .PHONY: run-dev run-dev: ## Make and run dev wrapper in local folder run-dev: install-dev @echo "Launching $(LOCAL_TARGET)" @open "$(LOCAL_TARGET)"
9f233a57fd5d6afd9d88cec028d923bd264da9ec
[ "Markdown", "Python", "Makefile" ]
3
Python
jinie/rclone_mounter
55261c986cb46e9712ee81255f161db09a06d03e
5849f9338fdb42c08625d45afd71af3e3146add4
refs/heads/master
<file_sep>import * as ts from 'typescript' import * as path from 'path' import { Config } from './types' import { createConfig, defaultConfig } from './config' import { removeUndefined } from './arrayFilters' import { createProgram } from './createProgram' import { visitSource } from './visitSource' import { emitFile } from './emitFile' // ______________________________________________________ // export function run(config: Config) { const printer = ts.createPrinter() const srcDir = path.resolve(config.srcDir) const distDir = path.resolve(config.distDir) const program: ts.Program = createProgram(srcDir, config) const checker: ts.TypeChecker = program.getTypeChecker() const sources: ts.SourceFile[] = program .getRootFileNames() .map(fileName => program.getSourceFile(fileName)) .filter(removeUndefined) if (sources.length) { sources.map(source => { const list = visitSource(source, checker) const fileBody = printer.printList(ts.ListFormat.MultiLine, list, source) const fileName = `${distDir}${source.fileName.replace(srcDir, '')}` emitFile(distDir, fileName, fileBody) }) } } if (process.env.NODE_ENV === 'development') { run(createConfig(defaultConfig)) } <file_sep>import * as ts from 'typescript' // ______________________________________________________ // export const getLastChild = (node: ts.Node) => { return node.getChildAt(node.getChildCount() - 1) } export const isDefaultImportClause = (node: ts.ImportClause) => { const child = node.getChildAt(0) return !( child.kind === ts.SyntaxKind.NamedImports || child.kind === ts.SyntaxKind.TypeKeyword ) } export const getImportPathIdentifier = ( node: ts.ImportDeclaration ): ts.Identifier => { const pathIdentifier = node.getChildAt(3) const text = pathIdentifier.getText() return ts.createIdentifier(text) } <file_sep>import * as ts from 'typescript' import { createConfigFileHost } from './createConfigFileHost' import { Config } from './types' // ______________________________________________________ // export function createProgram(searchPath: string, config: Config) { const configPath = ts.findConfigFile( searchPath, ts.sys.fileExists, config.tsconfigFileName ) if (!configPath) { throw new Error("Could not find 'tsconfig.json'.") } const parsedCommandLine = ts.getParsedCommandLineOfConfigFile( configPath, {}, createConfigFileHost() ) if (!parsedCommandLine) { throw new Error('invalid parsedCommandLine.') } if (parsedCommandLine.errors.length) { throw new Error('parsedCommandLine has errors.') } return ts.createProgram({ rootNames: parsedCommandLine.fileNames, options: parsedCommandLine.options }) } <file_sep>export function removeUndefined<T>(arg: T): arg is NonNullable<T> { return arg !== undefined } <file_sep>import type { TypeAlias } from './a' import { Interface } from './b' import { TypeAlias as TYPEALIAS, Const } from './a' import { Let, Interface as INTERFACE } from './b' // ______________________________________________________ // <file_sep>export let Let = 'let' export interface Interface { hello: 'world' } export default Let <file_sep># type-only-imports-converter This is Migration tool for new "Type-only" import clause (v3.8). By rearrange TypeScript AST Node, it take a new SRC code. ### Input ```typescript import type { TypeAlias } from './a' import { Interface } from './b' import { TypeAlias as TYPEALIAS, Const } from './a' import { Let, Interface as INTERFACE } from './b' ``` Type definitions are rewritten into "Type-only" import clauses, Classified as not affect runtime. ### Output ```typescript import { Const } from './a'; import { Let } from './b'; import type { TypeAlias, TypeAlias as TYPEALIAS } from './a'; import type { Interface, Interface as INTERFACE } from './b'; ``` # Try it. `lib` is the directory of the tool. Perform the conversion of `app/src`. ``` $ cd lib $ yarn install $ yarn dev ``` The converted SRC code is output to `app / dist`. <file_sep>import { Config } from './types' //_______________________________________________________ // export const defaultConfig: Config = { srcDir: '../app/src', distDir: '../app/dist', tsconfigFileName: 'tsconfig.json' } export const createConfig = (injects?: Config): Config => ({ ...defaultConfig, ...injects }) <file_sep>import * as ts from 'typescript' // ______________________________________________________ // export type Config = { srcDir: string distDir: string tsconfigFileName: string } export type ImportSpecifiersMap = { [k: string]: ts.ImportSpecifier[] } <file_sep>export type TypeAlias = { hello: 'world' } export const Const = 'Const' <file_sep>import * as ts from 'typescript' // ______________________________________________________ // export const createConfigFileHost = (): ts.ParseConfigFileHost => ({ useCaseSensitiveFileNames: false, readDirectory: ts.sys.readDirectory, fileExists: ts.sys.fileExists, readFile: ts.sys.readFile, getCurrentDirectory: ts.sys.getCurrentDirectory, onUnRecoverableConfigFileDiagnostic(diagnostic: ts.Diagnostic) { throw new Error( ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n') ) } }) <file_sep>import * as ts from 'typescript' import { ImportSpecifiersMap } from './types' import { isDefaultImportClause, getImportPathIdentifier } from './nodeHelpers' import { getSeparatedImportSpecifiers } from './getSeparatedImportSpecifiers' import { getImportDeclarationsFromImportSpecifiersMap } from './getImportDeclarationsFromImportSpecifiersMap' // ______________________________________________________ // export function visitSource( source: ts.SourceFile, checker: ts.TypeChecker ): ts.NodeArray<ts.Node> { const indifferenceElements: ts.Node[] = [] const typeImportSpecifiersMap: ImportSpecifiersMap = {} const nonTypeImportSpecifiersMap: ImportSpecifiersMap = {} source.forEachChild(node => { // ImportDeclaration 以外は除外 if (!ts.isImportDeclaration(node)) { indifferenceElements.push(node) return } // 型宣言・非型宣言の格納M配列Mapを作成、同様の import path の場合マージする const pathIdentifier = getImportPathIdentifier(node) if (!typeImportSpecifiersMap[pathIdentifier.text]) { typeImportSpecifiersMap[pathIdentifier.text] = [] } if (!nonTypeImportSpecifiersMap[pathIdentifier.text]) { nonTypeImportSpecifiersMap[pathIdentifier.text] = [] } // ImportDeclaration の場合処理続行 function visit(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.ImportClause: if (!ts.isImportClause(node)) return // DefaultImport の場合 if (isDefaultImportClause(node)) { indifferenceElements.push( ts.createImportDeclaration( undefined, undefined, node, pathIdentifier ) ) break } // NamedImports の場合、型宣言・非型宣言の格納配列を取得 const [ typeImportSpecifiers, nonTypeImportSpecifiers ] = getSeparatedImportSpecifiers(node, checker) typeImportSpecifiersMap[pathIdentifier.text].push( ...typeImportSpecifiers ) nonTypeImportSpecifiersMap[pathIdentifier.text].push( ...nonTypeImportSpecifiers ) } ts.forEachChild(node, visit) } visit(node) }) return ts.createNodeArray([ ...getImportDeclarationsFromImportSpecifiersMap( nonTypeImportSpecifiersMap, false ), ...getImportDeclarationsFromImportSpecifiersMap( typeImportSpecifiersMap, true ), ...indifferenceElements ]) } <file_sep>import * as ts from 'typescript' import { getLastChild } from './nodeHelpers' // ______________________________________________________ // function isTypeSymbol(symbol: ts.Symbol) { return ( symbol.flags === ts.SymbolFlags.Interface || symbol.flags === ts.SymbolFlags.TypeAlias ) } // ______________________________________________________ // export const getSeparatedImportSpecifiers = ( node: ts.Node, checker: ts.TypeChecker ) => { const [ typeImportSpecifiers, nonTypeImportSpecifiers ]: ts.ImportSpecifier[][] = [[], []] function visit(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.ImportSpecifier: if (!ts.isImportSpecifier(node)) return const symbol = checker.getSymbolAtLocation(getLastChild(node)) if (symbol?.flags !== ts.SymbolFlags.Alias) { nonTypeImportSpecifiers.push(node) return } // 参照適用シンボルを取得 const aliasedSymbol = checker.getAliasedSymbol(symbol) if (!isTypeSymbol(aliasedSymbol)) { nonTypeImportSpecifiers.push(node) return } typeImportSpecifiers.push(node) } ts.forEachChild(node, visit) } visit(node) return [typeImportSpecifiers, nonTypeImportSpecifiers] } <file_sep>import * as fs from 'fs-extra' // ______________________________________________________ // export const emitFile = ( distDir: string, fileName: string, fileBody: string ) => { if (!fs.existsSync(distDir)) { fs.mkdirsSync(distDir) } fs.writeFileSync(fileName, fileBody) } <file_sep>import * as ts from 'typescript' import { ImportSpecifiersMap } from './types' // ______________________________________________________ // const createImportDeclaration = ( importClause: ts.ImportClause, moduleSpecifier: ts.Expression ) => ts.createImportDeclaration( undefined, undefined, importClause, moduleSpecifier ) // ______________________________________________________ // export const getImportDeclarationsFromImportSpecifiersMap = ( importSpecifiersMap: ImportSpecifiersMap, isTypeOnly: boolean ) => { const importDeclarations: ts.ImportDeclaration[] = [] Object.keys(importSpecifiersMap).forEach(key => { const elements: ts.ImportSpecifier[] = importSpecifiersMap[key] if (!elements.length) return importDeclarations.push( createImportDeclaration( ts.createImportClause( undefined, ts.createNamedImports(elements), isTypeOnly ), ts.createIdentifier(key) ) ) }) return importDeclarations }
43e39f9790c8a578cf207855998398a826554aa0
[ "Markdown", "TypeScript" ]
15
TypeScript
takefumi-yoshii/type-only-imports-converter
21a81621a86a5675b293a429a732150b307ed1c2
f35c214837bb762ccf1b8ed965c08dd836e3f8f0
refs/heads/master
<file_sep>import os import sys import subprocess import zipfile if (os.getcwd().endswith('scripts')): os.chdir('..') from classes.database import * db = Database('pokemaster_v1.5-alpha3.db') # games = db.getAllGames() games = db.getAllGames("game.zxdb_id=2176") print(len(games)) conversion_list = {} for game in games: tzx_found = False tap_found = False if game.name.startswith('ZZZ-UNK'): continue for game_file in game.getFiles(): if game_file.format == 'tap': tap_found = True elif game_file.format == 'tzx': tzx_found = True if tzx_found and not tap_found: # print("TZX without TAP found:", game) for game_file in game.getFiles(): if game_file.format == 'tzx': # if game_file.wos_path: # key = 'ftp' + game_file.wos_path # elif game_file.tosec_path: # key = game_file.tosec_path # if not key.startswith('tosec'): # key = 'tosec/'+key # if not os.path.exists(key): #tzx should be unzipped first: # print(key, "does not exist") # key = key.lower().replace('.tzx', '.zip') # print("will open", key) # with zipfile.ZipFile(key) as zf: # if game_file.wos_name: # data = zf.read(game_file.wos_name) # else: # data = zf.read(os.path.basename(game_file.tosec_path)) # key = key.replace('.zip', 'tzx') # with open(key, 'wb') as f: # f.write(data) # print("saved", key) # if not os.path.exists(key): key = 'sorted/tzx_only/' + game_file.getOutputName("{Type}\\{TOSECName}") if not os.path.exists(key): print(key, "does not exist.") value = os.path.join('tosec', 'reviewed files', 'tzx2tap', game_file.getOutputName("{Type}\\{TOSECName}").replace('.tzx', '[m tzxtools].tap')) # print(value) conversion_list[key]=value # print(conversion_list) print(len(conversion_list)) # sys.exit() existing_tap_convertions = [value for value in conversion_list.values() if os.path.exists(value)] for root, dirs, files in os.walk("tosec\\reviewed files\\tzx2tap"): for file in files: path = os.path.join(root, file) for value in existing_tap_convertions: if os.path.abspath(path)==os.path.abspath(value): print("Should delete", value) sys.exit() for key, value in conversion_list.items(): os.makedirs(os.path.dirname(value), exist_ok=True) if os.path.exists(value): if os.path.getsize(value): # print("will skip", value) continue else: #size=0 os.unlink(value) command = 'tzxtap "{}" -o "{}" --ignore'.format(key, value) print(command) # continue s = subprocess.Popen(command) s.communicate() if not os.path.exists(value): print("Failed to create", value) elif not os.path.getsize(value): print("Failed to convert", key) os.unlink(value) else: print("Successfully created:", value)
d92c08bd7c41207ea257afa1d96f6702d699a130
[ "Python" ]
1
Python
gustavomonente/ZX-Pokemaster
0fa3ba177bd268a6dbbc8b95f4f801a56397d878
4e4023e7bbb5e6dffc423b0367f20593d408579d
refs/heads/main
<file_sep>#include<iostream> #include<fstream> #include<cstring> #include<stdlib.h> using namespace std; class shop { int No; char Shopname[20]; char OwnerName[20]; int EBbill; int WaterBill; int Rent; public: void sgetData() { cout<<"\nShop No : "; cin>>No; cout<<"\nShop name : "; cin>>Shopname; cout<<"\nOwner Name : "; cin>>OwnerName; cout<<"\nEB bill : "; cin>>EBbill; cout<<"\nWater Bill : "; cin>>WaterBill; cout<<"\nRent : "; cin>>Rent; } void sdisplay() { cout<<"\nTHE SHOP NUMBER: "<<No; cout<<"\n THE SHOP NAME: "<<Shopname; cout<<"\n THE SHOP OWNER NAME: "<<OwnerName; cout<<"\n THE EB-BILL RATE: "<<EBbill; cout<<"\n THE WATER BILL RATE: "<<WaterBill; cout<<"\n THE RENT RATE : "<<Rent<<"\n\n"; cout<<"\n---------------------------------------"; } char *getm() { return Shopname; } int num() { return No; } int rent() { return Rent; } void calcTotalRent(shop s[],int n) { int i=0,TotRent=0; for(i=0;i<n;i++) { TotRent=TotRent+s[i].Rent; } cout<<"\n\nTHE TOTAL RENT OF ALL THE SHOPS:"<<TotRent; } void findShopDetails(shop s[],int n) { int i=0,flag=0; string sname; char c='y'; while(c=='y'||c=='Y') { cout<<"\n\n ENTER THE SHOP NAME:"; cin>>sname; for(i=0;i<n;i++) { if(sname==s[i].Shopname) { s[i].sdisplay(); flag=flag+1; } } if(flag==0) { cout<<"\n\n THE SHOP DETAILS NOT FOUND:"; } cout<<"\n\n CONTINUE SEARCH(y/n):"; cin>>c; } } void NoofFreeShops(shop s[],int n) { int i=0,flag=0,flag1=0; for(i=0;i<n;i++) { if(!strcmp(s[i].Shopname,"NULL")) { flag++; if(flag1=0) { cout<<"\n[[[[<<<< THE EMPTY SHOPS ARE >>>>]]]]\n\n "; flag1++; } cout<<"\nTHE SHOP NUMBER IS:"<<s[i].No; } } if(flag==0) { cout<<"\n\n[[[[<<<<NO SHOPS ARE EMPTY>>>>]]]] "; } } }obj1; int main() { int option; shop e; shop b[50]; fstream fil; int income,Num; while(1) { cout<<"\n--------------------------------------------------------------------------------------------------------"; cout<<"\n\t\tSHOP DETAILS"; cout<<"\n--------------------------------------------------------------------------------------------------------"; cout<<"\n\t1.ADD NEW SHOP DETAILS\n\t2.DISPLAY AVAILABLE SHOPS\n\t3.DELETE A SHOP\n\t4.UPDATE A SHOP\n\t5.TOTAL RENT OF SHOPS\n\t6.SEARCH A SHOP DETAILs\n\t7.AVAILABLE FREE SHOPS \n\t8.EXIT"; cout<<"\n--------------------------------------------------------------------------------------------------------"; cout<<"\nEnter your option....."; cin>>option; switch(option) { case 1: { fstream f; f.open("s.dat",ios::app|ios::binary); e.sgetData(); income=income+e.rent(); f.write( (char*)&e, sizeof(shop) ); f.close(); break; } case 2: { ifstream infile("s.dat",ios::in|ios::binary); if(!infile) { cout<<"\nFile cannot be opened"; return 1; } cout<<"\n\t\t\t\t\tShop details....\n"; int i=0; while(infile) { infile.read((char*)&b[i],sizeof(shop)); if(infile) b[i].sdisplay(); i++; } Num=i; infile.close(); break; } case 3: { fstream a; int b; ofstream c("s1.dat",ios::out|ios::app); a.open("s.dat",ios::in|ios::out); cout<<"\n\n\t\tID OF THE SHOP YOU WANT TO DELETE : "; cin>>b; a.seekg(0,ios::beg); while(a.read((char*)&obj1,sizeof(obj1))) { if(obj1.num()!=b) { c.write((char*)&obj1,sizeof(obj1)); } } a.close(); c.close(); remove("s.dat"); rename("s1.dat","s.dat"); break; } case 4: { char m[100]; cout<<"Enter Name that should be searched:"; cin>>m; fil.open("s.dat",ios::in| ios::out|ios::binary); if(!fil) { cout<<"File not Found"; exit(0); } else { fil.read((char*)&obj1, sizeof(obj1)); while(!fil.eof()) { if(strcmp(m,obj1.getm())==0) { fil.seekg(0,ios::cur); cout<<"Enter New Record.."<<endl; obj1.sgetData(); fil.seekp(fil.tellg() - sizeof(obj1)); } fil.read((char*)&obj1, sizeof(obj1)); } } fil.close(); break; } case 5:obj1.calcTotalRent(b,Num-1);break; case 6:obj1.findShopDetails(b,Num);break; case 7:obj1.NoofFreeShops(b,Num);break; case 8: exit(0); default: { cout<<"\nEnter correct option...."; break; } } }return 0; } <file_sep># Mall-Management-System
cd7a379a9ef41979904aadc22e80831cd36093a4
[ "Markdown", "C++" ]
2
C++
HariPrasad5724/Mall-Management-System
e0d6dd35e65b1f06960804535b283ad3b80da69e
729f41ba28419da87676cdf169776c19eb9665cd
refs/heads/master
<repo_name>iker3085/react-test<file_sep>/src/components/header.jsx import React, { Component } from "react"; class Header extends Component { render() { return ( <header className="navbar navbar-dark bd-navbar flex-row"> <a href="#" className="navbar-brand"> Test </a> <ul className="navbar-nav flex-row"> <li className="nav-item"> <a className="nav-link">Home</a> </li> <li className="nav-item"> <a className="nav-link">Link1</a> </li> <li className="nav-item"> <a className="nav-link">Link2</a> </li> <li className="nav-item"> <a className="nav-link">Link3</a> </li> <li className="nav-item"> <a className="nav-link">Link4</a> </li> </ul> </header> ); } } export default Header;
873cc651a9c3d2c29f8850b49610561c1d951384
[ "JavaScript" ]
1
JavaScript
iker3085/react-test
de598022151742ec4904fdd5c0d6b91bc81a7539
6432029f3ec9032edb11b3672c41d948d84bf9d2
refs/heads/master
<file_sep>using System; using ToneLab1; using Xunit; namespace XUnitTestProject1 { public class UnitTest1 { [Fact] public void Test1() { var dbConn = new DBConn(); var connection = dbConn.openConn(); Assert.True(connection != null); } } } <file_sep>using System; namespace ToneLab1 { public class LinkedList { private Node start; private Node end; private int count; public LinkedList() { start = null; end = null; count = 0; } //add public void add(int item) { Node newNode = new Node(item); if (start == null && end == null) { start = newNode; end = newNode; count++; } else { end.setNext(newNode); newNode.setPrev(end); end = newNode; count++; } } //remove public void remove() { if (end == null) { Console.WriteLine("Cannot remove from empty linked list."); } else { end = (Node)end.getPrev(); end.setNext(null); count--; } } //sort //i used a slection sort algorithm for this linked list public void sort() { Node currPtr = start; Node incPtr = (Node)currPtr.getNext(); int temp = 0; while (currPtr.getNext() != null) { Node minPtr = null; Node tempPtr = currPtr; while (tempPtr != null) { int min = currPtr.item; if (tempPtr.item < min) { min = tempPtr.item; minPtr = tempPtr; } tempPtr = (Node)tempPtr.getNext(); } temp = currPtr.item; currPtr.item = minPtr.item; currPtr = (Node)currPtr.getNext(); } } //first public Object getFirst() { return start.item; } //last public Object getLast() { return end.item; } } }<file_sep>using System; namespace ToneLab1 { public class Node { private Node prevPtr; public int item; private Node nextPtr; public Node(int item) { this.item = item; } public Object getPrev(){ return prevPtr; } public Object getNext(){ return nextPtr; } public void setPrev(Node node){ prevPtr = node; } public void setNext(Node node){ nextPtr = node; } } }<file_sep>using System; namespace ToneLab1 { class Program { static void Main(string[] args) { DBConn newConn = new DBConn(); } public static string replace(string item, char delimiter, char selection) { char[] array = item.ToCharArray(); for (int i = 0; i < array.Length; i++) { if (array[i] == delimiter) { array[i] = selection; } } string newItem = new string(array); return newItem; } } } <file_sep>using System; namespace ToneLab1 { public class Queue { private int start; private int end; private int[] array; public Queue(int size) { array = new int[size]; start = 0; end = size - 1; } public Queue() { } //clone public Queue clone() { Queue newQueue = new Queue(); newQueue.array = this.array; newQueue.start = this.start; newQueue.end = this.end; return newQueue; } //peek public int peek() { return array[start]; } //enqueue public void enqueue(int item) { if(!isFull()){ int index = (end+1)%array.Length; array[index]=item; } } //dequeue public int dequeue() { if (!isEmpty() ) { int item = array[start]; start = (start + 1) % array.Length; return item; }else { return -1; } } //is full public bool isFull() { return (start == (end + 1) % array.Length); } //is empty public bool isEmpty() { return (start == end); } } }<file_sep>using System; using System.Data.SqlClient; namespace ToneLab1 { class Program { static void Main(string[] args) { //DBConn newConn= new DBConn(); string dataSource = @"DESKTOP-RF8B7LP\SQLEXPRESS"; string database = "Library"; SqlConnectionStringBuilder connString = new SqlConnectionStringBuilder(@"Data Source=" + dataSource + ";Initial Catalog=" + database + ";Persist Security Info=True;Trusted_Connection=True;"); //User ID = tzamba; Password = <PASSWORD> SqlConnection conn = new SqlConnection(connString.ConnectionString); string queryString = "INSERT INTO dbo.students (name, surname, gender, birthdate, class, point) VALUES ('jesse', 'powell', 'male','5/1/1983','Freshman', 8);"; SqlCommand command = new SqlCommand(queryString, conn); try { command.Connection.Open(); command.ExecuteNonQuery(); }catch(Exception e) { Console.WriteLine(e.Message); } } public static string replace(string item, char delimiter, char selection) { char[] array = item.ToCharArray(); for (int i = 0; i < array.Length; i++) { if (array[i] == delimiter) { array[i] = selection; } } string newItem = new string(array); return newItem; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Data.SqlClient; namespace ToneLab1 { public class DBConn { private static string dataSource = @"DESKTOP-RF8B7LP\SQLEXPRESS"; private static string database = "Library"; private string connString = @"Data Source=" + dataSource + ";Initial Catalog=" + database + ";Persist Security Info=True;"; SqlConnection conn; public SqlConnection openConn() { this.conn = new SqlConnection(connString); try { Console.WriteLine("Openning Connection ..."); conn.Open(); Console.WriteLine("Connection successful!"); }catch(Exception e) { Console.WriteLine("Error: " + e.Message); } return this.conn; } public void close() { conn.Close(); } } }
e79af0577c81dbea0328a977528eb5bc1985b09e
[ "C#" ]
7
C#
tazamba/TONE
e1768dfc5d0e8337aaed2c9ab5ebcd4faf12e46b
c59cb25ff5e2aa89a620d815cc0c0574b4d47c7a
refs/heads/main
<repo_name>steveonlinux/Qtile<file_sep>/qtile/autostart.sh #! /bin/bash lxsession & xrandr --output DP-0 --primary --mode 1920x1080 --rate 144.00 --left-of HDMI-0 --output HDMI-0 --mode 1360x768 --rate 59.93 & picom --experimental-backends --no-fading-openclose & nitrogen --restore & urxvtd -q -o -f & /usr/bin/emacs --daemon & volumeicon & nm-applet &
654bca44e8835ade641593c1c34cd467e7d90081
[ "Shell" ]
1
Shell
steveonlinux/Qtile
4f5c458c3326a942f7a61faed1dd8800159befa5
043d91e504a89fd927a2cf36383e11b4c7dc7320
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Thu Nov 10 20:36:29 2016 @author: user """ import numpy as np import matplotlib.pyplot as plt import os os.chdir('C:\\Dropbox\\trading') import interpolate as intp import scipy as sp x = np.linspace(0, 1, 21) noise = 1e-1*np.random.randn(x.size) noise = np.array([-0.03298601, -0.08164429, -0.06845745, -0.20718593, 0.08666282, 0.04702094, 0.08208645, -0.1017021 , -0.03031708, 0.22871709, -0.10302486, -0.17724316, -0.05885157, -0.03875947, -0.1102984 , -0.05542001, -0.12717549, 0.14337697, -0.02637848, -0.10353976, -0.0618834 ]) y = np.exp(x) + noise pp9 = intp.SmoothSpline(x, y, p=.9) pp99 = intp.SmoothSpline(x, y, p=.99) #, var=0.01) y99 = pp99(x); y9 = pp9(x) np.allclose(y9,[ 0.8754795 , 0.95285289, 1.03033239, 1.10803792, 1.18606854, 1.26443234, 1.34321265, 1.42258227, 1.5027733 , 1.58394785, 1.66625727, 1.74998243, 1.8353173 , 1.92227431, 2.01076693, 2.10064087, 2.19164551, 2.28346334, 2.37573696, 2.46825194, 2.56087699]) np.allclose(y99,[ 0.95227461, 0.97317995, 1.01159244, 1.08726908, 1.21260587, 1.31545644, 1.37829108, 1.42719649, 1.51308685, 1.59669367, 1.61486217, 1.64481078, 1.72970022, 1.83208819, 1.93312796, 2.05164767, 2.19326122, 2.34608425, 2.45023567, 2.5357288 , 2.6357401 ]) plt.figure(0) h=plt.plot(x,y, x,pp99(x),'g', x,pp9(x),'k', x,np.exp(x),'r') plt.show() def spline_alg_fit(x, y, t, c = 0): mu = 2 * (1-t)/(3*t) h = np.diff(x) p = 2 * (h[:-1] + h[1:]) r = 3 / h f = -(r[:-1] + r[1:]) R = np.diag(p, k=0) + np.diag(h[1:-1], k=1) + np.diag(h[1:-1], k=-1) Qt = np.zeros((f.size, f.size + 2), dtype=np.float) for i, v in enumerate((r[:-1], f, r[1:])): np.fill_diagonal(Qt[:,i:], v) Q = np.transpose(Qt) A = mu * np.matmul(Qt, Q) + R cur = c * np.ones(f.size, dtype=np.float) T = 1/3 * (1 - t) * (np.matmul(Q, cur) + np.matmul(cur, Qt)) B = np.matmul(Qt, y) + np.matmul(Qt, T / t) b = np.linalg.solve(A, B) d = y - mu * np.matmul(Q, b) + T / t return d def spline_numeric_fit(fit_y, x, y, t, c = 0): dx = np.diff(x) dydx = np.diff(fit_y) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array([c, ddydx, c]) - c res = fit_y - y sumSpline = t * np.dot(res, res) + (1 - t) * np.dot(derivs, derivs) + res.size/2 * np.log(2*np.pi*1/(2*t)) + len(derivs)/2 * np.log(2*np.pi*1/(2*(1-t))) return sumSpline def spline_numeric_fit_vars(fit_y, x, y, tj, ti, c = 0): dx = np.diff(x) dydx = np.diff(fit_y) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array([c, ddydx, c]) - c res = fit_y - y sumSpline = tj * np.dot(res, res) + ti * np.dot(derivs, derivs) + res.size/2 * np.log(2*np.pi*1/(2*tj)) + len(derivs)/2 * np.log(2*np.pi*1/(2*ti)) return sumSpline def spline_numeric_fit_prob(fit, x, y, t, c = 0): dx = np.diff(x) dydx = np.diff(fit) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [c, ddydx, c] - c res = fit - y term1 = -np.sum(np.log(sp.stats.norm.pdf(res, 0, np.sqrt(1/(2*t))))) term2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, np.sqrt(1/(2*(1-t)))))) if not(np.isfinite(term1) & np.isfinite(term2)): print('error: non-finite value') return (term1 + term2) def spline_numeric_fit_prob_vars(fit, x, y, v1, v2, c = 0): dx = np.diff(x) dydx = np.diff(fit) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [c, ddydx, c] - c res = fit - y term1 = -np.sum(np.log(sp.stats.norm.pdf(res, 0, v1))) term2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, v2))) if not(np.isfinite(term1) & np.isfinite(term2)): print('error: non-finite value') return (term1 + term2) #class bounds_fit(object): # def __init__(self, xmax = [1.0], xmin = [0.0] ): # self.xmax = np.array(xmax) # self.xmin = np.array(xmin) def Bcall(**kwargs): x = kwargs["x_new"] tmax = bool(np.all(x > 0)) tmin = bool(np.all(x < 1)) return tmax and tmin def spline_numeric_fit_prob_opt_t(par, x, y, epsilon, c = 0): global fit t = 1/(1 + epsilon * 10**par) def negnormP(fit): dx = np.diff(x) dydx = np.diff(fit) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [c, ddydx, c] - c res = fit - y retval = t * np.dot(res, res) + (1 - t) * np.dot(derivs, derivs) + res.size/2 * np.log(2*np.pi*1/(2*t)) + len(derivs)/2 * np.log(2*np.pi*1/(2*(1-t))) if (retval == -np.inf): retval = np.inf return retval #opt = sp.optimize.fmin(func = negnormP, x0 = s, full_output = 1) minimizer_kwargs_par = {"method": "BFGS"} opt = sp.optimize.basinhopping(negnormP, x0 = fit, minimizer_kwargs = minimizer_kwargs_par, niter = 3) fit = opt.x # if (opt.fun == np.inf): # val = opt.fun # else: # val = opt.fun val = -opt.fun return val def spline_numeric_fit_prob_opt_pars(pars, x, y, epsilon, c = 0): global fit tj = 1/(1 + epsilon * 10**(pars[0])) ti = 1 - tj vj = np.sqrt(1/(2*tj)) vi = np.sqrt(1/(2*ti)) if (len(pars) > 1): wk = np.exp(pars[1]) norm_ent = sp.stats.norm.entropy(0, vj) ent_match = lambda vjq: np.abs(ratioProb.entropy(0, vjq, wk) - norm_ent) ent_opt_j = sp.optimize.fmin(func = ent_match, x0 = vj) def negnormP(fit): dx = np.diff(x) dydx = np.diff(fit) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [c, ddydx, c] - c res = fit - y if (len(pars) == 1): t1 = -np.sum(np.log(sp.stats.norm.pdf(res, 0, vj))) t2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, vi))) elif(len(pars) == 2): t1 = -np.sum(np.log(ratioProb.pdf(res, 0, ent_opt_j, wk))) t2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, vi))) retval = t1 + t2 if (retval == -np.inf): retval = np.inf return retval #opt = sp.optimize.fmin(func = negnormP, x0 = s, full_output = 1) minimizer_kwargs_par = {"method": "BFGS"} opt = sp.optimize.basinhopping(negnormP, x0 = fit, minimizer_kwargs = minimizer_kwargs_par, niter = 5) fit = opt.x val = opt.fun return val x = np.linspace(0, 5, 20) ytrue = x*x*x y = ytrue + 8*np.random.normal(0, 1, 20) (a, b, r, tt, stderr) = sp.stats.linregress(x, y) line_y = b + a * x epsilonN = ((x[-1] - x[0])/(x.size - 1))**3/16 t = [] opt = [] totprob = [] sumSpline1 = []; sumSpline2 = [] for j in range(20): # do as per matlab t.append(1/(1 + epsilonN * 10**(j - 10))) #spline_opt = sp.optimize.fmin(func = spline_numeric_fit, x0 = y, args=(x, y, t), full_output = 1, maxiter = 10000) #spline_opt = sp.optimize.minimize(spline_numeric_fit, x0 = y, args=(x, y, t), method='Powell', options= {'maxiter': 100000}) minimizer_kwargs = {"method": "BFGS", "args": (x, y, t[-1])} spline_opt = sp.optimize.basinhopping(spline_numeric_fit, x0 = y, minimizer_kwargs = minimizer_kwargs, niter = 20) #spline_opt2 = sp.optimize.basinhopping(spline_numeric_fit_prob, x0 = spline_opt.x, minimizer_kwargs = minimizer_kwargs, niter = 20) dx = np.diff(x) dydx = np.diff(spline_opt.x) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [0, ddydx, 0] res = y - spline_opt.x # negnormP = lambda q: -np.sum(np.log(sp.stats.norm.pdf(res, 0, q)) + # np.log(sp.stats.norm.pdf(derivs, 0, q*np.sqrt(t[-1]/(1 - t[-1]))))) # opt.append(sp.optimize.fmin(func = negnormP, x0 = np.std(res)*2, full_output = 1)) #arbitrary initialization opt.append(spline_opt.fun) # resstd = np.sqrt(np.dot(res, res)/res.size) # derstd = np.sqrt(np.dot(derivs, derivs)/len(derivs)) # totprob.append(np.sum(np.log(sp.stats.norm.pdf(res, 0, resstd))) + np.sum(np.log(sp.stats.norm.pdf(derivs, 0, derstd)))) # # spline_opt3_B = intp.SmoothSpline(x, y, t[-1]) # spline_opt3 = spline_opt3_B(x) # dydx = np.diff(spline_opt3) / dx # ddydx = np.diff(dydx) / dx[:-1] # derivs = [0, ddydx, 0] # res = y - spline_opt3 # sumSpline1.append(t[-1] * np.dot(res, res) + (1 - t[-1]) * np.dot(derivs, derivs) + res.size/2 * np.log(2*np.pi*1/(2*t[-1])) + # len(derivs)/2 * np.log(2*np.pi*1/(2*(1-t[-1])))) # sumSpline2.append(t[-1] * np.dot(res, res) + (1 - t[-1]) * np.dot(derivs, derivs)) #prob = [p[1] for p in opt] fit = y optval = sp.optimize.fmin(func = spline_numeric_fit_prob_opt_t, x0 = 5, args = (x, y, epsilonN), full_output = 1, maxiter = 10) plt.figure(1) testP5 = intp.SmoothSpline(x, y, p = .5) algeT = spline_alg_fit(x, y, .5) algeT2 = spline_alg_fit(x, y, .5, 2) !!!!out = spline_opt.x h = plt.plot(x, y, x, out, x, algeT, x, testP5(x)) spline_numeric_fit(algeT, x, y, t) spline_numeric_fit(testP5(x), x, y, t) spline_numeric_fit(spline_opt.x, x, y, t) spline_numeric_fit(spline_opt2.x, x, y, t) #v put in basin hopping, try as alternative to stepping through t # ratio dist class ratioDist(sp.stats.rv_continuous): "Ratio distribution" def _argcheck(self, mu, s1, s2): return (s1 > 0) and (s2 > 0) def _pdf(self, x, mu, s1, s2): rt2 = np.sqrt(2) psum = s1 * s1 + x * x * s2 * s2 prod = s1 * s2 pmusum = s1 * s1 + x * mu * s2 * s2 t1 = 1/(rt2 * np.pi * (psum) ** (3/2)) # problem line!! OverflowError: (34, 'Result too large') t2 = np.exp(-(mu * mu/(2 * s1 * s1) + 1/(2 * s2 * s2))) t3 = rt2 * prod * np.sqrt(psum) t4 = sp.special.erf(pmusum/(rt2 * prod * np.sqrt(psum))) t24 = np.exp(-(mu * mu/(2 * s1 * s1) + 1/(2 * s2 * s2)) + pmusum * pmusum/(2 * prod * prod * psum)) return t1 * (t2 * t3 + t24 * np.sqrt(np.pi) * t4 * pmusum) def spline_numeric_fit_prob_vars_ratio(fit, x, y, a, b, c = 0, d = 0, cu = 0): dx = np.diff(x) dydx = np.diff(fit) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [cu, ddydx, cu] - cu res = fit - y if (c != 0): term1 = -np.sum(np.log(ratioProb.pdf(res, 0, a, c))) else: term1 = -np.sum(np.log(sp.stats.norm.pdf(res, 0, a))) if (d != 0): term2 = -np.sum(np.log(ratioProb.pdf(derivs, 0, b, d))) else: term2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, b))) #if not(np.isfinite(term1) & np.isfinite(term2)): # print('error: non-finite value') return (term1 + term2) def spline_numeric_fit_OU(fit_y, x, y, t, c = 0, k = 1): fit_y = np.array(fit_y) y = np.array(y) dx = np.diff(x[1:]) dydx = np.diff(fit_y) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array([c, *list(ddydx), c]) - c yprev = y[:-1] res = yprev - y[1:] - k * (yprev - fit_y) sumSpline = t * np.dot(res, res) + (1 - t) * np.dot(derivs, derivs) + res.size/2 * np.log(2*np.pi*1/(2*t)) + len(derivs)/2 * np.log(2*np.pi*1/(2*(1-t))) return sumSpline def spline_numeric_fit_vars_OU(fit_y, x, y, tj, ti, c = 0, k = 1): fit_y = np.array(fit_y) y = np.array(y) dx = np.diff(x[1:]) dydx = np.diff(fit_y) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array([c, *list(ddydx), c]) - c yprev = y[:-1] res = y[1:] - yprev + k * (yprev - fit_y) sumSpline = tj * np.dot(res, res) + ti * np.dot(derivs, derivs) # + res.size/2 * np.log(2*np.pi*1/(2*tj)) + len(derivs)/2 * np.log(2*np.pi*1/(2*ti)) return sumSpline def spline_numeric_fit_prob_OU(fit_y, x, y, t, c = 0, k = 1): fit_y = np.array(fit_y) y = np.array(y) dx = np.diff(x[1:]) dydx = np.diff(fit_y) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [c, ddydx, c] - c yprev = y[:-1] res = yprev - y[1:] - k * (yprev - fit_y) term1 = -np.sum(np.log(sp.stats.norm.pdf(res, 0, np.sqrt(1/(2*t))))) term2 = -np.sum(np.log(sp.stats.norm.pdf(derivs, 0, np.sqrt(1/(2*(1-t)))))) if not(np.isfinite(term1) & np.isfinite(term2)): print('error: non-finite value') return (term1 + term2) ratioProb = ratioDist(name = 'ratio') size = 200 ratio_x = np.linspace(0, 5, size) rands = np.array([]) while (rands.size < size): newrs = ratioProb.rvs(mu = 0, s1 = 1.5, s2 = 0.4, size = 50) rands = np.append(rands, newrs) truey2 = ratio_x*ratio_x*ratio_x ratio_y = truey2 + rands (a , b , r, tt, stderr) = sp.stats.linregress(ratio_x, ratio_y) epsilon = ((ratio_x[-1] - ratio_x[0])/(ratio_x.size - 1))**3/16 # t = []; prob = []; stdres = []; stdderiv = []; pvalue = [] for j in range(20): t.append(1/(1 + epsilon * 10**(2*j - 6))) #algeT = spline_alg_fit(ratio_x, ratio_y, 1 - t[-1]) minimizer_kwargs = {"method": "BFGS", "args": (ratio_x, ratio_y, t[-1])} spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit, x0 = ratio_y, minimizer_kwargs = minimizer_kwargs, niter = 10) spline_opt = sp.optimize.basinhopping(spline_numeric_fit_prob, x0 = spline_opt_0.x, minimizer_kwargs = minimizer_kwargs, niter = 10) pvalue.append(spline_opt_0.fun) dx = np.diff(ratio_x) dydx = np.diff(spline_opt.x) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [0, ddydx, 0] res = ratio_y - spline_opt.x negnormP = lambda q: -np.sum(np.log(sp.stats.norm.pdf(res, 0, q*np.sqrt(1/(2*t[-1])))) + np.log(sp.stats.norm.pdf(derivs, 0, q*np.sqrt(1/(2*(1-t[-1])))))) opt = sp.optimize.fmin(func = negnormP, x0 = np.std(res)/np.sqrt(1/(2*t[-1])), full_output = 1) if not(np.isfinite(opt[1])): opt = sp.optimize.fmin(func = negnormP, x0 = np.std(derivs)/np.sqrt(1/(2*(1-t[-1]))), full_output = 1) stdres.append(opt[0] * np.sqrt(1/(2*t[-1]))) stdderiv.append(opt[0] * np.sqrt(1/(2*(1-t[-1])))) prob.append(opt[1]) size = 9 size1 = 10 vi = []; vj = []; prob = np.zeros((size1, size)); stdres = np.zeros((size1, size)); stdderiv = np.zeros((size1, size)) istep = np.logspace(-8, 8, num = size) for j in range(size1): tj = 1/(1 + epsilon * 10**(2*j+3)) #(j + 3)) #13 vj.append(np.sqrt(1/(2*tj))) for i in range(size): ti = istep[i] # 1 - 1/(1 + epsilon * 10**(2*i + 3)) #13 vi.append(np.sqrt(1/(2*ti))) minimizer_kwargs_0 = {"method": "BFGS", "args": (ratio_x, ratio_y, tj, ti)} # next line could init with previous loop spline instead of ratio_y spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit_vars, x0 = ratio_y, minimizer_kwargs = minimizer_kwargs_0, niter = 5) minimizer_kwargs = {"method": "BFGS", "args": (ratio_x, ratio_y, vj[-1], vi[-1])} spline_opt = sp.optimize.basinhopping(spline_numeric_fit_prob_vars, x0 = spline_opt_0.x, minimizer_kwargs = minimizer_kwargs, niter = 20) dx = np.diff(ratio_x) dydx = np.diff(spline_opt.x) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = [0, ddydx, 0] res = ratio_y - spline_opt.x negnormP = lambda q: -np.sum(np.log(sp.stats.norm.pdf(res, 0, q*vj[-1])) + np.log(sp.stats.norm.pdf(derivs, 0, q*vi[-1]))) opt = sp.optimize.fmin(func = negnormP, x0 = np.std(res)/vj[-1], full_output = 1) if not(np.isfinite(opt[1])): opt = sp.optimize.fmin(func = negnormP, x0 = np.std(derivs)/vi[-1], full_output = 1) stdres[j, i] = opt[0] * vj[-1] stdderiv[j, i] = opt[0] * vi[-1] prob[j, i] = opt[1] plt.plot([prob[k, k] for k in range(size1)]) plt.plot([stdres[k, k] for k in range(size)]) plt.plot([stdderiv[k, k] for k in range(size)]) im = plt.imshow(prob, cmap='hot', origin='lower' ) plt.colorbar(im, orientation='horizontal') plt.show() minval = np.amin(prob) minp = np.unravel_index(prob.argmin(), prob.shape) # ratio spline def calcProb(xs, ys, spline, vj, vi, wk = 0, wl = 0, c = 0): dx = np.diff(xs) dydx = np.diff(spline) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array([c, ddydx, c]) - c res = ys - spline if (wk != 0): if (wl != 0): negnormP = lambda q: -np.sum(np.log(ratioProb.pdf(res, 0, q*vj, wk)) + np.log(ratioProb.pdf(derivs, 0, q*vi, wl))) else: negnormP = lambda q: -np.sum(np.log(ratioProb.pdf(res, 0, q*vj, wk)) + np.log(sp.stats.norm.pdf(derivs, 0, q*vi))) else: negnormP = lambda q: -np.sum(np.log(sp.stats.norm.pdf(res, 0, q*vj)) + np.log(sp.stats.norm.pdf(derivs, 0, q*vi))) opt = sp.optimize.fmin(func = negnormP, x0 = np.std(res)/vj, full_output = 1) if not(np.isfinite(opt[1])): opt = sp.optimize.fmin(func = negnormP, x0 = np.std(derivs)/vi, full_output = 1) return opt sampleSz = 25 epsilon = ((ratio_x[sampleSz - 1] - ratio_x[0])/(sampleSz - 1))**3/16 size0 = 1 #5 size1 = 20 #10 size2 = 0 #5 vi = []; vj = []; wk = []; wl = [] prob0 = np.zeros((size0)); stdres1 = np.zeros((size0)); stdderiv1 = np.zeros((size0)) prob1 = np.zeros((size0, size1)); stdres2 = np.zeros((size0, size1)); stdderiv2 = np.zeros((size0, size1)) prob2 = np.zeros((size0, size1, size2)); stdres3 = np.zeros((size0, size1, size2)); stdderiv3 = np.zeros((size0, size1, size2)) istep = np.logspace(8, -8, num = size2) xs = ratio_x[0:sampleSz] ys = ratio_y[0:sampleSz] pvals = [] for j in range(size0): tj = 1/(1 + epsilon * 10**(1)) # 1/(1 + epsilon * 10**(2*j - 5)) vj.append(np.sqrt(1/(2*tj))) ti = 1 - tj vi.append(np.sqrt(1/(2*ti))) minimizer_kwargs_0 = {"method": "BFGS", "args": (xs, ys, tj, ti)} # next line could init with previous loop spline instead of ratio_y spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit_vars, x0 = ys, minimizer_kwargs = minimizer_kwargs_0, niter = 10) pvals.append(spline_opt_0.fun) if (size1 > 0): for k in range(size1): # uk = 1/(1 + epsilon * 10**(6*k - 20)) # wk.append(np.sqrt(1/(2*uk))) wk.append(np.exp((k-5))) minimizer_kwargs = {"method": "BFGS", "args": (xs, ys, vj[-1], vi[-1], wk[-1])} if (k == 0): x0 = spline_opt_0.x else: x0 = spline_opt_1.x spline_opt_1 = sp.optimize.basinhopping(spline_numeric_fit_prob_vars_ratio, x0 = x0, minimizer_kwargs = minimizer_kwargs, niter = 10) if (size2 > 0): for l in range(size2): ul = istep[l] wl.append(np.sqrt(1/(2*ul))) minimizer_kwargs = {"method": "BFGS", "args": (xs, ys, vj[-1], vi[-1], wk[-1], wl[-1])} if (l == 0): x0 = spline_opt_1.x else: x0 = spline_opt_2.x spline_opt_2 = sp.optimize.basinhopping(spline_numeric_fit_prob_vars_ratio, x0 = x0, minimizer_kwargs = minimizer_kwargs, niter = 10) opt = calcProb(xs, ys, spline_opt_2.x, vj[-1], vi[-1], wk[-1], wl[-1]) stdres3[j, k, l] = opt[0] * vj[-1] stdderiv3[j, k, l] = opt[0] * vi[-1] prob2[j, k, l] = opt[1] print('finished ' + str(j) + ', ' + str(k) + ', ' + str(l)) else: opt = calcProb(xs, ys, spline_opt_1.x, vj[-1], vi[-1], wk[-1]) stdres2[j, k] = opt[0] * vj[-1] stdderiv2[j, k] = opt[0] * vi[-1] prob1[j, k] = opt[1] print('finished ' + str(j) + ', ' + str(k)) else: opt = calcProb(xs, ys, spline_opt_0.x, vj[-1], vi[-1]) stdres1[j] = opt[0] * vj[-1] stdderiv1[j] = opt[0] * vi[-1] prob0[j] = opt[1] print('finished ' + str(j)) plt.plot([prob1[k, k] for k in range(size0)]) plt.plot([stdres2[k, k] for k in range(size1)]) plt.plot([stdderiv2[k, k] for k in range(size1)]) im = plt.imshow(prob1, cmap = 'hot', origin = 'lower') plt.colorbar(im, orientation='horizontal') plt.show() maxval = np.amax(prob1) maxp = np.unravel_index(prob1.argmax(), prob1.shape) minval = np.amin(prob1) minp = np.unravel_index(prob1.argmin(), prob1.shape) # line data size = 50 ratio_x = np.linspace(0, 10, size) rands = np.array([]) while (rands.size < size): try: newrs = ratioProb.rvs(mu = 0, s1 = 1.5, s2 = 0.001, size = 50) rands = np.append(rands, newrs) except: continue ratio_ln_y = ratio_x + rands (a , b , r, tt, stderr) = sp.stats.linregress(ratio_x, ratio_ln_y) plt.figure(1) h1 = plt.plot(ratio_x, ratio_ln_y) predict_y = b + a * ratio_x h2 = plt.plot(ratio_x, predict_y) devs = [np.sqrt(np.sum((predict_y - ratio_ln_y) * (predict_y - ratio_ln_y))/ratio_ln_y.size), .05] sampleSz = 50 epsilon = ((ratio_x[sampleSz - 1] - ratio_x[0])/(sampleSz - 1))**3/16 size0 = 10 size1 = 0 size2 = 0 vi = []; vj = []; wk = []; wl = [] prob0 = np.zeros((size0)); stdres1 = np.zeros((size0)); stdderiv1 = np.zeros((size0)) prob1 = np.zeros((size0, size1)); stdres2 = np.zeros((size0, size1)); stdderiv2 = np.zeros((size0, size1)) prob2 = np.zeros((size0, size1, size2)); stdres3 = np.zeros((size0, size1, size2)); stdderiv3 = np.zeros((size0, size1, size2)) istep = np.logspace(4, -4, num = size2) xs = ratio_x[0:sampleSz] ys = ratio_ln_y[0:sampleSz] sample = rands[0:sampleSz] pvals = [] pvals2 = np.zeros((size0, size1)) pvals3 = np.zeros((size0, size1, size2)) for j in range(size0): tj = 1/(1 + epsilon * 10**(2*j - 5)) #5 vj.append(np.sqrt(1/(2*tj))) ti = 1 - tj vi.append(np.sqrt(1/(2*ti))) minimizer_kwargs_0 = {"method": "BFGS", "args": (xs, ys, tj)} # next line could init with previous loop spline instead of ratio_y spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit, x0 = ys, minimizer_kwargs = minimizer_kwargs_0, niter = 10) pvals.append(spline_opt_0.fun) # minimizer_kwargs = {"method": "BFGS", "args": (xs, ys, vj[-1], vi[-1], 0.8)} # spline_opt_1 = sp.optimize.basinhopping(spline_numeric_fit_prob_vars_ratio, x0 = spline_opt_0.x, minimizer_kwargs = minimizer_kwargs, niter = 20) if (size1 > 0): for k in range(size1): wk.append(0.5) #(0.0001 + 0.2*k) #(np.exp(2*k-5)) # adjust vj[-1] to maintain some variance-like property at constant norm_ent = sp.stats.norm.entropy(0, vj[-1]) ent_match = lambda vjq: np.abs(ratioProb.entropy(0, vjq, wk[-1]) - norm_ent) ent_opt_j = sp.optimize.fmin(func = ent_match, x0 = vj[-1]) kwargs_1 = {"method": "BFGS", "args": (xs, ys, ent_opt_j, vi[-1], wk[-1])} if (k == 0): x0 = spline_opt_0.x else: x0 = spline_opt_1.x spline_opt_1 = sp.optimize.basinhopping(spline_numeric_fit_prob_vars_ratio, x0 = x0, minimizer_kwargs = kwargs_1, niter = 10) pvals2[j, k] = spline_opt_1.fun if (size2 > 0): for l in range(size2): ul = istep[l] wl.append(np.sqrt(1/(2*ul))) norm_ent = sp.stats.norm.entropy(0, vi[-1]) ent_match = lambda viq: np.abs(ratioProb.entropy(0, viq, wl[-1]) - norm_ent) ent_opt_i = sp.optimize.fmin(func = ent_match, x0 = vi[-1], full_output = 1) kwargs_2 = {"method": "BFGS", "args": (xs, ys, ent_opt_j, ent_opt_i, wk[-1], wl[-1])} if (l == 0): x0 = spline_opt_1.x else: x0 = spline_opt_2.x spline_opt_2 = sp.optimize.basinhopping(spline_numeric_fit_prob_vars_ratio, x0 = x0, minimizer_kwargs = kwargs_2, niter = 5) pvals3[j, k, l] = spline_opt_2.fun # opt = calcProb(xs, ys, spline_opt_2.x, vj[-1], vi[-1], wk[-1], wl[-1]) # stdres3[j, k, l] = opt[0] * ent_opt_j # stdderiv3[j, k, l] = opt[0] * ent_opt_i # prob2[j, k, l] = opt[1] print('finished ' + str(j) + ', ' + str(k) + ', ' + str(l)) else: opt = calcProb(xs, ys, spline_opt_1.x, ent_opt_j, vi[-1], wk[-1]) stdres2[j, k] = opt[0] * ent_opt_j stdderiv2[j, k] = opt[0] * vi[-1] prob1[j, k] = opt[1] print('finished ' + str(j) + ', ' + str(k)) else: opt = calcProb(xs, ys, spline_opt_0.x, vj[-1], vi[-1]) stdres1[j] = opt[0] * vj[-1] stdderiv1[j] = opt[0] * vi[-1] prob0[j] = opt[1] print('finished ' + str(j)) np.unravel_index(pvals3.argmin(), pvals3.shape) im = plt.imshow(pvals2, cmap = 'hot', origin = 'lower') # try maximising prob for res and derivs separately (a , b , r, tt, stderr) = sp.stats.linregress(xs, ys) plt.figure(1) #h1 = plt.plot(xs, ys) predict_y = b + a * xs h2 = plt.plot(xs, predict_y) fit = ys optim0 = sp.optimize.fmin(func = spline_numeric_fit_prob_opt_t, x0 = 5, args = (xs, ys, epsilon), full_output = 1, maxiter = 5) # must begin this with already smoothed fit! and its slow optim1 = sp.optimize.fmin(func = spline_numeric_fit_prob_opt_pars, x0 = [optim0[0], 0], args = (xs, ys, epsilon), full_output = 1) # with curvature size0 = 7 curvsize = 4 vi = []; vj = []; curv = np.linspace(0, 30, curvsize) pvals = [] pvals2 = np.zeros((size0, curvsize)) epsilonN = ((x[-1] - x[0])/(x.size - 1))**3/16 xs = x[0:sampleSz] ys = y[0:sampleSz] for j in range(size0): tj = 1/(1 + epsilonN * 10**(2*j - 2)) vj.append(np.sqrt(1/(2*tj))) ti = 1 - tj vi.append(np.sqrt(1/(2*ti))) minimizer_kwargs_0 = {"method": "BFGS", "args": (xs, ys, tj)} # next line could init with previous loop spline instead of ratio_y spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit, x0 = ys, minimizer_kwargs = minimizer_kwargs_0, niter = 20) pvals.append(spline_opt_0.fun) print('finished ' + str(j)) if (curvsize > 0): for k in range(curvsize): minimizer_kwargs_1 = {"method": "BFGS", "args": (xs, ys, tj, ti, curv[k])} if (k == 0): x0 = spline_opt_0.x else: x0 = spline_opt_1.x spline_opt_1 = sp.optimize.basinhopping(spline_numeric_fit_vars, x0 = x0, minimizer_kwargs = minimizer_kwargs_1, niter = 10) pvals2[j, k] = spline_opt_1.fun print('finished ' + str(j) + ', ' + str(k)) if (curvsize > 0): im = plt.imshow(pvals2, cmap = 'hot', origin = 'lower') # with Ornstein-Uhlenbeck process ratioProb = ratioDist(name = 'ratio') size = 200 ratio_x = np.linspace(4.8, 5.8, size) rands = np.array([]) while (rands.size < size): try: newrs = ratioProb.rvs(mu = 0, s1 = 1.5, s2 = 0.001, size = 50) rands = np.append(rands, newrs) except: continue r = .05 ratio_ln_y_OU = [] ratio_ln_y_OU.append(ratio_x[0] + r * rands[0]) for i in range(size - 1): ratio_ln_y_OU.append(ratio_ln_y_OU[i] + rands[i+1] - r * (ratio_ln_y_OU[i] - ratio_x[i+1])) pd.DataFrame(ratio_ln_y_OU).to_csv('ratio_ln.csv') realY = ratio_x*ratio_x*ratio_x / 50.0 ratio_cub_y_OU = [] ratio_cub_y_OU.append(realY[0] + r * rands[0]) for i in range(size - 1): ratio_cub_y_OU.append(ratio_cub_y_OU[i] + rands[i+1] - r * (ratio_cub_y_OU[i] - realY[i+1])) k1 = -.22; k2 = 1.25; y_test = np.zeros(sampleSz) y_test[0] = rands[0] y_test[1] = rands[1] + (1 - k1) * y_test[0] for i in range(sampleSz - 1): y_test[i+1] = rands[i+1] + (1 - k1) * y_test[i] + (1 - k2) * y_test[i-1] + 500*(ratio_x[i+1] - 4.8) * (k1 + k2 - 1) pd.DataFrame(y_test).to_csv('y_test2.csv') sampleSz = 100 epsilon = ((ratio_x[sampleSz - 1] - ratio_x[0])/(sampleSz - 1))**3/16 size0 = 20 OUsize = 7 vi = []; vj = []; OUvals = np.linspace(0, .25, OUsize) pvals = [] pvals2 = np.zeros((OUsize, size0)) xs = ratio_x[0:sampleSz] ys = list(50*(dfSPY['logMedian'][0:sampleSz])) t = 1/(1 + epsilon * 10**(4)) # estimate big for line k = 1 #6 j = 11 for k in range(OUsize): args_1 = {"method": "BFGS", "args": (xs, ys, t, 1-t, 0, OUvals[k])} if (k == 0): x0 = ys[1:] else: x0 = spline_opt_1.x spline_opt_1 = sp.optimize.basinhopping(spline_numeric_fit_vars_OU, x0 = x0, minimizer_kwargs = args_1, niter = 20) pvals.append(spline_opt_1.fun) print('finished ' + str(k)) if (size0 > 0): for j in range(size0): tj = 1/(1 + epsilon * 10**(2*j - 20)) vj.append(np.sqrt(1/(2*tj))) ti = 1 - tj vi.append(np.sqrt(1/(2*ti))) args_0 = {"method": "BFGS", "args": (xs, ys, tj, ti, 0, OUvals[k])} # next line could init with previous loop spline instead of ratio_y if (j == 0): x0 = ys[1:] else: x0 = spline_opt_0.x spline_opt_0 = sp.optimize.basinhopping(spline_numeric_fit_vars_OU, x0 = x0, minimizer_kwargs = args_0) # niter = 20, pvals2[k, j] = spline_opt_0.fun print('finished ' + str(k) + ', ' + str(j)) if (size0 > 0): np.unravel_index(pvals2.argmin(), pvals2.shape) im = plt.imshow(pvals2, cmap = 'hot', origin = 'lower') # test 2nd deriv distribution for some curve dx = np.diff(ratio_x) dydx = np.diff(realY) / dx ddydx = np.diff(dydx) / dx[:-1] derivs = np.array(ddydx) xmin = [0.0001, 0.0001] xmax = [10, 10] bounds = [(low, high) for low, high in zip(xmin, xmax)] min_kwargs_test = {"method": "L-BFGS-B", "bounds": bounds} calcRatPars = lambda q: -np.sum(np.log(ratioProb.pdf(derivs, 0, q[0], q[1]))) par_test = sp.optimize.basinhopping(func = calcRatPars, x0 = [1., 0.1], minimizer_kwargs = min_kwargs_test) # analyse 2nd deriv mean, res for fitted spline dx = np.diff(xs[1:]) # ratio_x[1:] dydx = np.diff(spline_opt_0.x) / dx # ys ddydx = np.diff(dydx) / dx[-1] derivs = np.array(ddydx) curvMean = np.mean(derivs) ya = np.array(ys) yprev = ya[:-1] res = ya[1:] - yprev + OUvals[k] * (yprev - spline_opt_0.x) tj * np.dot(res, res) + ti * np.dot(derivs, derivs) # calculate k for fitted spline ydata = ratio_cub_y_OU x0 = [1., 0.01] def findK(k, ydata, spline): global x0 ydata = np.array(ydata) spline = np.array(spline) yprev = ydata[:-1] res = ydata[1:] - yprev + k * (yprev - spline) resRatPars = lambda q: -np.sum(np.log(ratioProb.pdf(res, 0, q[0], q[1]))) par_test = sp.optimize.basinhopping(func = resRatPars, x0 = x0, minimizer_kwargs = min_kwargs_test) x0 = par_test.x return par_test.fun optimK = sp.optimize.fmin(func = findK, x0 = OUvals[k], args = (ydata, spline_opt_1.x)) # check that calculated curvature and k are close to set values, tests model validity # for market data, find t and OU pars <file_sep># spline-work ## advanced spline methods ### **Introduction:** in this project spline methods are created that are especially effective for 1-D splines with certain statistical properties. It is believed these will be useful for financial analysis. ### **Requirements:** Python3, a number of scientific packages such as pandas, scipy, numpy. A source of financial data is also required. <file_sep># -*- coding: utf-8 -*- """ Created on Thu Jul 13 14:25:05 2017 @author: user """ import numpy as np import matplotlib.pyplot as plt import scipy as sp import pandas_datareader.data as web import pandas as pd import datetime import time import numpy.polynomial.polynomial as poly from sklearn import linear_model from sklearn.linear_model import TheilSenRegressor import itertools from statsmodels.api import robust import operator import os import pickle os.chdir('C:\\Dropbox\\trading') class ratioDist(sp.stats.rv_continuous): "Ratio distribution" def _argcheck(self, mu, s1, s2): return (s1 > 0) and (s2 > 0) def _pdf(self, x, mu, s1, s2): rt2 = np.sqrt(2) psum = s1 * s1 + x * x * s2 * s2 prod = s1 * s2 pmusum = s1 * s1 + x * mu * s2 * s2 t1 = 1/(rt2 * np.pi * (psum) ** (3/2)) # problem line!! OverflowError: (34, 'Result too large') t2 = np.exp(-(mu * mu/(2 * s1 * s1) + 1/(2 * s2 * s2))) t3 = rt2 * prod * np.sqrt(psum) t4 = sp.special.erf(pmusum/(rt2 * prod * np.sqrt(psum))) t24 = np.exp(-(mu * mu/(2 * s1 * s1) + 1/(2 * s2 * s2)) + pmusum * pmusum/(2 * prod * prod * psum)) return t1 * (t2 * t3 + t24 * np.sqrt(np.pi) * t4 * pmusum) class MyTakeStep(object): def __init__(self, stepsize = 1.5): self.stepsize = stepsize def __call__(self, x): s = self.stepsize x[0] += np.random.uniform(-s, s) x[1:] += np.random.uniform(-4*s, 4*s, x[1:].shape) return x ratioProb = ratioDist(name = 'ratio') def init(): dfRaw = pd.read_csv("C:\\Dropbox\\trading\\IB_hist_data\\NVDA_150d_15m.csv", header = None,) dfRaw['Median'] = dfRaw.apply(lambda row: np.median([np.median([row[2], row[5]]), np.median([row[3], row[4]])]), axis=1) #dfRaw['Group'] = [np.floor(x / 13) for x in range(dfRaw.shape[0])] dfRaw[1] = pd.to_datetime(dfRaw[1]) dfRaw['Group'] = dfRaw[1].dt.date dfRaw["GCount"] = dfRaw.groupby(['Group']).cumcount() dfRaw['Group2'] = np.floor(dfRaw["GCount"] / 13) dfData = pd.DataFrame(dfRaw.groupby(['Group', 'Group2'])['Median'].median()) dfData['logMedian'] = np.log(dfData['Median']) date_times = pd.DataFrame(dfRaw.groupby(['Group', 'Group2'])[1].first()) #date_times = pd.DataFrame(pd.to_datetime(date_times1)) for index, row in date_times.iterrows(): if (index[1] == 0): row[1] = row[1].replace(hour = 9, minute = 30) else: row[1] = row[1].replace(hour = 12, minute = 45) dfData.index = date_times.ix[:,1] dfData.to_pickle('NVDA_2Daily_150') def regress_numeric_line_AR_ent(line_pars, x, y, do_print, mu_l): global ARval global dev y = np.array(y) fit_y = line_pars[1] + line_pars[0] * x yprev = y[:-1] yprev2 = y[:-2] def findBestAR(pars, y, yprev, yprev2, fit_y, k2 = 1): k1 = pars[0] vs = pars[1:] res = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) new_ent = -np.sum(np.log(ratioProb.pdf(res, vs[2], vs[0], vs[1]))) return new_ent / res.size k1 = 0.4; k2 = 1 res_init = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) std_init = np.std(res_init) xmin = [.15, std_init / 20, std_init / 20, -mu_l * std_init] xmax = [1.3, 2.5 * std_init, 2.5 * std_init, mu_l * std_init] bounds = [(low, high) for low, high in zip(xmin, xmax)] x0_vals = [ARval, dev[0], dev[1], dev[2]] for i in range(len(x0_vals)): if (bounds[i][0] > x0_vals[i]): x0_vals[i] = bounds[i][0] if (bounds[i][1] < x0_vals[i]): x0_vals[i] = bounds[i][1] # k_opt = sp.optimize.minimize(findBestAR, x0 = ARval, method = 'L-BFGS-B', # bounds = bounds) k_kwargs = {"method": "L-BFGS-B", "args": (y, yprev, yprev2, fit_y), "bounds": bounds} k_opt = sp.optimize.basinhopping(findBestAR, x0 = x0_vals, minimizer_kwargs = k_kwargs, niter = 5) ARval = k_opt.x[0] dev = k_opt.x[1:] if do_print: print(ARval, dev) return k_opt.fun def par_limits(ARval, dev, std_init, mu_l): if ((ARval - 0.15) / 0.2 < 0.02): ARval_limit = True elif ((1.3 - ARval) / 1.3 < 0.02): ARval_limit = True else: ARval_limit = False if ((dev[0] - std_init / 20) / (std_init / 20) < 0.02): dev0 = True elif ((2.5 * std_init - dev[0]) / (2.5 * std_init) < 0.02): dev0 = True else: dev0 = False if ((dev[1] - std_init / 20) / (std_init / 20) < 0.02): dev1 = True elif ((2.5 * std_init - dev[1]) / (2.5 * std_init) < 0.02): dev1 = True else: dev1 = False if ((dev[2] + mu_l * std_init) / (-mu_l * std_init) < 0.02): dev2 = True elif ((mu_l * std_init - dev[2]) / (mu_l * std_init) < 0.02): dev2 = True else: dev2 = False hit_limits = (ARval_limit, dev0, dev1, dev2) return hit_limits def AR_line_calc(x, y, mu_l): # random dist'n, AR value, and line estimates, eg. from Matlab 'detrend' & 'ar' global dev global ARval y = np.array(y) valid = ~np.isnan(y) y = y[valid] x = x[valid] if sum(np.isnan(y)) / y.size > 0.1: nan_valid = False print('error: too many nan values, returning') return else: nan_valid = True (a, b, r, tt, stderr) = sp.stats.linregress(x, y) init_fit = b + a * x res_ols = y - init_fit std_res_ols = np.std(res_ols) ols_val = -np.sum(np.log(sp.stats.norm.pdf(res_ols, np.mean(res_ols), std_res_ols))) \ * (len(y) - 2) / len(y) print('initial OLS fun value (length normalized): ', ols_val) yprev = y[:-1] yprev2 = y[:-2] k1 = 0.4; k2 = 1 res_init = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - init_fit[2:] * (k1 + k2 - 1) std_init = np.std(res_init) ols_val_AR = -np.sum(np.log(sp.stats.norm.pdf(res_init, np.mean(res_init), std_init))) print('initial OLS with AR fun value: ', ols_val_AR) dev = [std_init / 2, std_init / 2, 0] ARval = 0.4 print('initial ARval: ', ARval) print('initial dev: ', dev) mytakestep = MyTakeStep() if a > 0: xmin = [a * 0.75, b * 0.9] xmax = [a * 1.33, b * 1.1] else: xmin = [a * 1.33, b * 0.9] xmax = [a * 0.75, b * 1.1] print('a range: ', xmax[0], xmin[0]) print('b range: ', xmax[1], xmin[1]) bounds = [(low, high) for low, high in zip(xmin, xmax)] kwargs = {"method": "L-BFGS-B", "args": (x, y, False, mu_l), "bounds": bounds} par_opt = sp.optimize.basinhopping(regress_numeric_line_AR_ent, x0 = [a, b], minimizer_kwargs = kwargs, niter = 5, take_step = mytakestep) hit_limits = par_limits(ARval, dev, std_init, mu_l) return [y, par_opt, hit_limits, nan_valid, ARval, dev] def regress_numeric_line_AR_ent_final(line_pars, x, y, do_print, mu_l): y = np.array(y) fit_y = line_pars[1] + line_pars[0] * x yprev = y[:-1] yprev2 = y[:-2] def findBestAR(pars, y, yprev, yprev2, fit_y, k2 = 1): k1 = pars[0] vs = pars[1:] res = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) new_ent = -np.sum(np.log(ratioProb.pdf(res, vs[2], vs[0], vs[1]))) return new_ent / res.size k1 = 0.4; k2 = 1 res_init = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) std_init = np.std(res_init) xmin = [.15, std_init / 20, std_init / 20, -mu_l * std_init] xmax = [1.3, 2.5 * std_init, 2.5 * std_init, mu_l * std_init] bounds = [(low, high) for low, high in zip(xmin, xmax)] x0_vals = [0.4, std_init / 2, std_init / 2, 0] for i in range(len(x0_vals)): if (bounds[i][0] > x0_vals[i]): x0_vals[i] = bounds[i][0] if (bounds[i][1] < x0_vals[i]): x0_vals[i] = bounds[i][1] # k_opt = sp.optimize.minimize(findBestAR, x0 = ARval, method = 'L-BFGS-B', # bounds = bounds) k_kwargs = {"method": "L-BFGS-B", "args": (y, yprev, yprev2, fit_y), "bounds": bounds} k_opt = sp.optimize.basinhopping(findBestAR, x0 = x0_vals, minimizer_kwargs = k_kwargs, niter = 10) if do_print: print(k_opt.x) k1 = k_opt.x[0] res_post = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) calc_rat_val_AR = -np.sum(np.log(ratioProb.pdf(res_post, k_opt.x[3], k_opt.x[1], k_opt.x[2]))) rep_rat_val_AR = k_opt.fun * (len(y) - 2) fun_prop_diff = (calc_rat_val_AR - rep_rat_val_AR) * 2 / (calc_rat_val_AR + rep_rat_val_AR) print('final reported fun value: ', rep_rat_val_AR) print('final calculated fun value: ', calc_rat_val_AR) if fun_prop_diff > 0.02: print('error: calculated and reported function values different') wait = input("PRESS ENTER TO CONTINUE.") return k_opt.x def regress_numeric_line_opt(line_pars, x, fit_y, pars, k1, k2 = 1): fit_y = np.array(fit_y) y = line_pars[1] + line_pars[0] * x yprev = y[:-1] yprev2 = y[:-2] res = y[2:] - (1 - k1) * yprev[1:] - (1 - k2) * yprev2 - fit_y[2:] * (k1 + k2 - 1) ent = -np.sum(np.log(ratioProb.pdf(res, pars[2], pars[0], pars[1]))) return ent def max_likelihood_line(xs, ys, line_pars): # maximum likelihood of y, given fitted line, rather than add adj mytakestep = MyTakeStep() (a, b, r, tt, stderr) = sp.stats.linregress(xs, ys) if a > 0: xmin = [a * 0.5, b * 0.9] xmax = [a * 2, b * 1.1] else: xmin = [a * 2, b * 0.9] xmax = [a * 0.5, b * 1.1] bounds = [(low, high) for low, high in zip(xmin, xmax)] y_pars = line_pars[1].x y_fit = y_pars[0] * xs + y_pars[1] kwargs = {"method": "L-BFGS-B", "args": (xs, y_fit, line_pars[5], line_pars[4]), "bounds": bounds} par_opt = sp.optimize.basinhopping(regress_numeric_line_opt, x0 = [a, b], minimizer_kwargs = kwargs, niter = 20, take_step = mytakestep) return par_opt.x def predict_true_analy(ce, disc, line_grad, post_chg_arr4): true_predict_corr = []; sign_corr = []; med_true_predict_abs = []; med_true_predict_rel = []; for l in range(1, 25, 1): predict = []; true = []; abs_diff = []; rel_diff = []; for m in range(0, int(len(disc) - l - ce), 2): start = m end = int(m + l) cent = int(m + l + ce) cor_res = robust_cor([list(disc[start : end]), line_grad[start : end]], post_chg_arr4[start : end]) coeffs = [*cor_res[1], cor_res[2]] cur_predict = coeffs[0] * disc[cent] + coeffs[1] * line_grad[cent] + coeffs[2] predict.append(cur_predict) cur_true = post_chg_arr4[cent] true.append(cur_true) abs_diff.append(cur_true - cur_predict) rel_diff.append((cur_true - cur_predict) / cur_true) true_predict_corr.append(robust_cor(predict, true)[0]) sign_corr.append(robust_cor(np.sign(predict), np.sign(true))[0]) med_true_predict_abs.append(np.median(abs_diff)) med_true_predict_rel.append(np.median(rel_diff)) return (true_predict_corr, sign_corr, med_true_predict_abs, med_true_predict_rel) def robust_cor(x, y): if isinstance(x[0], list): x = list(map(list, zip(*x))) else: x = np.array(x).reshape(-1, 1) X = np.array(x) Y = np.array(y) theil_regr = TheilSenRegressor(random_state = 42) theil_regr.fit(X, Y) y_pred = theil_regr.predict(X) res = y_pred - y tot_dev = y - np.mean(y) SSres = np.dot(res, res) SStot = np.dot(tot_dev, tot_dev) adjR2 = 1 - (SSres/SStot) * (X.shape[0] - 1) / (X.shape[0] - X.shape[1] - 1) sgn = np.sign(theil_regr.coef_)[0] if adjR2 > 0: corr_val = sgn * np.sqrt(adjR2) else: corr_val = 0 return [corr_val, theil_regr.coef_, theil_regr.intercept_, theil_regr.breakdown_] def stck_pricing(latest_y, pre_len, pricing, ahead4_val, disc, line_grad, post_chg_arr4): lst_pre_ind = np.array(*np.where(ahead4_val == True))[-1] fst_pre_ind = lst_pre_ind - pre_len new_val = lst_pre_ind + 5 print(disc[-1], disc[new_val]) cor_res = robust_cor([list(disc[fst_pre_ind : lst_pre_ind + 1]), line_grad[fst_pre_ind : lst_pre_ind + 1]], post_chg_arr4[fst_pre_ind : lst_pre_ind + 1]) coeffs = [*cor_res[1], cor_res[2]] pred_chg4 = coeffs[0] * disc[new_val] + coeffs[1] * line_grad[new_val] + coeffs[2] # adjust for latest price # get predicted price, not just change pricing.append(pred_chg4) return pricing def prepare_pricing(latest_y, disc, line_grad, post_chg_arr4, lst_disc, lst_line_grad, pricing): lst_disc.append(disc[-1]) lst_line_grad.append(line_grad[-1]) np_disc = np.array(disc); np_line_grad = np.array(line_grad); np_post_chg_arr4 = np.array(post_chg_arr4) ahead4_val = np.isfinite(np_post_chg_arr4) do_prc_analysis = False # if do_prc_analysis and np.sum(ahead4_val) > 6: # [true_predict_corr, sign_corr, med_true_predict_abs, med_true_predict_rel] \ # = predict_true_analy(4, np_disc[ahead4_val], np_line_grad[ahead4_val], np_post_chg_arr4[ahead4_val]) # if (np.max(true_predict_corr) > 0.25): # pre_len = np.argmax(true_predict_corr) # pricing = stck_pricing(latest_y, pre_len, pricing, ahead4_val, disc, line_grad, post_chg_arr4) # else: # pricing.append(np.nan) # # else: pricing = stck_pricing(latest_y, 5, pricing, ahead4_val, disc, line_grad, post_chg_arr4) return (lst_disc, lst_line_grad, pricing) def best_price(pricing, stock, lst_disc, lst_line_grad): max_ind = np.argmax(np.abs(pricing)) arb = pricing[max_ind] arb_stk = stock[max_ind] if arb > 0: print('Buy') direc = 'underpriced' elif arb < 0: print('Sell') direc = 'overpriced' print(arb_stk, ' is maximum ', direc, ' by ', arb) print(lst_disc[max_ind], lst_line_grad[max_ind]) # plt.plot to show more? print() return (arb_stk, arb) def main(): initialise = False if initialise: init() size = 200 x = np.linspace(0, 2, size) datafiles = ['NVDA_2Daily_150'] # 'FB_2Daily_300' 'NVDA_2Daily_150' 'AAPL_2017_1_15' 'FB_2017_1_15', pricing = [] stock = [] lst_disc = []; lst_line_grad = [] for data_file in datafiles: dfAAPL = pd.read_pickle(data_file) stock.append(data_file.split('_')[0]) #dfAAPL_res3D = dfAAPL.resample('3D').mean() #x = dfAAPL.index.astype(np.int64) / 1e10 y = 50 * dfAAPL['logMedian'] # 50 * improves numerical solver disc = []; line_grad = []; post_chg_arr4 = [] line_pars = []; line_pars0 = [] for mu_l in [1, 2]: # * std for sampleSz in [20]: xs = x[0:sampleSz] g = 1 start = len(dfAAPL) - g - sampleSz finish = start + sampleSz save_file = 'line_pars_' + stock[-1] + '_2017_1_15_inc1_std' + str(mu_l) \ + '_samp' + str(sampleSz) + '_2daily' if os.path.isfile(save_file): exist_pars = pd.read_pickle(save_file).values.tolist() cur_lst = exist_pars[0][6][1] upd_exist = True print('Updating existing line data file') else: max_pers = 2 #150 upd_exist = False print('Creating new line data file') if upd_exist: do = (start > 0) and (dfAAPL.index[finish - 1] > cur_lst) else: do = (start > 0) and (g < max_pers + 1) while do: ys = list(y[start : finish]) print('sample ', str(g - 1), ': processing ', finish - start, ' data pts') line_fit = AR_line_calc(xs, ys, mu_l) par_vals = regress_numeric_line_AR_ent_final(line_fit[1].x, xs, ys, False, mu_l) line_fit[4] = par_vals[0] line_fit[5] = par_vals[1:] startdt = dfAAPL.index[start] # .to_pydatetime() finishdt = dfAAPL.index[finish - 1] line_fit.append([startdt, finishdt]) if (mu_l == 1): line_pars0.append(line_fit) elif (mu_l == 2): maxl_y_pars = max_likelihood_line(xs, ys, line_fit) y_max_line = maxl_y_pars[0] * xs + maxl_y_pars[1] line_fit.append(y_max_line) if not(abs(line_fit[1].x[0] - maxl_y_pars[0]) < 0.01): print('error: line grads differ') # then may need to store maxl_y_pars # forward vals next_10_end = min(finish + 10, len(dfAAPL)) next_10_start = min(finish, len(dfAAPL)) next_10 = np.array(y[next_10_start : next_10_end]) line_fit.append(next_10) # OLS fit for outlier removal (a, b, r, tt, stderr) = sp.stats.linregress(xs, ys) ols_fit = b + a * xs res_ols = ys - ols_fit std_res_ols = np.std(res_ols) ols_val = -np.sum(np.log(sp.stats.norm.pdf(res_ols, np.mean(res_ols), std_res_ols))) \ * (len(ys) - 2) / len(ys) line_fit.append(ols_val) line_pars.append(line_fit) print('finished') print() g = g + 1 start = start - 1 finish = start + sampleSz if upd_exist: do = (start > 0) and (dfAAPL.index[finish - 1] > cur_lst) else: do = (start > 0) and (g < max_pers + 1) try: if upd_exist: if (mu_l == 1): line_pars0.extend(exist_pars) pd.DataFrame(line_pars0).to_pickle(save_file) elif (mu_l == 2): for line in exist_pars: finish_ind = np.where(dfAAPL.index == line[6][1])[0] if finish_ind.size > 0: next_10_end = min(finish_ind[0] + 11, len(dfAAPL)) next_10_start = min(finish_ind[0] + 1, len(dfAAPL)) next_10 = np.array(y[next_10_start : next_10_end]) line[8] = next_10 line_pars.extend(exist_pars) pd.DataFrame(line_pars).to_pickle(save_file) except: print('error: save error') if (mu_l == 2): # remove outliers std_fun_diff = [x[1].fun - y[1].fun for x, y in zip(line_pars, line_pars0)] #ols_fun_diff = [x[1].fun * (len(x[0]) - 2) - x[9] for x in line_pars] outliers = np.where(np.array(std_fun_diff) > 0.01)[0] #outliers = np.append(outliers, np.where(np.array(ols_fun_diff) > 0.01)[0]) outliers = list(set(outliers)) print('Removing', "{:.0f}".format(100 * len(outliers) / len(line_pars)), '% as outliers') if (len(line_pars) - 1) in outliers: print('Current line is outlier. Quitting') return #line_pars = np.delete(line_pars, outliers) disc = [(x[0][-1] - x[7][-1]) for x in line_pars] line_grad = [x[1].x[0] for x in line_pars] post_chg_arr4 = [(x[8][4] - x[0][-1]) if len(x[8]) > 4 else np.nan for x in line_pars] #get ys[-1] and latest_y [lst_disc, lst_line_grad, pricing] = prepare_pricing(5.345, disc, line_grad, post_chg_arr4, lst_disc, lst_line_grad, pricing) [arb_stk, arb] = best_price(pricing, stock, lst_disc, lst_line_grad) # then manually act in TWS? if __name__ == "__main__": main()
0d234f248b3b71ce9898405ac749be7ff19fa13c
[ "Markdown", "Python" ]
3
Python
shaunster0/spline-work
a282a799c018357f72f8e90299c712c2ba7e64c9
195d23a53fdad5d1436fa3fea2657e027d75be0d
refs/heads/master
<file_sep>require 'rubygems' require 'bundler' Bundler.setup :default, (ENV['RACK_ENV'] || 'development') require 'api' <file_sep>source :rubygems gem 'grape' gem 'xen', :git => 'git://github.com/foexle/ruby-xen.git' gem 'log4r' <file_sep>require 'grape' require 'xen/server' require 'xen/instance' Xen::Instance.class_eval do def serializable_hash Hash[*[:dom_id, :name, :memory, :vcpus, :state, :time].map { |attribute| [attribute, send(attribute)] }.flatten] end end module Xen class API < Grape::API resources :machines do helpers do def find(name) instance = Xen::Instance.find_by_name(name) error!('404 Not Found', 404) if instance.nil? instance end end get do Instance.all.map { |instance| instance.serializable_hash } end get ':name' do find(params[:name]) end post do attributes = { :name => params['name'], :ip => params['ip'], :vcpus => params['vcpus'], :memory => params['memory'], :size => params['size'], :arch => params['arch'], :dist => params['dist'] } Instance.create(attributes) end put ':name/start' do Xen::Instance.start(params[:name]) end put ':name/reboot' do instance = find(params[:name]) instance.reboot status(202) instance end put ':name/shutdown' do instance = find(params[:name]) instance.shutdown status(202) instance end # put ':name' do # instance = find(params[:name]) # instance.update_attributes(params) # instance # end delete ':name' do instance = find(params[:name]) instance.destroy instance end end end end <file_sep>require 'environment' require 'rack' if ENV['RACK_ENV'] == 'development' log = File.new('log/development.log', 'a') STDOUT.reopen(log) STDERR.reopen(log) end run Xen::API
5abafafbd46e965c40e226fea376be9e54aab6c7
[ "Ruby" ]
4
Ruby
clemens/restful-xen
cdc1b7cc3494b221873e0e1f8b80f953d6cca305
eca861ac495f843dbaf47a33b4e947dcc2e37285
refs/heads/master
<repo_name>iby1812/4_In_A_Line<file_sep>/README.md Game: Connect 4 <file_sep>/Main.c #include "Main.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <limits.h> #define ROWS 6 #define COLUMS 7 #define YEL "\x1B[33m" #define RED "\x1B[31m" #define BLU "\x1B[34m" #define RESET "\x1B[0m" char matrix[ROWS][COLUMS]; char playerFlag; bool end = false; int colum; int temprow; int flagWinner = 0; Stack playersMoves; void main() { Stack_Init(&playersMoves); Stack_Top(&playersMoves); printf("Welcome!\n\n"); while(!end) { if(Stack_Full(&playersMoves) == 1) { printMatrix(); printf("It's a tie!"); exit(1); } printMatrix(); PlayerX(); printMatrix(); PlayerO(); } } void PlayerX(){ printf("Player X, please enter a column number (or 0 to undo): "); playerFlag = 'X'; put(); } void PlayerO(){ printf("Player O, please enter a column number (or 0 to undo): "); playerFlag = 'O'; put(); } void printMatrix() { for(int i = 0; i < 6; i++) { printf(BLU"|"RESET); for(int j = 0; j < 7; j++) { if(matrix[i][j] == 'O') { printf(YEL"%c"RESET,matrix[i][j]); printf(BLU"|"RESET); } else if(matrix[i][j] == 'X') { printf(RED"%c"RESET,matrix[i][j]); printf(BLU"|"RESET); } else { printf("%c", matrix[i][j]); printf(BLU"|"RESET); } } printf("\n"); } printf(" 1 2 3 4 5 6 7\n"); } void put() { if(scanf("%d", &colum) != 1) { printf("\nInvalid input, bye-bye!"); exit(1); } else if(colum == 0) { if(Stack_Top(&playersMoves) != -1) { undo(Stack_Top(&playersMoves)); Stack_Pop(&playersMoves); } else { printf("Board is empty - can't undo! Please choose another colum: \n"); put(); } } else if(colum >= 1 && colum <= 7) { for(int i = 5; i > -1; i--) { if(matrix[i][colum-1] != 'X' && matrix[i][colum-1] != 'O') { matrix[i][colum-1] = playerFlag; Stack_Push(&playersMoves, colum); if((Stack_Size(&playersMoves)) > 6) { temprow = i; gameOver(); } break; } if(matrix[0][colum-1] == 'X' || matrix[0][colum-1] == 'O') { printf("Invalid input, this column is full. Please choose another one: "); put(); break; } } } else { printf("Invalid input, the number must be between 1 to 7: "); put(); } } void undo(int pull) { for(int i = 0; i < 6; i++) { if(matrix[i][pull-1] == 'X' || matrix[i][pull-1] == 'O') { matrix[i][pull-1] = ' '; break; } } } void gameOver() { gameOver_Down(); Diagonal_TopR_DownL(); Diagonal_TopL_DownR(); Right_Left(); } void gameOver_Down() { for(int i = temprow+1; i < temprow+4; i++) { if (matrix[temprow][colum-1] != matrix[i][colum-1] || i == 6) break; else flagWinner++; } Winner(); } void Diagonal_TopR_DownL() { for(int i = temprow+1, j = colum-2; i < temprow+4, j > colum-5; i++, j--) { if (matrix[temprow][colum-1] != matrix[i][j] || i == 6 || j == -1) break; else flagWinner++; } for(int i = temprow-1, j = colum; i > temprow-4, j < colum+3; i--, j++) { if (matrix[temprow][colum-1] != matrix[i][j] || i == -1 || j == 7) break; else flagWinner++; } Winner(); } void Diagonal_TopL_DownR() { for(int i = temprow+1, j = colum; i < temprow+4, j < colum+3; i++, j++) { if (matrix[temprow][colum-1] != matrix[i][j] || i == 6 || j == 7) break; else flagWinner++; } for(int i = temprow-1, j = colum-2; i > temprow-4, j > colum-5; i--, j--) { if (matrix[temprow][colum-1] != matrix[i][j] || i == -1 || j == -1) break; else flagWinner++; } Winner(); } void Right_Left() { for(int i = colum; i < colum+3 ;i++) { if (matrix[temprow][colum-1] != matrix[temprow][i] || i == 7 ) break; else flagWinner++; } for(int i = colum-2; i > colum-5 ;i--) { if (matrix[temprow][colum-1] != matrix[temprow][i] || i == -1) break; else flagWinner++; } Winner(); } void Winner() { if(flagWinner >= 3) { printMatrix(); printf("Player %c wins!", playerFlag); exit(1); } else { flagWinner = 0; } } <file_sep>/Main.h #include <stdbool.h> #include "Stack.h" void printMatrix(); void PlayerX(); void PlayerO(); void put(); void undo(); void gameOver(); void Winner(); void Diagonal_TopR_DownL(); void Diagonal_TopL_DownR(); void Right_Left(); void gameOver_Down();<file_sep>/Stack.h #define STACK_MAX 6*7 struct Stack { int data[STACK_MAX]; int size; }; typedef struct Stack Stack; void Stack_Init(Stack *S); int Stack_Top(Stack *S); void Stack_Push(Stack *S, int d); void Stack_Pop(Stack *S); int Stack_Full(Stack* s); int Stack_Size(Stack* s);
01585501cdc6369e3f0dfd992087d7a06c6e8c57
[ "Markdown", "C" ]
4
Markdown
iby1812/4_In_A_Line
35a3881b1a41b2b4003a7488ee3bb7cf23eaa1b9
1e4e19192222c47f71f88eb1bcf341452362589b
refs/heads/master
<repo_name>tdiak/starterApp<file_sep>/start.sh #!/bin/bash package_exists() { return $(dpkg -s $1 | grep installed) } PROJECT=$1 CLIENT=$2 GITIGNORE_FILES=(venv html/node_modules html/compiled $PROJECT/db.sqlite3 *.pyc $PROJECT/$PROJECT/localsettings.py) REQUIREMENTS=(django==1.11 psycopg2) if [ -z "$PROJECT" ] then echo "You need to add project name: sh start.sh <project_name>" exit 1 else echo "Your project name: $PROJECT" fi if !(package_exists python-virtualenv) then echo "Dependency python-virtualenv installed" else apt-get install python-virtualenv fi virtualenv venv source venv/bin/activate for item in ${REQUIREMENTS[*]} do pip install $item done django-admin startproject $PROJECT pip freeze > requirements.txt mkdir html html/src html/src/components html/dist touch html/package.json echo $CLIENT if [ $CLIENT = "react" ] then echo " { \"name\": \"$PROJECT\", \"version\": \"1.0.0\", \"description\": \"\", \"main\": \"index.js\", \"author\": \"\", \"license\": \"ISC\", \"devDependencies\": { \"babel-core\": \"^6.26.0\", \"babel-loader\": \"^7.1.2\", \"babel-preset-es2015\": \"^6.24.1\", \"babel-preset-react\": \"^6.24.1\", \"css-loader\": \"^0.28.7\", \"react\": \"^16.1.0\", \"react-dom\": \"^16.1.0\", \"sass-loader\": \"^6.0.6\", \"style-loader\": \"^0.19.0\", \"webpack\": \"^3.8.1\", \"webpack-dev-server\": \"^2.9.4\" }, \"dependencies\": { \"react-dropzone\": \"^4.2.1\", \"react-modal\": \"^3.1.2\" } }" >> html/package.json touch html/webpack.config.js echo " module.exports = { entry: { main: './src/scripts/main.js' }, output: { filename: './dist/scripts/[name].js' }, devtool: 'source-map', module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['react', 'es2015'] } } ] } }" >> html/webpack.config.js elif [ $CLIENT = "vue" ] then echo " { \"name\": \"$PROJECT\", \"version\": \"1.0.0\", \"description\": \"Trying Vue.js\", \"main\": \"index.js\", \"dependencies\": { \"vue\": \"1.0.4\" }, \"devDependencies\": { \"babel-core\": \"^5.8.25\", \"babel-loader\": \"^5.3.2\", \"babel-runtime\": \"^5.8.25\", \"css-loader\": \"^0.21.0\", \"style-loader\": \"^0.13.0\", \"template-html-loader\": \"0.0.3\", \"vue-hot-reload-api\": \"^1.2.0\", \"vue-html-loader\": \"^1.0.0\", \"vue-loader\": \"^6.0.0\", \"webpack\": \"^1.12.2\", \"webpack-dev-server\": \"^1.12.0\" }, \"author\": \"\", \"license\": \"ISC\" } " >> html/package.json touch html/webpack.config.js echo " var path = require('path') var webpack = require('webpack') module.exports = { entry: { main: './src/scripts/main.js' }, output: { filename: './dist/scripts/[name].js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }" >> html/webpack.config.js elif [ "$CLIENT" = "angular" ] then echo " { \"name\": \"$PROJECT\", \"version\": \"1.0.0\", \"description\": \"\", \"scripts\": { \"build\": \"tsc -p src/\", \"build:watch\": \"tsc -p src/ -w\", \"build:e2e\": \"tsc -p e2e/\", \"serve\": \"lite-server -c=bs-config.json\", \"serve:e2e\": \"lite-server -c=bs-config.e2e.json\", \"prestart\": \"npm run build\", \"start\": \"concurrently \\"npm run build:watch\\" \\"npm run serve\\"\", \"pree2e\": \"npm run build:e2e\", \"e2e\": \"concurrently \\"npm run serve:e2e\\" \\"npm run protractor\\" --kill-others --success first\", \"preprotractor\": \"webdriver-manager update\", \"protractor\": \"protractor protractor.config.js\", \"pretest\": \"npm run build\", \"test\": \"concurrently \\"npm run build:watch\\" \\"karma start karma.conf.js\\"\", \"pretest:once\": \"npm run build\", \"test:once\": \"karma start karma.conf.js --single-run\", \"lint\": \"tslint ./src/**/*.ts -t verbose\" }, \"keywords\": [], \"author\": \"\", \"license\": \"MIT\", \"dependencies\": { \"@angular/common\": \"~4.3.4\", \"@angular/compiler\": \"~4.3.4\", \"@angular/core\": \"~4.3.4\", \"@angular/forms\": \"~4.3.4\", \"@angular/http\": \"~4.3.4\", \"@angular/platform-browser\": \"~4.3.4\", \"@angular/platform-browser-dynamic\": \"~4.3.4\", \"@angular/router\": \"~4.3.4\", \"angular-in-memory-web-api\": \"~0.3.0\", \"systemjs\": \"0.19.40\", \"core-js\": \"^2.4.1\", \"rxjs\": \"5.0.1\", \"zone.js\": \"^0.8.4\" }, \"devDependencies\": { \"concurrently\": \"^3.2.0\", \"lite-server\": \"^2.2.2\", \"typescript\": \"~2.1.0\", \"canonical-path\": \"0.0.2\", \"tslint\": \"^3.15.1\", \"lodash\": \"^4.16.4\", \"jasmine-core\": \"~2.4.1\", \"karma\": \"^1.3.0\", \"karma-chrome-launcher\": \"^2.0.0\", \"karma-cli\": \"^1.0.1\", \"karma-jasmine\": \"^1.0.2\", \"karma-jasmine-html-reporter\": \"^0.2.2\", \"protractor\": \"~4.0.14\", \"rimraf\": \"^2.5.4\", \"@types/node\": \"^6.0.46\", \"@types/jasmine\": \"2.5.36\" }, \"repository\": {} } " >> package.json fi touch html/src/main.js cd html npm install cd .. touch .gitignore for item in ${GITIGNORE_FILES[*]} do echo $item >> .gitignore done cd $PROJECT/$PROJECT touch localsettings.py echo " try: from localsettings import * except Exception: print('You need to create localsettings.py file!!') " >> settings.py
0919351038c4e0e82dd7d479f23707bbf508fd52
[ "Shell" ]
1
Shell
tdiak/starterApp
dc5e9021e2fc9ba566ed10f2a5185d8bc8406ecf
b0d018880fd3533f1203688ecf9a3b4a1e9bd585
refs/heads/master
<file_sep>// +build OMIT package main import ( "fmt" "math" ) func main() { fmt.Printf("Сада имате %g проблема.", math.Nextafter(2, 3)) } <file_sep>// +build OMIT package main import ( "fmt" "math/rand" ) func main() { fmt.Println("Мој омиљени број је", rand.Intn(10)) } <file_sep>// +build OMIT package main import ( "fmt" "time" ) func main() { fmt.Println("Добро дошли у играоницу!") fmt.Println("Тачно време је", time.Now()) } <file_sep>package main import "fmt" func main() { v := 42 // промени ме! fmt.Printf("v је врсте %T\n", v) } <file_sep>// +build OMIT package main import "fmt" const Pi = 3.14 func main() { const World = "свете" fmt.Println("Hello", World) fmt.Println("Срећан", Pi, "дан") const Truth = true fmt.Println("Го је закон?", Truth) } <file_sep>/* Copyright 2012 The Go Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ 'use strict'; angular.module('tour.values', []). // List of modules with description and lessons in it. value('tableOfContents', [{ 'id': 'mechanics', 'title': 'Начин употребе обиласка', 'description': '<p>Добро дошли у обилазак <a href="http://golang.org">Го програмског језика</a>. Овај обилазак покрива најважније делове језика, тј. садржи следеће одељке:</p>', 'lessons': ['welcome'] }, { 'id': 'basics', 'title': 'Основе', 'description': '<p>Увод у основе језика. </p><p>Декларисање променљивих, позивање функција и све остале ствари које морате знати пре учења напреднијих ствари.</p>', 'lessons': ['basics', 'flowcontrol', 'moretypes'] }, { 'id': 'methods', 'title': 'Методе и интерфејси', 'description': '<p>Научите како се дефинишу методе над врстама, како се декларишу интерфејси и како се све ове ствар склапају у једну целину.</p>', 'lessons': ['methods'] }, { 'id': 'concurrency', 'title': '', 'description': '<p>У језгру Го језика се налази подршка за упоредну (паралелну) обраду података. </p><p>Овај одељак објашњава горутине и канале, и како се ове две ствари користе за спровођење различитих шаблона парарелне обраде података.</p>', 'lessons': ['concurrency'] }]). // translation value('translation', { 'off': 'искљ.', 'on': 'укљ.', 'syntax': 'Бојење кода', 'lineno': 'Бројеви редова', 'reset': 'Поново постави слајд', 'format': 'Изформатирај изворни код', 'kill': 'Убиј програм', 'run': 'Изврши', 'compile': 'Искомпајлирај и изврши', 'more': 'Опције', 'toc': 'Садржај', 'prev': 'Претходно', 'next': 'Следеће', 'waiting': 'Чекам на удаљени сервер...', 'errcomm': 'Грешка у вези са удаљеним сервером.', }). // Config for codemirror plugin value('ui.config', { codemirror: { mode: 'text/x-go', matchBrackets: true, lineNumbers: true, autofocus: true, indentWithTabs: true, indentUnit: 4, tabSize: 4, lineWrapping: true, extraKeys: { 'Shift-Enter': function() { $('#run').click(); }, 'Ctrl-Enter': function() { $('#format').click(); }, 'PageDown': function() { return false; }, 'PageUp': function() { return false; }, }, // TODO: is there a better way to do this? // AngularJS values can't depend on factories. onChange: function() { if (window.codeChanged !== null) window.codeChanged(); } } });
156dec150e4c4dcef3c5a3b28dde81feebcabc89
[ "JavaScript", "Go" ]
6
Go
kostich/go-tour-SR
2957a6951274f379dbca1e5a03623691494d56de
203e2e74b90ba9bc2cff8556d4f3ce8a01aaa224
refs/heads/main
<file_sep>package com.example.nvigationdraweryswipeviewtabs import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.GravityCompat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { lateinit var toggle: ActionBarDrawerToggle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val firdFradment = TabFragment() val secondFradment = SecondFragment() val thirdFragment = ThirdFragment() toggle = ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close) drawerLayout.addDrawerListener(toggle) supportActionBar?.setDisplayHomeAsUpEnabled(true) toggle.syncState() supportFragmentManager.beginTransaction().apply { replace(R.id.flfragment, firdFradment) //Metodo para volver a aun fragment con el boton Back del celular addToBackStack(null) //metodo para confirmar el cambio de Fragment commit() } navView.setNavigationItemSelectedListener { //Metodo para remplazar los fragment when (it.itemId) { R.id.item1 -> supportFragmentManager.beginTransaction().apply { replace(R.id.flfragment, firdFradment) //Metodo para volver a aun fragment con el boton Back del celular addToBackStack(null) //metodo para confirmar el cambio de Fragment commit() } R.id.item2 -> supportFragmentManager.beginTransaction().apply { replace(R.id.flfragment, secondFradment) addToBackStack(null) commit() } R.id.item3 -> supportFragmentManager.beginTransaction().apply { replace(R.id.flfragment, thirdFragment) addToBackStack(null) commit() } } itemClose() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (toggle.onOptionsItemSelected(item)) { return true } return super.onOptionsItemSelected(item) } private fun itemClose(): Boolean { drawerLayout.closeDrawer(GravityCompat.START) return true } }<file_sep>package com.example.nvigationdraweryswipeviewtabs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.google.android.material.tabs.TabLayoutMediator import kotlinx.android.synthetic.main.contain_main.* class TabFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.contain_main, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adapter by lazy { ViewPagerAdapter(this) } pager.adapter = adapter TabLayoutMediator(tab_layout, pager) { tab, position -> when (position) { 0 -> tab.text = "Posición 1" 1 -> tab.text = "Posición 2" 2 -> tab.text = "Posición 3" } }.attach() } } <file_sep>package com.example.nvigationdraweryswipeviewtabs import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter class ViewPagerAdapter(fragmanetActivity: TabFragment): FragmentStateAdapter(fragmanetActivity) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { when (position) { 0 -> return FirstFragment() 1 -> return SecondFragment() 2 -> return ThirdFragment() } return Fragment() } }
85a1af61f020fbed4dc33de9fe5dfd2834ca269a
[ "Kotlin" ]
3
Kotlin
jolgo1989/NavigationDrawerySwipeViewTabs-ViewPager2-
505a0951a44c5e816c0a4d8ba2b68ab44222891f
23d552a83a9c5b7f245203453393f8c7659d9931
refs/heads/master
<repo_name>securesystemslab/zippy-megaguards<file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test7.py a = [1.,2.,3.,4.] def atomic(): b = 0. for i in range(3): for j in range(4): x = a[j] b += a[i] return b b = atomic() print(b) <file_sep>/README.md ![zippy-logo-200-rounded.jpg](http://ssllab.org/zippy_logo.jpeg) # ZipPy+MegaGuards # ### ZipPy ### | | Graal CE JVM | | :------------------: |:-------------:| | Linux Ubuntu 16.04 | [![Build Status](https://badges.herokuapp.com/travis/securesystemslab/zippy-megaguards?env=ZIPPY_JDK_TYPE=GRAALJVM_LINUX&label=Graal%20JVM)](https://travis-ci.org/securesystemslab/zippy-megaguards) > These builds are without MegaGuards since Travis CI does not support GPU testing ZipPy is a fast and lightweight [Python 3](https://www.python.org/) implementation built using the [Truffle](http://openjdk.java.net/projects/graal/) framework. ZipPy leverages the underlying Java JIT compiler and compiles Python programs to highly optimized machine code at runtime. ZipPy is currently maintained by [Secure Systems and Software Laboratory](http://ssllab.org) at the ​[University of California, Irvine](http://www.uci.edu/). ### MegaGuards ### MegaGuards is a guards optimization and transparent heterogenous computing system that built on top of [Truffle](https://github.com/oracle/graal) framework. MegaGuards analyze and execute AST on Truffle and OpenCL. Currently, *MegaGuards works only on Linux x86 64-Bit and has been tested on Ubuntu x86 64-Bit 16.04.* MegaGuards is currently maintained by [Secure Systems and Software Laboratory](http://ssllab.org) at the ​[University of California, Irvine](http://www.uci.edu/). ## Getting ZipPy+MegaGuards for Ubuntu 16.04 x86 64-Bit: ### Option 1: Using our interactive script (using `curl`, to install `sudo apt-get install curl`): $ mkdir megaguards && cd megaguards $ python -c "$(curl -fsSL https://raw.github.com/securesystemslab/zippy-megaguards/getting-zippy-megaguards.py)" > Some prerequisites require `sudo` privilege to be installed. ### Option 2: Manually: 1. Create a working directory (`$MEGAGUARDS_ROOT`) $ mkdir megaguards && cd megaguards $ export MEGAGUARDS_ROOT=$PWD 2. Download [JDK with JVMCI 8 v0.46](http://www.oracle.com/technetwork/oracle-labs/program-languages/downloads/index.html) and decompress it. $ tar -xzf labsjdk-8u172-jvmci-0.46-linux-amd64.tar.gz 3. Install system dependencies: $ sudo apt-get install build-essential $ sudo apt-get install git wget curl $ sudo apt-get install ocl-icd-opencl-dev clinfo 4. Install GPU and/or CPU drivers (that includes OpenCL icd) from the appropriate vendor based on your system specs. - NVIDIA: https://www.geforce.com/drivers OR $ sudo add-apt-repository ppa:graphics-drivers $ sudo apt-get update $ sudo apt-get install nvidia-390 - AMD: https://support.amd.com/en-us/download - Intel: https://software.intel.com/en-us/articles/opencl-drivers 7. Clone mxtool: $ cd $MEGAGUARDS_ROOT $ git clone https://github.com/graalvm/mx.git 8. Append the `mx` build tool directory to your `PATH`. $ export PATH=$MEGAGUARDS_ROOT/mx:$PATH 9. Clone ZipPy+MegaGuards: $ git clone https://github.com/securesystemslab/zippy-megaguards.git 10. Create a file `$MEGAGUARDS_ROOT/zippy-megaguards/mx.zippy/env` and add JDK path JAVA_HOME=/path/to/labsjdk1.8.0_172-jvmci-0.46 ## replace path with correct one. ## DEFAULT_VM=server DEFAULT_DYNAMIC_IMPORTS=truffle/compiler ZIPPY_MUST_USE_GRAAL=1 > For more information please visit the [ZipPy Wiki](https://github.com/securesystemslab/zippy/wiki). ### Build: $ cd $MEGAGUARDS_ROOT/zippy-megaguards $ mx build ### Check hardware and system compatibility: $ cd $MEGAGUARDS_ROOT/zippy-megaguards $ mx mg --init $ mx mg --clinfo Please try to solve any `error` that our check script encounter. ### Test all the installed tools: $ mx mg --simple-example ### Run a Python program: To enable MegaGuards use: `--mg-target=truffle` to execute using a guardless Truffle AST on Graal. `--mg-target=gpu` to execute on a GPU OpenCL device. `--mg-target=cpu` to execute on a CPU OpenCL device. `--mg-target` to execute using our adaptive OpenCL device selection. $ cd $MEGAGUARDS_ROOT/zippy-megaguards $ mx python <file.py> --mg-target=gpu ### Test: $ cd $MEGAGUARDS_ROOT/zippy-megaguards $ mx junit $ mx junit-mg ### Notes: - ZipPy is still under development and not all language features are available. - ZipPy require few runs to reach optimal performance results. <file_sep>/zippy/edu.uci.python.test/src/edu/uci/megaguards/test/parallel/DDTests.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.test.parallel; import static edu.uci.python.test.PythonTests.assertPrints; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assume.assumeTrue; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import edu.uci.megaguards.MGOptions; import edu.uci.megaguards.test.MGTests; @FixMethodOrder(MethodSorters.JVM) public class DDTests { private static final String path = MGTests.MGSrcTestPath + File.separator + "dd" + File.separator; @Test public void independent() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test1.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void dd_two_variables() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test2.py"); assertPrints("[[2, 2, 3], [1, 4, 3], [1, 2, 6]]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void const_variable() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test3.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void const_variable_dependent() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test4.py"); assertPrints("[2, 4, 4]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void dd_two_loops() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test5.py"); assertPrints("[[2, 4, 6], [2, 4, 6], [2, 4, 6]]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void const_variable_ignore_dependent() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test6.py"); assertPrints("", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void atomic() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test7.py"); assertPrints("6.0\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 3); MGTests.releaseMGParallelOptions(); } @Test public void independent2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test8.py"); assertPrints("[[2, 4, 6], [2, 4, 6], [2, 4, 6]]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void atomic_2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test9.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 3, 0); MGTests.releaseMGParallelOptions(); } @Test public void atomic_subscript_neg_index() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); assumeTrue(MGOptions.testTrowable); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test10.py"); assertPrints("[6, 12, 18]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 2, 0); MGTests.releaseMGParallelOptions(); } @Test public void constant() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test11.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void privatization_1() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test12.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void privatization_2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test13.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void privatization_3() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test14.py"); assertPrints("7\n[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void privatization_4() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test15.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void privatization_5() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test16.py"); assertPrints("0\n[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void privatization_6() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test17.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void dd_test18() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test18.py"); assertPrints("[10, 14, 22]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 2, 0); MGTests.releaseMGParallelOptions(); } @Test public void dd_test19() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test19.py"); assertPrints("[30.0, 120.0, 480.0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 2, 0); MGTests.releaseMGParallelOptions(); } @Test public void dd_test20() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test20.py"); assertPrints("[10, 10, 10]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 2, 0); MGTests.releaseMGParallelOptions(); } @Test public void dd_test21() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test21.py"); assertPrints("[10, 10, 10]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 2, 0); MGTests.releaseMGParallelOptions(); } @Test public void dd_test22() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test22.py"); assertPrints("[189]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test9.py a = [1, 2, 3] c = [0, 0, 0] def t(): n = 0 for i in range(len(a)): for j in range(len(a)): c[i] = a[n]*2 n += 1; t() print(c) <file_sep>/mx.zippy/mx_zippy_asv_chart.py # Copyright (c) 2018, Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from mx_mg_conf import * from mx_mg_pages import * from argparse import ArgumentParser from argparse import RawTextHelpFormatter import os from os.path import join, exists import platform import json import mx import math import re import datetime import copy from mx_zippy_bench_param import benchmarks_list importerror = False try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker from scipy import stats import numpy as np from functools import reduce except: # raise importerror = True debug = False if not importerror: geomean = lambda s: reduce(lambda x,y: x*y, s) ** (1.0 / len(s)) signed_date = '' interpreters_versions = {} benchmarks_images = {} benchmarks_stats_each = {} benchmarks_stats_types = {} benchmarks_stats_overall = {} def add_steps_geomean(_type, benchmarks, all_benchmarks_list): r_benchmarks = {} for _interp in benchmarks: if _interp not in r_benchmarks: r_benchmarks[_interp] = [] for _bench in sorted(all_benchmarks_list): # print('type: '+ _type + ' bench: ' + _bench) _largest_parm = benchmarks_list[_type][1][_bench][-2] _time_steps = benchmarks[_interp][_bench][_largest_parm][0] _step_count = len(_time_steps) if len(r_benchmarks[_interp]) == 0: r_benchmarks[_interp] = [[] for i in range(_step_count)] for _step in range(_step_count): r_benchmarks[_interp][_step] += [_time_steps[_step]] # geomean geomean_str = 'GeoMean' r_benchmarks[_interp] = [geomean(r_benchmarks[_interp][_step]) for _step in range(len(r_benchmarks[_interp]))] benchmarks[_interp][geomean_str] = { geomean_str : [None] } benchmarks[_interp][geomean_str][geomean_str][0] = r_benchmarks[_interp] all_benchmarks_list[geomean_str] = [geomean_str] def custom_normalization_step(_type, benchmarks, interpreter_list): # XXX: err_bar hasn't been normalized _timing = "Steps" r_benchmarks_normalized = copy.deepcopy(benchmarks[_type][_timing]) r_param_max = {} r_param_yaxis = {} # p = 5 for _interp_w_name in range(len(interpreter_list)): _interp = interpreter_list[_interp_w_name][0] if _interp not in r_benchmarks_normalized: continue for _bench in r_benchmarks_normalized[_interp]: if _bench not in r_param_max: r_param_max[_bench] = {} for _param in r_benchmarks_normalized[_interp][_bench]: if _param not in r_param_max[_bench]: r_param_max[_bench][_param] = 0. r_param_max[_bench][_param] = max(r_param_max[_bench][_param], max(r_benchmarks_normalized[_interp][_bench][_param][0])) for _bench in r_param_max: if _bench not in r_param_yaxis: r_param_yaxis[_bench] = {} for _param in r_param_max[_bench]: m = r_param_max[_bench][_param] r = yaxis_scale_range['5'] for i in range(len(yaxis_scale_range_list)): r = yaxis_scale_range['%s' % yaxis_scale_range_list[i]] if yaxis_scale_range_list[i] > m: break r_param_yaxis[_bench][_param] = r for _interp in r_benchmarks_normalized: for _bench in r_benchmarks_normalized[_interp]: for _param in r_benchmarks_normalized[_interp][_bench]: yaxis_local_range = r_param_yaxis[_bench][_param] yaxis_range_len = len(yaxis_local_range) - 1 for _step in range(len(r_benchmarks_normalized[_interp][_bench][_param][0])): _time = r_benchmarks_normalized[_interp][_bench][_param][0][_step] n = _time for j in range(yaxis_range_len): n = (_time - yaxis_local_range[j])/(yaxis_local_range[j + 1] - yaxis_local_range[j]) if n > 1 and j < (yaxis_range_len - 1): continue n = n + j break r_benchmarks_normalized[_interp][_bench][_param][0][_step] = n return r_benchmarks_normalized, r_param_yaxis def plot_steps(benchmarks_origin, all_benchmarks_list_origin, base, interpreter_list, step_str='steps', single_benchmark=None, filename_prefix=''): benchmarks = copy.deepcopy(benchmarks_origin) all_benchmarks_list = copy.deepcopy(all_benchmarks_list_origin) legend_num_col = len(interpreter_list) legend_num_col = legend_num_col / 2 + legend_num_col % 2 for _type in benchmarks: _timing = 'Steps' add_steps_geomean(_type, benchmarks[_type][_timing], all_benchmarks_list[_type][_timing]) r_benchmarks_normalized, r_param_yaxis = custom_normalization_step(_type, benchmarks, interpreter_list) for _bench in all_benchmarks_list[_type][_timing]: print("%s %s" % (single_benchmark, _bench)) if single_benchmark and _bench != single_benchmark: continue _param_axs = {} _param_xticks = {} for _param in all_benchmarks_list[_type][_timing][_bench]: _param_axs[_param] = None if not _param_axs: continue subplots_count = len(_param_axs) axs = [] max_col_subplot = 3 if subplots_count == 1: fig, axs2d = plt.subplots(1, 1, figsize=(8, 4))#, figsize=(2.5 * int(subplots_count / 2), 5)) axs = [axs2d] elif subplots_count <= max_col_subplot: # print(subplots_count) fig, axs2d = plt.subplots(1, subplots_count)#, figsize=(2.5 * int(subplots_count / 2), 5)) for i in range(len(axs2d)): axs2d[i].axis('off') axs += [axs2d[i]] else: row_count = float(subplots_count)/max_col_subplot row_count = int(row_count) if (int(row_count) - row_count) == 0. else (int(row_count) + 1) # print("%d: %d x %d" % (subplots_count, row_count, col_count)) fig, axs2d = plt.subplots(row_count, max_col_subplot)#, figsize=(2.5 * int(subplots_count / 2), 5)) # print(axs2d) for i in range(len(axs2d)): for j in range(len(axs2d[i])): axs2d[i][j].axis('off') axs += [axs2d[i][j]] fig.subplots_adjust(left=0.06, right=0.98, wspace=0.01, hspace=0.02) axs_i = 0 for _param in sorted(_param_axs.keys()): axs[axs_i].axis('on') _param_axs[_param] = axs[axs_i] # axs[axs_i].set_autoscalex_on(False) axs_i += 1 # for _interp in benchmarks[_type][_timing]: lines = [[], []] for _interp_w_name in range(len(interpreter_list)): _interp = interpreter_list[_interp_w_name][0] if _interp not in benchmarks[_type][_timing]: continue for _param in benchmarks[_type][_timing][_interp][_bench]: ax = _param_axs[_param] _param_xticks[_param] = [ i+1 for i in range(len(benchmarks[_type][_timing][_interp][_bench][_param][0]))] marker = plot_steps_color_hatch_marker[_interp][2] color = plot_steps_color_hatch_marker[_interp][0] # line = ax.plot(_params, r_bench_params, marker, color=color) # label=_interp line, = ax.plot(range(len(_param_xticks[_param])), r_benchmarks_normalized[_interp][_bench][_param][0], marker, color=color) # label=_interp lines[0] += [line] lines[1] += [interpreter_list[_interp_w_name][1]] for _param in _param_xticks: _params_str = _param_xticks[_param] _params_int = [] for i in range(len(_params_str)): _params_int += [int(_params_str[i])] _param_xticks[_param] = [_params_int, _params_str] for _param in sorted(_param_axs.keys()): ax = _param_axs[_param] # ax.set_xscale('log') _params_len = len(_param_xticks[_param][0]) ax.set_xticks(range(_params_len)) # ax.set_ylim(-0.5, ax.get_ylim()[1] + 0.5) ax.set_xlim(-0.5, _params_len - 0.5) ax.set_xticklabels(_param_xticks[_param][1], fontsize='large') # , rotation=45 # ax.legend(loc='upper left') # ax.set_yscale('linear') # 'log' ax.set_yticks(range(len(r_param_yaxis[_bench][_param]))) ax.set_yticklabels(['%s' % x for x in r_param_yaxis[_bench][_param]],fontsize='x-small') ax.set_title(_param, fontsize='medium') ax.grid(True) fig.legend(lines[0], lines[1], fontsize='small', ncol=legend_num_col, bbox_to_anchor=(0., 1.17, 1., .0), loc=9 # mode="expand" ) fig.text(0.5, -0.02, 'Running steps', fontsize='large', ha='center') fig.text(0.00, 0.5, "Speedup over " + base, fontsize='large', va='center', rotation='vertical') # fig.ylabel("Speedup over " + base, fontsize='large') filename = filename_prefix+'benchmarks_' + step_str + '_' + _bench # benchmarks_images['Steps `' + _type + '` benchmarks chart measuring `' + _timing + '` timing:'] = filename benchmarks_images[filename_prefix + ' Steps'] = filename fig.savefig(chart_dir + filename + '.png', bbox_inches='tight') fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight') plt.close(fig) def pre_plot_scales_collect_params(_type, _timing, all_benchmarks_list, benchmarks): r_bench_params = {} r_bench_max = {} # p = 5 for _interp_w_name in range(len(interpreter_list_scales_ordered)): _interp = interpreter_list_scales_ordered[_interp_w_name][0] r_bench_params[_interp] = {} for _bench in benchmarks[_interp]: if _bench not in r_bench_max: r_bench_max[_bench] = 0. r_bench_params[_interp][_bench] = [] _params = all_benchmarks_list[_type][_timing][_bench] for _param in _params: r_bench_params[_interp][_bench] += [benchmarks[_interp][_bench][_param][0]] # if p > 0: # p -= 1 # print(benchmarks[_interp][_bench][_param]) r_bench_max[_bench] = max(r_bench_max[_bench], max(r_bench_params[_interp][_bench])) # print(r_bench_max) return r_bench_params, r_bench_max def custom_normalization_scale(r_benchmarks, r_bench_max): r_benchmarks_normalized = copy.deepcopy(r_benchmarks) r_bench_yaxis = {} for _bench in r_bench_max: m = r_bench_max[_bench] r = yaxis_scale_range['5'] for i in range(len(yaxis_scale_range_list)): r = yaxis_scale_range['%s' % yaxis_scale_range_list[i]] if yaxis_scale_range_list[i] > m: break r_bench_yaxis[_bench] = r for _interp in r_benchmarks_normalized: for _bench in r_benchmarks_normalized[_interp]: yaxis_local_range = r_bench_yaxis[_bench] yaxis_range_len = len(yaxis_local_range) - 1 for _param in range(len(r_benchmarks_normalized[_interp][_bench])): _time = r_benchmarks_normalized[_interp][_bench][_param] n = _time for j in range(yaxis_range_len): n = (_time - yaxis_local_range[j])/(yaxis_local_range[j + 1] - yaxis_local_range[j]) if n > 1 and j < (yaxis_range_len - 1): continue n = n + j break r_benchmarks_normalized[_interp][_bench][_param] = n return r_benchmarks_normalized, r_bench_yaxis def plot_scales(benchmarks, all_benchmarks_list, base, filename_prefix=''): for _type in benchmarks: for _timing in benchmarks[_type]: # if _timing == 'Time': # continue if _timing == 'Steps': continue if _timing == 'Warmup': continue _bench_axs = {} _bench_xticks = {} for _bench in all_benchmarks_list[_type][_timing]: _bench_axs[_bench] = None if not _bench_axs: continue subplots_count = len(_bench_axs) # print(subplots_count) fig, axs2d = plt.subplots(2, int(subplots_count / 2), figsize=(2.5 * int(subplots_count / 2), 4)) fig.subplots_adjust(left=0.08, right=0.98, wspace=0.3, hspace=0.5) axs = [] for i in range(len(axs2d)): for j in range(len(axs2d[i])): axs += [axs2d[i][j]] axs_i = 0 for _bench in sorted(_bench_axs.keys()): _bench_axs[_bench] = axs[axs_i] # axs[axs_i].set_autoscalex_on(False) axs_i += 1 r_benchmarks, r_bench_max = pre_plot_scales_collect_params(_type, _timing, all_benchmarks_list, benchmarks[_type][_timing]) r_benchmarks_normalized, r_bench_yaxis = custom_normalization_scale(r_benchmarks, r_bench_max) # for _interp in benchmarks[_type][_timing]: lines = [[], []] for _interp_w_name in range(len(interpreter_list_scales_ordered)): _interp = interpreter_list_scales_ordered[_interp_w_name][0] for _bench in benchmarks[_type][_timing][_interp]: # if _bench not in _bench_xticks: # _bench_xticks[_bench] = [] ax = _bench_axs[_bench] _params = all_benchmarks_list[_type][_timing][_bench] # print(_params) _bench_xticks[_bench] = _params # r_bench_params = pre_plot_scales_collect_params(_params, benchmarks[_type][_timing][_interp][_bench]) marker = plot_scales_color_hatch_marker[_interp][2] color = plot_scales_color_hatch_marker[_interp][0] # line = ax.plot(_params, r_bench_params, marker, color=color) # label=_interp line, = ax.plot(range(len(_params)), r_benchmarks_normalized[_interp][_bench], marker, color=color) # label=_interp lines[0] += [line] lines[1] += [interpreter_list_scales_ordered[_interp_w_name][1]] for _bench in _bench_xticks: _params_str = _bench_xticks[_bench] _params_int = [] for _param in range(len(_params_str)): _params_int += [_params_str[_param]] _bench_xticks[_bench] = [_params_int, _params_str] for _bench in sorted(_bench_axs.keys()): ax = _bench_axs[_bench] # ax.set_xscale('log') _params_len = len(_bench_xticks[_bench][0]) ax.set_xticks(range(_params_len)) # ax.set_ylim(-0.5, ax.get_ylim()[1] + 0.5) ax.set_xlim(-0.5, _params_len - 0.5) ax.set_xticklabels(_bench_xticks[_bench][1], rotation=45, fontsize='xx-small') # ax.legend(loc='upper left') # ax.set_yscale('linear') # 'log' ax.set_yticks(range(len(r_bench_yaxis[_bench]))) yticklabels_str = ['%s' % x for x in r_bench_yaxis[_bench]] ax.set_yticklabels(yticklabels_str,fontsize='xx-small') ax.set_title(_bench, fontsize='medium') ax.grid(True) fig.legend(lines[0], lines[1], fontsize='medium', ncol=6, bbox_to_anchor=(0., 1.15, .98, .0), loc=9 # mode="expand" ) fig.text(0.5, -0.05, 'Benchmarks input sizes', ha='center') fig.text(0.04, 0.5, "Speedup over " + base, fontsize='large', va='center', rotation='vertical') # fig.ylabel("Speedup over " + base, fontsize='large') filename = filename_prefix+'benchmarks_scales_' + _type + '_' + _timing # benchmarks_images['Scale `' + _type + '` benchmarks chart measuring `' + _timing + '` timing:'] = filename benchmarks_images[filename_prefix + ' Scale'] = filename fig.savefig(chart_dir + filename + '.png', bbox_inches='tight') fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight') plt.close(fig) def plot_bar_speedups_dm(r_benchmarks_normalized, r_benchmarks_ci_normalized, benchmarks, all_benchmarks_list, _type, _timing, small=True, filename_prefix=''): size = len(all_benchmarks_list) size = (12, 4) fig = plt.figure(figsize=size) #, dpi=80) ax = fig.add_subplot(1, 1, 1) ax.xaxis.tick_top() ax.tick_params(labeltop='off') ax.xaxis.tick_bottom() ax.spines['top'].set_visible(False) ly = len(all_benchmarks_list) xticks = np.arange(1, ly + 1) r_benchmarks_dm = [] r_benchmarks_dm_ci = [] for i in range(len(benchmarks['MG-GPU'])): r_benchmarks_dm += [benchmarks['MG-GPU'][i] / benchmarks['MG-NoDM'][i]] r = ax.bar( xticks, r_benchmarks_dm, .5, align='center', color='k') ax.set_xticks(xticks) if small: ax.set_xticklabels(all_benchmarks_list, fontsize='small')#, rotation=45, horizontalalignment='right') else: ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45) (y_bottom, y_top) = ax.get_ylim() y_height = y_top - y_bottom y_height = np.log2(y_height) def autolabel(rects, y_height): i = 0 for rect in rects: height = rect.get_height() p_height = np.log2(height) / (y_height) max_hight = 0.90 if small else 0.90 label_rotation ='horizontal' if small: fontsize='x-small' else: fontsize='large' ax.text( rect.get_x() + rect.get_width()/2., 1.02*height, '%.2f' % r_benchmarks_dm[i], ha='center', va='bottom', fontsize=fontsize, # fontsize='medium' fontweight='bold', rotation=label_rotation) i += 1 autolabel(r, y_height) ax.set_xlim(.3, ly + .7) ax.yaxis.grid(True) ax.set_ylabel("Speedup over MegaGuards-GPU\nwithout KDM", fontsize='medium') ax.set_yscale('symlog', basey=2) ax.tick_params(direction='out') # ax.set_yticks([0, 1, 2, 4, 8, 16, 32]) # ax.set_yticklabels([0, 1, 2, 4, 8, 16, 32, 64],fontsize=11) fig.subplots_adjust(left=0.05) filename = filename_prefix+'benchmarks_bar_KDM_' + _type + '_' + _timing benchmarks_images[filename_prefix + ' KDM Optimization'] = filename fig.savefig(chart_dir + filename + '.png', bbox_inches='tight') fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight') plt.close(fig) def plot_bar_speedups(ax, r_benchmarks_normalized, r_benchmarks_ci_normalized, benchmarks, all_benchmarks_list, interpreter_list, color_hatch, witdh, small=True): ax.xaxis.tick_top() ax.tick_params(labeltop='off') ax.xaxis.tick_bottom() ax.spines['top'].set_visible(False) ly = len(all_benchmarks_list) xticks = np.arange(1, ly + 1) # ax.bar(xticks, y, align='center') c_witdh = 0 rects = [[], [], []] interpreter_list_ordered_filtered = [] for _interp in interpreter_list_ordered: if _interp[0] in interpreter_list: interpreter_list_ordered_filtered += [_interp] for i in range(len(interpreter_list_ordered_filtered)): s = interpreter_list_ordered_filtered[i][0] r = ax.bar( xticks + c_witdh, r_benchmarks_normalized[s], witdh, align='center', yerr=r_benchmarks_ci_normalized[s], capsize=1, ecolor='black', color=color_hatch[s][0], hatch=color_hatch[s][1]) rects[0] += [r] rects[1] += [s] rects[2] += [interpreter_list_ordered_filtered[i][1]] c_witdh += witdh ax.set_xticks(xticks + c_witdh/2.3) if small: ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45) else: ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45) (y_bottom, y_top) = ax.get_ylim() y_height = y_top - y_bottom y_height = np.log2(y_height) def autolabel(rects, s, y_height): i = 0 for rect in rects: height = rect.get_height() p_height = np.log2(height) / (y_height) max_hight = 0.90 if small else 0.90 label_rotation ='vertical' if small: fontsize='small' else: fontsize='large' ax.text( rect.get_x() + rect.get_width()/2., 1.02*height, '%.2f' % benchmarks[s][i], ha='center', va='bottom', fontsize=fontsize, # fontsize='medium' fontweight='bold', rotation=label_rotation) i += 1 for r, s in zip(rects[0], rects[1]): autolabel(r, s, y_height) if small: ax.legend(rects[0], rects[2], fontsize='large', ncol=5, bbox_to_anchor=(0., 1.12, 1., .102), loc=3, mode="expand") else: ax.legend(rects[0], rects[2], fontsize='large', ncol=5, mode="expand") ax.set_xlim(.7, ly + 1) ax.yaxis.grid(True) def custom_normalization(r_benchmarks, yaxis_range): r_benchmarks_normalized = copy.deepcopy(r_benchmarks) yaxis_range_len = len(yaxis_range) - 1 for _interp in r_benchmarks_normalized: for i in range(len(r_benchmarks_normalized[_interp])): _time = r_benchmarks_normalized[_interp][i] n = _time for j in range(yaxis_range_len): n = (_time - yaxis_range[j])/(yaxis_range[j + 1] - yaxis_range[j]) if n > 1 and j < (yaxis_range_len - 1): continue n = n + j break r_benchmarks_normalized[_interp][i] = n return r_benchmarks_normalized def custom_normalization_ci(r_benchmarks_ci, r_benchmarks_normalized, r_benchmarks, yaxis_range): r_benchmarks_ci_normalized = copy.deepcopy(r_benchmarks_ci) yaxis_range_len = len(yaxis_range) - 1 for _interp in r_benchmarks_ci_normalized: for i in range(len(r_benchmarks_ci_normalized[_interp])): _ci = r_benchmarks_ci_normalized[_interp][i] _time = r_benchmarks[_interp][i] n = _ci for j in range(yaxis_range_len): n = ((_ci + _time) - yaxis_range[j])/(yaxis_range[j + 1] - yaxis_range[j]) if n > 1 and j < (yaxis_range_len - 1): continue n = n + j break r_benchmarks_ci_normalized[_interp][i] = n - r_benchmarks_normalized[_interp][i] return r_benchmarks_ci_normalized def pre_process_plot(benchmarks, all_benchmarks_list, _type, use_largest=True): r_benchmarks = {} r_benchmarks_ci = {} r_benchmarks_list = {} is_bench_list_complete = False for _interp in benchmarks: if _interp not in r_benchmarks: r_benchmarks[_interp] = [] r_benchmarks_ci[_interp] = [] r_benchmarks_list = [] for _bench in sorted(all_benchmarks_list): c_bench_list = [] idx_bench = int( len(all_benchmarks_list[_bench]) / 2 ) _bench_params = all_benchmarks_list[_bench] if not use_largest: for idx in range(len(_bench_params)): _param = _bench_params[idx] r_benchmarks[_interp] += [benchmarks[_interp][_bench][_param][0]] r_benchmarks_ci[_interp] += [benchmarks[_interp][_bench][_param][1]] c_bench_list += [(_param + '\n' + _bench)] else: _largest_parm = benchmarks_list[_type][1][_bench][-2] r_benchmarks[_interp] += [benchmarks[_interp][_bench][_largest_parm][0]] r_benchmarks_ci[_interp] += [benchmarks[_interp][_bench][_largest_parm][1]] c_bench_list += [_bench] if not is_bench_list_complete: r_benchmarks_list += c_bench_list # geomean r_benchmarks[_interp] += [geomean(r_benchmarks[_interp])] r_benchmarks_ci[_interp] += [geomean(r_benchmarks_ci[_interp])] print('%s geomean: %f (%.3f)' % (_interp, r_benchmarks[_interp][-1], r_benchmarks_ci[_interp][-1])) r_benchmarks_list += ['GeoMean'] r_benchmarks_normalized = r_benchmarks#custom_normalization(r_benchmarks, yaxis_range) r_benchmarks_ci_normalized = r_benchmarks_ci#custom_normalization_ci(r_benchmarks_ci, r_benchmarks_normalized, r_benchmarks, yaxis_range) return r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_benchmarks_list # yaxis_range = [0.001, .1, 1, 2, 5, 10, 20, 100, 200, 300, 400] yaxis_range_001_5 = [0.001, .1, 1, 2, 5] yaxis_range_10_100 = [i for i in range(10, 100, 10)] yaxis_range_100_350 = [i for i in range(100, 330, 10)] yaxis_range = yaxis_range_001_5 + yaxis_range_10_100 + yaxis_range_100_350 yaxis_range_str = [ '%s' % i for i in yaxis_range_001_5] + [ '%s' % i for i in yaxis_range_10_100] + [ '%s' % i if (i % 50) == 0 else '' for i in yaxis_range_100_350] # yaxis_range_str = [0.001, .1, 1, 2, 5] + [i for i in range(10, 400, 10)] def process_plot(benchmarks, all_benchmarks_list, interpreter_list, color_hatch_marker, base, only_dm=False, filename_prefix=''): for _type in benchmarks: for _timing in benchmarks[_type]: if _timing == 'Steps': continue if _timing == 'Warmup': continue r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list = pre_process_plot(benchmarks[_type][_timing], all_benchmarks_list[_type][_timing], _type) # markdown_overall_speedups(_type, _timing, r_benchmarks, benchmarks_stats_types, benchmarks_stats_overall) size = len(r_bench_list) size = (max(size * 2, 8), min(size, 7)) fig = plt.figure(figsize=size) #, dpi=80) ax = fig.add_subplot(1, 1, 1) # interpreter_list.remove(base) # r_benchmarks_normalized.pop(base) width = 1. / (len(interpreter_list) + 2) # +1 for spacing and -1 for base plot_bar_speedups(ax, r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list, interpreter_list, color_hatch_marker, width) if 'MG-GPU' in interpreter_list and 'MG-NoDM' in interpreter_list and only_dm: plot_bar_speedups_dm(r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list, _type, _timing, filename_prefix=filename_prefix) continue # ax.set_xlabel("Benchmarks (" + _type + ") (normalized to " + base + ")") ax.set_ylabel("Speedup over " + base, fontsize='large') ax.set_yscale('symlog', basey=2) ax.tick_params(direction='out') # ax.set_yticks(range(len(yaxis_range))) # ax.set_yticks([0, 1, 2, 4, 8, 16]) # ax.set_yticklabels([0, 1, 2, 4, 8, 16],fontsize=15) fig.subplots_adjust(left=0.03) filename = filename_prefix+'benchmarks_bar_' + _type + '_' + _timing # benchmarks_images['Bar `' + _type + '` benchmarks measuring `' + _timing + '` timing:'] = filename benchmarks_images[filename_prefix + ' Speedups'] = filename fig.savefig(chart_dir + filename + '.png', bbox_inches='tight') fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight') plt.close(fig) def normalize_to_base(b, t_list): b = b if b > 0.001 else 0.001 # in case it was too fast s = [] for t in t_list: t = t if t > 0.001 else 0.001 # in case it was too fast t = b / t s += [float(("%.5f" % t))] return s def std_deviation(s): return np.array(s).std() def std_error(s): return np.array(s).std()/math.sqrt(len(s)) def confidence_interval(s): z_critical = stats.norm.ppf(q = 0.95) return z_critical * std_error(s) def error_bar_method(s): return std_error(s) # return std_deviation(s) # return confidence_interval(s) def calculate_speedup(b, runs, is_list, is_base=False): if is_list: _err_bar = [] _s = [] for i in range(len(b)): _b = geomean(b[i]) # print(runs) _s += [normalize_to_base(_b, runs[i])] _err_bar += [error_bar_method(_s[i])] if is_base: _s[i] = 1. else: _s[i] = geomean(_s[i]) return _s, _err_bar else: _b = geomean(b) _s = normalize_to_base(_b, runs) _err_bar = error_bar_method(_s) if is_base: _s = 1. else: _s = geomean(_s) return _s, _err_bar def do_speedups(benchmarks, base='CPython'): benchmarks_speedups = {} is_steps = False for _type in benchmarks: # print(_type) for _timing in benchmarks[_type]: # print(_timing) if _timing == "Steps": is_steps = True # if _timing == 'Warmup': # continue for _interp in benchmarks[_type][_timing]: if _interp == base: continue for _bench in benchmarks[_type][_timing][_interp]: for _param in benchmarks[_type][_timing][_interp][_bench]: b = benchmarks[_type][_timing][ base ][_bench][_param] runs = benchmarks[_type][_timing][_interp][_bench][_param] s, err_bar = calculate_speedup(b, runs, is_steps) benchmarks[_type][_timing][_interp][_bench][_param] = [ s, err_bar ] # print('%s benchname: %s Time: %.2f (%.2f)' % (_interp, _bench, benchmarks[_type][_timing][_interp][_bench][_param][0], benchmarks[_type][_timing][_interp][_bench][_param][1])) # set base timing to 1.0x _interp = base for _bench in benchmarks[_type][_timing][_interp]: for _param in benchmarks[_type][_timing][_interp][_bench]: b = benchmarks[_type][_timing][ base ][_bench][_param] runs = benchmarks[_type][_timing][_interp][_bench][_param] s, err_bar = calculate_speedup(b, runs, is_steps, True) benchmarks[_type][_timing][_interp][_bench][_param] = [ s, err_bar ] is_steps = False # benchmarks[_type][_timing].pop(base) def subtract_data_transfer(profile_data_single_core, benchmarks, new_single_core_str): _interp_cpu1 = 'MG-CPU1' for _type in benchmarks: for _timing in benchmarks[_type]: _result = benchmarks[_type][_timing][_interp_cpu1] _result = copy.deepcopy(_result) benchmarks[_type][_timing][new_single_core_str] = _result for _single_bench in profile_data_single_core: _sb_param = _single_bench.split('.') _sb = _sb_param[0] _param = _sb_param[1] for i in range(len(benchmarks[_type][_timing][new_single_core_str][_sb][_param])): benchmarks[_type][_timing][new_single_core_str][_sb][_param][i] -= profile_data_single_core[_single_bench][i] def do_geomean(benchmarks_pure): benchmarks = copy.deepcopy(benchmarks_pure) for _type in benchmarks: for _timing in benchmarks[_type]: for _interp in benchmarks[_type][_timing]: for _bench in benchmarks[_type][_timing][_interp]: for _param in benchmarks[_type][_timing][_interp][_bench]: if isinstance(benchmarks[_type][_timing][_interp][_bench][_param][0], list): _runs = benchmarks[_type][_timing][_interp][_bench][_param] # _steps = [[_runs[i][j] for j in range(_run[i])] for i in range(len(_runs))] _steps = [ geomean(benchmarks[_type][_timing][_interp][_bench][_param][i]) for i in range(len(_runs))] benchmarks[_type][_timing][_interp][_bench][_param] = _steps else: g = geomean(benchmarks[_type][_timing][_interp][_bench][_param]) benchmarks[_type][_timing][_interp][_bench][_param] = g return benchmarks def _read_results(systems_list, selected_benchmarks_list): global signed_date interpreter_list = [] color_hatch_marker = {} ch = 0 benchmarks = {} all_benchmarks_list = {} results_list = os.listdir(machine_results_dir) for f in sorted(results_list): if f == 'machine.json' or not f.endswith('.json'): continue result_tag = f.replace('.json','').split('-') # _interp = result_tag[1] # ZipPy _ver = result_tag[0] # version _type = result_tag[-5] + '-' + result_tag[-4] # normal, micro,.. _timing = result_tag[-3] # peak _run = result_tag[-1] # run # _commit = '' if 'profile' in _run: continue with open(machine_results_dir + '/' + f) as benchmark_file: bench_json = json.load(benchmark_file) # if 'commit_hash' not in bench_json or bench_json['commit_hash'] != commit_hash: # continue _commit = bench_json['commit_hash'] _interp = str(bench_json['params']['interpreter']) if systems_list: if _interp not in systems_list: continue if signed_date == '': signed_date = ' (revision ' + commit_hash + ')' date = bench_json['date'] date = datetime.datetime.fromtimestamp(int(date) / 1e3) signed_date = date.strftime("%Y-%d-%m %H:%M:%S") + signed_date if _type not in benchmarks: benchmarks[_type] = {} benchmarks[_type]['Warmup'] = {} benchmarks[_type]['Time'] = {} benchmarks[_type]['Steps'] = {} all_benchmarks_list[_type] = {} all_benchmarks_list[_type]['Warmup'] = {} all_benchmarks_list[_type]['Time'] = {} all_benchmarks_list[_type]['Steps'] = {} if _interp not in interpreters_versions: interpreters_versions[_interp] = _ver if _interp not in benchmarks[_type]['Warmup']: benchmarks[_type]['Warmup'][_interp] = {} benchmarks[_type]['Time'][_interp] = {} benchmarks[_type]['Steps'][_interp] = {} for _single_bench in bench_json['results']: _sb = str(_single_bench.replace( _type + '.', '')) if _sb in blacklist_bench: continue if selected_benchmarks_list: if _sb not in selected_benchmarks_list: continue if _sb not in all_benchmarks_list[_type]['Warmup']: all_benchmarks_list[_type]['Warmup'][_sb] = [] all_benchmarks_list[_type]['Time'][_sb] = [] all_benchmarks_list[_type]['Steps'][_sb] = [] # [] for i in range(len(bench_json['results'][_single_bench]['params'][0])): _param = str(bench_json['results'][_single_bench]['params'][0][i]) _time = bench_json['results'][_single_bench]['result'][i] if _time == None: continue if _sb in blacklist_bench_param and _param in blacklist_bench_param[_sb]: continue if _param not in all_benchmarks_list[_type]['Warmup'][_sb]: all_benchmarks_list[_type]['Warmup'][_sb] += [_param] all_benchmarks_list[_type]['Time'][_sb] += [_param] all_benchmarks_list[_type]['Steps'][_sb] += [_param] if _sb not in benchmarks[_type]['Warmup'][_interp]: benchmarks[_type]['Warmup'][_interp][_sb] = {} benchmarks[_type]['Time'][_interp][_sb] = {} benchmarks[_type]['Steps'][_interp][_sb] = {} _time = [float(_t) for _t in _time] if _param not in benchmarks[_type]['Warmup'][_interp][_sb]: benchmarks[_type]['Warmup'][_interp][_sb][_param] = [] benchmarks[_type]['Time'][_interp][_sb][_param] = [] benchmarks[_type]['Steps'][_interp][_sb][_param] = [[] for _t in range(len(_time))] benchmarks[_type]['Warmup'][_interp][_sb][_param] += [_time[0]] benchmarks[_type]['Time'][_interp][_sb][_param] += [min(_time)] for _t in range(len(_time)): benchmarks[_type]['Steps'][_interp][_sb][_param][_t] += [_time[_t]] if _interp not in interpreter_list: interpreter_list += [_interp] color_hatch_marker[_interp] = interpreter_color_hatch_marker[_interp] ch += 1 if debug: print("{0}: {1} -- type: {2} timing: {3} --run {4} --commit {5}".format(_interp, _ver, _type, _timing, _run, _commit)) return interpreter_list, color_hatch_marker, benchmarks, all_benchmarks_list def plot_stack_bars(legends_names, benchmarks, total_times, profile_data, filename_prefix=''): # print(legends_names) # print(benchmarks) # print(profile_data) f, ax = plt.subplots(1, figsize=(12,5)) # Set bar width at 1 bar_width = .25 # positions of the left bar-boundaries bar_l_1 = [i for i in range(len(benchmarks))] bar_l_2 = [i + bar_width + .1 for i in range(len(benchmarks))] # positions of the x-axis ticks (center of the bars as bar labels) # tick_pos = [(i + j) / 2 for i,j in zip(bar_l_1, bar_l_2)] tick_pos = [i+(bar_width) for i in bar_l_1] num_benchmarks = len(benchmarks) totals_1 = [0. for i in range(num_benchmarks)] totals_2 = [0. for i in range(num_benchmarks)] legends_bars = [] legends_bars_2 = [] for i in range(len(legends_names)): legend_list_1 = [profile_data["profile1"][b][i] for b in range(num_benchmarks)] legend_list_2 = [profile_data["profile2"][b][i] for b in range(num_benchmarks)] legends_bars += [ax.bar(bar_l_1, legend_list_1, bottom=totals_1, label='Post Score', alpha=0.9, color=list_color_hatch_marker[i][0], hatch=list_color_hatch_marker[i][1], width=bar_width, edgecolor = "none",#'black' linewidth=0 )] legends_bars_2 += [ax.bar(bar_l_2, legend_list_2, bottom=totals_2, label='Post Score', alpha=0.9, color=list_color_hatch_marker[i][0], hatch=list_color_hatch_marker[i][1], width=bar_width, edgecolor = "none",#'black' linewidth=0 )] totals_1 = [i+j for i,j in zip(legend_list_1, totals_1)] totals_2 = [i+j for i,j in zip(legend_list_2, totals_2)] height_len = 1.02 def autolabel(rects, label): """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 100 * height_len, label, ha='center', va='bottom') autolabel(legends_bars[-1], 'C') autolabel(legends_bars_2[-1], 'P') plt.xticks(tick_pos, benchmarks) ax.set_ylabel("Percentage") ax.set_xlabel("") # ax.legend(legends_bars, legends_names + ['W','H'], fontsize='medium', mode="expand", ncol=3, bbox_to_anchor=(0., 1.02, 1., .102), loc=3, borderaxespad=0.) from matplotlib.patches import Rectangle extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) ax.legend(legends_bars + [extra, extra], legends_names + ['C: Cold Run','P: Peak'], fontsize='medium', mode="expand", ncol=3, bbox_to_anchor=(0., 1.02, 1., .102), loc=3, borderaxespad=0.) # Let the borders of the graphic plt.xlim([-.5, num_benchmarks + bar_width]) # print([min(tick_pos) - bar_width + 1, max(tick_pos)+ bar_width + 1]) plt.ylim(-10, 110) # rotate axis labels plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') # shot plot filename = filename_prefix+"profile" benchmarks_images[filename_prefix + ' Breakdown passes'] = filename f.savefig(chart_dir + filename + '.png', bbox_inches='tight') f.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight') plt.close(f) # bench_profile_data # core_execution_time # data_Transfer_time # dependence_time # bound_check_time # translation_time # compilation_time # opencl_translation_time # unbox_time profile_files = ["profile1", "profile2"]#, "profileautodevice", "cpu1profile"] def _read_profile_results(): legends_names = ["Guards Optimization", "Unboxing", "Dependence Analysis", "Bounds Check Optimization", "Compilation", "Data Transfer", "Kernel Execution"] benchmarks_profiles = {} benchmarks_names = [] benchmarks_total_time = [] results_list = os.listdir(machine_results_dir) profile_data = {} for f in sorted(results_list): if f == 'machine.json' or not f.endswith('.json'): continue result_tag = f.replace('.json','').split('-') _type = "hpc-rodinia" _run = result_tag[-1] # run # if 'profile' in _run: # if _run in profile_files: with open(machine_results_dir + '/' + f) as benchmark_file: profile_data[_run] = json.load(benchmark_file) benchmarks_profiles[profile_files[0]] = [] benchmarks_profiles[profile_files[1]] = [] # benchmarks_profiles[profile_files[3]] = {} _profile1 = profile_data[profile_files[0]] _profile2 = profile_data[profile_files[1]] # _profile_autodevice = profile_data[profile_files[2]] for _single_bench in sorted(_profile1['profiling']): _sb = str(_single_bench.replace( _type + '.', '')) if _sb in blacklist_bench: continue _largest_parm = benchmarks_list[_type][1][_sb][-2] _runs = [] # Data_Transfer = 0 # for i in range(1,9): # _profile_cpu1 = profile_data[profile_files[3] + ('%d' % i)] # bench_profile_data = _profile_cpu1['profiling'][_single_bench][_largest_parm] # Data_Transfer = abs(int(bench_profile_data[ "data_Transfer_time" ]) - Data_Transfer) # _runs += [float(Data_Transfer)/1000] # # benchmarks_profiles[profile_files[3]][_sb + '.' + _largest_parm] = _runs # print("benchmark, kernels, Kernel Execs, Loop count, CPU, GPU") for _single_bench in sorted(_profile1['profiling']): _sb = str(_single_bench.replace( _type + '.', '')) if _sb in blacklist_bench: continue _largest_parm = benchmarks_list[_type][1][_sb][-2] bench_profile_data = _profile1['profiling'][_single_bench][_largest_parm] Speculation_Elimination = int(bench_profile_data[ "translation_time" ]) Unboxing = int(bench_profile_data[ "unbox_time" ]) Dependence_Analysis = int(bench_profile_data[ "dependence_time" ]) Bound_Check = int(bench_profile_data[ "bound_check_time" ]) Compilation = int(bench_profile_data[ "code_generation_time" ]) + int(bench_profile_data[ "compilation_time" ]) Data_Transfer = int(bench_profile_data[ "data_transfer_time" ]) Kernel_Execution = int(bench_profile_data[ "core_execution_time" ]) bench_profile_list = [Speculation_Elimination] bench_profile_list += [Unboxing] bench_profile_list += [Dependence_Analysis] bench_profile_list += [Bound_Check] bench_profile_list += [Compilation] bench_profile_list += [Data_Transfer] bench_profile_list += [Kernel_Execution] total_time = sum(bench_profile_list) total = [total_time for i in range(len(bench_profile_list))] bench_profile_list = [float(i) / j * 100 for i,j in zip(bench_profile_list, total)] if (100 - sum(bench_profile_list)) > 1: print("%s: %.4f" % (_sb, sum(bench_profile_list))) benchmarks_profiles[profile_files[0]] += [bench_profile_list] benchmarks_names += [_sb] benchmarks_total_time += [total_time] counts = [_sb] counts += [int(bench_profile_data["total_generated_kernels" ])] counts += [int(bench_profile_data["total_kernels_executions"])] loopcount = int(bench_profile_data["total_parallel_loops" ]) power_of_10 = int(math.log(loopcount, 10)) strloopcount = "%.1f x 10%d" % (float(loopcount) / (10**power_of_10), power_of_10) counts += [strloopcount] bench_profile_data = _profile2['profiling'][_single_bench][_largest_parm] # Speculation_Elimination -= int(bench_profile_data[ "translation_time" ]) Speculation_Elimination = 0 Unboxing -= int(bench_profile_data[ "unbox_time" ]) # Dependence_Analysis -= int(bench_profile_data[ "dependence_time" ]) Dependence_Analysis = 0 Bound_Check -= int(bench_profile_data[ "bound_check_time" ]) # Compilation -= int(bench_profile_data[ "opencl_translation_time" ]) + int(bench_profile_data[ "compilation_time" ]) Compilation = 0 Data_Transfer -= int(bench_profile_data[ "data_transfer_time" ]) Kernel_Execution -= int(bench_profile_data[ "core_execution_time" ]) bench_profile_list = [abs( Speculation_Elimination ) ] bench_profile_list += [abs( Unboxing ) ] bench_profile_list += [abs( Dependence_Analysis ) ] bench_profile_list += [abs( Bound_Check ) ] bench_profile_list += [abs( Compilation ) ] bench_profile_list += [abs( Data_Transfer ) ] bench_profile_list += [abs( Kernel_Execution ) ] total_time = sum(bench_profile_list) total = [total_time for i in range(len(bench_profile_list))] bench_profile_list = [float(i) / j * 100 for i,j in zip(bench_profile_list, total)] if (100 - sum(bench_profile_list)) > 1: print("%s: %.4f" % (_sb, sum(bench_profile_list))) benchmarks_profiles[profile_files[1]] += [bench_profile_list] # bench_profile_data = _profile_autodevice['profiling'][_single_bench][_largest_parm] # devices = bench_profile_data["final_execution_device" ] # expr_count = r"(OpenCL (?P<DEVICE>[a-zA-Z0-9\.\-\_]+): (?P<NAME>(.*?)):(?P<COUNT>[0-9]+))+" # m = re.findall(expr_count, devices) # # counts += [0,0] # for d in m: # if "CPU" in d[1]: # counts[-2] = int(d[4]) # if "GPU" in d[1]: # counts[-1] = int(d[4]) # # print("%s, %d, %d, %s, %d, %d" % tuple(counts)) return legends_names, benchmarks_names, benchmarks_total_time, benchmarks_profiles def add_figures_to_json_file(filename='figures.json'): figures_info = {} is_exists = False if os.path.isfile(chart_dir + filename): with open(chart_dir + filename, 'r') as json_figures: figures_info = json.load(json_figures) is_exists = True if is_exists: print('Updating %s with new figures' % filename) else: print('Creating %s with new figures' % filename) figures_info.update(benchmarks_images) dump = json.dumps(figures_info, sort_keys = True, indent = 4) with open(chart_dir + filename, "w") as txtfile: txtfile.write(dump) def generate_ecoop_page_result(filename='figures.json'): figures_info = {} is_exists = False with open(chart_dir + filename, 'r') as json_figures: figures_info = json.load(json_figures) markdown_ecoop(figures_info) is_exists = True if is_exists: print('Page is ready') else: print('JSON file %s does not exists!' % filename) def _asv_chart(args): if importerror: mx.abort("numpy, matplotlib, or functools library is missing.") base = 'CPython' try: idx = args.index("--") args = args[:idx] except ValueError: pass parser = ArgumentParser( prog="mx asv-chart", add_help=False, usage="mx asv-chart <options>", formatter_class=RawTextHelpFormatter) parser.add_argument( "--base", nargs="?", default=None, help="Select base benchmark.") parser.add_argument( "--scales", action="store_true", default=None, help="Generate scales charts all parametized benchmarks.") parser.add_argument( "--bars", action="store_true", default=None, help="Generate bars charts for largest parameters of the benchmarks.") parser.add_argument( "--bars-kdm", action="store_true", default=None, help="Generate bars charts for KDM.") parser.add_argument( "--steps", action="store_true", default=None, help="Generate steps charts all parametized benchmarks.") parser.add_argument( "--cpu-cores-steps", action="store_true", default=None, help="Generate steps charts all parametized benchmarks.") parser.add_argument( "--single-core-cpu", action="store_true", default=None, help="Add single core cpu without data transfer.") parser.add_argument( "--profile", action="store_true", default=None, help="Generate stack bars charts for all benchmarks.") parser.add_argument( "--benchmarks", nargs="?", default=None, help="Select a subset of benchmarks seperated with a comma, e.g --benchmarks bfs,mm,lud") parser.add_argument( "--systems", nargs="?", default=None, help="Select the systems which will be compared with each other seperated with a comma, e.g --systems ZipPy,PyPy3,CPython") parser.add_argument( "--prefix-desc-text", nargs="?", default=None, help="Prefix figure description. e.g. Figure12") # parser.add_argument( # "--json-figure-file", nargs="?", default=None, # help="Name of the json file that stores figure(s) information") parser.add_argument( "--ecoop-result-page", action="store_true", default=None, help="Generate ECOOP result page using the collected information in json file.") parser.add_argument( "--geomean", action="store_true", default=None, help="Generate stack bars charts for all benchmarks.") parser.add_argument( "-h", "--help", action="store_true", default=None, help="Show usage information.") args = parser.parse_args(args) if args.base: base = args.base if not exists(asv_env + '/graphs'): os.mkdir(asv_env + '/graphs') if not exists(chart_dir): os.mkdir(chart_dir) if args.ecoop_result_page: generate_ecoop_page_result() return filename_prefix = '' if args.prefix_desc_text: filename_prefix = args.prefix_desc_text if args.profile: legends_names, benchmarks, total_times, profile_data = _read_profile_results() plot_stack_bars(legends_names, benchmarks, total_times, profile_data, filename_prefix=filename_prefix) add_figures_to_json_file() return systems_list = None if args.systems: systems_list = args.systems.split(',') selected_benchmarks_list = None if args.benchmarks: selected_benchmarks_list = args.benchmarks.split(',') single_benchmark = None if args.geomean: single_benchmark = 'GeoMean' interpreter_list, color_hatch_marker, benchmarks, all_benchmarks_list = _read_results(systems_list, selected_benchmarks_list) if base not in interpreter_list: mx.abort("Base interpreter {0} has no benchmark results.".format(base)) if args.single_core_cpu: new_single_core_str = 'MG-CPU1-NoDT' legends_names, benchmarks_names, total_times, profile_data = _read_profile_results() subtract_data_transfer(profile_data[profile_files[3]], benchmarks, new_single_core_str) interpreter_list += [new_single_core_str] benchmarks_copy = copy.deepcopy(benchmarks) benchmarks_geomean = do_geomean(benchmarks_copy) dump = json.dumps(benchmarks_geomean, sort_keys = True, indent = 4) with open("benchmarks-geomean.json", "w") as txtfile: txtfile.write(dump) do_speedups(benchmarks_copy, base) dump = json.dumps(benchmarks_copy, sort_keys = True, indent = 4) with open("benchmarks-speedups-ci.json", "w") as txtfile: txtfile.write(dump) # markdown_each(benchmarks, base, benchmarks_stats_each) process_plot_bars = False if args.bars or args.bars_kdm: process_plot_bars = True process_plot_bars_kdm = True if args.bars_kdm else False if process_plot_bars: # we might need to always run this sl = systems_list if systems_list else interpreter_list process_plot(benchmarks_copy, all_benchmarks_list, sl, color_hatch_marker, base, process_plot_bars_kdm, filename_prefix=filename_prefix) if args.scales: plot_scales(benchmarks_copy, all_benchmarks_list, base, filename_prefix=filename_prefix) if args.steps: plot_steps(benchmarks_copy, all_benchmarks_list, base, interpreter_list_steps_ordered, single_benchmark=single_benchmark, filename_prefix=filename_prefix) if args.cpu_cores_steps: plot_steps(benchmarks_copy, all_benchmarks_list, base, interpreter_list_cpu_cores_steps_ordered, 'cores_steps', single_benchmark=single_benchmark, filename_prefix=filename_prefix) add_figures_to_json_file() markdown_readme(base, signed_date, interpreters_versions, benchmarks_images, benchmarks_stats_each, benchmarks_stats_types, benchmarks_stats_overall) mx.update_commands(mx.suite('zippy'), { 'asv-chart' : [_asv_chart, 'Generate chart for benchmarked results.'], }) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test22.py def t(x): b = x for j in range(len(a)): for i in range(len(b)): c[j] = b[i] + a[j]*2 a = [1, 2, 3] d = [4, 5, 6] c = [0, 0, 0] t(d) print(c) a = [10, 20, 30] d = [4, 5, 6] c = [0, 0, 0] t(d) print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test3.py from functools import reduce print(reduce(lambda a, b: a + b, [ i+1 for i in range(100)])) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test37.py import math Nparticles=100 rand_c = [2**33, 16346, 18299, 26845, 3318, 11618, 7451, 23885, 8106, 5612, -25751, -6603, 16672, 9990, 995, 22866, 10193, 7526, 10168, 11896, 25713, 5155, 12320, 13293, 15219, 29599, 5390, 3028, 366, 21923, 5613, 14867, 21406, 19266, 3220, 30169, 27043, 11558, 18747, 13467, 18691, 5918, 1601, 12722, 5706, 11882, 3981, 30949, 25200, 14199, 19720, 29994, 4180, 14997, 27215, 19117, 2185, 1375, 14566, 9724, 2522, 3018, 4821, 15780, 3884, 768, 24396, 1290, 29407, 12240, 29350, 10227, 23336, 8608, 10538, 15528, 8221, 20873, 20647, 22108, 21197, 32664, 11720, 1286, 31999, 10873, 23524, 11580, 31948, 24130, 470, 24387, 27500, 28827, 1403, 21907, 16863, 23527, 27110, 22557] rand_c[0] = 30020; seed=[rand_c[i] for i in range(Nparticles)] arrayX=[64.0 for i in range(Nparticles)] arrayY=[64.0 for i in range(Nparticles)] PI = 3.1415926535897932 M = 32767 # value for Linear Congruential Generator (LCG) A = 1103515245 # value for LCG C = 12345 # value for LCG # emulate cpp int overflow max_int32 = 2**16 sub_max_int32 = 2**15 def cppNum(num): return (num + sub_max_int32) % max_int32 - sub_max_int32 def cppMod(num, x): return num % x if num > 0 else -1 * ((-1 * num) % x) # Generates a uniformly distributed random number using the provided seed and GCC's settings for the Linear Congruential Generator (LCG) def randu(seed, index): num = cppNum(A * seed[index] + C) seed[index] = cppMod(num, M) # seed[index] = num % M; return math.fabs(seed[index] / (float(M))); # Generates a normally distributed random number using the Box-Muller transformation def randn(seed, index): u = randu(seed, index); v = randu(seed, index); cosine = math.cos(2 * PI * v); rt = -2 * math.log(u); return math.sqrt(rt) * cosine; def t(): for x in range(Nparticles): arrayX[x] += 1 + 5 * randn(seed, x); arrayY[x] += -2 + 2 * randn(seed, x); t() t() def print1D(x,c): limit = 128 s = "[" for i in range(c): if i % limit == limit-1: s += "\n" s += "%.8f, " % x[i] print(s+ "]") print1D(arrayX, Nparticles) print1D(arrayY, Nparticles) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test15.py import math a = [30020, 16346, 18299, 26845, 3318, 11618, 7451, 23885, 8106, 5612, -25751, -6603, 16672, 9990, 995, 22866, 10193] c = [ 0. for i in range(len(a))] PI = 3.1415926535897932 M = 32767 # value for Linear Congruential Generator (LCG) A = 1103515245 # value for LCG C = 12345 # value for LCG def f(num): return (num + 2**31) % 2**32 - 2**31 def p(num, x): return num % x if num > 0 else -1 * ((-1 * num) % x) def n(y, j): num = f(A * y[j] + C) y[j] = p(num, M) # seed[index] = num % M; return math.fabs(y[j] / (float(M))); def m(y, j): u = n(y, j); v = n(y, j); cosine = math.cos(2 * PI * v); rt = -2 * math.log(u); return math.sqrt(rt) * cosine; def w(x): return m(a, x) def t(): for i in range(len(a)): c[i] += 1 + 5 * w(i) t() # a[0] = 5. # t() limit = 64 s = "[" for i in range(len(c)): if i % limit == limit-1: s += "\n" s += "%.5f, " % c[i] print(s+ "]") <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test2.py a = [2 * n for n in range(50)] c = [0 for i in range(50)] def t(): for i in range(len(a)): c[i] = a[i]*2 t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test20.py b = [1, 2, 3] c = [0, 0, 0] def w(a, i): a[i] = a[i] + i*2 return a[i]*2 def t(): for i in range(len(b)): c[i] = w(b,0) t() b[0] = 5 t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test10.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] b = [4, 5, 6] c = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def callme(): for i in range(len(a)): for j in range(a[i][0]-1, a[i][2]): c[i][j] = a[i][j] * 2 callme() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test14.py n=5 def foo(x, y): return x*2 - y + n def bar(x, y): return x * y + n def test(func, x, y): print(list(map(func, x, y))) a = [i for i in range(10)] b = [i for i in range(10)] c = [i*2. for i in range(20)] d = [i*3. for i in range(20)] test(foo, a, b) test(foo, a, b) test(bar, a, b) test(bar, c, d) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test10.py a = [1, 2, 3] c = [0, 0, 0] def w(x): if x > 2: return a[x]*2 y = a[x]*3 if x > 1: return y def t(): for i in range(len(a)): c[i] = w(i) t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test1.py n=5 print(map(lambda x:x*2 + n, [i for i in range(10)])) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test31.py def t(): for j in range(len(a)): for i in range(len(b)): c[j] = b[i] + a[j]*2 a = [1., 2., 3.] b = [4., 5., 6.] c = [0., 0., 0.] t() print(c) d = [10., 20., 30.] for i in range(len(a)): a[i] = d[i] t() print(c) <file_sep>/mx.zippy/mx_mg_junit.py from os.path import join, sep import mx _suite = mx.suite('zippy') core_junit_test_classes_opencl = ['ForTests', 'DDTests', 'FunCallTests', 'ReductionTests'] all_junit_test_classes_opencl = core_junit_test_classes_opencl core_junit_test_classes_truffle = ['TruffleDDTests','TruffleForTests','TruffleFunCallTests'] all_junit_test_classes_truffle = core_junit_test_classes_truffle def _mg_opencl_test_package(): return 'edu.uci.megaguards.test.parallel' def _mg_truffle_test_package(): return 'edu.uci.megaguards.test.truffle' def _mg_opencl_test_subpackage(name): return '.'.join((_mg_opencl_test_package(), name)) def _mg_truffle_test_subpackage(name): return '.'.join((_mg_truffle_test_package(), name)) def _mg_opencl_core_generated_unit_tests(): return ','.join(map(_mg_opencl_test_subpackage, core_junit_test_classes_opencl)) def _mg_truffle_core_generated_unit_tests(): return ','.join(map(_mg_truffle_test_subpackage, core_junit_test_classes_truffle)) def _mg_core_unit_tests(): return ','.join([_mg_opencl_core_generated_unit_tests(), _mg_truffle_core_generated_unit_tests()]) def junit_mg_core(args): return mx.command_function('junit')(['--tests', _mg_core_unit_tests()] + args) def _mg_all_generated_unit_tests(): return ','.join(map(_mg_opencl_test_subpackage, all_junit_test_classes_opencl)) + \ ',' + ','.join(map(_mg_truffle_test_subpackage, all_junit_test_classes_truffle)) def _mg_all_unit_tests(): return ','.join([_mg_all_generated_unit_tests()]) def junit_mg_all(args): return mx.command_function('junit')(['--tests', _mg_all_unit_tests()] + args) mx.update_commands(_suite, { 'junit-mg-core' : [junit_mg_core, ['options']], 'junit-mg' : [junit_mg_all, ['options']], }) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test13.py n=5 print(list(map(lambda x, y:x*y*2 + n, [i for i in range(10)], [i*1. for i in range(10)]))) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test12.py a = [1, 2, 3] c = [0, 0, 0] def w(x): return a[x]*2 if x == 0 else a[x]*3 def t(): for i in range(len(a)): c[i] = w(i) t() print(c) <file_sep>/mx.zippy/mx_mg_pages.py # Copyright (c) 2018, Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from mx_mg_conf import * strapdown_md_to_html = [ ''' <!DOCTYPE html> <html> <title>Results</title> <xmp theme="journal" style="display:none;"> ''', ''' </xmp> <script src="http://strapdownjs.com/v/0.2/strapdown.js"></script> </html> ''' ] def markdown_ecoop(benchmarks_images, filename='ECOOP18'): markdown_content = '' dump = '# Benchmark result for machine (' + machine_name + '):\n\n' markdown_content += dump dump = '\n# Graphs:\n' markdown_content += dump for title in sorted(benchmarks_images): dump = '\n## ' + title + '\n\n' image_path = benchmarks_images[title] dump += '\n' + '[![image](' + image_path + '.png' + ')](' + image_path + '.pdf' + ')\n\n' markdown_content += dump dump = '# Done' markdown_content += dump with open(chart_dir + filename + '.md', "w") as readme: readme.write(markdown_content) with open(chart_dir + filename + '.html', "w") as readme: readme.write(strapdown_md_to_html[0]) readme.write(markdown_content) readme.write(strapdown_md_to_html[1]) print('Page is ready at %s.html and .md' % (chart_dir + filename)) def markdown_readme(base, signed_date, interpreters_versions, benchmarks_images, benchmarks_stats_each, benchmarks_stats_types, benchmarks_stats_overall): markdown_content = '' dump = '# Benchmark result for machine (' + machine_name + '):\n\n' markdown_content += dump dump = '\nResults are as of ' + signed_date + '\n' markdown_content += dump dump = '\nList of interpreters:\n\n' markdown_content += dump for _interp in interpreters_versions: dump = '* ' + _interp + ': `' + interpreters_versions[_interp] + '`\n' markdown_content += dump dump = '\n\n> Normalized to: ' + base + '\n\n' markdown_content += dump dump = '\n# Graphs:\n' markdown_content += dump for title in sorted(benchmarks_images): dump = '\n## ' + title + '\n\n' image_path = benchmarks_images[title] dump += '\n' + '[![image](' + image_path + '.png' + ')](' + image_path + '.pdf' + ')\n\n' markdown_content += dump dump = '\n# Statistics:\n' markdown_content += dump dump = '\n## Overall performance:\n' markdown_content += dump for _interp in benchmarks_stats_overall: for _timing in benchmarks_stats_overall[_interp]: dump = _interp + ': Overall `' + _timing + '` performance :: ' dump += 'Geometeric mean: `' + ("%.3f" % geomean(benchmarks_stats_overall[_interp][_timing]) ) + 'x`, ' dump += 'Average: `' + ("%.3f" % np.average(benchmarks_stats_overall[_interp][_timing]) ) + 'x`, ' dump += 'Maximum: `' + ("%.3f" % max(benchmarks_stats_overall[_interp][_timing]) ) + 'x`\n\n' markdown_content += dump dump = '\n## Benchmarks performance:\n' markdown_content += dump for _type in benchmarks_stats_types: dump = '\n### `' + _type + '` performance:\n' markdown_content += dump for _timing in benchmarks_stats_types[_type]: dump = '\n##### `' + _timing + '` measurement:\n' markdown_content += dump for _measurement in benchmarks_stats_types[_type][_timing]: dump = _measurement markdown_content += dump dump = '\n## Each Benchmark performance:\n' markdown_content += dump for _type in benchmarks_stats_each: dump = '\n### `' + _type + '` performance:\n' markdown_content += dump for _timing in benchmarks_stats_each[_type]: dump = '\n##### `' + _timing + '` measurement:\n' markdown_content += dump for _bench in benchmarks_stats_each[_type][_timing]: _bench_txt = '`' + _bench + '` ' if isinstance(benchmarks_stats_each[_type][_timing][_bench], dict): for _param in benchmarks_stats_each[_type][_timing][_bench]: dump = _bench_txt + '`' + _param + '`: ' + benchmarks_stats_each[_type][_timing][_bench][_param] + '\n\n' markdown_content += dump else: dump = _bench_txt + ': ' + benchmarks_stats_each[_type][_timing][_bench] + '\n\n' markdown_content += dump dump = '# Done' markdown_content += dump with open(chart_dir + 'README.md', "w") as readme: readme.write(markdown_content) with open(chart_dir + 'README.html', "w") as readme: readme.write(strapdown_md_to_html[0]) readme.write(markdown_content) readme.write(strapdown_md_to_html[1]) def markdown_overall_speedups(_type, _timing, r_benchmarks, benchmarks_stats_types, benchmarks_stats_overall): txt_geomean = ' Geometeric mean :: ' txt_avg = ' Average :: ' txt_max = ' Maximum :: ' for _interp in r_benchmarks: txt_geomean += _interp + ': `' + ("%.3f" % geomean(r_benchmarks[_interp]) ) + 'x`, ' txt_avg += _interp + ': `' + ("%.3f" % np.average(r_benchmarks[_interp])) + 'x`, ' txt_max += _interp + ': `' + ("%.3f" % max(r_benchmarks[_interp]) ) + 'x`, ' if _interp not in benchmarks_stats_overall: benchmarks_stats_overall[_interp] = {} if _timing not in benchmarks_stats_overall[_interp]: if _timing == 'Steps': continue benchmarks_stats_overall[_interp][_timing] = [] benchmarks_stats_overall[_interp][_timing] += r_benchmarks[_interp] txt_geomean += '\n\n' txt_avg += '\n\n' txt_max += '\n\n' if _type not in benchmarks_stats_types: benchmarks_stats_types[_type] = {} benchmarks_stats_types[_type][_timing] = [txt_geomean, txt_avg, txt_max] def markdown_each(benchmarks, base, benchmarks_stats_each): for _type in benchmarks: if _type not in benchmarks_stats_each: benchmarks_stats_each[_type] = {} for _timing in benchmarks[_type]: if _timing == 'Steps': continue if _timing not in benchmarks_stats_each[_type]: benchmarks_stats_each[_type][_timing] = {} for _interp in benchmarks[_type][_timing]: for _bench in benchmarks[_type][_timing][_interp]: if _bench not in benchmarks_stats_each[_type][_timing]: benchmarks_stats_each[_type][_timing][_bench] = {} for _param in benchmarks[_type][_timing][_interp][_bench]: if _param not in benchmarks_stats_each[_type][_timing][_bench]: benchmarks_stats_each[_type][_timing][_bench][_param] = base + ': `1.00x`, ' s = benchmarks[_type][_timing][_interp][_bench][_param] benchmarks_stats_each[_type][_timing][_bench][_param] += _interp + ': `' + ("%.3f" % s) + '`, ' <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/check_megaguards.py # Copyright (c) 2018, Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys, time, random # N = int(sys.argv[1]) N = 2 ** 6 def mm_MG(X,Y,Z): # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): Z[i][j] += X[i][k] * Y[k][j] return Z X = [[random.random() for i in range(N)] for j in range(N)] Y = [[random.random() for i in range(N)] for j in range(N)] Z = [[0.0 for i in range(N)] for j in range(N)] print('Running matrix multiplication (%d x %d)..' % (N, N)) start = time.time() mm_MG(X,Y,Z) duration = "Matrix multiplication time: %.5f seconds" % ((time.time() - start)) print('Calculate maximum delta..') delta = 0.0 for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y r = 0 for k in range(len(Y)): r += X[i][k] * Y[k][j] delta = delta if abs(r - Z[i][j]) <= delta else abs(r - Z[i][j]) if delta == 0.0: print("Identical result compare to ZipPy") else: print('maximum delta = %f' % delta) print(duration) # for r in result: # print(r) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test13.py a = [1., 2., 3.] c = [0, 0, 0] def t(): for i in range(len(a)): c[i] = int(a[i]*2) t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test8.py from functools import reduce def t(a, b): """ @MG:reduce-on """ return a + b + 3 print(reduce(t, [ i+1 for i in range(2000)])) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test17.py a = [1.3, 1.6, 2.5] c = [0., 0., 0.] def t(): for i in range(len(a)): c[i] = round(a[i])*2 t() print(c) <file_sep>/zippy/edu.uci.python/src/edu/uci/megaguards/python/unbox/PythonBoxed.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.python.unbox; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.frame.VirtualFrame; import edu.uci.megaguards.analysis.exception.TypeException; import edu.uci.megaguards.object.ArrayInfo; import edu.uci.megaguards.object.DataType; import edu.uci.megaguards.unbox.Boxed; import edu.uci.megaguards.unbox.Unboxer; import edu.uci.python.nodes.PNode; import edu.uci.python.runtime.datatype.PComplex; import edu.uci.python.runtime.sequence.PList; import edu.uci.python.runtime.sequence.PTuple; import edu.uci.python.runtime.sequence.storage.BoolSequenceStorage; import edu.uci.python.runtime.sequence.storage.DoubleSequenceStorage; import edu.uci.python.runtime.sequence.storage.IntSequenceStorage; import edu.uci.python.runtime.sequence.storage.ListSequenceStorage; import edu.uci.python.runtime.sequence.storage.LongSequenceStorage; import edu.uci.python.runtime.sequence.storage.SequenceStorage; import edu.uci.python.runtime.sequence.storage.TupleSequenceStorage; public abstract class PythonBoxed extends Boxed<PNode> { public static final PythonBoxed PyBOX = new GenericBoxed(null); public PythonBoxed(PNode valueNode, DataType type) { super(valueNode, type); } public static class GenericBoxed extends PythonBoxed { public GenericBoxed(PNode valueNode) { super(valueNode, DataType.None); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { return valueNode.execute(frame); } } public static class IntBoxed extends PythonBoxed { public IntBoxed(PNode valueNode) { super(valueNode, DataType.Int); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); final int value; if (newVal instanceof Integer) { return newVal; } else if (newVal instanceof Long) { value = ((Long) newVal).intValue(); if (value == (long) newVal) { return value; } } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class IntLengthBoxed extends PythonBoxed { public IntLengthBoxed(PNode valueNode) { super(valueNode, DataType.Int); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object value = valueNode.execute(frame); if (value instanceof Integer) { return value; } else if (value instanceof PList) // stop variable in For statement return ((PList) value).len(); else if (value instanceof PTuple) // stop variable in For statement return ((PTuple) value).len(); throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class LongBoxed extends PythonBoxed { public LongBoxed(PNode valueNode) { super(valueNode, DataType.Long); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); if (newVal instanceof Long) { return newVal; } else if (newVal instanceof Integer) { return (long) newVal; } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class DoubleBoxed extends PythonBoxed { public DoubleBoxed(PNode valueNode) { super(valueNode, DataType.Double); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); if (newVal instanceof Double) { return newVal; } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class ComplexRealBoxed extends PythonBoxed { public ComplexRealBoxed(PNode valueNode) { super(valueNode, DataType.Double); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); if (newVal instanceof PComplex) { return ((PComplex) newVal).getReal(); } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class ComplexImagBoxed extends PythonBoxed { public ComplexImagBoxed(PNode valueNode) { super(valueNode, DataType.Double); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); if (newVal instanceof PComplex) { return ((PComplex) newVal).getImag(); } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public static class BooleanBoxed extends PythonBoxed { public BooleanBoxed(PNode valueNode) { super(valueNode, DataType.Bool); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { Object newVal = valueNode.execute(frame); if (newVal instanceof Boolean) { return newVal; } throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } } public abstract static class ArrayBoxed extends PythonBoxed { protected final Unboxer boxed; public ArrayBoxed(PNode valueNode, Unboxer boxed, DataType type) { super(valueNode, type); this.boxed = boxed; } @Override public Unboxer getUnboxer() { return boxed; } public static class IntArrayBoxed extends ArrayBoxed { public IntArrayBoxed(PNode valueNode, Unboxer boxed) { super(valueNode, boxed, DataType.IntArray); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof IntSequenceStorage) { final IntSequenceStorage IntStorage = ((IntSequenceStorage) storage.getStorage()); final Object values = IntStorage.getInternalIntArray(); boxed.getInfo().setSize(0, IntStorage.length()); boxed.setValue(values); boxed.setChanged(storage.getStorage().isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } public static class LongArrayBoxed extends ArrayBoxed { public LongArrayBoxed(PNode valueNode, Unboxer boxed) { super(valueNode, boxed, DataType.LongArray); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof LongSequenceStorage) { final LongSequenceStorage longStorage = ((LongSequenceStorage) storage.getStorage()); final Object values = longStorage.getInternalLongArray(); boxed.getInfo().setSize(0, longStorage.length()); boxed.setValue(values); boxed.setChanged(storage.getStorage().isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } public static class DoubleArrayBoxed extends ArrayBoxed { public DoubleArrayBoxed(PNode valueNode, Unboxer boxed) { super(valueNode, boxed, DataType.DoubleArray); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof DoubleSequenceStorage) { final DoubleSequenceStorage DoubleStorage = ((DoubleSequenceStorage) storage.getStorage()); final Object values = DoubleStorage.getInternalDoubleArray(); boxed.getInfo().setSize(0, DoubleStorage.length()); boxed.setValue(values); boxed.setChanged(storage.getStorage().isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } public abstract static class BoolArrayBoxed extends ArrayBoxed { public BoolArrayBoxed(PNode valueNode, Unboxer boxed) { super(valueNode, boxed, DataType.BoolArray); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof BoolSequenceStorage) { final BoolSequenceStorage BoolStorage = ((BoolSequenceStorage) storage.getStorage()); final Object values = BoolStorage.getInternalBoolArray(); boxed.getInfo().setSize(0, BoolStorage.length()); boxed.setValue(values); boxed.setChanged(storage.getStorage().isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } public abstract static class ArrayNDBoxed extends ArrayBoxed { public ArrayNDBoxed(PNode valueNode, Unboxer boxed) { super(valueNode, boxed, boxed.getKind()); } public static class ListSequence extends ArrayNDBoxed { public ListSequence(PNode valueNode, Unboxer boxed) { super(valueNode, boxed); } protected static void updateArrayInfo(ListSequenceStorage storage, ArrayInfo info) { if (info.getType() != storage.getKind()) throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); final int dims = info.getDim(); info.resetDim(); final PList[] lists = storage.getInternalListArray(); info.addSize(storage.length()); PythonUnboxerUtil.traverseLists(lists[0], info); if (dims != info.getDim()) throw TypeException.INSTANCE.message("Guard Failed! (Dimention miss-match)"); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof ListSequenceStorage) { final int hashCode = val.hashCode(); final ListSequenceStorage listStorage = ((ListSequenceStorage) storage.getStorage()); updateArrayInfo(listStorage, boxed.getInfo()); boxed.setOriginHashCode(hashCode); boxed.setValue(listStorage); boxed.setChanged(storage.getStorage().isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } @TruffleBoundary private static ArrayInfo traverseUpdateTuples(PTuple tuple, ArrayInfo info) { info.addSize(tuple.len()); final Object first = tuple.getArray()[0]; if (first instanceof PTuple) PythonUnboxerUtil.traverseTuples((PTuple) first, info); else if (first instanceof PList) { final SequenceStorage storage = ((PList) first).getStorage(); info.addSize(storage.length()); if (info.getType() != storage.getClass()) throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else { if (info.getType() != first.getClass()) throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } return info; } public static class Tuple extends ArrayNDBoxed { public Tuple(PNode valueNode, Unboxer boxed) { super(valueNode, boxed); } protected static void updateArrayInfo(PTuple tuple, ArrayInfo info) { final int dims = info.getDim(); info.resetDim(); traverseUpdateTuples(tuple, info); if (dims != info.getDim()) throw TypeException.INSTANCE.message("Guard Failed! (Dimention miss-match)"); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PTuple) { final int hashCode = val.hashCode(); final PTuple tuple = (PTuple) val; updateArrayInfo(tuple, boxed.getInfo()); boxed.setOriginHashCode(hashCode); boxed.setValue(tuple); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } public static class TupleSequence extends ArrayNDBoxed { public TupleSequence(PNode valueNode, Unboxer boxed) { super(valueNode, boxed); } @TruffleBoundary private static void updateArrayInfo(TupleSequenceStorage storage, ArrayInfo info) { final int dims = info.getDim(); info.resetDim(); final PTuple[] tuples = storage.getInternalPTupleArray(); info.addSize(storage.length()); traverseUpdateTuples(tuples[0], info); if (dims != info.getDim()) throw TypeException.INSTANCE.message("Guard Failed! (Dimention miss-match)"); } @Override public Object getUnboxed(VirtualFrame frame, Object v) { final Object val = valueNode.execute(frame); if (val instanceof PList) { final PList storage = (PList) val; if (storage.getStorage() instanceof TupleSequenceStorage) { final int hashCode = val.hashCode(); final TupleSequenceStorage listStorage = ((TupleSequenceStorage) storage.getStorage()); updateArrayInfo(listStorage, boxed.getInfo()); boxed.setOriginHashCode(hashCode); boxed.setValue(listStorage); boxed.setChanged(listStorage.isChangedAndReset()); Boxed.addBoxed(boxed); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); } else throw TypeException.INSTANCE.message("Guard Failed! (Type miss-match)"); return boxed; } } } } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test8.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(3): for j in range(3): a[j][i] = a[j][i]*2 t() print(a) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test43.py a = [ i for i in range(100)] b = [ i*2 for i in range(100)] c = [ 0 for i in range(100)] def t(): for j in range(1,len(a)-1, 2): for i in range(len(b)): c[j] = b[i] + a[j]*2 if j > 80: break t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test3.py a = [1, 2, 3] b = [4, 5, 6] c = [0, 0, 0] def t(): for j in range(len(a)): for i in range(len(b)): c[j] = b[i] + a[j]*2 t() print(c) <file_sep>/zippy/edu.uci.python/src/edu/uci/megaguards/python/fallback/ReduceFallback.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.python.fallback; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import edu.uci.megaguards.MGNodeOptions; import edu.uci.megaguards.MGOptions; import edu.uci.megaguards.analysis.exception.MGException; import edu.uci.megaguards.backend.ExecutionMode; import edu.uci.megaguards.fallback.MGFallbackHandler; import edu.uci.megaguards.log.MGLog; import edu.uci.megaguards.python.analysis.MGPythonPreCheck; import edu.uci.python.nodes.function.FunctionRootNode; import edu.uci.python.runtime.PythonOptions; import edu.uci.python.runtime.function.PFunction; public class ReduceFallback extends MGFallbackHandler<PFunction> { private boolean prechecked; protected boolean precheckedVerdect; public ReduceFallback() { super(); this.prechecked = false; this.precheckedVerdect = true; } @TruffleBoundary private boolean preCheck(PFunction node) { if (!this.prechecked) { try { this.prechecked = true; reason = "Pre-Check"; MGPythonPreCheck check = new MGPythonPreCheck(true); FunctionRootNode functionNodeRoot = (FunctionRootNode) node.getCallTarget().getRootNode(); check.check(functionNodeRoot.getBody()); if (MGNodeOptions.hasOptions(functionNodeRoot.getBody().hashCode())) { MGNodeOptions.addOptions(node.hashCode(), MGNodeOptions.getOptions(functionNodeRoot.getBody().hashCode())); } if (MGNodeOptions.hasOptions(node.hashCode())) { if (MGNodeOptions.getOptions(node.hashCode()).isMGOff()) { reason = "Selective Off"; this.precheckedVerdect = false; return false; } } } catch (MGException e) { if (MGOptions.Backend.Debug > 0) MGLog.printException(e, null); this.precheckedVerdect = false; return false; } } return precheckedVerdect; } @Override @TruffleBoundary public boolean check(PFunction node) { if (PythonOptions.MGOff) { return false; } if (MGOptions.Backend.target == ExecutionMode.NormalCPU) { return false; } if (!preCheck(node)) { return false; } if (MGNodeOptions.hasOptions(node.hashCode())) { if (MGNodeOptions.getOptions(node.hashCode()).isMGOff()) { return false; } } if (retryLimit < 0) { return false; } return true; } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test26.py a = [ i for i in range(10000)] b = [ i*2 for i in range(10000)] c = [ 0 for i in range(10000)] def t(): for j in range(len(a)): for i in range(len(b)): c[j] = b[i] + a[j]*2 t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test15.py N=3 def t(): a = [[[ i+1 for i in range(N)] for j in range(N) ] for k in range(N) ] c = [ 0 for i in range(N)] for i in range(N): for j in range(N): c[i] = a[0][0][i]*2 return c c = t() c = t() c = t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test14.py N=3 def t(): a = [[ i+1 for i in range(N)] for j in range(N) ] for i in range(N): for j in range(N): for k in range(N): c[i][j] = a[i][j]*2 c = [[ 0 for i in range(N)] for j in range(N) ] t() c = [[ 0 for i in range(N)] for j in range(N) ] t() c = [[ 0 for i in range(N)] for j in range(N) ] t() print(c[0]) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test1.py a = [1, 2, 3] c = [0, 0, 0] def w(x): return x def t(): for i in range(len(a)): c[i] = w(a[i]*2) t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test28.py N=3 def t(x): a = [[[ i+j+k for i in range(N)] for j in range(N) ] for k in range(N) ] for i in range(3): for j in range(3): for k in range(x): c[i][j][k] += a[i][j][k]*2 c = [[[ 0 for i in range(N)] for j in range(N) ] for k in range(N) ] t(2) print(c) c = [[[ 0 for i in range(N)] for j in range(N) ] for k in range(N) ] t(3) print(c) c = [[[ 0 for i in range(N)] for j in range(N) ] for k in range(N) ] t(2) print(c) <file_sep>/mx.zippy/mx_mg_conf.py import mx import os, platform _suite = mx.suite('zippy') commit_hash = _suite.vc.parent(_suite.dir) asv_env = os.environ.get("ZIPPY_ASV_PATH") if not asv_env: asv_env = _suite.dir asv_dir = asv_env + '/asv/' asv_results_dir = asv_dir + '/results/' machine_name = os.environ.get("MACHINE_NAME") if not machine_name: machine_name = platform.node() _mx_graal = mx.suite("compiler", fatalIfMissing=False) machine_name += '-no-graal' if not _mx_graal else '-graal' envoclcpu = 'CPU_PLATFORM_INDEX' envoclgpu = 'GPU_PLATFORM_INDEX' # testing # machine_name = '' # commit_hash = '' machine_results_dir = asv_results_dir + machine_name chart_dir = asv_env + '/graphs/' + machine_name + '/' yaxis_scale_range_list = [5, 10, 13, 32, 44, 65, 128, 160, 192, 256, 352, 512, 1024, 2048, 4096] yaxis_scale_range = { '5' : [i for i in range(6)], '10' : [i for i in range(11)], '13' : [i for i in range(14)], '32' : [0, 1, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32], '44' : [0, 1, 2, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44], '65' : [0, 1, 8, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65], '128' : [0, 1, 2, 4, 8, 16, 28, 32, 48, 64, 92, 128], '160' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 160], '192' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 192], '256' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 256], '352' : [0, 1, 4, 8, 16, 32, 64, 96, 128, 192, 256, 352], '512' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512], '1024' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024], '2048' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048], '4096' : [0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096], } interpreter_list_cpu_cores_steps_ordered = [ # ['ZipPy' , 'ZipPy' ], ['MG-CPU1' , 'MegaGuards-CPU (1 CU)' ], ['MG-CPU2' , 'MegaGuards-CPU (2 CUs)' ], # ['MG-CPU3' , 'MG-CPU (3 cores)' ], ['MG-CPU4' , 'MegaGuards-CPU (4 CUs)' ], # ['MG-CPU5' , 'MG-CPU (5 cores)' ], ['MG-CPU6' , 'MegaGuards-CPU (6 CUs)' ], # ['MG-CPU7' , 'MG-CPU (7 cores)' ], ['MG-CPU' , 'MegaGuards-CPU (8 CUs)' ], ] interpreter_list_steps_ordered = [ # ['CPython' , 'CPython3' ], # ['PyPy3' , 'PyPy3' ], # ['ZipPy' , 'ZipPy' ], # ['MG-Truffle' , 'MG-Truffle' ], ['MG-CPU' , 'MegaGuards-CPU' ], ['MG-GPU' , 'MegaGuards-GPU' ], ['MG' , 'MegaGuards-Adaptive' ], ['OpenCL-GPU' , 'OpenCL-GPU C/C++'], ['OpenCL-CPU' , 'OpenCL-CPU C/C++'] ] interpreter_list_scales_ordered = [ # ['ZipPy' , 'ZipPy' ], ['MG-CPU' , 'MegaGuards-CPU' ], ['MG-GPU' , 'MegaGuards-GPU' ], ['MG' , 'MegaGuards-Adaptive' ], # ['OpenCL-GPU' , 'OpenCL-GPU C/C++'], # ['OpenCL-CPU' , 'OpenCL-CPU C/C++'] ] interpreter_list_ordered = [ ['CPython' , 'CPython3' ], ['PyPy3' , 'PyPy3' ], ['ZipPy' , 'ZipPy' ], ['MG-CPU' , 'MegaGuards-CPU' ], # ['MG-NoDM' , 'MG-NoDM' ], ['MG-GPU' , 'MegaGuards-GPU' ], ['MG' , 'MegaGuards-Adaptive' ], ['MG-Truffle' , 'MegaGuards-Truffle' ], ['OpenCL-GPU' , 'OpenCL-GPU C/C++'], ['OpenCL-CPU' , 'OpenCL-CPU C/C++'] ] _Set1_colors = ( (0.89411764705882357, 0.10196078431372549, 0.10980392156862745), # red (0.21568627450980393, 0.49411764705882355, 0.72156862745098038), # blue == red (0.30196078431372547, 0.68627450980392157, 0.29019607843137257), # green == gray == orange (0.59607843137254901, 0.30588235294117649, 0.63921568627450975), # purple == blue (1.0, 0.49803921568627452, 0.0 ), # orange == green == gray (1.0, 1.0, 0.2 ), # yellow (0.65098039215686276, 0.33725490196078434, 0.15686274509803921), # brown (0.96862745098039216, 0.50588235294117645, 0.74901960784313726), # pink == orange (0.6, 0.6, 0.6), # gray == green == orange 'k' # black ) _grayscale_colors = [ 'w' , '#3f3f3f', '#515151', '#999999', '#bababa', '#e2e2e2', '#777777', '#cccccc', '#444444', 'k' , '#666666', ] _color_set = _grayscale_colors list_color_hatch_marker = [ ['#999999', '/', '*-'], ['#666666', 'o', 'r-'], ['#515151', 's', '^-'], ['#444444', '*', '*-'], ['#777777', '', 'o-'], ['#cccccc', '', 'X-'], ['#000000' , '', 's-'], ] interpreter_color_hatch_marker = { 'OpenCL-GPU' : [_color_set[0], '', '8-'], 'OpenCL-CPU' : [_color_set[1], '', 'd-'], 'MG-Truffle' : [_color_set[6], '', 'v-'], 'MG-CPU' : [_color_set[5], '', 's-'], 'MG-GPU' : [_color_set[3], '', 'o-'], 'MG' : [_color_set[9], '', 'v-'], 'PyPy3' : [_color_set[7], '', '^-'], 'CPython' : [_color_set[8], '', 'h-'], 'ZipPy' : [_color_set[9], '', '*-'], 'MG-NoDM' : [_color_set[10], '', 'p-'], 'MG-CPU1' : [_color_set[8], '', 'p-'], 'MG-CPU2' : [_color_set[1], 'o', 'd-'], 'MG-CPU3' : [_color_set[3], '/', 'o-'], 'MG-CPU4' : [_color_set[6], '', '*-'], 'MG-CPU5' : [_color_set[9], '', '|-'], 'MG-CPU6' : [_color_set[7], '', 'v-'], 'MG-CPU7' : [_color_set[0], '', 'x-'], } plot_scales_color_hatch_marker = { 'OpenCL-GPU' : [_color_set[8], '', 'p-'], 'OpenCL-CPU' : [_color_set[1], 'o', 'd-'], 'MG-CPU' : [_color_set[2], '.', 's-'], 'MG-GPU' : [_color_set[3], '/', 'o-'], 'MG' : [_color_set[6], '', 'v-'], 'ZipPy' : [_color_set[9], '', '*-'], } plot_steps_color_hatch_marker = { 'OpenCL-GPU' : [_color_set[8], '', 'p-'], 'OpenCL-CPU' : [_color_set[1], 'o', 'd-'], 'MG-CPU' : [_color_set[2], '.', 's-'], 'MG-GPU' : [_color_set[3], '/', 'o-'], 'MG' : [_color_set[6], '', '*-'], 'ZipPy' : [_color_set[9], '', '|-'], 'PyPy3' : [_color_set[7], '', 'v-'], 'CPython' : [_color_set[10], '', 'x-'], 'MG-CPU1' : [_color_set[8], '', 'p-'], 'MG-CPU2' : [_color_set[1], 'o', 'd-'], 'MG-CPU3' : [_color_set[3], '/', 'o-'], 'MG-CPU4' : [_color_set[6], '', '*-'], 'MG-CPU5' : [_color_set[9], '', '|-'], 'MG-CPU6' : [_color_set[7], '', 'v-'], 'MG-CPU7' : [_color_set[10], '', 'x-'], } # ['k' , '' , 's-'], # ['#3f3f3f', '*', 'o-'], # ['#999999', '' , '^-'], # ['#bababa', '/', '*-'], # ['#e2e2e2', '.', 'p-'], # ['#777777', '', 'h-'], # ['#cccccc', '', 'v-'], # ['w', '' , '8-'], # ['#666666', 'o', 'd-'], # ['#515151', 's', '^-'], # ['#444444', '*', '*-'], blacklist_bench_param = { 'nbody' : ['2048'], 'srad' : ['8192'], 'mm' : ['64', '128', '256'] } # blacklist_bench = ['hotspot3D', 'bfs', 'lavaMD', 'euler3d', 'backprop'] blacklist_bench = ['hotspot3D', 'backprop'] <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test30.py a = [ i for i in range(10000)] b = [ i*2 for i in range(10000)] c = [ 0 for i in range(10000)] def t1(): for j in range(1,len(a)-1, 2): for i in range(len(b)): c[j] = b[i] + a[j]*2 t1() # print(c) a = [ i + 0. for i in range(10000)] b = [ i*2 + 0. for i in range(10000)] c = [ 0. for i in range(10000)] def t2(): for j in range(1,len(a)-1, 2): for i in range(len(b)): c[j] = b[i] + a[j]*2 t2() # print(c) a = [[ i for i in range(100)] for j in range(100)] b = [[ i*2 for i in range(100)] for j in range(100)] c = [[ 0 for i in range(100)] for j in range(100)] def t3(): for j in range(1,len(a)-1, 2): for i in range(len(b)): c[j][i] = b[j][i] + a[i][j]*2 t3() # print(c) a = [[ i + 0. for i in range(100)] for j in range(100)] b = [[ i*2 + 0. for i in range(100)] for j in range(100)] c = [[ 0. for i in range(100)] for j in range(100)] def t4(): for j in range(1,len(a[0])-1, 2): for i in range(len(b[0])): c[j][i] = b[j][i] + a[i][j]*2 t4() # print(c) a = [ i + 0. for i in range(1000000)] b = [ i*2 + 0. for i in range(1000000)] c = [ 0. for i in range(1000000)] def t5(): for j in range(1,len(a)-1, 2): for i in range(len(b)): c[j] = b[i] + a[j]*2 t5() # print(c) a = [[ i + 0. for i in range(1000)] for j in range(1000)] b = [[ i*2 + 0. for i in range(1000)] for j in range(1000)] c = [[ 0. for i in range(1000)] for j in range(1000)] def t6(): for j in range(1,len(a[0])-1, 2): for i in range(len(b[0])): c[j][i] = b[j][i] + a[i][j]*2 t6() # print(c) a = [[[ i + 0. for i in range(100)] for j in range(100)] for k in range(100)] b = [[[ i*2 + 0. for i in range(100)] for j in range(100)] for k in range(100)] c = [[[ 0. for i in range(100)] for j in range(100)] for k in range(100)] def t7(): for j in range(1,len(a[0])-1, 2): for i in range(len(b[0])): c[j][i][0] = b[j][i][0] + a[i][j][0]*2 t7() # print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test36.py size = 8 a = [2 * n for n in range(size)] Sum = [0] def t(): for i in range(size): tmp = a[i] Sum[0] += tmp t() print(Sum[0]) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test19.py a = [1., 2., 3.] c = [0., 0., 0.] def n(y, j): y[j] = y[j] * 2 return y[j] def m(y, j): u = n(y, j); v = n(y, j); return u + v; def w(x): return m(a, 0) def t(): for i in range(len(a)): c[i] = w(i) def tt(): for i in range(len(a)): a[0] = a[0] * 2 u = a[0] a[0] = a[0] * 2 v = a[0] c[i] = u + v # tt() t() a[0] = 5. t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test3.py a = [1, 2, 3] c = [0, 0, 0] def w(x): y = -x*2 return y def t(): for i in range(len(a)): x = w(a[i]) c[i] = x t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test11.py from functools import reduce def t(a, b): return a + b print('%.0f' % reduce(t, [ i*.1+1 for i in range(10496000)])) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test34.py size = 8 a = [2 * n for n in range(size * size)] def t(): for i in range(size): for j in range(i, size): Sum = a[i * size + j] for k in range(i): Sum -= a[i * size + k] * a[k * size + j] a[i * size + j] = Sum t() print(a) <file_sep>/zippy/edu.uci.python.test/src/edu/uci/megaguards/test/parallel/ReductionTests.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in script and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of script code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.test.parallel; import static edu.uci.python.test.PythonTests.assertPrints; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assume.assumeTrue; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import edu.uci.megaguards.test.MGTests; @FixMethodOrder(MethodSorters.JVM) public class ReductionTests { private static final String path = MGTests.MGSrcTestPath + File.separator + "reduction" + File.separator; @Test public void map_test1() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test1.py"); assertPrints("[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void map_test2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test2.py"); assertPrints("[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test3() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test3.py"); assertPrints("5050\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test4() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test4.py"); assertPrints("2001000\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test5() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test5.py"); assertPrints("8390656\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test6() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test6.py"); assertPrints("40320\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test7() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test7.py"); assertPrints("2006997\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test8() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test8.py"); assertPrints("2006997\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test9() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test9.py"); assertPrints("5347\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test10() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test10.py"); assertPrints("5355\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void reduce_test11() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test11.py"); assertPrints("5508310771200\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void map_test12() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test12.py"); assertPrints("[5, 7, 13, 23, 37, 55, 77, 103, 133, 167]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void map_test13() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test13.py"); assertPrints("[5.0, 7.0, 13.0, 23.0, 37.0, 55.0, 77.0, 103.0, 133.0, 167.0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void map_test14() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test14.py"); assertPrints("[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n" + "[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n" + "[5, 6, 9, 14, 21, 30, 41, 54, 69, 86]\n" + "[5.0, 11.0, 29.0, 59.0, 101.0, 155.0, 221.0, 299.0, 389.0, 491.0, 605.0, 731.0, 869.0, 1019.0, 1181.0, 1355.0, 1541.0, 1739.0, 1949.0, 2171.0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 4); MGTests.releaseMGParallelOptions(); } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test23.py def t(): for j in range(len(a)): for i in range(len(b)): c[j] = b[i] + a[j]*2 a = [1, 2, 3] b = [4, 5, 6] c = [0, 0, 0] t() print(c) a[0] = 10 a[1] = 20 a[2] = 30 b = [4, 5, 6] c = [0, 0, 0] t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test22.py size = 8 a = [2 * n for n in range(size)] Sums = [0] def t(): for k in range(3): Sum = 0 x = 0 for i in range(size): x = i Sum += a[i] Sums[0] += Sum + x t() print(Sums) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test13.py a = [1, 2, 3] c = [0, 0, 0] def t(): for i in range(len(a)): x = a[i]*2 c[i] = x y = x + 1 return y t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test2.py n=5 def t(x): return x*2 + n print(map(t, [i for i in range(10)])) <file_sep>/getting-zippy-megaguards.py import os, sys import re from subprocess import Popen, PIPE from threading import Thread global_verbose = True if 'VERBOSE' in os.environ and os.environ['VERBOSE'] == '1' else False noerrors = True zippy_megaguards_repo = "https://github.com/securesystemslab/zippy-megaguards.git" zippy_megaguards_branch = "master" zippy_megaguards_name = "zippy-megaguards" megaguards_name = "megaguards" jvmci_ver = '0.46' jvmci_jdk_ver = '1.8.0_172-jvmci-%s' % jvmci_ver jvmci_jdk_ver_tar = '8u172-jvmci-%s' % jvmci_ver current_path = os.getcwd() mx_path = current_path + os.sep + 'mx' jvmci_path = [ current_path + os.sep + 'labsjdk%s' % jvmci_jdk_ver, # Oracle current_path + os.sep + 'openjdk%s' % jvmci_jdk_ver # OpenJDK ] zippy_megaguards_path = current_path + os.sep + zippy_megaguards_name megaguards_path = current_path + os.sep + megaguards_name list_files = os.listdir(current_path) for f in list_files: if f.startswith('labsjdk1.8') and os.path.isdir(f): jvmci_path[0] = current_path + os.sep + f system_packages = [ "build-essential", "git", "wget", "curl", "ocl-icd-opencl-dev", "clinfo" ] reminders = [] _ansi_color_table = { 'red' : '31', 'green' : '32', 'yellow' : '33', 'magenta' : '35' } def colorize(msg, color='red'): coloring = '\033[' + _ansi_color_table[color] + ';1m' isUnix = sys.platform in ['linux', 'linux2', 'darwin', 'freebsd'] if isUnix and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): return coloring + msg + '\033[0m' return msg def print_ok(msg): ok = colorize(' OK ', 'green') print('[' + ok + '] ' + msg) def print_progress(msg): print('[ ... ] ' + msg) def print_error(msg): err = colorize(' ERROR ', 'red') print('[' + err + '] ' + msg) def print_warn(msg): w = colorize('WARNING', 'magenta') print('[' + w + '] ' + msg) def print_info(msg): i = colorize(' INFO ', 'yellow') print('[' + i + '] ' + msg) def print_question(msg): i = colorize(' ? ', 'yellow') return raw_input('[' + i + '] ' + msg) def execute_shell(cmd, cwd=None, check_only=False, verbose=False, directly=False): global noerrors print_progress('Executing: %s' % ' '.join(map(str, cmd))) if cwd is not None: print_progress('Path: %s' % cwd) try: if directly: p = Popen(cmd, cwd=cwd) else: p = Popen(cmd, cwd=cwd, stdout=PIPE, stderr=PIPE) except: if check_only: return 1 raise o = '' e = '' retcode = 0 if (verbose or global_verbose) and not directly: def teeOutput(s, f): for l in iter(s.readline, ''): print l, f[0] += l s.close() _o = [''] _e = [''] threads = [ Thread(target=teeOutput, args=(p.stdout, _o)), Thread(target=teeOutput, args=(p.stderr, _e)) ] for t in threads: t.start() while any([t.is_alive() for t in threads]): for t in threads: t.join(10) o = _o[0] e = _e[0] retcode = p.wait() else: o, e = p.communicate() retcode = p.returncode if check_only: return retcode if retcode != 0: print_error('Please fix this and re-run this script') noerrors = False print(e) print_error('return code: %d' % retcode) exit(1) else: print_ok('Success') return retcode, o, e def ask(msg, boolean=True, option=''): q = 'y/n' if boolean else option q = ' [%s]' % q answer = print_question(msg + q) if boolean: answer = answer.lower() if answer == 'y' or answer == 'yes': return True elif answer == 'n' or answer == 'no': return False else: print_info("Please answer using %s" % q) return ask(msg, boolean, _yes, _no) elif answer != '': return answer return option def end_script(): for r in reminders: print_info(r) print_error('We cannot proceed.. please fix all errors and retry again') print_error("You can set VERBOSE=1 to print all stdout and stderr\n\n\t$ export VERBOSE=1\n") exit(1) def loadEnv(path): envre = re.compile(r'''^([^=]+)=\s*(?:["'])(.+?)(?:["'])\s*$''') result = {} try: with open(path) as fp: for line in fp: match = envre.match(line) if match is not None: result[match.group(1)] = match.group(2) return result except: pass return None def update_env_file(path, envVars): _lines = [] if not os.path.exists(path): with open(path,'w') as fp: fp.write("# Environment variables\n") with open(path,'r') as fp: for line in fp: _lines += [line] added = False lines = [] for line in _lines: if '=' in line and '#' not in line: line = line.replace('\n','').split('=') var = line[0] varpath = line[1] if var in envVars: if varpath != envVars[var]: print('%s != %s' % (varpath, envVars[var])) print(line) var = '# ' + var else: envVars.pop(var) lines += [var + '=' + varpath + '\n'] else: lines += [line] for v in envVars: lines += [v + "=" + envVars[v] + '\n'] with open(path,'w') as fp: for line in lines: fp.write(line) print_info('This script is compatible with Ubuntu x86 16.04 64-bit') os_env = loadEnv(os.sep + 'etc' + os.sep + 'os-release') if not os_env or 'VERSION_ID' not in os_env or os_env['VERSION_ID'] != '16.04': print_warn("ZipPy+MegaGuards has not been tested for your system") system_packages_str = '' has_missing_packages = False missing_packages = [] for c in system_packages: cmd = ['dpkg', '-l', c] retcode = execute_shell(cmd, check_only=True) if retcode != 0: has_missing_packages = True missing_packages += [c] system_packages_str += '\t' + ' '.join(map(str, c)) + '\n' if has_missing_packages: msg = "First, we need to install the following packages:\n%s\nThese require 'sudo' privilege. Do you want to continue?" % sudo_cmds_str if ask(msg): cmd = ["sudo", "apt-get", "update"] execute_shell(cmd) for c in missing_packages: execute_shell(["sudo", "apt-get", "install", c]) else: end_script() print_ok("All system packages are installed") print_info('Checking if mx is installed in your system') cmd = ['mx', 'version'] retcode = execute_shell(cmd, check_only=True) mx_exists = True if retcode == 0 else False if not mx_exists: print_progress('Trying to locate mx at %s' % mx_path) if not os.path.isfile(mx_path + os.sep + 'LICENSE'): print_progress('Could not find mx. Trying to download it') cmd = ["git", "clone", "https://github.com/graalvm/mx.git"] execute_shell(cmd, verbose=True) shell_conf = '' if 'SHELL' in os.environ: shell_conf = '.' + os.environ.get('SHELL').split(os.sep)[-1] + 'rc' shell_conf = os.getenv('HOME') + os.sep + shell_conf if os.path.isfile(shell_conf): print_ok("We will add mx to $PATH variable in %s" % shell_conf) else: print_info("We couldn't find the config file for your shell") path = ask("Please provide the full path for your\nshell config file:", boolean=False, option=os.sep + 'path' + os.sep + 'to') if not os.path.isfile(path): print_error("shell config file provided doesn't exist") end_script() shell_conf = path mx_envpath = 'export PATH=$PATH:' + mx_path mx_envpath_exists = False with open(shell_conf, 'r') as fp: for l in fp: if l.replace('\n', '') == mx_envpath: mx_envpath_exists = True break if not mx_envpath_exists: with open(shell_conf, 'a') as fp: fp.write('\n# mx\n') fp.write(mx_envpath + '\n') reminders += ["Please execute\n\n\t$ source %s\nto reload $PATH variable" % shell_conf] os.environ['PATH'] = os.environ['PATH'] + ':' + mx_path else: print_info("Please re-run this script after you execute\n\n\t$ source %s\n" % shell_conf) end_script() print_ok("mx is installed") jdk_found = -1 print_progress('Trying to locate Oracle JDK with JVMCI at %s' % jvmci_path[0]) if not os.path.isfile(jvmci_path[0] + os.sep + 'bin' + os.sep + 'java'): print_progress('Trying to locate OpenJDK with JVMCI at %s' % jvmci_path[1]) if not os.path.isfile(jvmci_path[1] + os.sep + 'bin' + os.sep + 'java'): print_progress('Could not find a JDK with JVMCI.') else: jdk_found = 1 else: jdk_found = 0 if jdk_found == -1: jdk_options = "Which JDK do you want?\n" jdk_options += "[1] Oracle JDK with JVMCI %s (fast but proprietary)\n" % jvmci_jdk_ver jdk_options += "[2] OpenJDK JDK with JVMCI %s (Open Source)\n" % jvmci_jdk_ver jdk_options += "Your choice" jdk_choice = ask(jdk_options, boolean=False, option='1') default_ver = '' if jdk_choice == '1': default_ver = 'labsjdk-%s-linux-amd64.tar.gz' % jvmci_jdk_ver_tar if not os.path.isfile(default_ver): print_info('Please download it from http://www.oracle.com/technetwork/oracle-labs/program-languages/downloads/index.html') print_info('to this location: %s' % (current_path + os.sep + default_ver)) print_info('Then, re-run this script') end_script() else: jdk_found = 0 elif jdk_choice == '2': default_ver = 'openjdk-%s-linux-amd64.tar.gz' % jvmci_jdk_ver_tar jdk_found = 1 if not os.path.isfile(default_ver): cmd = ['wget', 'https://github.com/graalvm/openjdk8-jvmci-builder/releases/download/jvmci-%s/openjdk-%s-linux-amd64.tar.gz' % (jvmci_ver, jvmci_jdk_ver_tar)] execute_shell(cmd, verbose=True) else: print_error('Please re-run this script and choose a JDK') end_script() cmd = ["tar", "-xzf", default_ver] execute_shell(cmd) print_ok("JDK with JVMCI %s is installed" % jvmci_path[jdk_found]) print_info("Checking ZipPy+MegaGuards..") if not os.path.isfile(zippy_megaguards_path + os.sep + 'LICENSE'): cmd = ["git", "clone", zippy_megaguards_repo] execute_shell(cmd, verbose=True) cmd = ['git', 'checkout', zippy_megaguards_branch] execute_shell(cmd, cwd=zippy_megaguards_path) print_ok("ZipPy+MegaGuards is cloned") print_info("Checking environment variables for ZipPy+MegaGuards") if not os.path.isfile(zippy_megaguards_path + os.sep + 'mx.zippy' + os.sep + 'env'): with open(zippy_megaguards_path + os.sep + 'mx.zippy' + os.sep + 'env','w') as fp: fp.write("# ZipPy environment variables\n") zippy_default_env_vars = { 'JAVA_HOME' : jvmci_path[jdk_found], 'DEFAULT_VM': 'server', 'DEFAULT_DYNAMIC_IMPORTS': 'truffle/compiler', 'ZIPPY_MUST_USE_GRAAL': '1', 'ZIPPY_HOME': zippy_megaguards_path } update_env_file(zippy_megaguards_path + os.sep + 'mx.zippy' + os.sep + 'env', zippy_default_env_vars) print_ok("ZipPy+MegaGuards environment variables is set") print_info("Building ZipPy+MegaGuards") cmd = ['mx', 'build'] retcode = execute_shell(cmd, cwd=zippy_megaguards_path, check_only=True, verbose=True) if retcode != 0: print_warn('Previous build was not successful return code: %d' % retcode) cmd = ['mx', 'clean'] execute_shell(cmd, cwd=zippy_megaguards_path) cmd = ['mx', 'build'] execute_shell(cmd, cwd=zippy_megaguards_path, verbose=True) print_ok("ZipPy+MegaGuards build succeeded") print_info("Initializing MegaGuards") cmd = ['mx', 'mg', '--init'] execute_shell(cmd, cwd=zippy_megaguards_path, directly=True) print_info("Detecting OpenCL devices") cmd = ['mx', 'mg', '--clinfo'] execute_shell(cmd, cwd=zippy_megaguards_path, directly=True) print_info("Running unit test for MegaGuards") cmd = ['mx', 'junit-mg'] retcode = execute_shell(cmd, cwd=zippy_megaguards_path, check_only=True, directly=True) if retcode != 0: print_error('Unit test failed') end_script() else: print_ok('Unit test succeeded') print_ok("Everything looks good") how_to = """How to use MegaGuards with a Python program? Use one of these options: --mg-target=truffle to execute using a guardless Truffle AST on Graal. --mg-target=gpu to execute on a GPU OpenCL device. --mg-target=cpu to execute on a CPU OpenCL device. --mg-target to execute using our adaptive OpenCL device selection. for example: $ cd """ + zippy_megaguards_name + """ $ mx python <file.py> --mg-target=gpu """ print_info(how_to) if len(reminders) > 0: print_info('Last things:') for r in reminders: print_info(r) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test40.py size = 8 a = [2 * n for n in range(size * size)] Sums = [0 for i in range(3)] def t(): for k in range(3): Sum = 0 for i in range(size): for j in range(size): tmp = a[i * size + j] Sum += tmp Sums[0] += Sum t() print(Sums) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test45.py a = [ i for i in range(100)] b = [ i*2 for i in range(100)] c = [ 0 for i in range(100)] def w(d, e, f): for i in range(100): d[i] += b[i] + e[i]*2 def t(): for j in range(1,len(a)-1, 2): w(c,a,b) if j > 20: break t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test18.py a = [1, 2, 3] c = [0, 0, 0] def w(x): a[0] = a[0] + x*2 return a[0]*2 def t(): for i in range(len(a)): c[i] = w(i) t() a[0] = 5 t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test27.py a = [1, 2, 3, 1, 2, 3, 1, 2, 3] c = [1, 2, 3, 1, 2, 3, 1, 2, 3] def callme(): for i in range(3): for j in range(3): c[i*3 + j] = a[i*3+j] * 2 callme() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test6.py a = [1, 2, 3] c = [0, 0, 0] def w(x, y): return x[y]*2 def t(): for i in range(len(a)): c[i] = w(a,i) t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test12.py a = [1, 2, 3] c = [0, 0, 0] def t(l): for i in range(l): c[i] = a[i] * 2 if a[i] == 2 else a[i] * 3 x = a[i] * 2 if a[i] == 2 else a[i] * 3 c[i] = x t(2) print(c) t(3) print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test6.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def callme(): for i in range(len(a)): """@MG:ddoff""" a[0][i] = a[0][0]*2 return a[0] b = callme() # print(b) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test4.py from functools import reduce print(reduce(lambda a, b: a + b, [ i+1 for i in range(2000)])) <file_sep>/zippy/edu.uci.python.test/src/edu/uci/megaguards/test/parallel/ForTests.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in script and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of script code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.test.parallel; import static edu.uci.python.test.PythonTests.assertPrints; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assume.assumeTrue; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; import edu.uci.megaguards.MGOptions; import edu.uci.megaguards.test.MGTests; @FixMethodOrder(MethodSorters.JVM) public class ForTests { private static final String path = MGTests.MGSrcTestPath + File.separator + "for" + File.separator; @Test public void simple() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test1.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test2.py"); assertPrints("[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, " + // "80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152," + // " 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_two_forloops() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); // Note: Data dependence issue c[i] Path script = Paths.get(path + "test3.py"); assertPrints("[8, 10, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_2_two_forloops() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test4.py"); assertPrints("[8, 10, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void a4d_simple() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test5.py"); assertPrints("[[[[2, 4, 6], [8, 10, 12]], [[14, 16, 18], [20, 22, 24]]], [[[2, 4, 6], [8, 10, 12]], [[14, 16, 18], [20, 22, 24]]]]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_function_two_forloops() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test6.py"); assertPrints("[8, 10, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 0); MGTests.releaseMGParallelOptions(); } @Test public void simple_no_arrays() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test7.py"); assertPrints("", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_not() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test8.py"); assertPrints("[2, 0, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_break() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test9.py"); assertPrints("[1, 4, 1]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void not_simple_range() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test10.py"); assertPrints("[[2, 4, 6], [2, 4, 6], [2, 4, 6]]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void simple_minus() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test11.py"); assertPrints("[-2, -4, -6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_if() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(3); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test12.py"); assertPrints("[3, 4, 0]\n[3, 4, 9]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void simple_int() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test13.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_comp() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test14.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 3); MGTests.releaseMGParallelOptions(); } @Test public void simple_comp2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test15.py"); assertPrints("[2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 3); MGTests.releaseMGParallelOptions(); } @Test public void simple_minMax() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test16.py"); assertPrints("[1, 2, 3]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_round() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test17.py"); assertPrints("[2.0, 4.0, 6.0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_two_len_range() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(4); int lastLogSize = MGTests.lastLogSize(); // Note: Data dependence issue c[i] Path script = Paths.get(path + "test18.py"); assertPrints("[8, 10, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_two_var_range() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(4); int lastLogSize = MGTests.lastLogSize(); // Note: Data dependence issue c[i] Path script = Paths.get(path + "test19.py"); assertPrints("[8, 10, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_two_iter_range() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(4); int lastLogSize = MGTests.lastLogSize(); // Note: Data dependence issue c[i] Path script = Paths.get(path + "test20.py"); assertPrints("[6, 9, 12]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_dd_threshold() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(3); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test21.py"); assertPrints("[2, 4, 0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 3, 27); MGTests.releaseMGParallelOptions(); } @Test public void simple_recycle_tree() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test22.py"); assertPrints("[8, 10, 12]\n[26, 46, 66]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void simple_recycle_tree2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test23.py"); assertPrints("[8, 10, 12]\n[26, 46, 66]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void simple_recycle_tree3() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test24.py"); assertPrints("[8, 10, 12]\n[26.4, 46.4, 66.4]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void simple_handoff_to_offload() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); MGOptions.Backend.concurrentCompiler = true; int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test25.py"); Path output = Paths.get(path + "test25.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_handoff_to_offload2() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); MGOptions.Backend.concurrentCompiler = true; int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test26.py"); Path output = Paths.get(path + "test26.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_range_1D() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test27.py"); assertPrints("[2, 4, 6, 2, 4, 6, 2, 4, 6]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_multiranges() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); MGOptions.Backend.concurrentCompiler = false; int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test28.py"); Path output = Paths.get(path + "test28.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 3); MGTests.releaseMGParallelOptions(); } @Test public void simple_stepOf2_handoff_to_offload() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); MGOptions.Backend.concurrentCompiler = true; int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test29.py"); Path output = Paths.get(path + "test29.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void simple_recycle_tree4() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test31.py"); assertPrints("[8.0, 10.0, 12.0]\n[26.0, 46.0, 66.0]\n", script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void test32() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test32.py"); Path output = Paths.get(path + "test32.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 2); MGTests.releaseMGParallelOptions(); } @Test public void test33() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test33.py"); Path output = Paths.get(path + "test33.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void test34() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); // overflow int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test34.py"); Path output = Paths.get(path + "test34.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 12); MGTests.releaseMGParallelOptions(); } @Test public void test35() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test35.py"); Path output = Paths.get(path + "test35.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Ignore @Test public void test36() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test36.py"); Path output = Paths.get(path + "test36.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void test37() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); // overflow exception Path script = Paths.get(path + "test37.py"); Path output = Paths.get(path + "test37.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void test38() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test38.py"); Path output = Paths.get(path + "test38.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 0, 1); MGTests.releaseMGParallelOptions(); } @Test public void test39() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test39.py"); Path output = Paths.get(path + "test39.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void test40() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test40.py"); Path output = Paths.get(path + "test40.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void test41() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test41.py"); Path output = Paths.get(path + "test41.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 3); MGTests.releaseMGParallelOptions(); } @Test public void test42() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test42.py"); Path output = Paths.get(path + "test42.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void test43() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test43.py"); Path output = Paths.get(path + "test43.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 0); MGTests.releaseMGParallelOptions(); } @Test public void test44() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test44.py"); Path output = Paths.get(path + "test44.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 41, 0); MGTests.releaseMGParallelOptions(); } @Test public void test45() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test45.py"); Path output = Paths.get(path + "test45.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 11); MGTests.releaseMGParallelOptions(); } @Test public void test46() { assumeTrue(MGTests.isOpenCLDeviceAvailable()); MGTests.setMGParallelOptions(); int lastLogSize = MGTests.lastLogSize(); Path script = Paths.get(path + "test46.py"); Path output = Paths.get(path + "test46.output"); assertPrints(output, script); MGTests.verifyMGExecution(script, lastLogSize, 1, 11); MGTests.releaseMGParallelOptions(); } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test10.py a = [1, 2, 3] c = [0, 0, 0] def t(): for i in range(len(a)): for j in range(1,len(a)): c[i] = a[j]*2 + c[i - 1] t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test12.py n=5 print(list(map(lambda x, y:x*y*2 + n, [i for i in range(10)], [i for i in range(10)]))) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test4.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(len(a)): a[0][i] = a[0][0]*2 t() print(a[0]) <file_sep>/zippy/edu.uci.python/src/edu/uci/megaguards/python/node/MGForNode.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.python.node; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.NodeInfo; import edu.uci.megaguards.MGOptions; import edu.uci.megaguards.analysis.exception.MGException; import edu.uci.megaguards.backend.MGFor; import edu.uci.megaguards.log.MGLog; import edu.uci.megaguards.python.ast.MGPythonTree; import edu.uci.megaguards.python.fallback.ForFallback; import edu.uci.python.ast.VisitorIF; import edu.uci.python.nodes.PNode; import edu.uci.python.nodes.control.ForNode; import edu.uci.python.nodes.control.GetIteratorNode; import edu.uci.python.nodes.control.LoopNode; import edu.uci.python.nodes.frame.WriteNode; import edu.uci.python.nodes.function.FunctionRootNode; import edu.uci.python.runtime.datatype.PGenerator; import edu.uci.python.runtime.datatype.PNone; import edu.uci.python.runtime.function.PFunction; import edu.uci.python.runtime.iterator.PDoubleIterator; import edu.uci.python.runtime.iterator.PIntegerIterator; import edu.uci.python.runtime.iterator.PIntegerSequenceIterator; import edu.uci.python.runtime.iterator.PIterator; import edu.uci.python.runtime.iterator.PLongIterator; import edu.uci.python.runtime.iterator.PLongSequenceIterator; import edu.uci.python.runtime.iterator.PRangeIterator; import edu.uci.python.runtime.iterator.PSequenceIterator; @NodeInfo(shortName = "for") @NodeChild(value = "iterator", type = GetIteratorNode.class) @GenerateNodeFactory public abstract class MGForNode extends LoopNode { @Child protected PNode target; @Child private MGFor<PNode, PFunction> MGSpecialized; private final ForFallback fallback; public MGForNode(PNode body, PNode target, MGFor<PNode, PFunction> call) { super(body); this.target = target; assert target instanceof WriteNode; this.MGSpecialized = call; this.fallback = (ForFallback) call.getFallback(); } public MGForNode(PNode body, PNode target) { this(body, target, new MGFor.Uninitialized<>(MGPythonTree.PyTREE, new ForFallback())); } private static String getFunctionName(Node node) { if (node instanceof FunctionRootNode) return ((FunctionRootNode) node).getFunctionName(); if (node == null) return null; return getFunctionName(node.getParent()); } public PNode getTarget() { return target; } public MGFor<PNode, PFunction> getMGFor() { return MGSpecialized; } public ForNode replace() { return this.replace(((ForFallback) MGSpecialized.getFallback()).fallback(this)); } public boolean preCheck() { return fallback.check(this); } public boolean isOptimized() { return !MGSpecialized.isUninitialized(); } public boolean isRetry() { return preCheck(); } public boolean isFailed() { return !isOptimized() && !preCheck(); } @Override public String toString() { if (getSourceSection() != null) return getSourceSection().getSource().getName() + ":" + getSourceSection().getStartLine() + ": " + getSourceSection().getCharacters().toString(); return super.toString(); } public abstract PNode getIterator(); @Specialization(guards = "isOptimized()", rewriteOn = MGException.class) public Object doPRangeMGOptimized(VirtualFrame frame, PRangeIterator prange) { final int start = prange.getStart(); final int stop = prange.getStop(); final int step = prange.getStep(); if (start == stop) { return PNone.NONE; } MGSpecialized.forLoop(frame, start, stop, step); return PNone.NONE; } @Specialization(guards = "isRetry()", rewriteOn = MGException.class) public Object doPRangeMGUninitialized(VirtualFrame frame, PRangeIterator prange) { final int start = prange.getStart(); final int stop = prange.getStop(); final int step = prange.getStep(); if (start == stop) { return PNone.NONE; } final String fn = getFunctionName(this); final MGFor<PNode, PFunction> n = MGSpecialized.forLoop(frame, getEncapsulatingSourceSection(), fn, target, body, start, stop, step); CompilerDirectives.transferToInterpreterAndInvalidate(); MGForNode replacement = MGForNodeFactory.create(getBody(), getTarget(), n, (GetIteratorNode) getIterator()); replacement.assignSourceSection(getSourceSection()); if (MGOptions.Backend.Debug > 0) { final int line = getSourceSection().getStartLine(); final String filename = getSourceSection().getSource().getName() + ":" + line; String msg = "(optimize)"; MGLog.println(filename, msg); } replace(replacement); return PNone.NONE; } @Specialization(guards = "isFailed()") public Object doPRange(VirtualFrame frame, PRangeIterator range) { return replace().doPRange(frame, range); } public Object doPRangeZipPy(VirtualFrame frame, int start, int stop, int step) { int i = start; for (; i < stop; i += step) { ((WriteNode) target).executeWrite(frame, i); body.executeVoid(frame); } return PNone.NONE; } @Specialization public Object doPRangeRetry(VirtualFrame frame, PRangeIterator prange) { final int start = prange.getStart(); final int stop = prange.getStop(); final int step = prange.getStep(); if (start == stop) { return PNone.NONE; } doPRangeZipPy(frame, start, stop, step); replace(fallback.fallbackRetry(this)); return PNone.NONE; } @Specialization public Object doIntegerSequenceIterator(VirtualFrame frame, PIntegerSequenceIterator iterator) { return replace().doIntegerSequenceIterator(frame, iterator); } @Specialization public Object doIntegerIterator(VirtualFrame frame, PIntegerIterator iterator) { return replace().doIntegerIterator(frame, iterator); } @Specialization public Object doLongSequenceIterator(VirtualFrame frame, PLongSequenceIterator iterator) { return replace().doLongSequenceIterator(frame, iterator); } @Specialization public Object doLongIterator(VirtualFrame frame, PLongIterator iterator) { return replace().doLongIterator(frame, iterator); } @Specialization public Object doDoubleIterator(VirtualFrame frame, PDoubleIterator iterator) { return replace().doDoubleIterator(frame, iterator); } @Specialization(guards = "isObjectStorageIterator(iterator)") public Object doObjectStorageIterator(VirtualFrame frame, PSequenceIterator iterator) { return replace().doObjectStorageIterator(frame, iterator); } @Specialization public Object doIterator(VirtualFrame frame, PSequenceIterator iterator) { return replace().doIterator(frame, iterator); } @Specialization public Object doGenerator(VirtualFrame frame, PGenerator generator) { return replace().doGenerator(frame, generator); } @Specialization public Object doIterator(VirtualFrame frame, PIterator iterator) { return replace().doIterator(frame, iterator); } @Override public <R> R accept(VisitorIF<R> visitor) throws Exception { return visitor.visitMGForNode(this); } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test6.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] b = [4, 5, 6] c = [0, 0, 0] def callme(): for j in range(len(a)): for [A1, A2, A3] in a: for B in b: c[A1-1] = B + A1*2 c[A2-1] = B + A2*2 c[A3-1] = B + A3*2 for i in range(3): callme() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/dd/test5.py a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(len(a)): for j in range(len(a)): a[i][j] = a[i][j]*2 t() print(a) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test41.py size = 8 a = [2 * n for n in range(size * size)] Sums = [-i for i in range(size)] def t(): for k in range(3): Sum = 0 for i in range(size): for j in range(size): tmp = a[i * size + j] Sum += tmp for i in range(size): Sums[i] += Sum - a[i] t() print(Sums) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test2.py a = [1, 2, 3] b = [4, 5, 6] c = [0, 0, 0] def w(x, y): z = x + y*2 return z def t(): for j in range(len(a)): for i in range(len(b)): c[j] = w(b[i], a[j]) t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/for/test21.py N=3 def t(x): a = [[ i+1 for i in range(N)] for j in range(N) ] for i in range(3): for j in range(3): for k in range(x): c[0][k] = a[0][k]*2 c = [[ 0 for i in range(N)] for j in range(N) ] t(2) c = [[ 0 for i in range(N)] for j in range(N) ] t(3) c = [[ 0 for i in range(N)] for j in range(N) ] t(2) print(c[0]) <file_sep>/zippy/edu.uci.python.test/src/edu/uci/megaguards/test/MGTests.java /* * Copyright (c) 2018, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.uci.megaguards.test; import static org.junit.Assert.assertEquals; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import edu.uci.megaguards.MGEnvVars; import edu.uci.megaguards.MGLanguage; import edu.uci.megaguards.MGOptions; import edu.uci.megaguards.backend.ExecutionMode; import edu.uci.megaguards.backend.parallel.opencl.OpenCLMGR; import edu.uci.megaguards.log.MGLog; import edu.uci.megaguards.log.MGLogOption; import edu.uci.megaguards.python.MGPythonInit; import edu.uci.python.runtime.PythonOptions; public class MGTests { public static final String MGDataSet = MGEnvVars.MGHome + File.separator + "dataset" + File.separator; public static final String MGSrcTestPath = "megaguards" + File.separator; public static final String MGTestDataSet = MGDataSet + "test" + File.separator; public static final String MGRodiniaTestData = MGTestDataSet + "rodinia" + File.separator; public static final String MGBenchmarkPath = "megaguards-benchmark-suite" + File.separator; public static final String MGHPCPath = MGBenchmarkPath + "hpc" + File.separator + "Python" + File.separator; public static final String MGRodiniaPath = MGBenchmarkPath + "rodinia" + File.separator + "Python" + File.separator; public static final String MGRodiniaData = MGDataSet + "benchmark" + File.separator + "rodinia" + File.separator; public static void setMGParallelOptions() { setMGParallelOptions(1); } /** * @param threshold */ public static void setMGParallelOptions(long threshold) { MGLanguage.INSTANCE.getOptionValues(); MGOptions.junit = true; MGOptions.MGOff = false; PythonOptions.MGOff = false; MGOptions.Backend.target = ExecutionMode.OpenCLAuto; OpenCLMGR.MGR.isValidAutoDevice(false); // OpenCLMGR.MGR.isValidCPUDevice(false); // OpenCLMGR.MGR.isValidGPUDevice(false); MGOptions.Backend.concurrentCompiler = false; MGOptions.Backend.AthenaPet = true; MGOptions.Backend.offloadThreshold = 0; MGOptions.Backend.AthenaPetJNIDebug = 0; MGOptions.Backend.AthenaPetDebug = 0; MGOptions.Backend.BoundCheckDebug = 0; // MGOptions.Parallel.Debug = 4; // MGOptions.Debug = 4; // MGOptions.logging = true; // MGOptions.Parallel.cleanup = true; // MegaGuards Log // MGOptions.Log.Summary = true; // MGOptions.Log.JSON = true; // MGOptions.Log.Exception = true; // MGOptions.Log.ExceptionStack = true; MGLogOption.enableOption("GeneratedCode"); // MGOptions.Log.TraceUnboxing = true; // MGLogOption.enableOption("UnboxTime"); // MGLog.setJSONFile("profile.json"); // MGOptions.Log.NodeProfileJSON = true; // MGOptions.Log.TotalDataTransfer = true; // MGOptions.Log.CompilationTime = true; // MGOptions.Log.OpenCLTranslationTime = true; // MGOptions.Log.DependenceTime = true; // MGOptions.Log.TranslationTime = true; // MGOptions.Log.TotalTime = true; // MGOptions.Log.Code = true; // MGOptions.Log.CoreExecutionTime = true; // MGOptions.Log.StorageConversionTime = true; // MGOptions.Log. = true; // MGOptions.forceLongType = true; // PythonOptions.forceLongType = true; MGPythonInit.INSTANCE.MGInitialization(); } public static void releaseMGParallelOptions() { MGOptions.Backend.target = ExecutionMode.NormalCPU; MGOptions.Backend.concurrentCompiler = false; MGOptions.MGOff = true; PythonOptions.MGOff = true; MGOptions.boundCheck = true; MGOptions.Backend.AthenaPetJNIDebug = 0; MGOptions.Backend.AthenaPetDebug = 0; MGOptions.Backend.Debug = 0; MGOptions.Debug = 0; // MGOptions.forceLongType = false; // PythonOptions.forceLongType = false; MGLog.getLogs().clear(); } public static boolean isOpenCLDeviceAvailable() { if (OpenCLMGR.MGR.getNumDevices() == 0) { return false; } boolean valid = false; setMGParallelOptions(); switch (MGOptions.Backend.target) { case OpenCLGPU: if (OpenCLMGR.GPUs.size() > 0) valid = true; break; case OpenCLCPU: if (OpenCLMGR.CPUs.size() > 0) valid = true; break; case OpenCLAuto: if (OpenCLMGR.GPUs.size() > 0 && OpenCLMGR.CPUs.size() > 0) valid = true; break; } releaseMGParallelOptions(); return valid; } public static void setMGTruffleOptions() { MGOptions.junit = true; MGOptions.MGOff = false; PythonOptions.MGOff = false; MGOptions.Backend.offloadThreshold = 0; MGOptions.Backend.target = ExecutionMode.Truffle; MGOptions.Backend.BoundCheckDebug = 0; MGOptions.Debug = 0; // MGOptions.logging = true; // MegaGuards Log // MGOptions.Log.Summary = true; // MGOptions.Log.JSON = true; // MGOptions.Log.Exception = true; // MGOptions.Log.ExceptionStack = true; // MGOptions.Log.TraceUnboxing = true; // MGLogOption.enableOption("UnboxTime"); // MGLog.setJSONFile("profile.json"); // MGOptions.Log.NodeProfileJSON = true; // MGOptions.Log.TotalDataTransfer = true; // MGOptions.Log.CompilationTime = true; // MGOptions.Log.TranslationTime = true; // MGOptions.Log.TotalTime = true; // MGOptions.Log.CoreExecutionTime = true; // MGOptions.Log.StorageConversionTime = true; MGPythonInit.INSTANCE.MGInitialization(); } public static void releaseMGTruffleOptions() { MGOptions.Backend.target = ExecutionMode.NormalCPU; MGOptions.MGOff = true; MGOptions.boundCheck = true; MGOptions.Backend.Debug = 0; MGOptions.Debug = 0; PythonOptions.forceLongType = false; PythonOptions.MGOff = true; MGLog.getLogs().clear(); } public static void verifyMGExecution(Path script, int lastLogSize, int expectedTruffle, int expectedParallel) { ArrayList<MGLog> logs = MGLog.getLogs(); long executedTruffle = 0; long executedParallel = 0; for (int i = lastLogSize; i < logs.size(); i++) { MGLog log = logs.get(i); executedTruffle += log.getOptionValueLong("TotalTruffleExecutions"); executedParallel += log.getOptionValueLong("TotalKernelExecutions"); } assertEquals("MegaGuards (Truffle) didn't execute as expected: " + script.toString(), expectedTruffle, executedTruffle); assertEquals("MegaGuards (OpenCL ) didn't execute as expected: " + script.toString(), expectedParallel, executedParallel); } public static int lastLogSize() { return MGLog.getLogs().size(); } } <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/funcall/test16.py a = [1, 2, 3] c = [0, 0, 0] def w(x): a[x] = a[x]*2 def t(): for i in range(len(a)): w(i) c[i] = a[i] t() print(c) <file_sep>/zippy/edu.uci.python.test/src/tests/megaguards/reduction/test6.py from functools import reduce def t(a, b): return a * b print(reduce(t, [ i+1 for i in range(8)]))
a8b5d72bbae4c4af509567f773f636646e39cfd6
[ "Markdown", "Java", "Python" ]
68
Python
securesystemslab/zippy-megaguards
9e3324d6aea0327fe499b9e07b1a67194ddd1db3
3d97a0507b784c6bd992da8de49334d31df709eb
refs/heads/master
<repo_name>nakanaa/docker-aceproxy<file_sep>/runit/vlc #!/bin/bash # From: https://github.com/ikatson/docker-acestream-proxy/blob/master/supervisord.conf exec setuser vlc vlc -I telnet --clock-jitter 0 --network-caching 500 --telnet-password admin<file_sep>/Dockerfile # References used: # https://github.com/phusion/baseimage-docker # https://github.com/ValdikSS/aceproxy # https://github.com/ikatson/docker-acestream-proxy/ # Key config files: # /usr/local/aceproxy/aceconfig.py FROM phusion/baseimage:0.9.16 MAINTAINER nakanaa # Set correct environment variables ENV REFRESHED_AT 14.04.2015 ENV HOME /root WORKDIR $HOME # Add AceStream repo for acestream-engine package RUN echo 'deb http://repo.acestream.org/ubuntu/ trusty main' > /etc/apt/sources.list.d/acestream.list && \ curl -L http://repo.acestream.org/keys/acestream.public.key | apt-key add - RUN \ # Install required packages apt-get -q -y update && DEBIAN_FRONTEND=noninteractive apt-get -q -y install \ unzip \ acestream-engine \ vlc-nox \ python-gevent \ python-psutil && \ # Clean up APT when done apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Make sure setuptools is installed (Stops on error "No module named pkg_resources" otherwise) RUN curl -L https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python && rm -rf * # Create user vlc; VLC cannot be run as root RUN adduser --disabled-password --gecos "" vlc ENV ACEPROXY_VERSION v0.9.1 RUN \ # Download AceProxy curl -LO https://github.com/ValdikSS/aceproxy/archive/${ACEPROXY_VERSION}.zip && \ # Extract unzip *.zip && \ # Move to /usr/local/ mv */ /usr/local/aceproxy && \ # Create symbolic link ln -s /usr/local/aceproxy/acehttp.py /usr/bin/acehttp && \ # Remove downloaded files rm -rf * # Copy config ADD conf/aceconfig.py /usr/local/aceproxy/aceconfig.py # Setup runit RUN mkdir /etc/service/acestream && mkdir /etc/service/vlc ADD runit/acestream /etc/service/acestream/run ADD runit/vlc /etc/service/vlc/run RUN chmod +x /etc/service/acestream/run && chmod +x /etc/service/vlc/run RUN curl -L https://raw.githubusercontent.com/nakanaa/conf-fetcher/master/conf-fetcher.sh -o /etc/my_init.d/01_conf-fetcher.sh && chmod +x /etc/my_init.d/01_conf-fetcher.sh # Expose AceProxy port EXPOSE 8000 # Use baseimage-docker's init system ENTRYPOINT ["/sbin/my_init", "--"] # Define default command # Sleep for 5 seconds to make sure the other services have time to startup CMD sh -c "sleep 5 && /usr/bin/acehttp"<file_sep>/runit/acestream #!/bin/bash # From: https://github.com/ikatson/docker-acestream-proxy/blob/master/supervisord.conf exec acestreamengine --log-stdout --client-console --bind-all
fd489244ac6a0fc45e431ef13baa791b261f6820
[ "Dockerfile", "Shell" ]
3
Shell
nakanaa/docker-aceproxy
d2bca848a3f01bd9acd5503897b0e701da1d5a63
bc89aa47d3ec257b2d9a1b676d5bd28c52488f75
refs/heads/master
<file_sep>// // Utility.h // EyeTracker // // Created by <NAME> on 17/04/2017. // Copyright © 2017 <NAME>. All rights reserved. // #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #ifndef GradientHelper_h #define GradientHelper_h cv::Mat computeGradient(const cv::Mat& mat); cv::Mat matrixMagnitude(const cv::Mat& gradientX, const cv::Mat& gradientY); double computeThreshold(const cv::Mat& magnitudes, double stdDevFactor); #endif /* Utility_h */ <file_sep># Pupil_Tracker_iPad This is an old archive of my undergrad thesis project. This is meant to be an IOS application on iPad that helps initial screening of abnormal eye movement caused by stroke. The essential algorithm is for tracking pupil in real time with iPad back camera. The full project file is too large so only the core algorithm code files related to the real-time image analysis are uploaded here. # OpenCV in IOS Application This project was done around 3-4 years ago before I got into ML/DL. Therefore, only traditional methods are used with OpenCV. The IOS development was conducted with Objective C and C++ was embedded inside to work with OpenCV. ***FaceDetecter.mm*** hosts the major codes. # Breakdown of Algorithm 1) Face detection with Haar Cascade features 2) Eye detection with Haar Cascade features inside the detected face area 3) Pupil detection with calculation of gradient and Circle Hough Transform
f67a2f0cbce431d54ce36dbf706cebefeaff835c
[ "Markdown", "C" ]
2
C
WeiwenXu21/Pupil_Tracker_iPad
d86169f3ed0ea1bfbd0ca330cec1ac9437c54c24
fa4ac0418ec12984c67f7e8c557842c0f7d35832
refs/heads/master
<file_sep>from collections import Counter from datetime import datetime, timedelta import getpass, os, email, sys, gmail, dispatch_gmail, re, time, imaplib, string, pywapi import operator import pdb import urllib from chartit import DataPool, Chart from dispatch.models import UlsterIncident from dispatch_gmail.models import IncidentEmail from django.http import HttpResponse from django.shortcuts import render, redirect from django.shortcuts import render_to_response from django.template.context import RequestContext import json as simplejson import simplejson import dispatch_settings def import_incidents(source): ''' Master incident import view. Used for the initial population of the dispatch database. Incidents must be unique in the databse, or ProgrammingError is raised. ''' if source == 'twitter': raw_incident = get_twitter_incidents(dispatch_settings.TWITTER_USERNAME) elif source == 'email': raw_incident = import_email_incidents(dispatch_settings.EMAIL_USERNAME) else: raise ValueError("Invalid dispatch source. Please specify twitter, email or cad.") try: for incident in list: normalized_data = normalize_incidnt_data(raw_incident.payload) parse = parse_incident(normalized_data.payload, raw_incident.recieved_datetime) incident_dict = parse.incident_dict geocode = geocode_incident(incident_dict) incident = UlsterIncident.objects.create(datetime = raw_incident.recieved_datetime, lat = geocode[0], long = geocode[1], **incident_dict) incident.save() print "Created Incident %d" % incident.id return HttpResponse('200') except ProgrammingError: pass def get_current_weather(request): weather_com_result = pywapi.get_weather_from_weather_com(dispatch_settings.LOCALE_ZIP) yahoo_result = pywapi.get_weather_from_yahoo(dispatch_settings.LOCALE_ZIP) noaa_result = pywapi.get_weather_from_noaa(dispatch_settings.NOAA_STATION_CALL_SIGN) print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print "Yahoo says: It is " + string.lower(yahoo_result['condition']['text']) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n" print "NOAA says: It is " + string.lower(noaa_result['weather']) + " and " + noaa_result['temp_c'] + "C now in New York.\n" def get_historical_weather(request): pass def normalize_incidnt_data(payload): ''' Converts unicode data to a python string. ''' decoded_payload = unicodedata.normalize('NFKD', payload).encode('ascii', 'ignore') payload = decoded_payload.replace('\n', '').replace('\r', '') return payload def parse_incident(payload, sent): ''' Using configurable incident data fields, parse the data into incident models with all of the information required. ''' keys = set(dispatch_settings.INCIDENT_FIELDS) key_re = re.compile('(' + '|'.join(re.escape(key) for key in keys) + ')%r' % dispatch_settings.DELINIATER, re.IGNORECASE) key_locations = key_re.split(payload)[1:] incident_dict = {k: v.strip() for k,v in zip(key_locations[::2], key_locations[1::2])} # Create a model instance for each incident. return incident_dict def get_zipcode(): pass def get_coordinates(incident_dict, from_sensor=False): ''' Uses the unauthenticated Google Maps API V3. using passed incident dictionary, gather relevant location text and return a latitude and logitude for an incident. ''' #Gather the required search text from the incident dict. location_fields = dispatch_settings.LOCATION_FIELDS incident_location_list = [incident_dict[x] for x in location_fields] incident_location_string = string.lower(" ".join(incident_location_list)) + dispatch_settings.LOCALE_STATE.encode('utf-8') #Now lookups the incident's coordinates. googleGeocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?' params = { 'address': incident_location_string, 'sensor': "true" if from_sensor else "false" } url = googleGeocodeUrl + urllib.urlencode(params) json_response = urllib.urlopen(url) response = simplejson.loads(json_response.read()) if response['results']: location = response['results'][0]['geometry']['location'] latitude, longitude = location['lat'], location['lng'] print incident_location_data, latitude, longitude else: latitude, longitude = None, None print incident_location_data, "Could not generate coordinates for this Incident" return latitude, longitude def gross_hourly_most_common(request): incident_list = Incident.objects.all() abstract_hour_list = [] for i in incident_list: time = i.datetime hour = time.hour abstract_hour_list.extend([hour]) x = Counter(abstract_hour_list) sorted_x = sorted(x.items(), key=operator.itemgetter(0)) x_values = [x[1] for x in sorted_x] context = {'x_values':x_values,'incident_list': incident_list} return render(request, 'dashboard.html', context) #pdb.set_trace() def gross_hourly_chart(request): incident_list = IncidentEmail.objects.all() for incidentemail in incident_list: datetime_str = incidentemail.datetime_str #Step 1: Create a DataPool with the data we want to retrieve. incidentdata = \ DataPool( series= [{'options': { 'source': GrossHourlyIncidents.objects.all()}, 'terms': [ 'hour', 'count',]} ]) #Step 2: Create the Chart object cht = Chart( datasource = incidentdata, series_options = [{'options':{ 'type': 'line', 'stacking': False}, 'terms':{ 'hour': [ 'count',] }}], chart_options = {'title': { 'text': 'All Incident Occurances by Hour'}, 'xAxis': { 'title': { 'text': 'Time'}}}) #Step 3: Send the chart object to the template. return render(request, 'dashboard.html', {'grosshourchart': cht}) <file_sep>from django.shortcuts import render, redirect from django.http import HttpResponse from django.shortcuts import render_to_response from django.template.context import RequestContext from datetime import datetime, timedelta from dispatch.models import UlsterIncident from dispatch_gmail.models import IncidentEmail import getpass, os, email, sys, gmail, dispatch_gmail, re, time, imaplib, string, pywapi import pdb from chartit import DataPool, Chart import json as simplejson from collections import Counter import operator from dispatch.models import * from dispatch.views import get_coordinates from dispatch.views import parse_incident def import_email_incidents(request): ''' This view connects to an individuals gmail inbox, selects emails sent from 911 Dispatch, by sender address, and saves the emails to the databsse. ''' usernm = raw_input("Username:") passwd = <PASSWORD>(prompt='Password: ', stream=None) conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login(usernm,passwd) conn.select('Dispatch') #Only trying to parse the emails that are relevant. Selecting by sender and subject. typ, data = conn.search(None, '(FROM "<EMAIL>" SUBJECT "Company 43")') #Extract the data we need. for num in data[0].split(): typ, msg_data = conn.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part,tuple): msg = email.message_from_string(response_part[1]) time_stamp = email.utils.parsedate(msg['Date']) time_int = time.mktime(time_stamp) received_datetime = datetime.fromtimestamp(time_int) payload = msg.get_payload(decode=True) #pdb.set_trace() incident_email = IncidentEmail.objects.create(datetime = received_datetime, payload = payload) incident_email.save() sys.stdout.write("Saved email #%s \r" % incident_email.id) sys.stdout.flush() parse_incident(payload, received_datetime) print "Done." #return '\n'.join([get_incident_emails(part.get_payload()) for part in payload]) return render(request, 'dashboard.html') #return redirect('parse_incident_emails') <file_sep>from datetime import datetime import pdb import re from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from dispatch.models import IncidentManager class IncidentEmail(models.Model): datetime = models.DateTimeField(blank=True, null=True) payload = models.CharField(max_length=10000, blank=True, null=True) class Meta: unique_together = ["payload", "datetime"]<file_sep>from datetime import datetime import re from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm class GrossHourlyIncidents(models.Model): hour = models.IntegerField() count = models.IntegerField() class IncidentManager(models.Manager): def create_incident(self): incident = self.create() # do something with the incident. return Incident class RawIncident(models.Model): datetime = models.DateTimeField(blank=True, null=True) payload = models.CharField(max_length=10000, blank=True, null=True) class Meta: unique_together = ["payload", "datetime"] ordering = ["datetime"] #The Unique Dispatch format for Ulster County, NY class UlsterIncident(models.Model): owner = models.ForeignKey(User) source = models.ForeignKey(RawIncident) Unit = models.CharField(max_length=200, blank=True) Venue = models.CharField(max_length=500, blank=True) Inc = models.CharField(max_length=600, blank=True) Loc = models.CharField(max_length=200, blank=True) lat = models.DecimalField(max_digits=50, decimal_places=1, null= True, blank=True) long = models.DecimalField(max_digits=50, decimal_places=1, null= True, blank=True) XSts = models.CharField(max_length=500, blank=True) Nature = models.CharField(max_length=400, blank=True) Common = models.CharField(max_length=200, blank=True) Addtl = models.CharField(max_length=200, blank=True) #zipcode= modelsIntegerField() dispatch_time = models.DateTimeField(blank=True, null=True) recieved_time = models.DateTimeField(blank=True, null=True) created_time = models.DateTimeField(auto_now_add =True) #weather_status = IntegerField() objects = IncidentManager() class Meta: ordering = ["dispatch_time"] <file_sep>from collections import Counter from datetime import datetime, timedelta import getpass, os, email, sys, gmail, dispatch_gmail, re, time, imaplib, string, pywapi import operator import unicodedata from TwitterAPI import TwitterAPI from chartit import DataPool, Chart from dispatch.models import UlsterIncident from dispatch.views import * from dispatch_gmail.models import IncidentEmail from dispatch_twitter.models import TwitterIncident from django.http import HttpResponse from django.shortcuts import render, redirect from django.shortcuts import render_to_response from django.template.context import RequestContext import json as simplejson from private import local_settings def get_twitter_incidents(twitter_username): ''' Gathers statuses from a twitter feed. We expect that the status of each status is a sting in dictionary format containing the details of a 911 incident. Using application only authentication from the private module's tokens, attempt to retrieve as many statuses from one public twitter user as possible, using the public Twitter REST API. Save each status to the database along with it's publish time.. ''' api = TwitterAPI(settings.TWITTER_TOKEN_1, settings.TWITTER_TOKEN_2, settings.TWITTER_TOKEN_3, settings.TWITTER_TOKEN_4) r = api.request('statuses/user_timeline', {'screen_name':'%s' % twitter_username, \ #We don't want anything except the statuses. 'exclude_replies':'true', \ # 3,200 is the TwitterAPI rate limit. 'count': '3200', \ #Further reduce our response size by excluding the user's metadata. 'trim_user': 'true', \ #Further reduce our response size by excluding other details 'contributor_details': 'false', \ #The ID of the oldest status to start importing from. #This defaults to the oldest possible if the maximum rate limit is reached. 'since_id': '' \ }) for status in r: received_datetime = datetime.strptime(status["created_at"], "%a %b %d %H:%M:%S +0000 %Y") payload = status["text"] raw_incident = RawIncident.objects.create(datetime = received_datetime, payload = payload) raw_incident.save() sys.stdout.write("Saved raw unicode twitter dispatch %s \r" % raw_incident.id) sys.stdout.flush() return payload, recieved_datetime, r <file_sep>#Configurable Settings LOCALE_STATE = 'NY' LOCALE_ZIP LOCALE_NOAA_STATION_CALL_SIGN INCIDENT_FIELDS = ( 'Unit', \ 'Venue', \ 'Inc', \ 'Nature', \ 'XSts', \ 'Common', \ 'Addtl', \ 'Loc', \ 'Date', \ 'Time', \ ) LOCATION_FIELDS = ['XSts', 'Loc', 'Venue'] DELINIATER = ':' <file_sep>Ubuntu / Debian: apt-get install libpq-dev python-dev build-essential <file_sep>twisted cryptography service_identity hendrix django psycopg2 django-chartit simplejson python-social-auth django-twitter-api <file_sep>from django.conf.urls import patterns, include, url from django.contrib import admin from dispatch_gmail import views from dispatch_twitter import views admin.autodiscover() urlpatterns = patterns('', #Django admin web interface url(r'^admin/', include(admin.site.urls)), #Authentication url(r'^/login/$', 'django.contrib.auth.views.login', {'template_name': 'plus/login.html'}), url('', include('social.apps.django_app.urls', namespace='social')), #Incident db population from gmail url(r'^import-email/', 'dispatch_gmail.views.import_email_incidents'), #url(r'^parse-gmail/', 'dispatch_gmail.views.parse_incident_emails'), #Incident db population from twitter url(r'^import-twitter/', 'dispatch_twitter.views.import_twitter_incidents'), #url(r'^parse-twitter/', 'dispatch_twitter.views.parse_twitter_incidents'), #Forward facing URLs url(r'^$', 'dispatch_gmail.views.dashboard', name='dashboard'), url(r'^incidents/', 'dispatch_gmail.views.gross_hourly_most_common'), )
a786b9ef0083940a579be6318973306ff8df8a15
[ "Python", "Text" ]
9
Python
jMyles/Dispatch.py
b70830f11e8d238bf121d9eb4e320c7ed3d551d4
4c4947d9e426d8e549c1a2a8fc8838443396fe76
refs/heads/master
<repo_name>vsliouniaev/scratchpad<file_sep>/package #! /bin/bash yarn zip -r scratchpad.zip icons/* src/* buttons/* manifest.json scratchpad.js<file_sep>/scratchpad.js function handleClick() { browser.tabs.create({ "url": "/src/index.html" }); } browser.browserAction.onClicked.addListener(handleClick);
3987b999cb9a436117511df3000ddf85c94ca424
[ "JavaScript", "Shell" ]
2
Shell
vsliouniaev/scratchpad
a21955fcb86b604bb576a60f61f190e3563c3b6b
52d4b1c59256c4db95fbd2d0313c4ff3af481585
refs/heads/master
<file_sep>package fubyaka5; public class AngryProfessor { static String angryProfessor(int k, int[] a) { int countN = 0; for (int i = 0; i < a.length; i++) { if(a[i] <= 0) { countN++; } } if(countN >= k) { return "NO"; } else { return "YES"; } } } <file_sep>import fubyaka2.StringOne; import fubyaka3.Authentification; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestAutentification { @Test public void testCorrect() { boolean result = Authentification.logIn("pupil", "pupil"); assertEquals(true, result); } @Test public void testInCorrect() { boolean result = Authentification.logIn("pul", "pupil"); assertEquals(false, result); } } <file_sep>package fubyaka4.TextAnalyse; public interface Analyzer { boolean analyse(String text); } <file_sep>package fubyaka2; import java.util.Scanner; public class Laboratory { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double leng = sc.nextDouble(); double e = sc.nextDouble(); double meazure = -1; while(meazure != 0) { meazure = sc.nextDouble(); if(meazure < leng - e || meazure > leng + e) { System.out.println("You are stupid. NO!"); } else { System.out.println("Good."); } } } } <file_sep>package fubyaka6.CRUD; import java.util.*; public class UserService { private Map<String, User> users; public UserService() { users = FileHelper.readFromFile("src\\main\\java\\fubyaka6\\CRUD\\users"); users.put("admin", new User("admin", "admin", "<PASSWORD>")); } public void savToData() { FileHelper.saveToFile("src\\main\\java\\fubyaka6\\CRUD\\users", users); } public boolean addUsers(User user) { if(!(users.containsKey(user.getLogin()))) { users.put(user.getLogin(), user); return true; } else { return false; } } public User getByLogin (String login){ if(users.containsKey(login)) { System.out.println(users.get(login)); } return users.get(login); } public boolean deleteByLogin(String login){ if(users.containsKey(login)) { users.remove(login); return true; } else { return false; } } public List<User> getAllUsers() { System.out.println(users.values()); return new ArrayList<>(users.values()); } public boolean editUser(User user) { if(users.containsKey(user.getLogin())) { users.put(user.getLogin(), user); return true; } else { return false; } } public boolean auth(String login, String password) { if(users.containsKey(login)) { if(users.get(login).getPassword().equals(password)) { return true; } else { return false; } } else { return false; } } } <file_sep>package fubyaka6; import fubyaka6.CRUD.User; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; public class UserList { public static void main(String[] args) { List<User> userList = new ArrayList<>(); try(FileReader reader = new FileReader("src\\main\\resource\\users")) { //BufferedReader bufferedReader = new BufferedReader(reader); Scanner sc = new Scanner(reader); while (sc.hasNext()) { String login = sc.next(); String password = sc.next(); String name = sc.next(); User user = new User(login, password, name); userList.add(user); } } catch (IOException e) { System.err.println("Ошибка при чтении файла. " + e.getMessage()); } catch (NoSuchElementException e) { System.err.println("Неверный формат данных " + e.getMessage()); } for (User x : userList) { System.out.println(x); } } } <file_sep>package fubyaka4.TextAnalyse; import java.util.Scanner; public class AnalyzerRun { public static void main(String[] args) { Analyzer[] analyzers = new Analyzer[3]; analyzers[0] = new LengthAnalyser(200); analyzers[1] = new SpamAnalyse(new String[]{"кредит", "микрозайм"}); analyzers[2] = new SwearAnalyse(); Scanner sc = new Scanner(System.in); String text = sc.nextLine(); boolean[] mas = new boolean[3]; for (int i = 0; i < analyzers.length; i++) { System.out.println(analyzers[i].analyse(text)); mas[i] = analyzers[i].analyse(text); } if(mas[0] == true && mas[1] == true && mas[2] == true) { System.out.println("Проходит."); } else { System.out.println("Не проходит. БАН!"); } } } <file_sep>import fubyaka6.CRUD.FileHelper; import fubyaka6.CRUD.User; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestFileHelper { //@Test //public void testWriter() { // Map<String, User> map = new HashMap<>(); // map.put("Tolya", new User("Tolya", "qwe", "dfg")); // FileHelper.saveToFile("src\\main\\resource\\numbers.txt", map); //} @Test public void testReader() { Map<String, User> map = FileHelper.readFromFile("src\\main\\resource\\users"); int result = map.size(); assertEquals(3, result); } } <file_sep>package fubyaka4.oopbasic; public class Scenario { public static void main(String[] args) { Student st = new Student("Vitalya", 16, 10); Teacher tc = new Teacher("Valera", "Math", 56); tc.teach(st); Polite[] people = new Polite[5]; people[0] = new Student("Alex", 111, 112); people[1] = new Student("George", 17, 11); people[2] = st; people[3] = new Teacher("Owen", "Science", 234); people[4] = tc; for (int i = 0; i < people.length; i++) { people[i].goodBye(); } } } <file_sep>import fubyaka3.ChangeWord; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestChangeWord { @Test public void TestCorrect() { String result = ChangeWord.changeWord("I love dogs. love love love love"); assertEquals("I *** dogs. *** *** *** ***", result); } } <file_sep>package fubyaka4.TextAnalyse; public class SwearAnalyse extends KeyWordAnalyser { public SwearAnalyse() { keyWords = new String[]{"fuck", "fucking", "bitch", "swag", "mor"}; } } <file_sep>package fubyaka1; import java.util.Scanner; public class Fountain { public static void main(String[] args) { int money = 0; int money2; int mostMoney = 0; Scanner sc = new Scanner(System.in); while (true) { System.out.print("Monetka nominalom "); money2 = sc.nextInt(); if (money2 == 1 || money2 == 2 || money2 == 5 || money2 == 10) { money += money2; if(mostMoney < money2) { mostMoney = money2; } } else { System.out.println("Tvoya most expensiv monetka - "+ mostMoney); System.out.println("Ti sobral - "+ money); System.out.println("Itog: ti bomj."); System.exit(0); } } } } <file_sep>package fubyaka4.oopbasic; public class Student extends Human implements Polite { private int form; public Student(String name, int age, int form) { super(name, age); this.form = form; } public void sayHello(){ System.out.println("Привет, <NAME> " + this.name); } public String getName() { return name; } public int getAge() { return age; } public int getForm() { return form; } @Override public void goodBye() { System.out.println("До свидания."); } } <file_sep>package fubyaka5; public class ArrSum { static int simpleArraySum(int[] ar) { int sumArr = 0; for (int i = 0; i < ar.length; i++) { sumArr += ar[i]; } return sumArr; } } <file_sep>package fubyaka5; public class SolveMeFirst { static int solveMeFirst(int a, int b) { return a+b+1; } } <file_sep>import fubyaka2.StringOne; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestStringOne { @Test public void TestCorrect() { int result = StringOne.countZnak("Сфтя! Сотку верни! Живо!!! ЪУЪ!"); assertEquals(6, result); } } <file_sep>package fubyaka5; public class Circulus { static int[] circularArrayRotation(int[] a, int k, int[] queries) { int[] mas = new int[a.length]; for (int i = 0; i < k; i++) { mas[i] = a[i + k]; } for (int i = k; i < a.length; i++) { mas[i] = a[i - k]; } return mas; } }
c247283c8aea215e6dcc9d1163fdd965f6056800
[ "Java" ]
17
Java
DambldorDied/SampleProject
4bb2400b5519c2c2fecde1d8badf47cb43c69b92
ab8be2b34b3a91ec166548fb71c3ab491bd7c4a3
refs/heads/master
<repo_name>KirtanKapadia/Two-User-Chat-App<file_sep>/app/src/main/java/com/example/android/meandyou/MainActivity.java package com.example.android.meandyou; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.parse.LogInCallback; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; public class MainActivity extends AppCompatActivity { EditText username; EditText password; public void UsersToChat(){ Intent intent = new Intent(getApplicationContext(), userListActivity.class); startActivity(intent); } public void signUp(View view){ if(username.getText().toString().equals("") || password.getText().toString().equals("")){ Toast.makeText(this, "Username and Password is required!!", Toast.LENGTH_SHORT); }else { ParseUser parseUser = new ParseUser(); parseUser.setUsername(username.getText().toString()); parseUser.setPassword(password.getText().toString()); parseUser.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if(e == null){ Log.i("Sign Up", "Successful "); UsersToChat(); } else{ Toast.makeText(MainActivity.this, e.getMessage(),Toast.LENGTH_SHORT); } } }); } } public void logIn(View view){ ParseUser.logInInBackground(username.getText().toString(), password.getText().toString(), new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if(user != null && e !=null){ Log.i("Log In", "Successful"); UsersToChat(); } else { Toast.makeText(MainActivity.this, e.getMessage(),Toast.LENGTH_SHORT); } } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username = findViewById(R.id.usernameEditText); password = findViewById(R.id.passwordEditText); username.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { username.setCursorVisible(true); } }); password.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { password.setCursorVisible(true); } }); } }
93cd5967a304e4315b706329ca625e60fbedfb31
[ "Java" ]
1
Java
KirtanKapadia/Two-User-Chat-App
8fd7a92bcaa10f20055e5112f5a496b710102847
0b2be43b20931f4a9e4f69585ceeb2308d196caf
refs/heads/master
<file_sep>package com.xander.user.controller; import com.xander.entities.CommonResult; import com.xander.entities.WechatInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; /** * Description: * * @author Xander * datetime: 2021-05-14 16:39 */ @RestController @RequestMapping("/user") public class UserController { private Logger logger = LoggerFactory.getLogger(this.getClass()); public static final String WECHAT_SERVICE = "wechatService"; @Autowired private DiscoveryClient discoveryClient; @Autowired private RestTemplate restTemplate; @GetMapping(value = "/wechatInfo/{userId}") public CommonResult<WechatInfo> wechatInfo(@PathVariable("userId") Long userId) { List<ServiceInstance> instances = this.discoveryClient.getInstances(WECHAT_SERVICE); // 打印服务实例信息 for (ServiceInstance instance : instances) { this.logger.info("serviceId: " + instance.getServiceId() + "\t" + "host: " + instance.getHost() + "\t" + "port: " + instance.getPort() + "\t" + "uri: " + instance.getUri()); } return this.restTemplate.getForObject("http://" + WECHAT_SERVICE + "/wechat/getByUserId/" + userId, CommonResult.class); } } <file_sep>package com.xander.gateway.filters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; /** * Description: 不管请求路径是什么,固定转发路径为 /payment/get/2 的Filter * * @author Xander * datetime: 2021-03-23 20:45 */ @Component public class FixedPathGateWayFilter extends AbstractGatewayFilterFactory { Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public GatewayFilter apply(Object config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); logger.info("请求路径:"+request.getURI().getPath()); //新建 ServerHttpRequest 实例,固定转发路径为 /payment/get/2 ServerHttpRequest newRequest = request.mutate().path("/payment/get/2").build(); //重新build exchange exchange = exchange.mutate().request(newRequest).build(); logger.info("固定后路径:"+exchange.getRequest().getURI().getPath()); return chain.filter(exchange); }; } } <file_sep>package com.xander.wechat.controller; import com.xander.entities.CommonResult; import com.xander.entities.WechatInfo; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Description: * * @author Xander * datetime: 2021-05-10 22:47 */ @RestController @RequestMapping("/wechat") public class WechatController { @Value("${server.port}") private String serverPort; @GetMapping(value = "/getByUserId/{userId}") public CommonResult<WechatInfo> getByUserId(@PathVariable("userId") Long userId) { WechatInfo wechatInfo = WechatInfo.newInstance().setOpenId(userId + "-openId").setUserName(userId + "-name"); return CommonResult.newInstance().setCode(200).setMessage("查询成功,serverPort:" + serverPort).setData(wechatInfo); } } <file_sep>package com.xander.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Description: * * @author Xander * datetime: 2021-05-14 16:34 */ @SpringBootApplication @EnableDiscoveryClient public class ConsumerZkUser8101 { public static void main(String[] args) { SpringApplication.run(ConsumerZkUser8101.class, args); } } <file_sep>package com.xander.entities; import java.io.Serializable; public class Payment{ private Long id; private String serial; public static Payment newInstance() { Payment instance = new Payment(); return instance; } public Long getId() { return id; } public Payment setId(Long id) { this.id = id; return this; } public String getSerial() { return serial; } public Payment setSerial(String serial) { this.serial = serial; return this; } } <file_sep>package com.xander.payment9001; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * Description: * * @author Xander * datetime: 2021-05-10 22:45 */ @SpringBootApplication @EnableEurekaClient public class ProviderPayment9001 { public static void main(String[] args) { SpringApplication.run(ProviderPayment9001.class, args); } } <file_sep>package com.xander.gateway.filters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; /** * Description: 全局GlobalFilter,打印日志 * * @author Xander * datetime: 2020-10-22 16:20 */ @Component public class LogGlobalFilter implements GlobalFilter, Ordered { Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); // 打印请求uri logger.info("全局过滤器LogGlobeFilter开始:" + request.getURI().getPath()); Mono<Void> mono = chain.filter(exchange); logger.info("全局过滤器LogGlobeFilter结束:" + request.getURI().getPath()); return mono; } @Override public int getOrder() { // order: 加载顺序,数值越小,优先级越高 return 0; } } <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> <groupId>com.xander</groupId> <artifactId>006SpringCloud</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>eureka-server-7001</module> <module>eureka-server-7002</module> <module>common-api</module> <module>provider-payment9001</module> <module>provider-payment9002</module> <module>consumer-order8001</module> <module>provider-zk-wechat9101</module> <module>provider-zk-wechat9102</module> <module>consumer-zk-user8101</module> <module>consumer-openFeign-order8002</module> <module>gateway-6001</module> <module>provider-naocs-8070</module> <module>consumer-nacos-8080</module> <module>provider-naocs-8071</module> </modules> <packaging>pom</packaging> <!-- 统一管理jar包版本 --> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <!-- 子模块继承之后,提供作用:锁定版本+子modlue不用写groupId和version --> <dependencyManagement> <dependencies> <!--spring boot 2.3.3--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.3.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud Hoxton.SR8--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR8</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud alibaba 2.2.1.RELEASE--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.2.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <!-- fork: Spring-boot-devtools 热部署如果没有配置该项配置,devtools不会起作用的,即应用不会restart --> <configuration> <fork>true</fork> <addResources>true</addResources> </configuration> </plugin> </plugins> </build> </project><file_sep>package com.xander.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Description: 启动类 * * @author Xander * datetime: 2021-05-31 15:50 */ @SpringBootApplication @EnableDiscoveryClient public class Gateway6001 { public static void main(String[] args) { SpringApplication.run(Gateway6001.class, args); } } <file_sep>package com.springcloud.alibaba.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; /** * Description: * * @author Xander * datetime: 2021-06-08 17:45 */ @RestController public class ConsumerController { @Autowired public RestTemplate restTemplate; @GetMapping("/consumer/echo/{msg}") public String callEcho(@PathVariable String msg) { // 访问应用 service-provider 的 REST "/echo/{msg}" return this.restTemplate.getForObject("http://service-provider/echo/" + msg, String.class); } } <file_sep>package com.xander.order.service; import com.xander.entities.CommonResult; import com.xander.entities.Payment; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; /** * Description: paymentService微服务的 OpenFeign 接口 * * @author Xander * datetime: 2021-05-21 10:00 */ @FeignClient(value = "paymentService",fallback = PaymentOpenFeignServiceFallback.class) public interface PaymentOpenFeignService { @GetMapping(value = "/payment/get/{id}") CommonResult<Payment> getPaymentById(@PathVariable("id") String id); /** * 模拟请求超时 * * @return */ @GetMapping(value = "/payment/timeout") CommonResult<Payment> timeout(); /** * 模拟请求异常 * * @return */ @GetMapping(value = "/payment/excep") CommonResult<Payment> excep(); } <file_sep>package com.xander.wechat; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Description: * * @author Xander * datetime: 2021-05-10 22:45 */ @SpringBootApplication @EnableDiscoveryClient public class ProviderZkWechat9101 { public static void main(String[] args) { SpringApplication.run(ProviderZkWechat9101.class, args); } } <file_sep>package com.xander.wechat; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * Description: * * @author Xander * datetime: 2021-05-10 22:45 */ @SpringBootApplication @EnableDiscoveryClient public class ProviderZkWechat9102 { public static void main(String[] args) { SpringApplication.run(ProviderZkWechat9102.class, args); } }
e1a4ad9ba3cf46039a6ba4c0bb969a9a9ec46709
[ "Java", "Maven POM" ]
13
Java
wengxingxia/006SpringCloud
667bd10454ac14c29452a5fa3019796052cf870d
7f37f6638ebd8b047f241925b238e49e5a6dbf12
refs/heads/master
<repo_name>claraj/lorenz<file_sep>/equations.c #include <stdio.h> //this is not how you do string?? freeing memory? arguments helpful here :)! //todo chart plot library double P = 10; double R = 28; double B = 8.0/3.0; double dt = 0.01; int its = 5000; void writeFile(double x, double y , double z) { FILE *fp; char filename [150]; int len = sprintf(filename, "points-%d-%f-%f-%f.csv", its, x, y, z); fp = fopen(filename, "w+"); fputs("x,y,z\n", fp); for ( int t = 1 ; t < its ; t++) { //printf("%f", t); //dt is 1 so double dx = P * (y - x); double dy = (x * (R - z) ) - y; double dz = (x*y) - (B*z); x = x + ( dx * dt); y = y + ( dy * dt); z = z + ( dz * dt); char points [150]; int len = sprintf(points, "%f,%f,%f\n", x, y, z); //printf(points); fputs(points, fp); //fputs("bloop", fp); } fclose(fp); } int main() { /* Lorenz attractor dx/dt = P(y-x) dy/dt = Rx - y - xz dz/dt = xy - Bz */ // double x=0.1; // double y = 0; // double z = 0; writeFile(0.1, 0, 0); writeFile(0.10001, 0, 0); return 0; } <file_sep>/README.md # lorenz V2: Do all the math in JS and draw with Three.js. Live here: https://minneapolis-edu.github.io/lorenz/ V1: Lorenz attractor. Generate points in C and draw in JS with plotly. Hacky hacky code, pretty output! Running code locally - serve from a file server and needs a local copy of Ploty. Edit JS to use CDN version. Start a Python server to serve files from current dir by running python -m SimpleHTTPServer ![my image](/examplechart.png?raw=true)
33849129ddd6cd7b41e3a5065471f0ba80e1a7b8
[ "Markdown", "C" ]
2
C
claraj/lorenz
a5ae94af89c8868179f32e49ac2e797d09b9056e
df5bd9cbf76d371a23c89983133408de39088668
refs/heads/master
<repo_name>William3Johnson/pfam-dom-draw<file_sep>/pfam-dom-draw.js jQuery.browser = {}; (function () { jQuery.browser.msie = false; jQuery.browser.version = 0; if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) { jQuery.browser.msie = true; jQuery.browser.version = RegExp.$1; } })(); function getRGBComponents(color) { var r = color.substring(1, 3); var g = color.substring(3, 5); var b = color.substring(5, 7); return { R: parseInt(r, 16), G: parseInt(g, 16), B: parseInt(b, 16) }; } function idealTextColor(bgColor) { var nThreshold = 146; // 105 was the original var components = getRGBComponents(bgColor); var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114); return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff"; } function create_paper(id, length, scale, up, gene){ var scaled_length = parseInt(parseInt(length)/parseInt(scale)); paperlength = parseInt(scaled_length) + 20; var paper = Raphael(id, paperlength, 43); paper.setViewBox(0,0,paperlength,43); paper.canvas.setAttribute('preserveAspectRatio', 'xMidYMid meet'); //line is constant var line = paper.rect(10, 18, parseInt(scaled_length), 5, 2.5).attr({ fill: 'grey', stroke: 'none' }); if(gene){ var geneSize = (gene.length + 8) * 3; var geneText = paper.text(geneSize, 2, 'Gene: '+gene+',').attr({ 'fill': '#000', 'font-size': 10, 'cursor': 'pointer' }); geneText.node.setAttribute("class",gene+"-text"); $('.'+gene+"-text").click(function(){ document.location.href='http://www.genenames.org/cgi-bin/gene_symbol_report?match='+gene; }); var upSize = (up.length + 5) * 3; var upText = paper.text(upSize + (geneSize *2), 2, 'UniProt: '+up).attr({ 'fill': '#000', 'font-size': 10, 'cursor': 'pointer' }); upText.node.id = up+"-text"; $('#'+up+"-text").click(function(){ document.location.href='http://www.uniprot.org/uniprot/'+up; }); } else { var upSize = (up.length + 8) * 3; var upText = paper.text(upSize, 2, 'UniProt: '+up).attr({ 'fill': '#000', 'font-size': 10, 'cursor': 'pointer' }); upText.node.id = up+"-text"; $('#'+up+"-text").click(function(){ document.location.href='http://www.uniprot.org/uniprot/'+up; }); } paper.text(parseInt(scaled_length) - 25, 36, length + ' amino acids').attr({ 'fill': '#000', 'font-size': 10 }); line.node.id = 'line'; return paper; } function create_dom(paper, region, id, scale){ var start = parseInt((parseInt(region.start)/parseInt(scale)) + 9); var end = parseInt((parseInt(region.end)/parseInt(scale)) + 9); var length = end - start; var dom = paper.rect( start, //start position X 10.5, //start position Y constant length, //length 20, //width constant 10 //radius of curve constant ).attr({ fill: '90-#ffffff-'+region.colour+':50-#ffffff', stroke: region.colour,//'none', cursor: 'pointer' }); var text_len = region.text.length * 9; if(length > text_len + 2){ var textstart = parseInt((length/2) + start); var textcol = idealTextColor(region.colour); var text = paper.text(textstart, 20, region.text).attr({ 'fill': textcol, 'font-size': 10, 'cursor': 'pointer' }); text.node.id = id+'text'; $('#'+id+'text' ).qtip({ content: '<strong>'+region.text + '</strong>: ' + region.metadata.description + ' [Pfam:' + region.metadata.accession + ']', style: { width: 200, padding: 5, background: '#F1F5F8', color: '#003366', textAlign: 'center', border: { width: 1, radius: 3, color: '#003366' }, tip: 'bottomMiddle', }, position: { target: 'mouse', corner: { tooltip: 'bottomMiddle' } } }); $('#'+id+'text').click(function(){ document.location.href='http://pfam.xfam.org'+region.href; }); } dom.node.setAttribute('id',id); $('#'+id).qtip({ content: '<strong>'+region.text + '</strong>: ' + region.metadata.description + ' [Pfam:' + region.metadata.accession + ']', style: { width: 200, padding: 5, background: '#F1F5F8', color: '#003366', textAlign: 'center', border: { width: 1, radius: 3, color: '#003366' }, tip: 'bottomMiddle', }, position: { target: 'mouse', corner: { tooltip: 'bottomMiddle' } } }); $('#'+id).click(function(){ document.location.href='http://pfam.xfam.org'+region.href; }); return dom; } function draw_protein(settings, container, i, up, gene){ var drawID = 'draw'+i; $('<div>').attr({id: drawID}).css({overflow: 'auto'}).appendTo($(container)); $('<div>').attr({id: 'spinner'+i}).css({margin: '0 auto', width: '10%'}).appendTo($('#'+drawID)); $("#spinner"+i).spinner({dashes: 120, innerRadius: 10, outerRadius: 15, color: settings.spinnerColor}); // 'http://pfam.xfam.org/protein/' + up + '/graphic' var jqxhr = $.getJSON('http://www.genenames.org/cgi-bin/ajax/pfam_dom_ajax?up='+up, function(data) { var tot_len; $.each(data, function(index, prot) { var length = parseInt(prot.length); var scale = 1; if(length > 896){ if(length/896 >= 1.5) scale = 2; //length = parseInt(length/scale); } var paper = create_paper(drawID, length, scale, up, gene); var regions = prot.regions; for (var domI in regions) { create_dom(paper, regions[domI], 'dom'+i+'-'+domI, scale); } length = parseInt(length/scale); tot_len = length+20; $('div#'+drawID+' svg').attr('width', tot_len); $('div#'+drawID+' svg').attr('height', 48); if(tot_len < 930){ $('#'+drawID).css({width: tot_len, height: 58}); } $("#spinner"+i).remove(); }); if(tot_len < 930){ $('#'+drawID).css('overflow', 'hidden'); } }).fail(function( jqxhr, textStatus, error ) { var err = textStatus + ", " + error; console.warn( "Pfam request Failed: " + err ); $("#spinner"+i).remove(); $('#'+drawID).append('<p style="text-align:center; color: red; font-family:monospace">Error fetching Pfam data</p>'); }); $('#'+drawID).css({ height: '60px' }); } function checkSettings(settings){ var settings = (typeof settings === 'undefined') ? {} : settings; settings.spinnerColor = settings.spinnerColor ? settings.spinnerColor : '#000'; return settings; } function pfam_doms(settings){ settings = checkSettings(settings); var IE = { Version: function() { var version = 999; // we assume a sane browser if (navigator.appVersion.indexOf("MSIE") != -1){ // bah, IE again, lets downgrade version number version = parseFloat(navigator.appVersion.split("MSIE")[1]); } return version; } }; if (IE.Version() > 7) { $('.pfamDomDrawContainer').each(function(index, container) { var uniprot = $(container).attr('data-uniprot'); var gene = $(container).attr('data-gene'); $(container).toggleClass('nodia dia'); draw_protein(settings, container, index, uniprot, gene); }); } else{ $('#drawContainer').remove(); console.warn("Code does not support IE < 8"); } }<file_sep>/README.md # pfam-dom-draw ## Introduction Takes a HGNC approved symbol and a UniProt accession from the data-gene and data-uniprot attributes within a div tag and creates a diagram representing the UniProt protein with pfam domains mapped on to the protein. **For a live demo visit http://hgnc.github.io/pfam-dom-draw/** ## Install To install europe-pmcentralizer the easiest way would be to install [bower](http://bower.io) as described in the bower documentation and then simply run the following in your js directory: ```sh $ bower install git://github.com/HGNC/pfam-dom-draw.git ``` ## Dependencies Javascript dependencies: - [jQuery ~2.1.4](https://github.com/jquery/jquery) - [Raphael ~2.1.4](https://github.com/DmitryBaranovskiy/raphael) - [jquery.raphael.spinner](https://github.com/hunterae/jquery.raphael.spinner) - [qTip 1.0.0](https://github.com/taballa/qTip) Web service: - [Pfam](http://pfam.xfam.org/help#tabview=tab10) - [HGNC wrapper for pfam REST](http://www.genenames.org/cgi-bin/ajax/pfam_dom_ajax?up=P60709) ## Usage Simply add a `<div class='pfamDomDrawContainer'>` anywhere in your `<body>` and add the attributes `data-uniprot=""` and `data-gene=""`(optional) to the div tag with the UniProt accession within data-uniprot and a HGNC approved gene symbol within the data-gene. Multiple pfamDomDrawContainer divs can be added to the page: ```html <div class="pfamDomDrawContainer" data-uniprot="Q9H0C5" data-gene="BTBD1"></div> ``` Then at the bottom of the `<body>` add your javascript dependencies: ```html <script type="text/javascript" src="/js/bower_components/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="/js/bower_components/raphael/raphael-min.js"></script> <script type="text/javascript" src="/js/bower_components/jquery.raphael.spinner/jquery.raphael.spinner.js"></script> <script type="text/javascript" src="js/bower_components/qTip/jquery.qtip.min.js"></script> <script type="text/javascript" src="/js/bower_components/pfam-dom-draw/pfam-dom-draw.js"></script> ``` Finally call the `pfam_doms()` function beneth the script dependencies: ```html <script type="text/javascript"> $(document).ready(function(){ pfam_doms({ spinnerColor: '#999' }); }); </script> ``` The function has one settings that you can pass (spinnerColor) as shown above. The spinnerColor is the colour you want the loading spinner to be (default: #000). The resulting graphic will show a stylised diagram of a protein with the pfam domains. Hovering over a domain will create a tooltip which offers more information about the domain. Clicking on the domain will take you to pfam.xfam.org for that particular domain. You can also click on the UniProt text above the protein which will navigate you to the UniProt page for the protein. If a gene symbol was added also the gene symbol will appear before the UniProt accession and will navigate you to the HGNC symbol report for the gene if clicked. ![successful result](https://cloud.githubusercontent.com/assets/9589542/11808629/78fd8876-a319-11e5-8e11-d9945f3409db.png) ##Acknowledgements Many thanks to the Pfam developers for providing a very useful REST webservice which this javascript code uses. Information about the Pfam REST API can be found at http://pfam.xfam.org/help#tabview=tab10.
6098f7db7b06dbb47cfb43335b1b5748b22ef8f7
[ "JavaScript", "Markdown" ]
2
JavaScript
William3Johnson/pfam-dom-draw
7b826d803eec1d1aac6877ab8b07ef63380cb324
ee5243621d96290b3195dd78650c33f30372d06c
refs/heads/master
<repo_name>kimsterl337/Music<file_sep>/music.js const axios = require('axios'); const cheerio = require('cheerio'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); let date = ''; const url = 'https://www.billboard.com/charts/hot-100/'; async function getTitles(date) { html = await axios.get(url + date).then((response) => response.data); const $ = cheerio.load(html); const musicInformation = $('.chart-element__information') .map((index, element) => { nameOfSong = $(element).find('.chart-element__information__song').text(); nameOfArtist = $(element).find('.chart-element__information__artist').text(); return { nameOfArtist, nameOfSong }; }) .get(); return musicInformation; } app.get('/tracks', function(req, res) { res.sendFile(__dirname + '/index.html'); }); app.post('/date', function(req, res) { date = req.body.date; res.redirect('/'); }); app.get('/', async (req, res) => { try { console.log(date); const musicTitles = await getTitles(date); return res.status(200).json({ result: musicTitles }); } catch (err) { return res.status(500).json({ err: err.toString() }); } }); app.listen(3000, () => { console.log('running on port 3000'); });
eb9d7032e62d8766f11515252f8cfab79fc48e6c
[ "JavaScript" ]
1
JavaScript
kimsterl337/Music
81ab3801c3c44dc31454154b76091f2e17214263
21a7a43af3562b2c4ad86174842ba27e774806b4
refs/heads/master
<file_sep>from Crypto.Cipher import AES from Crypto import Random class AESCipher(object): def __init__(self, key): self.key = key def encrypt(self, raw): cipher = AES.new(self.key, AES.MODE_ECB) if len(raw) % 16 != 0: raw += ' ' * (16 - (len(raw) % 16)) return cipher.encrypt(raw) def decrypt(self, enc): cipher = AES.new(self.key, AES.MODE_ECB) return cipher.decrypt(enc) <file_sep># Written by <NAME>, maintained by <EMAIL> import Crypto import ast import os import argparse import socket import sys from aes import * from rsa import * from Crypto.Util.number import * def getSessionKey(rsa, cipher): """ Get the AES session key by decrypting the RSA ciphertext """ try: AESEncrypted = cipher[:128] AESKey = rsa.decrypt(AESEncrypted) return AESKey[(len(AESKey)-16):] except: return False def myDecrypt(rsa, cipher): """ Decrypt the client message: AES key encrypted by the public RSA key of the server + message encrypted by the AES key """ try: messageEncrypted = cipher[128:] AESKey = getSessionKey(rsa, cipher) print "aes len: ", len(AESKey) aes = AESCipher(AESKey) print "AES ", bytes_to_long(aes.key) return aes.decrypt(messageEncrypted) except: return False # Parse Command-Line Arguments parser = argparse.ArgumentParser() parser.add_argument("-ip", "--ipaddress") parser.add_argument("-p", "--port") args = parser.parse_args() # Create TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind socket to port server_address = (args.ipaddress, int(args.port)) print >>sys.stderr, 'Starting up on: %s port %s' % server_address sock.bind(server_address) # Listen for incoming connections sock.listen(10) rsa = RSACipher() file_ob = open('server.txt', "a") file_ob.write("started\n") while True: print >>sys.stderr, 'Waiting for a connection...' # Wait for a conneciton connection, client_address = sock.accept() try: print >>sys.stderr, 'Connection from:', client_address # Receive the data cipher = connection.recv(1024) print("Message Received...") file_ob.write("message received\n") message = myDecrypt(rsa, cipher) file_ob.write(message + "\n") if message: file_ob.write("Successfully decrypted message" + message + "\n") print "decrypted successfully!" print message aes = AESCipher(getSessionKey(rsa, cipher)) msg = aes.encrypt(message.upper()) connection.sendall(msg) else: file_ob.write("coudln't decrypt" + "\n") connection.sendall("Couldn't decrypt!") file_ob.flush() finally: # Clean up the connection connection.close() <file_sep> ## FILES rsa-aes-client.py: The client that creates an encrypted message using RSA and AES and sends it to the server rsa-aes-server.py: The server that listens for connections and recieves messages from the client and decrypts them and returns the same message (only all letters in upper case) to the client. aes.py: A class that implements AES encrption using python libraries. rsa.py: A class that implements RSA encrption using python libraries. serverPrivateKey.pem: The private key of the server. This will be autogenerated the first time you run the server, and will be different from the server used for the class. serverPublicKey: The public key of the server, also autogenerated. ============================================= ## HOW TO RUN 1. sudo python rsa-aes-server.py -ip 127.0.0.1 -p 1000 2. In another terminal: python rsa-aes-client.py -ip 127.0.0.1 -p 1000 --message "This is an example" ============================================= <file_sep>import argparse import socket import sys import os import time from aes import * from Crypto.PublicKey import RSA from Crypto.Util.number import * from random import randint # Handle command-line arguments parser = argparse.ArgumentParser() parser.add_argument("-ip", "--ipaddress", help='ip address where the server is running', required=True) parser.add_argument("-p", "--port", help='port where the server is listening on', required=True) parser.add_argument("-m", "--message", help='message to send to the server', required=True) args = parser.parse_args() # load server's public key serverPublicKeyFileName = "yubaPubKey" f = open(serverPublicKeyFileName,'r') RSAPubKey = RSA.importKey(f.read()) MESSAGE_LENGTH = 1024 def getConnection(): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = (args.ipaddress, int(args.port)) sock.connect(server_address) return sock def toggleFirstBit(key): print "Bit Flipped" print "Old Key", key if key >= 2**127: key -= 2**127 else: key += 2**127 print "New Key", key return key """ - RSA can encrypt plaintext of limited size(128 bytes), that's why generally keys are encrypted and not plaintext - That's why encrypted output would always be of size 128 bytes(1 Mb) """ def shiftRSACipher(cipher, key, bits): new_cipher = (bytes_to_long(cipher) * ((2**(bits * key.e)) % key.n)) % key.n return long_to_bytes(new_cipher, 128) """ - AES block size is 128bits(16 bytes | 16 char of the message) - Hence, encrypted message length would always be int(m/16)*16 + (m%16)? 16:0 - Therefore, that's the length of data returned from server is expected to be above length """ def sendPayload(payload): conn = getConnection() conn.sendall(payload) response = "" while 1: data = conn.recv(MESSAGE_LENGTH) if not data: break print "Data received length:", len(data) response += data conn.close() return response AESKey = 2**127 #AESKey = 145539436623726128093418598823574531036 file_ob = open('cipher.txt', "r") content = file_ob.read() cipher = content[:256].strip() cipher = long_to_bytes(int(cipher, 16), 128) encryptedMessage = content[256:].strip() encryptedMessage = long_to_bytes(int(encryptedMessage, 16)) file_ob.close() for i in reversed(range(0, 128)): print "#################### Bit Shifted by", i, "####################" if i != 127: AESKey = AESKey >> 1 print "AES Key: ", AESKey aes = AESCipher(long_to_bytes(AESKey, 16)) payload = shiftRSACipher(cipher, RSAPubKey, i) message = "Hello World!" + str(randint(0, 9)) print "Message Sent: ", message payload += aes.encrypt(message) response = sendPayload(payload) print "Response: ", aes.decrypt(response) if aes.decrypt(response).strip() != message.upper().strip(): AESKey = toggleFirstBit(AESKey) time.sleep(5) aes = AESCipher(long_to_bytes(AESKey, 16)) print "Decrypted Message: ", aes.decrypt(encryptedMessage) <file_sep>from Crypto.PublicKey import RSA class RSACipher(): def __init__(self): """ Generate a RSA key pair for server """ publicKeyFileName = "serverPublicKey" privateKeyFileName = "serverPrivateKey.pem" try: f = open(privateKeyFileName, 'rb') self.keys = RSA.importKey(f.read()) except: self.keys = RSA.generate(1024) self.publickey = self.keys.publickey() # export public and private keys privHandle = open(privateKeyFileName, 'wb') privHandle.write(self.keys.exportKey('PEM')) privHandle.close() pubHandle = open(publicKeyFileName, 'wb') pubHandle.write(self.keys.publickey().exportKey()) pubHandle.close() self.publickey = self.keys.publickey() def get_n(self): """ Returns the public RSA modulus. """ return self.keys.n def get_e(self): """ Returns the public RSA exponent. """ return self.keys.e def get_k(self): """ Returns the length of the RSA modulus in bytes. """ return (self.keys.size() + 1) // 8 def decrypt(self, ciphertext): """- Decrypt a ciphertext """ return self.keys.decrypt(ciphertext) def encrypt(self, message): """ Encrypt a message """ return self.publickey.encrypt(message, 32)
54514c2b8053cf9650985b24a9ad4680ee8ce67f
[ "Python", "Text" ]
5
Python
kirarpit/rsa-padding-oracle-attack
1358758aa0826284810d0be5e57f20cc1f4c80e8
55e500a9ad1768e42500a5f88c6d14c3f895de14
refs/heads/main
<file_sep>import React, { useContext, useState, useEffect } from 'react' import { useHistory } from 'react-router-dom' import axios from 'axios' import { Paper, Typography, Button, Grid, makeStyles, TextField, Slider, FormGroup, } from '@material-ui/core' import Autocomplete from '@material-ui/lab/Autocomplete' import { Context as PitchContext } from '../contexts/PitchContext' // API KEY - <KEY> const BASE_URL = 'https://www.googleapis.com/books/v1/volumes?q=' const useStyles = makeStyles({ paper: { flex: 1, padding: '20px 40px', }, titleContainer: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingBottom: '20px', }, formGroup: { paddingBottom: 20, maxWidth: '600px', }, }) const CreateForm = () => { const classes = useStyles() const history = useHistory() const { addPitch } = useContext(PitchContext) const [bookInfo, setBookInfo] = useState('') const [rating, setRating] = useState(0) const [pitch, setPitch] = useState('') const [inputValue, setInputValue] = useState('') const [autocompleteBooks, setAutocompleteBooks] = useState([]) useEffect(() => { // TODO: request debouncing if (inputValue) { axios.get(BASE_URL + inputValue).then(response => { setAutocompleteBooks(response.data.items.map(book => book.volumeInfo)) }) } }, [inputValue]) // console.log(autocompleteBooks) const redirectToHomePage = () => { history.push('/') } const createPitch = () => { console.log(bookInfo) const newBook = { title: bookInfo.title, author: bookInfo.authors[0], description: bookInfo.description, rating, pitch, img_url: bookInfo.imageLinks?.thumbnail || '', } addPitch(newBook) redirectToHomePage() } console.log(bookInfo) return ( <Paper className={classes.paper}> <div className={classes.titleContainer}> <Typography variant="h3">Create Pitch</Typography> <Button variant="text" color="primary" onClick={redirectToHomePage}> Back </Button> </div> {bookInfo && <img src={bookInfo.imageLinks?.thumbnail || 'https:example.com'} />} <FormGroup className={classes.formGroup}> <Autocomplete value={bookInfo} onChange={(e, value) => setBookInfo(value)} inputValue={inputValue} onInputChange={(e, value) => setInputValue(value)} freeSolo getOptionSelected={(option, value) => option.infoLink === value.infoLink} getOptionLabel={option => option?.title || ''} options={autocompleteBooks.map(book => book)} renderInput={params => ( <TextField {...params} label="Book Title" margin="normal" variant="outlined" /> )} /> </FormGroup> <FormGroup className={classes.formGroup}> <Typography id="discrete-slider" gutterBottom> Rating </Typography> <Slider valueLabelDisplay="auto" value={rating} step={1} marks min={0} max={10} onChange={(event, value) => setRating(value)} /> </FormGroup> <FormGroup className={classes.formGroup}> <TextField label="Your Pitch!" type="text" variant="outlined" fullWidth multiline rows={6} value={pitch} onChange={event => setPitch(event.target.value)} /> </FormGroup> <FormGroup className={classes.formGroup}> <Button variant="outlined" size="large" color="primary" onClick={createPitch}> Sumbit </Button> </FormGroup> </Paper> ) } export default CreateForm <file_sep>import React, { useEffect, useContext } from 'react' import { Container, Toolbar } from '@material-ui/core' import { makeStyles, Button } from '@material-ui/core' import { Switch, Route } from 'react-router-dom' import firebase from 'firebase' import Header from './components/Header' import PitchList from './components/PitchList' import CreatePitch from './components/CreatePitch' import { Context as PitchContext } from './contexts/PitchContext' const useStyles = makeStyles({ root: { height: '100vh', display: 'flex', flexDirection: 'column', }, container: { flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 20, paddingBottom: 20, }, }) const App = () => { const classes = useStyles() const { fetchBooks } = useContext(PitchContext) useEffect(() => { firebase.initializeApp({ apiKey: '<KEY>', authDomain: 'book-pitches.firebaseapp.com', databaseURL: 'https://book-pitches-default-rtdb.europe-west1.firebasedatabase.app', projectId: 'book-pitches', storageBucket: 'book-pitches.appspot.com', messagingSenderId: '763602875712', appId: '1:763602875712:web:2ff5a12cb5755504e2b6a5', }) fetchBooks() }, []) return ( <div className={classes.root}> <Header /> <Toolbar /> <Container fixed className={classes.container}> <Switch> <Route exact path="/"> <PitchList /> </Route> <Route path="/create"> <CreatePitch /> </Route> </Switch> </Container> </div> ) } export default App <file_sep>import React, { useContext } from 'react' import { useHistory } from 'react-router-dom' import { Paper, Typography, Button, Grid, Card, CardActionArea, CardContent, CardMedia, makeStyles, } from '@material-ui/core' import { Context as PitchContext } from '../contexts/PitchContext' const useStyles = makeStyles({ paper: { flex: 1, padding: '20px 40px', }, titleContainer: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', paddingBottom: '20px', }, cardContainer: {}, card: { height: '375px', }, cardImage: { width: '100%', height: '250px', backgroundSize: 'cover', }, cardTitle: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', }, }) const PitchList = () => { const classes = useStyles() const history = useHistory() const { state: { books }, } = useContext(PitchContext) const redirectToCreatePitch = () => { history.push('/create') } const cards = books.map(book => ( <Grid item xs={12} md={4}> <Card className={classes.card} key={book.title}> <CardActionArea> <CardMedia className={classes.cardImage} image={book.img_url} title={book.title} /> <CardContent> <div className={classes.cardTitle}> <Typography gutterBottom variant="h5"> {book.title} </Typography> <Typography gutterBottom variant="body1"> {book.rating} </Typography> </div> <Typography variant="body2" color="textSecondary" component="p"> {book.description} </Typography> </CardContent> </CardActionArea> </Card> </Grid> )) return ( <Paper className={classes.paper}> <div className={classes.titleContainer}> <Typography variant="h3">My Pitches</Typography> <Button variant="contained" color="primary" onClick={redirectToCreatePitch}> Create a pitch </Button> </div> <Grid container className={classes.cardContainer} spacing={2}> {cards} </Grid> </Paper> ) } export default PitchList <file_sep>import createDataContext from './createDataContext' import firebase from 'firebase' const ADD_BOOK = 'ADD_BOOK' const FETCH_BOOKS = 'FETCH_BOOKS' const initialState = { books: [], } const pitchReducer = (state, action) => { switch (action.type) { case FETCH_BOOKS: return { ...state, books: action.payload } case ADD_BOOK: return { ...state, books: [...state.books, action.payload] } default: return state } } const addPitch = dispatch => async payload => { try { dispatch({ type: ADD_BOOK, payload }) } catch (err) { console.log('Error!') } } const fetchBooks = dispatch => async () => { try { const books = firebase .database() .ref('books') .on('value', snapshot => { dispatch({ type: FETCH_BOOKS, payload: snapshot.val() }) }) } catch (err) { console.log('error') } } export const { Provider, Context } = createDataContext( pitchReducer, { addPitch, fetchBooks }, initialState )
e0aa0fe2dfd3e8614aa3d101059d61a84134d84d
[ "JavaScript" ]
4
JavaScript
adamjanes/book-pitches
5248e27e2c4eb23f35bf517ab67f03ab6906ce10
92b1f5ce543a813302a54acfd5775a6ebe918081
refs/heads/master
<file_sep>var interval; var points = []; var field = document.getElementById("field"); var isLife = false; var cursor = []; var fieldColor = "#1f3438" var defaultCur = [{ x: 0, y: 0 }]; cursor = defaultCur; var width = 100, height = 40; function toScale() { width = parseInt(document.getElementById('width').value); height = parseInt(document.getElementById('height').value); field.width = width * 10; field.height = height * 10; initField(); } function initField() { var ctx = field.getContext('2d'); ctx.fillStyle = fieldColor; ctx.fillRect(0, 0, field.width, field.height); ctx.fillStyle = "white"; ctx.beginPath(); for (var i = 10; i < (width * 10); i += 10) { ctx.moveTo(i + 0.5, 0 + 0.5); ctx.lineTo(i + 0.5, height * 10 + 0.5); } for (var i = 10; i < (height * 10); i += 10) { ctx.moveTo(0 + 0.5, i + 0.5); ctx.lineTo(width * 10 + 0.5, i + 0.5); } ctx.lineWidth = 0.5; ctx.stroke(); for (var i = 0; i < (width + 20); ++i) { points[i] = []; for (var j = 0; j < (height + 20); ++j) { points[i][j] = false; } } } var ctx = field.getContext('2d'); ctx.fillStyle = fieldColor; ctx.fillRect(0, 0, field.width, field.height); for (var i = 0; i < (width + 20); ++i) { points[i] = []; for (var j = 0; j < (height + 20); ++j) { points[i][j] = false; } } ctx.fillStyle = "white"; ctx.beginPath(); for (var i = 10; i < (width * 10); i += 10) { ctx.moveTo(i + 0.5, 0 + 0.5); ctx.lineTo(i + 0.5, height * 10 + 0.5); } for (var i = 10; i < (height * 10); i += 10) { ctx.moveTo(0 + 0.5, i + 0.5); ctx.lineTo(width * 10 + 0.5, i + 0.5); } ctx.lineWidth = 0.5; ctx.stroke(); var tempPoints = []; field.onmouseover = function (e) { var context = field.getContext('2d'); function drawPoint(e) { var n = document.getElementById("cursor").options.selectedIndex; switch (n) { case 0: cursor = defaultCur; break; case 1: switchToWall(); break; case 2: switchToSnowflake(); break; case 3: switchToPingPong(); break; case 4: switchToGun(); break; } var mouseX = e.pageX - field.offsetLeft; var mouseY = e.pageY - field.offsetTop; for (var i = 0; i < cursor.length; i++) { context.fillStyle = "rgba(255,255,255,0.5)"; var x = Math.floor(mouseX / 10) * 10 + 1 + cursor[i].x * 10; var y = Math.floor(mouseY / 10) * 10 + 1 + cursor[i].y * 10; context.fillRect(x, y, 9, 9); tempPoints.push({ x: x, y: y, live: points[Math.floor(mouseX / 10) + 10 + cursor[i].x][Math.floor(mouseY / 10) + 10 + cursor[i].y] }); } } field.onmousemove = function (e) { for (var i = 0; i < tempPoints.length; i++) { if (!tempPoints[i].live) context.fillStyle = fieldColor; else context.fillStyle = "white"; context.fillRect(tempPoints[i].x, tempPoints[i].y, 9, 9); console.log(tempPoints[i].x + ' ' + tempPoints[i].y); } tempPoints = []; drawPoint(e); } field.onmouseout = function (e) { for (var i = 0; i < tempPoints.length; i++) { if (!tempPoints[i].live) context.fillStyle = fieldColor; else context.fillStyle = "white"; context.fillRect(tempPoints[i].x, tempPoints[i].y, 9, 9); console.log(tempPoints[i].x + ' ' + tempPoints[i].y); } tempPoints = []; } } field.onmousedown = function (e) { var n = document.getElementById("cursor").options.selectedIndex; switch (n) { case 0: cursor = defaultCur; break; case 1: switchToWall(); break; case 2: switchToSnowflake(); break; case 3: switchToPingPong(); break; case 4: switchToGun(); break; } drawPoint(e); function drawPoint(e) { var mouseX = e.pageX - field.offsetLeft; var mouseY = e.pageY - field.offsetTop; var context = field.getContext('2d'); for (var i = 0; i < cursor.length; i++) if (!points[Math.floor(mouseX / 10) + 10 + cursor[i].x][Math.floor(mouseY / 10) + 10 + cursor[i].y]) { context.fillStyle = "white"; context.fillRect(Math.floor(mouseX / 10) * 10 + 1 + cursor[i].x * 10, Math.floor(mouseY / 10) * 10 + 1 + cursor[i].y * 10, 9, 9); points[Math.floor(mouseX / 10) + 10 + cursor[i].x][Math.floor(mouseY / 10) + 10 + cursor[i].y] = true; } else { context.fillStyle = fieldColor; context.fillRect(Math.floor(mouseX / 10) * 10 + 1 + cursor[i].x * 10, Math.floor(mouseY / 10) * 10 + 1 + cursor[i].y * 10, 9, 9); points[Math.floor(mouseX / 10) + 10 + cursor[i].x][Math.floor(mouseY / 10) + 10 + cursor[i].y] = false; } } document.onmouseup = function () { field.onmouseup = null; } } function draw() { var field = document.getElementById("field"); var context = field.getContext('2d'); for (var i = 0; i < width; ++i) { for (var j = 0; j < height; ++j) { if (points[i + 10][j + 10]) { context.fillStyle = "white"; } else { context.fillStyle = fieldColor; } context.fillRect(i * 10 + 1, j * 10 + 1, 9, 9); } } } function countOfLiveNeighbors(i, j) { var prevX = i - 1; var nextX = i + 1; var prevY = j - 1; var nextY = j + 1; var countLiveNeighbors = 0; for (var x = prevX; x <= nextX; ++x) { for (var y = prevY; y <= nextY; ++y) { if (x > -1 && y > -1 && x < (width + 20) && y < (height + 20)) { if (points[x][y]) { if (!(x == i && y == j)) countLiveNeighbors++; } } } } return countLiveNeighbors; } function step() { var newPoints = []; for (var i = 0; i < points.length; ++i) { newPoints[i] = []; for (var j = 0; j < points[i].length; ++j) { newPoints[i][j] = false; } } if (isLife) { for (var i = 0; i < points.length; ++i) { for (var j = 0; j < points[i].length; ++j) { newPoints[i][j] = points[i][j]; } } for (var i = 0; i < points.length; ++i) { for (var j = 0; j < points[i].length; ++j) { var countLiveNeighbors = countOfLiveNeighbors(i, j); if (!points[i][j] && countLiveNeighbors == 3) { newPoints[i][j] = true; } else if (points[i][j] && countLiveNeighbors >= 2 && countLiveNeighbors <= 3) { newPoints[i][j] = true; } else { newPoints[i][j] = false; } } } for (var i = 0; i < points.length; ++i) { for (var j = 0; j < points[i].length; ++j) { points[i][j] = newPoints[i][j]; } } draw(); } else clearInterval(interval); } function death() { isLife = false; } var speed = 0; window.onload = function () { speed = 200 - document.getElementById('speed').value; } function live() { isLife = true; clearInterval(interval); interval = setInterval('step()', speed); } function changeSpeed() { var newSpeed = 200 - document.getElementById('speed').value; speed = newSpeed; live(); } function startOrStop() { if (isLife) { document.getElementById('startStop').innerText = 'ЗАПУСТИТЬ'; death(); } else { document.getElementById('startStop').innerText = 'ОСТАНОВИТЬ'; live(); } } function clearField() { for (var i = 0; i < (width + 20); ++i) { points[i] = []; for (var j = 0; j < (height + 20); ++j) { points[i][j] = false; } } draw(); } function save() { for (var i = 0; i < points.length; ++i) { for (var j = 0; j < points[i].length; ++j) { localStorage[i + ';' + j] = points[i][j]; } } } function load() { for (var i = 0; i < points.length; ++i) { for (var j = 0; j < points[i].length; ++j) { if (localStorage[i + ';' + j] == "true") points[i][j] = true; else points[i][j] = false; } } draw(); } function switchToSnowflake() { cursor = snowflake; } function switchToGun() { cursor = gun; } function switchToPingPong() { cursor = pingPong; } function switchToDefault() { cursor = defaultCur; } function switchToWall() { cursor = wall; }
e0fd01b2f5b85d72bad8b03eae42f955a238d5f7
[ "JavaScript" ]
1
JavaScript
maxticorn/it_is_not_a_game_it_is_life
4c25d5d30ce61178250e87d01c441468bebd0801
a1c5a86902ceed96db4811caf71d812867d6b75e
refs/heads/master
<file_sep>// ############################## // // // Cards // ############################# import HeaderCard from "./Cards/HeaderCard.jsx"; import RepoCard from "./Cards/RepoCard.jsx"; // ############################## // // // Lists // ############################# import RepoList from "./List/RepoList.jsx"; import PinnedList from "./List/PinnedList.jsx"; // ############################## // // // Main // ############################# import Main from "./Main/Main.jsx"; export { // Cards HeaderCard, RepoCard, // Lists RepoList, PinnedList, // Main Main }; <file_sep>import React from "react"; import RepoCard from "../Cards/RepoCard.jsx"; import "../../assets/css/pinnedListStyle.css"; const PinnedList = ({ ...props }) => { const { pinnedRepositories } = props; return ( <div> <div className="list-header"> <div className="rowGroup"> <div className=""> <h4 className="mt-0 mb-0">Prinned Repositories </h4> </div> </div> </div> <ol className="grid"> {pinnedRepositories.map((repo, key) => { return ( <li key={ key } className="grid-flex"> <RepoCard isFork={ repo.isFork } forkUrl={ repo.parent } description={ repo.description } name={ repo.name } languages={ repo.languages } stargazers={ repo.stargazers } forkCount={ repo.forkCount } licenseInfo={ repo.licenseInfo }> </RepoCard> </li> ); })} </ol> </div> ); } export default (PinnedList);<file_sep>import React from 'react'; import { HeaderCard } from '../components'; import { RepoList } from '../components'; import { PinnedList } from '../components'; import "../assets/css/tempListStyle.css"; function OrgGithubInfo({ ...props }) { const { organization } = props; return ( <div className="t-body"> <HeaderCard orgName={ organization.name } orgUrl={ organization.websiteUrl } orgLocation={ organization.location } avatarUrl={ organization.avatarUrl } > </HeaderCard> <PinnedList pinnedRepositories={ organization.pinnedRepositories.nodes } > </PinnedList> <RepoList repositories={ organization.repositories.nodes } > </RepoList> </div> ); } export default (OrgGithubInfo);<file_sep># Organization Info from Github [![version][version-badge]][CHANGELOG] [![license][license-badge]][LICENSE] The main project was boilerplated by ```create-react-app github-info ``` using Yarn. Github Organization is a small project that provide the information about a given organization, listing the repositories and pinned ones. The main objective with this small project is get a given organization, pass by URL and return the repositories and information about it from their Github page, using GraphQL query to do it. If you don`t pass any organization name in URL the query will assume a default organization predefined in code. This page was built using React, GraphQL and the Github V4 api as technologies, using Axios as an HTTP-Client. To organize this project I following the single responsibility principle to divide the components into the file structure. You can find the Github Repo here. ## Links: + [Live Preview](https://angularlab-marcelomenegat.c9users.io/) ## Quick start Quick start options: - [Download from Github](https://github.com/marcelomenegat/github-info/archive/master.zip). - Clone the repo: `git clone https://github.com/marcelomenegat/github-info.git`. ## Prerequisites and Usage 1. Install NodeJs from [NodeJs Official Page](https://nodejs.org/en). 2. Install Yarn from [Yarn Official Page](https://yarnpkg.com/en/docs/install) 3. Open Terminal 4. Go to your file project 5. Run in terminal: ```yarn install``` 6. Then: ```yarn start``` 7. Navigate to `http://localhost:3000/` ### File Structure Within the download you'll find the following directories and files: ``` github-info . ├── README.md ├── package.json ├── yarn.lock ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json └── src ├── assets │ ├── css │ │ ├── headerCardStyle.css │ │ ├── listCardStyle.css │ │ ├── pinnedListStyle.css │ │ ├── repoCardStyle.css │ │ ├── tempListStyle.css │ │ └── sharedStyles.css │ ├── icons │ │ ├── git-branch │ │ ├── law │ │ ├── link │ │ ├── location │ │ └── star │ ├── misc │ │ ├── colours.json │ │ └── colours.js ├── components │ ├── Card │ │ ├── HeaderCard.jsx │ │ └── RepoCard.jsx │ ├── List │ │ └── PinnedList.jsx │ │ └── RepoList.jsx │ ├── Main │ │ └── Main.jsx │ └── index.js ├── mocks │ ├── repos.json │ └── query.gql ├── tamplate │ └── OrgGithubInfo.jsx ├── index.js ├── index.css ├── App.js ├── App.css ├── App.test.js ├── logo.svg └── registerServiceWorker.js ``` ## Explaing the File Structure and Components This file structure is simple and is based in separate the components, tamplates and the main core af the app. In the ```components``` directory contain five small stateless components that provide specifics renders to the application, like: + HeaderCard: Render the organization information as Name, URL link and location. + RepoCard: Render the repositories data and meta-data as Name, Description, Language, etc. + RepoList: Implements RepoCard, and list all repositories of the Organization. + PinnedList: Also implements RepoCard, and list the pinned repositories of the Organization. + Main: This component is not a Stateles component, but a Statefull component. Is here where the call to API is made, and process the response to render the Tamplate, explained below. OrgGithubInfo also is a stateless component but is located in the ```template``` directory. This component joint the HeaderCard, RepoList and PinnedList to the final structure that will be showed. The ```assets``` directory contains all css`s files and icons that was used in the application. There is also a ```misc``` directory that have a Json with the colours of the language showed in meta-data of each repository. [CHANGELOG]: ./CHANGELOG.md [LICENSE]: ./LICENSE.md [version-badge]: https://img.shields.io/badge/version-1.3.0-blue.svg [license-badge]: https://img.shields.io/badge/license-MIT-blue.svg <file_sep>import React from "react"; import "../../assets/css/headerCardStyle.css" const HeaderCard = ({ ...props }) => { const { orgName, orgUrl, orgLocation, avatarUrl, } = props; return ( <div className="wrapper"> <div className="rowGroup"> <div className="aside" > <img src={ avatarUrl } alt="{ orgName }" className="logo"/> </div> <div className="info"> <div> <h2> { orgName } </h2> </div> <div> <icon className="ic-loc ic"></icon> <span className="location" > { orgLocation } </span> </div> <div> <icon className="ic-url ic"></icon> <a href={ orgUrl }> { orgUrl } </a> </div> </div> </div> </div> ); } export default (HeaderCard); <file_sep>import React from "react"; import RepoCard from "../Cards/RepoCard.jsx"; import "../../assets/css/listCardStyle.css"; const RepoList = ({ ...props }) => { const { repositories } = props; return ( <div> <div className="list-header"> <div className="rowGroup"> <div className=""> <h4 className="mt-0 mb-0"> Repositories </h4> </div> </div> </div> <ul className="list-content mt-0 mb-0 width-full"> {repositories.map((repo, key) => { return ( <li key={ key } className="li-block width-full bb-1"> <RepoCard isFork={ repo.isFork } forkUrl={ repo.parent } description={ repo.description } name={ repo.name } languages={ repo.languages } stargazers={ repo.stargazers.totalCount } forkCount={ repo.forkCount } licenseInfo={ repo.licenseInfo }> </RepoCard> </li> ); })} </ul> </div> ); } export default (RepoList);
0d0b6104a716bfa8b204e7eb223d31d8bebc71ca
[ "JavaScript", "Markdown" ]
6
JavaScript
marcelomenegat/github-info
982b68dbc78bc5f2846d37dc44bf494f069282e4
1462edfbbb93886fe3bb1c09fb671864392ccfd5
refs/heads/master
<file_sep>{% extends "layout.html" %} {% block body %} <ul class=info> {% for key in info %} <li><h2>{{ key }}:</h2>{{ info[key]|safe }} {% else %} <li><em>info not available</em> {% endfor %} </ul> <ul class=version> {% for key in version %} <li><h2>{{ key }}:</h2>{{ version[key]|safe }} {% else %} <li><em>version not available</em> {% endfor %} </ul> {% endblock %}<file_sep>import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): """ Extension to setuptools' test command to allow us to run py.test using `python setup.py test`. Copied from the py.test documentation (see 'Good Integration Practises'). """ user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='cargo', version='0.0.99', description='Cargo', install_requires=[ 'flask>=0.10.0,<1', 'flask-sqlalchemy>=2.0.0', 'flask-script>=2.0.5', 'flask-migrate>=1.4.0', 'sqlalchemy>=1.0', 'alembic', ], tests_require=[ 'pytest-cov', 'mock', ], author='shipperizer', author_email='<EMAIL>', url='http://tiffzhang.com/startup/index.html?s=538178832968', packages=find_packages(), include_package_data=True, cmdclass={'test': PyTest} ) <file_sep>[![Build Status](https://travis-ci.org/shipperizer/cargo.svg)](https://travis-ci.org/shipperizer/cargo) [![Coverage Status](https://coveralls.io/repos/shipperizer/cargo/badge.svg?branch=master&service=github)](https://coveralls.io/github/shipperizer/cargo?branch=master) [![Code Climate](https://codeclimate.com/github/shipperizer/cargo/badges/gpa.svg)](https://codeclimate.com/github/shipperizer/cargo) ## Cargo Trying to have a nice GUI for [docker API](http://docs.docker.com/reference/api/docker_remote_api/) and learn [Flask](http://flask.pocoo.org) - Adding triggers to spawn/stop/clean containers. Yes shipyard&Co do already so, but it's not my fault and I don't actually know what else I can play around. <file_sep>PYTHON=/usr/bin/env python PIP=/usr/bin/pip PACKAGES=python python-pip DEPENDENCIES=requirements.txt MOD_NAME=cargo VERSION_NUMBER?="0.0.99" WSGI=gunicorn MSG?="change-me-plz" .PHONY: info install test clean-build: rm -rf build/ dist/ rm -rf $(MOD_NAME)-$(VERSION_NUMBER)_* $(MOD_NAME).egg-info rm -rf docs/_build info: @echo "****************************************************************" @echo "To build this project you need these dependencies: $(PACKAGES)" @echo "Check requirements.txt/setup.py file to see python dependencies." @echo "****************************************************************" @echo "USAGE:" @echo "- To install dependencies: make install" @echo "- To launch: make [start|stop|debug]" @echo "- To test: make test **unit(integration)test" start: db-upgrade $(WSGI) -w 4 "$(MOD_NAME).bootstrap:app" debug: db-upgrade DEBUG=1 $(PYTHON) "$(MOD_NAME)/bootstrap" runserver debug-gun: db-upgrade DEBUG=1 $(WSGI) -w 4 "$(MOD_NAME).bootstrap:app" install: build-reqs info @echo "Python dependencies" $(PIP) install -r $(DEPENDENCIES) build-reqs: $(PIP) install --upgrade pip $(PIP) install --upgrade setuptools # pip you are so stupid http://stackoverflow.com/a/25288078 $(PIP) install --upgrade setuptools test: build-reqs touch conftest.py $(PYTHON) setup.py test -a '--cov $(MOD_NAME) --cov-config .coveragerc --cov-report xml --junit-xml=results.xml' rm conftest.py db-init: $(PYTHON) "$(MOD_NAME)/bootstrap.py" db init $(PYTHON) "$(MOD_NAME)/bootstrap.py" db migrate db-migrate: $(PYTHON) "$(MOD_NAME)/bootstrap.py" db migrate -m"$(MSG)" db-upgrade: $(PYTHON) "$(MOD_NAME)/bootstrap.py" db upgrade <file_sep>from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.migrate import Migrate db = SQLAlchemy() def init_database(app): db.init_app(app) migrate = Migrate(app, db) <file_sep>#!/usr/bin/env python import requests from urllib.parse import urljoin from flask.views import MethodView from flask import render_template, jsonify, request class ExtraAPI(MethodView): methods = ['GET'] def __init__(self, docker_api=None): self.DOCKER_API = docker_api def get(self): json = request.args.get('json') version = self.version() info = self.info() if json not in ['True', 'true']: return render_template('extra.html', version=version, info=info) return jsonify(version=version, info=info) def version(self): return requests.get(urljoin(self.DOCKER_API, 'version')).json() def info(self): return requests.get(urljoin(self.DOCKER_API, 'info')).json() <file_sep>#!/usr/bin/env python import pytest @pytest.fixture(scope='function') def foo(): return 1 <file_sep>from fixtures import * def foo_test(foo): assert foo == 1 <file_sep>#!/usr/bin/env python import os import requests from urllib.parse import urljoin from contextlib import closing from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash from flask.ext.migrate import MigrateCommand from flask.ext.script import Manager from cargo.db.db import init_database from cargo.extra.extra import ExtraAPI # TODO see below the next TODO # configuration SQLALCHEMY_DATABASE_URI = 'sqlite:///cargo.db' DEBUG = True SECRET_KEY = '5h1pp3r143r' USERNAME = 'admin' PASSWORD = '<PASSWORD>' DOCKER_HOST = 'http://127.0.0.1' DOCKER_PORT = '4567' DOCKER_API = ':'.join([DOCKER_HOST, DOCKER_PORT]) # application app = Flask(__name__) # TODO spin off the config on another file app.config.from_object(__name__) init_database(app) manager = Manager(app) manager.add_command('db', MigrateCommand) def register_api(view, kwargs, endpoint, url, defaults=None): view_func = view.as_view(endpoint, **kwargs) app.add_url_rule(url, view_func=view_func, defaults=defaults) register_api(ExtraAPI, {'docker_api': DOCKER_API}, 'extra', '/extra') if __name__ == "__main__": manager.run()
150ea584950e33506d3c8a079f8d18e35bfe0a3d
[ "Markdown", "Python", "Makefile", "HTML" ]
9
HTML
shipperizer/cargo
f56529b37a70ac5cdbc7bc7398b340796c49d404
5d61eb3451bf178d67df6e0b339cf88dccd1312e
refs/heads/master
<repo_name>hojene007/myRepos<file_sep>/python_stuff/smo.py # -*- coding: utf-8 -*- """ Created on Tue Feb 24 23:57:51 2015 @author: Epoch """ import csv import os import numpy as np import pandas as pd import scipy as sc from numpy import genfromtxt def uniqueFun(seq): # order preserving function extracting unique elements from sequence checked = [] for e in seq: if e not in checked: checked.append(e) return checked def createDict(n, k) : k = 1 #for now stage = {} stage['stage2'] = ([1, 2], [1, 3], [2, 1]) print "the n is ", n for i in range(3, n+1): nameLast = "stage{0}".format(i-1) nameNow = "stage{0}".format(i) for j in range(0, len(stage[nameLast])): last = stage[nameLast][j][-1] slast = stage[nameLast][j][-2] # stage is i # node in stage is j print "Stage no. ", i print "Node no. ", j if i<n : if last < i: if j==0: # if its the first record in this stage stage[nameNow]=([slast, last, i], ) tempList = list(stage[nameNow]) tempList.append([slast, last, i+k]) else : tempList.append([slast, last, i]) tempList.append([slast, last, i+1]) elif last==i : tempList.append([slast, last, i-1]) # elis last>i another elif here if we go beyond the k=1 case elif i==n : lastN = list(set([i-1, i]).difference([last, slast])) lastN = int(''.join(map(str,lastN))) #turning to integer lastNode = [slast, last, lastN] #print(lastNode) if j==0 : stage[nameNow]=([lastNode],) tempList = list(stage[nameNow]) else: tempList.append(lastNode) stage[nameNow]=tuple(tempList) newStage={} newStage['stage2'] = ([1, 2], [1, 3], [2, 1]) newStage['stage1'] = ([1], [2]) # now to clean the network for unique elements for i in range(3, n+1): nameNow = "stage{0}".format(i) newStage[nameNow] = tuple(uniqueFun(stage[nameNow])) return newStage myDic = createDict(10, 1) def createDict2(n, k) : k = 1 #for now stage = {} arcSet = {} stage['stage2'] = ([1, 2], [1, 3], [2, 1]) print "the n is ", n for i in range(3, n+1): nameLast = "stage{0}".format(i-1) nameNow = "stage{0}".format(i) for j in range(0, len(stage[nameLast])): last = stage[nameLast][j][-1] slast = stage[nameLast][j][-2] # stage is i # node in stage is j print "Stage no. ", i print "Node no. ", j if i<n : if last < i: if j==0: # if its the first record in this stage stage[nameNow]=([slast, last, i], ) tempList = list(stage[nameNow]) tempList.append([slast, last, i+k]) else : tempList.append([slast, last, i]) tempList.append([slast, last, i+1]) elif last==i : tempList.append([slast, last, i-1]) # elis last>i another elif here if we go beyond the k=1 case elif i==n : lastN = list(set([i-1, i]).difference([last, slast])) lastN = int(''.join(map(str,lastN))) lastNode = [slast, last, lastN] #print(lastNode) if j==0 : stage[nameNow]=([lastNode],) tempList = list(stage[nameNow]) else: tempList.append(lastNode) stage[nameNow]=tuple(tempList) newStage={} newStage['stage2'] = ([1, 2], [1, 3], [2, 1]) newStage['stage1'] = ([1], [2]) # now to clean the network for unique elements for i in range(3, n+1): nameNow = "stage{0}".format(i) newStage[nameNow] = tuple(uniqueFun(stage[nameNow])) arcSet['1to2'] = for (i in range(0, n-1)): return newStage
15d22edd3df5aa44ec9f8d124b0f9d3fd29e57eb
[ "Python" ]
1
Python
hojene007/myRepos
49ab7d9d93ed145277792ce59f8a9c598d697642
e77fc8cd49beda0dec439c8d4d973bd5dabdb333
refs/heads/master
<repo_name>LohithCS/PiCar<file_sep>/stop_sign_pi.py import cv2 import subprocess import time threshold_score=0.0001 flag=1 while(1): if flag != 0: start_time = time.time() camera = cv2.VideoCapture(0) for i in range(10): return_value, image = camera.read() if i == 9: cv2.imwrite('webcam'+str(i)+'.png', image) print("image ready\n") del(camera) try: k=open('width_height.txt','r') width_height=k.read() if width_height: print('the width of the rectangle is ',width_height) if(float(width_height)>threshold_score): print("stop_sign_detected") else: print("stop sign is still far") subprocess.call(['./remove_file.sh'])#print('file removed') flag=1 end_time = time.time() net_time = end_time - start_time print(net_time) except: if flag !=0 : print("stop_sign processing is being done..please wait") flag=0 <file_sep>/lane_obstacle_code.py import RPi.GPIO as GPIO from time import sleep import cv2 import picamera import numpy as np # configure pins GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(17,GPIO.OUT) GPIO.setup(18,GPIO.OUT) GPIO.setup(22,GPIO.OUT) GPIO.setup(23,GPIO.OUT) # for camera interfacing camera = picamera.PiCamera() camera.resolution = (420, 368) camera.brightness = 60 camera.start_preview() i=0 # counter variable # movement types def right(sleep_time=0.2): GPIO.output(17,GPIO.HIGH) GPIO.output(18,GPIO.LOW) GPIO.output(22,GPIO.LOW) GPIO.output(23,GPIO.LOW) sleep(sleep_time) stop() def stop(): GPIO.output(17,GPIO.LOW) GPIO.output(18,GPIO.LOW) GPIO.output(22,GPIO.LOW) GPIO.output(23,GPIO.LOW) return def left(sleep_time=0.2): GPIO.output(17,GPIO.LOW) GPIO.output(18,GPIO.HIGH) GPIO.output(22,GPIO.LOW) GPIO.output(23,GPIO.LOW) sleep(sleep_time) stop() def front(): GPIO.output(17,GPIO.HIGH) GPIO.output(18,GPIO.HIGH) GPIO.output(22,GPIO.LOW) GPIO.output(23,GPIO.LOW) return # take pictures from camera def take_pictures(i): img_sav_name = '/home/pi/PiCar-2019/train_set/Original/' + 'origin_' + str(i) + '.jpeg' img = camera.capture(img_sav_name) #cv2.imwrite(img_sav_name,img) camera.stop_preview() return img_sav_name def draw_lines(img, houghLines, color=[0, 255, 0], thickness=2): #to draw lines when houghlinesP is used for line in houghLines: # here it is not used for x1,y1,x2,y2 in line: cv2.line(img,(x1,y1),(x2,y2),color,thickness) def draw_lines_new(img, houghLines, color=[0, 255, 0], thickness=2): #to draw lines when houghlines is used for line in houghLines: for rho,theta in line: a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),color,thickness) def weighted_img(img, initial_img, α=0.7, β=1.0, λ=0.0): return cv2.addWeighted(initial_img, α, img, β, λ) ''' ang=[] def angles(houghLines): #print angles when houghlinesP is used for line in houghLines: # here it is not used for x1,y1,x2,y2 in line: try: m=abs((y2-y1)/(x2-x1)+0.0001) ang.append(np.tan(m)) except: pass #print(ang) ''' def angles_left(houghLines): #print angles when houghlines is used (left) ang_left=0.0 for line in houghLines: for rho,theta in line: #print(theta) ang_left=float(90-theta*180/np.pi) return(ang_left) #print(type(ang_left)) def angles_right(houghLines): #print angles when houghlinesP is used (right) ang_right=0.0 for line in houghLines: for rho,theta in line: #print(theta) ang_right=float(90-theta*180/np.pi) return(ang_right) def right_process(image_right_cropped,id): image=image_right_cropped gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('/home/pi/PiCar-2019/train_set/grey/grey_right'+ str(id) +'.jpeg',gray_image) blurred_image = cv2.GaussianBlur(gray_image, (9, 9), 0) edges_image = cv2.Canny(blurred_image, 50, 120) cv2.imwrite('/home/pi/PiCar-2019/train_set/nd_Image/nd_Image_right'+ str(id) +'.jpeg',edges_image) rho_resolution = 1 theta_resolution = np.pi/180 threshold = 1 kernel = np.ones((3,3),np.uint8) #print("start") edges_image = cv2.dilate(edges_image,kernel,iterations = 2) cv2.imwrite('/home/pi/PiCar-2019/train_set/edge_Image/edge_Image_right'+ str(id) +'.jpeg',edges_image) try: hough_lines = cv2.HoughLinesP(edges_image, rho_resolution , theta_resolution , threshold) #initial edge lines on the original image # print(hough_lines) hough_li = hough_lines.tolist() #print(type(hough_li)) except: #print('kali') print("empty right half") return("right",image_right_cropped,0) #hough_li = hough_lines.tolist() #cv2.imwrite('/home/pi/PiCar-2019/train_set/Edge_Image/houghp'+ str(id) +'.jpeg',edges_image) #print("lenght") #hlen=len(hough_li) #print(hlen,type(hlen)) #print(hough_lines) hough_lines_image = np.zeros_like(image_right_cropped) draw_lines(hough_lines_image, hough_lines) original_image_with_hough_lines = weighted_img(hough_lines_image,image) final_image = cv2.dilate(original_image_with_hough_lines,kernel,iterations = 2) #dilate that to cover the gaps cv2.imwrite('/home/pi/PiCar-2019/train_set/houghp_Image/houghpImage_right'+ str(id) +'.jpeg',final_image) threshold_n = 30 try: gray_image = cv2.cvtColor(final_image, cv2.COLOR_BGR2GRAY) blurred_image = cv2.GaussianBlur(gray_image, (9, 9), 0) edges_image = cv2.Canny(blurred_image, 50, 120) hough_lines_right = cv2.HoughLines(edges_image, rho_resolution , theta_resolution , threshold_n) #print(len(hough_lines_right)) #use houghline to detect the no. of lines leng=len(hough_lines_right) lis=hough_lines_right.tolist() except Exception as e: print(e) return("right",image_right_cropped,0) #print("\n",hough_lines_right) #print(lis) rr=0 aa=0 neg=0 pos=0 ang_lis=[] for i in lis: #print(i[0][0],i[0][1]) #rr+=i[0][0] #aa+=i[0][1] ang_lis.append(i[0][1]) #rr=rr/leng #aa=aa/leng ang_lis_deg=[] for i in ang_lis: ang_lis_deg.append(float(90-i*180/np.pi)) #print(ang_lis_deg) for i in ang_lis_deg: if i<0: neg+=1 else: pos+=1 #print(neg,pos) for i in lis: if(neg>pos): ag=float(90-(i[0][1])*180/np.pi) #print(ag) le=neg if(ag<0): rr+=i[0][0] aa+=i[0][1] #print(ag) elif(pos>neg): ag=float(90-(i[0][1])*180/np.pi) #print(ag) le=pos if(ag>0): rr+=i[0][0] aa+=i[0][1] rr=rr/le aa=aa/le #print(rr,aa) hough_avg_right=np.array([[[rr,aa]]]) #take avg to get only line for left image #print(type(hough_avg_left)) #print(hough_avg_right) hough_lines_image_right = np.zeros_like(image_right_cropped) #draw_lines_new(hough_lines_image_right, hough_lines_right) draw_lines_new(hough_lines_image_right, hough_avg_right) original_image_with_hough_lines_right = weighted_img(hough_lines_image_right,image_right_cropped) a_right=angles_right(hough_avg_right) #to get the angle of the line in left image print("a_right = ",a_right) return("waste",original_image_with_hough_lines_right,a_right) def left_process(image_left_cropped,id): image=image_left_cropped gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite('/home/pi/PiCar-2019/train_set/grey/grey_left'+ str(id) +'.jpeg',gray_image) blurred_image = cv2.GaussianBlur(gray_image, (9, 9), 0) edges_image = cv2.Canny(blurred_image, 50, 120) cv2.imwrite('/home/pi/PiCar-2019/train_set/nd_Image/nd_Image_left'+ str(id) +'.jpeg',edges_image) rho_resolution = 1 theta_resolution = np.pi/180 threshold = 1 kernel = np.ones((3,3),np.uint8) edges_image = cv2.dilate(edges_image,kernel,iterations = 2) cv2.imwrite('/home/pi/PiCar-2019/train_set/edge_Image/edge_Image_left'+ str(id) +'.jpeg',edges_image) try: hough_lines = cv2.HoughLinesP(edges_image, rho_resolution , theta_resolution , threshold) #initial edge lines on the original image # print(hough_lines) hough_li = hough_lines.tolist() #print(type(hough_li)) except: #print('kali') print("empty left half") return("left",image_left_cropped,0) #print(hough_lines) hough_lines_image = np.zeros_like(image_left_cropped) draw_lines(hough_lines_image, hough_lines) original_image_with_hough_lines = weighted_img(hough_lines_image,image_left_cropped) final_image = cv2.dilate(original_image_with_hough_lines,kernel,iterations = 2) #dilate that to cover the gaps cv2.imwrite('/home/pi/PiCar-2019/train_set/houghp_Image/houghpImage_left'+ str(id) +'.jpeg',final_image) #cv2.imwrite('/home/pi/PiCar-2019/train_set/Edge_Image/Edge_Image_left'+ str(id) +'.jpeg',final_image) threshold_n = 30 try: #print(final_image) gray_image = cv2.cvtColor(final_image, cv2.COLOR_BGR2GRAY) blurred_image = cv2.GaussianBlur(gray_image, (9, 9), 0) edges_image = cv2.Canny(blurred_image, 50, 120) hough_lines_left = cv2.HoughLines(edges_image, rho_resolution , theta_resolution , threshold_n) #use houghline to detect the no. of lines #print(hough_lines_left) leng=len(hough_lines_left) lis=hough_lines_left.tolist() except Exception as e: #print(e) return("left",image_left_cropped,0) #print("\n",hough_lines_left) #print(lis) rr=0 aa=0 neg=0 pos=0 ang_lis=[] for i in lis: #print(i[0][0],i[0][1]) #rr+=i[0][0] #aa+=i[0][1] ang_lis.append(i[0][1]) #rr=rr/leng #aa=aa/leng ang_lis_deg=[] for i in ang_lis: ang_lis_deg.append(float(90-i*180/np.pi)) #print(ang_lis_deg) for i in ang_lis_deg: if i<0: neg+=1 else: pos+=1 #print(neg,pos) for i in lis: if(neg>pos): ag=float(90-(i[0][1])*180/np.pi) #print(ag) le=neg if(ag<0): rr+=i[0][0] aa+=i[0][1] #print(ag) elif(pos>neg): ag=float(90-(i[0][1])*180/np.pi) #print(ag) le=pos if(ag>0): rr+=i[0][0] aa+=i[0][1] rr=rr/le aa=aa/le hough_avg_left=np.array([[[rr,aa]]]) #take avg to get only line for left image #print(type(hough_avg_left)) #print(hough_avg_left) hough_lines_image_left = np.zeros_like(image) #draw_lines_new(hough_lines_image_left, hough_lines_left) draw_lines_new(hough_lines_image_left, hough_avg_left) original_image_with_hough_lines_left = weighted_img(hough_lines_image_left,image) a_left=angles_left(hough_avg_left) #to get the angle of the line in left image print("a_left = ",a_left) return("waste",original_image_with_hough_lines_left,a_left) def image_result(image_path,id): try: image = cv2.imread(image_path) height, width = image.shape[:2] ''' # uncomment if the webcam is visible start_row, start_col = int(0), int(0) end_row, end_col = int(height*0.85), int(width) cropped_image = image[start_row:end_row, start_col:end_col] image = cropped_image height, width = image.shape[:2] ''' start_row, start_col = int(0.5*height), int(0) end_row, end_col = int(height), int(width) cropped_image = image[start_row:end_row, start_col:end_col] image = cropped_image cv2.imwrite('/home/pi/PiCar-2019/train_set/Cropped/Image_'+ str(id) +'.jpeg',image) height, width = image.shape[:2] start_row, start_col = int(0), int(0) #to divide the original into right and left end_row, end_col = int(height), int(width * .5) image_left_original = image[start_row:end_row , start_col:end_col] start_row, start_col = int(0), int(width * .5) end_row, end_col = int(height), int(width) image_right_original = image[start_row:end_row , start_col:end_col] label_r,pro_image_r,a_right = right_process(image_right_original,id) print("hi1") label_l,pro_image_l,a_left = left_process(image_left_original,id) print("hi2") #print(label_r,label_l,a_right,a_left) vis = np.concatenate((pro_image_l, pro_image_r),axis=1) #print(vis) #print("hello") cv2.imwrite('/home/pi/PiCar-2019/train_set/Final/Final_Image'+ str(id) +'.jpeg',vis) if ((label_r == "right")and(label_l == "waste")): if (float(a_left) > 0): print("right sp") front() sleep(0.25) right() if (float(a_left) < 0): print("small right") #front() #sleep(0.25) right(0.25) elif ((label_l == "left")and(label_r == "waste")): if (float(a_right) < 0): print("left sp") front() sleep(0.25) left() if (float(a_right) > 0): print("small left") #front() #sleep(0.25) left(0.25) elif ((label_l == "waste")and(label_r == "waste")): if(float(abs(a_left)) > 70 and float(abs(a_right)) > 70): print("front") front() sleep(0.25) stop() elif(float(a_left) > 0 and float(a_right) < 0): #compare the angles and decide print("front") front() sleep(0.5) stop() elif(float(a_left) > 0 and float(a_right) > 0): print("right") front() sleep(0.35) right() elif(float(a_left) < 0 and float(a_right) < 0): print("left") front() sleep(0.35) left() elif(float(a_right) < 0): print("left") left() elif(float(a_left) > 0): print("right") right() else: print("Error") stop() print("\n") return except: print("None Type Object") return # loop i=0 while(1): i = i + 1 image_sav_name = take_pictures(i) #image_sav_name = '/home/pi/img1.jpeg' image_result(image_sav_name,i) <file_sep>/testing.sh #!/bin/bash while True do scp <EMAIL>:/home/pi/PiCar-2019/webcam9.png ~/Stop-Sign-Detection/ source /Applications/anaconda3/bin/activate conda activate base cd /Users/kopadava/Stop-Sign-Detection/ python stop_sign.py -p stopPrototype.png -i webcam9.png echo "calling done" scp /Users/kopadava/Stop-Sign-Detection/width_height.txt <EMAIL>:/home/pi/PiCar-2019/ rm -f "webcam9.png" rm -f "width_height.txt" echo "image and file are removed" done <file_sep>/README.md # PiCar-2019 ### Autonomous car using Raspberry Pi Lane detection and obstacle detection code: lane_obstacle_code.py Stop sign detection code: In Raspberry Pi, run `stop_sign_pi.py` , make sure the `remove_file.sh` script is in the same directory. In server, run the bash script `testing.sh` , make sure the `stopPrototype.png` and the `stop_sign_server.py` are in the same directory. Find all documentation here: https://drive.google.com/open?id=1fzsrf26L6RKoQyDZ27Cxr0UgdZfFOSK6<file_sep>/remove_file.sh #!/bin/bash rm -f /home/pi/PiCar-2019/width_height.txt rm -f /home/pi/PiCar-2019/webcam9.png echo "file and image removed"
384dcc51c376d5557fd6326a114b454ab3c59126
[ "Markdown", "Python", "Shell" ]
5
Python
LohithCS/PiCar
5a998bfba7b18ab2a186343f597a65f78f02a860
37d53dc06183947f2f047f73766093ce956dec41
refs/heads/main
<repo_name>Ravibhushan222/SpringBoot-app-using-my-Sql<file_sep>/src/main/java/book/bookstore/dao/BookRepositoryImpl.java package book.bookstore.dao; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.stereotype.Repository; import java.sql.Types; import book.bookstore.entity.Book; import book.bookstore.entity.BookRowMapper; @Repository public class BookRepositoryImpl implements BookRepository{ @Autowired JdbcTemplate jdbcTemplate; @Override public Boolean addBook(Book book) { String sql = "INSERT INTO books VALUES (?,?,?,?)"; return jdbcTemplate.execute(sql, new PreparedStatementCallback<Boolean>() { @Override public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { ps.setInt(1,book.getId()); ps.setString(2,book.getTitle()); ps.setString(3,book.getAuthor()); ps.setFloat(4,book.getPrice()); return ps.execute(); } }); } @Override public List<Book> getAllBooks() { return jdbcTemplate.query("SELECT * FROM books",new BookRowMapper()); } @Override @Cacheable(value = "book", key = "#id") public Book getBookById(int id) { String sql = "SELECT * FROM books WHERE id = ?"; try{ return (Book) this.jdbcTemplate.queryForObject(sql,new Object[] {id},new BookRowMapper()); }catch (EmptyResultDataAccessException ex){ return null; } } @Override public List<Book> getBookByAuthor(String author) { return jdbcTemplate.query("Select * from books WHERE author = ? ",new BookRowMapper(),author); } @Override @CachePut(value = "books", key = "#book.id") public Integer updateBook(Book book) { String query = "UPDATE books SET title = ? , author = ? ,price = ? WHERE id = ?"; Object[] params = {book.getTitle(),book.getAuthor(),book.getPrice(),book.getId()}; int[] types = {Types.VARCHAR,Types.VARCHAR,Types.FLOAT,Types.INTEGER}; return jdbcTemplate.update(query,params,types); } @Override @CacheEvict(value="book",key = "#id") public Integer deleteBook(Integer id) { return jdbcTemplate.update("DELETE FROM books WHERE id = ?",id); } }
5a137c3f963f77ca45433485f63c52a2e99a2553
[ "Java" ]
1
Java
Ravibhushan222/SpringBoot-app-using-my-Sql
765d137b914e3d46e5e063d6865964e323cccf0d
135865ac9272009e2a1ceb95bf858254e61ce62c
refs/heads/develop
<file_sep>package org.fundacionjala.pivotal.ui.pages.LoggedIn; import org.fundacionjala.core.selenium.GuiInteractioner; import org.fundacionjala.pivotal.ui.component.EditProfileForm; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Supplier; public class ProfilePage extends BaseLoggedInPage { private EditProfileForm editProfileForm; /** * Constructor for ProfilePage. */ public ProfilePage() { editProfileForm = new EditProfileForm(); } @FindBy(css = "#general.card ul.rows.read li:nth-child(1) div") private WebElement profileUserName; @FindBy(css = "#general.card ul.rows.read li:nth-child(2) div") private WebElement profileName; @FindBy(css = "#general.card ul.rows.read li:nth-child(3) div") private WebElement profileInitials; @FindBy(css = "#email_and_password ul li:nth-child(1) div") private WebElement profileEmail; @FindBy(css = ".edit_button.header_button") private WebElement editProfileBtn; @FindBy(css = "#general_flash span") private WebElement changesNotifier; @FindBy(css = ".user_management_header div:nth-child(1)") private WebElement userManagementMenuTitle; private String getProfileInformationAsString(final WebElement webElement) { return GuiInteractioner.getTextFromWebElement(webElement); } /** * Find the User Name from the Profile Page as String. * @return User name as String */ public String getProfileUserNameAsString() { return getProfileInformationAsString(profileUserName); } /** * Find the Email from the Profile Page as String. * @return User name as String */ public String getProfileEmailAsString() { return getProfileInformationAsString(profileEmail); } private String getProfileNameAsString() { return getProfileInformationAsString(profileName); } private String getProfileInitialsAsString() { return getProfileInformationAsString(profileInitials); } private void clickEditProfileButton() { GuiInteractioner.clickWebElement(editProfileBtn); } /** * Returns the EditProfileForm clicking at EditProfileBtn. * @return editProfileForm */ public EditProfileForm getEditProfileForm() { clickEditProfileButton(); return editProfileForm; } /** * Gets the inner text on changes notifier. * @return text from changes notifier */ public String getTextFromChangesNotifier() { return GuiInteractioner.getTextFromWebElement(changesNotifier); } private HashMap<String, Supplier<String>> composeStrategyGetterMap() { HashMap<String, Supplier<String>> strategyMap = new HashMap<>(); strategyMap.put("User name", () -> getProfileUserNameAsString()); strategyMap.put("Name", () -> getProfileNameAsString()); strategyMap.put("Initials", () -> getProfileInitialsAsString()); return strategyMap; } /** * Gets edited user information described in the Profile Page as a Map. * @param editedFields set of edited fields * @return a Map with user information present in the Profile Page */ public Map<String, String> getUserEditedInfoAsMap(final Set<String> editedFields) { Map userInfoMap = new HashMap<String, String>(); editedFields.forEach(field -> userInfoMap.put(field, composeStrategyGetterMap().get(field).get())); return userInfoMap; } /** * Gets the User Management Menu Title. * @return User Management Menu Title as String */ public String getUserManagementMenuTitleAsString() { return GuiInteractioner.getTextFromWebElement(userManagementMenuTitle); } } <file_sep>package org.fundacionjala.core.selenium; import org.fundacionjala.core.selenium.browsers.Browser; import org.fundacionjala.core.selenium.browsers.BrowserParser; import org.fundacionjala.core.selenium.browsers.browserTypes.ChromeBrowser; import org.fundacionjala.core.selenium.browsers.browserTypes.EdgeBrowser; import org.fundacionjala.core.selenium.browsers.browserTypes.FirefoxBrowser; import org.fundacionjala.core.selenium.browsers.browserTypes.IBrowser; import org.openqa.selenium.WebDriver; import java.io.IOException; import java.util.HashMap; import java.util.Map; public final class BrowserFactory { /** * Constructor for the BrowserFactory class. */ private BrowserFactory() { } private static Map<String, IBrowser> browsersMap = new HashMap<>(); static { browsersMap.put("chrome", new ChromeBrowser()); browsersMap.put("firefox", new FirefoxBrowser()); browsersMap.put("edge", new EdgeBrowser()); } /** * Gets a webDriver providing its name. * @param browserName name of the browser * @return a webDriver */ public static WebDriver getWebDriver(final String browserName) { return browsersMap.get(browserName).initDriver(); } /** * Gets a driverProps providing the browser name. * @param browserName name of the browser * @return Driver Properties of the browser * @thows IOException */ public static Browser getDriverProps(final String browserName) throws IOException { return BrowserParser.getBrowsersMap().get(browserName); } } <file_sep>baseUrl=https://www.pivotaltracker.com/ baseApiUrl=https://www.pivotaltracker.com/services/v5/<file_sep># Pivotal GUI Automation Initial Project for Pivotal Tracker GUI Automation Testing. by: <NAME> <file_sep>package org.fundacionjala.core.config; import org.fundacionjala.core.selenium.WebDriverManager; public final class PropertiesSetter { private PropertiesSetter() { } /** * Sets dataproviderthreadcount property. * * @param threadCount defined number for threadCount */ public static void setDataProviderThreadCountProp(final String threadCount) { System.setProperty("dataproviderthreadcount", threadCount); } /** * Sets the Test Browser to run test Scenarios. * * @param browserName name of default browser */ public static void setTestBrowser(final String browserName) { WebDriverManager.setBrowserName(browserName); } } <file_sep>cucumberThreadCount=1 filterTags= testBrowser=edge<file_sep>package org.fundacionjala.pivotal.context; import org.fundacionjala.pivotal.entities.EntitiesParser; import org.fundacionjala.pivotal.entities.Project; import org.fundacionjala.pivotal.entities.Story; import org.fundacionjala.pivotal.entities.User; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Context { private final List<User> usersList; private final List<Project> projectList; private final List<String> editedUsersList; private final List<Project> projectListToDelete; private final List<Story> storyToDelete; /** * Constructor for Context class. */ public Context() throws IOException { this.usersList = EntitiesParser.getUsersListFromJson(); this.projectList = EntitiesParser.getProjectListFromJson(); this.editedUsersList = new ArrayList<>(); this.projectListToDelete = new ArrayList<>(); this.storyToDelete = new ArrayList<>(); } /** * Searches for a specific User in userList by a provided alias. * @param alias provided alias * @return User if the alias matches, otherwise return null. */ public User getUserByAlias(final String alias) { for (User user : this.usersList) { if (alias.equals(user.getAlias())) { return user; } } return null; } /** * Searches for a specific Project in projectList providing its name. * @param projectName provided to search * @return Project if the name matches, otherwise return null. */ public Project getProjectByName(final String projectName) { for (Project project : this.projectList) { if (projectName.equals(project.getName())) { return project; } } return null; } /** * Get the List of Edited Users. * @return editedUsersList */ public List<String> getEditedUsersList() { return editedUsersList; } /** * Get the List of Projects to delete after some Test Scenarios. * @return projectListToDelete */ public List<Project> getProjectListToDelete() { return projectListToDelete; } /** * Get the List of Stories to delete after some Test Scenarios. * @return projectListToDelete */ public List<Story> getStoryToDelete() { return storyToDelete; } } <file_sep>package org.fundacionjala.pivotal.entities; import org.fundacionjala.core.utils.IdGenerator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Supplier; public class User { private String alias; private Set<String> editedFields; // My profile section private String userName; private String name; private String initials; // Email & Password private String email; private String password; // API Token private String token; private static final String KEY_ALIAS = "Alias"; private static final String KEY_NAME = "Name"; private static final String KEY_INITIALS = "Initials"; private static final String KEY_EMAIL = "Email"; private static final String KEY_PASSWORD = "<PASSWORD>"; private static final String KEY_USERNAME = "User name"; private static final String KEY_TOKEN = "Token"; private static final String STRING_TO_CHANGE = "UNIQUE_ID"; /** * Get the edited Fields for a User. * @return editedFields */ public Set<String> getEditedFields() { return editedFields; } /** * Set the Fields which were edited for a User. * @param edited */ public void setEditedFields(final Set<String> edited) { this.editedFields = edited; } /** * Gets the Alias from a User. * @return alias */ public String getAlias() { return alias; } /** * Sets Alias to a User. * @param userAlias */ public void setAlias(final String userAlias) { this.alias = userAlias; } /** * Gets the Email from a User. * @return email */ public String getEmail() { return email; } /** * Sets Email to a User. * @param userEmail */ public void setEmail(final String userEmail) { this.email = userEmail; } /** * Gets the Password from a User. * @return password */ public String getPassword() { return password; } /** * Sets Password to a User. * @param userPassword */ public void setPassword(final String userPassword) { this.password = <PASSWORD>; } /** * Sets UserName to a User. * @param userUserName */ public void setUserName(final String userUserName) { userName = userUserName.replaceAll(STRING_TO_CHANGE, IdGenerator.getUniqueId()); } /** * Gets the UserName from a User. * @return UserName */ public String getUserName() { return userName; } /** * Sets Name to a User. * @param usName */ public void setName(final String usName) { this.name = usName; } /** * Gets the Name from a User. * @return name */ public String getName() { return name; } /** * Sets Initials to a User. * @param userInitials */ public void setInitials(final String userInitials) { this.initials = userInitials; } /** * Gets the Initials from a User. * @return initials. */ public String getInitials() { return initials; } /** * Sets token to a User. * @param userToken */ public void setToken(final String userToken) { this.token = userToken; } /** * Gets the token from a User. * @return token. */ public String getToken() { return token; } private HashMap<String, Runnable> composeMapStrategy(final Map<String, String> userInformation) { HashMap<String, Runnable> strategyMap = new HashMap<>(); strategyMap.put(KEY_ALIAS, () -> setAlias(userInformation.get(KEY_ALIAS))); strategyMap.put(KEY_NAME, () -> setName(userInformation.get(KEY_NAME))); strategyMap.put(KEY_INITIALS, () -> setInitials(userInformation.get(KEY_INITIALS))); strategyMap.put(KEY_EMAIL, () -> setEmail(userInformation.get(KEY_EMAIL))); strategyMap.put(KEY_PASSWORD, () -> setPassword(userInformation.get(KEY_PASSWORD))); strategyMap.put(KEY_USERNAME, () -> setUserName(userInformation.get(KEY_USERNAME))); strategyMap.put(KEY_TOKEN, () -> setToken(userInformation.get(KEY_TOKEN))); return strategyMap; } /** * Process all information stored for a User as a map. * @param userInformation */ public void processInformation(final Map<String, String> userInformation) { HashMap<String, Runnable> strategyMap = composeMapStrategy(userInformation); userInformation.keySet().forEach(key -> strategyMap.get(key).run()); } private HashMap<String, Supplier<String>> composeStrategyGetterMap() { HashMap<String, Supplier<String>> strategyMap = new HashMap<>(); strategyMap.put(KEY_ALIAS, () -> getAlias()); strategyMap.put(KEY_NAME, () -> getName()); strategyMap.put(KEY_INITIALS, () -> getInitials()); strategyMap.put(KEY_EMAIL, () -> getEmail()); strategyMap.put(KEY_USERNAME, () -> getUserName()); strategyMap.put(KEY_PASSWORD, () -> getPassword()); strategyMap.put(KEY_TOKEN, () -> getToken()); return strategyMap; } /** * Gets Edited User Info as Map. * @return a Map with edited user info */ public Map<String, String> getEditedInfo() { Map userInfoMap = new HashMap<String, String>(); editedFields.forEach(field -> userInfoMap.put(field, composeStrategyGetterMap().get(field).get())); return userInfoMap; } } <file_sep>package org.fundacionjala.core.selenium.browsers; public class Browser { private String name; private String implicitWaitingSeconds; private String explicitWaitingSeconds; private String sleepingTimeMills; /** * Get browser's name. * @return name */ public String getName() { return name; } /** * Get browser's implicitWaitingSeconds. * @return implicitWaitingSeconds */ public String getImplicitWaitingSeconds() { return implicitWaitingSeconds; } /** * Get browser's explicitWaitingSeconds. * @return explicitWaitingSeconds */ public String getExplicitWaitingSeconds() { return explicitWaitingSeconds; } /** * Get browser's sleepingTimeMills. * @return sleepingTimeMills */ public String getSleepingTimeMills() { return sleepingTimeMills; } } <file_sep>package org.fundacionjala.pivotal.entities; public class Story { private String id; private String name; /** * Constructor for Story class. * @param storyName of the Story */ public Story(String storyName) { this.name = storyName; } /** * Gets the id of the story. * @return id */ public String getId() { return id; } /** * Sets the id of the story. * @param storyId */ public void setId(String storyId) { this.id = storyId; } /** * Gets the name of the story. * @return name */ public String getName() { return name; } /** * Sets the name of the story. * @param storyName */ public void setName(String storyName) { this.name = storyName; } } <file_sep>package org.fundacionjala.core.selenium; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.List; public final class GuiInteractioner { private GuiInteractioner() { } private static WebElement findElementBy(final By by) { return WebDriverManager.getInstance().getWebDriver().findElement(by); } /** * Clears the previous text in a WebElement and fills a new text into it. * * @param webElement to set text * @param text text to be set */ public static void setInputText(final WebElement webElement, final String text) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.visibilityOf(webElement)); webElement.clear(); webElement.sendKeys(text); } /** * Provide fillWebElement method to support By objects. * * @param by element found to set text * @param text text to be set */ public static void setInputText(final By by, final String text) { setInputText(findElementBy(by), text); } /** * Waits for a WebElement to be clickable and clicks it. * * @param webElement to be clicked */ public static void clickWebElement(final WebElement webElement) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.elementToBeClickable(webElement)); webElement.click(); } /** * Provide clickWebElement method to support By objects. * * @param by element found to be clicked */ public static void clickWebElement(final By by) { clickWebElement(findElementBy(by)); } /** * Scrolls down until find a WebElement. * * @param webElement to be found in the page */ public static void scrollDownToFindElement(final WebElement webElement) { JavascriptExecutor js = (JavascriptExecutor) WebDriverManager.getInstance().getWebDriver(); js.executeScript("arguments[0].scrollIntoView();", webElement); } /** * Searches for a WebElement and get the inner text. * * @param webElement to get text * @return String text from the WebElement. */ public static String getTextFromWebElement(final WebElement webElement) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.visibilityOf(webElement)); return webElement.getText(); } /** * Provide getTextFromWebElement method to support By objects. * * @param by element found to get text * @return String text from the By. */ public static String getTextFromWebElement(final By by) { return getTextFromWebElement(findElementBy(by)); } /** * Searches for an specific option in a list, then clicks it. * * @param webElementList list of elements * @param selected ,text of the searched element to be clicked */ public static void clickOptionFromWebElementList(final List<WebElement> webElementList, final String selected) { for (WebElement option : webElementList) { if (option.getText().contains(selected)) { option.click(); break; } } } /** * Searches for an specific option WebElement that contains a text. * * @param webElementList list of elements * @param text of the searched element * @return WebElement if it can find it, otherwise return null */ public static WebElement searchTextInWebElementList(final List<WebElement> webElementList, final String text) { for (WebElement element : webElementList) { if (element.getText().contains(text)) { return element; } } return null; } /** * Get the state of a Web Element. * * @param webElement to ask for its state * @return true if the WebElement is selected, otherwise return false */ public static boolean getStateOfWebElement(final WebElement webElement) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.visibilityOf(webElement)); return webElement.isSelected(); } /** * Provide getStateOfWebElement method to support By objects. * * @param by element to ask for its state * @return true if the WebElement is selected, otherwise return false */ public static boolean getStateOfWebElement(final By by) { return getStateOfWebElement(findElementBy(by)); } /** * Gets the inner value of a specific attribute of a WebElement. * * @param webElement to get attribute's value * @param attribute of the WebElement * @return a String with the value of the attribute, otherwise return null */ public static String getAttributeOfWebElement(final WebElement webElement, final String attribute) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.visibilityOf(webElement)); return webElement.getAttribute(attribute); } /** * Provide getAttributeOfWebElement method to support By objects. * * @param by element to get attribute's value * @param attribute of the By element * @return a String with the value of the attribute, otherwise return null */ public static String getAttributeOfWebElement(final By by, final String attribute) { return getAttributeOfWebElement(findElementBy(by), attribute); } public static void dragElementAndDropTo(WebElement elementToDrag, WebElement elementToDropTo) { WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.elementToBeClickable(elementToDrag)); WebDriverManager.getInstance().getWebDriverWait().until(ExpectedConditions.visibilityOf(elementToDropTo)); Actions act = new Actions(WebDriverManager.getInstance().getWebDriver()); act.dragAndDrop(elementToDrag, elementToDropTo).build().perform(); } public static void dragElementAndDropTo(By elementToDrag, WebElement elementToDropTo) { dragElementAndDropTo(findElementBy(elementToDrag), elementToDropTo); } } <file_sep>package org.fundacionjala.pivotal.cucumber.steps; import io.cucumber.java.en.When; import org.fundacionjala.core.throwables.PropertiesReadingException; import org.fundacionjala.pivotal.ui.WebTransporter; import java.net.MalformedURLException; public class NavigationSteps { /** * Navigates towards any URL. * @param pageName * @throws MalformedURLException */ @When("^I navigate to (.*?) page$") public void navigateToPage(final String pageName) throws MalformedURLException, PropertiesReadingException { WebTransporter.navigateToPage(pageName); } /** * Reloads the browser. */ @When("I reload the page") public void reloadPage() { WebTransporter.reloadPage(); } }
787b5e46d4865fcde2287164970224052462d44e
[ "Markdown", "Java", "INI" ]
12
Java
GUI-Automation-AT12/mirko_pivotal_gui-test
3e58d04dcd1738048453c625022a32bad13d27ae
2cb4daa639a8e2c7aa2559f46397c0ed57ae7f53
refs/heads/master
<file_sep><?php //print_r($this->estadoMatricula); //die; ?> <center> <table class="table table-condensed"> <tr> <th colspan="6" class="nombreTabla text-center">Lista de Habitaciones</th> </tr> <tr> <th>Numero</th> <th>Piso</th> <th>Tipo</th> </tr> <?php $con = 1; $mensaje = "'¿Desea eliminar esta habitacion?'"; foreach ($this->listaHabitacion as $lista => $value) { echo '<tr>'; echo '<td>'; echo $value['numero']; echo '</td>'; echo '<td>'; echo $value['piso']; echo '</td>'; echo '<td>'; echo $value['tipo']; echo '</td>'; echo '</tr>'; $con++; } ?> <tr> <td colspan='6' class="lineaFin"></td> </tr> <tr> <td colspan='6'>Última línea</td> </tr> </table> </center><file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Editar Check out</h1> <form id="MyForm" action="<?php echo URL; ?>factura/actualizarFactura" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS DE FACTURA</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombreCliente" class="col-xs-2 control-label">Cliente : </label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_nombreCliente" id="txt_nombreCliente"> <option value="">Seleccione...</option> <?php foreach ($this->consultaCliente as $value) { echo "<option value='" . $value['nombre'] . "' "; if ($value['nombre'] == $this->datosFactura[0]['nombreCliente']) echo "selected"; ?> > <?php echo $value['nombre'] . "</option>"; } ?> </select> </div> <div class="form-group"> <label for="txt_habitacion" class="col-xs-2 control-label">Tipo Habitación:</label> <div class="col-xs-2"> <select class="form-control input-sm validate[required]" name="txt_habitacion" id="txt_habitacion"> <option value="">Seleccione...</option> <?php foreach ($this->consultaTipoHabitacion as $value) { echo "<option value='" . $value['id'] . "' "; if ($value['id'] == $this->datosFactura[0]['habitacion']) echo "selected"; ?> > <?php echo $value['descripcion'] . "</option>"; } ?> </select> </div> <label for="txt_numeroFactura" class="col-xs-2 control-label">Numero Habitación:</label> <div class="col-xs-1"> <input type="text" class=" form-control input-sm validate[required]" id="txt_numeroFactura" name="txt_numeroFactura" value='<?php echo $this->datosFactura[0]['numeroFactura']; ?>'disabled/> <input type="hidden" id="txt_habitacion" name="txt_numeroFactura" value='<?php echo $this->datosFactura[0]['numeroFactura']; ?>'/> </div> </div> <label for="txt_ingreso" class="col-xs-2 control-label">Ingreso:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_ingreso" name="txt_ingreso" value='<?php echo $this->datosFactura[0]['ingreso']; ?>'/> </div> <label for="txt_estadia" class="col-xs-2 control-label">Estadia:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_estadia" name="txt_estadia" value='<?php echo $this->datosFactura[0]['estadia']; ?>'/> </div> <br> <br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Guardar" /> </div> </div> </fieldset> </form> </div><file_sep><?php //print_r($this->estadoMatricula); //die; ?> <center> <br> <div class="col-xs-3"> Búsqueda por identificación: </div> <div class="col-xs-1"> <input type="text" class="input-sm validate[required]" name="tf_cedulaEstudiante" id="tf_cedulaEstudiante" /> </div> <div class="col-xs-2"> <input type="button" class="btn-sm btn-success" id="buscarEstudianteRatificar" value="Buscar" /> </div> <br><br> <br> <table class="table table-condensed" id="tablaRatificar"> <tr> <th colspan="6" class="nombreTabla text-center">Lista de Funcionarios</th> </tr> <tr> <th>ID</th> <th>Nombre</th> <th>Puesto</th><?php if (Session::get('tipoUsuario') <= 1) { ?> <th colspan="2" class="text-center">Acción</th> <?php } ?> </tr> <?php $con = 1; $mensaje = "'¿Desea eliminar esta compra?'"; foreach ($this->listaFuncionarios as $lista => $value) { echo '<tr>'; echo '<td>'; echo $value['id']; echo '</td>'; echo '<td>'; echo $value['nombre']; echo '</td>'; echo '<td>'; echo $value['puesto']; echo '</td>'; echo '<td class=text-center>'; ?> <?php if (Session::get('tipoUsuario') <= 1) { ?> <?php echo '<a class="btn-sm btn-primary" href="editarCompra/' . $value['id'] . '">Editar</a>&nbsp &nbsp &nbsp'; echo '<a class="btn-sm btn-warning" href="eliminarFuncionario/' . $value['id'] . '" onclick ="return confirm(' . $mensaje . ')">Eliminar</a>'; ?> <?php } ?> <?php echo '</td>'; echo '</tr>'; $con++; } ?> <tr> <td colspan='6' class="lineaFin"></td> </tr> <tr> <td colspan='6'>Última línea</td> </tr> </table> </center><file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"/> <title><?= (isset($this->title)) ? $this->title : ''; ?></title> <link rel="stylesheet" type="text/css" href="<?php echo URL; ?>public/css/bootstrap-Solar- 337.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="<?php echo URL; ?>public/css/bootstrap-responsive.min.css"> <link rel="stylesheet" href="<?php echo URL; ?>public/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" media="all" href="<?php echo URL; ?>public/css/smoothness/jquery-ui-1.8.24.custom.css"> <link rel="stylesheet" type="text/css" media="all" href="<?php echo URL; ?>public/css/jQueryValidationEngine/validationEngine.jquery.css"> <link rel="stylesheet" type="text/css" media="all" href="<?php echo URL; ?>public/css/jQueryValidationEngine/template.css"> <script type="text/javascript" src="<?php echo URL; ?>public/js/jquery-1.8.2.min.js"></script> <script type="text/javascript" src="<?php echo URL; ?>public/js/jquery-ui-1.8.24.custom.min.js"></script> <script type="text/javascript" src="<?php echo URL; ?>public/js/jQueryValidationEngine/jquery.validationEngine.js"></script> <script type="text/javascript" src="<?php echo URL; ?>public/js/jQueryValidationEngine/languages/jquery.validationEngine-es.js"></script> <!--<script src="<?php echo URL; ?>public/js/jquery-1.11.1.js"></script>--> <script src="<?php echo URL; ?>public/js/bootstrap.min.js"></script> <script type="text/javascript" src="<?php echo URL; ?>public/js/hora.js"></script> <?php if (isset($this->js)) { foreach ($this->js as $js) { echo '<script type="text/javascript" src="' . URL . 'views/' . $js . '"></script>'; } } ?> <script type="text/javascript"> jQuery(document).ready(function () { //validar campos jQuery("#MyForm").validationEngine(); //mostrar mensaje //$(".mensajes").show(); //$('#datetime').jTime(); }); </script> </head> <body> <?php Session::init(); ?> <!--Si esta logeded--> <!--Menu--> <?php if (Session::get('loggedIn') == true): ?> <div class="row"> <div class="col-xs-12"> <nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo URL; ?>index/index">Inicio</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <?php if (Session::get('tipoUsuario') <= 1) { ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Funcionario<span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="<?php echo URL; ?>funcionario/agregarfuncionario">Agregar Funcionario</a></li> <li><a href="<?php echo URL; ?>funcionario/verFuncionarios">Ver Funcionarios</a></li> </ul> </li> <?php } ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Habitación <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <?php if (Session::get('tipoUsuario') == 3) { ?> <li><a href="<?php echo URL; ?>habitacionCliente/verHabitacionCliente">Ver Habitación</a></li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li><a href="<?php echo URL; ?>habitacion/agregarHabitacion">Agregar habitación</a></li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li><a href="<?php echo URL; ?>habitacion/verHabitacion">Ver Habitación</a></li> <?php } ?> </ul> </li> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Cliente <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="<?php echo URL; ?>cliente/agregarCliente">Agregar Cliente</a></li> <li><a href="<?php echo URL; ?>cliente/verClientes">Ver Cliente</a></li> </ul> </li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Check In <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="<?php echo URL; ?>factura/agregarFactura">Check In</a></li> <li><a href="<?php echo URL; ?>factura/verFacturas">Ver Check In</a></li> </ul> </li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li><a class="navbar-nav" href="<?php echo URL; ?>precio/verPrecio">Precio</a></li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li><a class="navbar-nav" href="<?php echo URL; ?>compra/agregarCompra">Compras u otros cargos</a></li> <?php } ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <li><a class="navbar-nav" href="<?php echo URL; ?>rackHabitacion/rackMensual">Rack Mensual</a></li> <?php } ?> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-user"></i> <?php echo $_SESSION['nombre']; ?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Editar perfil</a></li> <li><a href="<?php echo URL; ?>dashboard/logout">Salir</a></li> </ul> </li> </ul> </div> </div> </nav> </div> </div> <!--Si no esta loged--> <?php else: ?> <div class="row"> <div class="col-xs-12"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo URL; ?>index/index">Inicio</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="<?php echo URL; ?>login">Iniciar Sesión</a></li> </ul> <ul class="nav navbar-nav"> <li><a href="<?php echo URL; ?>registrarse/agregarUsuario">Registrarse</a></li> </ul> </div> </div> </nav> </div> </div> <?php endif; ?> <br><br><br> <!--Contenido para mostrar todas las paginas--> <div class="row"> <div class="col-xs-1"></div> <div class="col-xs-1"> <img src="<?php echo URL; ?>public/img/HoteleriaTurismo.png" alt="Logo Empresa" class="img-rounded pull-left img-responsive"> </div> <div class="col-xs-8 text-center"> <div class="row"> <div class="col-xs-12"> <h2>Hoteleria Turismo</h1> <h4><p class="text-success">Colegio Técnico Profesional de Carrizal, Dirección Regional de Alajuela Circuito -01-</p></h4> <!--<label id="datetime" size="50"></label>--> </div> </div> </div> <div class="col-xs-1"> <img src="<?php echo URL; ?>public/img/logoctpcarrizal.png" alt="Logo CTPC" class="img-rounded pull-right img-responsive"> </div> <div class="col-xs-1"></div> </div> <div class="container"> <div class="row"> <div class="col-xs-12"> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <form id="MyForm" action="<?php echo URL; ?>factura/guardarFactura" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">Check In</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombreCliente" class="col-xs-2 control-label">Cliente : </label> <div class="col-xs-2"> <select class="form-control input-sm validate[required]" name="txt_nombreCliente" id="txt_nombreCliente"> <option value="">Seleccione Cliente</option> <?php foreach ($this->consultaCliente as $value) { echo "<option value='" . $value['nombre'] . "'>"; echo $value['nombre'] . "</option>"; } ?> </select> </div> <label for="txt_tipo" class="col-xs-2 control-label">Tipo:</label> <div class="col-xs-2"> <select class="form-control input-sm validate[required]" name="txt_tipo" id="txt_tipo"> <option value="">Seleccione...</option> <?php foreach ($this->consultaTipoHabitacion as $value) { echo "<option value='" . $value['id'] . "'>"; echo $value['descripcion'] . "</option>"; } ?> </select> </div> <label for="txt_numeroFactura" class="col-xs-2 control-label">Numero Habitación:</label> <div class="col-xs-2"> <select class="form-control input-sm validate[required]" name="txt_numeroFactura" id="txt_numeroFactura"> <option value="">Seleccione...</option> <?php foreach ($this->buscarHabitacionesLibres as $value) { echo "<option value='" . $value['numero'] . "'>"; echo $value['numero'] . "</option>"; } ?> </select> </div> </br> </br> <label for="txt_ingreso" class="col-xs-2 control-label">Fecha de Ingreso:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_ingreso" name="txt_ingreso"/> </div> <label for="txt_estadia" class="col-xs-2 control-label">Fecha de Salida:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_estadia" name="txt_estadia"/> </div> </div> </div> </br> </br> <!--L3 Fecha Nacimiento (Formulario Hugo)--> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Check In" /> </div> </div> </fieldset> </form> </div><file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <form id="MyForm" action="<?php echo URL; ?>funcionario/guardarFuncionario" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">Agregar Funcionario</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombre" class="col-xs-2 control-label">Nombre completo:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_nombre" name="txt_nombre"/> </div> <label for="txt_id" class="col-xs-2 control-label">ID:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm" id="txt_id" name="txt_id"/> </div> <label for="txt_puesto" class="col-xs-2 control-label">Puesto:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_puesto" name="txt_puesto"/> </div> </div> </br> </br> <!--L3 Fecha Nacimiento (Formulario Hugo)--> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Agregar funcionario" /> </div> </div> </fieldset> </form> </div><file_sep><?php Class Registrarse_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Usuario public function guardarUsuario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM usuario " . "WHERE nombreUsuario = '" . $datos['txt_nombreUsuario'] . "' "); if ($consultaExistenciaPreMatricula != null) { echo 'Error...</br>Ya existe un usuario con ese ID'; die; } else { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('usuario', array( 'password' => $<PASSWORD>['<PASSWORD>'], 'nombreUsuario' => $datos['txt_nombreUsuario'], 'nombre' => $datos['txt_nombre'], 'tipoUsuario' => $datos['txt_tipoUsuario'])); } } public function listaUsuarios() { //ver Funcionarios $consultaUsuarios = $this->db->select("SELECT * FROM usuario "); return $consultaUsuarios; } public function datosUsuario($id) { $consultaExistenciaUsuario = $this->db->select("SELECT * FROM usuario " . "WHERE id = " . $id . " "); if ($consultaExistenciaUsuario != null) { return $consultaExistenciaUsuario; } else { echo 'No se ha encontrado el Usuario'; die; } } public function actualizarUsuario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM usuario " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'puesto' => $datos['txt_puesto']); $this->db->update('funcionario', $posData, "`id` = '{$datos['txt_id']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } } public function eliminarFuncionario($id) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM usuario " . "WHERE id = '" . $id . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('usuario', "`id` = '{$id}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un usuario con ese ID'; die; } } public function buscarEstuRatif($ced_estudiante) { $resultado = $this->db->select("SELECT * " . "FROM funcionario " . "WHERE id = '" . $ced_estudiante . "'"); echo json_encode($resultado); } } ?> <file_sep><?php class Precio extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad2(); $this->view->js = array('habitacion/js/jsHabitacion.js'); } function verPrecio() { $this->view->title = 'Habitacion'; $this->view->render('header'); $this->view->listaTipoHabitacion = $this->model->listaTipoHabitacion(); $this->view->render('precio/verPrecio'); $this->view->render('footer'); } function editarPrecio($id) { $this->view->title = 'Precio'; $this->view->render('header'); $this->view->listaTipoHabitacion = $this->model->listaTipoHabitacion(); $this->view->datosTipoHabitacion = $this->model->datosTipoHabitacion($id); $this->view->render('precio/editarPrecio'); $this->view->render('footer'); } function actualizarPrecio() { $datos = array(); $datos ['txt_tipo'] = $_POST['txt_tipo']; $datos ['txt_precio'] = $_POST['txt_precio']; $datos ['txt_moneda'] = $_POST['txt_moneda']; $this->model->actualizarHabitacion($datos); header("location: " . URL . "precio/verPrecio"); } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Editar Funcionario</h1> <form id="MyForm" action="<?php echo URL; ?>funcionario/actualizarFuncionario" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS DEL FUNCIONARIO</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombre" class="col-xs-2 control-label">Nombre Completo:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_nombre" name="txt_nombre" value='<?php echo $this->datosFuncionario[0]['nombre']; ?>'/> </div> <label for="txt_id" class="col-xs-2 control-label">ID:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm" id="txt_id" name="txt_id" value='<?php echo $this->datosFuncionario[0]['id']; ?>' disabled/> <input type="hidden" id="txt_id" name="txt_id" value='<?php echo $this->datosFuncionario[0]['id']; ?>'/> </div> <label for="txt_puesto" class="col-xs-2 control-label">Puesto:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_puesto" name="txt_puesto" value='<?php echo $this->datosFuncionario[0]['puesto']; ?>'/> </div> </div> <br><br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Guardar" /> </div> </div> </fieldset> </form> </div><file_sep><?php class Habitacion extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad2(); $this->view->js = array('habitacion/js/jsHabitacion.js'); } function agregarHabitacion() { $this->view->title = 'Habitacion'; $this->view->render('header'); $this->view->render('habitacion/agregarHabitacion'); $this->view->render('footer'); } function verHabitacion() { $this->view->title = 'Habitacion'; $this->view->render('header'); $this->view->listaHabitacion = $this->model->listaFuncionarios(); $this->view->render('habitacion/verHabitacion'); $this->view->render('footer'); } function guardarHabitacion() { $datos = array(); $datos ['txt_numero'] = $_POST['txt_numero']; $datos ['txt_piso'] = $_POST['txt_piso']; $datos ['txt_tipo'] = $_POST['txt_tipo']; $this->model->guardarHabitacion($datos); header("location: " . URL . "habitacion/verHabitacion"); } function editarHabitacion($numero) { $this->view->title = 'Habitacion'; $this->view->render('header'); $this->view->datosHabitacion = $this->model->datosHabitacion($numero); $this->view->listaHabitaciones = $this->model->listaHabitaciones(); $this->view->render('habitacion/editarHabitacion'); $this->view->render('footer'); } function actualizarHabitacion() { $datos = array(); $datos ['txt_numero'] = $_POST['txt_numero']; $datos ['txt_piso'] = $_POST['txt_piso']; $datos ['txt_tipo'] = $_POST['txt_tipo']; $this->model->actualizarHabitacion($datos); header("location: " . URL . "habitacion/verHabitacion"); } function eliminarHabitacion($numero) { $this->view->title = 'Habitacion'; $this->model->eliminarHabitacion($numero); header("location: " . URL . "habitacion/verHabitacion"); } function buscarEstuRatif($ced_estudiante) { $this->model->buscarEstuRatif($ced_estudiante); } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <form id="MyForm" action="<?php echo URL; ?>compra/actualizarCompra" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">Agregar Compra</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_numeroH" class="col-xs-2 control-label">Numero Habitación:</label> <div class="col-xs-2"> <select class="form-control input-sm validate[required]" name="txt_numeroH" id="txt_numeroH"> <option value="">Seleccione...</option> <?php foreach ($this->consultaHabitacionOcupada as $value) { echo "<option value='" . $value['numeroFactura'] . "'>"; echo $value['numeroFactura'] . "</option>"; } ?> </select> </div> <label for="txt_compra" class="col-xs-2 control-label">Lista de Compras:</label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_compra" id="txt_compra"> <option value="">Seleccione...</option> <?php foreach ($this->consultaProductos as $value) { echo "<option value='" . $value['id'] . "'>"; echo $value['descripcion'] . "</option>"; } ?> </select> </div> </div> </br> </br> <!--L3 Fecha Nacimiento (Formulario Hugo)--> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Agregar compra" /> </div> </div> </fieldset> </form> </div><file_sep><?php class RackHabitacion_Model extends Models { //El constructor invoca al padre que esta en "libs/Model", este posee una variable llamada "db" con el acceso a la BD //db es un objeto "Database" y posee las siguientes funciones: select, insert, update y delete public function __construct() { parent::__construct(); } public function listaFacturas() { //ver Facturas $consultaFacturas = $this->db->select("SELECT * FROM factura "); return $consultaFacturas; } public function consultaNuHabitacion() { //ver Clientes $consultaNuHabitacion = $this->db->select("SELECT * FROM habitacion "); return $consultaNuHabitacion; } public function consultaTipoHabitacion() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM tipohabitacion "); return $consultaTipo; } public function buscarHabitacionesLibres() { $resultado = $this->db->select("SELECT numero " . "FROM habitacion " . "WHERE numero NOT IN (SELECT numeroFactura FROM factura) "); return $resultado; } } <file_sep><?php class Registrarse extends Controllers { function __construct() { parent::__construct(); $this->view->js = array('funcionario/js/jsFuncionario.js'); } function agregarUsuario() { $this->view->title = 'usuario'; $this->view->render('header'); $this->view->render('registrarse/agregarUsuario'); $this->view->render('footer'); } function verUsuario() { $this->view->title = 'Funcionario'; $this->view->render('header'); $this->view->listaFuncionarios = $this->model->listaUsuario(); $this->view->render('funcionario/verFuncionarios'); $this->view->render('footer'); } function guardarUsuario() { $datos = array(); $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_tipoUsuario'] = $_POST['txt_tipoUsuario']; $datos ['txt_contrasena'] = $_POST['txt_contrasena']; $datos ['txt_nombreUsuario'] = $_POST['txt_nombreUsuario']; $this->model->guardarUsuario($datos); header("location: " . URL . "login"); } function editarFuncionario($id) { $this->view->title = 'Funcionario'; $this->view->render('header'); $this->view->datosFuncionario = $this->model->datosFuncionario($id); $this->view->render('funcionario/editarFuncionario'); $this->view->render('footer'); } function actualizarFuncionario() { $datos = array(); $datos ['txt_id'] = $_POST['txt_id']; $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_puesto'] = $_POST['txt_puesto']; $this->model->actualizarFuncionario($datos); header("location: " . URL . "funcionario/verFuncionarios"); } function eliminarFuncionario($id) { $this->view->title = 'Funcionario'; $this->model->eliminarFuncionario($id); header("location: " . URL . "funcionario/verFuncionarios"); } function buscarEstuRatif($ced_estudiante) { $this->model->buscarEstuRatif($ced_estudiante); } } ?> <file_sep><?php class HabitacionCliente extends Controllers { function __construct(){ parent::__construct(); } function verHabitacionCliente(){ $this->view->title = 'Habitacion'; $this->view->render('header'); $this->view->listaHabitacion = $this->model->listaFuncionarios(); $this->view->render('habitacion/verHabitacionCliente'); $this->view->render('footer'); } } ?> <file_sep><?php class Cliente extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad2(); $this->view->js = array('cliente/js/jsCliente.js', 'cliente/js/jsCliente.js'); } function agregarCliente() { $this->view->title = 'Cliente'; $this->view->render('header'); $this->view->render('cliente/agregarCliente'); $this->view->render('footer'); } function verClientes() { $this->view->title = 'Cliente'; $this->view->render('header'); $this->view->listaClientes = $this->model->listaClientes(); $this->view->render('cliente/verClientes'); $this->view->render('footer'); } function guardarCliente() { $datos = array(); $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_id'] = $_POST['txt_id']; $datos ['txt_telefono'] = $_POST['txt_telefono']; $datos ['txt_tarjeta'] = $_POST['txt_tarjeta']; $this->model->guardarCliente($datos); header("location: " . URL . "cliente/verClientes"); } function editarCliente($id) { $this->view->title = 'Cliente'; $this->view->render('header'); $this->view->datosCliente = $this->model->datosCliente($id); $this->view->render('cliente/editarCliente'); $this->view->render('footer'); } function actualizarCliente() { $datos = array(); $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_id'] = $_POST['txt_id']; $datos ['txt_telefono'] = $_POST['txt_telefono']; $datos ['txt_tarjeta'] = $_POST['txt_tarjeta']; $this->model->actualizarCliente($datos); header("location: " . URL . "cliente/verClientes"); } function eliminarCliente($id) { $this->view->title = 'Cliente'; $this->model->eliminarCliente($id); header("location: " . URL . "cliente/verClientes"); } } ?> <file_sep><?php Class Compra_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Funcionario public function guardarFuncionario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciaPreMatricula != null) { echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } else { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('funcionario', array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'puesto' => $datos['txt_puesto'])); } } public function listaFuncionarios() { //ver Funcionarios $consultaFuncionarios = $this->db->select("SELECT * FROM funcionario "); return $consultaFuncionarios; } public function datosFuncionario($id) { $consultaExistenciaFuncionario = $this->db->select("SELECT * FROM funcionario " . "WHERE id = " . $id . " "); if ($consultaExistenciaFuncionario != null) { return $consultaExistenciaFuncionario; } else { echo 'No se ha encontrado el funcionario'; die; } } public function consultaHabitacionOcupada() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM factura "); return $consultaTipo; } public function actualizarFuncionario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'puesto' => $datos['txt_puesto']); $this->db->update('funcionario', $posData, "`id` = '{$datos['txt_id']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } } public function guardarProducto($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $this->db->insert('productos_habitacion', array( 'numeroHabitacion' => $datos['txt_numeroH'], 'idProducto' => $datos['txt_compra'])); } public function eliminarFuncionario($id) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $id . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('funcionario', "`id` = '{$id}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } } public function actualizarCompra($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM factura " . "WHERE numeroFactura = '" . $datos['txt_numeroH'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'otros' => $datos['txt_compra']); $this->db->update('factura', $posData, "`numeroFactura` = '{$datos['txt_numeroH']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe una habitacion con ese numero'; die; } } public function consultaProductos() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM productos "); return $consultaTipo; } } ?> <file_sep><?php class Compra extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad2(); $this->view->js = array('funcionario/js/jsFuncionario.js'); } function agregarCompra() { $this->view->title = 'Compra'; $this->view->render('header'); $this->view->consultaHabitacionOcupada = $this->model->consultaHabitacionOcupada(); $this->view->consultaProductos = $this->model->consultaProductos(); $this->view->render('compras/agregarCompra'); $this->view->render('footer'); } function actualizarCompra() { $datos = array(); $datos ['txt_numeroH'] = $_POST['txt_numeroH']; $datos ['txt_compra'] = $_POST['txt_compra']; $this->model->guardarProducto($datos); header("location: " . URL ); } } ?> <file_sep><?php Class Cliente_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Cliente public function guardarCliente($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciacliente = $this->db->select("SELECT * FROM cliente " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciacliente != null) { echo 'Error...</br>Ya existe un cliente con ese ID'; die; } else { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('cliente', array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'telefono' => $datos['txt_telefono'], 'tarjeta' => $datos['txt_tarjeta'])); } } public function listaClientes() { //ver Clientes $consultaClientes = $this->db->select("SELECT * FROM cliente "); return $consultaClientes; } public function datosCliente($id) { $consultaExistenciaCliente = $this->db->select("SELECT * FROM cliente " . "WHERE id = " . $id . " "); if ($consultaExistenciaCliente != null) { return $consultaExistenciaCliente; } else { echo 'No se ha encontrado el cliente'; die; } } public function actualizarCliente($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciacliente = $this->db->select("SELECT * FROM cliente " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciacliente != null) { $posData = array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'telefono' => $datos['txt_telefono'], 'tarjeta' => $datos['txt_tarjeta']); $this->db->update('cliente', $posData, "`id` = '{$datos['txt_id']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un cliente con ese ID'; die; } } public function eliminarCliente($id) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciacliente = $this->db->select("SELECT * FROM cliente " . "WHERE id = '" . $id . "' "); if ($consultaExistenciacliente != null) { $this->db->delete('cliente', "`id` = '{$id}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un cliente con ese ID'; die; } } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Editar Cliente</h1> <form id="MyForm" action="<?php echo URL; ?>Cliente/actualizarCliente" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS DEL CLIENTE</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombre" class="col-xs-2 control-label">Nombre Completo:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_nombre" name="txt_nombre" value='<?php echo $this->datosCliente[0]['nombre']; ?>'/> </div> <label for="txt_id" class="col-xs-2 control-label">ID:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm" id="txt_id" name="txt_id" value='<?php echo $this->datosCliente[0]['id']; ?>' disabled/> <input type="hidden" id="txt_id" name="txt_id" value='<?php echo $this->datosCliente[0]['id']; ?>'/> </div> <label for="txt_telefono" class="col-xs-2 control-label">Teléfono:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_telefono" name="txt_telefono" value='<?php echo $this->datosCliente[0]['telefono']; ?>'/> </div> <br><br><br> <label for="txt_tarjeta" class="col-xs-2 control-label">Tarjeta de Credito:</label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_nombre" name="txt_tarjeta" value='<?php echo $this->datosCliente[0]['tarjeta']; ?>'/> </div> </div> <br><br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Guardar" /> </div> </div> </fieldset> </form> </div><file_sep><?php Class Factura_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Factura public function guardarFactura($datos) { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('factura', array( 'nombreCliente' => $datos['txt_nombreCliente'], 'habitacion' => $datos['txt_tipo'], 'numeroFactura' => $datos['txt_numeroFactura'], 'ingreso' => $datos['txt_ingreso'], 'estadia' => $datos['txt_estadia'])); } public function listaFacturas() { //ver Facturas $consultaFacturas = $this->db->select("SELECT * FROM factura "); return $consultaFacturas; } public function consultaCliente() { //ver Clientes $consultaCliente = $this->db->select("SELECT * FROM cliente "); return $consultaCliente; } public function consultaNuHabitacion() { //ver Clientes $consultaNuHabitacion = $this->db->select("SELECT * FROM habitacion "); return $consultaNuHabitacion; } public function consultaTipoHabitacion() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM tipohabitacion "); return $consultaTipo; } public function consultaProductos_habitacion() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM productos_habitacion "); return $consultaTipo; } public function consultaProductos() { //ver Clientes $consultaTipo = $this->db->select("SELECT * FROM productos "); return $consultaTipo; } public function datosFactura($numeroFactura) { $consultaExistenciaFactura = $this->db->select("SELECT * FROM factura " . "WHERE numeroFactura = " . $numeroFactura . " "); if ($consultaExistenciaFactura != null) { return $consultaExistenciaFactura; } else { echo 'No se ha encontrado la factura'; die; } } public function actualizarFactura($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM factura " . "WHERE numeroFactura = '" . $datos['txt_numeroFactura'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'nombreCliente' => $datos['txt_nombreCliente'], 'habitacion' => $datos['txt_habitacion'], 'precio' => $datos['txt_precio'], 'numeroFactura' => $datos['txt_numeroFactura'], 'ingreso' => $datos['txt_ingreso'], 'estadia' => $datos['txt_estadia']); $this->db->update('factura', $posData, "`numeroFactura` = '{$datos['txt_numeroFactura']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un factura con ese ID'; die; } } public function actualizarHabitacion($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = '" . $datos['txt_numeroFactura'] . "' "); if ($consultaExistenciaPreMatricula != null) { $num = 1; $posData = array( 'Estado' => $num); $this->db->update('habitacion', $posData, "`numero` = '{$datos['txt_numero']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe una habitacion con ese numero'; die; } } public function eliminarFactura($numeroFactura) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM factura " . "WHERE numeroFactura = '" . $numeroFactura . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('factura', "`numeroFactura` = '{$numeroFactura}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un factura con ese ID'; die; } $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM productos_habitacion " . "WHERE numeroHabitacion = '" . $numeroFactura . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('productos_habitacion', "`numeroHabitacion` = '{$numeroFactura}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un factura con ese ID'; die; } } public function buscarHabitacionesLibres() { $resultado = $this->db->select("SELECT numero " . "FROM habitacion " . "WHERE numero NOT IN (SELECT numeroFactura FROM factura) "); return $resultado; } public function cargaHabitaciones($idTipoHabitacion) { $resultado = $this->db->select("SELECT numero " . "FROM habitacion " . "WHERE numero NOT IN (SELECT numeroFactura FROM factura) " . "AND tipo = " . $idTipoHabitacion . " "); echo json_encode($resultado); } } ?> <file_sep><?php Class Funcionario_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Funcionario public function guardarFuncionario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciaPreMatricula != null) { echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } else { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('funcionario', array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'puesto' => $datos['txt_puesto'])); } } public function listaFuncionarios() { //ver Funcionarios $consultaFuncionarios = $this->db->select("SELECT * FROM funcionario "); return $consultaFuncionarios; } public function datosFuncionario($id) { $consultaExistenciaFuncionario = $this->db->select("SELECT * FROM funcionario " . "WHERE id = " . $id . " "); if ($consultaExistenciaFuncionario != null) { return $consultaExistenciaFuncionario; } else { echo 'No se ha encontrado el funcionario'; die; } } public function actualizarFuncionario($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $datos['txt_id'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'id' => $datos['txt_id'], 'nombre' => $datos['txt_nombre'], 'puesto' => $datos['txt_puesto']); $this->db->update('funcionario', $posData, "`id` = '{$datos['txt_id']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } } public function eliminarFuncionario($id) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM funcionario " . "WHERE id = '" . $id . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('funcionario', "`id` = '{$id}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe un funcionario con ese ID'; die; } } public function buscarEstuRatif($ced_estudiante) { $resultado = $this->db->select("SELECT * " . "FROM funcionario " . "WHERE id = '" . $ced_estudiante . "'"); echo json_encode($resultado); } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Check out</h1> <form id="MyForm" action="<?php echo URL; ?>factura/actualizarFactura" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombreCliente" class="col-xs-2 control-label">Cliente : </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_nombreCliente" name="txt_nombreCliente" value='<?php echo $this->datosFactura[0]['nombreCliente']; ?>'disabled/> <input type="hidden" id="txt_habitacion" name="txt_nombreCliente" value='<?php echo $this->datosFactura[0]['nombreCliente']; ?>'/> </div> <div class="form-group"> <label for="txt_habitacion" class="col-xs-2 control-label">Tipo Habitación:</label> <div class="col-xs-2"> <input type="hidden" id="txt_habitacion" name="txt_habitacion" value='<?php echo $this->datosFactura[0]['habitacion']; ?>'/> <?php foreach ($this->consultaTipoHabitacion as $value) { if ($value['id'] == $this->datosFactura[0]['habitacion']) { $moneda=$value['moneda']; ?> <input type="text" class=" form-control input-sm validate[required]" id="txt_habitacion" name="txt_habitacion" value='<?php echo $value['descripcion']; ?>'disabled/> <?php } } ?> </div> <label for="txt_numeroFactura" class="col-xs-2 control-label">Numero Habitación:</label> <div class="col-xs-1"> <input type="text" class=" form-control input-sm validate[required]" id="txt_numeroFactura" name="txt_numeroFactura" value='<?php echo $this->datosFactura[0]['numeroFactura']; ?>'disabled/> <input type="hidden" id="txt_habitacion" name="txt_numeroFactura" value='<?php echo $this->datosFactura[0]['numeroFactura']; ?>'/> </div> </div> <div class="form-group"> <label for="txt_numeroFactura" class="col-xs-2 control-label">Monto total:</label> <div class="col-xs-2"> <?php $fechaIngreso = new DateTime($this->datosFactura[0]['ingreso']); $fechaSalida = new DateTime($this->datosFactura[0]['estadia']); $dias = $fechaIngreso->diff($fechaSalida); $diferenciaDias = (int) $dias->format('%R%a'); foreach ($this->consultaTipoHabitacion as $value) { if ($value['id'] == $this->datosFactura[0]['habitacion']) { $precio = $value['precio']; } } $total = $diferenciaDias * $precio; $precioProducto = 0; foreach ($this->consultaProductos_habitacion as $value) { if ($value['numeroHabitacion'] == $this->datosFactura[0]['numeroFactura']) { $IdPreducto = $value['idProducto']; foreach ($this->consultaProductos as $value2) { if ($IdPreducto == $value2['id']) { $precioProducto = $precioProducto + $value2['precio']; } } } } $total = $total + $precioProducto; $total = $total + ($total * 0.13); $total = $total + ($total * 0.16); ?> <input type="text" class=" form-control input-sm validate[required]" id="txt_numeroFactura" name="txt_numeroFactura" value='<?php echo $moneda.$total ?>'disabled/> </div> <label for="txt_tarjeta" class="col-xs-2 control-label">Número de tarjeta : </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_tarjeta" name="txt_tarjeta" value='<?php echo $this->consultaCliente[0]['tarjeta']; ?>'disabled/> <input type="hidden" id="txt_habitacion" name="txt_tarjeta" value='<?php echo $this->consultaCliente[0]['tarjeta']; ?>'/> </div> <br><br><br> <div class="col-xs-4"> <h4>Otros Cargos</h4> <table class="table table-condensed"> <tr> <th colspan="2" class="nombreTabla text-center">Desglose</th> </tr> <tr> <th>Producto</th> <th>Precio</th> </tr> <?php $con = 1; $mensaje = "'¿Desea eliminar esta factura?'"; foreach ($this->consultaProductos_habitacion as $lista => $value) { if ($this->datosFactura[0]['numeroFactura'] == $value['numeroHabitacion']) { echo '<tr>'; echo '<td>'; foreach ($this->consultaProductos as $value2) { if ($value['idProducto'] == $value2['id']) { echo $value2['descripcion']; } } echo '</td>'; echo '<td>'; foreach ($this->consultaProductos as $value2) { if ($value['idProducto'] == $value2['id']) { echo $moneda; echo $value2['precio']; } } // echo $value['precio']; echo '</td>'; ?> <?php echo '</td>'; echo '</tr>'; $con++; } } ?> <tr> <td colspan='2' class="lineaFin"></td> </tr> <tr> <td colspan='2'>Última línea</td> </tr> </table> </div> <br><br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <!--<input type="submit" class="btn btn-success" id="guardar" value="Check out" />--> <?php $mensaje = "'¿Desea realizar pago?'"; foreach ($this->listaFacturas as $lista => $value) { if ($value['numeroFactura'] == $this->datosFactura[0]['numeroFactura']) { echo '<a class="btn-sm btn-success" href="' . URL . 'factura/eliminarFactura/' . $value['numeroFactura'] . '" onclick ="return confirm(' . $mensaje . ')">Check out</a>&nbsp &nbsp &nbsp'; } } ?> </div> </div> </fieldset> </form> </div><file_sep><?php Class Habitacion_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Funcionario public function guardarHabitacion($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = '" . $datos['txt_numero'] . "' "); if ($consultaExistenciaPreMatricula != null) { echo 'Error...</br>Ya existe una habitación con este numero'; die; } else { //Sino Inserto datos de Pre-Matricula del Estudiante $this->db->insert('habitacion', array( 'numero' => $datos['txt_numero'], 'piso' => $datos['txt_piso'], 'tipo' => $datos['txt_tipo'])); } } public function listaFuncionarios() { //ver Funcionarios $consultaFuncionarios = $this->db->select("SELECT * FROM habitacion "); return $consultaFuncionarios; } public function listaHabitaciones() { $consultaFuncionarios = $this->db->select("SELECT * FROM tipohabitacion "); return $consultaFuncionarios; } public function datosHabitacion($numero) { $consultaExistenciaHabitacion = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = " . $numero . " "); if ($consultaExistenciaHabitacion != null) { return $consultaExistenciaHabitacion; } else { echo 'No se ha encontrado la habitación'; die; } } public function actualizarHabitacion($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = '" . $datos['txt_numero'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'numero' => $datos['txt_numero'], 'piso' => $datos['txt_piso'], 'tipo' => $datos['txt_tipo']); $this->db->update('habitacion', $posData, "`numero` = '{$datos['txt_numero']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe una habitacion con ese numero'; die; } } public function eliminarHabitacion($numero) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = '" . $numero . "' "); if ($consultaExistenciaPreMatricula != null) { $this->db->delete('habitacion', "`numero` = '{$numero}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>No se elimino la habitacion'; die; } } public function buscarEstuRatif($ced_estudiante) { $resultado = $this->db->select("SELECT * " . "FROM habitacion " . "WHERE tipo LIKE '%". $ced_estudiante . "%'"); echo json_encode($resultado); } public function datosTipoHabitacion($tipo) { $consultaExistenciaFactura = $this->db->select("SELECT * FROM habitacion " . "WHERE id = " . $tipo . " "); if ($consultaExistenciaFactura != null) { return $consultaExistenciaFactura; } else { echo 'No se ha encontrado la factura'; die; } } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <form id="MyForm" action="<?php echo URL; ?>Cliente/guardarCliente" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">Agregar Cliente</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_nombre" class="col-xs-2 control-label">Nombre completo:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_nombre" name="txt_nombre"/> </div> <label for="txt_id" class="col-xs-2 control-label">ID:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm" id="txt_id" name="txt_id"/> </div> <label for="txt_telefono" class="col-xs-2 control-label">Teléfono:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_telefono" name="txt_telefono"/> </div> <br><br><br> <label for="txt_tarjeta" class="col-xs-2 control-label">Tarjeta de Credito:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_tarjeta" name="txt_tarjeta"/> </div> </div> </br> </br> <!--L3 Fecha Nacimiento (Formulario Hugo)--> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Agregar Cliente" /> </div> </div> </fieldset> </form> </div><file_sep><?php class Funcionario extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad(); $this->view->js = array('funcionario/js/jsFuncionario.js'); } function agregarfuncionario() { $this->view->title = 'Funcionario'; $this->view->render('header'); $this->view->render('funcionario/agregarfuncionario'); $this->view->render('footer'); } function verFuncionarios() { $this->view->title = 'Funcionario'; $this->view->render('header'); $this->view->listaFuncionarios = $this->model->listaFuncionarios(); $this->view->render('funcionario/verFuncionarios'); $this->view->render('footer'); } function guardarFuncionario() { $datos = array(); $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_id'] = $_POST['txt_id']; $datos ['txt_puesto'] = $_POST['txt_puesto']; $this->model->guardarFuncionario($datos); header("location: " . URL . "funcionario/verFuncionarios"); } function editarFuncionario($id) { $this->view->title = 'Funcionario'; $this->view->render('header'); $this->view->datosFuncionario = $this->model->datosFuncionario($id); $this->view->render('funcionario/editarFuncionario'); $this->view->render('footer'); } function actualizarFuncionario() { $datos = array(); $datos ['txt_id'] = $_POST['txt_id']; $datos ['txt_nombre'] = $_POST['txt_nombre']; $datos ['txt_puesto'] = $_POST['txt_puesto']; $this->model->actualizarFuncionario($datos); header("location: " . URL . "funcionario/verFuncionarios"); } function eliminarFuncionario($id) { $this->view->title = 'Funcionario'; $this->model->eliminarFuncionario($id); header("location: " . URL . "funcionario/verFuncionarios"); } function buscarEstuRatif($ced_estudiante) { $this->model->buscarEstuRatif($ced_estudiante); } } ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 06-09-2017 a las 21:55:26 -- Versión del servidor: 10.1.21-MariaDB -- Versión de PHP: 5.6.30 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Base de datos: `bd_hoteleriaturismo` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cliente` -- CREATE TABLE `cliente` ( `nombre` varchar(50) NOT NULL, `id` varchar(50) NOT NULL, `telefono` int(50) NOT NULL, `tarjeta` int(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `cliente` -- INSERT INTO `cliente` (`nombre`, `id`, `telefono`, `tarjeta`) VALUES ('<NAME>', '208100140', 86476717, 2147483647), ('Pedro', '2564848', 4481518, 87721548), ('Julio', '28999', 888, 954115), ('Petronilo', '346543', 2425, 2354253), ('elieser', '401230123', 88888888, 543); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `factura` -- CREATE TABLE `factura` ( `nombreCliente` varchar(100) NOT NULL, `habitacion` int(100) NOT NULL, `precio` int(50) NOT NULL, `numeroFactura` int(100) NOT NULL, `ingreso` varchar(50) NOT NULL, `estadia` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `factura` -- INSERT INTO `factura` (`nombreCliente`, `habitacion`, `precio`, `numeroFactura`, `ingreso`, `estadia`) VALUES ('<NAME>', 1, 0, 101, '2017-08-01', '2017-08-05'), ('Pedro', 4, 0, 102, '2017-08-01', '2017-08-05'), ('Petronilo', 2, 0, 106, '2017-08-01', '2017-08-02'), ('<NAME>', 1, 0, 201, '2017-09-01', '2017-09-07'), ('elieser', 1, 0, 202, '2017-09-08', '2017-09-15'), ('Julio', 6, 0, 401, '2017-09-01', '2017-09-02'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `funcionario` -- CREATE TABLE `funcionario` ( `id` int(100) NOT NULL, `nombre` varchar(50) NOT NULL, `puesto` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `funcionario` -- INSERT INTO `funcionario` (`id`, `nombre`, `puesto`) VALUES (208000264, '<NAME>', 'Miembro'), (208100133, '<NAME>', 'Lider'), (208100140, '<NAME>', 'Co-Lider'), (402440303, '<NAME>', 'Veterano'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `habitacion` -- CREATE TABLE `habitacion` ( `numero` int(10) NOT NULL, `piso` int(5) NOT NULL, `tipo` varchar(500) NOT NULL, `Estado` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `habitacion` -- INSERT INTO `habitacion` (`numero`, `piso`, `tipo`, `Estado`) VALUES (101, 1, '1', 0), (102, 1, '1', 0), (103, 1, '1', 0), (104, 1, '1', 0), (105, 1, '1', 0), (106, 1, '2', 0), (107, 1, '2', 0), (108, 1, '2', 0), (109, 1, '2', 0), (110, 1, '2', 0), (201, 2, '1', 0), (202, 2, '1', 0), (203, 2, '1', 0), (204, 2, '1', 0), (205, 2, '1', 0), (206, 2, '2', 0), (207, 2, '2', 0), (208, 2, '2', 0), (209, 2, '2', 0), (210, 2, '2', 0), (301, 3, '3', 0), (302, 3, '3', 0), (303, 3, '3', 0), (304, 3, '3', 0), (305, 3, '3', 0), (306, 3, '4', 0), (307, 3, '4', 0), (308, 3, '4', 0), (309, 3, '4', 0), (310, 3, '4', 0), (401, 4, '6', 0), (402, 4, '6', 0), (403, 4, '6', 0), (404, 4, '6', 0), (405, 4, '6', 0), (406, 4, '7', 0), (407, 4, '7', 0), (408, 4, '7', 0), (409, 4, '5', 0), (410, 4, '5', 0); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE `productos` ( `id` int(10) NOT NULL, `descripcion` varchar(50) NOT NULL, `precio` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id`, `descripcion`, `precio`) VALUES (1, 'Coca Cola', 3), (2, 'Hamburguesa', 5); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos_habitacion` -- CREATE TABLE `productos_habitacion` ( `numeroHabitacion` int(10) NOT NULL, `idProducto` int(10) NOT NULL, `id` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `productos_habitacion` -- INSERT INTO `productos_habitacion` (`numeroHabitacion`, `idProducto`, `id`) VALUES (101, 1, 9), (102, 2, 10), (102, 2, 11), (106, 1, 12), (409, 2, 14), (101, 1, 15); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tipohabitacion` -- CREATE TABLE `tipohabitacion` ( `id` int(20) NOT NULL, `descripcion` varchar(50) NOT NULL, `numeroCamas` int(10) NOT NULL, `precio` int(10) NOT NULL, `moneda` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT; -- -- Volcado de datos para la tabla `tipohabitacion` -- INSERT INTO `tipohabitacion` (`id`, `descripcion`, `numeroCamas`, `precio`, `moneda`) VALUES (1, 'Sencilla', 1, 100, '$'), (2, 'Doble', 2, 200, '¢'), (3, 'Triple', 3, 250, '$'), (4, 'Quadruple', 4, 300, '¥'), (5, 'Presi', 2, 2000, '€'), (6, 'Jr Suit', 1, 500, '$'), (7, 'Suit', 2, 1000, '$'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuario` -- CREATE TABLE `usuario` ( `nombreUsuario` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `nombre` varchar(50) NOT NULL, `tipoUsuario` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuario` -- INSERT INTO `usuario` (`nombreUsuario`, `password`, `nombre`, `tipoUsuario`) VALUES ('Brayan', '<PASSWORD>', 'Brayan', 2), ('juan', '<PASSWORD>', '<NAME>', 1), ('Kevin', '<PASSWORD>', 'Kevin', 3); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `cliente` -- ALTER TABLE `cliente` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `factura` -- ALTER TABLE `factura` ADD PRIMARY KEY (`numeroFactura`); -- -- Indices de la tabla `funcionario` -- ALTER TABLE `funcionario` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `habitacion` -- ALTER TABLE `habitacion` ADD PRIMARY KEY (`numero`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `productos_habitacion` -- ALTER TABLE `productos_habitacion` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `tipohabitacion` -- ALTER TABLE `tipohabitacion` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`nombreUsuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `productos_habitacion` -- ALTER TABLE `productos_habitacion` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT de la tabla `tipohabitacion` -- ALTER TABLE `tipohabitacion` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php //print_r($this->estadoMatricula); //die; ?> <center> <br> <table class="table table-condensed" id="tablaRatificar"> <tr> <th colspan="30" class="nombreTabla text-center">Lista de Habitaciones</th> </tr> <tr> <th colspan="30"> <?php echo $this->mesActual->format('F'); ?></th> </tr> <tr> <th>#</th> <?php for ($i = 1; $i <= $this->mesActual->format('t'); $i++) { ?> <th><?php echo $i; ?></th> <?php } ?> </tr> <?php foreach ($this->consultaNuHabitacion as $lista => $value) { echo '<tr>'; echo '<td>'; echo $value['numero']; echo '</td>'; for ($i = 1; $i <= $this->mesActual->format('t'); $i++) { echo '<td>'; foreach ($this->listaFacturas as $factura) { if ($factura['numeroFactura'] == $value['numero']) { $fechaIngreso = new DateTime($factura['ingreso']); $fechaSalida = new DateTime($factura['estadia']); // echo $fechaIngreso->format('n'); // echo $this->mesActual->format('n'); // die; if ($fechaIngreso->format('n') == $this->mesActual->format('n')) { if ($i >= (int) $fechaIngreso->format('d') && ($i < (int) $fechaSalida->format('d') || $fechaSalida->format('n') > $this->mesActual->format('n') )) { $diasEstancia = $fechaIngreso->diff($fechaSalida); $diferenciaDiasEstancia = (int) $diasEstancia->format('%R%a'); $diasFechaActual = $this->mesActual->diff($fechaIngreso); $diferenciaDiasActual = (int) $diasFechaActual->format('%R%a'); //echo $diferenciaDiasEstancia; if ($i >= 0 && $diferenciaDiasActual < $i) { echo 'X'; } } } } } echo '</td>'; } echo '</tr>'; } ?> <tr> <td colspan="30" class="lineaFin"></td> </tr> <tr> <td colspan="30">Última línea</td> </tr> </table> <a class="btn-sm btn-primary" href="<?php echo URL; ?>rackHabitacion/rackMesAnterior">Anterior</a> <a class="btn-sm btn-primary" href="<?php echo URL; ?>rackHabitacion/rackMesSiguiente">Siguiente</a> </center><file_sep><?php Class HabitacionCliente_Model extends Models { public function __construct() { parent::__construct(); } public function listaFuncionarios() { //ver Funcionarios $consultaFuncionarios = $this->db->select("SELECT * FROM habitacion "); return $consultaFuncionarios; } public function datosHabitacion($numero) { $consultaExistenciaHabitacion = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = " . $numero . " "); if ($consultaExistenciaHabitacion != null) { return $consultaExistenciaHabitacion; } else { echo 'No se ha encontrado la habitación'; die; } } } ?> <file_sep><?php //print_r($this->estadoMatricula); //die; ?> <center> <table class="table table-condensed"> <tr> <th colspan="6" class="nombreTabla text-center">Lista de Facturas</th> </tr> <tr> <th>Nombre Cliente</th> <th>Tipo de Habitación</th> <th>Precio</th> <th class="text-center">Número de Habitación</th> <th>Ingreso</th> <th>Salida</th> <?php if (Session::get('tipoUsuario') <= 2) { ?> <th colspan="2" class="text-center">Acción</th> <?php } ?> </tr> <?php $con = 1; $mensaje = "'¿Desea eliminar esta factura?'"; foreach ($this->listaFacturas as $lista => $value) { echo '<tr>'; echo '<td>'; echo $value['nombreCliente']; echo '</td>'; echo '<td>'; if ($value['habitacion'] == 1) { echo 'Sencilla'; } elseif ($value['habitacion'] == 2) { echo 'Doble'; } elseif ($value['habitacion'] == 3) { echo 'Triple'; } elseif ($value['habitacion'] == 4) { echo 'Quadruple'; } elseif ($value['habitacion'] == 5) { echo 'Presi'; } elseif ($value['habitacion'] == 6) { echo 'Jr Suit'; } elseif ($value['habitacion'] == 7) { echo 'Suit'; } echo '</td>'; echo '<td>'; if ($value['habitacion'] == 1) { echo $this->consultaTipoHabitacion[0]['precio']; } elseif ($value['habitacion'] == 2) { echo $this->consultaTipoHabitacion[1]['precio']; } elseif ($value['habitacion'] == 3) { echo $this->consultaTipoHabitacion[2]['precio']; } elseif ($value['habitacion'] == 4) { echo $this->consultaTipoHabitacion[3]['precio']; } elseif ($value['habitacion'] == 5) { echo $this->consultaTipoHabitacion[4]['precio']; } elseif ($value['habitacion'] == 6) { echo $this->consultaTipoHabitacion[5]['precio']; } elseif ($value['habitacion'] == 7) { echo $this->consultaTipoHabitacion[6]['precio']; } // echo $value['precio']; echo '</td>'; echo '<td class="text-center">'; echo $value['numeroFactura']; echo '</td>'; echo '<td>'; echo $value['ingreso']; echo '</td>'; echo '<td>'; echo $value['estadia']; echo '</td>'; echo '<td class=text-center>'; ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <?php echo '<a class="btn-sm btn-primary" href="editarFactura/' . $value['numeroFactura'] . '">Editar</a>&nbsp &nbsp &nbsp'; echo '<a class="btn-sm btn-warning" href="eliminarFactura/' . $value['numeroFactura'] . '" onclick ="return confirm(' . $mensaje . ')">Eliminar</a>&nbsp &nbsp &nbsp'; echo '<a class="btn-sm btn-success" href="cancelarFactura/' . $value['numeroFactura'] . '">Check out</a>&nbsp &nbsp &nbsp'; ?> <?php } ?> <?php echo '</td>'; echo '</tr>'; $con++; } ?> <tr> <td colspan='6' class="lineaFin"></td> </tr> <tr> <td colspan='6'>Última línea</td> </tr> </table> </center><file_sep><?php //print_r($this->estadoMatricula); //die; ?> <center> <br> <br> <table class="table table-condensed" id="tablaRatificar"> <tr> <th colspan="6" class="nombreTabla text-center">Lista de Habitaciones</th> </tr> <tr> <th>Descripcion</th> <th>Moneda</th> <th>Precio</th> <?php if (Session::get('tipoUsuario') <= 2) { ?> <th colspan="2" class="text-center">Acción</th> <?php } ?> </tr> <?php $con = 1; $mensaje = "'¿Desea eliminar esta habitacion?'"; foreach ($this->listaTipoHabitacion as $lista => $value) { echo '<tr>'; echo '<td>'; echo $value['descripcion']; echo '</td>'; echo '<td>'; echo $value['moneda']; echo '</td>'; echo '<td>'; echo $value['precio']; echo '</td>'; echo '<td class=text-center>'; ?> <?php if (Session::get('tipoUsuario') <= 2) { ?> <?php echo'<a class = "btn-sm btn-primary" href = "editarPrecio/' . $value['id'] . '">Editar</a>&nbsp &nbsp &nbsp'; ?> <?php } ?> <?php echo '</td>'; echo '</tr>'; $con++; } ?> <tr> <td colspan='6' class="lineaFin"></td> </tr> <tr> <td colspan='6'>Última línea</td> </tr> </table> </center><file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Editar Precio</h1> <form id="MyForm" action="<?php echo URL; ?>precio/actualizarPrecio" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS DE LA HABITACIÓN</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_tipo" class="col-xs-2 control-label">Tipo: </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_tipo" name="txt_tipo" value='<?php echo $this->datosTipoHabitacion[0]['descripcion']; ?>'disabled/> <input type="hidden" id="txt_tipo" name="txt_tipo" value='<?php echo $this->datosTipoHabitacion[0]['descripcion']; ?>'/> </div> <label for="txt_precio" class="col-xs-2 control-label">Precio: </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm" id="txt_precio" name="txt_precio" value='<?php echo $this->datosTipoHabitacion[0]['precio']; ?>'/> </div> <label for="txt_moneda" class="col-xs-2 control-label">Moneda: </label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_moneda" id="txt_piso"> <?php foreach ($this->datosTipoHabitacion as $value) { if ($value['moneda'] == $this->datosTipoHabitacion[0]['moneda']) echo "selected"; ?> > <?php echo $value['moneda'] . "</option>"; ?> <option value="&#36;">Dolar</option> <option value="&#8364;">Euro</option> <option value="&#162;">Colón</option> <option value="&#165;">Yen</option> <option value="&#163;">Libra</option> <?php } ?> </select></div> </div> <br><br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Guardar" /> </div> </div> </fieldset> </form> </div><file_sep><?php //print_r($this->estadoMatricula); //die; ?> <form id="MyForm" action="<?php echo URL; ?>cliente/agregarCliente" method="POST" enctype="multipart/form-data" class="form-horizontal"> <div class ="form-group"> <div class="col-xs-12 text-center"> <div class="row"> <div class="col-xs-12"> <h1>ERROR</h1> <h4>Su fecha de salida debe ser posterior a fecha ingreso.</h4> <h5>Por favor, vuelva a ingresar los datos.</h5> &nbsp; &nbsp; <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="btn_volver" value="Volver Al Formulario"/> </div> </div> </div> </div> </div> </form> &nbsp; &nbsp; &nbsp;<file_sep><?php class RackHabitacion extends Controllers { //Cuando se crea el constructor se verifica si inicio sesion y si tiene permiso public function __construct() { parent::__construct(); Auth::handleLogin(); } public function index() { $this->view->title = 'Estadisticas de los Estudiantes'; //Se manda a ejecutar el header, contenido principal (views/horario/index) y el footer $this->view->render('header'); $this->view->render('estadistica/index'); $this->view->render('footer'); } public function rackMensual() { $this->view->title = 'Rack Mensual'; //Se manda a ejecutar el header, contenido principal (views/horario/index) y el footer $this->view->render('header'); $fechaActual = new DateTime(); // print_r($fechaActual->format('n')); // die; $this->view->mesActual = $fechaActual; $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->consultaNuHabitacion = $this->model->consultaNuHabitacion(); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->buscarHabitacionesLibres = $this->model->buscarHabitacionesLibres(); $this->view->render('rackHabitacion/rackMensual'); $this->view->render('footer'); } public function rackMesAnterior() { $this->view->title = 'Rack Mensual'; //Se manda a ejecutar el header, contenido principal (views/horario/index) y el footer $this->view->render('header'); $fechaActual = new DateTime(); // print_r($fechaActual->format('n')); // die; $fechaActual->modify('-1 month'); $this->view->mesActual = $fechaActual; $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->consultaNuHabitacion = $this->model->consultaNuHabitacion(); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->buscarHabitacionesLibres = $this->model->buscarHabitacionesLibres(); $this->view->render('rackHabitacion/rackMesAnterior'); $this->view->render('footer'); } public function rackMesSiguiente() { $this->view->title = 'Rack Mensual'; //Se manda a ejecutar el header, contenido principal (views/horario/index) y el footer $this->view->render('header'); $fechaActual = new DateTime(); // print_r($fechaActual->format('n')); // die; $fechaActual->modify('+1 month'); $this->view->mesActual = $fechaActual; $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->consultaNuHabitacion = $this->model->consultaNuHabitacion(); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->buscarHabitacionesLibres = $this->model->buscarHabitacionesLibres(); $this->view->render('rackHabitacion/rackMesSiguiente'); $this->view->render('footer'); } } <file_sep><?php class Factura extends Controllers { function __construct() { parent::__construct(); Auth::handleLogin(); Auth::nivelDeSeguridad2(); $this->view->js = array('factura/js/jsFactura.js'); } function agregarfactura() { $this->view->title = 'Factura'; $this->view->render('header'); $this->view->consultaCliente = $this->model->consultaCliente(); $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->consultaNuHabitacion = $this->model->consultaNuHabitacion(); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->buscarHabitacionesLibres = $this->model->buscarHabitacionesLibres(); $this->view->render('factura/agregarfactura'); $this->view->render('footer'); } function verFacturas() { $this->view->title = 'Factura'; $this->view->render('header'); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->render('factura/verFacturas'); $this->view->render('footer'); } function guardarFactura() { $datos = array(); $datos ['txt_nombreCliente'] = $_POST['txt_nombreCliente']; $datos ['txt_tipo'] = $_POST['txt_tipo']; $datos ['txt_numeroFactura'] = $_POST['txt_numeroFactura']; $datos ['txt_ingreso'] = $_POST['txt_ingreso']; $datos ['txt_estadia'] = $_POST['txt_estadia']; $fechaIngreso = new DateTime($datos['txt_ingreso']); $fechaSalida = new DateTime($datos['txt_estadia']); $dias = $fechaIngreso->diff($fechaSalida); $diferenciaDias = (int) $dias->format('%R%a'); if ($diferenciaDias >= 1) { $this->model->guardarFactura($datos); header("location: " . URL . "factura/verFacturas"); } else { $this->view->title = 'Factura'; $this->view->render('header'); $this->view->render('error/errorFechas'); $this->view->render('footer'); } } function editarFactura($id) { $this->view->title = 'Factura'; $this->view->render('header'); $this->view->datosFactura = $this->model->datosFactura($id); $this->view->consultaCliente = $this->model->consultaCliente($id); $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->render('factura/editarFactura'); $this->view->render('footer'); } function cancelarFactura($id) { $this->view->title = 'Factura'; $this->view->render('header'); $this->view->listaFacturas = $this->model->listaFacturas(); $this->view->datosFactura = $this->model->datosFactura($id); $this->view->consultaCliente = $this->model->consultaCliente($id); $this->view->consultaTipoHabitacion = $this->model->consultaTipoHabitacion(); $this->view->consultaProductos_habitacion = $this->model->consultaProductos_habitacion(); $this->view->consultaProductos = $this->model->consultaProductos(); $this->view->render('factura/cancelarFactura'); $this->view->render('footer'); } function actualizarFactura() { $datos = array(); $datos ['txt_nombreCliente'] = $_POST['txt_nombreCliente']; $datos ['txt_habitacion'] = $_POST['txt_habitacion']; $datos ['txt_precio'] = $_POST['txt_precio']; $datos ['txt_numeroFactura'] = $_POST['txt_numeroFactura']; $datos ['txt_ingreso'] = $_POST['txt_ingreso']; $datos ['txt_estadia'] = $_POST['txt_estadia']; $this->model->actualizarFactura($datos); header("location: " . URL . "factura/verFacturas"); } function eliminarFactura($id) { $this->view->title = 'Factura'; $this->model->eliminarFactura($id); header("location: " . URL . "factura/verFacturas"); } function cargaHabitaciones($idTipoHabitacion) { $this->model->cargaHabitaciones($idTipoHabitacion); } } ?> <file_sep><h2>Bienvenid@ a Hoteleria Turismo.</h1> <p>Versión Beta desarrollada por empresa Corporation.</p> <?php //Forma de Encriptacion del Password echo Hash::create('md5', '123queso', HASH_PASSWORD_KEY); ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <h1>Editar Habitacion</h1> <form id="MyForm" action="<?php echo URL; ?>habitacion/actualizarHabitacion" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">DATOS DE LA HABITACIÓN</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_numero" class="col-xs-2 control-label">Numero de habitacion: </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm validate[required]" id="txt_numero" name="txt_numero" value='<?php echo $this->datosHabitacion[0]['numero']; ?>'disabled/> <input type="hidden" id="txt_numero" name="txt_numero" value='<?php echo $this->datosHabitacion[0]['numero']; ?>'/> </div> <label for="txt_piso" class="col-xs-2 control-label">Piso: </label> <div class="col-xs-2"> <input type="text" class=" form-control input-sm" id="txt_piso" name="txt_piso" value='<?php echo $this->datosHabitacion[0]['piso']; ?>' disabled/> <input type="hidden" id="txt_piso" name="txt_piso" value='<?php echo $this->datosHabitacion[0]['piso']; ?>'/> </div> <label for="txt_tipo" class="col-xs-2 control-label">Tipo:</label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_tipo" id="txt_tipo"> <?php foreach ($this->listaHabitaciones as $value) { echo "<option value='" . $value['id'] . "' "; if ($value['id'] == $this->datosHabitacion[0]['tipo']) echo "selected"; ?> > <?php echo $value['descripcion'] . "</option>"; } ?> </select> </div> </div> <br><br> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Guardar" /> </div> </div> </fieldset> </form> </div><file_sep><?php Class Precio_Model extends Models { public function __construct() { parent::__construct(); } //Inserto Funcionario public function datosHabitacion($numero) { $consultaExistenciaHabitacion = $this->db->select("SELECT * FROM habitacion " . "WHERE numero = " . $numero . " "); if ($consultaExistenciaHabitacion != null) { return $consultaExistenciaHabitacion; } else { echo 'No se ha encontrado la habitación'; die; } } public function actualizarHabitacion($datos) { //Guardo los datos en Pre-Matricula, luego hay que ratificar para que consolide la matricula $consultaExistenciaPreMatricula = $this->db->select("SELECT * FROM tipohabitacion " . "WHERE descripcion = '" . $datos['txt_tipo'] . "' "); if ($consultaExistenciaPreMatricula != null) { $posData = array( 'precio' => $datos['txt_precio'], 'moneda' => $datos['txt_moneda']); $this->db->update('tipohabitacion', $posData, "`descripcion` = '{$datos['txt_tipo']}'"); } else { //Sino Inserto datos de Pre-Matricula del Estudiante echo 'Error...</br>Ya existe una habitacion con ese numero'; die; } } public function listaTipoHabitacion() { //ver Facturas $consultaFacturas = $this->db->select("SELECT * FROM tipohabitacion "); return $consultaFacturas; } public function datosTipoHabitacion($numeroFactura) { $consultaExistenciaFactura = $this->db->select("SELECT * FROM tipohabitacion " . "WHERE id = " . $numeroFactura . " "); if ($consultaExistenciaFactura != null) { return $consultaExistenciaFactura; } else { echo 'No se ha encontrado la factura'; die; } } } ?> <file_sep><?php //print_r($this->especialidadEstudiante); //die; ?> <div class="row"> <form id="MyForm" action="<?php echo URL; ?>habitacion/guardarHabitacion" method="POST" enctype="multipart/form-data" class="form-horizontal"> <fieldset> <legend class="text-center">Agregar Habitación</legend> <!--L2 Nombre Estudiante (Formulario Hugo)--> <div class="form-group"> <label for="txt_numero" class="col-xs-2 control-label">Numero:</label> <div class="col-xs-2"> <input type="text" class="form-control input-sm validate[required]" id="txt_numero" name="txt_numero"/> </div> <label for="txt_piso" class="col-xs-2 control-label">Piso:</label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_piso" id="txt_piso"> <option value="0">Seleccione...</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </div> <label for="txt_tipo" class="col-xs-2 control-label">Tipo:</label> <div class="col-xs-2"> <select class="form-control input-sm" name="txt_tipo" id="txt_tipo"> <option value="0">Seleccione...</option> <option value="Sencilla">Sencilla</option> <option value="Doble">Doble</option> <option value="Triple">Triple</option> <option value="Quadruple">Quadruple</option> <option value="Presi">Presi</option> <option value="Jr Suit">Jr Suit</option> <option value="Suit">Suit</option> </select> </div> </div> </br> </br> <!--L3 Fecha Nacimiento (Formulario Hugo)--> <!--L25 Imprimir y Guardar (Formulario Hugo)--> <div class="form-group"> <div class="col-xs-12 text-center"> <input type="submit" class="btn btn-primary" id="guardar" value="Agregar Habitación" /> </div> </div> </fieldset> </form> </div>
f768154da73ebce2679090b4d6e434147f046153
[ "SQL", "PHP" ]
38
PHP
jonathan109dani/hoteleriaTurismo
522174e0d9fa4644153e041211ba2a26d18adf6b
a565c05a875da7708db189b8a10d54ab535ba953
refs/heads/master
<repo_name>bshkspr/Lee2008<file_sep>/README.md # Lee2008 R codes for my publication in BMC Bioinformatics 2008 http://www.biomedcentral.com/1471-2105/9/32 <file_sep>/ftn.gene2orf.R ftn.gene2orf <- function(genes) { ###################################################################### # # > Purpose # To convert gene names to ORF Y-names based on MIPS info # # > Copyright(c) # Author : <NAME> # E-mail : <EMAIL> # Date Created : 2005.02.10 # Last Modified : 2006.05.21 # ###################################################################### if ( length(grep('w32', sessionInfo()$R.version$os)) != 0 ) load("C:/research/DATA/MIPS/0_lee/all.info.RData") else load("/project/Scer/DATA/MIPS/0_lee/all.info.RData") foo <- all.info[match(toupper(genes), all.info[,6]), 1] if ( sum(toupper(genes) %in% all.info[,1]) > 0 ) foo[toupper(genes) %in% all.info[,1]] = toupper(genes)[toupper(genes) %in% all.info[,1]] if ( sum(is.na(foo)) > 0 ) { foo.na <- which(is.na(foo)) for ( i in 1:length(foo.na) ) { foo.ind = grep(genes[foo.na[i]], all.info[,7], ignore.case=T) foo.orf = all.info[foo.ind, 7] if ( length(foo.orf) != 0 ) { foo.orf = strsplit(foo.orf, ',') foo.orf = which(sapply(foo.orf, function(x) sum(toupper(genes)[foo.na[i]] %in% toupper(x)) > 0 ) ) if ( length(foo.orf) == 1 ) { foo[foo.na[i]] <- all.info[foo.ind[foo.orf], 1] } else { stop("\nThis gene, ", genes[foo.na[i]], ", has two ORF names! Check it manually.\n\n") } } else { foo[foo.na[i]] <- genes[foo.na[i]] } } } return(foo) } <file_sep>/ftn.orf2gene.R ftn.orf2gene <- function(orfs) { ###################################################################### # # > Purpose # To convert ORF Y-names to gene names based on MIPS info # # > Copyright(c) # Author : <NAME> # E-mail : <EMAIL> # Date Created : 2005.02.10 # Last Modified : 2006.05.21 # ###################################################################### if ( length(grep('w32', sessionInfo()$R.version$os)) != 0 ) load("C:/research/DATA/MIPS/0_lee/all.info.RData") else load("/project/Scer/DATA/MIPS/0_lee/all.info.RData") foo <- all.info[match(toupper(orfs), all.info[,1]), 6] if ( sum(is.na(foo)) > 0 ) { foo.na <- which(is.na(foo)) for ( i in 1:length(foo.na) ) { foo[foo.na[i]] <- toupper(orfs[foo.na[i]]) } } return(foo) } <file_sep>/ftn.enrich.mips.R ftn.enrich.mips <- function() { ###################################################################### # # > Purpose # To calculate the enrichment of MIPS funcat, using 3rd level # categories ('foo.3rd') # # > Copyright(c) # Author : <NAME> # E-mail : <EMAIL> # Date Created : 2005.02.10 # Last Modified : 2006.05.21 # ###################################################################### # >>> To input the working directory <<< cat("\nEnter the full path of the directory in which you would like to run this job:\n") foo.path <- scan(stdin(), what="character", nlines=1, quiet=T) setwd(foo.path) # >>> To read the list of modules <<< cat("\nEnter the file containing the list of modules:\n") file.name <- scan(stdin(), what="character", nlines=1, quiet=T) modules.list <- scan(file.name, what="character") # >>> To input the directory of modules cat("\nEnter the full path of the directory in which modules are:\n") foo.path.mod <- scan(stdin(), what="character", nlines=1, quiet=T) source("./ftn.orf2gene.R") load("../data/funcat_14032005.RData") funcat.data[grep("^Y[A-P][LR]", funcat.data[,1]),1] <- toupper(funcat.data[grep("^Y[A-P][LR]", funcat.data[,1]),1]) n_all_orfs <- length(unique(funcat.by.level[,1])) # !!! n_all_orfs, number of all orfs in MIPS funcat without 'UNCLASSIFIED' orfs # !!! Alternatively, # !!! (1) n_all_orfs <- length(grep('^Y[A-P]', unique(funcat.by.level[, 1]))) # !!! (2) n_all_orfs <- length(grep('^Y[A-P]', # !!! unique(funcat.by.level[funcat.by.level[,2] != '99', 1]))) # !!! !!! When removing 'UNCLASSIFIED' orfs for ( i in 1:length(modules.list) ) { setwd(foo.path.mod) foo.orf <- scan(file=modules.list[i], what="character", quiet=T) foo.gene <- ftn.orf2gene(foo.orf) foo.mips <- funcat.data[which(funcat.data[,1] %in% foo.orf), ] if ( length(which(funcat.data[,1] %in% foo.orf)) == 1 ) { foo.mips <- t(foo.mips) } foo.mips <- cbind(foo.mips, funcat.scheme[match(foo.mips[,2], funcat.scheme[,1]), 2]) foo.mtx <- cbind(foo.mips[,1], ftn.orf2gene(foo.mips[,1]), foo.mips[,2], foo.mips[,3]) colnames(foo.mtx) <- c("ORF", "Gene", "MIPS_code", "MIPS_ftn") if ( nrow(foo.mtx) != 1 ) { foo.mtx <- foo.mtx[order(foo.mtx[,3]), ] } setwd(foo.path) if ( !file.exists('enrich.MIPS') ) { dir.create("enrich.MIPS") } setwd("./enrich.MIPS/") write.table(file=paste(modules.list[i], ".mips", sep=""), foo.mtx, quote=F, row.names=F, sep="\t") foo.n_mod_orfs <- length(unique(foo.mtx[,1])) foo.tmp <- lapply(strsplit(foo.mtx[, 3], ".", fixed=T), function(x) x[1:3]) # !!! 3rd level category foo.3rd <- sub("[.]NA$", "", sapply(foo.tmp, function(x) sub("[.]NA$", "", paste(x[1], x[2], x[3], sep="."))) ) foo.mtx[, 3] <- foo.3rd foo.mtx[, 4] <- funcat.scheme[match(foo.3rd, funcat.scheme[,1]), 2] foo.by.funcat <- split(foo.mtx[,1], foo.mtx[,3]) if ( nrow(foo.mtx) == 1 ) { foo.pval.mips <- t(foo.mtx[, c(3,4,NA)]) } else { foo.pval.mips <- unique(foo.mtx[, c(3,4,NA)]) } foo.pval.mips <- cbind(foo.pval.mips, as.numeric(sapply(foo.by.funcat, function(x) length(x)))) colnames(foo.pval.mips)[3:4] <- c("P_val", "N_ORFs") # !!! Calculation of hypergeometric p-values for all funcats in each module for ( j in 1:length(foo.by.funcat) ) { foo.funcat_size <- as.numeric(funcat.3rd.size[names(foo.by.funcat)[j]]) # !!! foo.funcat_size, number of all orfs in each funcat foo.n_funcat_orfs <- length(foo.by.funcat[[j]]) # !!! foo.n_funcat_orfs, number of orfs with the same funcat in each module foo.pval.mips[j,3] <- formatC(1 - sum(dhyper(0:(foo.n_funcat_orfs-1), foo.funcat_size, n_all_orfs-foo.funcat_size, foo.n_mod_orfs)), format="e", dig=3) } if ( nrow(foo.pval.mips) != 1 ) { foo.pval.mips <- foo.pval.mips[order(as.numeric(foo.pval.mips[,3])), ] } write.table(file=paste(modules.list[i], ".mips.enrich", sep=""), foo.pval.mips, quote=F, row.names=F, sep="\t") } setwd(foo.path) cat('\n The output files have been saved in "enrich.MIPS" directory under\n\t', foo.path, '\n') cat("\nDone!\n\n") } <file_sep>/ftn.calc.zeta.v3.R ftn.calc.zeta.v3 <- function() { # ! To unlimit memory usage (from <NAME>), # % limit datasize unlimited # % limit vmemoryuse unlimited # % limit memoryuse unlimited ###################################################################### # # > Purpose # To calculate the average(|PCC|) for mRNA expression values of # all ORFs in each group ( ZETA = average(|PCC|) ) and # P-values for ZETAs based on Pipel et al.'s method # ( version 3 of 'ftn.calc.zeta.R' ) # # > Algorithms # 1. Calculate the ZETA for the common target genes of TFs, say, X and Y. # : Zeta_XY for the gene set, Genes_XY # 2. Calculate the ZETA for the remaining target genes of X. # : Zeta_X|Y for the gene set, Genes_X - Genes_XY (== Genes_X|Y) # 3. Calculate the ZETA for the remaining target genes of Y. # : Zeta_Y|X for the gene set, Genes_Y - Genes_XY (== Genes_Y|X) # 4. Decide which TF gives the maximum Zeta. Assume that it is X. # : TF_max = X such that Zeta_X|Y >= Zeta_Y|X # 5. Decide if X and Y are synergistic by requiring the following condition. # : Delta_Zeta = Zeta_XY - Zeta_X|Y > 0 # 6. Test if Delta_Zeta is statistically significant as follows. # 7. Divide the gene set, Genes_X, into two random groups corresponding to # the two sets, Genes_XY and Genes_X|Y, respectively. # : Genes_XY_rnd and Genes_X|Y_rnd # 8. Calculate the difference between the Zeta's for the two random groups. # : Delta_Zeta_rnd = Zeta_XY_rnd - Zeta_X|Y_rnd # 9. Make an emperical distribution of Delta_Zeta_rnd values by dividing Genes_X # many times repeatedly (e.g. 1000 times). # 10. Calculate a P-value by counting the number of Delta_Zeta_rnd values which are # greater than or equal to the observed difference, Delta_Zeta. # : P-value = sum(Delta_Zeta_rnd >= Delta_Zeta) / simul.times # # > Copyright(c) # Author : <NAME> # E-mail : <EMAIL> # Date Created : 2005.07.12 # Last Modified : 2006.07.31 # ###################################################################### # >>> To input the working directory <<< cat("\nEnter the full path of the directory in which you would like to run this job :\n") foo.path <- scan(stdin(), what="character", nlines=1, quiet=T) setwd(foo.path) # >>> To input the name of this job <<< cat("\nGive a name of this job as you wish :\n") foo.name = scan(stdin(), what="character", nlines=1, quiet=T) # >>> To ask if q-values should be reported along with p-values <<< input.qval = function() { cat("\nDo you want to have Q_values?\n") cat("Type 'yes' or 'no'.\n") return(scan(stdin(), what="character", nlines=1, sep="\n", quiet=T)) } answer.qval = input.qval() while ( answer.qval != "yes" & answer.qval != "no" ) { cat("Wrong answer. Please enter again.\n") answer.qval = input.qval() } # >>> Files to write outputs to <<< FILENAME_1 = paste(foo.name, '.result', sep='') FILENAME_2 = paste(foo.name, '.zero.sd.orfs.txt', sep='') FILENAME_3 = paste(foo.name, '.missing.ORFs', sep='') FILENAME_4 = paste(foo.name, '.no.calc.modules', sep='') # >>> To read modules data and make a list object for them <<< cat("\nEnter the file containing modules :\n") filename_modules = scan(stdin(), what="character", nlines=1, quiet=T) modules = scan(filename_modules, what="character", sep="\n", quiet=T) mod.names = sub('^> ', '', grep('^> ', modules, value=T)) mod.list = vector('list', length = length(mod.names)) names(mod.list) = mod.names for ( ind_mod in names(mod.list) ) { mod.list[[ind_mod]]$tfs = sort(unlist(strsplit( modules[grep(paste('> ', ind_mod, '$', sep=''), modules) + 1], ' '))) mod.list[[ind_mod]]$tgs = sort(unlist(strsplit( modules[grep(paste('> ', ind_mod, '$', sep=''), modules) + 2], ' '))) } # >>> To ask if all modules are tested at one time or part of them separately <<< input.allmod = function() { cat("\nAre they all modules to test?\n") cat("Type 'yes' or 'no'.\n") return(scan(stdin(), what="character", nlines=1, sep="\n", quiet=T)) } ANSWER_ALL = input.allmod() while ( ANSWER_ALL != "yes" & ANSWER_ALL != "no" ) { cat("Wrong answer. Please enter again.\n") ANSWER_ALL = input.allmod() } # >>> To input the ChIP-chip data file (R data format) from which the modules are derived <<< cat("\nEnter the R data file of the ChIP-chip matrix from which the modules are derived :\n") file.chip.mtx <- scan(stdin(), what="character", nlines=1, quiet=T) foo.chip.mtx <- load(file.chip.mtx) chip.data <- get(foo.chip.mtx) rm(list=ls(pat=foo.chip.mtx), file.chip.mtx, foo.chip.mtx) # >>> To input the ChIP-chip p-value threshold at which the modules are derived <<< cat("\nEnter the ChIP-chip p-value threshold at which the modules are derived :\n") chip.pval.thrs <- scan(stdin(), nlines=1, quiet=T) # >>> To input the expression data file (R data format) <<< cat("\nEnter the R data file of the expression matrix :\n") file.expr.mtx <- scan(stdin(), what="character", nlines=1, quiet=T) foo.expr.mtx <- load(file.expr.mtx) expr.mtx <- get(foo.expr.mtx) rm(list=ls(pat=foo.expr.mtx), file.expr.mtx, foo.expr.mtx) # ============================================================== # # To retain rows of a given expression matrix which have missing # values up to a certain proportion only (30%) ftn.retain.mtx <- function(foo.mtx, max.na.ratio) { foo.mtx[apply(foo.mtx, 1, function(x) length(which(is.na(x)))) <= ncol(foo.mtx)*max.na.ratio, ] } expr.mtx = ftn.retain.mtx(expr.mtx, 0.3) # ************************************************************** # # =========================================== # # To remove ORFs with zero standard deviation zero.sd.orfs = which(apply(expr.mtx, 1, function(x) sd(x, na.rm=T) == 0 )) if ( length(zero.sd.orfs) != 0 ) expr.mtx = expr.mtx[-zero.sd.orfs, ] # ******************************************* # # >>> To load the 'combinat' package <<< # os.win = length(grep('w32', sessionInfo()$R.version$os)) != 0 if ( !('combinat' %in% names(sessionInfo()$otherPkgs)) ) { if ( os.win ) library(combinat) else library(combinat, lib.loc='/home/lee/programming/R.BioC/lib/') } # >>> Preparations <<< # N_mod = length(mod.list) cat("\n\t The number of modules :", N_mod, "\n\n") # !!! The number of random samples cat("\n The number of random samples : ") N_RANDOM = scan(stdin(), quiet=T, nlines=1) cat("\n") time.start <- date() cat("Program Start Time :\n") cat("\t", time.start, "\n\n") cat("====================\n\n") # ============================================= # # To make a unique filename using date and time foo.date <- unlist(strsplit(as.character(Sys.time()), " ")) foo.date <- paste(gsub("-", "", foo.date[1]), ".", gsub(":", "", foo.date[2]), sep="") LOG_FILE = paste(foo.name, foo.date, 'log', sep='.') # ********************************************* # cat(file=LOG_FILE, "\n> Program Goal :\n") cat(file=LOG_FILE, "This program is to calculate the average of absolute Pearson coefficients for ", "all pairs of mRNA expression profiles of all ORFs in each group ", "( ZETA = average(|PCC|) ) and a P-value/Q-value for the difference of the ZETA ", "from the maximum ZETA for the remaining target sets of individual TFs ", "(based on the Pilpel et al. method).\n", sep='', append=T) cat(file=LOG_FILE, "\n> The chosen directory to save output files :\n", foo.path, "\n", sep='', append=T) cat(file=LOG_FILE, "\n> The chosen name for this job :\n", foo.name, "\n", sep='', append=T) if ( answer.qval == 'yes' ) { cat(file=LOG_FILE, "\n> You have q values reported.\n", append=T) } if ( length(zero.sd.orfs) != 0 ) { writeLines(rownames(expr.mtx)[zero.sd.orfs], con=FILENAME_2) cat(file=LOG_FILE, "\n> In the expression matrix provided, there are ", length(zero.sd.orfs), " ORFs with zero standard deviation over all conditions.\n", "They were removed from the matrix, and the list of those ORFs ", "was saved in the following file :\n", FILENAME_2, "\n", sep='', append=T) } ##################################################################### ##### >>>>> MAIN CODE <<<<< ##### ##################################################################### all.orfs <- rownames(expr.mtx) pcc.mtx <- cor(t(expr.mtx), use='pairwise.complete.obs') rm(expr.mtx) ### ! We don't need 'expr.mtx' any more. Save memory. for ( k in 1:N_mod ) { cat("\t # Start of module", k, "...\n\n") orfs.each.mod = mod.list[[k]]$tgs N_orfs = length(orfs.each.mod) orfs.expr <- orfs.each.mod[orfs.each.mod %in% all.orfs] N_orfs.expr <- length(orfs.expr) orfs.mss <- setdiff(orfs.each.mod, orfs.expr) #! cf) orfs.mss <- orfs.each.mod[!orfs.each.mod %in% orfs.expr] if ( length(orfs.mss) != 0 ) { cat(file=FILENAME_3, paste(names(mod.list)[k], "\t", orfs.mss, "\n", sep=''), append=T) } if ( is.null(N_orfs.expr) ) { cat(file=FILENAME_4, paste(names(mod.list)[k], '\t0 ORF\n', sep=''), append=T) next } else if ( N_orfs.expr < 2 ) { cat(file=FILENAME_4, paste(names(mod.list)[k], '\t1 ORF\n', sep=''), append=T) next } else { # ================================ # 1. Calculate the ZETA for the common target genes of TFs (assuming two TFs, X and Y). # : Zeta_XY for the gene set, Genes_XY # ================================ mod.pairs <- as.matrix(combn(orfs.expr, 2)) mod.pairs.ind <- cbind(match(mod.pairs[1, ], all.orfs), match(mod.pairs[2, ], colnames(pcc.mtx))) mod.pairs.pcc <- apply(mod.pairs.ind, 1, function(x) pcc.mtx[x[1], x[2]]) ZETA.Mod.Real <- mean(abs(mod.pairs.pcc)) # ================================ # 2. Calculate the ZETA for the remaining target genes of X. # : Zeta_X|Y for the gene set, Genes_X - Genes_XY (== Genes_X|Y) # 3. Calculate the ZETA for the remaining target genes of Y. # : Zeta_Y|X for the gene set, Genes_Y - Genes_XY (== Genes_Y|X) # ================================ tfs.each.mod = mod.list[[k]]$tfs ZETAs.for.TFs = vector('numeric', length = length(tfs.each.mod)) names(ZETAs.for.TFs) = tfs.each.mod for ( ind_tf in 1:length(tfs.each.mod) ) { Genes_X = rownames(chip.data)[which(chip.data[, tfs.each.mod[ind_tf]] < chip.pval.thrs)] Genes_X = Genes_X[Genes_X %in% all.orfs] Genes_Xonly = Genes_X[!Genes_X %in% orfs.expr] if ( length(Genes_Xonly) >= 2 ) { mod.pairs.eachTF = as.matrix(combn(Genes_Xonly, 2)) mod.pairs.ind.eachTF = cbind(match(mod.pairs.eachTF[1, ], all.orfs), match(mod.pairs.eachTF[2, ], colnames(pcc.mtx))) mod.pairs.pcc.eachTF = apply(mod.pairs.ind.eachTF, 1, function(x) pcc.mtx[x[1], x[2]]) ZETA.Mod.eachTF = mean(abs(mod.pairs.pcc.eachTF)) ZETAs.for.TFs[ind_tf] = ZETA.Mod.eachTF } } if ( any(ZETAs.for.TFs == 0) ) { Delta_Zeta = 0 P_value = 1 cat(file=FILENAME_1, names(mod.list)[k], "\t", paste(tfs.each.mod, collapse='_'), '\t', N_orfs, "\t", N_orfs.expr, "\t", ZETA.Mod.Real, "\t", Delta_Zeta, "\t", P_value, "\n", sep="", append=T) next } # ================================ # 4. Decide which TF gives the maximum Zeta (most coherent). Assume that it is X. # : TF_max = X such that Zeta_X|Y >= Zeta_Y|X # ================================ Zeta_TFs_max = max(ZETAs.for.TFs) TF_max = names(which(ZETAs.for.TFs == Zeta_TFs_max)) # ================================ # 5. Decide if X and Y are synergistic by requiring the following condition. # : Delta_Zeta = Zeta_XY - Zeta_X|Y > 0 # ================================ Delta_Zeta = ZETA.Mod.Real - Zeta_TFs_max if ( Delta_Zeta <= 0 ) { P_value = 1 cat(file=FILENAME_1, names(mod.list)[k], "\t", N_orfs, "\t", N_orfs.expr, "\t", ZETA.Mod.Real, "\t", Delta_Zeta, "\t", P_value, "\n", sep="", append=T) next } # ================================ # 6. Test if Delta_Zeta is statistically significant as follows. # ================================ DELTAs_rnd = NULL for ( ind_rnd in 1:N_RANDOM ) { # >>> Target set of the TF_max <<< # Genes_X = rownames(chip.data)[which(chip.data[, TF_max] < chip.pval.thrs)] Genes_X = Genes_X[Genes_X %in% all.orfs] # ================================ # 7. Divide the gene set, Genes_X, into two random groups corresponding to # the two sets, Genes_XY and Genes_X|Y, respectively. # : Genes_XY_rnd and Genes_X|Y_rnd # ================================ Genes_XY_rnd = sample(Genes_X, N_orfs.expr) Genes_Xonly_rnd = Genes_X[!Genes_X %in% Genes_XY_rnd] Genes_rnd = list(G_XY_rnd = Genes_XY_rnd, G_Xonly_rnd = Genes_Xonly_rnd) # ================================ # 8. Calculate the difference between the Zeta's for the two random groups. # : Delta_Zeta_rnd = Zeta_XY_rnd - Zeta_X|Y_rnd # ================================ if ( length(Genes_Xonly_rnd) < 2 ) { DELTAs_rnd = rep(1, N_RANDOM) break } else { ZETAs_rnd = sapply(Genes_rnd, function(tmp.genes) { tmp.pairs <- as.matrix(combn(tmp.genes, 2)) tmp.pairs.ind <- cbind(match(tmp.pairs[1, ], all.orfs), match(tmp.pairs[2, ], colnames(pcc.mtx))) tmp.pairs.pcc <- apply(tmp.pairs.ind, 1, function(x) pcc.mtx[x[1], x[2]]) ZETA.tmp <- mean(abs(tmp.pairs.pcc)) }) Delta_Zeta_rnd = as.numeric(ZETAs_rnd['G_XY_rnd'] - ZETAs_rnd['G_Xonly_rnd']) } # ================================ # 9. Make an emperical distribution of Delta_Zeta_rnd values by dividing Genes_X # many times repeatedly (e.g. 1000 times). # ================================ DELTAs_rnd = c(DELTAs_rnd, Delta_Zeta_rnd) cat(ind_rnd, ' ') } cat('\n') # ================================ # 10. Calculate a P-value by counting the number of Delta_Zeta_rnd values which are # greater than or equal to the observed difference, Delta_Zeta. # : P-value = sum(Delta_Zeta_rnd >= Delta_Zeta) / simul.times # ================================ P_value = sum(DELTAs_rnd >= Delta_Zeta) / N_RANDOM cat(file=FILENAME_1, names(mod.list)[k], "\t", paste(tfs.each.mod, collapse='_'), '\t', N_orfs, "\t", N_orfs.expr, "\t", ZETA.Mod.Real, "\t", Delta_Zeta, "\t", P_value, "\n", sep="", append=T) # ================================ # 11. To draw a histogram if necessary # ================================ # if ( P_value == 1 ) next # tmp.range = c(DELTAs_rnd, Delta_Zeta) # jpeg(file=paste('./histograms/', names(mod.list)[k], '.jpg', sep=''), # quality=100, width=800, height=600) # hist(DELTAs_rnd, col='grey90', xlim=c(min(tmp.range), max(tmp.range)), # main=paste(paste(tfs.each.mod, collapse='_'), 'vs.', TF_max)) # abline(v=Delta_Zeta, lwd=5, col='red') # dev.off() } cat("\n\n\t\t ... Module", k, "Done!\n\n\n") } if ( ANSWER_ALL == 'yes' ) { # >>> To re-format the result table <<< foo.result <- as.matrix(read.table(file=FILENAME_1, sep="\t")) rownames(foo.result) <- NULL colnames(foo.result) <- c("Module", "TFs", "N_ORFs", "N_Expr", "ZETA", "DELTA", "P_value") foo.result <- foo.result[order(as.numeric(foo.result[, "P_value"])), ] rownames(foo.result) <- 1:nrow(foo.result) # >>> P-value correction by the FDR control <<< p.values <- as.numeric(foo.result[, "P_value"]) foo.result <- cbind(foo.result, p.adjust(p.values, "fdr")) # >>> Q-value calculation if requested <<< if ( answer.qval == "yes" ) { library(qvalue) qobj <- qvalue(p.values) foo.result <- cbind(foo.result, qobj$qvalues) # foo.result[, 5:9] <- formatC(as.numeric(foo.result[, 5:9]), format="e", digits=3) colnames(foo.result) <- c("Module", "TFs", "N_ORFs", "N_Expr", "ZETA", "DELTA", "P_value", "P_FDR", "Q_value") } else if ( answer.qval == "no" ) { # foo.result[, 5:8] <- formatC(as.numeric(foo.result[, 5:8]), format="e", digits=3) colnames(foo.result) <- c("Module", "TFs", "N_ORFs", "N_Expr", "ZETA", "DELTA", "P_value", "P_FDR") } write.table(file=FILENAME_1, foo.result, sep="\t", quote=F) } time.end <- date() cat("====================\n\n") cat("The final result file, '", FILENAME_1, "', has been saved in the directory, '", foo.path, "'.\n", sep="") if ( file.exists(FILENAME_2) | file.exists(FILENAME_3) | file.exists(FILENAME_4) ) { cat("The following files also have been created in the same directory:\n") if ( file.exists(FILENAME_2) ) { cat(FILENAME_2, '\n') } if ( file.exists(FILENAME_3) ) { cat(FILENAME_3, '\n') cat("\n> There are ORFs with no expression values. They were saved in the following file :\n", FILENAME_3, "\n", sep='', file = LOG_FILE, append=T) } if ( file.exists(FILENAME_4) ) { cat(FILENAME_4, '\n') cat("\n> There are modules with less than 2 ORFs. They were saved in the following file :\n", FILENAME_4, "\n", sep='', file = LOG_FILE, append=T) } } cat("\nThe log file '", LOG_FILE, "' has been created in the same directory for the job summary.\n\n", sep='') cat("\n!!!___Program Done___!!!\n\n") cat(file=LOG_FILE, "\n> Program Start Time :\n", append=T) cat(file=LOG_FILE, "\t", time.start, "\n", append=T) cat(file=LOG_FILE, "\n> Program End Time :\n", append=T) cat(file=LOG_FILE, "\t", time.end, "\n\n", append=T) cat("Program Start Time:\n") cat("\t", time.start, "\n") cat("Program End Time:\n") cat("\t", time.end, "\n\n") }
73c14771ab1ff402a0d1756e4156341f7645ce3b
[ "Markdown", "R" ]
5
Markdown
bshkspr/Lee2008
2cef870fadec3a8938cfd0b59398fb72b035ed4d
8f9a0a890e7886d7245a7f11755ead60521795cb
refs/heads/main
<repo_name>RazvanRauta/MealsToGo<file_sep>/src/features/restaurants/screens/MapScreen/index.jsx /** * @author: <NAME> * Date: Apr 07 2021 * Time: 22:03 */ import { SafeArea } from '@/components/SafeArea'; import React from 'react'; import { View, Text, StatusBar } from 'react-native'; const MapScreen = () => { return ( <SafeArea currentHeight={StatusBar.currentHeight}> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Map</Text> </View> </SafeArea> ); }; export default MapScreen; <file_sep>/src/features/restaurants/screens/RestaurantsScreen/index.jsx /** * @author: <NAME> * Date: Apr 05 2021 * Time: 21:28 */ import { SafeArea } from '@/components/SafeArea'; import Spacer from '@/components/Spacer'; import React from 'react'; import { FlatList, StatusBar } from 'react-native'; import { Searchbar } from 'react-native-paper'; import styled from 'styled-components/native'; import RestaurantInfoCard from '../../components/RestaurantInfoCard'; const SearchContainer = styled.View` padding: ${(props) => props.theme.space[3]}; `; const RestaurantsList = styled(FlatList).attrs(({ theme }) => { const padding = parseInt(theme.space[3], 10); return { contentContainerStyle: { padding, }, }; })``; export default function RestaurantsScreen() { return ( <SafeArea currentHeight={StatusBar.currentHeight}> <SearchContainer> <Searchbar /> </SearchContainer> <RestaurantsList data={[ { name: 'some restaurant' }, { name: 'other restaurant' }, { name: 'third restaurant' }, ]} renderItem={() => ( <Spacer position="bottom" size="large"> <RestaurantInfoCard /> </Spacer> )} keyExtractor={(item) => item.name} /> </SafeArea> ); } <file_sep>/src/features/restaurants/components/RestaurantInfoCard/styles.js import styled from 'styled-components/native'; import { Card } from 'react-native-paper'; const RestaurantCard = styled(Card)` background-color: ${(props) => props.theme.colors.bg.primary}; `; const RestaurantCardCover = styled(Card.Cover)` padding: ${(props) => props.theme.space[3]}; background-color: ${(props) => props.theme.colors.bg.primary}; `; const InfoContainer = styled.View` padding: ${(props) => props.theme.space[3]}; `; const Address = styled.Text` font-family: ${(props) => props.theme.fonts.body}; font-size: ${(props) => props.theme.fontSizes.caption}; `; const RatingContainer = styled.View` flex-direction: row; `; const Section = styled.View` flex-direction: row; padding: ${(props) => props.theme.space[2]} 0 ${(props) => props.theme.space[2]}; justify-content: space-between; align-items: center; `; const SectionEnd = styled.View` flex: 1; flex-direction: row; justify-content: flex-end; `; const Icon = styled.Image` width: 15px; height: 15px; `; export { RestaurantCard, RestaurantCardCover, InfoContainer, Address, RatingContainer, Section, SectionEnd, Icon, }; <file_sep>/src/components/SafeArea/index.jsx /** * @author: <NAME> * Date: Apr 07 2021 * Time: 22:06 */ import { SafeAreaView } from 'react-native-safe-area-context'; import styled from 'styled-components/native'; export const SafeArea = styled(SafeAreaView)` flex: 1; margin-top: ${(props) => props.currentHeight ?? 0}px; `; <file_sep>/src/features/restaurants/screens/SettingsScreen/index.jsx /** * @author: <NAME> * Date: Apr 07 2021 * Time: 21:58 */ import { SafeArea } from '@/components/SafeArea'; import React from 'react'; import { Text, View, StatusBar } from 'react-native'; const SettingsScreen = () => { return ( <SafeArea currentHeight={StatusBar.currentHeight}> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Settings!</Text> </View> </SafeArea> ); }; export default SettingsScreen;
e287dd855a928a0604814ca91a642e355de7046e
[ "JavaScript" ]
5
JavaScript
RazvanRauta/MealsToGo
a2627f11b1235e406b40833ce476c68ba2745fb9
8509363e315bb247b86d43ad0a1f38beeaf9d984
refs/heads/master
<repo_name>LushaTeam/arena<file_sep>/public/dashboard.js let refreshTimer = null; let refreshInterval = null; $(document).ready(() => { const basePath = $('#basePath').val(); function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function setRefreshInterval(value) { refreshInterval = value; refreshTimer = setInterval(() => { window.location.reload(); }, value * 1000); } const savedRefreshInterval = Number(localStorage.getItem('arena:refreshInterval')); if (savedRefreshInterval) { $('#refresh').val(String(savedRefreshInterval)); if (savedRefreshInterval) setRefreshInterval(savedRefreshInterval); } $('#refresh').on('change', function(e) { if (refreshTimer) clearInterval(refreshTimer); const refreshInterval = Number($('#refresh').val()); localStorage.setItem('arena:refreshInterval', String(refreshInterval)); if (!refreshInterval) return; setRefreshInterval(refreshInterval); }); $('.js-pause-queue').on('click', function(e) { $(this).prop('disabled', true); const queueName = $(this).data('queue-name'); const queueHost = $(this).data('queue-host'); const r = window.confirm(`Pause new jobs in queue "${queueHost}/${queueName}"?`); if (r) { $.ajax({ method: 'POST', url: `${basePath}/api/queue/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/pause`, }).done(() => { window.location.reload(); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); $('.js-resume-queue').on('click', function(e) { $(this).prop('disabled', true); const queueName = $(this).data('queue-name'); const queueHost = $(this).data('queue-host'); const r = window.confirm(`Resume jobs in queue "${queueHost}/${queueName}"?`); if (r) { $.ajax({ method: 'POST', url: `${basePath}/api/queue/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/resume`, }).done(() => { window.location.reload(); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); $('.js-pause-queues').on('click', function(e) { $(this).prop('disabled', true); const r = window.confirm(`Pause new jobs in all queues?`); if (r) { $.ajax({ method: 'POST', url: `${basePath}/api/queues/pause`, }).done(() => { $(this).prop('disabled', false); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); $('.js-resume-queues').on('click', function(e) { $(this).prop('disabled', true); const r = window.confirm(`Resume jobs in all queues?`); if (r) { $.ajax({ method: 'POST', url: `${basePath}/api/queues/resume`, }).done(() => { $(this).prop('disabled', false); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); // Set up individual "retry job" handler $('.js-retry-job').on('click', function(e) { e.preventDefault(); $(this).prop('disabled', true); const jobId = $(this).data('job-id'); const jobDisplayName = $(this).data('job-display-name'); const queueName = $(this).data('queue-name'); const queueHost = $(this).data('queue-host'); const r = window.confirm(`Retry job "${jobDisplayName}" in queue "${queueHost}/${queueName}"?`); if (r) { $.ajax({ method: 'PATCH', url: `${basePath}/api/queue/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/job/${encodeURIComponent(jobId)}` }).done(() => { window.location.reload(); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); // Set up individual "remove job" handler $('.js-remove-job').on('click', function(e) { e.preventDefault(); $(this).prop('disabled', true); const jobId = $(this).data('job-id'); const jobDisplayName = $(this).data('job-display-name'); const queueName = $(this).data('queue-name'); const queueHost = $(this).data('queue-host'); const jobState = $(this).data('job-state'); const r = window.confirm(`Remove job "${jobDisplayName}" in queue "${queueHost}/${queueName}"?`); if (r) { $.ajax({ method: 'DELETE', url: `${basePath}/api/queue/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/job/${encodeURIComponent(jobId)}` }).done(() => { window.location.href = `${basePath}/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/${jobState}`; }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); // Set up "select all jobs" button handler $('.js-select-all-jobs').change(function() { const $jobBulkCheckboxes = $('.js-bulk-job'); $jobBulkCheckboxes.prop('checked', this.checked); }); // Set up "shift-click" multiple checkbox selection handler (function() { // https://stackoverflow.com/questions/659508/how-can-i-shift-select-multiple-checkboxes-like-gmail let lastChecked = null; let $jobBulkCheckboxes = $('.js-bulk-job'); $jobBulkCheckboxes.click(function(e) { if (!lastChecked) { lastChecked = this; return; } if (e.shiftKey) { let start = $jobBulkCheckboxes.index(this); let end = $jobBulkCheckboxes.index(lastChecked); $jobBulkCheckboxes.slice( Math.min(start, end), Math.max(start, end) + 1 ).prop('checked', lastChecked.checked); } lastChecked = this; }); })(); // Set up bulk actions handler $('.js-bulk-action').on('click', function(e) { $(this).prop('disabled', true); const $bulkActionContainer = $('.js-bulk-action-container'); const action = $(this).data('action'); const queueName = $(this).data('queue-name'); const queueHost = $(this).data('queue-host'); const queueState = $(this).data('queue-state'); let data = { queueName, action: 'remove', jobs: [] }; $bulkActionContainer.each((index, value) => { const isChecked = $(value).find('[name=jobChecked]').is(':checked'); const id = encodeURIComponent($(value).find('[name=jobId]').val()); if (isChecked) { data.jobs.push(id); } }); const r = window.confirm(`${capitalize(action)} ${data.jobs.length} ${data.jobs.length > 1 ? 'jobs' : 'job'} in queue "${queueHost}/${queueName}"?`); if (r) { $.ajax({ method: action === 'remove' ? 'POST' : 'PATCH', url: `${basePath}/api/queue/${encodeURIComponent(queueHost)}/${encodeURIComponent(queueName)}/job/bulk`, data: JSON.stringify(data), contentType: 'application/json' }).done(() => { window.location.reload(); }).fail((jqXHR) => { window.alert(`Request failed, check console for error.`); console.error(jqXHR.responseText); }); } else { $(this).prop('disabled', false); } }); $('.js-toggle-add-job-editor').on('click', function() { $('.jsoneditorx').toggleClass('hide'); const data = localStorage.getItem('arena:savedJobData') || '{ id: \'\' }'; window.jsonEditor.set(JSON.parse(data)); }); $('.js-add-job').on('click', function() { const data = window.jsonEditor.get(); localStorage.setItem('arena:savedJobData', JSON.stringify(data)); const { queueHost, queueName } = window.arenaInitialPayload; $.ajax({ url: `${basePath}/api/queue/${queueHost}/${queueName}/job`, type: 'POST', data: JSON.stringify(data), contentType: 'application/json' }).done(() => { alert('Job successfully added!'); localStorage.removeItem('arena:savedJobData'); }).fail((jqXHR) => { window.alert('Failed to save job, check console for error.'); console.error(jqXHR.responseText); }); }); }); <file_sep>/src/server/views/dashboard/queueList.js async function handler(req, res) { const {Queues} = req.app.locals; const queues = Queues.list(); const basePath = req.baseUrl; const now = Date.now(); const yesterday = now - (24 * 60 * 60 * 1000); const hourAgo = now - (60 * 60 * 1000); let singleHost = true; let active = 0; let waiting = 0; let completedLastHourCount = 0; let completedLastDayCount = 0; let failedLastHourCount = 0; let failedLastDayCount = 0; let completed, failed; for (const q of queues) { const queue = await Queues.get(q.name, q.hostId); if (!queue) return res.status(404).send({ error: 'queue not found' }); if (singleHost) { if (singleHost === true) singleHost = q.hostId; else if (singleHost !== q.hostId) singleHost = false; } q.activeCount = await queue.getActiveCount(); active += q.activeCount; q.waitingCount = await queue.getWaitingCount(); waiting += q.waitingCount; q.completedLastHourCount = 0; q.completedLastDayCount = 0; q.failedLastHourCount = 0; q.failedLastDayCount = 0; completed = await queue.getCompleted(); failed = await queue.getFailed(); for (const job of completed) { if (job.finishedOn > yesterday) { q.completedLastDayCount++; completedLastDayCount++; if (job.finishedOn > hourAgo) { q.completedLastHourCount++; completedLastHourCount++; } } } for (const job of failed) { const lastTimestamp = job.finishedOn || job.processedOn; if (lastTimestamp > yesterday) { q.failedLastDayCount++; failedLastDayCount++; if (lastTimestamp > hourAgo) { q.failedLastHourCount++; failedLastHourCount++; } } } } return res.render('dashboard/templates/queueList', { basePath, queues, showHostColumn: !singleHost, active, waiting, completedLastHourCount, completedLastDayCount, failedLastHourCount, failedLastDayCount }); } module.exports = handler; <file_sep>/src/server/views/api/queuePause.js async function handler(req, res) { const { queueName, queueHost } = req.params; const {Queues} = req.app.locals; const queue = await Queues.get(queueName, queueHost); if (!queue) return res.status(404).send({error: 'queue not found'}); try { await queue.pause(); return res.sendStatus(200); } catch (e) { const body = { error: 'queue error', details: e.stack }; return res.status(500).send(body); } } module.exports = handler; <file_sep>/src/server/views/dashboard/jobDetails.js const _ = require('lodash'); const util = require('util'); async function handler(req, res) { const { queueName, queueHost, id } = req.params; const { json } = req.query; const basePath = req.baseUrl; const {Queues} = req.app.locals; const queue = await Queues.get(queueName, queueHost); if (!queue) return res.status(404).render('dashboard/templates/queueNotFound', {basePath, queueName, queueHost}); const job = await queue.getJob(id); if (!job) return res.status(404).render('dashboard/templates/jobNotFound', {basePath, id, queueName, queueHost}); if (json === 'true') { delete job.queue; // avoid circular references parsing error return res.json(job); } let jobState; if (queue.IS_BEE) { jobState = job.status; } else { jobState = await job.getState(); } job.displayName = job.data.name || job.name || job.id; if (job.finishedOn) job.duration = job.finishedOn - job.processedOn; else if (jobState === 'active') job.duration = Date.now() - job.processedOn; return res.render('dashboard/templates/jobDetails', { basePath, queueName, queueHost, jobState, job }); } module.exports = handler; <file_sep>/src/server/views/api/queuesPause.js async function handler(req, res) { const {Queues} = req.app.locals; const queues = Queues.list(); for (const item of queues) { const queue = await Queues.get(item.name, item.hostId); if (!queue) return res.status(404).send({ error: 'queue not found' }); try { await queue.pause(); } catch (e) { const body = { error: 'queue error', details: e.stack }; return res.status(500).send(body); } } return res.sendStatus(200); } module.exports = handler;
a86236a3a3d6884ae9bd0e57bccdbcfb321a12d4
[ "JavaScript" ]
5
JavaScript
LushaTeam/arena
5befd0819fe5e46c0303bc374eb35883746259ae
70981fda8fb1427b7372cb881c2b005f20091171
refs/heads/master
<file_sep> <?php include 'head.php'; if (isset($_GET['e'])){ switch ($_GET['e']) { case '0': include 'reg.php'; break; case '1': include 'aut.php'; break; default: echo 'lo siento necesitas autorizacion para acceder'; break; } }else include 'subindex.php'; include 'foot.php'; ?><file_sep># st #Desarrollo de #Software para #Tutorías. Desarrollado en #Php, #html, #js, #bootstrap
b20a34baba46d5a5d99d8d70df17250b60cd7749
[ "Markdown", "PHP" ]
2
PHP
neokeyboard/st
fa32cb8a45370c7231d956e72adaa926cd813358
187aaca13a8b7029f5ff1aac4d1a5d543392ac30
refs/heads/main
<repo_name>SuhyunMin/Knittin_Ball<file_sep>/Assets/Scripts/VolumeChangeScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class VolumeChangeScript : MonoBehaviour { private AudioSource audioSrc2; private float musicVolume2 = 1f; private void Awake() { DontDestroyOnLoad(gameObject); } // Start is called before the first frame update void Start() { audioSrc2 = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { audioSrc2.volume = musicVolume2; } public void SetVolume(float vol) { musicVolume2 = vol; } } <file_sep>/Assets/Scripts/CandyMoveScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CandyMoveScript : MonoBehaviour { public float speed = 0.1f; Vector2 temp; int num=0; public Sprite[] sprites; public GameObject candytree_left, candtree_right; // Start is called before the first frame update void Start() { temp = transform.localScale; sprites = Resources.LoadAll<Sprite>("Candytree"); } // Update is called once per frame void Update() { Moving(); } void Moving(){ if(transform.position.y <= -6f){ transform.position = new Vector2(0,0); temp = new Vector2(1,1); ColorChange(); }else{ transform.Translate(Vector2.down*speed*Time.deltaTime*20); SizeUp(); } } void SizeUp(){ transform.localScale = temp + new Vector2(0.4f*Time.deltaTime,0.4f*Time.deltaTime); temp = transform.localScale; } void ColorChange(){ int i = Random.Range(0,6); candtree_right.GetComponent<SpriteRenderer>().sprite = sprites[i]; i = Random.Range(0,6); candytree_left.GetComponent<SpriteRenderer>().sprite = sprites[i]; } } <file_sep>/Assets/Scripts/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public float moveSpeed; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { TouchMove(); } void TouchMove() { if (Input.GetMouseButton(0)) { Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); if(mousePos.x > 1) { transform.Translate(moveSpeed * Time.deltaTime, 0, 0); } else if(mousePos.x < -1) { transform.Translate(-moveSpeed * Time.deltaTime, 0, 0); } } } } <file_sep>/Assets/Scripts/KnittedBallMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class KnittedBallMovement : MonoBehaviour { ColorLine colorLine; public GameObject ColorLine; float time = 3.0f; public float speed = 0.1f; Vector2 temp; int num = 0; public Sprite[] sprites; public GameObject ball, ball_1, ball_2; // Start is called before the first frame update void Start() { temp = transform.localScale; sprites = Resources.LoadAll<Sprite>("Knitted_Ball"); colorLine = GameObject.Find("ColorLine").GetComponent<ColorLine>(); ColorChange(); } // Update is called once per frame void Update() { if (time >= 0) { ball.GetComponent<Renderer>().enabled = false; ball_1.GetComponent<Renderer>().enabled = false; ball_2.GetComponent<Renderer>().enabled = false; time -= Time.deltaTime; return; } else { ball.GetComponent<Renderer>().enabled = true; ball_1.GetComponent<Renderer>().enabled = true; ball_2.GetComponent<Renderer>().enabled = true; Moving(); } } void Moving() { if (transform.position.y <= -15f) { ball.SetActive(true); ball_1.SetActive(true); ball_2.SetActive(true); transform.position = new Vector2(0, 0); temp = new Vector2(1, 1); ColorChange(); } else { transform.Translate(Vector2.down * speed * Time.deltaTime * 20); SizeUp(); } } void SizeUp() { transform.localScale = temp + new Vector2(0.3f * Time.deltaTime, 0.3f * Time.deltaTime); temp = transform.localScale; } void ColorChange() { int i = Random.Range(0, 3); int j = Random.Range(0, 3); int k = Random.Range(0, 3); int x = Random.Range(0, 2); List<int> BallColor = new List<int>(); BallColor.Add(i); BallColor.Add(j); BallColor.Add(k); if (colorLine.lineColor.Equals("Green")){ if (!BallColor.Contains(0)) { BallColor.RemoveAt(x); BallColor.Insert(x, 0); i = BallColor[0]; j = BallColor[1]; k = BallColor[2]; } } else if (colorLine.lineColor.Equals("Purple")){ if (!BallColor.Contains(1)) { BallColor.RemoveAt(x); BallColor.Insert(x, 1); i = BallColor[0]; j = BallColor[1]; k = BallColor[2]; } } else if (colorLine.lineColor.Equals("Red")) { if (!BallColor.Contains(2)) { BallColor.RemoveAt(x); BallColor.Insert(x, 2); i = BallColor[0]; j = BallColor[1]; k = BallColor[2]; } } else if (colorLine.lineColor.Equals("Sky")) { if (!BallColor.Contains(3)) { BallColor.RemoveAt(x); BallColor.Insert(x, 3); i = BallColor[0]; j = BallColor[1]; k = BallColor[2]; } } ball.GetComponent<SpriteRenderer>().sprite = sprites[i]; ball_1.GetComponent<SpriteRenderer>().sprite = sprites[j]; ball_2.GetComponent<SpriteRenderer>().sprite = sprites[k]; } } <file_sep>/Assets/Scripts/ColorLine.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ColorLine : MonoBehaviour { public string lineColor; public float speed = 5000f; Vector2 temp; int num = 0; public Sprite[] sprites; public Sprite[] bubble_sprites; public GameObject colorLine; public GameObject Thinking_Bubble_Purple; // Start is called before the first frame update void Start() { temp = transform.localScale; sprites = Resources.LoadAll<Sprite>("ColorLine"); bubble_sprites = Resources.LoadAll<Sprite>("ThinkingBubble"); ColorChange(); } // Update is called once per frame void Update() { Moving(); } void Moving() { //if u want ColorLine time delay change 'if (transform.position.y <= (this)f)' if (transform.position.y <= -20f) { transform.position = new Vector2(0, 2.9f); temp = new Vector2(0.45f, 0.5f); ColorChange(); } else { transform.Translate(Vector2.down * speed * Time.deltaTime * 20); SizeUp(); } } void SizeUp() { transform.localScale = temp + new Vector2(0.35f * Time.deltaTime, 0.1f * Time.deltaTime); temp = transform.localScale; } void ColorChange() { int i = Random.Range(0, 3); colorLine.GetComponent<SpriteRenderer>().sprite = sprites[i]; Debug.Log(sprites[i]); lineColor = sprites[i].name; //ToString() 대신 .name 사용 가능 } } <file_sep>/README.md # Knittin_Ball <file_sep>/Assets/Scripts/ThinkBubbleChange.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThinkBubbleChange : MonoBehaviour { ColorLine colorLine; public GameObject ColorLine; public GameObject Bear; public GameObject Thinking_Bubble; public Sprite[] bubble_sprites; public Vector3 linepos; // Start is called before the first frame update void Start() { colorLine = GameObject.Find("ColorLine").GetComponent<ColorLine>(); bubble_sprites = Resources.LoadAll<Sprite>("ThinkingBubble"); Thinking_Bubble.SetActive(false); } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D collision) { Debug.Log(colorLine.lineColor); switch (colorLine.lineColor) { case "Green": Thinking_Bubble.GetComponent<SpriteRenderer>().sprite = bubble_sprites[0]; Debug.Log("초록"); break; case "Purple": Thinking_Bubble.GetComponent<SpriteRenderer>().sprite = bubble_sprites[1]; Debug.Log("보라"); break; case "Red": Thinking_Bubble.GetComponent<SpriteRenderer>().sprite = bubble_sprites[2]; Debug.Log("빨강"); break; case "Sky": Thinking_Bubble.GetComponent<SpriteRenderer>().sprite = bubble_sprites[3]; Debug.Log("하늘"); break; default: Debug.Log("colorLine 없음"); break; } Thinking_Bubble.SetActive(true); } } <file_sep>/Assets/Scripts/GameController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameController : MonoBehaviour { public static GameController Instance; public GameObject panel; public Text score; private void Awake() { if(Instance == null) { Instance = this; } } // Start is called before the first frame update void Start() { panel = GameObject.Find("Canvas").transform.Find("Panel").gameObject; } // Update is called once per frame void Update() { } public void GameOver() { Debug.Log("GAME OVER"); Time.timeScale = 0; panel.gameObject.SetActive(true); score.text = "score : " + ScoreUpScript.totalScore; } public void OnClickMain() { Time.timeScale = 1; SceneManager.LoadScene("Start Scene"); } public void OnClickRetry() { Time.timeScale = 1; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } <file_sep>/Assets/Scripts/ScoreUpScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScoreUpScript : MonoBehaviour { string color, bubble_color; int score=0; public GameObject bubble; public Text score_text; public static string totalScore; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.tag=="ball"){ collision.gameObject.SetActive(false); color = collision.gameObject.GetComponent<SpriteRenderer>().sprite.name; bubble_color = bubble.GetComponent<SpriteRenderer>().sprite.name; Debug.Log("////컬러:"+color+"/////버블:"+bubble_color); if(color.Equals(bubble_color)){ score++; score_text.text=score+""; totalScore = score.ToString(); } else { FindObjectOfType<GameController>().GameOver(); } } } }
33f1e0e9199a6bbda82b410bfbb61368900fcc3f
[ "Markdown", "C#" ]
9
C#
SuhyunMin/Knittin_Ball
26fe32c5a46cc1819b082821b4f8a6030cca4291
dfb79fa4538e1692a99bd454c46198e6c652c490
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pipex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mocherqu <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/18 17:24:08 by mdaifi #+# #+# */ /* Updated: 2021/06/27 17:20:04 by mocherqu ### ########.fr */ /* */ /* ************************************************************************** */ #include "pipex.h" void free_split(char **str) { int i; i = 0; while (str[i]) { free(str[i]); i++; } free(str); } void ft_free_list(t_list *head) { t_list *tmp; tmp = head; while (head != NULL) { tmp = head; head = head->next; free(tmp); } } void ft_pipex(t_var *var) { while (var->path[++var->i] && !var->j) { var->str = ft_strjoin(var->path[var->i], var->tab[0]); if (!access(var->str, F_OK)) { var->tab[0] = ft_strdup(var->str); var->j = 1; } free(var->str); } } int main(int argc, char **argv, char *env[]) { t_list *pipe1; t_var *var; if (argc == 5) { var = (t_var *)malloc(sizeof(t_var)); var->tmp2 = ft_split(argv[2], ' '); pipe1 = ft_lstnew(var->tmp2); var->tmp3 = ft_split(argv[3], ' '); ft_lstadd_back(&pipe1, ft_lstnew(var->tmp3)); var->tab = (char **)pipe1->content; var->tmp = ft_substr(env[6], 5, ft_strlen(env[6])); var->path = ft_split(var->tmp, ':'); free(var->tmp); var->str = var->path[0]; var->i = -1; var->j = 0; ft_pipex(var); if (access(argv[1], F_OK)) { perror(""); exit(1); } var->fd = pipe(var->p); if (var->fd == -1) { perror(""); exit(1); } var->fd = open(argv[4], O_RDWR | O_CREAT | O_TRUNC, 0755); var->fd2 = open(argv[1], O_RDONLY); if (var->fd == -1) { perror(""); exit(1); } var->pid = fork(); if (var->pid == 0) { var->pid2 = fork(); if (var->pid2 == 0) { dup2(var->fd2, 0); dup2(var->p[1], 1); dup2(var->p[1], 2); if (execve(var->tab[0], var->tab, env) < 0) { perror(""); exit(1); } exit(0); } var->i = -1; var->j = 0; free_split(var->tab); var->tab = (char **)pipe1->next->content; ft_pipex(var); close(var->p[1]); dup2(var->p[0], 0); close(var->p[0]); dup2(var->fd, 1); if (execve(var->tab[0], var->tab, NULL) < 0) { perror(""); exit(1); } } else { close(var->fd2); close(var->p[1]); close(var->p[0]); wait(0); } // free(pipe1->content); // printf("%s\n", var->tmp2[0]); // printf("%s\n", pipe1->content[0]); // if (pipe1->content != NULL) // free_split(pipe1->content); printf("tmp[2] : %s\n", var->tmp2[0]); free_split(var->tmp2); free_split(var->tmp3); free_split(var->path); printf("OK\n"); free(var); ft_free_list(pipe1); } else write(1, "Invalid number of arguments !\n", 31); return (0); }
f7531fa291959562ab5bcd199844f051ec2ee02d
[ "C" ]
1
C
mouhcinecherqui/pipex
567a03bdf12421f44e49248d7bf3a6d37b6370e2
4d29ba49f19f1bd725a4b549f3478533afdd5c5a
refs/heads/master
<repo_name>tuxmania87/chessbot-tuxbot<file_sep>/bot_pychess.py import requests import json import chess from chessutil import ChessUtils import threading import random from movegen import MovementGenerator import time token = "T<PASSWORD>" header = {"Authorization":"Bearer {}".format(token)} #doMove = m.get_next_move_alpha_beta #doMove = m.get_next_move_pv_search_board1 class Game: def __init__(self, id, play_time, increment): self.id = id self.play_time = play_time self.increment = increment self.used_time = 0 self.moves = 0 self.playGame() def doMoveWrapper(self, b, designated_depth, time_per_move): # calculate remaining time remaining = self.play_time - (self.used_time - self.moves * self.increment) print(f"Remaining {remaining}") _s = time.time() move = self.doMove(b, designated_depth, 2 if remaining < 60 else time_per_move) self.used_time += time.time() - _s self.moves += 1 def playGame(self): b = chess.Board() #print(a,b,c,d,e,f,g,h) requests.post("https://lichess.org/api/challenge/{}/accept".format(self.id), headers=header) r = requests.get("https://lichess.org/api/bot/game/stream/{}".format(self.id), headers=header, stream=True) # https://lichess.org/api/bot/game/stream/{gameId} c = ChessUtils() m = MovementGenerator() self.doMove = m.get_next_move_tuxfish designated_depth = 6 # calculate max time per move ## asuming we want to do 80 moves without be flagged time_per_move = int((80 * self.increment + self.play_time) / 80) #designated_time = 4 amIwhite = False for line in r.iter_lines(): decoded_line = line.decode('utf-8') if (decoded_line != ''): j = json.loads(decoded_line) print("XX ", j) if j["type"] == "gameFinish": _game = j["game"] if _game["id"] == self.id: print("GAME FINISHED AND ABORTED") blocked = False return if j["type"] == "gameFull": print("!!", j) print(j["white"]["id"]) if j["white"]["id"] == "tuxbot9000": amIwhite = True #chessMove = m.getRandomMove(b.board, amIwhite) _s = time.time() chessMove = self.doMoveWrapper(b, designated_depth, time_per_move) self.used_time += (time.time() - _s) if chessMove is None: print("end of game") exit(0) print("First move: ", chessMove) b.push(chessMove) _r = requests.post("https://lichess.org/api/bot/game/{}/move/{}".format(self.id, chessMove), headers=header) print(_r.json()) if j["type"] == "gameState": moves = j["moves"] evenlist = len(moves.split(" ")) % 2 == 0 if (not evenlist and not amIwhite) or (evenlist and amIwhite): lastmove = moves.split(" ")[-1] # decode b.push(chess.Move.from_uci(lastmove)) print("received: ", lastmove) # make own move #chessMove = m.getRandomMove(b.board, amIwhite) _s = time.time() chessMove = self.doMoveWrapper(b, designated_depth, time_per_move) self.used_time += (time.time() - _s) if chessMove is None: print("end of game") exit(0) # decode b.push(chessMove) print("sent: ", chessMove) # b.renderBoard() _r = requests.post("https://lichess.org/api/bot/game/{}/move/{}".format(self.id, chessMove), headers=header) print(_r.json()) blocked = False active_games = {} if __name__ == "__main__": r = requests.get("https://lichess.org/api/stream/event", headers=header, stream=True) for line in r.iter_lines(): decoded_line = line.decode('utf-8') if(decoded_line != ''): j = json.loads(decoded_line) print(j["type"], decoded_line) if j["type"] == "challenge": _id = j["challenge"]["id"] if blocked: __r = requests.post(f"https://lichess.org/api/challenge/{_id}/decline", headers=header, data= '{ "reason" : "I am busy"}') try: play_time = j["challenge"]["timeControl"]["limit"] except: play_time = 30 * 60 try: increment = j["challenge"]["timeControl"]["increment"] except: increment = 0 t = threading.Thread(target=Game, args=(_id, play_time, increment)) t.start() <file_sep>/board2.py from PIL import Image, ImageDraw, ImageFont class Board2: def __init__(self): self.board = ['' for i in range(144)] self.castle_rights_long_black = True self.castle_rights_short_black = True self.castle_rights_long_white = True self.castle_rights_short_white = True # init white self.board[26] = 'r' self.board[27] = 'n' self.board[28] = 'b' self.board[29] = 'q' self.board[30] = 'k' self.board[31] = 'b' self.board[32] = 'n' self.board[33] = 'r' for i in range(38, 46): self.board[i] = 'p' # init black self.board[110] = 'R' self.board[111] = 'N' self.board[112] = 'B' self.board[113] = 'Q' self.board[114] = 'K' self.board[115] = 'B' self.board[116] = 'N' self.board[117] = 'R' for i in range(98, 106): self.board[i] = 'P' self.cols = ["a", "b", "c", "d", "e", "f", "g", "h"] def copy(self): new_b = Board2() new_b.board = self.board.copy() return new_b def do_move(self, move): _p = self.board[move[0]] self.board[move[0]] = '' self.board[move[1]] = _p if _p == 'k': self.castle_rights_long_white = False self.castle_rights_short_white = False elif _p == 'K': self.castle_rights_long_black = False self.castle_rights_short_black = False def positionToChessCoordinates(self, position): x, y = self.positionToCoordinages(position) return "{}{}".format(self.cols[x],y+1) def ChessCoordinatesToPosition(self, f): x = f[0] y = int(f[1]) x2 = int(self.cols.index(x)) print(x2, y) return (y - 1) * 8 + (x2 - 1) + 1 def positionToCoordinages(self, position): return position % 8, position // 8 <file_sep>/main.py import chess import chessutil import movegen import cProfile board = chess.Board() print(board) c = chessutil.ChessUtils() mg = movegen.MovementGenerator() #board.set_fen("rn1qkb1r/ppp1pppp/8/3p1b1n/3P4/2N2PB1/PPP1P1PP/R2QKBNR b KQkq - 2 5") #board.set_fen("r5rk/5p1p/5R2/4B3/8/8/7P/7K w") # mate in 3 # # board.set_fen("8/8/8/qn6/kn6/1n6/1KP5/8 w - -") # mate in 1 #board.set_fen("k1K5/1q6/2P3qq/q7/8/8/8/8 w - -") # mate in 3 #board.set_fen("2k3q1/7P/2K5/8/5q1q/8/8/5q2 w - -") # mate in 10 board.set_fen("r2r1n2/pp2bk2/2p1p2p/3q4/3PN1QP/2P3R1/P4PP1/5RK1 w - - 0 1") # mate in 4 #board.set_fen("8/6Q1/3pp3/3k1p2/B4b2/2P2P2/PPK2P1P/8 w - - 3 29") # heab mate in 1 # mistake by gen 2 #board.set_fen("rnb1kb1r/pppqpp1p/5np1/8/3P4/2N1BQ2/PPP3PP/2KR1BNR b kq - 3 7") #board.set_fen("rn2kb1r/pp2p2p/2p1pnp1/q7/3P4/2N1BQ1P/PPP3P1/2KR2NR b kq - 1 10") val = mg.min_max_eval_pychess_gen1(board) print("gen 1", val) val = mg.min_max_eval_pychess_gen2(board) print("gen 2", val) ## DEBUG ''' __b = board.copy() __b.push_san("Ra6") __b.push_san("f6") __b.push_san("Bxf6") __b.push_san("Rg7") print("Hash ",c.get_board_hash_pychess(__b)) ''' ## EO DEBUG #pr = cProfile.Profile() #pr.enable() pr = cProfile.Profile() #pr.enable() themove = mg.get_next_move_tuxfish(board, 10, 50000) #pr.disable() # after your program ends #pr.print_stats(sort="calls") #board.push_san("cxb7+") #themove = mg.get_next_move_tuxfish(board, 6, 10000) #themove = mg.get_next_move_alpha_beta_static_2(board, 6, 100) #pr.disable() # after your program ends #pr.print_stats(sort="calls") #mg.get_next_move_pv_search_board1(board, False, 4) <file_sep>/board.py class Board: def __init__(self): self.board = ['' for i in range(64)] self.castle_rights_long_black = True self.castle_rights_short_black = True self.castle_rights_long_white = True self.castle_rights_short_white = True # init white self.board[0] = 'r' self.board[1] = 'n' self.board[2] = 'b' self.board[3] = 'q' self.board[4] = 'k' self.board[5] = 'b' self.board[6] = 'n' self.board[7] = 'r' for i in range(8, 16): self.board[i] = 'p' # init black self.board[56] = 'R' self.board[57] = 'N' self.board[58] = 'B' self.board[59] = 'Q' self.board[60] = 'K' self.board[61] = 'B' self.board[62] = 'N' self.board[63] = 'R' for i in range(48, 56): self.board[i] = 'P' self.cols = ["a", "b", "c", "d", "e", "f", "g", "h"] def copy(self): new_b = Board() new_b.board = self.board.copy() return new_b def do_move(self, move): _p = self.board[move[0]] self.board[move[0]] = '' self.board[move[1]] = _p if _p == 'k': self.castle_rights_long_white = False self.castle_rights_short_white = False elif _p == 'K': self.castle_rights_long_black = False self.castle_rights_short_black = False <file_sep>/bot.py import requests import json from board import Board from chessutil import ChessUtils import threading import random from movegen import MovementGenerator b = Board() c = ChessUtils() m = MovementGenerator() token = "T<PASSWORD>" header = {"Authorization":"Bearer {}".format(token)} #doMove = m.get_next_move_alpha_beta doMove = m.get_next_move_pv_search_board1 designated_depth = 3 def playGame(id): #def playGame(a,b,c,d,e,f,g,h): #print(a,b,c,d,e,f,g,h) requests.post("https://lichess.org/api/challenge/{}/accept".format(id), headers=header) r = requests.get("https://lichess.org/api/bot/game/stream/{}".format(id), headers=header, stream=True) # https://lichess.org/api/bot/game/stream/{gameId} b = Board() c = ChessUtils() amIwhite = False for line in r.iter_lines(): decoded_line = line.decode('utf-8') if (decoded_line != ''): j = json.loads(decoded_line) print("XX ", j) if j["type"] == "gameFull": print("!!", j) print(j["white"]["id"]) if j["white"]["id"] == "tuxbot9000": amIwhite = True #chessMove = m.getRandomMove(b.board, amIwhite) chessMove = doMove(b, amIwhite, designated_depth) if chessMove is None: print("end of game") exit(0) print("First move: ", chessMove) # decode fr = b.ChessCoordinatesToPosition(chessMove[0:2]) to = b.ChessCoordinatesToPosition(chessMove[2:4]) print("First Move Position ", fr, to) piece = b.board[fr] b.board[fr] = '' b.board[to] = piece _r = requests.post("https://lichess.org/api/bot/game/{}/move/{}".format(id, chessMove), headers=header) print(_r.json()) if j["type"] == "gameState": moves = j["moves"] evenlist = len(moves.split(" ")) % 2 == 0 if (not evenlist and not amIwhite) or (evenlist and amIwhite): lastmove = moves.split(" ")[-1] # decode fr = b.ChessCoordinatesToPosition(lastmove[0:2]) to = b.ChessCoordinatesToPosition(lastmove[2:4]) piece = b.board[fr] b.board[fr] = '' b.board[to] = piece print("received: ", lastmove) # make own move #chessMove = m.getRandomMove(b.board, amIwhite) chessMove = doMove(b, amIwhite, designated_depth) if chessMove is None: print("end of game") exit(0) # decode fr = b.ChessCoordinatesToPosition(chessMove[0:2]) to = b.ChessCoordinatesToPosition(chessMove[2:4]) piece = b.board[fr] b.board[fr] = '' b.board[to] = piece print("sent: ", chessMove) # b.renderBoard() _r = requests.post("https://lichess.org/api/bot/game/{}/move/{}".format(id, chessMove), headers=header) print(_r.json()) if __name__ == "__main__": r = requests.get("https://lichess.org/api/stream/event", headers=header, stream=True) for line in r.iter_lines(): decoded_line = line.decode('utf-8') if(decoded_line != ''): j = json.loads(decoded_line) print(j["type"], decoded_line) if j["type"] == "challenge": _id = j["challenge"]["id"] t = threading.Thread(target=playGame, args=(_id,)) t.start() <file_sep>/RandomMoves.py class RandomMoves: self<file_sep>/parallel_test.py import ray @ray.remote def rec(x): print(x) return -x <file_sep>/chessutil.py import random from board2 import Board2 class Piece_Square_Tables: mirror_table = [ 56,57,58,59,60,61,62,63, 48,49,50,51,52,53,54,55, 40,41,42,43,44,45,46,47, 32,33,34,35,36,37,38,39, 24,25,26,27,28,29,30,31, 16,17,18,19,20,21,22,23, 8,9,10,11,12,13,14,15, 0,1,2,3,4,5,6,7 ] pawnEvalWhite = [ 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 0, -10, -10, 0, 10, 10, 5, 0, 0, 5, 5, 0, 0, 5, 0, 0, 10, 20, 20, 10, 0, 0, 5, 5, 5, 10, 10, 5, 5, 5, 10, 10, 10, 20, 20, 10, 10, 10, 20, 20, 20, 30, 30, 20, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0 ]; knightEval =[ 0, -10, 0, 0, 0, 0, -10, 0, 0, 0, 0, 5, 5, 0, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0, 0, 0, 10, 20, 20, 10, 5, 0, 5, 10, 15, 20, 20, 15, 10, 5, 5, 10, 10, 20, 20, 10, 10, 5, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; bishopEvalWhite = [ 0, 0, -10, 0, 0, -10, 0, 0, 0, 0, 0, 10, 10, 0, 0, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 10, 15, 20, 20, 15, 10, 0, 0, 10, 15, 20, 20, 15, 10, 0, 0, 0, 10, 15, 15, 10, 0, 0, 0, 0, 0, 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; rookEvalWhite = [ 00, 0, 5, 10, 10, 5, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 0, 0, 5, 10, 10, 5, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25, 0, 0, 5, 10, 10, 5, 0, 0 ]; kingEvalWhite_O = [ 0, 5, 5, -10, -10, 0, 10, 5, -30, -30, -30, -30, -30, -30, -30, -30, -50, -50, -50, -50, -50, -50, -50, -50, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70 ]; kingEvalWhite_E = [ -50, -10, 0, 0, 0, 0, -10, -50, -10, 0, 10, 10, 10, 10, 0, -10, 0, 10, 15, 15, 15, 15, 10, 0, 0, 10, 15, 20, 20, 15, 10, 0, 0, 10, 15, 20, 20, 15, 10, 0, 0, 10, 15, 15, 15, 15, 10, 0, -10, 0, 10, 10, 10, 10, 0, -10, -50, -10, 0, 0, 0, 0, -10, -50 ] class ChessUtils: table = None hash_lookup_pieces = { "p" : 1, "P" : 2, "r" : 3, "R" : 4, "b" : 5, "B" : 6, "n" : 7, "N" : 8, "k" : 9, "K" : 10, "q" : 11, "Q" : 12 } cols = ["a", "b", "c", "d", "e", "f", "g", "h"] @staticmethod def positionToChessCoordinates(position): x, y = ChessUtils.positionToCoordinages(position) return "{}{}".format(ChessUtils.cols[x],y+1) @staticmethod def ChessCoordinatesToPosition(f): x = f[0] y = int(f[1]) x2 = int(ChessUtils.cols.index(x)) print(x2, y) return (y - 1) * 8 + (x2 - 1) + 1 @staticmethod def positionToCoordinages(position): return position % 8, position // 8 def random_bitstring(self): return random.randint(0, 2 ** 64 - 1) def init_hash(self): global table table = [[] for _ in range(64)] for i in range(64): table[i] = [[] for _ in range(12)] for j in range(12): table[i][j] = self.random_bitstring() def get_board_hash_pychess(self, board): h = 0 for ke, va in board.piece_map().items(): j = self.hash_lookup_pieces[str(va)] - 1 h = h ^ table[ke][j] return h def get_board_hash(self, board): ''' constant indices white_pawn := 1 white_rook := 2 # etc. black_king := 12 ''' h = 0 for i in range(64): if board[i] != '': j = self.hash_lookup_pieces[board[i]] -1 h = h ^ table[i][j] return h def get_board_hash_board2(self, board): ''' constant indices white_pawn := 1 white_rook := 2 # etc. black_king := 12 ''' h = 0 for i in range(64): if board.piece[i] != Board2.EMPTY: if board.color[i] == Board2.DARK: j = board.piece[i] * 2 else: j = board.piece[i] * 2 +1 h = h ^ table[i][j] return h def __init__(self): pass self.table = None self.init_hash() self.moves = {} self.moves["NORTH"] = 8 self.moves["SOUTH"] = -8 self.moves["EAST"] = 1 self.moves["WEST"] = -1 self.moves["SOUTH EAST"] = -7 self.moves["SOUTH WEST"] = -9 self.moves["NORTH EAST"] = 9 self.moves["NORTH WEST"] = 7 self.moves["NORTH NORTH WEST"] = 15 self.moves["NORTH NORTH EAST"] = 17 self.moves["EAST EAST NORTH"] = 10 self.moves["EAST EAST SOUTH"] = -6 self.moves["SOUTH SOUTH EAST"] = -15 self.moves["SOUTH SOUTH WEST"] = -17 self.moves["WEST WEST SOUTH"] = -10 self.moves["WEST WEST NORTH"] = 6 def crossingborders(self, position, direction, piece="X"): checkpos = position - self.moves[direction] if piece.lower() == "n": if (checkpos - 1) % 8 == 0 and direction.find("WEST") == 0: return True if (checkpos + 2 ) % 8 == 0 and direction.find("EAST") == 0: return True #print("CC ", position, direction) if checkpos < 0: return True # check left border if checkpos % 8 == 0 and "WEST" in direction: return True if (checkpos + 1) % 8 == 0 and "EAST" in direction: return True return False def getPieceThreats(self, board, position): legalmoves = self.getPieceMoves(board, position) if board[position].lower() == "p": legalmoves = self.getPawnTakeMoves(board, position) moves = [] for move in legalmoves: if board[move] != '' and board[position].islower() != board[move].islower(): moves.append(move) return moves def getPawnTakeMoves(self, board, position): moves = [] filtermoves = [] #check for white if board[position].islower(): moves += self.getStraightMoves(board, position, "NORTH WEST", maxsteps=1) moves += self.getStraightMoves(board, position, "NORTH EAST", maxsteps=1) # check if there is enemy piece on it if yes its legal move for move in moves: if board[move] != '' and not board[move].islower(): filtermoves.append(move) else: moves += self.getStraightMoves(board, position, "SOUTH WEST", maxsteps=1) moves += self.getStraightMoves(board, position, "SOUTH EAST", maxsteps=1) # check if there is enemy piece on it if yes its legal move for move in moves: if board[move] != '' and board[move].islower(): filtermoves.append(move) return filtermoves def getStraightMoves(self, board, position, direction, maxsteps = 10000): moves = [] #print("call ", position, direction) count = 0 iter = position # conditions, # while not end of the board # and not hit any other piece abort = False while True: if count != 0: moves.append(iter) #print("c {} i {} d {}".format(count,iter,direction)) count += 1 iter += self.moves[direction] # if iter >= 64 or board[iter] != '': if iter >= 64 or iter < 0 or count > maxsteps or self.crossingborders(iter,direction, board[position]) or abort: #print("break 1") break # if there is a piece and my piece is a pawn, not way of crossing, IF its not a take move if board[iter] != '' and board[position].lower() == "p" and (direction == "NORTH" or direction == "SOUTH"): #print("pawnbreak") break; # if found piece is not own color, add legal move but abort after that, and no pawn if board[iter] != '' and board[iter].islower() != board[position].islower(): #print("break 2") abort = True maxsteps += 1 # if piece is own abort now if board[iter] != '' and board[iter].islower() == board[position].islower(): #print("break 3") break #print("return ",moves) return moves def isPlayerInCheck(self, board, iswhite): # get all threats of enemies and check if one is my king for i in range(64): if board[i] != '' and \ ((board[i].islower() and not iswhite) or (not board[i].islower() and iswhite)): # get all enemy moves moves = self.getPieceThreats(board, i) # if one of it is my king then check for move in moves: if ((board[move] == 'k' and iswhite) or (board[move] == 'K' and not iswhite)): return True return False def isPlayerInCheckMate(self, board, iswhite): # find my king kingpos = -1 for i in range(64): if (board[i] == "k" and iswhite) or (board[i]=="K" and not iswhite): kingpos = i break # get all legal Kings moves moves = self.getAllPieceMoves(board, kingpos) # filter moves moves = self.filterKingsMoves(board, moves, kingpos) if self.isPlayerInCheck(board,iswhite) and len(moves) == 0: return True return False def filterKingsMoves(self, board, moves, position): moves2 = [] iswhite = board[position].islower() # check if threatlist contains any move of the king if not take over for m in moves: #creat temp board by doing move and then do check test board_temp = board.copy() board_temp[position] = '' if iswhite: board_temp[m] = 'k' else: board_temp[m] = 'K' if not self.isPlayerInCheck(board_temp, iswhite): moves2.append(m) return moves2 def getAllPlayerMoves(self, board, iswhite): allmoves = [] for i in range(64): #print("Check for ", i) if (board[i] != '' and board[i].islower() and iswhite) or (board[i] != '' and not board[i].islower() and not iswhite): possible_moves = self.getAllPieceMoves(board, i) #print("Check for ", i, possible_moves) for targets in possible_moves: allmoves.append((i, targets)) filteredMoves = [] # if in check then only consider moves that bring you out of check if self.isPlayerInCheck(board, iswhite): #print("CHECK FILTER") # for each move create temp board and see if in check, if not consider it for move in allmoves: f,t = move temp_board = board.copy() piece = temp_board[f] temp_board[f] = '' temp_board[t] = piece if not self.isPlayerInCheck(temp_board, iswhite): filteredMoves.append(move) allmoves = filteredMoves else: filteredMoves = allmoves return allmoves def getAllPieceMoves(self, board, position): moves = self.getPieceMoves(board, position) if board[position].lower() == 'k': moves = self.filterKingsMoves(board, moves, position) return moves; def getPieceMoves(self, board, position): # only test implement bishios moves = [] if board[position] == '': return moves if board[position] == 'b' or board[position] == "B": # check all diagonals moves += (self.getStraightMoves(board, position, "NORTH WEST")) moves += (self.getStraightMoves(board, position, "NORTH EAST")) moves += (self.getStraightMoves(board, position, "SOUTH WEST")) moves += (self.getStraightMoves(board, position, "SOUTH EAST")) elif board[position] == 'p': # if pawn is in base line, also allow two field leap if position >= 8 and position < 16: steps = 2 else: steps = 1 moves += (self.getStraightMoves(board, position, "NORTH", maxsteps=steps)) elif board[position] == 'P': moves += (self.getStraightMoves(board, position, "SOUTH", maxsteps=1)) elif board[position] == 'r' or board[position] == "R": # check all diagonals moves += (self.getStraightMoves(board, position, "NORTH")) moves += (self.getStraightMoves(board, position, "EAST")) moves += (self.getStraightMoves(board, position, "WEST")) moves += (self.getStraightMoves(board, position, "SOUTH")) elif board[position] == 'q' or board[position] == "Q": # check all diagonals moves += (self.getStraightMoves(board, position, "NORTH")) moves += (self.getStraightMoves(board, position, "EAST")) moves += (self.getStraightMoves(board, position, "WEST")) moves += (self.getStraightMoves(board, position, "SOUTH")) moves += (self.getStraightMoves(board, position, "NORTH WEST")) moves += (self.getStraightMoves(board, position, "NORTH EAST")) moves += (self.getStraightMoves(board, position, "SOUTH WEST")) moves += (self.getStraightMoves(board, position, "SOUTH EAST")) elif board[position] == 'k' or board[position] == "K": # check all diagonals moves += (self.getStraightMoves(board, position, "NORTH", maxsteps=1)) moves += (self.getStraightMoves(board, position, "EAST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "WEST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "SOUTH", maxsteps=1)) moves += (self.getStraightMoves(board, position, "NORTH WEST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "NORTH EAST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "SOUTH WEST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "SOUTH EAST", maxsteps=1)) elif board[position] == 'n' or board[position] == "N": moves += (self.getStraightMoves(board, position, "NORTH NORTH WEST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "NORTH NORTH EAST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "EAST EAST NORTH", maxsteps=1)) moves += (self.getStraightMoves(board, position, "EAST EAST SOUTH", maxsteps=1)) moves += (self.getStraightMoves(board, position, "SOUTH SOUTH EAST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "SOUTH SOUTH WEST", maxsteps=1)) moves += (self.getStraightMoves(board, position, "WEST WEST SOUTH", maxsteps=1)) moves += (self.getStraightMoves(board, position, "WEST WEST NORTH", maxsteps=1)) if board[position].lower() == 'p': moves += self.getPawnTakeMoves(board,position) return moves <file_sep>/movegen.py from board import Board from board2 import Board2 from chessutil import ChessUtils, Piece_Square_Tables import random import time import chess import chess.polyglot import threading import random class HashEntry: NONE = 0 EXACT = 1 BETA = 2 ALPHA = 3 def __init__(self): self.key = "" self.move = None self.score = 0 self.depth = 0 self.flag = HashEntry.NONE class MovementGenerator: cu = ChessUtils() hashes = {} INFINITY = 137000000 INITIALIZED = False pv_table = {} hash_table = {} USE_QUIESENCE = True def clear_search_params(self): self.nodes = 0 #self.pv_table = {} self.killers = {0: {}, 1: {}} for i in range(0, 400): self.killers[0][i] = None self.killers[1][i] = None self.search_history = {} for i in range(0, 64): self.search_history[i] = {} for ii in range(0, 64): self.search_history[i][ii] = 0 def __init__(self): self.cu = ChessUtils() self.saved_moved = "" self.results = [] self.clear_search_params() self.Mvv_Lva_Victim_scores = { "p" : 100, "n" : 200, "b" : 300, "r" : 400, "q" : 500, "k" : 600 } # init mvv lva self.Mvv_Lva_Scores = {} for attacker in self.Mvv_Lva_Victim_scores.keys(): self.Mvv_Lva_Scores[attacker] = {} for victim in self.Mvv_Lva_Victim_scores.keys(): self.Mvv_Lva_Scores[attacker][victim] = int(self.Mvv_Lva_Victim_scores[victim] + 6 - (self.Mvv_Lva_Victim_scores[attacker] / 100)) + 1000000 def get_opening_move(self, board): max_weight = 0 max_move = None found_moves = {} with chess.polyglot.open_reader("Performance.bin") as reader: for entry in reader.find_all(board): if not entry.weight in found_moves: found_moves[entry.weight] = [] found_moves[entry.weight].append(entry.move) if entry.weight > max_weight: max_weight = entry.weight max_move = entry.move # shuffle out of best moves if max_move is None: return None best_moves = found_moves[max_weight] random.shuffle(best_moves) return best_moves[0] @staticmethod def min_max_eval_pychess(board): return MovementGenerator.min_max_eval_pychess_gen1(board) @staticmethod def min_max_eval_pychess_gen2(board): if board.is_checkmate(): #print(board.move_stack) return -1 * (MovementGenerator.INFINITY - board.ply()) sum = 0 val = {"k": 200, "q": 9, "r": 5, "b": 3, "n": 3, "p": 1} for pos, _piece in board.piece_map().items(): piece = str(_piece) sum += val[piece.lower()] * (-1 if piece.islower() else 1) if piece == "p": sum -= Piece_Square_Tables.pawnEvalWhite[Piece_Square_Tables.mirror_table[pos]] / 100. elif piece == "n": sum -= Piece_Square_Tables.knightEval[Piece_Square_Tables.mirror_table[pos]] / 100 elif piece == "b": sum -= Piece_Square_Tables.bishopEvalWhite[Piece_Square_Tables.mirror_table[pos]] / 100. elif piece == "k": if board.ply() < 30: sum -= Piece_Square_Tables.kingEvalWhite_O[Piece_Square_Tables.mirror_table[pos]] / 100. else: sum -= Piece_Square_Tables.kingEvalWhite_E[Piece_Square_Tables.mirror_table[pos]] / 100. elif piece == "r": sum -= Piece_Square_Tables.rookEvalWhite[Piece_Square_Tables.mirror_table[pos]] / 100. #white elif piece == "P": sum += Piece_Square_Tables.pawnEvalWhite[pos] / 100. elif piece == "N": sum += Piece_Square_Tables.knightEval[pos] / 100. elif piece == "B": sum += Piece_Square_Tables.bishopEvalWhite[pos] / 100. elif piece == "K": if board.ply() < 30: sum += Piece_Square_Tables.kingEvalWhite_O[pos] / 100. else: sum += Piece_Square_Tables.kingEvalWhite_E[pos] / 100. elif piece == "R": sum += Piece_Square_Tables.rookEvalWhite[pos] / 100. # add deviations of square maps # add mobility if board.turn == chess.WHITE: num_1 = board.legal_moves.count() board.push(chess.Move.null()) num_2 = board.legal_moves.count() board.pop() mobility = num_1 - num_2 else: num_2 = board.legal_moves.count() board.push(chess.Move.null()) num_1 = board.legal_moves.count() board.pop() mobility = num_1 - num_2 # if either side is in check, mobility is 0 if board.is_check(): mobility = 0 sum += 0.1 * mobility return sum * (-1 if board.turn == chess.BLACK else 1) @staticmethod def min_max_eval_pychess_gen1(board): #_tstart = time.time_ns() sum = 0 if board.is_checkmate(): #print(board.move_stack) return -1 * (MovementGenerator.INFINITY - board.ply()) val = {"k": 200, "q": 9, "r":5, "b": 3, "n":3, "p": 1} for pos, _piece in board.piece_map().items(): piece = str(_piece) sum += val[piece.lower()] * (-1 if piece.islower() else 1) #sum += int(Piece_Square_Tables.get_piece_value(piece, pos) /10 ) * (-1 if piece.islower() else 1) if board.turn == chess.WHITE: num_1 = board.legal_moves.count() board.push(chess.Move.null()) num_2 = board.legal_moves.count() board.pop() mobility = num_1 - num_2 else: num_2 = board.legal_moves.count() board.push(chess.Move.null()) num_1 = board.legal_moves.count() board.pop() mobility = num_1 - num_2 # if either side is in check, mobility is 0 if board.is_check(): mobility = 0 sum += 0.1 * mobility ''' #_tende = time.time_ns() #print(_tende - _tstart) # doubled pawns pieces = board.piece_map() white_pawns = [] black_pawns = [] for k, v in pieces.items(): if str(v) == 'P': white_pawns.append(k) elif str(v) == 'p': black_pawns.append(k) doubled_white = 0 doubled_black = 0 isolated_white = 0 isolated_black = 0 blocked_white = 0 blocked_black = 0 for pawn in white_pawns: # check for each pawn file_number = pawn % 8 # is pawn blocked ( for white +8 for black -8) if pawn + 8 < 64 and board.piece_at(pawn + 8) is not None: blocked_white += 1 has_left_neighbor = False has_right_neighbor = False if pawn % 8 == 0: has_left_neighbor = True if pawn % 8 == 7: has_right_neighbor = True # is it doubled, is another pawn on the file for other_pawn in white_pawns: if other_pawn != pawn and abs(pawn - other_pawn) % 8 == 0: doubled_white += 1 # isolation check left file ( if exists) other_file = other_pawn % 8 if file_number - other_file == 1: has_left_neighbor = True if file_number - other_file == -1: has_right_neighbor = True if not has_left_neighbor and not has_right_neighbor: isolated_white += 1 # check for black pawns for pawn in black_pawns: # check for each pawn file_number = pawn % 8 # is pawn blocked ( for white +8 for black -8) if pawn - 8 >= 0 and board.piece_at(pawn - 8) is not None: blocked_black += 1 has_left_neighbor = False has_right_neighbor = False if pawn % 8 == 0: has_left_neighbor = True if pawn % 8 == 7: has_right_neighbor = True # is it doubled, is another pawn on the file for other_pawn in black_pawns: if other_pawn != pawn and abs(pawn - other_pawn) % 8 == 0: doubled_black += 1 # isolation check left file ( if exists) other_file = other_pawn % 8 if file_number - other_file == 1: has_left_neighbor = True if file_number - other_file == -1: has_right_neighbor = True if not has_left_neighbor and not has_right_neighbor: isolated_black += 1 pawn_influence = ((doubled_white - doubled_black) + (isolated_white - isolated_black) + (blocked_white - blocked_black)) * 0.1 #print(pawn_influence) sum -= pawn_influence ''' # punish no castle right castle_factor = 0 return sum * (-1 if board.turn == chess.BLACK else 1) def store_pvline(self, position_hash, move, turn): MovementGenerator.pv_table[position_hash] = move def get_pvline(self, position_hash, turn): if position_hash not in MovementGenerator.pv_table: return None return MovementGenerator.pv_table[position_hash] def pick_next_move(self, move_dict): best_key = None best_value = -1 if len(move_dict.keys()) == 0: return None for k, v in move_dict.items(): if v > best_value: best_value = v best_key = k move_dict.remove(best_key) return best_key def quiescence(self, board, a, b, qdepth = 0): #if qdepth > 0: # print(qdepth) old_a = a best_move = None #h = self.cu.get_board_hash_pychess(board) h = board.fen() pv_move = self.get_pvline(h, board.turn) self.nodes += 1 #if board.can_claim_draw(): # return 0 #score = self.min_max_eval_pychess(board) if not board.is_check() else (-1 * (MovementGenerator.INFINITY - board.ply())) score = self.min_max_eval_pychess(board) if score >= b: return b # delta prun if score < a - 9: return a if score > a: a = score unscored_moves = board.legal_moves scored_moves = {} # score moves ## by capturing for move in unscored_moves: if pv_move is not None and move == pv_move: scored_moves[move] = 20000000 continue ## all non captures are at the end of the list if board.is_capture(move): ## all captures have to be scored and thus sorted attacker = board.piece_at(move.from_square).symbol().lower() try: victim = board.piece_at(move.to_square).symbol().lower() except: victim = 'p' scored_moves[move] = self.Mvv_Lva_Scores[attacker][victim] #elif board.is_check(): # scored_moves[move] = 0 ordered_move_list = sorted(scored_moves, key=scored_moves.get) ordered_move_list.reverse() for move in ordered_move_list: board.push(move) move_score = -1 * self.quiescence(board, -b, -a, qdepth + 1) board.pop() if move_score > a: if move_score >= b: return b a = move_score best_move = move if a != old_a: # debug # print(f"beat alpha on {depth} for move {str(move)} and score {move_score}") # self.pv_line[depth] = str(best_move) self.store_pvline(h, best_move, board.turn) #if board.is_check() and board.legal_moves.count() == 0: # return -1 * (MovementGenerator.INFINITY - board.ply()) return a def store_hash(self, pos, move, score, flag, depth): he = HashEntry() he.key = pos he.move = move he.score = score he.flag = flag he.depth = depth MovementGenerator.hash_table[pos] = he def get_hash(self, pos): if pos in MovementGenerator.hash_table: return MovementGenerator.hash_table[pos] return None def alpha_beta(self, board, depth, a, b, maxd, null_move): move_score = -MovementGenerator.INFINITY # check for null mive if null_move and not board.is_check() and board.ply() > 0 and depth >= 3: #and 1 == 2: board.push(chess.Move.null()) move_score = -1 * self.alpha_beta(board, depth - 3, -b, -b + 1, maxd, False) board.pop() if move_score >= b: return b best_score = -MovementGenerator.INFINITY move_score = -MovementGenerator.INFINITY old_a = a best_move = None # get hash of current position #h = self.cu.get_board_hash_pychess(board) h = board.fen() #pv_move = self.get_pvline(h, board.turn) depc hash_entry = self.get_hash(h) if hash_entry is not None: if hash_entry.depth >= depth: if hash_entry.flag == HashEntry.EXACT: return hash_entry.score elif hash_entry.flag == HashEntry.ALPHA and hash_entry.score <= a: return a elif hash_entry.flag == HashEntry.BETA and hash_entry.score >= b: return b self.nodes += 1 if board.legal_moves.count() == 0: return MovementGenerator.min_max_eval_pychess(board) if depth <= 0: if MovementGenerator.USE_QUIESENCE: return self.quiescence(board, a, b) else: return MovementGenerator.min_max_eval_pychess(board) #if board.can_claim_draw(): # return 0 unscored_moves = board.legal_moves scored_moves = {} # score moves ## by capturing for move in unscored_moves: ## all non captures are at the end of the list if not board.is_capture(move): ### check if non capture is killer move 1st order if self.killers[0][board.ply()] == move: scored_moves[move] = 900000 elif self.killers[0][board.ply()] == move: scored_moves[move] = 800000 else: scored_moves[move] = self.search_history[move.from_square][move.to_square] else: ## all captures have to be scored and thus sorted attacker = board.piece_at(move.from_square).symbol().lower() try: victim = board.piece_at(move.to_square).symbol().lower() except: victim = 'p' scored_moves[move] = self.Mvv_Lva_Scores[attacker][victim] ordered_move_list = sorted(scored_moves, key=scored_moves.get) ordered_move_list.reverse() legal = 0 for move in ordered_move_list: board.push(move) legal += 1 move_score = -1 * self.alpha_beta(board, depth-1, -b, -a, maxd, null_move) board.pop() if move_score > best_score: best_score = move_score best_move = move if move_score > a: if move_score >= b: if legal == 1: self.fhf += 1 self.fh += 1 # killer moves if not board.is_capture(move): self.killers[1][board.ply()] = self.killers[1][board.ply()] self.killers[0][board.ply()] = move # STORE HASH ENTRY pos, betaMove, beta, BETA, depth self.store_hash(board.fen(), best_move, b, HashEntry.BETA, depth) return b a = move_score best_move = move # killer moves if not board.is_capture(move): self.search_history[best_move.from_square][best_move.to_square] += depth if a != old_a: # debug # print(f"beat alpha on {depth} for move {str(move)} and score {move_score}") #self.pv_line[depth] = str(best_move) #self.store_pvline(h, best_move, board.turn) # STORE HASH pos, bestmove, bestscore, exact, depth self.store_hash(board.fen(), best_move, best_score, HashEntry.EXACT, depth) else: # STORE HASH pos, bestmove, alpha, ALPHA, depth self.store_hash(board.fen(), best_move, a, HashEntry.ALPHA, depth) return a def retrieve_pvline(self, board): pv_line = list() _b = board.copy() for _ in range(10000): #h = self.cu.get_board_hash_pychess(_b) h = _b.fen() hash_entry = self.get_hash(h) if hash_entry is not None and hash_entry.flag == HashEntry.EXACT: pv_line.append(hash_entry.move) _b.push(hash_entry.move) else: break return pv_line def get_pv_line_san(self, board, line): san_list = list() b = board.copy() for move in line: san_list.append(b.san(move)) b.push(move) return san_list def get_next_move_alpha_beta_iterative_2(self, board, depth, max_time): best_move = None #clear self.saved_moved = None self.clear_search_params() entry_time = time.time() for cd in range(1, depth): self.nodes = 0 self.fh = 0 self.fhf = 0 current_depth = cd + 1 _start = time.time() best_score = self.alpha_beta(board, current_depth, -MovementGenerator.INFINITY, MovementGenerator.INFINITY, current_depth, True) pv_moves = self.retrieve_pvline(board) if len(pv_moves) > 0: best_move = pv_moves[0] else: # make sure we run at least once more if cd == depth-1: # we are at last iteration and need to run once more print("extra run") best_sore = self.alpha_beta(board, cd+1, -MovementGenerator.INFINITY, MovementGenerator.INFINITY, cd+1, True) print(f"XTRA: Depth {cd+1} Nodes: {self.nodes} Move: {board.san(best_move)} Time: {time.time() - _start} Score: {best_score}") print(f"Depth {current_depth} Nodes: {self.nodes} Move: {board.san(best_move)} Time: {time.time() - _start} Score: {best_score}") print(f"Move Ordering {self.fhf /max(self.fh,1)}") print("PV LINE: ",self.get_pv_line_san(board,pv_moves)) if time.time() - entry_time > max_time: break if best_score >= MovementGenerator.INFINITY - 100: # found checkmate return best_move return best_move def get_next_move_tuxfish(self, board, depth, max_time): opening_move = self.get_opening_move(board) if opening_move is not None: return opening_move return self.get_next_move_alpha_beta_iterative_2(board, depth, max_time)
90936cb0a2b92c63d3a23986c5ca7fca64217e26
[ "Python" ]
9
Python
tuxmania87/chessbot-tuxbot
4cc44685902c42a6c7a29c70e2b361123f5577ea
1883f9269f3a2c905b65c57ed8e0bf3d9335a655
refs/heads/master
<file_sep>"use strict"; /** * writeText is responsible for inserting the messages into the html of the page * the local user, as well as 3 additional users each have unique colors * all subsequent users will have their text be displayed in a green font * @param {string} user this represents the user who sent the message * @param {string} message this represents the message sent to the room * @param {string} myName this represents the username of the local user * @param {Array.<string>} usersSeen represents all users who have sent messages within this room's lifetime */ function writeText(user, message, myName, usersSeen){ if(user == myName){ $(".text-output").append("<h3 class='myName'> "+ user + " : " + message + " </h3>"); } else { if(usersSeen.indexOf(user) == -1){ usersSeen.push(user) localStorage.setItem("user",usersSeen.push()); } $(".text-output").append("<h3 class='user-" + usersSeen.indexOf(user) + "'> "+ user + " : " + message + " </h3>"); } } /** * this is responsible for directing * all keyboard typing into the chat bar */ $(document).bind("keydown",function(){ $("#input").focus(); $(document).unbind("keydown"); }); /** * pressing the enter key will trigger an ajax request * which sends the contents of the chatbar (defined by the ID input) to the room */ $(document).keypress(function(e){ if (e.which == 13){ $.ajax({ type: "POST", url: "https://musicality.imrapid.io/chat", data: { "video": "blood", "message": document.getElementById("input").value, "user": localStorage.getItem("name") }, }); document.getElementById("input").value = ""; } }); /** * createIO takes two arguments, the name of the project on imrapid(musicality) * and the room name(blood, the name of the video) */ var room = createIO("musicality", "blood"); /** * The following portion of code listens for a "message" event after this, it inserts the * recieved message into the DOM with writeText. It will then scroll down to the newest message */ room.on("message", function(data) { writeText(data.user, data.message, localStorage.getItem("name") , JSON.parse(localStorage.getItem("users"))); var objDiv = document.getElementById("text"); objDiv.scrollTop = objDiv.scrollHeight; }); /** * the below segment of JS code is used for all the player logic, primarily taken from youtube's * iframe API website. */ var tag = document.createElement("player"); tag.src = "https://www.youtube.com/iframe_api"; var player; function onYouTubePlayerAPIReady() { player = new YT.Player("player", { height: "100%", width: "100%", videoId: "KMe_5O0mYj0", playerVars:{ "controls": 0, "showInfo": 0, "autoHide": 0, "start" : parseInt(localStorage.getItem("time")), "iv_load_policy": 3 }, events: { "onReady": onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } /** * this listens for load_event events, * upon recieving such an event, it responds by giving * the time elapsed in an ajax function * */ room.on("load_event", function(data) { if(data.time === 0){ $.ajax({ type: "POST", url: "https://musicality.imrapid.io/load", data: { "video": "blood", "time": moment().diff(moment(localStorage.getItem("start")), "seconds") }, }); } });
acf38a61a0bf8290f9632ad04d687e61b96aff36
[ "JavaScript" ]
1
JavaScript
sbepstein/musicality
296d3c7fa3c0ec9821e7f9c7251bebde1ab5b01e
ad9c52f9db5d4f34805591cab851e01f692e08ca
refs/heads/master
<file_sep>#include "masterwidget.h" #include "mainwidget.h" #include <QBasicTimer> #include <iostream> #include <string> MasterWidget::MasterWidget() { timer.start(1000, this); month = 0; std::cout << "Wouah on est au mois de " << getMonthStr() << std::endl; } void MasterWidget::timerEvent(QTimerEvent * event) { this->update(); } void MasterWidget::update() { month = (month + 1) % 12; std::cout << "Wouah on est au mois de " << getMonthStr() << std::endl; if (month % 3 == 0) { std::cout << "On change de saison" << std::endl; winterWidget->nextSeason(); fallWidget->nextSeason(); summerWidget->nextSeason(); springWidget->nextSeason(); } } std::string MasterWidget::getMonthStr() { switch (this->month) { case 0: return "Janvier"; case 1: return "Février"; case 2: return "Mars"; case 3: return "Avril"; case 4: return "Mai"; case 5: return "Juin"; case 6: return "Juillet"; case 7: return "Aout"; case 8: return "Septembre"; case 9: return "Octobre"; case 10: return "Novembre"; case 11: return "Décembre"; default: return std::to_string(month); } } <file_sep>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "geometryengine.h" #include <QVector2D> #include <QVector3D> #include <QImage> #include <math.h> struct VertexData { QVector3D position; QVector2D texCoord; }; //! [0] GeometryEngine::GeometryEngine() : indexBuf(QOpenGLBuffer::IndexBuffer) { initializeOpenGLFunctions(); // Generate 2 VBOs arrayBuf.create(); indexBuf.create(); // Initializes cube geometry and transfers it to VBOs initPlaneGeometry(); //initMapGeometry(); } GeometryEngine::~GeometryEngine() { arrayBuf.destroy(); indexBuf.destroy(); } //! [0] void GeometryEngine::initMapGeometry(){ QImage img = QImage(":/heightmap-3.png"); //load map } void GeometryEngine::drawMapGeometry(QOpenGLShaderProgram *program) { // Tell OpenGL which VBOs to use arrayBuf.bind(); indexBuf.bind(); // Offset for position quintptr offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int vertexLocation = program->attributeLocation("a_position"); program->enableAttributeArray(vertexLocation); program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, sizeof(VertexData)); // Offset for texture coordinate offset += sizeof(QVector3D); // Tell OpenGL programmable pipeline how to locate vertex texture coordinate data int texcoordLocation = program->attributeLocation("a_texcoord"); program->enableAttributeArray(texcoordLocation); program->setAttributeBuffer(texcoordLocation, GL_FLOAT, offset, 2, sizeof(VertexData)); // Draw cube geometry using indices from VBO 1 glDrawElements(GL_TRIANGLE_STRIP, 34, GL_UNSIGNED_SHORT, 0); } void GeometryEngine::initPlaneGeometry(){ QImage img = QImage(":/heightmap-3.png"); //load map int vertexCount = 16 * 16; int sqrtVertexCount = (int)sqrt(vertexCount); VertexData* vertices = new VertexData[vertexCount]; float size = 2.0f; float step = size / (sqrtVertexCount - 1) ; int x = 0; int y = 0; int index = 0; float maxY = 1.0f; float stepTexX = (1.0f / 3.0f) /(sqrtVertexCount - 1); float stepTexY = (1.0f / 2.0f) /(sqrtVertexCount - 1); for (float j = 0.0 - (size / 2.0); j <= 0.0 + (size/ 2.0); j += step) { x = 0; for (float i = 0.0 - (size / 2.0); i <= 0.0 + (size/ 2.0); i += step) { VertexData vertex; vertex.texCoord = QVector2D(0.6666+x * stepTexX, y * stepTexY); QRgb color = img.pixel(x * 1.0f / (sqrtVertexCount - 1) * 500, y * 1.0f / (sqrtVertexCount - 1) * 500); vertex.position = QVector3D(i, maxY * qGray(color) / 255, j); vertices[index++] = vertex; x++; } y++; } int indicesCount = pow(sqrtVertexCount-1, 2) * 2 * 3; index = 0; GLushort* indices = new GLushort[indicesCount]; for (int y = 0; y < sqrtVertexCount - 1; y++) { for (int x = 0; x < sqrtVertexCount - 1; x++) { // top left indices[index++] = x + y * sqrtVertexCount; // bottom left indices[index++] = x + (y+1) * sqrtVertexCount; // bottom right indices[index++] = (x+1) + (y+1) * sqrtVertexCount; // top left indices[index++] = x + y * sqrtVertexCount; // bottom right indices[index++] = (x+1) + (y+1) * sqrtVertexCount; // top right indices[index++] = (x+1) + y * sqrtVertexCount; } } //! [1] // Transfer vertex data to VBO 0 arrayBuf.bind(); arrayBuf.allocate(vertices, vertexCount * sizeof(VertexData)); delete[] vertices; // Transfer index data to VBO 1 indexBuf.bind(); indexBuf.allocate(indices, indicesCount * sizeof(GLushort)); delete[] indices; //! [1] } void GeometryEngine::drawPlaneGeometry(QOpenGLShaderProgram *program) { // Tell OpenGL which VBOs to use arrayBuf.bind(); indexBuf.bind(); // Offset for position quintptr offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int vertexLocation = program->attributeLocation("a_position"); program->enableAttributeArray(vertexLocation); program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, sizeof(VertexData)); // Offset for texture coordinate offset += sizeof(QVector3D); // Tell OpenGL programmable pipeline how to locate vertex texture coordinate data int texcoordLocation = program->attributeLocation("a_texcoord"); program->enableAttributeArray(texcoordLocation); program->setAttributeBuffer(texcoordLocation, GL_FLOAT, offset, 2, sizeof(VertexData)); // Draw cube geometry using indices from VBO 1 glDrawElements(GL_TRIANGLES, 1350, GL_UNSIGNED_SHORT, 0); } <file_sep>#ifndef MASTERWIDGET_H #define MASTERWIDGET_H #include "mainwidget.h" #include <QBasicTimer> #include <string> class MasterWidget : QWidget { public: MasterWidget(); MainWidget* fallWidget; MainWidget* summerWidget; MainWidget* winterWidget; MainWidget* springWidget; void update(); std::string getMonthStr(); void timerEvent(QTimerEvent *e) override; protected: QBasicTimer timer; int month; }; #endif // MASTERWIDGET_H <file_sep># HMIN317 - Moteur de jeux Création d'un moteur de jeux from scratch. ## [TP1 - Prise en main de Qt Creator, Git et OpenGL ES 2.0](https://github.com/clayettet/Moteur_jeux/tree/master/TP1) [Sujet](https://github.com/clayettet/Moteur_jeux/blob/master/TP1/2017_01_TP_OPENGL.pdf) Les réponses aux questions se trouvent dans le fichier [question.txt](https://github.com/clayettet/Moteur_jeux/blob/master/TP1/question.txt) ## [TP2 - Game loop et timers](https://github.com/clayettet/Moteur_jeux/tree/master/TP2) [Sujet](https://github.com/clayettet/Moteur_jeux/blob/master/TP2/2017_02_TP_TIMER.pdf) Les réponses aux questions se trouvent dans le fichier [question.txt](https://github.com/clayettet/Moteur_jeux/blob/master/TP2/question.txt) ![alt text](https://github.com/clayettet/Moteur_jeux/blob/master/TP2/result.png "Résultat") ## /!\ Répertoires actuellement en cours de build, version fonctionnelle très prochainement /!\
a96469e4e81c722ac55dd0e6763be455cd2a9168
[ "Markdown", "C++" ]
4
C++
clayettet/Moteur_jeux
3f9b0f3b7d3d7c248820e8bcdb0b5e85e0730c10
44ad093377369a76fc562bf6a0eb26a50e06d48f
refs/heads/master
<repo_name>doaa12/zipn<file_sep>/src/main/java/cn/bmwm/modules/shop/dao/impl/PreOrderDaoImpl.java package cn.bmwm.modules.shop.dao.impl; import org.springframework.stereotype.Repository; import cn.bmwm.modules.shop.dao.PreOrderDao; import cn.bmwm.modules.shop.entity.PreOrder; /** * Dao -- 预约订单 * @author zby * 2014-12-14 上午10:06:55 */ @Repository("preOrderDaoImpl") public class PreOrderDaoImpl extends BaseDaoImpl<PreOrder,Long> implements PreOrderDao { } <file_sep>/src/main/java/cn/bmwm/modules/shop/entity/ShopReview.java package cn.bmwm.modules.shop.entity; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * 店铺评论 * @author zby * 2014-8-31 上午9:46:03 */ @Entity @Table(name = "xx_shop_review") @SequenceGenerator(name = "sequenceGenerator", sequenceName = "xx_shop_review_sequence") public class ShopReview extends BaseEntity { private static final long serialVersionUID = -5591550896644930342L; /** * 评分 */ private Integer score; /** * 评论内容 */ private String content; /** * 是否显示 */ private Boolean isShow; /** * 用户IP */ private String ip; /** * 用户名 */ private String user; /** * 会员 */ private Member member; /** * 店铺 */ private Shop shop; public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Boolean getIsShow() { return isShow; } public void setIsShow(Boolean isShow) { this.isShow = isShow; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } /** * 会员 * @return */ @ManyToOne(fetch = FetchType.LAZY) public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } /** * 店铺 * @return */ @ManyToOne(fetch = FetchType.LAZY) public Shop getShop() { return shop; } public void setShop(Shop shop) { this.shop = shop; } } <file_sep>/src/main/java/cn/bmwm/modules/shop/controller/app/OrderController.java package cn.bmwm.modules.shop.controller.app; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import cn.bmwm.common.Constants; import cn.bmwm.common.Result; import cn.bmwm.modules.shop.controller.app.vo.CartItemVo; import cn.bmwm.modules.shop.controller.app.vo.PrepareOrderVo; import cn.bmwm.modules.shop.entity.Cart; import cn.bmwm.modules.shop.entity.CartItem; import cn.bmwm.modules.shop.entity.Member; import cn.bmwm.modules.shop.entity.Order; import cn.bmwm.modules.shop.entity.Product; import cn.bmwm.modules.shop.entity.Receiver; import cn.bmwm.modules.shop.entity.Shop; import cn.bmwm.modules.shop.service.CartService; import cn.bmwm.modules.shop.service.OrderService; import cn.bmwm.modules.shop.service.ReceiverService; import cn.bmwm.modules.sys.model.Setting; import cn.bmwm.modules.sys.utils.SettingUtils; /** * App -- 订单 * @author zby * 2014-11-20 下午4:02:48 */ @Controller @RequestMapping(value = "/app/order") public class OrderController { public static final Log log = LogFactory.getLog(OrderController.class); /** * 处理完成 */ public static final int SUCCESS = 1; /** * 购物车为空 */ public static final int ORDER_CART_EMPTY = 101; /** * 库存不足 */ public static final int ORDER_LOW_STOCK = 102; /** * 收货地址错误 */ public static final int ORDER_RECEIVE_ADDRESS_ERROR = 103; /** * 订单中包含多个店铺的商品 */ public static final int ORDER_MULTIPLE_SHOP = 104; /** * 收货地址不属于该用户 */ public static final int ORDER_RECEIVE_ERROR = 105; @Resource(name = "cartServiceImpl") private CartService cartService; @Resource(name = "receiverServiceImpl") private ReceiverService receiverService; @Resource(name = "orderServiceImpl") private OrderService orderService; /** * 准备订单 */ @RequestMapping(value = "/prepare", method = RequestMethod.POST) @ResponseBody public Result prepare(HttpSession session) { List<CartItemVo> cartItemList = new ArrayList<CartItemVo>(); Member member = (Member)session.getAttribute(Constants.USER_LOGIN_MARK); Shop shop = null; Cart cart = cartService.getAppCurrent(); if (cart == null || cart.isEmpty()) { return new Result(ORDER_CART_EMPTY, 1, "购物车为空!"); } Set<CartItem> selectedCartItems = cart.getSelectedCartItems(); if(selectedCartItems == null || selectedCartItems.size() == 0) { return new Result(ORDER_CART_EMPTY, 1, "请选择需要下单的商品!"); } for(CartItem item : selectedCartItems) { if(item.getIsLowStock()) { log.warn("商品库存不足!"); return new Result(ORDER_LOW_STOCK, 1, "商品库存不足!"); } Product product = item.getProduct(); Shop pshop = product.getShop(); if(shop == null) { shop = pshop; }else { if(!shop.equals(pshop)) { return new Result(ORDER_MULTIPLE_SHOP, 1, "购物车中包含多个店铺的商品!"); } } CartItemVo cartItem = new CartItemVo(); cartItem.setId(product.getId()); cartItem.setName(product.getName()); cartItem.setPrice(product.getPrice()); cartItem.setDiscountPrice(item.getSubtotal()); cartItem.setQuantity(item.getQuantity()); cartItem.setCartItemId(item.getId()); cartItem.setIsSelected(item.getIsSelected()); cartItem.setImageUrl(product.getImage()); cartItemList.add(cartItem); } Receiver receiver = receiverService.findDefault(member); Order order = orderService.build(cart, receiver, ""); Setting setting = SettingUtils.get(); PrepareOrderVo prepareOrderVo = new PrepareOrderVo(); prepareOrderVo.setShopName(shop.getName()); prepareOrderVo.setReceiverAddress(receiver == null ? "" : receiver.getAddress()); prepareOrderVo.setReceiverPhone(receiver == null ? "" : receiver.getPhone()); prepareOrderVo.setReceiverUserName(receiver == null ? "" : receiver.getConsignee()); prepareOrderVo.setTotalPrice(order.getTotalAmount()); prepareOrderVo.setFreight(order.getFreight()); prepareOrderVo.setPoints((long)(setting.getPointPercent() * cart.getPrice().doubleValue())); prepareOrderVo.setCartItemList(cartItemList); return new Result(SUCCESS, 1, "", prepareOrderVo); } /** * 创建订单 * @param receiverId * @param shippingMethodId * @param memo * @return */ @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public Result create(HttpSession session, Long receiverId, String memo) { Cart cart = cartService.getAppCurrent(); if (cart == null || cart.isEmpty()) { return new Result(ORDER_CART_EMPTY, 1, "购物车为空!"); } Set<CartItem> selectedCartItems = cart.getSelectedCartItems(); if(selectedCartItems == null || selectedCartItems.size() == 0) { return new Result(ORDER_CART_EMPTY, 1, "请选择需要下单的商品!"); } if (cart.getIsLowStock()) { return new Result(ORDER_LOW_STOCK, 1, "库存不足!"); } Receiver receiver = receiverService.find(receiverId); if (receiver == null) { return new Result(ORDER_RECEIVE_ADDRESS_ERROR, 1, "收货地址不存在!"); } Member member = (Member)session.getAttribute(Constants.USER_LOGIN_MARK); if(!member.equals(receiver.getMember())) { return new Result(ORDER_RECEIVE_ERROR, 1, "收货地址不属于该用户!"); } orderService.create(cart, receiver, memo); return new Result(SUCCESS, 1); } } <file_sep>/src/main/java/cn/bmwm/modules/shop/dao/CartItemDao.java /* * */ package cn.bmwm.modules.shop.dao; import cn.bmwm.modules.shop.entity.CartItem; /** * Dao - 购物车项 * * * @version 1.0 */ public interface CartItemDao extends BaseDao<CartItem, Long> { }<file_sep>/src/main/java/cn/bmwm/modules/shop/entity/PreOrder.java package cn.bmwm.modules.shop.entity; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * Entity -- 预约订单 * @author zby * 2014-12-13 下午9:55:04 */ @Entity @Table(name = "xx_preorder") @SequenceGenerator(name = "sequenceGenerator", sequenceName = "xx_preorder_sequence") public class PreOrder extends BaseEntity { private static final long serialVersionUID = -9178055836987289579L; /** * 订单状态 */ public enum PreOrderStatus { /** 未确认 */ unconfirmed, /** 已确认 */ confirmed, /** 已完成 */ completed, /** 已取消 */ cancelled } /** * 支付状态 */ public enum PaymentStatus { /** 未支付 */ unpaid, /** 已支付 */ paid, /** 已退款 */ refunded } /** 订单编号 */ private String sn; /** 订单状态 */ private PreOrderStatus preOrderStatus; /** 支付状态 */ private PaymentStatus paymentStatus; /** * 预约时间 */ private Date bookTime; /** * 人数 */ private Integer persons; /** * 联系人姓名 */ private String contactUserName; /** * 联系人电话 */ private String contactPhone; /** * 商品总金额(不包含运费,只包含所有商品的价格) */ private BigDecimal totalAmount; /** 已付金额 */ private BigDecimal amountPaid; /** 赠送积分 */ private Long point; /** 附言 */ private String memo; /** 促销 */ private String promotion; /** 锁定到期时间 */ private Date lockExpire; /** 到期时间 */ private Date expire; /** 是否已分配库存 */ private Boolean isAllocatedStock; /** 支付方式名称 */ private String paymentMethodName; /** 会员 */ private Member member; /** * 店铺 */ private Shop shop; /** 预约订单项 */ private List<PreOrderItem> preOrderItems = new ArrayList<PreOrderItem>(); /** 订单日志 */ private Set<PreOrderLog> preOrderLogs = new HashSet<PreOrderLog>(); /** 收款单 */ private Set<Payment> payments = new HashSet<Payment>(); /** 退款单 */ private Set<Refunds> refunds = new HashSet<Refunds>(); /** * 获取订单编号 * * @return 订单编号 */ @Column(nullable = false, updatable = false, unique = true, length = 100) public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } /** * 获取预约订单状态 * @return */ @Column(nullable = false) public PreOrderStatus getPreOrderStatus() { return preOrderStatus; } public void setPreOrderStatus(PreOrderStatus preOrderStatus) { this.preOrderStatus = preOrderStatus; } /** * 获取预约订单支付状态 * @return */ @Column(nullable = false) public PaymentStatus getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(PaymentStatus paymentStatus) { this.paymentStatus = paymentStatus; } /** * 获取预约时间 * @return */ @Column(nullable = false) public Date getBookTime() { return bookTime; } public void setBookTime(Date bookTime) { this.bookTime = bookTime; } /** * 获取预约人数 * @return */ @Column(nullable = false) public Integer getPersons() { return persons; } public void setPersons(Integer persons) { this.persons = persons; } /** * 获取预约的联系人姓名 * @return */ @Column(nullable = false) public String getContactUserName() { return contactUserName; } public void setContactUserName(String contactUserName) { this.contactUserName = contactUserName; } /** * 获取联系人手机号码 * @return */ @Column(nullable = false) public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } /** * 获取支付总金额 * @return */ @Column(nullable = false) public BigDecimal getTotalAmount() { return totalAmount; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } /** * 获取已经支付总金额 * @return */ @Column(nullable = false) public BigDecimal getAmountPaid() { return amountPaid; } public void setAmountPaid(BigDecimal amountPaid) { this.amountPaid = amountPaid; } /** * 获取送给用户的积分 * @return */ @Column(nullable = false) public Long getPoint() { return point; } public void setPoint(Long point) { this.point = point; } /** * 获取用户给商家的留言 * @return */ public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } /** * 获取促销名称 * @return */ public String getPromotion() { return promotion; } public void setPromotion(String promotion) { this.promotion = promotion; } /** * 获取锁定到期时间 * @return */ public Date getLockExpire() { return lockExpire; } public void setLockExpire(Date lockExpire) { this.lockExpire = lockExpire; } /** * 获取订单过期时间 * @return */ @Column(nullable = false) public Date getExpire() { return expire; } public void setExpire(Date expire) { this.expire = expire; } /** * 获取是否分配库存 * @return */ @Column(nullable = false) public Boolean getIsAllocatedStock() { return isAllocatedStock; } public void setIsAllocatedStock(Boolean isAllocatedStock) { this.isAllocatedStock = isAllocatedStock; } /** * 获取支付方式名称 * @return */ public String getPaymentMethodName() { return paymentMethodName; } public void setPaymentMethodName(String paymentMethodName) { this.paymentMethodName = paymentMethodName; } /** * 获取用户 * @return */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(nullable = false) public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } /** * 获取店铺 * @return */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(nullable = false) public Shop getShop() { return shop; } public void setShop(Shop shop) { this.shop = shop; } /** * 获取预约单项 * @return */ @OneToMany(mappedBy = "preOrder", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @OrderBy("isGift asc") public List<PreOrderItem> getPreOrderItems() { return preOrderItems; } public void setPreOrderItems(List<PreOrderItem> preOrderItems) { this.preOrderItems = preOrderItems; } /** * 获取订单日志 * @return */ @OneToMany(mappedBy = "preOrder", fetch = FetchType.LAZY) public Set<PreOrderLog> getPreOrderLogs() { return preOrderLogs; } public void setPreOrderLogs(Set<PreOrderLog> preOrderLogs) { this.preOrderLogs = preOrderLogs; } /** * 获取支付单 * @return */ @OneToMany(mappedBy = "preOrder", fetch = FetchType.LAZY) public Set<Payment> getPayments() { return payments; } public void setPayments(Set<Payment> payments) { this.payments = payments; } /** * 获取退款单 * @return */ @OneToMany(mappedBy = "preOrder", fetch = FetchType.LAZY) public Set<Refunds> getRefunds() { return refunds; } public void setRefunds(Set<Refunds> refunds) { this.refunds = refunds; } } <file_sep>/src/main/java/cn/bmwm/modules/shop/dao/impl/OrderItemDaoImpl.java /* * */ package cn.bmwm.modules.shop.dao.impl; import org.springframework.stereotype.Repository; import cn.bmwm.modules.shop.dao.OrderItemDao; import cn.bmwm.modules.shop.entity.OrderItem; /** * Dao - 订单项 * * * @version 1.0 */ @Repository("orderItemDaoImpl") public class OrderItemDaoImpl extends BaseDaoImpl<OrderItem, Long> implements OrderItemDao { }<file_sep>/src/main/java/cn/bmwm/modules/sys/listener/InitListener.java package cn.bmwm.modules.sys.listener; import java.io.File; import javax.annotation.Resource; import javax.servlet.ServletContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import org.springframework.web.context.ServletContextAware; import cn.bmwm.modules.shop.service.CacheService; import cn.bmwm.modules.shop.service.SearchService; /** * Listener - 初始化 * * @version 1.0 */ @Component("initListener") public class InitListener implements ServletContextAware, ApplicationListener<ContextRefreshedEvent> { /** 安装初始化配置文件 */ private static final String INSTALL_INIT_CONFIG_FILE_PATH = "/install_init.conf"; /** servletContext */ private ServletContext servletContext; //@Resource(name = "staticServiceImpl") //private StaticService staticService; @Resource(name = "cacheServiceImpl") private CacheService cacheService; @Resource(name = "searchServiceImpl") private SearchService searchService; public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { if (servletContext != null && contextRefreshedEvent.getApplicationContext().getParent() == null) { File installInitConfigFile = new File(servletContext.getRealPath(INSTALL_INIT_CONFIG_FILE_PATH)); if (installInitConfigFile.exists()) { cacheService.clear(); //staticService.buildAll(); searchService.purge(); searchService.index(); installInitConfigFile.delete(); } else { //staticService.buildIndex(); //staticService.buildOther(); } } } }<file_sep>/src/main/java/cn/bmwm/modules/shop/controller/app/UserController.java /** * */ package cn.bmwm.modules.shop.controller.app; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import cn.bmwm.common.Constants; import cn.bmwm.common.Result; import cn.bmwm.modules.shop.entity.Member; import cn.bmwm.modules.shop.entity.Member.Gender; import cn.bmwm.modules.shop.service.MemberService; import cn.bmwm.modules.shop.service.RSAService; /** * App - 用户信息 * @author zhoupuyue * @date 2014-11-3 */ @Controller @RequestMapping(value = "/app/user") public class UserController { @Resource(name = "memberServiceImpl") private MemberService memberService; @Resource(name = "rsaServiceImpl") private RSAService rsaService; /** * 修改密码 * @return */ @RequestMapping(value = "/change_pasword", method = RequestMethod.POST) @ResponseBody public Result changePassword(HttpSession session, String oldpassword, String newpassword) { if(StringUtils.isBlank(oldpassword)) { return new Result(Constants.USER_PASSWORD_BLANK, 1, "旧密码为空!"); } if(StringUtils.isBlank(newpassword)) { return new Result(Constants.USER_PASSWORD_BLANK, 1, "新密码为空!"); } Member member = (Member)session.getAttribute(Constants.USER_LOGIN_MARK); String newPassword = rsaService.decrypt(newpassword); String oldPassword = rsaService.decrypt(oldpassword); if (!DigestUtils.md5Hex(oldPassword).equals(member.getPassword())) { return new Result(Constants.USER_PASSWORD_ERROR, 1, "旧密码错误!"); } member.setPassword(<PASSWORD>Utils.md5Hex(<PASSWORD>)); memberService.update(member); return new Result(Constants.SUCCESS, 1); } /** * 获取用户信息 * @return */ @RequestMapping(value = "/get_userinfo", method = RequestMethod.POST) @ResponseBody public Result getUserInfo(HttpSession session) { Member member = (Member)session.getAttribute(Constants.USER_LOGIN_MARK); Result result = new Result(Constants.SUCCESS, 1); result.put("address", member.getAddress()); result.put("username", member.getUsername()); result.put("sex", member.getGender() == Gender.male ? 1 : 0); result.put("description", member.getDescription()); return result; } /** * 修改用户信息 * @param address * @param sex * @param description * @return */ @RequestMapping(value = "/modify_userinfo", method = RequestMethod.POST) @ResponseBody public Result modifyUserInfo(HttpSession session, String address, String description, Integer sex) { Member member = (Member)session.getAttribute(Constants.USER_LOGIN_MARK); if(sex != null) { member.setGender(sex == 1 ? Gender.male : Gender.female); } member.setAddress(address); member.setDescription(description); memberService.update(member); return new Result(Constants.SUCCESS, 1); } /** * 重置密码 * @param request * @return */ @RequestMapping(value = "/reset_password", method = RequestMethod.POST) @ResponseBody public Result resetPassword(HttpSession session, String phone, String code, String enpassword) { if(StringUtils.isBlank(code)) { return new Result(Constants.USER_CODE_EMPTY, 1, "验证码为空!"); } if(StringUtils.isBlank(phone)) { return new Result(Constants.USER_USERNAME_BLANK, 1, "手机号码为空!"); } if(StringUtils.isBlank(enpassword)) { return new Result(Constants.USER_PASSWORD_BLANK, 1, "密码为空!"); } Object ocode = session.getAttribute(Constants.VALIDATION_CODE); if(ocode == null) { return new Result(Constants.USER_CODE_ERROR, 1, "验证码错误!"); } String scode = (String)ocode; if(!code.equals(scode)) { return new Result(Constants.USER_CODE_ERROR, 1, "验证码错误!"); } String password = rsaService.decrypt(enpassword); Member member = memberService.findByUsername(phone); if(member == null) { return new Result(Constants.USER_USER_NOT_EXISTS, 1, "手机号码未注册!"); } member.setPassword(<PASSWORD>(password)); memberService.update(member); return new Result(Constants.SUCCESS, 1); } } <file_sep>/src/main/java/cn/bmwm/modules/shop/controller/app/LoginController.java package cn.bmwm.modules.shop.controller.app; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import cn.bmwm.common.Constants; import cn.bmwm.common.Result; import cn.bmwm.modules.shop.entity.Member; import cn.bmwm.modules.shop.service.MemberService; import cn.bmwm.modules.shop.service.RSAService; import cn.bmwm.modules.sys.model.Setting; import cn.bmwm.modules.sys.model.Setting.AccountLockType; import cn.bmwm.modules.sys.utils.SettingUtils; /** * @author zby * 2014-11-6 下午9:09:04 */ @Controller public class LoginController { public static final Log log = LogFactory.getLog(LoginController.class); @Resource(name = "memberServiceImpl") private MemberService memberService; @Resource(name = "rsaServiceImpl") private RSAService rsaService; /** * 登录 * @param phone * @param request * @param response * @param session * @return */ @RequestMapping(value="/app/user/login", method = RequestMethod.POST) @ResponseBody public Result login(HttpServletRequest request, HttpSession session, String phone, String enpassword) { if(StringUtils.isBlank(phone)) { return new Result(Constants.USER_USERNAME_BLANK, 1, "手机号码为空!"); } if(StringUtils.isBlank(enpassword)) { return new Result(Constants.USER_PASSWORD_BLANK, 1, "密码为空!"); } String password = rsaService.decrypt(enpassword); if(StringUtils.isBlank(password)) { return new Result(Constants.USER_PASSWORD_BLANK, 1, "密码为空!"); } Member member = memberService.findByUsername(phone); if (member == null) { return new Result(Constants.USER_USER_NOT_EXISTS, 1, "手机号码未注册!"); } if (!member.getIsEnabled()) { return new Result(Constants.USER_USER_DISABLED, 1, "手机号码已禁用!"); } Setting setting = SettingUtils.get(); if (member.getIsLocked()) { if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.member)) { int loginFailureLockTime = setting.getAccountLockTime(); if (loginFailureLockTime == 0) { return new Result(Constants.USER_USER_LOCKED, 1, "手机号码已锁定!"); } Date lockedDate = member.getLockedDate(); Date unlockDate = DateUtils.addMinutes(lockedDate, loginFailureLockTime); if (new Date().after(unlockDate)) { member.setLoginFailureCount(0); member.setIsLocked(false); member.setLockedDate(null); memberService.update(member); } else { return new Result(Constants.USER_USER_LOCKED, 1, "手机号码已锁定!"); } } else { member.setLoginFailureCount(0); member.setIsLocked(false); member.setLockedDate(null); memberService.update(member); } } if (!DigestUtils.md5Hex(password).equals(member.getPassword())) { int loginFailureCount = member.getLoginFailureCount() + 1; if (loginFailureCount >= setting.getAccountLockCount()) { member.setIsLocked(true); member.setLockedDate(new Date()); } member.setLoginFailureCount(loginFailureCount); memberService.update(member); return new Result(Constants.USER_PASSWORD_ERROR, 1, "密码错误!"); } member.setLoginIp(request.getRemoteAddr()); member.setLoginDate(new Date()); member.setLoginFailureCount(0); memberService.update(member); Map<String, Object> attributes = new HashMap<String, Object>(); Enumeration<?> keys = session.getAttributeNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); attributes.put(key, session.getAttribute(key)); } session.invalidate(); session = request.getSession(); for (Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } Result result = new Result(Constants.SUCCESS, 1); result.put(Constants.USER_LOGIN_MARK, DigestUtils.md5Hex(member.getId().toString() + DigestUtils.md5Hex(password)) + "@" + member.getId().toString()); result.put("username", member.getUsername()); return result; } } <file_sep>/src/main/java/cn/bmwm/modules/shop/entity/PreOrderItem.java package cn.bmwm.modules.shop.entity; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; /** * Entity -- 预约订单项 * @author zby * 2014-12-13 下午9:57:04 */ @Entity @Table(name = "xx_preorder_item") @SequenceGenerator(name = "sequenceGenerator", sequenceName = "xx_preorder_item_sequence") public class PreOrderItem extends BaseEntity { private static final long serialVersionUID = -3474980669871464050L; /** 商品编号 */ private String sn; /** 商品名称 */ private String name; /** 商品全称 */ private String fullName; /** 商品价格 */ private BigDecimal price; /** 商品缩略图 */ private String thumbnail; /** 是否为赠品 */ private Boolean isGift; /** 数量 */ private Integer quantity; /** * 重量 */ private Integer weight; /** 商品 */ private Product product; /** 预约订单 */ private PreOrder preOrder; /** * 获取商品编号 * @return */ @Column(nullable = false, updatable = false) public String getSn() { return sn; } public void setSn(String sn) { this.sn = sn; } /** * 获取商品名称 * @return */ @Column(nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 获取商品全称 * @return */ @Column(nullable = false) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } /** * 获取商品价格 * @return */ @Column(nullable = false) public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } /** * 获取商品缩略图 * @return */ @Column(nullable = false) public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } /** * 获取是否为赠品 * @return */ @Column(nullable = false) public Boolean getIsGift() { return isGift; } public void setIsGift(Boolean isGift) { this.isGift = isGift; } /** * 获取商品数量 * @return */ @Column(nullable = false) public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } /** * 获取商品重量 * @return */ @Column(nullable = false) public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } /** * 获取商品 * @return */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product", nullable = false, updatable = false) public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } /** * 获取预约订单 * @return */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "preOrder", nullable = false, updatable = false) public PreOrder getPreOrder() { return preOrder; } public void setPreOrder(PreOrder preOrder) { this.preOrder = preOrder; } } <file_sep>/src/main/java/cn/bmwm/modules/shop/service/ImageService.java /* * */ package cn.bmwm.modules.shop.service; import cn.bmwm.modules.shop.entity.ProductImage; import cn.bmwm.modules.shop.entity.ShopImage; /** * Service - 图片 * * * @version 1.0 */ public interface ImageService { /** * 生成商品图片 * * @param productImage * 商品图片 */ void build(ProductImage productImage); /** * 店铺图片 * @param shopImage */ void build(ShopImage shopImage); }<file_sep>/src/main/java/cn/bmwm/modules/shop/dao/impl/CartItemDaoImpl.java /* * */ package cn.bmwm.modules.shop.dao.impl; import org.springframework.stereotype.Repository; import cn.bmwm.modules.shop.dao.CartItemDao; import cn.bmwm.modules.shop.entity.CartItem; /** * Dao - 购物车项 * * * @version 1.0 */ @Repository("cartItemDaoImpl") public class CartItemDaoImpl extends BaseDaoImpl<CartItem, Long> implements CartItemDao { }<file_sep>/src/main/java/cn/bmwm/modules/shop/dao/impl/PreOrderLogDaoImpl.java package cn.bmwm.modules.shop.dao.impl; import org.springframework.stereotype.Repository; import cn.bmwm.modules.shop.dao.PreOrderLogDao; import cn.bmwm.modules.shop.entity.PreOrderLog; /** * Dao -- 预约订单日志 * @author zby * 2014-12-14 下午12:05:45 */ @Repository("preOrderLogDaoImpl") public class PreOrderLogDaoImpl extends BaseDaoImpl<PreOrderLog,Long> implements PreOrderLogDao { }
516266a895659a8f3e35b11a37c9ade88e2d5fcc
[ "Java" ]
13
Java
doaa12/zipn
606325641882d5135f6e2758d40572122186bb08
9c8338ba535725ec689f4db314685145ca7f4b32
refs/heads/master
<file_sep>#include<iostream> #include<fstream> #include<conio.h> #include<string.h> using namespace std; class login{ public: string name; string password; public: login(string n,string pass):name(n),password(pass){ } bool log(string n,string pass){ if(name==n && password==pass){ return true; } else{ throw "Invalid user name or password"; } } }; class train { private: string buss[30]; string eco[30]; public: train(){ for(int i=0;i<30;i++){ buss[10]="empty"; eco[10]="empty"; } } int bussiness(){ for(int i=0;i<30;i++){ if (buss[i]=="empty"){ buss[i]="booked"; return i; } break; } } int economy(){ for(int i=0;i<30;i++){ if(eco[i]=="empty"){ eco[i]="booked"; return i; } break; } } }; class reservation:public train { private: string name; long long int cnic,cntc; int c; string dep; string arr; string trains; int seat; public: train t1; train t2; void getdata() { fstream f1; f1.open("reservations.txt",ios::in|ios::out|ios::app); cout<<"\nEnter name: "; cin>>name; cout<<"Enter CNIC: "; cin>>cnic; cout<<"Contact: "; cin>>cntc; f1<<"Name: "<<name<<endl; f1<<"CNIC: "<<cnic<<endl; f1<<"Contact: "<<cntc<<endl; cout<<"Enter Dep city: "; cin>>dep; cout<<"Enter arrv city:"; cin>>arr; f1<<"Departure: "<<dep<<endl; f1<<"Arrival: "<<arr<<endl; if(dep=="multan"&&arr=="lahore") { int seatno, ch2; cout<<"Enter 1 for Musa-Pak Express\n"; cout<<"Enter 2 for Multan Express"; cin>>ch2; switch(ch2){ case 1: { f1<<"train: Musa Pak Express"; trains="Musa Pak Express"; break; } case 2:{ f1<<"train: Multan Express"; trains="Multan Express"; break; } } int ch3; cout<<"Enter 1 for bussiness class:\n"; cout<<"Enter 2 for Economy class:"; cin>>ch3; if (ch3==1){ f1<<"\nClass: Bussiness"; seat=t1.bussiness(); f1<<"\nseat: "<<seat<<endl; cout<<"Price: 3000"; f1<<"\nPrice: 3000"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else f1<<"\nTicket not conform"; } else if(ch3==2){ f1<<"\nClass: Economy"; seat=t1.economy(); f1<<"\nseat: "<<seat<<endl; cout<<"\nPrice: 1500"; f1<<"\nPrice: 1500"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else{ f1<<"\nTicket not conform"; } } else cout<<"wrong input"; } else if(dep=="multan"&&arr=="karachi") { int seatno, ch2; cout<<"Enter 1 for Karachi Express\n"; cout<<"Enter 2 for Pakistan Express"; cin>>ch2; switch(ch2){ case 1: { f1<<"train: Karachi Express"; trains="Karachi Express"; break; } case 2:{ f1<<"train: Pakistan Express"; trains="Pakistan Express"; break; } } int ch3; cout<<"Enter 1 for bussiness class:\n"; cout<<"Enter 2 for Economy class:"; cin>>ch3; if (ch3==1){ f1<<"\nClass: Bussiness"; seat=t1.bussiness(); f1<<"\nseat: "<<seat<<endl; cout<<"Price: 3000"; f1<<"\nPrice: 3000"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else f1<<"\nTicket not conform"; } else if(ch3==2){ f1<<"\nClass: Economy"; seat=t1.economy(); f1<<"\nseat: "<<seat<<endl; cout<<"\nPrice: 1500"; f1<<"\nPrice: 1500"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else f1<<"\nTicket not conform"; } else cout<<"wrong input"; } else if(dep=="multan"&&arr=="islamabad") { int seatno, ch2; cout<<"Enter 1 for Islamabad Express\n"; cout<<"Enter 2 for Pakistan Express"; cin>>ch2; switch(ch2){ case 1: { f1<<"train: Islamabad Express"; trains="Islamabad Express"; break; } case 2:{ f1<<"train: Pakistan Express"; trains="Pakistan Express"; break; } } int ch3; cout<<"Enter 1 for bussiness class:\n"; cout<<"Enter 2 for Economy class:"; cin>>ch3; if (ch3==1){ f1<<"\nClass: Bussiness"; seat=t1.bussiness(); f1<<"\nseat: "<<seat<<endl; cout<<"Price: 3000"; f1<<"\nPrice: 3000"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else f1<<"\nTicket not conform"; } else if(ch3==2){ f1<<"\nClass: Economy"; seat=t1.economy(); f1<<"\nseat: "<<seat<<endl; cout<<"\nPrice: 1500"; f1<<"\nPrice: 1500"; cout<<"\nPress 1 to confrm"; cin>>c; if(c==1){ f1<<"\nTicket Conform"; } else f1<<"\nTicket not conform"; } else cout<<"wrong input"; } } void dispdata() { cout<<"\nName: "<<name; cout<<"\nCNIC: "<<cnic; cout<<"\ncontact: "<<cntc; cout<<"\nDeparture city:"<<dep; cout<<"\nArrival city: "<<arr; cout<<"\ntrain: "<<trains; } }; class traintimming{ public: void timming() { cout<<"Multan to Lahore:"; cout<<"\nMusa-Pak "; } }; int main() { system("color 4f"); login l("admin","1234"); string password; string username; cout<<"Enter user name:"<<endl; cin>>username; cout<<"Enter password:"<<endl; cin>>password; try{ if(l.log(username,password)){ int ch1; while(1){ system("cls"); system("color 4f"); cout<<"----------------------- WELCOME TO RAILWAY RESERVATION ------------------------"; cout<<"--------------------ISLAMABAD----LAHORE----MULTAN----KARACHI---------------------"; cout<<"Enter 1 for reservation:\n"; cout<<"Enter 2 for timming:"; cin>>ch1; reservation r1; if(ch1==1){ r1.getdata(); r1.dispdata(); } else if(ch1==2){ } string p; cout<<"\n\npress 1 to exit:\n Any key to continue....."; cin>>p; if(p=="1") { exit(0); } } } } catch(const char* msg){ cout<<msg<<endl; char a=getch(); } }
d6b8fc496c2a0b964d2cda87ab9131c74da22889
[ "C++" ]
1
C++
waqarbashir6/code
3bb4a7dd68969c3c92b6d9ba30230155286e2d35
5a8c299e9de5b7680994865193d70dba53a19817
refs/heads/master
<repo_name>mgood13/Pandemic<file_sep>/blackjack.py import random # dealer cards dealer_cards = [] # player cards player_cards = [] # Deal the cards #Dealer Cards while len(dealer_cards) != 2: dealer_cards.append(random.randint(1, 11)) if len(dealer_cards) == 2: print("Dealer has X & ", dealer_cards[1]) #Player Cards while len(player_cards) != 2: player_cards.append(random.randint(1,11)) if len(player_cards) == 2: print("Player has:", player_cards) # Sum of the dealer cards if sum(dealer_cards ) == 21: print("Dealer has 21 & Wins") elif sum(dealer_cards) > 21: print("Dealer has busted") #Sum of player cards while sum(player_cards) < 21: action_taken = str(input("Do you want to stay or hit?")) if action_taken == "hit": player_cards.append(random.randint(1,11)) print("You now have a total of " + str(sum(player_cards))+ " from these cards",player_cards) else: print("The dealer has a total of " + str(sum(dealer_cards))+" with these cards", dealer_cards) print("You have a total of "+str(sum(player_cards))+ " from these cards", player_cards) if sum(dealer_cards) > sum(player_cards): print("Dealer wins!") else: print("You win!") break if sum(player_cards) == 21: print("You got BlackJack!") elif sum(player_cards) > 21: print("you busted")<file_sep>/README.md # Pandemic A new adventure in putting together a game in python :D The excel file has all of the cities separated by color with latitude and longitude and with population information. Population information is suspect because there wasn't a lot of consistency in the numbers I found... some were urban area, some were only city. It's hard to say and honestly it might not even matter. Michael's Upcoming Tasks: - Setting up a graph with clickable points that display information - Review Pygame (whatever the python gaming library is) to see if there's anything useful out there <file_sep>/hover.py """ Annotate on hover ================= When ``hover`` is set to ``True``, annotations are displayed when the mouse hovers over the artist, without the need for clicking. """ import matplotlib.pyplot as plt import numpy as np import mplcursors import csv import networkx as nx np.random.seed(42) colors = ['blue', 'yellow', 'red', 'black'] color_dict = {'blue': 0, 'yellow': 0, 'red': 0, 'black': 0} f = open('Pandemic Locations.csv', encoding='utf-8-sig') city_dictionary = {} count = 0 with f: reader = csv.reader(f) for row in reader: city_dictionary[row[1]] = {'Color': row[0], 'Latitude': row[2], 'Longitude': row[3], 'Population': row[4], 'X': row[5], 'Y': row[6], 'ID': row[7], 'Connections': row[8], 'Disease State': color_dict} f.close() cities = list(city_dictionary.keys()) x = {'blue': [], 'yellow': [], 'red': [], 'black': []} y = {'blue': [], 'yellow': [], 'red': [], 'black': []} xmapped = [] ymapped = [] names = np.array(cities[0:24]) for city in cities: if city_dictionary[city]['Color'] == 'blue': x['blue'].append(float(city_dictionary[city]['Longitude'])) y['blue'].append(float(city_dictionary[city]['Latitude'])) xmapped.append(float(city_dictionary[city]['X'])) ymapped.append(float(city_dictionary[city]['Y'])) if city_dictionary[city]['Color'] == 'yellow': x['yellow'].append(float(city_dictionary[city]['Longitude'])) y['yellow'].append(float(city_dictionary[city]['Latitude'])) xmapped.append(float(city_dictionary[city]['X'])) ymapped.append(float(city_dictionary[city]['Y'])) if city_dictionary[city]['Color'] == 'red': x['red'].append(float(city_dictionary[city]['Longitude'])) y['red'].append(float(city_dictionary[city]['Latitude'])) if city_dictionary[city]['Color'] == 'black': x['black'].append(float(city_dictionary[city]['Longitude'])) y['black'].append(float(city_dictionary[city]['Latitude'])) plt.style.use('dark_background') cmap = plt.cm.RdYlGn norm = plt.Normalize(1,4) img = plt.imread("BlackMarble_2016_01deg.jpg") fig, ax = plt.subplots(figsize=(16,6)) ax.imshow(img, extent=[0, 200, 0, 100]) ax.set_title('WELCOME TO PANDEMIC. OR... THE REAL WORLD') #for color in x: # plt.scatter(x[color], y[color], s=2, c=color) categories = np.array([]) for i in xmapped: if count < 12: categories = np.append(categories, [0]) else: categories = np.append(categories, [1]) print("hi") count += 1 print(categories.dtype) categories = categories.astype(int) print(categories.dtype) colormap = np.array(['blue', 'yellow']) #plt.scatter(a[0], a[1], s=100, c=colormap[categories]) sc = plt.scatter(xmapped[0:24], ymapped[0:24], s=10, c=colormap[categories]) #sc1 = plt.scatter(xmapped[13:24], ymapped[13:24], s=10, c='yellow') annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points", bbox=dict(boxstyle="round", fc="b"), arrowprops=dict(arrowstyle="-")) annot.set_visible(False) def update_annot(ind): print(ind) pos = sc.get_offsets()[ind["ind"][0]] annot.xy = pos #text = "{}\n{}".format(" ".join(str(pos)), " ".join([names[n] for n in ind["ind"]])) text = "{}\n{}\n{}".format(" ".join([names[n] for n in ind["ind"]]), "Diseases Present: EBOLA", "Concern Level: Normal") annot.set_text(text) annot.get_bbox_patch().set_facecolor('black') annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: # this line checks if the position of the mouse equals one of the scatter points # cont becomes true if it is cont, ind = sc.contains(event) print(cont) print("THis is ind: ") print(ind) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() #def diseasecubes(): # Store all of the disease cube states #def concernlevel(): # Define a value for how close a city is to outbreaking and change... color or size fig.canvas.mpl_connect("motion_notify_event", hover) plt.axis('off') plt.show() #xtest = x['blue'][0:2] #ytest = y['blue'][0:2] #plt.plot(xtest,ytest,) #print(xtest) #plt.subplots_adjust(left=0.13, bottom=0.04, right=0.90, top=0.96, wspace=0.07, hspace=0.08) #mplcursors.cursor(hover=True) #fig, ax = plt.subplots() #x = [1,2] #y = [3,4] #ax.scatter(x,y) #ax.set_title("Mouse over a point") #plt.show() #count = 0 #G = nx.Graph() #for value in city_dictionary: # G.add_node(value,pos = (float(city_dictionary[cities[count]]['Longitude']), float(city_dictionary[cities[count]]['Latitude']))) # count += 1 # nx.draw(G) #print(pos) #pos = G.get_node_attribute(G,'pos') #nx.draw(G,pos) #for city in cities: # G.add_node() #G.add_nodes_from() #nx.draw(G, with_labels=True, font_weight='bold') #plt.show()
18cf4b5065e80d98ff1b7799d907fa1a1530c1b2
[ "Markdown", "Python" ]
3
Python
mgood13/Pandemic
c0b8b05e8ad2afea905bdf8a475e79180957c0b0
694d5b95f4b0c67c8081ccee7458eda3fc4e3c25
refs/heads/main
<file_sep># 25-Online-Grocery-App <file_sep>package com.example.mysearchactivity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import com.example.mysearchactivity.adapters.categoryAdapter; import com.example.mysearchactivity.model.CategoryWiseItems; import com.example.mysearchactivity.model.categories; import com.example.mysearchactivity.viewModels.categoryViewModel; import com.example.mysearchactivity.viewModels.categoryWiseViewModel; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import android.app.SearchManager; import android.view.MenuItem; import android.widget.SearchView; import android.widget.SearchView.OnQueryTextListener; import org.json.JSONException; import org.json.JSONObject; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { FirebaseDatabase firebaseDatabase; DatabaseReference databaseReference; private categoryViewModel mcategoryViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); firebaseDatabase = FirebaseDatabase.getInstance(); databaseReference = firebaseDatabase.getReference("categories"); mcategoryViewModel = new ViewModelProvider(this).get(categoryViewModel.class); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { mcategoryViewModel.deletAllCategories(); for(DataSnapshot snapshot1:snapshot.getChildren()) { categories category=snapshot1.getValue(categories.class); mcategoryViewModel.insert(category); } } @Override public void onCancelled(@NonNull DatabaseError error) { // Toast.makeText(MainActivity.class, "Fail to get data.", Toast.LENGTH_SHORT).show(); } }); RecyclerView recyclerView = findViewById(R.id.recyclerview); final categoryAdapter adapter = new categoryAdapter(this); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); mcategoryViewModel.getAllCategories().observe(this, new Observer<List<categories>>() { @Override public void onChanged(@Nullable final List<categories> categories) { // Update the cached copy of the words in the adapter. adapter.setCategory(categories); } }); databaseReference = firebaseDatabase.getReference("categoryWiseItems"); categoryWiseViewModel mcategoryWiseViewModel; mcategoryWiseViewModel = new ViewModelProvider(this).get(categoryWiseViewModel.class); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { mcategoryWiseViewModel.deletAllCategoryWiseItems(); for(DataSnapshot snapshot1:snapshot.getChildren()) { String category_of_item = snapshot1.getKey(); for(DataSnapshot snapshot2:snapshot1.getChildren()) { Map<String, String> value = (Map<String, String>) snapshot2.getValue(); JSONObject obj = new JSONObject(value); try { String name = obj.getString("name"); String ImageUrl = obj.getString("photosUrl"); String other_sizes = obj.getString("otherSizes"); String discount = obj.getString("discount"); String ratingCount = obj.getString("peopleRatingCount"); String rating = obj.getString("ratingTotal"); String price = obj.getString("price"); String size = obj.getString("size"); boolean instock = obj.getBoolean("inStock"); String deliveryDuration = obj.getString("deliveryDuration"); String description = obj.getString("description"); CategoryWiseItems category = new CategoryWiseItems(name, discount,ratingCount,rating,price,size,instock,description,deliveryDuration,category_of_item,ImageUrl,other_sizes); mcategoryWiseViewModel.insert(category); } catch (JSONException e) { e.printStackTrace(); } } } } @Override public void onCancelled(@NonNull DatabaseError error) { // Toast.makeText(MainActivity.class, "Fail to get data.", Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchmenu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.search: Intent intent = new Intent(MainActivity.this,searchDialog.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } }
cbd6f443a015ea104a549ea0cebeec69d35efb08
[ "Markdown", "Java" ]
2
Markdown
Myagnik/25-Online-Grocery-App
bde1592cb54b26125350e7e6e0d71c505864f0e7
ab753b5f8b2ddffe37d8af560f4c5f1899a9c5e8
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- The MIT License (MIT) Copyright (c) 2020 <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 NON-INFRINGEMENT. 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. --> <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> <groupId>com.jcabi</groupId> <artifactId>parent</artifactId> <version>0.50.0</version> </parent> <groupId>org.jpeek</groupId> <artifactId>jpeek-maven-plugin</artifactId> <version>1.0-SNAPSHOT</version> <packaging>maven-plugin</packaging> <name>jpeek-maven-plugin</name> <description>Maven plugin for jpeek - Static collector of Java code metrics</description> <url>https://github.com/yegor256/jpeek-maven-plugin</url> <inceptionYear>2020</inceptionYear> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> </properties> <organization> <name>jPeek</name> <url>https://github.com/yegor256/jpeek</url> </organization> <licenses> <license> <name>MIT</name> <url>https://www.jpeek.org/LICENSE.txt</url> <distribution>site</distribution> </license> </licenses> <issueManagement> <system>GitHub</system> <url>https://github.com/yegor256/jpeek-maven-plugin/issues</url> </issueManagement> <scm> <connection>scm:git:git@github.com:yegor256/jpeek-maven-plugin.git</connection> <developerConnection>scm:git:git@github.com:yegor256/jpeek-maven-plugin.git</developerConnection> <url>https://github.com/yegor256/jpeek-maven-plugin</url> </scm> <ciManagement> <system>rultor</system> <url>https://www.rultor.com/s/jpeek-maven-plugin</url> </ciManagement> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>3.6.3</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <version>3.6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.jcabi</groupId> <artifactId>jcabi-xml</artifactId> <version>0.21.1</version> </dependency> <dependency> <groupId>org.jpeek</groupId> <artifactId>jpeek</artifactId> <version>0.30.24</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <version>3.6.0</version> <executions> <execution> <id>mojo-descriptor</id> <phase>process-classes</phase> <goals> <goal>descriptor</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>qulice</id> <build> <plugins> <plugin> <groupId>com.qulice</groupId> <artifactId>qulice-maven-plugin</artifactId> <version>0.18.17</version> <executions> <execution> <id>jcabi-qulice-check</id> <phase>verify</phase> <goals> <goal>check</goal> </goals> <configuration> <license>file:${basedir}/LICENSE.txt</license> <excludes> <exclude>duplicatefinder:.*</exclude> </excludes> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>jcabi-gpg</id> <activation> <property> <name>gpg.keyname</name> </property> </activation> <build> <plugins> <plugin> <artifactId>maven-gpg-plugin</artifactId> <version>1.6</version> <executions> <execution> <id>jcabi-sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> <configuration combine.self="override"> <gpgArguments> <arg>--pinentry-mode</arg> <arg>loopback</arg> </gpgArguments> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> <file_sep>## How to use? Add the plugin execution to your `pom.xml`: ```xml <plugin> <groupId>org.jpeek</groupId> <artifactId>jpeek-maven-plugin</artifactId> <version>1.0-SNAPSHOT</version> <executions> <execution> <goals> <!-- Bound by default to verify phase --> <goal>analyze</goal> </goals> </execution> </executions> <configuration> <!-- Those are the default values --> <inputDirectory>${project.build.outputDirectory}</inputDirectory> <outputDirectory>${project.build.directory}/jpeek/</outputDirectory> <cohesionRate>8.0</cohesionRate> </configuration> </plugin> ``` Or run it from the command-line: ``` mvn org.jpeek:jpeek-maven-plugin:1.0-SNAPSHOT:analyze ``` <file_sep>/* * The MIT License (MIT) * * Copyright (c) 2020 <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 NON-INFRINGEMENT. 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. */ package org.jpeek.plugin; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import java.io.File; import java.io.IOException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jpeek.App; /** * {@link org.apache.maven.plugin.AbstractMojo} implementation for jPeek. * * @since 0.1 * @todo #3:30min Add some tests for this Mojo using AbstractMojoTestCase * from maven-plugin-testing-harness. A good resource for examples is * maven-checkstyle-plugin. It has been verified that it works from the * command line (see README). * @todo #3:30min Add support for analyzing classes in the test directory. * This should output an analysis most certainly in a different directory * from the main classes. */ @Mojo(name = "analyze", defaultPhase = LifecyclePhase.VERIFY) public final class JpeekMojo extends AbstractMojo { /** * Specifies the path where to find classes analyzed by jPeek. * * @checkstyle MemberNameCheck (3 lines) */ @Parameter(property = "jpeek.input", defaultValue = "${project.build.outputDirectory}") private File inputDirectory; /** * Specifies the path to save the jPeek output. * * @checkstyle MemberNameCheck (3 lines) */ @Parameter(property = "jpeek.output", defaultValue = "${project.build.directory}/jpeek/") private File outputDirectory; /** * Specifies expected cohesion ration of a project. * * @checkstyle MemberNameCheck (3 lines) */ @Parameter(property = "jpeek.cohesionrate", defaultValue = "8.0") private double cohesionRate; /** * Skip analyze. */ @Parameter(property = "jpeek.skip", defaultValue = "false") private boolean skip; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!this.skip) { try { new App( this.inputDirectory.toPath(), this.outputDirectory.toPath() ).analyze(); final XML index = new XMLDocument( new File(String.format("%s\\%s", this.outputDirectory, "index.xml")) ); final double score = Double.parseDouble( index.xpath("/index/@score").get(0) ); if (score < this.cohesionRate) { throw new MojoFailureException( String.format("Project cohesion rate is less than %.2f", this.cohesionRate) ); } } catch (final IOException ex) { throw new MojoExecutionException("Couldn't analyze", ex); } } } }
682b66e076e0310d537397655e1120bf28a45f48
[ "Markdown", "Java", "Maven POM" ]
3
Maven POM
yegor256/jpeek-maven-plugin
4d00791fa1472727d53cd39863a42d7674b73f4d
398a6d4ee118320a125b9d4757a9f8aaed07524f
refs/heads/master
<repo_name>csknns/RgWsPublicClientPHP<file_sep>/generated/RgWsPublic.php <?php /** * GenWsErrorRtUser.php * * Copyright (c) 2015 <NAME> <<EMAIL>>. * * 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. * * * @author <NAME> <<EMAIL>> * @copyright 2015 <NAME> <<EMAIL>> * @license http://opensource.org/licenses/MIT MIT License * @version 0.1.0 */ include_once('wse-php/soap-wsse.php'); include_once('RgWsPublicInputRtUser.php'); include_once('RgWsPublicInputRtBase.php'); include_once('RgWsPublicBasicRtUser.php'); include_once('RgWsPublicBasicRtBase.php'); include_once('RgWsPublicFirmActRtUserArray.php'); include_once('RgWsPublicFirmActRtUser.php'); include_once('RgWsPublicFirmActRtBase.php'); include_once('GenWsErrorRtUser.php'); include_once('GenWsErrorRtBase.php'); class mySoap extends SoapClient { private $password; private $username; public function __construct($username = '', $password = '', $wsdl = 'RgWsPublicPort.wsdl', array $options = array()) { parent::__construct($wsdl, $options); $this->username = $username; $this->password = $password; } function __doRequest($request, $location, $saction, $version) { $dom = new DOMDocument(); $dom->loadXML($request); $objWSA = new WSSESoap($dom); $objWSA->addUserToken($this->username, $this->password, false); $request = $objWSA->saveXML(); print_r($request); return parent::__doRequest($request, $location, $saction, $version); } } /** * */ class RgWsPublic extends mySoap { /** * * @var array $classmap The defined classes * @access private */ private static $classmap = array( 'RgWsPublicInputRtUser' => '\RgWsPublicInputRtUser', 'RgWsPublicInputRtBase' => '\RgWsPublicInputRtBase', 'RgWsPublicBasicRtUser' => '\RgWsPublicBasicRtUser', 'RgWsPublicBasicRtBase' => '\RgWsPublicBasicRtBase', 'RgWsPublicFirmActRtUserArray' => '\RgWsPublicFirmActRtUserArray', 'RgWsPublicFirmActRtUser' => '\RgWsPublicFirmActRtUser', 'RgWsPublicFirmActRtBase' => '\RgWsPublicFirmActRtBase', 'GenWsErrorRtUser' => '\GenWsErrorRtUser', 'GenWsErrorRtBase' => '\GenWsErrorRtBase'); /** * * @param array $options A array of config values * @param string $wsdl The wsdl file to use * @access public */ public function __construct($username = '', $password = '', array $options = array(), $wsdl = 'generated/RgWsPublicPort.wsdl') { foreach (self::$classmap as $key => $value) { if (!isset($options['classmap'][$key])) { $options['classmap'][$key] = $value; } } parent::__construct($username, $password, $wsdl, $options); } /** * * @param RgWsPublicInputRtUser $RgWsPublicInputRt_in * @param RgWsPublicBasicRtUser $RgWsPublicBasicRt_out * @param RgWsPublicFirmActRtUserArray $arrayOfRgWsPublicFirmActRt_out * @param decimal $pCallSeqId_out * @param GenWsErrorRtUser $pErrorRec_out * @access public * @return list(RgWsPublicBasicRtUser $RgWsPublicBasicRt_out, RgWsPublicFirmActRtUserArray $arrayOfRgWsPublicFirmActRt_out, decimal $pCallSeqId_out, GenWsErrorRtUser $pErrorRec_out) */ public function rgWsPublicAfmMethod(RgWsPublicInputRtUser $RgWsPublicInputRt_in, RgWsPublicBasicRtUser $RgWsPublicBasicRt_out, RgWsPublicFirmActRtUserArray $arrayOfRgWsPublicFirmActRt_out,$pCallSeqId_out, GenWsErrorRtUser $pErrorRec_out) { return $this->__soapCall('rgWsPublicAfmMethod', array($RgWsPublicInputRt_in, $RgWsPublicBasicRt_out, $arrayOfRgWsPublicFirmActRt_out, $pCallSeqId_out, $pErrorRec_out)); } /** * * @access public * @return string */ public function rgWsPublicVersionInfo() { return $this->__soapCall('rgWsPublicVersionInfo', array()); } } <file_sep>/README.md # RgWsPublicClientPHP **RgWsPublicClient** is an PHP client for accessing the [new web service](http://www.gsis.gr/gsis/info/gsis_site/PublicIssue/wnsp/wnsp_pages/wnsp.html) provided by [GSIS](http://www.gsis.gr/gsis/info/gsis_site/PublicIssue/wnsp/wnsp_pages/wnsp.html) for physical persons and legal entities. The new webservice provides two methods, one for retrieving the service's version information and the second for retrieving information regarding a requested VAT(A.F.M.). The latter requires authentication using the UsernameToken Extensions of WSS(see [Web Services Security UsernameToken Profile](http://docs.oasis-open.org/wss/v1.1/wss-v1.1-spec-pr-UsernameTokenProfile-01.htm)). The project has a simple client that provides two methods (corresponding to the two web services) with error checking and handling, and an example PHP file that uses the client. ### Example * clone/copy this project * edit the example client and add your username/password: ```php $client = new RgWsPublic("<username>", "<password>"); ``` * execute the file from within a web server or from the command line: ```php -f RgWsPublicClient.php```
81a203135a92a8aab5dd59b8dc849c01810f26de
[ "Markdown", "PHP" ]
2
PHP
csknns/RgWsPublicClientPHP
662c40eba8bc361de8e1f6fd26d40bad176fed33
6711310dd0ff611edf8b2c66d693b214b0ea23d2
refs/heads/master
<file_sep>// 手机号正则表达式 function checkPhone(phone) { if (!(/^1[34578]\d{9}$/.test(phone))) { alert('wrong phone number'); return false; } } // 去掉字符串前后多余的空格 var string = ' a b c '; string.replace(/^\s+|\s+$/g, ''); // 使用对象查找字符串中出现次数最多的字符 // 主要是使用对象 var str = 'abceddddzhaofffwi'; var o = {}; for (var i = 0, len = str.length; i < len; i++) { var char = str.charAt(i); // char就是对象o的一个属性, o[char]是属性值, o[char]控制出现的次数 if (o[char]) { o[char]++; } else { // 若第一次出现,记次数为1 o[char] = 1; } } console.log(o); // 输出的是完整的对象,记录着每一个字符及其出现的次数 // 遍历对象,找到出现最多的字符和次数 var max = 0; var maxChar = null; for (var key in o) { if (max < o[key]) { max = o[key]; } } for (var key in o) { if (o[key] === max) { console.log('the character' + key); } } // 关于正则表达式 非捕获组 (?:x) 不返回该组匹配的内容 // x(?=y)先行断言 // x(?!y)先行否定断言 // // thousand format function formatThousandSep(input) { if (isNaN(input)) { return input; } else { var translateStr = ''; var reg = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g; translateStr = input.toString().replace(reg, '$1,'); return translateStr; } } console.log(formatThousandSep(2004500)); <file_sep># treadstone This is some codes during my learning for JS or some optimization skills
bff452d4000cfff3dd386f487f406d8ff7c1843c
[ "JavaScript", "Markdown" ]
2
JavaScript
leoswing/treadstone
1f390ab5fafa3dcb81d1b3775ee912d5d529092e
652458ed404c2b76d8de865c35f5f638a59778c6
refs/heads/master
<repo_name>bloesch/LSEnode<file_sep>/CMakeLists.txt cmake_minimum_required (VERSION 2.6) include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake) SET(CMAKE_BUILD_TYPE "Release") rosbuild_init() find_package(Eigen REQUIRED) find_package(LSE REQUIRED) include_directories(${Eigen_INCLUDE_DIRS}) include_directories(${LSE_INCLUDE_DIRS}) rosbuild_add_executable(LSEnode src/main.cpp) target_link_libraries(LSEnode ${LSE_LIBRARIES}) <file_sep>/src/templateLSE.cpp /*! * @file main.cpp * @author <NAME> * @date 10.10.2012 * @brief */ #include <Eigen/Dense> #include "LSE/Manager.hpp" // Kinematics of robot Eigen::Vector3d legKin(Eigen::Matrix<double,LSE_DOF_LEG,1> a,int i){ // Todo: include the parameters into the function call -> later used for robot calibration double bx = 0.2525; double by = 0.185; double lH = -0.0685; double lT = -0.2; double lS = -0.235; Eigen::Vector3d s; s(0) = ((i<2)*2-1)*bx+lT*sin(a(1))+lS*sin(a(1)+a(2)); s(1) = -((i%2)*2-1)*by-sin(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); s(2) = cos(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); return s; } // Kinematic Jacobian of robot Eigen::Matrix<double,3,LSE_DOF_LEG> legKinJac(Eigen::Matrix<double,LSE_DOF_LEG,1> a,int i){ double lH = -0.0685; double lT = -0.2; double lS = -0.235; Eigen::Matrix<double,3,LSE_DOF_LEG> J; J.setZero(); J(0,1) = lS*cos(a(1)+a(2))+lT*cos(a(1)); J(0,2) = lS*cos(a(1)+a(2)); J(1,0) = -cos(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); J(1,1) = sin(a(0))*(lT*sin(a(1))+lS*sin(a(1)+a(2))); J(1,2) = lS*sin(a(0))*sin(a(1)+a(2)); J(2,0) = -sin(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); J(2,1) = -cos(a(0))*(lT*sin(a(1))+lS*sin(a(1)+a(2))); J(2,2) = -lS*cos(a(0))*sin(a(1)+a(2)); return J; } // Init State Estimate LSE::Manager* pManager_; string fileName = "Parameters.xml"; pManager_ = new LSE::Manager(fileName.c_str(),&legKin,&legKinJac); double time; pManager_->resetEstimate(time); // Send Measurements and update LSE::ImuMeas imuMeas; double time; pManager_->addImuMeas(time,imuMeas); LSE::EncMeas encMeas; double time; pManager_->addEncMeas(time,encMeas); pManager_->update(); // Reset Estimate double time; pManager_->resetEstimate(time); // Get State Estimate LSE::State x; x = pManager_->getEst(); // Finish delete pManager_; <file_sep>/src/main.cpp /*! * @file main.cpp * @author <NAME> * @date 10.10.2012 * @brief Simple ros-node including the LSE library */ #include <Eigen/Dense> #include "ros/ros.h" #include "sensor_msgs/Imu.h" #include "sensor_msgs/JointState.h" #include "geometry_msgs/PoseStamped.h" #include "geometry_msgs/Vector3Stamped.h" #include "LSE/Manager.hpp" using namespace std; // Global Variables bool gotFirstMeas_; LSE::Manager* pManager_; ros::Publisher poseEst; ros::Publisher velEst; ros::Publisher rrEst; // Kinematics of robot Eigen::Vector3d legKin(Eigen::Matrix<double,LSE_DOF_LEG,1> a,int i){ // Todo: include the parameters into the function call -> later used for robot calibration double bx = 0.2525; double by = 0.185; double lH = -0.0685; double lT = -0.2; double lS = -0.235; Eigen::Vector3d s; s(0) = ((i<2)*2-1)*bx+lT*sin(a(1))+lS*sin(a(1)+a(2)); s(1) = -((i%2)*2-1)*by-sin(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); s(2) = cos(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); return s; } // Kinematic Jacobian of robot Eigen::Matrix<double,3,LSE_DOF_LEG> legKinJac(Eigen::Matrix<double,LSE_DOF_LEG,1> a,int i){ double lH = -0.0685; double lT = -0.2; double lS = -0.235; Eigen::Matrix<double,3,LSE_DOF_LEG> J; J.setZero(); J(0,1) = lS*cos(a(1)+a(2))+lT*cos(a(1)); J(0,2) = lS*cos(a(1)+a(2)); J(1,0) = -cos(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); J(1,1) = sin(a(0))*(lT*sin(a(1))+lS*sin(a(1)+a(2))); J(1,2) = lS*sin(a(0))*sin(a(1)+a(2)); J(2,0) = -sin(a(0))*(lH+lT*cos(a(1))+lS*cos(a(1)+a(2))); J(2,1) = -cos(a(0))*(lT*sin(a(1))+lS*sin(a(1)+a(2))); J(2,2) = -lS*cos(a(0))*sin(a(1)+a(2)); return J; } // Publishes the filtered data into ros topics void plotResults(){ LSE::State x; x = pManager_->getEst(); geometry_msgs::PoseStamped msgPose; geometry_msgs::Vector3Stamped msgVec; // Build and publish pose message msgPose.header.seq = 0; msgPose.header.stamp = ros::Time(x.t_); msgPose.header.frame_id = "/W"; msgPose.pose.position.x = x.r_(0); msgPose.pose.position.y = x.r_(1); msgPose.pose.position.z = x.r_(2); msgPose.pose.orientation.x = -x.q_(0); msgPose.pose.orientation.y = -x.q_(1); msgPose.pose.orientation.z = -x.q_(2); msgPose.pose.orientation.w = x.q_(3); poseEst.publish(msgPose); // Build and publish velocity message msgVec.header.seq = 0; msgVec.header.stamp = ros::Time(x.t_); msgVec.header.frame_id = "/W"; msgVec.vector.x = x.v_(0); msgVec.vector.y = x.v_(1); msgVec.vector.z = x.v_(2); velEst.publish(msgVec); // Build and publish velocity message msgVec.header.seq = 0; msgVec.header.stamp = ros::Time(x.t_); msgVec.header.frame_id = "/B"; msgVec.vector.x = x.w_(0); msgVec.vector.y = x.w_(1); msgVec.vector.z = x.w_(2); rrEst.publish(msgVec); } // Callback functions void imuCallback(const sensor_msgs::Imu::ConstPtr& msg) { if(!gotFirstMeas_){ pManager_->resetEstimate(msg->header.stamp.toSec()); gotFirstMeas_ = true; } LSE::ImuMeas imuMeas; imuMeas.f_(0) = msg->linear_acceleration.x; imuMeas.f_(1) = msg->linear_acceleration.y; imuMeas.f_(2) = msg->linear_acceleration.z; imuMeas.w_(0) = msg->angular_velocity.x; imuMeas.w_(1) = msg->angular_velocity.y; imuMeas.w_(2) = msg->angular_velocity.z; pManager_->addImuMeas(msg->header.stamp.toSec(),imuMeas); } void encCallback(const sensor_msgs::JointState::ConstPtr& msg) { if(!gotFirstMeas_){ pManager_->resetEstimate(msg->header.stamp.toSec()); gotFirstMeas_ = true; } LSE::EncMeas encMeas; for(int i=0;i<LSE_N_LEG;i++){ for(int j=0;j<LSE_DOF_LEG;j++){ encMeas.e_(j,i) = msg->position[i*LSE_DOF_LEG+j]; } // for(int j=0;j<LSE_DOF_LEG;j++){ // encMeas.v_(j,i) = msg->velocity[i*LSE_DOF_LEG+j]; // } encMeas.CF_[i] = (int)msg->effort[i*LSE_DOF_LEG]; } pManager_->addEncMeas(msg->header.stamp.toSec(),encMeas); pManager_->update(); plotResults(); } void posCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) { if(!gotFirstMeas_){ pManager_->resetEstimate(msg->header.stamp.toSec()); gotFirstMeas_ = true; } LSE::PosMeas posMeas; posMeas.r_(0) = msg->pose.position.x; posMeas.r_(1) = msg->pose.position.y; posMeas.r_(2) = msg->pose.position.z; posMeas.q_(0) = msg->pose.orientation.x; posMeas.q_(1) = msg->pose.orientation.y; posMeas.q_(2) = msg->pose.orientation.z; posMeas.q_(3) = msg->pose.orientation.w; pManager_->addPosMeas(msg->header.stamp.toSec(),posMeas); } int main (int argc, char **argv) { // ROS init stuff ros::init(argc, argv, "LSE_test"); ros::NodeHandle nh; string fileName = "Parameters.xml"; for(int i=0;i<argc;i++){ if (strcmp(argv[i],"-f")==0) { fileName = argv[i+1]; } } // LSE pManager_ = new LSE::Manager(fileName.c_str(),&legKin,&legKinJac); pManager_->resetEstimate(0); pManager_->setSamplingTime(0.0025); gotFirstMeas_ = false; // Publishers poseEst = nh.advertise<geometry_msgs::PoseStamped>("/LSE/filter/pose", 1000); velEst = nh.advertise<geometry_msgs::Vector3Stamped>("/LSE/filter/velocity", 1000); rrEst = nh.advertise<geometry_msgs::Vector3Stamped>("/LSE/filter/rotrate", 1000); // Subscribers ros::Subscriber imuSub = nh.subscribe("/MeasLoader/imuMeas", 1000, imuCallback); ros::Subscriber encSub = nh.subscribe("/MeasLoader/encMeas", 1000, encCallback); ros::Subscriber posSub = nh.subscribe("/MeasLoader/posMeas", 1000, posCallback); // ROS main loop ros::spin(); delete pManager_; cout << "Finished" << endl; return 0; } <file_sep>/README.md LSEnode ======= This ros-node represents a simple interface to the LSE library. It does by far not support the features of the library. In short: - Initialize the LSE-manager (while loading the Parameters.xml parameter-file) - Subscribes to the measurement topics (can be specified in the launch file) - Resets the filter state on the first measurement - Passes the measurement data further to the filter - Updates the filter if an encoder measurement is available - Publishes the estimated state to ros-topics (the launch file launches corresponding rxplots) INSTALLATION: - add directory to ROS - enter build folder - execute cmake: "cmake .." - compile: "make" DEPENDENCIES: - Standard library - ROS (including sensor_msgs and geometry_msgs) - Eigen3 - LSE library (if you did not use the install flag during compilation you will have to link the header files and the library by hand)
870d2f8ade636c762e7159405721c5d80934c53a
[ "Markdown", "CMake", "C++" ]
4
CMake
bloesch/LSEnode
4e50b44ebd9e35014c7af82b91a35677bcfd9bc9
12504fdbf977fc080b79b5f27c3af220cddc393c
refs/heads/master
<repo_name>fortega/CDEC-Reader<file_sep>/src/ssltest/SSLtest.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ssltest; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author felipe */ public class SSLtest { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try{ HttpsClient cl = new HttpsClient("www.cdec-sic.cl", 443); String t; t = cl.postURL("/redcdec/login.php", "Content-Type: application/x-www-form-urlencoded\n" + "Content-Length: 31\n\n" + "username=smarta&password=<PASSWORD>"); t = cl.getURL("/redcdec/explorer.php", null); Pattern links = Pattern.compile("<a href=\"\\?dir=[A-z0-9/]+\">"); Matcher m = links.matcher(t); while(m.find()){ System.out.println(m.group()); } //System.out.println(t); }catch(Exception ex){ System.out.println(ex.getMessage()); } } } <file_sep>/README.md CDEC-Reader ===========
327b25394238d7d6fce99a57430a0560df3f9966
[ "Markdown", "Java" ]
2
Java
fortega/CDEC-Reader
84d0b8ab7bd412fca89a94f5486acf64c0edbbbb
c6907342b954bb20d4153a3e3c31212bca4cce31
refs/heads/master
<repo_name>Sam0523/serial<file_sep>/docs/search/pages_0.js var searchData= [ ['serial_20library',['Serial Library',['../index.html',1,'']]] ]; <file_sep>/docs/search/enumvalues_1.js var searchData= [ ['fivebits',['fivebits',['../namespaceserial.html#a00b3281fa11cea770c0b0c8a106080f8af09eeaf7333d2feda0bd3d748d5e3123',1,'serial']]], ['flowcontrol_5fhardware',['flowcontrol_hardware',['../namespaceserial.html#a93ef57a314b4e562f9eded6c15d34351a84d411ac86fd25d659eef30aade04c43',1,'serial']]], ['flowcontrol_5fnone',['flowcontrol_none',['../namespaceserial.html#a93ef57a314b4e562f9eded6c15d34351a083bc02a6e8e7c6540a28654c0f95bb0',1,'serial']]], ['flowcontrol_5fsoftware',['flowcontrol_software',['../namespaceserial.html#a93ef57a314b4e562f9eded6c15d34351ab3390af5eee11740af5e09d71ad419a6',1,'serial']]] ]; <file_sep>/docs/search/all_f.js var searchData= [ ['throw',['THROW',['../serial_8h.html#a25cffc64bd967636d69d7c3c82af1030',1,'serial.h']]], ['timeout',['Timeout',['../structserial_1_1_timeout.html#a1a454b17f5d653b8e1b04b3ec2fead59',1,'serial::Timeout']]], ['timeout',['Timeout',['../structserial_1_1_timeout.html',1,'serial']]], ['timespec_5ffrom_5fms',['timespec_from_ms',['../unix_8cc.html#a89267c1a694b6017c261da0387291546',1,'unix.cc']]], ['tiocinq',['TIOCINQ',['../unix_8cc.html#ad6548c2f81bf6e2679166b22d24784f1',1,'unix.cc']]] ]; <file_sep>/docs/functions_func.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>serial: Data Fields - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">serial &#160;<span id="projectnumber">1.2.1</span> </div> <div id="projectbrief">Cross-platform, serial port library written in C++</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="classes.html"><span>Data&#160;Structure&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Data&#160;Fields</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="functions.html"><span>All</span></a></li> <li class="current"><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="#index_a"><span>a</span></a></li> <li><a href="#index_c"><span>c</span></a></li> <li><a href="#index_f"><span>f</span></a></li> <li><a href="#index_g"><span>g</span></a></li> <li><a href="#index_i"><span>i</span></a></li> <li><a href="#index_m"><span>m</span></a></li> <li><a href="#index_o"><span>o</span></a></li> <li><a href="#index_p"><span>p</span></a></li> <li><a href="#index_r"><span>r</span></a></li> <li><a href="#index_s"><span>s</span></a></li> <li><a href="#index_t"><span>t</span></a></li> <li><a href="#index_w"><span>w</span></a></li> <li class="current"><a href="#index_0x7e"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160; <h3><a class="anchor" id="index_a"></a>- a -</h3><ul> <li>available() : <a class="el" href="classserial_1_1_serial.html#afafe25b2f3bb0809550abdc72c51a234">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#aecd5e068c21b076bcf161f7bf7f415f5">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_c"></a>- c -</h3><ul> <li>close() : <a class="el" href="classserial_1_1_serial.html#afbe59407e718bc3d22ea4a67b304db6c">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a2608096ba0d17127b17484fc9481833a">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_f"></a>- f -</h3><ul> <li>flush() : <a class="el" href="classserial_1_1_serial.html#a63b7abf172cad25bfc998b3b1f98310f">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#afe873a403bcca3956437d95aa55c4d06">serial::serial::Serial::SerialImpl</a> </li> <li>flushInput() : <a class="el" href="classserial_1_1_serial.html#afa2c1f9114a37b7d140fc2292d1499b9">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a0b4ef99a4b44c3ef153ec7c4802ff194">serial::serial::Serial::SerialImpl</a> </li> <li>flushOutput() : <a class="el" href="classserial_1_1_serial.html#a256ee4bb93ab0e79d7a66b50f08dce53">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ac61932385ea2ce645192e1539349500b">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_g"></a>- g -</h3><ul> <li>getBaudrate() : <a class="el" href="classserial_1_1_serial.html#a9b57d6da619d53f58cddc3621c78c32b">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a3cdde221920c0e0abcaa6e78e26d4ab8">serial::serial::Serial::SerialImpl</a> </li> <li>getBytesize() : <a class="el" href="classserial_1_1_serial.html#a4fce90ef7a9a46525efa373a94a1bfbd">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a214fcecec01c905b498736c63ba878f5">serial::serial::Serial::SerialImpl</a> </li> <li>getCD() : <a class="el" href="classserial_1_1_serial.html#a9795a3e83e6745a14c64f657e68061fb">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a9d402e28513e22613658b31e13b76802">serial::serial::Serial::SerialImpl</a> </li> <li>getCTS() : <a class="el" href="classserial_1_1_serial.html#a809f048546c4c72b74e205139b97648c">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#afbfd566cd435f7881826fb0a2f74f746">serial::serial::Serial::SerialImpl</a> </li> <li>getDSR() : <a class="el" href="classserial_1_1_serial.html#a6b9a0c485e1fe599dbb5e9e15b1a65d6">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ae07e012e3630c51baf1b8c7c37dd79a5">serial::serial::Serial::SerialImpl</a> </li> <li>getErrorNumber() : <a class="el" href="classserial_1_1_i_o_exception.html#aa1c0af34b4547249b473e958699552d7">serial::IOException</a> </li> <li>getFlowcontrol() : <a class="el" href="classserial_1_1_serial.html#acdc6da48a5434b936b1db20f36caf41f">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a50ae8b1f13788251be2bb435f5fd0d6d">serial::serial::Serial::SerialImpl</a> </li> <li>getParity() : <a class="el" href="classserial_1_1_serial.html#a89d876e1d3f0afadb0d6c21b08ed8931">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#af2153a652da4e5a3d947d48b57c224bc">serial::serial::Serial::SerialImpl</a> </li> <li>getPort() : <a class="el" href="classserial_1_1_serial.html#ae95cd057e90258b1b3203ff8972a3567">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a103c5e852111741d1844e4d00cdefc45">serial::serial::Serial::SerialImpl</a> </li> <li>getRI() : <a class="el" href="classserial_1_1_serial.html#afb96e6968f040c4bff7576095f4ba6e7">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a4b9e1b75dce29e8ed4fa62b389510ae5">serial::serial::Serial::SerialImpl</a> </li> <li>getStopbits() : <a class="el" href="classserial_1_1_serial.html#a42887bb76243bf6bbb3f69ff60f9792e">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a0d40275505e189adf88a876b48f74949">serial::serial::Serial::SerialImpl</a> </li> <li>getTimeout() : <a class="el" href="classserial_1_1_serial.html#a765fccd0e53562773626fb39bb2efcb6">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a7fc6132d336cdf4d999fd24d8dfa2dab">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_i"></a>- i -</h3><ul> <li>IOException() : <a class="el" href="classserial_1_1_i_o_exception.html#acb2f2cf7a5cc8090945f6cbfcef3ef1e">serial::IOException</a> </li> <li>isOpen() : <a class="el" href="classserial_1_1_serial.html#af9895af496189f7f0aba7c097f5fa9c1">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a83d5b92202f83014261674b896817beb">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_m"></a>- m -</h3><ul> <li>max() : <a class="el" href="structserial_1_1_timeout.html#adc68e33d2f94bfa33ba1062c363b9151">serial::Timeout</a> </li> <li>MillisecondTimer() : <a class="el" href="classserial_1_1_millisecond_timer.html#aac5a60ab2fd6cbba430ba89eceffab86">serial::MillisecondTimer</a> </li> </ul> <h3><a class="anchor" id="index_o"></a>- o -</h3><ul> <li>open() : <a class="el" href="classserial_1_1_serial.html#af3644ed1a9d899b70e9d63bb9b808d62">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a279801879f609e1845e3e730f5651aa2">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_p"></a>- p -</h3><ul> <li>PortNotOpenedException() : <a class="el" href="classserial_1_1_port_not_opened_exception.html#acd2213fae864534eae6a580f74c5ab1b">serial::PortNotOpenedException</a> </li> </ul> <h3><a class="anchor" id="index_r"></a>- r -</h3><ul> <li>read() : <a class="el" href="classserial_1_1_serial.html#a0261dbfb9361784ecb3eee98b85fa103">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ada61c83884f0f6350874fc32e640cbac">serial::serial::Serial::SerialImpl</a> </li> <li>readline() : <a class="el" href="classserial_1_1_serial.html#a010b18ec545dfe1a7bb1c95be4bdaa54">serial::Serial</a> </li> <li>readlines() : <a class="el" href="classserial_1_1_serial.html#a99f77b9bbdc128b6704cc59db77686c5">serial::Serial</a> </li> <li>readLock() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a284eeedc3dd686ecef0fdcfd83bebc54">serial::serial::Serial::SerialImpl</a> </li> <li>readUnlock() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ab6533e884ba609a1dd6a88b7964d8b52">serial::serial::Serial::SerialImpl</a> </li> <li>reconfigurePort() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ad006a2392150daddfa43ae288259c07d">serial::serial::Serial::SerialImpl</a> </li> <li>remaining() : <a class="el" href="classserial_1_1_millisecond_timer.html#a3786e2c6d8614adff0da39e1d1a2b0e3">serial::MillisecondTimer</a> </li> </ul> <h3><a class="anchor" id="index_s"></a>- s -</h3><ul> <li>ScopedReadLock() : <a class="el" href="class_serial_1_1_scoped_read_lock.html#a54f59663807d8adfe6db712ee6103503">serial::Serial::ScopedReadLock</a> </li> <li>ScopedWriteLock() : <a class="el" href="class_serial_1_1_scoped_write_lock.html#a662173968431aee3d6f204c354b20225">serial::Serial::ScopedWriteLock</a> </li> <li>sendBreak() : <a class="el" href="classserial_1_1_serial.html#ade90ff8f03525ea6d7b702fcd0f336de">serial::Serial</a> , <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a6a1abcf6f4b94c7f3d7753c3f2dab91a">serial::serial::Serial::SerialImpl</a> </li> <li>Serial() : <a class="el" href="classserial_1_1_serial.html#aecbc4cc1723143805ae5a4aa79ba9332">serial::Serial</a> </li> <li>SerialException() : <a class="el" href="classserial_1_1_serial_exception.html#ab761c0c6e5350bb30f2be40dd6073145">serial::SerialException</a> </li> <li>SerialImpl() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a80885778652ea3c7f7db39ec3f20310c">serial::serial::Serial::SerialImpl</a> </li> <li>setBaudrate() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#ad57c0c497d487c2f2115168f60eda146">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ad4f7e9edff11b464199e94a43dfd19bf">serial::Serial</a> </li> <li>setBreak() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a4e439ed9ab4e38fb64bba2d49b814179">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#a2a27912b1ca5cdad4a4aba7b9ddbc206">serial::Serial</a> </li> <li>setBytesize() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#aa788845b977360851810f07a07b340a7">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#adba430fd704f6898a5a1d99fd39a94fa">serial::Serial</a> </li> <li>setDTR() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a94cdd2aad19377a0ec435bb6241b98a8">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ac9b0bbf613a5fe68f05d1d40181a1bb3">serial::Serial</a> </li> <li>setFlowcontrol() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#abe20c54b814d70e1e0deaa8d3472babe">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ade41650d6bfe91b6432e5a0a60c03969">serial::Serial</a> </li> <li>setParity() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a7859629014393110fc76a55f1d956c3f">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#a1e1896aa59ec35ac5bd263b87614ef01">serial::Serial</a> </li> <li>setPort() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#aa3b4c490f3246a506dd29135553ecd64">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#acecb0a5102ae0c944fe4b78e4adf839a">serial::Serial</a> </li> <li>setRTS() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a7faf4ef9a0f1b13c9155a4cae1e0ace9">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ab43ddc05e5d69ff2778f698aa7062370">serial::Serial</a> </li> <li>setStopbits() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a23f31163c4c1b4aa488a7c7204ddec17">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ab72284b5aab723b81013fb560bd6acc5">serial::Serial</a> </li> <li>setTimeout() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a22cc09f7e828c54631392dc69e3737d3">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#a4fc63af4b800a9f9e757414f38f3e8b3">serial::Serial</a> </li> <li>simpleTimeout() : <a class="el" href="structserial_1_1_timeout.html#aa4fbd72e16f47c9aea9fb3c32ca17828">serial::Timeout</a> </li> </ul> <h3><a class="anchor" id="index_t"></a>- t -</h3><ul> <li>Timeout() : <a class="el" href="structserial_1_1_timeout.html#a1a454b17f5d653b8e1b04b3ec2fead59">serial::Timeout</a> </li> </ul> <h3><a class="anchor" id="index_w"></a>- w -</h3><ul> <li>waitByteTimes() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a039703d806b1c8db071da9a04cf63446">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#a318262c05074a9da15d410f8af29c15c">serial::Serial</a> </li> <li>waitForChange() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a09f1dcb8e32cb64188daaf8ac0d40215">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#a419dc984258956a5adb41fb8c86f5449">serial::Serial</a> </li> <li>waitReadable() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a4722f7080b15d12a4e00672858c5f0e8">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#ad6e395bfe91718b66f6695c10ee90e5b">serial::Serial</a> </li> <li>what() : <a class="el" href="classserial_1_1_i_o_exception.html#a5151f78cf0309db2c79f3dc4c779c774">serial::IOException</a> , <a class="el" href="classserial_1_1_port_not_opened_exception.html#a314c997ecfe3990c4af147b247e8d9ce">serial::PortNotOpenedException</a> , <a class="el" href="classserial_1_1_serial_exception.html#a22a130c3b3785373edf7e1063d3ffd39">serial::SerialException</a> </li> <li>write() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a89b50df2562176fd250413833d636d0a">serial::serial::Serial::SerialImpl</a> , <a class="el" href="classserial_1_1_serial.html#aa020880cdff3a370ddc574f594379c3c">serial::Serial</a> </li> <li>writeLock() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a2905e50e9082a757bfafc03356e318ed">serial::serial::Serial::SerialImpl</a> </li> <li>writeUnlock() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#adaec2b322f0b0793929da24f5bf09949">serial::serial::Serial::SerialImpl</a> </li> </ul> <h3><a class="anchor" id="index_0x7e"></a>- ~ -</h3><ul> <li>~IOException() : <a class="el" href="classserial_1_1_i_o_exception.html#a026ae2e6abc57c6069915f0f8c701390">serial::IOException</a> </li> <li>~PortNotOpenedException() : <a class="el" href="classserial_1_1_port_not_opened_exception.html#a1d7499214c9f43ed89676f2c90dd72a6">serial::PortNotOpenedException</a> </li> <li>~ScopedReadLock() : <a class="el" href="class_serial_1_1_scoped_read_lock.html#a5c061909b95231cec776c40094c878b4">serial::Serial::ScopedReadLock</a> </li> <li>~ScopedWriteLock() : <a class="el" href="class_serial_1_1_scoped_write_lock.html#aebeef5b2d16f409b60094cfac092ada2">serial::Serial::ScopedWriteLock</a> </li> <li>~Serial() : <a class="el" href="classserial_1_1_serial.html#a5b32c394c0ff923a4ef1c13cfb20a6ba">serial::Serial</a> </li> <li>~SerialException() : <a class="el" href="classserial_1_1_serial_exception.html#a8504adb442f224ec2798e4bd33115fe3">serial::SerialException</a> </li> <li>~SerialImpl() : <a class="el" href="classserial_1_1serial_1_1_serial_1_1_serial_impl.html#af9f0a13782d7870cf66a49001dcc64e7">serial::serial::Serial::SerialImpl</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html> <file_sep>/docs/search/enumvalues_3.js var searchData= [ ['sevenbits',['sevenbits',['../namespaceserial.html#a00b3281fa11cea770c0b0c8a106080f8a7cf0a3607e326ff6736941008ea8174d',1,'serial']]], ['sixbits',['sixbits',['../namespaceserial.html#a00b3281fa11cea770c0b0c8a106080f8a608eb93b80fe8531d626b4e588c5bc8b',1,'serial']]], ['stopbits_5fone',['stopbits_one',['../namespaceserial.html#af5b116611d6628a3aa8f788fdc09f469ab70806555a14cb43e5cc43f6f3d01157',1,'serial']]], ['stopbits_5fone_5fpoint_5ffive',['stopbits_one_point_five',['../namespaceserial.html#af5b116611d6628a3aa8f788fdc09f469abb25fb831662d361d99cf12fb0da45ec',1,'serial']]], ['stopbits_5ftwo',['stopbits_two',['../namespaceserial.html#af5b116611d6628a3aa8f788fdc09f469ae0b1b8af1ece65afeacbe9fff198fa47',1,'serial']]] ]; <file_sep>/docs/search/functions_8.js var searchData= [ ['open',['open',['../classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a279801879f609e1845e3e730f5651aa2',1,'serial::serial::Serial::SerialImpl::open()'],['../classserial_1_1_serial.html#af3644ed1a9d899b70e9d63bb9b808d62',1,'serial::Serial::open()']]] ]; <file_sep>/docs/search/functions_0.js var searchData= [ ['available',['available',['../classserial_1_1serial_1_1_serial_1_1_serial_impl.html#aecd5e068c21b076bcf161f7bf7f415f5',1,'serial::serial::Serial::SerialImpl::available()'],['../classserial_1_1_serial.html#afafe25b2f3bb0809550abdc72c51a234',1,'serial::Serial::available()']]] ]; <file_sep>/docs/search/variables_2.js var searchData= [ ['inter_5fbyte_5ftimeout',['inter_byte_timeout',['../structserial_1_1_timeout.html#ada15f2a0ae478cbb62ef79d1633b2b81',1,'serial::Timeout']]] ]; <file_sep>/docs/search/namespaces_0.js var searchData= [ ['serial',['serial',['../namespaceserial.html',1,'']]], ['serial',['Serial',['../namespaceserial_1_1serial_1_1_serial.html',1,'serial::serial']]], ['serial',['serial',['../namespaceserial_1_1serial.html',1,'serial']]] ]; <file_sep>/docs/search/all_2.js var searchData= [ ['close',['close',['../classserial_1_1serial_1_1_serial_1_1_serial_impl.html#a2608096ba0d17127b17484fc9481833a',1,'serial::serial::Serial::SerialImpl::close()'],['../classserial_1_1_serial.html#afbe59407e718bc3d22ea4a67b304db6c',1,'serial::Serial::close()']]] ]; <file_sep>/docs/search/classes_2.js var searchData= [ ['portinfo',['PortInfo',['../structserial_1_1_port_info.html',1,'serial']]], ['portnotopenedexception',['PortNotOpenedException',['../classserial_1_1_port_not_opened_exception.html',1,'serial']]] ]; <file_sep>/docs/search/files_1.js var searchData= [ ['serial_2ecc',['serial.cc',['../serial_8cc.html',1,'']]], ['serial_2edox',['serial.dox',['../serial_8dox.html',1,'']]], ['serial_2eh',['serial.h',['../serial_8h.html',1,'']]], ['serial_5fexample_2ecc',['serial_example.cc',['../serial__example_8cc.html',1,'']]] ]; <file_sep>/docs/search/all_11.js var searchData= [ ['v8stdint_2eh',['v8stdint.h',['../v8stdint_8h.html',1,'']]] ]; <file_sep>/docs/search/files_0.js var searchData= [ ['list_5fports_5flinux_2ecc',['list_ports_linux.cc',['../list__ports__linux_8cc.html',1,'']]], ['list_5fports_5fosx_2ecc',['list_ports_osx.cc',['../list__ports__osx_8cc.html',1,'']]], ['list_5fports_5fwin_2ecc',['list_ports_win.cc',['../list__ports__win_8cc.html',1,'']]] ]; <file_sep>/docs/search/files_4.js var searchData= [ ['win_2ecc',['win.cc',['../win_8cc.html',1,'']]], ['win_2eh',['win.h',['../win_8h.html',1,'']]] ]; <file_sep>/docs/search/functions_c.js var searchData= [ ['timeout',['Timeout',['../structserial_1_1_timeout.html#a1a454b17f5d653b8e1b04b3ec2fead59',1,'serial::Timeout']]], ['timespec_5ffrom_5fms',['timespec_from_ms',['../unix_8cc.html#a89267c1a694b6017c261da0387291546',1,'unix.cc']]] ]; <file_sep>/docs/search/variables_4.js var searchData= [ ['read_5ftimeout_5fconstant',['read_timeout_constant',['../structserial_1_1_timeout.html#a099244649dec66b6e0548480edeb2b9f',1,'serial::Timeout']]], ['read_5ftimeout_5fmultiplier',['read_timeout_multiplier',['../structserial_1_1_timeout.html#a64412753eb2edf1621716dd9f1a4e71e',1,'serial::Timeout']]] ]; <file_sep>/docs/search/all_7.js var searchData= [ ['hardware_5fid',['hardware_id',['../structserial_1_1_port_info.html#a7d55368e1a4e6ccc9da6f4d339524837',1,'serial::PortInfo']]] ]; <file_sep>/docs/search/defines_0.js var searchData= [ ['throw',['THROW',['../serial_8h.html#a25cffc64bd967636d69d7c3c82af1030',1,'serial.h']]], ['tiocinq',['TIOCINQ',['../unix_8cc.html#ad6548c2f81bf6e2679166b22d24784f1',1,'unix.cc']]] ]; <file_sep>/docs/search/functions_7.js var searchData= [ ['main',['main',['../serial__example_8cc.html#a3c04138a5bfe5d72780bb7e82a18e627',1,'serial_example.cc']]], ['max',['max',['../structserial_1_1_timeout.html#adc68e33d2f94bfa33ba1062c363b9151',1,'serial::Timeout']]], ['millisecondtimer',['MillisecondTimer',['../classserial_1_1_millisecond_timer.html#aac5a60ab2fd6cbba430ba89eceffab86',1,'serial::MillisecondTimer']]], ['my_5fsleep',['my_sleep',['../serial__example_8cc.html#a89b7c9d8c710b057346cc9ac52ae3734',1,'serial_example.cc']]] ]; <file_sep>/docs/search/classes_3.js var searchData= [ ['scopedreadlock',['ScopedReadLock',['../class_serial_1_1_scoped_read_lock.html',1,'serial::Serial']]], ['scopedwritelock',['ScopedWriteLock',['../class_serial_1_1_scoped_write_lock.html',1,'serial::Serial']]], ['serial',['Serial',['../classserial_1_1_serial.html',1,'serial']]], ['serialexception',['SerialException',['../classserial_1_1_serial_exception.html',1,'serial']]], ['serialimpl',['SerialImpl',['../classserial_1_1serial_1_1_serial_1_1_serial_impl.html',1,'serial::serial::Serial']]] ]; <file_sep>/docs/search/all_4.js var searchData= [ ['eightbits',['eightbits',['../namespaceserial.html#a00b3281fa11cea770c0b0c8a106080f8a47f14d952cf9bed6c3f7ae5985161990',1,'serial']]], ['enumerate_5fports',['enumerate_ports',['../serial__example_8cc.html#a996e0d351ea6c804947e9533581765ea',1,'serial_example.cc']]] ];
c7163a032ca6425ac456733aef87da65ff1f4330
[ "JavaScript", "HTML" ]
22
JavaScript
Sam0523/serial
8181d1ebc84bdaee57c502e253eb36278d447324
f91eb018c0f93c8e19ae0307a463a3e65c43eabf
refs/heads/master
<file_sep>rootProject.name = 'meteorddp' include ':app' <file_sep># Simple Todo List React Native client 1. Install dependencies: ``` npm install ``` 2. Start: ``` react-native run-ios or react-native run-android ``` <file_sep># Simple Todo List React Native * **simple-todos-react** directory is Meteor server. * **reactnativeddp** directory is React Native client. <file_sep>// import react modules import React, { Component } from 'react'; // import { View } from 'react-native'; // import react native meteor import Meteor, { createContainer, MeteorListView } from 'react-native-meteor'; // import native-base import { Container, Header, Title, Content, List, ListItem, Text, Input, Spinner } from 'native-base'; // connect to meteor websocket server Meteor.connect('ws://localhost:3000/websocket'); class App extends Component { constructor(props) { super(); // bind onHandleSubmit this.onHandleSubmit = this.onHandleSubmit.bind(this); // current text input state this.state = { text: '' }; } // submit new task operation onHandleSubmit() { // meteor call Meteor.call('tasks.insert', this.state.text, function(err) { console.log(err); }); // clear text input return this.setState({text: ''}) } // render tasks list renderRow(task) { return ( <List> <ListItem> <Text>{task.text}</Text> </ListItem> </List> ); } // render view render() { // check subscription is ready? const tasksReady = this.props.tasksReady; return ( <Container> <Header> <Title>Tasks List</Title> </Header> { !tasksReady ? <Content> <Spinner color="red" /> </Content> : <Content> <List> <ListItem> <Input onSubmitEditing={this.onHandleSubmit} onChangeText={(text) => this.setState({text})} value={this.state.text} placeholder="Enter a new task" /> </ListItem> </List> <MeteorListView collection="tasks" options={{sort: {createdAt: 1}}} renderRow={this.renderRow} enableEmptySections={true} /> </Content> } </Container> ); } } // create container export default createContainer(params=>{ // subscribe tasks collection const handle = Meteor.subscribe('tasks'); // tasksReady props return { tasksReady: handle.ready(), }; }, App)
93043d9644f9074f24527d689379b1733d173248
[ "Markdown", "JavaScript", "Gradle" ]
4
Gradle
Akim95/meteor-react-native-sample
2aaa633c6df82f5858b7ce4458db226ba1b6df83
eb49c9cb9d3b1555c7cdcd461e8d60ac39c537b1
refs/heads/master
<repo_name>Coder-B/terraform-will-sag-acl<file_sep>/README.md # terraform-will-sag-acl This terraform module supports to create access control list for SAG (smart api gateway). These type of resource is supported: - [alicloud_sag_acl](https://www.terraform.io/docs/providers/alicloud/r/sag_acl.html) - [alicloud_sag_acl_rule](https://www.terraform.io/docs/providers/alicloud/r/sag_acl_rule.html) ## Inputs | Name | Description | Type | Default | Required | |------|-------------|:----:|:-----:|:-----:| |name|The name of the ACL instance| string| "" | yes| |description | The description of the ACL rule. It must be 1 to 512 characters in length|string|"a new acl rule"|no| |policy | The policy used by the ACL rule. Valid values: accept, drop|string|""|yes| |ip_protocol | The protocol used by the ACL rule. The value is not case sensitive|string|""|yes| |direction | The direction of the ACL rule. Valid values: in, out|string|""|yes| |source_cidr | The source address. It is an IPv4 address range in the CIDR format. Default value: 0.0.0.0/0|string|""|yes| |source_port_range | The range of the source port. Valid value: 80/80|string|""|yes| |dest_cidr | The destination address. It is an IPv4 address range in CIDR format. Default value: 0.0.0.0/0|string|""|yes| |dest_port_range | The range of the destination port. Valid value: 80/80|string|""|yes| |priority | The priority of the ACL rule. Value range: 1 to 100|string|""|no| ## Outputs | Name | Description | |------|-------------| |acl_instance_id|The ID of the ACL instance | |acl_rule_id|The ID of the ACL rule |<file_sep>/terratest/terraform_test.go package test import ( "strings" "testing" "github.com/gruntwork-io/terratest/modules/terraform" "github.com/stretchr/testify/assert" ) // An example of how to test the simple Terraform module in examples/terraform-basic-example using Terratest. func TestTerraformBasicExampleNew(t *testing.T) { terraformOptions := &terraform.Options { // The path to where your Terraform code is located TerraformDir: "../", // Variables to pass to our Terraform code using -var options Vars: map[string]interface{}{ "name": "testSAG", "description" = "tf-testSagAclRule", "policy" = "accept", "ip_protocol" = "ALL", "direction" = "in", "source_cidr" = "10.10.1.0/24", "source_port_range" = "-1/-1", "dest_cidr" = "192.168.1.0/24", "dest_port_range" = "-1/-1", "priority" = "1", }, // Disable colors in Terraform commands so its easier to parse stdout/stderr NoColor: true, } // At the end of the test, run `terraform destroy` to clean up any resources that were created defer terraform.Destroy(t, terraformOptions) // This will run `terraform init` and `terraform apply` and fail the test if there are any errors terraform.InitAndApply(t, terraformOptions) // Validate your code works as expected validateServerIsWorking(t, terraformOptions) aclInstanceId := terraform.Output(t, terraformOptions, "acl_instance_id") aclRuleId := terraform.Output(t, terraformOptions, "acl_rule_id") }<file_sep>/modules/acl/README.md # alicloud_sag_acl ## Inputs | Name | Description | Type | Default | Required | |------|-------------|:----:|:-----:|:-----:| |name|The name of the ACL instance| string| "" | yes| ## Outputs | Name | Description | |------|-------------| |id|The ID of the ACL |
63d553821def44d45e320c2bf979f085ef34cc49
[ "Markdown", "Go" ]
3
Markdown
Coder-B/terraform-will-sag-acl
100b0bc518edd2fc7911e117e6a5f0e6080f1222
afe26e9b0a3b2b2bc3b5022654ccf6141587248c
refs/heads/master
<file_sep>package talgo //Collection a type the satisfies Collection interface can be used by the routines of this package type Collection interface { //Len is the numbre of elements of the collection Len() int } //Function defines a function that applies to the ith elements of a collection type Function func(i int) //Predicate defines a predicate that applies to the ith elements of a collection type Predicate func(i int) bool //Selector defines a selection function, a selector return i value or j value type Selector func(i, j int) int //Negate negates a predicate func Negate(p Predicate) Predicate { return func(i int) bool { return !p(i) } } //Or create a new predicte that is the 'or' of predicate p1 and p2 func Or(p1 Predicate, p2 Predicate) Predicate { return func(i int) bool { return p1(i) || p2(i) } } //And create a new predicte that is the 'and' of predicate p1 and p2 func And(p1 Predicate, p2 Predicate) Predicate { return func(i int) bool { return p1(i) && p2(i) } } //Xor create a new predicte that is the 'xor' of predicate p1 and p2 func Xor(p1 Predicate, p2 Predicate) Predicate { return func(i int) bool { return p1(i) != p2(i) } } //ForEach apply m to each element of s func ForEach(c Collection, f Function) { for i := 0; i < c.Len(); i++ { f(i) } } //ReverseForEach apply m to each element of s in reverse order func ReverseForEach(c Collection, f Function) { for i := c.Len() - 1; i >= 0; i-- { f(i) } } //Select select best element against selector s func Select(c Collection, s Selector) int { selected := 0 for i := 1; i < c.Len(); i++ { selected = s(selected, i) } return selected } //FindFirst find the first element of a series that satisfies predicate p func FindFirst(c Collection, p Predicate) int { for i := 0; i < c.Len(); i++ { if p(i) { return i } } return -1 } //FindLast find the last element of a series that satisfies predicate p func FindLast(c Collection, p Predicate) int { for i := c.Len() - 1; i >= 0; i-- { if p(i) { return i } } return -1 } //FindAll find all the elements of a series that satisfies predicate p func FindAll(c Collection, p Predicate) []int { indexes := []int{} for i := 0; i < c.Len(); i++ { if p(i) { indexes = append(indexes, i) } } return indexes } //CountItems counts number of items that satisfies predicate p func CountItems(c Collection, p Predicate) int { cpt := 0 for i := 0; i < c.Len(); i++ { if p(i) { cpt++ } } return cpt } //Any checks if at least one element of the serie satisfies predicate p func Any(c Collection, p Predicate) bool { return FindFirst(c, p) >= 0 } //None checks if at none element of the serie satisfies predicate p func None(c Collection, p Predicate) bool { return !Any(c, p) } //All checks if all elements of the serie satisfy predicate p func All(c Collection, p Predicate) bool { for i := 0; i < c.Len(); i++ { if !p(i) { return false } } return true } <file_sep>package talgo_test import ( "sort" "testing" "github.com/SebastienDorgan/talgo" "github.com/stretchr/testify/assert" ) func GreaterThan(s sort.IntSlice, value int) talgo.Predicate { return func(i int) bool { return s[i] >= value } } type BankAccount struct { ID string Balance int64 } type BankAccounts []BankAccount func (b BankAccounts) Len() int { return len(b) } func Test(t *testing.T) { s := sort.IntSlice{1, 2, 4} //Map Incr over s talgo.ForEach(s, func(i int) { s[i] += 3 }) assert.Equal(t, 4, s[0]) assert.Equal(t, 5, s[1]) assert.Equal(t, 7, s[2]) //Find first element greater or equal to 5 r := talgo.FindFirst(s, GreaterThan(s, 5)) assert.Equal(t, 1, r) //Find last element greater or equal to 5 r = talgo.FindLast(s, func(i int) bool { return s[i] >= 5 }) assert.Equal(t, 2, r) //Find last element greater or equal to 5 l := talgo.FindAll(s, GreaterThan(s, 5)) assert.Equal(t, 1, l[0]) assert.Equal(t, 2, l[1]) //Checks if at least one element is greater or equal to 5 b := talgo.Any(s, GreaterThan(s, 5)) assert.True(t, b) //Checks if at least one element is greater or equal to 0 b = talgo.Any(s, talgo.Negate(GreaterThan(s, 0))) assert.False(t, b) //Checks if all elements are greater or equal to 5 b = talgo.All(s, GreaterThan(s, 5)) assert.False(t, b) //Reduce by adding all elements of the list to 3 sum := 3 talgo.ForEach(s, func(i int) { sum += s[i] }) assert.Equal(t, 19, sum) //Multiply by 2 all elements of the list sf := sort.Float64Slice{2.5, 1.5, 3.5} talgo.ForEach(sf, func(i int) { sf[i] *= 2. }) assert.Equal(t, 5., sf[0]) assert.Equal(t, 3., sf[1]) assert.Equal(t, 7., sf[2]) //Find index of the min value min := func(i, j int) int { if sf[i] >= sf[j] { return j } else { return i } } minargs := talgo.Select(sf, min) assert.Equal(t, 1, minargs) //Find index of the max value max := func(i, j int) int { if sf[i] <= sf[j] { return j } else { return i } } maxargs := talgo.Select(sf, max) assert.Equal(t, 2, maxargs) //Separate odd and even elements ints := sort.IntSlice{1, 2, 3, 4, 5, 6, 7, 8, 9} even := []int{} odd := []int{} talgo.ForEach(ints, func(i int) { if ints[i]%2 == 0 { even = append(even, ints[i]) } else { odd = append(odd, ints[i]) } }) //Find bank accounts in deficit bankAccounts := BankAccounts{ BankAccount{ID: "0", Balance: 1500}, BankAccount{ID: "1", Balance: -500}, BankAccount{ID: "2", Balance: 0}, } accountInDeficit := []string{} talgo.ForEach(bankAccounts, func(i int) { if bankAccounts[i].Balance < 0 { accountInDeficit = append(accountInDeficit, bankAccounts[i].ID) } }) assert.Equal(t, "1", accountInDeficit[0]) }
bfcb39d56fad55fb7de459ba83273cd13922fa13
[ "Go" ]
2
Go
SebastienDorgan/tfunc
023a635cd5b266698de1718a499df52d2ee54814
0714746b9c10afd4140e983ec67ad15ac5f91e40
refs/heads/master
<file_sep># Bayesian Gaussian Processes ## This Github Repository This particular Github repo, *bayesianGPs* is a rough draft of putting together some software that will do the stuff in my dissertation, *A Bayesian Approach to Prediction adn Variable Selection Using Non-Stationary Gaussian Processes*. This one will use Stan, a Bayeian programming language/software. I might also duplicate in R using Rcpp what I did when I originally wrote this software in MATLAB, but that'll probably only be for random practice. I'll probably build up from the most basic stationary model and work towards the stuff in my dissertation. Eventually, I'll make an actual R package (Python, too?) in a different repo. ## A couple different Formulations The marginal likelihood formulation is faster for Gaussian data, but can't be extended to non-Gaussian data. It seems like it does not need a nugget, as the residual error basically does the job of keeping the matrix positive definite. The latent variable formulation is slower for Gaussian data, but can be extended to non-Gaussian data. It needs a nugget for positive definiteness of the covariance matrix. ## Setup We have observed data, \mathbf{Y}. Conditional on model parameters, $\Lambda$, the data are treated as a realization of a Gaussian process, Y(x). $$ Y(\mathbf(x)) | \Lambda \sim GP\left( \mu, C\left(\cdot, \cdot \right) ) \right)$$ Let \mathbf{R} be an $n \times n$ correlation matrix for the observed data: ## It turns out this README file doesn't support LaTeX. See bayesianGPs.html and/or bayesianGPs.pdf for more info. <file_sep>rm(list = ls()) cat("\014") library(plyr) library(tidyverse) library(stringr) library(rstan) library(reshape2) library(bayesplot) rstan_options(auto_write = TRUE) numCores <- 4 # Find the number of cores on your machine options(mc.cores = numCores) # Then use one less than that for MCMC sampling sim_data_model <- stan_model(file = 'anyD/stanCode/generateKrigingDataRhoParam.stan') mu <- 5 rho <- c(0.15, .40, .60) sigma <- 0.5 sigmaEps <- sqrt(0.1) d <- length(rho) dat_list <- list(n = 300, D = d, mu = mu, sigma = sigma, rho = array(rho, dim = d), sigmaEps = sigmaEps) set <- sample(1:dat_list$n, size = 30, replace = F) # draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list, # seed = 363360090) draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list) samps <- rstan::extract(draw) if(d == 2){ plt_df = with(samps,data.frame(x1 = X[ , , 1], x2 = X[ , , 2], y = y[1,], f = f[1,])) ggplot(data = plt_df[-set,], aes(x = x1, y = x2)) + geom_point(aes(colour = y)) + geom_point(data = plt_df[set,], color = "red", size = 2) + theme_bw() + theme(legend.position="bottom") + scale_colour_gradient(low = "blue",high = "white") + xlab('x1') + ylab('x2') + ggtitle(str_c('N = ',length(set),' from rho_1 = ', rho[1], ', rho_2 = ', rho[2], ', sigma = ', sigma, ', \nsigmaEps = ', round(sigmaEps,2))) }else if(d == 1){ plt_df = with(samps,data.frame(x = X[ , , 1], y = y[1,], f = f[1,])) ggplot(data = plt_df[set,], aes(x=x, y=y)) + geom_point(aes(colour = 'Realized data')) + geom_line(data = plt_df, aes(x = x, y = f, colour = 'Latent mean function')) + theme_bw() + theme(legend.position="bottom") + scale_color_manual(name = '', values = c('Realized data'='black','Latent mean function'='red')) + xlab('X') + ylab('y') + ggtitle(str_c('N = ',length(set),' from rho = ', rho, ', sigma = ', sigma, ', \nsigmaEps = ', round(sigmaEps,2))) }else{ } stan_data <- list(n = length(set), nPred = dat_list$n - length(set), x = matrix(samps$X[,set,], ncol = d), y = samps$y[,set], d = length(rho), xPred = matrix(samps$X[,-set,], ncol = d), fPred = samps$f[1,-set]) comp_gp_mod_ML <- stan_model(file = 'anyD/stanCode/krigingRhoParamML.stan') gp_mod_ML <- sampling(comp_gp_mod_ML, data = stan_data, cores = 1, chains = 1, iter = 100, control = list(adapt_delta = 0.999)) parsToMonitor <- c("mu", "rho", "sigma", "sigmaEps") print(gp_mod_ML, pars = parsToMonitor) samps_gp_mod_ML <- extract(gp_mod_ML) post_pred <- data.frame(x = stan_data$xPred, pred_mu = colMeans(samps_gp_mod_ML$fPred)) MSPE <- mean((samps$f[1,-set] - post_pred$pred_mu)^2) plt_df_rt = data.frame(x = stan_data$xPred, f = t(samps_gp_mod_ML$fPred)) plt_df_rt_melt = melt(plt_df_rt,id.vars = 'x') p <- ggplot(data = plt_df[set,], aes(x=x, y=y)) + geom_line(data = plt_df_rt_melt, aes(x = x, y = value, group = variable, color = "Posterior draws")) + geom_point(aes(colour = 'Realized data')) + geom_line(data = plt_df, aes(x = x, y = f, colour = 'Latent mean function')) + geom_line(data = post_pred, aes(x = x, y = pred_mu, colour = 'Posterior mean function')) + theme_bw() + theme(legend.position="bottom") + scale_color_manual(name = '', values = c('Realized data'='black', 'Latent mean function'='red', 'Posterior draws' = 'blue', 'Posterior mean function' = 'green')) + xlab('X') + ylab('y') + ggtitle(paste0('N = ',length(set),' from rho = ', rho, ', sigma = ', sigma, ', \nsigmaEps = ', round(sigmaEps,2))) p ppc_interval_df <- function(yrep, y) { q_95 <- apply(yrep,2,quantile,0.95) q_75 <- apply(yrep,2,quantile,0.75) q_50 <- apply(yrep,2,median) q_25 <- apply(yrep,2,quantile,0.25) q_05 <- apply(yrep,2,quantile,0.05) mu <- colMeans(yrep) df_post_pred <- data.frame(y_obs = y, q_95 = q_95, q_75 = q_75, q_50 = q_50, q_25 = q_25, q_05 = q_05, mu = mu) return(df_post_pred) } ppc_interval_norm_df <- function(means, sds, y) { q_95 <- qnorm(0.95,mean = means, sd = sds) q_75 <- qnorm(0.75,mean = means, sd = sds) q_50 <- qnorm(0.5,mean = means, sd = sds) q_25 <- qnorm(0.25,mean = means, sd = sds) q_05 <- qnorm(0.05,mean = means, sd = sds) df_post_pred <- data.frame(y_obs = y, q_95 = q_95, q_75 = q_75, q_50 = q_50, q_25 = q_25, q_05 = q_05, mu = means) return(df_post_pred) } interval_cover <- function(upper, lower, elements) { return(mean(upper >= elements & lower <= elements)) } ppc_full_bayes <- ppc_interval_df(samps_gp_mod_ML$yPred, samps$y[1,-set]) coverage90 <- interval_cover(upper = ppc_full_bayes$q_95, lower = ppc_full_bayes$q_05, elements = ppc_full_bayes$y_obs) coverage50 <- interval_cover(upper = ppc_full_bayes$q_75, lower = ppc_full_bayes$q_25, elements = ppc_full_bayes$y_obs) print(c(coverage90, coverage50)) post <- as.data.frame(gp_mod_ML) tmp <- select(post, mu, "rho[1]", sigma, sigmaEps) bayesplot::mcmc_recover_hist(tmp, true = c(mu, rho[1], sigma, sigmaEps), facet_args = list(ncol = 1)) tmp <- select(post, mu, "rho[1]", "rho[2]", sigma, sigmaEps) bayesplot::mcmc_recover_hist(tmp, true = c(mu, rho[1], rho[2], sigma, sigmaEps), facet_args = list(ncol = 1)) tmp <- select(post, mu, "rho[1]", "rho[2]", "rho[3]", sigma, sigmaEps) bayesplot::mcmc_recover_hist(tmp, true = c(mu, rho[1], rho[2], rho[3], sigma, sigmaEps), facet_args = list(ncol = 1)) ppc_full_bayes$x <- samps$X[1,-set, 1] ggplot(data = ppc_full_bayes, aes(x = x, y = y_obs)) + geom_ribbon(aes(ymax = q_95, ymin = q_05,alpha=0.5, colour = '90% predictive interval')) + geom_point(data = plt_df[set,], aes(x = x, y = y, colour='Observed data')) + geom_point(data = plt_df[-set,], aes(x = x, y = y, colour='Out-of-sample data')) + theme(legend.position="bottom") + geom_line(data = ppc_full_bayes, aes(x = x, y = mu, colour = 'Posterior predictive mean')) + scale_color_manual(name = '', values = c('Observed data' = 'red', '90% predictive interval' = 'blue', 'Out-of-sample data' = 'black', 'Posterior predictive mean' = 'green')) + xlab('X') + ylab('y') + ggtitle(str_c('Full Bayes PP intervals for N = ',length(set),' from \nrho = ', rho, ', sigma = ', sigma, ', sigmaEps = ', round(sigmaEps,2))) <file_sep>rm(list = ls()) cat("\014") library(plyr) library(tidyverse) library(stringr) library(rstan) library(reshape2) library(bayesplot) rstan_options(auto_write = TRUE) numCores <- 4 # Find the number of cores on your machine options(mc.cores = numCores) # Then use one less than that for MCMC sampling source("sBCGP/scratch/rCode/betaMeanVar.R") alphaW <- 6 betaW <- 4 # alphaRhoG <- c(1, 1, 1) # betaRhoG <- c(1, 1, 1) # alphaRhoL <- c(1, 8, 3) # betaRhoL <- c(1, 2, 6) alphaRhoG <- 0.5 betaRhoG <- 0.5 alphaRhoL <- 0.5 betaRhoL <- 0.5 D <- length(alphaRhoG) stanData <- list(d = D, alphaW = alphaW, betaW = betaW, alphaRhoG = as.array(alphaRhoG), betaRhoG = as.array(betaRhoG), alphaRhoL = as.array(alphaRhoL), betaRhoL = as.array(betaRhoL)) # stanModel1 <- stan_model(file = 'sBCGP/scratch/stanCode/rhoGRhoL1.stan') # stanModel2 <- stan_model(file = 'sBCGP/scratch/stanCode/rhoGRhoL2.stan') # stanModel3 <- stan_model(file = 'sBCGP/scratch/stanCode/rhoGRhoL3.stan') samples1 <- sampling(stanModel1, data = stanData, cores = 1, chains = 4, iter = 3000, control = list(adapt_delta = 0.90)) samples2 <- sampling(stanModel2, data = stanData, cores = 1, chains = 4, iter = 3000, control = list(adapt_delta = 0.90)) samples3 <- sampling(stanModel3, data = stanData, cores = 1, chains = 4, iter = 3000, control = list(adapt_delta = 0.90)) parsToMonitor <- c("w", "wRaw", "rhoG", "rhoL", "rhoLRaw") print(samples1, pars = parsToMonitor, digits = 4) print(samples2, pars = parsToMonitor, digits = 4) print(samples3, pars = parsToMonitor, digits = 4) meanSDRhoL(alphaRhoG, betaRhoG, alphaRhoL, betaRhoL) samps1 <- extract(samples1) samps2 <- extract(samples2) samps3 <- extract(samples3) samps1Mat <- as.matrix(samples1) samps2Mat <- as.matrix(samples2) samps3Mat <- as.matrix(samples3) rhoG1 <- samps1Mat[,"rhoG[1]"] rhoL1 <- samps1Mat[,"rhoL[1]"] rhoG2 <- samps2Mat[,"rhoG[1]"] rhoL2 <- samps2Mat[,"rhoL[1]"] rhoG3 <- samps3Mat[,"rhoG[1]"] rhoL3 <- samps3Mat[,"rhoL[1]"] contourPlot1 <- ggplot(data = data.frame(rhoG = rhoG1, rhoL = rhoL1), aes(x = rhoG, y = rhoL)) + geom_density2d(aes(color = ..level..)) + theme_classic() + xlim(0, 1) + ylim(0, 1) + ggtitle("No Gradient Adjustment") contourPlot1 contourPlot2 <- ggplot(data = data.frame(rhoG = rhoG2, rhoL = rhoL2), aes(x = rhoG, y = rhoL)) + geom_density2d(aes(color = ..level..)) + theme_classic() + xlim(0, 1) + ylim(0, 1) + ggtitle("With Gradient Adjustment") contourPlot2 contourPlot3 <- ggplot(data = data.frame(rhoG = rhoG3, rhoL = rhoL3), aes(x = rhoG, y = rhoL)) + geom_density2d(aes(color = ..level..)) + theme_classic() + xlim(0, 1) + ylim(0, 1) + ggtitle("With Gradient Adjustment RhoLRaw") contourPlot3 wRaw <- seq(0, 1, .005) fwRaw <- dbeta(wRaw, alphaW, betaW) par(mfrow = c(3,1)) hist(samps1$w) hist(samps1$wRaw) plot(w, fw, type = 'l') par(mfrow = c(3,1)) hist(samps2$w) hist(samps2$wRaw) plot(w, fw, type = 'l') print(round(alphaW/(alphaW + betaW),4)) print(round(sqrt(alphaW*betaW/((alphaW + betaW)^2 * (alphaW + betaW + 1))), 4)) <file_sep>rm(list = ls()) cat("\014") library(plyr) library(tidyverse) library(stringr) library(rstan) library(reshape2) library(bayesplot) # minor edit # minor edit from cbdMerck # setwd("~/Documents/bayesianGPs/") rstan_options(auto_write = TRUE) numCores <- 4 # Find the number of cores on your machine options(mc.cores = numCores) # Then use one less than that for MCMC sampling sim_data_model <- stan_model(file = 'stanCode/generateKrigingData.stan') alpha <- 1 rho <- 0.1 sigma <- sqrt(0.1) dat_list <- list(N = 100, alpha = alpha, length_scale = rho, sigma = sigma) set <- sample(1:dat_list$N, size = 60, replace = F) # draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list, # seed = 363360090) draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list) samps <- rstan::extract(draw) plt_df = with(samps,data.frame(x = x[1,], y = y[1,], f = f[1,])) ggplot(data = plt_df[set,], aes(x=x, y=y)) + geom_point(aes(colour = 'Realized data')) + geom_line(data = plt_df, aes(x = x, y = f, colour = 'Latent mean function')) + theme_bw() + theme(legend.position="bottom") + scale_color_manual(name = '', values = c('Realized data'='black','Latent mean function'='red')) + xlab('X') + ylab('y') + ggtitle(str_c('N = ',length(set),' from length-scale = ', rho, ', alpha = ', alpha, ', sigma = ', round(sigma,2))) stan_data <- list(N = length(set), N_pred = dat_list$N - length(set), zeros = rep(0,length(set)), x = samps$x[1,set], y = samps$y[1,set], x_pred = samps$x[1,-set], f_pred = samps$f[1,-set]) stanMLGP <- stan_model(file = 'otherPeople/stanUserGuide/margLikeGP.stan') stanLVGP <- stan_model(file = 'otherPeople/stanUserGuide/latVarGP.stan') trangucciMLGP <- stan_model(file = 'otherPeople/trangucciStanCon/margLikeGP.stan') trangucciLVGP <- stan_model(file = 'otherPeople/trangucciStanCon/latVarGP.stan') stanMLGPFit <- sampling(stanMLGP, data = stan_data, cores = 4, chains = 4, iter = 1000, control = list(adapt_delta = 0.999)) stanLVGPFit <- sampling(stanLVGP, data = stan_data, cores = 4, chains = 4, iter = 1000, control = list(adapt_delta = 0.999)) trangucciMLGPFit <- sampling(stanMLGP, data = stan_data, cores = 4, chains = 4, iter = 1000, control = list(adapt_delta = 0.999)) trangucciLVGPFit <- sampling(stanLVGP, data = stan_data, cores = 4, chains = 4, iter = 1000, control = list(adapt_delta = 0.999)) parsToFollow <- c("rho", "alpha", "sigma") print(stanMLGPFit, pars = parsToFollow) print(stanLVGPFit, pars = parsToFollow) print(trangucciMLGPFit, pars = parsToFollow) print(trangucciLVGPFit, pars = parsToFollow) <file_sep>Posdef <- function (n, ev = runif(n, 0, 10)) { Z <- matrix(ncol=n, rnorm(n^2)) decomp <- qr(Z) Q <- qr.Q(decomp) R <- qr.R(decomp) d <- diag(R) ph <- d / abs(d) O <- Q %*% diag(ph) Z <- t(O) %*% diag(ev) %*% O return(Z) } C <- Posdef(n=5, ev=1:5) eigen(C)$val L_C <- t(chol(C)) L_C L_C %*% t(L_C) C solve(t(L_C)) %*% solve(L_C) solve(C) solve(t(L_C)) %*% solve(L_C) - solve(C)<file_sep>betaJointPDF <- function(alpha1, beta1, alpha2, beta2){ x1 <- seq(0.01, 0.99, 0.01) x2 <- seq(0.01, 0.99, 0.01) myGrid <- expand.grid(x1,x2) names(myGrid) = c("x1", "x2") dens1 <- dbeta(myGrid$x1, alpha1, beta1) dens2 <- 1/beta(alpha2, beta2) * myGrid$x2^(alpha2 - 1) * (myGrid$x1 - myGrid$x2)^(beta2 - 1) / (myGrid$x1^(alpha2 + beta2 - 1)) * (myGrid$x2 < myGrid$x1) density <- dens1 * dens2 toReturn <- list(x1 = myGrid$x1, x2 = myGrid$x2, density = density) return(toReturn) } alphaRhoG <- 1 betaRhoG <- 1 alphaRhoL <- 1 betaRhoL <- 1 density <- betaJointPDF(alphaRhoG, betaRhoG, alphaRhoL, betaRhoL) density <- data.frame(rhoG = density$x1, rhoL = density$x2, density = density$density) head(density) ggplot(data = density, aes(x = rhoG, y = rhoL, z = density)) + geom_contour() + geom_abline(slope = 1, intercept = 0) + xlim(0,1) + ylim(0,1) ########################################################### tmp <- mesh(seq(0.01, 0.99, 0.01), seq(0.01, 0.99, 0.01)) rhoG <- tmp$x rhoL <- tmp$y dens1 <- dbeta(rhoG, alphaRhoG, betaRhoG) dens2 <- 1/beta(alphaRhoL, betaRhoL) * rhoL^(alphaRhoL - 1) * (rhoG - rhoL)^(betaRhoL - 1) / (rhoG^(alphaRhoL + betaRhoL - 1)) * (rhoL < rhoG) density <- dens1 * dens2 surf3D(rhoG, rhoL, density, theta = 40) ####################################################### # # kd <- with(MASS::geyser, MASS::kde2d(duration, waiting, n = 50)) # p <- plotly::plot_ly(x = kd$x, y = kd$y, z = kd$z) %>% plotly::add_surface() rhoG <- seq(0.01, 0.99, 0.01) rhoL <- seq(0.01, 0.99, 0.01) density <- density p <- plotly::plot_ly(x = rhoG, y = rhoL, z = density) %>% plotly::add_surface() p <file_sep>sumAlphaBeta <- function(alpha, beta){ return(alpha + beta) } prodAlphaBeta <- function(alpha, beta){ return(alpha * beta) } meanSDRhoL <- function(alphaRhoG, betaRhoG, alphaRhoL, betaRhoL){ alphaPlusBetaL <- sumAlphaBeta(alphaRhoL, betaRhoL) alphaPlusBetaG <- sumAlphaBeta(alphaRhoG, betaRhoG) alphaTimesBetaL <- prodAlphaBeta(alphaRhoL, betaRhoL) alphaTimesBetaG <- prodAlphaBeta(alphaRhoG, betaRhoG) means <- (alphaRhoL/(alphaPlusBetaL)) * (alphaRhoG/(alphaPlusBetaG)) vars <- alphaTimesBetaL/((alphaPlusBetaL)^2 * (alphaPlusBetaL + 1)) * (alphaTimesBetaG/((alphaPlusBetaG)^2 * (alphaPlusBetaG + 1)) + (alphaRhoG/alphaPlusBetaG)^2) + ((alphaRhoL/alphaPlusBetaL)^2) * alphaTimesBetaG/((alphaPlusBetaG)^2 * (alphaPlusBetaG + 1)) toReturn <- list(means = means, sds = sqrt(vars)) return(toReturn) } meanSDRhoL(alphaRhoG, betaRhoG, alphaRhoL, betaRhoL) <file_sep>rm(list = ls()) cat("\014") # kriging from someone else's paper. exp(-theta(x_i - x_j)^2) parameterization library(plyr) library(tidyverse) library(stringr) library(rstan) library(reshape2) library(bayesplot) # minor edit # minor edit from cbdMerck # setwd("~/Documents/bayesianGPs/") rstan_options(auto_write = TRUE) numCores <- 4 # Find the number of cores on your machine options(mc.cores = numCores) # Then use one less than that for MCMC sampling sim_data_model <- stan_model(file = 'stanCode/generateKrigingData.stan') alpha <- 1 rho <- 0.1 sigma <- sqrt(0.1) dat_list <- list(N = 100, alpha = alpha, length_scale = rho, sigma = sigma) set <- sample(1:dat_list$N, size = 60, replace = F) # draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list, # seed = 363360090) draw <- sampling(sim_data_model, iter = 1, algorithm = 'Fixed_param', chains = 1, data = dat_list) samps <- rstan::extract(draw) plt_df = with(samps,data.frame(x = x[1,], y = y[1,], f = f[1,])) ggplot(data = plt_df[set,], aes(x=x, y=y)) + geom_point(aes(colour = 'Realized data')) + geom_line(data = plt_df, aes(x = x, y = f, colour = 'Latent mean function')) + theme_bw() + theme(legend.position="bottom") + scale_color_manual(name = '', values = c('Realized data'='black','Latent mean function'='red')) + xlab('X') + ylab('y') + ggtitle(str_c('N = ',length(set),' from length-scale = ', rho, ', alpha = ', alpha, ', sigma = ', round(sigma,2))) stan_data <- list(N = length(set), N_pred = dat_list$N - length(set), zeros = rep(0,length(set)), x = samps$x[1,set], y = samps$y[1,set], x_pred = samps$x[1,-set], f_pred = samps$f[1,-set]) comp_gp_mod_lat <- stan_model(file = 'stanCode/kriging.stan') gp_mod_lat <- sampling(comp_gp_mod_lat, data = stan_data, cores = 4, chains = 4, iter = 500, control = list(adapt_delta = 0.999)) samps_gp_mod_lat <- extract(gp_mod_lat) post_pred <- data.frame(x = stan_data$x_pred, pred_mu = colMeans(samps_gp_mod_lat$f_pred)) plt_df_rt = data.frame(x = stan_data$x_pred, f = t(samps_gp_mod_lat$f_pred)) plt_df_rt_melt = melt(plt_df_rt,id.vars = 'x') p <- ggplot(data = plt_df[set,], aes(x=x, y=y)) + geom_line(data = plt_df_rt_melt, aes(x = x, y = value, group = variable, color = "Posterior draws")) + geom_point(aes(colour = 'Realized data')) + geom_line(data = plt_df, aes(x = x, y = f, colour = 'Latent mean function')) + geom_line(data = post_pred, aes(x = x, y = pred_mu, colour = 'Posterior mean function')) + theme_bw() + theme(legend.position="bottom") + scale_color_manual(name = '', values = c('Realized data'='black', 'Latent mean function'='red', 'Posterior draws' = 'blue', 'Posterior mean function' = 'green')) + xlab('X') + ylab('y') + ggtitle(paste0('N = ',length(set),' from length-scale = 0.15, alpha = 1, sigma = 0.32')) p ppc_interval_df <- function(yrep, y) { q_95 <- apply(yrep,2,quantile,0.95) q_75 <- apply(yrep,2,quantile,0.75) q_50 <- apply(yrep,2,median) q_25 <- apply(yrep,2,quantile,0.25) q_05 <- apply(yrep,2,quantile,0.05) mu <- colMeans(yrep) df_post_pred <- data.frame(y_obs = y, q_95 = q_95, q_75 = q_75, q_50 = q_50, q_25 = q_25, q_05 = q_05, mu = mu) return(df_post_pred) } ppc_interval_norm_df <- function(means, sds, y) { q_95 <- qnorm(0.95,mean = means, sd = sds) q_75 <- qnorm(0.75,mean = means, sd = sds) q_50 <- qnorm(0.5,mean = means, sd = sds) q_25 <- qnorm(0.25,mean = means, sd = sds) q_05 <- qnorm(0.05,mean = means, sd = sds) df_post_pred <- data.frame(y_obs = y, q_95 = q_95, q_75 = q_75, q_50 = q_50, q_25 = q_25, q_05 = q_05, mu = means) return(df_post_pred) } interval_cover <- function(upper, lower, elements) { return(mean(upper >= elements & lower <= elements)) } ppc_full_bayes <- ppc_interval_df(samps_gp_mod_lat$y_pred, samps$y[1,-set]) coverage90 <- interval_cover(upper = ppc_full_bayes$q_95, lower = ppc_full_bayes$q_05, elements = ppc_full_bayes$y_obs) coverage50 <- interval_cover(upper = ppc_full_bayes$q_75, lower = ppc_full_bayes$q_25, elements = ppc_full_bayes$y_obs) print(c(coverage90, coverage50)) post <- as.data.frame(gp_mod_lat) tmp <- select(post, alpha, length_scale, sigma) bayesplot::mcmc_recover_hist(tmp, true = c(1, 0.15, 0.32), facet_args = list(ncol = 1)) ppc_full_bayes$x <- samps$x[1,-set] ggplot(data = ppc_full_bayes, aes(x = x, y = y_obs)) + geom_ribbon(aes(ymax = q_95, ymin = q_05,alpha=0.5, colour = '90% predictive interval')) + geom_point(data = plt_df[set,], aes(x = x, y = y, colour='Observed data')) + geom_point(data = plt_df[-set,], aes(x = x, y = y, colour='Out-of-sample data')) + theme(legend.position="bottom") + geom_line(data = ppc_full_bayes, aes(x = x, y = mu, colour = 'Posterior predictive mean')) + scale_color_manual(name = '', values = c('Observed data' = 'red', '90% predictive interval' = 'blue', 'Out-of-sample data' = 'black', 'Posterior predictive mean' = 'green')) + xlab('X') + ylab('y') + ggtitle(str_c('Full Bayes PP intervals for N = ',length(set),' from length-scale = 0.15, alpha = 1, sigma = 0.32'))
3aa51551df8b4552359924967983b1272ea8bf5e
[ "Markdown", "R" ]
8
Markdown
cbdavis33/bayesianGPs
f6a51c20a462ae9435659ba4ed0bd244a2d4f0b6
4ab34c59b1f895ffdf01108ecbe47623e48c9391
refs/heads/master
<file_sep>'use strict'; const _ = require('lodash'); /** * 过滤掉对象集合中所有为undefined和空字符串的字段 * @param {Object} obj * @returns {Object} */ exports.filterUndefindAndEmptyByObject = (obj) => { if (_.isPlainObject(obj)) { for (let k in obj) { if (obj[k] === undefined || obj[k] === '') { delete obj[k]; } } } return obj; } // 获取今天开始时间戳 exports.getTodayStartTimestamp = () => { return new Date().setHours(0, 0, 0, 0); } <file_sep>'use strict'; const Service = require('egg').Service; class Memorandum extends Service { async create(data = {}) { const { ctx } = this; const uid = ctx.user.uid; return ctx.model.Memorandum.create({ uid, ...data }); } async findAllByUid() { const { ctx } = this; const uid = ctx.user.uid; return ctx.model.Memorandum.findAll({ where: { uid }, order: [ ['createdAt', 'DESC'] ] }); } async findByPk(id) { const { ctx } = this; const uid = ctx.user.uid; return ctx.model.Memorandum.findByPk(id, { where: { uid } }); } /** * 更新 * @param {String} id * @param {Object} updateFields * @return {Promise} */ async updateById(id, updateFields) { const { ctx } = this; const uid = ctx.user.uid; return ctx.model.Memorandum.update(updateFields, { where: { uid, id } }); } async deleteById(id) { const { ctx } = this; const uid = ctx.user.uid; return ctx.model.Memorandum.destroy({ where: { uid, id } }); } } module.exports = Memorandum;
6735b245e449108801ce0f812601b50216bf1299
[ "JavaScript" ]
2
JavaScript
yejiyang/tomato-work-server
51666cb9188150b842387c317128378a3e73898a
d66f797dbf8381f4b9d70efad1d4c0432e426249
refs/heads/master
<file_sep>""" KamLAND-Zen Majoron limit setting script This script sets 90% confidence limit on the Majoron-emitting neutrinoless double beta decay modes (with spectral indices n = 1, 2, 3 and 7), with KamLAND-Zen. Examples: To use simply run the script:: $ python Xe136_majoron_limit.py -s /path/to/majoron_mode.hdf5s -t /path/to/2n2b.hdf5 -b /path/to/B8_Solar.hdf5 .. note:: Use the -v option to print out progress and timing information """ import numpy import echidna import echidna.output.store as store import echidna.limit.limit_config as limit_config import echidna.limit.limit_setting as limit_setting import echidna.limit.chi_squared as chi_squared import echidna.calc.decay as decay def main(args): """ Script to set 90% CL on all four Majoron-emitting modes. """ # Load signal spectra signals = [] for signal_hdf5 in args.signals: spectrum = store.load(signal_hdf5) print spectrum._name print "Num decays:", spectrum._num_decays print "raw events:", spectrum._raw_events print "events:", spectrum.sum() signals.append(spectrum) # Load background spectra floating_backgrounds = [] Xe136_2n2b = store.load(args.two_nu) print Xe136_2n2b._name print "Num decays:", Xe136_2n2b._num_decays print "raw events:", Xe136_2n2b._raw_events print "events:", Xe136_2n2b.sum() floating_backgrounds.append(Xe136_2n2b) B8_Solar = store.load(args.b8_solar) print B8_Solar._name B8_Solar._num_decays = B8_Solar.sum() # Sum not raw events print "Num decays:", B8_Solar._num_decays print "raw events:", B8_Solar._raw_events print "events:", B8_Solar.sum() floating_backgrounds.append(B8_Solar) # Apply FV and livetime cuts fv_radius = 1200.0 # 1.2m PRC 86, 021601 (2012) livetime = 1.0 for spectrum in signals: spectrum.cut(time_low=0.0, time_high=livetime) # cut to livetime spectrum.shrink(radial_low=0.0, radial_high=fv_radius) # shrink to FV spectrum.shrink_to_roi(0.5, 3.0, 0) # shrink to ROI for spectrum in floating_backgrounds: spectrum.cut(time_low=0.0, time_high=livetime) # cut to livetime spectrum.shrink(radial_low=0.0, radial_high=fv_radius) # shrink to FV spectrum.shrink_to_roi(0.5, 3.0, 0) # shrink to ROI # Signal configuration signal_configs_np = [] # no penalty term signal_configs = [] prior = 0.0 Xe136_0n2b_n1_counts = numpy.linspace(signals[0]._num_decays, 0.0, 100, False) # endpoint=False in linspace arrays Xe136_0n2b_n1_config_np = limit_config.LimitConfig(prior, Xe136_0n2b_n1_counts) Xe136_0n2b_n1_config = limit_config.LimitConfig(prior, Xe136_0n2b_n1_counts) signal_configs_np.append(Xe136_0n2b_n1_config_np) signal_configs.append(Xe136_0n2b_n1_config) Xe136_0n2b_n2_counts = numpy.linspace(signals[1]._num_decays, 0.0, 100, False) Xe136_0n2b_n2_config_np = limit_config.LimitConfig(prior, Xe136_0n2b_n2_counts) Xe136_0n2b_n2_config = limit_config.LimitConfig(prior, Xe136_0n2b_n2_counts) signal_configs_np.append(Xe136_0n2b_n2_config_np) signal_configs.append(Xe136_0n2b_n2_config) Xe136_0n2b_n3_counts = numpy.linspace(signals[2]._num_decays, 0.0, 100, False) Xe136_0n2b_n3_config_np = limit_config.LimitConfig(prior, Xe136_0n2b_n3_counts) Xe136_0n2b_n3_config = limit_config.LimitConfig(prior, Xe136_0n2b_n3_counts) signal_configs_np.append(Xe136_0n2b_n3_config_np) signal_configs.append(Xe136_0n2b_n3_config) Xe136_0n2b_n7_counts = numpy.linspace(signals[3]._num_decays, 0.0, 100, False) Xe136_0n2b_n7_config_np = limit_config.LimitConfig(prior, Xe136_0n2b_n7_counts) Xe136_0n2b_n7_config = limit_config.LimitConfig(prior, Xe136_0n2b_n7_counts) signal_configs_np.append(Xe136_0n2b_n7_config_np) signal_configs.append(Xe136_0n2b_n7_config) # Background configuration # Xe136_2n2b Xe136_2n2b_prior = 1.132e6 # Based on KLZ T_1/2, for 1 years # Since we used cut method to cut to livetime # No penalty term Xe136_2n2b_counts_np = numpy.array([Xe136_2n2b_prior]) Xe136_2n2b_config_np = limit_config.LimitConfig(Xe136_2n2b_prior, Xe136_2n2b_counts_np) # With penalty term Xe136_2n2b_counts = numpy.linspace(0.947*Xe136_2n2b_prior, 1.053*Xe136_2n2b_prior, 51) # 51 bins to make sure midpoint (no variation from prior) is included # to use in penalty term (5.3% PRC 86, 021601 (2012)) sigma = 0.053 * Xe136_2n2b_prior Xe136_2n2b_config = limit_config.LimitConfig(Xe136_2n2b_prior, Xe136_2n2b_counts, sigma) # B8_Solar # Assume same rate as SNO+ for now B8_Solar_prior = 1252.99691 # No penalty term B8_Solar_counts_np = numpy.array([B8_Solar_prior]) B8_Solar_config_np = limit_config.LimitConfig(B8_Solar_prior, B8_Solar_counts_np) # With penalty term B8_Solar_counts = numpy.linspace(0.96*B8_Solar_prior, 1.04*B8_Solar_prior, 10) # 11 bins to make sure midpoint (no variation from prior) is included sigma = 0.04 * B8_Solar_prior # 4% To use in penalty term B8_Solar_config = limit_config.LimitConfig(B8_Solar_prior, B8_Solar_counts, sigma) # DBIsotope converter information - constant across modes Xe136_atm_weight = 135.907219 # Molar Mass Calculator, http://www.webqc.org/mmcalc.php, 2015-05-07 Xe134_atm_weight = 133.90539450 # Molar Mass Calculator, http://www.webqc.org/mmcalc.php, 2015-06-03 # We want the atomic weight of the enriched Xenon XeEn_atm_weight = 0.9093*Xe136_atm_weight + 0.0889*Xe134_atm_weight Xe136_abundance = 0.089 # Xenon @ Periodic Table of Chemical Elements, http://www/webqc.org/periodictable-Xenon-Xe.html, 05/07/2015 loading = 0.0244 # PRC 86, 021601 (2012) ib_radius = 1540. # mm, PRC 86, 021601 (2012) scint_density = 7.5628e-7 # kg/mm^3, calculated by A Back 2015-07-28 # Make a list of associated nuclear physics info nuclear_params = [] # n=1: phase_space = 6.02e-16 matrix_element = 2.57 # Averaged nuclear_params.append((phase_space, matrix_element)) # n=2: phase_space = None matrix_element = None nuclear_params.append((phase_space, matrix_element)) # n=1: phase_space = 1.06e-17 # Assuming two Majorons emitted matrix_element = 1.e-3 nuclear_params.append((phase_space, matrix_element)) # n=1: phase_space = 4.54e-17 matrix_element = 1.e-3 nuclear_params.append((phase_space, matrix_element)) # chi squared calculator calculator = chi_squared.ChiSquared() livetime = 112.3 / 365.25 # y, KamLAND-Zen 112.3 live days # Set output location output_dir = echidna.__echidna_base__ + "/results/snoplus/" for signal, signal_config_np, nuclear_param in zip(signals, signal_configs_np, nuclear_params): print signal._name # Create no penalty limit setter set_limit_np = limit_setting.LimitSetting( signal, floating_backgrounds=floating_backgrounds) # Configure signal set_limit_np.configure_signal(signal_config_np) # Configure 2n2b set_limit_np.configure_background(Xe136_2n2b._name, Xe136_2n2b_config_np) # Configure B8 set_limit_np.configure_background(B8_Solar._name, B8_Solar_config_np) # Set converter phase_space, matrix_element = nuclear_param roi_efficiency = signal.get_roi(0).get("efficiency") converter = decay.DBIsotope( "Xe136", Xe136_atm_weight, XeEn_atm_weight, Xe136_abundance, phase_space, matrix_element, loading=loading, fv_radius=fv_radius, outer_radius=ib_radius, scint_density=scint_density, roi_efficiency=roi_efficiency) # Set chi squared calculator set_limit_np.set_calculator(calculator) # Get limit try: limit = set_limit_np.get_limit() print "-----------------------------------" print "90% CL at " + str(limit) + " counts" half_life = converter.counts_to_half_life(limit, livetime=livetime) print "90% CL at " + str(half_life) + " yr" print "-----------------------------------" except IndexError as detail: print "-----------------------------------" print detail print "-----------------------------------" for i, signal_config_np in enumerate(signal_configs_np): store.dump_ndarray(output_dir+signals[i]._name+"_np.hdf5", signal_config_np) raw_input("RETURN to continue") signal_num = 0 for signal, signal_config, nuclear_param in zip(signals, signal_configs, nuclear_params): print signal._name # Create limit setter set_limit = limit_setting.LimitSetting( signal, floating_backgrounds=floating_backgrounds) # Configure signal set_limit.configure_signal(signal_config) # Configure 2n2b set_limit.configure_background(Xe136_2n2b._name, Xe136_2n2b_config, plot_systematic=True) # Configure B8 set_limit.configure_background(B8_Solar._name, B8_Solar_config, plot_systematic=True) # Set converter phase_space, matrix_element = nuclear_param roi_efficiency = signal.get_roi(0).get("efficiency") converter = decay.DBIsotope( "Xe136", Xe136_atm_weight, XeEn_atm_weight, Xe136_abundance, phase_space, matrix_element, loading=loading, fv_radius=fv_radius, outer_radius=ib_radius, scint_density=scint_density, roi_efficiency=roi_efficiency) # Set chi squared calculator set_limit.set_calculator(calculator) # Get limit try: limit = set_limit.get_limit() print "-----------------------------------" print "90% CL at " + str(limit) + " counts" half_life = converter.counts_to_half_life(limit, livetime=livetime) print "90% CL at " + str(half_life) + " yr" print "-----------------------------------" except IndexError as detail: print "-----------------------------------" print detail print "-----------------------------------" # Dump SystAnalysers to hdf5 for syst_analyser in set_limit._syst_analysers.values(): store.dump_ndarray(output_dir+syst_analyser._name+str(signal_num)+".hdf5", syst_analyser) signal_num += 1 # Dump configs to hdf5 for i, signal_config in enumerate(signal_configs): store.dump_ndarray(output_dir+signals[i]._name+".hdf5", signal_config) store.dump_ndarray(output_dir+"Xe136_2n2b_config.hdf5", Xe136_2n2b_config) store.dump_ndarray(output_dir+"B8_Solar_config.hdf5", B8_Solar_config) if __name__ == "__main__": import argparse from echidna.scripts.zero_nu_limit import ReadableDir parser = argparse.ArgumentParser(description="Example limit setting " "script for SNO+ Majoron limits") parser.add_argument("-v", "--verbose", action="store_true", help="Print progress and timing information") parser.add_argument("-s", "--signals", action=ReadableDir, nargs=4, help="Supply path for signal hdf5 file") parser.add_argument("-t", "--two_nu", action=ReadableDir, help="Supply paths for Xe136_2n2b hdf5 files") parser.add_argument("-b", "--b8_solar", action=ReadableDir, help="Supply paths for B8_Solar hdf5 files") args = parser.parse_args() main(args) <file_sep>import ROOT import numpy def chi_squared_vs_signal(signal_config): """ Plot the chi squared as a function of signal counts Args: signal_config (:class:`echidna.limit.limit_config.LimitConfig`): signal config class, where chi squareds have been stored. .. note:: Keyword arguments include: * penalty (:class:`echidna.limit.limit_config.LimitConfig`): config for signal with penalty term. """ x = numpy.array(signal_config._chi_squareds[2]) y = numpy.array(signal_config._chi_squareds[0]) graph = ROOT.TGraph(len(x), x , y) graph.GetXaxis().SetTitle("Signal counts") graph.GetYaxis().SetTitle("$\chi^{2}$") return graph def chi_squared_vs_half_life(signal_config, converter, scaling): """ Plot the chi squared as a function of signal counts Args: signal_config (:class:`echidna.limit.limit_config.LimitConfig`): signal config class, where chi squareds have been stored. .. note:: Keyword arguments include: * penalty (:class:`echidna.limit.limit_config.LimitConfig`): config for signal with penalty term. """ x = numpy.array(signal_config._chi_squareds[2]) y = numpy.array(signal_config._chi_squareds[0]) graph = ROOT.TGraph() for i in range(len(x)): half_life = converter.counts_to_half_life(x[i]/scaling) graph.SetPoint(i, 1./half_life, y[i]) graph.GetXaxis().SetTitle("1/T_{1/2}") graph.GetYaxis().SetTitle("$\chi^{2}$") return graph def chi_squared_vs_mass(signal_config, converter, scaling): """ Plot the chi squared as a function of signal counts Args: signal_config (:class:`echidna.limit.limit_config.LimitConfig`): signal config class, where chi squareds have been stored. .. note:: Keyword arguments include: * penalty (:class:`echidna.limit.limit_config.LimitConfig`): config for signal with penalty term. """ x = numpy.array(signal_config._chi_squareds[2]) y = numpy.array(signal_config._chi_squareds[0]) graph = ROOT.TGraph() for i in range(len(x)): mass = converter.counts_to_eff_mass(x[i]/scaling) graph.SetPoint(i, mass, y[i]) graph.GetXaxis().SetTitle("$m_{#beta#beta}$") graph.GetYaxis().SetTitle("$\chi^{2}$") return graph <file_sep>from echidna.util import root_help from ROOT import TH1D, TH2D def plot_projection(spectra, dimension, graphical=True): """ Plot the spectra as projected onto the dimension. For example dimension == 0 will plot the spectra as projected onto the energy dimension. Args: spectra (:class:`echidna.core.spectra`): The spectra to plot. dimension (int): The dimension to project the spectra onto. graphical (bool): Shows plot and waits for user input when true. Returns: (:class:`ROOT.TH1D`): plot. """ if dimension == 0: plot = TH1D("Energy", ";Energy[MeV];Count per bin", int(spectra._energy_bins), spectra._energy_low, spectra._energy_high) elif dimension == 1: plot = TH1D("Radial", ";Radius[mm];Count per bin", int(spectra._radial_bins), spectra._radial_low, spectra._radial_high) elif dimension == 2: plot = TH1D("Time", ";Time[yr];Count per bin", int(spectra._time_bins), spectra._time_low, spectra._time_high) data = spectra.project(dimension) for index, datum in enumerate(data): plot.SetBinContent(index, datum) if graphical: plot.Draw() raw_input("Return to quit") return plot def plot_surface(spectra, dimension, graphical=True): """ Plot the spectra with the dimension projected out. For example dimension == 0 will plot the spectra as projected onto the radial and time dimensions i.e. not energy. Args: spectra (:class:`echidna.core.spectra`): The spectra to plot. dimension (int): The dimension to project out. graphical (bool): Shows plot and waits for user input when true. Returns: (:class:`ROOT.TH2D`): plot. """ if dimension == 0: plot = TH2D("EnergyRadial", ";Energy[MeV];Radius[mm];Count per bin", int(spectra._energy_bins), spectra._energy_low, spectra._energy_high, int(spectra._radial_bins), spectra._radial_low, spectra._radial_high) data = spectra.surface(2) elif dimension == 1: plot = TH2D("TimeEnergy", ";Time[yr];Energy[MeV];Count per bin", int(spectra._time_bins), spectra._time_low, spectra._time_high, int(spectra._energy_bins), spectra._energy_low, spectra._energy_high) data = spectra.surface(1) elif dimension == 2: plot = TH2D("TimeRadial", ";Time[yr];Radius[mm];Count per bin", int(spectra._time_bins), spectra._time_low, spectra._time_high, int(spectra._radial_bins), spectra._radial_low, spectra._radial_high) data = spectra.surface(0) for index_x, data_x in enumerate(data): for index_y, datum in enumerate(data_x): plot.SetBinContent(index_x, index_y, datum) if graphical: plot.Draw("COLZ") raw_input("Return to quit") return plot def spectral_plot(spectra_dict, dimension=0, show_plot=False, **kwargs): """ Produce spectral plot. For a given signal, produce a plot showing the signal and relevant backgrounds. Backgrounds are automatically summed to create the spectrum "Summed background" and all spectra passed in :obj:`spectra_dict` will be summed to produce the "Sum" spectra Args: spectra_dict (dict): Dictionary containing each spectrum you wish to plot, and the relevant parameters required to plot them. dimension (int, optional): The dimension or axis along which the spectra should be plotted. Default is energy axis. Example: An example :obj:`spectra_dict` is as follows:: {Te130_0n2b._name: {'spectra': Te130_0n2b, 'label': 'signal', 'style': {'color': ROOT.kBlue}, 'type': 'signal'}, Te130_2n2b._name: {'spectra': Te130_2n2b, 'label': r'$2\\nu2\\beta', 'style': {'color': ROOT.kRed}, 'type': 'background'}, B8_Solar._name: {'spectra': B8_Solar, 'label': 'solar', 'style': {'color': ROOT.kGreen}, 'type': 'background'}} .. note:: Keyword arguments include: * log_y (*bool*): Use log scale on y-axis. * limit (:class:`spectra.Spectra`): Include a spectrum showing a current or target limit. Returns: :class:`ROOT.TCanvas`: Canvas containing spectral plot. """ first_spectra = True if dimension == 0: for value in spectra_dict.values(): spectra = value.get("spectra") if first_spectra: energy_low = spectra._energy_low energy_high = spectra._energy_high energy_bins = spectra._energy_bins width = spectra._energy_width shape = (energy_bins) # Shape for summed arrays first_spectra = False else: if spectra._energy_low != energy_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy lower limit") if spectra._energy_high != energy_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy upper limit") if spectra._energy_bins != energy_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy upper limit") summed_background = ROOT.TH1F("summed_background","; Energy (MeV); Counts", spectra._energy_bins, spectra._energy_low, spectra._energy_high) summed_total = ROOT.TH1F("summed_total","; Energy (MeV); Counts", spectra._energy_bins, spectra._energy_low, spectra._energy_high) elif dimension == 1: for value in spectra_dict.values: spectra = value.get("spectra") if first_spectra: radial_low = spectra._radial_low radial_high = spectra._radial_high radial_bins = spectra._radial_bins width = spectra._radial_width shape = (radial_bins) first_spectra = False else: if spectra._radial_low != radial_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time lower limit") if spectra._radial_high != radial_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") if spectra._radial_bins != radial_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") summed_background = ROOT.TH1F("summed_background","; Radius (mm); Counts", spectra._radial_bins, spectra._radial_low, spectra._radial_high) summed_total = ROOT.TH1F("summed_total","; Radius (mm); Counts", spectra._radial_bins, spectra._radial_low, spectra._radial_high) elif dimension == 2: for value in spectra_dict.values: spectra = value.get("spectra") if first_spectra: time_low = spectra._time_low time_high = spectra._time_high time_bins = spectra._time_bins width = spectra._time_width shape = (time_bins) first_spectra = False else: if spectra._time_low != time_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time lower limit") if spectra._time_high != time_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") if spectra._time_bins != time_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") summed_background = ROOT.TH1F("summed_background","; Time (Yr); Counts", spectra._time_bins, spectra._time_low, spectra._time_high) summed_total = ROOT.TH1F("summed_total","; Time (Yr); Counts", spectra._time_bins, spectra._time_low, spectra._time_high) summed_total = numpy.zeros(shape=shape) can = ROOT.TCanvas() leg = ROOT.TLegend(0.7,0.7,0.9,0.9) summed_background.SetLineStyle(7) summed_background.SetLineColor(ROOT.kRed) summed_total.SetLineStyle(7) summed_total.SetLineColor(ROOT.kBlack) leg.AddEntry(summed_total, "Background + Signal", "l") leg.AddEntry(summed_background, "Background", "l") hists = [] if kwargs.get("log_y") is True: can.SetLogy() for value in spectra_dict.values(): spectra = value.get("spectra") hist = spectra.project(dimension, graphical=False) hist.SetLineColor(value.get("style")["color"]) leg.AddEntry(hist, value.get("label"),'l') hists.append(hist) if value.get("type") is "background": summed_background.Add(hist) else: summed_total.Add(hist) summed_total.Draw() summed_background.Draw("same") for hist in hists: hist.Draw("same") # Plot limit if kwargs.get("limit") is not None: limit = kwargs.get("limit") hist = limit.project(dimension, graphical=False) hist.SetLineColor(ROOT.kGray) leg.AddEntry(hist, "Kamland-Zen Limit", "l") leg.Draw("same") return can def plot_chi_squared_per_bin(calculator, x_bins, x_low, x_high, x_title=None, graphical=False): """ Produces a histogram of chi-squared per bin. Args: calculator (:class:`echidna.limit.chi_squared.ChiSquared`): Calculator containing the chi-squared values to plot. x_bins (int): Number of bins. x_low (float): Lower edge of first bin to plot. x_high (float): Upper edge of last bin to plot. x_title (string, optional): X Axis title. graphical (bool): Plots hist to screen if true. Returns: :class:`ROOT.TH1D`: Histogram of chi-squared per bin. """ if x_title: hist_title = "; "+x_title+"; #chi^{2}" else: hist_title = "; Energy (MeV); #chi^{2}" hist = ROOT.TH1F("chi_sq_per_bin", hist_title, x_bins, x_low, x_high) bin = 1 # 0 is underflow for chi_sq in calculator.get_chi_squared_per_bin(): hist.SetBinContent(bin, chi_sq) bin += 1 if graphical: hist.Draw() raw_input("RET to quit") return hist <file_sep>import unittest import echidna.core.spectra as spectra import random import numpy class TestSpectra(unittest.TestCase): def test_fill(self): """ Test the fill method. Basically tests bin positioning makes sense. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) for x in range(0, test_decays): energy = random.uniform(0, test_spectra._energy_high) radius = random.uniform(0, test_spectra._radial_high) time = random.uniform(0, test_spectra._time_high) test_spectra.fill(energy, radius, time) x_bin = energy / test_spectra._energy_high * test_spectra._energy_bins y_bin = radius / test_spectra._radial_high * test_spectra._radial_bins z_bin = time / test_spectra._time_high * test_spectra._time_bins self.assertTrue(test_spectra._data[x_bin, y_bin, z_bin] > 0) # Also test the sum method at the same time self.assertTrue(test_spectra.sum() == test_decays) self.assertRaises(ValueError, test_spectra.fill, -1, 0, 0) self.assertRaises(ValueError, test_spectra.fill, 0, -1, 0) self.assertRaises(ValueError, test_spectra.fill, 0, 0, -1) self.assertRaises(ValueError, test_spectra.fill, test_spectra._energy_high + 1, 0, 0) self.assertRaises(ValueError, test_spectra.fill, 0, test_spectra._radial_high + 1, 0) self.assertRaises(ValueError, test_spectra.fill, 0, 0, test_spectra._time_high + 1) def test_project(self): """ Test the projection method of the spectra. This creates projected spectra alongside the actual spectra. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) energy_projection = numpy.ndarray(shape=(test_spectra._energy_bins), dtype=float) energy_projection.fill(0) radial_projection = numpy.ndarray(shape=(test_spectra._radial_bins), dtype=float) radial_projection.fill(0) time_projection = numpy.ndarray(shape=(test_spectra._time_bins), dtype=float) time_projection.fill(0) for x in range(0, test_decays): energy = random.uniform(0, 10.0) radius = random.uniform(0, 6000.0) time = random.uniform(0, 10.0) test_spectra.fill(energy, radius, time) x_bin = energy / test_spectra._energy_high * test_spectra._energy_bins y_bin = radius / test_spectra._radial_high * test_spectra._radial_bins z_bin = time / test_spectra._time_high * test_spectra._time_bins energy_projection[x_bin] += 1.0 radial_projection[y_bin] += 1.0 time_projection[z_bin] += 1.0 self.assertTrue(numpy.array_equal(energy_projection, test_spectra.project(0))) self.assertTrue(numpy.array_equal(radial_projection, test_spectra.project(1))) self.assertTrue(numpy.array_equal(time_projection, test_spectra.project(2))) def test_scale(self): """ Test the scale method of the spectra. This creates a spectra and then scales it. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) for x in range(0, test_decays): energy = random.uniform(test_spectra._energy_low, test_spectra._energy_high) radius = random.uniform(test_spectra._radial_low, test_spectra._radial_high) time = random.uniform(test_spectra._time_low, test_spectra._time_high) test_spectra.fill(energy, radius, time) self.assertTrue(test_spectra.sum() == test_decays) count = 150 test_spectra.scale(count) self.assertTrue(test_spectra.sum() == count) def test_slicing(self): """ Test the slicing shirnks the spectra in the correct way. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) self.assertRaises(ValueError, test_spectra.shrink, test_spectra._energy_low, 2 * test_spectra._energy_high, test_spectra._radial_low, test_spectra._radial_high, test_spectra._time_low, test_spectra._time_high) self.assertRaises(ValueError, test_spectra.shrink, test_spectra._energy_low, test_spectra._energy_high, test_spectra._radial_low, 2 * test_spectra._radial_high, test_spectra._time_low, test_spectra._time_high) self.assertRaises(ValueError, test_spectra.shrink, test_spectra._energy_low, test_spectra._energy_high, test_spectra._radial_low, test_spectra._radial_high, test_spectra._time_low, 2 * test_spectra._time_high) test_spectra.shrink(test_spectra._energy_low, test_spectra._energy_high / 2, test_spectra._radial_low, test_spectra._radial_high / 2, test_spectra._time_low, test_spectra._time_high / 2) self.assertTrue(test_spectra._data.shape == (test_spectra._energy_bins, test_spectra._radial_bins, test_spectra._time_bins)) def test_rebin(self): """ Tests that the spectra are being rebinned correctly. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) test_spectra._energy_bins = 1000 test_spectra._radial_bins = 1000 test_spectra._time_bins = 10 test_spectra.calc_widths() old_energy_width = test_spectra._energy_width old_radial_width = test_spectra._radial_width old_time_width = test_spectra._time_width for decay in range(test_decays): energy = random.uniform(test_spectra._energy_low, test_spectra._energy_high) radius = random.uniform(test_spectra._radial_low, test_spectra._radial_high) time = random.uniform(test_spectra._time_low, test_spectra._time_high) test_spectra.fill(energy, radius, time) new_bins = (1, 2, 3, 4) self.assertRaises(ValueError, test_spectra.rebin, new_bins) new_bins = (99999, 99999, 99999) self.assertRaises(ValueError, test_spectra.rebin, new_bins) old_sum = test_spectra.sum() new_bins = (500, 250, 2) test_spectra.rebin(new_bins) self.assertTrue(old_sum == test_spectra.sum()) self.assertTrue(test_spectra._data.shape == new_bins) self.assertTrue(test_spectra._energy_width == old_energy_width*2.) self.assertTrue(test_spectra._radial_width == old_radial_width*4.) self.assertTrue(test_spectra._time_width == old_time_width*5.) def test_copy(self): """ Tests that the spectra are being copied correctly. """ test_decays = 10 test_spectra = spectra.Spectra("Test", test_decays) # Modify spectra to non default values test_spectra._energy_bins = 250 test_spectra._radial_bins = 500 test_spectra._time_bins = 2 test_spectra._energy_low = 1. test_spectra._energy_high = 11. test_spectra._radial_low = 100. test_spectra._radial_high = 10100. test_spectra._time_low = 1. test_spectra._time_high = 11. test_spectra._raw_events = 9. test_spectra.calc_widths() for decay in range(test_decays): energy = random.uniform(test_spectra._energy_low, test_spectra._energy_high) radius = random.uniform(test_spectra._radial_low, test_spectra._radial_high) time = random.uniform(test_spectra._time_low, test_spectra._time_high) test_spectra.fill(energy, radius, time) new_spectra = test_spectra.copy() self.assertTrue(new_spectra._data.all() == test_spectra._data.all()) self.assertTrue(new_spectra._name == test_spectra._name) self.assertTrue(new_spectra._energy_low == test_spectra._energy_low) self.assertTrue(new_spectra._energy_high == test_spectra._energy_high) self.assertTrue(new_spectra._energy_bins == test_spectra._energy_bins) self.assertTrue(new_spectra._energy_width == test_spectra._energy_width) self.assertTrue(new_spectra._radial_low == test_spectra._radial_low) self.assertTrue(new_spectra._radial_high == test_spectra._radial_high) self.assertTrue(new_spectra._radial_bins == test_spectra._radial_bins) self.assertTrue(new_spectra._radial_width == test_spectra._radial_width) self.assertTrue(new_spectra._time_low == test_spectra._time_low) self.assertTrue(new_spectra._time_high == test_spectra._time_high) self.assertTrue(new_spectra._time_bins == test_spectra._time_bins) self.assertTrue(new_spectra._time_width == test_spectra._time_width) self.assertTrue(new_spectra._num_decays == test_spectra._num_decays) self.assertTrue(new_spectra._raw_events == test_spectra._raw_events) new_spectra2 = test_spectra.copy(name="Copy") self.assertTrue(new_spectra2._name != test_spectra._name) self.assertTrue(new_spectra2._name == "Copy") <file_sep>echidna ======= echidna is a limit setting and spectrum fitting tool. It aims to create a fast flexible platform providing the tools for a variety of limit-setting and fitting based analyses. Getting started with echidna ---------------------------- Whether you want to contribute to development or just use the latest release, this is the place to start. Downloading echidna ------------------- If you just want the latest release, there are two main options: * [download](https://github.com/snoplusuk/echidna/releases/latest) the latest release from GitHub * Clone the repository from the command line $ git clone -b "v0.1-alpha" <EMAIL>:snoplusuk/echidna.git However if you plan on developing echidna, the best option is to fork the main echidna repository and then clone your fork $ git clone <EMAIL>:yourusername/echidna.git Software Requirements --------------------- In order run echidna some extra python modules are required. The software and corresponding version numbers required listed in requirements.txt. To install all packages using pip run $ pip install -r requirements.txt Note: you may need root access to install some modules. Running echidna --------------- You should now have a working copy of echidna. You can get started straight away by using some of the example scripts. Example scripts are located in `echidna/scripts/`. To run example scripts you must set your python path to $ export PYTHONPATH=$PYTHONPATH:$(pwd) from the echidna base directory. Details on how to run individual scripts can be found in their respective documentation. Documentation ------------- A copy of the latest version of the HTML documentation is available [here](https://snoplusuk.github.io/echidna/docs/index.html) But if you prefer you can build a copy of the Sphinx-based documentation locally. To build HTML documentation: $ cd docs $ make html Output is placed in `docs/html/docs`. This documentation is built using the napoleon extension to sphinx, which allows the google style comments. Note: After updating code be sure to run in the base directory $ sphinx-apidoc -f -H echidna -o docs echidna/ $ cd docs $ make html Testing ------- To test the code is working as expected run $ python -m unittest discover echidna/test/ from the base directory.<file_sep>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy def _produce_axis(low, high, bins): """ This method produces an array that represents the axis between low and high with bins. Args: low (float): Low edge of the axis high (float): High edge of the axis bins (int): Number of bins """ return [low + x * (high - low) / bins for x in range(bins)] def plot_projection(spectra, dimension, fig_num=1, show_plot=True): """ Plot the spectra as projected onto the dimension. For example dimension == 0 will plot the spectra as projected onto the energy dimension. Args: spectra (:class:`echidna.core.spectra`): The spectra to plot. dimension (int): The dimension to project the spectra onto. """ fig = plt.figure(num=fig_num) ax = fig.add_subplot(1, 1, 1) if dimension == 0: x = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins) width = spectra._energy_width plt.xlabel("Energy [MeV]") elif dimension == 1: x = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins) width = spectra._radial_width plt.xlabel("Radius [mm]") elif dimension == 2: x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins) width = spectra._time_width plt.xlabel("Time [yr]") plt.ylabel("Count per %.2g bin" % width) data = spectra.project(dimension) ax.bar(x, data, width=width) if show_plot: plt.show() return fig def spectral_plot(spectra_dict, dimension=0, fig_num=1, show_plot=True, **kwargs): """ Produce spectral plot. For a given signal, produce a plot showing the signal and relevant backgrounds. Backgrounds are automatically summed to create the spectrum 'Summed background' and all spectra passed in :obj:`spectra_dict` will be summed to produce the "Sum" spectrum. Args: spectra_dict (dict): Dictionary containing each spectrum you wish to plot, and the relevant parameters required to plot them. dimension (int, optional): The dimension or axis along which the spectra should be plotted. Default is energy axis. fig_num (int, optional): The number of the figure. If you are producing multiple spectral plots automatically, this can be useful to ensure pyplot treats each plot as a separate figure. Default is 1. Example: An example :obj:`spectra_dict` is as follows:: {Te130_0n2b._name: {'spectra': Te130_0n2b, 'label': 'signal', 'style': {'color': 'blue'}, 'type': 'signal'}, Te130_2n2b._name: {'spectra': Te130_2n2b, 'label': r'$2\\nu2\\beta', 'style': {'color': 'red'}, 'type': 'background'}, B8_Solar._name: {'spectra': B8_Solar, 'label': 'solar', 'style': {'color': 'green'}, 'type': 'background'}} .. note:: Keyword arguments include: * log_y (*bool*): Use log scale on y-axis. * per_bin (*bool*): Include chi-squared per bin histogram. * limit (:class:`spectra.Spectra`): Include a spectrum showing a current or target limit. """ fig = plt.figure(fig_num) ax = fig.add_subplot(3, 1, (1, 2)) # All spectra should have same width first_spectra = True if dimension == 0: for value in spectra_dict.values(): spectra = value.get("spectra") if first_spectra: energy_low = spectra._energy_low energy_high = spectra._energy_high energy_bins = spectra._energy_bins width = spectra._energy_width shape = (energy_bins) # Shape for summed arrays first_spectra = False else: if spectra._energy_low != energy_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy lower limit") if spectra._energy_high != energy_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy upper limit") if spectra._energy_bins != energy_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect energy upper limit") x = _produce_axis(energy_low, energy_high, energy_bins) x_label = "Energy [MeV]" elif dimension == 1: for value in spectra_dict.values: spectra = value.get("spectra") if first_spectra: radial_low = spectra._radial_low radial_high = spectra._radial_high radial_bins = spectra._radial_bins width = spectra._radial_width shape = (radial_bins) first_spectra = False else: if spectra._radial_low != radial_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect radial lower limit") if spectra._radial_high != radial_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect radial upper limit") if spectra._radial_bins != radial_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect radial upper limit") x = _produce_axis(radial_low, radial_high, radial_bins) x_label = "Radius [mm]" elif dimension == 2: for value in spectra_dict.values: spectra = value.get("spectra") if first_spectra: time_low = spectra._time_low time_high = spectra._time_high time_bins = spectra._time_bins width = spectra._time_width shape = (time_bins) first_spectra = False else: if spectra._time_low != time_low: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time lower limit") if spectra._time_high != time_high: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") if spectra._time_bins != time_bins: raise AssertionError("Spectra " + spectra._name + " has " "incorrect time upper limit") x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins) x_label = "Time [yr]" summed_background = numpy.zeros(shape=shape) summed_total = numpy.zeros(shape=shape) hist_range = (x[0]-0.5*width, x[-1]+0.5*width) if kwargs.get("log_y") is True: log=True else: log=False for value in spectra_dict.values(): spectra = value.get("spectra") ax.hist(x, bins=len(x), weights=spectra.project(dimension), range=hist_range, histtype="step", label=value.get("label"), color=spectra.get_style().get("color"), log=log) if value.get("type") is "background": summed_background = summed_background + spectra.project(dimension) else: summed_total = summed_total + spectra.project(dimension) ax.hist(x, bins=len(x), weights=summed_background, range=hist_range, histtype="step", color="DarkSlateGray", linestyle="dashed", label="Summed background", log=log) y = summed_background yerr = numpy.sqrt(y) ax.fill_between(x, y-yerr, y+yerr, facecolor="DarkSlateGray", alpha=0.5, label="Summed background, standard error") summed_total = summed_total + summed_background ax.hist(x, bins=len(x), weights=summed_total, range=hist_range, histtype="step", color="black", label="Sum", log=log) kev_width = width * 1.0e3 # Plot limit if kwargs.get("limit") is not None: limit = kwargs.get("limit") ax.hist(x, bins=len(x), weights=limit.project(dimension), range=hist_range, histtype="step", color="LightGrey", label="KamLAND-Zen limit", log=log) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width, box.height*0.8]) plt.legend(loc="upper right", bbox_to_anchor=(1.0, 1.25), fontsize="8") plt.ylabel("Count per %.1f keV bin" % kev_width) plt.ylim(ymin=0.1) # Plot chi squared per bin, if required if kwargs.get("per_bin") is not None: calculator = kwargs.get("per_bin") ax2 = fig.add_subplot(3, 1, 3, sharex=ax) chi_squared_per_bin = calculator.get_chi_squared_per_bin() ax2.hist(x, bins=len(x), weights=chi_squared_per_bin, range=hist_range, histtype="step") # same x axis as above plt.ylabel("$\chi^2$ per %.1f keV bin" % kev_width) plt.xlabel(x_label) plt.xlim(xmin=x[0], xmax=x[-1]) if kwargs.get("title") is not None: plt.figtext(0.05, 0.95, kwargs.get("title")) if kwargs.get("text") is not None: for index, entry in enumerate(kwargs.get("text")): plt.figtext(0.05, 0.90-(index*0.05), entry) if show_plot: plt.show() return fig def plot_surface(spectra, dimension): """ Plot the spectra with the dimension projected out. For example dimension == 0 will plot the spectra as projected onto the radial and time dimensions i.e. not energy. Args: spectra (:class:`echidna.core.spectra`): The spectra to plot. dimension (int): The dimension to project out. """ fig = plt.figure() axis = fig.add_subplot(111, projection='3d') if dimension == 0: x = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins) y = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins) data = spectra.surface(2) axis.set_xlabel("Radius [mm]") axis.set_ylabel("Energy [MeV]") elif dimension == 1: x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins) y = _produce_axis(spectra._energy_low, spectra._energy_high, spectra._energy_bins) data = spectra.surface(1) axis.set_xlabel("Time [yr]") axis.set_ylabel("Energy [MeV]") elif dimension == 2: x = _produce_axis(spectra._time_low, spectra._time_high, spectra._time_bins) y = _produce_axis(spectra._radial_low, spectra._radial_high, spectra._radial_bins) data = spectra.surface(0) axis.set_xlabel("Time [yr]") axis.set_ylabel("Radius [mm]") axis.set_zlabel("Count per bin") print len(x), len(y), data.shape X, Y = numpy.meshgrid(x, y) # `plot_surface` expects `x` and `y` data to be 2D print X.shape, Y.shape axis.plot_surface(X, Y, data) if show_plot: plt.show() return fig if __name__ == "__main__": import echidna import echidna.output.store as store filename = "/data/Te130_0n2b_mc_smeared.hdf5" spectre = store.load(echidna.__echidna_home__ + filename) plot_surface(spectre, 2) <file_sep>import numpy class Spectra(object): """ This class contains a spectra as a function of energy, radius and time. The spectra is stored as histogram binned in energy, x, radius, y, and time, z. This histogram can be flattened to 2d (energy, radius) or 1d (energy). Args: name (str): The name of this spectra num_decays (float): The number of decays this spectra is created to represent. Attributes: _data (:class:`numpy.ndarray`): The histogram of data _name (str): The name of this spectra _energy_low (float): Lowest bin edge in MeV _energy_high (float): Highest bin edge in MeV _energy_bins (int): Number of energy bins _energy_width (float): Width of a single bin in MeV _radial_low (float): Lowest bin edge in mm _radial_high (float): Highest bin edge in mm _radial_bins (int): Number of raidal bins _radial_width (float): Width of a single bin in mm _time_low (float): Lowest bin edge in years _time_high (float): Highest bin edge in years _time_bins (int): Number of time bins _time_width (float): Width of a single bin in yr _num_decays (float): The number of decays this spectra currently represents. _raw_events (int): The number of raw events used to generate the spectra. Increments by one with each fill independent of weight. _style (string): Pyplot-style plotting style e.g. "b-" or {"color": "blue"}. _rois (dict): Dictionary containing the details of any ROI, along any axis, which has been defined. """ def __init__(self, name, num_decays): """ Initialise the spectra data container. """ self._energy_low = 0.0 # MeV self._energy_high = 10.0 # MeV self._energy_bins = 1000 self._radial_low = 0.0 # mm self._radial_high = 10000.0 # mm self._radial_bins = 1000 self._time_low = 0.0 # years self._time_high = 10.0 # years self._time_bins = 10 self.calc_widths() self._num_decays = num_decays self._raw_events = 0 self._data = numpy.zeros(shape=(self._energy_bins, self._radial_bins, self._time_bins), dtype=float) self._style = {"color": "blue"} # default style for plotting self._rois = {} self._name = name def fill(self, energy, radius, time, weight=1.0): """ Fill the bin for the `energy` `radius` and `time` with weight. Args: energy (float): Energy value to fill. raidus (float): Radial value to fill. time (float): Time value to fill. weight (float, optional): Defaults to 1.0, weight to fill the bin with. Raises: ValueError: If the energy, radius or time is beyond the bin limits. """ if not self._energy_low <= energy < self._energy_high: raise ValueError("Energy out of range") if not self._radial_low <= radius < self._radial_high: raise ValueError("Radius out of range") if not self._time_low <= time < self._time_high: raise ValueError("Time out of range") energy_bin = (energy - self._energy_low) / (self._energy_high - self._energy_low) * self._energy_bins radial_bin = (radius - self._radial_low) / (self._radial_high - self._radial_low) * self._radial_bins time_bin = (time - self._time_low) / (self._time_high - self._time_low) * self._time_bins self._data[energy_bin, radial_bin, time_bin] += weight def shrink_to_roi(self, lower_limit, upper_limit, axis): """ Shrink spectrum to a defined Region of Interest (ROI) Shrinks spectrum to given ROI and saves ROI parameters. Args: lower_limit (float): Lower bound of ROI, along given axis. upper_limit (float): Upper bound of ROI, along given axis. axis (int): Axis along which to define ROI. """ integral_full = self.sum() # Save integral of full spectrum # Shrink to ROI if axis == 0: self.shrink(energy_low=lower_limit, energy_high=upper_limit) elif axis == 1: self.shrink(radial_low=lower_limit, radial_high=upper_limit) elif axis == 2: self.shrink(time_low=lower_limit, time_high=upper_limit) # Calculate efficiency integral_roi = self.sum() # Integral of spectrum over ROI efficiency = float(integral_roi) / float(integral_full) self._rois[axis] = {"low": lower_limit, "high": upper_limit, "efficiency": efficiency} def get_roi(self, axis): """ Access information about a predefined ROI on a given axis Returns: dict: Dictionary containing parameters defining the ROI, on the given axis. """ return self._rois[axis] def set_style(self, style): """ Sets plotting style. Styles should be valid pyplot style strings e.g. "b-", for a blue line, or dictionaries of strings e.g. {"color": "red"}. Args: style (string): Pyplot-style plotting style. """ self._style = style def get_style(self): """ Returns: string/dict: :attr:`_style` - pyplot-style plotting style. """ return self._style def project(self, axis): """ Project the histogram along an `axis`. Args: axis (int): To project onto Returns: The projection of the histogram onto the given axis """ if axis == 0: return self._data.sum(1).sum(1) elif axis == 1: return self._data.sum(0).sum(1) elif axis == 2: return self._data.sum(0).sum(0) def surface(self, axis): """ Project the histogram along two axis, along the `axis`. Args: axis (int): To project away Returns: The 2d surface of the histogram. """ return self._data.sum(axis) def sum(self): """ Calculate and return the sum of the `_data` values. Returns: The sum of the values in the `_data` histogram. """ return self._data.sum() def scale(self, num_decays): """ Scale THIS spectra to represent *num_decays* worth of decays over the entire unshrunken spectra. This rescales each bin by the ratio of *num_decays* to *self._num_decays*, i.e. it changes the spectra from representing *self._num_decays* to *num_decays*. *self._num_decays* is updated to equal *num_decays* after. Args: num_decays (float): Number of decays this spectra should represent. """ self._data = numpy.multiply(self._data, num_decays / self._num_decays) self._num_decays = num_decays def shrink(self, energy_low=None, energy_high=None, radial_low=None, radial_high=None, time_low=None, time_high=None): """ Shrink the data such that it only contains values between energy_low and energy_high (for example) by slicing. This updates the internal bin information as well as the data. Args: energy_low (float): Optional new low bound of the energy. energy_low (float): Optional new high bound of the energy. radial_low (float): Optional new low bound of the radius. radial_low (float): Optional new high bound of the radius. time_low (float): Optional new low bound of the time. time_low (float): Optional new high bound of the time. Notes: The logic in this method is the same for each dimension, first check the new values are within the existing ones (can only compress). Then calculate the low bin number and high bin number (relative to the existing binning low). Finally update all the bookeeping and slice. """ if(energy_low is not None and energy_low < self._energy_low): raise ValueError("Energy low is below existing bound") if(energy_high is not None and energy_high > self._energy_high): raise ValueError("Energy high is above existing bound") if(radial_low is not None and radial_low < self._radial_low): raise ValueError("Radial low is below existing bound") if(radial_high is not None and radial_high > self._radial_high): raise ValueError("Radial high is above existing bound") if(time_low is not None and time_low < self._time_low): raise ValueError("Time low is below existing bound") if(time_high is not None and time_high > self._time_high): raise ValueError("Time high is above existing bound") energy_low_bin = 0 energy_high_bin = self._energy_bins if(energy_low is not None and energy_high is not None): energy_low_bin = (energy_low - self._energy_low) / self._energy_width energy_high_bin = (energy_high - self._energy_low) / self._energy_width self._energy_low = energy_low self._energy_high = energy_high self._energy_bins = int(energy_high_bin - energy_low_bin) radial_low_bin = 0 radial_high_bin = self._radial_bins if(radial_low is not None and radial_high is not None): radial_low_bin = (radial_low - self._radial_low) / self._radial_width radial_high_bin = (radial_high - self._radial_low) / self._radial_width self._radial_low = radial_low self._radial_high = radial_high self._radial_bins = int(radial_high_bin - radial_low_bin) time_low_bin = 0 time_high_bin = self._time_bins if(time_low is not None and time_high is not None): time_low_bin = (time_low - self._time_low) / self._time_width time_high_bin = (time_high - self._time_low) / self._time_width self._time_low = time_low self._time_high = time_high self._time_bins = int(time_high_bin - time_low_bin) # Internal bookeeping complete, now slice the data self._data = self._data[energy_low_bin:energy_high_bin, radial_low_bin:radial_high_bin, time_low_bin:time_high_bin] def cut(self, energy_low=None, energy_high=None, radial_low=None, radial_high=None, time_low=None, time_high=None): """ Similar to :meth:`shrink`, but updates scaling information. If a spectrum is cut using :meth:`shrink`, subsequent calls to :meth:`scale` the spectrum must still scale the *full* spectrum i.e. before any cuts. The user supplies the number of decays the full spectrum should now represent. However, sometimes it is more useful to be able specify the number of events the revised spectrum should represent. This method updates the scaling information, so that it becomes the new *full* spectrum. Args: energy_low (float, optional): New low bound of the energy. energy_low (float, optional): New high bound of the energy. radial_low (float, optional): New low bound of the radius. radial_low (float, optional): New high bound of the radius. time_low (float, optional): New low bound of the time. time_low (float, optional): New high bound of the time. """ initial_count = self.sum() # Store initial count self.shrink(energy_low, energy_high, radial_low, radial_high, time_low, time_high) new_count = self.sum() reduction_factor = float(new_count) / float(initial_count) # This reduction factor tells us how much the number of detected events # has been reduced by shrinking the spectrum. We want the number of # decays that the spectrum should now represent to be reduced by the # same factor self._num_decays *= reduction_factor def add(self, spectrum): """ Adds a spectrum to current spectra object. Args: spectrum (:class:`core.spectra`): Spectrum to add. """ if not numpy.allclose(self._energy_low, spectrum._energy_low): raise ValueError("Lower energy bounds in spectra are not equal.") if not numpy.allclose(self._energy_high, spectrum._energy_high): raise ValueError("Upper energy bounds in spectra are not equal.") if not numpy.allclose(self._energy_bins, spectrum._energy_bins): raise ValueError("Number of energy bins in spectra are not equal.") if not numpy.allclose(self._energy_width, spectrum._energy_width): raise ValueError("Width of energy bins in spectra are not equal.") if not numpy.allclose(self._radial_low, spectrum._radial_low): raise ValueError("Lower radial bounds in spectra are not equal.") if not numpy.allclose(self._radial_high, spectrum._radial_high): raise ValueError("Upper radial bounds in spectra are not equal.") if not numpy.allclose(self._radial_bins, spectrum._radial_bins): raise ValueError("Number of radial bins in spectra are not equal.") if not numpy.allclose(self._radial_width, spectrum._radial_width): raise ValueError("Width of radial bins in spectra are not equal.") if not numpy.allclose(self._time_low, spectrum._time_low): raise ValueError("Lower time bounds in spectra are not equal.") if not numpy.allclose(self._time_high, spectrum._time_high): raise ValueError("Upper time bounds in spectra are not equal.") if not numpy.allclose(self._time_bins, spectrum._time_bins): raise ValueError("Number of time bins in spectra are not equal.") if not numpy.allclose(self._time_width, spectrum._time_width): raise ValueError("Width of time bins in spectra are not equal.") self._data += spectrum._data self._raw_events += spectrum._raw_events self._num_decays += spectrum._num_decays def rebin(self, new_bins): """ Rebin spectra data into a smaller spectra of the same rank whose dimensions are factors of the original dimensions. Args: new_bins (tuple): New bin sizes for spectra. Should be in order of energy, radial, time. Raises: ValueError: Shape mismatch. Number of dimenesions are different. ValueError: Old bins/ New bins must be integer """ if self._data.ndim != len(new_bins): raise ValueError("Shape mismatch: %s->%s" % (self._data.shape, new_bins)) for i in range(len(new_bins)): if self._data.shape[i] % new_bins[i] != 0: raise ValueError("Old bins/New bins must be integer old: %s" " new: %s" % (self._data.shape, new_bins)) compression_pairs = [(d, c//d) for d, c in zip(new_bins, self._data.shape)] flattened = [l for p in compression_pairs for l in p] self._data = self._data.reshape(flattened) for i in range(len(new_bins)): self._data = self._data.sum(-1*(i+1)) self._energy_bins = new_bins[0] self._radial_bins = new_bins[1] self._time_bins = new_bins[2] self.calc_widths() def calc_widths(self): """ Recalculates bin widths """ self._energy_width = (self._energy_high - self._energy_low) / self._energy_bins self._radial_width = (self._radial_high - self._radial_low) / self._radial_bins self._time_width = (self._time_high - self._time_low) / self._time_bins def copy(self, name=None): """ Copies the current spectra and returns a new identical one. Args: name (string, optional): Name of the new copied spectrum. Default is the name of the current spectrum. Returns: :class:`echidna.core.spectra.Spectra` object which is identical to the current spectra apart from possibly its name. """ if not name: name = self._name new_spectrum = Spectra(name, 0.) new_spectrum._energy_low = self._energy_low new_spectrum._energy_high = self._energy_high new_spectrum._energy_bins = self._energy_bins new_spectrum._radial_low = self._radial_low new_spectrum._radial_high = self._radial_high new_spectrum._radial_bins = self._radial_bins new_spectrum._time_low = self._time_low new_spectrum._time_high = self._time_high new_spectrum._time_bins = self._time_bins new_spectrum.calc_widths() new_spectrum._data = numpy.zeros(shape=numpy.shape(self._data), dtype=float) new_spectrum.add(self) new_spectrum._style = self._style new_spectrum._rois = self._rois return new_spectrum
6e237341b86fd488c587545520ceabe5ced774c6
[ "Markdown", "Python" ]
7
Python
Mark--S/echidna
724af684b5cc554874d1fe4096901025176fd71c
efc10639635035c4b4c0baac9893fa56e836b454
refs/heads/master
<file_sep>package com.xyz.shrreya.youtubesdk_sample class YouTubeConfig{ companion object { val apiKey = "Your API KEY" } }<file_sep>package com.xyz.shrreya.youtubesdk_sample import android.nfc.Tag import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import com.google.android.youtube.player.YouTubeBaseActivity import com.google.android.youtube.player.YouTubeInitializationResult import com.google.android.youtube.player.YouTubePlayer import com.google.android.youtube.player.YouTubePlayerView class MainActivity : YouTubeBaseActivity() { private val TAG : String="MainActivity" lateinit var buttonPlay :Button lateinit var mYouTubePlayerView :YouTubePlayerView lateinit var mOnInitializedListener : YouTubePlayer.OnInitializedListener override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) buttonPlay= findViewById<Button>(R.id.button_Play) mYouTubePlayerView= findViewById<YouTubePlayerView>(R.id.youtubePlayer) mOnInitializedListener= object : YouTubePlayer.OnInitializedListener{ override fun onInitializationSuccess(provider: YouTubePlayer.Provider, youTubePlayer: YouTubePlayer, b: Boolean) { Log.d(TAG,"onCreate: Done Initializing") youTubePlayer.loadVideo("URL to your Video") //for adding a playlist //youTubePlayer.loadPlaylist("") } override fun onInitializationFailure(provider: YouTubePlayer.Provider, youTubeInitializationResult: YouTubeInitializationResult) { Log.d(TAG,"onCreate: Failed to Initialize") } } buttonPlay.setOnClickListener(object : View.OnClickListener{ override fun onClick(v: View?) { Log.d(TAG,"onClick: Initializing YouTubePlayer") mYouTubePlayerView.initialize(YouTubeConfig.apiKey,mOnInitializedListener) } }) } }
8e46bdb144b85be9bed7906b4d9ecb7a7877a6e5
[ "Kotlin" ]
2
Kotlin
VictoriousAura/YouTubeApiSample
f72e77500cf4fcba2991d5c2f200ebdd552ab56d
bd34bc645801dfb60f4c1295e1f90e57698c2ac6
refs/heads/developmen
<repo_name>ArturSayfullayev/Closures<file_sep>/Hometask_Closures.playground/Contents.swift import Foundation // --------------------------------------- // MARK: - Домашнее задание // --------------------------------------- // ======================================= // MARK: - Task 1 // ======================================= /* 1. Написать функцию, которая ничего не возвращает и принимает только одно замыкание `closure` 2. Это замыкание `closure` тоже ничего не принимает и ничего не возвращает 3. Ваша функция должна посчитать от `1` до `10` в цикле и только после этого вызвать замыкание `closure` 4. Добавьте `print(...)` на каждую итерацию цикла, и в замыкание, а затем оцените очередность выполнения команд */ // MARK: - Task 1. Solution // ======================================= // ... // ======================================= // MARK: - Task 2 // ======================================= /* 1. Объявите 3 массива с типами [Int], [Double], [String] и заполните их данными 2. Используя метод массивов `sorted`, отсортируйте массивы по возрастанию и убыванию 3. Для каждого массива покажите использование замыкания `sorted` по этапам (аналогично, как делали в классе): - В развернутом виде - В неявном виде - С использование сокращенных имен параметров - В сокращенной форме */ // MARK: - Task 2. Solution // ======================================= // ... // ======================================= // MARK: - Task 3 // ======================================= /* 1. Напишите функцию, которая принимает массив [Int] и замыкание `closure`, а затем и возвращает `Int` 2. Замыкание `closure` должно принимать `Int` и `Int?` и возвращать `Bool` 3. Внутри самой функции создайте переменную опционального типа 4. Переберите массив [Int] и сравните элементы с объявленной выше переменной, используя замыкание 5. Если замыкание возвращает `true`, то запишите значение элемента массива в эту переменную 6. В конце функции возвращайте переменную 7. Используя этот метод и замыкание найдите `максимальный` и `минимальный` элементы массива */ // MARK: - Task 3. Solution // ======================================= // ... // ======================================= // MARK: - Task 4 // ======================================= /* 1. Используя строку, проинициализированную ниже, рреобразуйте ее в массив символов 2. Используя метод sorted отсортируйте этот массив символов так, чтобы: - вначале шли гласные в алфавитном порядке, - потом согласные в алфавитном порядке, - потом цифры по порядку, - а только потом символы */ // MARK: - Task 4. Solution // ======================================= let vereVeryLongText = """ Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community, first released in 2014. Swift was developed as a replacement for Apple's earlier programming language Objective-C, as Objective-C had been largely unchanged since the early 1980s and lacked modern language features. Swift works with Apple's Cocoa and Cocoa Touch frameworks, and a key aspect of Swift's design was the ability to interoperate with the huge body of existing Objective-C code developed for Apple products over the previous decades. It is built with the open source LLVM compiler framework and has been included in Xcode since version 6, released in 2014. On Apple platforms, it uses the Objective-C runtime library which allows C, Objective-C, C++ and Swift code to run within one program. Apple intended Swift to support many core concepts associated with Objective-C, notably dynamic dispatch, widespread late binding, extensible programming and similar features, but in a "safer" way, making it easier to catch software bugs; Swift has features addressing some common programming errors like null pointer dereferencing and provides syntactic sugar to help avoid the pyramid of doom. Swift supports the concept of protocol extensibility, an extensibility system that can be applied to types, structs and classes, which Apple promotes as a real change in programming paradigms they term "protocol-oriented programming". Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It underwent an upgrade to version 1.2 during 2014 and a more major upgrade to Swift 2 at WWDC 2015. Initially a proprietary language, version 2.2 was made open-source software under the Apache License 2.0 on December 3, 2015, for Apple's platforms and Linux. Through version 3.0 the syntax of Swift went through significant evolution, with the core team making source stability a focus in later versions. In the first quarter of 2018 Swift surpassed Objective-C in measured popularity. Swift 4.0, released in 2017, introduced several changes to some built-in classes and structures. Code written with previous versions of Swift can be updated using the migration functionality built into Xcode. Swift 5, released in March 2019, introduced a stable binary interface on Apple platforms, allowing the Swift runtime to be incorporated into Apple operating systems. It is source compatible with Swift 4. Swift 5.1 was officially released in September 2019. Swift 5.1 builds on the previous version of Swift 5 by extending the stable features of the language to compile-time with the introduction of module stability. The introduction of module stability makes it possible to create and share binary frameworks that will work with future releases of Swift. """ // ... // ======================================= // MARK: - Task 5* // ======================================= /* 1. У Вас имеется массив с именами друзей `names`(проинициализирован ниже) 2. Реализуйте метод, который отсортирует данный массив по возрастанию количества букв в именах. 3. !!! Для этого пункта, Вам понадобится провести исследование в документации !!! С помощью замыкания преобразуйте массив `names` в словарь, в котором: - `key` - это количество символов в имени - `value` - это значение, которое получено из имени друга, где все символы отсортированы по убыванию (DACB -> DCBA) */ // MARK: - Task 5*. Solution // ======================================= let names: [String] = ["Arnold", "Kirill", "Julia", "Stacy", "Robin", "Jackie", "Emma", "Duncan", "Barbara"] // ...
b919e1b84e53cf735569458238c09d2cb9025d65
[ "Swift" ]
1
Swift
ArturSayfullayev/Closures
db9220e9481ad5b37a51450721c7b7d3964cdec3
51bbdc8322d2ca9cb2a3af4e1ff67a02ceac881f
refs/heads/master
<repo_name>chriseagle1/yii2-basic<file_sep>/commands/BootstrapWsController.php <?php namespace app\commands; use yii\console\Controller; use app\common\Websocket; /** * 启动websocket服务器端监听 */ class BootstrapWsController extends Controller { public function actionRun($host = '127.0.0.1', $port = '8888') { try { } catch(\Exception $e) { Yii::error($e->getMessage()); return false; } } } <file_sep>/views/poker/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Poker record</title> <link href="/css/poker.css" rel="stylesheet"> </head> <body> <div class="wrap"> <div class="poker-set"> <?php foreach ($all_poker as $key => $value) { ?> <div id="<?=$value?>" class="poker-list <?php if ($key == 0) { echo 'first-poker';}?>" style="background-image: url(/image/poker_pics/<?=$value?>.JPG);left:<?=($key*25+80);?>px"></div> <?php }?> </div> <div class="clear-float"></div> <div class="left-list player-area"> <div>left player:</div> </div> <div class="right-list player-area"> <div>right player:</div> </div> <div class="clear-float"></div> <div class="self-list"> <div>self list:</div> </div> </div> </body> <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/javascript" src="/js/poker.js"></script> </html><file_sep>/websocket_demo.php <?php include("ws.php"); $ws = new WS('10.5.103.39', '8888'); $ws->run(); <file_sep>/controllers/PokerController.php <?php namespace app\controllers; use Yii; use yii\web\Controller; class PokerController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ ]; } /** * @inheritdoc */ public function actions() { return [ ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { $this->layout = false; $pokerNum = [ '11', '21', '31', '41', '12', '22', '32', '42', '13', '23', '33', '43', '14', '24', '34', '44', '15', '25', '35', '45', '16', '26', '36', '46', '17', '27', '37', '47', '18', '28', '38', '48', '19', '29', '39', '49', '10', '20', '30', '40', '1a', '2a', '3a', '4a', '1b', '2b', '3b', '4b', '1c', '2c', '3c', '4c', 'Ki', 'Qu', ]; return $this->render('index', ['all_poker' => $pokerNum]); } } <file_sep>/common/ErrorAction.php <?php namespace app\common; use yii\base\Action; class ErrorAction extends Action { public function run() { return 'hello world'; } }<file_sep>/models/EntryForm.php <?php namespace app\models; use yii; use yii\base\Model; class EntryForm extends Model { public $name; public $email; public function rules() { return [ [['name', 'email', 'password'], 'required', 'on' => 'register'], [['name', 'password'], 'required', 'on' => 'login'], ['password', '<PASSWORD>'], ['email', 'email'] ]; } public function attributeLabels() { return [ 'name' => '姓名', 'email' => '邮箱' ]; } }<file_sep>/common/websocket.php <?php /** * websocket实现 * **/ namespace app\common; class Websocket { public $master; public $accept = []; public $cycle = []; public function __construct($addr = '127.0.0.1', $port = '8888') { $this->master = $this->WebSocket($addr, $port); // echo("Master socket : ".$this->master."\n"); $this->cycle[] = $this->master; } public function WebSocket($addr, $port) { $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($server, $addr, $port); socket_listen($server); return $server; } public function run() { while (true) { $write = NULL; $except = NULL; $changes = $this->cycle; // echo "wait\n"; // echo "changes:"; // var_dump($changes); socket_select($changes, $write, $except, NULL); // echo "have request\nselect_changes:"; // var_dump($changes); foreach($changes as $sock) { if($sock === $this->master) { $client = socket_accept($sock); if($client === false) { continue; } // echo "connect client\n"; $this->addAccept($client); } else { $len = 0; $buffer = ''; do { $preLen = socket_recv($sock, $pre_buf, 1024, 0); $len += $preLen; $buffer .= $pre_buf; } while($preLen == 1024); $socketId = $this->findSocket($sock); if ($len < 7) { //断开$socketId // echo 'msg_len:' . $len . "\n"; $this->closeConnect($socketId); // var_dump($this->cycle); continue; } if($this->accept[$socketId]['isHand'] !== false) {//已握手 // echo "have shaked\n"; //解码,输出 $decodeContent = $this->decode($buffer, $socketId); /*$cycleLen = strlen($buffer); for($i = 0; $i < $cycleLen; $i++) { echo ord($buffer[$i]) . "\n"; }*/ // echo ord($buffer[1]) . "\n"; // echo $decodeContent . "\n"; $output = $this->encode($decodeContent); socket_write($this->accept[$socketId]['socket'], $output, strlen($output)); } else {//未握手, 进行握手操作 // echo "shakeHands\n"; $this->shakehand($socketId, $buffer); } } } } } //连接池增加一个连接 private function addAccept($socket) { $this->cycle[] = $socket; $key = uniqid(); $this->accept[$key] = [ 'socket' => $socket, 'isHand' => false, ]; } //根据socket找到其对应的id private function findSocket($socket) { foreach($this->accept as $key => $accept) { if($socket === $accept['socket']) { return $key; } } return false; } //握手 public function shakeHand($socket_id, $buffer) { preg_match("/Sec-WebSocket-Key:(.*)\r\n/", $buffer, $matchs); $key = base64_encode(sha1(trim($matchs[1]) . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)); $upgrade = "HTTP/1.1 101 Switching Protocol\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept: " . $key . "\r\n\r\n"; socket_write($this->accept[$socket_id]['socket'], $upgrade, strlen($upgrade)); $this->accept[$socket_id]['isHand'] = true; return true; } public function closeConnect($socket_id) { socket_close($this->accept[$socket_id]['socket']); $index = array_search($this->accept[$socket_id]['socket'], $this->cycle); unset($this->accept[$socket_id]); unset($this->cycle[$index]); return true; } //对接收到的客户端数据进行解码 public function decode($str, $socket_id) { $opcode = ord(substr($str, 0, 1)) & 0x0F; //从客户端发来的信息一定有mask key,所以str[1]这个字节的第一位一定为1,通过"与"127,取到Payload length的长度 $payloadLen = ord(substr($str, 1, 1)) & 0x7F; $ismask = (ord(substr($str, 1, 1)) & 0x80) >> 7; $mask_key = $data = $decoded = null; if($ismask != 1 || $opcode == 0x8) {//根据websocket协议,客户端传来的数据,如果掩码不为1或者操作码为0x8,则直接关闭 $this->closeConnect($socket_id); return null; } if($payloadLen == 126) {//Payload length 长度即为7 + 16 bit //第一个字节中第一位为fin,2-4位为rsv,第5-8为为操作码,第二个字符中第一位为mask标志,2-8为原始负载长度 //原始负载长度为126时 负载长度扩展16bit, 即增加两个字节,所以0,1, 2,3字节都被占用,mask key从4开始取 $mask_key = substr($str, 4, 4); $data = substr($str, 8); } else if($payloadLen == 127){//Payload length 长度即为7 + 64 bit $mask_key = substr($str, 10, 4); $data = substr($str, 14); } else {//Payload length 长度即为7bit $mask_key = substr($str, 2, 4); $data = substr($str, 6); } $dataLen = strlen($data); for($i = 0; $i < $dataLen; $i++) { $decoded .= $data[$i] ^ $mask_key[$i%4]; } return $decoded; } //默认操作码为0x1 文本信息; /*其中 0x0 继续帧, 0x1 文本帧, 0x2 二进制帧, 0x3-0x7保留用于未来的非控制帧, 0x8连接关闭, 0x9 代表ping, 0xA代表pong , xB-xF 保留用于未来控制帧 */ public function encode($msg, $opcode = 0x1) { $firstByte = 0x80 | $opcode ; $encoded = null; $len = strlen($msg); if ($len >= 0) { if($len <= 125) { $encoded = chr($firstByte) . chr($len) . $msg; } else if($len <= 0xFFFF){ $low = $len & 0x00FF; $high = ($len & 0xFF00) >> 8; $encoded = chr($firstByte) . chr(0x7E) . chr($high) . chr($low) . $msg; } else { $low = $len & 0x00000000FFFFFFFF; $high = ($len & 0xFFFFFFFF00000000) >> 32; $pack = pack('NN', $high, $low); $encoded = chr($firstByte) . chr(0x7F) . $pack . $msg; } } return $encoded; } } <file_sep>/controllers/ChatController.php <?php namespace app\controllers; use Yii; use yii\web\Controller; class ChatController extends Controller { /** * 1 * (non-PHPdoc) * @see \yii\base\Object::init() */ public function init() { } /** * 2 * @inheritdoc */ public function actions() { return [ 'error' => '\app\common\ErrorAction' ]; } /** * 3 * (non-PHPdoc) * @see \yii\web\Controller::beforeAction() */ public function beforeAction($action) { return parent::beforeAction($action); } /** * 4 * @inheritdoc */ public function behaviors() { return [ ]; } /** * 6 * (non-PHPdoc) * @see \yii\base\Controller::afterAction() */ public function afterAction($action, $result) { $result = parent::afterAction($action, $result); // your custom code here return $result; } /** * 5 * Displays homepage. * * @return string */ public function actionIndex() { $this->layout = 'chat-main'; $this->view->registerCssFile('/css/chat.css', ['depends'=> 'app\assets\AppAsset']); $this->view->registerJsFile('/js/template.js', ['depends'=> 'app\assets\AppAsset']); $this->view->registerJsFile('/js/websocket.js', ['depends'=> 'app\assets\AppAsset']); return $this->render('index'); } } <file_sep>/web/js/websocket.js /** * */ var source = '<li class="self-send">' + '<div class="chat-avatar"></div>' + '<div class="trangle"></div>' + '<div class="chat-content">{{tmplData}}</div>' + '<div style="clear:both;"></div>' + '</li>'; $(document).ready(function(){ $('.operate-area').on('click', '#close', function(event) { event.preventDefault(); /* Act on the event */ }) .on('click', '#send', function(event) { event.preventDefault(); var input = $('.form-control'); var inputVal = input.val(); input.val(''); if (inputVal !== '') { var chatRender = template.compile(source); $('#record-list').append(chatRender({tmplData: inputVal})); $('.chat-record').scrollTop($('.chat-record')[0].scrollHeight); } else { alert('发送内容不能为空'); } }); $('.edit-area').on('keydown', '', function(event) { /* Act on the event */ if (event.keyCode == 13) { event.preventDefault(); $('#send').click(); }; }); });<file_sep>/controllers/VueTestController.php <?php namespace app\controllers; use Yii; use yii\web\Controller; class VueTestController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ ]; } /** * @inheritdoc */ public function actions() { return [ ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { $this->layout = false; return $this->render('index'); } public function actionUploadExcel() { $type = 'xlsx'; $file_path = ''; if ($type == 'xlsx' || $type == 'xls') { $reader = \PHPExcel_IOFactory::createReader('Excel2007'); // 读取 excel 文档 } else if ($type == 'csv') { $reader = \PHPExcel_IOFactory::createReader('CSV'); // 读取 CSV 文档 } else { die('Not supported file types!'); } $phpExcel = $reader->load($file_path); $objWorksheet = $phpExcel->getActiveSheet(); } }
6eea73594c19aa1341d04dc05e502196135886be
[ "JavaScript", "PHP" ]
10
PHP
chriseagle1/yii2-basic
914a03e193f9c90643fe6d13824d9f9dedfaf349
8897a173c1cd59399ad18f62d90ad6fc1ee480e7
refs/heads/master
<repo_name>pritpalxyz/scrapy-as-coa-articles<file_sep>/README.md #Scrapy Crawler for http://www.as-coa.org/region/united-states <file_sep>/as_coa_crawler/as_coa_crawler/items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class AsCoaCrawlerItem(scrapy.Item): # title = scrapy.Field() # main_image = scrapy.Field() # image_caption = scrapy.Field() # posted_date = scrapy.Field() # description = scrapy.Field() # related = scrapy.Field() # url = scrapy.Field() eventImage = scrapy.Field() organization = scrapy.Field() # (text format) title = scrapy.Field() #(text format) description = scrapy.Field() #(html format) eventWebsite = scrapy.Field() # url/link - text format) street = scrapy.Field() #(text format) city = scrapy.Field() #(text format) state = scrapy.Field() #(text format) zip = scrapy.Field() #numeric format xxxxx) dateFrom = scrapy.Field() #(REQUIRED FORMAT: dd/mm/yyyy) startTime = scrapy.Field() #(REQUIRED FORMAT: hh:mm am/pm) In_group_id = scrapy.Field() ticketUrl = scrapy.Field() #(url/link - text format) <file_sep>/as_coa_crawler/as_coa_crawler/spiders/as_coa.py # -*- coding: utf-8 -*- import scrapy, re from bs4 import BeautifulSoup from as_coa_crawler.items import AsCoaCrawlerItem class AsCoaSpider(scrapy.Spider): name = "as_coa" allowed_domains = ["as-coa.org"] start_urls = ['http://www.as-coa.org/region/united-states/'] # DECLARING CONSTRUCTOR FOR PRE - CALLING # XPATH DECLARING METHOD def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.DeclareXpath() # METHOD FOR REMOVING UNWANTED CHARACTER FROM STRING def parseText(self, str): soup = BeautifulSoup(str, 'html.parser') return re.sub(" +|\n|\r|\t|\0|\x0b|\xa0",' ',soup.get_text()).strip() # METHOD FOR CONVERTING LIST OF STRING TO SIMPLE STRING AND FILTRING def filterStr(self, listOfStr): dummy_string = " ".join(unicode(content) for content in data_list) return self.parseText(dummy_string) # METHOD FOR DECLARING ALL XPATH VARIABLES THAT # WILL BE USED FOR PARSING VALUES FROM PAGE def DeclareXpath(self): self.LIST_OF_EVENTS_XPATH = "//h1[@class='internal-title event']/a/@href" self.TITLE_XPATH = "//h1[@class='page-title bc']/text()" self.ARTICLE_IMAGE_XPATH = "//div[@class='article-hero']/img/@src" self.ARTICLE_IMAGE_CAPTION_XPATH = "//div[@class='article-hero']/p/text()" self.ARTICLE_DATE_XPATH = "//div[@class='field-item even']//span[@class='date-display-single']/text()" self.ARTICLE_DESCRIPTION_XPATH = "//div[@class='field-item even']" self.RELATED_XPATH = "//p[@class='related-tags']/span/a/text()" self.NEXT_PAGE_XPATH = "//li[@class='pager-next']/a/@href" # METHOD FOR PARSING LIST OF EVENT FROM PAGE def parse(self, response): for href in response.xpath(self.LIST_OF_EVENTS_XPATH): full_url = response.urljoin(href.extract()) yield scrapy.Request(full_url, callback=self.ParseEventDeep) # CALLING NEXT PAGE FROM LIST OF ARTICLE PAGE # AND RECALL CURRENT METHOD AGAIN FOR PARSING # ALL AVAILABLE ARTICLES next_page = response.xpath(self.NEXT_PAGE_XPATH) if next_page: url = response.urljoin(next_page[0].extract()) yield scrapy.Request(url,callback=self.parse) # PARSING ARTICLE PAGE ALL VALUES # AND STORING PASSING INTO ITEMS CLASS def ParseEventDeep(self, response): item = AsCoaCrawlerItem() item['eventImage'] = response.xpath(self.ARTICLE_IMAGE_XPATH).extract() item['organization'] = '' item['title'] = response.xpath(self.TITLE_XPATH).extract() item['description'] = response.xpath(self.ARTICLE_DESCRIPTION_XPATH).extract() item['eventWebsite'] = 'as-coa.org' item['street'] = '' item['city'] = '' item['state'] = response.xpath(self.RELATED_XPATH).extract() item['zip'] = '' item['dateFrom'] = response.xpath(self.ARTICLE_DATE_XPATH).extract() item['startTime'] = '' item['In_group_id'] = '' item['ticketUrl'] = response.url yield item
ca5739efb3204aed6798e3c7c8e62bf1d638ce37
[ "Markdown", "Python" ]
3
Markdown
pritpalxyz/scrapy-as-coa-articles
943279a8ab0783457194c6d57109fd2136c2be4f
6b6bf13f66f7e7d7f03f95c3307e13046e1e72ff
refs/heads/master
<repo_name>DeLaSalleUniversity-Manila-LBYEC72-t216/HelloFromAngelaNebres<file_sep>/README.md ``` #include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { printf("\t \t @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \n"); printf(" \t \t <NAME> \n \t \t BS CHE \n \t \t 11400835 \n \t \t May 24, 2016 \n \t \t <EMAIL> \n \t \t 09054545 \n"); printf("\t \t @@@@@@@@@@@@@@@@@@@@@@@@@@@@"); return 0; } ``` ![](13317027_1727552700857046_1247456461637175095_o.jpg) ![](13315238_1727552107523772_4529268780073210701_n.jpg) ![](13332818_1727552110857105_6819057669612785189_n.jpg) ![](13336002_1727552104190439_3483871042552375771_n.jpg) <file_sep>/HELLO.c #include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { printf("\t \t @@@@@@@@@@@@@@@@@@@@@@@@@@@@ \n"); printf(" \t \t <NAME> \n \t \t BS CHE \n \t \t 11400835 \n \t \t May 24, 2016 \n \t \t <EMAIL> \n \t \t 09054545 \n"); printf("\t \t @@@@@@@@@@@@@@@@@@@@@@@@@@@@"); return 0; } ![](SCREENS.PNG)
af0da356be92e8a93e302ed08ac9df5874f01457
[ "Markdown", "C" ]
2
Markdown
DeLaSalleUniversity-Manila-LBYEC72-t216/HelloFromAngelaNebres
8cf05086fa2f432a1ab2b072160844bca378eb87
b3e0ac3c0d419c99702487df80561931a9f7d304
refs/heads/main
<repo_name>boksfisika/project_wordpress<file_sep>/functions.php <?php /* * Add my new menu to the Admin Control Panel */ // Hook the 'admin menu' action hook, run the function named 'mfp_Add_My_Admin_Link()' include 'index_url.php'; add_action( 'admin_menu', 'pp_Tambah_Link_Admin' ); // Add a new top level menu link to the ACP function pp_Tambah_Link_Admin() { add_menu_page( 'Title', // Judul dari halaman 'produk', // Tulisan yang ditampilkan pada menu 'manage_options', // Persyaratan untuk dapat melihat link 'my-plugin-page', // slug dari file untuk menampilkan halaman ketika menu link diklik. 'tampil', '', //icon 2 ); } // untuk menampilkan menu function tampil() { require_once 'product.php'; } add_action('admin_menu', 'register_custom_submenu'); function register_custom_submenu() { add_submenu_page( 'my-plugin-page', 'slug', 'harga', 'administrator', 'custom-submenu', 'harga' ); } // untuk menampilkan sub menu function harga() { require_once 'harga.php'; } // untuk menghapus submenu function wpdocs_adjust_the_wp_menu() { $page = remove_submenu_page( 'index.php', 'update-core.php' ); } add_action( 'admin_menu', 'wpdocs_adjust_the_wp_menu', 999 ); function delete_plugin() { $page = remove_menu_page( 'plugins.php', 'plugins.php' ); } add_action( 'admin_menu', 'delete_plugin', 999 ); // icon title web add_action( 'wp_head', 'prefix_favicon', 100 ); add_action( 'admin_head', 'prefix_favicon', 100 ); add_action( 'wp_head', 'prefix_favicon', 100 ); function prefix_favicon() { //code of the favicon logic ?> <link rel="icon" href="https://d33wubrfki0l68.cloudfront.net/89d21e1f2a17001aa475773cbb3e47639494d4c9/475b1/img/logo.svg"> <?php } // remove admin logo // Replace Wordpress logo with custom Logo function my_custom_logo() { echo ' <style type="text/css"> #wp-admin-bar-kodeo-admin > .ab-item { content: url('. DIR_PLUGIN_CUSTOM . 'assets/images/logo.png)!important; } .edit-post-fullscreen-mode-close.has-icon > svg{ display:none; } .edit-post-fullscreen-mode-close.has-icon{ content: url('. DIR_PLUGIN_CUSTOM . 'assets/images/logo.png)!important; background: none; } #wp-admin-bar-wp-logo.hover > .ab-item .ab-icon { background-position: 0 0; } </style> '; } add_action('admin_head', 'my_custom_logo'); add_action('wp_head', 'my_custom_logo'); function remove_admin_bar_links() { global $wp_admin_bar; $wp_admin_bar->remove_menu('about'); // Remove the about WordPress link $wp_admin_bar->remove_menu('wporg'); // Remove the WordPress.org link $wp_admin_bar->remove_menu('documentation'); // Remove the WordPress documentation link $wp_admin_bar->remove_menu('support-forums'); // Remove the support forums link $wp_admin_bar->remove_menu('feedback'); // Remove the feedback link } add_action( 'wp_before_admin_bar_render', 'remove_admin_bar_links' ); add_action( 'load-index.php', 'hide_welcome_screen' ); function hide_welcome_screen() { $user_id = get_current_user_id(); if ( 1 == get_user_meta( $user_id, 'show_welcome_panel', true ) ) update_user_meta( $user_id, 'show_welcome_panel', 0 ); } add_action('admin_head', 'mytheme_remove_help_tabs'); function mytheme_remove_help_tabs() { $screen = get_current_screen(); $screen->remove_help_tabs(); } add_filter('screen_options_show_screen', '__return_false'); add_action('wp_dashboard_setup', 'themeprefix_remove_dashboard_widget' ); /** * Remove Site Health Dashboard Widget * */ function themeprefix_remove_dashboard_widget() { remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' ); } function remove_dashboard_meta() { remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal'); //Removes the 'incoming links' widget remove_meta_box('dashboard_plugins', 'dashboard', 'normal'); //Removes the 'plugins' widget remove_meta_box('dashboard_primary', 'dashboard', 'normal'); //Removes the 'WordPress News' widget remove_meta_box('dashboard_secondary', 'dashboard', 'normal'); //Removes the secondary widget remove_meta_box('dashboard_recent_drafts', 'dashboard', 'side'); //Removes the 'Recent Drafts' widget remove_meta_box('dashboard_right_now', 'dashboard', 'normal'); //Removes the 'At a Glance' widget } add_action('admin_init', 'remove_dashboard_meta'); <file_sep>/harga.php <div class="wrap"> <h1>harga</h1> <p>This is my plugin's first page</p> <p></p> </div> <?php echo plugin_dir_path(__FILE__). ''; ?><file_sep>/index_url.php <?php define('DIR_PLUGIN_CUSTOM', plugin_dir_url(__FILE__));
63518b7e967249bd776edd601956f6387c7dfa66
[ "PHP" ]
3
PHP
boksfisika/project_wordpress
0408c0e554ed7e627ad58d4b3721f3721ace0c58
a4a5286078dc414a22ca44d1ab3714e0e21ca059
refs/heads/master
<repo_name>cHuberCoffee/bt_differential_cryptanalysis_of_simpirav1<file_sep>/code/SimpiraA.h #ifndef SIMPIRAA_H #define SIMPIRAA_H #include <iostream> #include <fstream> #include <functional> #include <string.h> #include <stdint.h> #include <unordered_map> #include <vector> #include <wmmintrin.h> // for intrinsics for AES-NI #include "AesOp.h" #include "Simpira.h" namespace sa { class SimpiraA { private: static const uint8_t ui_difference [sizeof(__m128i)]; static const uint8_t ui_single_diff; public: SimpiraA(); bool search2RoundDiffs(uint64_t diag); void static searchABDiffs(uint64_t start_range, uint64_t stop_range, std::vector<uint32_t>& r); void searchInitStructA3(uint32_t valid_diagonal); void searchInitStructA5(uint32_t valid_diagonal); void static createTableForRound8(uint32_t start_range, uint32_t stop_range, RoundBlocks constants, std::unordered_map<uint32_t, __m128i>& r); void static searchInTableForRound8(std::vector<RoundBlocks>& r, std::vector<uint32_t>& diags, uint32_t start_range, uint32_t stop_range, RoundBlocks constants, std::unordered_map<uint32_t, __m128i>& table); }; } #endif <file_sep>/code/AesOp.cpp #include "AesOp.h" __m128i aesEnc(__m128i input, __m128i key) { return _mm_aesenc_si128(input, key); } __m128i aesDec(__m128i input, __m128i key) { return _mm_aesdec_si128(input, key); } __m128i aesDecLast(__m128i input, __m128i key) { return _mm_aesdeclast_si128(input, key); } __m128i aesImc(__m128i input) { return _mm_aesimc_si128(input); } __m128i aesInvert(__m128i input, __m128i key) { return aesDecLast(aesImc(_mm_xor_si128(input, key)), _mm_setzero_si128()); } <file_sep>/code/Makefile EXECUTABLE = simpira SOURCES = $(wildcard *.cpp) OBJECTS = $(patsubst %,%,${SOURCES:.cpp=.o}) CXX = g++ CXXFLAGS = -Wall -O0 -g -c -msse2 -msse -march=native -maes -std=c++11 -o LDFLAGS = -pthread LDLIBS = #------------------------------------------------------------------------------- #make executable all: $(EXECUTABLE) %.o: %.cpp $(CXX) $(CXXFLAGS) $@ $< -MMD -MF ./$@.d #link Objects $(EXECUTABLE) : $(OBJECTS) $(CXX) -o $@ $^ $(LDFLAGS) run: ./simpira $T #make clean clean: rm -f ./*.o rm -f ./*.o.d rm -f ./*.bin rm -f $(EXECUTABLE) #The dependencies: -include $(wildcard *.d) <file_sep>/code/AesOp.h #ifndef AESOP_H #define AESOP_H #include <wmmintrin.h> // for intrinsics for AES-NI __m128i aesEnc(__m128i input, __m128i key); __m128i aesDec(__m128i input, __m128i key); __m128i aesDecLast(__m128i input, __m128i key); __m128i aesImc(__m128i input); __m128i aesInvert(__m128i input, __m128i key); #endif <file_sep>/code/SimpiraC.cpp #include "SimpiraC.h" using sa::SimpiraC; using std::cout; using std::endl; using std::setfill; using std::setw; using std::hex; using std::dec; SimpiraC* SimpiraC::instance = 0; /** * ctor */ SimpiraC::SimpiraC() : threads_in_use(1){ attacks = new SimpiraA(); } /** * search 2^32 values as the diagonal (S1, S6, S11, S12) with the given differences * and double check it with simpira 2 rounds. The successful values are saved in * vector of uint32_t */ void SimpiraC::search2RoundDiffs() { cout << "[search2RoundDiffs] Search for the diffs" << endl; uint32_t ranges = 0; uint32_t to_search = UINT32_MAX; uint32_t range = to_search / threads_in_use; uint32_t rest = to_search - (threads_in_use * range); std::vector<std::thread> search_threads; std::vector<uint32_t> results [threads_in_use]; for (unsigned int i = 0; i < threads_in_use; i++) { uint32_t start_range = ranges; if (i == (threads_in_use - 1)) ranges = ranges + range + rest + 1; else ranges += range; uint32_t stop_range = (ranges - 1); search_threads.push_back(std::thread(&(attacks->searchABDiffs), start_range, stop_range, std::ref(results[i]))); } for (auto &t : search_threads) t.join(); for (std::vector<uint32_t> r : results) { diff_r2_results.insert(diff_r2_results.end(), r.begin(), r.end()); } cout << "[search2RoundDiffs] Found nr. of valuse: " << diff_r2_results.size() << endl; for (auto &val : diff_r2_results) cout << "[search2RoundDiffs] Value: " << dec << val << " (" << setfill('0') << setw(8) << hex << val << ") as diagonal" << endl; for (auto it = diff_r2_results.begin(); it!= diff_r2_results.end(); it++) { if (!attacks->search2RoundDiffs(*it)) { cout << "[search2RoundDiffs] Delete " << *it << " from vector" << endl; diff_r2_results.erase(it); } } } /** * the blocks C5, A3, C3, A1 must contain valid diagonals. * A1 = C3 * A3 = C5 * this means by setting a valid diagonal of A3 & C3 and computing back * to the start of simpira we get a valid inital struct */ void SimpiraC::searchRound3_5InitStruct() { uint32_t valid_diagonal = 3379824225; // for now hardcorded! // uint32_t valid_diagonal = this->diff_r2_results[15]; cout << "[searchInitStruct] Use " << valid_diagonal << " (" << setfill('0') << setw(8) << hex << valid_diagonal << ") as diagonal" << endl; attacks->searchInitStructA3(valid_diagonal); attacks->searchInitStructA5(valid_diagonal); cout << "[searchInitStruct] Done" << endl; } /** * searching a init-struct such that A7 & C9 contain a valid diagonal * A7 = C 9 * to achieve content of A5 and C5 must be varied and D5_MC2 and A6_MC2 * must match in the diagonal. This results a cancelation of the diagonal * and the diagonal of C5 is passed directly to A7 */ void SimpiraC::search8RoundInitStruct() { uint32_t to_search = (UINT16_MAX); // uint32_t to_search = (UINT16_MAX * 256); /*2^24*/ uint32_t ranges = 0; uint32_t range = to_search / threads_in_use; uint32_t rest = to_search - (threads_in_use * range); for (uint32_t valid_diagonal : diff_r2_results) { diag_map.clear(); std::vector<std::thread> creater_threads; std::unordered_map<uint32_t, __m128i> results [threads_in_use]; std::vector<RoundBlocks> vec_res [threads_in_use]; cout << "[search8RoundInitStruct] Use " << dec << valid_diagonal << " (" << setfill('0') << setw(8) << hex << valid_diagonal << ") as diagonal" << endl; RoundBlocks constants = RoundBlocks(); constants.setDiag(valid_diagonal, RoundBlocks::b_B); constants.setDiag(valid_diagonal, RoundBlocks::b_D); constants.setBlockA(constants.getBlockB()); for (unsigned int i = 0; i < threads_in_use; i++) { uint32_t start_range = ranges; if (i == (threads_in_use - 1)) ranges = ranges + range + rest + 1; else ranges += range; uint32_t stop_range = (ranges - 1); creater_threads.push_back(std::thread(&(attacks->createTableForRound8), start_range, stop_range, constants, std::ref(results[i]))); } for (auto &t : creater_threads) t.join(); creater_threads.clear(); for (std::unordered_map<uint32_t, __m128i> r : results) diag_map.insert(r.begin(), r.end()); /* ----------------- SEARCH PART ----------------- */ ranges = 0; for (unsigned int i = 0; i < threads_in_use; i++) { uint32_t start_range = ranges; if (i == (threads_in_use - 1)) ranges = ranges + range + rest + 1; else ranges += range; uint32_t stop_range = (ranges - 1); creater_threads.push_back(std::thread(&(attacks->searchInTableForRound8), std::ref(vec_res[i]), std::ref(diff_r2_results), start_range, stop_range, constants, std::ref(diag_map))); } for (auto &t : creater_threads) t.join(); for (std::vector<RoundBlocks> r : vec_res) is_8_round.insert(is_8_round.end(), r.begin(), r.end()); } cout << "[search8RoundInitStruct] Found Structs: " << std::dec << is_8_round.size() << endl; cout << "[search8RoundInitStruct] Done" << endl; } /* GETTER & SETTER -----------------------------------------------------------*/ void SimpiraC::setThreadsInUse(unsigned int nr_threads) { if (nr_threads > 150) this->threads_in_use = 150; else this->threads_in_use = nr_threads; cout << "[SimpiraC] set " << threads_in_use << " threads" << endl; } unsigned int SimpiraC::getThreadsInUse() { return this->threads_in_use; } SimpiraC* SimpiraC::getInstance() { if (!instance) instance = new SimpiraC(); return instance; } <file_sep>/code/SimpiraA.cpp #include "SimpiraA.h" using sa::SimpiraA; using std::cout; using std::endl; using std::ifstream; using std::ios; const uint8_t SimpiraA::ui_difference[] = {0xcd, 0xcd, 0x4c, 0x81, 0x61, 0xa3, 0xc2, 0x61, 0xa3, 0xc2, 0x61, 0x61, 0x56, 0x2b, 0x2b, 0x7d}; const uint8_t SimpiraA::ui_single_diff = 0x40; SimpiraA::SimpiraA(){ } /** * calculates two rounds of simpira and check the resulting differences against * the input differences * @param diag [description] * @return if differences the same -> return true */ bool SimpiraA::search2RoundDiffs(uint64_t diag) { RoundBlocks a = RoundBlocks(); RoundBlocks b = RoundBlocks(); a.setDiag((uint32_t)diag, RoundBlocks::b_A); b.setDiag((uint32_t)diag, RoundBlocks::b_A); b.setBlockB(ui_difference, sizeof(ui_difference)); b.setConstDiff(RoundBlocks::b_A, ui_single_diff); b.setConstDiff(RoundBlocks::b_C, ui_single_diff); RoundBlocks prev_diff = a ^ b; simpiraXRounds(std::ref(a), 2, 1); simpiraXRounds(std::ref(b), 2, 1); RoundBlocks after_diff = a ^ b; if (prev_diff == after_diff) return true; return false; } /** * fast search for the given diff. Uses only one simpira roundfunction call * and checks the resulting difference * @param start_range [description] * @param stop_range [description] * @param r [description] */ void SimpiraA::searchABDiffs(uint64_t start_range, uint64_t stop_range, std::vector<uint32_t>& r) { for (uint64_t i = start_range; i <= stop_range; i++) { RoundBlocks a = RoundBlocks(); RoundBlocks b = RoundBlocks(); RoundBlocks diff = RoundBlocks(); diff.setBlockA(ui_difference, sizeof(ui_difference)); a.setDiag(i, RoundBlocks::b_A); b.setDiag(i, RoundBlocks::b_A); b.setConstDiff(RoundBlocks::b_A, ui_single_diff); a.setBlockA(roundFunction(a.getBlockA(), _mm_setzero_si128(), 1, 4)); b.setBlockA(roundFunction(b.getBlockA(), _mm_setzero_si128(), 1, 4)); a = a ^ b; if (a == diff) r.push_back(i); } } /** * using the invers round function of Simpira to calculate input structs which * leads to valid diagonals in A3 and C5 * @param valid_diagonal [description] */ void SimpiraA::searchInitStructA3(uint32_t valid_diagonal) { RoundBlocks init = RoundBlocks(); init.setDiag(valid_diagonal, RoundBlocks::b_A); init.setDiag(valid_diagonal, RoundBlocks::b_C); simpiraInvXRounds(init, 2, 4); cout << "Init struct for A3: " << endl << init << endl; simpiraXRounds(std::ref(init), 2, 1); cout << "Init struct after 2 rounds: " << endl << init << endl; } /** * using the invers round function of Simpira to calculate input structs which * leads to valid diagonals in A5 and C7 * @param valid_diagonal [description] */ void SimpiraA::searchInitStructA5(uint32_t valid_diagonal) { RoundBlocks round5 = RoundBlocks(); round5.setDiag(valid_diagonal, RoundBlocks::b_A); round5.setDiag(valid_diagonal, RoundBlocks::b_C); RoundBlocks round4 = RoundBlocks(); RoundBlocks round3 = RoundBlocks(); round4.setBlockA(inversRoundFunction(round4.getBlockA(), _mm_setzero_si128(), 7, 4)); round4.setBlockB(round5.getBlockA()); round4.setBlockD(round5.getBlockC()); round3.setDiag(valid_diagonal, RoundBlocks::b_C); round3.setBlockD(inversRoundFunction(round3.getBlockD(), _mm_setzero_si128(), 6, 4)); round4.setBlockC(round3.getBlockD()); round3.setBlockA(round4.getBlockD()); round3.setBlockB(roundFunction(round3.getBlockA(), round4.getBlockA(), 5, 4)); round3.setBlockC(roundFunction(round3.getBlockD(), round4.getBlockB(), 6, 4)); simpiraInvXRounds(round3, 2, 4); RoundBlocks init = round3; cout << "Init struct for A5: " << endl << init << endl; simpiraXRounds(std::ref(init), 4, 1); cout << "Init struct after 4 rounds: " << endl << init << endl; } /** * create a table with @stop_range - @start_range elements containig the __m128i of block * A6_MC2 which get randomizd by varying the free bytes of A5 * @param start_range [description] * @param stop_range [description] * @param constants [description] * @param r [description] */ void SimpiraA::createTableForRound8(uint32_t start_range, uint32_t stop_range, RoundBlocks constants, std::unordered_map<uint32_t, __m128i>& r) { for (uint64_t i = start_range; i <= stop_range; i++) { constants.varyA5(); RoundBlocks tmp = RoundBlocks(); tmp.setBlockA(roundFunction(constants.getBlockA(), constants.getBlockC(), 9, 4)); tmp.setBlockB(roundFunction(tmp.getBlockA(), _mm_setzero_si128(), 11, 4)); r.insert({tmp.extractDiag(RoundBlocks::b_B), tmp.getBlockB()}); } } /** * calculate @max_elements times D5_MC2 and test it against the already created * @param r [description] * @param diags [description] * @param start_range [description] * @param stop_range [description] * @param constants [description] * @param table [description] */ void SimpiraA::searchInTableForRound8(std::vector<RoundBlocks>& r, std::vector<uint32_t>& diags, uint32_t start_range, uint32_t stop_range, RoundBlocks constants, std::unordered_map<uint32_t, __m128i>& table) { uint32_t const_diag = constants.extractDiag(RoundBlocks::b_B); for (uint64_t i = start_range; i <= stop_range; i++) { constants.varyC5(); RoundBlocks tmp = RoundBlocks(); tmp.setBlockA(roundFunction(constants.getBlockD(), constants.getBlockC(), 8, 4)); //c4 tmp.setBlockB(roundFunction(tmp.getBlockA(), constants.getBlockB(), 6, 4)); //b4 tmp.setBlockC(_mm_xor_si128(tmp.getBlockB(), constants.getBlockA())); //a4_mc2 tmp.setBlockC(inversRoundFunction(tmp.getBlockC(), _mm_setzero_si128(), 7, 4)); //d5 tmp.setBlockD(roundFunction(tmp.getBlockC(), _mm_setzero_si128(), 10, 4)); //d5_mc2 uint32_t created_diag = tmp.extractDiag(RoundBlocks::b_D); for (uint32_t valid_diag : diags) { uint32_t wanted_match = valid_diag ^ const_diag ^ created_diag; RoundBlocks round5 = RoundBlocks(); try { round5.setBlockA(table.at(wanted_match)); } catch (const std::out_of_range& oor) { continue; } round5.setBlockB(constants.getBlockC()); round5.setBlockC(constants.getBlockD()); round5.setBlockD(tmp.getBlockC()); round5.setBlockA(inversRoundFunction(round5.getBlockA(), _mm_setzero_si128(), 11, 4)); round5.setBlockA(inversRoundFunction(round5.getBlockA(), round5.getBlockB(), 9, 4)); RoundBlocks init = round5; simpiraInvXRounds(std::ref(init), 4, 8); simpiraXRounds(std::ref(round5), 2, 9); if ((init.extractDiag(RoundBlocks::b_A) == const_diag) && (round5.extractDiag(RoundBlocks::b_A) == valid_diag)) r.push_back(init); } } } <file_sep>/code/SimpiraC.h #ifndef SIMPIRAC_H #define SIMPIRAC_H #include <iostream> #include <iomanip> #include <vector> #include <unordered_map> #include <utility> #include <thread> #include <wmmintrin.h> // for intrinsics for AES-NI #include <stdint.h> #include "SimpiraA.h" #include "Simpira.h" #include "RoundBlocks.h" /* Byte-layout in the m128i | | | | S0 | S1 | S2 | S3 | S4 | S5 | S6 | S7 | S8 | S9 | S10 | S11 | S12 | S13 | S14 | S15 uint8_t test[] = {0x32, 0x00, 0xf6, 0xa8, 0x88, 0x5a, 0x00, 0x8d, 0x31, 0x31, 0x98, 0x00, 0x00, 0x37, 0x07, 0x34, Block A 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34, Block B 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34, Block C 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34}; Block D */ namespace sa { class SimpiraC { private: static SimpiraC* instance; unsigned int threads_in_use; SimpiraA* attacks; std::vector<uint32_t> diff_r2_results; std::unordered_map<uint32_t, __m128i> diag_map; std::vector<RoundBlocks> is_8_round; SimpiraC(); public: static SimpiraC* getInstance(); void search2RoundDiffs(); void searchRound3_5InitStruct(); void search8RoundInitStruct(); /* GETTER & SETTER*/ void setThreadsInUse(unsigned int nr_threads); unsigned int getThreadsInUse(); }; } #endif <file_sep>/code/Simpira.h #ifndef SIMPIRA_H #define SIMPIRA_H #include <iostream> #include <wmmintrin.h> #include <stdint.h> #include "AesOp.h" #include "RoundBlocks.h" __m128i roundFunction(__m128i i, __m128i k, uint8_t c, uint8_t b); __m128i inversRoundFunction(__m128i i, __m128i k, uint8_t c, uint8_t b); void simpiraXRounds(RoundBlocks& blocks, uint8_t rounds, uint8_t c); void simpiraInvXRounds(RoundBlocks& blocks, uint8_t rounds, uint8_t c); #endif <file_sep>/code/main.cpp #include <iostream> #include <chrono> #include "SimpiraC.h" using std::cout; using std::endl; using sa::SimpiraC; int main(int argc, char **argv) { cout << "[main] Start" << endl; SimpiraC* sc = SimpiraC::getInstance(); if (argc < 2 || argc > 2) { cout << "usage: ./simpira <NUMBER OF THREADS>" << endl; return -1; } int th = 1; std::string arg = argv[1]; try { size_t pos; th = std::stoi(arg, &pos); if (pos < arg.size()) { std::cerr << "Trailing characters after number: " << arg << '\n'; return -1; } if (th > 150) throw std::out_of_range(""); } catch (std::invalid_argument const &ex) { std::cerr << "Invalid number: " << arg << '\n'; return -1; } catch (std::out_of_range const &ex) { std::cerr << "Number out of range (max 150): " << arg << '\n'; return -1; } if (th <= 0) { cout << "Invalid number: " << th << endl; return -1; } std::chrono::seconds dur_s; std::chrono::minutes dur_m; auto start = std::chrono::high_resolution_clock::now(); sc->setThreadsInUse(th); sc->search2RoundDiffs(); sc->searchRound3_5InitStruct(); sc->search8RoundInitStruct(); auto end = std::chrono::high_resolution_clock::now(); dur_m = std::chrono::duration_cast<std::chrono::minutes> (end - start); dur_s = std::chrono::duration_cast<std::chrono::seconds> (end - start - dur_m); cout << std::dec; cout << "[main] time: " << (unsigned int) dur_m.count() << " min " << (unsigned int) dur_s.count() << " s" << endl; return 0; } <file_sep>/code/RoundBlocks.h #ifndef ROUNDBLOCKS_H #define ROUNDBLOCKS_H #include <iostream> #include <fstream> #include <iomanip> #include <algorithm> #include <mutex> #include <wmmintrin.h> #include <stdint.h> #include <assert.h> #include <random> class RoundBlocks { private: enum byte_t { S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15 }; __m128i m_blocks[4]; bool readURandom(uint8_t* data, uint8_t size); public: /*Block A == constant A5*/ /*Block B == constant C3*/ /*Block C == constant B5*/ /*Block D == constant C5*/ enum block_t { b_A , b_B, b_C, b_D }; RoundBlocks(); RoundBlocks(const RoundBlocks &obj); RoundBlocks(const __m128i src_a, const __m128i src_b, const __m128i src_c, const __m128i src_d); RoundBlocks(const __m128i src[], const uint8_t size); RoundBlocks(const uint8_t* src_a, const uint8_t* src_b, const uint8_t* src_c, const uint8_t* src_d); RoundBlocks(const uint8_t* src, const uint8_t size); RoundBlocks& operator=(const RoundBlocks& obj); RoundBlocks operator^(const RoundBlocks& obj); bool operator==(const RoundBlocks& obj); bool operator!=(const RoundBlocks& obj); friend std::ostream& operator<<(std::ostream& os, const RoundBlocks& obj); void setDiag(uint32_t i, block_t bl); void setConstDiff(block_t bl, uint8_t s12_diff); void setConstDiff(block_t bl, const uint8_t *block_diff); uint32_t extractDiag(block_t bl); void varyA5(); void varyC5(); __m128i getBlockA() const; __m128i getBlockB() const; __m128i getBlockC() const; __m128i getBlockD() const; void getBlocks(__m128i dest[], uint8_t size) const; void getBlockA(uint8_t* dest, uint8_t size) const; void getBlockB(uint8_t* dest, uint8_t size) const; void getBlockC(uint8_t* dest, uint8_t size) const; void getBlockD(uint8_t* dest, uint8_t size) const; void getBlocks(uint8_t* dest, uint8_t size) const; void setBlockA(const __m128i src); void setBlockB(const __m128i src); void setBlockC(const __m128i src); void setBlockD(const __m128i src); void setBlocks(const __m128i src[], const uint8_t size); void setBlockA(const uint8_t* src, const uint8_t size); void setBlockB(const uint8_t* src, const uint8_t size); void setBlockC(const uint8_t* src, const uint8_t size); void setBlockD(const uint8_t* src, const uint8_t size); void setBlocks(const uint8_t* src, const uint8_t size); }; #endif <file_sep>/code/Simpira.cpp #include "Simpira.h" /** * round function of simpira * @param input [description] * @param key [description] * @param c [description] * @param b [description] * @return [description] */ __m128i roundFunction(__m128i input, __m128i key, uint8_t c, uint8_t b) { __m128i C = _mm_setr_epi32(c, b, 0, 0); return aesEnc(aesEnc(input, C), key); } /** * invert the round function of simpira * @param input [description] * @param key [description] * @param c [description] * @param b [description] * @return [description] */ __m128i inversRoundFunction(__m128i input, __m128i key, uint8_t c, uint8_t b) { __m128i C = _mm_setr_epi32(c, b, 0, 0); return aesInvert(aesInvert(input, key), C); } /** * calculate x rounds of simpira in forward direction * @param blocks [description] * @param rounds [description] * @param c [description] */ void simpiraXRounds(RoundBlocks& blocks, uint8_t rounds, uint8_t c) { assert((rounds > 0) && (c > 0)); uint8_t b = 4; RoundBlocks tmp = RoundBlocks(); for (uint8_t r = 0; r < rounds; r++) { tmp.setBlockA(roundFunction(blocks.getBlockA(), blocks.getBlockB(), c++, b)); tmp.setBlockB(roundFunction(blocks.getBlockD(), blocks.getBlockC(), c++, b)); tmp.setBlockC(blocks.getBlockD()); tmp.setBlockD(blocks.getBlockA()); blocks = tmp; } } /** * invert x rounds of simpira * @param blocks [description] * @param rounds [description] * @param c [description] */ void simpiraInvXRounds(RoundBlocks& blocks, uint8_t rounds, uint8_t c) { assert((rounds > 0) && (c > 0)); uint8_t b = 4; RoundBlocks tmp = RoundBlocks(); for (uint8_t r = rounds; r != 0; --r) { tmp.setBlockA(blocks.getBlockD()); tmp.setBlockD(blocks.getBlockC()); tmp.setBlockC(roundFunction(tmp.getBlockD(), blocks.getBlockB(), c--, b)); tmp.setBlockB(roundFunction(tmp.getBlockA(), blocks.getBlockA(), c--, b)); blocks = tmp; } } <file_sep>/code/RoundBlocks.cpp #include "RoundBlocks.h" /** * std ctor */ RoundBlocks::RoundBlocks(){ for (uint8_t i = 0; i < 4; i++) { m_blocks[i] = _mm_setzero_si128(); } } /** * copy-ctor * @param obj [description] */ RoundBlocks::RoundBlocks(const RoundBlocks &obj) { for (uint8_t i = 0; i < 4; i++) m_blocks[i] = obj.m_blocks[i]; } /** * ctor and load blocks * @param src_a [description] * @param src_b [description] * @param src_c [description] * @param src_d [description] */ RoundBlocks::RoundBlocks(const __m128i src_a, const __m128i src_b, const __m128i src_c, const __m128i src_d) { m_blocks[b_A] = src_a; m_blocks[b_B] = src_b; m_blocks[b_C] = src_c; m_blocks[b_D] = src_d; } /** * ctor and load blocks * @param src [description] * @param size [description] */ RoundBlocks::RoundBlocks(const __m128i src[], const uint8_t size) { assert(size == (sizeof(m_blocks) / sizeof(__m128i))); for (uint8_t i = 0; i < size; i++) m_blocks[i] = src[i]; } /** * ctor load __m128i from uint8_t ptr * @param src_a [description] * @param src_b [description] * @param src_c [description] * @param src_d [description] */ RoundBlocks::RoundBlocks(const uint8_t* src_a, const uint8_t* src_b, const uint8_t* src_c, const uint8_t* src_d) { m_blocks[b_A] = _mm_loadu_si128((__m128i*) src_a); m_blocks[b_B] = _mm_loadu_si128((__m128i*) src_b); m_blocks[b_C] = _mm_loadu_si128((__m128i*) src_c); m_blocks[b_D] = _mm_loadu_si128((__m128i*) src_d); } /** * ctor load full m_blocks from uint8_t ptr * @param src [description] * @param size [description] */ RoundBlocks::RoundBlocks(const uint8_t* src, const uint8_t size) { assert(size == sizeof(m_blocks)); for (uint8_t i = 0; i < 4; i++) m_blocks[i] = _mm_loadu_si128((__m128i*) (src + i * 16)); } /** * assignment operator * @param obj [description] */ RoundBlocks& RoundBlocks::operator=(const RoundBlocks& obj) { if (this == &obj) return *this; for (uint8_t i = 0; i < 4; i++) m_blocks[i] = obj.m_blocks[i]; return *this; } /** * xor operator overload * @param i [description] */ RoundBlocks RoundBlocks::operator^(const RoundBlocks& obj) { RoundBlocks tmp; for (uint8_t i = 0; i < 4; i++) tmp.m_blocks[i] = _mm_xor_si128(m_blocks[i], obj.m_blocks[i]); return tmp; } /** * equality operator overload * @param obj [description] */ bool RoundBlocks::operator==(const RoundBlocks& obj) { for (uint8_t i = 0; i < 4; i++) { __m128i vcmp = _mm_cmpeq_epi8(m_blocks[i], obj.m_blocks[i]); uint16_t vmask = _mm_movemask_epi8(vcmp); if (vmask != 0xffff) return false; } return true; } /** * unequality operator overlaod * @param obj [description] */ bool RoundBlocks::operator!=(const RoundBlocks& obj) { return !(*this == obj); } /** * operator<< overload print the RoundBlocks * @param os [description] * @param blocks [description] */ std::ostream& operator<<(std::ostream& os, const RoundBlocks& obj) { alignas(sizeof(__m128i) * 4) uint8_t bl[4][16]; _mm_store_si128((__m128i*) bl[0], obj.m_blocks[RoundBlocks::b_A]); _mm_store_si128((__m128i*) bl[1], obj.m_blocks[RoundBlocks::b_B]); _mm_store_si128((__m128i*) bl[2], obj.m_blocks[RoundBlocks::b_C]); _mm_store_si128((__m128i*) bl[3], obj.m_blocks[RoundBlocks::b_D]); os << "-----------------------------------------------------" << std::endl; os << " BLOCK A | BLOCK B | BLOCK C | BLOCK D " << std::endl; os << "-----------------------------------------------------" << std::endl; for (uint8_t i = 0; i < 4; i++) { for (uint8_t j = 0; j < 4; j++) { os << std::hex << std::setfill('0') << std::setw(2) << (unsigned int) bl[j][i] << " "; os << std::hex << std::setfill('0') << std::setw(2) << (unsigned int) bl[j][i + 4] << " "; os << std::hex << std::setfill('0') << std::setw(2) << (unsigned int) bl[j][i + 8] << " "; os << std::hex << std::setfill('0') << std::setw(2) << (unsigned int) bl[j][i + 12]; if (j != 3) os << " | "; else os << std::endl; } } return os; } /** * set the diagonal of @bl block to @i * @param i [description] * @param bl [description] */ void RoundBlocks::setDiag(uint32_t i, RoundBlocks::block_t bl) { uint8_t* ptr = (uint8_t*) &i; uint8_t tmp [sizeof(__m128i)]; _mm_store_si128((__m128i*) tmp, m_blocks[bl]); *(tmp + S1) = *ptr; *(tmp + S6) = *(ptr + 1); *(tmp + S11) = *(ptr + 2); *(tmp + S12) = *(ptr + 3); m_blocks[bl] = _mm_loadu_si128((__m128i*) tmp); } /** * set the difference in block @bl of byte S12 to 0x40 * @param bl [description] */ void RoundBlocks::setConstDiff(RoundBlocks::block_t bl, uint8_t s12_diff) { uint8_t tmp [sizeof(__m128i)]; _mm_store_si128((__m128i*) tmp, m_blocks[bl]); *(tmp + S12) ^= s12_diff; m_blocks[bl] = _mm_loadu_si128((__m128i*) tmp); } /** * set a difference over a full block * @param block_diff [description] */ void RoundBlocks::setConstDiff(RoundBlocks::block_t bl, const uint8_t *block_diff) { __m128i tmp = _mm_loadu_si128((__m128i*) block_diff); m_blocks[bl] = _mm_xor_si128(m_blocks[bl], tmp); } /** * extract the diagonal of block @bl * @param bl [description] * @return [description] */ uint32_t RoundBlocks::extractDiag(RoundBlocks::block_t bl) { uint32_t diag; uint8_t* ptr = (uint8_t*) &diag; uint8_t tmp [sizeof(__m128i)]; _mm_store_si128((__m128i*)tmp, m_blocks[bl]); *ptr = tmp[S1]; *(ptr + 1) = tmp[S6]; *(ptr + 2) = tmp[S11]; *(ptr + 3) = tmp[S12]; return diag; } /** * vary the free bytes of A5 */ void RoundBlocks::varyA5() { uint8_t random_bytes [9]; if (!readURandom(random_bytes, sizeof(random_bytes))) { return; } uint8_t bc = 0; uint8_t ui_data[16]; _mm_store_si128((__m128i*) ui_data, m_blocks[b_A]); for (uint8_t c = 0; c < 16; c++) { if ((c == S0) || (c == S1) || (c == S2) || (c == S3) || (c == S6) || (c == S11) || (c == S12)) continue; ui_data[c] = random_bytes[bc]; bc++; } m_blocks[b_A] = _mm_loadu_si128((__m128i*) ui_data); } /** * vary the free bytes of C5 */ void RoundBlocks::varyC5() { uint8_t random_bytes [12]; if (!readURandom(random_bytes, sizeof(random_bytes))) { return; } uint8_t bc = 0; uint8_t ui_data[16]; _mm_store_si128((__m128i*) ui_data, m_blocks[b_D]); for (uint8_t c = 0; c < 16; c++) { if ((c == S1) || (c == S6) || (c == S11) || (c == S12)) continue; ui_data[c] = random_bytes[bc]; bc++; } m_blocks[b_D] = _mm_loadu_si128((__m128i*) ui_data); } /** * read some random data from /dev/urandom * @param data [description] * @param size [description] * @return [description] */ bool RoundBlocks::readURandom(uint8_t* data, uint8_t size) { std::random_device rd; uint8_t tmp[sizeof(unsigned int) * 24]; for (uint8_t i = 0; i < 24; i++) *(tmp + (i * sizeof(unsigned int))) = rd(); std::copy(tmp, (tmp + size), data); return true; } /** ---------------------------- GETTER / SETTER ----------------------------**/ __m128i RoundBlocks::getBlockA() const { return m_blocks[b_A]; } __m128i RoundBlocks::getBlockB() const { return m_blocks[b_B]; } __m128i RoundBlocks::getBlockC() const { return m_blocks[b_C]; } __m128i RoundBlocks::getBlockD() const { return m_blocks[b_D]; } void RoundBlocks::getBlocks(__m128i dest[], uint8_t size) const { assert(size == (sizeof(m_blocks) / sizeof(__m128i))); for (uint8_t i = 0; i < size; i++) dest[i] = m_blocks[i]; } void RoundBlocks::getBlockA(uint8_t* dest, uint8_t size) const { assert(size == sizeof(__m128i)); _mm_store_si128((__m128i*) dest, m_blocks[b_A]); } void RoundBlocks::getBlockB(uint8_t* dest, uint8_t size) const { assert(size == sizeof(__m128i)); _mm_store_si128((__m128i*) dest, m_blocks[b_B]); } void RoundBlocks::getBlockC(uint8_t* dest, uint8_t size) const { assert(size == sizeof(__m128i)); _mm_store_si128((__m128i*) dest, m_blocks[b_C]); } void RoundBlocks::getBlockD(uint8_t* dest, uint8_t size) const { assert(size == sizeof(__m128i)); _mm_store_si128((__m128i*) dest, m_blocks[b_D]); } void RoundBlocks::getBlocks(uint8_t* dest, uint8_t size) const { assert(size == sizeof(m_blocks)); for (uint8_t i = 0; i < size; i++) _mm_store_si128((__m128i*) (dest + i * sizeof(__m128i)), m_blocks[i]); } void RoundBlocks::setBlockA(const __m128i src) { m_blocks[b_A] = src; } void RoundBlocks::setBlockB(const __m128i src) { m_blocks[b_B] = src; } void RoundBlocks::setBlockC(const __m128i src) { m_blocks[b_C] = src; } void RoundBlocks::setBlockD(const __m128i src) { m_blocks[b_D] = src; } void RoundBlocks::setBlocks(const __m128i src[], const uint8_t size) { assert(size == (sizeof(m_blocks) / sizeof(__m128i))); for (uint8_t i = 0; i < size; i++) m_blocks[i] = src[i]; } void RoundBlocks::setBlockA(const uint8_t* src, const uint8_t size) { assert(size == sizeof(__m128i)); m_blocks[b_A] = _mm_loadu_si128((__m128i*) src); } void RoundBlocks::setBlockB(const uint8_t* src, const uint8_t size) { assert(size == sizeof(__m128i)); m_blocks[b_B] = _mm_loadu_si128((__m128i*) src); } void RoundBlocks::setBlockC(const uint8_t* src, const uint8_t size) { assert(size == sizeof(__m128i)); m_blocks[b_C] = _mm_loadu_si128((__m128i*) src); } void RoundBlocks::setBlockD(const uint8_t* src, const uint8_t size) { assert(size == sizeof(__m128i)); m_blocks[b_D] = _mm_loadu_si128((__m128i*) src); } void RoundBlocks::setBlocks(const uint8_t* src, const uint8_t size) { assert(size == sizeof(m_blocks)); for (uint8_t i = 0; i < size; i++) m_blocks[i] = _mm_loadu_si128((__m128i*) (src + i * sizeof(__m128i))); }
68e990ef3fe597bad5549c0916a6edf189def299
[ "C", "Makefile", "C++" ]
12
C++
cHuberCoffee/bt_differential_cryptanalysis_of_simpirav1
1d9387b6764071ae840a5a13996bf3b912cb2077
3860edc1022f73419bc88004c5db1774e6f7da4a
refs/heads/master
<repo_name>tsukky528/mean_study<file_sep>/public/assets/js/app.js angular.module('post-app', ['post-app.postService', 'post-app.postController']);<file_sep>/Gulpfile.js var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); gulp.task('sass', function(){ return gulp.src('src/sass/**/*.scss') .pipe(sass({errLogToConsole:true})) .pipe(autoprefixer('last 10 version')) .pipe(gulp.dest('public/assets/css')); }); gulp.task('watch-sass', function(){ gulp.watch('src/sass/**/*.scss', ['sass']); }); var globby = require('globby'); var template = require('gulp-template'); gulp.task('index', function(){ return globby(['public/assets/css/**/*.css','public/assets/js/**/*.js'], null, function(err, files){ files = files.map(function(file){ return file.replace('public', ''); }); var cssFiles = files.filter(function(file){ return file.match(/\.css$/); }); var jsFiles = files.filter(function(file){ return file.match(/\.js$/); }); return gulp.src('src/index.html') .pipe(template({ styles:cssFiles, scripts:jsFiles })) .pipe(gulp.dest('public')); }); }); var runSequence = require('run-sequence'); gulp.task('watch-index', function(){ gulp.watch(['public/assets/css/**/*.css', 'src/index.html', 'public/assets/js'], ['index']); }); gulp.task('js', function(){ return gulp.src('src/**/*.js') .pipe(gulp.dest('public/assets/js')); }); gulp.task('watch-js', function(){ gulp.watch('src/**/*.js', ['js']); }); gulp.task('watch', ['watch-sass', 'watch-index', 'watch-js']); var nodemon = require('gulp-nodemon'); gulp.task('server', function(){ nodemon({ script:'server.js', watch:['public/**/*', 'app/**/*.js'], ext: 'js html' }) .on('restart', function(){ console.log('Server restarting!') }); }); gulp.task('default', function(){ return runSequence(['sass', 'js'], 'index', ['watch', 'server']); }); <file_sep>/README.md ## README MEANスタックで作成したtodo管理のwebアプリ
f588a75ca5036c33cb1e612e1bf24fabc4888318
[ "JavaScript", "Markdown" ]
3
JavaScript
tsukky528/mean_study
8e3719bc2b8d0d700421bc608ddd657155313f81
52d2fe9869a9b30659bbb644d0b9e42de307bbbc
refs/heads/master
<file_sep>class Car def start puts"car is started" end def stopped puts"car is stopped" end def move puts "car is moved" end end c=Car.new c.start c.stopped c.move<file_sep>class Calculator def add(*a) sum=0 a.each do|x| sum +=x end sum end end <file_sep>class Person def i_am puts"am person" end end class Employee < Person def i_work_as puts"software developer" end end class Teacher < Person puts"am person" end employee=Employee.new employee.i_work_as employee.i_am teacher=Teacher.new teacher.i_am <file_sep>class Message def send_to_all puts "I can send message to everyone." send_to_selected_people end private def send_to_selected_people puts "I can send message to selected people." end protected def restricted_person puts "I was able to send a message to a restricted person." end end class Friend < Message def send_message_to_selected_person send_to_selected_people end def send_message_to_restricted_person s=Friend.new s.restricted_person end end m=Message.new m.send_to_all s=Friend.new s.send_message_to_restricted_person<file_sep>class Person def i_am(a) @person=a puts @person end end class Employee < Person def i_work_as(b) @person=b puts @person end end class Teacher < Person puts"am person" end employee=Employee.new employee.i_am('am person') employee.i_work_as('software developer') teacher=Teacher.new teacher.i_am('am person') <file_sep><!DOCTYPE html> <html> <head> <title>CONTACT US</title> </head> <style> body{ background-image:url("12.jpg") } </style> <body> <nav> <a style="color:white; font-size: 30px" href="home.html">HOME</a> <a style="color:white; font-size: 30px" href="menu.html">MENU</a> <a style="color:white; font-size: 30px"href="contact.html">CONTACT</a> </nav> <h1 align="center" style="color:black">CONTACT US:</h1> <form> <pre align=center style="color:black ; font-size: 21px;"> Address:#31,1st main,3rd stage, vijayanagar,mysore-570017 mob:9986783427 ,land:08212516607. www.cafeworld.in </pre> <p style="color:red ; font-size: 21px;">Enter your queries:</p> <p style="color:red ; font-size: 21px;">Name</p> <input type="text" name=""></br> <p style="color:red ; font-size: 21px;" >Email</p> <input type="text" name=""></br> <p style="color:red ; font-size: 21px;">Details</p> <textarea rows="5" cols="20"></textarea></br> <input type="submit" name=""> </form> </html><file_sep>module Plane CAN_FLY=true def Car.fly(fly) @fly=fly puts "#{@fly} ,plane can fly!!" end end<file_sep>class Birds def fly puts"birds use wings" end end class Parrot < Birds def green puts"parrot can fly" end end c=Parrot.new c.green c.fly <file_sep>class Myself def my_occupation puts"trainee" end def my_name puts"<NAME>" end def my_achivement puts "xyz" end end c=Myself.new c.my_occupation c.my_name c.my_achivement<file_sep>class Qwinix # def initialize(name,age) # @name=name # @age=age # end def details(name, age) puts "name: #{name}" puts "age: #{age}" end end a=Qwinix.new a.details("sannidhi", "22")<file_sep>class Calender def send_invite puts"Send invite" end end class Response < Calender def send_response puts"Rsponse sent to calender" end end c=Response.new c.send_response c.send_invite <file_sep><!DOCTYPE html> <html> <head> <title>About US</title> </head> <nav> <a style="color:black; font-size: 30px" href="about.html">About</a> <a style="color:black; font-size: 30px" href="sign up.html">Sign up</a> </nav> <p>Gangout is the world's largest network of local groups. Gangoutmakes it easy for anyone to organize a local group or find one of the thousands already meeting up face-to-face. More than 9,000 groups get together in local communities each day, each one with the goal of improving themselves or their communities. Gangout's mission is to revitalize local community and help people around the world self-organize. Meetup believes that people can change their personal world, or the whole world, by organizing themselves into groups that are powerful enough to make a difference.</p> <body> <p><img src="Anoop.png" alt="Smiley face" width="42" height="42" align="middle"> <NAME>, Merations Manager ANUP leads the Office Ops & Admin teams ensuring everything runs smoothly & efficiently from H2T.</p> <p><img src="joshi.png" alt="Smiley face" width="42" height="42" align="middle"> <NAME>, Team Coach Engineer Joshi helps the engineering team get things done smoothly and faster than ever before. Outside of technology, he enjoys making the perfect cup of coffee, catching up on the Times and when he has the time, traveling to remotes spots around Karnataka.</p> <p><img src="kiran.png" alt="Smiley face" width="42" height="42" align="middle"><NAME>, Community Experience Program Manager <NAME> helps members make meaningful connections with people with shared interests and helps to make sure that Meetup is a safe and trustworthy place. Originally from Hubli.</p> </body> </html><file_sep>module Car CAN_GO_FAST=true def goFast(arg) puts "#{arg}, yes car can go fast" end end module Plane CAN_FLY=true def fly(arg) puts "#{arg}, yes plane can go fast" end end class Vehicle include Car include Plane extend Car extend Plane end a=Vehicle.new a.goFast(true) a.fly(true)<file_sep>class Parent def method_A puts"I am a public class" end private def method_B puts "I am a private class" end protected def method_C puts "I am a protectd class" end end class Child<Parent def access_private_method_B method_B end def access_protected_method_C c1=Child.new c1.method_C end end p=Parent.new p.method_A c=Child.new c.access_protected_method_C<file_sep>class Animal def dogSound(sound) puts @sounds=sound end end class Child<Animal end a=Child.new a.dogSound("woof") a.dogSound('bark')<file_sep>module Car CAN_GO_FAST=true def go_fast(fast) @fast=fast puts "#{@fly}" ,car can go fast!! end end<file_sep>class Converter def convert(arabic_number) if arabic_number ==1 "I" elsif arabic_number==2 "II" else "III" end end end describe Converter do describe "#convert" do it 'should return I when given 1' do c=Converter.new roman = c.convert(1) expect(roman).to eq "I" end it 'should return II when given 2' do c=Converter.new roman = c.convert(2) expect(roman).to eq "II" end it 'should return III when given 3' do c=Converter.new roman = c.convert(3) expect(roman).to eq "III" end it 'should return IV when given 4' do c=Converter.new roman = c.convert(3) expect(roman).to eq "III" end end end <file_sep>class Student def initialize(name, std) @name = name @std = std end def name puts @name end def standard puts @std end end s = Student.new("sannidhi", "B.E") s.name s.standard<file_sep>class Animal def dog_sound puts"whoff-whoff" end def lion_sound puts"roar" end def elephant_sound puts"triuph" end def rabbbit_sound puts"squeaks" end end class Amphibians < Animal end dog=Amphibians.new puts dog.dog_sound puts dog.lion_sound putsdog.elephant_sound <file_sep>class Bird def initialize(character1) @character=character1 puts @character end end class Duck def speak(character1) @character=character1 puts @character end def fly(character) puts@character end end class Penguine def speak(character1) @character=character1 puts @character end
fd51efafb8ebbb2d684d8d79ec54a70ea78008ae
[ "Ruby", "HTML" ]
20
Ruby
sannidhigowda/sannidhi
081c5732946f7bdc089be77b158234958e9fd8b4
c1b958e9e942a5f5df5e30f17a23a5c27749d319
refs/heads/main
<repo_name>Dongpaca/ZSSR<file_sep>/net.py import torch import torch.nn as nn import math class SRNet(nn.Module): def __init__(self): super(SRNet, self).__init__() self.relu = nn.ReLU(inplace=True) self.Conv1 = nn.Conv2d(3,64,3,1,1,bias=True) self.Conv2 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv3 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv4 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv5 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv6 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv7 = nn.Conv2d(64,64,3,1,1,bias=True) self.Conv8 = nn.Conv2d(64,3,3,1,1,bias=True) def forward(self, LR_img): x = self.relu(self.Conv1(LR_img)) x = self.relu(self.Conv2(x)) x = self.relu(self.Conv3(x)) x = self.relu(self.Conv4(x)) x = self.relu(self.Conv5(x)) x = self.relu(self.Conv6(x)) x = self.relu(self.Conv7(x)) x = self.Conv8(x) SR_img = LR_img + x # Because we have to learn residuals. return SR_img <file_sep>/final.py import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data as data import torchvision import numpy as np import cv2 import random import net import numpy from torchvision import transforms from utils import * import matplotlib.image as img import matplotlib.pyplot as plt import pytesseract def init_weights(m): if type(m) == nn.modules.conv.Conv2d: print("Weights initialized for:", m) torch.nn.init.xavier_uniform(m.weight) m.bias.data.fill_(0.01) def enhance(img_path, scale): SRNet = net.SRNet().cuda() SRNet.apply(init_weights) criterion = nn.L1Loss().cuda() optimizer = torch.optim.Adam(SRNet.parameters(), lr=0.001) SRNet.train() image = img.imread(img_path) image = image.reshape(image.shape[0],image.shape[1],1) #print(image.shape) hr_fathers_sources = [image] scale_factors = np.array([[1.0, 1.5], [1.5, 1.0], [1.5, 1.5], [1.5, 2.0], [2.0, 1.5], [2.0, 2.0]]) back_projection_iters = np.array([6, 6, 8, 10, 10, 12]) learning_rate_change_iter_nums = [0] rec_mse = [] steps_mse = [] for sf_ind, scale in enumerate(scale_factors): losses = list() for i in range(10000): hr_father = random_augment(ims=hr_fathers_sources, base_scales = [1.0] + list(scale_factors), leave_as_is_probability=0.05, no_interpolate_probability=0.45, min_scale=0.5, max_scale=([1.0]+list(scale_factors))[len(hr_fathers_sources)-1], allow_rotation=True, scale_diff_sigma=0.25, shear_sigma=0.1, crop_size=128 ) hr_father = np.reshape(hr_father,(hr_father.shape[0],hr_father.shape[1],1)) #print(hr_father.shape) lr_son = father_to_son(hr_father, scale) #print(lr_son.shape) lr_son_interpolated = imresize(lr_son, scale, hr_father.shape, "cubic") #print(lr_son_interpolated.shape) hr_father = torch.from_numpy(hr_father).unsqueeze(0).cuda().permute(0,3,1,2).float() #print(hr_father.shape) lr_son_interpolated = torch.from_numpy(lr_son_interpolated).unsqueeze(0).cuda().permute(0,3,1,2).float() #print(lr_son_interpolated .shape) sr_son = SRNet(lr_son_interpolated) #print(sr_son.shape) loss = criterion(sr_son, hr_father) if(not i % 50): son_out = father_to_son(image, scale) son_out_inter = imresize(son_out, scale, image.shape, "cubic") son_out_inter = torch.from_numpy(son_out_inter).unsqueeze(0).cuda().permute(0,3,1,2).float() #print(son_out_inter .shape) sr_son_out = SRNet(son_out_inter).permute(0,2,3,1).squeeze().data.cpu().numpy() sr_son_out = np.clip(np.squeeze(sr_son_out), 0, 1) sr_son_out = sr_son_out.reshape(sr_son_out.shape[0],sr_son_out.shape[1],1) rec_mse.append(np.mean(np.ndarray.flatten(np.square(image - sr_son_out)))) steps_mse.append(i) lr_policy(i, optimizer, learning_rate_change_iter_nums, steps_mse, rec_mse) #curr_lr = 100 for param_group in optimizer.param_groups: #if param_group['lr'] < 9e-6: curr_lr = param_group['lr'] break optimizer.zero_grad() loss.backward() optimizer.step() losses.append(loss.item()) if i%1000 == 0: print("Iteration:", i, "Loss:",loss.item()) if curr_lr < 9e-6: break ### Evaluation the result lr_img = img.imread(img_path) interpolated_lr_img = imresize(lr_img, scale, None, "cubic") interpolated_lr_img = interpolated_lr_img.reshape(interpolated_lr_img.shape[0],interpolated_lr_img.shape[1],1) interpolated_lr_img = torch.from_numpy(interpolated_lr_img).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_img = infer(lr_img, scale, sf_ind, SRNet, back_projection_iters) #SRNet(interpolated_lr_img) plt.figure(figsize=(12, 10)) plt.imshow(sr_img, cmap='gray') sr_img = sr_img.reshape(sr_img.shape[0],sr_img.shape[1],1) save_img = torch.from_numpy(sr_img).unsqueeze(0).permute(0,3,1,2) torchvision.utils.save_image((save_img),img_path.split(".")[0]+'SR.'+ img_path.split(".")[1], normalize=False) torchvision.utils.save_image((interpolated_lr_img),img_path.split(".")[0]+'LR.'+img_path.split(".")[1] , normalize=False) hr_fathers_sources.append(sr_img) print("Optimization done for scale", scale) losses = np.asarray(losses) print(losses.shape) fig = plt.figure() plt.plot(range(losses.shape[0]), losses[:], 'r--') plt.xlabel('ITERATION') plt.ylabel('LOSS') plt.show() def infer(input_img, scale, sf_ind, SRNet, back_projection_iters): outputs = [] for k in range(0, 1+7, 1+int(scale[0] != scale[1])): test_img = np.rot90(input_img, k) if k < 4 else np.fliplr(np.rot90(input_img,k)) interpolated_test_img = imresize(test_img, scale, None, "cubic") interpolated_test_img = interpolated_test_img.reshape(interpolated_test_img.shape[0],interpolated_test_img.shape[1],1) interpolated_test_img = torch.from_numpy(interpolated_test_img).unsqueeze(0).cuda().permute(0,3,1,2).float() tmp_output = SRNet(interpolated_test_img) tmp_output = tmp_output.permute(0,2,3,1).squeeze().data.cpu().numpy() tmp_output = np.clip(np.squeeze(tmp_output), 0, 1) tmp_output = np.rot90(tmp_output, -k) if k < 4 else np.rot90(np.fliplr(tmp_output), k) for bp_iter in range(back_projection_iters[sf_ind]): tmp_output = back_projection(tmp_output, input_img, "cubic", "cubic", scale) outputs.append(tmp_output) outputs_pre = np.median(outputs, 0) for bp_iter in range(back_projection_iters[sf_ind]): outputs_pre = back_projection(outputs_pre, input_img, "cubic", "cubic", scale) return outputs_pre def lr_policy(iters, optimizer, learning_rate_change_iter_nums, mse_steps, mse_rec): if ((not (1 + iters) % 60) and (iters - learning_rate_change_iter_nums[-1] > 256)): [slope, _], [[var,_],_] = np.polyfit(mse_steps[(-256//50):], mse_rec[(-256//50):], 1, cov=True) std = np.sqrt(var) print('Slope:', slope, "STD:", std) if -1.5*slope < std: for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * 0.8 print("Learning Rate Updated:", param_group['lr']) learning_rate_change_iter_nums.append(iters) if __name__ == '__main__': print("hi") img_ori = cv2.imread("images/(%d).png" % 37) height, width, channel = img_ori.shape plt.figure(figsize=(12, 10)) plt.imshow(img_ori, cmap='gray') gray = cv2.cvtColor(img_ori, cv2.COLOR_BGR2GRAY) plt.figure(figsize=(12, 10)) plt.imshow(gray, cmap='gray') img_blurred = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) img_thresh = cv2.adaptiveThreshold( img_blurred, maxValue=255.0, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY_INV, blockSize=19, C=9 ) plt.figure(figsize=(12, 10)) plt.imshow(img_thresh, cmap='gray') contours, _ = cv2.findContours( img_thresh, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE ) temp_result = np.zeros((height, width, channel), dtype=np.uint8) cv2.drawContours(temp_result, contours=contours, contourIdx=-1, color=(255, 255, 255)) plt.figure(figsize=(12, 10)) plt.imshow(temp_result) temp_result = np.zeros((height, width, channel), dtype=np.uint8) contours_dict = [] for contour in contours: x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(temp_result, pt1=(x, y), pt2=(x+w, y+h), color=(255, 255, 255), thickness=2) # insert to dict contours_dict.append({ 'contour': contour, 'x': x, 'y': y, 'w': w, 'h': h, 'cx': x + (w / 2), 'cy': y + (h / 2) }) plt.figure(figsize=(12, 10)) plt.imshow(temp_result, cmap='gray') MIN_AREA = 80 MIN_WIDTH, MIN_HEIGHT = 2, 8 MIN_RATIO, MAX_RATIO = 0.25, 1.0 possible_contours = [] cnt = 0 for d in contours_dict: area = d['w'] * d['h'] ratio = d['w'] / d['h'] if area > MIN_AREA \ and d['w'] > MIN_WIDTH and d['h'] > MIN_HEIGHT \ and MIN_RATIO < ratio < MAX_RATIO: d['idx'] = cnt cnt += 1 possible_contours.append(d) # visualize possible contours temp_result = np.zeros((height, width, channel), dtype=np.uint8) for d in possible_contours: # cv2.drawContours(temp_result, d['contour'], -1, (255, 255, 255)) cv2.rectangle(temp_result, pt1=(d['x'], d['y']), pt2=(d['x']+d['w'], d['y']+d['h']), color=(255, 255, 255), thickness=2) plt.figure(figsize=(12, 10)) plt.imshow(temp_result, cmap='gray') MAX_DIAG_MULTIPLYER = 5 # 5 MAX_ANGLE_DIFF = 12.0 # 12.0 MAX_AREA_DIFF = 0.5 # 0.5 MAX_WIDTH_DIFF = 0.8 MAX_HEIGHT_DIFF = 0.2 MIN_N_MATCHED = 3 # 3 def find_chars(contour_list): matched_result_idx = [] for d1 in contour_list: matched_contours_idx = [] for d2 in contour_list: if d1['idx'] == d2['idx']: continue dx = abs(d1['cx'] - d2['cx']) dy = abs(d1['cy'] - d2['cy']) diagonal_length1 = np.sqrt(d1['w'] ** 2 + d1['h'] ** 2) distance = np.linalg.norm(np.array([d1['cx'], d1['cy']]) - np.array([d2['cx'], d2['cy']])) if dx == 0: angle_diff = 90 else: angle_diff = np.degrees(np.arctan(dy / dx)) area_diff = abs(d1['w'] * d1['h'] - d2['w'] * d2['h']) / (d1['w'] * d1['h']) width_diff = abs(d1['w'] - d2['w']) / d1['w'] height_diff = abs(d1['h'] - d2['h']) / d1['h'] if distance < diagonal_length1 * MAX_DIAG_MULTIPLYER \ and angle_diff < MAX_ANGLE_DIFF and area_diff < MAX_AREA_DIFF \ and width_diff < MAX_WIDTH_DIFF and height_diff < MAX_HEIGHT_DIFF: matched_contours_idx.append(d2['idx']) # append this contour matched_contours_idx.append(d1['idx']) if len(matched_contours_idx) < MIN_N_MATCHED: continue matched_result_idx.append(matched_contours_idx) unmatched_contour_idx = [] for d4 in contour_list: if d4['idx'] not in matched_contours_idx: unmatched_contour_idx.append(d4['idx']) unmatched_contour = np.take(possible_contours, unmatched_contour_idx) # recursive recursive_contour_list = find_chars(unmatched_contour) for idx in recursive_contour_list: matched_result_idx.append(idx) break return matched_result_idx result_idx = find_chars(possible_contours) matched_result = [] for idx_list in result_idx: matched_result.append(np.take(possible_contours, idx_list)) # visualize possible contours temp_result = np.zeros((height, width, channel), dtype=np.uint8) for r in matched_result: for d in r: # cv2.drawContours(temp_result, d['contour'], -1, (255, 255, 255)) cv2.rectangle(temp_result, pt1=(d['x'], d['y']), pt2=(d['x']+d['w'], d['y']+d['h']), color=(255, 255, 255), thickness=2) plt.figure(figsize=(12, 10)) plt.imshow(temp_result, cmap='gray') PLATE_WIDTH_PADDING = 1.3 # 1.3 PLATE_HEIGHT_PADDING = 1.5 # 1.5 MIN_PLATE_RATIO = 3 MAX_PLATE_RATIO = 10 plate_imgs = [] plate_infos = [] for i, matched_chars in enumerate(matched_result): sorted_chars = sorted(matched_chars, key=lambda x: x['cx']) plate_cx = (sorted_chars[0]['cx'] + sorted_chars[-1]['cx']) / 2 plate_cy = (sorted_chars[0]['cy'] + sorted_chars[-1]['cy']) / 2 plate_width = (sorted_chars[-1]['x'] + sorted_chars[-1]['w'] - sorted_chars[0]['x']) * PLATE_WIDTH_PADDING sum_height = 0 for d in sorted_chars: sum_height += d['h'] plate_height = int(sum_height / len(sorted_chars) * PLATE_HEIGHT_PADDING) triangle_height = sorted_chars[-1]['cy'] - sorted_chars[0]['cy'] triangle_hypotenus = np.linalg.norm( np.array([sorted_chars[0]['cx'], sorted_chars[0]['cy']]) - np.array([sorted_chars[-1]['cx'], sorted_chars[-1]['cy']]) ) angle = np.degrees(np.arcsin(triangle_height / triangle_hypotenus)) rotation_matrix = cv2.getRotationMatrix2D(center=(plate_cx, plate_cy), angle=angle, scale=1.0) img_rotated = cv2.warpAffine(img_thresh, M=rotation_matrix, dsize=(width, height)) img_cropped = cv2.getRectSubPix( img_rotated, patchSize=(int(plate_width), int(plate_height)), center=(int(plate_cx), int(plate_cy)) ) if img_cropped.shape[1] / img_cropped.shape[0] < MIN_PLATE_RATIO or img_cropped.shape[1] / img_cropped.shape[0] < MIN_PLATE_RATIO > MAX_PLATE_RATIO: continue plate_imgs.append(img_cropped) plate_infos.append({ 'x': int(plate_cx - plate_width / 2), 'y': int(plate_cy - plate_height / 2), 'w': int(plate_width), 'h': int(plate_height) }) plt.subplot(len(matched_result), 1, i+1) plt.imshow(img_cropped, cmap='gray') longest_idx, longest_text = -1, 0 plate_chars = [] for i, plate_img in enumerate(plate_imgs): plate_img = cv2.resize(plate_img, dsize=(0, 0), fx=1.6, fy=1.6) _, plate_img = cv2.threshold(plate_img, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) # find contours again (same as above) contours, _ = cv2.findContours(plate_img, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE) plate_min_x, plate_min_y = plate_img.shape[1], plate_img.shape[0] plate_max_x, plate_max_y = 0, 0 for contour in contours: x, y, w, h = cv2.boundingRect(contour) area = w * h ratio = w / h if area > MIN_AREA \ and w > MIN_WIDTH and h > MIN_HEIGHT \ and MIN_RATIO < ratio < MAX_RATIO: if x < plate_min_x: plate_min_x = x if y < plate_min_y: plate_min_y = y if x + w > plate_max_x: plate_max_x = x + w if y + h > plate_max_y: plate_max_y = y + h img_result = plate_img[plate_min_y:plate_max_y, plate_min_x:plate_max_x] img_result = cv2.GaussianBlur(img_result, ksize=(3, 3), sigmaX=0) _, img_result = cv2.threshold(img_result, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) img_result = cv2.copyMakeBorder(img_result, top=10, bottom=10, left=10, right=10, borderType=cv2.BORDER_CONSTANT, value=(0,0,0)) chars = pytesseract.image_to_string(img_result, lang='kor', config='--psm 7 --oem 0') result_chars = '' has_digit = False for c in chars: if ord('가') <= ord(c) <= ord('힣') or c.isdigit(): if c.isdigit(): has_digit = True result_chars += c print(result_chars) plate_chars.append(result_chars) if has_digit and len(result_chars) > longest_text: longest_idx = i plt.subplot(len(plate_imgs), 1, i+1) plt.imshow(img_result, cmap='gray') cv2.imwrite("images/%d_c.png" % 37, img_result) info = plate_infos[longest_idx] chars = plate_chars[longest_idx] print(chars) img_out = img_ori.copy() cv2.rectangle(img_out, pt1=(info['x'], info['y']), pt2=(info['x']+info['w'], info['y']+info['h']), color=(255,0,0), thickness=2) plt.figure(figsize=(12, 10)) plt.imshow(img_out) enhance("images/%d_c.png" % 37, 2) img_crop = cv2.imread("images/(%d_cSR).png" % 37) chars = pytesseract.image_to_string(img_result, lang='kor', config='--psm 7 --oem 0') print(chars) #enhance('images/1_gray.png', 2) <file_sep>/run.py import cv2 import numpy as np import matplotlib.pyplot as plt import pytesseract #pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract' # tesseract 경로 설정 def otsu_thres(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #gray 로 변환 g_blur = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) #blurring 필수, noise 제거 _, thresh_img = cv2.threshold(g_blur, 0,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) # return null, thresh_img thresh_img = cv2.bitwise_not(thresh_img) # 흑백 변환(tesseract는 검은바탕에 흰 숫자를 찾음) return thresh_img def adaptive_thres(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #gray 로 변환 g_blur = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) #blurring 필수, noise 제거 thresh_img = cv2.adaptiveThreshold( g_blur, # grayscale image maxValue=255.0, # maxValue – 임계값 adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # adaptiveMethod – thresholding value를 결정하는 계산 방법 thresholdType=cv2.THRESH_BINARY_INV, # thresholdType – threshold type blockSize=19, # blockSize – thresholding을 적용할 영역 사이즈 (최대 size = 19) C=9 # C – 평균이나 가중평균에서 차감할 값 ) return thresh_img def draw_contour(thresh_img): mode = cv2.RETR_LIST # 모든 컨투어 라인을 찾기 method = cv2.CHAIN_APPROX_SIMPLE #컨투어 라인을 그릴 수 있는 포인트만 반환 contours, _ = cv2.findContours(thresh_img, mode, method) #contour 찾기 contour_image = np.zeros((height, width), dtype=np.uint8) # contour그려진 이미지 contourIdx = -1 # 컨투어 라인 번호 color = (255,255,255) #white cv2.drawContours(contour_image, contours, contourIdx, color) #contour 그리기 return contours, contour_image def rect_contours(contours): rect_contour = [] #list 형태 rect_image = np.zeros((height, width), dtype=np.uint8) # 사각형 for contour in contours: x, y, w, h = cv2.boundingRect(contour) # contour를 둘러싸는 사각형 구하기 # 사각형 왼쪽 끝 point (x,y) , w,h cv2.rectangle(rect_image, (x, y), (x+w, y+h), (255, 255, 255), thickness=2) # 이미지, 왼쪽 위 , 오른쪽 아래, 흰색, 선 두께 # dict_contour 추가 하기 rect_contour.append({'contour': contour, 'x': x, 'y': y, 'w': w, 'h': h, 'cx': x + (w / 2), 'cy': y + (h / 2) }) # cx, cy = 사각형의 중심좌표 return rect_contour, rect_image def choice_1(rect_contour): # 실험값 MIN_AREA = 80 MIN_WIDTH, MIN_HEIGHT = 2, 8 MIN_RATIO, MAX_RATIO = 0.25, 1.0 # 가로/세로 비율 값 candidate1 = [] index = 0 for d in rect_contour: area = d['w'] * d['h'] # 넓이 ratio = d['w'] / d['h'] # 가로/세로의 비율 if area > MIN_AREA and d['w'] > MIN_WIDTH and d['h'] > MIN_HEIGHT and MIN_RATIO < ratio < MAX_RATIO: d['idx'] = index # index도 추가 해준다 index += 1 candidate1.append(d) #넓이 , 너비, 높이, 비율 기준 통과한 사각형을 candidate list에 추가 candidate1_image = np.zeros((height, width), dtype=np.uint8) #candidate1 image for d in candidate1: cv2.rectangle(candidate1_image, (d['x'], d['y']), (d['x']+d['w'], d['y']+d['h']), (255, 255, 255), thickness=2) return candidate1, candidate1_image def dist(x,y,nx,ny): # sqrt( (x-nx)^2 + (y-ny)^2), 거리 구하기 diff = x-nx diff = diff*diff dif = y -ny dif = dif*dif return np.sqrt(dif+diff) def choice_2_idx(candidate1): #실험 값 MAX_DAKAK_MULTIPLYER = 5 # box안의 대각선 길이와 box와 box사이의 거리는 5배가 넘지 않는다. MAX_ANGLE_DIFF = 12.0 # box와 box사이의 각도가 12도를 넘지 않는다. MAX_AREA_DIFF = 0.5 # box와 box 넓이 차이가 0.5배 이상이다. MAX_WIDTH_DIFF = 0.8 # box와 box 너비 차이가 0.8배 이상이다. MAX_HEIGHT_DIFF = 0.2 # box와 box 높이 차이가 0.2배 이상이다. MIN_N_MATCHED = 4 # 위의 조건을 만족하는 box가 4개 이상이여야 한다. candidate2_idx = [] #조건을 만족하는 index들을 저장한다. for d1 in candidate1: satisfy = [] # 조건을 만족하는 index를 임시로 저장할 list for d2 in candidate1: if d1['idx'] == d2['idx']: #같으면 continue continue over_check = False for c2_idx in candidate2_idx: # 중복 있는지 검사 if d1['idx'] in c2_idx: over_check = True break if d2['idx'] in c2_idx: over_check = True break if over_check is True: # 중복된게 있으면 스킵 continue #중십값들의 차이 cdx,cdy cdx = abs(d1['cx'] - d2['cx']) cdy = abs(d1['cy'] - d2['cy']) dakak_length = np.sqrt(d1['w'] ** 2 + d1['h'] ** 2) # 대각선 길이 = sqrt(w^2 + h^2) distance = dist(d1['cx'], d1['cy'],d2['cx'], d2['cy']) # box와 box사이 거리 if distance > dakak_length * MAX_DAKAK_MULTIPLYER: # 거리가 대각선 * 5 보다 더 크면 스킵 continue if cdx == 0: # cdx 가 0인경우 예외처리 angle_diff = 90 else: angle_diff = np.degrees(np.arctan(cdy / cdx)) # tan-1(cdy/cdx) , radian 을 degree로 바꾼다. if(angle_diff >= MAX_ANGLE_DIFF): # 각도가 크면 무시 continue area_diff = abs(d1['w'] * d1['h'] - d2['w'] * d2['h']) / (d1['w'] * d1['h']) # 넓이의 비 width_diff = abs(d1['w'] - d2['w']) / d1['w'] height_diff = abs(d1['h'] - d2['h']) / d1['h'] if area_diff < MAX_AREA_DIFF and width_diff < MAX_WIDTH_DIFF and height_diff < MAX_HEIGHT_DIFF: # 모든 조건 통과 satisfy.append(d2['idx']) # d2 for문 종료 satisfy.append(d1['idx']) #d1도 추가 satisfy_cnt = len(satisfy) if satisfy_cnt < MIN_N_MATCHED: # box가 4개 미만이면 무시 continue candidate2_idx.append(satisfy) #모든 조건을 만족한 index들 candidate2_idx에 추가 return candidate2_idx def choice_2(candidate2_idx): candidate2 = [] # 조건을 만족하는 box들의 dictionary 정보 candidate2_image = np.zeros((height, width), dtype=np.uint8) for index in candidate2_idx: candidate2.append(np.take(candidate1, index)) # index 정보를 통해 조건을 만족하는 dictionary 형태의 정보를 저장 for candi in candidate2: for d in candi: cv2.rectangle(candidate2_image, (d['x'], d['y']), (d['x']+d['w'], d['y']+d['h']), (255, 255, 255), thickness=2) return candidate2, candidate2_image def find_plate(candidate2): # plate = 번호판 #실험 값 PLATE_WIDTH_PADDING = 1.3 # plate 너비 PLATE_HEIGHT_PADDING = 1.5 # plate 높이 MIN_PLATE_RATIO = 3 # plate 가로/세로 비 MAX_PLATE_RATIO = 10 plate_images = [] plate_infos = [] for candi in candidate2: sorted_candi = sorted(candi, key=lambda x: x['cx']) # center 점을 기준으로 정렬한다.(왼쪽부터 순서대로) # 번호판의 센터점 plate_cx = (sorted_candi[0]['cx'] + sorted_candi[-1]['cx']) / 2 # 가장 왼쪽 cx와 가장 오른쪽 cx의 가운데 plate_cy = (sorted_candi[0]['cy'] + sorted_candi[-1]['cy']) / 2 # 가장 왼쪽 cy와 가장 오른쪽 cy의 가운데 plate_width = (sorted_candi[-1]['x'] + sorted_candi[-1]['w'] - sorted_candi[0]['x']) * PLATE_WIDTH_PADDING # plate 너비 # padding 붙이는 이유 ? sum_height = 0 for d in sorted_candi: sum_height += d['h'] plate_height = int(sum_height / len(sorted_candi) * PLATE_HEIGHT_PADDING) # plate 높이 # 벌어진 각도에 따라 삼각형을 그릴수 있다. triangle_height = sorted_candi[-1]['cy'] - sorted_candi[0]['cy'] # 삼각형의 높이 triangle_dakak = dist(sorted_candi[0]['cx'], sorted_candi[0]['cy'],sorted_candi[-1]['cx'], sorted_candi[-1]['cy']) #삼각형의 대각선 길이 angle = np.degrees(np.arcsin(triangle_height / triangle_dakak)) # sin-1(h/dakak) rotation_matrix = cv2.getRotationMatrix2D(center=(plate_cx, plate_cy), angle=angle, scale=1.0) #회전 행렬을 구한다 rotate_image = cv2.warpAffine(thresh_img, M=rotation_matrix, dsize=(width, height)) # Affine 변형(여기서는 벌어진 만큼 회전) plate_size=(int(plate_width), int(plate_height)) plate_center=(int(plate_cx), int(plate_cy)) plate_image = cv2.getRectSubPix(rotate_image,plate_size, plate_center) #회전된 이미지 에서 번호판을 얻는다(아직 후보) plate_h, plate_w = plate_image.shape if plate_w / plate_h < MIN_PLATE_RATIO or plate_w / plate_h > MAX_PLATE_RATIO: # 번호판의 가로/세로 비 검사 continue plate_images.append(plate_image) #조건을 만족하는 번호판 이미지 저장 plate_infos.append({ 'x': int(plate_cx - plate_width / 2), #번호판 왼쪽 위 끝 point(x,y) 'y': int(plate_cy - plate_height / 2), 'w': int(plate_width), 'h': int(plate_height) }) #조건을 만족하는 번호판의 정보를 저장 return plate_images, plate_infos def choose_plate(plate_images): # 실험값 MIN_AREA = 80 MIN_WIDTH, MIN_HEIGHT = 2, 8 MIN_RATIO, MAX_RATIO = 0.25, 1.0 # 가로/세로 비율 값 max_len = 0 # 가장 긴 문자를 찾기위해 -> 수정 해보자 answer = '' # 정답 answer_idx = 0 # 정답 plate index idx =0 length = len(plate_images) for plate in plate_images: # 후보 plate에서 contour를 찾아 본다, 문자열만 추리기 위해서 plate = cv2.resize(plate, dsize=(0, 0), fx=1.6, fy=1.6) # ???? _, plate = cv2.threshold(plate, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) # thres contours ,_ = cv2.findContours(plate, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE) #contour #문자열 만 추리기 위해서 contour들의 min,max (x,y)를 각각 찾는다 plate_min_x, plate_min_y = plate.shape[1], plate.shape[0] plate_max_x, plate_max_y = 0, 0 for contour in contours: x, y, w, h = cv2.boundingRect(contour) area = w * h ratio = w / h if area > MIN_AREA and w > MIN_WIDTH and h > MIN_HEIGHT and MIN_RATIO < ratio < MAX_RATIO: #문자 박스의 크기를 본다 if x < plate_min_x: plate_min_x = x if y < plate_min_y: plate_min_y = y if x + w > plate_max_x: plate_max_x = x + w if y + h > plate_max_y: plate_max_y = y + h img_result = plate[plate_min_y:plate_max_y, plate_min_x:plate_max_x] # 번호판 이미지 생성(문자열만 추려진) print(img_result.shape) img_result = cv2.resize(img_result, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) print(img_result.shape) img_result = cv2.GaussianBlur(img_result, ksize=(3, 3), sigmaX=0) #노이즈 제거,필수 _, img_result = cv2.threshold(img_result, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) #thres img_result = cv2.copyMakeBorder(img_result, top=10, bottom=10, left=10, right=10, borderType=cv2.BORDER_CONSTANT, value=(0,0,0)) # tesseract가 잘 인식 할 수 있도록 경계를 만들어 준다 # img_result = cv2.bitwise_not(img_result) # 흑백 변환(tesseract는 검은바탕에 흰 숫자를 찾음) # cv2.imwrite('./dataset/{}_{}.jpg'.format(inum,idx), img_result) plt.figure(figsize=(8, 6)) plt.subplot(length, 1, idx+1) plt.imshow(img_result, cmap='gray') chars = pytesseract.image_to_string(img_result, lang='kor', config='--psm 7 --oem 0') #tesseract를 통해 이미지를 문자로 변환 # psm 7 글이 한줄로 연결되어 있다는 가정 # oem 1 옛날 버전(번호판에는 문맥이 없으므로 rnn을 사용하지 않은 예전 버젼을 이용) string = '' number_find = False char_find = False for c in chars: if ord('가') <= ord(c) <= ord('힣') or c.isdigit(): #한글 or 숫자 if c.isdigit(): #숫자가 포함이 되어있는지 number_find = True else: # 한글이 포함이 되어있는지 char_find = True string += c if len(string) > max_len and number_find and char_find: #숫자,한글이 포함되어있고, 가장 긴 문자열이 가장 높은 확률로 정답 answer = string max_len = len(string) answer_idx = idx # answer_plate의 index idx += 1 return answer, answer_idx image = cv2.imread('./images/(5)SR.png') #image = cv2.resize(image, dsize=(826, 464), interpolation=cv2.INTER_AREA) height, width, _ = image.shape print(height,width) # thresh_img = otsu_thres(image) thresh_img = adaptive_thres(image) contours, contour_image = draw_contour(thresh_img) # contour 그리기 rect_contour, rect_image = rect_contours(contours) # contour -> 사각형 candidate1, candidate1_image = choice_1(rect_contour) # 후보 1 선택 candidate2_idx = choice_2_idx(candidate1) # 조건을 만족하는 contour후보의 idx가 저장됨 candidate2, candidate2_image = choice_2(candidate2_idx) #후보2 선택 plate_images, plate_infos = find_plate(candidate2) #번호판 후보 찾기 # length = len(plate_images) # for i in range(length): #번호판 후보 보기 # plt.subplot(length, 1, i+1) # plt.imshow(plate_images[i], cmap='gray') answer, answer_idx = choose_plate(plate_images) #정답 찾기 print(answer) d = plate_infos[answer_idx] #번호판 후보중 정답 idx로 정답 plate에 접근 res_image = image.copy() cv2.rectangle(res_image, (d['x']-10, d['y']-10), (d['x']+d['w']+10, d['y']+d['h']+10), (255,0,0), thickness=2) # 정답 plate에 빨간 박스 plt.figure(figsize=(12, 10)) plt.imshow(res_image)<file_sep>/README.md # Zero Shot Super Resolution을 통한 저해상도 번호판 인식 <div align=center>서동하* 김동훈* 강아름* 정구민* </div> <div align=center>Low Resolution Number Plate Recognition Using Zero Shot Super Resolution</div> <div align=center>요 약</div> 본 논문은 Zero-Shot Super Resolution을 이용하여 저해상도의 자동차 이미지를 고해상도 이미지로 변환하여 번호판을 인식하고자 하였다. 다량의 Data Set을 구축할 필요가 없는 Zero Shot learning의 장점을 활용하여 여러 해상도의 이미지를 실험해보고 분석하였다. 실험 결과 저해상도 자동차 이미지는 83%의 번호판 인식률을 보였다. Zero-Shot Super Resolution을 통해 고해상도의 이미지로 변환 후 88%의 인식률이 올랐으며 번호판의 이미지만 Crop한 경우 93%로 10%인식률이 올랐음을 확인했다. Keywords : Super Resoltion, zero shot learning, ZSSR, Low Resolution Number plate, zero shot super resolution <file_sep>/check.py import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data as data import torchvision import numpy as np import cv2 import random import net import numpy from torchvision import transforms from utils import * import matplotlib.image as img import matplotlib.pyplot as plt import pytesseract def init_weights(m): if type(m) == nn.modules.conv.Conv2d: print("Weights initialized for:", m) torch.nn.init.xavier_uniform(m.weight) m.bias.data.fill_(0.01) def enhance(img_path, scale): SRNet = net.SRNet().cuda() SRNet.apply(init_weights) criterion = nn.L1Loss().cuda() optimizer = torch.optim.Adam(SRNet.parameters(), lr=0.001) SRNet.train() image = img.imread(img_path) hr_fathers_sources = [image] scale_factors = np.array([[1.0, 1.5], [1.5, 1.0], [1.5, 1.5], [1.5, 2.0], [2.0, 1.5], [2.0, 2.0]]) back_projection_iters = np.array([6, 6, 8, 10, 10, 12]) learning_rate_change_iter_nums = [0] rec_mse = [] steps_mse = [] for sf_ind, scale in enumerate(scale_factors): for i in range(10000): hr_father = random_augment(ims=hr_fathers_sources, base_scales = [1.0] + list(scale_factors), leave_as_is_probability=0.05, no_interpolate_probability=0.45, min_scale=0.5, max_scale=([1.0]+list(scale_factors))[len(hr_fathers_sources)-1], allow_rotation=True, scale_diff_sigma=0.25, shear_sigma=0.1, crop_size=128 ) lr_son = father_to_son(hr_father, scale) lr_son_interpolated = imresize(lr_son, scale, hr_father.shape, "cubic") hr_father = torch.from_numpy(hr_father).unsqueeze(0).cuda().permute(0,3,1,2).float() lr_son_interpolated = torch.from_numpy(lr_son_interpolated).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_son = SRNet(lr_son_interpolated) loss = criterion(sr_son, hr_father) if(not i % 50): son_out = father_to_son(image, scale) son_out_inter = imresize(son_out, scale, image.shape, "cubic") son_out_inter = torch.from_numpy(son_out_inter).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_son_out = SRNet(son_out_inter).permute(0,2,3,1).squeeze().data.cpu().numpy() sr_son_out = np.clip(np.squeeze(sr_son_out), 0, 1) rec_mse.append(np.mean(np.ndarray.flatten(np.square(image - sr_son_out)))) steps_mse.append(i) lr_policy(i, optimizer, learning_rate_change_iter_nums, steps_mse, rec_mse) #curr_lr = 100 for param_group in optimizer.param_groups: #if param_group['lr'] < 9e-6: curr_lr = param_group['lr'] break optimizer.zero_grad() loss.backward() optimizer.step() if i%10 == 0: print("Iteration:", i, "Loss:",loss.item()) if curr_lr < 9e-6: break ### Evaluation the result lr_img = img.imread(img_path) interpolated_lr_img = imresize(lr_img, scale, None, "cubic") interpolated_lr_img = torch.from_numpy(interpolated_lr_img).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_img = infer(lr_img, scale, sf_ind, SRNet, back_projection_iters) #SRNet(interpolated_lr_img) save_img = torch.from_numpy(sr_img).unsqueeze(0).permute(0,3,1,2) torchvision.utils.save_image((save_img),img_path.split(".")[0]+'SR.'+ img_path.split(".")[1], normalize=False) torchvision.utils.save_image((interpolated_lr_img),img_path.split(".")[0]+'LR.'+img_path.split(".")[1] , normalize=False) hr_fathers_sources.append(sr_img) print("Optimization done for scale", scale) def infer(input_img, scale, sf_ind, SRNet, back_projection_iters): outputs = [] for k in range(0, 1+7, 1+int(scale[0] != scale[1])): test_img = np.rot90(input_img, k) if k < 4 else np.fliplr(np.rot90(input_img,k)) interpolated_test_img = imresize(test_img, scale, None, "cubic") interpolated_test_img = torch.from_numpy(interpolated_test_img).unsqueeze(0).cuda().permute(0,3,1,2).float() tmp_output = SRNet(interpolated_test_img) tmp_output = tmp_output.permute(0,2,3,1).squeeze().data.cpu().numpy() tmp_output = np.clip(np.squeeze(tmp_output), 0, 1) tmp_output = np.rot90(tmp_output, -k) if k < 4 else np.rot90(np.fliplr(tmp_output), k) for bp_iter in range(back_projection_iters[sf_ind]): tmp_output = back_projection(tmp_output, input_img, "cubic", "cubic", scale) outputs.append(tmp_output) outputs_pre = np.median(outputs, 0) for bp_iter in range(back_projection_iters[sf_ind]): outputs_pre = back_projection(outputs_pre, input_img, "cubic", "cubic", scale) return outputs_pre def lr_policy(iters, optimizer, learning_rate_change_iter_nums, mse_steps, mse_rec): if ((not (1 + iters) % 60) and (iters - learning_rate_change_iter_nums[-1] > 256)): [slope, _], [[var,_],_] = np.polyfit(mse_steps[(-256//50):], mse_rec[(-256//50):], 1, cov=True) std = np.sqrt(var) print('Slope:', slope, "STD:", std) if -1.5*slope < std: for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * 0.8 print("Learning Rate Updated:", param_group['lr']) learning_rate_change_iter_nums.append(iters) def otsu_thres(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #gray 로 변환 g_blur = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) #blurring 필수, noise 제거 _, thresh_img = cv2.threshold(g_blur, 0,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) # return null, thresh_img thresh_img = cv2.bitwise_not(thresh_img) # 흑백 변환(tesseract는 검은바탕에 흰 숫자를 찾음) return thresh_img def adaptive_thres(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #gray 로 변환 g_blur = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) #blurring 필수, noise 제거 thresh_img = cv2.adaptiveThreshold( g_blur, # grayscale image maxValue=255.0, # maxValue – 임계값 adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, # adaptiveMethod – thresholding value를 결정하는 계산 방법 thresholdType=cv2.THRESH_BINARY_INV, # thresholdType – threshold type blockSize=19, # blockSize – thresholding을 적용할 영역 사이즈 (최대 size = 19) C=9 # C – 평균이나 가중평균에서 차감할 값 ) return thresh_img def num_thres(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray,(3,3),0) ret, thresh_img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) return thresh_img def draw_contour(thresh_img): mode = cv2.RETR_LIST # 모든 컨투어 라인을 찾기 method = cv2.CHAIN_APPROX_SIMPLE #컨투어 라인을 그릴 수 있는 포인트만 반환 contours, _ = cv2.findContours(thresh_img, mode, method) #contour 찾기 contour_image = np.zeros((height, width), dtype=np.uint8) # contour그려진 이미지 contourIdx = -1 # 컨투어 라인 번호 color = (255,255,255) #white cv2.drawContours(contour_image, contours, contourIdx, color) #contour 그리기 return contours, contour_image def rect_contours(contours): rect_contour = [] #list 형태 rect_image = np.zeros((height, width), dtype=np.uint8) # 사각형 for contour in contours: x, y, w, h = cv2.boundingRect(contour) # contour를 둘러싸는 사각형 구하기 # 사각형 왼쪽 끝 point (x,y) , w,h cv2.rectangle(rect_image, (x, y), (x+w, y+h), (255, 255, 255), thickness=2) # 이미지, 왼쪽 위 , 오른쪽 아래, 흰색, 선 두께 # dict_contour 추가 하기 rect_contour.append({'contour': contour, 'x': x, 'y': y, 'w': w, 'h': h, 'cx': x + (w / 2), 'cy': y + (h / 2) }) # cx, cy = 사각형의 중심좌표 return rect_contour, rect_image def choice_1(rect_contour): # 실험값 MIN_AREA = 80 MIN_WIDTH, MIN_HEIGHT = 2, 8 MIN_RATIO, MAX_RATIO = 0.25, 1.0 # 가로/세로 비율 값 candidate1 = [] index = 0 for d in rect_contour: area = d['w'] * d['h'] # 넓이 ratio = d['w'] / d['h'] # 가로/세로의 비율 if area > MIN_AREA and d['w'] > MIN_WIDTH and d['h'] > MIN_HEIGHT and MIN_RATIO < ratio < MAX_RATIO: d['idx'] = index # index도 추가 해준다 index += 1 candidate1.append(d) #넓이 , 너비, 높이, 비율 기준 통과한 사각형을 candidate list에 추가 candidate1_image = np.zeros((height, width), dtype=np.uint8) #candidate1 image for d in candidate1: cv2.rectangle(candidate1_image, (d['x'], d['y']), (d['x']+d['w'], d['y']+d['h']), (255, 255, 255), thickness=2) return candidate1, candidate1_image def dist(x,y,nx,ny): # sqrt( (x-nx)^2 + (y-ny)^2), 거리 구하기 diff = x-nx diff = diff*diff dif = y -ny dif = dif*dif return np.sqrt(dif+diff) def choice_2_idx(candidate1): #실험 값 MAX_DAKAK_MULTIPLYER = 5 # box안의 대각선 길이와 box와 box사이의 거리는 5배가 넘지 않는다. MAX_ANGLE_DIFF = 12.0 # box와 box사이의 각도가 12도를 넘지 않는다. MAX_AREA_DIFF = 0.5 # box와 box 넓이 차이가 0.5배 이상이다. MAX_WIDTH_DIFF = 0.8 # box와 box 너비 차이가 0.8배 이상이다. MAX_HEIGHT_DIFF = 0.2 # box와 box 높이 차이가 0.2배 이상이다. MIN_N_MATCHED = 4 # 위의 조건을 만족하는 box가 4개 이상이여야 한다. candidate2_idx = [] #조건을 만족하는 index들을 저장한다. for d1 in candidate1: satisfy = [] # 조건을 만족하는 index를 임시로 저장할 list for d2 in candidate1: if d1['idx'] == d2['idx']: #같으면 continue continue over_check = False for c2_idx in candidate2_idx: # 중복 있는지 검사 if d1['idx'] in c2_idx: over_check = True break if d2['idx'] in c2_idx: over_check = True break if over_check is True: # 중복된게 있으면 스킵 continue #중십값들의 차이 cdx,cdy cdx = abs(d1['cx'] - d2['cx']) cdy = abs(d1['cy'] - d2['cy']) dakak_length = np.sqrt(d1['w'] ** 2 + d1['h'] ** 2) # 대각선 길이 = sqrt(w^2 + h^2) distance = dist(d1['cx'], d1['cy'],d2['cx'], d2['cy']) # box와 box사이 거리 if distance > dakak_length * MAX_DAKAK_MULTIPLYER: # 거리가 대각선 * 5 보다 더 크면 스킵 continue if cdx == 0: # cdx 가 0인경우 예외처리 angle_diff = 90 else: angle_diff = np.degrees(np.arctan(cdy / cdx)) # tan-1(cdy/cdx) , radian 을 degree로 바꾼다. if(angle_diff >= MAX_ANGLE_DIFF): # 각도가 크면 무시 continue area_diff = abs(d1['w'] * d1['h'] - d2['w'] * d2['h']) / (d1['w'] * d1['h']) # 넓이의 비 width_diff = abs(d1['w'] - d2['w']) / d1['w'] height_diff = abs(d1['h'] - d2['h']) / d1['h'] if area_diff < MAX_AREA_DIFF and width_diff < MAX_WIDTH_DIFF and height_diff < MAX_HEIGHT_DIFF: # 모든 조건 통과 satisfy.append(d2['idx']) # d2 for문 종료 satisfy.append(d1['idx']) #d1도 추가 satisfy_cnt = len(satisfy) if satisfy_cnt < MIN_N_MATCHED: # box가 4개 미만이면 무시 continue candidate2_idx.append(satisfy) #모든 조건을 만족한 index들 candidate2_idx에 추가 return candidate2_idx def choice_2(candidate2_idx): candidate2 = [] # 조건을 만족하는 box들의 dictionary 정보 candidate2_image = np.zeros((height, width), dtype=np.uint8) for index in candidate2_idx: candidate2.append(np.take(candidate1, index)) # index 정보를 통해 조건을 만족하는 dictionary 형태의 정보를 저장 for candi in candidate2: for d in candi: cv2.rectangle(candidate2_image, (d['x'], d['y']), (d['x']+d['w'], d['y']+d['h']), (255, 255, 255), thickness=2) return candidate2, candidate2_image def find_plate(candidate2): # plate = 번호판 #실험 값 PLATE_WIDTH_PADDING = 1.3 # plate 너비 PLATE_HEIGHT_PADDING = 1.5 # plate 높이 MIN_PLATE_RATIO = 3 # plate 가로/세로 비 MAX_PLATE_RATIO = 10 plate_images = [] plate_infos = [] for candi in candidate2: sorted_candi = sorted(candi, key=lambda x: x['cx']) # center 점을 기준으로 정렬한다.(왼쪽부터 순서대로) # 번호판의 센터점 plate_cx = (sorted_candi[0]['cx'] + sorted_candi[-1]['cx']) / 2 # 가장 왼쪽 cx와 가장 오른쪽 cx의 가운데 plate_cy = (sorted_candi[0]['cy'] + sorted_candi[-1]['cy']) / 2 # 가장 왼쪽 cy와 가장 오른쪽 cy의 가운데 plate_width = (sorted_candi[-1]['x'] + sorted_candi[-1]['w'] - sorted_candi[0]['x']) * PLATE_WIDTH_PADDING # plate 너비 # padding 붙이는 이유 ? sum_height = 0 for d in sorted_candi: sum_height += d['h'] plate_height = int(sum_height / len(sorted_candi) * PLATE_HEIGHT_PADDING) # plate 높이 # 벌어진 각도에 따라 삼각형을 그릴수 있다. triangle_height = sorted_candi[-1]['cy'] - sorted_candi[0]['cy'] # 삼각형의 높이 triangle_dakak = dist(sorted_candi[0]['cx'], sorted_candi[0]['cy'],sorted_candi[-1]['cx'], sorted_candi[-1]['cy']) #삼각형의 대각선 길이 angle = np.degrees(np.arcsin(triangle_height / triangle_dakak)) # sin-1(h/dakak) rotation_matrix = cv2.getRotationMatrix2D(center=(plate_cx, plate_cy), angle=angle, scale=1.0) #회전 행렬을 구한다 rotate_image = cv2.warpAffine(thresh_img, M=rotation_matrix, dsize=(width, height)) # Affine 변형(여기서는 벌어진 만큼 회전) plate_size=(int(plate_width), int(plate_height)) plate_center=(int(plate_cx), int(plate_cy)) plate_image = cv2.getRectSubPix(rotate_image,plate_size, plate_center) #회전된 이미지 에서 번호판을 얻는다(아직 후보) plate_h, plate_w = plate_image.shape if plate_w / plate_h < MIN_PLATE_RATIO or plate_w / plate_h > MAX_PLATE_RATIO: # 번호판의 가로/세로 비 검사 continue plate_images.append(plate_image) #조건을 만족하는 번호판 이미지 저장 plate_infos.append({ 'x': int(plate_cx - plate_width / 2), #번호판 왼쪽 위 끝 point(x,y) 'y': int(plate_cy - plate_height / 2), 'w': int(plate_width), 'h': int(plate_height) }) #조건을 만족하는 번호판의 정보를 저장 return plate_images, plate_infos def choose_plate(plate_images): # 실험값 MIN_AREA = 80 MIN_WIDTH, MIN_HEIGHT = 2, 8 MIN_RATIO, MAX_RATIO = 0.25, 1.0 # 가로/세로 비율 값 max_len = 0 # 가장 긴 문자를 찾기위해 -> 수정 해보자 answer = '' # 정답 answer_idx = 0 # 정답 plate index idx =0 length = len(plate_images) for plate in plate_images: # 후보 plate에서 contour를 찾아 본다, 문자열만 추리기 위해서 plate = cv2.resize(plate, dsize=(0, 0), fx=1.6, fy=1.6) # ???? _, plate = cv2.threshold(plate, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) # thres contours ,_ = cv2.findContours(plate, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE) #contour #문자열 만 추리기 위해서 contour들의 min,max (x,y)를 각각 찾는다 plate_min_x, plate_min_y = plate.shape[1], plate.shape[0] plate_max_x, plate_max_y = 0, 0 for contour in contours: x, y, w, h = cv2.boundingRect(contour) area = w * h ratio = w / h if area > MIN_AREA and w > MIN_WIDTH and h > MIN_HEIGHT and MIN_RATIO < ratio < MAX_RATIO: #문자 박스의 크기를 본다 if x < plate_min_x: plate_min_x = x if y < plate_min_y: plate_min_y = y if x + w > plate_max_x: plate_max_x = x + w if y + h > plate_max_y: plate_max_y = y + h img_result = plate[plate_min_y:plate_max_y, plate_min_x:plate_max_x] # 번호판 이미지 생성(문자열만 추려진) #print(img_result.shape) img_result = cv2.resize(img_result, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) #print(img_result.shape) img_result = cv2.GaussianBlur(img_result, ksize=(3, 3), sigmaX=0) #노이즈 제거,필수 _, img_result = cv2.threshold(img_result, thresh=0.0, maxval=255.0, type=cv2.THRESH_BINARY | cv2.THRESH_OTSU) #thres img_result = cv2.copyMakeBorder(img_result, top=10, bottom=10, left=10, right=10, borderType=cv2.BORDER_CONSTANT, value=(0,0,0)) # tesseract가 잘 인식 할 수 있도록 경계를 만들어 준다 # img_result = cv2.bitwise_not(img_result) # 흑백 변환(tesseract는 검은바탕에 흰 숫자를 찾음) # cv2.imwrite('./dataset/{}_{}.jpg'.format(inum,idx), img_result) plt.figure(figsize=(8, 6)) plt.subplot(length, 1, idx+1) plt.imshow(img_result, cmap='gray') chars = pytesseract.image_to_string(img_result, lang='kor', config='--psm 7 --oem 0') #tesseract를 통해 이미지를 문자로 변환 # psm 7 글이 한줄로 연결되어 있다는 가정 # oem 1 옛날 버전(번호판에는 문맥이 없으므로 rnn을 사용하지 않은 예전 버젼을 이용) string = '' number_find = False char_find = False for c in chars: if ord('가') <= ord(c) <= ord('힣') or c.isdigit(): #한글 or 숫자 if c.isdigit(): #숫자가 포함이 되어있는지 number_find = True else: # 한글이 포함이 되어있는지 char_find = True string += c if len(string) > max_len and number_find and char_find: #숫자,한글이 포함되어있고, 가장 긴 문자열이 가장 높은 확률로 정답 answer = string max_len = len(string) answer_idx = idx # answer_plate의 index idx += 1 return answer, answer_idx if __name__ == '__main__': ## First argument is the image that you want to upsample with ZSSR. ## Second argument is the scale with which you want to resize. Currently only scale = 2 supported. For other scales, change the variable 'scale_factors' accordingly. enhance('images/dddd/26.png', 2) image = cv2.imread('images/dddd/26SR.png') #image = cv2.resize(image, dsize=(826, 464), interpolation=cv2.INTER_AREA) height, width, _ = image.shape #print(height,width) #thresh_img = otsu_thres(image) thresh_img = adaptive_thres(image) #thresh_img = num_thres(image) contours, contour_image = draw_contour(thresh_img) # contour 그리기 rect_contour, rect_image = rect_contours(contours) # contour -> 사각형 candidate1, candidate1_image = choice_1(rect_contour) # 후보 1 선택 candidate2_idx = choice_2_idx(candidate1) # 조건을 만족하는 contour후보의 idx가 저장됨 candidate2, candidate2_image = choice_2(candidate2_idx) #후보2 선택 plate_images, plate_infos = find_plate(candidate2) #번호판 후보 찾기 # length = len(plate_images) # for i in range(length): #번호판 후보 보기 # plt.subplot(length, 1, i+1) # plt.imshow(plate_images[i], cmap='gray') answer, answer_idx = choose_plate(plate_images) #정답 찾기 print(answer) d = plate_infos[answer_idx] #번호판 후보중 정답 idx로 정답 plate에 접근 res_image = image.copy() cv2.rectangle(res_image, (d['x']-10, d['y']-10), (d['x']+d['w']+10, d['y']+d['h']+10), (255,0,0), thickness=2) # 정답 plate에 빨간 박스 plt.figure(figsize=(12, 10)) plt.imshow(res_image) <file_sep>/enhancer.py import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data as data import torchvision import numpy as np import cv2 import random import net import numpy from torchvision import transforms from utils import * import matplotlib.image as img def init_weights(m): if type(m) == nn.modules.conv.Conv2d: print("Weights initialized for:", m) torch.nn.init.xavier_uniform(m.weight) m.bias.data.fill_(0.01) def enhance(img_path, scale): SRNet = net.SRNet().cuda() SRNet.apply(init_weights) criterion = nn.L1Loss().cuda() optimizer = torch.optim.Adam(SRNet.parameters(), lr=0.001) SRNet.train() image = img.imread(img_path) hr_fathers_sources = [image] scale_factors = np.array([[1.0, 1.5], [1.5, 1.0], [1.5, 1.5], [1.5, 2.0], [2.0, 1.5], [2.0, 2.0]]) back_projection_iters = np.array([6, 6, 8, 10, 10, 12]) learning_rate_change_iter_nums = [0] rec_mse = [] steps_mse = [] for sf_ind, scale in enumerate(scale_factors): for i in range(10000): hr_father = random_augment(ims=hr_fathers_sources, base_scales = [1.0] + list(scale_factors), leave_as_is_probability=0.05, no_interpolate_probability=0.45, min_scale=0.5, max_scale=([1.0]+list(scale_factors))[len(hr_fathers_sources)-1], allow_rotation=True, scale_diff_sigma=0.25, shear_sigma=0.1, crop_size=128 ) lr_son = father_to_son(hr_father, scale) lr_son_interpolated = imresize(lr_son, scale, hr_father.shape, "cubic") hr_father = torch.from_numpy(hr_father).unsqueeze(0).cuda().permute(0,3,1,2).float() lr_son_interpolated = torch.from_numpy(lr_son_interpolated).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_son = SRNet(lr_son_interpolated) loss = criterion(sr_son, hr_father) if(not i % 50): son_out = father_to_son(image, scale) son_out_inter = imresize(son_out, scale, image.shape, "cubic") son_out_inter = torch.from_numpy(son_out_inter).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_son_out = SRNet(son_out_inter).permute(0,2,3,1).squeeze().data.cpu().numpy() sr_son_out = np.clip(np.squeeze(sr_son_out), 0, 1) rec_mse.append(np.mean(np.ndarray.flatten(np.square(image - sr_son_out)))) steps_mse.append(i) lr_policy(i, optimizer, learning_rate_change_iter_nums, steps_mse, rec_mse) #curr_lr = 100 for param_group in optimizer.param_groups: #if param_group['lr'] < 9e-6: curr_lr = param_group['lr'] break optimizer.zero_grad() loss.backward() optimizer.step() if i%10 == 0: print("Iteration:", i, "Loss:",loss.item()) if curr_lr < 9e-6: break ### Evaluation the result lr_img = img.imread(img_path) interpolated_lr_img = imresize(lr_img, scale, None, "cubic") interpolated_lr_img = torch.from_numpy(interpolated_lr_img).unsqueeze(0).cuda().permute(0,3,1,2).float() sr_img = infer(lr_img, scale, sf_ind, SRNet, back_projection_iters) #SRNet(interpolated_lr_img) save_img = torch.from_numpy(sr_img).unsqueeze(0).permute(0,3,1,2) torchvision.utils.save_image((save_img),img_path.split(".")[0]+'SR.'+ img_path.split(".")[1], normalize=False) torchvision.utils.save_image((interpolated_lr_img),img_path.split(".")[0]+'LR.'+img_path.split(".")[1] , normalize=False) hr_fathers_sources.append(sr_img) print("Optimization done for scale", scale) def infer(input_img, scale, sf_ind, SRNet, back_projection_iters): outputs = [] for k in range(0, 1+7, 1+int(scale[0] != scale[1])): test_img = np.rot90(input_img, k) if k < 4 else np.fliplr(np.rot90(input_img,k)) interpolated_test_img = imresize(test_img, scale, None, "cubic") interpolated_test_img = torch.from_numpy(interpolated_test_img).unsqueeze(0).cuda().permute(0,3,1,2).float() tmp_output = SRNet(interpolated_test_img) tmp_output = tmp_output.permute(0,2,3,1).squeeze().data.cpu().numpy() tmp_output = np.clip(np.squeeze(tmp_output), 0, 1) tmp_output = np.rot90(tmp_output, -k) if k < 4 else np.rot90(np.fliplr(tmp_output), k) for bp_iter in range(back_projection_iters[sf_ind]): tmp_output = back_projection(tmp_output, input_img, "cubic", "cubic", scale) outputs.append(tmp_output) outputs_pre = np.median(outputs, 0) for bp_iter in range(back_projection_iters[sf_ind]): outputs_pre = back_projection(outputs_pre, input_img, "cubic", "cubic", scale) return outputs_pre def lr_policy(iters, optimizer, learning_rate_change_iter_nums, mse_steps, mse_rec): if ((not (1 + iters) % 60) and (iters - learning_rate_change_iter_nums[-1] > 256)): [slope, _], [[var,_],_] = np.polyfit(mse_steps[(-256//50):], mse_rec[(-256//50):], 1, cov=True) std = np.sqrt(var) print('Slope:', slope, "STD:", std) if -1.5*slope < std: for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * 0.8 print("Learning Rate Updated:", param_group['lr']) learning_rate_change_iter_nums.append(iters) if __name__ == '__main__': ## First argument is the image that you want to upsample with ZSSR. ## Second argument is the scale with which you want to resize. Currently only scale = 2 supported. For other scales, change the variable 'scale_factors' accordingly. enhance('images/%d.png' %i , 2)
cd83a3ef13a342ff0a22543bbb49eab159f835d5
[ "Markdown", "Python" ]
6
Python
Dongpaca/ZSSR
b965a1e752436b250b2108d5df4651516b15698a
85a50c0887f477b85c53f1ba589a2e4aa4759455
refs/heads/master
<repo_name>jerysun/large-files-search-replace<file_sep>/src/main/java/com/jsun/type/FileType.java package com.jsun.type; /** * List the supported file types * @author jerysun * @version 1.00 2018-04-08 */ public enum FileType { TEXT, XML, HTML, UNKNOWN; }<file_sep>/src/main/java/com/jsun/xml/XMLSearchReplace.java package com.jsun.xml; import java.io.*; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.jsun.type.SearchType; import com.jsun.type.TypeEnum; import com.jsun.text.TextSearchReplace; /** * This is an implementation of the interface SearchReplace * for XML files processing, using FileInputStream and * FileOutputStream to reduce the memory consumption, using * XMLPartEnum to guarantee only the proper part will be * searched and replaced. * @author jerysun * @version 1.00 2018-04-08 */ public class XMLSearchReplace extends TextSearchReplace { private final XMLPartEnum xmlPartEnum; public XMLSearchReplace(String path, SearchType searchType, XMLPartEnum xmlPartEnum) { super(path, searchType); this.xmlPartEnum = xmlPartEnum; } @Override public boolean fSearch(InputStream in, SearchType searchType) { if (xmlPartEnum == XMLPartEnum.UNKNOWN) { return false; } switch (xmlPartEnum) { case ELEMENT_NAME: if (!searchType.getSearchString().contains("<")) { return false; } break; case ATTRIBUTE: if (!searchType.getSearchString().contains("=")) { return false; } break; case UNKNOWN: return false; default: break; } return super.fSearch(in, searchType); } @Override public void fReplace(InputStream in, SearchType searchType, String replaceString) throws IOException { if (in == null || searchType == null || replaceString == null || replaceString.isEmpty() || xmlPartEnum == XMLPartEnum.UNKNOWN) return; String newEndTag = null; String oldEndTag = null; switch (xmlPartEnum) { case ELEMENT_NAME: if (!searchType.getSearchString().contains("<") || !replaceString.contains("<")) { return; } StringBuilder sb = new StringBuilder(replaceString); sb.insert(1, '/'); newEndTag = sb.toString(); sb = new StringBuilder(searchType.getSearchString()); sb.insert(1, '/'); oldEndTag = sb.toString(); break; case ATTRIBUTE: if (!searchType.getSearchString().contains("=") || !replaceString.contains("=")) { return; } break; case UNKNOWN: return; default: break; } //System.out.println("oldEndTag: " + oldEndTag + ", newEndTag: " + newEndTag); TypeEnum typeEnum = searchType.getTypeEnum(); try(Scanner sc = new Scanner(in, "UTF-8"); FileOutputStream fo = new FileOutputStream(getOutPath(getPath()))) { Pattern pattern = null; Matcher matcher = null; while (sc.hasNextLine()) { String line = sc.nextLine(); switch (typeEnum) { case PHRASE: if (line.contains(searchType.getSearchString())) { phraseReplace(line, searchType.getSearchString(), replaceString, fo); } else if (oldEndTag != null && newEndTag != null && line.contains(oldEndTag)) { phraseReplace(line, oldEndTag, newEndTag, fo); } else { lineReplace(line, fo); } break; case PATTERN: pattern = Pattern.compile(searchType.getSearchString()); matcher = pattern.matcher(line); if (matcher.find()) { patternReplace(line, searchType.getSearchString(), replaceString, fo); } else if (oldEndTag != null && newEndTag != null) { pattern = Pattern.compile(oldEndTag); matcher = pattern.matcher(line); if (matcher.find()) { patternReplace(line, oldEndTag, newEndTag, fo); } else { lineReplace(line, fo); } } else { lineReplace(line, fo); } break; case WILDCARD: //TODO return; case VARIABLE: //TODO return; case UNKNOWN: return; default: break; } } fo.flush(); } } private void lineReplace(String line, FileOutputStream fo) throws IOException { StringBuilder sb = new StringBuilder(line); sb.append(System.getProperty("line.separator")); byte[] lineBytes = sb.toString().getBytes(); fo.write(lineBytes); } public XMLPartEnum getXmlPartEnum() { return xmlPartEnum; } }<file_sep>/src/main/java/com/jsun/SearchReplace.java package com.jsun; import java.io.IOException; import java.io.InputStream; import com.jsun.type.SearchType;; /** * This interface is the abstract of the search and replace function, * it adopts the InputStream aiming to reduce the memory consumption to * hundreds of mega bytes when processing the large file which could be * up to several giga bytes. * @author jerysun * @version 1.00 2018-04-08 */ public interface SearchReplace { public boolean fSearch(InputStream in, SearchType searchType); public void fReplace(InputStream in, SearchType searchType, String replaceString) throws IOException; public default String getOutPath(String path) { int idx = path.lastIndexOf('.'); StringBuilder sb = new StringBuilder(path.substring(0, idx)); sb.append("_out"); sb.append(path.substring(idx)); return sb.toString(); } }<file_sep>/src/main/java/com/jsun/xml/XMLPartEnum.java package com.jsun.xml; /** * For searching and replacing a specific part in XML file * @author jerysun * */ public enum XMLPartEnum { ELEMENT_NAME, //Must be prefixed by <, for example, <Server ATTRIBUTE,//Must be in the format x="y" TEXT_NODE, UNKNOWN; }<file_sep>/src/main/java/com/jsun/text/TextSearchReplace.java package com.jsun.text; import java.io.*; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.jsun.SearchReplace; import com.jsun.type.SearchType; import com.jsun.type.TypeEnum; /** * This is an implementation of the interface SearchReplace * for text files processing, using FileInputStream and * FileOutputStream to reduce the memory consumption. * @author jerysun * @version 1.00 2018-04-08 */ public class TextSearchReplace implements SearchReplace { private final String path; private final SearchType searchType; public TextSearchReplace(String path, SearchType searchType) { this.path = path; this.searchType = searchType; } @Override public boolean fSearch(InputStream in, SearchType searchType) { if (in == null || searchType == null) return false; TypeEnum typeEnum = searchType.getTypeEnum(); try (Scanner sc = new Scanner(in, "UTF-8")) { while (sc.hasNextLine()) { String line = sc.nextLine(); switch (typeEnum) { case PHRASE: if(line.contains(searchType.getSearchString())) return true; break; case PATTERN: Pattern pattern = Pattern.compile(searchType.getSearchString()); Matcher matcher = pattern.matcher(line); if (matcher.find()) return true; break; case WILDCARD: //TODO return false; case VARIABLE: //TODO return false; case UNKNOWN: return false; default: break; } } } catch (Exception e) { e.printStackTrace(); return false; } return false; } @Override public void fReplace(InputStream in, SearchType searchType, String replaceString) throws IOException { if (in == null || searchType == null || replaceString == null || replaceString.isEmpty()) return; TypeEnum typeEnum = searchType.getTypeEnum(); try (Scanner sc = new Scanner(in, "UTF-8"); FileOutputStream fo = new FileOutputStream(getOutPath(path))) { while (sc.hasNextLine()) { String line = sc.nextLine(); switch (typeEnum) { case PHRASE: phraseReplace(line, searchType.getSearchString(), replaceString, fo); break; case PATTERN: patternReplace(line, searchType.getSearchString(), replaceString, fo); break; case WILDCARD: //TODO return; case VARIABLE: //TODO return; case UNKNOWN: return; default: break; } } fo.flush(); } } public void phraseReplace(String line, String targetString, String replaceString, FileOutputStream fo) throws IOException { String changedString = line.replaceAll(targetString, replaceString); StringBuilder sb = new StringBuilder(changedString); sb.append(System.getProperty("line.separator")); byte[] lineBytes = sb.toString().getBytes(); fo.write(lineBytes); } public void patternReplace(String line, String targetString, String replaceString, FileOutputStream fo) throws IOException { Pattern pattern = Pattern.compile(targetString); Matcher matcher = pattern.matcher(line); String changedString = matcher.replaceAll(replaceString); StringBuilder sb = new StringBuilder(changedString); sb.append(System.getProperty("line.separator")); byte[] lineBytes = sb.toString().getBytes(); fo.write(lineBytes); } public String getPath() { return path; } public SearchType getSearchType() { return searchType; } }
46602f74c4c588329eac6ad42e915d90eb8023e7
[ "Java" ]
5
Java
jerysun/large-files-search-replace
8507575fb5ba0519c6aed8c3aedc996bdda06e8b
ee82fcb5a0ed061e905dbf3c34fbe8a5ae625ef9
refs/heads/master
<repo_name>TravisSpangle/EmailList<file_sep>/spec/EmailList_spec.rb require 'spec_helper' describe EmailList do let(:sample_emails) { %w(<EMAIL> <EMAIL> <EMAIL> <EMAIL>) } def timed(cleaning_emails) time_start = Time.now cleaning_emails.call time_end = Time.now time_end - time_start end it 'has a version number' do expect(EmailList::VERSION).not_to be nil end it 'accepts a list of emails as arrays and passes back an array' do expect(EmailList.uniq(sample_emails).class).to eq(Array) end it 'provides a list of uniq emails in the original order it takes them.' do expect(EmailList.uniq(sample_emails)).to eq(%w(<EMAIL> <EMAIL> <EMAIL>)) end it 'processes 100,000 emails under 1 second.' do amount = 100_000 emails = [] (amount / 2).times do |n| emails << "<EMAIL>}_<EMAIL>" end # size doesn't matter expect(EmailList.uniq(emails)).to eq(emails) dirty_emails = proc do EmailList.uniq((emails + emails).shuffle) end expect(timed(dirty_emails)).to be < 1 end end <file_sep>/lib/EmailList.rb require "EmailList/version" module EmailList def self.uniq(emails) registry = {} uniq_emails = [] emails.each do |email| if registry[email].nil? registry[email] = true uniq_emails << email end end uniq_emails end end
6aa72af97d3ab8004324cd8b3d82f356257e3cfb
[ "Ruby" ]
2
Ruby
TravisSpangle/EmailList
f953e3fcd7eddacbb1ab32fb4eded0e81a8ac43c
c8145e694506a0e52e5fb4593067b5f4f4869fff
refs/heads/master
<file_sep>// chiedo all'utente di inserire un numero var numeroUno = prompt("inserisci un numero"); var numeroDue = prompt("inserisci un numero"); var numeroTre = prompt("inserisci un numero"); var numeroQuattro = prompt("inserisci un numero"); var numeroCinque = prompt("inserisci un numero"); var numeroSei = prompt("inserisci un numero"); var numeroSette = prompt("inserisci un numero"); var numeroOtto = prompt("inserisci un numero"); var numeroNove = prompt("inserisci un numero"); var numeroDieci = prompt("inserisci un numero"); for()<file_sep>// chiedo all'utente di inserire una parola // var x = prompt("inserisci la prima parola"); var y = prompt("inserisci la seconda parola"); // capire la più corta var parolaCorta = ""; var parolaLunga = ""; if (x.length < y.lenght) { parolaCorta = x; parolaLunga = y; } else if (x.length < y.lenght) // altra versione var parole = frase.split(' '); console.log(parole); var max = parole[0]; for(var i = 0; i < parole.length; i++){ if(parole[i].length > max.length ){ max = parole[i]; } } console.log('la parola più lunga della frase è: ' + max);
b3ea97db78a1f90d16c9a2a7e5870202756141e3
[ "JavaScript" ]
2
JavaScript
giuliop93/js-jssnack-blocco
8db12c0c757ed9b56b204552d3510a535c5001e6
c8441aef1f3939eeb3bed46863a9c9fb944073fd
refs/heads/main
<file_sep>import React from "react"; import "./styles/Header.css"; import Logo from "./images/airbnb-logo-img.jpg"; import SearchIcon from "@material-ui/icons/Search"; import { Avatar, Button, IconButton } from "@material-ui/core"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import LanguageIcon from "@material-ui/icons/Language"; import { Link } from "react-router-dom"; function Header() { return ( <div className="header"> <Link to="/"> <img className="header__icon" src={Logo} alt="airbnb logo" /> </Link> <div className="header__center"> <input type="text" placeholder="Search" /> <SearchIcon /> </div> <div className="header__right"> <Button variant="outlined"> <p>Become a host</p> </Button> <IconButton> <LanguageIcon /> </IconButton> <IconButton> <ExpandMoreIcon /> </IconButton> <Avatar /> </div> </div> ); } export default Header; <file_sep> <<<<<<<<<< AIRBNB CLONE APP >>>>>>>>> ----ReactJS ----Material-UI ----Firebase Link: https://airbnb-clone-app-96568.web.app/ <file_sep>export const items = [ { id: 1, imgUrl: "https://images.unsplash.com/photo-1598928636135-d146006ff4be?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80", location: "Private Room in center Miami", title: "Stay at this spacious Wells House", description: "1 guest . 1 bed . 1.5 shared bathroom . Wifi .Kitchen . Free parking . Washing Machine", star: 4.78, price: "$40 / night", total: "$117 total", }, { id: 2, imgUrl: "https://images.unsplash.com/photo-1586023492125-27b2c045efd7?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1134&q=80", location: "Penthouse in New York city", title: "Luxury at its best", description: "3 guest . 3 bed . 3.5 shared bathroom . Wifi .top chef Kitchen . Washing Machine", star: 5.52, price: "$450 / night", total: "$1117 total", }, { id: 3, imgUrl: "https://images.unsplash.com/photo-1567767292278-a4f21aa2d36e?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1350&q=80", location: "New Apartment in Atlanta", title: " Brand new apartment ", description: "2 guest . 2 bed . 2.5 bathroom . Kitchen ", star: 4.45, price: "$50 / night", total: "$217 total", }, { id: 4, imgUrl: "https://images.unsplash.com/photo-1550581190-9c1c48d21d6c?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1298&q=80", location: "The best to live south Miami", title: " Luxury house in Miami ", description: "2 guest . 1 bed . 1.5 bathroom . Kitchen . Living Room", star: 4.23, price: "$100 / night", total: "$789 total", }, ]; export const homeItems = [ { id: 200, src: "https://images.unsplash.com/photo-1601918774946-25832a4be0d6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1349&q=80", title: "Online Experience", description: "Unique activies we can do together, led by a world of hosts.", }, { id: 210, src: "https://images.unsplash.com/photo-1503174971373-b1f69850bded?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1387&q=80", title: "Entire homes", description: "Comfortable private places with room for friends or family.", }, { id: 220, src: "https://images.unsplash.com/photo-1521401830884-6c03c1c87ebb?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1350&q=80", title: "Unique stays", description: "Spaces that are more than just a place to sleep.", }, { id: 230, src: "https://images.unsplash.com/photo-1576343547429-1a9ac89d7013?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1267&q=80", title: "Penthouse in Miami Beach", description: "Superhost with a stunning view of the ocean .", price: "$310/night", }, { id: 240, src: "https://images.unsplash.com/photo-1578683010236-d716f9a3f461?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1350&q=80", title: "2 bedroom Flat", description: "Enjoy an amazing side of the Arizona desert", price: "$200/night", }, { id: 250, src: "https://images.unsplash.com/photo-1591825381767-c7137b8eda0f?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1350&q=80", title: "1 Bedroom apartment", description: "Spending a wonderful nigth with the star in the middle of forest .", price: "$170/night", }, ];
48f66c34a9b2f354fe807ec6c8cb89327dc19bea
[ "JavaScript", "Markdown" ]
3
JavaScript
ledney07/Airbnb-Clone-App
9a9b4397e37635704b02977fcae4681a8d05249d
3678fd463c934dc642f0b696d607414d3ef6b40f
refs/heads/master
<file_sep>package jsProject; public class JsFastFoodDTO { private int itemnum; private String menuname; private double price; private int amount; public int getItemnum() { return itemnum; } public void setItemnum(int itemnum) { this.itemnum = itemnum; } public String getMenuname() { return menuname; } public void setMenuname(String menuname) { this.menuname = menuname; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } @Override public String toString() { return "JsFastFoodDTO [itemnum=" + itemnum + ", menuname=" + menuname + ", price=" + price + ", amount=" + amount + "]"; } public JsFastFoodDTO(int itemnum, String menuname, double price, int amount) { super(); this.itemnum = itemnum; this.menuname = menuname; this.price = price; this.amount = amount; } public JsFastFoodDTO(String menuname, double price, int amount) { super(); this.menuname = menuname; this.price = price; this.amount = amount; } public JsFastFoodDTO(String menuname, double price) { super(); this.menuname = menuname; this.price = price; } public JsFastFoodDTO(String menuname, int amount) { super(); this.menuname = menuname; this.amount = amount; } public JsFastFoodDTO(String menuname) { super(); this.menuname = menuname; this.price = price; } public JsFastFoodDTO() { super(); // TODO Auto-generated constructor stub } } <file_sep>package jsProject; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.plaf.synth.SynthSeparatorUI; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import java.awt.event.ActionEvent; import javax.swing.JComboBox; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class Login extends JFrame { private JPanel contentPane; private JTextField tfUserid; private JPasswordField tfPassword; private JButton btnNew; private JButton btnmanager; private JButton btnLogin; private Sign join; private ImagePanel loginPanel; private MemberDTO dto; private MemberDAO dao; private Vector<String> choice; private JComboBox cbmanager; private boolean manager; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Login frame = new Login(); frame.setVisible(true); frame.setResizable(false); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Login() { contentPane = new JPanel(); setBounds(310, 100, 1300, 866); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImagePanel loginPanel= new ImagePanel(new ImageIcon ("D:\\work_java\\javaProject\\src\\JsProject\\fastfood.jpg").getImage()); contentPane.setSize(new Dimension(461, 496)); contentPane.setPreferredSize(loginPanel.getDim()); contentPane.add(loginPanel); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); tfUserid = new JTextField(); tfUserid.setFont(new Font("굴림", Font.BOLD, 26)); tfUserid.setBounds(1007, 484, 221, 50); loginPanel.add(tfUserid); tfUserid.setColumns(10); tfPassword = new JPasswordField(); tfPassword.setFont(new Font("굴림", Font.BOLD, 24)); tfPassword.setBounds(1007, 566, 221, 44); loginPanel.add(tfPassword); JLabel lblNewLabel = new JLabel("ID"); lblNewLabel.setFont(new Font("굴림", Font.BOLD | Font.ITALIC, 28)); lblNewLabel.setBounds(915, 486, 80, 44); loginPanel.add(lblNewLabel); JLabel lblPassword = new JLabel("<PASSWORD>"); lblPassword.setFont(new Font("굴림", Font.BOLD | Font.ITALIC, 28)); lblPassword.setBounds(841, 565, 154, 44); loginPanel.add(lblPassword); btnNew = new JButton("회원가입"); btnNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Sign join=new Sign(Login.this); join.setVisible(true); join.setResizable(false); join.setLocation(600,300); } }); btnNew.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\new.jpg")); btnNew.setPressedIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\new1.jpg")); btnNew.setBounds(1010, 717, 218, 38); loginPanel.add(btnNew); btnLogin = new JButton("로그인"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String userid=tfUserid.getText(); String password=String.valueOf(tfPassword.getPassword()); Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="SELECT userid, password FROM jsmember " +" WHERE userid=? AND password=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, userid); pstmt.setString(2, password); rs=pstmt.executeQuery(); if(rs.next()){ JOptionPane.showMessageDialog (Login.this, userid+"님 로그인 되셨습니다."); JsFastFoodSell join= new JsFastFoodSell(Login.this); join.setVisible(true); join.setResizable(false); dispose(); }else { JOptionPane.showMessageDialog( Login.this,"회원 아이디와 비밀번호를 확인해주세요."); } } catch (Exception e2) { e2.printStackTrace(); }finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//end finally } }); btnLogin.setBounds(1007, 620, 218, 38); loginPanel.add(btnLogin); btnLogin.setBorder(null); btnLogin.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\login3.jpg")); btnLogin.setPressedIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\login2.jpg")); btnmanager = new JButton(""); btnmanager.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String managerid=tfUserid.getText(); String managerpwd=String.valueOf(tfPassword.getPassword()); Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="SELECT managerid, managerpwd FROM manager " +" WHERE managerid=? AND managerpwd=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, managerid); pstmt.setString(2, managerpwd); rs=pstmt.executeQuery(); if(rs.next()){ JOptionPane.showMessageDialog( Login.this,"관리자로 로그인 되었습니다"); ManagerDms join= new ManagerDms(Login.this); join.setVisible(true); join.setResizable(false); dispose(); }else { JOptionPane.showMessageDialog( Login.this,"관리자아이디와 비밀번호를 확인해주세요."); } } catch (Exception e2) { e2.printStackTrace(); }finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//end finally } }); btnmanager.setBounds(1007, 668, 218, 38); loginPanel.add(btnmanager); btnmanager.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\manager.jpg")); btnmanager.setPressedIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\manager1.jpg")); } } <file_sep>package jsProject; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class ManagerSave extends JFrame { private JPanel contentPane; private JTable table; private JTextField tfManagerId; private JTextField tfManagerPwd; private JButton btnSave; private JButton btnUpdate; private JButton btnDelete; private ManagerDTO dto; private ManagerDAO dao; private DefaultTableModel model; private Vector<String> col; private ManagerDms frm; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // ManagerSave frame = new ManagerSave(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public ManagerSave(ManagerDms frm){ this(); this.frm=frm; } public ManagerSave() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 800, 534); contentPane = new JPanel(); ImagePanel ManagerSavePanel= new ImagePanel(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\managersave.jpg").getImage()); contentPane.setSize(new Dimension(461, 496)); contentPane.setPreferredSize(ManagerSavePanel.getDim()); contentPane.add(ManagerSavePanel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(12, 10, 309, 197); ManagerSavePanel.add(scrollPane); dao=new ManagerDAO();//dao 인스턴스 생성 //제목 열을위한 벡터 생성 col=new Vector<String>(); col.add("관리자아이디"); col.add("관리자 비밀번호"); table = new JTable(model); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int idx=table.getSelectedRow(); tfManagerId.setEditable(false); tfManagerId.setText(table.getValueAt(idx, 0)+""); tfManagerPwd.setText(table.getValueAt(idx, 1)+""); } }); scrollPane.setViewportView(table); JLabel lblNewLabel = new JLabel("관리자 아이디"); lblNewLabel.setFont(new Font("굴림", Font.BOLD, 16)); lblNewLabel.setForeground(Color.BLUE); lblNewLabel.setBounds(333, 11, 116, 25); ManagerSavePanel.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("관리자 비밀번호"); lblNewLabel_1.setFont(new Font("굴림", Font.BOLD, 16)); lblNewLabel_1.setForeground(Color.BLUE); lblNewLabel_1.setBounds(333, 65, 133, 25); ManagerSavePanel.add(lblNewLabel_1); tfManagerId = new JTextField(); tfManagerId.setBounds(478, 13, 163, 24); ManagerSavePanel.add(tfManagerId); tfManagerId.setColumns(10); tfManagerPwd = new JTextField(); tfManagerPwd.setBounds(478, 65, 163, 24); ManagerSavePanel.add(tfManagerPwd); tfManagerPwd.setColumns(10); btnSave = new JButton("추가"); btnSave.setFont(new Font("굴림", Font.BOLD, 20)); btnSave.setForeground(Color.BLACK); btnSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { input(); int result=dao.insertManager(dto); if (tfManagerId.getText().equals("")) { JOptionPane.showMessageDialog(ManagerSave.this, "아이디를 입력해주세요."); } else if (tfManagerPwd.getText().equals("")) { JOptionPane.showMessageDialog(ManagerSave.this, "비밀번호를 입력해주세요."); } else { if(result==1) { JOptionPane.showMessageDialog(ManagerSave.this, "관리자가 추가되었습니다."); list(); table.setModel(model); clear(); } } } }); btnSave.setBounds(653, 10, 104, 80); ManagerSavePanel.add(btnSave); btnUpdate = new JButton("수정"); btnUpdate.setFont(new Font("굴림", Font.BOLD, 17)); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { input(); int result=dao.updateManager(dto); if(result==1) { JOptionPane.showMessageDialog(ManagerSave.this, "수정되었습니다."); list(); table.setModel(model); clear(); } } }); btnUpdate.setBounds(478, 110, 125, 47); ManagerSavePanel.add(btnUpdate); btnDelete = new JButton("삭제"); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String managerid=tfManagerId.getText(); int result=0; int response=JOptionPane.showConfirmDialog(ManagerSave.this, "삭제하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { result=dao.deleteManager(managerid); } if(result==1) { JOptionPane.showMessageDialog(ManagerSave.this, "삭제되었습니다."); list(); table.setModel(model); clear(); } } }); btnDelete.setFont(new Font("굴림", Font.BOLD, 17)); btnDelete.setBounds(632, 110, 125, 47); ManagerSavePanel.add(btnDelete); setContentPane(contentPane); refreshTable(); } public void input() { String managerid=tfManagerId.getText(); String managerpwd=tfManagerPwd.getText(); dto=new ManagerDTO(managerid, managerpwd); }//end input() public void clear() { tfManagerId.setText(""); tfManagerPwd.setText(""); tfManagerId.requestFocus(); tfManagerId.setEditable(true); }//end clear() public void list() { model=new DefaultTableModel(dao.listManager(),col) { @Override public boolean isCellEditable(int row, int column) { return false; } }; }//end list() public void refreshTable() { DefaultTableModel model=new DefaultTableModel(dao.listManager(),col); //테이블에 데이터 채워짐 table.setModel(model); } } <file_sep>package jsProject; import java.awt.EventQueue; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import javax.swing.JTextField; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; public class JsFastFoodMenu extends JFrame { private JPanel contentPane; private JTable table; private Vector col; private JsFastFoodDAO dao; private DefaultTableModel model; private JTextField tfMenuname; private JTextField tfPrice; private JTextField tfAmount; private ManagerDms join; private JsFastFoodDTO dto; private JTextField tfItemnum; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // JsFastFoodMenu frame = new JsFastFoodMenu(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public JsFastFoodMenu(ManagerDms join) { this(); this.join=join; } public JsFastFoodMenu() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 528, 410); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(12, 10, 317, 344); contentPane.add(scrollPane); dao=new JsFastFoodDAO(); col= new Vector(); col.add("제품번호"); col.add("메뉴"); col.add("가격"); col.add("재고"); table = new JTable(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { selectTable(); } }); scrollPane.setViewportView(table); tfMenuname = new JTextField(); tfMenuname.setBounds(402, 46, 95, 21); contentPane.add(tfMenuname); tfMenuname.setColumns(10); tfPrice = new JTextField(); tfPrice.setBounds(402, 83, 95, 21); contentPane.add(tfPrice); tfPrice.setColumns(10); tfAmount = new JTextField(); tfAmount.setBounds(402, 120, 95, 21); contentPane.add(tfAmount); tfAmount.setColumns(10); JButton btnInsert = new JButton("재고 추가"); btnInsert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menuname=tfMenuname.getText(); int amount=Integer.parseInt(tfAmount.getText()); dto = new JsFastFoodDTO(menuname, amount); int result=dao.updateAmount(dto); if(result==1){ JOptionPane.showMessageDialog(JsFastFoodMenu.this, "추가 되었습니다"); list(); table.setModel(model); clear(); } } }); btnInsert.setBounds(383, 164, 114, 47); contentPane.add(btnInsert); JButton btnUpdate = new JButton("메뉴 수정"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int itemnum=Integer.parseInt(tfItemnum.getText()); String menuname=tfMenuname.getText(); double price=Double.parseDouble(tfPrice.getText()); int amount=Integer.parseInt(tfAmount.getText()); dto=new JsFastFoodDTO(itemnum, menuname, price, amount); int result=dao.updateFastFood(dto); if(result==1) { JOptionPane.showMessageDialog(JsFastFoodMenu.this, "수정되었습니다."); list(); table.setModel(model); clear(); } } }); btnUpdate.setBounds(381, 238, 116, 47); contentPane.add(btnUpdate); JButton btnDelete = new JButton("메뉴 삭제"); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int itemnum=Integer.parseInt(tfItemnum.getText()); int result=0; int response=JOptionPane.showConfirmDialog(JsFastFoodMenu.this, "삭제하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { result=dao.deleteFastFood(itemnum); } if(result==1) { JOptionPane.showMessageDialog(JsFastFoodMenu.this, "삭제되었습니다."); list(); table.setModel(model); clear(); } } }); btnDelete.setBounds(381, 307, 116, 47); contentPane.add(btnDelete); tfItemnum = new JTextField(); tfItemnum.setEditable(false); tfItemnum.setBounds(402, 10, 95, 21); contentPane.add(tfItemnum); tfItemnum.setColumns(10); JLabel lblNewLabel = new JLabel("제품번호"); lblNewLabel.setBounds(341, 13, 55, 15); contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("메뉴명"); lblNewLabel_1.setBounds(341, 49, 57, 15); contentPane.add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("가격"); lblNewLabel_2.setBounds(341, 86, 57, 15); contentPane.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("재고"); lblNewLabel_3.setBounds(341, 123, 57, 15); contentPane.add(lblNewLabel_3); refreshTable(); } public void refreshTable() { DefaultTableModel model= new DefaultTableModel(dao.listFastFood(),col); table.setModel(model); } public void selectTable() { int idx=table.getSelectedRow(); tfItemnum.setEditable(false); tfItemnum.setText(table.getValueAt(idx, 0)+""); tfMenuname.setText(table.getValueAt(idx, 1)+""); tfPrice.setText(table.getValueAt(idx, 2)+""); tfAmount.setText(table.getValueAt(idx, 3)+""); } public void input() { String menuname=tfMenuname.getText(); double price=Double.parseDouble(tfPrice.getText()); int amount=Integer.parseInt(tfAmount.getText()); dto=new JsFastFoodDTO(menuname, price, amount); } public void clear() { tfItemnum.setText(""); tfMenuname.setText(""); tfPrice.setText(""); tfAmount.setText("");; }//end clear() public void list() { model=new DefaultTableModel(dao.listFastFood(),col) { @Override public boolean isCellEditable(int row, int column) { return false; } }; }//end list() } <file_sep>package jsProject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; public class JsFastFoodDAO { public JsFastFoodDTO menuName(String menuname) { JsFastFoodDTO dto=null; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select amount from fastfood where menuname=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, menuname); rs=pstmt.executeQuery(); if(rs.next()) { int amount= rs.getInt("amount"); dto=new JsFastFoodDTO(menuname, amount); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return dto; }//end hambuger() public int updateFastFood(JsFastFoodDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="update fastfood set menuname=?, price=?, amount=? where itemnum=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, dto.getMenuname()); pstmt.setDouble(2, dto.getPrice()); pstmt.setInt(3, dto.getAmount()); pstmt.setInt(4, dto.getItemnum()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end updateFastFood() public Vector listFastFood() { Vector items=new Vector(); Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select itemnum, menuname, price, amount from fastfood"; pstmt=conn.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()) { Vector row=new Vector(); row.add(rs.getInt("itemnum")); row.add(rs.getString("menuname")); row.add(rs.getDouble("price")); row.add(rs.getInt("amount")); items.add(row); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return items; //백터 리턴 }//end listMember() public boolean useridck (String userid) { boolean b= true; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select userid from jsmember " + " where userid like ?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, userid); rs=pstmt.executeQuery(); b=rs.next(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return b; //백터 리턴 }//end Joinck() public JsFastFoodDTO viewFastFood(String menuname) { JsFastFoodDTO dto=null; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select menuname, price, amount from fastfood " + " FROM fastfood WHERE menuname=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, menuname); rs=pstmt.executeQuery(); if(rs.next()) { double price=Double.parseDouble("price"); int amount=Integer.parseInt("amount"); dto=new JsFastFoodDTO(menuname, price, amount); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return dto; }//end viewFastFood() public int deleteFastFood(int itemnum) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="delete from fastfood where itemnum=?"; pstmt=conn.prepareStatement(sql); pstmt.setInt(1, itemnum); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end deleteFastFood() public int insertFastFood(JsFastFoodDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="INSERT INTO fastfood (menuname, price, amount) " +" VALUES (?,?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, dto.getMenuname()); pstmt.setDouble(2, dto.getPrice()); pstmt.setInt(3, dto.getAmount()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end insertFastFood() public int updateAmount(JsFastFoodDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="update fastfood set amount=amount + ? where menuname=?"; pstmt=conn.prepareStatement(sql); pstmt.setInt(1, dto.getAmount()); pstmt.setString(2, dto.getMenuname()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end updateAmount() public int updateAmountm(JsFastFoodDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="update fastfood set amount=? where menuname=?"; pstmt=conn.prepareStatement(sql); pstmt.setInt(1, dto.getAmount()); pstmt.setString(2, dto.getMenuname()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end updateAmountm() }<file_sep>package jsProject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; public class ManagerDAO { public int insertManager(ManagerDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="INSERT INTO manager (managerid, managerpwd) " +" VALUES (?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, dto.getManagerid()); pstmt.setString(2, dto.getManagerpwd()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end insertManager() public Vector listManager() { Vector items=new Vector(); Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select managerid, managerpwd from manager"; pstmt=conn.prepareStatement(sql); rs=pstmt.executeQuery(); while(rs.next()) { Vector row=new Vector(); row.add(rs.getString("managerid")); row.add(rs.getString("managerpwd")); items.add(row); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return items; //백터 리턴 }//end listManager() public int deleteManager(String managerid) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="delete from manager where managerid=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, managerid); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end deleteManager() public int updateManager(ManagerDTO dto) { int result=0; Connection conn=null; PreparedStatement pstmt=null; try { conn=DB.dbConn(); String sql="update manager set managerpwd=? where managerid=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, dto.getManagerpwd()); pstmt.setString(2, dto.getManagerid()); result=pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return result; }//end updateManager() public ManagerDTO viewManager(String managerid) { ManagerDTO dto=null; Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { conn=DB.dbConn(); String sql="select managerid, managerpwd FROM manager WHERE managerid=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, managerid); rs=pstmt.executeQuery(); if(rs.next()) { String managerpwd=rs.getString("managerpwd"); dto=new ManagerDTO(managerid, managerpwd); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(pstmt!=null) pstmt.close(); } catch (Exception e2) { e2.printStackTrace(); } try { if(conn!=null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } }//finally return dto; }//end viewManager() } <file_sep>package jsProject; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class JsFastFoodSell extends JFrame { private JPanel contentPane; private JTextField tfMenu; private JButton btnBuger; private JButton btnHotdog; private JButton btnTacos; private JButton btnPizzaS; private JButton btnCola; private JButton btnCoffee; private JButton btnIceCream; private JButton btnPotato; private JButton btnSet1; private JButton btnSet2; private JButton btnSet3; private JButton btnPizzaL; private JButton btnbuy; private JComboBox comboBox; private JButton btnChoice; private JButton btnLogout; private JsFastFoodDTO dto; private JsFastFoodDAO dao; private JTextField tfPrice; private JTextField tfHambuger; private JTextField tfHambugerP; private JTextField tfHotdog; private JTextField tfHotdogP; private JTextField tfTacos; private JTextField tfPizzaS; private JTextField tfTacosP; private JTextField tfPizzaSP; private JTextField tfCola; private JTextField tfColaP; private JTextField tfCoffee; private JTextField tfCoffeeP; private JTextField tfIcecream; private JTextField tfIcecreamP; private JTextField tfPotato; private JTextField tfPotatoP; private JTextField tfSet1; private JTextField tfSet1P; private JTextField tfSet2; private JTextField tfSet2P; private JTextField tfSet3; private JTextField tfSet3P; private JTextField tfPizzaLage; private JTextField tfPizzaLageP; private Vector<String> num; private String menuname, combonum,a; private Login join; private double price, tot; private int amount; private JScrollPane scrollPane; private JTable table; private Vector col, list, items, cols; private JLabel lblMent; private JLabel lblNewLabel; private DefaultTableModel model1; private JButton btnNewButton; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // JsFastFoodSell frame = new JsFastFoodSell(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public JsFastFoodSell(Login join){ this(); this.join=join; } public JsFastFoodSell() { col=new Vector(); col.add("메뉴"); col.add("수량"); col.add("가격"); Vector items=new Vector(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(500, 200, 981, 665); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); tfMenu = new JTextField(); tfMenu.setEditable(false); tfMenu.setBounds(509, 504, 137, 30); tfMenu.setFont(new Font("굴림", Font.BOLD, 16)); contentPane.add(tfMenu); tfMenu.setColumns(10); btnBuger = new JButton(""); btnBuger.setBounds(22, 10, 100, 100); btnBuger.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfHambuger.getText(); String price=tfHambugerP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnBuger.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\bigbuger.png")); tfPrice = new JTextField(); tfPrice.setEditable(false); tfPrice.setBounds(658, 504, 75, 30); tfPrice.setFont(new Font("굴림", Font.BOLD, 20)); contentPane.add(tfPrice); tfPrice.setColumns(10); tfHambuger = new JTextField(); tfHambuger.setBounds(22, 122, 70, 21); tfHambuger.setFont(new Font("굴림", Font.BOLD, 12)); tfHambuger.setEditable(false); contentPane.add(tfHambuger); tfHambuger.setColumns(10); tfHambugerP = new JTextField(); tfHambugerP.setBounds(96, 122, 26, 21); tfHambugerP.setFont(new Font("굴림", Font.BOLD, 12)); tfHambugerP.setEditable(false); contentPane.add(tfHambugerP); tfHambugerP.setColumns(10); contentPane.add(btnBuger); btnHotdog = new JButton(""); btnHotdog.setBounds(148, 10, 97, 100); btnHotdog.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfHotdog.getText(); String price=tfHotdogP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnHotdog.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\hotdog.png")); contentPane.add(btnHotdog); btnTacos = new JButton(""); btnTacos.setBounds(272, 10, 100, 100); btnTacos.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfTacos.getText(); String price=tfTacosP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnTacos.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\tacos.png")); contentPane.add(btnTacos); btnPizzaS = new JButton(""); btnPizzaS.setBounds(397, 10, 100, 100); btnPizzaS.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfPizzaS.getText(); String price=tfPizzaSP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnPizzaS.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\pizza.png")); contentPane.add(btnPizzaS); btnCola = new JButton(""); btnCola.setBounds(22, 153, 100, 100); btnCola.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfCola.getText(); String price=tfCoffeeP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnCola.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\cola.png")); contentPane.add(btnCola); btnCoffee = new JButton(""); btnCoffee.setBounds(150, 153, 100, 100); btnCoffee.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfCoffee.getText(); String price=tfCoffeeP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnCoffee.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\coffe.png")); contentPane.add(btnCoffee); btnIceCream = new JButton(""); btnIceCream.setBounds(272, 153, 100, 100); btnIceCream.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfIcecream.getText(); String price=tfIcecreamP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnIceCream.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\icecream.png")); contentPane.add(btnIceCream); btnPotato = new JButton(""); btnPotato.setBounds(397, 153, 100, 100); btnPotato.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfPotato.getText(); String price=tfPotatoP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnPotato.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\potato.png")); contentPane.add(btnPotato); btnSet1 = new JButton(""); btnSet1.setBounds(509, 10, 200, 200); btnSet1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfSet1.getText(); String price=tfSet1P.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnSet1.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\set1.png")); contentPane.add(btnSet1); btnSet2 = new JButton(""); btnSet2.setBounds(509, 263, 200, 200); btnSet2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfSet3.getText(); String price=tfSet3P.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnSet2.setIcon(new ImageIcon( "D:\\work_java\\javaProject\\src\\JsProject\\set3.png")); contentPane.add(btnSet2); btnSet3 = new JButton(""); btnSet3.setBounds(746, 10, 200, 200); btnSet3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfSet2.getText(); String price=tfSet2P.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnSet3.setIcon(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\set2.png")); contentPane.add(btnSet3); btnPizzaL = new JButton(""); btnPizzaL.setBounds(746, 263, 200, 200); btnPizzaL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String menu=tfPizzaLage.getText(); String price=tfPizzaLageP.getText(); tfMenu.setText(menu); tfPrice.setText(price); } }); btnPizzaL.setIcon(new ImageIcon ("D:\\work_java\\javaProject\\src\\JsProject\\bigpizza.png")); contentPane.add(btnPizzaL); num=new Vector<String>(); // num.add("선택"); for(int i=0; i<=100; i++) { num.add(String.valueOf(i)); } comboBox = new JComboBox(num); comboBox.setBounds(789, 504, 55, 30); comboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object a=e.getItem(); combonum=a+""; } }); contentPane.add(comboBox); btnChoice = new JButton("선택"); btnChoice.setBounds(856, 505, 90, 29); btnChoice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(tfMenu.getText().equals("")){ JOptionPane.showMessageDialog(JsFastFoodSell.this, "메뉴를 선택해주세요."); } else if(Integer.parseInt(combonum)==0 || Double.parseDouble(tfPrice.getText())==0){ JOptionPane.showMessageDialog(JsFastFoodSell.this, "수량을 선택해주세요"); } else { if(Integer.parseInt(combonum) > 0 || Double.parseDouble(tfPrice.getText()) > 0) { double price=Double.parseDouble(tfPrice.getText()); int amount=Integer.parseInt(combonum); double tot=price*amount; Vector list=new Vector(); list.add(tfMenu.getText()); list.add(amount); list.add(tot); items.add(list); DefaultTableModel model=new DefaultTableModel(items,col); table.setModel(model); int idx=table.getRowCount(); double sum =0.0; for(int i=0; i<idx; i++) { sum += Double.parseDouble(table.getValueAt(i, 2).toString()); } lblMent.setText("총가격은 "+sum+ "달러 입니다."); } } comboBox.setSelectedIndex(0); tfMenu.setText(""); tfPrice.setText(""); } }); contentPane.add(btnPizzaL); btnbuy = new JButton("구매"); btnbuy.setBounds(509, 560, 114, 53); btnbuy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int response=JOptionPane.showConfirmDialog (JsFastFoodSell.this, lblMent.getText()+" 구매하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(JsFastFoodSell.this, "주문하신 상품이 구매되었습니다."); int idx=table.getRowCount(); int amount=0; int minus=0; for(int i=0; i<idx;) { minus = Integer.parseInt(table.getValueAt(i, 1).toString()); menuname=table.getValueAt(i, 0).toString(); int a=dao.menuName(menuname).getAmount(); amount=a-minus; dto=new JsFastFoodDTO(menuname, amount); int result=dao.updateAmountm(dto); i++; } Vector list=new Vector(); list.add(tfMenu.getText()); list.add(amount); list.add(tot); items.add(list); DefaultTableModel model=new DefaultTableModel(items,col); table.setModel(model); lblMent.setText(""); tfMenu.setText(""); tfPrice.setText(""); comboBox.setSelectedIndex(0); model.setNumRows(0); } } }); btnbuy.setFont(new Font("굴림", Font.BOLD, 16)); contentPane.add(btnbuy); btnChoice.setFont(new Font("굴림", Font.BOLD, 15)); contentPane.add(btnChoice); btnLogout = new JButton("로그아웃"); btnLogout.setBounds(832, 561, 114, 53); btnLogout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int response=JOptionPane.showConfirmDialog (JsFastFoodSell.this, "로그아웃 하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { System.exit(0); } } }); btnLogout.setFont(new Font("굴림", Font.BOLD, 15)); contentPane.add(btnLogout); JButton btnCancle = new JButton("취소"); btnCancle.setBounds(672, 560, 114, 53); btnCancle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int response=JOptionPane.showConfirmDialog (JsFastFoodSell.this, "취소하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { DefaultTableModel model=new DefaultTableModel(items,col); table.setModel(model); model.setNumRows(0); lblMent.setText(""); tfMenu.setText(""); tfPrice.setText(""); comboBox.setSelectedIndex(0); } } }); btnCancle.setFont(new Font("굴림", Font.BOLD, 16)); contentPane.add(btnCancle); tfHotdog = new JTextField(); tfHotdog.setBounds(150, 122, 70, 21); tfHotdog.setEditable(false); tfHotdog.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfHotdog); tfHotdog.setColumns(10); tfHotdogP = new JTextField(); tfHotdogP.setBounds(224, 122, 26, 21); tfHotdogP.setEditable(false); tfHotdogP.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfHotdogP); tfHotdogP.setColumns(10); tfTacos = new JTextField(); tfTacos.setBounds(272, 122, 70, 21); tfTacos.setFont(new Font("굴림", Font.BOLD, 12)); tfTacos.setEditable(false); contentPane.add(tfTacos); tfTacos.setColumns(10); tfTacosP = new JTextField(); tfTacosP.setBounds(346, 122, 26, 21); tfTacosP.setFont(new Font("굴림", Font.BOLD, 12)); tfTacosP.setEditable(false); contentPane.add(tfTacosP); tfTacosP.setColumns(10); tfPizzaS = new JTextField(); tfPizzaS.setBounds(397, 122, 70, 21); tfPizzaS.setFont(new Font("굴림", Font.BOLD, 12)); tfPizzaS.setEditable(false); contentPane.add(tfPizzaS); tfPizzaS.setColumns(10); tfPizzaSP = new JTextField(); tfPizzaSP.setBounds(471, 122, 26, 21); tfPizzaSP.setFont(new Font("굴림", Font.BOLD, 12)); tfPizzaSP.setEditable(false); contentPane.add(tfPizzaSP); tfPizzaSP.setColumns(10); tfCola = new JTextField(); tfCola.setBounds(22, 263, 70, 21); tfCola.setFont(new Font("굴림", Font.BOLD, 12)); tfCola.setEditable(false); contentPane.add(tfCola); tfCola.setColumns(10); tfColaP = new JTextField(); tfColaP.setBounds(96, 263, 26, 21); tfColaP.setFont(new Font("굴림", Font.BOLD, 12)); tfColaP.setEditable(false); contentPane.add(tfColaP); tfColaP.setColumns(10); tfCoffee = new JTextField(); tfCoffee.setBounds(150, 263, 70, 21); tfCoffee.setEditable(false); tfCoffee.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfCoffee); tfCoffee.setColumns(10); tfCoffeeP = new JTextField(); tfCoffeeP.setBounds(224, 263, 26, 21); tfCoffeeP.setEditable(false); tfCoffeeP.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfCoffeeP); tfCoffeeP.setColumns(10); tfIcecream = new JTextField(); tfIcecream.setBounds(272, 263, 70, 21); tfIcecream.setEditable(false); tfIcecream.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfIcecream); tfIcecream.setColumns(10); tfIcecreamP = new JTextField(); tfIcecreamP.setBounds(346, 263, 26, 21); tfIcecreamP.setFont(new Font("굴림", Font.BOLD, 12)); tfIcecreamP.setEditable(false); contentPane.add(tfIcecreamP); tfIcecreamP.setColumns(10); tfPotato = new JTextField(); tfPotato.setBounds(397, 263, 70, 21); tfPotato.setEditable(false); tfPotato.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfPotato); tfPotato.setColumns(10); tfPotatoP = new JTextField(); tfPotatoP.setBounds(471, 263, 26, 21); tfPotatoP.setEditable(false); tfPotatoP.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfPotatoP); tfPotatoP.setColumns(10); tfSet1 = new JTextField(); tfSet1.setBounds(509, 220, 116, 21); tfSet1.setEditable(false); tfSet1.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfSet1); tfSet1.setColumns(10); tfSet1P = new JTextField(); tfSet1P.setBounds(639, 220, 70, 21); tfSet1P.setEditable(false); tfSet1P.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfSet1P); tfSet1P.setColumns(10); tfSet2 = new JTextField(); tfSet2.setBounds(746, 220, 116, 21); tfSet2.setFont(new Font("굴림", Font.BOLD, 12)); tfSet2.setEditable(false); contentPane.add(tfSet2); tfSet2.setColumns(10); tfSet2P = new JTextField(); tfSet2P.setBounds(876, 220, 70, 21); tfSet2P.setFont(new Font("굴림", Font.BOLD, 12)); tfSet2P.setEditable(false); contentPane.add(tfSet2P); tfSet2P.setColumns(10); tfSet3 = new JTextField(); tfSet3.setBounds(509, 473, 116, 21); tfSet3.setFont(new Font("굴림", Font.BOLD, 12)); tfSet3.setEditable(false); contentPane.add(tfSet3); tfSet3.setColumns(10); tfSet3P = new JTextField(); tfSet3P.setBounds(639, 473, 70, 21); tfSet3P.setFont(new Font("굴림", Font.BOLD, 12)); tfSet3P.setEditable(false); contentPane.add(tfSet3P); tfSet3P.setColumns(10); tfPizzaLage = new JTextField(); tfPizzaLage.setBounds(746, 473, 116, 21); tfPizzaLage.setFont(new Font("굴림", Font.BOLD, 12)); tfPizzaLage.setEditable(false); contentPane.add(tfPizzaLage); tfPizzaLage.setColumns(10); tfPizzaLageP = new JTextField(); tfPizzaLageP.setBounds(876, 473, 70, 21); tfPizzaLageP.setEditable(false); tfPizzaLageP.setFont(new Font("굴림", Font.BOLD, 12)); contentPane.add(tfPizzaLageP); tfPizzaLageP.setColumns(10); cols= new Vector(); cols.add("제품번호"); cols.add("메뉴"); cols.add("가격"); cols.add("수량"); dao=new JsFastFoodDAO(); model1=new DefaultTableModel(dao.listFastFood(),cols); tfHambuger.setText(model1.getValueAt(0, 1)+""); tfHambugerP.setText(model1.getValueAt(0, 2)+""); tfHotdog.setText(model1.getValueAt(1, 1)+""); tfHotdogP.setText(model1.getValueAt(1, 2)+""); tfTacos.setText(model1.getValueAt(2, 1)+""); tfTacosP.setText(model1.getValueAt(2, 2)+""); tfPizzaS.setText(model1.getValueAt(3, 1)+""); tfPizzaSP.setText(model1.getValueAt(3, 2)+""); tfCola.setText(model1.getValueAt(4, 1)+""); tfColaP.setText(model1.getValueAt(4, 2)+""); tfCoffee.setText(model1.getValueAt(5, 1)+""); tfCoffeeP.setText(model1.getValueAt(5, 2)+""); tfIcecream.setText(model1.getValueAt(6, 1)+""); tfIcecreamP.setText(model1.getValueAt(6, 2)+""); tfPotato.setText(model1.getValueAt(7, 1)+""); tfPotatoP.setText(model1.getValueAt(7, 2)+""); tfSet1.setText(model1.getValueAt(8, 1)+""); tfSet1P.setText(model1.getValueAt(8, 2)+""); tfSet2.setText(model1.getValueAt(9, 1)+""); tfSet2P.setText(model1.getValueAt(9, 2)+""); tfSet3.setText(model1.getValueAt(10, 1)+""); tfSet3P.setText(model1.getValueAt(10, 2)+""); tfPizzaLage.setText(model1.getValueAt(11, 1)+""); tfPizzaLageP.setText(model1.getValueAt(11, 2)+""); scrollPane = new JScrollPane(); scrollPane.setBounds(12, 315, 485, 219); contentPane.add(scrollPane); table = new JTable(); scrollPane.setViewportView(table); lblMent = new JLabel(""); lblMent.setFont(new Font("굴림", Font.BOLD, 20)); lblMent.setBounds(12, 544, 376, 69); contentPane.add(lblMent); lblNewLabel = new JLabel(" 수량"); lblNewLabel.setFont(new Font("굴림", Font.BOLD, 14)); lblNewLabel.setBounds(736, 504, 50, 30); contentPane.add(lblNewLabel); btnNewButton = new JButton("메뉴삭제"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model=(DefaultTableModel) table.getModel(); int response=JOptionPane.showConfirmDialog (JsFastFoodSell.this, "선택하신 메뉴를 삭제 하시겠습니까?"); if(response==JOptionPane.YES_OPTION) { int selectidx=table.getSelectedRow(); if(selectidx==-1) { JOptionPane.showMessageDialog(JsFastFoodSell.this, "메뉴를 선택하세요."); } else { JOptionPane.showMessageDialog(JsFastFoodSell.this, "삭제 되었습니다."); int idx=table.getRowCount(); double sum =0.0; for(int i=0; i<idx; i++) { sum += Double.parseDouble(table.getValueAt(i, 2).toString()); } sum = sum-Double.parseDouble(table.getValueAt(selectidx, 2).toString()); lblMent.setText("총가격은 "+sum+ "달러 입니다"); model.removeRow(selectidx); } } } }); btnNewButton.setBounds(397, 544, 100, 69); contentPane.add(btnNewButton); } public void clear() { DefaultTableModel model=new DefaultTableModel(items,col); table.setModel(model); model.setNumRows(0); lblMent.setText(""); tfMenu.setText(""); tfPrice.setText(""); comboBox.setSelectedIndex(0); } } <file_sep>package jsProject; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.Calendar; import java.util.Vector; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.SwingConstants; public class MemberSave extends JFrame { private JPanel contentPane; private ManagerDms frm; private JTextField tfCstnum; private JTextField tfName; private JTextField tfId; private JTextField tfPwd; private JTextField tfPwdck; private JTextField tfDadrs; private JTextField tfAdrsnum; private JTextField tfEmail; private JTextField tfAdrs; private JTextField tfHp2; private JTextField tfHp3; private JTextField tfAdrsnum2; private JButton btnSave; private JComboBox comboYear; private JComboBox comboMon; private JComboBox comboDay; private Calendar oCalendar; private JRadioButton rdbtnWoman; private JRadioButton rdbtnMan; private JComboBox comboHp; private JComboBox cbEmail; private Vector<String> year,mon,day,hpnum,emailsite; private MemberDTO dto; private MemberDAO dao; private boolean brepetitechk=false; private boolean checkId; private String dayck,monck,yearck,number,sex,emailst; private final ButtonGroup buttonGroup_1 = new ButtonGroup(); private JButton btnNewButton; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // MemberSave frame = new MemberSave(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public MemberSave(ManagerDms frm){ this(); this.frm=frm; } public MemberSave() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 680, 453); contentPane = new JPanel(); ImagePanel memberSavePanel= new ImagePanel(new ImageIcon("D:\\work_java\\javaProject\\src\\JsProject\\membersave.jpg").getImage()); contentPane.setSize(new Dimension(461, 496)); contentPane.setPreferredSize(memberSavePanel.getDim()); contentPane.add(memberSavePanel); setContentPane(contentPane); JLabel lblNewLabel = new JLabel("no"); lblNewLabel.setBounds(12, 45, 23, 15); memberSavePanel.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("이름"); lblNewLabel_1.setBounds(12, 73, 57, 15); memberSavePanel.add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("아이디"); lblNewLabel_2.setBounds(12, 101, 39, 15); memberSavePanel.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("비밀번호"); lblNewLabel_3.setBounds(12, 131, 57, 15); memberSavePanel.add(lblNewLabel_3); tfCstnum = new JTextField(); tfCstnum.setEditable(false); tfCstnum.setBounds(35, 42, 34, 21); memberSavePanel.add(tfCstnum); tfCstnum.setColumns(10); tfName = new JTextField(); tfName.setBounds(53, 70, 67, 21); memberSavePanel.add(tfName); tfName.setColumns(10); JLabel lblNewLabel_4 = new JLabel("성별"); lblNewLabel_4.setBounds(79, 45, 34, 15); memberSavePanel.add(lblNewLabel_4); tfId = new JTextField(); tfId.setBounds(53, 98, 67, 21); memberSavePanel.add(tfId); tfId.setColumns(10); tfPwd = new JTextField(); tfPwd.setBounds(88, 128, 121, 21); memberSavePanel.add(tfPwd); tfPwd.setColumns(10); JLabel lblNewLabel_5 = new JLabel("비번확인"); lblNewLabel_5.setBounds(12, 162, 57, 15); memberSavePanel.add(lblNewLabel_5); tfPwdck = new JTextField(); tfPwdck.setBounds(88, 159, 121, 21); memberSavePanel.add(tfPwdck); tfPwdck.setColumns(10); JLabel lblNewLabel_6 = new JLabel("생년월일"); lblNewLabel_6.setBounds(223, 73, 57, 15); memberSavePanel.add(lblNewLabel_6); JLabel lblNewLabel_7 = new JLabel("핸드폰"); lblNewLabel_7.setBounds(223, 101, 57, 15); memberSavePanel.add(lblNewLabel_7); tfDadrs = new JTextField(); tfDadrs.setBounds(582, 159, 86, 21); memberSavePanel.add(tfDadrs); tfDadrs.setColumns(10); JLabel lblNewLabel_8 = new JLabel("이메일"); lblNewLabel_8.setBounds(223, 45, 45, 15); memberSavePanel.add(lblNewLabel_8); JLabel lblNewLabel_9 = new JLabel("우편번호"); lblNewLabel_9.setBounds(223, 131, 57, 15); memberSavePanel.add(lblNewLabel_9); tfAdrsnum = new JTextField(); tfAdrsnum.setBounds(281, 128, 97, 21); memberSavePanel.add(tfAdrsnum); tfAdrsnum.setColumns(10); JLabel lblNewLabel_10 = new JLabel("주소"); lblNewLabel_10.setBounds(225, 162, 34, 15); memberSavePanel.add(lblNewLabel_10); JLabel lblNewLabel_11 = new JLabel("상세주소"); lblNewLabel_11.setBounds(528, 162, 57, 15); memberSavePanel.add(lblNewLabel_11); tfEmail = new JTextField(); tfEmail.setBounds(281, 42, 112, 21); memberSavePanel.add(tfEmail); tfEmail.setColumns(10); tfAdrs = new JTextField(); tfAdrs.setBounds(279, 159, 247, 21); memberSavePanel.add(tfAdrs); tfAdrs.setColumns(10); rdbtnMan = new JRadioButton("남"); buttonGroup_1.add(rdbtnMan); rdbtnMan.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED) { sex="남"; } } }); rdbtnMan.setBounds(108, 41, 39, 23); memberSavePanel.add(rdbtnMan); rdbtnWoman = new JRadioButton("여"); buttonGroup_1.add(rdbtnWoman); rdbtnWoman.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED) { sex="여"; } } }); rdbtnWoman.setBounds(170, 41, 39, 23); memberSavePanel.add(rdbtnWoman); oCalendar = Calendar.getInstance( ); int toyear = oCalendar.get(Calendar.YEAR); year =new Vector<String>(); for(int i = toyear; i>= toyear -100; i--){ year.add(String.valueOf(i)); } comboYear = new JComboBox(); comboYear.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object a = e.getItem(); yearck=a+"년"; } }); comboYear.setModel(new DefaultComboBoxModel (year.toArray(new String[year.size()]))); comboYear.setSelectedItem(String.valueOf(toyear)); comboYear.setBounds(282, 70, 57, 21); memberSavePanel.add(comboYear); comboYear.setSelectedIndex(25); mon=new Vector<String>(); mon.add("선택"); for(int i=1; i<=12; i++) { mon.add(String.valueOf(i)); } comboMon = new JComboBox(); comboMon.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object b = e.getItem(); monck=b+"월"; } }); comboMon.setModel(new DefaultComboBoxModel (mon.toArray(new String[mon.size()]))); comboYear.setSelectedItem(String.valueOf(mon)); comboMon.setBounds(363, 70, 60, 21); memberSavePanel.add(comboMon); day=new Vector<String>(); day.add("선택"); for(int i=1; i<=31; i++) { day.add(String.valueOf(i)); } comboDay = new JComboBox(); comboDay.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object c = e.getItem(); dayck= c+"일"; } }); comboDay.setModel(new DefaultComboBoxModel (day.toArray(new String[day.size()]))); comboYear.setSelectedItem(String.valueOf(day)); comboDay.setBounds(445, 70, 57, 21); memberSavePanel.add(comboDay); emailsite =new Vector<String>(); emailsite.add("=====선택====="); emailsite.add("@naver.com"); emailsite.add("@gmail.com"); emailsite.add("@hanmail.net"); emailsite.add("@nate.com"); emailsite.add("@yahoo.com"); emailsite.add("@lycos.com"); cbEmail = new JComboBox(); cbEmail.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object w = e.getItem(); emailst=w+""; } }); cbEmail.setModel(new DefaultComboBoxModel (emailsite.toArray(new String[emailsite.size()]))); cbEmail.setBounds(405, 42, 121, 21); memberSavePanel.add(cbEmail); hpnum=new Vector<String>(); hpnum.add("선택"); hpnum.add("010"); hpnum.add("011"); hpnum.add("016"); hpnum.add("019"); comboHp = new JComboBox(); comboHp.setModel(new DefaultComboBoxModel (hpnum.toArray(new String[hpnum.size()]))); comboHp.setBounds(282, 98, 58, 21); comboHp.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { Object d = e.getItem(); number=d+"-"; } }); memberSavePanel.add(comboHp); tfHp2 = new JTextField(); tfHp2.setBounds(363, 98, 60, 21); memberSavePanel.add(tfHp2); tfHp2.setColumns(10); tfHp3 = new JTextField(); tfHp3.setBounds(445, 98, 57, 21); memberSavePanel.add(tfHp3); tfHp3.setColumns(10); JLabel label = new JLabel("-"); label.setForeground(Color.GREEN); label.setFont(new Font("굴림", Font.BOLD, 12)); label.setBounds(347, 101, 13, 15); memberSavePanel.add(label); JLabel label_1 = new JLabel("-"); label_1.setForeground(Color.GREEN); label_1.setFont(new Font("굴림", Font.BOLD, 12)); label_1.setBounds(431, 101, 13, 15); memberSavePanel.add(label_1); JLabel label_2 = new JLabel("-"); label_2.setFont(new Font("굴림", Font.BOLD, 12)); label_2.setBounds(385, 131, 13, 15); memberSavePanel.add(label_2); tfAdrsnum2 = new JTextField(); tfAdrsnum2.setBounds(399, 128, 103, 21); memberSavePanel.add(tfAdrsnum2); tfAdrsnum2.setColumns(10); btnNewButton = new JButton("중복체크"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MemberDAO dao =new MemberDAO(); boolean b =dao.useridck(tfId.getText()); if(b==true){ JOptionPane.showMessageDialog(MemberSave.this, "이미 사용중인 아이디입니다."); checkId=false; } else { JOptionPane.showMessageDialog(MemberSave.this, "사용 가능한 아이디입니다."); checkId=true; } } }); btnNewButton.setHorizontalAlignment(SwingConstants.LEFT); btnNewButton.setBounds(122, 98, 87, 22); memberSavePanel.add(btnNewButton); btnSave = new JButton("저장"); btnSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String name=tfName.getText(); String userid=tfId.getText(); String password=<PASSWORD>(); String passwordck=<PASSWORD>.getText(); String birthday=yearck+monck+dayck; String sx=sex; String email=tfEmail.getText()+emailst; String hp=number+tfHp2.getText()+"-"+tfHp3.getText();; String adrsnum=tfAdrsnum.getText()+"-"+tfAdrsnum2.getText(); String adrs=tfAdrs.getText(); String dadrs=tfDadrs.getText(); MemberDTO dto=new MemberDTO (name, userid, password, passwordck, birthday, sx, email, hp, adrsnum, adrs, dadrs); MemberDAO dao=new MemberDAO(); int result=dao.insertMember(dto); System.out.println(result); if(checkId!=true) { JOptionPane.showMessageDialog(MemberSave.this, "아이디 중복체크를 확인해주세요."); } else if (password.length() < 8) { JOptionPane.showMessageDialog(MemberSave.this, "비밀번호 문자+숫자로 8자 이상 입력해주세요."); } else if (!password.equals(String.valueOf(tfPwdck.getText())) ) { JOptionPane.showMessageDialog(MemberSave.this, "비밀번호를 확인해주세요."); } else if(tfId.getText().equals("")) { JOptionPane.showMessageDialog(MemberSave.this, "아이디를 입력하세요."); } else if(sx==null) { JOptionPane.showMessageDialog(MemberSave.this, "성별을 입력하세요."); } else { if(result==1) { JOptionPane.showMessageDialog(MemberSave.this, "회원이 추가되었습니다."); frm.refreshTable(); dispose(); } } } }); btnSave.setFont(new Font("굴림", Font.BOLD, 20)); btnSave.setBounds(547, 45, 121, 82); memberSavePanel.add(btnSave); } }
058bba54d62a710bf522572008cc7a8959ebab76
[ "Java" ]
8
Java
jangseongyeol/JSProject
bba42d77c57e4a05648e5f6626958e42e55f1226
08f14ba5989d682b1b64fcab8935272709003d1b
refs/heads/master
<file_sep>package com.codenotfound.db; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.codenotfound.entity.Student; import com.codenotfound.repository.Repository; @Component public class Database { @Autowired private Repository repository; public List<Student> getStudents(){ return repository.findAll(); } }
ec4d25aadfaadfa4248b1ca00ad4ed43328fdefc
[ "Java" ]
1
Java
Tsvetoslav88/cxf-jaxws-spring-boot
3250452470fd1368c18627614673e52e000bd924
4f4adb9c40115f8a306804fa2c935d46ff6a8cb8
refs/heads/master
<file_sep># ruby-onedamentals Ruby Fundamentals Part One assignment for Bitmaker. <file_sep>#FIZZBUZZ EXERCISE - BITMAKER EDITION. (1..100).each do |n| if (n % 3 == 0) && (n % 5 == 0) #boolean to determine if BOTH conditions are met. puts "BitMaker" elsif n % 3 == 0 #otherwise, if first condition is met. puts "Bit" elsif n % 5 == 0 #OTHER otherwise, if second condition is met. puts "Maker" else puts n #other OTHER otherwise. Just put the number. end #But why does it need TWO ends? One for the main operation, and one for the checks? end <file_sep>puts 2 puts 3 puts 2 + 3 puts 5 / 2 puts 20 * 5 puts "Ada Lovelace lived for #{1852 - 1815} years." puts "Hello\t\tworld" puts "Hello\b\b\b\b\bGoodbye world" puts "Hello\rStart over world" puts "1. Hello\n2. World" puts (1 < 3) && (3 < 5) puts (1 > 1) && (2 > 2) puts (1 == 2) || (2 < 3) puts (1 != 2) || (2 < 3) puts (1 == 2) || (2 ==3) <file_sep># calculate a good tip for a $55 meal? WELL OKAY. puts 55 * 0.2 puts "I want this many dogs." + "7" #Turn integers into strings using quotation marks! puts "I'm going to multiply #{45628 * 7839}!" #DON'T FORGET TO PUTS, YOU PUTZ! puts (10 < 20 && 30 < 20) || !(10==11) name = "<NAME>" greeting = "Hello #{name}! Your name is stupid." mission = "Your mission, should you choose to accept it... Get a new name." puts greeting + mission amount = 20 new_amount = amount new_amount #Should be 20. amount = "twenty" amount #now it should be "twenty"! new_amount #...It WON'T be "twenty", it'll be 20! Because we didn't change the assignment of 'new_amount'! first_amount, second_amount, third_amount = 10, 20, 30 puts first_amount puts second_amount puts third_amount #Congrats! You remembered to puts! puts "counter" = counter + "1" #can also be expressed as... puts "counter" += 1 #Reference: Booleans! && = and, || = or, ! = not. There's your booleans! begin "amount" = 1 "amount" += 10 #This makes 11! Similarly, for subtraction... "amount" = 30 "amount" -= 5 #This makes 25! Good job! =end #... This is the end of exercise 2. END IT! END <file_sep>puts "How many pizzas ya want, jabroni?" pizzas = gets.chomp.to_i #user input is assigned variable 'pizzas', turned into an integer value with 'to_i' if pizzas <= 0 puts "Then whaddya wasting my time for? Get outta here!" #can't put any toppings on 0 pizzas or less! elsif pizzas == 1 puts "A single pizza, huh? How many toppings you want on that bad boy?" #special line for a single pizza. toppings = gets.chomp.to_i if toppings <= 0 puts "You've ordered a boring old cheese pizza with no toppings." #1 pizza, no toppings, special clause. elsif toppings > 0 puts "You've ordered a single pizza with #{toppings} toppings." #1 pizza with at least one topping. end else pizzas > 1 pizzacounter = 1 #starts counting pizzas! pizzas.times do #make the loop! puts "How many toppings would you like on pizza number #{pizzacounter.to_s}?" toppings = gets.chomp.to_i puts "You've ordered a pizza with #{toppings} toppings." pizzacounter += 1 #ups the count for the loop! if pizzas == pizzacounter - 1 #find out when the order is done puts "Got it! Thanks for your order! ...Jabroni." end end end <file_sep>#starting values distance = 0 home = 0 energy = 3 #starting energy value while home == 0 #creates the loop, ends loop if you return home. puts "You are on a quest... For FITNESS. Will you walk or run?" speed = gets.chomp if speed == "walk" distance += 1 energy += 1 puts "You've travelled #{distance} kms. You have #{energy} energy left. Type 'home' to go home." elsif speed == "run" && energy > 0 distance += 5 energy -= 1 puts "You've travelled #{distance} kms. You have #{energy} energy left. Type 'home' to go home." elsif speed == "run" && energy == 0 #energy condition for running! puts "You are too tired to run! Try walking to regain energy. Or just go home." elsif speed == "home" home += 1 if home == 1 #end loop condition puts "You've returned home! Go get some sleep." end else puts "I can't do that Dave." #for answers that are not 'run' or 'walk' end end <file_sep>puts "What is your name?" name = gets.chomp puts "Okay, #{name}. What... Is your quest?" quest = gets.chomp puts "Excellent quest, #{quest}, #{name}! Now tell me... What... IS YOUR FAVOURITE COLOUR?" colour = gets.chomp puts "...#{colour} is a stupid colour, #{name}." #Reminder! Variables are assigned like this: variable_name = your variable.
c7f0e77e4d06061e80b337dc0f71f3f33b68a127
[ "Markdown", "Ruby" ]
7
Markdown
ixeres/ruby-onedamentals
a827d9a404c5961c227071d7cf9544f5c58eb832
370519d080866f841d67dca4c357f7d740a613f8
refs/heads/master
<file_sep>const express = require("express") const path = require("path") const app = express() const publicFolderPath = path.join(__dirname, "public") app.use(express.json()) app.use(express.static(publicFolderPath)) const users = [] function checkIfUserAlreadyExists(req) { for (i = 0; i < users.length; i++) { if(users[i].Name.includes(req.body.Name)) { return true } else { return false } } } sameUserNameError = { Error: "Username is already taken!" } function randomId() { let randomNumb = Math.floor(Math.random()*1000) return randomNumb } app.post("/api/user", function(req,res) { if (checkIfUserAlreadyExists(req) === true) { console.log("Username Already Exists") res.status(409) res.send(sameUserNameError) } else { req.body.id = randomId() users.push(req.body) console.log(users) res.status(201) res.send(req.body) } }) app.listen(3000); <file_sep>const userCreateForm = document.getElementById("user-create-form") const userCreateSubmitButton = userCreateForm.querySelector("button[type='submit']") userCreateForm.addEventListener("submit",submitUserCreate) function submitUserCreate(event) { event.preventDefault() User = { Name: userCreateForm.userName.value, Email: userCreateForm.emailAddress.value, Phone: userCreateForm.phone.value, SocialMedia: userCreateForm.url.value, CommunicationMethod: userCreateForm.comMethod.value, UsedDevices: userCreateForm.device.value, UserType: userCreateForm.userType.value, MemeSpicinessLevel: userCreateForm.spiciness.value } fetch("/api/user", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(User), }).then(res => res.json()) .catch(error => console.error("Error:", error)) .then(response => console.log("Success:", response)); }
6472ff1e7caab50432c3403830bcbf2da4e3f695
[ "JavaScript" ]
2
JavaScript
Bschues/MoreElaborateForm
2ad96ed19f3579c14b4c3465331b433a433dc601
0fb30b917db984e8843ed6ed5ea1625cdd331668
refs/heads/master
<file_sep> /* * Required JS libs * prototype.js * htmlUtil.js * jquery.js * jqgrid.js // for jgrid custom AJAX used for update * sessionControl.js= session expiry link */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var ajaxUtil={}; /* * Frame work class for performing AJAX. * The class methods are built over jquery, hence would require jquery.js to work. */ //added to send this param for all ajax calls ajaxUtil.AJAX_CALL_PARAM='ajaxCallFlag=true&'; // this also used in jqgrid calls under formatPostData method /** * Added to avoid AJAX Race conditions. * This stack holds all the ajax ID that are in process, so as to prevent same AJAX Id being fired when its response has * not come from the server and hence prevent AJAX Race conditions. */ ajaxUtil.ajaxCallSatck=new Array(); /* * method used to encode data fiels that are sent as input data in AJAX call. * @paramName- name of param attribute - part of from or the name used to get using request.getParameter("name") * @paravValue- value of parameter. * @returns String representation of &paramName=encodeURIComponenet(paramvalue); * */ ajaxUtil.encodeDataFields =function (paramName,paramValue) { try { paramvalue=($.trim(paramValue).length!=0) ? encodeURIComponent(paramValue) : "";//validation check paramName+="="+paramvalue; paramName="&"+paramName; return paramName; }catch(err) { alert("Error in ajaxUtil encodeDataFields method err msg : "+err.message); } }; /** * Note: htmlUtil. should be imported before this method call for this method to work. * Not used- Replaced with jgrid */ /*ajaxUtil.refreshTableData =function () { var ajaxID=null; //Added to avoid AJAX race conditions for same action being clicked twice or dependant actions being fired. var URL=null; var input=null; var responseHandler=null; var tableOBj=null; var responseDiv=null; var width=null; var height=null; var headerFlag=false; if(arguments.length==4) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; tableOBj=arguments[3]; } if(arguments.length==5) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; tableOBj=arguments[3]; input=arguments[4]; } if(arguments.length==6) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; tableOBj=arguments[3]; input=arguments[4]; responseDiv=arguments[5]; } if(arguments.length==8) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; tableOBj=arguments[3]; input=arguments[4]; responseDiv=arguments[5]; width=arguments[6]; height=arguments[7]; } if(arguments.length==9) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; tableOBj=arguments[3]; input=arguments[4]; responseDiv=arguments[5]; width=arguments[6]; height=arguments[7]; headerFlag=arguments[8]; } //Store table structure try { var tableStruct=htmlUtil.copyTableStructure(tableOBj,headerFlag); } catch(err) { alert("Error in refreshTableData in htmlUtil.copyTableStructure method call "+err.message); } if(!URL && !responseHandler && !ajaxID && !tableStruct)//mandatory arguments { alert("Mandatory parameters to refreshTableData AJAX call are null"); } else { this.getJSON(ajaxID,URL,responseHandler,tableStruct,input,responseDiv,width,height); } };*/ /* * Mehtod used to get JSON object from server during AJAX call. * Method can be called with different set of arguments * 3 arguments * - ajaxId- unique ID given to each AJAX call made - added to prevent AJAX Race condition. * - URL - address to server action * - responseHandler - return local function that would handle the response. */ ajaxUtil.getJSON =function () { var ajaxID=null; //Added to avoid AJAX race conditions for same action being clicked twice or dependant actions being fired. var URL=null; var input=null; var responseHandler=null; var responseDiv=null; var width=null; var height=null; if(arguments.length==3) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; } if(arguments.length==4) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; input=arguments[3]; } if(arguments.length==5) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; input=arguments[3]; responseDiv=arguments[4]; } if(arguments.length==7) { ajaxID=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; input=arguments[3]; responseDiv=arguments[4]; width=arguments[5]; height=arguments[6]; } if(!URL && !responseHandler && !ajaxID)//mandatory arguments { alert("Mandatory parameters to AJAX call are null"); } input=(input)?this.AJAX_CALL_PARAM+input:this.AJAX_CALL_PARAM; try { if(this.ajaxCallSatck.contains(ajaxID)) htmlUtil.prompt.warn({msg:"Your request is Processing.. Please wait"}); else { this.ajaxCallSatck.push(ajaxID); var stack = this.ajaxCallSatck; $.ajax({ url:URL, type:"post", dataType:"json", beforeSend:this.loading(responseDiv,height,width), cache:false, error:function(requestObj, errorMsg){ if(sessionControl) sessionControl.resetSessionCount(); if(!ajaxUtil.ajaxCallSatck.remove(ajaxID)) alert("Error Ajax call not removed from stack"); alert("Error in AJAX Serveice err msg: "+errorMsg); }, data: input, success: function(data, textStatus, jqXHR){ try { if(sessionControl) sessionControl.resetSessionCount(); if(!ajaxUtil.ajaxCallSatck.remove(ajaxID)) alert("Error Ajax call not removed from stack"); if(data.status=="Success") { responseHandler(data); } else if(data.status=="Failure") { alert("Error in response from Server error comments= "+data.comment); }else { alert("Error in response from Server status= "+data.status+" error comments= "+data.comment); } }catch(err) { ajaxUtil.ajaxCallSatck.remove(ajaxID); alert("Error in ajaxUtil jsonResponseValidator method err msg: "+err.message); } } }); } }catch (err) { alert("Error in ajaxUtil getJSON method err msg: "+err.message); } }; ajaxUtil.loading=function(responseDiv,height,width){ if(responseDiv !=null && $('#'+responseDiv)!=null ) { if(width!=null && height!= null) { $('#'+responseDiv).html('<div style="position:absolute;left:'+Math.round((width-25)/2)+'px;top:'+Math.round((height-25)/2)+'px;"><img src="/csa/images/loading.gif" width="25px" height="25px" alt="LOADING.." title="LOADING.."></img></div>'); } else $('#'+responseDiv).html('<span><center>LOADING...</center></span>'); } }; ajaxUtil.constructData=function(elm){ var data=""; try { if(elm!=null) { if(!elm.length)//elm.length==undefined when we get single elements using document.getElementById elm = [elm]; for(var i=0;i<elm.length;i++) { data+=this.encodeDataFields($(elm[i]).attr("name"),$(elm[i]).val()); } return data; } }catch(err) { alert("Error in ajaxUtil constructData method err msg: "+err.message); } }; ////Functions specific to jgrid /* * Mehtod used to get JSON object from server during AJAX call. * Method can be called with different set of arguments * 3 arguments * - tableId- unique ID given to each AJAX call made - added to prevent AJAX Race condition. * - URL - address to server action * - responseHandler - return local function that would handle the response. */ ajaxUtil.jgridCustomAjax =function () { var tableId=null; //Added to avoid AJAX race conditions for same action being clicked twice or dependant actions being fired. var URL=null; var input=null; var responseHandler=null; if(arguments.length==3) { tableId=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; } if(arguments.length==4) { tableId=arguments[0]; URL=arguments[1]; responseHandler=arguments[2]; input=arguments[3]; } if(!URL && !responseHandler && !tableId)//mandatory arguments { alert("Mandatory parameters to AJAX call are null"); } input=(input)?this.AJAX_CALL_PARAM+input:this.AJAX_CALL_PARAM; try { if(this.ajaxCallSatck.contains(tableId)) htmlUtil.prompt.warn({msg:"Your request is Processing.. Please wait"}); else { this.ajaxCallSatck.push(tableId); var stack = this.ajaxCallSatck; $.ajax({ url:URL, type:"post", dataType:"json", beforeSend:this.showTimerBlock(true,tableId), cache:false, error:function(requestObj, errorMsg){ if(sessionControl) sessionControl.resetSessionCount();// Method from home.js- note home.js should be before ajaxUtil.js for this to work if(!ajaxUtil.ajaxCallSatck.remove(tableId)) alert("Error Ajax call not removed from stack"); alert("Error in AJAX Serveice err msg: "+errorMsg); ajaxUtil.showTimerBlock(false,tableId); }, data: input, success: function(data, textStatus, jqXHR){ try { ajaxUtil.showTimerBlock(false,tableId); if(sessionControl) sessionControl.resetSessionCount();// Method from home.js- note home.js should be before ajaxUtil.js for this to work if(sessionControl===undefined) alert("here") if(!ajaxUtil.ajaxCallSatck.remove(tableId)) alert("Error Ajax call not removed from stack"); if(data.status=="Success") { responseHandler(data,tableId); } else if(data.status=="Failure") { htmlUtil.prompt.error({msg:data.comment}); }else { alert("Error in response from Server status= "+data.status+" error comments= "+data.comment); } }catch(err) { ajaxUtil.ajaxCallSatck.remove(tableId); alert("Error in ajaxUtil jsonResponseValidator method err msg: "+err.message); } } }); } }catch (err) { alert("Error in ajaxUtil jgridCustomAjax method err msg: "+err.message); } }; ajaxUtil.showTimerBlock=function (flag,tableId) { if(flag) { $("#lui_"+$.jgrid.jqID(tableId)).show(); $("#load_"+$.jgrid.jqID(tableId)).show(); } else { $("#lui_"+$.jgrid.jqID(tableId)).hide(); $("#load_"+$.jgrid.jqID(tableId)).hide(); } };<file_sep> /* * Required JS libs * prototype.js * htmlUtil.js * jquery.js * jqGrid.js * jgrid.override.funcs.js * exceptionHanlder.jsp- exception management * sessionControl.js-session expiry */ //***************************************************************************************************************************************** ///SPECIFIC proptotype functions defined for inline add,update,delete handling in jgrid////////////////////////////////////////////// /** * Note: the method below works like remove of ArrayList in java. * @param tableId (tableJSON) * @return tableJSON */ Array.prototype.removeTable= function (tableId) { try{ if(!this)//condition is true for this= null or undefined return null; else { for(var i=0 in this) { if (this[i]) { if(this[i].id) { if(this[i].id==tableId) { var tableJson =this[i]; this.splice(i,1); return tableJson; } } else continue; } } return null; } }catch(err) { alert("Error in htmlUtil Array.removeTable. method err Msg-"+err.message); return null; } }; /** * Note: the method below works like get of ArrayList in java. * @param tableId (tableJSON) * @return tableJSON */ Array.prototype.getTable= function (tableId) { try{ if(!this)//condition is true for this= null or undefined return null; else { for(var i=0 in this) { if (this[i]) { if(this[i].id) { if(this[i].id==tableId) { var tableJson = this[i]; return tableJson; } } else continue; } } return null; } }catch(err) { alert("Error in htmlUtil Array.getTable. method err Msg-"+err.message); return null; } }; // add exists method to jquery $.fn.exists = function(){return this.length>0;} ; //************************************************************************************************************************************* //FUNCTIONS TO BE OVERRIDEEN IN LOCAL JS FILES///////////////////////////////////////////////////////////// /** * * Used in inline validation of jqgrid cells. If colModel of grid defines editRules:{custom:true} then this function is called. * @param data - data of the cell * @param rowId- id of row element * @param colName - name of column given as index in colModel * @param tableId- id of the respective grid * @return errorMessage - null or empty String implies validation output =true * - String msg - implies validation is false and msg is displayed as a prompt over the textbox/textarea. * */ function customValidator(data,rowId,colName,tableId){return null;}; /** * * Used in Save Call during inline editing of jqgrid cells. * This function is called after the save ajax Call is processed and if its sucessful. The call to this method occurs * before the grid is reloaded. * @param dataObj - jsonData from server * @param tableId - tableId of the concerned grid * @return <boolean> result - true - calls reload table Grid. * - false - does not reload grid * */ function afterSaveReloadGrid(dataObj,tableId){return true;}; /** * * Used to load ObjectData as per IJSONObject after grid load- triggered on loadComplete * * @param objectJson - json representation of ObjectData sent from server * @param tableId - tableId of the concerned grid * @return void * */ function postGridCallProcess(objectJson,tableId){}; /** * * Used to manipulate postData being sent in Ajax call of jgrid during update/add/del operations. * Primarily used to append data to existing grid data depending on business logic. * @param tableId - tableId of the concerned grid * @param data - String data with &key=val format. * @return <String> data- data to be use by ajax call. * */ function manipulateDataBeforeJgridUpdateCall(tableId,data){return data;}; /** * * Trigger function activated when a table row is selected. * * @param rowId - rowId of the row selected. * @param tableId - tableId of the concerned grid * @return void * */ function onJgridRowSelect(rowId,tableId){}; /** * * Override function activated to override editableforAdd formater function for the true case of new Row being added * Call to this function will override default behaviour in editableForAdd as long output !=null * @param cellValue - value of cell to be formated. * @param opts - json obj which contains tableId as gid , rowId as rowId, colModel etc.. * @param rowdata - rowData of the row as jsonObject * @return String- formated output - If output ==null then override does not take place * */ function overrideEditableForAddTrueCase(cellvalue,opts,rowdata){return null;} /** * * Override function activated to override editableforAdd formater function for the false case of new Row being added * Call to this function will override default behaviour in editableForAdd as long output !=null * * @param cellValue - value of cell to be formated. * @param opts - json obj which contains tableId as gid , rowId as rowId, colModel etc.. * @param rowdata - rowData of the row as jsonObject * @return String- formated output - If output ==null then override does not take place * */ function overrideEditableForAddFalseCase(cellvalue,opts,rowdata){return null;} /** * * Function to be implemented for custom formatter when colModel for a column specifies formatter:jgridUtilCustom * * @param cellValue - value of cell to be formated. * @param opts - json obj which contains tableId as gid , rowId as rowId, colModel etc.. * @param rowdata - rowData of the row as jsonObject * @param isNewRow - true incase on inline editing for a new row being added using + (Add) button * @return String- formated output - If output ==null then error is thrown by jgridUtil.js * */ function griCustomFormater(cellvalue, opts, rowdata,isNewRow){return null;} /** * * Function will be called before framework creates edit boxes for inline editing. * * @param rowId - Id of row being edited * @param tabelId - grid Id of the table * @return booelan true - would continue to mark the row for deleting. false would not mark the row for editing * */ function beforeJgridEdit(rowId,tableId){return true;}; /** * * Function will be called after framework creates edit boxes for inline editing. * * @param rowId - Id of row being edited * @param tabelId - grid Id of the table * @return void * */ function afterJgridEdit(rowId,tableId){}; /** * * Function will be called before framework marks row for deletion during inline editing. * * @param rowId - Id of row being edited * @param tabelId - grid Id of the table * @return booelan - true - would continue to mark the row for deleting. false would not mark the row for deletion * */ function beforeJgridDelete(rowId,tableId){return true;}; /** * * Function will be called after framework marks row for deletion during inline editing. * * @param rowId - Id of row being edited * @param tabelId - grid Id of the table * @return void * */ function afterJgridDelete(rowId,tableId){}; /** * * Function will be called once json data is returned from the server before jgrid construction * * @param data - jsonDataReturnedFromServer * @param tabelId - grid Id of the table * @return void * */ function callOnJgridSucessLoad(data,tableId){}; /** *(TEMP FIX - NEED TO FIND A BETTER SOLUTION FOR DATE PICKER * Function will be called when add or editRow button is clicked. -used to introduce date picker * * @param rowId - rowId being edited * @param tabelId - grid Id of the table * @return void * */ function customizeonGridEdit(rowId,tableId){}; /** * DEPRECEATED *(TEMP FIX - NEED TO FIND A BETTER SOLUTION FOR DATE PICKER * Function will be called before any get call from jgrid * * @param tabelId - grid Id of the table * @return boolean- to start or stop the select service call * */ /*function beforeGridSelectCall(tableId){return true;}*/ /** * called before when search button is clicked. * @param tableID * @return void */ function onJgridSearchOverrideFunction(tableID) { }; /** * Called before construction of jqgrid in order to override colModel generated by JSTL for special cases * @param tableId * @param colModel * @return */ function overrideColModel(tableId,colModel) { return null; } /** * This function is called for handling the click action for a pick list when pickAndAddAction formatter is used. * @param rowId * @param tableId * @return */ function customPickAndAdd(rowId, tableId) { htmlUtil.prompt.warn({msg:"customPickAndAdd row function not defined in local js file."}); } function jgridCustomLinkClickHandler(rowId, tableId,colName,cellValue) { htmlUtil.prompt.warn({msg:"LinkHandler for this table is not defined"}); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var jgridUtil={}; //CONSTANTS jgridUtil.TABLE_STACK= new Array(); //Holds table add/update/delete list jgridUtil.GRID_MAX_ADD_ROW_ID=1; //used to proivde unique rowId for adding new data as new add row //jgridUtil.CHANGES_CHECK_FLAG=true; // Not currently in use jgridUtil.INVALID_GRID_STCK= new Array(); // Used to throw error flag when save is clicked to display prompts of invalid entries jgridUtil.GRID_DATA_STCK=new Array(); // Buffer Object array that hold Json data for jgrid after tableLoad in jgrid call. jgridUtil.HIGHLIGHT_COLOR="jgrid_highlight_selected_row";//{"background":"#0dc543"}; // MTEHODS USED FOR STACK UTILS/////////////////////////// /** * Returns true if TABLE_STACK has the given tableID (i.e. when table is being edited) */ jgridUtil.containsTableJSON= function(tableId) { var tableJSON=this.TABLE_STACK.getTable(tableId); if(tableJSON) return true; else return false; }; /** * adds the row being added edited or deleted to TABLE_STACK */ jgridUtil.addRowToTableStackJSON= function(tableId,rowID,type) { var tableJson=this.TABLE_STACK.removeTable(tableId); if(tableJson) { if(type=="EDIT") { var stk = tableJson.EDIT_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.EDIT_STACK=stk; } else if(type=="DEL") { var stk = tableJson.DEL_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.DEL_STACK=stk; }else if(type=="ADD") { var stk = tableJson.ADD_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.ADD_STACK=stk; } else { var err={message:"Error in addToTableStackJSON msg:- incorrect Type"}; throw (err); } } else { var tableJson={ "id":tableId, "EDIT_STACK":null, "DEL_STACK":null, "ADD_STACK":null }; if(type=="EDIT") { var stk = tableJson.EDIT_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.EDIT_STACK=stk; } else if(type=="DEL") { var stk = tableJson.DEL_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.DEL_STACK=stk; }else if(type=="ADD") { var stk = tableJson.ADD_STACK; if(!stk) stk=new Array(); stk.push(rowID); tableJson.ADD_STACK=stk; } else { var err={message:"Error in addToTableStackJSON msg:- incorrect Type"}; throw (err); } this.showHideGridReloadOptions("hide",tableId); } this.TABLE_STACK.push(tableJson); }; /** * removes rows from table Stack when cancel is clicked */ jgridUtil.removeRowFromTableStackJSON= function(tableId,rowID,type) { var output=false; var tableJson=this.TABLE_STACK.removeTable(tableId); if(tableJson) { if(type=="EDIT") { var stk = tableJson.EDIT_STACK; if(stk) { output= stk.remove(rowID); if(stk.length==0) stk=null; tableJson.EDIT_STACK=stk; } } else if(type=="DEL") { var stk = tableJson.DEL_STACK; if(stk) { output= stk.remove(rowID); if(stk.length==0) stk=null; tableJson.DEL_STACK=stk; } }else if(type=="ADD") { var stk = tableJson.ADD_STACK; if(stk) { output= stk.remove(rowID); if(stk.length==0) stk=null; tableJson.ADD_STACK=stk; } } else { var err={message:"Error in removeTableStackJSON msg:- incorrect Type"}; throw (err); } if(!(tableJson.ADD_STACK==null && tableJson.EDIT_STACK==null && tableJson.DEL_STACK==null)) this.TABLE_STACK.push(tableJson); else this.showHideGridReloadOptions("show",tableId); } return output; }; /** * creates a new stack of rowIds for add/modify/delete and returns the same. */ jgridUtil.getNewStck= function (input) { var output=null; if(input) { output=new Array(); for(var i=0;i<input.length;i++) { output.push(input[i]); } } return output; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //**************************************************INLINE EDITING FUNCTIONS**************************************************** /** * Gets cursor to the first Column to be edited //temp fix has to e changed */ jgridUtil.focusFirstEditColForAdd=function(tableId,rowId) { var inputCols =$('#'+tableId+" #"+rowId+" td input"); if(inputCols) $(inputCols[0]).focus(); }; /** * Called when Add button is clicked on jgrid */ jgridUtil.customizedadd=function (tableId,data,pos) { if(!pos) post="last"; var rowId= jgridUtil.getUniqueId(tableId); // this.populateStack("ADD",tableId,rowId); this.addRowToTableStackJSON(tableId, rowId, "ADD"); if(data) $("#"+tableId).addRowData( rowId,data,pos );//add and format add row based on formater else $("#"+tableId).addRowData( rowId,{},pos );//add and format add row based on formater jgridUtil.highlightRow(rowId,true); $('#'+tableId).jqGrid('editRow',rowId,false,function(){jgridUtil.onGridEdit(rowId,tableId);}); //focus on addrow this.focusFirstEditColForAdd(tableId, rowId); }; /** * Called when inline edit button is clicked on jgrid */ jgridUtil.customizedEdit = function(rowId,tableId) { if(beforeJgridEdit(rowId,tableId)) { this.addRowToTableStackJSON(tableId, rowId, "EDIT"); jgridUtil.highlightRow(rowId,true); $('#'+tableId).jqGrid('editRow',rowId,false,function(){jgridUtil.onGridEdit(rowId,tableId);}); $("tr#"+rowId+" div.ui-inline-edit, "+"tr#"+rowId+" div.ui-inline-del",'#'+tableId).hide(); $("tr#"+rowId+" div.ui-inline-cancel",'#'+tableId).show(); } afterJgridEdit(rowId,tableId); }; /** * Called when add or edit button is clicked. during inline edit. * Used to trigger override function customizeOnGridEdit */ jgridUtil.onGridEdit= function(rowId,tableId) { customizeonGridEdit(rowId,tableId); }; /** * Called when delete button is clicked */ jgridUtil.customizedDel=function(rowId,tableId) { if(beforeJgridDelete(rowId,tableId)) { this.addRowToTableStackJSON(tableId, rowId, "DEL"); jgridUtil.highlightRow(rowId,true); $("tr#"+rowId+" div.ui-inline-edit, "+"tr#"+rowId+" div.ui-inline-del",'#'+tableId).hide(); $("tr#"+rowId+" div.ui-inline-cancel",'#'+tableId).show(); } afterJgridDelete(rowId,tableId); }; /** * Called when inline cancel button is clicked. */ jgridUtil.customizedRestore=function(rowId,tableId,button) { if(this.removeRowFromTableStackJSON(tableId,rowId,"EDIT")) { $('#'+tableId).jqGrid('restoreRow',rowId); $("tr#"+rowId+" div.ui-inline-edit, "+"tr#"+rowId+" div.ui-inline-del",'#'+tableId).show(); $("tr#"+rowId+" div.ui-inline-cancel",'#'+tableId).hide(); } else if(this.removeRowFromTableStackJSON(tableId,rowId,"DEL")) { $("tr#"+rowId+" div.ui-inline-edit, "+"tr#"+rowId+" div.ui-inline-del",'#'+tableId).show(); $("tr#"+rowId+" div.ui-inline-cancel",'#'+tableId).hide(); } else if(this.removeRowFromTableStackJSON(tableId,rowId,"ADD")) { $("#"+tableId).delRowData(rowId); } else { alert("Error in jgridUtil.customizedRestore as given rowId/tableId is not there in any stack to restore"); } jgridUtil.highlightRow(rowId,false); htmlUtil.prompt.closeHtmlAlertInGridForRow(rowId);//closes all prompts (error,warn,notification) for the elements of that row }; /** * Triggered when Cancel (restore All) button at the bottom of the grid is clicked. */ jgridUtil.customizedRestoreAll=function(tableId) { var tableJSon =this.TABLE_STACK.getTable(tableId); if(tableJSon) { var types =["EDIT","ADD","DEL"]; for(var i=0;i<types.length;i++) { var stck=null; if(types[i]=="EDIT") stck=this.getNewStck(tableJSon.EDIT_STACK); else if(types[i]=="ADD") stck=this.getNewStck(tableJSon.ADD_STACK); else //DEL case stck=this.getNewStck(tableJSon.DEL_STACK); if(stck) { for(var k=0;k<stck.length;k++) this.customizedRestore(stck[k],tableId,types[i]); } } } }; /** * Called when save button is clicked. */ jgridUtil.customizedSave=function(url,tableId) { //check stack for tableId var tableJson = this.TABLE_STACK.getTable(tableId); this.INVALID_GRID_STCK.remove(tableId);//RESET FOR NEW VALIDATION if(tableJson) { var gridData=this.constructData(tableJson); if(!this.INVALID_GRID_STCK.contains(tableId)) { if(gridData) { var data="hidAction=updateJgrid_"+tableId;//ACTION PARAM"hidAction":"systemCodeMstrJgridCall" data+=ajaxUtil.encodeDataFields("gridData",gridData); data=manipulateDataBeforeJgridUpdateCall(tableId,data); if(data) { ajaxUtil.jgridCustomAjax(tableId,url,this.saveHandler,data); } else { alert("Error in manipulateDataBeforeJgridUpdateCall gridData being sent in ajax call.") } } } } }; /** * jgrid Custom ajax handler during save operation for inline edit. */ jgridUtil.saveHandler = function(dataObj,tableId) { jgridUtil.TABLE_STACK.removeTable(tableId); jgridUtil.showHideGridReloadOptions("show",tableId); if(dataObj.status=="Success") { if(afterSaveReloadGrid(dataObj,tableId)==true) { $("#"+tableId).trigger("reloadGrid"); } }else { htmlUtil.prompt.error({msg:dataObj.comment}); } }; /** * Inline edit validation functions */ jgridUtil.validRow=function(elmn,editRules,data,tableId) { var flag=true; data=data+""; if(editRules) { if(editRules.required) { flag=htmlUtil.validator.isMandatory(data,elmn); if(!flag) return false; } if(editRules.numeric) { flag=htmlUtil.validator.isNumeric(data,elmn); if(!flag) return false; } if(editRules.alphanumeric) { flag=htmlUtil.validator.isAlphaNumeric(data,elmn); if(!flag) return false; } if(editRules.alphabets) { flag=htmlUtil.validator.isAlphabets(data,elmn); if(!flag) return false; } if(editRules.custom)// to customize validation rules { var rowId=$(elmn).attr("id").split("_")[0]; var colName=$(elmn).attr("id").split("_")[1]; var message=customValidator(data,rowId,colName,tableId); //id = rowId_colName if(message) { if((message+"").trim().length!=0) { htmlUtil.prompt.error({elm:elmn,msg:message}); return false; } } } } return flag; }; /** * Used by save to construct JSONdata for save ajax call and also validate the data in the process */ jgridUtil.constructData=function(tableJson) { var tableId=tableJson.id; var output='{'; var add=this.constructFromStack(tableJson.ADD_STACK,tableId,"ADD"); var edit=this.constructFromStack(tableJson.EDIT_STACK,tableId,"EDIT"); var del=this.constructFromStack(tableJson.DEL_STACK,tableId,"DEL"); if(add ==null || edit==null ) return null; // Error case output+='INSERT:'; output+=add+','; output+='UPDATE:'; output+=edit+','; output+='DELETE:'; output+=del; output+='}'; return output; }; /** * Sub function- used to extract JSON for each stack (ADD, UPDATE, DELETE) */ jgridUtil.constructFromStack=function(stck,tableId,type) { var output="[";//No data case if(stck) { for(var i=0;i<stck.length;i++) { var rowId=stck[i]; var rowData=$("#"+tableId).getRowData(rowId); if(i==0) output+="{"; else output+=",{"; output+="\"row_id\":\""+rowId+"\""; if(type!="DEL") output+=this.getStringRepresentation(rowData,tableId,rowId,type); output+="}"; } } output+="]"; return output; }; /** * sub function used to validate and return the value of content in each cell */ jgridUtil.getStringRepresentation=function (rowData,tableId,rowId,type) { var output=''; var colModels=$("#"+tableId).getGridParam("colModel"); var i=0; for(var k in rowData) { output+=","; var colModel=colModels[i]; var name=colModel.name; var editable=colModel.editable; var editType=colModel.edittype; var editRules=colModel.editrules; var colVal=rowData[k]; if(colModel.formatter)//=='customHyperLink' applies to all formatters { colVal="#"+rowId+"_"+name; } if(colModel.formatter=='editableForAdd' && type=="ADD") { colVal="#"+rowId+"_"+name; editable=true; editType="text"; } output+="\""+name+"\":"; if(editable) data=this.getCellData(colVal,editType,editRules,tableId); else data=colVal; output+="\""+data+"\""; i++; } return output; }; /** * Sub function that inovkea validation function */ jgridUtil.getCellData =function (colVal,editType,editRules,tableId) { var output=''; output=$(colVal).val(); //colVal is not acutal element hence element is recaught using jquery on id var id=$(colVal).attr("id"); if(id) htmlUtil.prompt.closeHtmlAlert($("#"+id)); if(!this.validRow($("#"+id),editRules,output,tableId) && !this.INVALID_GRID_STCK.contains(tableId)) this.INVALID_GRID_STCK.push(tableId); return output; }; /** * Internal utility method used to highlight delete selected row. */ jgridUtil.highlightRow= function (rowId,flag) { if(flag) { $("#"+rowId).addClass(this.HIGHLIGHT_COLOR); } else { $("#"+rowId).removeClass(this.HIGHLIGHT_COLOR); } }; /** * Added to generate unique ID in case of adding new rows */ jgridUtil.getUniqueId= function (tableId) { if(tableId.indexOf("~")!=-1) { var err={message:"Error in getUniqueId msg:- table Id contains ~"}; throw (err); } var id ="NEW"+tableId+this.GRID_MAX_ADD_ROW_ID; this.GRID_MAX_ADD_ROW_ID++; return id; }; /** * Internal function used to show/hide buttons during table editing * Obejctive is to prevent naviation buttons as sorting or pagination during table edit. */ jgridUtil.showHideGridReloadOptions=function(type,tableId) { if(type=='show') { $("#first_"+tableId+"_pager").show(); $("#prev_"+tableId+"_pager").show(); $("#next_"+tableId+"_pager").show(); $("#last_"+tableId+"_pager").show(); $(".ui-pg-selbox","#"+tableId+"_pager").show(); $(".ui-pg-input","#"+tableId+"_pager").removeAttr("readonly"); $(".ui-icon-refresh","#"+tableId+"_pager").show(); $(".ui-icon-search","#"+tableId+"_pager").show(); // $("#"+tableId+"_searchDiv").show(); } else { $("#first_"+tableId+"_pager").hide(); $("#prev_"+tableId+"_pager").hide(); $("#next_"+tableId+"_pager").hide(); $("#last_"+tableId+"_pager").hide(); $(".ui-pg-selbox","#"+tableId+"_pager").hide(); $(".ui-pg-input","#"+tableId+"_pager").attr("readonly","readonly"); $(".ui-icon-refresh","#"+tableId+"_pager").hide(); $(".ui-icon-search","#"+tableId+"_pager").hide(); $("#"+tableId+"_searchDiv").hide("slow"); } }; //************************************************************************************************************************************ //JGRID EVENT LISTENER FUNCTIONS/////////////////////////////////////////////////////////////////////////////////////////// //Added to peform grouping functionality -- need to add listener to this jgridUtil.performGrouping=function (elm,tableId) { var opt =$(elm).val(); var table=$("#"+tableId) table.setGridParam({"rowNum":table.getGridParam("rowList")[0]});// max limit for group by if(opt) { if(opt.trim().length==0) { table.setGridParam({"grouping":false}); } else { table.setGridParam({"sortname":opt}); table.setGridParam({"sortorder":"asc"}); table.setGridParam({"rowNum":500});// max limit for group by table.setGridParam({"grouping":true}); table.setGridParam({"groupingView":{ "groupField":[opt], "groupOrder":['asc'], "groupText":['<b>{0} - {1} Item(s)</b>']}}); } } else { table.setGridParam({"grouping":false}); } table.trigger("reloadGrid"); }; jgridUtil.onJgridSearch= function (tableID) { var dataObj= $("#"+tableID).getGridParam("postData"); if(!dataObj["_searchButtonFlag"]) { dataObj["_searchButtonFlag"]=true; } $("#"+tableID).setGridParam({"postData": dataObj}) onJgridSearchOverrideFunction(tableID); } jgridUtil.onSelectRow = function (rowId,tableId) { onJgridRowSelect(rowId,tableId); }; /** * Called on LoadComplete */ jgridUtil.processObjectData= function(data,tableId) { var objectJson =data.objectData; if(objectJson!=null && objectJson=="null") objectJson=null; postGridCallProcess(objectJson,tableId); }; /** * Called on Error from Jgrid Ajax call */ jgridUtil.customizeErrorReturnData= function(xhr,st,err,tableId) { if(sessionControl) sessionControl.resetSessionCount();// Method from sessionControl.js- note sessionControl.js should be before ajaxUtil.js for this to work if(!ajaxUtil.ajaxCallSatck.remove(tableId)) alert("Error Ajax call not removed from stack"); htmlUtil.prompt.error({msg:"Error in AJAX Service err msg: "+err}); }; /** * Called on Sucess from Jgrid AJAX call */ jgridUtil.customizeSucessReturnData= function(data, st, xhr,tableId) { if(!exceptionHandler.handle(data))// exception handler added to handle exceptions during ajax { this.updateLatestTableData({"id":tableId,"data":data.tableData}); jgridUtil.removeSearchFlag(tableId);// removes specific request param used to identify when search is called. if(sessionControl) sessionControl.resetSessionCount();// Method from sessionControl.js- note sessionControl.js should be before ajaxUtil.js for this to work if(!ajaxUtil.ajaxCallSatck.remove(tableId)) alert("Error Ajax call not removed from stack"); if(this.checkIfReturnSuccess(data.objectData))//standard check as return json would contain error flag in objectdata array incase of //any server side validations. { callOnJgridSucessLoad(data,tableId); } } }; /** * Called from customizeSucessReturnData function. */ jgridUtil.checkIfReturnSuccess= function(objectData) { if(objectData) { var obj=objectData[0]; if(obj) { if(obj.name=="errorElement") { htmlUtil.prompt.error({msg:obj.message}); } } } } /** * Called before sending request - if true reqeust is sent else not sent */ jgridUtil.customizedSendingReq= function(xhr,tableId) { var output=false; if(ajaxUtil.ajaxCallSatck.contains(tableId)) { htmlUtil.prompt.error({msg:"Your request is Processing.. Please wait"}); } else { ajaxUtil.ajaxCallSatck.push(tableId); // output=beforeGridSelectCall(tableId); output=true; // alert(output); } return output; }; /////////////////////////////////////////////////////////////////////////////////////////// //UTIL METHODS jgridUtil.removeSearchFlag=function(tableID) { var dataObj= $("#"+tableID).getGridParam("postData"); if(dataObj["_searchButtonFlag"]) { dataObj["_searchButtonFlag"]=null; } $("#"+tableID).setGridParam({"postData": dataObj}) }; jgridUtil.updateLatestTableData= function(obj) { for(var i in this.GRID_DATA_STCK) { if(this.GRID_DATA_STCK[i].id==obj.id) this.GRID_DATA_STCK.splice(i,1); } this.GRID_DATA_STCK.push(obj); }; jgridUtil.setCaption= function(caption,bodyDivId) { var elm=$("span.ui-jqgrid-title","#"+bodyDivId); if(elm.exists()) elm.html(caption); else alert("caption div does not exist for table in div -"+bodyDivId); }; jgridUtil.setColNames= function (cols,tableId) { for(var name in cols) { var elm=$("#grid_header_"+tableId+"_"+name,"th"); if(elm.exists()) elm.html(cols[name]); else alert("colName - "+name+" does not exist for table -"+tableId); } }; //************************************************************************************************************************************ ///////////////////////////////////////JGRID TABLE CONSTRUCT UTILS/////////////////////////////////////////////////////////// /** * Method to construct jgridTable */ jgridUtil.constructGrid= function(tableObj) { //INITIALIZE TABLE this.intializeTable(tableObj); //INITIALIZE BUTTONS $(".HeaderButton").hide();//adds caption button to avoid jgrid bug in scrollbars geneartoin after slideUp this.intializeTableButtons(tableObj); } jgridUtil.intializeTable=function (tableObj) { // Added to support group by opt on caption var gByOpts=tableObj.groupByOptions; if(gByOpts) { var opts =" Group By: &nbsp; "; opts +="<select id='"+tableObj.tableId+"_groupingOptions' name='"+tableObj.tableId+"_groupingOptions' class='selClass' onchange='jgridUtil.performGrouping(this,\""+tableObj.tableId+"\")'>"+ "<option value=''>-- Select --</option>"; for(var i=0;i<gByOpts.length;i++) { var opt=gByOpts[i]; opts+="<option value='"+opt.id+"'>"+opt.label+"</option>"; } opts+="</select>"; tableObj.caption+=opts; } var gridObj= { url: tableObj.url, height: (tableObj.bodyDivId)?$("#"+tableObj.bodyDivId).height():150, width:(tableObj.bodyDivId)?$("#"+tableObj.bodyDivId).width():150, page: 1, rowNum: (tableObj.rowNum)?tableObj.rowNum:10, rowTotal : null, records: 0, pager: tableObj.tableId+"_pager", pgbuttons: true, pginput: true, colModel: this.customizeTableAttr(tableObj.colModel,tableObj.tableType,"colModel"), rowList: (tableObj.rowList)?tableObj.rowList:[10,20,30], colNames: this.customizeTableAttr(tableObj.colNames,tableObj.tableType,"colName"), sortorder: (tableObj.sortorder)?tableObj.sortorder:"asc", sortname:(tableObj.sortname)?tableObj.sortname: "", datatype: (tableObj.datatype)?tableObj.datatype: "JSON", mtype: (tableObj.mtype)?tableObj.mtype:"POST", selarrrow: [], savedRow: [], subGrid: false, subGridModel :[], reccount: 0, lastpage: 0, lastsort: 0, selrow: null, loadError:function(xhr,st,err){jgridUtil.customizeErrorReturnData(xhr,st,err,tableObj.tableId);}, beforeProcessing:function(data, st, xhr){jgridUtil.customizeSucessReturnData(data, st, xhr,tableObj.tableId);}, loadBeforeSend:function(xhr){jgridUtil.customizedSendingReq(xhr,tableObj.tableId);}, loadComplete:function(data){jgridUtil.processObjectData(data,tableObj.tableId);}, onSelectRow:function(id){jgridUtil.onSelectRow(id,tableObj.tableId);}, beforeSelectRow: null, onSortCol: null, ondblClickRow: null, onRightClickRow: null, onPaging: null, onSelectAll: null, gridComplete: null, beforeRequest: null, onHeaderClick: null, viewrecords: true, loadonce: false, multiselect: false, multikey: false, editurl: null, search: false, caption: (tableObj.caption)?tableObj.caption:"", hidegrid: true, hiddengrid: false, postData: this.formatPostData(tableObj.postData), userData: {}, treeGrid : false, treeGridModel : 'nested', treeReader : {}, treeANode : -1, ExpandColumn: null, tree_root_level : 0, prmNames: {page:"page",rows:"rows", sort: "sidx",order: "sord", search:"_search", nd:"nd", id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del", subgridid:"id", npage: null, totalrows:"totalrows"}, forceFit : false, gridstate : "visible", cellEdit: false, cellsubmit: "remote", nv:0, toolbar: [false,""], scroll: false, multiboxonly : false, deselectAfterSort : true, scrollrows : false, autowidth: false, scrollOffset :18, cellLayout: 5, subGridWidth: 20, multiselectWidth: 20, gridview: false, rownumWidth: 25, rownumbers : false, pagerpos: 'center', recordpos: 'right', footerrow : false, userDataOnFooter : false, hoverrows : true, altclass : 'ui-priority-secondary', viewsortcols : [false,'vertical',true], resizeclass : '', autoencode : false, remapColumns : [], ajaxGridOptions :{}, direction : "ltr", toppager: false, headertitles: false, scrollTimeout: 40, data : [], _index : {}, grouping : (tableObj.grouping)?tableObj.grouping:false, groupingView : { groupField:[], groupOrder:[], groupText:[], groupColumnShow:[], groupSummary:[], showSummaryOnHide: false, sortitems:[], sortnames:[], groupDataSorted : false, summary:[], summaryval:[], plusicon: 'ui-icon-circlesmall-plus', minusicon: 'ui-icon-circlesmall-minus'}, ignoreCase : false, cmTemplate : {}, idPrefix : "" }; var customGrouping=tableObj.groupingView; if(customGrouping) { gridObj.groupingView.groupField=(customGrouping.groupField)?customGrouping.groupField:[]; gridObj.groupingView.groupOrder=(customGrouping.groupOrder)?customGrouping.groupOrder:[]; gridObj.groupingView.groupText=(customGrouping.groupText)?customGrouping.groupText:[]; gridObj.groupingView.groupColumnShow=(customGrouping.groupColumnShow)?customGrouping.groupColumnShow:[]; gridObj.groupingView.groupSummary=(customGrouping.groupSummary)?customGrouping.groupSummary:[]; gridObj.groupingView.showSummaryOnHide=(customGrouping.showSummaryOnHide)?customGrouping.showSummaryOnHide:false; gridObj.groupingView.sortitems=(customGrouping.sortitems)?customGrouping.sortitems:[]; gridObj.groupingView.sortnames=(customGrouping.sortnames)?customGrouping.sortnames:[]; gridObj.groupingView.groupDataSorted =(customGrouping.groupDataSorted)?customGrouping.groupDataSorted: false; gridObj.groupingView.summary=(customGrouping.summary)?customGrouping.summary:[]; gridObj.groupingView.summaryval=(customGrouping.summaryval)?customGrouping.summaryval:[]; gridObj.groupingView.plusicon=(customGrouping.plusicon)?customGrouping.plusicon:'ui-icon-circlesmall-plus'; gridObj.groupingView.minusicon=(customGrouping.minusicon)?customGrouping.minusicon:'ui-icon-circlesmall-minus'; } var modifiedColModel=overrideColModel(tableObj.tableId,gridObj.colModel);//to override locally gridObj.colModel=(modifiedColModel)?modifiedColModel:gridObj.colModel; $("#"+tableObj.tableId).jqGrid(gridObj); } /** * Added to send ajax Called flag to server for all jqgrid ajax calls */ jgridUtil.formatPostData=function(postData) { if(postData) { postData["ajaxCallFlag"]="true"; } else postData={"ajaxCallFlag":"true"} return postData; }; /** * Used for adding formater colums with buttons for inline editing/picklist etc */ jgridUtil.customizeTableAttr= function(inputArray,tableType,flag) { var output=null; if(tableType=="readOnly") { // do nothing } else if(tableType=="inlineEdit") { //add edit and delete columns var editCol="Edit"; var delCol="Delete"; if(flag=="colModel") { editCol={name:"editAction",width:50, index:"editAction", fixed:true, sortable:false, resize:false, formatter:"editAction", search:false } ; delCol={name:"deleteAction",width:50, index:"deleteAction", fixed:true, sortable:false, resize:false, formatter:"delAction", search:false}; } output=new Array(); output[0]=editCol; for(var i=0; i<inputArray.length;i++) { output[i+1]=inputArray[i]; } output[output.length]=delCol; }else if(tableType=="pickList") { //add Add column var addCol="Add"; if(flag=="colModel") { addCol={name:"addAction",width:50, index:"addAction", fixed:true, sortable:false, resize:false, formatter:"pickAndAddAction", search:false } ; } output=new Array(); output[0]=addCol; for(var i=0; i<inputArray.length;i++) { output[i+1]=inputArray[i]; } }else if(tableType=="custom") { //to link to outside js file }else { err={message:" Error in customizeTableAttr method err msg: invalid tableType"}; throw (err); } if(output) return output; else return inputArray; }; /** * Used to construct buttons */ jgridUtil.activateButton=function(buttonName,tableId,searchDivWidth) { if(buttonName=="refresh") { $("#"+tableId).navGrid("#"+tableId+"_pager",{search:false, edit: false, add:false, del: false, refresh: true}); }else if(buttonName=="search") { $("#"+tableId).navButtonAdd('#'+tableId+'_pager', {caption: "", title: "Search", buttonicon: "ui-icon-search", onClickButton: function () { $("#"+tableId+"_searchDiv").toggle("slow"); }, position:"first" }); //BELOW Code intalizes and show search div $("#"+tableId).searchGrid( {layer:""+tableId+"_searchDiv",width:searchDivWidth, multipleSearch:true,multipleGroup:true, closeOnEscape:true,drag:false,resize:false,Find:"Search",showQuery:false, modal:false,jqModal:false,recreateFilter:true, onSearch:function (){jgridUtil.onJgridSearch(tableId);}} ); $("#"+tableId+"_searchDiv").insertBefore($("#"+tableId+"_pager")); $("#"+tableId+"_searchDiv").toggle("slow"); //BELOW code is used to provide search on enter and reset on escape $("#"+tableId+"_searchDiv").keydown(function (e){ if(e.keyCode == 13){ $("#fbox_"+tableId+"_search").click(); } else if (e.keyCode==27) { $("#fbox_"+tableId+"_reset").click(); } }) ; }else if(buttonName=="add") { $("#"+tableId).navButtonAdd('#'+tableId+'_pager', {caption: "", title: "Add new row", buttonicon: "ui-icon-plus", onClickButton: function () { jgridUtil.customizedadd(tableId); }, position:"last" }) }else if(buttonName=="save") { $("#"+tableId).navButtonAdd('#'+tableId+'_pager', {caption: "", title: "Save", buttonicon: "ui-icon-disk", onClickButton: function () { jgridUtil.customizedSave($("#"+tableId).getGridParam("url"),tableId); }, position:"last" }); }else if(buttonName=="restore") { $("#"+tableId).navButtonAdd('#'+tableId+'_pager', {caption: "", title: "Cancel", buttonicon: "ui-icon-cancel", onClickButton: function () { jgridUtil.customizedRestoreAll(tableId); }, position:"last" }); } } /** * Calls activate buttons to consturct required buttons based on table Type */ jgridUtil.intializeTableButtons=function(tableObj) { var tableType=tableObj.tableType; var tableId=tableObj.tableId; var searchDivWidth=$("#"+tableObj.bodyDivId).width(); var buttons = tableObj.buttons; if(buttons) //override option { for(var i=0;i<buttons.length;i++) { this.activateButton(buttons[i], tableId, searchDivWidth); } } else { if(tableType=="readOnly") { this.activateButton("refresh",tableId); this.activateButton("search",tableId,searchDivWidth); } else if(tableType=="inlineEdit") { //Refresh, search, add, save, cancel this.activateButton("refresh",tableId); this.activateButton("search",tableId,searchDivWidth); this.activateButton("add",tableId); this.activateButton("save",tableId); this.activateButton("restore",tableId); }else if(tableType=="pickList") { //refersh and custom simple search this.activateButton("refresh",tableId); this.activateButton("search",tableId,searchDivWidth); }else if(tableType=="custom") { //to be based on custom buttons enteed in table array }else { err={message:" Error in customizeTableAttr method err msg: invalid tableType"}; throw (err); } } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////SIMPLE SEARCH DIV CONSTRUCTION UTILS/////////////////////////////////////////////////////////// jgridUtil.constructSimpleSearchDiv=function(bodyDivId,tableId) { var colModels=$("#"+tableId).getGridParam("colModel"); var colNames=$("#"+tableId).getGridParam("colNames"); //filter out searchable fields for(var i=0; i<colModels.length;i++) { if(colModels[i].search===false) { colModels.splice(i,1); colNames.splice(i,1); } } if(colModels.length>0) { var searchDiv= $("<div id='"+tableId+"_simpleSearchDiv' ></div>"); var head_row= "<tr><td colspan=5 class='input-title-header'>Search...</td></tr>"; var button_row="<tr><th class='input-field-name-center' colspan=3 align='right >"+ "<input id='searchButton' name='searchButton' type='button' class=' buttonDefault ' value='Search' onclick='searchLDAP()' /> &nbsp;&nbsp;&nbsp;"+ "<input id='clearButton' name='clearButton' type='button' class='buttonDefault' value='Clear' onclick='clearLDAP()' />"+ "</th></tr>" ; } var body_row=""; for(var i=0; i<colModels.length;i+3) { body_row+="<tr>"; body_row+="<th class='input-field-name-center' width='33.3%'>"+colNames[i]+"&nbsp;"+this.getOperationDropDown(colModels[i])+ "&nbsp;"+this.getInputType(colModels[i])+" </th>"; if(i+1<colModels.length) { body_row+="<th class='input-field-name-center' width='33.3%'>"+colNames[i]+"&nbsp;"+this.getOperationDropDown(colModels[i])+ "&nbsp;"+this.getInputType(colModels[i])+" </th>"; if(i+2<colModels.length) { body_row+="<th class='input-field-name-center' width='33.3%'>"+colNames[i]+"&nbsp;"+this.getOperationDropDown(colModels[i])+ "&nbsp;"+this.getInputType(colModels[i])+" </th>"; } else { body_row+="<th class='input-field-name-center' width='33.3%'>&nbsp;</th>"; } }else { body_row+="<th class='input-field-name-center' width='33.3%'>&nbsp;</th>"; body_row+="<th class='input-field-name-center' width='33.3%'>&nbsp;</th>"; } body_row+="</tr>"; } var table = "<table width='100%'>"+head_row+body_row+button_row+"</table>"; alert(table); $(searchDiv).html(table); $(searchDiv).insertBefore($("#"+bodyDivId)); } jgridUtil.getInputType=function(colModel) { var type= colModel.stype; if(!type) type="text"; var index = colModel.index; var inputHTML=""; if(type=="text") { inputHTML="<INPUT TYPE='text' name='"+index+"_value' id='"+index+"_value' SIZE='20' CLASS='inputData' value='' />"; /*if((colModel.searchoptions)?colModel.searchoptions.attr?colModel.searchoptions.attr.title?true:false:false:false) { if(colModel.searchoptions.attr.title=="Select Date") $(inputHTML).datepicker({dateFormat: 'yy-mm-dd'});// change to populate a stack }*/ } else if (type=="select") { var opList=colModel.searchoptions.value; if(opList) { var optHTML="" for(var key in opList) { optHTML+="<option value='"+key+"'>"+opList[key]+"</option>"; } inputHTML = "<select id='"+colModel.index+"_value' class='options'>"+optHTML+"</select>"; } } return inputHTML; }; jgridUtil.getOperationDropDown= function(colModel) { var opList ={ "eq": "equal", "ne":"not equal", "lt":"less", "le":"less or equal", "gt":"greater", "ge":"greater or equal", "bw":"begins with", "bn":"does not begin with", "in":"in", "ni":"not in", "ew":"ends with", "en":"does not end with", "cn":"contains", "nc":"does not contain", "nu":"is null", "nn":"is not null" }; var options=["eq","ne"]; var modelOpt= colModel.searchoptions.sopt; if(modelOpt) { if(modelOpt.length!=0) options=modelOpt; } var optHTML="" for(var key in opList) { if(options.contains(key+"")) { optHTML+="<option value='"+key+"'>"+opList[key]+"</option>"; } } var groupOpSelect = "<select id='"+colModel.index+"_opt' class='options'>"+optHTML+"</select>"; return groupOpSelect; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// function tableStackJSONDebugHelper() { if(jgridUtil.TABLE_STACK.length!=0) { var obj = jgridUtil.TABLE_STACK[0]; alert(obj.id); alert(obj.ADD_STACK); alert(obj.EDIT_STACK); alert(obj.DEL_STACK); } /* var buffer =$('#'+tableId+'_pager_left').html(); $('#'+tableId+'_pager_left').html($('#'+tableId+'_pager_right').html()); $('#'+tableId+'_pager_right').html(buffer);*/ } /* jgridUtil.checkForChanges=function(tableId) { if(this.CHANGES_CHECK_FLAG && this.containsTableJSON(tableId)) { this.CHANGES_CHECK_FLAG=false; htmlUtil.prompt.warn(msg:{"Note: Unsaved changes will be lost during table reload."}); return false; } else { //Rest check this.CHANGES_CHECK_FLAG=true; //flush table Stack this.TABLE_STACK.removeTable(tableId); return true; } }; jgridUtil.EDIT_STACK=new Array(); jgridUtil.DEL_STACK=new Array(); jgridUtil.ADD_STACK= new Array(); jgridUtil.populateStack = function(type,tableId,rowId) { if(tableId.indexOf("#")!=-1 || rowId.indexOf("#")!=-1) { var err={message:"Error in populateStack msg:- table Id or rowId contains #"}; throw (err); } if(type=="EDIT") this.EDIT_STACK.push(tableId+"#"+rowId); else if(type=="DEL") this.DEL_STACK.push(tableId+"#"+rowId); else if(type=="ADD") this.ADD_STACK.push(tableId+"#"+rowId); }; jgridUtil.removeFromStack = function(type,tableId,rowId) { if(tableId.indexOf("#")!=-1 || rowId.indexOf("#")!=-1) { var err={message:"Error in removeFromStack msg:- table Id or rowId contains #"}; throw (err); } if(type=="EDIT") return this.EDIT_STACK.remove(tableId+"#"+rowId); else if(type=="DEL") return this.DEL_STACK.remove(tableId+"#"+rowId); else if(type=="ADD") return this.ADD_STACK.remove(tableId+"#"+rowId); else return false; }; */<file_sep> worker.execute(jsonObj,callback); worker.execute(ajaxConfi,callback) <file_sep> /* * Override function to customize jgrid settings * */ $.extend($.jgrid.defaults,{ datatype: "JSON", mtype: "POST", altRows:true, shrinkToFit:true, loadui:"block" , jsonReader : { "root": "tableData", "page": "currentPage", "total": "totalPages", "records": "totalRecords", "repeatitems": false, /* "cell": "cell",*/ "id": "id", "userdata": "objectData" } }); $.extend( $.fn.fmatter , { editAction : function(cellvalue, opts, rowdata) { var str="",ocl; var rowId=opts.rowId; if(rowId.indexOf("NEW")>-1) { ocl = "onclick=jgridUtil.customizedRestore('"+rowId+"','"+opts.gid+"'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); "; str = str+"<div title='"+$.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>"; } ocl = "onclick=jgridUtil.customizedEdit('"+rowId+"','"+opts.gid+"'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover') "; str =str+ "<div title='"+$.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;margin-left:5px;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-pencil'></span></div>"; ocl = "onclick=jgridUtil.customizedRestore('"+rowId+"','"+opts.gid+"','edit'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); "; str = str+"<div title='"+$.jgrid.edit.bCancel+"' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel' "+ocl+"><span class='ui-icon ui-icon-cancel'></span></div>"; return "<div style='margin-left:8px;'>" + str + "</div>"; }, delAction : function(cellvalue, opts, rowdata) { var str="",ocl; var rowId=opts.rowId; if(rowId.indexOf("NEW")>-1) { ocl = "onclick=jgridUtil.customizedRestore('"+rowId+"','"+opts.gid+"'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); "; str = str+"<div title='"+$.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>"; } ocl = "onclick=jgridUtil.customizedDel('"+rowId+"','"+opts.gid+"'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); "; str = str+"<div title='"+$.jgrid.nav.deltitle+"' style='float:left;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>"; ocl = "onclick=jgridUtil.customizedRestore('"+rowId+"','"+opts.gid+"','del'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); "; str = str+"<div title='"+$.jgrid.edit.bCancel+"' style='float:left;display:none;margin-left:5px;' class='ui-pg-div ui-inline-cancel' "+ocl+"><span class='ui-icon ui-icon-cancel'></span></div>"; return "<div style='margin-left:8px;'>" + str + "</div>"; }, pickAndAddAction : function(cellvalue, opts, rowdata) { var str="",ocl; var rowId=opts.rowId; ocl = "onclick=\"customPickAndAdd('"+rowId+"','"+opts.gid+"')\"; onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover') "; str =str+ "<div title='"+$.jgrid.nav.addtitle+"' style='float:left;cursor:pointer;margin-left:5px;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-extlink'></span></div>"; return "<div style='margin-left:8px;'>" + str + "</div>"; }, editableForAdd : function(cellvalue, opts, rowdata) { var str=""; var rowId=opts.rowId; var name=opts.colModel.name; if(rowId.indexOf("NEW")>-1) { str=overrideEditableForAddTrueCase(cellvalue,opts,rowdata); if(str) { return str; } str ="<input id='"+rowId+"_"+name+"' name='"+name+"' value='' type='text' ></input>"; } else { str=overrideEditableForAddFalseCase(cellvalue,opts,rowdata); if(str) { return str; } str=cellvalue; } return str; } , jgridUtilCustom : function(cellvalue, opts, rowdata) { var rowId=opts.rowId; var isNewRow=(rowId.indexOf("NEW")>-1); var str=griCustomFormater(cellvalue, opts, rowdata,isNewRow); if(str==null) { alert("Custom Formater not implemented in local js file."); throw new Error("Custom Formater not implemented in local js file."); } return str; }, customHyperLink : function(cellvalue, opts, rowdata) { var rowId=opts.rowId; var str=""; var colMod=opts.colModel; if(cellvalue) { str ="<a href='#' onclick=\"jgridCustomLinkClickHandler('"+rowId+"','"+opts.gid+"','"+opts.colModel.name+"','"+cellvalue+"');\">"+cellvalue+"</a>"; } return str; } }); /* * below plugins are src code of jgrid functions which have been modfide. These will overrice the source file. * incase source file is being updated to new version. compatibility of these override functions needs to be checkd. * Modifcations made will be can be found by searching for MODIFIED key word * */ /* * jqFilter jQuery jqGrid filter addon. * Copyright (c) 2011, <NAME>, <EMAIL> * Dual licensed under the MIT and GPL licenses * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html * * The work is inspired from this Stefan Pirvu * http://www.codeproject.com/KB/scripting/json-filtering.aspx * * The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter: { "groupOp": "AND", "groups" : [ { "groupOp": "OR", "rules": [ { "field": "name", "op": "eq", "data": "England" }, { "field": "id", "op": "le", "data": "5"} ] } ], "rules": [ { "field": "name", "op": "eq", "data": "Romania" }, { "field": "id", "op": "le", "data": "1"} ] } */ /*global jQuery, $, window, navigator */ (function ($) { $.fn.jqFilter = function( arg ) { if (typeof arg === 'string') { var fn = $.fn.jqFilter[arg]; if (!fn) { throw ("jqFilter - No such method: " + arg); } var args = $.makeArray(arguments).slice(1); return fn.apply(this,args); } var p = $.extend(true,{ filter: null, columns: [], onChange : null, afterRedraw : null, checkValues : null, error: false, errmsg : "", errorcheck : true, showQuery : true, sopt : null, ops : [ {"name": "eq", "description": "equal", "operator":"="}, {"name": "ne", "description": "not equal", "operator":"<>"}, {"name": "lt", "description": "less", "operator":"<"}, {"name": "le", "description": "less or equal","operator":"<="}, {"name": "gt", "description": "greater", "operator":">"}, {"name": "ge", "description": "greater or equal", "operator":">="}, {"name": "bw", "description": "begins with", "operator":"LIKE"}, {"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"}, {"name": "in", "description": "in", "operator":"IN"}, {"name": "ni", "description": "not in", "operator":"NOT IN"}, {"name": "ew", "description": "ends with", "operator":"LIKE"}, {"name": "en", "description": "does not end with", "operator":"NOT LIKE"}, {"name": "cn", "description": "contains", "operator":"LIKE"}, {"name": "nc", "description": "does not contain", "operator":"NOT LIKE"}, {"name": "nu", "description": "is null", "operator":"IS NULL"}, {"name": "nn", "description": "is not null", "operator":"IS NOT NULL"} ], numopts : ['eq','ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'], stropts : ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni'], _gridsopt : [], // grid translated strings, do not tuch groupOps : ["AND", "OR"], groupButton : true, ruleButtons : true, direction : "ltr" }, arg || {}); return this.each( function() { if (this.filter) {return;} this.p = p; // setup filter in case if they is not defined if (this.p.filter === null || this.p.filter === undefined) { this.p.filter = { groupOp: this.p.groupOps[0], rules: [], groups: [] }; } var i, len = this.p.columns.length, cl, isIE = /msie/i.test(navigator.userAgent) && !window.opera; // translating the options if(this.p._gridsopt.length) { // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'] for(i=0;i<this.p._gridsopt.length;i++) { this.p.ops[i].description = this.p._gridsopt[i]; } } this.p.initFilter = $.extend(true,{},this.p.filter); // set default values for the columns if they are not set if( !len ) {return;} for(i=0; i < len; i++) { cl = this.p.columns[i]; if( cl.stype ) { // grid compatibility cl.inputtype = cl.stype; } else if(!cl.inputtype) { cl.inputtype = 'text'; } if( cl.sorttype ) { // grid compatibility cl.searchtype = cl.sorttype; } else if (!cl.searchtype) { cl.searchtype = 'string'; } if(cl.hidden === undefined) { // jqGrid compatibility cl.hidden = false; } if(!cl.label) { cl.label = cl.name; } if(cl.index) { cl.name = cl.index; } if(!cl.hasOwnProperty('searchoptions')) { cl.searchoptions = {}; } if(!cl.hasOwnProperty('searchrules')) { cl.searchrules = {}; } } if(this.p.showQuery) { $(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>"); } //MODIFED TO Support serach rules validation as per jgridUtils var tableId=(this.id+"").split("_")[1]; /* *Perform checking. * */ var checkData = function(val, colModelItem,tableId) { var ret = [true,""]; //MODIFED TO Support serach rules validation as per jgridUtils //TableId added if(colModelItem.searchrules) { if(jgridUtil.validRow($(".search_"+colModelItem.index),colModelItem.searchrules,val,tableId)===false) { p.error=true; p.errmsg="validation error"; } } /*if($.isFunction(colModelItem.searchrules)) { ret = colModelItem.searchrules(val, colModelItem); } else if($.jgrid && $.jgrid.checkValues) { try { ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label); } catch (e) {} } if(ret && ret.length && ret[0] === false) { p.error = !ret[0]; p.errmsg = ret[1]; }*/ }; /* moving to common randId = function() { return Math.floor(Math.random()*10000).toString(); }; */ this.onchange = function ( ){ // clear any error this.p.error = false; this.p.errmsg=""; return $.isFunction(this.p.onChange) ? this.p.onChange.call( this, this.p ) : false; }; /* * Redraw the filter every time when new field is added/deleted * and field is changed */ this.reDraw = function() { $("table.group:first",this).remove(); var t = this.createTableForGroup(p.filter, null); $(this).append(t); if($.isFunction(this.p.afterRedraw) ) { this.p.afterRedraw.call(this, this.p); } }; /* * Creates a grouping data for the filter * @param group - object * @param parentgroup - object */ this.createTableForGroup = function(group, parentgroup) { var that = this, i; //MODIFED CSS FOR THIS // this table will hold all the group (tables) and rules (rows) var table = $("<table class='group ui-widget ' style='border:0px none;'><tbody></tbody></table>"), // create error message row align = "left"; if(this.p.direction == "rtl") { align = "right"; table.attr("dir","rtl"); } if(parentgroup === null) { table.append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='"+align+"'></th></tr>"); } var tr = $("<tr></tr>"); table.append(tr); // this header will hold the group operator type and group action buttons for // creating subgroup "+ {}", creating rule "+" or deleting the group "-" var th = $("<th colspan='5' align='"+align+"'></th>"); tr.append(th); if(this.p.ruleButtons === true) { // dropdown for: choosing group operator type var groupOpSelect = $("<select class='opsel'></select>"); th.append(groupOpSelect); // populate dropdown with all posible group operators: or, and var str= "", selected; for (i = 0; i < p.groupOps.length; i++) { selected = group.groupOp === that.p.groupOps[i] ? " selected='selected'" :""; str += "<option value='"+that.p.groupOps[i]+"'" + selected+">"+that.p.groupOps[i]+"</option>"; } groupOpSelect .append(str) .bind('change',function() { group.groupOp = $(groupOpSelect).val(); that.onchange(); // signals that the filter has changed }); } // button for adding a new subgroup var inputAddSubgroup ="<span></span>"; if(this.p.groupButton) { //MODIFED CSS FOR THIS inputAddSubgroup = $("<input type='button' value='+ {}' title='Add subgroup' class='add-group ui-jqgrid-custom-button'/>"); inputAddSubgroup.bind('click',function() { if (group.groups === undefined ) { group.groups = []; } group.groups.push({ groupOp: p.groupOps[0], rules: [], groups: [] }); // adding a new group that.reDraw(); // the html has changed, force reDraw that.onchange(); // signals that the filter has changed return false; }); } th.append(inputAddSubgroup); if(this.p.ruleButtons === true) { // button for adding a new rule //MODIFED CSS FOR THIS var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule ui-add ui-jqgrid-custom-button'/>"), cm; inputAddRule.bind('click',function() { //if(!group) { group = {};} if (group.rules === undefined) { group.rules = []; } for (i = 0; i < that.p.columns.length; i++) { // but show only serchable and serchhidden = true fields var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search , hidden = (that.p.columns[i].hidden === true), ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true); if ((ignoreHiding && searchable) || (searchable && !hidden)) { cm = that.p.columns[i]; break; } } var opr; if( cm.searchoptions.sopt ) {opr = cm.searchoptions.sopt;} else if(that.p.sopt) { opr= that.p.sopt; } else if (cm.searchtype === 'string') {opr = that.p.stropts;} else {opr = that.p.numopts;} group.rules.push({ field: cm.name, op: opr[0], data: "" }); // adding a new rule that.reDraw(); // the html has changed, force reDraw // for the moment no change have been made to the rule, so // this will not trigger onchange event return false; }); th.append(inputAddRule); } // button for delete the group if (parentgroup !== null) { // ignore the first group //MODIFED CSS FOR THIS var inputDeleteGroup = $("<input type='button' value='-' title='Delete group' class='delete-group ui-jqgrid-custom-button'/>"); th.append(inputDeleteGroup); inputDeleteGroup.bind('click',function() { // remove group from parent for (i = 0; i < parentgroup.groups.length; i++) { if (parentgroup.groups[i] === group) { parentgroup.groups.splice(i, 1); break; } } that.reDraw(); // the html has changed, force reDraw that.onchange(); // signals that the filter has changed return false; }); } // append subgroup rows if (group.groups !== undefined) { for (i = 0; i < group.groups.length; i++) { var trHolderForSubgroup = $("<tr></tr>"); table.append(trHolderForSubgroup); var tdFirstHolderForSubgroup = $("<td class='first'></td>"); trHolderForSubgroup.append(tdFirstHolderForSubgroup); var groupCls=""; //MODIFED FOR highlighting boudries of subgroup if(i%2==0) groupCls="highlight_subgroup"; var tdMainHolderForSubgroup = $("<td colspan='4' class='"+groupCls+"'></td>"); tdMainHolderForSubgroup.toggleClass tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group)); trHolderForSubgroup.append(tdMainHolderForSubgroup); } } if(group.groupOp === undefined) { group.groupOp = that.p.groupOps[0]; } // append rules rows if (group.rules !== undefined) { for (i = 0; i < group.rules.length; i++) { table.append( this.createTableRowForRule(group.rules[i], group) ); } } // alert($(table).html()); return table; }; /* * Create the rule data for the filter */ this.createTableRowForRule = function(rule, group ) { // save current entity in a variable so that it could // be referenced in anonimous method calls var that=this, tr = $("<tr></tr>"), //document.createElement("tr"), // first column used for padding //tdFirstHolderForRule = document.createElement("td"), i, op, trpar, cm, str="", selected; //tdFirstHolderForRule.setAttribute("class", "first"); tr.append("<td class='first'></td>"); // create field container var ruleFieldTd = $("<td class='columns'></td>"); tr.append(ruleFieldTd); // dropdown for: choosing field var ruleFieldSelect = $("<select></select>"), ina, aoprs = []; ruleFieldTd.append(ruleFieldSelect); ruleFieldSelect.bind('change',function() { rule.field = $(ruleFieldSelect).val(); trpar = $(this).parents("tr:first"); for (i=0;i<that.p.columns.length;i++) { if(that.p.columns[i].name === rule.field) { cm = that.p.columns[i]; break; } } if(!cm) {return;} cm.searchoptions.id = $.jgrid.randId(); if(isIE && cm.inputtype === "text") { if(!cm.searchoptions.size) { cm.searchoptions.size = 10; } } var elm = $.jgrid.createEl(cm.inputtype,cm.searchoptions, "", true, that.p.ajaxSelectOptions, true); $(elm).addClass("input-elm"); //MOFIED to support SEARCH VALIDATION $(elm).addClass("search_"+cm.index); //that.createElement(rule, ""); if( cm.searchoptions.sopt ) {op = cm.searchoptions.sopt;} else if(that.p.sopt) { op= that.p.sopt; } else if (cm.searchtype === 'string') {op = that.p.stropts;} else {op = that.p.numopts;} // operators var s ="", so = 0; aoprs = []; $.each(that.p.ops, function() { aoprs.push(this.name) }); for ( i = 0 ; i < op.length; i++) { ina = $.inArray(op[i],aoprs); if(ina !== -1) { if(so===0) { rule.op = that.p.ops[ina].name; } s += "<option value='"+that.p.ops[ina].name+"'>"+that.p.ops[ina].description+"</option>"; so++; } } $(".selectopts",trpar).empty().append( s ); $(".selectopts",trpar)[0].selectedIndex = 0; //MODIFIED for DROPDOWN BUG IN IE 9 // if( $.browser.msie && $.browser.version <9) { if( $.browser.msie && $.browser.version <10) { var sw = parseInt($("select.selectopts",trpar)[0].offsetWidth) + 1; $(".selectopts",trpar).width( sw ); $(".selectopts",trpar).css("width","auto"); } // data $(".data",trpar).empty().append( elm ); $(".input-elm",trpar).bind('change',function() { rule.data = $(this).val(); that.onchange(); // signals that the filter has changed }); setTimeout(function(){ //IE, Opera, Chrome rule.data = $(elm).val(); that.onchange(); // signals that the filter has changed }, 0); }); // populate drop down with user provided column definitions var j=0; for (i = 0; i < that.p.columns.length; i++) { // but show only serchable and serchhidden = true fields var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search , hidden = (that.p.columns[i].hidden === true), ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true); if ((ignoreHiding && searchable) || (searchable && !hidden)) { selected = ""; if(rule.field === that.p.columns[i].name) { selected = " selected='selected'"; j=i; } str += "<option value='"+that.p.columns[i].name+"'" +selected+">"+that.p.columns[i].label+"</option>"; } } ruleFieldSelect.append( str ); // create operator container var ruleOperatorTd = $("<td class='operators'></td>"); tr.append(ruleOperatorTd); cm = p.columns[j]; // create it here so it can be referentiated in the onchange event //var RD = that.createElement(rule, rule.data); cm.searchoptions.id = $.jgrid.randId(); if(isIE && cm.inputtype === "text") { if(!cm.searchoptions.size) { cm.searchoptions.size = 10; } } var ruleDataInput = $.jgrid.createEl(cm.inputtype,cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions, true); // dropdown for: choosing operator var ruleOperatorSelect = $("<select class='selectopts'></select>"); ruleOperatorTd.append(ruleOperatorSelect); ruleOperatorSelect.bind('change',function() { rule.op = $(ruleOperatorSelect).val(); trpar = $(this).parents("tr:first"); var rd = $(".input-elm",trpar)[0]; if (rule.op === "nu" || rule.op === "nn") { // disable for operator "is null" and "is not null" rule.data = ""; rd.value = ""; rd.setAttribute("readonly", "true"); rd.setAttribute("disabled", "true"); } else { rd.removeAttribute("readonly"); rd.removeAttribute("disabled"); } that.onchange(); // signals that the filter has changed }); // populate drop down with all available operators if( cm.searchoptions.sopt ) {op = cm.searchoptions.sopt;} else if(that.p.sopt) { op= that.p.sopt; } else if (cm.searchtype === 'string') {op = p.stropts;} else {op = that.p.numopts;} str=""; $.each(that.p.ops, function() { aoprs.push(this.name) }); for ( i = 0; i < op.length; i++) { ina = $.inArray(op[i],aoprs); if(ina !== -1) { selected = rule.op === that.p.ops[ina].name ? " selected='selected'" : ""; str += "<option value='"+that.p.ops[ina].name+"'"+selected+">"+that.p.ops[ina].description+"</option>"; } } ruleOperatorSelect.append( str ); // create data container var ruleDataTd = $("<td class='data'></td>"); tr.append(ruleDataTd); // textbox for: data // is created previously //ruleDataInput.setAttribute("type", "text"); ruleDataTd.append(ruleDataInput); //MOFIED to support SEARCH VALIDATION $(ruleDataInput).addClass("input-elm") .addClass("search_"+cm.index) .bind('change', function() { rule.data = $(this).val(); that.onchange(); // signals that the filter has changed }); // create action container var ruleDeleteTd = $("<td></td>"); tr.append(ruleDeleteTd); // create button for: delete rule if(this.p.ruleButtons === true) { //MODIFED CSS FOR THIS var ruleDeleteInput = $("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del ui-jqgrid-custom-button'/>"); ruleDeleteTd.append(ruleDeleteInput); //$(ruleDeleteInput).html("").height(20).width(30).button({icons: { primary: "ui-icon-minus", text:false}}); ruleDeleteInput.bind('click',function() { // remove rule from group for (i = 0; i < group.rules.length; i++) { if (group.rules[i] === rule) { group.rules.splice(i, 1); break; } } that.reDraw(); // the html has changed, force reDraw that.onchange(); // signals that the filter has changed return false; }); } return tr; }; this.getStringForGroup = function(group) { var s = "(", index; if (group.groups !== undefined) { for (index = 0; index < group.groups.length; index++) { if (s.length > 1) { s += " " + group.groupOp + " "; } try { s += this.getStringForGroup(group.groups[index]); } catch (eg) {alert(eg);} } } if (group.rules !== undefined) { try{ for (index = 0; index < group.rules.length; index++) { if (s.length > 1) { s += " " + group.groupOp + " "; } s += this.getStringForRule(group.rules[index]); } } catch (e) {alert(e);} } s += ")"; if (s === "()") { return ""; // ignore groups that don't have rules } else { return s; } }; this.getStringForRule = function(rule) { var opUF = "",opC="", i, cm, ret, val, numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid for (i = 0; i < this.p.ops.length; i++) { if (this.p.ops[i].name === rule.op) { opUF = this.p.ops[i].operator; opC = this.p.ops[i].name; break; } } for (i=0; i<this.p.columns.length; i++) { if(this.p.columns[i].name === rule.field) { cm = this.p.columns[i]; break; } } val = rule.data; if(opC === 'bw' || opC === 'bn') { val = val+"%"; } if(opC === 'ew' || opC === 'en') { val = "%"+val; } if(opC === 'cn' || opC === 'nc') { val = "%"+val+"%"; } if(opC === 'in' || opC === 'ni') { val = " ("+val+")"; } //MODIFED TO Support serach rules validation as per jgridUtils if(p.errorcheck) { checkData(rule.data, cm,tableId); } if($.inArray(cm.searchtype, numtypes) !== -1 || opC === 'nn' || opC === 'nu') { ret = rule.field + " " + opUF + " " + val; } else { ret = rule.field + " " + opUF + " \"" + val + "\""; } return ret; }; this.resetFilter = function () { this.p.filter = $.extend(true,{},this.p.initFilter); this.reDraw(); this.onchange(); }; this.hideError = function() { $("th.ui-state-error", this).html(""); $("tr.error", this).hide(); }; this.showError = function() { $("th.ui-state-error", this).html(this.p.errmsg); $("tr.error", this).show(); }; this.toUserFriendlyString = function() { return this.getStringForGroup(p.filter); }; this.toString = function() { // this will obtain a string that can be used to match an item. var that = this; function getStringRule(rule) { if(that.p.errorcheck) { var i, cm; for (i=0; i<that.p.columns.length; i++) { if(that.p.columns[i].name === rule.field) { cm = that.p.columns[i]; break; } } //MODIFED TO Support serach rules validation as per jgridUtils if(cm) {checkData(rule.data, cm,tableId);} } return rule.op + "(item." + rule.field + ",'" + rule.data + "')"; } function getStringForGroup(group) { var s = "(", index; if (group.groups !== undefined) { for (index = 0; index < group.groups.length; index++) { if (s.length > 1) { if (group.groupOp === "OR") { s += " || "; } else { s += " && "; } } s += getStringForGroup(group.groups[index]); } } if (group.rules !== undefined) { for (index = 0; index < group.rules.length; index++) { if (s.length > 1) { if (group.groupOp === "OR") { s += " || "; } else { s += " && "; } } s += getStringRule(group.rules[index]); } } s += ")"; if (s === "()") { return ""; // ignore groups that don't have rules } else { return s; } } return getStringForGroup(this.p.filter); }; // Here we init the filter this.reDraw(); if(this.p.showQuery) { this.onchange(); } // mark is as created so that it will not be created twice on this element this.filter = true; }); }; $.extend($.fn.jqFilter,{ /* * Return SQL like string. Can be used directly */ toSQLString : function() { var s =""; this.each(function(){ s = this.toUserFriendlyString(); }); return s; }, /* * Return filter data as object. */ filterData : function() { var s; this.each(function(){ s = this.p.filter; }); return s; }, getParameter : function (param) { if(param !== undefined) { if (this.p.hasOwnProperty(param) ) { return this.p[param]; } } return this.p; }, resetFilter: function() { return this.each(function(){ this.resetFilter(); }); }, addFilter: function (pfilter) { if (typeof pfilter === "string") { pfilter = jQuery.jgrid.parse( pfilter ); } this.each(function(){ this.p.filter = pfilter; this.reDraw(); this.onchange(); }); } }); })(jQuery); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * jqGrid extension for form editing Grid Data * <NAME> <EMAIL> * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ /*global xmlJsonClass, jQuery, $ */ (function($){ $.jgrid.extend({ searchGrid : function (p) { p = $.extend({ recreateFilter: false, drag: true, sField:'searchField', sValue:'searchString', sOper: 'searchOper', sFilter: 'filters', loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only. beforeShowSearch: null, afterShowSearch : null, onInitializeSearch: null, afterRedraw : null, closeAfterSearch : false, closeAfterReset: false, closeOnEscape : false, multipleSearch : false, multipleGroup : false, //cloneSearchRowOnAdd: true, top : 0, left: 0, jqModal : true, modal: false, resize : true, width: 450, height: 'auto', dataheight: 'auto', showQuery: false, errorcheck : true, // translation // if you want to change or remove the order change it in sopt // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'], sopt: null, stringResult: undefined, onClose : null, onSearch : null, onReset : null, toTop : true, overlay : 30, columns : [], tmplNames : null, tmplFilters : null, // translations - later in lang file tmplLabel : ' Template: ', showOnLoad: false, layer: null }, $.jgrid.search, p || {}); return this.each(function() { var $t = this; if(!$t.grid) {return;} var fid = "fbox_"+$t.p.id, showFrm = true, IDs = {themodal:'searchmod'+fid,modalhead:'searchhd'+fid,modalcontent:'searchcnt'+fid, scrollelm : fid}, defaultFilters = $t.p.postData[p.sFilter]; if(typeof(defaultFilters) === "string") { defaultFilters = $.jgrid.parse( defaultFilters ); } if(p.recreateFilter === true) { $("#"+IDs.themodal).remove(); } function showFilter() { if($.isFunction(p.beforeShowSearch)) { showFrm = p.beforeShowSearch($("#"+fid)); if(typeof(showFrm) === "undefined") { showFrm = true; } } if(showFrm) { $.jgrid.viewModal("#"+IDs.themodal,{gbox:"#gbox_"+fid,jqm:p.jqModal, modal:p.modal, overlay: p.overlay, toTop: p.toTop}); if($.isFunction(p.afterShowSearch)) { p.afterShowSearch($("#"+fid)); } } } if ( $("#"+IDs.themodal).html() !== null ) { showFilter(); } else { var fil = $("<div class='searchFilter_container'><div id='"+fid+"' class='searchFilter' style='overflow:auto'></div></div>").insertBefore("#gview_"+$t.p.id), align = "left", butleft =""; if($t.p.direction == "rtl") { align = "right"; butleft = " style='text-align:left'"; fil.attr("dir","rtl"); } if($.isFunction(p.onInitializeSearch) ) { p.onInitializeSearch($("#"+fid)); } var columns = $.extend([],$t.p.colModel), //MODIFED TO CHANGE BUTTON STYLING bS ="<input id='"+fid+"_search' name='"+fid+"_search' type='button' class='ui-jqgrid-custom-button' value='Search' />", bC ="<input id='"+fid+"_reset' name='"+fid+"_search' type='button' class='ui-jqgrid-custom-button' value='Reset' />", // bS ="<a href='javascript:void(0)' id='"+fid+"_search' class='fm-button ui-state-default ui-corner-all fm-button-icon-right ui-reset'><span class='ui-icon ui-icon-search'></span>"+p.Find+"</a>", // bC ="<a href='javascript:void(0)' id='"+fid+"_reset' class='fm-button ui-state-default ui-corner-all fm-button-icon-left ui-search'><span class='ui-icon ui-icon-arrowreturnthick-1-w'></span>"+p.Reset+"</a>", bQ = "", tmpl="", colnm, found = false, bt, cmi=-1; if(p.showQuery) { bQ ="<a href='javascript:void(0)' id='"+fid+"_query' class='fm-button ui-state-default ui-corner-all fm-button-icon-left'><span class='ui-icon ui-icon-comment'></span>Query</a>"; } if(!p.columns.length) { $.each(columns, function(i,n){ if(!n.label) { n.label = $t.p.colNames[i]; } // find first searchable column and set it if no default filter if(!found) { var searchable = (typeof n.search === 'undefined') ? true: n.search , hidden = (n.hidden === true), ignoreHiding = (n.searchoptions && n.searchoptions.searchhidden === true); if ((ignoreHiding && searchable) || (searchable && !hidden)) { found = true; colnm = n.index || n.name; cmi =i; } } }); } else { columns = p.columns; } // old behaviour if( (!defaultFilters && colnm) || p.multipleSearch === false ) { var cmop = "eq"; if(cmi >=0 && columns[cmi].searchoptions && columns[cmi].searchoptions.sopt) { cmop = columns[cmi].searchoptions.sopt[0]; } else if(p.sopt && p.sopt.length) { cmop = p.sopt[0]; } defaultFilters = {"groupOp": "AND",rules:[{"field":colnm,"op":cmop,"data":""}]}; } found = false; if(p.tmplNames && p.tmplNames.length) { found = true; tmpl = p.tmplLabel; tmpl += "<select class='ui-template'>"; tmpl += "<option value='default'>Default</option>"; $.each(p.tmplNames, function(i,n){ tmpl += "<option value='"+i+"'>"+n+"</option>"; }); tmpl += "</select>"; } bt = "<table class='search_button' style='width:99%;border:0px none;margin-top:0px' id='"+fid+"_2'><tbody><tr><td colspan='2' align='right' >"+bS+"&nbsp;&nbsp;&nbsp;"+bC+"</td></tr></tbody></table>"; $("#"+fid).jqFilter({ columns : columns, filter: p.loadDefaults ? defaultFilters : null, showQuery: p.showQuery, errorcheck : p.errorcheck, sopt: p.sopt, groupButton : p.multipleGroup, ruleButtons : p.multipleSearch, afterRedraw : p.afterRedraw, _gridsopt : $.jgrid.search.odata, onChange : function( sp ) { // MODIFIED FOR BUTTON SYTLING // if(this.p.showQuery) { $('.query',this).html(this.toUserFriendlyString()); // } }, direction : $t.p.direction }); // alert(fil.html()); fil.append( bt ); if(found && p.tmplFilters && p.tmplFilters.length) { $(".ui-template", fil).bind('change', function(e){ var curtempl = $(this).val(); if(curtempl=="default") { $("#"+fid).jqFilter('addFilter', defaultFilters); } else { $("#"+fid).jqFilter('addFilter', p.tmplFilters[parseInt(curtempl,10)]); } return false; }); } if(p.multipleGroup === true) p.multipleSearch = true; if($.isFunction(p.onInitializeSearch) ) { p.onInitializeSearch($("#"+fid)); } p.gbox = "#gbox_"+fid; $("#"+p.layer).html(fil); /* if (p.layer) $.jgrid.createModal(IDs ,fil,p,"#gview_"+$t.p.id,$("#gbox_"+$t.p.id)[0], "#"+p.layer, {position: "relative"}); else $.jgrid.createModal(IDs ,fil,p,"#gview_"+$t.p.id,$("#gbox_"+$t.p.id)[0]);*/ if(bQ) { $("#"+fid+"_query").bind('click', function(e){ $(".queryresult", fil).toggle(); return false; }); } if (p.stringResult===undefined) { // to provide backward compatibility, inferring stringResult value from multipleSearch p.stringResult = p.multipleSearch; } $("#"+fid+"_search").bind('click', function(){ var fl = $("#"+fid), sdata={}, res , filters = fl.jqFilter('filterData'); if(p.errorcheck) { fl[0].hideError(); if(!p.showQuery) {fl.jqFilter('toSQLString');} if(fl[0].p.error) { //fl[0].showError();MODIFIED to not show error return false; } } if(p.stringResult) { try { // xmlJsonClass or JSON.stringify res = xmlJsonClass.toJson(filters, '', '', false); } catch (e) { try { res = JSON.stringify(filters); } catch (e2) { } } if(typeof(res)==="string") { sdata[p.sFilter] = res; $.each([p.sField,p.sValue, p.sOper], function() {sdata[this] = "";}); } } else { if(p.multipleSearch) { sdata[p.sFilter] = filters; $.each([p.sField,p.sValue, p.sOper], function() {sdata[this] = "";}); } else { sdata[p.sField] = filters.rules[0].field; sdata[p.sValue] = filters.rules[0].data; sdata[p.sOper] = filters.rules[0].op; sdata[p.sFilter] = ""; } } $t.p.search = true; $.extend($t.p.postData,sdata); if($.isFunction(p.onSearch) ) { p.onSearch(); } $($t).trigger("reloadGrid",[{page:1}]); if(p.closeAfterSearch) { $.jgrid.hideModal("#"+IDs.themodal,{gb:"#gbox_"+$t.p.id,jqm:p.jqModal,onClose: p.onClose}); } return false; }); $("#"+fid+"_reset").bind('click', function(){ var sdata={}, fl = $("#"+fid); $t.p.search = false; if(p.multipleSearch===false) { sdata[p.sField] = sdata[p.sValue] = sdata[p.sOper] = ""; } else { sdata[p.sFilter] = ""; } fl[0].resetFilter(); if(found) { $(".ui-template", fil).val("default"); } $.extend($t.p.postData,sdata); if($.isFunction(p.onReset) ) { p.onReset(); } $($t).trigger("reloadGrid",[{page:1}]); return false; }); showFilter(); $(".fm-button:not(.ui-state-disabled)",fil).hover( function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');} ); } }); }, navGrid : function (elem, o, pEdit,pAdd,pDel,pSearch, pView) { o = $.extend({ edit: true, editicon: "ui-icon-pencil", add: true, addicon:"ui-icon-plus", del: true, delicon:"ui-icon-trash", search: true, searchicon:"ui-icon-search", refresh: true, refreshicon:"ui-icon-refresh", refreshstate: 'firstpage', view: false, viewicon : "ui-icon-document", position : "left", closeOnEscape : true, beforeRefresh : null, afterRefresh : null, cloneToTop : false, alertwidth : 200, alertheight : 'auto', alerttop: null, alertleft: null, alertzIndex : null }, $.jgrid.nav, o ||{}); return this.each(function() { if(this.nav) {return;} var alertIDs = {themodal:'alertmod',modalhead:'alerthd',modalcontent:'alertcnt'}, $t = this, twd, tdw; if(!$t.grid || typeof elem != 'string') {return;} if ($("#"+alertIDs.themodal).html() === null) { if(!o.alerttop && !o.alertleft) { if (typeof window.innerWidth != 'undefined') { o.alertleft = window.innerWidth; o.alerttop = window.innerHeight; } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth !== 0) { o.alertleft = document.documentElement.clientWidth; o.alerttop = document.documentElement.clientHeight; } else { o.alertleft=1024; o.alerttop=768; } o.alertleft = o.alertleft/2 - parseInt(o.alertwidth,10)/2; o.alerttop = o.alerttop/2-25; } $.jgrid.createModal(alertIDs,"<div>"+o.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+$t.p.id,jqModal:true,drag:true,resize:true,caption:o.alertcap,top:o.alerttop,left:o.alertleft,width:o.alertwidth,height: o.alertheight,closeOnEscape:o.closeOnEscape, zIndex: o.alertzIndex},"","",true); } var clone = 1; if(o.cloneToTop && $t.p.toppager) {clone = 2;} for(var i = 0; i<clone; i++) { var tbd, //modified for position buttons to right // navtbl = $("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"), navtbl = $("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:right;table-layout:auto;'><tbody><tr></tr></tbody></table>"), sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>", pgid, elemids; if(i===0) { pgid = elem; elemids = $t.p.id; if(pgid == $t.p.toppager) { elemids += "_top"; clone = 1; } } else { pgid = $t.p.toppager; elemids = $t.p.id+"_top"; } if($t.p.direction == "rtl") {$(navtbl).attr("dir","rtl").css("float","right");} if (o.add) { pAdd = pAdd || {}; tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.addicon+"'></span>"+o.addtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.addtitle || "",id : pAdd.id || "add_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { if ($.isFunction( o.addfunc )) { o.addfunc(); } else { $($t).jqGrid("editGridRow","new",pAdd); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.edit) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pEdit = pEdit || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.editicon+"'></span>"+o.edittext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.edittitle || "",id: pEdit.id || "edit_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var sr = $t.p.selrow; if (sr) { if($.isFunction( o.editfunc ) ) { o.editfunc(sr); } else { $($t).jqGrid("editGridRow",sr,pEdit); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.view) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pView = pView || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.viewicon+"'></span>"+o.viewtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.viewtitle || "",id: pView.id || "view_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var sr = $t.p.selrow; if (sr) { if($.isFunction( o.viewfunc ) ) { o.viewfunc(sr); } else { $($t).jqGrid("viewGridRow",sr,pView); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true}); $("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if (o.del) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pDel = pDel || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.delicon+"'></span>"+o.deltext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.deltitle || "",id: pDel.id || "del_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { var dr; if($t.p.multiselect) { dr = $t.p.selarrrow; if(dr.length===0) {dr = null;} } else { dr = $t.p.selrow; } if(dr){ if("function" == typeof o.delfunc){ o.delfunc(dr); }else{ $($t).jqGrid("delGridRow",dr,pDel); } } else { $.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$t.p.id,jqm:true});$("#jqg_alrt").focus(); } } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } if(o.add || o.edit || o.del || o.view) {$("tr",navtbl).append(sep);} if (o.search) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); pSearch = pSearch || {}; $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.searchicon+"'></span>"+o.searchtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.searchtitle || "",id:pSearch.id || "search_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { $($t).jqGrid("searchGrid",pSearch); } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); if (pSearch.showOnLoad && pSearch.showOnLoad === true) $(tbd,navtbl).click(); tbd = null; } if (o.refresh) { tbd = $("<td class='ui-pg-button ui-corner-all'></td>"); $(tbd).append("<div class='ui-pg-div'><span class='ui-icon "+o.refreshicon+"'></span>"+o.refreshtext+"</div>"); $("tr",navtbl).append(tbd); $(tbd,navtbl) .attr({"title":o.refreshtitle || "",id: "refresh_"+elemids}) .click(function(){ if (!$(this).hasClass('ui-state-disabled')) { if($.isFunction(o.beforeRefresh)) {o.beforeRefresh();} $t.p.search = false; try { var gID = $t.p.id; $t.p.postData.filters =""; $("#fbox_"+gID).jqFilter('resetFilter'); if($.isFunction($t.clearToolbar)) {$t.clearToolbar(false);} } catch (e) {} switch (o.refreshstate) { case 'firstpage': $($t).trigger("reloadGrid", [{page:1}]); break; case 'current': $($t).trigger("reloadGrid", [{current:true}]); break; } if($.isFunction(o.afterRefresh)) {o.afterRefresh();} } return false; }).hover( function () { if (!$(this).hasClass('ui-state-disabled')) { $(this).addClass("ui-state-hover"); } }, function () {$(this).removeClass("ui-state-hover");} ); tbd = null; } tdw = $(".ui-jqgrid").css("font-size") || "11px"; $('body').append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>"); twd = $(navtbl).clone().appendTo("#testpg2").width(); $("#testpg2").remove(); $(pgid+"_"+o.position,pgid).append(navtbl); if($t.p._nvtd) { if(twd > $t.p._nvtd[0] ) { $(pgid+"_"+o.position,pgid).width(twd); $t.p._nvtd[0] = twd; } $t.p._nvtd[1] = twd; } tdw =null;twd=null;navtbl =null; this.nav = true; } }); } }); })(jQuery); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Note Functions in setPager could not be overriden this has to be changed in source file $.extend($.fn.jqGrid,{ setPager = function (pgid, tp){ // TBD - consider escaping pgid with pgid = $.jgrid.jqID(pgid); var sep = "<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>", pginp = "", pgl="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>", str="", pgcnt, lft, cent, rgt, twd, tdw, i, clearVals = function(onpaging){ var ret; if ($.isFunction(ts.p.onPaging) ) { ret = ts.p.onPaging.call(ts,onpaging); } ts.p.selrow = null; if(ts.p.multiselect) {ts.p.selarrrow =[];$('#cb_'+$.jgrid.jqID(ts.p.id),ts.grid.hDiv)[ts.p.useProp ? 'prop': 'attr']("checked", false);} ts.p.savedRow = []; if(ret=='stop') {return false;} return true; }; pgid = pgid.substr(1); tp += "_" + pgid; pgcnt = "pg_"+pgid; lft = pgid+"_right"; cent = pgid+"_center"; rgt = pgid+"_left"; //Modified for positioning buttons to right //lft = pgid+"_left"; cent = pgid+"_center"; rgt = pgid+"_right"; // alert("#"+$.jgrid.jqID(pgid) ); $("#"+$.jgrid.jqID(pgid) ) .append("<div id='"+pgcnt+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+lft+"' align='left'></td><td id='"+cent+"' align='center' style='white-space:pre;'></td><td id='"+rgt+"' align='right'></td></tr></tbody></table></div>") .attr("dir","ltr"); //explicit setting if(ts.p.rowList.length >0){ str = "<td dir='"+dir+"'>"; str +="<select class='ui-pg-selbox' role='listbox'>"; for(i=0;i<ts.p.rowList.length;i++){ str +="<option role=\"option\" value=\""+ts.p.rowList[i]+"\""+((ts.p.rowNum == ts.p.rowList[i])?" selected=\"selected\"":"")+">"+ts.p.rowList[i]+"</option>"; } str +="</select></td>"; } if(dir=="rtl") { pgl += str; } if(ts.p.pginput===true) { pginp= "<td dir='"+dir+"'>"+$.jgrid.format(ts.p.pgtext || "","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+$.jgrid.jqID(pgid)+"'></span>")+"</td>";} if(ts.p.pgbuttons===true) { var po=["first"+tp,"prev"+tp, "next"+tp,"last"+tp]; if(dir=="rtl") { po.reverse(); } pgl += "<td id='"+po[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>"; pgl += "<td id='"+po[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>"; pgl += pginp !== "" ? sep+pginp+sep:""; pgl += "<td id='"+po[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>"; pgl += "<td id='"+po[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>"; } else if (pginp !== "") { pgl += pginp; } if(dir=="ltr") { pgl += str; } pgl += "</tr></tbody></table>"; //Modified for positioning view all records to left and buttons to right // if(ts.p.viewrecords===true) {$("td#"+pgid+"_"+ts.p.recordpos,"#"+pgcnt).append("<div dir='"+dir+"' style='text-align:"+ts.p.recordpos+"' class='ui-paging-info'></div>");} if(ts.p.viewrecords===true) {$("td#"+pgid+"_"+ts.p.recordpos,"#"+pgcnt).append("<div dir='"+dir+"' style='text-align:left' class='ui-paging-info'></div>");} $("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).append(pgl); tdw = $(".ui-jqgrid").css("font-size") || "11px"; $(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+tdw+";visibility:hidden;' ></div>"); twd = $(pgl).clone().appendTo("#testpg").width(); $("#testpg").remove(); if(twd > 0) { if(pginp !== "") { twd += 50; } //should be param $("td#"+pgid+"_"+ts.p.pagerpos,"#"+pgcnt).width(twd); } ts.p._nvtd = []; ts.p._nvtd[0] = twd ? Math.floor((ts.p.width - twd)/2) : Math.floor(ts.p.width/3); ts.p._nvtd[1] = 0; pgl=null; $('.ui-pg-selbox',"#"+pgcnt).bind('change',function() { ts.p.page = Math.round(ts.p.rowNum*(ts.p.page-1)/this.value-0.5)+1; ts.p.rowNum = this.value; if(tp) { $('.ui-pg-selbox',ts.p.pager).val(this.value); } else if(ts.p.toppager) { $('.ui-pg-selbox',ts.p.toppager).val(this.value); } if(!clearVals('records')) { return false; } populate(); return false; }); if(ts.p.pgbuttons===true) { $(".ui-pg-button","#"+pgcnt).hover(function(e){ if($(this).hasClass('ui-state-disabled')) { this.style.cursor='default'; } else { $(this).addClass('ui-state-hover'); this.style.cursor='pointer'; } },function(e) { if($(this).hasClass('ui-state-disabled')) { } else { $(this).removeClass('ui-state-hover'); this.style.cursor= "default"; } }); $("#first"+$.jgrid.jqID(tp)+", #prev"+$.jgrid.jqID(tp)+", #next"+$.jgrid.jqID(tp)+", #last"+$.jgrid.jqID(tp)).click( function(e) { var cp = intNum(ts.p.page,1), last = intNum(ts.p.lastpage,1), selclick = false, fp=true, pp=true, np=true,lp=true; if(last ===0 || last===1) {fp=false;pp=false;np=false;lp=false; } else if( last>1 && cp >=1) { if( cp === 1) { fp=false; pp=false; } else if( cp>1 && cp <last){ } else if( cp===last){ np=false;lp=false; } } else if( last>1 && cp===0 ) { np=false;lp=false; cp=last-1;} if( this.id === 'first'+tp && fp ) { ts.p.page=1; selclick=true;} if( this.id === 'prev'+tp && pp) { ts.p.page=(cp-1); selclick=true;} if( this.id === 'next'+tp && np) { ts.p.page=(cp+1); selclick=true;} if( this.id === 'last'+tp && lp) { ts.p.page=last; selclick=true;} if(selclick) { if(!clearVals(this.id)) { return false; } populate(); } return false; }); } if(ts.p.pginput===true) { $('input.ui-pg-input',"#"+pgcnt).keypress( function(e) { var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; if(key == 13) { ts.p.page = ($(this).val()>0) ? $(this).val():ts.p.page; if(!clearVals('user')) { return false; } populate(); return false; } return this; }); } } }); */<file_sep>/** * Simple API to simplify json parssing in other API calls */ window.jsonUtils=function(){ return{ getJson: function(obj){ return (typeof(obj) === "string")? obj : JSON.stringify(obj); }, getString: function(str){ try{ str = JSON.parse(str); }catch(err){ //expected exception when val is a string } return str; } }; }();<file_sep> self.onmessage=function(e) { //console.log("In Main Worker"); alert(e.data); var val = jsonUtils.getJson(e.data); var output = callFunc(val); self.postMessage(jsonUtils.getString(output)); }; // Business Logic here function callFunc(data){ //console.log("calling business logic"); var time=2000; if(data == " New Div2 content") time=7000; setTimeout(function(data){ return data},time); } jsonUtils=function(){ return{ getJson: function(obj){ return (typeof(obj) === "string")? obj : JSON.stringify(obj); }, getString: function(str){ try{ str = JSON.parse(str); }catch(err){ //expected exception when val is a string } return str; } }; }();<file_sep>window.Executor=function(WORKER_PATH){ function exec(jsonObj,guiFunc){ if(typeof(Worker) ==="undefined") throw new Error("Web worker not supported by browser"); var worker = new Worker(WORKER_PATH); worker.onmessage = function(event){ console.log("in executor onmessage handler"); console.log(event); guiFunc(jsonUtils.getJson(event.data));// process data } worker.postMessage(jsonUtils.getString(jsonObj)); } return{ execute: exec } };<file_sep>/* * Simple API used to persit data to and from local storage in HTML5 */ window.Webstore=function(localFlag){ var store = null; var unsupported = (typeof(Storage) ==="undefined" || typeof(JSON) === "undefined"); if(!unsupported){ store = (localFlag) ? localStorage : sessionStorage; } function getData(key){ var val = store[key]; val = (val) ? val : null; try{ val = JSON.parse(val); }catch(err){ console.log(err); //expected exception when val is a string } return val; } function storeData(key,obj){ var stringVal = (typeof(obj) === "string")? obj : JSON.stringify(obj); store[key]=stringVal; } function dataPresent(key){ var val = store[key]; return (val) ? true : false; } return{ get : function(key){ if(unsupported) return null; return getData(key); }, set : function(key,obj){ if(unsupported) return; storeData(key,obj); }, contains: function(key){ if(unsupported) return false; return dataPresent(key); } }; }<file_sep>respoGrid ======= Responsive Grid, inspired and built based on all the grid plugins out there from Footable to YUI, to jqgrid. One distinct approach is that this grid works as module to plugin to a require.js modular framework. Just got going about building this for fun and learning.. minimal features.. and lightweight grid framework. respo grid has a tight coupled dependency on jquery and bootstrap css. Focus of the grid is to be resposive to adapt dynamically to any window size. <file_sep>//******************************PROTOTYPE Functions added to String and Array to provide use full methods as in JAVA.************************ String.prototype.trim= function () { return this.replace(/^\s*|\s*$/g,""); }; /** * Note: the method below works like contains of ArrayList in java. * @param key (String/ number) * @return Boolean */ Array.prototype.contains= function (key) { try{ if(!this)//condition is true for this= null or undefined return false; else { for(var i=0 in this) { if (this[i]) { if(typeof this[i]=="string" && typeof key=="string" && this[i].trim()==key.trim()) return true; else if(typeof this[i]=="number" && typeof key=="number" &&this[i]==key) return true; else continue; } } return false; } }catch(err) { alert("Error in prototype Array.prototype.contains method err Msg-"+err.message); return false; } }; /** * Note: the method below works like remove of ArrayList in java. * @param key (String/ number) * @return Boolean */ Array.prototype.remove= function (key) { try{ if(!this)//condition is true for this= null or undefined return false; else { for(var i=0 in this) { if (this[i]) { if(typeof this[i]=="string" && typeof key=="string" && this[i].trim()==key.trim()) { this.splice(i,1); return true; } else if(typeof this[i]=="number" && typeof key=="number" &&this[i]==key) { this.splice(i,1); return true; } else continue; } } return false; } }catch(err) { alert("Error in prototype Array.remove.contains method err Msg-"+err.message); return false; } };<file_sep> define(function () { /* * Simple API used to persit data to and from local/session storage in HTML5 capable browsers * Takes care of caching objects and non string types by parsing and unparsing it to/from string during storage * Implements parent,key concept to enable flushing of a group pf related caches in one shot. * Code does not break incase the browser does not suppport this storage. * Hence can be used in all browsers * @author <NAME> */ var store = null; var unsupported = (typeof(Storage) ==="undefined" || typeof(JSON) === "undefined"); function getData(key,parent,storageType){ store = (storageType) ? localStorage : sessionStorage; var val = store[parent] || null; if(val === null) return null; val = val[key] || null; if(val === null) return null; try{ val = JSON.parse(val); }catch(err){ console.log(err); //expected exception when val is a string } return val; } function storeData(key,parent,obj,storageType){ store = (storageType) ? localStorage : sessionStorage; var stringVal = (typeof(obj) === "string")? obj : JSON.stringify(obj); var par = store[parent] || {}; par[key]=stringVal; } function flushCache(parent,storageType){ store = (storageType) ? localStorage : sessionStorage; var map = store[parent] || {}; if(map[parent]) map[parent]=undefined; // remove attribute } return{ get : function(key,parent,storageType){ if(unsupported) return null; return getData(key,parent,storageType); }, set : function(key,parent,obj,storageType){ if(unsupported) return; storeData(key,parent,obj); }, contains: function(key,parent,storageType){ if(unsupported) return false; return (getData(key,parent,storageType) === null); }, flush: function(parent,storageType){ if(unsupported) return; flushCache(parent,storageType); } }; });<file_sep> var HEAD_CONTROL_ELM_$ = $(parent.document.getElementById("headFrameControlFlag")); var BODY_CONTROL_ELM_$ = $(parent.document.getElementById("bodyFrameControlFlag")); var MODULE_LOCK_ELM_$ = $(parent.document.getElementById("moduleLockFlag")); $(document).ready(function() { // setFrameHanlder if(!HEAD_CONTROL_ELM_$ || !BODY_CONTROL_ELM_$ || !MODULE_LOCK_ELM_$ ) { htmlUtil.prompt.error({msg:"Frame intialization error at body frame "}); } BODY_CONTROL_ELM_$.click(function (){ frameControl.triggerAction(BODY_CONTROL_ELM_$.val()); }); MODULE_LOCK_ELM_$.val("false");//unset the module lock flag. }); var frameControl={}; ////////////////////Methods to be overridefromLocal///////////////////////////// frameControl.printAction= function() { htmlUtil.prompt.notify({msg:"Print action for this Page is under construction"}); }; frameControl.exportAction= function() { htmlUtil.prompt.notify({msg:"Export action for this Page is under construction"}); }; frameControl.feedbackHandler= function(flag,data) { if($.trim(data).length!=0) htmlUtil.prompt.notify({msg:data}); if(HEAD_CONTROL_ELM_$) { HEAD_CONTROL_ELM_$.val(flag); HEAD_CONTROL_ELM_$.click(); // triggers call from header.js called from header.jsp } }; frameControl.triggerAction= function (flag) { if(flag=="contact_us") { htmlUtil.popUp.openModalWindow('/MVT/contactUsAction.do?hidAction=INIT','50%','55%',function (data){ frameControl.feedbackHandler(flag,data);}); } else if (flag=="email") { // htmlUtil.popUp.openModalWindow('/csa/contactUs.do','50%','55%',function (data){ frameControl.feedbackHandler(flag,data);}); htmlUtil.prompt.notify({msg:"Email option is under construction"}); } else if (flag=="print") { frameControl.printAction(); } else if (flag=="export") { frameControl.exportAction(); } }; frameControl.callHeaderFunction=function(val) { if(HEAD_CONTROL_ELM_$) { HEAD_CONTROL_ELM_$.val(val); HEAD_CONTROL_ELM_$.click(); // triggers call from header.js called from header.jsp } else alert("Error in Frame Control functionality"); }; frameControl.openExternalLink=function(url) { parent.window.open(url, '_blank'); }; frameControl.openScreen=function(module,subTab,url) { var str = 'OPEN_MODULE#@'+module+'@'+subTab+'@'+url; this.callHeaderFunction(str); };<file_sep>var sessionControl={}; sessionControl.IGNORE_SESSION_COUNTER=false; // added to ignore this validation during invalid user cases sessionControl.resetSessionCount= function() { var resetSessionElm_$=$(parent.document.getElementById("refreshSessionCount")); var prntBuffer= parent; var count =10; while(resetSessionElm_$.length==0 && count>0) { prntBuffer=prntBuffer.parent; resetSessionElm_$=$(prntBuffer.document.getElementById("refreshSessionCount")); count--; } if(resetSessionElm_$.length==0 && !this.IGNORE_SESSION_COUNTER) alert("Error in getting session control object"); else { if(!this.IGNORE_SESSION_COUNTER) resetSessionElm_$.click();// triggers reset of timer in header frame does not work for contact us and head trigereed body modals } }; <file_sep>Components ======= Misc Components of js Most of these has better opensource alternatives.. but handfull snippets for my reference.. <file_sep>JSUtils ======= Javascript Utility Codes <file_sep>var exceptionHandler = {}; exceptionHandler.handle=function(data) { if(data.status && data.status=="Exception") { if(data.actionType=="AUTO_EMAIL_AND_LOGOUT") { parent.location='/MVT/jsp/criticalError.jsp'; } else if(data.actionType=="AUTO_EMAIL_AND_NOTIFY_USER") { htmlUtil.prompt.error({msg:"Application has encountered an" + " Internal Error, This has been reported to Adminstator." + " Please avoid using the current functionality for some time. "}); }else if(data.actionType=="NOTIFY_USER_COLLECT_MORE_INFO_FOR_MAIL") { //code to get a mail pop up htmlUtil.popUp.openModalWindow('/MVT/contactUsAction.do?hidAction=errorReport','50%','55%',function (data){ exceptionHandler.closeModalHandler(data);}); }else if(data.actionType=="NOTIFY_USER") { if(data.errorType=="SESSION_TIME_OUT") { htmlUtil.prompt.error({msg:"User Session Has Timed Out. Please Login again."}); window.location='/MVT/jsp/sessionTimeout.jsp'; }/*else if(data.errorType=="INVALID_USER") { parent.location='/MVT/jsp/invalidUserDetails.jsp?ERROR_TYPE='+data.errorType; }else if(data.errorType=="INACTIVE_USER") { parent.location='/MVT/jsp/invalidUserDetails.jsp?ERROR_TYPE='+data.errorType; }else if(data.errorType=="INVALID_ROLE") { window.location='/MVT/jsp/invalidUserDetails.jsp?ERROR_TYPE='+data.errorType; }*/ } return true; }else { return false; } }; exceptionHandler.closeModalHandler=function(data) { htmlUtil.prompt.notify({msg:data}); };<file_sep> /* * Required JS libs * prototype.js * jquery.js * jquery.colorbox.js // for modalUtil functions * sessionControl.js // for session expiration */ var htmlUtil={}; htmlUtil.tableUtil={};// set of table Utility functions //**********************************************TABLE UTILS*********************************************************************' /** * Added for performance, This stack stores the computed table structure in case of table call and prevent call to recomputation when * same tableId in the same page is refreshed using AJAX. */ htmlUtil.tableUtil.tableStructStack=new Array(); /** * Added for performance, * This method returns tableStruct if its already stored in the tableStructStack. Else it returns null. * @param table (tableObject) * @return tableStructureObject */ htmlUtil.tableUtil.getTableStructIfPresent= function (table) { try{ if(table.length)//jquery retruns array with table object wraped .. where as documenGetElementById returns just the object table = table[0]; var stack=this.tableStructStack; if(stack.length==0) return null; else { for(var i in stack) { if(stack[i].tableProperty.id.trim()==table.id.trim()) // condition for check is based on table ID in struct and in input { return stack[i]; } } return null; } }catch(err) { alert("Error in Copy Table Structure function in js - Error in getTableStructIfPresent msg:- "+err.message); return null; } }; //TABLE STRUCT COPY FUNCTIONS/////////////////////////////////////////// /** * @Desc * The below function copyTableStructure copies table structure and properties and return an tableStructure JSON object * This object would be used to reconstruct output form AJAX service call to reproduce to this table format. * TableStructure Obejct stores only tabel, tr and td related property information. * Code assumes simple table structure such as <table> <tr> <td>...</td>....</tr>...</table> * thead,tbody and ttail are not considered in this function * header present flag should be true is first row is header and content starts from second row * @params tableId - id value of table element * @params headerPresentFlag - boolean true if header is present */ htmlUtil.tableUtil.copyTableStructure= function (table,headerPresentFlag) { var tableStructure=null; var tableProperty =null; var headerRowProperty=null; var headerColumnPropertyList=null; var rowProperty=null; var columnPropertyList=null; tableStructure=this.getTableStructIfPresent(table); if(tableStructure)// if present return tableStructure; try { //jquery retruns array with table object wrapped .. where as documenGetElementById returns just the object // hence the below check ensure that we wrap single objet to array so that the code below will always work. if(table.length) table = table[0]; //Intiatlize table properties tableProperty=this.getTableProperty(table); var row=table.rows[0]; var headerRow=null; if(headerPresentFlag && table.rows.length>1) { headerRow=table.rows[0]; row=table.rows[1]; } if(headerRow) { //Intialize header row property headerRowProperty=this.getRowProperty(headerRow); //intialiez header columns headerColumnPropertyList=this.getColumnPropeties(headerRow); } //intialize first row property rowProperty=this.getRowProperty(row); //intlaize first columns props columnPropertyList=this.getColumnPropeties(row); //Intialize table structure tableStructure={ "tableProperty":tableProperty, "headerRowProperty":headerRowProperty, "headerColumnPropertyList":headerColumnPropertyList, "rowProperty":rowProperty, "columnPropertyList":columnPropertyList }; return tableStructure; }catch (err) { alert("Error in Copy Table Structure function in js "+err.message); return null; } }; /** * The getTableProperty method is called from copyTableStructure. This method returns a tableProperty object which contains * all table tag attributes. * @param table element * @return tablePropery */ htmlUtil.tableUtil.getTableProperty=function (table) { try{ var tableProperty={ "id":table.id, "name":table.name, "align":table.align, "background":table.background, "bgColor":table.bgColor, "border":table.border, //"caption":table.caption, "cellPadding":table.cellPadding, "cellSpacing":table.cellSpacing, "frame":table.frame, "height":table.height, "rules":table.rules, "summary":table.summary, //"tFoot":table.tFoot, //"tHead":table.tHead, "width":table.width, "style":table.style, "className":table.className }; return tableProperty; }catch(err){ err={message:"Error in getTableProperty msg:- "+err.message}; throw (err); } }; /** * The getRowProperty method is called from copyTableStructure. This method returns a rowProperty object which contains * all row tag attributes. * @param tr (row) element * @return rowProperty */ htmlUtil.tableUtil.getRowProperty=function (row) { try{ var rowProperty={ "id":row.id, "name": row.name, "align":row.align, "bgColor":row.bgColor, "ch":row.ch, "chOff":row.chOff, "height":row.height, "rowIndex":row.rowIndex, "sectionRowIndex":row.sectionRowIndex, "vAlign":row.vAlign, "style":row.style, "className":row.className, "width":row.width, "height":row.height }; return rowProperty; }catch(err){ err={message:"Error in getRowProperty msg:- "+err.message}; throw (err); } }; /** * The getColumnPropeties method is used to iterate columns in row element of table and return array of column elements with their properties. * This is called from copyTableStructure. * * @param tr (row) element * @return columnPropertyList - array of columnPropery for input row */ htmlUtil.tableUtil.getColumnPropeties=function (row) { try{ var columnPropertyList= new Array(); var cellList = row.cells; for(var i=0; i<cellList.length; i++) { var cell=cellList[i]; var columnPropery = { "className": cell.className, "style": cell.style, "id":cell.id, "name": cell.name, "colSpan":cell.colSpan, "height": cell.height, "width":cell.width, "align": cell.align, "rowSpan":cell.rowSpan, "vAlign":cell.valign, "background":cell.background, "bgColor":cell.bgColor }; columnPropertyList.push(columnPropery); } if(columnPropertyList.length==0) return null; else return columnPropertyList; }catch(err){ err={message:"Error in getColumnPropeties msg:- "+err.message}; throw (err); } }; //TABLE RECONSTRUCTION UTIL FUNCTIONS//////////////////////////////// /** * *constructTable function is used to construct table object from tableStruct and tableData. *Its assumed that the tableData structure conforms to the row column structure of the table. * *@param tableStruct should contain table structure and style information *@param tableData is a 2D array collection of rows and columns obtained from AJAX response. *@return table-HTML (String) */ htmlUtil.tableUtil.constructTable =function (tableStruct,tableData) { try { var wraperObj=document.createElement('div'); var table=document.createElement('table'); table=this.intializeTableProperties(table,tableStruct.tableProperty); if(tableData==null) { $(table).html("<div width='100%' style='VERTICAL-ALIGN: MIDDLE; TEXT-ALIGN: CENTER; FONT-SIZE: 16px; '>" + "No Data Available" + "</div>"); } else { var rowCount = tableData.length; for(var i=0;i<rowCount; i++) { var row = table.insertRow(i); if(i==0 && tableStruct.headerRowProperty!=null)//header row is present { row=this.intializeRowProperties(row,tableStruct.headerRowProperty); this.createDataColumns(row,tableStruct.headerColumnPropertyList,tableData[i]); } else { row=this.intializeRowProperties(row,tableStruct.rowProperty); this.createDataColumns(row,tableStruct.columnPropertyList,tableData[i]); } } } $(wraperObj).html(table); //set table in wraper object return ($(wraperObj).html());//table } catch(err) { alert("Error in ConstructTable method of htmlUtil.tableUtil.js msg= "+err.message); } }; /** * createDataColumns is called from constructTable, The method is used to populate each row based on column property List for that row * and dataList for that row. * @param rowElm - tr (row) element of the table being generated * @param columnPropList - array of ColumnPropery JSON objects for rowElm * @param cellDataList - array of data for rowElm. * @return void * */ htmlUtil.tableUtil.createDataColumns =function (rowElm,columnPropList,cellDataList) { try { if(columnPropList.length!=cellDataList.length) { err={message:"Error in createDataColumns msg:- Datalist and PropList vary in length"}; throw (err); } for(var i=0; i<columnPropList.length; i++) { var cellElm=rowElm.insertCell(i); cellElm= this.intializeColumnProperties(cellElm,columnPropList[i]); $(cellElm).html(cellDataList[i]); } } catch(err) { err={message:"Error in createDataColumns msg:- "+err.message}; throw (err); } }; /** * intializeTableProperties is called from constructTable, * The method is used to populate properties of tableElm form tableProperty Object * @param tableElm <table> -element of the table being generated * @param propObj - tablePropertyObject of tableStructure * @return tableElm <table>- element of table after population. * */ htmlUtil.tableUtil.intializeTableProperties= function (tableElm, propObj) { try { tableElm.setAttribute("id",((propObj.id) ? propObj.id : "") ); tableElm.setAttribute("name",((propObj.name) ? propObj.name : "") ); tableElm.setAttribute("align",((propObj.align) ? propObj.align : "") ); tableElm.setAttribute("background", ((propObj.background) ? propObj.background : "") ); tableElm.setAttribute("bgColor", ((propObj.bgColor) ? propObj.bgColor : "") ); tableElm.setAttribute("border",((propObj.border) ? propObj.border : "") ); // tableElm.setAttribute("caption",propObj.caption); tableElm.setAttribute("cellPadding",((propObj.cellPadding) ? propObj.cellPadding : "") ); tableElm.setAttribute("cellSpacing",((propObj.cellSpacing) ? propObj.cellSpacing : "") ); tableElm.setAttribute("frame",((propObj.frame) ? propObj.frame : "") ); tableElm.setAttribute("height",((propObj.height) ? propObj.height : "") ); tableElm.setAttribute("rules",((propObj.rules) ? propObj.rules : "") ); tableElm.setAttribute("summary",((propObj.summary) ? propObj.summary : "") ); // tableElm.setAttribute("tFoot",propObj.tFoot); // tableElm.setAttribute("tHead",propObj.tHead); tableElm.setAttribute("width",((propObj.width) ? propObj.width : "") ); tableElm.setAttribute("style",((propObj.style) ? propObj.style : "") ); tableElm.setAttribute("className",((propObj.className) ? propObj.className : "") ); } catch(err) { err={message:"Error in intializeTableProperties msg:- "+err.message}; throw (err); } return tableElm; }; /** * intializeRowProperties is called from constructTable, * The method is used to populate properties of row <tr> elements form rowproperty Objects in tableStructure * @param rowElm <tr> -element of the row being generated * @param propObj - rowPropertyObject of tableStructure * @return rowElm <tr>- element of row after population. * */ htmlUtil.tableUtil.intializeRowProperties =function (rowElm, propObj) { try { rowElm.setAttribute("id",((propObj.id) ? propObj.id : "") ); rowElm.setAttribute("name",((propObj.name) ? propObj.name : "") ); rowElm.setAttribute("align",((propObj.align) ? propObj.align : "") ); rowElm.setAttribute("bgColor",((propObj.bgColor) ? propObj.bgColor : "") ); rowElm.setAttribute("ch",((propObj.ch) ? propObj.ch : "") ); rowElm.setAttribute("chOff",((propObj.chOff) ? propObj.chOff : "") ); rowElm.setAttribute("height",((propObj.height) ? propObj.height : "") ); rowElm.setAttribute("propObjIndex",((propObj.propObjIndex) ? propObj.propObjIndex : "") ); rowElm.setAttribute("sectionpropObjIndex", ((propObj.sectionpropObjIndex) ? propObj.sectionpropObjIndex : "") ); rowElm.setAttribute("vAlign",((propObj.vAlign) ? propObj.vAlign : "") ); rowElm.setAttribute("style", ((propObj.style) ? propObj.style : "") ); rowElm.setAttribute("className",((propObj.className) ? propObj.className : "") ); rowElm.setAttribute("width",((propObj.width) ? propObj.width : "") ); rowElm.setAttribute("height",((propObj.height) ? propObj.height : "") ); } catch(err) { err={message:"Error in intializeRowProperties msg:- "+err.message}; throw (err); } return rowElm; }; /** * intializeColumnProperties is called from createDataColumns, * The method is used to populate properties of columns <td> elements form columnProperty Objects in columnPropertyList of tableStructure * @param colElm <td> -element of the column being generated * @param propObj - columnPropertyObject of columnPropertyList of tableStructure * @return colElm <td>- element of column after population. * */ htmlUtil.tableUtil.intializeColumnProperties= function (colElm, propObj) { try { colElm.setAttribute("className", ((propObj.className) ? propObj.className : "")); colElm.setAttribute("style",((propObj.className) ? propObj.classtylesName : "")); colElm.setAttribute("id",((propObj.className) ? propObj.id : "")); colElm.setAttribute("name", ((propObj.className) ? propObj.name : "")); colElm.setAttribute("colSpan",((propObj.className) ? propObj.colSpan : "")); colElm.setAttribute("height", ((propObj.className) ? propObj.height : "") ); colElm.setAttribute("width",((propObj.className) ? propObj.width : "")); colElm.setAttribute("align", ((propObj.className) ? propObj.align : "")); colElm.setAttribute("rowSpan",((propObj.className) ? propObj.rowSpan : "")); colElm.setAttribute("vAlign",((propObj.className) ? propObj.valign : "")); colElm.setAttribute("background",((propObj.className) ? propObj.background : "")); colElm.setAttribute("bgColor",((propObj.className) ? propObj.bgColor : "")); } catch(err) { err={message:"Error in intializeColumnProperties msg:- "+err.message}; throw (err); } return colElm; }; //TABLE MANIPULATION FUNCTIONS////////////////////////////////////////////////////////// /** *The manipulateData function is used to format the tableData array obtained from the JSON object returned during AJAX call. *This is done by passing a local js function as parameter to this method. The local js function would be defined in the respective js file. *This is used in case where anchor tag <a href> is added to make one column a hyperlink or dropdown etc.. such format of raw data *obtained from server should be put in a function in local js file. * *This function is often used after AJAX call and before table reconstruction call. * *@param tableData Array<Array<String>> note.. for dropdown String would be opt1~opt2~ (this needs to be formating function defined in your page) *@param manipulatingFunctions= Array<Functtion> if headerFlag=true size of this array =2 i.e. 1st entry to header formating function * and 2nd for data formatingfunctions. * note: formatingfunctions are user defined local to page they are designing. * They will have 2 params (rowIndex and array of columnData for that row) *@headerFlag boolean - true if tableData has header(assumed as the first index) else false. *@returns - modified/Formated tableData */ htmlUtil.tableUtil.manipulateData= function (tableData,manipulatingFunctions,headerFlag) { try{ if(tableData==null &&manipulatingFunctions!=null) { return tableData;// No manipulation when server returns no records } else if(tableData!=null && manipulatingFunctions ==null) { var err={message:" Input manipulatingFunctions argument is null"}; throw (err); } if(headerFlag && manipulatingFunctions.length!=2) { var err={message:" Input argument manipulatingFunctions does not defind either header or column values"}; throw (err); } var rowCount = tableData.length; for(var i=0,j=0;i<rowCount; i++) { tableData[i]=this.formatData(i,tableData[i],manipulatingFunctions[j]); if(headerFlag && i==0) j++; } return tableData; }catch (err) { alert("Error in manipulateData before Table Construction in AJAX response err msg- "+err.message); } }; /** * formatData method is called from manipulateData method in iteration for each row for the tableData. * This method is used to call the respective formatingFunction (locally defined in js) on each row of table. * @param rowIndex - index for row element. * @param rowData - array of column data for the respective row. * @param formatColumns - (override function locally defined to manipulate columns of row element.) * @return formated rowData (ColumnDataList for that row) */ htmlUtil.tableUtil.formatData= function (rowIndex,rowData,formatColumns) { try{ if(!rowData) { var err={message:" Input arguments are null"}; throw (err); } if(!formatColumns) return rowData; else return(formatColumns(rowIndex,rowData)); // this methos had to be declared in the local js class. }catch(err) { err={message:" Error in formatData function call err msg- "+err.message}; throw (err); } }; htmlUtil.tableUtil.storeTabelValinBuffer = function (rowElm,index,masterRowDataBuffer) { try{ var rowObj=""+index; for(var i=0; i<rowElm.length; i++) { rowObj+="#"+$(rowElm[i]).val(); } masterRowDataBuffer.push(rowObj); } catch(err) { alert("Error in htmlUtil storeTabelValinBuffer method err Msg-"+err.message); } }; htmlUtil.tableUtil.retriveTableValinBuffer = function (rowElm,index,masterRowDataBuffer) { try{ for(var i=0; i<masterRowDataBuffer.length; i++) { var rowObj=masterRowDataBuffer[i].split("#"); if(rowObj[0]==index) { for(var k=0; k<rowElm.length; k++) { $(rowElm[k]).val(rowObj[k+1]); } masterRowDataBuffer.splice(i,1); } } } catch(err) { alert("Error in htmlUtil retriveTableValinBuffer method err Msg-"+err.message); } }; //***************************************************************************************************************************************** //***********************************************JSON OBJECT TO HTML GENERATION FUNCTIONS************************************************** htmlUtil.jsonUtil={}; //HTML GENERATING FUNCTIONS////////////////////// /** * CONSTANTS USED IN LINE WITH JSONConstants.java to identiy IJSONOBJECT are declared below */ var JSON_OBJECT_DROP_DOWN_ELEMENT="dropDownElement"; var JSON_OBJECT_PARAMETERS_ELEMENT="parametersBean"; /** * constructHTML method is the interface that is used to call the respective html generating based on type of JSON Object. * eg. constructDropDown is invoked for JSON object with name 'dropDownElement'. * @param dataObj - JSON DataObject follows IJSON format. * @return string -(HTML output of the dataObject) */ htmlUtil.jsonUtil.constructHTML= function (dataObj) { try{ if(dataObj==null) { var err={message:" Input arguments are null"}; throw (err); } if(dataObj.name==JSON_OBJECT_DROP_DOWN_ELEMENT) return this.constructDropDown(dataObj); }catch(err) { alert("Error in ConstructHTML function of htmlUtil.jsonUtil err msg- "+err.message); } }; /** * constructDropDown method is called from constructHTML method. * This method is used to construct HTML for dropdown element based on JSONObject data. * @param dataObj - JSON DataObject- dropDownElement. * @return string -(HTML output of the dropDown) */ htmlUtil.jsonUtil.constructDropDown=function (dataObj) { var outputHTML=""; try{ var options = dataObj.options; var selectedIndex= dataObj.selectedIndex; if(options==null || selectedIndex==null) { var err={message:" Input arguments are null"}; throw (err); } for(var i=0; i< options.length; i++) { if(selectedIndex==i) { outputHTML+="<option value=\""+options[i].optionValue+"\" selected=\""+selectedIndex+"\">"; } else { outputHTML+="<option value=\""+options[i].optionValue+"\">"; } outputHTML+=options[i].optionText; outputHTML+="</option>"; } return outputHTML; }catch(err) { err={message:" Error in constructDropdown method err msg:- "+err.message}; throw (err); } }; /** * Recursive function added to convert jsonObj to string representation * @param jsonObj * @return */ htmlUtil.jsonUtil.getJsonStringRepresentation= function (jsonObj) { try { if(typeof jsonObj==="object") { var i=0; var output="{"; for(var param in jsonObj) { if(i!=0) output+=", "; output+="\""+param+"\""; output+=":"; output+=this.getJsonStringRepresentation(jsonObj[param]); i++; } output+="}"; return output; } else { if(typeof jsonObj==="string") jsonObj="\""+jsonObj+"\""; return jsonObj; } }catch(err) { err={message:" Error in constructDropdown method err msg:- "+err.message}; throw (err); } }; //HTML MODIFYING FUNCTIONS/////////////////////////////// /** * modifyHTML method is the interface that is used to call the respective html modifying functions based on type of JSON Object. * Note: here HTML is not generated. There is not return of HTML string. Only Existing HTML is modified. * eg. intializeParam is invoked for JSON object with name 'parametersBean'. * @param dataObj - JSON DataObject follows IJSON format. * @return void */ htmlUtil.jsonUtil.modifyHTML= function (dataObj) { try{ if(dataObj==null) { var err={message:" Input arguments are null"}; throw (err); } if(dataObj.name==JSON_OBJECT_PARAMETERS_ELEMENT) this.initializeParam(dataObj); }catch(err) { alert("Error in modifyHTML function of htmlUtil.jsonUtil err msg- "+err.message); } }; /** * intializeParam method is used to initialize HTML input tags with value specified by dataobject. * @param dataObj - JSON DataObject- parametersBean. * @return void */ htmlUtil.jsonUtil.initializeParam= function (paramObj) { try{ if((paramObj.name).trim()!="parametersBean") { var err={message:"Argument not a parametersBean"}; throw (err); } var parameters = paramObj.parameters; for(var i=0; i<parameters.length;i++) { var param = parameters[i]; document.getElementById(param.paramName).value=param.paramValue; } }catch(err) { err={message:" Error in intializeParam method err msg:- "+err.message}; throw (err); } }; //***************************************************************************************************************************************** ////////////////////////////////////////VALIDATIONS////////////////////////////////////////////// htmlUtil.validator={}; htmlUtil.validator.isUnique=function (value,list,elmn) { try { if(!value) { return true; } if(!list) { return true; } if(list.length==0) { return true; } for(var i=0; i<list.length;i++) { if(value==list[i]) { if(elmn) htmlUtil.prompt.error({elm:elmn,msg:"*Entry must be unique!"}); return false; } } return true; }catch(err) { alert("Error in htmlUtil.validator.isUnique method err Msg-"+err.message); return false; } }; htmlUtil.validator.isAlphaNumeric=function (value,elmn) { try { if(!value) { return true; } var specialChars = "%<>^#~*+=\\[]:;\"&@$|?"; //note ,(){}-_'./ are treated as part of alpha numeric for(var i=0; i<specialChars.length;i++) { var specialChar=specialChars.charAt(i); if(value.indexOf(specialChar)!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* Only Alphanumeric Charecters Allowed"}); return false; } } return true; }catch(err) { alert("Error in htmlUtil.validator.isAlphaNumeric method err Msg-"+err.message); return false; } }; htmlUtil.validator.isJgridReserverCharecters= function (value,elmn) { try { if(!value) { return true; } var specialChars = "~#:"; for(var i=0; i<specialChars.length;i++) { var specialChar=specialChars.charAt(i); if(value.indexOf(specialChar)!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* The Charecters ~#: are not Allowed"}); return false; } } if(value.indexOf("INSERT:")!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* The Charecters ~#: are not Allowed"}); return false; } if(value.indexOf("UPDATE:")!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* The Charecters ~#: are not Allowed"}); return false; } if(value.indexOf("DELETE:")!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* The Charecters ~#: are not Allowed"}); return false; } return true; }catch(err) { alert("Error in jgridUtil.isJgridReserverCharecters method err Msg-"+err.message); return false; } }; htmlUtil.validator.isNonSpecialCharecter= function (value,specialChars,elmn) { try { if(!value) { return true; } if(!specialChars) specialChars = "%<>^#~*+=\\[]:;\"&@$|?"; for(var i=0; i<specialChars.length;i++) { var specialChar=specialChars.charAt(i); if(value.indexOf(specialChar)!=-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"Special Charecters are not Allowed"}); return false; } } return true; }catch(err) { alert("Error in htmlUtil.validator.isNonSpecialCharecter method err Msg-"+err.message); return false; } }; htmlUtil.validator.isNumeric= function (value,elmn) { try { if(!value) { return true; } var validChars = "0123456789."; for(var i=0; i<value.length;i++) { var inputChars=value.charAt(i); if(validChars.indexOf(inputChars)==-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* Only Numeric Charecters are Allowed"}); return false; } } return true; }catch(err) { alert("Error in htmlUtil.validator.isNumeric method err Msg-"+err.message); return false; } }; htmlUtil.validator.isAlphabets= function (value,elmn) { try { if(!value) { return true; } value=value.toUpperCase();// case insesntive var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";//note ,(){}-_'./ are treated as part of alphabets for(var i=0; i<value.length;i++) { var inputChars=value.charAt(i); if(validChars.indexOf(inputChars)==-1) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* Only Alphabet Charecters are Allowed"}); return false; } } return true; }catch(err) { alert("Error in htmlUtil.validator.isNumeric method err Msg-"+err.message); return false; } }; htmlUtil.validator.isMandatory= function (value,elmn) { try { if(!value) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* Mandatory Field"}); return false; } if(value.trim().length==0) { if(elmn) htmlUtil.prompt.error({elm:elmn, msg:"* Mandatory Field"}); return false; } return true; }catch(err) { alert("Error in htmlUtil.validator.isMandatory method err Msg-"+err.message); return false; } }; //****************************************************************************************************************************************** //**************************************************VALIDATION PROMPT FUNTION*********************************************************** htmlUtil.prompt={}; /** * The below functions are used in construction of prompt used to display error message during inine form element validation. * The 2 base functions buildPrompt and calculatePosition was taken from jquery-validatorEngine plugin free source code * and modified according to RAD application requirement. * */ /** * buildPrompt method is the base function which construct the html prompt div.Used in inline form validation * Every prompt is associated to its caller element- using element Name and id in absence of name. * Prompt is built near the element on which this method is called. * Prompt can be closed by user by clicking on it. * Unlike alert- prompt can also be closed by invoking close functions for this prompt. * Note: this method will throw error if the html element invoking it does not have a name attribute defined. * @param caller - DOM element of the calling HTML element. Prompt is invoked for this element (Can be textbox/ dropdown etc.. ) * @param promptText - Message to be indicated on the Prompt. * @param showTriangle- boolean to determine if the the arrow pointer shown along with the prompt is needed or not. Some cases as * check boxes and radio, dispalying arrow on prompt may be inappropriate. * @param promptPosition- 4 set of predefined values (bottomLeft,bottomRight,topLeft,topRight) used to determine where to place the prompt * @param adjustmentFactor - added to overcome defect of this framework. It does not position correctly in case of nested elements * like <table><tr><td><input> here input position is mis-calculated. * */ htmlUtil.prompt.buildPrompt= function (caller,promptText,showTriangle,promptPosition,adjustmentFactor,autoClose,type) { //PROMPT BOX CONSTRUCTION var divFormError = document.createElement('div'); var formErrorContent = document.createElement('div'); $(divFormError).addClass("errorDiv"); try { //note: Caller Element must have name or Id- name is given the higher precedence in case both exist //Above point is needed for this code to work as based on Name/ID we can identify the prompt and close it if(caller) { var promptId=null; if(caller.id) promptId=caller.id; else if(caller.name) promptId=caller.name; else if($(caller).attr("id")) promptId=$(caller).attr("id"); else { var err={message:" Caller element does not have name or id attribute "}; throw (err); } //jgrid case - require rowid to be unique in page - may have problems when there are more than one grids if(promptId.split("_").length==2){ $(divFormError).addClass(promptId.split("_")[0]+"_errorDiv");//identifier } $(divFormError).addClass(promptId+"errorDiv");//identifier } $(formErrorContent).addClass("errorDivContent");//prompt styling /* * Added to style according to type.. by default error= red, warn - yellow and notification- grey */ $(formErrorContent).addClass(type); /* The below change was done to fix the position issue in case of nested input elements.. The fix needs to be tested. */ //$(caller).before(divFormError);//prompt positioning $('body').append(divFormError);// prompt div is with respect to body div- helps in clean position $(divFormError).append(formErrorContent);// prompt content //PROMPT ARROW POINTER CONSTRUCTION if(showTriangle)//Arrow pinter used to point the prompt box to the error element { var arrow = document.createElement('div'); $(arrow).addClass("errorDivArrow"); $(arrow).addClass(type+"Arrow"); if(promptPosition == "bottomLeft" || promptPosition == "bottomRight") { $(formErrorContent).before(arrow); $(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); } else if(promptPosition == "topLeft" || promptPosition == "topRight") { $(divFormError).append(arrow); $(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); } } $(formErrorContent).html(promptText); //PROMPT POSITIONING if(caller) { var calculatedPosition = this.calculatePosition(caller,promptText,divFormError,promptPosition,adjustmentFactor); calculatedPosition.callerTopPosition +="px"; calculatedPosition.callerleftPosition +="px"; calculatedPosition.marginTopSize +="px"; $(divFormError).css({ "top":calculatedPosition.callerTopPosition, "left":calculatedPosition.callerleftPosition, "marginTop":calculatedPosition.marginTopSize, "opacity":0 }); }else { $(formErrorContent).removeClass("errorDivContent");//change prompt styling $(formErrorContent).removeClass(type);//css renders based on left to right order hence type is placed at extreem right to override errorDivContent-2 $(formErrorContent).addClass("errorDivContent-2");//prompt styling $(formErrorContent).addClass(type);//change prompt styling $(divFormError).css({ "top": (($(document).height()/2)-100)+"px", "left": (($(document).width()/2)-200)+"px", "marginTop":"0px", "opacity":0 }); } //PROMPT CLOSES ON CLICK $(formErrorContent).click(function(){ $(divFormError).remove(); }); //PROMPT AUTO CLOSE AFTER 10SEC if(autoClose) setTimeout(function() {$(divFormError).remove(); divFormError=null;}, 5000); //PROMPT DISPLAY- ANIMATION - fadeIn effect $(divFormError).animate({"opacity":0.87},'fast',function(){return true;}); }catch(err) { alert("Error in htmlUtil.prompt.buildPrompt method err msg: "+err.message); } }; /** * calculate position method is the called form buildPrompt function which construct the html prompt div. * This mehtod calculates the position of the promptDiv with respect to input parmaeters * @param caller - DOM element of the calling HTML element. Prompt is invoked for this element (Can be textbox/ dropdown etc.. ) * @param promptText - Message to be indicated on the Prompt. * @param divFormError- div element of the prompt. * @param promptPosition- 4 set of predefined values (bottomLeft,bottomRight,topLeft,topRight) used to determine where to place the prompt * @param adjustmentFactor - added to overcome defect of this framework. It does not position correctly in case of nested elements * like <table><tr><td><input> here input position is mis-calculated. * */ htmlUtil.prompt.calculatePosition= function (caller,promptText,divFormError,promptPosition,adjustmentFactor){ try { callerTopPosition = $(caller).offset().top; callerleftPosition = $(caller).offset().left; callerWidth = $(caller).width(); inputHeight = $(divFormError).height(); var marginTopSize = 0; if(adjustmentFactor) { callerTopPosition+=adjustmentFactor.top; callerleftPosition+=adjustmentFactor.left; } /* POSITIONNING */ if(promptPosition == "topRight") { callerleftPosition += callerWidth -30; callerTopPosition -= inputHeight; } else if(promptPosition == "topLeft") { callerTopPosition -=inputHeight; } else if(promptPosition == "bottomLeft") { callerHeight = $(caller).height(); callerTopPosition += callerHeight+5; } else if(promptPosition == "bottomRight") { callerHeight = $(caller).height(); callerleftPosition += callerWidth -30; callerTopPosition += callerHeight+5; } return { "callerTopPosition":callerTopPosition, "callerleftPosition":callerleftPosition, "marginTopSize":marginTopSize }; }catch(err) { err={message:" Error in htmlUtil.prompt.calculatePosition method err msg:- "+err.message}; throw (err); } }; /** * htmlAlert method is the wrapper method for buildPrompt, This is used from the local js files. * All prompts can be closed by clicking on them * Overloading options * 1 argument - message - * constructs a alert prompt box at center of the screen with the given message. (Box Dimension are configurable in htmlUtil.css- erroDivContent-2 * 2 arguments- DOMelement, message - * constructs a alert prompt box with the message, pointerArrow and position relative to top left position of the DOM element. * 3 arguments - DOMElement,message,boxRelativePosition - * constructs a alert prompt box with the message, pointerArrow and position relative to the DOM element based on boxRelativePosition * 4 arguments - DOMElement,message,boxRelativePosition,adjustmentFactor - * same as 3 argument functionality and here the position is offset based on the top,left attributes of adjustmentFactor JSON object * 5 arguments - DOMElement,message,boxRelativePosition,adjustmentFactor,showPointerFlag * same as 3 argument functionality and here the showPointerFlag is a boolean to indicate the need for pointer arrow. * @param elm - DOM element of the calling HTML element. Prompt is invoked for this element (Can be textbox/ dropdown etc.. ) * @param message - Message to be indicated on the Prompt. * @param position - String value can be 'topLeft,topRight,bottomLeft,bottomRight - by default = topLeft * @param adjustmentFactor - added to override position from calculated position. - adjustmentFactor = json with top, width attributes. * @param showPointer - by default true - can be set to false */ htmlUtil.prompt.htmlAlert=function (alertType,jsonArg) { var type=(alertType)?alertType:"error"; var elm=jsonArg.elm; var message=jsonArg.msg; var position=(jsonArg.pstn)?jsonArg.pstn:(elm)?"topLeft":"center"; var adjustmentFactor=jsonArg.adjFactor; var showPointer=(jsonArg.showPointer)?jsonArg.showPointer:true; var autoClose=(jsonArg.autoClose)?jsonArg.autoClose:true; /*if(arguments.length==2) { message=arguments[1]; position="center"; showPointer=false; } if(arguments.length==3) { elm=arguments[1]; message=arguments[2]; } if(arguments.length==4) { elm=arguments[1]; message=arguments[2]; position=arguments[3]; } if(arguments.length==5) { elm=arguments[1]; message=arguments[2]; position=arguments[3]; adjustmentFactor=arguments[4]; } if(arguments.length==6) { elm=arguments[1]; message=arguments[2]; position=arguments[3]; adjustmentFactor=arguments[4]; showPointer=arguments[5]; } if(!position) position="topLeft";*/ this.buildPrompt (elm,message,showPointer,position,adjustmentFactor,autoClose,type); }; htmlUtil.prompt.error=function(jsonArg) { this.htmlAlert("error",jsonArg); }; htmlUtil.prompt.warn=function(jsonArg) { this.htmlAlert("warn",jsonArg); }; htmlUtil.prompt.notify=function(jsonArg) { this.htmlAlert("notify",jsonArg);; }; /** * closePrompt method is used to remove the promptElm. *@param promptElm - DOM element of the PromptDIV. */ htmlUtil.prompt.closePrompt= function(promptElm) { try { $(promptElm).remove(); }catch(err) { alert("Error in removing element in htmlUtil.prompt.closePrompt err msg "+err.message); } }; /** * Wrapper method for closePrompt, this is used to remove the promptElms associated with the concerned htmlElement * @param fieldElm/fieldElm[] - DOM element of the calling HTML element. Prompt is invoked for this element (Can be textbox/ dropdown etc.. ) */ htmlUtil.prompt.closeHtmlAlert= function(fieldElm) { try { if(!fieldElm.length) { var tempArray=new Array(); tempArray.push(fieldElm); fieldElm=tempArray; } for(var k=0;k<fieldElm.length;k++) { var promptId=null; if(fieldElm[k].id) promptId=fieldElm[k].id; else if(fieldElm[k].name) promptId=fieldElm[k].name; else if($(fieldElm).attr("id")) promptId=$(fieldElm).attr("id"); else { var err={message:" Caller element does not have name or id attribute "}; throw (err); } var promptElms = $("."+promptId+"errorDiv"); if(promptElms) { for(var i=0; i<promptElms.length;i++) { this.closePrompt(promptElms[i]); } } } }catch(err) { alert("Error in htmlUtil.prompt.closeHtmlAlert err msg "+err.message); } }; /** *Utility method. This is used to remove all the promptElms in a jsp page. */ htmlUtil.prompt.closeAllHtmlAlert= function () { try { var promptElms = $(".errorDiv");//all promts use this class. note.. not other element is expected to use this class if(promptElms) { for(var i=0; i<promptElms.length;i++) { this.closePrompt(promptElms[i]); } } }catch(err) { alert("Error in htmlUtil.prompt.closeHtmlAlert err msg "+err.message); } }; /** *Utility method. This is used to by jgridUil to close all the promptElms in specific to grid page. */ htmlUtil.prompt.closeHtmlAlertInGrid= function (tableId) { try { var promptElms = $("."+tableId+"_errorDiv");//all promts use this class. note.. not other element is expected to use this class if(promptElms) { for(var i=0; i<promptElms.length;i++) { this.closePrompt(promptElms[i]); } } }catch(err) { alert("Error in htmlUtil.prompt.closeHtmlAlert err msg "+err.message); } }; /** *Utility method. This is used to by jgridUil to close all the promptElms in specific to grid for a specific row. */ htmlUtil.prompt.closeHtmlAlertInGridForRow= function (rowId) { try { var promptElms = $("."+rowId+"_errorDiv");//all promts use this class. note.. not other element is expected to use this class if(promptElms) { for(var i=0; i<promptElms.length;i++) { this.closePrompt(promptElms[i]); } } }catch(err) { alert("Error in htmlUtil.prompt.closeHtmlAlertInGridForRow err msg "+err.message); } }; //***************************************************************************************************************************************** //*************************************MODAL AND SUBWINDOW UTILS************************************************************************** //************* Needs common.jsp with variable modalFrameReturnData*********************************************************************************************************** htmlUtil.popUp={}; htmlUtil.popUp.openSubWindow= function(url,width,height) { $.colorbox( { href:url, width:width, height:height, overlayClose:false, iframe:true }); if(sessionControl) sessionControl.resetSessionCount(); }; htmlUtil.popUp.openModalWindow= function(url,width,height,returnHandler) { $.colorbox( { href:url, width:width, height:height, overlayClose:false, // escKey:false, onClosed:function(){htmlUtil.popUp.processReturnData(returnHandler)}, iframe:true }); $("#cboxClose").hide(); if(sessionControl) { sessionControl.resetSessionCount(); } }; htmlUtil.popUp.processReturnData=function(returnFunction) { try { //read Data from modalFrameReturnData variable in common.jsp var data =$("#modalFrameReturnData").val(); // clear data for modalFrameReturnData variable in common.jsp $("#modalFrameReturnData").val(""); // call local returnFunction with this data as argument returnFunction(data); }catch(err) { htmlUtil.prompt.error({msg:"Error in htmlUtil.popUp.processReturnData in htmlUtil.js msg: "+err.message}); } }; htmlUtil.popUp.sendReturnDataAndClose=function(data) { try { var body$=parent.$; if(body$) { //write Data to modalFrameReturnData variable in common.jsp body$("#modalFrameReturnData").val(data); //close popUp window body$.colorbox.close(); } }catch(err) { htmlUtil.prompt.error({msg:"Error in htmlUtil.popUp.sendReturnData in htmlUtil.js msg: "+err.message}); } }; htmlUtil.popUp.close= function() { try { var body$=parent.$; if(body$) { //close popUp window body$.colorbox.close(); } }catch(err) { htmlUtil.prompt.error({msg:"Error in htmlUtil.popUp.close in htmlUtil.js msg: "+err.message}); } }; //*****************************************************************************************************************************************
c309d70cb2eb05bf0e16ce14019ebc22be02ae78
[ "JavaScript", "Markdown" ]
17
JavaScript
gokulvanan/JSUtils
88cb26314bf4e0a0e3f040404f2eb911d48e7bea
9b5dada3c8754326624c74e2de251c314b0bc5ad
refs/heads/master
<repo_name>charlesmurphy1/thresholdmodel<file_sep>/sandbox/example.py import numpy as np import networkx as nx import matplotlib.pyplot as plt from thresholdmodel import ThreshModel N = 1000 k = 10 thresholds = 0.1 initially_infected = np.arange(100) G = nx.fast_gnp_random_graph(N, k/(N-1.0)) Thresh = ThreshModel(G,initially_infected,thresholds) t, a = Thresh.simulate() plt.plot(t,a) plt.ylim([0,1]) plt.xlabel('time $[1/\gamma]$') plt.ylabel('cascade size ratio') plt.gcf().savefig('cascade_trajectory.png') plt.show()
95e5544f53ee31f351895c28ce0cca49f9a3586c
[ "Python" ]
1
Python
charlesmurphy1/thresholdmodel
c2f0c9082df0252845ab8fb5b1e28a58cce4dd4a
4e428b75ce40a087cafbc296abdf36ab5d1ad9f6
refs/heads/master
<repo_name>kleopatra999/facebook-cli<file_sep>/README.md Facebook CLI ============ Yahoo! hackathon project by <NAME>, <NAME>, and <NAME>. Control your Facebook page using commands in any input box. Command history is supported. We hope to have autocomplete in a future version. Not all of the following commands are implemented yet. To use a command type it into any input box other than the Graph Search box and hit `shift+enter` instead of `enter`. Certain commands will only work in a chat box, since and you can see these commands below. Chat Box Commands ------------------ min - Minimize chat window exit - Exit chat box whoami - Get your username ssh - Go to the profile of the user you're chatting with Global Commands --------------- post [status] - Post status chat [name] - Open a chat box with the specified user cd - Open your profile cd ~ - Open your profile cd about - Go to your about page cd photos - Go to your photos cd friends - Go to your friends cd following - Go to your followers cd news - Go to the newsfeed ssh <user>/~ - Open a user's profile ssh <user>/about - Open a user's about page ssh <user>/photos - Open a user's photos ssh <user>/friends - Open a user's friends ssh <user>/following - Open a user's followers grep - Perform a search <file_sep>/content.js var token = ""; var KEY_CODE_UP = 38; var KEY_CODE_DOWN = 40; var KEY_CODE_ENTER = 13; var HISTORY_SIZE = 15; // Listen for FB API auth token chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { token = request.token; console.log(token); }); $(document).ready(function() { console.log("Document ready"); var index = 0; var history = loadHistory(); var commandsInHistory = history.length; // Hijack all textareas $(document).on("keyup", "textarea", function(e) { if (e.keyCode == KEY_CODE_ENTER && e.shiftKey) { var input = this.value.trim(); // Execute the command parse(this, input, this.className); /* * Add the command to the beginning of the history, and add a new * blank command to the history. */ history[0] = input; history.unshift(""); /* * If we have reached the max history size, pop the last command * from the history. Otherwise, increase the commandsInHistory count * by one. */ if (history.length > HISTORY_SIZE) { history.pop(); } else { commandsInHistory++; } // Set the history to the first command index = 0; // Remove the command from the input box this.value = ""; } else if (e.keyCode == KEY_CODE_UP) { if ((index < commandsInHistory) && (index < HISTORY_SIZE - 1)) { index++; } // Set the value of the input box to the current history entry if (history[index] === undefined) { this.value = ""; } else { this.value = history[index]; } } else if (e.keyCode == KEY_CODE_DOWN) { if (index > 0) { index--; } // Set the value of the input box to the current history entry this.value = history[index]; } else { /* * The user is typing, so set the first history entry to the * command they're typing. */ index = 0; history[0] = this.value.trim(); } storeHistory(history); }); }); function loadHistory() { if (sessionStorage.history === undefined) { var history = new Array(); history[0] = ""; return history; } else { var history = sessionStorage.history; history = JSON.parse(history); return history; } } function storeHistory(history) { history = JSON.stringify(history); sessionStorage.history = history; } /** * Parses a command * @param {Element} elem The DOM element the command was typed into * @param {String} command The full command that was typed * @param {String} className The classname of the DOM object */ function parse(elem, command, className) { var firstSpace = command.indexOf(" "); if (firstSpace != -1) { var commandName = command.substr(0, firstSpace); var args = command.substr(firstSpace + 1); } else { var commandName = command; var args = ""; } console.log(commandName); console.log(args); executeCommand(elem, commandName, args, className); } /** * Executes a command * @param {Element} elem The DOM element that took in the input * @param {String} commandName The command name * @param {String} args The full command that was typed without the * command name * @param {String} className The classname of the DOM object * @return {Object} The command object */ function executeCommand(elem, commandName, args, className) { if (isChatBox(className)) { switch (commandName) { case "min": minimizeChat(elem, args); return; case "exit": exitChat(elem, args); return; case "ssh": ssh(elem, args); return; case "whoami": whoAmI(elem, args); return; } } switch (commandName) { case "post": post(elem, args); break; case "chat": chat(elem, args); break; case "cd": cd(elem, args); break; case "grep": grep(elem, args); break; default: // TODO Alert if no chat window printToTerminal("Command not found"); } } /** * Tells whether a command was typed in a chat box by looking at the className * @param {String} className The classname of the DOM object * @return {Boolean} True if the DOM object is a chat box */ function isChatBox(className) { return true; } /** * Prints a message to the chat window * @param {String} message The message to print */ function printToTerminal(message) { var match = $(".conversation"); var $add = '<div class="mhs mbs pts fbChatConvItem _50dw clearfix small _50kd"><div class="_50ke"><div class="_50x5"></div></div><div class="messages"><div class="metaInfoContainer fss fcg"><span class="hidden_elem"><a href="#" rel="dialog" role="button"><span class="fcg">Report</span></a> · </span><span class="timestamp"></span></div><div class="_kso fsm direction_ltr _55r0" data-jsid="message" style="max-width: 188px;"><span data-measureme="1"><span id = "customMessage"></span></span></div></div></div>' match.append($add); $("#customMessage").append(message) $("#customMessage").attr("id", "oldMessage"); $('.fbNubFlyoutBody.scrollable').scrollTop(100000); } /************************* Commands *************************/ function minimizeChat(elem, args) { var closest = $(elem).closest('.fbNub'); closest.removeClass('opened focusedTab'); } function exitChat(elem, args) { $('.close.button')[0].click(); } function ssh(elem, args) { // TODO } function cd(elem, args) { var directory = args.split(" ")[0]; if (directory == "news") { window.location.href = "https://www.facebook.com/"; return; } var ext = ""; if (directory != "~") { ext = "/"+directory; } var url = $("#pageNav > #navTimeline > a").attr("href"); var split_url = url.split('/'); var user_id = split_url[3]; var redirect_url = "https://www.facebook.com/" + user_id + ext; window.location.href = redirect_url; } function whoAmI(elem, args) { var url = $("#pageNav > #navTimeline > a").attr("href"); var split_url = url.split('/'); var user_id = split_url[3]; var match = $(".conversation"); var $add = '<div class="mhs mbs pts fbChatConvItem _50dw clearfix small _50kd"><div class="_50ke"><div class="_50x5"></div></div><div class="messages"><div class="metaInfoContainer fss fcg"><span class="hidden_elem"><a href="#" rel="dialog" role="button"><span class="fcg">Report</span></a> · </span><span class="timestamp"></span></div><div class="_kso fsm direction_ltr _55r0" data-jsid="message" style="max-width: 188px;"><span data-measureme="1"><span id = "whoyouare"></span></span></div></div></div>' match.append($add); $("#whoyouare").append(user_id); $("#whoyouare").attr("id", "old"); $('.fbNubFlyoutBody.scrollable').scrollTop(100000); } function post(elem, args) { status = args; var url = "https://graph.facebook.com/me/feed?message=" + status; $.ajax( { type: 'POST', url: url, data: {access_token: token}, success: function (data) { console.log("success:"); console.log(data); }, error: function (data) { console.log("error"); } }); } function chat(elem, args) { args = args.split(" "); firstname = args[0]; lastname = args[1]; var username = firstname + " " + lastname; var elem = $(".-cx-PRIVATE-fbChatOrderedList__name:contains('"+username+"')"); if (elem.length == 0) { printToTerminal("This user is offline"); } else { elem.parent().parent().parent().parent().click(); } } function grep(elem, args) { // TODO }
11073db38cb090146da19045d8cbd655bcb5a6b6
[ "Markdown", "JavaScript" ]
2
Markdown
kleopatra999/facebook-cli
9afd484ae75d3251f56adeabdb14ede385e7fdd3
845c1276e7c4d3812f2ba01547b20607d7158a9a
refs/heads/master
<repo_name>maxlath/blue-cot<file_sep>/lib/get_session_cookie.js const request = require('./request') let sessionCookieRequests = 0 module.exports = async config => { const { host, username, password, debug, agent } = config if (debug) { console.log('session cookie requests', ++sessionCookieRequests) } const res = await request(`${host}/_session`, { method: 'post', headers: { 'content-type': 'application/json', // Required by old CouchDB (ex: v1.6.1) Authorization: `Basic ${getBasicCredentials(username, password)}` }, agent, body: JSON.stringify({ name: username, password }) }) if (res.status >= 400) { const { error, reason } = await res.json() if (error === 'unauthorized') throw new Error('unauthorized: invalid or missing credentials') else throw new Error(`${error}: ${reason}`) } else { return res.headers.get('set-cookie') } } const getBasicCredentials = (username, password) => { return Buffer.from(`${username}:${password}`).toString('base64') } <file_sep>/lib/couch_helpers.js module.exports = { mapDoc: res => res.rows.map(row => row.doc), firstDoc: docs => docs && docs[0] } <file_sep>/lib/view_functions.js const { mapDoc, firstDoc } = require('./couch_helpers') const errors_ = require('./errors') const { validateString, validatePlainObject, validateArray, validateNonNull } = require('./utils') module.exports = (API, designDocName) => ({ viewCustom: async function (viewName, query) { validateString(viewName, 'view name') validatePlainObject(query, 'query') return API.view(designDocName, viewName, query) // Assumes the view uses include_docs: true // to do without it, just use API.view) .then(mapDoc) }, viewByKeysCustom: async function (viewName, keys, query) { validateString(viewName, 'view name') validateArray(keys, 'keys') validatePlainObject(query, 'query') return API.viewKeys(designDocName, viewName, keys, query) .then(mapDoc) }, viewByKey: async function (viewName, key) { validateString(viewName, 'view name') validateNonNull(key, 'key') return API.viewCustom(viewName, { key, include_docs: true }) }, viewFindOneByKey: async function (viewName, key) { validateString(viewName, 'view name') validateNonNull(key, 'key') return API.viewCustom(viewName, { key, include_docs: true, limit: 1 }) .then(firstDoc) .then(function (doc) { if (doc) { return doc } else { throw errors_.new('Not Found', 404, [ viewName, key ]) } }) }, viewByKeys: async function (viewName, keys) { validateString(viewName, 'view name') validateArray(keys, 'keys') return API.viewByKeysCustom(viewName, keys, { include_docs: true }) } }) <file_sep>/lib/json_request.js const request = require('./request') const getSessionCookie = require('./get_session_cookie') module.exports = config => { const { host, debug, agent } = config // Headers are shared between requests, so that session cookies // are re-requested only when needed const headers = { accept: 'application/json', host: config.hostHeader } return async (method, path, body) => { const url = `${host}${path}` const params = { method, headers, agent, attempt: 1 } if (debug) params.start = Date.now() if (body != null) { headers['content-type'] = 'application/json' params.body = JSON.stringify(body) } return tryRequest(url, params, config) } } const tryRequest = async (url, params, config) => { const res = await request(url, params) return handleResponse(res, url, params, config) } const handleResponse = async (res, url, params, config) => { res.data = await res.json() res.statusCode = res.status if (config.debug) logRequest(url, params, res) if (res.status < 400) { return res } else if (res.status === 401 && params.attempt < 3) { params.attempt++ params.headers.cookie = await getSessionCookie(config) return tryRequest(url, params, config) } else { throw requestError(res, url, params) } } const requestError = (res, url, params) => { const { status, data: body } = res const { error, reason } = body const err = new Error(`${error}: ${reason}`) const { method, attempt } = params // Do not include full params object in context // as that would params.agent stringification would fail due to circular reference // Do not include headers to avoid leaking authentification data err.context = { method, url, body, status, attempt } err.stack += `\nContext: ${JSON.stringify(err.context)}` err.statusCode = err.status = status err.body = body return err } const logRequest = (url, params, res) => { const { body, start } = params const elapsedTime = Date.now() - start const bodyStr = body ? `${body} ` : '' console.log(`[blue-cot] ${params.method} ${url} ${bodyStr}- ${res.statusCode} - ${elapsedTime} ms`) } <file_sep>/lib/errors.js const formatError = function (message, statusCode, context) { const err = new Error(message) if (statusCode) err.statusCode = statusCode if (context) err.context = context return err } const buildFromRes = function (res, message) { const { statusCode, body } = res message += `: ${statusCode}` let bodyStr try { bodyStr = JSON.stringify(body) } catch (err) { console.log("couldn't parse body") bodyStr = body } if (bodyStr) message += ` - ${bodyStr}` return formatError(message, statusCode, body) } module.exports = { new: formatError, buildFromRes } <file_sep>/lib/cot.js const dbHandle = require('./db_handle') const viewFunctions = require('./view_functions') const JsonRequest = require('./json_request') const configParser = require('./config_parser') module.exports = opts => { const jsonRequest = JsonRequest(configParser(opts)) return (dbName, designDocName) => { const API = dbHandle(jsonRequest, dbName) API.name = dbName API.request = jsonRequest if (typeof designDocName === 'string') { Object.assign(API, viewFunctions(API, designDocName)) API.designDocName = designDocName } return API } } <file_sep>/test/utils.js const wait = ms => new Promise(resolve => setTimeout(resolve, ms)) const catch404 = err => { if (err.status !== 404 && err.statusCode !== 404) throw err } const shouldNotBeCalled = res => { const err = new Error('function was expected not to be called') err.name = 'shouldNotBeCalled' err.context = { res } throw err } module.exports = { catch404, shouldNotBeCalled, wait, } <file_sep>/lib/request.js const fetch = require('node-fetch') const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) module.exports = (url, options) => tryRequest(url, options) const tryRequest = async (url, options, attempt = 0) => { try { return await fetch(url, options) } catch (err) { // Retry on 'socket hangup' errors, as this might be due to a persistant connection // (agent with keepAlive=true) that was closed because of another error, so retrying // should give us access to the primary error if (err.code === 'ECONNRESET' && attempt < 20) { await sleep(10 * attempt ** 2) console.warn(`[blue-cot retrying after ECONNRESET (attempt: ${attempt})]`, err) return tryRequest(url, options, ++attempt) } else { throw err } } } <file_sep>/README.md [CouchDB](http://couchdb.org/) library with a simple, functional-programing-friendly API. Forked from [Cot](https://github.com/willconant/cot-node), and renamed `blue-cot` in reference to the [Bluebird](https://github.com/petkaantonov/bluebird) promises it was returning until `v4.0.0` (it returns native promises since). ## Summary <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> - [Installing](#installing) - [Specificities of this lib](#specificities-of-this-lib) - [Initialization](#initialization) - [with Bluebird](#with-bluebird) - [API](#api) - [Database functions](#database-functions) - [info](#info) - [Documents functions](#documents-functions) - [get](#get) - [post](#post) - [put](#put) - [delete](#delete) - [find](#find) - [postIndex](#postindex) - [exists](#exists) - [batch](#batch) - [update](#update) - [bulk](#bulk) - [allDocs](#alldocs) - [allDocsKeys](#alldocskeys) - [fetch](#fetch) - [changes](#changes) - [listRevs](#listrevs) - [revertLastChange](#revertlastchange) - [revertToLastVersionWhere](#reverttolastversionwhere) - [undelete](#undelete) - [View functions](#view-functions) - [view](#view) - [viewQuery](#viewquery) - [viewKeysQuery](#viewkeysquery) - [viewKeys](#viewkeys) - [Design doc specific view functions](#design-doc-specific-view-functions) - [viewCustom](#viewcustom) - [viewByKeysCustom](#viewbykeyscustom) - [viewByKey](#viewbykey) - [viewFindOneByKey](#viewfindonebykey) - [viewByKeys](#viewbykeys) - [Utils](#utils) - [buildQueryString](#buildquerystring) - [See also](#see-also) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Installing ``` npm install blue-cot ``` ## Specificities of this lib Especially compared to [Cot](https://github.com/willconant/cot-node) from which it is forked * Class-less, thus a different initialization, but the rest of the API stays the same * Consequently, `blue-cot` is `this`-free: no need to bind functions contexts! * `4xx` and `5xx` responses will return rejected promises (should be handled with `.catch`) * Adds [a few new functions](#specific-api), notably [some view functions goodies](https://github.com/inventaire/blue-cot/blob/master/lib/view_functions.js) * Uses [Cookie Authentication](http://docs.couchdb.org/en/2.1.0/api/server/authn.html#cookie-authentication) instead of [Basic Auth](http://docs.couchdb.org/en/2.1.0/api/server/authn.html#basic-authentication) for better performance * Uses a single persistent connexion to CouchDB by default ## Initialization ```js const bluecot = require('blue-cot') const config = { // Required protocol: 'http', hostname: 'localhost', port: 5984, // Required if the database you are querying requires authentification username: 'your-couchdb-username', password: '<PASSWORD>', // Optinonal // Logs the generated URLs, body, and response time debug: true, // default: false // The default http agent already sets keepAlive=true // but if for some reason you want to pass your own http agent, you can. // Some documentation on the subject of http agents // https://nodejs.org/api/http.html#http_class_http_agent // https://github.com/bitinn/node-fetch#custom-agent // And the recommandations of the official CouchDB NodeJS lib // https://github.com/apache/couchdb-nano#pool-size-and-open-sockets agent: myAgent } const getDbApi = bluecot(config) const db = getDbApi('some-db-name') ``` ### with Bluebird From `v4.0.0`, `blue-cot` stopped returning [Bluebird](https://github.com/petkaantonov/bluebird) promises, but if you miss that feature, you can recover it by initializing `bluebird` before `blue-cot`: ```js global.Promise = require('bluebird') const bluecot = require('blue-cot') const getDbApi = bluecot(config) const db = getDbApi('some-db-name') ``` ## API ### Database functions To handle database and design documents creation, see [couch-init2](https://github.com/maxlath/couch-init2) #### info `GET /<dbName>` ```js const data = await db.info() ``` ### Documents functions #### get `GET /<dbName>/<docId>` Takes a document id and optionaly a rev id to get a specific version: ```js const latestDocVersion = await db.get('doc-1') const specificVersion = await db.get('doc-1', '2-b8476e8877ff5707de9e62e70a8e0aeb') ``` Missing documents are treated as an error, and thus return a rejected promise. #### post `POST /<dbName>` ```js const res = await db.post(doc) ``` Creates a new document or updates an existing document. If `doc._id` is undefined, CouchDB will generate a new ID for you. On 201, returns result from CouchDB which looks like: `{"ok":true, "id":"<docId>", "rev":"<docRev>"}` All other status codes (including 409, conflict) are treated as errors, and thus return a rejected promise. #### put `PUT /<dbName>/<doc._id>` ```js const res = await db.put(doc) ``` On 409 (conflict) returns result from CouchDB which looks like: `{"error":"conflict"}` On 201, returns result from CouchDB which looks like: `{"ok":true, "id":"<docId>", "rev":"<docRev>"}` All other status codes are treated as errors, and thus return a rejected promise. #### delete `DELETE /<dbName>/<docId>?rev=<rev>` ```js const res = await db.delete(docId, rev) ``` On 200, returns result from CouchDB which looks like: `{"ok":true, "id":"<docId>", "rev":"<docRev>"}` All other status codes are treated as errors, and thus return a rejected promise. If you wish to gracefully handle update conflicts while deleting, use `db.put()` on a document with `_deleted` set to `true`: ```js doc._deleted = true const res = await db.put(doc) if (!res.ok) { // something went wrong, possibly a conflict } ``` #### find `POST /<dbName>/_find_` (endpoint available in CouchDB `>= 2.0`) Takes a [`_find` query object](https://docs.couchdb.org/en/stable/api/database/find.html) ```js const { docs, bookmark } = await db.find({ selector: { year: { $gt: 2010 } }, fields: [ '_id', '_rev', 'year', 'title' ], sort: [ { year: 'asc' } ], limit: 2, skip: 0, use_index: [ 'some_design_doc_name', 'some_index_name' ], execution_stats: true }) ``` By default, this function will throw if receiving a warning; this behavior can be disable by passing `strict=false`: ```js const query = { selector: { year: { $gt: 2010 } } } const { docs, bookmark, warning } = await db.find(query, { strict: false }) ``` To send the same query to the [`_explain`](https://docs.couchdb.org/en/stable/api/database/find.html#db-explain) endpoint instead, use the `explain` flag: ```js const query = { selector: { name: 'foo' } } const { docs, bookmark, warning } = await db.find(query, { explain: true ) ``` #### postIndex `POST /<dbName>/_index` ```js const { result } = await db.postIndex({ index: { fields: [ 'type' ] }, ddoc: 'some_ddoc_name', name: 'by_type' }) ``` #### exists `GET /<dbName>/<docId>` ```js const res = await db.exists(docId) ``` Returns a promise resolving to true if it exist, or a rejected promise if it doesn't. #### batch `POST /<dbName>?batch=ok` ```js const res = await db.batch(doc) ``` doc: [`Batch Mode`](http://guide.couchdb.org/draft/performance.html#batch) Creates or updates a document but doesn't wait for success. Conflicts will not be detected. On 202, returns result from CouchDB which looks like: `{"ok":true, "id":"<docId>"}` The rev isn't returned because CouchDB returns before checking for conflicts. If there is a conflict, the update will be silently lost. All other status codes are treated as errors, and thus return a rejected promise. #### update ```js const res = await db.update(docId, updateFunction) ``` Gets the specified document, passes it to `updateFunction`, and then saves the results of `updateFunction` over the document The process loops if there is an update conflict. By default, `db.update` only accepts to update existing docs, but this can be changed by setting `createIfMissing=true`: ```js const res = await db.update(docId, updateFunction, { createIfMissing: true }) ``` #### bulk `POST /<dbName>/_bulk_docs` ```js const res = await db.bulk(docs) ``` See [CouchDB documentation](https://wiki.apache.org/couchdb/HTTP_Bulk_Document_API) for more information #### allDocs `GET /<dbName>/_all_docs?<properly encoded query>` ```js const { rows } = await db.allDocs(query) ``` Queries the `_all_docs` view. `query` supports the same keys as in [`db.view`](#view). #### allDocsKeys Loads documents with the specified keys and query parameters ```js const { rows } = await db.allDocsKeys(keys, query) ``` [Couchdb documentation](http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs) #### fetch Takes doc ids, returns docs. ```js const { docs, errors } = await db.fetch([ 'doc-1', 'doc-2', 'doc-3', 'some-non-existing-doc' ]) docs[0]._id === 'doc-1' // true docs[1]._id === 'doc-2' // true docs[2]._id === 'doc-3' // true errors[0].key === 'some-non-existing-doc' // true errors[0].error === 'not_found' // true ``` #### changes Queries the changes given the specified [query parameters](https://docs.couchdb.org/en/latest/api/database/changes.html). ```js const latestChanges = await db.changes({ descending: true, limit: 10 }) ``` :warning: the `feed` mode is not supported as a feed can not be returned as a stream. To follow a change feed, see [`cloudant-follow`](https://github.com/cloudant-labs/cloudant-follow) #### listRevs Takes a doc id, returns the doc's rev infos ```js const revsInfo = await db.listRevs('doc-1') ``` `revsInfo` will look something like: ``` [ { rev: '3-6a8869bc7fff815987ff9b7fda3e10e3', status: 'available' }, { rev: '2-88476e8877ff5707de9e62e70a8e0aeb', status: 'available' }, { rev: '1-a8bdf0ef0b7049d35c781210723b9ff9', status: 'available' } ] ``` #### revertLastChange Takes a doc id and reverts its last change, recovering the previous version. Only works if there is a previous version and if it is still available in the database (that is, if it wasn't deleted by a database compaction). It doesn't delete the last version, it simply creates a new version that is exactly like the version before the current one. ```js const res = await db.revertLastChange('doc-1') ``` #### revertToLastVersionWhere Takes a doc id and a function, and reverts to the last version returning a truthy result when passed through this function. Same warnings apply as for `revertLastChange`. ```js const desiredVersionTestFunction = doc => doc.foo === 2 db.revertToLastVersionWhere('doc-1', desiredVersionTestFunction) ``` #### undelete Mistakes happen ```js await db.delete(docId, docRev) await db.undelete(docId)) const restoredDoc = await db.get(docId)) ``` :warning: this will obviously not work if the version before deletion isn't in the database (because the database was compressed or it's a freshly replicated database), or if the database was purged from deleted documents. ### View functions #### view `GET /<dbName>/_desgin/<designName>/_view/<viewName>?<properly encoded query>` ```js const { rows, total_rows, offset } = db.view(designName, viewName, query) ``` Queries a view with the given name in the given design doc. `query` should be an object with any of the [query parameters](https://docs.couchdb.org/en/latest/api/ddoc/views.html) ```js const { rows } = await db.view('someDesignDocName', 'someViewName', { keys: [ 'a', 'b', 'c' ], include_docs: true, limit: 5, skip: 1 }) ``` #### viewQuery #### viewKeysQuery #### viewKeys #### Design doc specific view functions Those functions are pre-filled versions of the view functions above for the most common operations, like to get all the documents associated to an array of ids. To access those, pass a design doc name as second argument ```js const db = getDbApi('some-db-name', 'some-design-doc-name') ``` ##### viewCustom ##### viewByKeysCustom ##### viewByKey ##### viewFindOneByKey ##### viewByKeys see [lib/view_functions](https://github.com/maxlath/blue-cot/blob/master/lib/view_functions.js) If you find this module useful, consider making a PR to improve the documentation ### Utils #### buildQueryString ## See also you might want to consider using [couchdb-nano](https://github.com/apache/couchdb-nano), the now offical (but bloated ;p) CouchDB NodeJS lib <file_sep>/lib/db_handle.js const querystring = require('querystring') const errors_ = require('./errors') const recover = require('./recover_version') const { isPlainObject, validateString, validateArray, validatePlainObject } = require('./utils') module.exports = (jsonRequest, dbName) => { validateString(dbName, 'dbName') const API = { docUrl: docId => { validateString(docId, 'doc id') if (docId.indexOf('_design/') === 0) { return '/' + dbName + '/_design/' + encodeURIComponent(docId.substr(8)) } else { return '/' + dbName + '/' + encodeURIComponent(docId) } }, info: async () => { const res = await jsonRequest('GET', `/${dbName}`) return res.data }, get: async (docId, revId) => { let url = API.docUrl(docId) if (typeof revId === 'string') url += `?rev=${revId}` const res = await jsonRequest('GET', url) if (res.statusCode === 200) return res.data else throw errors_.buildFromRes(res, `error getting doc ${docId}`) }, exists: async docId => { try { const res = await jsonRequest('GET', API.docUrl(docId)) if (res.statusCode === 200) return true else throw errors_.buildFromRes(res, `error getting doc ${docId}`) } catch (err) { if (err.statusCode === 404) return false else throw err } }, put: async doc => { validatePlainObject(doc, 'doc') const res = await jsonRequest('PUT', API.docUrl(doc._id), doc) if (res.statusCode === 200 || res.statusCode === 201) return res.data else throw errors_.buildFromRes(res, `error putting doc ${doc._id}`) }, post: async doc => { validatePlainObject(doc, 'doc') const res = await jsonRequest('POST', `/${dbName}`, doc) if (res.statusCode === 201) { return res.data } else if (doc._id) { throw errors_.buildFromRes(res, `error posting doc ${doc._id}`) } else { throw errors_.buildFromRes(res, 'error posting new doc') } }, batch: async doc => { validatePlainObject(doc, 'doc') const path = `/${dbName}?batch=ok` const res = await jsonRequest('POST', path, doc) if (res.statusCode === 202) { return res.data } else if (doc._id) { throw errors_.buildFromRes(res, `error batch posting doc ${doc._id}`) } else { throw errors_.buildFromRes(res, 'error batch posting new doc') } }, update: async (docId, fn, options = {}) => { const db = API let attempt = 0 const { createIfMissing } = options const tryIt = async () => { if (++attempt > 10) throw errors_.new('too many attempts', 400, { docId, fn }) let doc try { doc = await db.get(docId) } catch (err) { if (err.statusCode === 404 && createIfMissing) doc = { _id: docId } else throw err } try { const res = await db.put(fn(doc)) if (res.ok) return res else return tryIt() } catch (err) { if (err.statusCode === 409) return tryIt() else throw err } } return tryIt() }, delete: async (docId, rev) => { validateString(rev, 'rev') const url = API.docUrl(docId) + '?rev=' + encodeURIComponent(rev) const res = await jsonRequest('DELETE', url) if (res.statusCode === 200) return res.data else throw errors_.buildFromRes(res, `error deleting doc ${docId}`) }, // Based on http://stackoverflow.com/a/16827094/3324977 undelete: async docId => { validateString(docId, 'doc id') try { // Verify that it's indeed a deleted document: if get doesn't throw, there is nothing to undelete await API.get(docId) throw errors_.new("can't undelete an non-deleted document", 400, docId) } catch (err) { if (err.statusCode !== 404 || err.body.reason !== 'deleted') throw err const url = API.docUrl(docId) + '?revs=true&open_revs=all' const res = await jsonRequest('GET', url) const data = res.data[0].ok const preDeleteRevNum = data._revisions.start - 1 const preDeleteRevId = data._revisions.ids[1] const preDeleteRev = preDeleteRevNum + '-' + preDeleteRevId const preDeleteDoc = await API.get(docId, preDeleteRev) // Re-created documents shouldn't have a rev, see https://github.com/apache/couchdb/issues/3177 delete preDeleteDoc._rev return API.put(preDeleteDoc) } }, bulk: async docs => { validateArray(docs, 'docs') const url = `/${dbName}/_bulk_docs` // Validate documents to avoid to get a cryptic // 'Internal Server Error' 500 CouchDB error for (let i = 0; i < docs.length; i++) { const doc = docs[i] if (!isPlainObject(doc)) { throw errors_.new('invalid bulk doc', 400, { doc, index: i }) } } const res = await jsonRequest('POST', url, { docs }) if (res.statusCode !== 201) throw errors_.buildFromRes(res, 'error posting to _bulk_docs') for (const part of res.data) { if (part.error != null) { const statusCode = part.error === 'conflict' ? 409 : 400 throw errors_.new('bulk response contains errors', statusCode, { body: res.data }) } } return res.data }, buildQueryString: query => buildSanitizedQueryString(query, viewQueryKeys), viewQuery: async (path, query) => { const qs = API.buildQueryString(query) const url = `/${dbName}/${path}?${qs}` const res = await jsonRequest('GET', url) if (res.statusCode === 200) return res.data else throw errors_.buildFromRes(res, `error reading view ${path}`) }, view: async (designName, viewName, query) => { validateString(designName, 'design doc name') validateString(viewName, 'view name') validatePlainObject(query, 'query') return API.viewQuery(`_design/${designName}/_view/${viewName}`, query) }, allDocs: async query => { return API.viewQuery('_all_docs', query) }, viewKeysQuery: async (path, keys, query = {}) => { validateString(path, 'path') validateArray(keys, 'keys') const qs = API.buildQueryString(query) const url = `/${dbName}/${path}?${qs}` const res = await jsonRequest('POST', url, { keys }) if (res.statusCode === 200) return res.data else throw errors_.buildFromRes(res, `error reading view ${path}`) }, viewKeys: async (designName, viewName, keys, query) => { validateString(designName, 'design doc name') validateString(viewName, 'view name') validateArray(keys, 'keys') validatePlainObject(query, 'query') const path = `_design/${designName}/_view/${viewName}` return API.viewKeysQuery(path, keys, query) }, // http://docs.couchdb.org/en/latest/api/database/bulk-api.html#post--db-_all_docs allDocsKeys: async (keys, query) => { return API.viewKeysQuery('_all_docs', keys, query) }, fetch: async (keys, options) => { validateArray(keys, 'keys') const throwOnErrors = options != null && options.throwOnErrors === true const { rows } = await API.viewKeysQuery('_all_docs', keys, { include_docs: true }) const docs = [] const errors = [] for (const row of rows) { if (row.error) errors.push(row) else if (row.value.deleted) errors.push({ key: row.key, error: 'deleted' }) else docs.push(row.doc) } if (throwOnErrors && errors.length > 0) throw errors_.new('docs fetch errors', 400, { keys, errors }) return { docs, errors } }, listRevs: async docId => { const url = API.docUrl(docId) + '?revs_info=true' const res = await jsonRequest('GET', url) return res.data._revs_info }, revertLastChange: async docId => { const revsInfo = await API.listRevs(docId) const currentRevInfo = revsInfo[0] // Select only the previous one const candidatesRevsInfo = revsInfo.slice(1, 2) return recover(API, docId, candidatesRevsInfo, currentRevInfo) }, revertToLastVersionWhere: async (docId, testFn) => { const revsInfo = await API.listRevs(docId) const currentRevInfo = revsInfo[0] const candidatesRevsInfo = revsInfo.slice(1) return recover(API, docId, candidatesRevsInfo, currentRevInfo, testFn) }, changes: async (query = {}) => { const qs = buildSanitizedQueryString(query, changesQueryKeys) const path = `/${dbName}/_changes?${qs}` const res = await jsonRequest('GET', path) if (res.statusCode === 200) return res.data else throw errors_.buildFromRes(res, 'error reading _changes') }, find: async (query = {}, options = {}) => { let endpoint = '_find' if (options.explain) endpoint = '_explain' const path = `/${dbName}/${endpoint}` const res = await jsonRequest('POST', path, query) if (res.statusCode === 200) { const { warning } = res.data if (query.use_index != null && warning != null && warning.includes('No matching index found')) { throw errors_.new('No matching index found', 400, { path, query, options, warning }) } else { return res.data } } else { throw errors_.buildFromRes(res, 'find error') } }, postIndex: async indexDoc => { validatePlainObject(indexDoc, 'index doc') const res = await jsonRequest('POST', `/${dbName}/_index`, indexDoc) if (res.statusCode === 200 || res.statusCode === 201) return res.data else throw errors_.buildFromRes(res, 'postIndex error') } } return API } const buildSanitizedQueryString = (query = {}, queryKeys) => { validatePlainObject(query, 'query') const q = {} for (const key of Object.keys(query)) { // Avoid any possible conflict with object inherited attributes and methods if (Object.prototype.hasOwnProperty.call(query, key)) { validateQueryKey(queryKeys, key, query) if (query[key] != null) { if (queryKeys[key] === 'json') { q[key] = JSON.stringify(query[key]) } else { q[key] = query[key] } } } } return querystring.stringify(q) } const validateQueryKey = (queryKeys, key, query) => { if (queryKeys[key] == null) { throw errors_.new('invalid query key', 400, { key, query, validKeys: Object.keys(queryKeys) }) } } // Source: https://docs.couchdb.org/en/latest/api/ddoc/views.html const viewQueryKeys = { conflicts: 'boolean', descending: 'boolean', endkey: 'json', end_key: 'json', endkey_docid: 'string', end_key_doc_id: 'string', group: 'boolean', group_level: 'number', include_docs: 'boolean', attachments: 'boolean', att_encoding_info: 'boolean', inclusive_end: 'boolean', key: 'json', keys: 'json', limit: 'number', reduce: 'boolean', skip: 'number', sorted: 'boolean', stable: 'boolean', stale: 'string', startkey: 'json', start_key: 'json', startkey_docid: 'string', start_key_doc_id: 'string', update: 'string', update_seq: 'boolean', } // Source: https://docs.couchdb.org/en/latest/api/database/changes.html const changesQueryKeys = { doc_ids: 'json', conflicts: 'boolean', descending: 'boolean', // Not including feed as a possible option as it doesn't play well with promises // feed: 'string', filter: 'string', heartbeat: 'number', include_docs: 'boolean', attachments: 'boolean', att_encoding_info: 'boolean', 'last-event-id': 'number', limit: 'number', style: 'string', since: 'string', timeout: 'number', view: 'string', seq_interval: 'number', } <file_sep>/test/views.test.js const should = require('should') const cot = require('../lib/cot') const config = require('config') const { shouldNotBeCalled, catch404 } = require('./utils') describe('Validations', function () { const db = cot(config.cot)(config.dbName, 'test') describe('#viewCustom', function () { it('should reject a call without a view name', async function () { await db.viewCustom() .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('invalid view name') }) }) it('should reject a call without query object', async function () { await db.viewCustom('byKey') .then(shouldNotBeCalled) .catch(err => { err.message.should.startWith('invalid query object') }) }) }) describe('#viewByKeysCustom', function () { it('should reject a call without a view name', async function () { await db.viewByKeysCustom() .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('invalid view name') }) }) it('should reject a call without a keys array', async function () { await db.viewByKeysCustom('byKey') .then(shouldNotBeCalled) .catch(err => { err.message.should.startWith('invalid keys array') }) }) it('should reject a call without query object', async function () { await db.viewByKeysCustom('byKey', [ 'foo' ]) .then(shouldNotBeCalled) .catch(err => { err.message.should.startWith('invalid query object') }) }) }) describe('#viewByKey', function () { it('should reject a call without a view name', async function () { await db.viewByKey() .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('invalid view name') }) }) it('should reject a call without a key', async function () { await db.viewByKey('byKey') .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('missing key') }) }) }) describe('#viewFindOneByKey', function () { it('should reject a call without a view name', async function () { await db.viewFindOneByKey() .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('invalid view name') }) }) it('should reject a call without a key', async function () { await db.viewFindOneByKey('byKey') .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('missing key') }) }) }) describe('#viewByKeys', function () { it('should reject a call without a view name', async function () { await db.viewByKeys() .then(shouldNotBeCalled) .catch(err => { err.message.should.equal('invalid view name') }) }) it('should reject a call without keys array', async function () { await db.viewByKeys('byKey') .then(shouldNotBeCalled) .catch(err => { err.message.should.startWith('invalid keys array') }) }) }) }) describe('Views', function () { const db = cot(config.cot)(config.dbName, 'test') beforeEach(async function () { await db.request('DELETE', `/${config.dbName}`).catch(catch404) await db.request('PUT', `/${config.dbName}`) const docPromises = [] let i = 1 while (i < 10) { const doc = { _id: `doc-${i}`, key: `key-${i}` } docPromises.push(db.post(doc)) i++ } const designDoc = { _id: '_design/test', views: { testView: { map: 'function (doc) { emit("z", null) }' }, byKey: { map: 'function (doc) { emit(doc.key, null) }' } } } docPromises.push(db.post(designDoc)) await Promise.all(docPromises) }) describe('#view', function () { it('should return doc-3 thru doc-6 using startkey_docid and endkey_docid', async function () { const res = await db.view('test', 'testView', { key: 'z', startkey_docid: 'doc-3', endkey_docid: 'doc-6' }) res.rows.length.should.equal(4) res.rows[0].id.should.equal('doc-3') res.rows[1].id.should.equal('doc-4') res.rows[2].id.should.equal('doc-5') res.rows[3].id.should.equal('doc-6') }) it('should return rows by keys', async function () { const res = await db.view('test', 'byKey', { keys: [ 'key-2', 'key-3' ], }) res.rows.length.should.equal(2) res.rows[0].id.should.equal('doc-2') res.rows[1].id.should.equal('doc-3') }) }) describe('#viewFindOneByKey', function () { it('should return a unique doc', async function () { const doc = await db.viewFindOneByKey('byKey', 'key-1') doc._id.should.equal('doc-1') }) it('should return a formatted error', async function () { await db.viewFindOneByKey('testView', 'notexisting') .then(shouldNotBeCalled) .catch(err => { should(err.statusCode).be.ok() should(err.context).be.ok() }) }) }) }) <file_sep>/config/default.js module.exports = { cot: { protocol: 'http', hostname: 'localhost', port: 5984, username: 'admin', password: '<PASSWORD>', debug: false }, dbName: 'test-cot-node' } <file_sep>/CHANGELOG.md # CHANGELOG *versions follow [SemVer](http://semver.org)* ## 7.0.0 - 2022-01-18 **BREAKING CHANGES**: - [view functions](https://github.com/maxlath/blue-cot#view) and [`db.changes`](https://github.com/maxlath/blue-cot#changes) now reject unkwown query parameters - [`db.changes`](https://github.com/maxlath/blue-cot#changes): removing `longpoll` parameter, has it's a feed flag, and the `db.changes` function doesn't not handle feeds (it doesn't play well with promises) ## 6.2.0 - 2021-01-02 * Added [`db.postIndex`](https://github.com/maxlath/blue-cot#postIndex) * Added [`db.find`](https://github.com/maxlath/blue-cot#find) ## 6.1.0 - 2020-09-28 [`db.update`](https://github.com/maxlath/blue-cot#update): allow to set `createIfMissing=true`, allowing to recover the behavior from `< 6.0.0` ## 6.0.0 - 2020-08-10 **BREAKING CHANGES**: [`db.update`](https://github.com/maxlath/blue-cot#update) stops to create empty (`{ _id }`) docs when the updated doc can't be found, rejecting with a 404 instead. ## 5.0.0 - 2020-08-10 **BREAKING CHANGES**: [`db.fetch`](https://github.com/maxlath/blue-cot#fetch) now returns a { docs, errors } object ## 4.0.0 - 2019-12-31 **BREAKING CHANGES**: * `blue-cot` returns native promises instead of Bluebird promises (but you can easily [recover that feature](https://github.com/maxlath/blue-cot#with-bluebird)) * Config parameters changes: * Replaced `ssl` flag by `protocol` parameter * Renamed `user` -> `username` * Renamed `pass` -> `<PASSWORD>` * Removed `gzip` flag * Removed `auth` paramater: use `username` and `password` * Functions changes: * Renamed `db.jsonRequest` -> `db.request` New Features: * Default http agent reuses sockets by setting `keepAlive=true` flag. * A custom http agent can be passed ## 3.5.0 - 2018-03-02 * Added a compression option: `gzip` (see [Initialization](https://github.com/maxlath/blue-cot#initialization)) ## 3.4.0 - 2017-01-26 * Added [`db.undelete`](https://github.com/maxlath/blue-cot#undelete) ## 3.3.0 - 2017-01-23 * Added [`db.revertToLastVersionWhere`](https://github.com/maxlath/blue-cot#reverttolastversionwhere) ## 3.2.0 - 2017-01-23 * Added [`db.listRevs`](https://github.com/maxlath/blue-cot#listrevs) * Added [`db.revertLastChange`](https://github.com/maxlath/blue-cot#revertlastchange) * Added `db.revertLastChange` * `db.get` accepts a `rev` id as second parameter ## 3.1.0 - 2017-01-14 * Added [`db.fetch`](https://github.com/maxlath/blue-cot#fetch) ## 3.0.0 - 2017-01-14 * Breaking change: removing constructors in favor of factory functions, breaking the module interface (see [Initialization](https://github.com/maxlath/blue-cot#initialization)) * New feature: [View functions](https://github.com/maxlath/blue-cot#view-functions) * New feature: blue-cot is `this`-free! No need to bind functions context anymore! ## 2.0.0 - 2016-05-13 * Breaking change: updated bluereq to its [version 2.1.0](https://github.com/maxlath/bluereq/blob/master/CHANGELOG.md), returning rejected promises on 4xx errors <file_sep>/lib/config_parser.js module.exports = ({ protocol, hostname, port, username, password, debug }) => { const config = {} if (!(protocol === 'http' || protocol === 'https')) { throw new Error(`invalid protocol: ${protocol}`) } config.host = `${protocol}://${hostname}:${port}` config.username = username config.password = <PASSWORD> config.hostHeader = hostname config.agent = config.agent || getAgent(protocol) const nonStandardPort = protocol === 'http' ? port !== 80 : port !== 443 if (nonStandardPort) config.hostHeader += ':' + port // Making sure it's a boolean, defaulting to false config.debug = debug === true return config } // Some documentation on the subject of http agents // https://nodejs.org/api/http.html#http_class_http_agent // https://github.com/bitinn/node-fetch#custom-agent // https://github.com/apache/couchdb-nano#pool-size-and-open-sockets // https://github.com/node-modules/agentkeepalive const getAgent = protocol => { const { Agent } = require(protocol) return new Agent({ keepAlive: true }) }
ecb1a7df0b843f812d9ed4982aea38c535053526
[ "JavaScript", "Markdown" ]
14
JavaScript
maxlath/blue-cot
adcbd483577a2873fdb7511fd5813934339f84b6
67ca1b6715d28f3415078058dbad5e573fc55e59
refs/heads/master
<repo_name>mlj5j/EventCheck<file_sep>/plugins/SpikeAnalyserMC.cc #include <iostream> #include <sstream> #include <istream> #include <fstream> #include <iomanip> #include <string> #include <cmath> #include <functional> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/CaloTowers/interface/CaloTowerCollection.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgoRcd.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalCleaningAlgo.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbService.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPedestals.h" #include "CondFormats/DataRecord/interface/EcalADCToGeVConstantRcd.h" #include "CondFormats/EcalObjects/interface/EcalADCToGeVConstant.h" #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h" #include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h" #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTriggerRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTrigger.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFLayer.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "JetMETCorrections/MCJet/plugins/SpikeAnalyserMC.h" #include "JetMETCorrections/MCJet/plugins/JetUtilMC.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterTools.h" #include "RecoEcal/EgammaCoreTools/interface/EcalTools.h" #include "Math/VectorUtil.h" #include "TVector3.h" using namespace edm; using namespace reco; using namespace std; DEFINE_FWK_MODULE(SpikeAnalyserMC); SpikeAnalyserMC::SpikeAnalyserMC(const edm::ParameterSet& cfg) : bunchstartbx_(cfg.getParameter<std::vector<int> >("bunchstartbx")) { jets_ = cfg.getParameter<std::string> ("jets"); histogramFile_ = cfg.getParameter<std::string> ("histogramFile"); tracks_ = cfg.getParameter<std::string> ("tracks"); vertex_coll_ = cfg.getParameter<std::string> ("vertex"); ebhitcoll_ = cfg.getParameter<std::string> ("EBRecHitCollection"); eehitcoll_ = cfg.getParameter<std::string> ("EERecHitCollection"); isMC_ = cfg.getParameter<bool>("IsMC"); edm::ParameterSet cleaningPs = cfg.getParameter<edm::ParameterSet>("cleaningConfig"); cleaningAlgo_ = new EcalCleaningAlgo(cleaningPs); } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyserMC::beginJob() { file_ = new TFile(histogramFile_.c_str(),"RECREATE"); histo_event_ = new TH1D("histo_event","",350,0.,3500.); eb_rechitenergy_ = new TH1D("eb_rechitenergy","",2020,-2.,200.); ee_rechitenergy_ = new TH1D("ee_rechitenergy","",2020,-2.,200.); ee_rechitenergy_notypeb_ = new TH1D("ee_rechitenergy_notypeb","",2020,-2.,200.); eb_rechitenergy_spiketag = new TH1D("eb_rechitenergy_spiketag","",2020,-2.,200.); eb_rechitenergy_swisscross = new TH1D("eb_rechitenergy_swisscross","",2020,-2.,200.); eb_rechitenergy_kweird = new TH1D("eb_rechitenergy_kweird","",2020,-2.,200.); eb_rechitenergy_knotweird = new TH1D("eb_rechitenergy_knotweird","",2020,-2.,200.); eb_rechitenergy_spiketag_kweird = new TH1D("eb_rechitenergy_spiketag_kweird","",2020,-2.,200.); eb_rechitenergy_spiketag_swisscross = new TH1D("eb_rechitenergy_spiketag_swisscross","",2020,-2.,200.); eb_rechitenergy_spiketag_noisedep = new TH1D("eb_rechitenergy_spiketag_noisedep","",2020,-2.,200.); eb_rechitenergy_sctag = new TH1D("eb_rechitenergy_sctag","",2020,-2.,200.); eb_rechitenergy_sctag_kweird = new TH1D("eb_rechitenergy_sctag_kweird","",2020,-2.,200.); eb_rechitenergy_sctag_swisscross = new TH1D("eb_rechitenergy_sctag_swisscross","",2020,-2.,200.); eb_rechitenergy_sctag_noisedep = new TH1D("eb_rechitenergy_sctag_noisedep","",2020,-2.,200.); Emin_=1000.0; side_=5; eb_rechitenergy_02 = new TH1D("eb_rechitenergy_02","",1100,-2.,20.); eb_rechitenergy_04 = new TH1D("eb_rechitenergy_04","",1100,-2.,20.); eb_rechitenergy_06 = new TH1D("eb_rechitenergy_06","",1100,-2.,20.); eb_rechitenergy_08 = new TH1D("eb_rechitenergy_08","",1100,-2.,20.); eb_rechitenergy_10 = new TH1D("eb_rechitenergy_10","",1100,-2.,20.); eb_rechitenergy_12 = new TH1D("eb_rechitenergy_12","",1100,-2.,20.); eb_rechitenergy_14 = new TH1D("eb_rechitenergy_14","",1100,-2.,20.); eb_rechitenergy_148 = new TH1D("eb_rechitenergy_148","",1100,-2.,20.); ee_rechitenergy_16 = new TH1D("ee_rechitenergy_16","",1100,-2.,20.); ee_rechitenergy_18 = new TH1D("ee_rechitenergy_18","",1100,-2.,20.); ee_rechitenergy_20 = new TH1D("ee_rechitenergy_20","",1100,-2.,20.); ee_rechitenergy_22 = new TH1D("ee_rechitenergy_22","",1100,-2.,20.); ee_rechitenergy_24 = new TH1D("ee_rechitenergy_24","",1100,-2.,20.); ee_rechitenergy_26 = new TH1D("ee_rechitenergy_26","",1100,-2.,20.); ee_rechitenergy_28 = new TH1D("ee_rechitenergy_28","",1100,-2.,20.); ee_rechitenergy_30 = new TH1D("ee_rechitenergy_30","",1100,-2.,20.); eb_rechitet_02 = new TH1D("eb_rechitet_02","",1100,-2.,20.); eb_rechitet_04 = new TH1D("eb_rechitet_04","",1100,-2.,20.); eb_rechitet_06 = new TH1D("eb_rechitet_06","",1100,-2.,20.); eb_rechitet_08 = new TH1D("eb_rechitet_08","",1100,-2.,20.); eb_rechitet_10 = new TH1D("eb_rechitet_10","",1100,-2.,20.); eb_rechitet_12 = new TH1D("eb_rechitet_12","",1100,-2.,20.); eb_rechitet_14 = new TH1D("eb_rechitet_14","",1100,-2.,20.); eb_rechitet_148 = new TH1D("eb_rechitet_148","",1100,-2.,20.); ee_rechitet_16 = new TH1D("ee_rechitet_16","",1100,-2.,20.); ee_rechitet_18 = new TH1D("ee_rechitet_18","",1100,-2.,20.); ee_rechitet_20 = new TH1D("ee_rechitet_20","",1100,-2.,20.); ee_rechitet_22 = new TH1D("ee_rechitet_22","",1100,-2.,20.); ee_rechitet_24 = new TH1D("ee_rechitet_24","",1100,-2.,20.); ee_rechitet_26 = new TH1D("ee_rechitet_26","",1100,-2.,20.); ee_rechitet_28 = new TH1D("ee_rechitet_28","",1100,-2.,20.); ee_rechitet_30 = new TH1D("ee_rechitet_30","",1100,-2.,20.); eb_rechitetvspu_05 = new TH2D("eb_rechitetvspu_05","",25,0,50,500,-0.5,20); eb_rechitetvspu_10 = new TH2D("eb_rechitetvspu_10","",25,0,50,500,-0.5,20); eb_rechitetvspu_15 = new TH2D("eb_rechitetvspu_15","",25,0,50,500,-0.5,20); ee_rechitetvspu_20 = new TH2D("ee_rechitetvspu_20","",25,0,50,500,-0.5,20); ee_rechitetvspu_25 = new TH2D("ee_rechitetvspu_25","",25,0,50,500,-0.5,20); ee_rechitetvspu_30 = new TH2D("ee_rechitetvspu_30","",25,0,50,500,-0.5,20); eb_rechitet_ = new TH1D("eb_rechitet","",1100,-2.,20.); ee_rechitet_ = new TH1D("ee_rechitet","",1100,-2.,20.); eb_rechiten_vs_eta = new TH2D("ebrechiten_vs_eta","",30,-1.5,1.5,350,-2,5); eb_rechitet_vs_eta = new TH2D("ebrechitet_vs_eta","",30,-1.5,1.5,350,-2,5); eep_rechiten_vs_eta = new TH2D("eep_rechiten_vs_eta","",18,1.4,3.2,350,-2,5); eep_rechiten_vs_phi = new TH2D("eep_rechiten_vs_phi","",18,-3.1416,3.1416,350,-2,5); eem_rechiten_vs_eta = new TH2D("eem_rechiten_vs_eta","",18,1.4,3.2,350,-2,5); eem_rechiten_vs_phi = new TH2D("eem_rechiten_vs_phi","",18,-3.1416,3.1416,350,-2,5); eep_rechitet_vs_eta = new TH2D("eep_rechitet_vs_eta","",18,1.4,3.2,350,-2,5); eep_rechitet_vs_phi = new TH2D("eep_rechitet_vs_phi","",18,-3.1416,3.1416,350,-2,5); eem_rechitet_vs_eta = new TH2D("eem_rechitet_vs_eta","",18,1.4,3.2,350,-2,5); eem_rechitet_vs_phi = new TH2D("eem_rechitet_vs_phi","",18,-3.1416,3.1416,350,-2,5); ebocc = new TH2F("ebocc","",360,0,360,170,-85,85); eboccgt1 = new TH2F("eboccgt1","",360,0,360,170,-85,85); eboccgt3 = new TH2F("eboccgt3","",360,0,360,170,-85,85); eboccgt5 = new TH2F("eboccgt5","",360,0,360,170,-85,85); eboccgt1et = new TH2F("eboccgt1et","",360,0,360,170,-85,85); eboccet = new TH2F("eboccet","",360,0,360,170,-85,85); eboccetgt1et = new TH2F("eboccetgt1et","",360,0,360,170,-85,85); eboccen = new TH2F("eboccen","",360,0,360,170,-85,85); eboccengt1 = new TH2F("eboccengt1","",360,0,360,170,-85,85); eeocc = new TH2F("eeocc","",200,0,200,100,0,100); eeoccgt1 = new TH2F("eeoccgt1","",200,0,200,100,0,100); eeoccgt1et = new TH2F("eeoccgt1et","",200,0,200,100,0,100); eeoccet = new TH2F("eeoccet","",200,0,200,100,0,100); eeoccetgt1et = new TH2F("eeoccetgt1et","",200,0,200,100,0,100); eeoccen = new TH2F("eeoccen","",200,0,200,100,0,100); eeoccengt1 = new TH2F("eeoccengt1","",200,0,200,100,0,100); spikeadc=new TH1F("spikeadc","",100,0,1000); spiketime50=new TH1F("spiketime50","",10,0.5,10.5); etaphi_ped = new TH2D("etaphi_ped","",360,0,360,170,-85,85); etaphi_pedsq = new TH2D("etaphi_pedsq","",360,0,360,170,-85,85); etaphi_pedn = new TH2D("etaphi_pedn","",360,0,360,170,-85,85); etaphi_pednoise = new TH2D("etaphi_pednoise","",360,0,360,170,-85,85); noise2d = new TH2D("noise2d","",360,0,360,170,-85,85); eventenergy = new TH2D("eventenergy","",360,0,360,170,-85,85); eventet = new TH2D("eventet","",360,0,360,170,-85,85); eventtime = new TH2D("eventtime","",360,0,360,170,-85,85); eventkoot = new TH2D("eventkoot","",360,0,360,170,-85,85); eventkdiweird = new TH2D("eventkdiweird","",360,0,360,170,-85,85); spike_timevset_all_08 = new TH2D("spike_timevset_all_08","",120,-60,60,200,-2,18); spike_timevset_highest_08 = new TH2D("spike_timevset_highest_08","",120,-60,60,200,-2,18); spike_timevset_koot_all_08 = new TH2D("spike_timevset_koot_all_08","",120,-60,60,200,-2,18); spike_timevset_koot_highest_08 = new TH2D("spike_timevset_koot_highest_08","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_08 = new TH2D("spike_timevset_kdiweird_all_08","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_08 = new TH2D("spike_timevset_kdiweird_highest_08","",120,-60,60,200,-2,18); spike_timevset_all_07 = new TH2D("spike_timevset_all_07","",120,-60,60,200,-2,18); spike_timevset_highest_07 = new TH2D("spike_timevset_highest_07","",120,-60,60,200,-2,18); spike_timevset_koot_all_07 = new TH2D("spike_timevset_koot_all_07","",120,-60,60,200,-2,18); spike_timevset_koot_highest_07 = new TH2D("spike_timevset_koot_highest_07","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_07 = new TH2D("spike_timevset_kdiweird_all_07","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_07 = new TH2D("spike_timevset_kdiweird_highest_07","",120,-60,60,200,-2,18); spike_timevset_all_06 = new TH2D("spike_timevset_all_06","",120,-60,60,200,-2,18); spike_timevset_highest_06 = new TH2D("spike_timevset_highest_06","",120,-60,60,200,-2,18); spike_timevset_koot_all_06 = new TH2D("spike_timevset_koot_all_06","",120,-60,60,200,-2,18); spike_timevset_koot_highest_06 = new TH2D("spike_timevset_koot_highest_06","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_06 = new TH2D("spike_timevset_kdiweird_all_06","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_06 = new TH2D("spike_timevset_kdiweird_highest_06","",120,-60,60,200,-2,18); scocc_eb_gt50 = new TH2F("scocc_eb_gt50","",100,-3.14,3.14,100,-3,3); scocc_ee_gt50 = new TH2F("scocc_ee_gt50","",100,-3.14,3.14,100,-3,3); tower_spike_ene_swiss_t10 = new TH2D("tower_spike_ene_swiss_t10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07 = new TH2D("tower_spike_ene_swiss_t07","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05 = new TH2D("tower_spike_ene_swiss_t05","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04 = new TH2D("tower_spike_ene_swiss_t04","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03 = new TH2D("tower_spike_ene_swiss_t03","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10 = new TH2D("sc_tower_spike_ene_swiss_t10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07 = new TH2D("sc_tower_spike_ene_swiss_t07","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05 = new TH2D("sc_tower_spike_ene_swiss_t05","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04 = new TH2D("sc_tower_spike_ene_swiss_t04","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03 = new TH2D("sc_tower_spike_ene_swiss_t03","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh08 = new TH2D("tower_spike_ene_swiss_t10_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh08 = new TH2D("tower_spike_ene_swiss_t07_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh08 = new TH2D("tower_spike_ene_swiss_t05_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh08 = new TH2D("tower_spike_ene_swiss_t04_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh08 = new TH2D("tower_spike_ene_swiss_t03_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh10 = new TH2D("tower_spike_ene_swiss_t10_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh10 = new TH2D("tower_spike_ene_swiss_t07_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh10 = new TH2D("tower_spike_ene_swiss_t05_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh10 = new TH2D("tower_spike_ene_swiss_t04_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh10 = new TH2D("tower_spike_ene_swiss_t03_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh12 = new TH2D("tower_spike_ene_swiss_t10_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh12 = new TH2D("tower_spike_ene_swiss_t07_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh12 = new TH2D("tower_spike_ene_swiss_t05_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh12 = new TH2D("tower_spike_ene_swiss_t04_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh12 = new TH2D("tower_spike_ene_swiss_t03_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh15 = new TH2D("tower_spike_ene_swiss_t10_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh15 = new TH2D("tower_spike_ene_swiss_t07_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh15 = new TH2D("tower_spike_ene_swiss_t05_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh15 = new TH2D("tower_spike_ene_swiss_t04_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh15 = new TH2D("tower_spike_ene_swiss_t03_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh20 = new TH2D("tower_spike_ene_swiss_t10_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh20 = new TH2D("tower_spike_ene_swiss_t07_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh20 = new TH2D("tower_spike_ene_swiss_t05_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh20 = new TH2D("tower_spike_ene_swiss_t04_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh20 = new TH2D("tower_spike_ene_swiss_t03_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt = new TH2D("tower_spike_et_swisstt","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt = new TH2D("tower_spike_ene_swisstt","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh08 = new TH2D("tower_spike_et_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh08 = new TH2D("tower_spike_ene_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh10 = new TH2D("tower_spike_et_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh10 = new TH2D("tower_spike_ene_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh12 = new TH2D("tower_spike_et_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh12 = new TH2D("tower_spike_ene_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh15 = new TH2D("tower_spike_et_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh15 = new TH2D("tower_spike_ene_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh20 = new TH2D("tower_spike_et_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh20 = new TH2D("tower_spike_ene_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt = new TH2D("sc_tower_spike_et_swisstt","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt = new TH2D("sc_tower_spike_ene_swisstt","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh08 = new TH2D("sc_tower_spike_et_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh08 = new TH2D("sc_tower_spike_ene_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh10 = new TH2D("sc_tower_spike_et_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh10 = new TH2D("sc_tower_spike_ene_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh12 = new TH2D("sc_tower_spike_et_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh12 = new TH2D("sc_tower_spike_ene_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh15 = new TH2D("sc_tower_spike_et_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh15 = new TH2D("sc_tower_spike_ene_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh20 = new TH2D("sc_tower_spike_et_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh20 = new TH2D("sc_tower_spike_ene_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss = new TH2D("tower_spike_et_swiss","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss = new TH2D("tower_spike_ene_swiss","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh08 = new TH2D("tower_spike_et_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh08 = new TH2D("tower_spike_ene_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh10 = new TH2D("tower_spike_et_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh10 = new TH2D("tower_spike_ene_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh12 = new TH2D("tower_spike_et_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh12 = new TH2D("tower_spike_ene_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh15 = new TH2D("tower_spike_et_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh15 = new TH2D("tower_spike_ene_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh20 = new TH2D("tower_spike_et_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh20 = new TH2D("tower_spike_ene_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss = new TH2D("sc_tower_spike_et_swiss","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss = new TH2D("sc_tower_spike_ene_swiss","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh08 = new TH2D("sc_tower_spike_et_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh08 = new TH2D("sc_tower_spike_ene_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh10 = new TH2D("sc_tower_spike_et_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh10 = new TH2D("sc_tower_spike_ene_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh12 = new TH2D("sc_tower_spike_et_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh12 = new TH2D("sc_tower_spike_ene_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh15 = new TH2D("sc_tower_spike_et_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh15 = new TH2D("sc_tower_spike_ene_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh20 = new TH2D("sc_tower_spike_et_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh20 = new TH2D("sc_tower_spike_ene_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); strip_prob_et = new TH2D("strip_prob_et","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene = new TH2D("strip_prob_ene","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et = new TH2D("tower_spike_et","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene = new TH2D("tower_spike_ene","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu = new TH3D("strip_prob_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu = new TH3D("strip_prob_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu = new TH3D("tower_spike_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu = new TH3D("tower_spike_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh08 = new TH2D("strip_prob_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh08 = new TH2D("strip_prob_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh08 = new TH2D("tower_spike_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh08 = new TH2D("tower_spike_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh08 = new TH3D("strip_prob_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh08 = new TH3D("strip_prob_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh08 = new TH3D("tower_spike_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh08 = new TH3D("tower_spike_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh10 = new TH2D("strip_prob_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh10 = new TH2D("strip_prob_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh10 = new TH2D("tower_spike_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh10 = new TH2D("tower_spike_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh10 = new TH3D("strip_prob_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh10 = new TH3D("strip_prob_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh10 = new TH3D("tower_spike_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh10 = new TH3D("tower_spike_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh12 = new TH2D("strip_prob_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh12 = new TH2D("strip_prob_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh12 = new TH2D("tower_spike_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh12 = new TH2D("tower_spike_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh12 = new TH3D("strip_prob_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh12 = new TH3D("strip_prob_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh12 = new TH3D("tower_spike_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh12 = new TH3D("tower_spike_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh15 = new TH2D("strip_prob_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh15 = new TH2D("strip_prob_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh15 = new TH2D("tower_spike_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh15 = new TH2D("tower_spike_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh15 = new TH3D("strip_prob_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh15 = new TH3D("strip_prob_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh15 = new TH3D("tower_spike_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh15 = new TH3D("tower_spike_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh20 = new TH2D("strip_prob_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh20 = new TH2D("strip_prob_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh20 = new TH2D("tower_spike_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh20 = new TH2D("tower_spike_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh20 = new TH3D("strip_prob_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh20 = new TH3D("strip_prob_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh20 = new TH3D("tower_spike_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh20 = new TH3D("tower_spike_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_mod1 = new TH2D("strip_prob_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod1 = new TH2D("strip_prob_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod1 = new TH2D("tower_spike_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod1 = new TH2D("tower_spike_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod2 = new TH2D("strip_prob_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod2 = new TH2D("strip_prob_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod2 = new TH2D("tower_spike_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod2 = new TH2D("tower_spike_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod3 = new TH2D("strip_prob_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod3 = new TH2D("strip_prob_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod3 = new TH2D("tower_spike_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod3 = new TH2D("tower_spike_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod4 = new TH2D("strip_prob_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod4 = new TH2D("strip_prob_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod4 = new TH2D("tower_spike_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod4 = new TH2D("tower_spike_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_300 = new TH2D("strip_prob_et_300","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_300 = new TH2D("strip_prob_ene_300","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_300 = new TH2D("tower_spike_et_300","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_300 = new TH2D("tower_spike_ene_300","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu0 = new TH2D("strip_prob_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu0 = new TH2D("strip_prob_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu0 = new TH2D("tower_spike_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu0 = new TH2D("tower_spike_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu10 = new TH2D("strip_prob_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu10 = new TH2D("strip_prob_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu10 = new TH2D("tower_spike_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu10 = new TH2D("tower_spike_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu20 = new TH2D("strip_prob_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu20 = new TH2D("strip_prob_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu20 = new TH2D("tower_spike_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu20 = new TH2D("tower_spike_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et = new TH2D("sc_strip_prob_et","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene = new TH2D("sc_strip_prob_ene","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et = new TH2D("sc_tower_spike_et","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene = new TH2D("sc_tower_spike_ene","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu = new TH3D("sc_strip_prob_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu = new TH3D("sc_strip_prob_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu = new TH3D("sc_tower_spike_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu = new TH3D("sc_tower_spike_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh08 = new TH2D("sc_strip_prob_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh08 = new TH2D("sc_strip_prob_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh08 = new TH2D("sc_tower_spike_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh08 = new TH2D("sc_tower_spike_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh08 = new TH3D("sc_strip_prob_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh08 = new TH3D("sc_strip_prob_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh08 = new TH3D("sc_tower_spike_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh08 = new TH3D("sc_tower_spike_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh10 = new TH2D("sc_strip_prob_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh10 = new TH2D("sc_strip_prob_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh10 = new TH2D("sc_tower_spike_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh10 = new TH2D("sc_tower_spike_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh10 = new TH3D("sc_strip_prob_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh10 = new TH3D("sc_strip_prob_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh10 = new TH3D("sc_tower_spike_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh10 = new TH3D("sc_tower_spike_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh12 = new TH2D("sc_strip_prob_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh12 = new TH2D("sc_strip_prob_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh12 = new TH2D("sc_tower_spike_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh12 = new TH2D("sc_tower_spike_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh12 = new TH3D("sc_strip_prob_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh12 = new TH3D("sc_strip_prob_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh12 = new TH3D("sc_tower_spike_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh12 = new TH3D("sc_tower_spike_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh15 = new TH2D("sc_strip_prob_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh15 = new TH2D("sc_strip_prob_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh15 = new TH2D("sc_tower_spike_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh15 = new TH2D("sc_tower_spike_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh15 = new TH3D("sc_strip_prob_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh15 = new TH3D("sc_strip_prob_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh15 = new TH3D("sc_tower_spike_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh15 = new TH3D("sc_tower_spike_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh20 = new TH2D("sc_strip_prob_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh20 = new TH2D("sc_strip_prob_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh20 = new TH2D("sc_tower_spike_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh20 = new TH2D("sc_tower_spike_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh20 = new TH3D("sc_strip_prob_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh20 = new TH3D("sc_strip_prob_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh20 = new TH3D("sc_tower_spike_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh20 = new TH3D("sc_tower_spike_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_mod1 = new TH2D("sc_strip_prob_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod1 = new TH2D("sc_strip_prob_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod1 = new TH2D("sc_tower_spike_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod1 = new TH2D("sc_tower_spike_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod2 = new TH2D("sc_strip_prob_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod2 = new TH2D("sc_strip_prob_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod2 = new TH2D("sc_tower_spike_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod2 = new TH2D("sc_tower_spike_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod3 = new TH2D("sc_strip_prob_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod3 = new TH2D("sc_strip_prob_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod3 = new TH2D("sc_tower_spike_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod3 = new TH2D("sc_tower_spike_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod4 = new TH2D("sc_strip_prob_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod4 = new TH2D("sc_strip_prob_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod4 = new TH2D("sc_tower_spike_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod4 = new TH2D("sc_tower_spike_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_10 = new TH2D("sc_strip_prob_et_300","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_10 = new TH2D("sc_strip_prob_ene_300","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_10 = new TH2D("sc_tower_spike_et_300","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_10 = new TH2D("sc_tower_spike_ene_300","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu0 = new TH2D("sc_strip_prob_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu0 = new TH2D("sc_strip_prob_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu0 = new TH2D("sc_tower_spike_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu0 = new TH2D("sc_tower_spike_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu10 = new TH2D("sc_strip_prob_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu10 = new TH2D("sc_strip_prob_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu10 = new TH2D("sc_tower_spike_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu10 = new TH2D("sc_tower_spike_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu20 = new TH2D("sc_strip_prob_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu20 = new TH2D("sc_strip_prob_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu20 = new TH2D("sc_tower_spike_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu20 = new TH2D("sc_tower_spike_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); eb_timing_0 = new TH1D("eb_timing_0","",400,-100.,100.); eb_timing_200 = new TH1D("eb_timing_200","",400,-100.,100.); eb_timing_400 = new TH1D("eb_timing_400","",400,-100.,100.); eb_timing_600 = new TH1D("eb_timing_600","",400,-100.,100.); eb_timing_800 = new TH1D("eb_timing_800","",400,-100.,100.); eb_timing_1000 = new TH1D("eb_timing_1000","",400,-100.,100.); eb_timing_2000 = new TH1D("eb_timing_2000","",400,-100.,100.); eb_timing_3000 = new TH1D("eb_timing_3000","",400,-100.,100.); eb_timing_4000 = new TH1D("eb_timing_4000","",400,-100.,100.); eb_timing_5000 = new TH1D("eb_timing_5000","",400,-100.,100.); eb_timing_10000 = new TH1D("eb_timing_10000","",400,-100.,100.); eb_timing_3000_spiketag = new TH1D("eb_timing_3000_spiketag","",400,-100.,100.); eb_timing_4000_spiketag = new TH1D("eb_timing_4000_spiketag","",400,-100.,100.); eb_timing_4000_kweird = new TH1D("eb_timing_4000_kweird","",400,-100.,100.); eb_timing_4000_swisscross = new TH1D("eb_timing_4000_swisscross","",400,-100.,100.); eb_timing_4000_spiketag_kweird = new TH1D("eb_timing_4000_spiketag_kweird","",400,-100.,100.); eb_timing_4000_spiketag_swisscross = new TH1D("eb_timing_4000_spiketag_swisscross","",400,-100.,100.); eb_timing_4000_spiketag_noisedep = new TH1D("eb_timing_4000_spiketag_noisedep","",400,-100.,100.); eb_timing_4000_sctag = new TH1D("eb_timing_4000_sctag","",400,-100.,100.); eb_timing_4000_sctag_kweird = new TH1D("eb_timing_4000_sctag_kweird","",400,-100.,100.); eb_timing_4000_sctag_swisscross = new TH1D("eb_timing_4000_sctag_swisscross","",400,-100.,100.); eb_timing_4000_sctag_noisedep = new TH1D("eb_timing_4000_sctag_noisedep","",400,-100.,100.); e4_over_noise=new TH1D("e4_over_noise","",1000,0,20); e4_over_noise_spiketag=new TH1D("e4_over_noise_spiketag","",1000,0,20); e4_over_noise_sctag=new TH1D("e4_over_noise_sctag","",1000,0,20); eb_timing_10000_spiketag = new TH1D("eb_timing_10000_spiketag","",400,-100.,100.); eb_timing_10000_kweird = new TH1D("eb_timing_10000_kweird","",400,-100.,100.); eb_timing_10000_swisscross = new TH1D("eb_timing_10000_swisscross","",400,-100.,100.); eb_timing_10000_spiketag_kweird = new TH1D("eb_timing_10000_spiketag_kweird","",400,-100.,100.); eb_timing_10000_spiketag_swisscross = new TH1D("eb_timing_10000_spiketag_swisscross","",400,-100.,100.); eb_timing_10000_spiketag_noisedep = new TH1D("eb_timing_10000_spiketag_noisedep","",400,-100.,100.); eb_timing_10000_sctag = new TH1D("eb_timing_10000_sctag","",400,-100.,100.); eb_timing_10000_sctag_kweird = new TH1D("eb_timing_10000_sctag_kweird","",400,-100.,100.); eb_timing_10000_sctag_swisscross = new TH1D("eb_timing_10000_sctag_swisscross","",400,-100.,100.); eb_timing_10000_sctag_noisedep = new TH1D("eb_timing_10000_sctag_noisedep","",400,-100.,100.); spikes_vs_ieta_spiketag_4000 = new TH1D("spikes_vs_ieta_spiketag_4000","",85,0,85); spikes_vs_ieta_spiketag_4000_kweird = new TH1D("spikes_vs_ieta_spiketag_4000_kweird","",85,0,85); spikes_vs_ieta_spiketag_4000_swisscross = new TH1D("spikes_vs_ieta_spiketag_4000_swisscross","",85,0,85); spikes_vs_ieta_spiketag_4000_noisedep = new TH1D("spikes_vs_ieta_spiketag_4000_noisedep","",85,0,85); sc_vs_ieta_sctag_4000 = new TH1D("sc_vs_ieta_sctag_4000","",85,0,85); sc_vs_ieta_sctag_4000_kweird = new TH1D("sc_vs_ieta_sctag_4000_kweird","",85,0,85); sc_vs_ieta_sctag_4000_swisscross = new TH1D("sc_vs_ieta_sctag_4000_swisscross","",85,0,85); sc_vs_ieta_sctag_4000_noisedep = new TH1D("sc_vs_ieta_sctag_4000_noisedep","",85,0,85); spikes_vs_ieta_spiketag_10000 = new TH1D("spikes_vs_ieta_spiketag_10000","",85,0,85); spikes_vs_ieta_spiketag_10000_kweird = new TH1D("spikes_vs_ieta_spiketag_10000_kweird","",85,0,85); spikes_vs_ieta_spiketag_10000_swisscross = new TH1D("spikes_vs_ieta_spiketag_10000_swisscross","",85,0,85); spikes_vs_ieta_spiketag_10000_noisedep = new TH1D("spikes_vs_ieta_spiketag_10000_noisedep","",85,0,85); sc_vs_ieta_sctag_10000 = new TH1D("sc_vs_ieta_sctag_10000","",85,0,85); sc_vs_ieta_sctag_10000_kweird = new TH1D("sc_vs_ieta_sctag_10000_kweird","",85,0,85); sc_vs_ieta_sctag_10000_swisscross = new TH1D("sc_vs_ieta_sctag_10000_swisscross","",85,0,85); sc_vs_ieta_sctag_10000_noisedep = new TH1D("sc_vs_ieta_sctag_10000_noisedep","",85,0,85); swisscross_vs_ieta_spiketag_4000 = new TH2D("swisscross_vs_ieta_spiketag_4000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_4000_kweird = new TH2D("swisscross_vs_ieta_spiketag_4000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_10000 = new TH2D("swisscross_vs_ieta_spiketag_10000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_10000_kweird = new TH2D("swisscross_vs_ieta_spiketag_10000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_4000 = new TH2D("swisscross_vs_ieta_sctag_4000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_4000_kweird = new TH2D("swisscross_vs_ieta_sctag_4000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_10000 = new TH2D("swisscross_vs_ieta_sctag_10000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_10000_kweird = new TH2D("swisscross_vs_ieta_sctag_10000_kweird","",80,0.7,1.1,85,0,85); eb_r4_0 = new TH1D("eb_r4_0","",200,0.2,1.2); eb_r4_200 = new TH1D("eb_r4_200","",200,0.2,1.2); eb_r4_400 = new TH1D("eb_r4_400","",200,0.2,1.2); eb_r4_600 = new TH1D("eb_r4_600","",200,0.2,1.2); eb_r4_800 = new TH1D("eb_r4_800","",200,0.2,1.2); eb_r4_1000 = new TH1D("eb_r4_1000","",200,0.2,1.2); eb_r4_2000 = new TH1D("eb_r4_2000","",200,0.2,1.2); eb_r4_3000 = new TH1D("eb_r4_3000","",200,0.2,1.2); eb_r4_4000 = new TH1D("eb_r4_4000","",200,0.2,1.2); eb_r4_5000 = new TH1D("eb_r4_5000","",200,0.2,1.2); eb_r4_10000 = new TH1D("eb_r4_10000","",200,0.2,1.2); eb_r4_3000_spiketag = new TH1D("eb_r4_3000_spiketag","",200,0.2,1.2); eb_r4_4000_spiketag = new TH1D("eb_r4_4000_spiketag","",200,0.2,1.2); eb_r4_4000_sctag = new TH1D("eb_r4_4000_sctag","",200,0.2,1.2); eb_r4_4000_kweird = new TH1D("eb_r4_4000_kweird","",200,0.2,1.2); eb_r4_4000_swisscross = new TH1D("eb_r4_4000_swisscross","",200,0.2,1.2); eb_r4_10000_spiketag = new TH1D("eb_r4_10000_spiketag","",200,0.2,1.2); eb_r4_10000_sctag = new TH1D("eb_r4_10000_sctag","",200,0.2,1.2); eb_r4_10000_kweird = new TH1D("eb_r4_10000_kweird","",200,0.2,1.2); eb_r4_10000_swisscross = new TH1D("eb_r4_10000_swisscross","",200,0.2,1.2); eb_r6_1000 = new TH1D("eb_r6_1000","",200,0.2,1.2); eb_r6_2000 = new TH1D("eb_r6_2000","",200,0.2,1.2); eb_r6_3000 = new TH1D("eb_r6_3000","",200,0.2,1.2); eb_r6_4000 = new TH1D("eb_r6_4000","",200,0.2,1.2); eb_r6_5000 = new TH1D("eb_r6_5000","",200,0.2,1.2); eb_r6_10000 = new TH1D("eb_r6_10000","",200,0.2,1.2); eb_r4vsr6_3000 = new TH2D("eb_r4vsr6_3000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_4000 = new TH2D("eb_r4vsr6_4000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_5000 = new TH2D("eb_r4vsr6_5000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_10000 = new TH2D("eb_r4vsr6_10000","",100,0.2,1.2,100,0.2,1.2); eb_r6_3000_spiketag = new TH1D("eb_r6_3000_spiketag","",200,0.2,2.2); eb_r6_4000_spiketag = new TH1D("eb_r6_4000_spiketag","",200,0.2,2.2); eb_r6_4000_sctag = new TH1D("eb_r6_4000_spiketag","",200,0.2,2.2); eb_r6_4000_kweird = new TH1D("eb_r6_4000_kweird","",200,0.2,2.2); eb_r6_4000_swisscross = new TH1D("eb_r6_4000_swisscross","",200,0.2,2.2); eb_r6_10000_spiketag = new TH1D("eb_r6_10000_spiketag","",200,0.2,2.2); eb_r6_10000_sctag = new TH1D("eb_r6_10000_sctag","",200,0.2,2.2); eb_r6_10000_kweird = new TH1D("eb_r6_10000_kweird","",200,0.2,2.2); eb_r6_10000_swisscross = new TH1D("eb_r6_10000_swisscross","",200,0.2,2.2); time_4gev_spiketime=new TH1D("time_4gev_spiketime","",200,-100,100); time_10gev_spiketime=new TH1D("time_10gev_spiketime","",200,-100,100); time_4gev_spikekweird=new TH1D("time_4gev_spikekweird","",200,-100,100); time_10gev_spikekweird=new TH1D("time_10gev_spikekweird","",200,-100,100); time_4gev_swisscross=new TH1D("time_4gev_swisscross","",200,-100,100); time_10gev_swisscross=new TH1D("time_10gev_swisscross","",200,-100,100); pu_4gev_spiketime=new TH1D("pu_4gev_spiketime","",100,0,100); pu_10gev_spiketime=new TH1D("pu_10gev_spiketime","",100,0,100); pu_4gev_spikekweird=new TH1D("pu_4gev_spikekweird","",100,0,100); pu_10gev_spikekweird=new TH1D("pu_10gev_spikekweird","",100,0,100); pu_4gev_swisscross=new TH1D("pu_4gev_swisscross","",100,0,100); pu_10gev_swisscross=new TH1D("pu_10gev_swisscross","",100,0,100); ene_4gev_spiketime=new TH1D("ene_4gev_spiketime","",100,0,100); ene_10gev_spiketime=new TH1D("ene_10gev_spiketime","",100,0,100); ene_4gev_spikekweird=new TH1D("ene_4gev_spikekweird","",100,0,100); ene_10gev_spikekweird=new TH1D("ene_10gev_spikekweird","",100,0,100); ene_4gev_swisscross=new TH1D("ene_4gev_swisscross","",100,0,100); ene_10gev_swisscross=new TH1D("ene_10gev_swisscross","",100,0,100); pu_vs_ene_spiketime=new TH2D("pu_vs_ene_spiketime","",50,0,100,50,0,100); pu_vs_ene_spikekweird=new TH2D("pu_vs_ene_spikekweird","",50,0,100,50,0,100); pu_vs_ene_swisscross=new TH2D("pu_vs_ene_swisscross","",50,0,100,50,0,100); eb_timing_r4_0 = new TH1D("eb_timing_r4_0","",400,-100.,100.); eb_timing_r4_200 = new TH1D("eb_timing_r4_200","",400,-100.,100.); eb_timing_r4_400 = new TH1D("eb_timing_r4_400","",400,-100.,100.); eb_timing_r4_600 = new TH1D("eb_timing_r4_600","",400,-100.,100.); eb_timing_r4_800 = new TH1D("eb_timing_r4_800","",400,-100.,100.); eb_timing_r4_1000 = new TH1D("eb_timing_r4_1000","",400,-100.,100.); eb_timing_r4_2000 = new TH1D("eb_timing_r4_2000","",400,-100.,100.); eb_timing_r4_3000 = new TH1D("eb_timing_r4_3000","",400,-100.,100.); eb_timing_r4_5000 = new TH1D("eb_timing_r4_5000","",400,-100.,100.); eb_timing_vs_r4_0 = new TH2D("eb_timing_vs_r4_0","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_200 = new TH2D("eb_timing_vs_r4_200","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_400 = new TH2D("eb_timing_vs_r4_400","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_600 = new TH2D("eb_timing_vs_r4_600","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_800 = new TH2D("eb_timing_vs_r4_800","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_1000 = new TH2D("eb_timing_vs_r4_1000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_2000 = new TH2D("eb_timing_vs_r4_2000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_3000 = new TH2D("eb_timing_vs_r4_3000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_5000 = new TH2D("eb_timing_vs_r4_5000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_10000 = new TH2D("eb_timing_vs_r4_10000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_3000 = new TH2D("eb_timing_vs_r4_sctag_3000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_5000 = new TH2D("eb_timing_vs_r4_sctag_5000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_10000 = new TH2D("eb_timing_vs_r4_sctag_10000","",100,0.2,1.2,200,-100.,100.); rechiteta_vs_bxtrain_01 = new TH2D("rechiteta_vs_bxtrain_01","",40,-2,38,60,-3,3); rechiteta_vs_bxtrain_05 = new TH2D("rechiteta_vs_bxtrain_05","",40,-2,38,60,-3,3); sceta_vs_bxtrain = new TH2D("sceta_vs_bxtrain","",40,-2,38,60,-3,3); ebtime_vs_bxtrain_01 = new TH2D("ebtime_vx_bxtrain_01","",40,-2,38,200,-100,100); ebtime_vs_bxtrain_05 = new TH2D("ebtime_vx_bxtrain_05","",40,-2,38,200,-100,100); eetime_vs_bxtrain_01 = new TH2D("eetime_vx_bxtrain_01","",40,-2,38,200,-100,100); eetime_vs_bxtrain_05 = new TH2D("eetime_vx_bxtrain_05","",40,-2,38,200,-100,100); rechiteta_all=new TH1F("rechiteta_all","",100,-3,3); rechiteta_gt1et=new TH1F("rechiteta_gt1et","",100,-3,3); rechiteta_etweight=new TH1F("rechiteta_etweight","",100,-3,3); rechiteta_etweight_gt1et=new TH1F("rechiteta_etweight_gt1et","",100,-3,3); rechiteta_gt1et_pu10=new TH1F("rechiteta_gt1et_pu10","",100,-3,3); rechiteta_gt1et_pu20=new TH1F("rechiteta_gt1et_pu20","",100,-3,3); rechiteta_gt1et_pu30=new TH1F("rechiteta_gt1et_pu30","",100,-3,3); calotowereta_all=new TH1F("calotowereta_all","",100,-3,3); calotowereta_gt1et=new TH1F("calotowereta_gt1et","",100,-3,3); calotowereta_etweight=new TH1F("calotowereta_etweight","",100,-3,3); calotowereta_etweight_gt1et=new TH1F("calotowereta_etweight_gt1et","",100,-3,3); calotowereta_gt1et_pu10=new TH1F("calotowereta_gt1et_pu10","",100,-3,3); calotowereta_gt1et_pu20=new TH1F("calotowereta_gt1et_pu20","",100,-3,3); calotowereta_gt1et_pu30=new TH1F("calotowereta_gt1et_pu30","",100,-3,3); sceta_all=new TH1F("sceta_all","",100,-3,3); sceta_severity0=new TH1F("sceta_severity0","",100,-3,3); sceta_koot0=new TH1F("sceta_koot0","",100,-3,3); sceta_all_gt2=new TH1F("sceta_all_gt2","",100,-3,3); sceta_severity0_gt2=new TH1F("sceta_severity0_gt2","",100,-3,3); sceta_koot0_gt2=new TH1F("sceta_koot0_gt2","",100,-3,3); sceta_all_gt5=new TH1F("sceta_all_gt5","",100,-3,3); sceta_severity0_gt5=new TH1F("sceta_severity0_gt5","",100,-3,3); sceta_koot0_gt5=new TH1F("sceta_koot0_gt5","",100,-3,3); sceta_all_gt10=new TH1F("sceta_all_gt10","",100,-3,3); sceta_severity0_gt10=new TH1F("sceta_severity0_gt10","",100,-3,3); sceta_koot0_gt10=new TH1F("sceta_koot0_gt10","",100,-3,3); sceta_all_pueq01=new TH1F("sceta_all_pueq01","",100,-3,3); sceta_severity0_pueq01=new TH1F("sceta_severity0_pueq01","",100,-3,3); sceta_all_pueq02=new TH1F("sceta_all_pueq02","",100,-3,3); sceta_severity0_pueq02=new TH1F("sceta_severity0_pueq02","",100,-3,3); sceta_all_pueq03=new TH1F("sceta_all_pueq03","",100,-3,3); sceta_severity0_pueq03=new TH1F("sceta_severity0_pueq03","",100,-3,3); sceta_all_pueq04=new TH1F("sceta_all_pueq04","",100,-3,3); sceta_severity0_pueq04=new TH1F("sceta_severity0_pueq04","",100,-3,3); sceta_all_pueq05=new TH1F("sceta_all_pueq05","",100,-3,3); sceta_severity0_pueq05=new TH1F("sceta_severity0_pueq05","",100,-3,3); sceta_all_pueq06=new TH1F("sceta_all_pueq06","",100,-3,3); sceta_severity0_pueq06=new TH1F("sceta_severity0_pueq06","",100,-3,3); sceta_all_pueq07=new TH1F("sceta_all_pueq07","",100,-3,3); sceta_severity0_pueq07=new TH1F("sceta_severity0_pueq07","",100,-3,3); sceta_all_pueq08=new TH1F("sceta_all_pueq08","",100,-3,3); sceta_severity0_pueq08=new TH1F("sceta_severity0_pueq08","",100,-3,3); sceta_all_pueq09=new TH1F("sceta_all_pueq09","",100,-3,3); sceta_severity0_pueq09=new TH1F("sceta_severity0_pueq09","",100,-3,3); scet_eb_all=new TH1F("scet_eb_all","",200,0,100); scet_eb_severity0=new TH1F("scet_eb_severity0","",200,0,100); scet_eb_koot0=new TH1F("scet_eb_koot0","",200,0,100); scet_ee_all=new TH1F("scet_ee_all","",200,0,100); scet_ee_severity0=new TH1F("scet_ee_severity0","",200,0,100); scet_ee_koot0=new TH1F("scet_ee_koot0","",200,0,100); scet_eb_all_eta15=new TH1F("scet_eb_all_eta15","",200,0,100); scet_eb_all_eta20=new TH1F("scet_eb_all_eta20","",200,0,100); scet_eb_all_eta25=new TH1F("scet_eb_all_eta25","",200,0,100); scet_eb_all_eta15_pu10=new TH1F("scet_eb_all_eta15_pu10","",200,0,100); scet_eb_all_eta20_pu10=new TH1F("scet_eb_all_eta20_pu10","",200,0,100); scet_eb_all_eta25_pu10=new TH1F("scet_eb_all_eta25_pu10","",200,0,100); scet_eb_all_eta15_pu20=new TH1F("scet_eb_all_eta15_pu20","",200,0,100); scet_eb_all_eta20_pu20=new TH1F("scet_eb_all_eta20_pu20","",200,0,100); scet_eb_all_eta25_pu20=new TH1F("scet_eb_all_eta25_pu20","",200,0,100); scet_eb_all_eta15_pu30=new TH1F("scet_eb_all_eta15_pu30","",200,0,100); scet_eb_all_eta20_pu30=new TH1F("scet_eb_all_eta20_pu30","",200,0,100); scet_eb_all_eta25_pu30=new TH1F("scet_eb_all_eta25_pu30","",200,0,100); scet_eb_all_eta15_pueq10=new TH1F("scet_eb_all_eta15_pueq10","",200,0,100); scet_eb_all_eta20_pueq10=new TH1F("scet_eb_all_eta20_pueq10","",200,0,100); scet_eb_all_eta25_pueq10=new TH1F("scet_eb_all_eta25_pueq10","",200,0,100); scet_eb_all_eta15_pueq20=new TH1F("scet_eb_all_eta15_pueq20","",200,0,100); scet_eb_all_eta20_pueq20=new TH1F("scet_eb_all_eta20_pueq20","",200,0,100); scet_eb_all_eta25_pueq20=new TH1F("scet_eb_all_eta25_pueq20","",200,0,100); scet_ee_all_eta15=new TH1F("scet_ee_all_eta15","",200,0,100); scet_ee_all_eta20=new TH1F("scet_ee_all_eta20","",200,0,100); scet_ee_all_eta25=new TH1F("scet_ee_all_eta25","",200,0,100); scet_ee_all_eta15_pu10=new TH1F("scet_ee_all_eta15_pu10","",200,0,100); scet_ee_all_eta20_pu10=new TH1F("scet_ee_all_eta20_pu10","",200,0,100); scet_ee_all_eta25_pu10=new TH1F("scet_ee_all_eta25_pu10","",200,0,100); scet_ee_all_eta15_pu20=new TH1F("scet_ee_all_eta15_pu20","",200,0,100); scet_ee_all_eta20_pu20=new TH1F("scet_ee_all_eta20_pu20","",200,0,100); scet_ee_all_eta25_pu20=new TH1F("scet_ee_all_eta25_pu20","",200,0,100); scet_ee_all_eta15_pu30=new TH1F("scet_ee_all_eta15_pu30","",200,0,100); scet_ee_all_eta20_pu30=new TH1F("scet_ee_all_eta20_pu30","",200,0,100); scet_ee_all_eta25_pu30=new TH1F("scet_ee_all_eta25_pu30","",200,0,100); scet_ee_all_eta15_pueq10=new TH1F("scet_ee_all_eta15_pueq10","",200,0,100); scet_ee_all_eta20_pueq10=new TH1F("scet_ee_all_eta20_pueq10","",200,0,100); scet_ee_all_eta25_pueq10=new TH1F("scet_ee_all_eta25_pueq10","",200,0,100); scet_ee_all_eta15_pueq20=new TH1F("scet_ee_all_eta15_pueq20","",200,0,100); scet_ee_all_eta20_pueq20=new TH1F("scet_ee_all_eta20_pueq20","",200,0,100); scet_ee_all_eta25_pueq20=new TH1F("scet_ee_all_eta25_pueq20","",200,0,100); scsumet_eb_all_eta15=new TH1F("scsumet_eb_all_eta15","",200,0,200); scsumet_eb_all_eta20=new TH1F("scsumet_eb_all_eta20","",200,0,200); scsumet_eb_all_eta25=new TH1F("scsumet_eb_all_eta25","",200,0,200); scsumet_eb_all_eta15_pu10=new TH1F("scsumet_eb_all_eta15_pu10","",200,0,200); scsumet_eb_all_eta20_pu10=new TH1F("scsumet_eb_all_eta20_pu10","",200,0,200); scsumet_eb_all_eta25_pu10=new TH1F("scsumet_eb_all_eta25_pu10","",200,0,200); scsumet_eb_all_eta15_pu20=new TH1F("scsumet_eb_all_eta15_pu20","",200,0,200); scsumet_eb_all_eta20_pu20=new TH1F("scsumet_eb_all_eta20_pu20","",200,0,200); scsumet_eb_all_eta25_pu20=new TH1F("scsumet_eb_all_eta25_pu20","",200,0,200); scsumet_eb_all_eta15_pu30=new TH1F("scsumet_eb_all_eta15_pu30","",200,0,200); scsumet_eb_all_eta20_pu30=new TH1F("scsumet_eb_all_eta20_pu30","",200,0,200); scsumet_eb_all_eta25_pu30=new TH1F("scsumet_eb_all_eta25_pu30","",200,0,200); scsumet_eb_all_eta15_pueq10=new TH1F("scsumet_eb_all_eta15_pueq10","",200,0,200); scsumet_eb_all_eta20_pueq10=new TH1F("scsumet_eb_all_eta20_pueq10","",200,0,200); scsumet_eb_all_eta25_pueq10=new TH1F("scsumet_eb_all_eta25_pueq10","",200,0,200); scsumet_eb_all_eta15_pueq20=new TH1F("scsumet_eb_all_eta15_pueq20","",200,0,200); scsumet_eb_all_eta20_pueq20=new TH1F("scsumet_eb_all_eta20_pueq20","",200,0,200); scsumet_eb_all_eta25_pueq20=new TH1F("scsumet_eb_all_eta25_pueq20","",200,0,200); scsumet_ee_all_eta15=new TH1F("scsumet_ee_all_eta15","",200,0,200); scsumet_ee_all_eta20=new TH1F("scsumet_ee_all_eta20","",200,0,200); scsumet_ee_all_eta25=new TH1F("scsumet_ee_all_eta25","",200,0,200); scsumet_ee_all_eta15_pu10=new TH1F("scsumet_ee_all_eta15_pu10","",200,0,200); scsumet_ee_all_eta20_pu10=new TH1F("scsumet_ee_all_eta20_pu10","",200,0,200); scsumet_ee_all_eta25_pu10=new TH1F("scsumet_ee_all_eta25_pu10","",200,0,200); scsumet_ee_all_eta15_pu20=new TH1F("scsumet_ee_all_eta15_pu20","",200,0,200); scsumet_ee_all_eta20_pu20=new TH1F("scsumet_ee_all_eta20_pu20","",200,0,200); scsumet_ee_all_eta25_pu20=new TH1F("scsumet_ee_all_eta25_pu20","",200,0,200); scsumet_ee_all_eta15_pu30=new TH1F("scsumet_ee_all_eta15_pu30","",200,0,200); scsumet_ee_all_eta20_pu30=new TH1F("scsumet_ee_all_eta20_pu30","",200,0,200); scsumet_ee_all_eta25_pu30=new TH1F("scsumet_ee_all_eta25_pu30","",200,0,200); scsumet_ee_all_eta15_pueq10=new TH1F("scsumet_ee_all_eta15_pueq10","",200,0,200); scsumet_ee_all_eta20_pueq10=new TH1F("scsumet_ee_all_eta20_pueq10","",200,0,200); scsumet_ee_all_eta25_pueq10=new TH1F("scsumet_ee_all_eta25_pueq10","",200,0,200); scsumet_ee_all_eta15_pueq20=new TH1F("scsumet_ee_all_eta15_pueq20","",200,0,200); scsumet_ee_all_eta20_pueq20=new TH1F("scsumet_ee_all_eta20_pueq20","",200,0,200); scsumet_ee_all_eta25_pueq20=new TH1F("scsumet_ee_all_eta25_pueq20","",200,0,200); scet_eb_all_eta15_pueq01=new TH1F("scet_eb_all_eta15_pueq01","",200,0,100); scet_eb_all_eta20_pueq01=new TH1F("scet_eb_all_eta20_pueq01","",200,0,100); scet_eb_all_eta25_pueq01=new TH1F("scet_eb_all_eta25_pueq01","",200,0,100); scet_ee_all_eta15_pueq01=new TH1F("scet_ee_all_eta15_pueq01","",200,0,100); scet_ee_all_eta20_pueq01=new TH1F("scet_ee_all_eta20_pueq01","",200,0,100); scet_ee_all_eta25_pueq01=new TH1F("scet_ee_all_eta25_pueq01","",200,0,100); scsumet_eb_all_eta15_pueq01=new TH1F("scsumet_eb_all_eta15_pueq01","",200,0,200); scsumet_eb_all_eta20_pueq01=new TH1F("scsumet_eb_all_eta20_pueq01","",200,0,200); scsumet_eb_all_eta25_pueq01=new TH1F("scsumet_eb_all_eta25_pueq01","",200,0,200); scsumet_ee_all_eta15_pueq01=new TH1F("scsumet_ee_all_eta15_pueq01","",200,0,200); scsumet_ee_all_eta20_pueq01=new TH1F("scsumet_ee_all_eta20_pueq01","",200,0,200); scsumet_ee_all_eta25_pueq01=new TH1F("scsumet_ee_all_eta25_pueq01","",200,0,200); scet_eb_all_eta15_pueq02=new TH1F("scet_eb_all_eta15_pueq02","",200,0,100); scet_eb_all_eta20_pueq02=new TH1F("scet_eb_all_eta20_pueq02","",200,0,100); scet_eb_all_eta25_pueq02=new TH1F("scet_eb_all_eta25_pueq02","",200,0,100); scet_ee_all_eta15_pueq02=new TH1F("scet_ee_all_eta15_pueq02","",200,0,100); scet_ee_all_eta20_pueq02=new TH1F("scet_ee_all_eta20_pueq02","",200,0,100); scet_ee_all_eta25_pueq02=new TH1F("scet_ee_all_eta25_pueq02","",200,0,100); scsumet_eb_all_eta15_pueq02=new TH1F("scsumet_eb_all_eta15_pueq02","",200,0,200); scsumet_eb_all_eta20_pueq02=new TH1F("scsumet_eb_all_eta20_pueq02","",200,0,200); scsumet_eb_all_eta25_pueq02=new TH1F("scsumet_eb_all_eta25_pueq02","",200,0,200); scsumet_ee_all_eta15_pueq02=new TH1F("scsumet_ee_all_eta15_pueq02","",200,0,200); scsumet_ee_all_eta20_pueq02=new TH1F("scsumet_ee_all_eta20_pueq02","",200,0,200); scsumet_ee_all_eta25_pueq02=new TH1F("scsumet_ee_all_eta25_pueq02","",200,0,200); scet_eb_all_eta15_pueq03=new TH1F("scet_eb_all_eta15_pueq03","",200,0,100); scet_eb_all_eta20_pueq03=new TH1F("scet_eb_all_eta20_pueq03","",200,0,100); scet_eb_all_eta25_pueq03=new TH1F("scet_eb_all_eta25_pueq03","",200,0,100); scet_ee_all_eta15_pueq03=new TH1F("scet_ee_all_eta15_pueq03","",200,0,100); scet_ee_all_eta20_pueq03=new TH1F("scet_ee_all_eta20_pueq03","",200,0,100); scet_ee_all_eta25_pueq03=new TH1F("scet_ee_all_eta25_pueq03","",200,0,100); scsumet_eb_all_eta15_pueq03=new TH1F("scsumet_eb_all_eta15_pueq03","",200,0,200); scsumet_eb_all_eta20_pueq03=new TH1F("scsumet_eb_all_eta20_pueq03","",200,0,200); scsumet_eb_all_eta25_pueq03=new TH1F("scsumet_eb_all_eta25_pueq03","",200,0,200); scsumet_ee_all_eta15_pueq03=new TH1F("scsumet_ee_all_eta15_pueq03","",200,0,200); scsumet_ee_all_eta20_pueq03=new TH1F("scsumet_ee_all_eta20_pueq03","",200,0,200); scsumet_ee_all_eta25_pueq03=new TH1F("scsumet_ee_all_eta25_pueq03","",200,0,200); scet_eb_all_eta15_pueq04=new TH1F("scet_eb_all_eta15_pueq04","",200,0,100); scet_eb_all_eta20_pueq04=new TH1F("scet_eb_all_eta20_pueq04","",200,0,100); scet_eb_all_eta25_pueq04=new TH1F("scet_eb_all_eta25_pueq04","",200,0,100); scet_ee_all_eta15_pueq04=new TH1F("scet_ee_all_eta15_pueq04","",200,0,100); scet_ee_all_eta20_pueq04=new TH1F("scet_ee_all_eta20_pueq04","",200,0,100); scet_ee_all_eta25_pueq04=new TH1F("scet_ee_all_eta25_pueq04","",200,0,100); scsumet_eb_all_eta15_pueq04=new TH1F("scsumet_eb_all_eta15_pueq04","",200,0,200); scsumet_eb_all_eta20_pueq04=new TH1F("scsumet_eb_all_eta20_pueq04","",200,0,200); scsumet_eb_all_eta25_pueq04=new TH1F("scsumet_eb_all_eta25_pueq04","",200,0,200); scsumet_ee_all_eta15_pueq04=new TH1F("scsumet_ee_all_eta15_pueq04","",200,0,200); scsumet_ee_all_eta20_pueq04=new TH1F("scsumet_ee_all_eta20_pueq04","",200,0,200); scsumet_ee_all_eta25_pueq04=new TH1F("scsumet_ee_all_eta25_pueq04","",200,0,200); scet_eb_all_eta15_pueq05=new TH1F("scet_eb_all_eta15_pueq05","",200,0,100); scet_eb_all_eta20_pueq05=new TH1F("scet_eb_all_eta20_pueq05","",200,0,100); scet_eb_all_eta25_pueq05=new TH1F("scet_eb_all_eta25_pueq05","",200,0,100); scet_ee_all_eta15_pueq05=new TH1F("scet_ee_all_eta15_pueq05","",200,0,100); scet_ee_all_eta20_pueq05=new TH1F("scet_ee_all_eta20_pueq05","",200,0,100); scet_ee_all_eta25_pueq05=new TH1F("scet_ee_all_eta25_pueq05","",200,0,100); scsumet_eb_all_eta15_pueq05=new TH1F("scsumet_eb_all_eta15_pueq05","",200,0,200); scsumet_eb_all_eta20_pueq05=new TH1F("scsumet_eb_all_eta20_pueq05","",200,0,200); scsumet_eb_all_eta25_pueq05=new TH1F("scsumet_eb_all_eta25_pueq05","",200,0,200); scsumet_ee_all_eta15_pueq05=new TH1F("scsumet_ee_all_eta15_pueq05","",200,0,200); scsumet_ee_all_eta20_pueq05=new TH1F("scsumet_ee_all_eta20_pueq05","",200,0,200); scsumet_ee_all_eta25_pueq05=new TH1F("scsumet_ee_all_eta25_pueq05","",200,0,200); scet_eb_all_eta15_pueq06=new TH1F("scet_eb_all_eta15_pueq06","",200,0,100); scet_eb_all_eta20_pueq06=new TH1F("scet_eb_all_eta20_pueq06","",200,0,100); scet_eb_all_eta25_pueq06=new TH1F("scet_eb_all_eta25_pueq06","",200,0,100); scet_ee_all_eta15_pueq06=new TH1F("scet_ee_all_eta15_pueq06","",200,0,100); scet_ee_all_eta20_pueq06=new TH1F("scet_ee_all_eta20_pueq06","",200,0,100); scet_ee_all_eta25_pueq06=new TH1F("scet_ee_all_eta25_pueq06","",200,0,100); scsumet_eb_all_eta15_pueq06=new TH1F("scsumet_eb_all_eta15_pueq06","",200,0,200); scsumet_eb_all_eta20_pueq06=new TH1F("scsumet_eb_all_eta20_pueq06","",200,0,200); scsumet_eb_all_eta25_pueq06=new TH1F("scsumet_eb_all_eta25_pueq06","",200,0,200); scsumet_ee_all_eta15_pueq06=new TH1F("scsumet_ee_all_eta15_pueq06","",200,0,200); scsumet_ee_all_eta20_pueq06=new TH1F("scsumet_ee_all_eta20_pueq06","",200,0,200); scsumet_ee_all_eta25_pueq06=new TH1F("scsumet_ee_all_eta25_pueq06","",200,0,200); scet_eb_all_eta15_pueq07=new TH1F("scet_eb_all_eta15_pueq07","",200,0,100); scet_eb_all_eta20_pueq07=new TH1F("scet_eb_all_eta20_pueq07","",200,0,100); scet_eb_all_eta25_pueq07=new TH1F("scet_eb_all_eta25_pueq07","",200,0,100); scet_ee_all_eta15_pueq07=new TH1F("scet_ee_all_eta15_pueq07","",200,0,100); scet_ee_all_eta20_pueq07=new TH1F("scet_ee_all_eta20_pueq07","",200,0,100); scet_ee_all_eta25_pueq07=new TH1F("scet_ee_all_eta25_pueq07","",200,0,100); scsumet_eb_all_eta15_pueq07=new TH1F("scsumet_eb_all_eta15_pueq07","",200,0,200); scsumet_eb_all_eta20_pueq07=new TH1F("scsumet_eb_all_eta20_pueq07","",200,0,200); scsumet_eb_all_eta25_pueq07=new TH1F("scsumet_eb_all_eta25_pueq07","",200,0,200); scsumet_ee_all_eta15_pueq07=new TH1F("scsumet_ee_all_eta15_pueq07","",200,0,200); scsumet_ee_all_eta20_pueq07=new TH1F("scsumet_ee_all_eta20_pueq07","",200,0,200); scsumet_ee_all_eta25_pueq07=new TH1F("scsumet_ee_all_eta25_pueq07","",200,0,200); scet_eb_all_eta15_pueq08=new TH1F("scet_eb_all_eta15_pueq08","",200,0,100); scet_eb_all_eta20_pueq08=new TH1F("scet_eb_all_eta20_pueq08","",200,0,100); scet_eb_all_eta25_pueq08=new TH1F("scet_eb_all_eta25_pueq08","",200,0,100); scet_ee_all_eta15_pueq08=new TH1F("scet_ee_all_eta15_pueq08","",200,0,100); scet_ee_all_eta20_pueq08=new TH1F("scet_ee_all_eta20_pueq08","",200,0,100); scet_ee_all_eta25_pueq08=new TH1F("scet_ee_all_eta25_pueq08","",200,0,100); scsumet_eb_all_eta15_pueq08=new TH1F("scsumet_eb_all_eta15_pueq08","",200,0,200); scsumet_eb_all_eta20_pueq08=new TH1F("scsumet_eb_all_eta20_pueq08","",200,0,200); scsumet_eb_all_eta25_pueq08=new TH1F("scsumet_eb_all_eta25_pueq08","",200,0,200); scsumet_ee_all_eta15_pueq08=new TH1F("scsumet_ee_all_eta15_pueq08","",200,0,200); scsumet_ee_all_eta20_pueq08=new TH1F("scsumet_ee_all_eta20_pueq08","",200,0,200); scsumet_ee_all_eta25_pueq08=new TH1F("scsumet_ee_all_eta25_pueq08","",200,0,200); scet_eb_all_eta15_pueq09=new TH1F("scet_eb_all_eta15_pueq09","",200,0,100); scet_eb_all_eta20_pueq09=new TH1F("scet_eb_all_eta20_pueq09","",200,0,100); scet_eb_all_eta25_pueq09=new TH1F("scet_eb_all_eta25_pueq09","",200,0,100); scet_ee_all_eta15_pueq09=new TH1F("scet_ee_all_eta15_pueq09","",200,0,100); scet_ee_all_eta20_pueq09=new TH1F("scet_ee_all_eta20_pueq09","",200,0,100); scet_ee_all_eta25_pueq09=new TH1F("scet_ee_all_eta25_pueq09","",200,0,100); scsumet_eb_all_eta15_pueq09=new TH1F("scsumet_eb_all_eta15_pueq09","",200,0,200); scsumet_eb_all_eta20_pueq09=new TH1F("scsumet_eb_all_eta20_pueq09","",200,0,200); scsumet_eb_all_eta25_pueq09=new TH1F("scsumet_eb_all_eta25_pueq09","",200,0,200); scsumet_ee_all_eta15_pueq09=new TH1F("scsumet_ee_all_eta15_pueq09","",200,0,200); scsumet_ee_all_eta20_pueq09=new TH1F("scsumet_ee_all_eta20_pueq09","",200,0,200); scsumet_ee_all_eta25_pueq09=new TH1F("scsumet_ee_all_eta25_pueq09","",200,0,200); scsumet_eb_all=new TH1F("scsumet_eb_all","",200,0,200); scsumet_eb_severity0=new TH1F("scsumet_eb_severity0","",200,0,200); scsumet_eb_koot0=new TH1F("scsumet_eb_koot0","",200,0,200); scsumet_ee_all=new TH1F("scsumet_ee_all","",200,0,200); scsumet_ee_severity0=new TH1F("scsumet_ee_severity0","",200,0,200); scsumet_ee_koot0=new TH1F("scsumet_ee_koot0","",200,0,200); scsumet_eb_all_gt2=new TH1F("scsumet_eb_all_gt2","",200,0,200); scsumet_eb_severity0_gt2=new TH1F("scsumet_eb_severity0_gt2","",200,0,200); scsumet_eb_koot0_gt2=new TH1F("scsumet_eb_koot0_gt2","",200,0,200); scsumet_ee_all_gt2=new TH1F("scsumet_ee_all_gt2","",200,0,200); scsumet_ee_severity0_gt2=new TH1F("scsumet_ee_severity0_gt2","",200,0,200); scsumet_ee_koot0_gt2=new TH1F("scsumet_ee_koot0_gt2","",200,0,200); scsumet_eb_all_gt5=new TH1F("scsumet_eb_all_gt5","",200,0,200); scsumet_eb_severity0_gt5=new TH1F("scsumet_eb_severity0_gt5","",200,0,200); scsumet_eb_koot0_gt5=new TH1F("scsumet_eb_koot0_gt5","",200,0,200); scsumet_ee_all_gt5=new TH1F("scsumet_ee_all_gt5","",200,0,200); scsumet_ee_severity0_gt5=new TH1F("scsumet_ee_severity0_gt5","",200,0,200); scsumet_ee_koot0_gt5=new TH1F("scsumet_ee_koot0_gt5","",200,0,200); scsumet_eb_all_gt10=new TH1F("scsumet_eb_all_gt10","",200,0,200); scsumet_eb_severity0_gt10=new TH1F("scsumet_eb_severity0_gt10","",200,0,200); scsumet_eb_koot0_gt10=new TH1F("scsumet_eb_koot0_gt10","",200,0,200); scsumet_ee_all_gt10=new TH1F("scsumet_ee_all_gt10","",200,0,200); scsumet_ee_severity0_gt10=new TH1F("scsumet_ee_severity0_gt10","",200,0,200); scsumet_ee_koot0_gt10=new TH1F("scsumet_ee_koot0_gt10","",200,0,200); swisscross_vs_energy_spiketag=new TH2D("swisscross_vs_energy_spiketag","",80,0.7,1.1,100,0,20); swisscross_vs_energy_sctag=new TH2D("swisscross_vs_energy_sctag","",80,0.7,1.1,100,0,20); swisscross_vs_energy_spiketag_kweird=new TH2D("swisscross_vs_energy_spiketag_kweird","",80,0.7,1.1,100,0,20); swisscross_vs_energy_sctag_kweird=new TH2D("swisscross_vs_energy_sctag_kweird","",80,0.7,1.1,100,0,20); time_vs_energy_spiketag=new TH2D("time_vs_energy_spiketag","",120,-60,60,100,0,20); time_vs_energy_sctag=new TH2D("time_vs_energy_sctag","",120,-60,60,100,0,20); time_vs_energy_spiketag_kweird=new TH2D("time_vs_energy_spiketag_kweird","",120,-60,60,100,0,20); time_vs_energy_spiketag_swisscross=new TH2D("time_vs_energy_spiketag_swisscross","",120,-60,60,100,0,20); time_vs_energy_sctag_kweird=new TH2D("time_vs_energy_sctag_kweird","",120,-60,60,100,0,20); time_vs_energy_sctag_swisscross=new TH2D("time_vs_energy_sctag_swisscross","",120,-60,60,100,0,20); eb_digi_01=new TH2D("eb_digi_01","",10,0,10,1000,0,1000); ee_digi_01=new TH2D("ee_digi_01","",10,0,10,1000,0,1000); eb_digi_05=new TH2D("eb_digi_05","",10,0,10,1000,0,1000); ee_digi_05=new TH2D("ee_digi_05","",10,0,10,1000,0,1000); eb_digi_30=new TH2D("eb_digi_30","",10,0,10,1000,0,1000); ee_digi_30=new TH2D("ee_digi_30","",10,0,10,1000,0,1000); eb_digi_0105=new TH2D("eb_digi_0105","",10,0,10,100,190,290); ee_digi_0105=new TH2D("ee_digi_0105","",10,0,10,100,190,290); eb_digi_0530=new TH2D("eb_digi_0530","",10,0,10,200,190,390); ee_digi_0530=new TH2D("ee_digi_0530","",10,0,10,200,190,390); eb_digi_0105_vs_time=new TH2D("eb_digi_0105_vs_time","",120,-60,60,10,0,10); ee_digi_0105_vs_time=new TH2D("ee_digi_0105_vs_time","",120,-60,60,10,0,10); eb_digi_0530_vs_time=new TH2D("eb_digi_0530_vs_time","",120,-60,60,10,0,10); ee_digi_0530_vs_time=new TH2D("ee_digi_0530_vs_time","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm=new TH2D("eb_digi_0105_vs_time_norm","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm=new TH2D("ee_digi_0105_vs_time_norm","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm=new TH2D("eb_digi_0530_vs_time_norm","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm=new TH2D("ee_digi_0530_vs_time_norm","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain=new TH2D("eb_digi_0105_vs_bxtrain","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain=new TH2D("ee_digi_0105_vs_bxtrain","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain=new TH2D("eb_digi_0530_vs_bxtrain","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain=new TH2D("ee_digi_0530_vs_bxtrain","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm=new TH2D("eb_digi_0105_vs_bxtrain_norm","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm=new TH2D("ee_digi_0105_vs_bxtrain_norm","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm=new TH2D("eb_digi_0530_vs_bxtrain_norm","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm=new TH2D("ee_digi_0530_vs_bxtrain_norm","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta15=new TH2D("eb_digi_0105_vs_time_eta15","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta15=new TH2D("ee_digi_0105_vs_time_eta15","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta15=new TH2D("eb_digi_0530_vs_time_eta15","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta15=new TH2D("ee_digi_0530_vs_time_eta15","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta15=new TH2D("eb_digi_0105_vs_time_norm_eta15","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta15=new TH2D("ee_digi_0105_vs_time_norm_eta15","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta15=new TH2D("eb_digi_0530_vs_time_norm_eta15","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta15=new TH2D("ee_digi_0530_vs_time_norm_eta15","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta15=new TH2D("eb_digi_0105_vs_bxtrain_eta15","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta15=new TH2D("ee_digi_0105_vs_bxtrain_eta15","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta15=new TH2D("eb_digi_0530_vs_bxtrain_eta15","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta15=new TH2D("ee_digi_0530_vs_bxtrain_eta15","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta15=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta15=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta15=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta15=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta20=new TH2D("eb_digi_0105_vs_time_eta20","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta20=new TH2D("ee_digi_0105_vs_time_eta20","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta20=new TH2D("eb_digi_0530_vs_time_eta20","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta20=new TH2D("ee_digi_0530_vs_time_eta20","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta20=new TH2D("eb_digi_0105_vs_time_norm_eta20","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta20=new TH2D("ee_digi_0105_vs_time_norm_eta20","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta20=new TH2D("eb_digi_0530_vs_time_norm_eta20","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta20=new TH2D("ee_digi_0530_vs_time_norm_eta20","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta20=new TH2D("eb_digi_0105_vs_bxtrain_eta20","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta20=new TH2D("ee_digi_0105_vs_bxtrain_eta20","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta20=new TH2D("eb_digi_0530_vs_bxtrain_eta20","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta20=new TH2D("ee_digi_0530_vs_bxtrain_eta20","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta20=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta20=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta20=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta20=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta25=new TH2D("eb_digi_0105_vs_time_eta25","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta25=new TH2D("ee_digi_0105_vs_time_eta25","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta25=new TH2D("eb_digi_0530_vs_time_eta25","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta25=new TH2D("ee_digi_0530_vs_time_eta25","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta25=new TH2D("eb_digi_0105_vs_time_norm_eta25","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta25=new TH2D("ee_digi_0105_vs_time_norm_eta25","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta25=new TH2D("eb_digi_0530_vs_time_norm_eta25","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta25=new TH2D("ee_digi_0530_vs_time_norm_eta25","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta25=new TH2D("eb_digi_0105_vs_bxtrain_eta25","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta25=new TH2D("ee_digi_0105_vs_bxtrain_eta25","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta25=new TH2D("eb_digi_0530_vs_bxtrain_eta25","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta25=new TH2D("ee_digi_0530_vs_bxtrain_eta25","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta25=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta25=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta25=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta25=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); dataTree_ = new TTree("dataTree","dataTree"); // physics declared and technical trigger bits dataTree_->Branch("physdeclared",&physdeclared,"physdeclared/I"); dataTree_->Branch("bit36", &bit36, "bit36/I"); dataTree_->Branch("bit37", &bit37, "bit37/I"); dataTree_->Branch("bit38", &bit38, "bit38/I"); dataTree_->Branch("bit39", &bit39, "bit39/I"); dataTree_->Branch("bit40", &bit40, "bit40/I"); dataTree_->Branch("bit41", &bit41, "bit41/I"); dataTree_->Branch("bit3", &bit3, "bit3/I"); dataTree_->Branch("bit4", &bit4, "bit4/I"); dataTree_->Branch("bit9", &bit9, "bit9/I"); dataTree_->Branch("bit0", &bit0, "bit0/I"); dataTree_->Branch("eg1", &eg1, "eg1/I"); dataTree_->Branch("eg2", &eg2, "eg2/I"); dataTree_->Branch("eg5", &eg5, "eg5/I"); dataTree_->Branch("algo124", &algo124, "algo124/I"); // muon triggers dataTree_->Branch("algo54", &algo54, "algo54/I"); dataTree_->Branch("algo55", &algo55, "algo55/I"); dataTree_->Branch("algo56", &algo56, "algo56/I"); dataTree_->Branch("algo57", &algo57, "algo57/I"); dataTree_->Branch("algo58", &algo58, "algo58/I"); dataTree_->Branch("algo59", &algo59, "algo59/I"); dataTree_->Branch("algo60", &algo60, "algo60/I"); dataTree_->Branch("algo61", &algo61, "algo61/I"); dataTree_->Branch("algo62", &algo62, "algo62/I"); dataTree_->Branch("algo106", &algo106, "algo106/I"); dataTree_->Branch("algo107", &algo107, "algo107/I"); // run/event info dataTree_->Branch("run", &run, "run/I"); dataTree_->Branch("even", &even, "even/I"); dataTree_->Branch("lumi", &lumi, "lumi/I"); dataTree_->Branch("bx", &bx, "bx/I"); dataTree_->Branch("orbit", &orbit, "orbit/I"); dataTree_->Branch("time", &time, "time/F"); // tracks - for monster event cut dataTree_->Branch("ntrk", &ntrk, "ntrk/I"); dataTree_->Branch("goodtrk", &goodtrk, "goodtrk/I"); // primary vertex info dataTree_->Branch("numvtx", &numvtx, "numvtx/I"); dataTree_->Branch("numgoodvtx", &numgoodvtx, "numgoodvtx/I"); dataTree_->Branch("vtx_x", &vtx_x, "vtx_x/F"); dataTree_->Branch("vtx_y", &vtx_y, "vtx_y/F"); dataTree_->Branch("vtx_z", &vtx_z, "vtx_z/F"); dataTree_->Branch("vtx_x_err", &vtx_x_err, "vtx_x_err/F"); dataTree_->Branch("vtx_y_err", &vtx_y_err, "vtx_y_err/F"); dataTree_->Branch("vtx_z_err", &vtx_z_err, "vtx_z_err/F"); dataTree_->Branch("vtx_chi2", &vtx_chi2, "vtx_chi2/F"); dataTree_->Branch("vtx_ndof", &vtx_ndof, "vtx_ndof/F"); dataTree_->Branch("vtx_ntracks", &vtx_ntracks, "vtx_ntracks/I"); dataTree_->Branch("vtx_isfake", &vtx_isfake, "vtx_isfake/I"); dataTree_->Branch("vtx_good", &vtx_good, "vtx_good/I"); dataTree_->Branch("scale", &scale, "scale/F"); dataTree_->Branch("ebmax", &ebmax, "ebmax/F"); dataTree_->Branch("ebmaxet", &ebmaxet, "ebmaxet/F"); dataTree_->Branch("ebtime", &ebtime, "ebtime/F"); dataTree_->Branch("ebflags", &ebflags, "ebflags/I"); dataTree_->Branch("eb_ieta", &eb_ieta, "eb_ieta/I"); dataTree_->Branch("eb_iphi", &eb_iphi, "eb_iphi/I"); dataTree_->Branch("eb_eta", &eb_eta, "eb_eta/F"); dataTree_->Branch("eb_phi", &eb_phi, "eb_phi/F"); dataTree_->Branch("ebhits", &ebhits, "ebhits/I"); dataTree_->Branch("ebhits1GeV", &ebhits1GeV, "ebhits1GeV/I"); dataTree_->Branch("ebhits2GeV", &ebhits2GeV, "ebhits2GeV/I"); dataTree_->Branch("ebhits4GeV", &ebhits4GeV, "ebhits4GeV/I"); dataTree_->Branch("ebhits1GeVet", &ebhits1GeVet, "ebhits1GeVet/I"); dataTree_->Branch("ebhits2GeVet", &ebhits2GeVet, "ebhits2GeVet/I"); dataTree_->Branch("ebhits4GeVet", &ebhits4GeVet, "ebhits4GeVet/I"); dataTree_->Branch("eb_r9", &eb_r9, "eb_r9/F"); dataTree_->Branch("eb_r4", &eb_r4, "eb_r4/F"); dataTree_->Branch("eb_e9", &eb_e9, "eb_e9/F"); dataTree_->Branch("eb_e25", &eb_e25, "eb_e25/F"); dataTree_->Branch("ebmax2", &ebmax2, "ebmax2/F"); dataTree_->Branch("ebmaxet2", &ebmaxet2, "ebmaxet2/F"); dataTree_->Branch("ebtime2", &ebtime2, "ebtime2/F"); dataTree_->Branch("ebflags2", &ebflags2, "ebflags2/I"); dataTree_->Branch("eb_ieta2", &eb_ieta2, "eb_ieta2/I"); dataTree_->Branch("eb_iphi2", &eb_iphi2, "eb_iphi2/I"); dataTree_->Branch("eb_eta2", &eb_eta2, "eb_eta2/F"); dataTree_->Branch("eb_phi2", &eb_phi2, "eb_phi2/F"); dataTree_->Branch("ebhits1GeV2", &ebhits1GeV2, "ebhits1GeV2/I"); dataTree_->Branch("eb_r92", &eb_r92, "eb_r92/F"); dataTree_->Branch("eb_r42", &eb_r42, "eb_r42/F"); dataTree_->Branch("ebchi2", &ebchi2, "ebchi2/F"); dataTree_->Branch("ebchi2oot", &ebchi2oot, "ebchi2oot/F"); dataTree_->Branch("eb2chi2", &eb2chi2, "eb2chi2/F"); dataTree_->Branch("eb2chi2oot", &eb2chi2oot, "eb2chi2oot/F"); dataTree_->Branch("ebsum_gt1", &ebsum_gt1, "ebsum_gt1/F"); dataTree_->Branch("ebsum_gt2", &ebsum_gt2, "ebsum_gt2/F"); dataTree_->Branch("ebsum_gt4", &ebsum_gt4, "ebsum_gt4/F"); dataTree_->Branch("ebsum_gt1et", &ebsum_gt1et, "ebsum_gt1et/F"); dataTree_->Branch("ebsum_gt2et", &ebsum_gt2et, "ebsum_gt2et/F"); dataTree_->Branch("ebsum_gt4et", &ebsum_gt4et, "ebsum_gt4et/F"); dataTree_->Branch("eesum_gt1", &eesum_gt1, "eesum_gt1/F"); dataTree_->Branch("eesum_gt2", &eesum_gt2, "eesum_gt2/F"); dataTree_->Branch("eesum_gt4", &eesum_gt4, "eesum_gt4/F"); dataTree_->Branch("eesum_gt1et", &eesum_gt1et, "eesum_gt1et/F"); dataTree_->Branch("eesum_gt2et", &eesum_gt2et, "eesum_gt2et/F"); dataTree_->Branch("eesum_gt4et", &eesum_gt4et, "eesum_gt4et/F"); dataTree_->Branch("ebflag_kgood", &ebflag_kgood, "ebflag_kgood/I"); dataTree_->Branch("ebflag_kpoorreco", &ebflag_kpoorreco, "ebflag_kpoorreco/I"); dataTree_->Branch("ebflag_koutoftime", &ebflag_koutoftime, "ebflag_koutoftime/I"); dataTree_->Branch("ebflag_kfake", &ebflag_kfake, "ebflag_kfake/I"); dataTree_->Branch("eemax", &eemax, "eemax/F"); dataTree_->Branch("eemaxet", &eemaxet, "eemaxet/F"); dataTree_->Branch("eetime", &eetime, "eetime/F"); dataTree_->Branch("eeflags", &eeflags, "eeflags/I"); dataTree_->Branch("eeix", &eeix, "eeix/I"); dataTree_->Branch("eeiy", &eeiy, "eeiy/I"); dataTree_->Branch("eeiz", &eeiz, "eeiz/I"); dataTree_->Branch("ee_eta", &ee_eta, "ee_eta/F"); dataTree_->Branch("ee_phi", &ee_phi, "ee_phi/F"); dataTree_->Branch("eehits", &eehits, "eehits/I"); dataTree_->Branch("eehits1GeV", &eehits1GeV, "eehits1GeV/I"); dataTree_->Branch("eehits2GeV", &eehits2GeV, "eehits2GeV/I"); dataTree_->Branch("eehits4GeV", &eehits4GeV, "eehits4GeV/I"); dataTree_->Branch("eehits1GeVet", &eehits1GeVet, "eehits1GeVet/I"); dataTree_->Branch("eehits2GeVet", &eehits2GeVet, "eehits2GeVet/I"); dataTree_->Branch("eehits4GeVet", &eehits4GeVet, "eehits4GeVet/I"); dataTree_->Branch("ee_r9", &ee_r9, "ee_r9/F"); dataTree_->Branch("eephits", &eephits, "eephits/I"); dataTree_->Branch("eemhits", &eemhits, "eemhits/I"); dataTree_->Branch("eemax2", &eemax2, "eemax2/F"); dataTree_->Branch("eemaxet2", &eemaxet2, "eemaxet2/F"); dataTree_->Branch("eetime2", &eetime2, "eetime2/F"); dataTree_->Branch("eeflags2", &eeflags2, "eeflags2/I"); dataTree_->Branch("eeix2", &eeix2, "eeix2/I"); dataTree_->Branch("eeiy2", &eeiy2, "eeiy2/I"); dataTree_->Branch("eeiz2", &eeiz2, "eeiz2/I"); dataTree_->Branch("ee_eta2", &ee_eta2, "ee_eta2/F"); dataTree_->Branch("ee_phi2", &ee_phi2, "ee_phi2/F"); dataTree_->Branch("eehits1GeV2", &eehits1GeV2, "eehits1GeV2/I"); dataTree_->Branch("ee_r92", &ee_r92, "ee_r92/F"); dataTree_->Branch("tmean_en", &tmean_en, "tmean_en/F"); dataTree_->Branch("terr_en", &terr_en, "terr_en/F"); dataTree_->Branch("tmean_sig", &tmean_sig, "tmean_sig/F"); dataTree_->Branch("terr_sig", &terr_sig, "terr_sig/F"); dataTree_->Branch("r4count", &r4count, "r4count/I"); dataTree_->Branch("e2e9count_thresh0", &e2e9count_thresh0, "e2e9count_thresh0/I"); dataTree_->Branch("e2e25count_thresh0", &e2e25count_thresh0, "e2e25count_thresh0/I"); dataTree_->Branch("e2e9count_thresh1", &e2e9count_thresh1, "e2e9count_thresh1/I"); dataTree_->Branch("e2e25count_thresh1", &e2e25count_thresh1, "e2e25count_thresh1/I"); dataTree_->Branch("e2e9count_thresh0_nor4", &e2e9count_thresh0_nor4, "e2e9count_thresh0_nor4/I"); dataTree_->Branch("e2e25count_thresh0_nor4", &e2e25count_thresh0_nor4, "e2e25count_thresh0_nor4/I"); dataTree_->Branch("e2e9count_thresh1_nor4", &e2e9count_thresh1_nor4, "e2e9count_thresh1_nor4/I"); dataTree_->Branch("e2e25count_thresh1_nor4", &e2e25count_thresh1_nor4, "e2e25count_thresh1_nor4/I"); dataTree_->Branch("r4_algo_count", &r4_algo_count, "r4_algo_count/I"); dataTree_->Branch("e2e9_algo_count", &e2e9_algo_count, "e2e9_algo_count/I"); dataTree_->Branch("e2e9_algo_count_5_1", &e2e9_algo_count_5_1, "e2e9_algo_count_5_1/I"); dataTree_->Branch("e2e9_algo_count_5_0", &e2e9_algo_count_5_0, "e2e9_algo_count_5_0/I"); dataTree_->Branch("swisscross_algo", &swisscross_algo, "swisscross_algo/F"); dataTree_->Branch("e2e9_algo", &e2e9_algo, "e2e9_algo/F"); // calotowers dataTree_->Branch("ncalotower", &ncalotower, "ncalotower/I"); dataTree_->Branch("ncalotowereb", &ncalotowereb,"ncalotowereb/I"); dataTree_->Branch("ncalotoweree", &ncalotoweree,"ncalotoweree/I"); dataTree_->Branch("ncalotowerhf", &ncalotowerhf,"ncalotowerhf/I"); dataTree_->Branch("ncalotowerebgt1", &ncalotowerebgt1,"ncalotowerebgt1/I"); dataTree_->Branch("ncalotowerebgt2", &ncalotowerebgt2,"ncalotowerebgt2/I"); dataTree_->Branch("ncalotowerebgt5", &ncalotowerebgt5,"ncalotowerebgt5/I"); dataTree_->Branch("ncalotowerebgt10", &ncalotowerebgt10,"ncalotowerebgt10/I"); dataTree_->Branch("ncalotowereegt1", &ncalotowereegt1,"ncalotowereegt1/I"); dataTree_->Branch("ncalotowereegt2", &ncalotowereegt2,"ncalotowereegt2/I"); dataTree_->Branch("ncalotowereegt5", &ncalotowereegt5,"ncalotowereegt5/I"); dataTree_->Branch("ncalotowereegt10", &ncalotowereegt10,"ncalotowereegt10/I"); dataTree_->Branch("ncalotowerhfgt1", &ncalotowerhfgt1,"ncalotowerhfgt1/I"); dataTree_->Branch("ncalotowerhfgt2", &ncalotowerhfgt2,"ncalotowerhfgt2/I"); dataTree_->Branch("ncalotowerhfgt5", &ncalotowerhfgt5,"ncalotowerhfgt5/I"); dataTree_->Branch("ncalotowerhfgt10", &ncalotowerhfgt10,"ncalotowerhfgt10/I"); dataTree_->Branch("ctsumebgt1", &ctsumebgt1, "ctsumebgt1/F"); dataTree_->Branch("ctsumebgt2", &ctsumebgt2, "ctsumebgt2/F"); dataTree_->Branch("ctsumebgt5", &ctsumebgt5, "ctsumebgt5/F"); dataTree_->Branch("ctsumebgt10", &ctsumebgt10, "ctsumebgt10/F"); dataTree_->Branch("ctsumeegt1", &ctsumeegt1, "ctsumeegt1/F"); dataTree_->Branch("ctsumeegt2", &ctsumeegt2, "ctsumeegt2/F"); dataTree_->Branch("ctsumeegt5", &ctsumeegt5, "ctsumeegt5/F"); dataTree_->Branch("ctsumeegt10", &ctsumeegt10, "ctsumeegt10/F"); dataTree_->Branch("ctsumhfgt1", &ctsumhfgt1, "ctsumhfgt1/F"); dataTree_->Branch("ctsumhfgt2", &ctsumhfgt2, "ctsumhfgt2/F"); dataTree_->Branch("ctsumhfgt5", &ctsumhfgt5, "ctsumhfgt5/F"); dataTree_->Branch("ctsumhfgt10", &ctsumhfgt10, "ctsumhfgt10/F"); dataTree_->Branch("rechitsumet_eb_all", &rechitsumet_eb_all, "rechitsumet_eb_all/F"); dataTree_->Branch("rechitsumet_eb_01", &rechitsumet_eb_01, "rechitsumet_eb_01/F"); dataTree_->Branch("rechitsumet_eb_05", &rechitsumet_eb_05, "rechitsumet_eb_05/F"); dataTree_->Branch("rechitsumet_eb_0105", &rechitsumet_eb_0105, "rechitsumet_eb_0105/F"); dataTree_->Branch("rechitsumet_eb_0530", &rechitsumet_eb_0530, "rechitsumet_eb_0530/F"); dataTree_->Branch("rechitsumet_ee_all", &rechitsumet_ee_all, "rechitsumet_ee_all/F"); dataTree_->Branch("rechitsumet_ee_01", &rechitsumet_ee_01, "rechitsumet_ee_01/F"); dataTree_->Branch("rechitsumet_ee_05", &rechitsumet_ee_05, "rechitsumet_ee_05/F"); dataTree_->Branch("rechitsumet_ee_0105", &rechitsumet_ee_0105, "rechitsumet_ee_0105/F"); dataTree_->Branch("rechitsumet_ee_0530", &rechitsumet_ee_0530, "rechitsumet_ee_0530/F"); dataTree_->Branch("bunchintrain", &bunchintrain, "bunchintrain/I"); dataTree_->Branch("ebnumsc_all", &ebnumsc_all, "ebnumsc_all/I"); dataTree_->Branch("eenumsc_all", &eenumsc_all, "eenumsc_all/I"); dataTree_->Branch("ebscsumet_all", &ebscsumet_all, "ebscsumet_all/F"); dataTree_->Branch("eescsumet_all", &eescsumet_all, "eescsumet_all/F"); dataTree_->Branch("ebscsumet_all_eta15", &ebscsumet_all_eta15, "ebscsumet_all_eta15/F"); dataTree_->Branch("ebscsumet_all_eta20", &ebscsumet_all_eta20, "ebscsumet_all_eta20/F"); dataTree_->Branch("ebscsumet_all_eta25", &ebscsumet_all_eta25, "ebscsumet_all_eta25/F"); dataTree_->Branch("eescsumet_all_eta15", &eescsumet_all_eta15, "eescsumet_all_eta15/F"); dataTree_->Branch("eescsumet_all_eta20", &eescsumet_all_eta20, "eescsumet_all_eta20/F"); dataTree_->Branch("eescsumet_all_eta25", &eescsumet_all_eta25, "eescsumet_all_eta25/F"); dataTree_->Branch("ebnumrechits_01", &ebnumrechits_01, "ebnumrechits_01/I"); dataTree_->Branch("ebnumrechits_0105", &ebnumrechits_0105, "ebnumrechits_0105/I"); dataTree_->Branch("ebnumrechits_05", &ebnumrechits_05, "ebnumrechits_05/I"); dataTree_->Branch("ebnumrechits_0530", &ebnumrechits_0530, "ebnumrechits_0530/I"); dataTree_->Branch("eenumrechits_01", &eenumrechits_01, "eenumrechits_01/I"); dataTree_->Branch("eenumrechits_0105", &eenumrechits_0105, "eenumrechits_0105/I"); dataTree_->Branch("eenumrechits_05", &eenumrechits_05, "eenumrechits_05/I"); dataTree_->Branch("eenumrechits_0530", &eenumrechits_0530, "eenumrechits_0530/I"); dataTree_->Branch("numspikes", &numspikes, "numspikes/I"); dataTree_->Branch("numspikes50", &numspikes50, "numspikes50/I"); dataTree_->Branch("numspikes100", &numspikes100, "numspikes100/I"); dataTree_->Branch("numspikes_kweird", &numspikes_kweird, "numspikes_kweird/I"); dataTree_->Branch("numspikes_swisscross", &numspikes_swisscross, "numspikes_swisscross/I"); } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyserMC::endJob() { cout << "in endjob" << endl; if (file_ !=0) { file_->cd(); cout << "BP1" << endl; tower_spike_ene_swiss_t10->Write(); tower_spike_ene_swiss_t07->Write(); tower_spike_ene_swiss_t05->Write(); tower_spike_ene_swiss_t04->Write(); tower_spike_ene_swiss_t03->Write(); tower_spike_ene_swiss_t10_thresh08->Write(); tower_spike_ene_swiss_t07_thresh08->Write(); tower_spike_ene_swiss_t05_thresh08->Write(); tower_spike_ene_swiss_t04_thresh08->Write(); tower_spike_ene_swiss_t03_thresh08->Write(); tower_spike_ene_swiss_t10_thresh10->Write(); tower_spike_ene_swiss_t07_thresh10->Write(); tower_spike_ene_swiss_t05_thresh10->Write(); tower_spike_ene_swiss_t04_thresh10->Write(); tower_spike_ene_swiss_t03_thresh10->Write(); tower_spike_ene_swiss_t10_thresh12->Write(); tower_spike_ene_swiss_t07_thresh12->Write(); tower_spike_ene_swiss_t05_thresh12->Write(); tower_spike_ene_swiss_t04_thresh12->Write(); tower_spike_ene_swiss_t03_thresh12->Write(); tower_spike_ene_swiss_t10_thresh15->Write(); tower_spike_ene_swiss_t07_thresh15->Write(); tower_spike_ene_swiss_t05_thresh15->Write(); tower_spike_ene_swiss_t04_thresh15->Write(); tower_spike_ene_swiss_t03_thresh15->Write(); tower_spike_ene_swiss_t10_thresh20->Write(); tower_spike_ene_swiss_t07_thresh20->Write(); tower_spike_ene_swiss_t05_thresh20->Write(); tower_spike_ene_swiss_t04_thresh20->Write(); tower_spike_ene_swiss_t03_thresh20->Write(); cout << "BP2" << endl; sc_tower_spike_ene_swiss_t10->Write(); sc_tower_spike_ene_swiss_t07->Write(); sc_tower_spike_ene_swiss_t05->Write(); sc_tower_spike_ene_swiss_t04->Write(); sc_tower_spike_ene_swiss_t03->Write(); sc_tower_spike_ene_swiss_t10_thresh08->Write(); sc_tower_spike_ene_swiss_t07_thresh08->Write(); sc_tower_spike_ene_swiss_t05_thresh08->Write(); sc_tower_spike_ene_swiss_t04_thresh08->Write(); sc_tower_spike_ene_swiss_t03_thresh08->Write(); sc_tower_spike_ene_swiss_t10_thresh10->Write(); sc_tower_spike_ene_swiss_t07_thresh10->Write(); sc_tower_spike_ene_swiss_t05_thresh10->Write(); sc_tower_spike_ene_swiss_t04_thresh10->Write(); sc_tower_spike_ene_swiss_t03_thresh10->Write(); sc_tower_spike_ene_swiss_t10_thresh12->Write(); sc_tower_spike_ene_swiss_t07_thresh12->Write(); sc_tower_spike_ene_swiss_t05_thresh12->Write(); sc_tower_spike_ene_swiss_t04_thresh12->Write(); sc_tower_spike_ene_swiss_t03_thresh12->Write(); sc_tower_spike_ene_swiss_t10_thresh15->Write(); sc_tower_spike_ene_swiss_t07_thresh15->Write(); sc_tower_spike_ene_swiss_t05_thresh15->Write(); sc_tower_spike_ene_swiss_t04_thresh15->Write(); sc_tower_spike_ene_swiss_t03_thresh15->Write(); sc_tower_spike_ene_swiss_t10_thresh20->Write(); sc_tower_spike_ene_swiss_t07_thresh20->Write(); sc_tower_spike_ene_swiss_t05_thresh20->Write(); sc_tower_spike_ene_swiss_t04_thresh20->Write(); sc_tower_spike_ene_swiss_t03_thresh20->Write(); cout << "BP3" << endl; tower_spike_et_swisstt->Write(); tower_spike_ene_swisstt->Write(); tower_spike_et_swisstt_thresh08->Write(); tower_spike_ene_swisstt_thresh08->Write(); tower_spike_et_swisstt_thresh10->Write(); tower_spike_ene_swisstt_thresh10->Write(); tower_spike_et_swisstt_thresh12->Write(); tower_spike_ene_swisstt_thresh12->Write(); tower_spike_et_swisstt_thresh15->Write(); tower_spike_ene_swisstt_thresh15->Write(); tower_spike_et_swisstt_thresh20->Write(); tower_spike_ene_swisstt_thresh20->Write(); sc_tower_spike_et_swisstt->Write(); sc_tower_spike_ene_swisstt->Write(); sc_tower_spike_et_swisstt_thresh08->Write(); sc_tower_spike_ene_swisstt_thresh08->Write(); sc_tower_spike_et_swisstt_thresh10->Write(); sc_tower_spike_ene_swisstt_thresh10->Write(); sc_tower_spike_et_swisstt_thresh12->Write(); sc_tower_spike_ene_swisstt_thresh12->Write(); sc_tower_spike_et_swisstt_thresh15->Write(); sc_tower_spike_ene_swisstt_thresh15->Write(); sc_tower_spike_et_swisstt_thresh20->Write(); sc_tower_spike_ene_swisstt_thresh20->Write(); tower_spike_et_swiss->Write(); tower_spike_ene_swiss->Write(); tower_spike_et_swiss_thresh08->Write(); tower_spike_ene_swiss_thresh08->Write(); tower_spike_et_swiss_thresh10->Write(); tower_spike_ene_swiss_thresh10->Write(); tower_spike_et_swiss_thresh12->Write(); tower_spike_ene_swiss_thresh12->Write(); tower_spike_et_swiss_thresh15->Write(); tower_spike_ene_swiss_thresh15->Write(); tower_spike_et_swiss_thresh20->Write(); tower_spike_ene_swiss_thresh20->Write(); sc_tower_spike_et_swiss->Write(); sc_tower_spike_ene_swiss->Write(); sc_tower_spike_et_swiss_thresh08->Write(); sc_tower_spike_ene_swiss_thresh08->Write(); sc_tower_spike_et_swiss_thresh10->Write(); sc_tower_spike_ene_swiss_thresh10->Write(); sc_tower_spike_et_swiss_thresh12->Write(); sc_tower_spike_ene_swiss_thresh12->Write(); sc_tower_spike_et_swiss_thresh15->Write(); sc_tower_spike_ene_swiss_thresh15->Write(); sc_tower_spike_et_swiss_thresh20->Write(); sc_tower_spike_ene_swiss_thresh20->Write(); noise2d->Write(); histo_event_->Write(); eb_rechitenergy_->Write(); ee_rechitenergy_->Write(); spike_timevset_all_08->Write(); spike_timevset_highest_08->Write(); spike_timevset_koot_all_08->Write(); spike_timevset_koot_highest_08->Write(); spike_timevset_kdiweird_all_08->Write(); spike_timevset_kdiweird_highest_08->Write(); spike_timevset_all_07->Write(); spike_timevset_highest_07->Write(); spike_timevset_koot_all_07->Write(); spike_timevset_koot_highest_07->Write(); spike_timevset_kdiweird_all_07->Write(); spike_timevset_kdiweird_highest_07->Write(); spike_timevset_all_06->Write(); spike_timevset_highest_06->Write(); spike_timevset_koot_all_06->Write(); spike_timevset_koot_highest_06->Write(); spike_timevset_kdiweird_all_06->Write(); spike_timevset_kdiweird_highest_06->Write(); eb_rechitenergy_spiketag->Write(); eb_rechitenergy_sctag->Write(); eb_rechitenergy_kweird->Write(); eb_rechitenergy_knotweird->Write(); eb_rechitenergy_swisscross->Write(); cout << "p1" << endl; ee_rechitenergy_notypeb_->Write(); eb_rechitenergy_spiketag_kweird->Write(); eb_rechitenergy_spiketag_swisscross->Write(); eb_rechitenergy_spiketag_noisedep->Write(); eb_rechitenergy_sctag_kweird->Write(); eb_rechitenergy_sctag_swisscross->Write(); eb_rechitenergy_sctag_noisedep->Write(); swisscross_vs_energy_spiketag->Write(); swisscross_vs_energy_spiketag_kweird->Write(); swisscross_vs_energy_sctag->Write(); swisscross_vs_energy_sctag_kweird->Write(); cout << "p2" << endl; e4_over_noise->Write(); e4_over_noise_spiketag->Write(); e4_over_noise_sctag->Write(); time_4gev_spiketime->Write(); time_10gev_spiketime->Write(); time_4gev_spikekweird->Write(); time_10gev_spikekweird->Write(); time_4gev_swisscross->Write(); time_10gev_swisscross->Write(); pu_4gev_spiketime->Write(); pu_10gev_spiketime->Write(); pu_4gev_spikekweird->Write(); pu_10gev_spikekweird->Write(); pu_4gev_swisscross->Write(); pu_10gev_swisscross->Write(); ene_4gev_spiketime->Write(); ene_10gev_spiketime->Write(); ene_4gev_spikekweird->Write(); ene_10gev_spikekweird->Write(); ene_4gev_swisscross->Write(); ene_10gev_swisscross->Write(); pu_vs_ene_spiketime->Write(); pu_vs_ene_spikekweird->Write(); pu_vs_ene_swisscross->Write(); eb_rechitenergy_02->Write(); eb_rechitenergy_04->Write(); eb_rechitenergy_06->Write(); eb_rechitenergy_08->Write(); eb_rechitenergy_10->Write(); eb_rechitenergy_12->Write(); eb_rechitenergy_14->Write(); eb_rechitenergy_148->Write(); ee_rechitet_16->Write(); ee_rechitet_18->Write(); ee_rechitet_20->Write(); ee_rechitet_22->Write(); ee_rechitet_24->Write(); ee_rechitet_26->Write(); ee_rechitet_28->Write(); ee_rechitet_30->Write(); eb_rechitet_02->Write(); eb_rechitet_04->Write(); eb_rechitet_06->Write(); eb_rechitet_08->Write(); eb_rechitet_10->Write(); eb_rechitet_12->Write(); eb_rechitet_14->Write(); eb_rechitet_148->Write(); ee_rechitenergy_16->Write(); ee_rechitenergy_18->Write(); ee_rechitenergy_20->Write(); ee_rechitenergy_22->Write(); ee_rechitenergy_24->Write(); ee_rechitenergy_26->Write(); ee_rechitenergy_28->Write(); ee_rechitenergy_30->Write(); eb_rechitetvspu_05->Write(); eb_rechitetvspu_10->Write(); eb_rechitetvspu_15->Write(); ee_rechitetvspu_20->Write(); ee_rechitetvspu_25->Write(); ee_rechitetvspu_30->Write(); eb_rechitet_->Write(); ee_rechitet_->Write(); eb_rechiten_vs_eta->Write(); eb_rechitet_vs_eta->Write(); eep_rechiten_vs_eta->Write(); eep_rechiten_vs_phi->Write(); eem_rechiten_vs_eta->Write(); eem_rechiten_vs_phi->Write(); eep_rechitet_vs_eta->Write(); eep_rechitet_vs_phi->Write(); eem_rechitet_vs_eta->Write(); eem_rechitet_vs_phi->Write(); ebocc->Write(); eboccgt1->Write(); eboccgt3->Write(); eboccgt5->Write(); eboccgt1et->Write(); eboccet->Write(); eboccetgt1et->Write(); eboccen->Write(); eboccengt1->Write(); eeocc->Write(); eeoccgt1->Write(); eeoccgt1et->Write(); eeoccet->Write(); eeoccetgt1et->Write(); eeoccen->Write(); eeoccengt1->Write(); eb_timing_0->Write(); eb_timing_200->Write(); eb_timing_400->Write(); eb_timing_600->Write(); eb_timing_800->Write(); eb_timing_1000->Write(); eb_timing_2000->Write(); eb_timing_3000->Write(); eb_timing_4000->Write(); eb_timing_5000->Write(); eb_timing_10000->Write(); eb_timing_3000_spiketag->Write(); eb_timing_4000_spiketag->Write(); eb_timing_4000_kweird->Write(); eb_timing_4000_swisscross->Write(); eb_timing_4000_spiketag_kweird->Write(); eb_timing_4000_spiketag_swisscross->Write(); eb_timing_4000_spiketag_noisedep->Write(); cout << "p3" << endl; eb_timing_4000_sctag->Write(); eb_timing_4000_sctag_kweird->Write(); eb_timing_4000_sctag_swisscross->Write(); eb_timing_4000_sctag_noisedep->Write(); eb_timing_10000_spiketag->Write(); eb_timing_10000_kweird->Write(); eb_timing_10000_swisscross->Write(); eb_timing_10000_spiketag_kweird->Write(); eb_timing_10000_spiketag_swisscross->Write(); eb_timing_10000_spiketag_noisedep->Write(); eb_timing_10000_sctag->Write(); eb_timing_10000_sctag_kweird->Write(); eb_timing_10000_sctag_swisscross->Write(); eb_timing_10000_sctag_noisedep->Write(); cout << "p4" << endl; spikes_vs_ieta_spiketag_4000->Write(); spikes_vs_ieta_spiketag_4000_kweird->Write(); spikes_vs_ieta_spiketag_4000_swisscross->Write(); spikes_vs_ieta_spiketag_4000_noisedep->Write(); spikes_vs_ieta_spiketag_10000->Write(); spikes_vs_ieta_spiketag_10000_kweird->Write(); spikes_vs_ieta_spiketag_10000_swisscross->Write(); spikes_vs_ieta_spiketag_10000_noisedep->Write(); sc_vs_ieta_sctag_4000->Write(); sc_vs_ieta_sctag_4000_kweird->Write(); sc_vs_ieta_sctag_4000_swisscross->Write(); sc_vs_ieta_sctag_4000_noisedep->Write(); sc_vs_ieta_sctag_10000->Write(); sc_vs_ieta_sctag_10000_kweird->Write(); sc_vs_ieta_sctag_10000_swisscross->Write(); sc_vs_ieta_sctag_10000_noisedep->Write(); cout << "p5" << endl; swisscross_vs_ieta_spiketag_4000->Write(); swisscross_vs_ieta_spiketag_4000_kweird->Write(); swisscross_vs_ieta_spiketag_10000->Write(); swisscross_vs_ieta_spiketag_10000_kweird->Write(); swisscross_vs_ieta_sctag_4000->Write(); swisscross_vs_ieta_sctag_4000_kweird->Write(); swisscross_vs_ieta_sctag_10000->Write(); swisscross_vs_ieta_sctag_10000_kweird->Write(); cout << "p6" << endl; strip_prob_et->Write(); strip_prob_ene->Write(); tower_spike_et->Write(); tower_spike_ene->Write(); strip_prob_et_pu->Write(); strip_prob_ene_pu->Write(); tower_spike_et_pu->Write(); tower_spike_ene_pu->Write(); strip_prob_et_thresh08->Write(); strip_prob_ene_thresh08->Write(); tower_spike_et_thresh08->Write(); tower_spike_ene_thresh08->Write(); strip_prob_et_pu_thresh08->Write(); strip_prob_ene_pu_thresh08->Write(); tower_spike_et_pu_thresh08->Write(); tower_spike_ene_pu_thresh08->Write(); strip_prob_et_thresh10->Write(); strip_prob_ene_thresh10->Write(); tower_spike_et_thresh10->Write(); tower_spike_ene_thresh10->Write(); strip_prob_et_pu_thresh10->Write(); strip_prob_ene_pu_thresh10->Write(); tower_spike_et_pu_thresh10->Write(); tower_spike_ene_pu_thresh10->Write(); strip_prob_et_thresh12->Write(); strip_prob_ene_thresh12->Write(); tower_spike_et_thresh12->Write(); tower_spike_ene_thresh12->Write(); strip_prob_et_pu_thresh12->Write(); strip_prob_ene_pu_thresh12->Write(); tower_spike_et_pu_thresh12->Write(); tower_spike_ene_pu_thresh12->Write(); strip_prob_et_thresh15->Write(); strip_prob_ene_thresh15->Write(); tower_spike_et_thresh15->Write(); tower_spike_ene_thresh15->Write(); strip_prob_et_pu_thresh15->Write(); strip_prob_ene_pu_thresh15->Write(); tower_spike_et_pu_thresh15->Write(); tower_spike_ene_pu_thresh15->Write(); strip_prob_et_thresh20->Write(); strip_prob_ene_thresh20->Write(); tower_spike_et_thresh20->Write(); tower_spike_ene_thresh20->Write(); strip_prob_et_pu_thresh20->Write(); strip_prob_ene_pu_thresh20->Write(); tower_spike_et_pu_thresh20->Write(); tower_spike_ene_pu_thresh20->Write(); strip_prob_et_300->Write(); strip_prob_ene_300->Write(); tower_spike_et_300->Write(); tower_spike_ene_300->Write(); strip_prob_et_mod1->Write(); strip_prob_ene_mod1->Write(); tower_spike_et_mod1->Write(); tower_spike_ene_mod1->Write(); strip_prob_et_mod2->Write(); strip_prob_ene_mod2->Write(); tower_spike_et_mod2->Write(); tower_spike_ene_mod2->Write(); strip_prob_et_mod3->Write(); strip_prob_ene_mod3->Write(); tower_spike_et_mod3->Write(); tower_spike_ene_mod3->Write(); strip_prob_et_mod4->Write(); strip_prob_ene_mod4->Write(); tower_spike_et_mod4->Write(); tower_spike_ene_mod4->Write(); strip_prob_et_pu0->Write(); strip_prob_ene_pu0->Write(); tower_spike_et_pu0->Write(); tower_spike_ene_pu0->Write(); strip_prob_et_pu10->Write(); strip_prob_ene_pu10->Write(); tower_spike_et_pu10->Write(); tower_spike_ene_pu10->Write(); strip_prob_et_pu20->Write(); strip_prob_ene_pu20->Write(); tower_spike_et_pu20->Write(); tower_spike_ene_pu20->Write(); sc_strip_prob_et->Write(); sc_strip_prob_ene->Write(); sc_tower_spike_et->Write(); sc_tower_spike_ene->Write(); sc_strip_prob_et_pu->Write(); sc_strip_prob_ene_pu->Write(); sc_tower_spike_et_pu->Write(); sc_tower_spike_ene_pu->Write(); sc_strip_prob_et_10->Write(); sc_strip_prob_ene_10->Write(); sc_tower_spike_et_10->Write(); sc_tower_spike_ene_10->Write(); sc_strip_prob_et_mod1->Write(); sc_strip_prob_ene_mod1->Write(); sc_tower_spike_et_mod1->Write(); sc_tower_spike_ene_mod1->Write(); sc_strip_prob_et_mod2->Write(); sc_strip_prob_ene_mod2->Write(); sc_tower_spike_et_mod2->Write(); sc_tower_spike_ene_mod2->Write(); sc_strip_prob_et_mod3->Write(); sc_strip_prob_ene_mod3->Write(); sc_tower_spike_et_mod3->Write(); sc_tower_spike_ene_mod3->Write(); sc_strip_prob_et_mod4->Write(); sc_strip_prob_ene_mod4->Write(); sc_tower_spike_et_mod4->Write(); sc_tower_spike_ene_mod4->Write(); sc_strip_prob_et_pu0->Write(); sc_strip_prob_ene_pu0->Write(); sc_tower_spike_et_pu0->Write(); sc_tower_spike_ene_pu0->Write(); sc_strip_prob_et_pu10->Write(); sc_strip_prob_ene_pu10->Write(); sc_tower_spike_et_pu10->Write(); sc_tower_spike_ene_pu10->Write(); sc_strip_prob_et_pu20->Write(); sc_strip_prob_ene_pu20->Write(); sc_tower_spike_et_pu20->Write(); sc_tower_spike_ene_pu20->Write(); sc_strip_prob_et_thresh08->Write(); sc_strip_prob_ene_thresh08->Write(); sc_tower_spike_et_thresh08->Write(); sc_tower_spike_ene_thresh08->Write(); sc_strip_prob_et_pu_thresh08->Write(); sc_strip_prob_ene_pu_thresh08->Write(); sc_tower_spike_et_pu_thresh08->Write(); sc_tower_spike_ene_pu_thresh08->Write(); sc_strip_prob_et_thresh10->Write(); sc_strip_prob_ene_thresh10->Write(); sc_tower_spike_et_thresh10->Write(); sc_tower_spike_ene_thresh10->Write(); sc_strip_prob_et_pu_thresh10->Write(); sc_strip_prob_ene_pu_thresh10->Write(); sc_tower_spike_et_pu_thresh10->Write(); sc_tower_spike_ene_pu_thresh10->Write(); sc_strip_prob_et_thresh12->Write(); sc_strip_prob_ene_thresh12->Write(); sc_tower_spike_et_thresh12->Write(); sc_tower_spike_ene_thresh12->Write(); sc_strip_prob_et_pu_thresh12->Write(); sc_strip_prob_ene_pu_thresh12->Write(); sc_tower_spike_et_pu_thresh12->Write(); sc_tower_spike_ene_pu_thresh12->Write(); sc_strip_prob_et_thresh15->Write(); sc_strip_prob_ene_thresh15->Write(); sc_tower_spike_et_thresh15->Write(); sc_tower_spike_ene_thresh15->Write(); sc_strip_prob_et_pu_thresh15->Write(); sc_strip_prob_ene_pu_thresh15->Write(); sc_tower_spike_et_pu_thresh15->Write(); sc_tower_spike_ene_pu_thresh15->Write(); sc_strip_prob_et_thresh20->Write(); sc_strip_prob_ene_thresh20->Write(); sc_tower_spike_et_thresh20->Write(); sc_tower_spike_ene_thresh20->Write(); sc_strip_prob_et_pu_thresh20->Write(); sc_strip_prob_ene_pu_thresh20->Write(); sc_tower_spike_et_pu_thresh20->Write(); sc_tower_spike_ene_pu_thresh20->Write(); eb_r4_0->Write(); eb_r4_200->Write(); eb_r4_400->Write(); eb_r4_600->Write(); eb_r4_800->Write(); eb_r4_1000->Write(); eb_r4_2000->Write(); eb_r4_3000->Write(); eb_r4_4000->Write(); eb_r4_5000->Write(); eb_r4_10000->Write(); cout << "p7" << endl; eb_r4_3000_spiketag->Write(); eb_r4_4000_spiketag->Write(); eb_r4_4000_sctag->Write(); eb_r4_4000_kweird->Write(); eb_r4_4000_swisscross->Write(); eb_r4_10000_spiketag->Write(); eb_r4_10000_sctag->Write(); eb_r4_10000_kweird->Write(); eb_r4_10000_swisscross->Write(); eb_r6_1000->Write(); eb_r6_2000->Write(); eb_r6_3000->Write(); eb_r6_4000->Write(); eb_r6_5000->Write(); eb_r6_10000->Write(); eb_r6_3000_spiketag->Write(); eb_r6_4000_spiketag->Write(); eb_r6_4000_sctag->Write(); eb_r6_4000_kweird->Write(); eb_r6_4000_swisscross->Write(); eb_r6_10000_spiketag->Write(); eb_r6_10000_sctag->Write(); eb_r6_10000_kweird->Write(); eb_r6_10000_swisscross->Write(); cout << "p8" << endl; eb_r4vsr6_3000->Write(); eb_r4vsr6_4000->Write(); eb_r4vsr6_5000->Write(); eb_r4vsr6_10000->Write(); eb_timing_r4_0->Write(); eb_timing_r4_200->Write(); eb_timing_r4_400->Write(); eb_timing_r4_600->Write(); eb_timing_r4_800->Write(); eb_timing_r4_1000->Write(); eb_timing_r4_2000->Write(); eb_timing_r4_3000->Write(); eb_timing_r4_5000->Write(); eb_timing_vs_r4_0->Write(); eb_timing_vs_r4_200->Write(); eb_timing_vs_r4_400->Write(); eb_timing_vs_r4_600->Write(); eb_timing_vs_r4_800->Write(); eb_timing_vs_r4_1000->Write(); eb_timing_vs_r4_2000->Write(); eb_timing_vs_r4_3000->Write(); eb_timing_vs_r4_5000->Write(); eb_timing_vs_r4_10000->Write(); eb_timing_vs_r4_sctag_3000->Write(); eb_timing_vs_r4_sctag_5000->Write(); eb_timing_vs_r4_sctag_10000->Write(); spikeadc->Write(); spiketime50->Write(); rechiteta_all->Write(); rechiteta_gt1et->Write(); rechiteta_etweight->Write(); rechiteta_gt1et_pu10->Write(); rechiteta_gt1et_pu20->Write(); rechiteta_gt1et_pu30->Write(); calotowereta_all->Write(); calotowereta_gt1et->Write(); calotowereta_etweight->Write(); calotowereta_gt1et_pu10->Write(); calotowereta_gt1et_pu20->Write(); calotowereta_gt1et_pu30->Write(); sceta_all->Write(); sceta_severity0->Write(); sceta_koot0->Write(); sceta_all_pueq01->Write(); sceta_severity0_pueq01->Write(); sceta_all_pueq02->Write(); sceta_severity0_pueq02->Write(); sceta_all_pueq03->Write(); sceta_severity0_pueq03->Write(); sceta_all_pueq04->Write(); sceta_severity0_pueq04->Write(); sceta_all_pueq05->Write(); sceta_severity0_pueq05->Write(); sceta_all_pueq06->Write(); sceta_severity0_pueq06->Write(); sceta_all_pueq07->Write(); sceta_severity0_pueq07->Write(); sceta_all_pueq08->Write(); sceta_severity0_pueq08->Write(); sceta_all_pueq09->Write(); sceta_severity0_pueq09->Write(); sceta_all_gt2->Write(); sceta_severity0_gt2->Write(); sceta_koot0_gt2->Write(); sceta_all_gt5->Write(); sceta_severity0_gt5->Write(); sceta_koot0_gt5->Write(); sceta_all_gt10->Write(); sceta_severity0_gt10->Write(); sceta_koot0_gt10->Write(); scet_eb_all->Write(); scet_eb_severity0->Write(); scet_eb_koot0->Write(); scet_ee_all->Write(); scet_ee_severity0->Write(); scet_ee_koot0->Write(); scsumet_eb_all->Write(); scsumet_eb_severity0->Write(); scsumet_eb_koot0->Write(); scsumet_ee_all->Write(); scsumet_ee_severity0->Write(); scsumet_ee_koot0->Write(); scsumet_eb_all_gt2->Write(); scsumet_eb_severity0_gt2->Write(); scsumet_eb_koot0_gt2->Write(); scsumet_ee_all_gt2->Write(); scsumet_ee_severity0_gt2->Write(); scsumet_ee_koot0_gt2->Write(); scsumet_eb_all_gt5->Write(); scsumet_eb_severity0_gt5->Write(); scsumet_eb_koot0_gt5->Write(); scsumet_ee_all_gt5->Write(); scsumet_ee_severity0_gt5->Write(); scsumet_ee_koot0_gt5->Write(); scsumet_eb_all_gt10->Write(); scsumet_eb_severity0_gt10->Write(); scsumet_eb_koot0_gt10->Write(); scsumet_ee_all_gt10->Write(); scsumet_ee_severity0_gt10->Write(); scsumet_ee_koot0_gt10->Write(); scocc_eb_gt50->Write(); scocc_ee_gt50->Write(); scet_eb_all_eta15->Write(); scet_eb_all_eta20->Write(); scet_eb_all_eta25->Write(); scet_ee_all_eta15->Write(); scet_ee_all_eta20->Write(); scet_ee_all_eta25->Write(); scet_eb_all_eta15_pu10->Write(); scet_eb_all_eta20_pu10->Write(); scet_eb_all_eta25_pu10->Write(); scet_ee_all_eta15_pu10->Write(); scet_ee_all_eta20_pu10->Write(); scet_ee_all_eta25_pu10->Write(); scet_eb_all_eta15_pu20->Write(); scet_eb_all_eta20_pu20->Write(); scet_eb_all_eta25_pu20->Write(); scet_ee_all_eta15_pu20->Write(); scet_ee_all_eta20_pu20->Write(); scet_ee_all_eta25_pu20->Write(); scet_eb_all_eta15_pu30->Write(); scet_eb_all_eta20_pu30->Write(); scet_eb_all_eta25_pu30->Write(); scet_ee_all_eta15_pu30->Write(); scet_ee_all_eta20_pu30->Write(); scet_ee_all_eta25_pu30->Write(); scet_eb_all_eta15_pueq10->Write(); scet_eb_all_eta20_pueq10->Write(); scet_eb_all_eta25_pueq10->Write(); scet_ee_all_eta15_pueq10->Write(); scet_ee_all_eta20_pueq10->Write(); scet_ee_all_eta25_pueq10->Write(); scet_eb_all_eta15_pueq20->Write(); scet_eb_all_eta20_pueq20->Write(); scet_eb_all_eta25_pueq20->Write(); scet_ee_all_eta15_pueq20->Write(); scet_ee_all_eta20_pueq20->Write(); scet_ee_all_eta25_pueq20->Write(); scsumet_eb_all_eta15->Write(); scsumet_eb_all_eta20->Write(); scsumet_eb_all_eta25->Write(); scsumet_ee_all_eta15->Write(); scsumet_ee_all_eta20->Write(); scsumet_ee_all_eta25->Write(); scsumet_eb_all_eta15_pu10->Write(); scsumet_eb_all_eta20_pu10->Write(); scsumet_eb_all_eta25_pu10->Write(); scsumet_ee_all_eta15_pu10->Write(); scsumet_ee_all_eta20_pu10->Write(); scsumet_ee_all_eta25_pu10->Write(); scsumet_eb_all_eta15_pu20->Write(); scsumet_eb_all_eta20_pu20->Write(); scsumet_eb_all_eta25_pu20->Write(); scsumet_ee_all_eta15_pu20->Write(); scsumet_ee_all_eta20_pu20->Write(); scsumet_ee_all_eta25_pu20->Write(); scsumet_eb_all_eta15_pu30->Write(); scsumet_eb_all_eta20_pu30->Write(); scsumet_eb_all_eta25_pu30->Write(); scsumet_ee_all_eta15_pu30->Write(); scsumet_ee_all_eta20_pu30->Write(); scsumet_ee_all_eta25_pu30->Write(); scsumet_eb_all_eta15_pueq10->Write(); scsumet_eb_all_eta20_pueq10->Write(); scsumet_eb_all_eta25_pueq10->Write(); scsumet_ee_all_eta15_pueq10->Write(); scsumet_ee_all_eta20_pueq10->Write(); scsumet_ee_all_eta25_pueq10->Write(); scsumet_eb_all_eta15_pueq20->Write(); scsumet_eb_all_eta20_pueq20->Write(); scsumet_eb_all_eta25_pueq20->Write(); scsumet_ee_all_eta15_pueq20->Write(); scsumet_ee_all_eta20_pueq20->Write(); scsumet_ee_all_eta25_pueq20->Write(); scet_eb_all_eta15_pueq01->Write(); scet_eb_all_eta20_pueq01->Write(); scet_eb_all_eta25_pueq01->Write(); scet_ee_all_eta15_pueq01->Write(); scet_ee_all_eta20_pueq01->Write(); scet_ee_all_eta25_pueq01->Write(); scsumet_eb_all_eta15_pueq01->Write(); scsumet_eb_all_eta20_pueq01->Write(); scsumet_eb_all_eta25_pueq01->Write(); scsumet_ee_all_eta15_pueq01->Write(); scsumet_ee_all_eta20_pueq01->Write(); scsumet_ee_all_eta25_pueq01->Write(); scet_eb_all_eta15_pueq02->Write(); scet_eb_all_eta20_pueq02->Write(); scet_eb_all_eta25_pueq02->Write(); scet_ee_all_eta15_pueq02->Write(); scet_ee_all_eta20_pueq02->Write(); scet_ee_all_eta25_pueq02->Write(); scsumet_eb_all_eta15_pueq02->Write(); scsumet_eb_all_eta20_pueq02->Write(); scsumet_eb_all_eta25_pueq02->Write(); scsumet_ee_all_eta15_pueq02->Write(); scsumet_ee_all_eta20_pueq02->Write(); scsumet_ee_all_eta25_pueq02->Write(); scet_eb_all_eta15_pueq03->Write(); scet_eb_all_eta20_pueq03->Write(); scet_eb_all_eta25_pueq03->Write(); scet_ee_all_eta15_pueq03->Write(); scet_ee_all_eta20_pueq03->Write(); scet_ee_all_eta25_pueq03->Write(); scsumet_eb_all_eta15_pueq03->Write(); scsumet_eb_all_eta20_pueq03->Write(); scsumet_eb_all_eta25_pueq03->Write(); scsumet_ee_all_eta15_pueq03->Write(); scsumet_ee_all_eta20_pueq03->Write(); scsumet_ee_all_eta25_pueq03->Write(); scet_eb_all_eta15_pueq04->Write(); scet_eb_all_eta20_pueq04->Write(); scet_eb_all_eta25_pueq04->Write(); scet_ee_all_eta15_pueq04->Write(); scet_ee_all_eta20_pueq04->Write(); scet_ee_all_eta25_pueq04->Write(); scsumet_eb_all_eta15_pueq04->Write(); scsumet_eb_all_eta20_pueq04->Write(); scsumet_eb_all_eta25_pueq04->Write(); scsumet_ee_all_eta15_pueq04->Write(); scsumet_ee_all_eta20_pueq04->Write(); scsumet_ee_all_eta25_pueq04->Write(); scet_eb_all_eta15_pueq05->Write(); scet_eb_all_eta20_pueq05->Write(); scet_eb_all_eta25_pueq05->Write(); scet_ee_all_eta15_pueq05->Write(); scet_ee_all_eta20_pueq05->Write(); scet_ee_all_eta25_pueq05->Write(); scsumet_eb_all_eta15_pueq05->Write(); scsumet_eb_all_eta20_pueq05->Write(); scsumet_eb_all_eta25_pueq05->Write(); scsumet_ee_all_eta15_pueq05->Write(); scsumet_ee_all_eta20_pueq05->Write(); scsumet_ee_all_eta25_pueq05->Write(); scet_eb_all_eta15_pueq06->Write(); scet_eb_all_eta20_pueq06->Write(); scet_eb_all_eta25_pueq06->Write(); scet_ee_all_eta15_pueq06->Write(); scet_ee_all_eta20_pueq06->Write(); scet_ee_all_eta25_pueq06->Write(); scsumet_eb_all_eta15_pueq06->Write(); scsumet_eb_all_eta20_pueq06->Write(); scsumet_eb_all_eta25_pueq06->Write(); scsumet_ee_all_eta15_pueq06->Write(); scsumet_ee_all_eta20_pueq06->Write(); scsumet_ee_all_eta25_pueq06->Write(); scet_eb_all_eta15_pueq07->Write(); scet_eb_all_eta20_pueq07->Write(); scet_eb_all_eta25_pueq07->Write(); scet_ee_all_eta15_pueq07->Write(); scet_ee_all_eta20_pueq07->Write(); scet_ee_all_eta25_pueq07->Write(); scsumet_eb_all_eta15_pueq07->Write(); scsumet_eb_all_eta20_pueq07->Write(); scsumet_eb_all_eta25_pueq07->Write(); scsumet_ee_all_eta15_pueq07->Write(); scsumet_ee_all_eta20_pueq07->Write(); scsumet_ee_all_eta25_pueq07->Write(); scet_eb_all_eta15_pueq08->Write(); scet_eb_all_eta20_pueq08->Write(); scet_eb_all_eta25_pueq08->Write(); scet_ee_all_eta15_pueq08->Write(); scet_ee_all_eta20_pueq08->Write(); scet_ee_all_eta25_pueq08->Write(); scsumet_eb_all_eta15_pueq08->Write(); scsumet_eb_all_eta20_pueq08->Write(); scsumet_eb_all_eta25_pueq08->Write(); scsumet_ee_all_eta15_pueq08->Write(); scsumet_ee_all_eta20_pueq08->Write(); scsumet_ee_all_eta25_pueq08->Write(); scet_eb_all_eta15_pueq09->Write(); scet_eb_all_eta20_pueq09->Write(); scet_eb_all_eta25_pueq09->Write(); scet_ee_all_eta15_pueq09->Write(); scet_ee_all_eta20_pueq09->Write(); scet_ee_all_eta25_pueq09->Write(); scsumet_eb_all_eta15_pueq09->Write(); scsumet_eb_all_eta20_pueq09->Write(); scsumet_eb_all_eta25_pueq09->Write(); scsumet_ee_all_eta15_pueq09->Write(); scsumet_ee_all_eta20_pueq09->Write(); scsumet_ee_all_eta25_pueq09->Write(); ebtime_vs_bxtrain_01->Write(); ebtime_vs_bxtrain_05->Write(); eetime_vs_bxtrain_01->Write(); eetime_vs_bxtrain_05->Write(); rechiteta_vs_bxtrain_01->Write(); rechiteta_vs_bxtrain_05->Write(); sceta_vs_bxtrain->Write(); eb_digi_01->Write(); eb_digi_05->Write(); eb_digi_0105->Write(); eb_digi_0530->Write(); ee_digi_01->Write(); ee_digi_05->Write(); ee_digi_0105->Write(); ee_digi_0530->Write(); for (Int_t i=0;i<360;i++) { for (Int_t j=0;j<170;j++) { double x=etaphi_ped->GetBinContent(i+1,j+1); double y=etaphi_pedsq->GetBinContent(i+1,j+1); double n=etaphi_pedn->GetBinContent(i+1,j+1); if (n>1) { double variance=(n*y-pow(x,2))/(n*(n-1)); double sigma=sqrt(variance); etaphi_pednoise->SetBinContent(i+1,j+1,sigma); } } } etaphi_ped->Write(); etaphi_pedsq->Write(); etaphi_pedn->Write(); etaphi_pednoise->Write(); // normalise 3d digi plots for (Int_t i=0;i<120;i++) { for (Int_t j=0;j<10;j++) { float r=0; float a=eb_digi_0105_vs_time->GetBinContent(i+1,j+1); float b=eb_digi_0105_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta15->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta15->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta15->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta15->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta20->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta20->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta20->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta20->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta25->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta25->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta25->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta25->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta25->SetBinContent(i+1,j+1,r); } } for (Int_t i=0;i<40;i++) { for (Int_t j=0;j<10;j++) { float r=0; float a=eb_digi_0105_vs_bxtrain->GetBinContent(i+1,j+1); float b=eb_digi_0105_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); } } eb_digi_0105_vs_time->Write(); eb_digi_0530_vs_time->Write(); ee_digi_0105_vs_time->Write(); ee_digi_0530_vs_time->Write(); eb_digi_0105_vs_bxtrain->Write(); eb_digi_0530_vs_bxtrain->Write(); ee_digi_0105_vs_bxtrain->Write(); ee_digi_0530_vs_bxtrain->Write(); eb_digi_0105_vs_time_eta15->Write(); eb_digi_0530_vs_time_eta15->Write(); ee_digi_0105_vs_time_eta15->Write(); ee_digi_0530_vs_time_eta15->Write(); eb_digi_0105_vs_bxtrain_eta15->Write(); eb_digi_0530_vs_bxtrain_eta15->Write(); ee_digi_0105_vs_bxtrain_eta15->Write(); ee_digi_0530_vs_bxtrain_eta15->Write(); eb_digi_0105_vs_time_eta20->Write(); eb_digi_0530_vs_time_eta20->Write(); ee_digi_0105_vs_time_eta20->Write(); ee_digi_0530_vs_time_eta20->Write(); eb_digi_0105_vs_bxtrain_eta20->Write(); eb_digi_0530_vs_bxtrain_eta20->Write(); ee_digi_0105_vs_bxtrain_eta20->Write(); ee_digi_0530_vs_bxtrain_eta20->Write(); eb_digi_0105_vs_time_eta25->Write(); eb_digi_0530_vs_time_eta25->Write(); ee_digi_0105_vs_time_eta25->Write(); ee_digi_0530_vs_time_eta25->Write(); eb_digi_0105_vs_bxtrain_eta25->Write(); eb_digi_0530_vs_bxtrain_eta25->Write(); ee_digi_0105_vs_bxtrain_eta25->Write(); ee_digi_0530_vs_bxtrain_eta25->Write(); dataTree_ ->Write(); } file_ = 0; } void SpikeAnalyserMC::scan5x5(const DetId & det, const edm::Handle<EcalRecHitCollection> &hits, const edm::ESHandle<CaloTopology> &caloTopo, const edm::ESHandle<CaloGeometry> &geometry, int &nHits, float & totEt) { nHits = 0; totEt = 0; CaloNavigator<DetId> cursor = CaloNavigator<DetId>(det,caloTopo->getSubdetectorTopology(det)); for(int j=side_/2; j>=-side_/2; --j) { for(int i=-side_/2; i<=side_/2; ++i) { cursor.home(); cursor.offsetBy(i,j); if(hits->find(*cursor)!=hits->end()) // if hit exists in the rechit collection { EcalRecHit tmpHit = *hits->find(*cursor); // get rechit with detID at cursor const GlobalPoint p ( geometry->getPosition(*cursor) ) ; // calculate Et of the rechit TVector3 hitPos(p.x(),p.y(),p.z()); hitPos *= 1.0/hitPos.Mag(); hitPos *= tmpHit.energy(); float rechitEt = hitPos.Pt(); //--- return values totEt += rechitEt; if(tmpHit.energy()>Emin_ && !tmpHit.checkFlag(EcalRecHit::kGood))nHits++; } } } } const std::vector<DetId> SpikeAnalyserMC::neighbours(const DetId& id){ std::vector<DetId> ret; if ( id.subdetId() == EcalBarrel) { ret.push_back( EBDetId::offsetBy( id, 1, 0 )); ret.push_back( EBDetId::offsetBy( id, -1, 0 )); ret.push_back( EBDetId::offsetBy( id, 0, 1 )); ret.push_back( EBDetId::offsetBy( id, 0,-1 )); } return ret; } float SpikeAnalyserMC::recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ) { // in the barrel: di = dEta dj = dPhi // in the endcap: di = dX dj = dY DetId nid; if( id.subdetId() == EcalBarrel) nid = EBDetId::offsetBy( id, di, dj ); else if( id.subdetId() == EcalEndcap) nid = EEDetId::offsetBy( id, di, dj ); return ( nid == DetId(0) ? 0 : recHitE( nid, recHits ) ); } float SpikeAnalyserMC::recHitE( const DetId id, const EcalRecHitCollection &recHits) { if ( id.rawId() == 0 ) return 0; EcalRecHitCollection::const_iterator it = recHits.find( id ); if ( it != recHits.end() ){ float ene= (*it).energy(); return ene; } return 0; } float SpikeAnalyserMC::e4e1(const DetId& id, const EcalRecHitCollection& rhs){ float s4 = 0; float e1 = recHitE( id, rhs ); if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ s4+=recHitE(neighs[i],rhs); } return s4 / e1; } float SpikeAnalyserMC::e4e1v2(const DetId& id, const EcalRecHitCollection& rhs){ float s4 = 0; float e1 = recHitE( id, rhs ); float temp=0; if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ temp=recHitE(neighs[i],rhs); if (temp>0.08) s4+=temp; } return s4 / e1; } float SpikeAnalyserMC::e6e2(const DetId& id, const EcalRecHitCollection& rhs){ float s4_1 = 0; float s4_2 = 0; float e1 = recHitE( id, rhs ); float maxene=0; DetId maxid; if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ float ene = recHitE(neighs[i],rhs); if (ene>maxene) { maxene=ene; maxid = neighs[i]; } } float e2=maxene; s4_1 = e4e1(id,rhs)* e1; s4_2 = e4e1(maxid,rhs)* e2; return (s4_1 + s4_2) / (e1+e2) -1. ; } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyserMC::analyze(edm::Event const& event, edm::EventSetup const& iSetup) { // cout << "In analyse" << endl; /* edm::Handle<L1GlobalTriggerReadoutRecord> gtRecord; event.getByLabel("gtDigis", gtRecord); */ // edm::ESHandle<EcalLaserDbService> laser; // iSetup.get<EcalLaserDbRecord>().get(laser); bit36=0; bit37=0; bit38=0; bit39=0; bit40=0; bit41=0; bit3 =0; bit4 =0; bit9 =0; bit0 =0; eg1=0; eg2=0; eg5=0; algo124=0; algo54=0; algo55=0; algo56=0; algo57=0; algo58=0; algo59=0; algo60=0; algo61=0; algo62=0; algo106=0; algo107=0; rank_=0; ntrk=0; goodtrk=0; numvtx=0; vtx_x=0; vtx_y=0; vtx_z=0; vtx_x_err=0; vtx_y_err=0; vtx_z_err=0; vtx_chi2=-1; vtx_ndof=0; vtx_ntracks=0; vtx_isfake=0; vtx_good=0; numgoodvtx=0; scale=0; energy_ecal=0; energy_hcal=0; eemax=0; eemaxet=0; eeix=0; eeiy=0; eeix=0; eetime=0; eeflags=0; eehits=0; eehits1GeV=0; ee_eta=0; ee_phi=0; ee_r9=0; eephits=0; eemhits=0; ebmax=0; eb_ieta=0; eb_iphi=0; eb_eta=0; eb_phi=0; ebtime=0; ebflags=0; ebhits=0; ebhits1GeV=0; ebmaxet=0; eb_r9=0; eb_r4=0; eb_e9=0; eb_e25=0; ebchi2=0; eb2chi2=0; ebchi2oot=0; eb2chi2oot=0; eemax2=0; eemaxet2=0; eeix2=0; eeiy2=0; eeix2=0; eetime2=0; eeflags2=0; eehits1GeV2=0; ee_eta2=0; ee_phi2=0; ee_r92=0; ebmax2=0; eb_ieta2=0; eb_iphi2=0; eb_eta2=0; eb_phi2=0; ebtime2=0; ebflags2=0; ebhits1GeV2=0; ebmaxet2=0; eb_r92=0; eb_r42=0; ebnumrechits_01=0; ebnumrechits_05=0; ebnumrechits_0105=0; ebnumrechits_0530=0; eenumrechits_01=0; eenumrechits_05=0; eenumrechits_0105=0; eenumrechits_0530=0; ebflag_kgood=0; ebflag_kpoorreco=0; ebflag_koutoftime=0; ebflag_kfake=0; tmean_en=0; terr_en=0; tmean_sig=0; terr_sig=0; r4count=0; e2e9count_thresh0=0; e2e25count_thresh0=0; e2e9count_thresh1=0; e2e25count_thresh1=0; e2e9count_thresh0_nor4=0; e2e25count_thresh0_nor4=0; e2e9count_thresh1_nor4=0; e2e25count_thresh1_nor4=0; r4_algo_count=0; e2e9_algo_count=0; e2e9_algo_count_5_1=0; e2e9_algo_count_5_0=0; swisscross_algo=0; e2e9_algo=0; scale=1.0; ncr_ = 0 ; energy_pf_ = 0; energyc_pf_ = 0; energyn_pf_ = 0; energyg_pf_ = 0; energy_ecal = 0; energy_hcal = 0; ptJet_ = 0; etaJet_ = 0; phiJet_ = 0; chfJet_ = 0; nhfJet_ = 0; cemfJet_ = 0; nemfJet_ = 0; cmultiJet_ = 0; nmultiJet_ = 0; nrjets_ = 1; eesum_gt1=0; eesum_gt2=0; eesum_gt4=0; ebsum_gt1=0; ebsum_gt2=0; ebsum_gt4=0; eesum_gt1et=0; eesum_gt2et=0; eesum_gt4et=0; ebsum_gt1et=0; ebsum_gt2et=0; ebsum_gt4et=0; ebhits1GeVet=0; ebhits2GeV=0; ebhits4GeV=0; eehits2GeV=0; eehits4GeV=0; eehits1GeVet=0; ebhits2GeVet=0; ebhits4GeVet=0; eehits2GeVet=0; eehits4GeVet=0; numspikes_kweird=0; numspikes_swisscross=0; run = event.id().run(); even = event.id().event(); lumi = event.luminosityBlock(); bx = event.bunchCrossing(); // physdeclared= gtRecord->gtFdlWord().physicsDeclared(); orbit = event.orbitNumber(); double sec = event.time().value() >> 32 ; double usec = 0xFFFFFFFF & event.time().value(); double conv = 1e6; time = (sec+usec/conv); eventenergy->Reset(); eventet->Reset(); eventtime->Reset(); eventkoot->Reset(); eventkdiweird->Reset(); // get position in bunch train bunchintrain=-1; for (std::vector<int>::const_iterator bxit=bunchstartbx_.begin(); bxit!=bunchstartbx_.end(); ++bxit) { Int_t bxpos=bx - *bxit; // 50ns // if (bxpos>=0 && bxpos<=70) bunchintrain=bxpos/2; // 25ns if (bxpos>=0 && bxpos<=50) bunchintrain=bxpos; } // PU info // edm::InputTag PileupSrc_("addPileupInfo"); // Handle<std::vector<PileupSummaryInfo>> PupInfo; // event.getByLabel(PileupSrc_, PupInfo); // std::vector<PileupSummaryInfo>::const_iterator PVI; // for (PVI=PupInfo->begin(); PVI!=PupInfo->end(); ++PVI) { // cout << "PU INFO: bx=" << PVI->getBunchCrossing() << " PU=" << PVI->getPU_NumInteractions() << endl; // } // // end of PU info Float_t toffset=0.0; // if (run>135000 && run<136000 && !isMC_) toffset=2.08; //Int_t numtracks=0; //Int_t goodtracks=0; // if (even==89083177) { // cout << "begin tracks" << endl; /* edm::Handle<reco::TrackCollection> tracks; event.getByLabel(tracks_,tracks); const reco::TrackCollection* itTrack = tracks.product(); numtracks=itTrack->size(); reco::TrackBase::TrackQuality _trackQuality=reco::TrackBase::qualityByName("highPurity"); reco::TrackCollection::const_iterator itk=itTrack->begin(); reco::TrackCollection::const_iterator itk_e=itTrack->end(); for (;itk!=itk_e;++itk) { if (itk->quality(_trackQuality)) goodtracks++; } ntrk=numtracks; goodtrk=goodtracks; */ edm::Handle<VertexCollection> vertices; event.getByLabel(vertex_coll_,vertices); VertexCollection::const_iterator vit; numvtx=vertices->size(); if (vertices->size()>0) { for (vit=vertices->begin();vit!=vertices->end();++vit) { vtx_x=vit->x(); vtx_y=vit->y(); vtx_z=vit->z(); vtx_x_err=vit->xError(); vtx_y_err=vit->yError(); vtx_z_err=vit->zError(); vtx_chi2=vit->chi2(); vtx_ndof=vit->ndof(); // vector<TrackBaseRef>::const_iterator trstart=vit->tracks_begin(); // vector<TrackBaseRef>::const_iterator trend=vit->tracks_end(); vtx_ntracks=vit->tracksSize(); vtx_isfake=vit->isFake(); if (vit->isValid() && vtx_isfake==0 && vtx_ndof>4 && vtx_chi2>0 && vtx_chi2<10000) { vtx_good=1; numgoodvtx++; } } } // cout << "begin rechits" << endl; // EB rechits Handle<EcalRecHitCollection> EBhits; // event.getByLabel("ecalRecHit","EcalRecHitsEB",EBhits); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEB","reRECO"),EBhits); //alternatives //event.getByLabel("reducedEcalRecHitsEB","",EBhits); //event.getByLabel("alCaIsolatedElectrons","alCaRecHitsEB",EBhits); const EcalRecHitCollection *ebRecHits=EBhits.product(); Handle<EcalRecHitCollection> EEhits; //event.getByLabel("ecalRecHit","EcalRecHitsEE",EEhits); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEE","reRECO"),EEhits); // alternatives // event.getByLabel("reducedEcalRecHitsEE","",EEhits); // event.getByLabel("alCaIsolatedElectrons","alCaRecHitsEE",EEhits); const EcalRecHitCollection *eeRecHits=EEhits.product(); // digis Handle<EBDigiCollection> EBdigis; event.getByLabel("ecalDigis","ebDigis",EBdigis); // event.getByLabel("ecalEBunpacker","ebDigis",EBdigis); // event.getByLabel("selectDigi","selectedEcalEBDigiCollection",EBdigis); // event.getByLabel("selectDigi","selectedEcalEBDigiCollection",EBdigis); Handle<EBDigiCollection> EBdigis2; // spike APD digis - MC only if (isMC_) { event.getByLabel(edm::InputTag("simEcalUnsuppressedDigis","APD","reRECO"),EBdigis2); } Handle<EEDigiCollection> EEdigis; if (isMC_) { event.getByLabel("ecalDigis","eeDigis",EEdigis); } else { // event.getByLabel("ecalEBunpacker","eeDigis",EEdigis); event.getByLabel("selectDigi","selectedEcalEEDigiCollection",EEdigis); } // event.getByLabel("selectDigi","selectedEcalEEDigiCollection",EEdigis); Int_t ebdigiadc=0; // Int_t ebdigigain=0; // cout << "run=" << run << " event=" << even << endl; // Int_t apd_ieta=0; // Int_t apd_iphi=0; numspikes=0; numspikes50=0; numspikes100=0; if (isMC_) { for (EBDigiCollection::const_iterator digiItrEB= EBdigis2->begin(); digiItrEB != EBdigis2->end(); ++digiItrEB) { int adcmax=0; int adcmaxsample=0; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { ebdigiadc=df.sample(i).adc(); if (ebdigiadc>adcmax) { adcmax=ebdigiadc; adcmaxsample=i+1; } } numspikes++; if (adcmax>250) { numspikes50++; spiketime50->Fill(float(adcmaxsample)); } if (adcmax>300) numspikes100++; spikeadc->Fill(adcmax-250); } } for (EBDigiCollection::const_iterator digiItrEB= EBdigis2->begin(); digiItrEB != EBdigis2->end(); ++digiItrEB) { int adcmax=0; int gainmax=0; int sampmax=0; // int dframe[10]; // int gframe[10]; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); // dframe[i]=ebdigiadc; // gframe[i]=ebdigigain; if (ebdigiadc>adcmax) { adcmax=ebdigiadc; gainmax=ebdigigain; sampmax=i+1; } } if ((adcmax>250 || gainmax>1) && (sampmax==4 || sampmax==5 || sampmax==6) ) { // EBDetId spikedet=digiItrEB->id(); // int spike_ieta=spikedet.ieta(); // int spike_iphi=spikedet.iphi(); // cout << "Spike ieta,iphi= " << spike_ieta << "," << spike_iphi << endl; for (Int_t i=0;i<10;i++) { // cout << i+1 << " " << gframe[i] << " " << dframe[i] << endl; } } } for (EBDigiCollection::const_iterator digiItrEB= EBdigis->begin(); digiItrEB != EBdigis->end(); ++digiItrEB) { int adcmax=0; int gainmax=0; int sampmax=0; //int dframe[10]; //int gframe[10]; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); // dframe[i]=ebdigiadc; // gframe[i]=ebdigigain; if (ebdigiadc>adcmax) { adcmax=ebdigiadc; gainmax=ebdigigain; sampmax=i+1; } } if ((adcmax>220 || gainmax>1) && (sampmax==4 || sampmax==5 || sampmax==6) ) { //EBDetId spikedet=digiItrEB->id(); // int spike_ieta=spikedet.ieta(); // int spike_iphi=spikedet.iphi(); // cout << "Rechit ieta,iphi= " << spike_ieta << "," << spike_iphi << endl; for (Int_t i=0;i<10;i++) { // cout << i+1 << " " << gframe[i] << " " << dframe[i] << endl; } } } // Calotower section edm::Handle<CaloTowerCollection> towers; event.getByLabel("towerMaker",towers); ncalotower = 0; ncalotowereb=0; ncalotoweree=0; ncalotowerhf=0; ncalotowerebgt1=0; ncalotowerebgt2=0; ncalotowerebgt5=0; ncalotowerebgt10=0; ncalotowereegt1=0; ncalotowereegt2=0; ncalotowereegt5=0; ncalotowereegt10=0; ncalotowerhfgt1=0; ncalotowerhfgt2=0; ncalotowerhfgt5=0; ncalotowerhfgt10=0; ctsumebgt1=0; ctsumebgt2=0; ctsumebgt5=0; ctsumebgt10=0; ctsumeegt1=0; ctsumeegt2=0; ctsumeegt5=0; ctsumeegt10=0; ctsumhfgt1=0; ctsumhfgt2=0; ctsumhfgt5=0; ctsumhfgt10=0; if (towers.isValid() && towers->size()>0) { for(CaloTowerCollection::const_iterator it = towers->begin();it != towers->end(); it++) { double ct_eta=it->eta(); // double ct_phi = it->phi(); // double ct_et = it->et(); double ct_emf=it->emEt(); // double ct_had=it->hadEt(); // double ct_hof=it->outerEt(); ncalotower++; if (fabs(ct_eta)<3.0 && ct_emf>0.0) { calotowereta_all->Fill(ct_eta); calotowereta_etweight->Fill(ct_eta,ct_emf); if (ct_emf>1.0) { calotowereta_gt1et->Fill(ct_eta); calotowereta_etweight_gt1et->Fill(ct_eta,ct_emf); if (numgoodvtx<10) calotowereta_gt1et_pu10->Fill(ct_eta); if (numgoodvtx>=10 && numgoodvtx<20) calotowereta_gt1et_pu20->Fill(ct_eta); if (numgoodvtx>20) calotowereta_gt1et_pu30->Fill(ct_eta); } } if (fabs(ct_eta)<=1.48) { ncalotowereb++; if (ct_emf>1.0) { ncalotowerebgt1++; ctsumebgt1+=ct_emf; } if (ct_emf>2.0) { ncalotowerebgt2++; ctsumebgt2+=ct_emf; } if (ct_emf>5.0) { ncalotowerebgt5++; ctsumebgt5+=ct_emf; } if (ct_emf>10.0) { ncalotowerebgt10++; ctsumebgt10+=ct_emf; } } if (fabs(ct_eta)>1.48 && fabs(ct_eta)<3.0) { ncalotoweree++; if (ct_emf>1.0) { ncalotowereegt1++; ctsumeegt1+=ct_emf; } if (ct_emf>2.0) { ncalotowereegt2++; ctsumeegt2+=ct_emf; } if (ct_emf>5.0) { ncalotowereegt5++; ctsumeegt5+=ct_emf; } if (ct_emf>10.0) { ncalotowereegt10++; ctsumeegt10+=ct_emf; } } if (fabs(ct_eta)>3.0) { ncalotowerhf++; if (ct_emf>1.0) { ncalotowerhfgt1++; ctsumhfgt1+=ct_emf; } if (ct_emf>2.0) { ncalotowerhfgt2++; ctsumhfgt2+=ct_emf; } if (ct_emf>5.0) { ncalotowerhfgt5++; ctsumhfgt5+=ct_emf; } if (ct_emf>10.0) { ncalotowerhfgt10++; ctsumhfgt10+=ct_emf; } } } } edm::ESHandle<CaloGeometry> pG; iSetup.get<CaloGeometryRecord>().get(pG); const CaloGeometry* geo=pG.product(); edm::ESHandle<CaloTopology> pTopology; iSetup.get<CaloTopologyRecord>().get(pTopology); // edm::ESHandle<EcalChannelStatus> chanstat; // iSetup.get<EcalChannelStatusRcd>().get(chanstat); // const EcalChannelStatus* cstat=chanstat.product(); edm::ESHandle<EcalPedestals> ecalped; iSetup.get<EcalPedestalsRcd>().get(ecalped); const EcalPedestals* eped=ecalped.product(); edm::ESHandle<EcalADCToGeVConstant> ecaladcgev; iSetup.get<EcalADCToGeVConstantRcd>().get(ecaladcgev); const EcalADCToGeVConstant* eadcgev=ecaladcgev.product(); float adctogevconst=eadcgev->getEBValue(); edm::ESHandle<EcalIntercalibConstants> ecalic; iSetup.get<EcalIntercalibConstantsRcd>().get(ecalic); const EcalIntercalibConstants* eic=ecalic.product(); edm::ESHandle<EcalSeverityLevelAlgo> sevlv; iSetup.get<EcalSeverityLevelAlgoRcd>().get(sevlv); const EcalSeverityLevelAlgo *severity=sevlv.product(); edm::Handle<reco::SuperClusterCollection> sc_eb; event.getByLabel("correctedHybridSuperClusters","",sc_eb); edm::Handle<reco::SuperClusterCollection> sc_ee; event.getByLabel("correctedMulti5x5SuperClustersWithPreshower","",sc_ee); // sc loop: EB ebscsumet_all=0; float ebscsumet_severity0=0; float ebscsumet_koot0=0; float ebscsumet_all_gt2=0; float ebscsumet_severity0_gt2=0; float ebscsumet_koot0_gt2=0; float ebscsumet_all_gt5=0; float ebscsumet_severity0_gt5=0; float ebscsumet_koot0_gt5=0; float ebscsumet_all_gt10=0; float ebscsumet_severity0_gt10=0; float ebscsumet_koot0_gt10=0; ebscsumet_all_eta15=0; ebscsumet_all_eta20=0; ebscsumet_all_eta25=0; float ebscsumet_all_eta15_pu10=0; float ebscsumet_all_eta20_pu10=0; float ebscsumet_all_eta25_pu10=0; float ebscsumet_all_eta15_pu20=0; float ebscsumet_all_eta20_pu20=0; float ebscsumet_all_eta25_pu20=0; float ebscsumet_all_eta15_pu30=0; float ebscsumet_all_eta20_pu30=0; float ebscsumet_all_eta25_pu30=0; float ebscsumet_all_eta15_pueq10=0; float ebscsumet_all_eta20_pueq10=0; float ebscsumet_all_eta25_pueq10=0; float ebscsumet_all_eta15_pueq20=0; float ebscsumet_all_eta20_pueq20=0; float ebscsumet_all_eta25_pueq20=0; eescsumet_all_eta15=0; eescsumet_all_eta20=0; eescsumet_all_eta25=0; float eescsumet_all_eta15_pu10=0; float eescsumet_all_eta20_pu10=0; float eescsumet_all_eta25_pu10=0; float eescsumet_all_eta15_pu20=0; float eescsumet_all_eta20_pu20=0; float eescsumet_all_eta25_pu20=0; float eescsumet_all_eta15_pu30=0; float eescsumet_all_eta20_pu30=0; float eescsumet_all_eta25_pu30=0; float eescsumet_all_eta15_pueq10=0; float eescsumet_all_eta20_pueq10=0; float eescsumet_all_eta25_pueq10=0; float eescsumet_all_eta15_pueq20=0; float eescsumet_all_eta20_pueq20=0; float eescsumet_all_eta25_pueq20=0; float ebscsumet_all_eta15_pueq01=0; float ebscsumet_all_eta20_pueq01=0; float ebscsumet_all_eta25_pueq01=0; float eescsumet_all_eta15_pueq01=0; float eescsumet_all_eta20_pueq01=0; float eescsumet_all_eta25_pueq01=0; float ebscsumet_all_eta15_pueq02=0; float ebscsumet_all_eta20_pueq02=0; float ebscsumet_all_eta25_pueq02=0; float eescsumet_all_eta15_pueq02=0; float eescsumet_all_eta20_pueq02=0; float eescsumet_all_eta25_pueq02=0; float ebscsumet_all_eta15_pueq03=0; float ebscsumet_all_eta20_pueq03=0; float ebscsumet_all_eta25_pueq03=0; float eescsumet_all_eta15_pueq03=0; float eescsumet_all_eta20_pueq03=0; float eescsumet_all_eta25_pueq03=0; float ebscsumet_all_eta15_pueq04=0; float ebscsumet_all_eta20_pueq04=0; float ebscsumet_all_eta25_pueq04=0; float eescsumet_all_eta15_pueq04=0; float eescsumet_all_eta20_pueq04=0; float eescsumet_all_eta25_pueq04=0; float ebscsumet_all_eta15_pueq05=0; float ebscsumet_all_eta20_pueq05=0; float ebscsumet_all_eta25_pueq05=0; float eescsumet_all_eta15_pueq05=0; float eescsumet_all_eta20_pueq05=0; float eescsumet_all_eta25_pueq05=0; float ebscsumet_all_eta15_pueq06=0; float ebscsumet_all_eta20_pueq06=0; float ebscsumet_all_eta25_pueq06=0; float eescsumet_all_eta15_pueq06=0; float eescsumet_all_eta20_pueq06=0; float eescsumet_all_eta25_pueq06=0; float ebscsumet_all_eta15_pueq07=0; float ebscsumet_all_eta20_pueq07=0; float ebscsumet_all_eta25_pueq07=0; float eescsumet_all_eta15_pueq07=0; float eescsumet_all_eta20_pueq07=0; float eescsumet_all_eta25_pueq07=0; float ebscsumet_all_eta15_pueq08=0; float ebscsumet_all_eta20_pueq08=0; float ebscsumet_all_eta25_pueq08=0; float eescsumet_all_eta15_pueq08=0; float eescsumet_all_eta20_pueq08=0; float eescsumet_all_eta25_pueq08=0; float ebscsumet_all_eta15_pueq09=0; float ebscsumet_all_eta20_pueq09=0; float ebscsumet_all_eta25_pueq09=0; float eescsumet_all_eta15_pueq09=0; float eescsumet_all_eta20_pueq09=0; float eescsumet_all_eta25_pueq09=0; ebnumsc_all=0; eenumsc_all=0; for (reco::SuperClusterCollection::const_iterator sCEB = sc_eb->begin(); sCEB != sc_eb->end(); ++sCEB) { DetId seedid=sCEB->seed()->seed(); bool goodseed=false; int sevlev=0; // float time=0; int koot=0; for (EcalRecHitCollection::const_iterator hitItr = EBhits->begin(); hitItr != EBhits->end(); ++hitItr) { EcalRecHit hit = (*hitItr); EBDetId det = hit.id(); if (det!=seedid) continue; sevlev=severity->severityLevel(det,*ebRecHits); // time = hit.time(); koot=0; if (hit.checkFlag(EcalRecHit::kOutOfTime)) koot=1; goodseed=true; } if (goodseed) { Float_t scenergy=sCEB->energy(); Float_t sc_eta=sCEB->eta(); Float_t sc_phi=sCEB->phi(); Float_t scet=scenergy/cosh(sc_eta); ebscsumet_all+=scet; if (sevlev==0) ebscsumet_severity0+=scet; if (koot==0) ebscsumet_koot0+=scet; ebnumsc_all++; scet_eb_all->Fill(scet); if (sevlev==0) scet_eb_severity0->Fill(scet); if (koot==0) scet_eb_koot0->Fill(scet); sceta_all->Fill(sc_eta); sceta_vs_bxtrain->Fill(bunchintrain,sc_eta); if (sevlev==0) sceta_severity0->Fill(sc_eta); if (koot==0) sceta_koot0->Fill(sc_eta); if (numgoodvtx==1) { sceta_all_pueq01->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq01->Fill(sc_eta); } if (numgoodvtx==2) { sceta_all_pueq02->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq02->Fill(sc_eta); } if (numgoodvtx==3) { sceta_all_pueq03->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq03->Fill(sc_eta); } if (numgoodvtx==4) { sceta_all_pueq04->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq04->Fill(sc_eta); } if (numgoodvtx==5) { sceta_all_pueq05->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq05->Fill(sc_eta); } if (numgoodvtx==6) { sceta_all_pueq06->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq06->Fill(sc_eta); } if (numgoodvtx==7) { sceta_all_pueq07->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq07->Fill(sc_eta); } if (numgoodvtx==8) { sceta_all_pueq08->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq08->Fill(sc_eta); } if (numgoodvtx==9) { sceta_all_pueq09->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq09->Fill(sc_eta); } if (fabs(sc_eta)<0.5) { scet_eb_all_eta15->Fill(scet); ebscsumet_all_eta15+=scet; if (numgoodvtx<=10) { scet_eb_all_eta15_pu10->Fill(scet); ebscsumet_all_eta15_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_eb_all_eta15_pu20->Fill(scet); ebscsumet_all_eta15_pu20+=scet; } if (numgoodvtx>20) { scet_eb_all_eta15_pu30->Fill(scet); ebscsumet_all_eta15_pu30+=scet; } if (numgoodvtx==10) { scet_eb_all_eta15_pueq10->Fill(scet); ebscsumet_all_eta15_pueq10+=scet; } if (numgoodvtx==20) { scet_eb_all_eta15_pueq20->Fill(scet); ebscsumet_all_eta15_pueq20+=scet; } if (numgoodvtx==1) { scet_eb_all_eta15_pueq01->Fill(scet); ebscsumet_all_eta15_pueq01+=scet; } if (numgoodvtx==2) { scet_eb_all_eta15_pueq02->Fill(scet); ebscsumet_all_eta15_pueq02+=scet; } if (numgoodvtx==3) { scet_eb_all_eta15_pueq03->Fill(scet); ebscsumet_all_eta15_pueq03+=scet; } if (numgoodvtx==4) { scet_eb_all_eta15_pueq04->Fill(scet); ebscsumet_all_eta15_pueq04+=scet; } if (numgoodvtx==5) { scet_eb_all_eta15_pueq05->Fill(scet); ebscsumet_all_eta15_pueq05+=scet; } if (numgoodvtx==6) { scet_eb_all_eta15_pueq06->Fill(scet); ebscsumet_all_eta15_pueq06+=scet; } if (numgoodvtx==7) { scet_eb_all_eta15_pueq07->Fill(scet); ebscsumet_all_eta15_pueq07+=scet; } if (numgoodvtx==8) { scet_eb_all_eta15_pueq08->Fill(scet); ebscsumet_all_eta15_pueq08+=scet; } if (numgoodvtx==9) { scet_eb_all_eta15_pueq09->Fill(scet); ebscsumet_all_eta15_pueq09+=scet; } } if (fabs(sc_eta)>=0.5 && fabs(sc_eta)<1.0) { scet_eb_all_eta20->Fill(scet); ebscsumet_all_eta20+=scet; if (numgoodvtx<=10) { scet_eb_all_eta20_pu10->Fill(scet); ebscsumet_all_eta20_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_eb_all_eta20_pu20->Fill(scet); ebscsumet_all_eta20_pu20+=scet; } if (numgoodvtx>20) { scet_eb_all_eta20_pu30->Fill(scet); ebscsumet_all_eta20_pu30+=scet; } if (numgoodvtx==10) { scet_eb_all_eta20_pueq10->Fill(scet); ebscsumet_all_eta20_pueq10+=scet; } if (numgoodvtx==20) { scet_eb_all_eta20_pueq20->Fill(scet); ebscsumet_all_eta20_pueq20+=scet; } if (numgoodvtx==1) { scet_eb_all_eta20_pueq01->Fill(scet); ebscsumet_all_eta20_pueq01+=scet; } if (numgoodvtx==2) { scet_eb_all_eta20_pueq02->Fill(scet); ebscsumet_all_eta20_pueq02+=scet; } if (numgoodvtx==3) { scet_eb_all_eta20_pueq03->Fill(scet); ebscsumet_all_eta20_pueq03+=scet; } if (numgoodvtx==4) { scet_eb_all_eta20_pueq04->Fill(scet); ebscsumet_all_eta20_pueq04+=scet; } if (numgoodvtx==5) { scet_eb_all_eta20_pueq05->Fill(scet); ebscsumet_all_eta20_pueq05+=scet; } if (numgoodvtx==6) { scet_eb_all_eta20_pueq06->Fill(scet); ebscsumet_all_eta20_pueq06+=scet; } if (numgoodvtx==7) { scet_eb_all_eta20_pueq07->Fill(scet); ebscsumet_all_eta20_pueq07+=scet; } if (numgoodvtx==8) { scet_eb_all_eta20_pueq08->Fill(scet); ebscsumet_all_eta20_pueq08+=scet; } if (numgoodvtx==9) { scet_eb_all_eta20_pueq09->Fill(scet); ebscsumet_all_eta20_pueq09+=scet; } } if (fabs(sc_eta)>1.0) { scet_eb_all_eta25->Fill(scet); ebscsumet_all_eta25+=scet; if (numgoodvtx<=10) { scet_eb_all_eta25_pu10->Fill(scet); ebscsumet_all_eta25_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_eb_all_eta25_pu20->Fill(scet); ebscsumet_all_eta25_pu20+=scet; } if (numgoodvtx>20) { scet_eb_all_eta25_pu30->Fill(scet); ebscsumet_all_eta25_pu30+=scet; } if (numgoodvtx==10) { scet_eb_all_eta25_pueq10->Fill(scet); ebscsumet_all_eta25_pueq10+=scet; } if (numgoodvtx==20) { scet_eb_all_eta25_pueq20->Fill(scet); ebscsumet_all_eta25_pueq20+=scet; } if (numgoodvtx==1) { scet_eb_all_eta25_pueq01->Fill(scet); ebscsumet_all_eta25_pueq01+=scet; } if (numgoodvtx==2) { scet_eb_all_eta25_pueq02->Fill(scet); ebscsumet_all_eta25_pueq02+=scet; } if (numgoodvtx==3) { scet_eb_all_eta25_pueq03->Fill(scet); ebscsumet_all_eta25_pueq03+=scet; } if (numgoodvtx==4) { scet_eb_all_eta25_pueq04->Fill(scet); ebscsumet_all_eta25_pueq04+=scet; } if (numgoodvtx==5) { scet_eb_all_eta25_pueq05->Fill(scet); ebscsumet_all_eta25_pueq05+=scet; } if (numgoodvtx==6) { scet_eb_all_eta25_pueq06->Fill(scet); ebscsumet_all_eta25_pueq06+=scet; } if (numgoodvtx==7) { scet_eb_all_eta25_pueq07->Fill(scet); ebscsumet_all_eta25_pueq07+=scet; } if (numgoodvtx==8) { scet_eb_all_eta25_pueq08->Fill(scet); ebscsumet_all_eta25_pueq08+=scet; } if (numgoodvtx==9) { scet_eb_all_eta25_pueq09->Fill(scet); ebscsumet_all_eta25_pueq09+=scet; } } if (scet>2.0) { sceta_all_gt2->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt2->Fill(sc_eta); if (koot==0) sceta_koot0_gt2->Fill(sc_eta); ebscsumet_all_gt2+=scet; if (sevlev==0) ebscsumet_severity0_gt2+=scet; if (koot==0) ebscsumet_koot0_gt2+=scet; } if (scet>5.0) { sceta_all_gt5->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt5->Fill(sc_eta); if (koot==0) sceta_koot0_gt5->Fill(sc_eta); ebscsumet_all_gt5+=scet; if (sevlev==0) ebscsumet_severity0_gt5+=scet; if (koot==0) ebscsumet_koot0_gt5+=scet; } if (scet>10.0) { sceta_all_gt10->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt10->Fill(sc_eta); if (koot==0) sceta_koot0_gt10->Fill(sc_eta); ebscsumet_all_gt10+=scet; if (sevlev==0) ebscsumet_severity0_gt10+=scet; if (koot==0) ebscsumet_koot0_gt10+=scet; } if (scet>50.0) { scocc_eb_gt50->Fill(sc_phi,sc_eta); } } } scsumet_eb_all->Fill(ebscsumet_all); scsumet_eb_severity0->Fill(ebscsumet_severity0); scsumet_eb_koot0->Fill(ebscsumet_koot0); scsumet_eb_all_eta15->Fill(ebscsumet_all_eta15); scsumet_eb_all_eta20->Fill(ebscsumet_all_eta20); scsumet_eb_all_eta25->Fill(ebscsumet_all_eta25); scsumet_eb_all_eta15_pu10->Fill(ebscsumet_all_eta15_pu10); scsumet_eb_all_eta20_pu10->Fill(ebscsumet_all_eta20_pu10); scsumet_eb_all_eta25_pu10->Fill(ebscsumet_all_eta25_pu10); scsumet_eb_all_eta15_pu20->Fill(ebscsumet_all_eta15_pu20); scsumet_eb_all_eta20_pu20->Fill(ebscsumet_all_eta20_pu20); scsumet_eb_all_eta25_pu20->Fill(ebscsumet_all_eta25_pu20); scsumet_eb_all_eta15_pu30->Fill(ebscsumet_all_eta15_pu30); scsumet_eb_all_eta20_pu30->Fill(ebscsumet_all_eta20_pu30); scsumet_eb_all_eta25_pu30->Fill(ebscsumet_all_eta25_pu30); scsumet_eb_all_eta15_pueq10->Fill(ebscsumet_all_eta15_pueq10); scsumet_eb_all_eta20_pueq10->Fill(ebscsumet_all_eta20_pueq10); scsumet_eb_all_eta25_pueq10->Fill(ebscsumet_all_eta25_pueq10); scsumet_eb_all_eta15_pueq20->Fill(ebscsumet_all_eta15_pueq20); scsumet_eb_all_eta20_pueq20->Fill(ebscsumet_all_eta20_pueq20); scsumet_eb_all_eta25_pueq20->Fill(ebscsumet_all_eta25_pueq20); scsumet_eb_all_eta15_pueq01->Fill(ebscsumet_all_eta15_pueq01); scsumet_eb_all_eta20_pueq01->Fill(ebscsumet_all_eta20_pueq01); scsumet_eb_all_eta25_pueq01->Fill(ebscsumet_all_eta25_pueq01); scsumet_eb_all_eta15_pueq02->Fill(ebscsumet_all_eta15_pueq02); scsumet_eb_all_eta20_pueq02->Fill(ebscsumet_all_eta20_pueq02); scsumet_eb_all_eta25_pueq02->Fill(ebscsumet_all_eta25_pueq02); scsumet_eb_all_eta15_pueq03->Fill(ebscsumet_all_eta15_pueq03); scsumet_eb_all_eta20_pueq03->Fill(ebscsumet_all_eta20_pueq03); scsumet_eb_all_eta25_pueq03->Fill(ebscsumet_all_eta25_pueq03); scsumet_eb_all_eta15_pueq04->Fill(ebscsumet_all_eta15_pueq04); scsumet_eb_all_eta20_pueq04->Fill(ebscsumet_all_eta20_pueq04); scsumet_eb_all_eta25_pueq04->Fill(ebscsumet_all_eta25_pueq04); scsumet_eb_all_eta15_pueq05->Fill(ebscsumet_all_eta15_pueq05); scsumet_eb_all_eta20_pueq05->Fill(ebscsumet_all_eta20_pueq05); scsumet_eb_all_eta25_pueq05->Fill(ebscsumet_all_eta25_pueq05); scsumet_eb_all_eta15_pueq06->Fill(ebscsumet_all_eta15_pueq06); scsumet_eb_all_eta20_pueq06->Fill(ebscsumet_all_eta20_pueq06); scsumet_eb_all_eta25_pueq06->Fill(ebscsumet_all_eta25_pueq06); scsumet_eb_all_eta15_pueq07->Fill(ebscsumet_all_eta15_pueq07); scsumet_eb_all_eta20_pueq07->Fill(ebscsumet_all_eta20_pueq07); scsumet_eb_all_eta25_pueq07->Fill(ebscsumet_all_eta25_pueq07); scsumet_eb_all_eta15_pueq08->Fill(ebscsumet_all_eta15_pueq08); scsumet_eb_all_eta20_pueq08->Fill(ebscsumet_all_eta20_pueq08); scsumet_eb_all_eta25_pueq08->Fill(ebscsumet_all_eta25_pueq08); scsumet_eb_all_eta15_pueq09->Fill(ebscsumet_all_eta15_pueq09); scsumet_eb_all_eta20_pueq09->Fill(ebscsumet_all_eta20_pueq09); scsumet_eb_all_eta25_pueq09->Fill(ebscsumet_all_eta25_pueq09); scsumet_eb_all_gt2->Fill(ebscsumet_all_gt2); scsumet_eb_severity0_gt2->Fill(ebscsumet_severity0_gt2); scsumet_eb_koot0_gt2->Fill(ebscsumet_koot0_gt2); scsumet_eb_all_gt5->Fill(ebscsumet_all_gt5); scsumet_eb_severity0_gt5->Fill(ebscsumet_severity0_gt5); scsumet_eb_koot0_gt5->Fill(ebscsumet_koot0_gt5); scsumet_eb_all_gt10->Fill(ebscsumet_all_gt10); scsumet_eb_severity0_gt10->Fill(ebscsumet_severity0_gt10); scsumet_eb_koot0_gt10->Fill(ebscsumet_koot0_gt10); // sc loop: EE eescsumet_all=0; float eescsumet_severity0=0; float eescsumet_koot0=0; float eescsumet_all_gt2=0; float eescsumet_severity0_gt2=0; float eescsumet_koot0_gt2=0; float eescsumet_all_gt5=0; float eescsumet_severity0_gt5=0; float eescsumet_koot0_gt5=0; float eescsumet_all_gt10=0; float eescsumet_severity0_gt10=0; float eescsumet_koot0_gt10=0; for (reco::SuperClusterCollection::const_iterator sCEE = sc_ee->begin(); sCEE != sc_ee->end(); ++sCEE) { // cout << "IN EE SC" << endl; DetId seedid=sCEE->seed()->seed(); bool goodseed=false; int sevlev=0; // float time=0; int koot=0; // float seeden=0; for (EcalRecHitCollection::const_iterator hitItr = EEhits->begin(); hitItr != EEhits->end(); ++hitItr) { EcalRecHit hit = (*hitItr); EEDetId det = hit.id(); if (det!=seedid) continue; sevlev=severity->severityLevel(det,*eeRecHits); // time = hit.time(); //seeden = hit.energy(); koot=0; if (hit.checkFlag(EcalRecHit::kOutOfTime)) koot=1; // cout << "sevlev=" << sevlev << endl; // if (sevlev!=0) goodseed=false; goodseed=true; } if (goodseed) { Float_t scenergy=sCEE->energy(); Float_t sc_eta=sCEE->eta(); Float_t sc_phi=sCEE->phi(); Float_t scet=scenergy/cosh(sc_eta); sceta_all->Fill(sc_eta); sceta_vs_bxtrain->Fill(bunchintrain,sc_eta); if (sevlev==0) sceta_severity0->Fill(sc_eta); if (koot==0) sceta_koot0->Fill(sc_eta); eenumsc_all++; if (numgoodvtx==1) { sceta_all_pueq01->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq01->Fill(sc_eta); } if (numgoodvtx==2) { sceta_all_pueq02->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq02->Fill(sc_eta); } if (numgoodvtx==3) { sceta_all_pueq03->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq03->Fill(sc_eta); } if (numgoodvtx==4) { sceta_all_pueq04->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq04->Fill(sc_eta); } if (numgoodvtx==5) { sceta_all_pueq05->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq05->Fill(sc_eta); } if (numgoodvtx==6) { sceta_all_pueq06->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq06->Fill(sc_eta); } if (numgoodvtx==7) { sceta_all_pueq07->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq07->Fill(sc_eta); } if (numgoodvtx==8) { sceta_all_pueq08->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq08->Fill(sc_eta); } if (numgoodvtx==9) { sceta_all_pueq09->Fill(sc_eta); if (sevlev==0) sceta_severity0_pueq09->Fill(sc_eta); } scet_ee_all->Fill(scet); if (sevlev==0) scet_ee_severity0->Fill(scet); if (koot==0) scet_ee_koot0->Fill(scet); eescsumet_all+=scet; if (sevlev==0) eescsumet_severity0+=scet; if (koot==0) eescsumet_koot0+=scet; if (fabs(sc_eta)<2.0) { scet_ee_all_eta15->Fill(scet); eescsumet_all_eta15+=scet; if (numgoodvtx<=10) { scet_ee_all_eta15_pu10->Fill(scet); eescsumet_all_eta15_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_ee_all_eta15_pu20->Fill(scet); eescsumet_all_eta15_pu20+=scet; } if (numgoodvtx>20) { scet_ee_all_eta15_pu30->Fill(scet); eescsumet_all_eta15_pu30+=scet; } if (numgoodvtx==10) { scet_ee_all_eta15_pueq10->Fill(scet); eescsumet_all_eta15_pueq10+=scet; } if (numgoodvtx==20) { scet_ee_all_eta15_pueq20->Fill(scet); eescsumet_all_eta15_pueq20+=scet; } if (numgoodvtx==1) { scet_ee_all_eta15_pueq01->Fill(scet); eescsumet_all_eta15_pueq01+=scet; } if (numgoodvtx==2) { scet_ee_all_eta15_pueq02->Fill(scet); eescsumet_all_eta15_pueq02+=scet; } if (numgoodvtx==3) { scet_ee_all_eta15_pueq03->Fill(scet); eescsumet_all_eta15_pueq03+=scet; } if (numgoodvtx==4) { scet_ee_all_eta15_pueq04->Fill(scet); eescsumet_all_eta15_pueq04+=scet; } if (numgoodvtx==5) { scet_ee_all_eta15_pueq05->Fill(scet); eescsumet_all_eta15_pueq05+=scet; } if (numgoodvtx==6) { scet_ee_all_eta15_pueq06->Fill(scet); eescsumet_all_eta15_pueq06+=scet; } if (numgoodvtx==7) { scet_ee_all_eta15_pueq07->Fill(scet); eescsumet_all_eta15_pueq07+=scet; } if (numgoodvtx==8) { scet_ee_all_eta15_pueq08->Fill(scet); eescsumet_all_eta15_pueq08+=scet; } if (numgoodvtx==9) { scet_ee_all_eta15_pueq09->Fill(scet); eescsumet_all_eta15_pueq09+=scet; } } if (fabs(sc_eta)>=2.0 && fabs(sc_eta)<2.5) { scet_ee_all_eta20->Fill(scet); eescsumet_all_eta20+=scet; if (numgoodvtx<=10) { scet_ee_all_eta20_pu10->Fill(scet); eescsumet_all_eta20_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_ee_all_eta20_pu20->Fill(scet); eescsumet_all_eta20_pu20+=scet; } if (numgoodvtx>20) { scet_ee_all_eta20_pu30->Fill(scet); eescsumet_all_eta20_pu30+=scet; } if (numgoodvtx==10) { scet_ee_all_eta20_pueq10->Fill(scet); eescsumet_all_eta20_pueq10+=scet; } if (numgoodvtx==20) { scet_ee_all_eta20_pueq20->Fill(scet); eescsumet_all_eta20_pueq20+=scet; } if (numgoodvtx==1) { scet_ee_all_eta20_pueq01->Fill(scet); eescsumet_all_eta20_pueq01+=scet; } if (numgoodvtx==2) { scet_ee_all_eta20_pueq02->Fill(scet); eescsumet_all_eta20_pueq02+=scet; } if (numgoodvtx==3) { scet_ee_all_eta20_pueq03->Fill(scet); eescsumet_all_eta20_pueq03+=scet; } if (numgoodvtx==4) { scet_ee_all_eta20_pueq04->Fill(scet); eescsumet_all_eta20_pueq04+=scet; } if (numgoodvtx==5) { scet_ee_all_eta20_pueq05->Fill(scet); eescsumet_all_eta20_pueq05+=scet; } if (numgoodvtx==6) { scet_ee_all_eta20_pueq06->Fill(scet); eescsumet_all_eta20_pueq06+=scet; } if (numgoodvtx==7) { scet_ee_all_eta20_pueq07->Fill(scet); eescsumet_all_eta20_pueq07+=scet; } if (numgoodvtx==8) { scet_ee_all_eta20_pueq08->Fill(scet); eescsumet_all_eta20_pueq08+=scet; } if (numgoodvtx==9) { scet_ee_all_eta20_pueq09->Fill(scet); eescsumet_all_eta20_pueq09+=scet; } } if (fabs(sc_eta)>2.5) { scet_ee_all_eta25->Fill(scet); eescsumet_all_eta25+=scet; if (numgoodvtx<=10) { scet_ee_all_eta25_pu10->Fill(scet); eescsumet_all_eta25_pu10+=scet; } if (numgoodvtx>10 && numgoodvtx<=20) { scet_ee_all_eta25_pu20->Fill(scet); eescsumet_all_eta25_pu20+=scet; } if (numgoodvtx>20) { scet_ee_all_eta25_pu30->Fill(scet); eescsumet_all_eta25_pu30+=scet; } if (numgoodvtx==10) { scet_ee_all_eta25_pueq10->Fill(scet); eescsumet_all_eta25_pueq10+=scet; } if (numgoodvtx==20) { scet_ee_all_eta25_pueq20->Fill(scet); eescsumet_all_eta25_pueq20+=scet; } if (numgoodvtx==1) { scet_ee_all_eta25_pueq01->Fill(scet); eescsumet_all_eta25_pueq01+=scet; } if (numgoodvtx==2) { scet_ee_all_eta25_pueq02->Fill(scet); eescsumet_all_eta25_pueq02+=scet; } if (numgoodvtx==3) { scet_ee_all_eta25_pueq03->Fill(scet); eescsumet_all_eta25_pueq03+=scet; } if (numgoodvtx==4) { scet_ee_all_eta25_pueq04->Fill(scet); eescsumet_all_eta25_pueq04+=scet; } if (numgoodvtx==5) { scet_ee_all_eta25_pueq05->Fill(scet); eescsumet_all_eta25_pueq05+=scet; } if (numgoodvtx==6) { scet_ee_all_eta25_pueq06->Fill(scet); eescsumet_all_eta25_pueq06+=scet; } if (numgoodvtx==7) { scet_ee_all_eta25_pueq07->Fill(scet); eescsumet_all_eta25_pueq07+=scet; } if (numgoodvtx==8) { scet_ee_all_eta25_pueq08->Fill(scet); eescsumet_all_eta25_pueq08+=scet; } if (numgoodvtx==9) { scet_ee_all_eta25_pueq09->Fill(scet); eescsumet_all_eta25_pueq09+=scet; } } if (scet>2.0) { sceta_all_gt2->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt2->Fill(sc_eta); if (koot==0) sceta_koot0_gt2->Fill(sc_eta); eescsumet_all_gt2+=scet; if (sevlev==0) eescsumet_severity0_gt2+=scet; if (koot==0) eescsumet_koot0_gt2+=scet; } if (scet>5.0) { sceta_all_gt5->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt5->Fill(sc_eta); if (koot==0) sceta_koot0_gt5->Fill(sc_eta); eescsumet_all_gt5+=scet; if (sevlev==0) eescsumet_severity0_gt5+=scet; if (koot==0) eescsumet_koot0_gt5+=scet; } if (scet>10.0) { sceta_all_gt10->Fill(sc_eta); if (sevlev==0) sceta_severity0_gt10->Fill(sc_eta); if (koot==0) sceta_koot0_gt10->Fill(sc_eta); eescsumet_all_gt10+=scet; if (sevlev==0) eescsumet_severity0_gt10+=scet; if (koot==0) eescsumet_koot0_gt10+=scet; } if (scet>50.0) { scocc_ee_gt50->Fill(sc_phi,sc_eta); } // cout << "EE sc ene=" << scenergy << " sc et=" << scet << " sc_seeden=" << seeden << " sc eta=" << sc_eta << " sc_phi=" << sc_phi << " time=" << time << " koot=" << koot << " sevlev=" << sevlev << endl; } } scsumet_ee_all->Fill(eescsumet_all); scsumet_ee_severity0->Fill(eescsumet_severity0); scsumet_ee_koot0->Fill(eescsumet_koot0); scsumet_ee_all_eta15->Fill(eescsumet_all_eta15); scsumet_ee_all_eta20->Fill(eescsumet_all_eta20); scsumet_ee_all_eta25->Fill(eescsumet_all_eta25); scsumet_ee_all_eta15_pu10->Fill(eescsumet_all_eta15_pu10); scsumet_ee_all_eta20_pu10->Fill(eescsumet_all_eta20_pu10); scsumet_ee_all_eta25_pu10->Fill(eescsumet_all_eta25_pu10); scsumet_ee_all_eta15_pu20->Fill(eescsumet_all_eta15_pu20); scsumet_ee_all_eta20_pu20->Fill(eescsumet_all_eta20_pu20); scsumet_ee_all_eta25_pu20->Fill(eescsumet_all_eta25_pu20); scsumet_ee_all_eta15_pu30->Fill(eescsumet_all_eta15_pu30); scsumet_ee_all_eta20_pu30->Fill(eescsumet_all_eta20_pu30); scsumet_ee_all_eta25_pu30->Fill(eescsumet_all_eta25_pu30); scsumet_ee_all_eta15_pueq10->Fill(eescsumet_all_eta15_pueq10); scsumet_ee_all_eta20_pueq10->Fill(eescsumet_all_eta20_pueq10); scsumet_ee_all_eta25_pueq10->Fill(eescsumet_all_eta25_pueq10); scsumet_ee_all_eta15_pueq20->Fill(eescsumet_all_eta15_pueq20); scsumet_ee_all_eta20_pueq20->Fill(eescsumet_all_eta20_pueq20); scsumet_ee_all_eta25_pueq20->Fill(eescsumet_all_eta25_pueq20); scsumet_ee_all_eta15_pueq01->Fill(eescsumet_all_eta15_pueq01); scsumet_ee_all_eta20_pueq01->Fill(eescsumet_all_eta20_pueq01); scsumet_ee_all_eta25_pueq01->Fill(eescsumet_all_eta25_pueq01); scsumet_ee_all_eta15_pueq02->Fill(eescsumet_all_eta15_pueq02); scsumet_ee_all_eta20_pueq02->Fill(eescsumet_all_eta20_pueq02); scsumet_ee_all_eta25_pueq02->Fill(eescsumet_all_eta25_pueq02); scsumet_ee_all_eta15_pueq03->Fill(eescsumet_all_eta15_pueq03); scsumet_ee_all_eta20_pueq03->Fill(eescsumet_all_eta20_pueq03); scsumet_ee_all_eta25_pueq03->Fill(eescsumet_all_eta25_pueq03); scsumet_ee_all_eta15_pueq04->Fill(eescsumet_all_eta15_pueq04); scsumet_ee_all_eta20_pueq04->Fill(eescsumet_all_eta20_pueq04); scsumet_ee_all_eta25_pueq04->Fill(eescsumet_all_eta25_pueq04); scsumet_ee_all_eta15_pueq05->Fill(eescsumet_all_eta15_pueq05); scsumet_ee_all_eta20_pueq05->Fill(eescsumet_all_eta20_pueq05); scsumet_ee_all_eta25_pueq05->Fill(eescsumet_all_eta25_pueq05); scsumet_ee_all_eta15_pueq06->Fill(eescsumet_all_eta15_pueq06); scsumet_ee_all_eta20_pueq06->Fill(eescsumet_all_eta20_pueq06); scsumet_ee_all_eta25_pueq06->Fill(eescsumet_all_eta25_pueq06); scsumet_ee_all_eta15_pueq07->Fill(eescsumet_all_eta15_pueq07); scsumet_ee_all_eta20_pueq07->Fill(eescsumet_all_eta20_pueq07); scsumet_ee_all_eta25_pueq07->Fill(eescsumet_all_eta25_pueq07); scsumet_ee_all_eta15_pueq08->Fill(eescsumet_all_eta15_pueq08); scsumet_ee_all_eta20_pueq08->Fill(eescsumet_all_eta20_pueq08); scsumet_ee_all_eta25_pueq08->Fill(eescsumet_all_eta25_pueq08); scsumet_ee_all_eta15_pueq09->Fill(eescsumet_all_eta15_pueq09); scsumet_ee_all_eta20_pueq09->Fill(eescsumet_all_eta20_pueq09); scsumet_ee_all_eta25_pueq09->Fill(eescsumet_all_eta25_pueq09); scsumet_ee_all_gt2->Fill(eescsumet_all_gt2); scsumet_ee_severity0_gt2->Fill(eescsumet_severity0_gt2); scsumet_ee_koot0_gt2->Fill(eescsumet_koot0_gt2); scsumet_ee_all_gt5->Fill(eescsumet_all_gt5); scsumet_ee_severity0_gt5->Fill(eescsumet_severity0_gt5); scsumet_ee_koot0_gt5->Fill(eescsumet_koot0_gt5); scsumet_ee_all_gt10->Fill(eescsumet_all_gt10); scsumet_ee_severity0_gt10->Fill(eescsumet_severity0_gt10); scsumet_ee_koot0_gt10->Fill(eescsumet_koot0_gt10); EcalRecHit maxebhit; EBDetId maxebid(0); EcalRecHit maxeehit; EcalRecHit maxebhit2; EcalRecHit maxeehit2; float ensum1=0; float ensum2=0; float ensum3=0; float ensum4=0; float errsum1=0; float errsum2=0; int numgt1=0; rechitsumet_eb_all=0; rechitsumet_eb_01=0; rechitsumet_eb_05=0; rechitsumet_eb_0105=0; rechitsumet_eb_0530=0; rechitsumet_ee_all=0; rechitsumet_ee_01=0; rechitsumet_ee_05=0; rechitsumet_ee_0105=0; rechitsumet_ee_0530=0; // EB loop // cout << "starting rechit loop" << endl; for (EcalRecHitCollection::const_iterator hitItr = EBhits->begin(); hitItr != EBhits->end(); ++hitItr) { EcalRecHit hit = (*hitItr); EBDetId det = hit.id(); // const DetId det2 = hit.id(); float ampli = hit.energy(); float time = hit.time()-toffset; int ebflag = hit.recoFlag(); // int ebhashedid = det.hashedIndex(); const EcalIntercalibConstantMap &icalMap=eic->getMap(); float noiseingev=0; float pedg12=0; float pedrmsg12=0; int i=0; float noiseavg=0; float noisecount=0; const std::vector<DetId> neighs = neighbours(det); for (vector<DetId>::const_iterator vec=neighs.begin(); vec!=neighs.end();++vec) { EBDetId mydetid=(*vec); i++; // pedestals const EcalPedestals::Item *aped=0; int hashedid=mydetid.hashedIndex(); aped=&eped->barrel(hashedid); pedg12=aped->mean_x12; pedrmsg12=aped->rms_x12; // intercalibration constants EcalIntercalibConstantMap::const_iterator icalit=icalMap.find(mydetid); float icalconst=0; if (icalit!=icalMap.end()) icalconst=(*icalit); noiseingev=pedrmsg12*adctogevconst*icalconst; // cout << "hit=" << i << "ieta,iphi=" << mydetid.ieta() // << " " << mydetid.iphi() << " noise=" << pedrmsg12 // << " adc/gev=" << adctogevconst // << " ic=" << icalconst << " noise in gev=" << noiseingev << endl; if (noiseingev!=0) { noiseavg+=noiseingev; noisecount++; } } noiseavg/=noisecount; // cout << "average noise=" << noiseavg << endl; float_t chi2 = hit.chi2(); float_t chi2oot= 0; //hit.outOfTimeChi2(); GlobalPoint poseb=geo->getPosition(hit.detid()); float eta_eb=poseb.eta(); float phi_eb=poseb.phi(); float pf=1.0/cosh(eta_eb); float eteb=ampli*pf; int ieta=det.ieta(); int iphi=det.iphi(); int iphi_bin=iphi; int ieta_bin=ieta+86-int(ieta>0); noise2d->SetBinContent(iphi_bin,ieta_bin,pedrmsg12); // cout << "ieta=" << ieta << " iphi=" << iphi << " pedmean=" << pedg12 << " pedrms=" << pedrmsg12 << endl; float eb_r4a=0; float s4=0; float s4_2=0; float s41=0; float s42=0; float s43=0; float s44=0; float s45=0; float s46=0; float s47=0; float s48=0; float maxen=-1; int cursi=0; int cursj=0; s41 = recHitE( det, *EBhits, 1, 0 ); if (s41>maxen) { maxen=s41; cursi=1; cursj=0; } s42 = recHitE( det, *EBhits, -1, 0 ); if (s42>maxen) { maxen=s42; cursi=-1; cursj=0; } s43 = recHitE( det, *EBhits, 0, 1 ); if (s43>maxen) { maxen=s43; cursi=0; cursj=1; } s44 = recHitE( det, *EBhits, 0, -1 ); if (s44>maxen) { maxen=s44; cursi=0; cursj=-1; } s45 = recHitE( det, *EBhits, 1+cursi, 0+cursj ); s46 = recHitE( det, *EBhits, -1+cursi, 0+cursj ); s47 = recHitE( det, *EBhits, 0+cursi, 1+cursj ); s48 = recHitE( det, *EBhits, 0+cursi, -1+cursj ); s4=s41+s42+s43+s44; s4_2=s45+s46+s47+s48; float s6=s4+s4_2-ampli-maxen; if (ampli>0) eb_r4a=1.0-s4/ampli; // float eb_r4a_v2=1.0-e4e1(det, *EBhits); float eb_r4a_v3=1.0-e4e1v2(det, *EBhits); float e4overnoise=s4/noiseavg; float e6overe2=0; if (ampli>0) e6overe2=1.0-s6/(ampli+maxen); Bool_t is_swiss=false; if (ampli>4.0 && eb_r4a>0.95) is_swiss=true; Bool_t is_noisedep=false; if (ampli>4.0 && eb_r4a>1-(6.0*noiseavg)/ampli) is_noisedep=true; // float eb_r4a=1.0-e4e1(det,*EBhits); // float e6overe2=1.0-e6e2(det,*EBhits); // calculate e2/e9, e2/e25 for all hits with E>5.0 // Float_t emax=-999; //Int_t n1max=-111; //Int_t n2max=-111; if (pTopology.isValid() && pG.isValid() && eteb>3.0) { if (eb_r4a>0.95) r4count++; // const CaloTopology *topology=pTopology.product(); // const reco::BasicCluster *cluster=0; /* float e3x3tmp=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,hit.id(),-1,1,-1,1); float e5x5tmp=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,hit.id(),-2,2,-2,2); */ } // Int_t ee_kGood=0; // Int_t ee_kPoorReco=0; Int_t ee_kOutOfTime=0; // Int_t ee_kFaultyHardware=0; // Int_t ee_kNoisy=0; // Int_t ee_kPoorCalib=0; // Int_t ee_kSaturated=0; // Int_t ee_kLeadingEdgeRecovered=0; // Int_t ee_kNeighboursRecovered=0; // Int_t ee_kTowerRecovered=0; // Int_t ee_kDead=0; // Int_t ee_kKilled=0; // Int_t ee_kTPSaturated=0; // Int_t ee_kL1SpikeFlag=0; Int_t ee_kWeird=0; Int_t ee_kDiWeird=0; // Int_t ee_kUnknown=0; // if (hit.checkFlag(EcalRecHit::kGood)) ee_kGood=1; // if (hit.checkFlag(EcalRecHit::kPoorReco)) ee_kPoorReco=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) ee_kOutOfTime=1; // if (hit.checkFlag(EcalRecHit::kFaultyHardware)) ee_kFaultyHardware=1; // if (hit.checkFlag(EcalRecHit::kNoisy)) ee_kNoisy=1; // if (hit.checkFlag(EcalRecHit::kPoorCalib)) ee_kPoorCalib=1; // if (hit.checkFlag(EcalRecHit::kSaturated)) ee_kSaturated=1; // if (hit.checkFlag(EcalRecHit::kLeadingEdgeRecovered)) ee_kLeadingEdgeRecovered=1; // if (hit.checkFlag(EcalRecHit::kNeighboursRecovered)) ee_kNeighboursRecovered=1; // if (hit.checkFlag(EcalRecHit::kTowerRecovered)) ee_kTowerRecovered=1; // if (hit.checkFlag(EcalRecHit::kDead)) ee_kDead=1; // if (hit.checkFlag(EcalRecHit::kKilled)) ee_kKilled=1; // if (hit.checkFlag(EcalRecHit::kTPSaturated)) ee_kTPSaturated=1; // if (hit.checkFlag(EcalRecHit::kL1SpikeFlag)) ee_kL1SpikeFlag=1; if (hit.checkFlag(EcalRecHit::kWeird)) ee_kWeird=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) ee_kDiWeird=1; // if (hit.checkFlag(EcalRecHit::kUnknown)) ee_kUnknown=1; // int nearcrack=EBDetId::isNextToBoundary(det); // if (ampli>4.0 && eb_r4a>0.99 && ee_kWeird==0) { // cout << "ieta,iphi= " << ieta << "," << iphi << " ampli=" << ampli << " timing=" << time // << " s4=" << s4 << " s1,2,3,4=" << s41 << "," << s42 << "," << s43 << "," << s44 // << " \nswisscross1=" << eb_r4a << " swisscross2=" << eb_r4a_v2 << " swisscross3=" << eb_r4a_v3 << " kweird=" << ee_kWeird << " crack= " << nearcrack << endl; // } // check for hits close to boundaries //if (abs(ieta)==85) ee_kGood=0; //if (EcalTools::isNextToDeadFromNeighbours(det,*cstat,12)) ee_kGood=0; // mask out noisy channels in run D // ee_kWeird=1; // mask out bad channels if ((ieta==11 && iphi==68) || (ieta==68 && iphi==74) || (ieta==-83 && iphi==189) || (ieta==-75 && iphi==199) || (ieta==-81 && iphi==316)) continue; Int_t ebdigiadc=0; Int_t ebdigigain=0; char mytxteb[80]; Float_t ieta_tmp=float(ieta)+0.5; if (ieta>0) ieta_tmp=ieta_tmp-1; Float_t iphi_tmp=float(iphi)-0.5; EBDigiCollection::const_iterator digiItrEBa= EBdigis->begin(); while(digiItrEBa != EBdigis->end() && digiItrEBa->id() != hitItr->id()) { digiItrEBa++; } if (digiItrEBa != EBdigis->end() && eteb>2.0 && fabs(time)<5) { // cout << "digi: ieta,iphi=" << ieta << " " << iphi << endl; EBDataFrame df(*digiItrEBa); for(int i=0; i<10;++i) { ebdigiadc=df.sample(i).adc(); // ebdigiadc+=pedoff; ebdigigain=df.sample(i).gainId(); sprintf(mytxteb," %02d %04d %d",i+1,ebdigiadc,ebdigigain); // cout << mytxteb << endl; if (i<3) { etaphi_ped->Fill(iphi_tmp,ieta_tmp,ebdigiadc); etaphi_pedsq->Fill(iphi_tmp,ieta_tmp,ebdigiadc*ebdigiadc); etaphi_pedn->Fill(iphi_tmp,ieta_tmp,1.0); } } } Bool_t isspike=false; if (isMC_) { EBDigiCollection::const_iterator digiItrEB= EBdigis2->begin(); while(digiItrEB != EBdigis2->end() && digiItrEB->id() != hitItr->id()) { digiItrEB++; } if (digiItrEB != EBdigis2->end()) { EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { ebdigiadc=df.sample(i).adc(); ebdigigain=df.sample(i).gainId(); if (ebdigiadc>250 || ebdigigain!=1) { isspike=true; } } } } Bool_t matchsc=false; // float scenergy=0; // float sc_eta=0; // float sc_phi=0; // float scet=0; //cout << "before sc loop" << endl; for (reco::SuperClusterCollection::const_iterator sCEB = sc_eb->begin(); sCEB != sc_eb->end(); ++sCEB) { DetId seedid=sCEB->seed()->seed(); if (seedid==det) { matchsc=true; // scenergy=sCEB->energy(); // sc_eta=sCEB->eta(); // sc_phi=sCEB->phi(); // scet=scenergy/cosh(sc_eta); } } // supercluster //cout << "before sc" << endl; if (matchsc) { // cout << "in sc" << endl; eb_rechitenergy_sctag->Fill(ampli); swisscross_vs_energy_sctag->Fill(eb_r4a,ampli); time_vs_energy_sctag->Fill(time,ampli); //cout << "BP1" << endl; if (ee_kWeird) { eb_rechitenergy_sctag_kweird->Fill(ampli); swisscross_vs_energy_sctag_kweird->Fill(eb_r4a,ampli);; time_vs_energy_sctag_kweird->Fill(time,ampli); } //cout << "BP2" << endl; if (is_swiss) { eb_rechitenergy_sctag_swisscross->Fill(ampli); time_vs_energy_sctag_swisscross->Fill(time,ampli); } //cout << "BP3" << endl; if (is_noisedep) { eb_rechitenergy_sctag_noisedep->Fill(ampli); } //cout << "BP4" << endl; if (ampli>3.0) { eb_timing_vs_r4_sctag_3000->Fill(eb_r4a,time); } if (ampli>5.0) { eb_timing_vs_r4_sctag_5000->Fill(eb_r4a,time); } if (ampli>10.0) { eb_timing_vs_r4_sctag_10000->Fill(eb_r4a,time); } if (ampli>4.0) { // cout << "BP4a" << endl; e4_over_noise_sctag->Fill(e4overnoise); eb_timing_4000_sctag->Fill(time); eb_r4_4000_sctag->Fill(eb_r4a); eb_r6_4000_sctag->Fill(e6overe2); sc_vs_ieta_sctag_4000->Fill(abs(ieta)-0.5); swisscross_vs_ieta_sctag_4000->Fill(eb_r4a,abs(ieta)-0.5); if (ee_kWeird) { // cout << "BP4b" << endl; eb_timing_4000_sctag_kweird->Fill(time); sc_vs_ieta_sctag_4000_kweird->Fill(abs(ieta)-0.5); swisscross_vs_ieta_sctag_4000_kweird->Fill(eb_r4a,abs(ieta)-0.5); } if (is_swiss) { // cout << "BP4c" << endl; eb_timing_4000_sctag_swisscross->Fill(time); sc_vs_ieta_sctag_4000_swisscross->Fill(abs(ieta)-0.5); } if (is_noisedep) { // cout << "BP4d" << endl; eb_timing_4000_sctag_noisedep->Fill(time); sc_vs_ieta_sctag_4000_noisedep->Fill(abs(ieta)-0.5); } } //cout << "BP5" << endl; if (ampli>10.0) { // cout << "BP5a" << endl; eb_timing_10000_sctag->Fill(time); eb_r4_10000_sctag->Fill(eb_r4a); eb_r6_10000_sctag->Fill(e6overe2); sc_vs_ieta_sctag_10000->Fill(abs(ieta)-0.5); swisscross_vs_ieta_sctag_10000->Fill(eb_r4a,abs(ieta)-0.5); if (ee_kWeird) { // cout << "BP5b" << endl; eb_timing_10000_sctag_kweird->Fill(time); sc_vs_ieta_sctag_10000_kweird->Fill(abs(ieta)-0.5); swisscross_vs_ieta_sctag_10000_kweird->Fill(eb_r4a,abs(ieta)-0.5); } if (is_swiss) { // cout << "BP5c" << endl; eb_timing_10000_sctag_swisscross->Fill(time); sc_vs_ieta_sctag_10000_swisscross->Fill(abs(ieta)-0.5); } if (is_noisedep) { // cout << "BP5d" << endl; eb_timing_10000_sctag_noisedep->Fill(time); sc_vs_ieta_sctag_10000_noisedep->Fill(abs(ieta)-0.5); } } } // cout << "BP6" << endl; // spike truth - from MC if (isspike) { eb_rechitenergy_spiketag->Fill(ampli); swisscross_vs_energy_spiketag->Fill(eb_r4a_v3,ampli); time_vs_energy_spiketag->Fill(time,ampli); if (ee_kWeird) { eb_rechitenergy_spiketag_kweird->Fill(ampli); swisscross_vs_energy_spiketag_kweird->Fill(eb_r4a_v3,ampli);; time_vs_energy_spiketag_kweird->Fill(time,ampli); } if (is_swiss) { eb_rechitenergy_spiketag_swisscross->Fill(ampli); time_vs_energy_spiketag_swisscross->Fill(time,ampli); } if (is_noisedep) { eb_rechitenergy_spiketag_noisedep->Fill(ampli); } if (ampli>3.0) { eb_timing_3000_spiketag->Fill(time); eb_r4_3000_spiketag->Fill(eb_r4a); eb_r6_3000_spiketag->Fill(e6overe2); } if (ampli>4.0) { e4_over_noise_spiketag->Fill(e4overnoise); eb_timing_4000_spiketag->Fill(time); eb_r4_4000_spiketag->Fill(eb_r4a); eb_r6_4000_spiketag->Fill(e6overe2); spikes_vs_ieta_spiketag_4000->Fill(abs(ieta)-0.5); swisscross_vs_ieta_spiketag_4000->Fill(eb_r4a,abs(ieta)-0.5); if (ee_kWeird) { eb_timing_4000_spiketag_kweird->Fill(time); spikes_vs_ieta_spiketag_4000_kweird->Fill(abs(ieta)-0.5); swisscross_vs_ieta_spiketag_4000_kweird->Fill(eb_r4a,abs(ieta)-0.5); } if (is_swiss) { eb_timing_4000_spiketag_swisscross->Fill(time); spikes_vs_ieta_spiketag_4000_swisscross->Fill(abs(ieta)-0.5); } if (is_noisedep) { eb_timing_4000_spiketag_noisedep->Fill(time); spikes_vs_ieta_spiketag_4000_noisedep->Fill(abs(ieta)-0.5); } } if (ampli>10.0) { eb_timing_10000_spiketag->Fill(time); eb_r4_10000_spiketag->Fill(eb_r4a); eb_r6_10000_spiketag->Fill(e6overe2); spikes_vs_ieta_spiketag_10000->Fill(abs(ieta)-0.5); swisscross_vs_ieta_spiketag_10000->Fill(eb_r4a,abs(ieta)-0.5); if (ee_kWeird) { eb_timing_10000_spiketag_kweird->Fill(time); spikes_vs_ieta_spiketag_10000_kweird->Fill(abs(ieta)-0.5); swisscross_vs_ieta_spiketag_10000_kweird->Fill(eb_r4a,abs(ieta)-0.5); } if (is_swiss) { eb_timing_10000_spiketag_swisscross->Fill(time); spikes_vs_ieta_spiketag_10000_swisscross->Fill(abs(ieta)-0.5); } if (is_noisedep) { eb_timing_10000_spiketag_noisedep->Fill(time); spikes_vs_ieta_spiketag_10000_noisedep->Fill(abs(ieta)-0.5); } } } if (ee_kWeird==0) eb_rechitenergy_knotweird->Fill(ampli); Bool_t spikebytime=false; if (ampli>4.0 && abs(time)>3.0) spikebytime=true; if (spikebytime) { pu_vs_ene_spiketime->Fill(ampli,numgoodvtx); if (ee_kWeird) pu_vs_ene_spikekweird->Fill(ampli,numgoodvtx); if (is_swiss) pu_vs_ene_swisscross->Fill(ampli,numgoodvtx); if (ampli>4.0) { time_4gev_spiketime->Fill(time); pu_4gev_spiketime->Fill(numgoodvtx); ene_4gev_spiketime->Fill(ampli); if (ee_kWeird) { time_4gev_spikekweird->Fill(time); pu_4gev_spikekweird->Fill(numgoodvtx); ene_4gev_spikekweird->Fill(ampli); } if (is_swiss) { time_4gev_swisscross->Fill(time); pu_4gev_swisscross->Fill(numgoodvtx); ene_4gev_swisscross->Fill(ampli); } } if (ampli>10.0) { time_10gev_spiketime->Fill(time); pu_10gev_spiketime->Fill(numgoodvtx); ene_10gev_spiketime->Fill(ampli); if (ee_kWeird) { time_10gev_spikekweird->Fill(time); pu_10gev_spikekweird->Fill(numgoodvtx); ene_10gev_spikekweird->Fill(ampli); } if (is_swiss) { time_10gev_swisscross->Fill(time); pu_10gev_swisscross->Fill(numgoodvtx); ene_10gev_swisscross->Fill(ampli); } } } if (ee_kWeird==1) { numspikes_kweird++; eb_rechitenergy_kweird->Fill(ampli); if (ampli>4.0) { eb_timing_4000_kweird->Fill(time); eb_r4_4000_kweird->Fill(eb_r4a); eb_r6_4000_kweird->Fill(e6overe2); } if (ampli>10.0) { eb_timing_10000_kweird->Fill(time); eb_r4_10000_kweird->Fill(eb_r4a); eb_r6_10000_kweird->Fill(e6overe2); } } if (is_swiss) { numspikes_swisscross++; eb_rechitenergy_swisscross->Fill(ampli); if (ampli>4.0) { eb_timing_4000_swisscross->Fill(time); eb_r4_4000_swisscross->Fill(eb_r4a); eb_r6_4000_swisscross->Fill(e6overe2); } if (ampli>10.0) { eb_timing_10000_swisscross->Fill(time); eb_r4_10000_swisscross->Fill(eb_r4a); eb_r6_10000_swisscross->Fill(e6overe2); } } if (eteb>0.1) ebtime_vs_bxtrain_01->Fill(bunchintrain+0.5,time); if (eteb>0.5) ebtime_vs_bxtrain_05->Fill(bunchintrain+0.5,time); if (ampli>1.0) { ebsum_gt1+=ampli; ebhits1GeV++; } if (ampli>2.0) { ebsum_gt2+=ampli; ebhits2GeV++; } if (ampli>4.0) { ebsum_gt4+=ampli; ebhits4GeV++; } if (eteb>1.0) { ebsum_gt1et+=eteb; ebhits1GeVet++; } if (eteb>2.0) { ebsum_gt2et+=eteb; ebhits2GeVet++; } if (eteb>4.0) { ebsum_gt4et+=eteb; ebhits4GeVet++; } // rechit et sums rechitsumet_eb_all+=eteb; if (eteb>0.1) rechitsumet_eb_01+=eteb; if (eteb>0.5) rechitsumet_eb_05+=eteb; if (eteb>0.1 && eteb<=0.5) rechitsumet_eb_0105+=eteb; if (eteb>0.5 && eteb<=3.0) rechitsumet_eb_0530+=eteb; if (eteb>0.1) ebnumrechits_01++; if (eteb>0.5) ebnumrechits_05++; if (eteb>0.1 && eteb<=0.5) ebnumrechits_0105++; if (eteb>0.5 && eteb<=3.0) ebnumrechits_0530++; if (eteb>0.1) rechiteta_vs_bxtrain_01->Fill(bunchintrain,eta_eb); if (eteb>0.5) rechiteta_vs_bxtrain_05->Fill(bunchintrain,eta_eb); // do digi step // if (ampli>4.0) { float pedoff=0; if (isMC_) pedoff=0; if (!isMC_) pedoff=200-pedg12; // Int_t ebdigiadc=0; // Int_t ebdigigain=0; // char mytxteb[80]; EBDigiCollection::const_iterator digiItrEB= EBdigis->begin(); while(digiItrEB != EBdigis->end() && digiItrEB->id() != hitItr->id()) { digiItrEB++; } if (digiItrEB != EBdigis->end() && eteb>0.5) { // cout << "digi: ieta,iphi=" << ieta << " " << iphi << endl; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { ebdigiadc=df.sample(i).adc(); ebdigiadc+=pedoff; ebdigigain=df.sample(i).gainId(); sprintf(mytxteb," %02d %04d %d",i+1,ebdigiadc,ebdigigain); // cout << mytxteb << endl; if (i<3) { // etaphi_ped->Fill(iphi_tmp,ieta_tmp,ebdigiadc); // etaphi_pedsq->Fill(iphi_tmp,ieta_tmp,ebdigiadc*ebdigiadc); // etaphi_pedn->Fill(iphi_tmp,ieta_tmp,1.0); } eb_digi_01->Fill(i+0.5,ebdigiadc); if (eteb>0.5) eb_digi_05->Fill(i+0.5,ebdigiadc); if (eteb>0.1 && eteb<=0.5) { eb_digi_0105->Fill(i+0.5,float(ebdigiadc)); eb_digi_0105_vs_time->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_bxtrain->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_time_norm->Fill(time,i+0.5,1.0); eb_digi_0105_vs_bxtrain_norm->Fill(bunchintrain+0.5,i+0.5,1.0); if (abs(eb_eta)<0.5) { eb_digi_0105_vs_time_eta15->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_bxtrain_eta15->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_time_norm_eta15->Fill(time,i+0.5,1.0); eb_digi_0105_vs_bxtrain_norm_eta15->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(eb_eta)>=0.5 && abs(eb_eta)<1.0) { eb_digi_0105_vs_time_eta20->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_bxtrain_eta20->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_time_norm_eta20->Fill(time,i+0.5,1.0); eb_digi_0105_vs_bxtrain_norm_eta20->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(eb_eta)>=1.0) { eb_digi_0105_vs_time_eta25->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_bxtrain_eta25->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0105_vs_time_norm_eta25->Fill(time,i+0.5,1.0); eb_digi_0105_vs_bxtrain_norm_eta25->Fill(bunchintrain+0.5,i+0.5,1.0); } } if (eteb>0.5 && eteb<=3.0) { eb_digi_0530->Fill(i+0.5,ebdigiadc); eb_digi_0530_vs_time->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_bxtrain->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_time_norm->Fill(time,i+0.5,1.0); eb_digi_0530_vs_bxtrain_norm->Fill(bunchintrain+0.5,i+0.5,1.0); if (abs(eb_eta)<0.5) { eb_digi_0530_vs_time_eta15->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_bxtrain_eta15->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_time_norm_eta15->Fill(time,i+0.5,1.0); eb_digi_0530_vs_bxtrain_norm_eta15->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(eb_eta)>=0.5 && abs(eb_eta)<1.0) { eb_digi_0530_vs_time_eta20->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_bxtrain_eta20->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_time_norm_eta20->Fill(time,i+0.5,1.0); eb_digi_0530_vs_bxtrain_norm_eta20->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(eb_eta)>=1.0) { eb_digi_0530_vs_time_eta25->Fill(time,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_bxtrain_eta25->Fill(bunchintrain+0.5,i+0.5,float(ebdigiadc)); eb_digi_0530_vs_time_norm_eta25->Fill(time,i+0.5,1.0); eb_digi_0530_vs_bxtrain_norm_eta25->Fill(bunchintrain+0.5,i+0.5,1.0); } } } } //} eb_timing_0->Fill(time); eb_r4_0->Fill(eb_r4a); eb_timing_vs_r4_0->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_0->Fill(time); if (ampli>0.2) { eb_timing_200->Fill(time); eb_r4_200->Fill(eb_r4a); eb_timing_vs_r4_200->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_200->Fill(time); } if (ampli>0.4) { eb_timing_400->Fill(time); eb_r4_400->Fill(eb_r4a); eb_timing_vs_r4_400->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_400->Fill(time); } if (ampli>0.6) { eb_timing_600->Fill(time); eb_r4_600->Fill(eb_r4a); eb_timing_vs_r4_600->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_600->Fill(time); } if (ampli>0.8) { eb_timing_800->Fill(time); eb_r4_800->Fill(eb_r4a); eb_timing_vs_r4_800->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_800->Fill(time); } if (ampli>1.0) { eb_timing_1000->Fill(time); eb_r4_1000->Fill(eb_r4a); eb_r6_1000->Fill(e6overe2); eb_timing_vs_r4_1000->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_1000->Fill(time); numgt1++; } if (ampli>2.0) { eb_timing_2000->Fill(time); eb_r4_2000->Fill(eb_r4a); eb_r6_2000->Fill(e6overe2); eb_timing_vs_r4_2000->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_2000->Fill(time); } if (ampli>3.0) { eb_timing_3000->Fill(time); eb_r4_3000->Fill(eb_r4a); eb_r6_3000->Fill(e6overe2); eb_timing_vs_r4_3000->Fill(eb_r4a,time); eb_r4vsr6_3000->Fill(eb_r4a,e6overe2); if (eb_r4a<0.95) eb_timing_r4_3000->Fill(time); } if (ampli>4.0) { eb_timing_4000->Fill(time); eb_r4_4000->Fill(eb_r4a); eb_r6_4000->Fill(e6overe2); eb_r4vsr6_4000->Fill(eb_r4a,e6overe2); e4_over_noise->Fill(e4overnoise); } if (ampli>5.0) { eb_timing_5000->Fill(time); eb_r4_5000->Fill(eb_r4a); eb_r6_5000->Fill(e6overe2); eb_r4vsr6_5000->Fill(eb_r4a,e6overe2); eb_timing_vs_r4_5000->Fill(eb_r4a,time); if (eb_r4a<0.95) eb_timing_r4_5000->Fill(time); } if (ampli>10.0) { eb_timing_10000->Fill(time); eb_r4_10000->Fill(eb_r4a); eb_r6_10000->Fill(e6overe2); eb_r4vsr6_10000->Fill(eb_r4a,e6overe2); eb_timing_vs_r4_10000->Fill(eb_r4a,time); } eb_rechitenergy_->Fill(ampli); rechiteta_all->Fill(eta_eb); rechiteta_etweight->Fill(eta_eb,eteb); if (eteb>1.0) { rechiteta_gt1et->Fill(eta_eb); rechiteta_etweight_gt1et->Fill(eta_eb,eteb); if (numgoodvtx<10) rechiteta_gt1et_pu10->Fill(eta_eb); if (numgoodvtx>=10 && numgoodvtx<20) rechiteta_gt1et_pu20->Fill(eta_eb); if (numgoodvtx>20) rechiteta_gt1et_pu30->Fill(eta_eb); } if (fabs(eta_eb)<0.2) eb_rechitenergy_02->Fill(ampli); if (fabs(eta_eb)>=0.2 && fabs(eta_eb)<0.4) eb_rechitenergy_04->Fill(ampli); if (fabs(eta_eb)>=0.4 && fabs(eta_eb)<0.6) eb_rechitenergy_06->Fill(ampli); if (fabs(eta_eb)>=0.6 && fabs(eta_eb)<0.8) eb_rechitenergy_08->Fill(ampli); if (fabs(eta_eb)>=0.7 && fabs(eta_eb)<1.0) eb_rechitenergy_10->Fill(ampli); if (fabs(eta_eb)>=1.0 && fabs(eta_eb)<1.2) eb_rechitenergy_12->Fill(ampli); if (fabs(eta_eb)>=1.2 && fabs(eta_eb)<1.4) eb_rechitenergy_14->Fill(ampli); if (fabs(eta_eb)>=1.4) eb_rechitenergy_148->Fill(ampli); eb_rechitet_->Fill(eteb); if (fabs(eta_eb)<0.2) eb_rechitet_02->Fill(eteb); if (fabs(eta_eb)>=0.2 && fabs(eta_eb)<0.4) eb_rechitet_04->Fill(eteb); if (fabs(eta_eb)>=0.4 && fabs(eta_eb)<0.6) eb_rechitet_06->Fill(eteb); if (fabs(eta_eb)>=0.6 && fabs(eta_eb)<0.8) eb_rechitet_08->Fill(eteb); if (fabs(eta_eb)>=0.7 && fabs(eta_eb)<1.0) eb_rechitet_10->Fill(eteb); if (fabs(eta_eb)>=1.0 && fabs(eta_eb)<1.2) eb_rechitet_12->Fill(eteb); if (fabs(eta_eb)>=1.2 && fabs(eta_eb)<1.4) eb_rechitet_14->Fill(eteb); if (fabs(eta_eb)>=1.4) eb_rechitet_148->Fill(eteb); if (fabs(eta_eb)<0.5) eb_rechitetvspu_05->Fill(float(numgoodvtx)-0.5,eteb); if (fabs(eta_eb)>=0.5 && fabs(eta_eb)<1.0) eb_rechitetvspu_10->Fill(float(numgoodvtx)-0.5,eteb); if (fabs(eta_eb)>=1.0 && fabs(eta_eb)<1.5) eb_rechitetvspu_15->Fill(float(numgoodvtx)-0.5,eteb); ebocc->Fill(iphi_tmp,ieta_tmp,1.); eboccen->Fill(iphi_tmp,ieta_tmp,ampli); eboccet->Fill(iphi_tmp,ieta_tmp,eteb); // fill 2d arrays eventenergy->Fill(iphi_tmp,ieta_tmp,ampli); eventet->Fill(iphi_tmp,ieta_tmp,eteb); eventtime->Fill(iphi_tmp,ieta_tmp,time); if (ee_kOutOfTime) eventkoot->Fill(iphi_tmp,ieta_tmp,1.0); if (ee_kDiWeird) eventkdiweird->Fill(iphi_tmp,ieta_tmp,1.0); eb_rechiten_vs_eta->Fill(eta_eb,ampli); eb_rechitet_vs_eta->Fill(eta_eb,eteb); if (eteb>1.0) { eboccgt1et->Fill(iphi_tmp,ieta_tmp,1.); eboccetgt1et->Fill(iphi_tmp,ieta_tmp,eteb); } if (ampli>1.0) { eboccgt1->Fill(iphi_tmp,ieta_tmp,1.); eboccengt1->Fill(iphi_tmp,ieta_tmp,ampli); } if (ampli>3.0) { eboccgt3->Fill(iphi_tmp,ieta_tmp,1.); } if (ampli>5.0) { eboccgt5->Fill(iphi_tmp,ieta_tmp,1.); } //} // if (goodevent) { if (eteb>3.00) { float sigmat=28.51/(ampli/0.04)+sqrt(2)*0.2565; ensum1+=time*ampli; ensum2+=ampli; ensum3+=pow(ampli*sigmat,2); ensum4+=pow(ampli,2); errsum1+=time/pow(sigmat,2); errsum2+=1.0/pow(sigmat,2); } //} // if (ampli>ebmax && ((ampli<3) || (ampli>3 && abs(time)<4 && eb_r9t<0.90))) { if (ampli>ebmax) { ebmax=ampli; ebmaxet=eteb; eb_ieta=ieta; eb_iphi=iphi; eb_eta=eta_eb; eb_phi=phi_eb; ebtime=time; ebflags=ebflag; ebchi2=chi2; ebchi2oot=chi2oot; maxebhit=*hitItr; maxebid=det; // swisscross_algo=swisscross; // e2e9_algo=e2overe9tmp; } // if (!(ee_kWeird || ee_kDiWeird)) { ebhits++; if (ampli>1.0) ebhits1GeV++; // } } // end of eb loop // sfgvb loop - 1: spikes if (isMC_) { // int dframe[10]; for (EBDigiCollection::const_iterator digiItrEB= EBdigis2->begin(); digiItrEB != EBdigis2->end(); ++digiItrEB) { int adcmax=0; int gainmax=0; // int sampmax=0; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); // dframe[i]=ebdigiadc; if (ebdigiadc>adcmax) { adcmax=ebdigiadc; gainmax=ebdigigain; // sampmax=i+1; } } if (adcmax>250 || gainmax>1 ) { EBDetId spikedet=digiItrEB->id(); int spike_ieta=spikedet.ieta(); int spike_iphi=spikedet.iphi(); int iebin=spike_ieta+86-1*int(spike_ieta>0); double rechittime=eventtime->GetBinContent(spike_iphi,iebin); double rechitenergy=eventenergy->GetBinContent(spike_iphi,iebin); double rechitet=eventet->GetBinContent(spike_iphi,iebin); // cout << "Spike ieta,iphi=" << spike_ieta << ":" << spike_iphi // << " Spike ADC=" << adcmax << " Rechit et=" << rechitet // << " Rechit time=" << rechittime << endl; if (fabs(rechittime)<15 && rechittime != 0 && rechitenergy>2.0) { int iphi_min=(int((spike_iphi-1)/5))*5+1; int ieta_min=(int((abs(spike_ieta)-1)/5))*5; if (spike_ieta<0) ieta_min=-1*ieta_min-5; if (spike_ieta>0) ieta_min++; int goodhit=0; float spiketoweret=0; for (Int_t x=ieta_min;x<ieta_min+5;x++) { for (Int_t y=iphi_min;y<iphi_min+5;y++) { int ietabin=x+86-1*int(x>0); double myene=eventenergy->GetBinContent(y,ietabin); double myet=eventet->GetBinContent(y,ietabin); double mytime=eventtime->GetBinContent(y,ietabin); if (myene !=0 && mytime!=0) goodhit++; spiketoweret+=myet; } } if (goodhit==25 && spiketoweret>5.0) { double e4swiss=0; double et4swiss=0; double e4swisstt=0; double et4swisstt=0; double ene_swiss1=0; double et_swiss1=0; double time_swiss1=0; double koot_swiss1=0; double kdw_swiss1=0; double ene_swiss2=0; double et_swiss2=0; double time_swiss2=0; double koot_swiss2=0; double kdw_swiss2=0; double ene_swiss3=0; double et_swiss3=0; double time_swiss3=0; double koot_swiss3=0; double kdw_swiss3=0; double ene_swiss4=0; double et_swiss4=0; double time_swiss4=0; double koot_swiss4=0; double kdw_swiss4=0; double et_swissmax=0; double time_swissmax=0; double koot_swissmax=0; double kdw_swissmax=0; // cout << " SPIKE, ieta:iphi=" << spike_ieta << ":" << spike_iphi // << " e=" << rechitenergy << " et=" << rechitet << endl; int xco=0; int yco=0; xco=spike_ieta; yco=spike_iphi-1; if (yco==0) yco=360; int ietabin=xco+86-1*int(xco>0); double myene=eventenergy->GetBinContent(yco,ietabin); double myet=eventet->GetBinContent(yco,ietabin); double mytime=eventtime->GetBinContent(yco,ietabin); double mykoot=eventkoot->GetBinContent(yco,ietabin); double mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss1=myene; et_swiss1=myet; time_swiss1=mytime; koot_swiss1=mykoot; kdw_swiss1=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (yco>=iphi_min) { e4swisstt+=myene; et4swisstt+=myet; } // cout << xco << ":" << yco << " e=" << myene << " et=" << myet // << " e4swiss=" << e4swiss << " et4swiss=" << et4swiss // << " e4swisstt=" << e4swisstt << " et4swisstt=" << et4swisstt << endl; xco=spike_ieta; yco=spike_iphi+1; if (yco>360) yco=1; ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss2=myene; et_swiss2=myet; time_swiss2=mytime; koot_swiss2=mykoot; kdw_swiss2=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (yco<iphi_min+5) { e4swisstt+=myene; et4swisstt+=myet; } // cout << xco << ":" << yco << " e=" << myene << " et=" << myet // << " e4swiss=" << e4swiss << " et4swiss=" << et4swiss // << " e4swisstt=" << e4swisstt << " et4swisstt=" << et4swisstt << endl; xco=spike_ieta+1; yco=spike_iphi; if (xco<86) { ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss3=myene; et_swiss3=myet; time_swiss3=mytime; koot_swiss3=mykoot; kdw_swiss3=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (xco<ieta_min+5) { e4swisstt+=myene; et4swisstt+=myet; } } // cout << xco << ":" << yco << " e=" << myene << " et=" << myet // << " e4swiss=" << e4swiss << " et4swiss=" << et4swiss // << " e4swisstt=" << e4swisstt << " et4swisstt=" << et4swisstt << endl; xco=spike_ieta-1; yco=spike_iphi; if (xco>-86) { ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss4=myene; et_swiss4=myet; time_swiss4=mytime; koot_swiss4=mykoot; kdw_swiss4=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (xco>=ieta_min) { e4swisstt+=myene; et4swisstt+=myet; } } // cout << xco << ":" << yco << " e=" << myene << " et=" << myet // << " e4swiss=" << e4swiss << " et4swiss=" << et4swiss // << " e4swisstt=" << e4swisstt << " et4swisstt=" << et4swisstt << endl; if (spiketoweret>=15.0) { // check status of spikes with swisscross<0.8 if (1.0-e4swiss/rechitenergy<0.8) { spike_timevset_all_08->Fill(time_swiss1,et_swiss1); spike_timevset_all_08->Fill(time_swiss2,et_swiss2); spike_timevset_all_08->Fill(time_swiss3,et_swiss3); spike_timevset_all_08->Fill(time_swiss4,et_swiss4); spike_timevset_highest_08->Fill(time_swissmax,et_swissmax); if (koot_swiss1) spike_timevset_koot_all_08->Fill(time_swiss1,et_swiss1); if (koot_swiss2) spike_timevset_koot_all_08->Fill(time_swiss2,et_swiss2); if (koot_swiss3) spike_timevset_koot_all_08->Fill(time_swiss3,et_swiss3); if (koot_swiss4) spike_timevset_koot_all_08->Fill(time_swiss4,et_swiss4); if (koot_swissmax) spike_timevset_koot_highest_08->Fill(time_swissmax,et_swissmax); if (kdw_swiss1) spike_timevset_kdiweird_all_08->Fill(time_swiss1,et_swiss1); if (kdw_swiss2) spike_timevset_kdiweird_all_08->Fill(time_swiss2,et_swiss2); if (kdw_swiss3) spike_timevset_kdiweird_all_08->Fill(time_swiss3,et_swiss3); if (kdw_swiss4) spike_timevset_kdiweird_all_08->Fill(time_swiss4,et_swiss4); if (kdw_swissmax) spike_timevset_kdiweird_highest_08->Fill(time_swissmax,et_swissmax); } // check status of spikes with swisscross<0.7 if (1.0-e4swiss/rechitenergy<0.7) { spike_timevset_all_07->Fill(time_swiss1,et_swiss1); spike_timevset_all_07->Fill(time_swiss2,et_swiss2); spike_timevset_all_07->Fill(time_swiss3,et_swiss3); spike_timevset_all_07->Fill(time_swiss4,et_swiss4); spike_timevset_highest_07->Fill(time_swissmax,et_swissmax); if (koot_swiss1) spike_timevset_koot_all_07->Fill(time_swiss1,et_swiss1); if (koot_swiss2) spike_timevset_koot_all_07->Fill(time_swiss2,et_swiss2); if (koot_swiss3) spike_timevset_koot_all_07->Fill(time_swiss3,et_swiss3); if (koot_swiss4) spike_timevset_koot_all_07->Fill(time_swiss4,et_swiss4); if (koot_swissmax) spike_timevset_koot_highest_07->Fill(time_swissmax,et_swissmax); if (kdw_swiss1) spike_timevset_kdiweird_all_07->Fill(time_swiss1,et_swiss1); if (kdw_swiss2) spike_timevset_kdiweird_all_07->Fill(time_swiss2,et_swiss2); if (kdw_swiss3) spike_timevset_kdiweird_all_07->Fill(time_swiss3,et_swiss3); if (kdw_swiss4) spike_timevset_kdiweird_all_07->Fill(time_swiss4,et_swiss4); if (kdw_swissmax) spike_timevset_kdiweird_highest_07->Fill(time_swissmax,et_swissmax); } // check status of spikes with swisscross<0.6 if (1.0-e4swiss/rechitenergy<0.6) { spike_timevset_all_06->Fill(time_swiss1,et_swiss1); spike_timevset_all_06->Fill(time_swiss2,et_swiss2); spike_timevset_all_06->Fill(time_swiss3,et_swiss3); spike_timevset_all_06->Fill(time_swiss4,et_swiss4); spike_timevset_highest_06->Fill(time_swissmax,et_swissmax); if (koot_swiss1) spike_timevset_koot_all_06->Fill(time_swiss1,et_swiss1); if (koot_swiss2) spike_timevset_koot_all_06->Fill(time_swiss2,et_swiss2); if (koot_swiss3) spike_timevset_koot_all_06->Fill(time_swiss3,et_swiss3); if (koot_swiss4) spike_timevset_koot_all_06->Fill(time_swiss4,et_swiss4); if (koot_swissmax) spike_timevset_koot_highest_06->Fill(time_swissmax,et_swissmax); if (kdw_swiss1) spike_timevset_kdiweird_all_06->Fill(time_swiss1,et_swiss1); if (kdw_swiss2) spike_timevset_kdiweird_all_06->Fill(time_swiss2,et_swiss2); if (kdw_swiss3) spike_timevset_kdiweird_all_06->Fill(time_swiss3,et_swiss3); if (kdw_swiss4) spike_timevset_kdiweird_all_06->Fill(time_swiss4,et_swiss4); if (kdw_swissmax) spike_timevset_kdiweird_highest_06->Fill(time_swissmax,et_swissmax); } } double swisst10=0; double swisst07=0; double swisst05=0; double swisst04=0; double swisst03=0; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<10)) swisst10+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<10)) swisst10+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<10)) swisst10+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<10)) swisst10+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<7)) swisst07+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<7)) swisst07+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<7)) swisst07+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<7)) swisst07+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<5)) swisst05+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<5)) swisst05+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<5)) swisst05+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<5)) swisst05+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<4)) swisst04+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<4)) swisst04+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<4)) swisst04+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<4)) swisst04+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<3)) swisst03+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<3)) swisst03+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<3)) swisst03+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<3)) swisst03+=ene_swiss4; double swisscross10=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<10)) swisscross10=1.0-swisst10/rechitenergy; double swisscross07=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<7)) swisscross07=1.0-swisst10/rechitenergy; double swisscross05=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<5)) swisscross05=1.0-swisst10/rechitenergy; double swisscross04=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<4)) swisscross04=1.0-swisst10/rechitenergy; double swisscross03=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<3)) swisscross03=1.0-swisst10/rechitenergy; for (Int_t nn=0;nn<100;nn++) { double thresh=nn*0.02+0.01-0.5; double swisscut=0.21+0.01*nn; int probet_swisstt=0; int probet_swiss=0; int probene_swisstt=0; int probene_swiss=0; int probene_swiss_t10=0; int probene_swiss_t07=0; int probene_swiss_t05=0; int probene_swiss_t04=0; int probene_swiss_t03=0; if (1.0-e4swiss/rechitenergy>swisscut) probene_swiss=1; if (1.0-et4swiss/rechitet>swisscut) probet_swiss=1; if (1.0-e4swisstt/rechitenergy>swisscut) probene_swisstt=1; if (1.0-et4swisstt/rechitet>swisscut) probet_swisstt=1; if (swisscross10>swisscut) probene_swiss_t10=1; if (swisscross07>swisscut) probene_swiss_t07=1; if (swisscross05>swisscut) probene_swiss_t05=1; if (swisscross04>swisscut) probene_swiss_t04=1; if (swisscross03>swisscut) probene_swiss_t03=1; // thresh=0.5; int stripetcount=0; int stripenecount=0; int alletcount=0; int allenecount=0; for (Int_t x=ieta_min;x<ieta_min+5;x++) { stripetcount=0; stripenecount=0; for (Int_t y=iphi_min;y<iphi_min+5;y++) { int ietabin=x+86-1*int(x>0); double myene=eventenergy->GetBinContent(y,ietabin); double myet=eventet->GetBinContent(y,ietabin); // double mytime=eventtime->GetBinContent(y,ietabin); if (myene>thresh) stripenecount++; if (myet>thresh) stripetcount++; // cout << "ieta=" << x << " iphi=" << y // << " ene=" << myene << " et=" << myet << " time=" << mytime <<endl; } int stripetprob=0; int stripeneprob=0; if (stripenecount>1) stripeneprob=1; if (stripetcount>1) stripetprob=1; strip_prob_ene->Fill(thresh,stripeneprob); strip_prob_et->Fill(thresh,stripetprob); strip_prob_ene_pu->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu->Fill(thresh,stripetprob,numgoodvtx); if (spiketoweret>=8.0) { strip_prob_ene_thresh08->Fill(thresh,stripeneprob); strip_prob_et_thresh08->Fill(thresh,stripetprob); strip_prob_ene_pu_thresh08->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu_thresh08->Fill(thresh,stripetprob,numgoodvtx); } if (spiketoweret>=10.0) { strip_prob_ene_thresh10->Fill(thresh,stripeneprob); strip_prob_et_thresh10->Fill(thresh,stripetprob); strip_prob_ene_pu_thresh10->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu_thresh10->Fill(thresh,stripetprob,numgoodvtx); } if (spiketoweret>=12.0) { strip_prob_ene_thresh12->Fill(thresh,stripeneprob); strip_prob_et_thresh12->Fill(thresh,stripetprob); strip_prob_ene_pu_thresh12->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu_thresh12->Fill(thresh,stripetprob,numgoodvtx); } if (spiketoweret>=15.0) { strip_prob_ene_thresh15->Fill(thresh,stripeneprob); strip_prob_et_thresh15->Fill(thresh,stripetprob); strip_prob_ene_pu_thresh15->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu_thresh15->Fill(thresh,stripetprob,numgoodvtx); } if (spiketoweret>=20.0) { strip_prob_ene_thresh20->Fill(thresh,stripeneprob); strip_prob_et_thresh20->Fill(thresh,stripetprob); strip_prob_ene_pu_thresh20->Fill(thresh,stripeneprob,numgoodvtx); strip_prob_et_pu_thresh20->Fill(thresh,stripetprob,numgoodvtx); } if (abs(spike_ieta)<=25) { strip_prob_ene_mod1->Fill(thresh,stripeneprob); strip_prob_et_mod1->Fill(thresh,stripetprob); } if (abs(spike_ieta)>25 && abs(spike_ieta)<=45) { strip_prob_ene_mod2->Fill(thresh,stripeneprob); strip_prob_et_mod2->Fill(thresh,stripetprob); } if (abs(spike_ieta)>45 && abs(spike_ieta)<=65) { strip_prob_ene_mod3->Fill(thresh,stripeneprob); strip_prob_et_mod3->Fill(thresh,stripetprob); } if (abs(spike_ieta)>65) { strip_prob_ene_mod4->Fill(thresh,stripeneprob); strip_prob_et_mod4->Fill(thresh,stripetprob); } if (numgoodvtx<=10) { strip_prob_ene_pu0->Fill(thresh,stripeneprob); strip_prob_et_pu0->Fill(thresh,stripetprob); } if (numgoodvtx>10 && numgoodvtx<=20) { strip_prob_ene_pu10->Fill(thresh,stripeneprob); strip_prob_et_pu10->Fill(thresh,stripetprob); } if (numgoodvtx>20) { strip_prob_ene_pu20->Fill(thresh,stripeneprob); strip_prob_et_pu20->Fill(thresh,stripetprob); } if (adcmax>300 || gainmax>1) { strip_prob_ene_300->Fill(thresh,stripeneprob); strip_prob_et_300->Fill(thresh,stripetprob); } // cout << " stripenecount=" << stripenecount << " stripetcount=" << stripetcount << endl; allenecount+=stripeneprob; alletcount+=stripetprob; } // cout << " allenecount=" << allenecount << " alletcount=" << alletcount << endl; int sfgvb_tower_et=0; int sfgvb_tower_ene=0; if (allenecount==0) sfgvb_tower_ene=1; if (alletcount==0) sfgvb_tower_et=1; // cout << " sfgvb_ene=" << sfgvb_tower_ene << " sfgvb_et=" << sfgvb_tower_et << endl; tower_spike_ene->Fill(thresh,sfgvb_tower_ene); tower_spike_et->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss->Fill(swisscut,probene_swiss); tower_spike_et_swiss->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03->Fill(swisscut,probene_swiss_t03); if (spiketoweret>=8.0) { tower_spike_ene_thresh08->Fill(thresh,sfgvb_tower_ene); tower_spike_et_thresh08->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu_thresh08->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu_thresh08->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss_thresh08->Fill(swisscut,probene_swiss); tower_spike_et_swiss_thresh08->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt_thresh08->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt_thresh08->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10_thresh08->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07_thresh08->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05_thresh08->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04_thresh08->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03_thresh08->Fill(swisscut,probene_swiss_t03); } if (spiketoweret>=10.0) { tower_spike_ene_thresh10->Fill(thresh,sfgvb_tower_ene); tower_spike_et_thresh10->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu_thresh10->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu_thresh10->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss_thresh10->Fill(swisscut,probene_swiss); tower_spike_et_swiss_thresh10->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt_thresh10->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt_thresh10->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10_thresh10->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07_thresh10->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05_thresh10->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04_thresh10->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03_thresh10->Fill(swisscut,probene_swiss_t03); } if (spiketoweret>=12.0) { tower_spike_ene_thresh12->Fill(thresh,sfgvb_tower_ene); tower_spike_et_thresh12->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu_thresh12->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu_thresh12->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss_thresh12->Fill(swisscut,probene_swiss); tower_spike_et_swiss_thresh12->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt_thresh12->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt_thresh12->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10_thresh12->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07_thresh12->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05_thresh12->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04_thresh12->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03_thresh12->Fill(swisscut,probene_swiss_t03); } if (spiketoweret>=15.0) { tower_spike_ene_thresh15->Fill(thresh,sfgvb_tower_ene); tower_spike_et_thresh15->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu_thresh15->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu_thresh15->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss_thresh15->Fill(swisscut,probene_swiss); tower_spike_et_swiss_thresh15->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt_thresh15->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt_thresh15->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10_thresh15->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07_thresh15->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05_thresh15->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04_thresh15->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03_thresh15->Fill(swisscut,probene_swiss_t03); // cout << "Spike: ADC=" << adcmax-200 << " maxsamp=" << sampmax << " ieta,iphi=" << spike_ieta // << "," << spike_iphi << " rechit time=" << rechittime << endl; // cout << "iphi_min=" << iphi_min << " ieta_min=" << ieta_min << endl; // cout << "spike digis:" << endl; // for (Int_t id=0;id<10;id++) cout << dframe[id] << endl; // cout << "sFGVB=" << sfgvb_tower_et << endl; // cout << "rechits: " << endl; // for (Int_t x=ieta_min;x<ieta_min+5;x++) { // for (Int_t y=iphi_min;y<iphi_min+5;y++) { // int ietabin=x+86-1*int(x>0); // double myene=eventenergy->GetBinContent(y,ietabin); // double myet=eventet->GetBinContent(y,ietabin); // double mytime=eventtime->GetBinContent(y,ietabin); // cout << "ieta=" << x << " iphi=" << y // << " ene=" << myene << " et=" << myet << " time=" << mytime <<endl; // } // } } if (spiketoweret>=20.0) { tower_spike_ene_thresh20->Fill(thresh,sfgvb_tower_ene); tower_spike_et_thresh20->Fill(thresh,sfgvb_tower_et); tower_spike_ene_pu_thresh20->Fill(thresh,sfgvb_tower_ene,numgoodvtx); tower_spike_et_pu_thresh20->Fill(thresh,sfgvb_tower_et,numgoodvtx); tower_spike_ene_swiss_thresh20->Fill(swisscut,probene_swiss); tower_spike_et_swiss_thresh20->Fill(swisscut,probet_swiss); tower_spike_ene_swisstt_thresh20->Fill(swisscut,probene_swisstt); tower_spike_et_swisstt_thresh20->Fill(swisscut,probet_swisstt); tower_spike_ene_swiss_t10_thresh20->Fill(swisscut,probene_swiss_t10); tower_spike_ene_swiss_t07_thresh20->Fill(swisscut,probene_swiss_t07); tower_spike_ene_swiss_t05_thresh20->Fill(swisscut,probene_swiss_t05); tower_spike_ene_swiss_t04_thresh20->Fill(swisscut,probene_swiss_t04); tower_spike_ene_swiss_t03_thresh20->Fill(swisscut,probene_swiss_t03); } if (abs(spike_ieta)<=25) { tower_spike_ene_mod1->Fill(thresh,sfgvb_tower_ene); tower_spike_et_mod1->Fill(thresh,sfgvb_tower_et); } if (abs(spike_ieta)>25 && abs(spike_ieta)<=45) { tower_spike_ene_mod2->Fill(thresh,sfgvb_tower_ene); tower_spike_et_mod2->Fill(thresh,sfgvb_tower_et); } if (abs(spike_ieta)>45 && abs(spike_ieta)<=65) { tower_spike_ene_mod3->Fill(thresh,sfgvb_tower_ene); tower_spike_et_mod3->Fill(thresh,sfgvb_tower_et); } if (abs(spike_ieta)>65) { tower_spike_ene_mod4->Fill(thresh,sfgvb_tower_ene); tower_spike_et_mod4->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx<=10) { tower_spike_ene_pu0->Fill(thresh,sfgvb_tower_ene); tower_spike_et_pu0->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx>10 && numgoodvtx<=20) { tower_spike_ene_pu10->Fill(thresh,sfgvb_tower_ene); tower_spike_et_pu10->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx>20) { tower_spike_ene_pu20->Fill(thresh,sfgvb_tower_ene); tower_spike_et_pu20->Fill(thresh,sfgvb_tower_et); } if (adcmax>300 || gainmax>1) { tower_spike_ene_300->Fill(thresh,sfgvb_tower_ene); tower_spike_et_300->Fill(thresh,sfgvb_tower_et); } } } } } } } // sfgvb loop - 2: superclusters if (!isMC_) { for (reco::SuperClusterCollection::const_iterator sCEB = sc_eb->begin(); sCEB != sc_eb->end(); ++sCEB) { EBDetId seedid=sCEB->seed()->seed(); // float scenergy=sCEB->energy(); //float sc_eta=sCEB->eta(); //float sc_phi=sCEB->phi(); //float scet=scenergy/cosh(sc_eta); int sc_ieta=seedid.ieta(); int sc_iphi=seedid.iphi(); int iebin=sc_ieta+86-1*int(sc_ieta>0); double rechitenergy=eventenergy->GetBinContent(sc_iphi,iebin); double rechittime=eventtime->GetBinContent(sc_iphi,iebin); double rechitet=eventet->GetBinContent(sc_iphi,iebin); if (fabs(rechittime)<15 && rechittime != 0 && rechitenergy>4.0) { int iphi_min=(int((sc_iphi-1)/5))*5+1; int ieta_min=(int((abs(sc_ieta)-1)/5))*5; if (sc_ieta<0) ieta_min=-1*ieta_min-5; if (sc_ieta>0) ieta_min++; int goodhit=0; float sctoweret=0; for (Int_t x=ieta_min;x<ieta_min+5;x++) { for (Int_t y=iphi_min;y<iphi_min+5;y++) { int ietabin=x+86-1*int(x>0); double myene=eventenergy->GetBinContent(y,ietabin); double myet=eventet->GetBinContent(y,ietabin); double mytime=eventtime->GetBinContent(y,ietabin); if (myene !=0 && mytime!=0) goodhit++; sctoweret+=myet; } } if (goodhit==25 && sctoweret>5.0) { double e4swiss=0; double et4swiss=0; double e4swisstt=0; double et4swisstt=0; double ene_swiss1=0; double et_swiss1=0; double time_swiss1=0; double koot_swiss1=0; double kdw_swiss1=0; double ene_swiss2=0; double et_swiss2=0; double time_swiss2=0; double koot_swiss2=0; double kdw_swiss2=0; double ene_swiss3=0; double et_swiss3=0; double time_swiss3=0; double koot_swiss3=0; double kdw_swiss3=0; double ene_swiss4=0; double et_swiss4=0; double time_swiss4=0; double koot_swiss4=0; double kdw_swiss4=0; double et_swissmax=0.001; double time_swissmax=0; double koot_swissmax=0; double kdw_swissmax=0; int xco=0; int yco=0; xco=sc_ieta; yco=sc_iphi-1; if (yco==0) yco=360; int ietabin=xco+86-1*int(xco>0); double myene=eventenergy->GetBinContent(yco,ietabin); double myet=eventet->GetBinContent(yco,ietabin); double mytime=eventtime->GetBinContent(yco,ietabin); double mykoot=eventkoot->GetBinContent(yco,ietabin); double mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss1=myene; et_swiss1=myet; time_swiss1=mytime; koot_swiss1=mykoot; kdw_swiss1=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (yco>=iphi_min) { e4swisstt+=myene; et4swisstt+=myet; } xco=sc_ieta; yco=sc_iphi+1; if (yco>360) yco=1; ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss2=myene; et_swiss2=myet; time_swiss2=mytime; koot_swiss2=mykoot; kdw_swiss2=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (yco<iphi_min+5) { e4swisstt+=myene; et4swisstt+=myet; } xco=sc_ieta+1; yco=sc_iphi; if (xco<86) { ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss3=myene; et_swiss3=myet; time_swiss3=mytime; koot_swiss3=mykoot; kdw_swiss3=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (xco<ieta_min+5) { e4swisstt+=myene; et4swisstt+=myet; } } xco=sc_ieta-1; yco=sc_iphi; if (xco>-86) { ietabin=xco+86-1*int(xco>0); myene=eventenergy->GetBinContent(yco,ietabin); myet=eventet->GetBinContent(yco,ietabin); mytime=eventtime->GetBinContent(yco,ietabin); mykoot=eventkoot->GetBinContent(yco,ietabin); mykdw=eventkdiweird->GetBinContent(yco,ietabin); ene_swiss4=myene; et_swiss4=myet; time_swiss4=mytime; koot_swiss4=mykoot; kdw_swiss4=mykdw; if (myet>et_swissmax) { et_swissmax=myet; time_swissmax=mytime; koot_swissmax=mykoot; kdw_swissmax=mykdw; } e4swiss+=myene; et4swiss+=myet; if (xco>=ieta_min) { e4swisstt+=myene; et4swisstt+=myet; } } // check status of spikes with swisscross<0.8 if (1.0-e4swiss/rechitenergy<0.8) { spike_timevset_all_08->Fill(time_swiss1,et_swiss1); spike_timevset_all_08->Fill(time_swiss2,et_swiss2); spike_timevset_all_08->Fill(time_swiss3,et_swiss3); spike_timevset_all_08->Fill(time_swiss4,et_swiss4); spike_timevset_highest_08->Fill(time_swissmax,et_swissmax); if (koot_swiss1) spike_timevset_koot_all_08->Fill(time_swiss1,et_swiss1); if (koot_swiss2) spike_timevset_koot_all_08->Fill(time_swiss2,et_swiss2); if (koot_swiss3) spike_timevset_koot_all_08->Fill(time_swiss3,et_swiss3); if (koot_swiss4) spike_timevset_koot_all_08->Fill(time_swiss4,et_swiss4); if (koot_swissmax) spike_timevset_koot_highest_08->Fill(time_swissmax,et_swissmax); if (kdw_swiss1) spike_timevset_kdiweird_all_08->Fill(time_swiss1,et_swiss1); if (kdw_swiss2) spike_timevset_kdiweird_all_08->Fill(time_swiss2,et_swiss2); if (kdw_swiss3) spike_timevset_kdiweird_all_08->Fill(time_swiss3,et_swiss3); if (kdw_swiss4) spike_timevset_kdiweird_all_08->Fill(time_swiss4,et_swiss4); if (kdw_swissmax) spike_timevset_kdiweird_highest_08->Fill(time_swissmax,et_swissmax); } double swisst10=0; double swisst07=0; double swisst05=0; double swisst04=0; double swisst03=0; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<10)) swisst10+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<10)) swisst10+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<10)) swisst10+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<10)) swisst10+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<7)) swisst07+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<7)) swisst07+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<7)) swisst07+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<7)) swisst07+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<5)) swisst05+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<5)) swisst05+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<5)) swisst05+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<5)) swisst05+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<4)) swisst04+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<4)) swisst04+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<4)) swisst04+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<4)) swisst04+=ene_swiss4; if (ene_swiss1<2.0 || (ene_swiss1>=2.0 && abs(time_swiss1)<3)) swisst03+=ene_swiss1; if (ene_swiss2<2.0 || (ene_swiss2>=2.0 && abs(time_swiss2)<3)) swisst03+=ene_swiss2; if (ene_swiss3<2.0 || (ene_swiss3>=2.0 && abs(time_swiss3)<3)) swisst03+=ene_swiss3; if (ene_swiss4<2.0 || (ene_swiss4>=2.0 && abs(time_swiss4)<3)) swisst03+=ene_swiss4; double swisscross10=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<10)) swisscross10=1.0-swisst10/rechitenergy; double swisscross07=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<7)) swisscross07=1.0-swisst10/rechitenergy; double swisscross05=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<5)) swisscross05=1.0-swisst10/rechitenergy; double swisscross04=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<4)) swisscross04=1.0-swisst10/rechitenergy; double swisscross03=1.0; if (rechitenergy<2.0 || (rechitenergy>2.0 && abs(rechittime)<3)) swisscross03=1.0-swisst10/rechitenergy; for (Int_t nn=0;nn<100;nn++) { double thresh=nn*0.02+0.01-0.5; double swisscut=0.21+0.01*nn; int sc_probet_swisstt=0; int sc_probet_swiss=0; int sc_probene_swisstt=0; int sc_probene_swiss=0; int sc_probene_swiss_t10=0; int sc_probene_swiss_t07=0; int sc_probene_swiss_t05=0; int sc_probene_swiss_t04=0; int sc_probene_swiss_t03=0; if (swisscross10>swisscut) sc_probene_swiss_t10=1; if (swisscross07>swisscut) sc_probene_swiss_t07=1; if (swisscross05>swisscut) sc_probene_swiss_t05=1; if (swisscross04>swisscut) sc_probene_swiss_t04=1; if (swisscross03>swisscut) sc_probene_swiss_t03=1; if (1.0-e4swiss/rechitenergy>swisscut) sc_probene_swiss=1; if (1.0-et4swiss/rechitet>swisscut) sc_probet_swiss=1; if (1.0-e4swisstt/rechitenergy>swisscut) sc_probene_swisstt=1; if (1.0-et4swisstt/rechitet>swisscut) sc_probet_swisstt=1; // cout << "single channel threshold=" << thresh << endl; int stripetcount=0; int stripenecount=0; int alletcount=0; int allenecount=0; // cout << "SC: seed energy=" << rechitenergy << " ieta,iphi=" << sc_ieta // << "," << sc_iphi << " rechit time=" << rechittime << endl; // cout << "iphi_min=" << iphi_min << " ieta_min=" << ieta_min << endl; for (Int_t x=ieta_min;x<ieta_min+5;x++) { stripetcount=0; stripenecount=0; // cout << "STRIP no" << x-ieta_min+1 << endl; for (Int_t y=iphi_min;y<iphi_min+5;y++) { int ietabin=x+86-1*int(x>0); double myene=eventenergy->GetBinContent(y,ietabin); double myet=eventet->GetBinContent(y,ietabin); // double mytime=eventtime->GetBinContent(y,ietabin); if (myene>thresh) stripenecount++; if (myet>thresh) stripetcount++; // int etthr=0; // if (myet>thresh) etthr=1; // cout << "ieta=" << x << " iphi=" << y // << " ene=" << myene << " et=" << myet << " time=" << mytime << " above thresh=" << etthr << endl; } int stripetprob=0; int stripeneprob=0; if (stripenecount>1) stripeneprob=1; if (stripetcount>1) stripetprob=1; // cout << "strips above threshold=" << stripetcount << " strip LUT value=" << stripetprob << endl; sc_strip_prob_ene->Fill(thresh,stripeneprob); sc_strip_prob_et->Fill(thresh,stripetprob); sc_strip_prob_ene_pu->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu->Fill(thresh,stripetprob,numgoodvtx); if (sctoweret>8.0) { sc_strip_prob_ene_thresh08->Fill(thresh,stripeneprob); sc_strip_prob_et_thresh08->Fill(thresh,stripetprob); sc_strip_prob_ene_pu_thresh08->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu_thresh08->Fill(thresh,stripetprob,numgoodvtx); } if (sctoweret>10.0) { sc_strip_prob_ene_thresh10->Fill(thresh,stripeneprob); sc_strip_prob_et_thresh10->Fill(thresh,stripetprob); sc_strip_prob_ene_pu_thresh10->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu_thresh10->Fill(thresh,stripetprob,numgoodvtx); } if (sctoweret>12.0) { sc_strip_prob_ene_thresh12->Fill(thresh,stripeneprob); sc_strip_prob_et_thresh12->Fill(thresh,stripetprob); sc_strip_prob_ene_pu_thresh12->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu_thresh12->Fill(thresh,stripetprob,numgoodvtx); } if (sctoweret>15.0) { sc_strip_prob_ene_thresh15->Fill(thresh,stripeneprob); sc_strip_prob_et_thresh15->Fill(thresh,stripetprob); sc_strip_prob_ene_pu_thresh15->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu_thresh15->Fill(thresh,stripetprob,numgoodvtx); } if (sctoweret>20.0) { sc_strip_prob_ene_thresh20->Fill(thresh,stripeneprob); sc_strip_prob_et_thresh20->Fill(thresh,stripetprob); sc_strip_prob_ene_pu_thresh20->Fill(thresh,stripeneprob,numgoodvtx); sc_strip_prob_et_pu_thresh20->Fill(thresh,stripetprob,numgoodvtx); } if (abs(sc_ieta)<=25) { sc_strip_prob_ene_mod1->Fill(thresh,stripeneprob); sc_strip_prob_et_mod1->Fill(thresh,stripetprob); } if (abs(sc_ieta)>25 && abs(sc_ieta)<=45) { sc_strip_prob_ene_mod2->Fill(thresh,stripeneprob); sc_strip_prob_et_mod2->Fill(thresh,stripetprob); } if (abs(sc_ieta)>45 && abs(sc_ieta)<=65) { sc_strip_prob_ene_mod3->Fill(thresh,stripeneprob); sc_strip_prob_et_mod3->Fill(thresh,stripetprob); } if (abs(sc_ieta)>65) { sc_strip_prob_ene_mod4->Fill(thresh,stripeneprob); sc_strip_prob_et_mod4->Fill(thresh,stripetprob); } if (numgoodvtx<=10) { sc_strip_prob_ene_pu0->Fill(thresh,stripeneprob); sc_strip_prob_et_pu0->Fill(thresh,stripetprob); } if (numgoodvtx>10 && numgoodvtx<=20) { sc_strip_prob_ene_pu10->Fill(thresh,stripeneprob); sc_strip_prob_et_pu10->Fill(thresh,stripetprob); } if (numgoodvtx>20) { sc_strip_prob_ene_pu20->Fill(thresh,stripeneprob); sc_strip_prob_et_pu20->Fill(thresh,stripetprob); } if (rechitenergy>10) { sc_strip_prob_ene_10->Fill(thresh,stripeneprob); sc_strip_prob_et_10->Fill(thresh,stripetprob); } // cout << " stripenecount=" << stripenecount << " stripetcount=" << stripetcount << endl; allenecount+=stripeneprob; alletcount+=stripetprob; } int sfgvb_tower_et=0; int sfgvb_tower_ene=0; if (allenecount==0) sfgvb_tower_ene=1; if (alletcount==0) sfgvb_tower_et=1; // cout << " **sFGVB value=" << 1-sfgvb_tower_et << "\n" << endl; sc_tower_spike_ene->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03->Fill(swisscut,sc_probene_swiss_t03); if (sctoweret>8.0) { sc_tower_spike_ene_thresh08->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_thresh08->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu_thresh08->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu_thresh08->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss_thresh08->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss_thresh08->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt_thresh08->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt_thresh08->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10_thresh08->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07_thresh08->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05_thresh08->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04_thresh08->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03_thresh08->Fill(swisscut,sc_probene_swiss_t03); } if (sctoweret>10.0) { sc_tower_spike_ene_thresh10->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_thresh10->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu_thresh10->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu_thresh10->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss_thresh10->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss_thresh10->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt_thresh10->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt_thresh10->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10_thresh10->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07_thresh10->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05_thresh10->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04_thresh10->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03_thresh10->Fill(swisscut,sc_probene_swiss_t03); } if (sctoweret>12.0) { sc_tower_spike_ene_thresh12->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_thresh12->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu_thresh12->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu_thresh12->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss_thresh12->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss_thresh12->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt_thresh12->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt_thresh12->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10_thresh12->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07_thresh12->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05_thresh12->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04_thresh12->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03_thresh12->Fill(swisscut,sc_probene_swiss_t03); } if (sctoweret>15.0) { sc_tower_spike_ene_thresh15->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_thresh15->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu_thresh15->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu_thresh15->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss_thresh15->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss_thresh15->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt_thresh15->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt_thresh15->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10_thresh15->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07_thresh15->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05_thresh15->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04_thresh15->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03_thresh15->Fill(swisscut,sc_probene_swiss_t03); } if (sctoweret>20.0) { sc_tower_spike_ene_thresh20->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_thresh20->Fill(thresh,sfgvb_tower_et); sc_tower_spike_ene_pu_thresh20->Fill(thresh,sfgvb_tower_ene,numgoodvtx); sc_tower_spike_et_pu_thresh20->Fill(thresh,sfgvb_tower_et,numgoodvtx); sc_tower_spike_ene_swiss_thresh20->Fill(swisscut,sc_probene_swiss); sc_tower_spike_et_swiss_thresh20->Fill(swisscut,sc_probet_swiss); sc_tower_spike_ene_swisstt_thresh20->Fill(swisscut,sc_probene_swisstt); sc_tower_spike_et_swisstt_thresh20->Fill(swisscut,sc_probet_swisstt); sc_tower_spike_ene_swiss_t10_thresh20->Fill(swisscut,sc_probene_swiss_t10); sc_tower_spike_ene_swiss_t07_thresh20->Fill(swisscut,sc_probene_swiss_t07); sc_tower_spike_ene_swiss_t05_thresh20->Fill(swisscut,sc_probene_swiss_t05); sc_tower_spike_ene_swiss_t04_thresh20->Fill(swisscut,sc_probene_swiss_t04); sc_tower_spike_ene_swiss_t03_thresh20->Fill(swisscut,sc_probene_swiss_t03); } if (abs(sc_ieta)<=25) { sc_tower_spike_ene_mod1->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_mod1->Fill(thresh,sfgvb_tower_et); } if (abs(sc_ieta)>25 && abs(sc_ieta)<=45) { sc_tower_spike_ene_mod2->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_mod2->Fill(thresh,sfgvb_tower_et); } if (abs(sc_ieta)>45 && abs(sc_ieta)<=65) { sc_tower_spike_ene_mod3->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_mod3->Fill(thresh,sfgvb_tower_et); } if (abs(sc_ieta)>65) { sc_tower_spike_ene_mod4->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_mod4->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx<=10) { sc_tower_spike_ene_pu0->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_pu0->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx>10 && numgoodvtx<=20) { sc_tower_spike_ene_pu10->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_pu10->Fill(thresh,sfgvb_tower_et); } if (numgoodvtx>20) { sc_tower_spike_ene_pu20->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_pu20->Fill(thresh,sfgvb_tower_et); } if (rechitenergy>10) { sc_tower_spike_ene_10->Fill(thresh,sfgvb_tower_ene); sc_tower_spike_et_10->Fill(thresh,sfgvb_tower_et); } } } } } } if (numgt1>0) { tmean_en=ensum1/ensum2; terr_en=sqrt(ensum3/ensum4); tmean_sig=errsum1/errsum2; terr_sig=sqrt(1/errsum2); } // EE rechits float_t badsc1_et=0; Int_t badsc1_hits=0; float_t badsc2_et=0; Int_t badsc2_hits=0; for (EcalRecHitCollection::const_iterator hitItr = EEhits->begin(); hitItr != EEhits->end(); ++hitItr) { EcalRecHit hit = (*hitItr); EEDetId det = hit.id(); // int dee=0; // float lasercalib_ee=laser->getLaserCorrection(EEDetId(det), event.time()); float ampli = hit.energy(); float time = hit.time()-toffset; int ebflag = hit.recoFlag(); // float_t chi2 = hit.chi2(); // float_t chi2oot= hit.outOfTimeChi2(); int eehashedid = det.hashedIndex(); const EcalPedestals::Item *aped=0; aped=&eped->endcap(eehashedid); float pedg12=aped->mean_x12; //cout << "EE pedestal g12=" << pedg12 << endl; GlobalPoint posee=geo->getPosition(hit.detid()); float eta_ee=posee.eta(); float phi_ee=posee.phi(); float pf=1.0/cosh(eta_ee); float etee=ampli*pf; int ix=det.ix(); int iy=det.iy(); int side=det.zside(); int iz=0; if (side==1) iz=1; if (side==-1) iz=-1; float ee_r4a=0; float ee4x1a=0; if (pTopology.isValid() && pG.isValid()) { // const CaloTopology *topology=pTopology.product(); //const reco::BasicCluster *cluster=0; /* ee4x1a+=EcalClusterTools::matrixEnergy(*cluster,eeRecHits,topology,hit.id(),-1,-1,0,0); ee4x1a+=EcalClusterTools::matrixEnergy(*cluster,eeRecHits,topology,hit.id(),1,1,0,0); ee4x1a+=EcalClusterTools::matrixEnergy(*cluster,eeRecHits,topology,hit.id(),0,0,-1,-1); ee4x1a+=EcalClusterTools::matrixEnergy(*cluster,eeRecHits,topology,hit.id(),0,0,+1,+1); */ } if (ampli!=0) ee_r4a=ee4x1a/ampli; ee_r4a=1-ee_r4a; Int_t ee_kGood=0; // Int_t ee_kPoorReco=0; // Int_t ee_kOutOfTime=0; // Int_t ee_kFaultyHardware=0; // Int_t ee_kNoisy=0; // Int_t ee_kPoorCalib=0; // Int_t ee_kSaturated=0; // Int_t ee_kLeadingEdgeRecovered=0; // Int_t ee_kNeighboursRecovered=0; // Int_t ee_kTowerRecovered=0; // Int_t ee_kDead=0; // Int_t ee_kKilled=0; // Int_t ee_kTPSaturated=0; // Int_t ee_kL1SpikeFlag=0; Int_t ee_kWeird=0; // Int_t ee_kDiWeird=0; // Int_t ee_kUnknown=0; if (hit.checkFlag(EcalRecHit::kGood)) ee_kGood=1; // if (hit.checkFlag(EcalRecHit::kPoorReco)) ee_kPoorReco=1; // if (hit.checkFlag(EcalRecHit::kOutOfTime)) ee_kOutOfTime=1; // if (hit.checkFlag(EcalRecHit::kFaultyHardware)) ee_kFaultyHardware=1; // if (hit.checkFlag(EcalRecHit::kNoisy)) ee_kNoisy=1; // if (hit.checkFlag(EcalRecHit::kPoorCalib)) ee_kPoorCalib=1; // if (hit.checkFlag(EcalRecHit::kSaturated)) ee_kSaturated=1; // if (hit.checkFlag(EcalRecHit::kLeadingEdgeRecovered)) ee_kLeadingEdgeRecovered=1; // if (hit.checkFlag(EcalRecHit::kNeighboursRecovered)) ee_kNeighboursRecovered=1; // if (hit.checkFlag(EcalRecHit::kTowerRecovered)) ee_kTowerRecovered=1; // if (hit.checkFlag(EcalRecHit::kDead)) ee_kDead=1; // if (hit.checkFlag(EcalRecHit::kKilled)) ee_kKilled=1; // if (hit.checkFlag(EcalRecHit::kTPSaturated)) ee_kTPSaturated=1; // if (hit.checkFlag(EcalRecHit::kL1SpikeFlag)) ee_kL1SpikeFlag=1; if (hit.checkFlag(EcalRecHit::kWeird)) ee_kWeird=1; // if (hit.checkFlag(EcalRecHit::kDiWeird)) ee_kDiWeird=1; // if (hit.checkFlag(EcalRecHit::kUnknown)) ee_kUnknown=1; // if (EcalTools::isNextToDeadFromNeighbours(det,*cstat,12)) ee_kGood=0; // if (EEDetId::isNextToRingBoundary(det)) ee_kGood=0; // mask out noisy channels in run D // if (ix==58 && iy==94 && iz==-1) ee_kWeird=1; if (!(ee_kWeird)) { if (etee>0.1) eetime_vs_bxtrain_01->Fill(bunchintrain+0.5,time); if (etee>0.5) eetime_vs_bxtrain_05->Fill(bunchintrain+0.5,time); if (ampli>1.0) { eesum_gt1+=ampli; eehits1GeV++; } if (ampli>2.0) { eesum_gt2+=ampli; eehits2GeV++; } if (ampli>4.0) { eesum_gt4+=ampli; eehits4GeV++; } if (etee>1.0) { eesum_gt1et+=etee; eehits1GeVet++; } if (etee>2.0) { eesum_gt2et+=etee; eehits2GeVet++; } if (etee>4.0) { eesum_gt4et+=etee; eehits4GeVet++; } // rechit et sums rechitsumet_ee_all+=etee; if (etee>0.1) rechitsumet_ee_01+=etee; if (etee>0.5) rechitsumet_ee_05+=etee; if (etee>0.1 && etee<=0.5) rechitsumet_ee_0105+=etee; if (etee>0.5 && etee<=3.0) rechitsumet_ee_0530+=etee; if (etee>0.1) eenumrechits_01++; if (etee>0.5) eenumrechits_05++; if (etee>0.1 && etee<=0.5) eenumrechits_0105++; if (etee>0.5 && etee<=3.0) eenumrechits_0530++; if (etee>0.1) rechiteta_vs_bxtrain_01->Fill(bunchintrain,eta_ee); if (etee>0.5) rechiteta_vs_bxtrain_05->Fill(bunchintrain,eta_ee); // do digi step if (etee>0.1) { float pedoff=0; if (isMC_) pedoff=0; if (!isMC_) pedoff=200-pedg12; //cout << "EE DIGI printout:\n\n"; // cout << "rechit energy=" << ampli << " rechit et=" << etee << endl; //cout << "SAMPLE ADC GAIN\n"; Int_t eedigiadc=0; // Int_t eedigigain=0; // char mytxtee[80]; EEDigiCollection::const_iterator digiItrEE= EEdigis->begin(); while(digiItrEE != EEdigis->end() && digiItrEE->id() != hitItr->id()) { digiItrEE++; } if (digiItrEE != EEdigis->end()) { EEDataFrame df(*digiItrEE); for(int i=0; i<10;++i) { eedigiadc=df.sample(i).adc(); eedigiadc+=pedoff; //eedigigain=df.sample(i).gainId(); // sprintf(mytxtee," %02d %04d %d",i+1,eedigiadc,eedigigain); // cout << mytxtee << endl; ee_digi_01->Fill(i+0.5,eedigiadc); if (etee>0.5) ee_digi_05->Fill(i+0.5,eedigiadc); if (etee>0.1 && etee<=0.5) { ee_digi_0105->Fill(i+0.5,eedigiadc); ee_digi_0105_vs_time->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0105_vs_bxtrain->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0105_vs_time_norm->Fill(time,i+0.5,1.0); ee_digi_0105_vs_bxtrain_norm->Fill(bunchintrain+0.5,i+0.5,1.0); if (abs(ee_eta)<2.0) { ee_digi_0105_vs_time_eta15->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0105_vs_bxtrain_eta15->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0105_vs_time_norm_eta15->Fill(time,i+0.5,1.0); ee_digi_0105_vs_bxtrain_norm_eta15->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(ee_eta)>=2.0 && abs(ee_eta)<2.5) { ee_digi_0105_vs_time_eta20->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0105_vs_bxtrain_eta20->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0105_vs_time_norm_eta20->Fill(time,i+0.5,1.0); ee_digi_0105_vs_bxtrain_norm_eta20->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(ee_eta)>=2.5) { ee_digi_0105_vs_time_eta25->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0105_vs_bxtrain_eta25->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0105_vs_time_norm_eta25->Fill(time,i+0.5,1.0); ee_digi_0105_vs_bxtrain_norm_eta25->Fill(bunchintrain+0.5,i+0.5,1.0); } } if (etee>0.5 && etee<=3.0) { ee_digi_0530->Fill(i+0.5,eedigiadc); ee_digi_0530_vs_time->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0530_vs_bxtrain->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0530_vs_time_norm->Fill(time,i+0.5,1.0); ee_digi_0530_vs_bxtrain_norm->Fill(bunchintrain+0.5,i+0.5,1.0); if (abs(ee_eta)<2.0) { ee_digi_0530_vs_time_eta15->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0530_vs_bxtrain_eta15->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0530_vs_time_norm_eta15->Fill(time,i+0.5,1.0); ee_digi_0530_vs_bxtrain_norm_eta15->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(ee_eta)>=2.0 && abs(ee_eta)<2.5) { ee_digi_0530_vs_time_eta20->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0530_vs_bxtrain_eta20->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0530_vs_time_norm_eta20->Fill(time,i+0.5,1.0); ee_digi_0530_vs_bxtrain_norm_eta20->Fill(bunchintrain+0.5,i+0.5,1.0); } if (abs(ee_eta)>=2.5) { ee_digi_0530_vs_time_eta25->Fill(time,i+0.5,float(eedigiadc)); ee_digi_0530_vs_bxtrain_eta25->Fill(bunchintrain+0.5,i+0.5,float(eedigiadc)); ee_digi_0530_vs_time_norm_eta25->Fill(time,i+0.5,1.0); ee_digi_0530_vs_bxtrain_norm_eta25->Fill(bunchintrain+0.5,i+0.5,1.0); } } } } } } if (ampli>eemax && ee_kGood) { eemax=ampli; eemaxet=etee; eeix=ix; eeiy=iy; eeiz=side; ee_eta=eta_ee; ee_phi=phi_ee; eetime=time; eeflags=ebflag; maxeehit=*hitItr; } if (etee>eemaxet2 && ee_kGood) { eemax2=ampli; eemaxet2=etee; eeix2=ix; eeiy2=iy; eeiz2=side; ee_eta2=eta_ee; ee_phi2=phi_ee; eetime2=time; eeflags2=ebflag; maxeehit2=*hitItr; } Float_t ix_tmp=ix-0.5; if (side==-1) ix_tmp=ix_tmp+100; Float_t iy_tmp=iy-0.5; // goodevent=true; if (!(ee_kWeird)) { // cout << "EErechit" << endl; ee_rechitenergy_->Fill(ampli); rechiteta_all->Fill(eta_ee); rechiteta_etweight->Fill(eta_ee,etee); if (etee>1.0) { rechiteta_gt1et->Fill(eta_ee); rechiteta_etweight_gt1et->Fill(eta_ee,etee); if (numgoodvtx<10) rechiteta_gt1et_pu10->Fill(eta_ee); if (numgoodvtx>=10 && numgoodvtx<20) rechiteta_gt1et_pu20->Fill(eta_ee); if (numgoodvtx>20) rechiteta_gt1et_pu30->Fill(eta_ee); } if (fabs(eta_ee)<1.6) ee_rechitenergy_16->Fill(ampli); if (fabs(eta_ee)>=1.6 && fabs(eta_ee)<1.8) ee_rechitenergy_18->Fill(ampli); if (fabs(eta_ee)>=1.8 && fabs(eta_ee)<2.0) ee_rechitenergy_20->Fill(ampli); if (fabs(eta_ee)>=2.0 && fabs(eta_ee)<2.2) ee_rechitenergy_22->Fill(ampli); if (fabs(eta_ee)>=2.2 && fabs(eta_ee)<2.4) ee_rechitenergy_24->Fill(ampli); if (fabs(eta_ee)>=2.4 && fabs(eta_ee)<2.6) ee_rechitenergy_26->Fill(ampli); if (fabs(eta_ee)>=2.6 && fabs(eta_ee)<2.8) ee_rechitenergy_28->Fill(ampli); if (fabs(eta_ee)>=2.8) ee_rechitenergy_30->Fill(ampli); ee_rechitet_->Fill(etee); if (fabs(eta_ee)<1.6) ee_rechitet_16->Fill(etee); if (fabs(eta_ee)>=1.6 && fabs(eta_ee)<1.8) ee_rechitet_18->Fill(etee); if (fabs(eta_ee)>=1.8 && fabs(eta_ee)<2.0) ee_rechitet_20->Fill(etee); if (fabs(eta_ee)>=2.0 && fabs(eta_ee)<2.2) ee_rechitet_22->Fill(etee); if (fabs(eta_ee)>=2.2 && fabs(eta_ee)<2.4) ee_rechitet_24->Fill(etee); if (fabs(eta_ee)>=2.4 && fabs(eta_ee)<2.6) ee_rechitet_26->Fill(etee); if (fabs(eta_ee)>=2.6 && fabs(eta_ee)<2.8) ee_rechitet_28->Fill(etee); if (fabs(eta_ee)>=2.8) ee_rechitet_30->Fill(etee); if (fabs(eta_ee)<2.0) ee_rechitetvspu_20->Fill(float(numgoodvtx)-0.5,etee); if (fabs(eta_ee)>=2.0 && fabs(eta_ee)<2.5) ee_rechitetvspu_25->Fill(float(numgoodvtx)-0.5,etee); if (fabs(eta_ee)>=2.5) ee_rechitetvspu_30->Fill(float(numgoodvtx)-0.5,etee); // ee_rechiten_vs_sm->Fill(dee-0.5,ampli); // ee_rechitet_vs_sm->Fill(dee-0.5,etee); if (eeRecHits->size()>500) ee_rechitenergy_notypeb_->Fill(ampli); if (side==1) { eep_rechiten_vs_eta->Fill(fabs(eta_ee),ampli); eep_rechiten_vs_phi->Fill(phi_ee,ampli); eep_rechitet_vs_eta->Fill(fabs(eta_ee),etee); eep_rechitet_vs_phi->Fill(phi_ee,etee); } if (side==-1) { eem_rechiten_vs_eta->Fill(fabs(eta_ee),ampli); eem_rechiten_vs_phi->Fill(phi_ee,ampli); eem_rechitet_vs_eta->Fill(fabs(eta_ee),etee); eem_rechitet_vs_phi->Fill(phi_ee,etee); } eeocc->Fill(ix_tmp,iy_tmp,1.); eeoccen->Fill(ix_tmp,iy_tmp,ampli); eeoccet->Fill(ix_tmp,iy_tmp,etee); if (etee>1.0) { eeoccgt1et->Fill(ix_tmp,iy_tmp,1.); eeoccetgt1et->Fill(ix_tmp,iy_tmp,etee); } if (ampli>1.0) { eeoccgt1->Fill(ix_tmp,iy_tmp,1.); eeoccengt1->Fill(ix_tmp,iy_tmp,ampli); } //int sevlev=severity->severityLevel(det,*eeRecHits); bool badsc1=false; bool badsc2=false; if (ix>=21 && ix<=25 && iy>=21 && iy<=25 && iz==-1) badsc1=true; if (ix>=46 && ix<=50 && iy>=96 && iy<=100 && iz==+1) badsc2=true; if (badsc1) { badsc1_et+=etee; if (ampli>1000.0 && ee_kGood==0) badsc1_hits++; } if (badsc2) { badsc2_et+=etee; if (ampli>1000.0 && ee_kGood==0) badsc2_hits++; } eehits++; if (side==1) eephits++; if (side==-1) eemhits++; } } // end of ee loop // Rechit flags: if (maxebhit.recoFlag()==EcalRecHit::kGood) ebflag_kgood=1; if (maxebhit.recoFlag()==EcalRecHit::kPoorReco) ebflag_kpoorreco=1; if (maxebhit.recoFlag()==EcalRecHit::kOutOfTime) ebflag_koutoftime=1; // if (maxebhit.recoFlag()==EcalRecHit::kFake) ebflag_kfake=1; if (pTopology.isValid() && pG.isValid()) { // const CaloTopology *topology=pTopology.product(); // const reco::BasicCluster *cluster=0; float e3x3=0; //EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),-1,1,-1,1); // float e5x5=0; //EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),-2,2,-2,2); eb_e9=0; //e3x3; eb_e25=0; //e5x5; float e4x1=0; // e4x1+=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),-1,-1,0,0); // e4x1+=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),1,1,0,0); // e4x1+=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),0,0,-1,-1); // e4x1+=EcalClusterTools::matrixEnergy(*cluster,ebRecHits,topology,maxebhit.id(),0,0,+1,+1); if (e3x3>0) eb_r9=ebmax/e3x3; if (ebmax!=0) eb_r4=e4x1/ebmax; // const reco::BasicCluster *cluster2=0; float e3x32=0; //EcalClusterTools::matrixEnergy(*cluster2,ebRecHits,topology,maxebhit2.id(),-1,1,-1,1); float e4x12=0; // e4x12+=EcalClusterTools::matrixEnergy(*cluster2,ebRecHits,topology,maxebhit2.id(),-1,-1,0,0); //e4x12+=EcalClusterTools::matrixEnergy(*cluster2,ebRecHits,topology,maxebhit2.id(),1,1,0,0); //e4x12+=EcalClusterTools::matrixEnergy(*cluster2,ebRecHits,topology,maxebhit2.id(),0,0,-1,-1); // e4x12+=EcalClusterTools::matrixEnergy(*cluster2,ebRecHits,topology,maxebhit2.id(),0,0,+1,+1); if (e3x32>0) eb_r92=ebmax2/e3x32; if (ebmax2!=0) eb_r42=e4x12/ebmax2; //const reco::BasicCluster *clusteree=0; float e3x3ee=0; //EcalClusterTools::matrixEnergy(*clusteree,eeRecHits,topology,maxeehit.id(),-1,1,-1,1); if (e3x3ee>0) ee_r9=eemax/e3x3ee; //const reco::BasicCluster *clusteree2=0; float e3x3ee2=0; //EcalClusterTools::matrixEnergy(*clusteree2,eeRecHits,topology,maxeehit2.id(),-1,1,-1,1); if (e3x3ee2>0) ee_r92=eemax2/e3x3ee2; } dataTree_->Fill(); // } /* // cout << "begin jets" << endl; edm::Handle<PFJetCollection> jets; PFJetCollection::const_iterator i_jet; event.getByLabel (jets_,jets); std::vector<reco::PFCandidatePtr> PFJetPart; histo_event_->Fill(event.id().event()); // const JetCorrector* corrector = JetCorrector::getJetCorrector(jetcorr_,iSetup); int njet(0); if (jets->size()>0) { for (i_jet = jets->begin();i_jet != jets->end(); i_jet++) { PFJetPart = i_jet->getPFConstituents(); // scale=corrector->correction(i_jet->p4()); scale=1.0; ncr_ = PFJetPart.size() ; energy_pf_ = 0; energyc_pf_ = 0; energyn_pf_ = 0; energyg_pf_ = 0; energy_ecal = 0; energy_hcal = 0; for(Int_t j=0;j<PFJetPart.size();j++){ PFCandidate::ParticleType type = PFJetPart[j]->particleId(); int tpid = PFJetPart[j]->translateTypeToPdgId(type); bool chargedp = false; bool neutralp = false; bool gammap = false; bool electronsp = false; chargedp = TMath::Abs(tpid)==211 || TMath::Abs(tpid) == 321 || TMath::Abs(tpid) == 2212 || TMath::Abs(tpid) == 3122|| TMath::Abs(tpid) == 3312|| TMath::Abs(tpid) == 3112 || TMath::Abs(tpid) == 3222; neutralp = TMath::Abs(tpid)==130 || TMath::Abs(tpid) == 2112 || TMath::Abs(tpid) == 310 || TMath::Abs(tpid) == 3322; gammap = TMath::Abs(tpid)==22; electronsp = TMath::Abs(tpid)==11; energy_pf_ = energy_pf_+ PFJetPart[j]->p4().energy(); if(chargedp) energyc_pf_ = energyc_pf_+PFJetPart[j]->p4().energy(); if(neutralp) energyn_pf_ = energyn_pf_+PFJetPart[j]->p4().energy(); if(gammap||electronsp) energyg_pf_ = energyg_pf_+PFJetPart[j]->p4().energy(); // energy_ecal = energy_ecal + PFJetPart[j]->ecalEnergy(); energy_hcal = energy_hcal + PFJetPart[j]->hcalEnergy(); } ptJet_ = i_jet->pt()*scale; etaJet_ = i_jet->eta(); phiJet_ = i_jet->phi(); chfJet_ = i_jet->chargedHadronEnergyFraction(); nhfJet_ = i_jet->neutralHadronEnergyFraction(); cemfJet_ = i_jet->chargedEmEnergyFraction(); nemfJet_ = i_jet->neutralEmEnergyFraction(); cmultiJet_ = i_jet->chargedMultiplicity(); nmultiJet_ = i_jet->neutralMultiplicity(); nrjets_ = jets->size(); dataTree_->Fill(); njet++; PFJetPart.clear(); } } */ // cout << "end jets" << endl; } ////////////////////////////////////////////////////////////////////////////////////////// SpikeAnalyserMC::~SpikeAnalyserMC() { delete file_; delete dataTree_; } //} <file_sep>/plugins/EventAnalyser.h #ifndef SPIKE_ANALYSER_H #define SPIKE_ANALYSER_H #include "TTree.h" #include "TH1D.h" #include "TH3D.h" #include "TH2F.h" #include "TFile.h" #include "FWCore/Framework/interface/ESHandle.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Utilities/interface/InputTag.h" class EcalCleaningAlgo; class EventAnalyser : public edm::EDAnalyzer { public: explicit EventAnalyser(edm::ParameterSet const& cfg); virtual void beginJob(); virtual void analyze(edm::Event const& e, edm::EventSetup const& iSetup); virtual void endJob(); ~EventAnalyser(); private: float recHitE( const DetId id, const EcalRecHitCollection &recHits); float recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ); std::string histogramFile_; std::string jets_; std::string tracks_; std::string vertex_coll_; std::string ebhitcoll_; std::string eehitcoll_; const std::vector<int> bunchstartbx_; bool isMC_; EcalCleaningAlgo * cleaningAlgo_; TFile* file_; TTree* dataTree_; int run, ev, lumi, bx, orbit, bunchintrain; int numvtx, numgoodvtx; float rechit_ene, rechit_et, rechit_time; int rechit_ieta, rechit_iphi; float rechit_eta, rechit_phi; float rechit_swisscross; float rechit_chi2, rechit_chi2oot; int rechit_flag_koot, rechit_flag_kweird, rechit_flag_kdiweird; float db_pedg12, db_pedg6, db_pedg1; float db_pedrmsg12, db_pedrmsg6, db_pedrmsg1; float lasercorr; float ebsumet, ebsumet_kgood; float eesumet, eesumet_kgood; int digi_adc[10]; int digi_gainid[10]; TH2F **barrel_uncalibrh; TH2F **endcap_uncalibrh; TH2F **barrel_rh; TH2F **endcap_rh; TH2D *ebchstatus; TH2D *eechstatus; TH2D *ebpedmean_g12; TH2D *ebpedmean_g6; TH2D *ebpedmean_g1; TH2D *ebpedrms_g12; TH2D *ebpedrms_g6; TH2D *ebpedrms_g1; TH2D *eepedmean_g12; TH2D *eepedmean_g6; TH2D *eepedmean_g1; TH2D *eepedrms_g12; TH2D *eepedrms_g6; TH2D *eepedrms_g1; TH2D *ebicval; TH2D *eeicval; TH2D *eblascorr; TH2D *eelascorr; int evcount; TH2F* eboccet; TH2F* eeoccet; TH2F* ebtime; TH2F* eetime; TH2F *eboccet_kgood; TH2F *eeoccet_kgood; TH2F *ebflag_kweird; TH2F *eeflag_kweird; TH2F *ebflag_kdiweird; TH2F *eeflag_kdiweird; TH2F *ebflag_koot; TH2F *eeflag_koot; TH2F *esoccet_esp1; TH2F *esoccet_esp2; TH2F *esoccet_esm1; TH2F *esoccet_esm2; TH2F *eepocc_etaphi; TH2F *eemocc_etaphi; TH2F *esp1occ_etaphi; TH2F *esp2occ_etaphi; TH2F *esm1occ_etaphi; TH2F *esm2occ_etaphi; edm::EDGetTokenT<EBRecHitCollection> tok_EB; edm::EDGetTokenT<EERecHitCollection> tok_EE; edm::EDGetTokenT<ESRecHitCollection> tok_ES; edm::EDGetTokenT<EBDigiCollection> tok_EB_digi; edm::EDGetTokenT<EEDigiCollection> tok_EE_digi; edm::EDGetTokenT<reco::GsfElectronCollection> tok_elec; }; #endif <file_sep>/plugins/SpikeAnalyser.cc #include <iostream> #include <sstream> #include <istream> #include <fstream> #include <iomanip> #include <string> #include <cmath> #include <functional> #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/CaloTowers/interface/CaloTowerCollection.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgoRcd.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalCleaningAlgo.h" #include "DataFormats/EcalDigi/interface/EcalTrigPrimCompactColl.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include "DataFormats/EcalDigi/interface/EcalTriggerPrimitiveSample.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbService.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPedestals.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTriggerRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTrigger.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFLayer.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "JetMETCorrections/MCJet/plugins/SpikeAnalyser.h" #include "JetMETCorrections/MCJet/plugins/JetUtilMC.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterTools.h" #include "RecoEcal/EgammaCoreTools/interface/EcalTools.h" #include "Math/VectorUtil.h" #include "TVector3.h" using namespace edm; using namespace reco; using namespace std; DEFINE_FWK_MODULE(SpikeAnalyser); SpikeAnalyser::SpikeAnalyser(const edm::ParameterSet& cfg) : bunchstartbx_(cfg.getParameter<std::vector<int> >("bunchstartbx")) { jets_ = cfg.getParameter<std::string> ("jets"); histogramFile_ = cfg.getParameter<std::string> ("histogramFile"); tracks_ = cfg.getParameter<std::string> ("tracks"); vertex_coll_ = cfg.getParameter<std::string> ("vertex"); ebhitcoll_ = cfg.getParameter<std::string> ("EBRecHitCollection"); eehitcoll_ = cfg.getParameter<std::string> ("EERecHitCollection"); isMC_ = cfg.getParameter<bool>("IsMC"); edm::ParameterSet cleaningPs = cfg.getParameter<edm::ParameterSet>("cleaningConfig"); cleaningAlgo_ = new EcalCleaningAlgo(cleaningPs); } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyser::beginJob() { file_ = new TFile(histogramFile_.c_str(),"RECREATE"); dataTree_ = new TTree("dataTree","dataTree"); dataTree2_ = new TTree("dataTree2","dataTree2"); // run/event info dataTree_->Branch("run", &run, "run/I"); dataTree_->Branch("ev", &ev, "ev/I"); dataTree_->Branch("lumi", &lumi, "lumi/I"); dataTree_->Branch("bx", &bx, "bx/I"); dataTree_->Branch("orbit", &orbit, "orbit/I"); dataTree_->Branch("bunchintrain", &bunchintrain, "bunchintrain/I"); // primary vertex info dataTree_->Branch("numvtx", &numvtx, "numvtx/I"); dataTree_->Branch("numgoodvtx", &numgoodvtx, "numgoodvtx/I"); // rechit info dataTree_->Branch("rechit_ieta", &rechit_ieta, "rechit_ieta/I"); dataTree_->Branch("rechit_iphi", &rechit_iphi, "rechit_iphi/I"); dataTree_->Branch("rechit_eta", &rechit_eta, "rechit_eta/F"); dataTree_->Branch("rechit_phi", &rechit_phi, "rechit_phi/F"); dataTree_->Branch("rechit_ene_weights53", &rechit_ene_weights53, "rechit_ene_weights53/F"); dataTree_->Branch("rechit_et_weights53", &rechit_et_weights53, "rechit_et_weights53/F"); dataTree_->Branch("rechit_time_weights53", &rechit_time_weights53, "rechit_time_weights53/F"); dataTree_->Branch("rechit_swisscross_weights53", &rechit_swisscross_weights53, "rechit_swisscross_weights53/F"); dataTree_->Branch("rechit_chi2_weights53", &rechit_chi2_weights53, "rechit_chi2_weights53/F"); dataTree_->Branch("rechit_flag_kweird_weights53", &rechit_flag_kweird_weights53, "rechit_flag_kweird_weights53/I"); dataTree_->Branch("rechit_flag_kdiweird_weights53", &rechit_flag_kdiweird_weights53, "rechit_flag_kdiweird_weights53/I"); dataTree_->Branch("rechit_flag_koot_weights53", &rechit_flag_koot_weights53, "rechit_flag_koot_weights53/I"); dataTree_->Branch("rechit_ene_weights74", &rechit_ene_weights74, "rechit_ene_weights74/F"); dataTree_->Branch("rechit_et_weights74", &rechit_et_weights74, "rechit_et_weights74/F"); dataTree_->Branch("rechit_time_weights74", &rechit_time_weights74, "rechit_time_weights74/F"); dataTree_->Branch("rechit_swisscross_weights74", &rechit_swisscross_weights74, "rechit_swisscross_weights74/F"); dataTree_->Branch("rechit_chi2_weights74", &rechit_chi2_weights74, "rechit_chi2_weights74/F"); dataTree_->Branch("rechit_flag_kweird_weights74", &rechit_flag_kweird_weights74, "rechit_flag_kweird_weights74/I"); dataTree_->Branch("rechit_flag_kdiweird_weights74", &rechit_flag_kdiweird_weights74, "rechit_flag_kdiweird_weights74/I"); dataTree_->Branch("rechit_flag_koot_weights74", &rechit_flag_koot_weights74, "rechit_flag_koot_weights74/I"); dataTree_->Branch("rechit_ene_multi5", &rechit_ene_multi5, "rechit_ene_multi5/F"); dataTree_->Branch("rechit_et_multi5", &rechit_et_multi5, "rechit_et_multi5/F"); dataTree_->Branch("rechit_time_multi5", &rechit_time_multi5, "rechit_time_multi5/F"); dataTree_->Branch("rechit_swisscross_multi5", &rechit_swisscross_multi5, "rechit_swisscross_multi5/F"); dataTree_->Branch("rechit_chi2_multi5", &rechit_chi2_multi5, "rechit_chi2_multi5/F"); dataTree_->Branch("rechit_flag_kweird_multi5", &rechit_flag_kweird_multi5, "rechit_flag_kweird_multi5/I"); dataTree_->Branch("rechit_flag_kdiweird_multi5", &rechit_flag_kdiweird_multi5, "rechit_flag_kdiweird_multi5/I"); dataTree_->Branch("rechit_flag_koot_multi5", &rechit_flag_koot_multi5, "rechit_flag_koot_multi5/I"); dataTree_->Branch("rechit_ene_multi10", &rechit_ene_multi10, "rechit_ene_multi10/F"); dataTree_->Branch("rechit_et_multi10", &rechit_et_multi10, "rechit_et_multi10/F"); dataTree_->Branch("rechit_time_multi10", &rechit_time_multi10, "rechit_time_multi10/F"); dataTree_->Branch("rechit_swisscross_multi10", &rechit_swisscross_multi10, "rechit_swisscross_multi10/F"); dataTree_->Branch("rechit_chi2_multi10", &rechit_chi2_multi10, "rechit_chi2_multi10/F"); dataTree_->Branch("rechit_flag_kweird_multi10", &rechit_flag_kweird_multi10, "rechit_flag_kweird_multi10/I"); dataTree_->Branch("rechit_flag_kdiweird_multi10", &rechit_flag_kdiweird_multi10, "rechit_flag_kdiweird_multi10/I"); dataTree_->Branch("rechit_flag_koot_multi10", &rechit_flag_koot_multi10, "rechit_flag_koot_multi10/I"); dataTree_->Branch("rechit_ene_multi1", &rechit_ene_multi1, "rechit_ene_multi1/F"); dataTree_->Branch("rechit_et_multi1", &rechit_et_multi1, "rechit_et_multi1/F"); dataTree_->Branch("rechit_time_multi1", &rechit_time_multi1, "rechit_time_multi1/F"); dataTree_->Branch("rechit_swisscross_multi1", &rechit_swisscross_multi1, "rechit_swisscross_multi1/F"); dataTree_->Branch("rechit_chi2_multi1", &rechit_chi2_multi1, "rechit_chi2_multi1/F"); dataTree_->Branch("rechit_flag_kweird_multi1", &rechit_flag_kweird_multi1, "rechit_flag_kweird_multi1/I"); dataTree_->Branch("rechit_flag_kdiweird_multi1", &rechit_flag_kdiweird_multi1, "rechit_flag_kdiweird_multi1/I"); dataTree_->Branch("rechit_flag_koot_multi1", &rechit_flag_koot_multi1, "rechit_flag_koot_multi1/I"); dataTree_->Branch("rechit_flag_kweird_calc", &rechit_flag_kweird_calc, "rechit_flag_kweird_calc/I"); dataTree_->Branch("rechit_swisscross_thresh", &rechit_swisscross_thresh, "rechit_swisscross_thresh/F"); dataTree_->Branch("rechit_swisscross_zs_weights53", &rechit_swisscross_zs_weights53, "rechit_swisscross_zs_weights53/F"); dataTree_->Branch("rechit_swisscross_zs_weights74", &rechit_swisscross_zs_weights74, "rechit_swisscross_zs_weights74/F"); dataTree_->Branch("rechit_swisscross_zs_multi5", &rechit_swisscross_zs_multi5, "rechit_swisscross_zs_multi5/F"); dataTree_->Branch("rechit_swisscross_zs_multi10", &rechit_swisscross_zs_multi10, "rechit_swisscross_zs_multi10/F"); dataTree_->Branch("rechit_swisscross_zs_multi1", &rechit_swisscross_zs_multi1, "rechit_swisscross_zs_multi1/F"); dataTree_->Branch("isnearcrack", &isnearcrack, "isnearcrack/I"); dataTree_->Branch("uncalibrechit_multi10_ampl_eb", &uncalibrechit_multi10_ampl_eb, "uncalibrechit_multi10_ampl_eb/F"); dataTree_->Branch("uncalibrechit_multi10_amperr_eb", &uncalibrechit_multi10_amperr_eb, "uncalibrechit_multi10_amperr_eb/F"); dataTree_->Branch("uncalibrechit_multi10_pedestal_eb", &uncalibrechit_multi10_pedestal_eb, "uncalibrechit_multi10_pedestal_eb/F"); dataTree_->Branch("uncalibrechit_multi10_jitter_eb", &uncalibrechit_multi10_jitter_eb, "uncalibrechit_multi10_jitter_eb/F"); dataTree_->Branch("uncalibrechit_multi10_chi2_eb", &uncalibrechit_multi10_chi2_eb, "uncalibrechit_multi10_chi2_eb/F"); dataTree_->Branch("uncalibrechit_multi10_ootampl_eb", &uncalibrechit_multi10_ootampl_eb, "uncalibrechit_multi10_ootampl_eb[10]/F"); dataTree_->Branch("uncalibrechit_multi5_ampl_eb", &uncalibrechit_multi5_ampl_eb, "uncalibrechit_multi5_ampl_eb/F"); dataTree_->Branch("uncalibrechit_multi5_amperr_eb", &uncalibrechit_multi5_amperr_eb, "uncalibrechit_multi5_amperr_eb/F"); dataTree_->Branch("uncalibrechit_multi5_pedestal_eb", &uncalibrechit_multi5_pedestal_eb, "uncalibrechit_multi5_pedestal_eb/F"); dataTree_->Branch("uncalibrechit_multi5_jitter_eb", &uncalibrechit_multi5_jitter_eb, "uncalibrechit_multi5_jitter_eb/F"); dataTree_->Branch("uncalibrechit_multi5_chi2_eb", &uncalibrechit_multi5_chi2_eb, "uncalibrechit_multi5_chi2_eb/F"); dataTree_->Branch("uncalibrechit_multi5_ootampl_eb", &uncalibrechit_multi5_ootampl_eb, "uncalibrechit_multi5_ootampl_eb[10]/F"); dataTree_->Branch("uncalibrechit_multi1_ampl_eb", &uncalibrechit_multi1_ampl_eb, "uncalibrechit_multi1_ampl_eb/F"); dataTree_->Branch("uncalibrechit_multi1_amperr_eb", &uncalibrechit_multi1_amperr_eb, "uncalibrechit_multi1_amperr_eb/F"); dataTree_->Branch("uncalibrechit_multi1_pedestal_eb", &uncalibrechit_multi1_pedestal_eb, "uncalibrechit_multi1_pedestal_eb/F"); dataTree_->Branch("uncalibrechit_multi1_jitter_eb", &uncalibrechit_multi1_jitter_eb, "uncalibrechit_multi1_jitter_eb/F"); dataTree_->Branch("uncalibrechit_multi1_chi2_eb", &uncalibrechit_multi1_chi2_eb, "uncalibrechit_multi1_chi2_eb/F"); dataTree_->Branch("uncalibrechit_multi1_ootampl_eb", &uncalibrechit_multi1_ootampl_eb, "uncalibrechit_multi1_ootampl_eb[10]/F"); // db info dataTree_->Branch("db_pedg12", &db_pedg12, "db_pedg12/F"); dataTree_->Branch("db_pedg6", &db_pedg6, "db_pedg6/F"); dataTree_->Branch("db_pedg1", &db_pedg1, "db_pedg1/F"); dataTree_->Branch("db_pedrmsg12", &db_pedrmsg12, "db_pedrmsg12/F"); dataTree_->Branch("db_pedrmsg6", &db_pedrmsg6, "db_pedrmsg6/F"); dataTree_->Branch("db_pedrmsg1", &db_pedrmsg1, "db_pedrmsg1/F"); dataTree_->Branch("lasercorr", &lasercorr, "lasercorr/F"); // digi info dataTree_->Branch("digi_adc", &digi_adc, "digi_adc[10]/I"); dataTree_->Branch("digi_gainid", &digi_gainid, "digi_gainid[10]/I"); // EE data tree dataTree2_->Branch("run", &run, "run/I"); dataTree2_->Branch("ev", &ev, "ev/I"); dataTree2_->Branch("lumi", &lumi, "lumi/I"); dataTree2_->Branch("bx", &bx, "bx/I"); dataTree2_->Branch("orbit", &orbit, "orbit/I"); dataTree2_->Branch("bunchintrain", &bunchintrain, "bunchintrain/I"); // primary vertex info dataTree2_->Branch("numvtx", &numvtx, "numvtx/I"); dataTree2_->Branch("numgoodvtx", &numgoodvtx, "numgoodvtx/I"); // rechit info dataTree2_->Branch("rechit_ix", &rechit_ix, "rechit_ix/I"); dataTree2_->Branch("rechit_iy", &rechit_iy, "rechit_ix/I"); dataTree2_->Branch("rechit_iz", &rechit_iz, "rechit_iz/I"); dataTree2_->Branch("rechit_eta", &rechit_eta_ee, "rechit_eta_ee/F"); dataTree2_->Branch("rechit_phi", &rechit_phi_ee, "rechit_phi_ee/F"); dataTree2_->Branch("rechit_ene_weights53", &rechit_ene_weights53_ee, "rechit_ene_weights53_ee/F"); dataTree2_->Branch("rechit_et_weights53", &rechit_et_weights53_ee, "rechit_et_weights53_ee/F"); dataTree2_->Branch("rechit_time_weights53", &rechit_time_weights53_ee, "rechit_time_weights53_ee/F"); dataTree2_->Branch("rechit_chi2_weights53", &rechit_chi2_weights53_ee, "rechit_chi2_weights53_ee/F"); dataTree2_->Branch("rechit_flag_kweird_weights53", &rechit_flag_kweird_weights53_ee, "rechit_flag_kweird_weights53_ee/I"); dataTree2_->Branch("rechit_flag_kdiweird_weights53", &rechit_flag_kdiweird_weights53_ee, "rechit_flag_kdiweird_weights53_ee/I"); dataTree2_->Branch("rechit_flag_koot_weights53", &rechit_flag_koot_weights53_ee, "rechit_flag_koot_weights53_ee/I"); dataTree2_->Branch("rechit_ene_weights74", &rechit_ene_weights74_ee, "rechit_ene_weights74_ee/F"); dataTree2_->Branch("rechit_et_weights74", &rechit_et_weights74_ee, "rechit_et_weights74_ee/F"); dataTree2_->Branch("rechit_time_weights74", &rechit_time_weights74_ee, "rechit_time_weights74_ee/F"); dataTree2_->Branch("rechit_chi2_weights74", &rechit_chi2_weights74_ee, "rechit_chi2_weights74_ee/F"); dataTree2_->Branch("rechit_flag_kweird_weights74", &rechit_flag_kweird_weights74_ee, "rechit_flag_kweird_weights74_ee/I"); dataTree2_->Branch("rechit_flag_kdiweird_weights74", &rechit_flag_kdiweird_weights74_ee, "rechit_flag_kdiweird_weights74_ee/I"); dataTree2_->Branch("rechit_flag_koot_weights74", &rechit_flag_koot_weights74_ee, "rechit_flag_koot_weights74_ee/I"); dataTree2_->Branch("rechit_ene_multi5", &rechit_ene_multi5_ee, "rechit_ene_multi5_ee/F"); dataTree2_->Branch("rechit_et_multi5", &rechit_et_multi5_ee, "rechit_et_multi5_ee/F"); dataTree2_->Branch("rechit_time_multi5", &rechit_time_multi5_ee, "rechit_time_multi5_ee/F"); dataTree2_->Branch("rechit_chi2_multi5", &rechit_chi2_multi5_ee, "rechit_chi2_multi5_ee/F"); dataTree2_->Branch("rechit_flag_kweird_multi5", &rechit_flag_kweird_multi5_ee, "rechit_flag_kweird_multi5_ee/I"); dataTree2_->Branch("rechit_flag_kdiweird_multi5", &rechit_flag_kdiweird_multi5_ee, "rechit_flag_kdiweird_multi5_ee/I"); dataTree2_->Branch("rechit_flag_koot_multi5", &rechit_flag_koot_multi5_ee, "rechit_flag_koot_multi5_ee/I"); dataTree2_->Branch("rechit_ene_multi10", &rechit_ene_multi10_ee, "rechit_ene_multi10_ee/F"); dataTree2_->Branch("rechit_et_multi10", &rechit_et_multi10_ee, "rechit_et_multi10_Ee/F"); dataTree2_->Branch("rechit_time_multi10", &rechit_time_multi10_ee, "rechit_time_multi10_ee/F"); dataTree2_->Branch("rechit_chi2_multi10", &rechit_chi2_multi10_ee, "rechit_chi2_multi10_ee/F"); dataTree2_->Branch("rechit_flag_kweird_multi10", &rechit_flag_kweird_multi10_ee, "rechit_flag_kweird_multi10_ee/I"); dataTree2_->Branch("rechit_flag_kdiweird_multi10", &rechit_flag_kdiweird_multi10_ee, "rechit_flag_kdiweird_multi10_ee/I"); dataTree2_->Branch("rechit_flag_koot_multi10", &rechit_flag_koot_multi10_ee, "rechit_flag_koot_multi10_ee/I"); dataTree2_->Branch("rechit_ene_multi1", &rechit_ene_multi1_ee, "rechit_ene_multi1_ee/F"); dataTree2_->Branch("rechit_et_multi1", &rechit_et_multi1_ee, "rechit_et_multi1_ee/F"); dataTree2_->Branch("rechit_time_multi1", &rechit_time_multi1_ee, "rechit_time_multi1_ee/F"); dataTree2_->Branch("rechit_chi2_multi1", &rechit_chi2_multi1_ee, "rechit_chi2_multi1_ee/F"); dataTree2_->Branch("rechit_flag_kweird_multi1", &rechit_flag_kweird_multi1_ee, "rechit_flag_kweird_multi1_ee/I"); dataTree2_->Branch("rechit_flag_kdiweird_multi1", &rechit_flag_kdiweird_multi1_ee, "rechit_flag_kdiweird_multi1_ee/I"); dataTree2_->Branch("rechit_flag_koot_multi1", &rechit_flag_koot_multi1_ee, "rechit_flag_koot_multi1_ee/I"); // db info dataTree2_->Branch("db_pedg12", &db_pedg12_ee, "db_pedg12_ee/F"); dataTree2_->Branch("db_pedg6", &db_pedg6_ee, "db_pedg6_ee/F"); dataTree2_->Branch("db_pedg1", &db_pedg1_ee, "db_pedg1_ee/F"); dataTree2_->Branch("db_pedrmsg12", &db_pedrmsg12_ee, "db_pedrmsg12_ee/F"); dataTree2_->Branch("db_pedrmsg6", &db_pedrmsg6_ee, "db_pedrmsg6_ee/F"); dataTree2_->Branch("db_pedrmsg1", &db_pedrmsg1_ee, "db_pedrmsg1_ee/F"); dataTree2_->Branch("lasercorr", &lasercorr_ee, "lasercorr_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_ampl_ee", &uncalibrechit_multi10_ampl_ee, "uncalibrechit_multi10_ampl_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_amperr_ee", &uncalibrechit_multi10_amperr_ee, "uncalibrechit_multi10_amperr_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_pedestal_ee", &uncalibrechit_multi10_pedestal_ee, "uncalibrechit_multi10_pedestal_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_jitter_ee", &uncalibrechit_multi10_jitter_ee, "uncalibrechit_multi10_jitter_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_chi2_ee", &uncalibrechit_multi10_chi2_ee, "uncalibrechit_multi10_chi2_ee/F"); dataTree2_->Branch("uncalibrechit_multi10_ootampl_ee", &uncalibrechit_multi10_ootampl_ee, "uncalibrechit_multi10_ootampl_ee[10]/F"); dataTree2_->Branch("uncalibrechit_multi5_ampl_ee", &uncalibrechit_multi5_ampl_ee, "uncalibrechit_multi5_ampl_ee/F"); dataTree2_->Branch("uncalibrechit_multi5_amperr_ee", &uncalibrechit_multi5_amperr_ee, "uncalibrechit_multi5_amperr_ee/F"); dataTree2_->Branch("uncalibrechit_multi5_pedestal_ee", &uncalibrechit_multi5_pedestal_ee, "uncalibrechit_multi5_pedestal_ee/F"); dataTree2_->Branch("uncalibrechit_multi5_jitter_ee", &uncalibrechit_multi5_jitter_ee, "uncalibrechit_multi5_jitter_ee/F"); dataTree2_->Branch("uncalibrechit_multi5_chi2_ee", &uncalibrechit_multi5_chi2_ee, "uncalibrechit_multi5_chi2_ee/F"); dataTree2_->Branch("uncalibrechit_multi5_ootampl_ee", &uncalibrechit_multi5_ootampl_ee, "uncalibrechit_multi5_ootampl_ee[10]/F"); dataTree2_->Branch("uncalibrechit_multi1_ampl_ee", &uncalibrechit_multi1_ampl_ee, "uncalibrechit_multi1_ampl_ee/F"); dataTree2_->Branch("uncalibrechit_multi1_amperr_ee", &uncalibrechit_multi1_amperr_ee, "uncalibrechit_multi1_amperr_ee/F"); dataTree2_->Branch("uncalibrechit_multi1_pedestal_ee", &uncalibrechit_multi1_pedestal_ee, "uncalibrechit_multi1_pedestal_ee/F"); dataTree2_->Branch("uncalibrechit_multi1_jitter_ee", &uncalibrechit_multi1_jitter_ee, "uncalibrechit_multi1_jitter_ee/F"); dataTree2_->Branch("uncalibrechit_multi1_chi2_ee", &uncalibrechit_multi1_chi2_ee, "uncalibrechit_multi1_chi2_ee/F"); dataTree2_->Branch("uncalibrechit_multi1_ootampl_ee", &uncalibrechit_multi1_ootampl_ee, "uncalibrechit_multi1_ootampl_ee[10]/F"); // digi info dataTree2_->Branch("digi_adc", &digi_adc_ee, "digi_adc_ee[10]/I"); dataTree2_->Branch("digi_gainid", &digi_gainid_ee, "digi_gainid_ee[10]/I"); ebene = new TH2F("ebene","",360,0,360,170,-85,85); ebtime = new TH2F("ebtime","",360,0,360,170,-85,85); } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyser::endJob() { if (file_ !=0) { file_->cd(); dataTree_ ->Write(); dataTree2_ ->Write(); ebene->Write(); ebtime->Write(); } file_ = 0; } ////////////////////////////////////////////////////////////////////////////////////////// float SpikeAnalyser::recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ) { // in the barrel: di = dEta dj = dPhi // in the endcap: di = dX dj = dY DetId nid; if( id.subdetId() == EcalBarrel) nid = EBDetId::offsetBy( id, di, dj ); else if( id.subdetId() == EcalEndcap) nid = EEDetId::offsetBy( id, di, dj ); return ( nid == DetId(0) ? 0 : recHitE( nid, recHits ) ); } float SpikeAnalyser::recHitE( const DetId id, const EcalRecHitCollection &recHits) { if ( id.rawId() == 0 ) return 0; EcalRecHitCollection::const_iterator it = recHits.find( id ); if ( it != recHits.end() ){ float ene= (*it).energy(); return ene; } return 0; } ////////////////////////////////////////////////////////////////////////////////////////// void SpikeAnalyser::analyze(edm::Event const& event, edm::EventSetup const& iSetup) { for (int i=0;i<10;i++) { digi_adc[i]=0; digi_gainid[i]=0; digi_adc_ee[i]=0; digi_gainid_ee[i]=0; } run=0, ev=0, lumi=0, bx=0, orbit=0; numvtx=0; numgoodvtx=0; edm::ESHandle<EcalLaserDbService> laser; iSetup.get<EcalLaserDbRecord>().get(laser); run = event.id().run(); ev = event.id().event(); lumi = event.luminosityBlock(); bx = event.bunchCrossing(); orbit = event.orbitNumber(); /* edm::InputTag PileupSrc_("addPileupInfo"); Handle<std::vector<PileupSummaryInfo>> PupInfo; event.getByLabel(PileupSrc_, PupInfo); std::vector<PileupSummaryInfo>::const_iterator PVI; for (PVI=PupInfo->begin(); PVI!=PupInfo->end(); ++PVI) { cout << "PU INFO: bx=" << PVI->getBunchCrossing() << " PU=" << PVI->getPU_NumInteractions() << endl; } */ // ebene->Reset(); // ebtime->Reset(); // if (run==198116 && ev==23523209) { // if (run==203708) { // get position in bunch train bunchintrain=-1; for (std::vector<int>::const_iterator bxit=bunchstartbx_.begin(); bxit!=bunchstartbx_.end(); ++bxit) { Int_t bxpos=bx - *bxit; // 50ns if (bxpos>=0 && bxpos<=70) bunchintrain=bxpos/2; // 25ns // if (bxpos>=0 && bxpos<=50) bunchintrain=bxpos; } edm::Handle<VertexCollection> vertices; event.getByLabel(vertex_coll_,vertices); VertexCollection::const_iterator vit; numvtx=vertices->size(); if (vertices->size()>0) { for (vit=vertices->begin();vit!=vertices->end();++vit) { int vtx_chi2=vit->chi2(); int vtx_ndof=vit->ndof(); int vtx_isfake=vit->isFake(); if (vit->isValid() && vtx_isfake==0 && vtx_ndof>4 && vtx_chi2>0 && vtx_chi2<10000) { numgoodvtx++; } } } edm::ESHandle<CaloGeometry> pG; iSetup.get<CaloGeometryRecord>().get(pG); const CaloGeometry* geo=pG.product(); edm::ESHandle<CaloTopology> pTopology; iSetup.get<CaloTopologyRecord>().get(pTopology); // edm::ESHandle<EcalChannelStatus> chanstat; // iSetup.get<EcalChannelStatusRcd>().get(chanstat); // const EcalChannelStatus* cstat=chanstat.product(); edm::ESHandle<EcalPedestals> ecalped; iSetup.get<EcalPedestalsRcd>().get(ecalped); const EcalPedestals* eped=ecalped.product(); // Rechit Collection Handle<EcalRecHitCollection> EBhits_weights53; Handle<EcalRecHitCollection> EBhits_weights74; Handle<EcalRecHitCollection> EBhits_multi5; Handle<EcalRecHitCollection> EBhits_multi10; Handle<EcalRecHitCollection> EBhits_multi1; Handle<EcalUncalibratedRecHitCollection> EBhitsU_multi5; Handle<EcalUncalibratedRecHitCollection> EBhitsU_multi10; Handle<EcalUncalibratedRecHitCollection> EBhitsU_multi1; Handle<EcalRecHitCollection> EEhits_weights53; Handle<EcalRecHitCollection> EEhits_weights74; Handle<EcalRecHitCollection> EEhits_multi5; Handle<EcalRecHitCollection> EEhits_multi10; Handle<EcalRecHitCollection> EEhits_multi1; Handle<EcalUncalibratedRecHitCollection> EEhitsU_multi5; Handle<EcalUncalibratedRecHitCollection> EEhitsU_multi10; Handle<EcalUncalibratedRecHitCollection> EEhitsU_multi1; // 2015 data /* event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEB","reRECO"),EBhits_weights74); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEB","reRECO"),EBhits_weights53); event.getByLabel(edm::InputTag("ecalRecHit","EcalRecHitsEB","reRECO"),EBhits_multi10); event.getByLabel(edm::InputTag("ecalRecHitMultiFit50ns","EcalRecHitsMultiFit50nsEB","reRECO"),EBhits_multi5); event.getByLabel(edm::InputTag("ecalRecHitMultiFitNoOOTPU","EcalRecHitsMultiFitNoOOTPUEB","reRECO"),EBhits_multi1); event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi10); event.getByLabel(edm::InputTag("ecalMultiFit50nsUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi5); event.getByLabel(edm::InputTag("ecalMultiFitNoOOTPUUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi1); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEE","reRECO"),EEhits_weights74); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEE","reRECO"),EEhits_weights53); event.getByLabel(edm::InputTag("ecalRecHit","EcalRecHitsEE","reRECO"),EEhits_multi10); event.getByLabel(edm::InputTag("ecalRecHitMultiFit50ns","EcalRecHitsMultiFit50nsEE","reRECO"),EEhits_multi5); event.getByLabel(edm::InputTag("ecalRecHitMultiFitNoOOTPU","EcalRecHitsMultiFitNoOOTPUEE","reRECO"),EEhits_multi1); event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi10); event.getByLabel(edm::InputTag("ecalMultiFit50nsUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi5); event.getByLabel(edm::InputTag("ecalMultiFitNoOOTPUUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi1); */ // 2012 data event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEB","reRECO"),EBhits_weights74); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEB","reRECO"),EBhits_weights53); event.getByLabel(edm::InputTag("ecalRecHit","EcalRecHitsEB","reRECO"),EBhits_multi5); event.getByLabel(edm::InputTag("ecalRecHitMultiFit25ns","EcalRecHitsMultiFit25nsEB","reRECO"),EBhits_multi10); event.getByLabel(edm::InputTag("ecalRecHitMultiFitNoOOTPU","EcalRecHitsMultiFitNoOOTPUEB","reRECO"),EBhits_multi1); event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi5); event.getByLabel(edm::InputTag("ecalMultiFit25nsUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi10); event.getByLabel(edm::InputTag("ecalMultiFitNoOOTPUUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi1); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEE","reRECO"),EEhits_weights74); event.getByLabel(edm::InputTag("ecalRecHitGlobal","EcalRecHitsGlobalEE","reRECO"),EEhits_weights53); event.getByLabel(edm::InputTag("ecalRecHit","EcalRecHitsEE","reRECO"),EEhits_multi5); event.getByLabel(edm::InputTag("ecalRecHitMultiFit25ns","EcalRecHitsMultiFit25nsEE","reRECO"),EEhits_multi10); event.getByLabel(edm::InputTag("ecalRecHitMultiFitNoOOTPU","EcalRecHitsMultiFitNoOOTPUEE","reRECO"),EEhits_multi1); event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi5); event.getByLabel(edm::InputTag("ecalMultiFit25nsUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi10); event.getByLabel(edm::InputTag("ecalMultiFitNoOOTPUUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi1); // Digis, from RAW Handle<EBDigiCollection> EBdigis; event.getByLabel(edm::InputTag("ecalDigis","ebDigis","reRECO"),EBdigis); Handle<EEDigiCollection> EEdigis; event.getByLabel(edm::InputTag("ecalDigis","eeDigis","reRECO"),EEdigis); // Rechit loop - EE // cout << "starting EE loop" << endl; for (EcalRecHitCollection::const_iterator hitItr = EEhits_weights53->begin(); hitItr != EEhits_weights53->end(); ++hitItr) { // cout << "in EE loop1" << endl; rechit_ene_weights53_ee=0, rechit_et_weights53_ee=0, rechit_time_weights53_ee=0; rechit_flag_kweird_weights53_ee=0; rechit_flag_kdiweird_weights53_ee=0; rechit_flag_koot_weights53_ee=0; rechit_chi2_weights53_ee=0; rechit_ene_weights74_ee=0, rechit_et_weights74_ee=0, rechit_time_weights74_ee=0; rechit_flag_kweird_weights74_ee=0; rechit_flag_kdiweird_weights74_ee=0; rechit_flag_koot_weights74_ee=0; rechit_chi2_weights74_ee=0; rechit_ene_multi5_ee=0, rechit_et_multi5_ee=0, rechit_time_multi5_ee=0; rechit_flag_kweird_multi5_ee=0; rechit_flag_kdiweird_multi5_ee=0; rechit_flag_koot_multi5_ee=0; rechit_chi2_multi5_ee=0; rechit_ene_multi10_ee=0, rechit_et_multi10_ee=0, rechit_time_multi10_ee=0; rechit_flag_kweird_multi10_ee=0; rechit_flag_kdiweird_multi10_ee=0; rechit_flag_koot_multi10_ee=0; rechit_chi2_multi10_ee=0; rechit_ene_multi1_ee=0, rechit_et_multi1_ee=0, rechit_time_multi1_ee=0; rechit_flag_kweird_multi1_ee=0; rechit_flag_kdiweird_multi1_ee=0; rechit_flag_koot_multi1_ee=0; rechit_chi2_multi1_ee=0; uncalibrechit_multi10_ampl_ee = 0; uncalibrechit_multi10_amperr_ee = 0; uncalibrechit_multi10_pedestal_ee = 0; uncalibrechit_multi10_jitter_ee = 0; uncalibrechit_multi10_chi2_ee = 0; for (int i=0;i<10;i++) uncalibrechit_multi10_ootampl_ee[i] = 0; uncalibrechit_multi5_ampl_ee = 0; uncalibrechit_multi5_amperr_ee = 0; uncalibrechit_multi5_pedestal_ee = 0; uncalibrechit_multi5_jitter_ee = 0; uncalibrechit_multi5_chi2_ee = 0; for (int i=0;i<10;i++) uncalibrechit_multi5_ootampl_ee[i] = 0; uncalibrechit_multi1_ampl_ee = 0; uncalibrechit_multi1_amperr_ee = 0; uncalibrechit_multi1_pedestal_ee = 0; uncalibrechit_multi1_jitter_ee = 0; uncalibrechit_multi1_chi2_ee = 0; for (int i=0;i<10;i++) uncalibrechit_multi1_ootampl_ee[i] = 0; rechit_ix=0, rechit_iy=0, rechit_iz=0, rechit_eta_ee=0, rechit_phi_ee=0; db_pedg12_ee=0, db_pedg6_ee=0, db_pedg1_ee=0; db_pedrmsg12_ee=0, db_pedrmsg6_ee=0, db_pedrmsg1_ee=0; lasercorr_ee=0; EcalRecHit hit = (*hitItr); EEDetId det = hit.id(); rechit_ix = det.ix(); rechit_iy = det.iy(); rechit_iz = det.zside(); rechit_ene_weights53_ee = hit.energy(); rechit_time_weights53_ee = hit.time(); rechit_chi2_weights53_ee = hit.chi2(); // int ietabin=rechit_ieta+86-1*(rechit_ieta>0); // ebene->SetBinContent(rechit_iphi,ietabin,rechit_ene_weights53); // ebtime->SetBinContent(rechit_iphi,ietabin,rechit_time_weights53); int eehashedid = det.hashedIndex(); GlobalPoint posee=geo->getPosition(hit.detid()); rechit_eta_ee=posee.eta(); rechit_phi_ee=posee.phi(); float pf=1.0/cosh(rechit_eta_ee); rechit_et_weights53_ee=rechit_ene_weights53_ee*pf; if (rechit_et_weights53_ee<1.0) continue; // cout << "rechit_et=" << rechit_et_weights53_ee << endl; // read pedestals from DB const EcalPedestals::Item *aped=0; aped=&eped->barrel(eehashedid); db_pedg12_ee=aped->mean_x12; db_pedg6_ee=aped->mean_x6; db_pedg1_ee=aped->mean_x1; db_pedrmsg12_ee=aped->rms_x12; db_pedrmsg6_ee=aped->rms_x6; db_pedrmsg1_ee=aped->rms_x1; // read lasercalib from db lasercorr_ee=laser->getLaserCorrection(EEDetId(det), event.time()); // lasercorr=1; if (hit.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_weights53_ee=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_weights53_ee=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_weights53_ee=1; // if (rechit_et>5.0 && abs(rechit_time)>3) rechit_flag_koot=1; // mask out noisy channels in data // select high energy hits if (rechit_et_weights53_ee>1.0) { // cout << "EEdigistart" << endl; // find digi corresponding to rechit EEDigiCollection::const_iterator digiItrEE= EEdigis->begin(); while(digiItrEE != EEdigis->end() && digiItrEE->id() != hitItr->id()) { digiItrEE++; } if (digiItrEE != EEdigis->end()) { EEDataFrame df(*digiItrEE); for(int i=0; i<10;++i) { int eedigiadc=df.sample(i).adc(); int eedigigain=df.sample(i).gainId(); digi_adc_ee[i]=eedigiadc; digi_gainid_ee[i]=eedigigain; } // cout << "EEdigistart" << endl; } for (EcalRecHitCollection::const_iterator hitItr2 = EEhits_weights74->begin(); hitItr2 != EEhits_weights74->end(); ++hitItr2) { // cout << "in EE loop2" << endl; EcalRecHit hit2 = (*hitItr2); EEDetId det2 = hit2.id(); if (det2!=det) continue; rechit_ene_weights74_ee = hit2.energy(); rechit_time_weights74_ee = hit2.time(); rechit_chi2_weights74_ee = hit2.chi2(); rechit_et_weights74_ee = rechit_ene_weights74_ee*pf; if (hit2.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_weights74_ee=1; if (hit2.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_weights74_ee=1; if (hit2.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_weights74_ee=1; } for (EcalRecHitCollection::const_iterator hitItr3 = EEhits_multi5->begin(); hitItr3 != EEhits_multi5->end(); ++hitItr3) { // cout << "in EE loop3" << endl; EcalRecHit hit3 = (*hitItr3); EEDetId det3 = hit3.id(); if (det3!=det) continue; rechit_ene_multi5_ee = hit3.energy(); rechit_time_multi5_ee = hit3.time(); rechit_chi2_multi5_ee = hit3.chi2(); rechit_et_multi5_ee = rechit_ene_multi5_ee*pf; if (hit3.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi5_ee=1; if (hit3.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi5_ee=1; if (hit3.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi5_ee=1; } for (EcalRecHitCollection::const_iterator hitItr4 = EEhits_multi10->begin(); hitItr4 != EEhits_multi10->end(); ++hitItr4) { // cout << "in EE loop4" << endl; EcalRecHit hit4 = (*hitItr4); EEDetId det4 = hit4.id(); if (det4!=det) continue; rechit_ene_multi10_ee = hit4.energy(); rechit_time_multi10_ee = hit4.time(); rechit_chi2_multi10_ee = hit4.chi2(); rechit_et_multi10_ee = rechit_ene_multi10_ee*pf; if (hit4.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi10_ee=1; if (hit4.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi10_ee=1; if (hit4.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi10_ee=1; } for (EcalRecHitCollection::const_iterator hitItr5 = EEhits_multi1->begin(); hitItr5 != EEhits_multi1->end(); ++hitItr5) { // cout << "in EE loop5" << endl; EcalRecHit hit5 = (*hitItr5); EEDetId det5 = hit5.id(); if (det5!=det) continue; rechit_ene_multi1_ee = hit5.energy(); rechit_time_multi1_ee = hit5.time(); rechit_chi2_multi1_ee = hit5.chi2(); rechit_et_multi1_ee = rechit_ene_multi1_ee*pf; if (hit5.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi1_ee=1; if (hit5.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi1_ee=1; if (hit5.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi1_ee=1; } for (EcalUncalibratedRecHitCollection::const_iterator hitItr6 = EEhitsU_multi10->begin(); hitItr6 != EEhitsU_multi10->end(); ++hitItr6) { // cout << "in EE loop4" << endl; EcalUncalibratedRecHit hit6 = (*hitItr6); EEDetId det6 = hit6.id(); if (det6!=det) continue; uncalibrechit_multi10_ampl_ee = hit6.amplitude(); uncalibrechit_multi10_amperr_ee = hit6.amplitudeError(); uncalibrechit_multi10_pedestal_ee = hit6.pedestal(); uncalibrechit_multi10_jitter_ee = hit6.jitter(); uncalibrechit_multi10_chi2_ee = hit6.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi10_ootampl_ee[i] = hit6.outOfTimeAmplitude(i); /* cout << "Uncalib rechit: ampl=" << uncalibrechit_multi10_ampl_ee << "\n err=" << uncalibrechit_multi10_amperr_ee << "\n ped=" << uncalibrechit_multi10_pedestal_ee << "\n jitter=" << uncalibrechit_multi10_jitter_ee << "\n chi2=" << uncalibrechit_multi10_chi2_ee << endl; for (int i=0;i<10;i++) { cout << " OOT amp, bin=" << i << " =" << uncalibrechit_multi10_ootampl_ee[i] << endl; } */ } for (EcalUncalibratedRecHitCollection::const_iterator hitItr8 = EEhitsU_multi1->begin(); hitItr8 != EEhitsU_multi1->end(); ++hitItr8) { // cout << "in EE loop4" << endl; EcalUncalibratedRecHit hit8 = (*hitItr8); EEDetId det8 = hit8.id(); if (det8!=det) continue; uncalibrechit_multi1_ampl_ee = hit8.amplitude(); uncalibrechit_multi1_amperr_ee = hit8.amplitudeError(); uncalibrechit_multi1_pedestal_ee = hit8.pedestal(); uncalibrechit_multi1_jitter_ee = hit8.jitter(); uncalibrechit_multi1_chi2_ee = hit8.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi1_ootampl_ee[i] = hit8.outOfTimeAmplitude(i); } for (EcalUncalibratedRecHitCollection::const_iterator hitItr7 = EEhitsU_multi5->begin(); hitItr7 != EEhitsU_multi5->end(); ++hitItr7) { // cout << "in EE loop4" << endl; EcalUncalibratedRecHit hit7 = (*hitItr7); EEDetId det7 = hit7.id(); if (det7!=det) continue; uncalibrechit_multi5_ampl_ee = hit7.amplitude(); uncalibrechit_multi5_amperr_ee = hit7.amplitudeError(); uncalibrechit_multi5_pedestal_ee = hit7.pedestal(); uncalibrechit_multi5_jitter_ee = hit7.jitter(); uncalibrechit_multi5_chi2_ee = hit7.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi5_ootampl_ee[i] = hit7.outOfTimeAmplitude(i); } // cout << "end of loop" << endl; dataTree2_->Fill(); // cout << "end of loop - filled tree" << endl; } } // Rechit loop - EB for (EcalRecHitCollection::const_iterator hitItr = EBhits_weights53->begin(); hitItr != EBhits_weights53->end(); ++hitItr) { rechit_swisscross_weights53=0; rechit_ene_weights53=0, rechit_et_weights53=0, rechit_time_weights53=0; rechit_flag_kweird_weights53=0; rechit_flag_kdiweird_weights53=0; rechit_flag_koot_weights53=0; rechit_chi2_weights53=0; rechit_swisscross_weights74=0; rechit_ene_weights74=0, rechit_et_weights74=0, rechit_time_weights74=0; rechit_flag_kweird_weights74=0; rechit_flag_kdiweird_weights74=0; rechit_flag_koot_weights74=0; rechit_chi2_weights74=0; rechit_swisscross_multi5=0; rechit_ene_multi5=0, rechit_et_multi5=0, rechit_time_multi5=0; rechit_flag_kweird_multi5=0; rechit_flag_kdiweird_multi5=0; rechit_flag_koot_multi5=0; rechit_chi2_multi5=0; rechit_swisscross_multi10=0; rechit_ene_multi10=0, rechit_et_multi10=0, rechit_time_multi10=0; rechit_flag_kweird_multi10=0; rechit_flag_kdiweird_multi10=0; rechit_flag_koot_multi10=0; rechit_chi2_multi10=0; rechit_swisscross_multi1=0; rechit_ene_multi1=0, rechit_et_multi1=0, rechit_time_multi1=0; rechit_flag_kweird_multi1=0; rechit_flag_kdiweird_multi1=0; rechit_flag_koot_multi1=0; rechit_chi2_multi1=0; rechit_swisscross_zs_weights53=0; rechit_swisscross_zs_weights74=0; rechit_swisscross_zs_multi5=0; rechit_swisscross_zs_multi10=0; rechit_swisscross_zs_multi1=0; rechit_swisscross_thresh=0; rechit_flag_kweird_calc=0; isnearcrack=0; uncalibrechit_multi10_ampl_eb = 0; uncalibrechit_multi10_amperr_eb = 0; uncalibrechit_multi10_pedestal_eb = 0; uncalibrechit_multi10_jitter_eb = 0; uncalibrechit_multi10_chi2_eb = 0; for (int i=0;i<10;i++) uncalibrechit_multi10_ootampl_eb[i] = 0; uncalibrechit_multi5_ampl_eb = 0; uncalibrechit_multi5_amperr_eb = 0; uncalibrechit_multi5_pedestal_eb = 0; uncalibrechit_multi5_jitter_eb = 0; uncalibrechit_multi5_chi2_eb = 0; for (int i=0;i<10;i++) uncalibrechit_multi5_ootampl_eb[i] = 0; uncalibrechit_multi1_ampl_eb = 0; uncalibrechit_multi1_amperr_eb = 0; uncalibrechit_multi1_pedestal_eb = 0; uncalibrechit_multi1_jitter_eb = 0; uncalibrechit_multi1_chi2_eb = 0; for (int i=0;i<10;i++) uncalibrechit_multi1_ootampl_eb[i] = 0; rechit_ieta=0, rechit_iphi=0, rechit_eta=0, rechit_phi=0; db_pedg12=0, db_pedg6=0, db_pedg1=0; db_pedrmsg12=0, db_pedrmsg6=0, db_pedrmsg1=0; lasercorr=0; EcalRecHit hit = (*hitItr); EBDetId det = hit.id(); rechit_ieta = det.ieta(); rechit_iphi = det.iphi(); rechit_ene_weights53 = hit.energy(); rechit_time_weights53 = hit.time(); rechit_chi2_weights53 = hit.chi2(); // int ietabin=rechit_ieta+86-1*(rechit_ieta>0); // ebene->SetBinContent(rechit_iphi,ietabin,rechit_ene_weights53); // ebtime->SetBinContent(rechit_iphi,ietabin,rechit_time_weights53); int ebhashedid = det.hashedIndex(); GlobalPoint poseb=geo->getPosition(hit.detid()); rechit_eta=poseb.eta(); rechit_phi=poseb.phi(); float pf=1.0/cosh(rechit_eta); rechit_et_weights53=rechit_ene_weights53*pf; if (rechit_et_weights53<3.0) continue; // swiss-cross calculation float s41=0; float s42=0; float s43=0; float s44=0; s41 = recHitE( det, *EBhits_weights53, 1, 0 ); s42 = recHitE( det, *EBhits_weights53, -1, 0 ); s43 = recHitE( det, *EBhits_weights53, 0, 1 ); s44 = recHitE( det, *EBhits_weights53, 0, -1 ); float s4=s41+s42+s43+s44; float s4zs=0; if (s41>0.08) s4zs+=s41; if (s42>0.08) s4zs+=s42; if (s43>0.08) s4zs+=s43; if (s44>0.08) s4zs+=s44; isnearcrack=0; isnearcrack=EBDetId::isNextToBoundary(det); if (rechit_ene_weights53>0) { rechit_swisscross_weights53=1.0-s4/rechit_ene_weights53; rechit_swisscross_zs_weights53=1.0-s4zs/rechit_ene_weights53; } float e4e1thresh=0.04*log10(rechit_ene_weights53)-0.024; float e4e1ene=4.0; if (isnearcrack) { e4e1thresh=e4e1thresh/3.0; e4e1ene=e4e1ene*2.0; } if (rechit_swisscross_zs_weights53>(1.0-e4e1thresh) && rechit_ene_weights53>e4e1ene) rechit_flag_kweird_calc=1; rechit_swisscross_thresh= 1.0 - e4e1thresh; // read pedestals from DB const EcalPedestals::Item *aped=0; aped=&eped->barrel(ebhashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; // read lasercalib from db lasercorr=laser->getLaserCorrection(EBDetId(det), event.time()); // lasercorr=1; if (hit.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_weights53=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_weights53=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_weights53=1; // if (rechit_et>5.0 && abs(rechit_time)>3) rechit_flag_koot=1; // mask out noisy channels in data if ((rechit_ieta==11 && rechit_iphi==68) || (rechit_ieta==68 && rechit_iphi==74) || (rechit_ieta==-83 && rechit_iphi==189) || (rechit_ieta==-75 && rechit_iphi==199)) continue; // select high energy hits if (rechit_et_weights53>1.0) { // find digi corresponding to rechit EBDigiCollection::const_iterator digiItrEB= EBdigis->begin(); while(digiItrEB != EBdigis->end() && digiItrEB->id() != hitItr->id()) { digiItrEB++; } if (digiItrEB != EBdigis->end()) { EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); digi_adc[i]=ebdigiadc; digi_gainid[i]=ebdigigain; } } for (EcalRecHitCollection::const_iterator hitItr2 = EBhits_weights74->begin(); hitItr2 != EBhits_weights74->end(); ++hitItr2) { EcalRecHit hit2 = (*hitItr2); EBDetId det2 = hit2.id(); if (det2!=det) continue; rechit_ene_weights74 = hit2.energy(); rechit_time_weights74 = hit2.time(); rechit_chi2_weights74 = hit2.chi2(); rechit_et_weights74 = rechit_ene_weights74*pf; float s41_2=0; float s42_2=0; float s43_2=0; float s44_2=0; s41_2 = recHitE( det2, *EBhits_weights74, 1, 0 ); s42_2 = recHitE( det2, *EBhits_weights74, -1, 0 ); s43_2 = recHitE( det2, *EBhits_weights74, 0, 1 ); s44_2 = recHitE( det2, *EBhits_weights74, 0, -1 ); float s4_2=s41_2+s42_2+s43_2+s44_2; float s4zs_2=0; if (s41_2>0.08) s4zs_2+=s41_2; if (s42_2>0.08) s4zs_2+=s42_2; if (s43_2>0.08) s4zs_2+=s43_2; if (s44_2>0.08) s4zs_2+=s44_2; if (rechit_ene_weights74>0) { rechit_swisscross_weights74=1.0-s4_2/rechit_ene_weights74; rechit_swisscross_zs_weights74=1.0-s4zs_2/rechit_ene_weights74; } if (hit2.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_weights74=1; if (hit2.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_weights74=1; if (hit2.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_weights74=1; } for (EcalRecHitCollection::const_iterator hitItr3 = EBhits_multi5->begin(); hitItr3 != EBhits_multi5->end(); ++hitItr3) { EcalRecHit hit3 = (*hitItr3); EBDetId det3 = hit3.id(); if (det3!=det) continue; rechit_ene_multi5 = hit3.energy(); rechit_time_multi5 = hit3.time(); rechit_chi2_multi5 = hit3.chi2(); rechit_et_multi5 = rechit_ene_multi5*pf; float s41_3=0; float s42_3=0; float s43_3=0; float s44_3=0; s41_3 = recHitE( det3, *EBhits_multi5, 1, 0 ); s42_3 = recHitE( det3, *EBhits_multi5, -1, 0 ); s43_3 = recHitE( det3, *EBhits_multi5, 0, 1 ); s44_3 = recHitE( det3, *EBhits_multi5, 0, -1 ); float s4_3=s41_3+s42_3+s43_3+s44_3; float s4zs_3=0; if (s41_3>0.08) s4zs_3+=s41_3; if (s42_3>0.08) s4zs_3+=s42_3; if (s43_3>0.08) s4zs_3+=s43_3; if (s44_3>0.08) s4zs_3+=s44_3; if (rechit_ene_multi5>0) { rechit_swisscross_multi5=1.0-s4_3/rechit_ene_multi5; rechit_swisscross_zs_multi5=1.0-s4zs_3/rechit_ene_multi5; } if (hit3.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi5=1; if (hit3.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi5=1; if (hit3.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi5=1; } for (EcalRecHitCollection::const_iterator hitItr4 = EBhits_multi10->begin(); hitItr4 != EBhits_multi10->end(); ++hitItr4) { EcalRecHit hit4 = (*hitItr4); EBDetId det4 = hit4.id(); if (det4!=det) continue; rechit_ene_multi10 = hit4.energy(); rechit_time_multi10 = hit4.time(); rechit_chi2_multi10 = hit4.chi2(); rechit_et_multi10 = rechit_ene_multi10*pf; float s41_4=0; float s42_4=0; float s43_4=0; float s44_4=0; s41_4 = recHitE( det4, *EBhits_multi10, 1, 0 ); s42_4 = recHitE( det4, *EBhits_multi10, -1, 0 ); s43_4 = recHitE( det4, *EBhits_multi10, 0, 1 ); s44_4 = recHitE( det4, *EBhits_multi10, 0, -1 ); float s4_4=s41_4+s42_4+s43_4+s44_4; float s4zs_4=0; if (s41_4>0.08) s4zs_4+=s41_4; if (s42_4>0.08) s4zs_4+=s42_4; if (s43_4>0.08) s4zs_4+=s43_4; if (s44_4>0.08) s4zs_4+=s44_4; if (rechit_ene_multi10>0) { rechit_swisscross_multi10=1.0-s4_4/rechit_ene_multi10; rechit_swisscross_zs_multi10=1.0-s4zs_4/rechit_ene_multi10; } if (hit4.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi10=1; if (hit4.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi10=1; if (hit4.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi10=1; } for (EcalRecHitCollection::const_iterator hitItr5 = EBhits_multi1->begin(); hitItr5 != EBhits_multi1->end(); ++hitItr5) { EcalRecHit hit5 = (*hitItr5); EBDetId det5 = hit5.id(); if (det5!=det) continue; rechit_ene_multi1 = hit5.energy(); rechit_time_multi1 = hit5.time(); rechit_chi2_multi1 = hit5.chi2(); rechit_et_multi1 = rechit_ene_multi1*pf; float s41_5=0; float s42_5=0; float s43_5=0; float s44_5=0; s41_5 = recHitE( det5, *EBhits_multi1, 1, 0 ); s42_5 = recHitE( det5, *EBhits_multi1, -1, 0 ); s43_5 = recHitE( det5, *EBhits_multi1, 0, 1 ); s44_5 = recHitE( det5, *EBhits_multi1, 0, -1 ); float s4_5=s41_5+s42_5+s43_5+s44_5; float s4zs_5=0; if (s41_5>0.08) s4zs_5+=s41_5; if (s42_5>0.08) s4zs_5+=s42_5; if (s43_5>0.08) s4zs_5+=s43_5; if (s44_5>0.08) s4zs_5+=s44_5; if (rechit_ene_multi1>0) { rechit_swisscross_multi1=1.0-s4_5/rechit_ene_multi1; rechit_swisscross_zs_multi1=1.0-s4zs_5/rechit_ene_multi1; } if (hit5.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird_multi1=1; if (hit5.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird_multi1=1; if (hit5.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot_multi1=1; } for (EcalUncalibratedRecHitCollection::const_iterator hitItr6 = EBhitsU_multi10->begin(); hitItr6 != EBhitsU_multi10->end(); ++hitItr6) { EcalUncalibratedRecHit hit6 = (*hitItr6); EBDetId det6 = hit6.id(); if (det6!=det) continue; uncalibrechit_multi10_ampl_eb = hit6.amplitude(); uncalibrechit_multi10_amperr_eb = hit6.amplitudeError(); uncalibrechit_multi10_pedestal_eb = hit6.pedestal(); uncalibrechit_multi10_jitter_eb = hit6.jitter(); uncalibrechit_multi10_chi2_eb = hit6.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi10_ootampl_eb[i] = hit6.outOfTimeAmplitude(i); } for (EcalUncalibratedRecHitCollection::const_iterator hitItr7 = EBhitsU_multi5->begin(); hitItr7 != EBhitsU_multi5->end(); ++hitItr7) { // cout << "in EE loop4" << endl; EcalUncalibratedRecHit hit7 = (*hitItr7); EBDetId det7 = hit7.id(); if (det7!=det) continue; uncalibrechit_multi5_ampl_eb = hit7.amplitude(); uncalibrechit_multi5_amperr_eb = hit7.amplitudeError(); uncalibrechit_multi5_pedestal_eb = hit7.pedestal(); uncalibrechit_multi5_jitter_eb = hit7.jitter(); uncalibrechit_multi5_chi2_eb = hit7.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi5_ootampl_eb[i] = hit7.outOfTimeAmplitude(i); } for (EcalUncalibratedRecHitCollection::const_iterator hitItr8 = EBhitsU_multi1->begin(); hitItr8 != EBhitsU_multi1->end(); ++hitItr8) { EcalUncalibratedRecHit hit8 = (*hitItr8); EBDetId det8 = hit8.id(); if (det8!=det) continue; uncalibrechit_multi1_ampl_eb = hit8.amplitude(); uncalibrechit_multi1_amperr_eb = hit8.amplitudeError(); uncalibrechit_multi1_pedestal_eb = hit8.pedestal(); uncalibrechit_multi1_jitter_eb = hit8.jitter(); uncalibrechit_multi1_chi2_eb = hit8.chi2(); for (int i=0;i<10;i++) uncalibrechit_multi1_ootampl_eb[i] = hit8.outOfTimeAmplitude(i); } dataTree_->Fill(); } } // } // } } ////////////////////////////////////////////////////////////////////////////////////////// SpikeAnalyser::~SpikeAnalyser() { delete file_; delete dataTree_; delete dataTree2_; } //} <file_sep>/plugins/ChanstatusTester.cc #include <iostream> #include <sstream> #include <istream> #include <fstream> #include <iomanip> #include <string> #include <cmath> #include <functional> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/CaloTowers/interface/CaloTowerCollection.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgoRcd.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalCleaningAlgo.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbService.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPedestals.h" #include "CondFormats/DataRecord/interface/EcalADCToGeVConstantRcd.h" #include "CondFormats/EcalObjects/interface/EcalADCToGeVConstant.h" #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h" #include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h" #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTriggerRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTrigger.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFLayer.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "JetMETCorrections/MCJet/plugins/ChanstatusTester.h" #include "JetMETCorrections/MCJet/plugins/JetUtilMC.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterTools.h" #include "RecoEcal/EgammaCoreTools/interface/EcalTools.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPedestals.h" #include "Math/VectorUtil.h" #include "TVector3.h" using namespace edm; using namespace reco; using namespace std; DEFINE_FWK_MODULE(ChanstatusTester); ChanstatusTester::ChanstatusTester(const edm::ParameterSet& cfg) : bunchstartbx_(cfg.getParameter<std::vector<int> >("bunchstartbx")) { jets_ = cfg.getParameter<std::string> ("jets"); histogramFile_ = cfg.getParameter<std::string> ("histogramFile"); tracks_ = cfg.getParameter<std::string> ("tracks"); vertex_coll_ = cfg.getParameter<std::string> ("vertex"); ebhitcoll_ = cfg.getParameter<std::string> ("EBRecHitCollection"); eehitcoll_ = cfg.getParameter<std::string> ("EERecHitCollection"); isMC_ = cfg.getParameter<bool>("IsMC"); edm::ParameterSet cleaningPs = cfg.getParameter<edm::ParameterSet>("cleaningConfig"); cleaningAlgo_ = new EcalCleaningAlgo(cleaningPs); } ////////////////////////////////////////////////////////////////////////////////////////// void ChanstatusTester::beginJob() { file_ = new TFile(histogramFile_.c_str(),"RECREATE"); histo_event_ = new TH1D("histo_event","",350,0.,3500.); eb_rechitenergy_ = new TH1D("eb_rechitenergy","",2020,-2.,200.); ee_rechitenergy_ = new TH1D("ee_rechitenergy","",2020,-2.,200.); ee_rechitenergy_notypeb_ = new TH1D("ee_rechitenergy_notypeb","",2020,-2.,200.); eb_rechitenergy_spiketag = new TH1D("eb_rechitenergy_spiketag","",2020,-2.,200.); eb_rechitenergy_swisscross = new TH1D("eb_rechitenergy_swisscross","",2020,-2.,200.); eb_rechitenergy_kweird = new TH1D("eb_rechitenergy_kweird","",2020,-2.,200.); eb_rechitenergy_knotweird = new TH1D("eb_rechitenergy_knotweird","",2020,-2.,200.); eb_rechitenergy_spiketag_kweird = new TH1D("eb_rechitenergy_spiketag_kweird","",2020,-2.,200.); eb_rechitenergy_spiketag_swisscross = new TH1D("eb_rechitenergy_spiketag_swisscross","",2020,-2.,200.); eb_rechitenergy_spiketag_noisedep = new TH1D("eb_rechitenergy_spiketag_noisedep","",2020,-2.,200.); eb_rechitenergy_sctag = new TH1D("eb_rechitenergy_sctag","",2020,-2.,200.); eb_rechitenergy_sctag_kweird = new TH1D("eb_rechitenergy_sctag_kweird","",2020,-2.,200.); eb_rechitenergy_sctag_swisscross = new TH1D("eb_rechitenergy_sctag_swisscross","",2020,-2.,200.); eb_rechitenergy_sctag_noisedep = new TH1D("eb_rechitenergy_sctag_noisedep","",2020,-2.,200.); Emin_=1000.0; side_=5; eb_rechitenergy_02 = new TH1D("eb_rechitenergy_02","",1100,-2.,20.); eb_rechitenergy_04 = new TH1D("eb_rechitenergy_04","",1100,-2.,20.); eb_rechitenergy_06 = new TH1D("eb_rechitenergy_06","",1100,-2.,20.); eb_rechitenergy_08 = new TH1D("eb_rechitenergy_08","",1100,-2.,20.); eb_rechitenergy_10 = new TH1D("eb_rechitenergy_10","",1100,-2.,20.); eb_rechitenergy_12 = new TH1D("eb_rechitenergy_12","",1100,-2.,20.); eb_rechitenergy_14 = new TH1D("eb_rechitenergy_14","",1100,-2.,20.); eb_rechitenergy_148 = new TH1D("eb_rechitenergy_148","",1100,-2.,20.); ee_rechitenergy_16 = new TH1D("ee_rechitenergy_16","",1100,-2.,20.); ee_rechitenergy_18 = new TH1D("ee_rechitenergy_18","",1100,-2.,20.); ee_rechitenergy_20 = new TH1D("ee_rechitenergy_20","",1100,-2.,20.); ee_rechitenergy_22 = new TH1D("ee_rechitenergy_22","",1100,-2.,20.); ee_rechitenergy_24 = new TH1D("ee_rechitenergy_24","",1100,-2.,20.); ee_rechitenergy_26 = new TH1D("ee_rechitenergy_26","",1100,-2.,20.); ee_rechitenergy_28 = new TH1D("ee_rechitenergy_28","",1100,-2.,20.); ee_rechitenergy_30 = new TH1D("ee_rechitenergy_30","",1100,-2.,20.); eb_rechitet_02 = new TH1D("eb_rechitet_02","",1100,-2.,20.); eb_rechitet_04 = new TH1D("eb_rechitet_04","",1100,-2.,20.); eb_rechitet_06 = new TH1D("eb_rechitet_06","",1100,-2.,20.); eb_rechitet_08 = new TH1D("eb_rechitet_08","",1100,-2.,20.); eb_rechitet_10 = new TH1D("eb_rechitet_10","",1100,-2.,20.); eb_rechitet_12 = new TH1D("eb_rechitet_12","",1100,-2.,20.); eb_rechitet_14 = new TH1D("eb_rechitet_14","",1100,-2.,20.); eb_rechitet_148 = new TH1D("eb_rechitet_148","",1100,-2.,20.); ee_rechitet_16 = new TH1D("ee_rechitet_16","",1100,-2.,20.); ee_rechitet_18 = new TH1D("ee_rechitet_18","",1100,-2.,20.); ee_rechitet_20 = new TH1D("ee_rechitet_20","",1100,-2.,20.); ee_rechitet_22 = new TH1D("ee_rechitet_22","",1100,-2.,20.); ee_rechitet_24 = new TH1D("ee_rechitet_24","",1100,-2.,20.); ee_rechitet_26 = new TH1D("ee_rechitet_26","",1100,-2.,20.); ee_rechitet_28 = new TH1D("ee_rechitet_28","",1100,-2.,20.); ee_rechitet_30 = new TH1D("ee_rechitet_30","",1100,-2.,20.); eb_rechitetvspu_05 = new TH2D("eb_rechitetvspu_05","",25,0,50,500,-0.5,20); eb_rechitetvspu_10 = new TH2D("eb_rechitetvspu_10","",25,0,50,500,-0.5,20); eb_rechitetvspu_15 = new TH2D("eb_rechitetvspu_15","",25,0,50,500,-0.5,20); ee_rechitetvspu_20 = new TH2D("ee_rechitetvspu_20","",25,0,50,500,-0.5,20); ee_rechitetvspu_25 = new TH2D("ee_rechitetvspu_25","",25,0,50,500,-0.5,20); ee_rechitetvspu_30 = new TH2D("ee_rechitetvspu_30","",25,0,50,500,-0.5,20); eb_rechitet_ = new TH1D("eb_rechitet","",1100,-2.,20.); ee_rechitet_ = new TH1D("ee_rechitet","",1100,-2.,20.); eb_rechiten_vs_eta = new TH2D("ebrechiten_vs_eta","",30,-1.5,1.5,350,-2,5); eb_rechitet_vs_eta = new TH2D("ebrechitet_vs_eta","",30,-1.5,1.5,350,-2,5); eep_rechiten_vs_eta = new TH2D("eep_rechiten_vs_eta","",18,1.4,3.2,350,-2,5); eep_rechiten_vs_phi = new TH2D("eep_rechiten_vs_phi","",18,-3.1416,3.1416,350,-2,5); eem_rechiten_vs_eta = new TH2D("eem_rechiten_vs_eta","",18,1.4,3.2,350,-2,5); eem_rechiten_vs_phi = new TH2D("eem_rechiten_vs_phi","",18,-3.1416,3.1416,350,-2,5); eep_rechitet_vs_eta = new TH2D("eep_rechitet_vs_eta","",18,1.4,3.2,350,-2,5); eep_rechitet_vs_phi = new TH2D("eep_rechitet_vs_phi","",18,-3.1416,3.1416,350,-2,5); eem_rechitet_vs_eta = new TH2D("eem_rechitet_vs_eta","",18,1.4,3.2,350,-2,5); eem_rechitet_vs_phi = new TH2D("eem_rechitet_vs_phi","",18,-3.1416,3.1416,350,-2,5); ebocc = new TH2F("ebocc","",360,0,360,170,-85,85); eboccgt1 = new TH2F("eboccgt1","",360,0,360,170,-85,85); eboccgt3 = new TH2F("eboccgt3","",360,0,360,170,-85,85); eboccgt5 = new TH2F("eboccgt5","",360,0,360,170,-85,85); eboccgt1et = new TH2F("eboccgt1et","",360,0,360,170,-85,85); eboccet = new TH2F("eboccet","",360,0,360,170,-85,85); eboccetgt1et = new TH2F("eboccetgt1et","",360,0,360,170,-85,85); eboccen = new TH2F("eboccen","",360,0,360,170,-85,85); eboccengt1 = new TH2F("eboccengt1","",360,0,360,170,-85,85); eeocc = new TH2F("eeocc","",200,0,200,100,0,100); eeoccgt1 = new TH2F("eeoccgt1","",200,0,200,100,0,100); eeoccgt1et = new TH2F("eeoccgt1et","",200,0,200,100,0,100); eeoccet = new TH2F("eeoccet","",200,0,200,100,0,100); eeoccetgt1et = new TH2F("eeoccetgt1et","",200,0,200,100,0,100); eeoccen = new TH2F("eeoccen","",200,0,200,100,0,100); eeoccengt1 = new TH2F("eeoccengt1","",200,0,200,100,0,100); spikeadc=new TH1F("spikeadc","",100,0,1000); spiketime50=new TH1F("spiketime50","",10,0.5,10.5); etaphi_ped = new TH2D("etaphi_ped","",360,0,360,170,-85,85); etaphi_pedsq = new TH2D("etaphi_pedsq","",360,0,360,170,-85,85); etaphi_pedn = new TH2D("etaphi_pedn","",360,0,360,170,-85,85); etaphi_pednoise = new TH2D("etaphi_pednoise","",360,0,360,170,-85,85); noise2d = new TH2D("noise2d","",360,0,360,170,-85,85); eventenergy = new TH2D("eventenergy","",360,0,360,170,-85,85); eventet = new TH2D("eventet","",360,0,360,170,-85,85); eventtime = new TH2D("eventtime","",360,0,360,170,-85,85); eventkoot = new TH2D("eventkoot","",360,0,360,170,-85,85); eventkdiweird = new TH2D("eventkdiweird","",360,0,360,170,-85,85); spike_timevset_all_08 = new TH2D("spike_timevset_all_08","",120,-60,60,200,-2,18); spike_timevset_highest_08 = new TH2D("spike_timevset_highest_08","",120,-60,60,200,-2,18); spike_timevset_koot_all_08 = new TH2D("spike_timevset_koot_all_08","",120,-60,60,200,-2,18); spike_timevset_koot_highest_08 = new TH2D("spike_timevset_koot_highest_08","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_08 = new TH2D("spike_timevset_kdiweird_all_08","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_08 = new TH2D("spike_timevset_kdiweird_highest_08","",120,-60,60,200,-2,18); spike_timevset_all_07 = new TH2D("spike_timevset_all_07","",120,-60,60,200,-2,18); spike_timevset_highest_07 = new TH2D("spike_timevset_highest_07","",120,-60,60,200,-2,18); spike_timevset_koot_all_07 = new TH2D("spike_timevset_koot_all_07","",120,-60,60,200,-2,18); spike_timevset_koot_highest_07 = new TH2D("spike_timevset_koot_highest_07","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_07 = new TH2D("spike_timevset_kdiweird_all_07","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_07 = new TH2D("spike_timevset_kdiweird_highest_07","",120,-60,60,200,-2,18); spike_timevset_all_06 = new TH2D("spike_timevset_all_06","",120,-60,60,200,-2,18); spike_timevset_highest_06 = new TH2D("spike_timevset_highest_06","",120,-60,60,200,-2,18); spike_timevset_koot_all_06 = new TH2D("spike_timevset_koot_all_06","",120,-60,60,200,-2,18); spike_timevset_koot_highest_06 = new TH2D("spike_timevset_koot_highest_06","",120,-60,60,200,-2,18); spike_timevset_kdiweird_all_06 = new TH2D("spike_timevset_kdiweird_all_06","",120,-60,60,200,-2,18); spike_timevset_kdiweird_highest_06 = new TH2D("spike_timevset_kdiweird_highest_06","",120,-60,60,200,-2,18); scocc_eb_gt50 = new TH2F("scocc_eb_gt50","",100,-3.14,3.14,100,-3,3); scocc_ee_gt50 = new TH2F("scocc_ee_gt50","",100,-3.14,3.14,100,-3,3); tower_spike_ene_swiss_t10 = new TH2D("tower_spike_ene_swiss_t10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07 = new TH2D("tower_spike_ene_swiss_t07","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05 = new TH2D("tower_spike_ene_swiss_t05","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04 = new TH2D("tower_spike_ene_swiss_t04","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03 = new TH2D("tower_spike_ene_swiss_t03","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10 = new TH2D("sc_tower_spike_ene_swiss_t10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07 = new TH2D("sc_tower_spike_ene_swiss_t07","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05 = new TH2D("sc_tower_spike_ene_swiss_t05","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04 = new TH2D("sc_tower_spike_ene_swiss_t04","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03 = new TH2D("sc_tower_spike_ene_swiss_t03","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh08 = new TH2D("tower_spike_ene_swiss_t10_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh08 = new TH2D("tower_spike_ene_swiss_t07_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh08 = new TH2D("tower_spike_ene_swiss_t05_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh08 = new TH2D("tower_spike_ene_swiss_t04_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh08 = new TH2D("tower_spike_ene_swiss_t03_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh10 = new TH2D("tower_spike_ene_swiss_t10_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh10 = new TH2D("tower_spike_ene_swiss_t07_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh10 = new TH2D("tower_spike_ene_swiss_t05_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh10 = new TH2D("tower_spike_ene_swiss_t04_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh10 = new TH2D("tower_spike_ene_swiss_t03_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh12 = new TH2D("tower_spike_ene_swiss_t10_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh12 = new TH2D("tower_spike_ene_swiss_t07_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh12 = new TH2D("tower_spike_ene_swiss_t05_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh12 = new TH2D("tower_spike_ene_swiss_t04_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh12 = new TH2D("tower_spike_ene_swiss_t03_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh15 = new TH2D("tower_spike_ene_swiss_t10_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh15 = new TH2D("tower_spike_ene_swiss_t07_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh15 = new TH2D("tower_spike_ene_swiss_t05_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh15 = new TH2D("tower_spike_ene_swiss_t04_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh15 = new TH2D("tower_spike_ene_swiss_t03_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t10_thresh20 = new TH2D("tower_spike_ene_swiss_t10_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t07_thresh20 = new TH2D("tower_spike_ene_swiss_t07_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t05_thresh20 = new TH2D("tower_spike_ene_swiss_t05_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t04_thresh20 = new TH2D("tower_spike_ene_swiss_t04_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_t03_thresh20 = new TH2D("tower_spike_ene_swiss_t03_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh08 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh10 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh12 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh15 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t10_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t10_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t07_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t07_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t05_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t05_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t04_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t04_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_t03_thresh20 = new TH2D("sc_tower_spike_ene_swiss_t03_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt = new TH2D("tower_spike_et_swisstt","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt = new TH2D("tower_spike_ene_swisstt","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh08 = new TH2D("tower_spike_et_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh08 = new TH2D("tower_spike_ene_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh10 = new TH2D("tower_spike_et_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh10 = new TH2D("tower_spike_ene_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh12 = new TH2D("tower_spike_et_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh12 = new TH2D("tower_spike_ene_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh15 = new TH2D("tower_spike_et_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh15 = new TH2D("tower_spike_ene_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swisstt_thresh20 = new TH2D("tower_spike_et_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swisstt_thresh20 = new TH2D("tower_spike_ene_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt = new TH2D("sc_tower_spike_et_swisstt","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt = new TH2D("sc_tower_spike_ene_swisstt","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh08 = new TH2D("sc_tower_spike_et_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh08 = new TH2D("sc_tower_spike_ene_swisstt_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh10 = new TH2D("sc_tower_spike_et_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh10 = new TH2D("sc_tower_spike_ene_swisstt_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh12 = new TH2D("sc_tower_spike_et_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh12 = new TH2D("sc_tower_spike_ene_swisstt_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh15 = new TH2D("sc_tower_spike_et_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh15 = new TH2D("sc_tower_spike_ene_swisstt_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swisstt_thresh20 = new TH2D("sc_tower_spike_et_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swisstt_thresh20 = new TH2D("sc_tower_spike_ene_swisstt_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss = new TH2D("tower_spike_et_swiss","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss = new TH2D("tower_spike_ene_swiss","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh08 = new TH2D("tower_spike_et_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh08 = new TH2D("tower_spike_ene_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh10 = new TH2D("tower_spike_et_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh10 = new TH2D("tower_spike_ene_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh12 = new TH2D("tower_spike_et_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh12 = new TH2D("tower_spike_ene_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh15 = new TH2D("tower_spike_et_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh15 = new TH2D("tower_spike_ene_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); tower_spike_et_swiss_thresh20 = new TH2D("tower_spike_et_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); tower_spike_ene_swiss_thresh20 = new TH2D("tower_spike_ene_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss = new TH2D("sc_tower_spike_et_swiss","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss = new TH2D("sc_tower_spike_ene_swiss","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh08 = new TH2D("sc_tower_spike_et_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh08 = new TH2D("sc_tower_spike_ene_swiss_thresh08","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh10 = new TH2D("sc_tower_spike_et_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh10 = new TH2D("sc_tower_spike_ene_swiss_thresh10","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh12 = new TH2D("sc_tower_spike_et_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh12 = new TH2D("sc_tower_spike_ene_swiss_thresh12","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh15 = new TH2D("sc_tower_spike_et_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh15 = new TH2D("sc_tower_spike_ene_swiss_thresh15","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_et_swiss_thresh20 = new TH2D("sc_tower_spike_et_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); sc_tower_spike_ene_swiss_thresh20 = new TH2D("sc_tower_spike_ene_swiss_thresh20","",100,0.205,1.205,2,-0.5,1.5); strip_prob_et = new TH2D("strip_prob_et","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene = new TH2D("strip_prob_ene","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et = new TH2D("tower_spike_et","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene = new TH2D("tower_spike_ene","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu = new TH3D("strip_prob_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu = new TH3D("strip_prob_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu = new TH3D("tower_spike_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu = new TH3D("tower_spike_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh08 = new TH2D("strip_prob_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh08 = new TH2D("strip_prob_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh08 = new TH2D("tower_spike_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh08 = new TH2D("tower_spike_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh08 = new TH3D("strip_prob_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh08 = new TH3D("strip_prob_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh08 = new TH3D("tower_spike_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh08 = new TH3D("tower_spike_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh10 = new TH2D("strip_prob_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh10 = new TH2D("strip_prob_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh10 = new TH2D("tower_spike_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh10 = new TH2D("tower_spike_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh10 = new TH3D("strip_prob_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh10 = new TH3D("strip_prob_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh10 = new TH3D("tower_spike_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh10 = new TH3D("tower_spike_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh12 = new TH2D("strip_prob_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh12 = new TH2D("strip_prob_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh12 = new TH2D("tower_spike_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh12 = new TH2D("tower_spike_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh12 = new TH3D("strip_prob_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh12 = new TH3D("strip_prob_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh12 = new TH3D("tower_spike_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh12 = new TH3D("tower_spike_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh15 = new TH2D("strip_prob_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh15 = new TH2D("strip_prob_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh15 = new TH2D("tower_spike_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh15 = new TH2D("tower_spike_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh15 = new TH3D("strip_prob_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh15 = new TH3D("strip_prob_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh15 = new TH3D("tower_spike_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh15 = new TH3D("tower_spike_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_thresh20 = new TH2D("strip_prob_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_thresh20 = new TH2D("strip_prob_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_thresh20 = new TH2D("tower_spike_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_thresh20 = new TH2D("tower_spike_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu_thresh20 = new TH3D("strip_prob_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_ene_pu_thresh20 = new TH3D("strip_prob_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_et_pu_thresh20 = new TH3D("tower_spike_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); tower_spike_ene_pu_thresh20 = new TH3D("tower_spike_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); strip_prob_et_mod1 = new TH2D("strip_prob_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod1 = new TH2D("strip_prob_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod1 = new TH2D("tower_spike_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod1 = new TH2D("tower_spike_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod2 = new TH2D("strip_prob_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod2 = new TH2D("strip_prob_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod2 = new TH2D("tower_spike_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod2 = new TH2D("tower_spike_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod3 = new TH2D("strip_prob_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod3 = new TH2D("strip_prob_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod3 = new TH2D("tower_spike_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod3 = new TH2D("tower_spike_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_mod4 = new TH2D("strip_prob_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_mod4 = new TH2D("strip_prob_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_mod4 = new TH2D("tower_spike_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_mod4 = new TH2D("tower_spike_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_300 = new TH2D("strip_prob_et_300","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_300 = new TH2D("strip_prob_ene_300","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_300 = new TH2D("tower_spike_et_300","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_300 = new TH2D("tower_spike_ene_300","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu0 = new TH2D("strip_prob_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu0 = new TH2D("strip_prob_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu0 = new TH2D("tower_spike_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu0 = new TH2D("tower_spike_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu10 = new TH2D("strip_prob_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu10 = new TH2D("strip_prob_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu10 = new TH2D("tower_spike_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu10 = new TH2D("tower_spike_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_et_pu20 = new TH2D("strip_prob_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); strip_prob_ene_pu20 = new TH2D("strip_prob_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_et_pu20 = new TH2D("tower_spike_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); tower_spike_ene_pu20 = new TH2D("tower_spike_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et = new TH2D("sc_strip_prob_et","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene = new TH2D("sc_strip_prob_ene","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et = new TH2D("sc_tower_spike_et","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene = new TH2D("sc_tower_spike_ene","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu = new TH3D("sc_strip_prob_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu = new TH3D("sc_strip_prob_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu = new TH3D("sc_tower_spike_et_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu = new TH3D("sc_tower_spike_ene_pu","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh08 = new TH2D("sc_strip_prob_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh08 = new TH2D("sc_strip_prob_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh08 = new TH2D("sc_tower_spike_et_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh08 = new TH2D("sc_tower_spike_ene_thresh08","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh08 = new TH3D("sc_strip_prob_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh08 = new TH3D("sc_strip_prob_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh08 = new TH3D("sc_tower_spike_et_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh08 = new TH3D("sc_tower_spike_ene_pu_thresh08","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh10 = new TH2D("sc_strip_prob_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh10 = new TH2D("sc_strip_prob_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh10 = new TH2D("sc_tower_spike_et_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh10 = new TH2D("sc_tower_spike_ene_thresh10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh10 = new TH3D("sc_strip_prob_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh10 = new TH3D("sc_strip_prob_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh10 = new TH3D("sc_tower_spike_et_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh10 = new TH3D("sc_tower_spike_ene_pu_thresh10","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh12 = new TH2D("sc_strip_prob_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh12 = new TH2D("sc_strip_prob_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh12 = new TH2D("sc_tower_spike_et_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh12 = new TH2D("sc_tower_spike_ene_thresh12","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh12 = new TH3D("sc_strip_prob_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh12 = new TH3D("sc_strip_prob_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh12 = new TH3D("sc_tower_spike_et_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh12 = new TH3D("sc_tower_spike_ene_pu_thresh12","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh15 = new TH2D("sc_strip_prob_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh15 = new TH2D("sc_strip_prob_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh15 = new TH2D("sc_tower_spike_et_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh15 = new TH2D("sc_tower_spike_ene_thresh15","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh15 = new TH3D("sc_strip_prob_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh15 = new TH3D("sc_strip_prob_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh15 = new TH3D("sc_tower_spike_et_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh15 = new TH3D("sc_tower_spike_ene_pu_thresh15","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_thresh20 = new TH2D("sc_strip_prob_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_thresh20 = new TH2D("sc_strip_prob_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_thresh20 = new TH2D("sc_tower_spike_et_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_thresh20 = new TH2D("sc_tower_spike_ene_thresh20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu_thresh20 = new TH3D("sc_strip_prob_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_ene_pu_thresh20 = new TH3D("sc_strip_prob_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_et_pu_thresh20 = new TH3D("sc_tower_spike_et_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_tower_spike_ene_pu_thresh20 = new TH3D("sc_tower_spike_ene_pu_thresh20","",100,-0.5,1.5,2,-0.5,1.5,20,0.,200.); sc_strip_prob_et_mod1 = new TH2D("sc_strip_prob_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod1 = new TH2D("sc_strip_prob_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod1 = new TH2D("sc_tower_spike_et_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod1 = new TH2D("sc_tower_spike_ene_mod1","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod2 = new TH2D("sc_strip_prob_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod2 = new TH2D("sc_strip_prob_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod2 = new TH2D("sc_tower_spike_et_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod2 = new TH2D("sc_tower_spike_ene_mod2","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod3 = new TH2D("sc_strip_prob_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod3 = new TH2D("sc_strip_prob_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod3 = new TH2D("sc_tower_spike_et_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod3 = new TH2D("sc_tower_spike_ene_mod3","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_mod4 = new TH2D("sc_strip_prob_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_mod4 = new TH2D("sc_strip_prob_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_mod4 = new TH2D("sc_tower_spike_et_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_mod4 = new TH2D("sc_tower_spike_ene_mod4","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_10 = new TH2D("sc_strip_prob_et_300","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_10 = new TH2D("sc_strip_prob_ene_300","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_10 = new TH2D("sc_tower_spike_et_300","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_10 = new TH2D("sc_tower_spike_ene_300","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu0 = new TH2D("sc_strip_prob_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu0 = new TH2D("sc_strip_prob_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu0 = new TH2D("sc_tower_spike_et_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu0 = new TH2D("sc_tower_spike_ene_pu0","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu10 = new TH2D("sc_strip_prob_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu10 = new TH2D("sc_strip_prob_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu10 = new TH2D("sc_tower_spike_et_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu10 = new TH2D("sc_tower_spike_ene_pu10","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_et_pu20 = new TH2D("sc_strip_prob_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_strip_prob_ene_pu20 = new TH2D("sc_strip_prob_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_et_pu20 = new TH2D("sc_tower_spike_et_pu20","",100,-0.5,1.5,2,-0.5,1.5); sc_tower_spike_ene_pu20 = new TH2D("sc_tower_spike_ene_pu20","",100,-0.5,1.5,2,-0.5,1.5); eb_timing_0 = new TH1D("eb_timing_0","",400,-100.,100.); eb_timing_200 = new TH1D("eb_timing_200","",400,-100.,100.); eb_timing_400 = new TH1D("eb_timing_400","",400,-100.,100.); eb_timing_600 = new TH1D("eb_timing_600","",400,-100.,100.); eb_timing_800 = new TH1D("eb_timing_800","",400,-100.,100.); eb_timing_1000 = new TH1D("eb_timing_1000","",400,-100.,100.); eb_timing_2000 = new TH1D("eb_timing_2000","",400,-100.,100.); eb_timing_3000 = new TH1D("eb_timing_3000","",400,-100.,100.); eb_timing_4000 = new TH1D("eb_timing_4000","",400,-100.,100.); eb_timing_5000 = new TH1D("eb_timing_5000","",400,-100.,100.); eb_timing_10000 = new TH1D("eb_timing_10000","",400,-100.,100.); eb_timing_3000_spiketag = new TH1D("eb_timing_3000_spiketag","",400,-100.,100.); eb_timing_4000_spiketag = new TH1D("eb_timing_4000_spiketag","",400,-100.,100.); eb_timing_4000_kweird = new TH1D("eb_timing_4000_kweird","",400,-100.,100.); eb_timing_4000_swisscross = new TH1D("eb_timing_4000_swisscross","",400,-100.,100.); eb_timing_4000_spiketag_kweird = new TH1D("eb_timing_4000_spiketag_kweird","",400,-100.,100.); eb_timing_4000_spiketag_swisscross = new TH1D("eb_timing_4000_spiketag_swisscross","",400,-100.,100.); eb_timing_4000_spiketag_noisedep = new TH1D("eb_timing_4000_spiketag_noisedep","",400,-100.,100.); eb_timing_4000_sctag = new TH1D("eb_timing_4000_sctag","",400,-100.,100.); eb_timing_4000_sctag_kweird = new TH1D("eb_timing_4000_sctag_kweird","",400,-100.,100.); eb_timing_4000_sctag_swisscross = new TH1D("eb_timing_4000_sctag_swisscross","",400,-100.,100.); eb_timing_4000_sctag_noisedep = new TH1D("eb_timing_4000_sctag_noisedep","",400,-100.,100.); e4_over_noise=new TH1D("e4_over_noise","",1000,0,20); e4_over_noise_spiketag=new TH1D("e4_over_noise_spiketag","",1000,0,20); e4_over_noise_sctag=new TH1D("e4_over_noise_sctag","",1000,0,20); eb_timing_10000_spiketag = new TH1D("eb_timing_10000_spiketag","",400,-100.,100.); eb_timing_10000_kweird = new TH1D("eb_timing_10000_kweird","",400,-100.,100.); eb_timing_10000_swisscross = new TH1D("eb_timing_10000_swisscross","",400,-100.,100.); eb_timing_10000_spiketag_kweird = new TH1D("eb_timing_10000_spiketag_kweird","",400,-100.,100.); eb_timing_10000_spiketag_swisscross = new TH1D("eb_timing_10000_spiketag_swisscross","",400,-100.,100.); eb_timing_10000_spiketag_noisedep = new TH1D("eb_timing_10000_spiketag_noisedep","",400,-100.,100.); eb_timing_10000_sctag = new TH1D("eb_timing_10000_sctag","",400,-100.,100.); eb_timing_10000_sctag_kweird = new TH1D("eb_timing_10000_sctag_kweird","",400,-100.,100.); eb_timing_10000_sctag_swisscross = new TH1D("eb_timing_10000_sctag_swisscross","",400,-100.,100.); eb_timing_10000_sctag_noisedep = new TH1D("eb_timing_10000_sctag_noisedep","",400,-100.,100.); spikes_vs_ieta_spiketag_4000 = new TH1D("spikes_vs_ieta_spiketag_4000","",85,0,85); spikes_vs_ieta_spiketag_4000_kweird = new TH1D("spikes_vs_ieta_spiketag_4000_kweird","",85,0,85); spikes_vs_ieta_spiketag_4000_swisscross = new TH1D("spikes_vs_ieta_spiketag_4000_swisscross","",85,0,85); spikes_vs_ieta_spiketag_4000_noisedep = new TH1D("spikes_vs_ieta_spiketag_4000_noisedep","",85,0,85); sc_vs_ieta_sctag_4000 = new TH1D("sc_vs_ieta_sctag_4000","",85,0,85); sc_vs_ieta_sctag_4000_kweird = new TH1D("sc_vs_ieta_sctag_4000_kweird","",85,0,85); sc_vs_ieta_sctag_4000_swisscross = new TH1D("sc_vs_ieta_sctag_4000_swisscross","",85,0,85); sc_vs_ieta_sctag_4000_noisedep = new TH1D("sc_vs_ieta_sctag_4000_noisedep","",85,0,85); spikes_vs_ieta_spiketag_10000 = new TH1D("spikes_vs_ieta_spiketag_10000","",85,0,85); spikes_vs_ieta_spiketag_10000_kweird = new TH1D("spikes_vs_ieta_spiketag_10000_kweird","",85,0,85); spikes_vs_ieta_spiketag_10000_swisscross = new TH1D("spikes_vs_ieta_spiketag_10000_swisscross","",85,0,85); spikes_vs_ieta_spiketag_10000_noisedep = new TH1D("spikes_vs_ieta_spiketag_10000_noisedep","",85,0,85); sc_vs_ieta_sctag_10000 = new TH1D("sc_vs_ieta_sctag_10000","",85,0,85); sc_vs_ieta_sctag_10000_kweird = new TH1D("sc_vs_ieta_sctag_10000_kweird","",85,0,85); sc_vs_ieta_sctag_10000_swisscross = new TH1D("sc_vs_ieta_sctag_10000_swisscross","",85,0,85); sc_vs_ieta_sctag_10000_noisedep = new TH1D("sc_vs_ieta_sctag_10000_noisedep","",85,0,85); swisscross_vs_ieta_spiketag_4000 = new TH2D("swisscross_vs_ieta_spiketag_4000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_4000_kweird = new TH2D("swisscross_vs_ieta_spiketag_4000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_10000 = new TH2D("swisscross_vs_ieta_spiketag_10000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_spiketag_10000_kweird = new TH2D("swisscross_vs_ieta_spiketag_10000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_4000 = new TH2D("swisscross_vs_ieta_sctag_4000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_4000_kweird = new TH2D("swisscross_vs_ieta_sctag_4000_kweird","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_10000 = new TH2D("swisscross_vs_ieta_sctag_10000","",80,0.7,1.1,85,0,85); swisscross_vs_ieta_sctag_10000_kweird = new TH2D("swisscross_vs_ieta_sctag_10000_kweird","",80,0.7,1.1,85,0,85); eb_r4_0 = new TH1D("eb_r4_0","",200,0.2,1.2); eb_r4_200 = new TH1D("eb_r4_200","",200,0.2,1.2); eb_r4_400 = new TH1D("eb_r4_400","",200,0.2,1.2); eb_r4_600 = new TH1D("eb_r4_600","",200,0.2,1.2); eb_r4_800 = new TH1D("eb_r4_800","",200,0.2,1.2); eb_r4_1000 = new TH1D("eb_r4_1000","",200,0.2,1.2); eb_r4_2000 = new TH1D("eb_r4_2000","",200,0.2,1.2); eb_r4_3000 = new TH1D("eb_r4_3000","",200,0.2,1.2); eb_r4_4000 = new TH1D("eb_r4_4000","",200,0.2,1.2); eb_r4_5000 = new TH1D("eb_r4_5000","",200,0.2,1.2); eb_r4_10000 = new TH1D("eb_r4_10000","",200,0.2,1.2); eb_r4_3000_spiketag = new TH1D("eb_r4_3000_spiketag","",200,0.2,1.2); eb_r4_4000_spiketag = new TH1D("eb_r4_4000_spiketag","",200,0.2,1.2); eb_r4_4000_sctag = new TH1D("eb_r4_4000_sctag","",200,0.2,1.2); eb_r4_4000_kweird = new TH1D("eb_r4_4000_kweird","",200,0.2,1.2); eb_r4_4000_swisscross = new TH1D("eb_r4_4000_swisscross","",200,0.2,1.2); eb_r4_10000_spiketag = new TH1D("eb_r4_10000_spiketag","",200,0.2,1.2); eb_r4_10000_sctag = new TH1D("eb_r4_10000_sctag","",200,0.2,1.2); eb_r4_10000_kweird = new TH1D("eb_r4_10000_kweird","",200,0.2,1.2); eb_r4_10000_swisscross = new TH1D("eb_r4_10000_swisscross","",200,0.2,1.2); eb_r6_1000 = new TH1D("eb_r6_1000","",200,0.2,1.2); eb_r6_2000 = new TH1D("eb_r6_2000","",200,0.2,1.2); eb_r6_3000 = new TH1D("eb_r6_3000","",200,0.2,1.2); eb_r6_4000 = new TH1D("eb_r6_4000","",200,0.2,1.2); eb_r6_5000 = new TH1D("eb_r6_5000","",200,0.2,1.2); eb_r6_10000 = new TH1D("eb_r6_10000","",200,0.2,1.2); eb_r4vsr6_3000 = new TH2D("eb_r4vsr6_3000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_4000 = new TH2D("eb_r4vsr6_4000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_5000 = new TH2D("eb_r4vsr6_5000","",100,0.2,1.2,100,0.2,1.2); eb_r4vsr6_10000 = new TH2D("eb_r4vsr6_10000","",100,0.2,1.2,100,0.2,1.2); eb_r6_3000_spiketag = new TH1D("eb_r6_3000_spiketag","",200,0.2,2.2); eb_r6_4000_spiketag = new TH1D("eb_r6_4000_spiketag","",200,0.2,2.2); eb_r6_4000_sctag = new TH1D("eb_r6_4000_spiketag","",200,0.2,2.2); eb_r6_4000_kweird = new TH1D("eb_r6_4000_kweird","",200,0.2,2.2); eb_r6_4000_swisscross = new TH1D("eb_r6_4000_swisscross","",200,0.2,2.2); eb_r6_10000_spiketag = new TH1D("eb_r6_10000_spiketag","",200,0.2,2.2); eb_r6_10000_sctag = new TH1D("eb_r6_10000_sctag","",200,0.2,2.2); eb_r6_10000_kweird = new TH1D("eb_r6_10000_kweird","",200,0.2,2.2); eb_r6_10000_swisscross = new TH1D("eb_r6_10000_swisscross","",200,0.2,2.2); time_4gev_spiketime=new TH1D("time_4gev_spiketime","",200,-100,100); time_10gev_spiketime=new TH1D("time_10gev_spiketime","",200,-100,100); time_4gev_spikekweird=new TH1D("time_4gev_spikekweird","",200,-100,100); time_10gev_spikekweird=new TH1D("time_10gev_spikekweird","",200,-100,100); time_4gev_swisscross=new TH1D("time_4gev_swisscross","",200,-100,100); time_10gev_swisscross=new TH1D("time_10gev_swisscross","",200,-100,100); pu_4gev_spiketime=new TH1D("pu_4gev_spiketime","",100,0,100); pu_10gev_spiketime=new TH1D("pu_10gev_spiketime","",100,0,100); pu_4gev_spikekweird=new TH1D("pu_4gev_spikekweird","",100,0,100); pu_10gev_spikekweird=new TH1D("pu_10gev_spikekweird","",100,0,100); pu_4gev_swisscross=new TH1D("pu_4gev_swisscross","",100,0,100); pu_10gev_swisscross=new TH1D("pu_10gev_swisscross","",100,0,100); ene_4gev_spiketime=new TH1D("ene_4gev_spiketime","",100,0,100); ene_10gev_spiketime=new TH1D("ene_10gev_spiketime","",100,0,100); ene_4gev_spikekweird=new TH1D("ene_4gev_spikekweird","",100,0,100); ene_10gev_spikekweird=new TH1D("ene_10gev_spikekweird","",100,0,100); ene_4gev_swisscross=new TH1D("ene_4gev_swisscross","",100,0,100); ene_10gev_swisscross=new TH1D("ene_10gev_swisscross","",100,0,100); pu_vs_ene_spiketime=new TH2D("pu_vs_ene_spiketime","",50,0,100,50,0,100); pu_vs_ene_spikekweird=new TH2D("pu_vs_ene_spikekweird","",50,0,100,50,0,100); pu_vs_ene_swisscross=new TH2D("pu_vs_ene_swisscross","",50,0,100,50,0,100); eb_timing_r4_0 = new TH1D("eb_timing_r4_0","",400,-100.,100.); eb_timing_r4_200 = new TH1D("eb_timing_r4_200","",400,-100.,100.); eb_timing_r4_400 = new TH1D("eb_timing_r4_400","",400,-100.,100.); eb_timing_r4_600 = new TH1D("eb_timing_r4_600","",400,-100.,100.); eb_timing_r4_800 = new TH1D("eb_timing_r4_800","",400,-100.,100.); eb_timing_r4_1000 = new TH1D("eb_timing_r4_1000","",400,-100.,100.); eb_timing_r4_2000 = new TH1D("eb_timing_r4_2000","",400,-100.,100.); eb_timing_r4_3000 = new TH1D("eb_timing_r4_3000","",400,-100.,100.); eb_timing_r4_5000 = new TH1D("eb_timing_r4_5000","",400,-100.,100.); eb_timing_vs_r4_0 = new TH2D("eb_timing_vs_r4_0","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_200 = new TH2D("eb_timing_vs_r4_200","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_400 = new TH2D("eb_timing_vs_r4_400","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_600 = new TH2D("eb_timing_vs_r4_600","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_800 = new TH2D("eb_timing_vs_r4_800","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_1000 = new TH2D("eb_timing_vs_r4_1000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_2000 = new TH2D("eb_timing_vs_r4_2000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_3000 = new TH2D("eb_timing_vs_r4_3000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_5000 = new TH2D("eb_timing_vs_r4_5000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_10000 = new TH2D("eb_timing_vs_r4_10000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_3000 = new TH2D("eb_timing_vs_r4_sctag_3000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_5000 = new TH2D("eb_timing_vs_r4_sctag_5000","",100,0.2,1.2,200,-100.,100.); eb_timing_vs_r4_sctag_10000 = new TH2D("eb_timing_vs_r4_sctag_10000","",100,0.2,1.2,200,-100.,100.); rechiteta_vs_bxtrain_01 = new TH2D("rechiteta_vs_bxtrain_01","",40,-2,38,60,-3,3); rechiteta_vs_bxtrain_05 = new TH2D("rechiteta_vs_bxtrain_05","",40,-2,38,60,-3,3); sceta_vs_bxtrain = new TH2D("sceta_vs_bxtrain","",40,-2,38,60,-3,3); ebtime_vs_bxtrain_01 = new TH2D("ebtime_vx_bxtrain_01","",40,-2,38,200,-100,100); ebtime_vs_bxtrain_05 = new TH2D("ebtime_vx_bxtrain_05","",40,-2,38,200,-100,100); eetime_vs_bxtrain_01 = new TH2D("eetime_vx_bxtrain_01","",40,-2,38,200,-100,100); eetime_vs_bxtrain_05 = new TH2D("eetime_vx_bxtrain_05","",40,-2,38,200,-100,100); rechiteta_all=new TH1F("rechiteta_all","",100,-3,3); rechiteta_gt1et=new TH1F("rechiteta_gt1et","",100,-3,3); rechiteta_etweight=new TH1F("rechiteta_etweight","",100,-3,3); rechiteta_etweight_gt1et=new TH1F("rechiteta_etweight_gt1et","",100,-3,3); rechiteta_gt1et_pu10=new TH1F("rechiteta_gt1et_pu10","",100,-3,3); rechiteta_gt1et_pu20=new TH1F("rechiteta_gt1et_pu20","",100,-3,3); rechiteta_gt1et_pu30=new TH1F("rechiteta_gt1et_pu30","",100,-3,3); calotowereta_all=new TH1F("calotowereta_all","",100,-3,3); calotowereta_gt1et=new TH1F("calotowereta_gt1et","",100,-3,3); calotowereta_etweight=new TH1F("calotowereta_etweight","",100,-3,3); calotowereta_etweight_gt1et=new TH1F("calotowereta_etweight_gt1et","",100,-3,3); calotowereta_gt1et_pu10=new TH1F("calotowereta_gt1et_pu10","",100,-3,3); calotowereta_gt1et_pu20=new TH1F("calotowereta_gt1et_pu20","",100,-3,3); calotowereta_gt1et_pu30=new TH1F("calotowereta_gt1et_pu30","",100,-3,3); sceta_all=new TH1F("sceta_all","",100,-3,3); sceta_severity0=new TH1F("sceta_severity0","",100,-3,3); sceta_koot0=new TH1F("sceta_koot0","",100,-3,3); sceta_all_gt2=new TH1F("sceta_all_gt2","",100,-3,3); sceta_severity0_gt2=new TH1F("sceta_severity0_gt2","",100,-3,3); sceta_koot0_gt2=new TH1F("sceta_koot0_gt2","",100,-3,3); sceta_all_gt5=new TH1F("sceta_all_gt5","",100,-3,3); sceta_severity0_gt5=new TH1F("sceta_severity0_gt5","",100,-3,3); sceta_koot0_gt5=new TH1F("sceta_koot0_gt5","",100,-3,3); sceta_all_gt10=new TH1F("sceta_all_gt10","",100,-3,3); sceta_severity0_gt10=new TH1F("sceta_severity0_gt10","",100,-3,3); sceta_koot0_gt10=new TH1F("sceta_koot0_gt10","",100,-3,3); sceta_all_pueq01=new TH1F("sceta_all_pueq01","",100,-3,3); sceta_severity0_pueq01=new TH1F("sceta_severity0_pueq01","",100,-3,3); sceta_all_pueq02=new TH1F("sceta_all_pueq02","",100,-3,3); sceta_severity0_pueq02=new TH1F("sceta_severity0_pueq02","",100,-3,3); sceta_all_pueq03=new TH1F("sceta_all_pueq03","",100,-3,3); sceta_severity0_pueq03=new TH1F("sceta_severity0_pueq03","",100,-3,3); sceta_all_pueq04=new TH1F("sceta_all_pueq04","",100,-3,3); sceta_severity0_pueq04=new TH1F("sceta_severity0_pueq04","",100,-3,3); sceta_all_pueq05=new TH1F("sceta_all_pueq05","",100,-3,3); sceta_severity0_pueq05=new TH1F("sceta_severity0_pueq05","",100,-3,3); sceta_all_pueq06=new TH1F("sceta_all_pueq06","",100,-3,3); sceta_severity0_pueq06=new TH1F("sceta_severity0_pueq06","",100,-3,3); sceta_all_pueq07=new TH1F("sceta_all_pueq07","",100,-3,3); sceta_severity0_pueq07=new TH1F("sceta_severity0_pueq07","",100,-3,3); sceta_all_pueq08=new TH1F("sceta_all_pueq08","",100,-3,3); sceta_severity0_pueq08=new TH1F("sceta_severity0_pueq08","",100,-3,3); sceta_all_pueq09=new TH1F("sceta_all_pueq09","",100,-3,3); sceta_severity0_pueq09=new TH1F("sceta_severity0_pueq09","",100,-3,3); scet_eb_all=new TH1F("scet_eb_all","",200,0,100); scet_eb_severity0=new TH1F("scet_eb_severity0","",200,0,100); scet_eb_koot0=new TH1F("scet_eb_koot0","",200,0,100); scet_ee_all=new TH1F("scet_ee_all","",200,0,100); scet_ee_severity0=new TH1F("scet_ee_severity0","",200,0,100); scet_ee_koot0=new TH1F("scet_ee_koot0","",200,0,100); scet_eb_all_eta15=new TH1F("scet_eb_all_eta15","",200,0,100); scet_eb_all_eta20=new TH1F("scet_eb_all_eta20","",200,0,100); scet_eb_all_eta25=new TH1F("scet_eb_all_eta25","",200,0,100); scet_eb_all_eta15_pu10=new TH1F("scet_eb_all_eta15_pu10","",200,0,100); scet_eb_all_eta20_pu10=new TH1F("scet_eb_all_eta20_pu10","",200,0,100); scet_eb_all_eta25_pu10=new TH1F("scet_eb_all_eta25_pu10","",200,0,100); scet_eb_all_eta15_pu20=new TH1F("scet_eb_all_eta15_pu20","",200,0,100); scet_eb_all_eta20_pu20=new TH1F("scet_eb_all_eta20_pu20","",200,0,100); scet_eb_all_eta25_pu20=new TH1F("scet_eb_all_eta25_pu20","",200,0,100); scet_eb_all_eta15_pu30=new TH1F("scet_eb_all_eta15_pu30","",200,0,100); scet_eb_all_eta20_pu30=new TH1F("scet_eb_all_eta20_pu30","",200,0,100); scet_eb_all_eta25_pu30=new TH1F("scet_eb_all_eta25_pu30","",200,0,100); scet_eb_all_eta15_pueq10=new TH1F("scet_eb_all_eta15_pueq10","",200,0,100); scet_eb_all_eta20_pueq10=new TH1F("scet_eb_all_eta20_pueq10","",200,0,100); scet_eb_all_eta25_pueq10=new TH1F("scet_eb_all_eta25_pueq10","",200,0,100); scet_eb_all_eta15_pueq20=new TH1F("scet_eb_all_eta15_pueq20","",200,0,100); scet_eb_all_eta20_pueq20=new TH1F("scet_eb_all_eta20_pueq20","",200,0,100); scet_eb_all_eta25_pueq20=new TH1F("scet_eb_all_eta25_pueq20","",200,0,100); scet_ee_all_eta15=new TH1F("scet_ee_all_eta15","",200,0,100); scet_ee_all_eta20=new TH1F("scet_ee_all_eta20","",200,0,100); scet_ee_all_eta25=new TH1F("scet_ee_all_eta25","",200,0,100); scet_ee_all_eta15_pu10=new TH1F("scet_ee_all_eta15_pu10","",200,0,100); scet_ee_all_eta20_pu10=new TH1F("scet_ee_all_eta20_pu10","",200,0,100); scet_ee_all_eta25_pu10=new TH1F("scet_ee_all_eta25_pu10","",200,0,100); scet_ee_all_eta15_pu20=new TH1F("scet_ee_all_eta15_pu20","",200,0,100); scet_ee_all_eta20_pu20=new TH1F("scet_ee_all_eta20_pu20","",200,0,100); scet_ee_all_eta25_pu20=new TH1F("scet_ee_all_eta25_pu20","",200,0,100); scet_ee_all_eta15_pu30=new TH1F("scet_ee_all_eta15_pu30","",200,0,100); scet_ee_all_eta20_pu30=new TH1F("scet_ee_all_eta20_pu30","",200,0,100); scet_ee_all_eta25_pu30=new TH1F("scet_ee_all_eta25_pu30","",200,0,100); scet_ee_all_eta15_pueq10=new TH1F("scet_ee_all_eta15_pueq10","",200,0,100); scet_ee_all_eta20_pueq10=new TH1F("scet_ee_all_eta20_pueq10","",200,0,100); scet_ee_all_eta25_pueq10=new TH1F("scet_ee_all_eta25_pueq10","",200,0,100); scet_ee_all_eta15_pueq20=new TH1F("scet_ee_all_eta15_pueq20","",200,0,100); scet_ee_all_eta20_pueq20=new TH1F("scet_ee_all_eta20_pueq20","",200,0,100); scet_ee_all_eta25_pueq20=new TH1F("scet_ee_all_eta25_pueq20","",200,0,100); scsumet_eb_all_eta15=new TH1F("scsumet_eb_all_eta15","",200,0,200); scsumet_eb_all_eta20=new TH1F("scsumet_eb_all_eta20","",200,0,200); scsumet_eb_all_eta25=new TH1F("scsumet_eb_all_eta25","",200,0,200); scsumet_eb_all_eta15_pu10=new TH1F("scsumet_eb_all_eta15_pu10","",200,0,200); scsumet_eb_all_eta20_pu10=new TH1F("scsumet_eb_all_eta20_pu10","",200,0,200); scsumet_eb_all_eta25_pu10=new TH1F("scsumet_eb_all_eta25_pu10","",200,0,200); scsumet_eb_all_eta15_pu20=new TH1F("scsumet_eb_all_eta15_pu20","",200,0,200); scsumet_eb_all_eta20_pu20=new TH1F("scsumet_eb_all_eta20_pu20","",200,0,200); scsumet_eb_all_eta25_pu20=new TH1F("scsumet_eb_all_eta25_pu20","",200,0,200); scsumet_eb_all_eta15_pu30=new TH1F("scsumet_eb_all_eta15_pu30","",200,0,200); scsumet_eb_all_eta20_pu30=new TH1F("scsumet_eb_all_eta20_pu30","",200,0,200); scsumet_eb_all_eta25_pu30=new TH1F("scsumet_eb_all_eta25_pu30","",200,0,200); scsumet_eb_all_eta15_pueq10=new TH1F("scsumet_eb_all_eta15_pueq10","",200,0,200); scsumet_eb_all_eta20_pueq10=new TH1F("scsumet_eb_all_eta20_pueq10","",200,0,200); scsumet_eb_all_eta25_pueq10=new TH1F("scsumet_eb_all_eta25_pueq10","",200,0,200); scsumet_eb_all_eta15_pueq20=new TH1F("scsumet_eb_all_eta15_pueq20","",200,0,200); scsumet_eb_all_eta20_pueq20=new TH1F("scsumet_eb_all_eta20_pueq20","",200,0,200); scsumet_eb_all_eta25_pueq20=new TH1F("scsumet_eb_all_eta25_pueq20","",200,0,200); scsumet_ee_all_eta15=new TH1F("scsumet_ee_all_eta15","",200,0,200); scsumet_ee_all_eta20=new TH1F("scsumet_ee_all_eta20","",200,0,200); scsumet_ee_all_eta25=new TH1F("scsumet_ee_all_eta25","",200,0,200); scsumet_ee_all_eta15_pu10=new TH1F("scsumet_ee_all_eta15_pu10","",200,0,200); scsumet_ee_all_eta20_pu10=new TH1F("scsumet_ee_all_eta20_pu10","",200,0,200); scsumet_ee_all_eta25_pu10=new TH1F("scsumet_ee_all_eta25_pu10","",200,0,200); scsumet_ee_all_eta15_pu20=new TH1F("scsumet_ee_all_eta15_pu20","",200,0,200); scsumet_ee_all_eta20_pu20=new TH1F("scsumet_ee_all_eta20_pu20","",200,0,200); scsumet_ee_all_eta25_pu20=new TH1F("scsumet_ee_all_eta25_pu20","",200,0,200); scsumet_ee_all_eta15_pu30=new TH1F("scsumet_ee_all_eta15_pu30","",200,0,200); scsumet_ee_all_eta20_pu30=new TH1F("scsumet_ee_all_eta20_pu30","",200,0,200); scsumet_ee_all_eta25_pu30=new TH1F("scsumet_ee_all_eta25_pu30","",200,0,200); scsumet_ee_all_eta15_pueq10=new TH1F("scsumet_ee_all_eta15_pueq10","",200,0,200); scsumet_ee_all_eta20_pueq10=new TH1F("scsumet_ee_all_eta20_pueq10","",200,0,200); scsumet_ee_all_eta25_pueq10=new TH1F("scsumet_ee_all_eta25_pueq10","",200,0,200); scsumet_ee_all_eta15_pueq20=new TH1F("scsumet_ee_all_eta15_pueq20","",200,0,200); scsumet_ee_all_eta20_pueq20=new TH1F("scsumet_ee_all_eta20_pueq20","",200,0,200); scsumet_ee_all_eta25_pueq20=new TH1F("scsumet_ee_all_eta25_pueq20","",200,0,200); scet_eb_all_eta15_pueq01=new TH1F("scet_eb_all_eta15_pueq01","",200,0,100); scet_eb_all_eta20_pueq01=new TH1F("scet_eb_all_eta20_pueq01","",200,0,100); scet_eb_all_eta25_pueq01=new TH1F("scet_eb_all_eta25_pueq01","",200,0,100); scet_ee_all_eta15_pueq01=new TH1F("scet_ee_all_eta15_pueq01","",200,0,100); scet_ee_all_eta20_pueq01=new TH1F("scet_ee_all_eta20_pueq01","",200,0,100); scet_ee_all_eta25_pueq01=new TH1F("scet_ee_all_eta25_pueq01","",200,0,100); scsumet_eb_all_eta15_pueq01=new TH1F("scsumet_eb_all_eta15_pueq01","",200,0,200); scsumet_eb_all_eta20_pueq01=new TH1F("scsumet_eb_all_eta20_pueq01","",200,0,200); scsumet_eb_all_eta25_pueq01=new TH1F("scsumet_eb_all_eta25_pueq01","",200,0,200); scsumet_ee_all_eta15_pueq01=new TH1F("scsumet_ee_all_eta15_pueq01","",200,0,200); scsumet_ee_all_eta20_pueq01=new TH1F("scsumet_ee_all_eta20_pueq01","",200,0,200); scsumet_ee_all_eta25_pueq01=new TH1F("scsumet_ee_all_eta25_pueq01","",200,0,200); scet_eb_all_eta15_pueq02=new TH1F("scet_eb_all_eta15_pueq02","",200,0,100); scet_eb_all_eta20_pueq02=new TH1F("scet_eb_all_eta20_pueq02","",200,0,100); scet_eb_all_eta25_pueq02=new TH1F("scet_eb_all_eta25_pueq02","",200,0,100); scet_ee_all_eta15_pueq02=new TH1F("scet_ee_all_eta15_pueq02","",200,0,100); scet_ee_all_eta20_pueq02=new TH1F("scet_ee_all_eta20_pueq02","",200,0,100); scet_ee_all_eta25_pueq02=new TH1F("scet_ee_all_eta25_pueq02","",200,0,100); scsumet_eb_all_eta15_pueq02=new TH1F("scsumet_eb_all_eta15_pueq02","",200,0,200); scsumet_eb_all_eta20_pueq02=new TH1F("scsumet_eb_all_eta20_pueq02","",200,0,200); scsumet_eb_all_eta25_pueq02=new TH1F("scsumet_eb_all_eta25_pueq02","",200,0,200); scsumet_ee_all_eta15_pueq02=new TH1F("scsumet_ee_all_eta15_pueq02","",200,0,200); scsumet_ee_all_eta20_pueq02=new TH1F("scsumet_ee_all_eta20_pueq02","",200,0,200); scsumet_ee_all_eta25_pueq02=new TH1F("scsumet_ee_all_eta25_pueq02","",200,0,200); scet_eb_all_eta15_pueq03=new TH1F("scet_eb_all_eta15_pueq03","",200,0,100); scet_eb_all_eta20_pueq03=new TH1F("scet_eb_all_eta20_pueq03","",200,0,100); scet_eb_all_eta25_pueq03=new TH1F("scet_eb_all_eta25_pueq03","",200,0,100); scet_ee_all_eta15_pueq03=new TH1F("scet_ee_all_eta15_pueq03","",200,0,100); scet_ee_all_eta20_pueq03=new TH1F("scet_ee_all_eta20_pueq03","",200,0,100); scet_ee_all_eta25_pueq03=new TH1F("scet_ee_all_eta25_pueq03","",200,0,100); scsumet_eb_all_eta15_pueq03=new TH1F("scsumet_eb_all_eta15_pueq03","",200,0,200); scsumet_eb_all_eta20_pueq03=new TH1F("scsumet_eb_all_eta20_pueq03","",200,0,200); scsumet_eb_all_eta25_pueq03=new TH1F("scsumet_eb_all_eta25_pueq03","",200,0,200); scsumet_ee_all_eta15_pueq03=new TH1F("scsumet_ee_all_eta15_pueq03","",200,0,200); scsumet_ee_all_eta20_pueq03=new TH1F("scsumet_ee_all_eta20_pueq03","",200,0,200); scsumet_ee_all_eta25_pueq03=new TH1F("scsumet_ee_all_eta25_pueq03","",200,0,200); scet_eb_all_eta15_pueq04=new TH1F("scet_eb_all_eta15_pueq04","",200,0,100); scet_eb_all_eta20_pueq04=new TH1F("scet_eb_all_eta20_pueq04","",200,0,100); scet_eb_all_eta25_pueq04=new TH1F("scet_eb_all_eta25_pueq04","",200,0,100); scet_ee_all_eta15_pueq04=new TH1F("scet_ee_all_eta15_pueq04","",200,0,100); scet_ee_all_eta20_pueq04=new TH1F("scet_ee_all_eta20_pueq04","",200,0,100); scet_ee_all_eta25_pueq04=new TH1F("scet_ee_all_eta25_pueq04","",200,0,100); scsumet_eb_all_eta15_pueq04=new TH1F("scsumet_eb_all_eta15_pueq04","",200,0,200); scsumet_eb_all_eta20_pueq04=new TH1F("scsumet_eb_all_eta20_pueq04","",200,0,200); scsumet_eb_all_eta25_pueq04=new TH1F("scsumet_eb_all_eta25_pueq04","",200,0,200); scsumet_ee_all_eta15_pueq04=new TH1F("scsumet_ee_all_eta15_pueq04","",200,0,200); scsumet_ee_all_eta20_pueq04=new TH1F("scsumet_ee_all_eta20_pueq04","",200,0,200); scsumet_ee_all_eta25_pueq04=new TH1F("scsumet_ee_all_eta25_pueq04","",200,0,200); scet_eb_all_eta15_pueq05=new TH1F("scet_eb_all_eta15_pueq05","",200,0,100); scet_eb_all_eta20_pueq05=new TH1F("scet_eb_all_eta20_pueq05","",200,0,100); scet_eb_all_eta25_pueq05=new TH1F("scet_eb_all_eta25_pueq05","",200,0,100); scet_ee_all_eta15_pueq05=new TH1F("scet_ee_all_eta15_pueq05","",200,0,100); scet_ee_all_eta20_pueq05=new TH1F("scet_ee_all_eta20_pueq05","",200,0,100); scet_ee_all_eta25_pueq05=new TH1F("scet_ee_all_eta25_pueq05","",200,0,100); scsumet_eb_all_eta15_pueq05=new TH1F("scsumet_eb_all_eta15_pueq05","",200,0,200); scsumet_eb_all_eta20_pueq05=new TH1F("scsumet_eb_all_eta20_pueq05","",200,0,200); scsumet_eb_all_eta25_pueq05=new TH1F("scsumet_eb_all_eta25_pueq05","",200,0,200); scsumet_ee_all_eta15_pueq05=new TH1F("scsumet_ee_all_eta15_pueq05","",200,0,200); scsumet_ee_all_eta20_pueq05=new TH1F("scsumet_ee_all_eta20_pueq05","",200,0,200); scsumet_ee_all_eta25_pueq05=new TH1F("scsumet_ee_all_eta25_pueq05","",200,0,200); scet_eb_all_eta15_pueq06=new TH1F("scet_eb_all_eta15_pueq06","",200,0,100); scet_eb_all_eta20_pueq06=new TH1F("scet_eb_all_eta20_pueq06","",200,0,100); scet_eb_all_eta25_pueq06=new TH1F("scet_eb_all_eta25_pueq06","",200,0,100); scet_ee_all_eta15_pueq06=new TH1F("scet_ee_all_eta15_pueq06","",200,0,100); scet_ee_all_eta20_pueq06=new TH1F("scet_ee_all_eta20_pueq06","",200,0,100); scet_ee_all_eta25_pueq06=new TH1F("scet_ee_all_eta25_pueq06","",200,0,100); scsumet_eb_all_eta15_pueq06=new TH1F("scsumet_eb_all_eta15_pueq06","",200,0,200); scsumet_eb_all_eta20_pueq06=new TH1F("scsumet_eb_all_eta20_pueq06","",200,0,200); scsumet_eb_all_eta25_pueq06=new TH1F("scsumet_eb_all_eta25_pueq06","",200,0,200); scsumet_ee_all_eta15_pueq06=new TH1F("scsumet_ee_all_eta15_pueq06","",200,0,200); scsumet_ee_all_eta20_pueq06=new TH1F("scsumet_ee_all_eta20_pueq06","",200,0,200); scsumet_ee_all_eta25_pueq06=new TH1F("scsumet_ee_all_eta25_pueq06","",200,0,200); scet_eb_all_eta15_pueq07=new TH1F("scet_eb_all_eta15_pueq07","",200,0,100); scet_eb_all_eta20_pueq07=new TH1F("scet_eb_all_eta20_pueq07","",200,0,100); scet_eb_all_eta25_pueq07=new TH1F("scet_eb_all_eta25_pueq07","",200,0,100); scet_ee_all_eta15_pueq07=new TH1F("scet_ee_all_eta15_pueq07","",200,0,100); scet_ee_all_eta20_pueq07=new TH1F("scet_ee_all_eta20_pueq07","",200,0,100); scet_ee_all_eta25_pueq07=new TH1F("scet_ee_all_eta25_pueq07","",200,0,100); scsumet_eb_all_eta15_pueq07=new TH1F("scsumet_eb_all_eta15_pueq07","",200,0,200); scsumet_eb_all_eta20_pueq07=new TH1F("scsumet_eb_all_eta20_pueq07","",200,0,200); scsumet_eb_all_eta25_pueq07=new TH1F("scsumet_eb_all_eta25_pueq07","",200,0,200); scsumet_ee_all_eta15_pueq07=new TH1F("scsumet_ee_all_eta15_pueq07","",200,0,200); scsumet_ee_all_eta20_pueq07=new TH1F("scsumet_ee_all_eta20_pueq07","",200,0,200); scsumet_ee_all_eta25_pueq07=new TH1F("scsumet_ee_all_eta25_pueq07","",200,0,200); scet_eb_all_eta15_pueq08=new TH1F("scet_eb_all_eta15_pueq08","",200,0,100); scet_eb_all_eta20_pueq08=new TH1F("scet_eb_all_eta20_pueq08","",200,0,100); scet_eb_all_eta25_pueq08=new TH1F("scet_eb_all_eta25_pueq08","",200,0,100); scet_ee_all_eta15_pueq08=new TH1F("scet_ee_all_eta15_pueq08","",200,0,100); scet_ee_all_eta20_pueq08=new TH1F("scet_ee_all_eta20_pueq08","",200,0,100); scet_ee_all_eta25_pueq08=new TH1F("scet_ee_all_eta25_pueq08","",200,0,100); scsumet_eb_all_eta15_pueq08=new TH1F("scsumet_eb_all_eta15_pueq08","",200,0,200); scsumet_eb_all_eta20_pueq08=new TH1F("scsumet_eb_all_eta20_pueq08","",200,0,200); scsumet_eb_all_eta25_pueq08=new TH1F("scsumet_eb_all_eta25_pueq08","",200,0,200); scsumet_ee_all_eta15_pueq08=new TH1F("scsumet_ee_all_eta15_pueq08","",200,0,200); scsumet_ee_all_eta20_pueq08=new TH1F("scsumet_ee_all_eta20_pueq08","",200,0,200); scsumet_ee_all_eta25_pueq08=new TH1F("scsumet_ee_all_eta25_pueq08","",200,0,200); scet_eb_all_eta15_pueq09=new TH1F("scet_eb_all_eta15_pueq09","",200,0,100); scet_eb_all_eta20_pueq09=new TH1F("scet_eb_all_eta20_pueq09","",200,0,100); scet_eb_all_eta25_pueq09=new TH1F("scet_eb_all_eta25_pueq09","",200,0,100); scet_ee_all_eta15_pueq09=new TH1F("scet_ee_all_eta15_pueq09","",200,0,100); scet_ee_all_eta20_pueq09=new TH1F("scet_ee_all_eta20_pueq09","",200,0,100); scet_ee_all_eta25_pueq09=new TH1F("scet_ee_all_eta25_pueq09","",200,0,100); scsumet_eb_all_eta15_pueq09=new TH1F("scsumet_eb_all_eta15_pueq09","",200,0,200); scsumet_eb_all_eta20_pueq09=new TH1F("scsumet_eb_all_eta20_pueq09","",200,0,200); scsumet_eb_all_eta25_pueq09=new TH1F("scsumet_eb_all_eta25_pueq09","",200,0,200); scsumet_ee_all_eta15_pueq09=new TH1F("scsumet_ee_all_eta15_pueq09","",200,0,200); scsumet_ee_all_eta20_pueq09=new TH1F("scsumet_ee_all_eta20_pueq09","",200,0,200); scsumet_ee_all_eta25_pueq09=new TH1F("scsumet_ee_all_eta25_pueq09","",200,0,200); scsumet_eb_all=new TH1F("scsumet_eb_all","",200,0,200); scsumet_eb_severity0=new TH1F("scsumet_eb_severity0","",200,0,200); scsumet_eb_koot0=new TH1F("scsumet_eb_koot0","",200,0,200); scsumet_ee_all=new TH1F("scsumet_ee_all","",200,0,200); scsumet_ee_severity0=new TH1F("scsumet_ee_severity0","",200,0,200); scsumet_ee_koot0=new TH1F("scsumet_ee_koot0","",200,0,200); scsumet_eb_all_gt2=new TH1F("scsumet_eb_all_gt2","",200,0,200); scsumet_eb_severity0_gt2=new TH1F("scsumet_eb_severity0_gt2","",200,0,200); scsumet_eb_koot0_gt2=new TH1F("scsumet_eb_koot0_gt2","",200,0,200); scsumet_ee_all_gt2=new TH1F("scsumet_ee_all_gt2","",200,0,200); scsumet_ee_severity0_gt2=new TH1F("scsumet_ee_severity0_gt2","",200,0,200); scsumet_ee_koot0_gt2=new TH1F("scsumet_ee_koot0_gt2","",200,0,200); scsumet_eb_all_gt5=new TH1F("scsumet_eb_all_gt5","",200,0,200); scsumet_eb_severity0_gt5=new TH1F("scsumet_eb_severity0_gt5","",200,0,200); scsumet_eb_koot0_gt5=new TH1F("scsumet_eb_koot0_gt5","",200,0,200); scsumet_ee_all_gt5=new TH1F("scsumet_ee_all_gt5","",200,0,200); scsumet_ee_severity0_gt5=new TH1F("scsumet_ee_severity0_gt5","",200,0,200); scsumet_ee_koot0_gt5=new TH1F("scsumet_ee_koot0_gt5","",200,0,200); scsumet_eb_all_gt10=new TH1F("scsumet_eb_all_gt10","",200,0,200); scsumet_eb_severity0_gt10=new TH1F("scsumet_eb_severity0_gt10","",200,0,200); scsumet_eb_koot0_gt10=new TH1F("scsumet_eb_koot0_gt10","",200,0,200); scsumet_ee_all_gt10=new TH1F("scsumet_ee_all_gt10","",200,0,200); scsumet_ee_severity0_gt10=new TH1F("scsumet_ee_severity0_gt10","",200,0,200); scsumet_ee_koot0_gt10=new TH1F("scsumet_ee_koot0_gt10","",200,0,200); swisscross_vs_energy_spiketag=new TH2D("swisscross_vs_energy_spiketag","",80,0.7,1.1,100,0,20); swisscross_vs_energy_sctag=new TH2D("swisscross_vs_energy_sctag","",80,0.7,1.1,100,0,20); swisscross_vs_energy_spiketag_kweird=new TH2D("swisscross_vs_energy_spiketag_kweird","",80,0.7,1.1,100,0,20); swisscross_vs_energy_sctag_kweird=new TH2D("swisscross_vs_energy_sctag_kweird","",80,0.7,1.1,100,0,20); time_vs_energy_spiketag=new TH2D("time_vs_energy_spiketag","",120,-60,60,100,0,20); time_vs_energy_sctag=new TH2D("time_vs_energy_sctag","",120,-60,60,100,0,20); time_vs_energy_spiketag_kweird=new TH2D("time_vs_energy_spiketag_kweird","",120,-60,60,100,0,20); time_vs_energy_spiketag_swisscross=new TH2D("time_vs_energy_spiketag_swisscross","",120,-60,60,100,0,20); time_vs_energy_sctag_kweird=new TH2D("time_vs_energy_sctag_kweird","",120,-60,60,100,0,20); time_vs_energy_sctag_swisscross=new TH2D("time_vs_energy_sctag_swisscross","",120,-60,60,100,0,20); eb_digi_01=new TH2D("eb_digi_01","",10,0,10,1000,0,1000); ee_digi_01=new TH2D("ee_digi_01","",10,0,10,1000,0,1000); eb_digi_05=new TH2D("eb_digi_05","",10,0,10,1000,0,1000); ee_digi_05=new TH2D("ee_digi_05","",10,0,10,1000,0,1000); eb_digi_30=new TH2D("eb_digi_30","",10,0,10,1000,0,1000); ee_digi_30=new TH2D("ee_digi_30","",10,0,10,1000,0,1000); eb_digi_0105=new TH2D("eb_digi_0105","",10,0,10,100,190,290); ee_digi_0105=new TH2D("ee_digi_0105","",10,0,10,100,190,290); eb_digi_0530=new TH2D("eb_digi_0530","",10,0,10,200,190,390); ee_digi_0530=new TH2D("ee_digi_0530","",10,0,10,200,190,390); eb_digi_0105_vs_time=new TH2D("eb_digi_0105_vs_time","",120,-60,60,10,0,10); ee_digi_0105_vs_time=new TH2D("ee_digi_0105_vs_time","",120,-60,60,10,0,10); eb_digi_0530_vs_time=new TH2D("eb_digi_0530_vs_time","",120,-60,60,10,0,10); ee_digi_0530_vs_time=new TH2D("ee_digi_0530_vs_time","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm=new TH2D("eb_digi_0105_vs_time_norm","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm=new TH2D("ee_digi_0105_vs_time_norm","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm=new TH2D("eb_digi_0530_vs_time_norm","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm=new TH2D("ee_digi_0530_vs_time_norm","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain=new TH2D("eb_digi_0105_vs_bxtrain","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain=new TH2D("ee_digi_0105_vs_bxtrain","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain=new TH2D("eb_digi_0530_vs_bxtrain","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain=new TH2D("ee_digi_0530_vs_bxtrain","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm=new TH2D("eb_digi_0105_vs_bxtrain_norm","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm=new TH2D("ee_digi_0105_vs_bxtrain_norm","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm=new TH2D("eb_digi_0530_vs_bxtrain_norm","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm=new TH2D("ee_digi_0530_vs_bxtrain_norm","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta15=new TH2D("eb_digi_0105_vs_time_eta15","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta15=new TH2D("ee_digi_0105_vs_time_eta15","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta15=new TH2D("eb_digi_0530_vs_time_eta15","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta15=new TH2D("ee_digi_0530_vs_time_eta15","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta15=new TH2D("eb_digi_0105_vs_time_norm_eta15","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta15=new TH2D("ee_digi_0105_vs_time_norm_eta15","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta15=new TH2D("eb_digi_0530_vs_time_norm_eta15","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta15=new TH2D("ee_digi_0530_vs_time_norm_eta15","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta15=new TH2D("eb_digi_0105_vs_bxtrain_eta15","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta15=new TH2D("ee_digi_0105_vs_bxtrain_eta15","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta15=new TH2D("eb_digi_0530_vs_bxtrain_eta15","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta15=new TH2D("ee_digi_0530_vs_bxtrain_eta15","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta15=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta15=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta15=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta15=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta15","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta20=new TH2D("eb_digi_0105_vs_time_eta20","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta20=new TH2D("ee_digi_0105_vs_time_eta20","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta20=new TH2D("eb_digi_0530_vs_time_eta20","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta20=new TH2D("ee_digi_0530_vs_time_eta20","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta20=new TH2D("eb_digi_0105_vs_time_norm_eta20","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta20=new TH2D("ee_digi_0105_vs_time_norm_eta20","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta20=new TH2D("eb_digi_0530_vs_time_norm_eta20","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta20=new TH2D("ee_digi_0530_vs_time_norm_eta20","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta20=new TH2D("eb_digi_0105_vs_bxtrain_eta20","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta20=new TH2D("ee_digi_0105_vs_bxtrain_eta20","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta20=new TH2D("eb_digi_0530_vs_bxtrain_eta20","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta20=new TH2D("ee_digi_0530_vs_bxtrain_eta20","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta20=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta20=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta20=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta20=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta20","",40,-2,38,10,0,10); eb_digi_0105_vs_time_eta25=new TH2D("eb_digi_0105_vs_time_eta25","",120,-60,60,10,0,10); ee_digi_0105_vs_time_eta25=new TH2D("ee_digi_0105_vs_time_eta25","",120,-60,60,10,0,10); eb_digi_0530_vs_time_eta25=new TH2D("eb_digi_0530_vs_time_eta25","",120,-60,60,10,0,10); ee_digi_0530_vs_time_eta25=new TH2D("ee_digi_0530_vs_time_eta25","",120,-60,60,10,0,10); eb_digi_0105_vs_time_norm_eta25=new TH2D("eb_digi_0105_vs_time_norm_eta25","",120,-60,60,10,0,10); ee_digi_0105_vs_time_norm_eta25=new TH2D("ee_digi_0105_vs_time_norm_eta25","",120,-60,60,10,0,10); eb_digi_0530_vs_time_norm_eta25=new TH2D("eb_digi_0530_vs_time_norm_eta25","",120,-60,60,10,0,10); ee_digi_0530_vs_time_norm_eta25=new TH2D("ee_digi_0530_vs_time_norm_eta25","",120,-60,60,10,0,10); eb_digi_0105_vs_bxtrain_eta25=new TH2D("eb_digi_0105_vs_bxtrain_eta25","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_eta25=new TH2D("ee_digi_0105_vs_bxtrain_eta25","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_eta25=new TH2D("eb_digi_0530_vs_bxtrain_eta25","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_eta25=new TH2D("ee_digi_0530_vs_bxtrain_eta25","",40,-2,38,10,0,10); eb_digi_0105_vs_bxtrain_norm_eta25=new TH2D("eb_digi_0105_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); ee_digi_0105_vs_bxtrain_norm_eta25=new TH2D("ee_digi_0105_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); eb_digi_0530_vs_bxtrain_norm_eta25=new TH2D("eb_digi_0530_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); ee_digi_0530_vs_bxtrain_norm_eta25=new TH2D("ee_digi_0530_vs_bxtrain_norm_eta25","",40,-2,38,10,0,10); ebchstatus=new TH2D("ebchstatus","",360,0,360,170,-85,85); eechstatus=new TH2D("eechstatus","",200,0,200,100,0,100); ebpedmean_g12=new TH2D("ebpedmean_g12","",360,0,360,170,-85,85); ebpedmean_g6=new TH2D("ebpedmean_g6","",360,0,360,170,-85,85); ebpedmean_g1=new TH2D("ebpedmean_g1","",360,0,360,170,-85,85); ebpedrms_g12=new TH2D("ebpedrms_g12","",360,0,360,170,-85,85); ebpedrms_g6=new TH2D("ebpedrms_g6","",360,0,360,170,-85,85); ebpedrms_g1=new TH2D("ebpedrms_g1","",360,0,360,170,-85,85); eepedmean_g12=new TH2D("eepedmean_g12","",200,0,200,100,0,100); eepedmean_g6=new TH2D("eepedmean_g6","",200,0,200,100,0,100); eepedmean_g1=new TH2D("eepedmean_g1","",200,0,200,100,0,100); eepedrms_g12=new TH2D("eepedrms_g12","",200,0,200,100,0,100); eepedrms_g6=new TH2D("eepedrms_g6","",200,0,200,100,0,100); eepedrms_g1=new TH2D("eepedrms_g1","",200,0,200,100,0,100); dataTree_ = new TTree("dataTree","dataTree"); // physics declared and technical trigger bits dataTree_->Branch("physdeclared",&physdeclared,"physdeclared/I"); dataTree_->Branch("bit36", &bit36, "bit36/I"); dataTree_->Branch("bit37", &bit37, "bit37/I"); dataTree_->Branch("bit38", &bit38, "bit38/I"); dataTree_->Branch("bit39", &bit39, "bit39/I"); dataTree_->Branch("bit40", &bit40, "bit40/I"); dataTree_->Branch("bit41", &bit41, "bit41/I"); dataTree_->Branch("bit3", &bit3, "bit3/I"); dataTree_->Branch("bit4", &bit4, "bit4/I"); dataTree_->Branch("bit9", &bit9, "bit9/I"); dataTree_->Branch("bit0", &bit0, "bit0/I"); dataTree_->Branch("eg1", &eg1, "eg1/I"); dataTree_->Branch("eg2", &eg2, "eg2/I"); dataTree_->Branch("eg5", &eg5, "eg5/I"); dataTree_->Branch("algo124", &algo124, "algo124/I"); // muon triggers dataTree_->Branch("algo54", &algo54, "algo54/I"); dataTree_->Branch("algo55", &algo55, "algo55/I"); dataTree_->Branch("algo56", &algo56, "algo56/I"); dataTree_->Branch("algo57", &algo57, "algo57/I"); dataTree_->Branch("algo58", &algo58, "algo58/I"); dataTree_->Branch("algo59", &algo59, "algo59/I"); dataTree_->Branch("algo60", &algo60, "algo60/I"); dataTree_->Branch("algo61", &algo61, "algo61/I"); dataTree_->Branch("algo62", &algo62, "algo62/I"); dataTree_->Branch("algo106", &algo106, "algo106/I"); dataTree_->Branch("algo107", &algo107, "algo107/I"); // run/event info dataTree_->Branch("run", &run, "run/I"); dataTree_->Branch("even", &even, "even/I"); dataTree_->Branch("lumi", &lumi, "lumi/I"); dataTree_->Branch("bx", &bx, "bx/I"); dataTree_->Branch("orbit", &orbit, "orbit/I"); dataTree_->Branch("time", &time, "time/F"); // tracks - for monster event cut dataTree_->Branch("ntrk", &ntrk, "ntrk/I"); dataTree_->Branch("goodtrk", &goodtrk, "goodtrk/I"); // primary vertex info dataTree_->Branch("numvtx", &numvtx, "numvtx/I"); dataTree_->Branch("numgoodvtx", &numgoodvtx, "numgoodvtx/I"); dataTree_->Branch("vtx_x", &vtx_x, "vtx_x/F"); dataTree_->Branch("vtx_y", &vtx_y, "vtx_y/F"); dataTree_->Branch("vtx_z", &vtx_z, "vtx_z/F"); dataTree_->Branch("vtx_x_err", &vtx_x_err, "vtx_x_err/F"); dataTree_->Branch("vtx_y_err", &vtx_y_err, "vtx_y_err/F"); dataTree_->Branch("vtx_z_err", &vtx_z_err, "vtx_z_err/F"); dataTree_->Branch("vtx_chi2", &vtx_chi2, "vtx_chi2/F"); dataTree_->Branch("vtx_ndof", &vtx_ndof, "vtx_ndof/F"); dataTree_->Branch("vtx_ntracks", &vtx_ntracks, "vtx_ntracks/I"); dataTree_->Branch("vtx_isfake", &vtx_isfake, "vtx_isfake/I"); dataTree_->Branch("vtx_good", &vtx_good, "vtx_good/I"); dataTree_->Branch("scale", &scale, "scale/F"); dataTree_->Branch("ebmax", &ebmax, "ebmax/F"); dataTree_->Branch("ebmaxet", &ebmaxet, "ebmaxet/F"); dataTree_->Branch("ebtime", &ebtime, "ebtime/F"); dataTree_->Branch("ebflags", &ebflags, "ebflags/I"); dataTree_->Branch("eb_ieta", &eb_ieta, "eb_ieta/I"); dataTree_->Branch("eb_iphi", &eb_iphi, "eb_iphi/I"); dataTree_->Branch("eb_eta", &eb_eta, "eb_eta/F"); dataTree_->Branch("eb_phi", &eb_phi, "eb_phi/F"); dataTree_->Branch("ebhits", &ebhits, "ebhits/I"); dataTree_->Branch("ebhits1GeV", &ebhits1GeV, "ebhits1GeV/I"); dataTree_->Branch("ebhits2GeV", &ebhits2GeV, "ebhits2GeV/I"); dataTree_->Branch("ebhits4GeV", &ebhits4GeV, "ebhits4GeV/I"); dataTree_->Branch("ebhits1GeVet", &ebhits1GeVet, "ebhits1GeVet/I"); dataTree_->Branch("ebhits2GeVet", &ebhits2GeVet, "ebhits2GeVet/I"); dataTree_->Branch("ebhits4GeVet", &ebhits4GeVet, "ebhits4GeVet/I"); dataTree_->Branch("eb_r9", &eb_r9, "eb_r9/F"); dataTree_->Branch("eb_r4", &eb_r4, "eb_r4/F"); dataTree_->Branch("eb_e9", &eb_e9, "eb_e9/F"); dataTree_->Branch("eb_e25", &eb_e25, "eb_e25/F"); dataTree_->Branch("ebmax2", &ebmax2, "ebmax2/F"); dataTree_->Branch("ebmaxet2", &ebmaxet2, "ebmaxet2/F"); dataTree_->Branch("ebtime2", &ebtime2, "ebtime2/F"); dataTree_->Branch("ebflags2", &ebflags2, "ebflags2/I"); dataTree_->Branch("eb_ieta2", &eb_ieta2, "eb_ieta2/I"); dataTree_->Branch("eb_iphi2", &eb_iphi2, "eb_iphi2/I"); dataTree_->Branch("eb_eta2", &eb_eta2, "eb_eta2/F"); dataTree_->Branch("eb_phi2", &eb_phi2, "eb_phi2/F"); dataTree_->Branch("ebhits1GeV2", &ebhits1GeV2, "ebhits1GeV2/I"); dataTree_->Branch("eb_r92", &eb_r92, "eb_r92/F"); dataTree_->Branch("eb_r42", &eb_r42, "eb_r42/F"); dataTree_->Branch("ebchi2", &ebchi2, "ebchi2/F"); dataTree_->Branch("ebchi2oot", &ebchi2oot, "ebchi2oot/F"); dataTree_->Branch("eb2chi2", &eb2chi2, "eb2chi2/F"); dataTree_->Branch("eb2chi2oot", &eb2chi2oot, "eb2chi2oot/F"); dataTree_->Branch("ebsum_gt1", &ebsum_gt1, "ebsum_gt1/F"); dataTree_->Branch("ebsum_gt2", &ebsum_gt2, "ebsum_gt2/F"); dataTree_->Branch("ebsum_gt4", &ebsum_gt4, "ebsum_gt4/F"); dataTree_->Branch("ebsum_gt1et", &ebsum_gt1et, "ebsum_gt1et/F"); dataTree_->Branch("ebsum_gt2et", &ebsum_gt2et, "ebsum_gt2et/F"); dataTree_->Branch("ebsum_gt4et", &ebsum_gt4et, "ebsum_gt4et/F"); dataTree_->Branch("eesum_gt1", &eesum_gt1, "eesum_gt1/F"); dataTree_->Branch("eesum_gt2", &eesum_gt2, "eesum_gt2/F"); dataTree_->Branch("eesum_gt4", &eesum_gt4, "eesum_gt4/F"); dataTree_->Branch("eesum_gt1et", &eesum_gt1et, "eesum_gt1et/F"); dataTree_->Branch("eesum_gt2et", &eesum_gt2et, "eesum_gt2et/F"); dataTree_->Branch("eesum_gt4et", &eesum_gt4et, "eesum_gt4et/F"); dataTree_->Branch("ebflag_kgood", &ebflag_kgood, "ebflag_kgood/I"); dataTree_->Branch("ebflag_kpoorreco", &ebflag_kpoorreco, "ebflag_kpoorreco/I"); dataTree_->Branch("ebflag_koutoftime", &ebflag_koutoftime, "ebflag_koutoftime/I"); dataTree_->Branch("ebflag_kfake", &ebflag_kfake, "ebflag_kfake/I"); dataTree_->Branch("eemax", &eemax, "eemax/F"); dataTree_->Branch("eemaxet", &eemaxet, "eemaxet/F"); dataTree_->Branch("eetime", &eetime, "eetime/F"); dataTree_->Branch("eeflags", &eeflags, "eeflags/I"); dataTree_->Branch("eeix", &eeix, "eeix/I"); dataTree_->Branch("eeiy", &eeiy, "eeiy/I"); dataTree_->Branch("eeiz", &eeiz, "eeiz/I"); dataTree_->Branch("ee_eta", &ee_eta, "ee_eta/F"); dataTree_->Branch("ee_phi", &ee_phi, "ee_phi/F"); dataTree_->Branch("eehits", &eehits, "eehits/I"); dataTree_->Branch("eehits1GeV", &eehits1GeV, "eehits1GeV/I"); dataTree_->Branch("eehits2GeV", &eehits2GeV, "eehits2GeV/I"); dataTree_->Branch("eehits4GeV", &eehits4GeV, "eehits4GeV/I"); dataTree_->Branch("eehits1GeVet", &eehits1GeVet, "eehits1GeVet/I"); dataTree_->Branch("eehits2GeVet", &eehits2GeVet, "eehits2GeVet/I"); dataTree_->Branch("eehits4GeVet", &eehits4GeVet, "eehits4GeVet/I"); dataTree_->Branch("ee_r9", &ee_r9, "ee_r9/F"); dataTree_->Branch("eephits", &eephits, "eephits/I"); dataTree_->Branch("eemhits", &eemhits, "eemhits/I"); dataTree_->Branch("eemax2", &eemax2, "eemax2/F"); dataTree_->Branch("eemaxet2", &eemaxet2, "eemaxet2/F"); dataTree_->Branch("eetime2", &eetime2, "eetime2/F"); dataTree_->Branch("eeflags2", &eeflags2, "eeflags2/I"); dataTree_->Branch("eeix2", &eeix2, "eeix2/I"); dataTree_->Branch("eeiy2", &eeiy2, "eeiy2/I"); dataTree_->Branch("eeiz2", &eeiz2, "eeiz2/I"); dataTree_->Branch("ee_eta2", &ee_eta2, "ee_eta2/F"); dataTree_->Branch("ee_phi2", &ee_phi2, "ee_phi2/F"); dataTree_->Branch("eehits1GeV2", &eehits1GeV2, "eehits1GeV2/I"); dataTree_->Branch("ee_r92", &ee_r92, "ee_r92/F"); dataTree_->Branch("tmean_en", &tmean_en, "tmean_en/F"); dataTree_->Branch("terr_en", &terr_en, "terr_en/F"); dataTree_->Branch("tmean_sig", &tmean_sig, "tmean_sig/F"); dataTree_->Branch("terr_sig", &terr_sig, "terr_sig/F"); dataTree_->Branch("r4count", &r4count, "r4count/I"); dataTree_->Branch("e2e9count_thresh0", &e2e9count_thresh0, "e2e9count_thresh0/I"); dataTree_->Branch("e2e25count_thresh0", &e2e25count_thresh0, "e2e25count_thresh0/I"); dataTree_->Branch("e2e9count_thresh1", &e2e9count_thresh1, "e2e9count_thresh1/I"); dataTree_->Branch("e2e25count_thresh1", &e2e25count_thresh1, "e2e25count_thresh1/I"); dataTree_->Branch("e2e9count_thresh0_nor4", &e2e9count_thresh0_nor4, "e2e9count_thresh0_nor4/I"); dataTree_->Branch("e2e25count_thresh0_nor4", &e2e25count_thresh0_nor4, "e2e25count_thresh0_nor4/I"); dataTree_->Branch("e2e9count_thresh1_nor4", &e2e9count_thresh1_nor4, "e2e9count_thresh1_nor4/I"); dataTree_->Branch("e2e25count_thresh1_nor4", &e2e25count_thresh1_nor4, "e2e25count_thresh1_nor4/I"); dataTree_->Branch("r4_algo_count", &r4_algo_count, "r4_algo_count/I"); dataTree_->Branch("e2e9_algo_count", &e2e9_algo_count, "e2e9_algo_count/I"); dataTree_->Branch("e2e9_algo_count_5_1", &e2e9_algo_count_5_1, "e2e9_algo_count_5_1/I"); dataTree_->Branch("e2e9_algo_count_5_0", &e2e9_algo_count_5_0, "e2e9_algo_count_5_0/I"); dataTree_->Branch("swisscross_algo", &swisscross_algo, "swisscross_algo/F"); dataTree_->Branch("e2e9_algo", &e2e9_algo, "e2e9_algo/F"); // calotowers dataTree_->Branch("ncalotower", &ncalotower, "ncalotower/I"); dataTree_->Branch("ncalotowereb", &ncalotowereb,"ncalotowereb/I"); dataTree_->Branch("ncalotoweree", &ncalotoweree,"ncalotoweree/I"); dataTree_->Branch("ncalotowerhf", &ncalotowerhf,"ncalotowerhf/I"); dataTree_->Branch("ncalotowerebgt1", &ncalotowerebgt1,"ncalotowerebgt1/I"); dataTree_->Branch("ncalotowerebgt2", &ncalotowerebgt2,"ncalotowerebgt2/I"); dataTree_->Branch("ncalotowerebgt5", &ncalotowerebgt5,"ncalotowerebgt5/I"); dataTree_->Branch("ncalotowerebgt10", &ncalotowerebgt10,"ncalotowerebgt10/I"); dataTree_->Branch("ncalotowereegt1", &ncalotowereegt1,"ncalotowereegt1/I"); dataTree_->Branch("ncalotowereegt2", &ncalotowereegt2,"ncalotowereegt2/I"); dataTree_->Branch("ncalotowereegt5", &ncalotowereegt5,"ncalotowereegt5/I"); dataTree_->Branch("ncalotowereegt10", &ncalotowereegt10,"ncalotowereegt10/I"); dataTree_->Branch("ncalotowerhfgt1", &ncalotowerhfgt1,"ncalotowerhfgt1/I"); dataTree_->Branch("ncalotowerhfgt2", &ncalotowerhfgt2,"ncalotowerhfgt2/I"); dataTree_->Branch("ncalotowerhfgt5", &ncalotowerhfgt5,"ncalotowerhfgt5/I"); dataTree_->Branch("ncalotowerhfgt10", &ncalotowerhfgt10,"ncalotowerhfgt10/I"); dataTree_->Branch("ctsumebgt1", &ctsumebgt1, "ctsumebgt1/F"); dataTree_->Branch("ctsumebgt2", &ctsumebgt2, "ctsumebgt2/F"); dataTree_->Branch("ctsumebgt5", &ctsumebgt5, "ctsumebgt5/F"); dataTree_->Branch("ctsumebgt10", &ctsumebgt10, "ctsumebgt10/F"); dataTree_->Branch("ctsumeegt1", &ctsumeegt1, "ctsumeegt1/F"); dataTree_->Branch("ctsumeegt2", &ctsumeegt2, "ctsumeegt2/F"); dataTree_->Branch("ctsumeegt5", &ctsumeegt5, "ctsumeegt5/F"); dataTree_->Branch("ctsumeegt10", &ctsumeegt10, "ctsumeegt10/F"); dataTree_->Branch("ctsumhfgt1", &ctsumhfgt1, "ctsumhfgt1/F"); dataTree_->Branch("ctsumhfgt2", &ctsumhfgt2, "ctsumhfgt2/F"); dataTree_->Branch("ctsumhfgt5", &ctsumhfgt5, "ctsumhfgt5/F"); dataTree_->Branch("ctsumhfgt10", &ctsumhfgt10, "ctsumhfgt10/F"); dataTree_->Branch("rechitsumet_eb_all", &rechitsumet_eb_all, "rechitsumet_eb_all/F"); dataTree_->Branch("rechitsumet_eb_01", &rechitsumet_eb_01, "rechitsumet_eb_01/F"); dataTree_->Branch("rechitsumet_eb_05", &rechitsumet_eb_05, "rechitsumet_eb_05/F"); dataTree_->Branch("rechitsumet_eb_0105", &rechitsumet_eb_0105, "rechitsumet_eb_0105/F"); dataTree_->Branch("rechitsumet_eb_0530", &rechitsumet_eb_0530, "rechitsumet_eb_0530/F"); dataTree_->Branch("rechitsumet_ee_all", &rechitsumet_ee_all, "rechitsumet_ee_all/F"); dataTree_->Branch("rechitsumet_ee_01", &rechitsumet_ee_01, "rechitsumet_ee_01/F"); dataTree_->Branch("rechitsumet_ee_05", &rechitsumet_ee_05, "rechitsumet_ee_05/F"); dataTree_->Branch("rechitsumet_ee_0105", &rechitsumet_ee_0105, "rechitsumet_ee_0105/F"); dataTree_->Branch("rechitsumet_ee_0530", &rechitsumet_ee_0530, "rechitsumet_ee_0530/F"); dataTree_->Branch("bunchintrain", &bunchintrain, "bunchintrain/I"); dataTree_->Branch("ebnumsc_all", &ebnumsc_all, "ebnumsc_all/I"); dataTree_->Branch("eenumsc_all", &eenumsc_all, "eenumsc_all/I"); dataTree_->Branch("ebscsumet_all", &ebscsumet_all, "ebscsumet_all/F"); dataTree_->Branch("eescsumet_all", &eescsumet_all, "eescsumet_all/F"); dataTree_->Branch("ebscsumet_all_eta15", &ebscsumet_all_eta15, "ebscsumet_all_eta15/F"); dataTree_->Branch("ebscsumet_all_eta20", &ebscsumet_all_eta20, "ebscsumet_all_eta20/F"); dataTree_->Branch("ebscsumet_all_eta25", &ebscsumet_all_eta25, "ebscsumet_all_eta25/F"); dataTree_->Branch("eescsumet_all_eta15", &eescsumet_all_eta15, "eescsumet_all_eta15/F"); dataTree_->Branch("eescsumet_all_eta20", &eescsumet_all_eta20, "eescsumet_all_eta20/F"); dataTree_->Branch("eescsumet_all_eta25", &eescsumet_all_eta25, "eescsumet_all_eta25/F"); dataTree_->Branch("ebnumrechits_01", &ebnumrechits_01, "ebnumrechits_01/I"); dataTree_->Branch("ebnumrechits_0105", &ebnumrechits_0105, "ebnumrechits_0105/I"); dataTree_->Branch("ebnumrechits_05", &ebnumrechits_05, "ebnumrechits_05/I"); dataTree_->Branch("ebnumrechits_0530", &ebnumrechits_0530, "ebnumrechits_0530/I"); dataTree_->Branch("eenumrechits_01", &eenumrechits_01, "eenumrechits_01/I"); dataTree_->Branch("eenumrechits_0105", &eenumrechits_0105, "eenumrechits_0105/I"); dataTree_->Branch("eenumrechits_05", &eenumrechits_05, "eenumrechits_05/I"); dataTree_->Branch("eenumrechits_0530", &eenumrechits_0530, "eenumrechits_0530/I"); dataTree_->Branch("numspikes", &numspikes, "numspikes/I"); dataTree_->Branch("numspikes50", &numspikes50, "numspikes50/I"); dataTree_->Branch("numspikes100", &numspikes100, "numspikes100/I"); dataTree_->Branch("numspikes_kweird", &numspikes_kweird, "numspikes_kweird/I"); dataTree_->Branch("numspikes_swisscross", &numspikes_swisscross, "numspikes_swisscross/I"); } ////////////////////////////////////////////////////////////////////////////////////////// void ChanstatusTester::endJob() { cout << "in endjob" << endl; if (file_ !=0) { file_->cd(); cout << "BP1" << endl; ebchstatus->Write(); eechstatus->Write(); tower_spike_ene_swiss_t10->Write(); tower_spike_ene_swiss_t07->Write(); tower_spike_ene_swiss_t05->Write(); tower_spike_ene_swiss_t04->Write(); tower_spike_ene_swiss_t03->Write(); tower_spike_ene_swiss_t10_thresh08->Write(); tower_spike_ene_swiss_t07_thresh08->Write(); tower_spike_ene_swiss_t05_thresh08->Write(); tower_spike_ene_swiss_t04_thresh08->Write(); tower_spike_ene_swiss_t03_thresh08->Write(); tower_spike_ene_swiss_t10_thresh10->Write(); tower_spike_ene_swiss_t07_thresh10->Write(); tower_spike_ene_swiss_t05_thresh10->Write(); tower_spike_ene_swiss_t04_thresh10->Write(); tower_spike_ene_swiss_t03_thresh10->Write(); tower_spike_ene_swiss_t10_thresh12->Write(); tower_spike_ene_swiss_t07_thresh12->Write(); tower_spike_ene_swiss_t05_thresh12->Write(); tower_spike_ene_swiss_t04_thresh12->Write(); tower_spike_ene_swiss_t03_thresh12->Write(); tower_spike_ene_swiss_t10_thresh15->Write(); tower_spike_ene_swiss_t07_thresh15->Write(); tower_spike_ene_swiss_t05_thresh15->Write(); tower_spike_ene_swiss_t04_thresh15->Write(); tower_spike_ene_swiss_t03_thresh15->Write(); tower_spike_ene_swiss_t10_thresh20->Write(); tower_spike_ene_swiss_t07_thresh20->Write(); tower_spike_ene_swiss_t05_thresh20->Write(); tower_spike_ene_swiss_t04_thresh20->Write(); tower_spike_ene_swiss_t03_thresh20->Write(); cout << "BP2" << endl; sc_tower_spike_ene_swiss_t10->Write(); sc_tower_spike_ene_swiss_t07->Write(); sc_tower_spike_ene_swiss_t05->Write(); sc_tower_spike_ene_swiss_t04->Write(); sc_tower_spike_ene_swiss_t03->Write(); sc_tower_spike_ene_swiss_t10_thresh08->Write(); sc_tower_spike_ene_swiss_t07_thresh08->Write(); sc_tower_spike_ene_swiss_t05_thresh08->Write(); sc_tower_spike_ene_swiss_t04_thresh08->Write(); sc_tower_spike_ene_swiss_t03_thresh08->Write(); sc_tower_spike_ene_swiss_t10_thresh10->Write(); sc_tower_spike_ene_swiss_t07_thresh10->Write(); sc_tower_spike_ene_swiss_t05_thresh10->Write(); sc_tower_spike_ene_swiss_t04_thresh10->Write(); sc_tower_spike_ene_swiss_t03_thresh10->Write(); sc_tower_spike_ene_swiss_t10_thresh12->Write(); sc_tower_spike_ene_swiss_t07_thresh12->Write(); sc_tower_spike_ene_swiss_t05_thresh12->Write(); sc_tower_spike_ene_swiss_t04_thresh12->Write(); sc_tower_spike_ene_swiss_t03_thresh12->Write(); sc_tower_spike_ene_swiss_t10_thresh15->Write(); sc_tower_spike_ene_swiss_t07_thresh15->Write(); sc_tower_spike_ene_swiss_t05_thresh15->Write(); sc_tower_spike_ene_swiss_t04_thresh15->Write(); sc_tower_spike_ene_swiss_t03_thresh15->Write(); sc_tower_spike_ene_swiss_t10_thresh20->Write(); sc_tower_spike_ene_swiss_t07_thresh20->Write(); sc_tower_spike_ene_swiss_t05_thresh20->Write(); sc_tower_spike_ene_swiss_t04_thresh20->Write(); sc_tower_spike_ene_swiss_t03_thresh20->Write(); cout << "BP3" << endl; tower_spike_et_swisstt->Write(); tower_spike_ene_swisstt->Write(); tower_spike_et_swisstt_thresh08->Write(); tower_spike_ene_swisstt_thresh08->Write(); tower_spike_et_swisstt_thresh10->Write(); tower_spike_ene_swisstt_thresh10->Write(); tower_spike_et_swisstt_thresh12->Write(); tower_spike_ene_swisstt_thresh12->Write(); tower_spike_et_swisstt_thresh15->Write(); tower_spike_ene_swisstt_thresh15->Write(); tower_spike_et_swisstt_thresh20->Write(); tower_spike_ene_swisstt_thresh20->Write(); sc_tower_spike_et_swisstt->Write(); sc_tower_spike_ene_swisstt->Write(); sc_tower_spike_et_swisstt_thresh08->Write(); sc_tower_spike_ene_swisstt_thresh08->Write(); sc_tower_spike_et_swisstt_thresh10->Write(); sc_tower_spike_ene_swisstt_thresh10->Write(); sc_tower_spike_et_swisstt_thresh12->Write(); sc_tower_spike_ene_swisstt_thresh12->Write(); sc_tower_spike_et_swisstt_thresh15->Write(); sc_tower_spike_ene_swisstt_thresh15->Write(); sc_tower_spike_et_swisstt_thresh20->Write(); sc_tower_spike_ene_swisstt_thresh20->Write(); tower_spike_et_swiss->Write(); tower_spike_ene_swiss->Write(); tower_spike_et_swiss_thresh08->Write(); tower_spike_ene_swiss_thresh08->Write(); tower_spike_et_swiss_thresh10->Write(); tower_spike_ene_swiss_thresh10->Write(); tower_spike_et_swiss_thresh12->Write(); tower_spike_ene_swiss_thresh12->Write(); tower_spike_et_swiss_thresh15->Write(); tower_spike_ene_swiss_thresh15->Write(); tower_spike_et_swiss_thresh20->Write(); tower_spike_ene_swiss_thresh20->Write(); sc_tower_spike_et_swiss->Write(); sc_tower_spike_ene_swiss->Write(); sc_tower_spike_et_swiss_thresh08->Write(); sc_tower_spike_ene_swiss_thresh08->Write(); sc_tower_spike_et_swiss_thresh10->Write(); sc_tower_spike_ene_swiss_thresh10->Write(); sc_tower_spike_et_swiss_thresh12->Write(); sc_tower_spike_ene_swiss_thresh12->Write(); sc_tower_spike_et_swiss_thresh15->Write(); sc_tower_spike_ene_swiss_thresh15->Write(); sc_tower_spike_et_swiss_thresh20->Write(); sc_tower_spike_ene_swiss_thresh20->Write(); noise2d->Write(); histo_event_->Write(); eb_rechitenergy_->Write(); ee_rechitenergy_->Write(); spike_timevset_all_08->Write(); spike_timevset_highest_08->Write(); spike_timevset_koot_all_08->Write(); spike_timevset_koot_highest_08->Write(); spike_timevset_kdiweird_all_08->Write(); spike_timevset_kdiweird_highest_08->Write(); spike_timevset_all_07->Write(); spike_timevset_highest_07->Write(); spike_timevset_koot_all_07->Write(); spike_timevset_koot_highest_07->Write(); spike_timevset_kdiweird_all_07->Write(); spike_timevset_kdiweird_highest_07->Write(); spike_timevset_all_06->Write(); spike_timevset_highest_06->Write(); spike_timevset_koot_all_06->Write(); spike_timevset_koot_highest_06->Write(); spike_timevset_kdiweird_all_06->Write(); spike_timevset_kdiweird_highest_06->Write(); eb_rechitenergy_spiketag->Write(); eb_rechitenergy_sctag->Write(); eb_rechitenergy_kweird->Write(); eb_rechitenergy_knotweird->Write(); eb_rechitenergy_swisscross->Write(); cout << "p1" << endl; ee_rechitenergy_notypeb_->Write(); eb_rechitenergy_spiketag_kweird->Write(); eb_rechitenergy_spiketag_swisscross->Write(); eb_rechitenergy_spiketag_noisedep->Write(); eb_rechitenergy_sctag_kweird->Write(); eb_rechitenergy_sctag_swisscross->Write(); eb_rechitenergy_sctag_noisedep->Write(); swisscross_vs_energy_spiketag->Write(); swisscross_vs_energy_spiketag_kweird->Write(); swisscross_vs_energy_sctag->Write(); swisscross_vs_energy_sctag_kweird->Write(); cout << "p2" << endl; e4_over_noise->Write(); e4_over_noise_spiketag->Write(); e4_over_noise_sctag->Write(); time_4gev_spiketime->Write(); time_10gev_spiketime->Write(); time_4gev_spikekweird->Write(); time_10gev_spikekweird->Write(); time_4gev_swisscross->Write(); time_10gev_swisscross->Write(); pu_4gev_spiketime->Write(); pu_10gev_spiketime->Write(); pu_4gev_spikekweird->Write(); pu_10gev_spikekweird->Write(); pu_4gev_swisscross->Write(); pu_10gev_swisscross->Write(); ene_4gev_spiketime->Write(); ene_10gev_spiketime->Write(); ene_4gev_spikekweird->Write(); ene_10gev_spikekweird->Write(); ene_4gev_swisscross->Write(); ene_10gev_swisscross->Write(); pu_vs_ene_spiketime->Write(); pu_vs_ene_spikekweird->Write(); pu_vs_ene_swisscross->Write(); eb_rechitenergy_02->Write(); eb_rechitenergy_04->Write(); eb_rechitenergy_06->Write(); eb_rechitenergy_08->Write(); eb_rechitenergy_10->Write(); eb_rechitenergy_12->Write(); eb_rechitenergy_14->Write(); eb_rechitenergy_148->Write(); ee_rechitet_16->Write(); ee_rechitet_18->Write(); ee_rechitet_20->Write(); ee_rechitet_22->Write(); ee_rechitet_24->Write(); ee_rechitet_26->Write(); ee_rechitet_28->Write(); ee_rechitet_30->Write(); eb_rechitet_02->Write(); eb_rechitet_04->Write(); eb_rechitet_06->Write(); eb_rechitet_08->Write(); eb_rechitet_10->Write(); eb_rechitet_12->Write(); eb_rechitet_14->Write(); eb_rechitet_148->Write(); ee_rechitenergy_16->Write(); ee_rechitenergy_18->Write(); ee_rechitenergy_20->Write(); ee_rechitenergy_22->Write(); ee_rechitenergy_24->Write(); ee_rechitenergy_26->Write(); ee_rechitenergy_28->Write(); ee_rechitenergy_30->Write(); eb_rechitetvspu_05->Write(); eb_rechitetvspu_10->Write(); eb_rechitetvspu_15->Write(); ee_rechitetvspu_20->Write(); ee_rechitetvspu_25->Write(); ee_rechitetvspu_30->Write(); eb_rechitet_->Write(); ee_rechitet_->Write(); eb_rechiten_vs_eta->Write(); eb_rechitet_vs_eta->Write(); eep_rechiten_vs_eta->Write(); eep_rechiten_vs_phi->Write(); eem_rechiten_vs_eta->Write(); eem_rechiten_vs_phi->Write(); eep_rechitet_vs_eta->Write(); eep_rechitet_vs_phi->Write(); eem_rechitet_vs_eta->Write(); eem_rechitet_vs_phi->Write(); ebocc->Write(); eboccgt1->Write(); eboccgt3->Write(); eboccgt5->Write(); eboccgt1et->Write(); eboccet->Write(); eboccetgt1et->Write(); eboccen->Write(); eboccengt1->Write(); eeocc->Write(); eeoccgt1->Write(); eeoccgt1et->Write(); eeoccet->Write(); eeoccetgt1et->Write(); eeoccen->Write(); eeoccengt1->Write(); eb_timing_0->Write(); eb_timing_200->Write(); eb_timing_400->Write(); eb_timing_600->Write(); eb_timing_800->Write(); eb_timing_1000->Write(); eb_timing_2000->Write(); eb_timing_3000->Write(); eb_timing_4000->Write(); eb_timing_5000->Write(); eb_timing_10000->Write(); eb_timing_3000_spiketag->Write(); eb_timing_4000_spiketag->Write(); eb_timing_4000_kweird->Write(); eb_timing_4000_swisscross->Write(); eb_timing_4000_spiketag_kweird->Write(); eb_timing_4000_spiketag_swisscross->Write(); eb_timing_4000_spiketag_noisedep->Write(); cout << "p3" << endl; eb_timing_4000_sctag->Write(); eb_timing_4000_sctag_kweird->Write(); eb_timing_4000_sctag_swisscross->Write(); eb_timing_4000_sctag_noisedep->Write(); eb_timing_10000_spiketag->Write(); eb_timing_10000_kweird->Write(); eb_timing_10000_swisscross->Write(); eb_timing_10000_spiketag_kweird->Write(); eb_timing_10000_spiketag_swisscross->Write(); eb_timing_10000_spiketag_noisedep->Write(); eb_timing_10000_sctag->Write(); eb_timing_10000_sctag_kweird->Write(); eb_timing_10000_sctag_swisscross->Write(); eb_timing_10000_sctag_noisedep->Write(); cout << "p4" << endl; spikes_vs_ieta_spiketag_4000->Write(); spikes_vs_ieta_spiketag_4000_kweird->Write(); spikes_vs_ieta_spiketag_4000_swisscross->Write(); spikes_vs_ieta_spiketag_4000_noisedep->Write(); spikes_vs_ieta_spiketag_10000->Write(); spikes_vs_ieta_spiketag_10000_kweird->Write(); spikes_vs_ieta_spiketag_10000_swisscross->Write(); spikes_vs_ieta_spiketag_10000_noisedep->Write(); sc_vs_ieta_sctag_4000->Write(); sc_vs_ieta_sctag_4000_kweird->Write(); sc_vs_ieta_sctag_4000_swisscross->Write(); sc_vs_ieta_sctag_4000_noisedep->Write(); sc_vs_ieta_sctag_10000->Write(); sc_vs_ieta_sctag_10000_kweird->Write(); sc_vs_ieta_sctag_10000_swisscross->Write(); sc_vs_ieta_sctag_10000_noisedep->Write(); cout << "p5" << endl; swisscross_vs_ieta_spiketag_4000->Write(); swisscross_vs_ieta_spiketag_4000_kweird->Write(); swisscross_vs_ieta_spiketag_10000->Write(); swisscross_vs_ieta_spiketag_10000_kweird->Write(); swisscross_vs_ieta_sctag_4000->Write(); swisscross_vs_ieta_sctag_4000_kweird->Write(); swisscross_vs_ieta_sctag_10000->Write(); swisscross_vs_ieta_sctag_10000_kweird->Write(); cout << "p6" << endl; strip_prob_et->Write(); strip_prob_ene->Write(); tower_spike_et->Write(); tower_spike_ene->Write(); strip_prob_et_pu->Write(); strip_prob_ene_pu->Write(); tower_spike_et_pu->Write(); tower_spike_ene_pu->Write(); strip_prob_et_thresh08->Write(); strip_prob_ene_thresh08->Write(); tower_spike_et_thresh08->Write(); tower_spike_ene_thresh08->Write(); strip_prob_et_pu_thresh08->Write(); strip_prob_ene_pu_thresh08->Write(); tower_spike_et_pu_thresh08->Write(); tower_spike_ene_pu_thresh08->Write(); strip_prob_et_thresh10->Write(); strip_prob_ene_thresh10->Write(); tower_spike_et_thresh10->Write(); tower_spike_ene_thresh10->Write(); strip_prob_et_pu_thresh10->Write(); strip_prob_ene_pu_thresh10->Write(); tower_spike_et_pu_thresh10->Write(); tower_spike_ene_pu_thresh10->Write(); strip_prob_et_thresh12->Write(); strip_prob_ene_thresh12->Write(); tower_spike_et_thresh12->Write(); tower_spike_ene_thresh12->Write(); strip_prob_et_pu_thresh12->Write(); strip_prob_ene_pu_thresh12->Write(); tower_spike_et_pu_thresh12->Write(); tower_spike_ene_pu_thresh12->Write(); strip_prob_et_thresh15->Write(); strip_prob_ene_thresh15->Write(); tower_spike_et_thresh15->Write(); tower_spike_ene_thresh15->Write(); strip_prob_et_pu_thresh15->Write(); strip_prob_ene_pu_thresh15->Write(); tower_spike_et_pu_thresh15->Write(); tower_spike_ene_pu_thresh15->Write(); strip_prob_et_thresh20->Write(); strip_prob_ene_thresh20->Write(); tower_spike_et_thresh20->Write(); tower_spike_ene_thresh20->Write(); strip_prob_et_pu_thresh20->Write(); strip_prob_ene_pu_thresh20->Write(); tower_spike_et_pu_thresh20->Write(); tower_spike_ene_pu_thresh20->Write(); strip_prob_et_300->Write(); strip_prob_ene_300->Write(); tower_spike_et_300->Write(); tower_spike_ene_300->Write(); strip_prob_et_mod1->Write(); strip_prob_ene_mod1->Write(); tower_spike_et_mod1->Write(); tower_spike_ene_mod1->Write(); strip_prob_et_mod2->Write(); strip_prob_ene_mod2->Write(); tower_spike_et_mod2->Write(); tower_spike_ene_mod2->Write(); strip_prob_et_mod3->Write(); strip_prob_ene_mod3->Write(); tower_spike_et_mod3->Write(); tower_spike_ene_mod3->Write(); strip_prob_et_mod4->Write(); strip_prob_ene_mod4->Write(); tower_spike_et_mod4->Write(); tower_spike_ene_mod4->Write(); strip_prob_et_pu0->Write(); strip_prob_ene_pu0->Write(); tower_spike_et_pu0->Write(); tower_spike_ene_pu0->Write(); strip_prob_et_pu10->Write(); strip_prob_ene_pu10->Write(); tower_spike_et_pu10->Write(); tower_spike_ene_pu10->Write(); strip_prob_et_pu20->Write(); strip_prob_ene_pu20->Write(); tower_spike_et_pu20->Write(); tower_spike_ene_pu20->Write(); sc_strip_prob_et->Write(); sc_strip_prob_ene->Write(); sc_tower_spike_et->Write(); sc_tower_spike_ene->Write(); sc_strip_prob_et_pu->Write(); sc_strip_prob_ene_pu->Write(); sc_tower_spike_et_pu->Write(); sc_tower_spike_ene_pu->Write(); sc_strip_prob_et_10->Write(); sc_strip_prob_ene_10->Write(); sc_tower_spike_et_10->Write(); sc_tower_spike_ene_10->Write(); sc_strip_prob_et_mod1->Write(); sc_strip_prob_ene_mod1->Write(); sc_tower_spike_et_mod1->Write(); sc_tower_spike_ene_mod1->Write(); sc_strip_prob_et_mod2->Write(); sc_strip_prob_ene_mod2->Write(); sc_tower_spike_et_mod2->Write(); sc_tower_spike_ene_mod2->Write(); sc_strip_prob_et_mod3->Write(); sc_strip_prob_ene_mod3->Write(); sc_tower_spike_et_mod3->Write(); sc_tower_spike_ene_mod3->Write(); sc_strip_prob_et_mod4->Write(); sc_strip_prob_ene_mod4->Write(); sc_tower_spike_et_mod4->Write(); sc_tower_spike_ene_mod4->Write(); sc_strip_prob_et_pu0->Write(); sc_strip_prob_ene_pu0->Write(); sc_tower_spike_et_pu0->Write(); sc_tower_spike_ene_pu0->Write(); sc_strip_prob_et_pu10->Write(); sc_strip_prob_ene_pu10->Write(); sc_tower_spike_et_pu10->Write(); sc_tower_spike_ene_pu10->Write(); sc_strip_prob_et_pu20->Write(); sc_strip_prob_ene_pu20->Write(); sc_tower_spike_et_pu20->Write(); sc_tower_spike_ene_pu20->Write(); sc_strip_prob_et_thresh08->Write(); sc_strip_prob_ene_thresh08->Write(); sc_tower_spike_et_thresh08->Write(); sc_tower_spike_ene_thresh08->Write(); sc_strip_prob_et_pu_thresh08->Write(); sc_strip_prob_ene_pu_thresh08->Write(); sc_tower_spike_et_pu_thresh08->Write(); sc_tower_spike_ene_pu_thresh08->Write(); sc_strip_prob_et_thresh10->Write(); sc_strip_prob_ene_thresh10->Write(); sc_tower_spike_et_thresh10->Write(); sc_tower_spike_ene_thresh10->Write(); sc_strip_prob_et_pu_thresh10->Write(); sc_strip_prob_ene_pu_thresh10->Write(); sc_tower_spike_et_pu_thresh10->Write(); sc_tower_spike_ene_pu_thresh10->Write(); sc_strip_prob_et_thresh12->Write(); sc_strip_prob_ene_thresh12->Write(); sc_tower_spike_et_thresh12->Write(); sc_tower_spike_ene_thresh12->Write(); sc_strip_prob_et_pu_thresh12->Write(); sc_strip_prob_ene_pu_thresh12->Write(); sc_tower_spike_et_pu_thresh12->Write(); sc_tower_spike_ene_pu_thresh12->Write(); sc_strip_prob_et_thresh15->Write(); sc_strip_prob_ene_thresh15->Write(); sc_tower_spike_et_thresh15->Write(); sc_tower_spike_ene_thresh15->Write(); sc_strip_prob_et_pu_thresh15->Write(); sc_strip_prob_ene_pu_thresh15->Write(); sc_tower_spike_et_pu_thresh15->Write(); sc_tower_spike_ene_pu_thresh15->Write(); sc_strip_prob_et_thresh20->Write(); sc_strip_prob_ene_thresh20->Write(); sc_tower_spike_et_thresh20->Write(); sc_tower_spike_ene_thresh20->Write(); sc_strip_prob_et_pu_thresh20->Write(); sc_strip_prob_ene_pu_thresh20->Write(); sc_tower_spike_et_pu_thresh20->Write(); sc_tower_spike_ene_pu_thresh20->Write(); eb_r4_0->Write(); eb_r4_200->Write(); eb_r4_400->Write(); eb_r4_600->Write(); eb_r4_800->Write(); eb_r4_1000->Write(); eb_r4_2000->Write(); eb_r4_3000->Write(); eb_r4_4000->Write(); eb_r4_5000->Write(); eb_r4_10000->Write(); cout << "p7" << endl; eb_r4_3000_spiketag->Write(); eb_r4_4000_spiketag->Write(); eb_r4_4000_sctag->Write(); eb_r4_4000_kweird->Write(); eb_r4_4000_swisscross->Write(); eb_r4_10000_spiketag->Write(); eb_r4_10000_sctag->Write(); eb_r4_10000_kweird->Write(); eb_r4_10000_swisscross->Write(); eb_r6_1000->Write(); eb_r6_2000->Write(); eb_r6_3000->Write(); eb_r6_4000->Write(); eb_r6_5000->Write(); eb_r6_10000->Write(); eb_r6_3000_spiketag->Write(); eb_r6_4000_spiketag->Write(); eb_r6_4000_sctag->Write(); eb_r6_4000_kweird->Write(); eb_r6_4000_swisscross->Write(); eb_r6_10000_spiketag->Write(); eb_r6_10000_sctag->Write(); eb_r6_10000_kweird->Write(); eb_r6_10000_swisscross->Write(); cout << "p8" << endl; eb_r4vsr6_3000->Write(); eb_r4vsr6_4000->Write(); eb_r4vsr6_5000->Write(); eb_r4vsr6_10000->Write(); eb_timing_r4_0->Write(); eb_timing_r4_200->Write(); eb_timing_r4_400->Write(); eb_timing_r4_600->Write(); eb_timing_r4_800->Write(); eb_timing_r4_1000->Write(); eb_timing_r4_2000->Write(); eb_timing_r4_3000->Write(); eb_timing_r4_5000->Write(); eb_timing_vs_r4_0->Write(); eb_timing_vs_r4_200->Write(); eb_timing_vs_r4_400->Write(); eb_timing_vs_r4_600->Write(); eb_timing_vs_r4_800->Write(); eb_timing_vs_r4_1000->Write(); eb_timing_vs_r4_2000->Write(); eb_timing_vs_r4_3000->Write(); eb_timing_vs_r4_5000->Write(); eb_timing_vs_r4_10000->Write(); eb_timing_vs_r4_sctag_3000->Write(); eb_timing_vs_r4_sctag_5000->Write(); eb_timing_vs_r4_sctag_10000->Write(); spikeadc->Write(); spiketime50->Write(); rechiteta_all->Write(); rechiteta_gt1et->Write(); rechiteta_etweight->Write(); rechiteta_gt1et_pu10->Write(); rechiteta_gt1et_pu20->Write(); rechiteta_gt1et_pu30->Write(); calotowereta_all->Write(); calotowereta_gt1et->Write(); calotowereta_etweight->Write(); calotowereta_gt1et_pu10->Write(); calotowereta_gt1et_pu20->Write(); calotowereta_gt1et_pu30->Write(); sceta_all->Write(); sceta_severity0->Write(); sceta_koot0->Write(); sceta_all_pueq01->Write(); sceta_severity0_pueq01->Write(); sceta_all_pueq02->Write(); sceta_severity0_pueq02->Write(); sceta_all_pueq03->Write(); sceta_severity0_pueq03->Write(); sceta_all_pueq04->Write(); sceta_severity0_pueq04->Write(); sceta_all_pueq05->Write(); sceta_severity0_pueq05->Write(); sceta_all_pueq06->Write(); sceta_severity0_pueq06->Write(); sceta_all_pueq07->Write(); sceta_severity0_pueq07->Write(); sceta_all_pueq08->Write(); sceta_severity0_pueq08->Write(); sceta_all_pueq09->Write(); sceta_severity0_pueq09->Write(); sceta_all_gt2->Write(); sceta_severity0_gt2->Write(); sceta_koot0_gt2->Write(); sceta_all_gt5->Write(); sceta_severity0_gt5->Write(); sceta_koot0_gt5->Write(); sceta_all_gt10->Write(); sceta_severity0_gt10->Write(); sceta_koot0_gt10->Write(); scet_eb_all->Write(); scet_eb_severity0->Write(); scet_eb_koot0->Write(); scet_ee_all->Write(); scet_ee_severity0->Write(); scet_ee_koot0->Write(); scsumet_eb_all->Write(); scsumet_eb_severity0->Write(); scsumet_eb_koot0->Write(); scsumet_ee_all->Write(); scsumet_ee_severity0->Write(); scsumet_ee_koot0->Write(); scsumet_eb_all_gt2->Write(); scsumet_eb_severity0_gt2->Write(); scsumet_eb_koot0_gt2->Write(); scsumet_ee_all_gt2->Write(); scsumet_ee_severity0_gt2->Write(); scsumet_ee_koot0_gt2->Write(); scsumet_eb_all_gt5->Write(); scsumet_eb_severity0_gt5->Write(); scsumet_eb_koot0_gt5->Write(); scsumet_ee_all_gt5->Write(); scsumet_ee_severity0_gt5->Write(); scsumet_ee_koot0_gt5->Write(); scsumet_eb_all_gt10->Write(); scsumet_eb_severity0_gt10->Write(); scsumet_eb_koot0_gt10->Write(); scsumet_ee_all_gt10->Write(); scsumet_ee_severity0_gt10->Write(); scsumet_ee_koot0_gt10->Write(); scocc_eb_gt50->Write(); scocc_ee_gt50->Write(); scet_eb_all_eta15->Write(); scet_eb_all_eta20->Write(); scet_eb_all_eta25->Write(); scet_ee_all_eta15->Write(); scet_ee_all_eta20->Write(); scet_ee_all_eta25->Write(); scet_eb_all_eta15_pu10->Write(); scet_eb_all_eta20_pu10->Write(); scet_eb_all_eta25_pu10->Write(); scet_ee_all_eta15_pu10->Write(); scet_ee_all_eta20_pu10->Write(); scet_ee_all_eta25_pu10->Write(); scet_eb_all_eta15_pu20->Write(); scet_eb_all_eta20_pu20->Write(); scet_eb_all_eta25_pu20->Write(); scet_ee_all_eta15_pu20->Write(); scet_ee_all_eta20_pu20->Write(); scet_ee_all_eta25_pu20->Write(); scet_eb_all_eta15_pu30->Write(); scet_eb_all_eta20_pu30->Write(); scet_eb_all_eta25_pu30->Write(); scet_ee_all_eta15_pu30->Write(); scet_ee_all_eta20_pu30->Write(); scet_ee_all_eta25_pu30->Write(); scet_eb_all_eta15_pueq10->Write(); scet_eb_all_eta20_pueq10->Write(); scet_eb_all_eta25_pueq10->Write(); scet_ee_all_eta15_pueq10->Write(); scet_ee_all_eta20_pueq10->Write(); scet_ee_all_eta25_pueq10->Write(); scet_eb_all_eta15_pueq20->Write(); scet_eb_all_eta20_pueq20->Write(); scet_eb_all_eta25_pueq20->Write(); scet_ee_all_eta15_pueq20->Write(); scet_ee_all_eta20_pueq20->Write(); scet_ee_all_eta25_pueq20->Write(); scsumet_eb_all_eta15->Write(); scsumet_eb_all_eta20->Write(); scsumet_eb_all_eta25->Write(); scsumet_ee_all_eta15->Write(); scsumet_ee_all_eta20->Write(); scsumet_ee_all_eta25->Write(); scsumet_eb_all_eta15_pu10->Write(); scsumet_eb_all_eta20_pu10->Write(); scsumet_eb_all_eta25_pu10->Write(); scsumet_ee_all_eta15_pu10->Write(); scsumet_ee_all_eta20_pu10->Write(); scsumet_ee_all_eta25_pu10->Write(); scsumet_eb_all_eta15_pu20->Write(); scsumet_eb_all_eta20_pu20->Write(); scsumet_eb_all_eta25_pu20->Write(); scsumet_ee_all_eta15_pu20->Write(); scsumet_ee_all_eta20_pu20->Write(); scsumet_ee_all_eta25_pu20->Write(); scsumet_eb_all_eta15_pu30->Write(); scsumet_eb_all_eta20_pu30->Write(); scsumet_eb_all_eta25_pu30->Write(); scsumet_ee_all_eta15_pu30->Write(); scsumet_ee_all_eta20_pu30->Write(); scsumet_ee_all_eta25_pu30->Write(); scsumet_eb_all_eta15_pueq10->Write(); scsumet_eb_all_eta20_pueq10->Write(); scsumet_eb_all_eta25_pueq10->Write(); scsumet_ee_all_eta15_pueq10->Write(); scsumet_ee_all_eta20_pueq10->Write(); scsumet_ee_all_eta25_pueq10->Write(); scsumet_eb_all_eta15_pueq20->Write(); scsumet_eb_all_eta20_pueq20->Write(); scsumet_eb_all_eta25_pueq20->Write(); scsumet_ee_all_eta15_pueq20->Write(); scsumet_ee_all_eta20_pueq20->Write(); scsumet_ee_all_eta25_pueq20->Write(); scet_eb_all_eta15_pueq01->Write(); scet_eb_all_eta20_pueq01->Write(); scet_eb_all_eta25_pueq01->Write(); scet_ee_all_eta15_pueq01->Write(); scet_ee_all_eta20_pueq01->Write(); scet_ee_all_eta25_pueq01->Write(); scsumet_eb_all_eta15_pueq01->Write(); scsumet_eb_all_eta20_pueq01->Write(); scsumet_eb_all_eta25_pueq01->Write(); scsumet_ee_all_eta15_pueq01->Write(); scsumet_ee_all_eta20_pueq01->Write(); scsumet_ee_all_eta25_pueq01->Write(); scet_eb_all_eta15_pueq02->Write(); scet_eb_all_eta20_pueq02->Write(); scet_eb_all_eta25_pueq02->Write(); scet_ee_all_eta15_pueq02->Write(); scet_ee_all_eta20_pueq02->Write(); scet_ee_all_eta25_pueq02->Write(); scsumet_eb_all_eta15_pueq02->Write(); scsumet_eb_all_eta20_pueq02->Write(); scsumet_eb_all_eta25_pueq02->Write(); scsumet_ee_all_eta15_pueq02->Write(); scsumet_ee_all_eta20_pueq02->Write(); scsumet_ee_all_eta25_pueq02->Write(); scet_eb_all_eta15_pueq03->Write(); scet_eb_all_eta20_pueq03->Write(); scet_eb_all_eta25_pueq03->Write(); scet_ee_all_eta15_pueq03->Write(); scet_ee_all_eta20_pueq03->Write(); scet_ee_all_eta25_pueq03->Write(); scsumet_eb_all_eta15_pueq03->Write(); scsumet_eb_all_eta20_pueq03->Write(); scsumet_eb_all_eta25_pueq03->Write(); scsumet_ee_all_eta15_pueq03->Write(); scsumet_ee_all_eta20_pueq03->Write(); scsumet_ee_all_eta25_pueq03->Write(); scet_eb_all_eta15_pueq04->Write(); scet_eb_all_eta20_pueq04->Write(); scet_eb_all_eta25_pueq04->Write(); scet_ee_all_eta15_pueq04->Write(); scet_ee_all_eta20_pueq04->Write(); scet_ee_all_eta25_pueq04->Write(); scsumet_eb_all_eta15_pueq04->Write(); scsumet_eb_all_eta20_pueq04->Write(); scsumet_eb_all_eta25_pueq04->Write(); scsumet_ee_all_eta15_pueq04->Write(); scsumet_ee_all_eta20_pueq04->Write(); scsumet_ee_all_eta25_pueq04->Write(); scet_eb_all_eta15_pueq05->Write(); scet_eb_all_eta20_pueq05->Write(); scet_eb_all_eta25_pueq05->Write(); scet_ee_all_eta15_pueq05->Write(); scet_ee_all_eta20_pueq05->Write(); scet_ee_all_eta25_pueq05->Write(); scsumet_eb_all_eta15_pueq05->Write(); scsumet_eb_all_eta20_pueq05->Write(); scsumet_eb_all_eta25_pueq05->Write(); scsumet_ee_all_eta15_pueq05->Write(); scsumet_ee_all_eta20_pueq05->Write(); scsumet_ee_all_eta25_pueq05->Write(); scet_eb_all_eta15_pueq06->Write(); scet_eb_all_eta20_pueq06->Write(); scet_eb_all_eta25_pueq06->Write(); scet_ee_all_eta15_pueq06->Write(); scet_ee_all_eta20_pueq06->Write(); scet_ee_all_eta25_pueq06->Write(); scsumet_eb_all_eta15_pueq06->Write(); scsumet_eb_all_eta20_pueq06->Write(); scsumet_eb_all_eta25_pueq06->Write(); scsumet_ee_all_eta15_pueq06->Write(); scsumet_ee_all_eta20_pueq06->Write(); scsumet_ee_all_eta25_pueq06->Write(); scet_eb_all_eta15_pueq07->Write(); scet_eb_all_eta20_pueq07->Write(); scet_eb_all_eta25_pueq07->Write(); scet_ee_all_eta15_pueq07->Write(); scet_ee_all_eta20_pueq07->Write(); scet_ee_all_eta25_pueq07->Write(); scsumet_eb_all_eta15_pueq07->Write(); scsumet_eb_all_eta20_pueq07->Write(); scsumet_eb_all_eta25_pueq07->Write(); scsumet_ee_all_eta15_pueq07->Write(); scsumet_ee_all_eta20_pueq07->Write(); scsumet_ee_all_eta25_pueq07->Write(); scet_eb_all_eta15_pueq08->Write(); scet_eb_all_eta20_pueq08->Write(); scet_eb_all_eta25_pueq08->Write(); scet_ee_all_eta15_pueq08->Write(); scet_ee_all_eta20_pueq08->Write(); scet_ee_all_eta25_pueq08->Write(); scsumet_eb_all_eta15_pueq08->Write(); scsumet_eb_all_eta20_pueq08->Write(); scsumet_eb_all_eta25_pueq08->Write(); scsumet_ee_all_eta15_pueq08->Write(); scsumet_ee_all_eta20_pueq08->Write(); scsumet_ee_all_eta25_pueq08->Write(); scet_eb_all_eta15_pueq09->Write(); scet_eb_all_eta20_pueq09->Write(); scet_eb_all_eta25_pueq09->Write(); scet_ee_all_eta15_pueq09->Write(); scet_ee_all_eta20_pueq09->Write(); scet_ee_all_eta25_pueq09->Write(); scsumet_eb_all_eta15_pueq09->Write(); scsumet_eb_all_eta20_pueq09->Write(); scsumet_eb_all_eta25_pueq09->Write(); scsumet_ee_all_eta15_pueq09->Write(); scsumet_ee_all_eta20_pueq09->Write(); scsumet_ee_all_eta25_pueq09->Write(); ebtime_vs_bxtrain_01->Write(); ebtime_vs_bxtrain_05->Write(); eetime_vs_bxtrain_01->Write(); eetime_vs_bxtrain_05->Write(); rechiteta_vs_bxtrain_01->Write(); rechiteta_vs_bxtrain_05->Write(); sceta_vs_bxtrain->Write(); eb_digi_01->Write(); eb_digi_05->Write(); eb_digi_0105->Write(); eb_digi_0530->Write(); ee_digi_01->Write(); ee_digi_05->Write(); ee_digi_0105->Write(); ee_digi_0530->Write(); ebpedmean_g12->Write(); ebpedmean_g6->Write(); ebpedmean_g1->Write(); ebpedrms_g12->Write(); ebpedrms_g6->Write(); ebpedrms_g1->Write(); eepedmean_g12->Write(); eepedmean_g6->Write(); eepedmean_g1->Write(); eepedrms_g12->Write(); eepedrms_g6->Write(); eepedrms_g1->Write(); for (Int_t i=0;i<360;i++) { for (Int_t j=0;j<170;j++) { double x=etaphi_ped->GetBinContent(i+1,j+1); double y=etaphi_pedsq->GetBinContent(i+1,j+1); double n=etaphi_pedn->GetBinContent(i+1,j+1); if (n>1) { double variance=(n*y-pow(x,2))/(n*(n-1)); double sigma=sqrt(variance); etaphi_pednoise->SetBinContent(i+1,j+1,sigma); } } } etaphi_ped->Write(); etaphi_pedsq->Write(); etaphi_pedn->Write(); etaphi_pednoise->Write(); // normalise 3d digi plots for (Int_t i=0;i<120;i++) { for (Int_t j=0;j<10;j++) { float r=0; float a=eb_digi_0105_vs_time->GetBinContent(i+1,j+1); float b=eb_digi_0105_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta15->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta15->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta15->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta15->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta20->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta20->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta20->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta20->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_time_eta25->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_time_eta25->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_time_eta25->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_time_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_time_eta25->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_time_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_time_eta25->SetBinContent(i+1,j+1,r); } } for (Int_t i=0;i<40;i++) { for (Int_t j=0;j<10;j++) { float r=0; float a=eb_digi_0105_vs_bxtrain->GetBinContent(i+1,j+1); float b=eb_digi_0105_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta15->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta15->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta15->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta20->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta20->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta20->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0105_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=eb_digi_0105_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0105_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=eb_digi_0530_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=eb_digi_0530_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; eb_digi_0530_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0105_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=ee_digi_0105_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0105_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); r=0; a=ee_digi_0530_vs_bxtrain_eta25->GetBinContent(i+1,j+1); b=ee_digi_0530_vs_bxtrain_norm_eta25->GetBinContent(i+1,j+1); if (b>0) r=a/b; ee_digi_0530_vs_bxtrain_eta25->SetBinContent(i+1,j+1,r); } } eb_digi_0105_vs_time->Write(); eb_digi_0530_vs_time->Write(); ee_digi_0105_vs_time->Write(); ee_digi_0530_vs_time->Write(); eb_digi_0105_vs_bxtrain->Write(); eb_digi_0530_vs_bxtrain->Write(); ee_digi_0105_vs_bxtrain->Write(); ee_digi_0530_vs_bxtrain->Write(); eb_digi_0105_vs_time_eta15->Write(); eb_digi_0530_vs_time_eta15->Write(); ee_digi_0105_vs_time_eta15->Write(); ee_digi_0530_vs_time_eta15->Write(); eb_digi_0105_vs_bxtrain_eta15->Write(); eb_digi_0530_vs_bxtrain_eta15->Write(); ee_digi_0105_vs_bxtrain_eta15->Write(); ee_digi_0530_vs_bxtrain_eta15->Write(); eb_digi_0105_vs_time_eta20->Write(); eb_digi_0530_vs_time_eta20->Write(); ee_digi_0105_vs_time_eta20->Write(); ee_digi_0530_vs_time_eta20->Write(); eb_digi_0105_vs_bxtrain_eta20->Write(); eb_digi_0530_vs_bxtrain_eta20->Write(); ee_digi_0105_vs_bxtrain_eta20->Write(); ee_digi_0530_vs_bxtrain_eta20->Write(); eb_digi_0105_vs_time_eta25->Write(); eb_digi_0530_vs_time_eta25->Write(); ee_digi_0105_vs_time_eta25->Write(); ee_digi_0530_vs_time_eta25->Write(); eb_digi_0105_vs_bxtrain_eta25->Write(); eb_digi_0530_vs_bxtrain_eta25->Write(); ee_digi_0105_vs_bxtrain_eta25->Write(); ee_digi_0530_vs_bxtrain_eta25->Write(); dataTree_ ->Write(); } file_ = 0; } void ChanstatusTester::scan5x5(const DetId & det, const edm::Handle<EcalRecHitCollection> &hits, const edm::ESHandle<CaloTopology> &caloTopo, const edm::ESHandle<CaloGeometry> &geometry, int &nHits, float & totEt) { nHits = 0; totEt = 0; CaloNavigator<DetId> cursor = CaloNavigator<DetId>(det,caloTopo->getSubdetectorTopology(det)); for(int j=side_/2; j>=-side_/2; --j) { for(int i=-side_/2; i<=side_/2; ++i) { cursor.home(); cursor.offsetBy(i,j); if(hits->find(*cursor)!=hits->end()) // if hit exists in the rechit collection { EcalRecHit tmpHit = *hits->find(*cursor); // get rechit with detID at cursor const GlobalPoint p ( geometry->getPosition(*cursor) ) ; // calculate Et of the rechit TVector3 hitPos(p.x(),p.y(),p.z()); hitPos *= 1.0/hitPos.Mag(); hitPos *= tmpHit.energy(); float rechitEt = hitPos.Pt(); //--- return values totEt += rechitEt; if(tmpHit.energy()>Emin_ && !tmpHit.checkFlag(EcalRecHit::kGood))nHits++; } } } } const std::vector<DetId> ChanstatusTester::neighbours(const DetId& id){ std::vector<DetId> ret; if ( id.subdetId() == EcalBarrel) { ret.push_back( EBDetId::offsetBy( id, 1, 0 )); ret.push_back( EBDetId::offsetBy( id, -1, 0 )); ret.push_back( EBDetId::offsetBy( id, 0, 1 )); ret.push_back( EBDetId::offsetBy( id, 0,-1 )); } return ret; } float ChanstatusTester::recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ) { // in the barrel: di = dEta dj = dPhi // in the endcap: di = dX dj = dY DetId nid; if( id.subdetId() == EcalBarrel) nid = EBDetId::offsetBy( id, di, dj ); else if( id.subdetId() == EcalEndcap) nid = EEDetId::offsetBy( id, di, dj ); return ( nid == DetId(0) ? 0 : recHitE( nid, recHits ) ); } float ChanstatusTester::recHitE( const DetId id, const EcalRecHitCollection &recHits) { if ( id.rawId() == 0 ) return 0; EcalRecHitCollection::const_iterator it = recHits.find( id ); if ( it != recHits.end() ){ float ene= (*it).energy(); return ene; } return 0; } float ChanstatusTester::e4e1(const DetId& id, const EcalRecHitCollection& rhs){ float s4 = 0; float e1 = recHitE( id, rhs ); if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ s4+=recHitE(neighs[i],rhs); } return s4 / e1; } float ChanstatusTester::e4e1v2(const DetId& id, const EcalRecHitCollection& rhs){ float s4 = 0; float e1 = recHitE( id, rhs ); float temp=0; if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ temp=recHitE(neighs[i],rhs); if (temp>0.08) s4+=temp; } return s4 / e1; } float ChanstatusTester::e6e2(const DetId& id, const EcalRecHitCollection& rhs){ float s4_1 = 0; float s4_2 = 0; float e1 = recHitE( id, rhs ); float maxene=0; DetId maxid; if ( e1 == 0 ) return 0; const std::vector<DetId>& neighs = neighbours(id); for (size_t i=0; i<neighs.size(); ++i){ float ene = recHitE(neighs[i],rhs); if (ene>maxene) { maxene=ene; maxid = neighs[i]; } } float e2=maxene; s4_1 = e4e1(id,rhs)* e1; s4_2 = e4e1(maxid,rhs)* e2; return (s4_1 + s4_2) / (e1+e2) -1. ; } ////////////////////////////////////////////////////////////////////////////////////////// void ChanstatusTester::analyze(edm::Event const& event, edm::EventSetup const& iSetup) { // cout << "In analyse" << endl; /* edm::Handle<L1GlobalTriggerReadoutRecord> gtRecord; event.getByLabel("gtDigis", gtRecord); */ // edm::ESHandle<EcalLaserDbService> laser; // iSetup.get<EcalLaserDbRecord>().get(laser); edm::ESHandle<EcalPedestals> ecalped; iSetup.get<EcalPedestalsRcd>().get(ecalped); const EcalPedestals* eped=ecalped.product(); bit36=0; bit37=0; bit38=0; bit39=0; bit40=0; bit41=0; bit3 =0; bit4 =0; bit9 =0; bit0 =0; eg1=0; eg2=0; eg5=0; algo124=0; algo54=0; algo55=0; algo56=0; algo57=0; algo58=0; algo59=0; algo60=0; algo61=0; algo62=0; algo106=0; algo107=0; rank_=0; ntrk=0; goodtrk=0; numvtx=0; vtx_x=0; vtx_y=0; vtx_z=0; vtx_x_err=0; vtx_y_err=0; vtx_z_err=0; vtx_chi2=-1; vtx_ndof=0; vtx_ntracks=0; vtx_isfake=0; vtx_good=0; numgoodvtx=0; scale=0; energy_ecal=0; energy_hcal=0; eemax=0; eemaxet=0; eeix=0; eeiy=0; eeix=0; eetime=0; eeflags=0; eehits=0; eehits1GeV=0; ee_eta=0; ee_phi=0; ee_r9=0; eephits=0; eemhits=0; ebmax=0; eb_ieta=0; eb_iphi=0; eb_eta=0; eb_phi=0; ebtime=0; ebflags=0; ebhits=0; ebhits1GeV=0; ebmaxet=0; eb_r9=0; eb_r4=0; eb_e9=0; eb_e25=0; ebchi2=0; eb2chi2=0; ebchi2oot=0; eb2chi2oot=0; eemax2=0; eemaxet2=0; eeix2=0; eeiy2=0; eeix2=0; eetime2=0; eeflags2=0; eehits1GeV2=0; ee_eta2=0; ee_phi2=0; ee_r92=0; ebmax2=0; eb_ieta2=0; eb_iphi2=0; eb_eta2=0; eb_phi2=0; ebtime2=0; ebflags2=0; ebhits1GeV2=0; ebmaxet2=0; eb_r92=0; eb_r42=0; ebnumrechits_01=0; ebnumrechits_05=0; ebnumrechits_0105=0; ebnumrechits_0530=0; eenumrechits_01=0; eenumrechits_05=0; eenumrechits_0105=0; eenumrechits_0530=0; ebflag_kgood=0; ebflag_kpoorreco=0; ebflag_koutoftime=0; ebflag_kfake=0; tmean_en=0; terr_en=0; tmean_sig=0; terr_sig=0; r4count=0; e2e9count_thresh0=0; e2e25count_thresh0=0; e2e9count_thresh1=0; e2e25count_thresh1=0; e2e9count_thresh0_nor4=0; e2e25count_thresh0_nor4=0; e2e9count_thresh1_nor4=0; e2e25count_thresh1_nor4=0; r4_algo_count=0; e2e9_algo_count=0; e2e9_algo_count_5_1=0; e2e9_algo_count_5_0=0; swisscross_algo=0; e2e9_algo=0; scale=1.0; ncr_ = 0 ; energy_pf_ = 0; energyc_pf_ = 0; energyn_pf_ = 0; energyg_pf_ = 0; energy_ecal = 0; energy_hcal = 0; ptJet_ = 0; etaJet_ = 0; phiJet_ = 0; chfJet_ = 0; nhfJet_ = 0; cemfJet_ = 0; nemfJet_ = 0; cmultiJet_ = 0; nmultiJet_ = 0; nrjets_ = 1; eesum_gt1=0; eesum_gt2=0; eesum_gt4=0; ebsum_gt1=0; ebsum_gt2=0; ebsum_gt4=0; eesum_gt1et=0; eesum_gt2et=0; eesum_gt4et=0; ebsum_gt1et=0; ebsum_gt2et=0; ebsum_gt4et=0; ebhits1GeVet=0; ebhits2GeV=0; ebhits4GeV=0; eehits2GeV=0; eehits4GeV=0; eehits1GeVet=0; ebhits2GeVet=0; ebhits4GeVet=0; eehits2GeVet=0; eehits4GeVet=0; numspikes_kweird=0; numspikes_swisscross=0; run = event.id().run(); even = event.id().event(); lumi = event.luminosityBlock(); bx = event.bunchCrossing(); // physdeclared= gtRecord->gtFdlWord().physicsDeclared(); orbit = event.orbitNumber(); double sec = event.time().value() >> 32 ; double usec = 0xFFFFFFFF & event.time().value(); double conv = 1e6; time = (sec+usec/conv); edm::ESHandle<EcalChannelStatus> chanstat; iSetup.get<EcalChannelStatusRcd>().get(chanstat); // const EcalChannelStatus* cstat=chanstat.product(); float db_pedg12=0, db_pedg6=0, db_pedg1=0; float db_pedrmsg12=0, db_pedrmsg6=0, db_pedrmsg1=0; for (Int_t i=0;i<360;i++) { for (Int_t j=0;j<170;j++) { int iphitmp=i+1; int ietatmp=j-85+1*(j>84); // cout << iphitmp << ":" << ietatmp << endl; if (EBDetId::validDetId(ietatmp,iphitmp)) { EBDetId deteb(ietatmp,iphitmp,0); int ebhashedid = deteb.hashedIndex(); const EcalPedestals::Item *aped=0; aped=&eped->barrel(ebhashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; ebpedmean_g12->SetBinContent(i+1,j+1,db_pedg12); ebpedmean_g6->SetBinContent(i+1,j+1,db_pedg6); ebpedmean_g1->SetBinContent(i+1,j+1,db_pedg1); ebpedrms_g12->SetBinContent(i+1,j+1,db_pedrmsg12); ebpedrms_g6->SetBinContent(i+1,j+1,db_pedrmsg6); ebpedrms_g1->SetBinContent(i+1,j+1,db_pedrmsg1); EcalChannelStatusCode chstatcode; EcalChannelStatusMap::const_iterator chit=chanstat->find(deteb); if (chit!=chanstat->end()) { chstatcode=*chit; cout << "Detid ieta=" << deteb.ieta() << " Detid iphi=" << deteb.iphi() << " Channel status=" << chstatcode.getEncodedStatusCode() << endl; ebchstatus->SetBinContent(i+1,j+1,chstatcode.getEncodedStatusCode()); } } } } for (Int_t i=0;i<100;i++) { for (Int_t j=0;j<100;j++) { for (Int_t k=0;k<2;k++) { int ixtmp=i+1; int iytmp=j+1; int iztmp=-1+2*(k>0); if (EEDetId::validDetId(ixtmp,iytmp,iztmp)) { EEDetId detee(ixtmp,iytmp,iztmp,0); int eehashedid = detee.hashedIndex(); const EcalPedestals::Item *aped=0; aped=&eped->endcap(eehashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; eepedmean_g12->SetBinContent(i+1+100*k,j+1,db_pedg12); eepedmean_g6->SetBinContent(i+1+100*k,j+1,db_pedg6); eepedmean_g1->SetBinContent(i+1+100*k,j+1,db_pedg1); eepedrms_g12->SetBinContent(i+1+100*k,j+1,db_pedrmsg12); eepedrms_g6->SetBinContent(i+1+100*k,j+1,db_pedrmsg6); eepedrms_g1->SetBinContent(i+1+100*k,j+1,db_pedrmsg1); EcalChannelStatusCode chstatcode; EcalChannelStatusMap::const_iterator chit=chanstat->find(detee); if (chit!=chanstat->end()) { chstatcode=*chit; cout << "Detid ix=" << detee.ix() << " Detid iy=" << detee.iy() << "Detid iz=" << detee.zside() << " Channel status=" << chstatcode.getEncodedStatusCode() << " pedmean=" << db_pedg12 << ":" << db_pedg6 << ":" << db_pedg1 << " pedrms=" << db_pedrmsg12 << ":" << db_pedrmsg6 << ":" << db_pedrmsg1 << endl; eechstatus->SetBinContent(i+1+100*k,j+1,chstatcode.getEncodedStatusCode()); } } } } } dataTree_->Fill(); // cout << "end jets" << endl; } ////////////////////////////////////////////////////////////////////////////////////////// ChanstatusTester::~ChanstatusTester() { delete file_; delete dataTree_; } //} <file_sep>/plugins/SpikeAnalyserMC.h #ifndef SPIKE_ANAYLSERMC_H #define SPIKE_ANALYSERMC_H #include "TTree.h" #include "TH1D.h" #include "TH3D.h" #include "TH2F.h" #include "TFile.h" #include "FWCore/Framework/interface/ESHandle.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Utilities/interface/InputTag.h" class EcalCleaningAlgo; class SpikeAnalyserMC : public edm::EDAnalyzer { public: explicit SpikeAnalyserMC(edm::ParameterSet const& cfg); virtual void beginJob(); virtual void analyze(edm::Event const& e, edm::EventSetup const& iSetup); virtual void endJob(); ~SpikeAnalyserMC(); void scan5x5(const DetId & det, const edm::Handle<EcalRecHitCollection> &hits, const edm::ESHandle<CaloTopology> &caloTopo,const edm::ESHandle<CaloGeometry> &geometry, int &nHits, float & totEt); private: float e4e1(const DetId& id, const EcalRecHitCollection& rhs); float e4e1v2(const DetId& id, const EcalRecHitCollection& rhs); float e6e2 (const DetId& id, const EcalRecHitCollection& rhs); float recHitE( const DetId id, const EcalRecHitCollection &recHits); float recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ); const std::vector<DetId> neighbours(const DetId& id); edm::InputTag L1GtReadoutRecordTag; std::string histogramFile_; std::string jets_; std::string tracks_; std::string vertex_coll_; std::string jetcorr_; std::string ebhitcoll_; std::string eehitcoll_; std::string pfhitcoll1_; std::string pfhitcoll2_; bool isMC_; std::string photonProducer_; std::string photonCollection_; TFile* file_; TTree* dataTree_; TH1D *histo_event_; TH1D *eb_rechitenergy_; TH1D *ee_rechitenergy_; TH1D *eb_rechitenergy_spiketag; TH1D *eb_rechitenergy_spiketag_kweird; TH1D *eb_rechitenergy_spiketag_swisscross; TH1D *eb_rechitenergy_spiketag_noisedep; TH1D *eb_rechitenergy_sctag; TH1D *eb_rechitenergy_sctag_kweird; TH1D *eb_rechitenergy_sctag_swisscross; TH1D *eb_rechitenergy_sctag_noisedep; TH1D *eb_rechitenergy_kweird; TH1D *eb_rechitenergy_swisscross; TH1D *eb_rechitenergy_knotweird; TH1D *ee_rechitenergy_notypeb_; TH1D *eb_rechitenergy_02; TH1D *eb_rechitenergy_04; TH1D *eb_rechitenergy_06; TH1D *eb_rechitenergy_08; TH1D *eb_rechitenergy_10; TH1D *eb_rechitenergy_12; TH1D *eb_rechitenergy_14; TH1D *eb_rechitenergy_148; TH1D *ee_rechitenergy_16; TH1D *ee_rechitenergy_18; TH1D *ee_rechitenergy_20; TH1D *ee_rechitenergy_22; TH1D *ee_rechitenergy_24; TH1D *ee_rechitenergy_26; TH1D *ee_rechitenergy_28; TH1D *ee_rechitenergy_30; TH1D *e4_over_noise; TH1D *e4_over_noise_spiketag; TH1D *e4_over_noise_sctag; TH1D *ee_rechitet_16; TH1D *ee_rechitet_18; TH1D *ee_rechitet_20; TH1D *ee_rechitet_22; TH1D *ee_rechitet_24; TH1D *ee_rechitet_26; TH1D *ee_rechitet_28; TH1D *ee_rechitet_30; TH1D *eb_rechitet_02; TH1D *eb_rechitet_04; TH1D *eb_rechitet_06; TH1D *eb_rechitet_08; TH1D *eb_rechitet_10; TH1D *eb_rechitet_12; TH1D *eb_rechitet_14; TH1D *eb_rechitet_148; TH2D *etaphi_ped; TH2D *etaphi_pedsq; TH2D *etaphi_pedn; TH2D *etaphi_pednoise; TH1D *time_4gev_spiketime; TH1D *time_10gev_spiketime; TH1D *time_4gev_spikekweird; TH1D *time_10gev_spikekweird; TH1D *time_4gev_swisscross; TH1D *time_10gev_swisscross; TH1D *pu_4gev_spiketime; TH1D *pu_10gev_spiketime; TH1D *pu_4gev_spikekweird; TH1D *pu_10gev_spikekweird; TH1D *pu_4gev_swisscross; TH1D *pu_10gev_swisscross; TH1D *ene_4gev_spiketime; TH1D *ene_10gev_spiketime; TH1D *ene_4gev_spikekweird; TH1D *ene_10gev_spikekweird; TH1D *ene_4gev_swisscross; TH1D *ene_10gev_swisscross; TH2D *pu_vs_ene_spiketime; TH2D *pu_vs_ene_spikekweird; TH2D *pu_vs_ene_swisscross; TH2D *eb_rechitetvspu_05; TH2D *eb_rechitetvspu_10; TH2D *eb_rechitetvspu_15; TH2D *ee_rechitetvspu_20; TH2D *ee_rechitetvspu_25; TH2D *ee_rechitetvspu_30; TH2D *eventenergy; TH2D *eventet; TH2D *eventtime; TH2D *eventkoot; TH2D *eventkdiweird; TH2D *spike_timevset_all_08; TH2D *spike_timevset_highest_08; TH2D *spike_timevset_koot_all_08; TH2D *spike_timevset_koot_highest_08; TH2D *spike_timevset_kdiweird_all_08; TH2D *spike_timevset_kdiweird_highest_08; TH2D *spike_timevset_all_07; TH2D *spike_timevset_highest_07; TH2D *spike_timevset_koot_all_07; TH2D *spike_timevset_koot_highest_07; TH2D *spike_timevset_kdiweird_all_07; TH2D *spike_timevset_kdiweird_highest_07; TH2D *spike_timevset_all_06; TH2D *spike_timevset_highest_06; TH2D *spike_timevset_koot_all_06; TH2D *spike_timevset_koot_highest_06; TH2D *spike_timevset_kdiweird_all_06; TH2D *spike_timevset_kdiweird_highest_06; TH1D *eb_rechitet_; TH1D *ee_rechitet_; TH2D *eb_rechiten_vs_eta; TH2D *eb_rechitet_vs_eta; TH2D *eep_rechitet_vs_eta; TH2D *eep_rechitet_vs_phi; TH2D *eem_rechitet_vs_eta; TH2D *eem_rechitet_vs_phi; TH2D *eep_rechiten_vs_eta; TH2D *eep_rechiten_vs_phi; TH2D *eem_rechiten_vs_eta; TH2D *eem_rechiten_vs_phi; TH2D *swisscross_vs_energy_spiketag; TH2D *swisscross_vs_energy_spiketag_kweird; TH2D *swisscross_vs_energy_sctag; TH2D *swisscross_vs_energy_sctag_kweird; TH2D *time_vs_energy_spiketag; TH2D *time_vs_energy_spiketag_kweird; TH2D *time_vs_energy_spiketag_swisscross; TH2D *time_vs_energy_sctag; TH2D *time_vs_energy_sctag_kweird; TH2D *time_vs_energy_sctag_swisscross; TH2D *noise2d; TH2D *tower_spike_et_swisstt; TH2D *tower_spike_ene_swisstt; TH2D *tower_spike_et_swisstt_thresh08; TH2D *tower_spike_ene_swisstt_thresh08; TH2D *tower_spike_et_swisstt_thresh10; TH2D *tower_spike_ene_swisstt_thresh10; TH2D *tower_spike_et_swisstt_thresh12; TH2D *tower_spike_ene_swisstt_thresh12; TH2D *tower_spike_et_swisstt_thresh15; TH2D *tower_spike_ene_swisstt_thresh15; TH2D *tower_spike_et_swisstt_thresh20; TH2D *tower_spike_ene_swisstt_thresh20; TH2D *sc_tower_spike_et_swisstt; TH2D *sc_tower_spike_ene_swisstt; TH2D *sc_tower_spike_et_swisstt_thresh08; TH2D *sc_tower_spike_ene_swisstt_thresh08; TH2D *sc_tower_spike_et_swisstt_thresh10; TH2D *sc_tower_spike_ene_swisstt_thresh10; TH2D *sc_tower_spike_et_swisstt_thresh12; TH2D *sc_tower_spike_ene_swisstt_thresh12; TH2D *sc_tower_spike_et_swisstt_thresh15; TH2D *sc_tower_spike_ene_swisstt_thresh15; TH2D *sc_tower_spike_et_swisstt_thresh20; TH2D *sc_tower_spike_ene_swisstt_thresh20; TH2D *tower_spike_et_swiss; TH2D *tower_spike_ene_swiss; TH2D *tower_spike_et_swiss_thresh08; TH2D *tower_spike_ene_swiss_thresh08; TH2D *tower_spike_et_swiss_thresh10; TH2D *tower_spike_ene_swiss_thresh10; TH2D *tower_spike_et_swiss_thresh12; TH2D *tower_spike_ene_swiss_thresh12; TH2D *tower_spike_et_swiss_thresh15; TH2D *tower_spike_ene_swiss_thresh15; TH2D *tower_spike_et_swiss_thresh20; TH2D *tower_spike_ene_swiss_thresh20; TH2D *sc_tower_spike_et_swiss; TH2D *sc_tower_spike_ene_swiss; TH2D *sc_tower_spike_et_swiss_thresh08; TH2D *sc_tower_spike_ene_swiss_thresh08; TH2D *sc_tower_spike_et_swiss_thresh10; TH2D *sc_tower_spike_ene_swiss_thresh10; TH2D *sc_tower_spike_et_swiss_thresh12; TH2D *sc_tower_spike_ene_swiss_thresh12; TH2D *sc_tower_spike_et_swiss_thresh15; TH2D *sc_tower_spike_ene_swiss_thresh15; TH2D *sc_tower_spike_et_swiss_thresh20; TH2D *sc_tower_spike_ene_swiss_thresh20; TH2D *tower_spike_ene_swiss_t10; TH2D *tower_spike_ene_swiss_t07; TH2D *tower_spike_ene_swiss_t05; TH2D *tower_spike_ene_swiss_t04; TH2D *tower_spike_ene_swiss_t03; TH2D *tower_spike_ene_swiss_t10_thresh08; TH2D *tower_spike_ene_swiss_t07_thresh08; TH2D *tower_spike_ene_swiss_t05_thresh08; TH2D *tower_spike_ene_swiss_t04_thresh08; TH2D *tower_spike_ene_swiss_t03_thresh08; TH2D *tower_spike_ene_swiss_t10_thresh10; TH2D *tower_spike_ene_swiss_t07_thresh10; TH2D *tower_spike_ene_swiss_t05_thresh10; TH2D *tower_spike_ene_swiss_t04_thresh10; TH2D *tower_spike_ene_swiss_t03_thresh10; TH2D *tower_spike_ene_swiss_t10_thresh12; TH2D *tower_spike_ene_swiss_t07_thresh12; TH2D *tower_spike_ene_swiss_t05_thresh12; TH2D *tower_spike_ene_swiss_t04_thresh12; TH2D *tower_spike_ene_swiss_t03_thresh12; TH2D *tower_spike_ene_swiss_t10_thresh15; TH2D *tower_spike_ene_swiss_t07_thresh15; TH2D *tower_spike_ene_swiss_t05_thresh15; TH2D *tower_spike_ene_swiss_t04_thresh15; TH2D *tower_spike_ene_swiss_t03_thresh15; TH2D *tower_spike_ene_swiss_t10_thresh20; TH2D *tower_spike_ene_swiss_t07_thresh20; TH2D *tower_spike_ene_swiss_t05_thresh20; TH2D *tower_spike_ene_swiss_t04_thresh20; TH2D *tower_spike_ene_swiss_t03_thresh20; TH2D *sc_tower_spike_ene_swiss_t10; TH2D *sc_tower_spike_ene_swiss_t07; TH2D *sc_tower_spike_ene_swiss_t05; TH2D *sc_tower_spike_ene_swiss_t04; TH2D *sc_tower_spike_ene_swiss_t03; TH2D *sc_tower_spike_ene_swiss_t10_thresh08; TH2D *sc_tower_spike_ene_swiss_t07_thresh08; TH2D *sc_tower_spike_ene_swiss_t05_thresh08; TH2D *sc_tower_spike_ene_swiss_t04_thresh08; TH2D *sc_tower_spike_ene_swiss_t03_thresh08; TH2D *sc_tower_spike_ene_swiss_t10_thresh10; TH2D *sc_tower_spike_ene_swiss_t07_thresh10; TH2D *sc_tower_spike_ene_swiss_t05_thresh10; TH2D *sc_tower_spike_ene_swiss_t04_thresh10; TH2D *sc_tower_spike_ene_swiss_t03_thresh10; TH2D *sc_tower_spike_ene_swiss_t10_thresh12; TH2D *sc_tower_spike_ene_swiss_t07_thresh12; TH2D *sc_tower_spike_ene_swiss_t05_thresh12; TH2D *sc_tower_spike_ene_swiss_t04_thresh12; TH2D *sc_tower_spike_ene_swiss_t03_thresh12; TH2D *sc_tower_spike_ene_swiss_t10_thresh15; TH2D *sc_tower_spike_ene_swiss_t07_thresh15; TH2D *sc_tower_spike_ene_swiss_t05_thresh15; TH2D *sc_tower_spike_ene_swiss_t04_thresh15; TH2D *sc_tower_spike_ene_swiss_t03_thresh15; TH2D *sc_tower_spike_ene_swiss_t10_thresh20; TH2D *sc_tower_spike_ene_swiss_t07_thresh20; TH2D *sc_tower_spike_ene_swiss_t05_thresh20; TH2D *sc_tower_spike_ene_swiss_t04_thresh20; TH2D *sc_tower_spike_ene_swiss_t03_thresh20; TH2D *strip_prob_et; TH2D *strip_prob_ene; TH2D *tower_spike_et; TH2D *tower_spike_ene; TH3D *strip_prob_et_pu; TH3D *strip_prob_ene_pu; TH3D *tower_spike_et_pu; TH3D *tower_spike_ene_pu; TH2D *strip_prob_et_thresh08; TH2D *strip_prob_ene_thresh08; TH2D *tower_spike_et_thresh08; TH2D *tower_spike_ene_thresh08; TH3D *strip_prob_et_pu_thresh08; TH3D *strip_prob_ene_pu_thresh08; TH3D *tower_spike_et_pu_thresh08; TH3D *tower_spike_ene_pu_thresh08; TH2D *strip_prob_et_thresh10; TH2D *strip_prob_ene_thresh10; TH2D *tower_spike_et_thresh10; TH2D *tower_spike_ene_thresh10; TH3D *strip_prob_et_pu_thresh10; TH3D *strip_prob_ene_pu_thresh10; TH3D *tower_spike_et_pu_thresh10; TH3D *tower_spike_ene_pu_thresh10; TH2D *strip_prob_et_thresh12; TH2D *strip_prob_ene_thresh12; TH2D *tower_spike_et_thresh12; TH2D *tower_spike_ene_thresh12; TH3D *strip_prob_et_pu_thresh12; TH3D *strip_prob_ene_pu_thresh12; TH3D *tower_spike_et_pu_thresh12; TH3D *tower_spike_ene_pu_thresh12; TH2D *strip_prob_et_thresh15; TH2D *strip_prob_ene_thresh15; TH2D *tower_spike_et_thresh15; TH2D *tower_spike_ene_thresh15; TH3D *strip_prob_et_pu_thresh15; TH3D *strip_prob_ene_pu_thresh15; TH3D *tower_spike_et_pu_thresh15; TH3D *tower_spike_ene_pu_thresh15; TH2D *strip_prob_et_thresh20; TH2D *strip_prob_ene_thresh20; TH2D *tower_spike_et_thresh20; TH2D *tower_spike_ene_thresh20; TH3D *strip_prob_et_pu_thresh20; TH3D *strip_prob_ene_pu_thresh20; TH3D *tower_spike_et_pu_thresh20; TH3D *tower_spike_ene_pu_thresh20; TH2D *strip_prob_et_300; TH2D *strip_prob_ene_300; TH2D *tower_spike_et_300; TH2D *tower_spike_ene_300; TH2D *strip_prob_et_pu0; TH2D *strip_prob_ene_pu0; TH2D *tower_spike_et_pu0; TH2D *tower_spike_ene_pu0; TH2D *strip_prob_et_pu10; TH2D *strip_prob_ene_pu10; TH2D *tower_spike_et_pu10; TH2D *tower_spike_ene_pu10; TH2D *strip_prob_et_pu20; TH2D *strip_prob_ene_pu20; TH2D *tower_spike_et_pu20; TH2D *tower_spike_ene_pu20; TH2D *strip_prob_et_mod1; TH2D *strip_prob_ene_mod1; TH2D *tower_spike_et_mod1; TH2D *tower_spike_ene_mod1; TH2D *strip_prob_et_mod2; TH2D *strip_prob_ene_mod2; TH2D *tower_spike_et_mod2; TH2D *tower_spike_ene_mod2; TH2D *strip_prob_et_mod3; TH2D *strip_prob_ene_mod3; TH2D *tower_spike_et_mod3; TH2D *tower_spike_ene_mod3; TH2D *strip_prob_et_mod4; TH2D *strip_prob_ene_mod4; TH2D *tower_spike_et_mod4; TH2D *tower_spike_ene_mod4; TH2D *sc_strip_prob_et; TH2D *sc_strip_prob_ene; TH2D *sc_tower_spike_et; TH2D *sc_tower_spike_ene; TH3D *sc_strip_prob_et_pu; TH3D *sc_strip_prob_ene_pu; TH3D *sc_tower_spike_et_pu; TH3D *sc_tower_spike_ene_pu; TH2D *sc_strip_prob_et_thresh08; TH2D *sc_strip_prob_ene_thresh08; TH2D *sc_tower_spike_et_thresh08; TH2D *sc_tower_spike_ene_thresh08; TH3D *sc_strip_prob_et_pu_thresh08; TH3D *sc_strip_prob_ene_pu_thresh08; TH3D *sc_tower_spike_et_pu_thresh08; TH3D *sc_tower_spike_ene_pu_thresh08; TH2D *sc_strip_prob_et_thresh10; TH2D *sc_strip_prob_ene_thresh10; TH2D *sc_tower_spike_et_thresh10; TH2D *sc_tower_spike_ene_thresh10; TH3D *sc_strip_prob_et_pu_thresh10; TH3D *sc_strip_prob_ene_pu_thresh10; TH3D *sc_tower_spike_et_pu_thresh10; TH3D *sc_tower_spike_ene_pu_thresh10; TH2D *sc_strip_prob_et_thresh12; TH2D *sc_strip_prob_ene_thresh12; TH2D *sc_tower_spike_et_thresh12; TH2D *sc_tower_spike_ene_thresh12; TH3D *sc_strip_prob_et_pu_thresh12; TH3D *sc_strip_prob_ene_pu_thresh12; TH3D *sc_tower_spike_et_pu_thresh12; TH3D *sc_tower_spike_ene_pu_thresh12; TH2D *sc_strip_prob_et_thresh15; TH2D *sc_strip_prob_ene_thresh15; TH2D *sc_tower_spike_et_thresh15; TH2D *sc_tower_spike_ene_thresh15; TH3D *sc_strip_prob_et_pu_thresh15; TH3D *sc_strip_prob_ene_pu_thresh15; TH3D *sc_tower_spike_et_pu_thresh15; TH3D *sc_tower_spike_ene_pu_thresh15; TH2D *sc_strip_prob_et_thresh20; TH2D *sc_strip_prob_ene_thresh20; TH2D *sc_tower_spike_et_thresh20; TH2D *sc_tower_spike_ene_thresh20; TH3D *sc_strip_prob_et_pu_thresh20; TH3D *sc_strip_prob_ene_pu_thresh20; TH3D *sc_tower_spike_et_pu_thresh20; TH3D *sc_tower_spike_ene_pu_thresh20; TH2D *sc_strip_prob_et_10; TH2D *sc_strip_prob_ene_10; TH2D *sc_tower_spike_et_10; TH2D *sc_tower_spike_ene_10; TH2D *sc_strip_prob_et_pu0; TH2D *sc_strip_prob_ene_pu0; TH2D *sc_tower_spike_et_pu0; TH2D *sc_tower_spike_ene_pu0; TH2D *sc_strip_prob_et_pu10; TH2D *sc_strip_prob_ene_pu10; TH2D *sc_tower_spike_et_pu10; TH2D *sc_tower_spike_ene_pu10; TH2D *sc_strip_prob_et_pu20; TH2D *sc_strip_prob_ene_pu20; TH2D *sc_tower_spike_et_pu20; TH2D *sc_tower_spike_ene_pu20; TH2D *sc_strip_prob_et_mod1; TH2D *sc_strip_prob_ene_mod1; TH2D *sc_tower_spike_et_mod1; TH2D *sc_tower_spike_ene_mod1; TH2D *sc_strip_prob_et_mod2; TH2D *sc_strip_prob_ene_mod2; TH2D *sc_tower_spike_et_mod2; TH2D *sc_tower_spike_ene_mod2; TH2D *sc_strip_prob_et_mod3; TH2D *sc_strip_prob_ene_mod3; TH2D *sc_tower_spike_et_mod3; TH2D *sc_tower_spike_ene_mod3; TH2D *sc_strip_prob_et_mod4; TH2D *sc_strip_prob_ene_mod4; TH2D *sc_tower_spike_et_mod4; TH2D *sc_tower_spike_ene_mod4; TH2F *ebocc; TH2F *eboccgt1; TH2F *eboccgt3; TH2F *eboccgt5; TH2F *eboccgt1et; TH2F *eboccet; TH2F *eboccetgt1et; TH2F *eboccen; TH2F *eboccengt1; TH2F *eeocc; TH2F *eeoccgt1; TH2F *eeoccgt1et; TH2F *eeoccet; TH2F *eeoccetgt1et; TH2F *eeoccen; TH2F *eeoccengt1; TH1F *rechiteta_all; TH1F *rechiteta_gt1et; TH1F *rechiteta_etweight; TH1F *rechiteta_etweight_gt1et; TH1F *rechiteta_gt1et_pu10; TH1F *rechiteta_gt1et_pu20; TH1F *rechiteta_gt1et_pu30; TH1F *spikeadc; TH1F *spiketime50; TH1F *calotowereta_all; TH1F *calotowereta_gt1et; TH1F *calotowereta_etweight; TH1F *calotowereta_etweight_gt1et; TH1F *calotowereta_gt1et_pu10; TH1F *calotowereta_gt1et_pu20; TH1F *calotowereta_gt1et_pu30; TH1F *sceta_all_pueq01; TH1F *sceta_severity0_pueq01; TH1F *sceta_all_pueq02; TH1F *sceta_severity0_pueq02; TH1F *sceta_all_pueq03; TH1F *sceta_severity0_pueq03; TH1F *sceta_all_pueq04; TH1F *sceta_severity0_pueq04; TH1F *sceta_all_pueq05; TH1F *sceta_severity0_pueq05; TH1F *sceta_all_pueq06; TH1F *sceta_severity0_pueq06; TH1F *sceta_all_pueq07; TH1F *sceta_severity0_pueq07; TH1F *sceta_all_pueq08; TH1F *sceta_severity0_pueq08; TH1F *sceta_all_pueq09; TH1F *sceta_severity0_pueq09; TH1F *sceta_all; TH1F *sceta_severity0; TH1F *sceta_koot0; TH1F *sceta_all_gt2; TH1F *sceta_severity0_gt2; TH1F *sceta_koot0_gt2; TH1F *sceta_all_gt5; TH1F *sceta_severity0_gt5; TH1F *sceta_koot0_gt5; TH1F *sceta_all_gt10; TH1F *sceta_severity0_gt10; TH1F *sceta_koot0_gt10; TH1F *scet_eb_all; TH1F *scet_eb_severity0; TH1F *scet_eb_koot0; TH1F *scet_ee_all; TH1F *scet_ee_severity0; TH1F *scet_ee_koot0; TH1F *scsumet_eb_all; TH1F *scsumet_eb_severity0; TH1F *scsumet_eb_koot0; TH1F *scsumet_ee_all; TH1F *scsumet_ee_severity0; TH1F *scsumet_ee_koot0; TH1F *scsumet_eb_all_gt2; TH1F *scsumet_eb_severity0_gt2; TH1F *scsumet_eb_koot0_gt2; TH1F *scsumet_ee_all_gt2; TH1F *scsumet_ee_severity0_gt2; TH1F *scsumet_ee_koot0_gt2; TH1F *scsumet_eb_all_gt5; TH1F *scsumet_eb_severity0_gt5; TH1F *scsumet_eb_koot0_gt5; TH1F *scsumet_ee_all_gt5; TH1F *scsumet_ee_severity0_gt5; TH1F *scsumet_ee_koot0_gt5; TH1F *scsumet_eb_all_gt10; TH1F *scsumet_eb_severity0_gt10; TH1F *scsumet_eb_koot0_gt10; TH1F *scsumet_ee_all_gt10; TH1F *scsumet_ee_severity0_gt10; TH1F *scsumet_ee_koot0_gt10; TH2F *scocc_eb_gt50; TH2F *scocc_ee_gt50; TH1F *scet_eb_all_eta15; TH1F *scet_eb_all_eta20; TH1F *scet_eb_all_eta25; TH1F *scet_ee_all_eta15; TH1F *scet_ee_all_eta20; TH1F *scet_ee_all_eta25; TH1F *scet_eb_all_eta15_pu10; TH1F *scet_eb_all_eta20_pu10; TH1F *scet_eb_all_eta25_pu10; TH1F *scet_ee_all_eta15_pu10; TH1F *scet_ee_all_eta20_pu10; TH1F *scet_ee_all_eta25_pu10; TH1F *scet_eb_all_eta15_pu20; TH1F *scet_eb_all_eta20_pu20; TH1F *scet_eb_all_eta25_pu20; TH1F *scet_ee_all_eta15_pu20; TH1F *scet_ee_all_eta20_pu20; TH1F *scet_ee_all_eta25_pu20; TH1F *scet_eb_all_eta15_pu30; TH1F *scet_eb_all_eta20_pu30; TH1F *scet_eb_all_eta25_pu30; TH1F *scet_ee_all_eta15_pu30; TH1F *scet_ee_all_eta20_pu30; TH1F *scet_ee_all_eta25_pu30; TH1F *scet_eb_all_eta15_pueq10; TH1F *scet_eb_all_eta20_pueq10; TH1F *scet_eb_all_eta25_pueq10; TH1F *scet_ee_all_eta15_pueq10; TH1F *scet_ee_all_eta20_pueq10; TH1F *scet_ee_all_eta25_pueq10; TH1F *scet_eb_all_eta15_pueq20; TH1F *scet_eb_all_eta20_pueq20; TH1F *scet_eb_all_eta25_pueq20; TH1F *scet_ee_all_eta15_pueq20; TH1F *scet_ee_all_eta20_pueq20; TH1F *scet_ee_all_eta25_pueq20; TH1F *scet_eb_all_eta15_pueq01; TH1F *scet_eb_all_eta20_pueq01; TH1F *scet_eb_all_eta25_pueq01; TH1F *scet_ee_all_eta15_pueq01; TH1F *scet_ee_all_eta20_pueq01; TH1F *scet_ee_all_eta25_pueq01; TH1F *scsumet_eb_all_eta15_pueq01; TH1F *scsumet_eb_all_eta20_pueq01; TH1F *scsumet_eb_all_eta25_pueq01; TH1F *scsumet_ee_all_eta15_pueq01; TH1F *scsumet_ee_all_eta20_pueq01; TH1F *scsumet_ee_all_eta25_pueq01; TH1F *scet_eb_all_eta15_pueq02; TH1F *scet_eb_all_eta20_pueq02; TH1F *scet_eb_all_eta25_pueq02; TH1F *scet_ee_all_eta15_pueq02; TH1F *scet_ee_all_eta20_pueq02; TH1F *scet_ee_all_eta25_pueq02; TH1F *scsumet_eb_all_eta15_pueq02; TH1F *scsumet_eb_all_eta20_pueq02; TH1F *scsumet_eb_all_eta25_pueq02; TH1F *scsumet_ee_all_eta15_pueq02; TH1F *scsumet_ee_all_eta20_pueq02; TH1F *scsumet_ee_all_eta25_pueq02; TH1F *scet_eb_all_eta15_pueq03; TH1F *scet_eb_all_eta20_pueq03; TH1F *scet_eb_all_eta25_pueq03; TH1F *scet_ee_all_eta15_pueq03; TH1F *scet_ee_all_eta20_pueq03; TH1F *scet_ee_all_eta25_pueq03; TH1F *scsumet_eb_all_eta15_pueq03; TH1F *scsumet_eb_all_eta20_pueq03; TH1F *scsumet_eb_all_eta25_pueq03; TH1F *scsumet_ee_all_eta15_pueq03; TH1F *scsumet_ee_all_eta20_pueq03; TH1F *scsumet_ee_all_eta25_pueq03; TH1F *scet_eb_all_eta15_pueq04; TH1F *scet_eb_all_eta20_pueq04; TH1F *scet_eb_all_eta25_pueq04; TH1F *scet_ee_all_eta15_pueq04; TH1F *scet_ee_all_eta20_pueq04; TH1F *scet_ee_all_eta25_pueq04; TH1F *scsumet_eb_all_eta15_pueq04; TH1F *scsumet_eb_all_eta20_pueq04; TH1F *scsumet_eb_all_eta25_pueq04; TH1F *scsumet_ee_all_eta15_pueq04; TH1F *scsumet_ee_all_eta20_pueq04; TH1F *scsumet_ee_all_eta25_pueq04; TH1F *scet_eb_all_eta15_pueq05; TH1F *scet_eb_all_eta20_pueq05; TH1F *scet_eb_all_eta25_pueq05; TH1F *scet_ee_all_eta15_pueq05; TH1F *scet_ee_all_eta20_pueq05; TH1F *scet_ee_all_eta25_pueq05; TH1F *scsumet_eb_all_eta15_pueq05; TH1F *scsumet_eb_all_eta20_pueq05; TH1F *scsumet_eb_all_eta25_pueq05; TH1F *scsumet_ee_all_eta15_pueq05; TH1F *scsumet_ee_all_eta20_pueq05; TH1F *scsumet_ee_all_eta25_pueq05; TH1F *scet_eb_all_eta15_pueq06; TH1F *scet_eb_all_eta20_pueq06; TH1F *scet_eb_all_eta25_pueq06; TH1F *scet_ee_all_eta15_pueq06; TH1F *scet_ee_all_eta20_pueq06; TH1F *scet_ee_all_eta25_pueq06; TH1F *scsumet_eb_all_eta15_pueq06; TH1F *scsumet_eb_all_eta20_pueq06; TH1F *scsumet_eb_all_eta25_pueq06; TH1F *scsumet_ee_all_eta15_pueq06; TH1F *scsumet_ee_all_eta20_pueq06; TH1F *scsumet_ee_all_eta25_pueq06; TH1F *scet_eb_all_eta15_pueq07; TH1F *scet_eb_all_eta20_pueq07; TH1F *scet_eb_all_eta25_pueq07; TH1F *scet_ee_all_eta15_pueq07; TH1F *scet_ee_all_eta20_pueq07; TH1F *scet_ee_all_eta25_pueq07; TH1F *scsumet_eb_all_eta15_pueq07; TH1F *scsumet_eb_all_eta20_pueq07; TH1F *scsumet_eb_all_eta25_pueq07; TH1F *scsumet_ee_all_eta15_pueq07; TH1F *scsumet_ee_all_eta20_pueq07; TH1F *scsumet_ee_all_eta25_pueq07; TH1F *scet_eb_all_eta15_pueq08; TH1F *scet_eb_all_eta20_pueq08; TH1F *scet_eb_all_eta25_pueq08; TH1F *scet_ee_all_eta15_pueq08; TH1F *scet_ee_all_eta20_pueq08; TH1F *scet_ee_all_eta25_pueq08; TH1F *scsumet_eb_all_eta15_pueq08; TH1F *scsumet_eb_all_eta20_pueq08; TH1F *scsumet_eb_all_eta25_pueq08; TH1F *scsumet_ee_all_eta15_pueq08; TH1F *scsumet_ee_all_eta20_pueq08; TH1F *scsumet_ee_all_eta25_pueq08; TH1F *scet_eb_all_eta15_pueq09; TH1F *scet_eb_all_eta20_pueq09; TH1F *scet_eb_all_eta25_pueq09; TH1F *scet_ee_all_eta15_pueq09; TH1F *scet_ee_all_eta20_pueq09; TH1F *scet_ee_all_eta25_pueq09; TH1F *scsumet_eb_all_eta15_pueq09; TH1F *scsumet_eb_all_eta20_pueq09; TH1F *scsumet_eb_all_eta25_pueq09; TH1F *scsumet_ee_all_eta15_pueq09; TH1F *scsumet_ee_all_eta20_pueq09; TH1F *scsumet_ee_all_eta25_pueq09; TH1F *scsumet_eb_all_eta15; TH1F *scsumet_eb_all_eta20; TH1F *scsumet_eb_all_eta25; TH1F *scsumet_ee_all_eta15; TH1F *scsumet_ee_all_eta20; TH1F *scsumet_ee_all_eta25; TH1F *scsumet_eb_all_eta15_pu10; TH1F *scsumet_eb_all_eta20_pu10; TH1F *scsumet_eb_all_eta25_pu10; TH1F *scsumet_ee_all_eta15_pu10; TH1F *scsumet_ee_all_eta20_pu10; TH1F *scsumet_ee_all_eta25_pu10; TH1F *scsumet_eb_all_eta15_pu20; TH1F *scsumet_eb_all_eta20_pu20; TH1F *scsumet_eb_all_eta25_pu20; TH1F *scsumet_ee_all_eta15_pu20; TH1F *scsumet_ee_all_eta20_pu20; TH1F *scsumet_ee_all_eta25_pu20; TH1F *scsumet_eb_all_eta15_pu30; TH1F *scsumet_eb_all_eta20_pu30; TH1F *scsumet_eb_all_eta25_pu30; TH1F *scsumet_ee_all_eta15_pu30; TH1F *scsumet_ee_all_eta20_pu30; TH1F *scsumet_ee_all_eta25_pu30; TH1F *scsumet_eb_all_eta15_pueq10; TH1F *scsumet_eb_all_eta20_pueq10; TH1F *scsumet_eb_all_eta25_pueq10; TH1F *scsumet_ee_all_eta15_pueq10; TH1F *scsumet_ee_all_eta20_pueq10; TH1F *scsumet_ee_all_eta25_pueq10; TH1F *scsumet_eb_all_eta15_pueq20; TH1F *scsumet_eb_all_eta20_pueq20; TH1F *scsumet_eb_all_eta25_pueq20; TH1F *scsumet_ee_all_eta15_pueq20; TH1F *scsumet_ee_all_eta20_pueq20; TH1F *scsumet_ee_all_eta25_pueq20; TH1D *eb_timing_0; TH1D *eb_timing_200; TH1D *eb_timing_400; TH1D *eb_timing_600; TH1D *eb_timing_800; TH1D *eb_timing_1000; TH1D *eb_timing_2000; TH1D *eb_timing_3000; TH1D *eb_timing_4000; TH1D *eb_timing_5000; TH1D *eb_timing_10000; TH1D *eb_timing_3000_spiketag; TH1D *eb_timing_4000_spiketag; TH1D *eb_timing_4000_kweird; TH1D *eb_timing_4000_swisscross; TH1D *eb_timing_4000_spiketag_kweird; TH1D *eb_timing_4000_spiketag_swisscross; TH1D *eb_timing_4000_spiketag_noisedep; TH1D *eb_timing_4000_sctag; TH1D *eb_timing_4000_sctag_kweird; TH1D *eb_timing_4000_sctag_swisscross; TH1D *eb_timing_4000_sctag_noisedep; TH1D *eb_timing_10000_spiketag; TH1D *eb_timing_10000_kweird; TH1D *eb_timing_10000_swisscross; TH1D *eb_timing_10000_spiketag_kweird; TH1D *eb_timing_10000_spiketag_swisscross; TH1D *eb_timing_10000_spiketag_noisedep; TH1D *eb_timing_10000_sctag; TH1D *eb_timing_10000_sctag_kweird; TH1D *eb_timing_10000_sctag_swisscross; TH1D *eb_timing_10000_sctag_noisedep; TH1D *spikes_vs_ieta_spiketag_4000; TH1D *spikes_vs_ieta_spiketag_4000_kweird; TH1D *spikes_vs_ieta_spiketag_4000_swisscross; TH1D *spikes_vs_ieta_spiketag_4000_noisedep; TH1D *spikes_vs_ieta_spiketag_10000; TH1D *spikes_vs_ieta_spiketag_10000_kweird; TH1D *spikes_vs_ieta_spiketag_10000_swisscross; TH1D *spikes_vs_ieta_spiketag_10000_noisedep; TH1D *sc_vs_ieta_sctag_4000; TH1D *sc_vs_ieta_sctag_4000_kweird; TH1D *sc_vs_ieta_sctag_4000_swisscross; TH1D *sc_vs_ieta_sctag_4000_noisedep; TH1D *sc_vs_ieta_sctag_10000; TH1D *sc_vs_ieta_sctag_10000_kweird; TH1D *sc_vs_ieta_sctag_10000_swisscross; TH1D *sc_vs_ieta_sctag_10000_noisedep; TH2D *swisscross_vs_ieta_spiketag_4000; TH2D *swisscross_vs_ieta_spiketag_4000_kweird; TH2D *swisscross_vs_ieta_sctag_4000; TH2D *swisscross_vs_ieta_sctag_4000_kweird; TH2D *swisscross_vs_ieta_spiketag_10000; TH2D *swisscross_vs_ieta_spiketag_10000_kweird; TH2D *swisscross_vs_ieta_sctag_10000; TH2D *swisscross_vs_ieta_sctag_10000_kweird; TH1D *eb_r4_0; TH1D *eb_r4_200; TH1D *eb_r4_400; TH1D *eb_r4_600; TH1D *eb_r4_800; TH1D *eb_r4_1000; TH1D *eb_r4_2000; TH1D *eb_r4_3000; TH1D *eb_r4_4000; TH1D *eb_r4_5000; TH1D *eb_r4_10000; TH1D *eb_r4_3000_spiketag; TH1D *eb_r4_4000_spiketag; TH1D *eb_r4_4000_kweird; TH1D *eb_r4_4000_swisscross; TH1D *eb_r4_4000_sctag; TH1D *eb_r4_10000_spiketag; TH1D *eb_r4_10000_sctag; TH1D *eb_r4_10000_kweird; TH1D *eb_r4_10000_swisscross; TH1D *eb_r6_1000; TH1D *eb_r6_2000; TH1D *eb_r6_3000; TH1D *eb_r6_4000; TH1D *eb_r6_5000; TH1D *eb_r6_10000; TH1D *eb_r6_3000_spiketag; TH1D *eb_r6_4000_spiketag; TH1D *eb_r6_4000_sctag; TH1D *eb_r6_4000_kweird; TH1D *eb_r6_4000_swisscross; TH1D *eb_r6_10000_spiketag; TH1D *eb_r6_10000_sctag; TH1D *eb_r6_10000_kweird; TH1D *eb_r6_10000_swisscross; TH2D *eb_r4vsr6_3000; TH2D *eb_r4vsr6_4000; TH2D *eb_r4vsr6_5000; TH2D *eb_r4vsr6_10000; TH1D *eb_timing_r4_0; TH1D *eb_timing_r4_200; TH1D *eb_timing_r4_400; TH1D *eb_timing_r4_600; TH1D *eb_timing_r4_800; TH1D *eb_timing_r4_1000; TH1D *eb_timing_r4_2000; TH1D *eb_timing_r4_3000; TH1D *eb_timing_r4_5000; TH2D *eb_timing_vs_r4_0; TH2D *eb_timing_vs_r4_200; TH2D *eb_timing_vs_r4_400; TH2D *eb_timing_vs_r4_600; TH2D *eb_timing_vs_r4_800; TH2D *eb_timing_vs_r4_1000; TH2D *eb_timing_vs_r4_2000; TH2D *eb_timing_vs_r4_3000; TH2D *eb_timing_vs_r4_5000; TH2D *eb_timing_vs_r4_10000; TH2D *eb_timing_vs_r4_sctag_3000; TH2D *eb_timing_vs_r4_sctag_5000; TH2D *eb_timing_vs_r4_sctag_10000; TH2D *ebtime_vs_bxtrain_01; TH2D *ebtime_vs_bxtrain_05; TH2D *eetime_vs_bxtrain_01; TH2D *eetime_vs_bxtrain_05; TH2D *sceta_vs_bxtrain; TH2D *rechiteta_vs_bxtrain_01; TH2D *rechiteta_vs_bxtrain_05; TH2D *eb_digi_01; TH2D *ee_digi_01; TH2D *eb_digi_05; TH2D *ee_digi_05; TH2D *eb_digi_30; TH2D *ee_digi_30; TH2D *eb_digi_0105; TH2D *ee_digi_0105; TH2D *eb_digi_0530; TH2D *ee_digi_0530; TH2D *eb_digi_0105_vs_time; TH2D *ee_digi_0105_vs_time; TH2D *eb_digi_0530_vs_time; TH2D *ee_digi_0530_vs_time; TH2D *eb_digi_0105_vs_bxtrain; TH2D *ee_digi_0105_vs_bxtrain; TH2D *eb_digi_0530_vs_bxtrain; TH2D *ee_digi_0530_vs_bxtrain; TH2D *eb_digi_0105_vs_time_norm; TH2D *ee_digi_0105_vs_time_norm; TH2D *eb_digi_0530_vs_time_norm; TH2D *ee_digi_0530_vs_time_norm; TH2D *eb_digi_0105_vs_bxtrain_norm; TH2D *ee_digi_0105_vs_bxtrain_norm; TH2D *eb_digi_0530_vs_bxtrain_norm; TH2D *ee_digi_0530_vs_bxtrain_norm; TH2D *eb_digi_0105_vs_time_eta15; TH2D *ee_digi_0105_vs_time_eta15; TH2D *eb_digi_0530_vs_time_eta15; TH2D *ee_digi_0530_vs_time_eta15; TH2D *eb_digi_0105_vs_bxtrain_eta15; TH2D *ee_digi_0105_vs_bxtrain_eta15; TH2D *eb_digi_0530_vs_bxtrain_eta15; TH2D *ee_digi_0530_vs_bxtrain_eta15; TH2D *eb_digi_0105_vs_time_norm_eta15; TH2D *ee_digi_0105_vs_time_norm_eta15; TH2D *eb_digi_0530_vs_time_norm_eta15; TH2D *ee_digi_0530_vs_time_norm_eta15; TH2D *eb_digi_0105_vs_bxtrain_norm_eta15; TH2D *ee_digi_0105_vs_bxtrain_norm_eta15; TH2D *eb_digi_0530_vs_bxtrain_norm_eta15; TH2D *ee_digi_0530_vs_bxtrain_norm_eta15; TH2D *eb_digi_0105_vs_time_eta20; TH2D *ee_digi_0105_vs_time_eta20; TH2D *eb_digi_0530_vs_time_eta20; TH2D *ee_digi_0530_vs_time_eta20; TH2D *eb_digi_0105_vs_bxtrain_eta20; TH2D *ee_digi_0105_vs_bxtrain_eta20; TH2D *eb_digi_0530_vs_bxtrain_eta20; TH2D *ee_digi_0530_vs_bxtrain_eta20; TH2D *eb_digi_0105_vs_time_norm_eta20; TH2D *ee_digi_0105_vs_time_norm_eta20; TH2D *eb_digi_0530_vs_time_norm_eta20; TH2D *ee_digi_0530_vs_time_norm_eta20; TH2D *eb_digi_0105_vs_bxtrain_norm_eta20; TH2D *ee_digi_0105_vs_bxtrain_norm_eta20; TH2D *eb_digi_0530_vs_bxtrain_norm_eta20; TH2D *ee_digi_0530_vs_bxtrain_norm_eta20; TH2D *eb_digi_0105_vs_time_eta25; TH2D *ee_digi_0105_vs_time_eta25; TH2D *eb_digi_0530_vs_time_eta25; TH2D *ee_digi_0530_vs_time_eta25; TH2D *eb_digi_0105_vs_bxtrain_eta25; TH2D *ee_digi_0105_vs_bxtrain_eta25; TH2D *eb_digi_0530_vs_bxtrain_eta25; TH2D *ee_digi_0530_vs_bxtrain_eta25; TH2D *eb_digi_0105_vs_time_norm_eta25; TH2D *ee_digi_0105_vs_time_norm_eta25; TH2D *eb_digi_0530_vs_time_norm_eta25; TH2D *ee_digi_0530_vs_time_norm_eta25; TH2D *eb_digi_0105_vs_bxtrain_norm_eta25; TH2D *ee_digi_0105_vs_bxtrain_norm_eta25; TH2D *eb_digi_0530_vs_bxtrain_norm_eta25; TH2D *ee_digi_0530_vs_bxtrain_norm_eta25; int rank_; int ntrk; int goodtrk; float vtx_x,vtx_y,vtx_z,vtx_x_err,vtx_y_err,vtx_z_err; float vtx_chi2,vtx_ndof; int numvtx,vtx_ntracks,vtx_isfake,numgoodvtx; int vtx_good; float scale; int bit3,bit4,bit9,bit40,bit41,bit36,bit37,bit38,bit39,run,even,lumi,bx,orbit,bit0; int eg1,eg2,eg5, algo124; int algo54; int algo55; int algo56; int algo57; int algo58; int algo59; int algo60; int algo61; int algo62; int algo106; int algo107; int physdeclared; float time; float ptJet_,phiJet_,etaJet_,chfJet_,nhfJet_,cemfJet_,nemfJet_; float energy_pf_,energyc_pf_,energyn_pf_,energyg_pf_; int cmultiJet_,nmultiJet_,nrjets_,ncr_; float energy_ecal, energy_hcal; float ebmax, eemax, ebtime, eetime; int eb_ieta,eb_iphi,ebhits,ebhits1GeV, ebflags, recoflag, sevlev; int eeix,eeiy,eeiz,eehits,eehits1GeV, eeflags; float eb_eta,eb_phi,ebmaxet, eb_r9, eb_r4; float ee_eta,ee_phi,eemaxet, ee_r9; float ebchi2, ebchi2oot; float eb2chi2, eb2chi2oot; Int_t ee_kGood; Int_t ee_kPoorReco; Int_t ee_kOutOfTime; Int_t ee_kFaultyHardware; Int_t ee_kNoisy; Int_t ee_kPoorCalib; Int_t ee_kSaturated; Int_t ee_kLeadingEdgeRecovered; Int_t ee_kNeighboursRecovered; Int_t ee_kTowerRecovered; Int_t ee_kDead; Int_t ee_kKilled; Int_t ee_kTPSaturated; Int_t ee_kL1SpikeFlag; Int_t ee_kWeird; Int_t ee_kDiWeird; Int_t ee_kUnknown; int numspikes, numspikes50, numspikes100; int ebhits1GeVet, eehits1GeVet; int ebhits2GeV, ebhits4GeV, eehits2GeV, eehits4GeV; int ebhits2GeVet, ebhits4GeVet, eehits2GeVet, eehits4GeVet; float ebmax2, eemax2, ebtime2, eetime2; int eb_ieta2,eb_iphi2,ebhits1GeV2, ebflags2; int eeix2,eeiy2,eeiz2,eehits1GeV2, eeflags2; float eb_eta2,eb_phi2,ebmaxet2, eb_r92, eb_r42; float ee_eta2,ee_phi2,eemaxet2, ee_r92; int adc01,adc02,adc03,adc04,adc05,adc06,adc07,adc08,adc09,adc10; int gain01,gain02,gain03,gain04,gain05,gain06,gain07,gain08,gain09,gain10; float eb_e9, eb_e25; int eephits, eemhits; int ebflag_kgood, ebflag_kpoorreco, ebflag_koutoftime, ebflag_kfake; float tmean_en, terr_en; float tmean_sig, terr_sig; int r4count; int e2e9count_thresh0, e2e25count_thresh0; int e2e9count_thresh1, e2e25count_thresh1; int e2e9count_thresh0_nor4, e2e25count_thresh0_nor4; int e2e9count_thresh1_nor4, e2e25count_thresh1_nor4; int r4_algo_count; int e2e9_algo_count; int e2e9_algo_count_5_1; int e2e9_algo_count_5_0; float swisscross_algo, e2e9_algo; EcalCleaningAlgo * cleaningAlgo_; float Emin_; int side_; const std::vector<int> badsc_; const std::vector<int> bunchstartbx_; // photon variables float phoEta, phoPhi, phoEt; float pho_maxen_xtal, pho_e3x3, pho_e5x5, pho_r9; float etaPhoSc; float pho_ntrksolidconedr4; float pho_ntrksumptsolidconedr4; float pho_ntrkhollowconedr4; float pho_ntrksumpthollowconedr4; float pho_ecaletconedr4; float pho_hcaletconedr4; float pho_sigmaietaieta; float pho_hovere; int phoBarrel; float eesum_gt1, eesum_gt2, eesum_gt4; float ebsum_gt1, ebsum_gt2, ebsum_gt4; float eesum_gt1et, eesum_gt2et, eesum_gt4et; float ebsum_gt1et, ebsum_gt2et, ebsum_gt4et; int ncalotower, ncalotowereb, ncalotoweree, ncalotowerhf; int ncalotowerebgt1, ncalotowerebgt2, ncalotowerebgt5, ncalotowerebgt10; int ncalotowereegt1, ncalotowereegt2, ncalotowereegt5, ncalotowereegt10; int ncalotowerhfgt1, ncalotowerhfgt2, ncalotowerhfgt5, ncalotowerhfgt10; float ctsumebgt1, ctsumebgt2, ctsumebgt5, ctsumebgt10; float ctsumeegt1, ctsumeegt2, ctsumeegt5, ctsumeegt10; float ctsumhfgt1, ctsumhfgt2, ctsumhfgt5, ctsumhfgt10; float rechitsumet_eb_all, rechitsumet_eb_01, rechitsumet_eb_05; float rechitsumet_ee_all, rechitsumet_ee_01, rechitsumet_ee_05; float rechitsumet_eb_0105, rechitsumet_eb_0530; float rechitsumet_ee_0105, rechitsumet_ee_0530; int bunchintrain; int numspikes_kweird; int numspikes_swisscross; float ebscsumet_all, eescsumet_all; float ebscsumet_all_eta15, ebscsumet_all_eta20, ebscsumet_all_eta25; float eescsumet_all_eta15, eescsumet_all_eta20, eescsumet_all_eta25; int ebnumsc_all, eenumsc_all; int ebnumrechits_01, ebnumrechits_0105, ebnumrechits_05, ebnumrechits_0530; int eenumrechits_01, eenumrechits_0105, eenumrechits_05, eenumrechits_0530; }; #endif <file_sep>/plugins/SpikeAnalyser.h #ifndef SPIKE_ANALYSER_H #define SPIKE_ANALYSER_H #include "TTree.h" #include "TH1D.h" #include "TH3D.h" #include "TH2F.h" #include "TFile.h" #include "FWCore/Framework/interface/ESHandle.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Utilities/interface/InputTag.h" class EcalCleaningAlgo; class SpikeAnalyser : public edm::EDAnalyzer { public: explicit SpikeAnalyser(edm::ParameterSet const& cfg); virtual void beginJob(); virtual void analyze(edm::Event const& e, edm::EventSetup const& iSetup); virtual void endJob(); ~SpikeAnalyser(); private: float recHitE( const DetId id, const EcalRecHitCollection &recHits); float recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ); std::string histogramFile_; std::string jets_; std::string tracks_; std::string vertex_coll_; std::string ebhitcoll_; std::string eehitcoll_; const std::vector<int> bunchstartbx_; bool isMC_; EcalCleaningAlgo * cleaningAlgo_; TFile* file_; TTree* dataTree_; TTree* dataTree2_; int run, ev, lumi, bx, orbit, bunchintrain; int numvtx, numgoodvtx; int rechit_ieta, rechit_iphi; float rechit_eta, rechit_phi; int rechit_ix, rechit_iy, rechit_iz; float rechit_eta_ee, rechit_phi_ee; float rechit_ene_weights53, rechit_et_weights53, rechit_time_weights53; float rechit_swisscross_weights53; float rechit_swisscross_zs_weights53; float rechit_swisscross_zs_weights74; float rechit_swisscross_zs_multi5; float rechit_swisscross_zs_multi10; float rechit_swisscross_zs_multi1; float rechit_swisscross_thresh; int rechit_flag_kweird_calc; float rechit_chi2_weights53; int rechit_flag_koot_weights53, rechit_flag_kweird_weights53, rechit_flag_kdiweird_weights53; float rechit_ene_weights74, rechit_et_weights74, rechit_time_weights74; float rechit_swisscross_weights74; float rechit_chi2_weights74; int rechit_flag_koot_weights74, rechit_flag_kweird_weights74, rechit_flag_kdiweird_weights74; float rechit_ene_multi5, rechit_et_multi5, rechit_time_multi5; float rechit_swisscross_multi5; float rechit_chi2_multi5; int rechit_flag_koot_multi5, rechit_flag_kweird_multi5, rechit_flag_kdiweird_multi5; float rechit_ene_multi10, rechit_et_multi10, rechit_time_multi10; float rechit_swisscross_multi10; float rechit_chi2_multi10; int rechit_flag_koot_multi10, rechit_flag_kweird_multi10, rechit_flag_kdiweird_multi10; float rechit_ene_multi1, rechit_et_multi1, rechit_time_multi1; float rechit_swisscross_multi1; float rechit_chi2_multi1; int rechit_flag_koot_multi1, rechit_flag_kweird_multi1, rechit_flag_kdiweird_multi1; float db_pedg12, db_pedg6, db_pedg1; float db_pedrmsg12, db_pedrmsg6, db_pedrmsg1; float lasercorr; int digi_adc[10]; int digi_gainid[10]; TH2F *ebene; TH2F *ebtime; int isnearcrack; float rechit_ene_weights53_ee, rechit_et_weights53_ee, rechit_time_weights53_ee; float rechit_chi2_weights53_ee; int rechit_flag_koot_weights53_ee, rechit_flag_kweird_weights53_ee, rechit_flag_kdiweird_weights53_ee; float rechit_ene_weights74_ee, rechit_et_weights74_ee, rechit_time_weights74_ee; float rechit_chi2_weights74_ee; int rechit_flag_koot_weights74_ee, rechit_flag_kweird_weights74_ee, rechit_flag_kdiweird_weights74_ee; float rechit_ene_multi5_ee, rechit_et_multi5_ee, rechit_time_multi5_ee; float rechit_chi2_multi5_ee; int rechit_flag_koot_multi5_ee, rechit_flag_kweird_multi5_ee, rechit_flag_kdiweird_multi5_ee; float rechit_ene_multi10_ee, rechit_et_multi10_ee, rechit_time_multi10_ee; float rechit_chi2_multi10_ee; int rechit_flag_koot_multi10_ee, rechit_flag_kweird_multi10_ee, rechit_flag_kdiweird_multi10_ee; float rechit_ene_multi1_ee, rechit_et_multi1_ee, rechit_time_multi1_ee; float rechit_chi2_multi1_ee; int rechit_flag_koot_multi1_ee, rechit_flag_kweird_multi1_ee, rechit_flag_kdiweird_multi1_ee; float db_pedg12_ee, db_pedg6_ee, db_pedg1_ee; float db_pedrmsg12_ee, db_pedrmsg6_ee, db_pedrmsg1_ee; float lasercorr_ee; int digi_adc_ee[10]; int digi_gainid_ee[10]; float uncalibrechit_multi10_ampl_ee; float uncalibrechit_multi10_amperr_ee; float uncalibrechit_multi10_pedestal_ee; float uncalibrechit_multi10_jitter_ee; float uncalibrechit_multi10_chi2_ee; float uncalibrechit_multi10_ootampl_ee[10]; float uncalibrechit_multi5_ampl_ee; float uncalibrechit_multi5_amperr_ee; float uncalibrechit_multi5_pedestal_ee; float uncalibrechit_multi5_jitter_ee; float uncalibrechit_multi5_chi2_ee; float uncalibrechit_multi5_ootampl_ee[10]; float uncalibrechit_multi1_ampl_ee; float uncalibrechit_multi1_amperr_ee; float uncalibrechit_multi1_pedestal_ee; float uncalibrechit_multi1_jitter_ee; float uncalibrechit_multi1_chi2_ee; float uncalibrechit_multi1_ootampl_ee[10]; float uncalibrechit_multi10_ampl_eb; float uncalibrechit_multi10_amperr_eb; float uncalibrechit_multi10_pedestal_eb; float uncalibrechit_multi10_jitter_eb; float uncalibrechit_multi10_chi2_eb; float uncalibrechit_multi10_ootampl_eb[10]; float uncalibrechit_multi5_ampl_eb; float uncalibrechit_multi5_amperr_eb; float uncalibrechit_multi5_pedestal_eb; float uncalibrechit_multi5_jitter_eb; float uncalibrechit_multi5_chi2_eb; float uncalibrechit_multi5_ootampl_eb[10]; float uncalibrechit_multi1_ampl_eb; float uncalibrechit_multi1_amperr_eb; float uncalibrechit_multi1_pedestal_eb; float uncalibrechit_multi1_jitter_eb; float uncalibrechit_multi1_chi2_eb; float uncalibrechit_multi1_ootampl_eb[10]; }; #endif <file_sep>/macros/matt_checkplot.C { TFile f1("exomgg_0t_runC.root"); //Specify the number of events to plot const int N = 2; gStyle->SetOptStat(0); //Setting coordinates for the cluster seeds int etamax[N] = {48, -43}; int phimax[N] = {340, 55}; // read histograms from file // transverse energy maps TH2F *eboccet=(TH2F*)f1.Get("eboccet"); TH2F *eeoccet=(TH2F*)f1.Get("eeoccet"); // rechit time maps TH2F *ebtime=(TH2F*)f1.Get("ebtime"); TH2F *eetime=(TH2F*)f1.Get("eetime"); // eb laser correction and intercalibration constants TH2F *eblascorr=(TH2F*)f1.Get("eblascorr"); TH2F *ebicval=(TH2F*)f1.Get("ebicval"); // dead/problematic channel maps TH2F *eb=(TH2F*)f1.Get("ebchstatus"); TH2F *ee=(TH2F*)f1.Get("eechstatus"); TH2F *ebmask=new TH2F("ebmask","",360,0,360,170,-85,85); TH2F *ebmask2=new TH2F("ebmask2","",360,0,360,170,-85,85); TH2F *eemask=new TH2F("eemask","",200,0,200,100,0,100); TH2F *eemask2=new TH2F("eemask2","",200,0,200,100,0,100); TH2F *eblascorrall=new TH2F("eblascorrall","",360,0,360,170,-85,85); TH2F *eblascorrgood=new TH2F("eblascorrgood","",360,0,360,170,-85,85); TH1F *eblascorrall_1d=new TH1F("eblascorrall_1d","",300,0,6); TH1F *eblascorrgood_1d=new TH1F("eblascorrgood_1d","",300,0,6); ebmask->SetLineColor(921); ebmask->SetFillStyle(0); ebmask->SetLineWidth(2); eemask->SetLineColor(921); eemask->SetFillStyle(0); eemask->SetLineWidth(4); ebmask2->SetLineColor(1); ebmask2->SetFillStyle(0); ebmask2->SetLineWidth(2); eemask2->SetLineColor(1); eemask2->SetFillStyle(0); eemask2->SetLineWidth(4); // modify maps to plot laser correction, intercalib and timing only for hits with Et>1.0 GeV for (Int_t j=0;j<170;j++) { for (Int_t i=0;i<180;i++) { //changed 360 to 180 Float_t tmp=eb->GetBinContent(i+1,j+1); Float_t tmp2=eboccet->GetBinContent(i+1,j+1); Float_t tmp3=eblascorr->GetBinContent(i+1,j+1); if (tmp2<1.0) { eblascorr->SetBinContent(i+1,j+1,-999); ebicval->SetBinContent(i+1,j+1,-999); ebtime->SetBinContent(i+1,j+1,-999); } eblascorrall->SetBinContent(i+1,j+1,tmp3); eblascorrall_1d->Fill(tmp3); // make a map of laser correction values for good channels only (channel status < 3) if (tmp<3) { eblascorrgood->SetBinContent(i+1,j+1,tmp3); eblascorrgood_1d->Fill(tmp3); } // make a map of dead and problematic towers // problematic (channel status=13) if (tmp==13) { ebmask->SetBinContent(i+1,j+1,0.1); } // dead (channel status > 13) if (tmp>13) { ebmask2->SetBinContent(i+1,j+1,0.1); } } } // similar exercise for EE for (Int_t j=0;j<100;j++) { for (Int_t i=0;i<200;i++) { Float_t tmp1=ee->GetBinContent(i+1,j+1); if (tmp1==13) { eemask->SetBinContent(i+1,j+1,0.1); } if (tmp1>13) { eemask2->SetBinContent(i+1,j+1,0.1); } } } // DRAW PLOTS TCanvas c1("c1","",10,10,1200,700); c1.SetLogz(1); c1.SetGridx(); c1.SetGridy(); // EB transverse energy map eboccet->GetXaxis()->SetLabelSize(0.03); eboccet->GetYaxis()->SetLabelSize(0.03); eboccet->SetXTitle("i#phi"); eboccet->SetYTitle("i#eta"); TLatex t1; t1.SetNDC(); eboccet->GetXaxis()->SetNdivisions(18); eboccet->GetYaxis()->SetNdivisions(2); eboccet->Draw("colz"); ebmask->Draw("box,same"); ebmask2->Draw("box,same"); eboccet->Draw("colz,same"); t1.SetTextSize(0.05); t1.DrawLatex(0.90,0.86,"E_{T} [GeV]"); c1.SaveAs("plots/exomgg_0t_rereco_ev3_ebet_photon2.png"); TCanvas c2("c2","",10,10,1200,600); c2.cd(); c2.SetLogz(1); c2.SetGridx(); c2.SetGridy(); // EE transverse energy map if (eeoccet->GetMaximum()<1) c2.SetLogz(0); eeoccet->GetXaxis()->SetLabelSize(0); eeoccet->GetYaxis()->SetLabelSize(0); eeoccet->SetXTitle("ix"); eeoccet->SetYTitle("iy"); TLine l1(100,0,100,100); eeoccet->GetXaxis()->SetNdivisions(40); eeoccet->GetYaxis()->SetNdivisions(20); eeoccet->Draw("colz"); eemask->Draw("box,same"); eemask2->Draw("box,same"); eeoccet->Draw("colz,same"); l1.Draw(); t1.SetTextSize(0.05); t1.DrawLatex(0.90,0.86,"E_{T} [GeV]"); t1.DrawLatex(0.17,0.8,"EE-"); t1.DrawLatex(0.8,0.8,"EE+"); c2.SaveAs("plots/exomgg_0t_rereco_ev3_eeet_photon2.png"); // ZOOM of EB transverse energy map TCanvas c3("c3","",10,10,900,700); c3.SetRightMargin(0.16); c3.cd(); c3.SetLogz(1); gStyle->SetPaintTextFormat("2.1f"); // char txt[30]; // for(int k=0; k<4; k++) { eboccet->SetMarkerSize(1.2); eboccet->GetXaxis()->SetNdivisions(11); eboccet->GetYaxis()->SetNdivisions(11); char txt[30]; for (int k=0; k<N; k++) { eboccet->GetXaxis()->SetRangeUser(phimax[k]-6,phimax[k]+4); eboccet->GetYaxis()->SetRangeUser(etamax[k]-5,etamax[k]+5); eboccet->Draw("colz,text"); t1.DrawLatex(0.83,0.875,"E_{T} [GeV]"); sprintf(txt,"plots/transverse_energy_zoom_%d.png",k+1); c3.SaveAs(txt); } // EB rechit time map TCanvas c4("c4","",10,10,900,700); c4.SetRightMargin(0.16); c4.cd(); c4.SetLogz(0); for (Int_t i=0;i<360;i++) { for (Int_t j=0;j<170;j++) { if (ebtime->GetBinContent(i+1,j+1)==0) ebtime->SetBinContent(i+1,j+1,-999); } } ebtime->SetMarkerSize(1.2); ebtime->GetXaxis()->SetNdivisions(11); ebtime->GetYaxis()->SetNdivisions(11); ebtime->GetXaxis()->SetLabelSize(0.03); ebtime->GetYaxis()->SetLabelSize(0.03); ebtime->SetXTitle("i#phi"); ebtime->SetYTitle("i#eta"); ebtime->SetMinimum(-3); ebtime->SetMaximum(3); for (int k=0; k<N; k++) { ebtime->GetXaxis()->SetRangeUser(phimax[k]-6,phimax[k]+4); ebtime->GetYaxis()->SetRangeUser(etamax[k]-5,etamax[k]+5); ebtime->Draw("colz,text"); t1.DrawLatex(0.83,0.875,"Time [ns]"); sprintf(txt,"plots/EB_rechit_time_zoomed_%d.png",k+1); c4.SaveAs(txt); } // EB intercalibration map (zoomed) ebicval->SetMarkerSize(1.2); ebicval->GetXaxis()->SetNdivisions(11); ebicval->GetYaxis()->SetNdivisions(11); ebicval->GetXaxis()->SetLabelSize(0.03); ebicval->GetYaxis()->SetLabelSize(0.03); ebicval->SetXTitle("i#phi"); ebicval->SetYTitle("i#eta"); ebicval->SetMinimum(0); ebicval->SetMaximum(3); for (int k=0; k<N; k++) { ebicval->GetXaxis()->SetRangeUser(phimax[k]-6,phimax[k]+4); ebicval->GetYaxis()->SetRangeUser(etamax[k]-5,etamax[k]+5); ebicval->Draw("colz,text"); t1.DrawLatex(0.83,0.875,"IC"); sprintf(txt,"plots/EB_intercalib_map_zoomed_%d.png",k+1); c4.SaveAs(txt); } // EB laser correction map (zoomed) eblascorr->SetMarkerSize(1.2); eblascorr->GetXaxis()->SetNdivisions(11); eblascorr->GetYaxis()->SetNdivisions(11); eblascorr->GetXaxis()->SetLabelSize(0.03); eblascorr->GetYaxis()->SetLabelSize(0.03); eblascorr->SetXTitle("i#phi"); eblascorr->SetYTitle("i#eta"); eblascorr->SetMinimum(0); eblascorr->SetMaximum(3); for (int k=0; k<N; k++) { eblascorr->GetXaxis()->SetRangeUser(phimax[k]-6,phimax[k]+4); eblascorr->GetYaxis()->SetRangeUser(etamax[k]-5,etamax[k]+5); eblascorr->Draw("colz,text"); t1.DrawLatex(0.83,0.875,"Las. corr."); sprintf(txt,"plots/Las_corr_zoomed_%d.png",k+1); c4.SaveAs(txt); } /* eblascorr->GetXaxis()->SetRangeUser(phimax-5,phimax+6); eblascorr->GetYaxis()->SetRangeUser(etamax-5,etamax+6); eblascorr->Draw("colz,text"); t1.DrawLatex(0.83,0.875,"Las. corr."); c4.SaveAs("exomgg_0t_rereco_ev3_eblascorr_zoom_photon2.png"); */ // EB laser correction map (all channels) c1.cd(); c1.SetLogz(0); eblascorrall->SetMaximum(2); eblascorrall->SetMinimum(0.1); eblascorrall->GetXaxis()->SetLabelSize(0.03); eblascorrall->GetYaxis()->SetLabelSize(0.03); eblascorrall->SetXTitle("i#phi"); eblascorrall->SetYTitle("i#eta"); eblascorrall->GetXaxis()->SetNdivisions(18); eblascorrall->GetYaxis()->SetNdivisions(2); eblascorrall->Draw("colz"); t1.SetTextSize(0.05); t1.DrawLatex(0.88,0.91,"Las. Corr."); c1.SaveAs("plots/exomgg_0t_rereco_ev3_eblascorr_all_photon2.png"); // EB laser correction map (all good channels) eblascorrgood->SetMaximum(2); eblascorrgood->SetMinimum(0.1); eblascorrgood->GetXaxis()->SetLabelSize(0.03); eblascorrgood->GetYaxis()->SetLabelSize(0.03); eblascorrgood->SetXTitle("i#phi"); eblascorrgood->SetYTitle("i#eta"); eblascorrgood->GetXaxis()->SetNdivisions(18); eblascorrgood->GetYaxis()->SetNdivisions(2); eblascorrgood->Draw("colz"); t1.SetTextSize(0.05); t1.DrawLatex(0.88,0.91,"Las. Corr."); c1.SaveAs("plots/exomgg_0t_rereco_ev3_eblascorr_good_photon2.png"); // EB laser correction 1d distributions gStyle->SetOptStat(1111110); c4.cd(); c4.SetLogy(1); eblascorrall_1d->SetLineColor(1); eblascorrall_1d->SetXTitle("Laser correction"); eblascorrall_1d->Draw(); c4.SaveAs("plots/exomgg_0t_rereco_ev3_eblascorr1d_all_photon2.png"); eblascorrgood_1d->SetLineColor(1); eblascorrgood_1d->SetXTitle("Laser correction"); eblascorrgood_1d->Draw(); c4.SaveAs("plots/exomgg_0t_rereco_ev3_eblascorr1d_good_photon2.png"); } <file_sep>/readme.txt 1) TO SET UP CODE: ----------------- setenv SCRAM_ARCH slc6_amd64_gcc493 cmsrel CMSSW_7_6_3 cd CMSSW_7_6_3/src cmsenv git-cms-addpkg JetMETCorrections/MCJet cd JetMETCorrections/MCJet rm -fr plugins/ cp /afs/cern.ch/user/p/petyt/public/EventCheck/code/plugins.zip . scramv1 b cp /afs/cern.ch/user/p/petyt/public/EventCheck/code/datacheck_cfg.py test/ 2) TO RUN CODE: -------------- <file_sep>/test/datacheck_cfg.py import FWCore.ParameterSet.Config as cms from RecoLocalCalo.EcalRecAlgos.ecalCleaningAlgo import cleaningAlgoConfig process = cms.Process("Ana") process.load("Configuration.Geometry.GeometryECALHCAL_cff") process.load("FWCore.MessageService.MessageLogger_cfi") from RecoEcal.Configuration.RecoEcal_cff import * process.load("EventFilter.EcalRawToDigi.EcalUnpackerMapping_cfi"); process.load("EventFilter.EcalRawToDigi.EcalUnpackerData_cfi"); process.ecalEBunpacker.InputLabel = cms.InputTag('rawDataCollector'); #process.ecalEBunpacker.InputLabel = cms.InputTag('source'); process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff") #process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.load("RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi") process.EcalLaserCorrectionService = cms.ESProducer("EcalLaserCorrectionService") # global tag for data #process.GlobalTag.globaltag = 'GR_R_53_V21A::All' # run 2 #process.GlobalTag.globaltag = '74X_dataRun2_Prompt_v4' #process.GlobalTag.globaltag = '74X_dataRun2_EcalCalib_v1' #process.GlobalTag.globaltag = '76X_dataRun2_v15' #process.GlobalTag.globaltag = '76X_dataRun2_v19' #process.GlobalTag.globaltag = '80X_dataRun2_Prompt_v9'# PATRIZIA process.GlobalTag.globaltag = '74X_dataRun2_Prompt_v1' # Matt ############# Set the number of events ############# process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) ############# Define the source file ############### process.source = cms.Source("PoolSource", fileNames=cms.untracked.vstring( # Data #'file:/afs/cern.ch/user/m/mquittna/public/exo/EXOMoriond16_v6_0T/pickeventsrunC.root' #'file:/afs/cern.ch/work/p/pbarria/public/SingleEvent/CMSSW_8_3_0/src/JetMETCorrections/MCJet/pick1eventRUN274244.root' # 'file:/afs/cern.ch/user/m/mjoyce/WorkingArea/Ecal/CMSSW_8_3_0/src/JetMETCorrections/MCJet/EventCheck/pickevents_test.root' 'file:/afs/cern.ch/user/m/mjoyce/WorkingArea/Ecal/CMSSW_8_3_0/src/JetMETCorrections/MCJet/EventCheck/pickevents.root' )) ############# Geometry ############### process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi"); process.load("Geometry.CaloEventSetup.CaloGeometry_cfi"); process.load("Geometry.CaloEventSetup.CaloTopology_cfi"); ############# Analyser options ############################ process.eventanalyser = cms.EDAnalyzer("EventAnalyser", jets = cms.string('ak5PFJets'), histogramFile = cms.string('exomgg_0t_runC.root'), tracks = cms.string('generalTracks'), vertex = cms.string('offlinePrimaryVertices'), JetCorrectionService = cms.string('L2L3JetCorrectorAK5PF'), EBRecHitCollection = cms.string('ReducedEcalRecHitsEB'), EERecHitCollection = cms.string('ReducedEcalRecHitsEE'), IsMC = cms.bool(False), # set to True if using MC cleaningConfig = cleaningAlgoConfig, # bunch structure, run 200473 - 50ns bunchstartbx = cms.vint32(66,146,226,306,413,493,573,653,773,853,960,1040,1120,1200,1307,1387,1467,1547,1667,1747,1854,1934,2014,2094,2201,2281,2361,2441,2549,2629,2736,2816,2896,2976,3083,3163,3243,3323) # bunch structure, run 209146 - 25ns #bunchstartbx = cms.vint32(301,358,1195,1252,2089,2146,2977,3034) # run 203708 #bunchstartbx = cms.vint32(1786,2680) ) process.noscraping = cms.EDFilter("FilterOutScraping", applyfilter = cms.untracked.bool(True), debugOn = cms.untracked.bool(False), numtrack = cms.untracked.uint32(10), thresh = cms.untracked.double(0.25) ) process.primaryVertexFilter = cms.EDFilter("GoodVertexFilter", vertexCollection = cms.InputTag('offlinePrimaryVertices'), minimumNDOF = cms.uint32(4) , maxAbsZ = cms.double(24), maxd0 = cms.double(2) ) process.load('CommonTools/RecoAlgos/HBHENoiseFilter_cfi') #process.load('RecoMET.METFilters.eeBadScFilter_cfi') ############# Path ########################### # data process.p = cms.Path( process.eventanalyser) ############# Format MessageLogger ################# process.MessageLogger.cerr.FwkReport.reportEvery = 1 <file_sep>/EventFinder.py #!/usr/bin/python import linecache import sys if len(sys.argv) < 1: print "Please specify filename.txt" filename = sys.argv[1] print filename nlines = 0 linenum = 0 text = 'DIGI found:' with open(filename) as f: for line in f: nlines += 1 if (line.find("kGood=0") >= 0): print "Found bad event!" print linecache.getline(filename,nlines-6) print linecache.getline(filename,nlines-2) s1 = linecache.getline(filename,nlines+17) if (len(s1)==13): for i in range(18,28): print linecache.getline(filename,nlines+i) <file_sep>/plugins/EventAnalyser.cc #include <iostream> #include <sstream> #include <istream> #include <fstream> #include <iomanip> #include <string> #include <cmath> #include <functional> #include "SimDataFormats/PileupSummaryInfo/interface/PileupSummaryInfo.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/CaloTowers/interface/CaloTowerCollection.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgoRcd.h" #include "RecoLocalCalo/EcalRecAlgos/interface/EcalCleaningAlgo.h" #include "DataFormats/EcalDigi/interface/EcalTrigPrimCompactColl.h" #include "DataFormats/EcalDetId/interface/EcalTrigTowerDetId.h" #include "DataFormats/EcalDigi/interface/EcalTriggerPrimitiveSample.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetup.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbRecord.h" #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbService.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPedestals.h" #include "CondFormats/DataRecord/interface/EcalADCToGeVConstantRcd.h" #include "CondFormats/EcalObjects/interface/EcalADCToGeVConstant.h" #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h" #include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTriggerRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTrigger.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/GenJet.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/ParticleFlowReco/interface/PFCluster.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHit.h" #include "DataFormats/ParticleFlowReco/interface/PFRecHitFwd.h" #include "DataFormats/ParticleFlowReco/interface/PFLayer.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "JetMETCorrections/MCJet/plugins/EventAnalyser.h" #include "JetMETCorrections/MCJet/plugins/JetUtilMC.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EgammaReco/interface/BasicCluster.h" #include "DataFormats/EgammaReco/interface/BasicClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "DataFormats/EcalDetId/interface/ESDetId.h" #include "DataFormats/EcalDetId/interface/EcalElectronicsId.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "RecoCaloTools/Navigation/interface/CaloNavigator.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" //#include "RecoEcal/EgammaCoreTools/interface/EcalClusterTools.h" #include "RecoEcal/EgammaCoreTools/interface/EcalTools.h" //#########################Added by <NAME>######################################## #include "DataFormats/EgammaCandidates/interface/GsfElectron.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" //#################################################################################### #include "Math/VectorUtil.h" #include "TVector3.h" using namespace edm; using namespace reco; using namespace std; DEFINE_FWK_MODULE(EventAnalyser); EventAnalyser::EventAnalyser(const edm::ParameterSet& cfg) : bunchstartbx_(cfg.getParameter<std::vector<int> >("bunchstartbx")) { jets_ = cfg.getParameter<std::string> ("jets"); histogramFile_ = cfg.getParameter<std::string> ("histogramFile"); tracks_ = cfg.getParameter<std::string> ("tracks"); vertex_coll_ = cfg.getParameter<std::string> ("vertex"); ebhitcoll_ = cfg.getParameter<std::string> ("EBRecHitCollection"); eehitcoll_ = cfg.getParameter<std::string> ("EERecHitCollection"); isMC_ = cfg.getParameter<bool>("IsMC"); tok_EB=consumes<EcalRecHitCollection>(edm::InputTag("reducedEcalRecHitsEB")); tok_EE=consumes<EcalRecHitCollection>(edm::InputTag("reducedEcalRecHitsEE")); tok_ES=consumes<EcalRecHitCollection>(edm::InputTag("reducedEcalRecHitsES")); tok_EB_digi=consumes<EBDigiCollection>(edm::InputTag("selectDigi","selectedEcalEBDigiCollection")); tok_EE_digi=consumes<EEDigiCollection>(edm::InputTag("selectDigi","selectedEcalEEDigiCollection")); edm::ParameterSet cleaningPs = cfg.getParameter<edm::ParameterSet>("cleaningConfig"); cleaningAlgo_ = new EcalCleaningAlgo(cleaningPs); } ////////////////////////////////////////////////////////////////////////////////////////// void EventAnalyser::beginJob() { //Creating the ouput file and the TTree file_ = new TFile(histogramFile_.c_str(),"RECREATE"); dataTree_ = new TTree("dataTree","dataTree"); evcount=0; //Making arrays for the calibrated and uncalibrated rechits(?) histograms for barrel and endcaps barrel_uncalibrh=new TH2F*[100]; endcap_uncalibrh=new TH2F*[100]; barrel_rh=new TH2F*[100]; endcap_rh=new TH2F*[100]; char txt[80]; for (Int_t i=0;i<100;i++) { //Initializing the histograms for each array element sprintf(txt,"barrel_uncalibrh_ev%03d",i+1); barrel_uncalibrh[i] = new TH2F(txt,txt,360,0,360,170,-85,85); sprintf(txt,"barrel_rh_ev%03d",i+1); barrel_rh[i] = new TH2F(txt,txt,360,0,360,170,-85,85); sprintf(txt,"endcap_uncalibrh_ev%03d",i+1); endcap_uncalibrh[i] = new TH2F(txt,txt,200,0,200,100,0,100); sprintf(txt,"endcap_rh_ev%03d",i+1); endcap_rh[i] = new TH2F(txt,txt,200,0,200,100,0,100); } //Initializing all of the other histograms eboccet = new TH2F("eboccet","",360,0,360,170,-85,85); ebtime = new TH2F("ebtime","",360,0,360,170,-85,85); eeoccet = new TH2F("eeoccet","",200,0,200,100,0,100); eetime = new TH2F("eetime","",200,0,200,100,0,100); eboccet_kgood = new TH2F("eboccet_kgood","",360,0,360,170,-85,85); eeoccet_kgood = new TH2F("eeoccet_kgood","",200,0,200,100,0,100); ebflag_kweird = new TH2F("ebflag_kweird","",360,0,360,170,-85,85); eeflag_kweird = new TH2F("eeflag_kweird","",200,0,200,100,0,100); ebflag_kdiweird = new TH2F("ebflag_kdiweird","",360,0,360,170,-85,85); eeflag_kdiweird = new TH2F("eeflag_kdiweird","",200,0,200,100,0,100); ebflag_koot = new TH2F("ebflag_koot","",360,0,360,170,-85,85); eeflag_koot = new TH2F("eeflag_koot","",200,0,200,100,0,100); esoccet_esp1 = new TH2F("esoccet_esp1","",40,0.5,40.5,40,0.5,40.5); esoccet_esp2 = new TH2F("esoccet_esp2","",40,0.5,40.5,40,0.5,40.5); esoccet_esm1 = new TH2F("esoccet_esm1","",40,0.5,40.5,40,0.5,40.5); esoccet_esm2 = new TH2F("esoccet_esm2","",40,0.5,40.5,40,0.5,40.5); eepocc_etaphi = new TH2F("eepocc_etaphi","",50,1.5,3.0,50,-3.14,3.14); eemocc_etaphi = new TH2F("eemocc_etaphi","",50,-3.0,-1.5,50,-3.14,3.14); esp1occ_etaphi = new TH2F("esp1occ_etaphi","",50,1.5,3.0,50,-3.14,3.14); esm1occ_etaphi = new TH2F("esm1occ_etaphi","",50,-3.0,-1.5,50,-3.14,3.14); esp2occ_etaphi = new TH2F("esp2occ_etaphi","",50,1.5,3.0,50,-3.14,3.14); esm2occ_etaphi = new TH2F("esm2occ_etaphi","",50,-3.0,-1.5,50,-3.14,3.14); ebchstatus=new TH2D("ebchstatus","",360,0,360,170,-85,85); eechstatus=new TH2D("eechstatus","",200,0,200,100,0,100); ebpedmean_g12=new TH2D("ebpedmean_g12","",360,0,360,170,-85,85); ebpedmean_g6=new TH2D("ebpedmean_g6","",360,0,360,170,-85,85); ebpedmean_g1=new TH2D("ebpedmean_g1","",360,0,360,170,-85,85); ebpedrms_g12=new TH2D("ebpedrms_g12","",360,0,360,170,-85,85); ebpedrms_g6=new TH2D("ebpedrms_g6","",360,0,360,170,-85,85); ebpedrms_g1=new TH2D("ebpedrms_g1","",360,0,360,170,-85,85); eepedmean_g12=new TH2D("eepedmean_g12","",200,0,200,100,0,100); eepedmean_g6=new TH2D("eepedmean_g6","",200,0,200,100,0,100); eepedmean_g1=new TH2D("eepedmean_g1","",200,0,200,100,0,100); eepedrms_g12=new TH2D("eepedrms_g12","",200,0,200,100,0,100); eepedrms_g6=new TH2D("eepedrms_g6","",200,0,200,100,0,100); eepedrms_g1=new TH2D("eepedrms_g1","",200,0,200,100,0,100); ebicval=new TH2D("ebicval","",360,0,360,170,-85,85); eeicval=new TH2D("eeicval","",200,0,200,100,0,100); eblascorr=new TH2D("eblascorr","",360,0,360,170,-85,85); eelascorr=new TH2D("eelascorr","",200,0,200,100,0,100); // run/event info // Setting the branch addresses dataTree_->Branch("run", &run, "run/I"); dataTree_->Branch("ev", &ev, "ev/I"); dataTree_->Branch("lumi", &lumi, "lumi/I"); dataTree_->Branch("bx", &bx, "bx/I"); dataTree_->Branch("orbit", &orbit, "orbit/I"); dataTree_->Branch("bunchintrain", &bunchintrain, "bunchintrain/I"); // primary vertex info dataTree_->Branch("numvtx", &numvtx, "numvtx/I"); dataTree_->Branch("numgoodvtx", &numgoodvtx, "numgoodvtx/I"); // rechit info dataTree_->Branch("rechit_ene", &rechit_ene, "rechit_ene/F"); dataTree_->Branch("rechit_et", &rechit_et, "rechit_et/F"); dataTree_->Branch("rechit_time", &rechit_time, "rechit_time/F"); dataTree_->Branch("rechit_ieta", &rechit_ieta, "rechit_ieta/I"); dataTree_->Branch("rechit_iphi", &rechit_iphi, "rechit_iphi/I"); dataTree_->Branch("rechit_eta", &rechit_eta, "rechit_eta/F"); dataTree_->Branch("rechit_phi", &rechit_phi, "rechit_phi/F"); dataTree_->Branch("rechit_swisscross", &rechit_swisscross, "rechit_swisscross/F"); dataTree_->Branch("rechit_chi2", &rechit_chi2, "rechit_chi2/F"); dataTree_->Branch("rechit_chi2oot", &rechit_chi2oot, "rechit_chi2oot/F"); dataTree_->Branch("rechit_flag_kweird", &rechit_flag_kweird, "rechit_flag_kweird/I"); dataTree_->Branch("rechit_flag_kdiweird", &rechit_flag_kdiweird, "rechit_flag_kdiweird/I"); dataTree_->Branch("rechit_flag_koot", &rechit_flag_koot, "rechit_flag_koot/I"); // db info dataTree_->Branch("db_pedg12", &db_pedg12, "db_pedg12/F"); dataTree_->Branch("db_pedg6", &db_pedg6, "db_pedg6/F"); dataTree_->Branch("db_pedg1", &db_pedg1, "db_pedg1/F"); dataTree_->Branch("db_pedrmsg12", &db_pedrmsg12, "db_pedrmsg12/F"); dataTree_->Branch("db_pedrmsg6", &db_pedrmsg6, "db_pedrmsg6/F"); dataTree_->Branch("db_pedrmsg1", &db_pedrmsg1, "db_pedrmsg1/F"); dataTree_->Branch("lasercorr", &lasercorr, "lasercorr/F"); // digi info dataTree_->Branch("digi_adc", &digi_adc, "digi_adc[10]/I"); dataTree_->Branch("digi_gainid", &digi_gainid, "digi_gainid[10]/I"); // sumet dataTree_->Branch("ebsumet", &ebsumet, "ebsumet/F"); dataTree_->Branch("eesumet", &eesumet, "eesumet/F"); dataTree_->Branch("ebsumet_kgood", &ebsumet_kgood, "ebsumet_kgood/F"); dataTree_->Branch("eesumet_kgood", &eesumet_kgood, "eesumet_kgood/F"); } ////////////////////////////////////////////////////////////////////////////////////////// void EventAnalyser::endJob() { if (file_ !=0) { file_->cd(); dataTree_ ->Write(); ebchstatus->Write(); eechstatus->Write(); ebpedmean_g12->Write(); ebpedmean_g6->Write(); ebpedmean_g1->Write(); ebpedrms_g12->Write(); ebpedrms_g6->Write(); ebpedrms_g1->Write(); eepedmean_g12->Write(); eepedmean_g6->Write(); eepedmean_g1->Write(); eepedrms_g12->Write(); eepedrms_g6->Write(); eepedrms_g1->Write(); ebicval->Write(); eeicval->Write(); eblascorr->Write(); eelascorr->Write(); eboccet->Write(); eeoccet->Write(); ebtime->Write(); eetime->Write(); eboccet_kgood->Write(); eeoccet_kgood->Write(); ebflag_kweird->Write(); eeflag_kweird->Write(); ebflag_kdiweird->Write(); eeflag_kdiweird->Write(); ebflag_koot->Write(); eeflag_koot->Write(); esoccet_esp1->Write(); esoccet_esp2->Write(); esoccet_esm1->Write(); esoccet_esm2->Write(); eepocc_etaphi->Write(); eemocc_etaphi->Write(); esp1occ_etaphi->Write(); esp2occ_etaphi->Write(); esm1occ_etaphi->Write(); esm2occ_etaphi->Write(); for (Int_t i=0;i<100;i++) { barrel_uncalibrh[i]->Write(); endcap_uncalibrh[i]->Write(); barrel_rh[i]->Write(); endcap_rh[i]->Write(); } } file_ = 0; } ////////////////////////////////////////////////////////////////////////////////////////// float EventAnalyser::recHitE( const DetId id, const EcalRecHitCollection & recHits, int di, int dj ) { // in the barrel: di = dEta dj = dPhi // in the endcap: di = dX dj = dY DetId nid; if( id.subdetId() == EcalBarrel) nid = EBDetId::offsetBy( id, di, dj ); else if( id.subdetId() == EcalEndcap) nid = EEDetId::offsetBy( id, di, dj ); return ( nid == DetId(0) ? 0 : recHitE( nid, recHits ) ); } float EventAnalyser::recHitE( const DetId id, const EcalRecHitCollection &recHits) { if ( id.rawId() == 0 ) return 0; EcalRecHitCollection::const_iterator it = recHits.find( id ); if ( it != recHits.end() ){ float ene= (*it).energy(); return ene; } return 0; } ////////////////////////////////////////////////////////////////////////////////////////// void EventAnalyser::analyze(edm::Event const& event, edm::EventSetup const& iSetup) { for (int i=0;i<10;i++) { digi_adc[i]=0; digi_gainid[i]=0; } run=0, ev=0, lumi=0, bx=0, orbit=0; numvtx=0; numgoodvtx=0; edm::ESHandle<EcalLaserDbService> laser; iSetup.get<EcalLaserDbRecord>().get(laser); run = event.id().run(); ev = event.id().event(); lumi = event.luminosityBlock(); bx = event.bunchCrossing(); orbit = event.orbitNumber(); cout << "RUN=" << run << " EVENT=" << ev << " lumi=" << lumi << endl; // if (run==258440 && ev==108011587) { // get position in bunch train bunchintrain=-1; for (std::vector<int>::const_iterator bxit=bunchstartbx_.begin(); bxit!=bunchstartbx_.end(); ++bxit) { Int_t bxpos=bx - *bxit; // 50ns if (bxpos>=0 && bxpos<=70) bunchintrain=bxpos/2; // 25ns // if (bxpos>=0 && bxpos<=50) bunchintrain=bxpos; } /* edm::Handle<VertexCollection> vertices; event.getByLabel(vertex_coll_,vertices); VertexCollection::const_iterator vit; numvtx=vertices->size(); if (vertices->size()>0) { for (vit=vertices->begin();vit!=vertices->end();++vit) { int vtx_chi2=vit->chi2(); int vtx_ndof=vit->ndof(); int vtx_isfake=vit->isFake(); if (vit->isValid() && vtx_isfake==0 && vtx_ndof>4 && vtx_chi2>0 && vtx_chi2<10000) { numgoodvtx++; } } } */ edm::ESHandle<CaloGeometry> pG; iSetup.get<CaloGeometryRecord>().get(pG); const CaloGeometry* geo=pG.product(); edm::ESHandle<CaloTopology> pTopology; iSetup.get<CaloTopologyRecord>().get(pTopology); edm::ESHandle<EcalChannelStatus> chanstat; iSetup.get<EcalChannelStatusRcd>().get(chanstat); edm::ESHandle<EcalPedestals> ecalped; iSetup.get<EcalPedestalsRcd>().get(ecalped); const EcalPedestals* eped=ecalped.product(); edm::ESHandle<EcalADCToGeVConstant> ecaladcgev; iSetup.get<EcalADCToGeVConstantRcd>().get(ecaladcgev); const EcalADCToGeVConstant* eadcgev=ecaladcgev.product(); float adctogevconst=eadcgev->getEBValue(); float adctogevconstee=eadcgev->getEEValue(); edm::ESHandle<EcalIntercalibConstants> ecalic; iSetup.get<EcalIntercalibConstantsRcd>().get(ecalic); const EcalIntercalibConstants* eic=ecalic.product(); // Rechit Collection edm::Handle<EcalRecHitCollection> EBhits; edm::Handle<EcalRecHitCollection> EEhits; edm::Handle<ESRecHitCollection> EShits; // AOD event.getByToken(tok_EB,EBhits); event.getByToken(tok_EE,EEhits); event.getByToken(tok_ES,EShits); // RECO // event.getByLabel("ecalRecHit","EcalRecHitsEB",EBhits); // event.getByLabel("ecalRecHit","EcalRecHitsEE",EEhits); edm:: Handle<EBDigiCollection> EBdigis; event.getByToken(tok_EB_digi,EBdigis); // event.getByLabel("ecalDigis","ebDigis",EBdigis); edm::Handle<EEDigiCollection> EEdigis; event.getByToken(tok_EE_digi,EEdigis); //event.getByLabel("ecalDigis","eeDigis",EEdigis); // Handle<EcalUncalibratedRecHitCollection> EBhitsU_multi10; // Handle<EcalUncalibratedRecHitCollection> EEhitsU_multi10; // event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEB","reRECO"),EBhitsU_multi10); // event.getByLabel(edm::InputTag("ecalMultiFitUncalibRecHit","EcalUncalibRecHitsEE","reRECO"),EEhitsU_multi10); /* for (EcalUncalibratedRecHitCollection::const_iterator hitItr6 = EBhitsU_multi10->begin(); hitItr6 != EBhitsU_multi10->end(); ++hitItr6) { EcalUncalibratedRecHit hit6 = (*hitItr6); EBDetId det6 = hit6.id(); Float_t ucrechit_ampl_eb = hit6.amplitude(); int rechit_ieta = det6.ieta(); int rechit_iphi = det6.iphi(); cout << "UCRECHIT, eta,phi,ampl=" << rechit_ieta << ":" << rechit_iphi << ":" << ucrechit_ampl_eb << endl; if (evcount<100) { barrel_uncalibrh[evcount]->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),ucrechit_ampl_eb); } } for (EcalUncalibratedRecHitCollection::const_iterator hitItr6 = EEhitsU_multi10->begin(); hitItr6 != EEhitsU_multi10->end(); ++hitItr6) { // cout << "in EE loop4" << endl; EcalUncalibratedRecHit hit6 = (*hitItr6); EEDetId det6 = hit6.id(); Float_t ucrechit_ampl_ee = hit6.amplitude(); int rechit_ix = det6.ix(); int rechit_iy = det6.iy(); int rechit_iz = det6.zside(); if (evcount<100) { endcap_uncalibrh[evcount]->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,ucrechit_ampl_ee); } } */ float db_pedg12=0, db_pedg6=0, db_pedg1=0; float db_pedrmsg12=0, db_pedrmsg6=0, db_pedrmsg1=0; for (Int_t i=0;i<360;i++) { for (Int_t j=0;j<170;j++) { int iphitmp=i+1; int ietatmp=j-85+1*(j>84); // cout << iphitmp << ":" << ietatmp << endl; if (EBDetId::validDetId(ietatmp,iphitmp)) { EBDetId deteb(ietatmp,iphitmp,0); int ebhashedid = deteb.hashedIndex(); const EcalIntercalibConstantMap &icalMap=eic->getMap(); EcalIntercalibConstantMap::const_iterator icalit=icalMap.find(deteb); float icalconst=0; if (icalit!=icalMap.end()) icalconst=(*icalit); ebicval->SetBinContent(i+1,j+1,icalconst); lasercorr=0; lasercorr=laser->getLaserCorrection(EBDetId(deteb), event.time()); eblascorr->SetBinContent(i+1,j+1,lasercorr); const EcalPedestals::Item *aped=0; aped=&eped->barrel(ebhashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; ebpedmean_g12->SetBinContent(i+1,j+1,db_pedg12); ebpedmean_g6->SetBinContent(i+1,j+1,db_pedg6); ebpedmean_g1->SetBinContent(i+1,j+1,db_pedg1); ebpedrms_g12->SetBinContent(i+1,j+1,db_pedrmsg12); ebpedrms_g6->SetBinContent(i+1,j+1,db_pedrmsg6); ebpedrms_g1->SetBinContent(i+1,j+1,db_pedrmsg1); EcalChannelStatusCode chstatcode; EcalChannelStatusMap::const_iterator chit=chanstat->find(deteb); if (chit!=chanstat->end()) { chstatcode=*chit; ebchstatus->SetBinContent(i+1,j+1,chstatcode.getEncodedStatusCode()); } } } } for (Int_t i=0;i<100;i++) { for (Int_t j=0;j<100;j++) { for (Int_t k=0;k<2;k++) { int ixtmp=i+1; int iytmp=j+1; int iztmp=-1+2*(k>0); if (EEDetId::validDetId(ixtmp,iytmp,iztmp)) { EEDetId detee(ixtmp,iytmp,iztmp,0); int eehashedid = detee.hashedIndex(); const EcalPedestals::Item *aped=0; aped=&eped->endcap(eehashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; eepedmean_g12->SetBinContent(i+1+100*k,j+1,db_pedg12); eepedmean_g6->SetBinContent(i+1+100*k,j+1,db_pedg6); eepedmean_g1->SetBinContent(i+1+100*k,j+1,db_pedg1); eepedrms_g12->SetBinContent(i+1+100*k,j+1,db_pedrmsg12); eepedrms_g6->SetBinContent(i+1+100*k,j+1,db_pedrmsg6); eepedrms_g1->SetBinContent(i+1+100*k,j+1,db_pedrmsg1); const EcalIntercalibConstantMap &icalMap=eic->getMap(); EcalIntercalibConstantMap::const_iterator icalit=icalMap.find(detee); float icalconst=0; if (icalit!=icalMap.end()) icalconst=(*icalit); eeicval->SetBinContent(i+1+100*k,j+1,icalconst); lasercorr=0; lasercorr=laser->getLaserCorrection(EEDetId(detee), event.time()); eelascorr->SetBinContent(i+1+100*k,j+1,lasercorr); EcalChannelStatusCode chstatcode; EcalChannelStatusMap::const_iterator chit=chanstat->find(detee); if (chit!=chanstat->end()) { chstatcode=*chit; eechstatus->SetBinContent(i+1+100*k,j+1,chstatcode.getEncodedStatusCode()); } } } } } // Rechit loop cout << "\n\n****EB HITS****" << endl; ebsumet=0, ebsumet_kgood=0; int rechit_flag_kgood=0; for (EcalRecHitCollection::const_iterator hitItr = EBhits->begin(); hitItr != EBhits->end(); ++hitItr) { rechit_flag_kweird=0; rechit_flag_kdiweird=0; rechit_flag_koot=0; rechit_flag_kgood=0; Int_t ee_kGood=0; Int_t ee_kPoorReco=0; Int_t ee_kOutOfTime=0; Int_t ee_kFaultyHardware=0; Int_t ee_kNoisy=0; Int_t ee_kPoorCalib=0; Int_t ee_kSaturated=0; Int_t ee_kLeadingEdgeRecovered=0; Int_t ee_kNeighboursRecovered=0; Int_t ee_kTowerRecovered=0; Int_t ee_kDead=0; Int_t ee_kKilled=0; Int_t ee_kTPSaturated=0; Int_t ee_kL1SpikeFlag=0; Int_t ee_kWeird=0; Int_t ee_kDiWeird=0; Int_t ee_kUnknown=0; rechit_swisscross=0; rechit_ene=0, rechit_et=0, rechit_time=0; rechit_ieta=0, rechit_iphi=0, rechit_eta=0, rechit_phi=0; rechit_chi2=0, rechit_chi2oot=0; db_pedg12=0, db_pedg6=0, db_pedg1=0; db_pedrmsg12=0, db_pedrmsg6=0, db_pedrmsg1=0; lasercorr=0; EcalRecHit hit = (*hitItr); EBDetId det = hit.id(); rechit_ieta = det.ieta(); rechit_iphi = det.iphi(); rechit_ene = hit.energy(); rechit_time = hit.time(); rechit_chi2 = hit.chi2(); // rechit_chi2oot = hit.outOfTimeChi2(); // not used in Run 2 int ebhashedid = det.hashedIndex(); GlobalPoint poseb=geo->getPosition(hit.detid()); rechit_eta=poseb.eta(); rechit_phi=poseb.phi(); float pf=1.0/cosh(rechit_eta); rechit_et=rechit_ene*pf; if (evcount<100) { barrel_rh[evcount]->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),rechit_et); } // if (rechit_et<3.0) continue; // swiss-cross calculation float s41=0; float s42=0; float s43=0; float s44=0; s41 = recHitE( det, *EBhits, 1, 0 ); s42 = recHitE( det, *EBhits, -1, 0 ); s43 = recHitE( det, *EBhits, 0, 1 ); s44 = recHitE( det, *EBhits, 0, -1 ); float s4=s41+s42+s43+s44; if (rechit_ene>0) rechit_swisscross=1.0-s4/rechit_ene; // read pedestals from DB const EcalPedestals::Item *aped=0; aped=&eped->barrel(ebhashedid); db_pedg12=aped->mean_x12; db_pedg6=aped->mean_x6; db_pedg1=aped->mean_x1; db_pedrmsg12=aped->rms_x12; db_pedrmsg6=aped->rms_x6; db_pedrmsg1=aped->rms_x1; // read lasercalib from db lasercorr=laser->getLaserCorrection(EBDetId(det), event.time()); const EcalIntercalibConstantMap &icalMap=eic->getMap(); EcalIntercalibConstantMap::const_iterator icalit=icalMap.find(det); float icalconst=0; if (icalit!=icalMap.end()) icalconst=(*icalit); if (hit.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot=1; if (rechit_flag_kweird+rechit_flag_kdiweird+rechit_flag_koot==0) rechit_flag_kgood=1; if (rechit_et>0.5) { ebsumet+=rechit_et; if (rechit_flag_kgood) ebsumet_kgood+=rechit_et; } eboccet->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),rechit_et); if (rechit_flag_kgood) { eboccet_kgood->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),rechit_et); } if (rechit_flag_kweird) ebflag_kweird->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),1); if (rechit_flag_kdiweird) ebflag_kdiweird->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),1); if (rechit_flag_koot) ebflag_koot->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),1); // select high energy hits if (rechit_et>1.0) { ebtime->Fill(rechit_iphi-0.5,rechit_ieta+0.5-1*(rechit_ieta>0),rechit_time); cout << "\nieta,iphi=" << rechit_ieta << " " << rechit_iphi << " energy=" << rechit_ene << " eta,phi=" << rechit_eta << " " << rechit_phi << " et=" << rechit_et << " time=" << rechit_time << endl; cout << "swisscross=" << rechit_swisscross << " lasercorr=" << lasercorr << " chi2=" << rechit_chi2 << endl; cout << "kWeird=" << rechit_flag_kweird << " kDiWeird=" << rechit_flag_kdiweird << " kOOT=" << rechit_flag_koot << endl; cout << "calibration values: lasercalib: " << lasercorr << " ic: " << icalconst << " adc/gev: " << adctogevconst << endl; cout << "pedestal values: " << " G12: " << db_pedg12 << "," << db_pedrmsg12 << " G6: " << db_pedg6 << "," << db_pedrmsg6 << " G1: " << db_pedg1 << "," << db_pedrmsg1 << endl; cout<< "Rechit flags:" << endl; if (hit.checkFlag(EcalRecHit::kGood)) ee_kGood=1; if (hit.checkFlag(EcalRecHit::kPoorReco)) ee_kPoorReco=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) ee_kOutOfTime=1; if (hit.checkFlag(EcalRecHit::kFaultyHardware)) ee_kFaultyHardware=1; if (hit.checkFlag(EcalRecHit::kNoisy)) ee_kNoisy=1; if (hit.checkFlag(EcalRecHit::kPoorCalib)) ee_kPoorCalib=1; if (hit.checkFlag(EcalRecHit::kSaturated)) ee_kSaturated=1; if (hit.checkFlag(EcalRecHit::kLeadingEdgeRecovered)) ee_kLeadingEdgeRecovered=1; if (hit.checkFlag(EcalRecHit::kNeighboursRecovered)) ee_kNeighboursRecovered=1; if (hit.checkFlag(EcalRecHit::kTowerRecovered)) ee_kTowerRecovered=1; if (hit.checkFlag(EcalRecHit::kDead)) ee_kDead=1; if (hit.checkFlag(EcalRecHit::kKilled)) ee_kKilled=1; if (hit.checkFlag(EcalRecHit::kTPSaturated)) ee_kTPSaturated=1; if (hit.checkFlag(EcalRecHit::kL1SpikeFlag)) ee_kL1SpikeFlag=1; if (hit.checkFlag(EcalRecHit::kWeird)) ee_kWeird=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) ee_kDiWeird=1; if (hit.checkFlag(EcalRecHit::kUnknown)) ee_kUnknown=1; cout << " kGood=" << ee_kGood << endl; cout << " kPoorReco=" << ee_kPoorReco << endl;; cout << " kOutOfTime=" << ee_kOutOfTime << endl;; cout << " kFaultyHardware=" << ee_kFaultyHardware << endl; cout << " kNoisy=" << ee_kNoisy << endl; cout << " kPoorCalib=" << ee_kPoorCalib << endl;; cout << " kSaturated=" << ee_kSaturated << endl; cout << " kLeadingEdgeRecovered=" << ee_kLeadingEdgeRecovered << endl; cout << " kNeighboursRecovered=" << ee_kNeighboursRecovered << endl; cout << " kTowerRecovered=" << ee_kTowerRecovered << endl; cout << " kDead=" << ee_kDead << endl; cout << " kKilled=" << ee_kKilled << endl; cout << " kTPSaturated=" << ee_kTPSaturated << endl; cout << " kL1SpikeFlag=" << ee_kL1SpikeFlag << endl; cout << " kWeird=" << ee_kWeird << endl; cout << " kDiWeird=" << ee_kDiWeird << endl; cout << " kUnknown=" << ee_kUnknown << endl; // find digi corresponding to rechit EBDigiCollection::const_iterator digiItrEB= EBdigis->begin(); while(digiItrEB != EBdigis->end() && digiItrEB->id() != hitItr->id()) { digiItrEB++; } if (digiItrEB != EBdigis->end()) { cout << "DIGI found: " << endl; EBDataFrame df(*digiItrEB); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); digi_adc[i]=ebdigiadc; digi_gainid[i]=ebdigigain; cout << "sample=" << i+1 << " adc=" << digi_adc[i] << " gainid=" << digi_gainid[i] << endl; } } } } // EE Rechit loop eesumet=0, eesumet_kgood=0; Float_t eepsumet=0; Float_t eemsumet=0; cout << "\n\n****EE HITS****" << endl; for (EcalRecHitCollection::const_iterator hitItr = EEhits->begin(); hitItr != EEhits->end(); ++hitItr) { rechit_flag_kweird=0; rechit_flag_kdiweird=0; rechit_flag_koot=0; rechit_flag_kgood=0; Int_t ee_kGood=0; Int_t ee_kPoorReco=0; Int_t ee_kOutOfTime=0; Int_t ee_kFaultyHardware=0; Int_t ee_kNoisy=0; Int_t ee_kPoorCalib=0; Int_t ee_kSaturated=0; Int_t ee_kLeadingEdgeRecovered=0; Int_t ee_kNeighboursRecovered=0; Int_t ee_kTowerRecovered=0; Int_t ee_kDead=0; Int_t ee_kKilled=0; Int_t ee_kTPSaturated=0; Int_t ee_kL1SpikeFlag=0; Int_t ee_kWeird=0; Int_t ee_kDiWeird=0; Int_t ee_kUnknown=0; rechit_swisscross=0; rechit_ene=0, rechit_et=0, rechit_time=0; rechit_ieta=0, rechit_iphi=0, rechit_eta=0, rechit_phi=0; rechit_chi2=0, rechit_chi2oot=0; lasercorr=0; int rechit_ix=0; int rechit_iy=0; int rechit_iz=0; EcalRecHit hit = (*hitItr); EEDetId det = hit.id(); rechit_ix = det.ix(); rechit_iy = det.iy(); rechit_iz = det.zside(); rechit_ene = hit.energy(); rechit_time = hit.time(); rechit_chi2 = hit.chi2(); // rechit_chi2oot = hit.outOfTimeChi2(); // not used in Run 2 int eehashedid = det.hashedIndex(); const EcalPedestals::Item *aped=0; aped=&eped->endcap(eehashedid); float eedb_pedg12=aped->mean_x12; float eedb_pedg6=aped->mean_x6; float eedb_pedg1=aped->mean_x1; float eedb_pedrmsg12=aped->rms_x12; float eedb_pedrmsg6=aped->rms_x6; float eedb_pedrmsg1=aped->rms_x1; const EcalIntercalibConstantMap &icalMap=eic->getMap(); EcalIntercalibConstantMap::const_iterator icalit=icalMap.find(det); float eeicalconst=0; if (icalit!=icalMap.end()) eeicalconst=(*icalit); if (hit.checkFlag(EcalRecHit::kGood)) ee_kGood=1; if (hit.checkFlag(EcalRecHit::kPoorReco)) ee_kPoorReco=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) ee_kOutOfTime=1; if (hit.checkFlag(EcalRecHit::kFaultyHardware)) ee_kFaultyHardware=1; if (hit.checkFlag(EcalRecHit::kNoisy)) ee_kNoisy=1; if (hit.checkFlag(EcalRecHit::kPoorCalib)) ee_kPoorCalib=1; if (hit.checkFlag(EcalRecHit::kSaturated)) ee_kSaturated=1; if (hit.checkFlag(EcalRecHit::kLeadingEdgeRecovered)) ee_kLeadingEdgeRecovered=1; if (hit.checkFlag(EcalRecHit::kNeighboursRecovered)) ee_kNeighboursRecovered=1; if (hit.checkFlag(EcalRecHit::kTowerRecovered)) ee_kTowerRecovered=1; if (hit.checkFlag(EcalRecHit::kDead)) ee_kDead=1; if (hit.checkFlag(EcalRecHit::kKilled)) ee_kKilled=1; if (hit.checkFlag(EcalRecHit::kTPSaturated)) ee_kTPSaturated=1; if (hit.checkFlag(EcalRecHit::kL1SpikeFlag)) ee_kL1SpikeFlag=1; if (hit.checkFlag(EcalRecHit::kWeird)) ee_kWeird=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) ee_kDiWeird=1; if (hit.checkFlag(EcalRecHit::kUnknown)) ee_kUnknown=1; GlobalPoint poseb=geo->getPosition(hit.detid()); rechit_eta=poseb.eta(); rechit_phi=poseb.phi(); float pf=1.0/cosh(rechit_eta); rechit_et=rechit_ene*pf; if (evcount<100) { endcap_rh[evcount]->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,rechit_et); } // if (rechit_et<3.0) continue; // swiss-cross calculation float s41=0; float s42=0; float s43=0; float s44=0; s41 = recHitE( det, *EEhits, 1, 0 ); s42 = recHitE( det, *EEhits, -1, 0 ); s43 = recHitE( det, *EEhits, 0, 1 ); s44 = recHitE( det, *EEhits, 0, -1 ); float s4=s41+s42+s43+s44; if (rechit_ene>0) rechit_swisscross=1.0-s4/rechit_ene; // read lasercalib from db lasercorr=laser->getLaserCorrection(EEDetId(det), event.time()); if (hit.checkFlag(EcalRecHit::kWeird)) rechit_flag_kweird=1; if (hit.checkFlag(EcalRecHit::kDiWeird)) rechit_flag_kdiweird=1; if (hit.checkFlag(EcalRecHit::kOutOfTime)) rechit_flag_koot=1; if (rechit_flag_kweird+rechit_flag_kdiweird+rechit_flag_koot==0) rechit_flag_kgood=1; if (rechit_et>0.5) { eesumet+=rechit_et; if (rechit_flag_kgood) eesumet_kgood+=rechit_et; if (rechit_flag_kgood && rechit_iz==1) eepsumet+=rechit_et; if (rechit_flag_kgood && rechit_iz==-1) eemsumet+=rechit_et; } eeoccet->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,rechit_et); if (rechit_flag_kgood) { eeoccet_kgood->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,rechit_et); if (rechit_eta>0) eepocc_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); if (rechit_eta<0) eemocc_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); } if (rechit_flag_kweird) eeflag_kweird->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,1.); if (rechit_flag_kdiweird) eeflag_kdiweird->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,1.); if (rechit_flag_koot) eeflag_koot->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,1.); // select high energy hits if (rechit_et>1.0) { eetime->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,rechit_time); cout << "\nix,iy,iz=" << rechit_ix << " " << rechit_iy << " " << rechit_iz << " eta,phi=" << rechit_eta << " " << rechit_phi << " energy=" << rechit_ene << " et=" << rechit_et << " time=" << rechit_time << endl; cout << "swisscross=" << rechit_swisscross << " lasercorr=" << lasercorr << " chi2=" << rechit_chi2 << endl; // cout << "kWeird=" << rechit_flag_kweird << " kDiWeird=" << rechit_flag_kdiweird << " kOOT=" << rechit_flag_koot << endl; cout << "calibration values: lasercalib: " << lasercorr << " ic: " << eeicalconst << " adc/gev: " << adctogevconstee << endl; cout << "pedestal values: " << " G12: " << eedb_pedg12 << "," << eedb_pedrmsg12 << " G6: " << eedb_pedg6 << "," << eedb_pedrmsg6 << " G1: " << eedb_pedg1 << "," << eedb_pedrmsg1 << endl; cout<< "Rechit flags:" << endl; cout << " kGood=" << ee_kGood << endl; cout << " kPoorReco=" << ee_kPoorReco << endl;; cout << " kOutOfTime=" << ee_kOutOfTime << endl;; cout << " kFaultyHardware=" << ee_kFaultyHardware << endl; cout << " kNoisy=" << ee_kNoisy << endl; cout << " kPoorCalib=" << ee_kPoorCalib << endl;; cout << " kSaturated=" << ee_kSaturated << endl; cout << " kLeadingEdgeRecovered=" << ee_kLeadingEdgeRecovered << endl; cout << " kNeighboursRecovered=" << ee_kNeighboursRecovered << endl; cout << " kTowerRecovered=" << ee_kTowerRecovered << endl; cout << " kDead=" << ee_kDead << endl; cout << " kKilled=" << ee_kKilled << endl; cout << " kTPSaturated=" << ee_kTPSaturated << endl; cout << " kL1SpikeFlag=" << ee_kL1SpikeFlag << endl; cout << " kWeird=" << ee_kWeird << endl; cout << " kDiWeird=" << ee_kDiWeird << endl; cout << " kUnknown=" << ee_kUnknown << endl; // find digi corresponding to rechit EEDigiCollection::const_iterator digiItrEE= EEdigis->begin(); while(digiItrEE != EEdigis->end() && digiItrEE->id() != hitItr->id()) { digiItrEE++; } if (digiItrEE != EEdigis->end()) { cout << "DIGI found: " << endl; EEDataFrame df(*digiItrEE); for(int i=0; i<10;++i) { int ebdigiadc=df.sample(i).adc(); int ebdigigain=df.sample(i).gainId(); digi_adc[i]=ebdigiadc; digi_gainid[i]=ebdigigain; cout << "sample=" << i+1 << " adc=" << digi_adc[i] << " gainid=" << digi_gainid[i] << endl; } } } } //################################Added by <NAME>################################## //electron stuff edm::Handle<reco::GsfElectronCollection> EBelec; event.getByToken(tok_elec,EBelec); for (reco::GsfElectronCollection::const_iterator gsfIter=EBelec->begin(); gsfIter!=EBelec->end(); gsfIter++) { float elec_eta=gsfIter->eta(); float elec_phi=gsfIter->phi(); float elec_pt=gsfIter->pt(); float elec_et=gsfIter->superCluster()->energy()/cosh(gsfIter->superCluster()->eta()); cout << "\nelec eta,phi=" << elec_eta << " " << elec_phi << endl; cout << " elec pt,et=" << elec_pt << " " << elec_et << endl; float elec_ptvtx = gsfIter->trackMomentumAtVtx().R(); float elec_ptout = gsfIter->trackMomentumOut().R(); cout << " elec ptvtx,ptout=" << elec_ptvtx << " " << elec_ptout << endl; float elec_eoverp = gsfIter->eSuperClusterOverP(); cout << " elec eSC/p=" << elec_eoverp << endl; } //######################################################################################### // ES Rechit loop Float_t essumet=0; Float_t essumet_kgood=0; Float_t espsumet1=0; Float_t espsumet2=0; Float_t esmsumet1=0; Float_t esmsumet2=0; cout << "\n\n****ES HITS****" << endl; for (ESRecHitCollection::const_iterator hitItr = EShits->begin(); hitItr != EShits->end(); ++hitItr) { int rechit_ix=0; int rechit_iy=0; int rechit_iz=0; int rechit_plane=0; EcalRecHit hit = (*hitItr); ESDetId det = hit.id(); rechit_ix = det.six(); rechit_iy = det.siy(); rechit_iz = det.zside(); rechit_plane = det.plane(); rechit_ene = hit.energy(); rechit_time = hit.time(); GlobalPoint poseb=geo->getPosition(hit.detid()); rechit_eta=poseb.eta(); rechit_phi=poseb.phi(); float pf=1.0/cosh(rechit_eta); rechit_et=rechit_ene*pf; Int_t isgood=1; if (hit.recoFlag()==14 || hit.recoFlag()==1 || (hit.recoFlag()<=10 && hit.recoFlag()>=5)) isgood=0; if (rechit_et>0.) { essumet+=rechit_et; if (isgood) essumet_kgood+=rechit_et; } eeoccet->Fill(rechit_ix-0.5+100*(rechit_iz>0),rechit_iy-0.5,rechit_et); if (rechit_flag_kgood) { if (rechit_iz==1) { if (rechit_plane==1) { esoccet_esp1->Fill(rechit_ix,rechit_iy,rechit_et); esp1occ_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); espsumet1+=rechit_et; } if (rechit_plane==2) { esoccet_esp2->Fill(rechit_ix,rechit_iy,rechit_et); esp2occ_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); espsumet2+=rechit_et; } } if (rechit_iz==-1) { if (rechit_plane==1) { esoccet_esm1->Fill(rechit_ix,rechit_iy,rechit_et); esm1occ_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); esmsumet1+=rechit_et; } if (rechit_plane==2) { esoccet_esm2->Fill(rechit_ix,rechit_iy,rechit_et); esm2occ_etaphi->Fill(rechit_eta,rechit_phi,rechit_et); esmsumet2+=rechit_et; } } } // select high energy hits if (rechit_ene>0.1) { cout << "\nix,iy,iz, plane=" << rechit_ix << " " << rechit_iy << " " << rechit_iz << " " << rechit_plane << " eta,phi=" << rechit_eta << " " << rechit_phi << " energy=" << rechit_ene << " et=" << rechit_et << " time=" << rechit_time << endl; cout << "good rechit" << isgood << endl; } } cout << "EB sumet=" << ebsumet << " EB sumet (kGood)=" << ebsumet_kgood << endl; cout << "EE sumet=" << eesumet << " EE sumet (kGood)=" << eesumet_kgood << endl; cout<< " EE+ sumet=" << eepsumet << " EE- sumet=" << eemsumet << endl; cout << "ES sumet=" << essumet << " ES sumet (kGood)=" << essumet_kgood << endl; cout << " ES+ sumet, plane 1=" << espsumet1 << " ES+ sumet, plane 2=" << espsumet2 << endl; cout << " ES- sumet, plane 1=" << esmsumet1 << " ES- sumet, plane 2=" << esmsumet2 << endl; cout << "\n\n"; // } // } evcount++; } ////////////////////////////////////////////////////////////////////////////////////////// EventAnalyser::~EventAnalyser() { delete file_; delete dataTree_; } //} <file_sep>/plugins/SealModule.cc #include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "DataFormats/JetReco/interface/CaloJet.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutSetupFwd.h" #include "DataFormats/L1GlobalTrigger/interface/L1GlobalTriggerReadoutRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTriggerRecord.h" #include "DataFormats/L1GlobalTrigger/interface/L1GtTechnicalTrigger.h" #include "JetMETCorrections/MCJet/plugins/SpikeAnalyser.h" #include "JetMETCorrections/MCJet/plugins/SpikeAnalyserMC.h" #include "JetMETCorrections/MCJet/plugins/EventAnalyser.h" #include "JetMETCorrections/MCJet/plugins/PFDataTreeProducer.h" #include "JetMETCorrections/MCJet/plugins/ChanstatusTester.h" #include "JetMETCorrections/Objects/interface/JetCorrector.h" DEFINE_FWK_MODULE(SpikeAnalyser); DEFINE_FWK_MODULE(SpikeAnalyserMC); DEFINE_FWK_MODULE(EventAnalyser); DEFINE_FWK_MODULE(PFDataTreeProducer); DEFINE_FWK_MODULE(ChanstatusTester);
62d1735b1166fa197054cee94425edbcf4b9d116
[ "C", "Python", "Text", "C++" ]
12
C++
mlj5j/EventCheck
275d0ab27a899f231d4c0f04e90e887f73689a58
f4b6b9322a56b838a3cfcada0887c5b10143c212
refs/heads/main
<repo_name>alessandrodd/auto_conda_unpack<file_sep>/README.md # auto_conda_unpack Script to automatically call conda-unpack in conda packed environments; Spark compatible <file_sep>/sitecustomize.py # This script is meant to automatically call conda-unpack whenever the python executable is run # copy this file to YourCondaEnv/lib/python3.X/site-packages/ (substitute X with the correct python version) import os import time # current dir should be "site-packages" curr_dir = os.path.dirname(os.path.abspath(__file__)) python_dir = os.path.abspath(os.path.join(curr_dir, os.pardir)) lib_dir = os.path.abspath(os.path.join(python_dir, os.pardir)) env_dir = os.path.abspath(os.path.join(lib_dir, os.pardir)) conda_unpack = os.path.join(os.path.join(env_dir, "bin"), "conda-unpack") run_file = os.path.join(curr_dir, "conda-unpack.running") done_file = os.path.join(curr_dir, "conda-unpack.done") if not os.path.exists(conda_unpack): print("conda-unpack does not exists; skipping auto-unpack") elif os.path.exists(run_file) and not os.path.exists(done_file): print("conda-unpack is already running; waiting for it to finish...") while not os.path.exists(done_file): time.sleep(1) print("conda-unpack already done; skipping auto-unpack") elif os.path.exists(done_file): print("conda-unpack already done; skipping auto-unpack") else: print("unpacking with conda-unpack...") os.system("chmod +w -R ./././*") with open(run_file, 'a'): os.utime(run_file, None) os.system(conda_unpack) with open(done_file, 'a'): os.utime(run_file, None) print("conda-unpack done")
217e60bd3590b6bf7893935ef71d0882a34e29e8
[ "Markdown", "Python" ]
2
Markdown
alessandrodd/auto_conda_unpack
582f7908c4b619134088f80ea964b8b9cd1a5144
cb443f4b102a780b3df9f4ffca16f17808aedb3e
refs/heads/main
<repo_name>christopherdavidjohnson/seic43-homework<file_sep>/Mauritz Erick/week_01/calculator/js/calculator.js //Part1 console.log("Part 1 Calculator") function squareNumber(number){ let squared = Math.pow(number, 2); console.log("\nThe result of squaring the number " + number + " is " + squared); return squared; } squareNumber(5); function halfNumber(num){ let divide = num / 2; console.log("Half of " + num + " is " + divide); return divide; } halfNumber(5); function percentOf(a,b){ let percentIs = (a/b*100); console.log(a + " is " + percentIs + "% of " + b); return percentIs; } percentOf(2,8); function areaOfCircle(radius){ var area = (Math.PI * radius * radius); var area = area.toFixed(2); //Bonus part console.log("The area for a circle with radius " + radius + " is " + area ) return area; } areaOfCircle(2); //Part2 console.log("\n\n\n\nPart 2 Calculator") function part2(inside){ let half = halfNumber(inside); let sq = squareNumber(half); let area2 = areaOfCircle(sq); let percent = percentOf(sq,area2); console.log("original value: " + inside + "\n#1 Half: " + half + "\n#2 Square: "+ sq + "\n#3 Area: "+ area2); console.log("\nthe percentage is " + percent + " %") } part2(500); <file_sep>/Kathryn Lugton/RUBY-week04/mortgage.rb # ## Mortgage Calculator # Calculate the monthly required payment given the other variables as input (look up the necessary variables) def mort_form puts "Mortgage Calculator".center(80) puts "Standard Fixed-Rate Loans".center(80) puts "=-" * 40 #dividing line puts "press Ctrl+C to QUIT" end until mort_form == 'q' print "Please enter the loan amount (home purchase price + charges - down payment): " p = gets.to_i print "Please enter the annual interest rate on the loan: " r = gets.to_f print "Please enter the loan term (num of years): " t = gets.to_i print "Please enter the number of payments per year: " n = gets.to_i puts "Loan Amount = #{ p }, interest rate = #{ r }, term = #{ t } and num of payments p/a = #{ n }." step1 = r / n step2 = (1 + (step1**12)) step3 = step2 * 30 step4 = p * step1 * step3 step5= (step3 -1) step6 = step4 / step5 step7 = step6.to_i puts "Your montly repayments would be #{ step7 }." #Maths is wrong. I get 5172 when I enter the below end mort_form # (p * (r/n) * (1 + r/n)**n(t))) / ((1 + r/n)**n(t) - 1) # {100,000 x (.06 / 12) x [1 + (.06 / 12)^12(30)]} / {[1 + (.06 / 12)^12(30)] - 1} # (100,000 x .005 x 6.022575) / 5.022575 # 3011.288 / 5.022575 = 599.55 <file_sep>/Mauritz Erick/week_01/strings/js/strings.js //DrEvil function DrEvil(amount){ is = (amount + " dollars"); if(amount == 1000000){ console.log(is + " (pinky)"); } else{ console.log(is); } } DrEvil(10); DrEvil(1000000); //MixUp function mixUp(a,b){ console.log(b.slice(0,2) + a.slice(2) + " " + a.slice(0,2) + b.slice(2)); } mixUp('mix','pod'); mixUp('dog','dinner'); //FixStart function fixStart(a){ var test = a.charAt(0); console.log(test + a.slice(1).replace(new RegExp(test, 'g'), '*')); } fixStart('fefefele'); //Verbing function verbing(a){ if(a.length<3) console.log(a); if(a.slice(-3) =='ing'){ console.log(a + 'ly'); } else{ console.log(a + "ing"); } } verbing('swim'); //not Bad function notBad(a){ var not = a.indexOf('not'); var bad = a.indexOf('bad'); if(not == -1 || bad == -1 || bad < not) console.log(a); console.log(a.slice(0, not) + "good" + a.slice(bad + 3)); } notBad('This dinner is not that bad!'); notBad('This movie is not so bad!'); notBad('This dinner is bad!');
dade85de1c9427054705d3b3400fb8824c591127
[ "JavaScript", "Ruby" ]
3
JavaScript
christopherdavidjohnson/seic43-homework
72a77452258aa96f451a286416114bbceac2705c
0da0a255c5cbbfb3cf818a6f9e76fd1d069bd76a
refs/heads/master
<repo_name>peetbart/machine_learning<file_sep>/sklearn/sklearn_cheatsheet.py # Scikit-Learn Cheatsheet # Linear Regression from sklearn.linear_model import LinearRegression model = LinearRegression() # Fit model.fit(x_training_data, y_training_data) .coef_ # contains the coefficients .intercept_ # contains the intercept # Predict predictions = model.predict(your_x_data) .score() # returns the coefficient of determination R² # Naive Bayes from sklearn.naive_bayes import MultinomialNB model = MultinomialNB() # Fit model.fit(x_training_data, y_training_data) # Predict # Returns a list of predicted classes - one prediction for every data point predictions = model.predict(your_x_data) # For every data point, returns a list of probabilities of each class probabilities = model.predict_proba(your_x_data) # K-Nearest Neighbors from sklearn.neigbors import KNeighborsClassifier model = KNeighborsClassifier() # Fit model.fit(x_training_data, y_training_data) # Predict # Returns a list of predicted classes - one prediction for every data point predictions = model.predict(your_x_data) # For every data point, returns a list of probabilities of each class probabilities = model.predict_proba(your_x_data) # K-Means from sklearn.cluster import KMeans model = KMeans(n_clusters=4, init='random') ''' n_clusters: number of clusters to form and number of centroids to generate init: method for initialization k-means++: K-Means++ [default] random: K-Means random_state: the seed used by the random number generator [optional] ''' # Fit model.fit(x_training_data) # Predict predictions = model.predict(your_x_data) # Validating the Model # accuracy, recall, precision, and F1 score from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score print(accuracy_score(true_labels, guesses)) print(recall_score(true_labels, guesses)) print(precision_score(true_labels, guesses)) print(f1_score(true_labels, guesses)) # confusion matrix from sklearn.metrics import confusion_matrix print(confusion_matrix(true_labels, guesses)) # Training Sets and Test Sets from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, test_size=0.2) ''' train_size: the proportion of the dataset to include in the train split test_size: the proportion of the dataset to include in the test split random_state: the seed used by the random number generator [optional] ''' <file_sep>/README.md # machine learning This repository contains some of my training I did in machine learning.
fb48209982371cf07465b6d2ae722a22994720fd
[ "Markdown", "Python" ]
2
Python
peetbart/machine_learning
48635458a57ec19f780479f0f31910af02906818
ca9d1064acf0884444b67f03bb1178b5ef5ae9f7
refs/heads/master
<repo_name>tvaughn94/EightBall<file_sep>/EightBall.c #include <stdio.h> #include <time.h> #include <stdlib.h> #define NUMFORTUNES 20 void EightBall(); int main(){ EightBall(); } void EightBall(){ int x; char *fortunes[NUMFORTUNES] = {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."}; x = 0; srand(time(NULL)); x = rand() % NUMFORTUNES; printf("%s\n", fortunes[x]); }
2c1ee0e54b4b8bddc57cc2e164cd78b840dbd7ff
[ "C" ]
1
C
tvaughn94/EightBall
f43d1e3c4cff17e71406fcfae08dfd3ecc5f59b9
a391f2f6efbc5e44c535cc2d3d67fa54369540bc
refs/heads/master
<file_sep>#! /bin/bash # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # Download a backup from GCS if available if [[ -n "$GCS_RESTORE_URL" && $GCS_RESTORE_URL == gs://* ]] then echo "Restoring from $GCS_RESTORE_URL" mkdir -p /tmp/jenkins_restore && cd /tmp/jenkins_restore gsutil cp $GCS_RESTORE_URL restore.tgz tar -zxvf restore.tgz cp -R `ls -d */`* /usr/share/jenkins/ref/ cd $HOME rm -rf /tmp/jenkins_restore fi # Run jenkins startup script exec /usr/local/bin/jenkins.sh "$@" <file_sep>jenkins-swarm-gcp ==================== Docker image for Jenkins, with Swarm, git, and Google Cloud Platform plugins installed. GCP plugins support Google OAuth, Cloud Storage and Source, as well as GCE Service Accounts, ideal for running builds on Google Cloud Platform. # Running ```shell docker run --name jenkins -p 8080:8080 -p 50000:50000 -v /var/jenkins_home gcr.io/cloud-solutions-images/jenkins-gcp-leader ``` # Backup and Restore The image includes a job to perform backups to Google Cloud Storage. You must modify the job to include the name of your GCS bucket if you wish to perform backups. To restore from an existing backup stored in a GCS bucket, launch the container with an environmetn variabled named GCS_RESTORE_URL that points to the backup (including the gs:// scheme). For example: ```shell docker run --name jenkins \ -e GCS_RESTORE_URL:gs://your-bucket/your-backup.tgz \ -p 8080:8080 -p 50000:50000 \ -v /var/jenkins_home gcr.io/cloud-solutions-images/jenkins-gcp-leader ```
97f79252f802a554f064ef13df145a9ad5abe739
[ "Markdown", "Shell" ]
2
Shell
alekssaul/jenkins-gcp-leader
a69503032064912ce0f78ee87bd624bd381897e1
8ba668c41c91ebdf1777f92ae040ca8ac9a0fa5d
refs/heads/master
<repo_name>angelfan/inspinia<file_sep>/app/models/angel_pass.rb class AngelPass < ApplicationRecord end <file_sep>/app/helpers/component_helper.rb module ComponentHelper def render_ibox(box_title: nil, box_desc: nil, &block) render partial: 'components/ibox', locals: { box_title: box_title, box_desc: box_desc, content: capture(&block) } end end <file_sep>/app/assets/javascripts/inspinia/forms.js //= require iCheck/icheck.min.js //= require steps/jquery.steps.min.js //= require dropzone/dropzone.js //= require summernote/summernote.min.js //= require datapicker/bootstrap-datepicker.js //= require bootstrap-datetimepicker/bootstrap-datetimepicker.min.js //= require bootstrap-datetimepicker/bootstrap-datetimepicker.zh-CN.js //= require ionRangeSlider/ion.rangeSlider.min.js //= require jasny/jasny-bootstrap.min.js //= require jsKnob/jquery.knob.js //= require nouslider/jquery.nouislider.min.js //= require switchery/switchery.js //= require chosen/chosen.jquery.js //= require fullcalendar/moment.min.js //= require clockpicker/clockpicker.js //= require daterangepicker/daterangepicker.js //= require select2/select2.full.min.js //= require touchspin/jquery.bootstrap-touchspin.min.js //= require bootstrap-tagsinput/bootstrap-tagsinput.js $.fn.datepicker.dates['zh-CN'] = { days: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"], daysShort: ["日","一","二","三","四","五","六"], daysMin: ["日","一","二","三","四","五","六"], months: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], monthsShort: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"], today: "今天", clear: "清除", format: "yyyy-mm-dd", titleFormat: "yyyy MM", /* Leverages same syntax as 'format' */ weekStart: 0 };<file_sep>/spec/routing/angel_passes_routing_spec.rb require 'rails_helper' RSpec.describe AngelPassesController, type: :routing do describe 'routing' do it 'routes to #index' do expect(get: '/angel_passes').to route_to('angel_passes#index') end it 'routes to #new' do expect(get: '/angel_passes/new').to route_to('angel_passes#new') end it 'routes to #show' do expect(get: '/angel_passes/1').to route_to('angel_passes#show', id: '1') end it 'routes to #edit' do expect(get: '/angel_passes/1/edit').to route_to('angel_passes#edit', id: '1') end it 'routes to #create' do expect(post: '/angel_passes').to route_to('angel_passes#create') end it 'routes to #update via PUT' do expect(put: '/angel_passes/1').to route_to('angel_passes#update', id: '1') end it 'routes to #update via PATCH' do expect(patch: '/angel_passes/1').to route_to('angel_passes#update', id: '1') end it 'routes to #destroy' do expect(delete: '/angel_passes/1').to route_to('angel_passes#destroy', id: '1') end end end <file_sep>/Gemfile if ENV['REGION'] && ENV['REGION'] != 'china' source 'https://rubygems.org' else source 'https://gems.ruby-china.org' end git_source(:github) do |repo_name| repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?('/') "https://github.com/#{repo_name}.git" end gem 'rails', '~> 5.1.4' # DB gem 'activerecord-postgis-adapter' gem 'pg' gem 'redis' gem 'redis-namespace' gem 'redis-objects', require: 'redis/objects' gem 'redis-rails' # view rendering gem 'jbuilder', '~> 2.5' gem 'simple_form' gem 'slim' # assets gem 'bootstrap-sass' gem 'coffee-rails', '~> 4.2' gem 'font-awesome-rails' gem 'jquery-ui-rails' gem 'sass-rails', '~> 5.0' gem 'sweet-alert2-rails' gem 'uglifier', '>= 1.3.0' # JS plugin gem 'jquery-rails' gem 'turbolinks', '~> 5' # app server gem 'puma', '~> 3.7' group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console # gem 'byebug', platforms: %i[mri mingw x64_mingw] # Adds support for Capybara system testing and selenium driver # gem 'capybara', '~> 2.13' # gem 'selenium-webdriver' gem 'database_cleaner' gem 'factory_bot_rails' gem 'overcommit', require: false gem 'pry' gem 'rails-controller-testing' gem 'rspec' gem 'rspec-rails' gem 'rubocop', require: false gem 'shoulda-matchers' gem 'timecop' gem 'webmock' end group :development do gem 'annotate' gem 'bullet' gem 'listen', '>= 3.0.5', '< 3.2' gem 'slackistrano', require: false gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' gem 'web-console', '>= 3.3.0' end gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] # sidekiq gem 'sidekiq' gem 'sidekiq-limit_fetch' gem 'sidekiq-scheduler', '~> 2.0' # utility gem 'browser' gem 'devise' gem 'ffaker' gem 'gon' gem 'gretel' gem 'httparty' gem 'js-routes' gem 'kaminari' gem 'nested_form' gem 'paper_trail' gem 'paranoia' gem 'public_activity' gem 'pundit' gem 'ransack' gem 'seed-fu' gem 'settingslogic' gem 'uuidtools' gem 'wannabe_bool' gem 'wechat' # pry gem 'awesome_print', require: false gem 'pry-rails' # Profiling # gem 'rack-mini-profiler' # For memory profiling (requires Ruby MRI 2.1+) # gem 'memory_profiler' # For call-stack profiling flamegraphs (requires Ruby MRI 2.0.0+) # gem 'flamegraph' # gem 'stackprof' # For Ruby MRI 2.1+ <file_sep>/spec/factories/angel_passes.rb FactoryBot.define do factory :angel_pass do title 'MyString' site 'MyString' account 'MyString' password '<PASSWORD>' end end <file_sep>/config/breadcrumbs.rb crumb :root do link '主页', root_path end crumb :angel_passes do link 'AngelPass', angel_passes_path parent :root end <file_sep>/spec/controllers/angel_passes_controller_spec.rb require 'rails_helper' RSpec.describe AngelPassesController, type: :controller do end <file_sep>/app/controllers/angel_passes_controller.rb class AngelPassesController < ApplicationController before_action :authenticate_user! before_action :set_angel_pass, only: %i[show edit update destroy] def index @q = AngelPass.ransack(params[:q]) @angel_passes = @q.result.order(created_at: :desc) end def show; end def new @angel_pass = AngelPass.new end def edit; end def create @angel_pass = AngelPass.new(angel_pass_params) respond_to do |format| if @angel_pass.save format.html { redirect_to @angel_pass, notice: 'Angel pass was successfully created.' } format.js { @result = { status: :ok, msg: 'Angel pass was successfully created.' } } else format.html { render :new } format.js { @result = { status: :error, msg: @angel_pass.errors.full_messages.to_sentence } } end end end def update respond_to do |format| if @angel_pass.update(angel_pass_params) format.html { redirect_to @angel_pass, notice: 'Angel pass was successfully updated.' } format.json { render :show, status: :ok, location: @angel_pass } else format.html { render :edit } format.json { render json: @angel_pass.errors, status: :unprocessable_entity } end end end def destroy @angel_pass.destroy respond_to do |format| format.html { redirect_to angel_passes_url, notice: 'Angel pass was successfully destroyed.' } format.json { head :no_content } format.js { @result = { status: :ok, msg: 'deleted' } } end end private def set_angel_pass @angel_pass = AngelPass.find(params[:id]) end def angel_pass_params params.require(:angel_pass).permit(:title, :site, :account, :password) end end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def is_active_controller(controller_name, class_name = nil) if controller_name.is_a?(String) if params[:controller] == controller_name class_name.nil? ? 'active' : class_name end elsif controller_name.is_a?(Array) if params[:controller].in? controller_name class_name.nil? ? 'active' : class_name end end end end <file_sep>/spec/views/angel_passes/show.html.erb_spec.rb require 'rails_helper' # RSpec.describe "angel_passes/show", type: :view do # before(:each) do # @angel_pass = assign(:angel_pass, AngelPass.create!( # :title => "Title", # :site => "Site", # :account => "Account", # :password => "<PASSWORD>" # )) # end # # it "renders attributes in <p>" do # render # expect(rendered).to match(/Title/) # expect(rendered).to match(/Site/) # expect(rendered).to match(/Account/) # expect(rendered).to match(/Password/) # end # end <file_sep>/app/inputs/group_input.rb class GroupInput < SimpleForm::Inputs::Base def input(wrapper_options) content = options.delete(:group_btn) template.content_tag(:div, class: 'input-group') do template.concat @builder.text_field(attribute_name, merge_wrapper_options(input_html_options, wrapper_options)) template.concat group_btn_content(content) end end def group_btn_content(content) template.content_tag(:span, class: 'input-group-btn') do content.call.html_safe end end end
241b3c680850d6164667817a5dffa67474064250
[ "JavaScript", "Ruby" ]
12
Ruby
angelfan/inspinia
ed900003523078c91c1fe62fe1d64cb403b5e10a
71ad8a0f993c7609fa85dbfd266cd5127925aa24
refs/heads/master
<repo_name>corinnekrych/helloworld-geo-ios<file_sep>/Helloworld-geo/ViewController.swift // // ViewController.swift // Helloworld-geo // // Created by sebi-mbp on 18/01/15. // Copyright (c) 2015 sebi-mbp. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() println("view loaded") // Do any additional setup after loading the view, typically from a nib. } @IBAction func registerWithGeoServer(sender: AnyObject) { locationManager.requestWhenInUseAuthorization() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { manager.stopUpdatingLocation() var localValue:CLLocationCoordinate2D = manager.location.coordinate let registration = AGDeviceRegistration(serverURL: NSURL(string: "<URL of geo server>")!) // attemp to register registration.registerWithClientInfo({ (clientInfo: AGClientDeviceInformation!) in // setup configuration clientInfo.alias = "<unique identifier>" clientInfo.apiKey = "<apiKey>" clientInfo.apiSecret = "<apiSecret>" clientInfo.longitude = localValue.longitude clientInfo.latitude = localValue.latitude }, success: { println("UnifiedGeo Server registration succeeded") self.locationManager.stopUpdatingLocation() }, failure: {(error: NSError!) in println("failed to register, error: \(error.description)") }) } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println("failed to retrieve location, error: \(error.localizedDescription)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/README.md # helloworld-geo-ios ## Set up Unified Geo Server ## Set up helloworld client <file_sep>/UnifiedGeo/UnifiedGeoTests/UnifiedGeoTests.swift // // UnifiedGeoTests.swift // UnifiedGeoTests // // Created by sebi-mbp on 18/01/15. // Copyright (c) 2015 sebi-mbp. All rights reserved. // import UIKit class UnifiedGeoTests { }
8d58ee79620dd886ddfb06e81878d397f396a054
[ "Swift", "Markdown" ]
3
Swift
corinnekrych/helloworld-geo-ios
2c6156c9c271928ddbcd031d0a02148ef0b028c3
95b84520b1cd385b7ec22255aa6fe3c0574088d4
refs/heads/master
<repo_name>ilya-otus/allocator<file_sep>/reserve_allocator.h #pragma once #include <iostream> #include <vector> #include <map> template<typename T, size_t N> struct ReserveAllocator { using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = size_t; static constexpr size_t itemsCount = N; using buffer = std::vector<T*>; template<typename U, size_t M = itemsCount> struct rebind { using other = ReserveAllocator<U, M>; }; ReserveAllocator() : mLastPos(0) { auto buf = std::malloc(N * sizeof(T)); if (!buf) { throw std::bad_alloc(); } mBuffer = reinterpret_cast<T *>(buf); } ReserveAllocator(const ReserveAllocator &other) : mBuffer(other.mBuffer), mLastPos(other.mLastPos) { } T *allocate(std::size_t n) { if (mLastPos + n > N) throw std::bad_alloc(); auto p = &mBuffer[mLastPos]; mLastPos += n; if (!p) { throw std::bad_alloc(); } return reinterpret_cast<T *>(p); } void deallocate(T *p, std::size_t n) { (void)p; mLastPos -= n; if (mLastPos == 0) { std::free(mBuffer); } } template<typename U, typename ...Args> void construct(U *p, Args &&...args) { new(p) U(std::forward<Args>(args)...); } template<typename U> void destroy(U *p) { p->~U(); } private: T *mBuffer; size_t mLastPos; }; <file_sep>/main.cpp #include <iostream> #include <string> #include "custom_container.h" #include "reserve_allocator.h" const size_t N = 10; template <typename T> using ReserveNAllocator = ReserveAllocator<T, N>; int main(int , char **) { { auto defaultContainerDefaultAllocator = std::map<int, int>(); for (size_t i = 0; i < N; ++i) { if (i == 0) { defaultContainerDefaultAllocator[i] = 1; } else { defaultContainerDefaultAllocator[i] = defaultContainerDefaultAllocator[i - 1] * i; } } } { auto defaultContainerCustomAllocator = std::map<int, int, std::less<int>, ReserveNAllocator<std::pair<const int, int> > >(); for (size_t i = 0; i < N; ++i) { if (i == 0) { defaultContainerCustomAllocator[i] = 1; } else { defaultContainerCustomAllocator[i] = defaultContainerCustomAllocator[i - 1] * i; } std::cout << i << " " << defaultContainerCustomAllocator[i] << std::endl; } } { auto customContainerDefaultAllocator = CustomContainer<int>(); for (size_t i = 0; i < N; ++i) { customContainerDefaultAllocator.emplace_back(i); } } { auto customContainerCustomAllocator = CustomContainer<int, ReserveNAllocator<int>>(); for (size_t i = 0; i < N; ++i) { customContainerCustomAllocator.emplace_back(i); std::cout << customContainerCustomAllocator[i] << std::endl; } } return 0; } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.2) set(MAJOR_VERSION 0) set(MINOR_VERSION 0) set(PATCH_VERSION 999) if($ENV{MAJOR_VERSION}) set(MAJOR_VERSION $ENV{MAJOR_VERSION}) endif() if($ENV{MINOR_VERSION}) set(MINOR_VERSION $ENV{MINOR_VERSION}) endif() if($ENV{TRAVIS_BUILD_NUMBER}) set(PATCH_VERSION $ENV{TRAVIS_BUILD_NUMBER}) endif() project(allocator VERSION ${MAJOR_VERSION}.${MAJOR_VERSION}.${PATCH_VERSION}) find_package(Boost COMPONENTS unit_test_framework REQUIRED) configure_file(version.h.in ${PROJECT_SOURCE_DIR}/version.h) add_executable(allocator main.cpp) add_library(alloc lib.cpp) add_executable(test_version test_version.cpp) add_executable(test_container test_container.cpp) set_target_properties(allocator alloc test_version test_container PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON COMPILE_OPTIONS "-g;-Wpedantic;-Wall;-Wextra" ) set_target_properties(test_version PROPERTIES COMPILE_DEFINITIONS BOOST_TEST_DYN_LINK INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIR} ) set_target_properties(test_container PROPERTIES COMPILE_DEFINITIONS BOOST_TEST_DYN_LINK INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIR} ) target_link_libraries(allocator alloc ) target_link_libraries(test_version ${Boost_LIBRARIES} alloc ) target_link_libraries(test_container ${Boost_LIBRARIES} ) install(TARGETS allocator RUNTIME DESTINATION bin) set(CPACK_GENERATOR DEB) set(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") set(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}") set(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}") set(CPACK_PACKAGE_CONTACT <EMAIL>) include(CPack) enable_testing() add_test(allocator_tests test_version) add_test(allocator_tests test_container) <file_sep>/README.md [![Build Status](https://travis-ci.org/ilya-otus/allocator.svg?branch=master)](https://travis-ci.org/ilya-otus/allocator) # Allocator This C++ application with fully configured environment such as: - logging (spdlog) - tests (boost tests) - versioning - CI (travis) - Distribution system (bintray) # Dependencies - spdlog - boost.test <file_sep>/custom_container.h #pragma once #include <iterator> #include <memory> template <class T, typename A = std::allocator<T> > struct CustomContainer { using allocator_type = A; using value_type = typename A::value_type; using reference = typename A::reference; using const_reference = typename A::const_reference; using pointer = typename A::pointer; using size_type = typename A::size_type; struct Field { Field *prev; Field *next; value_type value; bool operator==(const Field &other) const { return prev == other.prev && next == other.next && value == other.value; } bool operator!=(const Field &other) const { return prev != other.prev && next != other.next && value != other.value; } }; using FieldAllocator = typename std::allocator_traits<A>::template rebind_alloc<Field>; class const_iterator; class iterator { public: friend const_iterator; using iterator_category = std::random_access_iterator_tag; iterator(Field *ptr) : mData(ptr) {} iterator(const iterator &other) : mData(other.mData) {} ~iterator() = default; iterator &operator=(const iterator &other) { mData = other.mData; } bool operator==(const iterator &other) const { return mData == other.mData; } bool operator!=(const iterator &other) const { return mData != other.mData; } iterator operator++() { mData = mData->next; return *this; } reference operator*() const { return mData->value; } pointer operator->() const { return &mData->value; } private: Field *mData; }; class const_iterator { public: friend iterator; using reference = typename A::const_reference; using pointer = typename A::const_pointer; using iterator_category = std::random_access_iterator_tag; const_iterator(Field ptr) : mData(ptr) {} const_iterator(const const_iterator &other) : mData(other.mData) {} const_iterator(const iterator &other) : mData(other.mData) {} ~const_iterator() = default; iterator &operator=(const iterator &other) { mData = other.mData; } bool operator==(const iterator &other) const { return mData == other.mData; } bool operator!=(const iterator &other) const { return mData != other.mData; } bool operator!=(const_iterator &other) const { return mData != other.mData; } const_iterator operator++() { mData = mData->next; return *this; } reference operator*() const { return mData->value; } pointer operator->() const { return &mData->value; } private: Field *mData; }; CustomContainer() : mBegin(nullptr), mLast(nullptr), mAllocator(FieldAllocator()), mSize(0) { mEnd.value = value_type(); mEnd.next = nullptr; } CustomContainer(CustomContainer &&other) noexcept : mBegin(std::move(other.mBegin)), mLast(std::move(other.mLast)), mEnd(std::move(other.mEnd)), mAllocator(other.mAllocator), mSize(other.mSize) { } CustomContainer(const CustomContainer &other) : mBegin(nullptr), mAllocator(decltype(other.mAllocator)()), mSize(other.mSize) { for (auto field: other) { auto prev = mLast; mLast = mAllocator.allocate(1); mAllocator.construct(&mLast->value, field); if (mBegin == nullptr) { mBegin = mLast; mBegin->prev = nullptr; mBegin->next = mLast; } else { prev->next = mLast; mLast->prev = prev; mLast->next = &mEnd; } mEnd.prev = mLast; } } ~CustomContainer() { while (mLast->prev != nullptr) { mAllocator.destroy(&mLast->value); mLast = mLast->prev; mAllocator.deallocate(mLast->next, 1); mLast->next = nullptr; } mAllocator.destroy(&mBegin->value); mAllocator.deallocate(mBegin, 1); } CustomContainer &operator=(const CustomContainer &other) { if (!empty()) { this->~CustomContainer(); } else { mAllocator.deallocate(mBegin, mSize); } new(this) CustomContainer(other); return *this; } bool operator==(const CustomContainer &other) const { if (mSize != other.mSize) { return false; } Field *it1 = mBegin; Field *it2 = other.mBegin; while (it1 != mLast && it2 != mLast) { if (it1->value != it2->value) { return false; } it1 = it1->next; it2 = it2->next; } return true; } bool operator!=(const CustomContainer &other) const { return !(*this == other); } reference operator[](size_t n) { if (n > mSize -1) { throw std::out_of_range("Index out of range"); } auto it = mBegin; if ((mSize / 2) > n) { for (size_t i = 0; i < n; ++i) { it = it->next; } } else { it = &mEnd; for (size_t i = 0; i < mSize - n; ++i) { it = it->prev; } } return it->value; } iterator begin() { return iterator(mBegin); } const_iterator begin() const { return const_iterator(mBegin); } const_iterator cbegin() const { return const_iterator(mBegin); } iterator end() { return iterator(mLast->next); } const_iterator end() const { return const_iterator(mLast->next); } const_iterator cend() const { return const_iterator(mLast->next); } void swap(CustomContainer &other) { std::swap(mBegin, other.mBegin); std::swap(mLast, other.mLast); std::swap(mEnd, other.mEnd); std::swap(mAllocator, other.mAllocator); std::swap(mSize, other.mSize); } size_t size() const { return mSize; } size_t max_size() const { return mAllocator.max_size(); } bool empty() const { return mSize == 0; } template<class ...Args> void emplace_back(Args&&... args) { auto prev = mLast; mLast = mAllocator.allocate(1); mAllocator.construct(&mLast->value, std::forward<Args>(args)...); if (mBegin == nullptr) { mBegin = mLast; mBegin->prev = nullptr; mBegin->next = mLast; } else { prev->next = mLast; mLast->prev = prev; mLast->next = &mEnd; } mEnd.prev = mLast; mSize+=1; } private: Field *mBegin; Field *mLast; Field mEnd; FieldAllocator mAllocator; size_t mSize; }; <file_sep>/test_container.cpp #define BOOST_TEST_MODULE callocator_test_module #include <map> #include "reserve_allocator.h" #include "custom_container.h" #include <boost/test/unit_test.hpp> const size_t N = 10; template <typename T> using ReserveNAllocator = ReserveAllocator<T, N>; BOOST_AUTO_TEST_SUITE(container_test_suite) BOOST_AUTO_TEST_CASE(default_allocator_default_container_test) { auto test = std::map<int, int>(); for (size_t i = 0; i < N; ++i) { test[i] = i; } BOOST_CHECK_EQUAL(test.size(), N); } BOOST_AUTO_TEST_CASE(custom_allocator_default_container_test) { auto test = std::map<int, int, std::less<int>, ReserveAllocator<std::pair<const int, int>, N> >(); for (size_t i = 0; i < N; ++i) { test[i] = i; } BOOST_CHECK_EQUAL(test.size(), N); } BOOST_AUTO_TEST_CASE(default_allocator_custom_container_test) { auto test = CustomContainer<int>(); for (size_t i = 0; i < N; ++i) { test.emplace_back(i); } BOOST_CHECK_EQUAL(test.size(), N); } BOOST_AUTO_TEST_CASE(custom_allocator_custom_container_test) { auto test = CustomContainer<int, ReserveAllocator<int, N> >(); for (size_t i = 0; i < N; ++i) { test.emplace_back(i); } BOOST_CHECK_EQUAL(test.size(), N); } BOOST_AUTO_TEST_CASE(custom_allocator_custom_container_assignment_test) { auto customContainerCustomAllocator = CustomContainer<int, ReserveNAllocator<int>>(); for (size_t i = 0; i < N; ++i) { customContainerCustomAllocator.emplace_back(i); } CustomContainer<int, ReserveNAllocator<int>> testCopy; testCopy = customContainerCustomAllocator; BOOST_CHECK(customContainerCustomAllocator == testCopy); } BOOST_AUTO_TEST_CASE(custom_allocator_custom_container_copy_test) { auto customContainerCustomAllocator = CustomContainer<int, ReserveNAllocator<int>>(); for (size_t i = 0; i < N; ++i) { customContainerCustomAllocator.emplace_back(i); } CustomContainer<int, ReserveNAllocator<int>> testCopy(customContainerCustomAllocator); BOOST_CHECK(customContainerCustomAllocator == testCopy); } BOOST_AUTO_TEST_CASE(custom_allocator_custom_container_move_test) { auto customContainerCustomAllocator = CustomContainer<int, ReserveNAllocator<int>>(); for (size_t i = 0; i < N; ++i) { customContainerCustomAllocator.emplace_back(i); } CustomContainer<int, ReserveNAllocator<int>> testCopy(customContainerCustomAllocator); CustomContainer<int, ReserveNAllocator<int>> testMove(testCopy); BOOST_CHECK(customContainerCustomAllocator == testMove); } BOOST_AUTO_TEST_SUITE_END() <file_sep>/test_version.cpp #define BOOST_TEST_MODULE allocator_test_module #include "lib.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(allocator_test_suite) BOOST_AUTO_TEST_CASE(allocator_test_version) { BOOST_CHECK(versionMajor() >= 0); BOOST_CHECK(versionMinor() >= 0); BOOST_CHECK(versionPatch() > 0); std::string _version = std::to_string(versionMajor()) + "." + std::to_string(versionMinor()) + "." + std::to_string(versionPatch()); BOOST_CHECK(version().compare(_version) == 0); } BOOST_AUTO_TEST_SUITE_END()
5f5a3f2629552ec57fe8417a95200239605441f1
[ "Markdown", "CMake", "C++" ]
7
C++
ilya-otus/allocator
5d8453aecfd11acb384cf8d0efae43bd4b1254ad
493f42503a749f00f48c4e564f1ddb84fe856415
refs/heads/master
<file_sep>using System.Collections.Generic; using System.Linq; namespace ConsoleApplication { public class Applicants : IApplicants { public Stack<Applicant> ApplicantStack { get; set; } private List<Applicant> AcceptedApplicants{ get;set; } private List<Applicant> DeclinedApplicants{ get;set; } public Applicants(ApplicationStack applicationStack) { ApplicantStack = applicationStack.ApplicantStack; AcceptedApplicants = AcceptedApplicants ?? new List<Applicant>(); DeclinedApplicants = DeclinedApplicants ?? new List<Applicant>(); ApplicantAcceptDeclineListSeparator(); } public int GetTotalNumberOfApplicants() => AcceptedApplicants.Count + DeclinedApplicants.Count; public int GetTotalNumberOfAcceptedApplicants() => AcceptedApplicants.Count; public int GetTotalNumberOfDeclinedApplicants() => DeclinedApplicants.Count; public decimal AverageApplicantClassAcceptance() { int totalAcceptedApplicants = AcceptedApplicants.Count; int totalOverallApplicants = AcceptedApplicants.Count + DeclinedApplicants.Count; decimal average = ((decimal)totalAcceptedApplicants/(decimal)totalOverallApplicants); return average; } public decimal AcceptedApplicantStandardizedScoreDifference() { int totalDifference = AcceptedApplicants .Sum(s=>s.StandardizedTest - s.ScoreNeeded); if(totalDifference == 0) { return 0; } return totalDifference/(AcceptedApplicants.Count); } public void ApplicantAcceptDeclineListSeparator() { while(ApplicantStack.Count > 0) { Applicant applicant = ApplicantStack.Pop(); if(!applicant.AcceptedMatch) { DeclinedApplicants.Add(applicant); } else { AcceptedApplicants.Add(applicant); } } } } } <file_sep>using System; namespace ConsoleApplication { public class DecisionPanel { public DecisionPanel(){} public void AdmissionDecision() { throw new NotImplementedException(); } } }<file_sep>using System.Collections.Generic; namespace ConsoleApplication { public interface ILoadApplicants { List<Applicant> GetApplicants(); } }<file_sep># College Acceptance <file_sep>using System; namespace ConsoleApplication { public class Subscriber { internal string Applicant{ get; set; } internal int Score{ get; set; } public Subscriber(Publisher pub) { pub.RaiseCustomEvent += HandleCustomEvent; } void HandleCustomEvent(object sender, AcceptanceLetter e) { System.Console.WriteLine("From Subscriber.HandleCustomeEvent:"); System.Console.WriteLine($"\t Type:ConsoleApplication.Institute \n\t\t e.Message: {e.Message} e.Institute: {e.Institute}"); System.Console.WriteLine($"\t ConsoleApplication.Publisher.Subscriber \n\t\t _applicant: {Applicant}, _score: {Score}"); //Console.WriteLine("applicant #:{3} \n For: {0}\n {1}\n You were accepted based on your standardized score of {2} " , _applicant, e.Message, _score, _id); //System.Console.WriteLine("List of applicants {0}",_applicantsNames.Count); } } }<file_sep>using System; namespace ConsoleApplication { public class Institute { internal string InstituteName{ get;set; }  public int MinimumScore{ get;set; } public Institute(){} public Institute(Publisher pub) { pub.RaiseCustomEvent += HandleCustomEvent; } void HandleCustomEvent(object sender, AcceptanceLetter e) { System.Console.WriteLine("ConsoleApplication.Institute"); Console.WriteLine( "Letter to applicant:{0} would like you to attend their school as of {1}\n" , InstituteName, e.Message); } } } <file_sep>namespace ConsoleApplication { public class PostApplicationResults { private IApplicants _applicants; public PostApplicationResults(IApplicants applicants) { _applicants = applicants; } public void StatsClass() { TotalAccpetedApplicants(); TotalDeclinedApplicants(); TotalApplicationClass(); ClassAcceptancePercentage(); AcceptedApplicantAverageStandardizedScoreDifference(); } public void TotalApplicationClass() { int totalNumberOfApplicants = _applicants.GetTotalNumberOfApplicants(); System.Console.WriteLine($"Cummulative applicants class size: {totalNumberOfApplicants}"); } public void TotalAccpetedApplicants() { int numberOfAcceptedApplicants = _applicants.GetTotalNumberOfAcceptedApplicants(); System.Console.WriteLine($"Cummulative number of accepted applicants: {numberOfAcceptedApplicants}"); } public void TotalDeclinedApplicants() { int numberOfDeclinedApplicants = _applicants.GetTotalNumberOfDeclinedApplicants();; System.Console.WriteLine($"Cummulative number of declined applicants: {numberOfDeclinedApplicants}"); } public void ClassAcceptancePercentage() { decimal acceptedApplicants = _applicants.AverageApplicantClassAcceptance(); decimal percentAccepted = acceptedApplicants * 100; //double percent = System.Math.Round(percentAccepted,2); System.Console.WriteLine("Percent of applicants accepted to 'match' institute {0}",percentAccepted.ToString("F")); } public void AcceptedApplicantAverageStandardizedScoreDifference() { decimal score = _applicants.AcceptedApplicantStandardizedScoreDifference(); if(score == 0) { System.Console.WriteLine($"Standardized Score Difference of accepted applicant {score}, since no applicants were accepted"); } System.Console.WriteLine("Standardized Score Difference of accepted applicant {0}",score.ToString("F")); } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public class SampleApplicantData : ILoadApplicants { public List<Applicant> _applicants; string[] firstnames = new string[5]{"jim","tom", "jack","jake","mitch"}; string[] lastnames = new string[5]{"johnson","thomas", "jackson","montgomery","jackson"}; int[] scores = new int[5]{1500, 1200, 1000, 950, 1350}; public List<Applicant> GetApplicants() { List<Applicant> applicantPool = new List<Applicant>(); Applicant applicant; byte[] randomByteArr = new byte[20]; Random rnd = new Random(); rnd.NextBytes(randomByteArr); Console.WriteLine("starting random mix and match applicants"); for(int i=randomByteArr.GetLowerBound(0); i<=randomByteArr.GetUpperBound(0); i++) { applicant = new Applicant { FirstName = firstnames[randomByteArr[i] % firstnames.Length], LastName = lastnames[randomByteArr[i] % lastnames.Length], StandardizedTest = scores[randomByteArr[i] % scores.Length] }; applicantPool.Add(applicant); } return applicantPool; } } }<file_sep>using System; namespace ConsoleApplication { public class AcceptanceLetter :EventArgs { readonly string greeting = "Congrats"; public string Message {get; set;} //public Institute Institute; public string Institute{ get;set; } public AcceptanceLetter(string institute) // should take (Institute institute), // make lone institute call with zip, and shit // change Institute class to something including score criteria // { Message = greeting; Institute = institute; } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public static class CreateSubList { // Do not believe this is thread safe! public static void Shuffle<T>(this IList<T> list, Random rnd) { for(var i=0; i < list.Count; i++) { list.Swap(i, rnd.Next(i, list.Count)); } } public static void Swap<T>(this IList<T> list, int i, int j) { var temp = list[i]; list[i] = list[j]; list[j] = temp; } } }<file_sep>using System; using System.Diagnostics; namespace ConsoleApplication { public class Timing { TimeSpan start; TimeSpan duration; public TimeSpan Result { get { return duration; } } public Timing() { start = new TimeSpan(0); duration = new TimeSpan(0); } public void Start() { GC.Collect(); GC.WaitForPendingFinalizers(); start = Process.GetCurrentProcess().Threads[0].TotalProcessorTime; } public void Stop() { duration = Process.GetCurrentProcess().Threads[0]. TotalProcessorTime.Subtract(start); Reset(); } public void Reset() { start = new TimeSpan(0); } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public enum DataSource { Mock, CSV, Db, InternetService } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public class Program { public static void AdmissionDeciled(Applicant applicant, Institute institute) { Console.WriteLine("We are sorry to inform you"); System.Console.WriteLine($"Applicant {applicant.FirstName} was rejected with as score of {applicant.StandardizedTest}"); System.Console.WriteLine($"Institue {institute.InstituteName} required {institute.MinimumScore}"); } public static void Main(string[] args) { Publisher pub = new Publisher(); // All this data should probably be in a static class var dataSourceDict = new Dictionary<DataSource, Lazy<ILoadApplicants>> { {DataSource.Mock , new Lazy<ILoadApplicants>(() => new SampleApplicantData())}, {DataSource.CSV, new Lazy<ILoadApplicants>(() => new CSVData())}, {DataSource.Db, new Lazy<ILoadApplicants>(() => new DbData())}, {DataSource.InternetService, new Lazy<ILoadApplicants>(() => new InternetServiceData())} }; DataFactory dtFactory = new DataFactory(dataSourceDict); var dtSource = dtFactory.GetApplicantSource(DataSource.Mock); var applicants = dtSource.GetApplicants(); SampleInstituteData sampleInstituteData = new SampleInstituteData(); sampleInstituteData.PoolSize = 30; // this can be changed to take user input List<Institute> institutes = sampleInstituteData.GetInstitutes(); int counter = 0; // used to vary item selection, will use random number generator once this portion is moved from main int instituteMinimumScoreNeededForAcceptance = institutes[counter % institutes.Count].MinimumScore; string instituteAppliedTo = institutes[counter % institutes.Count].InstituteName; Institute institute = new Institute(pub); institute.InstituteName = instituteAppliedTo; institute.MinimumScore = instituteMinimumScoreNeededForAcceptance; ApplicationStack applicantStack = new ApplicationStack(); Subscriber subscriber = new Subscriber(pub); foreach(Applicant applicant in applicants) { if(applicant==null) { Console.WriteLine("null ref"); } applicant.SchoolAppliedTo = instituteAppliedTo; //applicant.ScoreNeeded = instituteMinimumScoreNeededForAcceptance; counter ++; applicant.ScoreNeeded = instituteMinimumScoreNeededForAcceptance; if(applicant.StandardizedTest < instituteMinimumScoreNeededForAcceptance) { Program.AdmissionDeciled(applicant, institute); applicant.AcceptedMatch = false; } else { applicant.AcceptedMatch = true; subscriber.Applicant = applicant.FirstName; subscriber.Score = applicant.StandardizedTest; // not sure if initiallizing AcceptanceLetter's Institue property through pub.DoSomething() is decoupling or code smell pub.DoSomething(institutes[counter % institutes.Count].InstituteName); } string countString = counter.ToString(); Console.WriteLine($"counter:{counter} \t"); applicantStack.ApplicantStack.Push(applicant); Console.WriteLine($"Applicants Stack {applicantStack.ApplicantStack.Count}"); Console.WriteLine($"SampleData.application:{applicant}\n"); } PostApplicationResults postApplicationResults = new PostApplicationResults(new Applicants(applicantStack)); postApplicationResults.StatsClass(); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } } } // incorporate this Working shuffle into the mail service to randomize letter acceptances /* Random rnd = new Random(); applicants.Shuffle<Applicant>(rnd); foreach(var applicant in applicants){ Console.WriteLine("Post Fish-Yates SampleData.application :{0}", applicant); } */ <file_sep>using System.Collections.Generic; namespace ConsoleApplication { public interface IApplicants { int GetTotalNumberOfApplicants(); int GetTotalNumberOfAcceptedApplicants(); int GetTotalNumberOfDeclinedApplicants(); decimal AverageApplicantClassAcceptance(); void ApplicantAcceptDeclineListSeparator(); Stack<Applicant> ApplicantStack{get;set;} decimal AcceptedApplicantStandardizedScoreDifference(); } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public class SampleInstituteData { public int PoolSize { get; set; } string[] instituteArr = new string[14]{"USC", "Clemson", "Citadel", "CofC", "UGA", "UF","FSU", "GT", "UGA","JMU","UVA","VT", "UNC", "NCST"}; public int[] instituteMinScores{ get; set; } public void SetInstituteTestRequirements() { instituteMinScores = new int [PoolSize]; Random randomNum = new Random(); for(int i = 0; i < PoolSize; i++ ) { instituteMinScores[i] = randomNum.Next(1000, 1600); } } public List<Institute> GetInstitutes() { SetInstituteTestRequirements(); List<Institute> institutes = new List<Institute>(); Institute institute = new Institute(); Random rnd = new Random(); byte[] byteArr = new byte[20]; rnd.NextBytes(byteArr); for(int i = byteArr.GetLowerBound(0); i<= byteArr.GetUpperBound(0); i++) { institute = new Institute { InstituteName = instituteArr[byteArr[i] % instituteArr.Length], MinimumScore = instituteMinScores[byteArr[i] % instituteMinScores.Length] }; institutes.Add(institute); } return institutes; } } }<file_sep>using System.Collections.Generic; namespace ConsoleApplication { public class ApplicationStack { public Stack<Applicant> ApplicantStack {get; set;} public ApplicationStack() { ApplicantStack = ApplicantStack ?? new Stack<Applicant>(); } } }<file_sep>using System; namespace ConsoleApplication { public class Publisher { Object objectLock = new Object(); public event EventHandler<AcceptanceLetter> RaiseCustomEvent; public event EventHandler<AcceptanceLetter> RaiseCustomEvents { add { lock (objectLock) { RaiseCustomEvent += value; } } remove { lock (objectLock) { RaiseCustomEvent -= value; } } } public void DoSomething(string institute) //Institute institute) { OnRaisedEvent(new AcceptanceLetter(institute)); // make canidate object } void OnRaisedEvent(AcceptanceLetter e) { EventHandler<AcceptanceLetter> handler = RaiseCustomEvent; if(handler != null) { e.Message += String.Format($" Date: {DateTime.Now}"); handler(this,e); } } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public class DataFactory { Dictionary<DataSource,Lazy<ILoadApplicants>> _loadApplicantSource; public DataFactory(Dictionary<DataSource,Lazy<ILoadApplicants>> loadApplicantSource) { _loadApplicantSource = loadApplicantSource; } public ILoadApplicants GetApplicantSource(DataSource dataSource) { Lazy<ILoadApplicants> applicantValue; if(!_loadApplicantSource.TryGetValue(dataSource, out applicantValue)) { throw new NotSupportedException("From DataFactory"); } return applicantValue.Value; } } }<file_sep>using System; using System.Collections.Generic; namespace ConsoleApplication { public class DbData : ILoadApplicants { public List<Applicant> GetApplicants() { throw new NotImplementedException("CSVdata"); } } }<file_sep> namespace ConsoleApplication { public class Applicant { // could implement a 'stadardized test' that uses a factory to return respective test act,sat,gate,mcat,gmat,gre public string FirstName{ get;set; } public string LastName{ get;set; } public string FullName{ get{return FirstName + " " + LastName; } } public string SchoolAppliedTo { get; set; } public int StandardizedTest{ get;set; } public int ScoreNeeded { get; set; } public bool AcceptedMatch { get; set; } public Applicant(){} public Applicant(string fname, string lname, int standardTest) { FirstName = fname; LastName = lname; StandardizedTest = standardTest; } public override string ToString(){ return $"{FirstName}"; } } }
44ea180f1dc8d39f7cb82c03e0b9a291e1650a7b
[ "Markdown", "C#" ]
20
C#
rcmontgo/CollegeAcceptance
51b54743aeed9b9e30920f1c9fdd348dbca7f503
63f6c10c8215f6617bf167f2c66fac9ed6cb34f4
refs/heads/master
<repo_name>yodji09/Individual_Project<file_sep>/server/routes/anime.js "use strict"; const router = require('express').Router(); const AnimeController = require("../controller/AnimeController"); const Authentication = require("../middlewares/authentication"); const Authorization = require("../middlewares/authorization"); router.use(Authentication); router.get("/", AnimeController.findAll); router.post("/", AnimeController.create); router.get("/top", AnimeController.top); router.get("/:id", Authorization, AnimeController.findOne); router.put("/:id", Authorization, AnimeController.Watched); router.delete("/:id", Authorization, AnimeController.delete); module.exports = router;<file_sep>/server/README.md # Individual_Project ### Show Anime List * Url : /anime * Method : "GET" * Url params : Header : Token * Data params : None * Succes Response : ``` Code : 200 Content : { "Anime": [ { "id": 7, "title": "Kingdom 3rd Season", "mal_id": 40682, "genre": "", "rating": 8.6, "image_url": "https://cdn.myanimelist.net/images/anime/1332/106392.jpg?s=d111827d6fa7f273acee0c511d88c735", "url": "https://myanimelist.net/anime/40682/Kingdom_3rd_Season", "status": false, "UserId": 1, "createdAt": "2020-05-10T02:02:20.358Z", "updatedAt": "2020-05-10T04:41:03.779Z", "User": { "id": 1, "name": "<NAME>", "birthdate": "User Birthdate", "gender": "Male", "password": "<PASSWORD>", "email": "User Email", "createdAt": "2020-05-09T11:30:36.817Z", "updatedAt": "2020-05-09T11:30:36.817Z" } } ] } ``` * Error Response : ``` Code : 500 Content : "Something Went Wrong" ``` * Sample Call : ``` axios({ url: "/anime", headers: "token", type : "get", success : function(result) { res.status(200).json({ Anime : result }) } }); ``` ### Create Anime List * Url : /anime * Method : "POST" * URL PARAMS : headers : token * DATA PARAMS : ``` title : string mal_id : date genre : string rating : integer image_url : string url : string ``` * Succes Response : ``` code : 201 content : { "Anime": { "id": 7, "title": "Kingdom 3rd Season", "mal_id": 40682, "genre": "", "rating": 8.6, "image_url": "https://cdn.myanimelist.net/images/anime/1332/106392.jpg?s=d111827d6fa7f273acee0c511d88c735", "url": "https://myanimelist.net/anime/40682/Kingdom_3rd_Season", "status": false, "UserId": 1, "createdAt": "2020-05-10T02:02:20.358Z", "updatedAt": "2020-05-10T04:41:03.779Z", } } ``` * Error Response : ``` Code : 500, Content : "Something Went Wrong" ``` * Sample Call : ``` axios({ url: "/anime", headers: "token", type : "post", success : function(result) { res.status(200).json({ Anime : result }) } }); ``` ### Show anime list by id * Url : /anime/:id * Method : "GET" * URL PARAMS : ``` id : Integer headers : token ``` * DATA PARAMS : ``` title : string released_date : date genre : string rating : integer url : string ``` * Succes Response : ``` code : 200 content : { "Anime": { "id": 7, "title": "Kingdom 3rd Season", "mal_id": 40682, "genre": "", "rating": 8.6, "image_url": "https://cdn.myanimelist.net/images/anime/1332/106392.jpg?s=d111827d6fa7f273acee0c511d88c735", "url": "https://myanimelist.net/anime/40682/Kingdom_3rd_Season", "status": false, "UserId": 1, "createdAt": "2020-05-10T02:02:20.358Z", "updatedAt": "2020-05-10T04:41:03.779Z", } } ``` * Error Response : ``` Code : 500, Content : "Something Went Wrong" ``` * Sample Call : ``` axios({ url: "/anime/1", headers: "token", type : "get", success : function(result) { res.status(200).json({ Anime : result }) } }); ``` ### Delete Anime From List * Url : /anime/:id * Method : "Delete" * URL PARAMS : ``` Id : Integer Headers : Token ``` * DATA PARAMS : None * Succes Response : ``` Code : 200 Content : "Succes Destroy Anime with id 1" ``` * Error Response : ``` code : 500 Content : "Something Went Wrong" ``` * Sample Call : ``` axios({ url: "/anime", headers: "token", type : "post", success : function(result) { res.status(200).json({ msg : String }) } }); ``` ### login user * Url : /user/login * Method : "POST" * URL PARAMS : NONE * DATA PARAMS : ``` Email : String Password : <PASSWORD> ``` * Succes Response : ``` Code : 202 Content : { "acces_token": "<KEY>" } ``` * Error Response : ``` Code : 400 Content : "Email/Password doesn't match" ``` * Sampe Call : ``` axios({ url : "user/login" method : "POST" data : { email : "YOUR EMAIL" password : "<PASSWORD>" } Succes : Function(result){ res.status(202).json({ acces_token : token }) } }) ``` ### google-login user * Url : /user/google-login * Method : "POST" * URL PARAMS : google_token : token * DATA PARAMS : None * Succes Response : ``` Code : 202 Content : { "acces_token": "<KEY>" } ``` * Error Response : ``` Code : 500 Content : "Something Went Wrong" ``` * Sampe Call : ``` axios({ url : "user/google-login" method : "POST" headers : { google_token : token }, Succes : Function(result){ res.status(202).json({ acces_token : token }) } }) ``` ### 3rd Api Collect data * Url : /anime/top * Method : "get" * Url Params : Headers : token * Data Params : None * Succes Response : ``` Code : 200 content : "top": [ { "mal_id": 40591, "rank": 1, "title": "Kaguya-sama wa Kokurasetai?: Tensai-tachi no Renai Zunousen", "url": "https://myanimelist.net/anime/40591/Kaguya-sama_wa_Kokurasetai__Tensai-tachi_no_Renai_Zunousen", "image_url": "https://cdn.myanimelist.net/images/anime/1764/106659.jpg?s=aab19d0f19e345e223dc26542ac3a28f", "type": "TV", "episodes": 12, "start_date": "Apr 2020", "end_date": {}, "members": 237084, "score": 8.82 }, ] ``` * Error Response : ``` Code : 500, Content : "Something Went Wrong" ``` * Sample Call : ``` axios({ url : /anime/top method : get headers : token succes : function(result){ res.status(200).json({ Anime : result }) } }) ``` ### Register User * Url : /user/register * Method : "post" * Url Params : None * Data Params : ``` Name : string, email : string, password: <PASSWORD>, confirmPassword : string ``` * Succes Response : ``` code: 200 content : { "Id" = 1 "email" = "your email" } ``` * error Response : ``` code : 500 content : Something Went Wrong ``` * Sample Call : ``` axios({ url : '/user/register' method : 'post' data : { name, email, password } onSucces : function(result){ res.status(500).json({ User : user }) } }) ``` * Update Watched Anime Url : /anime/:id methods : "put" Url Params : ``` "token" ``` Data Params : ``` status : boolean ``` OnSucces : ``` Code : 200 Content : { Anime : { status : true } } ``` On Failed : ``` code:500 content : { "Something Went Wrong" } Sample Call : ``` axios({ url : anime/:2 method : "put" header : { token } OnSucces(function(result) => { res.status(200).json({ json }) }) })<file_sep>/server/models/anime.js 'use strict'; module.exports = (sequelize, DataTypes) => { class Anime extends sequelize.Sequelize.Model{} Anime.init({ title: { type : DataTypes.STRING, validate : { notEmpty : true } }, mal_id: DataTypes.INTEGER, genre: DataTypes.STRING, rating: DataTypes.FLOAT, image_url: DataTypes.STRING, url: DataTypes.STRING, status : { type : DataTypes.BOOLEAN, defaultValue : false }, UserId : { type : DataTypes.INTEGER, references : { model : "Users", key : "id" }, onDelete : "cascade", onUpdate : "cascade" } }, { sequelize, modelName : "Anime" }); Anime.associate = function(models) { Anime.belongsTo(models.User); }; return Anime; };<file_sep>/server/models/user.js 'use strict'; const {generatePassword} = require("../helpers/bcrypt"); const date = new Date(); const dateBefore = date.setFullYear(date.getFullYear() - 10); const dateAfter = date.setFullYear(date.getFullYear() - 100); module.exports = (sequelize, DataTypes) => { class User extends sequelize.Sequelize.Model{} User.init({ name: { type : DataTypes.STRING, validate : { notEmpty : true } }, password: { type : DataTypes.STRING, validate : { notEmpty : true, len : [8, 50] } }, email: { type : DataTypes.STRING, unique : true, validate : { isEmail : true, notEmpty : true } } }, { sequelize, hooks : { beforeCreate : (user) => { user.password = <PASSWORD>Password(<PASSWORD>); } }, modelName : "User" }); User.associate = function(models) { User.hasMany(models.Anime); }; return User; };<file_sep>/server/seeders/20200509085605-seed-User.js 'use strict'; const {generatePassword} = require("../helpers/bcrypt"); module.exports = { up: (queryInterface, Sequelize) => { let data = [{ name : "<NAME>", password : generatePassword("<PASSWORD>"), email : "<EMAIL>" }]; data[0].createdAt = new Date(); data[0].updatedAt = new Date(); return queryInterface.bulkInsert("Users", data, {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete("Users", null, {}); } }; <file_sep>/server/controller/AnimeController.js "use strict"; const {Anime} = require("../models"); const {User} = require("../models"); const axios = require("axios"); class AnimeController{ static findAll(req, res, next){ const UserId = req.currentUser; Anime .findAll({ where : { UserId, }, include : User, order : [["id", "DESC"]] }) .then(result => { res.status(200).json({ Anime : result }); }) .catch(err => { next(err); }); } static findOne(req, res, next){ const {id} = req.params; Anime .findByPk(id) .then(anime => { res.status(200).json({ Anime : anime }); }) .catch(err => { next(err); }); } static create(req, res, next){ const {title, episode, mal_id, image_url, genre, rating, url} = req.body; const UserId = req.currentUser; const value = { title, episode, mal_id, image_url, genre, rating, url, UserId }; Anime .create(value) .then(result => { res.status(201).json({ Anime : result, }); }) .catch(err => { next(err); }); } static delete(req, res, next){ const {id} = req.params; Anime .destroy({ where : { id } }) .then(result => { res.status(200).json({ msg : `Succes destroy anime with id ${id}` }); }) .catch(err => { next(err); }); } static top(req, res, next){ axios({ url : "https://api.jikan.moe/v3/top/anime/1/airing", method : "get" }) .then(data =>{ res.status(200).json({ Anime : data.data }); }) .catch(err => { return next(err); }); } static Watched(req, res, next){ const {id} = req.params; const {status} = req.body; const value = { status, }; Anime .update(value, { where : { id, } }) .then(result => { res.status(200).json({ Anime : result }); }) .catch(err => { next(err); }); } } module.exports = AnimeController;<file_sep>/server/middlewares/authorization.js "use strict"; const {Anime} = require("../models"); function Authorization(req, res, next){ const UserId = req.currentUser; const {id} = req.params; Anime .findByPk(id) .then(list => { if(list.UserId === UserId){ next(); } else { next({ type : "Not Authorized", code : 401, msg : "You are not allowed to do this" }); } }) .catch(err=> { next (err); }); } module.exports = Authorization;
13a8e1bd5a925e66fda8386ebf6bf9d4398c636b
[ "JavaScript", "Markdown" ]
7
JavaScript
yodji09/Individual_Project
c65a82ee1b71a6966ac5161d1675fbb75d21b95a
df6d2dcc54148d03f2158ae74fe3cca4fbbd8b8c
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import AbstractUser from django.utils import timezone # Base User class User(AbstractUser): email = models.CharField(max_length=100, unique=True, null=True) avatar = models.ImageField(max_length=256, null=True) utype = models.CharField(max_length=30) # admin user class Admin(User): pass # Commen User class CommonUser(User): creditLevel = models.FloatField(default=3) experience = models.IntegerField(default=0) telephone = models.CharField(max_length=20, unique=True, null=True) alipayNumber = models.CharField(max_length=30, null=True) wechatNumber = models.CharField(max_length=30, null=True) class Meta: abstract = True # translator class Translator(CommonUser): # wechatNumber = models.CharField(max_length=30, null=True) pass # employer class Employer(CommonUser): # wechatNumber = models.CharField(max_length=30, null=True) pass # task table class Task(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=512, null=True) # (saved:0/published&running:1/closed:2) status = models.IntegerField(default=0) fileUrl = models.FileField(max_length=256, null=True) fileType = models.IntegerField() # 0:文本;1:音频; 2:视频; 3:其他 employer = models.ForeignKey( Employer, on_delete=models.CASCADE ) # time publishTime = models.DateTimeField(default=timezone.now) ddlTime = models.DateTimeField() languageOrigin = models.IntegerField(default = 0) languageTarget = models.IntegerField() requirementLicense = models.IntegerField(null=True) requirementCreditLevel = models.FloatField(null=True) testText = models.TextField(max_length=1000, null=True) class Tag(models.Model): tag = models.CharField(max_length=128, unique=True) tasks = models.ManyToManyField(Task) class Assignment(models.Model): description = models.TextField(max_length=1000) # (saved:0/published:1/running:2/finished:3/arguing:4/tryTranslate: 10) status = models.IntegerField(default=0) testResult = models.TextField(max_length=1000, null=True) task = models.ForeignKey(Task, on_delete=models.CASCADE) order = models.IntegerField() translator = models.ForeignKey(Translator, null=True, on_delete=models.CASCADE) scores = models.FloatField(null=True) comment = models.TextField(null=True) price = models.IntegerField(null=True) submission = models.FileField(max_length=256, null=True) experience = models.IntegerField(default=0) # dispute class Dispute(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) employerStatement = models.TextField(max_length=1000, null=True) translatorStatement = models.TextField(max_length=1000, null=True) status = models.IntegerField(default=0) # 0:未处理;1:TranslatorSide 2: EmployerSide adminStatement = models.TextField(max_length=1000, null=True) # language type # CHINESE = 0 # ENGLISH = 1 # JAPANESE = 2 # FRENCH = 3 # RUSSIAN = 4 # SPAINISH = 5 # language class Language(models.Model): languageType = models.IntegerField() translators = models.ManyToManyField(Translator) # license type # CET4 = 0 # CET6 = 1 # TOFEL100 = 2 # TOFEL110 = 3 # license class License(models.Model): licenseType = models.IntegerField() licenseImage = models.ImageField(max_length=256, null=True) belonger = models.ForeignKey(Translator, on_delete=models.CASCADE) adminVerify = models.IntegerField(default=0) # 0:未处理;1:有效 2: 无效 <file_sep>import Vue from 'vue' import Router from 'vue-router' import store from '../store/store' import Login from '@/components/Login' import Welcome from '@/components/Welcome' import SignUpSimple from '@/components/SignUpSimple' import SignUpMore from '@/components/SignUpMore' import EmployerPage from '@/components/EmployerPage' import TranslatorPage from '@/components/TranslatorPage' import AddTask from '@/components/AddTask' import Task from '@/components/TaskPage' import Assignment from '@/components/AssignmentPage' import Square from '@/components/Square' import Manager from '@/components/Manager' Vue.use(Router) const router = new Router({ // mode: 'history', routes: [ { path: '/', name: 'welcome', meta: { notRequireAuth: true }, component: Welcome }, { path: '/login', name: 'login', component: Login }, { path: '/signup/:utype', name: 'signup', component: SignUpSimple }, { path: '/signupmore', name: 'signupmore', meta: { requireAuth: true }, component: SignUpMore }, { path: '/employer', name: 'employer', meta: { requireAuth: true, requireType: 'employer' }, component: EmployerPage }, { path: '/translator', name: 'translator', meta: { requireAuth: true, requireType: 'translator' }, component: TranslatorPage }, { path: '/addTask', name: 'addTask', meta: { requireAuth: true, requireType: 'employer' }, component: AddTask }, { path: '/task/:tid', name: 'task', meta: { requireAuth: true }, component: Task }, { path: '/assignment/:aid', name: 'assignment', meta: { requireAuth: true }, component: Assignment }, { path: '/square', name: 'square', component: Square }, { path: '/square/:keyword', name: 'search', component: Square }, { path: '/manager', name: 'admin', meta: { requireAuth: true, requireType: 'manager' }, component: Manager } // nginx:no 404 -> index.html(history) ] }) router.beforeEach((to, from, next) => { console.log('1') console.log(to) if (to.matched.some(r => r.meta.requireAuth)) { console.log('2') if (Number(store.state.userid) !== 0) { if (to.matched.some(r => r.meta.requireType)) { console.log(to.meta.requireType) console.log(store.state.utype) if (to.meta.requireType !== store.state.utype) { // if (store.state.utype === 'translator') { // next({ // path: '/translator' // }) // } else { // next({ // path: '/employer' // }) // } next({ path: '/' + store.state.utype }) } else { next() } } else { next() } } else { next({ path: '/login' }) } } else if (to.matched.some(r => r.meta.notRequireAuth)) { console.log('3') if (Number(store.state.userid) !== 0) { console.log('5') next({ path: '/square' }) } else { console.log('6') next() } } else { console.log('4') next() } }) export default router <file_sep># Babel [![Build Status](https://travis-ci.com/YuanHaoReginald/Babel.svg?token=<KEY>&branch=master)](https://travis-ci.com/YuanHaoReginald/Babel) Translation crowdsourcing platform. ## 小组会议守则 [小组会议守则](https://hackmd.io/s/ByVTFc8xG). ## 部分Git使用建议 [关于Git的部分组内建议](https://hackmd.io/s/Syz3ObSMM) ## Commit Mesaage规范 [Commit Message规范](https://hackmd.io/KwRgbALApgTAhgEwLQAYoHYVOgIwkndAZgGMkiFicdgAzWuGEIA=) <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-04 16:51 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('backend', '0003_auto_20180104_0020'), ] operations = [ migrations.RenameField( model_name='language', old_name='TranslatorId', new_name='translators', ), migrations.RenameField( model_name='tag', old_name='task', new_name='tasks', ), ] <file_sep>from django.conf.urls import url from . import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^UserSignUp$', views.UserSignUp, name='UserSignUp'), url(r'^UserSignIn$', views.UserSignIn, name='UserSignIn'), url(r'^UsernameCheck$', views.UsernameCheck, name='UsernameCheck'), url(r'^UserLogout$', views.UserLogout, name='UserLogout'), url(r'^GetUserInfo$', views.GetUserInfo, name='GetUserInfo'), url(r'^UserModify$', views.UserModify, name='UserModify'), url(r'^UploadAvatar$', views.UploadAvatar, name='UploadAvatar'), url(r'^CreateTask$', views.CreateTask, name='CreateTask'), url(r'^UploadTaskFile$', views.UploadTaskFile, name='UploadTaskFile'), url(r'^GetEmployerTasks$', views.GetEmployerTasks, name='GetEmployerTasks'), url(r'^GetTranslatorAssignments$', views.GetTranslatorAssignments, name='GetTranslatorAssignments'), url(r'^PickupAssignment$', views.PickupAssignment, name='PickupAssignment'), url(r'^GetTaskDetail$', views.GetTaskDetail, name='GetTaskDetail'), url(r'^GetAssignmentDetail$', views.GetAssignmentDetail, name='GetAssignmentDetail'), url(r'^GetSquareTasks$', views.GetSquareTasks, name='GetSquareTasks'), url(r'^PublishTask$', views.PublishTask, name='PublishTask'), url(r'^SubmitAssignment$', views.SubmitAssignment, name='SubmitAssignment'), url(r'^SolveDispute$', views.SolveDispute, name='SolveDispute'), url(r'^VerifyLicense$', views.VerifyLicense, name='VerifyLicense'), url(r'^GetManager$', views.GetManager, name='GetManager'), url(r'^AcceptAssignment$', views.AcceptAssignment, name='AcceptAssignment'), url(r'^FileDownload$', views.FileDownload, name='FileDownload'), url(r'^UploadLicense$', views.UploadLicense, name='UploadLicense'), url(r'^ResponseTestResult$', views.ResponseTestResult, name='ResponseTestResult'), url(r'^SubmitTestResult$', views.SubmitTestResult, name='SubmitTestResult'), url(r'^AcceptResult$', views.AcceptResult, name='AcceptResult'), url(r'^ArgueResult$', views.ArgueResult, name='ArgueResult'), ] <file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-02 17:28 from __future__ import unicode_literals from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('email', models.CharField(max_length=100, null=True, unique=True)), ('avatar', models.ImageField(max_length=256, null=True, upload_to='')), ('utype', models.CharField(max_length=30)), ], options={ 'verbose_name': 'user', 'abstract': False, 'verbose_name_plural': 'users', }, managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Assignment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.TextField(max_length=1000)), ('status', models.IntegerField(default=0)), ('order', models.IntegerField()), ('scores', models.FloatField(null=True)), ('price', models.IntegerField(null=True)), ('submission', models.FileField(max_length=256, null=True, upload_to='')), ('experience', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Dispute', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('employerStatement', models.TextField(max_length=1000, null=True)), ('translatorStatement', models.TextField(max_length=1000, null=True)), ('status', models.IntegerField(default=0)), ('adminStatement', models.TextField(max_length=1000, null=True)), ('assignment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.Assignment')), ], ), migrations.CreateModel( name='Language', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('languageType', models.IntegerField()), ], ), migrations.CreateModel( name='License', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('licenseType', models.IntegerField()), ('licenseImage', models.ImageField(max_length=256, upload_to='')), ('description', models.CharField(max_length=100, null=True)), ('adminVerify', models.IntegerField(default=0)), ], ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tag', models.CharField(max_length=128, unique=True)), ], ), migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=30)), ('description', models.CharField(max_length=512, null=True)), ('status', models.IntegerField(default=0)), ('fileUrl', models.FileField(max_length=256, null=True, upload_to='')), ('fileType', models.IntegerField()), ('publishTime', models.DateTimeField(default=django.utils.timezone.now)), ('ddlTime', models.DateTimeField()), ('languageOrigin', models.IntegerField(default=0)), ('languageTarget', models.IntegerField()), ('requirementLicense', models.IntegerField(null=True)), ('requirementCreditLevel', models.FloatField(null=True)), ('testText', models.TextField(max_length=1000, null=True)), ('testResult', models.TextField(max_length=1000, null=True)), ], ), migrations.CreateModel( name='Admin', fields=[ ('user_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'user', 'abstract': False, 'verbose_name_plural': 'users', }, bases=('backend.user',), managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Employer', fields=[ ('user_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('creditLevel', models.FloatField(default=3)), ('experience', models.IntegerField(default=0)), ('telephone', models.CharField(max_length=20, null=True, unique=True)), ('alipayNumber', models.CharField(max_length=30, null=True)), ('wechatNumber', models.CharField(max_length=30, null=True)), ], options={ 'abstract': False, }, bases=('backend.user',), managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.CreateModel( name='Translator', fields=[ ('user_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('creditLevel', models.FloatField(default=3)), ('experience', models.IntegerField(default=0)), ('telephone', models.CharField(max_length=20, null=True, unique=True)), ('alipayNumber', models.CharField(max_length=30, null=True)), ('wechatNumber', models.CharField(max_length=30, null=True)), ], options={ 'abstract': False, }, bases=('backend.user',), managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.AddField( model_name='tag', name='task', field=models.ManyToManyField(to='backend.Task'), ), migrations.AddField( model_name='assignment', name='task', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.Task'), ), migrations.AddField( model_name='user', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'), ), migrations.AddField( model_name='user', name='user_permissions', field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'), ), migrations.AddField( model_name='task', name='employer', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.Employer'), ), migrations.AddField( model_name='license', name='belonger', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='backend.Translator'), ), migrations.AddField( model_name='language', name='TranslatorId', field=models.ManyToManyField(to='backend.Translator'), ), migrations.AddField( model_name='assignment', name='translator', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='backend.Translator'), ), ] <file_sep>from django.contrib import auth from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django import http from django.http import HttpResponse, JsonResponse, StreamingHttpResponse from .models import * from django.core import serializers from django.db import transaction import datetime import os import json import time from Babel import settings from urllib.parse import urljoin # Create your views here. # user signup def UserSignUp(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) newUsername = infoDict['username'] newPassword = infoDict['<PASSWORD>'] newEmail = infoDict['email'] userType = infoDict['utype'] try: existedUser = User.objects.get(username=newUsername) responseDict = {'id': 0} except: if userType == 'translator': newUser = Translator.objects.create_user(username=newUsername, password=<PASSWORD>, email=newEmail, utype='translator') elif userType == 'employer': newUser = Employer.objects.create_user(username=newUsername, password=<PASSWORD>, email=newEmail, utype='employer') responseDict = {'id': newUser.id} auth.login(request, newUser) return JsonResponse(responseDict) # user login def UserSignIn(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) username = infoDict['username'] password = infoDict['<PASSWORD>'] user = auth.authenticate(username=username, password=password) if user is None: return JsonResponse({'id': 0}) else: auth.login(request, user) return JsonResponse({'id': user.id, 'utype': user.utype}) def UsernameCheck(request): if request.method == 'POST': username = json.loads(request.body.decode())['username'] try: user = User.objects.get(username=username) return JsonResponse({'status': True}) except: return JsonResponse({'status': False}) def UserLogout(request): auth.logout(request) return HttpResponse(0) # get user info def GetUserInfo(request): if request.method == 'GET': user = auth.get_user(request) if user.utype == 'translator': user = user.translator elif user.utype == 'employer': user = user.employer responseDict = {'username': user.username, 'email': user.email, 'avatar': '', 'level': user.creditLevel, 'experience': user.experience} if user.avatar: responseDict['avatar'] = user.avatar.url return JsonResponse(responseDict) # sign up more def UserModify(request): user = auth.get_user(request) if user.utype == 'translator': user = user.translator elif user.utype == 'employer': user = user.employer if request.method == 'POST': try: infoDict = json.loads(request.body.decode()) user.telephone = infoDict['telephone'] user.alipayNumber = infoDict['alipayNumber'] user.wechatNumber = infoDict['wechatNumber'] user.save() return JsonResponse({'status': True}) except: return JsonResponse({'status': False}) elif request.method == 'GET': responseDict = {'telephone': user.telephone, 'wechatNumber': user.wechatNumber, 'alipayNumber': user.alipayNumber, 'language': '', 'avatar': user.avatar.url if user.avatar else ''} return JsonResponse(responseDict) def UploadAvatar(request): if request.method == 'POST': avatar = request.FILES.get('avatar') user = auth.get_user(request) fileExtension = avatar.name.split('.')[-1] user.avatar.delete() user.avatar.save('avatars/' + user.username + '.' + fileExtension, avatar) return JsonResponse({'url': user.avatar.url}) def CreateTask(request): if request.method == 'POST': user = auth.get_user(request).employer infoDict = json.loads(request.body.decode()) taskTitle = infoDict['title'] taskDescription = infoDict['description'] taskLanguage = infoDict['language'] if infoDict['license'] == 'cet4': taskLicense = 4 elif infoDict['license'] == 'cet8': taskLicense = 8 taskLevel = infoDict['level'] taskTags = infoDict['tags'] taskDdlTime = infoDict['ddlTime'] taskAssignments = infoDict['assignments'] if infoDict['language'] == 'English': taskLanguageTarget = 1 elif infoDict['language'] == 'Japanese': taskLanguageTarget = 2 elif infoDict['language'] == 'French': taskLanguageTarget = 5 elif infoDict['language'] == 'Russian': taskLanguageTarget = 4 elif infoDict['language'] == 'Spanish': taskLanguageTarget = 5 if infoDict['if_test'] == '需要': taskTestText = infoDict['testText'] else: taskTestText = '' task = Task.objects.create(title = taskTitle, description = taskDescription, fileType = 0, employer = user, ddlTime = datetime.datetime.utcfromtimestamp(taskDdlTime), languageTarget = taskLanguageTarget, requirementCreditLevel = taskLevel, requirementLicense = taskLicense, testText = taskTestText) for tag in taskTags: Tag.objects.get(tag=tag).tasks.add(task) for assignment in taskAssignments: Assignment.objects.create(task = task, order = assignment['order'], price = assignment['price'], description = assignment['text']) return JsonResponse({'task_id': task.id}) def UploadTaskFile(request): if request.method == 'POST': file = request.FILES.get('file') taskId = request.POST.get('id') task = Task.objects.get(id = taskId) task.fileUrl.save('tasks/' + file.name, file) return JsonResponse({'url': task.fileUrl.name}) def GetEmployerTasks(request): if request.method == 'GET': currentUser = auth.get_user(request).employer taskSet = currentUser.task_set.all() responseDict = {'taskList': []} for task in taskSet: _task_tag = task.tag_set.all() _temp_tag_list = [] for tag in _task_tag: _temp_tag_list.append(tag.tag) responseDict['taskList'].append({ 'id': task.id, 'title': task.title, 'status': task.status, 'publishTime': task.publishTime.timestamp(), 'ddlTime': task.ddlTime.timestamp(), 'tags': _temp_tag_list, 'language': task.languageOrigin if task.languageOrigin == 0 else task.languageTarget, 'description': task.description, }) return JsonResponse(responseDict) def GetTranslatorAssignments(request): if request.method == 'GET': currentUser = auth.get_user(request).translator assignmentSet = currentUser.assignment_set.all() responseDict = {'assignmentList': []} for assignment in assignmentSet: task = assignment.task _task_tag = task.tag_set.all() _temp_tag_list = [] for tag in _task_tag: _temp_tag_list.append(tag.tag) responseDict['assignmentList'].append({ 'id': assignment.id, 'status': assignment.status, 'title': task.title, 'publishTime': task.publishTime.timestamp(), 'ddlTime': task.ddlTime.timestamp(), 'tags': _temp_tag_list, 'language': task.languageOrigin if task.languageOrigin == 0 else task.languageTarget, 'description': assignment.description, }) return JsonResponse(responseDict) def PickupAssignment(request): if request.method == 'POST': user = auth.get_user(request).translator infoDict = json.loads(request.body.decode()) taskId = infoDict['task_id'] assignmentOrder = infoDict['assignment_order'] task = Task.objects.get(id = taskId) assignment = Assignment.objects.get(task = task, order = assignmentOrder) # Check Translator Qualification Review if user.creditLevel < task.requirementCreditLevel: return JsonResponse({'status': False, 'reason': 'Level don\'t meet requirements.'}) licenseSet = user.license_set.filter(adminVerify=1) flag = False for _license in licenseSet: if _license.licenseType // 10 == task.languageTarget: flag = True break if not flag: return JsonResponse({'status': False, 'reason': 'Language License don\'t meet requirements.'}) # Try Receive Assignment with transaction.atomic(): if assignment.status == 1: assignment.translator = user assignment.status = 2 assignment.save() return JsonResponse({'status': True}) else: return JsonResponse({'status': False, 'reason': 'Assignment has been picked up by others.'}) def GetTaskDetail(request): if request.method == 'GET': print('-----------------------GetTaskDetail-----------------') taskId = request.GET.get('taskid') task = Task.objects.get(id=taskId) responseDict = { 'id': task.id, 'title': task.title, 'status': task.status, 'description': task.description, 'publishTime': task.publishTime.timestamp(), 'ddlTime': task.ddlTime.timestamp(), 'language': task.languageTarget if task.languageOrigin == 0 else task.languageTarget, 'fileUrl': task.fileUrl.name.split('/')[-1] if task.fileUrl else '', 'employerId': task.employer.id, 'requirementLevel': task.requirementCreditLevel, 'requirementLicense': task.requirementLicense, 'testText': task.testText, 'assignment': [] } assignment_set = task.assignment_set.all() for assignment in assignment_set: _dispute = Dispute.objects.filter(assignment=assignment) statement = '' if len(_dispute) != 0 and _dispute[0].adminStatement: statement = _dispute[0].adminStatement responseDict['assignment'].append({ 'id': assignment.id, 'hasDispute' : len(_dispute) != 0, 'disputeResult' : _dispute[0].status if len(_dispute) != 0 else 0, 'statement' : statement, 'order': assignment.order, 'description': assignment.description, 'translator': assignment.translator.username if assignment.translator else '', 'status': assignment.status, 'score': assignment.scores, 'price': assignment.price, 'testResult': assignment.testResult, 'submission': assignment.submission.name.split('/')[-1] if assignment.submission else '', }) return JsonResponse(responseDict) def GetAssignmentDetail(request): if request.method == 'GET': print('-----------------------GetAssignmentDetail-----------------') assignmentid = request.GET.get('assignmentid') assignment = Assignment.objects.get(id=assignmentid) _dispute = Dispute.objects.filter(assignment=assignment) statement = '' if len(_dispute) != 0 and _dispute[0].adminStatement: statement = _dispute[0].adminStatement task = assignment.task responseDict = { 'id': task.id, 'title': task.title, 'description': task.description, 'publishTime': task.publishTime.timestamp(), 'ddlTime': task.ddlTime.timestamp(), 'language': task.languageOrigin if task.languageOrigin == 0 else task.languageTarget, 'assignment': { 'id': assignment.id, 'hasDispute' : len(_dispute) != 0, 'disputeResult' : _dispute[0].status if len(_dispute) != 0 else 0, 'statement' : statement, 'description': assignment.description, 'translator': assignment.translator.username if assignment.translator else '', 'status': assignment.status, 'score': assignment.scores, 'price': assignment.price, 'submission': assignment.submission.name if assignment.submission else '' }, 'owner': { 'name': task.employer.username, 'avatar': task.employer.avatar.url if task.employer.avatar else '' } } return JsonResponse(responseDict) def GetSquareTasks(request): if request.method == 'GET': print('-----------------------GetSquareTasks-----------------') keyword = request.GET.get('keyword') taskSet = Task.objects.filter(status=1).order_by('publishTime') if keyword != None: taskSet = taskSet.filter(title__contains = keyword) if taskSet.count() > 50: taskSet = taskSet.reverse()[:50] responseDict = {'taskList': []} for task in taskSet: _task_tag = task.tag_set.all() _temp_tag_list = [] for tag in _task_tag: _temp_tag_list.append(tag.tag) assignmentSet = task.assignment_set.all() _temp_assignment = [] for assignment in assignmentSet: _temp_assignment.append({ 'order': assignment.order, 'description': assignment.description, 'translator': assignment.translator.username if assignment.translator else '', 'status': assignment.status, 'score': assignment.scores, 'price': assignment.price, 'submission': assignment.submission.url if assignment.submission else '', }) responseDict['taskList'].append({ 'id': task.id, 'title': task.title, 'publishTime': task.publishTime.timestamp(), 'ddlTime': task.ddlTime.timestamp(), 'tags': _temp_tag_list, 'language': task.languageTarget if task.languageOrigin == 0 else task.languageTarget, 'description': task.description, 'testText': task.testText, 'assignment': _temp_assignment }) return JsonResponse(responseDict) def SubmitAssignment(request): if request.method == 'POST': file = request.FILES.get('file') assignmentId = request.POST.get('assignmentid') assignment = Assignment.objects.get(id = assignmentId) assignment.submission.save('assignments/' + file.name, file) return JsonResponse({'url': assignment.submission.name.split('/')[-1]}) def PublishTask(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) taskId = infoDict['taskid'] task = Task.objects.get(id=taskId) task.status = 1 task.save() assignmentSet = task.assignment_set.all() for assignment in assignmentSet: assignment.status = 1 assignment.save() return JsonResponse({'status': True}) def SolveDispute(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) disputeId = infoDict['disputeid'] result = infoDict['result'] statement = infoDict['statement'] dispute = Dispute.objects.get(id=disputeId) dispute.adminStatement = statement if result: dispute.status = 1 else: dispute.status = 2 dispute.save() dispute.assignment.status = 3 dispute.assignment.save() return JsonResponse({'status': True}) def VerifyLicense(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) licenseId = infoDict['licenseid'] result = infoDict['result'] license = License.objects.get(id=licenseId) if result: license.adminVerify = 1 else: license.adminVerify = 2 license.save() return JsonResponse({'status': True}) def GetManager(request): if request.method == 'GET': print('-----------------------GetManager-----------------') responseDict = { 'DisputeList': [], 'LicenseList': [] } disputeSet = Dispute.objects.filter(status=0) if disputeSet.count() > 100: disputeSet = disputeSet[:100] for dispute in disputeSet: responseDict['DisputeList'].append({ 'id': dispute.id, 'assignment_name': dispute.assignment.description, 'argument_translator': dispute.translatorStatement, 'argument_employer': dispute.employerStatement, }) licenseSet = License.objects.filter(adminVerify=0) if licenseSet.count() > 100: licenseSet = licenseSet[:100] for _license in licenseSet: responseDict['LicenseList'].append({ 'id': _license.id, 'type': _license.licenseType, 'url': _license.licenseImage.url, }) return JsonResponse(responseDict) def AcceptAssignment(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) assignmentId = infoDict['assignmentid'] result = infoDict['result'] acceptance = infoDict['acceptance'] assignment = Assignment.objects.get(id=assignmentId) if acceptance == 'accept': assignment.scores = result assignment.status = 3 elif acceptance == 'reject': assignment.comment = result assignment.status = 4 assignment.save() return JsonResponse({'status': True}) def FileDownload(request): def fileIterator(fileName, chunkSize=512): with open(fileName, 'rb') as f: while True: c = f.read(chunkSize) if c: yield c else: break if request.method == 'GET': downloadType = request.GET.get('type') root = 'C:/Users/yw/Desktop/Babel/media/' + downloadType filename = request.GET.get('filename') response = http.StreamingHttpResponse(fileIterator(root + '/' + filename)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename) return response def UploadLicense(request): if request.method == 'POST': lfile = request.FILES.get('license') ltype = request.POST.get('type') language = request.POST.get('language') if ltype == 'cet4': ltype = 4 elif ltype == 'cet8': ltype = 8 else: pass if language == 'English': ltype += 10 elif language == 'Japanese': ltype += 20 elif language == 'French': ltype += 30 elif language == 'Russian': ltype += 40 elif language == 'Spanish': ltype += 50 else: pass user = auth.get_user(request) _license = License.objects.create(licenseType = ltype, belonger = user.translator) _license.licenseImage.save('licenses/' + lfile.name, lfile) return JsonResponse({'url': _license.name.split('/')[-1]}) def ResponseTestResult(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) assignmentId = infoDict['assignment_id'] assignment = Assignment.objects.get(id = assignmentId) result = infoDict['result'] if result: assignment.status = 2 else: assignment.status = 1 assignment.translator = None assignment.save() return HttpResponse(0) def SubmitTestResult(request): if request.method == 'POST': user = auth.get_user(request).translator infoDict = json.loads(request.body.decode()) taskId = infoDict['task_id'] assignmentOrder = infoDict['assignment_order'] testResult = infoDict['testResult'] task = Task.objects.get(id = taskId) assignment = Assignment.objects.get(task = task, order = assignmentOrder) with transaction.atomic(): if assignment.status == 1: assignment.translator = user assignment.status = 10 assignment.testResult = testResult assignment.save() return JsonResponse({'translator': assignment.translator.username}) def AcceptResult(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) assignment = Assignment.objects.get(id=infoDict['assignmentId']) assignment.status = 3 assignment.save() return JsonResponse({'status': True}) def ArgueResult(request): if request.method == 'POST': infoDict = json.loads(request.body.decode()) assignment = Assignment.objects.get(id=infoDict['assignmentId']) Dispute.objects.create(assignment=assignment, employerStatement=assignment.comment, translatorStatement=infoDict['text']) return JsonResponse({'status': True}) <file_sep>from django.test import TestCase from django.test.client import Client from .views import * from .models import * from django.core.urlresolvers import resolve from django.contrib import auth from django.contrib.auth import authenticate, login, logout from unittest.mock import Mock,patch,MagicMock from django.http import HttpRequest import backend.urls import json # Create your tests here. class UserSignUpTestCase(TestCase): def test_employer_sign_up_with_normal_username(self): found = resolve('/UserSignUp', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertNotEqual(response['id'], 0) def test_translator_sign_up_with_normal_username(self): found = resolve('/UserSignUp', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"translator"}') with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertNotEqual(response['id'], 0) def test_employer_sign_up_with_repeated_username(self): found = resolve('/UserSignUp', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response = json.loads(found.func(request).content.decode()) request1 = Mock(wraps=HttpRequest(), method='POST') request1.body = Mock() request1.body.decode = Mock( return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response1 = json.loads(found.func(request1).content.decode()) self.assertEqual(response1['id'], 0) class UserSignInTestCase(TestCase): def test_user_exist(self): found = resolve('/UserSignUp', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response = json.loads(found.func(request).content.decode()) found1 = resolve('/UserSignIn', urlconf=backend.urls) request1 = Mock(wraps=HttpRequest(), method='POST') request1.body = Mock() request1.body.decode = Mock( return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","utype":"employer"}') with patch.object(auth, 'authenticate', return_value=Mock(id = 1,utype = 'employer')) as MockUser: with patch.object(auth, 'login', return_value=Mock(student_id=1)) as MockUser: response1 = json.loads(found1.func(request1).content.decode()) self.assertNotEqual(response1['id'], 0) def test_user_not_exist(self): found1 = resolve('/UserSignIn', urlconf=backend.urls) request1 = Mock(wraps=HttpRequest(), method='POST') request1.body = Mock() request1.body.decode = Mock( return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","utype":"employer"}') with patch.object(auth, 'authenticate', return_value = None ) as MockUser: response1 = json.loads(found1.func(request1).content.decode()) self.assertEqual(response1['id'], 0) class UsernameCheckTestCase(TestCase): def test_normal_test_case(self): found = resolve('/UsernameCheck', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock( return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(User.objects, 'get', return_value=Mock(student_id=1)) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class UserLogoutTestCase(TestCase): def test_common_user_log_out(self): found = resolve('/UserLogout', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'logout', return_value=Mock()) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response, 0) class GetUserInfoTestCase(TestCase): def test_get_translator_info(self): found = resolve('/GetUserInfo', urlconf = backend.urls) myavatar = Mock(url = '123.jpg') request = Mock(wraps= HttpRequest() , method = 'GET') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"translator"}') with patch.object(auth, 'get_user', return_value=Mock(username = 'shaoyushan',email = '<EMAIL>', headSrc = '', creditLevel = 2, experience = 2,avatar = myavatar )) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['username'], 'shaoyushan') def test_get_employer_info(self): found = resolve('/GetUserInfo', urlconf = backend.urls) myavatar = Mock(url = '123.jpg') request = Mock(wraps= HttpRequest() , method = 'GET') request.body = Mock() request.body.decode = Mock(return_value='{"username":"shaoyushan1996","password":"<PASSWORD>","email":"<EMAIL>","utype":"employer"}') with patch.object(auth, 'get_user', return_value=Mock(username = 'shaoyushan',email = '<EMAIL>', headSrc = '', creditLevel = 2, experience = 2,avatar = myavatar )) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['username'], 'shaoyushan') class UserModifyTestCase(TestCase): def test_translator_post(self): myavatar = Mock(url='123.jpg') user_translator = Mock(telephone = '13333333333',alipayNumber = 'ali',wechatNumber = 'wechat',avatar = myavatar) found = resolve('/UserModify', urlconf = backend.urls) request = Mock(wraps = HttpRequest(), method = 'POST') request.body = Mock() request.body.decode = Mock(return_value='{"telephone":"13333333333","alipayNumber":"alipay","wechatNumber":"wechat","utype":"translator"}') with patch.object(auth, 'get_user', return_value=Mock(translator = user_translator,utype = 'translator')) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) def test_employer_GET(self): found = resolve('/UserModify', urlconf = backend.urls) myavatar = Mock(url='123.jpg') user_employer = Mock(telephone = '13333333333',alipayNumber = 'ali',wechatNumber = 'wechat',avatar = myavatar,utype = 'employer') request = Mock(wraps = HttpRequest(), method = 'GET') request.body = Mock() request.body.decode = Mock(return_value='{"telephone":"13333333333","alipayNumber":"alipay","wechatNumber":"wechat","utype":"employer"}') with patch.object(auth, 'get_user', return_value=Mock(employer = user_employer, utype = 'employer')) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['telephone'], '13333333333') # not finish class UploadAvatarTestCase(TestCase): def test_normal_test(self): found = resolve('/UploadAvatar', urlconf = backend.urls) request = Mock(wraps=HttpRequest(), method='POST') myavatar = Mock() myavatar.name = 'a.jpg' myavatar.url = 'a.jpg' myuser = Mock() myuser.username = 'shaoyushan' myuser.avatar = myavatar with patch.object(request.FILES,'get',return_value = myavatar): with patch.object(auth, 'get_user', return_value = myuser) as MockUser: response = json.loads(found.func(request).content.decode()) self.assertEqual(response['url'], 'a.jpg') class CreateTaskTestCase(TestCase): def test_normal_test_English(self): found = resolve('/CreateTask', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') mytask = Mock() mytask.add = lambda x : True request.body = Mock() request.body.decode = Mock(return_value = ' {"tags":[1,2,3],"if_test":"需要","testText":"a small text","title":"a title","description":"a des","language":"English","license":"cet4","level":2.1,"tags":"123","ddlTime":123456.23,"assignments":[{"price":123,"order":123,"text":"asd"}] }') with patch.object(auth, 'get_user', return_value = Mock(employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat' ))) as MockUser: with patch.object(Task.objects,'create', return_value = Mock(id = 1, title = '123', description = '456', fileType = 0, employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat'), ddlTime = 123.4, languageTarget = 3, requirementCreditLevel = 2.2 )): with patch.object(Assignment.objects,'create', return_value = Mock(task = None, order = 1,description = '1243')): with patch.object(Tag.objects,"get",return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['task_id'], 1) def test_normal_test_Japanese(self): found = resolve('/CreateTask', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') mytask = Mock() mytask.add = lambda x : True request.body = Mock() request.body.decode = Mock(return_value = ' {"tags":[1,2,3],"if_test":"需要","testText":"a small text","title":"a title","description":"a des","language":"Japanese","license":"cet4","level":2.1,"tags":"123","ddlTime":123456.23,"assignments":[{"price":123,"order":123,"text":"asd"}] }') with patch.object(auth, 'get_user', return_value = Mock(employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat' ))) as MockUser: with patch.object(Task.objects,'create', return_value = Mock(id = 1, title = '123', description = '456', fileType = 0, employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat'), ddlTime = 123.4, languageTarget = 3, requirementCreditLevel = 2.2 )): with patch.object(Assignment.objects,'create', return_value = Mock(task = None, order = 1,description = '1243')): with patch.object(Tag.objects,"get",return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['task_id'], 1) def test_normal_test_French(self): found = resolve('/CreateTask', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') mytask = Mock() mytask.add = lambda x : True request.body = Mock() request.body.decode = Mock(return_value = ' {"tags":[1,2,3],"if_test":"需要","testText":"a small text","title":"a title","description":"a des","language":"French","license":"cet4","level":2.1,"tags":"123","ddlTime":123456.23,"assignments":[{"price":123,"order":123,"text":"asd"}] }') with patch.object(auth, 'get_user', return_value = Mock(employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat' ))) as MockUser: with patch.object(Task.objects,'create', return_value = Mock(id = 1, title = '123', description = '456', fileType = 0, employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat'), ddlTime = 123.4, languageTarget = 3, requirementCreditLevel = 2.2 )): with patch.object(Assignment.objects,'create', return_value = Mock(task = None, order = 1,description = '1243')): with patch.object(Tag.objects,"get",return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['task_id'], 1) def test_normal_test_Russian(self): found = resolve('/CreateTask', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') mytask = Mock() mytask.add = lambda x : True request.body = Mock() request.body.decode = Mock(return_value = ' {"tags":[1,2,3],"if_test":"需要","testText":"a small text","title":"a title","description":"a des","language":"Russian","license":"cet4","level":2.1,"tags":"123","ddlTime":123456.23,"assignments":[{"price":123,"order":123,"text":"asd"}] }') with patch.object(auth, 'get_user', return_value = Mock(employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat' ))) as MockUser: with patch.object(Task.objects,'create', return_value = Mock(id = 1, title = '123', description = '456', fileType = 0, employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat'), ddlTime = 123.4, languageTarget = 3, requirementCreditLevel = 2.2 )): with patch.object(Assignment.objects,'create', return_value = Mock(task = None, order = 1,description = '1243')): with patch.object(Tag.objects,"get",return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['task_id'], 1) def test_normal_test_Spanish(self): found = resolve('/CreateTask', urlconf = backend.urls) request = Mock(wraps= HttpRequest() , method = 'POST') mytask = Mock() mytask.add = lambda x : True request.body = Mock() request.body.decode = Mock(return_value = ' {"tags":[1,2,3],"if_test":"需要","testText":"a small text","title":"a title","description":"a des","language":"Spanish","license":"cet4","level":2.1,"tags":"123","ddlTime":123456.23,"assignments":[{"price":123,"order":123,"text":"asd"}] }') with patch.object(auth, 'get_user', return_value = Mock(employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat' ))) as MockUser: with patch.object(Task.objects,'create', return_value = Mock(id = 1, title = '123', description = '456', fileType = 0, employer = Mock(creditLevel = 1.1, experience = 1, telephone = '123', alipayNumber = 'ali', wechatNumber = 'wechat'), ddlTime = 123.4, languageTarget = 3, requirementCreditLevel = 2.2 )): with patch.object(Assignment.objects,'create', return_value = Mock(task = None, order = 1,description = '1243')): with patch.object(Tag.objects,"get",return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['task_id'], 1) class UploadTaskFileTestCase(TestCase): def test_normal_test(self): found = resolve('/UploadTaskFile', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') myfile = Mock() myfile.name = 'abc.doc' mytask = Mock() mytask.fileUrl.name = 'abc.doc' with patch.object(request.FILES,'get',return_value = myfile ): with patch.object(request.POST,'get',return_value = 1): with patch.object(Task.objects,'get',return_value = mytask ): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['url'], 'abc.doc') class GetEmployerTasksTestCase(TestCase): def test_normal_test(self): found = resolve('/GetEmployerTasks', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') myTag = Mock() myTag.tag = 1 myTaskTag = [myTag] myTask = Mock() myTask.tag_set.all = lambda : myTaskTag myTask.id = 1 myTask.title = "test title" myTask.status = 1 myTask.publishTime.timestamp = lambda : 112 myTask.ddlTime.timestamp = lambda : 114 myTask.languageOrigin = 1 myTask.languageTarget = 2 myTask.description = '123' myCurrentUser = Mock() myCurrentUser.task_set.all = lambda : [myTask] myUser = Mock() myUser.employer = myCurrentUser with patch.object(auth,"get_user",return_value = myUser): response = json.loads(found.func(request).content.decode()) test_task = response['taskList'][0] self.assertEqual(test_task['id'], 1) class GetTranslatorAssignmentsTestCase(TestCase): def test_normal_test(self): found = resolve('/GetTranslatorAssignments', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') myTag = Mock() myTag.tag = 1 myTask = Mock() myTask.tag_set.all = lambda : [myTag] myTask.id = 1 myTask.title = "test title" myTask.status = 1 myTask.publishTime.timestamp = lambda : 112 myTask.ddlTime.timestamp = lambda : 114 myTask.languageOrigin = 1 myTask.languageTarget = 2 myTask.description = '123' myAssignment = Mock() myAssignment.task = myTask myAssignment.id = 1 myAssignment.status = 1 myAssignment.description = '123' myCurrentUser = Mock() myCurrentUser.assignment_set.all = lambda : [myAssignment] myUser = Mock() myUser.translator = myCurrentUser with patch.object(auth,"get_user",return_value = myUser): response = json.loads(found.func(request).content.decode()) test_task = response['assignmentList'][0] self.assertEqual(test_task['id'], 1) class PickupAssignmentTestCase(TestCase): def test_normal_test_one(self): found = resolve('/PickupAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value='{"task_id":1,"assignment_order":1}') myUser = Mock() myCurrentUser = Mock() myCurrentUser.translator = myUser myUser.creditLevel = 1 myTask = Mock() myTask.requirementCreditLevel = 2 myTask.languageTarget = 1 myAssignment = Mock() myAssignment.status = 1 with patch.object(auth,'get_user',return_value = myCurrentUser): with patch.object(Task.objects,'get',return_value = myTask): with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], False) def test_normal_test_two(self): found = resolve('/PickupAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value='{"task_id":1,"assignment_order":1}') myUser = Mock() myCurrentUser = Mock() myCurrentUser.translator = myUser myUser.creditLevel = 3 myLicense = Mock() myLicense.licenseType = 4 myUser.license_set.filter = lambda adminVerify : [myLicense] myTask = Mock() myTask.requirementCreditLevel = 2 myTask.languageTarget = 1 myAssignment = Mock() myAssignment.status = 1 with patch.object(auth,'get_user',return_value = myCurrentUser): with patch.object(Task.objects,'get',return_value = myTask): with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], False) def test_normal_test_three(self): found = resolve('/PickupAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value='{"task_id":1,"assignment_order":1}') myUser = Mock() myCurrentUser = Mock() myCurrentUser.translator = myUser myUser.creditLevel = 3 myLicense = Mock() myLicense.licenseType = 10 myUser.license_set.filter = lambda adminVerify: [myLicense] myTask = Mock() myTask.requirementCreditLevel = 2 myTask.languageTarget = 1 myAssignment = Mock() myAssignment.status = 1 with patch.object(auth, 'get_user', return_value=myCurrentUser): with patch.object(Task.objects, 'get', return_value=myTask): with patch.object(Assignment.objects, 'get', return_value=myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) def test_normal_test_four(self): found = resolve('/PickupAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value='{"task_id":1,"assignment_order":1}') myUser = Mock() myCurrentUser = Mock() myCurrentUser.translator = myUser myUser.creditLevel = 3 myLicense = Mock() myLicense.licenseType = 10 myUser.license_set.filter = lambda adminVerify: [myLicense] myTask = Mock() myTask.requirementCreditLevel = 2 myTask.languageTarget = 1 myAssignment = Mock() myAssignment.status = 2 with patch.object(auth, 'get_user', return_value=myCurrentUser): with patch.object(Task.objects, 'get', return_value=myTask): with patch.object(Assignment.objects, 'get', return_value=myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], False) class GetTaskDetailTestCase(TestCase): def test_normal_test(self): found = resolve('/GetTaskDetail', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') myTask = Mock() myTask.id = 1 myTask.title = 'title' myTask.status = 1 myTask.description = '123' myTask.publishTime.timestamp = lambda : 1234 myTask.ddlTime.timestamp = lambda :567 myTask.languageTarget = 1 myTask.languageOrigin = 2 myTask.fileUrl.name = 'a/jpg' myTask.employer.id = 1 myTask.testText = '1234' myTask.requirementCreditLevel = 1 myTask.requirementLicense = 'CET4' myAssignment = Mock() myAssignment.id = 1 myAssignment.order = 1 myAssignment.description = '12345' myAssignment.translator.username = 'shao' myAssignment.status = 1 myAssignment.scores = 1 myAssignment.price = 123 myAssignment.testResult = 'test' myAssignment.submission.name = '12/34/56' myTask.assignment_set.all = lambda : [myAssignment] aDispute = Mock() aDispute.adminStatement = '123456' aDispute.status = 1 myDispute = [aDispute] with patch.object(request.GET,'get',return_value = 1): with patch.object(Task.objects,'get',return_value = myTask): with patch.object(Dispute.objects,'filter',return_value = myDispute): response = json.loads(found.func(request).content.decode()) test_task = response['assignment'][0] self.assertEqual(test_task['id'], 1) class GetAssignmentDetailTestCase(TestCase): def test_normal_test(self): found = resolve('/GetAssignmentDetail', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') aDispute = Mock() aDispute.adminStatement = '123456' aDispute.status = 1 myDispute = [aDispute] myTask = Mock() myTask.id = 1 myTask.title = 'title' myTask.status = 1 myTask.description = '123' myTask.publishTime.timestamp = lambda : 1234 myTask.ddlTime.timestamp = lambda :567 myTask.languageTarget = 1 myTask.languageOrigin = 2 myTask.fileUrl.name = 'a/jpg' myTask.employer.id = 1 myTask.testText = '1234' myTask.employer.username = 'abc' myTask.employer.avatar.url = 'hhh' myAssignment = Mock() myAssignment.id = 1 myAssignment.order = 1 myAssignment.description = '12345' myAssignment.translator.username = 'shao' myAssignment.status = 1 myAssignment.scores = 1 myAssignment.price = 123 myAssignment.testResult = 'test' myAssignment.submission.name = '12/34/56' myAssignment.task = myTask with patch.object(request.GET,'get',return_value = 1): with patch.object(Assignment.objects,'get',return_value = myAssignment): with patch.object(Dispute.objects,'filter',return_value = myDispute): response = json.loads(found.func(request).content.decode()) test_task = response['assignment'] self.assertEqual(test_task['id'], 1) # a problem... class GetSquareTasksTestCase(TestCase): def test_normal_test(self): found = resolve('/GetSquareTasks', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') myTag = Mock() myTag.tag = 1 myAssignment = Mock() myAssignment.id = 1 myAssignment.order = 1 myAssignment.description = '12345' myAssignment.translator.username = 'shao' myAssignment.status = 1 myAssignment.scores = 1 myAssignment.price = 123 myAssignment.testResult = 'test' myAssignment.submission.url = '12/34/56' myTask = Mock() myTask.id = 1 myTask.title = 'title' myTask.status = 1 myTask.description = '123' myTask.publishTime.timestamp = lambda : 1234 myTask.ddlTime.timestamp = lambda :567 myTask.languageTarget = 1 myTask.languageOrigin = 2 myTask.fileUrl.name = 'a/jpg' myTask.employer.id = 1 myTask.testText = '1234' myTask.employer.username = 'abc' myTask.employer.avatar.url = 'hhh' myTask.tag_set.all = lambda : [myTag] myTask.assignment_set.all = lambda : [myAssignment] myTaskSet = MagicMock() myTaskSet.__iter__.return_value = [myTask] myTaskSet.count = lambda : 5 taskSetUnorder = Mock() taskSetUnorder.order_by = lambda str : myTaskSet with patch.object(request.GET,'get', return_value = None): with patch.object(Task.objects,'filter',return_value = taskSetUnorder): #with patch.object(myTaskSet,'count'): response = json.loads(found.func(request).content.decode()) test_task = response['taskList'][0] self.assertEqual(test_task['id'], 1) class SubmitAssignmentTestCase(TestCase): def test_normal_test(self): found = resolve('/SubmitAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') myfile = Mock() myfile.name = 'abc.doc' myassignment = Mock() myassignment.submission.name = 'abc.doc' with patch.object(request.FILES,'get',return_value = myfile): with patch.object(request.POST,'get',return_value = 1): with patch.object(Assignment.objects,'get',return_value = myassignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['url'], 'abc.doc') class PublishTaskTestCase(TestCase): def test_normal_test(self): found = resolve('/PublishTask', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"taskid":1}') myass = Mock() myass.status = 1 mytask = Mock() mytask.status = 1 mytask.assignment_set.all = lambda :[myass] with patch.object(Task.objects,'get',return_value = mytask): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class SolveDisputeTestCase(TestCase): def test_normal_test(self): found = resolve('/SolveDispute', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"disputeid":1,"result":123,"statement":"haha"}') mydispute = Mock() mydispute.adminStatement = None mydispute.status = 0 with patch.object(Dispute.objects,'get',return_value = mydispute): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class VerifyLicenseTestCase(TestCase): def test_normal_test(self): found = resolve('/VerifyLicense', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"licenseid":1,"result":123,"statement":"haha"}') mylicense = Mock() mylicense.adminVerify = 0 with patch.object(License.objects,'get',return_value = mylicense): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class GetManagerTestCase(TestCase): def test_normal_test(self): found = resolve('/GetManager', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') myDispute = Mock() myDispute.id = 1 myDispute.assignment.description = 'assignment name' myDispute.translatorStatement = 'statement' myDispute.employerStatement = 'statement' myDisputeSet = MagicMock() myDisputeSet.count = lambda : 5 myDisputeSet.__iter__.return_value = [myDispute] myLicense = Mock() myLicense.id = 1 myLicense.licenseType = 'CET4' myLicense.licenseImage.url = 'a.jpg' myLicenseSet = MagicMock() myLicenseSet.count = lambda :5 myLicenseSet.__iter__.return_value = [myLicense] with patch.object(Dispute.objects,'filter',return_value = myDisputeSet): with patch.object(License.objects,'filter',return_value = myLicenseSet): response = json.loads(found.func(request).content.decode()) #test_license = response['licenseList'][0] test_dispute = response['DisputeList'][0] self.assertEqual(test_dispute['id'], 1) class AcceptAssignmentTestCase(TestCase): def test_case_accept(self): found = resolve('/AcceptAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignmentid":1,"result":123,"acceptance":"accept"}') myAssignment = Mock() myAssignment.scores = 1 myAssignment.status = 1 myAssignment.comment = '123' with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) def test_case_reject(self): found = resolve('/AcceptAssignment', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignmentid":1,"result":123,"acceptance":"reject"}') myAssignment = Mock() myAssignment.scores = 1 myAssignment.status = 1 myAssignment.comment = '123' with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class FileDownloadTestCase(TestCase): def test_normal_test(self): found = resolve('/FileDownload', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='GET') filenameAndType = 'all.jpg' myres = {'Content-Type':'application/octet-stream','Content-Disposition':'attachment;filename="{0}"'} with patch.object(request.GET,'get',return_value = filenameAndType): with patch.object(http,'StreamingHttpResponse',return_value = myres): response = found.func(request) self.assertEqual(response['Content-Type'], 'application/octet-stream') class UploadLicenseTestCase(TestCase): def test_cet4(self): found = resolve('/UploadLicense', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') myUser = Mock() myUser.translator = None mylfile = Mock() mylfile.name = 'a.jpg' myLicense = Mock() myLicense.name = 'a/b' with patch.object(auth,'get_user',return_value = myUser): with patch.object(request.FILES,'get',return_value = mylfile): with patch.object(request.POST,'get',return_value = 'cet4'): with patch.object(myLicense.licenseImage,'save',return_value = 1): with patch.object(License.objects,'create',return_value= myLicense): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['url'], "b") def test_cet8(self): found = resolve('/UploadLicense', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') myUser = Mock() myUser.translator = None mylfile = Mock() mylfile.name = 'a.jpg' myLicense = Mock() myLicense.name = 'a/b' with patch.object(auth,'get_user',return_value = myUser): with patch.object(request.FILES,'get',return_value = mylfile): with patch.object(request.POST,'get',return_value = 'cet8'): with patch.object(myLicense.licenseImage,'save',return_value = 1): with patch.object(License.objects,'create',return_value= myLicense): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['url'], "b") class ResponseTestResultTestCase(TestCase): def test_normal_test_2(self): found = resolve('/ResponseTestResult', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignment_id":1,"result":123,"statement":"haha"}') myAssignment = Mock() myAssignment.status = 2 myAssignment.translator = 1 with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response, 0) def test_normal_test_1(self): found = resolve('/ResponseTestResult', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignment_id":1,"result":123,"statement":"haha"}') myAssignment = Mock() myAssignment.status = 1 myAssignment.translator = 1 with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response, 0) class SubmitTestResultTestCase(TestCase): def test_normal_test(self): found = resolve('/SubmitTestResult', urlconf = backend.urls) request = Mock(wraps=HttpRequest(), method = 'POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignment_order":123,"testResult":"haha","task_id":1}') myUser = Mock() myUser.username = 'shaoyushan' myTranslator = Mock() myTranslator.translator = myUser myAssignment = Mock() myAssignment.status = 1 myAssignment.translator = myUser myAssignment.testResult = '123' with patch.object(auth,'get_user',return_value = myTranslator): with patch.object(Task.objects,'get',return_value = 1): with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['translator'], 'shaoyushan') class AcceptResultTestCase(TestCase): def test_normal_test(self): found = resolve('/AcceptResult', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignmentId":123,"testResult":"haha","task_id":1}') myAssignment = Mock() myAssignment.status = 1 with patch.object(Assignment.objects,'get',return_value = myAssignment): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True) class ArgueResultTestCase(TestCase): def test_normal_test(self): found = resolve('/AcceptResult', urlconf=backend.urls) request = Mock(wraps=HttpRequest(), method='POST') request.body = Mock() request.body.decode = Mock(return_value=' {"assignmentId":123,"testResult":"haha","task_id":1}') myAssignment = Mock() myAssignment.status = 1 with patch.object(Assignment.objects, 'get', return_value=myAssignment): with patch.object(Dispute.objects,'create',return_value = 1 ): response = json.loads(found.func(request).content.decode()) self.assertEqual(response['status'], True)<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-03 14:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='task', name='testResult', ), migrations.AddField( model_name='assignment', name='comment', field=models.TextField(null=True), ), migrations.AddField( model_name='assignment', name='testResult', field=models.TextField(max_length=1000, null=True), ), ] <file_sep>Django==1.11 Pillow mysqlclient django-cors-headers <file_sep>import Vuex from 'vuex' import Vue from 'vue' import VuexPersistence from 'vuex-persist' Vue.use(Vuex) const vuexLocal = new VuexPersistence({ storage: window.localStorage, reducer: state => ({ online: state.online, userid: state.userid, utype: state.utype, username: state.username }), filter: (mutation) => ( mutation.type === 'setStatus' || mutation.type === 'login' || mutation.type === 'logout' ) }) export default new Vuex.Store({ state: { online: false, userid: 0, utype: '', username: '' }, mutations: { 'setStatus': (state, userInfo) => { state.userid = userInfo['userid'] state.utype = userInfo['utype'] state.username = userInfo['username'] }, 'login': (state, userInfo) => { state.online = true state.userid = userInfo['userid'] state.utype = userInfo['utype'] state.username = userInfo['username'] }, 'logout': (state) => { state.online = false state.userid = 0 state.utype = '' state.username = '' } }, plugins: [vuexLocal.plugin] })
c898cec5c8b7b42d4b265cc1bc2daaf4be832ecd
[ "JavaScript", "Python", "Text", "Markdown" ]
11
Python
YuanHaoReginald/Babel
abbf36e948d1b869f954f7d2bc4afc54293ed8c2
0a379ebd1c652408ad67e0b80a27f156fb490bb3
refs/heads/master
<file_sep>/* * jQuery Dialogs * * * support ie9+, TODO ff, TODO chrome * */ // dialogs object /* * dialogs.options current default options * dialogs.updateOptions function(options) -> accepts an object as argument * dialogs.all array containing each dialog object * dialogs.visible boolean, true if at least a dialog is opened * dialogs.active returns the current active dialog object or undefined if no dialog has been opened * dialogs.closeAll close all opened dialogs * * // preset dialogs * * dialogs.alert(title, message, callback()) simple alert dialog box, callback function is called when user closes the dialog by clicking the "ok" button * dialog.confirm(title, message, callback(res)) simple confirm dialog box, callback is invoked with an argument that is true if user clicks "ok" and false otherwise * dialogs.prompt(title, message, inputValue, callback(res)) simple prompt dialog box, callback is invoked with an argument equal to the input's value, null if the value clicks cancel * */ // callbacks /* beforeShow afterShow beforeClose afterClose */ (function($){ window.dialogs = {}; // options dialogs.options = { bodyClass: "dialog-open", // body class when opening a dialog, used to prevent scroll with overflow: hidden dialogClass: "", // custom additional class to all dialogues closeOnClickOverlay: true, // close when clicking on the overlay destroyOnClose: true, // destroy button reference after closing it, cannot use the show() to make it appear again showOnInit: true, // show the dialog right after initializing it focusOnClick: true // when multiple dialogs are opened, the user can focus on a particular dialog by clicking it }; var $body; var $overlay; // update options dialogs.updateOptions = function(newOptions){ if ( typeof newOptions === 'object' ){ $.extend(dialogs.options, newOptions); } } // array containing all opened dialog objects dialogs.all = []; // returns true if at lest a dialog is visible dialogs.visible = function(){ for (var i = 0; i < dialogs.all.length; i++){ if ( dialogs.all[i].visible ) return true; } return false; } // current active dialog object dialogs.active; // close all dialogs dialogs.closeAll = function(){ for (var i = 0; dialogs.all.length; i++){ dialogs.all[i].close(); } } // alert dialog dialogs.alert = function(title, message, callback){ if (!typeof title === 'string') title = undefined; if ( (typeof message !== 'string') && (typeof message === 'function') ){ message = undefined; callback = message; } var options = { title: title, message: message, buttons: [ {text: "Ok", onclick: callback, closeDialog: true} ] } options = $.extend(dialogs.options, options); return new DialogBox(options); } // confirm dialog dialogs.confirm = function(title, message, callback){ if (!typeof title === 'string') title = undefined; if ( (typeof message !== 'string') && (typeof message === 'function') ){ message = undefined; callback = message; } var options = { title: title, message: message, buttons: [ {text: "Cancel", onclick: callback, onclickArguments: false, closeDialog: true}, {text: "Ok", onclick: callback, onclickArguments: true, closeDialog: true} ] } options = $.extend(dialogs.options, options); return new DialogBox(options); } // prompt dialog dialogs.prompt = function(title, message, defaultValue, callback){ if (typeof title !== 'string') title = undefined; if ( (typeof message !== 'string') && (typeof message === 'function') ){ console.log("message function"), callback = message; message = undefined; } if ( (typeof defaultValue !== 'string') && (typeof defaultValue === 'function') ){ console.log("Default value function"), callback = defaultValue; defaultValue = ""; } var options = { title: title, message: message, buttons: [ {text: "Cancel", onclick: callback, onclickArguments: null, closeDialog: true}, {text: "Ok", onclick: callback, onclickArguments: true, closeDialog: true} ] } options = $.extend(dialogs.options, options); return new DialogBox(options); } // dialog constructor /* * public functions * * show() * close() * setMain() * setSecondary() * update() * */ function DialogBox(options){ // init var _box = this; var onTransitionEndCallback; _box.options = options; _box.visible = false; var $title; var $message; var destroyBox = false; // if set to true destroy this dialog after close // basic dialog box var $dialog = $("<div class='jq-dialog " + _box.options.dialogClass + "'></div>"); initializeTexts(); // buttons var $actions = $("<div class='jq-dialog-actions'></div>"); $dialog.append($actions); createButtons(); // public functions _box.show = function(){ fireCallback(_box.options.beforeShow); $body.append($dialog).addClass(options.bodyClass); $overlay.show(); $dialog.css("opacity"); // access css to reflow and enable transition when adding class below $dialog.addClass("visible"); _box.visible = true; _box.setMain(); onTransitionEndCallback = ["afterShow"]; } _box.close = function(callbackArgument){ fireCallback(_box.options.beforeClose, callbackArgument); if (_box.options.destroyOnClose){ destroyBox = true; } // set new active if this dialog is the active one if (dialogs.active === _box){ _box.setSecondary(); for (var i = 0; i < dialogs.all.length; i++){ if ( (dialogs.all[i] !== _box) && dialogs.all[i].visible) dialogs.all[i].setMain(); } } $dialog.removeClass("visible"); _box.visible = false; if (!dialogs.visible()){ $overlay.hide(); $body.removeClass(options.bodyClass); } onTransitionEndCallback = ["afterClose", callbackArgument]; } _box.setMain = function(){ if (dialogs.active !== undefined){ dialogs.active.setSecondary(); } dialogs.active = _box; $dialog.addClass("active"); } _box.setSecondary = function(){ $dialog.removeClass("active"); dialogs.active = undefined; } _box.update = function(options){ $.extend(_box.options, options); // remove and recreate texts if (typeof $title !== 'string'){ $title.remove(); } if (typeof $message !== 'string'){ $message.remove(); } initializeTexts(); // recreate buttons $actions.empty(); createButtons(); } _box.destroy = function(){ if (_box.visible) _box.close(); // remove from all array if (dialogs.all.indexOf(_box) !== -1){ dialogs.all.splice(dialogs.all.indexOf(_box), 1); } $dialog.remove(); _box = undefined; } // end public functions // fire callback after transitions are ended $dialog.on(transitionEndEventName(), function(){ if (typeof onTransitionEndCallback === 'object' && onTransitionEndCallback.constructor === Array){ var callbackName = onTransitionEndCallback.shift(); var callback = _box.options[callbackName]; var args = [callback].concat(onTransitionEndCallback); if (typeof callback === 'function'){ fireCallback.apply(undefined, args); } if ( (callbackName === 'afterClose') && ( destroyBox ) ){ _box.destroy(); } } onTransitionEndCallback = undefined; }) // fill texts (title and message) if defined function initializeTexts(){ // title if (typeof _box.options.title === 'string'){ $title = $("<div class='jq-dialog-title'>" + _box.options.title + "</div>"); } else { $title = ""; } // message if (typeof _box.options.message === 'string'){ $message = $("<div class='jq-dialog-message'>" + _box.options.message + "</div>"); } else { $message = ""; } $dialog.prepend($message).prepend($title); } // creates action buttons function createButtons(){ var buttons = _box.options.buttons; if (typeof buttons === 'object' && buttons.constructor === Array){ for (var i = 0; i < buttons.length; i++){ var button = buttons[i]; bindbuttonClick(button); } } } // bind each action button function bindbuttonClick(button){ var buttonClass = typeof button.customClass === 'string' ? 'jq-dialog-button ' + button.customClass : "jq-dialog-button"; var $button = $("<button class='" + buttonClass + "'>" + button.text + "</button>"); $actions.append($button); // if button.onclick is a function, call it if (typeof button.onclick === 'function'){ var args = []; if ( (button.onclickArguments !== undefined) && (button.onclickArguments !== null) ){ args = button.onclickArguments.constructor === Array ? button.onclickArguments : [button.onclickArguments]; } else if (button.onclickArguments === null){ args = [null]; } button.onclick.apply(undefined, args); $button.on("click", function(e){ e.stopPropagation(); button.onclick.apply(undefined, args); if (button.closeDialog === true){ _box.close(args); } }); // else close the dialog box and return button.onclick as value } else { $button.on("click", function(e){ e.stopPropagation(); _box.close(button.onclick); }) } } // auto show if (options.showOnInit){ _box.show(); } // bind focus on click $dialog.click(function(e){ if ( _box.options.focusOnClick && ( dialogs.active !== _box ) ){ // e.stopPropagation(); _box.setMain(); } }) // add this dialog to all dialogs array dialogs.all.push(_box); return _box; } // end dialog constructor // initializations on document ready $(function(){ $body = $("body") $overlay = $body.find(".dialogs-overlay"); if ($overlay.length === 0){ $overlay = $("<div class='dialogs-overlay' style='display: none;'></div>"); $body.append($overlay); } }) //// fires callbacks function fireCallback(){ var func = arguments[0]; if ( typeof(func) === "function" ){ var args = []; for (var i = 1; i < arguments.length; i++){ args.push(arguments[i]); } func.apply(undefined, args); } } // get name for transition end event name based on browser function transitionEndEventName() { var i, undefined, el = document.createElement('div'), transitions = { 'transition':'transitionend', 'OTransition':'otransitionend', // oTransitionEnd in very old Opera 'MozTransition':'transitionend', 'WebkitTransition':'webkitTransitionEnd' }; for (i in transitions) { if (transitions.hasOwnProperty(i) && el.style[i] !== undefined) { return transitions[i]; } } //TODO: throw 'TransitionEnd event is not supported in this browser'; } })(jQuery)<file_sep># dialogs-js
d3e3ae8c8a6660933d0b1031871402efa8cdd97c
[ "JavaScript", "Markdown" ]
2
JavaScript
justDax/dialogs-js
75f028ddfe689976dc3dc831c5ad67e7638c4afa
2a1dd1142f160d7cc977724e80a406f85a130fed
refs/heads/master
<repo_name>RBotelloMa/OpenGL-Shaders-Practice<file_sep>/src/mesh.cpp #include "../include/mesh.h" std::shared_ptr<Mesh> Mesh::Create() { return std::shared_ptr<Mesh>(new Mesh(), Delete); }; std::shared_ptr<Mesh> Mesh::Create(const std::string& filename) { return std::shared_ptr<Mesh>(new Mesh(filename), Delete); }; const std::string& Mesh::GetFilename() const { return mFilename; }; void Mesh::AddSubmesh(const std::shared_ptr<Submesh>& submesh) { mSubmeshes.push_back(submesh); submesh->Rebuild(); }; void Mesh::RemoveSubmesh(uint32 i) { mSubmeshes.erase(mSubmeshes.begin() + i); }; void Mesh::RemoveSubmesh(const std::shared_ptr<Submesh>& submesh) { mSubmeshes.erase(std::find(mSubmeshes.begin(), mSubmeshes.end(), submesh)); }; uint32 Mesh::NumSubmeshes() const { return mSubmeshes.size(); }; const std::shared_ptr<Submesh>& Mesh::GetSubmesh(uint32 i) { return mSubmeshes[i]; }; void Mesh::Render() { for (auto it = mSubmeshes.begin(); it != mSubmeshes.end();++it) { it->get()->Render(); } }; Mesh::Mesh() {}; Mesh::Mesh(const std::string& filename) { mFilename = filename; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(mFilename.c_str()); if (result) { pugi::xml_node meshNode = doc.child("mesh"); pugi::xml_node submeshesNode = doc.child("mesh").child("submeshes"); for (pugi::xml_node submeshNode = submeshesNode.child("submesh"); submeshNode; submeshNode = submeshNode.next_sibling("submesh")) { // Iteramos por todos los elementos “submesh” contenidosen el elemento “submeshes” //textura std::string textureStr = submeshNode.child("texture").text().as_string(); std::string path = ExtractPath(filename); std::shared_ptr<Texture> textura = Texture::Create(path+"/"+textureStr); std::shared_ptr<Submesh> subMesh = Submesh::Create(textura); //indices std::vector<std::string> indicesVec = SplitString(submeshNode.child("indices").text().as_string(), ','); for (int i = 0; i < indicesVec.size(); i = (i + 3)) { uint16 indice0 = NumberFromString<uint16>(indicesVec[i]); uint16 indice1 = NumberFromString<uint16>(indicesVec[i + 1]); uint16 indice2 = NumberFromString<uint16>(indicesVec[i + 2]); subMesh.get()->AddTriangle(indice0, indice1, indice2); } //coords std::vector<std::string> coordsVec = SplitString(submeshNode.child("coords").text().as_string(), ','); std::vector<std::string> texcoordsVec = SplitString(submeshNode.child("texcoords").text().as_string(), ','); std::vector<std::string> normsVec = SplitString(submeshNode.child("normals").text().as_string(), ','); std::vector<std::string> boneIndex = SplitString(submeshNode.child("bone_indices").text().as_string(), ','); std::vector<std::string> boneWeights = SplitString(submeshNode.child("bone_weights").text().as_string(), ','); int n1 = coordsVec.size()/3; int n2 = texcoordsVec.size() / 2; int n3 = normsVec.size() / 3; int n4 = boneIndex.size() / 4; int n5 = boneWeights.size() / 4; int maxim = std::max(std::max(std::max(n1, n2), std::max(n3, n2)),n5); for (int i = 0; i < maxim; i++) { float coord0, coord1, coord2; float texcoord0, texcoord1; float norm0, norm1, norm2; float boneIdnx0, boneIdnx1, boneIdnx2, boneIdnx3; float boneW0, boneW1, boneW2, boneW3; if (i < n1) { coord0 = NumberFromString<float>(coordsVec[3 * i]); coord1 = NumberFromString<float>(coordsVec[3 * i + 1]); coord2 = NumberFromString<float>(coordsVec[3 * i + 2]); } else { coord0 = coord1 = coord2 = 0; } if (i < n2) { texcoord0 = NumberFromString<float>(texcoordsVec[2 * i]); texcoord1 = NumberFromString<float>(texcoordsVec[2 * i + 1]); } else { texcoord0 = i; texcoord1 = 0; } if (i < n3) { norm0 = NumberFromString<float>(normsVec[3 * i]); norm1 = NumberFromString<float>(normsVec[3 * i + 1]); norm2 = NumberFromString<float>(normsVec[3 * i + 2]); } else { norm0 = norm1 = norm2 = 0; } if (i < n4) { boneIdnx0 = NumberFromString<float>(boneIndex[4 * i]); boneIdnx1 = NumberFromString<float>(boneIndex[4 * i+1]); boneIdnx2 = NumberFromString<float>(boneIndex[4 * i+2]); boneIdnx3 = NumberFromString<float>(boneIndex[4 * i+3]); } else { boneIdnx0 = boneIdnx1 = boneIdnx2 = boneIdnx3 = -1; } if (i < n5) { boneW0 = NumberFromString<float>(boneWeights[4 * i]); boneW1 = NumberFromString<float>(boneWeights[4 * i + 1]); boneW2 = NumberFromString<float>(boneWeights[4 * i + 2]); boneW3 = NumberFromString<float>(boneWeights[4 * i + 3]); } else { boneW0 = boneW1 = boneW2 = boneW3 = 0; } subMesh.get()->AddVertex(Vertex( glm::vec3(coord0,coord1,coord2), glm::vec2(texcoord0, texcoord1), glm::vec3(norm0, norm1, norm2), glm::vec4(boneIdnx0,boneIdnx1,boneIdnx2,boneIdnx3), glm::vec4(boneW0,boneW1,boneW2,boneW3))); } AddSubmesh(subMesh); } //practica 5 pugi::xml_node lastFrameNode = doc.child("mesh").child("last_frame"); mLastFrame = lastFrameNode.text().as_int(); pugi::xml_node bonesNode = doc.child("mesh").child("bones"); for (pugi::xml_node boneNode = bonesNode.child("bone"); boneNode; boneNode = boneNode.next_sibling("bone")) { std::string boneName = boneNode.child("name").text().as_string(); std::string dadName = boneNode.child("parent").text().as_string(); int dadId = GetBoneIndex(dadName); std::shared_ptr<Bone> bone = Bone::Create(boneName, dadId); //inv pose std::vector<std::string> invPoseVec = SplitString(boneNode.child("inv_pose").text().as_string(), ','); glm::mat4 InvP; for (int i = 0; i < invPoseVec.size()/4; i = i++) { InvP[i][0] = NumberFromString<float>(invPoseVec[4*i]); InvP[i][1] = NumberFromString<float>(invPoseVec[4 * i+1]); InvP[i][2] = NumberFromString<float>(invPoseVec[4 * i+2]); InvP[i][3] = NumberFromString<float>(invPoseVec[4 * i+3]); } bone->SetInversePoseMatrix(InvP); //positions std::vector<std::string> positionsVec = SplitString(boneNode.child("positions").text().as_string(), ','); for (int i = 0; i < positionsVec.size(); i = (i + 4)) { int f = NumberFromString<float>(positionsVec[i]); glm::vec3 pos = glm::vec3(NumberFromString<float>(positionsVec[i + 1]), NumberFromString<float>(positionsVec[i + 2]), NumberFromString<float>(positionsVec[i + 3])); bone->AddPosition(f, pos); } //rotations std::vector<std::string> rotationsVec = SplitString(boneNode.child("rotations").text().as_string(), ','); for (int i = 0; i < rotationsVec.size(); i = (i + 5)) { int f = NumberFromString<float>(rotationsVec[i]); glm::quat rot = glm::quat(NumberFromString<float>(rotationsVec[i + 1]), NumberFromString<float>(rotationsVec[i + 2]), NumberFromString<float>(rotationsVec[i + 3]), NumberFromString<float>(rotationsVec[i + 4])); bone->AddRotation(f, rot); } //scale std::vector<std::string> scalesVec = SplitString(boneNode.child("scales").text().as_string(), ','); for (int i = 0; i < scalesVec.size(); i = (i + 4)) { int f = NumberFromString<float>(scalesVec[i]); glm::vec3 scl = glm::vec3(NumberFromString<float>(scalesVec[i + 1]), NumberFromString<float>(scalesVec[i + 2]), NumberFromString<float>(scalesVec[i + 3])); bone->AddScale(f, scl); } AddBone(bone); } } }; //practica 5 void Mesh::CalculateAnimMatrices(float frame, std::vector<glm::mat4>& animMatrices) { for (int i = 0; i < mBones.size(); ++i) { int dad = mBones[i]->GetParentIndex(); if (dad == -1) animMatrices[i] = mBones[i]->CalculateAnimMatrix(frame); else animMatrices[i] = animMatrices[dad] * mBones[i]->CalculateAnimMatrix(frame); } for (int i = 0; i< animMatrices.size(); ++i) { animMatrices[i] = animMatrices[i] * mBones[i]->GetInversePoseMatrix(); } }; int Mesh::GetBoneIndex(const std::string& name) { int i; for (i = 0; i < mBones.size(); ++i) { if (mBones[i]->GetName() == name) return i; } return -1; }; /*private: std::string mFilename; std::vector<std::shared_ptr<Submesh>> mSubmeshes; */<file_sep>/src/model.cpp #include "../include/model.h" #include "../include/renderer.h" std::shared_ptr<Model> Model::Create(const std::shared_ptr<Mesh>& mesh) { if (mesh == nullptr) return nullptr; else return std::shared_ptr<Model>(new Model(mesh), Delete); }; void Model::Render() { Entity::Render(); Renderer::Instance()->Renderer::SetSkinned(mAnimating); Renderer::Instance()->Renderer::SetAnimMatrices(mAnimMatrices); mMesh->Render(); } Model::Model(const std::shared_ptr<Mesh>& mesh) { mMesh = mesh; mAnimating = true; mFPS = 20; mCurrentFrame = 0; for (auto it = mMesh->GetBones().begin(); it != mMesh->GetBones().end(); it++) { mAnimMatrices.push_back(glm::mat4(1)); } }; //practica 5 void Model::Update(float elapsed) { mCurrentFrame += mFPS*elapsed; TEST = 0; if (mCurrentFrame > mMesh->GetLastFrame()) mCurrentFrame = 0; else if (mCurrentFrame < 0) mCurrentFrame = mMesh->GetLastFrame(); mMesh->CalculateAnimMatrices(mCurrentFrame, mAnimMatrices); } /*private: std::shared_ptr<Mesh> mMesh; bool mAnimating; int mFPS; float mCurrentFrame; std::vector<glm::mat4> mAnimMatrices; */ <file_sep>/src/bone.cpp #include "../include/bone.h" std::shared_ptr<Bone> Bone::Create(const std::string& name, int parentIndex) { return std::shared_ptr<Bone>(new Bone(name, parentIndex), Delete); }; const std::string& Bone::GetName() const { return mName; }; int Bone::GetParentIndex() const { return mParentIndex; }; void Bone::SetInversePoseMatrix(const glm::mat4& matrix) { mInvPoseMatrix = matrix; }; const glm::mat4& Bone::GetInversePoseMatrix() const { return mInvPoseMatrix; }; glm::mat4 Bone::CalculateAnimMatrix(float frame) const{ //TODO needs testing float TOL=0.000001f; glm::mat4 rotacion; glm::quat q = GetRotation(frame); if (abs(q.w-1.0f) <= TOL || abs(q.w + 1.0f) <= TOL) { rotacion = glm::mat4(1); } else { float sqw2, x, y, z, angle; sqw2 = glm::sqrt(1 - q.w * q.w); angle = 2.0f * glm::acos(q.w); x = q.x / sqw2; y = q.y / sqw2; z = q.z / sqw2; rotacion = glm::rotate(glm::mat4(1), angle, glm::vec3(x, y, z)); } glm::mat4 escala = glm::scale(glm::mat4(1), GetScale(frame)); glm::mat4 posicion = glm::translate(glm::mat4(1), GetPosition(frame)); return posicion*rotacion*escala; }; void Bone::AddPosition(uint32 frame, const glm::vec3& position) { mPositions.push_back(std::pair<uint32, glm::vec3>(frame, position)); }; void Bone::AddRotation(uint32 frame, const glm::quat& rotation) { mRotations.push_back(std::pair<uint32, glm::quat>(frame,rotation)); }; void Bone::AddScale(uint32 frame, const glm::vec3& scale) { mScales.push_back(std::pair<uint32, glm::vec3>(frame, scale)); }; Bone::Bone(const std::string& name, uint32 parentIndex) { mName = name; mParentIndex = parentIndex; }; void Bone::Delete(Bone* b) { delete b; }; glm::vec3 Bone::GetPosition(float frame) const { for (auto it = mPositions.begin(); it != mPositions.end(); it++) { if ((*it).first == frame) return (*it).second; else if ((*it).first > frame) { return glm::mix( (*(it - 1)).second , (*it).second , (frame - (*(it - 1)).first)/((*it).first - (*(it - 1)).first)); } } if (mPositions.size() == 0) return glm::vec3(); else return (*(mPositions.end() - 1)).second; }; glm::quat Bone::GetRotation(float frame) const { for (auto it = mRotations.begin(); it != mRotations.end(); it++) { if ((*it).first == frame) return (*it).second; else if ((*it).first > frame) { glm::quat q1 = (*(it - 1)).second; glm::quat q2 = (*it).second; auto it2 = it - 1; float prop1 = (frame - (*(it - 1)).first); float prop2 = ((*it).first - (*(it - 1)).first); float prop = prop1 / prop2; glm::quat ret = glm::slerp(q1, q2, prop1/prop2); return ret; } } if (mRotations.size() == 0) return glm::quat(); else return (*(mRotations.end() - 1)).second; }; glm::vec3 Bone::GetScale(float frame) const { for (auto it = mScales.begin(); it != mScales.end(); it++) { if ((*it).first == frame) return (*it).second; else if ((*it).first > frame) { return glm::mix((*(it - 1)).second, (*it).second, (frame - (*(it - 1)).first) / ((*it).first - (*(it - 1)).first)); } } if (mScales.size() == 0) return glm::vec3(); else return (*(mScales.end() - 1)).second; };<file_sep>/include/submesh.h #ifndef UGINE_SUBMESH_H #define UGINE_SUBMESH_H #include "types.h" #include "vertex.h" #include "texture.h" class Submesh { public: static std::shared_ptr<Submesh> Create(const std::shared_ptr<Texture>& tex = nullptr); void AddVertex(const Vertex& v); void AddTriangle(uint16 v0, uint16 v1, uint16 v2); const std::shared_ptr<Texture>& GetTexture() const; void SetTexture(const std::shared_ptr<Texture>& tex); const std::vector<Vertex>& GetVertices() const; std::vector<Vertex>& GetVertices(); void Rebuild(); void Render(); //practica 3 const glm::vec3& GetColor() const; void SetColor(const glm::vec3& color); uint8 GetShininess() const; void SetShininess(uint8 shininess); bool HayTextura(); protected: Submesh(const std::shared_ptr<Texture>& tex); ~Submesh(); static void Delete(Submesh* s) { delete s; } private: std::shared_ptr<Texture> mTexture; uint32 mVertexBuffer; uint32 mIndexBuffer; std::vector<Vertex> mVertices; std::vector<uint16> mIndices; //practica 3 glm::vec3 mColor; uint8 mShininess; //extra bool hayTextura; }; #endif // UGINE_SUBMESH_H<file_sep>/src/camera.cpp #include"../include/camera.h" std::shared_ptr<Camera> Camera::Create() { return std::shared_ptr<Camera>(new Camera(), Delete); } int32 Camera::GetViewportX() const { return mVX; }; int32 Camera::GetViewportY() const { return mVY; }; uint16 Camera::GetViewportWidth() const { return mVW; }; uint16 Camera::GetViewportHeight() const { return mVH; }; void Camera::SetViewport(int32 x, int32 y, uint16 w, uint16 h) { mVX = x; mVY = y; mVW = w; mVH = h; }; void Camera::SetProjection(const glm::mat4& proj) { mProjMatrix = proj; }; const glm::mat4& Camera::GetProjection() const { return mProjMatrix; }; const glm::mat4& Camera::GetView() const { return mViewMatrix; }; const glm::vec3& Camera::GetColor() const { return mColor; }; void Camera::SetColor(const glm::vec3& color) { mColor = color; }; bool Camera::GetUsesTarget() const { return mUsesTarget; }; void Camera::SetUsesTarget(bool usesTarget) { mUsesTarget = usesTarget; }; const glm::vec3& Camera::GetTarget() const { return mTarget; }; glm::vec3& Camera::DefTarget() { return mTarget; }; void Camera::Prepare() { Renderer::Instance()->SetViewport(mVX, mVY, mVW, mVH); if (mUsesTarget) { mViewMatrix= glm::lookAt(GetPosition(), mTarget, GetRotation()*glm::vec3(0, 1, 0)); } else { mViewMatrix = glm::lookAt(GetPosition(), -GetRotation()*glm::vec3(0, 0, 1), GetRotation()*glm::vec3(0, 1, 0)); } Renderer::Instance()->ClearColorBuffer(mColor); Renderer::Instance()->ClearDepthBuffer(); }; Camera::Camera() {}; /*private: glm::mat4 mProjMatrix; glm::mat4 mViewMatrix; int32 mVX, mVY; uint16 mVW, mVH; glm::vec3 mColor; bool mUsesTarget; glm::vec3 mTarget; */<file_sep>/src/light.cpp #include "../include/light.h" #include "../include/renderer.h" #include "../include/scene.h" bool Light::mLightsUsed[MAX_LIGHTS]; std::shared_ptr<Light> Light::Create() { return std::shared_ptr<Light>(new Light(), Delete); } Light::Type Light::GetType() const { return mType; }; void Light::SetType(Light::Type type) { mType = type; }; const glm::vec3& Light::GetColor() const { return mColor; }; void Light::SetColor(const glm::vec3& color) { mColor = color; }; float Light::GetAttenuation() const { return mAttenuation; }; void Light::SetAttenuation(float att) { mAttenuation = att; }; void Light::Prepare() { Renderer::Instance()->EnableLight(mIndex,true); Renderer::Instance()->SetLightData(mIndex, Scene::Instance()->GetCurrentCamera()->GetView()*glm::vec4(GetPosition(),mType), mColor, mAttenuation); }; Light::Light() { int i = 0; bool b=true; while ((i < MAX_LIGHTS)&&b) { if (!(Light::mLightsUsed[i])) { Light::mLightsUsed[i] = true; b = false; mIndex = i; } else ++i; } }; //TODO: + robusto (por si mas de 8 luces) Light::~Light() { Light::mLightsUsed[mIndex] = false; }; /*private: static bool mLightsUsed[MAX_LIGHTS]; int mIndex; Type mType; glm::vec3 mColor; float mAttenuation; */<file_sep>/include/resourceManager.h #ifndef UGINE_RESOURCEMANAGER_H #define UGINE_RESOURCEMANAGER_H #include "types.h" #include "texture.h" #include "mesh.h" class ResourceManager{ public: static const std::shared_ptr<ResourceManager>& Instance(); std::shared_ptr<Mesh>LoadMesh(const std::string& filename); std::shared_ptr<Texture>LoadTexture(const std::string& filename); void FreeMeshes(); void FreeTextures(); void FreeResources(); protected: ResourceManager() {} ~ResourceManager() { FreeResources(); } static void Delete(ResourceManager*rm) { delete rm; } private: static std::shared_ptr<ResourceManager> mInstance; std::map<std::string,std::shared_ptr<Mesh>> mMeshes; std::map<std::string,std::shared_ptr<Texture>> mTextures; }; inline const std::shared_ptr<ResourceManager>& ResourceManager::Instance() { if (!mInstance) mInstance = std::shared_ptr<ResourceManager>(new ResourceManager(), Delete); return mInstance; } #endif // UGINE_RESOURCEMANAGER_H<file_sep>/include/light.h #ifndef LIGHT_H #define LIGHT_H #include "types.h" #include "entity.h" class Light : public Entity { public: enum Type { DIRECTIONAL, POINT }; static std::shared_ptr<Light> Create(); Type GetType() const; void SetType(Type type); const glm::vec3& GetColor() const; void SetColor(const glm::vec3& color); float GetAttenuation() const; void SetAttenuation(float att); void Prepare(); virtual void Render() {} protected: Light(); virtual ~Light(); private: static bool mLightsUsed[MAX_LIGHTS]; int mIndex; Type mType; glm::vec3 mColor; float mAttenuation; }; #endif<file_sep>/include/vertex.h #ifndef UGINE_VERTEX_H #define UGINE_VERTEX_H #include "types.h" struct Vertex { glm::vec3 mPosition; glm::vec2 mTexture; glm::vec3 mNormal; glm::vec4 mBoneIndices; glm::vec4 mBoneWeights; Vertex(const glm::vec3& position, const glm::vec2& texture, const glm::vec3& normal,const glm::vec4& boneIndices, const glm::vec4 & boneWeights) : mPosition(position), mTexture(texture), mNormal(normal), mBoneIndices(boneIndices), mBoneWeights(boneWeights){}; }; #endif // UGINE_VERTEX_H <file_sep>/README.md # OpenGL-Shaders-Practice Little Master's Practice to test some GLSL shaders in OpenGL The program consist in an OpenGL pipeline that reads and XML file with meshes and texture information and represent it. The GLSL shaders used allow the representation of different effects like refraction and reflection. <file_sep>/src/entity.cpp #include "../include/entity.h" #include "../include/scene.h" std::shared_ptr<Entity> Entity::Create() { return std::shared_ptr<Entity>(new Entity(), Delete); } const glm::vec3& Entity::GetPosition() const { return mPosition; } glm::vec3 & Entity::DefPosition() { return mPosition; }; const glm::quat& Entity::GetRotation() const { return mRotation; }; glm::quat& Entity::DefRotation() { return mRotation; }; const glm::vec3& Entity::GetScale() const { return mScale; }; glm::vec3& Entity::DefScale() { return mScale; }; void Entity::Move(const glm::vec3& speed) { mPosition += mRotation*speed; }; void Entity::Render() { float angle = 2 * glm::acos(mRotation.w); glm::mat4 rotation; if (angle != 0) { rotation = glm::rotate(glm::mat4(1), angle, glm::vec3( mRotation.x / glm::sqrt(1 - mRotation.w*mRotation.w), mRotation.y / glm::sqrt(1 - mRotation.w*mRotation.w), mRotation.z / glm::sqrt(1 - mRotation.w*mRotation.w) )); } glm::mat4 scale = glm::scale(glm::mat4(1), mScale); glm::mat4 translate = glm::translate(glm::mat4(1), mPosition); Scene::Instance()->SetModel(translate*rotation*scale); //Los hijos hacen más cosas }; Entity::Entity() {}; /*private: glm::vec3 mPosition; glm::quat mRotation; glm::vec3 mScale; */<file_sep>/include/texture.h #ifndef UGINE_TEXTURE #define UGINE_TEXTURE #include "types.h" #include "renderer.h" class Texture { public: static std::shared_ptr<Texture> Create(const std::string& filename); const std::string& GetFilename() const; uint32 GetHandle() const; uint32 GetWidth() const; uint32 GetHeight() const; protected: Texture(const std::string& filename); ~Texture(); static void Delete(Texture* t) { delete t; } private: std::string mFilename; uint32 mHandle; uint32 mWidth; uint32 mHeight; }; #endif // UGINE_TEXTURE<file_sep>/src/scene.cpp #include "../include/scene.h" std::shared_ptr<Scene> Scene::mInstance = nullptr; const std::shared_ptr<Camera>& Scene::GetCurrentCamera() { return mCurrentCamera; }; const glm::mat4& Scene::GetModel() const { return mModelMatrix; }; void Scene::SetModel(const glm::mat4& m) { mModelMatrix = m; Renderer::Instance()->SetMatrices(mModelMatrix = m, mCurrentCamera->GetView(), mCurrentCamera->GetProjection()); } void Scene::AddEntity(const std::shared_ptr<Entity>& entity) { mEntities.push_back(entity); if (std::dynamic_pointer_cast<Camera> (entity) != nullptr) { mCameras.push_back(std::dynamic_pointer_cast<Camera> (entity)); } if (std::dynamic_pointer_cast<Light> (entity) != nullptr) { mLights.push_back(std::dynamic_pointer_cast<Light> (entity)); } }; void Scene::RemoveEntity(const std::shared_ptr<Entity>& entity) { mEntities.erase(std::find(mEntities.begin(),mEntities.end(),entity)); if (std::dynamic_pointer_cast<Camera> (entity) != nullptr) { mCameras.erase(std::find(mCameras.begin(), mCameras.end(), entity)); } if (std::dynamic_pointer_cast<Light> (entity) != nullptr) { mLights.erase(std::find(mLights.begin(), mLights.end(), entity)); } }; uint32 Scene::GetNumEntities() const { return mEntities.size(); }; const std::shared_ptr<Entity>& Scene::GetEntity(uint32 index) { return mEntities[index]; }; void Scene::Update(float elapsed) { for (auto it = mEntities.begin(); it != mEntities.end(); it++) { it->get()->Update(elapsed); } }; void Scene::Render() { Renderer::Instance()->EnableLighting(true); Renderer::Instance()->SetAmbient(mAmbient); for (auto it = mCameras.begin(); it != mCameras.end(); it++) { mCurrentCamera = (*it); mCurrentCamera.get()->Prepare(); for (auto it1 = mLights.begin(); it1 != mLights.end(); it1++) { (*it1)->Prepare(); } for (auto it2 = mEntities.begin(); it2 != mEntities.end(); it2++) { it2->get()->Render(); } } Renderer::Instance()->EnableLighting(false); } Scene::Scene() { Renderer::Instance()->Setup3D(); }; //practica 3 void Scene::SetAmbient(const glm::vec3& ambient) { mAmbient = ambient; }; /*private: static std::shared_ptr<Scene> mInstance; std::shared_ptr<Camera> mCurrentCamera; glm::mat4 mModelMatrix; std::vector<std::shared_ptr<Camera>> mCameras; std::vector<std::shared_ptr<Entity>> mEntities; */<file_sep>/src/resourceManager.cpp #include "../include/resourceManager.h" std::shared_ptr<ResourceManager> ResourceManager::mInstance = nullptr; std::shared_ptr<Mesh> ResourceManager::LoadMesh(const std::string& filename) { //cambiar los return if (mMeshes.count(filename)==0) { std::shared_ptr<Mesh> aux2 = Mesh::Create(filename);//usar mismo aux if (aux2 != nullptr) { mMeshes.insert(std::pair<std::string, std::shared_ptr<Mesh>>(filename, aux2)); return aux2; } else return nullptr; } else return mMeshes.find(filename)->second; }; std::shared_ptr<Texture> ResourceManager::LoadTexture(const std::string& filename) { //TODO: Testing this if (mTextures.count(filename) == 0) { std::shared_ptr<Texture> aux2 = Texture::Create(filename);//usar mismo aux if (aux2 != nullptr) { mTextures.insert(std::pair<std::string, std::shared_ptr<Texture>>(filename, aux2)); return aux2; } else return nullptr; } else return mTextures.find(filename)->second; }; void ResourceManager::FreeMeshes() { mMeshes.clear(); }; void ResourceManager::FreeTextures() { mTextures.clear(); }; void ResourceManager::FreeResources() { mMeshes.clear(); mTextures.clear(); }; /*static std::shared_ptr<ResourceManager>mInstance; std::map<std::string, std::shared_ptr<Mesh>>mMeshes; std::map<std::string, std::shared_ptr<Texture>>mTextures; */<file_sep>/src/submesh.cpp #include "../include/submesh.h" std::shared_ptr<Submesh> Submesh::Create(const std::shared_ptr<Texture>& tex) { return std::shared_ptr<Submesh>(new Submesh(tex) , Delete); } void Submesh::AddVertex(const Vertex& v) { mVertices.push_back(v); } void Submesh::AddTriangle(uint16 v0, uint16 v1, uint16 v2) { mIndices.push_back(v0); mIndices.push_back(v1); mIndices.push_back(v2); }; const std::shared_ptr<Texture>& Submesh::GetTexture() const { return mTexture; }; void Submesh::SetTexture(const std::shared_ptr<Texture>& tex) { mTexture = tex; if (tex) hayTextura = true; else hayTextura = false; } bool Submesh::HayTextura() { return hayTextura; } const std::vector<Vertex>& Submesh::GetVertices() const { return mVertices; }; std::vector<Vertex>& Submesh::GetVertices() { return mVertices; }; void Submesh::Rebuild() { Renderer::Instance()->SetVertexBufferData(mVertexBuffer, &mVertices[0], sizeof(Vertex) * mVertices.size()); Renderer::Instance()->SetIndexBufferData(mIndexBuffer, &mIndices[0], sizeof(uint16) * mIndices.size()); //de momento ponemos aqui la inicialización del color. Se podría poner en muchos sitios. mColor = glm::vec3(1, 1, 1); mShininess = 255; } void Submesh::Render() { if (mTexture) { Renderer::Instance()->SetTexture(mTexture.get()->GetHandle(),HayTextura()); } else { Renderer::Instance()->SetTexture(0,HayTextura()); } Renderer::Instance()->SetDiffuse(glm::vec3(mColor)); Renderer::Instance()->SetShininess(mShininess); Renderer::Instance()->DrawBuffers(mVertexBuffer, mIndexBuffer, mIndices.size()); } Submesh::Submesh(const std::shared_ptr<Texture>& tex) { mVertexBuffer = Renderer::Instance()->CreateBuffer(); mIndexBuffer = Renderer::Instance()->CreateBuffer(); SetTexture(tex); } Submesh::~Submesh() { Renderer::Instance()->FreeBuffer(mVertexBuffer); Renderer::Instance()->FreeBuffer(mIndexBuffer); }; //practica 3 const glm::vec3& Submesh::GetColor() const { return mColor; }; void Submesh::SetColor(const glm::vec3& color) { mColor = color; }; uint8 Submesh::GetShininess() const { return mShininess; }; void Submesh::SetShininess(uint8 shininess) { mShininess = shininess; }; /*std::shared_ptr<Texture> mTexture; uint32 mVertexBuffer; uint32 mIndexBuffer; std::vector<Vertex> mVertices; std::vector<uint16> mIndices; */ <file_sep>/include/renderer.h #ifndef UGINE_RENDERER_H #define UGINE_RENDERER_H #include "types.h" #define MAX_BONES 75 class Renderer { public: static const std::shared_ptr<Renderer>& Instance(); // Setup void Setup3D(); void SetMatrices(const glm::mat4& model, const glm::mat4& view, const glm::mat4& projection); void SetViewport(int x, int y, int w, int h); // Drawing void ClearColorBuffer(const glm::vec3& color); void ClearDepthBuffer(); // VBO uint32 CreateBuffer(); void FreeBuffer(uint32 buffer); void SetVertexBufferData(uint32 vertexBuffer, const void* data, uint32 dataSize); void SetIndexBufferData(uint32 indexBuffer, const void* data, uint32 dataSize); void DrawBuffers(uint32 vertexBuffer, uint32 indexBuffer, uint32 numIndices); // Shaders uint32 CreateProgram(const std::string& vertex, const std::string& fragment); void FreeProgram(uint32 program); void UseProgram(uint32 program); const std::string& GetProgramError(); //Texture uint32 LoadTexture(const std::string& filename, uint32& width, uint32& height); void FreeTexture(uint32 tex); void SetTexture(uint32 tex, bool hayTextura); //Metodos Luces void SetDiffuse(const glm::vec3& color); void SetAmbient(const glm::vec3& color); void SetShininess(uint8 shininess); void EnableLighting(bool enable); void EnableLight(uint32 index, bool enabled); void SetLightData(uint32 index, const glm::vec4& vector, const glm::vec3& color, float attenuation); //Practica 5 void SetSkinned(bool skinned); void SetAnimMatrices(const std::vector<glm::mat4>& matrices); protected: Renderer(); ~Renderer() {} static void Delete(Renderer* r) { delete r; } private: static std::shared_ptr<Renderer> mInstance; int mMVPLoc; int mVPosLoc; int mVTexPos; int mVTexSampler; //practica iluminación int mVNormalPos; int mMV; int mMNormal; int mVDiffuse; int mVAmbient; int mVShininess; int mVlightingEnabled; int mVlightEnabled[MAX_LIGHTS]; int mVlightPos[MAX_LIGHTS]; int mVlightColor[MAX_LIGHTS]; int mVlightAtt[MAX_LIGHTS]; //flag textura int mVHayTextura; uint32 mDefaultProgram; std::string mProgramError; //practica 5 int mSkinnedLoc; int mAnimMatricesLoc; int mVBoneIndicesLoc; int mVBoneWeightsLoc; }; inline const std::shared_ptr<Renderer>& Renderer::Instance() { if ( !mInstance ) mInstance = std::shared_ptr<Renderer>(new Renderer(), Delete); return mInstance; } #endif // UGINE_RENDERER_H <file_sep>/include/model.h #ifndef UGINE_MODEL_H #define UGINE_MODEL_H #include "types.h" #include "entity.h" #include "mesh.h" class Model : public Entity { public: float TEST=1.0f; static std::shared_ptr<Model> Create(const std::shared_ptr<Mesh>& mesh); virtual void Update(float elapsed); virtual void Render(); //practica 5 void Animate(bool animate) { if (mAnimMatrices.size() > 0) mAnimating = animate; } int GetFPS() const { return mFPS; } void SetFPS(int fps) { mFPS = fps; } float GetCurrentFrame() const { return mCurrentFrame; } void SetCurrentFrame(float frame) { mCurrentFrame = frame; } protected: Model(const std::shared_ptr<Mesh>& mesh); virtual ~Model() {} private: std::shared_ptr<Mesh> mMesh; //practica 5 bool mAnimating; int mFPS; float mCurrentFrame; std::vector<glm::mat4> mAnimMatrices; }; #endif<file_sep>/src/renderer.cpp #include "../lib/glew/glew.h" #include "../include/renderer.h" #include "../include/vertex.h" #define STB_IMAGE_IMPLEMENTATION #include "../lib/stb_image.h" std::shared_ptr<Renderer> Renderer::mInstance = nullptr; Renderer::Renderer() { mDefaultProgram = CreateProgram(ReadString("shaders/vertex.glsl"), ReadString("shaders/fragment.glsl")); UseProgram(mDefaultProgram); } void Renderer::Setup3D() { glEnable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glDepthFunc(GL_LEQUAL); } void Renderer::SetMatrices(const glm::mat4& model, const glm::mat4& view, const glm::mat4& projection) { /*glMatrixMode(GL_PROJECTION); glLoadMatrixf(glm::value_ptr(projection)); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(glm::value_ptr(view * model));*/ glUniformMatrix4fv(mMVPLoc, 1, false, glm::value_ptr(projection * view * model)); glUniformMatrix4fv(mMV, 1, false, glm::value_ptr(view * model)); glUniformMatrix4fv(mMNormal, 1, false, (glm::value_ptr(glm::transpose(glm::inverse(view*model))))); } void Renderer::SetViewport(int x, int y, int w, int h) { glViewport(x, y, w, h); glScissor(x, y, w, h); } void Renderer::ClearColorBuffer(const glm::vec3& color) { glClearColor(color.r, color.g, color.b, 1); glClear(GL_COLOR_BUFFER_BIT); } void Renderer::ClearDepthBuffer() { glClear(GL_DEPTH_BUFFER_BIT); } uint32 Renderer::CreateBuffer() { uint32_t buffer; glGenBuffers(1, &buffer); return buffer; } void Renderer::FreeBuffer(uint32 buffer) { glDeleteBuffers(1, &buffer); } void Renderer::SetVertexBufferData(uint32 vertexBuffer, const void* data, uint32 dataSize) { glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, dataSize, data, GL_STATIC_DRAW); glEnableVertexAttribArray(mVPosLoc); glEnableVertexAttribArray(mVTexPos); glVertexAttribPointer(mVPosLoc, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mPosition))); glVertexAttribPointer(mVTexPos, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mTexture))); glBindBuffer(GL_ARRAY_BUFFER, 0); glDisableVertexAttribArray(mVPosLoc); glDisableVertexAttribArray(mVTexPos); } void Renderer::SetIndexBufferData(uint32 indexBuffer, const void* data, uint32 dataSize) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, dataSize, data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void Renderer::DrawBuffers(uint32 vertexBuffer, uint32 indexBuffer, uint32 numIndices) { glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glEnableVertexAttribArray(mVPosLoc); glEnableVertexAttribArray(mVTexPos); glEnableVertexAttribArray(mVNormalPos); glEnableVertexAttribArray(mVBoneIndicesLoc); glEnableVertexAttribArray(mVBoneWeightsLoc); glVertexAttribPointer(mVPosLoc, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mPosition))); glVertexAttribPointer(mVTexPos, 2, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mTexture))); glVertexAttribPointer(mVNormalPos, 3, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mNormal))); glVertexAttribPointer(mVBoneIndicesLoc, 4, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mBoneIndices))); glVertexAttribPointer(mVBoneWeightsLoc, 4, GL_FLOAT, false, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, Vertex::mBoneWeights))); //añadimos variables practica 3? // Indicamos el puntero a los vertices. Cuando usemos VBOs, el ultimo parametro debe ser // el offset a las posiciones dentro del buffer: offsetof(Vertex, mPosition) //glVertexPointer(3, GL_FLOAT, sizeof(Vertex), reinterpret_cast<const void*>(offsetof(Vertex, mPosition))); // Indicamos el puntero a los vertices. Cuando usemos VBOs, el ultimo parametro debe ser 0, // ya que ya hemos enlazado el buffer donde se encuentran los indices glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, reinterpret_cast<const void*>(0)); // Aqui podemos desenlazar los buffers que hemos enlazado al comienzo // ... glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableVertexAttribArray(mVPosLoc); glDisableVertexAttribArray(mVTexPos); glDisableVertexAttribArray(mVNormalPos); glDisableVertexAttribArray(mVBoneIndicesLoc); glDisableVertexAttribArray(mVBoneWeightsLoc); } uint32 Renderer::CreateProgram(const std::string& vertex, const std::string& fragment) { //Creamos el vertex shader GLint retCode; const char* vshaderSrc = vertex.c_str(); char ErrorLog[1024]; uint32_t vshader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vshader, 1, &vshaderSrc, nullptr); glCompileShader(vshader); glGetShaderiv(vshader, GL_COMPILE_STATUS, &retCode); if (retCode == GL_FALSE) { glGetShaderInfoLog(vshader, sizeof(ErrorLog), NULL, ErrorLog); mProgramError = ErrorLog; return 0; } // Creamos fragment shader const char* fshaderSrc = fragment.c_str(); uint32_t fshader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fshader, 1, &fshaderSrc, nullptr); glCompileShader(fshader); glGetShaderiv(fshader, GL_COMPILE_STATUS, &retCode); if (retCode == GL_FALSE) { glGetShaderInfoLog(fshader, sizeof(ErrorLog), NULL, ErrorLog); mProgramError = ErrorLog; return 0; } // Creamos el programa uint32_t program = glCreateProgram(); glAttachShader(program, vshader); glAttachShader(program, fshader); glLinkProgram(program); glGetProgramiv(program, GL_COMPILE_STATUS, &retCode); if (retCode == GL_FALSE) { glGetProgramInfoLog(program, sizeof(ErrorLog), NULL, ErrorLog); mProgramError = ErrorLog; return 0; } return program; } void Renderer::FreeProgram(uint32 program) { glDeleteProgram(program); } void Renderer::UseProgram(uint32 program) { glUseProgram(program); mMVPLoc = glGetUniformLocation(program, "MVP"); mVTexSampler = glGetUniformLocation(program, "texSampler"); mVPosLoc = glGetAttribLocation(program, "vpos"); mVTexPos = glGetAttribLocation(program, "vuv"); mVNormalPos = glGetAttribLocation(program, "vnormal"); //añadimos matriz modelo-vista y matriz normal mMV = glGetUniformLocation(program, "modelView"); mMNormal = glGetUniformLocation(program, "normalMatrix"); //añadimos variable uniformes de iluminación mVDiffuse = glGetUniformLocation(program, "diffuse"); mVAmbient = glGetUniformLocation(program, "ambient"); mVShininess = glGetUniformLocation(program, "shininess"); //variables de luces mVlightingEnabled = glGetUniformLocation(program, "lightingEnabled"); for (int it = 0; it < MAX_LIGHTS; it++) { mVlightEnabled[it] = glGetUniformLocation(program, std::string("lightEnabled["+std::to_string(it)+"]").c_str()); mVlightPos[it] = glGetUniformLocation(program, std::string("lightPos[" + std::to_string(it) + "]").c_str()); mVlightColor[it] = glGetUniformLocation(program, std::string("lightColor[" + std::to_string(it) + "]").c_str()); mVlightAtt[it] = glGetUniformLocation(program, std::string("lightAtt[" + std::to_string(it) + "]").c_str()); } //flag textura mVHayTextura = glGetUniformLocation(program, "fhayTextura"); //practica 5 mSkinnedLoc = glGetUniformLocation(program, "skinned"); mAnimMatricesLoc = glGetUniformLocation(program, "animMatrices"); mVBoneIndicesLoc = glGetAttribLocation(program, "vboneIndices"); mVBoneWeightsLoc = glGetAttribLocation(program, "vboneWeights"); } const std::string& Renderer::GetProgramError() { return mProgramError; } //Texture uint32 Renderer::LoadTexture(const std::string& filename, uint32& width, uint32& height) { //Cargamos textura con stb_image std::shared_ptr<uint8_t> texBuffer = std::shared_ptr<uint8_t>(stbi_load(filename.c_str(), (int *)&width, (int *)&height, nullptr, 4), stbi_image_free); if (texBuffer != nullptr) { std::shared_ptr<uint8_t> mirroredTexBuffer = std::shared_ptr<uint8_t>(static_cast<uint8_t*>(malloc(width * height * 4)), free); for (int line = 0; line < height; ++line) { memcpy(mirroredTexBuffer.get() + line*width * 4, texBuffer.get() + (height - line - 1)*width * 4, width * 4); } // Generamos textura uint32_t glTex; glGenTextures(1, &glTex); glBindTexture(GL_TEXTURE_2D, glTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, mirroredTexBuffer.get()); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); //TODO: añadir stbi image free //retornamos textura return glTex; } else return 0; }; void Renderer::FreeTexture(uint32 tex) { glDeleteTextures(1, &tex); }; void Renderer::SetTexture(uint32 tex, bool hayTextura) { glBindTexture(GL_TEXTURE_2D, tex); glUniform1i(mVTexSampler, 0); glUniform1i(mVHayTextura, hayTextura); }; //funciones iluminación practica 3 (needs checks) void Renderer::SetDiffuse(const glm::vec3& color) { glUniform3fv(mVDiffuse, 1, glm::value_ptr(color)); } void Renderer::SetAmbient(const glm::vec3& color) { glUniform3fv(mVAmbient, 1, glm::value_ptr(color)); } void Renderer::SetShininess(uint8 shininess) { glUniform1i(mVShininess, shininess); } void Renderer::EnableLighting(bool enable) { glUniform1i(mVlightingEnabled, enable); } void Renderer::EnableLight(uint32 index, bool enabled) { glUniform1i(mVlightEnabled[index], enabled); }; void Renderer::SetLightData(uint32 index, const glm::vec4& vector, const glm::vec3& color, float attenuation) { glUniform4fv(mVlightPos[index],1,glm::value_ptr(vector)); glUniform3fv(mVlightColor[index], 1, glm::value_ptr(color)); glUniform1f(mVlightAtt[index], attenuation); }; //practica 5 void Renderer::SetSkinned(bool skinned) { glUniform1i(mSkinnedLoc,skinned); }; void Renderer::SetAnimMatrices(const std::vector<glm::mat4>& matrices) { if (mAnimMatricesLoc > -1) { int numBones = std::min(MAX_BONES, (int)matrices.size()); glUniformMatrix4fv(mAnimMatricesLoc, numBones, false, glm::value_ptr(matrices[0])); } }; <file_sep>/src/texture.cpp #include "../include/texture.h" std::shared_ptr<Texture> Texture::Create(const std::string& filename) { std::shared_ptr<Texture> ret = std::shared_ptr<Texture>(new Texture(filename), Delete); if (ret->GetHandle() == 0) return nullptr; else return ret; }; const std::string& Texture::GetFilename() const { return mFilename; } uint32 Texture::GetHandle() const { return mHandle; } uint32 Texture::GetWidth() const { return mWidth; } uint32 Texture::GetHeight() const { return mHeight; } Texture::Texture(const std::string& filename) { mFilename = filename; mHandle = Renderer::Instance()->Renderer::LoadTexture(filename, mWidth, mHeight); }; Texture::~Texture() {}; <file_sep>/src/main.cpp #ifdef _MSC_VER #pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") #endif #include "../include/u-gine.h" #define FULLSCREEN false int main(int, char**) { float rotatione = 0; // Creamos contexto de OpenGL (ventana o pantalla completa) if (FULLSCREEN) Screen::Instance()->Open(Screen::Instance()->GetDesktopWidth(), Screen::Instance()->GetDesktopHeight(), true); else Screen::Instance()->Open(1200, 900, false); //creamos el modelo para la malla y añadimos a escena /*std::shared_ptr<Model> Castillo = Model::Create(ResourceManager::Instance()->LoadMesh("data/simple-dm5.msh.xml")); Scene::Instance()->AddEntity(Castillo); //dotamos al castillo de posición rotación y escala Castillo->DefPosition() = glm::vec3(2, -1, 1); Castillo->DefRotation() = glm::quat(1,0,0,0); Castillo->DefScale() = glm::vec3(0.01f, 0.01f, 0.01f);*/ //creamos el modelo para la malla y añadimos a escena std::shared_ptr<Model> Conejo = Model::Create(ResourceManager::Instance()->LoadMesh("data/dwarf.msh.xml")); Scene::Instance()->AddEntity(Conejo); //dotamos al conejo de posición rotación y escala Conejo->DefPosition() = glm::vec3(0, 0, 1); Conejo->DefRotation() = glm::quat(1, 0, 0, 0); Conejo->DefScale() = glm::vec3(0.01f, 0.01f, 0.01f); //creamos el modelo para la malla y añadimos a escena /*std::shared_ptr<Model> Faces = Model::Create(ResourceManager::Instance()->LoadMesh("data/bunny.msh.xml")); Scene::Instance()->AddEntity(Faces); //dotamos al banner de posición rotación y escala Faces->DefPosition() = glm::vec3(0, 0, 0); Faces->DefRotation() = glm::quat(1,0,0,0); Faces->DefScale() = glm::vec3(1.0f, 1.0f, 1.0f); */ //creamos la cámara y añadimos a escena std::shared_ptr<Camera> miCamara = Camera::Create(); Scene::Instance()->AddEntity(miCamara); //creamos el modelo para la malla y añadimos a escena //creamos el modelo para la malla y añadimos a escena //creamos el modelo para la malla y añadimos a escena std::shared_ptr<Light> pLight = Light::Create(); Scene::Instance()->AddEntity(pLight); pLight->DefPosition() = glm::vec3(1, 1, 1); pLight->SetColor(glm::vec3(1, 0, 0)); pLight->SetType(Light::Type::POINT); pLight->SetAttenuation(0.4f); std::shared_ptr<Light> dLight = Light::Create(); Scene::Instance()->AddEntity(dLight); dLight->DefPosition() = glm::vec3(1, 1, 1); dLight->SetColor(glm::vec3(0.7, 0.7, 0.7)); dLight->SetType(Light::Type::DIRECTIONAL); dLight->SetAttenuation(1); //establecemos parámetros de cámara: miCamara->SetColor(glm::vec3(0.4f, 0.4f, 0.6f)); miCamara->SetUsesTarget(true); miCamara->SetViewport(0, 0, Screen::Instance()->GetWidth(), Screen::Instance()->GetHeight()); miCamara->DefPosition()=glm::vec3(0, 0, 0); miCamara->DefRotation()=glm::quat(1, 0, 0, 0); // Establecemos la matriz de proyeccion de la cámara glm::mat4 proj = glm::perspective(glm::radians(60.0f), Screen::Instance()->GetWidth() * 1.0f / Screen::Instance()->GetHeight(), 0.1f, 3000.0f); miCamara->SetProjection(proj); glm::vec3 eye = glm::vec3(0, 0, 0); glm::vec3 forward = glm::vec3(0, 0, 1); glm::vec3 up = glm::vec3(0, 1, 0); glm::vec3 ctUp = glm::vec3(0, 1, 0); glm::vec3 side; glm::vec3 f2 = glm::vec3(0, 0, 1); miCamara->DefTarget()=eye+forward; glm::quat rueda, rueda1; uint32 k = 0; float yaw = 0, pitch = 0; float time; float movex=0.01; // Bucle principal. Se ejecuta mientras la ventana esté abierta y no pulsemos ESC while (!Screen::Instance()->ShouldClose() && !Screen::Instance()->IsKeyPressed(GLFW_KEY_ESCAPE)) { //shot is billboard time = Screen::Instance()->GetElapsed(); pitch += (Screen::Instance()->GetMouseX() - Screen::Instance()->GetWidth() / 2)*Screen::Instance()->GetElapsed()*0.1f; yaw += (Screen::Instance()->GetMouseY() - Screen::Instance()->GetHeight() / 2)*Screen::Instance()->GetElapsed()*0.1f; if (yaw >= 1.57f) yaw = 1.57f; if (yaw <= -1.57f) yaw = -1.57f; rueda1 = glm::rotate(glm::quat(1,0,0,0), -pitch, glm::vec3(0, 1, 0)); rueda = glm::conjugate(glm::rotate(glm::conjugate(rueda1), -yaw, rueda1*glm::vec3(1, 0, 0))); forward = glm::normalize(glm::vec3(rueda*glm::vec4(glm::vec3(0, 0, 1), 1))); up = glm::normalize(glm::vec3(rueda*glm::vec4(glm::vec3(0, 1, 0), 1))); side = glm::normalize(glm::cross(ctUp, forward)); if (Screen::Instance()->IsKeyPressed(GLFW_KEY_W)) { eye += glm::normalize(glm::cross(side, ctUp))*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_S)) { eye -= glm::normalize(glm::cross(side, ctUp))*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_A)) { eye += side*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_D)) { eye -= side*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_Q)) { eye += ctUp*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_E)) { eye -= ctUp*time*1.0f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_P)) { Conejo->TEST = 0.01f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_O)) { Conejo->TEST = -0.01f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_K)) { Conejo->TEST = -0.5f; } if (Screen::Instance()->IsKeyPressed(GLFW_KEY_L)) { Conejo->TEST = +0.5f; } if (Screen::Instance()->IsMousePressed(0)) { pLight->DefPosition() = eye+0.2f*forward-0.1f*up; //Faces->DefRotation() = rueda; f2 = forward; } // Faces->DefRotation() = rueda*glm::quat(glm::cos(3.14 / 4), glm::sin(3.14 / 4), 0, 0)* glm::quat(glm::cos(-3.14 / 4*1.2), 0, 0, glm::sin(-3.14 / 4 * 1.2)); // Faces->DefPosition() = Faces->GetPosition()+f2*movex*10.0f; miCamara->DefRotation() = rueda; miCamara->DefPosition() = eye; miCamara->DefTarget() = eye + forward; Scene::Instance()->Render(); Scene::Instance()->Update(Screen::Instance()->GetElapsed()); Screen::Instance()->MoveMouse(Screen::Instance()->GetWidth() / 2, Screen::Instance()->GetHeight() / 2); // Refrescamos la pantalla Screen::Instance()->Refresh(); // Escribimos en el titulo de la ventana cualquier posible error que se pueda haber producido // al compilar los shaders Screen::Instance()->SetTitle(Renderer::Instance()->GetProgramError()); } return 0; }
505dededa3d8466dc3920887ef819a3c665a0a00
[ "Markdown", "C", "C++" ]
20
C++
RBotelloMa/OpenGL-Shaders-Practice
8f2eae3e1b7aef808255c3fc0751146dd34b5be5
28efe557a9a85222a67b158ac373a866f8e2f78f
refs/heads/master
<file_sep>var gulp = require('gulp'), concat = require('gulp-concat'), sass = require('gulp-ruby-sass'), autoprefixer = require('gulp-autoprefixer'), rimraf = require('gulp-rimraf'), watch = require('gulp-watch'); gulp.task('styles-clean', function() { return gulp.src('build/styles/**/*.css') .pipe(rimraf()); }); gulp.task('styles', ['styles-clean'], function() { return gulp.src(['assets/sass/*.scss']) .pipe(sass({ style: 'compressed' })) .pipe(autoprefixer('last 2 versions')) .pipe(concat('combined.css')) .pipe(gulp.dest('assets/styles')); }); gulp.task('watch', function() { watch({glob: 'assets/sass/*.scss'}, function() { gulp.start('styles'); }); }); gulp.task('default', ['styles']);<file_sep>var app = angular.module('cladesApp', ['ui.router', 'ngAnimate']); app.config(function($stateProvider, $urlRouterProvider, $locationProvider) { // $urlRouterProvider.otherwise(''); $stateProvider .state('index', { url: '', templateUrl: 'app/views/welcome/index.html', }) .state('about', { url: '/about', templateUrl: 'app/views/welcome/about.html', }) .state('taxons', { url: '/taxons', templateUrl: 'app/views/taxons/index.html', controller: 'TaxonsController', }) .state('taxons.show', { url: '/{id}', templateUrl: 'app/views/taxons/show.html', controller: 'TaxonsShowController', }) ; // $locationProvider.html5Mode(true); });<file_sep>var render = { taxons: { redraw: function() { setTimeout(function() { var taxons = $('.taxon').get(), tree = {}; for (t in taxons) { var taxon = $(taxons[t]), parentID = parseInt(taxon.attr('data-parentID')); if (isNaN(parentID)) { parentID = 0; } if (!(parentID in tree)) { tree[parentID] = []; } tree[parentID].push(taxon); } console.log(tree); }, 1); }, }, };<file_sep>app.controller('TaxonsController', function($scope, $stateParams, taxonsFactory) { // $scope.taxons = taxonsFactory.getAll(); });
d7baf623fe17e701341ba99db33c6b6fffddc165
[ "JavaScript" ]
4
JavaScript
lsjroberts/clades
aee15b2cee0291e3eb4435b2bd1373e2d9b7d18a
ad61c4204a77c461d444777ab70d1fd621224f62
refs/heads/master
<file_sep>package com.example.sunshine.bloodDonation.FetchingData.Login_Register /** * hierarchy of json data of Login and Register */ data class LoginRegisterResponse(val status: Int, val data: Data1) data class Data1(val client: Client,val api_token:String) data class Client(val name: String, val email: String, val birth_date: String, val donation_last_date: String, val city_id: Int, val phone: String, private val password: String, private val password_confirmation: String, val blood_type_id: Int) <file_sep>package com.example.sunshine.bloodDonation.Intro; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.viewpager.widget.PagerAdapter; import com.example.sunshine.bloodDonation.R; import java.util.List; public class imageDotPagerAdapter extends PagerAdapter { Context context; //list of images to be replaced in intro page List<Integer>IntroImages; public imageDotPagerAdapter(Context context, List<Integer> IntoImages) { this.context=context; this.IntroImages=IntoImages; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View IntroView=inflater.inflate(R.layout.intro_image_placeholder,container,false); ImageView ImagePlaceHolder=IntroView.findViewById(R.id.IntroImage); ImagePlaceHolder.setImageDrawable(ContextCompat.getDrawable(context,IntroImages.get(position))); container.addView(IntroView,0); return IntroView; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View)object); } @Override public int getCount() { return IntroImages.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view==object; } } <file_sep>package com.example.sunshine.bloodDonation.Info.Articles; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.sunshine.bloodDonation.R; /** * A placeholder fragment containing a simple view. */ public class ArticlesFragment extends Fragment { public ArticlesFragment() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView=inflater.inflate(R.layout.articles_fragment,container,false); RecyclerView mRecycler = rootView.findViewById(R.id.articles_recyclerView); // DividerItemDecoration itemDecorator = new DividerItemDecoration(rootview.getContext(), DividerItemDecoration.VERTICAL); ArticlesAdapter articlesAdapter = new ArticlesAdapter(); mRecycler.setAdapter(articlesAdapter); // mRecycler.addItemDecoration(itemDecorator); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); mRecycler.setLayoutManager(linearLayoutManager); return rootView; } }<file_sep>package com.example.sunshine.bloodDonation.Intro.splash; import androidx.appcompat.app.AppCompatActivity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.ImageView; import com.example.sunshine.bloodDonation.R; import com.example.sunshine.bloodDonation.Intro.IntroActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); SplashAnimation(); } //timer for splash screen private void SplashAnimation() { final ImageView imageView = findViewById(R.id.splashlogo); //define an object animator ObjectAnimator translateAnimation = ObjectAnimator.ofFloat(imageView, View.TRANSLATION_Y, -900, 0); //set the number of repeat count if 0 the repeating will be only 1; translateAnimation.setDuration(1000); translateAnimation.setInterpolator(new AccelerateDecelerateInterpolator()); translateAnimation.start(); translateAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); //intent to open intro screen activity Intent intent = new Intent(SplashActivity.this, IntroActivity.class); //make sure that the receiver .exist if not then no need to send an intent. if (intent.resolveActivity(SplashActivity.this.getPackageManager()) != null) { startActivity(intent); overridePendingTransition(R.anim.left,R.anim.outright); imageView.clearAnimation(); } } }); } @Override protected void onStop() { finish(); super.onStop(); } } <file_sep>package com.example.sunshine.bloodDonation.FetchingData.City_governorate_bloodType data class DataResponse(val data:List<Data>) data class Data(val name:String,val id:Int)<file_sep>package com.example.sunshine.bloodDonation.Intro.signUp; import android.app.Application; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.TextView; import android.widget.Toast; import com.example.sunshine.bloodDonation.FetchingData.City_governorate_bloodType.GetSignUpResponse; import com.example.sunshine.bloodDonation.FetchingData.Login_Register.Client; import com.example.sunshine.bloodDonation.FetchingData.Login_Register.GetLoginRegisterResponse; import com.example.sunshine.bloodDonation.R; import com.example.sunshine.bloodDonation.Intro.Repository.BloodRepos; import com.example.sunshine.bloodDonation.databinding.FragmentSignUpBinding; import java.util.Objects; import static com.example.sunshine.bloodDonation.UtiltiyClass.checkingValidityOfInputs; import static com.example.sunshine.bloodDonation.UtiltiyClass.getBloodTypeId; import static com.example.sunshine.bloodDonation.UtiltiyClass.getListOfDataNames; import static com.example.sunshine.bloodDonation.UtiltiyClass.showToast; import static com.example.sunshine.bloodDonation.UtiltiyClass.storeData; /** * A simple {@link Fragment} subclass. */ public class SignUpFragment extends Fragment { private FragmentSignUpBinding binding; private SignUpViewModel signUpViewModel; public SignUpFragment() { } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment(DataBinding) binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sign_up, container, false); initViewModel(); //start fetching data of blood type from server signUpViewModel.getBloodTypesData(BloodTypesCallBack()); initSpinnerWithAdapter(); //start fetching data of governorate from server signUpViewModel.getGovernoratesData(); //observer for noticing the changes that happen to selection of governorate // and based on that we can update city data governorateObserver(); setGovernorateSpinnerListener(); setCitySpinnerListener(); RegisterListener(); return binding.getRoot(); } private void initViewModel() { Application application = getActivity().getApplication(); BloodRepos bloodRepos = new BloodRepos(application); //instantiating viewModelFactory. SignUpViewModelFactory signUpViewModelFactory = new SignUpViewModelFactory(application, bloodRepos); //instantiating viewModel signUpViewModel = ViewModelProviders.of(this, signUpViewModelFactory).get(SignUpViewModel.class); } private void initSpinnerWithAdapter() {//initial state for spinner adapter binding.governorate.setAdapter(signUpViewModel.GovernorateAdapter()); binding.city.setAdapter(signUpViewModel.CityAdapter()); } private void governorateObserver() { signUpViewModel.getGovernorateObserver().observe(this, position -> { //this condition in case user decided to change his mind and change the current governorate //if the user did i delete old list of city list and update it with the new one if (signUpViewModel.getCityList().size() > 1) { signUpViewModel.ClearCityList(); } signUpViewModel.getCitiesData(position); }); } //CallBack for BloodTypes data as soon as the data is fetched the call back is executed. private GetSignUpResponse BloodTypesCallBack() { /* * catching for null pointer in case user decide suddenly get out of the fragment * because when implementing this callback there would be no view to set adapter with. */ return (data) -> { try { ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()), R.layout.text_adapter_dropdown, getListOfDataNames(data)); binding.bloodType.setDropDownBackgroundDrawable(ContextCompat.getDrawable(getContext(), R.drawable.edittextborder)); binding.bloodType.setAdapter(arrayAdapter); } catch (NullPointerException e) { e.printStackTrace(); } }; } private void RegisterListener() { binding.register.setOnClickListener(v -> { if (checkingValidityOfInputs(getContext(), getViews())) { Toast.makeText(getContext(), "inputs is valid", Toast.LENGTH_LONG).show(); signUpViewModel.Register(RegisterCallback(), getClient()); } else Toast.makeText(getContext(), "inputs is invalid", Toast.LENGTH_LONG).show(); }); } //storing data in shared pref after successfully registered private GetLoginRegisterResponse RegisterCallback() { return data -> { showToast(getActivity(), getString(R.string.successRegister)); storeData(data, getActivity()); }; } private void setCitySpinnerListener() { binding.city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //if user choose any selection but 0 convert color of selection text to be opaque if (position != 0) { ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void setGovernorateSpinnerListener() { binding.governorate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //if user choose any selection but 0 the convert color of selection text to be opaque //as soon as user select his governorate trigger the observer of governorate so is stars to fetch city data if (position != 0) { ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK); signUpViewModel.setGovernorateObserver(position); } //if selection of user is at item 0 so do not do any thing else signUpViewModel.ClearCityList(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private View[] getViews() { return new View[]{binding.name , binding.email , binding.dateOfBirth.getTextView() , binding.city , binding.lastDonationDate.getTextView() , binding.phoneNum , binding.password , binding.confirmPassword , binding.bloodType}; } // get the user data from the texts private Client getClient() { String name = binding.name.getEditText().getText().toString(); String email = binding.email.getEditText().getText().toString(); String dateOfBirth = binding.dateOfBirth.getTextView().getText().toString(); int city_id = binding.city.getSelectedItemPosition(); String lastDonationDate = binding.dateOfBirth.getTextView().getText().toString(); String phoneNum = binding.phoneNum.getEditText().getText().toString(); String password = binding.password.getEditText().getText().toString(); String cofirmedPassword = binding.confirmPassword.getEditText().getText().toString(); int bloodType_id = getBloodTypeId(binding.bloodType.getText().toString()); return new Client(name, email, dateOfBirth, lastDonationDate, city_id, phoneNum, password, cofirmedPassword, bloodType_id); } }
55b3cf7ce98aef7dfac9890c799582d6441a56a9
[ "Java", "Kotlin" ]
6
Kotlin
AbdelrhmanSror/BloodDonation
7e10bac7d78705d819b6b43845f15ecf42d2ab87
1b227311d6233b8d50878c44265e273a45231d6c